diff --git a/.cmd b/.cmd new file mode 100644 index 0000000..ca8813a --- /dev/null +++ b/.cmd @@ -0,0 +1 @@ +rm bmp-deploy.tar.gz diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0664f36 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store + + [user] + name = + email = <京东邮箱> diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/Baremetal_Manage_Platform.iml b/.idea/Baremetal_Manage_Platform.iml new file mode 100644 index 0000000..d6ebd48 --- /dev/null +++ b/.idea/Baremetal_Manage_Platform.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..a55e7a1 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/devkit-JapiProjectStorage.xml b/.idea/devkit-JapiProjectStorage.xml new file mode 100644 index 0000000..a030d9b --- /dev/null +++ b/.idea/devkit-JapiProjectStorage.xml @@ -0,0 +1,7 @@ + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..6e86672 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..7690cd2 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..38e222b --- /dev/null +++ b/README.md @@ -0,0 +1,36 @@ +# Baremetal Manage Platform (BMP) + +English | [简体中文](README.zh-CN.md) + +## Introduction + +`Baremetal Manage Platform` is a private bare metal management platform that integrates local infrastructure resource management, server instance lifecycle management, operating system installation and initialization, network configuration initialization, and project-oriented basic resource management. +![bmp_en.png](docs/bmp-deploy/picture/bmp_en.png) +## Core functions +### Server full lifecycle management +- **Multi-brand server unified management** +Unified management of new and old models of domestic and foreign server brands, management of existing servers, regardless of server brand, no need to purchase new network equipment and install smart network cards/DPUs, and support adding custom models. +- **Server batch automatic deployment** +Supports batch large-scale import of equipment, realizes batch server installation and deployment in minutes, and provides server full lifecycle management after deployment. +- **Customized image management service** +Provides both general images and customized image services, pre-installed CentOS 7.9 and Ubuntu 18.04 images, which can be directly installed and used. It also supports importing multiple images, including CentOS, Ubuntu, Windows server, Debian, Open Euler, Kylin, Tongxin, etc. It provides image production guides and two-way linkage of image models. +- **Intelligent operation and maintenance monitoring management** +Supports in-band & out-of-band monitoring management, supports viewing the hardware device status of a single instance, viewing fault alarm log information and processing, and presetting multiple hardware alarm rules; it also supports in-band monitoring and alarm management of resources, displays the status of various monitoring indicators and sets alarm rules. + +### Asset management +- **Comprehensive computer room resource management** +The overall access security verification is adopted, and the global setting of out-of-band server out-of-band login account, password, switch login account, and password information is supported; batch export of full computer room information is provided. +- **Project-dimensional resource management** +Supports logical grouping of users' infrastructure resources, facilitates unified management of resources within the project, supports project sharing and transfer, and improves resource utilization efficiency; supports project addition, editing, and deletion, etc. + +### Permission management +- **User management and security center settings** +Preset three different roles with different permissions to meet the needs of different users, support setting basic user information, changing passwords, managing API keys, etc. +- **Unified operation role management** +Provide a self-service portal for platform administrators, operators, and ordinary users, support platform administrators to use the self-service portal to manage resources, operations, users and roles, and provide operators with unified management and operations of resources through the self-service portal. Ordinary users can apply for, use, operate and manage resources through the self-service portal, and change account names, passwords, etc. + +## Documentation + +- [Quick Experience](docs/setup.md) How to deploy the BMP system with one click. +- [Source code deployment](docs/develop.md) How to deploy the BMP system locally in a containerized manner +- [Local development](docs/local-develop.md) How to deploy and debug locally in a non-containerized manner \ No newline at end of file diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 0000000..63daeb5 --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,37 @@ +# Baremetal Manage Platform (BMP) + +[English](README.md) | 简体中文 + +## 介绍 + +`Baremetal Manage Platform` 是一款集本地基础设施资源管理、服务器实例生命周期管理、操作系统安装与初始化、网络配置初始化、面向项目的基础资源管理等功能于一体的私有化裸金属管理平台。 +![bmp.png](docs/zh/bmp-deploy/picture/bmp.png) +## 核心功能 +### 服务器全生命周期管理 +- **多品牌服务器统一纳管** + 针对国内外服务器品牌的新旧机型进行统一管理,纳管存量服务器,不挑服务器品牌,无需购买新网络设备及加装智能网卡/DPU,支持添加自定义机型。 +- **服务器批量自动化部署** + 支持批量大规模导入设备,实现批量服务器分钟级安装部署,部署后提供服务器全生命周期管理。 +- **定制化镜像管理服务** + 既提供通用镜像,又提供了定制化镜像服务,预置CentOS 7.9、Ubuntu 18.04镜像,可直接进行装机使用。同时支持导入多种镜像,涵盖CentOS、Ubuntu、Windows server、Debian、Open Euler、麒麟、统信等,提供镜像制作指南,镜像机型双向联动。 +- **智能运维监控管理** + 支持带内&带外监控管理,支持查看单个实例的硬件设备状态,查看故障报警日志信息及处理,预置多种硬件报警规则;同时支持资源带内监控和报警管理,展示各项监控指标情况并对设置报警规则。 + +### 资产管理 +- **全面的机房资源管理** +整体采用访问安全验证,支持全局设置带外服务器带外登录账号,密码,交换机登录账号,密码信息;提供批量导出机房全量信息。 +- **项目维度的资源管理** +支持对用户的基础设施资源进行逻辑分组,方便对项目内的资源进行统一管理,支持项目共享及转移,提升资源利用效率;支持项目添加、编辑、删除等。 + +### 权限管理 +- **用户管理及安全中心设置** +预置三种不同角色关联不同权限,满足不同用户使用需求,支持设置用户基本信息、修改密码、管理API密钥等。 +- **统一的运营角色管理** +为平台管理员、运营人员、普通用户提供自服务门户,支持平台管理员通过自服务门户进行资源的统一管理、运维、用户和角色的管理,提供运营人员通过自服务门户进行资源的统一管理、运维,普通用户可以通过自服务门户申请、使用、操作管理资源,修改账户名、密码等。 + + +## 文档 + +- [快速体验](docs/zh/setup.md) 如何一键部署BMP系统。 +- [源码部署](docs/zh/develop.md) 如何本地容器化部署BMP系统 +- [本地开发](docs/zh/local-develop.md) 如何本地非容器化部署调试 \ No newline at end of file diff --git a/bmp-agent/.cmd b/bmp-agent/.cmd new file mode 100644 index 0000000..822a583 --- /dev/null +++ b/bmp-agent/.cmd @@ -0,0 +1 @@ +rm -rf .gitignore diff --git a/bmp-agent/.dockerignore b/bmp-agent/.dockerignore new file mode 100644 index 0000000..15d1eaf --- /dev/null +++ b/bmp-agent/.dockerignore @@ -0,0 +1,26 @@ +# eclipse meta +.classpath +.project +.settings/ +.DS_Store +bin/ + +# vscode +.vscode/ + +# Log file +*.log + + +# python +*.eggs/ +*.egg-info/ +dist/ +build/ +*.pyc +.stestr +pylintrc +.tox + +# dev +dev.sh \ No newline at end of file diff --git a/bmp-agent/.stestr.conf b/bmp-agent/.stestr.conf new file mode 100644 index 0000000..c62673d --- /dev/null +++ b/bmp-agent/.stestr.conf @@ -0,0 +1,3 @@ +[DEFAULT] +test_path=${OS_TEST_PATH:-./bmpa/tests/unit} +top_dir=./ \ No newline at end of file diff --git a/bmp-agent/Changelog.md b/bmp-agent/Changelog.md new file mode 100644 index 0000000..dda6e71 --- /dev/null +++ b/bmp-agent/Changelog.md @@ -0,0 +1,42 @@ +# Changelog + +## [2.0.7] - 2024-08-09 +### Added +- 新增日志同步到rsyslog +- 修复format分区顺序和partition不一致时导致分区显示乱序问题 +- 新增Ubuntu22.04版本ramos +- 新增Ubuntu20.04版本ramos +- 修复cannot import name 'MutableMapping' from 'collections' + +## [2.0.6] - 2024-08-05 +### Fixed +- 修改刷新数据到硬盘的方式 + +## [2.0.5] - 2024-08-05 +### Fixed +- 修复写入文件的数据未刷到硬盘 + +## [2.0.4] - 2024-08-02 +### Changed +- 采集信息返回网卡bus_info + +## [2.0.3] - 2024-07-22 +### Added +- 修复硬盘发现较慢导致makeraid的sn值获取错误 + +## [2.0.2] - 2024-07-19 +### Added +- 采集信息指令新增返回系统架构字段 + +## [2.0.1] - 2024-05-28 +### Added +- RamOS构建新增版本号 +- 新增Ubuntu22.04RamOS + +### Changed +- 修改采集指令 +- 优化raid指令 + +## [2.0.0] - 2023-03-03 +### Added +- 升级到Python3,接口有重大调整,不兼容老系统 \ No newline at end of file diff --git a/bmp-agent/MANIFEST.in b/bmp-agent/MANIFEST.in new file mode 100755 index 0000000..a7d5697 --- /dev/null +++ b/bmp-agent/MANIFEST.in @@ -0,0 +1,5 @@ +include README.md +include docs/*.md +include bmpa/shell/*.sh +include bmpa/template/fstab/*.tpl +include bmpa/template/cloudinit/*.tpl \ No newline at end of file diff --git a/bmp-agent/Makefile b/bmp-agent/Makefile new file mode 100755 index 0000000..e3de7b3 --- /dev/null +++ b/bmp-agent/Makefile @@ -0,0 +1,48 @@ +.PHONY: clean-pyc clean-build clean + +help: + @echo "clean - remove all build, test, coverage and Python artifacts" + @echo "clean-build - remove build artifacts" + @echo "clean-pyc - remove Python file artifacts" + @echo "clean-test - remove test and coverage artifacts" + @echo "lint - check style with flake8" + @echo "test - run tests quickly with the default Python" + @echo "test-all - run tests on every Python version with tox" + @echo "install - install the package to the active Python's site-packages" + @echo "develop - build the package to the develop Python's site-packages" + +clean: clean-build clean-pyc clean-test + +clean-build: + rm -fr build/ + rm -fr dist/ + rm -fr .eggs/ + find . -name '*.egg-info' -exec rm -rf {} + + find . -name '*.egg' -exec rm -rf {} + + find . -name '*.log' -exec rm -rf {} + + +clean-pyc: + find . -name '*.pyc' -exec rm -f {} + + find . -name '*.pyo' -exec rm -f {} + + find . -name '*~' -exec rm -f {} + + find . -name '__pycache__' -exec rm -fr {} + + +clean-test: + rm -fr .tox/ + rm -f .coverage + rm -fr htmlcov/ + +lint: + flake8 leviathan_serving tests + +test: + python3 setup.py test + +test-all: + tox + +install: clean + python3 setup.py install + +develop: clean + python3 setup.py develop \ No newline at end of file diff --git a/bmp-agent/README.md b/bmp-agent/README.md new file mode 100755 index 0000000..8152b59 --- /dev/null +++ b/bmp-agent/README.md @@ -0,0 +1,40 @@ +# BMP Agent +English | [简体中文](README.zh-CN.md) + +The BMP Agent runs on RamOS, receiving commands from a scheduler via MQ (Message Queue) and executing corresponding instructions to install and configure the operating system. + +[Command Details](./doc/command.md) + +## Capabilities +1. Collect Server Configuration Information: Gather details such as network interface information, disk information, switch information, etc. +2. Install OS on Servers and Write Configuration Information + +## Deploy the Agent to the RamOS environment +Refer to [imagebuild-docker](./imagebuild-docker/README.md) + +## Log Directory +The Agent log file under RamOS is located at '/tmp/bmpa.log' + + +## Service Control +In RamOS, you can control the Agent service with the following commands: + +1. View service status +```shell +systemctl status bmpa +``` +2. Start the service +```shell +systemctl start bmpa +``` +3. Stop service +```shell +systemctl stop bmpa +``` +## Environment configuration information +Environment configuration information is passed through kernel parameters + +```shell +cat /proc/cmdline +``` + diff --git a/bmp-agent/README.zh-CN.md b/bmp-agent/README.zh-CN.md new file mode 100755 index 0000000..a211c8a --- /dev/null +++ b/bmp-agent/README.zh-CN.md @@ -0,0 +1,37 @@ +# BMP Agent +[English](README.md) | 简体中文 + +运行于RamOS中,通过MQ接收调度器下发的指令,并执行相应命令, 进行操作系统的安装及配置。 + +[指令详情](./doc/command.md) + +## 能力 +1. 采集服务器相关配置信息。如网卡信息、硬盘信息、交换机信息等 +2. 为服务器安装OS系统,并写入相关配置信息 + +## 将Agent部署到RamOS中 +详见[imagebuild-docker](./imagebuild-docker/README.md) + +## 日志目录 +RamOS下Agent日志文件位于'/tmp/bmpa.log' + +## 服务控制 +在RamOS中,可以通过以下命令控制Agent服务: +1. 查看服务状态 +```shell +systemctl status bmpa +``` +2. 启动服务 +```shell +systemctl start bmpa +``` +3. 停止服务 +```shell +systemctl stop bmpa +``` +## 环境配置信息 +环境配置信息通过内核参数传递,详见 +```shell +cat /proc/cmdline +``` + diff --git a/bmp-agent/bmpa/__init__.py b/bmp-agent/bmpa/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/bmp-agent/bmpa/client/__init__.py b/bmp-agent/bmpa/client/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/bmp-agent/bmpa/client/rabbitmq.py b/bmp-agent/bmpa/client/rabbitmq.py new file mode 100644 index 0000000..214ca99 --- /dev/null +++ b/bmp-agent/bmpa/client/rabbitmq.py @@ -0,0 +1,475 @@ +import logging +from queue import Empty +from queue import Queue +import time + +import pika + +from bmpa import config +from bmpa.utils import strutils + +LOG = logging.getLogger(__name__) + + +class Consumer(object): + + def __init__(self): + + self.queue = Queue() + # type: pika.connection.Connection + self.connection = None + # type: pika.channel.Channel + self.channel = None + self.consumer_tag = None + + self.username = None + self.password = None + self.host = None + self.port = None + self.vhost = None + self.exchange = None + self.exchange_type = None + self.queue_name = None + self.routing_key = None + + def init(self, queue_name: str): + self.queue_name = queue_name + self.routing_key = self.queue_name + self.username = config.mq_username + self.password = config.mq_password + self.host = config.mq_host + self.port = config.mq_port + self.vhost = config.mq_vhost + self.exchange = config.mq_exchange + self.exchange_type = config.mq_exchange_type + + def start(self): + wait = base = 2 + while True: + try: + self._build_connection() + LOG.info('Begin to comsume message.') + self.consumer_tag = self.channel.basic_consume( + queue=self.queue_name, + on_message_callback=self._on_message) + self.channel.start_consuming() + wait = base + except Exception as e: + wait = min(1024, wait * 2) + time.sleep(wait) + LOG.error("Comsume message failed. %s", e, exc_info=1) + finally: + try: + self._stop() + except Exception as e: + LOG.error( + "Close consumer connection failed. " + "retry to reconnect, %s", + e, + exc_info=1) + + def get_message(self): + try: + message = self.queue.get() + # LOG.info("Get message :%s.", message) + LOG.info("Get message :%s.", strutils.mask_password(message.decode('utf-8'))) + return message + except Exception as e: + LOG.warn("Get message error:%s.", str(e)) + return None + + def stop(self): + self._stop() + + def _connection_parameters(self): + credentials = pika.PlainCredentials(self.username, self.password) + return pika.ConnectionParameters(host=self.host, + port=self.port, + virtual_host=self.vhost, + credentials=credentials, + connection_attempts=1, + retry_delay=5, + socket_timeout=5, + heartbeat=5) + + def _build_connection(self): + """This method connects to RabbitMQ, returning the connection handle. + + When the connection is established, the on_connection_open method + will be invoked by pika. + + :rtype: pika.SelectConnection + """ + routing_key = self.queue_name + parameters = self._connection_parameters() + LOG.info('Connecting to %s', parameters) + self._connection = pika.BlockingConnection(parameters=parameters) + self.channel = self._connection.channel() + self._setup_exchange(self.channel, self.exchange, self.exchange_type) + self._setup_queue(self.channel, self.queue_name) + self._bind_queue_to_exchange(self.channel, self.exchange, + self.queue_name, routing_key) + + def _setup_exchange(self, channel, exchange_name, exchange_type): + """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC + + command. When it is complete, the on_exchange_declareok method will + be invoked by pika. + + :param str|unicode exchange_name: The name of the exchange to declare + """ + LOG.info('Declaring exchange : %s', exchange_name) + # Note: using functools.partial is not required, it is demonstrating + # how arbitrary data can be passed to the callback when it is called + channel.exchange_declare(exchange=exchange_name, + exchange_type=exchange_type, + durable=True) + + def _setup_queue(self, channel, queue_name, auto_delete=False): + """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC + + command. When it is complete, the on_queue_declareok method will + be invoked by pika. + + :param str|unicode queue_name: The name of the queue to declare. + """ + LOG.info('Declaring queue %s', queue_name) + channel.queue_declare(queue=queue_name, + durable=True, + auto_delete=auto_delete) + + def _bind_queue_to_exchange(self, channel, exchange, queue_name, + routing_key): + """Method invoked by pika when the Queue.Declare RPC call made in + + setup_queue has completed. In this method we will bind the queue + and exchange together with the routing key by issuing the Queue.Bind + RPC command. When this command is complete, the on_bindok method will + be invoked by pika. + + :param pika.frame.Method method_frame: The Queue.DeclareOk frame + :param str|unicode queue_name: Extra user data (queue name) + """ + LOG.info('Binding %s to %s with %s', exchange, queue_name, + routing_key) + channel.queue_bind(queue=queue_name, + exchange=exchange, + routing_key=routing_key) + + def start_consuming(self): + """This method sets up the consumer by first calling + + add_on_cancel_callback so that the object is notified if RabbitMQ + cancels the consumer. It then issues the Basic.Consume RPC command + which returns the consumer tag that is used to uniquely identify the + consumer with RabbitMQ. We keep the value to use it when we want to + cancel consuming. The on_message method is passed in as a callback pika + will invoke when a message is fully received. + """ + try: + LOG.info('Issuing consumer related RPC commands') + self.consumer_tag = self.channel.basic_consume( + queue=self.receive_queue_name, + on_message_callback=self.on_message) + self.channel.start_consuming() + except Exception as e: + try: + self._stop() + self._build_connection() + finally: + message = ("Connect failed. : %s") % str(e) + LOG.error("Connect failed. %s", message, exc_info=1) + + def _on_message(self, unused_channel, basic_deliver, properties, body): + """Invoked by pika when a message is delivered from RabbitMQ. The + + channel is passed for your convenience. The basic_deliver object that + is passed in carries the exchange, routing key, delivery tag and + a redelivered flag for the message. The properties passed in is an + instance of BasicProperties with the message properties and the body + is the message that was sent. + + :param pika.channel.Channel unused_channel: The channel object + :param pika.Spec.Basic.Deliver: basic_deliver method + :param pika.Spec.BasicProperties: properties + :param str|unicode body: The message body + """ + LOG.info('Received message # %s from %s: %s', + basic_deliver.delivery_tag, properties.app_id, strutils.mask_password(body.decode('utf-8'))) + self.queue.put(body) + self._acknowledge_message(basic_deliver.delivery_tag) + + def _acknowledge_message(self, delivery_tag): + """Acknowledge the message delivery from RabbitMQ by sending a + + Basic.Ack RPC method for the delivery tag. + + :param int delivery_tag: The delivery tag from the Basic.Deliver frame + """ + LOG.info('Acknowledging message %s', delivery_tag) + self.channel.basic_ack(delivery_tag) + + def _stop(self): + """Cleanly shutdown the connection to RabbitMQ by stopping the consumer + + with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok + will be invoked by pika, which will then closing the channel and + connection. The IOLoop is started again because this method is invoked + when CTRL-C is pressed raising a KeyboardInterrupt exception. This + exception stops the IOLoop which needs to be running for pika to + communicate with RabbitMQ. All of the commands issued prior to starting + the IOLoop will be buffered but not processed. + """ + + LOG.info('Stopping') + self._stop_consuming() + self._close_channel(self.channel) + self._close_connection(self.connection) + LOG.info('Stopped') + + def _stop_consuming(self): + """Tell RabbitMQ that you would like to stop consuming by sending the + + Basic.Cancel RPC command. + """ + if self.channel and self.channel.is_open: + LOG.info('Sending a Basic.Cancel RPC command to RabbitMQ') + self.channel.basic_cancel(consumer_tag=self.consumer_tag) + LOG.info("Stop consuming") + + def _close_channel(self, channel): + """Call to close the channel with RabbitMQ cleanly by issuing the + + Channel.Close RPC command. + """ + LOG.info('Closing the channel') + if channel and channel.is_open: + channel.close() + + def _close_connection(self, connection): + """This method closes the connection to RabbitMQ.""" + LOG.info('Closing connection') + if connection and connection.is_open: + connection.close() + + def __enter__(self): + return self + + def __exit__(self, exception_type, exception_value, traceback): + if exception_type is not None: + LOG.error("%s, %s, %s", exception_type, exception_value, + traceback) + + +class Publisher(object): + + def __init__(self): + + self.queue = Queue() + self.queue_name = None + self.routing_key = None + # type: pika.connection.Connection + self.connection = None + # type: pika.channel.Channel + self.channel = None + self.consumer_tag = None + + self.username = None + self.password = None + self.host = None + self.port = None + self.vhost = None + self.exchange = None + self.exchange_type = None + + def init(self): + self.queue_name = config.mq_exchange + self.routing_key = config.mq_exchange + + self.username = config.mq_username + self.password = config.mq_password + self.host = config.mq_host + self.port = config.mq_port + self.vhost = config.mq_vhost + self.exchange = config.mq_exchange + self.exchange_type = config.mq_exchange_type + + def publish_message(self, message): + self.queue.put(message) + + def start(self): + self._build_connection() + while True: + try: + message = self.queue.get(timeout=0.2) + if not message: + LOG.warn("Get a None message from publish queue.") + continue + try: + # 未收到ack确认信息时会抛出异常 + self.channel.basic_publish( + exchange=self.exchange, + routing_key=self.routing_key, + body=message, + properties=pika.BasicProperties( + content_type='application/json', + app_id=self.queue_name, + delivery_mode=2)) + + LOG.debug("Deliver message to %s %s %s.", self.exchange, + self.routing_key, strutils.mask_password(message)) + except Exception as e: + LOG.error( + "Publish message:%s failed, put message into queue. %s", + message, + e, + exc_info=1) + self.queue.put(message) + self._close_channel(self.channel) + self._close_connection(self.connection) + time.sleep(1) + self._build_connection() + time.sleep(1) + except Empty: + try: + if not self.is_connect(): + self._build_connection() + LOG.info('Connection is connect.') + continue + except Exception as e: + time.sleep(1) + LOG.info('Error:%s', e) + continue + LOG.debug("Publish queue is empty.") + time.sleep(1) + continue + except Exception as e: + LOG.error("Publish message failed. %s", e, exc_info=1) + time.sleep(1) + continue + + def stop(self): + self._stop() + + def is_connect(self): + if self.channel and self.channel.is_open: + LOG.debug("RabbitMQ connection is open.") + return True + else: + LOG.debug("RabbitMQ connection is closed.") + return False + + def _connection_parameters(self): + credentials = pika.PlainCredentials(self.username, self.password) + return pika.ConnectionParameters(host=self.host, + port=self.port, + virtual_host=self.vhost, + credentials=credentials, + connection_attempts=1, + retry_delay=5, + socket_timeout=5, + heartbeat=5) + + def _build_connection(self): + """This method connects to RabbitMQ, returning the connection handle. + + When the connection is established, the on_connection_open method + will be invoked by pika. + + :rtype: pika.SelectConnection + """ + parameters = self._connection_parameters() + LOG.info('Connecting to %s', parameters) + self._connection = pika.BlockingConnection(parameters=parameters) + self.channel = self._connection.channel() + self.channel.confirm_delivery() + self._setup_exchange(self.channel, self.exchange, self.exchange_type) + self._setup_queue(self.channel, self.queue_name) + self._bind_queue_to_exchange(self.channel, self.exchange, + self.queue_name, self.routing_key) + + def _setup_exchange(self, channel, exchange_name, exchange_type): + """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC + + command. When it is complete, the on_exchange_declareok method will + be invoked by pika. + + :param str|unicode exchange_name: The name of the exchange to declare + """ + LOG.info('Declaring exchange : %s', exchange_name) + # Note: using functools.partial is not required, it is demonstrating + # how arbitrary data can be passed to the callback when it is called + channel.exchange_declare(exchange=exchange_name, + exchange_type=exchange_type, + durable=True) + + def _setup_queue(self, channel, queue_name, auto_delete=False): + """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC + + command. When it is complete, the on_queue_declareok method will + be invoked by pika. + + :param str|unicode queue_name: The name of the queue to declare. + """ + LOG.info('Declaring queue %s', queue_name) + channel.queue_declare(queue=queue_name, + durable=True, + auto_delete=auto_delete) + + def _bind_queue_to_exchange(self, channel, exchange, queue_name, + routing_key): + """Method invoked by pika when the Queue.Declare RPC call made in + + setup_queue has completed. In this method we will bind the queue + and exchange together with the routing key by issuing the Queue.Bind + RPC command. When this command is complete, the on_bindok method will + be invoked by pika. + + :param pika.frame.Method method_frame: The Queue.DeclareOk frame + :param str|unicode queue_name: Extra user data (queue name) + """ + LOG.info('Binding %s to %s with %s', exchange, queue_name, + routing_key) + channel.queue_bind(queue=queue_name, + exchange=exchange, + routing_key=routing_key) + + def _stop(self): + """Cleanly shutdown the connection to RabbitMQ by stopping the consumer + + with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok + will be invoked by pika, which will then closing the channel and + connection. The IOLoop is started again because this method is invoked + when CTRL-C is pressed raising a KeyboardInterrupt exception. This + exception stops the IOLoop which needs to be running for pika to + communicate with RabbitMQ. All of the commands issued prior to starting + the IOLoop will be buffered but not processed. + """ + + LOG.info('Stopping') + self._close_channel(self.channel) + self._close_connection(self.connection) + LOG.info('Stopped') + + def _close_channel(self, channel): + """Call to close the channel with RabbitMQ cleanly by issuing the + + Channel.Close RPC command. + """ + LOG.info('Closing the channel') + if channel and channel.is_open: + channel.close() + + def _close_connection(self, connection): + """This method closes the connection to RabbitMQ.""" + LOG.info('Closing connection') + if connection and connection.is_open: + connection.close() + + def __enter__(self): + return self + + def __exit__(self, exception_type, exception_value, traceback): + if exception_type is not None: + LOG.error("%s, %s, %s", exception_type, exception_value, + traceback) diff --git a/bmp-agent/bmpa/cmd/__init__.py b/bmp-agent/bmpa/cmd/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/bmp-agent/bmpa/cmd/agent.py b/bmp-agent/bmpa/cmd/agent.py new file mode 100755 index 0000000..6ba1012 --- /dev/null +++ b/bmp-agent/bmpa/cmd/agent.py @@ -0,0 +1,58 @@ +import logging +import threading +import time + + +from bmpa import config +from bmpa import engine +from bmpa import log +from bmpa.utils import executor +from bmpa.utils import interfaceutils +from bmpa.utils import system + +LOG = logging.getLogger('bmpa') + +ascii_snake = """\ +============================================================================================= + + --..,_ _,.--. + `'.'. .'`__ o `;__. + '.'. .'.'` '---'` ` BMP Agent + '.`'--....--'`.' + `'--....--'` + +============================================================================================= +""" + + +def set_rsyslog_conf(): + try: + rsyslog_tpl_path = system.get_relative_path( + 'template/rsyslog/bmp-agent.conf.tpl') + rsyslog_config = system.render_template(rsyslog_tpl_path, { + 'log_path': config.log_path, + 'rsyslog_host': config.rsyslog_host, + 'rsyslog_port': config.rsyslog_port}) + rsyslog_path = '/etc/rsyslog.d/bmp-agent.conf' + with open(rsyslog_path, 'w') as f: + f.write(rsyslog_config) + executor.execute(*['systemctl', 'restart', 'rsyslog']) + except Exception as e: + LOG.error("Failed to set rsyslog config: %s", e) + + +def run(): + print(ascii_snake) + log.init() + LOG.debug("Cmdline path %s.", config.cmdline_path) + set_rsyslog_conf() + interfaceutils.dhclient() + interfaceutils.wait_for_dhcp() + eng = engine.Engine() + eng.start() + LOG.info("Engine is running.") + time.sleep(threading.TIMEOUT_MAX) + + +if __name__ == '__main__': + run() diff --git a/bmp-agent/bmpa/command/__init__.py b/bmp-agent/bmpa/command/__init__.py new file mode 100644 index 0000000..3aaf836 --- /dev/null +++ b/bmp-agent/bmpa/command/__init__.py @@ -0,0 +1,3 @@ +from bmpa.command.command_service import CommandService + +command_service = CommandService() diff --git a/bmp-agent/bmpa/command/blockdevice.py b/bmp-agent/bmpa/command/blockdevice.py new file mode 100644 index 0000000..9404922 --- /dev/null +++ b/bmp-agent/bmpa/command/blockdevice.py @@ -0,0 +1,15 @@ +import logging + +from bmpa.command.common import Command +from bmpa.service import blockdevice + +LOG = logging.getLogger(__name__) + + +class CleanBlockDevice(Command): + + def __init__(self, **kwargs): + super(CleanBlockDevice, self).__init__(**kwargs) + + def execute(self): + blockdevice.clean_blockdevice() diff --git a/bmp-agent/bmpa/command/collect.py b/bmp-agent/bmpa/command/collect.py new file mode 100755 index 0000000..0e69fd0 --- /dev/null +++ b/bmp-agent/bmpa/command/collect.py @@ -0,0 +1,36 @@ +import logging + +from bmpa.command.common import Command +from bmpa.service import collect + +LOG = logging.getLogger(__name__) + + +class CollectHardwareInfo(Command): + def __init__(self, **kwargs): + super(CollectHardwareInfo, self).__init__(**kwargs) + self.hardware_info = None + + def execute_before(self): + pass + + def execute(self): + self.hardware_info = collect.list_hardware_info() + + def execute_after(self): + self.data = self.hardware_info + + +class CollectDiskLocations(Command): + """Collecting Disk Information.""" + + def __init__(self, raid_driver=None, **kwargs): + super(CollectDiskLocations, self).__init__(**kwargs) + self.disk_data = None + self.raid_driver = raid_driver + + def execute(self): + self.disk_data = collect.collect_disks(self.raid_driver) + + def execute_after(self): + self.data = self.disk_data diff --git a/bmp-agent/bmpa/command/command_service.py b/bmp-agent/bmpa/command/command_service.py new file mode 100755 index 0000000..1a85520 --- /dev/null +++ b/bmp-agent/bmpa/command/command_service.py @@ -0,0 +1,69 @@ +import logging +from queue import Queue, Empty + +from bmpa.command.common import COMMAND_MAP +from bmpa.command.common import SystemCommandError +from bmpa import engine +from bmpa.errors import UnkownCommandError +from bmpa import serialize +from bmpa.service import node +from bmpa.utils import classloader +from bmpa.utils import strutils + + +LOG = logging.getLogger(__name__) + + +class CommandService: + + def __init__(self) -> None: + self._commands = Queue() + self.decoder = serialize.DefaultJsonDecoder() + + def dispatch(self): + LOG.info('Command dispatch start.') + while True: + command_str = None + action = None + request_id = None + try: + command_str = self._commands.get() + if not command_str: + LOG.warn("Get a None message: %.", command_str) + continue + command_str = command_str.decode('utf8') + LOG.info('Command: %s', strutils.mask_password(command_str)) + command = self.decoder.decode(command_str) + request_id = command.get('request_id', None) + if type(command) is dict and "action" in command.keys(): + action = command.get('action') + if action in COMMAND_MAP: + class_path = COMMAND_MAP.get(action) + command_clazz = classloader.load_class(class_path) + command_object = command_clazz(**command) + + command_object.run() + engine.Engine.send_command(command_object) + continue + + LOG.error("Unknow command action : %s.", + strutils.mask_password(command_str)) + raise UnkownCommandError( + details=strutils.mask_password(command_str)) + except Empty: + continue + except Exception as e: + LOG.error("Process command failed : %s.", + str(e), + exc_info=1) + cmd = SystemCommandError(sn=node.get_serial_number(), + action=action or 'SystemCommandError', + code=getattr(e, 'code', 500), + type=e.__class__.__name__, + details=getattr(e, 'details', None), + message=getattr(e, 'message', str(e)), + request_id=request_id) + engine.Engine.send_command(cmd) + + def receive_command(self, command): + self._commands.put(command) diff --git a/bmp-agent/bmpa/command/common.py b/bmp-agent/bmpa/command/common.py new file mode 100755 index 0000000..c06f082 --- /dev/null +++ b/bmp-agent/bmpa/command/common.py @@ -0,0 +1,129 @@ +import logging + +import bmpa.errors as errors +from bmpa.serialize import Serializable +from bmpa.service import node +import bmpa.utils.validates as validates + +LOG = logging.getLogger(__name__) + +OK = 200 + +OK_STRING = "OK" +ERROR_STRING = "ERROR" + +COMMAND_MAP = { + "CollectDiskLocations": "bmpa.command.collect.CollectDiskLocations", + "CollectHardwareInfo": "bmpa.command.collect.CollectHardwareInfo", + "CleanBlockDevice": "bmpa.command.blockdevice.CleanBlockDevice", + "CleanRaid": "bmpa.command.raid.CleanRaid", + "FormatPartitions": "bmpa.command.formatpartitions.FormatPartitions", + "InitNode": "bmpa.command.node.InitNode", + "MakePartitions": "bmpa.command.partitions.MakePartitions", + "MakeRaid": "bmpa.command.raid.MakeRaid", + "MountPartitions": "bmpa.command.mount.MountPartitions", + "Ping": "bmpa.command.ping.Ping", + "SetCloudinitConf": "bmpa.command.metadata.SetCloudinitConf", + "SetPassword": "bmpa.command.password.SetPassword", + "SetMetaData": "bmpa.command.metadata.SetMetaData", + "SetNetwork": "bmpa.command.metadata.SetNetwork", + "SetNetworkWindows": "bmpa.command.metadata.SetNetworkWindows", + "SetUserData": "bmpa.command.metadata.SetUserData", + "SetVendorData": "bmpa.command.metadata.SetVendorData", + "WriteImage": "bmpa.command.image.WriteImage", + "WriteImageTar": "bmpa.command.image.WriteImageTar", +} + + +class Command(Serializable): + + serializable_fields = ('sn', 'action', 'code', 'type', 'message', + 'details', 'data', 'request_id', 'status') + + def __init__(self, + sn: str = None, + action: str = None, + code: int = OK, + message: str = None, + request_id: str = None, + status=OK_STRING, + **kwargs): + + self.sn = sn # required + self.action = action # required + self.code = code + self.message = message + self.type = kwargs.get('type', None) + self.details = kwargs.get('details', None) + self.request_id = request_id + self.data = kwargs.get('data', None) + self.status = status + + def validate_common_param(self): + validates.is_required(self.sn, 'Sn') + validates.sn_match(self.sn, node.get_serial_number()) + validates.is_required(self.action, 'Action') + + def validate(self): + pass + + def run(self): + try: + try: + self.validate_common_param() + self.validate() + self.execute_before() + self.execute() + self.__handle_success() + except Exception as e: + self.__handle_exception(e) + finally: + self.data = self.data or dict() + self.execute_after() + except Exception as e: + self.__handle_exception(e) + + def execute_before(self): + pass + + def execute(self): + raise errors.CommandExecutionError("{}not impl execute method.".format( + self.__class__.__name__)) + + def execute_after(self): + pass + + def __handle_success(self): + message = "Run {} success.".format(type(self).__name__) + self.status = OK_STRING + self.message = message + + LOG.info(message) + + def __handle_exception(self, exec): + self.status = ERROR_STRING + self.code = getattr(exec, 'code', 500) + self.type = exec.__class__.__name__ + self.message = getattr(exec, 'message', None) + self.details = getattr(exec, 'details', None) + LOG.error("Run {} failed:{}.".format( + type(self).__name__, str(exec)), + exc_info=1) + raise exec + + +class SystemCommandError(Command): + """agent to scheduler command""" + + def __init__(self, sn: str, action: str, **kwargs): + super(SystemCommandError, self).__init__(sn=sn, + action=action, + status=ERROR_STRING, + **kwargs) + + +class Heart(Command): + """agent to scheduler command""" + + def __init__(self, **kwargs): + super(Heart, self).__init__(action=self.__class__.__name__, **kwargs) diff --git a/bmp-agent/bmpa/command/formatpartitions.py b/bmp-agent/bmpa/command/formatpartitions.py new file mode 100755 index 0000000..d1498ef --- /dev/null +++ b/bmp-agent/bmpa/command/formatpartitions.py @@ -0,0 +1,18 @@ +import logging + +from bmpa.command.common import Command +from bmpa.service import formatpartitions +import bmpa.utils.validates as validates + +LOG = logging.getLogger(__name__) + + +class FormatPartitions(Command): + def __init__(self, partitions, **kwargs): + self.partitions = partitions + validates.is_required(partitions, 'partitions') + + super(FormatPartitions, self).__init__(**kwargs) + + def execute(self): + formatpartitions.formatpartitions(self.partitions) diff --git a/bmp-agent/bmpa/command/hostname.py b/bmp-agent/bmpa/command/hostname.py new file mode 100644 index 0000000..5e99a3f --- /dev/null +++ b/bmp-agent/bmpa/command/hostname.py @@ -0,0 +1,28 @@ +import logging + +from bmpa.command.common import Command +import bmpa.service.hostname as service_hostname +from bmpa.utils import validates + + +LOG = logging.getLogger(__name__) + + +class SetHostname(Command): + + def __init__(self, hostname, **kwargs): + super(SetHostname, self).__init__(**kwargs) + self.hostname = hostname + + def validate(self): + validates.is_required(self.hostname) + + def execute(self): + hostname = self.hostname + + service_hostname.set_hostname(hostname) + LOG.info("Set hostname=%(hostname)s successfully.", + {"hostname": hostname}) + + def execute_after(self): + self.data["hostname"] = self.hostname diff --git a/bmp-agent/bmpa/command/image.py b/bmp-agent/bmpa/command/image.py new file mode 100644 index 0000000..77e0b5d --- /dev/null +++ b/bmp-agent/bmpa/command/image.py @@ -0,0 +1,65 @@ +from bmpa.command.common import Command +from bmpa.service import image +from bmpa.utils import validates + + +class WriteImage(Command): + + def __init__(self, + url, + format, + hash, + filename, + **kwargs): + super(WriteImage, self).__init__(**kwargs) + + self.url = url + self.format = format + self.hash = hash + self.filename = filename + self.res = None + + validates.is_required(url, 'url') + validates.is_required(format, 'format') + validates.is_required(hash, 'hash') + validates.is_required(filename, 'filename') + + def execute(self): + self.res = image.write_image(url=self.url, format=self.format, + hash=self.hash, filename=self.filename) + + def execute_after(self): + self.data["root_device_hints"] = self.res['root_device_hints'] + if "data_device_hints" in self.res: + self.data["data_device_hints"] = self.res['data_device_hints'] + + +class WriteImageTar(Command): + + def __init__(self, + url, + format, + hash, + filename, + **kwargs): + super(WriteImageTar, self).__init__(**kwargs) + + self.url = url + self.format = format + self.hash = hash + self.filename = filename + self.res = None + + validates.is_required(url, 'url') + validates.is_required(format, 'format') + validates.is_required(hash, 'hash') + validates.is_required(filename, 'filename') + + def execute(self): + self.res = image.write_image_tar(url=self.url, format=self.format, + hash=self.hash, filename=self.filename) + + def execute_after(self): + self.data["root_device_hints"] = self.res['root_device_hints'] + if "data_device_hints" in self.res: + self.data["data_device_hints"] = self.res['data_device_hints'] diff --git a/bmp-agent/bmpa/command/metadata.py b/bmp-agent/bmpa/command/metadata.py new file mode 100644 index 0000000..625fd72 --- /dev/null +++ b/bmp-agent/bmpa/command/metadata.py @@ -0,0 +1,87 @@ +import logging + +from bmpa.command.common import Command +from bmpa.service import metadata +from bmpa.utils import validates + + +LOG = logging.getLogger(__name__) + + +class SetMetaData(Command): + + def __init__(self, meta_data, **kwargs): + super(SetMetaData, self).__init__(**kwargs) + self.data = meta_data + + def validate(self): + validates.is_required(self.data, 'meta_data') + + def execute(self): + + metadata.set_meta_data(self.data) + + +class SetUserData(Command): + + def __init__(self, user_data='', **kwargs): + super(SetUserData, self).__init__(**kwargs) + self.data = user_data + + def execute(self): + + metadata.set_user_data(self.data) + + +class SetVendorData(Command): + + def __init__(self, vendor_data, **kwargs): + super(SetVendorData, self).__init__(**kwargs) + self.data = vendor_data + + def validate(self): + validates.is_required(self.data) + + def execute(self): + + metadata.set_vendor_data(self.data) + + +class SetNetwork(Command): + + def __init__(self, network, **kwargs): + super(SetNetwork, self).__init__(**kwargs) + self.data = network + + def validate(self): + validates.is_required(self.data, 'network') + + def execute(self): + + metadata.set_network(self.data) + + +class SetNetworkWindows(Command): + + def __init__(self, network, **kwargs): + super(SetNetworkWindows, self).__init__(**kwargs) + self.data = network + + def validate(self): + validates.is_required(self.data, 'network') + + def execute(self): + + metadata.set_network(self.data) + + +class SetCloudinitConf(Command): + + def __init__(self, ssh_pwauth="no", disable_root=False, **kwargs): + super(SetCloudinitConf, self).__init__(**kwargs) + self.ssh_pwauth = ssh_pwauth + self.disable_root = disable_root + + def execute(self): + + metadata.set_cloudinit_conf(self.ssh_pwauth, self.disable_root) diff --git a/bmp-agent/bmpa/command/mount.py b/bmp-agent/bmpa/command/mount.py new file mode 100755 index 0000000..bc66d4f --- /dev/null +++ b/bmp-agent/bmpa/command/mount.py @@ -0,0 +1,21 @@ +import logging + + +from bmpa.command.common import Command +from bmpa.service import mount +import bmpa.utils.validates as validates + +LOG = logging.getLogger(__name__) + + +class MountPartitions(Command): + def __init__(self, mounts, auto_mount_efi=True, **kwargs): + self.mounts = mounts + self.auto_mount_efi = auto_mount_efi + super(MountPartitions, self).__init__(**kwargs) + + validates.is_required(mounts, 'mounts') + + def execute(self): + mount.mount_partitions( + auto_mount_efi=self.auto_mount_efi, mounts=self.mounts) diff --git a/bmp-agent/bmpa/command/node.py b/bmp-agent/bmpa/command/node.py new file mode 100644 index 0000000..23f2d97 --- /dev/null +++ b/bmp-agent/bmpa/command/node.py @@ -0,0 +1,26 @@ +import logging + +from bmpa.command.common import Command +from bmpa.service import initnode +import bmpa.utils.validates as validates + +LOG = logging.getLogger(__name__) + + +class InitNode(Command): + + def __init__(self, node_data, **kwargs): + super(InitNode, self).__init__(**kwargs) + self.node_data = node_data + validates.is_required(node_data, 'node_data') + validates.check_field(node_data, 'os_type') + validates.check_field(node_data, 'os_version') + self.res_node = None + + def execute(self): + self.res_node = initnode.init_node(self.node_data) + + def execute_after(self): + if isinstance(self.res_node, dict): + for key, value in self.res_node.items(): + self.data[key] = value diff --git a/bmp-agent/bmpa/command/partitions.py b/bmp-agent/bmpa/command/partitions.py new file mode 100644 index 0000000..95d2466 --- /dev/null +++ b/bmp-agent/bmpa/command/partitions.py @@ -0,0 +1,33 @@ +from bmpa.command.common import Command +from bmpa.service import partitions +import bmpa.utils.validates as validates + + +class MakePartitions(Command): + """Make partition. + + :param auto_create_efi: Automatically create the UEFI partition in UEFI mode. + :param auto_create_bios_grub: Automatically create a 1M BIOS_GRUB partition in BIOS mode with GPT. + """ + + def __init__(self, + volumes, + boot_mode=None, + auto_create_efi=True, + auto_create_bios_grub=True, + **kwargs): + super(MakePartitions, self).__init__(**kwargs) + self.volumes = volumes + self.boot_mode = boot_mode + self.auto_create_efi = auto_create_efi + self.auto_create_bios_grub = auto_create_bios_grub + validates.is_required(volumes, 'volumes') + + self.res_volumes = None + + def execute(self): + self.res_volumes = partitions.make_partition( + self.volumes, self.boot_mode, self.auto_create_efi, self.auto_create_bios_grub) + + def execute_after(self): + self.data["volumes"] = self.res_volumes diff --git a/bmp-agent/bmpa/command/password.py b/bmp-agent/bmpa/command/password.py new file mode 100644 index 0000000..7baaeaf --- /dev/null +++ b/bmp-agent/bmpa/command/password.py @@ -0,0 +1,23 @@ +import logging + +from bmpa.command.common import Command +import bmpa.service.password as service_password +from bmpa.utils import validates + + +LOG = logging.getLogger(__name__) + + +class SetPassword(Command): + + def __init__(self, password, username='root', **kwargs): + super(SetPassword, self).__init__(**kwargs) + self.password = password + self.username = username + + def validate(self): + validates.is_required(self.password, 'password') + + def execute(self): + + service_password.set_password(self.password, self.username) diff --git a/bmp-agent/bmpa/command/ping.py b/bmp-agent/bmpa/command/ping.py new file mode 100755 index 0000000..ceb737d --- /dev/null +++ b/bmp-agent/bmpa/command/ping.py @@ -0,0 +1,20 @@ +import logging + +from bmpa.command.common import Command + +LOG = logging.getLogger(__name__) + + +class Ping(Command): + """Detect mq communication. + + Avoid high concurrency and the issue of message loss + when establishing a connection for the first time. + + """ + + def __init__(self, **kwargs): + super(Ping, self).__init__(**kwargs) + + def execute(self): + LOG.info("Ping completely.") diff --git a/bmp-agent/bmpa/command/raid.py b/bmp-agent/bmpa/command/raid.py new file mode 100644 index 0000000..33d1ad7 --- /dev/null +++ b/bmp-agent/bmpa/command/raid.py @@ -0,0 +1,38 @@ +import logging + +from bmpa.command.common import Command +from bmpa.service import raid +import bmpa.utils.validates as validates + +LOG = logging.getLogger(__name__) + + +class MakeRaid(Command): + + def __init__(self, raid_datas, **kwargs): + super(MakeRaid, self).__init__(**kwargs) + self.raid_datas = raid_datas + self.res_raid_datas = None + validates.is_required(raid_datas, 'raid_datas') + for raid_data in raid_datas: + validates.check_field(raid_data, 'adapter_id') + validates.check_field(raid_data, 'volumes') + + def execute(self): + self.res_raid_datas = raid.make_raid(self.raid_datas) + + def execute_after(self): + self.data["raid_datas"] = self.res_raid_datas + + +class CleanRaid(Command): + + def __init__(self, raid_datas, **kwargs): + super(CleanRaid, self).__init__(**kwargs) + self.raid_datas = raid_datas + validates.is_required(raid_datas, 'raid_datas') + for raid_data in raid_datas: + validates.check_field(raid_data, 'adapter_id') + + def execute(self): + raid.clean_raid(self.raid_datas) diff --git a/bmp-agent/bmpa/config.py b/bmp-agent/bmpa/config.py new file mode 100755 index 0000000..b2c71dd --- /dev/null +++ b/bmp-agent/bmpa/config.py @@ -0,0 +1,27 @@ +import os + +from bmpa import constants +from bmpa.utils import utils + +cmdline_path: str = os.getenv('BMD_CMDLINE_PATH', '/proc/cmdline') +AGENT_PARAMS: dict = utils.get_agent_params(cmdline_path) +heart_period: int = int(AGENT_PARAMS.get('BMP_HEART_PERIOD', 10)) +mq_host: str = AGENT_PARAMS.get('BMP_MQ_HOST') # required +mq_port: int = int(AGENT_PARAMS.get('BMP_MQ_PORT', 5672)) +mq_username: str = AGENT_PARAMS.get('BMP_MQ_USER') # required +mq_password: str = AGENT_PARAMS.get('BMP_MQ_PASSWORD') # required +mq_password = mq_password.strip("'") +mq_is_use_ssl: int = int(AGENT_PARAMS.get('BMP_MQ_IS_USE_SSL', + 0)) # 0:not use 1:use +mq_vhost: str = AGENT_PARAMS.get('BMP_MQ_VHOST', '/bmp') +mq_exchange: str = AGENT_PARAMS.get('BMP_MQ_EXCHANGE', 'CPS_IRONIC_SCHEDULER') +mq_exchange_type: str = AGENT_PARAMS.get('BMP_MQ_EXCHANGE_TYPE', 'direct') +image_host: str = AGENT_PARAMS.get('BMP_IMAGE_HOST') +image_port: int = int(AGENT_PARAMS.get('BMP_IMAGE_PORT', 10000)) +protocol: str = AGENT_PARAMS.get('BMP_PROTOCAL', constants.PROTOCAL_RABBITMQ) +log_path: str = AGENT_PARAMS.get('BMP_LOG_PATH', + '/var/log/bmp/bmp-agent.log') +# DEBUG,INFO,WARNING +logging_level = AGENT_PARAMS.get('LOGGING_LEVEL', 'INFO') +rsyslog_host = AGENT_PARAMS.get('BMP_RSYSLOG_HSOT', mq_host) +rsyslog_port = AGENT_PARAMS.get('BMP_RSYSLOG_PORT', 1514) diff --git a/bmp-agent/bmpa/constants.py b/bmp-agent/bmpa/constants.py new file mode 100644 index 0000000..a7b72b8 --- /dev/null +++ b/bmp-agent/bmpa/constants.py @@ -0,0 +1,12 @@ +PROTOCAL_RABBITMQ = 'rabbitmq' +PROTOCAL_HTTP = 'http' +UEFI = 'uefi' +EFI_FSTYPE = 'vfat' +BIOS = 'bios' +GPT = 'gpt' +MACHINE_AARCH64 = 'aarch64' +EFIBOOTMGR_LABEL = 'bmp' +WINDOWS_EFIBOOTMGR_LABEL = 'Windows Boot Manager' +ROOT_LABEL = 'l_root' +EFI_LABLE = 'l_efi' +WINDOWS_ROOT_LABEL = 'Windows' diff --git a/bmp-agent/bmpa/device/__init__.py b/bmp-agent/bmpa/device/__init__.py new file mode 100644 index 0000000..74b23f7 --- /dev/null +++ b/bmp-agent/bmpa/device/__init__.py @@ -0,0 +1,70 @@ +import logging + +from bmpa.errors import IncompatibleHardwareMethodError + +LOG = logging.getLogger(__name__) + +RAID_INDEX = { + "RAID0": "0", + "RAID1": "1", + "RAID5": "5", + "RAID10": "10" +} + + +class BaseRaid(object): + + root_device = None + + def execute_raid_config(self, config): + raid_level = config.raid_level.lower() + if raid_level == 'noraid': + return self.noraid(config) + elif raid_level == 'raid0': + return self.raid0(config) + elif raid_level == 'raid1': + return self.raid1(config) + elif raid_level == 'raid5': + return self.raid5(config) + elif raid_level == 'raid10': + return self.raid10(config) + else: + raise ValueError(f'Unsupported RAID level: {raid_level}') + + def list_adapter(self): + """Get adapters info. + + """ + return None + + def get_adapter_ids(self): + raise IncompatibleHardwareMethodError( + 'Not support get adapter ids method.') + + def display(self, adapter_id: int = 0): + """Get physical disks. + + """ + return None + + def get_disks(self, adapter_id: str = '0'): + raise IncompatibleHardwareMethodError('Not support get disk method.') + + def noraid(self, config): + raise IncompatibleHardwareMethodError('Not support NORAID type.') + + def raid0(self, config): + raise IncompatibleHardwareMethodError('Not support RAID0 type.') + + def raid1(self, config): + raise IncompatibleHardwareMethodError('Not support RAID1 type.') + + def raid5(self, config): + raise IncompatibleHardwareMethodError('Not support RAID5 type.') + + def raid10(self, config): + raise IncompatibleHardwareMethodError('Not support RAID10 type.') + + def clean_raid(self, adapter_id: str = '0', delay_time=0): + raise IncompatibleHardwareMethodError( + 'Not support clean raid config method.') diff --git a/bmp-agent/bmpa/device/default.py b/bmp-agent/bmpa/device/default.py new file mode 100644 index 0000000..93ef8e0 --- /dev/null +++ b/bmp-agent/bmpa/device/default.py @@ -0,0 +1,8 @@ + +class DefaultDevice(object): + + def __init__(self): + pass + + def grub_ttys(self): + return 'ttyS0' diff --git a/bmp-agent/bmpa/device/factory.py b/bmp-agent/bmpa/device/factory.py new file mode 100644 index 0000000..12b96ed --- /dev/null +++ b/bmp-agent/bmpa/device/factory.py @@ -0,0 +1,13 @@ +from bmpa.device.default import DefaultDevice +from bmpa.device.sogon import SogonW580G20 + + +def get_device(manufacturer, product_name): + return _get_device(manufacturer, product_name) + + +def _get_device(manufacturer, product_name): + if manufacturer == SogonW580G20.MANUFACTURER and product_name == SogonW580G20.PRODUCT_NAME: + return SogonW580G20() + + return DefaultDevice() diff --git a/bmp-agent/bmpa/device/sogon.py b/bmp-agent/bmpa/device/sogon.py new file mode 100644 index 0000000..a1a7f15 --- /dev/null +++ b/bmp-agent/bmpa/device/sogon.py @@ -0,0 +1,20 @@ +from bmpa.device.default import DefaultDevice + + +class Sogon(DefaultDevice): + def __init__(self): + super(Sogon, self).__init__() + + def grub_ttys(self): + return 'ttyS1' + + +class SogonW580G20(DefaultDevice): + MANUFACTURER = "Sugon" + PRODUCT_NAME = "W580-G20 (Default string)" + + def __init__(self): + super(Sogon, self).__init__() + + def grub_ttys(self): + return 'ttyS1' diff --git a/bmp-agent/bmpa/engine.py b/bmp-agent/bmpa/engine.py new file mode 100644 index 0000000..de17dc1 --- /dev/null +++ b/bmp-agent/bmpa/engine.py @@ -0,0 +1,107 @@ +import logging +import signal +import sys +import threading +import time + +from bmpa.command import command_service +from bmpa.command.common import Command +from bmpa import config +from bmpa import constants +import bmpa.lifecycle +from bmpa.service import node +from bmpa.utils import hardware + +LOG = logging.getLogger(__name__) + + +class Engine(bmpa.lifecycle.LifeCycle): + + def __init__(self): + super(Engine, self).__init__() + self.__init_protocol() + + def do_start(self): + self.__init_node() + self.__init_thread() + self.__bind_signal() + + def do_stop(self): + self.__unbind_signal() + LOG.info('stop.....') + + def __init_node(self): + vendor = hardware.get_system_vendor_info() + node.set_system_vendor_info(vendor) + node.set_serial_number(vendor.serial_number) + + def __init_thread(self): + __protocol_start_thread = threading.Thread( + name='ProtocalStartThread', + target=self.__protocol_start, + daemon=True) + __heartbeat_thread = threading.Thread(name='HeartbeatThread', + target=self.__heartbeat, + daemon=True) + __command_dispatch_thread = threading.Thread( + name='CommandDispatchThread', + target=self.__command_dispatch, + daemon=True) + + __command_query_thread = threading.Thread(name='CommandQueryThread', + target=self.__command_query, + daemon=True) + __protocol_start_thread.start() + __heartbeat_thread.start() + __command_dispatch_thread.start() + __command_query_thread.start() + + def __bind_signal(self): + # bind signal + self.hold_sigint = signal.signal(signal.SIGINT, self.__handler_signal) + self.hold_sigterm = signal.signal(signal.SIGTERM, + self.__handler_signal) + + def __unbind_signal(self): + # unbind signal + signal.signal(signal.SIGINT, self.hold_sigint) + signal.signal(signal.SIGTERM, self.hold_sigterm) + + def __handler_signal(self, signum, frame): + LOG.info("receive a kill signal %s=%s.", signum, frame) + self.stop() + sys.exit() + + def __heartbeat(self): + wait = base = config.heart_period + while not self.should_stop(): + try: + __protocol.heartbeat() + wait = base # reset to base wait time on success + LOG.info("Trigger a heart period %d.", wait) + except Exception as exc: + LOG.error(str(exc)) + wait = min(20, wait * 2 or 1) + + time.sleep(wait) + + def __command_dispatch(self): + while not self.should_stop(): + command_service.dispatch() + + def __command_query(self): + while not self.should_stop(): + __protocol.receive_command() + + def __protocol_start(self): + # while not self.should_stop(): + __protocol.start() + + def __init_protocol(self): + global __protocol + if config.protocol == constants.PROTOCAL_RABBITMQ: + from bmpa.protocol.rabbitmq import RabbitmqProtocol + __protocol = RabbitmqProtocol() + + def send_command(command: Command): + __protocol.send_command(command) diff --git a/bmp-agent/bmpa/errors.py b/bmp-agent/bmpa/errors.py new file mode 100644 index 0000000..54e092a --- /dev/null +++ b/bmp-agent/bmpa/errors.py @@ -0,0 +1,107 @@ +from bmpa import serialize + + +class RESTError(Exception, serialize.Serializable): + """Base class for errors.""" + message = 'Internal Server Error.' + details = 'An unexpected error occurred. Please try back later.' + status_code = 500 + serializable_fields = ('type', 'code', 'message', 'details') + + def __init__(self, details: str = None, *args, **kwargs): + super(RESTError, self).__init__(*args, **kwargs) + self.type = self.__class__.__name__ + self.code = self.status_code + if details: + self.details = details + + def __str__(self): + return "{}: {}".format(self.message, self.details) + + def __repr__(self): + return "{}('{}')".format(self.__class__.__name__, self.__str__()) + + +class UnkownCommandError(RESTError): + """Error which occurs if not has the command.""" + message = 'Not found' + status_code = 404 + details = 'The Command was not found.' + + def __init__(self, details: str = None): + if details: + self.details = details + super(UnkownCommandError, self).__init__(details) + + +class IncompatibleHardwareMethodError(RESTError): + """Error raised when HardwareManager method incompatible with hardware.""" + + message = 'HardwareManager method is not compatible with hardware.' + + def __init__(self, details: str = None): + super(IncompatibleHardwareMethodError, self).__init__(details) + + +class BlockDeviceError(RESTError): + """Error raised when a block devices causes an unknown error.""" + + message = 'Block device caused unknown error.' + + def __init__(self, details): + super(BlockDeviceError, self).__init__(details) + + +class BlockDeviceEraseError(RESTError): + """Error raised when an error occurs erasing a block device.""" + + message = 'Error erasing block device.' + + def __init__(self, details): + super(BlockDeviceEraseError, self).__init__(details) + + +class DeviceNotFound(RESTError): + status_code = 404 + """Error raised when the device to deploy the image onto is not found.""" + + message = ('Error finding the disk or partition device to deploy ' + 'the image onto') + + def __init__(self, details): + super(DeviceNotFound, self).__init__(details) + + +class ImageDownloadError(RESTError): + """Error raised when an image cannot be downloaded.""" + + message = 'Error downloading image.' + + def __init__(self, image_id, msg): + details = 'Download of image id {} failed: {}.'.format(image_id, msg) + self.secondary_message = msg + super(ImageDownloadError, self).__init__(details) + + +class ImageChecksumError(RESTError): + """Error raised when an image fails to verify against its checksum.""" + + message = 'Error verifying image checksum.' + details_str = ('Image failed to verify against checksum. location: {}; ' + 'image ID: {}; image checksum: {}; verification ' + 'checksum: {}') + + def __init__(self, image_id, image_location, checksum, + calculated_checksum): + details = self.details_str.format(image_location, image_id, checksum, + calculated_checksum) + super(ImageChecksumError, self).__init__(details) + + +class BmpError(RESTError): + """Error bmp error.""" + + message = 'Bmp error.' + + def __init__(self, details): + super(BmpError, self).__init__(details) diff --git a/bmp-agent/bmpa/lifecycle.py b/bmp-agent/bmpa/lifecycle.py new file mode 100644 index 0000000..4216b2c --- /dev/null +++ b/bmp-agent/bmpa/lifecycle.py @@ -0,0 +1,92 @@ +import logging +from threading import Condition + +LOG = logging.getLogger(__name__) + +STOPPED = "STOPPED" +FAILED = "FAILED" +STARTING = "STARTING" +STARTED = "STARTED" +STOPPING = "STOPPING" +RUNNING = "RUNNING" + + +class LifeCycleException(Exception): + + def __init__(self, message): + super(LifeCycleException, self).__init__(message) + + +class LifeCycle(object): + + def __init__(self): + self.lock = Condition() + self.state = STOPPED + + def start(self): + with self.lock: + try: + if self.state == STARTED or self.state == STARTING: + return + self.state = STARTING + LOG.info("%s is starting.", self.__class__.__name__) + self.do_start() + self.state = STARTED + LOG.info("%s is started.", self.__class__.__name__) + except Exception as e: + self.set_failed(e) + LOG.info("%s started failed.", self.__class__.__name__) + raise + + def stop(self): + with self.lock: + try: + if self.state == STOPPING or self.state == STOPPED: + return + self.state = STOPPING + LOG.info("%s is stopping.", self.__class__.__name__) + self.lock.notify() + self.do_stop() + self.state = STOPPED + LOG.info("%s is stopped.", self.__class__.__name__) + except Exception as e: + self.set_failed(e) + LOG.info("%s stop failed.", self.__class__.__name__) + raise + + def is_running(self): + return self.state == STARTED or self.state == STARTING + + def is_started(self): + return self.state == STARTED + + def is_starting(self): + return self.state == STARTING + + def is_stoping(self): + return self.state == STOPPING + + def is_stopped(self): + return self.state == STOPPED + + def is_failed(self): + return self.state == FAILED + + def do_start(self): + raise LifeCycleException("%s not impl doStart method." % + self.__class__.__name__) + + def do_stop(self): + raise LifeCycleException("%s not impl doStart method." % + self.__class__.__name__) + + def set_failed(self, exception): + self.state = FAILED + LOG.error("err:%s", str(exception)) + LOG.error("%s", __name__, exc_info=1) + + def get_state(self): + return self.state + + def should_stop(self): + return self.state in [STOPPING, STOPPED, FAILED] diff --git a/bmp-agent/bmpa/log.py b/bmp-agent/bmpa/log.py new file mode 100644 index 0000000..25a5461 --- /dev/null +++ b/bmp-agent/bmpa/log.py @@ -0,0 +1,46 @@ +import functools +import logging +import os + +import bmpa.config as config +import bmpa.utils.file as file + +app_name = 'bmpa' + + +def _setupLogging(name='bmpa'): + log_path = config.log_path + log_dir = os.path.dirname(log_path) + file.ensure_dir(log_dir) + + logger = logging.getLogger(name) + logger.setLevel(logging.getLevelName(config.logging_level)) + formatter = logging.Formatter( + '%(asctime)s %(name)s/%(filename)s[line:%(lineno)d] %(levelname)s %(message)s') + + file_handler = logging.FileHandler(log_path, encoding='utf-8') + file_handler.setFormatter(formatter) + + stream_handler = logging.StreamHandler() + stream_handler.setFormatter(formatter) + + logger.addHandler(file_handler) + logger.addHandler(stream_handler) + + +def init(name='bmpa'): + global app_name + app_name = name + _setupLogging(name) + + +def log_complete(func): + + @functools.wraps(func) + def wrapper(*args, **kwargs): + result = func(*args, **kwargs) + logger = logging.getLogger(app_name) + logger.info("%s complete.", func.__name__) + return result + + return wrapper diff --git a/bmp-agent/bmpa/model/__init__.py b/bmp-agent/bmpa/model/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/bmp-agent/bmpa/model/disk.py b/bmp-agent/bmpa/model/disk.py new file mode 100644 index 0000000..e52b558 --- /dev/null +++ b/bmp-agent/bmpa/model/disk.py @@ -0,0 +1,43 @@ +from bmpa.utils import utils + + +class Disk: + + def __init__(self, + serial: str = None, + enclosure: int = None, + slot: int = None, + pd_type: str = None, + media_type: str = None, + raw_size: float = None, + raw_size_unit: str = None, + size: float = None, + size_unit: str = None, + inquiry_data: str = None, + device_firware_level: str = None, + device_path: str = None): + self.serial = serial + self.enclosure = enclosure + self.slot = slot + self.pd_type = pd_type + self.media_type = media_type + self.raw_size, self.raw_size_unit = utils.convert_disk_size( + raw_size, raw_size_unit) + self.size, self.size_unit = utils.convert_disk_size(size, size_unit) + self.inquiry_data = inquiry_data + self.device_firware_level = device_firware_level + self.device_path = device_path + + def __str__(self): + return (f"Disk(serial='{self.serial}'," + f"enclosure='{self.enclosure}'," + f"slot='{self.slot}'," + f"pd_type='{self.pd_type}'," + f"media_type='{self.media_type}'," + f"raw_size='{self.raw_size}'," + f"raw_size_unit='{self.raw_size_unit}'," + f"size='{self.size}'," + f"size_unit='{self.size_unit}'," + f"inquiry_data='{self.inquiry_data}'," + f"device_firware_level='{self.device_firware_level}'," + f"device_path='{self.device_path}')") diff --git a/bmp-agent/bmpa/model/raid.py b/bmp-agent/bmpa/model/raid.py new file mode 100644 index 0000000..0915a1d --- /dev/null +++ b/bmp-agent/bmpa/model/raid.py @@ -0,0 +1,15 @@ +class RaidConfig: + + def __init__(self, + adapter_id: str, + raid_level: str, + physical_disks: list + ): + self.adapter_id = adapter_id + self.raid_level = raid_level + self.physical_disks = physical_disks + + def __str__(self): + return (f"RaidConfig(adapter_id='{self.adapter_id}'," + f"raid_level='{self.raid_level}'," + f"physical_disks='{self.physical_disks}')") diff --git a/bmp-agent/bmpa/osystem/__init__.py b/bmp-agent/bmpa/osystem/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bmp-agent/bmpa/osystem/centos.py b/bmp-agent/bmpa/osystem/centos.py new file mode 100644 index 0000000..b5c465c --- /dev/null +++ b/bmp-agent/bmpa/osystem/centos.py @@ -0,0 +1,51 @@ +import logging +import platform + +from bmpa import constants +from bmpa.osystem.default import DefaultOsystem +from bmpa.utils import chroot +from bmpa.utils import executor + + +LOG = logging.getLogger(__name__) + + +class CentOS7X(DefaultOsystem): + + def _distro(self): + return 'centos' + + def _set_network_service(self, target): + with chroot.ChrootTarget(target) as inchroot: + inchroot.execute('systemctl', 'enable', 'NetworkManager') + + +class CentOS8X(CentOS7X): + + def _set_network_service(self, target): + pass + + def _parse_user_data(self, data): + return data.replace("#!/usr/bin/env python", + "#!/usr/bin/env python3") + + def _install_grub_to_device(self, target, root_device): + # grub2-install has added UEFI Secure Boot verification, causing an error. + # We now utilize the corresponding modules from the image, eliminating the need for grub2-install. + pass + + def _kernel_install(self, target): + super(CentOS8X, self)._kernel_install_execute(target) + + def _configure_efi_boot_entry(self, root_device): + super(CentOS8X, self)._delete_efi_boot(constants.EFIBOOTMGR_LABEL) + distro = self._distro() + efi_file = '"\EFI\%(distro)s\grubx64.efi"' % {'distro': distro} + if platform.machine() == constants.MACHINE_AARCH64: + efi_file = '"\EFI\%(distro)s\grubaa64.efi"' % {'distro': distro} + cmd = ('efibootmgr', '-c', '-w', '-L', constants.EFIBOOTMGR_LABEL, '-d', root_device, '-p', '1', + '--write-signature', '-l', efi_file) + executor.execute(*cmd) + + def _efi_grub_config_path(self, target): + return '/boot/efi/EFI/centos/grub.cfg' diff --git a/bmp-agent/bmpa/osystem/debian.py b/bmp-agent/bmpa/osystem/debian.py new file mode 100644 index 0000000..832c9e8 --- /dev/null +++ b/bmp-agent/bmpa/osystem/debian.py @@ -0,0 +1,29 @@ +import logging + +from bmpa.errors import BmpError +from bmpa.osystem.default import DefaultOsystem +from bmpa.utils import chroot +from bmpa.utils.executor import ProcessExecutionError + +LOG = logging.getLogger(__name__) + + +class Debian10x(DefaultOsystem): + def _distro(self): + return 'debian' + + def _get_cloudinit_conf_template_file(self): + return "cloud_debian.tpl" + + def _update_initramfs(self, target): + cmd = ('update-initramfs', '-u') + try: + with chroot.ChrootTarget(target) as inchroot: + inchroot.execute(*cmd) + except ProcessExecutionError as e: + error_msg = ('repair initram fs' + 'failed with %(err)s' % { + 'err': e + }) + LOG.error(error_msg) + raise BmpError(error_msg) diff --git a/bmp-agent/bmpa/osystem/default.py b/bmp-agent/bmpa/osystem/default.py new file mode 100644 index 0000000..e9ca31d --- /dev/null +++ b/bmp-agent/bmpa/osystem/default.py @@ -0,0 +1,426 @@ + +import base64 +import json +import logging +import operator +import os +import re + +from bmpa import constants +from bmpa.errors import BmpError +from bmpa.utils import chroot +from bmpa.utils import executor +from bmpa.utils.executor import ProcessExecutionError +from bmpa.utils import hardware +from bmpa.utils import mountutils +from bmpa.utils import paths +from bmpa.utils import strutils +from bmpa.utils import system +from bmpa.utils import utils + +LOG = logging.getLogger(__name__) + + +class DefaultOsystem(object): + + def write_image_setup_boot(self): + pass + + def setup_boot(self, target, root_partition, root_device, boot_mode, mounts, grub_ttys): + self._update_fstab(target=target, mounts=mounts) + self._install_grub(target=target, root_device=root_device, + boot_mode=boot_mode, grub_ttys=grub_ttys) + self._update_initramfs(target=target) + + def set_password(self, target, root_partition, password, username='root'): + if mountutils.is_mounted(target=target): + self._set_password(target, password, username) + else: + mountutils.do_mount(src=root_partition, target=target) + self._set_password(target, password, username) + + self._open_password_auth(target) + os.sync() + + def _set_password(self, target, password, username='root'): + with chroot.ChrootTarget(target) as inchroot: + inchroot.execute('passwd', + username, + std_input='%(password)s\n%(password)s\n' % + {'password': password}) + + def set_hostname(self, target, root_partition, hostname): + path = paths.target_path(target, '/etc/hostname') + executor.execute('echo %(hostname)s > %(path)s' % + {'hostname': hostname, 'path': path}, shell=True) + + def set_meta_data(self, target, root_partition, data): + data = self._parse_meta_data(data) + file_path = self._meta_data_path() + self._write_data_to_target(target, file_path, data) + self.set_cloudbase_conf(target, root_partition) + + def set_network(self, target, root_partition, data): + file_path = self._network_path() + self._write_data_to_target(target, file_path, data) + self._set_network_service(target) + + def set_user_data(self, target, root_partition, data): + if data != '': + data = base64.b64decode(data) + if isinstance(data, bytes): + data = data.decode('utf-8') + data = self._parse_user_data(data) + file_path = self._user_data_path() + self._write_data_to_target(target, file_path, data) + + def set_vendor_data(self, target, root_partition, data): + file_path = 'var/lib/cloud/seed/nocloud/vendor-data' + self._write_data_to_target(target, file_path, data) + + def get_root_partition(self, root_device): + root_partition = None + root_lable = self._root_lable() + root_partition = hardware.get_labelled_partition( + root_device, root_lable, attempts_times=10) + + if root_partition is not None: + return root_partition + LOG.warn('Not fund root partition by label:%s', root_lable) + return self._guess_root_partition(root_device) + + def _root_lable(self): + return constants.ROOT_LABEL + + def _guess_root_partition(self, root_device): + partition_template = '%(root_device)s%(device_index)d' + if hardware.is_nvme_device(root_device): + partition_template = '%(root_device)sp%(device_index)d' + root_partition = partition_template % { + 'root_device': root_device, + 'device_index': 2 + } + return root_partition + + def set_cloudbase_conf(self, target, root_partition, only_set_network=False): + pass + + def formatpartitions(self, partitions): + root_partition_path = None + partitions = self._parse_partitions(partitions) + for partition in partitions: + fs = partition['fs_type'] + label = partition['label'] + device_path = partition['device_path'] + options = partition.get('options') + LOG.info('Format partitions fs:%(fs)s, path:%(path)s lable:%(label)s', { + 'fs': fs, + 'path': device_path, + 'label': label + }) + hardware.mkfs(fs=fs, path=device_path, + label=label, options=options) + if partition.get('is_root', False): + root_partition_path = device_path + return root_partition_path + + def _open_password_auth(self, target): + self._set_password_auth(target, 'yes') + + def _install_grub(self, target, root_device, boot_mode, grub_ttys): + try: + self._update_default_grub(target=target, grub_ttys=grub_ttys) + if boot_mode == constants.UEFI: + self._install_uefi_grub(target, root_device) + else: + self._install_bios_grub(target, root_device) + self._kernel_install(target) + except ProcessLookupError as e: + error_msg = ('Install grub' 'failed with %(err)s.' % {'err': e}) + LOG.error(error_msg) + raise BmpError(error_msg) + + def _install_bios_grub(self, target, root_device): + binary_name = 'grub' + if os.path.exists(paths.target_path(target, 'usr/sbin/grub2-install')): + binary_name = 'grub2' + + grub_install = '%s-install' % binary_name + grub_mkconfig = '%s-mkconfig' % binary_name + grub_cfg_path = '/boot/%s/grub.cfg' % binary_name + with chroot.ChrootTarget(target) as inchroot: + cmd = (grub_install, root_device) + LOG.info('Installing GRUB2 on disk %s.', root_device) + stdout, _ = inchroot.execute(*cmd) + LOG.info('GRUB2 successfully installed on device:%s, %s.', + root_device, stdout) + cmd = (grub_mkconfig, '-o', grub_cfg_path) + stdout, _ = inchroot.execute(*cmd) + LOG.info('Grub mkconfig successfully: %s.', stdout) + + def _install_uefi_grub(self, target, root_device): + self._install_grub_to_device(target, root_device) + self._generate_efi_grub_config(target) + self._configure_efi_boot_entry(root_device) + LOG.info('Install uefi grub success.') + + def _delete_efi_boot(self, efi_boot_label=None): + + delete_efi_boot_script = system.get_relative_path( + 'shell/delete_efi_boot.sh') + cmd = ['/bin/bash', delete_efi_boot_script] + if efi_boot_label is not None: + cmd.append(efi_boot_label) + LOG.info('Delete efi boot with command: %s', ' '.join(cmd)) + try: + stdout, stderr = executor.execute( + *cmd, check_exit_code=[0]) + LOG.info( + 'Delete efi boot completely. stdout : %s, stderr : %s.', + stdout, stderr) + except ProcessExecutionError as e: + LOG.warn('Delete efi boot error :%s.', e) + + def _distro(self): + return 'linux' + + def _update_dracut_conf(self, target): + dracut_path = paths.target_path(target, '/etc/dracut.conf') + with open(dracut_path, 'r') as g: + contents = g.read() + with open(dracut_path, 'w') as g: + g.write( + re.sub(r'#filesystems.*', r'filesystems="xfs ext4 "', + contents)) + + def _update_initramfs(self, target): + self._update_dracut_conf(target) + linux_version = self._get_kernel_version(target) + cmd = ('dracut', '--force', '--fstab', '--early-microcode', + '--kmoddir', '/lib/modules/%s' % linux_version, + '--kver=%s' % linux_version) + try: + with chroot.ChrootTarget(target) as inchroot: + inchroot.execute(*cmd) + except ProcessExecutionError as e: + error_msg = ('repair initram fs' + 'failed with %(err)s' % { + 'err': e + }) + LOG.error(error_msg) + raise BmpError(error_msg) + + def _get_kernel_version(self, target): + return system.get_kernel_version_by_dir(target) + + def _update_fstab(self, target, mounts, mode='w'): + LOG.info('Start update fstab mounts: %s.', mounts) + mounts = self._parse_fstab(mounts) + if mounts is not None and len(mounts) > 0: + fstab_tpl_path = system.get_relative_path( + 'template/fstab/fstab.tpl') + fstab_config = system.render_template( + fstab_tpl_path, {'mounts': mounts}) + + fstab_path = paths.target_path(target, 'etc/fstab') + system.ensure_dir(os.path.dirname(fstab_path)) + with open(fstab_path, mode) as f: + f.write(fstab_config) + + LOG.info('Update fstab write %s to %s.', fstab_config, + fstab_path) + + def _parse_fstab(self, mounts): + ret = [] + mounts = sorted(mounts, key=operator.itemgetter('mountpoint')) + for mount in mounts: + temp_mount = dict() + options = mount.get('options', '') + if options == '': + options = 'defaults' + temp_mount['label'] = mount['label'] + temp_mount['mountpoint'] = mount['mountpoint'] + temp_mount['fs_type'] = mount['fs_type'] + temp_mount['options'] = options + ret.append(temp_mount) + + return ret + + def _kernel_install(self, target): + pass + + def _kernel_install_execute(self, target): + """Incorporate to address Linux path generation errors in /boot/loader/entries. + + """ + kernel_version = self._get_kernel_version(target) + kernel_modules_vmlinuz_path = '/lib/modules/%s/vmlinuz' % kernel_version + + try: + cmd = ('kernel-install', 'add', kernel_version, + kernel_modules_vmlinuz_path) + with chroot.ChrootTarget(target) as inchroot: + inchroot.execute(*cmd) + except Exception as e: + # An exception may be raised here: 'No such file or directory, + # but it doesn't affect the update of the /boot/loader/entries content. + LOG.warn('%s', str(e)) + + def _install_grub_to_device(self, target, root_device): + binary_name = 'grub' + if os.path.exists(paths.target_path(target, 'usr/sbin/grub2-install')): + binary_name = 'grub2' + grub_install = '%s-install' % binary_name + cmd = (grub_install, root_device) + with chroot.ChrootTarget(target) as inchroot: + stdout, _ = inchroot.execute(*cmd) + LOG.info('Grub install successfully: %s.', stdout) + + def _generate_efi_grub_config(self, target): + binary_name = 'grub' + if os.path.exists(paths.target_path(target, 'usr/sbin/grub2-install')): + binary_name = 'grub2' + grub_mkconfig = '%s-mkconfig' % binary_name + grub_cfg_path = self._efi_grub_config_path(target) + cmd = (grub_mkconfig, '-o', grub_cfg_path) + with chroot.ChrootTarget(target) as inchroot: + stdout, _ = inchroot.execute(*cmd) + LOG.info('Generate efi grub config successfully: %s.', stdout) + + def _efi_grub_config_path(self, target): + binary_name = 'grub' + if os.path.exists(paths.target_path(target, 'usr/sbin/grub2-install')): + binary_name = 'grub2' + efi_grub_cfg_path = '/boot/%(binary_name)s/grub.cfg' % { + 'binary_name': binary_name} + return efi_grub_cfg_path + + def _configure_efi_boot_entry(self, root_device): + pass + + def _update_default_grub(self, target: str, grub_ttys: str): + grub_cmdline_linux = 'console=tty0 console=%s,115200n8 crashkernel=auto' % grub_ttys + LOG.info('Setting default grub biosedevname parameters: %s.', + grub_cmdline_linux) + default_grub_path = paths.target_path(target, '/etc/default/grub') + with open(default_grub_path, 'r') as g: + contents = g.read() + with open(default_grub_path, 'w') as g: + g.write( + re.sub(r'GRUB_CMDLINE_LINUX="(.*)"', + r'GRUB_CMDLINE_LINUX="%s"' % grub_cmdline_linux, + contents)) + + def _set_password_auth(self, target, status): + """Set password auth. + + parm: status: yes no + """ + path = paths.target_path(target, '/etc/ssh/sshd_config') + executor.execute('sed', '-i', '/PasswordAuthentication/d', path) + executor.execute('echo PasswordAuthentication %(status)s >> %(path)s' % { + 'status': status, 'path': path}, shell=True) + LOG.info('Set password auth %s', status) + + def _set_network_service(self, target): + pass + + def _parse_user_data(self, data): + return data + + def _parse_meta_data(self, data): + return data + + def _user_data_path(self): + return 'var/lib/cloud/seed/nocloud/user-data' + + def _network_path(self): + return 'var/lib/cloud/seed/nocloud/network-config' + + def _meta_data_path(self): + return 'var/lib/cloud/seed/nocloud/meta-data' + + def _vendor_data_path(self): + return 'var/lib/cloud/seed/nocloud/vendor-data' + + def _write_data_to_target(self, target, file_path, data): + absolute_file_path = paths.target_path(target, file_path) + file_dir = os.path.dirname(absolute_file_path) + system.ensure_dir(file_dir, 0o777) + if isinstance(data, (dict, list)): + data = json.dumps(data) + with open(absolute_file_path, 'w') as data_file: + data_file.write(data) + data_file.flush() + # Write the file from the buffer to the disk, + # otherwise it may result in the file not being written to the disk. + os.sync() + LOG.info("Write %s to %s", strutils.mask_password( + data), absolute_file_path) + + def set_cloudinit_conf(self, target, root_partition, ssh_pwauth, disable_root): + cloudinit_conf_path = 'etc/cloud/cloud.cfg' + absolute_cloudinit_conf_file_path = paths.target_path( + target, cloudinit_conf_path) + + cloudinit_conf_tpl_dir = system.get_relative_path('template/cloudinit') + + cloudinit_conf_tpl_file = self._get_cloudinit_conf_template_file() + cloudinit_conf_template_file_path = paths.target_path( + cloudinit_conf_tpl_dir, cloudinit_conf_tpl_file) + cloudinit_config = system.render_template( + cloudinit_conf_template_file_path, { + 'ssh_pwauth': ssh_pwauth, + 'disable_root': disable_root + }) + + with open(absolute_cloudinit_conf_file_path, 'w') as json_file: + json_file.write(cloudinit_config) + + LOG.info('Write %s to %s.', cloudinit_config, + absolute_cloudinit_conf_file_path) + self._enable_cloudinit_service(target) + self._remove_bonding_modules(target) + + def _enable_cloudinit_service(self, target): + with chroot.ChrootTarget(target) as inchroot: + inchroot.execute('systemctl', 'enable', 'cloud-init-local.service') + inchroot.execute('systemctl', 'enable', 'cloud-init.service') + inchroot.execute('systemctl', 'enable', 'cloud-config.service') + inchroot.execute('systemctl', 'enable', 'cloud-final.service') + LOG.info('Enable cloud service complete.') + + def _remove_bonding_modules(self, target): + etc_modules_path = paths.target_path(target, 'etc/modules') + if not os.path.exists(etc_modules_path): + LOG.info('Not exits /etc/modules.') + return + with chroot.ChrootTarget(target) as inchroot: + inchroot.execute('sed', '-i', '/bonding/d', '/etc/modules') + LOG.info('Remove bonding modules.') + + def _get_cloudinit_conf_template_file(self): + return 'cloud.tpl' + + def _parse_partitions(self, partitions): + for index, partition in enumerate(partitions): + old_options = partition.get('options') + fstype = partition['fs_type'] + new_options = self._fstype_options_handlers(fstype) + LOG.info('New options:%s', new_options) + options = utils.merge_list(old_options, new_options) + partitions[index]['options'] = options + return partitions + + def _apply_xfs_options(sef) -> tuple: + return None + + def _apply_swap_options(self) -> tuple: + return None + + def _fstype_options_handlers(self, fstype) -> tuple: + if fstype == 'xfs': + return self._apply_xfs_options() + elif fstype == 'swap': + return self._apply_swap_options() + return None diff --git a/bmp-agent/bmpa/osystem/factory.py b/bmp-agent/bmpa/osystem/factory.py new file mode 100644 index 0000000..60daa7e --- /dev/null +++ b/bmp-agent/bmpa/osystem/factory.py @@ -0,0 +1,51 @@ +import re + +from bmpa.osystem.centos import CentOS7X +from bmpa.osystem.centos import CentOS8X +from bmpa.osystem.debian import Debian10x +from bmpa.osystem.default import DefaultOsystem +from bmpa.osystem.kylin import Kylin10X +from bmpa.osystem.loongnix import Loongnix8X +from bmpa.osystem.openEuler import OpenEuler20X +from bmpa.osystem.ubuntu import Ubuntu18X +from bmpa.osystem.ubuntu import Ubuntu20X +from bmpa.osystem.uniontech import UnionTech20X +from bmpa.osystem.windows import Windows10 +from bmpa.osystem.windows import Windows2012 +from bmpa.osystem.windows import Windows2016 +from bmpa.osystem.windows import Windows2019 + + +def get_osystem(os_type, os_version): + return _get_osystem(os_type, os_version) + + +def _get_osystem(os_type, os_version): + if os_type.lower() == "centos": + if re.compile(r"7\.*").match(os_version): + return CentOS7X() + return CentOS8X() + elif os_type.lower() == "ubuntu": + if re.compile(r"18\.*").match(os_version): + return Ubuntu18X() + return Ubuntu20X() + elif os_type.lower() == "kylin": + return Kylin10X() + elif os_type.lower() == "openeuler": + return OpenEuler20X() + elif os_type.lower() == "uniontech": + return UnionTech20X() + elif os_type.lower() == "debian": + return Debian10x() + elif os_type.lower() == "loongnix": + return Loongnix8X() + elif os_type.lower() == "windowspc": + return Windows10() + elif os_type.lower() == "windows": + if re.compile(r"2012").match(os_version): + return Windows2012() + elif re.compile(r"2016").match(os_version): + return Windows2016() + return Windows2019() + + return DefaultOsystem() diff --git a/bmp-agent/bmpa/osystem/kylin.py b/bmp-agent/bmpa/osystem/kylin.py new file mode 100644 index 0000000..a62de22 --- /dev/null +++ b/bmp-agent/bmpa/osystem/kylin.py @@ -0,0 +1,6 @@ +from bmpa.osystem.default import DefaultOsystem + + +class Kylin10X(DefaultOsystem): + def _distro(self): + return 'kylin' diff --git a/bmp-agent/bmpa/osystem/loongnix.py b/bmp-agent/bmpa/osystem/loongnix.py new file mode 100644 index 0000000..8bb44e5 --- /dev/null +++ b/bmp-agent/bmpa/osystem/loongnix.py @@ -0,0 +1,28 @@ +from bmpa import constants +from bmpa.osystem.default import DefaultOsystem +from bmpa.utils import executor + + +class Loongnix8X(DefaultOsystem): + def _distro(self): + return 'loongnix-server' + + def _install_grub_to_device(self, target, root_device): + # grub2-install has added UEFI Secure Boot verification, causing an error. + # We now utilize the corresponding modules from the image, eliminating the need for grub2-install. + pass + + def _kernel_install(self, target): + super(Loongnix8X, self)._kernel_install_execute(target) + + def _configure_efi_boot_entry(self, root_device): + super(Loongnix8X, self)._delete_efi_boot(constants.EFIBOOTMGR_LABEL) + distro = self._distro() + efi_file = '"\EFI\%(distro)s\BOOTLOONGARCH64.efi"' % {'distro': distro} + cmd = ('efibootmgr', '-c', '-w', '-L', constants.EFIBOOTMGR_LABEL, '-d', root_device, '-p', '1', + '--write-signature', '-l', efi_file) + executor.execute(*cmd) + + def _efi_grub_config_path(self, target): + distro = self._distro() + return '/boot/efi/EFI/%s/grub.cfg' % distro diff --git a/bmp-agent/bmpa/osystem/openEuler.py b/bmp-agent/bmpa/osystem/openEuler.py new file mode 100644 index 0000000..d4dc109 --- /dev/null +++ b/bmp-agent/bmpa/osystem/openEuler.py @@ -0,0 +1,9 @@ +from bmpa.osystem.default import DefaultOsystem + + +class OpenEuler20X(DefaultOsystem): + def _distro(self): + return 'openEuler' + + def _kernel_install(self, target): + super(OpenEuler20X, self)._kernel_install_execute(target) diff --git a/bmp-agent/bmpa/osystem/ubuntu.py b/bmp-agent/bmpa/osystem/ubuntu.py new file mode 100644 index 0000000..70a8b99 --- /dev/null +++ b/bmp-agent/bmpa/osystem/ubuntu.py @@ -0,0 +1,40 @@ +import logging +import platform + +from bmpa import constants +from bmpa.errors import BmpError +from bmpa.osystem.default import DefaultOsystem +from bmpa.utils import chroot +from bmpa.utils.executor import ProcessExecutionError + +LOG = logging.getLogger(__name__) + + +class Ubuntu18X(DefaultOsystem): + def _distro(self): + return 'ubuntu' + + def _get_cloudinit_conf_template_file(self): + return "cloud_ubuntu.tpl" + + def _update_initramfs(self, target): + cmd = ('update-initramfs', '-u') + try: + with chroot.ChrootTarget(target) as inchroot: + inchroot.execute(*cmd) + except ProcessExecutionError as e: + error_msg = ('repair initram fs' + 'failed with %(err)s' % { + 'err': e + }) + LOG.error(error_msg) + raise BmpError(error_msg) + + def _apply_swap_options(self): + if platform.machine() == constants.MACHINE_AARCH64: + return ('-p', '4096') + return None + + +class Ubuntu20X(Ubuntu18X): + pass diff --git a/bmp-agent/bmpa/osystem/uniontech.py b/bmp-agent/bmpa/osystem/uniontech.py new file mode 100644 index 0000000..d9d061c --- /dev/null +++ b/bmp-agent/bmpa/osystem/uniontech.py @@ -0,0 +1,16 @@ +import platform + +from bmpa import constants +from bmpa.osystem.default import DefaultOsystem + + +class UnionTech20X(DefaultOsystem): + def _distro(self): + if platform.machine() == constants.MACHINE_AARCH64: + return 'UnionTech' + return 'uos' + + def _efi_grub_config_path(self, target): + if platform.machine() == constants.MACHINE_AARCH64: + return super(UnionTech20X, self)._efi_grub_config_path(target) + return '/boot/efi/EFI/%s/grub.cfg' % self._distro() diff --git a/bmp-agent/bmpa/osystem/windows.py b/bmp-agent/bmpa/osystem/windows.py new file mode 100644 index 0000000..8a5a3c3 --- /dev/null +++ b/bmp-agent/bmpa/osystem/windows.py @@ -0,0 +1,92 @@ +import logging + +from bmpa import constants +from bmpa.osystem.default import DefaultOsystem +from bmpa.utils import mountutils +from bmpa.utils import paths +from bmpa.utils import system + +LOG = logging.getLogger(__name__) + + +class WindowsBase(DefaultOsystem): + def _root_lable(self): + return constants.WINDOWS_ROOT_LABEL + + def set_password(self, target, root_partition, password, username='Administrator'): + with mountutils.mount(root_partition, target, ['-t', 'ntfs']): + passworddata_dict = dict() + if username == 'root': + username = 'Administrator' + passworddata_dict["name"] = username + passworddata_dict["admin_pass"] = password + path = 'Program Files/Cloudbase Solutions/Cloudbase-Init/openstack/latest/password_data.json' + super(WindowsBase, self)._write_data_to_target( + target=target, file_path=path, data=passworddata_dict) + + def set_meta_data(self, target, root_partition, data): + with mountutils.mount(root_partition, target, ['-t', 'ntfs']): + super(WindowsBase, self).set_meta_data( + target, root_partition, data) + + def set_user_data(self, target, root_partition, data): + with mountutils.mount(root_partition, target, ['-t', 'ntfs']): + super(WindowsBase, self).set_user_data( + target, root_partition, data) + + def set_network(self, target, root_partition, data): + with mountutils.mount(root_partition, target, ['-t', 'ntfs']): + super(WindowsBase, self).set_network(target, root_partition, data) + + def _user_data_path(self): + return 'Program Files/Cloudbase Solutions/Cloudbase-Init/openstack/latest/user_data' + + def _meta_data_path(self): + return 'Program Files/Cloudbase Solutions/Cloudbase-Init/openstack/latest/meta_data.json' + + def _network_path(self): + return 'Program Files/Cloudbase Solutions/Cloudbase-Init/openstack/latest/network_data.json' + + def _parse_meta_data(self, data): + if 'local-hostname' in data: + data['hostname'] = data.pop('local-hostname') + if 'instance-id' in data: + data['uuid'] = data.pop('instance-id') + return data + + def set_cloudbase_conf(self, target, root_partition, only_set_network=False): + with mountutils.mount(root_partition, target, ['-t', 'ntfs']): + cloudbase_conf_path = 'Program Files/Cloudbase Solutions/Cloudbase-Init/conf/cloudbase-init.conf' + absolute_cloudbase_conf_file_path = paths.target_path( + target, cloudbase_conf_path) + + cloudinit_conf_template_file_path = system.get_relative_path( + "template/cloudinit/cloudbase-init.tpl") + cloudbase_config = system.render_template( + cloudinit_conf_template_file_path, + {"only_set_network": only_set_network}) + + with open(absolute_cloudbase_conf_file_path, 'w') as json_file: + json_file.write(cloudbase_config) + + LOG.info("Write %s to %s", cloudbase_config, + absolute_cloudbase_conf_file_path) + + def set_cloudinit_conf(self, target, root_partition, ssh_pwauth, disable_root): + pass + + +class Windows10(WindowsBase): + pass + + +class Windows2012(WindowsBase): + pass + + +class Windows2016(Windows2012): + pass + + +class Windows2019(Windows2016): + pass diff --git a/bmp-agent/bmpa/protocol/__init__.py b/bmp-agent/bmpa/protocol/__init__.py new file mode 100755 index 0000000..b1f0a9d --- /dev/null +++ b/bmp-agent/bmpa/protocol/__init__.py @@ -0,0 +1,23 @@ +from abc import ABC, abstractmethod + +from bmpa.command.common import Command + + +class BaseProtocol(ABC): + + @abstractmethod + def send_command(self, command: Command): + raise NotImplementedError() + + @abstractmethod + def receive_command(self, command: str): + raise NotImplementedError() + + +class Protocol(BaseProtocol): + + def start(): + pass + + def stop(self): + pass diff --git a/bmp-agent/bmpa/protocol/rabbitmq.py b/bmp-agent/bmpa/protocol/rabbitmq.py new file mode 100644 index 0000000..dad188a --- /dev/null +++ b/bmp-agent/bmpa/protocol/rabbitmq.py @@ -0,0 +1,65 @@ +import logging +import threading + +from bmpa.client.rabbitmq import Consumer +from bmpa.client.rabbitmq import Publisher +from bmpa.command import command_service +from bmpa.command.common import Command +from bmpa.command.common import Heart +from bmpa.protocol import Protocol +from bmpa.serialize import DefaultJsonEncoder +from bmpa.service import node +from bmpa.utils import validates + +LOG = logging.getLogger(__name__) + + +class RabbitmqProtocol(Protocol): + + def __init__(self): + self.consumer = Consumer() + self.publisher = Publisher() + self.encoder = DefaultJsonEncoder() + + def start(self): + __consumer_thread = threading.Thread(name='ConsumerThread', + target=self._start_consumer, + daemon=True) + + __consumer_thread.start() + self._start_publisher() + + def stop(self): + self.consumer.stop() + + def send_command(self, command: Command): + message = self.encoder.encode(command.serialize()) + LOG.info("Send command: %s", message) + self.publisher.publish_message(message) + + def receive_command(self): + LOG.info('Receive command.') + message = self.consumer.get_message() + if message is not None: + command_service.receive_command(message) + + def _is_connect(self): + return self.publisher.is_connect() + + def heartbeat(self): + if self._is_connect(): + heart = Heart(sn=node.get_serial_number()) + self.send_command(heart) + else: + LOG.warning("RabbitMQ is not connect, not send heartbeat.") + + def _start_consumer(self): + queue_name = node.get_serial_number() + validates.is_required(queue_name, 'queu name') + LOG.info("Comsumer qeue name %s.", queue_name) + self.consumer.init(queue_name) + self.consumer.start() + + def _start_publisher(self): + self.publisher.init() + self.publisher.start() diff --git a/bmp-agent/bmpa/raid/__init__.py b/bmp-agent/bmpa/raid/__init__.py new file mode 100644 index 0000000..74b23f7 --- /dev/null +++ b/bmp-agent/bmpa/raid/__init__.py @@ -0,0 +1,70 @@ +import logging + +from bmpa.errors import IncompatibleHardwareMethodError + +LOG = logging.getLogger(__name__) + +RAID_INDEX = { + "RAID0": "0", + "RAID1": "1", + "RAID5": "5", + "RAID10": "10" +} + + +class BaseRaid(object): + + root_device = None + + def execute_raid_config(self, config): + raid_level = config.raid_level.lower() + if raid_level == 'noraid': + return self.noraid(config) + elif raid_level == 'raid0': + return self.raid0(config) + elif raid_level == 'raid1': + return self.raid1(config) + elif raid_level == 'raid5': + return self.raid5(config) + elif raid_level == 'raid10': + return self.raid10(config) + else: + raise ValueError(f'Unsupported RAID level: {raid_level}') + + def list_adapter(self): + """Get adapters info. + + """ + return None + + def get_adapter_ids(self): + raise IncompatibleHardwareMethodError( + 'Not support get adapter ids method.') + + def display(self, adapter_id: int = 0): + """Get physical disks. + + """ + return None + + def get_disks(self, adapter_id: str = '0'): + raise IncompatibleHardwareMethodError('Not support get disk method.') + + def noraid(self, config): + raise IncompatibleHardwareMethodError('Not support NORAID type.') + + def raid0(self, config): + raise IncompatibleHardwareMethodError('Not support RAID0 type.') + + def raid1(self, config): + raise IncompatibleHardwareMethodError('Not support RAID1 type.') + + def raid5(self, config): + raise IncompatibleHardwareMethodError('Not support RAID5 type.') + + def raid10(self, config): + raise IncompatibleHardwareMethodError('Not support RAID10 type.') + + def clean_raid(self, adapter_id: str = '0', delay_time=0): + raise IncompatibleHardwareMethodError( + 'Not support clean raid config method.') diff --git a/bmp-agent/bmpa/raid/arcconf.py b/bmp-agent/bmpa/raid/arcconf.py new file mode 100755 index 0000000..75a54eb --- /dev/null +++ b/bmp-agent/bmpa/raid/arcconf.py @@ -0,0 +1,136 @@ +import logging +import re +import time + +from bmpa.errors import BmpError, IncompatibleHardwareMethodError +from bmpa.model.disk import Disk +from bmpa.raid import BaseRaid, RAID_INDEX +from bmpa.utils import executor + +LOG = logging.getLogger(__name__) + +EXECUTABLE_FILE = '/usr/sbin/arcconf' + + +class Arcconf(BaseRaid): + + def list_adapter(self): + cmd = (EXECUTABLE_FILE, 'list') + stdout, stderr = executor.execute(*cmd) + if stderr: + raise BmpError('Excute list adapter error:%s', stderr) + LOG.info('List adapter operation : %s.', stdout) + return stdout + + def get_adapter_ids(self): + stdout = self.list_adapter() + if stdout: + pattern = r"\s+Controller\s+(\d+):" + pattern_object = re.compile(pattern, re.MULTILINE) + adapter_ids = [] + for m in pattern_object.finditer(stdout): + adapter_ids.append(m.group(1)) + if len(adapter_ids) > 0: + return adapter_ids + + raise BmpError('Get addapter ids error.') + + def display(self, adapter_id=0): + cmd = (EXECUTABLE_FILE, "GETCONFIG", adapter_id) + stdout, stderr = executor.execute(*cmd) + if stderr: + raise BmpError('Excute display error:%s', stderr) + LOG.info('Display raid adapter %s ', adapter_id) + return stdout + + def get_disks(self, adapter_id: str = '0'): + stdout = self.display(adapter_id) + if stdout: + LOG.debug('Display out:%s.', stdout) + return self._parse_disk(stdout) + return BmpError('Get disks error.') + + def noraid(self, config): + # only list adapter + self.list_adapter() + + def raid0(self, config): + raid_index = self._get_raid_index(config.raid_level) + adapter_id = config.adapter_id + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid1(self, config): + raid_index = self._get_raid_index(config.raid_level) + adapter_id = config.adapter_id + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid5(self, config): + raid_index = self._get_raid_index(config.raid_level) + adapter_id = config.adapter_id + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid10(self, config): + raid_index = self._get_raid_index(config.raid_level) + adapter_id = config.adapter_id + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def clean_raid(self, adapter_id: str = '0', delay_time=0): + time.sleep(30) + cmd = (EXECUTABLE_FILE, "delete", adapter_id, "array", "all", + "noprompt") + stdout = "" + stderr = "" + try: + stdout, stderr = executor.execute(*cmd) + except Exception as e: + if "No arrays configured" not in str(e): + raise e + + LOG.info('Delete %s operation : %s : %s.', adapter_id, stdout, + stderr) + time.sleep(delay_time) + + def _parse_disk(self, stdout): + LOG.info(stdout) + disks = [] + pattern = re.compile( + r'\s+Transfer Speed\s+:\s+(?P\S+).*?' + r'\s+Reported Channel,Device\S+\s+:\s+(?P\d+),(?P\d+).*?' + r'\s+Total\s+Size\s+:\s+(?P\d+)\s+(?P.*?[M|T|G]B).*?' + r'\s+SSD\s+:\s+(?P\S+).*?', re.DOTALL) + for match in re.finditer(pattern, stdout): + enclosure = int(match.group('enclosure').strip()) + slot = int(match.group('slot').strip()) + pd_type = match.group('pd_type').strip() + size = float(match.group('size').strip()) + size_unit = match.group('size_unit').strip() + is_ssd = match.group('is_ssd').strip() + media_type = "HDD" if is_ssd == "No" else "SSD" + disks.append( + Disk(enclosure=enclosure, + slot=slot, + pd_type=pd_type, + media_type=media_type, + size=size, + size_unit=size_unit).__dict__) + return disks + + def _get_raid_index(self, raid_level): + raid_index = RAID_INDEX.get(raid_level) + if not raid_index: + raise IncompatibleHardwareMethodError('Not support raid level %s.' % + raid_level) + return raid_index + + def _execute_raid(self, adapter_id, raid_index, disk_location, other_param=''): + cmd = ((EXECUTABLE_FILE, "create", adapter_id, "logicaldrive", "max", + raid_index) + tuple(disk_location) + ("noprompt", )) + stdout, stderr = executor.execute(*cmd) + LOG.info('Create %s raid%s : %s', raid_index, stdout, stderr) + + def _parse_physical_disks(self, physical_disks): + return tuple(item for disk in physical_disks for item in (disk["enclosure"], disk["slot"])) diff --git a/bmp-agent/bmpa/raid/factory.py b/bmp-agent/bmpa/raid/factory.py new file mode 100644 index 0000000..80678ed --- /dev/null +++ b/bmp-agent/bmpa/raid/factory.py @@ -0,0 +1,40 @@ +import logging + +from bmpa.raid.arcconf import Arcconf +from bmpa.raid.megacli64 import MegaCli64 +from bmpa.raid.no_raid import NoRaid +from bmpa.raid.perccli64 import Perccli64 +from bmpa.raid.sas2ircu import Sas2ircu +from bmpa.raid.sas3ircu import Sas3ircu +from bmpa.raid.storcli64 import Storcli64 + +LOG = logging.getLogger(__name__) + +RAID_MAPS = {'storcli64': Storcli64, 'megacli64': MegaCli64, + 'perccli64': Perccli64, 'sas3ircu': Sas3ircu, + 'sas2ircu': Sas2ircu, 'arcconf': Arcconf, 'no_raid': NoRaid} +RAIDS = [Sas3ircu, Sas2ircu, Arcconf, Storcli64, MegaCli64, Perccli64, NoRaid] + + +def get_raid_driver(raid_driver: str = None): + if raid_driver: + raid_driver = raid_driver.lower() + LOG.info('Raid driver:%s.', raid_driver) + if raid_driver in RAID_MAPS.keys(): + LOG.info('Raid driver:%s in map.', raid_driver) + return RAID_MAPS.get(raid_driver)() + return _guess_raid_driver() + + +def _guess_raid_driver(): + LOG.info('Guess raid dirver.') + for raid_driver in RAIDS: + try: + driver = raid_driver() + driver.get_adapter_ids() + except Exception as e: + LOG.info('%s can not get raid adapter:%s.', + raid_driver.__name__, str(e)) + else: + return driver + return NoRaid() diff --git a/bmp-agent/bmpa/raid/megacli64.py b/bmp-agent/bmpa/raid/megacli64.py new file mode 100644 index 0000000..fec5aa3 --- /dev/null +++ b/bmp-agent/bmpa/raid/megacli64.py @@ -0,0 +1,205 @@ +import logging +import re +import time + +from bmpa.errors import BmpError, IncompatibleHardwareMethodError +from bmpa.raid import BaseRaid, RAID_INDEX +from bmpa.model.disk import Disk +from bmpa.utils import executor +from bmpa.utils import strutils + +LOG = logging.getLogger(__name__) + +EXECUTABLE_FILE = '/usr/sbin/MegaCli64' + + +class MegaCli64(BaseRaid): + + def list_adapter(self): + cmd = (EXECUTABLE_FILE, '-AdpGetPciInfo', '-aAll') + stdout, stderr = executor.execute(*cmd) + if stderr: + raise BmpError('Excute list adapter error:%s', stderr) + LOG.info('List adapter operation : %s.', stdout) + return stdout + + def get_adapter_ids(self): + stdout = self.list_adapter() + adapter_ids = [] + if stdout: + pattern = re.compile( + r'PCI\sinformation\sfor\sController\s+(?P\d+)\s?') + for match in re.finditer(pattern, stdout): + adapter_ids.append(match.group('adapter_id')) + if len(adapter_ids) == 0: + raise BmpError('Get addapter ids error.') + + return adapter_ids + + def display(self, adapter_id: str = '0'): + cmd = (EXECUTABLE_FILE, '-PDList', '-a%s' % adapter_id) + stdout, stderr = executor.execute(*cmd) + if stderr: + raise BmpError('Excute display error:%s', stderr) + LOG.info('Display raid adapter %s ', adapter_id) + return stdout + + def get_disks(self, adapter_id: str = '0'): + stdout = self.display(adapter_id) + if stdout: + LOG.debug('Display out:%s.', stdout) + return self._parse_disk(stdout) + return BmpError('Get disks error.') + + def noraid(self, config): + self._close_jbod_mode() + adapter_id = config.adapter_id + raid_index = self._get_raid_index('RAID0') + for disk_location in config.physical_disks: + disk_location = self._parse_physical_disks([disk_location]) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid0(self, config): + self._close_jbod_mode() + adapter_id = config.adapter_id + raid_index = self._get_raid_index(config.raid_level) + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid1(self, config): + self._close_jbod_mode() + adapter_id = config.adapter_id + raid_index = self._get_raid_index(config.raid_level) + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid5(self, config): + self._close_jbod_mode() + adapter_id = config.adapter_id + raid_index = self._get_raid_index(config.raid_level) + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid10(self, config): + self._close_jbod_mode() + adapter_id = config.adapter_id + raid_index = self._get_raid_index(config.raid_level) + disk_location = self._parse_raid10_physical_disks( + config.physical_disks) + cmd = (EXECUTABLE_FILE, '-CfgSpanAdd', '-r10', + disk_location, 'WB', 'Direct', 'CachedBadBBU', '-a', + adapter_id) + stdout, stderr = executor.execute(*cmd) + LOG.info('Create %s raid%s : %s', raid_index, stdout, stderr) + + def clean_raid(self, adapter_id: str = '0', delay_time=0): + self._close_jbod_mode() + self._delete_raid_mode(adapter_id) + time.sleep(delay_time) + + def _get_raid_index(self, raid_level): + raid_index = RAID_INDEX.get(raid_level) + if not raid_index: + raise IncompatibleHardwareMethodError('Not support raid level %s.' % + raid_level) + return raid_index + + def _execute_raid(self, adapter_id, raid_index, disk_location, other_param=''): + cmd = (EXECUTABLE_FILE, '-CfgLdAdd', '-r%s' % raid_index, + disk_location, 'WB', 'Direct', 'CachedBadBBU', '-a', + adapter_id, other_param) + stdout, stderr = executor.execute(*cmd) + LOG.info('Create %s raid%s : %s', raid_index, stdout, stderr) + + def _parse_physical_disks(self, physical_disks): + disk_strings = [ + f"{disk['enclosure']}:{disk['slot']}" for disk in physical_disks] + return '[%s]' % ', '.join(disk_strings) + + def _parse_raid10_physical_disks(self, physical_disks): + """Parse raid10 param + + return like "-Array0 [65:2,65:3,65:4,65:5] -Array1 [65:6,65:7,65:8,65:9]" + """ + if len(physical_disks) % 2 != 0: + raise BmpError('Raid10 disk location must be 2X.') + + disk_location_groups = [] + # For arrays with 8 disks or fewer, the default value of pdperarray=2 can achieve maximum performance. + # For arrays with more than 8 disks, setting pdperarray=4 can achieve maximum performance. + if len(physical_disks) % 4 == 0 and len(physical_disks) > 8: + pdperarray_num = 4 + else: + pdperarray_num = 2 + pdperarray = [] + for index, disk in enumerate(physical_disks, 1): + pdperarray.append(f"{disk['enclosure']}:{disk['slot']}") + if index % pdperarray_num == 0: + disk_location_groups.append(pdperarray) + pdperarray = [] + + disk_location_arrays = [] + for index, dl in enumerate(disk_location_groups): + disk_location_arrays.append('-Array%d' % index) + disk_location_arrays.append('[%s]' % (','.join(dl))) + + return ' '.join(disk_location_arrays) + + def _parse_disk(self, stdout): + disks = [] + pattern = re.compile( + r'Enclosure\sDevice\sID:\s+(?P\d+).*?' + r'Slot Number:\s+(?P\d+).*?' + r'PD Type:\s+(?P\S+).*?' + r'Raw\sSize:\s+(?P\d+\.\d+)\s+(?P.*?[M|T|G]B).*?' + r'Coerced\sSize:\s+(?P\d+\.\d+)\s+(?P.*?[M|T|G]B).*?' + r'Device Firmware\sLevel:\s*(?P\S+).*?' + r'Inquiry Data:\s*(?P[^\n]+).*?' + r'Media Type:\s+(?P[^\n]+).*?', re.DOTALL) + for match in re.finditer(pattern, stdout): + enclosure = int(match.group('enclosure')) + slot = int(match.group('slot')) + pd_type = match.group('pd_type').strip() + raw_size = float(match.group('raw_size')) + raw_size_unit = match.group('raw_size_unit') + size = float(match.group('core_size')) + size_unit = match.group('core_size_unit') + inquiry_data = match.group('inquiry_data').strip() + device_firware_level = match.group('device_firware_level').strip() + media_type = strutils.get_initials( + match.group('media_type').strip()) + disks.append( + Disk(enclosure=enclosure, + slot=slot, + pd_type=pd_type, + raw_size=raw_size, + raw_size_unit=raw_size_unit, + size=size, + size_unit=size_unit, + inquiry_data=inquiry_data, + media_type=media_type, + device_firware_level=device_firware_level).__dict__) + return disks + + def _close_jbod_mode(self): + try: + # close JBOD mode + cmd = (EXECUTABLE_FILE, '-AdpSetProp', '-EnableJBOD', '-0', + '-aALL') + stdout, stderr = executor.execute(*cmd) + LOG.info('Close raid adapter JBOD mode : %s : %s.', stdout, + stderr) + except Exception as e: + LOG.warn('Close raid adapter JBOD mode error: %s.', str(e)) + + def _delete_raid_mode(self, adapter_id: str): + # clean old raid info + cmd = (EXECUTABLE_FILE, '-CfgLdDel', '-Lall', 'force', '-aALL') + stdout, stderr = executor.execute(*cmd) + LOG.info('Delete raid adapter old raid mode : %s : %s.', stdout, + stderr) + + cmd = (EXECUTABLE_FILE, '-CfgForeign', '-Clear', '-a%s' % adapter_id) + stdout, stderr = executor.execute(*cmd) + LOG.info('Clean raid adapter old raid mode : %s : %s.', stdout, + stderr) diff --git a/bmp-agent/bmpa/raid/no_raid.py b/bmp-agent/bmpa/raid/no_raid.py new file mode 100644 index 0000000..5201a75 --- /dev/null +++ b/bmp-agent/bmpa/raid/no_raid.py @@ -0,0 +1,37 @@ +import logging + +from bmpa.raid import BaseRaid + +LOG = logging.getLogger(__name__) + + +class NoRaid(BaseRaid): + + def __init__(self, **kwargs): + super(NoRaid, self).__init__(**kwargs) + + def get_disks(self, adapter_id: str = '0'): + LOG.warn('No raid adapter.') + return None + + def get_adapter_ids(self): + LOG.warn('Nothing operation to do.') + return None + + def noraid(self, config): + LOG.warn('Nothing raid operation to do.') + + def raid0(self, config): + LOG.warn('Nothing raid operation to do.') + + def raid1(self, config): + LOG.warn('Nothing raid operation to do.') + + def raid5(self, config): + LOG.warn('Nothing raid operation to do.') + + def raid10(self, config): + LOG.warn('Nothing raid operation to do.') + + def clean_raid(self, adapter_id: str = '0', delay_time=0): + LOG.warn('Nothing raid operation to do.') diff --git a/bmp-agent/bmpa/raid/perccli64.py b/bmp-agent/bmpa/raid/perccli64.py new file mode 100755 index 0000000..5f1daff --- /dev/null +++ b/bmp-agent/bmpa/raid/perccli64.py @@ -0,0 +1,153 @@ +import json +import logging +import time + +from bmpa.errors import BmpError, IncompatibleHardwareMethodError +from bmpa.model.disk import Disk +from bmpa.raid import BaseRaid, RAID_INDEX +from bmpa.utils import executor +from bmpa.utils.executor import ProcessExecutionError + + +LOG = logging.getLogger(__name__) + +EXECUTABLE_FILE = '/usr/sbin/perccli64' + + +class Perccli64(BaseRaid): + + def list_adapter(self, param='J'): + cmd = (EXECUTABLE_FILE, '/call show %(param)s' % {'param': param}) + stdout, stderr = executor.execute(*cmd) + if stderr: + raise BmpError('Excute list adapter error:%s', stderr) + LOG.info('List adapter operation : %s.', stdout) + return stdout + + def get_adapter_ids(self): + stdout = self.list_adapter() + adapter_ids = [] + if stdout: + adapter_ids = [] + json_out = json.loads(stdout) + for item in json_out['Controllers']: + adapter_ids.append(item['Command Status']['Controller']) + if len(adapter_ids) == 0: + raise BmpError('Get addapter ids error.') + + return adapter_ids + + def display(self, adapter_id=0, param='J'): + cmd = (EXECUTABLE_FILE, '/c%(adapter_id)s show %(param)s' % { + 'adapter_id': adapter_id, + 'param': param + }) + stdout, stderr = executor.execute(*cmd) + if stderr: + raise BmpError('Excute display error:%s', stderr) + LOG.info('Display raid adapter %s ', adapter_id) + return stdout + + def get_disks(self, adapter_id: str = '0'): + stdout = self.display(adapter_id) + if stdout: + LOG.debug('Display out:%s.', stdout) + return self._parse_disk(stdout) + return BmpError('Get disks error.') + + def noraid(self, config): + self._close_jbod_mode() + raid_level = config.raid_level + raid_index = RAID_INDEX.get('RAID0') + if not raid_index: + raise IncompatibleHardwareMethodError('Not support raid level %s.' % + raid_level) + for disk_location in config.physical_disks: + disk_location = self._parse_physical_disks([disk_location]) + cmd = (EXECUTABLE_FILE, '/c%s' % config.adapter_id, 'add', 'vd', + 'r%s' % raid_index, 'drives=%s' % disk_location) + stdout, stderr = executor.execute(*cmd) + LOG.info('Create %s raid : %s : %s.', raid_level, stdout, + stderr) + + def raid0(self, config): + self._execute_raid(config) + + def raid1(self, config): + self._execute_raid(config) + + def raid5(self, config): + self._execute_raid(config) + + def raid10(self, config): + pdperarray = self._pdperarray(config.physical_disks) + self._execute_raid(config, pdperarray) + + def clean_raid(self, adapter_id: str = '0', delay_time=0): + cmd = (EXECUTABLE_FILE, '/c%s/vall' % adapter_id, 'delete', + 'force') + try: + stdout, stderr = executor.execute(*cmd) + except ProcessExecutionError as e: + if 'No VD' not in e.stdout: + error_msg = ('clean raid config' + 'failed with %(err)s' % { + 'err': str(e) + }) + raise BmpError('Clean raid error:%s.' % error_msg) + else: + if 'syntax error' in stdout: + raise BmpError('Clean raid error:%s.' % stdout) + LOG.info('Delete %s operation : %s : %s', adapter_id, + stdout, stderr) + time.sleep(delay_time) + + def _parse_disk(self, stdout): + disks = [] + json_out = json.loads(stdout) + for item in json_out['Controllers'][0]['Response Data']['PD LIST']: + slot = int(item['EID:Slt'].split(':')[1]) + enclosure = int(item['EID:Slt'].split(':')[0]) + size = float(item['Size'].split(' ')[0]) + size_unit = item['Size'].split(' ')[1] + pd_type = item['Intf'] + media_type = item['Med'] + disks.append( + Disk(enclosure=enclosure, + slot=slot, + pd_type=pd_type, + media_type=media_type, + size=size, + size_unit=size_unit).__dict__) + return disks + + def _pdperarray(self, physical_disks): + if len(physical_disks) % 2 != 0: + raise BmpError('Raid10 disk location must be 2X.') + pdperarray_num = 2 + if len(physical_disks) % 4 == 0 and len(physical_disks) > 8: + pdperarray_num = 4 + return pdperarray_num + + def _execute_raid(self, config, pdperarray=None): + raid_level = config.raid_level + raid_index = RAID_INDEX.get(raid_level) + if not raid_index: + raise IncompatibleHardwareMethodError('Not support raid level %s.' % + raid_level) + disk_location = self._parse_physical_disks(config.physical_disks) + cmd = (EXECUTABLE_FILE, '-CfgLdAdd', '-r%s' % raid_index, + disk_location, 'WB', 'Direct', 'CachedBadBBU', '-a', + config.adapter_id) + pd = '' + if pdperarray is not None: + pd = 'pdperarray=%s' % pdperarray + cmd = (EXECUTABLE_FILE, '/c%s' % config.adapter_id, 'add', 'vd', + 'r%s' % raid_index, 'drives=%s' % disk_location, pd) + stdout, stderr = executor.execute(*cmd) + LOG.info('Create %s raid : %s : %s', raid_level, stdout, stderr) + + def _parse_physical_disks(self, physical_disks): + disk_strings = [ + f"{disk['enclosure']}:{disk['slot']}" for disk in physical_disks] + return '%s' % ', '.join(disk_strings) diff --git a/bmp-agent/bmpa/raid/sas2ircu.py b/bmp-agent/bmpa/raid/sas2ircu.py new file mode 100755 index 0000000..99b55ad --- /dev/null +++ b/bmp-agent/bmpa/raid/sas2ircu.py @@ -0,0 +1,150 @@ +import logging +import re +import time + +from bmpa.errors import BmpError, IncompatibleHardwareMethodError +from bmpa.model.disk import Disk +from bmpa.raid import BaseRaid, RAID_INDEX +from bmpa.utils import executor + +LOG = logging.getLogger(__name__) + +EXECUTABLE_FILE = '/usr/sbin/sas2ircu' + + +class Sas2ircu(BaseRaid): + + def list_adapter(self): + """Avago Technologies SAS2 IR Configuration Utility. + + Version 13.00.00.00 (2016.03.08) + Copyright (c) 2009-2016 Avago Technologies. All rights reserved. + + + Adapter Vendor Device SubSys SubSys + Index Type ID ID Pci Address Ven ID Dev ID + ----- ------------ ------ ------ ----------------- ------ ------ + 0 SAS2008 1000h 97h 00h:01h:00h:00h 1000h 3090h + SAS3IRCU: Utility Completed Successfully. + """ + cmd = (EXECUTABLE_FILE, 'list') + stdout, stderr = executor.execute(*cmd) + if stderr: + raise BmpError('Excute list adapter error:%s', stderr) + LOG.info('List adapter operation : %s.', stdout) + return stdout + + def get_adapter_ids(self): + stdout = self.list_adapter() + if stdout: + pattern = r'\s+(\d+)\s+SAS2008' + pattern_object = re.compile(pattern, re.MULTILINE) + adapter_ids = [] + for m in pattern_object.finditer(stdout): + adapter_ids.append(m.group(1)) + if len(adapter_ids) > 0: + return adapter_ids + + raise BmpError('Get addapter ids error.') + + def display(self, adapter_id=0): + cmd = (EXECUTABLE_FILE, adapter_id, 'display') + stdout, stderr = executor.execute(*cmd) + if stderr: + raise BmpError('Excute display error:%s', stderr) + LOG.info('Display raid adapter %s ', adapter_id) + return stdout + + def get_disks(self, adapter_id: str = '0'): + stdout = self.display(adapter_id) + if stdout: + LOG.debug('Display out:%s.', stdout) + return self._parse_disk(stdout) + return BmpError('Get disks error.') + + def noraid(self, config): + # only list adapter + self.list_adapter() + + def raid0(self, config): + raid_index = self._get_raid_index(config.raid_level) + adapter_id = config.adapter_id + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid1(self, config): + raid_index = self._get_raid_index(config.raid_level) + adapter_id = config.adapter_id + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid5(self, config): + raid_index = self._get_raid_index(config.raid_level) + adapter_id = config.adapter_id + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid10(self, config): + raid_index = self._get_raid_index(config.raid_level) + adapter_id = config.adapter_id + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def clean_raid(self, adapter_id: str = '0', delay_time=0): + time.sleep(30) + cmd = (EXECUTABLE_FILE, adapter_id, 'delete', 'noprompt') + stdout, stderr = executor.execute(*cmd) + LOG.info('Delete %s operation : %s : %s.', adapter_id, stdout, + stderr) + time.sleep(delay_time) + + def _parse_disk(self, stdout): + disks = [] + pattern = re.compile( + r'\s+Enclosure\s\#\s+:\s+(?P\d+)\s.*?' + r'\s+Slot\s\#\s+:\s+(?P\d+)\s.*?' + r'\s+Size\s\(in\s+(?P\w+).*?:\s+(?P\S+)/.*?' + r'\s+Protocol\s+:\s+(?P\S+)\s.*?' + r'\s+Drive Type\s+:\s+(?P\S+)\s.*?', re.DOTALL) + for match in re.finditer(pattern, stdout): + enclosure = int(match.group('enclosure').strip()) + slot = int(match.group('slot').strip()) + pd_type = match.group('pd_type').strip() + media_type = match.group( + 'media_type').strip().rsplit("_", 1)[-1].upper() + size = float(match.group('size').strip()) + size_unit = match.group('size_unit').strip() + disks.append( + Disk(enclosure=enclosure, + slot=slot, + pd_type=pd_type, + media_type=media_type, + size=size, + size_unit=size_unit).__dict__) + return disks + + def _get_raid_index(self, raid_level): + raid_index = RAID_INDEX.get(raid_level) + if not raid_index: + raise IncompatibleHardwareMethodError('Not support raid level %s.' % + raid_level) + return raid_index + + def _execute_raid(self, adapter_id, raid_index, disk_location, other_param=''): + cmd = (( + EXECUTABLE_FILE, + adapter_id, + 'create', + 'RAID%s' % raid_index, + 'MAX') + + disk_location + ( + 'noprompt', + other_param) + ) + stdout, stderr = executor.execute(*cmd) + LOG.info('Create %s raid%s : %s', raid_index, stdout, stderr) + + def _parse_physical_disks(self, physical_disks): + disk_strings = [ + f"{disk['enclosure']}:{disk['slot']}" for disk in physical_disks] + return tuple(disk_strings) diff --git a/bmp-agent/bmpa/raid/sas3ircu.py b/bmp-agent/bmpa/raid/sas3ircu.py new file mode 100755 index 0000000..79dfa46 --- /dev/null +++ b/bmp-agent/bmpa/raid/sas3ircu.py @@ -0,0 +1,150 @@ +import logging +import re +import time + +from bmpa.errors import BmpError, IncompatibleHardwareMethodError +from bmpa.model.disk import Disk +from bmpa.raid import BaseRaid, RAID_INDEX +from bmpa.utils import executor + +LOG = logging.getLogger(__name__) + +EXECUTABLE_FILE = '/usr/sbin/sas3ircu' + + +class Sas3ircu(BaseRaid): + + def list_adapter(self): + """Avago Technologies SAS3 IR Configuration Utility. + + Version 13.00.00.00 (2016.03.08) + Copyright (c) 2009-2016 Avago Technologies. All rights reserved. + + + Adapter Vendor Device SubSys SubSys + Index Type ID ID Pci Address Ven ID Dev ID + ----- ------------ ------ ------ ----------------- ------ ------ + 0 SAS3008 1000h 97h 00h:01h:00h:00h 1000h 3090h + SAS3IRCU: Utility Completed Successfully. + """ + cmd = (EXECUTABLE_FILE, 'list') + stdout, stderr = executor.execute(*cmd) + if stderr: + raise BmpError('Excute list adapter error:%s', stderr) + LOG.info('List adapter operation : %s.', stdout) + return stdout + + def get_adapter_ids(self): + stdout = self.list_adapter() + if stdout: + pattern = r'\s+(\d+)\s+SAS3008' + pattern_object = re.compile(pattern, re.MULTILINE) + adapter_ids = [] + for m in pattern_object.finditer(stdout): + adapter_ids.append(m.group(1)) + if len(adapter_ids) > 0: + return adapter_ids + + raise BmpError('Get addapter ids error.') + + def display(self, adapter_id=0): + cmd = (EXECUTABLE_FILE, adapter_id, 'display') + stdout, stderr = executor.execute(*cmd) + if stderr: + raise BmpError('Excute display error:%s', stderr) + LOG.info('Display raid adapter %s ', adapter_id) + return stdout + + def get_disks(self, adapter_id: str = '0'): + stdout = self.display(adapter_id) + if stdout: + LOG.debug('Display out:%s.', stdout) + return self._parse_disk(stdout) + return BmpError('Get disks error.') + + def noraid(self, config): + # only list adapter + self.list_adapter() + + def raid0(self, config): + raid_index = self._get_raid_index(config.raid_level) + adapter_id = config.adapter_id + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid1(self, config): + raid_index = self._get_raid_index(config.raid_level) + adapter_id = config.adapter_id + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid5(self, config): + raid_index = self._get_raid_index(config.raid_level) + adapter_id = config.adapter_id + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid10(self, config): + raid_index = self._get_raid_index(config.raid_level) + adapter_id = config.adapter_id + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def clean_raid(self, adapter_id: str = '0', delay_time=0): + time.sleep(30) + cmd = (EXECUTABLE_FILE, adapter_id, 'delete', 'noprompt') + stdout, stderr = executor.execute(*cmd) + LOG.info('Delete %s operation : %s : %s.', adapter_id, stdout, + stderr) + time.sleep(delay_time) + + def _parse_disk(self, stdout): + disks = [] + pattern = re.compile( + r'\s+Enclosure\s\#\s+:\s+(?P\d+)\s.*?' + r'\s+Slot\s\#\s+:\s+(?P\d+)\s.*?' + r'\s+Size\s\(in\s+(?P\w+).*?:\s+(?P\S+)/.*?' + r'\s+Protocol\s+:\s+(?P\S+)\s.*?' + r'\s+Drive Type\s+:\s+(?P\S+)\s.*?', re.DOTALL) + for match in re.finditer(pattern, stdout): + enclosure = int(match.group('enclosure').strip()) + slot = int(match.group('slot').strip()) + pd_type = match.group('pd_type').strip() + media_type = match.group( + 'media_type').strip().rsplit("_", 1)[-1].upper() + size = float(match.group('size').strip()) + size_unit = match.group('size_unit').strip() + disks.append( + Disk(enclosure=enclosure, + slot=slot, + pd_type=pd_type, + media_type=media_type, + size=size, + size_unit=size_unit).__dict__) + return disks + + def _get_raid_index(self, raid_level): + raid_index = RAID_INDEX.get(raid_level) + if not raid_index: + raise IncompatibleHardwareMethodError('Not support raid level %s.' % + raid_level) + return raid_index + + def _execute_raid(self, adapter_id, raid_index, disk_location, other_param=''): + cmd = (( + EXECUTABLE_FILE, + adapter_id, + 'create', + 'RAID%s' % raid_index, + 'MAX') + + disk_location + ( + 'noprompt', + other_param) + ) + stdout, stderr = executor.execute(*cmd) + LOG.info('Create %s raid%s : %s', raid_index, stdout, stderr) + + def _parse_physical_disks(self, physical_disks): + disk_strings = [ + f"{disk['enclosure']}:{disk['slot']}" for disk in physical_disks] + return tuple(disk_strings) diff --git a/bmp-agent/bmpa/raid/storcli64.py b/bmp-agent/bmpa/raid/storcli64.py new file mode 100755 index 0000000..2e9e56e --- /dev/null +++ b/bmp-agent/bmpa/raid/storcli64.py @@ -0,0 +1,152 @@ +import json +import logging +import time + +from bmpa.errors import BmpError, IncompatibleHardwareMethodError +from bmpa.model.disk import Disk +from bmpa.raid import BaseRaid, RAID_INDEX +from bmpa.utils import executor +from bmpa.utils.executor import ProcessExecutionError + + +LOG = logging.getLogger(__name__) + +EXECUTABLE_FILE = '/usr/sbin/storcli64' + + +class Storcli64(BaseRaid): + + def list_adapter(self, param='J'): + cmd = (EXECUTABLE_FILE, '/call show %(param)s' % {'param': param}) + stdout, stderr = executor.execute(*cmd) + if stderr: + raise BmpError('Excute list adapter error:%s', stderr) + LOG.info('List adapter operation : %s.', stdout) + return stdout + + def get_adapter_ids(self): + stdout = self.list_adapter() + adapter_ids = [] + if stdout: + adapter_ids = [] + json_out = json.loads(stdout) + for item in json_out['Controllers']: + adapter_ids.append(item['Command Status']['Controller']) + if len(adapter_ids) == 0: + raise BmpError('Get addapter ids error.') + + return adapter_ids + + def display(self, adapter_id=0, param='J'): + cmd = (EXECUTABLE_FILE, '/c%(adapter_id)s show %(param)s' % { + 'adapter_id': adapter_id, + 'param': param + }) + stdout, stderr = executor.execute(*cmd) + if stderr: + raise BmpError('Excute display error:%s', stderr) + LOG.info('Display raid adapter %s ', adapter_id) + return stdout + + def get_disks(self, adapter_id: str = '0'): + stdout = self.display(adapter_id) + if stdout: + LOG.debug('Display out:%s.', stdout) + return self._parse_disk(stdout) + return BmpError('Get disks error.') + + def noraid(self, config): + adapter_id = config.adapter_id + raid_index = self._get_raid_index('RAID0') + for disk_location in config.physical_disks: + disk_location = self._parse_physical_disks([disk_location]) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid0(self, config): + adapter_id = config.adapter_id + raid_index = self._get_raid_index(config.raid_level) + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid1(self, config): + adapter_id = config.adapter_id + raid_index = self._get_raid_index(config.raid_level) + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid5(self, config): + adapter_id = config.adapter_id + raid_index = self._get_raid_index(config.raid_level) + disk_location = self._parse_physical_disks(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location) + + def raid10(self, config): + adapter_id = config.adapter_id + raid_index = self._get_raid_index(config.raid_level) + disk_location = self._parse_physical_disks(config.physical_disks) + pdperarray = self._pdperarray(config.physical_disks) + self._execute_raid(adapter_id, raid_index, disk_location, pdperarray) + + def clean_raid(self, adapter_id: str = '0', delay_time=0): + cmd = (EXECUTABLE_FILE, '/c%s/vall' % adapter_id, 'delete', + 'force') + try: + stdout, stderr = executor.execute(*cmd) + except ProcessExecutionError as e: + if 'No VD' not in e.stdout: + error_msg = ('clean raid config' + 'failed with %(err)s' % { + 'err': str(e) + }) + raise BmpError('Clean raid error:%s.' % error_msg) + else: + if 'syntax error' in stdout: + raise BmpError('Clean raid error:%s.' % stdout) + LOG.info('Delete %s operation : %s : %s', adapter_id, + stdout, stderr) + time.sleep(delay_time) + + def _parse_disk(self, stdout): + disks = [] + json_out = json.loads(stdout) + for item in json_out['Controllers'][0]['Response Data']['PD LIST']: + slot = int(item['EID:Slt'].split(':')[1]) + enclosure = int(item['EID:Slt'].split(':')[0]) + size = float(item['Size'].split(' ')[0]) + size_unit = item['Size'].split(' ')[1] + pd_type = item['Intf'] + media_type = item['Med'] + disks.append( + Disk(enclosure=enclosure, + slot=slot, + pd_type=pd_type, + media_type=media_type, + size=size, + size_unit=size_unit).__dict__) + return disks + + def _pdperarray(self, physical_disks) -> str: + if len(physical_disks) % 2 != 0: + raise BmpError('Raid10 disk location must be 2X.') + pdperarray_num = 2 + if len(physical_disks) % 4 == 0 and len(physical_disks) > 8: + pdperarray_num = 4 + return 'pdperarray=%s' % pdperarray_num + + def _get_raid_index(self, raid_level): + raid_index = RAID_INDEX.get(raid_level) + if not raid_index: + raise IncompatibleHardwareMethodError('Not support raid level %s.' % + raid_level) + return raid_index + + def _execute_raid(self, adapter_id, raid_index, disk_location, other_param=''): + cmd = (EXECUTABLE_FILE, '/c%s' % adapter_id, 'add', 'vd', + 'r%s' % raid_index, 'drives=%s' % disk_location, other_param) + stdout, stderr = executor.execute(*cmd) + LOG.info('Create %s raid%s : %s', raid_index, stdout, stderr) + + def _parse_physical_disks(self, physical_disks): + disk_strings = [ + f"{disk['enclosure']}:{disk['slot']}" for disk in physical_disks] + return '%s' % ', '.join(disk_strings) diff --git a/bmp-agent/bmpa/serialize.py b/bmp-agent/bmpa/serialize.py new file mode 100755 index 0000000..185da74 --- /dev/null +++ b/bmp-agent/bmpa/serialize.py @@ -0,0 +1,70 @@ +import json +import uuid + + +class Serializable(object): + """Base class for things that can be serialized.""" + serializable_fields = () + + def serialize(self): + """Turn this object into a dict.""" + return dict((f, getattr(self, f)) for f in self.serializable_fields + if (hasattr(self, f) and getattr(self, f) is not None)) + + +class SerializableComparable(Serializable): + """A Serializable class which supports some comparison operators + + This class supports the '__eq__' and '__ne__' comparison operators, but + intentionally disables the '__hash__' operator as some child classes may be + mutable. The addition of these comparison operators is mainly used to + assist with unit testing. + """ + + __hash__ = None + + def __eq__(self, other): + return self.serialize() == other.serialize() + + def __ne__(self, other): + return self.serialize() != other.serialize() + + +class DefaultJsonEncoder(json.JSONEncoder): + """A slightly customized JSON encoder.""" + + def __init__(self, **kwargs): + super(DefaultJsonEncoder, self).__init__(**kwargs) + + def encode(self, o): + """Turn an object into JSON. + + Appends a newline to responses when configured to pretty-print, + in order to make use of curl less painful from most shells. + """ + delimiter = '' + + # if indent is None, newlines are still inserted, so we should too. + if self.indent is not None: + delimiter = '\n' + + return super(DefaultJsonEncoder, self).encode(o) + delimiter + + def default(self, o): + """Turn an object into a serializable object. + + In particular, by calling :meth:`.Serializable.serialize` on `o`. + """ + if isinstance(o, Serializable): + return o.serialize() + elif isinstance(o, uuid.UUID): + return str(o) + else: + return json.JSONEncoder.default(self, o) + + +class DefaultJsonDecoder(json.JSONDecoder): + """Customized JSON decoder.""" + + def __init__(self, **kwargs): + super(DefaultJsonDecoder, self).__init__(**kwargs) diff --git a/bmp-agent/bmpa/service/__init__.py b/bmp-agent/bmpa/service/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bmp-agent/bmpa/service/blockdevice.py b/bmp-agent/bmpa/service/blockdevice.py new file mode 100644 index 0000000..d388ba8 --- /dev/null +++ b/bmp-agent/bmpa/service/blockdevice.py @@ -0,0 +1,18 @@ +import logging + +from bmpa.log import log_complete +from bmpa.utils import clear_holders +from bmpa.utils import hardware + + +LOG = logging.getLogger(__name__) + + +@log_complete +def clean_blockdevice(): + block_devices = hardware.list_all_block_devices() + LOG.info('Clean blocks:%s', block_devices) + for bd in block_devices: + clear_holders.clear_holders(bd.name) + hardware.destroy_disk_metadata(bd.name) + hardware.erase_block_device(bd.name) diff --git a/bmp-agent/bmpa/service/collect.py b/bmp-agent/bmpa/service/collect.py new file mode 100755 index 0000000..14c383f --- /dev/null +++ b/bmp-agent/bmpa/service/collect.py @@ -0,0 +1,117 @@ +import json +import logging +import os +import time + +from bmpa.log import log_complete +from bmpa.model.disk import Disk +from bmpa.raid.factory import get_raid_driver +from bmpa.utils import executor +from bmpa.utils import hardware +from bmpa.utils import interfaceutils +from bmpa.utils import utils + +LOG = logging.getLogger(__name__) + + +def list_hardware_info(): + _patch_i40e_enable_lldp() + hardware_info = {} + hardware_info['interfaces'] = interfaceutils.list_network_interfaces_meta() + hardware_info['cpu'] = hardware.get_cpus() + hardware_info['disks'] = hardware.list_all_block_devices() + hardware_info['memory'] = hardware.get_memory() + hardware_info['bmc_address'] = hardware.get_bmc_address() + hardware_info['system_vendor'] = hardware.get_system_vendor_info() + hardware_info['boot'] = hardware.get_boot_info() + hardware_info['platform'] = hardware.get_platform_info() + return hardware_info + + +@log_complete +def collect_disks(raid_driver: str) -> dict: + raid = get_raid_driver(raid_driver) + adapter_ids = raid.get_adapter_ids() + controllers = None + if isinstance(adapter_ids, list): + controllers = [] + for adapter_id in adapter_ids: + data = {} + disks = raid.get_disks(adapter_id) + data['adapter_id'] = int(adapter_id) + data['disks'] = disks + controllers.append(data) + disk_data = {} + disk_data['controllers'] = controllers + disk_data['nvme'] = _get_nvme() + disk_data['devices'] = _parse_devices(hardware.list_all_block_devices()) + return disk_data + + +def _patch_i40e_enable_lldp(): + if not os.path.exists("/sys/module/i40e"): + LOG.warn('Not load i40e module.') + return + i40e_dir = "/sys/kernel/debug/i40e" + if not os.path.exists(i40e_dir): + LOG.warn("Not load i40e module.") + return + LOG.info("Ready to stop disabling embedded lldp in x710.") + i40_pci_dirs = os.listdir(i40e_dir) + for i40e_pci_dir in i40_pci_dirs: + i40e_pci_path = os.path.join(i40e_dir, i40e_pci_dir) + try: + os.system('echo "lldp stop" > %s/command' % i40e_pci_path) + LOG.info('echo "lldp stop" > %s/command' % i40e_pci_path) + # wait i40e firmware apply + time.sleep(30) + except Exception: + LOG.error('Send lldp stop to command failed.') + + +def _get_nvme(): + nvme_list = _get_nvme_list() + return _parse_nvme(nvme_list) + + +def _parse_nvme(nvme_list: str): + nvme = None + if nvme_list: + nvme_list = utils.json_hump2underline(nvme_list) + nvme_list = json.loads(nvme_list) + devices = nvme_list['devices'] + disks = [] + for device in devices: + disks.append(Disk( + serial=device['serial_number'], + size=device['physical_size'], + size_unit='B', + pd_type='NVME', + media_type='SSD', + device_path=device['device_path'] + ).__dict__) + nvme = {} + nvme['devices'] = disks + + return nvme + + +def _parse_devices(devices: list): + disks = [] + for device in devices: + media_type = "HDD" if device.rotational else "SSD" + disks.append(Disk( + serial=device.serial, + size=device.size, + size_unit='B', + media_type=media_type, + device_path=device.name + ).__dict__) + return disks + + +def _get_nvme_list() -> str: + cmd = ('nvme', "list", "-o", "json") + stdout, stderr = executor.execute(*cmd) + LOG.info("List nvme: %s : %s.", stdout, stderr) + return stdout diff --git a/bmp-agent/bmpa/service/formatpartitions.py b/bmp-agent/bmpa/service/formatpartitions.py new file mode 100644 index 0000000..62c641c --- /dev/null +++ b/bmp-agent/bmpa/service/formatpartitions.py @@ -0,0 +1,44 @@ + + +import logging + +from bmpa import constants +from bmpa.log import log_complete +from bmpa.osystem.factory import get_osystem +from bmpa.service import node +from bmpa.utils import utils + +LOG = logging.getLogger(__name__) + + +@log_complete +def formatpartitions(partitions): + os_type = node.get_os_type() + os_version = node.get_os_version() + osystem = get_osystem(os_type=os_type, os_version=os_version) + LOG.info('OS:%s', osystem.__class__.__name__) + partitions = _parse_partitions(partitions) + root_partition_path = osystem.formatpartitions(partitions) + if root_partition_path: + node.set_root_partition(root_partition_path) + + +def _parse_partitions(partitions): + for index, partition in enumerate(partitions): + volume = partition['volume'] + device_path = node.blockdev_id_to_devpath(volume) + partitions[index]['device_path'] = device_path + boot_mode = utils.get_boot_mode(node.get_boot_mode()) + LOG.info('boot mode:%s', boot_mode) + auto_create_efi = node.get_auto_create_efi() + LOG.info('auto create efi:%s', auto_create_efi) + if auto_create_efi and boot_mode == constants.UEFI: + efi_partition = dict() + efi_partition['label'] = constants.EFI_LABLE + efi_partition['fs_type'] = constants.EFI_FSTYPE + efi_partition_id = node.get_efi_partition_id() + device_path = node.blockdev_id_to_devpath(efi_partition_id) + efi_partition['device_path'] = device_path + partitions = [efi_partition] + partitions + LOG.info('Format auto efi partition %s.', partitions) + return partitions diff --git a/bmp-agent/bmpa/service/hostname.py b/bmp-agent/bmpa/service/hostname.py new file mode 100644 index 0000000..14eb2d4 --- /dev/null +++ b/bmp-agent/bmpa/service/hostname.py @@ -0,0 +1,11 @@ +from bmpa.log import log_complete +from bmpa.osystem.factory import get_osystem +from bmpa.service import node + + +@log_complete +def set_host_name(hostname: str): + os_type = node.get_os_type() + os_version = node.get_os_version() + osystem = get_osystem(os_type=os_type, os_version=os_version) + osystem.set_hostname(hostname) diff --git a/bmp-agent/bmpa/service/image.py b/bmp-agent/bmpa/service/image.py new file mode 100644 index 0000000..430a52f --- /dev/null +++ b/bmp-agent/bmpa/service/image.py @@ -0,0 +1,112 @@ +import logging +import os + +from bmpa import config +from bmpa.errors import ImageDownloadError, ImageChecksumError +from bmpa.log import log_complete +from bmpa.osystem.factory import get_osystem +from bmpa.service import node +from bmpa.utils import clear_holders +from bmpa.utils import device_hints +from bmpa.utils import executor +from bmpa.utils import file +from bmpa.utils import hardware +from bmpa.utils import system +from bmpa.utils import urlutils + +LOG = logging.getLogger(__name__) + + +def write_image(url: str, format: str, hash: str, filename: str): + root_device = node.get_root_devcie_name() + clear_holders.clear_holders(root_device) + hardware.destroy_disk_metadata(root_device) + local_file_dir = node.get_temp_directory() + url = _parse_url(url) + image_file_path = _download_image(url, hash, local_file_dir) + write_image_script = system.get_relative_path( + 'shell/write_image.sh') + cmd = ('/bin/bash', write_image_script, image_file_path, root_device) + LOG.info('Writing image with command: %s.', ' '.join(cmd)) + stdout, stderr = executor.execute(*cmd) + LOG.info('Write image to completely. stdout : %s, stderr : %s.', + stdout, stderr) + + hardware.fix_gpt_partition(root_device) + + os_type = node.get_os_type() + os_version = node.get_os_version() + osystem = get_osystem(os_type=os_type, os_version=os_version) + osystem.write_image_setup_boot() + root_partition = node.get_root_partition() + if not root_partition: + root_partition = osystem.get_root_partition(root_device) + node.set_root_partition(root_partition) + res = dict() + device = device_hints.get_device_by_hints( + {'name': root_device}) + res['root_device_hints'] = device + return res + + +@log_complete +def write_image_tar(url: str, format: str, hash: str, filename: str): + local_file_dir = node.get_temp_directory() + target = node.get_target() + root_device = node.get_root_devcie_name() + root_partition = node.get_root_partition() + grub_ttys = node.get_grub_ttys() + os_type = node.get_os_type() + os_version = node.get_os_version() + boot_mode = node.get_boot_mode() + mounts = node.get_mounts() + url = _parse_url(url) + image_file_path = _download_image(url, hash, local_file_dir) + _write_image(image_file_path, target) + + osystem = get_osystem(os_type=os_type, os_version=os_version) + LOG.info('OS:%s', osystem.__class__.__name__) + osystem.setup_boot(root_device=root_device, target=target, root_partition=root_partition, + boot_mode=boot_mode, mounts=mounts, grub_ttys=grub_ttys) + res = dict() + device = device_hints.get_device_by_hints( + {'name': root_device}) + res['root_device_hints'] = device + return res + + +def _parse_url(url): + host = "http://%(ip)s:%(port)s" % { + "ip": config.image_host, + "port": config.image_port + } + return url.replace("{host}", host) + + +def _write_image(image_file_path, target): + cmd = ('tar', 'xf', image_file_path, '-C', + target) + executor.execute(*cmd) + + LOG.info('Write image:%s success.', image_file_path) + + +def _download_image(url, hash, local_file_dir): + local_filename = url.split('/')[-1] + local_file_path = os.path.join(local_file_dir, local_filename) + try: + LOG.info('Dowload image start.') + urlutils.download(url, local_file_path) + except Exception as e: + raise ImageDownloadError(url, str(e)) + _check_image_hash(url, local_file_path, hash) + LOG.info('Dowload image finish.') + return local_file_path + + +def _check_image_hash(image_id, local_file_path, hash): + LOG.info('Check image hash start') + real_hash = file.md5sum(local_file_path) + if hash != real_hash: + raise ImageChecksumError(image_id, local_file_path, hash, real_hash) + LOG.info('Check image hash success.') diff --git a/bmp-agent/bmpa/service/initnode.py b/bmp-agent/bmpa/service/initnode.py new file mode 100644 index 0000000..5376e84 --- /dev/null +++ b/bmp-agent/bmpa/service/initnode.py @@ -0,0 +1,94 @@ +import logging +import operator +import os +import tempfile + + +from bmpa.device.factory import get_device +from bmpa.errors import BmpError +from bmpa.service import node +from bmpa.utils import device_hints +from bmpa.utils import hardware +from bmpa.utils import mountutils + +LOG = logging.getLogger(__name__) + + +def init_node(node_data): + mountutils.do_umount('/tmp', recursive=True) + node.update_node(node_data) + root_device = _init_root_device(node_data) + data_device = _init_data_device(node_data) + _init_dir() + _init_grub_ttys() + res_node = dict() + res_node['root_device_hints'] = root_device + if data_device is not None: + res_node['data_device_hints'] = data_device + return res_node + + +def _init_root_device(node_data) -> hardware.BlockDevice: + root_device_hints = node_data.get('root_device_hints') + if root_device_hints: + device = device_hints.get_device_by_hints(root_device_hints) + node.set_root_devcie_name(device['name']) + root_device_name = node.get_root_devcie_name() + if root_device_name: + return device_hints.get_device_by_hints( + {'name': root_device_name}) + + block_devices = hardware.list_all_block_devices() + if not block_devices or len(block_devices) <= 0: + raise BmpError("No block device found.") + block_devices = sorted(block_devices, key=operator.attrgetter('size')) + node.set_root_devcie_name(block_devices[0].name) + return block_devices[0] + + +def _init_data_device(node_data) -> hardware.BlockDevice: + data_device_hints = node_data.get('data_device_hints') + if data_device_hints: + device = device_hints.get_device_by_hints(data_device_hints) + node.set_data_devcie_name(device['name']) + data_device_name = node.get_data_devcie_name() + if data_device_name: + return device_hints.get_device_by_hints( + {'name': data_device_name}) + + block_devices = hardware.list_all_block_devices() + if block_devices and len(block_devices) > 1: + block_devices = sorted(block_devices, key=operator.attrgetter('size')) + node.set_data_devcie_name(block_devices[1].name) + return block_devices[1] + return None + + +def _init_dir(): + # work directory + work_directory = tempfile.mkdtemp() + LOG.info('Use work directory : %s.', work_directory) + + # target directory + target = os.path.join(work_directory, "chroot") + if not os.path.exists(target): + os.makedirs(target) + LOG.info('Use target directory : %s', target) + + # temp directory + temp_directory = os.path.join(work_directory, "temp") + if not os.path.exists(temp_directory): + os.makedirs(temp_directory) + LOG.info('Use temp directory : %s.', temp_directory) + + node.set_target(target) + node.set_temp_directory(temp_directory) + + +def _init_grub_ttys(): + system_vendor_info = node.get_system_vendor_info() + manufacturer = system_vendor_info.manufacturer + product_name = system_vendor_info.product_name + device = get_device(manufacturer, product_name) + grub_ttys = device.grub_ttys() + node.set_grub_ttys(grub_ttys) diff --git a/bmp-agent/bmpa/service/metadata.py b/bmp-agent/bmpa/service/metadata.py new file mode 100644 index 0000000..1e78ff9 --- /dev/null +++ b/bmp-agent/bmpa/service/metadata.py @@ -0,0 +1,54 @@ +from bmpa.log import log_complete +from bmpa.osystem.factory import get_osystem +from bmpa.service import node + + +@log_complete +def set_meta_data(data): + target = node.get_target() + root_partition = node.get_root_partition() + os_type = node.get_os_type() + os_version = node.get_os_version() + osystem = get_osystem(os_type=os_type, os_version=os_version) + osystem.set_meta_data(target=target, root_partition=root_partition, + data=data) + + +def set_user_data(data): + target = node.get_target() + root_partition = node.get_root_partition() + os_type = node.get_os_type() + os_version = node.get_os_version() + osystem = get_osystem(os_type=os_type, os_version=os_version) + osystem.set_user_data(target=target, root_partition=root_partition, + data=data) + + +def set_vendor_data(data): + target = node.get_target() + root_partition = node.get_root_partition() + os_type = node.get_os_type() + os_version = node.get_os_version() + osystem = get_osystem(os_type=os_type, os_version=os_version) + osystem.set_vendor_data(target=target, root_partition=root_partition, + data=data) + + +def set_network(data): + target = node.get_target() + root_partition = node.get_root_partition() + os_type = node.get_os_type() + os_version = node.get_os_version() + osystem = get_osystem(os_type=os_type, os_version=os_version) + osystem.set_network(target=target, root_partition=root_partition, + data=data) + + +def set_cloudinit_conf(ssh_pwauth, disable_root): + target = node.get_target() + root_partition = node.get_root_partition() + os_type = node.get_os_type() + os_version = node.get_os_version() + osystem = get_osystem(os_type=os_type, os_version=os_version) + osystem.set_cloudinit_conf(target=target, root_partition=root_partition, ssh_pwauth=ssh_pwauth, + disable_root=disable_root) diff --git a/bmp-agent/bmpa/service/mount.py b/bmp-agent/bmpa/service/mount.py new file mode 100755 index 0000000..b8c5318 --- /dev/null +++ b/bmp-agent/bmpa/service/mount.py @@ -0,0 +1,97 @@ +import logging +import operator +import os + +from bmpa import constants +from bmpa.errors import BmpError, DeviceNotFound +from bmpa.log import log_complete +from bmpa.service import node +from bmpa.utils import device_hints +from bmpa.utils.executor import ProcessExecutionError +from bmpa.utils import hardware +from bmpa.utils import mountutils +from bmpa.utils import utils + +LOG = logging.getLogger(__name__) + +EFI_LABEL = 'l_efi' +EFI_MOUNTPOINT = '/boot/efi' + + +@log_complete +def mount_partitions(auto_mount_efi, mounts): + target = node.get_target() + mounts = _parse_mounts(auto_mount_efi, mounts) + # Mounting needs to be done according to the hierarchy of mountpoint, + # with '/' being mounted first。 + mounts = sorted(mounts, key=operator.itemgetter('mountpoint')) + LOG.info('Mounts:%s', mounts) + node.set_mounts(mounts) + try: + for mount in mounts: + if mount['mountpoint'] == 'swap': + continue + mount_point = mount['mountpoint'] + partition_path = mount['partition_path'] + partition_mount_point = os.path.join(target, + mount_point.lstrip("/")) + + if not os.path.exists(partition_mount_point): + os.makedirs(partition_mount_point) + + mountutils.do_mount(src=partition_path, + target=partition_mount_point) + + except ProcessExecutionError as e: + error_msg = ('Mount partition error, failed with %(err)s.' % { + 'err': e + }) + LOG.error(error_msg) + raise BmpError(error_msg) + + +def _parse_mounts(auto_mount_efi, mounts): + blkid = hardware.blkid() + for index, mount in enumerate(mounts): + device_name = _get_device_name(mount) + if not device_name: + LOG.error("Device not found, volume:%s", mount) + raise DeviceNotFound() + label = mount['label'] + LOG.info('Mount info, device name:%s, lable:%s', device_name, label) + partition_path = hardware.get_labelled_partition( + device_name, label, attempts_times=10) + LOG.info('Partition path:%s.', partition_path) + mounts[index]['partition_path'] = partition_path + mounts[index]['fs_type'] = blkid[partition_path]['TYPE'] + + boot_mode = node.get_boot_mode() + boot_mode = utils.get_boot_mode(boot_mode) + LOG.info('Parse mounts boot_mode:%s.', boot_mode) + LOG.info('Parse mounts auto_mount_efi:%s.', auto_mount_efi) + if auto_mount_efi and boot_mode == constants.UEFI: + LOG.info('Parse auto mount efi.') + mount = dict() + mount['label'] = EFI_LABEL + mount['is_root_device'] = True + mount['mountpoint'] = EFI_MOUNTPOINT + device_name = node.get_root_devcie_name() + LOG.info('Mount info, device anme:%s, lable:%s', + device_name, mount['label']) + partition_path = hardware.get_labelled_partition( + device_name, mount['label'], attempts_times=10) + mount['partition_path'] = partition_path + mount['fs_type'] = constants.EFI_FSTYPE + mounts.append(mount) + return mounts + + +def _get_device_name(volume) -> str: + if volume.get('is_root_device', False): + return node.get_root_devcie_name() + if volume.get('is_data_device', False): + return node.get_data_devcie_name() + disk_hints = volume.get('disk_hints', None) + device = device_hints.get_device_by_hints(disk_hints) + LOG.info("Device name:%s", device.name) + return device.name diff --git a/bmp-agent/bmpa/service/node.py b/bmp-agent/bmpa/service/node.py new file mode 100644 index 0000000..e86b3eb --- /dev/null +++ b/bmp-agent/bmpa/service/node.py @@ -0,0 +1,153 @@ +import logging + +LOG = logging.getLogger(__name__) + +NODE = dict() +NODE['blockdev_id_to_devpath'] = dict() + + +def get_cached_node() -> dict: + """Return NODE.""" + return NODE + + +def update_node(node): + NODE.update(node) + LOG.info('node:%s', NODE) + + +def set_grub_ttys(grub_ttys): + NODE['grub_ttys'] = grub_ttys + + +def get_grub_ttys(): + return NODE['grub_ttys'] + + +def set_target(target): + NODE['target'] = target + + +def get_target(): + return NODE['target'] + + +def set_temp_directory(temp_directory): + NODE['temp_directory'] = temp_directory + + +def get_temp_directory(): + return NODE['temp_directory'] + + +def set_boot_mode(boot_mode): + NODE['boot_mode'] = boot_mode + + +def get_boot_mode(): + return NODE.get('boot_mode', None) + + +def set_os_version(os_version: str): + NODE['os_version'] = os_version + + +def get_os_version() -> str: + return NODE.get('os_version', None) + + +def set_os_type(os_type: str): + NODE['os_type'] = os_type + + +def get_os_type() -> str: + return NODE.get('os_type', None) + + +def set_system_vendor_info(vendor: any): + NODE['system_vendor_info'] = vendor + + +def get_system_vendor_info() -> any: + return NODE.get('system_vendor_info', None) + + +def set_serial_number(serial_number: str): + NODE['serial_number'] = serial_number + + +def get_serial_number() -> str: + return NODE.get('serial_number', None) + + +def set_root_devcie_name(device_name: str): + """Set root device name. + + device_name: like /dev/sda + """ + NODE['root_devcie_name'] = device_name + LOG.info('Root device name be set:%s', device_name) + + +def get_root_devcie_name() -> str: + return NODE.get('root_devcie_name', None) + + +def set_data_devcie_name(device_name: str): + NODE['data_devcie_name'] = device_name + LOG.info('Data device name be set:%s', device_name) + + +def get_data_devcie_name() -> str: + return NODE.get('data_devcie_name', None) + + +def set_root_partition(root_partition): + NODE['root_partition'] = root_partition + LOG.info("Root partition be set: %s", root_partition) + + +def get_root_partition(): + return NODE.get('root_partition', None) + + +def set_mounts(mounts): + NODE['mounts'] = mounts + + +def get_mounts(): + return NODE.get('mounts', None) + + +def set_auto_create_efi(auto_create_efi: bool): + NODE['auto_create_efi'] = auto_create_efi + LOG.info('Auto create efi:%s', auto_create_efi) + + +def get_auto_create_efi(): + return NODE.get('auto_create_efi', True) + + +def set_efi_partition_id(id: str): + NODE['efi_partition_id'] = id + + +def get_efi_partition_id(): + return NODE.get('efi_partition_id', None) + + +def blockdev_id_to_devpath_dict_add_item(id, path): + NODE['blockdev_id_to_devpath'][id] = path + LOG.info('Add blockdev_id_to_devpath %s:%s', id, path) + + +def blockdev_id_to_devpath(id): + devpath = NODE['blockdev_id_to_devpath'].get(id, None) + LOG.info('blockdev_id_to_devpath: %s:%s', id, devpath) + return devpath + + +def blockdev_id_to_devpath_dict(): + devpath_dict = NODE.get('blockdev_id_to_devpath', None) + LOG.info('blockdev_id_to_devpath_dict:%s', devpath_dict) + return devpath_dict diff --git a/bmp-agent/bmpa/service/partitions.py b/bmp-agent/bmpa/service/partitions.py new file mode 100644 index 0000000..ccc33c8 --- /dev/null +++ b/bmp-agent/bmpa/service/partitions.py @@ -0,0 +1,91 @@ +import logging +import uuid + +from bmpa import constants +from bmpa.errors import DeviceNotFound +from bmpa.log import log_complete +from bmpa.service import node +from bmpa.utils import clear_holders +from bmpa.utils import device_hints +from bmpa.utils import disk_partitioner +from bmpa.utils import hardware +from bmpa.utils import utils + +LOG = logging.getLogger(__name__) + + +@log_complete +def make_partition(volumes: list, boot_mode: str, + auto_create_efi: bool, auto_create_bios_grub: bool) -> dict: + boot_mode = utils.get_boot_mode(boot_mode) + node.set_boot_mode(boot_mode) + res = [] + for volume in volumes: + device_name = _get_device_name(volume) + if not device_name: + raise DeviceNotFound('Partition device not found.') + keep_data = volume.get('keep_data', True) + if keep_data: + continue + clear_holders.clear_holders(device_name) + hardware.destroy_disk_metadata(device_name) + hardware.erase_block_device(device_name) + partition = _parse_partition( + volume, boot_mode, auto_create_efi, auto_create_bios_grub) + part_dict = disk_partitioner.make_partitions( + device_name=partition['device_name'], partitions=partition['partitions'], + boot_mode=partition['boot_mode'], disk_label=partition['disk_label']) + for key, value in part_dict.items(): + node.blockdev_id_to_devpath_dict_add_item( + key, value) + disk_hints = device_hints.get_device_by_hints( + {'name': partition['device_name']}) + res_volume = dict() + res_volume['disk_hints'] = disk_hints + res.append(res_volume) + return res + + +def _get_device_name(volume) -> str: + if volume.get('is_root_device', False): + return node.get_root_devcie_name() + if volume.get('is_data_device', False): + return node.get_data_devcie_name() + disk_hints = volume.get('disk_hints', None) + device = device_hints.get_device_by_hints(disk_hints) + return device.name + + +def _parse_partition(volume: dict, boot_mode: str, + auto_create_efi: bool, auto_create_bios_grub: bool) -> list: + partitions = [] + is_root_device = volume.get('is_root_device', None) + disk_label = volume.get('disk_label', None) + device_name = _get_device_name(volume) + if is_root_device: + if auto_create_efi and boot_mode == constants.UEFI: + LOG.info('Auto create efi.') + partition = dict() + partition['id'] = uuid.uuid4().hex + partition['size'] = hardware.EFI_SYSTEM_PARTITION_SIZE + partition['fs_type'] = 'fat32' + partition['boot_flag'] = 'boot' + partitions.append(partition) + node.set_auto_create_efi(auto_create_efi) + node.set_efi_partition_id(partition['id']) + + if auto_create_bios_grub and boot_mode == constants.BIOS and disk_label == constants.GPT: + LOG.info('Auto crete bios grub.') + partition = dict() + partition['id'] = uuid.uuid4().hex + partition['size'] = hardware.BISO_BOOT_PARTITION_SIZE + partition['boot_flag'] = 'bios_grub' + partitions.append(partition) + partitions.extend(volume['partitions']) + disk_partitions = dict() + disk_partitions['device_name'] = device_name + disk_partitions['partitions'] = partitions + disk_partitions['boot_mode'] = boot_mode + disk_partitions['disk_label'] = disk_label + LOG.info('Parse partitions:%s', disk_partitions) + return disk_partitions diff --git a/bmp-agent/bmpa/service/password.py b/bmp-agent/bmpa/service/password.py new file mode 100644 index 0000000..d490a5b --- /dev/null +++ b/bmp-agent/bmpa/service/password.py @@ -0,0 +1,18 @@ +from bmpa.log import log_complete +from bmpa.osystem.factory import get_osystem +from bmpa.service import node + + +@log_complete +def set_password(password: str, username: str): + target = node.get_target() + root_device = node.get_root_devcie_name() + os_type = node.get_os_type() + os_version = node.get_os_version() + osystem = get_osystem(os_type=os_type, os_version=os_version) + root_partition = node.get_root_partition() + if not root_partition: + root_partition = osystem.get_root_partition(root_device) + node.set_root_partition(root_partition) + osystem.set_password(target=target, root_partition=root_partition, + password=password, username=username) diff --git a/bmp-agent/bmpa/service/raid.py b/bmp-agent/bmpa/service/raid.py new file mode 100644 index 0000000..8f37048 --- /dev/null +++ b/bmp-agent/bmpa/service/raid.py @@ -0,0 +1,91 @@ +import logging +import time + +from bmpa.errors import BlockDeviceError +from bmpa.log import log_complete +from bmpa.model.raid import RaidConfig +from bmpa.raid.factory import get_raid_driver +from bmpa.service import node +from bmpa.utils import hardware + + +LOG = logging.getLogger(__name__) + + +@log_complete +def make_raid(raid_datas): + res_raid_datas = [] + res_volumes = [] + for raid_data in raid_datas: + raid_driver = raid_data.get('raid_driver') + adapter_id = raid_data.get('adapter_id') + raid = get_raid_driver(raid_driver) + raid.clean_raid(adapter_id) + time.sleep(20) + for volume in raid_data['volumes']: + is_root_device, is_data_device = _get_is_root_is_data(volume) + devices_old = hardware.list_all_block_devices() + + raid_config = RaidConfig( + raid_data['adapter_id'], volume['raid_level'], volume['physical_disks']) + + raid.execute_raid_config(raid_config) + time.sleep(20) + devices_new = hardware.list_all_block_devices() + if not devices_new or len(devices_new) == 0: + raise BlockDeviceError('Devices get None.') + device_new = _get_device_new(devices_old, devices_new) + if is_root_device: + node.set_root_devcie_name(device_new.name) + LOG.info('Set root device:%s', device_new.name) + if is_data_device: + node.set_data_devcie_name(device_new.name) + LOG.info('Set data device:%s', device_new.name) + res_volumes_item = {} + res_volumes_item['volume_id'] = volume['volume_id'] + res_volumes_item['disk_hints'] = device_new + res_volumes.append(res_volumes_item) + res_raid_datas_item = {} + res_raid_datas_item['adapter_id'] = adapter_id + res_raid_datas_item['volumes'] = res_volumes + res_raid_datas.append(res_raid_datas_item) + time.sleep(10) + return res_raid_datas + + +def clean_raid(raid_datas): + for raid_data in raid_datas: + raid_driver = raid_data.get('raid_driver') + raid = get_raid_driver(raid_driver) + adapter_id = raid_data.get('adapter_id') + raid.clean_raid(adapter_id) + + +def _get_is_root_is_data(volume: dict): + is_root_device = False + is_data_device = False + if volume.get('is_root_device', False): + is_root_device = True + if volume.get('is_data_device', False): + is_data_device = True + return is_root_device, is_data_device + + +def _get_device_new(devices_old, devices_new): + LOG.info("Devices old:%s.", devices_old) + LOG.info("Devices new:%s.", devices_new) + device_new = None + if not devices_old or len(devices_old) == 0: + return devices_new[0] + devic_names = [device.name for device in devices_old] + for item in devices_new: + if item.name in devic_names: + LOG.info("Device name:%s in.", item.name) + continue + else: + LOG.info("New device name:%s.") + device_new = item + break + else: + BlockDeviceError('Can not find new device.') + return device_new diff --git a/bmp-agent/bmpa/shell/delete_efi_boot.sh b/bmp-agent/bmpa/shell/delete_efi_boot.sh new file mode 100755 index 0000000..c897ab6 --- /dev/null +++ b/bmp-agent/bmpa/shell/delete_efi_boot.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +set -u +set -x +set -e + +if [ $# -gt 0 ]; then + EFI_BOOT_LABEL=$1 +else + EFI_BOOT_LABEL="bmp" +fi + +if efibootmgr |grep -q "${EFI_BOOT_LABEL}";then +for num in `efibootmgr |grep "${EFI_BOOT_LABEL}"|awk -F'*' '{print $1}'|sed 's/Boot//g'` +do + efibootmgr -B -b ${num} +done +fi + +echo "Delete efi boot finished.!" diff --git a/bmp-agent/bmpa/shell/write_image.sh b/bmp-agent/bmpa/shell/write_image.sh new file mode 100755 index 0000000..12809eb --- /dev/null +++ b/bmp-agent/bmpa/shell/write_image.sh @@ -0,0 +1,34 @@ +#!/bin/bash + +set -e + +log() { + echo "`basename $0`: $@" +} + +usage() { + [[ -z "$1" ]] || echo -e "USAGE ERROR: $@\n" + echo "`basename $0`: IMAGEFILE DEVICE" + echo " - This script images DEVICE with IMAGEFILE" + exit 1 +} + +IMAGEFILE="$1" +DEVICE="$2" + +[[ -f $IMAGEFILE ]] || usage "$IMAGEFILE (IMAGEFILE) is not a file" +[[ -b $DEVICE ]] || usage "$DEVICE (DEVICE) is not a block device" + +# In production this will be replaced with secure erasing the drives +# For now we need to ensure there aren't any old (GPT) partitions on the drive +log "Erasing existing GPT and MBR data structures from ${DEVICE}" +sgdisk -Z $DEVICE || sgdisk -o $DEVICE + +log "Imaging $IMAGEFILE to $DEVICE" + +# limit the memory usage for qemu-img to 1 GiB +ulimit -v 1048576 +qemu-img convert -t directsync -O host_device $IMAGEFILE $DEVICE +sync + +log "${DEVICE} imaged successfully!" diff --git a/bmp-agent/bmpa/template/cloudinit/cloud.tpl b/bmp-agent/bmpa/template/cloudinit/cloud.tpl new file mode 100755 index 0000000..ec634a0 --- /dev/null +++ b/bmp-agent/bmpa/template/cloudinit/cloud.tpl @@ -0,0 +1,57 @@ +{% if disable_root %} +disable_root: true +{% else %} +disable_root: false +{% endif %} + +ssh_pwauth: {{ssh_pwauth}} + +datasource_list: [ NoCloud ] + +cloud_init_modules: + - disk_setup + - migrator + - bootcmd + - write-files + - growpart + - resizefs + - set_hostname + - update_hostname + - update_etc_hosts + - rsyslog + - users-groups + - ssh + +cloud_config_modules: + - mounts + - locale + - set-passwords + - rh_subscription + - yum-add-repo + - package-update-upgrade-install + - timezone + - puppet + - chef + - salt-minion + - mcollective + - disable-ec2-metadata + - runcmd + +cloud_final_modules: + - rightscale_userdata + - scripts-per-once + - scripts-per-boot + - scripts-per-instance + - scripts-user + - ssh-authkey-fingerprints + - keys-to-console + - phone-home + - final-message + - power-state-change + +system_info: + distro: rhel + paths: + cloud_dir: /var/lib/cloud + templates_dir: /etc/cloud/templates + ssh_svcname: sshd \ No newline at end of file diff --git a/bmp-agent/bmpa/template/cloudinit/cloud_debian.tpl b/bmp-agent/bmpa/template/cloudinit/cloud_debian.tpl new file mode 100755 index 0000000..c6d07a2 --- /dev/null +++ b/bmp-agent/bmpa/template/cloudinit/cloud_debian.tpl @@ -0,0 +1,100 @@ +#### debian +# The top level settings are used as module +# and system configuration. + +# A set of users which may be applied and/or used by various modules +# when a 'default' entry is found it will reference the 'default_user' +# from the distro configuration specified below + +# If this is set, 'root' will not be able to ssh in and they +# will get a message to login instead as the above $user (debian) +{% if disable_root %} +disable_root: true +{% else %} +disable_root: false +{% endif %} + +ssh_pwauth: {{ssh_pwauth}} + +datasource_list: [ NoCloud ] + +# This will cause the set+update hostname module to not operate (if true) +preserve_hostname: false + +# This preverts apt/sources.list to be updated at boot time, which +# may be annoying. +apt_preserve_sources_list: true + +# Example datasource config +# datasource: +# Ec2: +# metadata_urls: [ 'blah.com' ] +# timeout: 5 # (defaults to 50 seconds) +# max_wait: 10 # (defaults to 120 seconds) + +# The modules that run in the 'init' stage +cloud_init_modules: + - migrator + - seed_random + - bootcmd + - write-files + - growpart + - resizefs + - disk_setup + - mounts + - set_hostname + - update_hostname + - update_etc_hosts + - ca-certs + - rsyslog + - users-groups + - ssh + +# The modules that run in the 'config' stage +cloud_config_modules: +# Emit the cloud config ready event +# this can be used by upstart jobs for 'start on cloud-config'. + - emit_upstart + - ssh-import-id + - locale + - set-passwords + - grub-dpkg + - apt-pipelining + - apt-configure + - ntp + - timezone + - disable-ec2-metadata + - runcmd + - byobu + +# The modules that run in the 'final' stage +cloud_final_modules: + - package-update-upgrade-install + - fan + - puppet + - chef + - salt-minion + - mcollective + - rightscale_userdata + - scripts-vendor + - scripts-per-once + - scripts-per-boot + - scripts-per-instance + - scripts-user + - ssh-authkey-fingerprints + - keys-to-console + - phone-home + - final-message + - power-state-change + +# System and/or distro specific settings +# (not accessible to handlers/transforms) +system_info: + # This will affect which distro class gets used + distro: debian + # Other config here will be given to the distro class and/or path classes + paths: + cloud_dir: /var/lib/cloud/ + templates_dir: /etc/cloud/templates/ + upstart_dir: /etc/init/ + ssh_svcname: ssh \ No newline at end of file diff --git a/bmp-agent/bmpa/template/cloudinit/cloud_ubuntu.tpl b/bmp-agent/bmpa/template/cloudinit/cloud_ubuntu.tpl new file mode 100755 index 0000000..ccda7a1 --- /dev/null +++ b/bmp-agent/bmpa/template/cloudinit/cloud_ubuntu.tpl @@ -0,0 +1,112 @@ +# The top level settings are used as module +# and system configuration. +# A set of users which may be applied and/or used by various modules +# when a 'default' entry is found it will reference the 'default_user' +# from the distro configuration specified below + +# If this is set, 'root' will not be able to ssh in and they +# will get a message to login instead as the default $user +{% if disable_root %} +disable_root: true +{% else %} +disable_root: false +{% endif %} + +ssh_pwauth: {{ssh_pwauth}} + +datasource_list: [ NoCloud ] + +# This will cause the set+update hostname module to not operate (if true) +preserve_hostname: false + +# If you use datasource_list array, keep array items in a single line. +# If you use multi line array, ds-identify script won't read array items. +# Example datasource config +# datasource: +# Ec2: +# metadata_urls: [ 'blah.com' ] +# timeout: 5 # (defaults to 50 seconds) +# max_wait: 10 # (defaults to 120 seconds) + + + +# The modules that run in the 'init' stage +cloud_init_modules: + - migrator + - seed_random + - bootcmd + - write-files + - growpart + - resizefs + - disk_setup + - mounts + - set_hostname + - update_hostname + - update_etc_hosts + - ca-certs + - rsyslog + - users-groups + - ssh + +# The modules that run in the 'config' stage +cloud_config_modules: +# Emit the cloud config ready event +# this can be used by upstart jobs for 'start on cloud-config'. + - emit_upstart + - snap + - ssh-import-id + - keyboard + - locale + - set-passwords + - grub-dpkg + - apt-pipelining + - apt-configure + - ubuntu-advantage + - ntp + - timezone + - disable-ec2-metadata + - runcmd + - byobu + +# The modules that run in the 'final' stage +cloud_final_modules: + - package-update-upgrade-install + - fan + - landscape + - lxd + - ubuntu-drivers + - write-files-deferred + - puppet + - chef + - mcollective + - salt-minion + - reset_rmc + - refresh_rmc_and_interface + - rightscale_userdata + - scripts-vendor + - scripts-per-once + - scripts-per-boot + - scripts-per-instance + - scripts-user + - ssh-authkey-fingerprints + - keys-to-console + - install-hotplug + - phone-home + - final-message + - power-state-change + +# System and/or distro specific settings +# (not accessible to handlers/transforms) +system_info: + # This will affect which distro class gets used + distro: ubuntu + + # Automatically discover the best ntp_client + ntp_client: auto + # Other config here will be given to the distro class and/or path classes + paths: + cloud_dir: /var/lib/cloud/ + templates_dir: /etc/cloud/templates/ + upstart_dir: /etc/init/ + ssh_svcname: ssh + \ No newline at end of file diff --git a/bmp-agent/bmpa/template/cloudinit/cloudbase-init.tpl b/bmp-agent/bmpa/template/cloudinit/cloudbase-init.tpl new file mode 100644 index 0000000..92d0550 --- /dev/null +++ b/bmp-agent/bmpa/template/cloudinit/cloudbase-init.tpl @@ -0,0 +1,23 @@ +[DEFAULT] +username=Administrator +groups=Administrators +inject_user_password=true +config_drive_raw_hhd=true +config_drive_cdrom=true +config_drive_vfat=true +bsdtar_path=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\bin\bsdtar.exe +mtools_path=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\bin\ +verbose=true +debug=true +logdir=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\log\ +logfile=cloudbase-init.log +default_log_levels=comtypes=INFO,suds=INFO,iso8601=WARN,requests=WARN +logging_serial_port_settings=COM1,115200,N,8 +mtu_use_dhcp_config=true +ntp_use_dhcp_config=true +local_scripts_path=C:\Program Files\Cloudbase Solutions\Cloudbase-Init\LocalScripts\ +check_latest_version=true +{% if only_set_network %} +plugins=cloudbaseinit.plugins.common.networkconfig.NetworkConfigPlugin +{% endif %} +first_logon_behaviour=no \ No newline at end of file diff --git a/bmp-agent/bmpa/template/fstab/fstab.tpl b/bmp-agent/bmpa/template/fstab/fstab.tpl new file mode 100644 index 0000000..b89a48e --- /dev/null +++ b/bmp-agent/bmpa/template/fstab/fstab.tpl @@ -0,0 +1,3 @@ +{% for mount in mounts %} +LABEL={{mount.label}} {{mount.mountpoint}} {{mount.fs_type}} {{mount.options}} 0 0 +{% endfor %} \ No newline at end of file diff --git a/bmp-agent/bmpa/template/rsyslog/bmp-agent.conf.tpl b/bmp-agent/bmpa/template/rsyslog/bmp-agent.conf.tpl new file mode 100644 index 0000000..5d2f603 --- /dev/null +++ b/bmp-agent/bmpa/template/rsyslog/bmp-agent.conf.tpl @@ -0,0 +1,3 @@ +module(load="imfile") +input(type="imfile" File="{{log_path}}" Tag="bmp-agent") +if $programname == 'bmp-agent' then @{{rsyslog_host}}:{{rsyslog_port}} \ No newline at end of file diff --git a/bmp-agent/bmpa/tests/__init__.py b/bmp-agent/bmpa/tests/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/bmp-agent/bmpa/tests/unit/__init__.py b/bmp-agent/bmpa/tests/unit/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/bmp-agent/bmpa/tests/unit/test_config.py b/bmp-agent/bmpa/tests/unit/test_config.py new file mode 100644 index 0000000..4cf2687 --- /dev/null +++ b/bmp-agent/bmpa/tests/unit/test_config.py @@ -0,0 +1,10 @@ +import unittest +from unittest.mock import patch + + +class TestConfig(unittest.TestCase): + @patch('bmpa.utils.utils.get_agent_params') + def test_default_values(self, mock_get_agent_params): + import bmpa.config as config + mock_get_agent_params.return_value = {} + self.assertEqual(config.cmdline_path, '/proc/cmdline') diff --git a/bmp-agent/bmpa/utils/__init__.py b/bmp-agent/bmpa/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bmp-agent/bmpa/utils/chroot.py b/bmp-agent/bmpa/utils/chroot.py new file mode 100644 index 0000000..720f79d --- /dev/null +++ b/bmp-agent/bmpa/utils/chroot.py @@ -0,0 +1,38 @@ +from bmpa.utils import executor +from bmpa.utils import mountutils +from bmpa.utils import paths + + +class ChrootTarget: + def __init__(self, target, + mounts=None): + if target is None: + target = "/" + self.target = paths.target_path(target) + if mounts is not None: + self.mounts = mounts + else: + self.mounts = ["/dev", "/proc", "/run", "/sys"] + self.umounts = [] + + def __enter__(self): + for p in self.mounts: + tpath = paths.target_path(self.target, p) + mount_success = True + if p == '/sys': + mount_success = mountutils.do_mount( + 'none', tpath, opts=['-t', 'sysfs']) + else: + mount_success = mountutils.do_mount(p, tpath, opts='--bind') + if mount_success: + self.umounts.append(tpath) + return self + + def __exit__(self, etype, value, trace): + + for p in reversed(self.umounts): + mountutils.do_umount(p) + + def execute(self, *args, **kwargs): + kwargs['target'] = self.target + return executor.execute(*args, **kwargs) diff --git a/bmp-agent/bmpa/utils/classloader.py b/bmp-agent/bmpa/utils/classloader.py new file mode 100755 index 0000000..1bef6be --- /dev/null +++ b/bmp-agent/bmpa/utils/classloader.py @@ -0,0 +1,4 @@ +def load_class(class_path): + parts = class_path.rsplit('.', 1) + module = __import__(parts[0], fromlist=parts[1]) + return getattr(module, parts[1]) diff --git a/bmp-agent/bmpa/utils/clear_holders.py b/bmp-agent/bmpa/utils/clear_holders.py new file mode 100644 index 0000000..301d640 --- /dev/null +++ b/bmp-agent/bmpa/utils/clear_holders.py @@ -0,0 +1,326 @@ +import logging +import os +import time + +from bmpa.utils import executor +from bmpa.utils import hardware +from bmpa.utils import lvm +from bmpa.utils import system +from bmpa.utils import udev + + +LOG = logging.getLogger(__name__) + + +def clear_holders(base_paths): + """Clear all storage layers depending on the devices specified in 'base_paths' + + A single device or list of devices can be specified. + Device paths can be specified either as paths in /dev or /sys/block + Will throw OSError if any holders could not be shut down + """ + # handle single path + if not isinstance(base_paths, (list, tuple)): + base_paths = [base_paths] + LOG.info('Generating device storage trees for path(s): %s', base_paths) + + # get current holders and plan how to shut them down + holder_trees = [gen_holders_tree(path) for path in base_paths] + LOG.info('Current device storage tree:\n%s', + '\n'.join(_format_holders_tree(tree) for tree in holder_trees)) + ordered_devs = _plan_shutdown_holder_trees(holder_trees) + LOG.info('Shutdown Plan:\n%s', "\n".join(map(str, ordered_devs))) + + # run shutdown functions + for dev_info in ordered_devs: + dev_type = DEV_TYPES.get(dev_info['dev_type']) + shutdown_function = dev_type.get('shutdown') + if not shutdown_function: + continue + + if os.path.exists(dev_info['device']): + LOG.info("shutdown running on holder type: '%s' syspath: '%s'", + dev_info['dev_type'], dev_info['device']) + shutdown_function(dev_info['device']) + + +def gen_holders_tree(device): + """Generate a tree representing the current storage hirearchy above 'device'. + + """ + + device = hardware.sys_block_path(device) + kname = hardware.path_to_kname(device) + + # the holders for a device should consist of the devices in the holders/ + # dir in sysfs and any partitions on the device. this ensures that a + # storage tree starting from a disk will include all devices holding the + # disk's partitions + holders = hardware.get_holders(device) + holder_paths = ([hardware.sys_block_path(h) for h in holders] + + hardware.get_sysfs_partitions(device)) + # the DEV_TYPE registry contains a function under the key 'ident' for each + # device type entry that returns true if the device passed to it is of the + # correct type. there should never be a situation in which multiple + # identify functions return true. therefore, it will always work to take + # the device type with the first identify function that returns true as the + # device type for the current device. in the event that no identify + # functions return true, the device will be treated as a disk + # (DEFAULT_DEV_TYPE). the identify function for disk never returns true. + # the next() builtin in python will not raise a StopIteration exception if + # there is a default value defined + + dev_type = next((k for k, v in DEV_TYPES.items() if v['ident'](device)), + DEFAULT_DEV_TYPE) + return { + 'device': device, 'dev_type': dev_type, 'name': kname, + 'holders': [gen_holders_tree(h) for h in holder_paths], + } + + +def is_mpath_partition(devpath, info=None): + """Check if a device is a multipath partition, returns boolean. """ + result = False + if devpath.startswith('/dev/dm-'): + if not info: + info = udev.udevadm_info(devpath) + if 'DM_PART' in info and 'DM_MPATH' in info: + result = True + + LOG.debug("%s is multipath device partition? %s", devpath, result) + return result + + +def get_dmsetup_uuid(device): + """Get the dm uuid for a specified dmsetup device + + """ + blockdev = hardware.sysfs_to_devpath(device) + cmd = ('dmsetup', 'info', blockdev, '-C', '-o', 'uuid', + '--noheadings') + stdout, _ = executor.execute(*cmd) + return stdout.strip() + + +def _define_handlers_registry(): + """Returns instantiated dev_types + + """ + return { + 'lvm': {'shutdown': _shutdown_lvm, 'ident': _identify_lvm}, + 'disk': {'shutdown': wipe_superblock, 'ident': lambda x: False} + } + + +def _identify_lvm(device): + """Determine if specified device is a lvm device. + + """ + return (hardware.path_to_kname(device).startswith('dm') and + get_dmsetup_uuid(device).startswith('LVM')) + + +def _format_holders_tree(holders_tree): + """Draw a nice dirgram of the holders tree. + + """ + # spacer styles based on output of 'tree --charset=ascii' + spacers = (('`-- ', ' ' * 4), ('|-- ', '|' + ' ' * 3)) + + def format_tree(tree): + """Format entry and any subentries. + + """ + result = [tree['name']] + holders = tree['holders'] + for (holder_no, holder) in enumerate(holders): + spacer_style = spacers[min(len(holders) - (holder_no + 1), 1)] + subtree_lines = format_tree(holder) + for (line_no, line) in enumerate(subtree_lines): + result.append(spacer_style[min(line_no, 1)] + line) + return result + + return '\n'.join(format_tree(holders_tree)) + + +def _plan_shutdown_holder_trees(holders_trees): + """Plan best order to shut down holders in, taking into account high level + + storage layers that may have many devices below them + + returns a sorted list of descriptions of storage config entries including + their path in /sys/block and their dev type + + can accept either a single storage tree or a list of storage trees assumed + to start at an equal place in storage hirearchy (i.e. a list of trees + starting from disk) + """ + # holds a temporary registry of holders to allow cross references + # key = device sysfs path, value = {} of priority level, shutdown function + reg = {} + + # normalize to list of trees + if not isinstance(holders_trees, (list, tuple)): + holders_trees = [holders_trees] + + # sort the trees to ensure we generate a consistent plan + holders_trees = sorted(holders_trees, key=lambda x: x['device']) + + def htree_level(tree): + if len(tree['holders']) == 0: + return 0 + return 1 + sum(htree_level(holder) for holder in tree['holders']) + + def flatten_holders_tree(tree, level=0): + """Add entries from holders tree to registry with level key corresponding + + to how many layers from raw disks the current device is at + """ + device = tree['device'] + device_level = htree_level(tree) + + # always go with highest level if current device has been + # encountered already. since the device and everything above it is + # re-added to the registry it ensures that any increase of level + # required here will propagate down the tree + # this handles a scenario like mdadm + bcache, where the backing + # device for bcache is a 3rd level item like mdadm, but the cache + # device is 1st level (disk) or second level (partition), ensuring + # that the bcache item is always considered higher level than + # anything else regardless of whether it was added to the tree via + # the cache device or backing device first + if device in reg: + level = max(reg[device]['level'], level) + 1 + + else: + # first time device to registry, assume the larger value of the + # current level or the length of its dependencies. + level = max(device_level, level) + + reg[device] = {'level': level, 'device': device, + 'dev_type': tree['dev_type']} + + # handle holders above this level + for holder in tree['holders']: + flatten_holders_tree(holder, level=level + 1) + + # flatten the holders tree into the registry + for holders_tree in holders_trees: + flatten_holders_tree(holders_tree) + + def devtype_order(dtype): + """Return the order in which we want to clear device types, higher + + value should be cleared first. + :param: dtype: string. A device types name from the holders registry, + see _define_handlers_registry() + :returns: integer + """ + dev_type_order = [ + 'disk', 'lvm'] + return 1 + dev_type_order.index(dtype) + + # return list of entry dicts with greatest htree depth. The 'level' value + # indicates the number of additional devices that are "below" this device. + # Devices must be cleared in descending 'level' value. For devices which + # have the same 'level' value, we sort within the 'level' by devtype order. + return [reg[k] + for k in sorted(reg, reverse=True, + key=lambda x: (reg[x]['level'], + devtype_order(reg[x]['dev_type'])))] + + +def _shutdown_lvm(device): + """Shutdown specified lvm device. + + """ + device = hardware.sys_block_path(device) + # lvm devices have a dm directory that containes a file 'name' containing + # '{volume group}-{logical volume}'. The volume can be freed using lvremove + name_file = os.path.join(device, 'dm', 'name') + lvm_name = system.load_file(name_file).strip() + (vg_name, lv_name) = lvm.split_lvm_name(lvm_name) + vg_lv_name = "%s/%s" % (vg_name, lv_name) + devname = "/dev/" + vg_lv_name + + # wipe contents of the logical volume first + LOG.info('Wiping lvm logical volume: %s', devname) + hardware.quick_zero(devname) + + # remove the logical volume + LOG.debug('using "lvremove" on %s', vg_lv_name) + executor.execute(*['lvremove', '--force', '--force', vg_lv_name]) + + # if that was the last lvol in the volgroup, get rid of volgroup + if len(lvm.get_lvols_in_volgroup(vg_name)) == 0: + pvols = lvm.get_pvols_in_volgroup(vg_name) + executor.execute(*['vgremove', '--force', '--force', + vg_name], check_exit_code=[0, 5]) + + # wipe the underlying physical volumes + for pv in pvols: + LOG.info('Wiping lvm physical volume: %s', pv) + hardware.quick_zero(pv) + + +def wipe_superblock(device): + """Wrapper for block.wipe_volume compatible with shutdown function interface.""" + blockdev = hardware.sysfs_to_devpath(device) + if not hardware.is_online(blockdev): + LOG.debug("Device is not online (size=0), so skipping:" + " '%s'", blockdev) + return + + # gather any partitions + partitions = hardware.get_sysfs_partitions(device) + + _wipe_superblock(blockdev) + + # if we had partitions, make sure they've been removed + if partitions: + LOG.debug('%s had partitions, issuing partition reread', device) + retries = [.5, .5, 1, 2, 5, 7] + for attempt, wait in enumerate(retries): + try: + # only rereadpt on wiped device + hardware.rescan_block_devices(devices=[blockdev]) + # may raise IOError, OSError due to wiped partition table + curparts = hardware.get_sysfs_partitions(device) + if len(curparts) == 0: + return + except (IOError, OSError): + if attempt + 1 >= len(retries): + raise + + LOG.debug("%s partitions still present, rereading pt" + " (%s/%s). sleeping %ss before retry", + device, attempt + 1, len(retries), wait) + time.sleep(wait) + + +def _wipe_superblock(blockdev, exclusive=True): + """No checks, just call wipe_volume""" + + retries = [1, 3, 5, 7] + LOG.info('wiping superblock on %s', blockdev) + for attempt, wait in enumerate(retries): + LOG.debug('wiping %s attempt %s/%s', + blockdev, attempt + 1, len(retries)) + try: + hardware.wipe_volume(blockdev, mode='superblock', exclusive=exclusive) + LOG.debug('successfully wiped device %s on attempt %s/%s', + blockdev, attempt + 1, len(retries)) + return + except OSError: + if attempt + 1 >= len(retries): + raise + else: + LOG.debug("wiping device '%s' failed on attempt" + " %s/%s. sleeping %ss before retry", + blockdev, attempt + 1, len(retries), wait) + time.sleep(wait) + + +DEFAULT_DEV_TYPE = 'disk' +DATA_DESTROYING_HANDLERS = [lambda:None] +DEV_TYPES = _define_handlers_registry() diff --git a/bmp-agent/bmpa/utils/device_hints.py b/bmp-agent/bmpa/utils/device_hints.py new file mode 100644 index 0000000..0e99ef8 --- /dev/null +++ b/bmp-agent/bmpa/utils/device_hints.py @@ -0,0 +1,385 @@ +import copy +import logging +# python3 code +from urllib.request import pathname2url + +from bmpa.errors import DeviceNotFound +from bmpa.utils import hardware +from bmpa.utils import specs_matcher +from bmpa.utils import strutils + +LOG = logging.getLogger(__name__) + +# A dictionary in the form {hint name: hint type} +VALID_DEVICE_HINTS = { + 'size': int, + 'model': str, + 'wwn': str, + 'serial': str, + 'vendor': str, + 'wwn_with_extension': str, + 'wwn_vendor_extension': str, + 'name': str, + 'rotational': bool, + 'hctl': str, + 'by_path': str, +} + +NOT_VALID_DEVICE_HINTS = [ + 'rotational', 'hctl', 'name', 'wwn_with_extension', 'wwn_vendor_extension' +] + +DEVICE_HINTS_GRAMMAR = specs_matcher.make_grammar() + + +def get_device_by_hints(device_hints: dict, validate_all_default_hints: bool = False) -> hardware.BlockDevice: + block_devices = hardware.list_all_block_devices() + if (not device_hints) or len(device_hints) == 0: + raise DeviceNotFound("device_hints shoud not be None.") + else: + serialized_devs = [dev.serialize() for dev in block_devices] + try: + device = match_device_hints( + serialized_devs, + device_hints, + validate_all_default_hints=validate_all_default_hints) + except ValueError as e: + raise DeviceNotFound( + 'No devices could be found using the device hints ' + '%(hints)s because they failed to validate. Error: ' + '%(error)s' % { + 'hints': device_hints, + 'error': e + }) + + if not device: + raise DeviceNotFound( + "No suitable device was found for " + "deployment using these hints %s" % device_hints) + + dev_name = device['name'] + + LOG.info( + 'Picked device %(dev)s based on ' + 'device hints %(hints)s', { + 'dev': dev_name, + 'hints': device_hints + }) + return device + + +def match_device_hints(devices, + device_hints, + validate_all_default_hints=True) -> hardware.BlockDevice: + """Try to find a device that matches the device hints. + + Try to find a device that matches the device hints. In order + for a device to be matched it needs to satisfy all the given hints. + + :param devices: A list of dictionaries representing the devices + containing one or more of the following keys: + + :name: (String) The device name, e.g /dev/sda + :size: (Integer) Size of the device in *bytes* + :model: (String) Device model + :vendor: (String) Device vendor name + :serial: (String) Device serial number + :wwn: (String) Unique storage identifier + :wwn_with_extension: (String): Unique storage identifier with + the vendor extension appended + :wwn_vendor_extension: (String): United vendor storage identifier + :rotational: (Boolean) Whether it's a rotational device or + not. Useful to distinguish HDDs (rotational) and SSDs + (not rotational). + :hctl: (String): The SCSI address: Host, channel, target and lun. + For example: '1:0:0:0'. + :by_path: (String): The alternative device name, + e.g. /dev/disk/by-path/pci-0000:00 + + :param device_hints: A dictionary with the device hints. + :raises: ValueError, if some information is invalid. + :returns: The first device to match all the hints or None. + """ + try: + dev = next( + find_devices_by_hints(devices, device_hints, + validate_all_default_hints)) + except StopIteration: + LOG.warning('No device found that matches the device hints %s', + device_hints) + else: + LOG.info( + 'Device found! The device "%s" matches the ' + 'device hints %s', dev, device_hints) + return dev + + +def parse_device_hints(device, validate_all_default_hints=True): + """Parse the device property of a node. + + Parses and validates the device property of a node. These are + hints for how a node's device is created. The 'size' hint + should be a positive integer. The 'rotational' hint should be a + Boolean value. + + :param device: the device dictionary from the node's property. + :returns: a dictionary with the device hints parsed or + None if there are no hints. + :raises: ValueError, if some information is invalid. + + """ + if not device: + return + + device = copy.deepcopy(device) + if validate_all_default_hints: + invalid_hints = set(device) - set(VALID_DEVICE_HINTS) + if invalid_hints: + raise ValueError( + ('The hints "%(invalid_hints)s" are invalid. ' + 'Valid hints are: "%(valid_hints)s"') % { + 'invalid_hints': ', '.join(invalid_hints), + 'valid_hints': ', '.join(VALID_DEVICE_HINTS) + }) + + for name, expression in device.items(): + hint_type = VALID_DEVICE_HINTS[name] + if hint_type is str: + if not isinstance(expression, str): + raise ValueError( + ('Device hint "%(name)s" is not a string value. ' + 'Hint expression: %(expression)s') % { + 'name': name, + 'expression': expression + }) + device[name] = _normalize_hint_expression(expression, name) + + elif hint_type is int: + for v in _extract_hint_operator_and_values(expression, + name)['values']: + try: + integer = int(v) + except ValueError: + raise ValueError( + ('Device hint "%(name)s" is not an integer ' + 'value. Current value: %(expression)s') % { + 'name': name, + 'expression': expression + }) + + if integer <= 0: + raise ValueError( + ('Device hint "%(name)s" should be a positive ' + 'integer. Current value: %(expression)s') % { + 'name': name, + 'expression': expression + }) + + elif hint_type is bool: + try: + device[name] = strutils.bool_from_string( + expression, strict=True) + except ValueError: + raise ValueError( + ('Device hint "%(name)s" is not a Boolean value. ' + 'Current value: %(expression)s') % { + 'name': name, + 'expression': expression + }) + + return _append_operator_to_hints(device) + + +def find_devices_by_hints(devices, + device_hints, + validate_all_default_hints=True): + """Find all devices that match the device hints. + + Try to find devices that match the device hints. In order + for a device to be matched it needs to satisfy all the given hints. + + :param devices: A list of dictionaries representing the devices + containing one or more of the following keys: + + :name: (String) The device name, e.g /dev/sda + :size: (Integer) Size of the device in *bytes* + :model: (String) Device model + :vendor: (String) Device vendor name + :serial: (String) Device serial number + :wwn: (String) Unique storage identifier + :wwn_with_extension: (String): Unique storage identifier with + the vendor extension appended + :wwn_vendor_extension: (String): United vendor storage identifier + :rotational: (Boolean) Whether it's a rotational device or + not. Useful to distinguish HDDs (rotational) and SSDs + (not rotational). + :hctl: (String): The SCSI address: Host, channel, target and lun. + For example: '1:0:0:0'. + :by_path: (String): The alternative device name, + e.g. /dev/disk/by-path/pci-0000:00 + + :param device_hints: A dictionary with the device hints. + :raises: ValueError, if some information is invalid. + :returns: A generator with all matching devices as dictionaries. + """ + LOG.info( + 'Trying to find devices from "%(devs)s" that match the ' + 'device hints "%(hints)s"', { + 'devs': ', '.join([d.get('name') for d in devices]), + 'hints': device_hints + }) + parsed_hints = parse_device_hints(device_hints) + LOG.info("parsed_hints:%s", parsed_hints) + for dev in devices: + device_name = dev.get('name') + + for hint in parsed_hints: + hint_type = VALID_DEVICE_HINTS[hint] + device_value = dev.get(hint) + hint_value = parsed_hints[hint] + + if hint_type is str: + try: + device_value = _normalize_hint_expression( + device_value, hint) + except ValueError: + LOG.warning( + 'The attribute "%(attr)s" of the device "%(dev)s" ' + 'has an empty value. Skipping device.', { + 'attr': hint, + 'dev': device_name + }) + break + + if validate_all_default_hints: + if hint in NOT_VALID_DEVICE_HINTS: + continue + + LOG.info( + 'Trying to match the device hint "%(hint)s" ' + 'with a value of "%(hint_value)s" against the same ' + 'device\'s (%(dev)s) attribute with a value of ' + '"%(dev_value)s"', { + 'hint': hint, + 'dev': device_name, + 'hint_value': hint_value, + 'dev_value': device_value + }) + + # Boolean hints are not supported by + # specs_matcher.match(), so we need to do the comparison + # ourselves + if hint_type is bool: + try: + device_value = strutils.bool_from_string( + device_value, strict=True) + except ValueError: + LOG.warning( + 'The attribute "%(attr)s" (with value ' + '"%(value)s") of device "%(dev)s" is not ' + 'a valid Boolean. Skipping device.', { + 'attr': hint, + 'value': device_value, + 'dev': device_name + }) + break + if device_value == hint_value: + continue + + elif specs_matcher.match(device_value, hint_value): + continue + + LOG.warn( + 'The attribute "%(attr)s" (with value "%(value)s") ' + 'of device "%(dev)s" does not match the hint %(hint)s', { + 'attr': hint, + 'value': device_value, + 'dev': device_name, + 'hint': hint_value + }) + break + else: + LOG.info("yield dev") + yield dev + + +def _extract_hint_operator_and_values(hint_expression, hint_name): + """Extract the operator and value(s) of a device hint expression. + + A device hint expression could contain one or more values + depending on the operator. This method extracts the operator and + value(s) and returns a dictionary containing both. + + :param hint_expression: The hint expression string containing value(s) + and operator (optionally). + :param hint_name: The name of the hint. Used for logging. + :raises: ValueError if the hint_expression is empty. + :returns: A dictionary containing: + + :op: The operator. An empty string in case of None. + :values: A list of values stripped and converted to lowercase. + """ + expression = str(hint_expression).strip().lower() + if not expression: + raise ValueError( + ('Device hint "%s" expression is empty') % hint_name) + + # parseString() returns a list of tokens which the operator (if + # present) is always the first element. + ast = DEVICE_HINTS_GRAMMAR.parseString(expression) + if len(ast) <= 1: + # hint_expression had no operator + return {'op': '', 'values': [expression]} + + op = ast[0] + return { + 'values': [v.strip() for v in re.split(op, expression) if v], + 'op': op + } + + +def _normalize_hint_expression(hint_expression, hint_name): + """Normalize a string type hint expression. + + A string-type hint expression contains one or more operators and + one or more values: [] [ ]*. This normalizes + the values by url-encoding white spaces and special characters. The + operators are not normalized. For example: the hint value of " + foo bar bar" will become " foo%20bar bar". + + :param hint_expression: The hint expression string containing value(s) + and operator (optionally). + :param hint_name: The name of the hint. Used for logging. + :raises: ValueError if the hint_expression is empty. + :returns: A normalized string. + """ + hdict = _extract_hint_operator_and_values(hint_expression, hint_name) + result = hdict['op'].join( + [' %s ' % pathname2url(t) for t in hdict['values']]) + return (hdict['op'] + result).strip() + + +def _append_operator_to_hints(device): + """Add an equal (s== or ==) operator to the hints. + + For backwards compatibility, for device hints where no operator + means equal, this method adds the equal operator to the hint. This is + needed when using oslo.utils.specs_matcher methods. + + :param device: The device hints dictionary. + """ + for name, expression in device.items(): + # The specs_matcher does not support boolean, + # so we don't need to append any operator for it. + if VALID_DEVICE_HINTS[name] is bool: + continue + + expression = str(expression) + ast = DEVICE_HINTS_GRAMMAR.parseString(expression) + if len(ast) > 1: + continue + + op = 's== %s' if VALID_DEVICE_HINTS[name] is str else '== %s' + device[name] = op % expression + + return device diff --git a/bmp-agent/bmpa/utils/disk_partitioner.py b/bmp-agent/bmpa/utils/disk_partitioner.py new file mode 100644 index 0000000..2d54a1e --- /dev/null +++ b/bmp-agent/bmpa/utils/disk_partitioner.py @@ -0,0 +1,205 @@ + +import logging + +from bmpa.errors import BmpError +from bmpa.utils import executor +from bmpa.utils import hardware + +LOG = logging.getLogger(__name__) + +ALL_UNALLOCATED_SPACE = 999999999 + + +class DiskPartitioner(object): + def __init__(self, + device, + disk_label='msdos', + alignment='optimal', + start=1): + """A convenient wrapper around the parted tool. + + :param device: The device path. + :param disk_label: The type of the partition table. Valid types are: + "bsd", "dvh", "gpt", "loop", "mac", "msdos", + "pc98", or "sun". + :param alignment: Set alignment for newly created partitions. + Valid types are: none, cylinder, minimal and + optimal. + + """ + self._device = device + self._disk_label = disk_label + self._alignment = alignment + self._partitions = [] + self.start = start + + def _exec(self, *args): + executor.execute('parted', + '-a', + self._alignment, + '-s', + self._device, + '--', + 'unit', + 'MiB', + *args, + check_exit_code=[0], + use_standard_locale=True, + run_as_root=True) + + def add_partition(self, + size, + part_type='primary', + fs_type='', + boot_flag=None, + extra_flags=None): + """Add a partition. + + :param size: The size of the partition in MiB. + :param part_type: The type of the partition. Valid values are: + primary, logical, or extended. + :param fs_type: The filesystem type. Valid types are: ext2, fat32, + fat16, HFS, linux-swap, NTFS, reiserfs, ufs. + If blank (''), it will create a Linux native + partition (83). + :param boot_flag: Boot flag that needs to be configured on the + partition. Ignored if None. It can take values + 'bios_grub', 'boot'. + :param extra_flags: List of flags to set on the partition. Ignored + if None. + :returns: The partition number. + + """ + if part_type is None: + part_type = 'primary' + if fs_type is None: + fs_type = '' + self._partitions.append({ + 'size': size, + 'type': part_type, + 'fs_type': fs_type, + 'boot_flag': boot_flag, + 'extra_flags': extra_flags + }) + return len(self._partitions) + + def get_partitions(self): + """Get the partitioning layout. + + :returns: An iterator with the partition number and the + partition layout. + + """ + return enumerate(self._partitions, 1) + + def commit(self): + """Write to the disk.""" + LOG.debug("Committing partitions to disk.") + if self._disk_label is not None: + cmd_args = ['mklabel', self._disk_label] + else: + cmd_args = [] + # Lead in with 1MiB to allow room for the + # partition table itself. + start = self.start + for num, part in self.get_partitions(): + if part['size'] == ALL_UNALLOCATED_SPACE: + end = "100%" + else: + end = start + part['size'] + cmd_args.extend([ + 'mkpart', part['type'], part['fs_type'], + str(start), + str(end) + ]) + if part['boot_flag']: + cmd_args.extend(['set', str(num), part['boot_flag'], 'on']) + if part['extra_flags']: + for flag in part['extra_flags']: + cmd_args.extend(['set', str(num), flag, 'on']) + start = end + + self._exec(*cmd_args) + + try: + hardware.wait_for_disk_to_become_available( + self._device) + except BmpError as e: + raise BmpError( + ('Disk partitioning failed on device %(device)s. ' + 'Error: %(error)s') % { + 'device': self._device, + 'error': e + }) + + +def make_partitions(device_name, + partitions, + boot_mode="bios", + disk_label=None, + start=1, + exist_part_num=0): + """Partition the disk device. + + Create partitions for root, boot and system partitions on a disk device. + + :param device_name: Path for the device to work on. + :param partitions: partitions. + :param boot_mode: bios or uefi. + param disk_label: gpt or None. + param start: partition start Mib. + :returns: A dictionary containing the partition type as Key and partition + path as Value for the partitions created by this method. + + """ + LOG.debug("Starting to partition the disk device: %(device_name)s ", + {'device_name': device_name}) + part_dict = {} + + # prevent resetting partitions when adding new partitions to existing ones + if disk_label is None and exist_part_num == 0: + disk_label = 'gpt' if boot_mode == 'uefi' else 'msdos' + + dp = DiskPartitioner(device_name, + disk_label=disk_label, + start=start) + + for partion in partitions: + LOG.debug("Add partition (%(size)d MiB) to device: %(dev)s ", { + 'dev': device_name, + 'size': partion['size'] + }) + part_type = partion.get('partion', None) + fs_type = partion.get('fs_type', None) + if fs_type == 'swap': + fs_type = 'linux-swap' + boot_flag = partion.get('boot_flag', None) + extra_flags = partion.get('extra_flags', None) + part_num = dp.add_partition( + partion['size'], part_type, fs_type, boot_flag, extra_flags) + exist_part_num + part_dict[partion['id']] = partition_index_to_path( + device_name, part_num) + + dp.commit() + hardware.trigger_device_rescan(device_name) + return part_dict + + +def partition_index_to_path(device_name: str, index: int): + """Guess a partition path based on its device and index. + + :param device_name: Device path. + :param index: Partition index. + """ + if is_last_char_digit(device_name): + part_template = '%sp%d' + else: + part_template = '%s%d' + return part_template % (device_name, index) + + +def is_last_char_digit(device_name): + """check whether device name ends with a digit""" + if len(device_name) >= 1: + return device_name[-1].isdigit() + return False diff --git a/bmp-agent/bmpa/utils/encode.py b/bmp-agent/bmpa/utils/encode.py new file mode 100755 index 0000000..c196a2e --- /dev/null +++ b/bmp-agent/bmpa/utils/encode.py @@ -0,0 +1,12 @@ +def to_utf8(text): + """Encode Unicode to UTF-8, return bytes unchanged. + + Raise TypeError if text is not a bytes string or a Unicode string. + """ + if isinstance(text, bytes): + return text + elif isinstance(text, str): + return text.encode('utf-8') + else: + raise TypeError('bytes or Unicode expected, got %s' % + type(text).__name__) diff --git a/bmp-agent/bmpa/utils/executor.py b/bmp-agent/bmpa/utils/executor.py new file mode 100755 index 0000000..76bf836 --- /dev/null +++ b/bmp-agent/bmpa/utils/executor.py @@ -0,0 +1,250 @@ +import logging +import os +import subprocess +import time + +from bmpa.utils import encode + +LOG = logging.getLogger(__name__) + + +class UnknownArgumentError(Exception): + + def __init__(self, message=None): + super(UnknownArgumentError, self).__init__(message) + + +class ProcessExecutionError(Exception): + + def __init__(self, + stdout=None, + stderr=None, + exit_code=None, + cmd=None, + description=None): + super(ProcessExecutionError, self).__init__(stdout, stderr, exit_code, + cmd, description) + self.stdout = stdout + self.stderr = stderr + self.exit_code = exit_code + self.cmd = cmd + self.description = description + + def __str__(self): + description = self.description + if description is None: + description = "Unexpected error while running command." + + exit_code = self.exit_code + if exit_code is None: + exit_code = '-' + + message_param = { + 'description': description, + 'cmd': self.cmd, + 'exit_code': exit_code, + 'stdout': self.stdout + } + message = ('%(description)s\n' + 'Command: %(cmd)s\n' + 'Exit code: %(exit_code)s\n' + 'Stdout: %(stdout)r') % message_param + return message + + +class NoRootPermissionError(ProcessExecutionError): + + def __init__(self, **kwargs): + super(NoRootPermissionError, self).__init__(**kwargs) + + +def try_execute(*cmd, **kwargs): + """The same as execute but returns None on error. + + Instead of raising an exception on failure, this method simply + returns None in case of failure. + + :param *cmd: positional arguments to pass to execute() + :param **kwargs: keyword arguments to pass to processutils.execute() + :raises: UnknownArgumentException on receiving unknown arguments + :returns: tuple of (stdout, stderr) or None in some error cases + """ + try: + return execute(*cmd, **kwargs) + except (ProcessExecutionError, OSError) as e: + LOG.info('Command failed: %s', e) + + +def execute(*cmd, **kwargs): + """Helper method to shell out and execute a command through subprocess. + + Allows optional. + + :param cmd: Passed to subprocess.Popen. + :type cmd: string + + :param cwd: Set the current working directory + :type cwd: string + + :param target: Chroot dir + :type target: string + + :type std_input: string or bytes + + :param env_variables: Environment variables and their values that + will be set for the process. + :type env_variables: dict + + :param check_exit_code: Single bool, int, or list of allowed exit + codes. Defaults to [0]. Raise + :class:`ProcessExecutionException` unless + program exits with one of these code. + :type check_exit_code: boolean, int, or [int] + + + :param delay_on_retry: True | False. Defaults to True. If set to True, + wait a short amount of time before retrying. + :type delay_on_retry: boolean + + :param attempts_times: How many times to retry cmd. + :type attempts_times: int + + :param run_as_root: True | False. Defaults to False. If set to True, + the command is prefixed by the command specified + in the root_helper kwarg. + :type run_as_root: boolean + + :param shell: whether or not there should be a shell used to + execute this command. Defaults to True. + :type shell: boolean + + :param binary: On Python 3, return stdout and stderr as bytes if + binary is True, as Unicode otherwise. + :type binary: boolean + + :param use_standard_locale: keyword-only argument. True | False. + Defaults to True. If set to True, + execute command with standard locale + added to environment variables. + :type boolean + + :returns: (status, stdout, stderr) from process execution + """ + + target = kwargs.pop('target', '/') + chroot_args = [] if target == '/' else ['chroot', target] + cmd = [str(c) for c in cmd] + cmd = chroot_args + cmd + cmd_text = ' '.join(cmd) + use_standard_locale = kwargs.pop('use_standard_locale', True) + if use_standard_locale: + environ = os.environ.copy() + environ['PATH'] = '%s:/bin' % environ['PATH'] + env = kwargs.pop('env_variables', environ) + env['LC_ALL'] = 'C' + kwargs['env_variables'] = env + + cwd = kwargs.pop('cwd', None) + + std_input = kwargs.pop('std_input', None) + if std_input is not None: + std_input = encode.to_utf8(std_input) + + env_variables = kwargs.pop('env_variables', None) + + ignore_exit_code = False + check_exit_code = kwargs.pop('check_exit_code', [0]) + if isinstance(check_exit_code, bool): + ignore_exit_code = not check_exit_code + check_exit_code = [0] + elif isinstance(check_exit_code, int): + check_exit_code = [check_exit_code] + + delay_on_retry = kwargs.pop('delay_on_retry', True) + + attempts_times = kwargs.pop('attempts_times', 1) + + run_as_root = kwargs.pop('run_as_root', False) + if run_as_root and hasattr(os, 'geteuid') and os.geteuid() != 0: + raise NoRootPermissionError( + cmd=cmd_text, + description='Command requested root, but did not ' + 'specify a root helper.') + + shell = kwargs.pop('shell', False) + + binary = kwargs.pop('binary', False) + + if kwargs: + raise UnknownArgumentError('Got unknown keyword args: %r' % kwargs) + + temp_attempts_times = attempts_times + while temp_attempts_times > 0: + temp_attempts_times -= 1 + + LOG.info("ready to run %s", cmd_text) + try: + _PIPE = subprocess.PIPE + obj = subprocess.Popen(cmd, + stdin=_PIPE, + stdout=_PIPE, + stderr=subprocess.STDOUT, + close_fds=True, + preexec_fn=None, + shell=shell, + cwd=cwd, + env=env_variables) + result = obj.communicate(std_input) + obj.stdin.close() + _returncode = obj.returncode + if not ignore_exit_code and _returncode not in check_exit_code: + (stdout, stderr) = result + stdout = os.fsdecode(stdout) if stdout is not None else None + stderr = os.fsdecode(stderr) if stderr is not None else None + raise ProcessExecutionError(exit_code=_returncode, + stdout=stdout, + stderr=stderr, + cmd=cmd) + if not binary and result is not None: + (stdout, stderr) = result + # Decode from the locale using using the surrogateescape error + # handler (decoding cannot fail) + stdout = os.fsdecode(stdout) if stdout is not None else None + stderr = os.fsdecode(stderr) if stderr is not None else None + return (stdout, stderr) + else: + return result + except (ProcessExecutionError, OSError) as e: + if isinstance(e, ProcessExecutionError): + LOG.error( + "%(desc)r\ncommand: %(cmd)r\nexit code: %(code)r\n' \ + stdout: %(stdout)r\n" % { + "desc": e.description, + "cmd": e.cmd, + "code": e.exit_code, + "stdout": e.stdout + }) + else: + LOG.error( + 'Got an OSError, command: %(cmd)r, errno: %(errno)r' % { + "cmd": cmd_text, + "errno": e.strerror + }) + if delay_on_retry and temp_attempts_times > 0: + attempts_period = 0.5 * 2**(attempts_times - + temp_attempts_times) + LOG.info("retry to run `%s` after %.2f seconds" % + (cmd, attempts_period)) + time.sleep(attempts_period) + continue + raise + + finally: + # this appears to be necessary to let the subprocess + # call clean something up in between calls, without + # it two execute calls in a row hangs the second one + # Above is probably specific to the eventlet subprocess + # module eventlet subprocess module, but since we still + # have to support that we're leaving the sleep. It won't + # hurt anything in the stdlib case anyway. + time.sleep(0) diff --git a/bmp-agent/bmpa/utils/file.py b/bmp-agent/bmpa/utils/file.py new file mode 100644 index 0000000..35cced8 --- /dev/null +++ b/bmp-agent/bmpa/utils/file.py @@ -0,0 +1,20 @@ +import hashlib +import os + + +def ensure_dir(path, mode=None): + if path == "": + path = "." + if not os.path.exists(path): + os.makedirs(path) + + if mode is not None: + os.chmod(path, mode) + + +def md5sum(path): + hashlib_md5 = hashlib.md5() + with open(path, 'rb') as f: + for chunk in iter(lambda: f.read(4096), b""): + hashlib_md5.update(chunk) + return hashlib_md5.hexdigest() diff --git a/bmp-agent/bmpa/utils/hardware.py b/bmp-agent/bmpa/utils/hardware.py new file mode 100644 index 0000000..4933cc8 --- /dev/null +++ b/bmp-agent/bmpa/utils/hardware.py @@ -0,0 +1,1568 @@ +from contextlib import contextmanager +import errno +import json +import logging +import os +import platform +import re +import shlex +import stat +import sys +import time + +import netaddr +import pint +import psutil +import pyudev +import tenacity + +from bmpa import constants +from bmpa.errors import BlockDeviceError, BmpError, BlockDeviceEraseError +from bmpa.serialize import SerializableComparable +from bmpa.utils import executor +from bmpa.utils.executor import ProcessExecutionError, UnknownArgumentError +from bmpa.utils import multipath +from bmpa.utils import system +from bmpa.utils import utils + + +LOG = logging.getLogger(__name__) + +EFI_SYSTEM_PARTITION_SIZE = 512 +BISO_BOOT_PARTITION_SIZE = 1 + +NVME_CLI_FORMAT_SUPPORTED_FLAG = 0b10 +NVME_CLI_CRYPTO_FORMAT_SUPPORTED_FLAG = 0b100 + +GPT_SIZE_SECTORS = 33 + +SECTOR_SIZE_BYTES = 512 + + +class BlockDevice(SerializableComparable): + serializable_fields = ('name', 'model', 'size', 'rotational', 'wwn', + 'serial', 'vendor', 'wwn_with_extension', + 'wwn_vendor_extension', 'hctl', 'by_path') + + def __init__(self, + name, + model, + size, + rotational, + wwn=None, + serial=None, + vendor=None, + wwn_with_extension=None, + wwn_vendor_extension=None, + hctl=None, + by_path=None): + self.name = name + self.model = model + self.size = size + self.rotational = rotational + self.wwn = wwn + self.serial = serial + self.vendor = vendor + self.wwn_with_extension = wwn_with_extension + self.wwn_vendor_extension = wwn_vendor_extension + self.hctl = hctl + self.by_path = by_path + + def __repr__(self): + return "BlockDevice %s" % self.serialize() + + +def list_all_block_devices(block_type='disk'): + """List all physical block devices + + The switches we use for lsblk: P for KEY="value" output, b for size output + in bytes, d to exclude dependent devices (like md or dm devices), i to + ensure ascii characters only, and o to specify the fields/columns we need. + + Broken out as its own function to facilitate custom hardware managers that + don't need to subclass GenericHardwareManager. + + :param block_type: Type of block device to find + :return: A list of BlockDevices + """ + udev_settle() + + # map device names to /dev/disk/by-path symbolic links that points to it + + by_path_mapping = {} + + disk_by_path_dir = '/dev/disk/by-path' + + try: + paths = os.listdir(disk_by_path_dir) + + for path in paths: + path = os.path.join(disk_by_path_dir, path) + # Turn possibly relative symbolic link into absolute + devname = os.path.join(disk_by_path_dir, os.readlink(path)) + devname = os.path.abspath(devname) + by_path_mapping[devname] = path + + except OSError as e: + LOG.warning( + "Path %(path)s is inaccessible, /dev/disk/by-path/* " + "version of block device name is unavailable " + "Cause: %(error)s", { + 'path': disk_by_path_dir, + 'error': e + }) + + columns = ['KNAME', 'MODEL', 'SIZE', 'ROTA', 'TYPE'] + report = executor.execute('lsblk', + '-Pbdi', + '-o{}'.format(','.join(columns)), + check_exit_code=[0])[0] + lines = report.split('\n') + context = pyudev.Context() + + devices = [] + for line in lines: + if line == '': + continue + device = {} + # Split into KEY=VAL pairs + vals = shlex.split(line) + for key, val in (v.split('=', 1) for v in vals): + device[key] = val.strip() + # Ignore block types not specified + if device.get('TYPE') != block_type: + LOG.warn( + "TYPE did not match. Wanted: {!r} but found: {!r}", + block_type, line) + continue + + # Ensure all required columns are at least present, even if blank + missing = set(columns) - set(device) + if missing: + raise BlockDeviceError( + '%s must be returned by lsblk.' % ', '.join(sorted(missing))) + + name = os.path.join('/dev', device['KNAME']) + + try: + udev = pyudev.Device.from_device_file(context, name) + # pyudev started raising another error in 0.18 + except (ValueError, EnvironmentError, pyudev.DeviceNotFoundError) as e: + LOG.warning( + "Device %(dev)s is inaccessible, skipping... " + "Error: %(error)s", { + 'dev': name, + 'error': e + }) + extra = {} + else: + # Since lsblk only supports + # returning the short serial we are using + # ID_SERIAL_SHORT here to keep compatibility with the + # bash deploy ramdisk + extra = { + key: udev.get('ID_%s' % udev_key) + for key, udev_key in [('wwn', 'WWN'), ( + 'serial', 'SERIAL_SHORT' + ), ('wwn_with_extension', 'WWN_WITH_EXTENSION' + ), ('wwn_vendor_extension', 'WWN_VENDOR_EXTENSION')] + } + + # Newer versions of the lsblk tool supports + # HCTL as a parameter but let's get it from sysfs to avoid breaking + # old distros. + try: + extra['hctl'] = os.listdir('/sys/block/%s/device/scsi_device' % + device['KNAME'])[0] + except (OSError, IndexError): + LOG.warning( + 'Could not find the SCSI address (HCTL) for ' + 'device %s. Skipping', name) + + # Not all /dev entries are pointed to from /dev/disk/by-path + by_path_name = by_path_mapping.get(name) + + devices.append( + BlockDevice(name=name, + model=device['MODEL'], + size=int(device['SIZE']), + rotational=bool(int(device['ROTA'])), + vendor=get_device_info( + device['KNAME'], 'block', 'vendor'), + by_path=by_path_name, + **extra)) + return devices + + +def udev_settle(): + """Wait for the udev event queue to settle. + + Wait for the udev event queue to settle to make sure all devices + are detected once the machine boots up. + + :return: True on success, False otherwise. + """ + LOG.info('Waiting until udev event queue is empty') + try: + executor.execute('udevadm', 'settle') + except ProcessExecutionError as e: + LOG.warning( + 'Something went wrong when waiting for udev ' + 'to settle. Error: %s', e) + return False + else: + return True + + +def _lsblock(args=None): + """Get lsblock data as dict.""" + # lsblk --help | sed -n '/Available/,/^$/p' | + # sed -e 1d -e '$d' -e 's,^[ ]\+,,' -e 's, .*,,' | sort + keys = ['ALIGNMENT', 'DISC-ALN', 'DISC-GRAN', 'DISC-MAX', 'DISC-ZERO', + 'FSTYPE', 'GROUP', 'KNAME', 'LABEL', 'LOG-SEC', 'MAJ:MIN', + 'MIN-IO', 'MODE', 'MODEL', 'MOUNTPOINT', 'NAME', 'OPT-IO', 'OWNER', + 'PHY-SEC', 'RM', 'RO', 'ROTA', 'RQ-SIZE', 'SCHED', 'SIZE', 'STATE', + 'TYPE', 'UUID'] + if args is None: + args = [] + args = [x.replace('!', '/') for x in args] + + # in order to avoid a very odd error with '-o' and all output fields above + # we just drop one. doesn't really matter which one. + keys.remove('SCHED') + basecmd = ['lsblk', '--noheadings', '--bytes', '--pairs', + '--output=' + ','.join(keys)] + out, _ = executor.execute(basecmd + list(args)) + out = out.replace('!', '/') + return _lsblock_pairs_to_dict(out) + + +def _lsblock_pairs_to_dict(lines): + """Parse lsblock output and convert to dict.""" + ret = {} + for line in lines.splitlines(): + toks = shlex.split(line) + cur = {} + for tok in toks: + k, v = tok.split("=", 1) + if k == 'MAJ_MIN': + k = 'MAJ:MIN' + else: + k = k.replace('_', '-') + cur[k] = v + # use KNAME, as NAME may include spaces and other info, + # for example, lvm decices may show 'dm0 lvm1' + cur['device_path'] = get_dev_name_entry(cur['KNAME'])[1] + ret[cur['KNAME']] = cur + return ret + + +def get_dev_name_entry(devname): + """Convert device name to path in /dev.""" + bname = devname.split('/dev/')[-1] + return (bname, "/dev/" + bname) + + +def get_unused_blockdev_info(): + """return a list of unused block devices. + + These are devices that do not have anything mounted on them. + """ + + # get a list of top level block devices, then iterate over it to get + # devices dependent on those. If the lsblk call for that specific + # call has nothing 'MOUNTED", then this is an unused block device + bdinfo = _lsblock(['--nodeps']) + unused = {} + for devname, data in bdinfo.items(): + cur = _lsblock([data['device_path']]) + mountpoints = [x for x in cur if cur[x].get('MOUNTPOINT')] + if len(mountpoints) == 0: + unused[devname] = data + return unused + + +def rescan_block_devices(devices=None, warn_on_fail=True): + """Run 'blockdev --rereadpt' for all block devices not currently mounted.""" + if not devices: + unused = get_unused_blockdev_info() + devices = [] + for devname, data in unused.items(): + if data.get('RM') == "1": + continue + if data.get('RO') != "0" or data.get('TYPE') != "disk": + continue + devices.append(data['device_path']) + + if not devices: + LOG.info("no devices found to rescan") + return + + # blockdev needs /dev/ parameters, convert if needed + cmd = ['blockdev', '--rereadpt'] + [dev if dev.startswith('/dev/') + else sysfs_to_devpath(dev) + for dev in devices] + try: + executor.execute(*cmd) + except ProcessExecutionError as e: + if warn_on_fail: + # FIXME: its less than ideal to swallow this error, but until + # we fix LP: #1489521 we kind of need to. + LOG.warn( + "Error rescanning devices, possibly known issue LP: #1489521") + # Reformatting the exception output so as to not trigger + # vmtest scanning for Unexepected errors in install logfile + LOG.warn("cmd: %s\nstdout:%s\nstderr:%s\nexit_code:%s", e.cmd, + e.stdout, e.stderr, e.exit_code) + + udev_settle() + + return + + +class SystemVendorInfo(SerializableComparable): + + serializable_fields = ('product_name', 'serial_number', 'manufacturer') + + def __init__(self, product_name, serial_number, manufacturer): + self.product_name = product_name + self.serial_number = serial_number + self.manufacturer = manufacturer + + def __repr__(self): + return "SystemVendorInfo %s" % self.serialize() + + +def get_system_vendor_info(): + try: + cmd = ['dmidecode', '-t', 'system'] + lines = executor.execute(*cmd)[0] + system_vendor_info = { + k.strip().lower(): v.strip() + for k, v in (line.split(':', 1) for line in lines.split('\n') + if (line.strip() and line.count(":") == 1)) + } + except (ProcessExecutionError, OSError, ValueError) as e: + LOG.warning('Could not retrieve vendor info from dmidecode: %e', e) + system_vendor_info = {} + return SystemVendorInfo( + product_name=system_vendor_info.get('product name', ''), + serial_number=system_vendor_info.get('serial number', ''), + manufacturer=system_vendor_info.get('manufacturer', '')) + + +def shred_block_device(device_name): + """Erase a block device using shred. + + :param node: Ironic node info. + :param block_device: a BlockDevice object to be erased + :returns: True if the erase succeeds, False if it fails for any reason + """ + try: + if is_nvme_device(device_name): + _nvme_erase(device_name) + return True + + except BlockDeviceEraseError: + pass + + try: + executor.execute('shred', '--force', '--zero', '--verbose', + '--iterations=0', '--size=100M', + device_name) + except (ProcessExecutionError, OSError) as e: + msg = "Erasing block device %(device_name)s failed with error %(err)s" + LOG.error(msg, {'device_name': device_name, 'err': e}) + return False + + return True + + +def erase_block_device(device_name): + if shred_block_device(device_name): + return + + msg = 'Unable to erase block device %(device_name)s: device is unsupported.' % { + 'device_name': device_name + } + LOG.error(msg) + raise BmpError(msg) + + +def _nvme_erase(device_name): + """Attempt to clean the NVMe using the most secure supported method + + :param block_device: a BlockDevice object + :return: True if cleaning operation succeeded, False if it failed + :raises: BlockDeviceEraseError + """ + + # check if crypto format is supported + try: + LOG.info("Attempting to fetch NVMe capabilities for device %s", + device_name) + nvme_info, _e = executor.execute('nvme', 'id-ctrl', + device_name, '-o', 'json') + nvme_info = json.loads(nvme_info) + + except ProcessExecutionError as e: + msg = (("Failed to fetch NVMe capabilities for device {}: {}").format( + device_name, e)) + LOG.error(msg) + raise BlockDeviceEraseError(msg) + + # execute format with crypto option (ses=2) if supported + # if crypto is unsupported use user-data erase (ses=1) + if nvme_info: + # Check if the device supports NVMe format at all. This info + # is in "oacs" section of nvme-cli id-ctrl output. If it does, + # set format mode to 1 (this is passed as -s parameter + # to nvme-cli later) + fmt_caps = nvme_info['oacs'] + if fmt_caps & NVME_CLI_FORMAT_SUPPORTED_FLAG: + # Given the device supports format, check if crypto + # erase format mode is supported and pass it to nvme-cli + # instead + crypto_caps = nvme_info['fna'] + if crypto_caps & NVME_CLI_CRYPTO_FORMAT_SUPPORTED_FLAG: + format_mode = 2 # crypto erase + else: + format_mode = 1 # user-data erase + else: + msg = ('nvme-cli did not return any supported format modes ' + 'for device: {device}').format(device=device_name) + LOG.error(msg) + raise BlockDeviceEraseError(msg) + else: + # If nvme-cli output is empty, raise an exception + msg = ('nvme-cli did not return any information ' + 'for device: {device}').format(device=device_name) + LOG.error(msg) + raise BlockDeviceEraseError(msg) + + try: + LOG.debug( + "Attempting to nvme-format %s using secure format mode " + "(ses) %s", device_name, format_mode) + executor.execute('nvme', 'format', device_name, '-s', + format_mode) + LOG.info( + "nvme-cli format for device %s (ses= %s ) completed " + "successfully.", device_name, format_mode) + return True + + except ProcessExecutionError as e: + msg = (("Failed to nvme format device {}: {}").format(device_name, e)) + raise BlockDeviceEraseError(msg) + + +def wait_for_disk_to_become_available(device): + """Wait for a disk device to become available. + + Waits for a disk device to become available for use by + waiting until all process locks on the device have been + released. + + Timeout and iteration settings come from the configuration + options used by the in-library disk_partitioner: + ``check_device_interval`` and ``check_device_max_retries``. + + :params device: The path to the device. + :raises: IronicException If the disk fails to become + available. + """ + pids = [''] + stderr = [''] + interval = 1 + max_retries = 20 + + def _wait_for_disk(): + # A regex is likely overkill here, but variations in fuser + # means we should likely use it. + fuser_pids_re = re.compile(r'\d+') + + # There are 'psmisc' and 'busybox' versions of the 'fuser' program. The + # 'fuser' programs differ in how they output data to stderr. The + # busybox version does not output the filename to stderr, while the + # standard 'psmisc' version does output the filename to stderr. How + # they output to stdout is almost identical in that only the PIDs are + # output to stdout, with the 'psmisc' version adding a leading space + # character to the list of PIDs. + try: + # fuser returns a non-zero return code if none of + # the specified files is accessed. + # user does not report LVM devices as in use + # unless the LVM device-mapper device is the + # device that is directly polled. + # The -m flag allows fuser to reveal data about + # mounted filesystems, which should be considered + # busy/locked. That being said, it is not used + # because busybox fuser has a different behavior. + # fuser outputs a list of found PIDs to stdout. + # All other text is returned via stderr, and the + # output to a terminal is merged as a result. + out, err = executor.execute('fuser', + device, + check_exit_code=[0, 1], + run_as_root=True) + + if not out and not err: + return True + + stderr[0] = err + # findall() returns a list of matches, or an empty list if no matches + pids[0] = fuser_pids_re.findall(out) + + except ProcessExecutionError as exc: + LOG.warning( + 'Failed to check the device %(device)s with fuser:' + ' %(err)s', { + 'device': device, + 'err': exc + }) + return False + + retry = tenacity.retry(retry=tenacity.retry_if_result(lambda r: not r), + stop=tenacity.stop_after_attempt(max_retries), + wait=tenacity.wait_fixed(interval), + reraise=True) + try: + retry(_wait_for_disk)() + except tenacity.RetryError: + if pids[0]: + raise BmpError( + ('Processes with the following PIDs are holding ' + 'device %(device)s: %(pids)s. ' + 'Timed out waiting for completion.') % { + 'device': device, + 'pids': ', '.join(pids[0]) + }) + else: + raise BmpError( + ('Fuser exited with "%(fuser_err)s" while checking ' + 'locks for device %(device)s. Timed out waiting for ' + 'completion.') % { + 'device': device, + 'fuser_err': stderr[0] + }) + + +def get_dev_block_size(dev): + """Get the device size in 512 byte sectors.""" + block_sz, _ = executor.execute('blockdev', + '--getsz', + dev, + run_as_root=True, + check_exit_code=[0]) + return int(block_sz) + + +def destroy_disk_metadata(dev): + """Destroy metadata structures on node's disk. + + Ensure that node's disk magic strings are wiped without zeroing the + entire drive. To do this we use the wipefs tool from util-linux. + :param dev: Path for the device to work on. + """ + LOG.debug("Start destroy disk metadata .") + try: + executor.execute('wipefs', + '--force', + '--all', + dev, + run_as_root=True, + use_standard_locale=True) + except ProcessExecutionError as e: + # Check if --force option is supported for wipefs, + # if not, we should try without it. + if '--force' in str(e): + executor.execute('wipefs', '--all', dev) + + # Overwrite the Primary GPT, catch very small partitions (like EBRs) + dd_device = 'of=%s' % dev + dd_count = 'count=%s' % GPT_SIZE_SECTORS + dev_size = get_dev_block_size(dev) + LOG.info("dev size %s", dev_size) + if dev_size < GPT_SIZE_SECTORS: + dd_count = 'count=%s' % dev_size + executor.execute('dd', + 'bs=512', + 'if=/dev/zero', + dd_device, + dd_count, + run_as_root=True, + use_standard_locale=True) + + # Overwrite the Secondary GPT, do this only if there could be one + if dev_size > GPT_SIZE_SECTORS: + gpt_backup = dev_size - GPT_SIZE_SECTORS + dd_seek = 'seek=%i' % gpt_backup + dd_count = 'count=%s' % GPT_SIZE_SECTORS + executor.execute('dd', + 'bs=512', + 'if=/dev/zero', + dd_device, + dd_count, + dd_seek, + run_as_root=True, + use_standard_locale=True) + + # Go ahead and let sgdisk run as well. + executor.execute('sgdisk', + '-Z', + dev, + run_as_root=True, + use_standard_locale=True) + + try: + wait_for_disk_to_become_available(dev) + except BmpError as e: + raise BmpError( + ('Destroying metadata failed on device %(device)s. ' + 'Error: %(error)s') % { + 'device': dev, + 'error': e + }) + + LOG.info("Disk metadata on %(dev)s successfully destroyed ", + {'dev': dev}) + + +def is_nvme_device(device_name): + """Check whether the device path belongs to an NVMe drive.""" + return "/dev/nvme" in device_name + + +def is_block_device(dev): + """Check whether a device is block or not.""" + attempts = 3 + for attempt in range(attempts): + try: + s = os.stat(dev) + except OSError as e: + LOG.warn( + "Unable to stat device %(dev)s. Attempt %(attempt)d " + "out of %(total)d. Error: %(err)s", { + "dev": dev, + "attempt": attempt + 1, + "total": attempts, + "err": e + }) + time.sleep(1) + else: + return stat.S_ISBLK(s.st_mode) + msg = ("Unable to stat device %(dev)s after attempting to verify " + "%(attempts)d times.") % { + 'dev': dev, + 'attempts': attempts + } + LOG.error(msg) + raise BmpError(msg) + + +def partprobe(device, attempts=None): + """Probe partitions on the given device. + + :param device: The block device containing paritions that is attempting + to be updated. + :param attempts: Number of attempts to run partprobe, the default is read + from the configuration. + :return: True on success, False otherwise. + """ + if attempts is None: + attempts = 3 + + try: + executor.execute('partprobe', + device, + run_as_root=True, + attempts_times=attempts) + except (UnknownArgumentError, ProcessExecutionError, OSError) as e: + LOG.warning( + "Unable to probe for partitions on device %(device)s, " + "the partitioning table may be broken. Error: %(error)s", { + 'device': device, + 'error': e + }) + return False + else: + return True + + +def trigger_device_rescan(device, attempts=None): + """Sync and trigger device rescan. + + Disk partition performed via parted, when performed on a ramdisk + do not have to honor the fsync mechanism. In essence, fsync is used + on the file representing the block device, which falls to the kernel + filesystem layer to trigger a sync event. On a ramdisk using ramfs, + this is an explicit non-operation. + + As a result of this, we need to trigger a system wide sync operation + which will trigger cache to flush to disk, after which partition changes + should be visible upon re-scan. + + When ramdisks are not in use, this also helps ensure that data has + been safely flushed across the wire, such as on iscsi connections. + + :param device: The block device containing paritions that is attempting + to be updated. + :param attempts: Number of attempts to run partprobe, the default is read + from the configuration. + :return: True on success, False otherwise. + """ + LOG.info('Explicitly calling sync to force buffer/cache flush') + executor.execute('sync') + # Make sure any additions to the partitioning are reflected in the + # kernel. + udev_settle() + partprobe(device, attempts=attempts) + try: + # Also verify that the partitioning is correct now. + executor.execute('sgdisk', '-v', device, run_as_root=True) + except ProcessExecutionError as exc: + LOG.warning( + 'Failed to verify partition tables on device %(dev)s: ' + '%(err)s', { + 'dev': device, + 'err': exc + }) + return False + else: + return True + + +def get_device_info(dev, devclass, field): + """Get the device info according to device class and field.""" + try: + devname = os.path.basename(dev) + with open('/sys/class/%s/%s/device/%s' % (devclass, devname, field), + 'r') as f: + return f.read().strip() + except IOError: + LOG.warning("Can't find field %(field)s for " + "device %(dev)s in device class %(class)s", + {'field': field, 'dev': dev, 'class': devclass}) + + +def get_blockdev_for_partition(devpath, strict=True): + """Find the parent device for a partition. + + returns a tuple of the parent block device and the partition number + if device is not a partition, None will be returned for partition number + """ + # normalize path + rpath = os.path.realpath(devpath) + + # convert an entry in /dev/ to parent disk and partition number + # if devpath is a block device and not a partition, return (devpath, None) + base = '/sys/class/block' + + # input of /dev/vdb, /dev/disk/by-label/foo, /sys/block/foo, + # /sys/block/class/foo, or just foo + syspath = os.path.join(base, path_to_kname(devpath)) + + # don't need to try out multiple sysfs paths as path_to_kname handles cciss + if strict and not os.path.exists(syspath): + raise OSError("%s had no syspath (%s)" % (devpath, syspath)) + + if rpath.startswith('/dev/dm-'): + parent_info = multipath.mpath_partition_to_mpath_id_and_partnumber( + rpath) + if parent_info is not None: + mpath_id, ptnum = parent_info + return os.path.realpath('/dev/mapper/' + mpath_id), ptnum + + ptpath = os.path.join(syspath, "partition") + if not os.path.exists(ptpath): + return (rpath, None) + + ptnum = system.load_file(ptpath).rstrip() + + # for a partition, real syspath is something like: + # /sys/devices/pci0000:00/0000:00:04.0/virtio1/block/vda/vda1 + rsyspath = os.path.realpath(syspath) + disksyspath = os.path.dirname(rsyspath) + + diskmajmin = system.load_file(os.path.join(disksyspath, "dev")).rstrip() + diskdevpath = os.path.realpath("/dev/block/%s" % diskmajmin) + + # diskdevpath has something like 253:0 + # and udev has put links in /dev/block/253:0 to the device name in /dev/ + return (diskdevpath, ptnum) + + +def get_sysfs_partitions(device): + """Get a list of sysfs paths for partitions. + + under a block device accepts input as a device kname, + sysfs path, or dev path + returns empty list if no partitions available + """ + sysfs_path = sys_block_path(device) + LOG.debug("sysfs_path:%s", sysfs_path) + return [sys_block_path(kname) for kname in os.listdir(sysfs_path) + if os.path.exists(os.path.join(sysfs_path, kname, 'partition'))] + + +def sysfs_partition_data(blockdev=None, sysfs_path=None): + # given block device or sysfs_path, return a list of tuples + # of (kernel_name, number, offset, size) + if blockdev: + blockdev = os.path.normpath(blockdev) + sysfs_path = sys_block_path(blockdev) + elif sysfs_path: + # use normpath to ensure that paths with trailing slash work + sysfs_path = os.path.normpath(sysfs_path) + blockdev = os.path.join('/dev', os.path.basename(sysfs_path)) + else: + raise ValueError("Blockdev and sysfs_path cannot both be None") + + sysfs_prefix = sysfs_path + (parent, partnum) = get_blockdev_for_partition(blockdev) + if partnum: + sysfs_prefix = sys_block_path(parent) + partnum = int(partnum) + + ptdata = [] + for part_sysfs in get_sysfs_partitions(sysfs_prefix): + data = {} + for sfile in ('partition', 'start', 'size'): + dfile = os.path.join(part_sysfs, sfile) + if not os.path.isfile(dfile): + continue + data[sfile] = int(system.load_file(dfile)) + if partnum is None or data['partition'] == partnum: + ptdata.append(( + path_to_kname(part_sysfs), + data['partition'], + data['start'] * SECTOR_SIZE_BYTES, + data['size'] * SECTOR_SIZE_BYTES, + )) + + return ptdata + + +def kname_to_path(kname): + """Converts a kname to a path in /dev. + + taking special devices and unusual naming schemes into account + """ + # if given something that is already a dev path, return it + if os.path.exists(kname) and is_block_device(kname): + return os.path.realpath(kname) + # adding '/dev' to path is not sufficient to handle cciss devices and + # possibly other special devices which have not been encountered yet + path = os.path.realpath(os.sep.join(['/dev'] + kname.split('!'))) + # make sure path we get is correct + if not (os.path.exists(path) and is_block_device(path)): + raise OSError( + 'Could not get path to dev from kname: {}.'.format(kname)) + return path + + +def sysfs_to_devpath(sysfs_path): + """Convert a path in /sys/class/block to a path in /dev.""" + path = kname_to_path(path_to_kname(sysfs_path)) + if not is_block_device(path): + raise ValueError('could not find blockdev for sys path: {}' + .format(sysfs_path)) + return path + + +def dev_path(devname): + """Convert device name to path in /dev.""" + if devname.startswith('/dev/'): + # it could be something like /dev/mapper/mpatha-part2 + return os.path.realpath(devname) + else: + return '/dev/' + devname + + +def is_online(device): + """Check if device is online.""" + sys_path = sys_block_path(device) + device_size = system.load_file( + os.path.join(sys_path, 'size')) + # a block device should have non-zero size to be usable + return int(device_size) > 0 + + +def wipe_volume(path, mode="superblock", exclusive=True): + """Wipe a volume/block device.""" + if mode == "superblock": + quick_zero(path, partitions=False, exclusive=exclusive) + elif mode == "superblock-recursive": + quick_zero(path, partitions=True, exclusive=exclusive) + else: + raise ValueError("wipe mode %s not supported" % mode) + + +def quick_zero(path, partitions=True, exclusive=True): + """Zero 1M at front, 1M at end, and 1M at front + + if this is a block device and partitions is true, then + zero 1M at front and end of each partition. + """ + buflen = 1024 + count = 1024 + zero_size = buflen * count + offsets = [0, -zero_size] + is_block = is_block_device(path) + LOG.info('%s is block: %s', path, is_block) + if not (is_block or os.path.isfile(path)): + raise ValueError("%s: not an existing file or block device.", path) + + pt_names = [] + if partitions and is_block: + ptdata = sysfs_partition_data(path) + for kname, ptnum, start, size in ptdata: + pt_names.append((dev_path(kname), kname, ptnum)) + pt_names.reverse() + + for (pt, kname, ptnum) in pt_names: + LOG.info('Wiping path: dev:%s kname:%s partnum:%s', + pt, kname, ptnum) + quick_zero(pt, partitions=False) + + LOG.info("Wiping 1M on %s at offsets %s.", path, offsets) + return zero_file_at_offsets(path, + offsets, + buflen=buflen, + count=count, + exclusive=exclusive) + + +def zero_file_at_offsets(path, + offsets, + buflen=1024, + count=1024, + strict=False, + exclusive=True): + """Write zeros to file at specified offsets.""" + + bmsg = "{path} (size={size}): " + m_short = bmsg + "{tot} bytes from {offset} > size." + m_badoff = bmsg + "invalid offset {offset}." + if not strict: + m_short += " Shortened to {wsize} bytes." + m_badoff += " Skipping." + + buf = b'\0' * buflen + tot = buflen * count + msg_vals = {'path': path, 'tot': buflen * count} + + # allow caller to control if we require exclusive open + with exclusive_open(path, exclusive=exclusive) as fp: + # get the size by seeking to end. + fp.seek(0, 2) + size = fp.tell() + msg_vals['size'] = size + + for offset in offsets: + if offset < 0: + pos = size + offset + else: + pos = offset + msg_vals['offset'] = offset + msg_vals['pos'] = pos + if pos > size or pos < 0: + if strict: + raise ValueError(m_badoff.format(**msg_vals)) + else: + LOG.debug(m_badoff.format(**msg_vals)) + continue + + msg_vals['wsize'] = size - pos + if pos + tot > size: + if strict: + raise ValueError(m_short.format(**msg_vals)) + else: + LOG.debug(m_short.format(**msg_vals)) + fp.seek(pos) + for i in range(count): + pos = fp.tell() + if pos + buflen > size: + fp.write(buf[0:size - pos]) + else: + fp.write(buf) + + +@contextmanager +def exclusive_open(path, exclusive=True): + """Obtain an exclusive file-handle to the file/device specified unless + + caller specifics exclusive=False. + """ + mode = 'rb+' + fd = None + if not os.path.exists(path): + raise ValueError("No such file at path: %s" % path) + + flags = os.O_RDWR + if exclusive: + flags += os.O_EXCL + try: + fd = os.open(path, flags) + try: + fd_needs_closing = True + with os.fdopen(fd, mode) as fo: + yield fo + fd_needs_closing = False + except OSError: + LOG.exception("Failed to create file-object from fd") + raise + finally: + # python2 leaves fd open if there os.fdopen fails + if fd_needs_closing and sys.version_info.major == 2: + os.close(fd) + except OSError: + LOG.error("Failed to exclusively open path: %s", path) + holders = get_holders(path) + LOG.error('Device holders with exclusive access: %s', holders) + mount_points = list_device_mounts(path) + LOG.error('Device mounts: %s', mount_points) + raise + + +def list_device_mounts(device): + # return mount entry if device is in /proc/mounts + mounts = "" + with open("/proc/mounts", "r") as fp: + mounts = fp.read() + + dev_mounts = [] + for line in mounts.splitlines(): + if line.split()[0] == device: + dev_mounts.append(line) + return dev_mounts + + +def get_holders(device_name): + """Look up any block device holders, return list of knames. + + """ + # block.sys_block_path works when given a /sys or /dev path + sysfs_path = sys_block_path(device_name) + # get holders + holders_path = os.path.join(sysfs_path, 'holders') + holders = os.listdir(holders_path) + LOG.info("The device '%s' had holders: %s.", device_name, holders) + return holders + + +def path_to_kname(path): + """Converts a path in /dev or a path in /sys/block to the device kname. + + """ + if os.path.sep in path: + path = os.path.realpath(path) + device_kname = os.path.basename(path) + return device_kname + + +def sys_block_path(device_name, additional_path=None, strict=True): + """Get path to device in /sys/class/block. + + """ + path_components = ['/sys/class/block'] + device_name = os.path.normpath(device_name) + if device_name.startswith('/dev/') and not os.path.exists(device_name): + LOG.warning('The devname %s does not exist.', device_name) + + path_components.append(path_to_kname(device_name)) + + if additional_path is not None: + path_components.append(additional_path) + path = os.sep.join(path_components) + if strict and not os.path.exists(path): + err = OSError( + "The devname '{}' did not have existing syspath '{}'.".format( + device_name, path)) + err.errno = errno.ENOENT + raise err + + return os.path.normpath(path) + + +def mkfs(fs, path, label=None, options=None): + """Format a file or block device. + + :param fs: Filesystem type (examples include 'swap', 'ext3', 'ext4' + 'btrfs', etc.) + :param path: Path to file or block device to format + :param label: Volume label to use + """ + if fs == 'fat32': + fs = 'vfat' + + if fs == 'swap': + args = ['mkswap'] + else: + args = ['mkfs', '-t', fs] + + if options: + args.extend(options) + # add -F to force no interactive execute on non-block device. + if fs in ('ext3', 'ext4'): + args.extend(['-F']) + if fs in ('xfs'): + args.extend(['-f']) + + if label: + if fs in ('msdos', 'vfat'): + label_opt = '-n' + else: + label_opt = '-L' + args.extend([label_opt, label]) + args.append(path) + try: + executor.execute(*args, + run_as_root=True, + use_standard_locale=True) + executor.execute('sync') + except ProcessExecutionError as e: + if os.strerror(errno.ENOENT) in e.stdout: + LOG.exception( + 'Failed to make file system. ' + 'File system %s is not supported.', fs) + raise BmpError(("Failed to create a file system. " + "File system %s is not supported.") % fs) + else: + LOG.exception( + 'Failed to create a file system ' + 'in %(path)s. Error: %(error)s', { + 'path': path, + 'error': e + }) + + +def blkid(devs=None, cache=True): + """Get data about block devices from blkid and convert to dict. + + """ + if devs is None: + devs = [] + + # 14.04 blkid reads undocumented /dev/.blkid.tab + # man pages mention /run/blkid.tab and /etc/blkid.tab + if not cache: + cfiles = ("/run/blkid/blkid.tab", "/dev/.blkid.tab", "/etc/blkid.tab") + for cachefile in cfiles: + if os.path.exists(cachefile): + os.unlink(cachefile) + + cmd = ['blkid', '-o', 'full'] + cmd.extend(devs) + # blkid output is : KEY=VALUE + # where KEY is TYPE, UUID, PARTUUID, LABEL + out, _ = executor.execute(*cmd) + data = {} + for line in out.splitlines(): + curdev, curdata = line.split(":", 1) + data[curdev] = dict(tok.split('=', 1) + for tok in shlex.split(curdata)) + LOG.info('Blkid info:%s', data) + return data + + +def get_labelled_partition(device_path, label, attempts_times=1): + """Check and return if partition with given label exists + + :param device_path: The device path. + :param label: Partition label + :raises: InstanceDeployFailure, if any disk partitioning related + commands fail. + :returns: block device file for partition if it exists; otherwise it + returns None. + """ + LOG.info("Get device path:%s by %s", device_path, label) + temp_attempts_times = attempts_times + while attempts_times > 0: + temp_attempts_times -= 1 + partprobe(device_path) + wait_for_disk_to_become_available(device_path) + try: + output, _ = executor.execute('lsblk', + '-Po', + 'name,label', + device_path, + check_exit_code=[0, 1], + use_standard_locale=True, + run_as_root=True) + + except (UnknownArgumentError, ProcessExecutionError, OSError) as e: + msg = (('Failed to retrieve partition labels on disk %(disk)s ' + 'Error: %(error)s') % { + 'disk': device_path, + 'error': e + }) + LOG.error(msg) + raise BmpError(msg) + + found_part = None + if output: + for device in output.split('\n'): + dev = { + key: value + for key, value in (v.split('=', 1) + for v in shlex.split(device)) + } + if not dev: + continue + if dev['LABEL'].upper() == label.upper(): + if found_part: + found_2 = '/dev/%(part)s' % { + 'part': dev['NAME'].strip()} + found = [found_part, found_2] + raise BmpError( + ('More than one partition with label "%(label)s" ' + 'exists on device %(device)s: ' + '%(found)s.') % { + 'label': label, + 'device': device_path, + 'found': ' and '.join(found) + }) + found_part = '/dev/%(part)s' % { + 'part': dev['NAME'].strip()} + + if found_part: + LOG.info("Get labelled partition, found part%s", found_part) + return found_part + else: + attempts_period = 0.5 * 2**(attempts_times - + temp_attempts_times) + LOG.info("Retry to run after %.2f seconds." % attempts_period) + time.sleep(attempts_period) + continue + + +def _fix_gpt_structs(device): + """Checks backup GPT data structures and moves them to end of the device + + :param device: The device path. + :raises: InstanceDeployFailure, if any disk partitioning related + commands fail. + """ + try: + output, _err = executor.execute('sgdisk', + '-v', + device, + run_as_root=True) + + search_str = "it doesn't reside\nat the end of the disk" + if search_str in output: + executor.execute('sgdisk', + '-e', + device, + run_as_root=True) + except (UnknownArgumentError, ProcessExecutionError, OSError) as e: + msg = (('Failed to fix GPT data structures on disk %(disk)s ' + 'Error: %(error)s') % { + 'disk': device, + 'error': e + }) + LOG.error(msg) + raise BmpError(msg) + + +def fix_gpt_partition(device): + """Fix GPT partition + + Fix GPT table information when image is written to a disk which + has a bigger extend (e.g. 30GB image written on a 60Gb physical disk). + + :param device: The device path. + :raises: InstanceDeployFailure if exception is caught. + """ + try: + disk_is_gpt_partitioned = _is_disk_gpt_partitioned(device) + if disk_is_gpt_partitioned: + _fix_gpt_structs(device) + except Exception as e: + msg = (('Failed to fix GPT partition on disk %(disk)s ' + 'Error: %(error)s') % { + 'disk': device, + 'error': e + }) + LOG.error(msg) + raise BmpError(msg) + + +def _is_disk_gpt_partitioned(device): + """Checks if the disk is GPT partitioned + + :param device: The device path. + :raises: InstanceDeployFailure, if any disk partitioning related + commands fail. + :returns: Boolean. Returns True if disk is GPT partitioned + """ + try: + stdout, _ = executor.execute( + 'blkid', + '-p', + '-o', + 'value', + '-s', + 'PTTYPE', + device, + use_standard_locale=True, + run_as_root=True) + except (UnknownArgumentError, ProcessExecutionError, OSError) as e: + msg = (('Failed to retrieve partition table type for disk %(disk)s ' + 'Error: %(error)s') % { + 'disk': device, + 'error': e + }) + LOG.error(msg) + raise BmpError(msg) + + return (stdout.lower().strip() == 'gpt') + + +class CPU(SerializableComparable): + + serializable_fields = ('model_name', 'frequency', 'count', 'architecture', + 'flags') + + def __init__(self, model_name, frequency, count, architecture, flags=None): + self.model_name = model_name + self.frequency = frequency + self.count = count + self.architecture = architecture + self.flags = flags or [] + + def __repr__(self): + return "CPU %s" % self.serialize() + + +class Memory(SerializableComparable): + + serializable_fields = ('total', 'physical_mb') + + # physical = total + kernel binary + reserved space + + def __init__(self, total, physical_mb=None): + self.total = total + self.physical_mb = physical_mb + + def __repr__(self): + return "Memory %s" % self.serialize() + + +def is_device(interface_name): + device_path = '/sys/class/net/{}/device'.format(interface_name) + return os.path.exists(device_path) + + +def get_bios_given_nic_name(interface_name): + """Collect the BIOS given NICs name. + + This function uses the biosdevname utility to collect the BIOS given + name of network interfaces. + The collected data is added to the network interface inventory with an + extra field named ``biosdevname``. + :param interface_name: list of names of node's interfaces. + :return: the BIOS given NIC name of node's interfaces or default + as None. + """ + try: + + stdout, _ = executor.execute('biosdevname', '-i', + interface_name) + return stdout.rstrip('\n') + except OSError: + LOG.warning("Executable 'biosdevname' not found") + return interface_name + except ProcessExecutionError as e: + LOG.warning('Biosdevname get error:%s', str(e)) + return interface_name + + +def get_system_lshw_dict(): + """Get a dict representation of the system from lshw + + Retrieves a json representation of the system from lshw and converts + it to a python dict + + :return: A python dict from the lshw json output + """ + out, _ = executor.execute('lshw', + '-quiet', + '-json') + res = json.loads(out) + if isinstance(res, list): + return res[0] + else: + return res + + +def get_cpus(): + lines = executor.execute('lscpu')[0] + cpu_info = { + k.strip().lower(): v.strip() + for k, v in (line.split(':', 1) for line in lines.split('\n') + if line.strip()) + } + # Current CPU frequency can be different from maximum one on modern + # processors + freq = cpu_info.get('cpu max mhz', cpu_info.get('cpu mhz')) + flags = [] + colum_grep = '^flags' + if platform.machine() == constants.MACHINE_AARCH64: + colum_grep = '^Features' + + out = executor.try_execute('grep', '-Em1', colum_grep, + '/proc/cpuinfo') + if out: + try: + # Example output (much longer for a real system): + # flags : fpu vme de pse + flags = out[0].strip().split(':', 1)[1].strip().split() + except (IndexError, ValueError): + LOG.warning('Malformed CPU flags information: %s', out) + else: + LOG.warning('Failed to get CPU flags') + return CPU( + model_name=cpu_info.get('model name'), + frequency=freq, + # this includes hyperthreading cores + count=int(cpu_info.get('cpu(s)')), + architecture=cpu_info.get('architecture'), + flags=flags) + + +def get_memory(): + # psutil returns a long, so we force it to an int + try: + total = int(psutil.virtual_memory().total) + except Exception: + # This is explicitly catching all exceptions. We want to catch any + # situation where a newly upgraded psutil would fail, and instead + # print an error instead of blowing up the stack on IPA. + total = None + LOG.exception(("Cannot fetch total memory size using psutil " + "version %s"), psutil.version_info[0]) + sys_dict = None + try: + sys_dict = get_system_lshw_dict() + except (ProcessExecutionError, OSError, ValueError) as e: + LOG.warning('Could not get real physical RAM from lshw: %s', e) + physical = None + else: + physical = _calc_memory(sys_dict) + if not physical: + LOG.warning('Did not find any physical RAM') + return Memory(total=total, physical_mb=physical) + + +_MEMORY_ID_RE = re.compile(r'^memory(:\d+)?$') +UNIT_CONVERTER = pint.UnitRegistry(filename=None) +UNIT_CONVERTER.define('bytes = []') +UNIT_CONVERTER.define('MB = 1048576 bytes') + + +def _calc_memory(sys_dict): + physical = 0 + for sys_child in sys_dict['children']: + if sys_child['id'] != 'core': + continue + for core_child in sys_child['children']: + if not _MEMORY_ID_RE.match(core_child['id']): + continue + if core_child.get('size'): + value = ("%(size)s %(units)s" % core_child) + physical += int(UNIT_CONVERTER(value).to('MB').magnitude) + else: + for bank in core_child.get('children', ()): + if bank.get('size'): + value = ("%(size)s %(units)s" % bank) + physical += int( + UNIT_CONVERTER(value).to('MB').magnitude) + return physical + + +def get_bmc_address(): + """Attempt to detect BMC IP address + + :return: IP address of lan channel or 0.0.0.0 in case none of them is + configured properly + """ + # These modules are rarely loaded automatically + executor.try_execute('modprobe', 'ipmi_msghandler') + executor.try_execute('modprobe', 'ipmi_devintf') + executor.try_execute('modprobe', 'ipmi_si', + 'unload_when_empty=0') + + try: + # From all the channels 0-15, only 1-7 can be assigned to different + # types of communication media and protocols and effectively used + for channel in range(1, 8): + try: + out, _ = executor.execute( + "ipmitool lan print %(channel)s |grep -E \"IP Address : \"" + % {"channel": channel}, + shell=True) + except Exception: + continue + if out.startswith('Invalid channel'): + continue + if ":" not in out: + continue + out = out.split(':')[1].strip() + + try: + netaddr.IPAddress(out) + except ValueError: + LOG.warning('Invalid IP address: %s', out) + continue + except netaddr.AddrFormatError: + LOG.warning('Invalid IP address: %s', out) + continue + + # In case we get 0.0.0.0 on a valid channel, we need to keep + # querying + if out == '0.0.0.0': + continue + return out + + except (ProcessExecutionError, OSError) as e: + # Not error, because it's normal in virtual environment + LOG.warning('Cannot get BMC address: %s', e) + return + + return '0.0.0.0' + + +class BootInfo(SerializableComparable): + + serializable_fields = ('current_boot_mode', 'pxe_interface') + + def __init__(self, current_boot_mode, pxe_interface=None): + self.current_boot_mode = current_boot_mode + self.pxe_interface = pxe_interface + + def __repr__(self): + return "BootInfo %s" % self.serialize() + + +def get_boot_info(): + boot_mode = constants.UEFI if utils.is_uefi_bootable() else constants.BIOS + LOG.debug('The current boot mode is %s', boot_mode) + return BootInfo(current_boot_mode=boot_mode) + + +class PlatformInfo(SerializableComparable): + + serializable_fields = ('machine', ) + + def __init__(self, machine): + self.machine = machine + + def __repr__(self): + return "PlatformInfo %s" % self.serialize() + + +def get_platform_info(): + machine = platform.machine() + return PlatformInfo(machine=machine) diff --git a/bmp-agent/bmpa/utils/interfaceutils.py b/bmp-agent/bmpa/utils/interfaceutils.py new file mode 100755 index 0000000..30107cc --- /dev/null +++ b/bmp-agent/bmpa/utils/interfaceutils.py @@ -0,0 +1,543 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import binascii +import ctypes +import fcntl +import logging +import os +import select +import socket +import struct +import sys +import time + +import netifaces +import pyudev + +from bmpa.errors import BmpError, IncompatibleHardwareMethodError +from bmpa.serialize import SerializableComparable +from bmpa.utils import executor +from bmpa.utils import hardware +from bmpa.utils import netutils + + +LOG = logging.getLogger(__name__) + +DEFAULT_DHCP_WAIT_TIMEOUT = 600 +DHCP_RETRY_INTERVAL = 2 + +LLDP_TIMEOUT = 60.0 + +LLDP_ETHERTYPE = 0x88cc +IFF_PROMISC = 0x100 +SIOCGIFFLAGS = 0x8913 +SIOCSIFFLAGS = 0x8914 +DMAC_TYPE_NEAREST_BRIDGE = 0xe + + +class ifreq(ctypes.Structure): + """Class for setting flags on a socket.""" + _fields_ = [("ifr_ifrn", ctypes.c_char * 16), + ("ifr_flags", ctypes.c_short)] + + +class RawPromiscuousSockets(object): + def __init__(self, interface_names, protocol): + """Initialize context manager. + + :param interface_names: a list of interface names to bind to + :param protocol: the protocol to listen for + :returns: A list of tuple of (interface_name, bound_socket), or [] if + there is an exception binding or putting the sockets in + promiscuous mode + """ + if not interface_names: + raise ValueError('interface_names must be a non-empty list of ' + 'network interface names to bind to.') + self.protocol = protocol + # A 3-tuple of (interface_name, socket, ifreq object) + self.interfaces = [(name, self._get_socket(), ifreq()) + for name in interface_names] + + def __enter__(self): + for interface_name, sock, ifr in self.interfaces: + LOG.info( + 'Interface %s entering promiscuous mode to capture ', interface_name) + try: + ifr.ifr_ifrn = interface_name.encode() + # Get current flags + fcntl.ioctl(sock.fileno(), SIOCGIFFLAGS, ifr) # G for Get + # bitwise or the flags with promiscuous mode, set the new flags + ifr.ifr_flags |= IFF_PROMISC + fcntl.ioctl(sock.fileno(), SIOCSIFFLAGS, ifr) # S for Set + # Bind the socket so it can be used + LOG.debug( + 'Binding interface %(interface)s for protocol ' + '%(proto)s', { + 'interface': interface_name, + 'proto': self.protocol + }) + sock.bind((interface_name, self.protocol)) + except Exception: + LOG.error('Failed to open all RawPromiscuousSockets, ' + 'attempting to close any opened sockets.') + self.__exit__(*sys.exc_info()) + raise + + # No need to return each interfaces ifreq. + return [(sock[0], sock[1]) for sock in self.interfaces] + + def __exit__(self, exception_type, exception_val, trace): + for name, sock, ifr in self.interfaces: + # bitwise or with the opposite of promiscuous mode to remove + ifr.ifr_flags &= ~IFF_PROMISC + try: + fcntl.ioctl(sock.fileno(), SIOCSIFFLAGS, ifr) + sock.close() + except Exception: + LOG.exception('Failed to close raw socket for interface %s', + name) + + def _get_socket(self): + return socket.socket(socket.AF_PACKET, socket.SOCK_RAW, self.protocol) + + +class NetworkInterface(SerializableComparable): + serializable_fields = ('name', 'mac_address', 'ipv4_address', + 'has_carrier', 'lldp', 'vendor', 'product', + 'client_id', 'biosdevname', 'switch_index', + 'switch_manage_ip', 'bus_info') + + def __init__(self, + name, + mac_addr, + ipv4_address=None, + has_carrier=True, + lldp=None, + vendor=None, + product=None, + client_id=None, + biosdevname=None, + switch_index=None, + switch_manage_ip=None, + bus_info=None): + self.name = name + self.mac_address = mac_addr + self.ipv4_address = ipv4_address + self.has_carrier = has_carrier + self.lldp = lldp + self.vendor = vendor + self.product = product + self.biosdevname = biosdevname + # client_id is used for InfiniBand only. we calculate the DHCP + # client identifier Option to allow DHCP to work over InfiniBand. + # see https://tools.ietf.org/html/rfc4390 + self.client_id = client_id + self.switch_index = switch_index + self.switch_manage_ip = switch_manage_ip + self.bus_info = bus_info + + def __repr__(self): + return "NetworkInterface %s" % self.serialize() + + +def get_lldp_info(interface_names): + """Get LLDP info from the switch(es) the agent is connected to. + + Listens on either a single or all interfaces for LLDP packets, then + parses them. If no LLDP packets are received before lldp_timeout, + returns a dictionary in the form {'interface': [],...}. + + :param interface_names: The interface to listen for packets on. If + None, will listen on each interface. + :return: A dictionary in the form + {'interface': [(lldp_type, lldp_data)],...} + """ + with RawPromiscuousSockets(interface_names, LLDP_ETHERTYPE) as interfaces: + try: + return _get_lldp_info(interfaces) + except Exception as e: + LOG.exception('Error while getting LLDP info: %s', str(e)) + raise + + +def _get_lldp_info(interfaces): + """Wait for packets on each socket, parse the received LLDP packets. + + """ + LOG.debug('Getting LLDP info for interfaces %s', interfaces) + + lldp_info = {} + if not interfaces: + return {} + + while interfaces: + LOG.info( + 'Waiting on LLDP info for interfaces: %(interfaces)s, ' + 'timeout: %(timeout)s', { + 'interfaces': interfaces, + 'timeout': LLDP_TIMEOUT + }) + + socks = [interface[1] for interface in interfaces] + # rlist is a list of sockets ready for reading + rlist, _, _ = select.select(socks, [], [], LLDP_TIMEOUT) + if not rlist: + # Empty read list means timeout on all interfaces + LOG.warning('LLDP timed out, remaining interfaces: %s', + interfaces) + break + + for s in rlist: + # Find interface name matching socket ready for read + # Create a copy of interfaces to avoid deleting while iterating. + for index, interface in enumerate(list(interfaces)): + if s == interface[1]: + try: + dmac_type, lldp_info[ + interface[0]] = _receive_lldp_packets(s) + except socket.error: + LOG.exception( + 'Socket for network interface %s said ' + 'that it was ready to read we were ' + 'unable to read from the socket while ' + 'trying to get LLDP packet. Skipping ' + 'this network interface.', interface[0]) + else: + LOG.info('Found LLDP info for interface: %s', + interface[0]) + # Remove interface from the list, only need one packet + if dmac_type == DMAC_TYPE_NEAREST_BRIDGE: + del interfaces[index] + + # Add any interfaces that didn't get a packet as empty lists + for name, _sock in interfaces: + lldp_info[name] = [] + + return lldp_info + + +def collect_lldp_data(interfaces_names): + """Collect and convert LLDP info from the node. + + In order to process the LLDP information later, the raw data needs to + be converted for serialization purposes. + + :param interface_names: list of names of node's interfaces. + :return: a dict, containing the lldp data from every interface. + """ + interface_names = [name for name in interfaces_names if name != 'lo'] + lldp_data = {} + try: + raw_lldp_data = get_lldp_info(interface_names) + except Exception: + # NOTE(sambetts) The get_lldp_info function will log this exception + # and we don't invalidate any existing data in the cache if we fail + # to get data to replace it so just return. + return lldp_data + for ifname, tlvs in raw_lldp_data.items(): + # NOTE(sambetts) Convert each type-length-value (TLV) value to hex + # so that it can be serialised safely + processed_tlvs = [] + for typ, data in tlvs: + try: + # binascii.hexlify(data).decode())) + processed_tlvs.append((typ, data)) + except (binascii.Error, binascii.Incomplete) as e: + LOG.warning( + 'An error occurred while processing TLV type ' + '%s for interface %s: %s', typ, ifname, e) + lldp_data[ifname] = processed_tlvs + return lldp_data + + +def _receive_lldp_packets(sock): + """Receive LLDP packets and process them. + + :param sock: A bound socket + :return: A list of tuples in the form (lldp_type, lldp_data) + """ + pkt = sock.recv(1600) + # Filter invalid packets + if not pkt or len(pkt) < 14: + return [] + dmac_type = struct.unpack('!H', pkt[4:6])[0] + # Skip header (dst MAC, src MAC, ethertype) + pkt = pkt[14:] + return dmac_type, _parse_tlv(pkt) + + +def _parse_tlv(buff): + """Iterate over a buffer and generate structured TLV data. + + :param buff: An ethernet packet with the header trimmed off (first + 14 bytes) + """ + lldp_info = [] + while len(buff) >= 2: + # TLV structure: type (7 bits), length (9 bits), val (0-511 bytes) + tlvhdr = struct.unpack('!H', buff[:2])[0] + tlvtype = (tlvhdr & 0xfe00) >> 9 + tlvlen = (tlvhdr & 0x01ff) + tlvdata = buff[2:tlvlen + 2] + buff = buff[tlvlen + 2:] + lldp_info.append((tlvtype, tlvdata)) + + if buff: + LOG.warning("Trailing byte received in an LLDP package: %r", buff) + return lldp_info + + +def get_interface_bus_info(interface_name): + context = pyudev.Context() + for device in context.list_devices(subsystem='net'): + if device.get('INTERFACE') == interface_name: + path = device.get('ID_PATH') + if path: + parts = path.split('-') + return parts[1] if len(parts) > 1 else path + return None + + +def get_interface_info(interface_name): + mac_addr = get_mac_addr(interface_name) + if mac_addr is None: + raise IncompatibleHardwareMethodError() + + return NetworkInterface( + interface_name, + mac_addr, + ipv4_address=get_ipv4_addr(interface_name), + has_carrier=interface_has_carrier(interface_name), + vendor=hardware.get_device_info(interface_name, 'net', + 'vendor'), + product=hardware.get_device_info(interface_name, 'net', + 'device'), + biosdevname=hardware.get_bios_given_nic_name(interface_name), + bus_info=get_interface_bus_info(interface_name)) + + +def list_network_interfaces_meta(include_lldp=True, is_up_eth=True): + network_interfaces = [] + interface_names = list_interface_name() + if is_up_eth: + for if_name in interface_names: + is_inactive = is_inactive_eth(if_name) + if is_inactive: + try: + executor.execute( + 'ifconfig %s up' % if_name, shell=True) + finally: + LOG.info('ifconfig %s up', if_name) + lldp_data = None + if include_lldp: + lldp_data = collect_lldp_data(interface_names) + + for if_name in interface_names: + result = get_interface_info(if_name) + if (lldp_data and type(lldp_data) is dict + and if_name in lldp_data.keys()): + lldp = lldp_data.get(if_name) + if len(lldp) <= 0: + continue + switch_index = parse_switch_index(lldp) + if switch_index is None: + continue + LOG.info("%s switch index %s", if_name, switch_index) + switch_manage_ip = parse_switch_management_ip(lldp) + LOG.info("%s switch management ip %s", if_name, + switch_manage_ip) + result.switch_index = switch_index + result.switch_manage_ip = switch_manage_ip + network_interfaces.append(result) + + return network_interfaces + + +def parse_switch_index(lldp): + """doc: https://en.wikipedia.org/wiki/Link_Layer_Discovery_Protocol + + tlv type: + 0 End of LLDPDU Mandatory + 1 Chassis ID Mandatory + 2 Port ID Mandatory + 3 Time To Live Mandatory + 4 Port description Optional + 5 System name Optional + 6 System description Optional + 7 System capabilities Optional + 8 Management address Optional + 9–126 Reserved - + 127 Custom TLVs Optional + + data struct: + [(1, '\x04\xdc!\xe2u\xa01'), + (2, '\x0525GE1/0/25'), + (3, '\x00x'), + (5, 'SQV03_Physics-Cloud_T4-L3-161_TOR-HUAWEI-25G'), + (6, 'Huawei Versatile Routing Platform Software\r\nVRP (R) software, Version 8.180 (CE6865EI V200R005C10SPC800)\r\nCopyright (C) 2012-2018 Huawei Technologies Co., Ltd.\r\nHUAWEI CE6865-48S8CQ-EI\r\n'), + (7, '\x00\x14\x00\x14'), + (8, '\x05\x01\n\xd0\x08Y\x02\x00\x00\x00>\x11\x06\x0f+\x06\x01\x04\x01\x8f[\x05\x19)\x01\x02\x01\x01\x01'), + (127, '\x00\x80\xc2\x01\x00d'), (127, '\x00\x80\xc2\x02\x00\x00\x00'), + (127, '\x00\x80\xc2\x03\x00d\x07VLAN100'), + (127, '\x00\x12\x0f\x01\x00\x00\x00\x00\x00'), + (127, '\x00\x12\x0f\x03\x01\x00\x00\x00\x00'), + (127, '\x00\x12\x0f\x04$\x00'), (0, '')] + """ + + for tlv in lldp: + if tlv[0] == 2: + if isinstance(tlv[1][1:], bytes): + try: + return tlv[1][1:].decode('utf-8') + except Exception as e: + LOG.info("Invalid lldp info : %s, err:%s.", lldp, e) + return None + + return tlv[1][1:] + LOG.info("Invalid lldp info : %s." % lldp) + return None + + +def parse_switch_management_ip(lldp): + for tlv in lldp: + if tlv[0] == 8: + management_ip = tlv[1][2:6] + return "%d.%d.%d.%d" % (management_ip[0], + management_ip[1], management_ip[2], + management_ip[3]) + raise BmpError("Invalid lldp info : %s." % lldp) + + +def list_interface_name(): + iface_names = os.listdir('/sys/class/net') + iface_names = [ + name for name in iface_names if hardware.is_device(name) + ] + return iface_names + + +def get_interface_flags(interface_name): + """Get interface flags. + + :param iface_name + :type string + + """ + try: + with open('/sys/class/net/%s/flags' % interface_name, 'r') as f: + return f.read().strip() + except IOError: + LOG.warn("Can't find interface %s flags", interface_name) + + +def is_inactive_eth(interface_name): + """Ethernet adapter is not activated. + + :param iface_name + :type string + + """ + status = get_interface_flags(interface_name) + if status is not None: + if status == "0x1002": + return True + return False + + +def list_network_interfaces(): + network_interfaces = [] + iface_names = list_interface_name() + + for iface_name in iface_names: + result = get_interface_info(interface_name=iface_name) + network_interfaces.append(result) + return network_interfaces + + +def get_ipv4_addr(if_name): + try: + addrs = netifaces.ifaddresses(if_name) + return addrs[netifaces.AF_INET][0]['addr'] + except (ValueError, IndexError, KeyError): + # No default IPv4 address found + return None + + +def get_mac_addr(interface_name): + try: + addrs = netifaces.ifaddresses(interface_name) + return addrs[netifaces.AF_LINK][0]['addr'] + except (ValueError, IndexError, KeyError): + # No mac address found + return None + + +def interface_has_carrier(interface_name): + path = '/sys/class/net/{}/carrier'.format(interface_name) + try: + with open(path, 'rt') as fp: + return fp.read().strip() == '1' + except EnvironmentError: + LOG.debug('No carrier information for interface %s', interface_name) + return False + + +def wrap_ipv6(ip): + if netutils.is_valid_ipv6(ip): + return "[%s]" % ip + return ip + + +def get_wildcard_address(): + if netutils.is_ipv6_enabled(): + return "::" + return "0.0.0.0" + + +def _normalize_mac(mac): + """Convert MAC to a well-known format aa:bb:cc:dd:ee:ff.""" + if '-' in mac: + # pxelinux format is 01-aa-bb-cc-dd-ee-ff + mac = mac.split('-', 1)[1] + mac = mac.replace('-', ':') + return mac.lower() + + +def wait_for_dhcp(): + """Wait until NIC's get their IP addresses via DHCP or timeout happens. + + Depending on the value of inspection_dhcp_all_interfaces configuration + option will wait for either all or only PXE booting NIC. + + Note: only supports IPv4 addresses for now. + + :return: True if all NIC's got IP addresses, False if timeout happened. + Also returns True if waiting is disabled via configuration. + """ + threshold = time.time() + DEFAULT_DHCP_WAIT_TIMEOUT + while time.time() <= threshold: + interfaces = list_network_interfaces_meta(include_lldp=False) + for iface in interfaces: + if iface.ipv4_address: + LOG.info("capture ipv4 address : %s", iface) + return (True, iface.name) + + LOG.debug('Still waiting for interfaces to get IP addresses') + time.sleep(DHCP_RETRY_INTERVAL) + + LOG.warning( + 'Not all network interfaces received IP addresses in \ + %(timeout)d seconds', {'timeout': DEFAULT_DHCP_WAIT_TIMEOUT}) + return (False, None) + + +def dhclient(): + """Run dhclient + + """ + try: + executor.execute('dhclient', shell=True) + except Exception as e: + LOG.error('Run dhclient error:%s.' % e) diff --git a/bmp-agent/bmpa/utils/lvm.py b/bmp-agent/bmpa/utils/lvm.py new file mode 100755 index 0000000..7d41417 --- /dev/null +++ b/bmp-agent/bmpa/utils/lvm.py @@ -0,0 +1,38 @@ +from bmpa.utils import executor + +_SEP = '=' + + +def split_lvm_name(full): + """split full lvm name into tuple of (volgroup, lv_name)""" + # 'dmsetup splitname' is the authoratative source for lvm name parsing + stdout, _ = executor.execute(*[ + 'dmsetup', 'splitname', full, '-c', '--noheadings', '--separator', + _SEP, '-o', 'vg_name,lv_name' + ]) + return stdout.strip().split(_SEP) + + +def _filter_lvm_info(lvtool, match_field, query_field, match_key, args=None): + """filter output of pv/vg/lvdisplay tools""" + if args is None: + args = [] + stdout, _ = executor.execute(*[ + lvtool, '-C', '--separator', _SEP, '--noheadings', '-o', ','.join( + [match_field, query_field]) + ] + args) + return [ + qf for (mf, qf) in + [line.strip().split(_SEP) for line in stdout.strip().splitlines()] + if mf == match_key + ] + + +def get_lvols_in_volgroup(vg_name): + """get logical volumes in volgroup""" + return _filter_lvm_info('lvdisplay', 'vg_name', 'lv_name', vg_name) + + +def get_pvols_in_volgroup(vg_name): + """get physical volumes used by volgroup""" + return _filter_lvm_info('pvdisplay', 'vg_name', 'pv_name', vg_name) diff --git a/bmp-agent/bmpa/utils/mountutils.py b/bmp-agent/bmpa/utils/mountutils.py new file mode 100644 index 0000000..9e1e0f7 --- /dev/null +++ b/bmp-agent/bmpa/utils/mountutils.py @@ -0,0 +1,78 @@ + +from contextlib import contextmanager +import os + +from bmpa.utils import executor +from bmpa.utils import system + + +@contextmanager +def mount(src, target, opts=None): + do_mount(src, target, opts) + yield + do_umount(target) + + +def do_mount(src, target, opts=None): + """Mount src at target with opts. + + if already mounted, return False + """ + if opts is None: + opts = [] + if isinstance(opts, str): + opts = [opts] + + if is_mounted(target): + return False + + system.ensure_dir(target) + cmd = ['mount'] + opts + [src, target] + executor.execute(*cmd) + return True + + +def do_umount(mountpoint, recursive=False): + """Unmount mountpoint. + + """ + mp = os.path.abspath(mountpoint) + + ret = False + mountpoints = [ + line.split()[1] + for line in system.load_file("/proc/mounts", decode=True).splitlines()] + + for curmp in reversed(mountpoints): + if curmp == mp or (recursive and curmp.startswith(mp + os.path.sep)): + executor.execute('umount', curmp, attempts_times=10, + delay_on_retry=True) + if curmp == mp: + ret = True + return ret + + +def is_mounted(target): + """Return whether or not target was mounted . + + """ + mounts = "" + with open("/proc/mounts", "r") as fp: + mounts = fp.read() + + for line in mounts.splitlines(): + if line.split()[1] == os.path.abspath(target): + return True + return False + + +def unmount_by_device(device): + mounts = "" + with open("/proc/mounts", "r") as fp: + mounts = fp.read() + mount_lines = mounts.splitlines() + mount_info = [line.split() for line in mount_lines] + + for mount_point, mounted_device in mount_info: + if mounted_device == device: + executor.execute(*('umount', mount_point)) diff --git a/bmp-agent/bmpa/utils/multipath.py b/bmp-agent/bmpa/utils/multipath.py new file mode 100755 index 0000000..355a4c6 --- /dev/null +++ b/bmp-agent/bmpa/utils/multipath.py @@ -0,0 +1,10 @@ +from bmpa.utils import udev + + +def mpath_partition_to_mpath_id_and_partnumber(devpath): + """Return the mpath id and partition number of a multipath partition. """ + info = udev.udevadm_info(devpath) + if 'DM_MPATH' in info and 'DM_PART' in info: + return info['DM_MPATH'], info['DM_PART'] + + return None diff --git a/bmp-agent/bmpa/utils/netutils.py b/bmp-agent/bmpa/utils/netutils.py new file mode 100755 index 0000000..6b0ea6d --- /dev/null +++ b/bmp-agent/bmpa/utils/netutils.py @@ -0,0 +1,171 @@ +import os +import re + +import netaddr +import six + +_IS_IPV6_ENABLED = None + + +def is_valid_ipv4(address): + """Verify that address represents a valid IPv4 address. + + :param address: Value to verify + :type address: string + :returns: bool + + .. versionadded:: 1.1 + """ + try: + return netaddr.valid_ipv4(address) + except netaddr.AddrFormatError: + return False + + +def is_valid_ipv6(address): + """Verify that address represents a valid IPv6 address. + + :param address: Value to verify + :type address: string + :returns: bool + + .. versionadded:: 1.1 + """ + if not address: + return False + + parts = address.rsplit("%", 1) + address = parts[0] + scope = parts[1] if len(parts) > 1 else None + if scope is not None and (len(scope) < 1 or len(scope) > 15): + return False + + try: + return netaddr.valid_ipv6(address, netaddr.core.INET_PTON) + except netaddr.AddrFormatError: + return False + + +def is_valid_cidr(address): + """Verify that address represents a valid CIDR address. + + :param address: Value to verify + :type address: string + :returns: bool + + .. versionadded:: 3.8 + """ + try: + # Validate the correct CIDR Address + netaddr.IPNetwork(address) + except (TypeError, netaddr.AddrFormatError): + return False + + # Prior validation partially verify /xx part + # Verify it here + ip_segment = address.split('/') + + if (len(ip_segment) <= 1 or ip_segment[1] == ''): + return False + + return True + + +def is_valid_ip(address): + """Verify that address represents a valid IP address. + + :param address: Value to verify + :type address: string + :returns: bool + + .. versionadded:: 1.1 + """ + return is_valid_ipv4(address) or is_valid_ipv6(address) + + +def is_valid_mac(address): + """Verify the format of a MAC address. + + Check if a MAC address is valid and contains six octets. Accepts + colon-separated format only. + + :param address: MAC address to be validated. + :returns: True if valid. False if not. + + .. versionadded:: 3.17 + """ + m = "[0-9a-f]{2}(:[0-9a-f]{2}){5}$" + return (isinstance(address, six.string_types) + and re.match(m, address.lower())) + + +def _is_int_in_range(value, start, end): + """Try to convert value to int and check if it lies within + + range 'start' to 'end'. + + :param value: value to verify + :param start: start number of range + :param end: end number of range + :returns: bool + """ + try: + val = int(value) + except (ValueError, TypeError): + return False + return (start <= val <= end) + + +def is_valid_port(port): + """Verify that port represents a valid port number. + + Port can be valid integer having a value of 0 up to and + including 65535. + + .. versionadded:: 1.1.1 + """ + return _is_int_in_range(port, 0, 65535) + + +def is_ipv6_enabled(): + """Check if IPv6 support is enabled on the platform. + + This api will look into the proc entries of the platform to figure + out the status of IPv6 support on the platform. + + :returns: True if the platform has IPv6 support, False otherwise. + + .. versionadded:: 1.4 + """ + + global _IS_IPV6_ENABLED + + if _IS_IPV6_ENABLED is None: + disabled_ipv6_path = "/proc/sys/net/ipv6/conf/default/disable_ipv6" + if os.path.exists(disabled_ipv6_path): + with open(disabled_ipv6_path, 'r') as f: + disabled = f.read().strip() + _IS_IPV6_ENABLED = disabled == "0" + else: + _IS_IPV6_ENABLED = False + return _IS_IPV6_ENABLED + + +def netmask_to_cidr(netmask): + """netmast to cidr + + :param netmask: netmask ip addr (eg: 255.255.255.0) + :return: equivalent cidr number to given netmask ip (eg: 24) + """ + return sum([bin(int(x)).count('1') for x in netmask.split('.')]) + + +def ip_to_cidr(ip_addr, netmask): + """ip to cidr + + :param ip_addr: ip addr (eg: 10.208.14.165) + :param netmask: netmask ip addr (eg: 255.255.255.224) + :return: ip/cidr (eg: 10.208.14.165/24) + """ + cidr = netmask_to_cidr(netmask) + return '%s/%s' % (ip_addr, cidr) diff --git a/bmp-agent/bmpa/utils/paths.py b/bmp-agent/bmpa/utils/paths.py new file mode 100644 index 0000000..b9d3252 --- /dev/null +++ b/bmp-agent/bmpa/utils/paths.py @@ -0,0 +1,15 @@ +import os + + +def target_path(target, path=None): + if target in (None, ""): + target = "/" + + target = os.path.abspath(target) + + if not path: + return target + + path = path.lstrip("/") + + return os.path.join(target, path) diff --git a/bmp-agent/bmpa/utils/specs_matcher.py b/bmp-agent/bmpa/utils/specs_matcher.py new file mode 100755 index 0000000..d74f768 --- /dev/null +++ b/bmp-agent/bmpa/utils/specs_matcher.py @@ -0,0 +1,137 @@ +import ast +import operator + +import pyparsing + + +def _all_in(x, *y): + x = ast.literal_eval(x) + if not isinstance(x, list): + raise TypeError(" must compare with a list literal" + " string, EG \"%s\"" % (['aes', 'mmx'], )) + return all(val in x for val in y) + + +op_methods = { + # This one is special/odd, + # TODO(harlowja): fix it so that it's not greater than or + # equal, see here for the original @ https://review.openstack.org/#/c/8089/ + '=': lambda x, y: float(x) >= float(y), + # More sane ops/methods + # Numerical methods + '!=': lambda x, y: float(x) != float(y), + '<=': lambda x, y: float(x) <= float(y), + '<': lambda x, y: float(x) < float(y), + '==': lambda x, y: float(x) == float(y), + '>=': lambda x, y: float(x) >= float(y), + '>': lambda x, y: float(x) > float(y), + # String methods + 's!=': operator.ne, + 's<': operator.lt, + 's<=': operator.le, + 's==': operator.eq, + 's>': operator.gt, + 's>=': operator.ge, + # Other + '': _all_in, + '': lambda x, y: y in x, + '': lambda x, *y: any(x == a for a in y), +} + + +def make_grammar(): + """Creates the grammar to be used by a spec matcher. + +The grammar created supports the following operations. +Numerical values: + * ``= :`` equal to or greater than. This is equivalent to ``>=`` and is + supported for `legacy reasons + `_ + * ``!= :`` Float/integer value not equal + * ``<= :`` Float/integer value less than or equal + * ``< :`` Float/integer value less than + * ``== :`` Float/integer value equal + * ``>= :`` Float/integer value greater than or equal + * ``> :`` Float/integer value greater +String operations: + * ``s!= :`` Not equal + * ``s< :`` Less than + * ``s<= :`` Less than or equal + * ``s== :`` Equal + * ``s> :`` Greater than + * ``s>= :`` Greater than or equal +Other operations: + * `` :`` All items 'in' value + * `` :`` Item 'in' value, like a substring in a string. + * `` :`` Logical 'or' +If no operator is specified the default is ``s==`` (string equality comparison) +Example operations: + * ``">= 60"`` Is the numerical value greater than or equal to 60 + * ``" spam eggs"`` Does the value contain ``spam`` or ``eggs`` + * ``"s== 2.1.0"`` Is the string value equal to ``2.1.0`` + * ``" gcc"`` Is the string ``gcc`` contained in the value string + * ``" aes mmx"`` Are both ``aes`` and ``mmx`` in the value +:returns: A pyparsing.MatchFirst object. See + https://pythonhosted.org/pyparsing/ for details on pyparsing. + """ + # This is apparently how pyparsing recommends to be used, + # as http://pyparsing.wikispaces.com/share/view/644825 states that + # it is not thread-safe to use a parser across threads. + + unary_ops = ( + # Order matters here (so that '=' doesn't match before '==') + pyparsing.Literal("==") | pyparsing.Literal("=") + | pyparsing.Literal("!=") | pyparsing.Literal("") + | pyparsing.Literal(">=") | pyparsing.Literal("<=") + | pyparsing.Literal(">") | pyparsing.Literal("<") + | pyparsing.Literal("s==") | pyparsing.Literal("s!=") | + # Order matters here (so that '<' doesn't match before '<=') + pyparsing.Literal("s<=") | pyparsing.Literal("s<") | + # Order matters here (so that '>' doesn't match before '>=') + pyparsing.Literal("s>=") | pyparsing.Literal("s>")) + + all_in_nary_op = pyparsing.Literal("") + or_ = pyparsing.Literal("") + + # An atom is anything not an keyword followed by anything but whitespace + atom = ~(unary_ops | all_in_nary_op | or_) + pyparsing.Regex(r"\S+") + + unary = unary_ops + atom + nary = all_in_nary_op + pyparsing.OneOrMore(atom) + disjunction = pyparsing.OneOrMore(or_ + atom) + + # Even-numbered tokens will be '', so we drop them + disjunction.setParseAction(lambda _s, _l, t: [""] + t[1::2]) + + expr = disjunction | nary | unary | atom + return expr + + +def match(cmp_value, spec): + """Match a given value to a given spec DSL. + + This uses the grammar defined by make_grammar() + :param cmp_value: Value to be checked for match. + :param spec: The comparison specification string, for example ``">= 70"`` + or ``"s== string_value"``. See ``make_grammar()`` for examples + of a specification string. + :returns: True if cmp_value is a match for spec. False otherwise. + """ + expr = make_grammar() + try: + # As of 2018-01-29 documentation on parseString() + # https://pythonhosted.org/pyparsing/pyparsing.ParserElement-class.html#parseString + # + # parseString() will take our specification string, for example "< 6" + # and convert it into a list of ['<', "6"] + tree = expr.parseString(spec) + except pyparsing.ParseException: + # If an exception then we will just check if the value matches the spec + tree = [spec] + if len(tree) == 1: + return tree[0] == cmp_value + + # tree[0] will contain a string representation of a comparison operation + # such as '>=', we then convert that string to a comparison function + compare_func = op_methods[tree[0]] + return compare_func(cmp_value, *tree[1:]) diff --git a/bmp-agent/bmpa/utils/strutils.py b/bmp-agent/bmpa/utils/strutils.py new file mode 100755 index 0000000..988d596 --- /dev/null +++ b/bmp-agent/bmpa/utils/strutils.py @@ -0,0 +1,357 @@ +import math +import re + +import six + +UNIT_SYSTEM_INFO = { + 'IEC': (1024, re.compile(r'(^[-+]?\d*\.?\d+)([KMGT]i?)?(b|bit|B)$')), + 'SI': (1000, re.compile(r'(^[-+]?\d*\.?\d+)([kMGT])?(b|bit|B)$')), + 'mixed': (None, re.compile(r'(^[-+]?\d*\.?\d+)([kKMGT]i?)?(b|bit|B)$')), +} + +UNIT_PREFIX_EXPONENT = { + 'k': 1, + 'K': 1, + 'Ki': 1, + 'M': 2, + 'Mi': 2, + 'G': 3, + 'Gi': 3, + 'T': 4, + 'Ti': 4, +} + +TRUE_STRINGS = ('1', 't', 'true', 'on', 'y', 'yes') +FALSE_STRINGS = ('0', 'f', 'false', 'off', 'n', 'no') + + +def string_to_bytes(text, unit_system='IEC', return_int=False): + """Converts a string into an float representation of bytes. + + The units supported for IEC / mixed:: + + Kb(it), Kib(it), Mb(it), Mib(it), Gb(it), Gib(it), Tb(it), Tib(it) + KB, KiB, MB, MiB, GB, GiB, TB, TiB + + The units supported for SI :: + + kb(it), Mb(it), Gb(it), Tb(it) + kB, MB, GB, TB + + SI units are interpreted as power-of-ten (e.g. 1kb = 1000b). Note + that the SI unit system does not support capital letter 'K' + + IEC units are interpreted as power-of-two (e.g. 1MiB = 1MB = + 1024b) + + Mixed units interpret the "i" to mean IEC, and no "i" to mean SI + (e.g. 1kb = 1000b, 1kib == 1024b). Additionaly, mixed units + interpret 'K' as power-of-ten. This mode is not particuarly + useful for new code, but can help with compatability for parsers + such as GNU parted. + + :param text: String input for bytes size conversion. + :param unit_system: Unit system for byte size conversion. + :param return_int: If True, returns integer representation of text + in bytes. (default: decimal) + :returns: Numerical representation of text in bytes. + :raises ValueError: If text has an invalid value. + + """ + try: + base, reg_ex = UNIT_SYSTEM_INFO[unit_system] + except KeyError: + msg = 'Invalid unit system: "%s"' % unit_system + raise ValueError(msg) + match = reg_ex.match(text) + if match: + magnitude = float(match.group(1)) + unit_prefix = match.group(2) + if match.group(3) in ['b', 'bit']: + magnitude /= 8 + + # In the mixed matcher, IEC units (with a trailing 'i') are + # interpreted as power-of-two, others as power-of-ten + if unit_system == 'mixed': + if unit_prefix and not unit_prefix.endswith('i'): + # For maximum compatability in mixed mode, we understand + # "K" (which is not strict SI) as "k" + if unit_prefix.startswith == 'K': + unit_prefix = 'k' + base = 1000 + else: + base = 1024 + else: + msg = 'Invalid string format: %s' % text + raise ValueError(msg) + + if not unit_prefix: + res = magnitude + else: + res = magnitude * pow(base, UNIT_PREFIX_EXPONENT[unit_prefix]) + if return_int: + return int(math.ceil(res)) + return res + + +def bool_from_string(subject, strict=False, default=False): + """Interpret a subject as a boolean. + + A subject can be a boolean, a string or an integer. Boolean type value + will be returned directly, otherwise the subject will be converted to + a string. A case-insensitive match is performed such that strings + matching 't','true', 'on', 'y', 'yes', or '1' are considered True and, + when `strict=False`, anything else returns the value specified by + 'default'. + + Useful for JSON-decoded stuff and config file parsing. + + If `strict=True`, unrecognized values, including None, will raise a + ValueError which is useful when parsing values passed in from an API call. + Strings yielding False are 'f', 'false', 'off', 'n', 'no', or '0'. + """ + if isinstance(subject, bool): + return subject + if not isinstance(subject, six.string_types): + subject = six.text_type(subject) + + lowered = subject.strip().lower() + + if lowered in TRUE_STRINGS: + return True + elif lowered in FALSE_STRINGS: + return False + elif strict: + acceptable = ', '.join("'%s'" % s + for s in sorted(TRUE_STRINGS + FALSE_STRINGS)) + msg = _("Unrecognized value '%(val)s', acceptable values are:" + " %(acceptable)s") % { + 'val': subject, + 'acceptable': acceptable + } + raise ValueError(msg) + else: + return default + + +def check_string_length(value, name=None, min_length=0, max_length=None): + """Check the length of specified string. + + :param value: the value of the string + :param name: the name of the string + :param min_length: the min_length of the string + :param max_length: the max_length of the string + :raises TypeError, ValueError: For any invalid input. + + .. versionadded:: 3.7 + """ + if name is None: + name = value + + if not isinstance(value, six.string_types): + msg = _("%s is not a string or unicode") % name + raise TypeError(msg) + + length = len(value) + if length < min_length: + msg = _("%(name)s has %(length)s characters, less than " + "%(min_length)s.") % { + 'name': name, + 'length': length, + 'min_length': min_length + } + raise ValueError(msg) + + if max_length and length > max_length: + msg = _("%(name)s has %(length)s characters, more than " + "%(max_length)s.") % { + 'name': name, + 'length': length, + 'max_length': max_length + } + raise ValueError(msg) + + +def validate_integer(value, name, min_value=None, max_value=None): + """Make sure that value is a valid integer, potentially within range. + + :param value: value of the integer + :param name: name of the integer + :param min_value: min_value of the integer + :param max_value: max_value of the integer + :returns: integer + :raises: ValueError if value is an invalid integer + + .. versionadded:: 3.33 + """ + try: + value = int(str(value)) + except (ValueError, UnicodeEncodeError): + msg = _('%(value_name)s must be an integer') % {'value_name': name} + raise ValueError(msg) + + if min_value is not None and value < min_value: + msg = _('%(value_name)s must be >= %(min_value)d') % { + 'value_name': name, + 'min_value': min_value + } + raise ValueError(msg) + + if max_value is not None and value > max_value: + msg = _('%(value_name)s must be <= %(max_value)d') % { + 'value_name': name, + 'max_value': max_value + } + raise ValueError(msg) + + return value + + +def get_re_items(content, pattern): + pattern_object = re.compile(pattern, re.MULTILINE) + items = [] + for m in pattern_object.finditer(content): + item = m.groups() + items.append(item[0]) + return items + + +_SANITIZE_KEYS = ['password', 'admin_pass', 'public_key', 'public_keys'] + +# Let's build a list of regex objects using the list of +# _SANITIZE_KEYS we already have. This way, we only have to add the new key +# to the list of _SANITIZE_KEYS and we can generate regular expressions +# for XML and JSON automatically. +_SANITIZE_PATTERNS_2 = {} +_SANITIZE_PATTERNS_1 = {} +_SANITIZE_PATTERNS_WILDCARD = {} +_SANITIZE_PATTERNS_ARR = {} + +# Some regular expressions have only one parameter, some +# have two parameters. Use different lists of patterns here. +_FORMAT_PATTERNS_1 = [r'(%(key)s[0-9]*\s*[=]\s*)[^\s^\'^\"]+'] +_FORMAT_PATTERNS_2 = [ + r'(%(key)s[0-9]*\s*[=]\s*[\"\'])[^\"\']*([\"\'])', + r'(%(key)s[0-9]*\s*[=]\s*[\"])[^\"]*([\"])', + r'(%(key)s[0-9]*\s*[=]\s*[\'])[^\']*([\'])', + r'(%(key)s[0-9]*\s+[\"\'])[^\"\']*([\"\'])', + r'([-]{2}%(key)s[0-9]*\s+)[^\'^\"^=^\s]+([\s]*)', + r'(<%(key)s[0-9]*>)[^<]*()', + r'([\"\']%(key)s[0-9]*[\"\']\s*:\s*[\"\'])[^\"\']*' + r'([\"\'])', r'([\'"][^"\']*%(key)s[0-9]*[\'"]\s*:\s*u?[\'"])[^\"\']*' + r'([\'"])', r'([\'"][^\'"]*%(key)s[0-9]*[\'"]\s*,\s*\'--?[A-z]+' + r'\'\s*,\s*u?[\'"])[^\"\']*([\'"])', + r'(%(key)s[0-9]*\s*--?[A-z]+\s*)\S+(\s*)' +] + +# like this "public_keys": ["ssha 1", "ssha 2"] +_FORMAT_PATTERNS_ARR = [ + r'([\"\']\s*%(key)s[0-9]*\s*[\"\']\s*:\s*\[)([^\]]*)(\])'] + +# Keep a separate list of patterns by key so we only +# need to apply the substitutions for keys we find using a quick "in" +# test. +for key in _SANITIZE_KEYS: + _SANITIZE_PATTERNS_1[key] = [] + _SANITIZE_PATTERNS_2[key] = [] + _SANITIZE_PATTERNS_WILDCARD[key] = [] + _SANITIZE_PATTERNS_ARR[key] = [] + + for pattern in _FORMAT_PATTERNS_2: + reg_ex = re.compile(pattern % {'key': key}, re.DOTALL | re.IGNORECASE) + _SANITIZE_PATTERNS_2[key].append(reg_ex) + + for pattern in _FORMAT_PATTERNS_1: + reg_ex = re.compile(pattern % {'key': key}, re.DOTALL | re.IGNORECASE) + _SANITIZE_PATTERNS_1[key].append(reg_ex) + + for pattern in _FORMAT_PATTERNS_ARR: + reg_ex = re.compile(pattern % {'key': key}, re.DOTALL | re.IGNORECASE) + _SANITIZE_PATTERNS_ARR[key].append(reg_ex) + + +# Before submitting a patch to add a new argument to +# this function to allow the caller to pass in "extra" or "additional" +# or "replacement" patterns to be masked out, please note that we have +# discussed that feature many times and always rejected it based on +# the desire to have Oslo functions behave consistently across all +# projects and *especially* to have security features work the same +# way no matter where they are used. If every project adopted its own +# set patterns for secret values, it would be very difficult to audit +# the logging to ensure that everything is properly masked. So, please +# either add your pattern to the module-level variables at the top of +# this file or, even better, pick an existing pattern or key to use in +# your application to ensure that the value is masked by this +# function. +def mask_password(message, secret="***"): # nosec + """Replace password with *secret* in message. + + :param message: The string which includes security information. + :param secret: value with which to replace passwords. + :returns: The unicode value of message with the password fields masked. + + For example: + + >>> mask_password("'password' : 'aaaaa'") + "'password' : '***'" + """ + + try: + message = str(message) + except UnicodeDecodeError: + pass + + substitute1 = r'\g<1>' + secret + substitute2 = r'\g<1>' + secret + r'\g<2>' + substitute_wildcard = r'\g<1>' + + def substitute_arr(secret): + + def replace(match): + pattern = r'(?P["\'])(.*?)(?P=quote)' + reg_ex = re.compile(pattern, re.DOTALL | re.IGNORECASE) + substitute = r'\g' + secret + r'\g' + return match.group(1) + re.sub(reg_ex, substitute, + match.group(2)) + match.group(3) + + return replace + + # Check to see if anything in message contains any key + # specified in _SANITIZE_KEYS, if not then just return the message since + # we don't have to mask any passwords. + for key in _SANITIZE_KEYS: + if key in message.lower(): + for pattern in _SANITIZE_PATTERNS_2[key]: + message = re.sub(pattern, substitute2, message) + for pattern in _SANITIZE_PATTERNS_1[key]: + message = re.sub(pattern, substitute1, message) + # Those case are poorly handled by previous + # patterns. They are passwords with quotes or double quotes. + # They also needs a different way to substitute group this is why + # they aren't fix in the pattern 1 or 2. + for pattern in _SANITIZE_PATTERNS_WILDCARD[key]: + message = re.sub(pattern, substitute_wildcard, message) + + for pattern in _SANITIZE_PATTERNS_ARR[key]: + message = re.sub(pattern, substitute_arr(secret), message) + return message + + +def get_initials(text): + """Generate a string of initials from the input text. + + This function takes a string that contains multiple words separated by spaces + and returns a new string that consists of the uppercase first letter of each word. + + Parameters: + - text (str): A string of text that may contain multiple words. + + Returns: + - str: A string of uppercase initials of the words in the input text. + + Usage examples: + - get_initials("Hard Disk Device") returns "HDD" + """ + words = text.split() + initials = [word[0].upper() for word in words] + return ''.join(initials) diff --git a/bmp-agent/bmpa/utils/system.py b/bmp-agent/bmpa/utils/system.py new file mode 100755 index 0000000..9d138a9 --- /dev/null +++ b/bmp-agent/bmpa/utils/system.py @@ -0,0 +1,89 @@ +import errno +import logging +import os + +from jinja2 import DictLoader +from jinja2 import Environment +from jinja2 import FileSystemLoader + +from bmpa.errors import BmpError + + +LOG = logging.getLogger(__name__) + + +def decode_binary(blob, encoding='utf-8', errors='replace'): + # Converts a binary type into a text type using given encoding. + return blob.decode(encoding, errors=errors) + + +def load_file(path, read_len=None, offset=0, decode=True): + with open(path, "rb") as fp: + if offset: + fp.seek(offset) + contents = fp.read(read_len) if read_len else fp.read() + + if decode: + return decode_binary(contents) + else: + return contents + + +def ensure_dir(path, mode=None): + if path == "": + path = "." + try: + os.makedirs(path) + except OSError as e: + if e.errno != errno.EEXIST: + raise + + if mode is not None: + os.chmod(path, mode) + + +def get_kernel_version_by_dir(target): + LOG.info("Get kernel versioon by dir.") + kernel_path_candidates = [ + os.path.join(target, "usr/src/kernels"), + os.path.join(target, "usr/lib/modules") + ] + for path in kernel_path_candidates: + if os.path.exists(path): + dirs = os.listdir(path) + if dirs: + return dirs[0] + raise BmpError("Get kernels path error.") + + +def get_relative_path(script): + """Get the relative path of a script which ships with bmpa. + + :param script: The script name as a string. + :returns: The relative path of the script. + """ + cwd = os.path.dirname(os.path.realpath(__file__)) + return os.path.join(cwd, '..', script) + + +def render_template(template, params=None, is_file=True): + """Renders Jinja2 template file with given parameters. + + :param template: full path to the Jinja2 template file + :param params: dictionary with parameters to use when rende ring + :param is_file: whether template is file or string with template itself + :returns: the rendered template as a string + """ + if is_file: + tmpl_path, tmpl_name = os.path.split(template) + loader = FileSystemLoader(tmpl_path) + else: + tmpl_name = 'template' + loader = DictLoader({tmpl_name: template}) + env = Environment(loader=loader) + tmpl = env.get_template(tmpl_name) + + if params is not None: + return tmpl.render(params, enumerate=enumerate) + else: + return tmpl.render() diff --git a/bmp-agent/bmpa/utils/udev.py b/bmp-agent/bmpa/utils/udev.py new file mode 100755 index 0000000..a340a82 --- /dev/null +++ b/bmp-agent/bmpa/utils/udev.py @@ -0,0 +1,73 @@ +import logging +import shlex + +from bmpa.utils import executor + +LOG = logging.getLogger(__name__) + +try: + shlex_quote = shlex.quote +except AttributeError: + # python2.7 uses pipes.quote + import pipes + shlex_quote = pipes.quote + + +def udevadm_info(path=None): + """Return a dictionary populated by properties of the device specified + + in the `path` variable via querying udev 'property' database. + :params: path: path to device, either /dev or /sys + :returns: dictionary of key=value pairs as exported from the udev database + :raises: ValueError path is None, ProcessExecutionError on exec error. + """ + if not path: + raise ValueError('Invalid path: "%s"' % path) + + info_cmd = ['udevadm', 'info', '--query=property', '--export', path] + output, _ = executor.execute(*info_cmd) + + # strip for trailing empty line + info = {} + for line in output.splitlines(): + if not line: + continue + # maxsplit=1 gives us key and remaininng part of line is value + # py2.7 on Trusty doesn't have keyword, pass as argument + key, value = line.split('=', 1) + if not value: + value = None + if value: + # preserve spaces in values to match udev database + try: + parsed = shlex.split(value) + except ValueError: + # strip the leading/ending single tick from udev output before + # escaping the value to prevent their inclusion in the result. + trimmed_value = value[1:-1] + try: + quoted = shlex_quote(trimmed_value) + LOG.debug( + 'udevadm_info: quoting shell-escape chars ' + 'in %s=%s -> %s', key, value, quoted) + parsed = shlex.split(quoted) + except ValueError: + escaped_value = (trimmed_value.replace("'", "_").replace( + '"', "_")) + LOG.debug( + 'udevadm_info: replacing shell-escape chars ' + 'in %s=%s -> %s', key, value, escaped_value) + parsed = shlex.split(escaped_value) + if ' ' not in value: + info[key] = parsed[0] + else: + # special case some known entries with spaces, e.g. ID_SERIAL + # and DEVLINKS, see tests/unittests/test_udev.py + if key == "DEVLINKS": + info[key] = shlex.split(parsed[0]) + elif key == 'ID_SERIAL': + info[key] = parsed[0] + else: + info[key] = parsed + + return info diff --git a/bmp-agent/bmpa/utils/urlutils.py b/bmp-agent/bmpa/utils/urlutils.py new file mode 100755 index 0000000..b48d82c --- /dev/null +++ b/bmp-agent/bmpa/utils/urlutils.py @@ -0,0 +1,46 @@ +import logging +import sys +import time + +LOG = logging.getLogger(__name__) + + +def download(url: str, path: str): + """Download url to path""" + if sys.version_info >= (3, ): + import urllib.request as urllib2 + else: + import urllib2 + + buf_len = 8192 + info = None + with open(path, 'wb') as f: + try: + buf = None + fsize = 0 + start = time.time() + last_time = start + u = urllib2.urlopen(url) + info = u.info() + total_size = int(info.get('Content-Length', 1)) + while True: + buf = u.read(buf_len) + if not buf: + break + f.write(buf) + fsize += len(buf) + time_delta = time.time() - last_time + if time_delta >= 10: + progress = fsize / total_size * 100 + LOG.info( + "Downloaded %d bytes from %s to %s in %.2fs (%.2fMbps), %.2f%%.", fsize, + url, path, time.time() - start, fsize / time_delta / 1024 / 1024, progress) + last_time = time.time() + + time_delta = time.time() - start + LOG.info( + "Downloaded %d bytes from %s to %s in %.2fs (%.2fMbps) success.", fsize, + url, path, time_delta, fsize / time_delta / 1024 / 1024) + except Exception as e: + raise e + return path, info diff --git a/bmp-agent/bmpa/utils/utils.py b/bmp-agent/bmpa/utils/utils.py new file mode 100755 index 0000000..0f9baa8 --- /dev/null +++ b/bmp-agent/bmpa/utils/utils.py @@ -0,0 +1,83 @@ +import os +import re + +from bmpa import constants + + +def _read_params_from_file(filepath: str): + """Extract key=value pairs from a file. + + :param filepath: path to a file containing key=value pairs separated by + whitespace or newlines. + :returns: a dictionary representing the content of the file + """ + with open(filepath) as f: + cmdline = f.read() + + options = cmdline.split() + params = {} + for option in options: + if '=' not in option: + continue + k, v = option.split('=', 1) + params[k] = v + + return params + + +def get_agent_params(cmdline_path: str = '/proc/cmdline'): + """Gets parameters passed to the agent via kernel cmdline.""" + return _read_params_from_file(cmdline_path) + + +def hump2underline(hunp_str): + pattern = re.compile(r'([a-z]|\d)([A-Z])') + sub = re.sub(pattern, r'\1_\2', hunp_str).lower() + return sub + + +def json_hump2underline(hump_json_str): + pattern = re.compile(r'"\s*(\w+)\s*"\s*:') + sub = re.sub(pattern, lambda x: '"' + hump2underline(x.group(1)) + '" :', + hump_json_str) + return sub + + +def is_uefi_bootable(): + return os.path.exists('/sys/firmware/efi') is True + + +def merge_list(list1: list, list2: list) -> list: + if list1 and list2: + res = list1 + list2 + elif list1: + res = list1 + elif list2: + res = list2 + else: + res = None + return res + + +def get_boot_mode(boot_mode) -> str: + if boot_mode: + return boot_mode + return constants.UEFI if is_uefi_bootable() else constants.BIOS + + +def convert_disk_size(size, size_unit, capacity=1024): + if size_unit == 'B': + size = size / capacity**3 + size_unit = 'GB' + elif size_unit == 'KB': + size = size / capacity**2 + size_unit = 'GB' + elif size_unit == 'MB': + size = size / capacity + size_unit = 'GB' + + if size_unit == 'GB' and size > capacity: + size = size / capacity + size_unit = 'TB' + + return size, size_unit diff --git a/bmp-agent/bmpa/utils/validates.py b/bmp-agent/bmpa/utils/validates.py new file mode 100644 index 0000000..17e7942 --- /dev/null +++ b/bmp-agent/bmpa/utils/validates.py @@ -0,0 +1,35 @@ +from typing import Dict + + +def is_required(arg: object, param_name): + not_null(arg, param_name) + not_empty(arg, param_name) + + +def check_field(dict_obj: Dict, field: str): + not_field(dict_obj, field) + not_null(dict_obj[field], field) + not_empty(dict_obj[field], field) + + +def not_field(dict_obj: Dict, field: str): + if field not in dict_obj: + raise ValueError('Missing field: [{0}]'.format(field)) + + +def not_null(arg: object, param_name: str): + if arg is None: + raise ValueError("Parameter `{param_name}` cannot not be None".format( + param_name=param_name)) + + +def not_empty(arg: object, param_name: str): + if arg == '': + raise ValueError("Parameter `{param_name}` cannot be empty".format( + param_name=param_name)) + + +def sn_match(sn, sn_now): + if sn != sn_now: + raise ValueError("Sn `{sn}` not match `{sn_now}`".format( + sn=sn, sn_now=sn_now)) diff --git a/bmp-agent/bmpa/version b/bmp-agent/bmpa/version new file mode 100644 index 0000000..12be384 --- /dev/null +++ b/bmp-agent/bmpa/version @@ -0,0 +1 @@ +v2.0.7 \ No newline at end of file diff --git a/bmp-agent/doc/command.md b/bmp-agent/doc/command.md new file mode 100755 index 0000000..6390b12 --- /dev/null +++ b/bmp-agent/doc/command.md @@ -0,0 +1,872 @@ +指令实例模板 +=========================================== + +### ping 探测连接建立 + +```json +{ + "action" : "Ping", + "sn" : "0" +} +``` + +### 收集硬件信息 + +```json +{ + "action" : "CollectHardwareInfo", + "sn" : "0" +} +``` + +response +```json +{ + "action": "CollectHardwareInfo", + "status": "OK", + "message": "run CollectHardwareInfo success.", + "data": { + "raid_driver": "megacli64", + "bmc_address": "10.208.16.165", + "interfaces": [{ + "product": "0x1572", + "vendor": "0x8086", + "name": "eth0", + "bus_info":"0000:01:00.0",//总线位置信息。0000:01:00代表着相应设备编号可用于标识网卡,.0是设备函数,通过.分割前面的可代表网卡设备 + "has_carrier": true, + "ipv4_address": "10.208.14.174",//ip地址 + "switch_manage_ip": "10.208.13.11",//交换机ip + "biosdevname": "p3p1", + "mac_address": "3c:fd:fe:51:f2:30",//mac地址 + "switch_index": "Ten-GigabitEthernet1/0/7"//交换机端口号 + }, { + "product": "0x1572", + "vendor": "0x8086", + "name": "eth1", + "bus_info":"0000:01:00.1", + "has_carrier": true, + "ipv4_address": "10.208.14.175", + "switch_manage_ip": "10.208.13.11", + "biosdevname": "p3p2", + "mac_address": "3c:fd:fe:51:f2:31", + "switch_index": "Ten-GigabitEthernet1/0/8" + }], + "disks": [], + "boot": { + "current_boot_mode": "bios" + }, + "system_vendor": { + "serial_number": "J33H4YT", + "product_name": "System x3650 M5: -[8871AC1]- ((none))", + "manufacturer": "LENOVO" + }, + "memory": { + "physical_mb": 131072, + "total": 134743052288 + }, + "cpu": { + "count": 32, + "frequency": "3000.0000", + "flags": ["fpu", "vme", "de", "pse", "tsc", "msr", "pae", "mce", "cx8", "apic", "sep", "mtrr", "pge", "mca", "cmov", "pat", "pse36", "clflush", "dts", "acpi", "mmx", "fxsr", "sse", "sse2", "ss", "ht", "tm", "pbe", "syscall", "nx", "pdpe1gb", "rdtscp", "lm", "constant_tsc", "arch_perfmon", "pebs", "bts", "rep_good", "nopl", "xtopology", "nonstop_tsc", "aperfmperf", "eagerfpu", "pni", "pclmulqdq", "dtes64", "monitor", "ds_cpl", "vmx", "smx", "est", "tm2", "ssse3", "sdbg", "fma", "cx16", "xtpr", "pdcm", "pcid", "dca", "sse4_1", "sse4_2", "x2apic", "movbe", "popcnt", "tsc_deadline_timer", "aes", "xsave", "avx", "f16c", "rdrand", "lahf_lm", "abm", "3dnowprefetch", "epb", "cat_l3", "cdp_l3", "invpcid_single", "intel_ppin", "intel_pt", "tpr_shadow", "vnmi", "flexpriority", "ept", "vpid", "fsgsbase", "tsc_adjust", "bmi1", "hle", "avx2", "smep", "bmi2", "erms", "invpcid", "rtm", "cqm", "rdt_a", "rdseed", "adx", "smap", "xsaveopt", "cqm_llc", "cqm_occup_llc", "cqm_mbm_total", "cqm_mbm_local", "dtherm", "ida", "arat", "pln", "pts"], + "model_name": "Intel(R) Xeon(R) CPU E5-2620 v4 @ 2.10GHz", + "architecture": "x86_64" + }, + "platform":{ + "machine":"x86_64" //系统架构 x86_64、aarch64 + } + }, + "sn": "J33H4YT" +} +``` + +### 收集硬盘信息 + +```json +{ + "action" : "CollectDiskLocations", + "sn" : "0", + "raid_driver" : "" //可选。传参:sas2ircu,sas3ircu,megacli64,storcli64,perccli64,arcconf。不传参数则只可采集已适配机型,如果未适配则采集失败 +} +``` + +response +``` json +{ + "action": "CollectDiskLocations", + "status": "OK", + "message": "run CollectDiskLocations success.", + "data": { + "controllers": [{ + "disks": [{ + "enclosure": 8, + "slot": 0, + "size": 278.464, + "size_unit": "GB", + "pd_type": "SAS", + "media_type": "SDD" + }, { + "enclosure": 8, //int + "slot": 1,// int + "size": 278.464, //硬盘大小 float + "size_unit": "GB", //硬盘大小单位 GB TB ,1024进制 + "pd_type": "SAS", //接口类型 + "media_type": "SDD" //磁盘类型 + }], + "adapter_id": 0, + }], + "nvme":{ + "devices" : [// nvme无须做raid enclosure,slot都设置为0即可 + { + "device_path" : "/dev/nvme0n1", + "index" : 0, + "serial" : "BTLJ133609V74P0VGN", + "size" : 4.000787030016, + "size_unit": "TB", + "pd_type": "NVME", + "media_type": "SDD" + } + ] + }, + "devices":[ + { + "device_path": "/dev/sda",//此盘符可能是直通盘符,也可能是做了raid后组成的盘符 + "media_type": "SSD", + "serial": "600062b20313f5c029d090b717000e67", + "size": 798.999183360, + "size_unit": "GB", + }, + { + "device_path": "/dev/sdb", + "media_type": "SSD", + "serial": "600062b20313f5c029d090b717f8cb7d", + "size": 999.9999827968, + "size_unit": "GB", + } + ] + }, + "sn": "J33H4YT" +} +``` + +### make raid + +```json +{ + "action": "MakeRaid", + "sn": "0", + "raid_datas": [{ + "raid_driver": "megacli64", //可选。sas2ircu,sas3ircu,megacli64,storcli64,perccli64,arcconf。不传时,系统自动判断使用哪个raid driver + "adapter_id": 0, + "volumes": [{ + "volume_id": "v-lloenltsstdkqraogf5cqconvbsg",//uuid 用于response数据返回时进行数据关联 + "is_root_device": true, // 可选。是否是系统盘,true表示是系统盘。不传时根据盘符由小到大排序,第一块为系统盘 + "raid_level": "RAID5", //raid类型:NORAID,RAID0,RAID1,RAID5,RAID10 + "physical_disks": [{ + "enclosure": 8, + "slot": 0, + }, + { + "enclosure": 8, + "slot": 1 + }, + { + "enclosure": 8, + "slot": 2 + }, + { + "enclosure": 8, + "slot": 3 + }, + { + "enclosure": 8, + "slot": 4, + } + ] + }, + { + "volume_id": "v-ptuu7zhtmqydeutrvciyfbjv3pjw", + "is_data_device": true, //[字段废弃] 可选。是否是数据盘,true表示是数据盘。不传时根据盘符由小到大排序,第二块为数据盘 + "raid_level": "RAID1", + "physical_disks": [{ + "enclosure": 8, + "slot": 5 + }, + { + "enclosure": 8, + "slot": 6 + } + ] + } + ] + }] +} +``` + +response +```json +{ + "sn": "J33RFRX", + "action": "MakeRaid", + "code": 200, + "message": "Run MakeRaid success.", + "data": { + "raid_datas": [{ + "adapter_id": 0, + "volumes": [{ + "volume_id": "v-lloenltsstdkqraogf5cqconvbsg", + "disk_hints": { + "name": "/dev/sda", + "model": "ServeRAID M5210", + "size": 298999349248, + "rotational": true, + "wwn": "0x600605b00d89bb80", + "serial": "600605b00d89bb802de2e524599e42e9", + "vendor": "IBM", + "wwn_with_extension": "0x600605b00d89bb802de2e524599e42e9", + "wwn_vendor_extension": "0x2de2e524599e42e9", + "hctl": "0:2:0:0", + "by_path": "/dev/disk/by-path/pci-0000:0b:00.0-scsi-0:2:0:0" + } + }, { + "volume_id": "v-ptuu7zhtmqydeutrvciyfbjv3pjw", + "disk_hints": { + "name": "/dev/sdb", + "model": "ServeRAID M5210", + "size": 798999183360, + "rotational": true, + "wwn": "0x600605b00d89bb80", + "serial": "600605b00d89bb802de2e52659c204d8", + "vendor": "IBM", + "wwn_with_extension": "0x600605b00d89bb802de2e52659c204d8", + "wwn_vendor_extension": "0x2de2e52659c204d8", + "hctl": "0:2:1:0", + "by_path": "/dev/disk/by-path/pci-0000:0b:00.0-scsi-0:2:1:0" + } + }] + }] + }, + "status": "OK" +} +``` + +### clean raid + +```json +{ + "action": "CleanRaid", + "sn": "0", + "raid_datas": [{ + "raid_driver": "megacli64", //可选。sas2ircu,sas3ircu,megacli64,storcli64,perccli64,arcconf。不传时,系统自动判断使用哪个raid driver + "adapter_id": 0 + }] +} + + +``` +创建分区 +```json +{ + "action": "MakePartitions", + "sn": "0", + "version": "2.0", + "boot_mode": "uefi",//可选,默认:空。不传此参数时,agent将自动判断模式 + "auto_create_efi": true, //可选,默认:true。uefi模式下自动创建efi分区 + "auto_create_bios_grub": true,//可选,默认:true。bios模式下自动创建bios_grub分区 + "volumes": [{ + "keep_data": false,//true:保留数据, false:不保留数据。新装机器时为false + "is_root_device": true,//可选。相对于disk_hints优先级更高 + "disk_hints":{"serial": "600062b10030a4802c961499f2a09445"},//可选。可指定特定的盘符进行分区 + "disk_label": "gpt", + "partitions": [ + { + "id": "ipt-haxcsxs570fhqew36zuuilks5w6v",//表uuid + "part_type":"esp",//可选 + "fs_type":"fat32",//可选 + "boot_flag": "boot",//可选。bios模式:引导分区需要设置此参数(有boot分区时是) + "number": 1, + "size": 512 //单位Mb + }, + { + "id": "ipt-1bt811r0feavi4sfln5nyyz8qgvg", + "number": 2, + "size": 102400 + } + ] + }, + { + "keep_data": true, //true:保留数据, false:不保留数据。新装机器时为false + "is_data_device": true,//[字段废弃]可选 + "disk_hints":{"serial": "600062b10030a4802c961499f2a09445"}, + "disk_label": "gpt", + "partitions": [ + { + "id": "ipt-ptuu7zhtmqydeutrvciyfbjv3pjw", + "number": 1, + "size": 512 + }, + { + "id": "ipt- llnm71kosh9l7yvwggungl2uawwx", + "number": 2, + "size": 102400 + } + ] + } + ] +} +``` +备注:重装系统保留数据时:只传系统盘分区,不要传数据盘等相关分区。格式化分区也只传系统盘相关。 + +格式化分区 +```json +{ + "action": "FormatPartitions", + "sn": "0", + "version":"2.0", + "partitions": [ + { + "volume": "ipt-1bt811r0feavi4sfln5nyyz8qgvg",// 此参数来自,MakePartitions的 "id": "ipt-1bt811r0feavi4sfln5nyyz8qgvg" 或MakeSoftRaid的 "id": "ipg-yhzcyaxnw6rtieorpgfdnbfshfh9" + "is_root": true, //是否是根分区 + "fs_type": "ext4", + "label": "l_root" + } + ] +} +``` + +### 挂载目录 +```json +{ + "action": "MountPartitions", + "sn": "0", + "version":"2.0", + "auto_mount_efi":true, //可选,自动挂载efi分区 + "mounts": [{ + "is_root_device": true, + "disk_hints":{"serial": "600062b10030a4802c961499f2a09445"},//盘符特性信息。确定盘符信息由is_root_device或disk_hints确定is_root_device优先级更高 + "label":"l_root",//label只在每个盘符下唯一,所以同时需要确定盘符的相应信息 + "options": "errors=remount-ro", + "mountpoint": "/" + }, + { + "is_data_device": true, //[字段废弃] + "disk_hints":{"serial": "600062b10030a4802c961499f2a09445"},//盘符特性信息。确定盘符信息由is_root_device或disk_hints确定is_root_device优先级更高 + "label":"l_export", + "options": "errors=remount-ro", + "mountpoint": "/export" + } + ] +} +``` + +### 写镜像 + +```json +{ + "action" : "WriteImage", + "sn" : "0", + "url" : "{host}/ubuntu-trusty.qcow2", + "format" : "qcow2", + "hash" : "d3a470cc4d53fa89026ad7433964f769", + "filename" : "ubuntu-trusty.qcow2" +} +``` + +```json +{ + "sn": "0", + "action": "WriteImage", + "code": 200, + "message": "Run WriteImage success.", + "data": { + "root_device_hints": { + "name": "/dev/sdp", + "model": "LogicalDrv 0", + "size": 600070840320, + "rotational": true, + "wwn": "0x600508b1001c3cfe", + "serial": "600508b1001c3cfe2d5e6e4568e31521", + "vendor": "SmartIO", + "wwn_with_extension": "0x600508b1001c3cfe2d5e6e4568e31521", + "wwn_vendor_extension": "0x2d5e6e4568e31521", + "hctl": "0:0:0:0", + "by_path": "/dev/disk/by-path/pci-0000:01:00.0-scsi-0:0:0:0" + } + }, + "status": "OK" +} +``` + +# 写Tar镜像 +```json +{ + "action": "WriteImageTar", + "sn": "0", + "url": "{host}/v1.3.0-centos-6.6-2020112716.tar.xz", + "format": "tar", + "hash": "281e40975e2091b14c63586bb8a9301e", + "filename": "v1.3.0-centos-6.6-2020112716.tar.xz" +} +``` + +```json +{ + "sn": "0", + "action": "WriteImageTar", + "code": 200, + "message": "Run WriteImageTar success.", + "data": { + "root_device_hints": { + "name": "/dev/sdp", + "model": "LogicalDrv 0", + "size": 600070840320, + "rotational": true, + "wwn": "0x600508b1001c3cfe", + "serial": "600508b1001c3cfe2d5e6e4568e31521", + "vendor": "SmartIO", + "wwn_with_extension": "0x600508b1001c3cfe2d5e6e4568e31521", + "wwn_vendor_extension": "0x2d5e6e4568e31521", + "hctl": "0:0:0:0", + "by_path": "/dev/disk/by-path/pci-0000:01:00.0-scsi-0:0:0:0" + } + }, + "status": "OK" +} +``` + +### 设置 root password + +```json +{ + "action" : "SetPassword", + "sn" : "0", + "password": "beijing", + "username": "root" //windows时是Administrator +} +``` + +### 清理所有磁盘数据 + +```json +{ + "action" : "CleanBlockDevice", + "sn" : "0" +} +``` + +### 初始化设备信息 + +```json + +{ + "action": "InitNode", + "sn": "0", + "node_data": { + "root_device_hints": {"serial": "600062b10030a4802c961499f2a09445"},//可选。只需要传serial一个参数 + "data_device_hints": {"name": "/dev/nvme0n2"},//[字段废弃]可选。name字段预留 + "os_type": "Ubuntu", + "os_version": "20.04" + } +} + +``` + +### windows设置网络bond + +```json +{ + "action": "SetNetworkWindows", + "sn": "0", + "network": { + "services": [{ + "type": "dns", + "address": "172.16.16.16" + }, { + "type": "dns", + "address": "10.16.16.16" + }], + "networks": [{ + "link": "bond0", + "type": "ipv4", + "ip_address": "10.209.10.234", + "netmask": "255.255.255.248", + "routes": [{ + "network": "0.0.0.0", + "netmask": "0.0.0.0", + "gateway": "10.209.10.233" + }] + }, + { + "link": "bond0", + "type": "ipv6", + "ip_address": "fd01:0:1:0:2::4", + "netmask":120, + "routes": [{ + "network": "::", + "netmask": "::", + "gateway": "fd01:0:1:0:1" + }] + } + ], + "links": [{ + "ethernet_mac_address": "0c:42:a1:d8:64:6a", + "type": "phy", + "id": "eth0", + "mtu": 1500 + }, { + "ethernet_mac_address": "0c:42:a1:d8:64:6b", + "type": "phy", + "id": "eth1", + "mtu": 1500 + }, { + "bond_miimon": 100, + "ethernet_mac_address": "0c:42:a1:d8:64:6a", + "bond_mode": "802.3ad", + "bond_links": ["eth0", "eth1"], + "type": "bond", + "id": "bond0" + }] + } +} +``` +### windows设置网络,网口非聚合 +```json +{ + "action": "SetNetworkWindows", + "sn": "0", + "network": { + "services": [{ + "type": "dns", + "address": "172.16.16.16" + }, { + "type": "dns", + "address": "10.16.16.16" + }], + "networks": [{ + "ip_address": "10.209.10.234", + "type": "ipv4", + "netmask": "255.255.255.248", + "link": "eth0", + "routes": [{ + "network": "10.209.10.234", + "netmask": "255.255.255.248", + "gateway": "10.209.10.233" + }, { + "network": "0.0.0.0", + "netmask": "0.0.0.0", + "gateway": "10.209.10.233" + } + ] + }, + { + "ip_address": "2403:1EC0:8549:60C0::4", + "type": "ipv6", + "netmask": "64", + "link": "eth0", + "routes": [{ + "network": "::", + "netmask": "::", + "gateway": "2403:1EC0:8549:60C0::1" + } + ] + } + ], + "links": [{ + "ethernet_mac_address": "0c:42:a1:d8:64:6a", + "type": "phy", + "id": "eth0", + "mtu": 1500 + }] + } +} +``` + +### linux 设置 network bond +```json +{ + "action": "SetNetwork", + "sn": "0", + "network": { + "ethernets": { + "eth0": {//网卡key 使用网卡名称 + "match": { + "macaddress": "38:68:dd:04:8e:68" //网卡mac地址 + }, + "set-name": "eth0" //网卡名称 + }, + "eth1": { + "match": { + "macaddress": "38:68:dd:04:8e:69" + }, + "set-name": "eth1" + } + }, + "bonds": { + "bond0": { + "macaddress": "38:68:dd:04:8e:68", //eth0 对应网卡mac + "addresses": ["10.0.0.2/16", "2402:db40:51ba:f1::3/64"], //私有地址ip+子网cidr 支持ipv4和ipv6同时设置 + "gateway4": "10.0.0.1", //子网网关 + "gateway6":"2402:db40:51ba:af::1", //设置ipv6地址时必传 + "nameservers": { + "addresses": ["114.114.114.114", "8.8.8.8"] //dns地址 + }, + "interfaces": ["eth0", "eth1"], //关联的网卡key + "parameters": { + "mode": "802.3ad", //当前传此固定值 + "mii-monitor-interval": 100 //整型 当前传此固定值 + } + } + }, + "version": 2 //整型 + } +} + +``` + +### linux 设置 network 非聚合 +#### 说明 +- 双网口vpc时,辅网口不要设置gateway4,否则cloud-init会为其设置默认路由0.0.0.0与主网卡冲突 +- 双网口基础网络环境,开启外网时(eth1是外网),此时eth0不设置gateway4,eth1设置gateway4 +```json + +{ + "action": "SetNetwork", + "sn": "0", + "network": { + "ethernets": { + "eth0": {//网卡key 使用网卡名称 + "match": { + "macaddress": "38:68:dd:04:8e:68" //网卡mac地址 + }, + "set-name": "eth0", //set-name 是中划线不是下划线 + "addresses": ["10.0.0.2/16", "2402:db40:51ba:f1::3/64"], //私有地址ip+子网cidr 支持ipv4和ipv6同时设置 + "netmask":"255.255.0.0", + "gateway4": "10.0.0.1", + "gateway6": "2402:db40:51ba:af::1", //设置ipv6地址时必传 + "nameservers": { + "addresses": ["103.224.222.222", "103.224.222.223"] + }, + "routes":[ + { + "to":"0.0.0.0/0", //固定值全局路由 + "via":"10.0.0.1" //子网网关 + }, + { + "to":"10.0.0.0/16",//vpc网段 + "via":"10.0.0.1" //子网网关 + } + ] + }, + "eth1": { + "match": { + "macaddress": "38:68:dd:04:8e:69" //网卡mac地址 + }, + "set-name": "eth1", + "addresses": ["192.168.0.4/27", "2402:db40:51ba:af::3/64"], //ipv6辅网卡无需设置gateway6 + "netmask":"255.255.255.224", + "nameservers": { + "addresses": ["103.224.222.222", "103.224.222.223"] + }, + "routes":[ + { + "to":"192.168.0.0/26", //vpc网段 + "via":"192.168.0.1" //子网网关 + } + ] + } + }, + "version": 2 //整型 + } +} +``` + +### 设置 metadata +```json +{ + "action": "SetMetaData", + "sn": "0", + "meta_data": { + "instance-id": "cps-s4r3e3exknzbo8wxr2nkdwuz5v94", //required 实例id + "local-hostname": "host001", //required 主机名 + "public-keys": ["ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC0vbep6l/mGZh8XItDj2oaldOPYiZXb1MkQlpC1zhda9YXzdFoufKrqFH4o5Gch6ve7/wncEUarnGb49IEjGdN77ooLQ+wWTw1HnJCKy1CPYVFL1oMYt2+89gh9HlyjbpyHnlHXG2hvklYvKVNtqQqDTwOM8794/W/Ik3H8iES8dCrD1+XoljSxDSaM6ou/h/W7tVflLI5TN74I/uxdOdRzbisB662HZXIXysGR6jMvUpvbENolB7j1S1ttWGs2sNKOcpExu76EcvOcLoTqdwbZ0fOG/q5xsgcTuPtyECzOK336u+VsBnp1vxdLzLcQi8Ry1+2NrnAN9U4pW0gEdab"]//公钥值 不需设置时,不要传此参数 + } +} +``` +### 设置 userdata +```json +{ + "action" : "SetUserData",//不设置用户自定义脚本时,Linux系统也需要传此指令,user_data传空字符串。Nocloud必须要有user_data文件才认为读取数据正常。Windows系统可不传此指令 + "sn" : "0", + "user_data":"IyEvYmluL2Jhc2gKZWNobyAndGVzdCB1c2VyIGRhdGEnID4gL3Jvb3QvZmlsZQ==" //用户自定义数据 +} +``` + +### 设置 vendordata +```json +{ + "action": "SetVendorData",//此指令暂时可不使用,未来扩展使用 + "sn": "0", + "vendor_data": { + "local-hostname": "hostname001" + } +} +``` + +### 设置 cloudinit 配置文件 +```json +{ + "action" : "SetCloudinitConf", + "sn" : "0", + "ssh_pwauth":"yes" //yes:启用密码登陆 //no禁用密码登陆 +} +``` + +#### raid_driver 可用值 +- sas2ircu +- sas3ircu +- megacli64 +- storcli64 +- perccli64 +- arcconf + +### TAR镜像,装机模版 +#### 不做raid,新装 +- DHCPConfigAddHost +- SetPXEBoot +- Ping +- InitNode +- MakePartitions +- FormatPartitions +- MountPartitions +- WriteImageTar +- SetPassword +- SetCloudinitConf +- SetMetaData +- SetNetwork +- SetUserData +- DHCPConfigDelHost +- SetDISKBoot +- PowerCycle +#### 不做raid,重装 +- DHCPConfigAddHost +- SetPXEBoot +- Ping +- InitNode +- MakePartitions +- FormatPartitions 1.保留数据时,只传系统盘相关信息;2.不保留数据时,同新装传全量数据 +- MountPartitions +- WriteImageTar +- SetPassword +- SetCloudinitConf +- SetMetaData +- SetNetwork +- SetUserData +- DHCPConfigDelHost +- SetDISKBoot +- PowerCycle +#### 做raid,新装 +- DHCPConfigAddHost +- SetPXEBoot +- Ping +- MakeRaid +- InitNode +- MakePartitions +- FormatPartitions +- MountPartitions +- WriteImageTar +- SetPassword +- SetCloudinitConf +- SetMetaData +- SetNetwork +- SetUserData +- DHCPConfigDelHost +- SetDISKBoot +- PowerCycle +#### 做raid,重装 +- DHCPConfigAddHost +- SetPXEBoot +- Ping +- InitNode +- MakePartitions +- FormatPartitions 1.保留数据时,只传系统盘相关信息;2.不保留数据时,同新装传全量数据 +- MountPartitions +- WriteImageTar +- SetPassword +- SetCloudinitConf +- SetMetaData +- SetNetwork +- SetUserData +- DHCPConfigDelHost +- SetDISKBoot +- PowerCycle +#### 修改密码 +- DHCPConfigAddHost +- SetPXEBoot +- Ping +- InitNode +- SetPassword +- DHCPConfigDelHost +- PowerOff +### QCOW2,TAR通用模版 +#### 不做raid,销毁机器 +- DHCPConfigAddHost +- SetPXEBoot +- Ping +- CleanBlockDevice +- DHCPConfigDelHost +- PowerOff +#### 做raid,销毁机器 +- DHCPConfigAddHost +- SetPXEBoot +- Ping +- CleanBlockDevice +- CleanRaid +- DHCPConfigDelHost +- PowerOff +### WINDOWS QCOW2镜像,装机模版 +SetMetaData,部分传参变化 +- hostname变更为local-hostname +- uuid变更为instance-id +#### 不做raid,新装,重装相同 +- DHCPConfigAddHost +- SetPXEBoot +- Ping +- InitNode +- WriteImage +- SetPassword +- SetMetaData +- SetNetworkWindows +- SetUserData(设置自定义脚本设置需要此指令,不设置时不需要) +- DHCPConfigDelHost +- SetDISKBoot +- PowerCycle +#### 做raid,新装,重装相同 +- DHCPConfigAddHost +- SetPXEBoot +- Ping +- MakeRaid +- InitNode +- WriteImage +- SetPassword +- SetMetaData +- SetNetworkWindows +- SetUserData(设置自定义脚本设置需要此指令,不设置时不需要) +- DHCPConfigDelHost +- SetDISKBoot +- PowerCycle +#### 修改密码 +- DHCPConfigAddHost +- SetPXEBoot +- Ping +- InitNode +- SetPassword +- DHCPConfigDelHost +- PowerOff + + +## 备注 +对于特殊机器新增TFTPConfigAddGrub、TFTPConfigDelGrub指令 +``` +TFTPConfigDelGrub、TFTPConfigAddGrub放在DHCPConfigAddHost前面 +TFTPConfigDelGrub放在DHCPConfigDelHost后面 +``` + diff --git a/bmp-agent/doc/raid/arcconf.md b/bmp-agent/doc/raid/arcconf.md new file mode 100755 index 0000000..eebda77 --- /dev/null +++ b/bmp-agent/doc/raid/arcconf.md @@ -0,0 +1,1038 @@ +Controllers found: 1 +---------------------------------------------------------------------- +Controller information +---------------------------------------------------------------------- + Controller Status : Optimal + Controller Mode : Mixed + Channel description : SCSI + Controller Model : Adaptec SmartIOC 8i + Controller Serial Number : Unknown + Controller World Wide Name : 50123456789ABC00 + Physical Slot : 10 + Temperature : 48 C/ 118 F (Normal) + Power Consumption : Not Applicable + Power Mode : Unknown + Power Mode Operational : Unknown + Survival Mode : Unknown + Host bus type : PCIe 3.0 + Host bus speed : 7880 MBps + Host bus link width : 8 bit(s)/link(s) + PCI Address (Bus:Device:Function) : 0:1:0:0 + I2C Address : 0xDE + I2C Clock Speed : 400 KHZ + I2C Clock Stretching : Enabled + Number of Ports : 2 + Internal Port Count : 2 + External Port Count : 0 + Defunct disk drive count : 0 + Logical devices/Failed/Degraded : 1/0/0 + NCQ status : Enabled + Queue Depth : Automatic + Monitor and Performance Delay : 60 minutes + Elevator Sort : Enabled + Degraded Mode Performance Optimization : Disabled + Latency : Default + Statistics data collection mode : Disabled + Global Physical Device Write Cache Policy: Disabled + maxCache RAID5 WriteBack Enabled : Disabled + maxCache Version : Not Applicable + Post Prompt Timeout : 15 seconds + Boot Controller : False + Primary Boot Volume : None + Secondary Boot Volume : None + Driver Name : aacraid + Driver Supports SSD Smart Path : No + Manufacturing Part Number : Not Applicable + Manufacturing Spare Part Number : Not Applicable + Manufacturing Wellness Log : Not Applicable + -------------------------------------------------------- + RAID Properties + -------------------------------------------------------- + Automatic Failover : Disabled + Background consistency check : Idle + Consistency Check Delay : 3 seconds + Parallel Consistency Check Supported : Enabled + Parallel Consistency Check Count : 1 + Inconsistency Repair Policy : Disabled + Consistency Check Inconsistency Notify : Disabled + Rebuild Priority : High + Expand Priority : Medium + -------------------------------------------------------- + Controller Version Information + -------------------------------------------------------- + Firmware : 3.52[0] + Driver : 1.2.1.50877 + Hardware Revision : B + -------------------------------------------------------- + Temperature Sensors Information + -------------------------------------------------------- + Sensor ID : 0 + Current Value : 32 deg C + Max Value Since Powered On : 33 deg C + Location : Inlet Ambient + + Sensor ID : 1 + Current Value : 48 deg C + Max Value Since Powered On : 49 deg C + Location : ASIC + + +---------------------------------------------------------------------- +Array Information +---------------------------------------------------------------------- +Array Number 0 + Name : A + Status : Ok + Interface : SAS + Total Size : 571904 MB + Unused Size : 0 MB + Block Size : 512 Bytes + Array Utilization : 100.00% Used, 0.00% Unused + Type : Data + Transformation Status : Not Applicable + Spare Rebuild Mode : Dedicated + -------------------------------------------------------- + Array Logical Device Information + -------------------------------------------------------- + Logical 0 : Optimal (1, Data, 286136 MB) LogicalDrv 0 + -------------------------------------------------------- + Array Physical Device Information + -------------------------------------------------------- + Device 26 : Present (286168MB, SAS, HDD, Connector:0, Enclosure:1, Slot:28) 0AGRGZTH + Device 27 : Present (286168MB, SAS, HDD, Connector:0, Enclosure:1, Slot:29) 0AGRJ8ZH + + +---------------------------------------------------------------------- +Logical device information +---------------------------------------------------------------------- +Logical Device number 0 + Logical Device name : LogicalDrv 0 + Disk Name : /dev/sda + Array : 0 + RAID level : 1 + Status of Logical Device : Optimal + Size : 286136 MB + Full Stripe Size : 256 KB + Interface Type : Serial Attached SCSI + Device Type : Data + Boot Type : None + Heads : 255 + Sectors Per Track : 32 + Cylinders : 65535 + Mount Points : Not Applicable + LD Acceleration Method : None + Volume Unique Identifier : 600508B1001C2EB4A2D267CB8008C226 + -------------------------------------------------------- + Array Physical Device Information + -------------------------------------------------------- + Device 26 : Present (286168MB, SAS, HDD, Connector:0, Enclosure:1, Slot:28) 0AGRGZTH + Device 27 : Present (286168MB, SAS, HDD, Connector:0, Enclosure:1, Slot:29) 0AGRJ8ZH + + +---------------------------------------------------------------------- +Physical Device information +---------------------------------------------------------------------- + Channel #0: + Device #8 + Device is a Hard drive + State : Ready + Drive has stale RIS data : False + Disk Name : /dev/sdb + Block Size : 512 Bytes + Physical Block Size : 4K Bytes + Transfer Speed : SATA 6.0 Gb/s + Reported Channel,Device(T:L) : 0,8(8:0) + Reported Location : Enclosure 1, Slot 0(Connector 0:CN0) + Vendor : ATA + Model : HGST HUS726060AL + Firmware : APBDTAF0 + Serial number : K8G72GUD + World-wide name : 53CE5A63C6BE9000 + Reserved Size : 32768 KB + Used Size : 0 MB + Unused Size : 5723134 MB + Total Size : 5723166 MB + S.M.A.R.T. : No + S.M.A.R.T. warnings : 0 + SSD : No + NCQ supported : Supported + NCQ status : Enabled + Boot Type : None + Rotational Speed : 7200 RPM + Current Temperature : 29 deg C + Maximum Temperature : 43 deg C + Threshold Temperature : 65 deg C + PHY Count : 1 + Drive Configuration Type : Unassigned + Mount Point(s) : Not Mounted + Drive Exposed to OS : True + Sanitize Erase Support : False + Drive Unique ID : BF1324C6FF7FAF02FF7FA3DAFFFF4565 + Last Failure Reason : No Failure + ---------------------------------------------------------------- + Device Phy Information + ---------------------------------------------------------------- + Phy #0 + Negotiated Link Rate : 6 Gbps + Maximum Link Rate : 6 Gbps + + ---------------------------------------------------------------- + Device Error Counters + ---------------------------------------------------------------- + Aborted Commands : 0 + Bad Target Errors : 0 + Ecc Recovered Read Errors : 0 + Failed Read Recovers : 0 + Failed Write Recovers : 0 + Format Errors : 0 + Hardware Errors : 0 + Hard Read Errors : 0 + Hard Write Errors : 0 + Hot Plug Count : 0 + Media Failures : 0 + Not Ready Errors : 0 + Other Time Out Errors : 0 + Predictive Failures : 0 + Retry Recovered Read Errors : 0 + Retry Recovered Write Errors : 0 + Scsi Bus Faults : 0 + + Device #9 + Device is a Hard drive + State : Ready + Drive has stale RIS data : False + Disk Name : /dev/sdc + Block Size : 512 Bytes + Physical Block Size : 4K Bytes + Transfer Speed : SATA 6.0 Gb/s + Reported Channel,Device(T:L) : 0,9(9:0) + Reported Location : Enclosure 1, Slot 1(Connector 0:CN0) + Vendor : ATA + Model : HGST HUS726060AL + Firmware : APBDTAF0 + Serial number : K8G9N2BN + World-wide name : 53CE5A63C6BE9001 + Reserved Size : 32768 KB + Used Size : 0 MB + Unused Size : 5723134 MB + Total Size : 5723166 MB + S.M.A.R.T. : No + S.M.A.R.T. warnings : 0 + SSD : No + NCQ supported : Supported + NCQ status : Enabled + Boot Type : None + Rotational Speed : 7200 RPM + Current Temperature : 29 deg C + Maximum Temperature : 44 deg C + Threshold Temperature : 65 deg C + PHY Count : 1 + Drive Configuration Type : Unassigned + Mount Point(s) : Not Mounted + Drive Exposed to OS : True + Sanitize Erase Support : False + Drive Unique ID : 3F3477B83FAD5F613FAD58513F21DB55 + Last Failure Reason : No Failure + ---------------------------------------------------------------- + Device Phy Information + ---------------------------------------------------------------- + Phy #0 + Negotiated Link Rate : 6 Gbps + Maximum Link Rate : 6 Gbps + + ---------------------------------------------------------------- + Device Error Counters + ---------------------------------------------------------------- + Aborted Commands : 0 + Bad Target Errors : 0 + Ecc Recovered Read Errors : 0 + Failed Read Recovers : 0 + Failed Write Recovers : 0 + Format Errors : 0 + Hardware Errors : 0 + Hard Read Errors : 0 + Hard Write Errors : 0 + Hot Plug Count : 0 + Media Failures : 0 + Not Ready Errors : 0 + Other Time Out Errors : 0 + Predictive Failures : 0 + Retry Recovered Read Errors : 0 + Retry Recovered Write Errors : 0 + Scsi Bus Faults : 0 + + Device #10 + Device is a Hard drive + State : Ready + Drive has stale RIS data : False + Disk Name : /dev/sdd + Block Size : 512 Bytes + Physical Block Size : 4K Bytes + Transfer Speed : SATA 6.0 Gb/s + Reported Channel,Device(T:L) : 0,10(10:0) + Reported Location : Enclosure 1, Slot 2(Connector 0:CN0) + Vendor : ATA + Model : HGST HUS726060AL + Firmware : APBDTAF0 + Serial number : K8GADKYN + World-wide name : 53CE5A63C6BE9002 + Reserved Size : 32768 KB + Used Size : 0 MB + Unused Size : 5723134 MB + Total Size : 5723166 MB + S.M.A.R.T. : No + S.M.A.R.T. warnings : 0 + SSD : No + NCQ supported : Supported + NCQ status : Enabled + Boot Type : None + Rotational Speed : 7200 RPM + Current Temperature : 29 deg C + Maximum Temperature : 43 deg C + Threshold Temperature : 65 deg C + PHY Count : 1 + Drive Configuration Type : Unassigned + Mount Point(s) : Not Mounted + Drive Exposed to OS : True + Sanitize Erase Support : False + Drive Unique ID : 3FCCE374FF7B3FD1FF7B3E99FFBBE0D9 + Last Failure Reason : No Failure + ---------------------------------------------------------------- + Device Phy Information + ---------------------------------------------------------------- + Phy #0 + Negotiated Link Rate : 6 Gbps + Maximum Link Rate : 6 Gbps + + ---------------------------------------------------------------- + Device Error Counters + ---------------------------------------------------------------- + Aborted Commands : 0 + Bad Target Errors : 0 + Ecc Recovered Read Errors : 0 + Failed Read Recovers : 0 + Failed Write Recovers : 0 + Format Errors : 0 + Hardware Errors : 0 + Hard Read Errors : 0 + Hard Write Errors : 0 + Hot Plug Count : 0 + Media Failures : 0 + Not Ready Errors : 0 + Other Time Out Errors : 0 + Predictive Failures : 0 + Retry Recovered Read Errors : 0 + Retry Recovered Write Errors : 0 + Scsi Bus Faults : 0 + + Device #11 + Device is a Hard drive + State : Ready + Drive has stale RIS data : False + Disk Name : /dev/sde + Block Size : 512 Bytes + Physical Block Size : 4K Bytes + Transfer Speed : SATA 6.0 Gb/s + Reported Channel,Device(T:L) : 0,11(11:0) + Reported Location : Enclosure 1, Slot 3(Connector 0:CN0) + Vendor : ATA + Model : HGST HUS726060AL + Firmware : APBDTAF0 + Serial number : K8GA18MD + World-wide name : 53CE5A63C6BE9003 + Reserved Size : 32768 KB + Used Size : 0 MB + Unused Size : 5723134 MB + Total Size : 5723166 MB + S.M.A.R.T. : No + S.M.A.R.T. warnings : 0 + SSD : No + NCQ supported : Supported + NCQ status : Enabled + Boot Type : None + Rotational Speed : 7200 RPM + Current Temperature : 30 deg C + Maximum Temperature : 45 deg C + Threshold Temperature : 65 deg C + PHY Count : 1 + Drive Configuration Type : Unassigned + Mount Point(s) : Not Mounted + Drive Exposed to OS : True + Sanitize Erase Support : False + Drive Unique ID : 3F7AA1FA7FFE23DB3FFE22AB3F66A58C + Last Failure Reason : No Failure + ---------------------------------------------------------------- + Device Phy Information + ---------------------------------------------------------------- + Phy #0 + Negotiated Link Rate : 6 Gbps + Maximum Link Rate : 6 Gbps + + ---------------------------------------------------------------- + Device Error Counters + ---------------------------------------------------------------- + Aborted Commands : 0 + Bad Target Errors : 0 + Ecc Recovered Read Errors : 0 + Failed Read Recovers : 0 + Failed Write Recovers : 0 + Format Errors : 0 + Hardware Errors : 0 + Hard Read Errors : 0 + Hard Write Errors : 0 + Hot Plug Count : 0 + Media Failures : 0 + Not Ready Errors : 0 + Other Time Out Errors : 0 + Predictive Failures : 0 + Retry Recovered Read Errors : 0 + Retry Recovered Write Errors : 0 + Scsi Bus Faults : 0 + + Device #12 + Device is a Hard drive + State : Ready + Drive has stale RIS data : False + Disk Name : /dev/sdf + Block Size : 512 Bytes + Physical Block Size : 4K Bytes + Transfer Speed : SATA 6.0 Gb/s + Reported Channel,Device(T:L) : 0,12(12:0) + Reported Location : Enclosure 1, Slot 4(Connector 0:CN0) + Vendor : ATA + Model : ST6000NM0115-1YZ + Firmware : SN05 + Serial number : ZADAQJMV + World-wide name : 53CE5A63C6BE9004 + Reserved Size : 32768 KB + Used Size : 0 MB + Unused Size : 5723134 MB + Total Size : 5723166 MB + S.M.A.R.T. : No + S.M.A.R.T. warnings : 0 + SSD : No + NCQ supported : Supported + NCQ status : Enabled + Boot Type : None + Rotational Speed : 7200 RPM + Current Temperature : 27 deg C + Maximum Temperature : 44 deg C + Threshold Temperature : 65 deg C + PHY Count : 1 + Drive Configuration Type : Unassigned + Mount Point(s) : Not Mounted + Drive Exposed to OS : True + Sanitize Erase Support : True + Drive Unique ID : 3F5C016CBFBFFF0EBFBC578EBF3C9A92 + Last Failure Reason : No Failure + ---------------------------------------------------------------- + Device Phy Information + ---------------------------------------------------------------- + Phy #0 + Negotiated Link Rate : 6 Gbps + Maximum Link Rate : 6 Gbps + + ---------------------------------------------------------------- + Device Error Counters + ---------------------------------------------------------------- + Aborted Commands : 0 + Bad Target Errors : 0 + Ecc Recovered Read Errors : 0 + Failed Read Recovers : 0 + Failed Write Recovers : 0 + Format Errors : 0 + Hardware Errors : 0 + Hard Read Errors : 0 + Hard Write Errors : 0 + Hot Plug Count : 0 + Media Failures : 0 + Not Ready Errors : 0 + Other Time Out Errors : 0 + Predictive Failures : 0 + Retry Recovered Read Errors : 0 + Retry Recovered Write Errors : 0 + Scsi Bus Faults : 0 + + Device #13 + Device is a Hard drive + State : Ready + Drive has stale RIS data : False + Disk Name : /dev/sdg + Block Size : 512 Bytes + Physical Block Size : 4K Bytes + Transfer Speed : SATA 6.0 Gb/s + Reported Channel,Device(T:L) : 0,13(13:0) + Reported Location : Enclosure 1, Slot 5(Connector 0:CN0) + Vendor : ATA + Model : HGST HUS726060AL + Firmware : APBDTAF0 + Serial number : K8GABGVN + World-wide name : 53CE5A63C6BE9005 + Reserved Size : 32768 KB + Used Size : 0 MB + Unused Size : 5723134 MB + Total Size : 5723166 MB + S.M.A.R.T. : No + S.M.A.R.T. warnings : 0 + SSD : No + NCQ supported : Supported + NCQ status : Enabled + Boot Type : None + Rotational Speed : 7200 RPM + Current Temperature : 29 deg C + Maximum Temperature : 44 deg C + Threshold Temperature : 65 deg C + PHY Count : 1 + Drive Configuration Type : Unassigned + Mount Point(s) : Not Mounted + Drive Exposed to OS : True + Sanitize Erase Support : False + Drive Unique ID : FF817C9FFFFF7F22FFEF67F2FF6D0AED + Last Failure Reason : No Failure + ---------------------------------------------------------------- + Device Phy Information + ---------------------------------------------------------------- + Phy #0 + Negotiated Link Rate : 6 Gbps + Maximum Link Rate : 6 Gbps + + ---------------------------------------------------------------- + Device Error Counters + ---------------------------------------------------------------- + Aborted Commands : 0 + Bad Target Errors : 0 + Ecc Recovered Read Errors : 0 + Failed Read Recovers : 0 + Failed Write Recovers : 0 + Format Errors : 0 + Hardware Errors : 0 + Hard Read Errors : 0 + Hard Write Errors : 0 + Hot Plug Count : 0 + Media Failures : 0 + Not Ready Errors : 0 + Other Time Out Errors : 0 + Predictive Failures : 0 + Retry Recovered Read Errors : 0 + Retry Recovered Write Errors : 0 + Scsi Bus Faults : 0 + + Device #14 + Device is a Hard drive + State : Ready + Drive has stale RIS data : False + Disk Name : /dev/sdh + Block Size : 512 Bytes + Physical Block Size : 4K Bytes + Transfer Speed : SATA 6.0 Gb/s + Reported Channel,Device(T:L) : 0,14(14:0) + Reported Location : Enclosure 1, Slot 6(Connector 0:CN0) + Vendor : ATA + Model : HGST HUS726060AL + Firmware : APBDTAF0 + Serial number : K8G9WLPD + World-wide name : 53CE5A63C6BE9006 + Reserved Size : 32768 KB + Used Size : 0 MB + Unused Size : 5723134 MB + Total Size : 5723166 MB + S.M.A.R.T. : No + S.M.A.R.T. warnings : 0 + SSD : No + NCQ supported : Supported + NCQ status : Enabled + Boot Type : None + Rotational Speed : 7200 RPM + Current Temperature : 29 deg C + Maximum Temperature : 43 deg C + Threshold Temperature : 65 deg C + PHY Count : 1 + Drive Configuration Type : Unassigned + Mount Point(s) : Not Mounted + Drive Exposed to OS : True + Sanitize Erase Support : False + Drive Unique ID : 3FD465E37FFB4BB57F7B4A453FC2CC26 + Last Failure Reason : No Failure + ---------------------------------------------------------------- + Device Phy Information + ---------------------------------------------------------------- + Phy #0 + Negotiated Link Rate : 6 Gbps + Maximum Link Rate : 6 Gbps + + ---------------------------------------------------------------- + Device Error Counters + ---------------------------------------------------------------- + Aborted Commands : 0 + Bad Target Errors : 0 + Ecc Recovered Read Errors : 0 + Failed Read Recovers : 0 + Failed Write Recovers : 0 + Format Errors : 0 + Hardware Errors : 0 + Hard Read Errors : 0 + Hard Write Errors : 0 + Hot Plug Count : 0 + Media Failures : 0 + Not Ready Errors : 0 + Other Time Out Errors : 0 + Predictive Failures : 0 + Retry Recovered Read Errors : 0 + Retry Recovered Write Errors : 0 + Scsi Bus Faults : 0 + + Device #15 + Device is a Hard drive + State : Ready + Drive has stale RIS data : False + Disk Name : /dev/sdi + Block Size : 512 Bytes + Physical Block Size : 4K Bytes + Transfer Speed : SATA 6.0 Gb/s + Reported Channel,Device(T:L) : 0,15(15:0) + Reported Location : Enclosure 1, Slot 7(Connector 0:CN0) + Vendor : ATA + Model : HGST HUS726060AL + Firmware : APBDTAF0 + Serial number : K8GA39KD + World-wide name : 53CE5A63C6BE9007 + Reserved Size : 32768 KB + Used Size : 0 MB + Unused Size : 5723134 MB + Total Size : 5723166 MB + S.M.A.R.T. : No + S.M.A.R.T. warnings : 0 + SSD : No + NCQ supported : Supported + NCQ status : Enabled + Boot Type : None + Rotational Speed : 7200 RPM + Current Temperature : 29 deg C + Maximum Temperature : 43 deg C + Threshold Temperature : 65 deg C + PHY Count : 1 + Drive Configuration Type : Unassigned + Mount Point(s) : Not Mounted + Drive Exposed to OS : True + Sanitize Erase Support : False + Drive Unique ID : 3FAC8A6CFFBFBD47FF1BB5FF7F9B9772 + Last Failure Reason : No Failure + ---------------------------------------------------------------- + Device Phy Information + ---------------------------------------------------------------- + Phy #0 + Negotiated Link Rate : 6 Gbps + Maximum Link Rate : 6 Gbps + + ---------------------------------------------------------------- + Device Error Counters + ---------------------------------------------------------------- + Aborted Commands : 0 + Bad Target Errors : 0 + Ecc Recovered Read Errors : 0 + Failed Read Recovers : 0 + Failed Write Recovers : 0 + Format Errors : 0 + Hardware Errors : 0 + Hard Read Errors : 0 + Hard Write Errors : 0 + Hot Plug Count : 0 + Media Failures : 0 + Not Ready Errors : 0 + Other Time Out Errors : 0 + Predictive Failures : 0 + Retry Recovered Read Errors : 0 + Retry Recovered Write Errors : 0 + Scsi Bus Faults : 0 + + Device #16 + Device is a Hard drive + State : Ready + Drive has stale RIS data : False + Disk Name : /dev/sdj + Block Size : 512 Bytes + Physical Block Size : 4K Bytes + Transfer Speed : SATA 6.0 Gb/s + Reported Channel,Device(T:L) : 0,16(16:0) + Reported Location : Enclosure 1, Slot 8(Connector 0:CN0) + Vendor : ATA + Model : HGST HUS726060AL + Firmware : APBDTAF0 + Serial number : K8G9WBKD + World-wide name : 53CE5A63C6BE9008 + Reserved Size : 32768 KB + Used Size : 0 MB + Unused Size : 5723134 MB + Total Size : 5723166 MB + S.M.A.R.T. : No + S.M.A.R.T. warnings : 0 + SSD : No + NCQ supported : Supported + NCQ status : Enabled + Boot Type : None + Rotational Speed : 7200 RPM + Current Temperature : 29 deg C + Maximum Temperature : 43 deg C + Threshold Temperature : 65 deg C + PHY Count : 1 + Drive Configuration Type : Unassigned + Mount Point(s) : Not Mounted + Drive Exposed to OS : True + Sanitize Erase Support : False + Drive Unique ID : 3F0C7AABFFFF3D9DFF7E3CB57FFABEA6 + Last Failure Reason : No Failure + ---------------------------------------------------------------- + Device Phy Information + ---------------------------------------------------------------- + Phy #0 + Negotiated Link Rate : 6 Gbps + Maximum Link Rate : 6 Gbps + + ---------------------------------------------------------------- + Device Error Counters + ---------------------------------------------------------------- + Aborted Commands : 0 + Bad Target Errors : 0 + Ecc Recovered Read Errors : 0 + Failed Read Recovers : 0 + Failed Write Recovers : 0 + Format Errors : 0 + Hardware Errors : 0 + Hard Read Errors : 0 + Hard Write Errors : 0 + Hot Plug Count : 0 + Media Failures : 0 + Not Ready Errors : 0 + Other Time Out Errors : 0 + Predictive Failures : 0 + Retry Recovered Read Errors : 0 + Retry Recovered Write Errors : 0 + Scsi Bus Faults : 0 + + Device #17 + Device is a Hard drive + State : Ready + Drive has stale RIS data : False + Disk Name : /dev/sdk + Block Size : 512 Bytes + Physical Block Size : 4K Bytes + Transfer Speed : SATA 6.0 Gb/s + Reported Channel,Device(T:L) : 0,17(17:0) + Reported Location : Enclosure 1, Slot 9(Connector 0:CN0) + Vendor : ATA + Model : HGST HUS726060AL + Firmware : APBDTAF0 + Serial number : K8G6A3JD + World-wide name : 53CE5A63C6BE9009 + Reserved Size : 32768 KB + Used Size : 0 MB + Unused Size : 5723134 MB + Total Size : 5723166 MB + S.M.A.R.T. : No + S.M.A.R.T. warnings : 0 + SSD : No + NCQ supported : Supported + NCQ status : Enabled + Boot Type : None + Rotational Speed : 7200 RPM + Current Temperature : 29 deg C + Maximum Temperature : 44 deg C + Threshold Temperature : 65 deg C + PHY Count : 1 + Drive Configuration Type : Unassigned + Mount Point(s) : Not Mounted + Drive Exposed to OS : True + Sanitize Erase Support : False + Drive Unique ID : 3F0F8B66FF7FA714FF7BA374BFFB6540 + Last Failure Reason : No Failure + ---------------------------------------------------------------- + Device Phy Information + ---------------------------------------------------------------- + Phy #0 + Negotiated Link Rate : 6 Gbps + Maximum Link Rate : 6 Gbps + + ---------------------------------------------------------------- + Device Error Counters + ---------------------------------------------------------------- + Aborted Commands : 0 + Bad Target Errors : 0 + Ecc Recovered Read Errors : 0 + Failed Read Recovers : 0 + Failed Write Recovers : 0 + Format Errors : 0 + Hardware Errors : 0 + Hard Read Errors : 0 + Hard Write Errors : 0 + Hot Plug Count : 0 + Media Failures : 0 + Not Ready Errors : 0 + Other Time Out Errors : 0 + Predictive Failures : 0 + Retry Recovered Read Errors : 0 + Retry Recovered Write Errors : 0 + Scsi Bus Faults : 0 + + Device #18 + Device is a Hard drive + State : Ready + Drive has stale RIS data : False + Disk Name : /dev/sdl + Block Size : 512 Bytes + Physical Block Size : 4K Bytes + Transfer Speed : SATA 6.0 Gb/s + Reported Channel,Device(T:L) : 0,18(18:0) + Reported Location : Enclosure 1, Slot 10(Connector 0:CN0) + Vendor : ATA + Model : HGST HUS726060AL + Firmware : APBDTAF0 + Serial number : K8GAA8WD + World-wide name : 53CE5A63C6BE900A + Reserved Size : 32768 KB + Used Size : 0 MB + Unused Size : 5723134 MB + Total Size : 5723166 MB + S.M.A.R.T. : No + S.M.A.R.T. warnings : 0 + SSD : No + NCQ supported : Supported + NCQ status : Enabled + Boot Type : None + Rotational Speed : 7200 RPM + Current Temperature : 29 deg C + Maximum Temperature : 44 deg C + Threshold Temperature : 65 deg C + PHY Count : 1 + Drive Configuration Type : Unassigned + Mount Point(s) : Not Mounted + Drive Exposed to OS : True + Sanitize Erase Support : False + Drive Unique ID : 3FB2F3BEFFDE9B377F5E9B0F7F9E7DEB + Last Failure Reason : No Failure + ---------------------------------------------------------------- + Device Phy Information + ---------------------------------------------------------------- + Phy #0 + Negotiated Link Rate : 6 Gbps + Maximum Link Rate : 6 Gbps + + ---------------------------------------------------------------- + Device Error Counters + ---------------------------------------------------------------- + Aborted Commands : 0 + Bad Target Errors : 0 + Ecc Recovered Read Errors : 0 + Failed Read Recovers : 0 + Failed Write Recovers : 0 + Format Errors : 0 + Hardware Errors : 0 + Hard Read Errors : 0 + Hard Write Errors : 0 + Hot Plug Count : 0 + Media Failures : 0 + Not Ready Errors : 0 + Other Time Out Errors : 0 + Predictive Failures : 0 + Retry Recovered Read Errors : 0 + Retry Recovered Write Errors : 0 + Scsi Bus Faults : 0 + + Device #19 + Device is a Hard drive + State : Ready + Drive has stale RIS data : False + Disk Name : /dev/sdm + Block Size : 512 Bytes + Physical Block Size : 4K Bytes + Transfer Speed : SATA 6.0 Gb/s + Reported Channel,Device(T:L) : 0,19(19:0) + Reported Location : Enclosure 1, Slot 11(Connector 0:CN0) + Vendor : ATA + Model : HGST HUS726060AL + Firmware : APBDTAF0 + Serial number : K8G89X1D + World-wide name : 53CE5A63C6BE900B + Reserved Size : 32768 KB + Used Size : 0 MB + Unused Size : 5723134 MB + Total Size : 5723166 MB + S.M.A.R.T. : No + S.M.A.R.T. warnings : 0 + SSD : No + NCQ supported : Supported + NCQ status : Enabled + Boot Type : None + Rotational Speed : 7200 RPM + Current Temperature : 29 deg C + Maximum Temperature : 43 deg C + Threshold Temperature : 65 deg C + PHY Count : 1 + Drive Configuration Type : Unassigned + Mount Point(s) : Not Mounted + Drive Exposed to OS : True + Sanitize Erase Support : False + Drive Unique ID : 3F7C24CBFFFF39F3FFFF392B7F6B1C9D + Last Failure Reason : No Failure + ---------------------------------------------------------------- + Device Phy Information + ---------------------------------------------------------------- + Phy #0 + Negotiated Link Rate : 6 Gbps + Maximum Link Rate : 6 Gbps + + ---------------------------------------------------------------- + Device Error Counters + ---------------------------------------------------------------- + Aborted Commands : 0 + Bad Target Errors : 0 + Ecc Recovered Read Errors : 0 + Failed Read Recovers : 0 + Failed Write Recovers : 0 + Format Errors : 0 + Hardware Errors : 0 + Hard Read Errors : 0 + Hard Write Errors : 0 + Hot Plug Count : 0 + Media Failures : 0 + Not Ready Errors : 0 + Other Time Out Errors : 0 + Predictive Failures : 0 + Retry Recovered Read Errors : 0 + Retry Recovered Write Errors : 0 + Scsi Bus Faults : 0 + + Device #26 + Device is a Hard drive + State : Online + Drive has stale RIS data : False + Block Size : 512 Bytes + Physical Block Size : 512 Bytes + Transfer Speed : SAS 12.0 Gb/s + Reported Channel,Device(T:L) : 0,26(26:0) + Reported Location : Enclosure 1, Slot 28(Connector 0:CN0) + Array : 0 + Vendor : HGST + Model : HUC101830CSS200 + Firmware : ADB0 + Serial number : 0AGRGZTH + World-wide name : 5000CCA07C28E1C9 + Reserved Size : 32768 KB + Used Size : 286136 MB + Unused Size : 0 MB + Total Size : 286168 MB + S.M.A.R.T. : No + S.M.A.R.T. warnings : 0 + SSD : No + Boot Type : None + Rotational Speed : 10500 RPM + Current Temperature : 34 deg C + Maximum Temperature : Not Applicable + Threshold Temperature : 85 deg C + PHY Count : 2 + Drive Configuration Type : Data + Mount Point(s) : Not Mounted + Drive Exposed to OS : False + Sanitize Erase Support : False + Drive Unique ID : 5000CCA07C28E1C8619300085000CCA0 + Last Failure Reason : No Failure + ---------------------------------------------------------------- + Device Phy Information + ---------------------------------------------------------------- + Phy #0 + Negotiated Link Rate : Reserved [11] + Maximum Link Rate : Reserved [11] + Phy #1 + Negotiated Link Rate : unknown + Maximum Link Rate : Reserved [11] + + + Device #27 + Device is a Hard drive + State : Online + Drive has stale RIS data : False + Block Size : 512 Bytes + Physical Block Size : 512 Bytes + Transfer Speed : SAS 12.0 Gb/s + Reported Channel,Device(T:L) : 0,27(27:0) + Reported Location : Enclosure 1, Slot 29(Connector 0:CN0) + Array : 0 + Vendor : HGST + Model : HUC101830CSS200 + Firmware : ADB0 + Serial number : 0AGRJ8ZH + World-wide name : 5000CCA07C28F541 + Reserved Size : 32768 KB + Used Size : 286136 MB + Unused Size : 0 MB + Total Size : 286168 MB + S.M.A.R.T. : No + S.M.A.R.T. warnings : 0 + SSD : No + Boot Type : None + Rotational Speed : 10500 RPM + Current Temperature : 35 deg C + Maximum Temperature : Not Applicable + Threshold Temperature : 85 deg C + PHY Count : 2 + Drive Configuration Type : Data + Mount Point(s) : Not Mounted + Drive Exposed to OS : False + Sanitize Erase Support : False + Drive Unique ID : 5000CCA07C28F540619300085000CCA0 + Last Failure Reason : No Failure + ---------------------------------------------------------------- + Device Phy Information + ---------------------------------------------------------------- + Phy #0 + Negotiated Link Rate : Reserved [11] + Maximum Link Rate : Reserved [11] + Phy #1 + Negotiated Link Rate : unknown + Maximum Link Rate : Reserved [11] + + + Channel #2: + Device #0 + Device is an Enclosure Services Device + Reported Channel,Device(T:L) : 2,0(0:0) + Reported Location : Connector 0, Enclosure 1 + Enclosure ID : 1 + Enclosure Logical Identifier : 53CE5A63C6BE907E + Expander ID : 0 + Expander SAS Address : 53CE5A63C6BE907F + Type : SES2 + Vendor : H3C-Exp + Model : SXP 36x12G + Firmware : RevB + Status of Enclosure Services Device + Speaker status : Not Available + Channel #2: + Device #3 + Device is an Enclosure Services Device + Reported Channel,Device(T:L) : 2,3(3:0) + Enclosure ID : 0 + Enclosure Logical Identifier : 50123456789ABC00 + Type : SES2 + Vendor : ADAPTEC + Model : Virtual SGPIO + Firmware : 3.52 + Status of Enclosure Services Device + Speaker status : Not Available + + +---------------------------------------------------------------------- +Connector information +---------------------------------------------------------------------- +Connector #0 + Connector Name : CN0 + Functional Mode : Mixed + Connector Location : Internal + SAS Address : 50123456789ABC00 + + +Connector #1 + Connector Name : CN1 + Functional Mode : Mixed + Connector Location : Internal + SAS Address : 50123456789ABC04 + diff --git a/bmp-agent/doc/raid/megacli.md b/bmp-agent/doc/raid/megacli.md new file mode 100755 index 0000000..503466f --- /dev/null +++ b/bmp-agent/doc/raid/megacli.md @@ -0,0 +1,99 @@ +Adapter #0 + +Enclosure Device ID: 32 +Slot Number: 0 +Drive's position: DiskGroup: 0, Span: 0, Arm: 0 +Enclosure position: 1 +Device Id: 0 +WWN: 5000C500B75B7350 +Sequence Number: 2 +Media Error Count: 0 +Other Error Count: 0 +Predictive Failure Count: 0 +Last Predictive Failure Event Seq Number: 0 +PD Type: SAS + +Raw Size: 279.396 GB [0x22ecb25c Sectors] +Non Coerced Size: 278.896 GB [0x22dcb25c Sectors] +Coerced Size: 278.875 GB [0x22dc0000 Sectors] +Sector Size: 512 +Logical Sector Size: 512 +Physical Sector Size: 512 +Firmware state: Online, Spun Up +Device Firmware Level: BS04 +Shield Counter: 0 +Successful diagnostics completion on : N/A +SAS Address(0): 0x5000c500b75b7351 +SAS Address(1): 0x0 +Connected Port Number: 0(path0) +Inquiry Data: SEAGATE ST300MM0078 BS04W0K1SSQF +FDE Capable: Not Capable +FDE Enable: Disable +Secured: Unsecured +Locked: Unlocked +Needs EKM Attention: No +Foreign State: None +Device Speed: 12.0Gb/s +Link Speed: 12.0Gb/s +Media Type: Hard Disk Device +Drive Temperature :20C (68.00 F) +PI Eligibility: No +Drive is formatted for PI information: Yes +PI: PI with type 2 +Port-0 : +Port status: Active +Port's Linkspeed: 12.0Gb/s +Port-1 : +Port status: Active +Port's Linkspeed: 12.0Gb/s +Drive has flagged a S.M.A.R.T alert : No + + + +Enclosure Device ID: 32 +Slot Number: 1 +Drive's position: DiskGroup: 0, Span: 0, Arm: 1 +Enclosure position: 1 +Device Id: 1 +WWN: 5000C500B75B92E0 +Sequence Number: 2 +Media Error Count: 0 +Other Error Count: 0 +Predictive Failure Count: 0 +Last Predictive Failure Event Seq Number: 0 +PD Type: SAS + +Raw Size: 279.396 GB [0x22ecb25c Sectors] +Non Coerced Size: 278.896 GB [0x22dcb25c Sectors] +Coerced Size: 278.875 GB [0x22dc0000 Sectors] +Sector Size: 512 +Logical Sector Size: 512 +Physical Sector Size: 512 +Firmware state: Online, Spun Up +Device Firmware Level: BS04 +Shield Counter: 0 +Successful diagnostics completion on : N/A +SAS Address(0): 0x5000c500b75b92e1 +SAS Address(1): 0x0 +Connected Port Number: 0(path0) +Inquiry Data: SEAGATE ST300MM0078 BS04W0K1SSEF +FDE Capable: Not Capable +FDE Enable: Disable +Secured: Unsecured +Locked: Unlocked +Needs EKM Attention: No +Foreign State: None +Device Speed: 12.0Gb/s +Link Speed: 12.0Gb/s +Media Type: Hard Disk Device +Drive Temperature :20C (68.00 F) +PI Eligibility: No +Drive is formatted for PI information: Yes +PI: PI with type 2 +Port-0 : +Port status: Active +Port's Linkspeed: 12.0Gb/s +Port-1 : +Port status: Active +Port's Linkspeed: 12.0Gb/s +Drive has flagged a S.M.A.R.T alert : No diff --git a/bmp-agent/doc/raid/perccli.md b/bmp-agent/doc/raid/perccli.md new file mode 100755 index 0000000..e4199f4 --- /dev/null +++ b/bmp-agent/doc/raid/perccli.md @@ -0,0 +1,339 @@ +{ +"Controllers":[ +{ + "Command Status" : { + "CLI Version" : "007.1623.0000.0000 May 17, 2021", + "Operating system" : "Linux 3.10.0-1160.53.1.el7.x86_64", + "Controller" : 0, + "Status" : "Success", + "Description" : "None" + }, + "Response Data" : { + "Product Name" : "PERC H750 Adapter", + "Serial Number" : "1AK04HI", + "SAS Address" : " 5f4ee080097f5c00", + "PCI Address" : "00:af:00:00", + "System Time" : "02/25/2022 15:54:45", + "Mfg. Date" : "10/26/21", + "Controller Time" : "02/25/2022 15:54:43", + "FW Package Build" : "52.16.1-4074", + "BIOS Version" : "7.16.00.0_0x07100501", + "FW Version" : "5.160.02-3530", + "Driver Name" : "megaraid_sas", + "Driver Version" : "07.714.04.00-rh1", + "Current Personality" : "RAID-Mode ", + "Vendor Id" : 4096, + "Device Id" : 4322, + "SubVendor Id" : 4136, + "SubDevice Id" : 8566, + "Host Interface" : "PCI-E", + "Device Interface" : "SAS-12G", + "Bus Number" : 175, + "Device Number" : 0, + "Function Number" : 0, + "Domain ID" : 0, + "Security Protocol" : "None", + "Physical Drives" : 18, + "PD LIST" : [ + { + "EID:Slt" : "64:0", + "DID" : 1, + "State" : "UGood", + "DG" : "-", + "Size" : "446.625 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS480G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:1", + "DID" : 6, + "State" : "UGood", + "DG" : "-", + "Size" : "446.625 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS480G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:2", + "DID" : 8, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:3", + "DID" : 3, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:4", + "DID" : 0, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:5", + "DID" : 10, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:6", + "DID" : 5, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:7", + "DID" : 15, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:8", + "DID" : 7, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:9", + "DID" : 9, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:10", + "DID" : 13, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:11", + "DID" : 4, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:12", + "DID" : 2, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:13", + "DID" : 12, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:14", + "DID" : 16, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:15", + "DID" : 14, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:16", + "DID" : 17, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "64:17", + "DID" : 11, + "State" : "UGood", + "DG" : "-", + "Size" : "893.750 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "HFS960G3H2X069N", + "Sp" : "U", + "Type" : "-" + } + ], + "Enclosures" : 1, + "Enclosure LIST" : [ + { + "EID" : 64, + "State" : "OK", + "Slots" : 24, + "PD" : 18, + "PS" : 0, + "Fans" : 0, + "TSs" : 0, + "Alms" : 0, + "SIM" : 1, + "Port#" : "-", + "ProdID" : "BP14G+EXP", + "VendorSpecific" : " (" + } + ], + "BBU_Info" : [ + { + "Model" : "BBU", + "State" : "Optimal", + "RetentionTime" : "0 hour(s)", + "Temp" : "40C", + "Mode" : "-", + "MfgDate" : "0/00/00" + } + ] + } +} +] +} diff --git a/bmp-agent/doc/raid/sas2308.md b/bmp-agent/doc/raid/sas2308.md new file mode 100755 index 0000000..bb1fd97 --- /dev/null +++ b/bmp-agent/doc/raid/sas2308.md @@ -0,0 +1,53 @@ +LSI Corporation SAS2 IR Configuration Utility. +Version 10.00.00.00 (2011.05.12) +Copyright (c) 2009-2010 LSI Corporation. All rights reserved. + +Read configuration has been initiated for controller 0 +------------------------------------------------------------------------ +Controller information +------------------------------------------------------------------------ + Controller type : SAS2308_2 + BIOS version : 7.25.00.00 + Firmware version : 15.00.03.00 + Channel description : 1 Serial Attached SCSI + Initiator ID : 0 + Maximum physical devices : 255 + Concurrent commands supported : 3072 + Slot : 0 + Segment : 0 + Bus : 1 + Device : 0 + Function : 0 + RAID Support : Yes +------------------------------------------------------------------------ +IR Volume information +------------------------------------------------------------------------ +------------------------------------------------------------------------ +Physical device information +------------------------------------------------------------------------ +Initiator at ID #0 + +Device is a Hard disk + Enclosure # : 1 + Slot # : 0 + SAS Address : 5000c50-0-9589-4e45 + State : Ready (RDY) + Size (in MB)/(in sectors) : 286102/585937499 + Manufacturer : HP + Model Number : EG0300FCVBF + Firmware Revision : HPD9 + Serial No : S0M6L7VJ + GUID : 5000c50095894e47 + Protocol : SAS + Drive Type : SAS_HDD +------------------------------------------------------------------------ +Enclosure information +------------------------------------------------------------------------ + Enclosure# : 1 + Logical ID : 5ac853db:088e3000 + Numslots : 8 + StartSlot : 0 + Primary Boot Slot : 0 +------------------------------------------------------------------------ +SAS2IRCU: Command DISPLAY Completed Successfully. +SAS2IRCU: Utility Completed Successfully. \ No newline at end of file diff --git a/bmp-agent/doc/raid/storcli.md b/bmp-agent/doc/raid/storcli.md new file mode 100755 index 0000000..e938f22 --- /dev/null +++ b/bmp-agent/doc/raid/storcli.md @@ -0,0 +1,245 @@ +{ +"Controllers":[ +{ + "Command Status" : { + "CLI Version" : "007.1613.0000.0000 Oct 29, 2020", + "Operating system" : "Linux 3.10.0-1160.59.1.el7.x86_64", + "Controller" : 0, + "Status" : "Success", + "Description" : "None" + }, + "Response Data" : { + "Product Name" : "ServeRAID M5210", + "Serial Number" : "SK73269658", + "SAS Address" : " 500605b00d60a910", + "PCI Address" : "00:0b:00:00", + "System Time" : "03/04/2022 07:10:27", + "Mfg. Date" : "08/10/17", + "Controller Time" : "03/04/2022 07:10:27", + "FW Package Build" : "24.16.0-0104", + "BIOS Version" : "6.32.02.1_4.17.08.00_0x06150501", + "FW Version" : "4.660.00-8218", + "Driver Name" : "megaraid_sas", + "Driver Version" : "07.714.04.00-rh1", + "Vendor Id" : 4096, + "Device Id" : 93, + "SubVendor Id" : 4116, + "SubDevice Id" : 1108, + "Host Interface" : "PCI-E", + "Device Interface" : "SAS-12G", + "Bus Number" : 11, + "Device Number" : 0, + "Function Number" : 0, + "Domain ID" : 0, + "Security Protocol" : "None", + "Physical Drives" : 10, + "PD LIST" : [ + { + "EID:Slt" : "8:0", + "DID" : 10, + "State" : "UGood", + "DG" : "-", + "Size" : "278.464 GB", + "Intf" : "SAS", + "Med" : "HDD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "ST300MM0048 ", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "8:1", + "DID" : 11, + "State" : "UGood", + "DG" : "-", + "Size" : "278.464 GB", + "Intf" : "SAS", + "Med" : "HDD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "ST300MM0048 ", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "8:2", + "DID" : 12, + "State" : "UGood", + "DG" : "-", + "Size" : "893.137 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "MTFDDAK960TCB-1AR1ZA 01GV854 01GV857LEN", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "8:3", + "DID" : 16, + "State" : "UGood", + "DG" : "-", + "Size" : "893.137 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "MTFDDAK960TCB-1AR1ZA 01GV854 01GV857LEN", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "9:4", + "DID" : 15, + "State" : "UGood", + "DG" : "-", + "Size" : "893.137 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "MTFDDAK960TCB-1AR1ZA 01GV854 01GV857LEN", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "9:5", + "DID" : 18, + "State" : "UGood", + "DG" : "-", + "Size" : "893.137 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "MTFDDAK960TCB-1AR1ZA 01GV854 01GV857LEN", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "9:6", + "DID" : 14, + "State" : "UGood", + "DG" : "-", + "Size" : "893.137 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "MTFDDAK960TCB-1AR1ZA 01GV854 01GV857LEN", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "9:7", + "DID" : 19, + "State" : "UGood", + "DG" : "-", + "Size" : "893.137 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "MTFDDAK960TCB-1AR1ZA 01GV854 01GV857LEN", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "9:8", + "DID" : 13, + "State" : "UGood", + "DG" : "-", + "Size" : "893.137 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "MTFDDAK960TCB-1AR1ZA 01GV854 01GV857LEN", + "Sp" : "U", + "Type" : "-" + }, + { + "EID:Slt" : "9:9", + "DID" : 17, + "State" : "UGood", + "DG" : "-", + "Size" : "893.137 GB", + "Intf" : "SATA", + "Med" : "SSD", + "SED" : "N", + "PI" : "N", + "SeSz" : "512B", + "Model" : "MTFDDAK960TCB-1AR1ZA 01GV854 01GV857LEN", + "Sp" : "U", + "Type" : "-" + } + ], + "Enclosures" : 3, + "Enclosure LIST" : [ + { + "EID" : 8, + "State" : "OK", + "Slots" : 32, + "PD" : 4, + "PS" : 0, + "Fans" : 0, + "TSs" : 0, + "Alms" : 0, + "SIM" : 0, + "Port#" : "Port 0 - 3 x4", + "ProdID" : "SAS EXP BP", + "VendorSpecific" : "00000007" + }, + { + "EID" : 9, + "State" : "OK", + "Slots" : 32, + "PD" : 6, + "PS" : 0, + "Fans" : 0, + "TSs" : 0, + "Alms" : 0, + "SIM" : 0, + "Port#" : "Port 4 - 7 x4", + "ProdID" : "SAS EXP BP", + "VendorSpecific" : "00000007" + }, + { + "EID" : 252, + "State" : "OK", + "Slots" : 8, + "PD" : 0, + "PS" : 0, + "Fans" : 0, + "TSs" : 0, + "Alms" : 0, + "SIM" : 1, + "Port#" : "-", + "ProdID" : "SGPIO", + "VendorSpecific" : " " + } + ], + "Cachevault_Info" : [ + { + "Model" : "CVPM02", + "State" : "Optimal", + "Temp" : "21C", + "Mode" : "-", + "MfgDate" : "2017/02/10" + } + ] + } +} +] +} diff --git a/bmp-agent/imagebuild-docker/Makefile b/bmp-agent/imagebuild-docker/Makefile new file mode 100644 index 0000000..7db89b9 --- /dev/null +++ b/bmp-agent/imagebuild-docker/Makefile @@ -0,0 +1,27 @@ +.PHONY: clean +export CUR_DIR=${PWD} + +help: + @echo "build - build vmlinz initramfs.gz " + +install_loongarch64: + ./build.sh -v -d loongarch64_8_4 -b ${CUR_DIR} -i bmp-agent-base:8.4 -a loongarch64 + +install_ubuntu_2204: + ./build.sh -v -d ubuntu_2204 -b ${CUR_DIR} -i bmp-agent-base:2204 -a x86_64 + +install_ubuntu_2204_arm64: + ./build.sh -v -d ubuntu_2204_arm64 -b ${CUR_DIR} -i bmp-agent-base:2204 -a arm64 + +install_ubuntu_2004_arm64: + ./build.sh -v -d ubuntu_2004_arm64 -b ${CUR_DIR} -i bmp-agent-base:2004 -a arm64 + +install_7_9: + ./build.sh -v -d centos_7_9 -b ${CUR_DIR} -i bmp-agent-base:7.9 -a x86_64 + +install: install_7_9 + +install_7_9_arm64: + ./build.sh -v -d centos_7_9_arm64 -b ${CUR_DIR} -i bmp-agent-base:7.9 -a arm64 + +install_arm: install_7_9_arm64 diff --git a/bmp-agent/imagebuild-docker/README.md b/bmp-agent/imagebuild-docker/README.md new file mode 100644 index 0000000..725c8bf --- /dev/null +++ b/bmp-agent/imagebuild-docker/README.md @@ -0,0 +1,21 @@ +# Building RamOS +English | [简体中文](README.zh-CN.md) + +This project will build the vmlinu and initramfs.gz files required for pxe to boot RamOS, and build the agent service into RamOS. + +## Dependency +1. Docker 20.10.19+ +2. JQ + +## Build Process +1. Enter the current directory imagebuild-docker +2. Building RamOS + +Execute the following command to build RamOS based on CentOS 7.9: +``` +make install +``` +After the build is complete, the generated vmlinuz and initramfs.gz files will be located in the ./build/centos_7_9 directory. + +3. Building other versions of RamOS: +See [Makefile](./Makefile) for build options for more versions. diff --git a/bmp-agent/imagebuild-docker/README.zh-CN.md b/bmp-agent/imagebuild-docker/README.zh-CN.md new file mode 100755 index 0000000..1dc0061 --- /dev/null +++ b/bmp-agent/imagebuild-docker/README.zh-CN.md @@ -0,0 +1,21 @@ +# 构建RamOS +[English](README.md) | 简体中文 + +此项目将会构建出pxe引导RamOS所需要的vmlinu和initramfs.gz文件,并将agent服务内置到RamOS中。 + +## 依赖 +1. Docker 20.10.19及以上 +2. JQ + +## 构建过程 +1. 进入到当前目录 imagebuild-docker +2. 构建RamOS + +执行以下命令构建基于 CentOS 7.9 的 RamOS: +``` +make install +``` +构建完成后,生成的 vmlinuz 和 initramfs.gz 文件将位于 ./build/centos_7_9 目录下。 + +3. 构建其他版本的 RamOS: +请参阅[Makefile](./Makefile)获取更多版本的构建选项 diff --git a/bmp-agent/imagebuild-docker/archive.sh b/bmp-agent/imagebuild-docker/archive.sh new file mode 100755 index 0000000..660d2a4 --- /dev/null +++ b/bmp-agent/imagebuild-docker/archive.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +USAGE="Usage: $0 -i input_image_path -o output_image_path -p package_path + +Build vmlinuz and initramfs.gz from imaget.tar.gz + +Options: + -a Architecture + -d distro Operating system distro and version + -i Image path + -o Output build directory + -p Base directory of packages + -h Display this help and exit + -v Turn on verbose messages for debugging + -V Image version +" +while getopts "V:a:d:i:o:p:h:v" OPTION; do + case $OPTION in + V) VERSION=$OPTARG ;; + a) ARCH=$OPTARG ;; + d) DISTRO=$OPTARG ;; + i) IMAGE=$OPTARG ;; + o) OUTPUT_BUILD_DIR=$OPTARG ;; + p) BASE_DIR=$OPTARG ;; + h) echo "$USAGE" && exit 0 ;; + v) set -x && export VERBOSE=1 ;; + *) echo "$USAGE" && exit 1 ;; + esac +done + +set -e + +IMAGE_TMP=$(mktemp -d -t image-XXXXXXX) +INITRAMFS_DIR=$(mktemp -d -t initramfs-XXXXXXX) +ROOTFS_DIR=$(mktemp -d -t rootfs-XXXXXXX) +trap "rm -rf $IMAGE_TMP && rm -rf $INITRAMFS_DIR && rm -rf $ROOTFS_DIR" EXIT +echo $IMAGE_TMP +xz -d -c -f $IMAGE | tar --warning=no-timestamp -x -f - -C $IMAGE_TMP +ls $IMAGE_TMP + +KERNEL=$(ls -al $IMAGE_TMP/boot/vmlinuz-* | awk {'print $9'} | sort -V | grep -v rescue | head -1) +KERNEL_VERSION=$(echo $KERNEL | sed "s:$IMAGE_TMP/boot/vmlinuz-::g") +echo "Kernel version: $KERNEL_VERSION" + +CURRENT_DATE=`date +%Y%m%d%H` +if [ -n "${VERSION}" ]; then + VMLINUZ_NAME="${VERSION}-${DISTRO}-${CURRENT_DATE}-vmlinuz" + INITRAMFS_NAME="${VERSION}-${DISTRO}-${CURRENT_DATE}-initramfs.gz" +else + VMLINUZ_NAME="${DISTRO}-${CURRENT_DATE}-vmlinuz" + INITRAMFS_NAME="${DISTRO}-${CURRENT_DATE}-initramfs.gz" +fi + +# linux kernel +/bin/cp $IMAGE_TMP/boot/vmlinuz-$KERNEL_VERSION $OUTPUT_BUILD_DIR/$VMLINUZ_NAME +chown -R root:root $OUTPUT_BUILD_DIR/$VMLINUZ_NAME +chmod 755 $OUTPUT_BUILD_DIR/$VMLINUZ_NAME + +# busybox +mkdir -p $INITRAMFS_DIR/bin +/bin/cp $BASE_DIR/$ARCH/initramfs/busybox $INITRAMFS_DIR/bin/ +chmod +x $INITRAMFS_DIR/bin/busybox + +# init +/bin/cp $BASE_DIR/$ARCH/initramfs/init $INITRAMFS_DIR/ +chmod +x $INITRAMFS_DIR/init + +# rootfs +/bin/cp $IMAGE $INITRAMFS_DIR/rootfs.tar.xz + +# initramfs +cd $INITRAMFS_DIR +find . -print0 | cpio --null -ov --format=newc | gzip -9 > $OUTPUT_BUILD_DIR/$INITRAMFS_NAME +chown -R root:root $OUTPUT_BUILD_DIR/$INITRAMFS_NAME +chmod 644 $OUTPUT_BUILD_DIR/$INITRAMFS_NAME diff --git a/bmp-agent/imagebuild-docker/arm64/chroot/bmpa.service b/bmp-agent/imagebuild-docker/arm64/chroot/bmpa.service new file mode 100644 index 0000000..b44d62e --- /dev/null +++ b/bmp-agent/imagebuild-docker/arm64/chroot/bmpa.service @@ -0,0 +1,11 @@ +[Unit] +Description=BMP Agent +After=network.target + +[Service] +Environment="PYTHON_EGG_CACHE=/tmp/.cache" +ExecStart=/usr/local/bin/bmp-agent + +[Install] +WantedBy=multi-user.target +Alias=bmpa.service \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/arm64/chroot/fstab b/bmp-agent/imagebuild-docker/arm64/chroot/fstab new file mode 100755 index 0000000..33fb180 --- /dev/null +++ b/bmp-agent/imagebuild-docker/arm64/chroot/fstab @@ -0,0 +1,18 @@ +# /etc/fstab: static file system information. +# +# noatime turns off atimes for increased performance (atimes normally aren't +# needed); notail increases performance of ReiserFS (at the expense of storage +# efficiency). It's safe to drop the noatime options if you want and to +# switch between notail / tail freely. +# +# The root filesystem should have a pass number of either 0 or 1. +# All other filesystems should have a pass number of 0 or greater than 1. +# +# See the manpage fstab(5) for more information. +# + +# + +# NOTE: If your BOOT partition is ReiserFS, add the notail option to opts. +tmpfs /tmp tmpfs rw,size=30% 0 0 +tmpfs /var/log tmpfs rw,size=5% 0 0 \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/arm64/chroot/id_rsa.pub b/bmp-agent/imagebuild-docker/arm64/chroot/id_rsa.pub new file mode 100755 index 0000000..9a6d4f9 --- /dev/null +++ b/bmp-agent/imagebuild-docker/arm64/chroot/id_rsa.pub @@ -0,0 +1 @@ +ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDQtb/De7i3VlPv/efEal5jQXkB9C7rJgjUWhIziUgEcKTtsTZaQMwLY0dJ/OFsLd2BdxQ/d6htPkPNKiseB239i0wkM78fp0MGdAcwcqh998MHQOslO5ckHNC4iM+Z3gQR+gPjwvUKGlXH8KPfOsS78dLTUNWL93Wx56cJLYu6NBysmfLKNgdEFCm8vVAJK9sdxzkHQ49j3fZeL8o5jHu1L0kHk3c/nAMzFqKQh9w0LIQ1So2SlvsWq/N08hKxXc6AEO5rGKOD8tLG+sAdG8BUqY5LVavMRM0wnkuTzYp7GGTxj7Wzrlmm9YNzCI+w9hlIEWVXuEpJ0jY9800Dfyh7 root@A02-R12-I168-156-6ZDHZX1.JD.LOCAL \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/arm64/chroot/interfaces b/bmp-agent/imagebuild-docker/arm64/chroot/interfaces new file mode 100755 index 0000000..a9ccdf0 --- /dev/null +++ b/bmp-agent/imagebuild-docker/arm64/chroot/interfaces @@ -0,0 +1,33 @@ +# interfaces(5) file used by ifup(8) and ifdown(8) +# Include files from /etc/network/interfaces.d: +source-directory /etc/network/interfaces.d + +auto lo +iface lo inet loopback + +allow-hotplug eth0 +iface eth0 inet dhcp + +allow-hotplug eth1 +iface eth1 inet dhcp + +allow-hotplug eth2 +iface eth2 inet dhcp + +allow-hotplug eth3 +iface eth3 inet dhcp + +allow-hotplug eth4 +iface eth4 inet dhcp + +allow-hotplug eth5 +iface eth5 inet dhcp + +allow-hotplug eth6 +iface eth6 inet dhcp + +allow-hotplug eth7 +iface eth7 inet dhcp + +allow-hotplug eth8 +iface eth8 inet dhcp \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/arm64/chroot/pip.conf b/bmp-agent/imagebuild-docker/arm64/chroot/pip.conf new file mode 100755 index 0000000..7781d7d --- /dev/null +++ b/bmp-agent/imagebuild-docker/arm64/chroot/pip.conf @@ -0,0 +1,5 @@ +[global] +index-url = http://mirrors.aliyun.com/pypi/simple/ + +[install] +trusted-host=mirrors.aliyun.com \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/arm64/chroot/python-install.sh b/bmp-agent/imagebuild-docker/arm64/chroot/python-install.sh new file mode 100644 index 0000000..843d438 --- /dev/null +++ b/bmp-agent/imagebuild-docker/arm64/chroot/python-install.sh @@ -0,0 +1,9 @@ +yum install -y make zlib zlib-devel +cp -f /usr/lib/rpm/openEuler/config.guess /tmp/Python-2.7.18/config.guess +cp -f /usr/lib/rpm/openEuler/config.sub /tmp/Python-2.7.18/config.sub +cd /tmp/Python-2.7.18 +./configure --prefix=/usr/local/python-2.7.18 && make -j 8 && make install +ln -s /usr/local/python-2.7.18/bin/python /usr/bin/python +echo /usr/local/python-2.7.18/lib > /etc/ld.so.conf.d/py2.conf +ldconfig +python -m ensurepip \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/arm64/chroot/sources.20.04.list b/bmp-agent/imagebuild-docker/arm64/chroot/sources.20.04.list new file mode 100755 index 0000000..b1ec40f --- /dev/null +++ b/bmp-agent/imagebuild-docker/arm64/chroot/sources.20.04.list @@ -0,0 +1,5 @@ +deb http://mirrors.aliyun.com/ubuntu-ports/ focal main multiverse restricted universe +deb http://mirrors.aliyun.com/ubuntu-ports/ focal-backports main multiverse restricted universe +deb http://mirrors.aliyun.com/ubuntu-ports/ focal-proposed main multiverse restricted universe +deb http://mirrors.aliyun.com/ubuntu-ports/ focal-security main multiverse restricted universe +deb http://mirrors.aliyun.com/ubuntu-ports/ focal-updates main multiverse restricted universe \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/arm64/chroot/sources.22.04.list b/bmp-agent/imagebuild-docker/arm64/chroot/sources.22.04.list new file mode 100755 index 0000000..c3d1426 --- /dev/null +++ b/bmp-agent/imagebuild-docker/arm64/chroot/sources.22.04.list @@ -0,0 +1,5 @@ +deb http://mirrors.aliyun.com/ubuntu-ports/ jammy main multiverse restricted universe +deb http://mirrors.aliyun.com/ubuntu-ports/ jammy-backports main multiverse restricted universe +deb http://mirrors.aliyun.com/ubuntu-ports/ jammy-proposed main multiverse restricted universe +deb http://mirrors.aliyun.com/ubuntu-ports/ jammy-security main multiverse restricted universe +deb http://mirrors.aliyun.com/ubuntu-ports/ jammy-updates main multiverse restricted universe \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/arm64/chroot/sshd_config b/bmp-agent/imagebuild-docker/arm64/chroot/sshd_config new file mode 100755 index 0000000..fa6377d --- /dev/null +++ b/bmp-agent/imagebuild-docker/arm64/chroot/sshd_config @@ -0,0 +1,88 @@ +# Package generated configuration file +# See the sshd_config(5) manpage for details + +# What ports, IPs and protocols we listen for +Port 22 +# Use these options to restrict which interfaces/protocols sshd will bind to +#ListenAddress :: +#ListenAddress 0.0.0.0 +Protocol 2 +# HostKeys for protocol version 2 +HostKey /etc/ssh/ssh_host_rsa_key +HostKey /etc/ssh/ssh_host_dsa_key +HostKey /etc/ssh/ssh_host_ecdsa_key +HostKey /etc/ssh/ssh_host_ed25519_key +#Privilege Separation is turned on for security +UsePrivilegeSeparation yes + +# Lifetime and size of ephemeral version 1 server key +KeyRegenerationInterval 3600 +ServerKeyBits 1024 + +# Logging +SyslogFacility AUTH +LogLevel INFO + +# Authentication: +LoginGraceTime 120 +PermitRootLogin yes +StrictModes yes + +RSAAuthentication yes +PubkeyAuthentication yes +#AuthorizedKeysFile %h/.ssh/authorized_keys + +# Don't read the user's ~/.rhosts and ~/.shosts files +IgnoreRhosts yes +# For this to work you will also need host keys in /etc/ssh_known_hosts +RhostsRSAAuthentication no +# similar for protocol version 2 +HostbasedAuthentication no +# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication +#IgnoreUserKnownHosts yes + +# To enable empty passwords, change to yes (NOT RECOMMENDED) +PermitEmptyPasswords no + +# Change to yes to enable challenge-response passwords (beware issues with +# some PAM modules and threads) +ChallengeResponseAuthentication no + +# Change to no to disable tunnelled clear text passwords +#PasswordAuthentication yes + +# Kerberos options +#KerberosAuthentication no +#KerberosGetAFSToken no +#KerberosOrLocalPasswd yes +#KerberosTicketCleanup yes + +# GSSAPI options +#GSSAPIAuthentication no +#GSSAPICleanupCredentials yes + +X11Forwarding yes +X11DisplayOffset 10 +PrintMotd no +PrintLastLog yes +TCPKeepAlive yes +#UseLogin no + +#MaxStartups 10:30:60 +#Banner /etc/issue.net + +# Allow client to pass locale environment variables +AcceptEnv LANG LC_* + +Subsystem sftp /usr/lib/openssh/sftp-server + +# Set this to 'yes' to enable PAM authentication, account processing, +# and session processing. If this is enabled, PAM authentication will +# be allowed through the ChallengeResponseAuthentication and +# PasswordAuthentication. Depending on your PAM configuration, +# PAM authentication via ChallengeResponseAuthentication may bypass +# the setting of "PermitRootLogin without-password". +# If you just want the PAM account and session checks to run without +# PAM authentication, then enable this but set PasswordAuthentication +# and ChallengeResponseAuthentication to 'no'. +UsePAM yes diff --git a/bmp-agent/imagebuild-docker/arm64/initramfs/busybox b/bmp-agent/imagebuild-docker/arm64/initramfs/busybox new file mode 100755 index 0000000..ef80734 Binary files /dev/null and b/bmp-agent/imagebuild-docker/arm64/initramfs/busybox differ diff --git a/bmp-agent/imagebuild-docker/arm64/initramfs/init b/bmp-agent/imagebuild-docker/arm64/initramfs/init new file mode 100755 index 0000000..bf97ac7 --- /dev/null +++ b/bmp-agent/imagebuild-docker/arm64/initramfs/init @@ -0,0 +1,40 @@ +#!/bin/busybox sh + +# Dump to sh if something fails +error() { + echo "Jumping into the shell..." + setsid cttyhack sh +} + +# Populate /bin with binaries from busybox +/bin/busybox --install /bin + +mkdir -p /proc +mount -t proc proc /proc + +mkdir -p /sys +mount -t sysfs sysfs /sys + +mkdir -p /sys/dev +mkdir -p /var/run +mkdir -p /dev + +mkdir -p /dev/pts +mount -t devpts devpts /dev/pts + +# Populate /dev +echo /bin/mdev > /proc/sys/kernel/hotplug +mdev -s + +mkdir -p /newroot +mount -t tmpfs -o size=80% tmpfs /newroot || error + +echo "mount rootfs... " +# mount filesystem.squashfs /newroot -t squashfs -o loop +xz -d -c -f rootfs.tar.xz | tar -x -f - -C /newroot || error + +mount --move /sys /newroot/sys +mount --move /proc /newroot/proc +mount --move /dev /newroot/dev + +exec switch_root /newroot /sbin/init || error \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/arm64/packages/nvme-cli-1.8.1-1-omv4050.aarch64.rpm b/bmp-agent/imagebuild-docker/arm64/packages/nvme-cli-1.8.1-1-omv4050.aarch64.rpm new file mode 100644 index 0000000..88a7aaa Binary files /dev/null and b/bmp-agent/imagebuild-docker/arm64/packages/nvme-cli-1.8.1-1-omv4050.aarch64.rpm differ diff --git a/bmp-agent/imagebuild-docker/arm64/packages/sas3ircu b/bmp-agent/imagebuild-docker/arm64/packages/sas3ircu new file mode 100755 index 0000000..e2d0a51 Binary files /dev/null and b/bmp-agent/imagebuild-docker/arm64/packages/sas3ircu differ diff --git a/bmp-agent/imagebuild-docker/arm64/packages/storcli64 b/bmp-agent/imagebuild-docker/arm64/packages/storcli64 new file mode 100755 index 0000000..dfaf678 Binary files /dev/null and b/bmp-agent/imagebuild-docker/arm64/packages/storcli64 differ diff --git a/bmp-agent/imagebuild-docker/build.sh b/bmp-agent/imagebuild-docker/build.sh new file mode 100755 index 0000000..d0231b5 --- /dev/null +++ b/bmp-agent/imagebuild-docker/build.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +USAGE="Usage: $0 + +Build vmlinuz and initramfs.gz + +Options: + -a Architecture + -d distro Operating system distro and version + -h Display this help and exit + -v Turn on verbose messages for debugging +" + +BUILD_SCRIPT_FILE=$0 +BUILD_SCRIPT_ABSOLUTE_PATH=$(cd "$(dirname "$BUILD_SCRIPT_FILE")"; pwd) +BASE_DIR=$BUILD_SCRIPT_ABSOLUTE_PATH +VERBOSE_OPT='' +VERSION=$(cat "$BUILD_SCRIPT_ABSOLUTE_PATH/../bmpa/version" | tr -d '\n[:space:]') + + +while getopts "a:b:d:i:hv" OPTION; do + case $OPTION in + a) ARCH=$OPTARG ;; + b) BASE_DIR=$OPTARG ;; + d) DISTRO=$OPTARG ;; + i) IMAGE=$OPTARG ;; + h) echo "$USAGE" && exit 0 ;; + v) set -x && export VERBOSE=1 && VERBOSE_OPT='-v';; + *) echo "$USAGE" && exit 1 ;; + esac +done + +set -e + +DEST_BUILD_DIR=$BASE_DIR/build/$DISTRO +DOCKERFILE_PATH=$BASE_DIR/$DISTRO/Dockerfile +rm -rf $DEST_BUILD_DIR +mkdir -p $DEST_BUILD_DIR + +$BASE_DIR/docker-build.sh $VERBOSE_OPT -t $IMAGE -f $DOCKERFILE_PATH -p ../ + +SAVE2_IMAGE_PLUGIN=$BASE_DIR/save2image_plugin.sh +if [[ -f "$BASE_DIR/$DISTRO/save2image_plugin.sh" ]];then + SAVE2_IMAGE_PLUGIN=$BASE_DIR/$DISTRO/save2image_plugin.sh +fi + +docker save $IMAGE | $BASE_DIR/save2image.sh $VERBOSE_OPT -p $SAVE2_IMAGE_PLUGIN -o ${DEST_BUILD_DIR}/image.tar.gz.tmp +mv "${DEST_BUILD_DIR}/image.tar.gz.tmp" "${DEST_BUILD_DIR}/image.tar.gz" +trap "rm -rf ${DEST_BUILD_DIR}/image.tar.gz" EXIT +$BASE_DIR/archive.sh $VERBOSE_OPT -i $DEST_BUILD_DIR/image.tar.gz -p $BASE_DIR -o $DEST_BUILD_DIR -a $ARCH -V $VERSION -d $DISTRO + +echo "Build image success" diff --git a/bmp-agent/imagebuild-docker/centos_7_9/Dockerfile b/bmp-agent/imagebuild-docker/centos_7_9/Dockerfile new file mode 100644 index 0000000..d3bef59 --- /dev/null +++ b/bmp-agent/imagebuild-docker/centos_7_9/Dockerfile @@ -0,0 +1,119 @@ +FROM centos:7.9.2009 +ENV ARCH=x86_64 +ENV BASE_DIR=imagebuild-docker/$ARCH +RUN yum install -y dhcp \ +&& yum install -y rsyslog \ +&& yum install -y python3 \ +&& yum install -y python3-devel \ +&& yum install -y libyaml-devel \ +&& yum install -y biosdevname \ +&& yum install -y lshw \ +&& yum install -y hdparm \ +&& yum install -y ipmitool \ +&& yum install -y qemu-kvm libvirt libvirt-python libguestfs-tools virt-install \ +&& yum install -y dmidecode \ +&& yum install -y gdisk \ +&& yum install -y smartmontools \ +&& yum install -y vim \ +&& yum install -y sysfsutils \ +&& yum install -y epel-release dkms \ +&& yum install -y net-tools \ +&& yum install -y curl \ +&& yum install -y ntpdate \ +&& yum install -y sg3_utils \ +&& yum install -y kexec-tools \ +&& yum install -y python3-pip \ +&& yum install -y ntfs-3g \ +&& yum install -y sysstat \ +&& yum install -y tcpdump \ +&& yum install -y telnet \ +&& yum install -y parted \ +&& yum install -y psmisc \ +&& yum install -y efibootmgr \ +&& yum install -y dosfstools \ +&& yum install -y xfsprogs \ +&& yum install -y make \ +&& yum install -y gcc +# base config +RUN mkdir -p /root/.pip +COPY $BASE_DIR/chroot/pip.conf /root/.pip/ +# fstab +COPY $BASE_DIR/chroot/fstab $CHROOT_DIR/etc/fstab + +RUN echo "root:beijing" | chpasswd \ +&& echo "SELINUX=disabled" > /etc/selinux/config \ +&& mkdir -p /etc/systemd/getty/root@.service.d \ +&& echo "[Service]" >> /etc/systemd/getty/root@.service.d/noclear.conf \ +&& echo "TTYVTDisallocate=no" >> /etc/systemd/getty/root@.service.d/noclear.conf +# network +RUN for i in $(seq 0 8); \ +do \ +echo DEVICE=eth${i} >> /etc/sysconfig/network-scripts/ifcfg-eth${i}; \ +echo "BOOTPROTO=dhcp" >> /etc/sysconfig/network-scripts/ifcfg-eth${i}; \ +echo "ONBOOT=yes" >> /etc/sysconfig/network-scripts/ifcfg-eth${i}; \ +done \ +# if has not this file, interface will up failed +&& touch network /etc/sysconfig/network + +# nvme-cli +COPY $BASE_DIR/packages/nvme-cli-1.8.1-3.el7.x86_64.rpm /tmp/ +RUN rpm -i /tmp/nvme-cli-1.8.1-3.el7.x86_64.rpm + +# storcli +COPY $BASE_DIR/packages/storcli-007.1613.0000.0000-1.noarch.rpm /tmp/ +RUN rpm -i /tmp/storcli-007.1613.0000.0000-1.noarch.rpm \ +&& ln -s /opt/MegaRAID/storcli/storcli64 /usr/sbin/storcli64 +# megacli +COPY $BASE_DIR/packages/Lib_Utils2-1.00-10.noarch.rpm /tmp/ +RUN rpm -i /tmp/Lib_Utils2-1.00-10.noarch.rpm +COPY $BASE_DIR/packages/MegaCli-8.07.14-1.noarch.rpm /tmp/ +RUN rpm -i /tmp/MegaCli-8.07.14-1.noarch.rpm \ +&& ln -s /opt/MegaRAID/MegaCli/MegaCli64 /usr/sbin/MegaCli64 +# perccli +COPY $BASE_DIR/packages/perccli-007.1623.0000.0000-1.noarch.rpm /tmp/ +RUN rpm -i /tmp/perccli-007.1623.0000.0000-1.noarch.rpm \ +&& ln -s /opt/MegaRAID/perccli/perccli64 /usr/sbin/perccli64 +# sas2ircu +COPY $BASE_DIR/packages/sas2ircu /usr/sbin +RUN chmod +x /usr/sbin/sas2ircu +# sas3ircu +COPY $BASE_DIR/packages/sas3ircu /usr/sbin +RUN chmod +x /usr/sbin/sas3ircu + +# arcconf +COPY $BASE_DIR/packages/arcconf /usr/sbin +RUN chmod +x /usr/sbin/arcconf + +COPY $BASE_DIR/chroot/sshd_config $CHROOT_DIR/etc/ssh/ +# bmp-agent service +COPY $BASE_DIR/chroot/bmpa.service /lib/systemd/system/ +COPY requirements.txt /tmp/bmp-agent/ +RUN pip3 install -r /tmp/bmp-agent/requirements.txt +COPY bmpa /tmp/bmp-agent/bmpa +COPY MANIFEST.in /tmp/bmp-agent/ +COPY setup.py /tmp/bmp-agent/ +RUN cd /tmp/bmp-agent && python3 setup.py install \ +&& systemctl enable bmpa.service \ +# openssh-server +&& yum install -y openssh-server \ +&& mkdir -p /root/.ssh \ +&& chmod 700 /root/.ssh \ +&& touch /root/.ssh/authorized_keys \ +&& chmod 600 /root/.ssh/authorized_keys +COPY $BASE_DIR/chroot/id_rsa.pub /tmp/ +RUN cat /tmp/id_rsa.pub /root/.ssh/authorized_keys \ +# dns +&& echo UseDNS no >> /etc/ssh/sshd_config \ +# clean base system +&& systemctl disable smartd \ +&& systemctl disable systemd-tmpfiles-setup \ +&& yum remove -y python3-devel \ +&& yum remove -y libyaml-devel \ +&& yum clean all \ +&& rm -rf /var/cache/* \ +&& rm -rf /var/lib/apt/lists/* \ +&& rm -rf /var/log/* \ +&& rm -rf /usr/share/doc/* \ +&& rm -rf /usr/share/man/* \ +&& rm -rf /usr/share/locale/* \ +&& rm -rf /tmp/* \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/centos_7_9_arm64/Dockerfile b/bmp-agent/imagebuild-docker/centos_7_9_arm64/Dockerfile new file mode 100644 index 0000000..ee0b560 --- /dev/null +++ b/bmp-agent/imagebuild-docker/centos_7_9_arm64/Dockerfile @@ -0,0 +1,107 @@ +FROM scratch +ENV bmp_oss_url https://bmp.s3-internal.cn-north-1.jdcloud-oss.com +ENV bmp_oss_liveos_prefix LiveOS +ENV image_name centos7-aarch64-2009-rootfs.tar.gz + +ADD ${bmp_oss_url}/${bmp_oss_liveos_prefix}/${image_name} / +RUN rm -rf /centos7-aarch64-2009-rootfs.tar.gz +ENV ARCH=arm64 +ENV BASE_DIR=imagebuild-docker/$ARCH +RUN yum install -y dhcp \ +&& yum install -y rsyslog \ +&& yum install -y python3 \ +&& yum install -y python3-devel \ +&& yum install -y libyaml-devel \ +&& yum install -y lshw \ +&& yum install -y hdparm \ +&& yum install -y ipmitool \ +&& yum install -y qemu-kvm libvirt libvirt-python libguestfs-tools virt-install \ +&& yum install -y dmidecode \ +&& yum install -y gdisk \ +&& yum install -y smartmontools \ +&& yum install -y vim \ +&& yum install -y sysfsutils \ +&& yum install -y epel-release dkms \ +&& yum install -y net-tools \ +&& yum install -y curl \ +&& yum install -y ntpdate \ +&& yum install -y sg3_utils \ +&& yum install -y kexec-tools \ +&& yum install -y python3-pip \ +&& yum install -y ntfs-3g \ +&& yum install -y sysstat \ +&& yum install -y tcpdump \ +&& yum install -y telnet \ +&& yum install -y parted \ +&& yum install -y psmisc \ +&& yum install -y efibootmgr \ +&& yum install -y dosfstools \ +&& yum install -y xfsprogs \ +&& yum install -y make \ +&& yum install -y gcc +# base config +RUN mkdir -p /root/.pip +COPY $BASE_DIR/chroot/pip.conf /root/.pip/ +# fstab +COPY $BASE_DIR/chroot/fstab $CHROOT_DIR/etc/fstab +RUN echo "root:beijing" | chpasswd \ +&& echo "SELINUX=disabled" > /etc/selinux/config \ +&& mkdir -p /etc/systemd/getty/root@.service.d \ +&& echo "[Service]" >> /etc/systemd/getty/root@.service.d/noclear.conf \ +&& echo "TTYVTDisallocate=no" >> /etc/systemd/getty/root@.service.d/noclear.conf +# network +RUN for i in $(seq 0 8); \ +do \ +echo DEVICE=eth${i} >> /etc/sysconfig/network-scripts/ifcfg-eth${i}; \ +echo "BOOTPROTO=dhcp" >> /etc/sysconfig/network-scripts/ifcfg-eth${i}; \ +echo "ONBOOT=yes" >> /etc/sysconfig/network-scripts/ifcfg-eth${i}; \ +done \ +# if has not this file, interface will up failed +&& touch network /etc/sysconfig/network +# nvme-cli +RUN yum install -y nvme-cli +# storcli +COPY $BASE_DIR/packages/storcli64 /usr/sbin +RUN chmod +x /usr/sbin/storcli64 +# sas3ircu +COPY $BASE_DIR/packages/sas3ircu /usr/sbin +RUN chmod +x /usr/sbin/sas3ircu +COPY $BASE_DIR/chroot/sshd_config $CHROOT_DIR/etc/ssh/ +# openssh-server +RUN curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-altarch-7.repo +RUN rpm --rebuilddb && yum install -y openssh-server \ +&& mkdir -p /root/.ssh \ +&& chmod 700 /root/.ssh \ +&& touch /root/.ssh/authorized_keys \ +&& chmod 600 /root/.ssh/authorized_keys +COPY $BASE_DIR/chroot/id_rsa.pub /tmp/ +RUN cat /tmp/id_rsa.pub /root/.ssh/authorized_keys +# bmp-agent service +COPY $BASE_DIR/chroot/bmpa.service /lib/systemd/system/ +COPY requirements.txt /tmp/bmp-agent/ +RUN pip3 install -r /tmp/bmp-agent/requirements.txt +COPY bmpa /tmp/bmp-agent/bmpa +COPY MANIFEST.in /tmp/bmp-agent/ +COPY setup.py /tmp/bmp-agent/ +RUN cd /tmp/bmp-agent && python3 setup.py install \ +&& systemctl enable bmpa.service \ +# dns +&& echo UseDNS no >> /etc/ssh/sshd_config \ +# disable cloud-init +&& systemctl disable cloud-init-local.service \ +&& systemctl disable cloud-init.service \ +&& systemctl disable cloud-config.service \ +&& systemctl disable cloud-final.service \ +# clean base system +&& systemctl disable smartd \ +&& systemctl disable systemd-tmpfiles-setup \ +&& yum remove -y python3-devel \ +&& yum remove -y libyaml-devel \ +&& yum clean all \ +&& rm -rf /var/cache/* \ +&& rm -rf /var/lib/apt/lists/* \ +&& rm -rf /var/log/* \ +&& rm -rf /usr/share/doc/* \ +&& rm -rf /usr/share/man/* \ +&& rm -rf /usr/share/locale/* \ +&& rm -rf /tmp/* diff --git a/bmp-agent/imagebuild-docker/deploy.sh b/bmp-agent/imagebuild-docker/deploy.sh new file mode 100644 index 0000000..7fd91a9 --- /dev/null +++ b/bmp-agent/imagebuild-docker/deploy.sh @@ -0,0 +1,26 @@ +#!/bin/bash + +arch=$(uname -m) +DISTRO=${1:-centos_7_9} +SOURCE_DIR=./build/${DISTRO} +bmp_kernel="bmp_kernel_name_x86" +bmp_initramfs="bmp_initramfs_name_x86" +if [ "$arch" == "x86_64" ]; then + : +elif [ "$arch" == "aarch64" ]; then + SOURCE_DIR="${SOURCE_DIR}_arm64" + bmp_kernel="bmp_kernel_name_arm64" + bmp_initramfs="bmp_initramfs_name_arm64" +else + echo "error" + exit +fi +# file to 72 +scp ${SOURCE_DIR}/* 10.208.12.72:/home/bmp/bmp-deploy/data/ +scp ${SOURCE_DIR}/* 10.226.193.42:/home/bmp/bmp-deploy/data/ + +# config name +vmlinuz_name=$(find "${SOURCE_DIR}/" -type f -name "*-vmlinuz" -exec basename {} \;) +initramfs_name=$(find "${SOURCE_DIR}/" -type f -name "*-initramfs.gz" -exec basename {} \;) +echo "${bmp_kernel}=${vmlinuz_name}" +echo "${bmp_initramfs}=${initramfs_name}" \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/docker-build.sh b/bmp-agent/imagebuild-docker/docker-build.sh new file mode 100755 index 0000000..6f0685b --- /dev/null +++ b/bmp-agent/imagebuild-docker/docker-build.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +USAGE="Usage: $0 -t image_tag -f dockerfile_path -p build_content_path + +Build docker image + +Options: + -p Build Content path + -t tag list Name and optionally a tag in the 'name:tag' format + -f file path Name of the Dockerfile + -h Display this help and exit + -v Turn on verbose messages for debugging +" +while getopts "p:t:f:hv" OPTION; do + case $OPTION in + p) BUILD_CONTENT_PATH=$OPTARG ;; + t) IMAGE=$OPTARG ;; + f) DOCKERFILE_PATH=$OPTARG ;; + h) echo "$USAGE" && exit 0 ;; + v) set -x && export VERBOSE=1 ;; + *) echo "$USAGE" && exit 1 ;; + esac +done + +set -e + +docker build -t $IMAGE -f $DOCKERFILE_PATH $BUILD_CONTENT_PATH \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/loongarch64/chroot/bmpa.service b/bmp-agent/imagebuild-docker/loongarch64/chroot/bmpa.service new file mode 100644 index 0000000..28bab52 --- /dev/null +++ b/bmp-agent/imagebuild-docker/loongarch64/chroot/bmpa.service @@ -0,0 +1,12 @@ +[Unit] +Description=BMP Agent +After=network-online.target +Wants=network-online.target + +[Service] +Environment="PYTHON_EGG_CACHE=/tmp/.cache" +ExecStart=/usr/local/bin/bmp-agent + +[Install] +WantedBy=multi-user.target +Alias=bmpa.service \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/loongarch64/chroot/fstab b/bmp-agent/imagebuild-docker/loongarch64/chroot/fstab new file mode 100755 index 0000000..33fb180 --- /dev/null +++ b/bmp-agent/imagebuild-docker/loongarch64/chroot/fstab @@ -0,0 +1,18 @@ +# /etc/fstab: static file system information. +# +# noatime turns off atimes for increased performance (atimes normally aren't +# needed); notail increases performance of ReiserFS (at the expense of storage +# efficiency). It's safe to drop the noatime options if you want and to +# switch between notail / tail freely. +# +# The root filesystem should have a pass number of either 0 or 1. +# All other filesystems should have a pass number of 0 or greater than 1. +# +# See the manpage fstab(5) for more information. +# + +# + +# NOTE: If your BOOT partition is ReiserFS, add the notail option to opts. +tmpfs /tmp tmpfs rw,size=30% 0 0 +tmpfs /var/log tmpfs rw,size=5% 0 0 \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/loongarch64/chroot/id_rsa.pub b/bmp-agent/imagebuild-docker/loongarch64/chroot/id_rsa.pub new file mode 100755 index 0000000..9a6d4f9 --- /dev/null +++ b/bmp-agent/imagebuild-docker/loongarch64/chroot/id_rsa.pub @@ -0,0 +1 @@ +ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDQtb/De7i3VlPv/efEal5jQXkB9C7rJgjUWhIziUgEcKTtsTZaQMwLY0dJ/OFsLd2BdxQ/d6htPkPNKiseB239i0wkM78fp0MGdAcwcqh998MHQOslO5ckHNC4iM+Z3gQR+gPjwvUKGlXH8KPfOsS78dLTUNWL93Wx56cJLYu6NBysmfLKNgdEFCm8vVAJK9sdxzkHQ49j3fZeL8o5jHu1L0kHk3c/nAMzFqKQh9w0LIQ1So2SlvsWq/N08hKxXc6AEO5rGKOD8tLG+sAdG8BUqY5LVavMRM0wnkuTzYp7GGTxj7Wzrlmm9YNzCI+w9hlIEWVXuEpJ0jY9800Dfyh7 root@A02-R12-I168-156-6ZDHZX1.JD.LOCAL \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/loongarch64/chroot/openeuler-22.03.repo b/bmp-agent/imagebuild-docker/loongarch64/chroot/openeuler-22.03.repo new file mode 100644 index 0000000..5ba9255 --- /dev/null +++ b/bmp-agent/imagebuild-docker/loongarch64/chroot/openeuler-22.03.repo @@ -0,0 +1,6 @@ +[loongarch64] +name=loongarch64 +baseurl=http://119.3.219.20:82/openEuler:/22.03:/LTS:/LoongArch/standard_loongarch64/ +enabled=1 +gpgcheck=0 +#gpgkey=http://119.3.219.20:82/openEuler:/22.03:/LTS:/LoongArch/standard_loongarch64/repodata/ \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/loongarch64/chroot/sshd_config b/bmp-agent/imagebuild-docker/loongarch64/chroot/sshd_config new file mode 100755 index 0000000..fa6377d --- /dev/null +++ b/bmp-agent/imagebuild-docker/loongarch64/chroot/sshd_config @@ -0,0 +1,88 @@ +# Package generated configuration file +# See the sshd_config(5) manpage for details + +# What ports, IPs and protocols we listen for +Port 22 +# Use these options to restrict which interfaces/protocols sshd will bind to +#ListenAddress :: +#ListenAddress 0.0.0.0 +Protocol 2 +# HostKeys for protocol version 2 +HostKey /etc/ssh/ssh_host_rsa_key +HostKey /etc/ssh/ssh_host_dsa_key +HostKey /etc/ssh/ssh_host_ecdsa_key +HostKey /etc/ssh/ssh_host_ed25519_key +#Privilege Separation is turned on for security +UsePrivilegeSeparation yes + +# Lifetime and size of ephemeral version 1 server key +KeyRegenerationInterval 3600 +ServerKeyBits 1024 + +# Logging +SyslogFacility AUTH +LogLevel INFO + +# Authentication: +LoginGraceTime 120 +PermitRootLogin yes +StrictModes yes + +RSAAuthentication yes +PubkeyAuthentication yes +#AuthorizedKeysFile %h/.ssh/authorized_keys + +# Don't read the user's ~/.rhosts and ~/.shosts files +IgnoreRhosts yes +# For this to work you will also need host keys in /etc/ssh_known_hosts +RhostsRSAAuthentication no +# similar for protocol version 2 +HostbasedAuthentication no +# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication +#IgnoreUserKnownHosts yes + +# To enable empty passwords, change to yes (NOT RECOMMENDED) +PermitEmptyPasswords no + +# Change to yes to enable challenge-response passwords (beware issues with +# some PAM modules and threads) +ChallengeResponseAuthentication no + +# Change to no to disable tunnelled clear text passwords +#PasswordAuthentication yes + +# Kerberos options +#KerberosAuthentication no +#KerberosGetAFSToken no +#KerberosOrLocalPasswd yes +#KerberosTicketCleanup yes + +# GSSAPI options +#GSSAPIAuthentication no +#GSSAPICleanupCredentials yes + +X11Forwarding yes +X11DisplayOffset 10 +PrintMotd no +PrintLastLog yes +TCPKeepAlive yes +#UseLogin no + +#MaxStartups 10:30:60 +#Banner /etc/issue.net + +# Allow client to pass locale environment variables +AcceptEnv LANG LC_* + +Subsystem sftp /usr/lib/openssh/sftp-server + +# Set this to 'yes' to enable PAM authentication, account processing, +# and session processing. If this is enabled, PAM authentication will +# be allowed through the ChallengeResponseAuthentication and +# PasswordAuthentication. Depending on your PAM configuration, +# PAM authentication via ChallengeResponseAuthentication may bypass +# the setting of "PermitRootLogin without-password". +# If you just want the PAM account and session checks to run without +# PAM authentication, then enable this but set PasswordAuthentication +# and ChallengeResponseAuthentication to 'no'. +UsePAM yes diff --git a/bmp-agent/imagebuild-docker/loongarch64/initramfs/busybox b/bmp-agent/imagebuild-docker/loongarch64/initramfs/busybox new file mode 100644 index 0000000..0966545 Binary files /dev/null and b/bmp-agent/imagebuild-docker/loongarch64/initramfs/busybox differ diff --git a/bmp-agent/imagebuild-docker/loongarch64/initramfs/init b/bmp-agent/imagebuild-docker/loongarch64/initramfs/init new file mode 100755 index 0000000..bf97ac7 --- /dev/null +++ b/bmp-agent/imagebuild-docker/loongarch64/initramfs/init @@ -0,0 +1,40 @@ +#!/bin/busybox sh + +# Dump to sh if something fails +error() { + echo "Jumping into the shell..." + setsid cttyhack sh +} + +# Populate /bin with binaries from busybox +/bin/busybox --install /bin + +mkdir -p /proc +mount -t proc proc /proc + +mkdir -p /sys +mount -t sysfs sysfs /sys + +mkdir -p /sys/dev +mkdir -p /var/run +mkdir -p /dev + +mkdir -p /dev/pts +mount -t devpts devpts /dev/pts + +# Populate /dev +echo /bin/mdev > /proc/sys/kernel/hotplug +mdev -s + +mkdir -p /newroot +mount -t tmpfs -o size=80% tmpfs /newroot || error + +echo "mount rootfs... " +# mount filesystem.squashfs /newroot -t squashfs -o loop +xz -d -c -f rootfs.tar.xz | tar -x -f - -C /newroot || error + +mount --move /sys /newroot/sys +mount --move /proc /newroot/proc +mount --move /dev /newroot/dev + +exec switch_root /newroot /sbin/init || error \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/MegaRAID/storcli/storcli b/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/MegaRAID/storcli/storcli new file mode 100755 index 0000000..0988d52 Binary files /dev/null and b/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/MegaRAID/storcli/storcli differ diff --git a/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/MegaRAID/storcli/storcli64 b/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/MegaRAID/storcli/storcli64 new file mode 100755 index 0000000..cf47c18 Binary files /dev/null and b/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/MegaRAID/storcli/storcli64 differ diff --git a/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/README b/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/README new file mode 100644 index 0000000..606130c --- /dev/null +++ b/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/README @@ -0,0 +1,17 @@ +Loongson storcli installation + +The list of the packet: + + MegaRAID/ qemu-x86_64 installer uninstaller storcli64_ls README + + +installation: + Execution the "installer", it can automaticlly install. + ./installer + +remove: + Execution the "uninstaller", it can automaticlly remove. + ./uninstaller + + qemu: version is v5.2.0-1-g0aca0361ea-dirty + storcli64: StorCli SAS Customization Utility Ver 1.23.02 Mar 28, 2017 diff --git a/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/installer b/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/installer new file mode 100755 index 0000000..318f9b0 --- /dev/null +++ b/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/installer @@ -0,0 +1,5 @@ +#!/bin/bash + +cp MegaRAID/ /opt/ -af +cp qemu-x86_64 /usr/bin/ +cp storcli64_ls /usr/bin/ diff --git a/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/qemu-x86_64 b/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/qemu-x86_64 new file mode 100755 index 0000000..0283cf8 Binary files /dev/null and b/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/qemu-x86_64 differ diff --git a/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/storcli64_ls b/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/storcli64_ls new file mode 100755 index 0000000..f1e5c90 --- /dev/null +++ b/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/storcli64_ls @@ -0,0 +1,6 @@ +#!/bin/bash + +#export LD_LIBRARY_PATH=/usr/local/lib/libx64/ + +#qemu-x86_64 /opt/MegaRAID/MegaCli/MegaCli64 $@ +qemu-x86_64 /opt/MegaRAID/storcli/storcli64 $@ diff --git a/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/uninstaller b/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/uninstaller new file mode 100755 index 0000000..0013e67 --- /dev/null +++ b/bmp-agent/imagebuild-docker/loongarch64/packages/raid-static-conf-loongarch-storcli-v0.6/uninstaller @@ -0,0 +1,10 @@ +#!/bin/bash + +rm /opt/MegaRAID/ -rf +#rm /opt/lsi/ -rf + +#rm /usr/local/lib/libx64/ -rf +#rm /lib64/ld-linux-x86-64.so.2 -rf + +rm /usr/bin/qemu-x86_64 -rf +rm /usr/bin/storcli64_ls -rf diff --git a/bmp-agent/imagebuild-docker/loongarch64_8_4/Dockerfile b/bmp-agent/imagebuild-docker/loongarch64_8_4/Dockerfile new file mode 100644 index 0000000..f477ea4 --- /dev/null +++ b/bmp-agent/imagebuild-docker/loongarch64_8_4/Dockerfile @@ -0,0 +1,99 @@ +FROM scratch +ENV bmp_oss_url https://bmp.s3-internal.cn-north-1.jdcloud-oss.com +ENV bmp_oss_liveos_prefix LiveOS +ENV image_name v1.7.0-loongnix-8.4-2023053018.tar.xz + +ADD ${bmp_oss_url}/${bmp_oss_liveos_prefix}/${image_name} / +RUN rm -rf /v1.7.0-loongnix-8.4-2023053018.tar.xz +ENV ARCH=loongarch64 +ENV BASE_DIR=imagebuild-docker/$ARCH +RUN yum install -y rsyslog \ +&& yum install -y python3 \ +&& yum install -y python3-devel \ +&& yum install -y libyaml-devel \ +&& yum install -y lshw \ +&& yum install -y hdparm \ +&& yum install -y ipmitool \ +&& yum install -y dmidecode \ +&& yum install -y gdisk \ +&& yum install -y smartmontools \ +&& yum install -y vim \ +&& yum install -y sysfsutils \ +&& yum install -y net-tools \ +&& yum install -y curl \ +&& yum install -y sg3_utils \ +&& yum install -y kexec-tools \ +&& yum install -y python3-pip \ +&& yum install -y sysstat \ +&& yum install -y tcpdump \ +&& yum install -y telnet \ +&& yum install -y parted \ +&& yum install -y psmisc \ +&& yum install -y efibootmgr \ +&& yum install -y dosfstools \ +&& yum install -y xfsprogs \ +&& yum install -y make \ +&& yum install -y gcc \ +&& yum install -y tar +# base config +# fstab +COPY $BASE_DIR/chroot/fstab /etc/fstab + +RUN echo "root:beijing" | chpasswd \ +&& echo "SELINUX=disabled" > /etc/selinux/config \ +&& mkdir -p /etc/systemd/getty/root@.service.d \ +&& echo "[Service]" >> /etc/systemd/getty/root@.service.d/noclear.conf \ +&& echo "TTYVTDisallocate=no" >> /etc/systemd/getty/root@.service.d/noclear.conf +# network +RUN for i in $(seq 0 8); \ +do \ +echo DEVICE=eth${i} >> /etc/sysconfig/network-scripts/ifcfg-eth${i}; \ +echo "BOOTPROTO=dhcp" >> /etc/sysconfig/network-scripts/ifcfg-eth${i}; \ +echo "ONBOOT=yes" >> /etc/sysconfig/network-scripts/ifcfg-eth${i}; \ +done \ +# If has not this file, interface will up failed +&& touch network /etc/sysconfig/network + +RUN yum install -y nvme-cli + +# storcli +COPY $BASE_DIR/packages/raid-static-conf-loongarch-storcli-v0.6 /tmp/raid-static-conf-loongarch-storcli-v0.6 +RUN cd /tmp/raid-static-conf-loongarch-storcli-v0.6 && ./installer \ +&& ln -s /usr/bin/storcli64_ls /usr/sbin/storcli64 + + +COPY $BASE_DIR/chroot/sshd_config /etc/ssh/ +# bmp-agent service +COPY $BASE_DIR/chroot/bmpa.service /lib/systemd/system/ +COPY bmpa /tmp/bmp-agent/bmpa +COPY MANIFEST.in /tmp/bmp-agent/ +COPY requirements.txt /tmp/bmp-agent/ +COPY setup.py /tmp/bmp-agent/ +RUN pip3 install -r /tmp/bmp-agent/requirements.txt \ +&& cd /tmp/bmp-agent && python3 setup.py install \ +&& systemctl enable bmpa.service \ + +# openssh-server +&& yum install -y openssh-server \ +&& mkdir -p /root/.ssh \ +&& chmod 700 /root/.ssh \ +&& touch /root/.ssh/authorized_keys \ +&& chmod 600 /root/.ssh/authorized_keys +COPY $BASE_DIR/chroot/id_rsa.pub /tmp/ +RUN cat /tmp/id_rsa.pub /root/.ssh/authorized_keys \ +# dns +&& echo UseDNS no >> /etc/ssh/sshd_config \ + +# clean base system +&& systemctl disable smartd \ +&& systemctl disable systemd-tmpfiles-setup \ +&& yum remove -y python3-devel \ +&& yum remove -y libyaml-devel \ +&& yum clean all \ +&& rm -rf /var/cache/* \ +&& rm -rf /var/lib/apt/lists/* \ +&& rm -rf /var/log/* \ +&& rm -rf /usr/share/doc/* \ +&& rm -rf /usr/share/man/* \ +&& rm -rf /usr/share/locale/* \ +&& rm -rf /tmp/* diff --git a/bmp-agent/imagebuild-docker/save2image.sh b/bmp-agent/imagebuild-docker/save2image.sh new file mode 100755 index 0000000..f40dbb0 --- /dev/null +++ b/bmp-agent/imagebuild-docker/save2image.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +USAGE="Usage: $0 < multi_layer_tar > tar + +Extracts a multi-layer 'docker save' TAR archive from stdin, +finds the largest archives and then consolidates them within a single +.tar.xz rootfs archive on stdout. + +Options: + -p Plugin file + -h Display this help and exit + -v Turn on verbose messages for debugging +" +while getopts "o:p:hv" OPTION; do + case $OPTION in + p) PLUGIN_FILE=$OPTARG ;; + h) echo "$USAGE" && exit 0 ;; + o) OUTPUT_FILE=$OPTARG ;; + v) set -x && export VERBOSE=1 && VERBOSE_OPT='-v' ;; + *) echo "$USAGE" && exit 1 ;; + esac +done + +say() { + echo "$@" >&2 +} + +msg() { :; } + +set -e + +# Check for deps +for DEP in tar jq mktemp; do + if ! type $DEP &>/dev/null; then + say "Error: $DEP not found. Please install it first." + exit 1 + fi +done + +TEMP=$(mktemp -d -t cps-image-XXXXXXX) +# shellcheck disable=SC2064 +trap "rm -rf $TEMP" EXIT +msg "Temp directory is: $TEMP" + +PACKDIR=$TEMP/consolidated +mkdir "$PACKDIR" + +cd "$TEMP" +msg "Extracting image" +tar --warning=no-timestamp -xf- +for LAYER in $(jq -r '.[0].Layers[]' manifest.json); do + msg "Extracting layer $LAYER" + tar --warning=no-timestamp -xf "$LAYER" -C "$PACKDIR" + find "$PACKDIR" -name .wh.\* | while read -r PATH; do + msg $PATH + /bin/rm -rf "$PATH" "${PATH/.wh./}" + done +done + +cd "$PACKDIR" +msg "Creating consolidated image archive..." + +if [[ -f "$PLUGIN_FILE" ]];then + $PLUGIN_FILE -p $PACKDIR $VERBOSE_OPT +fi + +if time tar -cf - . | xz -v --threads=24 > $OUTPUT_FILE; then + msg "Flattened image archive created successfully" +else + say "ERROR: Image archive creation failed" +fi diff --git a/bmp-agent/imagebuild-docker/save2image_plugin.sh b/bmp-agent/imagebuild-docker/save2image_plugin.sh new file mode 100755 index 0000000..f257395 --- /dev/null +++ b/bmp-agent/imagebuild-docker/save2image_plugin.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash + +USAGE="Usage: $0 packdir + +Before image archive to add operation + +Options: + -p Plugin file + -h Display this help and exit + -v Turn on verbose messages for debugging +" +while getopts "p:hv" OPTION; do + case $OPTION in + p) PACKDIR=$OPTARG ;; + h) echo "$USAGE" && exit 0 ;; + v) set -x && export VERBOSE=1 ;; + *) echo "$USAGE" && exit 1 ;; + esac +done + +set -e + +# Check packdir is / or empty, avoid operate host directory +PACKDIR=`echo $PACKDIR | sed 's/ //g'` +if [[ -f "$PACKDIR" || "$PACKDIR" =~ ^/+$ ]];then + echo "packdir can not use / or empty" + exit 1 +fi + +# Dockerfile can not set image hostname persistent +echo "bmp_agent" > $PACKDIR/etc/hostname \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/ubuntu_2004_arm64/Dockerfile b/bmp-agent/imagebuild-docker/ubuntu_2004_arm64/Dockerfile new file mode 100644 index 0000000..8e617aa --- /dev/null +++ b/bmp-agent/imagebuild-docker/ubuntu_2004_arm64/Dockerfile @@ -0,0 +1,117 @@ +FROM ubuntu:20.04 +ENV ARCH=arm64 +ENV BASE_DIR=imagebuild-docker/$ARCH +ENV DEBIAN_FRONTEND=noninteractive +COPY $BASE_DIR/chroot/sources.20.04.list /etc/apt/sources.list +RUN apt-get update \ +&& apt-get install -y rsyslog \ +&& apt-get install -y python3 \ +&& apt-get install -y python3-dev \ +&& apt-get install -y libyaml-dev \ +&& apt-get install -y --assume-yes apt-utils \ +&& apt-get install -y initramfs-tools \ +&& apt-get install -y lshw \ +&& apt-get install -y hdparm \ +&& apt-get install -y ipmitool \ +&& apt-get install -y qemu-utils \ +&& apt-get install -y dmidecode \ +&& apt-get install -y gdisk \ +&& DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" smartmontools \ +&& apt-get install -y vim \ +&& apt-get install -y sysfsutils \ +&& apt-get install -y dkms \ +&& apt-get install -y net-tools \ +&& apt-get install -y ifupdown \ +&& apt-get install -y curl \ +&& apt-get install -y ntpdate \ +&& apt-get install -y sg3-utils \ +&& DEBIAN_FRONTEND=noninteractive apt-get install -y kexec-tools \ +&& apt-get install -y python3-pip \ +&& apt-get install -y ntfs-3g \ +&& apt-get install -y sysstat \ +&& apt-get install -y tcpdump \ +&& apt-get install -y telnet \ +&& apt-get install -y parted \ +&& apt-get install -y psmisc \ +&& apt-get install -y efibootmgr \ +&& apt-get install -y dosfstools \ +&& apt-get install -y xfsprogs \ +&& apt-get install -y nvme-cli +# base config +RUN mkdir -p /root/.pip +COPY $BASE_DIR/chroot/pip.conf /root/.pip/ +# fstab +COPY $BASE_DIR/chroot/fstab $CHROOT_DIR/etc/fstab +RUN echo "root:beijing" | chpasswd \ +&& echo "SELINUX=disabled" > /etc/selinux/config \ +&& mkdir -p /etc/systemd/getty/root@.service.d \ +&& echo "[Service]" >> /etc/systemd/getty/root@.service.d/noclear.conf \ +&& echo "TTYVTDisallocate=no" >> /etc/systemd/getty/root@.service.d/noclear.conf +# network +# network +RUN rm -rvf /etc/netplan/* +COPY $BASE_DIR/chroot/interfaces /etc/network/ + +# storcli64 +COPY $BASE_DIR/packages/storcli64 $CHROOT_DIR/usr/sbin +RUN chmod +x /usr/sbin/storcli64 + +# sas3ircu +COPY $BASE_DIR/packages/sas3ircu $CHROOT_DIR/usr/sbin +RUN chmod +x /usr/sbin/sas3ircu + +COPY $BASE_DIR/chroot/sshd_config $CHROOT_DIR/etc/ssh/ +# openssh-server +RUN apt-get install -y openssh-server \ +&& mkdir -p /root/.ssh \ +&& chmod 700 /root/.ssh \ +&& touch /root/.ssh/authorized_keys \ +&& chmod 600 /root/.ssh/authorized_keys +COPY $BASE_DIR/chroot/id_rsa.pub /tmp/ +RUN cat /tmp/id_rsa.pub /root/.ssh/authorized_keys \ +# dns +&& echo UseDNS no >> /etc/ssh/sshd_config \ +# kernel +&& apt-get install -y linux-image-generic \ +&& apt-get remove -y linux-image-generic + +# bmp-agent service +COPY $BASE_DIR/chroot/bmpa.service /lib/systemd/system/ +COPY requirements.txt /tmp/bmp-agent/ +RUN pip3 install -r /tmp/bmp-agent/requirements.txt +COPY bmpa /tmp/bmp-agent/bmpa +COPY MANIFEST.in /tmp/bmp-agent/ +COPY requirements.txt /tmp/bmp-agent/ +COPY setup.py /tmp/bmp-agent/ +RUN pip3 install -r /tmp/bmp-agent/requirements.txt \ +&& cd /tmp/bmp-agent && python3 setup.py install \ +&& systemctl enable bmpa.service \ +# clean base system +&& systemctl disable smartd \ +&& systemctl disable systemd-tmpfiles-setup \ +&& apt-get remove -y python3-dev \ +&& apt-get remove -y libyaml-dev \ +&& apt-get clean -y \ +&& rm -rf /var/cache/* \ +&& rm -rf /var/lib/apt/lists/* \ +&& rm -rf /var/log/* \ +&& rm -rf /usr/share/doc/* \ +&& rm -rf /usr/share/man/* \ +&& rm -rf /usr/share/locale/* \ +&& rm -rf /tmp/* \ +&& rm -rf /usr/lib/firmware/iwlwifi-* \ +&& rm -rf /usr/lib/modules/*/kernel/drivers/media \ +&& rm -rf /usr/lib/modules/*/kernel/drivers/usb \ +&& rm -rf /usr/lib/modules/*/kernel/drivers/video \ +&& rm -rf /usr/lib/modules/*/kernel/drivers/net/wireless \ +&& rm -rf /usr/lib/modules/*/kernel/drivers/net/usb \ +&& rm -rf /usr/lib/firmware/netronome/nic-sriov \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/sound \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/zfs \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/wireless \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/mac80211 \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/bluetooth \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/sunrpc \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/openvswitch \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/ceph \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/drivers/infiniband \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/ubuntu_2204/Dockerfile b/bmp-agent/imagebuild-docker/ubuntu_2204/Dockerfile new file mode 100644 index 0000000..a75aa26 --- /dev/null +++ b/bmp-agent/imagebuild-docker/ubuntu_2204/Dockerfile @@ -0,0 +1,138 @@ +FROM ubuntu:22.04 +ENV ARCH=x86_64 +ENV BASE_DIR=imagebuild-docker/$ARCH +COPY $BASE_DIR/chroot/sources.22.04.list /etc/apt/sources.list +RUN apt-get update \ +&& apt-get install -y rsyslog \ +&& apt-get install -y python3 \ +&& apt-get install -y python3-dev \ +&& apt-get install -y libyaml-dev \ +&& apt-get install -y --assume-yes apt-utils \ +&& apt-get install -y initramfs-tools \ +&& apt-get install -y lshw \ +&& apt-get install -y hdparm \ +&& apt-get install -y ipmitool \ +&& apt-get install -y qemu-utils \ +&& apt-get install -y dmidecode \ +&& apt-get install -y gdisk \ +&& DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" smartmontools \ +&& apt-get install -y vim \ +&& apt-get install -y sysfsutils \ +&& apt-get install -y dkms \ +&& apt-get install -y net-tools \ +&& apt-get install -y ifupdown \ +&& apt-get install -y curl \ +&& apt-get install -y ntpdate \ +&& apt-get install -y sg3-utils \ +&& DEBIAN_FRONTEND=noninteractive apt-get install -y kexec-tools \ +&& apt-get install -y python3-pip \ +&& apt-get install -y ntfs-3g \ +&& apt-get install -y sysstat \ +&& apt-get install -y tcpdump \ +&& apt-get install -y telnet \ +&& apt-get install -y parted \ +&& apt-get install -y psmisc \ +&& apt-get install -y efibootmgr \ +&& apt-get install -y dosfstools \ +&& apt-get install -y xfsprogs \ +&& apt-get install -y nvme-cli +# base config +RUN mkdir -p /root/.pip +COPY $BASE_DIR/chroot/pip.conf /root/.pip/ +# fstab +COPY $BASE_DIR/chroot/fstab $CHROOT_DIR/etc/fstab +RUN echo "root:beijing" | chpasswd \ +&& echo "SELINUX=disabled" > /etc/selinux/config \ +&& mkdir -p /etc/systemd/getty/root@.service.d \ +&& echo "[Service]" >> /etc/systemd/getty/root@.service.d/noclear.conf \ +&& echo "TTYVTDisallocate=no" >> /etc/systemd/getty/root@.service.d/noclear.conf +# network +# network +RUN rm -rvf /etc/netplan/* +COPY $BASE_DIR/chroot/interfaces /etc/network/ +# storcli +COPY $BASE_DIR/packages/storcli_1.18.11_all.deb /tmp/ +RUN dpkg -i /tmp/storcli_1.18.11_all.deb \ +&& ln -s /opt/MegaRAID/storcli/storcli64 /usr/sbin/storcli64 +# hpssacli +COPY $BASE_DIR/packages/hpssacli_2.30-7_amd64.deb /tmp/ +RUN dpkg -i /tmp/hpssacli_2.30-7_amd64.deb +# megacli +COPY $BASE_DIR/packages/lib-utils_1.00-10_all.deb /tmp/ +RUN dpkg -i /tmp/lib-utils_1.00-10_all.deb +COPY $BASE_DIR/packages/megacli_8.07.10-2_all.deb /tmp/ +RUN dpkg -i /tmp/megacli_8.07.10-2_all.deb \ +&& ln -s /opt/MegaRAID/MegaCli/MegaCli64 /usr/sbin/MegaCli64 +# perccli +COPY $BASE_DIR/packages/perccli_007.1020.0000.0000-2_all.deb /tmp/ +RUN dpkg -i /tmp/perccli_007.1020.0000.0000-2_all.deb \ +&& ln -s /opt/MegaRAID/perccli/perccli64 /usr/sbin/perccli64 +# sas2ircu +COPY $BASE_DIR/packages/sas2ircu /usr/sbin +RUN chmod +x /usr/sbin/sas2ircu +# sas3ircu +COPY $BASE_DIR/packages/sas3ircu /usr/sbin +RUN chmod +x /usr/sbin/sas3ircu +# arcconf +COPY $BASE_DIR/packages/arcconf /usr/sbin +RUN chmod +x /usr/sbin/arcconf +# racadm +COPY $BASE_DIR/packages/srvadmin-idracadm7_9.4.0-3733.15734_amd64.deb /tmp/ +RUN dpkg -i /tmp/srvadmin-idracadm7_9.4.0-3733.15734_amd64.deb \ +&& apt-get install -y libargtable2-0 \ +&& ln -s /opt/dell/srvadmin/bin/idracadm7 /usr/sbin/racadm +COPY $BASE_DIR/chroot/sshd_config $CHROOT_DIR/etc/ssh/ +# openssh-server +RUN apt-get install -y openssh-server \ +&& mkdir -p /root/.ssh \ +&& chmod 700 /root/.ssh \ +&& touch /root/.ssh/authorized_keys \ +&& chmod 600 /root/.ssh/authorized_keys +COPY $BASE_DIR/chroot/id_rsa.pub /tmp/ +RUN cat /tmp/id_rsa.pub /root/.ssh/authorized_keys \ +# dns +&& echo UseDNS no >> /etc/ssh/sshd_config \ +# kernel +&& apt-get install -y linux-image-generic \ +&& apt-get remove -y linux-image-generic + +# bmp-agent service +COPY $BASE_DIR/chroot/bmpa.service /lib/systemd/system/ +COPY requirements.txt /tmp/bmp-agent/ +RUN pip3 install -r /tmp/bmp-agent/requirements.txt +COPY bmpa /tmp/bmp-agent/bmpa +COPY MANIFEST.in /tmp/bmp-agent/ +COPY requirements.txt /tmp/bmp-agent/ +COPY setup.py /tmp/bmp-agent/ +RUN pip3 install -r /tmp/bmp-agent/requirements.txt \ +&& cd /tmp/bmp-agent && python3 setup.py install \ +&& systemctl enable bmpa.service \ +# clean base system +&& systemctl disable smartd \ +&& systemctl disable systemd-tmpfiles-setup \ +&& apt-get remove -y python3-dev \ +&& apt-get remove -y libyaml-dev \ +&& apt-get clean -y \ +&& rm -rf /var/cache/* \ +&& rm -rf /var/lib/apt/lists/* \ +&& rm -rf /var/log/* \ +&& rm -rf /usr/share/doc/* \ +&& rm -rf /usr/share/man/* \ +&& rm -rf /usr/share/locale/* \ +&& rm -rf /tmp/* \ +&& rm -rf /usr/lib/firmware/iwlwifi-* \ +&& rm -rf /usr/lib/modules/*/kernel/drivers/media \ +&& rm -rf /usr/lib/modules/*/kernel/drivers/usb \ +&& rm -rf /usr/lib/modules/*/kernel/drivers/video \ +&& rm -rf /usr/lib/modules/*/kernel/drivers/net/wireless \ +&& rm -rf /usr/lib/modules/*/kernel/drivers/net/usb \ +&& rm -rf /usr/lib/firmware/netronome/nic-sriov \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/sound \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/zfs \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/wireless \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/mac80211 \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/bluetooth \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/sunrpc \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/openvswitch \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/ceph \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/drivers/infiniband \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/ubuntu_2204_arm64/Dockerfile b/bmp-agent/imagebuild-docker/ubuntu_2204_arm64/Dockerfile new file mode 100644 index 0000000..944e085 --- /dev/null +++ b/bmp-agent/imagebuild-docker/ubuntu_2204_arm64/Dockerfile @@ -0,0 +1,116 @@ +FROM ubuntu:22.04 +ENV ARCH=arm64 +ENV BASE_DIR=imagebuild-docker/$ARCH +COPY $BASE_DIR/chroot/sources.22.04.list /etc/apt/sources.list +RUN apt-get update \ +&& apt-get install -y rsyslog \ +&& apt-get install -y python3 \ +&& apt-get install -y python3-dev \ +&& apt-get install -y libyaml-dev \ +&& apt-get install -y --assume-yes apt-utils \ +&& apt-get install -y initramfs-tools \ +&& apt-get install -y lshw \ +&& apt-get install -y hdparm \ +&& apt-get install -y ipmitool \ +&& apt-get install -y qemu-utils \ +&& apt-get install -y dmidecode \ +&& apt-get install -y gdisk \ +&& DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" smartmontools \ +&& apt-get install -y vim \ +&& apt-get install -y sysfsutils \ +&& apt-get install -y dkms \ +&& apt-get install -y net-tools \ +&& apt-get install -y ifupdown \ +&& apt-get install -y curl \ +&& apt-get install -y ntpdate \ +&& apt-get install -y sg3-utils \ +&& DEBIAN_FRONTEND=noninteractive apt-get install -y kexec-tools \ +&& apt-get install -y python3-pip \ +&& apt-get install -y ntfs-3g \ +&& apt-get install -y sysstat \ +&& apt-get install -y tcpdump \ +&& apt-get install -y telnet \ +&& apt-get install -y parted \ +&& apt-get install -y psmisc \ +&& apt-get install -y efibootmgr \ +&& apt-get install -y dosfstools \ +&& apt-get install -y xfsprogs \ +&& apt-get install -y nvme-cli +# base config +RUN mkdir -p /root/.pip +COPY $BASE_DIR/chroot/pip.conf /root/.pip/ +# fstab +COPY $BASE_DIR/chroot/fstab $CHROOT_DIR/etc/fstab +RUN echo "root:beijing" | chpasswd \ +&& echo "SELINUX=disabled" > /etc/selinux/config \ +&& mkdir -p /etc/systemd/getty/root@.service.d \ +&& echo "[Service]" >> /etc/systemd/getty/root@.service.d/noclear.conf \ +&& echo "TTYVTDisallocate=no" >> /etc/systemd/getty/root@.service.d/noclear.conf +# network +# network +RUN rm -rvf /etc/netplan/* +COPY $BASE_DIR/chroot/interfaces /etc/network/ + +# storcli64 +COPY $BASE_DIR/packages/storcli64 $CHROOT_DIR/usr/sbin +RUN chmod +x /usr/sbin/storcli64 + +# sas3ircu +COPY $BASE_DIR/packages/sas3ircu $CHROOT_DIR/usr/sbin +RUN chmod +x /usr/sbin/sas3ircu + +COPY $BASE_DIR/chroot/sshd_config $CHROOT_DIR/etc/ssh/ +# openssh-server +RUN apt-get install -y openssh-server \ +&& mkdir -p /root/.ssh \ +&& chmod 700 /root/.ssh \ +&& touch /root/.ssh/authorized_keys \ +&& chmod 600 /root/.ssh/authorized_keys +COPY $BASE_DIR/chroot/id_rsa.pub /tmp/ +RUN cat /tmp/id_rsa.pub /root/.ssh/authorized_keys \ +# dns +&& echo UseDNS no >> /etc/ssh/sshd_config \ +# kernel +&& apt-get install -y linux-image-generic \ +&& apt-get remove -y linux-image-generic + +# bmp-agent service +COPY $BASE_DIR/chroot/bmpa.service /lib/systemd/system/ +COPY requirements.txt /tmp/bmp-agent/ +RUN pip3 install -r /tmp/bmp-agent/requirements.txt +COPY bmpa /tmp/bmp-agent/bmpa +COPY MANIFEST.in /tmp/bmp-agent/ +COPY requirements.txt /tmp/bmp-agent/ +COPY setup.py /tmp/bmp-agent/ +RUN pip3 install -r /tmp/bmp-agent/requirements.txt \ +&& cd /tmp/bmp-agent && python3 setup.py install \ +&& systemctl enable bmpa.service \ +# clean base system +&& systemctl disable smartd \ +&& systemctl disable systemd-tmpfiles-setup \ +&& apt-get remove -y python3-dev \ +&& apt-get remove -y libyaml-dev \ +&& apt-get clean -y \ +&& rm -rf /var/cache/* \ +&& rm -rf /var/lib/apt/lists/* \ +&& rm -rf /var/log/* \ +&& rm -rf /usr/share/doc/* \ +&& rm -rf /usr/share/man/* \ +&& rm -rf /usr/share/locale/* \ +&& rm -rf /tmp/* \ +&& rm -rf /usr/lib/firmware/iwlwifi-* \ +&& rm -rf /usr/lib/modules/*/kernel/drivers/media \ +&& rm -rf /usr/lib/modules/*/kernel/drivers/usb \ +&& rm -rf /usr/lib/modules/*/kernel/drivers/video \ +&& rm -rf /usr/lib/modules/*/kernel/drivers/net/wireless \ +&& rm -rf /usr/lib/modules/*/kernel/drivers/net/usb \ +&& rm -rf /usr/lib/firmware/netronome/nic-sriov \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/sound \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/zfs \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/wireless \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/mac80211 \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/bluetooth \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/sunrpc \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/openvswitch \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/net/ceph \ +&& rm -rf /usr/lib/modules/5.15.0-112-generic/kernel/drivers/infiniband \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/x86_64/chroot/bmpa.service b/bmp-agent/imagebuild-docker/x86_64/chroot/bmpa.service new file mode 100644 index 0000000..b44d62e --- /dev/null +++ b/bmp-agent/imagebuild-docker/x86_64/chroot/bmpa.service @@ -0,0 +1,11 @@ +[Unit] +Description=BMP Agent +After=network.target + +[Service] +Environment="PYTHON_EGG_CACHE=/tmp/.cache" +ExecStart=/usr/local/bin/bmp-agent + +[Install] +WantedBy=multi-user.target +Alias=bmpa.service \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/x86_64/chroot/fstab b/bmp-agent/imagebuild-docker/x86_64/chroot/fstab new file mode 100755 index 0000000..33fb180 --- /dev/null +++ b/bmp-agent/imagebuild-docker/x86_64/chroot/fstab @@ -0,0 +1,18 @@ +# /etc/fstab: static file system information. +# +# noatime turns off atimes for increased performance (atimes normally aren't +# needed); notail increases performance of ReiserFS (at the expense of storage +# efficiency). It's safe to drop the noatime options if you want and to +# switch between notail / tail freely. +# +# The root filesystem should have a pass number of either 0 or 1. +# All other filesystems should have a pass number of 0 or greater than 1. +# +# See the manpage fstab(5) for more information. +# + +# + +# NOTE: If your BOOT partition is ReiserFS, add the notail option to opts. +tmpfs /tmp tmpfs rw,size=30% 0 0 +tmpfs /var/log tmpfs rw,size=5% 0 0 \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/x86_64/chroot/id_rsa.pub b/bmp-agent/imagebuild-docker/x86_64/chroot/id_rsa.pub new file mode 100755 index 0000000..9a6d4f9 --- /dev/null +++ b/bmp-agent/imagebuild-docker/x86_64/chroot/id_rsa.pub @@ -0,0 +1 @@ +ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDQtb/De7i3VlPv/efEal5jQXkB9C7rJgjUWhIziUgEcKTtsTZaQMwLY0dJ/OFsLd2BdxQ/d6htPkPNKiseB239i0wkM78fp0MGdAcwcqh998MHQOslO5ckHNC4iM+Z3gQR+gPjwvUKGlXH8KPfOsS78dLTUNWL93Wx56cJLYu6NBysmfLKNgdEFCm8vVAJK9sdxzkHQ49j3fZeL8o5jHu1L0kHk3c/nAMzFqKQh9w0LIQ1So2SlvsWq/N08hKxXc6AEO5rGKOD8tLG+sAdG8BUqY5LVavMRM0wnkuTzYp7GGTxj7Wzrlmm9YNzCI+w9hlIEWVXuEpJ0jY9800Dfyh7 root@A02-R12-I168-156-6ZDHZX1.JD.LOCAL \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/x86_64/chroot/interfaces b/bmp-agent/imagebuild-docker/x86_64/chroot/interfaces new file mode 100755 index 0000000..a9ccdf0 --- /dev/null +++ b/bmp-agent/imagebuild-docker/x86_64/chroot/interfaces @@ -0,0 +1,33 @@ +# interfaces(5) file used by ifup(8) and ifdown(8) +# Include files from /etc/network/interfaces.d: +source-directory /etc/network/interfaces.d + +auto lo +iface lo inet loopback + +allow-hotplug eth0 +iface eth0 inet dhcp + +allow-hotplug eth1 +iface eth1 inet dhcp + +allow-hotplug eth2 +iface eth2 inet dhcp + +allow-hotplug eth3 +iface eth3 inet dhcp + +allow-hotplug eth4 +iface eth4 inet dhcp + +allow-hotplug eth5 +iface eth5 inet dhcp + +allow-hotplug eth6 +iface eth6 inet dhcp + +allow-hotplug eth7 +iface eth7 inet dhcp + +allow-hotplug eth8 +iface eth8 inet dhcp \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/x86_64/chroot/pip.conf b/bmp-agent/imagebuild-docker/x86_64/chroot/pip.conf new file mode 100755 index 0000000..7781d7d --- /dev/null +++ b/bmp-agent/imagebuild-docker/x86_64/chroot/pip.conf @@ -0,0 +1,5 @@ +[global] +index-url = http://mirrors.aliyun.com/pypi/simple/ + +[install] +trusted-host=mirrors.aliyun.com \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/x86_64/chroot/sources.22.04.list b/bmp-agent/imagebuild-docker/x86_64/chroot/sources.22.04.list new file mode 100755 index 0000000..20be342 --- /dev/null +++ b/bmp-agent/imagebuild-docker/x86_64/chroot/sources.22.04.list @@ -0,0 +1,5 @@ +deb http://mirrors.aliyun.com/ubuntu/ jammy main multiverse restricted universe +deb http://mirrors.aliyun.com/ubuntu/ jammy-backports main multiverse restricted universe +deb http://mirrors.aliyun.com/ubuntu/ jammy-proposed main multiverse restricted universe +deb http://mirrors.aliyun.com/ubuntu/ jammy-security main multiverse restricted universe +deb http://mirrors.aliyun.com/ubuntu/ jammy-updates main multiverse restricted universe \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/x86_64/chroot/sshd_config b/bmp-agent/imagebuild-docker/x86_64/chroot/sshd_config new file mode 100755 index 0000000..fa6377d --- /dev/null +++ b/bmp-agent/imagebuild-docker/x86_64/chroot/sshd_config @@ -0,0 +1,88 @@ +# Package generated configuration file +# See the sshd_config(5) manpage for details + +# What ports, IPs and protocols we listen for +Port 22 +# Use these options to restrict which interfaces/protocols sshd will bind to +#ListenAddress :: +#ListenAddress 0.0.0.0 +Protocol 2 +# HostKeys for protocol version 2 +HostKey /etc/ssh/ssh_host_rsa_key +HostKey /etc/ssh/ssh_host_dsa_key +HostKey /etc/ssh/ssh_host_ecdsa_key +HostKey /etc/ssh/ssh_host_ed25519_key +#Privilege Separation is turned on for security +UsePrivilegeSeparation yes + +# Lifetime and size of ephemeral version 1 server key +KeyRegenerationInterval 3600 +ServerKeyBits 1024 + +# Logging +SyslogFacility AUTH +LogLevel INFO + +# Authentication: +LoginGraceTime 120 +PermitRootLogin yes +StrictModes yes + +RSAAuthentication yes +PubkeyAuthentication yes +#AuthorizedKeysFile %h/.ssh/authorized_keys + +# Don't read the user's ~/.rhosts and ~/.shosts files +IgnoreRhosts yes +# For this to work you will also need host keys in /etc/ssh_known_hosts +RhostsRSAAuthentication no +# similar for protocol version 2 +HostbasedAuthentication no +# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication +#IgnoreUserKnownHosts yes + +# To enable empty passwords, change to yes (NOT RECOMMENDED) +PermitEmptyPasswords no + +# Change to yes to enable challenge-response passwords (beware issues with +# some PAM modules and threads) +ChallengeResponseAuthentication no + +# Change to no to disable tunnelled clear text passwords +#PasswordAuthentication yes + +# Kerberos options +#KerberosAuthentication no +#KerberosGetAFSToken no +#KerberosOrLocalPasswd yes +#KerberosTicketCleanup yes + +# GSSAPI options +#GSSAPIAuthentication no +#GSSAPICleanupCredentials yes + +X11Forwarding yes +X11DisplayOffset 10 +PrintMotd no +PrintLastLog yes +TCPKeepAlive yes +#UseLogin no + +#MaxStartups 10:30:60 +#Banner /etc/issue.net + +# Allow client to pass locale environment variables +AcceptEnv LANG LC_* + +Subsystem sftp /usr/lib/openssh/sftp-server + +# Set this to 'yes' to enable PAM authentication, account processing, +# and session processing. If this is enabled, PAM authentication will +# be allowed through the ChallengeResponseAuthentication and +# PasswordAuthentication. Depending on your PAM configuration, +# PAM authentication via ChallengeResponseAuthentication may bypass +# the setting of "PermitRootLogin without-password". +# If you just want the PAM account and session checks to run without +# PAM authentication, then enable this but set PasswordAuthentication +# and ChallengeResponseAuthentication to 'no'. +UsePAM yes diff --git a/bmp-agent/imagebuild-docker/x86_64/initramfs/busybox b/bmp-agent/imagebuild-docker/x86_64/initramfs/busybox new file mode 100755 index 0000000..18cc4bc Binary files /dev/null and b/bmp-agent/imagebuild-docker/x86_64/initramfs/busybox differ diff --git a/bmp-agent/imagebuild-docker/x86_64/initramfs/init b/bmp-agent/imagebuild-docker/x86_64/initramfs/init new file mode 100755 index 0000000..bf97ac7 --- /dev/null +++ b/bmp-agent/imagebuild-docker/x86_64/initramfs/init @@ -0,0 +1,40 @@ +#!/bin/busybox sh + +# Dump to sh if something fails +error() { + echo "Jumping into the shell..." + setsid cttyhack sh +} + +# Populate /bin with binaries from busybox +/bin/busybox --install /bin + +mkdir -p /proc +mount -t proc proc /proc + +mkdir -p /sys +mount -t sysfs sysfs /sys + +mkdir -p /sys/dev +mkdir -p /var/run +mkdir -p /dev + +mkdir -p /dev/pts +mount -t devpts devpts /dev/pts + +# Populate /dev +echo /bin/mdev > /proc/sys/kernel/hotplug +mdev -s + +mkdir -p /newroot +mount -t tmpfs -o size=80% tmpfs /newroot || error + +echo "mount rootfs... " +# mount filesystem.squashfs /newroot -t squashfs -o loop +xz -d -c -f rootfs.tar.xz | tar -x -f - -C /newroot || error + +mount --move /sys /newroot/sys +mount --move /proc /newroot/proc +mount --move /dev /newroot/dev + +exec switch_root /newroot /sbin/init || error \ No newline at end of file diff --git a/bmp-agent/imagebuild-docker/x86_64/packages/Lib_Utils2-1.00-10.noarch.rpm b/bmp-agent/imagebuild-docker/x86_64/packages/Lib_Utils2-1.00-10.noarch.rpm new file mode 100755 index 0000000..bef2421 Binary files /dev/null and b/bmp-agent/imagebuild-docker/x86_64/packages/Lib_Utils2-1.00-10.noarch.rpm differ diff --git a/bmp-agent/imagebuild-docker/x86_64/packages/MegaCli-8.07.14-1.noarch.rpm b/bmp-agent/imagebuild-docker/x86_64/packages/MegaCli-8.07.14-1.noarch.rpm new file mode 100755 index 0000000..b79499e Binary files /dev/null and b/bmp-agent/imagebuild-docker/x86_64/packages/MegaCli-8.07.14-1.noarch.rpm differ diff --git a/bmp-agent/imagebuild-docker/x86_64/packages/arcconf b/bmp-agent/imagebuild-docker/x86_64/packages/arcconf new file mode 100755 index 0000000..d5a2aae Binary files /dev/null and b/bmp-agent/imagebuild-docker/x86_64/packages/arcconf differ diff --git a/bmp-agent/imagebuild-docker/x86_64/packages/hpssacli_2.30-7_amd64.deb b/bmp-agent/imagebuild-docker/x86_64/packages/hpssacli_2.30-7_amd64.deb new file mode 100755 index 0000000..2720f25 Binary files /dev/null and b/bmp-agent/imagebuild-docker/x86_64/packages/hpssacli_2.30-7_amd64.deb differ diff --git a/bmp-agent/imagebuild-docker/x86_64/packages/lib-utils_1.00-10_all.deb b/bmp-agent/imagebuild-docker/x86_64/packages/lib-utils_1.00-10_all.deb new file mode 100755 index 0000000..52f3a80 Binary files /dev/null and b/bmp-agent/imagebuild-docker/x86_64/packages/lib-utils_1.00-10_all.deb differ diff --git a/bmp-agent/imagebuild-docker/x86_64/packages/megacli_8.07.10-2_all.deb b/bmp-agent/imagebuild-docker/x86_64/packages/megacli_8.07.10-2_all.deb new file mode 100755 index 0000000..6d9a036 Binary files /dev/null and b/bmp-agent/imagebuild-docker/x86_64/packages/megacli_8.07.10-2_all.deb differ diff --git a/bmp-agent/imagebuild-docker/x86_64/packages/nvme-cli-1.8.1-3.el7.x86_64.rpm b/bmp-agent/imagebuild-docker/x86_64/packages/nvme-cli-1.8.1-3.el7.x86_64.rpm new file mode 100755 index 0000000..94c5815 Binary files /dev/null and b/bmp-agent/imagebuild-docker/x86_64/packages/nvme-cli-1.8.1-3.el7.x86_64.rpm differ diff --git a/bmp-agent/imagebuild-docker/x86_64/packages/perccli-007.1623.0000.0000-1.noarch.rpm b/bmp-agent/imagebuild-docker/x86_64/packages/perccli-007.1623.0000.0000-1.noarch.rpm new file mode 100755 index 0000000..c995504 Binary files /dev/null and b/bmp-agent/imagebuild-docker/x86_64/packages/perccli-007.1623.0000.0000-1.noarch.rpm differ diff --git a/bmp-agent/imagebuild-docker/x86_64/packages/perccli_007.1020.0000.0000-2_all.deb b/bmp-agent/imagebuild-docker/x86_64/packages/perccli_007.1020.0000.0000-2_all.deb new file mode 100644 index 0000000..44fcc3f Binary files /dev/null and b/bmp-agent/imagebuild-docker/x86_64/packages/perccli_007.1020.0000.0000-2_all.deb differ diff --git a/bmp-agent/imagebuild-docker/x86_64/packages/sas2ircu b/bmp-agent/imagebuild-docker/x86_64/packages/sas2ircu new file mode 100755 index 0000000..82348b6 Binary files /dev/null and b/bmp-agent/imagebuild-docker/x86_64/packages/sas2ircu differ diff --git a/bmp-agent/imagebuild-docker/x86_64/packages/sas3ircu b/bmp-agent/imagebuild-docker/x86_64/packages/sas3ircu new file mode 100755 index 0000000..8765d44 Binary files /dev/null and b/bmp-agent/imagebuild-docker/x86_64/packages/sas3ircu differ diff --git a/bmp-agent/imagebuild-docker/x86_64/packages/srvadmin-idracadm7_9.4.0-3733.15734_amd64.deb b/bmp-agent/imagebuild-docker/x86_64/packages/srvadmin-idracadm7_9.4.0-3733.15734_amd64.deb new file mode 100644 index 0000000..d244892 Binary files /dev/null and b/bmp-agent/imagebuild-docker/x86_64/packages/srvadmin-idracadm7_9.4.0-3733.15734_amd64.deb differ diff --git a/bmp-agent/imagebuild-docker/x86_64/packages/storcli-007.1613.0000.0000-1.noarch.rpm b/bmp-agent/imagebuild-docker/x86_64/packages/storcli-007.1613.0000.0000-1.noarch.rpm new file mode 100755 index 0000000..e189ef8 Binary files /dev/null and b/bmp-agent/imagebuild-docker/x86_64/packages/storcli-007.1613.0000.0000-1.noarch.rpm differ diff --git a/bmp-agent/imagebuild-docker/x86_64/packages/storcli_1.18.11_all.deb b/bmp-agent/imagebuild-docker/x86_64/packages/storcli_1.18.11_all.deb new file mode 100755 index 0000000..1aa827a Binary files /dev/null and b/bmp-agent/imagebuild-docker/x86_64/packages/storcli_1.18.11_all.deb differ diff --git a/bmp-agent/requirements.txt b/bmp-agent/requirements.txt new file mode 100755 index 0000000..98d54df --- /dev/null +++ b/bmp-agent/requirements.txt @@ -0,0 +1,11 @@ + +netaddr==0.7.19 +netifaces>=0.10.7 +pika>=1.3.1 +pint>=0.8.1 +psutil>=5.4.7 +pyparsing>=3.1.1 +pyudev>=0.21.0 +six>=1.16.0 +tenacity>=8.2.1 +Jinja2>=3.0.1 \ No newline at end of file diff --git a/bmp-agent/setup.py b/bmp-agent/setup.py new file mode 100755 index 0000000..36be960 --- /dev/null +++ b/bmp-agent/setup.py @@ -0,0 +1,49 @@ +import io +import os +import sys + +from setuptools import setup, find_packages + +NAME = "bmpa" +DESCRIPTION = "BMP Agent" +URL = "" +EMAIL = "" +AUTHOR = "JD Cloud Pysical System" +REQUIRES_PYTHON = ">=3.6" +VERSION = None + +here = os.path.abspath(os.path.dirname(__file__)) + + +# What packages are required for this module to be executed +def read_requires(): + with open(os.path.join(here, "requirements.txt")) as f: + return f.read().splitlines() + + +if not VERSION: + with open(os.path.join(here, NAME, "version")) as f: + VERSION = f.readline().strip() + +setup( + name=NAME, + version=VERSION, + description=DESCRIPTION, + author=AUTHOR, + author_email=EMAIL, + platforms="any", + python_requires=REQUIRES_PYTHON, + url=URL, + packages=find_packages( + exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), + entry_points={ + "console_scripts": [ + "bmp-agent = bmpa.cmd.agent:run", + ], + }, + install_requires=read_requires(), + # These files are included via the MANIFEST.in will be + # automatically installed with your package + include_package_data=True, + # license="", + zip_safe=False) diff --git a/bmp-agent/test-requirements.txt b/bmp-agent/test-requirements.txt new file mode 100755 index 0000000..c2a8eaf --- /dev/null +++ b/bmp-agent/test-requirements.txt @@ -0,0 +1,8 @@ +# The order of packages is significant, because pip processes them in the order +# of appearance. Changing the order has an impact on the overall integration +# process, which may cause wedges in the gate later. + +coverage!=4.4,>=4.0 # Apache-2.0 +testtools>=2.2.0 # MIT +stestr>=1.0.0 # Apache-2.0 +mock>=1.2 \ No newline at end of file diff --git a/bmp-agent/tox.ini b/bmp-agent/tox.ini new file mode 100755 index 0000000..64d745d --- /dev/null +++ b/bmp-agent/tox.ini @@ -0,0 +1,74 @@ +[tox] +skipsdist = True +envlist = python3,pep8 +ignore_basepython_conflict=true + +[testenv] +usedevelop = True +setenv = + VIRTUAL_ENV={envdir} + PYTHONDONTWRITEBYTECODE = 1 + OS_TEST_PATH=./bmpa/tests/unit + LANGUAGE=en_US + LC_ALL=en_US.utf-8 +deps = + -r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt +commands = stestr run {posargs} +passenv = http_proxy, HTTP_PROXY, https_proxy, HTTPS_PROXY, no_proxy, NO_PROXY + +[testenv:cover] +setenv = VIRTUAL_ENV={envdir} + PYTHON=coverage run --source bmpa --omit='*tests*' --parallel-mode +commands = + coverage erase + stestr run {posargs} + coverage combine + coverage report --omit='*tests*' + coverage html -d ./cover --omit='*tests*' + +[testenv:venv] +setenv = PYTHONHASHSEED=0 +commands = {posargs:} + +[testenv:pep8] +basepython = python3 +usedevelop = False +deps= + hacking>=4.1.0 # Apache-2.0 + bashate>=0.5.1 # Apache-2.0 + flake8>=3.8.0 + flake8-import-order>=0.17.1 # LGPLv3 + doc8>=0.8.1 # Apache-2.0 +allowlist_externals = bash +commands = flake8 {posargs:bmpa} + # Run bashate during pep8 runs to ensure violations are caught by + # the check and gate queues. + +[flake8] +# [E129] visually indented line with same indent as next logical line. +# [W503] Line break before binary operator. +# [E999] SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers +# [H301] one import per line +# [W605] invalid escape sequence '\g' +# [E501] line too long(> 79 characters) +# [W504] line break after binary operator +# [H237] module thread is removed in Python 3 +# [H216] he unittest.mock module should be used rather than the third party mock package unless actually needed. If so, disable the H216 check in hacking config and ensure mock is declared in the project's requirements. +# [F821] undefined name '_' +# [E121] continuation line under-indented for hanging indent +# [E126] continuation line over-indented for hanging indent +ignore = E129,W503,E999,H301,W605,E501,W504,H237,H216,F821,E121,E126 +exclude = .venv,.git,.tox,dist,*lib/python*,*egg,imagebuild +import-order-style = pep8 +application-import-names = bmpa +# [H106] Don't put vim configuration in source files. +# [H203] Use assertIs(Not)None to check for None. +# [H204] Use assert(Not)Equal to check for equality. +# [H205] Use assert(Greater|Less)(Equal) for comparison. +# [H210] Require 'autospec', 'spec', or 'spec_set' in mock.patch/mock.patch.object calls +# [H904] Delay string interpolations at logging calls. +enable-extensions=H106,H203,H204,H205,H210 + + + diff --git a/bmp-console-api/.cmd b/bmp-console-api/.cmd new file mode 100644 index 0000000..ced32d3 --- /dev/null +++ b/bmp-console-api/.cmd @@ -0,0 +1 @@ +rm -rf vendor diff --git a/bmp-console-api/.gitmodules b/bmp-console-api/.gitmodules new file mode 100644 index 0000000..506f24c --- /dev/null +++ b/bmp-console-api/.gitmodules @@ -0,0 +1,3 @@ +[submodule "bmp-deploy"] + path = bmp-deploy + url = git@coding.jd.com:aidc-bmp/bmp-deploy.git diff --git a/bmp-console-api/Dockerfile b/bmp-console-api/Dockerfile new file mode 100644 index 0000000..b22118a --- /dev/null +++ b/bmp-console-api/Dockerfile @@ -0,0 +1,17 @@ +FROM centos:7.9.2009 + +MAINTAINER minping@jd.com +USER root +RUN groupadd -g 2001 ironic-console +RUN useradd -d /home/ironic-console -u 2001 -g 2001 ironic-console + +WORKDIR /home/ironic-console + +ADD ./ironic-console /home/ironic-console/ +RUN mkdir -p /home/ironic-console/conf +ADD ./conf/* /home/ironic-console/conf/ + +RUN chmod 755 /home/ironic-console/ironic-console +USER ironic-console +EXPOSE 9998 +CMD ./ironic-console \ No newline at end of file diff --git a/bmp-console-api/Makefile b/bmp-console-api/Makefile new file mode 100644 index 0000000..59677f8 --- /dev/null +++ b/bmp-console-api/Makefile @@ -0,0 +1,10 @@ + +BUILD_TIME := $(shell date +%Y%m%d%H%M%S) +VERSION := $(shell git describe --tags --always) +COMMITID := $(shell git rev-parse ${VERSION} | cut -c 1-32) +APP_NAME := ironic-console-jdstack + +#GOARCH=amd64 GOOS=linux +ldflags ="-s -X main.VERSION=${COMMITID} -X main.BUILD_TIME=${BUILD_TIME}" +all: + GOARCH=amd64 GOOS=linux go build -ldflags ${ldflags} -o ${APP_NAME} main.go diff --git a/bmp-console-api/README.md b/bmp-console-api/README.md new file mode 100644 index 0000000..54f5488 --- /dev/null +++ b/bmp-console-api/README.md @@ -0,0 +1,18 @@ +# bmp-console-api + +English | [简体中文](README.zh-CN.md) + + +## Introduce + +The console adaptation layer, Around the life cycle of an instance provides an interface for bmp-console-web and requests bmp-openapi-console to obtain data. + +The location of bmp-console-api in the entire bmp architecture is shown in:[bmp arch](../bmp-scheduler/README.md) + + + +## 2,Core Features + +- Serving the life cycle of instances. +- Provides an interface for bmp-console-web. +- Request bmp-openapi-console to obtain data. \ No newline at end of file diff --git a/bmp-console-api/README.zh-CN.md b/bmp-console-api/README.zh-CN.md new file mode 100644 index 0000000..5533f1f --- /dev/null +++ b/bmp-console-api/README.zh-CN.md @@ -0,0 +1,19 @@ +# bmp-console-api + +[English](README.md) | 简体中文 + + +## 介绍 + +控制台适配层,围绕实例的生命周期,向上为bmp-console-web提供接口,向下请求bmp-openapi-console获取数据。 + +bmp-console-api在整个bmp架构中的位置见:[bmp架构图](../bmp-scheduler/README.zh-CN.md) + + + +## 2,核心功能 + +- 服务于实例的生命周期流转。 +- 向上为bmp-console-web提供接口。 +- 向下请求bmp-openapi-console获取数据。 + diff --git a/bmp-console-api/bmp-console-api.Dockerfile b/bmp-console-api/bmp-console-api.Dockerfile new file mode 100644 index 0000000..0504a21 --- /dev/null +++ b/bmp-console-api/bmp-console-api.Dockerfile @@ -0,0 +1,26 @@ +FROM quay.io/goswagger/swagger AS SDK +ENV GOPROXY https://goproxy.cn +WORKDIR /usr/src/bmp-openapi-console +COPY ./bmp-openapi-console . +RUN swagger generate spec -o ./swagger.yml +RUN swagger validate swagger.yml +RUN mkdir -p ../bmp-openapi-console-sdk +RUN cd ../bmp-openapi-console-sdk && go mod init coding.jd.com/aidc-bmp/bmp-openapi-console-sdk +RUN cd ../bmp-openapi-console +RUN swagger generate client -f swagger.yml --target=../bmp-openapi-console-sdk + +FROM golang:1.17-alpine AS builder +ENV GOPROXY https://goproxy.cn +WORKDIR /usr/src/bmp-console-api +COPY ./bmp-console-api . +COPY --from=SDK /usr/src/bmp-openapi-console-sdk ./bmp_vendor/bmp-openapi-console-sdk +RUN go mod tidy -compat=1.17 +RUN go mod vendor +RUN go build -o /tmp/bmp-console-api . + +FROM alpine:3.16 +WORKDIR /home/bmp/bmp-console-api +COPY --from=builder /tmp/bmp-console-api . +COPY ./bmp-console-api/conf ./conf +CMD ["./bmp-console-api"] + diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/api_key_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/api_key_client.go new file mode 100644 index 0000000..f786155 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/api_key_client.go @@ -0,0 +1,237 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new api key API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for api key API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateUserApikey(params *CreateUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserApikeyOK, error) + + DeleteUserApikey(params *DeleteUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserApikeyOK, error) + + DescribeUserAPIKey(params *DescribeUserAPIKeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserAPIKeyOK, error) + + DescribeUserAPIKeys(params *DescribeUserAPIKeysParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserAPIKeysOK, error) + + ModifyUserApikey(params *ModifyUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserApikeyOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateUserApikey CreateUserApikey 创建apikey +*/ +func (a *Client) CreateUserApikey(params *CreateUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserApikeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateUserApikeyParams() + } + op := &runtime.ClientOperation{ + ID: "createUserApikey", + Method: "POST", + PathPattern: "/user/apikeys", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateUserApikeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateUserApikeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateUserApikeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteUserApikey DeleteUserApikey 删除某个apikey +*/ +func (a *Client) DeleteUserApikey(params *DeleteUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserApikeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteUserApikeyParams() + } + op := &runtime.ClientOperation{ + ID: "deleteUserApikey", + Method: "DELETE", + PathPattern: "/user/apikeys/{apikey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteUserApikeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteUserApikeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteUserApikeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserAPIKey DescribeUserAPIKey 获取apikey详情 +*/ +func (a *Client) DescribeUserAPIKey(params *DescribeUserAPIKeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserAPIKeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserAPIKeyParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserAPIKey", + Method: "GET", + PathPattern: "/user/apikeys/{apikey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserAPIKeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserAPIKeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserAPIKeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserAPIKeys DescribeUserAPIKeys 获取APIKey列表 +*/ +func (a *Client) DescribeUserAPIKeys(params *DescribeUserAPIKeysParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserAPIKeysOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserAPIKeysParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserAPIKeys", + Method: "GET", + PathPattern: "/user/apikeys", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserAPIKeysReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserAPIKeysOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserAPIKeysDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyUserApikey ModifyUserApikey 修改apikey(暂不启用) +*/ +func (a *Client) ModifyUserApikey(params *ModifyUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserApikeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyUserApikeyParams() + } + op := &runtime.ClientOperation{ + ID: "modifyUserApikey", + Method: "PUT", + PathPattern: "/user/apikeys/{apikey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyUserApikeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyUserApikeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyUserApikeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/create_user_apikey_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/create_user_apikey_parameters.go new file mode 100644 index 0000000..a4eb98d --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/create_user_apikey_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewCreateUserApikeyParams creates a new CreateUserApikeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateUserApikeyParams() *CreateUserApikeyParams { + return &CreateUserApikeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateUserApikeyParamsWithTimeout creates a new CreateUserApikeyParams object +// with the ability to set a timeout on a request. +func NewCreateUserApikeyParamsWithTimeout(timeout time.Duration) *CreateUserApikeyParams { + return &CreateUserApikeyParams{ + timeout: timeout, + } +} + +// NewCreateUserApikeyParamsWithContext creates a new CreateUserApikeyParams object +// with the ability to set a context for a request. +func NewCreateUserApikeyParamsWithContext(ctx context.Context) *CreateUserApikeyParams { + return &CreateUserApikeyParams{ + Context: ctx, + } +} + +// NewCreateUserApikeyParamsWithHTTPClient creates a new CreateUserApikeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateUserApikeyParamsWithHTTPClient(client *http.Client) *CreateUserApikeyParams { + return &CreateUserApikeyParams{ + HTTPClient: client, + } +} + +/* CreateUserApikeyParams contains all the parameters to send to the API endpoint + for the create user apikey operation. + + Typically these are written to a http.Request. +*/ +type CreateUserApikeyParams struct { + + // Body. + Body *models.CreateApikeyRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserApikeyParams) WithDefaults() *CreateUserApikeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserApikeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create user apikey params +func (o *CreateUserApikeyParams) WithTimeout(timeout time.Duration) *CreateUserApikeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create user apikey params +func (o *CreateUserApikeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create user apikey params +func (o *CreateUserApikeyParams) WithContext(ctx context.Context) *CreateUserApikeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create user apikey params +func (o *CreateUserApikeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create user apikey params +func (o *CreateUserApikeyParams) WithHTTPClient(client *http.Client) *CreateUserApikeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create user apikey params +func (o *CreateUserApikeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create user apikey params +func (o *CreateUserApikeyParams) WithBody(body *models.CreateApikeyRequest) *CreateUserApikeyParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create user apikey params +func (o *CreateUserApikeyParams) SetBody(body *models.CreateApikeyRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create user apikey params +func (o *CreateUserApikeyParams) WithAuthorization(authorization string) *CreateUserApikeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create user apikey params +func (o *CreateUserApikeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create user apikey params +func (o *CreateUserApikeyParams) WithBmpLanguage(bmpLanguage *string) *CreateUserApikeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create user apikey params +func (o *CreateUserApikeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create user apikey params +func (o *CreateUserApikeyParams) WithBmpUserID(bmpUserID *string) *CreateUserApikeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create user apikey params +func (o *CreateUserApikeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create user apikey params +func (o *CreateUserApikeyParams) WithTraceID(traceID string) *CreateUserApikeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create user apikey params +func (o *CreateUserApikeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateUserApikeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/create_user_apikey_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/create_user_apikey_responses.go new file mode 100644 index 0000000..ee9bbbb --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/create_user_apikey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// CreateUserApikeyReader is a Reader for the CreateUserApikey structure. +type CreateUserApikeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateUserApikeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateUserApikeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateUserApikeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateUserApikeyOK creates a CreateUserApikeyOK with default headers values +func NewCreateUserApikeyOK() *CreateUserApikeyOK { + return &CreateUserApikeyOK{} +} + +/* CreateUserApikeyOK describes a response with status code 200, with default header values. + +A CreateUserApikeyResult is an response struct that is used to describe create apikey result. +*/ +type CreateUserApikeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserApikeyOKBody +} + +// IsSuccess returns true when this create user apikey o k response has a 2xx status code +func (o *CreateUserApikeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create user apikey o k response has a 3xx status code +func (o *CreateUserApikeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create user apikey o k response has a 4xx status code +func (o *CreateUserApikeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create user apikey o k response has a 5xx status code +func (o *CreateUserApikeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create user apikey o k response a status code equal to that given +func (o *CreateUserApikeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateUserApikeyOK) Error() string { + return fmt.Sprintf("[POST /user/apikeys][%d] createUserApikeyOK %+v", 200, o.Payload) +} + +func (o *CreateUserApikeyOK) String() string { + return fmt.Sprintf("[POST /user/apikeys][%d] createUserApikeyOK %+v", 200, o.Payload) +} + +func (o *CreateUserApikeyOK) GetPayload() *CreateUserApikeyOKBody { + return o.Payload +} + +func (o *CreateUserApikeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserApikeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateUserApikeyDefault creates a CreateUserApikeyDefault with default headers values +func NewCreateUserApikeyDefault(code int) *CreateUserApikeyDefault { + return &CreateUserApikeyDefault{ + _statusCode: code, + } +} + +/* CreateUserApikeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateUserApikeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserApikeyDefaultBody +} + +// Code gets the status code for the create user apikey default response +func (o *CreateUserApikeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create user apikey default response has a 2xx status code +func (o *CreateUserApikeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create user apikey default response has a 3xx status code +func (o *CreateUserApikeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create user apikey default response has a 4xx status code +func (o *CreateUserApikeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create user apikey default response has a 5xx status code +func (o *CreateUserApikeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create user apikey default response a status code equal to that given +func (o *CreateUserApikeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateUserApikeyDefault) Error() string { + return fmt.Sprintf("[POST /user/apikeys][%d] createUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserApikeyDefault) String() string { + return fmt.Sprintf("[POST /user/apikeys][%d] createUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserApikeyDefault) GetPayload() *CreateUserApikeyDefaultBody { + return o.Payload +} + +func (o *CreateUserApikeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserApikeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateUserApikeyDefaultBody create user apikey default body +swagger:model CreateUserApikeyDefaultBody +*/ +type CreateUserApikeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create user apikey default body +func (o *CreateUserApikeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserApikeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createUserApikey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateUserApikeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createUserApikey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user apikey default body based on the context it is used +func (o *CreateUserApikeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserApikeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserApikeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserApikeyDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateUserApikeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateUserApikeyOKBody create user apikey o k body +swagger:model CreateUserApikeyOKBody +*/ +type CreateUserApikeyOKBody struct { + + // result + Result *models.ApikeyID `json:"result,omitempty"` +} + +// Validate validates this create user apikey o k body +func (o *CreateUserApikeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserApikeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user apikey o k body based on the context it is used +func (o *CreateUserApikeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserApikeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserApikeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserApikeyOKBody) UnmarshalBinary(b []byte) error { + var res CreateUserApikeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/delete_user_apikey_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/delete_user_apikey_parameters.go new file mode 100644 index 0000000..3dd7d9b --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/delete_user_apikey_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteUserApikeyParams creates a new DeleteUserApikeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteUserApikeyParams() *DeleteUserApikeyParams { + return &DeleteUserApikeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteUserApikeyParamsWithTimeout creates a new DeleteUserApikeyParams object +// with the ability to set a timeout on a request. +func NewDeleteUserApikeyParamsWithTimeout(timeout time.Duration) *DeleteUserApikeyParams { + return &DeleteUserApikeyParams{ + timeout: timeout, + } +} + +// NewDeleteUserApikeyParamsWithContext creates a new DeleteUserApikeyParams object +// with the ability to set a context for a request. +func NewDeleteUserApikeyParamsWithContext(ctx context.Context) *DeleteUserApikeyParams { + return &DeleteUserApikeyParams{ + Context: ctx, + } +} + +// NewDeleteUserApikeyParamsWithHTTPClient creates a new DeleteUserApikeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteUserApikeyParamsWithHTTPClient(client *http.Client) *DeleteUserApikeyParams { + return &DeleteUserApikeyParams{ + HTTPClient: client, + } +} + +/* DeleteUserApikeyParams contains all the parameters to send to the API endpoint + for the delete user apikey operation. + + Typically these are written to a http.Request. +*/ +type DeleteUserApikeyParams struct { + + // ApikeyID. + ApikeyID string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserApikeyParams) WithDefaults() *DeleteUserApikeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserApikeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete user apikey params +func (o *DeleteUserApikeyParams) WithTimeout(timeout time.Duration) *DeleteUserApikeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete user apikey params +func (o *DeleteUserApikeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete user apikey params +func (o *DeleteUserApikeyParams) WithContext(ctx context.Context) *DeleteUserApikeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete user apikey params +func (o *DeleteUserApikeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete user apikey params +func (o *DeleteUserApikeyParams) WithHTTPClient(client *http.Client) *DeleteUserApikeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete user apikey params +func (o *DeleteUserApikeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithApikeyID adds the apikeyID to the delete user apikey params +func (o *DeleteUserApikeyParams) WithApikeyID(apikeyID string) *DeleteUserApikeyParams { + o.SetApikeyID(apikeyID) + return o +} + +// SetApikeyID adds the apikeyId to the delete user apikey params +func (o *DeleteUserApikeyParams) SetApikeyID(apikeyID string) { + o.ApikeyID = apikeyID +} + +// WithAuthorization adds the authorization to the delete user apikey params +func (o *DeleteUserApikeyParams) WithAuthorization(authorization string) *DeleteUserApikeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete user apikey params +func (o *DeleteUserApikeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete user apikey params +func (o *DeleteUserApikeyParams) WithBmpLanguage(bmpLanguage *string) *DeleteUserApikeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete user apikey params +func (o *DeleteUserApikeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete user apikey params +func (o *DeleteUserApikeyParams) WithBmpUserID(bmpUserID *string) *DeleteUserApikeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete user apikey params +func (o *DeleteUserApikeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete user apikey params +func (o *DeleteUserApikeyParams) WithTraceID(traceID string) *DeleteUserApikeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete user apikey params +func (o *DeleteUserApikeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteUserApikeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param apikey_id + if err := r.SetPathParam("apikey_id", o.ApikeyID); err != nil { + return err + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/delete_user_apikey_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/delete_user_apikey_responses.go new file mode 100644 index 0000000..6eedb73 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/delete_user_apikey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DeleteUserApikeyReader is a Reader for the DeleteUserApikey structure. +type DeleteUserApikeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteUserApikeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteUserApikeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteUserApikeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteUserApikeyOK creates a DeleteUserApikeyOK with default headers values +func NewDeleteUserApikeyOK() *DeleteUserApikeyOK { + return &DeleteUserApikeyOK{} +} + +/* DeleteUserApikeyOK describes a response with status code 200, with default header values. + +A DeleteUserApikeyResult is an response struct that is used to describe delete Apikey result. +*/ +type DeleteUserApikeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserApikeyOKBody +} + +// IsSuccess returns true when this delete user apikey o k response has a 2xx status code +func (o *DeleteUserApikeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete user apikey o k response has a 3xx status code +func (o *DeleteUserApikeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete user apikey o k response has a 4xx status code +func (o *DeleteUserApikeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete user apikey o k response has a 5xx status code +func (o *DeleteUserApikeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete user apikey o k response a status code equal to that given +func (o *DeleteUserApikeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteUserApikeyOK) Error() string { + return fmt.Sprintf("[DELETE /user/apikeys/{apikey_id}][%d] deleteUserApikeyOK %+v", 200, o.Payload) +} + +func (o *DeleteUserApikeyOK) String() string { + return fmt.Sprintf("[DELETE /user/apikeys/{apikey_id}][%d] deleteUserApikeyOK %+v", 200, o.Payload) +} + +func (o *DeleteUserApikeyOK) GetPayload() *DeleteUserApikeyOKBody { + return o.Payload +} + +func (o *DeleteUserApikeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserApikeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteUserApikeyDefault creates a DeleteUserApikeyDefault with default headers values +func NewDeleteUserApikeyDefault(code int) *DeleteUserApikeyDefault { + return &DeleteUserApikeyDefault{ + _statusCode: code, + } +} + +/* DeleteUserApikeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteUserApikeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserApikeyDefaultBody +} + +// Code gets the status code for the delete user apikey default response +func (o *DeleteUserApikeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete user apikey default response has a 2xx status code +func (o *DeleteUserApikeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete user apikey default response has a 3xx status code +func (o *DeleteUserApikeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete user apikey default response has a 4xx status code +func (o *DeleteUserApikeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete user apikey default response has a 5xx status code +func (o *DeleteUserApikeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete user apikey default response a status code equal to that given +func (o *DeleteUserApikeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteUserApikeyDefault) Error() string { + return fmt.Sprintf("[DELETE /user/apikeys/{apikey_id}][%d] deleteUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserApikeyDefault) String() string { + return fmt.Sprintf("[DELETE /user/apikeys/{apikey_id}][%d] deleteUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserApikeyDefault) GetPayload() *DeleteUserApikeyDefaultBody { + return o.Payload +} + +func (o *DeleteUserApikeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserApikeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteUserApikeyDefaultBody delete user apikey default body +swagger:model DeleteUserApikeyDefaultBody +*/ +type DeleteUserApikeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete user apikey default body +func (o *DeleteUserApikeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserApikeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserApikey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteUserApikeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserApikey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user apikey default body based on the context it is used +func (o *DeleteUserApikeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserApikeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserApikeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserApikeyDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteUserApikeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteUserApikeyOKBody delete user apikey o k body +swagger:model DeleteUserApikeyOKBody +*/ +type DeleteUserApikeyOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete user apikey o k body +func (o *DeleteUserApikeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserApikeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user apikey o k body based on the context it is used +func (o *DeleteUserApikeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserApikeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserApikeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserApikeyOKBody) UnmarshalBinary(b []byte) error { + var res DeleteUserApikeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/describe_user_api_key_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/describe_user_api_key_parameters.go new file mode 100644 index 0000000..0d39690 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/describe_user_api_key_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeUserAPIKeyParams creates a new DescribeUserAPIKeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserAPIKeyParams() *DescribeUserAPIKeyParams { + return &DescribeUserAPIKeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserAPIKeyParamsWithTimeout creates a new DescribeUserAPIKeyParams object +// with the ability to set a timeout on a request. +func NewDescribeUserAPIKeyParamsWithTimeout(timeout time.Duration) *DescribeUserAPIKeyParams { + return &DescribeUserAPIKeyParams{ + timeout: timeout, + } +} + +// NewDescribeUserAPIKeyParamsWithContext creates a new DescribeUserAPIKeyParams object +// with the ability to set a context for a request. +func NewDescribeUserAPIKeyParamsWithContext(ctx context.Context) *DescribeUserAPIKeyParams { + return &DescribeUserAPIKeyParams{ + Context: ctx, + } +} + +// NewDescribeUserAPIKeyParamsWithHTTPClient creates a new DescribeUserAPIKeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserAPIKeyParamsWithHTTPClient(client *http.Client) *DescribeUserAPIKeyParams { + return &DescribeUserAPIKeyParams{ + HTTPClient: client, + } +} + +/* DescribeUserAPIKeyParams contains all the parameters to send to the API endpoint + for the describe user API key operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserAPIKeyParams struct { + + // ApikeyID. + ApikeyID string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user API key params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserAPIKeyParams) WithDefaults() *DescribeUserAPIKeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user API key params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserAPIKeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithTimeout(timeout time.Duration) *DescribeUserAPIKeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithContext(ctx context.Context) *DescribeUserAPIKeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithHTTPClient(client *http.Client) *DescribeUserAPIKeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithApikeyID adds the apikeyID to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithApikeyID(apikeyID string) *DescribeUserAPIKeyParams { + o.SetApikeyID(apikeyID) + return o +} + +// SetApikeyID adds the apikeyId to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetApikeyID(apikeyID string) { + o.ApikeyID = apikeyID +} + +// WithAuthorization adds the authorization to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithAuthorization(authorization string) *DescribeUserAPIKeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserAPIKeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithBmpUserID(bmpUserID *string) *DescribeUserAPIKeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithTraceID(traceID string) *DescribeUserAPIKeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserAPIKeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param apikey_id + if err := r.SetPathParam("apikey_id", o.ApikeyID); err != nil { + return err + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/describe_user_api_key_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/describe_user_api_key_responses.go new file mode 100644 index 0000000..dae5018 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/describe_user_api_key_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeUserAPIKeyReader is a Reader for the DescribeUserAPIKey structure. +type DescribeUserAPIKeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserAPIKeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserAPIKeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserAPIKeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserAPIKeyOK creates a DescribeUserAPIKeyOK with default headers values +func NewDescribeUserAPIKeyOK() *DescribeUserAPIKeyOK { + return &DescribeUserAPIKeyOK{} +} + +/* DescribeUserAPIKeyOK describes a response with status code 200, with default header values. + +A DescribeUserAPIKeyResult is an response struct that is used to describe getapikey. +*/ +type DescribeUserAPIKeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserAPIKeyOKBody +} + +// IsSuccess returns true when this describe user Api key o k response has a 2xx status code +func (o *DescribeUserAPIKeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user Api key o k response has a 3xx status code +func (o *DescribeUserAPIKeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user Api key o k response has a 4xx status code +func (o *DescribeUserAPIKeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user Api key o k response has a 5xx status code +func (o *DescribeUserAPIKeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user Api key o k response a status code equal to that given +func (o *DescribeUserAPIKeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserAPIKeyOK) Error() string { + return fmt.Sprintf("[GET /user/apikeys/{apikey_id}][%d] describeUserApiKeyOK %+v", 200, o.Payload) +} + +func (o *DescribeUserAPIKeyOK) String() string { + return fmt.Sprintf("[GET /user/apikeys/{apikey_id}][%d] describeUserApiKeyOK %+v", 200, o.Payload) +} + +func (o *DescribeUserAPIKeyOK) GetPayload() *DescribeUserAPIKeyOKBody { + return o.Payload +} + +func (o *DescribeUserAPIKeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserAPIKeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserAPIKeyDefault creates a DescribeUserAPIKeyDefault with default headers values +func NewDescribeUserAPIKeyDefault(code int) *DescribeUserAPIKeyDefault { + return &DescribeUserAPIKeyDefault{ + _statusCode: code, + } +} + +/* DescribeUserAPIKeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserAPIKeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserAPIKeyDefaultBody +} + +// Code gets the status code for the describe user API key default response +func (o *DescribeUserAPIKeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user API key default response has a 2xx status code +func (o *DescribeUserAPIKeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user API key default response has a 3xx status code +func (o *DescribeUserAPIKeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user API key default response has a 4xx status code +func (o *DescribeUserAPIKeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user API key default response has a 5xx status code +func (o *DescribeUserAPIKeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user API key default response a status code equal to that given +func (o *DescribeUserAPIKeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserAPIKeyDefault) Error() string { + return fmt.Sprintf("[GET /user/apikeys/{apikey_id}][%d] describeUserAPIKey default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserAPIKeyDefault) String() string { + return fmt.Sprintf("[GET /user/apikeys/{apikey_id}][%d] describeUserAPIKey default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserAPIKeyDefault) GetPayload() *DescribeUserAPIKeyDefaultBody { + return o.Payload +} + +func (o *DescribeUserAPIKeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserAPIKeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserAPIKeyDefaultBody describe user API key default body +swagger:model DescribeUserAPIKeyDefaultBody +*/ +type DescribeUserAPIKeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user API key default body +func (o *DescribeUserAPIKeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserAPIKey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserAPIKeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserAPIKey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserAPIKey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserAPIKey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user API key default body based on the context it is used +func (o *DescribeUserAPIKeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserAPIKey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserAPIKey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserAPIKeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserAPIKeyDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserAPIKeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserAPIKeyOKBody describe user API key o k body +swagger:model DescribeUserAPIKeyOKBody +*/ +type DescribeUserAPIKeyOKBody struct { + + // result + Result *models.ApikeyInfo `json:"result,omitempty"` +} + +// Validate validates this describe user API key o k body +func (o *DescribeUserAPIKeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserApiKeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserApiKeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user API key o k body based on the context it is used +func (o *DescribeUserAPIKeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserApiKeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserApiKeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserAPIKeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserAPIKeyOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserAPIKeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/describe_user_api_keys_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/describe_user_api_keys_parameters.go new file mode 100644 index 0000000..4fecbc7 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/describe_user_api_keys_parameters.go @@ -0,0 +1,396 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeUserAPIKeysParams creates a new DescribeUserAPIKeysParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserAPIKeysParams() *DescribeUserAPIKeysParams { + return &DescribeUserAPIKeysParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserAPIKeysParamsWithTimeout creates a new DescribeUserAPIKeysParams object +// with the ability to set a timeout on a request. +func NewDescribeUserAPIKeysParamsWithTimeout(timeout time.Duration) *DescribeUserAPIKeysParams { + return &DescribeUserAPIKeysParams{ + timeout: timeout, + } +} + +// NewDescribeUserAPIKeysParamsWithContext creates a new DescribeUserAPIKeysParams object +// with the ability to set a context for a request. +func NewDescribeUserAPIKeysParamsWithContext(ctx context.Context) *DescribeUserAPIKeysParams { + return &DescribeUserAPIKeysParams{ + Context: ctx, + } +} + +// NewDescribeUserAPIKeysParamsWithHTTPClient creates a new DescribeUserAPIKeysParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserAPIKeysParamsWithHTTPClient(client *http.Client) *DescribeUserAPIKeysParams { + return &DescribeUserAPIKeysParams{ + HTTPClient: client, + } +} + +/* DescribeUserAPIKeysParams contains all the parameters to send to the API endpoint + for the describe user API keys operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserAPIKeysParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否查询全部/导出 + */ + IsAll *string + + /* Name. + + 秘钥对名称 + */ + Name *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* Type. + + Token类型, [system/user] + */ + Type *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user API keys params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserAPIKeysParams) WithDefaults() *DescribeUserAPIKeysParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user API keys params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserAPIKeysParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithTimeout(timeout time.Duration) *DescribeUserAPIKeysParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithContext(ctx context.Context) *DescribeUserAPIKeysParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithHTTPClient(client *http.Client) *DescribeUserAPIKeysParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithAuthorization(authorization string) *DescribeUserAPIKeysParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserAPIKeysParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithBmpUserID(bmpUserID *string) *DescribeUserAPIKeysParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithIsAll(isAll *string) *DescribeUserAPIKeysParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithName adds the name to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithName(name *string) *DescribeUserAPIKeysParams { + o.SetName(name) + return o +} + +// SetName adds the name to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetName(name *string) { + o.Name = name +} + +// WithPageNumber adds the pageNumber to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithPageNumber(pageNumber *int64) *DescribeUserAPIKeysParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithPageSize(pageSize *int64) *DescribeUserAPIKeysParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithTraceID(traceID string) *DescribeUserAPIKeysParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithType adds the typeVar to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithType(typeVar *string) *DescribeUserAPIKeysParams { + o.SetType(typeVar) + return o +} + +// SetType adds the type to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetType(typeVar *string) { + o.Type = typeVar +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserAPIKeysParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.Type != nil { + + // query param type + var qrType string + + if o.Type != nil { + qrType = *o.Type + } + qType := qrType + if qType != "" { + + if err := r.SetQueryParam("type", qType); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/describe_user_api_keys_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/describe_user_api_keys_responses.go new file mode 100644 index 0000000..5fef1ab --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/describe_user_api_keys_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeUserAPIKeysReader is a Reader for the DescribeUserAPIKeys structure. +type DescribeUserAPIKeysReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserAPIKeysReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserAPIKeysOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserAPIKeysDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserAPIKeysOK creates a DescribeUserAPIKeysOK with default headers values +func NewDescribeUserAPIKeysOK() *DescribeUserAPIKeysOK { + return &DescribeUserAPIKeysOK{} +} + +/* DescribeUserAPIKeysOK describes a response with status code 200, with default header values. + +A DescribeUserAPIKeysResult is an response struct that is used to describe getapikeylist. +*/ +type DescribeUserAPIKeysOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserAPIKeysOKBody +} + +// IsSuccess returns true when this describe user Api keys o k response has a 2xx status code +func (o *DescribeUserAPIKeysOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user Api keys o k response has a 3xx status code +func (o *DescribeUserAPIKeysOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user Api keys o k response has a 4xx status code +func (o *DescribeUserAPIKeysOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user Api keys o k response has a 5xx status code +func (o *DescribeUserAPIKeysOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user Api keys o k response a status code equal to that given +func (o *DescribeUserAPIKeysOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserAPIKeysOK) Error() string { + return fmt.Sprintf("[GET /user/apikeys][%d] describeUserApiKeysOK %+v", 200, o.Payload) +} + +func (o *DescribeUserAPIKeysOK) String() string { + return fmt.Sprintf("[GET /user/apikeys][%d] describeUserApiKeysOK %+v", 200, o.Payload) +} + +func (o *DescribeUserAPIKeysOK) GetPayload() *DescribeUserAPIKeysOKBody { + return o.Payload +} + +func (o *DescribeUserAPIKeysOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserAPIKeysOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserAPIKeysDefault creates a DescribeUserAPIKeysDefault with default headers values +func NewDescribeUserAPIKeysDefault(code int) *DescribeUserAPIKeysDefault { + return &DescribeUserAPIKeysDefault{ + _statusCode: code, + } +} + +/* DescribeUserAPIKeysDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserAPIKeysDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserAPIKeysDefaultBody +} + +// Code gets the status code for the describe user API keys default response +func (o *DescribeUserAPIKeysDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user API keys default response has a 2xx status code +func (o *DescribeUserAPIKeysDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user API keys default response has a 3xx status code +func (o *DescribeUserAPIKeysDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user API keys default response has a 4xx status code +func (o *DescribeUserAPIKeysDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user API keys default response has a 5xx status code +func (o *DescribeUserAPIKeysDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user API keys default response a status code equal to that given +func (o *DescribeUserAPIKeysDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserAPIKeysDefault) Error() string { + return fmt.Sprintf("[GET /user/apikeys][%d] describeUserAPIKeys default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserAPIKeysDefault) String() string { + return fmt.Sprintf("[GET /user/apikeys][%d] describeUserAPIKeys default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserAPIKeysDefault) GetPayload() *DescribeUserAPIKeysDefaultBody { + return o.Payload +} + +func (o *DescribeUserAPIKeysDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserAPIKeysDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserAPIKeysDefaultBody describe user API keys default body +swagger:model DescribeUserAPIKeysDefaultBody +*/ +type DescribeUserAPIKeysDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user API keys default body +func (o *DescribeUserAPIKeysDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeysDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserAPIKeys default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserAPIKeysDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserAPIKeys default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserAPIKeys default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserAPIKeys default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user API keys default body based on the context it is used +func (o *DescribeUserAPIKeysDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeysDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserAPIKeys default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserAPIKeys default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserAPIKeysDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserAPIKeysDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserAPIKeysDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserAPIKeysOKBody describe user API keys o k body +swagger:model DescribeUserAPIKeysOKBody +*/ +type DescribeUserAPIKeysOKBody struct { + + // result + Result *models.ApikeyList `json:"result,omitempty"` +} + +// Validate validates this describe user API keys o k body +func (o *DescribeUserAPIKeysOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeysOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserApiKeysOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserApiKeysOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user API keys o k body based on the context it is used +func (o *DescribeUserAPIKeysOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeysOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserApiKeysOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserApiKeysOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserAPIKeysOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserAPIKeysOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserAPIKeysOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/modify_user_apikey_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/modify_user_apikey_parameters.go new file mode 100644 index 0000000..6121ec1 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/modify_user_apikey_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewModifyUserApikeyParams creates a new ModifyUserApikeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyUserApikeyParams() *ModifyUserApikeyParams { + return &ModifyUserApikeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyUserApikeyParamsWithTimeout creates a new ModifyUserApikeyParams object +// with the ability to set a timeout on a request. +func NewModifyUserApikeyParamsWithTimeout(timeout time.Duration) *ModifyUserApikeyParams { + return &ModifyUserApikeyParams{ + timeout: timeout, + } +} + +// NewModifyUserApikeyParamsWithContext creates a new ModifyUserApikeyParams object +// with the ability to set a context for a request. +func NewModifyUserApikeyParamsWithContext(ctx context.Context) *ModifyUserApikeyParams { + return &ModifyUserApikeyParams{ + Context: ctx, + } +} + +// NewModifyUserApikeyParamsWithHTTPClient creates a new ModifyUserApikeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyUserApikeyParamsWithHTTPClient(client *http.Client) *ModifyUserApikeyParams { + return &ModifyUserApikeyParams{ + HTTPClient: client, + } +} + +/* ModifyUserApikeyParams contains all the parameters to send to the API endpoint + for the modify user apikey operation. + + Typically these are written to a http.Request. +*/ +type ModifyUserApikeyParams struct { + + // Body. + Body *models.ModifyApikeyRequest + + // ApikeyID. + ApikeyID string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserApikeyParams) WithDefaults() *ModifyUserApikeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserApikeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify user apikey params +func (o *ModifyUserApikeyParams) WithTimeout(timeout time.Duration) *ModifyUserApikeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify user apikey params +func (o *ModifyUserApikeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify user apikey params +func (o *ModifyUserApikeyParams) WithContext(ctx context.Context) *ModifyUserApikeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify user apikey params +func (o *ModifyUserApikeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify user apikey params +func (o *ModifyUserApikeyParams) WithHTTPClient(client *http.Client) *ModifyUserApikeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify user apikey params +func (o *ModifyUserApikeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify user apikey params +func (o *ModifyUserApikeyParams) WithBody(body *models.ModifyApikeyRequest) *ModifyUserApikeyParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify user apikey params +func (o *ModifyUserApikeyParams) SetBody(body *models.ModifyApikeyRequest) { + o.Body = body +} + +// WithApikeyID adds the apikeyID to the modify user apikey params +func (o *ModifyUserApikeyParams) WithApikeyID(apikeyID string) *ModifyUserApikeyParams { + o.SetApikeyID(apikeyID) + return o +} + +// SetApikeyID adds the apikeyId to the modify user apikey params +func (o *ModifyUserApikeyParams) SetApikeyID(apikeyID string) { + o.ApikeyID = apikeyID +} + +// WithAuthorization adds the authorization to the modify user apikey params +func (o *ModifyUserApikeyParams) WithAuthorization(authorization string) *ModifyUserApikeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify user apikey params +func (o *ModifyUserApikeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify user apikey params +func (o *ModifyUserApikeyParams) WithBmpLanguage(bmpLanguage *string) *ModifyUserApikeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify user apikey params +func (o *ModifyUserApikeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify user apikey params +func (o *ModifyUserApikeyParams) WithBmpUserID(bmpUserID *string) *ModifyUserApikeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify user apikey params +func (o *ModifyUserApikeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the modify user apikey params +func (o *ModifyUserApikeyParams) WithTraceID(traceID string) *ModifyUserApikeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify user apikey params +func (o *ModifyUserApikeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyUserApikeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // path param apikey_id + if err := r.SetPathParam("apikey_id", o.ApikeyID); err != nil { + return err + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/modify_user_apikey_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/modify_user_apikey_responses.go new file mode 100644 index 0000000..16eb663 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/api_key/modify_user_apikey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// ModifyUserApikeyReader is a Reader for the ModifyUserApikey structure. +type ModifyUserApikeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyUserApikeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyUserApikeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyUserApikeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyUserApikeyOK creates a ModifyUserApikeyOK with default headers values +func NewModifyUserApikeyOK() *ModifyUserApikeyOK { + return &ModifyUserApikeyOK{} +} + +/* ModifyUserApikeyOK describes a response with status code 200, with default header values. + +A ModifyUserApikeyResult is an response struct that is used to describe modifyApikey result. +*/ +type ModifyUserApikeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserApikeyOKBody +} + +// IsSuccess returns true when this modify user apikey o k response has a 2xx status code +func (o *ModifyUserApikeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify user apikey o k response has a 3xx status code +func (o *ModifyUserApikeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify user apikey o k response has a 4xx status code +func (o *ModifyUserApikeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify user apikey o k response has a 5xx status code +func (o *ModifyUserApikeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify user apikey o k response a status code equal to that given +func (o *ModifyUserApikeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyUserApikeyOK) Error() string { + return fmt.Sprintf("[PUT /user/apikeys/{apikey_id}][%d] modifyUserApikeyOK %+v", 200, o.Payload) +} + +func (o *ModifyUserApikeyOK) String() string { + return fmt.Sprintf("[PUT /user/apikeys/{apikey_id}][%d] modifyUserApikeyOK %+v", 200, o.Payload) +} + +func (o *ModifyUserApikeyOK) GetPayload() *ModifyUserApikeyOKBody { + return o.Payload +} + +func (o *ModifyUserApikeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserApikeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyUserApikeyDefault creates a ModifyUserApikeyDefault with default headers values +func NewModifyUserApikeyDefault(code int) *ModifyUserApikeyDefault { + return &ModifyUserApikeyDefault{ + _statusCode: code, + } +} + +/* ModifyUserApikeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyUserApikeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserApikeyDefaultBody +} + +// Code gets the status code for the modify user apikey default response +func (o *ModifyUserApikeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify user apikey default response has a 2xx status code +func (o *ModifyUserApikeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify user apikey default response has a 3xx status code +func (o *ModifyUserApikeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify user apikey default response has a 4xx status code +func (o *ModifyUserApikeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify user apikey default response has a 5xx status code +func (o *ModifyUserApikeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify user apikey default response a status code equal to that given +func (o *ModifyUserApikeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyUserApikeyDefault) Error() string { + return fmt.Sprintf("[PUT /user/apikeys/{apikey_id}][%d] modifyUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserApikeyDefault) String() string { + return fmt.Sprintf("[PUT /user/apikeys/{apikey_id}][%d] modifyUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserApikeyDefault) GetPayload() *ModifyUserApikeyDefaultBody { + return o.Payload +} + +func (o *ModifyUserApikeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserApikeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyUserApikeyDefaultBody modify user apikey default body +swagger:model ModifyUserApikeyDefaultBody +*/ +type ModifyUserApikeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify user apikey default body +func (o *ModifyUserApikeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserApikeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserApikey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyUserApikeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserApikey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user apikey default body based on the context it is used +func (o *ModifyUserApikeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserApikeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserApikeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserApikeyDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyUserApikeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyUserApikeyOKBody modify user apikey o k body +swagger:model ModifyUserApikeyOKBody +*/ +type ModifyUserApikeyOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify user apikey o k body +func (o *ModifyUserApikeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserApikeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user apikey o k body based on the context it is used +func (o *ModifyUserApikeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserApikeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserApikeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserApikeyOKBody) UnmarshalBinary(b []byte) error { + var res ModifyUserApikeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/audit_log/audit_log_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/audit_log/audit_log_client.go new file mode 100644 index 0000000..38e1c67 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/audit_log/audit_log_client.go @@ -0,0 +1,117 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package audit_log + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new audit log API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for audit log API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DescribeAuditLogTypes(params *DescribeAuditLogTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAuditLogTypesOK, error) + + DescribeAuditLogs(params *DescribeAuditLogsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAuditLogsOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DescribeAuditLogTypes DescribeAuditLogTypes 获取审计日志类型 +*/ +func (a *Client) DescribeAuditLogTypes(params *DescribeAuditLogTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAuditLogTypesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeAuditLogTypesParams() + } + op := &runtime.ClientOperation{ + ID: "describeAuditLogTypes", + Method: "GET", + PathPattern: "/auditLogs/types", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeAuditLogTypesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeAuditLogTypesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeAuditLogTypesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeAuditLogs DescribeAuditLogs 获取审计日志列表 +*/ +func (a *Client) DescribeAuditLogs(params *DescribeAuditLogsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAuditLogsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeAuditLogsParams() + } + op := &runtime.ClientOperation{ + ID: "describeAuditLogs", + Method: "GET", + PathPattern: "/auditLogs", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeAuditLogsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeAuditLogsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeAuditLogsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/audit_log/describe_audit_log_types_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/audit_log/describe_audit_log_types_parameters.go new file mode 100644 index 0000000..b7dcb80 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/audit_log/describe_audit_log_types_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package audit_log + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeAuditLogTypesParams creates a new DescribeAuditLogTypesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeAuditLogTypesParams() *DescribeAuditLogTypesParams { + return &DescribeAuditLogTypesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeAuditLogTypesParamsWithTimeout creates a new DescribeAuditLogTypesParams object +// with the ability to set a timeout on a request. +func NewDescribeAuditLogTypesParamsWithTimeout(timeout time.Duration) *DescribeAuditLogTypesParams { + return &DescribeAuditLogTypesParams{ + timeout: timeout, + } +} + +// NewDescribeAuditLogTypesParamsWithContext creates a new DescribeAuditLogTypesParams object +// with the ability to set a context for a request. +func NewDescribeAuditLogTypesParamsWithContext(ctx context.Context) *DescribeAuditLogTypesParams { + return &DescribeAuditLogTypesParams{ + Context: ctx, + } +} + +// NewDescribeAuditLogTypesParamsWithHTTPClient creates a new DescribeAuditLogTypesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeAuditLogTypesParamsWithHTTPClient(client *http.Client) *DescribeAuditLogTypesParams { + return &DescribeAuditLogTypesParams{ + HTTPClient: client, + } +} + +/* DescribeAuditLogTypesParams contains all the parameters to send to the API endpoint + for the describe audit log types operation. + + Typically these are written to a http.Request. +*/ +type DescribeAuditLogTypesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe audit log types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAuditLogTypesParams) WithDefaults() *DescribeAuditLogTypesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe audit log types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAuditLogTypesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe audit log types params +func (o *DescribeAuditLogTypesParams) WithTimeout(timeout time.Duration) *DescribeAuditLogTypesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe audit log types params +func (o *DescribeAuditLogTypesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe audit log types params +func (o *DescribeAuditLogTypesParams) WithContext(ctx context.Context) *DescribeAuditLogTypesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe audit log types params +func (o *DescribeAuditLogTypesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe audit log types params +func (o *DescribeAuditLogTypesParams) WithHTTPClient(client *http.Client) *DescribeAuditLogTypesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe audit log types params +func (o *DescribeAuditLogTypesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe audit log types params +func (o *DescribeAuditLogTypesParams) WithAuthorization(authorization string) *DescribeAuditLogTypesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe audit log types params +func (o *DescribeAuditLogTypesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe audit log types params +func (o *DescribeAuditLogTypesParams) WithBmpLanguage(bmpLanguage *string) *DescribeAuditLogTypesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe audit log types params +func (o *DescribeAuditLogTypesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe audit log types params +func (o *DescribeAuditLogTypesParams) WithBmpUserID(bmpUserID *string) *DescribeAuditLogTypesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe audit log types params +func (o *DescribeAuditLogTypesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe audit log types params +func (o *DescribeAuditLogTypesParams) WithTraceID(traceID string) *DescribeAuditLogTypesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe audit log types params +func (o *DescribeAuditLogTypesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeAuditLogTypesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/audit_log/describe_audit_log_types_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/audit_log/describe_audit_log_types_responses.go new file mode 100644 index 0000000..9ab2262 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/audit_log/describe_audit_log_types_responses.go @@ -0,0 +1,415 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package audit_log + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeAuditLogTypesReader is a Reader for the DescribeAuditLogTypes structure. +type DescribeAuditLogTypesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeAuditLogTypesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeAuditLogTypesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeAuditLogTypesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeAuditLogTypesOK creates a DescribeAuditLogTypesOK with default headers values +func NewDescribeAuditLogTypesOK() *DescribeAuditLogTypesOK { + return &DescribeAuditLogTypesOK{} +} + +/* DescribeAuditLogTypesOK describes a response with status code 200, with default header values. + +DescribeAuditLogTypesOK describe audit log types o k +*/ +type DescribeAuditLogTypesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAuditLogTypesOKBody +} + +// IsSuccess returns true when this describe audit log types o k response has a 2xx status code +func (o *DescribeAuditLogTypesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe audit log types o k response has a 3xx status code +func (o *DescribeAuditLogTypesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe audit log types o k response has a 4xx status code +func (o *DescribeAuditLogTypesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe audit log types o k response has a 5xx status code +func (o *DescribeAuditLogTypesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe audit log types o k response a status code equal to that given +func (o *DescribeAuditLogTypesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeAuditLogTypesOK) Error() string { + return fmt.Sprintf("[GET /auditLogs/types][%d] describeAuditLogTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeAuditLogTypesOK) String() string { + return fmt.Sprintf("[GET /auditLogs/types][%d] describeAuditLogTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeAuditLogTypesOK) GetPayload() *DescribeAuditLogTypesOKBody { + return o.Payload +} + +func (o *DescribeAuditLogTypesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAuditLogTypesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeAuditLogTypesDefault creates a DescribeAuditLogTypesDefault with default headers values +func NewDescribeAuditLogTypesDefault(code int) *DescribeAuditLogTypesDefault { + return &DescribeAuditLogTypesDefault{ + _statusCode: code, + } +} + +/* DescribeAuditLogTypesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeAuditLogTypesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAuditLogTypesDefaultBody +} + +// Code gets the status code for the describe audit log types default response +func (o *DescribeAuditLogTypesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe audit log types default response has a 2xx status code +func (o *DescribeAuditLogTypesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe audit log types default response has a 3xx status code +func (o *DescribeAuditLogTypesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe audit log types default response has a 4xx status code +func (o *DescribeAuditLogTypesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe audit log types default response has a 5xx status code +func (o *DescribeAuditLogTypesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe audit log types default response a status code equal to that given +func (o *DescribeAuditLogTypesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeAuditLogTypesDefault) Error() string { + return fmt.Sprintf("[GET /auditLogs/types][%d] describeAuditLogTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAuditLogTypesDefault) String() string { + return fmt.Sprintf("[GET /auditLogs/types][%d] describeAuditLogTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAuditLogTypesDefault) GetPayload() *DescribeAuditLogTypesDefaultBody { + return o.Payload +} + +func (o *DescribeAuditLogTypesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAuditLogTypesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeAuditLogTypesDefaultBody describe audit log types default body +swagger:model DescribeAuditLogTypesDefaultBody +*/ +type DescribeAuditLogTypesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe audit log types default body +func (o *DescribeAuditLogTypesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogTypesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeAuditLogTypes default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeAuditLogTypesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeAuditLogTypes default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe audit log types default body based on the context it is used +func (o *DescribeAuditLogTypesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogTypesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAuditLogTypesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAuditLogTypesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeAuditLogTypesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeAuditLogTypesOKBody describe audit log types o k body +swagger:model DescribeAuditLogTypesOKBody +*/ +type DescribeAuditLogTypesOKBody struct { + + // result + Result []*models.AuditLogsType `json:"result"` +} + +// Validate validates this describe audit log types o k body +func (o *DescribeAuditLogTypesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogTypesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + for i := 0; i < len(o.Result); i++ { + if swag.IsZero(o.Result[i]) { // not required + continue + } + + if o.Result[i] != nil { + if err := o.Result[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogTypesOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogTypesOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this describe audit log types o k body based on the context it is used +func (o *DescribeAuditLogTypesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogTypesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Result); i++ { + + if o.Result[i] != nil { + if err := o.Result[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogTypesOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogTypesOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAuditLogTypesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAuditLogTypesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeAuditLogTypesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/audit_log/describe_audit_logs_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/audit_log/describe_audit_logs_parameters.go new file mode 100644 index 0000000..37dced3 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/audit_log/describe_audit_logs_parameters.go @@ -0,0 +1,536 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package audit_log + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeAuditLogsParams creates a new DescribeAuditLogsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeAuditLogsParams() *DescribeAuditLogsParams { + return &DescribeAuditLogsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeAuditLogsParamsWithTimeout creates a new DescribeAuditLogsParams object +// with the ability to set a timeout on a request. +func NewDescribeAuditLogsParamsWithTimeout(timeout time.Duration) *DescribeAuditLogsParams { + return &DescribeAuditLogsParams{ + timeout: timeout, + } +} + +// NewDescribeAuditLogsParamsWithContext creates a new DescribeAuditLogsParams object +// with the ability to set a context for a request. +func NewDescribeAuditLogsParamsWithContext(ctx context.Context) *DescribeAuditLogsParams { + return &DescribeAuditLogsParams{ + Context: ctx, + } +} + +// NewDescribeAuditLogsParamsWithHTTPClient creates a new DescribeAuditLogsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeAuditLogsParamsWithHTTPClient(client *http.Client) *DescribeAuditLogsParams { + return &DescribeAuditLogsParams{ + HTTPClient: client, + } +} + +/* DescribeAuditLogsParams contains all the parameters to send to the API endpoint + for the describe audit logs operation. + + Typically these are written to a http.Request. +*/ +type DescribeAuditLogsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* EndTime. + + 操作时间上限 + + Format: int64 + */ + EndTime *int64 + + /* InstanceID. + + instance_id + */ + InstanceID *string + + /* IsAll. + + 是否显示所有 + */ + IsAll *string + + /* Operation. + + 操作名称 + */ + Operation *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* Result. + + result + */ + Result *string + + /* StartTime. + + 操作时间下限 + + Format: int64 + */ + StartTime *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* Username. + + 操作人 + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe audit logs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAuditLogsParams) WithDefaults() *DescribeAuditLogsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe audit logs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAuditLogsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe audit logs params +func (o *DescribeAuditLogsParams) WithTimeout(timeout time.Duration) *DescribeAuditLogsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe audit logs params +func (o *DescribeAuditLogsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe audit logs params +func (o *DescribeAuditLogsParams) WithContext(ctx context.Context) *DescribeAuditLogsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe audit logs params +func (o *DescribeAuditLogsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe audit logs params +func (o *DescribeAuditLogsParams) WithHTTPClient(client *http.Client) *DescribeAuditLogsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe audit logs params +func (o *DescribeAuditLogsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe audit logs params +func (o *DescribeAuditLogsParams) WithAuthorization(authorization string) *DescribeAuditLogsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe audit logs params +func (o *DescribeAuditLogsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe audit logs params +func (o *DescribeAuditLogsParams) WithBmpLanguage(bmpLanguage *string) *DescribeAuditLogsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe audit logs params +func (o *DescribeAuditLogsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe audit logs params +func (o *DescribeAuditLogsParams) WithBmpUserID(bmpUserID *string) *DescribeAuditLogsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe audit logs params +func (o *DescribeAuditLogsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithEndTime adds the endTime to the describe audit logs params +func (o *DescribeAuditLogsParams) WithEndTime(endTime *int64) *DescribeAuditLogsParams { + o.SetEndTime(endTime) + return o +} + +// SetEndTime adds the endTime to the describe audit logs params +func (o *DescribeAuditLogsParams) SetEndTime(endTime *int64) { + o.EndTime = endTime +} + +// WithInstanceID adds the instanceID to the describe audit logs params +func (o *DescribeAuditLogsParams) WithInstanceID(instanceID *string) *DescribeAuditLogsParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the describe audit logs params +func (o *DescribeAuditLogsParams) SetInstanceID(instanceID *string) { + o.InstanceID = instanceID +} + +// WithIsAll adds the isAll to the describe audit logs params +func (o *DescribeAuditLogsParams) WithIsAll(isAll *string) *DescribeAuditLogsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe audit logs params +func (o *DescribeAuditLogsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithOperation adds the operation to the describe audit logs params +func (o *DescribeAuditLogsParams) WithOperation(operation *string) *DescribeAuditLogsParams { + o.SetOperation(operation) + return o +} + +// SetOperation adds the operation to the describe audit logs params +func (o *DescribeAuditLogsParams) SetOperation(operation *string) { + o.Operation = operation +} + +// WithPageNumber adds the pageNumber to the describe audit logs params +func (o *DescribeAuditLogsParams) WithPageNumber(pageNumber *int64) *DescribeAuditLogsParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe audit logs params +func (o *DescribeAuditLogsParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe audit logs params +func (o *DescribeAuditLogsParams) WithPageSize(pageSize *int64) *DescribeAuditLogsParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe audit logs params +func (o *DescribeAuditLogsParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithResult adds the result to the describe audit logs params +func (o *DescribeAuditLogsParams) WithResult(result *string) *DescribeAuditLogsParams { + o.SetResult(result) + return o +} + +// SetResult adds the result to the describe audit logs params +func (o *DescribeAuditLogsParams) SetResult(result *string) { + o.Result = result +} + +// WithStartTime adds the startTime to the describe audit logs params +func (o *DescribeAuditLogsParams) WithStartTime(startTime *int64) *DescribeAuditLogsParams { + o.SetStartTime(startTime) + return o +} + +// SetStartTime adds the startTime to the describe audit logs params +func (o *DescribeAuditLogsParams) SetStartTime(startTime *int64) { + o.StartTime = startTime +} + +// WithTraceID adds the traceID to the describe audit logs params +func (o *DescribeAuditLogsParams) WithTraceID(traceID string) *DescribeAuditLogsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe audit logs params +func (o *DescribeAuditLogsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserName adds the username to the describe audit logs params +func (o *DescribeAuditLogsParams) WithUserName(username *string) *DescribeAuditLogsParams { + o.SetUserName(username) + return o +} + +// SetUserName adds the username to the describe audit logs params +func (o *DescribeAuditLogsParams) SetUserName(username *string) { + o.UserName = username +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeAuditLogsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.EndTime != nil { + + // query param endTime + var qrEndTime int64 + + if o.EndTime != nil { + qrEndTime = *o.EndTime + } + qEndTime := swag.FormatInt64(qrEndTime) + if qEndTime != "" { + + if err := r.SetQueryParam("endTime", qEndTime); err != nil { + return err + } + } + } + + if o.InstanceID != nil { + + // query param instance_id + var qrInstanceID string + + if o.InstanceID != nil { + qrInstanceID = *o.InstanceID + } + qInstanceID := qrInstanceID + if qInstanceID != "" { + + if err := r.SetQueryParam("instance_id", qInstanceID); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Operation != nil { + + // query param operation + var qrOperation string + + if o.Operation != nil { + qrOperation = *o.Operation + } + qOperation := qrOperation + if qOperation != "" { + + if err := r.SetQueryParam("operation", qOperation); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.Result != nil { + + // query param result + var qrResult string + + if o.Result != nil { + qrResult = *o.Result + } + qResult := qrResult + if qResult != "" { + + if err := r.SetQueryParam("result", qResult); err != nil { + return err + } + } + } + + if o.StartTime != nil { + + // query param startTime + var qrStartTime int64 + + if o.StartTime != nil { + qrStartTime = *o.StartTime + } + qStartTime := swag.FormatInt64(qrStartTime) + if qStartTime != "" { + + if err := r.SetQueryParam("startTime", qStartTime); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserName != nil { + + // query param username + var qrUsername string + + if o.UserName != nil { + qrUsername = *o.UserName + } + qUsername := qrUsername + if qUsername != "" { + + if err := r.SetQueryParam("username", qUsername); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/audit_log/describe_audit_logs_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/audit_log/describe_audit_logs_responses.go new file mode 100644 index 0000000..3de31d8 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/audit_log/describe_audit_logs_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package audit_log + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeAuditLogsReader is a Reader for the DescribeAuditLogs structure. +type DescribeAuditLogsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeAuditLogsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeAuditLogsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeAuditLogsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeAuditLogsOK creates a DescribeAuditLogsOK with default headers values +func NewDescribeAuditLogsOK() *DescribeAuditLogsOK { + return &DescribeAuditLogsOK{} +} + +/* DescribeAuditLogsOK describes a response with status code 200, with default header values. + +DescribeAuditLogsOK describe audit logs o k +*/ +type DescribeAuditLogsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAuditLogsOKBody +} + +// IsSuccess returns true when this describe audit logs o k response has a 2xx status code +func (o *DescribeAuditLogsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe audit logs o k response has a 3xx status code +func (o *DescribeAuditLogsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe audit logs o k response has a 4xx status code +func (o *DescribeAuditLogsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe audit logs o k response has a 5xx status code +func (o *DescribeAuditLogsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe audit logs o k response a status code equal to that given +func (o *DescribeAuditLogsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeAuditLogsOK) Error() string { + return fmt.Sprintf("[GET /auditLogs][%d] describeAuditLogsOK %+v", 200, o.Payload) +} + +func (o *DescribeAuditLogsOK) String() string { + return fmt.Sprintf("[GET /auditLogs][%d] describeAuditLogsOK %+v", 200, o.Payload) +} + +func (o *DescribeAuditLogsOK) GetPayload() *DescribeAuditLogsOKBody { + return o.Payload +} + +func (o *DescribeAuditLogsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAuditLogsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeAuditLogsDefault creates a DescribeAuditLogsDefault with default headers values +func NewDescribeAuditLogsDefault(code int) *DescribeAuditLogsDefault { + return &DescribeAuditLogsDefault{ + _statusCode: code, + } +} + +/* DescribeAuditLogsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeAuditLogsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAuditLogsDefaultBody +} + +// Code gets the status code for the describe audit logs default response +func (o *DescribeAuditLogsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe audit logs default response has a 2xx status code +func (o *DescribeAuditLogsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe audit logs default response has a 3xx status code +func (o *DescribeAuditLogsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe audit logs default response has a 4xx status code +func (o *DescribeAuditLogsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe audit logs default response has a 5xx status code +func (o *DescribeAuditLogsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe audit logs default response a status code equal to that given +func (o *DescribeAuditLogsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeAuditLogsDefault) Error() string { + return fmt.Sprintf("[GET /auditLogs][%d] describeAuditLogs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAuditLogsDefault) String() string { + return fmt.Sprintf("[GET /auditLogs][%d] describeAuditLogs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAuditLogsDefault) GetPayload() *DescribeAuditLogsDefaultBody { + return o.Payload +} + +func (o *DescribeAuditLogsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAuditLogsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeAuditLogsDefaultBody describe audit logs default body +swagger:model DescribeAuditLogsDefaultBody +*/ +type DescribeAuditLogsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe audit logs default body +func (o *DescribeAuditLogsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeAuditLogs default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeAuditLogsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeAuditLogs default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogs default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe audit logs default body based on the context it is used +func (o *DescribeAuditLogsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogs default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAuditLogsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAuditLogsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeAuditLogsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeAuditLogsOKBody describe audit logs o k body +swagger:model DescribeAuditLogsOKBody +*/ +type DescribeAuditLogsOKBody struct { + + // result + Result *models.AuditLogList `json:"result,omitempty"` +} + +// Validate validates this describe audit logs o k body +func (o *DescribeAuditLogsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe audit logs o k body based on the context it is used +func (o *DescribeAuditLogsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAuditLogsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAuditLogsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeAuditLogsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/c_p_s_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/c_p_s_client.go new file mode 100644 index 0000000..f4c6114 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/c_p_s_client.go @@ -0,0 +1,202 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package client + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/api_key" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/audit_log" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/device" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/device_type" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/idc" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/image" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/instance" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/license" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/message" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/monitor_alert" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/monitor_data" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/monitor_proxy" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/monitor_rule" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/os" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/project" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/resource" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/role" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/sshkey" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/user" +) + +// Default c p s HTTP client. +var Default = NewHTTPClient(nil) + +const ( + // DefaultHost is the default Host + // found in Meta (info) section of spec file + DefaultHost string = "bmp-openapi-console.bmp.local" + // DefaultBasePath is the default BasePath + // found in Meta (info) section of spec file + DefaultBasePath string = "/v1" +) + +// DefaultSchemes are the default schemes found in Meta (info) section of spec file +var DefaultSchemes = []string{"http"} + +// NewHTTPClient creates a new c p s HTTP client. +func NewHTTPClient(formats strfmt.Registry) *CPS { + return NewHTTPClientWithConfig(formats, nil) +} + +// NewHTTPClientWithConfig creates a new c p s HTTP client, +// using a customizable transport config. +func NewHTTPClientWithConfig(formats strfmt.Registry, cfg *TransportConfig) *CPS { + // ensure nullable parameters have default + if cfg == nil { + cfg = DefaultTransportConfig() + } + + // create transport and client + transport := httptransport.New(cfg.Host, cfg.BasePath, cfg.Schemes) + return New(transport, formats) +} + +// New creates a new c p s client +func New(transport runtime.ClientTransport, formats strfmt.Registry) *CPS { + // ensure nullable parameters have default + if formats == nil { + formats = strfmt.Default + } + + cli := new(CPS) + cli.Transport = transport + cli.APIKey = api_key.New(transport, formats) + cli.AuditLog = audit_log.New(transport, formats) + cli.Device = device.New(transport, formats) + cli.DeviceType = device_type.New(transport, formats) + cli.Idc = idc.New(transport, formats) + cli.Image = image.New(transport, formats) + cli.Instance = instance.New(transport, formats) + cli.License = license.New(transport, formats) + cli.Message = message.New(transport, formats) + cli.MonitorAlert = monitor_alert.New(transport, formats) + cli.MonitorData = monitor_data.New(transport, formats) + cli.MonitorProxy = monitor_proxy.New(transport, formats) + cli.MonitorRule = monitor_rule.New(transport, formats) + cli.Os = os.New(transport, formats) + cli.Project = project.New(transport, formats) + cli.Resource = resource.New(transport, formats) + cli.Role = role.New(transport, formats) + cli.Sshkey = sshkey.New(transport, formats) + cli.User = user.New(transport, formats) + return cli +} + +// DefaultTransportConfig creates a TransportConfig with the +// default settings taken from the meta section of the spec file. +func DefaultTransportConfig() *TransportConfig { + return &TransportConfig{ + Host: DefaultHost, + BasePath: DefaultBasePath, + Schemes: DefaultSchemes, + } +} + +// TransportConfig contains the transport related info, +// found in the meta section of the spec file. +type TransportConfig struct { + Host string + BasePath string + Schemes []string +} + +// WithHost overrides the default host, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithHost(host string) *TransportConfig { + cfg.Host = host + return cfg +} + +// WithBasePath overrides the default basePath, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithBasePath(basePath string) *TransportConfig { + cfg.BasePath = basePath + return cfg +} + +// WithSchemes overrides the default schemes, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithSchemes(schemes []string) *TransportConfig { + cfg.Schemes = schemes + return cfg +} + +// CPS is a client for c p s +type CPS struct { + APIKey api_key.ClientService + + AuditLog audit_log.ClientService + + Device device.ClientService + + DeviceType device_type.ClientService + + Idc idc.ClientService + + Image image.ClientService + + Instance instance.ClientService + + License license.ClientService + + Message message.ClientService + + MonitorAlert monitor_alert.ClientService + + MonitorData monitor_data.ClientService + + MonitorProxy monitor_proxy.ClientService + + MonitorRule monitor_rule.ClientService + + Os os.ClientService + + Project project.ClientService + + Resource resource.ClientService + + Role role.ClientService + + Sshkey sshkey.ClientService + + User user.ClientService + + Transport runtime.ClientTransport +} + +// SetTransport changes the transport on the client and all its subresources +func (c *CPS) SetTransport(transport runtime.ClientTransport) { + c.Transport = transport + c.APIKey.SetTransport(transport) + c.AuditLog.SetTransport(transport) + c.Device.SetTransport(transport) + c.DeviceType.SetTransport(transport) + c.Idc.SetTransport(transport) + c.Image.SetTransport(transport) + c.Instance.SetTransport(transport) + c.License.SetTransport(transport) + c.Message.SetTransport(transport) + c.MonitorAlert.SetTransport(transport) + c.MonitorData.SetTransport(transport) + c.MonitorProxy.SetTransport(transport) + c.MonitorRule.SetTransport(transport) + c.Os.SetTransport(transport) + c.Project.SetTransport(transport) + c.Resource.SetTransport(transport) + c.Role.SetTransport(transport) + c.Sshkey.SetTransport(transport) + c.User.SetTransport(transport) +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_device_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_device_parameters.go new file mode 100644 index 0000000..7c7e31e --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_device_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeDeviceParams creates a new DescribeDeviceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceParams() *DescribeDeviceParams { + return &DescribeDeviceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceParamsWithTimeout creates a new DescribeDeviceParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceParamsWithTimeout(timeout time.Duration) *DescribeDeviceParams { + return &DescribeDeviceParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceParamsWithContext creates a new DescribeDeviceParams object +// with the ability to set a context for a request. +func NewDescribeDeviceParamsWithContext(ctx context.Context) *DescribeDeviceParams { + return &DescribeDeviceParams{ + Context: ctx, + } +} + +// NewDescribeDeviceParamsWithHTTPClient creates a new DescribeDeviceParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceParamsWithHTTPClient(client *http.Client) *DescribeDeviceParams { + return &DescribeDeviceParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceParams contains all the parameters to send to the API endpoint + for the describe device operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // DeviceID. + DeviceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceParams) WithDefaults() *DescribeDeviceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device params +func (o *DescribeDeviceParams) WithTimeout(timeout time.Duration) *DescribeDeviceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device params +func (o *DescribeDeviceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device params +func (o *DescribeDeviceParams) WithContext(ctx context.Context) *DescribeDeviceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device params +func (o *DescribeDeviceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device params +func (o *DescribeDeviceParams) WithHTTPClient(client *http.Client) *DescribeDeviceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device params +func (o *DescribeDeviceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device params +func (o *DescribeDeviceParams) WithAuthorization(authorization string) *DescribeDeviceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device params +func (o *DescribeDeviceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device params +func (o *DescribeDeviceParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device params +func (o *DescribeDeviceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device params +func (o *DescribeDeviceParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device params +func (o *DescribeDeviceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceID adds the deviceID to the describe device params +func (o *DescribeDeviceParams) WithDeviceID(deviceID string) *DescribeDeviceParams { + o.SetDeviceID(deviceID) + return o +} + +// SetDeviceID adds the deviceId to the describe device params +func (o *DescribeDeviceParams) SetDeviceID(deviceID string) { + o.DeviceID = deviceID +} + +// WithTraceID adds the traceID to the describe device params +func (o *DescribeDeviceParams) WithTraceID(traceID string) *DescribeDeviceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device params +func (o *DescribeDeviceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_id + if err := r.SetPathParam("device_id", o.DeviceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_device_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_device_responses.go new file mode 100644 index 0000000..27e5c0c --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_device_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeDeviceReader is a Reader for the DescribeDevice structure. +type DescribeDeviceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceOK creates a DescribeDeviceOK with default headers values +func NewDescribeDeviceOK() *DescribeDeviceOK { + return &DescribeDeviceOK{} +} + +/* DescribeDeviceOK describes a response with status code 200, with default header values. + +DescribeDeviceOK describe device o k +*/ +type DescribeDeviceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceOKBody +} + +// IsSuccess returns true when this describe device o k response has a 2xx status code +func (o *DescribeDeviceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device o k response has a 3xx status code +func (o *DescribeDeviceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device o k response has a 4xx status code +func (o *DescribeDeviceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device o k response has a 5xx status code +func (o *DescribeDeviceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device o k response a status code equal to that given +func (o *DescribeDeviceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceOK) Error() string { + return fmt.Sprintf("[GET /devices/{device_id}][%d] describeDeviceOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceOK) String() string { + return fmt.Sprintf("[GET /devices/{device_id}][%d] describeDeviceOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceOK) GetPayload() *DescribeDeviceOKBody { + return o.Payload +} + +func (o *DescribeDeviceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceDefault creates a DescribeDeviceDefault with default headers values +func NewDescribeDeviceDefault(code int) *DescribeDeviceDefault { + return &DescribeDeviceDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceDefaultBody +} + +// Code gets the status code for the describe device default response +func (o *DescribeDeviceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device default response has a 2xx status code +func (o *DescribeDeviceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device default response has a 3xx status code +func (o *DescribeDeviceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device default response has a 4xx status code +func (o *DescribeDeviceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device default response has a 5xx status code +func (o *DescribeDeviceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device default response a status code equal to that given +func (o *DescribeDeviceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceDefault) Error() string { + return fmt.Sprintf("[GET /devices/{device_id}][%d] describeDevice default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceDefault) String() string { + return fmt.Sprintf("[GET /devices/{device_id}][%d] describeDevice default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceDefault) GetPayload() *DescribeDeviceDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceDefaultBody describe device default body +swagger:model DescribeDeviceDefaultBody +*/ +type DescribeDeviceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device default body +func (o *DescribeDeviceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDevice default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDevice default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device default body based on the context it is used +func (o *DescribeDeviceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceOKBody describe device o k body +swagger:model DescribeDeviceOKBody +*/ +type DescribeDeviceOKBody struct { + + // result + Result *models.DeviceInfo `json:"result,omitempty"` +} + +// Validate validates this describe device o k body +func (o *DescribeDeviceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device o k body based on the context it is used +func (o *DescribeDeviceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_device_stock_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_device_stock_parameters.go new file mode 100644 index 0000000..66c5c8f --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_device_stock_parameters.go @@ -0,0 +1,252 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeDeviceStockParams creates a new DescribeDeviceStockParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceStockParams() *DescribeDeviceStockParams { + return &DescribeDeviceStockParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceStockParamsWithTimeout creates a new DescribeDeviceStockParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceStockParamsWithTimeout(timeout time.Duration) *DescribeDeviceStockParams { + return &DescribeDeviceStockParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceStockParamsWithContext creates a new DescribeDeviceStockParams object +// with the ability to set a context for a request. +func NewDescribeDeviceStockParamsWithContext(ctx context.Context) *DescribeDeviceStockParams { + return &DescribeDeviceStockParams{ + Context: ctx, + } +} + +// NewDescribeDeviceStockParamsWithHTTPClient creates a new DescribeDeviceStockParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceStockParamsWithHTTPClient(client *http.Client) *DescribeDeviceStockParams { + return &DescribeDeviceStockParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceStockParams contains all the parameters to send to the API endpoint + for the describe device stock operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceStockParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // DeviceTypeID. + DeviceTypeID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device stock params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceStockParams) WithDefaults() *DescribeDeviceStockParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device stock params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceStockParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device stock params +func (o *DescribeDeviceStockParams) WithTimeout(timeout time.Duration) *DescribeDeviceStockParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device stock params +func (o *DescribeDeviceStockParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device stock params +func (o *DescribeDeviceStockParams) WithContext(ctx context.Context) *DescribeDeviceStockParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device stock params +func (o *DescribeDeviceStockParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device stock params +func (o *DescribeDeviceStockParams) WithHTTPClient(client *http.Client) *DescribeDeviceStockParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device stock params +func (o *DescribeDeviceStockParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device stock params +func (o *DescribeDeviceStockParams) WithAuthorization(authorization string) *DescribeDeviceStockParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device stock params +func (o *DescribeDeviceStockParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device stock params +func (o *DescribeDeviceStockParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceStockParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device stock params +func (o *DescribeDeviceStockParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device stock params +func (o *DescribeDeviceStockParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceStockParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device stock params +func (o *DescribeDeviceStockParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device stock params +func (o *DescribeDeviceStockParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDeviceStockParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device stock params +func (o *DescribeDeviceStockParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithTraceID adds the traceID to the describe device stock params +func (o *DescribeDeviceStockParams) WithTraceID(traceID string) *DescribeDeviceStockParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device stock params +func (o *DescribeDeviceStockParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceStockParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_device_stock_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_device_stock_responses.go new file mode 100644 index 0000000..0b33dda --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_device_stock_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeDeviceStockReader is a Reader for the DescribeDeviceStock structure. +type DescribeDeviceStockReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceStockReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceStockOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceStockDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceStockOK creates a DescribeDeviceStockOK with default headers values +func NewDescribeDeviceStockOK() *DescribeDeviceStockOK { + return &DescribeDeviceStockOK{} +} + +/* DescribeDeviceStockOK describes a response with status code 200, with default header values. + +A GetDeviceStockResult is an response struct that is used to get device stock. +*/ +type DescribeDeviceStockOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceStockOKBody +} + +// IsSuccess returns true when this describe device stock o k response has a 2xx status code +func (o *DescribeDeviceStockOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device stock o k response has a 3xx status code +func (o *DescribeDeviceStockOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device stock o k response has a 4xx status code +func (o *DescribeDeviceStockOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device stock o k response has a 5xx status code +func (o *DescribeDeviceStockOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device stock o k response a status code equal to that given +func (o *DescribeDeviceStockOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceStockOK) Error() string { + return fmt.Sprintf("[DELETE /devices/stock][%d] describeDeviceStockOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceStockOK) String() string { + return fmt.Sprintf("[DELETE /devices/stock][%d] describeDeviceStockOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceStockOK) GetPayload() *DescribeDeviceStockOKBody { + return o.Payload +} + +func (o *DescribeDeviceStockOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceStockOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceStockDefault creates a DescribeDeviceStockDefault with default headers values +func NewDescribeDeviceStockDefault(code int) *DescribeDeviceStockDefault { + return &DescribeDeviceStockDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceStockDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceStockDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceStockDefaultBody +} + +// Code gets the status code for the describe device stock default response +func (o *DescribeDeviceStockDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device stock default response has a 2xx status code +func (o *DescribeDeviceStockDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device stock default response has a 3xx status code +func (o *DescribeDeviceStockDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device stock default response has a 4xx status code +func (o *DescribeDeviceStockDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device stock default response has a 5xx status code +func (o *DescribeDeviceStockDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device stock default response a status code equal to that given +func (o *DescribeDeviceStockDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceStockDefault) Error() string { + return fmt.Sprintf("[DELETE /devices/stock][%d] describeDeviceStock default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceStockDefault) String() string { + return fmt.Sprintf("[DELETE /devices/stock][%d] describeDeviceStock default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceStockDefault) GetPayload() *DescribeDeviceStockDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceStockDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceStockDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceStockDefaultBody describe device stock default body +swagger:model DescribeDeviceStockDefaultBody +*/ +type DescribeDeviceStockDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device stock default body +func (o *DescribeDeviceStockDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceStockDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceStock default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceStockDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceStock default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceStock default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceStock default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device stock default body based on the context it is used +func (o *DescribeDeviceStockDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceStockDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceStock default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceStock default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceStockDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceStockDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceStockDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceStockOKBody describe device stock o k body +swagger:model DescribeDeviceStockOKBody +*/ +type DescribeDeviceStockOKBody struct { + + // result + Result *models.DeviceStock `json:"result,omitempty"` +} + +// Validate validates this describe device stock o k body +func (o *DescribeDeviceStockOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceStockOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceStockOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceStockOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device stock o k body based on the context it is used +func (o *DescribeDeviceStockOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceStockOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceStockOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceStockOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceStockOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceStockOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceStockOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_devices_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_devices_parameters.go new file mode 100644 index 0000000..bcfea73 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_devices_parameters.go @@ -0,0 +1,702 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeDevicesParams creates a new DescribeDevicesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDevicesParams() *DescribeDevicesParams { + return &DescribeDevicesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDevicesParamsWithTimeout creates a new DescribeDevicesParams object +// with the ability to set a timeout on a request. +func NewDescribeDevicesParamsWithTimeout(timeout time.Duration) *DescribeDevicesParams { + return &DescribeDevicesParams{ + timeout: timeout, + } +} + +// NewDescribeDevicesParamsWithContext creates a new DescribeDevicesParams object +// with the ability to set a context for a request. +func NewDescribeDevicesParamsWithContext(ctx context.Context) *DescribeDevicesParams { + return &DescribeDevicesParams{ + Context: ctx, + } +} + +// NewDescribeDevicesParamsWithHTTPClient creates a new DescribeDevicesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDevicesParamsWithHTTPClient(client *http.Client) *DescribeDevicesParams { + return &DescribeDevicesParams{ + HTTPClient: client, + } +} + +/* DescribeDevicesParams contains all the parameters to send to the API endpoint + for the describe devices operation. + + Typically these are written to a http.Request. +*/ +type DescribeDevicesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceSeries. + + 机型类型 + */ + DeviceSeries *string + + /* DeviceTypeID. + + 机型id + */ + DeviceTypeID *string + + /* IdcID. + + 机房id + */ + IDcID *string + + /* IloIP. + + 带外ip + */ + IloIP *string + + /* InstanceID. + + 实例id + */ + InstanceID *string + + /* IPV4. + + ipv4 + */ + IPV4 *string + + /* IPV6. + + ipv6 + */ + IPV6 *string + + /* IsAll. + + 是否显示全部,1不分页 + */ + IsAll *string + + /* ManageStatus. + + 设备管理状态 + */ + ManageStatus *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* Sn. + + 设备sn + */ + Sn *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserID. + + 所属用户id + */ + UserID *string + + /* UserName. + + 所属用户 + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe devices params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDevicesParams) WithDefaults() *DescribeDevicesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe devices params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDevicesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe devices params +func (o *DescribeDevicesParams) WithTimeout(timeout time.Duration) *DescribeDevicesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe devices params +func (o *DescribeDevicesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe devices params +func (o *DescribeDevicesParams) WithContext(ctx context.Context) *DescribeDevicesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe devices params +func (o *DescribeDevicesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe devices params +func (o *DescribeDevicesParams) WithHTTPClient(client *http.Client) *DescribeDevicesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe devices params +func (o *DescribeDevicesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe devices params +func (o *DescribeDevicesParams) WithAuthorization(authorization string) *DescribeDevicesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe devices params +func (o *DescribeDevicesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe devices params +func (o *DescribeDevicesParams) WithBmpLanguage(bmpLanguage *string) *DescribeDevicesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe devices params +func (o *DescribeDevicesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe devices params +func (o *DescribeDevicesParams) WithBmpUserID(bmpUserID *string) *DescribeDevicesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe devices params +func (o *DescribeDevicesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceSeries adds the deviceSeries to the describe devices params +func (o *DescribeDevicesParams) WithDeviceSeries(deviceSeries *string) *DescribeDevicesParams { + o.SetDeviceSeries(deviceSeries) + return o +} + +// SetDeviceSeries adds the deviceSeries to the describe devices params +func (o *DescribeDevicesParams) SetDeviceSeries(deviceSeries *string) { + o.DeviceSeries = deviceSeries +} + +// WithDeviceTypeID adds the deviceTypeID to the describe devices params +func (o *DescribeDevicesParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDevicesParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe devices params +func (o *DescribeDevicesParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithIDcID adds the idcID to the describe devices params +func (o *DescribeDevicesParams) WithIDcID(idcID *string) *DescribeDevicesParams { + o.SetIDcID(idcID) + return o +} + +// SetIDcID adds the idcId to the describe devices params +func (o *DescribeDevicesParams) SetIDcID(idcID *string) { + o.IDcID = idcID +} + +// WithIloIP adds the iloIP to the describe devices params +func (o *DescribeDevicesParams) WithIloIP(iloIP *string) *DescribeDevicesParams { + o.SetIloIP(iloIP) + return o +} + +// SetIloIP adds the iloIp to the describe devices params +func (o *DescribeDevicesParams) SetIloIP(iloIP *string) { + o.IloIP = iloIP +} + +// WithInstanceID adds the instanceID to the describe devices params +func (o *DescribeDevicesParams) WithInstanceID(instanceID *string) *DescribeDevicesParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the describe devices params +func (o *DescribeDevicesParams) SetInstanceID(instanceID *string) { + o.InstanceID = instanceID +} + +// WithIPV4 adds the iPV4 to the describe devices params +func (o *DescribeDevicesParams) WithIPV4(iPV4 *string) *DescribeDevicesParams { + o.SetIPV4(iPV4) + return o +} + +// SetIPV4 adds the ipv4 to the describe devices params +func (o *DescribeDevicesParams) SetIPV4(iPV4 *string) { + o.IPV4 = iPV4 +} + +// WithIPV6 adds the iPV6 to the describe devices params +func (o *DescribeDevicesParams) WithIPV6(iPV6 *string) *DescribeDevicesParams { + o.SetIPV6(iPV6) + return o +} + +// SetIPV6 adds the ipv6 to the describe devices params +func (o *DescribeDevicesParams) SetIPV6(iPV6 *string) { + o.IPV6 = iPV6 +} + +// WithIsAll adds the isAll to the describe devices params +func (o *DescribeDevicesParams) WithIsAll(isAll *string) *DescribeDevicesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe devices params +func (o *DescribeDevicesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithManageStatus adds the manageStatus to the describe devices params +func (o *DescribeDevicesParams) WithManageStatus(manageStatus *string) *DescribeDevicesParams { + o.SetManageStatus(manageStatus) + return o +} + +// SetManageStatus adds the manageStatus to the describe devices params +func (o *DescribeDevicesParams) SetManageStatus(manageStatus *string) { + o.ManageStatus = manageStatus +} + +// WithPageNumber adds the pageNumber to the describe devices params +func (o *DescribeDevicesParams) WithPageNumber(pageNumber *int64) *DescribeDevicesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe devices params +func (o *DescribeDevicesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe devices params +func (o *DescribeDevicesParams) WithPageSize(pageSize *int64) *DescribeDevicesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe devices params +func (o *DescribeDevicesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithSn adds the sn to the describe devices params +func (o *DescribeDevicesParams) WithSn(sn *string) *DescribeDevicesParams { + o.SetSn(sn) + return o +} + +// SetSn adds the sn to the describe devices params +func (o *DescribeDevicesParams) SetSn(sn *string) { + o.Sn = sn +} + +// WithTraceID adds the traceID to the describe devices params +func (o *DescribeDevicesParams) WithTraceID(traceID string) *DescribeDevicesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe devices params +func (o *DescribeDevicesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserID adds the userID to the describe devices params +func (o *DescribeDevicesParams) WithUserID(userID *string) *DescribeDevicesParams { + o.SetUserID(userID) + return o +} + +// SetUserID adds the userId to the describe devices params +func (o *DescribeDevicesParams) SetUserID(userID *string) { + o.UserID = userID +} + +// WithUserName adds the userName to the describe devices params +func (o *DescribeDevicesParams) WithUserName(userName *string) *DescribeDevicesParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe devices params +func (o *DescribeDevicesParams) SetUserName(userName *string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDevicesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceSeries != nil { + + // query param deviceSeries + var qrDeviceSeries string + + if o.DeviceSeries != nil { + qrDeviceSeries = *o.DeviceSeries + } + qDeviceSeries := qrDeviceSeries + if qDeviceSeries != "" { + + if err := r.SetQueryParam("deviceSeries", qDeviceSeries); err != nil { + return err + } + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.IDcID != nil { + + // query param idcId + var qrIdcID string + + if o.IDcID != nil { + qrIdcID = *o.IDcID + } + qIdcID := qrIdcID + if qIdcID != "" { + + if err := r.SetQueryParam("idcId", qIdcID); err != nil { + return err + } + } + } + + if o.IloIP != nil { + + // query param iloIp + var qrIloIP string + + if o.IloIP != nil { + qrIloIP = *o.IloIP + } + qIloIP := qrIloIP + if qIloIP != "" { + + if err := r.SetQueryParam("iloIp", qIloIP); err != nil { + return err + } + } + } + + if o.InstanceID != nil { + + // query param instanceId + var qrInstanceID string + + if o.InstanceID != nil { + qrInstanceID = *o.InstanceID + } + qInstanceID := qrInstanceID + if qInstanceID != "" { + + if err := r.SetQueryParam("instanceId", qInstanceID); err != nil { + return err + } + } + } + + if o.IPV4 != nil { + + // query param ipv4 + var qrIPV4 string + + if o.IPV4 != nil { + qrIPV4 = *o.IPV4 + } + qIPV4 := qrIPV4 + if qIPV4 != "" { + + if err := r.SetQueryParam("ipv4", qIPV4); err != nil { + return err + } + } + } + + if o.IPV6 != nil { + + // query param ipv6 + var qrIPV6 string + + if o.IPV6 != nil { + qrIPV6 = *o.IPV6 + } + qIPV6 := qrIPV6 + if qIPV6 != "" { + + if err := r.SetQueryParam("ipv6", qIPV6); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.ManageStatus != nil { + + // query param manageStatus + var qrManageStatus string + + if o.ManageStatus != nil { + qrManageStatus = *o.ManageStatus + } + qManageStatus := qrManageStatus + if qManageStatus != "" { + + if err := r.SetQueryParam("manageStatus", qManageStatus); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.Sn != nil { + + // query param sn + var qrSn string + + if o.Sn != nil { + qrSn = *o.Sn + } + qSn := qrSn + if qSn != "" { + + if err := r.SetQueryParam("sn", qSn); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserID != nil { + + // query param userId + var qrUserID string + + if o.UserID != nil { + qrUserID = *o.UserID + } + qUserID := qrUserID + if qUserID != "" { + + if err := r.SetQueryParam("userId", qUserID); err != nil { + return err + } + } + } + + if o.UserName != nil { + + // query param userName + var qrUserName string + + if o.UserName != nil { + qrUserName = *o.UserName + } + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_devices_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_devices_responses.go new file mode 100644 index 0000000..5ad5781 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/describe_devices_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeDevicesReader is a Reader for the DescribeDevices structure. +type DescribeDevicesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDevicesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDevicesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDevicesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDevicesOK creates a DescribeDevicesOK with default headers values +func NewDescribeDevicesOK() *DescribeDevicesOK { + return &DescribeDevicesOK{} +} + +/* DescribeDevicesOK describes a response with status code 200, with default header values. + +DescribeDevicesOK describe devices o k +*/ +type DescribeDevicesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDevicesOKBody +} + +// IsSuccess returns true when this describe devices o k response has a 2xx status code +func (o *DescribeDevicesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe devices o k response has a 3xx status code +func (o *DescribeDevicesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe devices o k response has a 4xx status code +func (o *DescribeDevicesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe devices o k response has a 5xx status code +func (o *DescribeDevicesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe devices o k response a status code equal to that given +func (o *DescribeDevicesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDevicesOK) Error() string { + return fmt.Sprintf("[GET /devices][%d] describeDevicesOK %+v", 200, o.Payload) +} + +func (o *DescribeDevicesOK) String() string { + return fmt.Sprintf("[GET /devices][%d] describeDevicesOK %+v", 200, o.Payload) +} + +func (o *DescribeDevicesOK) GetPayload() *DescribeDevicesOKBody { + return o.Payload +} + +func (o *DescribeDevicesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDevicesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDevicesDefault creates a DescribeDevicesDefault with default headers values +func NewDescribeDevicesDefault(code int) *DescribeDevicesDefault { + return &DescribeDevicesDefault{ + _statusCode: code, + } +} + +/* DescribeDevicesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDevicesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDevicesDefaultBody +} + +// Code gets the status code for the describe devices default response +func (o *DescribeDevicesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe devices default response has a 2xx status code +func (o *DescribeDevicesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe devices default response has a 3xx status code +func (o *DescribeDevicesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe devices default response has a 4xx status code +func (o *DescribeDevicesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe devices default response has a 5xx status code +func (o *DescribeDevicesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe devices default response a status code equal to that given +func (o *DescribeDevicesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDevicesDefault) Error() string { + return fmt.Sprintf("[GET /devices][%d] describeDevices default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDevicesDefault) String() string { + return fmt.Sprintf("[GET /devices][%d] describeDevices default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDevicesDefault) GetPayload() *DescribeDevicesDefaultBody { + return o.Payload +} + +func (o *DescribeDevicesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDevicesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDevicesDefaultBody describe devices default body +swagger:model DescribeDevicesDefaultBody +*/ +type DescribeDevicesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe devices default body +func (o *DescribeDevicesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDevicesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDevices default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDevicesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDevices default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevices default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevices default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe devices default body based on the context it is used +func (o *DescribeDevicesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDevicesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevices default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevices default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDevicesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDevicesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDevicesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDevicesOKBody describe devices o k body +swagger:model DescribeDevicesOKBody +*/ +type DescribeDevicesOKBody struct { + + // result + Result *models.DeviceList `json:"result,omitempty"` +} + +// Validate validates this describe devices o k body +func (o *DescribeDevicesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDevicesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevicesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevicesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe devices o k body based on the context it is used +func (o *DescribeDevicesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDevicesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevicesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevicesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDevicesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDevicesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDevicesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/device_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/device_client.go new file mode 100644 index 0000000..866a527 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device/device_client.go @@ -0,0 +1,157 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new device API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for device API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DescribeDevice(params *DescribeDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceOK, error) + + DescribeDeviceStock(params *DescribeDeviceStockParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceStockOK, error) + + DescribeDevices(params *DescribeDevicesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDevicesOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DescribeDevice DescribeDevice 获取设备详情 +*/ +func (a *Client) DescribeDevice(params *DescribeDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceParams() + } + op := &runtime.ClientOperation{ + ID: "describeDevice", + Method: "GET", + PathPattern: "/devices/{device_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceStock DescribeDeviceStock 获取指定机型的设备库存 +*/ +func (a *Client) DescribeDeviceStock(params *DescribeDeviceStockParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceStockOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceStockParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceStock", + Method: "DELETE", + PathPattern: "/devices/stock", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceStockReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceStockOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceStockDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDevices DescribeDevices 获取设备列表 +*/ +func (a *Client) DescribeDevices(params *DescribeDevicesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDevicesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDevicesParams() + } + op := &runtime.ClientOperation{ + ID: "describeDevices", + Method: "GET", + PathPattern: "/devices", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDevicesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDevicesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDevicesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_image_partitions_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_image_partitions_parameters.go new file mode 100644 index 0000000..93af2e4 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_image_partitions_parameters.go @@ -0,0 +1,323 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeDeviceTypeImagePartitionsParams creates a new DescribeDeviceTypeImagePartitionsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceTypeImagePartitionsParams() *DescribeDeviceTypeImagePartitionsParams { + return &DescribeDeviceTypeImagePartitionsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceTypeImagePartitionsParamsWithTimeout creates a new DescribeDeviceTypeImagePartitionsParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceTypeImagePartitionsParamsWithTimeout(timeout time.Duration) *DescribeDeviceTypeImagePartitionsParams { + return &DescribeDeviceTypeImagePartitionsParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceTypeImagePartitionsParamsWithContext creates a new DescribeDeviceTypeImagePartitionsParams object +// with the ability to set a context for a request. +func NewDescribeDeviceTypeImagePartitionsParamsWithContext(ctx context.Context) *DescribeDeviceTypeImagePartitionsParams { + return &DescribeDeviceTypeImagePartitionsParams{ + Context: ctx, + } +} + +// NewDescribeDeviceTypeImagePartitionsParamsWithHTTPClient creates a new DescribeDeviceTypeImagePartitionsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceTypeImagePartitionsParamsWithHTTPClient(client *http.Client) *DescribeDeviceTypeImagePartitionsParams { + return &DescribeDeviceTypeImagePartitionsParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceTypeImagePartitionsParams contains all the parameters to send to the API endpoint + for the describe device type image partitions operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceTypeImagePartitionsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceTypeID. + + 机型id + */ + DeviceTypeID *string + + /* ImageID. + + 镜像id + */ + ImageID *string + + /* IsAll. + + 是否显示所有,isAll=1显示所有 + */ + IsAll *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device type image partitions params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeImagePartitionsParams) WithDefaults() *DescribeDeviceTypeImagePartitionsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device type image partitions params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeImagePartitionsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithTimeout(timeout time.Duration) *DescribeDeviceTypeImagePartitionsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithContext(ctx context.Context) *DescribeDeviceTypeImagePartitionsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithHTTPClient(client *http.Client) *DescribeDeviceTypeImagePartitionsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithAuthorization(authorization string) *DescribeDeviceTypeImagePartitionsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceTypeImagePartitionsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceTypeImagePartitionsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDeviceTypeImagePartitionsParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithImageID adds the imageID to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithImageID(imageID *string) *DescribeDeviceTypeImagePartitionsParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetImageID(imageID *string) { + o.ImageID = imageID +} + +// WithIsAll adds the isAll to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithIsAll(isAll *string) *DescribeDeviceTypeImagePartitionsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithTraceID adds the traceID to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithTraceID(traceID string) *DescribeDeviceTypeImagePartitionsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceTypeImagePartitionsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.ImageID != nil { + + // query param imageId + var qrImageID string + + if o.ImageID != nil { + qrImageID = *o.ImageID + } + qImageID := qrImageID + if qImageID != "" { + + if err := r.SetQueryParam("imageId", qImageID); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_image_partitions_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_image_partitions_responses.go new file mode 100644 index 0000000..5f63b2f --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_image_partitions_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeDeviceTypeImagePartitionsReader is a Reader for the DescribeDeviceTypeImagePartitions structure. +type DescribeDeviceTypeImagePartitionsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceTypeImagePartitionsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceTypeImagePartitionsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceTypeImagePartitionsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceTypeImagePartitionsOK creates a DescribeDeviceTypeImagePartitionsOK with default headers values +func NewDescribeDeviceTypeImagePartitionsOK() *DescribeDeviceTypeImagePartitionsOK { + return &DescribeDeviceTypeImagePartitionsOK{} +} + +/* DescribeDeviceTypeImagePartitionsOK describes a response with status code 200, with default header values. + +DescribeDeviceTypeImagePartitionsOK describe device type image partitions o k +*/ +type DescribeDeviceTypeImagePartitionsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeImagePartitionsOKBody +} + +// IsSuccess returns true when this describe device type image partitions o k response has a 2xx status code +func (o *DescribeDeviceTypeImagePartitionsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device type image partitions o k response has a 3xx status code +func (o *DescribeDeviceTypeImagePartitionsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device type image partitions o k response has a 4xx status code +func (o *DescribeDeviceTypeImagePartitionsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device type image partitions o k response has a 5xx status code +func (o *DescribeDeviceTypeImagePartitionsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device type image partitions o k response a status code equal to that given +func (o *DescribeDeviceTypeImagePartitionsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceTypeImagePartitionsOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImagePartition][%d] describeDeviceTypeImagePartitionsOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeImagePartitionsOK) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImagePartition][%d] describeDeviceTypeImagePartitionsOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeImagePartitionsOK) GetPayload() *DescribeDeviceTypeImagePartitionsOKBody { + return o.Payload +} + +func (o *DescribeDeviceTypeImagePartitionsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeImagePartitionsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceTypeImagePartitionsDefault creates a DescribeDeviceTypeImagePartitionsDefault with default headers values +func NewDescribeDeviceTypeImagePartitionsDefault(code int) *DescribeDeviceTypeImagePartitionsDefault { + return &DescribeDeviceTypeImagePartitionsDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceTypeImagePartitionsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceTypeImagePartitionsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeImagePartitionsDefaultBody +} + +// Code gets the status code for the describe device type image partitions default response +func (o *DescribeDeviceTypeImagePartitionsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device type image partitions default response has a 2xx status code +func (o *DescribeDeviceTypeImagePartitionsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device type image partitions default response has a 3xx status code +func (o *DescribeDeviceTypeImagePartitionsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device type image partitions default response has a 4xx status code +func (o *DescribeDeviceTypeImagePartitionsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device type image partitions default response has a 5xx status code +func (o *DescribeDeviceTypeImagePartitionsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device type image partitions default response a status code equal to that given +func (o *DescribeDeviceTypeImagePartitionsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceTypeImagePartitionsDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImagePartition][%d] describeDeviceTypeImagePartitions default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeImagePartitionsDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImagePartition][%d] describeDeviceTypeImagePartitions default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeImagePartitionsDefault) GetPayload() *DescribeDeviceTypeImagePartitionsDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceTypeImagePartitionsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeImagePartitionsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceTypeImagePartitionsDefaultBody describe device type image partitions default body +swagger:model DescribeDeviceTypeImagePartitionsDefaultBody +*/ +type DescribeDeviceTypeImagePartitionsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device type image partitions default body +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeImagePartitions default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeImagePartitions default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagePartitions default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagePartitions default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type image partitions default body based on the context it is used +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagePartitions default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagePartitions default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeImagePartitionsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceTypeImagePartitionsOKBody describe device type image partitions o k body +swagger:model DescribeDeviceTypeImagePartitionsOKBody +*/ +type DescribeDeviceTypeImagePartitionsOKBody struct { + + // result + Result *models.QueryDeviceTypeImagePartitionResponse `json:"result,omitempty"` +} + +// Validate validates this describe device type image partitions o k body +func (o *DescribeDeviceTypeImagePartitionsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagePartitionsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagePartitionsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagePartitionsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type image partitions o k body based on the context it is used +func (o *DescribeDeviceTypeImagePartitionsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagePartitionsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagePartitionsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagePartitionsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeImagePartitionsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeImagePartitionsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeImagePartitionsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_images_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_images_parameters.go new file mode 100644 index 0000000..18a2d74 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_images_parameters.go @@ -0,0 +1,600 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeDeviceTypeImagesParams creates a new DescribeDeviceTypeImagesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceTypeImagesParams() *DescribeDeviceTypeImagesParams { + return &DescribeDeviceTypeImagesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceTypeImagesParamsWithTimeout creates a new DescribeDeviceTypeImagesParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceTypeImagesParamsWithTimeout(timeout time.Duration) *DescribeDeviceTypeImagesParams { + return &DescribeDeviceTypeImagesParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceTypeImagesParamsWithContext creates a new DescribeDeviceTypeImagesParams object +// with the ability to set a context for a request. +func NewDescribeDeviceTypeImagesParamsWithContext(ctx context.Context) *DescribeDeviceTypeImagesParams { + return &DescribeDeviceTypeImagesParams{ + Context: ctx, + } +} + +// NewDescribeDeviceTypeImagesParamsWithHTTPClient creates a new DescribeDeviceTypeImagesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceTypeImagesParamsWithHTTPClient(client *http.Client) *DescribeDeviceTypeImagesParams { + return &DescribeDeviceTypeImagesParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceTypeImagesParams contains all the parameters to send to the API endpoint + for the describe device type images operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceTypeImagesParams struct { + + /* Architecture. + + 体系架构 + */ + Architecture *string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceTypeID. + + 机型id + */ + DeviceTypeID *string + + /* ImageID. + + 镜像id + */ + ImageID *string + + /* ImageName. + + 镜像名称 + */ + ImageName *string + + /* IsAll. + + 是否显示全部 + */ + IsAll *string + + /* OsID. + + 操作系统ID + */ + OsID *string + + /* OsType. + + 操作系统平台 + */ + OsType *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* Source. + + 镜像类型,预置,自定义 + */ + Source *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* Version. + + 版本号 + */ + Version *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device type images params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeImagesParams) WithDefaults() *DescribeDeviceTypeImagesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device type images params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeImagesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithTimeout(timeout time.Duration) *DescribeDeviceTypeImagesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithContext(ctx context.Context) *DescribeDeviceTypeImagesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithHTTPClient(client *http.Client) *DescribeDeviceTypeImagesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithArchitecture adds the architecture to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithArchitecture(architecture *string) *DescribeDeviceTypeImagesParams { + o.SetArchitecture(architecture) + return o +} + +// SetArchitecture adds the architecture to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetArchitecture(architecture *string) { + o.Architecture = architecture +} + +// WithAuthorization adds the authorization to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithAuthorization(authorization string) *DescribeDeviceTypeImagesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceTypeImagesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceTypeImagesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDeviceTypeImagesParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithImageID adds the imageID to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithImageID(imageID *string) *DescribeDeviceTypeImagesParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetImageID(imageID *string) { + o.ImageID = imageID +} + +// WithImageName adds the imageName to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithImageName(imageName *string) *DescribeDeviceTypeImagesParams { + o.SetImageName(imageName) + return o +} + +// SetImageName adds the imageName to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetImageName(imageName *string) { + o.ImageName = imageName +} + +// WithIsAll adds the isAll to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithIsAll(isAll *string) *DescribeDeviceTypeImagesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithOsID adds the osID to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithOsID(osID *string) *DescribeDeviceTypeImagesParams { + o.SetOsID(osID) + return o +} + +// SetOsID adds the osId to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetOsID(osID *string) { + o.OsID = osID +} + +// WithOsType adds the osType to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithOsType(osType *string) *DescribeDeviceTypeImagesParams { + o.SetOsType(osType) + return o +} + +// SetOsType adds the osType to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetOsType(osType *string) { + o.OsType = osType +} + +// WithPageNumber adds the pageNumber to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithPageNumber(pageNumber *int64) *DescribeDeviceTypeImagesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithPageSize(pageSize *int64) *DescribeDeviceTypeImagesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithSource adds the source to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithSource(source *string) *DescribeDeviceTypeImagesParams { + o.SetSource(source) + return o +} + +// SetSource adds the source to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetSource(source *string) { + o.Source = source +} + +// WithTraceID adds the traceID to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithTraceID(traceID string) *DescribeDeviceTypeImagesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithVersion adds the version to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithVersion(version *string) *DescribeDeviceTypeImagesParams { + o.SetVersion(version) + return o +} + +// SetVersion adds the version to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetVersion(version *string) { + o.Version = version +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceTypeImagesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Architecture != nil { + + // query param architecture + var qrArchitecture string + + if o.Architecture != nil { + qrArchitecture = *o.Architecture + } + qArchitecture := qrArchitecture + if qArchitecture != "" { + + if err := r.SetQueryParam("architecture", qArchitecture); err != nil { + return err + } + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.ImageID != nil { + + // query param imageId + var qrImageID string + + if o.ImageID != nil { + qrImageID = *o.ImageID + } + qImageID := qrImageID + if qImageID != "" { + + if err := r.SetQueryParam("imageId", qImageID); err != nil { + return err + } + } + } + + if o.ImageName != nil { + + // query param imageName + var qrImageName string + + if o.ImageName != nil { + qrImageName = *o.ImageName + } + qImageName := qrImageName + if qImageName != "" { + + if err := r.SetQueryParam("imageName", qImageName); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.OsID != nil { + + // query param osId + var qrOsID string + + if o.OsID != nil { + qrOsID = *o.OsID + } + qOsID := qrOsID + if qOsID != "" { + + if err := r.SetQueryParam("osId", qOsID); err != nil { + return err + } + } + } + + if o.OsType != nil { + + // query param osType + var qrOsType string + + if o.OsType != nil { + qrOsType = *o.OsType + } + qOsType := qrOsType + if qOsType != "" { + + if err := r.SetQueryParam("osType", qOsType); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.Source != nil { + + // query param source + var qrSource string + + if o.Source != nil { + qrSource = *o.Source + } + qSource := qrSource + if qSource != "" { + + if err := r.SetQueryParam("source", qSource); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.Version != nil { + + // query param version + var qrVersion string + + if o.Version != nil { + qrVersion = *o.Version + } + qVersion := qrVersion + if qVersion != "" { + + if err := r.SetQueryParam("version", qVersion); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_images_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_images_responses.go new file mode 100644 index 0000000..ef8a14b --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_images_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeDeviceTypeImagesReader is a Reader for the DescribeDeviceTypeImages structure. +type DescribeDeviceTypeImagesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceTypeImagesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceTypeImagesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceTypeImagesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceTypeImagesOK creates a DescribeDeviceTypeImagesOK with default headers values +func NewDescribeDeviceTypeImagesOK() *DescribeDeviceTypeImagesOK { + return &DescribeDeviceTypeImagesOK{} +} + +/* DescribeDeviceTypeImagesOK describes a response with status code 200, with default header values. + +DescribeDeviceTypeImagesOK describe device type images o k +*/ +type DescribeDeviceTypeImagesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeImagesOKBody +} + +// IsSuccess returns true when this describe device type images o k response has a 2xx status code +func (o *DescribeDeviceTypeImagesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device type images o k response has a 3xx status code +func (o *DescribeDeviceTypeImagesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device type images o k response has a 4xx status code +func (o *DescribeDeviceTypeImagesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device type images o k response has a 5xx status code +func (o *DescribeDeviceTypeImagesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device type images o k response a status code equal to that given +func (o *DescribeDeviceTypeImagesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceTypeImagesOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImage][%d] describeDeviceTypeImagesOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeImagesOK) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImage][%d] describeDeviceTypeImagesOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeImagesOK) GetPayload() *DescribeDeviceTypeImagesOKBody { + return o.Payload +} + +func (o *DescribeDeviceTypeImagesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeImagesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceTypeImagesDefault creates a DescribeDeviceTypeImagesDefault with default headers values +func NewDescribeDeviceTypeImagesDefault(code int) *DescribeDeviceTypeImagesDefault { + return &DescribeDeviceTypeImagesDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceTypeImagesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceTypeImagesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeImagesDefaultBody +} + +// Code gets the status code for the describe device type images default response +func (o *DescribeDeviceTypeImagesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device type images default response has a 2xx status code +func (o *DescribeDeviceTypeImagesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device type images default response has a 3xx status code +func (o *DescribeDeviceTypeImagesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device type images default response has a 4xx status code +func (o *DescribeDeviceTypeImagesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device type images default response has a 5xx status code +func (o *DescribeDeviceTypeImagesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device type images default response a status code equal to that given +func (o *DescribeDeviceTypeImagesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceTypeImagesDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImage][%d] describeDeviceTypeImages default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeImagesDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImage][%d] describeDeviceTypeImages default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeImagesDefault) GetPayload() *DescribeDeviceTypeImagesDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceTypeImagesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeImagesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceTypeImagesDefaultBody describe device type images default body +swagger:model DescribeDeviceTypeImagesDefaultBody +*/ +type DescribeDeviceTypeImagesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device type images default body +func (o *DescribeDeviceTypeImagesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeImages default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceTypeImagesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeImages default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImages default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImages default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type images default body based on the context it is used +func (o *DescribeDeviceTypeImagesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImages default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImages default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeImagesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeImagesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeImagesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceTypeImagesOKBody describe device type images o k body +swagger:model DescribeDeviceTypeImagesOKBody +*/ +type DescribeDeviceTypeImagesOKBody struct { + + // result + Result *models.ImageList `json:"result,omitempty"` +} + +// Validate validates this describe device type images o k body +func (o *DescribeDeviceTypeImagesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type images o k body based on the context it is used +func (o *DescribeDeviceTypeImagesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeImagesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeImagesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeImagesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_parameters.go new file mode 100644 index 0000000..fb352df --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeDeviceTypeParams creates a new DescribeDeviceTypeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceTypeParams() *DescribeDeviceTypeParams { + return &DescribeDeviceTypeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceTypeParamsWithTimeout creates a new DescribeDeviceTypeParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceTypeParamsWithTimeout(timeout time.Duration) *DescribeDeviceTypeParams { + return &DescribeDeviceTypeParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceTypeParamsWithContext creates a new DescribeDeviceTypeParams object +// with the ability to set a context for a request. +func NewDescribeDeviceTypeParamsWithContext(ctx context.Context) *DescribeDeviceTypeParams { + return &DescribeDeviceTypeParams{ + Context: ctx, + } +} + +// NewDescribeDeviceTypeParamsWithHTTPClient creates a new DescribeDeviceTypeParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceTypeParamsWithHTTPClient(client *http.Client) *DescribeDeviceTypeParams { + return &DescribeDeviceTypeParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceTypeParams contains all the parameters to send to the API endpoint + for the describe device type operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceTypeParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // DeviceTypeID. + DeviceTypeID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeParams) WithDefaults() *DescribeDeviceTypeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device type params +func (o *DescribeDeviceTypeParams) WithTimeout(timeout time.Duration) *DescribeDeviceTypeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device type params +func (o *DescribeDeviceTypeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device type params +func (o *DescribeDeviceTypeParams) WithContext(ctx context.Context) *DescribeDeviceTypeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device type params +func (o *DescribeDeviceTypeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device type params +func (o *DescribeDeviceTypeParams) WithHTTPClient(client *http.Client) *DescribeDeviceTypeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device type params +func (o *DescribeDeviceTypeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device type params +func (o *DescribeDeviceTypeParams) WithAuthorization(authorization string) *DescribeDeviceTypeParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device type params +func (o *DescribeDeviceTypeParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device type params +func (o *DescribeDeviceTypeParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceTypeParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device type params +func (o *DescribeDeviceTypeParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device type params +func (o *DescribeDeviceTypeParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceTypeParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device type params +func (o *DescribeDeviceTypeParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device type params +func (o *DescribeDeviceTypeParams) WithDeviceTypeID(deviceTypeID string) *DescribeDeviceTypeParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device type params +func (o *DescribeDeviceTypeParams) SetDeviceTypeID(deviceTypeID string) { + o.DeviceTypeID = deviceTypeID +} + +// WithTraceID adds the traceID to the describe device type params +func (o *DescribeDeviceTypeParams) WithTraceID(traceID string) *DescribeDeviceTypeParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device type params +func (o *DescribeDeviceTypeParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceTypeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_type_id + if err := r.SetPathParam("device_type_id", o.DeviceTypeID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_responses.go new file mode 100644 index 0000000..8947d34 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_type_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeDeviceTypeReader is a Reader for the DescribeDeviceType structure. +type DescribeDeviceTypeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceTypeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceTypeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceTypeDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceTypeOK creates a DescribeDeviceTypeOK with default headers values +func NewDescribeDeviceTypeOK() *DescribeDeviceTypeOK { + return &DescribeDeviceTypeOK{} +} + +/* DescribeDeviceTypeOK describes a response with status code 200, with default header values. + +DescribeDeviceTypeOK describe device type o k +*/ +type DescribeDeviceTypeOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeOKBody +} + +// IsSuccess returns true when this describe device type o k response has a 2xx status code +func (o *DescribeDeviceTypeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device type o k response has a 3xx status code +func (o *DescribeDeviceTypeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device type o k response has a 4xx status code +func (o *DescribeDeviceTypeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device type o k response has a 5xx status code +func (o *DescribeDeviceTypeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device type o k response a status code equal to that given +func (o *DescribeDeviceTypeOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceTypeOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}][%d] describeDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeOK) String() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}][%d] describeDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeOK) GetPayload() *DescribeDeviceTypeOKBody { + return o.Payload +} + +func (o *DescribeDeviceTypeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceTypeDefault creates a DescribeDeviceTypeDefault with default headers values +func NewDescribeDeviceTypeDefault(code int) *DescribeDeviceTypeDefault { + return &DescribeDeviceTypeDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceTypeDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceTypeDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeDefaultBody +} + +// Code gets the status code for the describe device type default response +func (o *DescribeDeviceTypeDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device type default response has a 2xx status code +func (o *DescribeDeviceTypeDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device type default response has a 3xx status code +func (o *DescribeDeviceTypeDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device type default response has a 4xx status code +func (o *DescribeDeviceTypeDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device type default response has a 5xx status code +func (o *DescribeDeviceTypeDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device type default response a status code equal to that given +func (o *DescribeDeviceTypeDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceTypeDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}][%d] describeDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}][%d] describeDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeDefault) GetPayload() *DescribeDeviceTypeDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceTypeDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceTypeDefaultBody describe device type default body +swagger:model DescribeDeviceTypeDefaultBody +*/ +type DescribeDeviceTypeDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device type default body +func (o *DescribeDeviceTypeDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceType default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceTypeDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceType default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type default body based on the context it is used +func (o *DescribeDeviceTypeDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceTypeOKBody describe device type o k body +swagger:model DescribeDeviceTypeOKBody +*/ +type DescribeDeviceTypeOKBody struct { + + // result + Result *models.DeviceTypeInfo `json:"result,omitempty"` +} + +// Validate validates this describe device type o k body +func (o *DescribeDeviceTypeOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type o k body based on the context it is used +func (o *DescribeDeviceTypeOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_types_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_types_parameters.go new file mode 100644 index 0000000..515c3d8 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_types_parameters.go @@ -0,0 +1,495 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeDeviceTypesParams creates a new DescribeDeviceTypesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceTypesParams() *DescribeDeviceTypesParams { + return &DescribeDeviceTypesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceTypesParamsWithTimeout creates a new DescribeDeviceTypesParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceTypesParamsWithTimeout(timeout time.Duration) *DescribeDeviceTypesParams { + return &DescribeDeviceTypesParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceTypesParamsWithContext creates a new DescribeDeviceTypesParams object +// with the ability to set a context for a request. +func NewDescribeDeviceTypesParamsWithContext(ctx context.Context) *DescribeDeviceTypesParams { + return &DescribeDeviceTypesParams{ + Context: ctx, + } +} + +// NewDescribeDeviceTypesParamsWithHTTPClient creates a new DescribeDeviceTypesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceTypesParamsWithHTTPClient(client *http.Client) *DescribeDeviceTypesParams { + return &DescribeDeviceTypesParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceTypesParams contains all the parameters to send to the API endpoint + for the describe device types operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceTypesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceSeries. + + 机型类型 + */ + DeviceSeries *string + + /* DeviceType. + + 机型规格 + */ + DeviceType *string + + /* DeviceTypeID. + + 机型id + */ + DeviceTypeID *string + + /* IdcID. + + 机房id + */ + IdcID *string + + // IsAll. + IsAll *string + + /* Name. + + 机型名称 + */ + Name *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypesParams) WithDefaults() *DescribeDeviceTypesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device types params +func (o *DescribeDeviceTypesParams) WithTimeout(timeout time.Duration) *DescribeDeviceTypesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device types params +func (o *DescribeDeviceTypesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device types params +func (o *DescribeDeviceTypesParams) WithContext(ctx context.Context) *DescribeDeviceTypesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device types params +func (o *DescribeDeviceTypesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device types params +func (o *DescribeDeviceTypesParams) WithHTTPClient(client *http.Client) *DescribeDeviceTypesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device types params +func (o *DescribeDeviceTypesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device types params +func (o *DescribeDeviceTypesParams) WithAuthorization(authorization string) *DescribeDeviceTypesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device types params +func (o *DescribeDeviceTypesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device types params +func (o *DescribeDeviceTypesParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceTypesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device types params +func (o *DescribeDeviceTypesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device types params +func (o *DescribeDeviceTypesParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceTypesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device types params +func (o *DescribeDeviceTypesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceSeries adds the deviceSeries to the describe device types params +func (o *DescribeDeviceTypesParams) WithDeviceSeries(deviceSeries *string) *DescribeDeviceTypesParams { + o.SetDeviceSeries(deviceSeries) + return o +} + +// SetDeviceSeries adds the deviceSeries to the describe device types params +func (o *DescribeDeviceTypesParams) SetDeviceSeries(deviceSeries *string) { + o.DeviceSeries = deviceSeries +} + +// WithDeviceType adds the deviceType to the describe device types params +func (o *DescribeDeviceTypesParams) WithDeviceType(deviceType *string) *DescribeDeviceTypesParams { + o.SetDeviceType(deviceType) + return o +} + +// SetDeviceType adds the deviceType to the describe device types params +func (o *DescribeDeviceTypesParams) SetDeviceType(deviceType *string) { + o.DeviceType = deviceType +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device types params +func (o *DescribeDeviceTypesParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDeviceTypesParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device types params +func (o *DescribeDeviceTypesParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithIdcID adds the idcID to the describe device types params +func (o *DescribeDeviceTypesParams) WithIdcID(idcID *string) *DescribeDeviceTypesParams { + o.SetIdcID(idcID) + return o +} + +// SetIdcID adds the idcId to the describe device types params +func (o *DescribeDeviceTypesParams) SetIdcID(idcID *string) { + o.IdcID = idcID +} + +// WithIsAll adds the isAll to the describe device types params +func (o *DescribeDeviceTypesParams) WithIsAll(isAll *string) *DescribeDeviceTypesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe device types params +func (o *DescribeDeviceTypesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithName adds the name to the describe device types params +func (o *DescribeDeviceTypesParams) WithName(name *string) *DescribeDeviceTypesParams { + o.SetName(name) + return o +} + +// SetName adds the name to the describe device types params +func (o *DescribeDeviceTypesParams) SetName(name *string) { + o.Name = name +} + +// WithPageNumber adds the pageNumber to the describe device types params +func (o *DescribeDeviceTypesParams) WithPageNumber(pageNumber *int64) *DescribeDeviceTypesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe device types params +func (o *DescribeDeviceTypesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe device types params +func (o *DescribeDeviceTypesParams) WithPageSize(pageSize *int64) *DescribeDeviceTypesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe device types params +func (o *DescribeDeviceTypesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe device types params +func (o *DescribeDeviceTypesParams) WithTraceID(traceID string) *DescribeDeviceTypesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device types params +func (o *DescribeDeviceTypesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceTypesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceSeries != nil { + + // query param deviceSeries + var qrDeviceSeries string + + if o.DeviceSeries != nil { + qrDeviceSeries = *o.DeviceSeries + } + qDeviceSeries := qrDeviceSeries + if qDeviceSeries != "" { + + if err := r.SetQueryParam("deviceSeries", qDeviceSeries); err != nil { + return err + } + } + } + + if o.DeviceType != nil { + + // query param deviceType + var qrDeviceType string + + if o.DeviceType != nil { + qrDeviceType = *o.DeviceType + } + qDeviceType := qrDeviceType + if qDeviceType != "" { + + if err := r.SetQueryParam("deviceType", qDeviceType); err != nil { + return err + } + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.IdcID != nil { + + // query param idcId + var qrIdcID string + + if o.IdcID != nil { + qrIdcID = *o.IdcID + } + qIdcID := qrIdcID + if qIdcID != "" { + + if err := r.SetQueryParam("idcId", qIdcID); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_types_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_types_responses.go new file mode 100644 index 0000000..4a6d708 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_device_types_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeDeviceTypesReader is a Reader for the DescribeDeviceTypes structure. +type DescribeDeviceTypesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceTypesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceTypesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceTypesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceTypesOK creates a DescribeDeviceTypesOK with default headers values +func NewDescribeDeviceTypesOK() *DescribeDeviceTypesOK { + return &DescribeDeviceTypesOK{} +} + +/* DescribeDeviceTypesOK describes a response with status code 200, with default header values. + +DescribeDeviceTypesOK describe device types o k +*/ +type DescribeDeviceTypesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypesOKBody +} + +// IsSuccess returns true when this describe device types o k response has a 2xx status code +func (o *DescribeDeviceTypesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device types o k response has a 3xx status code +func (o *DescribeDeviceTypesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device types o k response has a 4xx status code +func (o *DescribeDeviceTypesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device types o k response has a 5xx status code +func (o *DescribeDeviceTypesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device types o k response a status code equal to that given +func (o *DescribeDeviceTypesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceTypesOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes][%d] describeDeviceTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypesOK) String() string { + return fmt.Sprintf("[GET /deviceTypes][%d] describeDeviceTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypesOK) GetPayload() *DescribeDeviceTypesOKBody { + return o.Payload +} + +func (o *DescribeDeviceTypesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceTypesDefault creates a DescribeDeviceTypesDefault with default headers values +func NewDescribeDeviceTypesDefault(code int) *DescribeDeviceTypesDefault { + return &DescribeDeviceTypesDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceTypesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceTypesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypesDefaultBody +} + +// Code gets the status code for the describe device types default response +func (o *DescribeDeviceTypesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device types default response has a 2xx status code +func (o *DescribeDeviceTypesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device types default response has a 3xx status code +func (o *DescribeDeviceTypesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device types default response has a 4xx status code +func (o *DescribeDeviceTypesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device types default response has a 5xx status code +func (o *DescribeDeviceTypesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device types default response a status code equal to that given +func (o *DescribeDeviceTypesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceTypesDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes][%d] describeDeviceTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypesDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes][%d] describeDeviceTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypesDefault) GetPayload() *DescribeDeviceTypesDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceTypesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceTypesDefaultBody describe device types default body +swagger:model DescribeDeviceTypesDefaultBody +*/ +type DescribeDeviceTypesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device types default body +func (o *DescribeDeviceTypesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypes default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceTypesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypes default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device types default body based on the context it is used +func (o *DescribeDeviceTypesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceTypesOKBody describe device types o k body +swagger:model DescribeDeviceTypesOKBody +*/ +type DescribeDeviceTypesOKBody struct { + + // result + Result *models.DeviceTypeList `json:"result,omitempty"` +} + +// Validate validates this describe device types o k body +func (o *DescribeDeviceTypesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device types o k body based on the context it is used +func (o *DescribeDeviceTypesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_volumes_raids_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_volumes_raids_parameters.go new file mode 100644 index 0000000..8f6b00c --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_volumes_raids_parameters.go @@ -0,0 +1,323 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeVolumesRaidsParams creates a new DescribeVolumesRaidsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeVolumesRaidsParams() *DescribeVolumesRaidsParams { + return &DescribeVolumesRaidsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeVolumesRaidsParamsWithTimeout creates a new DescribeVolumesRaidsParams object +// with the ability to set a timeout on a request. +func NewDescribeVolumesRaidsParamsWithTimeout(timeout time.Duration) *DescribeVolumesRaidsParams { + return &DescribeVolumesRaidsParams{ + timeout: timeout, + } +} + +// NewDescribeVolumesRaidsParamsWithContext creates a new DescribeVolumesRaidsParams object +// with the ability to set a context for a request. +func NewDescribeVolumesRaidsParamsWithContext(ctx context.Context) *DescribeVolumesRaidsParams { + return &DescribeVolumesRaidsParams{ + Context: ctx, + } +} + +// NewDescribeVolumesRaidsParamsWithHTTPClient creates a new DescribeVolumesRaidsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeVolumesRaidsParamsWithHTTPClient(client *http.Client) *DescribeVolumesRaidsParams { + return &DescribeVolumesRaidsParams{ + HTTPClient: client, + } +} + +/* DescribeVolumesRaidsParams contains all the parameters to send to the API endpoint + for the describe volumes raids operation. + + Typically these are written to a http.Request. +*/ +type DescribeVolumesRaidsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceTypeID. + + 机型id + */ + DeviceTypeID *string + + /* IsAll. + + 是否显示所有 + */ + IsAll *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* VolumeType. + + 系统盘还是数据盘 + */ + VolumeType *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe volumes raids params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeVolumesRaidsParams) WithDefaults() *DescribeVolumesRaidsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe volumes raids params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeVolumesRaidsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) WithTimeout(timeout time.Duration) *DescribeVolumesRaidsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) WithContext(ctx context.Context) *DescribeVolumesRaidsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) WithHTTPClient(client *http.Client) *DescribeVolumesRaidsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) WithAuthorization(authorization string) *DescribeVolumesRaidsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) WithBmpLanguage(bmpLanguage *string) *DescribeVolumesRaidsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) WithBmpUserID(bmpUserID *string) *DescribeVolumesRaidsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) WithDeviceTypeID(deviceTypeID *string) *DescribeVolumesRaidsParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithIsAll adds the isAll to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) WithIsAll(isAll *string) *DescribeVolumesRaidsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithTraceID adds the traceID to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) WithTraceID(traceID string) *DescribeVolumesRaidsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithVolumeType adds the volumeType to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) WithVolumeType(volumeType *string) *DescribeVolumesRaidsParams { + o.SetVolumeType(volumeType) + return o +} + +// SetVolumeType adds the volumeType to the describe volumes raids params +func (o *DescribeVolumesRaidsParams) SetVolumeType(volumeType *string) { + o.VolumeType = volumeType +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeVolumesRaidsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.VolumeType != nil { + + // query param volumeType + var qrVolumeType string + + if o.VolumeType != nil { + qrVolumeType = *o.VolumeType + } + qVolumeType := qrVolumeType + if qVolumeType != "" { + + if err := r.SetQueryParam("volumeType", qVolumeType); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_volumes_raids_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_volumes_raids_responses.go new file mode 100644 index 0000000..3b66669 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/describe_volumes_raids_responses.go @@ -0,0 +1,415 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeVolumesRaidsReader is a Reader for the DescribeVolumesRaids structure. +type DescribeVolumesRaidsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeVolumesRaidsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeVolumesRaidsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeVolumesRaidsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeVolumesRaidsOK creates a DescribeVolumesRaidsOK with default headers values +func NewDescribeVolumesRaidsOK() *DescribeVolumesRaidsOK { + return &DescribeVolumesRaidsOK{} +} + +/* DescribeVolumesRaidsOK describes a response with status code 200, with default header values. + +DescribeVolumesRaidsOK describe volumes raids o k +*/ +type DescribeVolumesRaidsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeVolumesRaidsOKBody +} + +// IsSuccess returns true when this describe volumes raids o k response has a 2xx status code +func (o *DescribeVolumesRaidsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe volumes raids o k response has a 3xx status code +func (o *DescribeVolumesRaidsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe volumes raids o k response has a 4xx status code +func (o *DescribeVolumesRaidsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe volumes raids o k response has a 5xx status code +func (o *DescribeVolumesRaidsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe volumes raids o k response a status code equal to that given +func (o *DescribeVolumesRaidsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeVolumesRaidsOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes/volumesRaids][%d] describeVolumesRaidsOK %+v", 200, o.Payload) +} + +func (o *DescribeVolumesRaidsOK) String() string { + return fmt.Sprintf("[GET /deviceTypes/volumesRaids][%d] describeVolumesRaidsOK %+v", 200, o.Payload) +} + +func (o *DescribeVolumesRaidsOK) GetPayload() *DescribeVolumesRaidsOKBody { + return o.Payload +} + +func (o *DescribeVolumesRaidsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeVolumesRaidsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeVolumesRaidsDefault creates a DescribeVolumesRaidsDefault with default headers values +func NewDescribeVolumesRaidsDefault(code int) *DescribeVolumesRaidsDefault { + return &DescribeVolumesRaidsDefault{ + _statusCode: code, + } +} + +/* DescribeVolumesRaidsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeVolumesRaidsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeVolumesRaidsDefaultBody +} + +// Code gets the status code for the describe volumes raids default response +func (o *DescribeVolumesRaidsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe volumes raids default response has a 2xx status code +func (o *DescribeVolumesRaidsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe volumes raids default response has a 3xx status code +func (o *DescribeVolumesRaidsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe volumes raids default response has a 4xx status code +func (o *DescribeVolumesRaidsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe volumes raids default response has a 5xx status code +func (o *DescribeVolumesRaidsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe volumes raids default response a status code equal to that given +func (o *DescribeVolumesRaidsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeVolumesRaidsDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes/volumesRaids][%d] describeVolumesRaids default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeVolumesRaidsDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes/volumesRaids][%d] describeVolumesRaids default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeVolumesRaidsDefault) GetPayload() *DescribeVolumesRaidsDefaultBody { + return o.Payload +} + +func (o *DescribeVolumesRaidsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeVolumesRaidsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeVolumesRaidsDefaultBody describe volumes raids default body +swagger:model DescribeVolumesRaidsDefaultBody +*/ +type DescribeVolumesRaidsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe volumes raids default body +func (o *DescribeVolumesRaidsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeVolumesRaidsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeVolumesRaids default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeVolumesRaidsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeVolumesRaids default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeVolumesRaids default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeVolumesRaids default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe volumes raids default body based on the context it is used +func (o *DescribeVolumesRaidsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeVolumesRaidsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeVolumesRaids default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeVolumesRaids default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeVolumesRaidsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeVolumesRaidsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeVolumesRaidsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeVolumesRaidsOKBody describe volumes raids o k body +swagger:model DescribeVolumesRaidsOKBody +*/ +type DescribeVolumesRaidsOKBody struct { + + // result + Result []*models.VolumeRaids `json:"result"` +} + +// Validate validates this describe volumes raids o k body +func (o *DescribeVolumesRaidsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeVolumesRaidsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + for i := 0; i < len(o.Result); i++ { + if swag.IsZero(o.Result[i]) { // not required + continue + } + + if o.Result[i] != nil { + if err := o.Result[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeVolumesRaidsOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeVolumesRaidsOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this describe volumes raids o k body based on the context it is used +func (o *DescribeVolumesRaidsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeVolumesRaidsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Result); i++ { + + if o.Result[i] != nil { + if err := o.Result[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeVolumesRaidsOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeVolumesRaidsOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeVolumesRaidsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeVolumesRaidsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeVolumesRaidsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/device_type_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/device_type_client.go new file mode 100644 index 0000000..50b9e88 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/device_type/device_type_client.go @@ -0,0 +1,237 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new device type API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for device type API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DescribeDeviceType(params *DescribeDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeOK, error) + + DescribeDeviceTypeImagePartitions(params *DescribeDeviceTypeImagePartitionsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeImagePartitionsOK, error) + + DescribeDeviceTypeImages(params *DescribeDeviceTypeImagesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeImagesOK, error) + + DescribeDeviceTypes(params *DescribeDeviceTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypesOK, error) + + DescribeVolumesRaids(params *DescribeVolumesRaidsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeVolumesRaidsOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DescribeDeviceType DescribeDeviceType 获取机型详情 +*/ +func (a *Client) DescribeDeviceType(params *DescribeDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceTypeParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceType", + Method: "GET", + PathPattern: "/deviceTypes/{device_type_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceTypeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceTypeOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceTypeDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceTypeImagePartitions QueryDeviceTypeImagePartition 根据机型,镜像,获取分区 +*/ +func (a *Client) DescribeDeviceTypeImagePartitions(params *DescribeDeviceTypeImagePartitionsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeImagePartitionsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceTypeImagePartitionsParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceTypeImagePartitions", + Method: "GET", + PathPattern: "/deviceTypes/deviceTypeImagePartition", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceTypeImagePartitionsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceTypeImagePartitionsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceTypeImagePartitionsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceTypeImages QueryDeviceTypeImage 根据机型获取镜像 +*/ +func (a *Client) DescribeDeviceTypeImages(params *DescribeDeviceTypeImagesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeImagesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceTypeImagesParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceTypeImages", + Method: "GET", + PathPattern: "/deviceTypes/deviceTypeImage", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceTypeImagesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceTypeImagesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceTypeImagesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceTypes DescribeDeviceTypes 获取机型列表 +*/ +func (a *Client) DescribeDeviceTypes(params *DescribeDeviceTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceTypesParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceTypes", + Method: "GET", + PathPattern: "/deviceTypes", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceTypesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceTypesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceTypesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeVolumesRaids DescribeVolumesRaids 根据机型获取卷和raid信息 (deviceTypeRaid->volumesRaids) +*/ +func (a *Client) DescribeVolumesRaids(params *DescribeVolumesRaidsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeVolumesRaidsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeVolumesRaidsParams() + } + op := &runtime.ClientOperation{ + ID: "describeVolumesRaids", + Method: "GET", + PathPattern: "/deviceTypes/volumesRaids", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeVolumesRaidsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeVolumesRaidsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeVolumesRaidsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/idc/describe_idc_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/idc/describe_idc_parameters.go new file mode 100644 index 0000000..8a6fc34 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/idc/describe_idc_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeIdcParams creates a new DescribeIdcParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeIdcParams() *DescribeIdcParams { + return &DescribeIdcParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeIdcParamsWithTimeout creates a new DescribeIdcParams object +// with the ability to set a timeout on a request. +func NewDescribeIdcParamsWithTimeout(timeout time.Duration) *DescribeIdcParams { + return &DescribeIdcParams{ + timeout: timeout, + } +} + +// NewDescribeIdcParamsWithContext creates a new DescribeIdcParams object +// with the ability to set a context for a request. +func NewDescribeIdcParamsWithContext(ctx context.Context) *DescribeIdcParams { + return &DescribeIdcParams{ + Context: ctx, + } +} + +// NewDescribeIdcParamsWithHTTPClient creates a new DescribeIdcParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeIdcParamsWithHTTPClient(client *http.Client) *DescribeIdcParams { + return &DescribeIdcParams{ + HTTPClient: client, + } +} + +/* DescribeIdcParams contains all the parameters to send to the API endpoint + for the describe idc operation. + + Typically these are written to a http.Request. +*/ +type DescribeIdcParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // IdcID. + IdcID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeIdcParams) WithDefaults() *DescribeIdcParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeIdcParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe idc params +func (o *DescribeIdcParams) WithTimeout(timeout time.Duration) *DescribeIdcParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe idc params +func (o *DescribeIdcParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe idc params +func (o *DescribeIdcParams) WithContext(ctx context.Context) *DescribeIdcParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe idc params +func (o *DescribeIdcParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe idc params +func (o *DescribeIdcParams) WithHTTPClient(client *http.Client) *DescribeIdcParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe idc params +func (o *DescribeIdcParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe idc params +func (o *DescribeIdcParams) WithAuthorization(authorization string) *DescribeIdcParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe idc params +func (o *DescribeIdcParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe idc params +func (o *DescribeIdcParams) WithBmpLanguage(bmpLanguage *string) *DescribeIdcParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe idc params +func (o *DescribeIdcParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe idc params +func (o *DescribeIdcParams) WithBmpUserID(bmpUserID *string) *DescribeIdcParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe idc params +func (o *DescribeIdcParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIdcID adds the idcID to the describe idc params +func (o *DescribeIdcParams) WithIdcID(idcID string) *DescribeIdcParams { + o.SetIdcID(idcID) + return o +} + +// SetIdcID adds the idcId to the describe idc params +func (o *DescribeIdcParams) SetIdcID(idcID string) { + o.IdcID = idcID +} + +// WithTraceID adds the traceID to the describe idc params +func (o *DescribeIdcParams) WithTraceID(traceID string) *DescribeIdcParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe idc params +func (o *DescribeIdcParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeIdcParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param idc_id + if err := r.SetPathParam("idc_id", o.IdcID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/idc/describe_idc_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/idc/describe_idc_responses.go new file mode 100644 index 0000000..f78b984 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/idc/describe_idc_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeIdcReader is a Reader for the DescribeIdc structure. +type DescribeIdcReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeIdcReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeIdcOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeIdcDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeIdcOK creates a DescribeIdcOK with default headers values +func NewDescribeIdcOK() *DescribeIdcOK { + return &DescribeIdcOK{} +} + +/* DescribeIdcOK describes a response with status code 200, with default header values. + +A DescribeIdcResult is an response struct that is used to describe idc. +*/ +type DescribeIdcOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeIdcOKBody +} + +// IsSuccess returns true when this describe idc o k response has a 2xx status code +func (o *DescribeIdcOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe idc o k response has a 3xx status code +func (o *DescribeIdcOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe idc o k response has a 4xx status code +func (o *DescribeIdcOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe idc o k response has a 5xx status code +func (o *DescribeIdcOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe idc o k response a status code equal to that given +func (o *DescribeIdcOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeIdcOK) Error() string { + return fmt.Sprintf("[GET /idcs/{idc_id}][%d] describeIdcOK %+v", 200, o.Payload) +} + +func (o *DescribeIdcOK) String() string { + return fmt.Sprintf("[GET /idcs/{idc_id}][%d] describeIdcOK %+v", 200, o.Payload) +} + +func (o *DescribeIdcOK) GetPayload() *DescribeIdcOKBody { + return o.Payload +} + +func (o *DescribeIdcOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeIdcOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeIdcDefault creates a DescribeIdcDefault with default headers values +func NewDescribeIdcDefault(code int) *DescribeIdcDefault { + return &DescribeIdcDefault{ + _statusCode: code, + } +} + +/* DescribeIdcDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeIdcDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeIdcDefaultBody +} + +// Code gets the status code for the describe idc default response +func (o *DescribeIdcDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe idc default response has a 2xx status code +func (o *DescribeIdcDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe idc default response has a 3xx status code +func (o *DescribeIdcDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe idc default response has a 4xx status code +func (o *DescribeIdcDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe idc default response has a 5xx status code +func (o *DescribeIdcDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe idc default response a status code equal to that given +func (o *DescribeIdcDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeIdcDefault) Error() string { + return fmt.Sprintf("[GET /idcs/{idc_id}][%d] describeIdc default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeIdcDefault) String() string { + return fmt.Sprintf("[GET /idcs/{idc_id}][%d] describeIdc default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeIdcDefault) GetPayload() *DescribeIdcDefaultBody { + return o.Payload +} + +func (o *DescribeIdcDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeIdcDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeIdcDefaultBody describe idc default body +swagger:model DescribeIdcDefaultBody +*/ +type DescribeIdcDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe idc default body +func (o *DescribeIdcDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeIdc default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeIdcDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeIdc default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe idc default body based on the context it is used +func (o *DescribeIdcDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeIdcDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeIdcDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeIdcDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeIdcOKBody describe idc o k body +swagger:model DescribeIdcOKBody +*/ +type DescribeIdcOKBody struct { + + // result + Result *models.IdcInfo `json:"result,omitempty"` +} + +// Validate validates this describe idc o k body +func (o *DescribeIdcOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe idc o k body based on the context it is used +func (o *DescribeIdcOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeIdcOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeIdcOKBody) UnmarshalBinary(b []byte) error { + var res DescribeIdcOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/idc/describe_idcs_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/idc/describe_idcs_parameters.go new file mode 100644 index 0000000..b70ce2a --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/idc/describe_idcs_parameters.go @@ -0,0 +1,430 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeIdcsParams creates a new DescribeIdcsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeIdcsParams() *DescribeIdcsParams { + return &DescribeIdcsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeIdcsParamsWithTimeout creates a new DescribeIdcsParams object +// with the ability to set a timeout on a request. +func NewDescribeIdcsParamsWithTimeout(timeout time.Duration) *DescribeIdcsParams { + return &DescribeIdcsParams{ + timeout: timeout, + } +} + +// NewDescribeIdcsParamsWithContext creates a new DescribeIdcsParams object +// with the ability to set a context for a request. +func NewDescribeIdcsParamsWithContext(ctx context.Context) *DescribeIdcsParams { + return &DescribeIdcsParams{ + Context: ctx, + } +} + +// NewDescribeIdcsParamsWithHTTPClient creates a new DescribeIdcsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeIdcsParamsWithHTTPClient(client *http.Client) *DescribeIdcsParams { + return &DescribeIdcsParams{ + HTTPClient: client, + } +} + +/* DescribeIdcsParams contains all the parameters to send to the API endpoint + for the describe idcs operation. + + Typically these are written to a http.Request. +*/ +type DescribeIdcsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否显示所有 + */ + IsAll *string + + /* Level. + + 机房等级 + */ + Level *string + + /* Name. + + 机房名称 + */ + Name *string + + /* NameEn. + + 机房英文名称 + */ + NameEn *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe idcs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeIdcsParams) WithDefaults() *DescribeIdcsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe idcs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeIdcsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe idcs params +func (o *DescribeIdcsParams) WithTimeout(timeout time.Duration) *DescribeIdcsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe idcs params +func (o *DescribeIdcsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe idcs params +func (o *DescribeIdcsParams) WithContext(ctx context.Context) *DescribeIdcsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe idcs params +func (o *DescribeIdcsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe idcs params +func (o *DescribeIdcsParams) WithHTTPClient(client *http.Client) *DescribeIdcsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe idcs params +func (o *DescribeIdcsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe idcs params +func (o *DescribeIdcsParams) WithAuthorization(authorization string) *DescribeIdcsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe idcs params +func (o *DescribeIdcsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe idcs params +func (o *DescribeIdcsParams) WithBmpLanguage(bmpLanguage *string) *DescribeIdcsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe idcs params +func (o *DescribeIdcsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe idcs params +func (o *DescribeIdcsParams) WithBmpUserID(bmpUserID *string) *DescribeIdcsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe idcs params +func (o *DescribeIdcsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe idcs params +func (o *DescribeIdcsParams) WithIsAll(isAll *string) *DescribeIdcsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe idcs params +func (o *DescribeIdcsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithLevel adds the level to the describe idcs params +func (o *DescribeIdcsParams) WithLevel(level *string) *DescribeIdcsParams { + o.SetLevel(level) + return o +} + +// SetLevel adds the level to the describe idcs params +func (o *DescribeIdcsParams) SetLevel(level *string) { + o.Level = level +} + +// WithName adds the name to the describe idcs params +func (o *DescribeIdcsParams) WithName(name *string) *DescribeIdcsParams { + o.SetName(name) + return o +} + +// SetName adds the name to the describe idcs params +func (o *DescribeIdcsParams) SetName(name *string) { + o.Name = name +} + +// WithNameEn adds the nameEn to the describe idcs params +func (o *DescribeIdcsParams) WithNameEn(nameEn *string) *DescribeIdcsParams { + o.SetNameEn(nameEn) + return o +} + +// SetNameEn adds the nameEn to the describe idcs params +func (o *DescribeIdcsParams) SetNameEn(nameEn *string) { + o.NameEn = nameEn +} + +// WithPageNumber adds the pageNumber to the describe idcs params +func (o *DescribeIdcsParams) WithPageNumber(pageNumber *int64) *DescribeIdcsParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe idcs params +func (o *DescribeIdcsParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe idcs params +func (o *DescribeIdcsParams) WithPageSize(pageSize *int64) *DescribeIdcsParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe idcs params +func (o *DescribeIdcsParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe idcs params +func (o *DescribeIdcsParams) WithTraceID(traceID string) *DescribeIdcsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe idcs params +func (o *DescribeIdcsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeIdcsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Level != nil { + + // query param level + var qrLevel string + + if o.Level != nil { + qrLevel = *o.Level + } + qLevel := qrLevel + if qLevel != "" { + + if err := r.SetQueryParam("level", qLevel); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.NameEn != nil { + + // query param nameEn + var qrNameEn string + + if o.NameEn != nil { + qrNameEn = *o.NameEn + } + qNameEn := qrNameEn + if qNameEn != "" { + + if err := r.SetQueryParam("nameEn", qNameEn); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/idc/describe_idcs_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/idc/describe_idcs_responses.go new file mode 100644 index 0000000..4fde06e --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/idc/describe_idcs_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeIdcsReader is a Reader for the DescribeIdcs structure. +type DescribeIdcsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeIdcsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeIdcsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeIdcsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeIdcsOK creates a DescribeIdcsOK with default headers values +func NewDescribeIdcsOK() *DescribeIdcsOK { + return &DescribeIdcsOK{} +} + +/* DescribeIdcsOK describes a response with status code 200, with default header values. + +A DescribIdcsResult is an response struct that is used to describe idcs. +*/ +type DescribeIdcsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeIdcsOKBody +} + +// IsSuccess returns true when this describe idcs o k response has a 2xx status code +func (o *DescribeIdcsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe idcs o k response has a 3xx status code +func (o *DescribeIdcsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe idcs o k response has a 4xx status code +func (o *DescribeIdcsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe idcs o k response has a 5xx status code +func (o *DescribeIdcsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe idcs o k response a status code equal to that given +func (o *DescribeIdcsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeIdcsOK) Error() string { + return fmt.Sprintf("[GET /idcs][%d] describeIdcsOK %+v", 200, o.Payload) +} + +func (o *DescribeIdcsOK) String() string { + return fmt.Sprintf("[GET /idcs][%d] describeIdcsOK %+v", 200, o.Payload) +} + +func (o *DescribeIdcsOK) GetPayload() *DescribeIdcsOKBody { + return o.Payload +} + +func (o *DescribeIdcsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeIdcsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeIdcsDefault creates a DescribeIdcsDefault with default headers values +func NewDescribeIdcsDefault(code int) *DescribeIdcsDefault { + return &DescribeIdcsDefault{ + _statusCode: code, + } +} + +/* DescribeIdcsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeIdcsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeIdcsDefaultBody +} + +// Code gets the status code for the describe idcs default response +func (o *DescribeIdcsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe idcs default response has a 2xx status code +func (o *DescribeIdcsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe idcs default response has a 3xx status code +func (o *DescribeIdcsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe idcs default response has a 4xx status code +func (o *DescribeIdcsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe idcs default response has a 5xx status code +func (o *DescribeIdcsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe idcs default response a status code equal to that given +func (o *DescribeIdcsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeIdcsDefault) Error() string { + return fmt.Sprintf("[GET /idcs][%d] describeIdcs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeIdcsDefault) String() string { + return fmt.Sprintf("[GET /idcs][%d] describeIdcs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeIdcsDefault) GetPayload() *DescribeIdcsDefaultBody { + return o.Payload +} + +func (o *DescribeIdcsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeIdcsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeIdcsDefaultBody describe idcs default body +swagger:model DescribeIdcsDefaultBody +*/ +type DescribeIdcsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe idcs default body +func (o *DescribeIdcsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeIdcs default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeIdcsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeIdcs default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcs default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe idcs default body based on the context it is used +func (o *DescribeIdcsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcs default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeIdcsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeIdcsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeIdcsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeIdcsOKBody describe idcs o k body +swagger:model DescribeIdcsOKBody +*/ +type DescribeIdcsOKBody struct { + + // result + Result *models.IdcList `json:"result,omitempty"` +} + +// Validate validates this describe idcs o k body +func (o *DescribeIdcsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe idcs o k body based on the context it is used +func (o *DescribeIdcsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeIdcsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeIdcsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeIdcsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/idc/idc_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/idc/idc_client.go new file mode 100644 index 0000000..8ff1eed --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/idc/idc_client.go @@ -0,0 +1,117 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new idc API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for idc API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DescribeIdc(params *DescribeIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeIdcOK, error) + + DescribeIdcs(params *DescribeIdcsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeIdcsOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DescribeIdc DescribeIdc 获取idc详情 +*/ +func (a *Client) DescribeIdc(params *DescribeIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeIdcOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeIdcParams() + } + op := &runtime.ClientOperation{ + ID: "describeIdc", + Method: "GET", + PathPattern: "/idcs/{idc_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeIdcReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeIdcOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeIdcDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeIdcs DescribeIdcs 获取idc列表 +*/ +func (a *Client) DescribeIdcs(params *DescribeIdcsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeIdcsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeIdcsParams() + } + op := &runtime.ClientOperation{ + ID: "describeIdcs", + Method: "GET", + PathPattern: "/idcs", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeIdcsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeIdcsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeIdcsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_image_device_types_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_image_device_types_parameters.go new file mode 100644 index 0000000..00dad00 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_image_device_types_parameters.go @@ -0,0 +1,423 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeImageDeviceTypesParams creates a new DescribeImageDeviceTypesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeImageDeviceTypesParams() *DescribeImageDeviceTypesParams { + return &DescribeImageDeviceTypesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeImageDeviceTypesParamsWithTimeout creates a new DescribeImageDeviceTypesParams object +// with the ability to set a timeout on a request. +func NewDescribeImageDeviceTypesParamsWithTimeout(timeout time.Duration) *DescribeImageDeviceTypesParams { + return &DescribeImageDeviceTypesParams{ + timeout: timeout, + } +} + +// NewDescribeImageDeviceTypesParamsWithContext creates a new DescribeImageDeviceTypesParams object +// with the ability to set a context for a request. +func NewDescribeImageDeviceTypesParamsWithContext(ctx context.Context) *DescribeImageDeviceTypesParams { + return &DescribeImageDeviceTypesParams{ + Context: ctx, + } +} + +// NewDescribeImageDeviceTypesParamsWithHTTPClient creates a new DescribeImageDeviceTypesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeImageDeviceTypesParamsWithHTTPClient(client *http.Client) *DescribeImageDeviceTypesParams { + return &DescribeImageDeviceTypesParams{ + HTTPClient: client, + } +} + +/* DescribeImageDeviceTypesParams contains all the parameters to send to the API endpoint + for the describe image device types operation. + + Typically these are written to a http.Request. +*/ +type DescribeImageDeviceTypesParams struct { + + /* Architecture. + + 体系架构 + */ + Architecture *string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* ImageID. + + 镜像ID + */ + ImageID string + + /* IsAll. + + 是否显示全部 + */ + IsAll *string + + /* IsBind. + + 镜像是否绑定了机型,0查询该镜像没有绑定的机型列表 1查询该镜像已经绑定了的机型列表 + */ + IsBind *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe image device types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImageDeviceTypesParams) WithDefaults() *DescribeImageDeviceTypesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe image device types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImageDeviceTypesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithTimeout(timeout time.Duration) *DescribeImageDeviceTypesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithContext(ctx context.Context) *DescribeImageDeviceTypesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithHTTPClient(client *http.Client) *DescribeImageDeviceTypesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithArchitecture adds the architecture to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithArchitecture(architecture *string) *DescribeImageDeviceTypesParams { + o.SetArchitecture(architecture) + return o +} + +// SetArchitecture adds the architecture to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetArchitecture(architecture *string) { + o.Architecture = architecture +} + +// WithAuthorization adds the authorization to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithAuthorization(authorization string) *DescribeImageDeviceTypesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithBmpLanguage(bmpLanguage *string) *DescribeImageDeviceTypesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithBmpUserID(bmpUserID *string) *DescribeImageDeviceTypesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithImageID adds the imageID to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithImageID(imageID string) *DescribeImageDeviceTypesParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetImageID(imageID string) { + o.ImageID = imageID +} + +// WithIsAll adds the isAll to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithIsAll(isAll *string) *DescribeImageDeviceTypesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithIsBind adds the isBind to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithIsBind(isBind *string) *DescribeImageDeviceTypesParams { + o.SetIsBind(isBind) + return o +} + +// SetIsBind adds the isBind to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetIsBind(isBind *string) { + o.IsBind = isBind +} + +// WithPageNumber adds the pageNumber to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithPageNumber(pageNumber *int64) *DescribeImageDeviceTypesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithPageSize(pageSize *int64) *DescribeImageDeviceTypesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithTraceID(traceID string) *DescribeImageDeviceTypesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeImageDeviceTypesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Architecture != nil { + + // query param architecture + var qrArchitecture string + + if o.Architecture != nil { + qrArchitecture = *o.Architecture + } + qArchitecture := qrArchitecture + if qArchitecture != "" { + + if err := r.SetQueryParam("architecture", qArchitecture); err != nil { + return err + } + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // query param imageId + qrImageID := o.ImageID + qImageID := qrImageID + if qImageID != "" { + + if err := r.SetQueryParam("imageId", qImageID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.IsBind != nil { + + // query param isBind + var qrIsBind string + + if o.IsBind != nil { + qrIsBind = *o.IsBind + } + qIsBind := qrIsBind + if qIsBind != "" { + + if err := r.SetQueryParam("isBind", qIsBind); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_image_device_types_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_image_device_types_responses.go new file mode 100644 index 0000000..637f5be --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_image_device_types_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeImageDeviceTypesReader is a Reader for the DescribeImageDeviceTypes structure. +type DescribeImageDeviceTypesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeImageDeviceTypesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeImageDeviceTypesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeImageDeviceTypesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeImageDeviceTypesOK creates a DescribeImageDeviceTypesOK with default headers values +func NewDescribeImageDeviceTypesOK() *DescribeImageDeviceTypesOK { + return &DescribeImageDeviceTypesOK{} +} + +/* DescribeImageDeviceTypesOK describes a response with status code 200, with default header values. + +DescribeImageDeviceTypesOK describe image device types o k +*/ +type DescribeImageDeviceTypesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImageDeviceTypesOKBody +} + +// IsSuccess returns true when this describe image device types o k response has a 2xx status code +func (o *DescribeImageDeviceTypesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe image device types o k response has a 3xx status code +func (o *DescribeImageDeviceTypesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe image device types o k response has a 4xx status code +func (o *DescribeImageDeviceTypesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe image device types o k response has a 5xx status code +func (o *DescribeImageDeviceTypesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe image device types o k response a status code equal to that given +func (o *DescribeImageDeviceTypesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeImageDeviceTypesOK) Error() string { + return fmt.Sprintf("[GET /images/imageDeviceTypes][%d] describeImageDeviceTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeImageDeviceTypesOK) String() string { + return fmt.Sprintf("[GET /images/imageDeviceTypes][%d] describeImageDeviceTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeImageDeviceTypesOK) GetPayload() *DescribeImageDeviceTypesOKBody { + return o.Payload +} + +func (o *DescribeImageDeviceTypesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImageDeviceTypesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeImageDeviceTypesDefault creates a DescribeImageDeviceTypesDefault with default headers values +func NewDescribeImageDeviceTypesDefault(code int) *DescribeImageDeviceTypesDefault { + return &DescribeImageDeviceTypesDefault{ + _statusCode: code, + } +} + +/* DescribeImageDeviceTypesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeImageDeviceTypesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImageDeviceTypesDefaultBody +} + +// Code gets the status code for the describe image device types default response +func (o *DescribeImageDeviceTypesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe image device types default response has a 2xx status code +func (o *DescribeImageDeviceTypesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe image device types default response has a 3xx status code +func (o *DescribeImageDeviceTypesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe image device types default response has a 4xx status code +func (o *DescribeImageDeviceTypesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe image device types default response has a 5xx status code +func (o *DescribeImageDeviceTypesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe image device types default response a status code equal to that given +func (o *DescribeImageDeviceTypesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeImageDeviceTypesDefault) Error() string { + return fmt.Sprintf("[GET /images/imageDeviceTypes][%d] describeImageDeviceTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImageDeviceTypesDefault) String() string { + return fmt.Sprintf("[GET /images/imageDeviceTypes][%d] describeImageDeviceTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImageDeviceTypesDefault) GetPayload() *DescribeImageDeviceTypesDefaultBody { + return o.Payload +} + +func (o *DescribeImageDeviceTypesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImageDeviceTypesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeImageDeviceTypesDefaultBody describe image device types default body +swagger:model DescribeImageDeviceTypesDefaultBody +*/ +type DescribeImageDeviceTypesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe image device types default body +func (o *DescribeImageDeviceTypesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDeviceTypesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeImageDeviceTypes default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeImageDeviceTypesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeImageDeviceTypes default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageDeviceTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageDeviceTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe image device types default body based on the context it is used +func (o *DescribeImageDeviceTypesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDeviceTypesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageDeviceTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageDeviceTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImageDeviceTypesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImageDeviceTypesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeImageDeviceTypesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeImageDeviceTypesOKBody describe image device types o k body +swagger:model DescribeImageDeviceTypesOKBody +*/ +type DescribeImageDeviceTypesOKBody struct { + + // result + Result *models.DeviceTypeList `json:"result,omitempty"` +} + +// Validate validates this describe image device types o k body +func (o *DescribeImageDeviceTypesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDeviceTypesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageDeviceTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageDeviceTypesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe image device types o k body based on the context it is used +func (o *DescribeImageDeviceTypesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDeviceTypesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageDeviceTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageDeviceTypesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImageDeviceTypesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImageDeviceTypesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeImageDeviceTypesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_image_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_image_parameters.go new file mode 100644 index 0000000..7057d4b --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_image_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeImageParams creates a new DescribeImageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeImageParams() *DescribeImageParams { + return &DescribeImageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeImageParamsWithTimeout creates a new DescribeImageParams object +// with the ability to set a timeout on a request. +func NewDescribeImageParamsWithTimeout(timeout time.Duration) *DescribeImageParams { + return &DescribeImageParams{ + timeout: timeout, + } +} + +// NewDescribeImageParamsWithContext creates a new DescribeImageParams object +// with the ability to set a context for a request. +func NewDescribeImageParamsWithContext(ctx context.Context) *DescribeImageParams { + return &DescribeImageParams{ + Context: ctx, + } +} + +// NewDescribeImageParamsWithHTTPClient creates a new DescribeImageParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeImageParamsWithHTTPClient(client *http.Client) *DescribeImageParams { + return &DescribeImageParams{ + HTTPClient: client, + } +} + +/* DescribeImageParams contains all the parameters to send to the API endpoint + for the describe image operation. + + Typically these are written to a http.Request. +*/ +type DescribeImageParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // ImageID. + ImageID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImageParams) WithDefaults() *DescribeImageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe image params +func (o *DescribeImageParams) WithTimeout(timeout time.Duration) *DescribeImageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe image params +func (o *DescribeImageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe image params +func (o *DescribeImageParams) WithContext(ctx context.Context) *DescribeImageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe image params +func (o *DescribeImageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe image params +func (o *DescribeImageParams) WithHTTPClient(client *http.Client) *DescribeImageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe image params +func (o *DescribeImageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe image params +func (o *DescribeImageParams) WithAuthorization(authorization string) *DescribeImageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe image params +func (o *DescribeImageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe image params +func (o *DescribeImageParams) WithBmpLanguage(bmpLanguage *string) *DescribeImageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe image params +func (o *DescribeImageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe image params +func (o *DescribeImageParams) WithBmpUserID(bmpUserID *string) *DescribeImageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe image params +func (o *DescribeImageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithImageID adds the imageID to the describe image params +func (o *DescribeImageParams) WithImageID(imageID string) *DescribeImageParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the describe image params +func (o *DescribeImageParams) SetImageID(imageID string) { + o.ImageID = imageID +} + +// WithTraceID adds the traceID to the describe image params +func (o *DescribeImageParams) WithTraceID(traceID string) *DescribeImageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe image params +func (o *DescribeImageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param image_id + if err := r.SetPathParam("image_id", o.ImageID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_image_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_image_responses.go new file mode 100644 index 0000000..4b43b6d --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_image_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeImageReader is a Reader for the DescribeImage structure. +type DescribeImageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeImageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeImageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeImageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeImageOK creates a DescribeImageOK with default headers values +func NewDescribeImageOK() *DescribeImageOK { + return &DescribeImageOK{} +} + +/* DescribeImageOK describes a response with status code 200, with default header values. + +A DescribeImageResult is an response struct that is used to describe image. +*/ +type DescribeImageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImageOKBody +} + +// IsSuccess returns true when this describe image o k response has a 2xx status code +func (o *DescribeImageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe image o k response has a 3xx status code +func (o *DescribeImageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe image o k response has a 4xx status code +func (o *DescribeImageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe image o k response has a 5xx status code +func (o *DescribeImageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe image o k response a status code equal to that given +func (o *DescribeImageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeImageOK) Error() string { + return fmt.Sprintf("[GET /images/{image_id}][%d] describeImageOK %+v", 200, o.Payload) +} + +func (o *DescribeImageOK) String() string { + return fmt.Sprintf("[GET /images/{image_id}][%d] describeImageOK %+v", 200, o.Payload) +} + +func (o *DescribeImageOK) GetPayload() *DescribeImageOKBody { + return o.Payload +} + +func (o *DescribeImageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeImageDefault creates a DescribeImageDefault with default headers values +func NewDescribeImageDefault(code int) *DescribeImageDefault { + return &DescribeImageDefault{ + _statusCode: code, + } +} + +/* DescribeImageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeImageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImageDefaultBody +} + +// Code gets the status code for the describe image default response +func (o *DescribeImageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe image default response has a 2xx status code +func (o *DescribeImageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe image default response has a 3xx status code +func (o *DescribeImageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe image default response has a 4xx status code +func (o *DescribeImageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe image default response has a 5xx status code +func (o *DescribeImageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe image default response a status code equal to that given +func (o *DescribeImageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeImageDefault) Error() string { + return fmt.Sprintf("[GET /images/{image_id}][%d] describeImage default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImageDefault) String() string { + return fmt.Sprintf("[GET /images/{image_id}][%d] describeImage default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImageDefault) GetPayload() *DescribeImageDefaultBody { + return o.Payload +} + +func (o *DescribeImageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeImageDefaultBody describe image default body +swagger:model DescribeImageDefaultBody +*/ +type DescribeImageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe image default body +func (o *DescribeImageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeImage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeImageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeImage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe image default body based on the context it is used +func (o *DescribeImageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImageDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeImageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeImageOKBody describe image o k body +swagger:model DescribeImageOKBody +*/ +type DescribeImageOKBody struct { + + // result + Result *models.ImageInfo `json:"result,omitempty"` +} + +// Validate validates this describe image o k body +func (o *DescribeImageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe image o k body based on the context it is used +func (o *DescribeImageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImageOKBody) UnmarshalBinary(b []byte) error { + var res DescribeImageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_images_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_images_parameters.go new file mode 100644 index 0000000..7e11911 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_images_parameters.go @@ -0,0 +1,645 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeImagesParams creates a new DescribeImagesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeImagesParams() *DescribeImagesParams { + return &DescribeImagesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeImagesParamsWithTimeout creates a new DescribeImagesParams object +// with the ability to set a timeout on a request. +func NewDescribeImagesParamsWithTimeout(timeout time.Duration) *DescribeImagesParams { + return &DescribeImagesParams{ + timeout: timeout, + } +} + +// NewDescribeImagesParamsWithContext creates a new DescribeImagesParams object +// with the ability to set a context for a request. +func NewDescribeImagesParamsWithContext(ctx context.Context) *DescribeImagesParams { + return &DescribeImagesParams{ + Context: ctx, + } +} + +// NewDescribeImagesParamsWithHTTPClient creates a new DescribeImagesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeImagesParamsWithHTTPClient(client *http.Client) *DescribeImagesParams { + return &DescribeImagesParams{ + HTTPClient: client, + } +} + +/* DescribeImagesParams contains all the parameters to send to the API endpoint + for the describe images operation. + + Typically these are written to a http.Request. +*/ +type DescribeImagesParams struct { + + /* Architecture. + + 体系架构 + */ + Architecture *string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceTypeID. + + 设备类型id + */ + DeviceTypeID *string + + /* ImageID. + + 镜像ID + */ + ImageID *string + + /* ImageIds. + + 镜像ID,数组,支持多个 + */ + ImageIDs []string + + /* ImageName. + + 镜像名称 + */ + ImageName *string + + /* IsAll. + + 是否显示全部 + */ + IsAll *string + + /* OsID. + + 操作系统ID + */ + OsID *string + + /* OsType. + + 操作系统平台 + */ + OsType *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* Source. + + 镜像类型,预置,自定义 + */ + Source *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* Version. + + 版本号 + */ + Version *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe images params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImagesParams) WithDefaults() *DescribeImagesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe images params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImagesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe images params +func (o *DescribeImagesParams) WithTimeout(timeout time.Duration) *DescribeImagesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe images params +func (o *DescribeImagesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe images params +func (o *DescribeImagesParams) WithContext(ctx context.Context) *DescribeImagesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe images params +func (o *DescribeImagesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe images params +func (o *DescribeImagesParams) WithHTTPClient(client *http.Client) *DescribeImagesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe images params +func (o *DescribeImagesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithArchitecture adds the architecture to the describe images params +func (o *DescribeImagesParams) WithArchitecture(architecture *string) *DescribeImagesParams { + o.SetArchitecture(architecture) + return o +} + +// SetArchitecture adds the architecture to the describe images params +func (o *DescribeImagesParams) SetArchitecture(architecture *string) { + o.Architecture = architecture +} + +// WithAuthorization adds the authorization to the describe images params +func (o *DescribeImagesParams) WithAuthorization(authorization string) *DescribeImagesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe images params +func (o *DescribeImagesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe images params +func (o *DescribeImagesParams) WithBmpLanguage(bmpLanguage *string) *DescribeImagesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe images params +func (o *DescribeImagesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe images params +func (o *DescribeImagesParams) WithBmpUserID(bmpUserID *string) *DescribeImagesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe images params +func (o *DescribeImagesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe images params +func (o *DescribeImagesParams) WithDeviceTypeID(deviceTypeID *string) *DescribeImagesParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe images params +func (o *DescribeImagesParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithImageID adds the imageID to the describe images params +func (o *DescribeImagesParams) WithImageID(imageID *string) *DescribeImagesParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the describe images params +func (o *DescribeImagesParams) SetImageID(imageID *string) { + o.ImageID = imageID +} + +// WithImageIDs adds the imageIds to the describe images params +func (o *DescribeImagesParams) WithImageIDs(imageIds []string) *DescribeImagesParams { + o.SetImageIDs(imageIds) + return o +} + +// SetImageIDs adds the imageIds to the describe images params +func (o *DescribeImagesParams) SetImageIDs(imageIds []string) { + o.ImageIDs = imageIds +} + +// WithImageName adds the imageName to the describe images params +func (o *DescribeImagesParams) WithImageName(imageName *string) *DescribeImagesParams { + o.SetImageName(imageName) + return o +} + +// SetImageName adds the imageName to the describe images params +func (o *DescribeImagesParams) SetImageName(imageName *string) { + o.ImageName = imageName +} + +// WithIsAll adds the isAll to the describe images params +func (o *DescribeImagesParams) WithIsAll(isAll *string) *DescribeImagesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe images params +func (o *DescribeImagesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithOsID adds the osID to the describe images params +func (o *DescribeImagesParams) WithOsID(osID *string) *DescribeImagesParams { + o.SetOsID(osID) + return o +} + +// SetOsID adds the osId to the describe images params +func (o *DescribeImagesParams) SetOsID(osID *string) { + o.OsID = osID +} + +// WithOsType adds the osType to the describe images params +func (o *DescribeImagesParams) WithOsType(osType *string) *DescribeImagesParams { + o.SetOsType(osType) + return o +} + +// SetOsType adds the osType to the describe images params +func (o *DescribeImagesParams) SetOsType(osType *string) { + o.OsType = osType +} + +// WithPageNumber adds the pageNumber to the describe images params +func (o *DescribeImagesParams) WithPageNumber(pageNumber *int64) *DescribeImagesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe images params +func (o *DescribeImagesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe images params +func (o *DescribeImagesParams) WithPageSize(pageSize *int64) *DescribeImagesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe images params +func (o *DescribeImagesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithSource adds the source to the describe images params +func (o *DescribeImagesParams) WithSource(source *string) *DescribeImagesParams { + o.SetSource(source) + return o +} + +// SetSource adds the source to the describe images params +func (o *DescribeImagesParams) SetSource(source *string) { + o.Source = source +} + +// WithTraceID adds the traceID to the describe images params +func (o *DescribeImagesParams) WithTraceID(traceID string) *DescribeImagesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe images params +func (o *DescribeImagesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithVersion adds the version to the describe images params +func (o *DescribeImagesParams) WithVersion(version *string) *DescribeImagesParams { + o.SetVersion(version) + return o +} + +// SetVersion adds the version to the describe images params +func (o *DescribeImagesParams) SetVersion(version *string) { + o.Version = version +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeImagesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Architecture != nil { + + // query param architecture + var qrArchitecture string + + if o.Architecture != nil { + qrArchitecture = *o.Architecture + } + qArchitecture := qrArchitecture + if qArchitecture != "" { + + if err := r.SetQueryParam("architecture", qArchitecture); err != nil { + return err + } + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.ImageID != nil { + + // query param imageId + var qrImageID string + + if o.ImageID != nil { + qrImageID = *o.ImageID + } + qImageID := qrImageID + if qImageID != "" { + + if err := r.SetQueryParam("imageId", qImageID); err != nil { + return err + } + } + } + + if o.ImageIDs != nil { + + // binding items for imageIds + joinedImageIds := o.bindParamImageIds(reg) + + // query array param imageIds + if err := r.SetQueryParam("imageIds", joinedImageIds...); err != nil { + return err + } + } + + if o.ImageName != nil { + + // query param imageName + var qrImageName string + + if o.ImageName != nil { + qrImageName = *o.ImageName + } + qImageName := qrImageName + if qImageName != "" { + + if err := r.SetQueryParam("imageName", qImageName); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.OsID != nil { + + // query param osId + var qrOsID string + + if o.OsID != nil { + qrOsID = *o.OsID + } + qOsID := qrOsID + if qOsID != "" { + + if err := r.SetQueryParam("osId", qOsID); err != nil { + return err + } + } + } + + if o.OsType != nil { + + // query param osType + var qrOsType string + + if o.OsType != nil { + qrOsType = *o.OsType + } + qOsType := qrOsType + if qOsType != "" { + + if err := r.SetQueryParam("osType", qOsType); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.Source != nil { + + // query param source + var qrSource string + + if o.Source != nil { + qrSource = *o.Source + } + qSource := qrSource + if qSource != "" { + + if err := r.SetQueryParam("source", qSource); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.Version != nil { + + // query param version + var qrVersion string + + if o.Version != nil { + qrVersion = *o.Version + } + qVersion := qrVersion + if qVersion != "" { + + if err := r.SetQueryParam("version", qVersion); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindParamDescribeImages binds the parameter imageIds +func (o *DescribeImagesParams) bindParamImageIds(formats strfmt.Registry) []string { + imageIdsIR := o.ImageIDs + + var imageIdsIC []string + for _, imageIdsIIR := range imageIdsIR { // explode []string + + imageIdsIIV := imageIdsIIR // string as string + imageIdsIC = append(imageIdsIC, imageIdsIIV) + } + + // items.CollectionFormat: "" + imageIdsIS := swag.JoinByFormat(imageIdsIC, "") + + return imageIdsIS +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_images_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_images_responses.go new file mode 100644 index 0000000..95de66f --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/describe_images_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeImagesReader is a Reader for the DescribeImages structure. +type DescribeImagesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeImagesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeImagesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeImagesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeImagesOK creates a DescribeImagesOK with default headers values +func NewDescribeImagesOK() *DescribeImagesOK { + return &DescribeImagesOK{} +} + +/* DescribeImagesOK describes a response with status code 200, with default header values. + +A DescribeImagesResult is an response struct that is used to describe images. +*/ +type DescribeImagesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImagesOKBody +} + +// IsSuccess returns true when this describe images o k response has a 2xx status code +func (o *DescribeImagesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe images o k response has a 3xx status code +func (o *DescribeImagesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe images o k response has a 4xx status code +func (o *DescribeImagesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe images o k response has a 5xx status code +func (o *DescribeImagesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe images o k response a status code equal to that given +func (o *DescribeImagesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeImagesOK) Error() string { + return fmt.Sprintf("[GET /images][%d] describeImagesOK %+v", 200, o.Payload) +} + +func (o *DescribeImagesOK) String() string { + return fmt.Sprintf("[GET /images][%d] describeImagesOK %+v", 200, o.Payload) +} + +func (o *DescribeImagesOK) GetPayload() *DescribeImagesOKBody { + return o.Payload +} + +func (o *DescribeImagesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImagesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeImagesDefault creates a DescribeImagesDefault with default headers values +func NewDescribeImagesDefault(code int) *DescribeImagesDefault { + return &DescribeImagesDefault{ + _statusCode: code, + } +} + +/* DescribeImagesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeImagesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImagesDefaultBody +} + +// Code gets the status code for the describe images default response +func (o *DescribeImagesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe images default response has a 2xx status code +func (o *DescribeImagesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe images default response has a 3xx status code +func (o *DescribeImagesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe images default response has a 4xx status code +func (o *DescribeImagesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe images default response has a 5xx status code +func (o *DescribeImagesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe images default response a status code equal to that given +func (o *DescribeImagesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeImagesDefault) Error() string { + return fmt.Sprintf("[GET /images][%d] describeImages default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImagesDefault) String() string { + return fmt.Sprintf("[GET /images][%d] describeImages default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImagesDefault) GetPayload() *DescribeImagesDefaultBody { + return o.Payload +} + +func (o *DescribeImagesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImagesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeImagesDefaultBody describe images default body +swagger:model DescribeImagesDefaultBody +*/ +type DescribeImagesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe images default body +func (o *DescribeImagesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImagesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeImages default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeImagesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeImages default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImages default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImages default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe images default body based on the context it is used +func (o *DescribeImagesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImagesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImages default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImages default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImagesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImagesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeImagesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeImagesOKBody describe images o k body +swagger:model DescribeImagesOKBody +*/ +type DescribeImagesOKBody struct { + + // result + Result *models.ImageList `json:"result,omitempty"` +} + +// Validate validates this describe images o k body +func (o *DescribeImagesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImagesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImagesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImagesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe images o k body based on the context it is used +func (o *DescribeImagesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImagesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImagesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImagesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImagesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImagesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeImagesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/image_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/image_client.go new file mode 100644 index 0000000..7d96891 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/image/image_client.go @@ -0,0 +1,157 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new image API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for image API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DescribeImage(params *DescribeImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImageOK, error) + + DescribeImageDeviceTypes(params *DescribeImageDeviceTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImageDeviceTypesOK, error) + + DescribeImages(params *DescribeImagesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImagesOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DescribeImage DescribeImage 获取镜像详情 +*/ +func (a *Client) DescribeImage(params *DescribeImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeImageParams() + } + op := &runtime.ClientOperation{ + ID: "describeImage", + Method: "GET", + PathPattern: "/images/{image_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeImageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeImageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeImageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeImageDeviceTypes DescribeImageDeviceTypes 查看镜像绑定的机型 +*/ +func (a *Client) DescribeImageDeviceTypes(params *DescribeImageDeviceTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImageDeviceTypesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeImageDeviceTypesParams() + } + op := &runtime.ClientOperation{ + ID: "describeImageDeviceTypes", + Method: "GET", + PathPattern: "/images/imageDeviceTypes", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeImageDeviceTypesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeImageDeviceTypesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeImageDeviceTypesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeImages DescribeImages 获取镜像列表 +*/ +func (a *Client) DescribeImages(params *DescribeImagesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImagesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeImagesParams() + } + op := &runtime.ClientOperation{ + ID: "describeImages", + Method: "GET", + PathPattern: "/images", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeImagesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeImagesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeImagesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/create_project_instance_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/create_project_instance_parameters.go new file mode 100644 index 0000000..8772e7e --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/create_project_instance_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewCreateProjectInstanceParams creates a new CreateProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateProjectInstanceParams() *CreateProjectInstanceParams { + return &CreateProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateProjectInstanceParamsWithTimeout creates a new CreateProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewCreateProjectInstanceParamsWithTimeout(timeout time.Duration) *CreateProjectInstanceParams { + return &CreateProjectInstanceParams{ + timeout: timeout, + } +} + +// NewCreateProjectInstanceParamsWithContext creates a new CreateProjectInstanceParams object +// with the ability to set a context for a request. +func NewCreateProjectInstanceParamsWithContext(ctx context.Context) *CreateProjectInstanceParams { + return &CreateProjectInstanceParams{ + Context: ctx, + } +} + +// NewCreateProjectInstanceParamsWithHTTPClient creates a new CreateProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateProjectInstanceParamsWithHTTPClient(client *http.Client) *CreateProjectInstanceParams { + return &CreateProjectInstanceParams{ + HTTPClient: client, + } +} + +/* CreateProjectInstanceParams contains all the parameters to send to the API endpoint + for the create project instance operation. + + Typically these are written to a http.Request. +*/ +type CreateProjectInstanceParams struct { + + // Body. + Body *models.CreateInstanceRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateProjectInstanceParams) WithDefaults() *CreateProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create project instance params +func (o *CreateProjectInstanceParams) WithTimeout(timeout time.Duration) *CreateProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create project instance params +func (o *CreateProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create project instance params +func (o *CreateProjectInstanceParams) WithContext(ctx context.Context) *CreateProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create project instance params +func (o *CreateProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create project instance params +func (o *CreateProjectInstanceParams) WithHTTPClient(client *http.Client) *CreateProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create project instance params +func (o *CreateProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create project instance params +func (o *CreateProjectInstanceParams) WithBody(body *models.CreateInstanceRequest) *CreateProjectInstanceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create project instance params +func (o *CreateProjectInstanceParams) SetBody(body *models.CreateInstanceRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create project instance params +func (o *CreateProjectInstanceParams) WithAuthorization(authorization string) *CreateProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create project instance params +func (o *CreateProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create project instance params +func (o *CreateProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *CreateProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create project instance params +func (o *CreateProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create project instance params +func (o *CreateProjectInstanceParams) WithBmpUserID(bmpUserID *string) *CreateProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create project instance params +func (o *CreateProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create project instance params +func (o *CreateProjectInstanceParams) WithTraceID(traceID string) *CreateProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create project instance params +func (o *CreateProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/create_project_instance_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/create_project_instance_responses.go new file mode 100644 index 0000000..9435bc4 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/create_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// CreateProjectInstanceReader is a Reader for the CreateProjectInstance structure. +type CreateProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateProjectInstanceOK creates a CreateProjectInstanceOK with default headers values +func NewCreateProjectInstanceOK() *CreateProjectInstanceOK { + return &CreateProjectInstanceOK{} +} + +/* CreateProjectInstanceOK describes a response with status code 200, with default header values. + +A CreateProjectInstanceResult is an response struct that is used to describe create instance result. +*/ +type CreateProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateProjectInstanceOKBody +} + +// IsSuccess returns true when this create project instance o k response has a 2xx status code +func (o *CreateProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create project instance o k response has a 3xx status code +func (o *CreateProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create project instance o k response has a 4xx status code +func (o *CreateProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create project instance o k response has a 5xx status code +func (o *CreateProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create project instance o k response a status code equal to that given +func (o *CreateProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateProjectInstanceOK) Error() string { + return fmt.Sprintf("[POST /project/instances][%d] createProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *CreateProjectInstanceOK) String() string { + return fmt.Sprintf("[POST /project/instances][%d] createProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *CreateProjectInstanceOK) GetPayload() *CreateProjectInstanceOKBody { + return o.Payload +} + +func (o *CreateProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateProjectInstanceDefault creates a CreateProjectInstanceDefault with default headers values +func NewCreateProjectInstanceDefault(code int) *CreateProjectInstanceDefault { + return &CreateProjectInstanceDefault{ + _statusCode: code, + } +} + +/* CreateProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateProjectInstanceDefaultBody +} + +// Code gets the status code for the create project instance default response +func (o *CreateProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create project instance default response has a 2xx status code +func (o *CreateProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create project instance default response has a 3xx status code +func (o *CreateProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create project instance default response has a 4xx status code +func (o *CreateProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create project instance default response has a 5xx status code +func (o *CreateProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create project instance default response a status code equal to that given +func (o *CreateProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateProjectInstanceDefault) Error() string { + return fmt.Sprintf("[POST /project/instances][%d] createProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *CreateProjectInstanceDefault) String() string { + return fmt.Sprintf("[POST /project/instances][%d] createProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *CreateProjectInstanceDefault) GetPayload() *CreateProjectInstanceDefaultBody { + return o.Payload +} + +func (o *CreateProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateProjectInstanceDefaultBody create project instance default body +swagger:model CreateProjectInstanceDefaultBody +*/ +type CreateProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create project instance default body +func (o *CreateProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create project instance default body based on the context it is used +func (o *CreateProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateProjectInstanceOKBody create project instance o k body +swagger:model CreateProjectInstanceOKBody +*/ +type CreateProjectInstanceOKBody struct { + + // result + Result *models.InstanceIds `json:"result,omitempty"` +} + +// Validate validates this create project instance o k body +func (o *CreateProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create project instance o k body based on the context it is used +func (o *CreateProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res CreateProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/delete_instances_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/delete_instances_parameters.go new file mode 100644 index 0000000..9df0cd1 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/delete_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewDeleteInstancesParams creates a new DeleteInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteInstancesParams() *DeleteInstancesParams { + return &DeleteInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteInstancesParamsWithTimeout creates a new DeleteInstancesParams object +// with the ability to set a timeout on a request. +func NewDeleteInstancesParamsWithTimeout(timeout time.Duration) *DeleteInstancesParams { + return &DeleteInstancesParams{ + timeout: timeout, + } +} + +// NewDeleteInstancesParamsWithContext creates a new DeleteInstancesParams object +// with the ability to set a context for a request. +func NewDeleteInstancesParamsWithContext(ctx context.Context) *DeleteInstancesParams { + return &DeleteInstancesParams{ + Context: ctx, + } +} + +// NewDeleteInstancesParamsWithHTTPClient creates a new DeleteInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteInstancesParamsWithHTTPClient(client *http.Client) *DeleteInstancesParams { + return &DeleteInstancesParams{ + HTTPClient: client, + } +} + +/* DeleteInstancesParams contains all the parameters to send to the API endpoint + for the delete instances operation. + + Typically these are written to a http.Request. +*/ +type DeleteInstancesParams struct { + + // Body. + Body *models.DeleteInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteInstancesParams) WithDefaults() *DeleteInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete instances params +func (o *DeleteInstancesParams) WithTimeout(timeout time.Duration) *DeleteInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete instances params +func (o *DeleteInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete instances params +func (o *DeleteInstancesParams) WithContext(ctx context.Context) *DeleteInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete instances params +func (o *DeleteInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete instances params +func (o *DeleteInstancesParams) WithHTTPClient(client *http.Client) *DeleteInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete instances params +func (o *DeleteInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the delete instances params +func (o *DeleteInstancesParams) WithBody(body *models.DeleteInstancesRequest) *DeleteInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the delete instances params +func (o *DeleteInstancesParams) SetBody(body *models.DeleteInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the delete instances params +func (o *DeleteInstancesParams) WithAuthorization(authorization string) *DeleteInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete instances params +func (o *DeleteInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete instances params +func (o *DeleteInstancesParams) WithBmpLanguage(bmpLanguage *string) *DeleteInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete instances params +func (o *DeleteInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete instances params +func (o *DeleteInstancesParams) WithBmpUserID(bmpUserID *string) *DeleteInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete instances params +func (o *DeleteInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete instances params +func (o *DeleteInstancesParams) WithTraceID(traceID string) *DeleteInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete instances params +func (o *DeleteInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/delete_instances_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/delete_instances_responses.go new file mode 100644 index 0000000..7d51ed6 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/delete_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DeleteInstancesReader is a Reader for the DeleteInstances structure. +type DeleteInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteInstancesOK creates a DeleteInstancesOK with default headers values +func NewDeleteInstancesOK() *DeleteInstancesOK { + return &DeleteInstancesOK{} +} + +/* DeleteInstancesOK describes a response with status code 200, with default header values. + +A DeleteInstancesResult is an response struct that is used to describe modify instance result. +*/ +type DeleteInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteInstancesOKBody +} + +// IsSuccess returns true when this delete instances o k response has a 2xx status code +func (o *DeleteInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete instances o k response has a 3xx status code +func (o *DeleteInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete instances o k response has a 4xx status code +func (o *DeleteInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete instances o k response has a 5xx status code +func (o *DeleteInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete instances o k response a status code equal to that given +func (o *DeleteInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteInstancesOK) Error() string { + return fmt.Sprintf("[DELETE /project/instances/batch/instances:deleteInstances][%d] deleteInstancesOK %+v", 200, o.Payload) +} + +func (o *DeleteInstancesOK) String() string { + return fmt.Sprintf("[DELETE /project/instances/batch/instances:deleteInstances][%d] deleteInstancesOK %+v", 200, o.Payload) +} + +func (o *DeleteInstancesOK) GetPayload() *DeleteInstancesOKBody { + return o.Payload +} + +func (o *DeleteInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteInstancesDefault creates a DeleteInstancesDefault with default headers values +func NewDeleteInstancesDefault(code int) *DeleteInstancesDefault { + return &DeleteInstancesDefault{ + _statusCode: code, + } +} + +/* DeleteInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteInstancesDefaultBody +} + +// Code gets the status code for the delete instances default response +func (o *DeleteInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete instances default response has a 2xx status code +func (o *DeleteInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete instances default response has a 3xx status code +func (o *DeleteInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete instances default response has a 4xx status code +func (o *DeleteInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete instances default response has a 5xx status code +func (o *DeleteInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete instances default response a status code equal to that given +func (o *DeleteInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteInstancesDefault) Error() string { + return fmt.Sprintf("[DELETE /project/instances/batch/instances:deleteInstances][%d] deleteInstances default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteInstancesDefault) String() string { + return fmt.Sprintf("[DELETE /project/instances/batch/instances:deleteInstances][%d] deleteInstances default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteInstancesDefault) GetPayload() *DeleteInstancesDefaultBody { + return o.Payload +} + +func (o *DeleteInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteInstancesDefaultBody delete instances default body +swagger:model DeleteInstancesDefaultBody +*/ +type DeleteInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete instances default body +func (o *DeleteInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete instances default body based on the context it is used +func (o *DeleteInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteInstancesOKBody delete instances o k body +swagger:model DeleteInstancesOKBody +*/ +type DeleteInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete instances o k body +func (o *DeleteInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete instances o k body based on the context it is used +func (o *DeleteInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteInstancesOKBody) UnmarshalBinary(b []byte) error { + var res DeleteInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/delete_project_instance_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/delete_project_instance_parameters.go new file mode 100644 index 0000000..0ed6624 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/delete_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteProjectInstanceParams creates a new DeleteProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteProjectInstanceParams() *DeleteProjectInstanceParams { + return &DeleteProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteProjectInstanceParamsWithTimeout creates a new DeleteProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewDeleteProjectInstanceParamsWithTimeout(timeout time.Duration) *DeleteProjectInstanceParams { + return &DeleteProjectInstanceParams{ + timeout: timeout, + } +} + +// NewDeleteProjectInstanceParamsWithContext creates a new DeleteProjectInstanceParams object +// with the ability to set a context for a request. +func NewDeleteProjectInstanceParamsWithContext(ctx context.Context) *DeleteProjectInstanceParams { + return &DeleteProjectInstanceParams{ + Context: ctx, + } +} + +// NewDeleteProjectInstanceParamsWithHTTPClient creates a new DeleteProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteProjectInstanceParamsWithHTTPClient(client *http.Client) *DeleteProjectInstanceParams { + return &DeleteProjectInstanceParams{ + HTTPClient: client, + } +} + +/* DeleteProjectInstanceParams contains all the parameters to send to the API endpoint + for the delete project instance operation. + + Typically these are written to a http.Request. +*/ +type DeleteProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteProjectInstanceParams) WithDefaults() *DeleteProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete project instance params +func (o *DeleteProjectInstanceParams) WithTimeout(timeout time.Duration) *DeleteProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete project instance params +func (o *DeleteProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete project instance params +func (o *DeleteProjectInstanceParams) WithContext(ctx context.Context) *DeleteProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete project instance params +func (o *DeleteProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete project instance params +func (o *DeleteProjectInstanceParams) WithHTTPClient(client *http.Client) *DeleteProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete project instance params +func (o *DeleteProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete project instance params +func (o *DeleteProjectInstanceParams) WithAuthorization(authorization string) *DeleteProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete project instance params +func (o *DeleteProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete project instance params +func (o *DeleteProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *DeleteProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete project instance params +func (o *DeleteProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete project instance params +func (o *DeleteProjectInstanceParams) WithBmpUserID(bmpUserID *string) *DeleteProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete project instance params +func (o *DeleteProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the delete project instance params +func (o *DeleteProjectInstanceParams) WithInstanceID(instanceID string) *DeleteProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the delete project instance params +func (o *DeleteProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the delete project instance params +func (o *DeleteProjectInstanceParams) WithTraceID(traceID string) *DeleteProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete project instance params +func (o *DeleteProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/delete_project_instance_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/delete_project_instance_responses.go new file mode 100644 index 0000000..8810ef6 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/delete_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DeleteProjectInstanceReader is a Reader for the DeleteProjectInstance structure. +type DeleteProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteProjectInstanceOK creates a DeleteProjectInstanceOK with default headers values +func NewDeleteProjectInstanceOK() *DeleteProjectInstanceOK { + return &DeleteProjectInstanceOK{} +} + +/* DeleteProjectInstanceOK describes a response with status code 200, with default header values. + +A DeleteProjectInstanceResult is an response struct that is used to delete stop instance result. +*/ +type DeleteProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteProjectInstanceOKBody +} + +// IsSuccess returns true when this delete project instance o k response has a 2xx status code +func (o *DeleteProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete project instance o k response has a 3xx status code +func (o *DeleteProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete project instance o k response has a 4xx status code +func (o *DeleteProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete project instance o k response has a 5xx status code +func (o *DeleteProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete project instance o k response a status code equal to that given +func (o *DeleteProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteProjectInstanceOK) Error() string { + return fmt.Sprintf("[DELETE /project/instances/{instance_id}][%d] deleteProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *DeleteProjectInstanceOK) String() string { + return fmt.Sprintf("[DELETE /project/instances/{instance_id}][%d] deleteProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *DeleteProjectInstanceOK) GetPayload() *DeleteProjectInstanceOKBody { + return o.Payload +} + +func (o *DeleteProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteProjectInstanceDefault creates a DeleteProjectInstanceDefault with default headers values +func NewDeleteProjectInstanceDefault(code int) *DeleteProjectInstanceDefault { + return &DeleteProjectInstanceDefault{ + _statusCode: code, + } +} + +/* DeleteProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteProjectInstanceDefaultBody +} + +// Code gets the status code for the delete project instance default response +func (o *DeleteProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete project instance default response has a 2xx status code +func (o *DeleteProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete project instance default response has a 3xx status code +func (o *DeleteProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete project instance default response has a 4xx status code +func (o *DeleteProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete project instance default response has a 5xx status code +func (o *DeleteProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete project instance default response a status code equal to that given +func (o *DeleteProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteProjectInstanceDefault) Error() string { + return fmt.Sprintf("[DELETE /project/instances/{instance_id}][%d] deleteProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteProjectInstanceDefault) String() string { + return fmt.Sprintf("[DELETE /project/instances/{instance_id}][%d] deleteProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteProjectInstanceDefault) GetPayload() *DeleteProjectInstanceDefaultBody { + return o.Payload +} + +func (o *DeleteProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteProjectInstanceDefaultBody delete project instance default body +swagger:model DeleteProjectInstanceDefaultBody +*/ +type DeleteProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete project instance default body +func (o *DeleteProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete project instance default body based on the context it is used +func (o *DeleteProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteProjectInstanceOKBody delete project instance o k body +swagger:model DeleteProjectInstanceOKBody +*/ +type DeleteProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete project instance o k body +func (o *DeleteProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete project instance o k body based on the context it is used +func (o *DeleteProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res DeleteProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_instances_by_project_id_and_owner_name_and_sharer_name_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_instances_by_project_id_and_owner_name_and_sharer_name_parameters.go new file mode 100644 index 0000000..91c8e52 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_instances_by_project_id_and_owner_name_and_sharer_name_parameters.go @@ -0,0 +1,486 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams creates a new DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams() *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + return &DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameParamsWithTimeout creates a new DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams object +// with the ability to set a timeout on a request. +func NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameParamsWithTimeout(timeout time.Duration) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + return &DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams{ + timeout: timeout, + } +} + +// NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameParamsWithContext creates a new DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams object +// with the ability to set a context for a request. +func NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameParamsWithContext(ctx context.Context) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + return &DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams{ + Context: ctx, + } +} + +// NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameParamsWithHTTPClient creates a new DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameParamsWithHTTPClient(client *http.Client) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + return &DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams{ + HTTPClient: client, + } +} + +/* DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams contains all the parameters to send to the API endpoint + for the describe instances by project Id and owner name and sharer name operation. + + Typically these are written to a http.Request. +*/ +type DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // InstanceID. + InstanceID *string + + /* InstanceName. + + 这两项支持模糊搜索 + */ + InstanceName *string + + // IsAll. + IsAll *string + + // OwnerName. + OwnerName *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* ProjectID. + + 项目ID + */ + ProjectID *string + + // SharerName. + SharerName *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe instances by project Id and owner name and sharer name params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithDefaults() *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe instances by project Id and owner name and sharer name params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithTimeout(timeout time.Duration) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithContext(ctx context.Context) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithHTTPClient(client *http.Client) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithAuthorization(authorization string) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithBmpLanguage(bmpLanguage *string) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithBmpUserID(bmpUserID *string) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithInstanceID(instanceID *string) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetInstanceID(instanceID *string) { + o.InstanceID = instanceID +} + +// WithInstanceName adds the instanceName to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithInstanceName(instanceName *string) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetInstanceName(instanceName) + return o +} + +// SetInstanceName adds the instanceName to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetInstanceName(instanceName *string) { + o.InstanceName = instanceName +} + +// WithIsAll adds the isAll to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithIsAll(isAll *string) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithOwnerName adds the ownerName to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithOwnerName(ownerName *string) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetOwnerName(ownerName) + return o +} + +// SetOwnerName adds the ownerName to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetOwnerName(ownerName *string) { + o.OwnerName = ownerName +} + +// WithPageNumber adds the pageNumber to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithPageNumber(pageNumber *int64) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithPageSize(pageSize *int64) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithProjectID adds the projectID to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithProjectID(projectID *string) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetProjectID(projectID *string) { + o.ProjectID = projectID +} + +// WithSharerName adds the sharerName to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithSharerName(sharerName *string) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetSharerName(sharerName) + return o +} + +// SetSharerName adds the sharerName to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetSharerName(sharerName *string) { + o.SharerName = sharerName +} + +// WithTraceID adds the traceID to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WithTraceID(traceID string) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe instances by project Id and owner name and sharer name params +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.InstanceID != nil { + + // query param instanceId + var qrInstanceID string + + if o.InstanceID != nil { + qrInstanceID = *o.InstanceID + } + qInstanceID := qrInstanceID + if qInstanceID != "" { + + if err := r.SetQueryParam("instanceId", qInstanceID); err != nil { + return err + } + } + } + + if o.InstanceName != nil { + + // query param instanceName + var qrInstanceName string + + if o.InstanceName != nil { + qrInstanceName = *o.InstanceName + } + qInstanceName := qrInstanceName + if qInstanceName != "" { + + if err := r.SetQueryParam("instanceName", qInstanceName); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.OwnerName != nil { + + // query param ownerName + var qrOwnerName string + + if o.OwnerName != nil { + qrOwnerName = *o.OwnerName + } + qOwnerName := qrOwnerName + if qOwnerName != "" { + + if err := r.SetQueryParam("ownerName", qOwnerName); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.ProjectID != nil { + + // query param projectId + var qrProjectID string + + if o.ProjectID != nil { + qrProjectID = *o.ProjectID + } + qProjectID := qrProjectID + if qProjectID != "" { + + if err := r.SetQueryParam("projectId", qProjectID); err != nil { + return err + } + } + } + + if o.SharerName != nil { + + // query param sharerName + var qrSharerName string + + if o.SharerName != nil { + qrSharerName = *o.SharerName + } + qSharerName := qrSharerName + if qSharerName != "" { + + if err := r.SetQueryParam("sharerName", qSharerName); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_instances_by_project_id_and_owner_name_and_sharer_name_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_instances_by_project_id_and_owner_name_and_sharer_name_responses.go new file mode 100644 index 0000000..b6b64b0 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_instances_by_project_id_and_owner_name_and_sharer_name_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeInstancesByProjectIDAndOwnerNameAndSharerNameReader is a Reader for the DescribeInstancesByProjectIDAndOwnerNameAndSharerName structure. +type DescribeInstancesByProjectIDAndOwnerNameAndSharerNameReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK creates a DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK with default headers values +func NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK() *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK { + return &DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK{} +} + +/* DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK describes a response with status code 200, with default header values. + +A DescribeInstancesByProjectIdAndOwnerNameAndSharerNameResult is an response struct that is used to get instance list. +*/ +type DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOKBody +} + +// IsSuccess returns true when this describe instances by project Id and owner name and sharer name o k response has a 2xx status code +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe instances by project Id and owner name and sharer name o k response has a 3xx status code +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe instances by project Id and owner name and sharer name o k response has a 4xx status code +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe instances by project Id and owner name and sharer name o k response has a 5xx status code +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe instances by project Id and owner name and sharer name o k response a status code equal to that given +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK) Error() string { + return fmt.Sprintf("[GET /project/instances/share/describeInstances][%d] describeInstancesByProjectIdAndOwnerNameAndSharerNameOK %+v", 200, o.Payload) +} + +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK) String() string { + return fmt.Sprintf("[GET /project/instances/share/describeInstances][%d] describeInstancesByProjectIdAndOwnerNameAndSharerNameOK %+v", 200, o.Payload) +} + +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK) GetPayload() *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOKBody { + return o.Payload +} + +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault creates a DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault with default headers values +func NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault(code int) *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault { + return &DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault{ + _statusCode: code, + } +} + +/* DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefaultBody +} + +// Code gets the status code for the describe instances by project Id and owner name and sharer name default response +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe instances by project Id and owner name and sharer name default response has a 2xx status code +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe instances by project Id and owner name and sharer name default response has a 3xx status code +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe instances by project Id and owner name and sharer name default response has a 4xx status code +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe instances by project Id and owner name and sharer name default response has a 5xx status code +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe instances by project Id and owner name and sharer name default response a status code equal to that given +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault) Error() string { + return fmt.Sprintf("[GET /project/instances/share/describeInstances][%d] describeInstancesByProjectIdAndOwnerNameAndSharerName default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault) String() string { + return fmt.Sprintf("[GET /project/instances/share/describeInstances][%d] describeInstancesByProjectIdAndOwnerNameAndSharerName default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault) GetPayload() *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefaultBody { + return o.Payload +} + +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefaultBody describe instances by project ID and owner name and sharer name default body +swagger:model DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefaultBody +*/ +type DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe instances by project ID and owner name and sharer name default body +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeInstancesByProjectIdAndOwnerNameAndSharerName default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeInstancesByProjectIdAndOwnerNameAndSharerName default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeInstancesByProjectIdAndOwnerNameAndSharerName default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeInstancesByProjectIdAndOwnerNameAndSharerName default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe instances by project ID and owner name and sharer name default body based on the context it is used +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeInstancesByProjectIdAndOwnerNameAndSharerName default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeInstancesByProjectIdAndOwnerNameAndSharerName default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOKBody describe instances by project ID and owner name and sharer name o k body +swagger:model DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOKBody +*/ +type DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOKBody struct { + + // result + Result *models.InstanceForShareList `json:"result,omitempty"` +} + +// Validate validates this describe instances by project ID and owner name and sharer name o k body +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeInstancesByProjectIdAndOwnerNameAndSharerNameOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeInstancesByProjectIdAndOwnerNameAndSharerNameOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe instances by project ID and owner name and sharer name o k body based on the context it is used +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeInstancesByProjectIdAndOwnerNameAndSharerNameOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeInstancesByProjectIdAndOwnerNameAndSharerNameOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOKBody) UnmarshalBinary(b []byte) error { + var res DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_project_instance_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_project_instance_parameters.go new file mode 100644 index 0000000..f7def69 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_project_instance_parameters.go @@ -0,0 +1,243 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeProjectInstanceParams creates a new DescribeProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeProjectInstanceParams() *DescribeProjectInstanceParams { + return &DescribeProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeProjectInstanceParamsWithTimeout creates a new DescribeProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewDescribeProjectInstanceParamsWithTimeout(timeout time.Duration) *DescribeProjectInstanceParams { + return &DescribeProjectInstanceParams{ + timeout: timeout, + } +} + +// NewDescribeProjectInstanceParamsWithContext creates a new DescribeProjectInstanceParams object +// with the ability to set a context for a request. +func NewDescribeProjectInstanceParamsWithContext(ctx context.Context) *DescribeProjectInstanceParams { + return &DescribeProjectInstanceParams{ + Context: ctx, + } +} + +// NewDescribeProjectInstanceParamsWithHTTPClient creates a new DescribeProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeProjectInstanceParamsWithHTTPClient(client *http.Client) *DescribeProjectInstanceParams { + return &DescribeProjectInstanceParams{ + HTTPClient: client, + } +} + +/* DescribeProjectInstanceParams contains all the parameters to send to the API endpoint + for the describe project instance operation. + + Typically these are written to a http.Request. +*/ +type DescribeProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* InstanceID. + + 实例uuid + */ + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeProjectInstanceParams) WithDefaults() *DescribeProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe project instance params +func (o *DescribeProjectInstanceParams) WithTimeout(timeout time.Duration) *DescribeProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe project instance params +func (o *DescribeProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe project instance params +func (o *DescribeProjectInstanceParams) WithContext(ctx context.Context) *DescribeProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe project instance params +func (o *DescribeProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe project instance params +func (o *DescribeProjectInstanceParams) WithHTTPClient(client *http.Client) *DescribeProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe project instance params +func (o *DescribeProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe project instance params +func (o *DescribeProjectInstanceParams) WithAuthorization(authorization string) *DescribeProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe project instance params +func (o *DescribeProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe project instance params +func (o *DescribeProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *DescribeProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe project instance params +func (o *DescribeProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe project instance params +func (o *DescribeProjectInstanceParams) WithBmpUserID(bmpUserID *string) *DescribeProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe project instance params +func (o *DescribeProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the describe project instance params +func (o *DescribeProjectInstanceParams) WithInstanceID(instanceID string) *DescribeProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the describe project instance params +func (o *DescribeProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the describe project instance params +func (o *DescribeProjectInstanceParams) WithTraceID(traceID string) *DescribeProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe project instance params +func (o *DescribeProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_project_instance_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_project_instance_responses.go new file mode 100644 index 0000000..33696be --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeProjectInstanceReader is a Reader for the DescribeProjectInstance structure. +type DescribeProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeProjectInstanceOK creates a DescribeProjectInstanceOK with default headers values +func NewDescribeProjectInstanceOK() *DescribeProjectInstanceOK { + return &DescribeProjectInstanceOK{} +} + +/* DescribeProjectInstanceOK describes a response with status code 200, with default header values. + +A GetInstanceResult is an response struct that is used to describe instance. +*/ +type DescribeProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeProjectInstanceOKBody +} + +// IsSuccess returns true when this describe project instance o k response has a 2xx status code +func (o *DescribeProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe project instance o k response has a 3xx status code +func (o *DescribeProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe project instance o k response has a 4xx status code +func (o *DescribeProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe project instance o k response has a 5xx status code +func (o *DescribeProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe project instance o k response a status code equal to that given +func (o *DescribeProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeProjectInstanceOK) Error() string { + return fmt.Sprintf("[GET /project/instances/{instance_id}][%d] describeProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *DescribeProjectInstanceOK) String() string { + return fmt.Sprintf("[GET /project/instances/{instance_id}][%d] describeProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *DescribeProjectInstanceOK) GetPayload() *DescribeProjectInstanceOKBody { + return o.Payload +} + +func (o *DescribeProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeProjectInstanceDefault creates a DescribeProjectInstanceDefault with default headers values +func NewDescribeProjectInstanceDefault(code int) *DescribeProjectInstanceDefault { + return &DescribeProjectInstanceDefault{ + _statusCode: code, + } +} + +/* DescribeProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeProjectInstanceDefaultBody +} + +// Code gets the status code for the describe project instance default response +func (o *DescribeProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe project instance default response has a 2xx status code +func (o *DescribeProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe project instance default response has a 3xx status code +func (o *DescribeProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe project instance default response has a 4xx status code +func (o *DescribeProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe project instance default response has a 5xx status code +func (o *DescribeProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe project instance default response a status code equal to that given +func (o *DescribeProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeProjectInstanceDefault) Error() string { + return fmt.Sprintf("[GET /project/instances/{instance_id}][%d] describeProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeProjectInstanceDefault) String() string { + return fmt.Sprintf("[GET /project/instances/{instance_id}][%d] describeProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeProjectInstanceDefault) GetPayload() *DescribeProjectInstanceDefaultBody { + return o.Payload +} + +func (o *DescribeProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeProjectInstanceDefaultBody describe project instance default body +swagger:model DescribeProjectInstanceDefaultBody +*/ +type DescribeProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe project instance default body +func (o *DescribeProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe project instance default body based on the context it is used +func (o *DescribeProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeProjectInstanceOKBody describe project instance o k body +swagger:model DescribeProjectInstanceOKBody +*/ +type DescribeProjectInstanceOKBody struct { + + // result + Result *models.InstanceInfo `json:"result,omitempty"` +} + +// Validate validates this describe project instance o k body +func (o *DescribeProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe project instance o k body based on the context it is used +func (o *DescribeProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res DescribeProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_project_instances_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_project_instances_parameters.go new file mode 100644 index 0000000..0edd173 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_project_instances_parameters.go @@ -0,0 +1,736 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeProjectInstancesParams creates a new DescribeProjectInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeProjectInstancesParams() *DescribeProjectInstancesParams { + return &DescribeProjectInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeProjectInstancesParamsWithTimeout creates a new DescribeProjectInstancesParams object +// with the ability to set a timeout on a request. +func NewDescribeProjectInstancesParamsWithTimeout(timeout time.Duration) *DescribeProjectInstancesParams { + return &DescribeProjectInstancesParams{ + timeout: timeout, + } +} + +// NewDescribeProjectInstancesParamsWithContext creates a new DescribeProjectInstancesParams object +// with the ability to set a context for a request. +func NewDescribeProjectInstancesParamsWithContext(ctx context.Context) *DescribeProjectInstancesParams { + return &DescribeProjectInstancesParams{ + Context: ctx, + } +} + +// NewDescribeProjectInstancesParamsWithHTTPClient creates a new DescribeProjectInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeProjectInstancesParamsWithHTTPClient(client *http.Client) *DescribeProjectInstancesParams { + return &DescribeProjectInstancesParams{ + HTTPClient: client, + } +} + +/* DescribeProjectInstancesParams contains all the parameters to send to the API endpoint + for the describe project instances operation. + + Typically these are written to a http.Request. +*/ +type DescribeProjectInstancesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceID. + + 设备ID + */ + DeviceID *string + + /* DeviceTypeID. + + 设备类型ID + */ + DeviceTypeID *string + + /* IdcID. + + 机房ID + */ + IdcID *string + + /* IloIP. + + 带外ip,精确搜索 + */ + IloIP *string + + /* InstanceID. + + 实例ID + */ + InstanceID *string + + /* InstanceName. + + 实例名称,模糊搜索 + */ + InstanceName *string + + /* IPV4. + + ipv4,精确搜索 + */ + IPV4 *string + + /* IPV6. + + ipv6,精确搜索 + */ + IPV6 *string + + /* IsAll. + + 是否显示全部,取值为1时表示全部 + */ + IsAll *string + + /* IsInstallAgent. + + 是否安装了agent,"0"表示未安装,"1"表示已安装 + */ + IsInstallAgent *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* ProjectID. + + 项目ID + */ + ProjectID *string + + /* Sn. + + SN + */ + Sn *string + + /* Status. + + 运行状态 + */ + Status *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe project instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeProjectInstancesParams) WithDefaults() *DescribeProjectInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe project instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeProjectInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe project instances params +func (o *DescribeProjectInstancesParams) WithTimeout(timeout time.Duration) *DescribeProjectInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe project instances params +func (o *DescribeProjectInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe project instances params +func (o *DescribeProjectInstancesParams) WithContext(ctx context.Context) *DescribeProjectInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe project instances params +func (o *DescribeProjectInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe project instances params +func (o *DescribeProjectInstancesParams) WithHTTPClient(client *http.Client) *DescribeProjectInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe project instances params +func (o *DescribeProjectInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe project instances params +func (o *DescribeProjectInstancesParams) WithAuthorization(authorization string) *DescribeProjectInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe project instances params +func (o *DescribeProjectInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe project instances params +func (o *DescribeProjectInstancesParams) WithBmpLanguage(bmpLanguage *string) *DescribeProjectInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe project instances params +func (o *DescribeProjectInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithBmpUserID(bmpUserID *string) *DescribeProjectInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceID adds the deviceID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithDeviceID(deviceID *string) *DescribeProjectInstancesParams { + o.SetDeviceID(deviceID) + return o +} + +// SetDeviceID adds the deviceId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetDeviceID(deviceID *string) { + o.DeviceID = deviceID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithDeviceTypeID(deviceTypeID *string) *DescribeProjectInstancesParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithIdcID adds the idcID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIdcID(idcID *string) *DescribeProjectInstancesParams { + o.SetIdcID(idcID) + return o +} + +// SetIdcID adds the idcId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIdcID(idcID *string) { + o.IdcID = idcID +} + +// WithIloIP adds the iloIP to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIloIP(iloIP *string) *DescribeProjectInstancesParams { + o.SetIloIP(iloIP) + return o +} + +// SetIloIP adds the iloIp to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIloIP(iloIP *string) { + o.IloIP = iloIP +} + +// WithInstanceID adds the instanceID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithInstanceID(instanceID *string) *DescribeProjectInstancesParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetInstanceID(instanceID *string) { + o.InstanceID = instanceID +} + +// WithInstanceName adds the instanceName to the describe project instances params +func (o *DescribeProjectInstancesParams) WithInstanceName(instanceName *string) *DescribeProjectInstancesParams { + o.SetInstanceName(instanceName) + return o +} + +// SetInstanceName adds the instanceName to the describe project instances params +func (o *DescribeProjectInstancesParams) SetInstanceName(instanceName *string) { + o.InstanceName = instanceName +} + +// WithIPV4 adds the iPV4 to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIPV4(iPV4 *string) *DescribeProjectInstancesParams { + o.SetIPV4(iPV4) + return o +} + +// SetIPV4 adds the ipv4 to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIPV4(iPV4 *string) { + o.IPV4 = iPV4 +} + +// WithIPV6 adds the iPV6 to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIPV6(iPV6 *string) *DescribeProjectInstancesParams { + o.SetIPV6(iPV6) + return o +} + +// SetIPV6 adds the ipv6 to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIPV6(iPV6 *string) { + o.IPV6 = iPV6 +} + +// WithIsAll adds the isAll to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIsAll(isAll *string) *DescribeProjectInstancesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithIsInstallAgent adds the isInstallAgent to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIsInstallAgent(isInstallAgent *string) *DescribeProjectInstancesParams { + o.SetIsInstallAgent(isInstallAgent) + return o +} + +// SetIsInstallAgent adds the isInstallAgent to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIsInstallAgent(isInstallAgent *string) { + o.IsInstallAgent = isInstallAgent +} + +// WithPageNumber adds the pageNumber to the describe project instances params +func (o *DescribeProjectInstancesParams) WithPageNumber(pageNumber *int64) *DescribeProjectInstancesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe project instances params +func (o *DescribeProjectInstancesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe project instances params +func (o *DescribeProjectInstancesParams) WithPageSize(pageSize *int64) *DescribeProjectInstancesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe project instances params +func (o *DescribeProjectInstancesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithProjectID adds the projectID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithProjectID(projectID *string) *DescribeProjectInstancesParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetProjectID(projectID *string) { + o.ProjectID = projectID +} + +// WithSn adds the sn to the describe project instances params +func (o *DescribeProjectInstancesParams) WithSn(sn *string) *DescribeProjectInstancesParams { + o.SetSn(sn) + return o +} + +// SetSn adds the sn to the describe project instances params +func (o *DescribeProjectInstancesParams) SetSn(sn *string) { + o.Sn = sn +} + +// WithStatus adds the status to the describe project instances params +func (o *DescribeProjectInstancesParams) WithStatus(status *string) *DescribeProjectInstancesParams { + o.SetStatus(status) + return o +} + +// SetStatus adds the status to the describe project instances params +func (o *DescribeProjectInstancesParams) SetStatus(status *string) { + o.Status = status +} + +// WithTraceID adds the traceID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithTraceID(traceID string) *DescribeProjectInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeProjectInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceID != nil { + + // query param deviceId + var qrDeviceID string + + if o.DeviceID != nil { + qrDeviceID = *o.DeviceID + } + qDeviceID := qrDeviceID + if qDeviceID != "" { + + if err := r.SetQueryParam("deviceId", qDeviceID); err != nil { + return err + } + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.IdcID != nil { + + // query param idcId + var qrIdcID string + + if o.IdcID != nil { + qrIdcID = *o.IdcID + } + qIdcID := qrIdcID + if qIdcID != "" { + + if err := r.SetQueryParam("idcId", qIdcID); err != nil { + return err + } + } + } + + if o.IloIP != nil { + + // query param ilo_ip + var qrIloIP string + + if o.IloIP != nil { + qrIloIP = *o.IloIP + } + qIloIP := qrIloIP + if qIloIP != "" { + + if err := r.SetQueryParam("ilo_ip", qIloIP); err != nil { + return err + } + } + } + + if o.InstanceID != nil { + + // query param instanceId + var qrInstanceID string + + if o.InstanceID != nil { + qrInstanceID = *o.InstanceID + } + qInstanceID := qrInstanceID + if qInstanceID != "" { + + if err := r.SetQueryParam("instanceId", qInstanceID); err != nil { + return err + } + } + } + + if o.InstanceName != nil { + + // query param instanceName + var qrInstanceName string + + if o.InstanceName != nil { + qrInstanceName = *o.InstanceName + } + qInstanceName := qrInstanceName + if qInstanceName != "" { + + if err := r.SetQueryParam("instanceName", qInstanceName); err != nil { + return err + } + } + } + + if o.IPV4 != nil { + + // query param ipv4 + var qrIPV4 string + + if o.IPV4 != nil { + qrIPV4 = *o.IPV4 + } + qIPV4 := qrIPV4 + if qIPV4 != "" { + + if err := r.SetQueryParam("ipv4", qIPV4); err != nil { + return err + } + } + } + + if o.IPV6 != nil { + + // query param ipv6 + var qrIPV6 string + + if o.IPV6 != nil { + qrIPV6 = *o.IPV6 + } + qIPV6 := qrIPV6 + if qIPV6 != "" { + + if err := r.SetQueryParam("ipv6", qIPV6); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.IsInstallAgent != nil { + + // query param isInstallAgent + var qrIsInstallAgent string + + if o.IsInstallAgent != nil { + qrIsInstallAgent = *o.IsInstallAgent + } + qIsInstallAgent := qrIsInstallAgent + if qIsInstallAgent != "" { + + if err := r.SetQueryParam("isInstallAgent", qIsInstallAgent); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.ProjectID != nil { + + // query param projectId + var qrProjectID string + + if o.ProjectID != nil { + qrProjectID = *o.ProjectID + } + qProjectID := qrProjectID + if qProjectID != "" { + + if err := r.SetQueryParam("projectId", qProjectID); err != nil { + return err + } + } + } + + if o.Sn != nil { + + // query param sn + var qrSn string + + if o.Sn != nil { + qrSn = *o.Sn + } + qSn := qrSn + if qSn != "" { + + if err := r.SetQueryParam("sn", qSn); err != nil { + return err + } + } + } + + if o.Status != nil { + + // query param status + var qrStatus string + + if o.Status != nil { + qrStatus = *o.Status + } + qStatus := qrStatus + if qStatus != "" { + + if err := r.SetQueryParam("status", qStatus); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_project_instances_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_project_instances_responses.go new file mode 100644 index 0000000..60e7059 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/describe_project_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeProjectInstancesReader is a Reader for the DescribeProjectInstances structure. +type DescribeProjectInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeProjectInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeProjectInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeProjectInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeProjectInstancesOK creates a DescribeProjectInstancesOK with default headers values +func NewDescribeProjectInstancesOK() *DescribeProjectInstancesOK { + return &DescribeProjectInstancesOK{} +} + +/* DescribeProjectInstancesOK describes a response with status code 200, with default header values. + +A DescribeProjectInstancesResult is an response struct that is used to get instance list. +*/ +type DescribeProjectInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeProjectInstancesOKBody +} + +// IsSuccess returns true when this describe project instances o k response has a 2xx status code +func (o *DescribeProjectInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe project instances o k response has a 3xx status code +func (o *DescribeProjectInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe project instances o k response has a 4xx status code +func (o *DescribeProjectInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe project instances o k response has a 5xx status code +func (o *DescribeProjectInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe project instances o k response a status code equal to that given +func (o *DescribeProjectInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeProjectInstancesOK) Error() string { + return fmt.Sprintf("[GET /project/instances][%d] describeProjectInstancesOK %+v", 200, o.Payload) +} + +func (o *DescribeProjectInstancesOK) String() string { + return fmt.Sprintf("[GET /project/instances][%d] describeProjectInstancesOK %+v", 200, o.Payload) +} + +func (o *DescribeProjectInstancesOK) GetPayload() *DescribeProjectInstancesOKBody { + return o.Payload +} + +func (o *DescribeProjectInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeProjectInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeProjectInstancesDefault creates a DescribeProjectInstancesDefault with default headers values +func NewDescribeProjectInstancesDefault(code int) *DescribeProjectInstancesDefault { + return &DescribeProjectInstancesDefault{ + _statusCode: code, + } +} + +/* DescribeProjectInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeProjectInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeProjectInstancesDefaultBody +} + +// Code gets the status code for the describe project instances default response +func (o *DescribeProjectInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe project instances default response has a 2xx status code +func (o *DescribeProjectInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe project instances default response has a 3xx status code +func (o *DescribeProjectInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe project instances default response has a 4xx status code +func (o *DescribeProjectInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe project instances default response has a 5xx status code +func (o *DescribeProjectInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe project instances default response a status code equal to that given +func (o *DescribeProjectInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeProjectInstancesDefault) Error() string { + return fmt.Sprintf("[GET /project/instances][%d] describeProjectInstances default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeProjectInstancesDefault) String() string { + return fmt.Sprintf("[GET /project/instances][%d] describeProjectInstances default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeProjectInstancesDefault) GetPayload() *DescribeProjectInstancesDefaultBody { + return o.Payload +} + +func (o *DescribeProjectInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeProjectInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeProjectInstancesDefaultBody describe project instances default body +swagger:model DescribeProjectInstancesDefaultBody +*/ +type DescribeProjectInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe project instances default body +func (o *DescribeProjectInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeProjectInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeProjectInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeProjectInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe project instances default body based on the context it is used +func (o *DescribeProjectInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeProjectInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeProjectInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeProjectInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeProjectInstancesOKBody describe project instances o k body +swagger:model DescribeProjectInstancesOKBody +*/ +type DescribeProjectInstancesOKBody struct { + + // result + Result *models.InstanceList `json:"result,omitempty"` +} + +// Validate validates this describe project instances o k body +func (o *DescribeProjectInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe project instances o k body based on the context it is used +func (o *DescribeProjectInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeProjectInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeProjectInstancesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeProjectInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/instance_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/instance_client.go new file mode 100644 index 0000000..0d1a188 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/instance_client.go @@ -0,0 +1,837 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new instance API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for instance API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateProjectInstance(params *CreateProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateProjectInstanceOK, error) + + DeleteInstances(params *DeleteInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteInstancesOK, error) + + DeleteProjectInstance(params *DeleteProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteProjectInstanceOK, error) + + DescribeInstancesByProjectIDAndOwnerNameAndSharerName(params *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK, error) + + DescribeProjectInstance(params *DescribeProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeProjectInstanceOK, error) + + DescribeProjectInstances(params *DescribeProjectInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeProjectInstancesOK, error) + + LockProjectInstance(params *LockProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*LockProjectInstanceOK, error) + + ModifyInstances(params *ModifyInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyInstancesOK, error) + + ModifyProjectInstance(params *ModifyProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyProjectInstanceOK, error) + + ReinstallProjectInstance(params *ReinstallProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ReinstallProjectInstanceOK, error) + + ResetInstanceStatus(params *ResetInstanceStatusParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetInstanceStatusOK, error) + + ResetProjectInstancePasswd(params *ResetProjectInstancePasswdParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetProjectInstancePasswdOK, error) + + ResetProjectInstancesPasswd(params *ResetProjectInstancesPasswdParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetProjectInstancesPasswdOK, error) + + RestartInstances(params *RestartInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RestartInstancesOK, error) + + RestartProjectInstance(params *RestartProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RestartProjectInstanceOK, error) + + StartInstances(params *StartInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StartInstancesOK, error) + + StartProjectInstance(params *StartProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StartProjectInstanceOK, error) + + StopInstances(params *StopInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StopInstancesOK, error) + + StopProjectInstance(params *StopProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StopProjectInstanceOK, error) + + UnLockProjectInstance(params *UnLockProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UnLockProjectInstanceOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateProjectInstance CreateProjectInstance 创建实例 +*/ +func (a *Client) CreateProjectInstance(params *CreateProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "createProjectInstance", + Method: "POST", + PathPattern: "/project/instances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteInstances DeleteInstances 批量删除实例 +*/ +func (a *Client) DeleteInstances(params *DeleteInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "deleteInstances", + Method: "DELETE", + PathPattern: "/project/instances/batch/instances:deleteInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteProjectInstance DeleteProjectInstance 删除实例 +*/ +func (a *Client) DeleteProjectInstance(params *DeleteProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "deleteProjectInstance", + Method: "DELETE", + PathPattern: "/project/instances/{instance_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeInstancesByProjectIDAndOwnerNameAndSharerName DescribeInstancesByProjectIdAndOwnerNameAndSharerName 根据projectid,ownername,username来获取实例列表。为了支持部分资源转移中的实例列表 +*/ +func (a *Client) DescribeInstancesByProjectIDAndOwnerNameAndSharerName(params *DescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams() + } + op := &runtime.ClientOperation{ + ID: "describeInstancesByProjectIdAndOwnerNameAndSharerName", + Method: "GET", + PathPattern: "/project/instances/share/describeInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeInstancesByProjectIDAndOwnerNameAndSharerNameReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeInstancesByProjectIDAndOwnerNameAndSharerNameOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeInstancesByProjectIDAndOwnerNameAndSharerNameDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeProjectInstance DescribeProjectInstance 获取实例详情 +*/ +func (a *Client) DescribeProjectInstance(params *DescribeProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "describeProjectInstance", + Method: "GET", + PathPattern: "/project/instances/{instance_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeProjectInstances DescribeProjectInstances 获取实例列表 +*/ +func (a *Client) DescribeProjectInstances(params *DescribeProjectInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeProjectInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeProjectInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "describeProjectInstances", + Method: "GET", + PathPattern: "/project/instances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeProjectInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeProjectInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeProjectInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + LockProjectInstance LockProjectInstance 锁定实例 +*/ +func (a *Client) LockProjectInstance(params *LockProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*LockProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewLockProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "lockProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/lock", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &LockProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*LockProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*LockProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyInstances ModifyInstances 批量修改实例名称 +*/ +func (a *Client) ModifyInstances(params *ModifyInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "modifyInstances", + Method: "PUT", + PathPattern: "/project/instances/batch/instances:modifyInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyProjectInstance ModifyProjectInstance 修改实例信息 +*/ +func (a *Client) ModifyProjectInstance(params *ModifyProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "modifyProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ReinstallProjectInstance ReinstallInstance 重装实例 +*/ +func (a *Client) ReinstallProjectInstance(params *ReinstallProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ReinstallProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewReinstallProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "reinstallProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/reinstallInstance", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ReinstallProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ReinstallProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ReinstallProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ResetInstanceStatus ResetInstanceStatus 重置实例状态 +*/ +func (a *Client) ResetInstanceStatus(params *ResetInstanceStatusParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetInstanceStatusOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewResetInstanceStatusParams() + } + op := &runtime.ClientOperation{ + ID: "resetInstanceStatus", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/resetStatus", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ResetInstanceStatusReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ResetInstanceStatusOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ResetInstanceStatusDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ResetProjectInstancePasswd ResetPasswd 重置密码 +*/ +func (a *Client) ResetProjectInstancePasswd(params *ResetProjectInstancePasswdParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetProjectInstancePasswdOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewResetProjectInstancePasswdParams() + } + op := &runtime.ClientOperation{ + ID: "resetProjectInstancePasswd", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/resetpasswd", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ResetProjectInstancePasswdReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ResetProjectInstancePasswdOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ResetProjectInstancePasswdDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ResetProjectInstancesPasswd ResetInstancesPasswd 批量重置密码 +*/ +func (a *Client) ResetProjectInstancesPasswd(params *ResetProjectInstancesPasswdParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetProjectInstancesPasswdOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewResetProjectInstancesPasswdParams() + } + op := &runtime.ClientOperation{ + ID: "resetProjectInstancesPasswd", + Method: "PUT", + PathPattern: "/project/instances/batch/instances:resetPasswd", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ResetProjectInstancesPasswdReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ResetProjectInstancesPasswdOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ResetProjectInstancesPasswdDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + RestartInstances StartInstances 批量重启 +*/ +func (a *Client) RestartInstances(params *RestartInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RestartInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewRestartInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "restartInstances", + Method: "PUT", + PathPattern: "/project/instances/batch/instances:restartInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &RestartInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*RestartInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*RestartInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + RestartProjectInstance RestartProjectInstance 实例重启 +*/ +func (a *Client) RestartProjectInstance(params *RestartProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RestartProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewRestartProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "restartProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/restart", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &RestartProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*RestartProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*RestartProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + StartInstances StartInstances 批量开机 +*/ +func (a *Client) StartInstances(params *StartInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StartInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewStartInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "startInstances", + Method: "PUT", + PathPattern: "/project/instances/batch/instances:startInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &StartInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*StartInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*StartInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + StartProjectInstance StartProjectInstance 实例开机 +*/ +func (a *Client) StartProjectInstance(params *StartProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StartProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewStartProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "startProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/start", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &StartProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*StartProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*StartProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + StopInstances StartInstances 批量关机 +*/ +func (a *Client) StopInstances(params *StopInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StopInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewStopInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "stopInstances", + Method: "PUT", + PathPattern: "/project/instances/batch/instances:stopInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &StopInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*StopInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*StopInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + StopProjectInstance StopProjectInstance 实例关机 +*/ +func (a *Client) StopProjectInstance(params *StopProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StopProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewStopProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "stopProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/stop", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &StopProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*StopProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*StopProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + UnLockProjectInstance UnLockProjectInstance 解锁实例 +*/ +func (a *Client) UnLockProjectInstance(params *UnLockProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UnLockProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewUnLockProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "unLockProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/unlock", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UnLockProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*UnLockProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*UnLockProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/lock_project_instance_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/lock_project_instance_parameters.go new file mode 100644 index 0000000..8758de3 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/lock_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewLockProjectInstanceParams creates a new LockProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewLockProjectInstanceParams() *LockProjectInstanceParams { + return &LockProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewLockProjectInstanceParamsWithTimeout creates a new LockProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewLockProjectInstanceParamsWithTimeout(timeout time.Duration) *LockProjectInstanceParams { + return &LockProjectInstanceParams{ + timeout: timeout, + } +} + +// NewLockProjectInstanceParamsWithContext creates a new LockProjectInstanceParams object +// with the ability to set a context for a request. +func NewLockProjectInstanceParamsWithContext(ctx context.Context) *LockProjectInstanceParams { + return &LockProjectInstanceParams{ + Context: ctx, + } +} + +// NewLockProjectInstanceParamsWithHTTPClient creates a new LockProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewLockProjectInstanceParamsWithHTTPClient(client *http.Client) *LockProjectInstanceParams { + return &LockProjectInstanceParams{ + HTTPClient: client, + } +} + +/* LockProjectInstanceParams contains all the parameters to send to the API endpoint + for the lock project instance operation. + + Typically these are written to a http.Request. +*/ +type LockProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the lock project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *LockProjectInstanceParams) WithDefaults() *LockProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the lock project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *LockProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the lock project instance params +func (o *LockProjectInstanceParams) WithTimeout(timeout time.Duration) *LockProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the lock project instance params +func (o *LockProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the lock project instance params +func (o *LockProjectInstanceParams) WithContext(ctx context.Context) *LockProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the lock project instance params +func (o *LockProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the lock project instance params +func (o *LockProjectInstanceParams) WithHTTPClient(client *http.Client) *LockProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the lock project instance params +func (o *LockProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the lock project instance params +func (o *LockProjectInstanceParams) WithAuthorization(authorization string) *LockProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the lock project instance params +func (o *LockProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the lock project instance params +func (o *LockProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *LockProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the lock project instance params +func (o *LockProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the lock project instance params +func (o *LockProjectInstanceParams) WithBmpUserID(bmpUserID *string) *LockProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the lock project instance params +func (o *LockProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the lock project instance params +func (o *LockProjectInstanceParams) WithInstanceID(instanceID string) *LockProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the lock project instance params +func (o *LockProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the lock project instance params +func (o *LockProjectInstanceParams) WithTraceID(traceID string) *LockProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the lock project instance params +func (o *LockProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *LockProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/lock_project_instance_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/lock_project_instance_responses.go new file mode 100644 index 0000000..b982db4 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/lock_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// LockProjectInstanceReader is a Reader for the LockProjectInstance structure. +type LockProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *LockProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewLockProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewLockProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewLockProjectInstanceOK creates a LockProjectInstanceOK with default headers values +func NewLockProjectInstanceOK() *LockProjectInstanceOK { + return &LockProjectInstanceOK{} +} + +/* LockProjectInstanceOK describes a response with status code 200, with default header values. + +A LockProjectInstanceResult is an response struct that is used to describe lock instance result. +*/ +type LockProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *LockProjectInstanceOKBody +} + +// IsSuccess returns true when this lock project instance o k response has a 2xx status code +func (o *LockProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this lock project instance o k response has a 3xx status code +func (o *LockProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this lock project instance o k response has a 4xx status code +func (o *LockProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this lock project instance o k response has a 5xx status code +func (o *LockProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this lock project instance o k response a status code equal to that given +func (o *LockProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *LockProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/lock][%d] lockProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *LockProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/lock][%d] lockProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *LockProjectInstanceOK) GetPayload() *LockProjectInstanceOKBody { + return o.Payload +} + +func (o *LockProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(LockProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewLockProjectInstanceDefault creates a LockProjectInstanceDefault with default headers values +func NewLockProjectInstanceDefault(code int) *LockProjectInstanceDefault { + return &LockProjectInstanceDefault{ + _statusCode: code, + } +} + +/* LockProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type LockProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *LockProjectInstanceDefaultBody +} + +// Code gets the status code for the lock project instance default response +func (o *LockProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this lock project instance default response has a 2xx status code +func (o *LockProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this lock project instance default response has a 3xx status code +func (o *LockProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this lock project instance default response has a 4xx status code +func (o *LockProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this lock project instance default response has a 5xx status code +func (o *LockProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this lock project instance default response a status code equal to that given +func (o *LockProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *LockProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/lock][%d] lockProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *LockProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/lock][%d] lockProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *LockProjectInstanceDefault) GetPayload() *LockProjectInstanceDefaultBody { + return o.Payload +} + +func (o *LockProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(LockProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*LockProjectInstanceDefaultBody lock project instance default body +swagger:model LockProjectInstanceDefaultBody +*/ +type LockProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this lock project instance default body +func (o *LockProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *LockProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("lockProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *LockProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("lockProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("lockProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("lockProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this lock project instance default body based on the context it is used +func (o *LockProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *LockProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("lockProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("lockProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *LockProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *LockProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res LockProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*LockProjectInstanceOKBody lock project instance o k body +swagger:model LockProjectInstanceOKBody +*/ +type LockProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this lock project instance o k body +func (o *LockProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *LockProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("lockProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("lockProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this lock project instance o k body based on the context it is used +func (o *LockProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *LockProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("lockProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("lockProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *LockProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *LockProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res LockProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/modify_instances_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/modify_instances_parameters.go new file mode 100644 index 0000000..0d5e7ea --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/modify_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewModifyInstancesParams creates a new ModifyInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyInstancesParams() *ModifyInstancesParams { + return &ModifyInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyInstancesParamsWithTimeout creates a new ModifyInstancesParams object +// with the ability to set a timeout on a request. +func NewModifyInstancesParamsWithTimeout(timeout time.Duration) *ModifyInstancesParams { + return &ModifyInstancesParams{ + timeout: timeout, + } +} + +// NewModifyInstancesParamsWithContext creates a new ModifyInstancesParams object +// with the ability to set a context for a request. +func NewModifyInstancesParamsWithContext(ctx context.Context) *ModifyInstancesParams { + return &ModifyInstancesParams{ + Context: ctx, + } +} + +// NewModifyInstancesParamsWithHTTPClient creates a new ModifyInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyInstancesParamsWithHTTPClient(client *http.Client) *ModifyInstancesParams { + return &ModifyInstancesParams{ + HTTPClient: client, + } +} + +/* ModifyInstancesParams contains all the parameters to send to the API endpoint + for the modify instances operation. + + Typically these are written to a http.Request. +*/ +type ModifyInstancesParams struct { + + // Body. + Body *models.ModifyInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyInstancesParams) WithDefaults() *ModifyInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify instances params +func (o *ModifyInstancesParams) WithTimeout(timeout time.Duration) *ModifyInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify instances params +func (o *ModifyInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify instances params +func (o *ModifyInstancesParams) WithContext(ctx context.Context) *ModifyInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify instances params +func (o *ModifyInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify instances params +func (o *ModifyInstancesParams) WithHTTPClient(client *http.Client) *ModifyInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify instances params +func (o *ModifyInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify instances params +func (o *ModifyInstancesParams) WithBody(body *models.ModifyInstancesRequest) *ModifyInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify instances params +func (o *ModifyInstancesParams) SetBody(body *models.ModifyInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify instances params +func (o *ModifyInstancesParams) WithAuthorization(authorization string) *ModifyInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify instances params +func (o *ModifyInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify instances params +func (o *ModifyInstancesParams) WithBmpLanguage(bmpLanguage *string) *ModifyInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify instances params +func (o *ModifyInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify instances params +func (o *ModifyInstancesParams) WithBmpUserID(bmpUserID *string) *ModifyInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify instances params +func (o *ModifyInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the modify instances params +func (o *ModifyInstancesParams) WithTraceID(traceID string) *ModifyInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify instances params +func (o *ModifyInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/modify_instances_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/modify_instances_responses.go new file mode 100644 index 0000000..e23cac5 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/modify_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// ModifyInstancesReader is a Reader for the ModifyInstances structure. +type ModifyInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyInstancesOK creates a ModifyInstancesOK with default headers values +func NewModifyInstancesOK() *ModifyInstancesOK { + return &ModifyInstancesOK{} +} + +/* ModifyInstancesOK describes a response with status code 200, with default header values. + +A ModifyInstancesResult is an response struct that is used to describe modify instance result. +*/ +type ModifyInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyInstancesOKBody +} + +// IsSuccess returns true when this modify instances o k response has a 2xx status code +func (o *ModifyInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify instances o k response has a 3xx status code +func (o *ModifyInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify instances o k response has a 4xx status code +func (o *ModifyInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify instances o k response has a 5xx status code +func (o *ModifyInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify instances o k response a status code equal to that given +func (o *ModifyInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyInstancesOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:modifyInstances][%d] modifyInstancesOK %+v", 200, o.Payload) +} + +func (o *ModifyInstancesOK) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:modifyInstances][%d] modifyInstancesOK %+v", 200, o.Payload) +} + +func (o *ModifyInstancesOK) GetPayload() *ModifyInstancesOKBody { + return o.Payload +} + +func (o *ModifyInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyInstancesDefault creates a ModifyInstancesDefault with default headers values +func NewModifyInstancesDefault(code int) *ModifyInstancesDefault { + return &ModifyInstancesDefault{ + _statusCode: code, + } +} + +/* ModifyInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyInstancesDefaultBody +} + +// Code gets the status code for the modify instances default response +func (o *ModifyInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify instances default response has a 2xx status code +func (o *ModifyInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify instances default response has a 3xx status code +func (o *ModifyInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify instances default response has a 4xx status code +func (o *ModifyInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify instances default response has a 5xx status code +func (o *ModifyInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify instances default response a status code equal to that given +func (o *ModifyInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyInstancesDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:modifyInstances][%d] modifyInstances default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyInstancesDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:modifyInstances][%d] modifyInstances default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyInstancesDefault) GetPayload() *ModifyInstancesDefaultBody { + return o.Payload +} + +func (o *ModifyInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyInstancesDefaultBody modify instances default body +swagger:model ModifyInstancesDefaultBody +*/ +type ModifyInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify instances default body +func (o *ModifyInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify instances default body based on the context it is used +func (o *ModifyInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyInstancesOKBody modify instances o k body +swagger:model ModifyInstancesOKBody +*/ +type ModifyInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify instances o k body +func (o *ModifyInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify instances o k body based on the context it is used +func (o *ModifyInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyInstancesOKBody) UnmarshalBinary(b []byte) error { + var res ModifyInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/modify_project_instance_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/modify_project_instance_parameters.go new file mode 100644 index 0000000..58a38ee --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/modify_project_instance_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewModifyProjectInstanceParams creates a new ModifyProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyProjectInstanceParams() *ModifyProjectInstanceParams { + return &ModifyProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyProjectInstanceParamsWithTimeout creates a new ModifyProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewModifyProjectInstanceParamsWithTimeout(timeout time.Duration) *ModifyProjectInstanceParams { + return &ModifyProjectInstanceParams{ + timeout: timeout, + } +} + +// NewModifyProjectInstanceParamsWithContext creates a new ModifyProjectInstanceParams object +// with the ability to set a context for a request. +func NewModifyProjectInstanceParamsWithContext(ctx context.Context) *ModifyProjectInstanceParams { + return &ModifyProjectInstanceParams{ + Context: ctx, + } +} + +// NewModifyProjectInstanceParamsWithHTTPClient creates a new ModifyProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyProjectInstanceParamsWithHTTPClient(client *http.Client) *ModifyProjectInstanceParams { + return &ModifyProjectInstanceParams{ + HTTPClient: client, + } +} + +/* ModifyProjectInstanceParams contains all the parameters to send to the API endpoint + for the modify project instance operation. + + Typically these are written to a http.Request. +*/ +type ModifyProjectInstanceParams struct { + + // Body. + Body *models.ModifyInstanceRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyProjectInstanceParams) WithDefaults() *ModifyProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify project instance params +func (o *ModifyProjectInstanceParams) WithTimeout(timeout time.Duration) *ModifyProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify project instance params +func (o *ModifyProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify project instance params +func (o *ModifyProjectInstanceParams) WithContext(ctx context.Context) *ModifyProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify project instance params +func (o *ModifyProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify project instance params +func (o *ModifyProjectInstanceParams) WithHTTPClient(client *http.Client) *ModifyProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify project instance params +func (o *ModifyProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify project instance params +func (o *ModifyProjectInstanceParams) WithBody(body *models.ModifyInstanceRequest) *ModifyProjectInstanceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify project instance params +func (o *ModifyProjectInstanceParams) SetBody(body *models.ModifyInstanceRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify project instance params +func (o *ModifyProjectInstanceParams) WithAuthorization(authorization string) *ModifyProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify project instance params +func (o *ModifyProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify project instance params +func (o *ModifyProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *ModifyProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify project instance params +func (o *ModifyProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify project instance params +func (o *ModifyProjectInstanceParams) WithBmpUserID(bmpUserID *string) *ModifyProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify project instance params +func (o *ModifyProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the modify project instance params +func (o *ModifyProjectInstanceParams) WithInstanceID(instanceID string) *ModifyProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the modify project instance params +func (o *ModifyProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the modify project instance params +func (o *ModifyProjectInstanceParams) WithTraceID(traceID string) *ModifyProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify project instance params +func (o *ModifyProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/modify_project_instance_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/modify_project_instance_responses.go new file mode 100644 index 0000000..553cbc7 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/modify_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// ModifyProjectInstanceReader is a Reader for the ModifyProjectInstance structure. +type ModifyProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyProjectInstanceOK creates a ModifyProjectInstanceOK with default headers values +func NewModifyProjectInstanceOK() *ModifyProjectInstanceOK { + return &ModifyProjectInstanceOK{} +} + +/* ModifyProjectInstanceOK describes a response with status code 200, with default header values. + +A ModifyProjectInstanceResult is an response struct that is used to describe modify instance result. +*/ +type ModifyProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyProjectInstanceOKBody +} + +// IsSuccess returns true when this modify project instance o k response has a 2xx status code +func (o *ModifyProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify project instance o k response has a 3xx status code +func (o *ModifyProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify project instance o k response has a 4xx status code +func (o *ModifyProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify project instance o k response has a 5xx status code +func (o *ModifyProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify project instance o k response a status code equal to that given +func (o *ModifyProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}][%d] modifyProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *ModifyProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}][%d] modifyProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *ModifyProjectInstanceOK) GetPayload() *ModifyProjectInstanceOKBody { + return o.Payload +} + +func (o *ModifyProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyProjectInstanceDefault creates a ModifyProjectInstanceDefault with default headers values +func NewModifyProjectInstanceDefault(code int) *ModifyProjectInstanceDefault { + return &ModifyProjectInstanceDefault{ + _statusCode: code, + } +} + +/* ModifyProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyProjectInstanceDefaultBody +} + +// Code gets the status code for the modify project instance default response +func (o *ModifyProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify project instance default response has a 2xx status code +func (o *ModifyProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify project instance default response has a 3xx status code +func (o *ModifyProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify project instance default response has a 4xx status code +func (o *ModifyProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify project instance default response has a 5xx status code +func (o *ModifyProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify project instance default response a status code equal to that given +func (o *ModifyProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}][%d] modifyProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}][%d] modifyProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyProjectInstanceDefault) GetPayload() *ModifyProjectInstanceDefaultBody { + return o.Payload +} + +func (o *ModifyProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyProjectInstanceDefaultBody modify project instance default body +swagger:model ModifyProjectInstanceDefaultBody +*/ +type ModifyProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify project instance default body +func (o *ModifyProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify project instance default body based on the context it is used +func (o *ModifyProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyProjectInstanceOKBody modify project instance o k body +swagger:model ModifyProjectInstanceOKBody +*/ +type ModifyProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify project instance o k body +func (o *ModifyProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify project instance o k body based on the context it is used +func (o *ModifyProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res ModifyProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reinstall_project_instance_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reinstall_project_instance_parameters.go new file mode 100644 index 0000000..d0b5182 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reinstall_project_instance_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewReinstallProjectInstanceParams creates a new ReinstallProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewReinstallProjectInstanceParams() *ReinstallProjectInstanceParams { + return &ReinstallProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewReinstallProjectInstanceParamsWithTimeout creates a new ReinstallProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewReinstallProjectInstanceParamsWithTimeout(timeout time.Duration) *ReinstallProjectInstanceParams { + return &ReinstallProjectInstanceParams{ + timeout: timeout, + } +} + +// NewReinstallProjectInstanceParamsWithContext creates a new ReinstallProjectInstanceParams object +// with the ability to set a context for a request. +func NewReinstallProjectInstanceParamsWithContext(ctx context.Context) *ReinstallProjectInstanceParams { + return &ReinstallProjectInstanceParams{ + Context: ctx, + } +} + +// NewReinstallProjectInstanceParamsWithHTTPClient creates a new ReinstallProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewReinstallProjectInstanceParamsWithHTTPClient(client *http.Client) *ReinstallProjectInstanceParams { + return &ReinstallProjectInstanceParams{ + HTTPClient: client, + } +} + +/* ReinstallProjectInstanceParams contains all the parameters to send to the API endpoint + for the reinstall project instance operation. + + Typically these are written to a http.Request. +*/ +type ReinstallProjectInstanceParams struct { + + // Body. + Body *models.ReinstallInstanceRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the reinstall project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ReinstallProjectInstanceParams) WithDefaults() *ReinstallProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the reinstall project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ReinstallProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithTimeout(timeout time.Duration) *ReinstallProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithContext(ctx context.Context) *ReinstallProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithHTTPClient(client *http.Client) *ReinstallProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithBody(body *models.ReinstallInstanceRequest) *ReinstallProjectInstanceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetBody(body *models.ReinstallInstanceRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithAuthorization(authorization string) *ReinstallProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *ReinstallProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithBmpUserID(bmpUserID *string) *ReinstallProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithInstanceID(instanceID string) *ReinstallProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithTraceID(traceID string) *ReinstallProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ReinstallProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reinstall_project_instance_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reinstall_project_instance_responses.go new file mode 100644 index 0000000..76a56bf --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reinstall_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// ReinstallProjectInstanceReader is a Reader for the ReinstallProjectInstance structure. +type ReinstallProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ReinstallProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewReinstallProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewReinstallProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewReinstallProjectInstanceOK creates a ReinstallProjectInstanceOK with default headers values +func NewReinstallProjectInstanceOK() *ReinstallProjectInstanceOK { + return &ReinstallProjectInstanceOK{} +} + +/* ReinstallProjectInstanceOK describes a response with status code 200, with default header values. + +A ReinstallProjectInstanceResult is an response struct that is used to describe reinstall instance. +*/ +type ReinstallProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ReinstallProjectInstanceOKBody +} + +// IsSuccess returns true when this reinstall project instance o k response has a 2xx status code +func (o *ReinstallProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this reinstall project instance o k response has a 3xx status code +func (o *ReinstallProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this reinstall project instance o k response has a 4xx status code +func (o *ReinstallProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this reinstall project instance o k response has a 5xx status code +func (o *ReinstallProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this reinstall project instance o k response a status code equal to that given +func (o *ReinstallProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ReinstallProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/reinstallInstance][%d] reinstallProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *ReinstallProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/reinstallInstance][%d] reinstallProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *ReinstallProjectInstanceOK) GetPayload() *ReinstallProjectInstanceOKBody { + return o.Payload +} + +func (o *ReinstallProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ReinstallProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewReinstallProjectInstanceDefault creates a ReinstallProjectInstanceDefault with default headers values +func NewReinstallProjectInstanceDefault(code int) *ReinstallProjectInstanceDefault { + return &ReinstallProjectInstanceDefault{ + _statusCode: code, + } +} + +/* ReinstallProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ReinstallProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ReinstallProjectInstanceDefaultBody +} + +// Code gets the status code for the reinstall project instance default response +func (o *ReinstallProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this reinstall project instance default response has a 2xx status code +func (o *ReinstallProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this reinstall project instance default response has a 3xx status code +func (o *ReinstallProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this reinstall project instance default response has a 4xx status code +func (o *ReinstallProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this reinstall project instance default response has a 5xx status code +func (o *ReinstallProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this reinstall project instance default response a status code equal to that given +func (o *ReinstallProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ReinstallProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/reinstallInstance][%d] reinstallProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *ReinstallProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/reinstallInstance][%d] reinstallProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *ReinstallProjectInstanceDefault) GetPayload() *ReinstallProjectInstanceDefaultBody { + return o.Payload +} + +func (o *ReinstallProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ReinstallProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ReinstallProjectInstanceDefaultBody reinstall project instance default body +swagger:model ReinstallProjectInstanceDefaultBody +*/ +type ReinstallProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this reinstall project instance default body +func (o *ReinstallProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReinstallProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("reinstallProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ReinstallProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("reinstallProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("reinstallProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("reinstallProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reinstall project instance default body based on the context it is used +func (o *ReinstallProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReinstallProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("reinstallProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("reinstallProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ReinstallProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ReinstallProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res ReinstallProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ReinstallProjectInstanceOKBody reinstall project instance o k body +swagger:model ReinstallProjectInstanceOKBody +*/ +type ReinstallProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this reinstall project instance o k body +func (o *ReinstallProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReinstallProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("reinstallProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("reinstallProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reinstall project instance o k body based on the context it is used +func (o *ReinstallProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReinstallProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("reinstallProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("reinstallProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ReinstallProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ReinstallProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res ReinstallProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_instance_status_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_instance_status_parameters.go new file mode 100644 index 0000000..853f1fe --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_instance_status_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewResetInstanceStatusParams creates a new ResetInstanceStatusParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewResetInstanceStatusParams() *ResetInstanceStatusParams { + return &ResetInstanceStatusParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewResetInstanceStatusParamsWithTimeout creates a new ResetInstanceStatusParams object +// with the ability to set a timeout on a request. +func NewResetInstanceStatusParamsWithTimeout(timeout time.Duration) *ResetInstanceStatusParams { + return &ResetInstanceStatusParams{ + timeout: timeout, + } +} + +// NewResetInstanceStatusParamsWithContext creates a new ResetInstanceStatusParams object +// with the ability to set a context for a request. +func NewResetInstanceStatusParamsWithContext(ctx context.Context) *ResetInstanceStatusParams { + return &ResetInstanceStatusParams{ + Context: ctx, + } +} + +// NewResetInstanceStatusParamsWithHTTPClient creates a new ResetInstanceStatusParams object +// with the ability to set a custom HTTPClient for a request. +func NewResetInstanceStatusParamsWithHTTPClient(client *http.Client) *ResetInstanceStatusParams { + return &ResetInstanceStatusParams{ + HTTPClient: client, + } +} + +/* ResetInstanceStatusParams contains all the parameters to send to the API endpoint + for the reset instance status operation. + + Typically these are written to a http.Request. +*/ +type ResetInstanceStatusParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the reset instance status params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetInstanceStatusParams) WithDefaults() *ResetInstanceStatusParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the reset instance status params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetInstanceStatusParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the reset instance status params +func (o *ResetInstanceStatusParams) WithTimeout(timeout time.Duration) *ResetInstanceStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the reset instance status params +func (o *ResetInstanceStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the reset instance status params +func (o *ResetInstanceStatusParams) WithContext(ctx context.Context) *ResetInstanceStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the reset instance status params +func (o *ResetInstanceStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the reset instance status params +func (o *ResetInstanceStatusParams) WithHTTPClient(client *http.Client) *ResetInstanceStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the reset instance status params +func (o *ResetInstanceStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the reset instance status params +func (o *ResetInstanceStatusParams) WithAuthorization(authorization string) *ResetInstanceStatusParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the reset instance status params +func (o *ResetInstanceStatusParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the reset instance status params +func (o *ResetInstanceStatusParams) WithBmpLanguage(bmpLanguage *string) *ResetInstanceStatusParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the reset instance status params +func (o *ResetInstanceStatusParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the reset instance status params +func (o *ResetInstanceStatusParams) WithBmpUserID(bmpUserID *string) *ResetInstanceStatusParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the reset instance status params +func (o *ResetInstanceStatusParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the reset instance status params +func (o *ResetInstanceStatusParams) WithInstanceID(instanceID string) *ResetInstanceStatusParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the reset instance status params +func (o *ResetInstanceStatusParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the reset instance status params +func (o *ResetInstanceStatusParams) WithTraceID(traceID string) *ResetInstanceStatusParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the reset instance status params +func (o *ResetInstanceStatusParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ResetInstanceStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_instance_status_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_instance_status_responses.go new file mode 100644 index 0000000..0620207 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_instance_status_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// ResetInstanceStatusReader is a Reader for the ResetInstanceStatus structure. +type ResetInstanceStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ResetInstanceStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewResetInstanceStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewResetInstanceStatusDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewResetInstanceStatusOK creates a ResetInstanceStatusOK with default headers values +func NewResetInstanceStatusOK() *ResetInstanceStatusOK { + return &ResetInstanceStatusOK{} +} + +/* ResetInstanceStatusOK describes a response with status code 200, with default header values. + +A ResetInstanceStatusResult is an response struct that is used to describe restart instance result. +*/ +type ResetInstanceStatusOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetInstanceStatusOKBody +} + +// IsSuccess returns true when this reset instance status o k response has a 2xx status code +func (o *ResetInstanceStatusOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this reset instance status o k response has a 3xx status code +func (o *ResetInstanceStatusOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this reset instance status o k response has a 4xx status code +func (o *ResetInstanceStatusOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this reset instance status o k response has a 5xx status code +func (o *ResetInstanceStatusOK) IsServerError() bool { + return false +} + +// IsCode returns true when this reset instance status o k response a status code equal to that given +func (o *ResetInstanceStatusOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ResetInstanceStatusOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetStatus][%d] resetInstanceStatusOK %+v", 200, o.Payload) +} + +func (o *ResetInstanceStatusOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetStatus][%d] resetInstanceStatusOK %+v", 200, o.Payload) +} + +func (o *ResetInstanceStatusOK) GetPayload() *ResetInstanceStatusOKBody { + return o.Payload +} + +func (o *ResetInstanceStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetInstanceStatusOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewResetInstanceStatusDefault creates a ResetInstanceStatusDefault with default headers values +func NewResetInstanceStatusDefault(code int) *ResetInstanceStatusDefault { + return &ResetInstanceStatusDefault{ + _statusCode: code, + } +} + +/* ResetInstanceStatusDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ResetInstanceStatusDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetInstanceStatusDefaultBody +} + +// Code gets the status code for the reset instance status default response +func (o *ResetInstanceStatusDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this reset instance status default response has a 2xx status code +func (o *ResetInstanceStatusDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this reset instance status default response has a 3xx status code +func (o *ResetInstanceStatusDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this reset instance status default response has a 4xx status code +func (o *ResetInstanceStatusDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this reset instance status default response has a 5xx status code +func (o *ResetInstanceStatusDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this reset instance status default response a status code equal to that given +func (o *ResetInstanceStatusDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ResetInstanceStatusDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetStatus][%d] resetInstanceStatus default %+v", o._statusCode, o.Payload) +} + +func (o *ResetInstanceStatusDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetStatus][%d] resetInstanceStatus default %+v", o._statusCode, o.Payload) +} + +func (o *ResetInstanceStatusDefault) GetPayload() *ResetInstanceStatusDefaultBody { + return o.Payload +} + +func (o *ResetInstanceStatusDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetInstanceStatusDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ResetInstanceStatusDefaultBody reset instance status default body +swagger:model ResetInstanceStatusDefaultBody +*/ +type ResetInstanceStatusDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this reset instance status default body +func (o *ResetInstanceStatusDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetInstanceStatusDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("resetInstanceStatus default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ResetInstanceStatusDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("resetInstanceStatus default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetInstanceStatus default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetInstanceStatus default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset instance status default body based on the context it is used +func (o *ResetInstanceStatusDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetInstanceStatusDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetInstanceStatus default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetInstanceStatus default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetInstanceStatusDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetInstanceStatusDefaultBody) UnmarshalBinary(b []byte) error { + var res ResetInstanceStatusDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ResetInstanceStatusOKBody reset instance status o k body +swagger:model ResetInstanceStatusOKBody +*/ +type ResetInstanceStatusOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this reset instance status o k body +func (o *ResetInstanceStatusOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetInstanceStatusOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetInstanceStatusOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetInstanceStatusOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset instance status o k body based on the context it is used +func (o *ResetInstanceStatusOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetInstanceStatusOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetInstanceStatusOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetInstanceStatusOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetInstanceStatusOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetInstanceStatusOKBody) UnmarshalBinary(b []byte) error { + var res ResetInstanceStatusOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_project_instance_passwd_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_project_instance_passwd_parameters.go new file mode 100644 index 0000000..1909bc0 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_project_instance_passwd_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewResetProjectInstancePasswdParams creates a new ResetProjectInstancePasswdParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewResetProjectInstancePasswdParams() *ResetProjectInstancePasswdParams { + return &ResetProjectInstancePasswdParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewResetProjectInstancePasswdParamsWithTimeout creates a new ResetProjectInstancePasswdParams object +// with the ability to set a timeout on a request. +func NewResetProjectInstancePasswdParamsWithTimeout(timeout time.Duration) *ResetProjectInstancePasswdParams { + return &ResetProjectInstancePasswdParams{ + timeout: timeout, + } +} + +// NewResetProjectInstancePasswdParamsWithContext creates a new ResetProjectInstancePasswdParams object +// with the ability to set a context for a request. +func NewResetProjectInstancePasswdParamsWithContext(ctx context.Context) *ResetProjectInstancePasswdParams { + return &ResetProjectInstancePasswdParams{ + Context: ctx, + } +} + +// NewResetProjectInstancePasswdParamsWithHTTPClient creates a new ResetProjectInstancePasswdParams object +// with the ability to set a custom HTTPClient for a request. +func NewResetProjectInstancePasswdParamsWithHTTPClient(client *http.Client) *ResetProjectInstancePasswdParams { + return &ResetProjectInstancePasswdParams{ + HTTPClient: client, + } +} + +/* ResetProjectInstancePasswdParams contains all the parameters to send to the API endpoint + for the reset project instance passwd operation. + + Typically these are written to a http.Request. +*/ +type ResetProjectInstancePasswdParams struct { + + // Body. + Body *models.ResetInstancePasswdRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the reset project instance passwd params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetProjectInstancePasswdParams) WithDefaults() *ResetProjectInstancePasswdParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the reset project instance passwd params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetProjectInstancePasswdParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithTimeout(timeout time.Duration) *ResetProjectInstancePasswdParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithContext(ctx context.Context) *ResetProjectInstancePasswdParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithHTTPClient(client *http.Client) *ResetProjectInstancePasswdParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithBody(body *models.ResetInstancePasswdRequest) *ResetProjectInstancePasswdParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetBody(body *models.ResetInstancePasswdRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithAuthorization(authorization string) *ResetProjectInstancePasswdParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithBmpLanguage(bmpLanguage *string) *ResetProjectInstancePasswdParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithBmpUserID(bmpUserID *string) *ResetProjectInstancePasswdParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithInstanceID(instanceID string) *ResetProjectInstancePasswdParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithTraceID(traceID string) *ResetProjectInstancePasswdParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ResetProjectInstancePasswdParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_project_instance_passwd_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_project_instance_passwd_responses.go new file mode 100644 index 0000000..f3c9d2b --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_project_instance_passwd_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// ResetProjectInstancePasswdReader is a Reader for the ResetProjectInstancePasswd structure. +type ResetProjectInstancePasswdReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ResetProjectInstancePasswdReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewResetProjectInstancePasswdOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewResetProjectInstancePasswdDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewResetProjectInstancePasswdOK creates a ResetProjectInstancePasswdOK with default headers values +func NewResetProjectInstancePasswdOK() *ResetProjectInstancePasswdOK { + return &ResetProjectInstancePasswdOK{} +} + +/* ResetProjectInstancePasswdOK describes a response with status code 200, with default header values. + +A ResetProjectInstancePasswdResult is an response struct that is used to describe reset instance password. +*/ +type ResetProjectInstancePasswdOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetProjectInstancePasswdOKBody +} + +// IsSuccess returns true when this reset project instance passwd o k response has a 2xx status code +func (o *ResetProjectInstancePasswdOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this reset project instance passwd o k response has a 3xx status code +func (o *ResetProjectInstancePasswdOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this reset project instance passwd o k response has a 4xx status code +func (o *ResetProjectInstancePasswdOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this reset project instance passwd o k response has a 5xx status code +func (o *ResetProjectInstancePasswdOK) IsServerError() bool { + return false +} + +// IsCode returns true when this reset project instance passwd o k response a status code equal to that given +func (o *ResetProjectInstancePasswdOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ResetProjectInstancePasswdOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetpasswd][%d] resetProjectInstancePasswdOK %+v", 200, o.Payload) +} + +func (o *ResetProjectInstancePasswdOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetpasswd][%d] resetProjectInstancePasswdOK %+v", 200, o.Payload) +} + +func (o *ResetProjectInstancePasswdOK) GetPayload() *ResetProjectInstancePasswdOKBody { + return o.Payload +} + +func (o *ResetProjectInstancePasswdOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetProjectInstancePasswdOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewResetProjectInstancePasswdDefault creates a ResetProjectInstancePasswdDefault with default headers values +func NewResetProjectInstancePasswdDefault(code int) *ResetProjectInstancePasswdDefault { + return &ResetProjectInstancePasswdDefault{ + _statusCode: code, + } +} + +/* ResetProjectInstancePasswdDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ResetProjectInstancePasswdDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetProjectInstancePasswdDefaultBody +} + +// Code gets the status code for the reset project instance passwd default response +func (o *ResetProjectInstancePasswdDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this reset project instance passwd default response has a 2xx status code +func (o *ResetProjectInstancePasswdDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this reset project instance passwd default response has a 3xx status code +func (o *ResetProjectInstancePasswdDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this reset project instance passwd default response has a 4xx status code +func (o *ResetProjectInstancePasswdDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this reset project instance passwd default response has a 5xx status code +func (o *ResetProjectInstancePasswdDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this reset project instance passwd default response a status code equal to that given +func (o *ResetProjectInstancePasswdDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ResetProjectInstancePasswdDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetpasswd][%d] resetProjectInstancePasswd default %+v", o._statusCode, o.Payload) +} + +func (o *ResetProjectInstancePasswdDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetpasswd][%d] resetProjectInstancePasswd default %+v", o._statusCode, o.Payload) +} + +func (o *ResetProjectInstancePasswdDefault) GetPayload() *ResetProjectInstancePasswdDefaultBody { + return o.Payload +} + +func (o *ResetProjectInstancePasswdDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetProjectInstancePasswdDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ResetProjectInstancePasswdDefaultBody reset project instance passwd default body +swagger:model ResetProjectInstancePasswdDefaultBody +*/ +type ResetProjectInstancePasswdDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this reset project instance passwd default body +func (o *ResetProjectInstancePasswdDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancePasswdDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("resetProjectInstancePasswd default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ResetProjectInstancePasswdDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("resetProjectInstancePasswd default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancePasswd default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancePasswd default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset project instance passwd default body based on the context it is used +func (o *ResetProjectInstancePasswdDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancePasswdDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancePasswd default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancePasswd default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetProjectInstancePasswdDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetProjectInstancePasswdDefaultBody) UnmarshalBinary(b []byte) error { + var res ResetProjectInstancePasswdDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ResetProjectInstancePasswdOKBody reset project instance passwd o k body +swagger:model ResetProjectInstancePasswdOKBody +*/ +type ResetProjectInstancePasswdOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this reset project instance passwd o k body +func (o *ResetProjectInstancePasswdOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancePasswdOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancePasswdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancePasswdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset project instance passwd o k body based on the context it is used +func (o *ResetProjectInstancePasswdOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancePasswdOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancePasswdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancePasswdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetProjectInstancePasswdOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetProjectInstancePasswdOKBody) UnmarshalBinary(b []byte) error { + var res ResetProjectInstancePasswdOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_project_instances_passwd_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_project_instances_passwd_parameters.go new file mode 100644 index 0000000..60207e2 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_project_instances_passwd_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewResetProjectInstancesPasswdParams creates a new ResetProjectInstancesPasswdParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewResetProjectInstancesPasswdParams() *ResetProjectInstancesPasswdParams { + return &ResetProjectInstancesPasswdParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewResetProjectInstancesPasswdParamsWithTimeout creates a new ResetProjectInstancesPasswdParams object +// with the ability to set a timeout on a request. +func NewResetProjectInstancesPasswdParamsWithTimeout(timeout time.Duration) *ResetProjectInstancesPasswdParams { + return &ResetProjectInstancesPasswdParams{ + timeout: timeout, + } +} + +// NewResetProjectInstancesPasswdParamsWithContext creates a new ResetProjectInstancesPasswdParams object +// with the ability to set a context for a request. +func NewResetProjectInstancesPasswdParamsWithContext(ctx context.Context) *ResetProjectInstancesPasswdParams { + return &ResetProjectInstancesPasswdParams{ + Context: ctx, + } +} + +// NewResetProjectInstancesPasswdParamsWithHTTPClient creates a new ResetProjectInstancesPasswdParams object +// with the ability to set a custom HTTPClient for a request. +func NewResetProjectInstancesPasswdParamsWithHTTPClient(client *http.Client) *ResetProjectInstancesPasswdParams { + return &ResetProjectInstancesPasswdParams{ + HTTPClient: client, + } +} + +/* ResetProjectInstancesPasswdParams contains all the parameters to send to the API endpoint + for the reset project instances passwd operation. + + Typically these are written to a http.Request. +*/ +type ResetProjectInstancesPasswdParams struct { + + // Body. + Body *models.ResetInstancesPasswdRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the reset project instances passwd params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetProjectInstancesPasswdParams) WithDefaults() *ResetProjectInstancesPasswdParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the reset project instances passwd params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetProjectInstancesPasswdParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithTimeout(timeout time.Duration) *ResetProjectInstancesPasswdParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithContext(ctx context.Context) *ResetProjectInstancesPasswdParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithHTTPClient(client *http.Client) *ResetProjectInstancesPasswdParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithBody(body *models.ResetInstancesPasswdRequest) *ResetProjectInstancesPasswdParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetBody(body *models.ResetInstancesPasswdRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithAuthorization(authorization string) *ResetProjectInstancesPasswdParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithBmpLanguage(bmpLanguage *string) *ResetProjectInstancesPasswdParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithBmpUserID(bmpUserID *string) *ResetProjectInstancesPasswdParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithTraceID(traceID string) *ResetProjectInstancesPasswdParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ResetProjectInstancesPasswdParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_project_instances_passwd_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_project_instances_passwd_responses.go new file mode 100644 index 0000000..4a94ea4 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/reset_project_instances_passwd_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// ResetProjectInstancesPasswdReader is a Reader for the ResetProjectInstancesPasswd structure. +type ResetProjectInstancesPasswdReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ResetProjectInstancesPasswdReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewResetProjectInstancesPasswdOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewResetProjectInstancesPasswdDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewResetProjectInstancesPasswdOK creates a ResetProjectInstancesPasswdOK with default headers values +func NewResetProjectInstancesPasswdOK() *ResetProjectInstancesPasswdOK { + return &ResetProjectInstancesPasswdOK{} +} + +/* ResetProjectInstancesPasswdOK describes a response with status code 200, with default header values. + +A ResetProjectInstancesPasswdResult is an response struct that is used to describe reset instance password. +*/ +type ResetProjectInstancesPasswdOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetProjectInstancesPasswdOKBody +} + +// IsSuccess returns true when this reset project instances passwd o k response has a 2xx status code +func (o *ResetProjectInstancesPasswdOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this reset project instances passwd o k response has a 3xx status code +func (o *ResetProjectInstancesPasswdOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this reset project instances passwd o k response has a 4xx status code +func (o *ResetProjectInstancesPasswdOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this reset project instances passwd o k response has a 5xx status code +func (o *ResetProjectInstancesPasswdOK) IsServerError() bool { + return false +} + +// IsCode returns true when this reset project instances passwd o k response a status code equal to that given +func (o *ResetProjectInstancesPasswdOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ResetProjectInstancesPasswdOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:resetPasswd][%d] resetProjectInstancesPasswdOK %+v", 200, o.Payload) +} + +func (o *ResetProjectInstancesPasswdOK) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:resetPasswd][%d] resetProjectInstancesPasswdOK %+v", 200, o.Payload) +} + +func (o *ResetProjectInstancesPasswdOK) GetPayload() *ResetProjectInstancesPasswdOKBody { + return o.Payload +} + +func (o *ResetProjectInstancesPasswdOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetProjectInstancesPasswdOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewResetProjectInstancesPasswdDefault creates a ResetProjectInstancesPasswdDefault with default headers values +func NewResetProjectInstancesPasswdDefault(code int) *ResetProjectInstancesPasswdDefault { + return &ResetProjectInstancesPasswdDefault{ + _statusCode: code, + } +} + +/* ResetProjectInstancesPasswdDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ResetProjectInstancesPasswdDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetProjectInstancesPasswdDefaultBody +} + +// Code gets the status code for the reset project instances passwd default response +func (o *ResetProjectInstancesPasswdDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this reset project instances passwd default response has a 2xx status code +func (o *ResetProjectInstancesPasswdDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this reset project instances passwd default response has a 3xx status code +func (o *ResetProjectInstancesPasswdDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this reset project instances passwd default response has a 4xx status code +func (o *ResetProjectInstancesPasswdDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this reset project instances passwd default response has a 5xx status code +func (o *ResetProjectInstancesPasswdDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this reset project instances passwd default response a status code equal to that given +func (o *ResetProjectInstancesPasswdDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ResetProjectInstancesPasswdDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:resetPasswd][%d] resetProjectInstancesPasswd default %+v", o._statusCode, o.Payload) +} + +func (o *ResetProjectInstancesPasswdDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:resetPasswd][%d] resetProjectInstancesPasswd default %+v", o._statusCode, o.Payload) +} + +func (o *ResetProjectInstancesPasswdDefault) GetPayload() *ResetProjectInstancesPasswdDefaultBody { + return o.Payload +} + +func (o *ResetProjectInstancesPasswdDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetProjectInstancesPasswdDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ResetProjectInstancesPasswdDefaultBody reset project instances passwd default body +swagger:model ResetProjectInstancesPasswdDefaultBody +*/ +type ResetProjectInstancesPasswdDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this reset project instances passwd default body +func (o *ResetProjectInstancesPasswdDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancesPasswdDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("resetProjectInstancesPasswd default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ResetProjectInstancesPasswdDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("resetProjectInstancesPasswd default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancesPasswd default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancesPasswd default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset project instances passwd default body based on the context it is used +func (o *ResetProjectInstancesPasswdDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancesPasswdDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancesPasswd default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancesPasswd default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetProjectInstancesPasswdDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetProjectInstancesPasswdDefaultBody) UnmarshalBinary(b []byte) error { + var res ResetProjectInstancesPasswdDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ResetProjectInstancesPasswdOKBody reset project instances passwd o k body +swagger:model ResetProjectInstancesPasswdOKBody +*/ +type ResetProjectInstancesPasswdOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this reset project instances passwd o k body +func (o *ResetProjectInstancesPasswdOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancesPasswdOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancesPasswdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancesPasswdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset project instances passwd o k body based on the context it is used +func (o *ResetProjectInstancesPasswdOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancesPasswdOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancesPasswdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancesPasswdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetProjectInstancesPasswdOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetProjectInstancesPasswdOKBody) UnmarshalBinary(b []byte) error { + var res ResetProjectInstancesPasswdOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/restart_instances_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/restart_instances_parameters.go new file mode 100644 index 0000000..3d7419c --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/restart_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewRestartInstancesParams creates a new RestartInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewRestartInstancesParams() *RestartInstancesParams { + return &RestartInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewRestartInstancesParamsWithTimeout creates a new RestartInstancesParams object +// with the ability to set a timeout on a request. +func NewRestartInstancesParamsWithTimeout(timeout time.Duration) *RestartInstancesParams { + return &RestartInstancesParams{ + timeout: timeout, + } +} + +// NewRestartInstancesParamsWithContext creates a new RestartInstancesParams object +// with the ability to set a context for a request. +func NewRestartInstancesParamsWithContext(ctx context.Context) *RestartInstancesParams { + return &RestartInstancesParams{ + Context: ctx, + } +} + +// NewRestartInstancesParamsWithHTTPClient creates a new RestartInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewRestartInstancesParamsWithHTTPClient(client *http.Client) *RestartInstancesParams { + return &RestartInstancesParams{ + HTTPClient: client, + } +} + +/* RestartInstancesParams contains all the parameters to send to the API endpoint + for the restart instances operation. + + Typically these are written to a http.Request. +*/ +type RestartInstancesParams struct { + + // Body. + Body *models.RestartInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the restart instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RestartInstancesParams) WithDefaults() *RestartInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the restart instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RestartInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the restart instances params +func (o *RestartInstancesParams) WithTimeout(timeout time.Duration) *RestartInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the restart instances params +func (o *RestartInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the restart instances params +func (o *RestartInstancesParams) WithContext(ctx context.Context) *RestartInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the restart instances params +func (o *RestartInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the restart instances params +func (o *RestartInstancesParams) WithHTTPClient(client *http.Client) *RestartInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the restart instances params +func (o *RestartInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the restart instances params +func (o *RestartInstancesParams) WithBody(body *models.RestartInstancesRequest) *RestartInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the restart instances params +func (o *RestartInstancesParams) SetBody(body *models.RestartInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the restart instances params +func (o *RestartInstancesParams) WithAuthorization(authorization string) *RestartInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the restart instances params +func (o *RestartInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the restart instances params +func (o *RestartInstancesParams) WithBmpLanguage(bmpLanguage *string) *RestartInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the restart instances params +func (o *RestartInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the restart instances params +func (o *RestartInstancesParams) WithBmpUserID(bmpUserID *string) *RestartInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the restart instances params +func (o *RestartInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the restart instances params +func (o *RestartInstancesParams) WithTraceID(traceID string) *RestartInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the restart instances params +func (o *RestartInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *RestartInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/restart_instances_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/restart_instances_responses.go new file mode 100644 index 0000000..c7ad946 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/restart_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// RestartInstancesReader is a Reader for the RestartInstances structure. +type RestartInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *RestartInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewRestartInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewRestartInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewRestartInstancesOK creates a RestartInstancesOK with default headers values +func NewRestartInstancesOK() *RestartInstancesOK { + return &RestartInstancesOK{} +} + +/* RestartInstancesOK describes a response with status code 200, with default header values. + +A RestartInstancesResult is an response struct +*/ +type RestartInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *RestartInstancesOKBody +} + +// IsSuccess returns true when this restart instances o k response has a 2xx status code +func (o *RestartInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this restart instances o k response has a 3xx status code +func (o *RestartInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this restart instances o k response has a 4xx status code +func (o *RestartInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this restart instances o k response has a 5xx status code +func (o *RestartInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this restart instances o k response a status code equal to that given +func (o *RestartInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *RestartInstancesOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:restartInstances][%d] restartInstancesOK %+v", 200, o.Payload) +} + +func (o *RestartInstancesOK) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:restartInstances][%d] restartInstancesOK %+v", 200, o.Payload) +} + +func (o *RestartInstancesOK) GetPayload() *RestartInstancesOKBody { + return o.Payload +} + +func (o *RestartInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RestartInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewRestartInstancesDefault creates a RestartInstancesDefault with default headers values +func NewRestartInstancesDefault(code int) *RestartInstancesDefault { + return &RestartInstancesDefault{ + _statusCode: code, + } +} + +/* RestartInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type RestartInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *RestartInstancesDefaultBody +} + +// Code gets the status code for the restart instances default response +func (o *RestartInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this restart instances default response has a 2xx status code +func (o *RestartInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this restart instances default response has a 3xx status code +func (o *RestartInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this restart instances default response has a 4xx status code +func (o *RestartInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this restart instances default response has a 5xx status code +func (o *RestartInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this restart instances default response a status code equal to that given +func (o *RestartInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *RestartInstancesDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:restartInstances][%d] restartInstances default %+v", o._statusCode, o.Payload) +} + +func (o *RestartInstancesDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:restartInstances][%d] restartInstances default %+v", o._statusCode, o.Payload) +} + +func (o *RestartInstancesDefault) GetPayload() *RestartInstancesDefaultBody { + return o.Payload +} + +func (o *RestartInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RestartInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*RestartInstancesDefaultBody restart instances default body +swagger:model RestartInstancesDefaultBody +*/ +type RestartInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this restart instances default body +func (o *RestartInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("restartInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *RestartInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("restartInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this restart instances default body based on the context it is used +func (o *RestartInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RestartInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RestartInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res RestartInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*RestartInstancesOKBody restart instances o k body +swagger:model RestartInstancesOKBody +*/ +type RestartInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this restart instances o k body +func (o *RestartInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this restart instances o k body based on the context it is used +func (o *RestartInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RestartInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RestartInstancesOKBody) UnmarshalBinary(b []byte) error { + var res RestartInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/restart_project_instance_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/restart_project_instance_parameters.go new file mode 100644 index 0000000..d1b78b2 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/restart_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewRestartProjectInstanceParams creates a new RestartProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewRestartProjectInstanceParams() *RestartProjectInstanceParams { + return &RestartProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewRestartProjectInstanceParamsWithTimeout creates a new RestartProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewRestartProjectInstanceParamsWithTimeout(timeout time.Duration) *RestartProjectInstanceParams { + return &RestartProjectInstanceParams{ + timeout: timeout, + } +} + +// NewRestartProjectInstanceParamsWithContext creates a new RestartProjectInstanceParams object +// with the ability to set a context for a request. +func NewRestartProjectInstanceParamsWithContext(ctx context.Context) *RestartProjectInstanceParams { + return &RestartProjectInstanceParams{ + Context: ctx, + } +} + +// NewRestartProjectInstanceParamsWithHTTPClient creates a new RestartProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewRestartProjectInstanceParamsWithHTTPClient(client *http.Client) *RestartProjectInstanceParams { + return &RestartProjectInstanceParams{ + HTTPClient: client, + } +} + +/* RestartProjectInstanceParams contains all the parameters to send to the API endpoint + for the restart project instance operation. + + Typically these are written to a http.Request. +*/ +type RestartProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the restart project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RestartProjectInstanceParams) WithDefaults() *RestartProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the restart project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RestartProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the restart project instance params +func (o *RestartProjectInstanceParams) WithTimeout(timeout time.Duration) *RestartProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the restart project instance params +func (o *RestartProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the restart project instance params +func (o *RestartProjectInstanceParams) WithContext(ctx context.Context) *RestartProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the restart project instance params +func (o *RestartProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the restart project instance params +func (o *RestartProjectInstanceParams) WithHTTPClient(client *http.Client) *RestartProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the restart project instance params +func (o *RestartProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the restart project instance params +func (o *RestartProjectInstanceParams) WithAuthorization(authorization string) *RestartProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the restart project instance params +func (o *RestartProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the restart project instance params +func (o *RestartProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *RestartProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the restart project instance params +func (o *RestartProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the restart project instance params +func (o *RestartProjectInstanceParams) WithBmpUserID(bmpUserID *string) *RestartProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the restart project instance params +func (o *RestartProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the restart project instance params +func (o *RestartProjectInstanceParams) WithInstanceID(instanceID string) *RestartProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the restart project instance params +func (o *RestartProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the restart project instance params +func (o *RestartProjectInstanceParams) WithTraceID(traceID string) *RestartProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the restart project instance params +func (o *RestartProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *RestartProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/restart_project_instance_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/restart_project_instance_responses.go new file mode 100644 index 0000000..c1f0e62 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/restart_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// RestartProjectInstanceReader is a Reader for the RestartProjectInstance structure. +type RestartProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *RestartProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewRestartProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewRestartProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewRestartProjectInstanceOK creates a RestartProjectInstanceOK with default headers values +func NewRestartProjectInstanceOK() *RestartProjectInstanceOK { + return &RestartProjectInstanceOK{} +} + +/* RestartProjectInstanceOK describes a response with status code 200, with default header values. + +A RestartProjectInstanceResult is an response struct that is used to describe restart instance result. +*/ +type RestartProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *RestartProjectInstanceOKBody +} + +// IsSuccess returns true when this restart project instance o k response has a 2xx status code +func (o *RestartProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this restart project instance o k response has a 3xx status code +func (o *RestartProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this restart project instance o k response has a 4xx status code +func (o *RestartProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this restart project instance o k response has a 5xx status code +func (o *RestartProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this restart project instance o k response a status code equal to that given +func (o *RestartProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *RestartProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/restart][%d] restartProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *RestartProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/restart][%d] restartProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *RestartProjectInstanceOK) GetPayload() *RestartProjectInstanceOKBody { + return o.Payload +} + +func (o *RestartProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RestartProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewRestartProjectInstanceDefault creates a RestartProjectInstanceDefault with default headers values +func NewRestartProjectInstanceDefault(code int) *RestartProjectInstanceDefault { + return &RestartProjectInstanceDefault{ + _statusCode: code, + } +} + +/* RestartProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type RestartProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *RestartProjectInstanceDefaultBody +} + +// Code gets the status code for the restart project instance default response +func (o *RestartProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this restart project instance default response has a 2xx status code +func (o *RestartProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this restart project instance default response has a 3xx status code +func (o *RestartProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this restart project instance default response has a 4xx status code +func (o *RestartProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this restart project instance default response has a 5xx status code +func (o *RestartProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this restart project instance default response a status code equal to that given +func (o *RestartProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *RestartProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/restart][%d] restartProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *RestartProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/restart][%d] restartProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *RestartProjectInstanceDefault) GetPayload() *RestartProjectInstanceDefaultBody { + return o.Payload +} + +func (o *RestartProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RestartProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*RestartProjectInstanceDefaultBody restart project instance default body +swagger:model RestartProjectInstanceDefaultBody +*/ +type RestartProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this restart project instance default body +func (o *RestartProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("restartProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *RestartProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("restartProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this restart project instance default body based on the context it is used +func (o *RestartProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RestartProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RestartProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res RestartProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*RestartProjectInstanceOKBody restart project instance o k body +swagger:model RestartProjectInstanceOKBody +*/ +type RestartProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this restart project instance o k body +func (o *RestartProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this restart project instance o k body based on the context it is used +func (o *RestartProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RestartProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RestartProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res RestartProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/start_instances_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/start_instances_parameters.go new file mode 100644 index 0000000..3cb0af3 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/start_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewStartInstancesParams creates a new StartInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewStartInstancesParams() *StartInstancesParams { + return &StartInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewStartInstancesParamsWithTimeout creates a new StartInstancesParams object +// with the ability to set a timeout on a request. +func NewStartInstancesParamsWithTimeout(timeout time.Duration) *StartInstancesParams { + return &StartInstancesParams{ + timeout: timeout, + } +} + +// NewStartInstancesParamsWithContext creates a new StartInstancesParams object +// with the ability to set a context for a request. +func NewStartInstancesParamsWithContext(ctx context.Context) *StartInstancesParams { + return &StartInstancesParams{ + Context: ctx, + } +} + +// NewStartInstancesParamsWithHTTPClient creates a new StartInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewStartInstancesParamsWithHTTPClient(client *http.Client) *StartInstancesParams { + return &StartInstancesParams{ + HTTPClient: client, + } +} + +/* StartInstancesParams contains all the parameters to send to the API endpoint + for the start instances operation. + + Typically these are written to a http.Request. +*/ +type StartInstancesParams struct { + + // Body. + Body *models.StartInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the start instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StartInstancesParams) WithDefaults() *StartInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the start instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StartInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the start instances params +func (o *StartInstancesParams) WithTimeout(timeout time.Duration) *StartInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the start instances params +func (o *StartInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the start instances params +func (o *StartInstancesParams) WithContext(ctx context.Context) *StartInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the start instances params +func (o *StartInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the start instances params +func (o *StartInstancesParams) WithHTTPClient(client *http.Client) *StartInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the start instances params +func (o *StartInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the start instances params +func (o *StartInstancesParams) WithBody(body *models.StartInstancesRequest) *StartInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the start instances params +func (o *StartInstancesParams) SetBody(body *models.StartInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the start instances params +func (o *StartInstancesParams) WithAuthorization(authorization string) *StartInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the start instances params +func (o *StartInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the start instances params +func (o *StartInstancesParams) WithBmpLanguage(bmpLanguage *string) *StartInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the start instances params +func (o *StartInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the start instances params +func (o *StartInstancesParams) WithBmpUserID(bmpUserID *string) *StartInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the start instances params +func (o *StartInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the start instances params +func (o *StartInstancesParams) WithTraceID(traceID string) *StartInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the start instances params +func (o *StartInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *StartInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/start_instances_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/start_instances_responses.go new file mode 100644 index 0000000..6bdc84d --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/start_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// StartInstancesReader is a Reader for the StartInstances structure. +type StartInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *StartInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewStartInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewStartInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewStartInstancesOK creates a StartInstancesOK with default headers values +func NewStartInstancesOK() *StartInstancesOK { + return &StartInstancesOK{} +} + +/* StartInstancesOK describes a response with status code 200, with default header values. + +A StartInstancesResult is an response struct +*/ +type StartInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *StartInstancesOKBody +} + +// IsSuccess returns true when this start instances o k response has a 2xx status code +func (o *StartInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this start instances o k response has a 3xx status code +func (o *StartInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this start instances o k response has a 4xx status code +func (o *StartInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this start instances o k response has a 5xx status code +func (o *StartInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this start instances o k response a status code equal to that given +func (o *StartInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *StartInstancesOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:startInstances][%d] startInstancesOK %+v", 200, o.Payload) +} + +func (o *StartInstancesOK) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:startInstances][%d] startInstancesOK %+v", 200, o.Payload) +} + +func (o *StartInstancesOK) GetPayload() *StartInstancesOKBody { + return o.Payload +} + +func (o *StartInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StartInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewStartInstancesDefault creates a StartInstancesDefault with default headers values +func NewStartInstancesDefault(code int) *StartInstancesDefault { + return &StartInstancesDefault{ + _statusCode: code, + } +} + +/* StartInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type StartInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *StartInstancesDefaultBody +} + +// Code gets the status code for the start instances default response +func (o *StartInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this start instances default response has a 2xx status code +func (o *StartInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this start instances default response has a 3xx status code +func (o *StartInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this start instances default response has a 4xx status code +func (o *StartInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this start instances default response has a 5xx status code +func (o *StartInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this start instances default response a status code equal to that given +func (o *StartInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *StartInstancesDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:startInstances][%d] startInstances default %+v", o._statusCode, o.Payload) +} + +func (o *StartInstancesDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:startInstances][%d] startInstances default %+v", o._statusCode, o.Payload) +} + +func (o *StartInstancesDefault) GetPayload() *StartInstancesDefaultBody { + return o.Payload +} + +func (o *StartInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StartInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*StartInstancesDefaultBody start instances default body +swagger:model StartInstancesDefaultBody +*/ +type StartInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this start instances default body +func (o *StartInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("startInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *StartInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("startInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this start instances default body based on the context it is used +func (o *StartInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StartInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StartInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res StartInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*StartInstancesOKBody start instances o k body +swagger:model StartInstancesOKBody +*/ +type StartInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this start instances o k body +func (o *StartInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this start instances o k body based on the context it is used +func (o *StartInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StartInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StartInstancesOKBody) UnmarshalBinary(b []byte) error { + var res StartInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/start_project_instance_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/start_project_instance_parameters.go new file mode 100644 index 0000000..9014aa5 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/start_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewStartProjectInstanceParams creates a new StartProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewStartProjectInstanceParams() *StartProjectInstanceParams { + return &StartProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewStartProjectInstanceParamsWithTimeout creates a new StartProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewStartProjectInstanceParamsWithTimeout(timeout time.Duration) *StartProjectInstanceParams { + return &StartProjectInstanceParams{ + timeout: timeout, + } +} + +// NewStartProjectInstanceParamsWithContext creates a new StartProjectInstanceParams object +// with the ability to set a context for a request. +func NewStartProjectInstanceParamsWithContext(ctx context.Context) *StartProjectInstanceParams { + return &StartProjectInstanceParams{ + Context: ctx, + } +} + +// NewStartProjectInstanceParamsWithHTTPClient creates a new StartProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewStartProjectInstanceParamsWithHTTPClient(client *http.Client) *StartProjectInstanceParams { + return &StartProjectInstanceParams{ + HTTPClient: client, + } +} + +/* StartProjectInstanceParams contains all the parameters to send to the API endpoint + for the start project instance operation. + + Typically these are written to a http.Request. +*/ +type StartProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the start project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StartProjectInstanceParams) WithDefaults() *StartProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the start project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StartProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the start project instance params +func (o *StartProjectInstanceParams) WithTimeout(timeout time.Duration) *StartProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the start project instance params +func (o *StartProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the start project instance params +func (o *StartProjectInstanceParams) WithContext(ctx context.Context) *StartProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the start project instance params +func (o *StartProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the start project instance params +func (o *StartProjectInstanceParams) WithHTTPClient(client *http.Client) *StartProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the start project instance params +func (o *StartProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the start project instance params +func (o *StartProjectInstanceParams) WithAuthorization(authorization string) *StartProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the start project instance params +func (o *StartProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the start project instance params +func (o *StartProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *StartProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the start project instance params +func (o *StartProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the start project instance params +func (o *StartProjectInstanceParams) WithBmpUserID(bmpUserID *string) *StartProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the start project instance params +func (o *StartProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the start project instance params +func (o *StartProjectInstanceParams) WithInstanceID(instanceID string) *StartProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the start project instance params +func (o *StartProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the start project instance params +func (o *StartProjectInstanceParams) WithTraceID(traceID string) *StartProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the start project instance params +func (o *StartProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *StartProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/start_project_instance_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/start_project_instance_responses.go new file mode 100644 index 0000000..197e3e7 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/start_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// StartProjectInstanceReader is a Reader for the StartProjectInstance structure. +type StartProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *StartProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewStartProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewStartProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewStartProjectInstanceOK creates a StartProjectInstanceOK with default headers values +func NewStartProjectInstanceOK() *StartProjectInstanceOK { + return &StartProjectInstanceOK{} +} + +/* StartProjectInstanceOK describes a response with status code 200, with default header values. + +A StartProjectInstanceResult is an response struct that is used to describe start instance result. +*/ +type StartProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *StartProjectInstanceOKBody +} + +// IsSuccess returns true when this start project instance o k response has a 2xx status code +func (o *StartProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this start project instance o k response has a 3xx status code +func (o *StartProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this start project instance o k response has a 4xx status code +func (o *StartProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this start project instance o k response has a 5xx status code +func (o *StartProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this start project instance o k response a status code equal to that given +func (o *StartProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *StartProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/start][%d] startProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *StartProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/start][%d] startProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *StartProjectInstanceOK) GetPayload() *StartProjectInstanceOKBody { + return o.Payload +} + +func (o *StartProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StartProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewStartProjectInstanceDefault creates a StartProjectInstanceDefault with default headers values +func NewStartProjectInstanceDefault(code int) *StartProjectInstanceDefault { + return &StartProjectInstanceDefault{ + _statusCode: code, + } +} + +/* StartProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type StartProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *StartProjectInstanceDefaultBody +} + +// Code gets the status code for the start project instance default response +func (o *StartProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this start project instance default response has a 2xx status code +func (o *StartProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this start project instance default response has a 3xx status code +func (o *StartProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this start project instance default response has a 4xx status code +func (o *StartProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this start project instance default response has a 5xx status code +func (o *StartProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this start project instance default response a status code equal to that given +func (o *StartProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *StartProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/start][%d] startProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *StartProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/start][%d] startProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *StartProjectInstanceDefault) GetPayload() *StartProjectInstanceDefaultBody { + return o.Payload +} + +func (o *StartProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StartProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*StartProjectInstanceDefaultBody start project instance default body +swagger:model StartProjectInstanceDefaultBody +*/ +type StartProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this start project instance default body +func (o *StartProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("startProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *StartProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("startProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this start project instance default body based on the context it is used +func (o *StartProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StartProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StartProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res StartProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*StartProjectInstanceOKBody start project instance o k body +swagger:model StartProjectInstanceOKBody +*/ +type StartProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this start project instance o k body +func (o *StartProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this start project instance o k body based on the context it is used +func (o *StartProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StartProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StartProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res StartProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/stop_instances_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/stop_instances_parameters.go new file mode 100644 index 0000000..f74653a --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/stop_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewStopInstancesParams creates a new StopInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewStopInstancesParams() *StopInstancesParams { + return &StopInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewStopInstancesParamsWithTimeout creates a new StopInstancesParams object +// with the ability to set a timeout on a request. +func NewStopInstancesParamsWithTimeout(timeout time.Duration) *StopInstancesParams { + return &StopInstancesParams{ + timeout: timeout, + } +} + +// NewStopInstancesParamsWithContext creates a new StopInstancesParams object +// with the ability to set a context for a request. +func NewStopInstancesParamsWithContext(ctx context.Context) *StopInstancesParams { + return &StopInstancesParams{ + Context: ctx, + } +} + +// NewStopInstancesParamsWithHTTPClient creates a new StopInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewStopInstancesParamsWithHTTPClient(client *http.Client) *StopInstancesParams { + return &StopInstancesParams{ + HTTPClient: client, + } +} + +/* StopInstancesParams contains all the parameters to send to the API endpoint + for the stop instances operation. + + Typically these are written to a http.Request. +*/ +type StopInstancesParams struct { + + // Body. + Body *models.StopInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the stop instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StopInstancesParams) WithDefaults() *StopInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the stop instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StopInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the stop instances params +func (o *StopInstancesParams) WithTimeout(timeout time.Duration) *StopInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the stop instances params +func (o *StopInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the stop instances params +func (o *StopInstancesParams) WithContext(ctx context.Context) *StopInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the stop instances params +func (o *StopInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the stop instances params +func (o *StopInstancesParams) WithHTTPClient(client *http.Client) *StopInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the stop instances params +func (o *StopInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the stop instances params +func (o *StopInstancesParams) WithBody(body *models.StopInstancesRequest) *StopInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the stop instances params +func (o *StopInstancesParams) SetBody(body *models.StopInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the stop instances params +func (o *StopInstancesParams) WithAuthorization(authorization string) *StopInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the stop instances params +func (o *StopInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the stop instances params +func (o *StopInstancesParams) WithBmpLanguage(bmpLanguage *string) *StopInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the stop instances params +func (o *StopInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the stop instances params +func (o *StopInstancesParams) WithBmpUserID(bmpUserID *string) *StopInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the stop instances params +func (o *StopInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the stop instances params +func (o *StopInstancesParams) WithTraceID(traceID string) *StopInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the stop instances params +func (o *StopInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *StopInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/stop_instances_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/stop_instances_responses.go new file mode 100644 index 0000000..fb496d1 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/stop_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// StopInstancesReader is a Reader for the StopInstances structure. +type StopInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *StopInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewStopInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewStopInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewStopInstancesOK creates a StopInstancesOK with default headers values +func NewStopInstancesOK() *StopInstancesOK { + return &StopInstancesOK{} +} + +/* StopInstancesOK describes a response with status code 200, with default header values. + +A StopInstancesResult is an response struct +*/ +type StopInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *StopInstancesOKBody +} + +// IsSuccess returns true when this stop instances o k response has a 2xx status code +func (o *StopInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this stop instances o k response has a 3xx status code +func (o *StopInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this stop instances o k response has a 4xx status code +func (o *StopInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this stop instances o k response has a 5xx status code +func (o *StopInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this stop instances o k response a status code equal to that given +func (o *StopInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *StopInstancesOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:stopInstances][%d] stopInstancesOK %+v", 200, o.Payload) +} + +func (o *StopInstancesOK) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:stopInstances][%d] stopInstancesOK %+v", 200, o.Payload) +} + +func (o *StopInstancesOK) GetPayload() *StopInstancesOKBody { + return o.Payload +} + +func (o *StopInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StopInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewStopInstancesDefault creates a StopInstancesDefault with default headers values +func NewStopInstancesDefault(code int) *StopInstancesDefault { + return &StopInstancesDefault{ + _statusCode: code, + } +} + +/* StopInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type StopInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *StopInstancesDefaultBody +} + +// Code gets the status code for the stop instances default response +func (o *StopInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this stop instances default response has a 2xx status code +func (o *StopInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this stop instances default response has a 3xx status code +func (o *StopInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this stop instances default response has a 4xx status code +func (o *StopInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this stop instances default response has a 5xx status code +func (o *StopInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this stop instances default response a status code equal to that given +func (o *StopInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *StopInstancesDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:stopInstances][%d] stopInstances default %+v", o._statusCode, o.Payload) +} + +func (o *StopInstancesDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:stopInstances][%d] stopInstances default %+v", o._statusCode, o.Payload) +} + +func (o *StopInstancesDefault) GetPayload() *StopInstancesDefaultBody { + return o.Payload +} + +func (o *StopInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StopInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*StopInstancesDefaultBody stop instances default body +swagger:model StopInstancesDefaultBody +*/ +type StopInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this stop instances default body +func (o *StopInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("stopInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *StopInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("stopInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this stop instances default body based on the context it is used +func (o *StopInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StopInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StopInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res StopInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*StopInstancesOKBody stop instances o k body +swagger:model StopInstancesOKBody +*/ +type StopInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this stop instances o k body +func (o *StopInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this stop instances o k body based on the context it is used +func (o *StopInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StopInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StopInstancesOKBody) UnmarshalBinary(b []byte) error { + var res StopInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/stop_project_instance_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/stop_project_instance_parameters.go new file mode 100644 index 0000000..f9a48c8 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/stop_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewStopProjectInstanceParams creates a new StopProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewStopProjectInstanceParams() *StopProjectInstanceParams { + return &StopProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewStopProjectInstanceParamsWithTimeout creates a new StopProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewStopProjectInstanceParamsWithTimeout(timeout time.Duration) *StopProjectInstanceParams { + return &StopProjectInstanceParams{ + timeout: timeout, + } +} + +// NewStopProjectInstanceParamsWithContext creates a new StopProjectInstanceParams object +// with the ability to set a context for a request. +func NewStopProjectInstanceParamsWithContext(ctx context.Context) *StopProjectInstanceParams { + return &StopProjectInstanceParams{ + Context: ctx, + } +} + +// NewStopProjectInstanceParamsWithHTTPClient creates a new StopProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewStopProjectInstanceParamsWithHTTPClient(client *http.Client) *StopProjectInstanceParams { + return &StopProjectInstanceParams{ + HTTPClient: client, + } +} + +/* StopProjectInstanceParams contains all the parameters to send to the API endpoint + for the stop project instance operation. + + Typically these are written to a http.Request. +*/ +type StopProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the stop project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StopProjectInstanceParams) WithDefaults() *StopProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the stop project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StopProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the stop project instance params +func (o *StopProjectInstanceParams) WithTimeout(timeout time.Duration) *StopProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the stop project instance params +func (o *StopProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the stop project instance params +func (o *StopProjectInstanceParams) WithContext(ctx context.Context) *StopProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the stop project instance params +func (o *StopProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the stop project instance params +func (o *StopProjectInstanceParams) WithHTTPClient(client *http.Client) *StopProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the stop project instance params +func (o *StopProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the stop project instance params +func (o *StopProjectInstanceParams) WithAuthorization(authorization string) *StopProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the stop project instance params +func (o *StopProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the stop project instance params +func (o *StopProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *StopProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the stop project instance params +func (o *StopProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the stop project instance params +func (o *StopProjectInstanceParams) WithBmpUserID(bmpUserID *string) *StopProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the stop project instance params +func (o *StopProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the stop project instance params +func (o *StopProjectInstanceParams) WithInstanceID(instanceID string) *StopProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the stop project instance params +func (o *StopProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the stop project instance params +func (o *StopProjectInstanceParams) WithTraceID(traceID string) *StopProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the stop project instance params +func (o *StopProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *StopProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/stop_project_instance_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/stop_project_instance_responses.go new file mode 100644 index 0000000..5d720d3 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/stop_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// StopProjectInstanceReader is a Reader for the StopProjectInstance structure. +type StopProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *StopProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewStopProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewStopProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewStopProjectInstanceOK creates a StopProjectInstanceOK with default headers values +func NewStopProjectInstanceOK() *StopProjectInstanceOK { + return &StopProjectInstanceOK{} +} + +/* StopProjectInstanceOK describes a response with status code 200, with default header values. + +A StopProjectInstanceResult is an response struct that is used to describe stop instance result. +*/ +type StopProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *StopProjectInstanceOKBody +} + +// IsSuccess returns true when this stop project instance o k response has a 2xx status code +func (o *StopProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this stop project instance o k response has a 3xx status code +func (o *StopProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this stop project instance o k response has a 4xx status code +func (o *StopProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this stop project instance o k response has a 5xx status code +func (o *StopProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this stop project instance o k response a status code equal to that given +func (o *StopProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *StopProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/stop][%d] stopProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *StopProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/stop][%d] stopProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *StopProjectInstanceOK) GetPayload() *StopProjectInstanceOKBody { + return o.Payload +} + +func (o *StopProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StopProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewStopProjectInstanceDefault creates a StopProjectInstanceDefault with default headers values +func NewStopProjectInstanceDefault(code int) *StopProjectInstanceDefault { + return &StopProjectInstanceDefault{ + _statusCode: code, + } +} + +/* StopProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type StopProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *StopProjectInstanceDefaultBody +} + +// Code gets the status code for the stop project instance default response +func (o *StopProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this stop project instance default response has a 2xx status code +func (o *StopProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this stop project instance default response has a 3xx status code +func (o *StopProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this stop project instance default response has a 4xx status code +func (o *StopProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this stop project instance default response has a 5xx status code +func (o *StopProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this stop project instance default response a status code equal to that given +func (o *StopProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *StopProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/stop][%d] stopProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *StopProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/stop][%d] stopProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *StopProjectInstanceDefault) GetPayload() *StopProjectInstanceDefaultBody { + return o.Payload +} + +func (o *StopProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StopProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*StopProjectInstanceDefaultBody stop project instance default body +swagger:model StopProjectInstanceDefaultBody +*/ +type StopProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this stop project instance default body +func (o *StopProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("stopProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *StopProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("stopProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this stop project instance default body based on the context it is used +func (o *StopProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StopProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StopProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res StopProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*StopProjectInstanceOKBody stop project instance o k body +swagger:model StopProjectInstanceOKBody +*/ +type StopProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this stop project instance o k body +func (o *StopProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this stop project instance o k body based on the context it is used +func (o *StopProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StopProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StopProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res StopProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/un_lock_project_instance_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/un_lock_project_instance_parameters.go new file mode 100644 index 0000000..c23507f --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/un_lock_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewUnLockProjectInstanceParams creates a new UnLockProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewUnLockProjectInstanceParams() *UnLockProjectInstanceParams { + return &UnLockProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUnLockProjectInstanceParamsWithTimeout creates a new UnLockProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewUnLockProjectInstanceParamsWithTimeout(timeout time.Duration) *UnLockProjectInstanceParams { + return &UnLockProjectInstanceParams{ + timeout: timeout, + } +} + +// NewUnLockProjectInstanceParamsWithContext creates a new UnLockProjectInstanceParams object +// with the ability to set a context for a request. +func NewUnLockProjectInstanceParamsWithContext(ctx context.Context) *UnLockProjectInstanceParams { + return &UnLockProjectInstanceParams{ + Context: ctx, + } +} + +// NewUnLockProjectInstanceParamsWithHTTPClient creates a new UnLockProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewUnLockProjectInstanceParamsWithHTTPClient(client *http.Client) *UnLockProjectInstanceParams { + return &UnLockProjectInstanceParams{ + HTTPClient: client, + } +} + +/* UnLockProjectInstanceParams contains all the parameters to send to the API endpoint + for the un lock project instance operation. + + Typically these are written to a http.Request. +*/ +type UnLockProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the un lock project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UnLockProjectInstanceParams) WithDefaults() *UnLockProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the un lock project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UnLockProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithTimeout(timeout time.Duration) *UnLockProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithContext(ctx context.Context) *UnLockProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithHTTPClient(client *http.Client) *UnLockProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithAuthorization(authorization string) *UnLockProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *UnLockProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithBmpUserID(bmpUserID *string) *UnLockProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithInstanceID(instanceID string) *UnLockProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithTraceID(traceID string) *UnLockProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *UnLockProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/un_lock_project_instance_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/un_lock_project_instance_responses.go new file mode 100644 index 0000000..bc5068d --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/instance/un_lock_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// UnLockProjectInstanceReader is a Reader for the UnLockProjectInstance structure. +type UnLockProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UnLockProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUnLockProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewUnLockProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewUnLockProjectInstanceOK creates a UnLockProjectInstanceOK with default headers values +func NewUnLockProjectInstanceOK() *UnLockProjectInstanceOK { + return &UnLockProjectInstanceOK{} +} + +/* UnLockProjectInstanceOK describes a response with status code 200, with default header values. + +A UnLockProjectInstanceResult is an response struct that is used to describe unlock instance result. +*/ +type UnLockProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *UnLockProjectInstanceOKBody +} + +// IsSuccess returns true when this un lock project instance o k response has a 2xx status code +func (o *UnLockProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this un lock project instance o k response has a 3xx status code +func (o *UnLockProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this un lock project instance o k response has a 4xx status code +func (o *UnLockProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this un lock project instance o k response has a 5xx status code +func (o *UnLockProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this un lock project instance o k response a status code equal to that given +func (o *UnLockProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *UnLockProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/unlock][%d] unLockProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *UnLockProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/unlock][%d] unLockProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *UnLockProjectInstanceOK) GetPayload() *UnLockProjectInstanceOKBody { + return o.Payload +} + +func (o *UnLockProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(UnLockProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUnLockProjectInstanceDefault creates a UnLockProjectInstanceDefault with default headers values +func NewUnLockProjectInstanceDefault(code int) *UnLockProjectInstanceDefault { + return &UnLockProjectInstanceDefault{ + _statusCode: code, + } +} + +/* UnLockProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type UnLockProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *UnLockProjectInstanceDefaultBody +} + +// Code gets the status code for the un lock project instance default response +func (o *UnLockProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this un lock project instance default response has a 2xx status code +func (o *UnLockProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this un lock project instance default response has a 3xx status code +func (o *UnLockProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this un lock project instance default response has a 4xx status code +func (o *UnLockProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this un lock project instance default response has a 5xx status code +func (o *UnLockProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this un lock project instance default response a status code equal to that given +func (o *UnLockProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *UnLockProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/unlock][%d] unLockProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *UnLockProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/unlock][%d] unLockProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *UnLockProjectInstanceDefault) GetPayload() *UnLockProjectInstanceDefaultBody { + return o.Payload +} + +func (o *UnLockProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(UnLockProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*UnLockProjectInstanceDefaultBody un lock project instance default body +swagger:model UnLockProjectInstanceDefaultBody +*/ +type UnLockProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this un lock project instance default body +func (o *UnLockProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnLockProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("unLockProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *UnLockProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("unLockProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unLockProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unLockProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this un lock project instance default body based on the context it is used +func (o *UnLockProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnLockProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unLockProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unLockProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *UnLockProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *UnLockProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res UnLockProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*UnLockProjectInstanceOKBody un lock project instance o k body +swagger:model UnLockProjectInstanceOKBody +*/ +type UnLockProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this un lock project instance o k body +func (o *UnLockProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnLockProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unLockProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unLockProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this un lock project instance o k body based on the context it is used +func (o *UnLockProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnLockProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unLockProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unLockProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *UnLockProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *UnLockProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res UnLockProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/license/describe_license_content_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/license/describe_license_content_parameters.go new file mode 100644 index 0000000..aa6caae --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/license/describe_license_content_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeLicenseContentParams creates a new DescribeLicenseContentParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeLicenseContentParams() *DescribeLicenseContentParams { + return &DescribeLicenseContentParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeLicenseContentParamsWithTimeout creates a new DescribeLicenseContentParams object +// with the ability to set a timeout on a request. +func NewDescribeLicenseContentParamsWithTimeout(timeout time.Duration) *DescribeLicenseContentParams { + return &DescribeLicenseContentParams{ + timeout: timeout, + } +} + +// NewDescribeLicenseContentParamsWithContext creates a new DescribeLicenseContentParams object +// with the ability to set a context for a request. +func NewDescribeLicenseContentParamsWithContext(ctx context.Context) *DescribeLicenseContentParams { + return &DescribeLicenseContentParams{ + Context: ctx, + } +} + +// NewDescribeLicenseContentParamsWithHTTPClient creates a new DescribeLicenseContentParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeLicenseContentParamsWithHTTPClient(client *http.Client) *DescribeLicenseContentParams { + return &DescribeLicenseContentParams{ + HTTPClient: client, + } +} + +/* DescribeLicenseContentParams contains all the parameters to send to the API endpoint + for the describe license content operation. + + Typically these are written to a http.Request. +*/ +type DescribeLicenseContentParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe license content params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLicenseContentParams) WithDefaults() *DescribeLicenseContentParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe license content params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLicenseContentParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe license content params +func (o *DescribeLicenseContentParams) WithTimeout(timeout time.Duration) *DescribeLicenseContentParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe license content params +func (o *DescribeLicenseContentParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe license content params +func (o *DescribeLicenseContentParams) WithContext(ctx context.Context) *DescribeLicenseContentParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe license content params +func (o *DescribeLicenseContentParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe license content params +func (o *DescribeLicenseContentParams) WithHTTPClient(client *http.Client) *DescribeLicenseContentParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe license content params +func (o *DescribeLicenseContentParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe license content params +func (o *DescribeLicenseContentParams) WithAuthorization(authorization string) *DescribeLicenseContentParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe license content params +func (o *DescribeLicenseContentParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe license content params +func (o *DescribeLicenseContentParams) WithBmpLanguage(bmpLanguage *string) *DescribeLicenseContentParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe license content params +func (o *DescribeLicenseContentParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe license content params +func (o *DescribeLicenseContentParams) WithBmpUserID(bmpUserID *string) *DescribeLicenseContentParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe license content params +func (o *DescribeLicenseContentParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe license content params +func (o *DescribeLicenseContentParams) WithTraceID(traceID string) *DescribeLicenseContentParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe license content params +func (o *DescribeLicenseContentParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeLicenseContentParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/license/describe_license_content_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/license/describe_license_content_responses.go new file mode 100644 index 0000000..479d3b8 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/license/describe_license_content_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeLicenseContentReader is a Reader for the DescribeLicenseContent structure. +type DescribeLicenseContentReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeLicenseContentReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeLicenseContentOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeLicenseContentDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeLicenseContentOK creates a DescribeLicenseContentOK with default headers values +func NewDescribeLicenseContentOK() *DescribeLicenseContentOK { + return &DescribeLicenseContentOK{} +} + +/* DescribeLicenseContentOK describes a response with status code 200, with default header values. + +A DescribeLicenseContentResult is an response struct that is used to describe getuser. +*/ +type DescribeLicenseContentOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLicenseContentOKBody +} + +// IsSuccess returns true when this describe license content o k response has a 2xx status code +func (o *DescribeLicenseContentOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe license content o k response has a 3xx status code +func (o *DescribeLicenseContentOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe license content o k response has a 4xx status code +func (o *DescribeLicenseContentOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe license content o k response has a 5xx status code +func (o *DescribeLicenseContentOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe license content o k response a status code equal to that given +func (o *DescribeLicenseContentOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeLicenseContentOK) Error() string { + return fmt.Sprintf("[GET /license/content][%d] describeLicenseContentOK %+v", 200, o.Payload) +} + +func (o *DescribeLicenseContentOK) String() string { + return fmt.Sprintf("[GET /license/content][%d] describeLicenseContentOK %+v", 200, o.Payload) +} + +func (o *DescribeLicenseContentOK) GetPayload() *DescribeLicenseContentOKBody { + return o.Payload +} + +func (o *DescribeLicenseContentOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLicenseContentOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeLicenseContentDefault creates a DescribeLicenseContentDefault with default headers values +func NewDescribeLicenseContentDefault(code int) *DescribeLicenseContentDefault { + return &DescribeLicenseContentDefault{ + _statusCode: code, + } +} + +/* DescribeLicenseContentDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeLicenseContentDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLicenseContentDefaultBody +} + +// Code gets the status code for the describe license content default response +func (o *DescribeLicenseContentDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe license content default response has a 2xx status code +func (o *DescribeLicenseContentDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe license content default response has a 3xx status code +func (o *DescribeLicenseContentDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe license content default response has a 4xx status code +func (o *DescribeLicenseContentDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe license content default response has a 5xx status code +func (o *DescribeLicenseContentDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe license content default response a status code equal to that given +func (o *DescribeLicenseContentDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeLicenseContentDefault) Error() string { + return fmt.Sprintf("[GET /license/content][%d] describeLicenseContent default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLicenseContentDefault) String() string { + return fmt.Sprintf("[GET /license/content][%d] describeLicenseContent default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLicenseContentDefault) GetPayload() *DescribeLicenseContentDefaultBody { + return o.Payload +} + +func (o *DescribeLicenseContentDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLicenseContentDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeLicenseContentDefaultBody describe license content default body +swagger:model DescribeLicenseContentDefaultBody +*/ +type DescribeLicenseContentDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe license content default body +func (o *DescribeLicenseContentDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseContentDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeLicenseContent default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeLicenseContentDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeLicenseContent default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseContent default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseContent default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe license content default body based on the context it is used +func (o *DescribeLicenseContentDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseContentDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseContent default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseContent default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLicenseContentDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLicenseContentDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeLicenseContentDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeLicenseContentOKBody describe license content o k body +swagger:model DescribeLicenseContentOKBody +*/ +type DescribeLicenseContentOKBody struct { + + // result + Result *models.LicenseContent `json:"result,omitempty"` +} + +// Validate validates this describe license content o k body +func (o *DescribeLicenseContentOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseContentOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseContentOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseContentOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe license content o k body based on the context it is used +func (o *DescribeLicenseContentOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseContentOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseContentOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseContentOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLicenseContentOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLicenseContentOKBody) UnmarshalBinary(b []byte) error { + var res DescribeLicenseContentOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/license/license_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/license/license_client.go new file mode 100644 index 0000000..9829fbc --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/license/license_client.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new license API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for license API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DescribeLicenseContent(params *DescribeLicenseContentParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLicenseContentOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DescribeLicenseContent DescribeLicenseContent 获取授权详情 +*/ +func (a *Client) DescribeLicenseContent(params *DescribeLicenseContentParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLicenseContentOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeLicenseContentParams() + } + op := &runtime.ClientOperation{ + ID: "describeLicenseContent", + Method: "GET", + PathPattern: "/license/content", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeLicenseContentReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeLicenseContentOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeLicenseContentDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/delete_message_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/delete_message_parameters.go new file mode 100644 index 0000000..a5aa471 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/delete_message_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewDeleteMessageParams creates a new DeleteMessageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteMessageParams() *DeleteMessageParams { + return &DeleteMessageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteMessageParamsWithTimeout creates a new DeleteMessageParams object +// with the ability to set a timeout on a request. +func NewDeleteMessageParamsWithTimeout(timeout time.Duration) *DeleteMessageParams { + return &DeleteMessageParams{ + timeout: timeout, + } +} + +// NewDeleteMessageParamsWithContext creates a new DeleteMessageParams object +// with the ability to set a context for a request. +func NewDeleteMessageParamsWithContext(ctx context.Context) *DeleteMessageParams { + return &DeleteMessageParams{ + Context: ctx, + } +} + +// NewDeleteMessageParamsWithHTTPClient creates a new DeleteMessageParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteMessageParamsWithHTTPClient(client *http.Client) *DeleteMessageParams { + return &DeleteMessageParams{ + HTTPClient: client, + } +} + +/* DeleteMessageParams contains all the parameters to send to the API endpoint + for the delete message operation. + + Typically these are written to a http.Request. +*/ +type DeleteMessageParams struct { + + // Body. + Body *models.DeleteMessagesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete message params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteMessageParams) WithDefaults() *DeleteMessageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete message params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteMessageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete message params +func (o *DeleteMessageParams) WithTimeout(timeout time.Duration) *DeleteMessageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete message params +func (o *DeleteMessageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete message params +func (o *DeleteMessageParams) WithContext(ctx context.Context) *DeleteMessageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete message params +func (o *DeleteMessageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete message params +func (o *DeleteMessageParams) WithHTTPClient(client *http.Client) *DeleteMessageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete message params +func (o *DeleteMessageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the delete message params +func (o *DeleteMessageParams) WithBody(body *models.DeleteMessagesRequest) *DeleteMessageParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the delete message params +func (o *DeleteMessageParams) SetBody(body *models.DeleteMessagesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the delete message params +func (o *DeleteMessageParams) WithAuthorization(authorization string) *DeleteMessageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete message params +func (o *DeleteMessageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete message params +func (o *DeleteMessageParams) WithBmpLanguage(bmpLanguage *string) *DeleteMessageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete message params +func (o *DeleteMessageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete message params +func (o *DeleteMessageParams) WithBmpUserID(bmpUserID *string) *DeleteMessageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete message params +func (o *DeleteMessageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete message params +func (o *DeleteMessageParams) WithTraceID(traceID string) *DeleteMessageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete message params +func (o *DeleteMessageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteMessageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/delete_message_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/delete_message_responses.go new file mode 100644 index 0000000..fbb3a5a --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/delete_message_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DeleteMessageReader is a Reader for the DeleteMessage structure. +type DeleteMessageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteMessageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteMessageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteMessageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteMessageOK creates a DeleteMessageOK with default headers values +func NewDeleteMessageOK() *DeleteMessageOK { + return &DeleteMessageOK{} +} + +/* DeleteMessageOK describes a response with status code 200, with default header values. + +A DeleteMessageResult is an response struct +*/ +type DeleteMessageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteMessageOKBody +} + +// IsSuccess returns true when this delete message o k response has a 2xx status code +func (o *DeleteMessageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete message o k response has a 3xx status code +func (o *DeleteMessageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete message o k response has a 4xx status code +func (o *DeleteMessageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete message o k response has a 5xx status code +func (o *DeleteMessageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete message o k response a status code equal to that given +func (o *DeleteMessageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteMessageOK) Error() string { + return fmt.Sprintf("[DELETE /messages/delete][%d] deleteMessageOK %+v", 200, o.Payload) +} + +func (o *DeleteMessageOK) String() string { + return fmt.Sprintf("[DELETE /messages/delete][%d] deleteMessageOK %+v", 200, o.Payload) +} + +func (o *DeleteMessageOK) GetPayload() *DeleteMessageOKBody { + return o.Payload +} + +func (o *DeleteMessageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteMessageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteMessageDefault creates a DeleteMessageDefault with default headers values +func NewDeleteMessageDefault(code int) *DeleteMessageDefault { + return &DeleteMessageDefault{ + _statusCode: code, + } +} + +/* DeleteMessageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteMessageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteMessageDefaultBody +} + +// Code gets the status code for the delete message default response +func (o *DeleteMessageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete message default response has a 2xx status code +func (o *DeleteMessageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete message default response has a 3xx status code +func (o *DeleteMessageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete message default response has a 4xx status code +func (o *DeleteMessageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete message default response has a 5xx status code +func (o *DeleteMessageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete message default response a status code equal to that given +func (o *DeleteMessageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteMessageDefault) Error() string { + return fmt.Sprintf("[DELETE /messages/delete][%d] deleteMessage default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteMessageDefault) String() string { + return fmt.Sprintf("[DELETE /messages/delete][%d] deleteMessage default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteMessageDefault) GetPayload() *DeleteMessageDefaultBody { + return o.Payload +} + +func (o *DeleteMessageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteMessageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteMessageDefaultBody delete message default body +swagger:model DeleteMessageDefaultBody +*/ +type DeleteMessageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete message default body +func (o *DeleteMessageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteMessageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteMessage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteMessageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteMessage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteMessage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteMessage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete message default body based on the context it is used +func (o *DeleteMessageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteMessageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteMessage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteMessage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteMessageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteMessageDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteMessageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteMessageOKBody delete message o k body +swagger:model DeleteMessageOKBody +*/ +type DeleteMessageOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete message o k body +func (o *DeleteMessageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteMessageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteMessageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteMessageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete message o k body based on the context it is used +func (o *DeleteMessageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteMessageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteMessageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteMessageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteMessageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteMessageOKBody) UnmarshalBinary(b []byte) error { + var res DeleteMessageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_by_id_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_by_id_parameters.go new file mode 100644 index 0000000..a6bc375 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_by_id_parameters.go @@ -0,0 +1,245 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetMessageByIDParams creates a new GetMessageByIDParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetMessageByIDParams() *GetMessageByIDParams { + return &GetMessageByIDParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetMessageByIDParamsWithTimeout creates a new GetMessageByIDParams object +// with the ability to set a timeout on a request. +func NewGetMessageByIDParamsWithTimeout(timeout time.Duration) *GetMessageByIDParams { + return &GetMessageByIDParams{ + timeout: timeout, + } +} + +// NewGetMessageByIDParamsWithContext creates a new GetMessageByIDParams object +// with the ability to set a context for a request. +func NewGetMessageByIDParamsWithContext(ctx context.Context) *GetMessageByIDParams { + return &GetMessageByIDParams{ + Context: ctx, + } +} + +// NewGetMessageByIDParamsWithHTTPClient creates a new GetMessageByIDParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetMessageByIDParamsWithHTTPClient(client *http.Client) *GetMessageByIDParams { + return &GetMessageByIDParams{ + HTTPClient: client, + } +} + +/* GetMessageByIDParams contains all the parameters to send to the API endpoint + for the get message by Id operation. + + Typically these are written to a http.Request. +*/ +type GetMessageByIDParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // MessageID. + MessageID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get message by Id params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageByIDParams) WithDefaults() *GetMessageByIDParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get message by Id params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageByIDParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get message by Id params +func (o *GetMessageByIDParams) WithTimeout(timeout time.Duration) *GetMessageByIDParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get message by Id params +func (o *GetMessageByIDParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get message by Id params +func (o *GetMessageByIDParams) WithContext(ctx context.Context) *GetMessageByIDParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get message by Id params +func (o *GetMessageByIDParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get message by Id params +func (o *GetMessageByIDParams) WithHTTPClient(client *http.Client) *GetMessageByIDParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get message by Id params +func (o *GetMessageByIDParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the get message by Id params +func (o *GetMessageByIDParams) WithAuthorization(authorization string) *GetMessageByIDParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the get message by Id params +func (o *GetMessageByIDParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the get message by Id params +func (o *GetMessageByIDParams) WithBmpLanguage(bmpLanguage *string) *GetMessageByIDParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the get message by Id params +func (o *GetMessageByIDParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the get message by Id params +func (o *GetMessageByIDParams) WithBmpUserID(bmpUserID *string) *GetMessageByIDParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the get message by Id params +func (o *GetMessageByIDParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithMessageID adds the messageID to the get message by Id params +func (o *GetMessageByIDParams) WithMessageID(messageID string) *GetMessageByIDParams { + o.SetMessageID(messageID) + return o +} + +// SetMessageID adds the messageId to the get message by Id params +func (o *GetMessageByIDParams) SetMessageID(messageID string) { + o.MessageID = messageID +} + +// WithTraceID adds the traceID to the get message by Id params +func (o *GetMessageByIDParams) WithTraceID(traceID string) *GetMessageByIDParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the get message by Id params +func (o *GetMessageByIDParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetMessageByIDParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // query param messageId + qrMessageID := o.MessageID + qMessageID := qrMessageID + if qMessageID != "" { + + if err := r.SetQueryParam("messageId", qMessageID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_by_id_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_by_id_responses.go new file mode 100644 index 0000000..71fa797 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_by_id_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// GetMessageByIDReader is a Reader for the GetMessageByID structure. +type GetMessageByIDReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetMessageByIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetMessageByIDOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetMessageByIDDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetMessageByIDOK creates a GetMessageByIDOK with default headers values +func NewGetMessageByIDOK() *GetMessageByIDOK { + return &GetMessageByIDOK{} +} + +/* GetMessageByIDOK describes a response with status code 200, with default header values. + +GetMessageByIDOK get message by Id o k +*/ +type GetMessageByIDOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageByIDOKBody +} + +// IsSuccess returns true when this get message by Id o k response has a 2xx status code +func (o *GetMessageByIDOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get message by Id o k response has a 3xx status code +func (o *GetMessageByIDOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get message by Id o k response has a 4xx status code +func (o *GetMessageByIDOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get message by Id o k response has a 5xx status code +func (o *GetMessageByIDOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get message by Id o k response a status code equal to that given +func (o *GetMessageByIDOK) IsCode(code int) bool { + return code == 200 +} + +func (o *GetMessageByIDOK) Error() string { + return fmt.Sprintf("[GET /messages/getMessageById][%d] getMessageByIdOK %+v", 200, o.Payload) +} + +func (o *GetMessageByIDOK) String() string { + return fmt.Sprintf("[GET /messages/getMessageById][%d] getMessageByIdOK %+v", 200, o.Payload) +} + +func (o *GetMessageByIDOK) GetPayload() *GetMessageByIDOKBody { + return o.Payload +} + +func (o *GetMessageByIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageByIDOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetMessageByIDDefault creates a GetMessageByIDDefault with default headers values +func NewGetMessageByIDDefault(code int) *GetMessageByIDDefault { + return &GetMessageByIDDefault{ + _statusCode: code, + } +} + +/* GetMessageByIDDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type GetMessageByIDDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageByIDDefaultBody +} + +// Code gets the status code for the get message by Id default response +func (o *GetMessageByIDDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this get message by Id default response has a 2xx status code +func (o *GetMessageByIDDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get message by Id default response has a 3xx status code +func (o *GetMessageByIDDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get message by Id default response has a 4xx status code +func (o *GetMessageByIDDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get message by Id default response has a 5xx status code +func (o *GetMessageByIDDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get message by Id default response a status code equal to that given +func (o *GetMessageByIDDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *GetMessageByIDDefault) Error() string { + return fmt.Sprintf("[GET /messages/getMessageById][%d] getMessageById default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageByIDDefault) String() string { + return fmt.Sprintf("[GET /messages/getMessageById][%d] getMessageById default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageByIDDefault) GetPayload() *GetMessageByIDDefaultBody { + return o.Payload +} + +func (o *GetMessageByIDDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageByIDDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*GetMessageByIDDefaultBody get message by ID default body +swagger:model GetMessageByIDDefaultBody +*/ +type GetMessageByIDDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this get message by ID default body +func (o *GetMessageByIDDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageByIDDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("getMessageById default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *GetMessageByIDDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("getMessageById default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageById default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageById default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message by ID default body based on the context it is used +func (o *GetMessageByIDDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageByIDDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageById default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageById default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageByIDDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageByIDDefaultBody) UnmarshalBinary(b []byte) error { + var res GetMessageByIDDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*GetMessageByIDOKBody get message by ID o k body +swagger:model GetMessageByIDOKBody +*/ +type GetMessageByIDOKBody struct { + + // result + Result *models.MessageWithNextPrev `json:"result,omitempty"` +} + +// Validate validates this get message by ID o k body +func (o *GetMessageByIDOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageByIDOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageByIdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageByIdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message by ID o k body based on the context it is used +func (o *GetMessageByIDOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageByIDOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageByIdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageByIdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageByIDOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageByIDOKBody) UnmarshalBinary(b []byte) error { + var res GetMessageByIDOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_list_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_list_parameters.go new file mode 100644 index 0000000..e513e14 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_list_parameters.go @@ -0,0 +1,464 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetMessageListParams creates a new GetMessageListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetMessageListParams() *GetMessageListParams { + return &GetMessageListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetMessageListParamsWithTimeout creates a new GetMessageListParams object +// with the ability to set a timeout on a request. +func NewGetMessageListParamsWithTimeout(timeout time.Duration) *GetMessageListParams { + return &GetMessageListParams{ + timeout: timeout, + } +} + +// NewGetMessageListParamsWithContext creates a new GetMessageListParams object +// with the ability to set a context for a request. +func NewGetMessageListParamsWithContext(ctx context.Context) *GetMessageListParams { + return &GetMessageListParams{ + Context: ctx, + } +} + +// NewGetMessageListParamsWithHTTPClient creates a new GetMessageListParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetMessageListParamsWithHTTPClient(client *http.Client) *GetMessageListParams { + return &GetMessageListParams{ + HTTPClient: client, + } +} + +/* GetMessageListParams contains all the parameters to send to the API endpoint + for the get message list operation. + + Typically these are written to a http.Request. +*/ +type GetMessageListParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* Detail. + + 内容模糊搜索 + */ + Detail *string + + /* HasRead. + + 0:未读;1:已读;""不传表示全部 + */ + HasRead *string + + /* IsAll. + + 是否显示全部,取值为1时表示全部 + */ + IsAll *string + + /* MessageSubType. + + 消息子类型 + */ + MessageSubType *string + + /* MessageType. + + 消息类型 + */ + MessageType *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get message list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageListParams) WithDefaults() *GetMessageListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get message list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get message list params +func (o *GetMessageListParams) WithTimeout(timeout time.Duration) *GetMessageListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get message list params +func (o *GetMessageListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get message list params +func (o *GetMessageListParams) WithContext(ctx context.Context) *GetMessageListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get message list params +func (o *GetMessageListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get message list params +func (o *GetMessageListParams) WithHTTPClient(client *http.Client) *GetMessageListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get message list params +func (o *GetMessageListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the get message list params +func (o *GetMessageListParams) WithAuthorization(authorization string) *GetMessageListParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the get message list params +func (o *GetMessageListParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the get message list params +func (o *GetMessageListParams) WithBmpLanguage(bmpLanguage *string) *GetMessageListParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the get message list params +func (o *GetMessageListParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the get message list params +func (o *GetMessageListParams) WithBmpUserID(bmpUserID *string) *GetMessageListParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the get message list params +func (o *GetMessageListParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDetail adds the detail to the get message list params +func (o *GetMessageListParams) WithDetail(detail *string) *GetMessageListParams { + o.SetDetail(detail) + return o +} + +// SetDetail adds the detail to the get message list params +func (o *GetMessageListParams) SetDetail(detail *string) { + o.Detail = detail +} + +// WithHasRead adds the hasRead to the get message list params +func (o *GetMessageListParams) WithHasRead(hasRead *string) *GetMessageListParams { + o.SetHasRead(hasRead) + return o +} + +// SetHasRead adds the hasRead to the get message list params +func (o *GetMessageListParams) SetHasRead(hasRead *string) { + o.HasRead = hasRead +} + +// WithIsAll adds the isAll to the get message list params +func (o *GetMessageListParams) WithIsAll(isAll *string) *GetMessageListParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the get message list params +func (o *GetMessageListParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithMessageSubType adds the messageSubType to the get message list params +func (o *GetMessageListParams) WithMessageSubType(messageSubType *string) *GetMessageListParams { + o.SetMessageSubType(messageSubType) + return o +} + +// SetMessageSubType adds the messageSubType to the get message list params +func (o *GetMessageListParams) SetMessageSubType(messageSubType *string) { + o.MessageSubType = messageSubType +} + +// WithMessageType adds the messageType to the get message list params +func (o *GetMessageListParams) WithMessageType(messageType *string) *GetMessageListParams { + o.SetMessageType(messageType) + return o +} + +// SetMessageType adds the messageType to the get message list params +func (o *GetMessageListParams) SetMessageType(messageType *string) { + o.MessageType = messageType +} + +// WithPageNumber adds the pageNumber to the get message list params +func (o *GetMessageListParams) WithPageNumber(pageNumber *int64) *GetMessageListParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the get message list params +func (o *GetMessageListParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the get message list params +func (o *GetMessageListParams) WithPageSize(pageSize *int64) *GetMessageListParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the get message list params +func (o *GetMessageListParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the get message list params +func (o *GetMessageListParams) WithTraceID(traceID string) *GetMessageListParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the get message list params +func (o *GetMessageListParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetMessageListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.Detail != nil { + + // query param detail + var qrDetail string + + if o.Detail != nil { + qrDetail = *o.Detail + } + qDetail := qrDetail + if qDetail != "" { + + if err := r.SetQueryParam("detail", qDetail); err != nil { + return err + } + } + } + + if o.HasRead != nil { + + // query param hasRead + var qrHasRead string + + if o.HasRead != nil { + qrHasRead = *o.HasRead + } + qHasRead := qrHasRead + if qHasRead != "" { + + if err := r.SetQueryParam("hasRead", qHasRead); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.MessageSubType != nil { + + // query param messageSubType + var qrMessageSubType string + + if o.MessageSubType != nil { + qrMessageSubType = *o.MessageSubType + } + qMessageSubType := qrMessageSubType + if qMessageSubType != "" { + + if err := r.SetQueryParam("messageSubType", qMessageSubType); err != nil { + return err + } + } + } + + if o.MessageType != nil { + + // query param messageType + var qrMessageType string + + if o.MessageType != nil { + qrMessageType = *o.MessageType + } + qMessageType := qrMessageType + if qMessageType != "" { + + if err := r.SetQueryParam("messageType", qMessageType); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_list_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_list_responses.go new file mode 100644 index 0000000..66f7243 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_list_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// GetMessageListReader is a Reader for the GetMessageList structure. +type GetMessageListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetMessageListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetMessageListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetMessageListDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetMessageListOK creates a GetMessageListOK with default headers values +func NewGetMessageListOK() *GetMessageListOK { + return &GetMessageListOK{} +} + +/* GetMessageListOK describes a response with status code 200, with default header values. + +GetMessageListOK get message list o k +*/ +type GetMessageListOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageListOKBody +} + +// IsSuccess returns true when this get message list o k response has a 2xx status code +func (o *GetMessageListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get message list o k response has a 3xx status code +func (o *GetMessageListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get message list o k response has a 4xx status code +func (o *GetMessageListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get message list o k response has a 5xx status code +func (o *GetMessageListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get message list o k response a status code equal to that given +func (o *GetMessageListOK) IsCode(code int) bool { + return code == 200 +} + +func (o *GetMessageListOK) Error() string { + return fmt.Sprintf("[GET /messages][%d] getMessageListOK %+v", 200, o.Payload) +} + +func (o *GetMessageListOK) String() string { + return fmt.Sprintf("[GET /messages][%d] getMessageListOK %+v", 200, o.Payload) +} + +func (o *GetMessageListOK) GetPayload() *GetMessageListOKBody { + return o.Payload +} + +func (o *GetMessageListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageListOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetMessageListDefault creates a GetMessageListDefault with default headers values +func NewGetMessageListDefault(code int) *GetMessageListDefault { + return &GetMessageListDefault{ + _statusCode: code, + } +} + +/* GetMessageListDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type GetMessageListDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageListDefaultBody +} + +// Code gets the status code for the get message list default response +func (o *GetMessageListDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this get message list default response has a 2xx status code +func (o *GetMessageListDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get message list default response has a 3xx status code +func (o *GetMessageListDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get message list default response has a 4xx status code +func (o *GetMessageListDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get message list default response has a 5xx status code +func (o *GetMessageListDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get message list default response a status code equal to that given +func (o *GetMessageListDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *GetMessageListDefault) Error() string { + return fmt.Sprintf("[GET /messages][%d] getMessageList default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageListDefault) String() string { + return fmt.Sprintf("[GET /messages][%d] getMessageList default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageListDefault) GetPayload() *GetMessageListDefaultBody { + return o.Payload +} + +func (o *GetMessageListDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageListDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*GetMessageListDefaultBody get message list default body +swagger:model GetMessageListDefaultBody +*/ +type GetMessageListDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this get message list default body +func (o *GetMessageListDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageListDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("getMessageList default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *GetMessageListDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("getMessageList default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageList default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageList default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message list default body based on the context it is used +func (o *GetMessageListDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageListDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageList default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageList default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageListDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageListDefaultBody) UnmarshalBinary(b []byte) error { + var res GetMessageListDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*GetMessageListOKBody get message list o k body +swagger:model GetMessageListOKBody +*/ +type GetMessageListOKBody struct { + + // result + Result *models.MessageList `json:"result,omitempty"` +} + +// Validate validates this get message list o k body +func (o *GetMessageListOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageListOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageListOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageListOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message list o k body based on the context it is used +func (o *GetMessageListOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageListOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageListOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageListOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageListOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageListOKBody) UnmarshalBinary(b []byte) error { + var res GetMessageListOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_statistic_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_statistic_parameters.go new file mode 100644 index 0000000..8775faf --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_statistic_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetMessageStatisticParams creates a new GetMessageStatisticParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetMessageStatisticParams() *GetMessageStatisticParams { + return &GetMessageStatisticParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetMessageStatisticParamsWithTimeout creates a new GetMessageStatisticParams object +// with the ability to set a timeout on a request. +func NewGetMessageStatisticParamsWithTimeout(timeout time.Duration) *GetMessageStatisticParams { + return &GetMessageStatisticParams{ + timeout: timeout, + } +} + +// NewGetMessageStatisticParamsWithContext creates a new GetMessageStatisticParams object +// with the ability to set a context for a request. +func NewGetMessageStatisticParamsWithContext(ctx context.Context) *GetMessageStatisticParams { + return &GetMessageStatisticParams{ + Context: ctx, + } +} + +// NewGetMessageStatisticParamsWithHTTPClient creates a new GetMessageStatisticParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetMessageStatisticParamsWithHTTPClient(client *http.Client) *GetMessageStatisticParams { + return &GetMessageStatisticParams{ + HTTPClient: client, + } +} + +/* GetMessageStatisticParams contains all the parameters to send to the API endpoint + for the get message statistic operation. + + Typically these are written to a http.Request. +*/ +type GetMessageStatisticParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get message statistic params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageStatisticParams) WithDefaults() *GetMessageStatisticParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get message statistic params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageStatisticParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get message statistic params +func (o *GetMessageStatisticParams) WithTimeout(timeout time.Duration) *GetMessageStatisticParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get message statistic params +func (o *GetMessageStatisticParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get message statistic params +func (o *GetMessageStatisticParams) WithContext(ctx context.Context) *GetMessageStatisticParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get message statistic params +func (o *GetMessageStatisticParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get message statistic params +func (o *GetMessageStatisticParams) WithHTTPClient(client *http.Client) *GetMessageStatisticParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get message statistic params +func (o *GetMessageStatisticParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the get message statistic params +func (o *GetMessageStatisticParams) WithAuthorization(authorization string) *GetMessageStatisticParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the get message statistic params +func (o *GetMessageStatisticParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the get message statistic params +func (o *GetMessageStatisticParams) WithBmpLanguage(bmpLanguage *string) *GetMessageStatisticParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the get message statistic params +func (o *GetMessageStatisticParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the get message statistic params +func (o *GetMessageStatisticParams) WithBmpUserID(bmpUserID *string) *GetMessageStatisticParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the get message statistic params +func (o *GetMessageStatisticParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the get message statistic params +func (o *GetMessageStatisticParams) WithTraceID(traceID string) *GetMessageStatisticParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the get message statistic params +func (o *GetMessageStatisticParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetMessageStatisticParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_statistic_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_statistic_responses.go new file mode 100644 index 0000000..70694df --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_statistic_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// GetMessageStatisticReader is a Reader for the GetMessageStatistic structure. +type GetMessageStatisticReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetMessageStatisticReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetMessageStatisticOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetMessageStatisticDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetMessageStatisticOK creates a GetMessageStatisticOK with default headers values +func NewGetMessageStatisticOK() *GetMessageStatisticOK { + return &GetMessageStatisticOK{} +} + +/* GetMessageStatisticOK describes a response with status code 200, with default header values. + +GetMessageStatisticOK get message statistic o k +*/ +type GetMessageStatisticOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageStatisticOKBody +} + +// IsSuccess returns true when this get message statistic o k response has a 2xx status code +func (o *GetMessageStatisticOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get message statistic o k response has a 3xx status code +func (o *GetMessageStatisticOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get message statistic o k response has a 4xx status code +func (o *GetMessageStatisticOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get message statistic o k response has a 5xx status code +func (o *GetMessageStatisticOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get message statistic o k response a status code equal to that given +func (o *GetMessageStatisticOK) IsCode(code int) bool { + return code == 200 +} + +func (o *GetMessageStatisticOK) Error() string { + return fmt.Sprintf("[GET /messages/statistic][%d] getMessageStatisticOK %+v", 200, o.Payload) +} + +func (o *GetMessageStatisticOK) String() string { + return fmt.Sprintf("[GET /messages/statistic][%d] getMessageStatisticOK %+v", 200, o.Payload) +} + +func (o *GetMessageStatisticOK) GetPayload() *GetMessageStatisticOKBody { + return o.Payload +} + +func (o *GetMessageStatisticOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageStatisticOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetMessageStatisticDefault creates a GetMessageStatisticDefault with default headers values +func NewGetMessageStatisticDefault(code int) *GetMessageStatisticDefault { + return &GetMessageStatisticDefault{ + _statusCode: code, + } +} + +/* GetMessageStatisticDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type GetMessageStatisticDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageStatisticDefaultBody +} + +// Code gets the status code for the get message statistic default response +func (o *GetMessageStatisticDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this get message statistic default response has a 2xx status code +func (o *GetMessageStatisticDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get message statistic default response has a 3xx status code +func (o *GetMessageStatisticDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get message statistic default response has a 4xx status code +func (o *GetMessageStatisticDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get message statistic default response has a 5xx status code +func (o *GetMessageStatisticDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get message statistic default response a status code equal to that given +func (o *GetMessageStatisticDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *GetMessageStatisticDefault) Error() string { + return fmt.Sprintf("[GET /messages/statistic][%d] getMessageStatistic default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageStatisticDefault) String() string { + return fmt.Sprintf("[GET /messages/statistic][%d] getMessageStatistic default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageStatisticDefault) GetPayload() *GetMessageStatisticDefaultBody { + return o.Payload +} + +func (o *GetMessageStatisticDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageStatisticDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*GetMessageStatisticDefaultBody get message statistic default body +swagger:model GetMessageStatisticDefaultBody +*/ +type GetMessageStatisticDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this get message statistic default body +func (o *GetMessageStatisticDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageStatisticDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("getMessageStatistic default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *GetMessageStatisticDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("getMessageStatistic default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageStatistic default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageStatistic default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message statistic default body based on the context it is used +func (o *GetMessageStatisticDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageStatisticDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageStatistic default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageStatistic default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageStatisticDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageStatisticDefaultBody) UnmarshalBinary(b []byte) error { + var res GetMessageStatisticDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*GetMessageStatisticOKBody get message statistic o k body +swagger:model GetMessageStatisticOKBody +*/ +type GetMessageStatisticOKBody struct { + + // result + Result *models.MessageStatistic `json:"result,omitempty"` +} + +// Validate validates this get message statistic o k body +func (o *GetMessageStatisticOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageStatisticOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageStatisticOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageStatisticOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message statistic o k body based on the context it is used +func (o *GetMessageStatisticOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageStatisticOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageStatisticOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageStatisticOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageStatisticOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageStatisticOKBody) UnmarshalBinary(b []byte) error { + var res GetMessageStatisticOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_types_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_types_parameters.go new file mode 100644 index 0000000..47c011c --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_types_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetMessageTypesParams creates a new GetMessageTypesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetMessageTypesParams() *GetMessageTypesParams { + return &GetMessageTypesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetMessageTypesParamsWithTimeout creates a new GetMessageTypesParams object +// with the ability to set a timeout on a request. +func NewGetMessageTypesParamsWithTimeout(timeout time.Duration) *GetMessageTypesParams { + return &GetMessageTypesParams{ + timeout: timeout, + } +} + +// NewGetMessageTypesParamsWithContext creates a new GetMessageTypesParams object +// with the ability to set a context for a request. +func NewGetMessageTypesParamsWithContext(ctx context.Context) *GetMessageTypesParams { + return &GetMessageTypesParams{ + Context: ctx, + } +} + +// NewGetMessageTypesParamsWithHTTPClient creates a new GetMessageTypesParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetMessageTypesParamsWithHTTPClient(client *http.Client) *GetMessageTypesParams { + return &GetMessageTypesParams{ + HTTPClient: client, + } +} + +/* GetMessageTypesParams contains all the parameters to send to the API endpoint + for the get message types operation. + + Typically these are written to a http.Request. +*/ +type GetMessageTypesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get message types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageTypesParams) WithDefaults() *GetMessageTypesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get message types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageTypesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get message types params +func (o *GetMessageTypesParams) WithTimeout(timeout time.Duration) *GetMessageTypesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get message types params +func (o *GetMessageTypesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get message types params +func (o *GetMessageTypesParams) WithContext(ctx context.Context) *GetMessageTypesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get message types params +func (o *GetMessageTypesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get message types params +func (o *GetMessageTypesParams) WithHTTPClient(client *http.Client) *GetMessageTypesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get message types params +func (o *GetMessageTypesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the get message types params +func (o *GetMessageTypesParams) WithAuthorization(authorization string) *GetMessageTypesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the get message types params +func (o *GetMessageTypesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the get message types params +func (o *GetMessageTypesParams) WithBmpLanguage(bmpLanguage *string) *GetMessageTypesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the get message types params +func (o *GetMessageTypesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the get message types params +func (o *GetMessageTypesParams) WithBmpUserID(bmpUserID *string) *GetMessageTypesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the get message types params +func (o *GetMessageTypesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the get message types params +func (o *GetMessageTypesParams) WithTraceID(traceID string) *GetMessageTypesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the get message types params +func (o *GetMessageTypesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetMessageTypesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_types_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_types_responses.go new file mode 100644 index 0000000..ed14a46 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/get_message_types_responses.go @@ -0,0 +1,401 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// GetMessageTypesReader is a Reader for the GetMessageTypes structure. +type GetMessageTypesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetMessageTypesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetMessageTypesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetMessageTypesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetMessageTypesOK creates a GetMessageTypesOK with default headers values +func NewGetMessageTypesOK() *GetMessageTypesOK { + return &GetMessageTypesOK{} +} + +/* GetMessageTypesOK describes a response with status code 200, with default header values. + +GetMessageTypesOK get message types o k +*/ +type GetMessageTypesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageTypesOKBody +} + +// IsSuccess returns true when this get message types o k response has a 2xx status code +func (o *GetMessageTypesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get message types o k response has a 3xx status code +func (o *GetMessageTypesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get message types o k response has a 4xx status code +func (o *GetMessageTypesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get message types o k response has a 5xx status code +func (o *GetMessageTypesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get message types o k response a status code equal to that given +func (o *GetMessageTypesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *GetMessageTypesOK) Error() string { + return fmt.Sprintf("[GET /messages/getMessageTypes][%d] getMessageTypesOK %+v", 200, o.Payload) +} + +func (o *GetMessageTypesOK) String() string { + return fmt.Sprintf("[GET /messages/getMessageTypes][%d] getMessageTypesOK %+v", 200, o.Payload) +} + +func (o *GetMessageTypesOK) GetPayload() *GetMessageTypesOKBody { + return o.Payload +} + +func (o *GetMessageTypesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageTypesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetMessageTypesDefault creates a GetMessageTypesDefault with default headers values +func NewGetMessageTypesDefault(code int) *GetMessageTypesDefault { + return &GetMessageTypesDefault{ + _statusCode: code, + } +} + +/* GetMessageTypesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type GetMessageTypesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageTypesDefaultBody +} + +// Code gets the status code for the get message types default response +func (o *GetMessageTypesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this get message types default response has a 2xx status code +func (o *GetMessageTypesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get message types default response has a 3xx status code +func (o *GetMessageTypesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get message types default response has a 4xx status code +func (o *GetMessageTypesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get message types default response has a 5xx status code +func (o *GetMessageTypesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get message types default response a status code equal to that given +func (o *GetMessageTypesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *GetMessageTypesDefault) Error() string { + return fmt.Sprintf("[GET /messages/getMessageTypes][%d] getMessageTypes default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageTypesDefault) String() string { + return fmt.Sprintf("[GET /messages/getMessageTypes][%d] getMessageTypes default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageTypesDefault) GetPayload() *GetMessageTypesDefaultBody { + return o.Payload +} + +func (o *GetMessageTypesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageTypesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*GetMessageTypesDefaultBody get message types default body +swagger:model GetMessageTypesDefaultBody +*/ +type GetMessageTypesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this get message types default body +func (o *GetMessageTypesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageTypesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("getMessageTypes default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *GetMessageTypesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("getMessageTypes default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message types default body based on the context it is used +func (o *GetMessageTypesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageTypesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageTypesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageTypesDefaultBody) UnmarshalBinary(b []byte) error { + var res GetMessageTypesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*GetMessageTypesOKBody get message types o k body +swagger:model GetMessageTypesOKBody +*/ +type GetMessageTypesOKBody struct { + + // result + Result models.MessageTypesResp `json:"result,omitempty"` +} + +// Validate validates this get message types o k body +func (o *GetMessageTypesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageTypesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageTypesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message types o k body based on the context it is used +func (o *GetMessageTypesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageTypesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageTypesOK" + "." + "result") + } + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageTypesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageTypesOKBody) UnmarshalBinary(b []byte) error { + var res GetMessageTypesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/has_unread_message_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/has_unread_message_parameters.go new file mode 100644 index 0000000..574dec2 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/has_unread_message_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewHasUnreadMessageParams creates a new HasUnreadMessageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewHasUnreadMessageParams() *HasUnreadMessageParams { + return &HasUnreadMessageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewHasUnreadMessageParamsWithTimeout creates a new HasUnreadMessageParams object +// with the ability to set a timeout on a request. +func NewHasUnreadMessageParamsWithTimeout(timeout time.Duration) *HasUnreadMessageParams { + return &HasUnreadMessageParams{ + timeout: timeout, + } +} + +// NewHasUnreadMessageParamsWithContext creates a new HasUnreadMessageParams object +// with the ability to set a context for a request. +func NewHasUnreadMessageParamsWithContext(ctx context.Context) *HasUnreadMessageParams { + return &HasUnreadMessageParams{ + Context: ctx, + } +} + +// NewHasUnreadMessageParamsWithHTTPClient creates a new HasUnreadMessageParams object +// with the ability to set a custom HTTPClient for a request. +func NewHasUnreadMessageParamsWithHTTPClient(client *http.Client) *HasUnreadMessageParams { + return &HasUnreadMessageParams{ + HTTPClient: client, + } +} + +/* HasUnreadMessageParams contains all the parameters to send to the API endpoint + for the has unread message operation. + + Typically these are written to a http.Request. +*/ +type HasUnreadMessageParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the has unread message params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *HasUnreadMessageParams) WithDefaults() *HasUnreadMessageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the has unread message params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *HasUnreadMessageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the has unread message params +func (o *HasUnreadMessageParams) WithTimeout(timeout time.Duration) *HasUnreadMessageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the has unread message params +func (o *HasUnreadMessageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the has unread message params +func (o *HasUnreadMessageParams) WithContext(ctx context.Context) *HasUnreadMessageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the has unread message params +func (o *HasUnreadMessageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the has unread message params +func (o *HasUnreadMessageParams) WithHTTPClient(client *http.Client) *HasUnreadMessageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the has unread message params +func (o *HasUnreadMessageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the has unread message params +func (o *HasUnreadMessageParams) WithAuthorization(authorization string) *HasUnreadMessageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the has unread message params +func (o *HasUnreadMessageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the has unread message params +func (o *HasUnreadMessageParams) WithBmpLanguage(bmpLanguage *string) *HasUnreadMessageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the has unread message params +func (o *HasUnreadMessageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the has unread message params +func (o *HasUnreadMessageParams) WithBmpUserID(bmpUserID *string) *HasUnreadMessageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the has unread message params +func (o *HasUnreadMessageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the has unread message params +func (o *HasUnreadMessageParams) WithTraceID(traceID string) *HasUnreadMessageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the has unread message params +func (o *HasUnreadMessageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *HasUnreadMessageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/has_unread_message_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/has_unread_message_responses.go new file mode 100644 index 0000000..13990ec --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/has_unread_message_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// HasUnreadMessageReader is a Reader for the HasUnreadMessage structure. +type HasUnreadMessageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *HasUnreadMessageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewHasUnreadMessageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewHasUnreadMessageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewHasUnreadMessageOK creates a HasUnreadMessageOK with default headers values +func NewHasUnreadMessageOK() *HasUnreadMessageOK { + return &HasUnreadMessageOK{} +} + +/* HasUnreadMessageOK describes a response with status code 200, with default header values. + +HasUnreadMessageOK has unread message o k +*/ +type HasUnreadMessageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *HasUnreadMessageOKBody +} + +// IsSuccess returns true when this has unread message o k response has a 2xx status code +func (o *HasUnreadMessageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this has unread message o k response has a 3xx status code +func (o *HasUnreadMessageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this has unread message o k response has a 4xx status code +func (o *HasUnreadMessageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this has unread message o k response has a 5xx status code +func (o *HasUnreadMessageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this has unread message o k response a status code equal to that given +func (o *HasUnreadMessageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *HasUnreadMessageOK) Error() string { + return fmt.Sprintf("[GET /messages/hasUnreadMessage][%d] hasUnreadMessageOK %+v", 200, o.Payload) +} + +func (o *HasUnreadMessageOK) String() string { + return fmt.Sprintf("[GET /messages/hasUnreadMessage][%d] hasUnreadMessageOK %+v", 200, o.Payload) +} + +func (o *HasUnreadMessageOK) GetPayload() *HasUnreadMessageOKBody { + return o.Payload +} + +func (o *HasUnreadMessageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(HasUnreadMessageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewHasUnreadMessageDefault creates a HasUnreadMessageDefault with default headers values +func NewHasUnreadMessageDefault(code int) *HasUnreadMessageDefault { + return &HasUnreadMessageDefault{ + _statusCode: code, + } +} + +/* HasUnreadMessageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type HasUnreadMessageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *HasUnreadMessageDefaultBody +} + +// Code gets the status code for the has unread message default response +func (o *HasUnreadMessageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this has unread message default response has a 2xx status code +func (o *HasUnreadMessageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this has unread message default response has a 3xx status code +func (o *HasUnreadMessageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this has unread message default response has a 4xx status code +func (o *HasUnreadMessageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this has unread message default response has a 5xx status code +func (o *HasUnreadMessageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this has unread message default response a status code equal to that given +func (o *HasUnreadMessageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *HasUnreadMessageDefault) Error() string { + return fmt.Sprintf("[GET /messages/hasUnreadMessage][%d] hasUnreadMessage default %+v", o._statusCode, o.Payload) +} + +func (o *HasUnreadMessageDefault) String() string { + return fmt.Sprintf("[GET /messages/hasUnreadMessage][%d] hasUnreadMessage default %+v", o._statusCode, o.Payload) +} + +func (o *HasUnreadMessageDefault) GetPayload() *HasUnreadMessageDefaultBody { + return o.Payload +} + +func (o *HasUnreadMessageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(HasUnreadMessageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*HasUnreadMessageDefaultBody has unread message default body +swagger:model HasUnreadMessageDefaultBody +*/ +type HasUnreadMessageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this has unread message default body +func (o *HasUnreadMessageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *HasUnreadMessageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("hasUnreadMessage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *HasUnreadMessageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("hasUnreadMessage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("hasUnreadMessage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("hasUnreadMessage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this has unread message default body based on the context it is used +func (o *HasUnreadMessageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *HasUnreadMessageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("hasUnreadMessage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("hasUnreadMessage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *HasUnreadMessageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *HasUnreadMessageDefaultBody) UnmarshalBinary(b []byte) error { + var res HasUnreadMessageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*HasUnreadMessageOKBody has unread message o k body +swagger:model HasUnreadMessageOKBody +*/ +type HasUnreadMessageOKBody struct { + + // result + Result *models.HasUnreadMessage `json:"result,omitempty"` +} + +// Validate validates this has unread message o k body +func (o *HasUnreadMessageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *HasUnreadMessageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("hasUnreadMessageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("hasUnreadMessageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this has unread message o k body based on the context it is used +func (o *HasUnreadMessageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *HasUnreadMessageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("hasUnreadMessageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("hasUnreadMessageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *HasUnreadMessageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *HasUnreadMessageOKBody) UnmarshalBinary(b []byte) error { + var res HasUnreadMessageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/message_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/message_client.go new file mode 100644 index 0000000..c4c8f1e --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/message_client.go @@ -0,0 +1,317 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new message API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for message API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DeleteMessage(params *DeleteMessageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteMessageOK, error) + + GetMessageByID(params *GetMessageByIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageByIDOK, error) + + GetMessageList(params *GetMessageListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageListOK, error) + + GetMessageStatistic(params *GetMessageStatisticParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageStatisticOK, error) + + GetMessageTypes(params *GetMessageTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageTypesOK, error) + + HasUnreadMessage(params *HasUnreadMessageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*HasUnreadMessageOK, error) + + ReadMessage(params *ReadMessageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ReadMessageOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DeleteMessage DeleteMessage 删除消息(可多条) +*/ +func (a *Client) DeleteMessage(params *DeleteMessageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteMessageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteMessageParams() + } + op := &runtime.ClientOperation{ + ID: "deleteMessage", + Method: "DELETE", + PathPattern: "/messages/delete", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteMessageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteMessageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteMessageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + GetMessageByID GetMessageById 获取消息详情,包括上一条/下一条的messageid +*/ +func (a *Client) GetMessageByID(params *GetMessageByIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageByIDOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetMessageByIDParams() + } + op := &runtime.ClientOperation{ + ID: "getMessageById", + Method: "GET", + PathPattern: "/messages/getMessageById", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetMessageByIDReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetMessageByIDOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetMessageByIDDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + GetMessageList GetMessageList 获取message列表(分页) +*/ +func (a *Client) GetMessageList(params *GetMessageListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetMessageListParams() + } + op := &runtime.ClientOperation{ + ID: "getMessageList", + Method: "GET", + PathPattern: "/messages", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetMessageListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetMessageListOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetMessageListDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + GetMessageStatistic GetMessageStatistic 获取message总数和未读数 +*/ +func (a *Client) GetMessageStatistic(params *GetMessageStatisticParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageStatisticOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetMessageStatisticParams() + } + op := &runtime.ClientOperation{ + ID: "getMessageStatistic", + Method: "GET", + PathPattern: "/messages/statistic", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetMessageStatisticReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetMessageStatisticOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetMessageStatisticDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + GetMessageTypes GetMessageTypes 获取消息类型/子类型 +*/ +func (a *Client) GetMessageTypes(params *GetMessageTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageTypesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetMessageTypesParams() + } + op := &runtime.ClientOperation{ + ID: "getMessageTypes", + Method: "GET", + PathPattern: "/messages/getMessageTypes", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetMessageTypesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetMessageTypesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetMessageTypesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + HasUnreadMessage HasUnreadMessage 获取有没有未读消息 +*/ +func (a *Client) HasUnreadMessage(params *HasUnreadMessageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*HasUnreadMessageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewHasUnreadMessageParams() + } + op := &runtime.ClientOperation{ + ID: "hasUnreadMessage", + Method: "GET", + PathPattern: "/messages/hasUnreadMessage", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &HasUnreadMessageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*HasUnreadMessageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*HasUnreadMessageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ReadMessage ReadMessage 将消息设置为已读(可多条) +*/ +func (a *Client) ReadMessage(params *ReadMessageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ReadMessageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewReadMessageParams() + } + op := &runtime.ClientOperation{ + ID: "readMessage", + Method: "PUT", + PathPattern: "/messages/doRead", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ReadMessageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ReadMessageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ReadMessageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/read_message_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/read_message_parameters.go new file mode 100644 index 0000000..e53ede2 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/read_message_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewReadMessageParams creates a new ReadMessageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewReadMessageParams() *ReadMessageParams { + return &ReadMessageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewReadMessageParamsWithTimeout creates a new ReadMessageParams object +// with the ability to set a timeout on a request. +func NewReadMessageParamsWithTimeout(timeout time.Duration) *ReadMessageParams { + return &ReadMessageParams{ + timeout: timeout, + } +} + +// NewReadMessageParamsWithContext creates a new ReadMessageParams object +// with the ability to set a context for a request. +func NewReadMessageParamsWithContext(ctx context.Context) *ReadMessageParams { + return &ReadMessageParams{ + Context: ctx, + } +} + +// NewReadMessageParamsWithHTTPClient creates a new ReadMessageParams object +// with the ability to set a custom HTTPClient for a request. +func NewReadMessageParamsWithHTTPClient(client *http.Client) *ReadMessageParams { + return &ReadMessageParams{ + HTTPClient: client, + } +} + +/* ReadMessageParams contains all the parameters to send to the API endpoint + for the read message operation. + + Typically these are written to a http.Request. +*/ +type ReadMessageParams struct { + + // Body. + Body *models.ReadMessagesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the read message params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ReadMessageParams) WithDefaults() *ReadMessageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the read message params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ReadMessageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the read message params +func (o *ReadMessageParams) WithTimeout(timeout time.Duration) *ReadMessageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the read message params +func (o *ReadMessageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the read message params +func (o *ReadMessageParams) WithContext(ctx context.Context) *ReadMessageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the read message params +func (o *ReadMessageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the read message params +func (o *ReadMessageParams) WithHTTPClient(client *http.Client) *ReadMessageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the read message params +func (o *ReadMessageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the read message params +func (o *ReadMessageParams) WithBody(body *models.ReadMessagesRequest) *ReadMessageParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the read message params +func (o *ReadMessageParams) SetBody(body *models.ReadMessagesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the read message params +func (o *ReadMessageParams) WithAuthorization(authorization string) *ReadMessageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the read message params +func (o *ReadMessageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the read message params +func (o *ReadMessageParams) WithBmpLanguage(bmpLanguage *string) *ReadMessageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the read message params +func (o *ReadMessageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the read message params +func (o *ReadMessageParams) WithBmpUserID(bmpUserID *string) *ReadMessageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the read message params +func (o *ReadMessageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the read message params +func (o *ReadMessageParams) WithTraceID(traceID string) *ReadMessageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the read message params +func (o *ReadMessageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ReadMessageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/read_message_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/read_message_responses.go new file mode 100644 index 0000000..5a86eed --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/message/read_message_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// ReadMessageReader is a Reader for the ReadMessage structure. +type ReadMessageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ReadMessageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewReadMessageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewReadMessageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewReadMessageOK creates a ReadMessageOK with default headers values +func NewReadMessageOK() *ReadMessageOK { + return &ReadMessageOK{} +} + +/* ReadMessageOK describes a response with status code 200, with default header values. + +A ReadMessageResult is an response struct +*/ +type ReadMessageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ReadMessageOKBody +} + +// IsSuccess returns true when this read message o k response has a 2xx status code +func (o *ReadMessageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this read message o k response has a 3xx status code +func (o *ReadMessageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this read message o k response has a 4xx status code +func (o *ReadMessageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this read message o k response has a 5xx status code +func (o *ReadMessageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this read message o k response a status code equal to that given +func (o *ReadMessageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ReadMessageOK) Error() string { + return fmt.Sprintf("[PUT /messages/doRead][%d] readMessageOK %+v", 200, o.Payload) +} + +func (o *ReadMessageOK) String() string { + return fmt.Sprintf("[PUT /messages/doRead][%d] readMessageOK %+v", 200, o.Payload) +} + +func (o *ReadMessageOK) GetPayload() *ReadMessageOKBody { + return o.Payload +} + +func (o *ReadMessageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ReadMessageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewReadMessageDefault creates a ReadMessageDefault with default headers values +func NewReadMessageDefault(code int) *ReadMessageDefault { + return &ReadMessageDefault{ + _statusCode: code, + } +} + +/* ReadMessageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ReadMessageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ReadMessageDefaultBody +} + +// Code gets the status code for the read message default response +func (o *ReadMessageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this read message default response has a 2xx status code +func (o *ReadMessageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this read message default response has a 3xx status code +func (o *ReadMessageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this read message default response has a 4xx status code +func (o *ReadMessageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this read message default response has a 5xx status code +func (o *ReadMessageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this read message default response a status code equal to that given +func (o *ReadMessageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ReadMessageDefault) Error() string { + return fmt.Sprintf("[PUT /messages/doRead][%d] readMessage default %+v", o._statusCode, o.Payload) +} + +func (o *ReadMessageDefault) String() string { + return fmt.Sprintf("[PUT /messages/doRead][%d] readMessage default %+v", o._statusCode, o.Payload) +} + +func (o *ReadMessageDefault) GetPayload() *ReadMessageDefaultBody { + return o.Payload +} + +func (o *ReadMessageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ReadMessageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ReadMessageDefaultBody read message default body +swagger:model ReadMessageDefaultBody +*/ +type ReadMessageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this read message default body +func (o *ReadMessageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReadMessageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("readMessage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ReadMessageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("readMessage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("readMessage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("readMessage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this read message default body based on the context it is used +func (o *ReadMessageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReadMessageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("readMessage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("readMessage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ReadMessageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ReadMessageDefaultBody) UnmarshalBinary(b []byte) error { + var res ReadMessageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ReadMessageOKBody read message o k body +swagger:model ReadMessageOKBody +*/ +type ReadMessageOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this read message o k body +func (o *ReadMessageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReadMessageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("readMessageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("readMessageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this read message o k body based on the context it is used +func (o *ReadMessageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReadMessageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("readMessageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("readMessageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ReadMessageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ReadMessageOKBody) UnmarshalBinary(b []byte) error { + var res ReadMessageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/add_alert_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/add_alert_parameters.go new file mode 100644 index 0000000..7e087e4 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/add_alert_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewAddAlertParams creates a new AddAlertParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewAddAlertParams() *AddAlertParams { + return &AddAlertParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewAddAlertParamsWithTimeout creates a new AddAlertParams object +// with the ability to set a timeout on a request. +func NewAddAlertParamsWithTimeout(timeout time.Duration) *AddAlertParams { + return &AddAlertParams{ + timeout: timeout, + } +} + +// NewAddAlertParamsWithContext creates a new AddAlertParams object +// with the ability to set a context for a request. +func NewAddAlertParamsWithContext(ctx context.Context) *AddAlertParams { + return &AddAlertParams{ + Context: ctx, + } +} + +// NewAddAlertParamsWithHTTPClient creates a new AddAlertParams object +// with the ability to set a custom HTTPClient for a request. +func NewAddAlertParamsWithHTTPClient(client *http.Client) *AddAlertParams { + return &AddAlertParams{ + HTTPClient: client, + } +} + +/* AddAlertParams contains all the parameters to send to the API endpoint + for the add alert operation. + + Typically these are written to a http.Request. +*/ +type AddAlertParams struct { + + // Body. + Body *models.AddAlertRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the add alert params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AddAlertParams) WithDefaults() *AddAlertParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the add alert params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AddAlertParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the add alert params +func (o *AddAlertParams) WithTimeout(timeout time.Duration) *AddAlertParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the add alert params +func (o *AddAlertParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the add alert params +func (o *AddAlertParams) WithContext(ctx context.Context) *AddAlertParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the add alert params +func (o *AddAlertParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the add alert params +func (o *AddAlertParams) WithHTTPClient(client *http.Client) *AddAlertParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the add alert params +func (o *AddAlertParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the add alert params +func (o *AddAlertParams) WithBody(body *models.AddAlertRequest) *AddAlertParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the add alert params +func (o *AddAlertParams) SetBody(body *models.AddAlertRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the add alert params +func (o *AddAlertParams) WithAuthorization(authorization string) *AddAlertParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the add alert params +func (o *AddAlertParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the add alert params +func (o *AddAlertParams) WithBmpLanguage(bmpLanguage *string) *AddAlertParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the add alert params +func (o *AddAlertParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the add alert params +func (o *AddAlertParams) WithBmpUserID(bmpUserID *string) *AddAlertParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the add alert params +func (o *AddAlertParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the add alert params +func (o *AddAlertParams) WithTraceID(traceID string) *AddAlertParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the add alert params +func (o *AddAlertParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *AddAlertParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/add_alert_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/add_alert_responses.go new file mode 100644 index 0000000..6988ae1 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/add_alert_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// AddAlertReader is a Reader for the AddAlert structure. +type AddAlertReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *AddAlertReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewAddAlertOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewAddAlertDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewAddAlertOK creates a AddAlertOK with default headers values +func NewAddAlertOK() *AddAlertOK { + return &AddAlertOK{} +} + +/* AddAlertOK describes a response with status code 200, with default header values. + +A AddAlertResult is an response struct that is used to describe create Alert result. +*/ +type AddAlertOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *AddAlertOKBody +} + +// IsSuccess returns true when this add alert o k response has a 2xx status code +func (o *AddAlertOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this add alert o k response has a 3xx status code +func (o *AddAlertOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this add alert o k response has a 4xx status code +func (o *AddAlertOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this add alert o k response has a 5xx status code +func (o *AddAlertOK) IsServerError() bool { + return false +} + +// IsCode returns true when this add alert o k response a status code equal to that given +func (o *AddAlertOK) IsCode(code int) bool { + return code == 200 +} + +func (o *AddAlertOK) Error() string { + return fmt.Sprintf("[POST /monitorAlert/addAlert][%d] addAlertOK %+v", 200, o.Payload) +} + +func (o *AddAlertOK) String() string { + return fmt.Sprintf("[POST /monitorAlert/addAlert][%d] addAlertOK %+v", 200, o.Payload) +} + +func (o *AddAlertOK) GetPayload() *AddAlertOKBody { + return o.Payload +} + +func (o *AddAlertOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AddAlertOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAddAlertDefault creates a AddAlertDefault with default headers values +func NewAddAlertDefault(code int) *AddAlertDefault { + return &AddAlertDefault{ + _statusCode: code, + } +} + +/* AddAlertDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type AddAlertDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *AddAlertDefaultBody +} + +// Code gets the status code for the add alert default response +func (o *AddAlertDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this add alert default response has a 2xx status code +func (o *AddAlertDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this add alert default response has a 3xx status code +func (o *AddAlertDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this add alert default response has a 4xx status code +func (o *AddAlertDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this add alert default response has a 5xx status code +func (o *AddAlertDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this add alert default response a status code equal to that given +func (o *AddAlertDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *AddAlertDefault) Error() string { + return fmt.Sprintf("[POST /monitorAlert/addAlert][%d] addAlert default %+v", o._statusCode, o.Payload) +} + +func (o *AddAlertDefault) String() string { + return fmt.Sprintf("[POST /monitorAlert/addAlert][%d] addAlert default %+v", o._statusCode, o.Payload) +} + +func (o *AddAlertDefault) GetPayload() *AddAlertDefaultBody { + return o.Payload +} + +func (o *AddAlertDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AddAlertDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*AddAlertDefaultBody add alert default body +swagger:model AddAlertDefaultBody +*/ +type AddAlertDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this add alert default body +func (o *AddAlertDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AddAlertDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("addAlert default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *AddAlertDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("addAlert default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("addAlert default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("addAlert default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this add alert default body based on the context it is used +func (o *AddAlertDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AddAlertDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("addAlert default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("addAlert default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AddAlertDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AddAlertDefaultBody) UnmarshalBinary(b []byte) error { + var res AddAlertDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*AddAlertOKBody add alert o k body +swagger:model AddAlertOKBody +*/ +type AddAlertOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this add alert o k body +func (o *AddAlertOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AddAlertOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("addAlertOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("addAlertOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this add alert o k body based on the context it is used +func (o *AddAlertOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AddAlertOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("addAlertOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("addAlertOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AddAlertOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AddAlertOKBody) UnmarshalBinary(b []byte) error { + var res AddAlertOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/delete_alert_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/delete_alert_parameters.go new file mode 100644 index 0000000..c6d9b97 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/delete_alert_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewDeleteAlertParams creates a new DeleteAlertParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteAlertParams() *DeleteAlertParams { + return &DeleteAlertParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteAlertParamsWithTimeout creates a new DeleteAlertParams object +// with the ability to set a timeout on a request. +func NewDeleteAlertParamsWithTimeout(timeout time.Duration) *DeleteAlertParams { + return &DeleteAlertParams{ + timeout: timeout, + } +} + +// NewDeleteAlertParamsWithContext creates a new DeleteAlertParams object +// with the ability to set a context for a request. +func NewDeleteAlertParamsWithContext(ctx context.Context) *DeleteAlertParams { + return &DeleteAlertParams{ + Context: ctx, + } +} + +// NewDeleteAlertParamsWithHTTPClient creates a new DeleteAlertParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteAlertParamsWithHTTPClient(client *http.Client) *DeleteAlertParams { + return &DeleteAlertParams{ + HTTPClient: client, + } +} + +/* DeleteAlertParams contains all the parameters to send to the API endpoint + for the delete alert operation. + + Typically these are written to a http.Request. +*/ +type DeleteAlertParams struct { + + // Body. + Body *models.DeleteAlertRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete alert params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteAlertParams) WithDefaults() *DeleteAlertParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete alert params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteAlertParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete alert params +func (o *DeleteAlertParams) WithTimeout(timeout time.Duration) *DeleteAlertParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete alert params +func (o *DeleteAlertParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete alert params +func (o *DeleteAlertParams) WithContext(ctx context.Context) *DeleteAlertParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete alert params +func (o *DeleteAlertParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete alert params +func (o *DeleteAlertParams) WithHTTPClient(client *http.Client) *DeleteAlertParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete alert params +func (o *DeleteAlertParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the delete alert params +func (o *DeleteAlertParams) WithBody(body *models.DeleteAlertRequest) *DeleteAlertParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the delete alert params +func (o *DeleteAlertParams) SetBody(body *models.DeleteAlertRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the delete alert params +func (o *DeleteAlertParams) WithAuthorization(authorization string) *DeleteAlertParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete alert params +func (o *DeleteAlertParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete alert params +func (o *DeleteAlertParams) WithBmpLanguage(bmpLanguage *string) *DeleteAlertParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete alert params +func (o *DeleteAlertParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete alert params +func (o *DeleteAlertParams) WithBmpUserID(bmpUserID *string) *DeleteAlertParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete alert params +func (o *DeleteAlertParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete alert params +func (o *DeleteAlertParams) WithTraceID(traceID string) *DeleteAlertParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete alert params +func (o *DeleteAlertParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteAlertParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/delete_alert_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/delete_alert_responses.go new file mode 100644 index 0000000..cfca19b --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/delete_alert_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DeleteAlertReader is a Reader for the DeleteAlert structure. +type DeleteAlertReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteAlertReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteAlertOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteAlertDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteAlertOK creates a DeleteAlertOK with default headers values +func NewDeleteAlertOK() *DeleteAlertOK { + return &DeleteAlertOK{} +} + +/* DeleteAlertOK describes a response with status code 200, with default header values. + +A DeleteAlertResult is an response struct that is used to describe create alert result. +*/ +type DeleteAlertOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteAlertOKBody +} + +// IsSuccess returns true when this delete alert o k response has a 2xx status code +func (o *DeleteAlertOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete alert o k response has a 3xx status code +func (o *DeleteAlertOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete alert o k response has a 4xx status code +func (o *DeleteAlertOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete alert o k response has a 5xx status code +func (o *DeleteAlertOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete alert o k response a status code equal to that given +func (o *DeleteAlertOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteAlertOK) Error() string { + return fmt.Sprintf("[DELETE /monitorAlert/deleteAlert][%d] deleteAlertOK %+v", 200, o.Payload) +} + +func (o *DeleteAlertOK) String() string { + return fmt.Sprintf("[DELETE /monitorAlert/deleteAlert][%d] deleteAlertOK %+v", 200, o.Payload) +} + +func (o *DeleteAlertOK) GetPayload() *DeleteAlertOKBody { + return o.Payload +} + +func (o *DeleteAlertOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteAlertOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteAlertDefault creates a DeleteAlertDefault with default headers values +func NewDeleteAlertDefault(code int) *DeleteAlertDefault { + return &DeleteAlertDefault{ + _statusCode: code, + } +} + +/* DeleteAlertDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteAlertDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteAlertDefaultBody +} + +// Code gets the status code for the delete alert default response +func (o *DeleteAlertDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete alert default response has a 2xx status code +func (o *DeleteAlertDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete alert default response has a 3xx status code +func (o *DeleteAlertDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete alert default response has a 4xx status code +func (o *DeleteAlertDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete alert default response has a 5xx status code +func (o *DeleteAlertDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete alert default response a status code equal to that given +func (o *DeleteAlertDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteAlertDefault) Error() string { + return fmt.Sprintf("[DELETE /monitorAlert/deleteAlert][%d] deleteAlert default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteAlertDefault) String() string { + return fmt.Sprintf("[DELETE /monitorAlert/deleteAlert][%d] deleteAlert default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteAlertDefault) GetPayload() *DeleteAlertDefaultBody { + return o.Payload +} + +func (o *DeleteAlertDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteAlertDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteAlertDefaultBody delete alert default body +swagger:model DeleteAlertDefaultBody +*/ +type DeleteAlertDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete alert default body +func (o *DeleteAlertDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteAlertDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteAlert default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteAlertDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteAlert default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteAlert default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteAlert default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete alert default body based on the context it is used +func (o *DeleteAlertDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteAlertDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteAlert default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteAlert default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteAlertDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteAlertDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteAlertDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteAlertOKBody delete alert o k body +swagger:model DeleteAlertOKBody +*/ +type DeleteAlertOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete alert o k body +func (o *DeleteAlertOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteAlertOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteAlertOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteAlertOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete alert o k body based on the context it is used +func (o *DeleteAlertOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteAlertOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteAlertOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteAlertOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteAlertOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteAlertOKBody) UnmarshalBinary(b []byte) error { + var res DeleteAlertOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/describe_alert_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/describe_alert_parameters.go new file mode 100644 index 0000000..7e32513 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/describe_alert_parameters.go @@ -0,0 +1,248 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeAlertParams creates a new DescribeAlertParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeAlertParams() *DescribeAlertParams { + return &DescribeAlertParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeAlertParamsWithTimeout creates a new DescribeAlertParams object +// with the ability to set a timeout on a request. +func NewDescribeAlertParamsWithTimeout(timeout time.Duration) *DescribeAlertParams { + return &DescribeAlertParams{ + timeout: timeout, + } +} + +// NewDescribeAlertParamsWithContext creates a new DescribeAlertParams object +// with the ability to set a context for a request. +func NewDescribeAlertParamsWithContext(ctx context.Context) *DescribeAlertParams { + return &DescribeAlertParams{ + Context: ctx, + } +} + +// NewDescribeAlertParamsWithHTTPClient creates a new DescribeAlertParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeAlertParamsWithHTTPClient(client *http.Client) *DescribeAlertParams { + return &DescribeAlertParams{ + HTTPClient: client, + } +} + +/* DescribeAlertParams contains all the parameters to send to the API endpoint + for the describe alert operation. + + Typically these are written to a http.Request. +*/ +type DescribeAlertParams struct { + + /* AlertID. + + rule uuid + */ + AlertID string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe alert params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAlertParams) WithDefaults() *DescribeAlertParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe alert params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAlertParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe alert params +func (o *DescribeAlertParams) WithTimeout(timeout time.Duration) *DescribeAlertParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe alert params +func (o *DescribeAlertParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe alert params +func (o *DescribeAlertParams) WithContext(ctx context.Context) *DescribeAlertParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe alert params +func (o *DescribeAlertParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe alert params +func (o *DescribeAlertParams) WithHTTPClient(client *http.Client) *DescribeAlertParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe alert params +func (o *DescribeAlertParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAlertID adds the alertID to the describe alert params +func (o *DescribeAlertParams) WithAlertID(alertID string) *DescribeAlertParams { + o.SetAlertID(alertID) + return o +} + +// SetAlertID adds the alertId to the describe alert params +func (o *DescribeAlertParams) SetAlertID(alertID string) { + o.AlertID = alertID +} + +// WithAuthorization adds the authorization to the describe alert params +func (o *DescribeAlertParams) WithAuthorization(authorization string) *DescribeAlertParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe alert params +func (o *DescribeAlertParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe alert params +func (o *DescribeAlertParams) WithBmpLanguage(bmpLanguage *string) *DescribeAlertParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe alert params +func (o *DescribeAlertParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe alert params +func (o *DescribeAlertParams) WithBmpUserID(bmpUserID *string) *DescribeAlertParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe alert params +func (o *DescribeAlertParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe alert params +func (o *DescribeAlertParams) WithTraceID(traceID string) *DescribeAlertParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe alert params +func (o *DescribeAlertParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeAlertParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // query param alertId + qrAlertID := o.AlertID + qAlertID := qrAlertID + if qAlertID != "" { + + if err := r.SetQueryParam("alertId", qAlertID); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/describe_alert_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/describe_alert_responses.go new file mode 100644 index 0000000..9ff99b2 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/describe_alert_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeAlertReader is a Reader for the DescribeAlert structure. +type DescribeAlertReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeAlertReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeAlertOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeAlertDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeAlertOK creates a DescribeAlertOK with default headers values +func NewDescribeAlertOK() *DescribeAlertOK { + return &DescribeAlertOK{} +} + +/* DescribeAlertOK describes a response with status code 200, with default header values. + +A DescribeAlertResult is an response struct that is used to describe get Alert. +*/ +type DescribeAlertOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAlertOKBody +} + +// IsSuccess returns true when this describe alert o k response has a 2xx status code +func (o *DescribeAlertOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe alert o k response has a 3xx status code +func (o *DescribeAlertOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe alert o k response has a 4xx status code +func (o *DescribeAlertOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe alert o k response has a 5xx status code +func (o *DescribeAlertOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe alert o k response a status code equal to that given +func (o *DescribeAlertOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeAlertOK) Error() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlert][%d] describeAlertOK %+v", 200, o.Payload) +} + +func (o *DescribeAlertOK) String() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlert][%d] describeAlertOK %+v", 200, o.Payload) +} + +func (o *DescribeAlertOK) GetPayload() *DescribeAlertOKBody { + return o.Payload +} + +func (o *DescribeAlertOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAlertOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeAlertDefault creates a DescribeAlertDefault with default headers values +func NewDescribeAlertDefault(code int) *DescribeAlertDefault { + return &DescribeAlertDefault{ + _statusCode: code, + } +} + +/* DescribeAlertDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeAlertDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAlertDefaultBody +} + +// Code gets the status code for the describe alert default response +func (o *DescribeAlertDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe alert default response has a 2xx status code +func (o *DescribeAlertDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe alert default response has a 3xx status code +func (o *DescribeAlertDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe alert default response has a 4xx status code +func (o *DescribeAlertDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe alert default response has a 5xx status code +func (o *DescribeAlertDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe alert default response a status code equal to that given +func (o *DescribeAlertDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeAlertDefault) Error() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlert][%d] describeAlert default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAlertDefault) String() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlert][%d] describeAlert default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAlertDefault) GetPayload() *DescribeAlertDefaultBody { + return o.Payload +} + +func (o *DescribeAlertDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAlertDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeAlertDefaultBody describe alert default body +swagger:model DescribeAlertDefaultBody +*/ +type DescribeAlertDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe alert default body +func (o *DescribeAlertDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeAlert default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeAlertDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeAlert default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlert default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlert default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe alert default body based on the context it is used +func (o *DescribeAlertDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlert default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlert default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAlertDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAlertDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeAlertDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeAlertOKBody describe alert o k body +swagger:model DescribeAlertOKBody +*/ +type DescribeAlertOKBody struct { + + // result + Result *models.Alert `json:"result,omitempty"` +} + +// Validate validates this describe alert o k body +func (o *DescribeAlertOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlertOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlertOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe alert o k body based on the context it is used +func (o *DescribeAlertOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlertOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlertOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAlertOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAlertOKBody) UnmarshalBinary(b []byte) error { + var res DescribeAlertOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/describe_alerts_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/describe_alerts_parameters.go new file mode 100644 index 0000000..8a6ffbc --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/describe_alerts_parameters.go @@ -0,0 +1,604 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeAlertsParams creates a new DescribeAlertsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeAlertsParams() *DescribeAlertsParams { + return &DescribeAlertsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeAlertsParamsWithTimeout creates a new DescribeAlertsParams object +// with the ability to set a timeout on a request. +func NewDescribeAlertsParamsWithTimeout(timeout time.Duration) *DescribeAlertsParams { + return &DescribeAlertsParams{ + timeout: timeout, + } +} + +// NewDescribeAlertsParamsWithContext creates a new DescribeAlertsParams object +// with the ability to set a context for a request. +func NewDescribeAlertsParamsWithContext(ctx context.Context) *DescribeAlertsParams { + return &DescribeAlertsParams{ + Context: ctx, + } +} + +// NewDescribeAlertsParamsWithHTTPClient creates a new DescribeAlertsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeAlertsParamsWithHTTPClient(client *http.Client) *DescribeAlertsParams { + return &DescribeAlertsParams{ + HTTPClient: client, + } +} + +/* DescribeAlertsParams contains all the parameters to send to the API endpoint + for the describe alerts operation. + + Typically these are written to a http.Request. +*/ +type DescribeAlertsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* EndTime. + + 报警时间筛选etime + + Format: int64 + */ + EndTime *int64 + + /* IsAll. + + 是否显示全部,取值为1时表示全部 + */ + IsAll *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* ProjectID. + + project uuid + */ + ProjectID *string + + /* ResourceID. + + 资源id,目前就是实例id + */ + ResourceID *string + + /* RuleID. + + 规则uuid + */ + RuleID *string + + /* RuleName. + + 规则名称 + */ + RuleName *string + + /* StartTime. + + 报警时间筛选stime + + Format: int64 + */ + StartTime *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserID. + + user uuid + */ + UserID *string + + /* UserName. + + username + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe alerts params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAlertsParams) WithDefaults() *DescribeAlertsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe alerts params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAlertsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe alerts params +func (o *DescribeAlertsParams) WithTimeout(timeout time.Duration) *DescribeAlertsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe alerts params +func (o *DescribeAlertsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe alerts params +func (o *DescribeAlertsParams) WithContext(ctx context.Context) *DescribeAlertsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe alerts params +func (o *DescribeAlertsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe alerts params +func (o *DescribeAlertsParams) WithHTTPClient(client *http.Client) *DescribeAlertsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe alerts params +func (o *DescribeAlertsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe alerts params +func (o *DescribeAlertsParams) WithAuthorization(authorization string) *DescribeAlertsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe alerts params +func (o *DescribeAlertsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe alerts params +func (o *DescribeAlertsParams) WithBmpLanguage(bmpLanguage *string) *DescribeAlertsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe alerts params +func (o *DescribeAlertsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe alerts params +func (o *DescribeAlertsParams) WithBmpUserID(bmpUserID *string) *DescribeAlertsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe alerts params +func (o *DescribeAlertsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithEndTime adds the endTime to the describe alerts params +func (o *DescribeAlertsParams) WithEndTime(endTime *int64) *DescribeAlertsParams { + o.SetEndTime(endTime) + return o +} + +// SetEndTime adds the endTime to the describe alerts params +func (o *DescribeAlertsParams) SetEndTime(endTime *int64) { + o.EndTime = endTime +} + +// WithIsAll adds the isAll to the describe alerts params +func (o *DescribeAlertsParams) WithIsAll(isAll *string) *DescribeAlertsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe alerts params +func (o *DescribeAlertsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithPageNumber adds the pageNumber to the describe alerts params +func (o *DescribeAlertsParams) WithPageNumber(pageNumber *int64) *DescribeAlertsParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe alerts params +func (o *DescribeAlertsParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe alerts params +func (o *DescribeAlertsParams) WithPageSize(pageSize *int64) *DescribeAlertsParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe alerts params +func (o *DescribeAlertsParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithProjectID adds the projectID to the describe alerts params +func (o *DescribeAlertsParams) WithProjectID(projectID *string) *DescribeAlertsParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the describe alerts params +func (o *DescribeAlertsParams) SetProjectID(projectID *string) { + o.ProjectID = projectID +} + +// WithResourceID adds the resourceID to the describe alerts params +func (o *DescribeAlertsParams) WithResourceID(resourceID *string) *DescribeAlertsParams { + o.SetResourceID(resourceID) + return o +} + +// SetResourceID adds the resourceId to the describe alerts params +func (o *DescribeAlertsParams) SetResourceID(resourceID *string) { + o.ResourceID = resourceID +} + +// WithRuleID adds the ruleID to the describe alerts params +func (o *DescribeAlertsParams) WithRuleID(ruleID *string) *DescribeAlertsParams { + o.SetRuleID(ruleID) + return o +} + +// SetRuleID adds the ruleId to the describe alerts params +func (o *DescribeAlertsParams) SetRuleID(ruleID *string) { + o.RuleID = ruleID +} + +// WithRuleName adds the ruleName to the describe alerts params +func (o *DescribeAlertsParams) WithRuleName(ruleName *string) *DescribeAlertsParams { + o.SetRuleName(ruleName) + return o +} + +// SetRuleName adds the ruleName to the describe alerts params +func (o *DescribeAlertsParams) SetRuleName(ruleName *string) { + o.RuleName = ruleName +} + +// WithStartTime adds the startTime to the describe alerts params +func (o *DescribeAlertsParams) WithStartTime(startTime *int64) *DescribeAlertsParams { + o.SetStartTime(startTime) + return o +} + +// SetStartTime adds the startTime to the describe alerts params +func (o *DescribeAlertsParams) SetStartTime(startTime *int64) { + o.StartTime = startTime +} + +// WithTraceID adds the traceID to the describe alerts params +func (o *DescribeAlertsParams) WithTraceID(traceID string) *DescribeAlertsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe alerts params +func (o *DescribeAlertsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserID adds the userID to the describe alerts params +func (o *DescribeAlertsParams) WithUserID(userID *string) *DescribeAlertsParams { + o.SetUserID(userID) + return o +} + +// SetUserID adds the userId to the describe alerts params +func (o *DescribeAlertsParams) SetUserID(userID *string) { + o.UserID = userID +} + +// WithUserName adds the userName to the describe alerts params +func (o *DescribeAlertsParams) WithUserName(userName *string) *DescribeAlertsParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe alerts params +func (o *DescribeAlertsParams) SetUserName(userName *string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeAlertsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.EndTime != nil { + + // query param endTime + var qrEndTime int64 + + if o.EndTime != nil { + qrEndTime = *o.EndTime + } + qEndTime := swag.FormatInt64(qrEndTime) + if qEndTime != "" { + + if err := r.SetQueryParam("endTime", qEndTime); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.ProjectID != nil { + + // query param projectId + var qrProjectID string + + if o.ProjectID != nil { + qrProjectID = *o.ProjectID + } + qProjectID := qrProjectID + if qProjectID != "" { + + if err := r.SetQueryParam("projectId", qProjectID); err != nil { + return err + } + } + } + + if o.ResourceID != nil { + + // query param resourceId + var qrResourceID string + + if o.ResourceID != nil { + qrResourceID = *o.ResourceID + } + qResourceID := qrResourceID + if qResourceID != "" { + + if err := r.SetQueryParam("resourceId", qResourceID); err != nil { + return err + } + } + } + + if o.RuleID != nil { + + // query param ruleId + var qrRuleID string + + if o.RuleID != nil { + qrRuleID = *o.RuleID + } + qRuleID := qrRuleID + if qRuleID != "" { + + if err := r.SetQueryParam("ruleId", qRuleID); err != nil { + return err + } + } + } + + if o.RuleName != nil { + + // query param ruleName + var qrRuleName string + + if o.RuleName != nil { + qrRuleName = *o.RuleName + } + qRuleName := qrRuleName + if qRuleName != "" { + + if err := r.SetQueryParam("ruleName", qRuleName); err != nil { + return err + } + } + } + + if o.StartTime != nil { + + // query param startTime + var qrStartTime int64 + + if o.StartTime != nil { + qrStartTime = *o.StartTime + } + qStartTime := swag.FormatInt64(qrStartTime) + if qStartTime != "" { + + if err := r.SetQueryParam("startTime", qStartTime); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserID != nil { + + // query param userId + var qrUserID string + + if o.UserID != nil { + qrUserID = *o.UserID + } + qUserID := qrUserID + if qUserID != "" { + + if err := r.SetQueryParam("userId", qUserID); err != nil { + return err + } + } + } + + if o.UserName != nil { + + // query param userName + var qrUserName string + + if o.UserName != nil { + qrUserName = *o.UserName + } + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/describe_alerts_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/describe_alerts_responses.go new file mode 100644 index 0000000..f3c2ebb --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/describe_alerts_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeAlertsReader is a Reader for the DescribeAlerts structure. +type DescribeAlertsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeAlertsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeAlertsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeAlertsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeAlertsOK creates a DescribeAlertsOK with default headers values +func NewDescribeAlertsOK() *DescribeAlertsOK { + return &DescribeAlertsOK{} +} + +/* DescribeAlertsOK describes a response with status code 200, with default header values. + +A DescribeAlertsResult is an response struct that is used to describe get Alert. +*/ +type DescribeAlertsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAlertsOKBody +} + +// IsSuccess returns true when this describe alerts o k response has a 2xx status code +func (o *DescribeAlertsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe alerts o k response has a 3xx status code +func (o *DescribeAlertsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe alerts o k response has a 4xx status code +func (o *DescribeAlertsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe alerts o k response has a 5xx status code +func (o *DescribeAlertsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe alerts o k response a status code equal to that given +func (o *DescribeAlertsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeAlertsOK) Error() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlerts][%d] describeAlertsOK %+v", 200, o.Payload) +} + +func (o *DescribeAlertsOK) String() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlerts][%d] describeAlertsOK %+v", 200, o.Payload) +} + +func (o *DescribeAlertsOK) GetPayload() *DescribeAlertsOKBody { + return o.Payload +} + +func (o *DescribeAlertsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAlertsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeAlertsDefault creates a DescribeAlertsDefault with default headers values +func NewDescribeAlertsDefault(code int) *DescribeAlertsDefault { + return &DescribeAlertsDefault{ + _statusCode: code, + } +} + +/* DescribeAlertsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeAlertsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAlertsDefaultBody +} + +// Code gets the status code for the describe alerts default response +func (o *DescribeAlertsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe alerts default response has a 2xx status code +func (o *DescribeAlertsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe alerts default response has a 3xx status code +func (o *DescribeAlertsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe alerts default response has a 4xx status code +func (o *DescribeAlertsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe alerts default response has a 5xx status code +func (o *DescribeAlertsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe alerts default response a status code equal to that given +func (o *DescribeAlertsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeAlertsDefault) Error() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlerts][%d] describeAlerts default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAlertsDefault) String() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlerts][%d] describeAlerts default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAlertsDefault) GetPayload() *DescribeAlertsDefaultBody { + return o.Payload +} + +func (o *DescribeAlertsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAlertsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeAlertsDefaultBody describe alerts default body +swagger:model DescribeAlertsDefaultBody +*/ +type DescribeAlertsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe alerts default body +func (o *DescribeAlertsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeAlerts default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeAlertsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeAlerts default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlerts default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlerts default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe alerts default body based on the context it is used +func (o *DescribeAlertsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlerts default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlerts default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAlertsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAlertsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeAlertsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeAlertsOKBody describe alerts o k body +swagger:model DescribeAlertsOKBody +*/ +type DescribeAlertsOKBody struct { + + // result + Result *models.AlertList `json:"result,omitempty"` +} + +// Validate validates this describe alerts o k body +func (o *DescribeAlertsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlertsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlertsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe alerts o k body based on the context it is used +func (o *DescribeAlertsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlertsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlertsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAlertsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAlertsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeAlertsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/monitor_alert_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/monitor_alert_client.go new file mode 100644 index 0000000..d1348a1 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_alert/monitor_alert_client.go @@ -0,0 +1,197 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new monitor alert API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for monitor alert API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + AddAlert(params *AddAlertParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AddAlertOK, error) + + DeleteAlert(params *DeleteAlertParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteAlertOK, error) + + DescribeAlert(params *DescribeAlertParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAlertOK, error) + + DescribeAlerts(params *DescribeAlertsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAlertsOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + AddAlert AddAlert 添加(接收)告警 +*/ +func (a *Client) AddAlert(params *AddAlertParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AddAlertOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewAddAlertParams() + } + op := &runtime.ClientOperation{ + ID: "addAlert", + Method: "POST", + PathPattern: "/monitorAlert/addAlert", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &AddAlertReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*AddAlertOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*AddAlertDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteAlert DeleteAlert 删除告警 +*/ +func (a *Client) DeleteAlert(params *DeleteAlertParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteAlertOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteAlertParams() + } + op := &runtime.ClientOperation{ + ID: "deleteAlert", + Method: "DELETE", + PathPattern: "/monitorAlert/deleteAlert", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteAlertReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteAlertOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteAlertDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeAlert DescribeAlert 告警详情 +*/ +func (a *Client) DescribeAlert(params *DescribeAlertParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAlertOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeAlertParams() + } + op := &runtime.ClientOperation{ + ID: "describeAlert", + Method: "GET", + PathPattern: "/monitorAlert/describeAlert", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeAlertReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeAlertOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeAlertDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeAlerts DescribeAlerts 告警列表 +*/ +func (a *Client) DescribeAlerts(params *DescribeAlertsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAlertsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeAlertsParams() + } + op := &runtime.ClientOperation{ + ID: "describeAlerts", + Method: "GET", + PathPattern: "/monitorAlert/describeAlerts", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeAlertsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeAlertsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeAlertsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_data/get_monitor_data_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_data/get_monitor_data_parameters.go new file mode 100644 index 0000000..8965de8 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_data/get_monitor_data_parameters.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_data + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetMonitorDataParams creates a new GetMonitorDataParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetMonitorDataParams() *GetMonitorDataParams { + return &GetMonitorDataParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetMonitorDataParamsWithTimeout creates a new GetMonitorDataParams object +// with the ability to set a timeout on a request. +func NewGetMonitorDataParamsWithTimeout(timeout time.Duration) *GetMonitorDataParams { + return &GetMonitorDataParams{ + timeout: timeout, + } +} + +// NewGetMonitorDataParamsWithContext creates a new GetMonitorDataParams object +// with the ability to set a context for a request. +func NewGetMonitorDataParamsWithContext(ctx context.Context) *GetMonitorDataParams { + return &GetMonitorDataParams{ + Context: ctx, + } +} + +// NewGetMonitorDataParamsWithHTTPClient creates a new GetMonitorDataParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetMonitorDataParamsWithHTTPClient(client *http.Client) *GetMonitorDataParams { + return &GetMonitorDataParams{ + HTTPClient: client, + } +} + +/* GetMonitorDataParams contains all the parameters to send to the API endpoint + for the get monitor data operation. + + Typically these are written to a http.Request. +*/ +type GetMonitorDataParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* Device. + + 标签值 + */ + Device *string + + /* DownSampleType. + + avg, min, max, sum + */ + DownSampleType *string + + /* EndTime. + + 结束时间戳 + + Format: int64 + */ + EndTime *int64 + + /* InstanceID. + + 实例id + */ + InstanceID *string + + /* LastManyTime. + + 最近多少时间,小时为单位 + + Format: int64 + */ + LastManyTime *int64 + + /* MetricName. + + 指标名称,支持多个,用逗号隔离开 + */ + MetricName *string + + /* StartTime. + + 开始时间戳 + + Format: int64 + */ + StartTime *int64 + + /* TimeInterval. + + 间隔多久一个点 s为单位 + + Format: int64 + */ + TimeInterval *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get monitor data params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMonitorDataParams) WithDefaults() *GetMonitorDataParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get monitor data params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMonitorDataParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get monitor data params +func (o *GetMonitorDataParams) WithTimeout(timeout time.Duration) *GetMonitorDataParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get monitor data params +func (o *GetMonitorDataParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get monitor data params +func (o *GetMonitorDataParams) WithContext(ctx context.Context) *GetMonitorDataParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get monitor data params +func (o *GetMonitorDataParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get monitor data params +func (o *GetMonitorDataParams) WithHTTPClient(client *http.Client) *GetMonitorDataParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get monitor data params +func (o *GetMonitorDataParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the get monitor data params +func (o *GetMonitorDataParams) WithAuthorization(authorization string) *GetMonitorDataParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the get monitor data params +func (o *GetMonitorDataParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the get monitor data params +func (o *GetMonitorDataParams) WithBmpLanguage(bmpLanguage *string) *GetMonitorDataParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the get monitor data params +func (o *GetMonitorDataParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the get monitor data params +func (o *GetMonitorDataParams) WithBmpUserID(bmpUserID *string) *GetMonitorDataParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the get monitor data params +func (o *GetMonitorDataParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDevice adds the device to the get monitor data params +func (o *GetMonitorDataParams) WithDevice(device *string) *GetMonitorDataParams { + o.SetDevice(device) + return o +} + +// SetDevice adds the device to the get monitor data params +func (o *GetMonitorDataParams) SetDevice(device *string) { + o.Device = device +} + +// WithDownSampleType adds the downSampleType to the get monitor data params +func (o *GetMonitorDataParams) WithDownSampleType(downSampleType *string) *GetMonitorDataParams { + o.SetDownSampleType(downSampleType) + return o +} + +// SetDownSampleType adds the downSampleType to the get monitor data params +func (o *GetMonitorDataParams) SetDownSampleType(downSampleType *string) { + o.DownSampleType = downSampleType +} + +// WithEndTime adds the endTime to the get monitor data params +func (o *GetMonitorDataParams) WithEndTime(endTime *int64) *GetMonitorDataParams { + o.SetEndTime(endTime) + return o +} + +// SetEndTime adds the endTime to the get monitor data params +func (o *GetMonitorDataParams) SetEndTime(endTime *int64) { + o.EndTime = endTime +} + +// WithInstanceID adds the instanceID to the get monitor data params +func (o *GetMonitorDataParams) WithInstanceID(instanceID *string) *GetMonitorDataParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the get monitor data params +func (o *GetMonitorDataParams) SetInstanceID(instanceID *string) { + o.InstanceID = instanceID +} + +// WithLastManyTime adds the lastManyTime to the get monitor data params +func (o *GetMonitorDataParams) WithLastManyTime(lastManyTime *int64) *GetMonitorDataParams { + o.SetLastManyTime(lastManyTime) + return o +} + +// SetLastManyTime adds the lastManyTime to the get monitor data params +func (o *GetMonitorDataParams) SetLastManyTime(lastManyTime *int64) { + o.LastManyTime = lastManyTime +} + +// WithMetricName adds the metricName to the get monitor data params +func (o *GetMonitorDataParams) WithMetricName(metricName *string) *GetMonitorDataParams { + o.SetMetricName(metricName) + return o +} + +// SetMetricName adds the metricName to the get monitor data params +func (o *GetMonitorDataParams) SetMetricName(metricName *string) { + o.MetricName = metricName +} + +// WithStartTime adds the startTime to the get monitor data params +func (o *GetMonitorDataParams) WithStartTime(startTime *int64) *GetMonitorDataParams { + o.SetStartTime(startTime) + return o +} + +// SetStartTime adds the startTime to the get monitor data params +func (o *GetMonitorDataParams) SetStartTime(startTime *int64) { + o.StartTime = startTime +} + +// WithTimeInterval adds the timeInterval to the get monitor data params +func (o *GetMonitorDataParams) WithTimeInterval(timeInterval *int64) *GetMonitorDataParams { + o.SetTimeInterval(timeInterval) + return o +} + +// SetTimeInterval adds the timeInterval to the get monitor data params +func (o *GetMonitorDataParams) SetTimeInterval(timeInterval *int64) { + o.TimeInterval = timeInterval +} + +// WithTraceID adds the traceID to the get monitor data params +func (o *GetMonitorDataParams) WithTraceID(traceID string) *GetMonitorDataParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the get monitor data params +func (o *GetMonitorDataParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetMonitorDataParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.Device != nil { + + // query param device + var qrDevice string + + if o.Device != nil { + qrDevice = *o.Device + } + qDevice := qrDevice + if qDevice != "" { + + if err := r.SetQueryParam("device", qDevice); err != nil { + return err + } + } + } + + if o.DownSampleType != nil { + + // query param downSampleType + var qrDownSampleType string + + if o.DownSampleType != nil { + qrDownSampleType = *o.DownSampleType + } + qDownSampleType := qrDownSampleType + if qDownSampleType != "" { + + if err := r.SetQueryParam("downSampleType", qDownSampleType); err != nil { + return err + } + } + } + + if o.EndTime != nil { + + // query param endTime + var qrEndTime int64 + + if o.EndTime != nil { + qrEndTime = *o.EndTime + } + qEndTime := swag.FormatInt64(qrEndTime) + if qEndTime != "" { + + if err := r.SetQueryParam("endTime", qEndTime); err != nil { + return err + } + } + } + + if o.InstanceID != nil { + + // query param instanceId + var qrInstanceID string + + if o.InstanceID != nil { + qrInstanceID = *o.InstanceID + } + qInstanceID := qrInstanceID + if qInstanceID != "" { + + if err := r.SetQueryParam("instanceId", qInstanceID); err != nil { + return err + } + } + } + + if o.LastManyTime != nil { + + // query param lastManyTime + var qrLastManyTime int64 + + if o.LastManyTime != nil { + qrLastManyTime = *o.LastManyTime + } + qLastManyTime := swag.FormatInt64(qrLastManyTime) + if qLastManyTime != "" { + + if err := r.SetQueryParam("lastManyTime", qLastManyTime); err != nil { + return err + } + } + } + + if o.MetricName != nil { + + // query param metricName + var qrMetricName string + + if o.MetricName != nil { + qrMetricName = *o.MetricName + } + qMetricName := qrMetricName + if qMetricName != "" { + + if err := r.SetQueryParam("metricName", qMetricName); err != nil { + return err + } + } + } + + if o.StartTime != nil { + + // query param startTime + var qrStartTime int64 + + if o.StartTime != nil { + qrStartTime = *o.StartTime + } + qStartTime := swag.FormatInt64(qrStartTime) + if qStartTime != "" { + + if err := r.SetQueryParam("startTime", qStartTime); err != nil { + return err + } + } + } + + if o.TimeInterval != nil { + + // query param timeInterval + var qrTimeInterval int64 + + if o.TimeInterval != nil { + qrTimeInterval = *o.TimeInterval + } + qTimeInterval := swag.FormatInt64(qrTimeInterval) + if qTimeInterval != "" { + + if err := r.SetQueryParam("timeInterval", qTimeInterval); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_data/get_monitor_data_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_data/get_monitor_data_responses.go new file mode 100644 index 0000000..6d47c22 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_data/get_monitor_data_responses.go @@ -0,0 +1,415 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_data + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// GetMonitorDataReader is a Reader for the GetMonitorData structure. +type GetMonitorDataReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetMonitorDataReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetMonitorDataOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetMonitorDataDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetMonitorDataOK creates a GetMonitorDataOK with default headers values +func NewGetMonitorDataOK() *GetMonitorDataOK { + return &GetMonitorDataOK{} +} + +/* GetMonitorDataOK describes a response with status code 200, with default header values. + +GetMonitorDataOK get monitor data o k +*/ +type GetMonitorDataOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMonitorDataOKBody +} + +// IsSuccess returns true when this get monitor data o k response has a 2xx status code +func (o *GetMonitorDataOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get monitor data o k response has a 3xx status code +func (o *GetMonitorDataOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get monitor data o k response has a 4xx status code +func (o *GetMonitorDataOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get monitor data o k response has a 5xx status code +func (o *GetMonitorDataOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get monitor data o k response a status code equal to that given +func (o *GetMonitorDataOK) IsCode(code int) bool { + return code == 200 +} + +func (o *GetMonitorDataOK) Error() string { + return fmt.Sprintf("[GET /monitorData][%d] getMonitorDataOK %+v", 200, o.Payload) +} + +func (o *GetMonitorDataOK) String() string { + return fmt.Sprintf("[GET /monitorData][%d] getMonitorDataOK %+v", 200, o.Payload) +} + +func (o *GetMonitorDataOK) GetPayload() *GetMonitorDataOKBody { + return o.Payload +} + +func (o *GetMonitorDataOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMonitorDataOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetMonitorDataDefault creates a GetMonitorDataDefault with default headers values +func NewGetMonitorDataDefault(code int) *GetMonitorDataDefault { + return &GetMonitorDataDefault{ + _statusCode: code, + } +} + +/* GetMonitorDataDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type GetMonitorDataDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMonitorDataDefaultBody +} + +// Code gets the status code for the get monitor data default response +func (o *GetMonitorDataDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this get monitor data default response has a 2xx status code +func (o *GetMonitorDataDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get monitor data default response has a 3xx status code +func (o *GetMonitorDataDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get monitor data default response has a 4xx status code +func (o *GetMonitorDataDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get monitor data default response has a 5xx status code +func (o *GetMonitorDataDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get monitor data default response a status code equal to that given +func (o *GetMonitorDataDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *GetMonitorDataDefault) Error() string { + return fmt.Sprintf("[GET /monitorData][%d] getMonitorData default %+v", o._statusCode, o.Payload) +} + +func (o *GetMonitorDataDefault) String() string { + return fmt.Sprintf("[GET /monitorData][%d] getMonitorData default %+v", o._statusCode, o.Payload) +} + +func (o *GetMonitorDataDefault) GetPayload() *GetMonitorDataDefaultBody { + return o.Payload +} + +func (o *GetMonitorDataDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMonitorDataDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*GetMonitorDataDefaultBody get monitor data default body +swagger:model GetMonitorDataDefaultBody +*/ +type GetMonitorDataDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this get monitor data default body +func (o *GetMonitorDataDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMonitorDataDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("getMonitorData default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *GetMonitorDataDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("getMonitorData default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMonitorData default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMonitorData default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get monitor data default body based on the context it is used +func (o *GetMonitorDataDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMonitorDataDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMonitorData default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMonitorData default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMonitorDataDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMonitorDataDefaultBody) UnmarshalBinary(b []byte) error { + var res GetMonitorDataDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*GetMonitorDataOKBody get monitor data o k body +swagger:model GetMonitorDataOKBody +*/ +type GetMonitorDataOKBody struct { + + // result + Result []*models.DataEveryMetric `json:"result"` +} + +// Validate validates this get monitor data o k body +func (o *GetMonitorDataOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMonitorDataOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + for i := 0; i < len(o.Result); i++ { + if swag.IsZero(o.Result[i]) { // not required + continue + } + + if o.Result[i] != nil { + if err := o.Result[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMonitorDataOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMonitorDataOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get monitor data o k body based on the context it is used +func (o *GetMonitorDataOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMonitorDataOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Result); i++ { + + if o.Result[i] != nil { + if err := o.Result[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMonitorDataOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMonitorDataOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMonitorDataOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMonitorDataOKBody) UnmarshalBinary(b []byte) error { + var res GetMonitorDataOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_data/monitor_data_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_data/monitor_data_client.go new file mode 100644 index 0000000..6925f61 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_data/monitor_data_client.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_data + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new monitor data API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for monitor data API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + GetMonitorData(params *GetMonitorDataParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMonitorDataOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + GetMonitorData GetMonitorData 获取图表监控数据 +*/ +func (a *Client) GetMonitorData(params *GetMonitorDataParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMonitorDataOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetMonitorDataParams() + } + op := &runtime.ClientOperation{ + ID: "getMonitorData", + Method: "GET", + PathPattern: "/monitorData", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetMonitorDataReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetMonitorDataOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetMonitorDataDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_proxy/desrcibe_agent_status_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_proxy/desrcibe_agent_status_parameters.go new file mode 100644 index 0000000..45c1e12 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_proxy/desrcibe_agent_status_parameters.go @@ -0,0 +1,248 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_proxy + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDesrcibeAgentStatusParams creates a new DesrcibeAgentStatusParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDesrcibeAgentStatusParams() *DesrcibeAgentStatusParams { + return &DesrcibeAgentStatusParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDesrcibeAgentStatusParamsWithTimeout creates a new DesrcibeAgentStatusParams object +// with the ability to set a timeout on a request. +func NewDesrcibeAgentStatusParamsWithTimeout(timeout time.Duration) *DesrcibeAgentStatusParams { + return &DesrcibeAgentStatusParams{ + timeout: timeout, + } +} + +// NewDesrcibeAgentStatusParamsWithContext creates a new DesrcibeAgentStatusParams object +// with the ability to set a context for a request. +func NewDesrcibeAgentStatusParamsWithContext(ctx context.Context) *DesrcibeAgentStatusParams { + return &DesrcibeAgentStatusParams{ + Context: ctx, + } +} + +// NewDesrcibeAgentStatusParamsWithHTTPClient creates a new DesrcibeAgentStatusParams object +// with the ability to set a custom HTTPClient for a request. +func NewDesrcibeAgentStatusParamsWithHTTPClient(client *http.Client) *DesrcibeAgentStatusParams { + return &DesrcibeAgentStatusParams{ + HTTPClient: client, + } +} + +/* DesrcibeAgentStatusParams contains all the parameters to send to the API endpoint + for the desrcibe agent status operation. + + Typically these are written to a http.Request. +*/ +type DesrcibeAgentStatusParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* InstanceID. + + InstanceId,多个用逗号分隔 + */ + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the desrcibe agent status params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DesrcibeAgentStatusParams) WithDefaults() *DesrcibeAgentStatusParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the desrcibe agent status params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DesrcibeAgentStatusParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithTimeout(timeout time.Duration) *DesrcibeAgentStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithContext(ctx context.Context) *DesrcibeAgentStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithHTTPClient(client *http.Client) *DesrcibeAgentStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithAuthorization(authorization string) *DesrcibeAgentStatusParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithBmpLanguage(bmpLanguage *string) *DesrcibeAgentStatusParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithBmpUserID(bmpUserID *string) *DesrcibeAgentStatusParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithInstanceID(instanceID string) *DesrcibeAgentStatusParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithTraceID(traceID string) *DesrcibeAgentStatusParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DesrcibeAgentStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // query param instanceId + qrInstanceID := o.InstanceID + qInstanceID := qrInstanceID + if qInstanceID != "" { + + if err := r.SetQueryParam("instanceId", qInstanceID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_proxy/desrcibe_agent_status_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_proxy/desrcibe_agent_status_responses.go new file mode 100644 index 0000000..9dcb5da --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_proxy/desrcibe_agent_status_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_proxy + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DesrcibeAgentStatusReader is a Reader for the DesrcibeAgentStatus structure. +type DesrcibeAgentStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DesrcibeAgentStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDesrcibeAgentStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDesrcibeAgentStatusDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDesrcibeAgentStatusOK creates a DesrcibeAgentStatusOK with default headers values +func NewDesrcibeAgentStatusOK() *DesrcibeAgentStatusOK { + return &DesrcibeAgentStatusOK{} +} + +/* DesrcibeAgentStatusOK describes a response with status code 200, with default header values. + +DesrcibeAgentStatusOK desrcibe agent status o k +*/ +type DesrcibeAgentStatusOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DesrcibeAgentStatusOKBody +} + +// IsSuccess returns true when this desrcibe agent status o k response has a 2xx status code +func (o *DesrcibeAgentStatusOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this desrcibe agent status o k response has a 3xx status code +func (o *DesrcibeAgentStatusOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this desrcibe agent status o k response has a 4xx status code +func (o *DesrcibeAgentStatusOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this desrcibe agent status o k response has a 5xx status code +func (o *DesrcibeAgentStatusOK) IsServerError() bool { + return false +} + +// IsCode returns true when this desrcibe agent status o k response a status code equal to that given +func (o *DesrcibeAgentStatusOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DesrcibeAgentStatusOK) Error() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeAgentStatus][%d] desrcibeAgentStatusOK %+v", 200, o.Payload) +} + +func (o *DesrcibeAgentStatusOK) String() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeAgentStatus][%d] desrcibeAgentStatusOK %+v", 200, o.Payload) +} + +func (o *DesrcibeAgentStatusOK) GetPayload() *DesrcibeAgentStatusOKBody { + return o.Payload +} + +func (o *DesrcibeAgentStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DesrcibeAgentStatusOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDesrcibeAgentStatusDefault creates a DesrcibeAgentStatusDefault with default headers values +func NewDesrcibeAgentStatusDefault(code int) *DesrcibeAgentStatusDefault { + return &DesrcibeAgentStatusDefault{ + _statusCode: code, + } +} + +/* DesrcibeAgentStatusDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DesrcibeAgentStatusDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DesrcibeAgentStatusDefaultBody +} + +// Code gets the status code for the desrcibe agent status default response +func (o *DesrcibeAgentStatusDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this desrcibe agent status default response has a 2xx status code +func (o *DesrcibeAgentStatusDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this desrcibe agent status default response has a 3xx status code +func (o *DesrcibeAgentStatusDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this desrcibe agent status default response has a 4xx status code +func (o *DesrcibeAgentStatusDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this desrcibe agent status default response has a 5xx status code +func (o *DesrcibeAgentStatusDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this desrcibe agent status default response a status code equal to that given +func (o *DesrcibeAgentStatusDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DesrcibeAgentStatusDefault) Error() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeAgentStatus][%d] desrcibeAgentStatus default %+v", o._statusCode, o.Payload) +} + +func (o *DesrcibeAgentStatusDefault) String() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeAgentStatus][%d] desrcibeAgentStatus default %+v", o._statusCode, o.Payload) +} + +func (o *DesrcibeAgentStatusDefault) GetPayload() *DesrcibeAgentStatusDefaultBody { + return o.Payload +} + +func (o *DesrcibeAgentStatusDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DesrcibeAgentStatusDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DesrcibeAgentStatusDefaultBody desrcibe agent status default body +swagger:model DesrcibeAgentStatusDefaultBody +*/ +type DesrcibeAgentStatusDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this desrcibe agent status default body +func (o *DesrcibeAgentStatusDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeAgentStatusDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("desrcibeAgentStatus default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DesrcibeAgentStatusDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("desrcibeAgentStatus default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeAgentStatus default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeAgentStatus default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this desrcibe agent status default body based on the context it is used +func (o *DesrcibeAgentStatusDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeAgentStatusDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeAgentStatus default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeAgentStatus default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DesrcibeAgentStatusDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DesrcibeAgentStatusDefaultBody) UnmarshalBinary(b []byte) error { + var res DesrcibeAgentStatusDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DesrcibeAgentStatusOKBody desrcibe agent status o k body +swagger:model DesrcibeAgentStatusOKBody +*/ +type DesrcibeAgentStatusOKBody struct { + + // result + Result *models.AgentStatusResponse `json:"result,omitempty"` +} + +// Validate validates this desrcibe agent status o k body +func (o *DesrcibeAgentStatusOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeAgentStatusOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeAgentStatusOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeAgentStatusOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this desrcibe agent status o k body based on the context it is used +func (o *DesrcibeAgentStatusOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeAgentStatusOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeAgentStatusOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeAgentStatusOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DesrcibeAgentStatusOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DesrcibeAgentStatusOKBody) UnmarshalBinary(b []byte) error { + var res DesrcibeAgentStatusOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_proxy/desrcibe_tags_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_proxy/desrcibe_tags_parameters.go new file mode 100644 index 0000000..e270152 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_proxy/desrcibe_tags_parameters.go @@ -0,0 +1,275 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_proxy + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDesrcibeTagsParams creates a new DesrcibeTagsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDesrcibeTagsParams() *DesrcibeTagsParams { + return &DesrcibeTagsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDesrcibeTagsParamsWithTimeout creates a new DesrcibeTagsParams object +// with the ability to set a timeout on a request. +func NewDesrcibeTagsParamsWithTimeout(timeout time.Duration) *DesrcibeTagsParams { + return &DesrcibeTagsParams{ + timeout: timeout, + } +} + +// NewDesrcibeTagsParamsWithContext creates a new DesrcibeTagsParams object +// with the ability to set a context for a request. +func NewDesrcibeTagsParamsWithContext(ctx context.Context) *DesrcibeTagsParams { + return &DesrcibeTagsParams{ + Context: ctx, + } +} + +// NewDesrcibeTagsParamsWithHTTPClient creates a new DesrcibeTagsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDesrcibeTagsParamsWithHTTPClient(client *http.Client) *DesrcibeTagsParams { + return &DesrcibeTagsParams{ + HTTPClient: client, + } +} + +/* DesrcibeTagsParams contains all the parameters to send to the API endpoint + for the desrcibe tags operation. + + Typically these are written to a http.Request. +*/ +type DesrcibeTagsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* InstanceID. + + instanceId + */ + InstanceID string + + /* TagName. + + tagName [disk mountpoint nic] + */ + TagName string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the desrcibe tags params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DesrcibeTagsParams) WithDefaults() *DesrcibeTagsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the desrcibe tags params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DesrcibeTagsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the desrcibe tags params +func (o *DesrcibeTagsParams) WithTimeout(timeout time.Duration) *DesrcibeTagsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the desrcibe tags params +func (o *DesrcibeTagsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the desrcibe tags params +func (o *DesrcibeTagsParams) WithContext(ctx context.Context) *DesrcibeTagsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the desrcibe tags params +func (o *DesrcibeTagsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the desrcibe tags params +func (o *DesrcibeTagsParams) WithHTTPClient(client *http.Client) *DesrcibeTagsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the desrcibe tags params +func (o *DesrcibeTagsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the desrcibe tags params +func (o *DesrcibeTagsParams) WithAuthorization(authorization string) *DesrcibeTagsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the desrcibe tags params +func (o *DesrcibeTagsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the desrcibe tags params +func (o *DesrcibeTagsParams) WithBmpLanguage(bmpLanguage *string) *DesrcibeTagsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the desrcibe tags params +func (o *DesrcibeTagsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the desrcibe tags params +func (o *DesrcibeTagsParams) WithBmpUserID(bmpUserID *string) *DesrcibeTagsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the desrcibe tags params +func (o *DesrcibeTagsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the desrcibe tags params +func (o *DesrcibeTagsParams) WithInstanceID(instanceID string) *DesrcibeTagsParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the desrcibe tags params +func (o *DesrcibeTagsParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTagName adds the tagName to the desrcibe tags params +func (o *DesrcibeTagsParams) WithTagName(tagName string) *DesrcibeTagsParams { + o.SetTagName(tagName) + return o +} + +// SetTagName adds the tagName to the desrcibe tags params +func (o *DesrcibeTagsParams) SetTagName(tagName string) { + o.TagName = tagName +} + +// WithTraceID adds the traceID to the desrcibe tags params +func (o *DesrcibeTagsParams) WithTraceID(traceID string) *DesrcibeTagsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the desrcibe tags params +func (o *DesrcibeTagsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DesrcibeTagsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // query param instanceId + qrInstanceID := o.InstanceID + qInstanceID := qrInstanceID + if qInstanceID != "" { + + if err := r.SetQueryParam("instanceId", qInstanceID); err != nil { + return err + } + } + + // query param tagName + qrTagName := o.TagName + qTagName := qrTagName + if qTagName != "" { + + if err := r.SetQueryParam("tagName", qTagName); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_proxy/desrcibe_tags_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_proxy/desrcibe_tags_responses.go new file mode 100644 index 0000000..63fa365 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_proxy/desrcibe_tags_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_proxy + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DesrcibeTagsReader is a Reader for the DesrcibeTags structure. +type DesrcibeTagsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DesrcibeTagsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDesrcibeTagsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDesrcibeTagsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDesrcibeTagsOK creates a DesrcibeTagsOK with default headers values +func NewDesrcibeTagsOK() *DesrcibeTagsOK { + return &DesrcibeTagsOK{} +} + +/* DesrcibeTagsOK describes a response with status code 200, with default header values. + +DesrcibeTagsOK desrcibe tags o k +*/ +type DesrcibeTagsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DesrcibeTagsOKBody +} + +// IsSuccess returns true when this desrcibe tags o k response has a 2xx status code +func (o *DesrcibeTagsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this desrcibe tags o k response has a 3xx status code +func (o *DesrcibeTagsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this desrcibe tags o k response has a 4xx status code +func (o *DesrcibeTagsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this desrcibe tags o k response has a 5xx status code +func (o *DesrcibeTagsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this desrcibe tags o k response a status code equal to that given +func (o *DesrcibeTagsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DesrcibeTagsOK) Error() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeTags][%d] desrcibeTagsOK %+v", 200, o.Payload) +} + +func (o *DesrcibeTagsOK) String() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeTags][%d] desrcibeTagsOK %+v", 200, o.Payload) +} + +func (o *DesrcibeTagsOK) GetPayload() *DesrcibeTagsOKBody { + return o.Payload +} + +func (o *DesrcibeTagsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DesrcibeTagsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDesrcibeTagsDefault creates a DesrcibeTagsDefault with default headers values +func NewDesrcibeTagsDefault(code int) *DesrcibeTagsDefault { + return &DesrcibeTagsDefault{ + _statusCode: code, + } +} + +/* DesrcibeTagsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DesrcibeTagsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DesrcibeTagsDefaultBody +} + +// Code gets the status code for the desrcibe tags default response +func (o *DesrcibeTagsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this desrcibe tags default response has a 2xx status code +func (o *DesrcibeTagsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this desrcibe tags default response has a 3xx status code +func (o *DesrcibeTagsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this desrcibe tags default response has a 4xx status code +func (o *DesrcibeTagsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this desrcibe tags default response has a 5xx status code +func (o *DesrcibeTagsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this desrcibe tags default response a status code equal to that given +func (o *DesrcibeTagsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DesrcibeTagsDefault) Error() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeTags][%d] desrcibeTags default %+v", o._statusCode, o.Payload) +} + +func (o *DesrcibeTagsDefault) String() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeTags][%d] desrcibeTags default %+v", o._statusCode, o.Payload) +} + +func (o *DesrcibeTagsDefault) GetPayload() *DesrcibeTagsDefaultBody { + return o.Payload +} + +func (o *DesrcibeTagsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DesrcibeTagsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DesrcibeTagsDefaultBody desrcibe tags default body +swagger:model DesrcibeTagsDefaultBody +*/ +type DesrcibeTagsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this desrcibe tags default body +func (o *DesrcibeTagsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeTagsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("desrcibeTags default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DesrcibeTagsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("desrcibeTags default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeTags default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeTags default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this desrcibe tags default body based on the context it is used +func (o *DesrcibeTagsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeTagsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeTags default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeTags default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DesrcibeTagsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DesrcibeTagsDefaultBody) UnmarshalBinary(b []byte) error { + var res DesrcibeTagsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DesrcibeTagsOKBody desrcibe tags o k body +swagger:model DesrcibeTagsOKBody +*/ +type DesrcibeTagsOKBody struct { + + // result + Result *models.TagsResponse `json:"result,omitempty"` +} + +// Validate validates this desrcibe tags o k body +func (o *DesrcibeTagsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeTagsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeTagsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeTagsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this desrcibe tags o k body based on the context it is used +func (o *DesrcibeTagsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeTagsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeTagsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeTagsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DesrcibeTagsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DesrcibeTagsOKBody) UnmarshalBinary(b []byte) error { + var res DesrcibeTagsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_proxy/monitor_proxy_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_proxy/monitor_proxy_client.go new file mode 100644 index 0000000..548eb1f --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_proxy/monitor_proxy_client.go @@ -0,0 +1,117 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_proxy + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new monitor proxy API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for monitor proxy API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DesrcibeAgentStatus(params *DesrcibeAgentStatusParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DesrcibeAgentStatusOK, error) + + DesrcibeTags(params *DesrcibeTagsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DesrcibeTagsOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DesrcibeAgentStatus DesrcibeAgentStatus 获取agent状态 +*/ +func (a *Client) DesrcibeAgentStatus(params *DesrcibeAgentStatusParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DesrcibeAgentStatusOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDesrcibeAgentStatusParams() + } + op := &runtime.ClientOperation{ + ID: "desrcibeAgentStatus", + Method: "GET", + PathPattern: "/monitorProxy/desrcibeAgentStatus", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DesrcibeAgentStatusReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DesrcibeAgentStatusOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DesrcibeAgentStatusDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DesrcibeTags DesrcibeAgentStatus 获取tag列表 +*/ +func (a *Client) DesrcibeTags(params *DesrcibeTagsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DesrcibeTagsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDesrcibeTagsParams() + } + op := &runtime.ClientOperation{ + ID: "desrcibeTags", + Method: "GET", + PathPattern: "/monitorProxy/desrcibeTags", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DesrcibeTagsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DesrcibeTagsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DesrcibeTagsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/add_rule_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/add_rule_parameters.go new file mode 100644 index 0000000..49c4bb8 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/add_rule_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewAddRuleParams creates a new AddRuleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewAddRuleParams() *AddRuleParams { + return &AddRuleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewAddRuleParamsWithTimeout creates a new AddRuleParams object +// with the ability to set a timeout on a request. +func NewAddRuleParamsWithTimeout(timeout time.Duration) *AddRuleParams { + return &AddRuleParams{ + timeout: timeout, + } +} + +// NewAddRuleParamsWithContext creates a new AddRuleParams object +// with the ability to set a context for a request. +func NewAddRuleParamsWithContext(ctx context.Context) *AddRuleParams { + return &AddRuleParams{ + Context: ctx, + } +} + +// NewAddRuleParamsWithHTTPClient creates a new AddRuleParams object +// with the ability to set a custom HTTPClient for a request. +func NewAddRuleParamsWithHTTPClient(client *http.Client) *AddRuleParams { + return &AddRuleParams{ + HTTPClient: client, + } +} + +/* AddRuleParams contains all the parameters to send to the API endpoint + for the add rule operation. + + Typically these are written to a http.Request. +*/ +type AddRuleParams struct { + + // Body. + Body *models.AddRuleRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the add rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AddRuleParams) WithDefaults() *AddRuleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the add rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AddRuleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the add rule params +func (o *AddRuleParams) WithTimeout(timeout time.Duration) *AddRuleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the add rule params +func (o *AddRuleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the add rule params +func (o *AddRuleParams) WithContext(ctx context.Context) *AddRuleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the add rule params +func (o *AddRuleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the add rule params +func (o *AddRuleParams) WithHTTPClient(client *http.Client) *AddRuleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the add rule params +func (o *AddRuleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the add rule params +func (o *AddRuleParams) WithBody(body *models.AddRuleRequest) *AddRuleParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the add rule params +func (o *AddRuleParams) SetBody(body *models.AddRuleRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the add rule params +func (o *AddRuleParams) WithAuthorization(authorization string) *AddRuleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the add rule params +func (o *AddRuleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the add rule params +func (o *AddRuleParams) WithBmpLanguage(bmpLanguage *string) *AddRuleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the add rule params +func (o *AddRuleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the add rule params +func (o *AddRuleParams) WithBmpUserID(bmpUserID *string) *AddRuleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the add rule params +func (o *AddRuleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the add rule params +func (o *AddRuleParams) WithTraceID(traceID string) *AddRuleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the add rule params +func (o *AddRuleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *AddRuleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/add_rule_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/add_rule_responses.go new file mode 100644 index 0000000..fee5bbe --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/add_rule_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// AddRuleReader is a Reader for the AddRule structure. +type AddRuleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *AddRuleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewAddRuleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewAddRuleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewAddRuleOK creates a AddRuleOK with default headers values +func NewAddRuleOK() *AddRuleOK { + return &AddRuleOK{} +} + +/* AddRuleOK describes a response with status code 200, with default header values. + +A AddRuleResult is an response struct that is used to describe create rule result. +*/ +type AddRuleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *AddRuleOKBody +} + +// IsSuccess returns true when this add rule o k response has a 2xx status code +func (o *AddRuleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this add rule o k response has a 3xx status code +func (o *AddRuleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this add rule o k response has a 4xx status code +func (o *AddRuleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this add rule o k response has a 5xx status code +func (o *AddRuleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this add rule o k response a status code equal to that given +func (o *AddRuleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *AddRuleOK) Error() string { + return fmt.Sprintf("[POST /monitorRule/addRule][%d] addRuleOK %+v", 200, o.Payload) +} + +func (o *AddRuleOK) String() string { + return fmt.Sprintf("[POST /monitorRule/addRule][%d] addRuleOK %+v", 200, o.Payload) +} + +func (o *AddRuleOK) GetPayload() *AddRuleOKBody { + return o.Payload +} + +func (o *AddRuleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AddRuleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAddRuleDefault creates a AddRuleDefault with default headers values +func NewAddRuleDefault(code int) *AddRuleDefault { + return &AddRuleDefault{ + _statusCode: code, + } +} + +/* AddRuleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type AddRuleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *AddRuleDefaultBody +} + +// Code gets the status code for the add rule default response +func (o *AddRuleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this add rule default response has a 2xx status code +func (o *AddRuleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this add rule default response has a 3xx status code +func (o *AddRuleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this add rule default response has a 4xx status code +func (o *AddRuleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this add rule default response has a 5xx status code +func (o *AddRuleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this add rule default response a status code equal to that given +func (o *AddRuleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *AddRuleDefault) Error() string { + return fmt.Sprintf("[POST /monitorRule/addRule][%d] addRule default %+v", o._statusCode, o.Payload) +} + +func (o *AddRuleDefault) String() string { + return fmt.Sprintf("[POST /monitorRule/addRule][%d] addRule default %+v", o._statusCode, o.Payload) +} + +func (o *AddRuleDefault) GetPayload() *AddRuleDefaultBody { + return o.Payload +} + +func (o *AddRuleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AddRuleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*AddRuleDefaultBody add rule default body +swagger:model AddRuleDefaultBody +*/ +type AddRuleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this add rule default body +func (o *AddRuleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AddRuleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("addRule default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *AddRuleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("addRule default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("addRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("addRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this add rule default body based on the context it is used +func (o *AddRuleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AddRuleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("addRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("addRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AddRuleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AddRuleDefaultBody) UnmarshalBinary(b []byte) error { + var res AddRuleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*AddRuleOKBody add rule o k body +swagger:model AddRuleOKBody +*/ +type AddRuleOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this add rule o k body +func (o *AddRuleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AddRuleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("addRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("addRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this add rule o k body based on the context it is used +func (o *AddRuleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AddRuleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("addRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("addRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AddRuleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AddRuleOKBody) UnmarshalBinary(b []byte) error { + var res AddRuleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/delete_rule_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/delete_rule_parameters.go new file mode 100644 index 0000000..745ee8c --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/delete_rule_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewDeleteRuleParams creates a new DeleteRuleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteRuleParams() *DeleteRuleParams { + return &DeleteRuleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteRuleParamsWithTimeout creates a new DeleteRuleParams object +// with the ability to set a timeout on a request. +func NewDeleteRuleParamsWithTimeout(timeout time.Duration) *DeleteRuleParams { + return &DeleteRuleParams{ + timeout: timeout, + } +} + +// NewDeleteRuleParamsWithContext creates a new DeleteRuleParams object +// with the ability to set a context for a request. +func NewDeleteRuleParamsWithContext(ctx context.Context) *DeleteRuleParams { + return &DeleteRuleParams{ + Context: ctx, + } +} + +// NewDeleteRuleParamsWithHTTPClient creates a new DeleteRuleParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteRuleParamsWithHTTPClient(client *http.Client) *DeleteRuleParams { + return &DeleteRuleParams{ + HTTPClient: client, + } +} + +/* DeleteRuleParams contains all the parameters to send to the API endpoint + for the delete rule operation. + + Typically these are written to a http.Request. +*/ +type DeleteRuleParams struct { + + // Body. + Body *models.DeleteRuleRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteRuleParams) WithDefaults() *DeleteRuleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteRuleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete rule params +func (o *DeleteRuleParams) WithTimeout(timeout time.Duration) *DeleteRuleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete rule params +func (o *DeleteRuleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete rule params +func (o *DeleteRuleParams) WithContext(ctx context.Context) *DeleteRuleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete rule params +func (o *DeleteRuleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete rule params +func (o *DeleteRuleParams) WithHTTPClient(client *http.Client) *DeleteRuleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete rule params +func (o *DeleteRuleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the delete rule params +func (o *DeleteRuleParams) WithBody(body *models.DeleteRuleRequest) *DeleteRuleParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the delete rule params +func (o *DeleteRuleParams) SetBody(body *models.DeleteRuleRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the delete rule params +func (o *DeleteRuleParams) WithAuthorization(authorization string) *DeleteRuleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete rule params +func (o *DeleteRuleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete rule params +func (o *DeleteRuleParams) WithBmpLanguage(bmpLanguage *string) *DeleteRuleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete rule params +func (o *DeleteRuleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete rule params +func (o *DeleteRuleParams) WithBmpUserID(bmpUserID *string) *DeleteRuleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete rule params +func (o *DeleteRuleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete rule params +func (o *DeleteRuleParams) WithTraceID(traceID string) *DeleteRuleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete rule params +func (o *DeleteRuleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteRuleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/delete_rule_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/delete_rule_responses.go new file mode 100644 index 0000000..de808c1 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/delete_rule_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DeleteRuleReader is a Reader for the DeleteRule structure. +type DeleteRuleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteRuleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteRuleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteRuleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteRuleOK creates a DeleteRuleOK with default headers values +func NewDeleteRuleOK() *DeleteRuleOK { + return &DeleteRuleOK{} +} + +/* DeleteRuleOK describes a response with status code 200, with default header values. + +A DeleteRuleResult is an response struct that is used to describe create rule result. +*/ +type DeleteRuleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteRuleOKBody +} + +// IsSuccess returns true when this delete rule o k response has a 2xx status code +func (o *DeleteRuleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete rule o k response has a 3xx status code +func (o *DeleteRuleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete rule o k response has a 4xx status code +func (o *DeleteRuleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete rule o k response has a 5xx status code +func (o *DeleteRuleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete rule o k response a status code equal to that given +func (o *DeleteRuleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteRuleOK) Error() string { + return fmt.Sprintf("[DELETE /monitorRule/deleteRule][%d] deleteRuleOK %+v", 200, o.Payload) +} + +func (o *DeleteRuleOK) String() string { + return fmt.Sprintf("[DELETE /monitorRule/deleteRule][%d] deleteRuleOK %+v", 200, o.Payload) +} + +func (o *DeleteRuleOK) GetPayload() *DeleteRuleOKBody { + return o.Payload +} + +func (o *DeleteRuleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteRuleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteRuleDefault creates a DeleteRuleDefault with default headers values +func NewDeleteRuleDefault(code int) *DeleteRuleDefault { + return &DeleteRuleDefault{ + _statusCode: code, + } +} + +/* DeleteRuleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteRuleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteRuleDefaultBody +} + +// Code gets the status code for the delete rule default response +func (o *DeleteRuleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete rule default response has a 2xx status code +func (o *DeleteRuleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete rule default response has a 3xx status code +func (o *DeleteRuleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete rule default response has a 4xx status code +func (o *DeleteRuleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete rule default response has a 5xx status code +func (o *DeleteRuleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete rule default response a status code equal to that given +func (o *DeleteRuleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteRuleDefault) Error() string { + return fmt.Sprintf("[DELETE /monitorRule/deleteRule][%d] deleteRule default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteRuleDefault) String() string { + return fmt.Sprintf("[DELETE /monitorRule/deleteRule][%d] deleteRule default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteRuleDefault) GetPayload() *DeleteRuleDefaultBody { + return o.Payload +} + +func (o *DeleteRuleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteRuleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteRuleDefaultBody delete rule default body +swagger:model DeleteRuleDefaultBody +*/ +type DeleteRuleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete rule default body +func (o *DeleteRuleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRuleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteRule default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteRuleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteRule default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete rule default body based on the context it is used +func (o *DeleteRuleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRuleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteRuleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteRuleDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteRuleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteRuleOKBody delete rule o k body +swagger:model DeleteRuleOKBody +*/ +type DeleteRuleOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete rule o k body +func (o *DeleteRuleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRuleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete rule o k body based on the context it is used +func (o *DeleteRuleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRuleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteRuleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteRuleOKBody) UnmarshalBinary(b []byte) error { + var res DeleteRuleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/describe_rule_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/describe_rule_parameters.go new file mode 100644 index 0000000..b568b57 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/describe_rule_parameters.go @@ -0,0 +1,248 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeRuleParams creates a new DescribeRuleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeRuleParams() *DescribeRuleParams { + return &DescribeRuleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeRuleParamsWithTimeout creates a new DescribeRuleParams object +// with the ability to set a timeout on a request. +func NewDescribeRuleParamsWithTimeout(timeout time.Duration) *DescribeRuleParams { + return &DescribeRuleParams{ + timeout: timeout, + } +} + +// NewDescribeRuleParamsWithContext creates a new DescribeRuleParams object +// with the ability to set a context for a request. +func NewDescribeRuleParamsWithContext(ctx context.Context) *DescribeRuleParams { + return &DescribeRuleParams{ + Context: ctx, + } +} + +// NewDescribeRuleParamsWithHTTPClient creates a new DescribeRuleParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeRuleParamsWithHTTPClient(client *http.Client) *DescribeRuleParams { + return &DescribeRuleParams{ + HTTPClient: client, + } +} + +/* DescribeRuleParams contains all the parameters to send to the API endpoint + for the describe rule operation. + + Typically these are written to a http.Request. +*/ +type DescribeRuleParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* RuleID. + + rule uuid + */ + RuleID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRuleParams) WithDefaults() *DescribeRuleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRuleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe rule params +func (o *DescribeRuleParams) WithTimeout(timeout time.Duration) *DescribeRuleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe rule params +func (o *DescribeRuleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe rule params +func (o *DescribeRuleParams) WithContext(ctx context.Context) *DescribeRuleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe rule params +func (o *DescribeRuleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe rule params +func (o *DescribeRuleParams) WithHTTPClient(client *http.Client) *DescribeRuleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe rule params +func (o *DescribeRuleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe rule params +func (o *DescribeRuleParams) WithAuthorization(authorization string) *DescribeRuleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe rule params +func (o *DescribeRuleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe rule params +func (o *DescribeRuleParams) WithBmpLanguage(bmpLanguage *string) *DescribeRuleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe rule params +func (o *DescribeRuleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe rule params +func (o *DescribeRuleParams) WithBmpUserID(bmpUserID *string) *DescribeRuleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe rule params +func (o *DescribeRuleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithRuleID adds the ruleID to the describe rule params +func (o *DescribeRuleParams) WithRuleID(ruleID string) *DescribeRuleParams { + o.SetRuleID(ruleID) + return o +} + +// SetRuleID adds the ruleId to the describe rule params +func (o *DescribeRuleParams) SetRuleID(ruleID string) { + o.RuleID = ruleID +} + +// WithTraceID adds the traceID to the describe rule params +func (o *DescribeRuleParams) WithTraceID(traceID string) *DescribeRuleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe rule params +func (o *DescribeRuleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeRuleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // query param ruleId + qrRuleID := o.RuleID + qRuleID := qrRuleID + if qRuleID != "" { + + if err := r.SetQueryParam("ruleId", qRuleID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/describe_rule_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/describe_rule_responses.go new file mode 100644 index 0000000..05b6301 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/describe_rule_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeRuleReader is a Reader for the DescribeRule structure. +type DescribeRuleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeRuleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeRuleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeRuleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeRuleOK creates a DescribeRuleOK with default headers values +func NewDescribeRuleOK() *DescribeRuleOK { + return &DescribeRuleOK{} +} + +/* DescribeRuleOK describes a response with status code 200, with default header values. + +A DescribeRuleResult is an response struct that is used to describe get rule. +*/ +type DescribeRuleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRuleOKBody +} + +// IsSuccess returns true when this describe rule o k response has a 2xx status code +func (o *DescribeRuleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe rule o k response has a 3xx status code +func (o *DescribeRuleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe rule o k response has a 4xx status code +func (o *DescribeRuleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe rule o k response has a 5xx status code +func (o *DescribeRuleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe rule o k response a status code equal to that given +func (o *DescribeRuleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeRuleOK) Error() string { + return fmt.Sprintf("[GET /monitorRule/describeRule][%d] describeRuleOK %+v", 200, o.Payload) +} + +func (o *DescribeRuleOK) String() string { + return fmt.Sprintf("[GET /monitorRule/describeRule][%d] describeRuleOK %+v", 200, o.Payload) +} + +func (o *DescribeRuleOK) GetPayload() *DescribeRuleOKBody { + return o.Payload +} + +func (o *DescribeRuleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRuleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeRuleDefault creates a DescribeRuleDefault with default headers values +func NewDescribeRuleDefault(code int) *DescribeRuleDefault { + return &DescribeRuleDefault{ + _statusCode: code, + } +} + +/* DescribeRuleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeRuleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRuleDefaultBody +} + +// Code gets the status code for the describe rule default response +func (o *DescribeRuleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe rule default response has a 2xx status code +func (o *DescribeRuleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe rule default response has a 3xx status code +func (o *DescribeRuleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe rule default response has a 4xx status code +func (o *DescribeRuleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe rule default response has a 5xx status code +func (o *DescribeRuleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe rule default response a status code equal to that given +func (o *DescribeRuleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeRuleDefault) Error() string { + return fmt.Sprintf("[GET /monitorRule/describeRule][%d] describeRule default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRuleDefault) String() string { + return fmt.Sprintf("[GET /monitorRule/describeRule][%d] describeRule default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRuleDefault) GetPayload() *DescribeRuleDefaultBody { + return o.Payload +} + +func (o *DescribeRuleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRuleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeRuleDefaultBody describe rule default body +swagger:model DescribeRuleDefaultBody +*/ +type DescribeRuleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe rule default body +func (o *DescribeRuleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRuleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeRule default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeRuleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeRule default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe rule default body based on the context it is used +func (o *DescribeRuleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRuleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRuleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRuleDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeRuleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeRuleOKBody describe rule o k body +swagger:model DescribeRuleOKBody +*/ +type DescribeRuleOKBody struct { + + // result + Result *models.Rule `json:"result,omitempty"` +} + +// Validate validates this describe rule o k body +func (o *DescribeRuleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRuleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe rule o k body based on the context it is used +func (o *DescribeRuleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRuleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRuleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRuleOKBody) UnmarshalBinary(b []byte) error { + var res DescribeRuleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/describe_rules_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/describe_rules_parameters.go new file mode 100644 index 0000000..9eedecb --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/describe_rules_parameters.go @@ -0,0 +1,534 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeRulesParams creates a new DescribeRulesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeRulesParams() *DescribeRulesParams { + return &DescribeRulesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeRulesParamsWithTimeout creates a new DescribeRulesParams object +// with the ability to set a timeout on a request. +func NewDescribeRulesParamsWithTimeout(timeout time.Duration) *DescribeRulesParams { + return &DescribeRulesParams{ + timeout: timeout, + } +} + +// NewDescribeRulesParamsWithContext creates a new DescribeRulesParams object +// with the ability to set a context for a request. +func NewDescribeRulesParamsWithContext(ctx context.Context) *DescribeRulesParams { + return &DescribeRulesParams{ + Context: ctx, + } +} + +// NewDescribeRulesParamsWithHTTPClient creates a new DescribeRulesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeRulesParamsWithHTTPClient(client *http.Client) *DescribeRulesParams { + return &DescribeRulesParams{ + HTTPClient: client, + } +} + +/* DescribeRulesParams contains all the parameters to send to the API endpoint + for the describe rules operation. + + Typically these are written to a http.Request. +*/ +type DescribeRulesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否显示全部,取值为1时表示全部 + */ + IsAll *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* ProjectID. + + project uuid + */ + ProjectID *string + + /* RuleID. + + 规则uuid + */ + RuleID *string + + /* RuleName. + + 规则名称,模糊搜索 + */ + RuleName *string + + /* Status. + + 规则状态[1->正常,2->禁用,3->报警] + + Format: int64 + */ + Status *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserID. + + user uuid + */ + UserID *string + + /* UserName. + + username + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe rules params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRulesParams) WithDefaults() *DescribeRulesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe rules params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRulesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe rules params +func (o *DescribeRulesParams) WithTimeout(timeout time.Duration) *DescribeRulesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe rules params +func (o *DescribeRulesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe rules params +func (o *DescribeRulesParams) WithContext(ctx context.Context) *DescribeRulesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe rules params +func (o *DescribeRulesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe rules params +func (o *DescribeRulesParams) WithHTTPClient(client *http.Client) *DescribeRulesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe rules params +func (o *DescribeRulesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe rules params +func (o *DescribeRulesParams) WithAuthorization(authorization string) *DescribeRulesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe rules params +func (o *DescribeRulesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe rules params +func (o *DescribeRulesParams) WithBmpLanguage(bmpLanguage *string) *DescribeRulesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe rules params +func (o *DescribeRulesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe rules params +func (o *DescribeRulesParams) WithBmpUserID(bmpUserID *string) *DescribeRulesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe rules params +func (o *DescribeRulesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe rules params +func (o *DescribeRulesParams) WithIsAll(isAll *string) *DescribeRulesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe rules params +func (o *DescribeRulesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithPageNumber adds the pageNumber to the describe rules params +func (o *DescribeRulesParams) WithPageNumber(pageNumber *int64) *DescribeRulesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe rules params +func (o *DescribeRulesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe rules params +func (o *DescribeRulesParams) WithPageSize(pageSize *int64) *DescribeRulesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe rules params +func (o *DescribeRulesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithProjectID adds the projectID to the describe rules params +func (o *DescribeRulesParams) WithProjectID(projectID *string) *DescribeRulesParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the describe rules params +func (o *DescribeRulesParams) SetProjectID(projectID *string) { + o.ProjectID = projectID +} + +// WithRuleID adds the ruleID to the describe rules params +func (o *DescribeRulesParams) WithRuleID(ruleID *string) *DescribeRulesParams { + o.SetRuleID(ruleID) + return o +} + +// SetRuleID adds the ruleId to the describe rules params +func (o *DescribeRulesParams) SetRuleID(ruleID *string) { + o.RuleID = ruleID +} + +// WithRuleName adds the ruleName to the describe rules params +func (o *DescribeRulesParams) WithRuleName(ruleName *string) *DescribeRulesParams { + o.SetRuleName(ruleName) + return o +} + +// SetRuleName adds the ruleName to the describe rules params +func (o *DescribeRulesParams) SetRuleName(ruleName *string) { + o.RuleName = ruleName +} + +// WithStatus adds the status to the describe rules params +func (o *DescribeRulesParams) WithStatus(status *int64) *DescribeRulesParams { + o.SetStatus(status) + return o +} + +// SetStatus adds the status to the describe rules params +func (o *DescribeRulesParams) SetStatus(status *int64) { + o.Status = status +} + +// WithTraceID adds the traceID to the describe rules params +func (o *DescribeRulesParams) WithTraceID(traceID string) *DescribeRulesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe rules params +func (o *DescribeRulesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserID adds the userID to the describe rules params +func (o *DescribeRulesParams) WithUserID(userID *string) *DescribeRulesParams { + o.SetUserID(userID) + return o +} + +// SetUserID adds the userId to the describe rules params +func (o *DescribeRulesParams) SetUserID(userID *string) { + o.UserID = userID +} + +// WithUserName adds the userName to the describe rules params +func (o *DescribeRulesParams) WithUserName(userName *string) *DescribeRulesParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe rules params +func (o *DescribeRulesParams) SetUserName(userName *string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeRulesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.ProjectID != nil { + + // query param projectId + var qrProjectID string + + if o.ProjectID != nil { + qrProjectID = *o.ProjectID + } + qProjectID := qrProjectID + if qProjectID != "" { + + if err := r.SetQueryParam("projectId", qProjectID); err != nil { + return err + } + } + } + + if o.RuleID != nil { + + // query param ruleId + var qrRuleID string + + if o.RuleID != nil { + qrRuleID = *o.RuleID + } + qRuleID := qrRuleID + if qRuleID != "" { + + if err := r.SetQueryParam("ruleId", qRuleID); err != nil { + return err + } + } + } + + if o.RuleName != nil { + + // query param ruleName + var qrRuleName string + + if o.RuleName != nil { + qrRuleName = *o.RuleName + } + qRuleName := qrRuleName + if qRuleName != "" { + + if err := r.SetQueryParam("ruleName", qRuleName); err != nil { + return err + } + } + } + + if o.Status != nil { + + // query param status + var qrStatus int64 + + if o.Status != nil { + qrStatus = *o.Status + } + qStatus := swag.FormatInt64(qrStatus) + if qStatus != "" { + + if err := r.SetQueryParam("status", qStatus); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserID != nil { + + // query param userId + var qrUserID string + + if o.UserID != nil { + qrUserID = *o.UserID + } + qUserID := qrUserID + if qUserID != "" { + + if err := r.SetQueryParam("userId", qUserID); err != nil { + return err + } + } + } + + if o.UserName != nil { + + // query param userName + var qrUserName string + + if o.UserName != nil { + qrUserName = *o.UserName + } + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/describe_rules_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/describe_rules_responses.go new file mode 100644 index 0000000..549ca27 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/describe_rules_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeRulesReader is a Reader for the DescribeRules structure. +type DescribeRulesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeRulesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeRulesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeRulesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeRulesOK creates a DescribeRulesOK with default headers values +func NewDescribeRulesOK() *DescribeRulesOK { + return &DescribeRulesOK{} +} + +/* DescribeRulesOK describes a response with status code 200, with default header values. + +A DescribeRuleResult is an response struct that is used to describe get rule. +*/ +type DescribeRulesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRulesOKBody +} + +// IsSuccess returns true when this describe rules o k response has a 2xx status code +func (o *DescribeRulesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe rules o k response has a 3xx status code +func (o *DescribeRulesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe rules o k response has a 4xx status code +func (o *DescribeRulesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe rules o k response has a 5xx status code +func (o *DescribeRulesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe rules o k response a status code equal to that given +func (o *DescribeRulesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeRulesOK) Error() string { + return fmt.Sprintf("[GET /monitorRule/describeRules][%d] describeRulesOK %+v", 200, o.Payload) +} + +func (o *DescribeRulesOK) String() string { + return fmt.Sprintf("[GET /monitorRule/describeRules][%d] describeRulesOK %+v", 200, o.Payload) +} + +func (o *DescribeRulesOK) GetPayload() *DescribeRulesOKBody { + return o.Payload +} + +func (o *DescribeRulesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRulesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeRulesDefault creates a DescribeRulesDefault with default headers values +func NewDescribeRulesDefault(code int) *DescribeRulesDefault { + return &DescribeRulesDefault{ + _statusCode: code, + } +} + +/* DescribeRulesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeRulesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRulesDefaultBody +} + +// Code gets the status code for the describe rules default response +func (o *DescribeRulesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe rules default response has a 2xx status code +func (o *DescribeRulesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe rules default response has a 3xx status code +func (o *DescribeRulesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe rules default response has a 4xx status code +func (o *DescribeRulesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe rules default response has a 5xx status code +func (o *DescribeRulesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe rules default response a status code equal to that given +func (o *DescribeRulesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeRulesDefault) Error() string { + return fmt.Sprintf("[GET /monitorRule/describeRules][%d] describeRules default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRulesDefault) String() string { + return fmt.Sprintf("[GET /monitorRule/describeRules][%d] describeRules default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRulesDefault) GetPayload() *DescribeRulesDefaultBody { + return o.Payload +} + +func (o *DescribeRulesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRulesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeRulesDefaultBody describe rules default body +swagger:model DescribeRulesDefaultBody +*/ +type DescribeRulesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe rules default body +func (o *DescribeRulesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRulesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeRules default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeRulesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeRules default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRules default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRules default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe rules default body based on the context it is used +func (o *DescribeRulesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRulesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRules default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRules default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRulesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRulesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeRulesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeRulesOKBody describe rules o k body +swagger:model DescribeRulesOKBody +*/ +type DescribeRulesOKBody struct { + + // result + Result *models.RuleList `json:"result,omitempty"` +} + +// Validate validates this describe rules o k body +func (o *DescribeRulesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRulesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRulesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRulesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe rules o k body based on the context it is used +func (o *DescribeRulesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRulesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRulesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRulesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRulesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRulesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeRulesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/disable_rule_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/disable_rule_parameters.go new file mode 100644 index 0000000..b0544d2 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/disable_rule_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewDisableRuleParams creates a new DisableRuleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDisableRuleParams() *DisableRuleParams { + return &DisableRuleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDisableRuleParamsWithTimeout creates a new DisableRuleParams object +// with the ability to set a timeout on a request. +func NewDisableRuleParamsWithTimeout(timeout time.Duration) *DisableRuleParams { + return &DisableRuleParams{ + timeout: timeout, + } +} + +// NewDisableRuleParamsWithContext creates a new DisableRuleParams object +// with the ability to set a context for a request. +func NewDisableRuleParamsWithContext(ctx context.Context) *DisableRuleParams { + return &DisableRuleParams{ + Context: ctx, + } +} + +// NewDisableRuleParamsWithHTTPClient creates a new DisableRuleParams object +// with the ability to set a custom HTTPClient for a request. +func NewDisableRuleParamsWithHTTPClient(client *http.Client) *DisableRuleParams { + return &DisableRuleParams{ + HTTPClient: client, + } +} + +/* DisableRuleParams contains all the parameters to send to the API endpoint + for the disable rule operation. + + Typically these are written to a http.Request. +*/ +type DisableRuleParams struct { + + // Body. + Body *models.DisableRuleRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the disable rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DisableRuleParams) WithDefaults() *DisableRuleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the disable rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DisableRuleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the disable rule params +func (o *DisableRuleParams) WithTimeout(timeout time.Duration) *DisableRuleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the disable rule params +func (o *DisableRuleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the disable rule params +func (o *DisableRuleParams) WithContext(ctx context.Context) *DisableRuleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the disable rule params +func (o *DisableRuleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the disable rule params +func (o *DisableRuleParams) WithHTTPClient(client *http.Client) *DisableRuleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the disable rule params +func (o *DisableRuleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the disable rule params +func (o *DisableRuleParams) WithBody(body *models.DisableRuleRequest) *DisableRuleParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the disable rule params +func (o *DisableRuleParams) SetBody(body *models.DisableRuleRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the disable rule params +func (o *DisableRuleParams) WithAuthorization(authorization string) *DisableRuleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the disable rule params +func (o *DisableRuleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the disable rule params +func (o *DisableRuleParams) WithBmpLanguage(bmpLanguage *string) *DisableRuleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the disable rule params +func (o *DisableRuleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the disable rule params +func (o *DisableRuleParams) WithBmpUserID(bmpUserID *string) *DisableRuleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the disable rule params +func (o *DisableRuleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the disable rule params +func (o *DisableRuleParams) WithTraceID(traceID string) *DisableRuleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the disable rule params +func (o *DisableRuleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DisableRuleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/disable_rule_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/disable_rule_responses.go new file mode 100644 index 0000000..55cfe08 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/disable_rule_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DisableRuleReader is a Reader for the DisableRule structure. +type DisableRuleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DisableRuleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDisableRuleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDisableRuleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDisableRuleOK creates a DisableRuleOK with default headers values +func NewDisableRuleOK() *DisableRuleOK { + return &DisableRuleOK{} +} + +/* DisableRuleOK describes a response with status code 200, with default header values. + +A DisableRuleResult is an response struct that is used to describe create rule result. +*/ +type DisableRuleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DisableRuleOKBody +} + +// IsSuccess returns true when this disable rule o k response has a 2xx status code +func (o *DisableRuleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this disable rule o k response has a 3xx status code +func (o *DisableRuleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this disable rule o k response has a 4xx status code +func (o *DisableRuleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this disable rule o k response has a 5xx status code +func (o *DisableRuleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this disable rule o k response a status code equal to that given +func (o *DisableRuleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DisableRuleOK) Error() string { + return fmt.Sprintf("[PUT /monitorRule/disableRule][%d] disableRuleOK %+v", 200, o.Payload) +} + +func (o *DisableRuleOK) String() string { + return fmt.Sprintf("[PUT /monitorRule/disableRule][%d] disableRuleOK %+v", 200, o.Payload) +} + +func (o *DisableRuleOK) GetPayload() *DisableRuleOKBody { + return o.Payload +} + +func (o *DisableRuleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DisableRuleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDisableRuleDefault creates a DisableRuleDefault with default headers values +func NewDisableRuleDefault(code int) *DisableRuleDefault { + return &DisableRuleDefault{ + _statusCode: code, + } +} + +/* DisableRuleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DisableRuleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DisableRuleDefaultBody +} + +// Code gets the status code for the disable rule default response +func (o *DisableRuleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this disable rule default response has a 2xx status code +func (o *DisableRuleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this disable rule default response has a 3xx status code +func (o *DisableRuleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this disable rule default response has a 4xx status code +func (o *DisableRuleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this disable rule default response has a 5xx status code +func (o *DisableRuleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this disable rule default response a status code equal to that given +func (o *DisableRuleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DisableRuleDefault) Error() string { + return fmt.Sprintf("[PUT /monitorRule/disableRule][%d] disableRule default %+v", o._statusCode, o.Payload) +} + +func (o *DisableRuleDefault) String() string { + return fmt.Sprintf("[PUT /monitorRule/disableRule][%d] disableRule default %+v", o._statusCode, o.Payload) +} + +func (o *DisableRuleDefault) GetPayload() *DisableRuleDefaultBody { + return o.Payload +} + +func (o *DisableRuleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DisableRuleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DisableRuleDefaultBody disable rule default body +swagger:model DisableRuleDefaultBody +*/ +type DisableRuleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this disable rule default body +func (o *DisableRuleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DisableRuleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("disableRule default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DisableRuleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("disableRule default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("disableRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("disableRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this disable rule default body based on the context it is used +func (o *DisableRuleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DisableRuleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("disableRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("disableRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DisableRuleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DisableRuleDefaultBody) UnmarshalBinary(b []byte) error { + var res DisableRuleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DisableRuleOKBody disable rule o k body +swagger:model DisableRuleOKBody +*/ +type DisableRuleOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this disable rule o k body +func (o *DisableRuleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DisableRuleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("disableRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("disableRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this disable rule o k body based on the context it is used +func (o *DisableRuleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DisableRuleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("disableRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("disableRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DisableRuleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DisableRuleOKBody) UnmarshalBinary(b []byte) error { + var res DisableRuleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/edit_rule_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/edit_rule_parameters.go new file mode 100644 index 0000000..31a1a4c --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/edit_rule_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewEditRuleParams creates a new EditRuleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewEditRuleParams() *EditRuleParams { + return &EditRuleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewEditRuleParamsWithTimeout creates a new EditRuleParams object +// with the ability to set a timeout on a request. +func NewEditRuleParamsWithTimeout(timeout time.Duration) *EditRuleParams { + return &EditRuleParams{ + timeout: timeout, + } +} + +// NewEditRuleParamsWithContext creates a new EditRuleParams object +// with the ability to set a context for a request. +func NewEditRuleParamsWithContext(ctx context.Context) *EditRuleParams { + return &EditRuleParams{ + Context: ctx, + } +} + +// NewEditRuleParamsWithHTTPClient creates a new EditRuleParams object +// with the ability to set a custom HTTPClient for a request. +func NewEditRuleParamsWithHTTPClient(client *http.Client) *EditRuleParams { + return &EditRuleParams{ + HTTPClient: client, + } +} + +/* EditRuleParams contains all the parameters to send to the API endpoint + for the edit rule operation. + + Typically these are written to a http.Request. +*/ +type EditRuleParams struct { + + // Body. + Body *models.EditRuleRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the edit rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *EditRuleParams) WithDefaults() *EditRuleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the edit rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *EditRuleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the edit rule params +func (o *EditRuleParams) WithTimeout(timeout time.Duration) *EditRuleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the edit rule params +func (o *EditRuleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the edit rule params +func (o *EditRuleParams) WithContext(ctx context.Context) *EditRuleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the edit rule params +func (o *EditRuleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the edit rule params +func (o *EditRuleParams) WithHTTPClient(client *http.Client) *EditRuleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the edit rule params +func (o *EditRuleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the edit rule params +func (o *EditRuleParams) WithBody(body *models.EditRuleRequest) *EditRuleParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the edit rule params +func (o *EditRuleParams) SetBody(body *models.EditRuleRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the edit rule params +func (o *EditRuleParams) WithAuthorization(authorization string) *EditRuleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the edit rule params +func (o *EditRuleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the edit rule params +func (o *EditRuleParams) WithBmpLanguage(bmpLanguage *string) *EditRuleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the edit rule params +func (o *EditRuleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the edit rule params +func (o *EditRuleParams) WithBmpUserID(bmpUserID *string) *EditRuleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the edit rule params +func (o *EditRuleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the edit rule params +func (o *EditRuleParams) WithTraceID(traceID string) *EditRuleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the edit rule params +func (o *EditRuleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *EditRuleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/edit_rule_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/edit_rule_responses.go new file mode 100644 index 0000000..1367a26 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/edit_rule_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// EditRuleReader is a Reader for the EditRule structure. +type EditRuleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *EditRuleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewEditRuleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewEditRuleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewEditRuleOK creates a EditRuleOK with default headers values +func NewEditRuleOK() *EditRuleOK { + return &EditRuleOK{} +} + +/* EditRuleOK describes a response with status code 200, with default header values. + +A EditRuleResult is an response struct that is used to describe create rule result. +*/ +type EditRuleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *EditRuleOKBody +} + +// IsSuccess returns true when this edit rule o k response has a 2xx status code +func (o *EditRuleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this edit rule o k response has a 3xx status code +func (o *EditRuleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this edit rule o k response has a 4xx status code +func (o *EditRuleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this edit rule o k response has a 5xx status code +func (o *EditRuleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this edit rule o k response a status code equal to that given +func (o *EditRuleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *EditRuleOK) Error() string { + return fmt.Sprintf("[PUT /monitorRule/editRule][%d] editRuleOK %+v", 200, o.Payload) +} + +func (o *EditRuleOK) String() string { + return fmt.Sprintf("[PUT /monitorRule/editRule][%d] editRuleOK %+v", 200, o.Payload) +} + +func (o *EditRuleOK) GetPayload() *EditRuleOKBody { + return o.Payload +} + +func (o *EditRuleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(EditRuleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewEditRuleDefault creates a EditRuleDefault with default headers values +func NewEditRuleDefault(code int) *EditRuleDefault { + return &EditRuleDefault{ + _statusCode: code, + } +} + +/* EditRuleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type EditRuleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *EditRuleDefaultBody +} + +// Code gets the status code for the edit rule default response +func (o *EditRuleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this edit rule default response has a 2xx status code +func (o *EditRuleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this edit rule default response has a 3xx status code +func (o *EditRuleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this edit rule default response has a 4xx status code +func (o *EditRuleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this edit rule default response has a 5xx status code +func (o *EditRuleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this edit rule default response a status code equal to that given +func (o *EditRuleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *EditRuleDefault) Error() string { + return fmt.Sprintf("[PUT /monitorRule/editRule][%d] editRule default %+v", o._statusCode, o.Payload) +} + +func (o *EditRuleDefault) String() string { + return fmt.Sprintf("[PUT /monitorRule/editRule][%d] editRule default %+v", o._statusCode, o.Payload) +} + +func (o *EditRuleDefault) GetPayload() *EditRuleDefaultBody { + return o.Payload +} + +func (o *EditRuleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(EditRuleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*EditRuleDefaultBody edit rule default body +swagger:model EditRuleDefaultBody +*/ +type EditRuleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this edit rule default body +func (o *EditRuleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EditRuleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("editRule default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *EditRuleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("editRule default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("editRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("editRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this edit rule default body based on the context it is used +func (o *EditRuleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EditRuleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("editRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("editRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *EditRuleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *EditRuleDefaultBody) UnmarshalBinary(b []byte) error { + var res EditRuleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*EditRuleOKBody edit rule o k body +swagger:model EditRuleOKBody +*/ +type EditRuleOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this edit rule o k body +func (o *EditRuleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EditRuleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("editRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("editRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this edit rule o k body based on the context it is used +func (o *EditRuleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EditRuleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("editRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("editRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *EditRuleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *EditRuleOKBody) UnmarshalBinary(b []byte) error { + var res EditRuleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/enable_rule_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/enable_rule_parameters.go new file mode 100644 index 0000000..a641c53 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/enable_rule_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewEnableRuleParams creates a new EnableRuleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewEnableRuleParams() *EnableRuleParams { + return &EnableRuleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewEnableRuleParamsWithTimeout creates a new EnableRuleParams object +// with the ability to set a timeout on a request. +func NewEnableRuleParamsWithTimeout(timeout time.Duration) *EnableRuleParams { + return &EnableRuleParams{ + timeout: timeout, + } +} + +// NewEnableRuleParamsWithContext creates a new EnableRuleParams object +// with the ability to set a context for a request. +func NewEnableRuleParamsWithContext(ctx context.Context) *EnableRuleParams { + return &EnableRuleParams{ + Context: ctx, + } +} + +// NewEnableRuleParamsWithHTTPClient creates a new EnableRuleParams object +// with the ability to set a custom HTTPClient for a request. +func NewEnableRuleParamsWithHTTPClient(client *http.Client) *EnableRuleParams { + return &EnableRuleParams{ + HTTPClient: client, + } +} + +/* EnableRuleParams contains all the parameters to send to the API endpoint + for the enable rule operation. + + Typically these are written to a http.Request. +*/ +type EnableRuleParams struct { + + // Body. + Body *models.EnableRuleRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the enable rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *EnableRuleParams) WithDefaults() *EnableRuleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the enable rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *EnableRuleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the enable rule params +func (o *EnableRuleParams) WithTimeout(timeout time.Duration) *EnableRuleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the enable rule params +func (o *EnableRuleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the enable rule params +func (o *EnableRuleParams) WithContext(ctx context.Context) *EnableRuleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the enable rule params +func (o *EnableRuleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the enable rule params +func (o *EnableRuleParams) WithHTTPClient(client *http.Client) *EnableRuleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the enable rule params +func (o *EnableRuleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the enable rule params +func (o *EnableRuleParams) WithBody(body *models.EnableRuleRequest) *EnableRuleParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the enable rule params +func (o *EnableRuleParams) SetBody(body *models.EnableRuleRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the enable rule params +func (o *EnableRuleParams) WithAuthorization(authorization string) *EnableRuleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the enable rule params +func (o *EnableRuleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the enable rule params +func (o *EnableRuleParams) WithBmpLanguage(bmpLanguage *string) *EnableRuleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the enable rule params +func (o *EnableRuleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the enable rule params +func (o *EnableRuleParams) WithBmpUserID(bmpUserID *string) *EnableRuleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the enable rule params +func (o *EnableRuleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the enable rule params +func (o *EnableRuleParams) WithTraceID(traceID string) *EnableRuleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the enable rule params +func (o *EnableRuleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *EnableRuleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/enable_rule_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/enable_rule_responses.go new file mode 100644 index 0000000..f969b83 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/enable_rule_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// EnableRuleReader is a Reader for the EnableRule structure. +type EnableRuleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *EnableRuleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewEnableRuleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewEnableRuleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewEnableRuleOK creates a EnableRuleOK with default headers values +func NewEnableRuleOK() *EnableRuleOK { + return &EnableRuleOK{} +} + +/* EnableRuleOK describes a response with status code 200, with default header values. + +A EnableRuleResult is an response struct that is used to describe create rule result. +*/ +type EnableRuleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *EnableRuleOKBody +} + +// IsSuccess returns true when this enable rule o k response has a 2xx status code +func (o *EnableRuleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this enable rule o k response has a 3xx status code +func (o *EnableRuleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this enable rule o k response has a 4xx status code +func (o *EnableRuleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this enable rule o k response has a 5xx status code +func (o *EnableRuleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this enable rule o k response a status code equal to that given +func (o *EnableRuleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *EnableRuleOK) Error() string { + return fmt.Sprintf("[PUT /monitorRule/enableRule][%d] enableRuleOK %+v", 200, o.Payload) +} + +func (o *EnableRuleOK) String() string { + return fmt.Sprintf("[PUT /monitorRule/enableRule][%d] enableRuleOK %+v", 200, o.Payload) +} + +func (o *EnableRuleOK) GetPayload() *EnableRuleOKBody { + return o.Payload +} + +func (o *EnableRuleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(EnableRuleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewEnableRuleDefault creates a EnableRuleDefault with default headers values +func NewEnableRuleDefault(code int) *EnableRuleDefault { + return &EnableRuleDefault{ + _statusCode: code, + } +} + +/* EnableRuleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type EnableRuleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *EnableRuleDefaultBody +} + +// Code gets the status code for the enable rule default response +func (o *EnableRuleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this enable rule default response has a 2xx status code +func (o *EnableRuleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this enable rule default response has a 3xx status code +func (o *EnableRuleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this enable rule default response has a 4xx status code +func (o *EnableRuleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this enable rule default response has a 5xx status code +func (o *EnableRuleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this enable rule default response a status code equal to that given +func (o *EnableRuleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *EnableRuleDefault) Error() string { + return fmt.Sprintf("[PUT /monitorRule/enableRule][%d] enableRule default %+v", o._statusCode, o.Payload) +} + +func (o *EnableRuleDefault) String() string { + return fmt.Sprintf("[PUT /monitorRule/enableRule][%d] enableRule default %+v", o._statusCode, o.Payload) +} + +func (o *EnableRuleDefault) GetPayload() *EnableRuleDefaultBody { + return o.Payload +} + +func (o *EnableRuleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(EnableRuleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*EnableRuleDefaultBody enable rule default body +swagger:model EnableRuleDefaultBody +*/ +type EnableRuleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this enable rule default body +func (o *EnableRuleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EnableRuleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("enableRule default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *EnableRuleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("enableRule default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("enableRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("enableRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this enable rule default body based on the context it is used +func (o *EnableRuleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EnableRuleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("enableRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("enableRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *EnableRuleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *EnableRuleDefaultBody) UnmarshalBinary(b []byte) error { + var res EnableRuleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*EnableRuleOKBody enable rule o k body +swagger:model EnableRuleOKBody +*/ +type EnableRuleOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this enable rule o k body +func (o *EnableRuleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EnableRuleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("enableRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("enableRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this enable rule o k body based on the context it is used +func (o *EnableRuleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EnableRuleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("enableRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("enableRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *EnableRuleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *EnableRuleOKBody) UnmarshalBinary(b []byte) error { + var res EnableRuleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/monitor_rule_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/monitor_rule_client.go new file mode 100644 index 0000000..286c404 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/monitor_rule/monitor_rule_client.go @@ -0,0 +1,317 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new monitor rule API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for monitor rule API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + AddRule(params *AddRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AddRuleOK, error) + + DeleteRule(params *DeleteRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteRuleOK, error) + + DescribeRule(params *DescribeRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRuleOK, error) + + DescribeRules(params *DescribeRulesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRulesOK, error) + + DisableRule(params *DisableRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DisableRuleOK, error) + + EditRule(params *EditRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*EditRuleOK, error) + + EnableRule(params *EnableRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*EnableRuleOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + AddRule AddRule 添加规则 +*/ +func (a *Client) AddRule(params *AddRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AddRuleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewAddRuleParams() + } + op := &runtime.ClientOperation{ + ID: "addRule", + Method: "POST", + PathPattern: "/monitorRule/addRule", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &AddRuleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*AddRuleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*AddRuleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteRule DeleteRule 删除规则 +*/ +func (a *Client) DeleteRule(params *DeleteRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteRuleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteRuleParams() + } + op := &runtime.ClientOperation{ + ID: "deleteRule", + Method: "DELETE", + PathPattern: "/monitorRule/deleteRule", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteRuleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteRuleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteRuleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeRule DescribeRule 规则详情 +*/ +func (a *Client) DescribeRule(params *DescribeRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRuleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeRuleParams() + } + op := &runtime.ClientOperation{ + ID: "describeRule", + Method: "GET", + PathPattern: "/monitorRule/describeRule", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeRuleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeRuleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeRuleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeRules DescribeRules 规则列表 +*/ +func (a *Client) DescribeRules(params *DescribeRulesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRulesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeRulesParams() + } + op := &runtime.ClientOperation{ + ID: "describeRules", + Method: "GET", + PathPattern: "/monitorRule/describeRules", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeRulesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeRulesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeRulesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DisableRule DisableRule 禁用规则 +*/ +func (a *Client) DisableRule(params *DisableRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DisableRuleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDisableRuleParams() + } + op := &runtime.ClientOperation{ + ID: "disableRule", + Method: "PUT", + PathPattern: "/monitorRule/disableRule", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DisableRuleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DisableRuleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DisableRuleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + EditRule EditRule 编辑规则 +*/ +func (a *Client) EditRule(params *EditRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*EditRuleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewEditRuleParams() + } + op := &runtime.ClientOperation{ + ID: "editRule", + Method: "PUT", + PathPattern: "/monitorRule/editRule", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &EditRuleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*EditRuleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*EditRuleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + EnableRule EnableRule 启用规则 +*/ +func (a *Client) EnableRule(params *EnableRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*EnableRuleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewEnableRuleParams() + } + op := &runtime.ClientOperation{ + ID: "enableRule", + Method: "PUT", + PathPattern: "/monitorRule/enableRule", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &EnableRuleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*EnableRuleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*EnableRuleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/os/describe_o_s_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/os/describe_o_s_parameters.go new file mode 100644 index 0000000..df2f89f --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/os/describe_o_s_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeOSParams creates a new DescribeOSParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeOSParams() *DescribeOSParams { + return &DescribeOSParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeOSParamsWithTimeout creates a new DescribeOSParams object +// with the ability to set a timeout on a request. +func NewDescribeOSParamsWithTimeout(timeout time.Duration) *DescribeOSParams { + return &DescribeOSParams{ + timeout: timeout, + } +} + +// NewDescribeOSParamsWithContext creates a new DescribeOSParams object +// with the ability to set a context for a request. +func NewDescribeOSParamsWithContext(ctx context.Context) *DescribeOSParams { + return &DescribeOSParams{ + Context: ctx, + } +} + +// NewDescribeOSParamsWithHTTPClient creates a new DescribeOSParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeOSParamsWithHTTPClient(client *http.Client) *DescribeOSParams { + return &DescribeOSParams{ + HTTPClient: client, + } +} + +/* DescribeOSParams contains all the parameters to send to the API endpoint + for the describe o s operation. + + Typically these are written to a http.Request. +*/ +type DescribeOSParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // OsID. + OsID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeOSParams) WithDefaults() *DescribeOSParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeOSParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe o s params +func (o *DescribeOSParams) WithTimeout(timeout time.Duration) *DescribeOSParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe o s params +func (o *DescribeOSParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe o s params +func (o *DescribeOSParams) WithContext(ctx context.Context) *DescribeOSParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe o s params +func (o *DescribeOSParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe o s params +func (o *DescribeOSParams) WithHTTPClient(client *http.Client) *DescribeOSParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe o s params +func (o *DescribeOSParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe o s params +func (o *DescribeOSParams) WithAuthorization(authorization string) *DescribeOSParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe o s params +func (o *DescribeOSParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe o s params +func (o *DescribeOSParams) WithBmpLanguage(bmpLanguage *string) *DescribeOSParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe o s params +func (o *DescribeOSParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe o s params +func (o *DescribeOSParams) WithBmpUserID(bmpUserID *string) *DescribeOSParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe o s params +func (o *DescribeOSParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithOsID adds the osID to the describe o s params +func (o *DescribeOSParams) WithOsID(osID string) *DescribeOSParams { + o.SetOsID(osID) + return o +} + +// SetOsID adds the osId to the describe o s params +func (o *DescribeOSParams) SetOsID(osID string) { + o.OsID = osID +} + +// WithTraceID adds the traceID to the describe o s params +func (o *DescribeOSParams) WithTraceID(traceID string) *DescribeOSParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe o s params +func (o *DescribeOSParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeOSParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param os_id + if err := r.SetPathParam("os_id", o.OsID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/os/describe_o_s_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/os/describe_o_s_responses.go new file mode 100644 index 0000000..51bc548 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/os/describe_o_s_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeOSReader is a Reader for the DescribeOS structure. +type DescribeOSReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeOSReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeOSOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeOSDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeOSOK creates a DescribeOSOK with default headers values +func NewDescribeOSOK() *DescribeOSOK { + return &DescribeOSOK{} +} + +/* DescribeOSOK describes a response with status code 200, with default header values. + +A DescribeOsResult is an response struct that is used to describe os. +*/ +type DescribeOSOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeOSOKBody +} + +// IsSuccess returns true when this describe o s o k response has a 2xx status code +func (o *DescribeOSOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe o s o k response has a 3xx status code +func (o *DescribeOSOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe o s o k response has a 4xx status code +func (o *DescribeOSOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe o s o k response has a 5xx status code +func (o *DescribeOSOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe o s o k response a status code equal to that given +func (o *DescribeOSOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeOSOK) Error() string { + return fmt.Sprintf("[GET /oss/{os_id}][%d] describeOSOK %+v", 200, o.Payload) +} + +func (o *DescribeOSOK) String() string { + return fmt.Sprintf("[GET /oss/{os_id}][%d] describeOSOK %+v", 200, o.Payload) +} + +func (o *DescribeOSOK) GetPayload() *DescribeOSOKBody { + return o.Payload +} + +func (o *DescribeOSOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeOSOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeOSDefault creates a DescribeOSDefault with default headers values +func NewDescribeOSDefault(code int) *DescribeOSDefault { + return &DescribeOSDefault{ + _statusCode: code, + } +} + +/* DescribeOSDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeOSDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeOSDefaultBody +} + +// Code gets the status code for the describe o s default response +func (o *DescribeOSDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe o s default response has a 2xx status code +func (o *DescribeOSDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe o s default response has a 3xx status code +func (o *DescribeOSDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe o s default response has a 4xx status code +func (o *DescribeOSDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe o s default response has a 5xx status code +func (o *DescribeOSDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe o s default response a status code equal to that given +func (o *DescribeOSDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeOSDefault) Error() string { + return fmt.Sprintf("[GET /oss/{os_id}][%d] describeOS default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeOSDefault) String() string { + return fmt.Sprintf("[GET /oss/{os_id}][%d] describeOS default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeOSDefault) GetPayload() *DescribeOSDefaultBody { + return o.Payload +} + +func (o *DescribeOSDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeOSDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeOSDefaultBody describe o s default body +swagger:model DescribeOSDefaultBody +*/ +type DescribeOSDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe o s default body +func (o *DescribeOSDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeOS default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeOSDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeOS default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe o s default body based on the context it is used +func (o *DescribeOSDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeOSDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeOSDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeOSDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeOSOKBody describe o s o k body +swagger:model DescribeOSOKBody +*/ +type DescribeOSOKBody struct { + + // result + Result *models.OsInfo `json:"result,omitempty"` +} + +// Validate validates this describe o s o k body +func (o *DescribeOSOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe o s o k body based on the context it is used +func (o *DescribeOSOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeOSOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeOSOKBody) UnmarshalBinary(b []byte) error { + var res DescribeOSOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/os/describe_o_ss_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/os/describe_o_ss_parameters.go new file mode 100644 index 0000000..d009e8d --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/os/describe_o_ss_parameters.go @@ -0,0 +1,357 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeOSsParams creates a new DescribeOSsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeOSsParams() *DescribeOSsParams { + return &DescribeOSsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeOSsParamsWithTimeout creates a new DescribeOSsParams object +// with the ability to set a timeout on a request. +func NewDescribeOSsParamsWithTimeout(timeout time.Duration) *DescribeOSsParams { + return &DescribeOSsParams{ + timeout: timeout, + } +} + +// NewDescribeOSsParamsWithContext creates a new DescribeOSsParams object +// with the ability to set a context for a request. +func NewDescribeOSsParamsWithContext(ctx context.Context) *DescribeOSsParams { + return &DescribeOSsParams{ + Context: ctx, + } +} + +// NewDescribeOSsParamsWithHTTPClient creates a new DescribeOSsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeOSsParamsWithHTTPClient(client *http.Client) *DescribeOSsParams { + return &DescribeOSsParams{ + HTTPClient: client, + } +} + +/* DescribeOSsParams contains all the parameters to send to the API endpoint + for the describe o ss operation. + + Typically these are written to a http.Request. +*/ +type DescribeOSsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否显示所有 + */ + IsAll *string + + /* OsName. + + 操作系统名称 + */ + OsName *string + + /* OsType. + + 操作系统平台 + */ + OsType *string + + /* OsVersion. + + 操作系统版本 + */ + OsVersion *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe o ss params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeOSsParams) WithDefaults() *DescribeOSsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe o ss params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeOSsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe o ss params +func (o *DescribeOSsParams) WithTimeout(timeout time.Duration) *DescribeOSsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe o ss params +func (o *DescribeOSsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe o ss params +func (o *DescribeOSsParams) WithContext(ctx context.Context) *DescribeOSsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe o ss params +func (o *DescribeOSsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe o ss params +func (o *DescribeOSsParams) WithHTTPClient(client *http.Client) *DescribeOSsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe o ss params +func (o *DescribeOSsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe o ss params +func (o *DescribeOSsParams) WithAuthorization(authorization string) *DescribeOSsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe o ss params +func (o *DescribeOSsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe o ss params +func (o *DescribeOSsParams) WithBmpLanguage(bmpLanguage *string) *DescribeOSsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe o ss params +func (o *DescribeOSsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe o ss params +func (o *DescribeOSsParams) WithBmpUserID(bmpUserID *string) *DescribeOSsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe o ss params +func (o *DescribeOSsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe o ss params +func (o *DescribeOSsParams) WithIsAll(isAll *string) *DescribeOSsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe o ss params +func (o *DescribeOSsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithOsName adds the osName to the describe o ss params +func (o *DescribeOSsParams) WithOsName(osName *string) *DescribeOSsParams { + o.SetOsName(osName) + return o +} + +// SetOsName adds the osName to the describe o ss params +func (o *DescribeOSsParams) SetOsName(osName *string) { + o.OsName = osName +} + +// WithOsType adds the osType to the describe o ss params +func (o *DescribeOSsParams) WithOsType(osType *string) *DescribeOSsParams { + o.SetOsType(osType) + return o +} + +// SetOsType adds the osType to the describe o ss params +func (o *DescribeOSsParams) SetOsType(osType *string) { + o.OsType = osType +} + +// WithOsVersion adds the osVersion to the describe o ss params +func (o *DescribeOSsParams) WithOsVersion(osVersion *string) *DescribeOSsParams { + o.SetOsVersion(osVersion) + return o +} + +// SetOsVersion adds the osVersion to the describe o ss params +func (o *DescribeOSsParams) SetOsVersion(osVersion *string) { + o.OsVersion = osVersion +} + +// WithTraceID adds the traceID to the describe o ss params +func (o *DescribeOSsParams) WithTraceID(traceID string) *DescribeOSsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe o ss params +func (o *DescribeOSsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeOSsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.OsName != nil { + + // query param osName + var qrOsName string + + if o.OsName != nil { + qrOsName = *o.OsName + } + qOsName := qrOsName + if qOsName != "" { + + if err := r.SetQueryParam("osName", qOsName); err != nil { + return err + } + } + } + + if o.OsType != nil { + + // query param osType + var qrOsType string + + if o.OsType != nil { + qrOsType = *o.OsType + } + qOsType := qrOsType + if qOsType != "" { + + if err := r.SetQueryParam("osType", qOsType); err != nil { + return err + } + } + } + + if o.OsVersion != nil { + + // query param osVersion + var qrOsVersion string + + if o.OsVersion != nil { + qrOsVersion = *o.OsVersion + } + qOsVersion := qrOsVersion + if qOsVersion != "" { + + if err := r.SetQueryParam("osVersion", qOsVersion); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/os/describe_o_ss_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/os/describe_o_ss_responses.go new file mode 100644 index 0000000..cb0775b --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/os/describe_o_ss_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeOSsReader is a Reader for the DescribeOSs structure. +type DescribeOSsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeOSsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeOSsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeOSsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeOSsOK creates a DescribeOSsOK with default headers values +func NewDescribeOSsOK() *DescribeOSsOK { + return &DescribeOSsOK{} +} + +/* DescribeOSsOK describes a response with status code 200, with default header values. + +A DescribeOssResult is an response struct that is used to describe oss. +*/ +type DescribeOSsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeOSsOKBody +} + +// IsSuccess returns true when this describe o ss o k response has a 2xx status code +func (o *DescribeOSsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe o ss o k response has a 3xx status code +func (o *DescribeOSsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe o ss o k response has a 4xx status code +func (o *DescribeOSsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe o ss o k response has a 5xx status code +func (o *DescribeOSsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe o ss o k response a status code equal to that given +func (o *DescribeOSsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeOSsOK) Error() string { + return fmt.Sprintf("[GET /oss][%d] describeOSsOK %+v", 200, o.Payload) +} + +func (o *DescribeOSsOK) String() string { + return fmt.Sprintf("[GET /oss][%d] describeOSsOK %+v", 200, o.Payload) +} + +func (o *DescribeOSsOK) GetPayload() *DescribeOSsOKBody { + return o.Payload +} + +func (o *DescribeOSsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeOSsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeOSsDefault creates a DescribeOSsDefault with default headers values +func NewDescribeOSsDefault(code int) *DescribeOSsDefault { + return &DescribeOSsDefault{ + _statusCode: code, + } +} + +/* DescribeOSsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeOSsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeOSsDefaultBody +} + +// Code gets the status code for the describe o ss default response +func (o *DescribeOSsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe o ss default response has a 2xx status code +func (o *DescribeOSsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe o ss default response has a 3xx status code +func (o *DescribeOSsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe o ss default response has a 4xx status code +func (o *DescribeOSsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe o ss default response has a 5xx status code +func (o *DescribeOSsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe o ss default response a status code equal to that given +func (o *DescribeOSsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeOSsDefault) Error() string { + return fmt.Sprintf("[GET /oss][%d] describeOSs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeOSsDefault) String() string { + return fmt.Sprintf("[GET /oss][%d] describeOSs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeOSsDefault) GetPayload() *DescribeOSsDefaultBody { + return o.Payload +} + +func (o *DescribeOSsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeOSsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeOSsDefaultBody describe o ss default body +swagger:model DescribeOSsDefaultBody +*/ +type DescribeOSsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe o ss default body +func (o *DescribeOSsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeOSs default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeOSsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeOSs default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSs default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe o ss default body based on the context it is used +func (o *DescribeOSsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSs default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeOSsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeOSsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeOSsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeOSsOKBody describe o ss o k body +swagger:model DescribeOSsOKBody +*/ +type DescribeOSsOKBody struct { + + // result + Result *models.OsList `json:"result,omitempty"` +} + +// Validate validates this describe o ss o k body +func (o *DescribeOSsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe o ss o k body based on the context it is used +func (o *DescribeOSsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeOSsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeOSsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeOSsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/os/os_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/os/os_client.go new file mode 100644 index 0000000..8844046 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/os/os_client.go @@ -0,0 +1,117 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new os API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for os API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DescribeOS(params *DescribeOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeOSOK, error) + + DescribeOSs(params *DescribeOSsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeOSsOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DescribeOS DescribeOS 获取os系统详情(暂不启用) +*/ +func (a *Client) DescribeOS(params *DescribeOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeOSOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeOSParams() + } + op := &runtime.ClientOperation{ + ID: "describeOS", + Method: "GET", + PathPattern: "/oss/{os_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeOSReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeOSOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeOSDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeOSs DescribeOSs 获取os列表(暂不启用) +*/ +func (a *Client) DescribeOSs(params *DescribeOSsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeOSsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeOSsParams() + } + op := &runtime.ClientOperation{ + ID: "describeOSs", + Method: "GET", + PathPattern: "/oss", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeOSsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeOSsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeOSsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/cancel_share_user_project_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/cancel_share_user_project_parameters.go new file mode 100644 index 0000000..955c286 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/cancel_share_user_project_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewCancelShareUserProjectParams creates a new CancelShareUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCancelShareUserProjectParams() *CancelShareUserProjectParams { + return &CancelShareUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCancelShareUserProjectParamsWithTimeout creates a new CancelShareUserProjectParams object +// with the ability to set a timeout on a request. +func NewCancelShareUserProjectParamsWithTimeout(timeout time.Duration) *CancelShareUserProjectParams { + return &CancelShareUserProjectParams{ + timeout: timeout, + } +} + +// NewCancelShareUserProjectParamsWithContext creates a new CancelShareUserProjectParams object +// with the ability to set a context for a request. +func NewCancelShareUserProjectParamsWithContext(ctx context.Context) *CancelShareUserProjectParams { + return &CancelShareUserProjectParams{ + Context: ctx, + } +} + +// NewCancelShareUserProjectParamsWithHTTPClient creates a new CancelShareUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewCancelShareUserProjectParamsWithHTTPClient(client *http.Client) *CancelShareUserProjectParams { + return &CancelShareUserProjectParams{ + HTTPClient: client, + } +} + +/* CancelShareUserProjectParams contains all the parameters to send to the API endpoint + for the cancel share user project operation. + + Typically these are written to a http.Request. +*/ +type CancelShareUserProjectParams struct { + + // Body. + Body *models.CalcelShareProjectRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the cancel share user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CancelShareUserProjectParams) WithDefaults() *CancelShareUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the cancel share user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CancelShareUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the cancel share user project params +func (o *CancelShareUserProjectParams) WithTimeout(timeout time.Duration) *CancelShareUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the cancel share user project params +func (o *CancelShareUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the cancel share user project params +func (o *CancelShareUserProjectParams) WithContext(ctx context.Context) *CancelShareUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the cancel share user project params +func (o *CancelShareUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the cancel share user project params +func (o *CancelShareUserProjectParams) WithHTTPClient(client *http.Client) *CancelShareUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the cancel share user project params +func (o *CancelShareUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the cancel share user project params +func (o *CancelShareUserProjectParams) WithBody(body *models.CalcelShareProjectRequest) *CancelShareUserProjectParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the cancel share user project params +func (o *CancelShareUserProjectParams) SetBody(body *models.CalcelShareProjectRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the cancel share user project params +func (o *CancelShareUserProjectParams) WithAuthorization(authorization string) *CancelShareUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the cancel share user project params +func (o *CancelShareUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the cancel share user project params +func (o *CancelShareUserProjectParams) WithBmpLanguage(bmpLanguage *string) *CancelShareUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the cancel share user project params +func (o *CancelShareUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the cancel share user project params +func (o *CancelShareUserProjectParams) WithBmpUserID(bmpUserID *string) *CancelShareUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the cancel share user project params +func (o *CancelShareUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the cancel share user project params +func (o *CancelShareUserProjectParams) WithProjectID(projectID string) *CancelShareUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the cancel share user project params +func (o *CancelShareUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the cancel share user project params +func (o *CancelShareUserProjectParams) WithTraceID(traceID string) *CancelShareUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the cancel share user project params +func (o *CancelShareUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CancelShareUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/cancel_share_user_project_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/cancel_share_user_project_responses.go new file mode 100644 index 0000000..c705147 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/cancel_share_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// CancelShareUserProjectReader is a Reader for the CancelShareUserProject structure. +type CancelShareUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CancelShareUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCancelShareUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCancelShareUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCancelShareUserProjectOK creates a CancelShareUserProjectOK with default headers values +func NewCancelShareUserProjectOK() *CancelShareUserProjectOK { + return &CancelShareUserProjectOK{} +} + +/* CancelShareUserProjectOK describes a response with status code 200, with default header values. + +A CancelShareUserProjectResult is an response struct +*/ +type CancelShareUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CancelShareUserProjectOKBody +} + +// IsSuccess returns true when this cancel share user project o k response has a 2xx status code +func (o *CancelShareUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this cancel share user project o k response has a 3xx status code +func (o *CancelShareUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this cancel share user project o k response has a 4xx status code +func (o *CancelShareUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this cancel share user project o k response has a 5xx status code +func (o *CancelShareUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this cancel share user project o k response a status code equal to that given +func (o *CancelShareUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CancelShareUserProjectOK) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/cancelShare][%d] cancelShareUserProjectOK %+v", 200, o.Payload) +} + +func (o *CancelShareUserProjectOK) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/cancelShare][%d] cancelShareUserProjectOK %+v", 200, o.Payload) +} + +func (o *CancelShareUserProjectOK) GetPayload() *CancelShareUserProjectOKBody { + return o.Payload +} + +func (o *CancelShareUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CancelShareUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCancelShareUserProjectDefault creates a CancelShareUserProjectDefault with default headers values +func NewCancelShareUserProjectDefault(code int) *CancelShareUserProjectDefault { + return &CancelShareUserProjectDefault{ + _statusCode: code, + } +} + +/* CancelShareUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CancelShareUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CancelShareUserProjectDefaultBody +} + +// Code gets the status code for the cancel share user project default response +func (o *CancelShareUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this cancel share user project default response has a 2xx status code +func (o *CancelShareUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this cancel share user project default response has a 3xx status code +func (o *CancelShareUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this cancel share user project default response has a 4xx status code +func (o *CancelShareUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this cancel share user project default response has a 5xx status code +func (o *CancelShareUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this cancel share user project default response a status code equal to that given +func (o *CancelShareUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CancelShareUserProjectDefault) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/cancelShare][%d] cancelShareUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *CancelShareUserProjectDefault) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/cancelShare][%d] cancelShareUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *CancelShareUserProjectDefault) GetPayload() *CancelShareUserProjectDefaultBody { + return o.Payload +} + +func (o *CancelShareUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CancelShareUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CancelShareUserProjectDefaultBody cancel share user project default body +swagger:model CancelShareUserProjectDefaultBody +*/ +type CancelShareUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this cancel share user project default body +func (o *CancelShareUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CancelShareUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("cancelShareUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CancelShareUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("cancelShareUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cancelShareUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cancelShareUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this cancel share user project default body based on the context it is used +func (o *CancelShareUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CancelShareUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cancelShareUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cancelShareUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CancelShareUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CancelShareUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res CancelShareUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CancelShareUserProjectOKBody cancel share user project o k body +swagger:model CancelShareUserProjectOKBody +*/ +type CancelShareUserProjectOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this cancel share user project o k body +func (o *CancelShareUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CancelShareUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cancelShareUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cancelShareUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this cancel share user project o k body based on the context it is used +func (o *CancelShareUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CancelShareUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cancelShareUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cancelShareUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CancelShareUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CancelShareUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res CancelShareUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/create_user_project_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/create_user_project_parameters.go new file mode 100644 index 0000000..25b4494 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/create_user_project_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewCreateUserProjectParams creates a new CreateUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateUserProjectParams() *CreateUserProjectParams { + return &CreateUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateUserProjectParamsWithTimeout creates a new CreateUserProjectParams object +// with the ability to set a timeout on a request. +func NewCreateUserProjectParamsWithTimeout(timeout time.Duration) *CreateUserProjectParams { + return &CreateUserProjectParams{ + timeout: timeout, + } +} + +// NewCreateUserProjectParamsWithContext creates a new CreateUserProjectParams object +// with the ability to set a context for a request. +func NewCreateUserProjectParamsWithContext(ctx context.Context) *CreateUserProjectParams { + return &CreateUserProjectParams{ + Context: ctx, + } +} + +// NewCreateUserProjectParamsWithHTTPClient creates a new CreateUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateUserProjectParamsWithHTTPClient(client *http.Client) *CreateUserProjectParams { + return &CreateUserProjectParams{ + HTTPClient: client, + } +} + +/* CreateUserProjectParams contains all the parameters to send to the API endpoint + for the create user project operation. + + Typically these are written to a http.Request. +*/ +type CreateUserProjectParams struct { + + // Body. + Body *models.CreateProjectRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserProjectParams) WithDefaults() *CreateUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create user project params +func (o *CreateUserProjectParams) WithTimeout(timeout time.Duration) *CreateUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create user project params +func (o *CreateUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create user project params +func (o *CreateUserProjectParams) WithContext(ctx context.Context) *CreateUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create user project params +func (o *CreateUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create user project params +func (o *CreateUserProjectParams) WithHTTPClient(client *http.Client) *CreateUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create user project params +func (o *CreateUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create user project params +func (o *CreateUserProjectParams) WithBody(body *models.CreateProjectRequest) *CreateUserProjectParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create user project params +func (o *CreateUserProjectParams) SetBody(body *models.CreateProjectRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create user project params +func (o *CreateUserProjectParams) WithAuthorization(authorization string) *CreateUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create user project params +func (o *CreateUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create user project params +func (o *CreateUserProjectParams) WithBmpLanguage(bmpLanguage *string) *CreateUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create user project params +func (o *CreateUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create user project params +func (o *CreateUserProjectParams) WithBmpUserID(bmpUserID *string) *CreateUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create user project params +func (o *CreateUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create user project params +func (o *CreateUserProjectParams) WithTraceID(traceID string) *CreateUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create user project params +func (o *CreateUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/create_user_project_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/create_user_project_responses.go new file mode 100644 index 0000000..8728b94 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/create_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// CreateUserProjectReader is a Reader for the CreateUserProject structure. +type CreateUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateUserProjectOK creates a CreateUserProjectOK with default headers values +func NewCreateUserProjectOK() *CreateUserProjectOK { + return &CreateUserProjectOK{} +} + +/* CreateUserProjectOK describes a response with status code 200, with default header values. + +CreateUserProjectOK create user project o k +*/ +type CreateUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserProjectOKBody +} + +// IsSuccess returns true when this create user project o k response has a 2xx status code +func (o *CreateUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create user project o k response has a 3xx status code +func (o *CreateUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create user project o k response has a 4xx status code +func (o *CreateUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create user project o k response has a 5xx status code +func (o *CreateUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create user project o k response a status code equal to that given +func (o *CreateUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateUserProjectOK) Error() string { + return fmt.Sprintf("[POST /user/projects][%d] createUserProjectOK %+v", 200, o.Payload) +} + +func (o *CreateUserProjectOK) String() string { + return fmt.Sprintf("[POST /user/projects][%d] createUserProjectOK %+v", 200, o.Payload) +} + +func (o *CreateUserProjectOK) GetPayload() *CreateUserProjectOKBody { + return o.Payload +} + +func (o *CreateUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateUserProjectDefault creates a CreateUserProjectDefault with default headers values +func NewCreateUserProjectDefault(code int) *CreateUserProjectDefault { + return &CreateUserProjectDefault{ + _statusCode: code, + } +} + +/* CreateUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserProjectDefaultBody +} + +// Code gets the status code for the create user project default response +func (o *CreateUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create user project default response has a 2xx status code +func (o *CreateUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create user project default response has a 3xx status code +func (o *CreateUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create user project default response has a 4xx status code +func (o *CreateUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create user project default response has a 5xx status code +func (o *CreateUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create user project default response a status code equal to that given +func (o *CreateUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateUserProjectDefault) Error() string { + return fmt.Sprintf("[POST /user/projects][%d] createUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserProjectDefault) String() string { + return fmt.Sprintf("[POST /user/projects][%d] createUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserProjectDefault) GetPayload() *CreateUserProjectDefaultBody { + return o.Payload +} + +func (o *CreateUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateUserProjectDefaultBody create user project default body +swagger:model CreateUserProjectDefaultBody +*/ +type CreateUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create user project default body +func (o *CreateUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user project default body based on the context it is used +func (o *CreateUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateUserProjectOKBody create user project o k body +swagger:model CreateUserProjectOKBody +*/ +type CreateUserProjectOKBody struct { + + // result + Result *models.ProjectID `json:"result,omitempty"` +} + +// Validate validates this create user project o k body +func (o *CreateUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user project o k body based on the context it is used +func (o *CreateUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res CreateUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/delete_user_project_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/delete_user_project_parameters.go new file mode 100644 index 0000000..161bf7f --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/delete_user_project_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteUserProjectParams creates a new DeleteUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteUserProjectParams() *DeleteUserProjectParams { + return &DeleteUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteUserProjectParamsWithTimeout creates a new DeleteUserProjectParams object +// with the ability to set a timeout on a request. +func NewDeleteUserProjectParamsWithTimeout(timeout time.Duration) *DeleteUserProjectParams { + return &DeleteUserProjectParams{ + timeout: timeout, + } +} + +// NewDeleteUserProjectParamsWithContext creates a new DeleteUserProjectParams object +// with the ability to set a context for a request. +func NewDeleteUserProjectParamsWithContext(ctx context.Context) *DeleteUserProjectParams { + return &DeleteUserProjectParams{ + Context: ctx, + } +} + +// NewDeleteUserProjectParamsWithHTTPClient creates a new DeleteUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteUserProjectParamsWithHTTPClient(client *http.Client) *DeleteUserProjectParams { + return &DeleteUserProjectParams{ + HTTPClient: client, + } +} + +/* DeleteUserProjectParams contains all the parameters to send to the API endpoint + for the delete user project operation. + + Typically these are written to a http.Request. +*/ +type DeleteUserProjectParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserProjectParams) WithDefaults() *DeleteUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete user project params +func (o *DeleteUserProjectParams) WithTimeout(timeout time.Duration) *DeleteUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete user project params +func (o *DeleteUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete user project params +func (o *DeleteUserProjectParams) WithContext(ctx context.Context) *DeleteUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete user project params +func (o *DeleteUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete user project params +func (o *DeleteUserProjectParams) WithHTTPClient(client *http.Client) *DeleteUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete user project params +func (o *DeleteUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete user project params +func (o *DeleteUserProjectParams) WithAuthorization(authorization string) *DeleteUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete user project params +func (o *DeleteUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete user project params +func (o *DeleteUserProjectParams) WithBmpLanguage(bmpLanguage *string) *DeleteUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete user project params +func (o *DeleteUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete user project params +func (o *DeleteUserProjectParams) WithBmpUserID(bmpUserID *string) *DeleteUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete user project params +func (o *DeleteUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the delete user project params +func (o *DeleteUserProjectParams) WithProjectID(projectID string) *DeleteUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the delete user project params +func (o *DeleteUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the delete user project params +func (o *DeleteUserProjectParams) WithTraceID(traceID string) *DeleteUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete user project params +func (o *DeleteUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/delete_user_project_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/delete_user_project_responses.go new file mode 100644 index 0000000..bd54f45 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/delete_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DeleteUserProjectReader is a Reader for the DeleteUserProject structure. +type DeleteUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteUserProjectOK creates a DeleteUserProjectOK with default headers values +func NewDeleteUserProjectOK() *DeleteUserProjectOK { + return &DeleteUserProjectOK{} +} + +/* DeleteUserProjectOK describes a response with status code 200, with default header values. + +DeleteUserProjectOK delete user project o k +*/ +type DeleteUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserProjectOKBody +} + +// IsSuccess returns true when this delete user project o k response has a 2xx status code +func (o *DeleteUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete user project o k response has a 3xx status code +func (o *DeleteUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete user project o k response has a 4xx status code +func (o *DeleteUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete user project o k response has a 5xx status code +func (o *DeleteUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete user project o k response a status code equal to that given +func (o *DeleteUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteUserProjectOK) Error() string { + return fmt.Sprintf("[DELETE /user/projects/{project_id}][%d] deleteUserProjectOK %+v", 200, o.Payload) +} + +func (o *DeleteUserProjectOK) String() string { + return fmt.Sprintf("[DELETE /user/projects/{project_id}][%d] deleteUserProjectOK %+v", 200, o.Payload) +} + +func (o *DeleteUserProjectOK) GetPayload() *DeleteUserProjectOKBody { + return o.Payload +} + +func (o *DeleteUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteUserProjectDefault creates a DeleteUserProjectDefault with default headers values +func NewDeleteUserProjectDefault(code int) *DeleteUserProjectDefault { + return &DeleteUserProjectDefault{ + _statusCode: code, + } +} + +/* DeleteUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserProjectDefaultBody +} + +// Code gets the status code for the delete user project default response +func (o *DeleteUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete user project default response has a 2xx status code +func (o *DeleteUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete user project default response has a 3xx status code +func (o *DeleteUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete user project default response has a 4xx status code +func (o *DeleteUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete user project default response has a 5xx status code +func (o *DeleteUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete user project default response a status code equal to that given +func (o *DeleteUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteUserProjectDefault) Error() string { + return fmt.Sprintf("[DELETE /user/projects/{project_id}][%d] deleteUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserProjectDefault) String() string { + return fmt.Sprintf("[DELETE /user/projects/{project_id}][%d] deleteUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserProjectDefault) GetPayload() *DeleteUserProjectDefaultBody { + return o.Payload +} + +func (o *DeleteUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteUserProjectDefaultBody delete user project default body +swagger:model DeleteUserProjectDefaultBody +*/ +type DeleteUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete user project default body +func (o *DeleteUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user project default body based on the context it is used +func (o *DeleteUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteUserProjectOKBody delete user project o k body +swagger:model DeleteUserProjectOKBody +*/ +type DeleteUserProjectOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete user project o k body +func (o *DeleteUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user project o k body based on the context it is used +func (o *DeleteUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res DeleteUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_share_project_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_share_project_parameters.go new file mode 100644 index 0000000..54c074e --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_share_project_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeShareProjectParams creates a new DescribeShareProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeShareProjectParams() *DescribeShareProjectParams { + return &DescribeShareProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeShareProjectParamsWithTimeout creates a new DescribeShareProjectParams object +// with the ability to set a timeout on a request. +func NewDescribeShareProjectParamsWithTimeout(timeout time.Duration) *DescribeShareProjectParams { + return &DescribeShareProjectParams{ + timeout: timeout, + } +} + +// NewDescribeShareProjectParamsWithContext creates a new DescribeShareProjectParams object +// with the ability to set a context for a request. +func NewDescribeShareProjectParamsWithContext(ctx context.Context) *DescribeShareProjectParams { + return &DescribeShareProjectParams{ + Context: ctx, + } +} + +// NewDescribeShareProjectParamsWithHTTPClient creates a new DescribeShareProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeShareProjectParamsWithHTTPClient(client *http.Client) *DescribeShareProjectParams { + return &DescribeShareProjectParams{ + HTTPClient: client, + } +} + +/* DescribeShareProjectParams contains all the parameters to send to the API endpoint + for the describe share project operation. + + Typically these are written to a http.Request. +*/ +type DescribeShareProjectParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe share project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeShareProjectParams) WithDefaults() *DescribeShareProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe share project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeShareProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe share project params +func (o *DescribeShareProjectParams) WithTimeout(timeout time.Duration) *DescribeShareProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe share project params +func (o *DescribeShareProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe share project params +func (o *DescribeShareProjectParams) WithContext(ctx context.Context) *DescribeShareProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe share project params +func (o *DescribeShareProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe share project params +func (o *DescribeShareProjectParams) WithHTTPClient(client *http.Client) *DescribeShareProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe share project params +func (o *DescribeShareProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe share project params +func (o *DescribeShareProjectParams) WithAuthorization(authorization string) *DescribeShareProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe share project params +func (o *DescribeShareProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe share project params +func (o *DescribeShareProjectParams) WithBmpLanguage(bmpLanguage *string) *DescribeShareProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe share project params +func (o *DescribeShareProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe share project params +func (o *DescribeShareProjectParams) WithBmpUserID(bmpUserID *string) *DescribeShareProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe share project params +func (o *DescribeShareProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the describe share project params +func (o *DescribeShareProjectParams) WithProjectID(projectID string) *DescribeShareProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the describe share project params +func (o *DescribeShareProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the describe share project params +func (o *DescribeShareProjectParams) WithTraceID(traceID string) *DescribeShareProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe share project params +func (o *DescribeShareProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeShareProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_share_project_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_share_project_responses.go new file mode 100644 index 0000000..7cf8ee4 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_share_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeShareProjectReader is a Reader for the DescribeShareProject structure. +type DescribeShareProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeShareProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeShareProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeShareProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeShareProjectOK creates a DescribeShareProjectOK with default headers values +func NewDescribeShareProjectOK() *DescribeShareProjectOK { + return &DescribeShareProjectOK{} +} + +/* DescribeShareProjectOK describes a response with status code 200, with default header values. + +A DescribeShareProjectResult is an response struct that is used to describe getapikey. +*/ +type DescribeShareProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeShareProjectOKBody +} + +// IsSuccess returns true when this describe share project o k response has a 2xx status code +func (o *DescribeShareProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe share project o k response has a 3xx status code +func (o *DescribeShareProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe share project o k response has a 4xx status code +func (o *DescribeShareProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe share project o k response has a 5xx status code +func (o *DescribeShareProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe share project o k response a status code equal to that given +func (o *DescribeShareProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeShareProjectOK) Error() string { + return fmt.Sprintf("[GET /user/projects/{project_id}/describeSharProject][%d] describeShareProjectOK %+v", 200, o.Payload) +} + +func (o *DescribeShareProjectOK) String() string { + return fmt.Sprintf("[GET /user/projects/{project_id}/describeSharProject][%d] describeShareProjectOK %+v", 200, o.Payload) +} + +func (o *DescribeShareProjectOK) GetPayload() *DescribeShareProjectOKBody { + return o.Payload +} + +func (o *DescribeShareProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeShareProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeShareProjectDefault creates a DescribeShareProjectDefault with default headers values +func NewDescribeShareProjectDefault(code int) *DescribeShareProjectDefault { + return &DescribeShareProjectDefault{ + _statusCode: code, + } +} + +/* DescribeShareProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeShareProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeShareProjectDefaultBody +} + +// Code gets the status code for the describe share project default response +func (o *DescribeShareProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe share project default response has a 2xx status code +func (o *DescribeShareProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe share project default response has a 3xx status code +func (o *DescribeShareProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe share project default response has a 4xx status code +func (o *DescribeShareProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe share project default response has a 5xx status code +func (o *DescribeShareProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe share project default response a status code equal to that given +func (o *DescribeShareProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeShareProjectDefault) Error() string { + return fmt.Sprintf("[GET /user/projects/{project_id}/describeSharProject][%d] describeShareProject default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeShareProjectDefault) String() string { + return fmt.Sprintf("[GET /user/projects/{project_id}/describeSharProject][%d] describeShareProject default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeShareProjectDefault) GetPayload() *DescribeShareProjectDefaultBody { + return o.Payload +} + +func (o *DescribeShareProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeShareProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeShareProjectDefaultBody describe share project default body +swagger:model DescribeShareProjectDefaultBody +*/ +type DescribeShareProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe share project default body +func (o *DescribeShareProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeShareProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeShareProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeShareProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeShareProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeShareProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeShareProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe share project default body based on the context it is used +func (o *DescribeShareProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeShareProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeShareProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeShareProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeShareProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeShareProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeShareProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeShareProjectOKBody describe share project o k body +swagger:model DescribeShareProjectOKBody +*/ +type DescribeShareProjectOKBody struct { + + // result + Result *models.ShareProjectInfo `json:"result,omitempty"` +} + +// Validate validates this describe share project o k body +func (o *DescribeShareProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeShareProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeShareProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeShareProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe share project o k body based on the context it is used +func (o *DescribeShareProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeShareProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeShareProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeShareProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeShareProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeShareProjectOKBody) UnmarshalBinary(b []byte) error { + var res DescribeShareProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_user_project_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_user_project_parameters.go new file mode 100644 index 0000000..3610ef7 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_user_project_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeUserProjectParams creates a new DescribeUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserProjectParams() *DescribeUserProjectParams { + return &DescribeUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserProjectParamsWithTimeout creates a new DescribeUserProjectParams object +// with the ability to set a timeout on a request. +func NewDescribeUserProjectParamsWithTimeout(timeout time.Duration) *DescribeUserProjectParams { + return &DescribeUserProjectParams{ + timeout: timeout, + } +} + +// NewDescribeUserProjectParamsWithContext creates a new DescribeUserProjectParams object +// with the ability to set a context for a request. +func NewDescribeUserProjectParamsWithContext(ctx context.Context) *DescribeUserProjectParams { + return &DescribeUserProjectParams{ + Context: ctx, + } +} + +// NewDescribeUserProjectParamsWithHTTPClient creates a new DescribeUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserProjectParamsWithHTTPClient(client *http.Client) *DescribeUserProjectParams { + return &DescribeUserProjectParams{ + HTTPClient: client, + } +} + +/* DescribeUserProjectParams contains all the parameters to send to the API endpoint + for the describe user project operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserProjectParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserProjectParams) WithDefaults() *DescribeUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user project params +func (o *DescribeUserProjectParams) WithTimeout(timeout time.Duration) *DescribeUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user project params +func (o *DescribeUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user project params +func (o *DescribeUserProjectParams) WithContext(ctx context.Context) *DescribeUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user project params +func (o *DescribeUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user project params +func (o *DescribeUserProjectParams) WithHTTPClient(client *http.Client) *DescribeUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user project params +func (o *DescribeUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user project params +func (o *DescribeUserProjectParams) WithAuthorization(authorization string) *DescribeUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user project params +func (o *DescribeUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user project params +func (o *DescribeUserProjectParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user project params +func (o *DescribeUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user project params +func (o *DescribeUserProjectParams) WithBmpUserID(bmpUserID *string) *DescribeUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user project params +func (o *DescribeUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the describe user project params +func (o *DescribeUserProjectParams) WithProjectID(projectID string) *DescribeUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the describe user project params +func (o *DescribeUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the describe user project params +func (o *DescribeUserProjectParams) WithTraceID(traceID string) *DescribeUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user project params +func (o *DescribeUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_user_project_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_user_project_responses.go new file mode 100644 index 0000000..9215e11 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeUserProjectReader is a Reader for the DescribeUserProject structure. +type DescribeUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserProjectOK creates a DescribeUserProjectOK with default headers values +func NewDescribeUserProjectOK() *DescribeUserProjectOK { + return &DescribeUserProjectOK{} +} + +/* DescribeUserProjectOK describes a response with status code 200, with default header values. + +DescribeUserProjectOK describe user project o k +*/ +type DescribeUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserProjectOKBody +} + +// IsSuccess returns true when this describe user project o k response has a 2xx status code +func (o *DescribeUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user project o k response has a 3xx status code +func (o *DescribeUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user project o k response has a 4xx status code +func (o *DescribeUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user project o k response has a 5xx status code +func (o *DescribeUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user project o k response a status code equal to that given +func (o *DescribeUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserProjectOK) Error() string { + return fmt.Sprintf("[GET /user/projects/{project_id}][%d] describeUserProjectOK %+v", 200, o.Payload) +} + +func (o *DescribeUserProjectOK) String() string { + return fmt.Sprintf("[GET /user/projects/{project_id}][%d] describeUserProjectOK %+v", 200, o.Payload) +} + +func (o *DescribeUserProjectOK) GetPayload() *DescribeUserProjectOKBody { + return o.Payload +} + +func (o *DescribeUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserProjectDefault creates a DescribeUserProjectDefault with default headers values +func NewDescribeUserProjectDefault(code int) *DescribeUserProjectDefault { + return &DescribeUserProjectDefault{ + _statusCode: code, + } +} + +/* DescribeUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserProjectDefaultBody +} + +// Code gets the status code for the describe user project default response +func (o *DescribeUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user project default response has a 2xx status code +func (o *DescribeUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user project default response has a 3xx status code +func (o *DescribeUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user project default response has a 4xx status code +func (o *DescribeUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user project default response has a 5xx status code +func (o *DescribeUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user project default response a status code equal to that given +func (o *DescribeUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserProjectDefault) Error() string { + return fmt.Sprintf("[GET /user/projects/{project_id}][%d] describeUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserProjectDefault) String() string { + return fmt.Sprintf("[GET /user/projects/{project_id}][%d] describeUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserProjectDefault) GetPayload() *DescribeUserProjectDefaultBody { + return o.Payload +} + +func (o *DescribeUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserProjectDefaultBody describe user project default body +swagger:model DescribeUserProjectDefaultBody +*/ +type DescribeUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user project default body +func (o *DescribeUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user project default body based on the context it is used +func (o *DescribeUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserProjectOKBody describe user project o k body +swagger:model DescribeUserProjectOKBody +*/ +type DescribeUserProjectOKBody struct { + + // result + Result *models.ProjectInfo `json:"result,omitempty"` +} + +// Validate validates this describe user project o k body +func (o *DescribeUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user project o k body based on the context it is used +func (o *DescribeUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_user_projects_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_user_projects_parameters.go new file mode 100644 index 0000000..0f0747a --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_user_projects_parameters.go @@ -0,0 +1,497 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeUserProjectsParams creates a new DescribeUserProjectsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserProjectsParams() *DescribeUserProjectsParams { + return &DescribeUserProjectsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserProjectsParamsWithTimeout creates a new DescribeUserProjectsParams object +// with the ability to set a timeout on a request. +func NewDescribeUserProjectsParamsWithTimeout(timeout time.Duration) *DescribeUserProjectsParams { + return &DescribeUserProjectsParams{ + timeout: timeout, + } +} + +// NewDescribeUserProjectsParamsWithContext creates a new DescribeUserProjectsParams object +// with the ability to set a context for a request. +func NewDescribeUserProjectsParamsWithContext(ctx context.Context) *DescribeUserProjectsParams { + return &DescribeUserProjectsParams{ + Context: ctx, + } +} + +// NewDescribeUserProjectsParamsWithHTTPClient creates a new DescribeUserProjectsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserProjectsParamsWithHTTPClient(client *http.Client) *DescribeUserProjectsParams { + return &DescribeUserProjectsParams{ + HTTPClient: client, + } +} + +/* DescribeUserProjectsParams contains all the parameters to send to the API endpoint + for the describe user projects operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserProjectsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // IsAll. + IsAll *string + + /* OrderByCreatetime. + + 按创建时间asc/desc排列 + */ + OrderByCreatetime *string + + /* Owned. + + 0表示全部,1表示拥有者,2表示被共享者 + + Format: int64 + */ + Owned *int64 + + /* OwnerName. + + 新增可选,按用户名查找 + */ + OwnerName *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* ProjectName. + + 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + */ + ProjectName *string + + /* SharerName. + + 新增可选,按被转移用户的用户名查找它拥有的项目 + */ + SharerName *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user projects params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserProjectsParams) WithDefaults() *DescribeUserProjectsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user projects params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserProjectsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user projects params +func (o *DescribeUserProjectsParams) WithTimeout(timeout time.Duration) *DescribeUserProjectsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user projects params +func (o *DescribeUserProjectsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user projects params +func (o *DescribeUserProjectsParams) WithContext(ctx context.Context) *DescribeUserProjectsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user projects params +func (o *DescribeUserProjectsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user projects params +func (o *DescribeUserProjectsParams) WithHTTPClient(client *http.Client) *DescribeUserProjectsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user projects params +func (o *DescribeUserProjectsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user projects params +func (o *DescribeUserProjectsParams) WithAuthorization(authorization string) *DescribeUserProjectsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user projects params +func (o *DescribeUserProjectsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user projects params +func (o *DescribeUserProjectsParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserProjectsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user projects params +func (o *DescribeUserProjectsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user projects params +func (o *DescribeUserProjectsParams) WithBmpUserID(bmpUserID *string) *DescribeUserProjectsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user projects params +func (o *DescribeUserProjectsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe user projects params +func (o *DescribeUserProjectsParams) WithIsAll(isAll *string) *DescribeUserProjectsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe user projects params +func (o *DescribeUserProjectsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithOrderByCreatetime adds the orderByCreatetime to the describe user projects params +func (o *DescribeUserProjectsParams) WithOrderByCreatetime(orderByCreatetime *string) *DescribeUserProjectsParams { + o.SetOrderByCreatetime(orderByCreatetime) + return o +} + +// SetOrderByCreatetime adds the orderByCreatetime to the describe user projects params +func (o *DescribeUserProjectsParams) SetOrderByCreatetime(orderByCreatetime *string) { + o.OrderByCreatetime = orderByCreatetime +} + +// WithOwned adds the owned to the describe user projects params +func (o *DescribeUserProjectsParams) WithOwned(owned *int64) *DescribeUserProjectsParams { + o.SetOwned(owned) + return o +} + +// SetOwned adds the owned to the describe user projects params +func (o *DescribeUserProjectsParams) SetOwned(owned *int64) { + o.Owned = owned +} + +// WithOwnerName adds the ownerName to the describe user projects params +func (o *DescribeUserProjectsParams) WithOwnerName(ownerName *string) *DescribeUserProjectsParams { + o.SetOwnerName(ownerName) + return o +} + +// SetOwnerName adds the ownerName to the describe user projects params +func (o *DescribeUserProjectsParams) SetOwnerName(ownerName *string) { + o.OwnerName = ownerName +} + +// WithPageNumber adds the pageNumber to the describe user projects params +func (o *DescribeUserProjectsParams) WithPageNumber(pageNumber *int64) *DescribeUserProjectsParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe user projects params +func (o *DescribeUserProjectsParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe user projects params +func (o *DescribeUserProjectsParams) WithPageSize(pageSize *int64) *DescribeUserProjectsParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe user projects params +func (o *DescribeUserProjectsParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithProjectName adds the projectName to the describe user projects params +func (o *DescribeUserProjectsParams) WithProjectName(projectName *string) *DescribeUserProjectsParams { + o.SetProjectName(projectName) + return o +} + +// SetProjectName adds the projectName to the describe user projects params +func (o *DescribeUserProjectsParams) SetProjectName(projectName *string) { + o.ProjectName = projectName +} + +// WithSharerName adds the sharerName to the describe user projects params +func (o *DescribeUserProjectsParams) WithSharerName(sharerName *string) *DescribeUserProjectsParams { + o.SetSharerName(sharerName) + return o +} + +// SetSharerName adds the sharerName to the describe user projects params +func (o *DescribeUserProjectsParams) SetSharerName(sharerName *string) { + o.SharerName = sharerName +} + +// WithTraceID adds the traceID to the describe user projects params +func (o *DescribeUserProjectsParams) WithTraceID(traceID string) *DescribeUserProjectsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user projects params +func (o *DescribeUserProjectsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserProjectsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.OrderByCreatetime != nil { + + // query param orderByCreatetime + var qrOrderByCreatetime string + + if o.OrderByCreatetime != nil { + qrOrderByCreatetime = *o.OrderByCreatetime + } + qOrderByCreatetime := qrOrderByCreatetime + if qOrderByCreatetime != "" { + + if err := r.SetQueryParam("orderByCreatetime", qOrderByCreatetime); err != nil { + return err + } + } + } + + if o.Owned != nil { + + // query param owned + var qrOwned int64 + + if o.Owned != nil { + qrOwned = *o.Owned + } + qOwned := swag.FormatInt64(qrOwned) + if qOwned != "" { + + if err := r.SetQueryParam("owned", qOwned); err != nil { + return err + } + } + } + + if o.OwnerName != nil { + + // query param ownerName + var qrOwnerName string + + if o.OwnerName != nil { + qrOwnerName = *o.OwnerName + } + qOwnerName := qrOwnerName + if qOwnerName != "" { + + if err := r.SetQueryParam("ownerName", qOwnerName); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.ProjectName != nil { + + // query param projectName + var qrProjectName string + + if o.ProjectName != nil { + qrProjectName = *o.ProjectName + } + qProjectName := qrProjectName + if qProjectName != "" { + + if err := r.SetQueryParam("projectName", qProjectName); err != nil { + return err + } + } + } + + if o.SharerName != nil { + + // query param sharerName + var qrSharerName string + + if o.SharerName != nil { + qrSharerName = *o.SharerName + } + qSharerName := qrSharerName + if qSharerName != "" { + + if err := r.SetQueryParam("sharerName", qSharerName); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_user_projects_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_user_projects_responses.go new file mode 100644 index 0000000..b4a757e --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/describe_user_projects_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeUserProjectsReader is a Reader for the DescribeUserProjects structure. +type DescribeUserProjectsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserProjectsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserProjectsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserProjectsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserProjectsOK creates a DescribeUserProjectsOK with default headers values +func NewDescribeUserProjectsOK() *DescribeUserProjectsOK { + return &DescribeUserProjectsOK{} +} + +/* DescribeUserProjectsOK describes a response with status code 200, with default header values. + +DescribeUserProjectsOK describe user projects o k +*/ +type DescribeUserProjectsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserProjectsOKBody +} + +// IsSuccess returns true when this describe user projects o k response has a 2xx status code +func (o *DescribeUserProjectsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user projects o k response has a 3xx status code +func (o *DescribeUserProjectsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user projects o k response has a 4xx status code +func (o *DescribeUserProjectsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user projects o k response has a 5xx status code +func (o *DescribeUserProjectsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user projects o k response a status code equal to that given +func (o *DescribeUserProjectsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserProjectsOK) Error() string { + return fmt.Sprintf("[GET /user/projects][%d] describeUserProjectsOK %+v", 200, o.Payload) +} + +func (o *DescribeUserProjectsOK) String() string { + return fmt.Sprintf("[GET /user/projects][%d] describeUserProjectsOK %+v", 200, o.Payload) +} + +func (o *DescribeUserProjectsOK) GetPayload() *DescribeUserProjectsOKBody { + return o.Payload +} + +func (o *DescribeUserProjectsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserProjectsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserProjectsDefault creates a DescribeUserProjectsDefault with default headers values +func NewDescribeUserProjectsDefault(code int) *DescribeUserProjectsDefault { + return &DescribeUserProjectsDefault{ + _statusCode: code, + } +} + +/* DescribeUserProjectsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserProjectsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserProjectsDefaultBody +} + +// Code gets the status code for the describe user projects default response +func (o *DescribeUserProjectsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user projects default response has a 2xx status code +func (o *DescribeUserProjectsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user projects default response has a 3xx status code +func (o *DescribeUserProjectsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user projects default response has a 4xx status code +func (o *DescribeUserProjectsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user projects default response has a 5xx status code +func (o *DescribeUserProjectsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user projects default response a status code equal to that given +func (o *DescribeUserProjectsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserProjectsDefault) Error() string { + return fmt.Sprintf("[GET /user/projects][%d] describeUserProjects default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserProjectsDefault) String() string { + return fmt.Sprintf("[GET /user/projects][%d] describeUserProjects default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserProjectsDefault) GetPayload() *DescribeUserProjectsDefaultBody { + return o.Payload +} + +func (o *DescribeUserProjectsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserProjectsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserProjectsDefaultBody describe user projects default body +swagger:model DescribeUserProjectsDefaultBody +*/ +type DescribeUserProjectsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user projects default body +func (o *DescribeUserProjectsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserProjects default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserProjectsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserProjects default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjects default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjects default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user projects default body based on the context it is used +func (o *DescribeUserProjectsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjects default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjects default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserProjectsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserProjectsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserProjectsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserProjectsOKBody describe user projects o k body +swagger:model DescribeUserProjectsOKBody +*/ +type DescribeUserProjectsOKBody struct { + + // result + Result *models.ProjectList `json:"result,omitempty"` +} + +// Validate validates this describe user projects o k body +func (o *DescribeUserProjectsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjectsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjectsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user projects o k body based on the context it is used +func (o *DescribeUserProjectsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjectsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjectsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserProjectsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserProjectsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserProjectsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/modify_user_project_description_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/modify_user_project_description_parameters.go new file mode 100644 index 0000000..2211ae4 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/modify_user_project_description_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewModifyUserProjectDescriptionParams creates a new ModifyUserProjectDescriptionParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyUserProjectDescriptionParams() *ModifyUserProjectDescriptionParams { + return &ModifyUserProjectDescriptionParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyUserProjectDescriptionParamsWithTimeout creates a new ModifyUserProjectDescriptionParams object +// with the ability to set a timeout on a request. +func NewModifyUserProjectDescriptionParamsWithTimeout(timeout time.Duration) *ModifyUserProjectDescriptionParams { + return &ModifyUserProjectDescriptionParams{ + timeout: timeout, + } +} + +// NewModifyUserProjectDescriptionParamsWithContext creates a new ModifyUserProjectDescriptionParams object +// with the ability to set a context for a request. +func NewModifyUserProjectDescriptionParamsWithContext(ctx context.Context) *ModifyUserProjectDescriptionParams { + return &ModifyUserProjectDescriptionParams{ + Context: ctx, + } +} + +// NewModifyUserProjectDescriptionParamsWithHTTPClient creates a new ModifyUserProjectDescriptionParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyUserProjectDescriptionParamsWithHTTPClient(client *http.Client) *ModifyUserProjectDescriptionParams { + return &ModifyUserProjectDescriptionParams{ + HTTPClient: client, + } +} + +/* ModifyUserProjectDescriptionParams contains all the parameters to send to the API endpoint + for the modify user project description operation. + + Typically these are written to a http.Request. +*/ +type ModifyUserProjectDescriptionParams struct { + + // Body. + Body *models.ModifyProjectDescriptionRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify user project description params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserProjectDescriptionParams) WithDefaults() *ModifyUserProjectDescriptionParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify user project description params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserProjectDescriptionParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) WithTimeout(timeout time.Duration) *ModifyUserProjectDescriptionParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) WithContext(ctx context.Context) *ModifyUserProjectDescriptionParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) WithHTTPClient(client *http.Client) *ModifyUserProjectDescriptionParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) WithBody(body *models.ModifyProjectDescriptionRequest) *ModifyUserProjectDescriptionParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) SetBody(body *models.ModifyProjectDescriptionRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) WithAuthorization(authorization string) *ModifyUserProjectDescriptionParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) WithBmpLanguage(bmpLanguage *string) *ModifyUserProjectDescriptionParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) WithBmpUserID(bmpUserID *string) *ModifyUserProjectDescriptionParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) WithProjectID(projectID string) *ModifyUserProjectDescriptionParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) WithTraceID(traceID string) *ModifyUserProjectDescriptionParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify user project description params +func (o *ModifyUserProjectDescriptionParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyUserProjectDescriptionParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/modify_user_project_description_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/modify_user_project_description_responses.go new file mode 100644 index 0000000..b990bcb --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/modify_user_project_description_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// ModifyUserProjectDescriptionReader is a Reader for the ModifyUserProjectDescription structure. +type ModifyUserProjectDescriptionReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyUserProjectDescriptionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyUserProjectDescriptionOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyUserProjectDescriptionDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyUserProjectDescriptionOK creates a ModifyUserProjectDescriptionOK with default headers values +func NewModifyUserProjectDescriptionOK() *ModifyUserProjectDescriptionOK { + return &ModifyUserProjectDescriptionOK{} +} + +/* ModifyUserProjectDescriptionOK describes a response with status code 200, with default header values. + +ModifyUserProjectDescriptionOK modify user project description o k +*/ +type ModifyUserProjectDescriptionOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserProjectDescriptionOKBody +} + +// IsSuccess returns true when this modify user project description o k response has a 2xx status code +func (o *ModifyUserProjectDescriptionOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify user project description o k response has a 3xx status code +func (o *ModifyUserProjectDescriptionOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify user project description o k response has a 4xx status code +func (o *ModifyUserProjectDescriptionOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify user project description o k response has a 5xx status code +func (o *ModifyUserProjectDescriptionOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify user project description o k response a status code equal to that given +func (o *ModifyUserProjectDescriptionOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyUserProjectDescriptionOK) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/description][%d] modifyUserProjectDescriptionOK %+v", 200, o.Payload) +} + +func (o *ModifyUserProjectDescriptionOK) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/description][%d] modifyUserProjectDescriptionOK %+v", 200, o.Payload) +} + +func (o *ModifyUserProjectDescriptionOK) GetPayload() *ModifyUserProjectDescriptionOKBody { + return o.Payload +} + +func (o *ModifyUserProjectDescriptionOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserProjectDescriptionOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyUserProjectDescriptionDefault creates a ModifyUserProjectDescriptionDefault with default headers values +func NewModifyUserProjectDescriptionDefault(code int) *ModifyUserProjectDescriptionDefault { + return &ModifyUserProjectDescriptionDefault{ + _statusCode: code, + } +} + +/* ModifyUserProjectDescriptionDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyUserProjectDescriptionDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserProjectDescriptionDefaultBody +} + +// Code gets the status code for the modify user project description default response +func (o *ModifyUserProjectDescriptionDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify user project description default response has a 2xx status code +func (o *ModifyUserProjectDescriptionDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify user project description default response has a 3xx status code +func (o *ModifyUserProjectDescriptionDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify user project description default response has a 4xx status code +func (o *ModifyUserProjectDescriptionDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify user project description default response has a 5xx status code +func (o *ModifyUserProjectDescriptionDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify user project description default response a status code equal to that given +func (o *ModifyUserProjectDescriptionDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyUserProjectDescriptionDefault) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/description][%d] modifyUserProjectDescription default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserProjectDescriptionDefault) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/description][%d] modifyUserProjectDescription default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserProjectDescriptionDefault) GetPayload() *ModifyUserProjectDescriptionDefaultBody { + return o.Payload +} + +func (o *ModifyUserProjectDescriptionDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserProjectDescriptionDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyUserProjectDescriptionDefaultBody modify user project description default body +swagger:model ModifyUserProjectDescriptionDefaultBody +*/ +type ModifyUserProjectDescriptionDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify user project description default body +func (o *ModifyUserProjectDescriptionDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectDescriptionDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserProjectDescription default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyUserProjectDescriptionDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserProjectDescription default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProjectDescription default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProjectDescription default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user project description default body based on the context it is used +func (o *ModifyUserProjectDescriptionDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectDescriptionDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProjectDescription default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProjectDescription default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserProjectDescriptionDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserProjectDescriptionDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyUserProjectDescriptionDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyUserProjectDescriptionOKBody modify user project description o k body +swagger:model ModifyUserProjectDescriptionOKBody +*/ +type ModifyUserProjectDescriptionOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify user project description o k body +func (o *ModifyUserProjectDescriptionOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectDescriptionOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProjectDescriptionOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProjectDescriptionOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user project description o k body based on the context it is used +func (o *ModifyUserProjectDescriptionOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectDescriptionOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProjectDescriptionOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProjectDescriptionOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserProjectDescriptionOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserProjectDescriptionOKBody) UnmarshalBinary(b []byte) error { + var res ModifyUserProjectDescriptionOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/modify_user_project_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/modify_user_project_parameters.go new file mode 100644 index 0000000..14433d0 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/modify_user_project_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewModifyUserProjectParams creates a new ModifyUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyUserProjectParams() *ModifyUserProjectParams { + return &ModifyUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyUserProjectParamsWithTimeout creates a new ModifyUserProjectParams object +// with the ability to set a timeout on a request. +func NewModifyUserProjectParamsWithTimeout(timeout time.Duration) *ModifyUserProjectParams { + return &ModifyUserProjectParams{ + timeout: timeout, + } +} + +// NewModifyUserProjectParamsWithContext creates a new ModifyUserProjectParams object +// with the ability to set a context for a request. +func NewModifyUserProjectParamsWithContext(ctx context.Context) *ModifyUserProjectParams { + return &ModifyUserProjectParams{ + Context: ctx, + } +} + +// NewModifyUserProjectParamsWithHTTPClient creates a new ModifyUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyUserProjectParamsWithHTTPClient(client *http.Client) *ModifyUserProjectParams { + return &ModifyUserProjectParams{ + HTTPClient: client, + } +} + +/* ModifyUserProjectParams contains all the parameters to send to the API endpoint + for the modify user project operation. + + Typically these are written to a http.Request. +*/ +type ModifyUserProjectParams struct { + + // Body. + Body *models.ModifyProjectRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserProjectParams) WithDefaults() *ModifyUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify user project params +func (o *ModifyUserProjectParams) WithTimeout(timeout time.Duration) *ModifyUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify user project params +func (o *ModifyUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify user project params +func (o *ModifyUserProjectParams) WithContext(ctx context.Context) *ModifyUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify user project params +func (o *ModifyUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify user project params +func (o *ModifyUserProjectParams) WithHTTPClient(client *http.Client) *ModifyUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify user project params +func (o *ModifyUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify user project params +func (o *ModifyUserProjectParams) WithBody(body *models.ModifyProjectRequest) *ModifyUserProjectParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify user project params +func (o *ModifyUserProjectParams) SetBody(body *models.ModifyProjectRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify user project params +func (o *ModifyUserProjectParams) WithAuthorization(authorization string) *ModifyUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify user project params +func (o *ModifyUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify user project params +func (o *ModifyUserProjectParams) WithBmpLanguage(bmpLanguage *string) *ModifyUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify user project params +func (o *ModifyUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify user project params +func (o *ModifyUserProjectParams) WithBmpUserID(bmpUserID *string) *ModifyUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify user project params +func (o *ModifyUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the modify user project params +func (o *ModifyUserProjectParams) WithProjectID(projectID string) *ModifyUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the modify user project params +func (o *ModifyUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the modify user project params +func (o *ModifyUserProjectParams) WithTraceID(traceID string) *ModifyUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify user project params +func (o *ModifyUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/modify_user_project_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/modify_user_project_responses.go new file mode 100644 index 0000000..3725925 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/modify_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// ModifyUserProjectReader is a Reader for the ModifyUserProject structure. +type ModifyUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyUserProjectOK creates a ModifyUserProjectOK with default headers values +func NewModifyUserProjectOK() *ModifyUserProjectOK { + return &ModifyUserProjectOK{} +} + +/* ModifyUserProjectOK describes a response with status code 200, with default header values. + +ModifyUserProjectOK modify user project o k +*/ +type ModifyUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserProjectOKBody +} + +// IsSuccess returns true when this modify user project o k response has a 2xx status code +func (o *ModifyUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify user project o k response has a 3xx status code +func (o *ModifyUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify user project o k response has a 4xx status code +func (o *ModifyUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify user project o k response has a 5xx status code +func (o *ModifyUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify user project o k response a status code equal to that given +func (o *ModifyUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyUserProjectOK) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}][%d] modifyUserProjectOK %+v", 200, o.Payload) +} + +func (o *ModifyUserProjectOK) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}][%d] modifyUserProjectOK %+v", 200, o.Payload) +} + +func (o *ModifyUserProjectOK) GetPayload() *ModifyUserProjectOKBody { + return o.Payload +} + +func (o *ModifyUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyUserProjectDefault creates a ModifyUserProjectDefault with default headers values +func NewModifyUserProjectDefault(code int) *ModifyUserProjectDefault { + return &ModifyUserProjectDefault{ + _statusCode: code, + } +} + +/* ModifyUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserProjectDefaultBody +} + +// Code gets the status code for the modify user project default response +func (o *ModifyUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify user project default response has a 2xx status code +func (o *ModifyUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify user project default response has a 3xx status code +func (o *ModifyUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify user project default response has a 4xx status code +func (o *ModifyUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify user project default response has a 5xx status code +func (o *ModifyUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify user project default response a status code equal to that given +func (o *ModifyUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyUserProjectDefault) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}][%d] modifyUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserProjectDefault) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}][%d] modifyUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserProjectDefault) GetPayload() *ModifyUserProjectDefaultBody { + return o.Payload +} + +func (o *ModifyUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyUserProjectDefaultBody modify user project default body +swagger:model ModifyUserProjectDefaultBody +*/ +type ModifyUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify user project default body +func (o *ModifyUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user project default body based on the context it is used +func (o *ModifyUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyUserProjectOKBody modify user project o k body +swagger:model ModifyUserProjectOKBody +*/ +type ModifyUserProjectOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify user project o k body +func (o *ModifyUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user project o k body based on the context it is used +func (o *ModifyUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res ModifyUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/move_user_instances_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/move_user_instances_parameters.go new file mode 100644 index 0000000..3fefc46 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/move_user_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewMoveUserInstancesParams creates a new MoveUserInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewMoveUserInstancesParams() *MoveUserInstancesParams { + return &MoveUserInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewMoveUserInstancesParamsWithTimeout creates a new MoveUserInstancesParams object +// with the ability to set a timeout on a request. +func NewMoveUserInstancesParamsWithTimeout(timeout time.Duration) *MoveUserInstancesParams { + return &MoveUserInstancesParams{ + timeout: timeout, + } +} + +// NewMoveUserInstancesParamsWithContext creates a new MoveUserInstancesParams object +// with the ability to set a context for a request. +func NewMoveUserInstancesParamsWithContext(ctx context.Context) *MoveUserInstancesParams { + return &MoveUserInstancesParams{ + Context: ctx, + } +} + +// NewMoveUserInstancesParamsWithHTTPClient creates a new MoveUserInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewMoveUserInstancesParamsWithHTTPClient(client *http.Client) *MoveUserInstancesParams { + return &MoveUserInstancesParams{ + HTTPClient: client, + } +} + +/* MoveUserInstancesParams contains all the parameters to send to the API endpoint + for the move user instances operation. + + Typically these are written to a http.Request. +*/ +type MoveUserInstancesParams struct { + + // Body. + Body *models.MoveInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the move user instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *MoveUserInstancesParams) WithDefaults() *MoveUserInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the move user instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *MoveUserInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the move user instances params +func (o *MoveUserInstancesParams) WithTimeout(timeout time.Duration) *MoveUserInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the move user instances params +func (o *MoveUserInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the move user instances params +func (o *MoveUserInstancesParams) WithContext(ctx context.Context) *MoveUserInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the move user instances params +func (o *MoveUserInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the move user instances params +func (o *MoveUserInstancesParams) WithHTTPClient(client *http.Client) *MoveUserInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the move user instances params +func (o *MoveUserInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the move user instances params +func (o *MoveUserInstancesParams) WithBody(body *models.MoveInstancesRequest) *MoveUserInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the move user instances params +func (o *MoveUserInstancesParams) SetBody(body *models.MoveInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the move user instances params +func (o *MoveUserInstancesParams) WithAuthorization(authorization string) *MoveUserInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the move user instances params +func (o *MoveUserInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the move user instances params +func (o *MoveUserInstancesParams) WithBmpLanguage(bmpLanguage *string) *MoveUserInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the move user instances params +func (o *MoveUserInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the move user instances params +func (o *MoveUserInstancesParams) WithBmpUserID(bmpUserID *string) *MoveUserInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the move user instances params +func (o *MoveUserInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the move user instances params +func (o *MoveUserInstancesParams) WithTraceID(traceID string) *MoveUserInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the move user instances params +func (o *MoveUserInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *MoveUserInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/move_user_instances_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/move_user_instances_responses.go new file mode 100644 index 0000000..2789d30 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/move_user_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// MoveUserInstancesReader is a Reader for the MoveUserInstances structure. +type MoveUserInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *MoveUserInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewMoveUserInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewMoveUserInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewMoveUserInstancesOK creates a MoveUserInstancesOK with default headers values +func NewMoveUserInstancesOK() *MoveUserInstancesOK { + return &MoveUserInstancesOK{} +} + +/* MoveUserInstancesOK describes a response with status code 200, with default header values. + +A MoveInstanceResult is an response struct +*/ +type MoveUserInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *MoveUserInstancesOKBody +} + +// IsSuccess returns true when this move user instances o k response has a 2xx status code +func (o *MoveUserInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this move user instances o k response has a 3xx status code +func (o *MoveUserInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this move user instances o k response has a 4xx status code +func (o *MoveUserInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this move user instances o k response has a 5xx status code +func (o *MoveUserInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this move user instances o k response a status code equal to that given +func (o *MoveUserInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *MoveUserInstancesOK) Error() string { + return fmt.Sprintf("[PUT /user/projects/move/instances][%d] moveUserInstancesOK %+v", 200, o.Payload) +} + +func (o *MoveUserInstancesOK) String() string { + return fmt.Sprintf("[PUT /user/projects/move/instances][%d] moveUserInstancesOK %+v", 200, o.Payload) +} + +func (o *MoveUserInstancesOK) GetPayload() *MoveUserInstancesOKBody { + return o.Payload +} + +func (o *MoveUserInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(MoveUserInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewMoveUserInstancesDefault creates a MoveUserInstancesDefault with default headers values +func NewMoveUserInstancesDefault(code int) *MoveUserInstancesDefault { + return &MoveUserInstancesDefault{ + _statusCode: code, + } +} + +/* MoveUserInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type MoveUserInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *MoveUserInstancesDefaultBody +} + +// Code gets the status code for the move user instances default response +func (o *MoveUserInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this move user instances default response has a 2xx status code +func (o *MoveUserInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this move user instances default response has a 3xx status code +func (o *MoveUserInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this move user instances default response has a 4xx status code +func (o *MoveUserInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this move user instances default response has a 5xx status code +func (o *MoveUserInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this move user instances default response a status code equal to that given +func (o *MoveUserInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *MoveUserInstancesDefault) Error() string { + return fmt.Sprintf("[PUT /user/projects/move/instances][%d] moveUserInstances default %+v", o._statusCode, o.Payload) +} + +func (o *MoveUserInstancesDefault) String() string { + return fmt.Sprintf("[PUT /user/projects/move/instances][%d] moveUserInstances default %+v", o._statusCode, o.Payload) +} + +func (o *MoveUserInstancesDefault) GetPayload() *MoveUserInstancesDefaultBody { + return o.Payload +} + +func (o *MoveUserInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(MoveUserInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*MoveUserInstancesDefaultBody move user instances default body +swagger:model MoveUserInstancesDefaultBody +*/ +type MoveUserInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this move user instances default body +func (o *MoveUserInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MoveUserInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("moveUserInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *MoveUserInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("moveUserInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("moveUserInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("moveUserInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this move user instances default body based on the context it is used +func (o *MoveUserInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MoveUserInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("moveUserInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("moveUserInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *MoveUserInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *MoveUserInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res MoveUserInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*MoveUserInstancesOKBody move user instances o k body +swagger:model MoveUserInstancesOKBody +*/ +type MoveUserInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this move user instances o k body +func (o *MoveUserInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MoveUserInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("moveUserInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("moveUserInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this move user instances o k body based on the context it is used +func (o *MoveUserInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MoveUserInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("moveUserInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("moveUserInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *MoveUserInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *MoveUserInstancesOKBody) UnmarshalBinary(b []byte) error { + var res MoveUserInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/move_user_project_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/move_user_project_parameters.go new file mode 100644 index 0000000..ca7188b --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/move_user_project_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewMoveUserProjectParams creates a new MoveUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewMoveUserProjectParams() *MoveUserProjectParams { + return &MoveUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewMoveUserProjectParamsWithTimeout creates a new MoveUserProjectParams object +// with the ability to set a timeout on a request. +func NewMoveUserProjectParamsWithTimeout(timeout time.Duration) *MoveUserProjectParams { + return &MoveUserProjectParams{ + timeout: timeout, + } +} + +// NewMoveUserProjectParamsWithContext creates a new MoveUserProjectParams object +// with the ability to set a context for a request. +func NewMoveUserProjectParamsWithContext(ctx context.Context) *MoveUserProjectParams { + return &MoveUserProjectParams{ + Context: ctx, + } +} + +// NewMoveUserProjectParamsWithHTTPClient creates a new MoveUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewMoveUserProjectParamsWithHTTPClient(client *http.Client) *MoveUserProjectParams { + return &MoveUserProjectParams{ + HTTPClient: client, + } +} + +/* MoveUserProjectParams contains all the parameters to send to the API endpoint + for the move user project operation. + + Typically these are written to a http.Request. +*/ +type MoveUserProjectParams struct { + + // Body. + Body *models.MoveProjectRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the move user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *MoveUserProjectParams) WithDefaults() *MoveUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the move user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *MoveUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the move user project params +func (o *MoveUserProjectParams) WithTimeout(timeout time.Duration) *MoveUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the move user project params +func (o *MoveUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the move user project params +func (o *MoveUserProjectParams) WithContext(ctx context.Context) *MoveUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the move user project params +func (o *MoveUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the move user project params +func (o *MoveUserProjectParams) WithHTTPClient(client *http.Client) *MoveUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the move user project params +func (o *MoveUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the move user project params +func (o *MoveUserProjectParams) WithBody(body *models.MoveProjectRequest) *MoveUserProjectParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the move user project params +func (o *MoveUserProjectParams) SetBody(body *models.MoveProjectRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the move user project params +func (o *MoveUserProjectParams) WithAuthorization(authorization string) *MoveUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the move user project params +func (o *MoveUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the move user project params +func (o *MoveUserProjectParams) WithBmpLanguage(bmpLanguage *string) *MoveUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the move user project params +func (o *MoveUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the move user project params +func (o *MoveUserProjectParams) WithBmpUserID(bmpUserID *string) *MoveUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the move user project params +func (o *MoveUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the move user project params +func (o *MoveUserProjectParams) WithProjectID(projectID string) *MoveUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the move user project params +func (o *MoveUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the move user project params +func (o *MoveUserProjectParams) WithTraceID(traceID string) *MoveUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the move user project params +func (o *MoveUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *MoveUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/move_user_project_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/move_user_project_responses.go new file mode 100644 index 0000000..da87b67 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/move_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// MoveUserProjectReader is a Reader for the MoveUserProject structure. +type MoveUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *MoveUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewMoveUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewMoveUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewMoveUserProjectOK creates a MoveUserProjectOK with default headers values +func NewMoveUserProjectOK() *MoveUserProjectOK { + return &MoveUserProjectOK{} +} + +/* MoveUserProjectOK describes a response with status code 200, with default header values. + +A MoveProjectResult is an response struct +*/ +type MoveUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *MoveUserProjectOKBody +} + +// IsSuccess returns true when this move user project o k response has a 2xx status code +func (o *MoveUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this move user project o k response has a 3xx status code +func (o *MoveUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this move user project o k response has a 4xx status code +func (o *MoveUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this move user project o k response has a 5xx status code +func (o *MoveUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this move user project o k response a status code equal to that given +func (o *MoveUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *MoveUserProjectOK) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/move][%d] moveUserProjectOK %+v", 200, o.Payload) +} + +func (o *MoveUserProjectOK) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/move][%d] moveUserProjectOK %+v", 200, o.Payload) +} + +func (o *MoveUserProjectOK) GetPayload() *MoveUserProjectOKBody { + return o.Payload +} + +func (o *MoveUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(MoveUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewMoveUserProjectDefault creates a MoveUserProjectDefault with default headers values +func NewMoveUserProjectDefault(code int) *MoveUserProjectDefault { + return &MoveUserProjectDefault{ + _statusCode: code, + } +} + +/* MoveUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type MoveUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *MoveUserProjectDefaultBody +} + +// Code gets the status code for the move user project default response +func (o *MoveUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this move user project default response has a 2xx status code +func (o *MoveUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this move user project default response has a 3xx status code +func (o *MoveUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this move user project default response has a 4xx status code +func (o *MoveUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this move user project default response has a 5xx status code +func (o *MoveUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this move user project default response a status code equal to that given +func (o *MoveUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *MoveUserProjectDefault) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/move][%d] moveUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *MoveUserProjectDefault) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/move][%d] moveUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *MoveUserProjectDefault) GetPayload() *MoveUserProjectDefaultBody { + return o.Payload +} + +func (o *MoveUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(MoveUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*MoveUserProjectDefaultBody move user project default body +swagger:model MoveUserProjectDefaultBody +*/ +type MoveUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this move user project default body +func (o *MoveUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MoveUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("moveUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *MoveUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("moveUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("moveUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("moveUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this move user project default body based on the context it is used +func (o *MoveUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MoveUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("moveUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("moveUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *MoveUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *MoveUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res MoveUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*MoveUserProjectOKBody move user project o k body +swagger:model MoveUserProjectOKBody +*/ +type MoveUserProjectOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this move user project o k body +func (o *MoveUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MoveUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("moveUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("moveUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this move user project o k body based on the context it is used +func (o *MoveUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MoveUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("moveUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("moveUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *MoveUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *MoveUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res MoveUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/project_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/project_client.go new file mode 100644 index 0000000..d62b518 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/project_client.go @@ -0,0 +1,477 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new project API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for project API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CancelShareUserProject(params *CancelShareUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CancelShareUserProjectOK, error) + + CreateUserProject(params *CreateUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserProjectOK, error) + + DeleteUserProject(params *DeleteUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserProjectOK, error) + + DescribeShareProject(params *DescribeShareProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeShareProjectOK, error) + + DescribeUserProject(params *DescribeUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserProjectOK, error) + + DescribeUserProjects(params *DescribeUserProjectsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserProjectsOK, error) + + ModifyUserProject(params *ModifyUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserProjectOK, error) + + ModifyUserProjectDescription(params *ModifyUserProjectDescriptionParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserProjectDescriptionOK, error) + + MoveUserInstances(params *MoveUserInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*MoveUserInstancesOK, error) + + MoveUserProject(params *MoveUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*MoveUserProjectOK, error) + + ShareUserProject(params *ShareUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ShareUserProjectOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CancelShareUserProject CancelShareUserProject 取消共享项目 +*/ +func (a *Client) CancelShareUserProject(params *CancelShareUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CancelShareUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCancelShareUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "cancelShareUserProject", + Method: "PUT", + PathPattern: "/user/projects/{project_id}/cancelShare", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CancelShareUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CancelShareUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CancelShareUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + CreateUserProject CreateUserProject 创建项目 +*/ +func (a *Client) CreateUserProject(params *CreateUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "createUserProject", + Method: "POST", + PathPattern: "/user/projects", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteUserProject DeleteUserProject 删除项目 +*/ +func (a *Client) DeleteUserProject(params *DeleteUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "deleteUserProject", + Method: "DELETE", + PathPattern: "/user/projects/{project_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeShareProject DescribeShareUserProject 获取共享项目详情 +*/ +func (a *Client) DescribeShareProject(params *DescribeShareProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeShareProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeShareProjectParams() + } + op := &runtime.ClientOperation{ + ID: "describeShareProject", + Method: "GET", + PathPattern: "/user/projects/{project_id}/describeSharProject", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeShareProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeShareProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeShareProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserProject DescribeUserProject 获取项目详情 +*/ +func (a *Client) DescribeUserProject(params *DescribeUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserProject", + Method: "GET", + PathPattern: "/user/projects/{project_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserProjects DescribeUserProjects 获取项目列表 +*/ +func (a *Client) DescribeUserProjects(params *DescribeUserProjectsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserProjectsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserProjectsParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserProjects", + Method: "GET", + PathPattern: "/user/projects", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserProjectsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserProjectsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserProjectsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyUserProject ModifyUserProject 修改项目信息 +*/ +func (a *Client) ModifyUserProject(params *ModifyUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "modifyUserProject", + Method: "PUT", + PathPattern: "/user/projects/{project_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyUserProjectDescription ModifyUserProject 修改项目信息 +*/ +func (a *Client) ModifyUserProjectDescription(params *ModifyUserProjectDescriptionParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserProjectDescriptionOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyUserProjectDescriptionParams() + } + op := &runtime.ClientOperation{ + ID: "modifyUserProjectDescription", + Method: "PUT", + PathPattern: "/user/projects/{project_id}/description", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyUserProjectDescriptionReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyUserProjectDescriptionOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyUserProjectDescriptionDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + MoveUserInstances MoveUserInstances 转移项目下的某些实例 +*/ +func (a *Client) MoveUserInstances(params *MoveUserInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*MoveUserInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewMoveUserInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "moveUserInstances", + Method: "PUT", + PathPattern: "/user/projects/move/instances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &MoveUserInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*MoveUserInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*MoveUserInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + MoveUserProject MoveUserProject 转移项目 +*/ +func (a *Client) MoveUserProject(params *MoveUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*MoveUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewMoveUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "moveUserProject", + Method: "PUT", + PathPattern: "/user/projects/{project_id}/move", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &MoveUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*MoveUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*MoveUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ShareUserProject ShareUserProject 共享项目 +*/ +func (a *Client) ShareUserProject(params *ShareUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ShareUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewShareUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "shareUserProject", + Method: "PUT", + PathPattern: "/user/projects/{project_id}/share", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ShareUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ShareUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ShareUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/share_user_project_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/share_user_project_parameters.go new file mode 100644 index 0000000..493b409 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/share_user_project_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewShareUserProjectParams creates a new ShareUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewShareUserProjectParams() *ShareUserProjectParams { + return &ShareUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewShareUserProjectParamsWithTimeout creates a new ShareUserProjectParams object +// with the ability to set a timeout on a request. +func NewShareUserProjectParamsWithTimeout(timeout time.Duration) *ShareUserProjectParams { + return &ShareUserProjectParams{ + timeout: timeout, + } +} + +// NewShareUserProjectParamsWithContext creates a new ShareUserProjectParams object +// with the ability to set a context for a request. +func NewShareUserProjectParamsWithContext(ctx context.Context) *ShareUserProjectParams { + return &ShareUserProjectParams{ + Context: ctx, + } +} + +// NewShareUserProjectParamsWithHTTPClient creates a new ShareUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewShareUserProjectParamsWithHTTPClient(client *http.Client) *ShareUserProjectParams { + return &ShareUserProjectParams{ + HTTPClient: client, + } +} + +/* ShareUserProjectParams contains all the parameters to send to the API endpoint + for the share user project operation. + + Typically these are written to a http.Request. +*/ +type ShareUserProjectParams struct { + + // Body. + Body *models.ShareProjectRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the share user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ShareUserProjectParams) WithDefaults() *ShareUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the share user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ShareUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the share user project params +func (o *ShareUserProjectParams) WithTimeout(timeout time.Duration) *ShareUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the share user project params +func (o *ShareUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the share user project params +func (o *ShareUserProjectParams) WithContext(ctx context.Context) *ShareUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the share user project params +func (o *ShareUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the share user project params +func (o *ShareUserProjectParams) WithHTTPClient(client *http.Client) *ShareUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the share user project params +func (o *ShareUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the share user project params +func (o *ShareUserProjectParams) WithBody(body *models.ShareProjectRequest) *ShareUserProjectParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the share user project params +func (o *ShareUserProjectParams) SetBody(body *models.ShareProjectRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the share user project params +func (o *ShareUserProjectParams) WithAuthorization(authorization string) *ShareUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the share user project params +func (o *ShareUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the share user project params +func (o *ShareUserProjectParams) WithBmpLanguage(bmpLanguage *string) *ShareUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the share user project params +func (o *ShareUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the share user project params +func (o *ShareUserProjectParams) WithBmpUserID(bmpUserID *string) *ShareUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the share user project params +func (o *ShareUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the share user project params +func (o *ShareUserProjectParams) WithProjectID(projectID string) *ShareUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the share user project params +func (o *ShareUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the share user project params +func (o *ShareUserProjectParams) WithTraceID(traceID string) *ShareUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the share user project params +func (o *ShareUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ShareUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/share_user_project_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/share_user_project_responses.go new file mode 100644 index 0000000..adc633e --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/project/share_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// ShareUserProjectReader is a Reader for the ShareUserProject structure. +type ShareUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ShareUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewShareUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewShareUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewShareUserProjectOK creates a ShareUserProjectOK with default headers values +func NewShareUserProjectOK() *ShareUserProjectOK { + return &ShareUserProjectOK{} +} + +/* ShareUserProjectOK describes a response with status code 200, with default header values. + +A ShareUserProjectResult is an response struct +*/ +type ShareUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ShareUserProjectOKBody +} + +// IsSuccess returns true when this share user project o k response has a 2xx status code +func (o *ShareUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this share user project o k response has a 3xx status code +func (o *ShareUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this share user project o k response has a 4xx status code +func (o *ShareUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this share user project o k response has a 5xx status code +func (o *ShareUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this share user project o k response a status code equal to that given +func (o *ShareUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ShareUserProjectOK) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/share][%d] shareUserProjectOK %+v", 200, o.Payload) +} + +func (o *ShareUserProjectOK) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/share][%d] shareUserProjectOK %+v", 200, o.Payload) +} + +func (o *ShareUserProjectOK) GetPayload() *ShareUserProjectOKBody { + return o.Payload +} + +func (o *ShareUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ShareUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewShareUserProjectDefault creates a ShareUserProjectDefault with default headers values +func NewShareUserProjectDefault(code int) *ShareUserProjectDefault { + return &ShareUserProjectDefault{ + _statusCode: code, + } +} + +/* ShareUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ShareUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ShareUserProjectDefaultBody +} + +// Code gets the status code for the share user project default response +func (o *ShareUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this share user project default response has a 2xx status code +func (o *ShareUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this share user project default response has a 3xx status code +func (o *ShareUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this share user project default response has a 4xx status code +func (o *ShareUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this share user project default response has a 5xx status code +func (o *ShareUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this share user project default response a status code equal to that given +func (o *ShareUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ShareUserProjectDefault) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/share][%d] shareUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *ShareUserProjectDefault) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/share][%d] shareUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *ShareUserProjectDefault) GetPayload() *ShareUserProjectDefaultBody { + return o.Payload +} + +func (o *ShareUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ShareUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ShareUserProjectDefaultBody share user project default body +swagger:model ShareUserProjectDefaultBody +*/ +type ShareUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this share user project default body +func (o *ShareUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ShareUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("shareUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ShareUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("shareUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this share user project default body based on the context it is used +func (o *ShareUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ShareUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ShareUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ShareUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res ShareUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ShareUserProjectOKBody share user project o k body +swagger:model ShareUserProjectOKBody +*/ +type ShareUserProjectOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this share user project o k body +func (o *ShareUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ShareUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this share user project o k body based on the context it is used +func (o *ShareUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ShareUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ShareUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ShareUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res ShareUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/resource/describe_resources_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/resource/describe_resources_parameters.go new file mode 100644 index 0000000..ea3d17d --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/resource/describe_resources_parameters.go @@ -0,0 +1,361 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package resource + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeResourcesParams creates a new DescribeResourcesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeResourcesParams() *DescribeResourcesParams { + return &DescribeResourcesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeResourcesParamsWithTimeout creates a new DescribeResourcesParams object +// with the ability to set a timeout on a request. +func NewDescribeResourcesParamsWithTimeout(timeout time.Duration) *DescribeResourcesParams { + return &DescribeResourcesParams{ + timeout: timeout, + } +} + +// NewDescribeResourcesParamsWithContext creates a new DescribeResourcesParams object +// with the ability to set a context for a request. +func NewDescribeResourcesParamsWithContext(ctx context.Context) *DescribeResourcesParams { + return &DescribeResourcesParams{ + Context: ctx, + } +} + +// NewDescribeResourcesParamsWithHTTPClient creates a new DescribeResourcesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeResourcesParamsWithHTTPClient(client *http.Client) *DescribeResourcesParams { + return &DescribeResourcesParams{ + HTTPClient: client, + } +} + +/* DescribeResourcesParams contains all the parameters to send to the API endpoint + for the describe resources operation. + + Typically these are written to a http.Request. +*/ +type DescribeResourcesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceType. + + 机型规格 + */ + DeviceType *string + + /* ImageName. + + 镜像名称 + */ + ImageName *string + + /* Name. + + 机房名称 + IdcName string `json:"idcName"` + 机房英文名称 + IdcNameEn string `json:"idcNameEn"`[*]/ + 机型名称 + */ + Name *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserName. + + 用户名称 + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe resources params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeResourcesParams) WithDefaults() *DescribeResourcesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe resources params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeResourcesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe resources params +func (o *DescribeResourcesParams) WithTimeout(timeout time.Duration) *DescribeResourcesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe resources params +func (o *DescribeResourcesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe resources params +func (o *DescribeResourcesParams) WithContext(ctx context.Context) *DescribeResourcesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe resources params +func (o *DescribeResourcesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe resources params +func (o *DescribeResourcesParams) WithHTTPClient(client *http.Client) *DescribeResourcesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe resources params +func (o *DescribeResourcesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe resources params +func (o *DescribeResourcesParams) WithAuthorization(authorization string) *DescribeResourcesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe resources params +func (o *DescribeResourcesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe resources params +func (o *DescribeResourcesParams) WithBmpLanguage(bmpLanguage *string) *DescribeResourcesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe resources params +func (o *DescribeResourcesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe resources params +func (o *DescribeResourcesParams) WithBmpUserID(bmpUserID *string) *DescribeResourcesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe resources params +func (o *DescribeResourcesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceType adds the deviceType to the describe resources params +func (o *DescribeResourcesParams) WithDeviceType(deviceType *string) *DescribeResourcesParams { + o.SetDeviceType(deviceType) + return o +} + +// SetDeviceType adds the deviceType to the describe resources params +func (o *DescribeResourcesParams) SetDeviceType(deviceType *string) { + o.DeviceType = deviceType +} + +// WithImageName adds the imageName to the describe resources params +func (o *DescribeResourcesParams) WithImageName(imageName *string) *DescribeResourcesParams { + o.SetImageName(imageName) + return o +} + +// SetImageName adds the imageName to the describe resources params +func (o *DescribeResourcesParams) SetImageName(imageName *string) { + o.ImageName = imageName +} + +// WithName adds the name to the describe resources params +func (o *DescribeResourcesParams) WithName(name *string) *DescribeResourcesParams { + o.SetName(name) + return o +} + +// SetName adds the name to the describe resources params +func (o *DescribeResourcesParams) SetName(name *string) { + o.Name = name +} + +// WithTraceID adds the traceID to the describe resources params +func (o *DescribeResourcesParams) WithTraceID(traceID string) *DescribeResourcesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe resources params +func (o *DescribeResourcesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserName adds the userName to the describe resources params +func (o *DescribeResourcesParams) WithUserName(userName *string) *DescribeResourcesParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe resources params +func (o *DescribeResourcesParams) SetUserName(userName *string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeResourcesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceType != nil { + + // query param deviceType + var qrDeviceType string + + if o.DeviceType != nil { + qrDeviceType = *o.DeviceType + } + qDeviceType := qrDeviceType + if qDeviceType != "" { + + if err := r.SetQueryParam("deviceType", qDeviceType); err != nil { + return err + } + } + } + + if o.ImageName != nil { + + // query param imageName + var qrImageName string + + if o.ImageName != nil { + qrImageName = *o.ImageName + } + qImageName := qrImageName + if qImageName != "" { + + if err := r.SetQueryParam("imageName", qImageName); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserName != nil { + + // query param userName + var qrUserName string + + if o.UserName != nil { + qrUserName = *o.UserName + } + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/resource/describe_resources_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/resource/describe_resources_responses.go new file mode 100644 index 0000000..4b1086d --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/resource/describe_resources_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package resource + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeResourcesReader is a Reader for the DescribeResources structure. +type DescribeResourcesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeResourcesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeResourcesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeResourcesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeResourcesOK creates a DescribeResourcesOK with default headers values +func NewDescribeResourcesOK() *DescribeResourcesOK { + return &DescribeResourcesOK{} +} + +/* DescribeResourcesOK describes a response with status code 200, with default header values. + +DescribeResourcesOK describe resources o k +*/ +type DescribeResourcesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeResourcesOKBody +} + +// IsSuccess returns true when this describe resources o k response has a 2xx status code +func (o *DescribeResourcesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe resources o k response has a 3xx status code +func (o *DescribeResourcesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe resources o k response has a 4xx status code +func (o *DescribeResourcesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe resources o k response has a 5xx status code +func (o *DescribeResourcesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe resources o k response a status code equal to that given +func (o *DescribeResourcesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeResourcesOK) Error() string { + return fmt.Sprintf("[GET /resources][%d] describeResourcesOK %+v", 200, o.Payload) +} + +func (o *DescribeResourcesOK) String() string { + return fmt.Sprintf("[GET /resources][%d] describeResourcesOK %+v", 200, o.Payload) +} + +func (o *DescribeResourcesOK) GetPayload() *DescribeResourcesOKBody { + return o.Payload +} + +func (o *DescribeResourcesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeResourcesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeResourcesDefault creates a DescribeResourcesDefault with default headers values +func NewDescribeResourcesDefault(code int) *DescribeResourcesDefault { + return &DescribeResourcesDefault{ + _statusCode: code, + } +} + +/* DescribeResourcesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeResourcesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeResourcesDefaultBody +} + +// Code gets the status code for the describe resources default response +func (o *DescribeResourcesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe resources default response has a 2xx status code +func (o *DescribeResourcesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe resources default response has a 3xx status code +func (o *DescribeResourcesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe resources default response has a 4xx status code +func (o *DescribeResourcesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe resources default response has a 5xx status code +func (o *DescribeResourcesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe resources default response a status code equal to that given +func (o *DescribeResourcesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeResourcesDefault) Error() string { + return fmt.Sprintf("[GET /resources][%d] describeResources default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeResourcesDefault) String() string { + return fmt.Sprintf("[GET /resources][%d] describeResources default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeResourcesDefault) GetPayload() *DescribeResourcesDefaultBody { + return o.Payload +} + +func (o *DescribeResourcesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeResourcesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeResourcesDefaultBody describe resources default body +swagger:model DescribeResourcesDefaultBody +*/ +type DescribeResourcesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe resources default body +func (o *DescribeResourcesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeResourcesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeResources default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeResourcesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeResources default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeResources default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeResources default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe resources default body based on the context it is used +func (o *DescribeResourcesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeResourcesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeResources default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeResources default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeResourcesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeResourcesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeResourcesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeResourcesOKBody describe resources o k body +swagger:model DescribeResourcesOKBody +*/ +type DescribeResourcesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this describe resources o k body +func (o *DescribeResourcesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeResourcesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeResourcesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeResourcesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe resources o k body based on the context it is used +func (o *DescribeResourcesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeResourcesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeResourcesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeResourcesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeResourcesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeResourcesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeResourcesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/resource/resource_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/resource/resource_client.go new file mode 100644 index 0000000..4bc504f --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/resource/resource_client.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package resource + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new resource API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for resource API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DescribeResources(params *DescribeResourcesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeResourcesOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DescribeResources DescribeResources 根据某个字段值精确查询对应的资源列表(如根据imageName查询镜像列表,根据idcName查询机房列表) +*/ +func (a *Client) DescribeResources(params *DescribeResourcesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeResourcesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeResourcesParams() + } + op := &runtime.ClientOperation{ + ID: "describeResources", + Method: "GET", + PathPattern: "/resources", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeResourcesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeResourcesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeResourcesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/current_role_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/current_role_parameters.go new file mode 100644 index 0000000..e39198b --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/current_role_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewCurrentRoleParams creates a new CurrentRoleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCurrentRoleParams() *CurrentRoleParams { + return &CurrentRoleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCurrentRoleParamsWithTimeout creates a new CurrentRoleParams object +// with the ability to set a timeout on a request. +func NewCurrentRoleParamsWithTimeout(timeout time.Duration) *CurrentRoleParams { + return &CurrentRoleParams{ + timeout: timeout, + } +} + +// NewCurrentRoleParamsWithContext creates a new CurrentRoleParams object +// with the ability to set a context for a request. +func NewCurrentRoleParamsWithContext(ctx context.Context) *CurrentRoleParams { + return &CurrentRoleParams{ + Context: ctx, + } +} + +// NewCurrentRoleParamsWithHTTPClient creates a new CurrentRoleParams object +// with the ability to set a custom HTTPClient for a request. +func NewCurrentRoleParamsWithHTTPClient(client *http.Client) *CurrentRoleParams { + return &CurrentRoleParams{ + HTTPClient: client, + } +} + +/* CurrentRoleParams contains all the parameters to send to the API endpoint + for the current role operation. + + Typically these are written to a http.Request. +*/ +type CurrentRoleParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the current role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CurrentRoleParams) WithDefaults() *CurrentRoleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the current role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CurrentRoleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the current role params +func (o *CurrentRoleParams) WithTimeout(timeout time.Duration) *CurrentRoleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the current role params +func (o *CurrentRoleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the current role params +func (o *CurrentRoleParams) WithContext(ctx context.Context) *CurrentRoleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the current role params +func (o *CurrentRoleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the current role params +func (o *CurrentRoleParams) WithHTTPClient(client *http.Client) *CurrentRoleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the current role params +func (o *CurrentRoleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the current role params +func (o *CurrentRoleParams) WithAuthorization(authorization string) *CurrentRoleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the current role params +func (o *CurrentRoleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the current role params +func (o *CurrentRoleParams) WithBmpLanguage(bmpLanguage *string) *CurrentRoleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the current role params +func (o *CurrentRoleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the current role params +func (o *CurrentRoleParams) WithBmpUserID(bmpUserID *string) *CurrentRoleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the current role params +func (o *CurrentRoleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the current role params +func (o *CurrentRoleParams) WithTraceID(traceID string) *CurrentRoleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the current role params +func (o *CurrentRoleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CurrentRoleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/current_role_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/current_role_responses.go new file mode 100644 index 0000000..ed072ef --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/current_role_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// CurrentRoleReader is a Reader for the CurrentRole structure. +type CurrentRoleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CurrentRoleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCurrentRoleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCurrentRoleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCurrentRoleOK creates a CurrentRoleOK with default headers values +func NewCurrentRoleOK() *CurrentRoleOK { + return &CurrentRoleOK{} +} + +/* CurrentRoleOK describes a response with status code 200, with default header values. + +A CurrentRoleResult is an response struct that is used to describe role. +*/ +type CurrentRoleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CurrentRoleOKBody +} + +// IsSuccess returns true when this current role o k response has a 2xx status code +func (o *CurrentRoleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this current role o k response has a 3xx status code +func (o *CurrentRoleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this current role o k response has a 4xx status code +func (o *CurrentRoleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this current role o k response has a 5xx status code +func (o *CurrentRoleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this current role o k response a status code equal to that given +func (o *CurrentRoleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CurrentRoleOK) Error() string { + return fmt.Sprintf("[GET /roles/roleInfo/current][%d] currentRoleOK %+v", 200, o.Payload) +} + +func (o *CurrentRoleOK) String() string { + return fmt.Sprintf("[GET /roles/roleInfo/current][%d] currentRoleOK %+v", 200, o.Payload) +} + +func (o *CurrentRoleOK) GetPayload() *CurrentRoleOKBody { + return o.Payload +} + +func (o *CurrentRoleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CurrentRoleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCurrentRoleDefault creates a CurrentRoleDefault with default headers values +func NewCurrentRoleDefault(code int) *CurrentRoleDefault { + return &CurrentRoleDefault{ + _statusCode: code, + } +} + +/* CurrentRoleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CurrentRoleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CurrentRoleDefaultBody +} + +// Code gets the status code for the current role default response +func (o *CurrentRoleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this current role default response has a 2xx status code +func (o *CurrentRoleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this current role default response has a 3xx status code +func (o *CurrentRoleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this current role default response has a 4xx status code +func (o *CurrentRoleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this current role default response has a 5xx status code +func (o *CurrentRoleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this current role default response a status code equal to that given +func (o *CurrentRoleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CurrentRoleDefault) Error() string { + return fmt.Sprintf("[GET /roles/roleInfo/current][%d] currentRole default %+v", o._statusCode, o.Payload) +} + +func (o *CurrentRoleDefault) String() string { + return fmt.Sprintf("[GET /roles/roleInfo/current][%d] currentRole default %+v", o._statusCode, o.Payload) +} + +func (o *CurrentRoleDefault) GetPayload() *CurrentRoleDefaultBody { + return o.Payload +} + +func (o *CurrentRoleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CurrentRoleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CurrentRoleDefaultBody current role default body +swagger:model CurrentRoleDefaultBody +*/ +type CurrentRoleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this current role default body +func (o *CurrentRoleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CurrentRoleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("currentRole default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CurrentRoleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("currentRole default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("currentRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("currentRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this current role default body based on the context it is used +func (o *CurrentRoleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CurrentRoleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("currentRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("currentRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CurrentRoleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CurrentRoleDefaultBody) UnmarshalBinary(b []byte) error { + var res CurrentRoleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CurrentRoleOKBody current role o k body +swagger:model CurrentRoleOKBody +*/ +type CurrentRoleOKBody struct { + + // result + Result *models.RoleInfo `json:"result,omitempty"` +} + +// Validate validates this current role o k body +func (o *CurrentRoleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CurrentRoleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("currentRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("currentRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this current role o k body based on the context it is used +func (o *CurrentRoleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CurrentRoleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("currentRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("currentRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CurrentRoleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CurrentRoleOKBody) UnmarshalBinary(b []byte) error { + var res CurrentRoleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/describe_role_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/describe_role_parameters.go new file mode 100644 index 0000000..5cda2db --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/describe_role_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeRoleParams creates a new DescribeRoleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeRoleParams() *DescribeRoleParams { + return &DescribeRoleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeRoleParamsWithTimeout creates a new DescribeRoleParams object +// with the ability to set a timeout on a request. +func NewDescribeRoleParamsWithTimeout(timeout time.Duration) *DescribeRoleParams { + return &DescribeRoleParams{ + timeout: timeout, + } +} + +// NewDescribeRoleParamsWithContext creates a new DescribeRoleParams object +// with the ability to set a context for a request. +func NewDescribeRoleParamsWithContext(ctx context.Context) *DescribeRoleParams { + return &DescribeRoleParams{ + Context: ctx, + } +} + +// NewDescribeRoleParamsWithHTTPClient creates a new DescribeRoleParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeRoleParamsWithHTTPClient(client *http.Client) *DescribeRoleParams { + return &DescribeRoleParams{ + HTTPClient: client, + } +} + +/* DescribeRoleParams contains all the parameters to send to the API endpoint + for the describe role operation. + + Typically these are written to a http.Request. +*/ +type DescribeRoleParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // RoleID. + RoleID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRoleParams) WithDefaults() *DescribeRoleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRoleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe role params +func (o *DescribeRoleParams) WithTimeout(timeout time.Duration) *DescribeRoleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe role params +func (o *DescribeRoleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe role params +func (o *DescribeRoleParams) WithContext(ctx context.Context) *DescribeRoleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe role params +func (o *DescribeRoleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe role params +func (o *DescribeRoleParams) WithHTTPClient(client *http.Client) *DescribeRoleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe role params +func (o *DescribeRoleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe role params +func (o *DescribeRoleParams) WithAuthorization(authorization string) *DescribeRoleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe role params +func (o *DescribeRoleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe role params +func (o *DescribeRoleParams) WithBmpLanguage(bmpLanguage *string) *DescribeRoleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe role params +func (o *DescribeRoleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe role params +func (o *DescribeRoleParams) WithBmpUserID(bmpUserID *string) *DescribeRoleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe role params +func (o *DescribeRoleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithRoleID adds the roleID to the describe role params +func (o *DescribeRoleParams) WithRoleID(roleID string) *DescribeRoleParams { + o.SetRoleID(roleID) + return o +} + +// SetRoleID adds the roleId to the describe role params +func (o *DescribeRoleParams) SetRoleID(roleID string) { + o.RoleID = roleID +} + +// WithTraceID adds the traceID to the describe role params +func (o *DescribeRoleParams) WithTraceID(traceID string) *DescribeRoleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe role params +func (o *DescribeRoleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeRoleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param role_id + if err := r.SetPathParam("role_id", o.RoleID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/describe_role_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/describe_role_responses.go new file mode 100644 index 0000000..7afc1ee --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/describe_role_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeRoleReader is a Reader for the DescribeRole structure. +type DescribeRoleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeRoleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeRoleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeRoleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeRoleOK creates a DescribeRoleOK with default headers values +func NewDescribeRoleOK() *DescribeRoleOK { + return &DescribeRoleOK{} +} + +/* DescribeRoleOK describes a response with status code 200, with default header values. + +A GetRoleResult is an response struct that is used to describe role. +*/ +type DescribeRoleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRoleOKBody +} + +// IsSuccess returns true when this describe role o k response has a 2xx status code +func (o *DescribeRoleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe role o k response has a 3xx status code +func (o *DescribeRoleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe role o k response has a 4xx status code +func (o *DescribeRoleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe role o k response has a 5xx status code +func (o *DescribeRoleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe role o k response a status code equal to that given +func (o *DescribeRoleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeRoleOK) Error() string { + return fmt.Sprintf("[GET /roles/{role_id}][%d] describeRoleOK %+v", 200, o.Payload) +} + +func (o *DescribeRoleOK) String() string { + return fmt.Sprintf("[GET /roles/{role_id}][%d] describeRoleOK %+v", 200, o.Payload) +} + +func (o *DescribeRoleOK) GetPayload() *DescribeRoleOKBody { + return o.Payload +} + +func (o *DescribeRoleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRoleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeRoleDefault creates a DescribeRoleDefault with default headers values +func NewDescribeRoleDefault(code int) *DescribeRoleDefault { + return &DescribeRoleDefault{ + _statusCode: code, + } +} + +/* DescribeRoleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeRoleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRoleDefaultBody +} + +// Code gets the status code for the describe role default response +func (o *DescribeRoleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe role default response has a 2xx status code +func (o *DescribeRoleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe role default response has a 3xx status code +func (o *DescribeRoleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe role default response has a 4xx status code +func (o *DescribeRoleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe role default response has a 5xx status code +func (o *DescribeRoleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe role default response a status code equal to that given +func (o *DescribeRoleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeRoleDefault) Error() string { + return fmt.Sprintf("[GET /roles/{role_id}][%d] describeRole default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRoleDefault) String() string { + return fmt.Sprintf("[GET /roles/{role_id}][%d] describeRole default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRoleDefault) GetPayload() *DescribeRoleDefaultBody { + return o.Payload +} + +func (o *DescribeRoleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRoleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeRoleDefaultBody describe role default body +swagger:model DescribeRoleDefaultBody +*/ +type DescribeRoleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe role default body +func (o *DescribeRoleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRoleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeRole default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeRoleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeRole default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe role default body based on the context it is used +func (o *DescribeRoleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRoleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRoleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRoleDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeRoleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeRoleOKBody describe role o k body +swagger:model DescribeRoleOKBody +*/ +type DescribeRoleOKBody struct { + + // result + Result *models.RoleInfo `json:"result,omitempty"` +} + +// Validate validates this describe role o k body +func (o *DescribeRoleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRoleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe role o k body based on the context it is used +func (o *DescribeRoleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRoleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRoleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRoleOKBody) UnmarshalBinary(b []byte) error { + var res DescribeRoleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/describe_roles_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/describe_roles_parameters.go new file mode 100644 index 0000000..d8b50db --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/describe_roles_parameters.go @@ -0,0 +1,328 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeRolesParams creates a new DescribeRolesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeRolesParams() *DescribeRolesParams { + return &DescribeRolesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeRolesParamsWithTimeout creates a new DescribeRolesParams object +// with the ability to set a timeout on a request. +func NewDescribeRolesParamsWithTimeout(timeout time.Duration) *DescribeRolesParams { + return &DescribeRolesParams{ + timeout: timeout, + } +} + +// NewDescribeRolesParamsWithContext creates a new DescribeRolesParams object +// with the ability to set a context for a request. +func NewDescribeRolesParamsWithContext(ctx context.Context) *DescribeRolesParams { + return &DescribeRolesParams{ + Context: ctx, + } +} + +// NewDescribeRolesParamsWithHTTPClient creates a new DescribeRolesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeRolesParamsWithHTTPClient(client *http.Client) *DescribeRolesParams { + return &DescribeRolesParams{ + HTTPClient: client, + } +} + +/* DescribeRolesParams contains all the parameters to send to the API endpoint + for the describe roles operation. + + Typically these are written to a http.Request. +*/ +type DescribeRolesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否显示所有 + */ + IsAll *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe roles params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRolesParams) WithDefaults() *DescribeRolesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe roles params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRolesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe roles params +func (o *DescribeRolesParams) WithTimeout(timeout time.Duration) *DescribeRolesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe roles params +func (o *DescribeRolesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe roles params +func (o *DescribeRolesParams) WithContext(ctx context.Context) *DescribeRolesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe roles params +func (o *DescribeRolesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe roles params +func (o *DescribeRolesParams) WithHTTPClient(client *http.Client) *DescribeRolesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe roles params +func (o *DescribeRolesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe roles params +func (o *DescribeRolesParams) WithAuthorization(authorization string) *DescribeRolesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe roles params +func (o *DescribeRolesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe roles params +func (o *DescribeRolesParams) WithBmpLanguage(bmpLanguage *string) *DescribeRolesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe roles params +func (o *DescribeRolesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe roles params +func (o *DescribeRolesParams) WithBmpUserID(bmpUserID *string) *DescribeRolesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe roles params +func (o *DescribeRolesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe roles params +func (o *DescribeRolesParams) WithIsAll(isAll *string) *DescribeRolesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe roles params +func (o *DescribeRolesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithPageNumber adds the pageNumber to the describe roles params +func (o *DescribeRolesParams) WithPageNumber(pageNumber *int64) *DescribeRolesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe roles params +func (o *DescribeRolesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe roles params +func (o *DescribeRolesParams) WithPageSize(pageSize *int64) *DescribeRolesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe roles params +func (o *DescribeRolesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe roles params +func (o *DescribeRolesParams) WithTraceID(traceID string) *DescribeRolesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe roles params +func (o *DescribeRolesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeRolesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/describe_roles_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/describe_roles_responses.go new file mode 100644 index 0000000..859f323 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/describe_roles_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeRolesReader is a Reader for the DescribeRoles structure. +type DescribeRolesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeRolesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeRolesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeRolesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeRolesOK creates a DescribeRolesOK with default headers values +func NewDescribeRolesOK() *DescribeRolesOK { + return &DescribeRolesOK{} +} + +/* DescribeRolesOK describes a response with status code 200, with default header values. + +A GetRoleListResult is an response struct that is used to describe get role list. +*/ +type DescribeRolesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRolesOKBody +} + +// IsSuccess returns true when this describe roles o k response has a 2xx status code +func (o *DescribeRolesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe roles o k response has a 3xx status code +func (o *DescribeRolesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe roles o k response has a 4xx status code +func (o *DescribeRolesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe roles o k response has a 5xx status code +func (o *DescribeRolesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe roles o k response a status code equal to that given +func (o *DescribeRolesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeRolesOK) Error() string { + return fmt.Sprintf("[GET /roles][%d] describeRolesOK %+v", 200, o.Payload) +} + +func (o *DescribeRolesOK) String() string { + return fmt.Sprintf("[GET /roles][%d] describeRolesOK %+v", 200, o.Payload) +} + +func (o *DescribeRolesOK) GetPayload() *DescribeRolesOKBody { + return o.Payload +} + +func (o *DescribeRolesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRolesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeRolesDefault creates a DescribeRolesDefault with default headers values +func NewDescribeRolesDefault(code int) *DescribeRolesDefault { + return &DescribeRolesDefault{ + _statusCode: code, + } +} + +/* DescribeRolesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeRolesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRolesDefaultBody +} + +// Code gets the status code for the describe roles default response +func (o *DescribeRolesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe roles default response has a 2xx status code +func (o *DescribeRolesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe roles default response has a 3xx status code +func (o *DescribeRolesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe roles default response has a 4xx status code +func (o *DescribeRolesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe roles default response has a 5xx status code +func (o *DescribeRolesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe roles default response a status code equal to that given +func (o *DescribeRolesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeRolesDefault) Error() string { + return fmt.Sprintf("[GET /roles][%d] describeRoles default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRolesDefault) String() string { + return fmt.Sprintf("[GET /roles][%d] describeRoles default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRolesDefault) GetPayload() *DescribeRolesDefaultBody { + return o.Payload +} + +func (o *DescribeRolesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRolesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeRolesDefaultBody describe roles default body +swagger:model DescribeRolesDefaultBody +*/ +type DescribeRolesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe roles default body +func (o *DescribeRolesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRolesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeRoles default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeRolesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeRoles default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRoles default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRoles default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe roles default body based on the context it is used +func (o *DescribeRolesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRolesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRoles default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRoles default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRolesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRolesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeRolesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeRolesOKBody describe roles o k body +swagger:model DescribeRolesOKBody +*/ +type DescribeRolesOKBody struct { + + // result + Result *models.RoleList `json:"result,omitempty"` +} + +// Validate validates this describe roles o k body +func (o *DescribeRolesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRolesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRolesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRolesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe roles o k body based on the context it is used +func (o *DescribeRolesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRolesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRolesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRolesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRolesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRolesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeRolesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/role_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/role_client.go new file mode 100644 index 0000000..71fe879 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/role/role_client.go @@ -0,0 +1,157 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new role API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for role API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CurrentRole(params *CurrentRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CurrentRoleOK, error) + + DescribeRole(params *DescribeRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRoleOK, error) + + DescribeRoles(params *DescribeRolesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRolesOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CurrentRole CurrentRole 获取当前登录用户的角色 +*/ +func (a *Client) CurrentRole(params *CurrentRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CurrentRoleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCurrentRoleParams() + } + op := &runtime.ClientOperation{ + ID: "currentRole", + Method: "GET", + PathPattern: "/roles/roleInfo/current", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CurrentRoleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CurrentRoleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CurrentRoleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeRole DescribeRole 获取角色详情 +*/ +func (a *Client) DescribeRole(params *DescribeRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRoleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeRoleParams() + } + op := &runtime.ClientOperation{ + ID: "describeRole", + Method: "GET", + PathPattern: "/roles/{role_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeRoleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeRoleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeRoleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeRoles DescribeRoles 获取角色列表 +*/ +func (a *Client) DescribeRoles(params *DescribeRolesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRolesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeRolesParams() + } + op := &runtime.ClientOperation{ + ID: "describeRoles", + Method: "GET", + PathPattern: "/roles", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeRolesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeRolesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeRolesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/create_user_sshkey_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/create_user_sshkey_parameters.go new file mode 100644 index 0000000..f203b27 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/create_user_sshkey_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewCreateUserSshkeyParams creates a new CreateUserSshkeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateUserSshkeyParams() *CreateUserSshkeyParams { + return &CreateUserSshkeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateUserSshkeyParamsWithTimeout creates a new CreateUserSshkeyParams object +// with the ability to set a timeout on a request. +func NewCreateUserSshkeyParamsWithTimeout(timeout time.Duration) *CreateUserSshkeyParams { + return &CreateUserSshkeyParams{ + timeout: timeout, + } +} + +// NewCreateUserSshkeyParamsWithContext creates a new CreateUserSshkeyParams object +// with the ability to set a context for a request. +func NewCreateUserSshkeyParamsWithContext(ctx context.Context) *CreateUserSshkeyParams { + return &CreateUserSshkeyParams{ + Context: ctx, + } +} + +// NewCreateUserSshkeyParamsWithHTTPClient creates a new CreateUserSshkeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateUserSshkeyParamsWithHTTPClient(client *http.Client) *CreateUserSshkeyParams { + return &CreateUserSshkeyParams{ + HTTPClient: client, + } +} + +/* CreateUserSshkeyParams contains all the parameters to send to the API endpoint + for the create user sshkey operation. + + Typically these are written to a http.Request. +*/ +type CreateUserSshkeyParams struct { + + // Body. + Body *models.CreateSshkeyRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserSshkeyParams) WithDefaults() *CreateUserSshkeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserSshkeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create user sshkey params +func (o *CreateUserSshkeyParams) WithTimeout(timeout time.Duration) *CreateUserSshkeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create user sshkey params +func (o *CreateUserSshkeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create user sshkey params +func (o *CreateUserSshkeyParams) WithContext(ctx context.Context) *CreateUserSshkeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create user sshkey params +func (o *CreateUserSshkeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create user sshkey params +func (o *CreateUserSshkeyParams) WithHTTPClient(client *http.Client) *CreateUserSshkeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create user sshkey params +func (o *CreateUserSshkeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create user sshkey params +func (o *CreateUserSshkeyParams) WithBody(body *models.CreateSshkeyRequest) *CreateUserSshkeyParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create user sshkey params +func (o *CreateUserSshkeyParams) SetBody(body *models.CreateSshkeyRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create user sshkey params +func (o *CreateUserSshkeyParams) WithAuthorization(authorization string) *CreateUserSshkeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create user sshkey params +func (o *CreateUserSshkeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create user sshkey params +func (o *CreateUserSshkeyParams) WithBmpLanguage(bmpLanguage *string) *CreateUserSshkeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create user sshkey params +func (o *CreateUserSshkeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create user sshkey params +func (o *CreateUserSshkeyParams) WithBmpUserID(bmpUserID *string) *CreateUserSshkeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create user sshkey params +func (o *CreateUserSshkeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create user sshkey params +func (o *CreateUserSshkeyParams) WithTraceID(traceID string) *CreateUserSshkeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create user sshkey params +func (o *CreateUserSshkeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateUserSshkeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/create_user_sshkey_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/create_user_sshkey_responses.go new file mode 100644 index 0000000..8d03aaf --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/create_user_sshkey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// CreateUserSshkeyReader is a Reader for the CreateUserSshkey structure. +type CreateUserSshkeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateUserSshkeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateUserSshkeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateUserSshkeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateUserSshkeyOK creates a CreateUserSshkeyOK with default headers values +func NewCreateUserSshkeyOK() *CreateUserSshkeyOK { + return &CreateUserSshkeyOK{} +} + +/* CreateUserSshkeyOK describes a response with status code 200, with default header values. + +A CreateUserSshkeyResult is an response struct that is used to describe create sshkey result. +*/ +type CreateUserSshkeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserSshkeyOKBody +} + +// IsSuccess returns true when this create user sshkey o k response has a 2xx status code +func (o *CreateUserSshkeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create user sshkey o k response has a 3xx status code +func (o *CreateUserSshkeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create user sshkey o k response has a 4xx status code +func (o *CreateUserSshkeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create user sshkey o k response has a 5xx status code +func (o *CreateUserSshkeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create user sshkey o k response a status code equal to that given +func (o *CreateUserSshkeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateUserSshkeyOK) Error() string { + return fmt.Sprintf("[POST /user/sshkeys][%d] createUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *CreateUserSshkeyOK) String() string { + return fmt.Sprintf("[POST /user/sshkeys][%d] createUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *CreateUserSshkeyOK) GetPayload() *CreateUserSshkeyOKBody { + return o.Payload +} + +func (o *CreateUserSshkeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserSshkeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateUserSshkeyDefault creates a CreateUserSshkeyDefault with default headers values +func NewCreateUserSshkeyDefault(code int) *CreateUserSshkeyDefault { + return &CreateUserSshkeyDefault{ + _statusCode: code, + } +} + +/* CreateUserSshkeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateUserSshkeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserSshkeyDefaultBody +} + +// Code gets the status code for the create user sshkey default response +func (o *CreateUserSshkeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create user sshkey default response has a 2xx status code +func (o *CreateUserSshkeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create user sshkey default response has a 3xx status code +func (o *CreateUserSshkeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create user sshkey default response has a 4xx status code +func (o *CreateUserSshkeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create user sshkey default response has a 5xx status code +func (o *CreateUserSshkeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create user sshkey default response a status code equal to that given +func (o *CreateUserSshkeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateUserSshkeyDefault) Error() string { + return fmt.Sprintf("[POST /user/sshkeys][%d] createUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserSshkeyDefault) String() string { + return fmt.Sprintf("[POST /user/sshkeys][%d] createUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserSshkeyDefault) GetPayload() *CreateUserSshkeyDefaultBody { + return o.Payload +} + +func (o *CreateUserSshkeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserSshkeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateUserSshkeyDefaultBody create user sshkey default body +swagger:model CreateUserSshkeyDefaultBody +*/ +type CreateUserSshkeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create user sshkey default body +func (o *CreateUserSshkeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserSshkeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createUserSshkey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateUserSshkeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createUserSshkey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user sshkey default body based on the context it is used +func (o *CreateUserSshkeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserSshkeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserSshkeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserSshkeyDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateUserSshkeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateUserSshkeyOKBody create user sshkey o k body +swagger:model CreateUserSshkeyOKBody +*/ +type CreateUserSshkeyOKBody struct { + + // result + Result *models.SshkeyID `json:"result,omitempty"` +} + +// Validate validates this create user sshkey o k body +func (o *CreateUserSshkeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserSshkeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user sshkey o k body based on the context it is used +func (o *CreateUserSshkeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserSshkeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserSshkeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserSshkeyOKBody) UnmarshalBinary(b []byte) error { + var res CreateUserSshkeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/delete_user_sshkey_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/delete_user_sshkey_parameters.go new file mode 100644 index 0000000..9fdcc89 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/delete_user_sshkey_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteUserSshkeyParams creates a new DeleteUserSshkeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteUserSshkeyParams() *DeleteUserSshkeyParams { + return &DeleteUserSshkeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteUserSshkeyParamsWithTimeout creates a new DeleteUserSshkeyParams object +// with the ability to set a timeout on a request. +func NewDeleteUserSshkeyParamsWithTimeout(timeout time.Duration) *DeleteUserSshkeyParams { + return &DeleteUserSshkeyParams{ + timeout: timeout, + } +} + +// NewDeleteUserSshkeyParamsWithContext creates a new DeleteUserSshkeyParams object +// with the ability to set a context for a request. +func NewDeleteUserSshkeyParamsWithContext(ctx context.Context) *DeleteUserSshkeyParams { + return &DeleteUserSshkeyParams{ + Context: ctx, + } +} + +// NewDeleteUserSshkeyParamsWithHTTPClient creates a new DeleteUserSshkeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteUserSshkeyParamsWithHTTPClient(client *http.Client) *DeleteUserSshkeyParams { + return &DeleteUserSshkeyParams{ + HTTPClient: client, + } +} + +/* DeleteUserSshkeyParams contains all the parameters to send to the API endpoint + for the delete user sshkey operation. + + Typically these are written to a http.Request. +*/ +type DeleteUserSshkeyParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // SshkeyID. + SshkeyID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserSshkeyParams) WithDefaults() *DeleteUserSshkeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserSshkeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithTimeout(timeout time.Duration) *DeleteUserSshkeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithContext(ctx context.Context) *DeleteUserSshkeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithHTTPClient(client *http.Client) *DeleteUserSshkeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithAuthorization(authorization string) *DeleteUserSshkeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithBmpLanguage(bmpLanguage *string) *DeleteUserSshkeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithBmpUserID(bmpUserID *string) *DeleteUserSshkeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithSshkeyID adds the sshkeyID to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithSshkeyID(sshkeyID string) *DeleteUserSshkeyParams { + o.SetSshkeyID(sshkeyID) + return o +} + +// SetSshkeyID adds the sshkeyId to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetSshkeyID(sshkeyID string) { + o.SshkeyID = sshkeyID +} + +// WithTraceID adds the traceID to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithTraceID(traceID string) *DeleteUserSshkeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteUserSshkeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param sshkey_id + if err := r.SetPathParam("sshkey_id", o.SshkeyID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/delete_user_sshkey_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/delete_user_sshkey_responses.go new file mode 100644 index 0000000..97272d1 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/delete_user_sshkey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DeleteUserSshkeyReader is a Reader for the DeleteUserSshkey structure. +type DeleteUserSshkeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteUserSshkeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteUserSshkeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteUserSshkeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteUserSshkeyOK creates a DeleteUserSshkeyOK with default headers values +func NewDeleteUserSshkeyOK() *DeleteUserSshkeyOK { + return &DeleteUserSshkeyOK{} +} + +/* DeleteUserSshkeyOK describes a response with status code 200, with default header values. + +A DeleteUserSshkeyResult is an response struct that is used to describe delete sshkey result. +*/ +type DeleteUserSshkeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserSshkeyOKBody +} + +// IsSuccess returns true when this delete user sshkey o k response has a 2xx status code +func (o *DeleteUserSshkeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete user sshkey o k response has a 3xx status code +func (o *DeleteUserSshkeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete user sshkey o k response has a 4xx status code +func (o *DeleteUserSshkeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete user sshkey o k response has a 5xx status code +func (o *DeleteUserSshkeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete user sshkey o k response a status code equal to that given +func (o *DeleteUserSshkeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteUserSshkeyOK) Error() string { + return fmt.Sprintf("[DELETE /user/sshkeys/{sshkey_id}][%d] deleteUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *DeleteUserSshkeyOK) String() string { + return fmt.Sprintf("[DELETE /user/sshkeys/{sshkey_id}][%d] deleteUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *DeleteUserSshkeyOK) GetPayload() *DeleteUserSshkeyOKBody { + return o.Payload +} + +func (o *DeleteUserSshkeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserSshkeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteUserSshkeyDefault creates a DeleteUserSshkeyDefault with default headers values +func NewDeleteUserSshkeyDefault(code int) *DeleteUserSshkeyDefault { + return &DeleteUserSshkeyDefault{ + _statusCode: code, + } +} + +/* DeleteUserSshkeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteUserSshkeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserSshkeyDefaultBody +} + +// Code gets the status code for the delete user sshkey default response +func (o *DeleteUserSshkeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete user sshkey default response has a 2xx status code +func (o *DeleteUserSshkeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete user sshkey default response has a 3xx status code +func (o *DeleteUserSshkeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete user sshkey default response has a 4xx status code +func (o *DeleteUserSshkeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete user sshkey default response has a 5xx status code +func (o *DeleteUserSshkeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete user sshkey default response a status code equal to that given +func (o *DeleteUserSshkeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteUserSshkeyDefault) Error() string { + return fmt.Sprintf("[DELETE /user/sshkeys/{sshkey_id}][%d] deleteUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserSshkeyDefault) String() string { + return fmt.Sprintf("[DELETE /user/sshkeys/{sshkey_id}][%d] deleteUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserSshkeyDefault) GetPayload() *DeleteUserSshkeyDefaultBody { + return o.Payload +} + +func (o *DeleteUserSshkeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserSshkeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteUserSshkeyDefaultBody delete user sshkey default body +swagger:model DeleteUserSshkeyDefaultBody +*/ +type DeleteUserSshkeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete user sshkey default body +func (o *DeleteUserSshkeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserSshkeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserSshkey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteUserSshkeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserSshkey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user sshkey default body based on the context it is used +func (o *DeleteUserSshkeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserSshkeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserSshkeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserSshkeyDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteUserSshkeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteUserSshkeyOKBody delete user sshkey o k body +swagger:model DeleteUserSshkeyOKBody +*/ +type DeleteUserSshkeyOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete user sshkey o k body +func (o *DeleteUserSshkeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserSshkeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user sshkey o k body based on the context it is used +func (o *DeleteUserSshkeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserSshkeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserSshkeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserSshkeyOKBody) UnmarshalBinary(b []byte) error { + var res DeleteUserSshkeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/describe_user_ssh_key_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/describe_user_ssh_key_parameters.go new file mode 100644 index 0000000..0039fc8 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/describe_user_ssh_key_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeUserSSHKeyParams creates a new DescribeUserSSHKeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserSSHKeyParams() *DescribeUserSSHKeyParams { + return &DescribeUserSSHKeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserSSHKeyParamsWithTimeout creates a new DescribeUserSSHKeyParams object +// with the ability to set a timeout on a request. +func NewDescribeUserSSHKeyParamsWithTimeout(timeout time.Duration) *DescribeUserSSHKeyParams { + return &DescribeUserSSHKeyParams{ + timeout: timeout, + } +} + +// NewDescribeUserSSHKeyParamsWithContext creates a new DescribeUserSSHKeyParams object +// with the ability to set a context for a request. +func NewDescribeUserSSHKeyParamsWithContext(ctx context.Context) *DescribeUserSSHKeyParams { + return &DescribeUserSSHKeyParams{ + Context: ctx, + } +} + +// NewDescribeUserSSHKeyParamsWithHTTPClient creates a new DescribeUserSSHKeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserSSHKeyParamsWithHTTPClient(client *http.Client) *DescribeUserSSHKeyParams { + return &DescribeUserSSHKeyParams{ + HTTPClient: client, + } +} + +/* DescribeUserSSHKeyParams contains all the parameters to send to the API endpoint + for the describe user Ssh key operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserSSHKeyParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // SshkeyID. + SshkeyID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user Ssh key params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserSSHKeyParams) WithDefaults() *DescribeUserSSHKeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user Ssh key params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserSSHKeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithTimeout(timeout time.Duration) *DescribeUserSSHKeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithContext(ctx context.Context) *DescribeUserSSHKeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithHTTPClient(client *http.Client) *DescribeUserSSHKeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithAuthorization(authorization string) *DescribeUserSSHKeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserSSHKeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithBmpUserID(bmpUserID *string) *DescribeUserSSHKeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithSshkeyID adds the sshkeyID to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithSshkeyID(sshkeyID string) *DescribeUserSSHKeyParams { + o.SetSshkeyID(sshkeyID) + return o +} + +// SetSshkeyID adds the sshkeyId to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetSshkeyID(sshkeyID string) { + o.SshkeyID = sshkeyID +} + +// WithTraceID adds the traceID to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithTraceID(traceID string) *DescribeUserSSHKeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserSSHKeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param sshkey_id + if err := r.SetPathParam("sshkey_id", o.SshkeyID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/describe_user_ssh_key_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/describe_user_ssh_key_responses.go new file mode 100644 index 0000000..992e2b2 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/describe_user_ssh_key_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeUserSSHKeyReader is a Reader for the DescribeUserSSHKey structure. +type DescribeUserSSHKeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserSSHKeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserSSHKeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserSSHKeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserSSHKeyOK creates a DescribeUserSSHKeyOK with default headers values +func NewDescribeUserSSHKeyOK() *DescribeUserSSHKeyOK { + return &DescribeUserSSHKeyOK{} +} + +/* DescribeUserSSHKeyOK describes a response with status code 200, with default header values. + +A DescribeUserSshKeyResult is an response struct that is used to describe sshkey. +*/ +type DescribeUserSSHKeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserSSHKeyOKBody +} + +// IsSuccess returns true when this describe user Ssh key o k response has a 2xx status code +func (o *DescribeUserSSHKeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user Ssh key o k response has a 3xx status code +func (o *DescribeUserSSHKeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user Ssh key o k response has a 4xx status code +func (o *DescribeUserSSHKeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user Ssh key o k response has a 5xx status code +func (o *DescribeUserSSHKeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user Ssh key o k response a status code equal to that given +func (o *DescribeUserSSHKeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserSSHKeyOK) Error() string { + return fmt.Sprintf("[GET /user/sshkeys/{sshkey_id}][%d] describeUserSshKeyOK %+v", 200, o.Payload) +} + +func (o *DescribeUserSSHKeyOK) String() string { + return fmt.Sprintf("[GET /user/sshkeys/{sshkey_id}][%d] describeUserSshKeyOK %+v", 200, o.Payload) +} + +func (o *DescribeUserSSHKeyOK) GetPayload() *DescribeUserSSHKeyOKBody { + return o.Payload +} + +func (o *DescribeUserSSHKeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserSSHKeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserSSHKeyDefault creates a DescribeUserSSHKeyDefault with default headers values +func NewDescribeUserSSHKeyDefault(code int) *DescribeUserSSHKeyDefault { + return &DescribeUserSSHKeyDefault{ + _statusCode: code, + } +} + +/* DescribeUserSSHKeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserSSHKeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserSSHKeyDefaultBody +} + +// Code gets the status code for the describe user Ssh key default response +func (o *DescribeUserSSHKeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user Ssh key default response has a 2xx status code +func (o *DescribeUserSSHKeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user Ssh key default response has a 3xx status code +func (o *DescribeUserSSHKeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user Ssh key default response has a 4xx status code +func (o *DescribeUserSSHKeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user Ssh key default response has a 5xx status code +func (o *DescribeUserSSHKeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user Ssh key default response a status code equal to that given +func (o *DescribeUserSSHKeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserSSHKeyDefault) Error() string { + return fmt.Sprintf("[GET /user/sshkeys/{sshkey_id}][%d] describeUserSshKey default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserSSHKeyDefault) String() string { + return fmt.Sprintf("[GET /user/sshkeys/{sshkey_id}][%d] describeUserSshKey default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserSSHKeyDefault) GetPayload() *DescribeUserSSHKeyDefaultBody { + return o.Payload +} + +func (o *DescribeUserSSHKeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserSSHKeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserSSHKeyDefaultBody describe user SSH key default body +swagger:model DescribeUserSSHKeyDefaultBody +*/ +type DescribeUserSSHKeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user SSH key default body +func (o *DescribeUserSSHKeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserSshKey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserSSHKeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserSshKey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user SSH key default body based on the context it is used +func (o *DescribeUserSSHKeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserSSHKeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserSSHKeyDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserSSHKeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserSSHKeyOKBody describe user SSH key o k body +swagger:model DescribeUserSSHKeyOKBody +*/ +type DescribeUserSSHKeyOKBody struct { + + // result + Result *models.SshkeyInfo `json:"result,omitempty"` +} + +// Validate validates this describe user SSH key o k body +func (o *DescribeUserSSHKeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user SSH key o k body based on the context it is used +func (o *DescribeUserSSHKeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserSSHKeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserSSHKeyOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserSSHKeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/describe_user_ssh_keys_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/describe_user_ssh_keys_parameters.go new file mode 100644 index 0000000..78cbf1f --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/describe_user_ssh_keys_parameters.go @@ -0,0 +1,362 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeUserSSHKeysParams creates a new DescribeUserSSHKeysParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserSSHKeysParams() *DescribeUserSSHKeysParams { + return &DescribeUserSSHKeysParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserSSHKeysParamsWithTimeout creates a new DescribeUserSSHKeysParams object +// with the ability to set a timeout on a request. +func NewDescribeUserSSHKeysParamsWithTimeout(timeout time.Duration) *DescribeUserSSHKeysParams { + return &DescribeUserSSHKeysParams{ + timeout: timeout, + } +} + +// NewDescribeUserSSHKeysParamsWithContext creates a new DescribeUserSSHKeysParams object +// with the ability to set a context for a request. +func NewDescribeUserSSHKeysParamsWithContext(ctx context.Context) *DescribeUserSSHKeysParams { + return &DescribeUserSSHKeysParams{ + Context: ctx, + } +} + +// NewDescribeUserSSHKeysParamsWithHTTPClient creates a new DescribeUserSSHKeysParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserSSHKeysParamsWithHTTPClient(client *http.Client) *DescribeUserSSHKeysParams { + return &DescribeUserSSHKeysParams{ + HTTPClient: client, + } +} + +/* DescribeUserSSHKeysParams contains all the parameters to send to the API endpoint + for the describe user Ssh keys operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserSSHKeysParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否显示全部 + */ + IsAll *string + + /* Name. + + 秘钥名称 + */ + Name *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user Ssh keys params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserSSHKeysParams) WithDefaults() *DescribeUserSSHKeysParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user Ssh keys params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserSSHKeysParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithTimeout(timeout time.Duration) *DescribeUserSSHKeysParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithContext(ctx context.Context) *DescribeUserSSHKeysParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithHTTPClient(client *http.Client) *DescribeUserSSHKeysParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithAuthorization(authorization string) *DescribeUserSSHKeysParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserSSHKeysParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithBmpUserID(bmpUserID *string) *DescribeUserSSHKeysParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithIsAll(isAll *string) *DescribeUserSSHKeysParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithName adds the name to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithName(name *string) *DescribeUserSSHKeysParams { + o.SetName(name) + return o +} + +// SetName adds the name to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetName(name *string) { + o.Name = name +} + +// WithPageNumber adds the pageNumber to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithPageNumber(pageNumber *int64) *DescribeUserSSHKeysParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithPageSize(pageSize *int64) *DescribeUserSSHKeysParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithTraceID(traceID string) *DescribeUserSSHKeysParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserSSHKeysParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/describe_user_ssh_keys_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/describe_user_ssh_keys_responses.go new file mode 100644 index 0000000..e8e7fb0 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/describe_user_ssh_keys_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeUserSSHKeysReader is a Reader for the DescribeUserSSHKeys structure. +type DescribeUserSSHKeysReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserSSHKeysReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserSSHKeysOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserSSHKeysDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserSSHKeysOK creates a DescribeUserSSHKeysOK with default headers values +func NewDescribeUserSSHKeysOK() *DescribeUserSSHKeysOK { + return &DescribeUserSSHKeysOK{} +} + +/* DescribeUserSSHKeysOK describes a response with status code 200, with default header values. + +A DescribeUserSshKeysResult is an response struct that is used to describe get sshkey list. +*/ +type DescribeUserSSHKeysOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserSSHKeysOKBody +} + +// IsSuccess returns true when this describe user Ssh keys o k response has a 2xx status code +func (o *DescribeUserSSHKeysOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user Ssh keys o k response has a 3xx status code +func (o *DescribeUserSSHKeysOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user Ssh keys o k response has a 4xx status code +func (o *DescribeUserSSHKeysOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user Ssh keys o k response has a 5xx status code +func (o *DescribeUserSSHKeysOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user Ssh keys o k response a status code equal to that given +func (o *DescribeUserSSHKeysOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserSSHKeysOK) Error() string { + return fmt.Sprintf("[GET /user/sshkeys][%d] describeUserSshKeysOK %+v", 200, o.Payload) +} + +func (o *DescribeUserSSHKeysOK) String() string { + return fmt.Sprintf("[GET /user/sshkeys][%d] describeUserSshKeysOK %+v", 200, o.Payload) +} + +func (o *DescribeUserSSHKeysOK) GetPayload() *DescribeUserSSHKeysOKBody { + return o.Payload +} + +func (o *DescribeUserSSHKeysOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserSSHKeysOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserSSHKeysDefault creates a DescribeUserSSHKeysDefault with default headers values +func NewDescribeUserSSHKeysDefault(code int) *DescribeUserSSHKeysDefault { + return &DescribeUserSSHKeysDefault{ + _statusCode: code, + } +} + +/* DescribeUserSSHKeysDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserSSHKeysDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserSSHKeysDefaultBody +} + +// Code gets the status code for the describe user Ssh keys default response +func (o *DescribeUserSSHKeysDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user Ssh keys default response has a 2xx status code +func (o *DescribeUserSSHKeysDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user Ssh keys default response has a 3xx status code +func (o *DescribeUserSSHKeysDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user Ssh keys default response has a 4xx status code +func (o *DescribeUserSSHKeysDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user Ssh keys default response has a 5xx status code +func (o *DescribeUserSSHKeysDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user Ssh keys default response a status code equal to that given +func (o *DescribeUserSSHKeysDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserSSHKeysDefault) Error() string { + return fmt.Sprintf("[GET /user/sshkeys][%d] describeUserSshKeys default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserSSHKeysDefault) String() string { + return fmt.Sprintf("[GET /user/sshkeys][%d] describeUserSshKeys default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserSSHKeysDefault) GetPayload() *DescribeUserSSHKeysDefaultBody { + return o.Payload +} + +func (o *DescribeUserSSHKeysDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserSSHKeysDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserSSHKeysDefaultBody describe user SSH keys default body +swagger:model DescribeUserSSHKeysDefaultBody +*/ +type DescribeUserSSHKeysDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user SSH keys default body +func (o *DescribeUserSSHKeysDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeysDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserSshKeys default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserSSHKeysDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserSshKeys default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeys default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeys default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user SSH keys default body based on the context it is used +func (o *DescribeUserSSHKeysDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeysDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeys default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeys default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserSSHKeysDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserSSHKeysDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserSSHKeysDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserSSHKeysOKBody describe user SSH keys o k body +swagger:model DescribeUserSSHKeysOKBody +*/ +type DescribeUserSSHKeysOKBody struct { + + // result + Result *models.SshkeyList `json:"result,omitempty"` +} + +// Validate validates this describe user SSH keys o k body +func (o *DescribeUserSSHKeysOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeysOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeysOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeysOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user SSH keys o k body based on the context it is used +func (o *DescribeUserSSHKeysOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeysOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeysOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeysOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserSSHKeysOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserSSHKeysOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserSSHKeysOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/get_instances_by_sshkey_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/get_instances_by_sshkey_parameters.go new file mode 100644 index 0000000..d12c7d1 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/get_instances_by_sshkey_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetInstancesBySshkeyParams creates a new GetInstancesBySshkeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetInstancesBySshkeyParams() *GetInstancesBySshkeyParams { + return &GetInstancesBySshkeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetInstancesBySshkeyParamsWithTimeout creates a new GetInstancesBySshkeyParams object +// with the ability to set a timeout on a request. +func NewGetInstancesBySshkeyParamsWithTimeout(timeout time.Duration) *GetInstancesBySshkeyParams { + return &GetInstancesBySshkeyParams{ + timeout: timeout, + } +} + +// NewGetInstancesBySshkeyParamsWithContext creates a new GetInstancesBySshkeyParams object +// with the ability to set a context for a request. +func NewGetInstancesBySshkeyParamsWithContext(ctx context.Context) *GetInstancesBySshkeyParams { + return &GetInstancesBySshkeyParams{ + Context: ctx, + } +} + +// NewGetInstancesBySshkeyParamsWithHTTPClient creates a new GetInstancesBySshkeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetInstancesBySshkeyParamsWithHTTPClient(client *http.Client) *GetInstancesBySshkeyParams { + return &GetInstancesBySshkeyParams{ + HTTPClient: client, + } +} + +/* GetInstancesBySshkeyParams contains all the parameters to send to the API endpoint + for the get instances by sshkey operation. + + Typically these are written to a http.Request. +*/ +type GetInstancesBySshkeyParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // SshkeyID. + SshkeyID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get instances by sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetInstancesBySshkeyParams) WithDefaults() *GetInstancesBySshkeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get instances by sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetInstancesBySshkeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithTimeout(timeout time.Duration) *GetInstancesBySshkeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithContext(ctx context.Context) *GetInstancesBySshkeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithHTTPClient(client *http.Client) *GetInstancesBySshkeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithAuthorization(authorization string) *GetInstancesBySshkeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithBmpLanguage(bmpLanguage *string) *GetInstancesBySshkeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithBmpUserID(bmpUserID *string) *GetInstancesBySshkeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithSshkeyID adds the sshkeyID to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithSshkeyID(sshkeyID string) *GetInstancesBySshkeyParams { + o.SetSshkeyID(sshkeyID) + return o +} + +// SetSshkeyID adds the sshkeyId to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetSshkeyID(sshkeyID string) { + o.SshkeyID = sshkeyID +} + +// WithTraceID adds the traceID to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithTraceID(traceID string) *GetInstancesBySshkeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetInstancesBySshkeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param sshkey_id + if err := r.SetPathParam("sshkey_id", o.SshkeyID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/get_instances_by_sshkey_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/get_instances_by_sshkey_responses.go new file mode 100644 index 0000000..33df91e --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/get_instances_by_sshkey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// GetInstancesBySshkeyReader is a Reader for the GetInstancesBySshkey structure. +type GetInstancesBySshkeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetInstancesBySshkeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetInstancesBySshkeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetInstancesBySshkeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetInstancesBySshkeyOK creates a GetInstancesBySshkeyOK with default headers values +func NewGetInstancesBySshkeyOK() *GetInstancesBySshkeyOK { + return &GetInstancesBySshkeyOK{} +} + +/* GetInstancesBySshkeyOK describes a response with status code 200, with default header values. + +A GetInstancesBySshkeyResult is an response struct that is used to get instance list by sshkey. +*/ +type GetInstancesBySshkeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetInstancesBySshkeyOKBody +} + +// IsSuccess returns true when this get instances by sshkey o k response has a 2xx status code +func (o *GetInstancesBySshkeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get instances by sshkey o k response has a 3xx status code +func (o *GetInstancesBySshkeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get instances by sshkey o k response has a 4xx status code +func (o *GetInstancesBySshkeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get instances by sshkey o k response has a 5xx status code +func (o *GetInstancesBySshkeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get instances by sshkey o k response a status code equal to that given +func (o *GetInstancesBySshkeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *GetInstancesBySshkeyOK) Error() string { + return fmt.Sprintf("[GET /user/sshkeys/instances/{sshkey_id}][%d] getInstancesBySshkeyOK %+v", 200, o.Payload) +} + +func (o *GetInstancesBySshkeyOK) String() string { + return fmt.Sprintf("[GET /user/sshkeys/instances/{sshkey_id}][%d] getInstancesBySshkeyOK %+v", 200, o.Payload) +} + +func (o *GetInstancesBySshkeyOK) GetPayload() *GetInstancesBySshkeyOKBody { + return o.Payload +} + +func (o *GetInstancesBySshkeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetInstancesBySshkeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetInstancesBySshkeyDefault creates a GetInstancesBySshkeyDefault with default headers values +func NewGetInstancesBySshkeyDefault(code int) *GetInstancesBySshkeyDefault { + return &GetInstancesBySshkeyDefault{ + _statusCode: code, + } +} + +/* GetInstancesBySshkeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type GetInstancesBySshkeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetInstancesBySshkeyDefaultBody +} + +// Code gets the status code for the get instances by sshkey default response +func (o *GetInstancesBySshkeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this get instances by sshkey default response has a 2xx status code +func (o *GetInstancesBySshkeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get instances by sshkey default response has a 3xx status code +func (o *GetInstancesBySshkeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get instances by sshkey default response has a 4xx status code +func (o *GetInstancesBySshkeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get instances by sshkey default response has a 5xx status code +func (o *GetInstancesBySshkeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get instances by sshkey default response a status code equal to that given +func (o *GetInstancesBySshkeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *GetInstancesBySshkeyDefault) Error() string { + return fmt.Sprintf("[GET /user/sshkeys/instances/{sshkey_id}][%d] getInstancesBySshkey default %+v", o._statusCode, o.Payload) +} + +func (o *GetInstancesBySshkeyDefault) String() string { + return fmt.Sprintf("[GET /user/sshkeys/instances/{sshkey_id}][%d] getInstancesBySshkey default %+v", o._statusCode, o.Payload) +} + +func (o *GetInstancesBySshkeyDefault) GetPayload() *GetInstancesBySshkeyDefaultBody { + return o.Payload +} + +func (o *GetInstancesBySshkeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetInstancesBySshkeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*GetInstancesBySshkeyDefaultBody get instances by sshkey default body +swagger:model GetInstancesBySshkeyDefaultBody +*/ +type GetInstancesBySshkeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this get instances by sshkey default body +func (o *GetInstancesBySshkeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetInstancesBySshkeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("getInstancesBySshkey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *GetInstancesBySshkeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("getInstancesBySshkey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getInstancesBySshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getInstancesBySshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get instances by sshkey default body based on the context it is used +func (o *GetInstancesBySshkeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetInstancesBySshkeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getInstancesBySshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getInstancesBySshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetInstancesBySshkeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetInstancesBySshkeyDefaultBody) UnmarshalBinary(b []byte) error { + var res GetInstancesBySshkeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*GetInstancesBySshkeyOKBody get instances by sshkey o k body +swagger:model GetInstancesBySshkeyOKBody +*/ +type GetInstancesBySshkeyOKBody struct { + + // result + Result *models.InstancesSshkeyInfoResponse `json:"result,omitempty"` +} + +// Validate validates this get instances by sshkey o k body +func (o *GetInstancesBySshkeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetInstancesBySshkeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getInstancesBySshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getInstancesBySshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get instances by sshkey o k body based on the context it is used +func (o *GetInstancesBySshkeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetInstancesBySshkeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getInstancesBySshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getInstancesBySshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetInstancesBySshkeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetInstancesBySshkeyOKBody) UnmarshalBinary(b []byte) error { + var res GetInstancesBySshkeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/modify_user_sshkey_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/modify_user_sshkey_parameters.go new file mode 100644 index 0000000..1ae4926 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/modify_user_sshkey_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewModifyUserSshkeyParams creates a new ModifyUserSshkeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyUserSshkeyParams() *ModifyUserSshkeyParams { + return &ModifyUserSshkeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyUserSshkeyParamsWithTimeout creates a new ModifyUserSshkeyParams object +// with the ability to set a timeout on a request. +func NewModifyUserSshkeyParamsWithTimeout(timeout time.Duration) *ModifyUserSshkeyParams { + return &ModifyUserSshkeyParams{ + timeout: timeout, + } +} + +// NewModifyUserSshkeyParamsWithContext creates a new ModifyUserSshkeyParams object +// with the ability to set a context for a request. +func NewModifyUserSshkeyParamsWithContext(ctx context.Context) *ModifyUserSshkeyParams { + return &ModifyUserSshkeyParams{ + Context: ctx, + } +} + +// NewModifyUserSshkeyParamsWithHTTPClient creates a new ModifyUserSshkeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyUserSshkeyParamsWithHTTPClient(client *http.Client) *ModifyUserSshkeyParams { + return &ModifyUserSshkeyParams{ + HTTPClient: client, + } +} + +/* ModifyUserSshkeyParams contains all the parameters to send to the API endpoint + for the modify user sshkey operation. + + Typically these are written to a http.Request. +*/ +type ModifyUserSshkeyParams struct { + + // Body. + Body *models.ModifySshkeyRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // SshkeyID. + SshkeyID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserSshkeyParams) WithDefaults() *ModifyUserSshkeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserSshkeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithTimeout(timeout time.Duration) *ModifyUserSshkeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithContext(ctx context.Context) *ModifyUserSshkeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithHTTPClient(client *http.Client) *ModifyUserSshkeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithBody(body *models.ModifySshkeyRequest) *ModifyUserSshkeyParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetBody(body *models.ModifySshkeyRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithAuthorization(authorization string) *ModifyUserSshkeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithBmpLanguage(bmpLanguage *string) *ModifyUserSshkeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithBmpUserID(bmpUserID *string) *ModifyUserSshkeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithSshkeyID adds the sshkeyID to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithSshkeyID(sshkeyID string) *ModifyUserSshkeyParams { + o.SetSshkeyID(sshkeyID) + return o +} + +// SetSshkeyID adds the sshkeyId to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetSshkeyID(sshkeyID string) { + o.SshkeyID = sshkeyID +} + +// WithTraceID adds the traceID to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithTraceID(traceID string) *ModifyUserSshkeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyUserSshkeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param sshkey_id + if err := r.SetPathParam("sshkey_id", o.SshkeyID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/modify_user_sshkey_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/modify_user_sshkey_responses.go new file mode 100644 index 0000000..bbdc03d --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/modify_user_sshkey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// ModifyUserSshkeyReader is a Reader for the ModifyUserSshkey structure. +type ModifyUserSshkeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyUserSshkeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyUserSshkeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyUserSshkeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyUserSshkeyOK creates a ModifyUserSshkeyOK with default headers values +func NewModifyUserSshkeyOK() *ModifyUserSshkeyOK { + return &ModifyUserSshkeyOK{} +} + +/* ModifyUserSshkeyOK describes a response with status code 200, with default header values. + +A ModifyUserSshkeyResult is an response struct that is used to modify sshkey result. +*/ +type ModifyUserSshkeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserSshkeyOKBody +} + +// IsSuccess returns true when this modify user sshkey o k response has a 2xx status code +func (o *ModifyUserSshkeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify user sshkey o k response has a 3xx status code +func (o *ModifyUserSshkeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify user sshkey o k response has a 4xx status code +func (o *ModifyUserSshkeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify user sshkey o k response has a 5xx status code +func (o *ModifyUserSshkeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify user sshkey o k response a status code equal to that given +func (o *ModifyUserSshkeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyUserSshkeyOK) Error() string { + return fmt.Sprintf("[PUT /user/sshkeys/{sshkey_id}][%d] modifyUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *ModifyUserSshkeyOK) String() string { + return fmt.Sprintf("[PUT /user/sshkeys/{sshkey_id}][%d] modifyUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *ModifyUserSshkeyOK) GetPayload() *ModifyUserSshkeyOKBody { + return o.Payload +} + +func (o *ModifyUserSshkeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserSshkeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyUserSshkeyDefault creates a ModifyUserSshkeyDefault with default headers values +func NewModifyUserSshkeyDefault(code int) *ModifyUserSshkeyDefault { + return &ModifyUserSshkeyDefault{ + _statusCode: code, + } +} + +/* ModifyUserSshkeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyUserSshkeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserSshkeyDefaultBody +} + +// Code gets the status code for the modify user sshkey default response +func (o *ModifyUserSshkeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify user sshkey default response has a 2xx status code +func (o *ModifyUserSshkeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify user sshkey default response has a 3xx status code +func (o *ModifyUserSshkeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify user sshkey default response has a 4xx status code +func (o *ModifyUserSshkeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify user sshkey default response has a 5xx status code +func (o *ModifyUserSshkeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify user sshkey default response a status code equal to that given +func (o *ModifyUserSshkeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyUserSshkeyDefault) Error() string { + return fmt.Sprintf("[PUT /user/sshkeys/{sshkey_id}][%d] modifyUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserSshkeyDefault) String() string { + return fmt.Sprintf("[PUT /user/sshkeys/{sshkey_id}][%d] modifyUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserSshkeyDefault) GetPayload() *ModifyUserSshkeyDefaultBody { + return o.Payload +} + +func (o *ModifyUserSshkeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserSshkeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyUserSshkeyDefaultBody modify user sshkey default body +swagger:model ModifyUserSshkeyDefaultBody +*/ +type ModifyUserSshkeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify user sshkey default body +func (o *ModifyUserSshkeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserSshkeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserSshkey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyUserSshkeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserSshkey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user sshkey default body based on the context it is used +func (o *ModifyUserSshkeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserSshkeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserSshkeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserSshkeyDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyUserSshkeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyUserSshkeyOKBody modify user sshkey o k body +swagger:model ModifyUserSshkeyOKBody +*/ +type ModifyUserSshkeyOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify user sshkey o k body +func (o *ModifyUserSshkeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserSshkeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user sshkey o k body based on the context it is used +func (o *ModifyUserSshkeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserSshkeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserSshkeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserSshkeyOKBody) UnmarshalBinary(b []byte) error { + var res ModifyUserSshkeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/sshkey_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/sshkey_client.go new file mode 100644 index 0000000..16c7309 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/sshkey/sshkey_client.go @@ -0,0 +1,277 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new sshkey API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for sshkey API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateUserSshkey(params *CreateUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserSshkeyOK, error) + + DeleteUserSshkey(params *DeleteUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserSshkeyOK, error) + + DescribeUserSSHKey(params *DescribeUserSSHKeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserSSHKeyOK, error) + + DescribeUserSSHKeys(params *DescribeUserSSHKeysParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserSSHKeysOK, error) + + GetInstancesBySshkey(params *GetInstancesBySshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetInstancesBySshkeyOK, error) + + ModifyUserSshkey(params *ModifyUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserSshkeyOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateUserSshkey CreateUserSshkey 创建个人sshkey +*/ +func (a *Client) CreateUserSshkey(params *CreateUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserSshkeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateUserSshkeyParams() + } + op := &runtime.ClientOperation{ + ID: "createUserSshkey", + Method: "POST", + PathPattern: "/user/sshkeys", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateUserSshkeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateUserSshkeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateUserSshkeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteUserSshkey DeleteUserSshkey 删除sshkey +*/ +func (a *Client) DeleteUserSshkey(params *DeleteUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserSshkeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteUserSshkeyParams() + } + op := &runtime.ClientOperation{ + ID: "deleteUserSshkey", + Method: "DELETE", + PathPattern: "/user/sshkeys/{sshkey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteUserSshkeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteUserSshkeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteUserSshkeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserSSHKey DescribeUserSshKey 获取sshkey详情 +*/ +func (a *Client) DescribeUserSSHKey(params *DescribeUserSSHKeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserSSHKeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserSSHKeyParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserSshKey", + Method: "GET", + PathPattern: "/user/sshkeys/{sshkey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserSSHKeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserSSHKeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserSSHKeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserSSHKeys DescribeUserSshKeys 获取个人sshkey列表 +*/ +func (a *Client) DescribeUserSSHKeys(params *DescribeUserSSHKeysParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserSSHKeysOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserSSHKeysParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserSshKeys", + Method: "GET", + PathPattern: "/user/sshkeys", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserSSHKeysReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserSSHKeysOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserSSHKeysDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + GetInstancesBySshkey GetInstancesBySshkey 根据sshkey获取实例列表 +*/ +func (a *Client) GetInstancesBySshkey(params *GetInstancesBySshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetInstancesBySshkeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetInstancesBySshkeyParams() + } + op := &runtime.ClientOperation{ + ID: "getInstancesBySshkey", + Method: "GET", + PathPattern: "/user/sshkeys/instances/{sshkey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetInstancesBySshkeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetInstancesBySshkeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetInstancesBySshkeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyUserSshkey ModifyUserSshkey 修改sshkey +*/ +func (a *Client) ModifyUserSshkey(params *ModifyUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserSshkeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyUserSshkeyParams() + } + op := &runtime.ClientOperation{ + ID: "modifyUserSshkey", + Method: "PUT", + PathPattern: "/user/sshkeys/{sshkey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyUserSshkeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyUserSshkeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyUserSshkeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_local_user_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_local_user_parameters.go new file mode 100644 index 0000000..737566e --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_local_user_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeLocalUserParams creates a new DescribeLocalUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeLocalUserParams() *DescribeLocalUserParams { + return &DescribeLocalUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeLocalUserParamsWithTimeout creates a new DescribeLocalUserParams object +// with the ability to set a timeout on a request. +func NewDescribeLocalUserParamsWithTimeout(timeout time.Duration) *DescribeLocalUserParams { + return &DescribeLocalUserParams{ + timeout: timeout, + } +} + +// NewDescribeLocalUserParamsWithContext creates a new DescribeLocalUserParams object +// with the ability to set a context for a request. +func NewDescribeLocalUserParamsWithContext(ctx context.Context) *DescribeLocalUserParams { + return &DescribeLocalUserParams{ + Context: ctx, + } +} + +// NewDescribeLocalUserParamsWithHTTPClient creates a new DescribeLocalUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeLocalUserParamsWithHTTPClient(client *http.Client) *DescribeLocalUserParams { + return &DescribeLocalUserParams{ + HTTPClient: client, + } +} + +/* DescribeLocalUserParams contains all the parameters to send to the API endpoint + for the describe local user operation. + + Typically these are written to a http.Request. +*/ +type DescribeLocalUserParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe local user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLocalUserParams) WithDefaults() *DescribeLocalUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe local user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLocalUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe local user params +func (o *DescribeLocalUserParams) WithTimeout(timeout time.Duration) *DescribeLocalUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe local user params +func (o *DescribeLocalUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe local user params +func (o *DescribeLocalUserParams) WithContext(ctx context.Context) *DescribeLocalUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe local user params +func (o *DescribeLocalUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe local user params +func (o *DescribeLocalUserParams) WithHTTPClient(client *http.Client) *DescribeLocalUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe local user params +func (o *DescribeLocalUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe local user params +func (o *DescribeLocalUserParams) WithAuthorization(authorization string) *DescribeLocalUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe local user params +func (o *DescribeLocalUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe local user params +func (o *DescribeLocalUserParams) WithBmpLanguage(bmpLanguage *string) *DescribeLocalUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe local user params +func (o *DescribeLocalUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe local user params +func (o *DescribeLocalUserParams) WithBmpUserID(bmpUserID *string) *DescribeLocalUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe local user params +func (o *DescribeLocalUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe local user params +func (o *DescribeLocalUserParams) WithTraceID(traceID string) *DescribeLocalUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe local user params +func (o *DescribeLocalUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeLocalUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_local_user_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_local_user_responses.go new file mode 100644 index 0000000..e67bfec --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_local_user_responses.go @@ -0,0 +1,449 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeLocalUserReader is a Reader for the DescribeLocalUser structure. +type DescribeLocalUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeLocalUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeLocalUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeLocalUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeLocalUserOK creates a DescribeLocalUserOK with default headers values +func NewDescribeLocalUserOK() *DescribeLocalUserOK { + return &DescribeLocalUserOK{} +} + +/* DescribeLocalUserOK describes a response with status code 200, with default header values. + +A DescribeLocalUserResult is an response struct that is used to describe getuser. +*/ +type DescribeLocalUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLocalUserOKBody +} + +// IsSuccess returns true when this describe local user o k response has a 2xx status code +func (o *DescribeLocalUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe local user o k response has a 3xx status code +func (o *DescribeLocalUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe local user o k response has a 4xx status code +func (o *DescribeLocalUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe local user o k response has a 5xx status code +func (o *DescribeLocalUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe local user o k response a status code equal to that given +func (o *DescribeLocalUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeLocalUserOK) Error() string { + return fmt.Sprintf("[GET /local/users][%d] describeLocalUserOK %+v", 200, o.Payload) +} + +func (o *DescribeLocalUserOK) String() string { + return fmt.Sprintf("[GET /local/users][%d] describeLocalUserOK %+v", 200, o.Payload) +} + +func (o *DescribeLocalUserOK) GetPayload() *DescribeLocalUserOKBody { + return o.Payload +} + +func (o *DescribeLocalUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLocalUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeLocalUserDefault creates a DescribeLocalUserDefault with default headers values +func NewDescribeLocalUserDefault(code int) *DescribeLocalUserDefault { + return &DescribeLocalUserDefault{ + _statusCode: code, + } +} + +/* DescribeLocalUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeLocalUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLocalUserDefaultBody +} + +// Code gets the status code for the describe local user default response +func (o *DescribeLocalUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe local user default response has a 2xx status code +func (o *DescribeLocalUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe local user default response has a 3xx status code +func (o *DescribeLocalUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe local user default response has a 4xx status code +func (o *DescribeLocalUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe local user default response has a 5xx status code +func (o *DescribeLocalUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe local user default response a status code equal to that given +func (o *DescribeLocalUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeLocalUserDefault) Error() string { + return fmt.Sprintf("[GET /local/users][%d] describeLocalUser default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLocalUserDefault) String() string { + return fmt.Sprintf("[GET /local/users][%d] describeLocalUser default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLocalUserDefault) GetPayload() *DescribeLocalUserDefaultBody { + return o.Payload +} + +func (o *DescribeLocalUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLocalUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeLocalUserDefaultBody describe local user default body +swagger:model DescribeLocalUserDefaultBody +*/ +type DescribeLocalUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe local user default body +func (o *DescribeLocalUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLocalUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeLocalUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeLocalUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeLocalUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe local user default body based on the context it is used +func (o *DescribeLocalUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLocalUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLocalUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLocalUserDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeLocalUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeLocalUserOKBody describe local user o k body +swagger:model DescribeLocalUserOKBody +*/ +type DescribeLocalUserOKBody struct { + + // error + Error *models.ErrorResponse `json:"error,omitempty"` + + // result + Result *models.UserInfo `json:"result,omitempty"` +} + +// Validate validates this describe local user o k body +func (o *DescribeLocalUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLocalUserOKBody) validateError(formats strfmt.Registry) error { + if swag.IsZero(o.Error) { // not required + return nil + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUserOK" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUserOK" + "." + "error") + } + return err + } + } + + return nil +} + +func (o *DescribeLocalUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe local user o k body based on the context it is used +func (o *DescribeLocalUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLocalUserOKBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUserOK" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUserOK" + "." + "error") + } + return err + } + } + + return nil +} + +func (o *DescribeLocalUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLocalUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLocalUserOKBody) UnmarshalBinary(b []byte) error { + var res DescribeLocalUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_user_by_name_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_user_by_name_parameters.go new file mode 100644 index 0000000..488d83c --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_user_by_name_parameters.go @@ -0,0 +1,248 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeUserByNameParams creates a new DescribeUserByNameParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserByNameParams() *DescribeUserByNameParams { + return &DescribeUserByNameParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserByNameParamsWithTimeout creates a new DescribeUserByNameParams object +// with the ability to set a timeout on a request. +func NewDescribeUserByNameParamsWithTimeout(timeout time.Duration) *DescribeUserByNameParams { + return &DescribeUserByNameParams{ + timeout: timeout, + } +} + +// NewDescribeUserByNameParamsWithContext creates a new DescribeUserByNameParams object +// with the ability to set a context for a request. +func NewDescribeUserByNameParamsWithContext(ctx context.Context) *DescribeUserByNameParams { + return &DescribeUserByNameParams{ + Context: ctx, + } +} + +// NewDescribeUserByNameParamsWithHTTPClient creates a new DescribeUserByNameParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserByNameParamsWithHTTPClient(client *http.Client) *DescribeUserByNameParams { + return &DescribeUserByNameParams{ + HTTPClient: client, + } +} + +/* DescribeUserByNameParams contains all the parameters to send to the API endpoint + for the describe user by name operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserByNameParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserName. + + 用户名,唯一 + */ + UserName string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user by name params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserByNameParams) WithDefaults() *DescribeUserByNameParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user by name params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserByNameParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user by name params +func (o *DescribeUserByNameParams) WithTimeout(timeout time.Duration) *DescribeUserByNameParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user by name params +func (o *DescribeUserByNameParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user by name params +func (o *DescribeUserByNameParams) WithContext(ctx context.Context) *DescribeUserByNameParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user by name params +func (o *DescribeUserByNameParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user by name params +func (o *DescribeUserByNameParams) WithHTTPClient(client *http.Client) *DescribeUserByNameParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user by name params +func (o *DescribeUserByNameParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user by name params +func (o *DescribeUserByNameParams) WithAuthorization(authorization string) *DescribeUserByNameParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user by name params +func (o *DescribeUserByNameParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user by name params +func (o *DescribeUserByNameParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserByNameParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user by name params +func (o *DescribeUserByNameParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user by name params +func (o *DescribeUserByNameParams) WithBmpUserID(bmpUserID *string) *DescribeUserByNameParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user by name params +func (o *DescribeUserByNameParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe user by name params +func (o *DescribeUserByNameParams) WithTraceID(traceID string) *DescribeUserByNameParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user by name params +func (o *DescribeUserByNameParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserName adds the userName to the describe user by name params +func (o *DescribeUserByNameParams) WithUserName(userName string) *DescribeUserByNameParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe user by name params +func (o *DescribeUserByNameParams) SetUserName(userName string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserByNameParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + // query param userName + qrUserName := o.UserName + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_user_by_name_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_user_by_name_responses.go new file mode 100644 index 0000000..26d2cd6 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_user_by_name_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeUserByNameReader is a Reader for the DescribeUserByName structure. +type DescribeUserByNameReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserByNameReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserByNameOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserByNameDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserByNameOK creates a DescribeUserByNameOK with default headers values +func NewDescribeUserByNameOK() *DescribeUserByNameOK { + return &DescribeUserByNameOK{} +} + +/* DescribeUserByNameOK describes a response with status code 200, with default header values. + +A GetUserByNameResult is an response struct that is used to describe user. +*/ +type DescribeUserByNameOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserByNameOKBody +} + +// IsSuccess returns true when this describe user by name o k response has a 2xx status code +func (o *DescribeUserByNameOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user by name o k response has a 3xx status code +func (o *DescribeUserByNameOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user by name o k response has a 4xx status code +func (o *DescribeUserByNameOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user by name o k response has a 5xx status code +func (o *DescribeUserByNameOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user by name o k response a status code equal to that given +func (o *DescribeUserByNameOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserByNameOK) Error() string { + return fmt.Sprintf("[GET /users/getUserByName][%d] describeUserByNameOK %+v", 200, o.Payload) +} + +func (o *DescribeUserByNameOK) String() string { + return fmt.Sprintf("[GET /users/getUserByName][%d] describeUserByNameOK %+v", 200, o.Payload) +} + +func (o *DescribeUserByNameOK) GetPayload() *DescribeUserByNameOKBody { + return o.Payload +} + +func (o *DescribeUserByNameOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserByNameOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserByNameDefault creates a DescribeUserByNameDefault with default headers values +func NewDescribeUserByNameDefault(code int) *DescribeUserByNameDefault { + return &DescribeUserByNameDefault{ + _statusCode: code, + } +} + +/* DescribeUserByNameDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserByNameDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserByNameDefaultBody +} + +// Code gets the status code for the describe user by name default response +func (o *DescribeUserByNameDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user by name default response has a 2xx status code +func (o *DescribeUserByNameDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user by name default response has a 3xx status code +func (o *DescribeUserByNameDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user by name default response has a 4xx status code +func (o *DescribeUserByNameDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user by name default response has a 5xx status code +func (o *DescribeUserByNameDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user by name default response a status code equal to that given +func (o *DescribeUserByNameDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserByNameDefault) Error() string { + return fmt.Sprintf("[GET /users/getUserByName][%d] describeUserByName default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserByNameDefault) String() string { + return fmt.Sprintf("[GET /users/getUserByName][%d] describeUserByName default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserByNameDefault) GetPayload() *DescribeUserByNameDefaultBody { + return o.Payload +} + +func (o *DescribeUserByNameDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserByNameDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserByNameDefaultBody describe user by name default body +swagger:model DescribeUserByNameDefaultBody +*/ +type DescribeUserByNameDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user by name default body +func (o *DescribeUserByNameDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserByNameDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserByName default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserByNameDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserByName default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserByName default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserByName default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user by name default body based on the context it is used +func (o *DescribeUserByNameDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserByNameDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserByName default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserByName default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserByNameDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserByNameDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserByNameDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserByNameOKBody describe user by name o k body +swagger:model DescribeUserByNameOKBody +*/ +type DescribeUserByNameOKBody struct { + + // result + Result *models.UserInfo `json:"result,omitempty"` +} + +// Validate validates this describe user by name o k body +func (o *DescribeUserByNameOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserByNameOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserByNameOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserByNameOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user by name o k body based on the context it is used +func (o *DescribeUserByNameOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserByNameOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserByNameOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserByNameOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserByNameOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserByNameOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserByNameOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_user_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_user_parameters.go new file mode 100644 index 0000000..8b874fd --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_user_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeUserParams creates a new DescribeUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserParams() *DescribeUserParams { + return &DescribeUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserParamsWithTimeout creates a new DescribeUserParams object +// with the ability to set a timeout on a request. +func NewDescribeUserParamsWithTimeout(timeout time.Duration) *DescribeUserParams { + return &DescribeUserParams{ + timeout: timeout, + } +} + +// NewDescribeUserParamsWithContext creates a new DescribeUserParams object +// with the ability to set a context for a request. +func NewDescribeUserParamsWithContext(ctx context.Context) *DescribeUserParams { + return &DescribeUserParams{ + Context: ctx, + } +} + +// NewDescribeUserParamsWithHTTPClient creates a new DescribeUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserParamsWithHTTPClient(client *http.Client) *DescribeUserParams { + return &DescribeUserParams{ + HTTPClient: client, + } +} + +/* DescribeUserParams contains all the parameters to send to the API endpoint + for the describe user operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + // UserID. + UserID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserParams) WithDefaults() *DescribeUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user params +func (o *DescribeUserParams) WithTimeout(timeout time.Duration) *DescribeUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user params +func (o *DescribeUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user params +func (o *DescribeUserParams) WithContext(ctx context.Context) *DescribeUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user params +func (o *DescribeUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user params +func (o *DescribeUserParams) WithHTTPClient(client *http.Client) *DescribeUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user params +func (o *DescribeUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user params +func (o *DescribeUserParams) WithAuthorization(authorization string) *DescribeUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user params +func (o *DescribeUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user params +func (o *DescribeUserParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user params +func (o *DescribeUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user params +func (o *DescribeUserParams) WithBmpUserID(bmpUserID *string) *DescribeUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user params +func (o *DescribeUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe user params +func (o *DescribeUserParams) WithTraceID(traceID string) *DescribeUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user params +func (o *DescribeUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserID adds the userID to the describe user params +func (o *DescribeUserParams) WithUserID(userID string) *DescribeUserParams { + o.SetUserID(userID) + return o +} + +// SetUserID adds the userId to the describe user params +func (o *DescribeUserParams) SetUserID(userID string) { + o.UserID = userID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + // path param user_id + if err := r.SetPathParam("user_id", o.UserID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_user_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_user_responses.go new file mode 100644 index 0000000..4108966 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_user_responses.go @@ -0,0 +1,449 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeUserReader is a Reader for the DescribeUser structure. +type DescribeUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserOK creates a DescribeUserOK with default headers values +func NewDescribeUserOK() *DescribeUserOK { + return &DescribeUserOK{} +} + +/* DescribeUserOK describes a response with status code 200, with default header values. + +DescribeUserOK describe user o k +*/ +type DescribeUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserOKBody +} + +// IsSuccess returns true when this describe user o k response has a 2xx status code +func (o *DescribeUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user o k response has a 3xx status code +func (o *DescribeUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user o k response has a 4xx status code +func (o *DescribeUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user o k response has a 5xx status code +func (o *DescribeUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user o k response a status code equal to that given +func (o *DescribeUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserOK) Error() string { + return fmt.Sprintf("[GET /users/{user_id}][%d] describeUserOK %+v", 200, o.Payload) +} + +func (o *DescribeUserOK) String() string { + return fmt.Sprintf("[GET /users/{user_id}][%d] describeUserOK %+v", 200, o.Payload) +} + +func (o *DescribeUserOK) GetPayload() *DescribeUserOKBody { + return o.Payload +} + +func (o *DescribeUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserDefault creates a DescribeUserDefault with default headers values +func NewDescribeUserDefault(code int) *DescribeUserDefault { + return &DescribeUserDefault{ + _statusCode: code, + } +} + +/* DescribeUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserDefaultBody +} + +// Code gets the status code for the describe user default response +func (o *DescribeUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user default response has a 2xx status code +func (o *DescribeUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user default response has a 3xx status code +func (o *DescribeUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user default response has a 4xx status code +func (o *DescribeUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user default response has a 5xx status code +func (o *DescribeUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user default response a status code equal to that given +func (o *DescribeUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserDefault) Error() string { + return fmt.Sprintf("[GET /users/{user_id}][%d] describeUser default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserDefault) String() string { + return fmt.Sprintf("[GET /users/{user_id}][%d] describeUser default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserDefault) GetPayload() *DescribeUserDefaultBody { + return o.Payload +} + +func (o *DescribeUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserDefaultBody describe user default body +swagger:model DescribeUserDefaultBody +*/ +type DescribeUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user default body +func (o *DescribeUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user default body based on the context it is used +func (o *DescribeUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserOKBody describe user o k body +swagger:model DescribeUserOKBody +*/ +type DescribeUserOKBody struct { + + // error + Error *models.ErrorResponse `json:"error,omitempty"` + + // result + Result *models.UserInfo `json:"result,omitempty"` +} + +// Validate validates this describe user o k body +func (o *DescribeUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserOKBody) validateError(formats strfmt.Registry) error { + if swag.IsZero(o.Error) { // not required + return nil + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserOK" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserOK" + "." + "error") + } + return err + } + } + + return nil +} + +func (o *DescribeUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user o k body based on the context it is used +func (o *DescribeUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserOKBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserOK" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserOK" + "." + "error") + } + return err + } + } + + return nil +} + +func (o *DescribeUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_users_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_users_parameters.go new file mode 100644 index 0000000..6bc90a4 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_users_parameters.go @@ -0,0 +1,430 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeUsersParams creates a new DescribeUsersParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUsersParams() *DescribeUsersParams { + return &DescribeUsersParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUsersParamsWithTimeout creates a new DescribeUsersParams object +// with the ability to set a timeout on a request. +func NewDescribeUsersParamsWithTimeout(timeout time.Duration) *DescribeUsersParams { + return &DescribeUsersParams{ + timeout: timeout, + } +} + +// NewDescribeUsersParamsWithContext creates a new DescribeUsersParams object +// with the ability to set a context for a request. +func NewDescribeUsersParamsWithContext(ctx context.Context) *DescribeUsersParams { + return &DescribeUsersParams{ + Context: ctx, + } +} + +// NewDescribeUsersParamsWithHTTPClient creates a new DescribeUsersParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUsersParamsWithHTTPClient(client *http.Client) *DescribeUsersParams { + return &DescribeUsersParams{ + HTTPClient: client, + } +} + +/* DescribeUsersParams contains all the parameters to send to the API endpoint + for the describe users operation. + + Typically these are written to a http.Request. +*/ +type DescribeUsersParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DefaultProjectID. + + 项目uuid + */ + DefaultProjectID *string + + /* IsAll. + + 是否显示全部, isAll=1表示全部 + */ + IsAll *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* RoleID. + + 角色uuid + */ + RoleID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserName. + + 用户名 + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe users params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUsersParams) WithDefaults() *DescribeUsersParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe users params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUsersParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe users params +func (o *DescribeUsersParams) WithTimeout(timeout time.Duration) *DescribeUsersParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe users params +func (o *DescribeUsersParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe users params +func (o *DescribeUsersParams) WithContext(ctx context.Context) *DescribeUsersParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe users params +func (o *DescribeUsersParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe users params +func (o *DescribeUsersParams) WithHTTPClient(client *http.Client) *DescribeUsersParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe users params +func (o *DescribeUsersParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe users params +func (o *DescribeUsersParams) WithAuthorization(authorization string) *DescribeUsersParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe users params +func (o *DescribeUsersParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe users params +func (o *DescribeUsersParams) WithBmpLanguage(bmpLanguage *string) *DescribeUsersParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe users params +func (o *DescribeUsersParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe users params +func (o *DescribeUsersParams) WithBmpUserID(bmpUserID *string) *DescribeUsersParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe users params +func (o *DescribeUsersParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDefaultProjectID adds the defaultProjectID to the describe users params +func (o *DescribeUsersParams) WithDefaultProjectID(defaultProjectID *string) *DescribeUsersParams { + o.SetDefaultProjectID(defaultProjectID) + return o +} + +// SetDefaultProjectID adds the defaultProjectId to the describe users params +func (o *DescribeUsersParams) SetDefaultProjectID(defaultProjectID *string) { + o.DefaultProjectID = defaultProjectID +} + +// WithIsAll adds the isAll to the describe users params +func (o *DescribeUsersParams) WithIsAll(isAll *string) *DescribeUsersParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe users params +func (o *DescribeUsersParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithPageNumber adds the pageNumber to the describe users params +func (o *DescribeUsersParams) WithPageNumber(pageNumber *int64) *DescribeUsersParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe users params +func (o *DescribeUsersParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe users params +func (o *DescribeUsersParams) WithPageSize(pageSize *int64) *DescribeUsersParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe users params +func (o *DescribeUsersParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithRoleID adds the roleID to the describe users params +func (o *DescribeUsersParams) WithRoleID(roleID *string) *DescribeUsersParams { + o.SetRoleID(roleID) + return o +} + +// SetRoleID adds the roleId to the describe users params +func (o *DescribeUsersParams) SetRoleID(roleID *string) { + o.RoleID = roleID +} + +// WithTraceID adds the traceID to the describe users params +func (o *DescribeUsersParams) WithTraceID(traceID string) *DescribeUsersParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe users params +func (o *DescribeUsersParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserName adds the userName to the describe users params +func (o *DescribeUsersParams) WithUserName(userName *string) *DescribeUsersParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe users params +func (o *DescribeUsersParams) SetUserName(userName *string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUsersParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DefaultProjectID != nil { + + // query param defaultProjectId + var qrDefaultProjectID string + + if o.DefaultProjectID != nil { + qrDefaultProjectID = *o.DefaultProjectID + } + qDefaultProjectID := qrDefaultProjectID + if qDefaultProjectID != "" { + + if err := r.SetQueryParam("defaultProjectId", qDefaultProjectID); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.RoleID != nil { + + // query param roleId + var qrRoleID string + + if o.RoleID != nil { + qrRoleID = *o.RoleID + } + qRoleID := qrRoleID + if qRoleID != "" { + + if err := r.SetQueryParam("roleId", qRoleID); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserName != nil { + + // query param userName + var qrUserName string + + if o.UserName != nil { + qrUserName = *o.UserName + } + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_users_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_users_responses.go new file mode 100644 index 0000000..20b73a8 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/describe_users_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// DescribeUsersReader is a Reader for the DescribeUsers structure. +type DescribeUsersReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUsersReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUsersOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUsersDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUsersOK creates a DescribeUsersOK with default headers values +func NewDescribeUsersOK() *DescribeUsersOK { + return &DescribeUsersOK{} +} + +/* DescribeUsersOK describes a response with status code 200, with default header values. + +DescribeUsersOK describe users o k +*/ +type DescribeUsersOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUsersOKBody +} + +// IsSuccess returns true when this describe users o k response has a 2xx status code +func (o *DescribeUsersOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe users o k response has a 3xx status code +func (o *DescribeUsersOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe users o k response has a 4xx status code +func (o *DescribeUsersOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe users o k response has a 5xx status code +func (o *DescribeUsersOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe users o k response a status code equal to that given +func (o *DescribeUsersOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUsersOK) Error() string { + return fmt.Sprintf("[GET /users][%d] describeUsersOK %+v", 200, o.Payload) +} + +func (o *DescribeUsersOK) String() string { + return fmt.Sprintf("[GET /users][%d] describeUsersOK %+v", 200, o.Payload) +} + +func (o *DescribeUsersOK) GetPayload() *DescribeUsersOKBody { + return o.Payload +} + +func (o *DescribeUsersOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUsersOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUsersDefault creates a DescribeUsersDefault with default headers values +func NewDescribeUsersDefault(code int) *DescribeUsersDefault { + return &DescribeUsersDefault{ + _statusCode: code, + } +} + +/* DescribeUsersDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUsersDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUsersDefaultBody +} + +// Code gets the status code for the describe users default response +func (o *DescribeUsersDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe users default response has a 2xx status code +func (o *DescribeUsersDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe users default response has a 3xx status code +func (o *DescribeUsersDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe users default response has a 4xx status code +func (o *DescribeUsersDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe users default response has a 5xx status code +func (o *DescribeUsersDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe users default response a status code equal to that given +func (o *DescribeUsersDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUsersDefault) Error() string { + return fmt.Sprintf("[GET /users][%d] describeUsers default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUsersDefault) String() string { + return fmt.Sprintf("[GET /users][%d] describeUsers default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUsersDefault) GetPayload() *DescribeUsersDefaultBody { + return o.Payload +} + +func (o *DescribeUsersDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUsersDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUsersDefaultBody describe users default body +swagger:model DescribeUsersDefaultBody +*/ +type DescribeUsersDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe users default body +func (o *DescribeUsersDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUsersDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUsers default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUsersDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUsers default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUsers default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUsers default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe users default body based on the context it is used +func (o *DescribeUsersDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUsersDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUsers default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUsers default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUsersDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUsersDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUsersDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUsersOKBody describe users o k body +swagger:model DescribeUsersOKBody +*/ +type DescribeUsersOKBody struct { + + // result + Result *models.UserList `json:"result,omitempty"` +} + +// Validate validates this describe users o k body +func (o *DescribeUsersOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUsersOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUsersOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUsersOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe users o k body based on the context it is used +func (o *DescribeUsersOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUsersOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUsersOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUsersOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUsersOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUsersOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUsersOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_local_user_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_local_user_parameters.go new file mode 100644 index 0000000..ab0272e --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_local_user_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewModifyLocalUserParams creates a new ModifyLocalUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyLocalUserParams() *ModifyLocalUserParams { + return &ModifyLocalUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyLocalUserParamsWithTimeout creates a new ModifyLocalUserParams object +// with the ability to set a timeout on a request. +func NewModifyLocalUserParamsWithTimeout(timeout time.Duration) *ModifyLocalUserParams { + return &ModifyLocalUserParams{ + timeout: timeout, + } +} + +// NewModifyLocalUserParamsWithContext creates a new ModifyLocalUserParams object +// with the ability to set a context for a request. +func NewModifyLocalUserParamsWithContext(ctx context.Context) *ModifyLocalUserParams { + return &ModifyLocalUserParams{ + Context: ctx, + } +} + +// NewModifyLocalUserParamsWithHTTPClient creates a new ModifyLocalUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyLocalUserParamsWithHTTPClient(client *http.Client) *ModifyLocalUserParams { + return &ModifyLocalUserParams{ + HTTPClient: client, + } +} + +/* ModifyLocalUserParams contains all the parameters to send to the API endpoint + for the modify local user operation. + + Typically these are written to a http.Request. +*/ +type ModifyLocalUserParams struct { + + // Body. + Body *models.ModifyLocalUserRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify local user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyLocalUserParams) WithDefaults() *ModifyLocalUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify local user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyLocalUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify local user params +func (o *ModifyLocalUserParams) WithTimeout(timeout time.Duration) *ModifyLocalUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify local user params +func (o *ModifyLocalUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify local user params +func (o *ModifyLocalUserParams) WithContext(ctx context.Context) *ModifyLocalUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify local user params +func (o *ModifyLocalUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify local user params +func (o *ModifyLocalUserParams) WithHTTPClient(client *http.Client) *ModifyLocalUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify local user params +func (o *ModifyLocalUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify local user params +func (o *ModifyLocalUserParams) WithBody(body *models.ModifyLocalUserRequest) *ModifyLocalUserParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify local user params +func (o *ModifyLocalUserParams) SetBody(body *models.ModifyLocalUserRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify local user params +func (o *ModifyLocalUserParams) WithAuthorization(authorization string) *ModifyLocalUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify local user params +func (o *ModifyLocalUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify local user params +func (o *ModifyLocalUserParams) WithBmpLanguage(bmpLanguage *string) *ModifyLocalUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify local user params +func (o *ModifyLocalUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify local user params +func (o *ModifyLocalUserParams) WithBmpUserID(bmpUserID *string) *ModifyLocalUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify local user params +func (o *ModifyLocalUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the modify local user params +func (o *ModifyLocalUserParams) WithTraceID(traceID string) *ModifyLocalUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify local user params +func (o *ModifyLocalUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyLocalUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_local_user_password_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_local_user_password_parameters.go new file mode 100644 index 0000000..9c962f0 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_local_user_password_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewModifyLocalUserPasswordParams creates a new ModifyLocalUserPasswordParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyLocalUserPasswordParams() *ModifyLocalUserPasswordParams { + return &ModifyLocalUserPasswordParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyLocalUserPasswordParamsWithTimeout creates a new ModifyLocalUserPasswordParams object +// with the ability to set a timeout on a request. +func NewModifyLocalUserPasswordParamsWithTimeout(timeout time.Duration) *ModifyLocalUserPasswordParams { + return &ModifyLocalUserPasswordParams{ + timeout: timeout, + } +} + +// NewModifyLocalUserPasswordParamsWithContext creates a new ModifyLocalUserPasswordParams object +// with the ability to set a context for a request. +func NewModifyLocalUserPasswordParamsWithContext(ctx context.Context) *ModifyLocalUserPasswordParams { + return &ModifyLocalUserPasswordParams{ + Context: ctx, + } +} + +// NewModifyLocalUserPasswordParamsWithHTTPClient creates a new ModifyLocalUserPasswordParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyLocalUserPasswordParamsWithHTTPClient(client *http.Client) *ModifyLocalUserPasswordParams { + return &ModifyLocalUserPasswordParams{ + HTTPClient: client, + } +} + +/* ModifyLocalUserPasswordParams contains all the parameters to send to the API endpoint + for the modify local user password operation. + + Typically these are written to a http.Request. +*/ +type ModifyLocalUserPasswordParams struct { + + // Body. + Body *models.ModifyUserPasswordRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify local user password params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyLocalUserPasswordParams) WithDefaults() *ModifyLocalUserPasswordParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify local user password params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyLocalUserPasswordParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithTimeout(timeout time.Duration) *ModifyLocalUserPasswordParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithContext(ctx context.Context) *ModifyLocalUserPasswordParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithHTTPClient(client *http.Client) *ModifyLocalUserPasswordParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithBody(body *models.ModifyUserPasswordRequest) *ModifyLocalUserPasswordParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetBody(body *models.ModifyUserPasswordRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithAuthorization(authorization string) *ModifyLocalUserPasswordParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithBmpLanguage(bmpLanguage *string) *ModifyLocalUserPasswordParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithBmpUserID(bmpUserID *string) *ModifyLocalUserPasswordParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithTraceID(traceID string) *ModifyLocalUserPasswordParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyLocalUserPasswordParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_local_user_password_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_local_user_password_responses.go new file mode 100644 index 0000000..d0dfe15 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_local_user_password_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// ModifyLocalUserPasswordReader is a Reader for the ModifyLocalUserPassword structure. +type ModifyLocalUserPasswordReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyLocalUserPasswordReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyLocalUserPasswordOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyLocalUserPasswordDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyLocalUserPasswordOK creates a ModifyLocalUserPasswordOK with default headers values +func NewModifyLocalUserPasswordOK() *ModifyLocalUserPasswordOK { + return &ModifyLocalUserPasswordOK{} +} + +/* ModifyLocalUserPasswordOK describes a response with status code 200, with default header values. + +A ModifyLocalUserPasswordResult is an response struct that is used to describe getuser. +*/ +type ModifyLocalUserPasswordOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyLocalUserPasswordOKBody +} + +// IsSuccess returns true when this modify local user password o k response has a 2xx status code +func (o *ModifyLocalUserPasswordOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify local user password o k response has a 3xx status code +func (o *ModifyLocalUserPasswordOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify local user password o k response has a 4xx status code +func (o *ModifyLocalUserPasswordOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify local user password o k response has a 5xx status code +func (o *ModifyLocalUserPasswordOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify local user password o k response a status code equal to that given +func (o *ModifyLocalUserPasswordOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyLocalUserPasswordOK) Error() string { + return fmt.Sprintf("[PUT /local/users/password][%d] modifyLocalUserPasswordOK %+v", 200, o.Payload) +} + +func (o *ModifyLocalUserPasswordOK) String() string { + return fmt.Sprintf("[PUT /local/users/password][%d] modifyLocalUserPasswordOK %+v", 200, o.Payload) +} + +func (o *ModifyLocalUserPasswordOK) GetPayload() *ModifyLocalUserPasswordOKBody { + return o.Payload +} + +func (o *ModifyLocalUserPasswordOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyLocalUserPasswordOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyLocalUserPasswordDefault creates a ModifyLocalUserPasswordDefault with default headers values +func NewModifyLocalUserPasswordDefault(code int) *ModifyLocalUserPasswordDefault { + return &ModifyLocalUserPasswordDefault{ + _statusCode: code, + } +} + +/* ModifyLocalUserPasswordDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyLocalUserPasswordDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyLocalUserPasswordDefaultBody +} + +// Code gets the status code for the modify local user password default response +func (o *ModifyLocalUserPasswordDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify local user password default response has a 2xx status code +func (o *ModifyLocalUserPasswordDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify local user password default response has a 3xx status code +func (o *ModifyLocalUserPasswordDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify local user password default response has a 4xx status code +func (o *ModifyLocalUserPasswordDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify local user password default response has a 5xx status code +func (o *ModifyLocalUserPasswordDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify local user password default response a status code equal to that given +func (o *ModifyLocalUserPasswordDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyLocalUserPasswordDefault) Error() string { + return fmt.Sprintf("[PUT /local/users/password][%d] modifyLocalUserPassword default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyLocalUserPasswordDefault) String() string { + return fmt.Sprintf("[PUT /local/users/password][%d] modifyLocalUserPassword default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyLocalUserPasswordDefault) GetPayload() *ModifyLocalUserPasswordDefaultBody { + return o.Payload +} + +func (o *ModifyLocalUserPasswordDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyLocalUserPasswordDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyLocalUserPasswordDefaultBody modify local user password default body +swagger:model ModifyLocalUserPasswordDefaultBody +*/ +type ModifyLocalUserPasswordDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify local user password default body +func (o *ModifyLocalUserPasswordDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserPasswordDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyLocalUserPassword default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyLocalUserPasswordDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyLocalUserPassword default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserPassword default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserPassword default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify local user password default body based on the context it is used +func (o *ModifyLocalUserPasswordDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserPasswordDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserPassword default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserPassword default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyLocalUserPasswordDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyLocalUserPasswordDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyLocalUserPasswordDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyLocalUserPasswordOKBody modify local user password o k body +swagger:model ModifyLocalUserPasswordOKBody +*/ +type ModifyLocalUserPasswordOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify local user password o k body +func (o *ModifyLocalUserPasswordOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserPasswordOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserPasswordOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserPasswordOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify local user password o k body based on the context it is used +func (o *ModifyLocalUserPasswordOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserPasswordOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserPasswordOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserPasswordOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyLocalUserPasswordOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyLocalUserPasswordOKBody) UnmarshalBinary(b []byte) error { + var res ModifyLocalUserPasswordOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_local_user_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_local_user_responses.go new file mode 100644 index 0000000..246ccdb --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_local_user_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// ModifyLocalUserReader is a Reader for the ModifyLocalUser structure. +type ModifyLocalUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyLocalUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyLocalUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyLocalUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyLocalUserOK creates a ModifyLocalUserOK with default headers values +func NewModifyLocalUserOK() *ModifyLocalUserOK { + return &ModifyLocalUserOK{} +} + +/* ModifyLocalUserOK describes a response with status code 200, with default header values. + +A ModifyLocalUserResult is an response struct that is used to describe getuser. +*/ +type ModifyLocalUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyLocalUserOKBody +} + +// IsSuccess returns true when this modify local user o k response has a 2xx status code +func (o *ModifyLocalUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify local user o k response has a 3xx status code +func (o *ModifyLocalUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify local user o k response has a 4xx status code +func (o *ModifyLocalUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify local user o k response has a 5xx status code +func (o *ModifyLocalUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify local user o k response a status code equal to that given +func (o *ModifyLocalUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyLocalUserOK) Error() string { + return fmt.Sprintf("[PUT /local/users][%d] modifyLocalUserOK %+v", 200, o.Payload) +} + +func (o *ModifyLocalUserOK) String() string { + return fmt.Sprintf("[PUT /local/users][%d] modifyLocalUserOK %+v", 200, o.Payload) +} + +func (o *ModifyLocalUserOK) GetPayload() *ModifyLocalUserOKBody { + return o.Payload +} + +func (o *ModifyLocalUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyLocalUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyLocalUserDefault creates a ModifyLocalUserDefault with default headers values +func NewModifyLocalUserDefault(code int) *ModifyLocalUserDefault { + return &ModifyLocalUserDefault{ + _statusCode: code, + } +} + +/* ModifyLocalUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyLocalUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyLocalUserDefaultBody +} + +// Code gets the status code for the modify local user default response +func (o *ModifyLocalUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify local user default response has a 2xx status code +func (o *ModifyLocalUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify local user default response has a 3xx status code +func (o *ModifyLocalUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify local user default response has a 4xx status code +func (o *ModifyLocalUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify local user default response has a 5xx status code +func (o *ModifyLocalUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify local user default response a status code equal to that given +func (o *ModifyLocalUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyLocalUserDefault) Error() string { + return fmt.Sprintf("[PUT /local/users][%d] modifyLocalUser default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyLocalUserDefault) String() string { + return fmt.Sprintf("[PUT /local/users][%d] modifyLocalUser default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyLocalUserDefault) GetPayload() *ModifyLocalUserDefaultBody { + return o.Payload +} + +func (o *ModifyLocalUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyLocalUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyLocalUserDefaultBody modify local user default body +swagger:model ModifyLocalUserDefaultBody +*/ +type ModifyLocalUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify local user default body +func (o *ModifyLocalUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyLocalUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyLocalUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyLocalUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify local user default body based on the context it is used +func (o *ModifyLocalUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyLocalUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyLocalUserDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyLocalUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyLocalUserOKBody modify local user o k body +swagger:model ModifyLocalUserOKBody +*/ +type ModifyLocalUserOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify local user o k body +func (o *ModifyLocalUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify local user o k body based on the context it is used +func (o *ModifyLocalUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyLocalUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyLocalUserOKBody) UnmarshalBinary(b []byte) error { + var res ModifyLocalUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_user_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_user_parameters.go new file mode 100644 index 0000000..1efc8e5 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_user_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewModifyUserParams creates a new ModifyUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyUserParams() *ModifyUserParams { + return &ModifyUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyUserParamsWithTimeout creates a new ModifyUserParams object +// with the ability to set a timeout on a request. +func NewModifyUserParamsWithTimeout(timeout time.Duration) *ModifyUserParams { + return &ModifyUserParams{ + timeout: timeout, + } +} + +// NewModifyUserParamsWithContext creates a new ModifyUserParams object +// with the ability to set a context for a request. +func NewModifyUserParamsWithContext(ctx context.Context) *ModifyUserParams { + return &ModifyUserParams{ + Context: ctx, + } +} + +// NewModifyUserParamsWithHTTPClient creates a new ModifyUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyUserParamsWithHTTPClient(client *http.Client) *ModifyUserParams { + return &ModifyUserParams{ + HTTPClient: client, + } +} + +/* ModifyUserParams contains all the parameters to send to the API endpoint + for the modify user operation. + + Typically these are written to a http.Request. +*/ +type ModifyUserParams struct { + + // Body. + Body *models.ModifyUserRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + // UserID. + UserID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserParams) WithDefaults() *ModifyUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify user params +func (o *ModifyUserParams) WithTimeout(timeout time.Duration) *ModifyUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify user params +func (o *ModifyUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify user params +func (o *ModifyUserParams) WithContext(ctx context.Context) *ModifyUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify user params +func (o *ModifyUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify user params +func (o *ModifyUserParams) WithHTTPClient(client *http.Client) *ModifyUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify user params +func (o *ModifyUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify user params +func (o *ModifyUserParams) WithBody(body *models.ModifyUserRequest) *ModifyUserParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify user params +func (o *ModifyUserParams) SetBody(body *models.ModifyUserRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify user params +func (o *ModifyUserParams) WithAuthorization(authorization string) *ModifyUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify user params +func (o *ModifyUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify user params +func (o *ModifyUserParams) WithBmpLanguage(bmpLanguage *string) *ModifyUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify user params +func (o *ModifyUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify user params +func (o *ModifyUserParams) WithBmpUserID(bmpUserID *string) *ModifyUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify user params +func (o *ModifyUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the modify user params +func (o *ModifyUserParams) WithTraceID(traceID string) *ModifyUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify user params +func (o *ModifyUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserID adds the userID to the modify user params +func (o *ModifyUserParams) WithUserID(userID string) *ModifyUserParams { + o.SetUserID(userID) + return o +} + +// SetUserID adds the userId to the modify user params +func (o *ModifyUserParams) SetUserID(userID string) { + o.UserID = userID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + // path param user_id + if err := r.SetPathParam("user_id", o.UserID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_user_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_user_responses.go new file mode 100644 index 0000000..30f2c93 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/modify_user_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// ModifyUserReader is a Reader for the ModifyUser structure. +type ModifyUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyUserOK creates a ModifyUserOK with default headers values +func NewModifyUserOK() *ModifyUserOK { + return &ModifyUserOK{} +} + +/* ModifyUserOK describes a response with status code 200, with default header values. + +A GetUserResult is an response struct that is used to describe getuser. +*/ +type ModifyUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserOKBody +} + +// IsSuccess returns true when this modify user o k response has a 2xx status code +func (o *ModifyUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify user o k response has a 3xx status code +func (o *ModifyUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify user o k response has a 4xx status code +func (o *ModifyUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify user o k response has a 5xx status code +func (o *ModifyUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify user o k response a status code equal to that given +func (o *ModifyUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyUserOK) Error() string { + return fmt.Sprintf("[PUT /users/{user_id}][%d] modifyUserOK %+v", 200, o.Payload) +} + +func (o *ModifyUserOK) String() string { + return fmt.Sprintf("[PUT /users/{user_id}][%d] modifyUserOK %+v", 200, o.Payload) +} + +func (o *ModifyUserOK) GetPayload() *ModifyUserOKBody { + return o.Payload +} + +func (o *ModifyUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyUserDefault creates a ModifyUserDefault with default headers values +func NewModifyUserDefault(code int) *ModifyUserDefault { + return &ModifyUserDefault{ + _statusCode: code, + } +} + +/* ModifyUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserDefaultBody +} + +// Code gets the status code for the modify user default response +func (o *ModifyUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify user default response has a 2xx status code +func (o *ModifyUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify user default response has a 3xx status code +func (o *ModifyUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify user default response has a 4xx status code +func (o *ModifyUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify user default response has a 5xx status code +func (o *ModifyUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify user default response a status code equal to that given +func (o *ModifyUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyUserDefault) Error() string { + return fmt.Sprintf("[PUT /users/{user_id}][%d] modifyUser default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserDefault) String() string { + return fmt.Sprintf("[PUT /users/{user_id}][%d] modifyUser default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserDefault) GetPayload() *ModifyUserDefaultBody { + return o.Payload +} + +func (o *ModifyUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyUserDefaultBody modify user default body +swagger:model ModifyUserDefaultBody +*/ +type ModifyUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify user default body +func (o *ModifyUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user default body based on the context it is used +func (o *ModifyUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyUserOKBody modify user o k body +swagger:model ModifyUserOKBody +*/ +type ModifyUserOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify user o k body +func (o *ModifyUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user o k body based on the context it is used +func (o *ModifyUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserOKBody) UnmarshalBinary(b []byte) error { + var res ModifyUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/user_client.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/user_client.go new file mode 100644 index 0000000..2c23148 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/user_client.go @@ -0,0 +1,357 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new user API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for user API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DescribeLocalUser(params *DescribeLocalUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLocalUserOK, error) + + DescribeUser(params *DescribeUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserOK, error) + + DescribeUserByName(params *DescribeUserByNameParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserByNameOK, error) + + DescribeUsers(params *DescribeUsersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUsersOK, error) + + ModifyLocalUser(params *ModifyLocalUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyLocalUserOK, error) + + ModifyLocalUserPassword(params *ModifyLocalUserPasswordParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyLocalUserPasswordOK, error) + + ModifyUser(params *ModifyUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserOK, error) + + VerifyUser(params *VerifyUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*VerifyUserOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DescribeLocalUser DescribeLocalUser 控制台获取用户详情 +*/ +func (a *Client) DescribeLocalUser(params *DescribeLocalUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLocalUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeLocalUserParams() + } + op := &runtime.ClientOperation{ + ID: "describeLocalUser", + Method: "GET", + PathPattern: "/local/users", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeLocalUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeLocalUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeLocalUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUser DescribeUser 获取用户详情 +*/ +func (a *Client) DescribeUser(params *DescribeUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserParams() + } + op := &runtime.ClientOperation{ + ID: "describeUser", + Method: "GET", + PathPattern: "/users/{user_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserByName DescribeUserByName 根据用户名获取用户详情 +*/ +func (a *Client) DescribeUserByName(params *DescribeUserByNameParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserByNameOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserByNameParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserByName", + Method: "GET", + PathPattern: "/users/getUserByName", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserByNameReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserByNameOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserByNameDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUsers DescribeUsers 获取用户列表 +*/ +func (a *Client) DescribeUsers(params *DescribeUsersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUsersOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUsersParams() + } + op := &runtime.ClientOperation{ + ID: "describeUsers", + Method: "GET", + PathPattern: "/users", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUsersReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUsersOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUsersDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyLocalUser ModifyLocalUser 控制台修改除密码外的个人信息 +*/ +func (a *Client) ModifyLocalUser(params *ModifyLocalUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyLocalUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyLocalUserParams() + } + op := &runtime.ClientOperation{ + ID: "modifyLocalUser", + Method: "PUT", + PathPattern: "/local/users", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyLocalUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyLocalUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyLocalUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyLocalUserPassword ModifyLocalUserPassword 控制台修改个人密码 +*/ +func (a *Client) ModifyLocalUserPassword(params *ModifyLocalUserPasswordParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyLocalUserPasswordOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyLocalUserPasswordParams() + } + op := &runtime.ClientOperation{ + ID: "modifyLocalUserPassword", + Method: "PUT", + PathPattern: "/local/users/password", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyLocalUserPasswordReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyLocalUserPasswordOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyLocalUserPasswordDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyUser ModifyUser 修改用户信息 +*/ +func (a *Client) ModifyUser(params *ModifyUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyUserParams() + } + op := &runtime.ClientOperation{ + ID: "modifyUser", + Method: "PUT", + PathPattern: "/users/{user_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + VerifyUser VerifyUser 鉴定用户 +*/ +func (a *Client) VerifyUser(params *VerifyUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*VerifyUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewVerifyUserParams() + } + op := &runtime.ClientOperation{ + ID: "verifyUser", + Method: "POST", + PathPattern: "/users/verify", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &VerifyUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*VerifyUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*VerifyUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/verify_user_parameters.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/verify_user_parameters.go new file mode 100644 index 0000000..0358067 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/verify_user_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// NewVerifyUserParams creates a new VerifyUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewVerifyUserParams() *VerifyUserParams { + return &VerifyUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewVerifyUserParamsWithTimeout creates a new VerifyUserParams object +// with the ability to set a timeout on a request. +func NewVerifyUserParamsWithTimeout(timeout time.Duration) *VerifyUserParams { + return &VerifyUserParams{ + timeout: timeout, + } +} + +// NewVerifyUserParamsWithContext creates a new VerifyUserParams object +// with the ability to set a context for a request. +func NewVerifyUserParamsWithContext(ctx context.Context) *VerifyUserParams { + return &VerifyUserParams{ + Context: ctx, + } +} + +// NewVerifyUserParamsWithHTTPClient creates a new VerifyUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewVerifyUserParamsWithHTTPClient(client *http.Client) *VerifyUserParams { + return &VerifyUserParams{ + HTTPClient: client, + } +} + +/* VerifyUserParams contains all the parameters to send to the API endpoint + for the verify user operation. + + Typically these are written to a http.Request. +*/ +type VerifyUserParams struct { + + // Body. + Body *models.VerifyUserRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the verify user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *VerifyUserParams) WithDefaults() *VerifyUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the verify user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *VerifyUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the verify user params +func (o *VerifyUserParams) WithTimeout(timeout time.Duration) *VerifyUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the verify user params +func (o *VerifyUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the verify user params +func (o *VerifyUserParams) WithContext(ctx context.Context) *VerifyUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the verify user params +func (o *VerifyUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the verify user params +func (o *VerifyUserParams) WithHTTPClient(client *http.Client) *VerifyUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the verify user params +func (o *VerifyUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the verify user params +func (o *VerifyUserParams) WithBody(body *models.VerifyUserRequest) *VerifyUserParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the verify user params +func (o *VerifyUserParams) SetBody(body *models.VerifyUserRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the verify user params +func (o *VerifyUserParams) WithAuthorization(authorization string) *VerifyUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the verify user params +func (o *VerifyUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the verify user params +func (o *VerifyUserParams) WithBmpLanguage(bmpLanguage *string) *VerifyUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the verify user params +func (o *VerifyUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the verify user params +func (o *VerifyUserParams) WithBmpUserID(bmpUserID *string) *VerifyUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the verify user params +func (o *VerifyUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the verify user params +func (o *VerifyUserParams) WithTraceID(traceID string) *VerifyUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the verify user params +func (o *VerifyUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *VerifyUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/verify_user_responses.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/verify_user_responses.go new file mode 100644 index 0000000..3fbdbf5 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/client/user/verify_user_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// VerifyUserReader is a Reader for the VerifyUser structure. +type VerifyUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *VerifyUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewVerifyUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewVerifyUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewVerifyUserOK creates a VerifyUserOK with default headers values +func NewVerifyUserOK() *VerifyUserOK { + return &VerifyUserOK{} +} + +/* VerifyUserOK describes a response with status code 200, with default header values. + +A VerifyUserResult is an response struct that is used to describe verify user result. +*/ +type VerifyUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *VerifyUserOKBody +} + +// IsSuccess returns true when this verify user o k response has a 2xx status code +func (o *VerifyUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this verify user o k response has a 3xx status code +func (o *VerifyUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this verify user o k response has a 4xx status code +func (o *VerifyUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this verify user o k response has a 5xx status code +func (o *VerifyUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this verify user o k response a status code equal to that given +func (o *VerifyUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *VerifyUserOK) Error() string { + return fmt.Sprintf("[POST /users/verify][%d] verifyUserOK %+v", 200, o.Payload) +} + +func (o *VerifyUserOK) String() string { + return fmt.Sprintf("[POST /users/verify][%d] verifyUserOK %+v", 200, o.Payload) +} + +func (o *VerifyUserOK) GetPayload() *VerifyUserOKBody { + return o.Payload +} + +func (o *VerifyUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(VerifyUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewVerifyUserDefault creates a VerifyUserDefault with default headers values +func NewVerifyUserDefault(code int) *VerifyUserDefault { + return &VerifyUserDefault{ + _statusCode: code, + } +} + +/* VerifyUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type VerifyUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *VerifyUserDefaultBody +} + +// Code gets the status code for the verify user default response +func (o *VerifyUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this verify user default response has a 2xx status code +func (o *VerifyUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this verify user default response has a 3xx status code +func (o *VerifyUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this verify user default response has a 4xx status code +func (o *VerifyUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this verify user default response has a 5xx status code +func (o *VerifyUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this verify user default response a status code equal to that given +func (o *VerifyUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *VerifyUserDefault) Error() string { + return fmt.Sprintf("[POST /users/verify][%d] verifyUser default %+v", o._statusCode, o.Payload) +} + +func (o *VerifyUserDefault) String() string { + return fmt.Sprintf("[POST /users/verify][%d] verifyUser default %+v", o._statusCode, o.Payload) +} + +func (o *VerifyUserDefault) GetPayload() *VerifyUserDefaultBody { + return o.Payload +} + +func (o *VerifyUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(VerifyUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*VerifyUserDefaultBody verify user default body +swagger:model VerifyUserDefaultBody +*/ +type VerifyUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this verify user default body +func (o *VerifyUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *VerifyUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("verifyUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *VerifyUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("verifyUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("verifyUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("verifyUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this verify user default body based on the context it is used +func (o *VerifyUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *VerifyUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("verifyUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("verifyUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *VerifyUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *VerifyUserDefaultBody) UnmarshalBinary(b []byte) error { + var res VerifyUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*VerifyUserOKBody verify user o k body +swagger:model VerifyUserOKBody +*/ +type VerifyUserOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this verify user o k body +func (o *VerifyUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *VerifyUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("verifyUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("verifyUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this verify user o k body based on the context it is used +func (o *VerifyUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *VerifyUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("verifyUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("verifyUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *VerifyUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *VerifyUserOKBody) UnmarshalBinary(b []byte) error { + var res VerifyUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/go.mod b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/go.mod new file mode 100644 index 0000000..087e102 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/go.mod @@ -0,0 +1,3 @@ +module coding.jd.com/aidc-bmp/bmp-openapi-console-sdk + +go 1.17 diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/add_alert_item.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/add_alert_item.go new file mode 100644 index 0000000..7d8917a --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/add_alert_item.go @@ -0,0 +1,165 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// AddAlertItem add alert item +// +// swagger:model AddAlertItem +type AddAlertItem struct { + + // 告警持续时间 + // Required: true + AlertPeriod *int64 `json:"alertPeriod"` + + // 告警时间戳 + // Required: true + AlertTimestamp *int64 `json:"alertTimestamp"` + + // 告警值 + // Required: true + AlertValue *string `json:"alertValue"` + + // 计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出] + CalculationUnit string `json:"calculationUnit,omitempty"` + + // 实例id + // Required: true + InstanceID *string `json:"instanceId"` + + // 是否为恢复通知,0为不是,1为是 + IsRecover int64 `json:"isRecover,omitempty"` + + // 规则ID + // Required: true + RuleID *string `json:"ruleId"` + + // 规则名称 + RuleName string `json:"ruleName,omitempty"` + + // 触发条件 + // Required: true + Trigger *string `json:"trigger"` +} + +// Validate validates this add alert item +func (m *AddAlertItem) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAlertPeriod(formats); err != nil { + res = append(res, err) + } + + if err := m.validateAlertTimestamp(formats); err != nil { + res = append(res, err) + } + + if err := m.validateAlertValue(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInstanceID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRuleID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTrigger(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AddAlertItem) validateAlertPeriod(formats strfmt.Registry) error { + + if err := validate.Required("alertPeriod", "body", m.AlertPeriod); err != nil { + return err + } + + return nil +} + +func (m *AddAlertItem) validateAlertTimestamp(formats strfmt.Registry) error { + + if err := validate.Required("alertTimestamp", "body", m.AlertTimestamp); err != nil { + return err + } + + return nil +} + +func (m *AddAlertItem) validateAlertValue(formats strfmt.Registry) error { + + if err := validate.Required("alertValue", "body", m.AlertValue); err != nil { + return err + } + + return nil +} + +func (m *AddAlertItem) validateInstanceID(formats strfmt.Registry) error { + + if err := validate.Required("instanceId", "body", m.InstanceID); err != nil { + return err + } + + return nil +} + +func (m *AddAlertItem) validateRuleID(formats strfmt.Registry) error { + + if err := validate.Required("ruleId", "body", m.RuleID); err != nil { + return err + } + + return nil +} + +func (m *AddAlertItem) validateTrigger(formats strfmt.Registry) error { + + if err := validate.Required("trigger", "body", m.Trigger); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this add alert item based on context it is used +func (m *AddAlertItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *AddAlertItem) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AddAlertItem) UnmarshalBinary(b []byte) error { + var res AddAlertItem + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/add_alert_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/add_alert_request.go new file mode 100644 index 0000000..72b5011 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/add_alert_request.go @@ -0,0 +1,116 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// AddAlertRequest add alert request +// +// swagger:model AddAlertRequest +type AddAlertRequest struct { + + // alerts + Alerts []*AddAlertItem `json:"alerts"` +} + +// Validate validates this add alert request +func (m *AddAlertRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAlerts(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AddAlertRequest) validateAlerts(formats strfmt.Registry) error { + if swag.IsZero(m.Alerts) { // not required + return nil + } + + for i := 0; i < len(m.Alerts); i++ { + if swag.IsZero(m.Alerts[i]) { // not required + continue + } + + if m.Alerts[i] != nil { + if err := m.Alerts[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("alerts" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("alerts" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this add alert request based on the context it is used +func (m *AddAlertRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateAlerts(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AddAlertRequest) contextValidateAlerts(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Alerts); i++ { + + if m.Alerts[i] != nil { + if err := m.Alerts[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("alerts" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("alerts" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *AddAlertRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AddAlertRequest) UnmarshalBinary(b []byte) error { + var res AddAlertRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/add_rule_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/add_rule_request.go new file mode 100644 index 0000000..d8aff9c --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/add_rule_request.go @@ -0,0 +1,255 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// AddRuleRequest add rule request +// +// swagger:model AddRuleRequest +type AddRuleRequest struct { + + // 盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag,omitempty"` + + // 维度 [instance、disk、mountpoint、nic] + // Required: true + Dimension *string `json:"dimension"` + + // 实例id列表 + // Required: true + InstanceIds []string `json:"instanceIds"` + + // 规则所属的项目uuid + // Required: true + ProjectID *string `json:"projectId"` + + // 资源类型,目前只支持instance + // Required: true + Resource *string `json:"resource"` + + // 规则名称 + // Required: true + RuleName *string `json:"ruleName"` + + // 触发条件 + // Required: true + TriggerOption []*RuleTrigger `json:"triggerOption"` + + // notice option + // Required: true + NoticeOption *RuleNotice `json:"noticeOption"` +} + +// Validate validates this add rule request +func (m *AddRuleRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDimension(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInstanceIds(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProjectID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateResource(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRuleName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTriggerOption(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNoticeOption(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AddRuleRequest) validateDimension(formats strfmt.Registry) error { + + if err := validate.Required("dimension", "body", m.Dimension); err != nil { + return err + } + + return nil +} + +func (m *AddRuleRequest) validateInstanceIds(formats strfmt.Registry) error { + + if err := validate.Required("instanceIds", "body", m.InstanceIds); err != nil { + return err + } + + return nil +} + +func (m *AddRuleRequest) validateProjectID(formats strfmt.Registry) error { + + if err := validate.Required("projectId", "body", m.ProjectID); err != nil { + return err + } + + return nil +} + +func (m *AddRuleRequest) validateResource(formats strfmt.Registry) error { + + if err := validate.Required("resource", "body", m.Resource); err != nil { + return err + } + + return nil +} + +func (m *AddRuleRequest) validateRuleName(formats strfmt.Registry) error { + + if err := validate.Required("ruleName", "body", m.RuleName); err != nil { + return err + } + + return nil +} + +func (m *AddRuleRequest) validateTriggerOption(formats strfmt.Registry) error { + + if err := validate.Required("triggerOption", "body", m.TriggerOption); err != nil { + return err + } + + for i := 0; i < len(m.TriggerOption); i++ { + if swag.IsZero(m.TriggerOption[i]) { // not required + continue + } + + if m.TriggerOption[i] != nil { + if err := m.TriggerOption[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *AddRuleRequest) validateNoticeOption(formats strfmt.Registry) error { + + if err := validate.Required("noticeOption", "body", m.NoticeOption); err != nil { + return err + } + + if m.NoticeOption != nil { + if err := m.NoticeOption.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("noticeOption") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("noticeOption") + } + return err + } + } + + return nil +} + +// ContextValidate validate this add rule request based on the context it is used +func (m *AddRuleRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateTriggerOption(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateNoticeOption(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AddRuleRequest) contextValidateTriggerOption(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.TriggerOption); i++ { + + if m.TriggerOption[i] != nil { + if err := m.TriggerOption[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *AddRuleRequest) contextValidateNoticeOption(ctx context.Context, formats strfmt.Registry) error { + + if m.NoticeOption != nil { + if err := m.NoticeOption.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("noticeOption") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("noticeOption") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *AddRuleRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AddRuleRequest) UnmarshalBinary(b []byte) error { + var res AddRuleRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/agent_status_item.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/agent_status_item.go new file mode 100644 index 0000000..2aa421b --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/agent_status_item.go @@ -0,0 +1,65 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// AgentStatusItem agent status item +// +// swagger:model AgentStatusItem +type AgentStatusItem struct { + + // agent version + AgentVersion string `json:"agent_version,omitempty"` + + // instance ID + InstanceID string `json:"instance_id,omitempty"` + + // s n + SN string `json:"sn,omitempty"` + + // 1->running 2->stopped 0->unknown + Status int64 `json:"status,omitempty"` + + // status 运行 停止 未知 + StatusName string `json:"statusName,omitempty"` + + // timestamp + Timestamp int64 `json:"timestamp,omitempty"` +} + +// Validate validates this agent status item +func (m *AgentStatusItem) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this agent status item based on context it is used +func (m *AgentStatusItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *AgentStatusItem) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AgentStatusItem) UnmarshalBinary(b []byte) error { + var res AgentStatusItem + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/agent_status_response.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/agent_status_response.go new file mode 100644 index 0000000..1e9bfb3 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/agent_status_response.go @@ -0,0 +1,116 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// AgentStatusResponse agent status response +// +// swagger:model AgentStatusResponse +type AgentStatusResponse struct { + + // agent status + AgentStatus []*AgentStatusItem `json:"agentStatus"` +} + +// Validate validates this agent status response +func (m *AgentStatusResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAgentStatus(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AgentStatusResponse) validateAgentStatus(formats strfmt.Registry) error { + if swag.IsZero(m.AgentStatus) { // not required + return nil + } + + for i := 0; i < len(m.AgentStatus); i++ { + if swag.IsZero(m.AgentStatus[i]) { // not required + continue + } + + if m.AgentStatus[i] != nil { + if err := m.AgentStatus[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("agentStatus" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("agentStatus" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this agent status response based on the context it is used +func (m *AgentStatusResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateAgentStatus(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AgentStatusResponse) contextValidateAgentStatus(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.AgentStatus); i++ { + + if m.AgentStatus[i] != nil { + if err := m.AgentStatus[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("agentStatus" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("agentStatus" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *AgentStatusResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AgentStatusResponse) UnmarshalBinary(b []byte) error { + var res AgentStatusResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/alert.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/alert.go new file mode 100644 index 0000000..fac0eb7 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/alert.go @@ -0,0 +1,192 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Alert alert +// +// swagger:model Alert +type Alert struct { + + // alert uuid + AlertID string `json:"alertId,omitempty"` + + // 1表示一般,2表示严重,3表示紧急 + AlertLevel int64 `json:"alertLevel,omitempty"` + + // 级别描述 + AlertLevelDescription string `json:"alertLevelDescription,omitempty"` + + // 告警持续时间(分钟为单位) + AlertPeriod int64 `json:"alertPeriod,omitempty"` + + // 告警时间戳 + AlertTime int64 `json:"alertTime,omitempty"` + + // 报警值 + AlertValue string `json:"alertValue,omitempty"` + + // 创建时间戳 + CreatedTime int64 `json:"createdTime,omitempty"` + + // 资源类型 [只支持instance一种] + Resource string `json:"resource,omitempty"` + + // 资源id,目前就是实例id + ResourceID string `json:"resourceId,omitempty"` + + // 资源名称,目前就是实例名称 + ResourceName string `json:"resourceName,omitempty"` + + // 触发条件,接口需要翻译 + Trigger string `json:"trigger,omitempty"` + + // 触发条件描述 + TriggerDescription string `json:"triggerDescription,omitempty"` + + // 通知对象 userid + UserID string `json:"userId,omitempty"` + + // 通知对象 用户名 + UserName string `json:"userName,omitempty"` + + // instance + Instance *Instance `json:"instance,omitempty"` + + // rule + Rule *Rule `json:"rule,omitempty"` +} + +// Validate validates this alert +func (m *Alert) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstance(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRule(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Alert) validateInstance(formats strfmt.Registry) error { + if swag.IsZero(m.Instance) { // not required + return nil + } + + if m.Instance != nil { + if err := m.Instance.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instance") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instance") + } + return err + } + } + + return nil +} + +func (m *Alert) validateRule(formats strfmt.Registry) error { + if swag.IsZero(m.Rule) { // not required + return nil + } + + if m.Rule != nil { + if err := m.Rule.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("rule") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("rule") + } + return err + } + } + + return nil +} + +// ContextValidate validate this alert based on the context it is used +func (m *Alert) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateInstance(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateRule(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Alert) contextValidateInstance(ctx context.Context, formats strfmt.Registry) error { + + if m.Instance != nil { + if err := m.Instance.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instance") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instance") + } + return err + } + } + + return nil +} + +func (m *Alert) contextValidateRule(ctx context.Context, formats strfmt.Registry) error { + + if m.Rule != nil { + if err := m.Rule.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("rule") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("rule") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Alert) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Alert) UnmarshalBinary(b []byte) error { + var res Alert + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/alert_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/alert_list.go new file mode 100644 index 0000000..1d844d3 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/alert_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// AlertList alert list +// +// swagger:model AlertList +type AlertList struct { + + // rules数组 + Alerts []*Alert `json:"instances"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this alert list +func (m *AlertList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAlerts(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AlertList) validateAlerts(formats strfmt.Registry) error { + if swag.IsZero(m.Alerts) { // not required + return nil + } + + for i := 0; i < len(m.Alerts); i++ { + if swag.IsZero(m.Alerts[i]) { // not required + continue + } + + if m.Alerts[i] != nil { + if err := m.Alerts[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this alert list based on the context it is used +func (m *AlertList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateAlerts(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AlertList) contextValidateAlerts(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Alerts); i++ { + + if m.Alerts[i] != nil { + if err := m.Alerts[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *AlertList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AlertList) UnmarshalBinary(b []byte) error { + var res AlertList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/apikey.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/apikey.go new file mode 100644 index 0000000..415fe37 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/apikey.go @@ -0,0 +1,171 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Apikey apikey +// +// swagger:model Apikey +type Apikey struct { + + // apikey uuid + // Required: true + ApikeyID *string `json:"apiKeyId"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // ID + ID int64 `json:"id,omitempty"` + + // 名称 + // Required: true + Name *string `json:"name"` + + // 是否支持只读, [0/1], 1表示只读 + // Required: true + ReadOnly *int8 `json:"readOnly"` + + // 32位字符令牌,使用token来独立访问openapi + // Required: true + Token *string `json:"token"` + + // apikey的类型,[system/user] + // Required: true + Type *string `json:"type"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 所属用户uuid + // Required: true + UserID *string `json:"userId"` +} + +// Validate validates this apikey +func (m *Apikey) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateApikeyID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateReadOnly(formats); err != nil { + res = append(res, err) + } + + if err := m.validateToken(formats); err != nil { + res = append(res, err) + } + + if err := m.validateType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Apikey) validateApikeyID(formats strfmt.Registry) error { + + if err := validate.Required("apiKeyId", "body", m.ApikeyID); err != nil { + return err + } + + return nil +} + +func (m *Apikey) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +func (m *Apikey) validateReadOnly(formats strfmt.Registry) error { + + if err := validate.Required("readOnly", "body", m.ReadOnly); err != nil { + return err + } + + return nil +} + +func (m *Apikey) validateToken(formats strfmt.Registry) error { + + if err := validate.Required("token", "body", m.Token); err != nil { + return err + } + + return nil +} + +func (m *Apikey) validateType(formats strfmt.Registry) error { + + if err := validate.Required("type", "body", m.Type); err != nil { + return err + } + + return nil +} + +func (m *Apikey) validateUserID(formats strfmt.Registry) error { + + if err := validate.Required("userId", "body", m.UserID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this apikey based on context it is used +func (m *Apikey) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Apikey) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Apikey) UnmarshalBinary(b []byte) error { + var res Apikey + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/apikey_id.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/apikey_id.go new file mode 100644 index 0000000..6097b8a --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/apikey_id.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ApikeyID apikey Id +// +// swagger:model ApikeyId +type ApikeyID struct { + + // apikey uuid + // Required: true + ApikeyID *string `json:"apikeyId"` +} + +// Validate validates this apikey Id +func (m *ApikeyID) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateApikeyID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ApikeyID) validateApikeyID(formats strfmt.Registry) error { + + if err := validate.Required("apikeyId", "body", m.ApikeyID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this apikey Id based on context it is used +func (m *ApikeyID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ApikeyID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ApikeyID) UnmarshalBinary(b []byte) error { + var res ApikeyID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/apikey_info.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/apikey_info.go new file mode 100644 index 0000000..652fa8c --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/apikey_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ApikeyInfo apikey info +// +// swagger:model ApikeyInfo +type ApikeyInfo struct { + + // apikey + Apikey *Apikey `json:"apikey,omitempty"` +} + +// Validate validates this apikey info +func (m *ApikeyInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateApikey(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ApikeyInfo) validateApikey(formats strfmt.Registry) error { + if swag.IsZero(m.Apikey) { // not required + return nil + } + + if m.Apikey != nil { + if err := m.Apikey.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("apikey") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("apikey") + } + return err + } + } + + return nil +} + +// ContextValidate validate this apikey info based on the context it is used +func (m *ApikeyInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateApikey(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ApikeyInfo) contextValidateApikey(ctx context.Context, formats strfmt.Registry) error { + + if m.Apikey != nil { + if err := m.Apikey.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("apikey") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("apikey") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ApikeyInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ApikeyInfo) UnmarshalBinary(b []byte) error { + var res ApikeyInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/apikey_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/apikey_list.go new file mode 100644 index 0000000..6cceae9 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/apikey_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ApikeyList apikey list +// +// swagger:model ApikeyList +type ApikeyList struct { + + // apikeys + Apikeys []*Apikey `json:"apikeys"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this apikey list +func (m *ApikeyList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateApikeys(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ApikeyList) validateApikeys(formats strfmt.Registry) error { + if swag.IsZero(m.Apikeys) { // not required + return nil + } + + for i := 0; i < len(m.Apikeys); i++ { + if swag.IsZero(m.Apikeys[i]) { // not required + continue + } + + if m.Apikeys[i] != nil { + if err := m.Apikeys[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("apikeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("apikeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this apikey list based on the context it is used +func (m *ApikeyList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateApikeys(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ApikeyList) contextValidateApikeys(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Apikeys); i++ { + + if m.Apikeys[i] != nil { + if err := m.Apikeys[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("apikeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("apikeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ApikeyList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ApikeyList) UnmarshalBinary(b []byte) error { + var res ApikeyList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/audit_log.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/audit_log.go new file mode 100644 index 0000000..ae6098d --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/audit_log.go @@ -0,0 +1,86 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// AuditLog audit log +// +// swagger:model AuditLog +type AuditLog struct { + + // device_id + DeviceID string `json:"deviceId,omitempty"` + + // 失败原因 + FailReason string `json:"failReason,omitempty"` + + // 完成时间 + FinishTime int64 `json:"finishTime,omitempty"` + + // ID + ID int64 `json:"id,omitempty"` + + // instance_id + InstanceID string `json:"instanceId,omitempty"` + + // 日志uuid + LogID string `json:"logid,omitempty"` + + // 操作时间 + OperateTime int64 `json:"operateTime,omitempty"` + + // 操作 + Operation string `json:"operation,omitempty"` + + // 操作名称 + OperationName string `json:"operationName,omitempty"` + + // 结果 success/fail + Result string `json:"result,omitempty"` + + // sn + Sn string `json:"sn,omitempty"` + + // 操作人 + UserID string `json:"userID,omitempty"` + + // 操作人 + UserName string `json:"userName,omitempty"` +} + +// Validate validates this audit log +func (m *AuditLog) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this audit log based on context it is used +func (m *AuditLog) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *AuditLog) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AuditLog) UnmarshalBinary(b []byte) error { + var res AuditLog + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/audit_log_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/audit_log_list.go new file mode 100644 index 0000000..510813d --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/audit_log_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// AuditLogList audit log list +// +// swagger:model AuditLogList +type AuditLogList struct { + + // 机型列表 + AuditLogs []*AuditLog `json:"auditLogs"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this audit log list +func (m *AuditLogList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAuditLogs(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AuditLogList) validateAuditLogs(formats strfmt.Registry) error { + if swag.IsZero(m.AuditLogs) { // not required + return nil + } + + for i := 0; i < len(m.AuditLogs); i++ { + if swag.IsZero(m.AuditLogs[i]) { // not required + continue + } + + if m.AuditLogs[i] != nil { + if err := m.AuditLogs[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("auditLogs" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("auditLogs" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this audit log list based on the context it is used +func (m *AuditLogList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateAuditLogs(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AuditLogList) contextValidateAuditLogs(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.AuditLogs); i++ { + + if m.AuditLogs[i] != nil { + if err := m.AuditLogs[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("auditLogs" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("auditLogs" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *AuditLogList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AuditLogList) UnmarshalBinary(b []byte) error { + var res AuditLogList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/audit_logs_type.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/audit_logs_type.go new file mode 100644 index 0000000..34decc2 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/audit_logs_type.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// AuditLogsType audit logs type +// +// swagger:model AuditLogsType +type AuditLogsType struct { + + // name,自动适配中英文 + Name string `json:"name,omitempty"` + + // 数据库中存储的operation + Operation string `json:"operation,omitempty"` +} + +// Validate validates this audit logs type +func (m *AuditLogsType) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this audit logs type based on context it is used +func (m *AuditLogsType) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *AuditLogsType) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AuditLogsType) UnmarshalBinary(b []byte) error { + var res AuditLogsType + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/calcel_share_project_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/calcel_share_project_request.go new file mode 100644 index 0000000..f4d413a --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/calcel_share_project_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CalcelShareProjectRequest calcel share project request +// +// swagger:model CalcelShareProjectRequest +type CalcelShareProjectRequest struct { + + // from user_id + // Required: true + OwnerID *string `json:"ownerID"` + + // to user_id + // Required: true + SharerID *string `json:"sharerID"` +} + +// Validate validates this calcel share project request +func (m *CalcelShareProjectRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateOwnerID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSharerID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CalcelShareProjectRequest) validateOwnerID(formats strfmt.Registry) error { + + if err := validate.Required("ownerID", "body", m.OwnerID); err != nil { + return err + } + + return nil +} + +func (m *CalcelShareProjectRequest) validateSharerID(formats strfmt.Registry) error { + + if err := validate.Required("sharerID", "body", m.SharerID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this calcel share project request based on context it is used +func (m *CalcelShareProjectRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CalcelShareProjectRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CalcelShareProjectRequest) UnmarshalBinary(b []byte) error { + var res CalcelShareProjectRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/common_response.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/common_response.go new file mode 100644 index 0000000..f3957c5 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/common_response.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonResponse common response +// +// swagger:model CommonResponse +type CommonResponse struct { + + // 操作是否成功 [true/false] + Success bool `json:"success,omitempty"` +} + +// Validate validates this common response +func (m *CommonResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common response based on context it is used +func (m *CommonResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonResponse) UnmarshalBinary(b []byte) error { + var res CommonResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/create_apikey_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/create_apikey_request.go new file mode 100644 index 0000000..7462b07 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/create_apikey_request.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateApikeyRequest create apikey request +// +// swagger:model CreateApikeyRequest +type CreateApikeyRequest struct { + + // 秘钥对名称 + // Required: true + Name *string `json:"name"` + + // 是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法 + // Required: true + ReadOnly *int8 `json:"readOnly"` + + // Token类型, [system/user] + // Required: true + Type *string `json:"type"` +} + +// Validate validates this create apikey request +func (m *CreateApikeyRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateReadOnly(formats); err != nil { + res = append(res, err) + } + + if err := m.validateType(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateApikeyRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +func (m *CreateApikeyRequest) validateReadOnly(formats strfmt.Registry) error { + + if err := validate.Required("readOnly", "body", m.ReadOnly); err != nil { + return err + } + + return nil +} + +func (m *CreateApikeyRequest) validateType(formats strfmt.Registry) error { + + if err := validate.Required("type", "body", m.Type); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create apikey request based on context it is used +func (m *CreateApikeyRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateApikeyRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateApikeyRequest) UnmarshalBinary(b []byte) error { + var res CreateApikeyRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/create_instance_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/create_instance_request.go new file mode 100644 index 0000000..44efd90 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/create_instance_request.go @@ -0,0 +1,297 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateInstanceRequest create instance request +// +// swagger:model CreateInstanceRequest +type CreateInstanceRequest struct { + + // 启动模式 + BootMode string `json:"bootMode,omitempty"` + + // 创建数量 + Count int64 `json:"count,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 设备类型ID + // Required: true + DeviceTypeID *string `json:"deviceTypeId"` + + // 主机名称 + HostName string `json:"hostname,omitempty"` + + // 机房ID + // Required: true + IdcID *string `json:"idcId"` + + // 镜像ID + // Required: true + ImageID *string `json:"imageId"` + + // 是否安装bmp-agent + InstallBmpAgent bool `json:"installBmpAgent,omitempty"` + + // 实例名称 + // Required: true + InstanceName *string `json:"instanceName"` + + // 密码 + Password string `json:"password,omitempty"` + + // 项目ID + // Required: true + ProjectID *string `json:"projectId"` + + // 秘钥ID + SSHKeyID string `json:"sshKeyId,omitempty"` + + // 系统盘分区 + SystemPartition []*Partition `json:"systemPartition"` + + // 系统盘RAID ID + // Required: true + SystemVolumeRaidID *string `json:"systemVolumeRaidId"` + + // 数据卷和选择的raidid + VolumeRaIDs []*VolumeRaID `json:"VolumeRaids"` +} + +// Validate validates this create instance request +func (m *CreateInstanceRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceTypeID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIdcID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImageID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInstanceName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProjectID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemPartition(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemVolumeRaidID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVolumeRaIDs(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateInstanceRequest) validateDeviceTypeID(formats strfmt.Registry) error { + + if err := validate.Required("deviceTypeId", "body", m.DeviceTypeID); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateIdcID(formats strfmt.Registry) error { + + if err := validate.Required("idcId", "body", m.IdcID); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateImageID(formats strfmt.Registry) error { + + if err := validate.Required("imageId", "body", m.ImageID); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateInstanceName(formats strfmt.Registry) error { + + if err := validate.Required("instanceName", "body", m.InstanceName); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateProjectID(formats strfmt.Registry) error { + + if err := validate.Required("projectId", "body", m.ProjectID); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateSystemPartition(formats strfmt.Registry) error { + if swag.IsZero(m.SystemPartition) { // not required + return nil + } + + for i := 0; i < len(m.SystemPartition); i++ { + if swag.IsZero(m.SystemPartition[i]) { // not required + continue + } + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CreateInstanceRequest) validateSystemVolumeRaidID(formats strfmt.Registry) error { + + if err := validate.Required("systemVolumeRaidId", "body", m.SystemVolumeRaidID); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateVolumeRaIDs(formats strfmt.Registry) error { + if swag.IsZero(m.VolumeRaIDs) { // not required + return nil + } + + for i := 0; i < len(m.VolumeRaIDs); i++ { + if swag.IsZero(m.VolumeRaIDs[i]) { // not required + continue + } + + if m.VolumeRaIDs[i] != nil { + if err := m.VolumeRaIDs[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("VolumeRaids" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("VolumeRaids" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this create instance request based on the context it is used +func (m *CreateInstanceRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSystemPartition(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateVolumeRaIDs(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateInstanceRequest) contextValidateSystemPartition(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.SystemPartition); i++ { + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CreateInstanceRequest) contextValidateVolumeRaIDs(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.VolumeRaIDs); i++ { + + if m.VolumeRaIDs[i] != nil { + if err := m.VolumeRaIDs[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("VolumeRaids" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("VolumeRaids" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CreateInstanceRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateInstanceRequest) UnmarshalBinary(b []byte) error { + var res CreateInstanceRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/create_project_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/create_project_request.go new file mode 100644 index 0000000..017df2d --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/create_project_request.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateProjectRequest create project request +// +// swagger:model CreateProjectRequest +type CreateProjectRequest struct { + + // 是否作为该用户的默认项目, [0/1], 默认为0 + IsDefault int8 `json:"isDefault,omitempty"` + + // 是否作为系统项目, [0/1], 默认为0 + IsSystem int8 `json:"isSystem,omitempty"` + + // ProjectName 1~64字符,只支持数字、大小写字母、中英文下划线“_”及中划线“-” + // Required: true + ProjectName *string `json:"projectName"` +} + +// Validate validates this create project request +func (m *CreateProjectRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateProjectName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateProjectRequest) validateProjectName(formats strfmt.Registry) error { + + if err := validate.Required("projectName", "body", m.ProjectName); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create project request based on context it is used +func (m *CreateProjectRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateProjectRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateProjectRequest) UnmarshalBinary(b []byte) error { + var res CreateProjectRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/create_sshkey_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/create_sshkey_request.go new file mode 100644 index 0000000..8afaff3 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/create_sshkey_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateSshkeyRequest create sshkey request +// +// swagger:model CreateSshkeyRequest +type CreateSshkeyRequest struct { + + // 公钥内容,格式:^ssh-rsa AAAAB3NzaC1yc2.* + // Required: true + Key *string `json:"key"` + + // 秘钥名称 + // Required: true + Name *string `json:"name"` +} + +// Validate validates this create sshkey request +func (m *CreateSshkeyRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateKey(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateSshkeyRequest) validateKey(formats strfmt.Registry) error { + + if err := validate.Required("key", "body", m.Key); err != nil { + return err + } + + return nil +} + +func (m *CreateSshkeyRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create sshkey request based on context it is used +func (m *CreateSshkeyRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateSshkeyRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateSshkeyRequest) UnmarshalBinary(b []byte) error { + var res CreateSshkeyRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/data_every_metric.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/data_every_metric.go new file mode 100644 index 0000000..62fc3c2 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/data_every_metric.go @@ -0,0 +1,162 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DataEveryMetric data every metric +// +// swagger:model DataEveryMetric +type DataEveryMetric struct { + + // data + Data []*MonitorDataItem `json:"data"` + + // query + Query *MonitorDataQuery `json:"query,omitempty"` +} + +// Validate validates this data every metric +func (m *DataEveryMetric) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateData(formats); err != nil { + res = append(res, err) + } + + if err := m.validateQuery(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DataEveryMetric) validateData(formats strfmt.Registry) error { + if swag.IsZero(m.Data) { // not required + return nil + } + + for i := 0; i < len(m.Data); i++ { + if swag.IsZero(m.Data[i]) { // not required + continue + } + + if m.Data[i] != nil { + if err := m.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *DataEveryMetric) validateQuery(formats strfmt.Registry) error { + if swag.IsZero(m.Query) { // not required + return nil + } + + if m.Query != nil { + if err := m.Query.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("query") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("query") + } + return err + } + } + + return nil +} + +// ContextValidate validate this data every metric based on the context it is used +func (m *DataEveryMetric) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateQuery(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DataEveryMetric) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Data); i++ { + + if m.Data[i] != nil { + if err := m.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *DataEveryMetric) contextValidateQuery(ctx context.Context, formats strfmt.Registry) error { + + if m.Query != nil { + if err := m.Query.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("query") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("query") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DataEveryMetric) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DataEveryMetric) UnmarshalBinary(b []byte) error { + var res DataEveryMetric + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/delete_alert_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/delete_alert_request.go new file mode 100644 index 0000000..00089d3 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/delete_alert_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DeleteAlertRequest delete alert request +// +// swagger:model DeleteAlertRequest +type DeleteAlertRequest struct { + + // 告警id + // Required: true + AlertID *string `json:"alertId"` +} + +// Validate validates this delete alert request +func (m *DeleteAlertRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAlertID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeleteAlertRequest) validateAlertID(formats strfmt.Registry) error { + + if err := validate.Required("alertId", "body", m.AlertID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this delete alert request based on context it is used +func (m *DeleteAlertRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeleteAlertRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeleteAlertRequest) UnmarshalBinary(b []byte) error { + var res DeleteAlertRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/delete_instances_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/delete_instances_request.go new file mode 100644 index 0000000..c95504b --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/delete_instances_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeleteInstancesRequest 批量删除实例 +// +// swagger:model DeleteInstancesRequest +type DeleteInstancesRequest struct { + + // 实例id列表 + InstanceIDs []string `json:"instance_ids"` +} + +// Validate validates this delete instances request +func (m *DeleteInstancesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this delete instances request based on context it is used +func (m *DeleteInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeleteInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeleteInstancesRequest) UnmarshalBinary(b []byte) error { + var res DeleteInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/delete_messages_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/delete_messages_request.go new file mode 100644 index 0000000..2e44060 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/delete_messages_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DeleteMessagesRequest delete messages request +// +// swagger:model DeleteMessagesRequest +type DeleteMessagesRequest struct { + + // message ids + // Required: true + MessageIds []string `json:"messageIds"` +} + +// Validate validates this delete messages request +func (m *DeleteMessagesRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateMessageIds(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeleteMessagesRequest) validateMessageIds(formats strfmt.Registry) error { + + if err := validate.Required("messageIds", "body", m.MessageIds); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this delete messages request based on context it is used +func (m *DeleteMessagesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeleteMessagesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeleteMessagesRequest) UnmarshalBinary(b []byte) error { + var res DeleteMessagesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/delete_rule_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/delete_rule_request.go new file mode 100644 index 0000000..3080e96 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/delete_rule_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DeleteRuleRequest delete rule request +// +// swagger:model DeleteRuleRequest +type DeleteRuleRequest struct { + + // 规则id + // Required: true + RuleID *string `json:"ruleId"` +} + +// Validate validates this delete rule request +func (m *DeleteRuleRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRuleID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeleteRuleRequest) validateRuleID(formats strfmt.Registry) error { + + if err := validate.Required("ruleId", "body", m.RuleID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this delete rule request based on context it is used +func (m *DeleteRuleRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeleteRuleRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeleteRuleRequest) UnmarshalBinary(b []byte) error { + var res DeleteRuleRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device.go new file mode 100644 index 0000000..057bb4f --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device.go @@ -0,0 +1,344 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Device device +// +// swagger:model Device +type Device struct { + + // adapter_id + AdapterID int64 `json:"adapterId,omitempty"` + + // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Architecture string `json:"architecture,omitempty"` + + // 品牌 + Brand string `json:"brand,omitempty"` + + // cpu数量 + CPUAmount int64 `json:"cpuAmount,omitempty"` + + // 单个cpu内核数 + CPUCores int64 `json:"cpuCores,omitempty"` + + // cpu频率(G) + CPUFrequency string `json:"cpuFrequency,omitempty"` + + // cpu厂商 + CPUManufacturer string `json:"cpuManufacturer,omitempty"` + + // cpu处理器型号 + CPUModel string `json:"cpuModel,omitempty"` + + // 单个cpu路数 + CPURoads int8 `json:"cpuRoads,omitempty"` + + // 机柜编码 + Cabinet string `json:"cabinet,omitempty"` + + // 拼装信息 + CPUInfo string `json:"cpuInfo,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 数据盘数量 + DataVolumeAmount int64 `json:"dataVolumeAmount,omitempty"` + + // 数据盘接口类型(SATA,SAS,NVME) + DataVolumeInterfaceType string `json:"dataVolumeInterfaceType,omitempty"` + + // 数据盘单盘大小 + DataVolumeSize int64 `json:"dataVolumeSize,omitempty"` + + // 数据盘类型(SSD,HDD) + DataVolumeType string `json:"dataVolumeType,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 设备uuid + DeviceID string `json:"deviceId,omitempty"` + + // 计算型,存储型 + DeviceSeries string `json:"deviceSeries,omitempty"` + + // 计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName,omitempty"` + + // 型号,机型规格cps.normal + DeviceType string `json:"deviceType,omitempty"` + + // 机型uuid + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // 机型名称 + DeviceTypeName string `json:"deviceTypeName,omitempty"` + + // dv info + DvInfo string `json:"dvInfo,omitempty"` + + // 添加到disk表, 系统盘1背板号 + Enclosure1 string `json:"enclosure1,omitempty"` + + // 系统盘2背板号 + Enclosure2 string `json:"Enclosure2,omitempty"` + + // eth1子网掩码 + Eth1Mask string `json:"eth1Mask,omitempty"` + + // 网关地址 + Gateway string `json:"gateway,omitempty"` + + // gpu数量 + GpuAmount int64 `json:"gpuAmount,omitempty"` + + // gpu info + GpuInfo string `json:"gpuInfo,omitempty"` + + // gpu厂商 + GpuManufacturer string `json:"gpuManufacturer,omitempty"` + + // gpu处理器型号 + GpuModel string `json:"gpuModel,omitempty"` + + // 设备ID编号 + ID int64 `json:"id,omitempty"` + + // idcname + IDcNameEn string `json:"idcNameEn,omitempty"` + + // 机房uuid + // Required: true + IdcID *string `json:"idcId"` + + // 机房名称 + IdcName string `json:"idcName,omitempty"` + + // 带外管理IP + IloIP string `json:"iloIp,omitempty"` + + // 带外账号密码 + IloPassword string `json:"iloPassword,omitempty"` + + // 带外账号 + IloUser string `json:"iloUser,omitempty"` + + // 实例镜像名称 + ImageName string `json:"imageName,omitempty"` + + // 实例创建时间 + InstanceCreatedTime string `json:"instanceCreatedTime,omitempty"` + + // 实例描述 + InstanceDescription string `json:"instanceDescription,omitempty"` + + // 实例id + InstanceID string `json:"instanceId,omitempty"` + + // 实例名称 + InstanceName string `json:"instanceName,omitempty"` + + // 实例失败原因 + InstanceReason string `json:"instanceReason,omitempty"` + + // 实例状态 + InstanceStatus string `json:"instanceStatus,omitempty"` + + // 实例状态 + InstanceStatusName string `json:"instanceStatusName,omitempty"` + + // 【网口模式】【网络设置】: bond单网口,dual双网口 + InterfaceMode string `json:"interfaceMode,omitempty"` + + // 实例是否锁定 锁定locked 未锁定unlocked + Locked string `json:"locked,omitempty"` + + // MAC1(eth0) + Mac1 string `json:"mac1,omitempty"` + + // MAC2(eth2) + Mac2 string `json:"mac2,omitempty"` + + // 设备状态: 未装机,已装机 + ManageStatus string `json:"manageStatus,omitempty"` + + // 设备状态: 未装机,已装机 + ManageStatusName string `json:"manageStatusName,omitempty"` + + // 子网掩码 + Mask string `json:"mask,omitempty"` + + // 内存数量 + MemAmount int64 `json:"memAmount,omitempty"` + + // 内存主频(MHz) + MemFrequency int64 `json:"memFrequency,omitempty"` + + // mem info + MemInfo string `json:"memInfo,omitempty"` + + // 单个内存大小(GB) + MemSize int64 `json:"memSize,omitempty"` + + // 内存接口(如DDR3,DDR4) + MemType string `json:"memType,omitempty"` + + // 型号 + Model string `json:"model,omitempty"` + + // 网卡数量 + NicAmount int64 `json:"nicAmount,omitempty"` + + // nic info + NicInfo string `json:"nicInfo,omitempty"` + + // 网卡传输速率(GE) + NicRate int64 `json:"nicRate,omitempty"` + + // eth1内网IPV4 + PrivateEth1IPV4 string `json:"privateEth1Ipv4,omitempty"` + + // eth1内网IPV6 + PrivateEth1IPV6 string `json:"privateEth1Ipv6,omitempty"` + + // 内网IPV4 + PrivateIPV4 string `json:"privateIpv4,omitempty"` + + // 内网IPV6 + PrivateIPV6 string `json:"privateIpv6,omitempty"` + + // raid工具:(megacli64等) + RaidDriver string `json:"raidDriver,omitempty"` + + // 设备状态变更失败原因 + Reason string `json:"reason,omitempty"` + + // 系统盘1槽位 + Slot1 int64 `json:"slot1,omitempty"` + + // 系统盘2槽位 + Slot2 int64 `json:"slot2,omitempty"` + + // 设备SN + Sn string `json:"sn,omitempty"` + + // sv info + SvInfo string `json:"svInfo,omitempty"` + + // 网口交换机IP + SwitchIP string `json:"switchIp,omitempty"` + + // 交换机1ip + SwitchIP1 string `json:"switchIp1,omitempty"` + + // 交换机2ip + SwitchIP2 string `json:"switchIp2,omitempty"` + + // 交换机1登录密码 + SwitchPassword1 string `json:"switchPassword1,omitempty"` + + // 交换机2登录密码 + SwitchPassword2 string `json:"switchPassword2,omitempty"` + + // 交换机1port + SwitchPort1 string `json:"switchPort1,omitempty"` + + // 交换机2port + SwitchPort2 string `json:"switchPort2,omitempty"` + + // 交换机1登录账号,如果为空,取所在机房的值 + SwitchUser1 string `json:"switchUser1,omitempty"` + + // 交换机2登录账号,如果为空,取所在机房的值 + SwitchUser2 string `json:"switchUser2,omitempty"` + + // 系统盘数量 + SystemVolumeAmount int64 `json:"systemVolumeAmount,omitempty"` + + // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeInterfaceType string `json:"systemVolumeInterfaceType,omitempty"` + + // 系统盘单盘大小 + SystemVolumeSize int64 `json:"systemVolumeSize,omitempty"` + + // 系统盘类型(SSD,HDD) + SystemVolumeType string `json:"systemVolumeType,omitempty"` + + // U位 + UPosition string `json:"uPosition,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 实例归属用户uuid + UserID string `json:"userId,omitempty"` + + // 实例归属用户名称 + UserName string `json:"userName,omitempty"` +} + +// Validate validates this device +func (m *Device) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateIdcID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Device) validateIdcID(formats strfmt.Registry) error { + + if err := validate.Required("idcId", "body", m.IdcID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this device based on context it is used +func (m *Device) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Device) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Device) UnmarshalBinary(b []byte) error { + var res Device + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_info.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_info.go new file mode 100644 index 0000000..a70a4e4 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceInfo device info +// +// swagger:model DeviceInfo +type DeviceInfo struct { + + // device + Device *Device `json:"device,omitempty"` +} + +// Validate validates this device info +func (m *DeviceInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDevice(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceInfo) validateDevice(formats strfmt.Registry) error { + if swag.IsZero(m.Device) { // not required + return nil + } + + if m.Device != nil { + if err := m.Device.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("device") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("device") + } + return err + } + } + + return nil +} + +// ContextValidate validate this device info based on the context it is used +func (m *DeviceInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDevice(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceInfo) contextValidateDevice(ctx context.Context, formats strfmt.Registry) error { + + if m.Device != nil { + if err := m.Device.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("device") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("device") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceInfo) UnmarshalBinary(b []byte) error { + var res DeviceInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_list.go new file mode 100644 index 0000000..0f58c64 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceList device list +// +// swagger:model DeviceList +type DeviceList struct { + + // 设备列表 + Devices []*Device `json:"devices"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this device list +func (m *DeviceList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDevices(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceList) validateDevices(formats strfmt.Registry) error { + if swag.IsZero(m.Devices) { // not required + return nil + } + + for i := 0; i < len(m.Devices); i++ { + if swag.IsZero(m.Devices[i]) { // not required + continue + } + + if m.Devices[i] != nil { + if err := m.Devices[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("devices" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("devices" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this device list based on the context it is used +func (m *DeviceList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDevices(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceList) contextValidateDevices(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Devices); i++ { + + if m.Devices[i] != nil { + if err := m.Devices[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("devices" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("devices" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceList) UnmarshalBinary(b []byte) error { + var res DeviceList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_stock.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_stock.go new file mode 100644 index 0000000..5ad0cb9 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_stock.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceStock device stock +// +// swagger:model DeviceStock +type DeviceStock struct { + + // 库存量 + Stocks int64 `json:"stocks,omitempty"` +} + +// Validate validates this device stock +func (m *DeviceStock) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this device stock based on context it is used +func (m *DeviceStock) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceStock) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceStock) UnmarshalBinary(b []byte) error { + var res DeviceStock + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_type.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_type.go new file mode 100644 index 0000000..d5d887b --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_type.go @@ -0,0 +1,257 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceType device type +// +// swagger:model DeviceType +type DeviceType struct { + + // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Architecture string `json:"architecture,omitempty"` + + // boot模式 + BootMode string `json:"boot_mode,omitempty"` + + // cpu数量 + CPUAmount int64 `json:"cpuAmount,omitempty"` + + // 单个cpu内核数 + CPUCores int64 `json:"cpuCores,omitempty"` + + // cpu频率(G) + CPUFrequency string `json:"cpuFrequency,omitempty"` + + // cpu厂商 + CPUManufacturer string `json:"cpuManufacturer,omitempty"` + + // cpu处理器型号 + CPUModel string `json:"cpuModel,omitempty"` + + // 拼装信息 + CPUInfo string `json:"cpuInfo,omitempty"` + + // CPU 规格,预置还是其它 + CPUSpec string `json:"cpuSpec,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // device count + DeviceCount int64 `json:"deviceCount,omitempty"` + + // 机型类型,如计算型,存储型 + DeviceSeries string `json:"deviceSeries,omitempty"` + + // 机型类型,如计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName,omitempty"` + + // 机型规格, cps.c.normal + DeviceType string `json:"deviceType,omitempty"` + + // 机型uuid + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // dv info + DvInfo string `json:"dvInfo,omitempty"` + + // gpu数量 + GpuAmount int64 `json:"gpuAmount,omitempty"` + + // gpu info + GpuInfo string `json:"gpuInfo,omitempty"` + + // gpu厂商 + GpuManufacturer string `json:"gpuManufacturer,omitempty"` + + // gpu处理器型号 + GpuModel string `json:"gpuModel,omitempty"` + + // 显示机型高度 + Height int64 `json:"height,omitempty"` + + // ID + ID int64 `json:"id,omitempty"` + + // 机房uuid + IDcID string `json:"idcId,omitempty"` + + // 机房名称 + IDcName string `json:"idcName,omitempty"` + + // 机房名称 + IDcNameEn string `json:"idcNameEn,omitempty"` + + // instance count + InstanceCount int64 `json:"instanceCount,omitempty"` + + // instance status + InstanceStatus []string `json:"instanceStatus"` + + // bond单网口,dual双网口 + InterfaceMode string `json:"interfaceMode,omitempty"` + + // 是否配置了阵列卡 + IsNeedRaid string `json:"isNeedRaid,omitempty"` + + // 内存数量 + MemAmount int64 `json:"memAmount,omitempty"` + + // 内存主频(MHz) + MemFrequency int64 `json:"memFrequency,omitempty"` + + // mem info + MemInfo string `json:"memInfo,omitempty"` + + // 单个内存大小(GB) + MemSize int64 `json:"memSize,omitempty"` + + // 内存 规格,预置还是其它 + MemSpec string `json:"memSpec,omitempty"` + + // 内存接口(如DDR3,DDR4) + MemType string `json:"memType,omitempty"` + + // 机型名称,如计算效能型,标准计算型 + Name string `json:"name,omitempty"` + + // 网卡数量 + NicAmount int64 `json:"nicAmount,omitempty"` + + // nic info + NicInfo string `json:"nicInfo,omitempty"` + + // 网卡传输速率(GE) + NicRate int64 `json:"nicRate,omitempty"` + + // 系统盘raid + Raid string `json:"raid,omitempty"` + + // raid配置 + RaidCan string `json:"raidCan,omitempty"` + + // StockAvailable 可用库存 + StockAvailable int64 `json:"stockAvailable,omitempty"` + + // sv info + SvInfo string `json:"svInfo,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 机型的卷信息 + Volumes []*Volume `json:"volumes"` +} + +// Validate validates this device type +func (m *DeviceType) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateVolumes(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceType) validateVolumes(formats strfmt.Registry) error { + if swag.IsZero(m.Volumes) { // not required + return nil + } + + for i := 0; i < len(m.Volumes); i++ { + if swag.IsZero(m.Volumes[i]) { // not required + continue + } + + if m.Volumes[i] != nil { + if err := m.Volumes[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this device type based on the context it is used +func (m *DeviceType) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateVolumes(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceType) contextValidateVolumes(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Volumes); i++ { + + if m.Volumes[i] != nil { + if err := m.Volumes[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceType) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceType) UnmarshalBinary(b []byte) error { + var res DeviceType + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_type_info.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_type_info.go new file mode 100644 index 0000000..382e25c --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_type_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceTypeInfo device type info +// +// swagger:model DeviceTypeInfo +type DeviceTypeInfo struct { + + // device type + DeviceType *DeviceType `json:"deviceType,omitempty"` +} + +// Validate validates this device type info +func (m *DeviceTypeInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceType(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceTypeInfo) validateDeviceType(formats strfmt.Registry) error { + if swag.IsZero(m.DeviceType) { // not required + return nil + } + + if m.DeviceType != nil { + if err := m.DeviceType.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceType") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceType") + } + return err + } + } + + return nil +} + +// ContextValidate validate this device type info based on the context it is used +func (m *DeviceTypeInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDeviceType(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceTypeInfo) contextValidateDeviceType(ctx context.Context, formats strfmt.Registry) error { + + if m.DeviceType != nil { + if err := m.DeviceType.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceType") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceType") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceTypeInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceTypeInfo) UnmarshalBinary(b []byte) error { + var res DeviceTypeInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_type_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_type_list.go new file mode 100644 index 0000000..8959ae5 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/device_type_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceTypeList device type list +// +// swagger:model DeviceTypeList +type DeviceTypeList struct { + + // 机型列表 + DeviceTypes []*DeviceType `json:"deviceTypes"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this device type list +func (m *DeviceTypeList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceTypes(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceTypeList) validateDeviceTypes(formats strfmt.Registry) error { + if swag.IsZero(m.DeviceTypes) { // not required + return nil + } + + for i := 0; i < len(m.DeviceTypes); i++ { + if swag.IsZero(m.DeviceTypes[i]) { // not required + continue + } + + if m.DeviceTypes[i] != nil { + if err := m.DeviceTypes[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceTypes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceTypes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this device type list based on the context it is used +func (m *DeviceTypeList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDeviceTypes(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceTypeList) contextValidateDeviceTypes(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.DeviceTypes); i++ { + + if m.DeviceTypes[i] != nil { + if err := m.DeviceTypes[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceTypes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceTypes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceTypeList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceTypeList) UnmarshalBinary(b []byte) error { + var res DeviceTypeList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/disable_rule_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/disable_rule_request.go new file mode 100644 index 0000000..ce8ec67 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/disable_rule_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DisableRuleRequest disable rule request +// +// swagger:model DisableRuleRequest +type DisableRuleRequest struct { + + // 规则id + // Required: true + RuleID *string `json:"ruleId"` +} + +// Validate validates this disable rule request +func (m *DisableRuleRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRuleID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DisableRuleRequest) validateRuleID(formats strfmt.Registry) error { + + if err := validate.Required("ruleId", "body", m.RuleID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this disable rule request based on context it is used +func (m *DisableRuleRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DisableRuleRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DisableRuleRequest) UnmarshalBinary(b []byte) error { + var res DisableRuleRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/edit_rule_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/edit_rule_request.go new file mode 100644 index 0000000..30887f9 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/edit_rule_request.go @@ -0,0 +1,255 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// EditRuleRequest edit rule request +// +// swagger:model EditRuleRequest +type EditRuleRequest struct { + + // 盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag,omitempty"` + + // 维度 [instance、disk、mountpoint、nic] + // Required: true + Dimension *string `json:"dimension"` + + // 实例id列表 + // Required: true + InstanceIds []string `json:"instanceIds"` + + // 资源类型,目前只支持instance + // Required: true + Resource *string `json:"resource"` + + // 规则id + // Required: true + RuleID *string `json:"ruleId"` + + // 规则名称 + // Required: true + RuleName *string `json:"ruleName"` + + // 触发条件 + // Required: true + TriggerOption []*RuleTrigger `json:"triggerOption"` + + // notice option + // Required: true + NoticeOption *RuleNotice `json:"noticeOption"` +} + +// Validate validates this edit rule request +func (m *EditRuleRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDimension(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInstanceIds(formats); err != nil { + res = append(res, err) + } + + if err := m.validateResource(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRuleID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRuleName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTriggerOption(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNoticeOption(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *EditRuleRequest) validateDimension(formats strfmt.Registry) error { + + if err := validate.Required("dimension", "body", m.Dimension); err != nil { + return err + } + + return nil +} + +func (m *EditRuleRequest) validateInstanceIds(formats strfmt.Registry) error { + + if err := validate.Required("instanceIds", "body", m.InstanceIds); err != nil { + return err + } + + return nil +} + +func (m *EditRuleRequest) validateResource(formats strfmt.Registry) error { + + if err := validate.Required("resource", "body", m.Resource); err != nil { + return err + } + + return nil +} + +func (m *EditRuleRequest) validateRuleID(formats strfmt.Registry) error { + + if err := validate.Required("ruleId", "body", m.RuleID); err != nil { + return err + } + + return nil +} + +func (m *EditRuleRequest) validateRuleName(formats strfmt.Registry) error { + + if err := validate.Required("ruleName", "body", m.RuleName); err != nil { + return err + } + + return nil +} + +func (m *EditRuleRequest) validateTriggerOption(formats strfmt.Registry) error { + + if err := validate.Required("triggerOption", "body", m.TriggerOption); err != nil { + return err + } + + for i := 0; i < len(m.TriggerOption); i++ { + if swag.IsZero(m.TriggerOption[i]) { // not required + continue + } + + if m.TriggerOption[i] != nil { + if err := m.TriggerOption[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *EditRuleRequest) validateNoticeOption(formats strfmt.Registry) error { + + if err := validate.Required("noticeOption", "body", m.NoticeOption); err != nil { + return err + } + + if m.NoticeOption != nil { + if err := m.NoticeOption.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("noticeOption") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("noticeOption") + } + return err + } + } + + return nil +} + +// ContextValidate validate this edit rule request based on the context it is used +func (m *EditRuleRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateTriggerOption(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateNoticeOption(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *EditRuleRequest) contextValidateTriggerOption(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.TriggerOption); i++ { + + if m.TriggerOption[i] != nil { + if err := m.TriggerOption[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *EditRuleRequest) contextValidateNoticeOption(ctx context.Context, formats strfmt.Registry) error { + + if m.NoticeOption != nil { + if err := m.NoticeOption.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("noticeOption") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("noticeOption") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *EditRuleRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *EditRuleRequest) UnmarshalBinary(b []byte) error { + var res EditRuleRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/enable_rule_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/enable_rule_request.go new file mode 100644 index 0000000..e00eba4 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/enable_rule_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// EnableRuleRequest enable rule request +// +// swagger:model EnableRuleRequest +type EnableRuleRequest struct { + + // 规则id + // Required: true + RuleID *string `json:"ruleId"` +} + +// Validate validates this enable rule request +func (m *EnableRuleRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRuleID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *EnableRuleRequest) validateRuleID(formats strfmt.Registry) error { + + if err := validate.Required("ruleId", "body", m.RuleID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this enable rule request based on context it is used +func (m *EnableRuleRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *EnableRuleRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *EnableRuleRequest) UnmarshalBinary(b []byte) error { + var res EnableRuleRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/error_response.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/error_response.go new file mode 100644 index 0000000..e39f94b --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/error_response.go @@ -0,0 +1,56 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ErrorResponse error response +// +// swagger:model ErrorResponse +type ErrorResponse struct { + + // 错误码 + Code int64 `json:"code,omitempty"` + + // 错误信息 + Message string `json:"message,omitempty"` + + // 错误状态 + Status string `json:"status,omitempty"` +} + +// Validate validates this error response +func (m *ErrorResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this error response based on context it is used +func (m *ErrorResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ErrorResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ErrorResponse) UnmarshalBinary(b []byte) error { + var res ErrorResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/has_unread_message.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/has_unread_message.go new file mode 100644 index 0000000..c3a5dce --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/has_unread_message.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HasUnreadMessage has unread message +// +// swagger:model HasUnreadMessage +type HasUnreadMessage struct { + + // has unread + HasUnread bool `json:"hasUnread,omitempty"` +} + +// Validate validates this has unread message +func (m *HasUnreadMessage) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this has unread message based on context it is used +func (m *HasUnreadMessage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HasUnreadMessage) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HasUnreadMessage) UnmarshalBinary(b []byte) error { + var res HasUnreadMessage + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/idc.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/idc.go new file mode 100644 index 0000000..bbe18a9 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/idc.go @@ -0,0 +1,98 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Idc idc +// +// swagger:model Idc +type Idc struct { + + // 机房地址 + Address string `json:"address,omitempty"` + + // 创建时间 + CreateTime string `json:"createTime,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // ID + ID int64 `json:"id,omitempty"` + + // 机房uuid + IDcID string `json:"idcId,omitempty"` + + // 机房公用带外管理password + IloPassword string `json:"iloPassword,omitempty"` + + // 机房公用带外管理user + IloUser string `json:"iloUser,omitempty"` + + // 机房等级 + Level string `json:"level,omitempty"` + + // 机房名称 + Name string `json:"name,omitempty"` + + // 机房名称en + NameEn string `json:"nameEn,omitempty"` + + // shortname + Shortname string `json:"shortname,omitempty"` + + // 交换机密码1 + SwitchPassword1 string `json:"switchPassword1,omitempty"` + + // 交换机密码2 + SwitchPassword2 string `json:"switchPassword2,omitempty"` + + // 交换机用户名1 + SwitchUser1 string `json:"switchUser1,omitempty"` + + // 交换机用户名2 + SwitchUser2 string `json:"switchUser2,omitempty"` + + // 修改时间 + UpdateTime string `json:"updateTime,omitempty"` + + // 修改用户 + UpdatedBy string `json:"updatedBy,omitempty"` +} + +// Validate validates this idc +func (m *Idc) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this idc based on context it is used +func (m *Idc) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Idc) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Idc) UnmarshalBinary(b []byte) error { + var res Idc + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/idc_info.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/idc_info.go new file mode 100644 index 0000000..8ca49a0 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/idc_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// IdcInfo idc info +// +// swagger:model IdcInfo +type IdcInfo struct { + + // idc + Idc *Idc `json:"idc,omitempty"` +} + +// Validate validates this idc info +func (m *IdcInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateIdc(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *IdcInfo) validateIdc(formats strfmt.Registry) error { + if swag.IsZero(m.Idc) { // not required + return nil + } + + if m.Idc != nil { + if err := m.Idc.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("idc") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("idc") + } + return err + } + } + + return nil +} + +// ContextValidate validate this idc info based on the context it is used +func (m *IdcInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateIdc(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *IdcInfo) contextValidateIdc(ctx context.Context, formats strfmt.Registry) error { + + if m.Idc != nil { + if err := m.Idc.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("idc") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("idc") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *IdcInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *IdcInfo) UnmarshalBinary(b []byte) error { + var res IdcInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/idc_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/idc_list.go new file mode 100644 index 0000000..3cb1fe4 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/idc_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// IdcList idc list +// +// swagger:model IdcList +type IdcList struct { + + // 机房列表 + Idcs []*Idc `json:"idcs"` + + // 页数 + PageNumber int64 `json:"pageNumber,omitempty"` + + // 页大小 + PageSize int64 `json:"pageSize,omitempty"` + + // 总条数 + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this idc list +func (m *IdcList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateIdcs(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *IdcList) validateIdcs(formats strfmt.Registry) error { + if swag.IsZero(m.Idcs) { // not required + return nil + } + + for i := 0; i < len(m.Idcs); i++ { + if swag.IsZero(m.Idcs[i]) { // not required + continue + } + + if m.Idcs[i] != nil { + if err := m.Idcs[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("idcs" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("idcs" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this idc list based on the context it is used +func (m *IdcList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateIdcs(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *IdcList) contextValidateIdcs(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Idcs); i++ { + + if m.Idcs[i] != nil { + if err := m.Idcs[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("idcs" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("idcs" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *IdcList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *IdcList) UnmarshalBinary(b []byte) error { + var res IdcList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/image.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/image.go new file mode 100644 index 0000000..054c284 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/image.go @@ -0,0 +1,119 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Image image +// +// swagger:model Image +type Image struct { + + // 架构:x86/x64/i386/ + Architecture string `json:"architecture,omitempty"` + + // 引导模式 【UEFI Legacy/BIOS】 + BootMode string `json:"bootMode,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 数据分区信息 + DataPartition string `json:"dataPartition,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 绑定了机型数量 + DeviceTypeNum int64 `json:"deviceTypeNum,omitempty"` + + // 镜像文件名称 + Filename string `json:"filename,omitempty"` + + // 镜像格式(qcow2、tar) + Format string `json:"format,omitempty"` + + // 镜像校验码 + Hash string `json:"hash,omitempty"` + + // ID + ID uint64 `json:"id,omitempty"` + + // 镜像uuid + ImageID string `json:"imageId,omitempty"` + + // 镜像名称 + ImageName string `json:"imageName,omitempty"` + + // 是否绑定了某个机型 + IsBind bool `json:"isBind,omitempty"` + + // 源os uuid + OsID string `json:"osId,omitempty"` + + // CentOS 7.2 64-bit + OsName string `json:"osName,omitempty"` + + // 操作系统分类:linux/windows + OsType string `json:"osType,omitempty"` + + // 操作系统版本 + OsVersion string `json:"osVersion,omitempty"` + + // 镜像来源(common通用、customize定制、user_defined自定义) + Source string `json:"source,omitempty"` + + // 镜像来源(common通用、customize定制、user_defined自定义) + SourceName string `json:"sourceName,omitempty"` + + // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + SystemPartition string `json:"systemPartition,omitempty"` + + // 镜像源路径 + URL string `json:"url,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` +} + +// Validate validates this image +func (m *Image) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this image based on context it is used +func (m *Image) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Image) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Image) UnmarshalBinary(b []byte) error { + var res Image + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/image_info.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/image_info.go new file mode 100644 index 0000000..7064fb8 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/image_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ImageInfo image info +// +// swagger:model ImageInfo +type ImageInfo struct { + + // image + Image *Image `json:"image,omitempty"` +} + +// Validate validates this image info +func (m *ImageInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateImage(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ImageInfo) validateImage(formats strfmt.Registry) error { + if swag.IsZero(m.Image) { // not required + return nil + } + + if m.Image != nil { + if err := m.Image.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("image") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("image") + } + return err + } + } + + return nil +} + +// ContextValidate validate this image info based on the context it is used +func (m *ImageInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateImage(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ImageInfo) contextValidateImage(ctx context.Context, formats strfmt.Registry) error { + + if m.Image != nil { + if err := m.Image.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("image") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("image") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ImageInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ImageInfo) UnmarshalBinary(b []byte) error { + var res ImageInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/image_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/image_list.go new file mode 100644 index 0000000..61ce37d --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/image_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ImageList image list +// +// swagger:model ImageList +type ImageList struct { + + // 镜像实体列表 + Images []*Image `json:"images"` + + // 页数 + PageNumber int64 `json:"pageNumber,omitempty"` + + // 页大小 + PageSize int64 `json:"pageSize,omitempty"` + + // 总条数 + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this image list +func (m *ImageList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateImages(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ImageList) validateImages(formats strfmt.Registry) error { + if swag.IsZero(m.Images) { // not required + return nil + } + + for i := 0; i < len(m.Images); i++ { + if swag.IsZero(m.Images[i]) { // not required + continue + } + + if m.Images[i] != nil { + if err := m.Images[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("images" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("images" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this image list based on the context it is used +func (m *ImageList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateImages(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ImageList) contextValidateImages(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Images); i++ { + + if m.Images[i] != nil { + if err := m.Images[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("images" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("images" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ImageList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ImageList) UnmarshalBinary(b []byte) error { + var res ImageList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance.go new file mode 100644 index 0000000..ed18e4e --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance.go @@ -0,0 +1,272 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Instance instance +// +// swagger:model Instance +type Instance struct { + + // 引导模式 [UEFI Legacy/BIOS] + BootMode string `json:"bootMode,omitempty"` + + // cpu数量 + CPUAmount int64 `json:"cpuAmount,omitempty"` + + // 单个cpu内核数 + CPUCores int64 `json:"cpuCores,omitempty"` + + // cpu频率(GHz) + CPUFrequency string `json:"cpuFrequency,omitempty"` + + // cpu厂商 + CPUManufacturer string `json:"cpuManufacturer,omitempty"` + + // cpu处理器型号 + CPUModel string `json:"cpuModel,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 实例描述 + Description string `json:"description,omitempty"` + + // 设备uuid + DeviceID string `json:"deviceId,omitempty"` + + // 机型类型,如computer + DeviceSeries string `json:"deviceSeries,omitempty"` + + // 机型类型,如计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName,omitempty"` + + // 机型规格, cps.c.normal + DeviceType string `json:"deviceType,omitempty"` + + // 机型uuid + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // 机型名称,如计算效能型,标准计算型 + DeviceTypeName string `json:"deviceTypeName,omitempty"` + + // eth1 mask + Eth1Mask string `json:"eth1Mask,omitempty"` + + // gpu数量 + GpuAmount int64 `json:"gpuAmount,omitempty"` + + // gpu厂商 + GpuManufacturer string `json:"gpuManufacturer,omitempty"` + + // gpu处理器型号 + GpuModel string `json:"gpuModel,omitempty"` + + // 主机名 + Hostname string `json:"hostname,omitempty"` + + // 机房uuid + IDcID string `json:"idcId,omitempty"` + + // 机房名称 + IdcName string `json:"idcName,omitempty"` + + // 带外管理IP + IloIP string `json:"iloIp,omitempty"` + + // 镜像uuid + ImageID string `json:"imageId,omitempty"` + + // 镜像名称 + ImageName string `json:"imageName,omitempty"` + + // 实例uuid + InstanceID string `json:"instanceId,omitempty"` + + // 实例名称 + InstanceName string `json:"instanceName,omitempty"` + + // 实例的volume和raid信息 + InstanceVolumeRaids []*InstanceVolumeRaid `json:"volumeRaid"` + + // 【网口模式】【网络设置】: bond单网口,dual双网口 + InterfaceMode string `json:"interfaceMode,omitempty"` + + // 所属的机型是否需要配置raid,页面有用 + IsNeedRaid string `json:"isNeedRaid,omitempty"` + + // 是否锁定解锁锁定:locked,解锁unlocked + Locked string `json:"locked,omitempty"` + + // 是否锁定解锁锁定:已解锁,已锁定 + LockedName string `json:"lockedName,omitempty"` + + // mask + Mask string `json:"mask,omitempty"` + + // 内存数量 + MemAmount int64 `json:"memAmount,omitempty"` + + // 内存主频(MHz) + MemFrequency int64 `json:"memFrequency,omitempty"` + + // 单个内存大小(GB) + MemSize int64 `json:"memSize,omitempty"` + + // 内存接口(如DDR3,DDR4) + MemType string `json:"memType,omitempty"` + + // 网卡数量 + NicAmount int64 `json:"nicAmount,omitempty"` + + // 网卡传输速率(GE) + NicRate int64 `json:"nicRate,omitempty"` + + // eth1内网IPV4 + PrivateEth1IPV4 string `json:"privateEth1Ipv4,omitempty"` + + // eth1内网IPV6 + PrivateEth1IPV6 string `json:"privateEth1Ipv6,omitempty"` + + // 内网IPV4 + PrivateIPV4 string `json:"privateIpv4,omitempty"` + + // 内网IPV6 + PrivateIPV6 string `json:"privateIpv6,omitempty"` + + // 实例所属项目UUID + ProjectID string `json:"projectId,omitempty"` + + // 实例错误状态时的错误原因 + Reason string `json:"reason,omitempty"` + + // 设备SN + Sn string `json:"sn,omitempty"` + + // 运行状态 + Status string `json:"status,omitempty"` + + // 运行状态中文名字 + StatusName string `json:"statusName,omitempty"` + + // 系统盘raidId + SystemVolumeRaidID string `json:"systemVolumeRaidId,omitempty"` + + // 系统盘raid名称 + SystemVolumeRaidName string `json:"systemVolumeRaidName,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 实例所属用户UUID + UserID string `json:"userId,omitempty"` +} + +// Validate validates this instance +func (m *Instance) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstanceVolumeRaids(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Instance) validateInstanceVolumeRaids(formats strfmt.Registry) error { + if swag.IsZero(m.InstanceVolumeRaids) { // not required + return nil + } + + for i := 0; i < len(m.InstanceVolumeRaids); i++ { + if swag.IsZero(m.InstanceVolumeRaids[i]) { // not required + continue + } + + if m.InstanceVolumeRaids[i] != nil { + if err := m.InstanceVolumeRaids[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumeRaid" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumeRaid" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this instance based on the context it is used +func (m *Instance) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateInstanceVolumeRaids(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Instance) contextValidateInstanceVolumeRaids(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.InstanceVolumeRaids); i++ { + + if m.InstanceVolumeRaids[i] != nil { + if err := m.InstanceVolumeRaids[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumeRaid" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumeRaid" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Instance) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Instance) UnmarshalBinary(b []byte) error { + var res Instance + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_for_share.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_for_share.go new file mode 100644 index 0000000..b30c932 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_for_share.go @@ -0,0 +1,56 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstanceForShare instance for share +// +// swagger:model InstanceForShare +type InstanceForShare struct { + + // 新增,是否已经被共享过 + HasShared bool `json:"hasShared,omitempty"` + + // 实例uuid + InstanceID string `json:"instanceId,omitempty"` + + // 实例名称 + InstanceName string `json:"instanceName,omitempty"` +} + +// Validate validates this instance for share +func (m *InstanceForShare) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this instance for share based on context it is used +func (m *InstanceForShare) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *InstanceForShare) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstanceForShare) UnmarshalBinary(b []byte) error { + var res InstanceForShare + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_for_share_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_for_share_list.go new file mode 100644 index 0000000..58e6f97 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_for_share_list.go @@ -0,0 +1,116 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstanceForShareList instance for share list +// +// swagger:model InstanceForShareList +type InstanceForShareList struct { + + // instance实体数组 + Instances []*InstanceForShare `json:"instances"` +} + +// Validate validates this instance for share list +func (m *InstanceForShareList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstances(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceForShareList) validateInstances(formats strfmt.Registry) error { + if swag.IsZero(m.Instances) { // not required + return nil + } + + for i := 0; i < len(m.Instances); i++ { + if swag.IsZero(m.Instances[i]) { // not required + continue + } + + if m.Instances[i] != nil { + if err := m.Instances[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this instance for share list based on the context it is used +func (m *InstanceForShareList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateInstances(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceForShareList) contextValidateInstances(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Instances); i++ { + + if m.Instances[i] != nil { + if err := m.Instances[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *InstanceForShareList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstanceForShareList) UnmarshalBinary(b []byte) error { + var res InstanceForShareList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_ids.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_ids.go new file mode 100644 index 0000000..1120ae1 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_ids.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstanceIds instance ids +// +// swagger:model InstanceIds +type InstanceIds struct { + + // instanceId 列表 + InstanceIds []string `json:"instanceIds"` +} + +// Validate validates this instance ids +func (m *InstanceIds) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this instance ids based on context it is used +func (m *InstanceIds) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *InstanceIds) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstanceIds) UnmarshalBinary(b []byte) error { + var res InstanceIds + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_info.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_info.go new file mode 100644 index 0000000..abf1a71 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstanceInfo instance info +// +// swagger:model InstanceInfo +type InstanceInfo struct { + + // instance + Instance *Instance `json:"instance,omitempty"` +} + +// Validate validates this instance info +func (m *InstanceInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstance(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceInfo) validateInstance(formats strfmt.Registry) error { + if swag.IsZero(m.Instance) { // not required + return nil + } + + if m.Instance != nil { + if err := m.Instance.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instance") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instance") + } + return err + } + } + + return nil +} + +// ContextValidate validate this instance info based on the context it is used +func (m *InstanceInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateInstance(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceInfo) contextValidateInstance(ctx context.Context, formats strfmt.Registry) error { + + if m.Instance != nil { + if err := m.Instance.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instance") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instance") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *InstanceInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstanceInfo) UnmarshalBinary(b []byte) error { + var res InstanceInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_list.go new file mode 100644 index 0000000..1cdd579 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstanceList instance list +// +// swagger:model InstanceList +type InstanceList struct { + + // instance实体数组 + Instances []*Instance `json:"instances"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this instance list +func (m *InstanceList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstances(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceList) validateInstances(formats strfmt.Registry) error { + if swag.IsZero(m.Instances) { // not required + return nil + } + + for i := 0; i < len(m.Instances); i++ { + if swag.IsZero(m.Instances[i]) { // not required + continue + } + + if m.Instances[i] != nil { + if err := m.Instances[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this instance list based on the context it is used +func (m *InstanceList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateInstances(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceList) contextValidateInstances(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Instances); i++ { + + if m.Instances[i] != nil { + if err := m.Instances[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *InstanceList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstanceList) UnmarshalBinary(b []byte) error { + var res InstanceList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_volume_raid.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_volume_raid.go new file mode 100644 index 0000000..885b029 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instance_volume_raid.go @@ -0,0 +1,150 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstanceVolumeRaid instance volume raid +// +// swagger:model InstanceVolumeRaid +type InstanceVolumeRaid struct { + + // raid + Raid *Raid `json:"raid,omitempty"` + + // volume + Volume *Volume `json:"volume,omitempty"` +} + +// Validate validates this instance volume raid +func (m *InstanceVolumeRaid) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRaid(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVolume(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceVolumeRaid) validateRaid(formats strfmt.Registry) error { + if swag.IsZero(m.Raid) { // not required + return nil + } + + if m.Raid != nil { + if err := m.Raid.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("raid") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("raid") + } + return err + } + } + + return nil +} + +func (m *InstanceVolumeRaid) validateVolume(formats strfmt.Registry) error { + if swag.IsZero(m.Volume) { // not required + return nil + } + + if m.Volume != nil { + if err := m.Volume.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volume") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volume") + } + return err + } + } + + return nil +} + +// ContextValidate validate this instance volume raid based on the context it is used +func (m *InstanceVolumeRaid) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateRaid(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateVolume(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceVolumeRaid) contextValidateRaid(ctx context.Context, formats strfmt.Registry) error { + + if m.Raid != nil { + if err := m.Raid.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("raid") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("raid") + } + return err + } + } + + return nil +} + +func (m *InstanceVolumeRaid) contextValidateVolume(ctx context.Context, formats strfmt.Registry) error { + + if m.Volume != nil { + if err := m.Volume.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volume") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volume") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *InstanceVolumeRaid) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstanceVolumeRaid) UnmarshalBinary(b []byte) error { + var res InstanceVolumeRaid + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instances_sshkey_info_response.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instances_sshkey_info_response.go new file mode 100644 index 0000000..e0acfb3 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/instances_sshkey_info_response.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstancesSshkeyInfoResponse instances sshkey info response +// +// swagger:model InstancesSshkeyInfoResponse +type InstancesSshkeyInfoResponse struct { + + // 实例Id列表 + InstanceIds []string `json:"instanceIds"` +} + +// Validate validates this instances sshkey info response +func (m *InstancesSshkeyInfoResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this instances sshkey info response based on context it is used +func (m *InstancesSshkeyInfoResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *InstancesSshkeyInfoResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstancesSshkeyInfoResponse) UnmarshalBinary(b []byte) error { + var res InstancesSshkeyInfoResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/license_content.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/license_content.go new file mode 100644 index 0000000..eb375b0 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/license_content.go @@ -0,0 +1,74 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// LicenseContent license content +// +// swagger:model LicenseContent +type LicenseContent struct { + + // end time + EndTime int64 `json:"end_time,omitempty"` + + // hard ware + HardWare string `json:"hardwareinfo,omitempty"` + + // license name + LicenseName string `json:"license_name,omitempty"` + + // license type + LicenseType string `json:"license_type,omitempty"` + + // models + Models []string `json:"models"` + + // nodes num + NodesNum int64 `json:"nodes_num,omitempty"` + + // start time + StartTime int64 `json:"start_time,omitempty"` + + // used nodes num + UsedNodesNum int64 `json:"used_nodes_num,omitempty"` + + // version + Version string `json:"version,omitempty"` +} + +// Validate validates this license content +func (m *LicenseContent) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this license content based on context it is used +func (m *LicenseContent) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *LicenseContent) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *LicenseContent) UnmarshalBinary(b []byte) error { + var res LicenseContent + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/message.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/message.go new file mode 100644 index 0000000..4dbda28 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/message.go @@ -0,0 +1,140 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Message message +// +// swagger:model Message +type Message struct { + + // 告警次数,始终为1,带外故障消息专属字段 + AlertCount int64 `json:"alert_count,omitempty"` + + // 故障告警时间,带外故障消息专属字段 + AlertTime int64 `json:"alert_time,omitempty"` + + // 故障内容,带外故障消息专属字段 + Content string `json:"content,omitempty"` + + // 详情, 带外监控日志的详情请用content + Detail string `json:"detail,omitempty"` + + // device ID + DeviceID string `json:"device_id,omitempty"` + + // 故障类型, 带外故障消息专属字段 + FaultType string `json:"fault_type,omitempty"` + + // 消息时间戳 + FinishTime int64 `json:"finish_time,omitempty"` + + // 0未读, 1已读 + HasRead int8 `json:"has_read,omitempty"` + + // 独一处的下划线,跟sdk一致 + IDcID string `json:"idc_id,omitempty"` + + // i dc name + IDcName string `json:"idc_name,omitempty"` + + // 实例id + InstanceID string `json:"instance_id,omitempty"` + + // 实例name + InstanceName string `json:"instance_name,omitempty"` + + // 是否删除0未删除 1已删除 + IsDel int8 `json:"is_del,omitempty"` + + // is recover + IsRecover int8 `json:"is_recover,omitempty"` + + // 版本名称, 许可证到期消息专属字段 + LicenseName string `json:"license_name,omitempty"` + + // 版本号, 许可证到期消息专属字段 + LicenseNumber string `json:"license_number,omitempty"` + + // 结束时间, 许可证到期消息专属字段 + LienseEndTime int64 `json:"license_end_time,omitempty"` + + // 开始时间, 许可证到期消息专属字段 + LienseStartTime int64 `json:"license_start_time,omitempty"` + + // 系统原始日志id, 带外故障消息专属字段 + LogID string `json:"logid,omitempty"` + + // message uuid + MessageID string `json:"message_id,omitempty"` + + // 消息子类型 + MessageSubType string `json:"message_sub_type,omitempty"` + + // 消息类型 + MessageType string `json:"message_type,omitempty"` + + // project ID + ProjectID string `json:"project_id,omitempty"` + + // project name + ProjectName string `json:"project_name,omitempty"` + + // 资源类型 实例/设备 + ResourceType string `json:"resource_type,omitempty"` + + // 操作结果 fail/succ + Result string `json:"result,omitempty"` + + // inbond rule uuid + RuleID string `json:"rule_id,omitempty"` + + // inbond rule name + RuleName string `json:"rule_name,omitempty"` + + // 设备sn + SN string `json:"sn,omitempty"` + + // user_id + UserID string `json:"user_id,omitempty"` + + // user_name + UserName string `json:"user_name,omitempty"` +} + +// Validate validates this message +func (m *Message) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this message based on context it is used +func (m *Message) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Message) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Message) UnmarshalBinary(b []byte) error { + var res Message + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/message_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/message_list.go new file mode 100644 index 0000000..655c2b1 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/message_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// MessageList message list +// +// swagger:model MessageList +type MessageList struct { + + // messages + Messages []*Message `json:"messages"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this message list +func (m *MessageList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateMessages(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MessageList) validateMessages(formats strfmt.Registry) error { + if swag.IsZero(m.Messages) { // not required + return nil + } + + for i := 0; i < len(m.Messages); i++ { + if swag.IsZero(m.Messages[i]) { // not required + continue + } + + if m.Messages[i] != nil { + if err := m.Messages[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("messages" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("messages" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this message list based on the context it is used +func (m *MessageList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateMessages(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MessageList) contextValidateMessages(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Messages); i++ { + + if m.Messages[i] != nil { + if err := m.Messages[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("messages" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("messages" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *MessageList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MessageList) UnmarshalBinary(b []byte) error { + var res MessageList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/message_statistic.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/message_statistic.go new file mode 100644 index 0000000..89a5a76 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/message_statistic.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// MessageStatistic message statistic +// +// swagger:model MessageStatistic +type MessageStatistic struct { + + // total count + TotalCount int64 `json:"totalCount,omitempty"` + + // unread count + UnreadCount int64 `json:"unreadCount,omitempty"` +} + +// Validate validates this message statistic +func (m *MessageStatistic) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this message statistic based on context it is used +func (m *MessageStatistic) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *MessageStatistic) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MessageStatistic) UnmarshalBinary(b []byte) error { + var res MessageStatistic + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/message_types_resp.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/message_types_resp.go new file mode 100644 index 0000000..0a51420 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/message_types_resp.go @@ -0,0 +1,27 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" +) + +// MessageTypesResp message types resp +// +// swagger:model MessageTypesResp +type MessageTypesResp map[string][]string + +// Validate validates this message types resp +func (m MessageTypesResp) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this message types resp based on context it is used +func (m MessageTypesResp) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/message_with_next_prev.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/message_with_next_prev.go new file mode 100644 index 0000000..ccf69b1 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/message_with_next_prev.go @@ -0,0 +1,110 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// MessageWithNextPrev message with next prev +// +// swagger:model MessageWithNextPrev +type MessageWithNextPrev struct { + + // next message Id + NextMessageID string `json:"nextMessageId,omitempty"` + + // prev message Id + PrevMessageID string `json:"prevMessageId,omitempty"` + + // message + Message *Message `json:"message,omitempty"` +} + +// Validate validates this message with next prev +func (m *MessageWithNextPrev) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateMessage(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MessageWithNextPrev) validateMessage(formats strfmt.Registry) error { + if swag.IsZero(m.Message) { // not required + return nil + } + + if m.Message != nil { + if err := m.Message.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("message") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("message") + } + return err + } + } + + return nil +} + +// ContextValidate validate this message with next prev based on the context it is used +func (m *MessageWithNextPrev) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateMessage(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MessageWithNextPrev) contextValidateMessage(ctx context.Context, formats strfmt.Registry) error { + + if m.Message != nil { + if err := m.Message.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("message") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("message") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *MessageWithNextPrev) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MessageWithNextPrev) UnmarshalBinary(b []byte) error { + var res MessageWithNextPrev + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_apikey_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_apikey_request.go new file mode 100644 index 0000000..8a852b2 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_apikey_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ModifyApikeyRequest modify apikey request +// +// swagger:model ModifyApikeyRequest +type ModifyApikeyRequest struct { + + // 秘钥对名称 + // Required: true + Name *string `json:"name"` + + // 是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法 + // Required: true + ReadOnly *int8 `json:"readOnly"` +} + +// Validate validates this modify apikey request +func (m *ModifyApikeyRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateReadOnly(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ModifyApikeyRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +func (m *ModifyApikeyRequest) validateReadOnly(formats strfmt.Registry) error { + + if err := validate.Required("readOnly", "body", m.ReadOnly); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this modify apikey request based on context it is used +func (m *ModifyApikeyRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyApikeyRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyApikeyRequest) UnmarshalBinary(b []byte) error { + var res ModifyApikeyRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_instance_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_instance_request.go new file mode 100644 index 0000000..6cf9850 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_instance_request.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyInstanceRequest modify instance request +// +// swagger:model ModifyInstanceRequest +type ModifyInstanceRequest struct { + + // 描述 + Description *string `json:"description,omitempty"` + + // 实例名称 + InstanceName string `json:"instanceName,omitempty"` +} + +// Validate validates this modify instance request +func (m *ModifyInstanceRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify instance request based on context it is used +func (m *ModifyInstanceRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyInstanceRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyInstanceRequest) UnmarshalBinary(b []byte) error { + var res ModifyInstanceRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_instances_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_instances_request.go new file mode 100644 index 0000000..93be971 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_instances_request.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyInstancesRequest 批量修改实例名称 +// +// swagger:model ModifyInstancesRequest +type ModifyInstancesRequest struct { + + // 实例id列表 + InstanceIDs []string `json:"instance_ids"` + + // 实例名称 + InstanceName string `json:"instanceName,omitempty"` +} + +// Validate validates this modify instances request +func (m *ModifyInstancesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify instances request based on context it is used +func (m *ModifyInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyInstancesRequest) UnmarshalBinary(b []byte) error { + var res ModifyInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_local_user_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_local_user_request.go new file mode 100644 index 0000000..f08328d --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_local_user_request.go @@ -0,0 +1,65 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyLocalUserRequest modify local user request +// +// swagger:model ModifyLocalUserRequest +type ModifyLocalUserRequest struct { + + // 用户默认项目uuid + DefaultProjectID *string `json:"defaultProjectId,omitempty"` + + // 邮箱 + Email *string `json:"email,omitempty"` + + // 语言[en_US, zh_CN] + Language *string `json:"language,omitempty"` + + // 手机号 + PhoneNumber *string `json:"phoneNumber,omitempty"` + + // 国家地区码,如86 + PhonePrefix *string `json:"phonePrefix,omitempty"` + + // 时区 Asia/Shanghai + Timezone *string `json:"timezone,omitempty"` +} + +// Validate validates this modify local user request +func (m *ModifyLocalUserRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify local user request based on context it is used +func (m *ModifyLocalUserRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyLocalUserRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyLocalUserRequest) UnmarshalBinary(b []byte) error { + var res ModifyLocalUserRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_project_description_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_project_description_request.go new file mode 100644 index 0000000..a2fb32f --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_project_description_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ModifyProjectDescriptionRequest modify project description request +// +// swagger:model ModifyProjectDescriptionRequest +type ModifyProjectDescriptionRequest struct { + + // 项目描述 + // Required: true + Description *string `json:"description"` +} + +// Validate validates this modify project description request +func (m *ModifyProjectDescriptionRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDescription(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ModifyProjectDescriptionRequest) validateDescription(formats strfmt.Registry) error { + + if err := validate.Required("description", "body", m.Description); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this modify project description request based on context it is used +func (m *ModifyProjectDescriptionRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyProjectDescriptionRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyProjectDescriptionRequest) UnmarshalBinary(b []byte) error { + var res ModifyProjectDescriptionRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_project_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_project_request.go new file mode 100644 index 0000000..1e030ef --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_project_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ModifyProjectRequest modify project request +// +// swagger:model ModifyProjectRequest +type ModifyProjectRequest struct { + + // 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + // Required: true + ProjectName *string `json:"projectName"` +} + +// Validate validates this modify project request +func (m *ModifyProjectRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateProjectName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ModifyProjectRequest) validateProjectName(formats strfmt.Registry) error { + + if err := validate.Required("projectName", "body", m.ProjectName); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this modify project request based on context it is used +func (m *ModifyProjectRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyProjectRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyProjectRequest) UnmarshalBinary(b []byte) error { + var res ModifyProjectRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_sshkey_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_sshkey_request.go new file mode 100644 index 0000000..5e17a3a --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_sshkey_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifySshkeyRequest modify sshkey request +// +// swagger:model ModifySshkeyRequest +type ModifySshkeyRequest struct { + + // 秘钥名称 + Name *string `json:"name,omitempty"` +} + +// Validate validates this modify sshkey request +func (m *ModifySshkeyRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify sshkey request based on context it is used +func (m *ModifySshkeyRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifySshkeyRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifySshkeyRequest) UnmarshalBinary(b []byte) error { + var res ModifySshkeyRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_user_password_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_user_password_request.go new file mode 100644 index 0000000..51fa312 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_user_password_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ModifyUserPasswordRequest modify user password request +// +// swagger:model ModifyUserPasswordRequest +type ModifyUserPasswordRequest struct { + + // 旧密码,明文 + // Required: true + OldPassword *string `json:"oldPassword"` + + // 新密码 明文,密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + // Required: true + Password *string `json:"password"` +} + +// Validate validates this modify user password request +func (m *ModifyUserPasswordRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateOldPassword(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePassword(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ModifyUserPasswordRequest) validateOldPassword(formats strfmt.Registry) error { + + if err := validate.Required("oldPassword", "body", m.OldPassword); err != nil { + return err + } + + return nil +} + +func (m *ModifyUserPasswordRequest) validatePassword(formats strfmt.Registry) error { + + if err := validate.Required("password", "body", m.Password); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this modify user password request based on context it is used +func (m *ModifyUserPasswordRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyUserPasswordRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyUserPasswordRequest) UnmarshalBinary(b []byte) error { + var res ModifyUserPasswordRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_user_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_user_request.go new file mode 100644 index 0000000..ea68964 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/modify_user_request.go @@ -0,0 +1,59 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyUserRequest modify user request +// +// swagger:model ModifyUserRequest +type ModifyUserRequest struct { + + // 描述 + Description *string `json:"description,omitempty"` + + // 邮箱 + Email *string `json:"email,omitempty"` + + // 手机号 + PhoneNumber *string `json:"phoneNumber,omitempty"` + + // 国家地区码,如86 + PhonePrefix *string `json:"phonePrefix,omitempty"` +} + +// Validate validates this modify user request +func (m *ModifyUserRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify user request based on context it is used +func (m *ModifyUserRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyUserRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyUserRequest) UnmarshalBinary(b []byte) error { + var res ModifyUserRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/monitor_data_item.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/monitor_data_item.go new file mode 100644 index 0000000..d3fc90e --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/monitor_data_item.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// MonitorDataItem monitor data item +// +// swagger:model MonitorDataItem +type MonitorDataItem struct { + + // timestamp + Timestamp int64 `json:"timestamp,omitempty"` + + // value + Value string `json:"value,omitempty"` +} + +// Validate validates this monitor data item +func (m *MonitorDataItem) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this monitor data item based on context it is used +func (m *MonitorDataItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *MonitorDataItem) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MonitorDataItem) UnmarshalBinary(b []byte) error { + var res MonitorDataItem + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/monitor_data_query.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/monitor_data_query.go new file mode 100644 index 0000000..f119ed8 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/monitor_data_query.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// MonitorDataQuery monitor data query +// +// swagger:model MonitorDataQuery +type MonitorDataQuery struct { + + // end time + EndTime int64 `json:"endTime,omitempty"` + + // 跟赛迪约定,转换单位放这里实现 + Func map[string]int64 `json:"func,omitempty"` + + // metric都放这里了 + Labels map[string]string `json:"labels,omitempty"` + + // MetricName string `json:"metricName"` + // [rate, increase] + SampleMethod string `json:"sampleMethod,omitempty"` + + // start time + StartTime int64 `json:"startTime,omitempty"` + + // step + Step int64 `json:"step,omitempty"` + + // [bmp_monitor_counter bmp_monitor_gauge] + TableName string `json:"tableName,omitempty"` +} + +// Validate validates this monitor data query +func (m *MonitorDataQuery) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this monitor data query based on context it is used +func (m *MonitorDataQuery) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *MonitorDataQuery) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MonitorDataQuery) UnmarshalBinary(b []byte) error { + var res MonitorDataQuery + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/move_instances_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/move_instances_request.go new file mode 100644 index 0000000..ea4e9a7 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/move_instances_request.go @@ -0,0 +1,139 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// MoveInstancesRequest move instances request +// +// swagger:model MoveInstancesRequest +type MoveInstancesRequest struct { + + // instanceIDs + // Required: true + InstanceIDs *string `json:"instanceIDs"` + + // to user_id + // Required: true + MoverID *string `json:"moverID"` + + // to project_id + // Required: true + MoverProjectID *string `json:"moverProjectID"` + + // from user_id + // Required: true + OwnerID *string `json:"ownerID"` + + // from project_id + // Required: true + OwnerProjectID *string `json:"ownerProjectID"` +} + +// Validate validates this move instances request +func (m *MoveInstancesRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstanceIDs(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMoverID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMoverProjectID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOwnerID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOwnerProjectID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MoveInstancesRequest) validateInstanceIDs(formats strfmt.Registry) error { + + if err := validate.Required("instanceIDs", "body", m.InstanceIDs); err != nil { + return err + } + + return nil +} + +func (m *MoveInstancesRequest) validateMoverID(formats strfmt.Registry) error { + + if err := validate.Required("moverID", "body", m.MoverID); err != nil { + return err + } + + return nil +} + +func (m *MoveInstancesRequest) validateMoverProjectID(formats strfmt.Registry) error { + + if err := validate.Required("moverProjectID", "body", m.MoverProjectID); err != nil { + return err + } + + return nil +} + +func (m *MoveInstancesRequest) validateOwnerID(formats strfmt.Registry) error { + + if err := validate.Required("ownerID", "body", m.OwnerID); err != nil { + return err + } + + return nil +} + +func (m *MoveInstancesRequest) validateOwnerProjectID(formats strfmt.Registry) error { + + if err := validate.Required("ownerProjectID", "body", m.OwnerProjectID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this move instances request based on context it is used +func (m *MoveInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *MoveInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MoveInstancesRequest) UnmarshalBinary(b []byte) error { + var res MoveInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/move_project_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/move_project_request.go new file mode 100644 index 0000000..6230dcd --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/move_project_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// MoveProjectRequest move project request +// +// swagger:model MoveProjectRequest +type MoveProjectRequest struct { + + // to user_id + // Required: true + MoverID *string `json:"moverID"` + + // from user_id + // Required: true + OwnerID *string `json:"ownerID"` +} + +// Validate validates this move project request +func (m *MoveProjectRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateMoverID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOwnerID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MoveProjectRequest) validateMoverID(formats strfmt.Registry) error { + + if err := validate.Required("moverID", "body", m.MoverID); err != nil { + return err + } + + return nil +} + +func (m *MoveProjectRequest) validateOwnerID(formats strfmt.Registry) error { + + if err := validate.Required("ownerID", "body", m.OwnerID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this move project request based on context it is used +func (m *MoveProjectRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *MoveProjectRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MoveProjectRequest) UnmarshalBinary(b []byte) error { + var res MoveProjectRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/os.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/os.go new file mode 100644 index 0000000..f563370 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/os.go @@ -0,0 +1,89 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Os os +// +// swagger:model Os +type Os struct { + + // 架构:x86/x64/i386/ + Architecture string `json:"architecture,omitempty"` + + // 指令宽度:64/32位 + Bits int64 `json:"bits,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 删除时间 + DeletedTime string `json:"deletedTime,omitempty"` + + // ID + ID uint64 `json:"id,omitempty"` + + // 是否删除0未删除 1已删除 + IsDel int8 `json:"isDel,omitempty"` + + // 操作系统uuid + OsID string `json:"osId,omitempty"` + + // 操作系统名称 + OsName string `json:"osName,omitempty"` + + // 操作系统分类:linux/windows + OsType string `json:"osType,omitempty"` + + // 操作系统版本 + OsVersion string `json:"osVersion,omitempty"` + + // 管理员账户 + SysUser string `json:"sysUser,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` +} + +// Validate validates this os +func (m *Os) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this os based on context it is used +func (m *Os) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Os) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Os) UnmarshalBinary(b []byte) error { + var res Os + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/os_info.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/os_info.go new file mode 100644 index 0000000..3042eb8 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/os_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// OsInfo os info +// +// swagger:model OsInfo +type OsInfo struct { + + // os + Os *Os `json:"os,omitempty"` +} + +// Validate validates this os info +func (m *OsInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateOs(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *OsInfo) validateOs(formats strfmt.Registry) error { + if swag.IsZero(m.Os) { // not required + return nil + } + + if m.Os != nil { + if err := m.Os.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("os") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("os") + } + return err + } + } + + return nil +} + +// ContextValidate validate this os info based on the context it is used +func (m *OsInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateOs(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *OsInfo) contextValidateOs(ctx context.Context, formats strfmt.Registry) error { + + if m.Os != nil { + if err := m.Os.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("os") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("os") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *OsInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *OsInfo) UnmarshalBinary(b []byte) error { + var res OsInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/os_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/os_list.go new file mode 100644 index 0000000..522f28d --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/os_list.go @@ -0,0 +1,116 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// OsList os list +// +// swagger:model OsList +type OsList struct { + + // 操作系统列表 + Oss []*Os `json:"oss"` +} + +// Validate validates this os list +func (m *OsList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateOss(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *OsList) validateOss(formats strfmt.Registry) error { + if swag.IsZero(m.Oss) { // not required + return nil + } + + for i := 0; i < len(m.Oss); i++ { + if swag.IsZero(m.Oss[i]) { // not required + continue + } + + if m.Oss[i] != nil { + if err := m.Oss[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("oss" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("oss" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this os list based on the context it is used +func (m *OsList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateOss(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *OsList) contextValidateOss(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Oss); i++ { + + if m.Oss[i] != nil { + if err := m.Oss[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("oss" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("oss" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *OsList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *OsList) UnmarshalBinary(b []byte) error { + var res OsList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/partition.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/partition.go new file mode 100644 index 0000000..b0047e8 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/partition.go @@ -0,0 +1,57 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Partition 镜像默认分区 +// [{"format":"swap","point":"swap","size":10240},{"format":"xfs","point":"/","size":51200}] +// +// swagger:model Partition +type Partition struct { + + // format,如[swap, xfs] + FsType string `json:"format,omitempty"` + + // point,如[swap, /, /var] + MountPoint string `json:"point,omitempty"` + + // 分区大小, MB为单位 + Size int64 `json:"size,omitempty"` +} + +// Validate validates this partition +func (m *Partition) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this partition based on context it is used +func (m *Partition) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Partition) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Partition) UnmarshalBinary(b []byte) error { + var res Partition + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/project.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/project.go new file mode 100644 index 0000000..4383d7e --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/project.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Project project +// +// swagger:model Project +type Project struct { + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 项目描述,新增 + Description string `json:"description,omitempty"` + + // 项目下实例数量 + InstanceCount int64 `json:"instanceCount,omitempty"` + + // 此项目的共享标志位,1为拥有,2为共享 + Owned int64 `json:"owned,omitempty"` + + // 拥有者 + OwnedBy string `json:"ownedBy,omitempty"` + + // 项目uuid + ProjectID string `json:"projectId,omitempty"` + + // 项目名称 + ProjectName string `json:"projectName,omitempty"` + + // 共享 + ShareProjects []*ShareProject `json:"shareProjects"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` +} + +// Validate validates this project +func (m *Project) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateShareProjects(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Project) validateShareProjects(formats strfmt.Registry) error { + if swag.IsZero(m.ShareProjects) { // not required + return nil + } + + for i := 0; i < len(m.ShareProjects); i++ { + if swag.IsZero(m.ShareProjects[i]) { // not required + continue + } + + if m.ShareProjects[i] != nil { + if err := m.ShareProjects[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this project based on the context it is used +func (m *Project) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateShareProjects(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Project) contextValidateShareProjects(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.ShareProjects); i++ { + + if m.ShareProjects[i] != nil { + if err := m.ShareProjects[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Project) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Project) UnmarshalBinary(b []byte) error { + var res Project + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/project_id.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/project_id.go new file mode 100644 index 0000000..3c4cef9 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/project_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ProjectID project Id +// +// swagger:model ProjectId +type ProjectID struct { + + // 项目uuid + ProjectID string `json:"projectId,omitempty"` +} + +// Validate validates this project Id +func (m *ProjectID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this project Id based on context it is used +func (m *ProjectID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ProjectID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ProjectID) UnmarshalBinary(b []byte) error { + var res ProjectID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/project_info.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/project_info.go new file mode 100644 index 0000000..8a6287d --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/project_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ProjectInfo project info +// +// swagger:model ProjectInfo +type ProjectInfo struct { + + // project + Project *Project `json:"project,omitempty"` +} + +// Validate validates this project info +func (m *ProjectInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateProject(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ProjectInfo) validateProject(formats strfmt.Registry) error { + if swag.IsZero(m.Project) { // not required + return nil + } + + if m.Project != nil { + if err := m.Project.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("project") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("project") + } + return err + } + } + + return nil +} + +// ContextValidate validate this project info based on the context it is used +func (m *ProjectInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateProject(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ProjectInfo) contextValidateProject(ctx context.Context, formats strfmt.Registry) error { + + if m.Project != nil { + if err := m.Project.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("project") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("project") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ProjectInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ProjectInfo) UnmarshalBinary(b []byte) error { + var res ProjectInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/project_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/project_list.go new file mode 100644 index 0000000..a9e6867 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/project_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ProjectList project list +// +// swagger:model ProjectList +type ProjectList struct { + + // 页数 + PageNumber int64 `json:"pageNumber,omitempty"` + + // 页大小 + PageSize int64 `json:"pageSize,omitempty"` + + // 项目实体列表 + Projects []*Project `json:"projects"` + + // 总条数 + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this project list +func (m *ProjectList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateProjects(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ProjectList) validateProjects(formats strfmt.Registry) error { + if swag.IsZero(m.Projects) { // not required + return nil + } + + for i := 0; i < len(m.Projects); i++ { + if swag.IsZero(m.Projects[i]) { // not required + continue + } + + if m.Projects[i] != nil { + if err := m.Projects[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("projects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("projects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this project list based on the context it is used +func (m *ProjectList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateProjects(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ProjectList) contextValidateProjects(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Projects); i++ { + + if m.Projects[i] != nil { + if err := m.Projects[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("projects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("projects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ProjectList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ProjectList) UnmarshalBinary(b []byte) error { + var res ProjectList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/query_device_type_image_partition_response.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/query_device_type_image_partition_response.go new file mode 100644 index 0000000..01b3e25 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/query_device_type_image_partition_response.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// QueryDeviceTypeImagePartitionResponse query device type image partition response +// +// swagger:model QueryDeviceTypeImagePartitionResponse +type QueryDeviceTypeImagePartitionResponse struct { + + // 数据盘分区列表 + DataPartition []*Partition `json:"dataPartition"` + + // 系统盘分区列表 + SystemPartition []*Partition `json:"systemPartition"` +} + +// Validate validates this query device type image partition response +func (m *QueryDeviceTypeImagePartitionResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDataPartition(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemPartition(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *QueryDeviceTypeImagePartitionResponse) validateDataPartition(formats strfmt.Registry) error { + if swag.IsZero(m.DataPartition) { // not required + return nil + } + + for i := 0; i < len(m.DataPartition); i++ { + if swag.IsZero(m.DataPartition[i]) { // not required + continue + } + + if m.DataPartition[i] != nil { + if err := m.DataPartition[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *QueryDeviceTypeImagePartitionResponse) validateSystemPartition(formats strfmt.Registry) error { + if swag.IsZero(m.SystemPartition) { // not required + return nil + } + + for i := 0; i < len(m.SystemPartition); i++ { + if swag.IsZero(m.SystemPartition[i]) { // not required + continue + } + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this query device type image partition response based on the context it is used +func (m *QueryDeviceTypeImagePartitionResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDataPartition(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateSystemPartition(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *QueryDeviceTypeImagePartitionResponse) contextValidateDataPartition(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.DataPartition); i++ { + + if m.DataPartition[i] != nil { + if err := m.DataPartition[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *QueryDeviceTypeImagePartitionResponse) contextValidateSystemPartition(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.SystemPartition); i++ { + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *QueryDeviceTypeImagePartitionResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *QueryDeviceTypeImagePartitionResponse) UnmarshalBinary(b []byte) error { + var res QueryDeviceTypeImagePartitionResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/r_volume_raid.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/r_volume_raid.go new file mode 100644 index 0000000..6173ede --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/r_volume_raid.go @@ -0,0 +1,80 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RVolumeRaid Volume RAID 关联关系表 +// +// swagger:model RVolumeRaid +type RVolumeRaid struct { + + // created by + CreatedBy string `json:"createdBy,omitempty"` + + // created time + CreatedTime int64 `json:"createdTime,omitempty"` + + // deleted time + DeletedTime int64 `json:"deletedTime,omitempty"` + + // device type ID + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // is del + IsDel int8 `json:"isDel,omitempty"` + + // raid can + RaidCan string `json:"raidCan,omitempty"` + + // raid ID + RaidID string `json:"raidId,omitempty"` + + // raid name + RaidName string `json:"raidName,omitempty"` + + // updated by + UpdatedBy string `json:"updatedBy,omitempty"` + + // updated time + UpdatedTime int64 `json:"updatedTime,omitempty"` + + // volume ID + VolumeID string `json:"volumeId,omitempty"` +} + +// Validate validates this r volume raid +func (m *RVolumeRaid) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this r volume raid based on context it is used +func (m *RVolumeRaid) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RVolumeRaid) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RVolumeRaid) UnmarshalBinary(b []byte) error { + var res RVolumeRaid + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/raid.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/raid.go new file mode 100644 index 0000000..8344939 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/raid.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Raid Raid raid +// +// swagger:model Raid +type Raid struct { + + // created by + CreatedBy string `json:"createdBy,omitempty"` + + // created time + CreatedTime int64 `json:"createdTime,omitempty"` + + // deleted time + DeletedTime int64 `json:"deletedTime,omitempty"` + + // description en + DescriptionEn string `json:"descriptionEn,omitempty"` + + // description zh + DescriptionZh string `json:"descriptionZh,omitempty"` + + // is del + IsDel int8 `json:"isDel,omitempty"` + + // name + Name string `json:"name,omitempty"` + + // raid ID + RaidID string `json:"raidId,omitempty"` + + // updated by + UpdatedBy string `json:"updatedBy,omitempty"` + + // updated time + UpdatedTime int64 `json:"updatedTime,omitempty"` +} + +// Validate validates this raid +func (m *Raid) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this raid based on context it is used +func (m *Raid) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Raid) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Raid) UnmarshalBinary(b []byte) error { + var res Raid + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/read_messages_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/read_messages_request.go new file mode 100644 index 0000000..d133997 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/read_messages_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ReadMessagesRequest read messages request +// +// swagger:model ReadMessagesRequest +type ReadMessagesRequest struct { + + // message ids + // Required: true + MessageIds []string `json:"messageIds"` +} + +// Validate validates this read messages request +func (m *ReadMessagesRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateMessageIds(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ReadMessagesRequest) validateMessageIds(formats strfmt.Registry) error { + + if err := validate.Required("messageIds", "body", m.MessageIds); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this read messages request based on context it is used +func (m *ReadMessagesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ReadMessagesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ReadMessagesRequest) UnmarshalBinary(b []byte) error { + var res ReadMessagesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/reinstall_instance_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/reinstall_instance_request.go new file mode 100644 index 0000000..0e2c054 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/reinstall_instance_request.go @@ -0,0 +1,257 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ReinstallInstanceRequest reinstall instance request +// +// swagger:model ReinstallInstanceRequest +type ReinstallInstanceRequest struct { + + // 引导模式 [UEFI Legacy/BIOS] + // Required: true + BootMode *string `json:"bootMode"` + + // 数据盘分区 + DataPartition []*Partition `json:"dataPartition"` + + // 描述 + Description string `json:"description,omitempty"` + + // 主机名称 + HostName string `json:"hostname,omitempty"` + + // 镜像ID + // Required: true + ImageID *string `json:"imageId"` + + // 是否安装bmp-agent + InstallBmpAgent bool `json:"installBmpAgent,omitempty"` + + // 实例名称 + // Required: true + InstanceName *string `json:"instanceName"` + + // 密码 + Password string `json:"password,omitempty"` + + // 秘钥ID + SSHKeyID string `json:"sshKeyId,omitempty"` + + // 系统盘分区 + SystemPartition []*Partition `json:"systemPartition"` + + // 系统盘RAID ID + // Required: true + SystemVolumeRaidID *string `json:"systemVolumeRaidId"` +} + +// Validate validates this reinstall instance request +func (m *ReinstallInstanceRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateBootMode(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDataPartition(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImageID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInstanceName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemPartition(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemVolumeRaidID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ReinstallInstanceRequest) validateBootMode(formats strfmt.Registry) error { + + if err := validate.Required("bootMode", "body", m.BootMode); err != nil { + return err + } + + return nil +} + +func (m *ReinstallInstanceRequest) validateDataPartition(formats strfmt.Registry) error { + if swag.IsZero(m.DataPartition) { // not required + return nil + } + + for i := 0; i < len(m.DataPartition); i++ { + if swag.IsZero(m.DataPartition[i]) { // not required + continue + } + + if m.DataPartition[i] != nil { + if err := m.DataPartition[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *ReinstallInstanceRequest) validateImageID(formats strfmt.Registry) error { + + if err := validate.Required("imageId", "body", m.ImageID); err != nil { + return err + } + + return nil +} + +func (m *ReinstallInstanceRequest) validateInstanceName(formats strfmt.Registry) error { + + if err := validate.Required("instanceName", "body", m.InstanceName); err != nil { + return err + } + + return nil +} + +func (m *ReinstallInstanceRequest) validateSystemPartition(formats strfmt.Registry) error { + if swag.IsZero(m.SystemPartition) { // not required + return nil + } + + for i := 0; i < len(m.SystemPartition); i++ { + if swag.IsZero(m.SystemPartition[i]) { // not required + continue + } + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *ReinstallInstanceRequest) validateSystemVolumeRaidID(formats strfmt.Registry) error { + + if err := validate.Required("systemVolumeRaidId", "body", m.SystemVolumeRaidID); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this reinstall instance request based on the context it is used +func (m *ReinstallInstanceRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDataPartition(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateSystemPartition(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ReinstallInstanceRequest) contextValidateDataPartition(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.DataPartition); i++ { + + if m.DataPartition[i] != nil { + if err := m.DataPartition[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *ReinstallInstanceRequest) contextValidateSystemPartition(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.SystemPartition); i++ { + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ReinstallInstanceRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ReinstallInstanceRequest) UnmarshalBinary(b []byte) error { + var res ReinstallInstanceRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/reset_instance_passwd_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/reset_instance_passwd_request.go new file mode 100644 index 0000000..0a735f2 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/reset_instance_passwd_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ResetInstancePasswdRequest 重置实例密码 +// +// swagger:model ResetInstancePasswdRequest +type ResetInstancePasswdRequest struct { + + // 新密码 + Password string `json:"password,omitempty"` +} + +// Validate validates this reset instance passwd request +func (m *ResetInstancePasswdRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this reset instance passwd request based on context it is used +func (m *ResetInstancePasswdRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ResetInstancePasswdRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ResetInstancePasswdRequest) UnmarshalBinary(b []byte) error { + var res ResetInstancePasswdRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/reset_instances_passwd_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/reset_instances_passwd_request.go new file mode 100644 index 0000000..fef10ab --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/reset_instances_passwd_request.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ResetInstancesPasswdRequest 批量重置实例密码 +// +// swagger:model ResetInstancesPasswdRequest +type ResetInstancesPasswdRequest struct { + + // 实例id列表 + InstanceIDs []string `json:"instance_ids"` + + // 新密码 + Password string `json:"password,omitempty"` +} + +// Validate validates this reset instances passwd request +func (m *ResetInstancesPasswdRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this reset instances passwd request based on context it is used +func (m *ResetInstancesPasswdRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ResetInstancesPasswdRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ResetInstancesPasswdRequest) UnmarshalBinary(b []byte) error { + var res ResetInstancesPasswdRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/restart_instances_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/restart_instances_request.go new file mode 100644 index 0000000..d26b5a8 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/restart_instances_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RestartInstancesRequest restart instances request +// +// swagger:model RestartInstancesRequest +type RestartInstancesRequest struct { + + // instance ids + InstanceIds []string `json:"instanceIds"` +} + +// Validate validates this restart instances request +func (m *RestartInstancesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this restart instances request based on context it is used +func (m *RestartInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RestartInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RestartInstancesRequest) UnmarshalBinary(b []byte) error { + var res RestartInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/role.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/role.go new file mode 100644 index 0000000..9881844 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/role.go @@ -0,0 +1,83 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Role role +// +// swagger:model Role +type Role struct { + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // description + DescriptionCn string `json:"descriptionCn,omitempty"` + + // 权限描述 + DescriptionEn string `json:"descriptionEn,omitempty"` + + // 权限 + Permission string `json:"permission,omitempty"` + + // 角色uuid + RoleID string `json:"roleId,omitempty"` + + // 角色名称 + RoleName string `json:"roleName,omitempty"` + + // 角色名称,唯一 + RoleNameCn string `json:"roleNameCn,omitempty"` + + // 角色名称,唯一 + RoleNameEn string `json:"roleNameEn,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 用户数 + UserCount int64 `json:"userCount,omitempty"` +} + +// Validate validates this role +func (m *Role) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this role based on context it is used +func (m *Role) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Role) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Role) UnmarshalBinary(b []byte) error { + var res Role + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/role_info.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/role_info.go new file mode 100644 index 0000000..bf39a63 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/role_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RoleInfo role info +// +// swagger:model RoleInfo +type RoleInfo struct { + + // role + Role *Role `json:"role,omitempty"` +} + +// Validate validates this role info +func (m *RoleInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRole(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RoleInfo) validateRole(formats strfmt.Registry) error { + if swag.IsZero(m.Role) { // not required + return nil + } + + if m.Role != nil { + if err := m.Role.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("role") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("role") + } + return err + } + } + + return nil +} + +// ContextValidate validate this role info based on the context it is used +func (m *RoleInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateRole(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RoleInfo) contextValidateRole(ctx context.Context, formats strfmt.Registry) error { + + if m.Role != nil { + if err := m.Role.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("role") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("role") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *RoleInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RoleInfo) UnmarshalBinary(b []byte) error { + var res RoleInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/role_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/role_list.go new file mode 100644 index 0000000..25876cb --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/role_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RoleList role list +// +// swagger:model RoleList +type RoleList struct { + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // 角色实体列表 + Roles []*Role `json:"roles"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this role list +func (m *RoleList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRoles(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RoleList) validateRoles(formats strfmt.Registry) error { + if swag.IsZero(m.Roles) { // not required + return nil + } + + for i := 0; i < len(m.Roles); i++ { + if swag.IsZero(m.Roles[i]) { // not required + continue + } + + if m.Roles[i] != nil { + if err := m.Roles[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("roles" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("roles" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this role list based on the context it is used +func (m *RoleList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateRoles(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RoleList) contextValidateRoles(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Roles); i++ { + + if m.Roles[i] != nil { + if err := m.Roles[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("roles" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("roles" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *RoleList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RoleList) UnmarshalBinary(b []byte) error { + var res RoleList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/rule.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/rule.go new file mode 100644 index 0000000..48e56b2 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/rule.go @@ -0,0 +1,258 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Rule rule +// +// swagger:model Rule +type Rule struct { + + // 盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag,omitempty"` + + // 维度 [instance、disk、mountpoint、nic] + Dimension string `json:"dimension,omitempty"` + + // 维度名称 [实例、盘符、挂载点、网卡] + DimensionName string `json:"dimensionName,omitempty"` + + // 关联的实例个数 + InstanceCount int64 `json:"instanceCount,omitempty"` + + // 实例id列表 + InstanceIds []string `json:"instanceIds"` + + // 实例详细信息 + Instances []*Instance `json:"instances"` + + // 此规则关联的资源数 + RelatedResourceCount int64 `json:"relatedResourceCount,omitempty"` + + // 资源类型,目前只支持instance + Resource string `json:"resource,omitempty"` + + // 资源类型名称 实例 + ResourceName string `json:"resourceName,omitempty"` + + // 规则uuid + RuleID string `json:"ruleId,omitempty"` + + // 规则名称 + RuleName string `json:"ruleName,omitempty"` + + // 状态 [1启用 2不启用 3告警] + Status int64 `json:"status,omitempty"` + + // 规则状态名称 + StatusName string `json:"statusName,omitempty"` + + // 触发条件描述 + TriggerDescription []string `json:"triggerDescription"` + + // 触发条件 + TriggerOption []*RuleTrigger `json:"triggerOption"` + + // notice option + NoticeOption *RuleNotice `json:"noticeOption,omitempty"` +} + +// Validate validates this rule +func (m *Rule) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstances(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTriggerOption(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNoticeOption(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Rule) validateInstances(formats strfmt.Registry) error { + if swag.IsZero(m.Instances) { // not required + return nil + } + + for i := 0; i < len(m.Instances); i++ { + if swag.IsZero(m.Instances[i]) { // not required + continue + } + + if m.Instances[i] != nil { + if err := m.Instances[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *Rule) validateTriggerOption(formats strfmt.Registry) error { + if swag.IsZero(m.TriggerOption) { // not required + return nil + } + + for i := 0; i < len(m.TriggerOption); i++ { + if swag.IsZero(m.TriggerOption[i]) { // not required + continue + } + + if m.TriggerOption[i] != nil { + if err := m.TriggerOption[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *Rule) validateNoticeOption(formats strfmt.Registry) error { + if swag.IsZero(m.NoticeOption) { // not required + return nil + } + + if m.NoticeOption != nil { + if err := m.NoticeOption.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("noticeOption") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("noticeOption") + } + return err + } + } + + return nil +} + +// ContextValidate validate this rule based on the context it is used +func (m *Rule) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateInstances(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateTriggerOption(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateNoticeOption(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Rule) contextValidateInstances(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Instances); i++ { + + if m.Instances[i] != nil { + if err := m.Instances[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *Rule) contextValidateTriggerOption(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.TriggerOption); i++ { + + if m.TriggerOption[i] != nil { + if err := m.TriggerOption[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *Rule) contextValidateNoticeOption(ctx context.Context, formats strfmt.Registry) error { + + if m.NoticeOption != nil { + if err := m.NoticeOption.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("noticeOption") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("noticeOption") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Rule) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Rule) UnmarshalBinary(b []byte) error { + var res Rule + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/rule_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/rule_list.go new file mode 100644 index 0000000..3744ca7 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/rule_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RuleList rule list +// +// swagger:model RuleList +type RuleList struct { + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // rules数组 + Rules []*Rule `json:"rules"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this rule list +func (m *RuleList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRules(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RuleList) validateRules(formats strfmt.Registry) error { + if swag.IsZero(m.Rules) { // not required + return nil + } + + for i := 0; i < len(m.Rules); i++ { + if swag.IsZero(m.Rules[i]) { // not required + continue + } + + if m.Rules[i] != nil { + if err := m.Rules[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("rules" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("rules" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this rule list based on the context it is used +func (m *RuleList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateRules(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RuleList) contextValidateRules(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Rules); i++ { + + if m.Rules[i] != nil { + if err := m.Rules[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("rules" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("rules" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *RuleList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RuleList) UnmarshalBinary(b []byte) error { + var res RuleList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/rule_notice.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/rule_notice.go new file mode 100644 index 0000000..43c7ea4 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/rule_notice.go @@ -0,0 +1,159 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// RuleNotice 通知策略 +// +// swagger:model RuleNotice +type RuleNotice struct { + + // 有效时段结束时间 ["23:59:59"] + // Required: true + EffectiveIntervalEnd *string `json:"effectiveIntervalEnd"` + + // 有效时段开始时间 ["00:00:00"] + // Required: true + EffectiveIntervalStart *string `json:"effectiveIntervalStart"` + + // 通知条件,可多选 [1表示报警, 2表示恢复正常] + // Required: true + NoticeCondition []int64 `json:"noticeCondition"` + + // 通知周期(分钟) [5 10 15 30 60 180 360 720 1440] + // Required: true + NoticePeriod *int64 `json:"noticePeriod"` + + // 接收渠道,可多选 [1表示站内信, 2表示邮件] + // Required: true + NoticeWay []int64 `json:"noticeWay"` + + // 通知对象用户Id + // Required: true + UserID *string `json:"userId"` + + // 通知对象用户 + UserName string `json:"userName,omitempty"` +} + +// Validate validates this rule notice +func (m *RuleNotice) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateEffectiveIntervalEnd(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEffectiveIntervalStart(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNoticeCondition(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNoticePeriod(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNoticeWay(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RuleNotice) validateEffectiveIntervalEnd(formats strfmt.Registry) error { + + if err := validate.Required("effectiveIntervalEnd", "body", m.EffectiveIntervalEnd); err != nil { + return err + } + + return nil +} + +func (m *RuleNotice) validateEffectiveIntervalStart(formats strfmt.Registry) error { + + if err := validate.Required("effectiveIntervalStart", "body", m.EffectiveIntervalStart); err != nil { + return err + } + + return nil +} + +func (m *RuleNotice) validateNoticeCondition(formats strfmt.Registry) error { + + if err := validate.Required("noticeCondition", "body", m.NoticeCondition); err != nil { + return err + } + + return nil +} + +func (m *RuleNotice) validateNoticePeriod(formats strfmt.Registry) error { + + if err := validate.Required("noticePeriod", "body", m.NoticePeriod); err != nil { + return err + } + + return nil +} + +func (m *RuleNotice) validateNoticeWay(formats strfmt.Registry) error { + + if err := validate.Required("noticeWay", "body", m.NoticeWay); err != nil { + return err + } + + return nil +} + +func (m *RuleNotice) validateUserID(formats strfmt.Registry) error { + + if err := validate.Required("userId", "body", m.UserID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this rule notice based on context it is used +func (m *RuleNotice) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RuleNotice) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RuleNotice) UnmarshalBinary(b []byte) error { + var res RuleNotice + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/rule_trigger.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/rule_trigger.go new file mode 100644 index 0000000..e7f3f9e --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/rule_trigger.go @@ -0,0 +1,185 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// RuleTrigger 单个触发条件 +// +// swagger:model RuleTrigger +type RuleTrigger struct { + + // 计算方式 [min max avg sum] + // Required: true + Calculation *string `json:"calculation"` + + // 计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出] + CalculationUnit string `json:"calculationUnit,omitempty"` + + // 对此rule的描述 + Description string `json:"description,omitempty"` + + // 监控指标 cps.cpu.util + // Required: true + Metric *string `json:"metric"` + + // 监控指标名称 CPU使用率 + MetricName string `json:"metricName,omitempty"` + + // 告警级别 [1表示一般,2表示严重,3表示紧急] + // Required: true + NoticeLevel *int64 `json:"noticeLevel"` + + // 比较方式 [> >= < <= == !=]或者[gt gte lt lte eq neq] + // Required: true + Operation *string `json:"operation"` + + // 周期 5(分钟) + // Required: true + Period *int64 `json:"period"` + + // [bmp_monitor_counter, bmp_monitor_gauge] + TableName string `json:"tableName,omitempty"` + + // 阈值 + // Required: true + Threshold *float64 `json:"threshold"` + + // 持续周期数 [1, 2, 3, 5, 10, 15, 30, 60] + // Required: true + Times *int64 `json:"times"` +} + +// Validate validates this rule trigger +func (m *RuleTrigger) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCalculation(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMetric(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNoticeLevel(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOperation(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePeriod(formats); err != nil { + res = append(res, err) + } + + if err := m.validateThreshold(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTimes(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RuleTrigger) validateCalculation(formats strfmt.Registry) error { + + if err := validate.Required("calculation", "body", m.Calculation); err != nil { + return err + } + + return nil +} + +func (m *RuleTrigger) validateMetric(formats strfmt.Registry) error { + + if err := validate.Required("metric", "body", m.Metric); err != nil { + return err + } + + return nil +} + +func (m *RuleTrigger) validateNoticeLevel(formats strfmt.Registry) error { + + if err := validate.Required("noticeLevel", "body", m.NoticeLevel); err != nil { + return err + } + + return nil +} + +func (m *RuleTrigger) validateOperation(formats strfmt.Registry) error { + + if err := validate.Required("operation", "body", m.Operation); err != nil { + return err + } + + return nil +} + +func (m *RuleTrigger) validatePeriod(formats strfmt.Registry) error { + + if err := validate.Required("period", "body", m.Period); err != nil { + return err + } + + return nil +} + +func (m *RuleTrigger) validateThreshold(formats strfmt.Registry) error { + + if err := validate.Required("threshold", "body", m.Threshold); err != nil { + return err + } + + return nil +} + +func (m *RuleTrigger) validateTimes(formats strfmt.Registry) error { + + if err := validate.Required("times", "body", m.Times); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this rule trigger based on context it is used +func (m *RuleTrigger) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RuleTrigger) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RuleTrigger) UnmarshalBinary(b []byte) error { + var res RuleTrigger + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/share_project.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/share_project.go new file mode 100644 index 0000000..5188a30 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/share_project.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ShareProject share project +// +// swagger:model ShareProject +type ShareProject struct { + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 项目拥有者用户id + OwnerUserID string `json:"ownerUserId,omitempty"` + + // 项目拥有者用户名 + OwnerUserName string `json:"ownerUserName,omitempty"` + + // 项目uuid + ProjectID string `json:"projectId,omitempty"` + + // 项目名称 + ProjectName string `json:"projectName,omitempty"` + + // shared instance i ds + SharedInstanceIDs string `json:"sharedInstanceIds,omitempty"` + + // 项目共享者用户id + SharedUserID string `json:"sharedUserId,omitempty"` + + // 项目拥有者用户名 + SharedUserName string `json:"sharedUserName,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` +} + +// Validate validates this share project +func (m *ShareProject) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this share project based on context it is used +func (m *ShareProject) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ShareProject) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ShareProject) UnmarshalBinary(b []byte) error { + var res ShareProject + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/share_project_info.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/share_project_info.go new file mode 100644 index 0000000..5657090 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/share_project_info.go @@ -0,0 +1,119 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ShareProjectInfo share project info +// +// swagger:model ShareProjectInfo +type ShareProjectInfo struct { + + // 项目实体 + ProjectID string `json:"projectId,omitempty"` + + // shares + Shares []*SharingProject `json:"shares"` +} + +// Validate validates this share project info +func (m *ShareProjectInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateShares(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ShareProjectInfo) validateShares(formats strfmt.Registry) error { + if swag.IsZero(m.Shares) { // not required + return nil + } + + for i := 0; i < len(m.Shares); i++ { + if swag.IsZero(m.Shares[i]) { // not required + continue + } + + if m.Shares[i] != nil { + if err := m.Shares[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shares" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shares" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this share project info based on the context it is used +func (m *ShareProjectInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateShares(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ShareProjectInfo) contextValidateShares(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Shares); i++ { + + if m.Shares[i] != nil { + if err := m.Shares[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shares" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shares" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ShareProjectInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ShareProjectInfo) UnmarshalBinary(b []byte) error { + var res ShareProjectInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/share_project_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/share_project_request.go new file mode 100644 index 0000000..56d6fa8 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/share_project_request.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ShareProjectRequest share project request +// +// swagger:model ShareProjectRequest +type ShareProjectRequest struct { + + // 如果部分分享,instance_id逗号分隔; 如果全部分享,传all + // Required: true + InstanceIDs *string `json:"instanceIDs"` + + // from user_id + // Required: true + OwnerID *string `json:"ownerID"` + + // to user_id + // Required: true + SharerID *string `json:"sharerID"` +} + +// Validate validates this share project request +func (m *ShareProjectRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstanceIDs(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOwnerID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSharerID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ShareProjectRequest) validateInstanceIDs(formats strfmt.Registry) error { + + if err := validate.Required("instanceIDs", "body", m.InstanceIDs); err != nil { + return err + } + + return nil +} + +func (m *ShareProjectRequest) validateOwnerID(formats strfmt.Registry) error { + + if err := validate.Required("ownerID", "body", m.OwnerID); err != nil { + return err + } + + return nil +} + +func (m *ShareProjectRequest) validateSharerID(formats strfmt.Registry) error { + + if err := validate.Required("sharerID", "body", m.SharerID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this share project request based on context it is used +func (m *ShareProjectRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ShareProjectRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ShareProjectRequest) UnmarshalBinary(b []byte) error { + var res ShareProjectRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/sharing_project.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/sharing_project.go new file mode 100644 index 0000000..1553dbb --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/sharing_project.go @@ -0,0 +1,92 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// SharingProject SharingProject 共享项目 +// +// swagger:model SharingProject +type SharingProject struct { + + // created by + CreatedBy string `json:"created_by,omitempty"` + + // created time + CreatedTime int64 `json:"created_time,omitempty"` + + // deleted time + DeletedTime int64 `json:"deleted_time,omitempty"` + + // is default + IsDefault int8 `json:"is_default,omitempty"` + + // is del + IsDel int8 `json:"is_del,omitempty"` + + // owner user ID + OwnerUserID string `json:"owner_user_id,omitempty"` + + // owner user name + OwnerUserName string `json:"owner_user_name,omitempty"` + + // premission + Premission string `json:"premission,omitempty"` + + // project ID + ProjectID string `json:"project_id,omitempty"` + + // project name + ProjectName string `json:"project_name,omitempty"` + + // shared instance i ds + SharedInstanceIDs string `json:"shared_instance_ids,omitempty"` + + // shared user ID + SharedUserID string `json:"shared_user_id,omitempty"` + + // shared user name + SharedUserName string `json:"shared_user_name,omitempty"` + + // updated by + UpdatedBy string `json:"updated_by,omitempty"` + + // updated time + UpdatedTime int64 `json:"updated_time,omitempty"` +} + +// Validate validates this sharing project +func (m *SharingProject) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this sharing project based on context it is used +func (m *SharingProject) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SharingProject) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SharingProject) UnmarshalBinary(b []byte) error { + var res SharingProject + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/sshkey.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/sshkey.go new file mode 100644 index 0000000..5a0fae4 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/sshkey.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Sshkey sshkey +// +// swagger:model Sshkey +type Sshkey struct { + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 公钥指纹 + FingerPrint string `json:"fingerPrint,omitempty"` + + // id + ID int64 `json:"id,omitempty"` + + // 公钥,格式:ssh-rsa AAA + Key string `json:"key,omitempty"` + + // 秘钥名称 + Name string `json:"name,omitempty"` + + // 秘钥uuid + SshkeyID string `json:"sshkeyId,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 所属用户uuid + UserID string `json:"userId,omitempty"` +} + +// Validate validates this sshkey +func (m *Sshkey) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this sshkey based on context it is used +func (m *Sshkey) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Sshkey) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Sshkey) UnmarshalBinary(b []byte) error { + var res Sshkey + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/sshkey_id.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/sshkey_id.go new file mode 100644 index 0000000..c14abe6 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/sshkey_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// SshkeyID sshkey Id +// +// swagger:model SshkeyId +type SshkeyID struct { + + // sshkey uuid + SshkeyID string `json:"sshkeyId,omitempty"` +} + +// Validate validates this sshkey Id +func (m *SshkeyID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this sshkey Id based on context it is used +func (m *SshkeyID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SshkeyID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SshkeyID) UnmarshalBinary(b []byte) error { + var res SshkeyID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/sshkey_info.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/sshkey_info.go new file mode 100644 index 0000000..60eb531 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/sshkey_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// SshkeyInfo sshkey info +// +// swagger:model SshkeyInfo +type SshkeyInfo struct { + + // sshkey + Sshkey *Sshkey `json:"sshkey,omitempty"` +} + +// Validate validates this sshkey info +func (m *SshkeyInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSshkey(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SshkeyInfo) validateSshkey(formats strfmt.Registry) error { + if swag.IsZero(m.Sshkey) { // not required + return nil + } + + if m.Sshkey != nil { + if err := m.Sshkey.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sshkey") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sshkey") + } + return err + } + } + + return nil +} + +// ContextValidate validate this sshkey info based on the context it is used +func (m *SshkeyInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSshkey(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SshkeyInfo) contextValidateSshkey(ctx context.Context, formats strfmt.Registry) error { + + if m.Sshkey != nil { + if err := m.Sshkey.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sshkey") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sshkey") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SshkeyInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SshkeyInfo) UnmarshalBinary(b []byte) error { + var res SshkeyInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/sshkey_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/sshkey_list.go new file mode 100644 index 0000000..af8e27f --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/sshkey_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// SshkeyList sshkey list +// +// swagger:model SshkeyList +type SshkeyList struct { + + // 页数 + PageNumber int64 `json:"pageNumber,omitempty"` + + // 页大小 + PageSize int64 `json:"pageSize,omitempty"` + + // sshkey实体列表 + Sshkeys []*Sshkey `json:"sshkeys"` + + // 总条数 + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this sshkey list +func (m *SshkeyList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSshkeys(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SshkeyList) validateSshkeys(formats strfmt.Registry) error { + if swag.IsZero(m.Sshkeys) { // not required + return nil + } + + for i := 0; i < len(m.Sshkeys); i++ { + if swag.IsZero(m.Sshkeys[i]) { // not required + continue + } + + if m.Sshkeys[i] != nil { + if err := m.Sshkeys[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sshkeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sshkeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this sshkey list based on the context it is used +func (m *SshkeyList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSshkeys(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SshkeyList) contextValidateSshkeys(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Sshkeys); i++ { + + if m.Sshkeys[i] != nil { + if err := m.Sshkeys[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sshkeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sshkeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SshkeyList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SshkeyList) UnmarshalBinary(b []byte) error { + var res SshkeyList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/start_instances_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/start_instances_request.go new file mode 100644 index 0000000..cb20838 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/start_instances_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// StartInstancesRequest start instances request +// +// swagger:model StartInstancesRequest +type StartInstancesRequest struct { + + // instance ids + InstanceIds []string `json:"instanceIds"` +} + +// Validate validates this start instances request +func (m *StartInstancesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this start instances request based on context it is used +func (m *StartInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *StartInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *StartInstancesRequest) UnmarshalBinary(b []byte) error { + var res StartInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/stop_instances_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/stop_instances_request.go new file mode 100644 index 0000000..ae9f8d3 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/stop_instances_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// StopInstancesRequest stop instances request +// +// swagger:model StopInstancesRequest +type StopInstancesRequest struct { + + // instance ids + InstanceIds []string `json:"instanceIds"` +} + +// Validate validates this stop instances request +func (m *StopInstancesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this stop instances request based on context it is used +func (m *StopInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *StopInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *StopInstancesRequest) UnmarshalBinary(b []byte) error { + var res StopInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/tags_response.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/tags_response.go new file mode 100644 index 0000000..45fe4aa --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/tags_response.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// TagsResponse tags response +// +// swagger:model TagsResponse +type TagsResponse struct { + + // tags + Tags []string `json:"tags"` +} + +// Validate validates this tags response +func (m *TagsResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this tags response based on context it is used +func (m *TagsResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *TagsResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *TagsResponse) UnmarshalBinary(b []byte) error { + var res TagsResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/user.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/user.go new file mode 100644 index 0000000..d91f37f --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/user.go @@ -0,0 +1,98 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// User user +// +// swagger:model User +type User struct { + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 用户默认项目uuid + DefaultProjectID string `json:"defaultProjectId,omitempty"` + + // 用户默认项目名称 + DefaultProjectName string `json:"defaultProjectName,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 邮箱 + Email string `json:"email,omitempty"` + + // 用户id + ID int64 `json:"id,omitempty"` + + // 默认语言(en_US/zh_CN) + Language string `json:"language,omitempty"` + + // 手机号 + PhoneNumber string `json:"phoneNumber,omitempty"` + + // 国家地区码,如86 + PhonePrefix string `json:"phonePrefix,omitempty"` + + // 角色uuid + RoleID string `json:"roleId,omitempty"` + + // 角色名称 + RoleName string `json:"roleName,omitempty"` + + // 时区 + Timezone string `json:"timezone,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 用户uuid + UserID string `json:"userId,omitempty"` + + // 用户名,唯一 + UserName string `json:"userName,omitempty"` +} + +// Validate validates this user +func (m *User) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this user based on context it is used +func (m *User) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *User) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *User) UnmarshalBinary(b []byte) error { + var res User + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/user_info.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/user_info.go new file mode 100644 index 0000000..81d4111 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/user_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// UserInfo user info +// +// swagger:model UserInfo +type UserInfo struct { + + // user + User *User `json:"user,omitempty"` +} + +// Validate validates this user info +func (m *UserInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateUser(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UserInfo) validateUser(formats strfmt.Registry) error { + if swag.IsZero(m.User) { // not required + return nil + } + + if m.User != nil { + if err := m.User.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("user") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("user") + } + return err + } + } + + return nil +} + +// ContextValidate validate this user info based on the context it is used +func (m *UserInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateUser(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UserInfo) contextValidateUser(ctx context.Context, formats strfmt.Registry) error { + + if m.User != nil { + if err := m.User.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("user") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("user") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *UserInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UserInfo) UnmarshalBinary(b []byte) error { + var res UserInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/user_list.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/user_list.go new file mode 100644 index 0000000..b072faa --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/user_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// UserList user list +// +// swagger:model UserList +type UserList struct { + + // 页数 + PageNumber int64 `json:"pageNumber,omitempty"` + + // 页大小 + PageSize int64 `json:"pageSize,omitempty"` + + // 总条数 + TotalCount int64 `json:"totalCount,omitempty"` + + // user实体列表 + Users []*User `json:"users"` +} + +// Validate validates this user list +func (m *UserList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateUsers(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UserList) validateUsers(formats strfmt.Registry) error { + if swag.IsZero(m.Users) { // not required + return nil + } + + for i := 0; i < len(m.Users); i++ { + if swag.IsZero(m.Users[i]) { // not required + continue + } + + if m.Users[i] != nil { + if err := m.Users[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("users" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("users" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this user list based on the context it is used +func (m *UserList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateUsers(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UserList) contextValidateUsers(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Users); i++ { + + if m.Users[i] != nil { + if err := m.Users[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("users" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("users" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *UserList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UserList) UnmarshalBinary(b []byte) error { + var res UserList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/verify_user_request.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/verify_user_request.go new file mode 100644 index 0000000..e902b1c --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/verify_user_request.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// VerifyUserRequest verify user request +// +// swagger:model VerifyUserRequest +type VerifyUserRequest struct { + + // 密码 + // Required: true + Password *string `json:"password"` + + // 角色uuid + // Required: true + RoleID *string `json:"roleId"` + + // 用户名,唯一 + // Required: true + UserName *string `json:"userName"` +} + +// Validate validates this verify user request +func (m *VerifyUserRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validatePassword(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRoleID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *VerifyUserRequest) validatePassword(formats strfmt.Registry) error { + + if err := validate.Required("password", "body", m.Password); err != nil { + return err + } + + return nil +} + +func (m *VerifyUserRequest) validateRoleID(formats strfmt.Registry) error { + + if err := validate.Required("roleId", "body", m.RoleID); err != nil { + return err + } + + return nil +} + +func (m *VerifyUserRequest) validateUserName(formats strfmt.Registry) error { + + if err := validate.Required("userName", "body", m.UserName); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this verify user request based on context it is used +func (m *VerifyUserRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *VerifyUserRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *VerifyUserRequest) UnmarshalBinary(b []byte) error { + var res VerifyUserRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/volume.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/volume.go new file mode 100644 index 0000000..3d6a41b --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/volume.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Volume Volume 卷管理表 +// +// swagger:model Volume +type Volume struct { + + // RaidCan string `gorm:"column:raid_can" json:"raidCan"` // RAID配置: (RAID,NO RAID) + // Raid string `gorm:"column:raid" json:"raid"` // RAID模式:RAID1,RIAD10等 + CreatedBy string `json:"createdBy,omitempty"` + + // created time + CreatedTime int64 `json:"createdTime,omitempty"` + + // deleted time + DeletedTime int64 `json:"deletedTime,omitempty"` + + // 设备类型uuid + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // 硬盘类型(SSD,HDD) + DiskType string `json:"diskType,omitempty"` + + // 接口类型(SATA,SAS,NVME,不限制) + InterfaceType string `json:"interfaceType,omitempty"` + + // is del + IsDel int8 `json:"isDel,omitempty"` + + // updated by + UpdatedBy string `json:"updatedBy,omitempty"` + + // updated time + UpdatedTime int64 `json:"updatedTime,omitempty"` + + // 硬盘数量(最低块数) + VolumeAmount int64 `json:"volumeAmount,omitempty"` + + // 卷uuid + VolumeID string `json:"volumeId,omitempty"` + + // 卷名称 + VolumeName string `json:"volumeName,omitempty"` + + // 单盘大小(最小容量) + VolumeSize string `json:"volumeSize,omitempty"` + + // 卷类型:系统卷,数据卷 + VolumeType string `json:"volumeType,omitempty"` + + // 硬盘单位(GB,TB) + VolumeUnit string `json:"volumeUnit,omitempty"` +} + +// Validate validates this volume +func (m *Volume) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this volume based on context it is used +func (m *Volume) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Volume) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Volume) UnmarshalBinary(b []byte) error { + var res Volume + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/volume_ra_id.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/volume_ra_id.go new file mode 100644 index 0000000..f0f5436 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/volume_ra_id.go @@ -0,0 +1,59 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// VolumeRaID volume ra ID +// +// swagger:model VolumeRaID +type VolumeRaID struct { + + // raid can + RaidCan string `json:"raidCan,omitempty"` + + // raid uuid + RaidID string `json:"raidId,omitempty"` + + // 卷 uuid + VolumeID string `json:"volumeId,omitempty"` + + // system|data + VolumeType string `json:"volumeType,omitempty"` +} + +// Validate validates this volume ra ID +func (m *VolumeRaID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this volume ra ID based on context it is used +func (m *VolumeRaID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *VolumeRaID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *VolumeRaID) UnmarshalBinary(b []byte) error { + var res VolumeRaID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/volume_raids.go b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/volume_raids.go new file mode 100644 index 0000000..5f83fd8 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp-openapi-console-sdk/models/volume_raids.go @@ -0,0 +1,162 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// VolumeRaids volume raids +// +// swagger:model VolumeRaids +type VolumeRaids struct { + + // RaidCan string `gorm:"column:raid_can" json:"raidCan"` // RAID配置: (RAID,NO RAID) + // Raid string `gorm:"column:raid" json:"raid"` // RAID模式:RAID1,RIAD10等 + CreatedBy string `json:"createdBy,omitempty"` + + // created time + CreatedTime int64 `json:"createdTime,omitempty"` + + // deleted time + DeletedTime int64 `json:"deletedTime,omitempty"` + + // 设备类型uuid + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // 硬盘类型(SSD,HDD) + DiskType string `json:"diskType,omitempty"` + + // 接口类型(SATA,SAS,NVME,不限制) + InterfaceType string `json:"interfaceType,omitempty"` + + // is del + IsDel int8 `json:"isDel,omitempty"` + + // raids + Raids []*RVolumeRaid `json:"raids"` + + // updated by + UpdatedBy string `json:"updatedBy,omitempty"` + + // updated time + UpdatedTime int64 `json:"updatedTime,omitempty"` + + // 硬盘数量(最低块数) + VolumeAmount int64 `json:"volumeAmount,omitempty"` + + // 卷uuid + VolumeID string `json:"volumeId,omitempty"` + + // 卷名称 + VolumeName string `json:"volumeName,omitempty"` + + // 单盘大小(最小容量) + VolumeSize string `json:"volumeSize,omitempty"` + + // 卷类型:系统卷,数据卷 + VolumeType string `json:"volumeType,omitempty"` + + // 硬盘单位(GB,TB) + VolumeUnit string `json:"volumeUnit,omitempty"` +} + +// Validate validates this volume raids +func (m *VolumeRaids) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRaids(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *VolumeRaids) validateRaids(formats strfmt.Registry) error { + if swag.IsZero(m.Raids) { // not required + return nil + } + + for i := 0; i < len(m.Raids); i++ { + if swag.IsZero(m.Raids[i]) { // not required + continue + } + + if m.Raids[i] != nil { + if err := m.Raids[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("raids" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("raids" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this volume raids based on the context it is used +func (m *VolumeRaids) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateRaids(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *VolumeRaids) contextValidateRaids(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Raids); i++ { + + if m.Raids[i] != nil { + if err := m.Raids[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("raids" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("raids" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *VolumeRaids) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *VolumeRaids) UnmarshalBinary(b []byte) error { + var res VolumeRaids + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-console-api/bmp_vendor/bmp_log/.cmd b/bmp-console-api/bmp_vendor/bmp_log/.cmd new file mode 100644 index 0000000..5c2f328 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp_log/.cmd @@ -0,0 +1 @@ +rm test.log.FATAL test.log.INFO test.log.WARN diff --git a/bmp-console-api/bmp_vendor/bmp_log/README.md b/bmp-console-api/bmp_vendor/bmp_log/README.md new file mode 100644 index 0000000..f39a094 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp_log/README.md @@ -0,0 +1,6 @@ +精简日志库,用于打点统计,监控,告警等场景 +- WARN,FATAL等等级的日志即时打印落盘 + - 一个流量可以打印多条WARN,FATAL日志 +- INFO,DEBUG等级的日志,一个流量只落一条日志 + - 支持字段顺序自定义,便于正则匹配做监控等场景 + - 支持自定义代码段耗时打印,便于后续性能统计分析 diff --git a/bmp-console-api/bmp_vendor/bmp_log/go.mod b/bmp-console-api/bmp_vendor/bmp_log/go.mod new file mode 100644 index 0000000..410b4d1 --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp_log/go.mod @@ -0,0 +1,3 @@ +module coding.jd.com/aidc-bmp/bmp_log + +go 1.17 diff --git a/bmp-console-api/bmp_vendor/bmp_log/log.go b/bmp-console-api/bmp_vendor/bmp_log/log.go new file mode 100644 index 0000000..6e5b79c --- /dev/null +++ b/bmp-console-api/bmp_vendor/bmp_log/log.go @@ -0,0 +1,249 @@ +package cps_log + +import ( + "encoding/json" + "fmt" + "io" + "log" + "os" + "reflect" + "strings" + "time" +) + +// Level type +type Level uint32 + +const ( + // TraceLevel level. Designates finer-grained informational events than the Debug. + TraceLevel Level = iota + // DebugLevel level. Usually only enabled when debugging. Very verbose logging. + DebugLevel + // InfoLevel level. General operational entries about what's going on inside the + // application. + InfoLevel + // WarnLevel level. Non-critical entries that deserve eyes. + WarnLevel + // ErrorLevel level. Logs. Used for errors that should definitely be noted. + // Commonly used for hooks to send errors to an error tracking service. + ErrorLevel + // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the + // logging level is set to Panic. + FatalLevel + // PanicLevel level, highest level of severity. Logs and then calls panic with the + // message passed to Debug, Info, ... + PanicLevel +) + +var globalDefinedKeys = []string{"time", "logid", "self_t", "all_t"} + +type Logger struct { + data map[string]interface{} + level Level + fileName string + definedKeys []string +} + +func New(filename string) *Logger { + if filename == "" { + log.Fatal("filename must be provided !!!") + return nil + } + l := &Logger{ + data: make(map[string]interface{}), + fileName: filename, + } + l.definedKeys = append([]string{}, globalDefinedKeys...) + l.data["time"] = time.Now().Format("2006-01-02T15:04:05") + return l +} + +func NewLoggerWithConfig(filename string, level Level, definedKeys []string) *Logger { + l := New(filename) + l.SetLevel(level) + l.SetStableFields(definedKeys) + return l +} + +func (l *Logger) SetLevel(level Level) { + l.level = level +} + +//SetStableFields 需要固定每条日志的字段时,通过此接口设置,global在前,userdefined在后 +func (l *Logger) SetStableFields(fields []string) { + l.definedKeys = append(l.definedKeys, fields...) +} + +func (l *Logger) Point(key string, val interface{}) { + l.data[key] = val +} + +func (l *Logger) GetPoint(key string) interface{} { + return l.data[key] +} + +func (l *Logger) TimeStart(key string) { + if _, ok := l.data[key]; ok { + log.Print(fmt.Sprintf("point %s TimeStart more than once, check !!!", key)) + } + l.data[key] = time.Now() + +} + +func (l *Logger) TimeEnd(key string) { + if t, ok := l.data[key]; ok { + v := time.Now().Sub(t.(time.Time)).Milliseconds() + l.data[key] = fmt.Sprintf("%f", float64(v)/1000.0) + } else { + log.Print(fmt.Sprintf("missing call TimeStart before TimeEnd when point %s, check it!!!", key)) + } + +} + +func (l *Logger) PushPoint(key string, val interface{}) { + if _, ok := l.data[key]; !ok { + l.data[key] = []interface{}{} + } + d := l.data[key].([]interface{}) + d = append(d, val) +} + +func (l *Logger) Info(v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Infof(format string, v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warn(v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warnf(format string, v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatal(v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatalf(format string, v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Flush() { + if l.level > DebugLevel { + return + } + var beforeStr, afterStr string + for _, key := range l.definedKeys { + if val, ok := l.data[key]; ok { + if key == "time" { + beforeStr = val.(string) + continue + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + beforeStr = beforeStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + beforeStr = beforeStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + beforeStr = beforeStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Printf("val for %s unknown type!!!", key)) + + } + } + } + for key, val := range l.data { + if exist, _ := inArray(key, l.definedKeys); !exist { + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + afterStr = afterStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + afterStr = afterStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + afterStr = afterStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Sprintf("val for %s unknown type!!!", key)) + } + } + } + + line := strings.TrimSpace(beforeStr) + " " + strings.TrimSpace(afterStr) + "\r\n" + filename := fmt.Sprintf("%s.DEBUG", l.fileName) + WriteFile(filename, line) +} + +func WriteFile(filename, line string) { + TimeStamp := time.Now() + str := filename + "." + TimeStamp.Format("2006-01-02") + logf, err := os.OpenFile(str, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + if err != nil { + log.Fatal("open filename error:", err.Error()) + } + defer logf.Close() + if _, err := io.WriteString(logf, line); err != nil { + log.Fatal("write line error:", err.Error()) + } +} + +func inArray(val interface{}, array interface{}) (exists bool, index int) { + exists = false + index = -1 + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + index = i + exists = true + return + } + } + } + return +} diff --git a/bmp-console-api/bmp_vendor/ironic-common/exception/exception.go b/bmp-console-api/bmp_vendor/ironic-common/exception/exception.go new file mode 100644 index 0000000..daf985f --- /dev/null +++ b/bmp-console-api/bmp_vendor/ironic-common/exception/exception.go @@ -0,0 +1,24 @@ +package exception + +import ( + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +type Exception struct { + Status int `json:"code"` + ErrorCode string `json:"status"` + Msg string `json:"message"` +} + +var CommonParamValid = Exception{ + Status: httpStatus.BAD_REQUEST, + ErrorCode: errorCode.INVALID_ARGUMENT, + Msg: "param invalid", +} + +var InternalError = Exception{ + Status: httpStatus.INTERNAL_SERVER_ERROR, + ErrorCode: errorCode.INTERNAL, + Msg: "内部错误", +} diff --git a/bmp-console-api/bmp_vendor/ironic-common/go.mod b/bmp-console-api/bmp_vendor/ironic-common/go.mod new file mode 100644 index 0000000..5364f89 --- /dev/null +++ b/bmp-console-api/bmp_vendor/ironic-common/go.mod @@ -0,0 +1,3 @@ +module git.jd.com/cps-golang/ironic-common + +go 1.17 diff --git a/bmp-console-api/bmp_vendor/ironic-common/ironic/common/ErrorCode/ErrorCode.go b/bmp-console-api/bmp_vendor/ironic-common/ironic/common/ErrorCode/ErrorCode.go new file mode 100644 index 0000000..68743e6 --- /dev/null +++ b/bmp-console-api/bmp_vendor/ironic-common/ironic/common/ErrorCode/ErrorCode.go @@ -0,0 +1,134 @@ +package ErrorCode + +const ( + // 此操作需要的预置条件不满足 400 + FAILED_PRECONDITION = "FAILED_PRECONDITION" + + // 参数错误 400 + INVALID_ARGUMENT = "INVALID_ARGUMENT" + + // 缺少参数 400 + MISSING_ARGUMENT = "MISSING_ARGUMENT" + + // 参数类型不匹配400 + MISMATCH_ARGUMENT_TYPE = "MISMATCH_ARGUMENT_TYPE" + + // 无效的action 400 + INVALID_ACTION = "INVALID_ACTION" + + // 参数超出范围 400 + OUT_OF_RANGE = "OUT_OF_RANGE" + + // 缺少Multipart 400 + MISSING_MULTIPART = "MISSING_MULTIPART" + + // 缺少header信息 400 + MISSING_HEADER = "MISSING_HEADER" + + // pathVariable参数错误 400 + INVALID_PATHVARIABLE = "INVALID_PATHVARIABLE" + + // 验证失败 401 + UNAUTHENTICATED = "UNAUTHENTICATED" + + // 用户未激活 402 + USER_NOT_ACTIVE = "USER_NOT_ACTIVE" + + // 没有权限 403 + HTTP_FORBIDDEN = "HTTP_FORBIDDEN" + + // 找不到对象 404 + NOT_FOUND = "NOT_FOUND" + + // 操作终止 409 + ABORTED = "ABORTED" + + // 对象已存在 409 + ALREADY_EXISTS = "ALREADY_EXISTS" + + // 媒体类型不支持 415 + UNSUPPORTED_MEDIA_TYPE = "UNSUPPORTED_MEDIA_TYPE" + + // 不支持的请求方法 405 + UNSUPPORTED_HTTP_REQUEST_METHOD = "UNSUPPORTED_HTTP_REQUEST_METHOD" + + // 配额不足 429 + QUOTA_EXCEEDED = "QUOTA_EXCEEDED" + + // 库存不足429 + STOCK_SHORTAGE = "STOCK_SHORTAGE" + + // 未知错误 500 + UNKNOWN = "UNKNOWN" + + // 内部错误 500 + INTERNAL = "INTERNAL" + + // 服务不可用 503 + UNAVAILABLE = "UNAVAILABLE" + + // 会话网关 Timeout 504 + SESSION_GATEWAY_TIMEOUT = "SESSION_GATEWAY_TIMEOUT" + + // 参数错误 + PARAMETER_ERROR = "PARAMETER_ERROR" + + //com.jcloud.cps.ironic.common.ErrorCode + UNSUPPORTED_OPERATION = "UNSUPPORTED_OPERATION" + + // 子网没有可用的内网IP可以分配 400 + EXHAUSTED_SUBNET = "EXHAUSTED_SUBNET" + + EXHAUSTED_PUBLIC_IP = "EXHAUSTED_PUBLIC_IP" + + UNSUPPORTED_RAID_TYPE = "UNSUPPORTED_RAID_TYPE" + + CHANGE_ARE_NOT_ALLOWED = "CHANGE_ARE_NOT_ALLOWED" + + // 权限校验失败 + NO_PERMISSION = "NO_PERMISSION" + + // 资源被占用 + RESOURCE_IN_USE = "RESOURCE_IN_USE" + + // 内网IP超出范围 + PRIVATE_IP_NOT_IN_SUBNET = "PRIVATE_IP_NOT_IN_SUBNET" + + // EIP已经绑定 + EIP_ALREADY_ASSOCIATE = "EIP_ALREADY_ASSOCIATE" + + // EIP未绑定 + EIP_HAS_NOT_ASSOCIATE = "EIP_HAS_NOT_ASSOCIATE" + + // 子网未开通IPv6 + SUBNET_HAS_NOT_ASSIGN_IPV6 = "SUBNET_HAS_NOT_ASSIGN_IPV6" + + // IPV6已经被分配 + IPV6_ALREADY_ASSIGN = "IPV6_ALREADY_ASSIGN" + + // 实例已经绑定EIP + INSTANCE_ALREADY_ASSOCIATE_EIP = "INSTANCE_ALREADY_ASSOCIATE_EIP" + + // 实例还没有绑定EIP + INSTANCE_HAS_NOT_ASSOCIATE_EIP = "INSTANCE_HAS_NOT_ASSOCIATE_EIP" + + // 实例已经绑定IPV6 + INSTANCE_ALREADY_ASSOCIATE_IPV6 = "INSTANCE_ALREADY_ASSOCIATE_IPV6" + + // 基础网路不支持EIP + UNSUPPORTED_EIP_IN_BASIC_NETWORK = "UNSUPPORTED_EIP_IN_BASIC_NETWORK" + + // VPC网络不支持调整带宽 + UNSUPPORTED_MODIFY_BANDWIDTH_IN_VPC_NETWORK = "UNSUPPORTED_MODIFY_BANDWIDTH_IN_VPC_NETWORK" + + // 不支持批量指定内网IP + UNSUPPORTED_BATCH_SPECIFYING_PRIVATE_IP = "UNSUPPORTED_BATCH_SPECIFYING_PRIVATE_IP" + + // 不支持批量指定别名IP + UNSUPPORTED_BATCH_SPECIFYING_ALIAS_IP = "UNSUPPORTED_BATCH_SPECIFYING_ALIAS_IP" + + // 密钥对正在被实例使用 + KEYPAIR_IS_USING_BY_INSTANCE = "KEYPAIR_IS_USING_BY_INSTANCE" + + ARGUMENT_ERROR = "ARGUMENT_ERROR" +) diff --git a/bmp-console-api/bmp_vendor/ironic-common/ironic/enums/HttpStatus/HttpStatus.go b/bmp-console-api/bmp_vendor/ironic-common/ironic/enums/HttpStatus/HttpStatus.go new file mode 100644 index 0000000..243c37c --- /dev/null +++ b/bmp-console-api/bmp_vendor/ironic-common/ironic/enums/HttpStatus/HttpStatus.go @@ -0,0 +1,66 @@ +package HttpStatus + +// refer https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpStatus.html +const ( + ACCEPTED = 202 //Accepted. + ALREADY_REPORTED = 208 //Already Reported. + BAD_GATEWAY = 502 //Bad Gateway. + BAD_REQUEST = 400 //Bad Request. + BANDWIDTH_LIMIT_EXCEEDED = 509 //Bandwidth Limit Exceeded + CHECKPOINT = 103 //Checkpoint. + CONFLICT = 409 //Conflict. + CONTINUE = 100 //Continue. + CREATED = 201 //Created. + EXPECTATION_FAILED = 417 //Expectation Failed. + FAILED_DEPENDENCY = 424 //Failed Dependency. + FORBIDDEN = 403 //Forbidden. + FOUND = 302 //Found. + GATEWAY_TIMEOUT = 504 //Gateway Timeout. + GONE = 410 //Gone. + HTTP_VERSION_NOT_SUPPORTED = 505 //HTTP Version Not Supported. + I_AM_A_TEAPOT = 418 //I'm a teapot. + IM_USED = 226 //IM Used. + INSUFFICIENT_STORAGE = 507 //Insufficient Storage + INTERNAL_SERVER_ERROR = 500 //Internal Server Error. + LENGTH_REQUIRED = 411 //Length Required. + LOCKED = 423 //Locked. + LOOP_DETECTED = 508 //Loop Detected + METHOD_NOT_ALLOWED = 405 //Method Not Allowed. + MOVED_PERMANENTLY = 301 //Moved Permanently. = MOVE//D_TEMPORARILY Deprecated in favor of FOUND which will be returned from HttpStatusvalueOf(302). + MULTI_STATUS = 207 //Multi-Status. + MULTIPLE_CHOICES = 300 //Multiple Choices. + NETWORK_AUTHENTICATION_REQUIRED = 511 //Network Authentication Required. + NO_CONTENT = 204 //No Content. + NON_AUTHORITATIVE_INFORMATION = 203 //Non-Authoritative Information. + NOT_ACCEPTABLE = 406 //Not Acceptable. + NOT_EXTENDED = 510 //Not Extended + NOT_FOUND = 404 //Not Found. + NOT_IMPLEMENTED = 501 //Not Implemented. + NOT_MODIFIED = 304 //Not Modified. + OK = 200 //OK. + PARTIAL_CONTENT = 206 //Partial Content. + PAYLOAD_TOO_LARGE = 413 //Payload Too Large. + PAYMENT_REQUIRED = 402 //Payment Required. + PERMANENT_REDIRECT = 308 //Permanent Redirect. + PRECONDITION_FAILED = 412 //Precondition failed. + PRECONDITION_REQUIRED = 428 //Precondition Required. + PROCESSING = 102 //Processing. + PROXY_AUTHENTICATION_REQUIRED = 407 //Proxy Authentication Required. + REQUEST_HEADER_FIELDS_TOO_LARGE = 431 //Request Header Fields Too Large. + REQUEST_TIMEOUT = 408 //Request Timeout. + REQUESTED_RANGE_NOT_SATISFIABLE = 416 //Requested Range Not Satisfiable. + RESET_CONTENT = 205 //Reset Content. + SEE_OTHER = 303 //See Other. + SERVICE_UNAVAILABLE = 503 //Service Unavailable. + SWITCHING_PROTOCOLS = 101 //Switching Protocols. + TEMPORARY_REDIRECT = 307 //Temporary Redirect. + TOO_EARLY = 425 //Too Early. + TOO_MANY_REQUESTS = 429 //Too Many Requests. + UNAUTHORIZED = 401 //Unauthorized. + UNAVAILABLE_FOR_LEGAL_REASONS = 451 //Unavailable For Legal Reasons. + UNPROCESSABLE_ENTITY = 422 //Unprocessable Entity. + UNSUPPORTED_MEDIA_TYPE = 415 //Unsupported Media Type. + UPGRADE_REQUIRED = 426 //Upgrade Required. + URI_TOO_LONG = 414 //URI Too Long USE_PROXY Deprecated due to security concerns regarding in-band configuration of a proxy + VARIANT_ALSO_NEGOTIATES = 506 //Variant Also Negotiates +) diff --git a/bmp-console-api/bmp_vendor/ironic-common/ironic/util/util.go b/bmp-console-api/bmp_vendor/ironic-common/ironic/util/util.go new file mode 100644 index 0000000..5aca77e --- /dev/null +++ b/bmp-console-api/bmp_vendor/ironic-common/ironic/util/util.go @@ -0,0 +1,77 @@ +package util + +import ( + "encoding/json" + "errors" + "fmt" + "math/rand" + "reflect" + "strconv" + "time" +) + +//GetRandString 借鉴RandomStringUtils.random包生成随机字符串 +// length 随机字符串的长度(不包括前缀) +// uletter 随机字符串是否包含大写字母字符 +// dletter 随机字符串是否包含小写字母字符 +// number 随机字符串是否包含数字字符 +func GetRandString(prefix string, length int32, uletter, dletter, number bool) string { + rand.Seed(time.Now().UnixNano()) + uletters := []rune("ABCDEFGHIGKLMNOPQRSTUVWXYZ") + dletters := []rune("abcdefghijklmnopqrstuvwxyz") + numbers := []rune("0123456789") + source := []rune{} + if uletter { + source = append(source, uletters...) + } + if dletter { + source = append(source, dletters...) + } + if number { + source = append(source, numbers...) + } + if len(source) == 0 { + return "atLeastContainsLetterOrNumber" + } + b := make([]rune, length) + for i := range b { + b[i] = source[rand.Intn(len(source))] + } + return prefix + string(b) +} + +// 跟现有环境一致,格式:aafc4d1b-f696-4ec2-924f-6fd012aa8345 +func GenerateRandUuid() string { + s := GetRandString("", 32, false, true, true) + runes := []rune(s) + return string(runes[0:8]) + "-" + string(runes[8:12]) + "-" + string(runes[12:16]) + "-" + string(runes[16:20]) + "-" + string(runes[20:32]) +} + +func Convert2String(val interface{}) (msg string, err error) { + + if val == nil{ + return "", nil + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool: + msg = strconv.FormatBool(val.(bool)) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + msg = fmt.Sprintf("%v", val) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + msg = fmt.Sprintf("%v", val) + case reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + msg = fmt.Sprintf("%v", val) + case reflect.String: + msg = val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + s, err := json.Marshal(val) + if err == nil { + msg = string(s) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + err = errors.New(fmt.Sprintf("type %s not support convert to string", reflect.TypeOf(val).String())) + default: + err = errors.New(fmt.Sprintf("type %s not support convert to string", reflect.TypeOf(val).String())) + } + return +} diff --git a/bmp-console-api/build.sh b/bmp-console-api/build.sh new file mode 100644 index 0000000..c076ae2 --- /dev/null +++ b/bmp-console-api/build.sh @@ -0,0 +1,124 @@ +#!/bin/bash +############################################################################### +#编译脚本的原理是将编译结果放到output目录中,这个样例模版提供一个产生 +#一个最基本golang运行程序包的编译脚本,对于特殊的需求请酌情考虑 +# +#1、该脚本支持参数化,参数将传入build_package函数(内容为最终执行的编译命令) +# ,用$1,$2....表示,第1,2...个参数 +#2、部署需要启动程序,所以需要提供control文件放在当前目录中,用于启动和 +# 监控程序状态 + +###############用户修改部分################ +readonly PROJECT_NAME="ironic-jdstack" #项目名称,相对于$GOPATH/src文件夹所在的目录,可选项 +readonly PACKAGE_DIR_NAME=main.go #main文件相对于src文件夹所在的目录,可选项 +readonly PACKAGE_BIN_NAME=ironic-jdstack #定义产出的运行程序名,必填项 +readonly CONF_DIR_NAME="conf" #定义配置文件目录,此路径为相对路径,可选项 +readonly OTHERS_DIR_NAME="" #定义其它文件目录,多个目录以空格区分,此路径为相对路径,可选项 +#最终的抽包路径为$OUTPUT +########################################### + +if [[ "${PACKAGE_BIN_NAME}" == "" ]];then + echo "Please set "PACKAGE_BIN_NAME" value" + exit 1 +fi + +function set_work_dir +{ + readonly OUTPUT=$(pwd)/output + readonly WORKSPACE_DIR=$(pwd) +} + +#清理编译构建目录操作 +function clean_before_build +{ + cd ${WORKSPACE_DIR} + rm -rf bin pkg + rm -rf ${OUTPUT} +} + +#初始化编译环境 +function prepare_package() +{ + if [ ! -z "$PROJECT_NAME" ];then + mkdir -p src/$PROJECT_NAME + copy_files=`ls |grep -vw 'src'` + cp -rf $copy_files src/$PROJECT_NAME/ + fi +} + +#实际的编译命令 +#这个函数中可使用$1,$2...获取第1,2...个参数 +function build_package() +{ + cd ${WORKSPACE_DIR} + # export GOPATH=$(pwd) + go clean + echo $(pwd) + echo $(ls) + go build -v -gcflags="-N -l" -o ${PACKAGE_BIN_NAME} ${PACKAGE_DIR_NAME} || return 1 +} + +#建立最终发布的目录 +function build_dir +{ + mkdir -p ${OUTPUT}/bin || return 1 +} + +function dir_not_empty() +{ + if [[ ! -d $1 ]];then + return 1 + fi + if [[ $(ls $1|wc -l) -eq 0 ]];then + return 1 + fi + return 0 +} + +#拷贝编译结果到发布的目录 +function copy_result +{ + cd ${WORKSPACE_DIR} + cp -r ${PACKAGE_BIN_NAME} ${OUTPUT}/bin/ || return 1 + cp -r ./control ${OUTPUT}/bin || return 1 + dir_not_empty ${WORKSPACE_DIR}/${CONF_DIR_NAME} && mkdir -p ${OUTPUT}/${CONF_DIR_NAME} + cp -rf ./${CONF_DIR_NAME}/* ${OUTPUT}/${CONF_DIR_NAME}/ + test -z "$OTHERS_DIR_NAME" || cp -rf $OTHERS_DIR_NAME ${OUTPUT}/ + return 0 +} + +#执行 +function main() +{ + cd $(dirname $0) + set_work_dir + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Cleaning...' + clean_before_build || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Clean completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'preparng...' + prepare_package || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'prepare completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Building...' + build_package $@ || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Build completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Making dir...' + build_dir || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Make completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy result to publish dir...' + copy_result || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy completed' + echo + + exit 0 +} + +main $@ diff --git a/bmp-console-api/conf/app.conf b/bmp-console-api/conf/app.conf new file mode 100644 index 0000000..e69de29 diff --git a/bmp-console-api/conf/bmp-console-test.ini b/bmp-console-api/conf/bmp-console-test.ini new file mode 100644 index 0000000..d6e9411 --- /dev/null +++ b/bmp-console-api/conf/bmp-console-test.ini @@ -0,0 +1,8 @@ +[test] +# redis +bmp_redis_host=${BMP_REDIS_HOST||10.226.192.72} +bmp_redis_port=${BMP_REDIS_PORT||16379} +bmp_redis_password=${BMP_REDIS_PASSWORD||LE&oN$9wHB} + +openapi_host=${BMP_OPENAPI_CONSOLE_HOST||127.0.0.1} +openapi_port=${BMP_OPENAPI_CONSOLE_PORT||8802} \ No newline at end of file diff --git a/bmp-console-api/conf/bmp-console.ini b/bmp-console-api/conf/bmp-console.ini new file mode 100644 index 0000000..c187915 --- /dev/null +++ b/bmp-console-api/conf/bmp-console.ini @@ -0,0 +1,34 @@ +appname = bmp-console-api +runmode = "${BMP_CONSOLE_RUNMODE||test}" +autorender = false +copyrequestbody = true +EnableDocs = true +httpport = 8800 + + +# 打开session +sessionon = true +# 设置session id的名字 +sessionname = bmp_console_api +# 设置session存储引擎 +sessionlife = 43200 + + +bmp_redis_host=${BMP_REDIS_HOST} +bmp_redis_port=${BMP_REDIS_PORT} +bmp_redis_password=${BMP_REDIS_PASSWORD} + +openapi_host=${BMP_OPENAPI_CONSOLE_HOST} +openapi_port=${BMP_OPENAPI_CONSOLE_PORT} + +openapi_token="Ym1wLWNvbnNvbGUtYXBp" + +# log +log.level=DEBUG +log.max.history=10 +log.path=/var/log/bmp/bmp-console-api +# upload file path(image,device) +upload.path=./data + +# 本地调试的话,把下面的注释打开,读取本地配置文件 +#include "bmp-console-test.ini" diff --git a/bmp-console-api/constants/constants.go b/bmp-console-api/constants/constants.go new file mode 100644 index 0000000..aaa0999 --- /dev/null +++ b/bmp-console-api/constants/constants.go @@ -0,0 +1,6 @@ +package constants + +const ( + LANGUAGE_EN = "en_US" + LANGUAGE_ZH = "zh_CN" +) diff --git a/bmp-console-api/control b/bmp-console-api/control new file mode 100644 index 0000000..5396811 --- /dev/null +++ b/bmp-console-api/control @@ -0,0 +1,125 @@ +#!/bin/bash +set -x +cd "$(dirname $0)"/.. +BASE_DIR=`pwd` +if [ -f default_env.sh ];then + source default_env.sh +fi + +PROC_NAME=ironic-jdstack # 进程名 一般就是二进制的名字java类程序一般就是java +PROC_PORT=8503 # 程序占用的端口,建议写,程序不占用端口的话只用ps来判断进程是否启动,机器上有同名程序是可能有问题 +WAIT_TIME=60 # 执行START_COMMAND后到程序能完全启动listen端口需要花的时间 + +USER=nginx +app_dir=/home/$USER/$PROC_NAME +mkdir -p $app_dir/log + +START_COMMAND="$app_dir/bin/ironic-jdstack -c $app_dir/conf/ironic-console.ini" #在output目录下启动你程序的命令 + +help(){ + echo "${0} " + exit 1 +} + +checkhealth(){ + if [[ -n "$PROC_PORT" ]] ; then + PORT_PROC=$(/usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d |awk '{print $NF}' |grep -oP '".*"' |sed "s/\"//g" |uniq) + if [ X"$PORT_PROC" = X"$PROC_NAME" ] ; then + echo "1 running" + return 0 + fi + echo "1 not running" + return 1 + else + ps -eo comm,pid |grep -P "^$PROC_NAME" + if [ "$?" = 0 ] ; then + echo "2 running" + return 0 + fi + echo "2 not running" + return 1 + fi +} + + +start(){ + checkhealth + if [ $? = 0 ]; then + echo "[WARN] $PROC_NAME is aleady running!" + return 0 + fi + + [ -d "$app_dir" ] && cd $app_dir && rm -rf `ls ${app_dir} | grep -v log` + cp -r $BASE_DIR/* ${app_dir}/ + chown -R $USER:$USER ${app_dir} + su $USER -c "nohup $START_COMMAND > ${app_dir}/log/cps-ironic-api.log 2>&1 &" + + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ $? = 0 ]; then + echo "Start $PROC_NAME success" + return 0 + fi + done + echo "[ERROR] Start $PROC_NAME failed" + return 1 +} + +stop(){ + if [[ -n "$PROC_PORT" ]] ; then + PROC_ID=$( /usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d | awk '{print $NF}' | grep -oP ',.*,' | grep -oP "\d+" | uniq ) + else + PROC_ID=$(ps -eo comm,pid | grep "^$PROC_NAME" |awk '{print $2}') + fi + + if [[ -z "$PROC_ID" ]] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + + checkhealth + if [ "$?" != "0" ] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + kill $PROC_ID + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + done + + kill -9 $PROC_ID + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + + echo "[ERROR] Stop $PROC_NAME failed" + return 1 +} + +case "${1}" in + start) + start + ;; + stop) + stop + ;; + status|health|checkhealth) + checkhealth + ;; + restart) + stop && start + ;; + *) + help + ;; +esac + diff --git a/bmp-console-api/controllers/ApikeyController.go b/bmp-console-api/controllers/ApikeyController.go new file mode 100644 index 0000000..a26549c --- /dev/null +++ b/bmp-console-api/controllers/ApikeyController.go @@ -0,0 +1,86 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-console-api/logic/ApikeyLogic" + + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + response "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type ApikeyController struct { + BaseController +} + +// swagger:route PUT /apikey keypair createApikey +// CreateAPIkey 创建apikey +// Responses: +// 200: createApikey +// default: ErrorResponse + +func (c *ApikeyController) CreateApikey() { + req := &sdkModels.CreateApikeyRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateAPIkey parse pAPIkeyt body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + // req.Validate(c.logPoints) + uuid, err := ApikeyLogic.CreateApikey(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ApikeyId{ + ApikeyId: uuid, + } +} + +// swagger:route GET /apikey keypair getApikeyList +// GetApikeyList 获取apikey列表 +// Responses: +// 200: getApikeyList +// default: ErrorResponse + +func (c *ApikeyController) GetApikeyList() { + defer c.CatchException() + + req := requestTypes.GetApikeyListRequest{ + PagingRequest: requestTypes.PagingRequest{ + PageNumber: c.getPageNumber(), + PageSize: c.getPageSize(), + }, + } + + // req.Validate(c.logPoints) + res, err := ApikeyLogic.GetApikeyList(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res + +} + +// swagger:route DELETE /apikey/{apikey_id} keypair deleteApikey +// DeleteApikey 删除apikey +// Responses: +// 200: deleteApikey +// default: ErrorResponse + +func (c *ApikeyController) DeleteApikey() { + defer c.CatchException() + apikeyId := c.Ctx.Input.Param(":apikey_id") + if err := ApikeyLogic.DeleteApikey(c.logPoints, apikeyId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} diff --git a/bmp-console-api/controllers/BaseController.go b/bmp-console-api/controllers/BaseController.go new file mode 100644 index 0000000..ead9a95 --- /dev/null +++ b/bmp-console-api/controllers/BaseController.go @@ -0,0 +1,326 @@ +package controllers + +import ( + "encoding/json" + "fmt" + "strconv" + "strings" + + UserLoigc "coding.jd.com/aidc-bmp/bmp-console-api/logic/UserLogic" + util "coding.jd.com/aidc-bmp/bmp-console-api/util" + log "coding.jd.com/aidc-bmp/bmp_log" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + "github.com/beego/beego/v2/server/web" + + beego "github.com/beego/beego/v2/server/web" +) + +var sessionName string + +func init() { + sessionName, _ = beego.AppConfig.String("sessionname") +} + +func Init() { + sessionName, _ = beego.AppConfig.String("sessionname") +} + +type ErrorResponse struct { + Code int `json:"code"` + Message string `json:"message"` + Status string `json:"status"` +} + +type Response struct { + Result interface{} `json:"result,omitempty"` + Error *ErrorResponse `json:"error,omitempty"` + RequestId string `json:"requestId"` +} + +// SubnetController operations for Subnet +type BaseController struct { + web.Controller + logPoints *log.Logger + Res Response + pageable util.Pageable +} + +func (b *BaseController) SetErrorResponse(code int, message, status string) { + + b.Ctx.Output.Status = code + b.Res.Error = &ErrorResponse{ + Code: code, + Message: message, + Status: status, + } +} + +func (b *BaseController) Prepare() { + web.ReadFromRequest(&b.Controller) + logPath, _ := beego.AppConfig.String("log.path") + b.logPoints = log.New(logPath + "/bmp-console.log") + + fmt.Println("[DEBUG MINPING]req url:", b.Ctx.Request.URL) + fmt.Println("[DEBUG MINPING]req method", b.Ctx.Request.Method) + fmt.Println("[DEBUG MINPING]req header", b.Ctx.Request.Header) + fmt.Println("[DEBUG MINPING]req body:", string(b.Ctx.Input.RequestBody)) + + b.logPoints.SetStableFields([]string{"method", "uri", "header", "request", "response"}) + b.logPoints.Point("uri", b.Ctx.Request.RequestURI) + b.logPoints.Point("method", b.Ctx.Request.Method) + b.logPoints.Point("header", b.Ctx.Request.Header) + b.logPoints.Point("request", string(b.Ctx.Input.RequestBody)) + b.logPoints.TimeStart("all_t") + b.logPoints.TimeStart("self_t") + requestID := b.GetRequestID() + + b.logPoints.Point("logid", requestID) + // b.logPoints.Point("pin", b.GetPin()) + b.logPoints.Point("language", b.GetLanguage()) + b.Ctx.Output.Header("X-Jdcloud-Request-Id", requestID) + b.Res = Response{} + b.pageable = util.Pageable{ + PageNumber: b.getPageNumber(), + PageSize: b.getPageSize(), + } + + if !strings.HasPrefix(b.Ctx.Input.URI(), "/login") && !strings.HasPrefix(b.Ctx.Input.URI(), "/logout") { + jdc := b.Ctx.GetCookie(sessionName) + fmt.Println("prepare func get cookie:", jdc) + b.logPoints.Infof("vvv prepare func get cookie:%s, sessionName:%s", jdc, sessionName) + if jdc == "" { + b.logPoints.Warn("no session_id in cookie, the cookies are: %v", b.Ctx.Request.Cookies()) + b.Ctx.ResponseWriter.WriteHeader(402) + fmt.Fprintln(b.Ctx.ResponseWriter, "user not login") + return + } + //err := b.SetSession(jdc, "admin") + //fmt.Println(err) + userName := b.GetSession(jdc) + fmt.Println("prepare func get session.username:", userName) + b.logPoints.Infof("prepare func get cookie:%s, session.username:%s, sessionname:%s", jdc, userName, sessionName) + if userName == nil { + b.logPoints.Warnf("session_id %s not found or timeout, relogin please...", jdc) + b.Ctx.ResponseWriter.WriteHeader(402) + fmt.Fprintln(b.Ctx.ResponseWriter, "user not login") + return + } else { + b.Ctx.Output.Header("X-Jdcloud-Username", userName.(string)) + b.logPoints.Point("username", userName.(string)) + user, err := UserLoigc.GetUserByName(b.logPoints, userName.(string)) + if err != nil { + fmt.Println("prepare.fun.GetUserByName err:", err.Error()) + b.logPoints.Warnf("prepare.UserLoigc.GetUserByName error, username:%s, error:%s", userName.(string), err.Error()) + return + } + fmt.Println("prepare.fun.userid is:", user.UserID) + b.logPoints.Point("userId", user.UserID) + if user.Timezone == "" { + user.Timezone = "Asia/Shanghai" + } + b.logPoints.Point("timezone", user.Timezone) + b.Ctx.Output.Header("X-Jdcloud-UserID", user.UserID) + b.logPoints.Infof("get session success, session_id: %s, userid: %s", jdc, userName) + } + } + +} + +func (b *BaseController) Finish() { + //上述情况为正确情况 + b.Res.RequestId = b.GetRequestID() + b.Data["json"] = b.Res + + b.ServeJSON() + b.logPoints.TimeEnd("self_t") + b.logPoints.TimeEnd("all_t") + + v, _ := json.Marshal(b.Data["json"]) + fmt.Println("[DEBUG MINPING]resp body:", string(v)) + + b.logPoints.Point("response", b.Data["json"]) + b.logPoints.Flush() + +} + +func (b *BaseController) GetString(key string) string { + return b.Controller.GetString(key, "") +} + +func (b *BaseController) GetInt(key string) (int, error) { + return b.Controller.GetInt(key, 0) +} + +//业务代码可以直接panic终止运行 +func (b *BaseController) CatchException() { + /* + if r := recover(); r != nil { + //t := make([]byte, 1<<16) + //runtime.Stack(t, true) + t, _ := json.Marshal(r) + //fmt.Println(reflect.ValueOf(r)) + b.logPoints.Warn(string(t)) + //fmt.Printf("%T", reflect.ValueOf(r).Field(0).Int()) + } + */ +} + +func (b *BaseController) GetRequestID() string { + if b.Ctx.Request.Header["X-Jdcloud-Request-Id"] != nil { + return b.Ctx.Request.Header["X-Jdcloud-Request-Id"][0] + } + //生成随机字符串logid + logid := commonUtil.GenerateRandUuid() + b.Ctx.Request.Header["X-Jdcloud-Request-Id"] = []string{logid} + return logid +} + +func (b *BaseController) GetErp() string { + if b.Ctx.Request.Header["X-Jdcloud-Erp"] != nil { + return b.Ctx.Request.Header["X-Jdcloud-Erp"][0] + } + return "" +} + +func (b *BaseController) GetJDCookie() string { + if b.Ctx.Request.Header["X-Jdcloud-Cookie"] != nil { + return b.Ctx.Request.Header["X-Jdcloud-Host"][0] + } + return "" +} + +func (b *BaseController) GetJDHost() string { + if b.Ctx.Request.Header["X-Jdcloud-Host"] != nil { + return b.Ctx.Request.Header["X-Jdcloud-Host"][0] + } + return "" +} + +// v1/validation success res: {"requestId":"0wzsgfzm-veo8-rjbm-nf53-0gqparr6b9di","error":null,"result":{"loginInfo":{"type":1,"pin":"4cb497f05ae7455c9272","adminPin":null,"credentialInfo":null,"loginUrl":"","loginName":"zyTest"}}} + +// failed res:{"requestId":"bygqoepg-k3n1-k8rc-4l52-iho1nr3brmtp","error":null,"result":{"loginInfo":{"type":0,"pin":null,"adminPin":null,"credentialInfo":null,"loginUrl":"http://login-stag.jdcloud.com","loginName":null}}} + +type LoginstateValidationRes struct { + RequestId string `json:"requestId"` + // Error string `json:"error"` + Result struct { + LoginInfo LoginInfo `json:"loginInfo"` + } `json:"result"` +} + +type LoginInfo struct { + Type int `json:"type"` //0表示未登录,1表示主账号登录,2表示子账号登录,3表示角色登录 + Pin string `json:"pin"` + AdminPin string `json:"adminPin"` + CredentialInfo *CredentialInfo `json:"credentialInfo"` + LoginUrl string `json:"loginUrl"` + LoginName string `json:"loginName"` +} + +type CredentialInfo struct { + AccessKey string `json:"accessKey"` + SecretKey string `json:"secretKey"` + SessionToken string `json:"sessionToken"` + Expiration string `json:"expiration"` //类型是data还是string?返回结果此字段都没有数据,先定义成string + RolePin string `json:"rolePin"` +} + +func (b *BaseController) GetLanguage() string { + fmt.Println("语言header", b.Ctx.Request.Header["X-Jdcloud-Language"]) + fmt.Println("语言cookie", b.Ctx.GetCookie("X-Jdcloud-Language"), b.Ctx.GetCookie("path_url")) + return b.Ctx.GetCookie("X-Jdcloud-Language") + //if len(b.Ctx.Request.Header["X-Jdcloud-Language"]) == 0 { + // return "" + //} + //return b.Ctx.Request.Header["X-Jdcloud-Language"][0] + +} + +func (b *BaseController) GetHost() string { + return b.Ctx.Request.Host +} + +func (b *BaseController) GetFields() (fields []string) { + // fields: col1,col2,entity.col3 + if v := b.GetString("fields"); v != "" { + fields = strings.Split(v, ",") + } + return +} + +func (b *BaseController) GetSortBy() (sortby []string) { + // sortby: col1,col2 + if v := b.GetString("sortby"); v != "" { + sortby = strings.Split(v, ",") + } + return +} + +func (b *BaseController) GetOrder() (order []string) { + // order: desc,asc + if v := b.GetString("order"); v != "" { + order = strings.Split(v, ",") + } + return +} + +// GetOffset 默认返回0 +func (b *BaseController) GetOffset() int64 { + if o := b.GetString("pageNumber"); o != "" { + if v, err := strconv.ParseInt(o, 10, 64); err == nil { + //第2页 每页10条 offset=10 + //第1页, 每页10条,offset=0 + if v > 0 { + return (v - 1) * b.GetLimit() + } + } + } + return 0 +} + +// GetOffset 默认返回10 +func (b *BaseController) GetLimit() int64 { + if l := b.GetString("pageSize"); l != "" { + if v, err := strconv.ParseInt(l, 10, 64); err == nil { + return v + } + } + return 20 +} + +func (b *BaseController) getPageNumber() int64 { + if l := b.GetString("pageNumber"); l != "" { + if v, err := strconv.Atoi(l); err == nil { + return int64(v) + } + } + return 1 +} + +func (b *BaseController) getPageSize() int64 { + if l := b.GetString("pageSize"); l != "" { + if v, err := strconv.Atoi(l); err == nil { + return int64(v) + } + } + if strings.HasPrefix(b.Ctx.Request.RequestURI, "/devices") { + return 10 + } + if strings.HasPrefix(b.Ctx.Request.RequestURI, "/instances") { + return 10 + } + if strings.HasPrefix(b.Ctx.Request.RequestURI, "/subnets") { + return 10 + } + return 20 +} + +func restfulResponseException(code int, status string, msg string) map[string]interface{} { + return map[string]interface{}{ + "error": map[string]interface{}{ + "code": code, + "status": status, + "message": msg, + }, + } +} diff --git a/bmp-console-api/controllers/CustomController.go b/bmp-console-api/controllers/CustomController.go new file mode 100644 index 0000000..c32885f --- /dev/null +++ b/bmp-console-api/controllers/CustomController.go @@ -0,0 +1,50 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-console-api/logic/CustomInfoLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "git.jd.com/cps-golang/ironic-common/exception" +) + +// CustomController operations for custom info +type CustomController struct { + BaseController +} + +// SetCustomInfo ... +// swagger:route POST /custom/setCustomInfo custom setCustomInfo +// SetCustomInfo 设置自定义表头 +// Responses: +// 200: setCustomInfo +// default: ErrorResponse + +func (c *CustomController) SetCustomInfo() { + defer c.CatchException() + req := &requestTypes.SetCustomInfoRequest{} + // req.Validate() + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + panic(exception.Exception{Msg: err.Error()}) + } + res := CustomInfoLogic.SetCustomInfo(c.logPoints, *req) + c.Res.Result = res +} + +// GetCustomInfo ... +// swagger:route GET /custom/getCustomInfo custom getCustomInfo +// GetCustomInfo 获取自定义表头 +// Responses: +// 200: getCustomInfo +// default: ErrorResponse + +func (c *CustomController) GetCustomInfo() { + defer c.CatchException() + req := &requestTypes.QueryCustomInfoRequest{ + PageKey: c.GetString("pageKey"), + Reload: c.GetString("reload"), + } + // req.Validate() + res := CustomInfoLogic.GetCustomInfo(c.logPoints, *req) + c.Res.Result = res +} diff --git a/bmp-console-api/controllers/DeviceController.go b/bmp-console-api/controllers/DeviceController.go new file mode 100644 index 0000000..cb6efb4 --- /dev/null +++ b/bmp-console-api/controllers/DeviceController.go @@ -0,0 +1,43 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/logic/DeviceLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceController operations for Device +type DeviceController struct { + BaseController +} + +// swagger:route GET /device/isDeviceStockEnough device isDeviceStockEnough +// IsDeviceStockEnough 查询设备库存是否足够 +// Responses: +// 200: isDeviceStockEnough +// default: ErrorResponse + +func (c *DeviceController) IsDeviceStockEnough() { + defer c.CatchException() + + cnt, _ := c.GetInt("count") + req := requestTypes.QueryDeviceStockRequest{ + IdcID: c.GetString("idc_id"), + DeviceTypeId: c.GetString("deviceTypeId"), + Count: int64(cnt), + } + + // req.Validate(c.logPoints) + res, err := DeviceLogic.QueryDeviceStockCount(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = responseTypes.QueryDeviceStockResponse{ + Success: res >= int64(cnt), + AvaliableCount: res, + } + +} diff --git a/bmp-console-api/controllers/DeviceTypeController.go b/bmp-console-api/controllers/DeviceTypeController.go new file mode 100644 index 0000000..40b84ed --- /dev/null +++ b/bmp-console-api/controllers/DeviceTypeController.go @@ -0,0 +1,35 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/logic/DeviceTypeLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for DeviceType +type DeviceTypeController struct { + BaseController +} + +// swagger:route GET /deviceType/getAvailableDeviceTypes deviceType getAvailableDeviceTypes +// GetAvailableDeviceTypes 获取该机房内可用机型列表 +// Responses: +// 200: getAvailableDeviceTypes +// default: ErrorResponse + +func (c *DeviceTypeController) GetAvailableDeviceTypes() { + defer c.CatchException() + req := requestTypes.GetAvailableDeviceTypesRequest{ + IdcID: c.GetString("idc_id"), + } + + // req.Validate(c.logPoints) + res, err := DeviceTypeLogic.GetAvailableDeviceTypes(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = res + +} diff --git a/bmp-console-api/controllers/IdcController.go b/bmp-console-api/controllers/IdcController.go new file mode 100644 index 0000000..dac0653 --- /dev/null +++ b/bmp-console-api/controllers/IdcController.go @@ -0,0 +1,37 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/logic/IdcLogic" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// IdcController operations for idc +type IdcController struct { + BaseController +} + +// swagger:route GET /idc idc getIdcList +// GetIdcList 获取idc列表 +// Responses: +// 200: getIdcList +// default: ErrorResponse + +func (c *IdcController) GetIdcList() { + defer c.CatchException() + + // req.Validate(c.logPoints) + res, err := IdcLogic.GetIdcList(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + if c.GetString("exportType") != "" { + fileName, downloadFileName := IdcLogic.ExportIdcList(c.logPoints, res.Idcs) + //c.Ctx.Input.SetData("download", "yes") + c.Ctx.Output.Download(fileName, downloadFileName) + return + } else { + c.Res.Result = res + } +} diff --git a/bmp-console-api/controllers/ImageController.go b/bmp-console-api/controllers/ImageController.go new file mode 100644 index 0000000..957a61b --- /dev/null +++ b/bmp-console-api/controllers/ImageController.go @@ -0,0 +1,36 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/logic/ImageLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// ImageController operations for image +type ImageController struct { + BaseController +} + +// swagger:route GET /image/queryImagesByDeviceType image queryImagesByDeviceType +// QueryImagesByDeviceType 根据机型获取绑定的镜像列表 +// Responses: +// 200: queryImagesByDeviceType +// default: ErrorResponse + +func (c *ImageController) QueryImagesByDeviceType() { + defer c.CatchException() + + req := requestTypes.QueryImagesByDeviceTypeRequest{ + IdcID: c.GetString("idc_id"), + DeviceTypeID: c.GetString("deviceTypeId"), + } + // req.Validate(c.logPoints) + res, err := ImageLogic.QueryImagesByDeviceType(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = res + +} diff --git a/bmp-console-api/controllers/InstanceController.go b/bmp-console-api/controllers/InstanceController.go new file mode 100644 index 0000000..79283b3 --- /dev/null +++ b/bmp-console-api/controllers/InstanceController.go @@ -0,0 +1,509 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-console-api/logic/InstanceLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + response "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" + + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +type InstanceController struct { + BaseController +} + +// swagger:route GET /instance instance getInstanceList +// GetInstanceList 实例列表 +// Responses: +// 200: getInstanceList +// default: ErrorResponse + +func (c *InstanceController) GetInstanceList() { + defer c.CatchException() + pr := requestTypes.PagingRequest{ + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + } + param := requestTypes.QueryInstancesRequest{ + PagingRequest: pr, + ProjectID: c.GetString("projectId"), + IdcID: c.GetString("idcId"), + Status: c.GetString("status"), // v2.27.2 状态,逗号分隔;显示所有选项,复选框选择,支持多选。 + DeviceTypeId: c.GetString("deviceTypeId"), //按照机型搜索 + Name: c.GetString("name"), //v2.27.2 实例列表搜索框支持联合搜索| 模糊搜索 + DeviceType: c.GetString("deviceType"), + InstanceId: c.GetString("instanceId"), + + KeypairId: c.GetString("keypairId"), + Sn: c.GetString("sn"), + PrivateIp: c.GetString("privateIp"), + PrivateIpv6: c.GetString("privateIpv6"), + IloIp: c.GetString("iloIp"), // 带外管理IP,逗号分隔 + // Cabinets: c.GetString("cabinets"), //机柜编码,逗号分隔 + DeviceTypeList: c.GetString("deviceTypeList"), // 规格类型,逗号分隔 + ExportType: c.GetString("exportType"), + IsAll: c.GetString("isAll"), + IsInstallAgent: c.GetString("isInstallAgent"), + } + res, err := InstanceLogic.DescribeInstances(c.logPoints, param) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if res.Instances == nil { + res.Instances = make([]response.Instance, 0) + } + if c.GetString("exportType") != "" { + fileName, downloadFileName := InstanceLogic.ExportInstance(c.logPoints, res.Instances) + //c.Ctx.Input.SetData("download", "yes") + c.Ctx.Output.Download(fileName, downloadFileName) + return + } else { + c.Res.Result = res + } +} + +// swagger:route GET /instance/{instance_id} instance getInstanceInfo +// GetInstanceInfo 查看实例详情 +// Responses: +// 200: getInstanceInfo +// default: ErrorResponse + +func (c *InstanceController) GetInstanceInfo() { + defer c.CatchException() + param := requestTypes.QueryInstanceRequest{ + InstanceId: c.Ctx.Input.Param(":instance_id"), + } + res, err := InstanceLogic.DescribeInstance(c.logPoints, param) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route PUT /instance instance createInstance +// CreateInstance 创建实例 +// Responses: +// 200: createInstance +// default: ErrorResponse + +func (c *InstanceController) CreateInstance() { + + defer c.CatchException() + + req := &sdkModels.CreateInstanceRequest{} + c.logPoints.Infof("CreateInstance body is:%s", string(c.Ctx.Input.RequestBody)) + //fmt.Println(req, req.Hostname) + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + // req.Validate() + res, err := InstanceLogic.CreateInstanceApi(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } else { + c.Res.Result = response.CreateInstanceResponse{ + InstanceIDs: res, + } + return + } + +} + +// swagger:route POST /instance/startInstance instance startInstance +// StartInstance 开机 +// Responses: +// 200: startInstance +// default: ErrorResponse + +func (c *InstanceController) StartInstance() { + defer c.CatchException() + + req := &requestTypes.StartInstanceRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + // req.Validate() + res, err := InstanceLogic.StartInstance(c.logPoints, *req) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instance/stopInstance instance stopInstance +// StopInstance 关机 +// Responses: +// 200: stopInstance +// default: ErrorResponse + +func (c *InstanceController) StopInstance() { + defer c.CatchException() + req := &requestTypes.StopInstanceRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + // req.Validate() + res, err := InstanceLogic.StopInstance(c.logPoints, *req) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instance/restartInstance instance restartInstance +// RestartInstance 重启实例 +// Responses: +// 200: restartInstance +// default: ErrorResponse + +func (c *InstanceController) RestartInstance() { + defer c.CatchException() + req := &requestTypes.RestartInstanceRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + } + // req.Validate() + res, err := InstanceLogic.RestartInstance(c.logPoints, *req) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instance/modifyInstance instance modifyInstance +// ModifyInstance 修改实例信息 +// Responses: +// 200: modifyInstance +// default: ErrorResponse + +func (c *InstanceController) ModifyInstance() { + defer c.CatchException() + req := &requestTypes.ModifyInstanceRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + } + // req.Validate() + res, err := InstanceLogic.ModifyInstance(c.logPoints, *req) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route DELETE /instance/{instance_id} instance deleteInstance +// DeleteInstance 删除实例 +// Responses: +// 200: deleteInstance +// default: ErrorResponse + +func (c *InstanceController) DeleteInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + + // req.Validate() + res, err := InstanceLogic.DeleteInstance(c.logPoints, instanceId) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instance/lockInstance instance lockInstance +// LockInstance 锁定实例 +// Responses: +// 200: lockInstance +// default: ErrorResponse + +func (c *InstanceController) LockInstance() { + defer c.CatchException() + req := &requestTypes.LockInstanceRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + } + // req.Validate() + res, err := InstanceLogic.LockInstance(c.logPoints, *req) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instance/unlockInstance instance unlockInstance +// UnlockInstance 解锁实例 +// Responses: +// 200: unlockInstance +// default: ErrorResponse + +func (c *InstanceController) UnlockInstance() { + defer c.CatchException() + req := &requestTypes.UnLockInstanceRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + } + // req.Validate() + res, err := InstanceLogic.UnLockInstance(c.logPoints, *req) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instance/startInstances instance startInstances +// StartInstances 批量开机 +// Responses: +// 200: startInstances +// default: ErrorResponse +// StartInstances 批量开机 +func (c *InstanceController) StartInstances() { + defer c.CatchException() + req := &requestTypes.StartInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("StartInstances unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + // req.Validate() + res, err := InstanceLogic.StartInstances(c.logPoints, req.InstanceIDs) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instance/stopInstances instance stopInstances +// StopInstances 批量关机 +// Responses: +// 200: stopInstances +// default: ErrorResponse +func (c *InstanceController) StopInstances() { + defer c.CatchException() + req := &requestTypes.StartInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("StopInstances unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + // req.Validate() + res, err := InstanceLogic.StopInstances(c.logPoints, req.InstanceIDs) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instance/restartInstances instance restartInstances +// RestartInstances 批量重启 +// Responses: +// 200: restartInstances +// default: ErrorResponse +func (c *InstanceController) RestartInstances() { + defer c.CatchException() + req := &requestTypes.StartInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("RestartInstances unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + // req.Validate() + res, err := InstanceLogic.RestartInstances(c.logPoints, req.InstanceIDs) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instance/modifyInstances instance modifyInstances +// ModifyInstances 批量编辑实例名称 +// Responses: +// 200: modifyInstances +// default: ErrorResponse +func (c *InstanceController) ModifyInstances() { + defer c.CatchException() + req := &requestTypes.ModifyInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("ModifyInstancesRequest unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + // req.Validate() + res, err := InstanceLogic.ModifyInstances(c.logPoints, req.InstanceIDs, req.InstanceName) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route DELETE /instance/deleteInstances instance deleteInstances +// DeleteInstances 批量删除实例 +// Responses: +// 200: deleteInstances +// default: ErrorResponse +func (c *InstanceController) DeleteInstances() { + defer c.CatchException() + req := &requestTypes.StartInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("DeleteInstances unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + // req.Validate() + res, err := InstanceLogic.DeleteInstances(c.logPoints, req.InstanceIDs) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instance/resetPasswd instance resetPasswd +// resetPasswd 重置密码 +// Responses: +// 200: resetPasswd +// default: ErrorResponse + +func (c *InstanceController) ResetPasswd() { + defer c.CatchException() + + req := &requestTypes.ResetPasswdRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + // req.Validate() + res, err := InstanceLogic.ResetInstancePassword(c.logPoints, req.InstanceId, req.Password) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instance/batchResetPasswd instance resetInstancesPasswd +// resetInstancesPasswd 批量重置密码 +// Responses: +// 200: resetInstancesPasswd +// default: ErrorResponse + +func (c *InstanceController) ResetInstancesPasswd() { + defer c.CatchException() + + req := &requestTypes.ResetInstancesPasswdRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + // req.Validate() + res, err := InstanceLogic.ResetInstancesPassword(c.logPoints, req.InstanceIds, req.Password) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instance/reinstallInstance instance reinstallInstance +// ReinstallInstance 重装实例 +// Responses: +// 200: reinstallInstance +// default: ErrorResponse + +func (c *InstanceController) ReinstallInstance() { + defer c.CatchException() + + req := &requestTypes.ReinstallInstanceRequest{} + + //fmt.Println(req, req.Hostname) + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + // req.Validate() + res, err := InstanceLogic.ReinstallInstance(c.logPoints, *req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } else { + c.Res.Result = response.CommonResponse{ + Success: res, + } + return + } +} + +// swagger:route GET /instance/forshare/list instance getInstanceListForShare +// GetInstanceListForShare 实例列表 +// Responses: +// 200: getInstanceListForShare +// default: ErrorResponse + +func (c *InstanceController) GetInstanceListForShare() { + defer c.CatchException() + + param := requestTypes.QueryInstancesForShareRequest{ + ProjectID: c.GetString("projectId"), + OwnerName: c.GetString("ownerName"), + SharerName: c.GetString("sharerName"), + //支持如下的模糊搜索 + InstanceName: c.GetString("instanceName"), + InstanceId: c.GetString("instanceId"), + } + res, err := InstanceLogic.DescribeInstancesForShare(c.logPoints, param) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-console-api/controllers/KeypairController.go b/bmp-console-api/controllers/KeypairController.go new file mode 100644 index 0000000..5f0d295 --- /dev/null +++ b/bmp-console-api/controllers/KeypairController.go @@ -0,0 +1,149 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" + + "coding.jd.com/aidc-bmp/bmp-console-api/logic/KeypairLoigc" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" +) + +// DeviceController operations for Device +type KeypairController struct { + BaseController +} + +// swagger:route GET /keypair keypair getKeypairList +// GetKeypairList 获取keypair列表 +// Responses: +// 200: getKeypairList +// default: ErrorResponse + +func (c *KeypairController) GetKeypairList() { + defer c.CatchException() + pg := requestTypes.PagingRequest{ + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + } + req := &requestTypes.QueryKeypairsRequest{ + PagingRequest: pg, + Name: c.GetString("name"), + KeypairIds: c.GetStrings("keypairId"), + } + + res, err := KeypairLoigc.DescribeKeypairs(c.logPoints, *req) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route GET /keypair/{keypair_id} keypair getKeypairInfo +// GetKeypairInfo 获取keypair详情 +// Responses: +// 200: getKeypairInfo +// default: ErrorResponse + +func (c *KeypairController) GetKeypairInfo() { + defer c.CatchException() + keypairID := c.Ctx.Input.Param(":keypair_id") + + res, err := KeypairLoigc.DescribeKeypair(c.logPoints, keypairID) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route PUT /keypair keypair createKeypair +// CreateKeypair 创建keypair +// Responses: +// 200: createKeypair +// default: ErrorResponse + +func (c *KeypairController) CreateKeypair() { + defer c.CatchException() + req := &requestTypes.CreateKeypairRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := KeypairLoigc.CreateKeypairs(c.logPoints, *req) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route PUT /keypair/{keypair_id} keypair modifyKeypair +// ModifyKeypair 修改keypair信息 +// Responses: +// 200: modifyKeypair +// default: ErrorResponse + +func (c *KeypairController) ModifyKeypair() { + defer c.CatchException() + keypairID := c.Ctx.Input.Param(":keypair_id") + req := &requestTypes.ModifyKeypairRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := KeypairLoigc.ModifyKeypair(c.logPoints, keypairID, req.Name) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route DELETE /keypair/{keypair_id} keypair deleteKeypair +// DeleteKeypair 删除keypair +// Responses: +// 200: deleteKeypair +// default: ErrorResponse + +func (c *KeypairController) DeleteKeypair() { + defer c.CatchException() + keypairID := c.Ctx.Input.Param(":keypair_id") + res, err := KeypairLoigc.DeleteKeypairs(c.logPoints, keypairID) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// CheckKeypairName ... +// swagger:route GET /keypair/checkKeypairName keypair checkKeypairName +// CheckKeypairName 查询keypair名称是否已存在 +// Responses: +// 200: checkKeypairName +// default: ErrorResponse + +func (c *KeypairController) CheckKeypairName() { + defer c.CatchException() + req := &requestTypes.QueryKeypairsRequest{ + Name: c.GetString("name"), + } + res, err := KeypairLoigc.DescribeKeypairs(c.logPoints, *req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + result := response.CommonResponse{} + if res.TotalCount == 0 { //如果没有这个秘钥名字,返回false,可以创建 + result.Success = false + } else { + result.Success = true + } + c.Res.Result = result +} diff --git a/bmp-console-api/controllers/MessageController.go b/bmp-console-api/controllers/MessageController.go new file mode 100644 index 0000000..1212630 --- /dev/null +++ b/bmp-console-api/controllers/MessageController.go @@ -0,0 +1,208 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-console-api/logic/messageLogic" + util "coding.jd.com/aidc-bmp/bmp-console-api/util" + + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type MessageController struct { + BaseController +} + +// HasUnreadMessage ... +// swagger:route GET /messages/hasUnreadMessage message hasUnreadMessage +// +// HasUnreadMessage 获取有没有未读消息 +// +// Responses: +// 200: hasUnreadMessage +// default: ErrorResponse + +func (c *MessageController) HasUnreadMessage() { + defer c.CatchException() + + res, err := messageLogic.HasUnreadMessage(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.HasUnreadMessage{ + HasUnread: res, + } +} + +// GetMessageList ... +// swagger:route GET /messages message getMessageList +// +// GetMessageList 获取message列表(分页) +// +// Responses: +// 200: getMessageList +// default: ErrorResponse +func (c *MessageController) GetMessageList() { + defer c.CatchException() + + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + + req := &requestTypes.QueryMessagesRequest{ + IsAll: c.GetString("isAll"), + HasRead: c.GetString("hasRead"), + MessageType: c.GetString("messageType"), + MessageSubType: c.GetString("messageSubType"), + Detail: c.GetString("detail"), + ExportType: c.GetString("exportType"), + } + req.Validate(c.logPoints) + + res, err := messageLogic.GetPageMessages(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if c.GetString("exportType") != "" { + fileName, downloadFileName := messageLogic.ExportMessage(c.logPoints, res.Messages) + //c.Ctx.Input.SetData("download", "yes") + c.Ctx.Output.Download(fileName, downloadFileName) + return + } else { + c.Res.Result = res + } +} + +// GetMessageStatistic ... +// swagger:route GET /messages/statistic message getMessageStatistic +// +// GetMessageStatistic 获取message总数和未读数 +// +// Responses: +// 200: getMessageStatistic +// default: ErrorResponse +func (c *MessageController) GetMessageStatistic() { + defer c.CatchException() + + total, unread, err := messageLogic.GetMessageStatistic(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = response.MessageStatistic{ + + TotalCount: total, + UnreadCount: unread, + } +} + +// ReadMessage ... +// swagger:route PUT /messages/doRead message readMessage +// +// ReadMessage 将消息设置为已读(可多条) +// +// Responses: +// 200: readMessage +// default: ErrorResponse +func (c *MessageController) ReadMessage() { + defer c.CatchException() + + req := &requestTypes.ReadMessagesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ReadMessage parse ReadMessagesRequest body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := messageLogic.ReadMessages(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// GetMessageById ... +// swagger:route GET /messages/getMessageById message getMessageById +// +// GetMessageById 获取消息详情,包括上一条/下一条的messageid +// +// Responses: +// 200: getMessageById +// default: ErrorResponse + +func (c *MessageController) GetMessageById() { + defer c.CatchException() + + req := &requestTypes.GetMessageByIdRequest{ + MessageId: c.GetString("messageId"), + } + req.Validate(c.logPoints) + msg, nextMsgId, prevMsgId, err := messageLogic.GetMessageById(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.MessageWithNextPrev{ + Message: msg, + NextMessageId: nextMsgId, + PrevMessageId: prevMsgId, + } +} + +// GetMessageTypes ... +// swagger:route GET /messages/getMessageTypes message getMessageTypes +// +// GetMessageTypes 获取消息类型/子类型 +// +// Responses: +// 200: getMessageTypes +// default: ErrorResponse + +func (c *MessageController) GetMessageTypes() { + defer c.CatchException() + + res, err := messageLogic.GetMessageTypes(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// DeleteMessage ... +// swagger:route DELETE /messages/delete message deleteMessage +// +// DeleteMessage 删除消息(可多条) +// +// Responses: +// 200: deleteMessage +// default: ErrorResponse +func (c *MessageController) DeleteMessage() { + defer c.CatchException() + + req := &requestTypes.DeleteMessagesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DeleteMessage parse DeleteMessagesRequest body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := messageLogic.DeleteMessages(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} diff --git a/bmp-console-api/controllers/PartitionController.go b/bmp-console-api/controllers/PartitionController.go new file mode 100644 index 0000000..995833f --- /dev/null +++ b/bmp-console-api/controllers/PartitionController.go @@ -0,0 +1,39 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/logic/PartitionLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// PartitionController operations for partition +type PartitionController struct { + BaseController +} + +// swagger:route GET /partition/queryDefaultSystemPartitions keypair queryDefaultSystemPartitions +// QueryDefaultSystemPartitions 根据机型和镜像查系统盘默认分区列表 +// Responses: +// 200: queryDefaultSystemPartitions +// default: ErrorResponse + +func (c *PartitionController) QueryDefaultSystemPartitions() { + defer c.CatchException() + + req := requestTypes.QueryDefaultSystemPartitionRequest{ + ImageID: c.GetString("imageId"), + DeviceTypeID: c.GetString("deviceTypeId"), + } + if err := req.Validate(c.logPoints); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.PARAMETER_ERROR) + return + } + res, err := PartitionLogic.QueryDefaultSystemPartitions(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.PARAMETER_ERROR) + return + } + c.Res.Result = res + +} diff --git a/bmp-console-api/controllers/ProjectController.go b/bmp-console-api/controllers/ProjectController.go new file mode 100644 index 0000000..7267dae --- /dev/null +++ b/bmp-console-api/controllers/ProjectController.go @@ -0,0 +1,268 @@ +package controllers + +import ( + "encoding/json" + + projectLogic "coding.jd.com/aidc-bmp/bmp-console-api/logic/ProjectLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// ProjectController operations for project +type ProjectController struct { + BaseController +} + +// swagger:route PUT /project project createProject +// CreateProject 创建项目 +// Responses: +// 200: createProject +// default: ErrorResponse + +func (c *ProjectController) CreateProject() { + defer c.CatchException() + req := &sdkModels.CreateProjectRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateProject parse pProjectt body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + // req.Validate(c.logPoints) + uuid, err := projectLogic.CreateProject(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = response.ProjectId{ + ProjectId: uuid, + } +} + +// swagger:route GET /project project getProjectList +// GetProjectList 获取项目列表 +// Responses: +// 200: getProjectList +// default: ErrorResponse + +func (c *ProjectController) GetProjectList() { + defer c.CatchException() + req := &requestTypes.QueryProjectsRequest{ + ProjectName: c.GetString("projectName"), + ExportType: c.GetString("exportType"), + IsAll: c.GetString("isAll"), + OrderByCreatetime: c.GetString("orderByCreatetime"), + Owned: c.GetString("owned"), + OwnerName: c.GetString("ownerName"), + SharerName: c.GetString("sharerName"), + PagingRequest: requestTypes.PagingRequest{ + PageNumber: c.getPageNumber(), + PageSize: c.getPageSize(), + }, + } + req.Validate(c.logPoints) + res, err := projectLogic.GetProjectList(c.logPoints, *req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + if c.GetString("exportType") != "" { + fileName, downloadFileName := projectLogic.ExportProject(c.logPoints, res.Projects) + //c.Ctx.Input.SetData("download", "yes") + c.Ctx.Output.Download(fileName, downloadFileName) + return + } else { + c.Res.Result = res + } + +} + +// swagger:route GET /project/{project_id} project getProject +// GetProject 获取项目详情 +// Responses: +// 200: getProject +// default: ErrorResponse + +func (c *ProjectController) GetProject() { + defer c.CatchException() + ProjectId := c.Ctx.Input.Param(":project_id") + res, err := projectLogic.GetProjectById(c.logPoints, ProjectId) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = res +} + +// ModifyProject ... +// swagger:route POST /project/{project_id} project modifyProject +// ModifyProject 修改项目名称 +// Responses: +// 200: modifyProject +// default: ErrorResponse + +func (c *ProjectController) ModifyProject() { + defer c.CatchException() + ProjectId := c.Ctx.Input.Param(":project_id") + req := &sdkModels.ModifyProjectRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyProject parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + // req.Validate(c.logPoints) + if err := projectLogic.ModifyProject(c.logPoints, req, ProjectId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// ModifyProject ... +// swagger:route POST /project/{project_id}/description project modifyProjectDescription +// ModifyProject 修改项目描述 +// Responses: +// 200: modifyProjectDescription +// default: ErrorResponse + +func (c *ProjectController) ModifyProjectDescription() { + defer c.CatchException() + ProjectId := c.Ctx.Input.Param(":project_id") + req := &sdkModels.ModifyProjectDescriptionRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyProject parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + // req.Validate(c.logPoints) + if err := projectLogic.ModifyProjectDescription(c.logPoints, req, ProjectId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// swagger:route DELETE /project/{project_id} project deleteProject +// DeleteProject 删除项目 +// Responses: +// 200: deleteProject +// default: ErrorResponse + +func (c *ProjectController) DeleteProject() { + defer c.CatchException() + ProjectId := c.Ctx.Input.Param(":project_id") + if err := projectLogic.DeleteProject(c.logPoints, ProjectId); err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /project/{project_id}/share project shareProject +// ShareProject 共享项目 +// Responses: +// 200: shareProject +// default: ErrorResponse +func (c *ProjectController) ShareProject() { + defer c.CatchException() + ProjectId := c.Ctx.Input.Param(":project_id") + req := requestTypes.ShareProjectRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.logPoints.Warn("ShareProjectRequest parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + // req.Validate(c.logPoints) + if err := projectLogic.ShareProject(c.logPoints, ProjectId, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /project/{project_id}/cancelShare project cancelshareProject +// CancelShareProject 取消共享项目 +// Responses: +// 200: cancelshareProject +// default: ErrorResponse +func (c *ProjectController) CancelShareProject() { + defer c.CatchException() + ProjectId := c.Ctx.Input.Param(":project_id") + req := requestTypes.ShareProjectRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.logPoints.Warn("CancelShareProject parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + // req.Validate(c.logPoints) + if err := projectLogic.CancelShareProject(c.logPoints, ProjectId, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /project/{project_id}/move project moveProject +// MoveProject 转移项目 +// Responses: +// 200: moveProject +// default: ErrorResponse +func (c *ProjectController) MoveProject() { + defer c.CatchException() + ProjectId := c.Ctx.Input.Param(":project_id") + req := requestTypes.MoveProjectRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.logPoints.Warn("MoveProjectRequest parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + // req.Validate(c.logPoints) + if err := projectLogic.MoveProject(c.logPoints, ProjectId, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /project/move/instances project moveInstances +// +// MoveInstances 转移项目下的某些实例 +// Responses: +// 200: moveInstances +// default: ErrorResponse + +func (c *ProjectController) MoveInstances() { + defer c.CatchException() + + req := &requestTypes.MoveInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("MoveProject parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + // req.Validate(c.logPoints) + if err := projectLogic.MoveInstances(c.logPoints, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} diff --git a/bmp-console-api/controllers/RaidController.go b/bmp-console-api/controllers/RaidController.go new file mode 100644 index 0000000..b73c480 --- /dev/null +++ b/bmp-console-api/controllers/RaidController.go @@ -0,0 +1,40 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/logic/RaidLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// RaidController operations for raid +type RaidController struct { + BaseController +} + +// swagger:route GET /raid/queryRaidsByDeviceTypeIDAndVolumeType raid queryVolumeRaids +// QueryVolumeRaids 根据机型查询系统卷/数据卷和可用raid列表 +// Responses: +// 200: queryVolumeRaids +// default: ErrorResponse + +func (c *RaidController) QueryVolumeRaids() { + defer c.CatchException() + + req := requestTypes.QueryVolumeRaidsRequest{ + DeviceTypeID: c.GetString("deviceTypeId"), + VolumeType: c.GetString("volumeType"), + } + if err := req.Validate(c.logPoints); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.PARAMETER_ERROR) + return + } + raids, err := RaidLogic.QueryVolumesRaids(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.PARAMETER_ERROR) + return + } + + c.Res.Result = raids + return +} diff --git a/bmp-console-api/controllers/TimezoneController.go b/bmp-console-api/controllers/TimezoneController.go new file mode 100644 index 0000000..2f037e0 --- /dev/null +++ b/bmp-console-api/controllers/TimezoneController.go @@ -0,0 +1,25 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/logic/TimezoneLogic" + responseTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/response" +) + +type TimezoneController struct { + BaseController +} + +// swagger:route GET /user/timezones user getTimezoneList +// GetTimezoneList 获取时区列表 +// Responses: +// 200: getTimezoneList +// default: ErrorResponse + +func (c *TimezoneController) GetTimezoneList() { + + res := TimezoneLogic.GetTimeZoneList(c.logPoints) + c.Res.Result = responseTypes.GetTimezoneListResponse{ + TimeZones: res, + } + +} diff --git a/bmp-console-api/controllers/UserController.go b/bmp-console-api/controllers/UserController.go new file mode 100644 index 0000000..7e43103 --- /dev/null +++ b/bmp-console-api/controllers/UserController.go @@ -0,0 +1,216 @@ +package controllers + +import ( + "encoding/json" + "fmt" + + UserLoigc "coding.jd.com/aidc-bmp/bmp-console-api/logic/UserLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +type UserController struct { + BaseController +} + +// Login 登录 +// swagger:route POST /login user login +// Login 登录 +// Responses: +// 200: login +// default: ErrorResponse + +func (c *UserController) Login() { + + // defer c.CatchException() + req := &requestTypes.LoginRequest{} + // req.Validate() + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + _, err := UserLoigc.VerifyUser(c.logPoints, req.Username, req.Password) + + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.HTTP_FORBIDDEN) + return + } + + jdc := c.Ctx.GetCookie(sessionName) + if err := c.SetSession(jdc, req.Username); err != nil { + c.logPoints.Warnf("SetSession error, session_id:%s, username:%s, error:%s", jdc, req.Username, err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.HTTP_FORBIDDEN) + return + } + c.Ctx.Output.Header("X-Jdcloud-Username", req.Username) + c.logPoints.Infof("SetSession success, session_id:%s, username:%s:", jdc, req.Username) + c.Res.Result = responseTypes.CommonResponse{ + Success: true, + } +} + +// Logout 登出 +// swagger:route POST /logout user logout +// Logout 登出 +// Responses: +// 200: logout +// default: ErrorResponse + +func (c *UserController) Logout() { + //username := c.GetString("username") + + // fmt.Println("所有cookie:", c.Ctx.Request.Cookies()) + jdc := c.Ctx.GetCookie(sessionName) + username := c.GetSession(jdc) + + if err := c.DelSession(jdc); err != nil { + c.logPoints.Warnf("del session error, session_id:%s, username:%s, error:%s", jdc, username, err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.HTTP_FORBIDDEN) + return + } + c.logPoints.Infof("del session success, session_id:%s, username:%s", jdc, username) + c.Res.Result = responseTypes.CommonResponse{ + Success: true, + } +} + +// swagger:route GET /user user getUserInfo +//GetUserInfo 获取用户详情 +// Responses: +// 200: getUserInfo +// default: ErrorResponse + +func (c *UserController) GetUserInfo() { + defer c.CatchException() + result, err := UserLoigc.GetUserInfo(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.HTTP_FORBIDDEN) + return + } + c.Res.Result = result +} + +// swagger:route PUT /user/password user updatePassword +// UpdatePassword 修改密码 +// Responses: +// 200: updatePassword +// default: ErrorResponse + +func (c *UserController) UpdatePassword() { + req := &requestTypes.UpdatePasswordRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + userId := c.logPoints.GetPoint("userId").(string) + res, err := UserLoigc.ModifyUserPassword(c.logPoints, userId, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.HTTP_FORBIDDEN) + return + } + //修改完成后登出 + if res { + jdc := c.Ctx.GetCookie(sessionName) + username := c.GetSession(jdc) + + if err := c.DelSession(jdc); err != nil { + c.logPoints.Warnf("UpdatePassword del session error, session_id:%s, username:%s, error:%s", jdc, username, err.Error()) + } else { + c.Ctx.ResponseWriter.WriteHeader(402) + fmt.Fprintln(c.Ctx.ResponseWriter, "请重新登录") + return + } + } + c.Res.Result = responseTypes.CommonResponse{ + Success: res, + } + +} + +// swagger:route PUT /user user updateUserInfo +// UpdateUserInfo 修改个人信息(除密码) +// Responses: +// 200: updateUserInfo +// default: ErrorResponse + +func (c *UserController) UpdateUserInfo() { + userId := c.logPoints.GetPoint("userId").(string) + req := &requestTypes.ModifyUserInfoRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := UserLoigc.ModifyUserInfo(c.logPoints, userId, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.HTTP_FORBIDDEN) + return + } + c.Res.Result = responseTypes.CommonResponse{ + Success: res, + } + +} + +// swagger:route GET /user/getConsoleAccessUserList user getConsoleAccessUserList +// GetConsoleAccessUserList 获取有控制台权限的用户列表 +// Responses: +// 200: getConsoleAccessUserList +// default: ErrorResponse +func (c *UserController) GetConsoleAccessUserList() { + userId := c.logPoints.GetPoint("userId").(string) + + res, err := UserLoigc.GetConsoleAccessUserList(c.logPoints, userId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.HTTP_FORBIDDEN) + return + } + c.Res.Result = res + +} + +// swagger:route GET /user/checkUserConsoleAccess user checkUserConsoleAccess +// CheckUserConsoleAccess 校验被转移的用户有没有控制台权限 +// Responses: +// 200: checkUserConsoleAccess +// default: ErrorResponse +func (c *UserController) CheckUserConsoleAccess() { + + userId := c.logPoints.GetPoint("userId").(string) + req := requestTypes.CheckUserConsoleAccessRequest{ + CheckedUserId: c.GetString("checkedUserId"), + } + res, err := UserLoigc.CheckUserConsoleAccess(c.logPoints, userId, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.HTTP_FORBIDDEN) + return + } + c.Res.Result = responseTypes.CommonResponse{ + Success: res, + } +} + +// swagger:route GET /user/checkUserConsoleAccessByName user checkUserConsoleAccessByName +// CheckUserConsoleAccess 按用户名校验被转移的用户有没有控制台权限 +// Responses: +// 200: checkUserConsoleAccessByName +// default: ErrorResponse +func (c *UserController) CheckUserConsoleAccessByName() { + + userId := c.logPoints.GetPoint("userId").(string) + req := requestTypes.CheckUserConsoleAccessByNameRequest{ + CheckedUserName: c.GetString("checkedUserName"), + ProjectID: c.GetString("projectId"), + Operation: c.GetString("operation"), + } + res, err := UserLoigc.CheckUserConsoleAccessByName(c.logPoints, userId, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.HTTP_FORBIDDEN) + return + } + c.Res.Result = responseTypes.CommonResponse{ + Success: res, + } +} diff --git a/bmp-console-api/controllers/WebSocketController.go b/bmp-console-api/controllers/WebSocketController.go new file mode 100644 index 0000000..ba0e8d1 --- /dev/null +++ b/bmp-console-api/controllers/WebSocketController.go @@ -0,0 +1,104 @@ +package controllers + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "time" + + "coding.jd.com/aidc-bmp/bmp-console-api/logic/WebsocketLogic" + response "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + "github.com/gorilla/websocket" +) + +// WebSocketController operations for Msg +type WebSocketController struct { + BaseController +} + +func (wsc *WebSocketController) Send() { + userId := wsc.logPoints.GetPoint("userId").(string) + err := WebsocketLogic.SendMsg2Client(wsc.logPoints, []string{userId}, WebsocketLogic.NofifyMessage{ + Type: "test", + SubType: "sendTestSocketmsg", + Message: "test text", + }) + success := true + if err != nil { + success = false + } + + wsc.Res.Result = response.CommonResponse{ + Success: success, + } + +} + +func (wsc *WebSocketController) Get() { + + var upgrader = websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 1024, + // 解决跨域问题 + CheckOrigin: func(r *http.Request) bool { + return true + }, + } + + ws, err := upgrader.Upgrade(wsc.Ctx.ResponseWriter, wsc.Ctx.Request, nil) + if err != nil { + log.Fatal(err) + } + + ConnId := wsc.logPoints.GetPoint("logid").(string) + c := &WebsocketLogic.Client{ + ID: ConnId, // 连接id + UserId: wsc.logPoints.GetPoint("userId").(string), + HeartbeatTime: time.Now().Unix(), + Socket: ws, + } + + // defer ws.Close() + WebsocketLogic.RegisterChan <- c + + defer func() { + WebsocketLogic.UnregisterChan <- c + }() + for { + // 读取消息 + _, body, err := c.Socket.ReadMessage() + if err != nil { + wsc.logPoints.Warnf("c.Socket.ReadMessage error:%s", err.Error()) + break + } + + fmt.Println("message from client:", string(body)) + + msg := WebsocketLogic.ReceiveMessage{} + err = json.Unmarshal(body, &msg) + if err != nil { + wsc.logPoints.Warnf("unmarshal error:%s", err.Error()) + continue + } + + if msg.Type == WebsocketLogic.MessageTypeHeartbeatFromClient { // 维持心跳消息 + // 刷新连接时间 + c.HeartbeatTime = time.Now().Unix() + + // 回复心跳 + replyMsg := WebsocketLogic.NofifyMessage{ + Type: WebsocketLogic.MessageTypeHeartbeatFromServer, + } + err = c.Socket.WriteJSON(replyMsg) + if err != nil { + fmt.Println("c.Socket.WriteJSON error:", err.Error()) + wsc.logPoints.Warnf("c.Socket.WriteJSON error:%s", err.Error()) + } + // + } else { + //目前nothing + } + } + +} diff --git a/bmp-console-api/controllers/auditLogsController.go b/bmp-console-api/controllers/auditLogsController.go new file mode 100644 index 0000000..3cca941 --- /dev/null +++ b/bmp-console-api/controllers/auditLogsController.go @@ -0,0 +1,67 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/logic/AuditLogLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// AuditLogsController operations for auditlog +type AuditLogsController struct { + BaseController +} + +// swagger:route GET /auditLogs auditLog describeAuditLogs +// DescribeAuditLogs 获取审计日志列表 +// Responses: +// 200: describeAuditLogs +// default: ErrorResponse + +func (c *AuditLogsController) DescribeAuditLogs() { + defer c.CatchException() + + p := requestTypes.PagingRequest{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.DescribeAuditLogsRequest{ + PagingRequest: p, + InstanceID: c.GetString("instanceId"), + Operation: c.GetString("operation"), + UserName: c.GetString("userName"), + Result: c.GetString("result"), + IsAll: c.GetString("isAll"), + } + st, _ := c.GetInt64("startTime") + et, _ := c.GetInt64("endTime") + req.StartTime = st + req.EndTime = et + + //device_types, err := deviceTypeLogic.QueryByRequest(c.logPoints, req) + res, err := AuditLogLogic.QueryAuditLogs(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if c.GetString("exportType") != "" { + fileName, downloadFileName := AuditLogLogic.ExportAuditLogs(c.logPoints, res.AuditLogs) + //c.Ctx.Input.SetData("download", "yes") + c.Ctx.Output.Download(fileName, downloadFileName) + return + } else { + c.Res.Result = res + } + +} + +func (c *AuditLogsController) DescribeAuditLogTypes() { + + //device_types, err := deviceTypeLogic.QueryByRequest(c.logPoints, req) + res, err := AuditLogLogic.DescribeAuditLogsTypes(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-console-api/controllers/monitorAlertController.go b/bmp-console-api/controllers/monitorAlertController.go new file mode 100644 index 0000000..8976ac2 --- /dev/null +++ b/bmp-console-api/controllers/monitorAlertController.go @@ -0,0 +1,111 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-console-api/logic/monitorAlertLogic" + "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + response "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + util "coding.jd.com/aidc-bmp/bmp-console-api/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorAlertController 告警规则 +type MonitorAlertController struct { + BaseController +} + +// swagger:route GET /monitorAlert/describeAlert monitorAlert describeAlert +// +// DescribeAlert 告警详情 +// +// Responses: +// 200: describeAlert +// default: ErrorResponse +func (c *MonitorAlertController) DescribeAlert() { + defer c.CatchException() + req := request.DescribeAlertRequest{ + AlertID: c.GetString("AlertId"), + } + req.Validate(c.logPoints) + res, err := monitorAlertLogic.DescribeAlert(c.logPoints, req.AlertID) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route GET /monitorAlert/describeAlerts monitorAlert describeAlerts +// +// DescribeAlerts 告警列表 +// +// Responses: +// 200: describeAlerts +// default: ErrorResponse +func (c *MonitorAlertController) DescribeAlerts() { + defer c.CatchException() + + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + stime, _ := c.GetInt64("startTime") + etime, _ := c.GetInt64("endTime") + + req := &request.DescribeAlertsRequest{ + IsAll: c.GetString("isAll"), + UserName: c.GetString("userName"), + UserID: c.GetString("userId"), + RuleName: c.GetString("ruleName"), + RuleID: c.GetString("ruleId"), + ResourceID: c.GetString("resourceId"), + StartTime: stime, + EndTime: etime, + ProjectID: c.GetString("projectId"), + } + req.Validate(c.logPoints) + + res, err := monitorAlertLogic.DescribeAlerts(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if c.GetString("exportType") != "" { + fileName, downloadFileName := monitorAlertLogic.ExportAlerts(c.logPoints, res.Alerts) + //c.Ctx.Input.SetData("download", "yes") + c.Ctx.Output.Download(fileName, downloadFileName) + return + } else { + c.Res.Result = res + } +} + +// swagger:route DELETE /monitorAlert/deleteAlert monitorAlert deleteAlert +// +// DeleteAlert 删除告警 +// +// Responses: +// 200: deleteAlert +// default: ErrorResponse +func (c *MonitorAlertController) DeleteAlert() { + defer c.CatchException() + c.logPoints.Infof("EnableAlert body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.DeleteAlertRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DeleteAlert parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorAlertLogic.DeleteAlert(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} diff --git a/bmp-console-api/controllers/monitorDataController.go b/bmp-console-api/controllers/monitorDataController.go new file mode 100644 index 0000000..47379d5 --- /dev/null +++ b/bmp-console-api/controllers/monitorDataController.go @@ -0,0 +1,46 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/logic/monitorDataLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorDataController 读取监控数据 +type MonitorDataController struct { + BaseController +} + +// swagger:route GET /monitorData monitorData getMonitorData +// +// GetMonitorData 获取图表监控数据 +// +// Responses: +// 200: getMonitorData +// default: ErrorResponse +func (c *MonitorDataController) GetMonitorData() { + + stime, _ := c.GetInt64("startTime") + etime, _ := c.GetInt64("endTime") + ti, _ := c.GetInt64("timeInterval") + lastManyTime, _ := c.GetInt64("lastManyTime") + req := requestTypes.GetMonitorDataRequest{ + MetricName: c.GetString("metricName"), + InstanceID: c.GetString("instanceId"), + Device: c.GetString("device"), + StartTime: stime, + EndTime: etime, + TimeInterval: ti, + LastManyTime: lastManyTime, + DownSampleType: c.GetString("downSampleType"), + } + + res, err := monitorDataLogic.GetMonitorData(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res + +} diff --git a/bmp-console-api/controllers/monitorProxyController.go b/bmp-console-api/controllers/monitorProxyController.go new file mode 100644 index 0000000..2dc07f1 --- /dev/null +++ b/bmp-console-api/controllers/monitorProxyController.go @@ -0,0 +1,55 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/logic/monitorProxyLogic" + "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorProxyController 从monitorproxy服务读取数据,包括agent状态,tag列表等 +type MonitorProxyController struct { + BaseController +} + +// swagger:route GET /monitorProxy/desrcibeAgentStatus monitorProxy desrcibeAgentStatus +// +// DesrcibeAgentStatus 获取agent状态 +// +// Responses: +// 200: desrcibeAgentStatus +// default: ErrorResponse +func (c *MonitorProxyController) DesrcibeAgentStatus() { + req := &request.DesrcibeAgentStatusRequest{ + InstanceId: c.GetString("instanceId"), + } + req.Validate(c.logPoints) + res, err := monitorProxyLogic.DescribeAgentStatus(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res + +} + +// swagger:route GET /monitorProxy/desrcibeTags monitorProxy desrcibeTags +// +// DesrcibeAgentStatus 获取tag列表 +// +// Responses: +// 200: desrcibeTags +// default: ErrorResponse +func (c *MonitorProxyController) DesrcibeTags() { + req := &request.DesrcibeTagsRequest{ + InstanceID: c.GetString("instanceId"), + TagName: c.GetString("tagName"), + } + req.Validate(c.logPoints) + res, err := monitorProxyLogic.DescribeDeviceTags(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-console-api/controllers/monitorRuleController.go b/bmp-console-api/controllers/monitorRuleController.go new file mode 100644 index 0000000..77f6830 --- /dev/null +++ b/bmp-console-api/controllers/monitorRuleController.go @@ -0,0 +1,219 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-console-api/logic/monitorRuleLogic" + "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorRuleController 告警规则 +type MonitorRuleController struct { + BaseController +} + +// swagger:route POST /monitorRule/addRule monitorRule addRule +// +// AddRule 添加规则 +// +// Responses: +// 200: addRule +// default: ErrorResponse +func (c *MonitorRuleController) AddRule() { + defer c.CatchException() + c.logPoints.Infof("AddRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.AddRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("AddRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.AddRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route GET /monitorRule/describeRule monitorRule describeRule +// +// DescribeRule 规则详情 +// +// Responses: +// 200: describeRule +// default: ErrorResponse +func (c *MonitorRuleController) DescribeRule() { + defer c.CatchException() + req := request.DescribeRuleRequest{ + RuleID: c.GetString("ruleId"), + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.DescribeRule(c.logPoints, req.RuleID) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route GET /monitorRule/describeRules monitorRule describeRules +// +// DescribeRules 规则列表 +// +// Responses: +// 200: describeRules +// default: ErrorResponse +func (c *MonitorRuleController) DescribeRules() { + defer c.CatchException() + + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + s, _ := c.GetInt("status") + req := &request.DescribeRulesRequest{ + IsAll: c.GetString("isAll"), + UserName: c.GetString("userName"), + UserId: c.GetString("userId"), + RuleName: c.GetString("ruleName"), + RuleId: c.GetString("ruleId"), + Status: s, + ProjectID: c.GetString("projectId"), + } + req.Validate(c.logPoints) + + res, err := monitorRuleLogic.DescribeRules(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if c.GetString("exportType") != "" { + fileName, downloadFileName := monitorRuleLogic.ExportRules(c.logPoints, res.Rules) + //c.Ctx.Input.SetData("download", "yes") + c.Ctx.Output.Download(fileName, downloadFileName) + return + } else { + c.Res.Result = res + } +} + +// swagger:route PUT /monitorRule/editRule monitorRule editRule +// +// EditRule 编辑规则 +// +// Responses: +// 200: editRule +// default: ErrorResponse +func (c *MonitorRuleController) EditRule() { + defer c.CatchException() + c.logPoints.Infof("EditRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.EditRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("EditRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.EditRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route PUT /monitorRule/enableRule monitorRule enableRule +// +// EnableRule 启用规则 +// +// Responses: +// 200: enableRule +// default: ErrorResponse +func (c *MonitorRuleController) EnableRule() { + defer c.CatchException() + c.logPoints.Infof("EnableRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.EnableRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("EnableRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.EnableRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route PUT /monitorRule/disableRule monitorRule disableRule +// +// DisableRule 禁用规则 +// +// Responses: +// 200: disableRule +// default: ErrorResponse +func (c *MonitorRuleController) DisableRule() { + defer c.CatchException() + c.logPoints.Infof("DisableRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.DisableRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DisableRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.DisableRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route DELETE /monitorRule/deleteRule monitorRule deleteRule +// +// DeleteRule 删除规则 +// +// Responses: +// 200: deleteRule +// default: ErrorResponse +func (c *MonitorRuleController) DeleteRule() { + defer c.CatchException() + c.logPoints.Infof("EnableRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.DeleteRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DeleteRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.DeleteRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} diff --git a/bmp-console-api/errors/code.go b/bmp-console-api/errors/code.go new file mode 100644 index 0000000..046cf23 --- /dev/null +++ b/bmp-console-api/errors/code.go @@ -0,0 +1,107 @@ +package errors + +const ( + API_OK = 10000 + API_ARGUMENTS_ERROR = 20040 + API_NO_ARGUMENTS = 20041 + API_DB_ERROR = 20050 + API_UNKOWN_ERROR = 20051 + API_INTERNAL_ERROR = 20052 + API_CALL_SERVICE_ERROR = 20053 + API_RESOURCE_NOT_FOUND = 20060 + API_RESOURCE_HAS_EXISTED = 20061 + API_RESOURCE_OCCUPIED = 20062 + API_RESOURCE_OUT_OF_RANGE = 20063 + API_RESOURCE_NOT_MATCH = 20064 + API_LOGIN_ERROR = 20065 + API_UPLOAD_FILE_ERROR = 20066 + API_RESOURCE_UNAVAILABLE = 20067 +) + +type codeMsg struct { + HttpCode int + Message string +} + +var CodeMap = make(map[int]*codeMsg) + +func init() { + CodeMap = map[int]*codeMsg{ + API_OK: { + 200, + "OK", + }, + API_ARGUMENTS_ERROR: { + 400, + "参数错误", + }, + API_NO_ARGUMENTS: { + 400, + "参数缺失", + }, + API_DB_ERROR: { + 500, + "数据库错误", + }, + API_UNKOWN_ERROR: { + 500, + "未知错误", + }, + API_INTERNAL_ERROR: { + 500, + "内部错误", + }, + API_CALL_SERVICE_ERROR: { + 500, + "调用外部服务错误", + }, + API_RESOURCE_NOT_FOUND: { + 400, + "资源未找到", + }, + API_RESOURCE_HAS_EXISTED: { + 400, + "资源已存在", + }, + API_RESOURCE_OCCUPIED: { + 400, + "资源已被占用", + }, + API_RESOURCE_OUT_OF_RANGE: { + 400, + "资源数量超出限制", + }, + API_RESOURCE_NOT_MATCH: { + 400, + "资源不匹配", + }, + API_LOGIN_ERROR: { + 401, + "请先进行单点登录", + }, + API_UPLOAD_FILE_ERROR: { + 400, + "上传文件有误", + }, + API_RESOURCE_UNAVAILABLE: { + 400, + "资源不可用", + }, + } +} + +func GetCodeMsg(errCode int) string { + if msg, ok := CodeMap[errCode]; ok { + return msg.Message + } else { + return CodeMap[API_UNKOWN_ERROR].Message + } +} + +func GetHttpCode(errCode int) int { + if msg, ok := CodeMap[errCode]; ok { + return msg.HttpCode + } else { + return CodeMap[API_UNKOWN_ERROR].HttpCode + } +} diff --git a/bmp-console-api/errors/errors.go b/bmp-console-api/errors/errors.go new file mode 100644 index 0000000..0269e41 --- /dev/null +++ b/bmp-console-api/errors/errors.go @@ -0,0 +1,49 @@ +package errors + +import "fmt" + +type Error interface { + error + GetErrorCode() int + GetMessage() string + GetOriginError() error +} + +type CommonError struct { + errorCode int + message string + originError error +} + +func NewCommonError(errorCode int, message string, originErr error) Error { + return &CommonError{ + errorCode: errorCode, + message: message, + originError: originErr, + } +} + +func (e *CommonError) Error() string { + var msg string + if e.GetMessage() == "" { + msg = fmt.Sprintf("%s", GetCodeMsg(e.GetErrorCode())) + } else { + msg = fmt.Sprintf("%s:%s", GetCodeMsg(e.GetErrorCode()), e.GetMessage()) + } + if e.GetOriginError() != nil { + return msg + " caused by: " + e.GetOriginError().Error() + } + return msg +} + +func (e *CommonError) GetErrorCode() int { + return e.errorCode +} + +func (e *CommonError) GetOriginError() error { + return e.originError +} + +func (e *CommonError) GetMessage() string { + return e.message +} diff --git a/bmp-console-api/go.mod b/bmp-console-api/go.mod new file mode 100644 index 0000000..880a001 --- /dev/null +++ b/bmp-console-api/go.mod @@ -0,0 +1,78 @@ +module coding.jd.com/aidc-bmp/bmp-console-api + +go 1.17 + +require github.com/beego/beego/v2 v2.0.1 + +require ( + coding.jd.com/aidc-bmp/bmp-openapi-console-sdk v0.0.0-00010101000000-000000000000 + coding.jd.com/aidc-bmp/bmp_log v0.0.0-00010101000000-000000000000 + github.com/gorilla/websocket v1.5.1 +) + +require ( + github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.1.1 // indirect + github.com/go-logr/logr v1.2.3 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-openapi/analysis v0.21.4 // indirect + github.com/go-openapi/errors v0.20.4 // indirect + github.com/go-openapi/jsonpointer v0.19.5 // indirect + github.com/go-openapi/jsonreference v0.20.0 // indirect + github.com/go-openapi/loads v0.21.2 // indirect + github.com/go-openapi/spec v0.20.8 // indirect + github.com/go-openapi/swag v0.22.4 // indirect + github.com/go-openapi/validate v0.22.1 // indirect + github.com/go-playground/locales v0.13.0 // indirect + github.com/go-playground/universal-translator v0.17.0 // indirect + github.com/go-redis/redis/v7 v7.4.0 // indirect + github.com/golang/protobuf v1.4.2 // indirect + github.com/hashicorp/golang-lru v0.5.4 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/leodido/go-urn v1.2.0 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect + github.com/oklog/ulid v1.3.1 // indirect + github.com/opentracing/opentracing-go v1.2.0 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/prometheus/client_golang v1.7.0 // indirect + github.com/prometheus/client_model v0.2.0 // indirect + github.com/prometheus/common v0.10.0 // indirect + github.com/prometheus/procfs v0.1.3 // indirect + github.com/richardlehane/mscfb v1.0.3 // indirect + github.com/richardlehane/msoleps v1.0.1 // indirect + github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect + github.com/xuri/efp v0.0.0-20210322160811-ab561f5b45e3 // indirect + go.mongodb.org/mongo-driver v1.11.3 // indirect + go.opentelemetry.io/otel v1.14.0 // indirect + go.opentelemetry.io/otel/trace v1.14.0 // indirect + golang.org/x/mod v0.8.0 // indirect + golang.org/x/sys v0.13.0 // indirect + golang.org/x/text v0.13.0 // indirect + google.golang.org/protobuf v1.23.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) + +require ( + git.jd.com/cps-golang/ironic-common v0.0.0-00010101000000-000000000000 + github.com/go-openapi/runtime v0.26.0 + github.com/go-openapi/strfmt v0.21.7 + github.com/go-playground/validator/v10 v10.4.1 + github.com/go-redis/redis v6.14.2+incompatible + github.com/go-sql-driver/mysql v1.5.0 + github.com/gofrs/uuid v4.2.0+incompatible + github.com/xuri/excelize/v2 v2.5.0 + golang.org/x/crypto v0.14.0 + golang.org/x/net v0.17.0 // indirect + golang.org/x/tools v0.6.0 // indirect +) + +replace coding.jd.com/aidc-bmp/bmp_log => ./bmp_vendor/bmp_log + +replace git.jd.com/cps-golang/ironic-common => ./bmp_vendor/ironic-common + +replace coding.jd.com/aidc-bmp/bmp-openapi-console-sdk => ./bmp_vendor/bmp-openapi-console-sdk diff --git a/bmp-console-api/go.sum b/bmp-console-api/go.sum new file mode 100644 index 0000000..a713d75 --- /dev/null +++ b/bmp-console-api/go.sum @@ -0,0 +1,467 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= +github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk= +github.com/asaskevich/govalidator v0.0.0-20200907205600-7a23bdc65eef/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= +github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/beego/beego/v2 v2.0.1 h1:07a7Z0Ok5vbqyqh+q53sDPl9LdhKh0ZDy3gbyGrhFnE= +github.com/beego/beego/v2 v2.0.1/go.mod h1:8zyHi1FnWO1mZLwTn62aKRIZF/aIKvkCBB2JYs+eqQI= +github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ= +github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60= +github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= +github.com/coreos/etcd v3.3.25+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U= +github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= +github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= +github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk= +github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0= +github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-openapi/analysis v0.21.2/go.mod h1:HZwRk4RRisyG8vx2Oe6aqeSQcoxRp47Xkp3+K6q+LdY= +github.com/go-openapi/analysis v0.21.4 h1:ZDFLvSNxpDaomuCueM0BlSXxpANBlFYiBvr+GXrvIHc= +github.com/go-openapi/analysis v0.21.4/go.mod h1:4zQ35W4neeZTqh3ol0rv/O8JBbka9QyAgQRPp9y3pfo= +github.com/go-openapi/errors v0.19.8/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= +github.com/go-openapi/errors v0.19.9/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= +github.com/go-openapi/errors v0.20.2/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= +github.com/go-openapi/errors v0.20.4 h1:unTcVm6PispJsMECE3zWgvG4xTiKda1LIR5rCRWLG6M= +github.com/go-openapi/errors v0.20.4/go.mod h1:Z3FlZ4I8jEGxjUK+bugx3on2mIAk4txuAOhlsB1FSgk= +github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= +github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= +github.com/go-openapi/jsonreference v0.20.0 h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA= +github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo= +github.com/go-openapi/loads v0.21.1/go.mod h1:/DtAMXXneXFjbQMGEtbamCZb+4x7eGwkvZCvBmwUG+g= +github.com/go-openapi/loads v0.21.2 h1:r2a/xFIYeZ4Qd2TnGpWDIQNcP80dIaZgf704za8enro= +github.com/go-openapi/loads v0.21.2/go.mod h1:Jq58Os6SSGz0rzh62ptiu8Z31I+OTHqmULx5e/gJbNw= +github.com/go-openapi/runtime v0.26.0 h1:HYOFtG00FM1UvqrcxbEJg/SwvDRvYLQKGhw2zaQjTcc= +github.com/go-openapi/runtime v0.26.0/go.mod h1:QgRGeZwrUcSHdeh4Ka9Glvo0ug1LC5WyE+EV88plZrQ= +github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= +github.com/go-openapi/spec v0.20.6/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= +github.com/go-openapi/spec v0.20.8 h1:ubHmXNY3FCIOinT8RNrrPfGc9t7I1qhPtdOGoG2AxRU= +github.com/go-openapi/spec v0.20.8/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= +github.com/go-openapi/strfmt v0.21.0/go.mod h1:ZRQ409bWMj+SOgXofQAGTIo2Ebu72Gs+WaRADcS5iNg= +github.com/go-openapi/strfmt v0.21.1/go.mod h1:I/XVKeLc5+MM5oPNN7P6urMOpuLXEcNrCX/rPGuWb0k= +github.com/go-openapi/strfmt v0.21.3/go.mod h1:k+RzNO0Da+k3FrrynSNN8F7n/peCmQQqbbXjtDfvmGg= +github.com/go-openapi/strfmt v0.21.7 h1:rspiXgNWgeUzhjo1YU01do6qsahtJNByjLVbPLNHb8k= +github.com/go-openapi/strfmt v0.21.7/go.mod h1:adeGTkxE44sPyLk0JV235VQAO/ZXUr8KAzYjclFs3ew= +github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= +github.com/go-openapi/swag v0.21.1/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= +github.com/go-openapi/swag v0.22.4 h1:QLMzNJnMGPRNDCbySlcj1x01tzU8/9LTTL9hZZZogBU= +github.com/go-openapi/swag v0.22.4/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= +github.com/go-openapi/validate v0.22.1 h1:G+c2ub6q47kfX1sOBLwIQwzBVt8qmOAARyo/9Fqs9NU= +github.com/go-openapi/validate v0.22.1/go.mod h1:rjnrwK57VJ7A8xqfpAOEKRH8yQSGUriMu5/zuPSQ1hg= +github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= +github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= +github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= +github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= +github.com/go-redis/redis v6.14.2+incompatible h1:UE9pLhzmWf+xHNmZsoccjXosPicuiNaInPgym8nzfg0= +github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis/v7 v7.4.0 h1:7obg6wUoj05T0EpY0o8B59S9w5yeMWql7sw2kwNW1x4= +github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= +github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gobuffalo/attrs v0.0.0-20190224210810-a9411de4debd/go.mod h1:4duuawTqi2wkkpB4ePgWMaai6/Kc6WEz83bhFwpHzj0= +github.com/gobuffalo/depgen v0.0.0-20190329151759-d478694a28d3/go.mod h1:3STtPUQYuzV0gBVOY3vy6CfMm/ljR4pABfrTeHNLHUY= +github.com/gobuffalo/depgen v0.1.0/go.mod h1:+ifsuy7fhi15RWncXQQKjWS9JPkdah5sZvtHc2RXGlg= +github.com/gobuffalo/envy v1.6.15/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI= +github.com/gobuffalo/envy v1.7.0/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI= +github.com/gobuffalo/flect v0.1.0/go.mod h1:d2ehjJqGOH/Kjqcoz+F7jHTBbmDb38yXA598Hb50EGs= +github.com/gobuffalo/flect v0.1.1/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI= +github.com/gobuffalo/flect v0.1.3/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI= +github.com/gobuffalo/genny v0.0.0-20190329151137-27723ad26ef9/go.mod h1:rWs4Z12d1Zbf19rlsn0nurr75KqhYp52EAGGxTbBhNk= +github.com/gobuffalo/genny v0.0.0-20190403191548-3ca520ef0d9e/go.mod h1:80lIj3kVJWwOrXWWMRzzdhW3DsrdjILVil/SFKBzF28= +github.com/gobuffalo/genny v0.1.0/go.mod h1:XidbUqzak3lHdS//TPu2OgiFB+51Ur5f7CSnXZ/JDvo= +github.com/gobuffalo/genny v0.1.1/go.mod h1:5TExbEyY48pfunL4QSXxlDOmdsD44RRq4mVZ0Ex28Xk= +github.com/gobuffalo/gitgen v0.0.0-20190315122116-cc086187d211/go.mod h1:vEHJk/E9DmhejeLeNt7UVvlSGv3ziL+djtTr3yyzcOw= +github.com/gobuffalo/gogen v0.0.0-20190315121717-8f38393713f5/go.mod h1:V9QVDIxsgKNZs6L2IYiGR8datgMhB577vzTDqypH360= +github.com/gobuffalo/gogen v0.1.0/go.mod h1:8NTelM5qd8RZ15VjQTFkAW6qOMx5wBbW4dSCS3BY8gg= +github.com/gobuffalo/gogen v0.1.1/go.mod h1:y8iBtmHmGc4qa3urIyo1shvOD8JftTtfcKi+71xfDNE= +github.com/gobuffalo/logger v0.0.0-20190315122211-86e12af44bc2/go.mod h1:QdxcLw541hSGtBnhUc4gaNIXRjiDppFGaDqzbrBd3v8= +github.com/gobuffalo/mapi v1.0.1/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc= +github.com/gobuffalo/mapi v1.0.2/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc= +github.com/gobuffalo/packd v0.0.0-20190315124812-a385830c7fc0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4= +github.com/gobuffalo/packd v0.1.0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4= +github.com/gobuffalo/packr/v2 v2.0.9/go.mod h1:emmyGweYTm6Kdper+iywB6YK5YzuKchGtJQZ0Odn4pQ= +github.com/gobuffalo/packr/v2 v2.2.0/go.mod h1:CaAwI0GPIAv+5wKLtv8Afwl+Cm78K/I/VCm/3ptBN+0= +github.com/gobuffalo/syncx v0.0.0-20190224160051-33c29581e754/go.mod h1:HhnNqWY95UYwwW3uSASeV7vtgYkT2t16hJgV3AEPUpw= +github.com/gofrs/uuid v4.2.0+incompatible h1:yyYWMnhkhrKwwr8gAOcOCYxOOscHgDS9yZgBrnJfGa0= +github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY= +github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/karrick/godirwalk v1.8.0/go.mod h1:H5KPZjojv4lE+QYImBI8xVtrBRgYrIVsaRPx4tDPEn4= +github.com/karrick/godirwalk v1.10.3/go.mod h1:RoGL9dQei4vP9ilrpETWE8CLOZ1kiN0LhBygSwrAsHA= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDuKuq+uX4v1fulaMbA/7ZLLhjc85h7chZGBCQ= +github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= +github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/markbates/oncer v0.0.0-20181203154359-bf2de49a0be2/go.mod h1:Ld9puTsIW75CHf65OeIOkyKbteujpZVXDpWK6YGZbxE= +github.com/markbates/safe v1.0.1/go.mod h1:nAqgmRi7cY2nqMc92/bSEeQA+R4OheNU2T1kNSCBdG0= +github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= +github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= +github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.0 h1:Iw5WCbBcaAAd0fpRb1c9r5YCylv4XDoCSigm1zLevwU= +github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.7.0/go.mod h1:vwGMzjaWMwyfHwgIBhI2YUM4fB6nL6lVAvS1LBMMhTE= +github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= +github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.7.0 h1:wCi7urQOGBsYcQROHqpUUX4ct84xp40t9R9JX0FuA/U= +github.com/prometheus/client_golang v1.7.0/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.10.0 h1:RyRA7RzGXQZiW+tGMr7sxa85G1z0yOpM1qq5c8lNawc= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.1.3 h1:F0+tqvhOksq22sc6iCHF5WGlWjdwj92p0udFh1VFBS8= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/richardlehane/mscfb v1.0.3 h1:rD8TBkYWkObWO0oLDFCbwMeZ4KoalxQy+QgniCj3nKI= +github.com/richardlehane/mscfb v1.0.3/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk= +github.com/richardlehane/msoleps v1.0.1 h1:RfrALnSNXzmXLbGct/P2b4xkFz4e8Gmj/0Vj9M9xC1o= +github.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg= +github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= +github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= +github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s= +github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= +github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= +github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= +github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= +github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs= +github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g= +github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM= +github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8= +github.com/xuri/efp v0.0.0-20210322160811-ab561f5b45e3 h1:EpI0bqf/eX9SdZDwlMmahKM+CDBgNbsXMhsN28XrM8o= +github.com/xuri/efp v0.0.0-20210322160811-ab561f5b45e3/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI= +github.com/xuri/excelize/v2 v2.5.0 h1:nDDVfX0qaDuGjAvb+5zTd0Bxxoqa1Ffv9B4kiE23PTM= +github.com/xuri/excelize/v2 v2.5.0/go.mod h1:rSu0C3papjzxQA3sdK8cU544TebhrPUoTOaGPIh0Q1A= +github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= +go.etcd.io/etcd v3.3.25+incompatible/go.mod h1:yaeTdrJi5lOmYerz05bd8+V7KubZs8YSFZfzsF9A6aI= +go.mongodb.org/mongo-driver v1.7.3/go.mod h1:NqaYOwnXWr5Pm7AOpO5QFxKJ503nbMse/R79oO62zWg= +go.mongodb.org/mongo-driver v1.7.5/go.mod h1:VXEWRZ6URJIkUq2SCAyapmhH0ZLRBP+FT4xhp5Zvxng= +go.mongodb.org/mongo-driver v1.10.0/go.mod h1:wsihk0Kdgv8Kqu1Anit4sfK+22vSFbUrAVEYRhCXrA8= +go.mongodb.org/mongo-driver v1.11.3 h1:Ql6K6qYHEzB6xvu4+AU0BoRoqf9vFPcc4o7MUIdPW8Y= +go.mongodb.org/mongo-driver v1.11.3/go.mod h1:PTSz5yu21bkT/wXpkS7WR5f0ddqw5quethTUn9WM+2g= +go.opentelemetry.io/otel v1.14.0 h1:/79Huy8wbf5DnIPhemGB+zEPVwnN6fuQybr/SRXa6hM= +go.opentelemetry.io/otel v1.14.0/go.mod h1:o4buv+dJzx8rohcUeRmWUZhqupFvzWis188WlggnNeU= +go.opentelemetry.io/otel/sdk v1.14.0 h1:PDCppFRDq8A1jL9v6KMI6dYesaq+DFcDZvjsoGvxGzY= +go.opentelemetry.io/otel/trace v1.14.0 h1:wp2Mmvj41tDsyAJXiWDWpfNsOiIyd38fy85pyKcFq/M= +go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+gozhnZjy/rw9G8= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190422162423-af44ce270edf/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb h1:fqpd0EBDzlHRCjiphRR5Zo/RSWWQlWv34418dnEixWk= +golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= +golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= +golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190412183630-56d357773e84/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190419153524-e8e3143a4f4a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190531175056-4c3a928424d2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.13.0 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190329151228-23e29df326fe/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190416151739-9c9e1878f421/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190420181800-aa740d480789/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200605160147-a5ece683394c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.5/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= diff --git a/bmp-console-api/log/batch/.gitkeep b/bmp-console-api/log/batch/.gitkeep new file mode 100644 index 0000000..c6a5447 --- /dev/null +++ b/bmp-console-api/log/batch/.gitkeep @@ -0,0 +1,3 @@ +# Ignore everything in this directory +* +# Except this file !.gitkeep diff --git a/bmp-console-api/logic/ApikeyLogic/ApikeyLogic.go b/bmp-console-api/logic/ApikeyLogic/ApikeyLogic.go new file mode 100644 index 0000000..29e3f9a --- /dev/null +++ b/bmp-console-api/logic/ApikeyLogic/ApikeyLogic.go @@ -0,0 +1,88 @@ +package ApikeyLogic + +import ( + "errors" + + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + sdkApikeyParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/api_key" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func CreateApikey(logger *log.Logger, param *sdkModels.CreateApikeyRequest) (string, error) { + + logid := logger.GetPoint("logid").(string) + + req := sdkApikeyParameters.NewCreateUserApikeyParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithBody(param) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("CreateApikey openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.APIKey.CreateUserApikey(req, nil) + logger.Info("CreateApikey openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("CreateApikey openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return "", err + } + return "", errors.New(respErr.Message) + } + return *responseApi.Payload.Result.ApikeyID, nil + +} + +func DeleteApikey(logger *log.Logger, apikeyId string) error { + logid := logger.GetPoint("logid").(string) + req := sdkApikeyParameters.NewDeleteUserApikeyParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithApikeyID(apikeyId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("DeleteApikey openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.APIKey.DeleteUserApikey(req, nil) + logger.Info("DeleteApikey openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DeleteApikey openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return err + } + return errors.New(respErr.Message) + } + return nil +} + +func GetApikeyList(logger *log.Logger, param requestTypes.GetApikeyListRequest) (*sdkModels.ApikeyList, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkApikeyParameters.NewDescribeUserAPIKeysParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithPageNumber(¶m.PageNumber) + req.WithPageSize(¶m.PageSize) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("GetApikeyList openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.APIKey.DescribeUserAPIKeys(req, nil) + logger.Info("GetApikeyList openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("GetApikeyList openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + return responseApi.Payload.Result, nil + +} diff --git a/bmp-console-api/logic/AuditLogLogic/AuditLogLogic.go b/bmp-console-api/logic/AuditLogLogic/AuditLogLogic.go new file mode 100644 index 0000000..7c26674 --- /dev/null +++ b/bmp-console-api/logic/AuditLogLogic/AuditLogLogic.go @@ -0,0 +1,154 @@ +package AuditLogLogic + +import ( + "errors" + "math/rand" + "strconv" + "time" + + "coding.jd.com/aidc-bmp/bmp-console-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/excel" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + sdkAuditLogParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/audit_log" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + "git.jd.com/cps-golang/ironic-common/exception" + + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func QueryAuditLogs(logger *log.Logger, param *requestTypes.DescribeAuditLogsRequest) (*response.AuditLogsList, error) { + // language := logger.GetPoint("language").(string) + logid := logger.GetPoint("logid").(string) + request := sdkAuditLogParameters.NewDescribeAuditLogsParams() + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithInstanceID(¶m.InstanceID) + + request.WithPageNumber(¶m.PageNumber) + request.WithPageSize(¶m.PageSize) + if param.Operation != "" { + request.WithOperation(¶m.Operation) + } + if param.UserName != "" { + request.WithUserName(¶m.UserName) + } + if param.Result != "" { + request.WithResult(¶m.Result) + } + if param.StartTime != 0 { + request.WithStartTime(¶m.StartTime) + } + if param.EndTime != 0 { + request.WithEndTime(¶m.EndTime) + } + + if param.ExportType != "" || param.IsAll == "1" { + isAll := "1" + request.IsAll = &isAll + } + + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + logger.Info("DescribeAuditLogs openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.AuditLog.DescribeAuditLogs(request, nil) + logger.Info("DescribeAuditLogs openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeAuditLogs openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + resp := &response.AuditLogsList{ + AuditLogs: responseApi.Payload.Result.AuditLogs, + PageNumber: responseApi.Payload.Result.PageNumber, + PageSize: responseApi.Payload.Result.PageSize, + TotalCount: responseApi.Payload.Result.TotalCount, + } + + return resp, nil + +} + +var resultMapEn map[string]string = map[string]string{ + "success": "Operation Success", + "fail": "Operation Fail", + "doing": "Doing", +} + +var resultMapZh map[string]string = map[string]string{ + "success": "操作成功", + "fail": "操作失败", + "doing": "操作中", +} + +func ExportAuditLogs(logger *log.Logger, result []*models.AuditLog) (fileName, downLoadFileName string) { + + language := logger.GetPoint("language").(string) + + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + + for _, data := range result { + var result string = resultMapZh[data.Result] + if language == "en_US" { + result = resultMapEn[data.Result] + } + sheetData = append(sheetData, []string{ + data.LogID, + data.OperationName, + data.UserName, + time.Unix(data.OperateTime, 0).Format("2006-01-02 15:04:05"), + result, + data.FailReason, + }) + } + exportHeader := BaseLogic.ExportAuditLogsHeader + if language == "en_US" { + exportHeader = BaseLogic.ExportAuditLogsHeaderEn + } + if err := e.SetSheetData("Sheet1", exportHeader, sheetData); err != nil { + panic(exception.Exception{Msg: "新建excel失败", Status: BaseLogic.ERROR_CODE}) + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + downloadFileName := "auditlogs_list_" + time.Now().Format(BaseLogic.FormatDate) + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" //生成100000到100000+900000之间的随机数,左闭右开 + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Info("保存excel到本地失败" + err.Error()) + panic(exception.Exception{Msg: "保存excel到本地失败", Status: BaseLogic.ERROR_CODE}) + } + return fileName, downloadFileName +} + +func DescribeAuditLogsTypes(logger *log.Logger) ([]*models.AuditLogsType, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkAuditLogParameters.NewDescribeAuditLogTypesParams() + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + logger.Info("DescribeAuditLogTypes openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.AuditLog.DescribeAuditLogTypes(request, nil) + logger.Info("DescribeAuditLogTypes openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeAuditLogTypes openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + return responseApi.Payload.Result, nil +} diff --git a/bmp-console-api/logic/BaseLogic/BaseLogic.go b/bmp-console-api/logic/BaseLogic/BaseLogic.go new file mode 100644 index 0000000..b2c8af9 --- /dev/null +++ b/bmp-console-api/logic/BaseLogic/BaseLogic.go @@ -0,0 +1,470 @@ +package BaseLogic + +import ( + "fmt" + "os" + "runtime/debug" +) + +const EN_US = "en_US" +const ZH_CN = "zh_CN" + +const ( + SUCCESS_CODE_OPENAPI = 0 //openapi返回的code,成功返回0,如果不是0,说明有错误,需要抛出错误信息 + ERROR_CODE = 400 + EOPEN_CODE = 500 + ERROR_REDIS_CODE = 401 + ERROR_MYSQL_CODE = 402 + + LOCAL_FILE_PATH = "./log/batch/" + UPLOAD_FILE_FORMAT_ERROR = "20201" + UPLOAD_FILE_SIZE_ERROR = "20202" + UPLOAD_FILE_BASE64 = "20203" + UPLOAD_FILE_NOT_BASE64 = "20204" + + //uc的调用路径配置 + + USERCENTER_GET_PRIVILEGENEW = "/usercenter/getPrivilegeNew" + ORDER_SUBMITRENEW = "/operate/submitRenew" + //以下错误码返给前端特定的错误提示,并且支持国际化 + ERROR_NO = 400001 //通用返回错误码 + ERROR_NO_INSTANCE_NOT_FOUND = "400002" + ERROR_NO_STRING_TO_STRING = 400003 +) + +func init() { + _, e := os.Stat(LOCAL_FILE_PATH) + if e != nil { + if os.IsNotExist(e) { + if e := os.MkdirAll(LOCAL_FILE_PATH, os.ModePerm); e != nil { + fmt.Println(fmt.Sprintf("create LOCAL_FILE_PATH error, %v\n%s", e, debug.Stack())) + return + } + } + } + +} + +var ( + FileError = map[string]string{ + UPLOAD_FILE_FORMAT_ERROR: "uploadFileFormatError", + UPLOAD_FILE_SIZE_ERROR: "uploadFileSizeError", + UPLOAD_FILE_BASE64: "uploadFileBase64", + UPLOAD_FILE_NOT_BASE64: "uploadFileNotBase64", + } + FormatTime = "2006-01-02 15:04:05" + FormatDate = "2006-01-02" + MountPoints = map[string]map[string][]string{ + "points": map[string][]string{ + "data": []string{"/var", "/export", "/data0"}, + "system": []string{"/", "/boot", "swap", "/var", "/export", "/data0"}, + }, + } + OSFileSystemFormats = map[string][]string{ + "formats": []string{"XFS", "EXT3", "EXT4", "SWAP"}, + } + HeaderList = map[string]map[string]map[string]map[string]bool{ + //实例自定义表头 + "instanceList": { + "customInfo": { + "instanceName": { + "selected": true, //默认选中 + "required": true, //true代表灰色按钮,直接就是选中,不可更改选中状态,默认就是选中 + }, + "status": { + "selected": true, //默认选中 + "required": false, //true代表灰色按钮,直接就是选中,不可更改选中状态,默认就是选中 + }, + "deviceTypeName": { //机型 + "selected": true, + "required": false, + }, + "imageName": { //镜像 + "selected": true, + "required": false, + }, + "iloIp": { + "selected": true, + "required": false, + }, + "privateIpv4": { + "selected": true, + "required": false, + }, + "privateEth1Ipv4": { + "selected": true, + "required": false, + }, + "privateIpv6": { + "selected": true, + "required": false, + }, + "privateEth1Ipv6": { + "selected": true, + "required": false, + }, + "config": { + "selected": true, + "required": false, + }, + "createdTime": { + "selected": true, + "required": false, + }, + }, + }, + //项目自定义表头 + "projectList": { + "customInfo": { + "projectName": { + "selected": true, + "required": true, + }, + "projectId": { // + "selected": true, + "required": false, + }, + "instanceCount": { // + "selected": true, + "required": false, + }, + "createdTime": { // + "selected": true, + "required": false, + }, + "updatedTime": { // + "selected": true, + "required": false, + }, + "owned": { // + "selected": true, + "required": false, + }, + }, + }, + //消息自定义表头 + "messageList": { + "customInfo": { + "detail": { + "selected": true, + "required": true, + }, + "finish_time": { // + "selected": true, + "required": false, + }, + "message_type": { // + "selected": true, + "required": false, + }, + "message_sub_type": { // + "selected": true, + "required": false, + }, + }, + }, + "auditLogsList": { + "customInfo": { + "logid": { + "selected": true, + "required": true, + }, + "operationName": { // + "selected": true, + "required": true, + }, + "userName": { // + "selected": true, + "required": false, + }, + "operateTime": { // + "selected": true, + "required": false, + }, + "result": { // + "selected": true, + "required": false, + }, + "failReason": { // + "selected": true, + "required": false, + }, + }, + }, + "monitorRulesList": { + "customInfo": { + "ruleName": { + "selected": true, + "required": true, + }, + "ruleId": { // + "selected": true, + "required": false, + }, + "resourceName": { // + "selected": true, + "required": false, + }, + "instanceCount": { // + "selected": true, + "required": false, + }, + "triggerDescription": { // + "selected": true, + "required": false, + }, + "statusName": { // + "selected": true, + "required": false, + }, + }, + }, + "monitorAlertsList": { + "customInfo": { + "alertTime": { + "selected": true, + "required": true, + }, + "resourceName": { // + "selected": true, + "required": false, + }, + "triggerDescription": { // + "selected": true, + "required": false, + }, + "alertValue": { // + "selected": true, + "required": false, + }, + "alertLevelDescription": { // + "selected": true, + "required": false, + }, + "alertPeriod": { // + "selected": true, + "required": false, + }, + "userName": { // + "selected": true, + "required": false, + }, + }, + }, + } + ExportInstanceHeader = []string{ + "实例名称/ID", + "状态", + "机型", + "镜像", + "带外IP", + "内网IPv4(eth0)", + "内网IPv4(eth1)", + "内网IPV6(eth0)", + "内网IPV6(eth1)", + "配置", + "创建时间", + } + + ExportInstanceHeaderEn = []string{ + "Instance Name/ID", + "Status", + "Instance Type", + "Image", + "Out-of-band IP", + "Private IPv4(eth0)", + "Private IPv4(eth1)", + "Private IPv6(eth0)", + "Private IPv6(eth1)", + "Configuration", + "Created Time", + } + + ExportProjectHeader = []string{ + "项目名称", + "项目ID", + "项目协作状态", + "实例数", + "创建时间", + "更新时间", + } + + ExportProjectHeaderEn = []string{ + "ProjectName", + "ProjectID", + "sharedStatus", + "Instances", + "CreateTime", + "UpdateTime", + } + + ExportIdcHeader = []string{ + "机房名称", + "机房编码", + "机房等级", + "机房地址", + "创建时间", + "创建人", + "更新时间", + "更新人", + } + + ExportIdcHeaderEn = []string{ + "IdcName", + "Cabinet", + "Level", + "Address", + "CreateTime", + "CreatedBy", + "UpdatedTime", + "UpdatedBy", + } + + NetworkType = map[string]string{ + "basic": "基础网络", + "vpc": "私有网络", + "retail": "定制网络", + } + + NetworkTypeEn = map[string]string{ + "basic": "basic", + "vpc": "vpc", + "retail": "retail", + } + + InterfaceMode = map[string]string{ + "bond": "单网口", + "dual": "双网口", + } + InterfaceModeEn = map[string]string{ + "bond": "bond", + "dual": "dual", + } + InstanceStatus = map[string]string{ + "creating": "创建中", + "starting": "开机中", + "running": "运行", + "stopping": "关机中", + "stopped": "关机", + "restarting": "重启中", + "resetting_password": "重置密码中", + "destroying": "销毁中", + "destroyed": "已销毁", + "error": "错误", + "upgrading": "调整配置中", + "reinstalling": "重装系统中", + "Creation failed": "创建失败", + "Startup failed": "开机失败", + "Shutdown failed": "关机失败", + "Reboot failed": "重启失败", + "Delete failed": "删除失败", + } + + InstanceStatusEn = map[string]string{ + "creating": "Creating", + "starting": "Starting up", + "running": "Running", + "stopping": "Shutting Down", + "stopped": "Stopped", + "restarting": "Restarting", + "resetting_password": "Reset Password", + "destroying": "Destructing", + "destroyed": "Destroyed", + "error": "Error", + "upgrading": "Upgrading", + "reinstalling": "Reinstalling System", + "Creation failed": "Creation failed", + "Startup failed": "Startup failed", + "Shutdown failed": "Shutdown failed", + "Reboot failed": "Reboot failed", + "Delete failed": "Delete failed", + } + + FilterInstanceStatus = map[string]string{ //给前端用的实例列表的fiter筛选接口用 + "running": "运行", + "stopped": "关机", + "error": "错误", + } + + FilterInstanceStatusEn = map[string]string{ //给前端用的实例列表的fiter筛选接口用 + "running": "running", + "stopped": "stopped", + "error": "error", + } + Instance = map[string]map[string]string{ + ERROR_NO_INSTANCE_NOT_FOUND: map[string]string{ + "cn": "资源实例未找到", + "en": "instance not found", + }, + //todo + } + + ExportMessageHeader = []string{ + "消息内容", + "接收时间", + "消息类型", + "消息子类型", + } + + ExportMessageHeaderEn = []string{ + "message content", + "time", + "message type", + "message subtype", + } + + ExportAuditLogsHeader = []string{ + "LogID", + "操作名称", + "操作人", + "操作时间", + "操作反馈", + "错误码", + } + + ExportAuditLogsHeaderEn = []string{ + "LogID", + "Operation Name", + "Operator", + "Operation Time", + "Operation Feedback", + "Fault Info", + } + + ExportRulesHeader = []string{ + "规则名称", + "规则ID", + "资源类型", + "实例关联数量", + "触发条件", + "状态", + } + + ExportRulesHeaderEn = []string{ + "Rule Name", + "Rule ID", + "Resource Type", + "Instance associated number", + "Triggering conditions", + "Status", + } + ExportAlertsHeader = []string{ + "报警时间", + "报警资源ID", + "触发条件", + "报警值", + "报警级别", + "持续时间", + "通知对象", + } + + ExportAlertsHeaderEn = []string{ + "Alarm time", + "Alarm Resources ID", + "Trigger conditions", + "Alarm value", + "Alarm level", + "duration", + "Notification object", + } +) diff --git a/bmp-console-api/logic/CustomInfoLogic/CustomInfoLogic.go b/bmp-console-api/logic/CustomInfoLogic/CustomInfoLogic.go new file mode 100644 index 0000000..9783d75 --- /dev/null +++ b/bmp-console-api/logic/CustomInfoLogic/CustomInfoLogic.go @@ -0,0 +1,48 @@ +package CustomInfoLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/logic/BaseLogic" + rdsUtil "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/redis" + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + "fmt" + + //"coding.jd.com/bmp/ironic-console-jdstack/thirdpart/redis" + "encoding/json" + + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + log "coding.jd.com/aidc-bmp/bmp_log" + "git.jd.com/cps-golang/ironic-common/exception" + "github.com/go-redis/redis" +) + +func SetCustomInfo(logger *log.Logger, param requestTypes.SetCustomInfoRequest) *response.CommonResponse { + userId := logger.GetPoint("userId").(string) + redisValue := make(map[string]map[string]map[string]bool, 0) + redisValue["customInfo"] = param.PageValue + err := rdsUtil.RedisCli.Set("custom_info_console_"+userId+":"+param.PageKey, util.InterfaceToJson(redisValue), 0).Err() + if err != nil { + panic(exception.Exception{Msg: "redis set " + param.PageKey + " error", Status: BaseLogic.ERROR_CODE}) + } + res := response.CommonResponse{ + Success: true, + } + return &res +} +func GetCustomInfo(logger *log.Logger, param requestTypes.QueryCustomInfoRequest) *map[string]map[string]map[string]bool { + userId := logger.GetPoint("userId").(string) + if param.Reload == "true" { + rdsUtil.RedisCli.Del("custom_info_console_" + userId + ":" + param.PageKey) + } + result, err := rdsUtil.RedisCli.Get("custom_info_console_" + userId + ":" + param.PageKey).Result() + if err == redis.Nil { //如果key不存在,取默认值 + fmt.Println("meiqudao") + result = util.InterfaceToJson(BaseLogic.HeaderList[param.PageKey]) + //panic(exception.Exception{Msg: "redis name " + param.PageKey + " does not exist", Status: BaseLogic.ERROR_CODE}) + } else if err != nil { + panic(exception.Exception{Msg: "get redis name " + param.PageKey + " failed", Status: BaseLogic.ERROR_CODE}) + } + obj := make(map[string]map[string]map[string]bool, 0) //responseWeb.GetCustomInfoResponse{} + err = json.Unmarshal([]byte(result), &obj) + return &obj +} diff --git a/bmp-console-api/logic/DeviceLogic/DeviceLogic.go b/bmp-console-api/logic/DeviceLogic/DeviceLogic.go new file mode 100644 index 0000000..a94d779 --- /dev/null +++ b/bmp-console-api/logic/DeviceLogic/DeviceLogic.go @@ -0,0 +1,41 @@ +package DeviceLogic + +import ( + "errors" + + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + sdkDeviceParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/device" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func QueryDeviceStockCount(logger *log.Logger, param requestTypes.QueryDeviceStockRequest) (int64, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkDeviceParameters.NewDescribeDevicesParams() + userId := logger.GetPoint("userId").(string) + req.WithTraceID(logid) + req.WithBmpUserID(&userId) + req.WithDeviceTypeID(¶m.DeviceTypeId) + //status和isAll等,openapi没设计好,后面修改 + status := "putaway" + req.WithManageStatus(&status) + isAll := "1" + req.WithIsAll(&isAll) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + // req.WithIdcID(¶m.IdcID) + logger.Info("DescribeDevices openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Device.DescribeDevices(req, nil) + logger.Info("DescribeDevices openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeDevices openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return 0, err + } + return 0, errors.New(respErr.Message) + } + return responseApi.Payload.Result.TotalCount, nil +} diff --git a/bmp-console-api/logic/DeviceTypeLogic/DeviceTypeLogic.go b/bmp-console-api/logic/DeviceTypeLogic/DeviceTypeLogic.go new file mode 100644 index 0000000..bcfa9d8 --- /dev/null +++ b/bmp-console-api/logic/DeviceTypeLogic/DeviceTypeLogic.go @@ -0,0 +1,203 @@ +package DeviceTypeLogic + +import ( + "errors" + "fmt" + "strconv" + "strings" + + "coding.jd.com/aidc-bmp/bmp-console-api/constants" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + sdkDeviceTypeParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/device_type" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func sdkDeviceType2DeviceType(logger *log.Logger, v *sdkModels.DeviceType) responseTypes.DeviceType { + language := logger.GetPoint("language").(string) + + /* + CPU:2* 24物理核,2.6GHz + + 内存:384GB,2933MHz + + 数据盘:2* 480 SSD + + 系统盘:2* 2TB NVME + + 网卡:2* 25GE + + GPU:4* NVIDIA T4 + */ + //var cputpl string = "%d*%d 物理核,%s" // + //var memtpl string = "%d*%d, %d MHZ" + //var systemtpl string = "%d*%d %s" + //var datatpl string = "%d*%d %s" + //var nictpl string = "%d*%d GE" + //var gputpl string = "%d*%s %s" + //if language == constants.LANGUAGE_EN { + // cputpl = "%d*%d cores,%s" + //} + + //raidMap := make(map[string]responseTypes.Raid) // 请求一次,避免循环请求 + + //raid, _ := raidLogic.QueryRaids(logger, requestTypes.QueryRaidsRequest{ + // DeviceTypeID: v.DeviceTypeID, + //}) + //raidStr := "" + //for _, value := range raid { + // raidStr += value.RaidName + "," + //} + //raidStr = strings.Trim(raidStr, ",") + cpu_ := strconv.Itoa(int(v.CPUAmount)) + "*" + strconv.Itoa(int(v.CPUCores)) + "物理核," + v.CPUFrequency + "GHz" + if language == constants.LANGUAGE_EN { + cpu_ = strconv.Itoa(int(v.CPUAmount)) + "*" + strconv.Itoa(int(v.CPUCores)) + "cores," + v.CPUFrequency + "GHz" + } + mem_ := strconv.Itoa(int(v.MemAmount)*int(v.MemSize)) + "GB " + v.MemType + " " + strconv.Itoa(int(v.MemFrequency)) + "MHz" + // 系统盘:显示总容量 (单块容量 接口类型 类型*数量 RAID 模式) + // 240GB 240GB SATA SSD*2 RAID1 + //sv_ := strconv.Itoa(int(v.SystemVolumeAmount)*int(v.SystemVolumeSize)) + "GB (" + strconv.Itoa(int(v.SystemVolumeSize)) + "GB " + v.SystemVolumeInterfaceType + " " + v.SystemVolumeType + "*" + strconv.Itoa(int(v.SystemVolumeAmount)) + "," + raidStr + ")" + //if v.SystemVolumeUnit == "TB" { + // sv_ = strconv.FormatFloat(float64(v.SystemVolumeAmount)*float64(v.SystemVolumeSize)/1000, 'f', 2, 64) + "TB (" + strconv.FormatFloat(float64(v.SystemVolumeSize)/1000, 'f', 2, 64) + "TB " + v.SystemVolumeInterfaceType + " " + v.SystemVolumeType + "*" + strconv.Itoa(int(v.SystemVolumeAmount)) + "," + raidStr + ")" + //} + //// 数据盘:显示总容量 (单块容量 接口类型 类型*数量 RAID 模式) + //dv_ := strconv.Itoa(int(v.DataVolumeAmount)*int(v.DataVolumeSize)) + "GB (" + strconv.Itoa(int(v.DataVolumeSize)) + "GB " + v.DataVolumeInterfaceType + " " + v.DataVolumeType + "*" + strconv.Itoa(int(v.DataVolumeAmount)) + "," + raidStr + ")" + //if v.DataVolumeUnit == "TB" { + // dv_ = strconv.FormatFloat(float64(v.DataVolumeAmount)*float64(v.DataVolumeSize)/1000, 'f', 2, 64) + "TB (" + strconv.FormatFloat(float64(v.DataVolumeSize)/1000, 'f', 2, 64) + "TB " + v.DataVolumeInterfaceType + " " + v.DataVolumeType + "*" + strconv.Itoa(int(v.DataVolumeAmount)) + "," + raidStr + ")" + //} + //if v.DataVolumeAmount == 0 { + // dv_ = "" + //} + + // 显示品牌 显卡型号 个数,例 NVIDIA P40 * 4 + gpu_ := v.GpuManufacturer + " " + v.GpuModel + "*" + strconv.Itoa(int(v.GpuAmount)) + if v.GpuAmount == 0 { + gpu_ = "" + } + nicInfo := strconv.Itoa(int(v.NicAmount)) + "*" + strconv.Itoa(int(v.NicRate)) + "GE" + sv_, dv_ := Volumes2SystemDataInfo(logger, v.Volumes) + return responseTypes.DeviceType{ + Name: v.Name, + DeviceTypeId: v.DeviceTypeID, + //Cpu: fmt.Sprintf(cputpl, v.CPUAmount, v.CPUCores, v.CPUFrequency), + //Mem: fmt.Sprintf(memtpl, v.MemAmount, v.MemSize, v.MemFrequency), + //System: fmt.Sprintf(systemtpl, v.SystemVolumeAmount, v.SystemVolumeSize, v.SystemVolumeType), + //Data: fmt.Sprintf(datatpl, v.DataVolumeAmount, v.DataVolumeSize, v.DataVolumeType), + //Nic: fmt.Sprintf(nictpl, v.NicAmount, v.NicRate), + //Gpu: fmt.Sprintf(gputpl, v.GpuAmount, v.GpuManufacturer, v.GpuModel), + Cpu: cpu_, + Mem: mem_, + System: sv_, + Data: dv_, + Nic: nicInfo, + Gpu: gpu_, + AvailableStock: v.StockAvailable, + DeviceSeries: v.DeviceSeries, + DeviceSeriesName: v.DeviceSeriesName, + BootMode: v.BootMode, + IsNeedRaid: v.IsNeedRaid, + } +} + +func Volumes2SystemDataInfo(logger *log.Logger, volumes []*sdkModels.Volume) (string, string) { + var sv_, dv_ string + ks := map[string]int{} + for _, v := range volumes { + if v.VolumeType == "system" { //系统卷只有一个 + sv_ = v.VolumeSize + v.VolumeUnit + "*" + strconv.Itoa(int(v.VolumeAmount)) + " " + v.InterfaceType + " " + v.DiskType + } else { + key := fmt.Sprintf("%s___%s___%s___%s", v.VolumeSize, v.VolumeUnit, v.InterfaceType, v.DiskType) + ks[key] = 1 + } + } + for k, v := range ks { + items := strings.Split(k, "___") + dv_ += items[0] + items[1] + "*" + strconv.Itoa(v) + " " + items[2] + " " + items[3] + ";" + } + dv_ = strings.TrimRight(dv_, ";") + + return sv_, dv_ +} + +func GetAvailableDeviceTypes(logger *log.Logger, param requestTypes.GetAvailableDeviceTypesRequest) (*responseTypes.AvailableDeviceType, error) { + + logid := logger.GetPoint("logid").(string) + userId := logger.GetPoint("userId").(string) + req := sdkDeviceTypeParameters.NewDescribeDeviceTypesParams() + req.WithTraceID(logid) + req.WithIdcID(¶m.IdcID) + req.WithBmpUserID(&userId) + isAll := "1" + req.WithIsAll(&isAll) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("QueryDeviceTypes openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.DeviceType.DescribeDeviceTypes(req, nil) + logger.Info("QueryDeviceTypes openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("QueryDeviceTypes openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + deviceTypes := responseApi.Payload.Result.DeviceTypes + res := map[string][]responseTypes.DeviceType{} + for _, v := range deviceTypes { + if _, ok := res[v.DeviceSeries]; !ok { + res[v.DeviceSeries] = []responseTypes.DeviceType{sdkDeviceType2DeviceType(logger, v)} + } else { + res[v.DeviceSeries] = append(res[v.DeviceSeries], sdkDeviceType2DeviceType(logger, v)) + } + } + obj := &responseTypes.AvailableDeviceType{} + if len(res["computer"]) != 0 { + obj.Computer = res["computer"] + } + if len(res["storage"]) != 0 { + obj.Storage = res["storage"] + } + if len(res["gpu"]) != 0 { + obj.Gpu = res["gpu"] + } + if len(res["other"]) != 0 { + obj.Other = res["other"] + } + fmt.Println(obj) + return obj, nil + +} +func Trim(str string) string { + s := strings.TrimRight(str, "0") + s = strings.TrimRight(s, ".") + return s +} + +func GetDeviceTypeByUuid(logger *log.Logger, deviceTypeID string) (*sdkModels.DeviceType, error) { + + logid := logger.GetPoint("logid").(string) + userId := logger.GetPoint("userId").(string) + req := sdkDeviceTypeParameters.NewDescribeDeviceTypeParams() + req.WithTraceID(logid) + req.WithDeviceTypeID(deviceTypeID) + req.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("DescribeDeviceType openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.DeviceType.DescribeDeviceType(req, nil) + logger.Info("DescribeDeviceType openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeDeviceType openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + deviceTypes := responseApi.Payload.Result.DeviceType + return deviceTypes, nil +} diff --git a/bmp-console-api/logic/IdcLogic/IdcLogic.go b/bmp-console-api/logic/IdcLogic/IdcLogic.go new file mode 100644 index 0000000..a7a12a9 --- /dev/null +++ b/bmp-console-api/logic/IdcLogic/IdcLogic.go @@ -0,0 +1,79 @@ +package IdcLogic + +import ( + "errors" + "math/rand" + "strconv" + "time" + + "coding.jd.com/aidc-bmp/bmp-console-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/excel" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + sdkIdcParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/idc" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + log "coding.jd.com/aidc-bmp/bmp_log" + "git.jd.com/cps-golang/ironic-common/exception" +) + +func GetIdcList(logger *log.Logger) (*sdkModels.IdcList, error) { + + logid := logger.GetPoint("logid").(string) + userId := logger.GetPoint("userId").(string) + req := sdkIdcParameters.NewDescribeIdcsParams() + req.WithTraceID(logid) + // req.WithIdcID(¶m.IdcID) + req.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("DescribeIdcs openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Idc.DescribeIdcs(req, nil) + logger.Info("DescribeIdcs openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeIdcs openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + return responseApi.Payload.Result, nil +} + +func ExportIdcList(logger *log.Logger, result []*sdkModels.Idc) (fileName, downLoadFileName string) { + + language := logger.GetPoint("language").(string) + + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + for _, data := range result { + + sheetData = append(sheetData, []string{ + data.Name, + data.NameEn, + data.Level, + data.Address, + data.CreateTime, + data.CreatedBy, + data.UpdateTime, + data.UpdatedBy, + }) + } + exportIdcHeader := BaseLogic.ExportIdcHeader + if language == "en_US" { + exportIdcHeader = BaseLogic.ExportIdcHeaderEn + } + if err := e.SetSheetData("Sheet1", exportIdcHeader, sheetData); err != nil { + panic(exception.Exception{Msg: "新建excel失败", Status: BaseLogic.ERROR_CODE}) + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + downloadFileName := "idc_list_" + time.Now().Format(BaseLogic.FormatDate) + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" //生成100000到100000+900000之间的随机数,左闭右开 + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Info("保存excel到本地失败" + err.Error()) + panic(exception.Exception{Msg: "保存excel到本地失败", Status: BaseLogic.ERROR_CODE}) + } + return fileName, downloadFileName +} diff --git a/bmp-console-api/logic/ImageLogic/ImageLogic.go b/bmp-console-api/logic/ImageLogic/ImageLogic.go new file mode 100644 index 0000000..f9eb77c --- /dev/null +++ b/bmp-console-api/logic/ImageLogic/ImageLogic.go @@ -0,0 +1,46 @@ +package ImageLogic + +import ( + "errors" + + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + sdkDeviceTypeParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/device_type" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func QueryImagesByDeviceType(logger *log.Logger, param requestTypes.QueryImagesByDeviceTypeRequest) (map[string][]*sdkModels.Image, error) { + + logid := logger.GetPoint("logid").(string) + userId := logger.GetPoint("userId").(string) + req := sdkDeviceTypeParameters.NewDescribeDeviceTypeImagesParams() + req.WithTraceID(logid) + req.WithBmpUserID(&userId) + req.WithDeviceTypeID(¶m.DeviceTypeID) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + // req.WithIdcID(¶m.IdcID) + logger.Info("DescribeImages openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.DeviceType.DescribeDeviceTypeImages(req, nil) + logger.Info("DescribeImages openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeImages openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + res := map[string][]*sdkModels.Image{} + images := responseApi.Payload.Result.Images + for _, v := range images { + if _, ok := res[v.OsType]; !ok { + res[v.OsType] = []*sdkModels.Image{v} + } else { + res[v.OsType] = append(res[v.OsType], v) + } + } + return res, nil +} diff --git a/bmp-console-api/logic/InstanceLogic/InstanceLogic.go b/bmp-console-api/logic/InstanceLogic/InstanceLogic.go new file mode 100644 index 0000000..a31179a --- /dev/null +++ b/bmp-console-api/logic/InstanceLogic/InstanceLogic.go @@ -0,0 +1,896 @@ +package InstanceLogic + +import ( + "errors" + "fmt" + "math/rand" + "mime/multipart" + "path" + "strconv" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-console-api/constants" + "coding.jd.com/aidc-bmp/bmp-console-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-console-api/logic/RaidLogic" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/excel" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + + log "coding.jd.com/aidc-bmp/bmp_log" + "git.jd.com/cps-golang/ironic-common/exception" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + + sdkInstanceParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/instance" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +type Formula struct { + Key string `json:"key"` + Value float64 `json:"value"` + Unit string `json:"unit"` +} + +type ExtraInfo struct { + Name string `json:"name"` + Value string `json:"value"` +} + +func SdkInstance2RespInstance(logger *log.Logger, v sdkModels.Instance) response.Instance { + /* + CPU:Intel E5-2650V4(2*12物理核,2.2GHz) + 内存:256GB DDR4 + 系统盘:300GB (2*300GB SAS, RAID1) + 数据盘:72TB (12*6TB SATA, NO RAID) + 网卡:2*25GE + GPU:P40*4 + */ + //cputpl := "%s %s (%d*%d物理核, %sGHz)" + //memtpl := "%dGB %s %dGHZ" + //systemtpl := "%dGB(%dGB %s %s*%d,%s)" + //datatpl := "%dGB(%dGB %s %s*%d,%s)" + //nictpl := "%d*%dGE" + //gputpl := "%s %s*%d" + language := logger.GetPoint("language").(string) + //if language == constants.LANGUAGE_EN { + // cputpl = "%s %s (%d*%dcores, %sGHz)" + //} + + //raidMap := make(map[string]response.DeviceTypeRaid) // 请求一次,避免循环请求 + + // raid, _ := raidLogic.QueryRaid(logger, v.SystemVolumeRaidID) + // raidStr := "" + // if raid != nil { + // raidStr = raid.Name + // } + + cpu_ := strconv.Itoa(int(v.CPUAmount)) + "*" + strconv.Itoa(int(v.CPUCores)) + "物理核," + v.CPUFrequency + "GHz" + if language == constants.LANGUAGE_EN { + cpu_ = strconv.Itoa(int(v.CPUAmount)) + "*" + strconv.Itoa(int(v.CPUCores)) + "cores," + v.CPUFrequency + "GHz" + } + mem_ := strconv.Itoa(int(v.MemAmount)*int(v.MemSize)) + "GB(" + strconv.Itoa(int(v.MemSize)) + "GB*" + strconv.Itoa(int(v.MemAmount)) + ")" + v.MemType + " " + strconv.Itoa(int(v.MemFrequency)) + "MHz" + //系统盘:显示总容量 (单块容量 接口类型 类型*数量 RAID 模式) + //240GB 240GB SATA SSD*2 RAID1 + sv_ := getInstanceSystemDiskInfo(logger, v.InstanceVolumeRaids) + + // 显示品牌 显卡型号 个数,例 NVIDIA P40 * 4 + gpu_ := v.GpuManufacturer + " " + v.GpuModel + "*" + strconv.Itoa(int(v.GpuAmount)) + if v.GpuAmount == 0 { + gpu_ = "" + } + nicInfo := strconv.Itoa(int(v.NicAmount)) + "*" + strconv.Itoa(int(v.NicRate)) + "GE" + return response.Instance{ + Instance: v, + CpuInfo: cpu_, + MemInfo: mem_, + SystemInfo: sv_, + NicInfo: nicInfo, + GpuInfo: gpu_, + Volumes: v.InstanceVolumeRaids, + } +} + +func getInstanceSystemDiskInfo(logger *log.Logger, ivr []*models.InstanceVolumeRaid) string { + //TODO,返回的是结构 + for _, v := range ivr { + if v.Volume == nil { + logger.Warnf("getInstanceSystemDiskInfo.Volume empty, v:%s", util.InterfaceToJson(v)) + continue + } + if v.Raid == nil { //没有raid卡,不做raid + // logger.Warnf("getInstanceSystemDiskInfo.Raid empty, v:%s", util.InterfaceToJson(v)) + // continue + } + if v.Volume.VolumeType == "system" { + + vr := &models.VolumeRaids{ + // 硬盘数量(最低块数) + VolumeAmount: v.Volume.VolumeAmount, + + // 卷uuid + VolumeID: v.Volume.VolumeID, + + // 卷名称 + VolumeName: v.Volume.VolumeName, + + // 单盘大小(最小容量) + VolumeSize: v.Volume.VolumeSize, + + // 卷类型:系统卷,数据卷 + VolumeType: v.Volume.VolumeType, + + // 硬盘单位(GB,TB) + VolumeUnit: v.Volume.VolumeUnit, + + // 硬盘类型(SSD,HDD) + DiskType: v.Volume.DiskType, + + // 接口类型(SATA,SAS,NVME,不限制) + InterfaceType: v.Volume.InterfaceType, + } + return RaidLogic.GetDiskDetailByRaid(vr, v.Raid) + } + } + return "" +} + +func DescribeInstances(logger *log.Logger, param requestTypes.QueryInstancesRequest) (*response.InstancesResponse, error) { + // language := logger.GetPoint("language").(string) + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewDescribeProjectInstancesParams() + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithProjectID(¶m.ProjectID) + request.WithDeviceTypeID(¶m.DeviceTypeId) + request.WithStatus(¶m.Status) + request.WithPageNumber(¶m.PageNumber) + request.WithPageSize(¶m.PageSize) + if param.IloIp != "" { + request.WithIloIP(¶m.IloIp) + } + if param.PrivateIp != "" { + request.WithIPV4(¶m.PrivateIp) + } + if param.PrivateIpv6 != "" { + request.WithIPV6(¶m.PrivateIpv6) + } + + if param.InstanceId != "" { + request.WithInstanceID(¶m.InstanceId) + } + + if param.ExportType != "" || param.IsAll == "1" { + isAll := "1" + request.IsAll = &isAll + } + + if param.Name != "" { + request.WithInstanceName(¶m.Name) + } + + if param.IsInstallAgent != "" { + request.WithIsInstallAgent(¶m.IsInstallAgent) + } + + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + logger.Info("DescribeProjectInstances openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.DescribeProjectInstances(request, nil) + logger.Info("DescribeProjectInstances openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeProjectInstances openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + resp := response.InstancesResponse{} + resp.PagingResponse.PageNumber = responseApi.Payload.Result.PageNumber + resp.PagingResponse.PageSize = responseApi.Payload.Result.PageSize + resp.PagingResponse.TotalCount = responseApi.Payload.Result.TotalCount + + obj := response.Instance{} + + for _, v := range responseApi.Payload.Result.Instances { + obj = SdkInstance2RespInstance(logger, *v) + + resp.Instances = append(resp.Instances, obj) + } + return &resp, nil +} + +func DescribeInstance(logger *log.Logger, param requestTypes.QueryInstanceRequest) (*response.InstanceInfo, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewDescribeProjectInstanceParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + request.WithInstanceID(param.InstanceId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("DescribeProjectInstance openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.DescribeProjectInstance(request, nil) + logger.Info("DescribeProjectInstance openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeProjectInstance openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + obj := response.Instance{} + v := responseApi.Payload.Result.Instance + + obj = SdkInstance2RespInstance(logger, *v) + + return &response.InstanceInfo{ + Instance: obj, + }, nil +} + +// func formatDiskDesc(logger *log.Logger, deviceType string, raidId string, volumnType string) string { + +// region := logger.GetPoint("region").(string) +// pin := logger.GetPoint("pin").(string) +// req := requestTypes.QueryRaidsRequest{ +// Region: region, +// DeviceType: deviceType, +// } +// raidsResult, err := RaidLogic.DescribeDeviceRaids(logger, req, pin) +// if err != nil { +// logger.Warnf("RaidLogic.DescribeDeviceRaids error:%s", err.Error()) +// return "" +// } +// raids := raidsResult.Raids +// for _, raid := range raids { +// if raid.RaidID == raidId && strings.EqualFold(volumnType, raid.VolumeType) { +// volume_detail := strings.TrimRight(raid.VolumeDetail, ")") +// raidType := strings.ReplaceAll(raid.RaidID, "NORAID", "NO RAID") +// return fmt.Sprintf("%s, %s)", volume_detail, raidType) +// } +// } +// return "" +// } + +func StartInstance(logger *log.Logger, param requestTypes.StartInstanceRequest) (bool, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewStartProjectInstanceParams() + request.WithInstanceID(param.InstanceId) + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("StartProjectInstance openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.StartProjectInstance(request, nil) + logger.Info("StartProjectInstance openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("StartProjectInstance openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + return responseApi.Payload.Result.Success, nil +} + +func StopInstance(logger *log.Logger, param requestTypes.StopInstanceRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewStopProjectInstanceParams() + request.WithInstanceID(param.InstanceId) + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("stopinstance openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.StopProjectInstance(request, nil) + logger.Info("stopinstance openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("stopinstance openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + return responseApi.Payload.Result.Success, nil +} + +func RestartInstance(logger *log.Logger, param requestTypes.RestartInstanceRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewRestartProjectInstanceParams() + request.WithInstanceID(param.InstanceId) + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("restartinstance openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.RestartProjectInstance(request, nil) + logger.Info("restartinstance openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("restartinstance openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + return responseApi.Payload.Result.Success, nil +} + +func ModifyInstance(logger *log.Logger, param requestTypes.ModifyInstanceRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewModifyProjectInstanceParams() + request.WithInstanceID(param.InstanceID) + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + body := sdkModels.ModifyInstanceRequest{ + Description: param.Description, + InstanceName: param.Name, + } + request.WithBody(&body) + logger.Info("ModifyProjectInstance openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.ModifyProjectInstance(request, nil) + logger.Info("ModifyProjectInstance openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("ModifyProjectInstance openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + return responseApi.Payload.Result.Success, nil +} + +func DeleteInstance(logger *log.Logger, instanceId string) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewDeleteProjectInstanceParams() + request.WithInstanceID(instanceId) + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("deleteinstance openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.DeleteProjectInstance(request, nil) + logger.Info("deleteinstance openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("restartinstance openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + return responseApi.Payload.Result.Success, nil +} + +func LockInstance(logger *log.Logger, param requestTypes.LockInstanceRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewLockProjectInstanceParams() + request.WithInstanceID(param.InstanceId) + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("lockinstance openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.LockProjectInstance(request, nil) + logger.Info("lockinstance openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("lockinstance openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + return responseApi.Payload.Result.Success, nil +} + +func UnLockInstance(logger *log.Logger, param requestTypes.UnLockInstanceRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewUnLockProjectInstanceParams() + request.WithInstanceID(param.InstanceId) + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("unlockinstance openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.UnLockProjectInstance(request, nil) + logger.Info("unlockinstance openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("lockinstance openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + return responseApi.Payload.Result.Success, nil +} + +//CreateInstanceApi 测试sdk直接创建使用 +func CreateInstanceApi(logger *log.Logger, param *sdkModels.CreateInstanceRequest) ([]string, error) { + + logid := logger.GetPoint("logid").(string) + + req := sdkInstanceParameters.NewCreateProjectInstanceParams() + req.WithTraceID(logid) + req.WithBody(param) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("createinstancesApi openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Instance.CreateProjectInstance(req, nil) + logger.Info("createinstancesApi openapi response:", util.InterfaceToJson(responseApi)) + fmt.Println("createinstancesApi openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("createinstancesApi openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.InstanceIds, nil +} + +func getOrCreate(str string) string { + if str != "" { + return str + } + return commonUtil.GenerateRandUuid() +} + +func ExportInstance(logger *log.Logger, result []response.Instance) (fileName, downLoadFileName string) { + + language := logger.GetPoint("language").(string) + + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + + //cputpl := "%s %s (%d*%d 物理核, %s)" + //if language == "en_US" { + // cputpl = "%s %s (%d*%d cores, %s)" + //} + //memtpl := "%d*%d %s" + + for _, data := range result { + + // interfaceMode := BaseLogic.InterfaceMode[data.InterfaceMode] + //var instanceStatus string + //if language == "en_US" { + // // interfaceMode = BaseLogic.InterfaceModeEn[data.InterfaceMode] + // instanceStatus = BaseLogic.InstanceStatusEn[data.Status] + //} else { + // instanceStatus = BaseLogic.InstanceStatus[data.Status] + //} + var info string + //cpu_ := strconv.Itoa(int(data.CPUAmount)) + "*" + strconv.Itoa(int(data.CPUCores)) + " 物理核," + data.CPUFrequency + "GHz" + //mem_ := strconv.Itoa(int(data.MemAmount)*int(data.MemSize)) + "GB (" + strconv.Itoa(int(data.MemSize)) + "*" + strconv.Itoa(int(data.MemAmount)) + ") " + data.MemType + "," + strconv.Itoa(int(data.MemFrequency)) + "MHz" + info = fmt.Sprintf("CPU:%s, 内存:%s", data.CpuInfo, data.MemInfo) + if language == constants.LANGUAGE_EN { + //cpu_ = strconv.Itoa(int(data.CPUAmount)) + "*" + strconv.Itoa(int(data.CPUCores)) + " cores, " + data.CPUFrequency + "GHz" + info = fmt.Sprintf("CPU:%s, Memory:%s", data.CpuInfo, data.MemInfo) + } + //cpuInfo := fmt.Sprintf(cputpl, data.CPUManufacturer, data.CPUModel, data.CPUAmount, data.CPUCores, data.CPUFrequency) + //memInfo := fmt.Sprintf(memtpl, data.MemAmount, data.MemSize, data.MemType) + + sheetData = append(sheetData, []string{ + fmt.Sprintf("%s/%s", data.InstanceName, data.InstanceID), + data.StatusName, + data.DeviceTypeName, + data.ImageName, + data.IloIP, + data.PrivateIPV4, + data.PrivateEth1IPV4, + data.PrivateIPV6, + data.PrivateEth1IPV6, + info, + data.CreatedTime, + }) + } + exportInstanceHeader := BaseLogic.ExportInstanceHeader + if language == "en_US" { + exportInstanceHeader = BaseLogic.ExportInstanceHeaderEn + } + if err := e.SetSheetData("Sheet1", exportInstanceHeader, sheetData); err != nil { + panic(exception.Exception{Msg: "新建excel失败", Status: BaseLogic.ERROR_CODE}) + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + downloadFileName := "instance_list_" + time.Now().Format(BaseLogic.FormatDate) + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" //生成100000到100000+900000之间的随机数,左闭右开 + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Info("保存excel到本地失败" + err.Error()) + panic(exception.Exception{Msg: "保存excel到本地失败", Status: BaseLogic.ERROR_CODE}) + } + return fileName, downloadFileName +} +func ParseFile(logger *log.Logger, param requestTypes.ParseFileRequest, header *multipart.FileHeader) string { + if header.Size > 16*1024 { + panic(exception.Exception{Msg: BaseLogic.FileError[BaseLogic.UPLOAD_FILE_SIZE_ERROR], ErrorCode: BaseLogic.UPLOAD_FILE_SIZE_ERROR}) + } + arr := strings.Split(header.Filename, ".") + suffix := strings.ToLower(arr[len(arr)-1]) + AvailableSuffix := []string{"jpg", "jpeg", "png", "gif"} + if util.InArray(suffix, AvailableSuffix) { + panic(exception.Exception{Msg: "file is image", Status: BaseLogic.ERROR_CODE}) + } + dir, err := util.GetBaseDir() + if err != nil { + logger.Info("获取当前根目录失败" + err.Error()) + panic(exception.Exception{Msg: "获取当前根目录失败", Status: BaseLogic.ERROR_CODE}) + } + prefix := util.GenUuid() + excel.CreateDirIfNotExist(BaseLogic.LOCAL_FILE_PATH) //如果目录不存在,创建一个目录 + localFileName := path.Join(dir, BaseLogic.LOCAL_FILE_PATH, prefix+"-"+header.Filename) + if err = util.SaveToLocal(localFileName, param.UserDataFile); err != nil { + logger.Info("保存excel到本地失败" + err.Error()) + panic(exception.Exception{Msg: "保存文件到本地失败" + err.Error(), Status: BaseLogic.ERROR_CODE}) + } + contentFile, err := util.ReadFileContent(localFileName) + content := "" + if err != nil { + logger.Info("读取文件失败" + err.Error()) + panic(exception.Exception{Msg: "读取文件失败", Status: BaseLogic.ERROR_CODE}) + } + contentByte, err := util.Base64Decrypt(string(contentFile)) + if err != nil && param.Base64 { //如果选了64,结果内容不是64 + panic(exception.Exception{Msg: BaseLogic.FileError[BaseLogic.UPLOAD_FILE_NOT_BASE64], ErrorCode: BaseLogic.UPLOAD_FILE_NOT_BASE64}) + } + if err == nil && !param.Base64 { //如果内容是64,结果还没有勾选64 + panic(exception.Exception{Msg: BaseLogic.FileError[BaseLogic.UPLOAD_FILE_BASE64], ErrorCode: BaseLogic.UPLOAD_FILE_BASE64}) + } + if err != nil { //说明不是64位编码,原始代码 + content = string(contentFile) + } else { + content = string(contentByte) + } + //fmt.Println("qq", strings.Index(content, "#!/bin/bash")) + //必须在文件第一行的开头是如下内容才能通过 + if strings.Index(content, "#!/bin/bash") != 0 && strings.Index(content, "#!/usr/bin/env python") != 0 && strings.Index(content, "(rem cmd|)") != 0 { + panic(exception.Exception{Msg: BaseLogic.FileError[BaseLogic.UPLOAD_FILE_FORMAT_ERROR], ErrorCode: BaseLogic.UPLOAD_FILE_FORMAT_ERROR}) + } + return string(contentFile) +} +func Trim(str string) string { + s := strings.TrimRight(str, "0") + s = strings.TrimRight(s, ".") + return s +} + +// 【设备管理】【批量开机】 +func StartInstances(logger *log.Logger, instanceIDs []string) (bool, error) { + logid := logger.GetPoint("logid").(string) + req := sdkInstanceParameters.NewStartInstancesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := sdkModels.StartInstancesRequest{ + InstanceIds: instanceIDs, + } + req.WithBody(&body) + + logger.Info("StartInstances openapi sdk req:", util.InterfaceToJson(req)) + client, err := openApi.SdkClient.Instance.StartInstances(req, nil) + logger.Info("StartInstances openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return true, nil +} + +// 【设备管理】【批量关机】 +func StopInstances(logger *log.Logger, instanceIDs []string) (bool, error) { + logid := logger.GetPoint("logid").(string) + req := sdkInstanceParameters.NewStopInstancesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := sdkModels.StopInstancesRequest{ + InstanceIds: instanceIDs, + } + req.WithBody(&body) + + logger.Info("StopInstances openapi sdk req:", util.InterfaceToJson(req)) + client, err := openApi.SdkClient.Instance.StopInstances(req, nil) + logger.Info("StopInstances openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return true, nil +} + +// 【设备管理】【批量重启】 +func RestartInstances(logger *log.Logger, instanceIDs []string) (bool, error) { + logid := logger.GetPoint("logid").(string) + req := sdkInstanceParameters.NewRestartInstancesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := sdkModels.RestartInstancesRequest{ + InstanceIds: instanceIDs, + } + req.WithBody(&body) + + logger.Info("RestartInstances openapi sdk req:", util.InterfaceToJson(req)) + client, err := openApi.SdkClient.Instance.RestartInstances(req, nil) + logger.Info("RestartInstances openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return true, nil +} + +// 【设备管理】【批量编辑实例名称】 +func ModifyInstances(logger *log.Logger, instanceIDs []string, instanceName string) (bool, error) { + logid := logger.GetPoint("logid").(string) + req := sdkInstanceParameters.NewModifyInstancesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := sdkModels.ModifyInstancesRequest{ + InstanceIDs: instanceIDs, + InstanceName: instanceName, + } + req.WithBody(&body) + + logger.Info("ModifyInstances openapi sdk req:", util.InterfaceToJson(req)) + client, err := openApi.SdkClient.Instance.ModifyInstances(req, nil) + logger.Info("ModifyInstances openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return true, nil +} + +// 【设备管理】【批量删除】 +func DeleteInstances(logger *log.Logger, instanceIDs []string) (bool, error) { + logid := logger.GetPoint("logid").(string) + req := sdkInstanceParameters.NewDeleteInstancesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := sdkModels.DeleteInstancesRequest{ + InstanceIDs: instanceIDs, + } + req.WithBody(&body) + + logger.Info("DeleteInstances openapi sdk req:", util.InterfaceToJson(req)) + client, err := openApi.SdkClient.Instance.DeleteInstances(req, nil) + logger.Info("DeleteInstances openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return true, nil +} + +func ResetInstancePassword(logger *log.Logger, instanceId string, password string) (bool, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewResetProjectInstancePasswdParams() + request.WithInstanceID(instanceId) + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + body := sdkModels.ResetInstancePasswdRequest{ + Password: password, + } + request.WithBody(&body) + + logger.Info("ResetProjectInstancePasswd openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.ResetProjectInstancePasswd(request, nil) + logger.Info("ResetProjectInstancePasswd openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("ResetProjectInstancePasswd openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + return responseApi.Payload.Result.Success, nil +} + +func ResetInstancesPassword(logger *log.Logger, instanceIds []string, password string) (bool, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewResetProjectInstancesPasswdParams() + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + body := sdkModels.ResetInstancesPasswdRequest{ + Password: password, + InstanceIDs: instanceIds, + } + request.WithBody(&body) + + logger.Info("ResetProjectInstancesPasswd openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.ResetProjectInstancesPasswd(request, nil) + logger.Info("ResetProjectInstancesPasswd openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("ResetProjectInstancesPasswd openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + return responseApi.Payload.Result.Success, nil +} + +//ReinstallInstance sdk重装 +func ReinstallInstance(logger *log.Logger, param requestTypes.ReinstallInstanceRequest) (bool, error) { + + logid := logger.GetPoint("logid").(string) + + req := sdkInstanceParameters.NewReinstallProjectInstanceParams() + req.WithTraceID(logid) + req.WithBody(¶m.ReinstallInstanceRequest) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithInstanceID(param.InstanceId) + logger.Info("ReinstallProjectInstance openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Instance.ReinstallProjectInstance(req, nil) + logger.Info("ReinstallProjectInstance openapi response:", util.InterfaceToJson(responseApi)) + fmt.Println("ReinstallProjectInstance openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("ReinstallProjectInstance openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil +} + +func DescribeInstancesForShare(logger *log.Logger, param requestTypes.QueryInstancesForShareRequest) ([]*sdkModels.InstanceForShare, error) { + // language := logger.GetPoint("language").(string) + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewDescribeInstancesByProjectIDAndOwnerNameAndSharerNameParams() + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithProjectID(¶m.ProjectID) + request.WithOwnerName(¶m.OwnerName) + request.WithSharerName(¶m.SharerName) + + if param.InstanceId != "" { + request.WithInstanceID(¶m.InstanceId) + } + if param.InstanceName != "" { + request.WithInstanceName(¶m.InstanceName) + } + + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + logger.Info("DescribeInstancesByProjectIDAndOwnerNameAndSharerName openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.DescribeInstancesByProjectIDAndOwnerNameAndSharerName(request, nil) + logger.Info("DescribeInstancesByProjectIDAndOwnerNameAndSharerName openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeInstancesByProjectIDAndOwnerNameAndSharerName openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Instances, nil +} diff --git a/bmp-console-api/logic/KeypairLoigc/KeypairLoigc.go b/bmp-console-api/logic/KeypairLoigc/KeypairLoigc.go new file mode 100644 index 0000000..82bbd67 --- /dev/null +++ b/bmp-console-api/logic/KeypairLoigc/KeypairLoigc.go @@ -0,0 +1,239 @@ +package KeypairLoigc + +import ( + "errors" + + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + + "coding.jd.com/aidc-bmp/bmp-console-api/util" + sdkSshkeyParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/sshkey" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func DescribeKeypairs(logger *log.Logger, param requestTypes.QueryKeypairsRequest) (*response.KeyPairsResponse, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkSshkeyParameters.NewDescribeUserSSHKeysParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + if param.Name != "" { + req.WithName(¶m.Name) + } + pageNumber := param.PageNumber + pageSize := param.PageSize + if pageNumber != 0 { + req.WithPageNumber(&pageNumber) + } + if pageSize != 0 { + req.WithPageSize(&pageSize) + } + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("describekeypairs openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Sshkey.DescribeUserSSHKeys(req, nil) + logger.Info("describekeypairs openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("describekeypairs openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + resp := response.KeyPairsResponse{} + resp.PagingResponse.PageNumber = responseApi.Payload.Result.PageNumber + resp.PagingResponse.PageSize = responseApi.Payload.Result.PageSize + resp.PagingResponse.TotalCount = responseApi.Payload.Result.TotalCount + + obj := response.KeyPair{} + for _, v := range responseApi.Payload.Result.Sshkeys { + + obj.Name = v.Name + obj.KeypairId = v.SshkeyID + + req := sdkSshkeyParameters.NewGetInstancesBySshkeyParams() + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithSshkeyID(v.SshkeyID) + req.WithBmpLanguage(&language) + logger.Info("getInstancesBySshkey openapi request:", util.InterfaceToJson(req)) + respInstance, _ := openApi.SdkClient.Sshkey.GetInstancesBySshkey(req, nil) + logger.Info("getInstancesBySshkey openapi response:", util.InterfaceToJson(respInstance)) + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warn("getInstancesBySshkey openapi error:", err.Error()) + } + logger.Warn("getInstancesBySshkey openapi error:", respErr.Message) + } + obj.IsCheckDelete = "yes" + if len(respInstance.Payload.Result.InstanceIds) != 0 { + // for _, value := range respInstance.Result.Instances { + // if value.Status == "creating" || value.Status == "reinstalling" { + // logger.Info("list keypair "+v.KeypairId+" is using by instance:", value.InstanceId) + // obj.IsCheckDelete = "no" + // break + // } + // } + obj.IsCheckDelete = "no" + } + obj.FingerPrint = v.FingerPrint + obj.CreatedTime = v.CreatedTime + obj.UpdatedTime = v.UpdatedTime + resp.Keypairs = append(resp.Keypairs, obj) + + } + + return &resp, nil +} + +func DescribeKeypair(logger *log.Logger, keypairID string) (*response.KeyPairInfo, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkSshkeyParameters.NewDescribeUserSSHKeyParams() + req.WithSshkeyID(keypairID) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("describekeypair openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Sshkey.DescribeUserSSHKey(req, nil) + logger.Info("describekeypair openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("describekeypair openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + obj := response.KeyPairInfo{} + v := responseApi.Payload.Result.Sshkey + obj.Keypair.Name = v.Name + obj.Keypair.KeypairId = v.SshkeyID + + insReq := sdkSshkeyParameters.NewGetInstancesBySshkeyParams() + req.WithSshkeyID(v.SshkeyID) + req.WithBmpUserID(&userId) + req.WithBmpLanguage(&language) + logger.Info("getInstancesBySshkey openapi request:", util.InterfaceToJson(insReq)) + respInstance, err := openApi.SdkClient.Sshkey.GetInstancesBySshkey(insReq, nil) + logger.Info("getInstancesBySshkey openapi response:", util.InterfaceToJson(respInstance)) + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warn("getInstancesBySshkey openapi error:", err.Error()) + } + logger.Warn("getInstancesBySshkey openapi error:", respErr.Message) + } + obj.Keypair.IsCheckDelete = "yes" + if len(respInstance.Payload.Result.InstanceIds) != 0 { + // for _, value := range respInstance.Result.Instances { + // if value.Status == "creating" || value.Status == "reinstalling" { + // logger.Info("list keypair "+v.KeypairId+" is using by instance:", value.InstanceId) + // obj.IsCheckDelete = "no" + // break + // } + // } + obj.Keypair.IsCheckDelete = "no" + } + + //obj.Keypair.IsCheckDelete = "yes" + obj.Keypair.FingerPrint = v.FingerPrint + obj.Keypair.CreatedTime = v.CreatedTime + obj.Keypair.UpdatedTime = v.UpdatedTime + + return &obj, nil +} + +func CreateKeypairs(logger *log.Logger, param requestTypes.CreateKeypairRequest) (*response.KeyPair, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkSshkeyParameters.NewCreateUserSshkeyParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + body := &sdkModels.CreateSshkeyRequest{ + Name: ¶m.Name, + Key: ¶m.Key, + } + req.WithBody(body) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("createkeypairs openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Sshkey.CreateUserSshkey(req, nil) + logger.Info("createkeypairs openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("createkeypairs openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + obj := response.KeyPair{} + // v := responseApi.Payload.Result + obj.Name = param.Name + // obj.KeypairId = v.KeypairId + + return &obj, nil +} + +func ModifyKeypair(logger *log.Logger, keypairId, name string) (bool, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkSshkeyParameters.NewModifyUserSshkeyParams() + req.WithTraceID(logid) + req.WithSshkeyID(keypairId) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + body := &sdkModels.ModifySshkeyRequest{ + Name: &name, + } + req.WithBody(body) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("ModifyUserSshkey openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Sshkey.ModifyUserSshkey(req, nil) + if err != nil { + logger.Info("ModifyUserSshkey openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + logger.Info("ModifyUserSshkey openapi response:", util.InterfaceToJson(responseApi)) + return responseApi.Payload.Result.Success, nil +} + +func DeleteKeypairs(logger *log.Logger, keypairID string) (bool, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkSshkeyParameters.NewDeleteUserSshkeyParams() + req.WithTraceID(logid) + req.WithSshkeyID(keypairID) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("deletekeypairs openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Sshkey.DeleteUserSshkey(req, nil) + if err != nil { + logger.Info("deletekeypairs openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + logger.Info("deletekeypairs openapi response:", util.InterfaceToJson(responseApi)) + return responseApi.Payload.Result.Success, nil +} diff --git a/bmp-console-api/logic/PartitionLogic/PartitionLogic.go b/bmp-console-api/logic/PartitionLogic/PartitionLogic.go new file mode 100644 index 0000000..c5d5ff5 --- /dev/null +++ b/bmp-console-api/logic/PartitionLogic/PartitionLogic.go @@ -0,0 +1,40 @@ +package PartitionLogic + +import ( + "errors" + + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + log "coding.jd.com/aidc-bmp/bmp_log" + + sdkDeviceTypeParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/device_type" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +func QueryDefaultSystemPartitions(logger *log.Logger, param requestTypes.QueryDefaultSystemPartitionRequest) ([]*sdkModels.Partition, error) { + + // language := logger.GetPoint("language").(string) + logid := logger.GetPoint("logid").(string) + request := sdkDeviceTypeParameters.NewDescribeDeviceTypeImagePartitionsParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + request.WithImageID(¶m.ImageID) + request.WithDeviceTypeID(¶m.DeviceTypeID) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("QueryDeviceTypeImagePartition openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.DeviceType.DescribeDeviceTypeImagePartitions(request, nil) + logger.Info("QueryDeviceTypeImagePartition openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("QueryDeviceTypeImagePartition openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + return responseApi.Payload.Result.SystemPartition, nil + +} diff --git a/bmp-console-api/logic/ProjectLogic/ProjectLogic.go b/bmp-console-api/logic/ProjectLogic/ProjectLogic.go new file mode 100644 index 0000000..6571ced --- /dev/null +++ b/bmp-console-api/logic/ProjectLogic/ProjectLogic.go @@ -0,0 +1,438 @@ +package ProjectLogic + +import ( + "errors" + "fmt" + "math/rand" + "strconv" + "time" + + "coding.jd.com/aidc-bmp/bmp-console-api/logic/BaseLogic" + UserLoigc "coding.jd.com/aidc-bmp/bmp-console-api/logic/UserLogic" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/excel" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + log "coding.jd.com/aidc-bmp/bmp_log" + "git.jd.com/cps-golang/ironic-common/exception" + + sdkProjectParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/project" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +func GetProjectById(logger *log.Logger, ProjectId string) (*sdkModels.Project, error) { + + // language := logger.GetPoint("language").(string) + logid := logger.GetPoint("logid").(string) + request := sdkProjectParameters.NewDescribeUserProjectParams() + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithProjectID(ProjectId) + logger.Info("GetProjectById openapi request:", util.InterfaceToJson(request)) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + responseApi, err := openApi.SdkClient.Project.DescribeUserProject(request, nil) + logger.Info("GetProjectById openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + fmt.Println("DescribeUserProject openapi error:", err.Error()) + logger.Info("DescribeUserProject openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + project := responseApi.Payload.Result.Project + if project == nil { + return nil, errors.New("openapi returns empty project") + } + return project, nil +} + +func CreateProject(logger *log.Logger, param *sdkModels.CreateProjectRequest) (string, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkProjectParameters.NewCreateUserProjectParams() + req.WithTraceID(logid) + req.WithBody(param) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("CreateProject openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Project.CreateUserProject(req, nil) + logger.Info("CreateProject openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + fmt.Println("CreateProject openapi error:", err.Error()) + logger.Info("CreateProject openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return "", err + } + return "", errors.New(respErr.Message) + } + return responseApi.Payload.Result.ProjectID, nil +} + +func ModifyProject(logger *log.Logger, param *sdkModels.ModifyProjectRequest, ProjectId string) error { + logid := logger.GetPoint("logid").(string) + req := sdkProjectParameters.NewModifyUserProjectParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithProjectID(ProjectId) + req.WithBody(param) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("ModifyProject openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Project.ModifyUserProject(req, nil) + logger.Info("ModifyProject openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + fmt.Println("ModifyProject openapi error:", err.Error()) + logger.Info("ModifyProject openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return err + } + return errors.New(respErr.Message) + } + return nil +} + +func ModifyProjectDescription(logger *log.Logger, param *sdkModels.ModifyProjectDescriptionRequest, ProjectId string) error { + logid := logger.GetPoint("logid").(string) + req := sdkProjectParameters.NewModifyUserProjectDescriptionParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithProjectID(ProjectId) + req.WithBody(param) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("ModifyProjectDescription openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Project.ModifyUserProjectDescription(req, nil) + logger.Info("ModifyProjectDescription openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + fmt.Println("ModifyProjectDescription openapi error:", err.Error()) + logger.Info("ModifyProjectDescription openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return err + } + return errors.New(respErr.Message) + } + return nil +} + +func DeleteProject(logger *log.Logger, ProjectId string) error { + logid := logger.GetPoint("logid").(string) + req := sdkProjectParameters.NewDeleteUserProjectParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithProjectID(ProjectId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("DeleteProject openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Project.DeleteUserProject(req, nil) + logger.Info("DeleteProject openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DeleteProject openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return err + } + return errors.New(respErr.Message) + } + return nil +} + +func GetProjectList(logger *log.Logger, param requestTypes.QueryProjectsRequest) (*sdkModels.ProjectList, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkProjectParameters.NewDescribeUserProjectsParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithPageNumber(¶m.PageNumber) + req.WithPageSize(¶m.PageSize) + if param.ExportType != "" || param.IsAll == "1" { + isAll := "1" + req.WithIsAll(&isAll) + } + var owned int64 = 0 + if param.Owned == "1" { + owned = 1 + } else if param.Owned == "2" { + owned = 2 + } else { + owned = 0 + } + req.Owned = &owned + if param.OwnerName != "" { + req.OwnerName = ¶m.OwnerName + } + if param.SharerName != "" { + req.SharerName = ¶m.SharerName + } + + req.WithOrderByCreatetime(¶m.OrderByCreatetime) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("GetProjectList openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Project.DescribeUserProjects(req, nil) + logger.Info("GetProjectList openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DeleteProject openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result, nil +} + +func ExportProject(logger *log.Logger, result []*sdkModels.Project) (fileName, downLoadFileName string) { + + language := logger.GetPoint("language").(string) + + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + for _, data := range result { + var shareStatus string + ownerText := "拥有者" + shareText := "共享者" + if logger.GetPoint("language").(string) == BaseLogic.EN_US { + ownerText = "Owner" + shareText = "collaborator" + } + if data.Owned == 1 { + shareStatus = ownerText + } else { + shareStatus = shareText + } + sheetData = append(sheetData, []string{ + data.ProjectName, + data.ProjectID, + shareStatus, + fmt.Sprintf("%d", data.InstanceCount), + data.CreatedTime, + data.UpdatedTime, + }) + } + exportProjectHeader := BaseLogic.ExportProjectHeader + if language == "en_US" { + exportProjectHeader = BaseLogic.ExportProjectHeaderEn + } + if err := e.SetSheetData("Sheet1", exportProjectHeader, sheetData); err != nil { + panic(exception.Exception{Msg: "新建excel失败", Status: BaseLogic.ERROR_CODE}) + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + downloadFileName := "project_list_" + time.Now().Format(BaseLogic.FormatDate) + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" //生成100000到100000+900000之间的随机数,左闭右开 + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Info("保存excel到本地失败" + err.Error()) + panic(exception.Exception{Msg: "保存excel到本地失败", Status: BaseLogic.ERROR_CODE}) + } + return fileName, downloadFileName +} + +func ShareProject(logger *log.Logger, ProjectId string, param requestTypes.ShareProjectRequest) error { + + logid := logger.GetPoint("logid").(string) + + ownUser, _ := UserLoigc.GetUserByName(logger, param.OwnerName) + if ownUser == nil { + return fmt.Errorf("param.OwnerName invalid") + } + shareUser, _ := UserLoigc.GetUserByName(logger, param.SharerName) + if shareUser == nil { + return fmt.Errorf("param.SharerName invalid") + } + + p := &sdkModels.ShareProjectRequest{ + OwnerID: &ownUser.UserID, + SharerID: &shareUser.UserID, + InstanceIDs: ¶m.InstanceIDs, + } + + req := sdkProjectParameters.NewShareUserProjectParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithProjectID(ProjectId) + + req.WithBody(p) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("ShareUserProject openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Project.ShareUserProject(req, nil) + logger.Info("ShareUserProject openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("ShareUserProject openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return err + } + return errors.New(respErr.Message) + } + return nil +} + +func CancelShareProject(logger *log.Logger, ProjectId string, param requestTypes.ShareProjectRequest) error { + logid := logger.GetPoint("logid").(string) + + ownUser, _ := UserLoigc.GetUserByName(logger, param.OwnerName) + if ownUser == nil { + return fmt.Errorf("param.OwnerName invalid") + } + shareUser, _ := UserLoigc.GetUserByName(logger, param.SharerName) + if shareUser == nil { + return fmt.Errorf("param.SharerName invalid") + } + + p := &sdkModels.CalcelShareProjectRequest{ + OwnerID: &ownUser.UserID, + SharerID: &shareUser.UserID, + } + + req := sdkProjectParameters.NewCancelShareUserProjectParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithProjectID(ProjectId) + req.WithBody(p) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("ShareUserProject openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Project.CancelShareUserProject(req, nil) + logger.Info("ShareUserProject openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("ShareUserProject openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return err + } + return errors.New(respErr.Message) + } + return nil +} + +func GetShareProjectInfo(logger *log.Logger, ProjectId string) (*sdkModels.ShareProjectInfo, error) { + logid := logger.GetPoint("logid").(string) + + req := sdkProjectParameters.NewDescribeShareProjectParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithProjectID(ProjectId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("DescribeShareProject openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Project.DescribeShareProject(req, nil) + logger.Info("DescribeShareProject openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeShareProject openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + return responseApi.Payload.Result, nil +} + +func MoveProject(logger *log.Logger, ProjectId string, param requestTypes.MoveProjectRequest) error { + + logid := logger.GetPoint("logid").(string) + + ownUser, _ := UserLoigc.GetUserByName(logger, param.OwnerName) + if ownUser == nil { + return fmt.Errorf("param.OwnerName invalid") + } + moverUser, _ := UserLoigc.GetUserByName(logger, param.MoverName) + if moverUser == nil { + return fmt.Errorf("param.MoverName invalid") + } + + p := &sdkModels.MoveProjectRequest{ + OwnerID: &ownUser.UserID, + MoverID: &moverUser.UserID, + } + + req := sdkProjectParameters.NewMoveUserProjectParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithProjectID(ProjectId) + req.WithBody(p) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("MoveUserProject openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Project.MoveUserProject(req, nil) + logger.Info("MoveUserProject openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("MoveUserProject openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return err + } + return errors.New(respErr.Message) + } + return nil +} + +func MoveInstances(logger *log.Logger, param *requestTypes.MoveInstancesRequest) error { + + logid := logger.GetPoint("logid").(string) + + ownUser, _ := UserLoigc.GetUserByName(logger, param.OwnerName) + if ownUser == nil { + return fmt.Errorf("param.OwnerName invalid") + } + moverUser, _ := UserLoigc.GetUserByName(logger, param.MoverName) + if moverUser == nil { + return fmt.Errorf("param.MoverName invalid") + } + ownerProject, _ := GetProjectById(logger, param.OwnerProjectID) + if ownerProject == nil { + return fmt.Errorf("param.OwnerProjectID invalid") + } + moverProject, _ := GetProjectById(logger, param.MoverProjectID) + if moverProject == nil { + return fmt.Errorf("param.MoverProjectID invalid") + } + + p := &sdkModels.MoveInstancesRequest{ + OwnerID: &ownUser.UserID, + MoverID: &moverUser.UserID, + OwnerProjectID: ¶m.OwnerProjectID, + MoverProjectID: ¶m.MoverProjectID, + InstanceIDs: ¶m.InstanceIDs, + } + + req := sdkProjectParameters.NewMoveUserInstancesParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithBody(p) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("MoveUserInstance openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Project.MoveUserInstances(req, nil) + logger.Info("MoveUserInstance openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("MoveUserInstance openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return err + } + return errors.New(respErr.Message) + } + return nil +} diff --git a/bmp-console-api/logic/RaidLogic/RaidLogic.go b/bmp-console-api/logic/RaidLogic/RaidLogic.go new file mode 100644 index 0000000..30d76fa --- /dev/null +++ b/bmp-console-api/logic/RaidLogic/RaidLogic.go @@ -0,0 +1,123 @@ +package RaidLogic + +import ( + "errors" + "strconv" + + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + + log "coding.jd.com/aidc-bmp/bmp_log" + + sdkDeviceTypeParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/device_type" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +func QueryVolumesRaids(logger *log.Logger, param requestTypes.QueryVolumeRaidsRequest) ([]*response.VolumeRaid, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkDeviceTypeParameters.NewDescribeVolumesRaidsParams() + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithDeviceTypeID(¶m.DeviceTypeID) + request.WithVolumeType(¶m.VolumeType) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + //request.SetOsType(param.ImageType) + logger.Info("DescribeVolumesRaids openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.DeviceType.DescribeVolumesRaids(request, nil) + logger.Info("DescribeVolumesRaids openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeVolumesRaids openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + res := []*response.VolumeRaid{} + for _, v := range responseApi.Payload.Result { + volumeSize, err := strconv.ParseFloat(v.VolumeSize, 64) + if err != nil { + logger.Warnf("QueryVolumesRaids parse VolumeSize error, volume_id:%s, volume_size:%s", v.VolumeID, v.VolumeSize) + } + item := &response.VolumeRaid{ + // 卷uuid + VolumeID: v.VolumeID, + // 设备类型uuid + DeviceTypeID: v.DeviceTypeID, + // 卷名称 + VolumeName: v.VolumeName, + // 卷类型:系统卷,数据卷 + VolumeType: v.VolumeType, + // 硬盘类型(SSD,HDD) + DiskType: v.DiskType, + // 接口类型(SATA,SAS,NVME,不限制) + InterfaceType: v.InterfaceType, + // 单盘大小(最小容量) + VolumeSize: volumeSize, + // 硬盘单位(GB,TB) + VolumeUnit: v.VolumeUnit, + // 硬盘数量(最低块数) + VolumeAmount: int(v.VolumeAmount), + //支持的raid模式 + } + rs := []*response.Raid{} + for _, r := range v.Raids { + + rs = append(rs, &response.Raid{ + RaidCan: r.RaidCan, + RaidID: r.RaidID, + RaidName: r.RaidName, + //容量大小描述 + Detail: GetDiskDetailByRaid(v, &models.Raid{ + RaidID: r.RaidID, + Name: r.RaidName, + }), + }) + } + item.Raids = rs + res = append(res, item) + } + return res, nil + +} + +func GetDiskDetailByRaid(v *models.VolumeRaids, raid *models.Raid) string { + + volumeDetail := "" + // avaliableValue := .0 + all := 0.0 + volumeSize, _ := strconv.ParseFloat(v.VolumeSize, 64) + size := volumeSize + all = volumeSize * float64(v.VolumeAmount) + if raid != nil { + if util.InArray(raid.Name, []string{"RAID1", "RAID10"}) { + all = all / 2 + } else if util.InArray(raid.Name, []string{"RAID51H"}) { + all = volumeSize * float64(v.VolumeAmount-2) + } else if util.InArray(raid.Name, []string{"RAID5"}) { + all = volumeSize * float64(v.VolumeAmount-1) + } + } + var allStr, sizeStr string + if v.VolumeUnit == "TB" { //保留两位小数 + allStr = strconv.FormatFloat(all, 'f', 2, 64) + sizeStr = strconv.FormatFloat(size, 'f', 2, 64) + } else { //不保留小数 + allStr = strconv.Itoa(int(all)) + sizeStr = strconv.Itoa(int(size)) + + } + + volumeDetail = allStr + v.VolumeUnit + "(" + + (strconv.Itoa(int(v.VolumeAmount)) + "*" + sizeStr + v.VolumeUnit) + " " + v.InterfaceType + ")" + + //NVME另外算法 TODO + return volumeDetail + +} diff --git a/bmp-console-api/logic/TimezoneLogic/TimezoneLogic.go b/bmp-console-api/logic/TimezoneLogic/TimezoneLogic.go new file mode 100644 index 0000000..664a382 --- /dev/null +++ b/bmp-console-api/logic/TimezoneLogic/TimezoneLogic.go @@ -0,0 +1,245 @@ +package TimezoneLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/constants" + responseTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +var TimeZoneDictZh responseTypes.OrderedJsonDict = responseTypes.OrderedJsonDict{ + M: map[string]string{ + "Pacific/Pago_Pago": "(GMT-11:00)帕果帕果", + "US/Hawaii": "(GMT-10:00)夏威夷时间", + "US/Pacific": "(GMT-08:00)太平洋时间", + "America/Tijuana": "(GMT-08:00)太平洋时间-提华纳", + "US/Mountain": "(GMT-07:00)山区时间", + "US/Arizona": "(GMT-07:00)山区时间-亚利桑那州", + "America/Chihuahua": "(GMT-07:00)山区时间-奇瓦瓦,马萨特兰", + "US/Central": "(GMT-07:00)中部时间", + "America/Mexico_City": "(GMT-06:00)中部时间-墨西哥城", + "America/Regina": "(GMT-06:00)中部时间-里贾纳", + "America/Guatemala": "(GMT-06:00)中部时间-里贾纳", + "America/Bogota": "(GMT-05:00)波哥大", + "US/Eastern": "(GMT-05:00)东部时间", + "America/Lima": "(GMT-05:00)利马", + "America/Caracas": "(GMT-04:30)加拉加斯", + "America/Halifax": "(GMT-04:00)大西洋时间-哈利法克斯", + "America/Guyana": "(GMT-04:00)圭亚那", + "America/La_Paz": "(GMT-04:00)拉巴斯", + "America/Buenos_Aires": "(GMT-03:00)布宜诺斯艾利斯", + "America/Godthab": "(GMT-03:00)戈特霍布", + "America/Montevideo": "(GMT-03:00)蒙得维的亚", + "Canada/Newfoundland": "(GMT-03:30)纽芬兰时间-圣约翰", + "America/Santiago": "(GMT-03:00)圣地亚哥", + "America/Sao_Paulo": "(GMT-02:00)圣保罗", + "Atlantic/South_Georgia": "(GMT-02:00)南乔治亚州", + "Atlantic/Azores": "(GMT-01:00)亚速尔群岛", + "Atlantic/Cape_Verde": "(GMT-01:00)佛得角", + "Africa/Casablanca": "(GMT+00:00)卡萨布兰卡", + "Europe/Dublin": "(GMT+00:00)都柏林", + "Europe/Lisbon": "(GMT+00:00)里斯本", + "Europe/London": "(GMT+00:00)伦敦", + "Africa/Monrovia": "(GMT+00:00)蒙罗维亚", + "Africa/Algiers": "(GMT+01:00)阿尔及尔", + "Europe/Amsterdam": "(GMT+01:00)阿姆斯特丹", + "Europe/Berlin": "(GMT+01:00)柏林", + "Europe/Brussels": "(GMT+01:00)布鲁塞尔", + "Europe/Budapest": "(GMT+01:00)布达佩斯", + "Europe/Belgrade": "(GMT+01:00)中欧时间-贝尔格莱德", + "Europe/Prague": "(GMT+01:00)中欧时间-布拉格", + "Europe/Copenhagen": "(GMT+01:00)哥本哈根", + "Europe/Madrid": "(GMT+01:00)马德里", + "Europe/Paris": "(GMT+01:00)巴黎", + "Europe/Rome": "(GMT+01:00)罗马", + "Europe/Stockholm": "(GMT+01:00)斯德哥尔摩", + "Europe/Vienna": "(GMT+01:00)维也纳", + "Europe/Warsaw": "(GMT+01:00)华沙", + "Europe/Athens": "(GMT+02:00)雅典", + "Europe/Bucharest": "(GMT+02:00)布加勒斯特", + "Africa/Cairo": "(GMT+02:00)开罗", + "Europe/Helsinki": "(GMT+02:00)赫尔辛基", + "Asia/Jerusalem": "(GMT+02:00)耶路撒冷", + "Africa/Johannesburg": "(GMT+02:00)约翰内斯堡", + "Europe/Kiev": "(GMT+02:00)基辅", + "Europe/Kaliningrad": "(GMT+02:00)莫斯科-加里宁格勒", + "Europe/Riga": "(GMT+02:00)里加", + "Europe/Sofia": "(GMT+02:00)索非亚", + "Europe/Tallinn": "(GMT+02:00)塔林", + "Europe/Vilnius": "(GMT+02:00)维尔纽斯", + "Asia/Baghdad": "(GMT+03:00)巴格达", + "Asia/Istanbul": "(GMT+03:00)伊斯坦布尔", + "Europe/Minsk": "(GMT+03:00)明斯克", + "Asia/Riyadh": "(GMT+03:00)利雅得", + "Europe/Moscow": "(GMT+03:00)莫斯科-莫斯科", + "Asia/Tehran": "(GMT+03:30)德黑兰", + "Asia/Baku": "(GMT+04:00)巴库", + "Europe/Samara": "(GMT+04:00)莫斯科-萨马拉", + "Asia/Tbilisi": "(GMT+04:00)第比利斯", + "Asia/Yerevan": "(GMT+04:00)埃里温", + "Asia/Kabul": "(GMT+04:30)喀布尔", + "Asia/Karachi": "(GMT+05:00)卡拉奇", + "Asia/Yekaterinburg": "(GMT+05:00)莫斯科-叶卡捷琳堡", + "Asia/Tashkent": "(GMT+05:00)塔什干", + "Asia/Colombo": "(GMT+05:30)科伦坡", + "Asia/Almaty": "(GMT+06:00)阿拉木图", + "Asia/Dhaka": "(GMT+06:00)达卡", + "Asia/Rangoon": "(GMT+06:30)仰光", + "Asia/Bangkok": "(GMT+07:00)曼谷", + "Asia/Jakarta": "(GMT+07:00)雅加达", + "Asia/Krasnoyarsk": "(GMT+07:00)莫斯科-克拉斯诺亚尔斯克", + "Asia/Shanghai": "(GMT+08:00)中国时间-北京", + "Hongkong": "(GMT+08:00)香港", + "Asia/Kuala_Lumpur": "(GMT+08:00)吉隆坡", + "Asia/Irkutsk": "(GMT+08:00)莫斯科-伊尔库茨克", + "Asia/Singapore": "(GMT+08:00)新加坡", + "Asia/Taipei": "(GMT+08:00)台北", + "Asia/Ulaanbaatar": "(GMT+08:00)乌兰巴托", + "Australia/Perth": "(GMT+08:00)西部时间-珀斯", + "Asia/Yakutsk": "(GMT+09:00)莫斯科-雅库茨克", + "Asia/Seoul": "(GMT+09:00)首尔", + "Asia/Tokyo": "(GMT+09:00)东京", + "Australia/Darwin": "(GMT+09:30)中部时间-达尔文", + "Australia/Brisbane": "(GMT+10:00)东部时间-布里斯班", + "Pacific/Guam": "(GMT+10:00)关岛", + "Asia/Magadan": "(GMT+10:00)莫斯科-马加丹", + "Asia/Sakhalin": "(GMT+10:00)莫斯科-南萨哈林斯克", + "Pacific/Port_Moresby": "(GMT+10:00)莫尔兹比港", + "Australia/Adelaide": "(GMT+10:30)中部时间-阿德莱德", + "Australia/Hobart": "(GMT+11:00)东部时间-霍巴特", + "Australia/Melbourne": "(GMT+11:00)东部时间-悉尼墨尔本", + "Pacific/Guadalcanal": "(GMT+11:00)Guadalcanal", + "Pacific/Noumea": "(GMT+11:00)努美阿", + "Pacific/Majuro": "(GMT+12:00)马朱罗", + "Asia/Kamchatka": "(GMT+12:00)莫斯科-堪察加彼得罗巴甫洛夫斯克", + "Pacific/Auckland": "(GMT+13:00)奥克兰", + "Pacific/Fakaofo": "(GMT+13:00)法考福", + "Pacific/Fiji": "(GMT+13:00)斐济", + "Pacific/Tongatapu": "(GMT+13:00)汤加塔布群岛", + "Pacific/Apia": "(GMT+14:00)阿皮亚", + }, + Keys: []string{"Pacific/Pago_Pago", "US/Hawaii", "US/Pacific", "America/Tijuana", "US/Mountain", "US/Arizona", "America/Chihuahua", "US/Central", "America/Mexico_City", "America/Regina", "America/Guatemala", "America/Bogota", "US/Eastern", "America/Lima", "America/Caracas", "America/Halifax", "America/Guyana", "America/La_Paz", "America/Buenos_Aires", "America/Godthab", "America/Montevideo", "Canada/Newfoundland", "America/Santiago", "America/Sao_Paulo", "Atlantic/South_Georgia", "Atlantic/Azores", "Atlantic/Cape_Verde", "Africa/Casablanca", "Europe/Dublin", "Europe/Lisbon", "Europe/London", "Africa/Monrovia", "Africa/Algiers", "Europe/Amsterdam", "Europe/Berlin", "Europe/Brussels", "Europe/Budapest", "Europe/Belgrade", "Europe/Prague", "Europe/Copenhagen", "Europe/Madrid", "Europe/Paris", "Europe/Rome", "Europe/Stockholm", "Europe/Vienna", "Europe/Warsaw", "Europe/Athens", "Europe/Bucharest", "Africa/Cairo", "Europe/Helsinki", "Asia/Jerusalem", "Africa/Johannesburg", "Europe/Kiev", "Europe/Kaliningrad", "Europe/Riga", "Europe/Sofia", "Europe/Tallinn", "Europe/Vilnius", "Asia/Baghdad", "Asia/Istanbul", "Europe/Minsk", "Asia/Riyadh", "Europe/Moscow", "Asia/Tehran", "Asia/Baku", "Europe/Samara", "Asia/Tbilisi", "Asia/Yerevan", "Asia/Kabul", "Asia/Karachi", "Asia/Yekaterinburg", "Asia/Tashkent", "Asia/Colombo", "Asia/Almaty", "Asia/Dhaka", "Asia/Rangoon", "Asia/Bangkok", "Asia/Jakarta", "Asia/Krasnoyarsk", "Asia/Shanghai", "Hongkong", "Asia/Kuala_Lumpur", "Asia/Irkutsk", "Asia/Singapore", "Asia/Taipei", "Asia/Ulaanbaatar", "Australia/Perth", "Asia/Yakutsk", "Asia/Seoul", "Asia/Tokyo", "Australia/Darwin", "Australia/Brisbane", "Pacific/Guam", "Asia/Magadan", "Asia/Sakhalin", "Pacific/Port_Moresby", "Australia/Adelaide", "Australia/Hobart", "Australia/Melbourne", "Pacific/Guadalcanal", "Pacific/Noumea", "Pacific/Majuro", "Asia/Kamchatka", "Pacific/Auckland", "Pacific/Fakaofo", "Pacific/Fiji", "Pacific/Tongatapu", "Pacific/Apia"}, +} + +var TimeZoneDictEn responseTypes.OrderedJsonDict = responseTypes.OrderedJsonDict{ + M: map[string]string{ + "Pacific/Pago_Pago": "(GMT-11:00) Pago Pago", + "US/Hawaii": "(GMT-10:00) Hawaii Time", + "US/Pacific": "(GMT-08:00) Pacific Time", + "America/Tijuana": "(GMT-08:00) Pacific Time - Tijuana", + "US/Mountain": "(GMT-07:00) Mountain Time", + "US/Arizona": "(GMT-07:00) Mountain Time - Arizona", + "America/Chihuahua": "(GMT-07:00) Mountain Time - Chihuahua, Mazatlan", + "US/Central": "(GMT-06:00) Central Time", + "America/Mexico_City": "(GMT-06:00) Central Time - Mexico City", + "America/Regina": "(GMT-06:00) Central Time - Regina", + "America/Guatemala": "(GMT-06:00) Guatemala", + "America/Bogota": "(GMT-05:00) Bogota", + "US/Eastern": "(GMT-05:00) Eastern Time", + "America/Lima": "(GMT-05:00) Lima", + "America/Caracas": "(GMT-04:30) Caracas", + "America/Halifax": "(GMT-04:00) Atlantic Time - Halifax", + "America/Guyana": "(GMT-04:00) Guyana", + "America/La_Paz": "(GMT-04:00) La Paz", + "America/Buenos_Aires": "(GMT-03:00) Buenos Aires", + "America/Godthab": "(GMT-03:00) Godthab", + "America/Montevideo": "(GMT-03:00) Montevideo", + "Canada/Newfoundland": "(GMT-03:30) Newfoundland Time - St. Johns", + "America/Santiago": "(GMT-03:00) Santiago", + "America/Sao_Paulo": "(GMT-02:00) Sao Paulo", + "Atlantic/South_Georgia": "(GMT-02:00) South Georgia", + "Atlantic/Azores": "(GMT-01:00) Azores", + "Atlantic/Cape_Verde": "(GMT-01:00) Cape Verde", + "Africa/Casablanca": "(GMT+00:00) Casablanca", + "Europe/Dublin": "(GMT+00:00) Dublin", + "Europe/Lisbon": "(GMT+00:00) Lisbon", + "Europe/London": "(GMT+00:00) London", + "Africa/Monrovia": "(GMT+00:00) Monrovia", + "Africa/Algiers": "(GMT+01:00) Algiers", + "Europe/Amsterdam": "(GMT+01:00) Amsterdam", + "Europe/Berlin": "(GMT+01:00) Berlin", + "Europe/Brussels": "(GMT+01:00) Brussels", + "Europe/Budapest": "(GMT+01:00) Budapest", + "Europe/Belgrade": "(GMT+01:00) Central European Time - Belgrade", + "Europe/Prague": "(GMT+01:00) Central European Time - Prague", + "Europe/Copenhagen": "(GMT+01:00) Copenhagen", + "Europe/Madrid": "(GMT+01:00) Madrid", + "Europe/Paris": "(GMT+01:00) Paris", + "Europe/Rome": "(GMT+01:00) Rome", + "Europe/Stockholm": "(GMT+01:00) Stockholm", + "Europe/Vienna": "(GMT+01:00) Vienna", + "Europe/Warsaw": "(GMT+01:00) Warsaw", + "Europe/Athens": "(GMT+02:00) Athens", + "Europe/Bucharest": "(GMT+02:00) Bucharest", + "Africa/Cairo": "(GMT+02:00) Cairo", + "Europe/Helsinki": "(GMT+02:00) Helsinki", + "Asia/Jerusalem": "(GMT+02:00) Jerusalem", + "Africa/Johannesburg": "(GMT+02:00) Johannesburg", + "Europe/Kiev": "(GMT+02:00) Kiev", + "Europe/Kaliningrad": "(GMT+02:00) Moscow-01 - Kaliningrad", + "Europe/Riga": "(GMT+02:00) Riga", + "Europe/Sofia": "(GMT+02:00) Sofia", + "Europe/Tallinn": "(GMT+02:00) Tallinn", + "Europe/Vilnius": "(GMT+02:00) Vilnius", + "Asia/Baghdad": "(GMT+03:00) Baghdad", + "Asia/Istanbul": "(GMT+03:00) Istanbul", + "Europe/Minsk": "(GMT+03:00) Minsk", + "Asia/Riyadh": "(GMT+03:00) Riyadh", + "Europe/Moscow": "(GMT+03:00) Moscow+00 - Moscow", + "Asia/Tehran": "(GMT+03:30) Tehran", + "Asia/Baku": "(GMT+04:00) Baku", + "Europe/Samara": "(GMT+04:00) Moscow+01 - Samara", + "Asia/Tbilisi": "(GMT+04:00) Tbilisi", + "Asia/Yerevan": "(GMT+04:00) Yerevan", + "Asia/Kabul": "(GMT+04:30) Kabul", + "Asia/Karachi": "(GMT+05:00) Karachi", + "Asia/Yekaterinburg": "(GMT+05:00) Moscow+02 - Yekaterinburg", + "Asia/Tashkent": "(GMT+05:00) Tashkent", + "Asia/Colombo": "(GMT+05:30) Colombo", + "Asia/Almaty": "(GMT+06:00) Almaty", + "Asia/Dhaka": "(GMT+06:00) Dhaka", + "Asia/Rangoon": "(GMT+06:30) Rangoon", + "Asia/Bangkok": "(GMT+07:00) Bangkok", + "Asia/Jakarta": "(GMT+07:00) Jakarta", + "Asia/Krasnoyarsk": "(GMT+07:00) Moscow+04 - Krasnoyarsk", + "Asia/Shanghai": "(GMT+08:00) China Time - Beijing", + "Hongkong": "(GMT+08:00) Hong Kong", + "Asia/Kuala_Lumpur": "(GMT+08:00) Kuala Lumpur", + "Asia/Irkutsk": "(GMT+08:00) Moscow+05 - Irkutsk", + "Asia/Singapore": "(GMT+08:00) Singapore", + "Asia/Taipei": "(GMT+08:00) Taipei", + "Asia/Ulaanbaatar": "(GMT+08:00) Ulaanbaatar", + "Australia/Perth": "(GMT+08:00) Western Time - Perth", + "Asia/Yakutsk": "(GMT+09:00) Moscow+06 - Yakutsk", + "Asia/Seoul": "(GMT+09:00) Seoul", + "Asia/Tokyo": "(GMT+09:00) Tokyo", + "Australia/Darwin": "(GMT+09:30) Central Time - Darwin", + "Australia/Brisbane": "(GMT+10:00) Eastern Time - Brisbane", + "Pacific/Guam": "(GMT+10:00) Guam", + "Asia/Magadan": "(GMT+10:00) Moscow+07 - Magadan", + "Asia/Sakhalin": "(GMT+10:00) Moscow+07 - Yuzhno-Sakhalinsk", + "Pacific/Port_Moresby": "(GMT+10:00) Port Moresby", + "Australia/Adelaide": "(GMT+10:30) Central Time - Adelaide", + "Australia/Hobart": "(GMT+11:00) Eastern Time - Hobart", + "Australia/Melbourne": "(GMT+11:00) Eastern Time - Melbourne, Sydney", + "Pacific/Guadalcanal": "(GMT+11:00) Guadalcanal", + "Pacific/Noumea": "(GMT+11:00) Noumea", + "Pacific/Majuro": "(GMT+12:00) Majuro", + "Asia/Kamchatka": "(GMT+12:00) Moscow+09 - Petropavlovsk-Kamchatskiy", + "Pacific/Auckland": "(GMT+13:00) Auckland", + "Pacific/Fakaofo": "(GMT+13:00) Fakaofo", + "Pacific/Fiji": "(GMT+13:00) Fiji", + "Pacific/Tongatapu": "(GMT+13:00) Tongatapu", + "Pacific/Apia": "(GMT+14:00) Apia", + }, + Keys: []string{"Pacific/Pago_Pago", "US/Hawaii", "US/Pacific", "America/Tijuana", "US/Mountain", "US/Arizona", "America/Chihuahua", "US/Central", "America/Mexico_City", "America/Regina", "America/Guatemala", "America/Bogota", "US/Eastern", "America/Lima", "America/Caracas", "America/Halifax", "America/Guyana", "America/La_Paz", "America/Buenos_Aires", "America/Godthab", "America/Montevideo", "Canada/Newfoundland", "America/Santiago", "America/Sao_Paulo", "Atlantic/South_Georgia", "Atlantic/Azores", "Atlantic/Cape_Verde", "Africa/Casablanca", "Europe/Dublin", "Europe/Lisbon", "Europe/London", "Africa/Monrovia", "Africa/Algiers", "Europe/Amsterdam", "Europe/Berlin", "Europe/Brussels", "Europe/Budapest", "Europe/Belgrade", "Europe/Prague", "Europe/Copenhagen", "Europe/Madrid", "Europe/Paris", "Europe/Rome", "Europe/Stockholm", "Europe/Vienna", "Europe/Warsaw", "Europe/Athens", "Europe/Bucharest", "Africa/Cairo", "Europe/Helsinki", "Asia/Jerusalem", "Africa/Johannesburg", "Europe/Kiev", "Europe/Kaliningrad", "Europe/Riga", "Europe/Sofia", "Europe/Tallinn", "Europe/Vilnius", "Asia/Baghdad", "Asia/Istanbul", "Europe/Minsk", "Asia/Riyadh", "Europe/Moscow", "Asia/Tehran", "Asia/Baku", "Europe/Samara", "Asia/Tbilisi", "Asia/Yerevan", "Asia/Kabul", "Asia/Karachi", "Asia/Yekaterinburg", "Asia/Tashkent", "Asia/Colombo", "Asia/Almaty", "Asia/Dhaka", "Asia/Rangoon", "Asia/Bangkok", "Asia/Jakarta", "Asia/Krasnoyarsk", "Asia/Shanghai", "Hongkong", "Asia/Kuala_Lumpur", "Asia/Irkutsk", "Asia/Singapore", "Asia/Taipei", "Asia/Ulaanbaatar", "Australia/Perth", "Asia/Yakutsk", "Asia/Seoul", "Asia/Tokyo", "Australia/Darwin", "Australia/Brisbane", "Pacific/Guam", "Asia/Magadan", "Asia/Sakhalin", "Pacific/Port_Moresby", "Australia/Adelaide", "Australia/Hobart", "Australia/Melbourne", "Pacific/Guadalcanal", "Pacific/Noumea", "Pacific/Majuro", "Asia/Kamchatka", "Pacific/Auckland", "Pacific/Fakaofo", "Pacific/Fiji", "Pacific/Tongatapu", "Pacific/Apia"}, +} + +func GetTimeZoneList(logger *log.Logger) responseTypes.OrderedJsonDict { + + language := logger.GetPoint("language").(string) + if language == constants.LANGUAGE_EN { + return TimeZoneDictEn + } else { + return TimeZoneDictZh + } +} diff --git a/bmp-console-api/logic/UserLogic/UserLogic.go b/bmp-console-api/logic/UserLogic/UserLogic.go new file mode 100644 index 0000000..fce66d1 --- /dev/null +++ b/bmp-console-api/logic/UserLogic/UserLogic.go @@ -0,0 +1,370 @@ +package UserLoigc + +import ( + "encoding/base64" + "errors" + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-console-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + sdkProjectParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/project" + sdkUserParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/user" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +const CONSOLE_ROLE_ID = "role-user-uuid-01" +const ADMIN_ROLE_ID = "role-admin-uuid-01" + +func GetUserByName(logger *log.Logger, username string) (*sdkModels.User, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewDescribeUserByNameParams() + req.WithTraceID(logid) + // userId := logger.GetPoint("userId").(string) + // req.WithBmpUserID(&userId) + req.WithUserName(username) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + resp, err := openApi.SdkClient.User.DescribeUserByName(req, nil) + if err != nil { + + logger.Warn("DescribeUserByName openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + fmt.Println("DescribeUserByName error:", err.Error()) + return nil, err + } + fmt.Println("DescribeUserByName error:", respErr.Message) + return nil, errors.New(respErr.Message) + } + return resp.Payload.Result.User, nil + +} + +// 【用户管理】【用户详情】 +func GetUserInfo(logger *log.Logger) (*response.User, error) { + userId := logger.GetPoint("userId").(string) + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewDescribeLocalUserParams() + req.WithTraceID(logid) + req.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + responseApi, err := openApi.SdkClient.User.DescribeLocalUser(req, nil) + if err != nil { + logger.Info("DescribeLocalUser openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + var v = responseApi.Payload.Result.User + obj := response.User{} + obj.ID = int64(v.ID) + obj.UserID = v.UserID + obj.UserName = v.UserName + obj.Email = v.Email + obj.Timezone = v.Timezone + obj.Language = v.Language + obj.DefaultProjectID = v.DefaultProjectID + obj.DefaultProjectName = v.DefaultProjectName + obj.Description = v.Description + obj.PhoneNumber = v.PhoneNumber + obj.PhonePrefix = v.PhonePrefix + obj.RoleID = v.RoleID + obj.RoleName = v.RoleName + obj.CreatedBy = v.CreatedBy + obj.CreatedTime = v.CreatedTime + obj.UpdatedBy = v.UpdatedBy + obj.UpdatedBy = v.UpdatedTime + obj.LicenseExist = true + obj.LicenseModels = []string{"带内监控管理", "带外监控管理"} + + return &obj, nil +} + +// 【用户管理】【修改密码】 +func ModifyUserPassword(logger *log.Logger, userID string, param *requestTypes.UpdatePasswordRequest) (bool, error) { + + fmt.Println("[DEBUG] ORIGIN OLD PASSWORD IS:", param.OldPassword) + //前端传过来的是加密并base64过的 + pv, err := base64.StdEncoding.DecodeString(param.OldPassword) + if err != nil { + return false, errors.New("parse old password error:" + err.Error()) + } + pv, err = util.AesDecrypt(pv) + if err != nil { + return false, errors.New("old password aes decode error:" + err.Error()) + } + param.OldPassword = string(pv) + fmt.Println("[DEBUG] PARSED OLD PASSWORD IS:", param.OldPassword) + //// + fmt.Println("[DEBUG] ORIGIN PASSWORD IS:", param.Password) + //前端传过来的是加密并base64过的 + pv, err = base64.StdEncoding.DecodeString(param.Password) + if err != nil { + return false, errors.New("parse password error:" + err.Error()) + } + pv, err = util.AesDecrypt(pv) + if err != nil { + return false, errors.New("password aes decode error:" + err.Error()) + } + param.Password = string(pv) + fmt.Println("[DEBUG] PARSED PASSWORD IS:", param.Password) + + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewModifyLocalUserPasswordParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + + body := sdkModels.ModifyUserPasswordRequest{ + Password: ¶m.Password, + OldPassword: ¶m.OldPassword, + } + req.WithBody(&body) + + res, err := openApi.SdkClient.User.ModifyLocalUserPassword(req, nil) + if err != nil { + logger.Info("ModifyLocalUserPassword openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return res.Payload.Result.Success, nil +} + +// 【用户管理】【编辑用户信息】 +func ModifyUserInfo(logger *log.Logger, userID string, param *requestTypes.ModifyUserInfoRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewModifyLocalUserParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + + body := sdkModels.ModifyLocalUserRequest{ + DefaultProjectID: param.DefaultProjectID, + //Description: param.Description, + Email: param.Email, + Language: param.Language, + PhonePrefix: param.PhonePrefix, + PhoneNumber: param.PhoneNumber, + Timezone: param.Timezone, + } + req.WithBody(&body) + + res, err := openApi.SdkClient.User.ModifyLocalUser(req, nil) + if err != nil { + logger.Info("ModifyLocalUserPassword openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return res.Payload.Result.Success, nil +} + +func VerifyUser(logger *log.Logger, username, password string) (bool, error) { + + fmt.Println("[DEBUG] ORIGIN PASSWORD IS:", password) + //前端传过来的是加密并base64过的 + pv, err := base64.StdEncoding.DecodeString(password) + if err != nil { + return false, errors.New("parse password error:" + err.Error()) + } + pv, err = util.AesDecrypt(pv) + if err != nil { + return false, errors.New("password aes decode error:" + err.Error()) + } + password = string(pv) + fmt.Println("[DEBUG] PARSED PASSWORD IS:", password) + + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewVerifyUserParams() + req.WithTraceID(logid) + + var roleId string = CONSOLE_ROLE_ID + + body := &sdkModels.VerifyUserRequest{ + UserName: &username, + Password: &password, + RoleID: &roleId, + } + req.WithBody(body) + + logger.Info("VerifyUser req:", util.InterfaceToJson(req)) + resp, err := openApi.SdkClient.User.VerifyUser(req, nil) + logger.Info("VerifyUser resp:", util.InterfaceToJson(resp)) + if err != nil { + logger.Info("VerifyUser openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return resp.Payload.Result.Success, nil +} + +func GetConsoleAccessUserList(logger *log.Logger, userId string) ([]*sdkModels.User, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkUserParameters.NewDescribeUsersParams() + request.WithTraceID(logid) + request.WithBmpUserID(&userId) + consoleAccessRoles := strings.Join([]string{ADMIN_ROLE_ID, CONSOLE_ROLE_ID}, ",") + request.WithRoleID(&consoleAccessRoles) + isAll := "1" + request.WithIsAll(&isAll) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + //request.SetOsType(param.ImageType) + logger.Info("DescribeUsers openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.User.DescribeUsers(request, nil) + logger.Info("DescribeUsers openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeUsers openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + users := []*sdkModels.User{} + for _, v := range responseApi.Payload.Result.Users { + if v.UserID != userId { + users = append(users, v) + } + } + return users, nil +} + +func CheckUserConsoleAccess(logger *log.Logger, userId string, req requestTypes.CheckUserConsoleAccessRequest) (bool, error) { + + //不能校验自己 + if userId == req.CheckedUserId { + return false, fmt.Errorf("param invalided") + } + + users, err := GetConsoleAccessUserList(logger, userId) + if err != nil { + return false, err + } + for _, v := range users { + if v.UserID == req.CheckedUserId { + return true, nil + } + + } + return false, nil +} + +func CheckUserConsoleAccessByName(logger *log.Logger, userId string, req requestTypes.CheckUserConsoleAccessByNameRequest) (bool, error) { + + isEn := logger.GetPoint("language").(string) == BaseLogic.EN_US + + var errMsg string + u, _ := GetUserInfo(logger) + if u == nil { + if isEn { + errMsg = "no operator user info found" + } else { + errMsg = "未获取到操作用户信息" + } + return false, fmt.Errorf(errMsg) + } + if u.UserName == req.CheckedUserName { + if isEn { + errMsg = "cannot be project owner" + } else { + errMsg = "不能是项目拥有者本人" + } + return false, fmt.Errorf(errMsg) + } + + u1, _ := GetUserByName(logger, req.CheckedUserName) + if u1 == nil { + if isEn { + errMsg = "user input not exist, re input please" + } else { + errMsg = "该用户不存在,请重新输入" + } + return false, fmt.Errorf(errMsg) + } + + if req.Operation == "move" { //项目转移 + + } else if req.Operation == "share" { //项目共享,可以多次共享 + // s, _ := GetShareProjectInfo(logger, req.ProjectID) + // for _, v := range s.Shares { + // if v.SharedUserName == req.CheckedUserName { + // if isEn { + // errMsg = "project already shared to the user" + // } else { + // errMsg = "该用户已经添加共享" + // } + // return false, fmt.Errorf(errMsg) + // } + // } + } + users, err := GetConsoleAccessUserList(logger, userId) + if err != nil { + logger.Warnf("CheckUserConsoleAccessByName.GetConsoleAccessUserList error:%s", err.Error()) + } + + for _, v := range users { + if v.UserName == req.CheckedUserName { + return true, nil + } + } + + if isEn { + errMsg = "the user is non-console role, re input please" + } else { + errMsg = "该用户不是 user 角色,请重新输入" + } + return false, fmt.Errorf(errMsg) + +} + +func GetShareProjectInfo(logger *log.Logger, ProjectId string) (*sdkModels.ShareProjectInfo, error) { + logid := logger.GetPoint("logid").(string) + + req := sdkProjectParameters.NewDescribeShareProjectParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithProjectID(ProjectId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("DescribeShareProject openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Project.DescribeShareProject(req, nil) + logger.Info("DescribeShareProject openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeShareProject openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + return responseApi.Payload.Result, nil +} diff --git a/bmp-console-api/logic/WebsocketLogic/WebsocketLogic.go b/bmp-console-api/logic/WebsocketLogic/WebsocketLogic.go new file mode 100644 index 0000000..5cdf9b6 --- /dev/null +++ b/bmp-console-api/logic/WebsocketLogic/WebsocketLogic.go @@ -0,0 +1,257 @@ +package WebsocketLogic + +import ( + "fmt" + "sync" + "time" + + "coding.jd.com/aidc-bmp/bmp-console-api/util" + log "coding.jd.com/aidc-bmp/bmp_log" + "github.com/gorilla/websocket" +) + +const ( + MessageTypeHeartbeatFromClient = "heartbeat" // 心跳 + MessageTypeHeartbeatFromServer = "ok" // 心跳回复成功 + MessageTypeRegisterFromClient = "register" // 注册 + MessageTypeRegisterSuccFromServer = "register ok" // 注册成功 + MessageTypeRegisterFailFromServer = "register err" // 注册失败 + MessageTypeNewNofifyFromServer = "nofifyfromserver" + + HeartbeatCheckTime = 10 // 心跳检测几秒检测一次 + HeartbeatTime = 300 // 心跳距离上一次的最大时间 + + ChanBufferRegister = 100 // 注册chan缓冲 + ChanBufferUnregister = 100 // 注销chan大小 +) + +// ReceiveMessage 客户端请求的报文格式(心跳or业务消息) +type ReceiveMessage struct { + Type string `json:"type"` + Message string `json:"message"` +} + +// NofifyMessage 回复给客户端的报文格式(心跳回复or业务消息) +type NofifyMessage struct { + Type string `json:"type"` + SubType string `json:"subType"` + Message string `json:"message"` + MetaData string `json:"metaData"` // 元数据 +} + +// var Nofify = make(chan NofifyMessage) + +// 客户端连接信息 +type Client struct { + ID string // 连接ID + UserId string // 账号id, 一个账号可能有多个连接 + Socket *websocket.Conn // socket连接 + HeartbeatTime int64 // 前一次心跳时间 +} + +// 客户端管理 +type ClientManager struct { + Clients map[string]*Client // 保存连接 + Accounts map[string][]string // 账号和连接关系,map的key是账号id即:AccountId,这里主要考虑到一个账号多个连接 + mu *sync.Mutex +} + +// 定义一个管理Manager +var Manager = ClientManager{ + Clients: make(map[string]*Client), // 参与连接的用户,出于性能的考虑,需要设置最大连接数 + Accounts: make(map[string][]string), // 账号和连接关系 + mu: new(sync.Mutex), +} + +var ( + RegisterChan = make(chan *Client, ChanBufferRegister) // 注册 + UnregisterChan = make(chan *Client, ChanBufferUnregister) // 注销 +) + +//有新消息,在这里通知到客户端 +func init() { + + go dealRegister() + go dealHeartbeat() + + go MSendInterval() + + // for { + // msg := <-Nofify + + // logPath, _ := beego.AppConfig.String("log.path") + // logger := log.New(logPath + "/bmp-msg-notify.log") + // logger.SetStableFields([]string{"time", "type", "subtype", "message"}) + // //没有requestid,临时生成 + // logger.Point("logid", util.GenerateRandUuid()) + // logger.Point("time", time.Now().String()) + // logger.Point("type", msg.Type) + // logger.Point("subtype", msg.SubType) + // logger.Point("message", msg.Message) + + // // for _, client := range Manager.Clients { + // // err := client.Socket.WriteJSON(msg) + // // if err != nil { + // // logger.Warnf("client.WriteJSON error: %v", err) + // // client.Socket.Close() + // // delete(Manager.Clients, client) + // // } + // // } + // logger.Flush() + // } +} + +// 注册注销 +func dealRegister() { + for { + select { + case conn := <-RegisterChan: // 新注册,新连接 + // 加入连接,进行管理 + connBind(conn) + + // 回复消息 + content := NofifyMessage{ + Type: "register", + SubType: "register", + Message: "register success", + } + _ = conn.Socket.WriteJSON(content) + + case conn := <-UnregisterChan: // 注销,或者没有心跳 + fmt.Println("UnregisterChan come...") + // 删除Client + connUnBind(conn) + } + } +} + +// 新加连接 +func connBind(c *Client) { + Manager.mu.Lock() + defer Manager.mu.Unlock() + + // 加入到连接 + Manager.Clients[c.ID] = c + + // 加入到绑定 + if _, ok := Manager.Accounts[c.UserId]; ok { // 该账号已经有绑定,就追加一个绑定 + Manager.Accounts[c.UserId] = append(Manager.Accounts[c.UserId], c.ID) + } else { // 没有就新增一个账号的绑定切片 + Manager.Accounts[c.UserId] = []string{c.ID} + } +} + +// 删除连接并关闭 +func connUnBind(c *Client) { + Manager.mu.Lock() + defer Manager.mu.Unlock() + + defer c.Socket.Close() + + // 取消连接 + delete(Manager.Clients, c.ID) + + // 取消绑定 + if len(Manager.Accounts[c.UserId]) > 0 { + for k, clientId := range Manager.Accounts[c.UserId] { + if clientId == c.ID { // 找到绑定客户端Id + Manager.Accounts[c.UserId] = append(Manager.Accounts[c.UserId][:k], Manager.Accounts[c.UserId][k+1:]...) + } + if len(Manager.Accounts[c.UserId]) == 0 { + delete(Manager.Accounts, c.UserId) + } + } + } +} + +// 维持心跳 +func dealHeartbeat() { + for { + // 获取所有的Clients + Manager.mu.Lock() + // clients := make([]*Client, len(Manager.Clients)) + clients := []*Client{} + for _, c := range Manager.Clients { + clients = append(clients, c) + } + Manager.mu.Unlock() + fmt.Println(time.Now().String(), "debug... clients is:", clients) + fmt.Println(time.Now().String(), "debug... Manager.Clients is:", Manager.Clients) + fmt.Println(time.Now().String(), "debug... Manager.Accounts is:", Manager.Accounts) + for _, c := range clients { + // fmt.Println("debug... c is:", c) + if time.Now().Unix()-c.HeartbeatTime > HeartbeatTime { + connUnBind(c) + } + } + + time.Sleep(time.Second * HeartbeatCheckTime) + } +} + +// 有新消息时,业务侧通过这个func发送消息到客户端 +func SendMsg2Client(logger *log.Logger, userIds []string, message NofifyMessage) error { + + for _, userId := range userIds { + // 获取连接id + clients := GetClient(userId) + // 发送消息 + for _, c := range clients { + err := c.Socket.WriteJSON(message) + if err != nil { + logger.Infof("SendMsg2Client failed, userId:%s, message:%s, error:%s", userId, util.ObjToJsonString(message), err.Error()) + connUnBind(c) + } else { + logger.Infof("SendMsg2Client success, userId:%s, message:%s", userId, util.ObjToJsonString(message)) + } + } + } + + return nil +} + +// 根据账号获取连接 +func GetClient(userId string) []*Client { + clients := make([]*Client, 0) + + Manager.mu.Lock() + defer Manager.mu.Unlock() + + if len(Manager.Accounts[userId]) > 0 { + for _, clientId := range Manager.Accounts[userId] { + if c, ok := Manager.Clients[clientId]; ok { + clients = append(clients, c) + } + } + } + + return clients +} + +func MSendInterval() { + + message := NofifyMessage{ + Type: "test", + SubType: "send_interval", + Message: "hello socket", + MetaData: "1min", + } + for { + for _, c := range Manager.Clients { + if c == nil { + fmt.Println(time.Now().String(), "socket client is nil ...., check it") + continue + } + err := c.Socket.WriteJSON(message) + if err != nil { + fmt.Printf(time.Now().String(), "SendMsg2Client failed, message:%s, error:%s\n", util.ObjToJsonString(message), err.Error()) + connUnBind(c) + } else { + fmt.Printf(time.Now().String(), "SendMsg2Client success, message:%s\n", util.ObjToJsonString(message)) + } + + } + time.Sleep(1 * time.Minute) + } + +} diff --git a/bmp-console-api/logic/messageLogic/messageLogic.go b/bmp-console-api/logic/messageLogic/messageLogic.go new file mode 100644 index 0000000..baaee79 --- /dev/null +++ b/bmp-console-api/logic/messageLogic/messageLogic.go @@ -0,0 +1,272 @@ +package messageLogic + +import ( + // "coding.jd.com/aidc-bmp/bmp-openapi/dao/messageDao" + "errors" + "math/rand" + "strconv" + "time" + + "coding.jd.com/aidc-bmp/bmp-console-api/constants" + "coding.jd.com/aidc-bmp/bmp-console-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/excel" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + sdkMessageParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/message" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + "git.jd.com/cps-golang/ironic-common/exception" + + // "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func HasUnreadMessage(logger *log.Logger) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewHasUnreadMessageParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("HasUnreadMessage openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.HasUnreadMessage(request, nil) + logger.Info("HasUnreadMessage openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("HasUnreadMessage openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.HasUnread, nil +} + +func GetPageMessages(logger *log.Logger, param *requestTypes.QueryMessagesRequest, p util.Pageable) (*response.MessageList, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewGetMessageListParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + request.WithPageNumber(&p.PageNumber) + request.WithPageSize(&p.PageSize) + if param.HasRead != "" { + request.WithHasRead(¶m.HasRead) + } + if param.IsAll != "" || param.ExportType != "" { + param.IsAll = "1" + request.WithIsAll(¶m.IsAll) + } + if param.MessageType != "" { + request.WithMessageType(¶m.MessageType) + } + if param.MessageSubType != "" { + request.WithMessageSubType(¶m.MessageSubType) + } + if param.Detail != "" { + request.WithDetail(¶m.Detail) + } + + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("GetMessageList openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.GetMessageList(request, nil) + logger.Info("GetMessageList openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("GetMessageList openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + resp := response.MessageList{} + resp.PageNumber = responseApi.Payload.Result.PageNumber + resp.PageSize = responseApi.Payload.Result.PageSize + resp.TotalCount = responseApi.Payload.Result.TotalCount + resp.Messages = responseApi.Payload.Result.Messages + + return &resp, nil + +} + +func GetMessageStatistic(logger *log.Logger) (int64, int64, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewGetMessageStatisticParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("GetMessageStatistic openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.GetMessageStatistic(request, nil) + logger.Info("GetMessageStatistic openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("GetMessageStatistic openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return 0, 0, err + } + return 0, 0, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.TotalCount, responseApi.Payload.Result.UnreadCount, nil + +} + +func ReadMessages(logger *log.Logger, param *requestTypes.ReadMessagesRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewReadMessageParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + body := sdkModels.ReadMessagesRequest{ + MessageIds: param.MessageIds, + } + request.WithBody(&body) + + logger.Info("ReadMessage openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.ReadMessage(request, nil) + logger.Info("ReadMessage openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("ReadMessage openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil +} + +func GetMessageById(logger *log.Logger, param *requestTypes.GetMessageByIdRequest) (*sdkModels.Message, string, string, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewGetMessageByIDParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + request.WithMessageID(param.MessageId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("GetMessageByID openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.GetMessageByID(request, nil) + logger.Info("GetMessageByID openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("GetMessageByID openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, "", "", err + } + return nil, "", "", errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Message, responseApi.Payload.Result.NextMessageID, responseApi.Payload.Result.PrevMessageID, nil + +} + +func GetMessageTypes(logger *log.Logger) (*sdkModels.MessageTypesResp, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewGetMessageTypesParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("GetMessageTypes openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.GetMessageTypes(request, nil) + logger.Info("GetMessageTypes openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("GetMessageTypes openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return &responseApi.Payload.Result, nil + +} + +func DeleteMessages(logger *log.Logger, param *requestTypes.DeleteMessagesRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewDeleteMessageParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + body := sdkModels.DeleteMessagesRequest{ + MessageIds: param.MessageIds, + } + request.WithBody(&body) + + logger.Info("DeleteMessage openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.DeleteMessage(request, nil) + logger.Info("DeleteMessage openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DeleteMessage openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil +} + +func ExportMessage(logger *log.Logger, result []*models.Message) (fileName, downLoadFileName string) { + + tz := logger.GetPoint("timezone").(string) + + language := logger.GetPoint("language").(string) + + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + + for _, data := range result { + + if language == constants.LANGUAGE_EN { + + } + + sheetData = append(sheetData, []string{ + data.Detail, + util.TimestampToString(int64(data.FinishTime), tz), + data.MessageType, + data.MessageSubType, + }) + } + exportMessageHeader := BaseLogic.ExportMessageHeader + if language == "en_US" { + exportMessageHeader = BaseLogic.ExportMessageHeaderEn + } + if err := e.SetSheetData("Sheet1", exportMessageHeader, sheetData); err != nil { + panic(exception.Exception{Msg: "新建excel失败", Status: BaseLogic.ERROR_CODE}) + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + downloadFileName := "message_list_" + time.Now().Format(BaseLogic.FormatDate) + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" //生成100000到100000+900000之间的随机数,左闭右开 + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Info("保存excel到本地失败" + err.Error()) + panic(exception.Exception{Msg: "保存excel到本地失败", Status: BaseLogic.ERROR_CODE}) + } + return fileName, downloadFileName +} diff --git a/bmp-console-api/logic/monitorAlertLogic/monitorAlertLogic.go b/bmp-console-api/logic/monitorAlertLogic/monitorAlertLogic.go new file mode 100644 index 0000000..803234c --- /dev/null +++ b/bmp-console-api/logic/monitorAlertLogic/monitorAlertLogic.go @@ -0,0 +1,150 @@ +package monitorAlertLogic + +import ( + "errors" + "fmt" + "math/rand" + "strconv" + "time" + + "coding.jd.com/aidc-bmp/bmp-console-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/excel" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + sdkmonitorAlertParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/monitor_alert" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + log "coding.jd.com/aidc-bmp/bmp_log" + "git.jd.com/cps-golang/ironic-common/exception" +) + +func DescribeAlert(logger *log.Logger, AlertId string) (*sdkModels.Alert, error) { + logid := logger.GetPoint("logid").(string) + request := sdkmonitorAlertParameters.NewDescribeAlertParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + request.WithAlertID(AlertId) + logger.Info("DescribeAlert openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.MonitorAlert.DescribeAlert(request, nil) + logger.Info("DescribeAlert openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeAlert openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result, nil + +} + +func DescribeAlerts(logger *log.Logger, param *request.DescribeAlertsRequest, p util.Pageable) (*sdkModels.AlertList, error) { + logid := logger.GetPoint("logid").(string) + request := sdkmonitorAlertParameters.NewDescribeAlertsParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + request.WithIsAll(¶m.IsAll) + request.WithPageNumber(&p.PageNumber) + request.WithPageSize(&p.PageSize) + request.WithUserID(¶m.UserID) + request.WithUserName(¶m.UserName) + request.WithRuleID(¶m.RuleID) + request.WithRuleName(¶m.RuleName) + request.WithStartTime(¶m.StartTime) + request.WithEndTime(¶m.EndTime) + request.WithResourceID(¶m.ResourceID) + request.WithProjectID(¶m.ProjectID) + + logger.Info("DescribeAlerts openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.MonitorAlert.DescribeAlerts(request, nil) + logger.Info("DescribeAlerts openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeAlerts openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result, nil +} + +func ExportAlerts(logger *log.Logger, result []*sdkModels.Alert) (fileName, downLoadFileName string) { + + tz := logger.GetPoint("timezone").(string) + language := logger.GetPoint("language").(string) + + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + for _, data := range result { + alertPeriod := fmt.Sprintf("%d分钟", data.AlertPeriod) + if language == "en_US" { + alertPeriod = fmt.Sprintf("%dmin", data.AlertPeriod) + } + sheetData = append(sheetData, []string{ + util.TimestampToString(int64(data.AlertTime), tz), + data.ResourceID, + data.TriggerDescription, + data.AlertValue, + data.AlertLevelDescription, + alertPeriod, + data.UserName, + }) + } + exportAlertHeader := BaseLogic.ExportAlertsHeader + if language == "en_US" { + exportAlertHeader = BaseLogic.ExportAlertsHeaderEn + } + if err := e.SetSheetData("Sheet1", exportAlertHeader, sheetData); err != nil { + panic(exception.Exception{Msg: "新建excel失败", Status: BaseLogic.ERROR_CODE}) + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + downloadFileName := "alert_list_" + time.Now().Format(BaseLogic.FormatDate) + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" //生成100000到100000+900000之间的随机数,左闭右开 + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Info("保存excel到本地失败" + err.Error()) + panic(exception.Exception{Msg: "保存excel到本地失败", Status: BaseLogic.ERROR_CODE}) + } + return fileName, downloadFileName +} + +func DeleteAlert(logger *log.Logger, param *request.DeleteAlertRequest) (bool, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkmonitorAlertParameters.NewDeleteAlertParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := &sdkModels.DeleteAlertRequest{ + AlertID: ¶m.AlertId, + } + req.WithBody(body) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("DeleteAlert openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.MonitorAlert.DeleteAlert(req, nil) + logger.Info("DeleteAlert openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DeleteAlert openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil + +} diff --git a/bmp-console-api/logic/monitorDataLogic/monitorDataLogic.go b/bmp-console-api/logic/monitorDataLogic/monitorDataLogic.go new file mode 100644 index 0000000..5eb1c48 --- /dev/null +++ b/bmp-console-api/logic/monitorDataLogic/monitorDataLogic.go @@ -0,0 +1,43 @@ +package monitorDataLogic + +import ( + "errors" + + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + sdkmonitorDataParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/monitor_data" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func GetMonitorData(logger *log.Logger, param request.GetMonitorDataRequest) ([]*sdkModels.DataEveryMetric, error) { + logid := logger.GetPoint("logid").(string) + request := sdkmonitorDataParameters.NewGetMonitorDataParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + request.WithMetricName(¶m.MetricName) + request.WithInstanceID(¶m.InstanceID) + request.WithDevice(¶m.Device) + request.WithStartTime(¶m.StartTime) + request.WithEndTime(¶m.EndTime) + request.WithTimeInterval(¶m.TimeInterval) + request.WithDownSampleType(¶m.DownSampleType) + request.WithLastManyTime(¶m.LastManyTime) + logger.Info("GetMonitorData openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.MonitorData.GetMonitorData(request, nil) + logger.Info("GetMonitorData openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("GetMonitorData openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result, nil +} diff --git a/bmp-console-api/logic/monitorProxyLogic/monitorProxyLogic.go b/bmp-console-api/logic/monitorProxyLogic/monitorProxyLogic.go new file mode 100644 index 0000000..714d073 --- /dev/null +++ b/bmp-console-api/logic/monitorProxyLogic/monitorProxyLogic.go @@ -0,0 +1,65 @@ +package monitorProxyLogic + +import ( + "errors" + + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + sdkmonitorProxyParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/monitor_proxy" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func DescribeAgentStatus(logger *log.Logger, param *request.DesrcibeAgentStatusRequest) (*sdkModels.AgentStatusResponse, error) { + logid := logger.GetPoint("logid").(string) + request := sdkmonitorProxyParameters.NewDesrcibeAgentStatusParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + request.WithInstanceID(param.InstanceId) + + logger.Info("DesrcibeAgentStatus openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.MonitorProxy.DesrcibeAgentStatus(request, nil) + logger.Info("DesrcibeAgentStatus openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DesrcibeAgentStatus openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result, nil + +} + +func DescribeDeviceTags(logger *log.Logger, param *request.DesrcibeTagsRequest) (response.TagsResponse, error) { + logid := logger.GetPoint("logid").(string) + request := sdkmonitorProxyParameters.NewDesrcibeTagsParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + request.WithInstanceID(param.InstanceID) + request.WithTagName(param.TagName) + + logger.Info("DesrcibeTags openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.MonitorProxy.DesrcibeTags(request, nil) + logger.Info("DesrcibeTags openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DesrcibeTags openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Tags, nil +} diff --git a/bmp-console-api/logic/monitorRuleLogic/monitorRuleLogic.go b/bmp-console-api/logic/monitorRuleLogic/monitorRuleLogic.go new file mode 100644 index 0000000..5a585fb --- /dev/null +++ b/bmp-console-api/logic/monitorRuleLogic/monitorRuleLogic.go @@ -0,0 +1,322 @@ +package monitorRuleLogic + +import ( + "errors" + "fmt" + "math/rand" + "strconv" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-console-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/excel" + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" + "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + sdkmonitorRuleParameters "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client/monitor_rule" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + log "coding.jd.com/aidc-bmp/bmp_log" + "git.jd.com/cps-golang/ironic-common/exception" +) + +func AddRule(logger *log.Logger, param *request.AddRuleRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + req := sdkmonitorRuleParameters.NewAddRuleParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + trOption := []*sdkModels.RuleTrigger{} + for _, vv := range param.TriggerOption { + v := vv + item := &sdkModels.RuleTrigger{ + Calculation: &v.Calculation, + CalculationUnit: v.CalculationUnit, + Metric: &v.Metric, + NoticeLevel: &v.NoticeLevel, + Operation: &v.Operation, + Period: &v.Period, + Threshold: &v.Threshold, + Times: &v.Times, + } + trOption = append(trOption, item) + } + notifyOption := &sdkModels.RuleNotice{ + EffectiveIntervalEnd: ¶m.NoticeOption.EffectiveIntervalEnd, + EffectiveIntervalStart: ¶m.NoticeOption.EffectiveIntervalStart, + NoticeCondition: param.NoticeOption.NoticeCondition, + NoticePeriod: ¶m.NoticeOption.NoticePeriod, + NoticeWay: param.NoticeOption.NoticeWay, + UserID: ¶m.NoticeOption.UserID, + } + body := &sdkModels.AddRuleRequest{ + DeviceTag: param.DeviceTag, + Dimension: ¶m.Dimension, + InstanceIds: param.InstanceIds, + Resource: ¶m.Resource, + RuleName: ¶m.RuleName, + TriggerOption: trOption, + NoticeOption: notifyOption, + ProjectID: ¶m.ProjectID, + } + req.WithBody(body) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("AddRule openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.MonitorRule.AddRule(req, nil) + logger.Info("AddRule openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("AddRule openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil + +} + +func DescribeRule(logger *log.Logger, ruleId string) (*sdkModels.Rule, error) { + logid := logger.GetPoint("logid").(string) + request := sdkmonitorRuleParameters.NewDescribeRuleParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + request.WithRuleID(ruleId) + logger.Info("DescribeRule openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.MonitorRule.DescribeRule(request, nil) + logger.Info("DescribeRule openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeRule openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result, nil + +} + +func DescribeRules(logger *log.Logger, param *request.DescribeRulesRequest, p util.Pageable) (*sdkModels.RuleList, error) { + logid := logger.GetPoint("logid").(string) + request := sdkmonitorRuleParameters.NewDescribeRulesParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + request.WithIsAll(¶m.IsAll) + request.WithPageNumber(&p.PageNumber) + request.WithPageSize(&p.PageSize) + request.WithUserID(¶m.UserId) + request.WithUserName(¶m.UserName) + request.WithRuleID(¶m.RuleId) + request.WithRuleName(¶m.RuleName) + request.WithProjectID(¶m.ProjectID) + status := int64(param.Status) + request.WithStatus(&status) + + logger.Info("DescribeRules openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.MonitorRule.DescribeRules(request, nil) + logger.Info("DescribeRules openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeRules openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result, nil +} + +func ExportRules(logger *log.Logger, result []*sdkModels.Rule) (fileName, downLoadFileName string) { + + language := logger.GetPoint("language").(string) + + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + for _, data := range result { + + sheetData = append(sheetData, []string{ + data.RuleName, + data.RuleID, + data.ResourceName, + fmt.Sprintf("%d", len(data.InstanceIds)), + strings.Join(data.TriggerDescription, ";"), + data.StatusName, + }) + } + exportRuleHeader := BaseLogic.ExportRulesHeader + if language == "en_US" { + exportRuleHeader = BaseLogic.ExportRulesHeaderEn + } + if err := e.SetSheetData("Sheet1", exportRuleHeader, sheetData); err != nil { + panic(exception.Exception{Msg: "新建excel失败", Status: BaseLogic.ERROR_CODE}) + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + downloadFileName := "rule_list_" + time.Now().Format(BaseLogic.FormatDate) + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" //生成100000到100000+900000之间的随机数,左闭右开 + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Info("保存excel到本地失败" + err.Error()) + panic(exception.Exception{Msg: "保存excel到本地失败", Status: BaseLogic.ERROR_CODE}) + } + return fileName, downloadFileName +} + +func EditRule(logger *log.Logger, param *request.EditRuleRequest) (bool, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkmonitorRuleParameters.NewEditRuleParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + trOption := []*sdkModels.RuleTrigger{} + for _, vv := range param.TriggerOption { + v := vv + item := &sdkModels.RuleTrigger{ + Calculation: &v.Calculation, + CalculationUnit: v.CalculationUnit, + Metric: &v.Metric, + NoticeLevel: &v.NoticeLevel, + Operation: &v.Operation, + Period: &v.Period, + Threshold: &v.Threshold, + Times: &v.Times, + } + trOption = append(trOption, item) + } + notifyOption := &sdkModels.RuleNotice{ + EffectiveIntervalEnd: ¶m.NoticeOption.EffectiveIntervalEnd, + EffectiveIntervalStart: ¶m.NoticeOption.EffectiveIntervalStart, + NoticeCondition: param.NoticeOption.NoticeCondition, + NoticePeriod: ¶m.NoticeOption.NoticePeriod, + NoticeWay: param.NoticeOption.NoticeWay, + UserID: ¶m.NoticeOption.UserID, + } + body := &sdkModels.EditRuleRequest{ + DeviceTag: param.DeviceTag, + Dimension: ¶m.Dimension, + InstanceIds: param.InstanceIds, + Resource: ¶m.Resource, + RuleID: ¶m.RuleId, + RuleName: ¶m.RuleName, + TriggerOption: trOption, + NoticeOption: notifyOption, + } + req.WithBody(body) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("EditRule openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.MonitorRule.EditRule(req, nil) + logger.Info("EditRule openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("EditRule openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil + +} + +func EnableRule(logger *log.Logger, param *request.EnableRuleRequest) (bool, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkmonitorRuleParameters.NewEnableRuleParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := &sdkModels.EnableRuleRequest{ + RuleID: ¶m.RuleId, + } + req.WithBody(body) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("EnableRule openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.MonitorRule.EnableRule(req, nil) + logger.Info("EnableRule openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("EnableRule openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil + +} + +func DisableRule(logger *log.Logger, param *request.DisableRuleRequest) (bool, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkmonitorRuleParameters.NewDisableRuleParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := &sdkModels.DisableRuleRequest{ + RuleID: ¶m.RuleId, + } + req.WithBody(body) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("DisableRule openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.MonitorRule.DisableRule(req, nil) + logger.Info("DisableRule openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DisableRule openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil + +} + +func DeleteRule(logger *log.Logger, param *request.DeleteRuleRequest) (bool, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkmonitorRuleParameters.NewDeleteRuleParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := &sdkModels.DeleteRuleRequest{ + RuleID: ¶m.RuleId, + } + req.WithBody(body) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("DeleteRule openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.MonitorRule.DeleteRule(req, nil) + logger.Info("DeleteRule openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DeleteRule openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil + +} diff --git a/bmp-console-api/main.go b/bmp-console-api/main.go new file mode 100644 index 0000000..9599db0 --- /dev/null +++ b/bmp-console-api/main.go @@ -0,0 +1,92 @@ +package main + +import ( + "flag" + "fmt" + "log" + "os" + "time" + + "coding.jd.com/aidc-bmp/bmp-console-api/controllers" + sessionUtil "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/session" + "github.com/beego/beego/v2/core/logs" + + _ "coding.jd.com/aidc-bmp/bmp-console-api/routers" + rds "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/redis" + _ "github.com/beego/beego/v2/server/web/session/redis" + _ "github.com/go-sql-driver/mysql" + + beego "github.com/beego/beego/v2/server/web" + + "coding.jd.com/aidc-bmp/bmp-console-api/thirdpart/openApi" +) + +const ( + defaultConfigFile = "conf/bmp-console.ini" +) + +var ( + VERSION = "should be compiled with make." + BUILD_TIME = "should be compiled with make." +) + +var configFile = flag.String("c", defaultConfigFile, "specify config file") +var versionFlag = flag.Bool("v", false, "show version") + +func main() { + + time.LoadLocation("Asia/Shanghai") + flag.Parse() + + if *versionFlag { + fmt.Println("commit_id:", VERSION, "build_time:", BUILD_TIME) + os.Exit(0) + } + + log.Println("[bmp-console] start...") + // logs.SetLogger(logs.AdapterConsole) + logs.SetLevel(logs.LevelTrace) + logs.EnableFuncCallDepth(true) + logs.SetLogFuncCallDepth(3) + logs.Info("============== Start========") + + // initial Config From file + if err := beego.LoadAppConfig("ini", *configFile); err != nil { + fmt.Println("LoadAppConfig Error:", err.Error()) + return + } + rds.Init() + //cpsApiHost, err := beego.AppConfig.String("cps-api.host") + //if err != nil { + // fmt.Println("parse cps-api.host from confile error:", err.Error()) + // return + //} + //if err := cpsApi.InitCpsApiConfig(cpsApiHost); err != nil { + // fmt.Println("init cpsApi conf error:", err.Error()) + // // return + //} + + //if err := initGormDB(); err != nil { + // fmt.Println("initGormDB() Error:", err.Error()) + // return + //} + + //kafka, 创建实例付费成功接收msg + // kafkaOrderHost, _ := beego.AppConfig.String("kafka.order.bootstrap-server") + // kafkaOrderTopic, _ := beego.AppConfig.String("kafka.order.topic.order_produce") + // go kafka.Consume(kafkaOrderHost, kafkaOrderTopic) + + // TODO 监听付款成功的kafka消息,然后请求innerCreateInstance + openApi.Init() + sessionUtil.Init() + + controllers.Init() //手动调用初始化 + + beego.Run() +} + +// func initGormDB() error { +// // initial mysql +// sqlconn, _ := beego.AppConfig.String("jdbc.url") //mysql +// return dao.InitGormDb(sqlconn) +// } diff --git a/bmp-console-api/routers/router.go b/bmp-console-api/routers/router.go new file mode 100644 index 0000000..c8629e5 --- /dev/null +++ b/bmp-console-api/routers/router.go @@ -0,0 +1,208 @@ +// @APIVersion 1.0.0 +// @Title beego Test API +// @Description beego has a very cool tools to autogenerate documents for your API +// @Contact astaxie@gmail.com +// @TermsOfServiceUrl http://beego.me/ +// @License Apache 2.0 +// @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html +package routers + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/controllers" + + beego "github.com/beego/beego/v2/server/web" +) + +func init() { + beego.Router("/ws/msg", &controllers.WebSocketController{}) + beego.Router("/ws/innerSendmsg", &controllers.WebSocketController{}, "post:Send") + beego.Router("/login", &controllers.UserController{}, "post:Login") + beego.Router("/logout", &controllers.UserController{}, "post:Logout") + + // 后面用户角色校验时需要放开 + // beego.InsertFilter("/v1/*", beego.BeforeRouter, controllers.Authentication) + // beego.InsertFilter("/api/*", beego.BeforeRouter, controllers.Authentication) + + // beego.InsertFilter("/*", beego.BeforeRouter, filter.FilterPin) + + //----------------------------- console api ---------------------------------------- + customer := beego.NewNamespace("/custom", + beego.NSRouter("/setCustomInfo", &controllers.CustomController{}, "post:SetCustomInfo"), //暂时没用到,前端自己存 + beego.NSRouter("/getCustomInfo", &controllers.CustomController{}, "get:GetCustomInfo"), + ) + beego.AddNamespace(customer) + + apikeyNS := beego.NewNamespace("/apikey", + beego.NSRouter("/", &controllers.ApikeyController{}, "put:CreateApikey"), //td + beego.NSRouter("/", &controllers.ApikeyController{}, "get:GetApikeyList"), + beego.NSRouter("/?:apikey_id", &controllers.ApikeyController{}, "delete:DeleteApikey"), + ) + beego.AddNamespace(apikeyNS) + + deviceNS := beego.NewNamespace("/device", + beego.NSRouter("/isDeviceStockEnough", &controllers.DeviceController{}, "get:IsDeviceStockEnough"), //td + ) + beego.AddNamespace(deviceNS) + + deviceTypeNS := beego.NewNamespace("/deviceType", + beego.NSRouter("/getAvailableDeviceTypes", &controllers.DeviceTypeController{}, "get:GetAvailableDeviceTypes"), //td + ) + beego.AddNamespace(deviceTypeNS) + + idcNS := beego.NewNamespace("/idc", + beego.NSRouter("/", &controllers.IdcController{}, "get:GetIdcList"), //td + ) + beego.AddNamespace(idcNS) + + imageNS := beego.NewNamespace("/image", + beego.NSRouter("/queryImagesByDeviceType", &controllers.ImageController{}, "get:QueryImagesByDeviceType"), //td + ) + beego.AddNamespace(imageNS) + + partitionNS := beego.NewNamespace("/partition", + beego.NSRouter("/queryDefaultSystemPartitions", &controllers.PartitionController{}, "get:QueryDefaultSystemPartitions"), //td + ) + beego.AddNamespace(partitionNS) + + projectNS := beego.NewNamespace("/project", + beego.NSRouter("/", &controllers.ProjectController{}, "put:CreateProject"), //td + beego.NSRouter("/", &controllers.ProjectController{}, "get:GetProjectList"), //td + beego.NSRouter("/?:project_id", &controllers.ProjectController{}, "get:GetProject"), //td + beego.NSRouter("/?:project_id", &controllers.ProjectController{}, "post:ModifyProject"), //修改项目名称 + beego.NSRouter("/?:project_id/description", &controllers.ProjectController{}, "post:ModifyProjectDescription"), //修改项目描述 + beego.NSRouter("/?:project_id", &controllers.ProjectController{}, "delete:DeleteProject"), //td + beego.NSRouter("/?:project_id", &controllers.ProjectController{}, "delete:DeleteProject"), //td + beego.NSRouter("/?:project_id/share", &controllers.ProjectController{}, "put:ShareProject"), //td + beego.NSRouter("/?:project_id/cancelShare", &controllers.ProjectController{}, "put:CancelShareProject"), //td + beego.NSRouter("/?:project_id/move", &controllers.ProjectController{}, "put:MoveProject"), + beego.NSRouter("/move/instances", &controllers.ProjectController{}, "put:MoveInstances"), + ) + beego.AddNamespace(projectNS) + + raidNS := beego.NewNamespace("/raid", + beego.NSRouter("/queryRaidsByDeviceTypeIDAndVolumeType", &controllers.RaidController{}, "get:QueryVolumeRaids"), //td + ) + beego.AddNamespace(raidNS) + + userNS := beego.NewNamespace("/user", + beego.NSRouter("/", &controllers.UserController{}, "get:GetUserInfo"), //td + beego.NSRouter("/password", &controllers.UserController{}, "put:UpdatePassword"), //td + beego.NSRouter("/", &controllers.UserController{}, "put:UpdateUserInfo"), //td + beego.NSRouter("/timezones", &controllers.TimezoneController{}, "get:GetTimezoneList"), + //获取有控制台权限的用户列表 + beego.NSRouter("/getConsoleAccessUserList", &controllers.UserController{}, "get:GetConsoleAccessUserList"), + //校验用户是否有控制台权限 + beego.NSRouter("/checkUserConsoleAccess", &controllers.UserController{}, "get:CheckUserConsoleAccess"), + //校验用户是否有控制台权限,按用户名 + beego.NSRouter("/checkUserConsoleAccessByName", &controllers.UserController{}, "get:CheckUserConsoleAccessByName"), + ) + beego.AddNamespace(userNS) + + keypairNS := beego.NewNamespace("/keypair", + beego.NSRouter("/", &controllers.KeypairController{}, "put:CreateKeypair"), //td + beego.NSRouter("/", &controllers.KeypairController{}, "get:GetKeypairList"), + beego.NSRouter("/?:keypair_id", &controllers.KeypairController{}, "get:GetKeypairInfo"), + beego.NSRouter("/?:keypair_id", &controllers.KeypairController{}, "put:ModifyKeypair"), + beego.NSRouter("/?:keypair_id", &controllers.KeypairController{}, "delete:DeleteKeypair"), + beego.NSRouter("/checkKeypairName", &controllers.KeypairController{}, "get:CheckKeypairName"), //td + ) + beego.AddNamespace(keypairNS) + + instanceNS := beego.NewNamespace("/instance", + beego.NSRouter("/", &controllers.InstanceController{}, "get:GetInstanceList"), //td + beego.NSRouter("/?:instance_id", &controllers.InstanceController{}, "get:GetInstanceInfo"), //td + beego.NSRouter("/", &controllers.InstanceController{}, "put:CreateInstance"), + beego.NSRouter("/startInstance", &controllers.InstanceController{}, "post:StartInstance"), + beego.NSRouter("/stopInstance", &controllers.InstanceController{}, "post:StopInstance"), + beego.NSRouter("/modifyInstance", &controllers.InstanceController{}, "post:ModifyInstance"), + beego.NSRouter("/restartInstance", &controllers.InstanceController{}, "post:RestartInstance"), + beego.NSRouter("/resetPasswd", &controllers.InstanceController{}, "post:ResetPasswd"), + beego.NSRouter("/batchResetPasswd", &controllers.InstanceController{}, "post:ResetInstancesPasswd"), + beego.NSRouter("/?:instance_id", &controllers.InstanceController{}, "delete:DeleteInstance"), + beego.NSRouter("/lockInstance", &controllers.InstanceController{}, "post:LockInstance"), + beego.NSRouter("/unlockInstance", &controllers.InstanceController{}, "post:UnlockInstance"), + beego.NSRouter("/startInstances", &controllers.InstanceController{}, "post:StartInstances"), //批量开机 + beego.NSRouter("/stopInstances", &controllers.InstanceController{}, "post:StopInstances"), //批量关机 + beego.NSRouter("/restartInstances", &controllers.InstanceController{}, "post:RestartInstances"), //批量重启 + beego.NSRouter("/modifyInstances", &controllers.InstanceController{}, "post:ModifyInstances"), //批量编辑实例名称 + beego.NSRouter("/deleteInstances", &controllers.InstanceController{}, "delete:DeleteInstances"), //批量删除 + beego.NSRouter("/reinstallInstance", &controllers.InstanceController{}, "post:ReinstallInstance"), + //部分共享的实例列表 + beego.NSRouter("/forshare/list", &controllers.InstanceController{}, "get:GetInstanceListForShare"), + ) + beego.AddNamespace(instanceNS) + + // licenseNS := beego.NewNamespace("/license", + // beego.NSRouter("/content", &controllers.LicenseController{}, "get:GetLicenceContent"), //td + // ) + // beego.AddNamespace(licenseNS) + + messageNS := beego.NewNamespace("/messages", + beego.NSRouter("/hasUnreadMessage", &controllers.MessageController{}, "get:HasUnreadMessage"), + beego.NSRouter("/", &controllers.MessageController{}, "get:GetMessageList"), + beego.NSRouter("/statistic", &controllers.MessageController{}, "get:GetMessageStatistic"), + beego.NSRouter("/doRead", &controllers.MessageController{}, "put:ReadMessage"), + beego.NSRouter("/delete", &controllers.MessageController{}, "delete:DeleteMessage"), + beego.NSRouter("/getMessageById", &controllers.MessageController{}, "get:GetMessageById"), + beego.NSRouter("/getMessageTypes", &controllers.MessageController{}, "get:GetMessageTypes"), + ) + beego.AddNamespace(messageNS) + + auditLogNS := beego.NewNamespace("/auditLogs", + beego.NSRouter("/", &controllers.AuditLogsController{}, "get:DescribeAuditLogs"), + beego.NSRouter("/types", &controllers.AuditLogsController{}, "get:DescribeAuditLogTypes"), + ) + beego.AddNamespace(auditLogNS) + + //报警规则相关 + monitorRuleNs := + beego.NewNamespace("/monitorRule", + //添加规则 + beego.NSRouter("/addRule", &controllers.MonitorRuleController{}, "post:AddRule"), + //规则详情 + beego.NSRouter("/describeRule", &controllers.MonitorRuleController{}, "get:DescribeRule"), + //规则列表 + beego.NSRouter("/describeRules", &controllers.MonitorRuleController{}, "get:DescribeRules"), + //编辑规则 + beego.NSRouter("/editRule", &controllers.MonitorRuleController{}, "put:EditRule"), + //启用规则 + beego.NSRouter("/enableRule", &controllers.MonitorRuleController{}, "put:EnableRule"), + //禁用规则 + beego.NSRouter("/disableRule", &controllers.MonitorRuleController{}, "put:DisableRule"), + //删除规则 + beego.NSRouter("/deleteRule", &controllers.MonitorRuleController{}, "delete:DeleteRule"), + ) + + beego.AddNamespace(monitorRuleNs) + + //监控报警相关 + monitorAlertNs := + beego.NewNamespace("/monitorAlert", + //告警详情 + beego.NSRouter("/describeAlert", &controllers.MonitorAlertController{}, "get:DescribeAlert"), + //告警列表 + beego.NSRouter("/describeAlerts", &controllers.MonitorAlertController{}, "get:DescribeAlerts"), + //删除告警 + beego.NSRouter("/deleteAlert", &controllers.MonitorAlertController{}, "delete:DeleteAlert"), + ) + + beego.AddNamespace(monitorAlertNs) + + //带内监控-图表数据获取 + monitorDataNs := + beego.NewNamespace("/monitorData", + beego.NSRouter("/", &controllers.MonitorDataController{}, "get:GetMonitorData"), + ) + + beego.AddNamespace(monitorDataNs) + + //带内监控-获取agent状态、获取tag列表 + monitorProxyNs := + beego.NewNamespace("/monitorProxy", + beego.NSRouter("/desrcibeAgentStatus", &controllers.MonitorProxyController{}, "get:DesrcibeAgentStatus"), + beego.NSRouter("/desrcibeTags", &controllers.MonitorProxyController{}, "get:DesrcibeTags"), + ) + + beego.AddNamespace(monitorProxyNs) + +} diff --git a/bmp-console-api/swagger.json b/bmp-console-api/swagger.json new file mode 100644 index 0000000..10b27aa --- /dev/null +++ b/bmp-console-api/swagger.json @@ -0,0 +1,3811 @@ +{ + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "schemes": [ + "http" + ], + "swagger": "2.0", + "info": { + "description": "the purpose of this application is to provide an application\nthat is using plain go code to define an API\n\nThis should demonstrate all the possible comment annotations\nthat are available to turn go code into a fully compliant swagger 2.0 spec", + "title": "bmp-console-api", + "termsOfService": "there are no TOS at this moment, use at your own risk we take no responsibility", + "contact": { + "email": "minping@jd.com" + }, + "license": { + "name": "MIT", + "url": "http://opensource.org/licenses/MIT" + }, + "version": "0.0.1" + }, + "host": "bmp-console-api.local", + "basePath": "/", + "paths": { + "/apikey": { + "get": { + "description": "GetApikeyList 获取apikey列表", + "tags": [ + "keypair" + ], + "operationId": "getApikeyList", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "name": "pageSize", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getApikeyList" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "CreateAPIkey 创建apikey", + "tags": [ + "keypair" + ], + "operationId": "createApikey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateApikeyRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createApikey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/apikey/{apikey_id}": { + "delete": { + "description": "DeleteApikey 删除apikey", + "tags": [ + "keypair" + ], + "operationId": "deleteApikey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ApikeyID", + "name": "apikey_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteApikey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/custom/getCustomInfo": { + "get": { + "description": "GetCustomInfo 获取自定义表头", + "tags": [ + "custom" + ], + "operationId": "getCustomInfo", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "PageKey", + "name": "pageKey", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Reload", + "name": "reload", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getCustomInfo" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/custom/setCustomInfo": { + "post": { + "description": "SetCustomInfo 设置自定义表头", + "tags": [ + "custom" + ], + "operationId": "setCustomInfo", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/SetCustomInfoRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/setCustomInfo" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/device/isDeviceStockEnough": { + "get": { + "description": "IsDeviceStockEnough 查询设备库存是否足够", + "tags": [ + "device" + ], + "operationId": "isDeviceStockEnough", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "IdcID", + "name": "idc_id", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceTypeId", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "Count", + "name": "count", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/isDeviceStockEnough" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/deviceType/getAvailableDeviceTypes": { + "get": { + "description": "GetAvailableDeviceTypes 获取该机房内可用机型列表", + "tags": [ + "deviceType" + ], + "operationId": "getAvailableDeviceTypes", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "IdcID", + "name": "idc_id", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getAvailableDeviceTypes" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/idc": { + "get": { + "description": "GetIdcList 获取idc列表", + "tags": [ + "idc" + ], + "operationId": "getIdcList", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ExportType", + "name": "exportType", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getIdcList" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/image/queryImagesByDeviceType": { + "get": { + "description": "QueryImagesByDeviceType 根据机型获取绑定的镜像列表", + "tags": [ + "image" + ], + "operationId": "queryImagesByDeviceType", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "IdcID", + "description": "Pin string `json:\"pin\"`", + "name": "idc_id", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "name": "deviceTypeId", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/queryImagesByDeviceType" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/instance": { + "get": { + "description": "GetInstanceList 实例列表", + "tags": [ + "instance" + ], + "operationId": "getInstanceList", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "projectId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IdcID", + "name": "idcId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Status", + "name": "status", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Name", + "name": "name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceType", + "name": "deviceType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "InstanceIds", + "name": "instanceIds", + "in": "query" + }, + { + "type": "string", + "x-go-name": "PrivateIp", + "name": "privateIp", + "in": "query" + }, + { + "type": "string", + "x-go-name": "KeypairId", + "name": "keypairId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Sn", + "name": "sn", + "in": "query" + }, + { + "type": "string", + "x-go-name": "PrivateIps", + "name": "privateIps", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IloIps", + "name": "iloIps", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceTypeList", + "name": "deviceTypeList", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ExportType", + "name": "exportType", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getInstanceList" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "CreateInstance 创建实例", + "tags": [ + "instance" + ], + "operationId": "createInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateInstanceRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/instance/lockInstance": { + "post": { + "description": "LockInstance 锁定实例", + "tags": [ + "instance" + ], + "operationId": "lockInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/LockInstanceRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/lockInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/instance/restartInstance": { + "post": { + "description": "RestartInstance 重启实例", + "tags": [ + "instance" + ], + "operationId": "restartInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/RestartInstanceRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/restartInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/instance/startInstance": { + "post": { + "description": "StartInstance 开机", + "tags": [ + "instance" + ], + "operationId": "startInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/StartInstanceRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/startInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/instance/stopInstance": { + "post": { + "description": "StopInstance 关机", + "tags": [ + "instance" + ], + "operationId": "stopInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/StopInstanceRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/stopInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/instance/unlockInstance": { + "post": { + "description": "UnlockInstance 解锁实例", + "tags": [ + "instance" + ], + "operationId": "unlockInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/UnLockInstanceRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/unlockInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/instance/{instance_id}": { + "get": { + "description": "GetInstanceInfo 查看实例详情", + "tags": [ + "instance" + ], + "operationId": "getInstanceInfo", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/getInstanceInfo" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteInstance 删除实例", + "tags": [ + "instance" + ], + "operationId": "deleteInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/keypair": { + "get": { + "description": "GetKeypairList 获取keypair列表", + "tags": [ + "keypair" + ], + "operationId": "getKeypairList", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Name", + "name": "name", + "in": "query" + }, + { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "KeypairIds", + "name": "keypairId", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getKeypairList" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "CreateKeypair 创建keypair", + "tags": [ + "keypair" + ], + "operationId": "createKeypair", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateKeypairRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createKeypair" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/keypair/checkKeypairName": { + "get": { + "description": "CheckKeypairName 查询keypair名称是否已存在", + "tags": [ + "keypair" + ], + "operationId": "checkKeypairName", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Name", + "name": "name", + "in": "query" + }, + { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "KeypairIds", + "name": "keypairId", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/checkKeypairName" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/keypair/{keypair_id}": { + "get": { + "description": "GetKeypairInfo 获取keypair详情", + "tags": [ + "keypair" + ], + "operationId": "getKeypairInfo", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "KeypairID", + "name": "keypair_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/getKeypairInfo" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyKeypair 修改keypair信息", + "tags": [ + "keypair" + ], + "operationId": "modifyKeypair", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "KeypairID", + "name": "keypair_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyKeypairRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyKeypair" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteKeypair 删除keypair", + "tags": [ + "keypair" + ], + "operationId": "deleteKeypair", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "KeypairID", + "name": "keypair_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteKeypair" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/login": { + "post": { + "description": "Login 登录", + "tags": [ + "user" + ], + "operationId": "login", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/LoginRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/login" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/logout": { + "post": { + "description": "Logout 登出", + "tags": [ + "user" + ], + "operationId": "logout", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/logout" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/partition/queryDefaultSystemPartitions": { + "get": { + "description": "QueryDefaultSystemPartitions 根据机型和镜像查系统盘默认分区列表", + "tags": [ + "keypair" + ], + "operationId": "queryDefaultSystemPartitions", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ImageID", + "name": "imageId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "name": "deviceTypeId", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/queryDefaultSystemPartitions" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project": { + "get": { + "description": "GetProjectList 获取项目列表", + "tags": [ + "project" + ], + "operationId": "getProjectList", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ProjectName", + "name": "projectName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ExportType", + "name": "exportType", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getProjectList" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "CreateProject 创建项目", + "tags": [ + "project" + ], + "operationId": "createProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateProjectRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/{project_id}": { + "get": { + "description": "GetProject 获取项目详情", + "tags": [ + "project" + ], + "operationId": "getProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/getProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "ModifyProject 修改项目", + "tags": [ + "project" + ], + "operationId": "modifyProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyProjectRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteProject 删除项目", + "tags": [ + "project" + ], + "operationId": "deleteProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/raid/queryRaidsByDeviceTypeIDAndVolumeType": { + "get": { + "description": "QueryRaidsByDeviceTypeIDAndVolumeType 根据机型查询系统盘/数据盘可用raid列表", + "tags": [ + "raid" + ], + "operationId": "queryRaidsByDeviceTypeIDAndVolumeType", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "VolumeType", + "name": "volumeType", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/queryRaidsByDeviceTypeIDAndVolumeType" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user": { + "get": { + "description": "GetUserInfo 获取用户详情", + "tags": [ + "user" + ], + "operationId": "getUserInfo", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getUserInfo" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "UpdateUserInfo 修改个人信息(除密码)", + "tags": [ + "user" + ], + "operationId": "updateUserInfo", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyUserInfoRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/updateUserInfo" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/password": { + "put": { + "description": "UpdatePassword 修改密码", + "tags": [ + "user" + ], + "operationId": "updatePassword", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/UpdatePasswordRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/updatePassword" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/timezones": { + "get": { + "description": "GetTimezoneList 获取时区列表", + "tags": [ + "user" + ], + "operationId": "getTimezoneList", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Cookie", + "name": "cookie", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getTimezoneList" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + } + }, + "definitions": { + "Apikey": { + "description": "Apikey apikey", + "type": "object", + "properties": { + "apiKeyId": { + "description": "apikey ID", + "type": "string", + "x-go-name": "ApikeyID" + }, + "createdBy": { + "description": "created by", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "created time", + "type": "string", + "x-go-name": "CreatedTime" + }, + "id": { + "description": "ID", + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "name": { + "description": "name", + "type": "string", + "x-go-name": "Name" + }, + "readOnly": { + "description": "read only", + "type": "integer", + "format": "int8", + "x-go-name": "ReadOnly" + }, + "token": { + "description": "token", + "type": "string", + "x-go-name": "Token" + }, + "type": { + "description": "type", + "type": "string", + "x-go-name": "Type" + }, + "updatedBy": { + "description": "updated by", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "updated time", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "userId": { + "description": "user ID", + "type": "string", + "x-go-name": "UserID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + }, + "ApikeyId": { + "type": "object", + "properties": { + "apikeyId": { + "type": "string", + "x-go-name": "ApikeyId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + }, + "ApikeyList": { + "description": "ApikeyList apikey list", + "type": "object", + "properties": { + "apikeys": { + "description": "apikeys", + "type": "array", + "items": { + "$ref": "#/definitions/Apikey" + }, + "x-go-name": "Apikeys" + }, + "pageNumber": { + "description": "page number", + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "description": "page size", + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "description": "total count", + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + }, + "CommonResponse": { + "description": "新增加或者删除返给前端的true或者false", + "type": "object", + "properties": { + "success": { + "type": "boolean", + "x-go-name": "Success" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + }, + "CreateApikeyRequest": { + "description": "CreateApikeyRequest create apikey request", + "type": "object", + "properties": { + "name": { + "description": "name", + "type": "string", + "x-go-name": "Name" + }, + "readOnly": { + "description": "read only", + "type": "integer", + "format": "int8", + "x-go-name": "ReadOnly" + }, + "type": { + "description": "type", + "type": "string", + "x-go-name": "Type" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + }, + "CreateInstanceRequest": { + "description": "CreateInstanceRequest create instance request", + "type": "object", + "properties": { + "count": { + "description": "count", + "type": "integer", + "format": "int64", + "x-go-name": "Count" + }, + "description": { + "description": "description", + "type": "string", + "x-go-name": "Description" + }, + "deviceTypeId": { + "description": "device type ID", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "hostname": { + "description": "host name", + "type": "string", + "x-go-name": "HostName" + }, + "idcId": { + "description": "idc ID", + "type": "string", + "x-go-name": "IdcID" + }, + "imageId": { + "description": "image ID", + "type": "string", + "x-go-name": "ImageID" + }, + "instanceName": { + "description": "instance name", + "type": "string", + "x-go-name": "InstanceName" + }, + "password": { + "description": "password", + "type": "string", + "x-go-name": "Password" + }, + "projectId": { + "description": "project ID", + "type": "string", + "x-go-name": "ProjectID" + }, + "sshKeyId": { + "description": "Ssh key ID", + "type": "string", + "x-go-name": "SSHKeyID" + }, + "systemPartition": { + "description": "system partition", + "type": "array", + "items": { + "$ref": "#/definitions/Partition" + }, + "x-go-name": "SystemPartition" + }, + "systemVolumeRaidId": { + "description": "system volume raid ID", + "type": "string", + "x-go-name": "SystemVolumeRaidID" + }, + "username": { + "description": "user name", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + }, + "CreateInstanceResponse": { + "type": "object", + "properties": { + "instanceIds": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIDs" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + }, + "CreateKeypairRequest": { + "type": "object", + "properties": { + "clientToken": { + "type": "integer", + "format": "int64", + "x-go-name": "ClientToken" + }, + "key": { + "type": "string", + "x-go-name": "Key" + }, + "name": { + "type": "string", + "x-go-name": "Name" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + }, + "CreateProjectRequest": { + "description": "CreateProjectRequest create project request", + "type": "object", + "properties": { + "isDefault": { + "description": "is default", + "type": "integer", + "format": "int8", + "x-go-name": "IsDefault" + }, + "isSystem": { + "description": "is system", + "type": "integer", + "format": "int8", + "x-go-name": "IsSystem" + }, + "projectName": { + "description": "ProjectName 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-”", + "type": "string", + "x-go-name": "ProjectName" + }, + "userId": { + "description": "user ID", + "type": "string", + "x-go-name": "UserID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + }, + "DeviceType": { + "type": "object", + "properties": { + "availableStock": { + "description": "IsStockAvailable 是否有库存", + "type": "integer", + "format": "int64", + "x-go-name": "AvailableStock" + }, + "cpu": { + "type": "string", + "x-go-name": "Cpu" + }, + "data": { + "type": "string", + "x-go-name": "Data" + }, + "deviceSeries": { + "type": "string", + "x-go-name": "DeviceSeries" + }, + "deviceSeriesName": { + "type": "string", + "x-go-name": "DeviceSeriesName" + }, + "deviceTypeId": { + "type": "string", + "x-go-name": "DeviceTypeId" + }, + "gpu": { + "type": "string", + "x-go-name": "Gpu" + }, + "mem": { + "type": "string", + "x-go-name": "Mem" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "nic": { + "type": "string", + "x-go-name": "Nic" + }, + "system": { + "type": "string", + "x-go-name": "System" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + }, + "ErrorResponse": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "type": "string", + "x-go-name": "Message" + }, + "status": { + "type": "string", + "x-go-name": "Status" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/controllers" + }, + "GetTimezoneListResponse": { + "type": "object", + "properties": { + "timezones": { + "$ref": "#/definitions/OrderedJsonDict" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + }, + "Idc": { + "description": "Idc idc", + "type": "object", + "properties": { + "address": { + "description": "address", + "type": "string", + "x-go-name": "Address" + }, + "cabinetNum": { + "description": "cabinet num", + "type": "integer", + "format": "int64", + "x-go-name": "CabinetNum" + }, + "createTime": { + "description": "create time", + "type": "string", + "x-go-name": "CreateTime" + }, + "createdBy": { + "description": "created by", + "type": "string", + "x-go-name": "CreatedBy" + }, + "id": { + "description": "ID", + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "idcId": { + "description": "i dc ID", + "type": "string", + "x-go-name": "IDcID" + }, + "iloPassword": { + "description": "ilo password", + "type": "string", + "x-go-name": "IloPassword" + }, + "iloUser": { + "description": "ilo user", + "type": "string", + "x-go-name": "IloUser" + }, + "level": { + "description": "level", + "type": "string", + "x-go-name": "Level" + }, + "name": { + "description": "name", + "type": "string", + "x-go-name": "Name" + }, + "nameEn": { + "description": "name en", + "type": "string", + "x-go-name": "NameEn" + }, + "shortname": { + "description": "shortname", + "type": "string", + "x-go-name": "Shortname" + }, + "switchPassword1": { + "description": "switch password1", + "type": "string", + "x-go-name": "SwitchPassword1" + }, + "switchPassword2": { + "description": "switch password2", + "type": "string", + "x-go-name": "SwitchPassword2" + }, + "switchUser1": { + "description": "switch user1", + "type": "string", + "x-go-name": "SwitchUser1" + }, + "switchUser2": { + "description": "switch user2", + "type": "string", + "x-go-name": "SwitchUser2" + }, + "updateTime": { + "description": "update time", + "type": "string", + "x-go-name": "UpdateTime" + }, + "updatedBy": { + "description": "updated by", + "type": "string", + "x-go-name": "UpdatedBy" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + }, + "IdcList": { + "description": "IdcList idc list", + "type": "object", + "properties": { + "idcs": { + "description": "idcs", + "type": "array", + "items": { + "$ref": "#/definitions/Idc" + }, + "x-go-name": "Idcs" + }, + "pageNumber": { + "description": "page number", + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "description": "page size", + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "description": "total count", + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + }, + "Image": { + "description": "Image image", + "type": "object", + "properties": { + "architecture": { + "description": "architecture", + "type": "string", + "x-go-name": "Architecture" + }, + "createdBy": { + "description": "created by", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "created time", + "type": "string", + "x-go-name": "CreatedTime" + }, + "dataPartition": { + "description": "data partition", + "type": "string", + "x-go-name": "DataPartition" + }, + "description": { + "description": "description", + "type": "string", + "x-go-name": "Description" + }, + "deviceTypeNum": { + "description": "device type num", + "type": "integer", + "format": "int64", + "x-go-name": "DeviceTypeNum" + }, + "filename": { + "description": "filename", + "type": "string", + "x-go-name": "Filename" + }, + "format": { + "description": "format", + "type": "string", + "x-go-name": "Format" + }, + "hash": { + "description": "hash", + "type": "string", + "x-go-name": "Hash" + }, + "id": { + "description": "ID", + "type": "integer", + "format": "uint64", + "x-go-name": "ID" + }, + "imageId": { + "description": "image ID", + "type": "string", + "x-go-name": "ImageID" + }, + "imageName": { + "description": "image name", + "type": "string", + "x-go-name": "ImageName" + }, + "isBind": { + "description": "is bind", + "type": "boolean", + "x-go-name": "IsBind" + }, + "osId": { + "description": "os ID", + "type": "string", + "x-go-name": "OsID" + }, + "osName": { + "description": "os name", + "type": "string", + "x-go-name": "OsName" + }, + "osType": { + "description": "os type", + "type": "string", + "x-go-name": "OsType" + }, + "osVersion": { + "description": "os version", + "type": "string", + "x-go-name": "OsVersion" + }, + "source": { + "description": "source", + "type": "string", + "x-go-name": "Source" + }, + "sourceName": { + "description": "source name", + "type": "string", + "x-go-name": "SourceName" + }, + "systemPartition": { + "description": "system partition", + "type": "string", + "x-go-name": "SystemPartition" + }, + "updatedBy": { + "description": "updated by", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "updated time", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "url": { + "description": "URL", + "type": "string", + "x-go-name": "URL" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + }, + "Instance": { + "description": "列表", + "type": "object", + "properties": { + "DataVolumeRaidName": { + "description": "data volume raid name", + "type": "string" + }, + "StatusName": { + "description": "status name", + "type": "string" + }, + "cpuAmount": { + "description": "CPU amount", + "type": "integer", + "format": "int8", + "x-go-name": "CPUAmount" + }, + "cpuCores": { + "description": "CPU cores", + "type": "integer", + "format": "int8", + "x-go-name": "CPUCores" + }, + "cpuFrequency": { + "description": "CPU frequency", + "type": "string", + "x-go-name": "CPUFrequency" + }, + "cpuInfo": { + "type": "string", + "x-go-name": "CpuInfo" + }, + "cpuManufacturer": { + "description": "CPU manufacturer", + "type": "string", + "x-go-name": "CPUManufacturer" + }, + "cpuModel": { + "description": "CPU model", + "type": "string", + "x-go-name": "CPUModel" + }, + "createdBy": { + "description": "created by", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "created time", + "type": "string", + "x-go-name": "CreatedTime" + }, + "dataInfo": { + "type": "string", + "x-go-name": "DataInfo" + }, + "dataVolumeAmount": { + "description": "data volume amount", + "type": "integer", + "format": "int8", + "x-go-name": "DataVolumeAmount" + }, + "dataVolumeInterfaceType": { + "description": "data volume interface type", + "type": "string", + "x-go-name": "DataVolumeInterfaceType" + }, + "dataVolumeRaidId": { + "description": "data volume raid ID", + "type": "string", + "x-go-name": "DataVolumeRaidID" + }, + "dataVolumeSize": { + "description": "data volume size", + "type": "integer", + "format": "int64", + "x-go-name": "DataVolumeSize" + }, + "dataVolumeType": { + "description": "data volume type", + "type": "string", + "x-go-name": "DataVolumeType" + }, + "description": { + "description": "description", + "type": "string", + "x-go-name": "Description" + }, + "deviceId": { + "description": "device ID", + "type": "string", + "x-go-name": "DeviceID" + }, + "deviceSeries": { + "description": "device series", + "type": "string", + "x-go-name": "DeviceSeries" + }, + "deviceSeriesName": { + "description": "device series name", + "type": "string", + "x-go-name": "DeviceSeriesName" + }, + "deviceType": { + "description": "device type", + "type": "string", + "x-go-name": "DeviceType" + }, + "deviceTypeId": { + "description": "device type ID", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "deviceTypeName": { + "description": "device type name", + "type": "string", + "x-go-name": "DeviceTypeName" + }, + "gpuAmount": { + "description": "gpu amount", + "type": "integer", + "format": "int8", + "x-go-name": "GpuAmount" + }, + "gpuInfo": { + "type": "string", + "x-go-name": "GpuInfo" + }, + "gpuManufacturer": { + "description": "gpu manufacturer", + "type": "string", + "x-go-name": "GpuManufacturer" + }, + "gpuModel": { + "description": "gpu model", + "type": "string", + "x-go-name": "GpuModel" + }, + "hostname": { + "description": "hostname", + "type": "string", + "x-go-name": "Hostname" + }, + "idcId": { + "description": "i dc ID", + "type": "string", + "x-go-name": "IDcID" + }, + "idcName": { + "description": "idc name", + "type": "string", + "x-go-name": "IdcName" + }, + "iloIp": { + "description": "ilo IP", + "type": "string", + "x-go-name": "IloIP" + }, + "imageId": { + "description": "image ID", + "type": "string", + "x-go-name": "ImageID" + }, + "imageName": { + "description": "image name", + "type": "string", + "x-go-name": "ImageName" + }, + "instanceId": { + "description": "instance ID", + "type": "string", + "x-go-name": "InstanceID" + }, + "instanceName": { + "description": "instance name", + "type": "string", + "x-go-name": "InstanceName" + }, + "interfaceMode": { + "description": "interface mode", + "type": "string", + "x-go-name": "InterfaceMode" + }, + "locked": { + "description": "locked", + "type": "string", + "x-go-name": "Locked" + }, + "lockedName": { + "description": "locked name", + "type": "string", + "x-go-name": "LockedName" + }, + "memAmount": { + "description": "mem amount", + "type": "integer", + "format": "int64", + "x-go-name": "MemAmount" + }, + "memFrequency": { + "description": "mem frequency", + "type": "integer", + "format": "int64", + "x-go-name": "MemFrequency" + }, + "memInfo": { + "type": "string", + "x-go-name": "MemInfo" + }, + "memSize": { + "description": "mem size", + "type": "integer", + "format": "int64", + "x-go-name": "MemSize" + }, + "memType": { + "description": "mem type", + "type": "string", + "x-go-name": "MemType" + }, + "nicAmount": { + "description": "nic amount", + "type": "integer", + "format": "int8", + "x-go-name": "NicAmount" + }, + "nicInfo": { + "type": "string", + "x-go-name": "NicInfo" + }, + "nicRate": { + "description": "nic rate", + "type": "integer", + "format": "int64", + "x-go-name": "NicRate" + }, + "privateIpv4": { + "description": "private IPv4", + "type": "string", + "x-go-name": "PrivateIPV4" + }, + "privateIpv6": { + "description": "private IPv6", + "type": "string", + "x-go-name": "PrivateIPV6" + }, + "projectId": { + "description": "project ID", + "type": "string", + "x-go-name": "ProjectID" + }, + "reason": { + "description": "reason", + "type": "string", + "x-go-name": "Reason" + }, + "sn": { + "description": "sn", + "type": "string", + "x-go-name": "Sn" + }, + "status": { + "description": "status", + "type": "string", + "x-go-name": "Status" + }, + "systemInfo": { + "type": "string", + "x-go-name": "SystemInfo" + }, + "systemVolumeAmount": { + "description": "system volume amount", + "type": "integer", + "format": "int8", + "x-go-name": "SystemVolumeAmount" + }, + "systemVolumeInterfaceType": { + "description": "system volume interface type", + "type": "string", + "x-go-name": "SystemVolumeInterfaceType" + }, + "systemVolumeRaidId": { + "description": "system volume raid ID", + "type": "string", + "x-go-name": "SystemVolumeRaidID" + }, + "systemVolumeRaidName": { + "description": "system volume raid name", + "type": "string", + "x-go-name": "SystemVolumeRaidName" + }, + "systemVolumeSize": { + "description": "system volume size", + "type": "integer", + "format": "int64", + "x-go-name": "SystemVolumeSize" + }, + "systemVolumeType": { + "description": "system volume type", + "type": "string", + "x-go-name": "SystemVolumeType" + }, + "updatedBy": { + "description": "updated by", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "updated time", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "userId": { + "description": "user ID", + "type": "string", + "x-go-name": "UserID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + }, + "InstanceInfo": { + "description": "详情使用", + "type": "object", + "properties": { + "instance": { + "$ref": "#/definitions/Instance" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + }, + "InstancesResponse": { + "type": "object", + "properties": { + "instances": { + "type": "array", + "items": { + "$ref": "#/definitions/Instance" + }, + "x-go-name": "Instances" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + }, + "KeyPair": { + "description": "给列表用的", + "type": "object", + "properties": { + "createdTime": { + "type": "string", + "x-go-name": "CreatedTime" + }, + "fingerPrint": { + "type": "string", + "x-go-name": "FingerPrint" + }, + "isCheckDelete": { + "type": "string", + "x-go-name": "IsCheckDelete" + }, + "keypairId": { + "type": "string", + "x-go-name": "KeypairId" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "privateKey": { + "type": "string", + "x-go-name": "PrivateKey" + }, + "publicKey": { + "type": "string", + "x-go-name": "PublicKey" + }, + "updatedTime": { + "type": "string", + "x-go-name": "UpdatedTime" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + }, + "KeyPairInfo": { + "description": "给详情用的", + "type": "object", + "properties": { + "keypair": { + "type": "object", + "properties": { + "createdTime": { + "type": "string", + "x-go-name": "CreatedTime" + }, + "fingerPrint": { + "type": "string", + "x-go-name": "FingerPrint" + }, + "isCheckDelete": { + "type": "string", + "x-go-name": "IsCheckDelete" + }, + "keypairId": { + "type": "string", + "x-go-name": "KeypairId" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "privateKey": { + "type": "string", + "x-go-name": "PrivateKey" + }, + "publicKey": { + "type": "string", + "x-go-name": "PublicKey" + }, + "updatedTime": { + "type": "string", + "x-go-name": "UpdatedTime" + } + }, + "x-go-name": "Keypair" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + }, + "KeyPairsResponse": { + "type": "object", + "properties": { + "keypairs": { + "type": "array", + "items": { + "$ref": "#/definitions/KeyPair" + }, + "x-go-name": "Keypairs" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + }, + "LockInstanceRequest": { + "type": "object", + "properties": { + "idc_id": { + "type": "string", + "x-go-name": "IdcID" + }, + "instanceId": { + "type": "string", + "x-go-name": "InstanceId" + }, + "token": { + "type": "string", + "x-go-name": "Token" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + }, + "LoginRequest": { + "type": "object", + "properties": { + "password": { + "type": "string", + "x-go-name": "Password" + }, + "username": { + "type": "string", + "x-go-name": "Username" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + }, + "ModifyKeypairRequest": { + "type": "object", + "properties": { + "clientToken": { + "type": "integer", + "format": "int64", + "x-go-name": "ClientToken" + }, + "name": { + "type": "string", + "x-go-name": "Name" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + }, + "ModifyProjectRequest": { + "description": "ModifyProjectRequest modify project request", + "type": "object", + "properties": { + "projectName": { + "description": "ProjectName 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-”", + "type": "string", + "x-go-name": "ProjectName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + }, + "ModifyUserInfoRequest": { + "description": "【用户管理】【编辑用户信息】", + "type": "object", + "properties": { + "defaultProjectId": { + "type": "string", + "x-go-name": "DefaultProjectID" + }, + "description": { + "type": "string", + "x-go-name": "Description" + }, + "email": { + "type": "string", + "x-go-name": "Email" + }, + "language": { + "type": "string", + "x-go-name": "Language" + }, + "phoneNumber": { + "type": "string", + "x-go-name": "PhoneNumber" + }, + "phonePrefix": { + "type": "string", + "x-go-name": "PhonePrefix" + }, + "timezone": { + "type": "string", + "x-go-name": "Timezone" + }, + "userName": { + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + }, + "OrderedJsonDict": { + "type": "object", + "properties": { + "Keys": { + "type": "array", + "items": { + "type": "string" + } + }, + "M": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + }, + "Partition": { + "description": "Partition 镜像默认分区\n[{\"format\":\"swap\",\"point\":\"swap\",\"size\":10240},{\"format\":\"xfs\",\"point\":\"/\",\"size\":51200}]", + "type": "object", + "properties": { + "format": { + "description": "fs type", + "type": "string", + "x-go-name": "FsType" + }, + "point": { + "description": "mount point", + "type": "string", + "x-go-name": "MountPoint" + }, + "size": { + "description": "size", + "type": "integer", + "format": "int64", + "x-go-name": "Size" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + }, + "Project": { + "type": "object", + "properties": { + "createdBy": { + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "type": "string", + "x-go-name": "CreatedTime" + }, + "instanceCount": { + "type": "integer", + "format": "int64", + "x-go-name": "InstanceCount" + }, + "projectId": { + "type": "string", + "x-go-name": "ProjectID" + }, + "projectName": { + "type": "string", + "x-go-name": "ProjectName" + }, + "updatedBy": { + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "type": "string", + "x-go-name": "UpdatedTime" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + }, + "ProjectId": { + "type": "object", + "properties": { + "projectId": { + "type": "string", + "x-go-name": "ProjectId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + }, + "ProjectList": { + "description": "ProjectList project list", + "type": "object", + "properties": { + "pageNumber": { + "description": "page number", + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "description": "page size", + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "projects": { + "description": "projects", + "type": "array", + "items": { + "$ref": "#/definitions/Project" + }, + "x-go-name": "Projects" + }, + "totalCount": { + "description": "total count", + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + }, + "QueryDeviceStockResponse": { + "type": "object", + "properties": { + "avaliableCount": { + "type": "integer", + "format": "int64", + "x-go-name": "AvaliableCount" + }, + "success": { + "type": "boolean", + "x-go-name": "Success" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + }, + "RDeviceTypeRaid": { + "description": "RDeviceTypeRaid r device type raid", + "type": "object", + "properties": { + "DiskInterfaceType": { + "description": "disk interface type", + "type": "string" + }, + "availableValue": { + "description": "available value", + "type": "integer", + "format": "int64", + "x-go-name": "AvailableValue" + }, + "createdBy": { + "description": "created by", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "created time", + "type": "string", + "x-go-name": "CreatedTime" + }, + "deviceTypeId": { + "description": "device type ID", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "diskType": { + "description": "disk type", + "type": "string", + "x-go-name": "DiskType" + }, + "raidId": { + "description": "raid ID", + "type": "string", + "x-go-name": "RaidID" + }, + "systemPartitionCount": { + "description": "system partition count", + "type": "integer", + "format": "int64", + "x-go-name": "SystemPartitionCount" + }, + "updatedBy": { + "description": "updated by", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "updated time", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "volumeDetail": { + "description": "volume detail", + "type": "string", + "x-go-name": "VolumeDetail" + }, + "volumeType": { + "description": "volume type", + "type": "string", + "x-go-name": "VolumeType" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + }, + "RestartInstanceRequest": { + "type": "object", + "properties": { + "clientToken": { + "type": "integer", + "format": "int64", + "x-go-name": "ClientToken" + }, + "idc_id": { + "type": "string", + "x-go-name": "IdcID" + }, + "instanceId": { + "type": "string", + "x-go-name": "InstanceId" + }, + "token": { + "type": "string", + "x-go-name": "Token" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + }, + "SetCustomInfoRequest": { + "type": "object", + "properties": { + "pageKey": { + "type": "string", + "x-go-name": "PageKey" + }, + "pageValue": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "boolean" + } + }, + "x-go-name": "PageValue" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + }, + "StartInstanceRequest": { + "type": "object", + "properties": { + "clientToken": { + "type": "integer", + "format": "int64", + "x-go-name": "ClientToken" + }, + "idc_id": { + "type": "string", + "x-go-name": "IdcID" + }, + "instanceId": { + "type": "string", + "x-go-name": "InstanceId" + }, + "token": { + "type": "string", + "x-go-name": "Token" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + }, + "StopInstanceRequest": { + "type": "object", + "properties": { + "clientToken": { + "type": "integer", + "format": "int64", + "x-go-name": "ClientToken" + }, + "idc_id": { + "type": "string", + "x-go-name": "IdcID" + }, + "instanceId": { + "type": "string", + "x-go-name": "InstanceId" + }, + "token": { + "type": "string", + "x-go-name": "Token" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + }, + "UnLockInstanceRequest": { + "type": "object", + "properties": { + "idc_id": { + "type": "string", + "x-go-name": "IdcID" + }, + "instanceId": { + "type": "string", + "x-go-name": "InstanceId" + }, + "token": { + "type": "string", + "x-go-name": "Token" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + }, + "UpdatePasswordRequest": { + "type": "object", + "properties": { + "oldPassword": { + "type": "string", + "x-go-name": "OldPassword" + }, + "password": { + "type": "string", + "x-go-name": "Password" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + }, + "User": { + "type": "object", + "properties": { + "DefaultProjectName": { + "type": "string" + }, + "createdBy": { + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "type": "string", + "x-go-name": "CreatedTime" + }, + "defaultProjectId": { + "type": "string", + "x-go-name": "DefaultProjectID" + }, + "description": { + "type": "string", + "x-go-name": "Description" + }, + "email": { + "type": "string", + "x-go-name": "Email" + }, + "id": { + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "language": { + "type": "string", + "x-go-name": "Language" + }, + "password": { + "type": "string", + "x-go-name": "Password" + }, + "phoneNumber": { + "type": "string", + "x-go-name": "PhoneNumber" + }, + "phonePrefix": { + "type": "string", + "x-go-name": "PhonePrefix" + }, + "roleId": { + "type": "string", + "x-go-name": "RoleID" + }, + "roleName": { + "type": "string", + "x-go-name": "RoleName" + }, + "timezone": { + "type": "string", + "x-go-name": "Timezone" + }, + "updatedBy": { + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "type": "string", + "x-go-name": "UpdatedTime" + }, + "userId": { + "type": "string", + "x-go-name": "UserID" + }, + "userName": { + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + } + }, + "responses": { + "ErrorResponse": { + "description": "unit err response for non 200", + "schema": { + "type": "object", + "properties": { + "error": { + "$ref": "#/definitions/ErrorResponse" + }, + "requestId": { + "type": "string", + "x-go-name": "RequestId" + } + } + } + }, + "checkKeypairName": { + "description": "CheckKeypairNameResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "createApikey": { + "description": "CreateApikeyResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/ApikeyId" + } + } + } + }, + "createInstance": { + "description": "CreateInstanceResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CreateInstanceResponse" + } + } + } + }, + "createKeypair": { + "description": "CreateKeypairResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/KeyPair" + } + } + } + }, + "createProject": { + "description": "CreateProjectResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/ProjectId" + } + } + } + }, + "deleteApikey": { + "description": "DeleteApikeyResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "deleteInstance": { + "description": "DeleteInstanceResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "deleteKeypair": { + "description": "DeleteKeypairResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "deleteProject": { + "description": "DeleteProjectResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "getApikeyList": { + "description": "GetApikeyListResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/ApikeyList" + } + } + } + }, + "getAvailableDeviceTypes": { + "description": "GetAvailableDeviceTypesResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "$ref": "#/definitions/DeviceType" + } + }, + "x-go-name": "Result" + } + } + } + }, + "getCustomInfo": { + "description": "GetCustomInfoResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "getIdcList": { + "description": "GetIdcListResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/IdcList" + } + } + } + }, + "getInstanceInfo": { + "description": "GetInstanceInfoResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/InstanceInfo" + } + } + } + }, + "getInstanceList": { + "description": "GetInstanceListResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/InstancesResponse" + } + } + } + }, + "getKeypairInfo": { + "description": "GetKeypairInfoResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/KeyPairInfo" + } + } + } + }, + "getKeypairList": { + "description": "GetKeypairListResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/KeyPairsResponse" + } + } + } + }, + "getProject": { + "description": "GetProjectResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/Project" + } + } + } + }, + "getProjectList": { + "description": "GetProjectListResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/ProjectList" + } + } + } + }, + "getTimezoneList": { + "description": "GetTimezoneListResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/GetTimezoneListResponse" + } + } + } + }, + "getUserInfo": { + "description": "GetUserInfoResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/User" + } + } + } + }, + "isDeviceStockEnough": { + "description": "IsDeviceStockEnoughResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/QueryDeviceStockResponse" + } + } + } + }, + "lockInstance": { + "description": "LockInstanceResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "login": { + "description": "LoginResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "logout": { + "description": "LogoutResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "modifyKeypair": { + "description": "ModifyKeypairResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "modifyProject": { + "description": "ModifyProjectResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "queryDefaultSystemPartitions": { + "description": "QueryDefaultSystemPartitionsResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "type": "array", + "items": { + "$ref": "#/definitions/Partition" + }, + "x-go-name": "Result" + } + } + } + }, + "queryImagesByDeviceType": { + "description": "QueryImagesByDeviceTypeResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "$ref": "#/definitions/Image" + } + }, + "x-go-name": "Result" + } + } + } + }, + "queryRaidsByDeviceTypeIDAndVolumeType": { + "description": "QueryRaidsByDeviceTypeIDAndVolumeTypeResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "type": "array", + "items": { + "$ref": "#/definitions/RDeviceTypeRaid" + }, + "x-go-name": "Result" + } + } + } + }, + "restartInstance": { + "description": "RestartInstanceResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "setCustomInfo": { + "description": "SetCustomInfoResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "startInstance": { + "description": "StartInstanceResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "stopInstance": { + "description": "StopInstanceResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "unlockInstance": { + "description": "UnlockInstanceResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "updatePassword": { + "description": "UpdatePasswordResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + }, + "updateUserInfo": { + "description": "UpdateUserInfoResponse is an response struct", + "schema": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "x-go-name": "RequestId" + }, + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + } + } + } +} \ No newline at end of file diff --git a/bmp-console-api/swagger.yml b/bmp-console-api/swagger.yml new file mode 100644 index 0000000..3efdf95 --- /dev/null +++ b/bmp-console-api/swagger.yml @@ -0,0 +1,4539 @@ +basePath: / +consumes: + - application/json +definitions: + Apikey: + description: Apikey apikey + properties: + apiKeyId: + description: apikey uuid + type: string + x-go-name: ApikeyID + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + id: + description: ID + format: int64 + type: integer + x-go-name: ID + name: + description: 名称 + type: string + x-go-name: Name + readOnly: + description: 是否支持只读, [0/1], 1表示只读 + format: int8 + type: integer + x-go-name: ReadOnly + token: + description: 32位字符令牌,使用token来独立访问openapi + type: string + x-go-name: Token + type: + description: apikey的类型,[system/user] + type: string + x-go-name: Type + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + userId: + description: 所属用户uuid + type: string + x-go-name: UserID + required: + - apiKeyId + - name + - readOnly + - token + - type + - userId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + ApikeyId: + properties: + apikeyId: + type: string + x-go-name: ApikeyId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + ApikeyList: + description: ApikeyList apikey list + properties: + apikeys: + description: apikeys + items: + $ref: '#/definitions/Apikey' + type: array + x-go-name: Apikeys + pageNumber: + description: page number + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + description: page size + format: int64 + type: integer + x-go-name: PageSize + totalCount: + description: total count + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + AuditLog: + description: AuditLog audit log + properties: + deviceId: + description: device_id + type: string + x-go-name: DeviceID + failReason: + description: 失败原因 + type: string + x-go-name: FailReason + finishTime: + description: 完成时间 + format: int64 + type: integer + x-go-name: FinishTime + id: + description: ID + format: int64 + type: integer + x-go-name: ID + instanceId: + description: instance_id + type: string + x-go-name: InstanceID + logid: + description: 日志uuid + type: string + x-go-name: LogID + operateTime: + description: 操作时间 + format: int64 + type: integer + x-go-name: OperateTime + operation: + description: 操作 + type: string + x-go-name: Operation + operationName: + description: 操作名称 + type: string + x-go-name: OperationName + result: + description: 结果 success/fail + type: string + x-go-name: Result + sn: + description: sn + type: string + x-go-name: Sn + userID: + description: 操作人 + type: string + x-go-name: UserID + userName: + description: 操作人 + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + AuditLogsList: + properties: + messages: + items: + $ref: '#/definitions/AuditLog' + type: array + x-go-name: AuditLogs + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + CommonResponse: + description: 新增加或者删除返给前端的true或者false + properties: + success: + type: boolean + x-go-name: Success + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + CreateApikeyRequest: + description: CreateApikeyRequest create apikey request + properties: + name: + description: 秘钥对名称 + type: string + x-go-name: Name + readOnly: + description: 是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法 + format: int8 + type: integer + x-go-name: ReadOnly + type: + description: Token类型, [system/user] + type: string + x-go-name: Type + required: + - name + - readOnly + - type + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + CreateInstanceRequest: + description: CreateInstanceRequest create instance request + properties: + VolumeRaids: + description: 数据卷和选择的raidid + items: + $ref: '#/definitions/VolumeRaID' + type: array + x-go-name: VolumeRaIDs + bootMode: + description: boot mode + type: string + x-go-name: BootMode + count: + description: 创建数量 + format: int64 + type: integer + x-go-name: Count + description: + description: 描述 + type: string + x-go-name: Description + deviceTypeId: + description: 设备类型ID + type: string + x-go-name: DeviceTypeID + hostname: + description: 主机名称 + type: string + x-go-name: HostName + idcId: + description: 机房ID + type: string + x-go-name: IdcID + imageId: + description: 镜像ID + type: string + x-go-name: ImageID + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + password: + description: 密码 + type: string + x-go-name: Password + projectId: + description: 项目ID + type: string + x-go-name: ProjectID + sshKeyId: + description: 秘钥ID + type: string + x-go-name: SSHKeyID + systemPartition: + description: 系统盘分区 + items: + $ref: '#/definitions/Partition' + type: array + x-go-name: SystemPartition + systemVolumeRaidId: + description: 系统盘RAID ID + type: string + x-go-name: SystemVolumeRaidID + required: + - deviceTypeId + - idcId + - imageId + - instanceName + - projectId + - systemVolumeRaidId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + CreateInstanceResponse: + properties: + instanceIds: + items: + type: string + type: array + x-go-name: InstanceIDs + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + CreateKeypairRequest: + properties: + clientToken: + format: int64 + type: integer + x-go-name: ClientToken + key: + type: string + x-go-name: Key + name: + type: string + x-go-name: Name + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + CreateProjectRequest: + description: CreateProjectRequest create project request + properties: + isDefault: + description: 是否作为该用户的默认项目, [0/1], 默认为0 + format: int8 + type: integer + x-go-name: IsDefault + isSystem: + description: 是否作为系统项目, [0/1], 默认为0 + format: int8 + type: integer + x-go-name: IsSystem + projectName: + description: ProjectName 1~64字符,只支持数字、大小写字母、中英文下划线“_”及中划线“-” + type: string + x-go-name: ProjectName + required: + - projectName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + DeleteMessagesRequest: + properties: + messageIds: + items: + type: string + type: array + x-go-name: MessageIds + required: + - messageIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + DeviceType: + properties: + availableStock: + description: IsStockAvailable 是否有库存 + format: int64 + type: integer + x-go-name: AvailableStock + boot_mode: + description: boot模式 + type: string + x-go-name: BootMode + cpu: + type: string + x-go-name: Cpu + data: + type: string + x-go-name: Data + deviceSeries: + type: string + x-go-name: DeviceSeries + deviceSeriesName: + type: string + x-go-name: DeviceSeriesName + deviceTypeId: + type: string + x-go-name: DeviceTypeId + gpu: + type: string + x-go-name: Gpu + isNeedRaid: + description: 是否需要做raid + type: string + x-go-name: IsNeedRaid + mem: + type: string + x-go-name: Mem + name: + type: string + x-go-name: Name + nic: + type: string + x-go-name: Nic + system: + type: string + x-go-name: System + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + ErrorResponse: + properties: + code: + format: int64 + type: integer + x-go-name: Code + message: + type: string + x-go-name: Message + status: + type: string + x-go-name: Status + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/controllers + GetTimezoneListResponse: + properties: + timezones: + $ref: '#/definitions/OrderedJsonDict' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + HasUnreadMessage: + properties: + hasUnread: + type: boolean + x-go-name: HasUnread + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + Idc: + description: Idc idc + properties: + address: + description: 机房地址 + type: string + x-go-name: Address + createTime: + description: 创建时间 + type: string + x-go-name: CreateTime + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + id: + description: ID + format: int64 + type: integer + x-go-name: ID + idcId: + description: 机房uuid + type: string + x-go-name: IDcID + iloPassword: + description: 机房公用带外管理password + type: string + x-go-name: IloPassword + iloUser: + description: 机房公用带外管理user + type: string + x-go-name: IloUser + level: + description: 机房等级 + type: string + x-go-name: Level + name: + description: 机房名称 + type: string + x-go-name: Name + nameEn: + description: 机房名称en + type: string + x-go-name: NameEn + shortname: + description: shortname + type: string + x-go-name: Shortname + switchPassword1: + description: 交换机密码1 + type: string + x-go-name: SwitchPassword1 + switchPassword2: + description: 交换机密码2 + type: string + x-go-name: SwitchPassword2 + switchUser1: + description: 交换机用户名1 + type: string + x-go-name: SwitchUser1 + switchUser2: + description: 交换机用户名2 + type: string + x-go-name: SwitchUser2 + updateTime: + description: 修改时间 + type: string + x-go-name: UpdateTime + updatedBy: + description: 修改用户 + type: string + x-go-name: UpdatedBy + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + IdcList: + description: IdcList idc list + properties: + idcs: + description: 机房列表 + items: + $ref: '#/definitions/Idc' + type: array + x-go-name: Idcs + pageNumber: + description: 页数 + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + description: 页大小 + format: int64 + type: integer + x-go-name: PageSize + totalCount: + description: 总条数 + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + Image: + description: Image image + properties: + architecture: + description: 架构:x86/x64/i386/ + type: string + x-go-name: Architecture + bootMode: + description: 引导模式 【UEFI Legacy/BIOS】 + type: string + x-go-name: BootMode + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + dataPartition: + description: 数据分区信息 + type: string + x-go-name: DataPartition + description: + description: 描述 + type: string + x-go-name: Description + deviceTypeNum: + description: 绑定了机型数量 + format: int64 + type: integer + x-go-name: DeviceTypeNum + filename: + description: 镜像文件名称 + type: string + x-go-name: Filename + format: + description: 镜像格式(qcow2、tar) + type: string + x-go-name: Format + hash: + description: 镜像校验码 + type: string + x-go-name: Hash + id: + description: ID + format: uint64 + type: integer + x-go-name: ID + imageId: + description: 镜像uuid + type: string + x-go-name: ImageID + imageName: + description: 镜像名称 + type: string + x-go-name: ImageName + isBind: + description: 是否绑定了某个机型 + type: boolean + x-go-name: IsBind + osId: + description: 源os uuid + type: string + x-go-name: OsID + osName: + description: CentOS 7.2 64-bit + type: string + x-go-name: OsName + osType: + description: 操作系统分类:linux/windows + type: string + x-go-name: OsType + osVersion: + description: 操作系统版本 + type: string + x-go-name: OsVersion + source: + description: 镜像来源(common通用、customize定制、user_defined自定义) + type: string + x-go-name: Source + sourceName: + description: 镜像来源(common通用、customize定制、user_defined自定义) + type: string + x-go-name: SourceName + systemPartition: + description: 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + type: string + x-go-name: SystemPartition + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + url: + description: 镜像源路径 + type: string + x-go-name: URL + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + Instance: + description: 列表 + properties: + bootMode: + description: 引导模式 [UEFI Legacy/BIOS] + type: string + x-go-name: BootMode + cpuAmount: + description: cpu数量 + format: int64 + type: integer + x-go-name: CPUAmount + cpuCores: + description: 单个cpu内核数 + format: int64 + type: integer + x-go-name: CPUCores + cpuFrequency: + description: cpu频率(GHz) + type: string + x-go-name: CPUFrequency + cpuInfo: + type: string + x-go-name: CpuInfo + cpuManufacturer: + description: cpu厂商 + type: string + x-go-name: CPUManufacturer + cpuModel: + description: cpu处理器型号 + type: string + x-go-name: CPUModel + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + dataInfo: + type: string + x-go-name: DataInfo + description: + description: 实例描述 + type: string + x-go-name: Description + deviceId: + description: 设备uuid + type: string + x-go-name: DeviceID + deviceSeries: + description: 机型类型,如computer + type: string + x-go-name: DeviceSeries + deviceSeriesName: + description: 机型类型,如计算型,存储型 + type: string + x-go-name: DeviceSeriesName + deviceType: + description: 机型规格, cps.c.normal + type: string + x-go-name: DeviceType + deviceTypeId: + description: 机型uuid + type: string + x-go-name: DeviceTypeID + deviceTypeName: + description: 机型名称,如计算效能型,标准计算型 + type: string + x-go-name: DeviceTypeName + eth1Mask: + description: eth1 mask + type: string + x-go-name: Eth1Mask + gpuAmount: + description: gpu数量 + format: int64 + type: integer + x-go-name: GpuAmount + gpuInfo: + type: string + x-go-name: GpuInfo + gpuManufacturer: + description: gpu厂商 + type: string + x-go-name: GpuManufacturer + gpuModel: + description: gpu处理器型号 + type: string + x-go-name: GpuModel + hostname: + description: 主机名 + type: string + x-go-name: Hostname + idcId: + description: 机房uuid + type: string + x-go-name: IDcID + idcName: + description: 机房名称 + type: string + x-go-name: IdcName + iloIp: + description: 带外管理IP + type: string + x-go-name: IloIP + imageId: + description: 镜像uuid + type: string + x-go-name: ImageID + imageName: + description: 镜像名称 + type: string + x-go-name: ImageName + instanceId: + description: 实例uuid + type: string + x-go-name: InstanceID + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + interfaceMode: + description: '【网口模式】【网络设置】: bond单网口,dual双网口' + type: string + x-go-name: InterfaceMode + isNeedRaid: + description: 所属的机型是否需要配置raid,页面有用 + type: string + x-go-name: IsNeedRaid + locked: + description: 是否锁定解锁锁定:locked,解锁unlocked + type: string + x-go-name: Locked + lockedName: + description: 是否锁定解锁锁定:已解锁,已锁定 + type: string + x-go-name: LockedName + mask: + description: mask + type: string + x-go-name: Mask + memAmount: + description: 内存数量 + format: int64 + type: integer + x-go-name: MemAmount + memFrequency: + description: 内存主频(MHz) + format: int64 + type: integer + x-go-name: MemFrequency + memInfo: + type: string + x-go-name: MemInfo + memSize: + description: 单个内存大小(GB) + format: int64 + type: integer + x-go-name: MemSize + memType: + description: 内存接口(如DDR3,DDR4) + type: string + x-go-name: MemType + nicAmount: + description: 网卡数量 + format: int64 + type: integer + x-go-name: NicAmount + nicInfo: + type: string + x-go-name: NicInfo + nicRate: + description: 网卡传输速率(GE) + format: int64 + type: integer + x-go-name: NicRate + privateEth1Ipv4: + description: eth1内网IPV4 + type: string + x-go-name: PrivateEth1IPV4 + privateEth1Ipv6: + description: eth1内网IPV6 + type: string + x-go-name: PrivateEth1IPV6 + privateIpv4: + description: 内网IPV4 + type: string + x-go-name: PrivateIPV4 + privateIpv6: + description: 内网IPV6 + type: string + x-go-name: PrivateIPV6 + projectId: + description: 实例所属项目UUID + type: string + x-go-name: ProjectID + reason: + description: 实例错误状态时的错误原因 + type: string + x-go-name: Reason + sn: + description: 设备SN + type: string + x-go-name: Sn + status: + description: 运行状态 + type: string + x-go-name: Status + statusName: + description: 运行状态中文名字 + type: string + x-go-name: StatusName + systemInfo: + type: string + x-go-name: SystemInfo + systemVolumeRaidId: + description: 系统盘raidId + type: string + x-go-name: SystemVolumeRaidID + systemVolumeRaidName: + description: 系统盘raid名称 + type: string + x-go-name: SystemVolumeRaidName + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + userId: + description: 实例所属用户UUID + type: string + x-go-name: UserID + volumeRaid: + description: 实例的volume和raid信息 + items: + $ref: '#/definitions/InstanceVolumeRaid' + type: array + x-go-name: InstanceVolumeRaids + volumes: + items: + $ref: '#/definitions/InstanceVolumeRaid' + type: array + x-go-name: Volumes + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + InstanceForShare: + description: InstanceForShare instance for share + properties: + hasShared: + description: 新增,是否已经被共享过 + type: boolean + x-go-name: HasShared + instanceId: + description: 实例uuid + type: string + x-go-name: InstanceID + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + InstanceInfo: + description: 详情使用 + properties: + instance: + $ref: '#/definitions/Instance' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + InstanceVolumeRaid: + description: InstanceVolumeRaid instance volume raid + properties: + raid: + $ref: '#/definitions/Raid' + volume: + $ref: '#/definitions/Volume' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + InstancesResponse: + properties: + instances: + items: + $ref: '#/definitions/Instance' + type: array + x-go-name: Instances + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + KeyPair: + description: 给列表用的 + properties: + createdTime: + type: string + x-go-name: CreatedTime + fingerPrint: + type: string + x-go-name: FingerPrint + isCheckDelete: + type: string + x-go-name: IsCheckDelete + keypairId: + type: string + x-go-name: KeypairId + name: + type: string + x-go-name: Name + privateKey: + type: string + x-go-name: PrivateKey + publicKey: + type: string + x-go-name: PublicKey + updatedTime: + type: string + x-go-name: UpdatedTime + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + KeyPairInfo: + description: 给详情用的 + properties: + keypair: + properties: + createdTime: + type: string + x-go-name: CreatedTime + fingerPrint: + type: string + x-go-name: FingerPrint + isCheckDelete: + type: string + x-go-name: IsCheckDelete + keypairId: + type: string + x-go-name: KeypairId + name: + type: string + x-go-name: Name + privateKey: + type: string + x-go-name: PrivateKey + publicKey: + type: string + x-go-name: PublicKey + updatedTime: + type: string + x-go-name: UpdatedTime + type: object + x-go-name: Keypair + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + KeyPairsResponse: + properties: + keypairs: + items: + $ref: '#/definitions/KeyPair' + type: array + x-go-name: Keypairs + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + LockInstanceRequest: + properties: + idc_id: + type: string + x-go-name: IdcID + instanceId: + type: string + x-go-name: InstanceId + token: + type: string + x-go-name: Token + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + LoginRequest: + properties: + password: + type: string + x-go-name: Password + username: + type: string + x-go-name: Username + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + MessageList: + properties: + messages: + items: + $ref: '#/definitions/WebMessage' + type: array + x-go-name: Messages + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + MessageStatistic: + properties: + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + unreadCount: + format: int64 + type: integer + x-go-name: UnreadCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + MessageWithNextPrev: + properties: + message: + $ref: '#/definitions/WebMessage' + nextMessageId: + type: string + x-go-name: NextMessageId + prevMessageId: + type: string + x-go-name: PrevMessageId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + ModifyInstanceRequest: + properties: + description: + type: string + x-go-name: Description + idc_id: + type: string + x-go-name: IdcID + instanceId: + type: string + x-go-name: InstanceID + name: + type: string + x-go-name: Name + token: + type: string + x-go-name: Token + required: + - instanceId + - description + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + ModifyInstancesRequest: + properties: + instanceIds: + items: + type: string + type: array + x-go-name: InstanceIDs + instanceName: + type: string + x-go-name: InstanceName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + ModifyKeypairRequest: + properties: + clientToken: + format: int64 + type: integer + x-go-name: ClientToken + name: + type: string + x-go-name: Name + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + ModifyProjectDescriptionRequest: + description: ModifyProjectDescriptionRequest modify project description request + properties: + description: + description: 项目描述 + type: string + x-go-name: Description + required: + - description + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + ModifyProjectRequest: + description: ModifyProjectRequest modify project request + properties: + projectName: + description: 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + type: string + x-go-name: ProjectName + required: + - projectName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + ModifyUserInfoRequest: + description: 【用户管理】【编辑用户信息】 + properties: + defaultProjectId: + type: string + x-go-name: DefaultProjectID + description: + type: string + x-go-name: Description + email: + type: string + x-go-name: Email + language: + type: string + x-go-name: Language + phoneNumber: + type: string + x-go-name: PhoneNumber + phonePrefix: + type: string + x-go-name: PhonePrefix + timezone: + type: string + x-go-name: Timezone + userName: + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + MoveInstancesRequest: + properties: + instanceIDs: + type: string + x-go-name: InstanceIDs + moverName: + type: string + x-go-name: MoverName + moverProjectID: + type: string + x-go-name: MoverProjectID + ownerName: + type: string + x-go-name: OwnerName + ownerProjectID: + type: string + x-go-name: OwnerProjectID + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + MoveProjectRequest: + properties: + moverName: + type: string + x-go-name: MoverName + ownerName: + type: string + x-go-name: OwnerName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + OrderedJsonDict: + properties: + Keys: + items: + type: string + type: array + M: + additionalProperties: + type: string + type: object + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + Partition: + description: |- + Partition 镜像默认分区 + [{"format":"swap","point":"swap","size":10240},{"format":"xfs","point":"/","size":51200}] + properties: + format: + description: format,如[swap, xfs] + type: string + x-go-name: FsType + point: + description: point,如[swap, /, /var] + type: string + x-go-name: MountPoint + size: + description: 分区大小, MB为单位 + format: int64 + type: integer + x-go-name: Size + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + Project: + properties: + createdBy: + type: string + x-go-name: CreatedBy + createdTime: + type: string + x-go-name: CreatedTime + instanceCount: + format: int64 + type: integer + x-go-name: InstanceCount + projectId: + type: string + x-go-name: ProjectID + projectName: + type: string + x-go-name: ProjectName + updatedBy: + type: string + x-go-name: UpdatedBy + updatedTime: + type: string + x-go-name: UpdatedTime + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + ProjectId: + properties: + projectId: + type: string + x-go-name: ProjectId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + ProjectList: + description: ProjectList project list + properties: + pageNumber: + description: 页数 + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + description: 页大小 + format: int64 + type: integer + x-go-name: PageSize + projects: + description: 项目实体列表 + items: + $ref: '#/definitions/Project' + type: array + x-go-name: Projects + totalCount: + description: 总条数 + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + QueryDeviceStockResponse: + properties: + avaliableCount: + format: int64 + type: integer + x-go-name: AvaliableCount + success: + type: boolean + x-go-name: Success + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + Raid: + properties: + detail: + description: 容量大小描述 + type: string + x-go-name: Detail + raidCan: + type: string + x-go-name: RaidCan + raidId: + type: string + x-go-name: RaidID + raidName: + type: string + x-go-name: RaidName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + ReadMessagesRequest: + properties: + messageIds: + items: + type: string + type: array + x-go-name: MessageIds + required: + - messageIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + ReinstallInstanceRequest: + properties: + bootMode: + description: 引导模式 [UEFI Legacy/BIOS] + type: string + x-go-name: BootMode + dataPartition: + description: 数据盘分区 + items: + $ref: '#/definitions/Partition' + type: array + x-go-name: DataPartition + description: + description: 描述 + type: string + x-go-name: Description + hostname: + description: 主机名称 + type: string + x-go-name: HostName + idc_id: + type: string + x-go-name: IdcID + imageId: + description: 镜像ID + type: string + x-go-name: ImageID + instanceId: + type: string + x-go-name: InstanceId + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + password: + description: 密码 + type: string + x-go-name: Password + sshKeyId: + description: 秘钥ID + type: string + x-go-name: SSHKeyID + systemPartition: + description: 系统盘分区 + items: + $ref: '#/definitions/Partition' + type: array + x-go-name: SystemPartition + systemVolumeRaidId: + description: 系统盘RAID ID + type: string + x-go-name: SystemVolumeRaidID + token: + type: string + x-go-name: Token + required: + - bootMode + - imageId + - instanceName + - systemVolumeRaidId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + ResetInstancesPasswdRequest: + properties: + idc_id: + type: string + x-go-name: IdcID + instanceIds: + items: + type: string + type: array + x-go-name: InstanceIds + password: + type: string + x-go-name: Password + token: + type: string + x-go-name: Token + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + ResetPasswdRequest: + properties: + idc_id: + type: string + x-go-name: IdcID + instanceId: + type: string + x-go-name: InstanceId + password: + type: string + x-go-name: Password + token: + type: string + x-go-name: Token + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + RestartInstanceRequest: + properties: + clientToken: + format: int64 + type: integer + x-go-name: ClientToken + idc_id: + type: string + x-go-name: IdcID + instanceId: + type: string + x-go-name: InstanceId + token: + type: string + x-go-name: Token + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + SetCustomInfoRequest: + properties: + pageKey: + type: string + x-go-name: PageKey + pageValue: + additionalProperties: + additionalProperties: + type: boolean + type: object + type: object + x-go-name: PageValue + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + ShareProjectRequest: + properties: + instanceIDs: + description: 新增, 如果部分分享,instance_id逗号分隔; 如果全部分享,传all + type: string + x-go-name: InstanceIDs + ownerName: + type: string + x-go-name: OwnerName + sharerName: + type: string + x-go-name: SharerName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + StartInstanceRequest: + properties: + clientToken: + format: int64 + type: integer + x-go-name: ClientToken + idc_id: + type: string + x-go-name: IdcID + instanceId: + type: string + x-go-name: InstanceId + token: + type: string + x-go-name: Token + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + StartInstancesRequest: + properties: + instanceIds: + items: + type: string + type: array + x-go-name: InstanceIDs + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + StopInstanceRequest: + properties: + clientToken: + format: int64 + type: integer + x-go-name: ClientToken + idc_id: + type: string + x-go-name: IdcID + instanceId: + type: string + x-go-name: InstanceId + token: + type: string + x-go-name: Token + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + UnLockInstanceRequest: + properties: + idc_id: + type: string + x-go-name: IdcID + instanceId: + type: string + x-go-name: InstanceId + token: + type: string + x-go-name: Token + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + UpdatePasswordRequest: + properties: + oldPassword: + type: string + x-go-name: OldPassword + password: + type: string + x-go-name: Password + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/request + User: + description: User user + properties: + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + defaultProjectId: + description: 用户默认项目uuid + type: string + x-go-name: DefaultProjectID + defaultProjectName: + description: 用户默认项目名称 + type: string + x-go-name: DefaultProjectName + description: + description: 描述 + type: string + x-go-name: Description + email: + description: 邮箱 + type: string + x-go-name: Email + id: + description: 用户id + format: int64 + type: integer + x-go-name: ID + language: + description: 默认语言(en_US/zh_CN) + type: string + x-go-name: Language + phoneNumber: + description: 手机号 + type: string + x-go-name: PhoneNumber + phonePrefix: + description: 国家地区码,如86 + type: string + x-go-name: PhonePrefix + roleId: + description: 角色uuid + type: string + x-go-name: RoleID + roleName: + description: 角色名称 + type: string + x-go-name: RoleName + timezone: + description: 时区 + type: string + x-go-name: Timezone + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + userId: + description: 用户uuid + type: string + x-go-name: UserID + userName: + description: 用户名,唯一 + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + Volume: + description: Volume Volume 卷管理表 + properties: + createdBy: + description: |- + RaidCan string `gorm:"column:raid_can" json:"raidCan"` // RAID配置: (RAID,NO RAID) + Raid string `gorm:"column:raid" json:"raid"` // RAID模式:RAID1,RIAD10等 + type: string + x-go-name: CreatedBy + createdTime: + description: created time + format: int64 + type: integer + x-go-name: CreatedTime + deletedTime: + description: deleted time + format: int64 + type: integer + x-go-name: DeletedTime + deviceTypeId: + description: 设备类型uuid + type: string + x-go-name: DeviceTypeID + diskType: + description: 硬盘类型(SSD,HDD) + type: string + x-go-name: DiskType + interfaceType: + description: 接口类型(SATA,SAS,NVME,不限制) + type: string + x-go-name: InterfaceType + isDel: + description: is del + format: int8 + type: integer + x-go-name: IsDel + updatedBy: + description: updated by + type: string + x-go-name: UpdatedBy + updatedTime: + description: updated time + format: int64 + type: integer + x-go-name: UpdatedTime + volumeAmount: + description: 硬盘数量(最低块数) + format: int64 + type: integer + x-go-name: VolumeAmount + volumeId: + description: 卷uuid + type: string + x-go-name: VolumeID + volumeName: + description: 卷名称 + type: string + x-go-name: VolumeName + volumeSize: + description: 单盘大小(最小容量) + type: string + x-go-name: VolumeSize + volumeType: + description: 卷类型:系统卷,数据卷 + type: string + x-go-name: VolumeType + volumeUnit: + description: 硬盘单位(GB,TB) + type: string + x-go-name: VolumeUnit + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + VolumeRaID: + description: VolumeRaID volume ra ID + properties: + raidCan: + description: raid can + type: string + x-go-name: RaidCan + raidId: + description: raid uuid + type: string + x-go-name: RaidID + volumeId: + description: 卷 uuid + type: string + x-go-name: VolumeID + volumeType: + description: system|data + type: string + x-go-name: VolumeType + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models + VolumeRaid: + properties: + deviceTypeId: + description: 设备类型uuid + type: string + x-go-name: DeviceTypeID + diskType: + description: 硬盘类型(SSD,HDD) + type: string + x-go-name: DiskType + interfaceType: + description: 接口类型(SATA,SAS,NVME,不限制) + type: string + x-go-name: InterfaceType + raids: + description: 支持的raid模式 + items: + $ref: '#/definitions/Raid' + type: array + x-go-name: Raids + volumeAmount: + description: 硬盘数量(最低块数) + format: int64 + type: integer + x-go-name: VolumeAmount + volumeId: + description: 卷uuid + type: string + x-go-name: VolumeID + volumeName: + description: 卷名称 + type: string + x-go-name: VolumeName + volumeSize: + description: 单盘大小(最小容量) + format: double + type: number + x-go-name: VolumeSize + volumeType: + description: 卷类型:系统卷,数据卷 + type: string + x-go-name: VolumeType + volumeUnit: + description: 硬盘单位(GB,TB) + type: string + x-go-name: VolumeUnit + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-console-api/types/response + WebMessage: + description: WebMessage WebMessage message + properties: + alert_count: + description: 告警次数,始终为1,带外故障消息专属字段 + format: int64 + type: integer + x-go-name: AlertCount + alert_time: + description: 故障告警时间,带外故障消息专属字段 + format: int64 + type: integer + x-go-name: AlertTime + content: + description: 故障内容,带外故障消息专属字段 + type: string + x-go-name: Content + detail: + description: 详情, 带外监控日志的详情请用content + type: string + x-go-name: Detail + fault_type: + description: 故障类型, 带外故障消息专属字段 + type: string + x-go-name: FaultType + finish_time: + description: 消息时间戳 + format: int64 + type: integer + x-go-name: FinishTime + has_read: + description: 0未读, 1已读 + format: int8 + type: integer + x-go-name: HasRead + instance_id: + description: 实例id + type: string + x-go-name: InstanceID + instance_name: + description: 实例name + type: string + x-go-name: InstanceName + is_del: + description: 是否删除0未删除 1已删除 + format: int8 + type: integer + x-go-name: IsDel + license_end_time: + description: 结束时间, 许可证到期消息专属字段 + format: int64 + type: integer + x-go-name: LienseEndTime + license_name: + description: 版本名称, 许可证到期消息专属字段 + type: string + x-go-name: LicenseName + license_number: + description: 版本号, 许可证到期消息专属字段 + type: string + x-go-name: LicenseNumber + license_start_time: + description: 开始时间, 许可证到期消息专属字段 + format: int64 + type: integer + x-go-name: LienseStartTime + logid: + description: 系统原始日志id, 带外故障消息专属字段 + type: string + x-go-name: LogID + message_id: + description: message uuid + type: string + x-go-name: MessageID + message_sub_type: + description: 消息子类型 + type: string + x-go-name: MessageSubType + message_type: + description: 消息类型 + type: string + x-go-name: MessageType + resource_type: + description: 资源类型 实例/设备 + type: string + x-go-name: ResourceType + result: + description: 操作结果 fail/succ + type: string + x-go-name: Result + sn: + description: 设备sn + type: string + x-go-name: SN + user_id: + description: user_id + type: string + x-go-name: UserID + user_name: + description: user_name + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models +host: bmp-console-api.local +info: + contact: + email: minping@jd.com + description: |- + the purpose of this application is to provide an application + that is using plain go code to define an API + + This should demonstrate all the possible comment annotations + that are available to turn go code into a fully compliant swagger 2.0 spec + license: + name: MIT + url: http://opensource.org/licenses/MIT + termsOfService: there are no TOS at this moment, use at your own risk we take no responsibility + title: bmp-console-api + version: 0.0.1 +paths: + /apikey: + get: + description: GetApikeyList 获取apikey列表 + operationId: getApikeyList + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + responses: + "200": + $ref: '#/responses/getApikeyList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - keypair + put: + description: CreateAPIkey 创建apikey + operationId: createApikey + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/CreateApikeyRequest' + responses: + "200": + $ref: '#/responses/createApikey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - keypair + /apikey/{apikey_id}: + delete: + description: DeleteApikey 删除apikey + operationId: deleteApikey + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: apikey_id + required: true + type: string + x-go-name: ApikeyID + responses: + "200": + $ref: '#/responses/deleteApikey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - keypair + /auditLogs: + get: + description: DescribeAuditLogs 获取审计日志列表 + operationId: describeAuditLogs + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: instance_id + in: query + name: instanceId + type: string + x-go-name: InstanceID + - description: 操作名称 + in: query + name: operation + type: string + x-go-name: Operation + - description: 操作人 + in: query + name: userName + type: string + x-go-name: UserName + - description: result + in: query + name: result + type: string + x-go-name: Result + - description: 操作时间下限 + format: int64 + in: query + name: startTime + type: integer + x-go-name: StartTime + - description: 操作时间上限 + format: int64 + in: query + name: endTime + type: integer + x-go-name: EndTime + - description: 是否显示所有 + in: query + name: isAll + type: string + x-go-name: IsAll + - in: query + name: exportType + type: string + x-go-name: ExportType + responses: + "200": + $ref: '#/responses/describeAuditLogs' + default: + $ref: '#/responses/ErrorResponse' + tags: + - auditLog + /custom/getCustomInfo: + get: + description: GetCustomInfo 获取自定义表头 + operationId: getCustomInfo + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: query + name: pageKey + type: string + x-go-name: PageKey + - in: query + name: reload + type: string + x-go-name: Reload + responses: + "200": + $ref: '#/responses/getCustomInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - custom + /custom/setCustomInfo: + post: + description: SetCustomInfo 设置自定义表头 + operationId: setCustomInfo + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/SetCustomInfoRequest' + responses: + "200": + $ref: '#/responses/setCustomInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - custom + /device/isDeviceStockEnough: + get: + description: IsDeviceStockEnough 查询设备库存是否足够 + operationId: isDeviceStockEnough + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: query + name: idc_id + type: string + x-go-name: IdcID + - in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeId + - format: int64 + in: query + name: count + type: integer + x-go-name: Count + responses: + "200": + $ref: '#/responses/isDeviceStockEnough' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /deviceType/getAvailableDeviceTypes: + get: + description: GetAvailableDeviceTypes 获取该机房内可用机型列表 + operationId: getAvailableDeviceTypes + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: query + name: idc_id + type: string + x-go-name: IdcID + responses: + "200": + $ref: '#/responses/getAvailableDeviceTypes' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /idc: + get: + description: GetIdcList 获取idc列表 + operationId: getIdcList + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: query + name: exportType + type: string + x-go-name: ExportType + responses: + "200": + $ref: '#/responses/getIdcList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - idc + /image/queryImagesByDeviceType: + get: + description: QueryImagesByDeviceType 根据机型获取绑定的镜像列表 + operationId: queryImagesByDeviceType + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - description: Pin string `json:"pin"` + in: query + name: idc_id + type: string + x-go-name: IdcID + - in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + responses: + "200": + $ref: '#/responses/queryImagesByDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + /instance: + get: + description: GetInstanceList 实例列表 + operationId: getInstanceList + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - in: query + name: projectId + type: string + x-go-name: ProjectID + - in: query + name: idcId + type: string + x-go-name: IdcID + - in: query + name: status + type: string + x-go-name: Status + - in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeId + - in: query + name: name + type: string + x-go-name: Name + - in: query + name: deviceType + type: string + x-go-name: DeviceType + - in: query + name: instanceId + type: string + x-go-name: InstanceId + - in: query + name: privateIp + type: string + x-go-name: PrivateIp + - in: query + name: privateIpv6 + type: string + x-go-name: PrivateIpv6 + - in: query + name: keypairId + type: string + x-go-name: KeypairId + - in: query + name: sn + type: string + x-go-name: Sn + - in: query + name: iloIp + type: string + x-go-name: IloIp + - in: query + name: deviceTypeList + type: string + x-go-name: DeviceTypeList + - in: query + name: exportType + type: string + x-go-name: ExportType + - description: '"1" 表示全部' + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/getInstanceList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + put: + description: CreateInstance 创建实例 + operationId: createInstance + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/CreateInstanceRequest' + responses: + "200": + $ref: '#/responses/createInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/{instance_id}: + delete: + description: DeleteInstance 删除实例 + operationId: deleteInstance + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/deleteInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + get: + description: GetInstanceInfo 查看实例详情 + operationId: getInstanceInfo + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/getInstanceInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/batchResetPasswd: + post: + description: resetInstancesPasswd 批量重置密码 + operationId: resetInstancesPasswd + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/ResetInstancesPasswdRequest' + responses: + "200": + $ref: '#/responses/resetInstancesPasswd' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/deleteInstances: + delete: + description: DeleteInstances 批量删除实例 + operationId: deleteInstances + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/StartInstancesRequest' + responses: + "200": + $ref: '#/responses/deleteInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/forshare/list: + get: + description: GetInstanceListForShare 实例列表 + operationId: getInstanceListForShare + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: query + name: projectId + type: string + x-go-name: ProjectID + - in: query + name: ownerName + type: string + x-go-name: OwnerName + - in: query + name: sharerName + type: string + x-go-name: SharerName + - description: 支持搜索 + in: query + name: instanceName + type: string + x-go-name: InstanceName + - in: query + name: instanceId + type: string + x-go-name: InstanceId + responses: + "200": + $ref: '#/responses/getInstanceListForShare' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/lockInstance: + post: + description: LockInstance 锁定实例 + operationId: lockInstance + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/LockInstanceRequest' + responses: + "200": + $ref: '#/responses/lockInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/modifyInstance: + post: + description: ModifyInstance 修改实例信息 + operationId: modifyInstance + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyInstanceRequest' + responses: + "200": + $ref: '#/responses/modifyInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/modifyInstances: + post: + description: ModifyInstances 批量编辑实例名称 + operationId: modifyInstances + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyInstancesRequest' + responses: + "200": + $ref: '#/responses/modifyInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/reinstallInstance: + post: + description: ReinstallInstance 重装实例 + operationId: reinstallInstance + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/ReinstallInstanceRequest' + responses: + "200": + $ref: '#/responses/reinstallInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/resetPasswd: + post: + description: resetPasswd 重置密码 + operationId: resetPasswd + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/ResetPasswdRequest' + responses: + "200": + $ref: '#/responses/resetPasswd' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/restartInstance: + post: + description: RestartInstance 重启实例 + operationId: restartInstance + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/RestartInstanceRequest' + responses: + "200": + $ref: '#/responses/restartInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/restartInstances: + post: + description: RestartInstances 批量重启 + operationId: restartInstances + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/StartInstancesRequest' + responses: + "200": + $ref: '#/responses/restartInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/startInstance: + post: + description: StartInstance 开机 + operationId: startInstance + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/StartInstanceRequest' + responses: + "200": + $ref: '#/responses/startInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/startInstances: + post: + description: StartInstances 批量开机 + operationId: startInstances + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/StartInstancesRequest' + responses: + "200": + $ref: '#/responses/startInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/stopInstance: + post: + description: StopInstance 关机 + operationId: stopInstance + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/StopInstanceRequest' + responses: + "200": + $ref: '#/responses/stopInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/stopInstances: + post: + description: StopInstances 批量关机 + operationId: stopInstances + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/StartInstancesRequest' + responses: + "200": + $ref: '#/responses/stopInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instance/unlockInstance: + post: + description: UnlockInstance 解锁实例 + operationId: unlockInstance + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/UnLockInstanceRequest' + responses: + "200": + $ref: '#/responses/unlockInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /keypair: + get: + description: GetKeypairList 获取keypair列表 + operationId: getKeypairList + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - in: query + name: name + type: string + x-go-name: Name + - in: query + items: + type: string + name: keypairId + type: array + x-go-name: KeypairIds + responses: + "200": + $ref: '#/responses/getKeypairList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - keypair + put: + description: CreateKeypair 创建keypair + operationId: createKeypair + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/CreateKeypairRequest' + responses: + "200": + $ref: '#/responses/createKeypair' + default: + $ref: '#/responses/ErrorResponse' + tags: + - keypair + /keypair/{keypair_id}: + delete: + description: DeleteKeypair 删除keypair + operationId: deleteKeypair + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: keypair_id + required: true + type: string + x-go-name: KeypairID + responses: + "200": + $ref: '#/responses/deleteKeypair' + default: + $ref: '#/responses/ErrorResponse' + tags: + - keypair + get: + description: GetKeypairInfo 获取keypair详情 + operationId: getKeypairInfo + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: keypair_id + required: true + type: string + x-go-name: KeypairID + responses: + "200": + $ref: '#/responses/getKeypairInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - keypair + put: + description: ModifyKeypair 修改keypair信息 + operationId: modifyKeypair + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: keypair_id + required: true + type: string + x-go-name: KeypairID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyKeypairRequest' + responses: + "200": + $ref: '#/responses/modifyKeypair' + default: + $ref: '#/responses/ErrorResponse' + tags: + - keypair + /keypair/checkKeypairName: + get: + description: CheckKeypairName 查询keypair名称是否已存在 + operationId: checkKeypairName + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - in: query + name: name + type: string + x-go-name: Name + - in: query + items: + type: string + name: keypairId + type: array + x-go-name: KeypairIds + responses: + "200": + $ref: '#/responses/checkKeypairName' + default: + $ref: '#/responses/ErrorResponse' + tags: + - keypair + /login: + post: + description: Login 登录 + operationId: login + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/LoginRequest' + responses: + "200": + $ref: '#/responses/login' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /logout: + post: + description: Logout 登出 + operationId: logout + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + responses: + "200": + $ref: '#/responses/logout' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /messages: + get: + description: GetMessageList 获取message列表(分页) + operationId: getMessageList + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 0:导出全部实力;1:导出选中实例;2:导出搜索结果 + in: query + name: exportType + type: string + x-go-name: ExportType + - description: 是否显示全部,取值为1时表示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + - description: 0:未读;1:已读;""不传表示全部 + in: query + name: hasRead + type: string + x-go-name: HasRead + - description: 消息类型 + in: query + name: messageType + type: string + x-go-name: MessageType + - description: 消息子类型 + in: query + name: messageSubType + type: string + x-go-name: MessageSubType + - description: 内容,支持模糊搜索 + in: query + name: detail + type: string + x-go-name: Detail + responses: + "200": + $ref: '#/responses/getMessageList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/delete: + delete: + description: DeleteMessage 删除消息(可多条) + operationId: deleteMessage + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/DeleteMessagesRequest' + responses: + "200": + $ref: '#/responses/deleteMessage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/doRead: + put: + description: ReadMessage 将消息设置为已读(可多条) + operationId: readMessage + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/ReadMessagesRequest' + responses: + "200": + $ref: '#/responses/readMessage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/getMessageById: + get: + description: GetMessageById 获取消息详情,包括上一条/下一条的messageid + operationId: getMessageById + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: query + name: messageId + required: true + type: string + x-go-name: MessageId + responses: + "200": + $ref: '#/responses/getMessageById' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/getMessageTypes: + get: + description: GetMessageTypes 获取消息类型/子类型 + operationId: getMessageTypes + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + responses: + "200": + $ref: '#/responses/getMessageTypes' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/hasUnreadMessage: + get: + description: HasUnreadMessage 获取有没有未读消息 + operationId: hasUnreadMessage + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + responses: + "200": + $ref: '#/responses/hasUnreadMessage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/statistic: + get: + description: GetMessageStatistic 获取message总数和未读数 + operationId: getMessageStatistic + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + responses: + "200": + $ref: '#/responses/getMessageStatistic' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /monitorAlert/addAlert: + post: + description: AddAlert 添加告警 + operationId: addAlert + responses: + "200": + $ref: '#/responses/addAlert' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorAlert + /monitorAlert/deleteAlert: + delete: + description: DeleteAlert 删除告警 + operationId: deleteAlert + responses: + "200": + $ref: '#/responses/deleteAlert' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorAlert + /monitorAlert/describeAlert: + get: + description: DescribeAlert 告警详情 + operationId: describeAlert + responses: + "200": + $ref: '#/responses/describeAlert' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorAlert + /monitorAlert/describeAlerts: + get: + description: DescribeAlerts 告警列表 + operationId: describeAlerts + responses: + "200": + $ref: '#/responses/describeAlerts' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorAlert + /monitorData: + get: + description: GetMonitorData 获取图表监控数据 + operationId: getMonitorData + responses: + "200": + $ref: '#/responses/getMonitorData' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorData + /monitorProxy/desrcibeAgentStatus: + get: + description: DesrcibeAgentStatus 获取agent状态 + operationId: desrcibeAgentStatus + responses: + "200": + $ref: '#/responses/desrcibeAgentStatus' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorProxy + /monitorProxy/desrcibeTags: + get: + description: DesrcibeAgentStatus 获取tag列表 + operationId: desrcibeTags + responses: + "200": + $ref: '#/responses/desrcibeTags' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorProxy + /monitorRule/addRule: + post: + description: AddRule 添加规则 + operationId: addRule + responses: + "200": + $ref: '#/responses/addRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/deleteRule: + delete: + description: DeleteRule 删除规则 + operationId: deleteRule + responses: + "200": + $ref: '#/responses/deleteRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/describeRule: + get: + description: DescribeRule 规则详情 + operationId: describeRule + responses: + "200": + $ref: '#/responses/describeRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/describeRules: + get: + description: DescribeRules 规则列表 + operationId: describeRules + responses: + "200": + $ref: '#/responses/describeRules' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/disableRule: + put: + description: DisableRule 禁用规则 + operationId: disableRule + responses: + "200": + $ref: '#/responses/disableRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/editRule: + put: + description: EditRule 编辑规则 + operationId: editRule + responses: + "200": + $ref: '#/responses/editRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/enableRule: + put: + description: EnableRule 启用规则 + operationId: enableRule + responses: + "200": + $ref: '#/responses/enableRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /partition/queryDefaultSystemPartitions: + get: + description: QueryDefaultSystemPartitions 根据机型和镜像查系统盘默认分区列表 + operationId: queryDefaultSystemPartitions + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: query + name: imageId + type: string + x-go-name: ImageID + - in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + responses: + "200": + $ref: '#/responses/queryDefaultSystemPartitions' + default: + $ref: '#/responses/ErrorResponse' + tags: + - keypair + /project: + get: + description: GetProjectList 获取项目列表 + operationId: getProjectList + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - in: query + name: projectName + type: string + x-go-name: ProjectName + - in: query + name: exportType + type: string + x-go-name: ExportType + - in: query + name: isAll + type: string + x-go-name: IsAll + - in: query + name: orderByCreatetime + type: string + x-go-name: OrderByCreatetime + - in: query + name: owned + type: string + x-go-name: Owned + - description: 新增,可选,根据用户名获取项目列表 + in: query + name: ownerName + type: string + x-go-name: OwnerName + - description: 新增,可选,根据被转移用户的用户名获取它拥有的项目列表 + in: query + name: sharerName + type: string + x-go-name: SharerName + responses: + "200": + $ref: '#/responses/getProjectList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + put: + description: CreateProject 创建项目 + operationId: createProject + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/CreateProjectRequest' + responses: + "200": + $ref: '#/responses/createProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /project/{project_id}: + delete: + description: DeleteProject 删除项目 + operationId: deleteProject + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + responses: + "200": + $ref: '#/responses/deleteProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + get: + description: GetProject 获取项目详情 + operationId: getProject + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + responses: + "200": + $ref: '#/responses/getProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + post: + description: ModifyProject 修改项目名称 + operationId: modifyProject + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyProjectRequest' + responses: + "200": + $ref: '#/responses/modifyProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /project/{project_id}/cancelShare: + put: + description: CancelShareProject 取消共享项目 + operationId: cancelshareProject + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + - in: body + name: Body + schema: + $ref: '#/definitions/ShareProjectRequest' + responses: + "200": + $ref: '#/responses/cancelshareProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /project/{project_id}/description: + post: + description: ModifyProject 修改项目描述 + operationId: modifyProjectDescription + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyProjectDescriptionRequest' + responses: + "200": + $ref: '#/responses/modifyProjectDescription' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /project/{project_id}/move: + put: + description: MoveProject 转移项目 + operationId: moveProject + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + - in: body + name: Body + schema: + $ref: '#/definitions/MoveProjectRequest' + responses: + "200": + $ref: '#/responses/moveProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /project/{project_id}/share: + put: + description: ShareProject 共享项目 + operationId: shareProject + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + - in: body + name: Body + schema: + $ref: '#/definitions/ShareProjectRequest' + responses: + "200": + $ref: '#/responses/shareProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /project/move/instances: + put: + description: MoveInstances 转移项目下的某些实例 + operationId: moveInstances + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/MoveInstancesRequest' + responses: + "200": + $ref: '#/responses/moveInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /raid/queryRaidsByDeviceTypeIDAndVolumeType: + get: + description: QueryVolumeRaids 根据机型查询系统卷/数据卷和可用raid列表 + operationId: queryVolumeRaids + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - in: query + name: volumeType + type: string + x-go-name: VolumeType + responses: + "200": + $ref: '#/responses/queryVolumeRaids' + default: + $ref: '#/responses/ErrorResponse' + tags: + - raid + /user: + get: + description: GetUserInfo 获取用户详情 + operationId: getUserInfo + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + responses: + "200": + $ref: '#/responses/getUserInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + put: + description: UpdateUserInfo 修改个人信息(除密码) + operationId: updateUserInfo + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyUserInfoRequest' + responses: + "200": + $ref: '#/responses/updateUserInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /user/checkUserConsoleAccess: + get: + description: CheckUserConsoleAccess 校验被转移的用户有没有控制台权限 + operationId: checkUserConsoleAccess + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: query + name: checkedUserId + type: string + x-go-name: CheckedUserId + responses: + "200": + $ref: '#/responses/checkUserConsoleAccess' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /user/checkUserConsoleAccessByName: + get: + description: CheckUserConsoleAccess 按用户名校验被转移的用户有没有控制台权限 + operationId: checkUserConsoleAccessByName + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: query + name: checkedUserName + type: string + x-go-name: CheckedUserName + - in: query + name: projectId + type: string + x-go-name: ProjectID + - description: '[move/share]' + in: query + name: operation + type: string + x-go-name: Operation + responses: + "200": + $ref: '#/responses/checkUserConsoleAccessByName' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /user/getConsoleAccessUserList: + get: + description: GetConsoleAccessUserList 获取有控制台权限的用户列表 + operationId: getConsoleAccessUserList + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + responses: + "200": + $ref: '#/responses/getConsoleAccessUserList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /user/password: + put: + description: UpdatePassword 修改密码 + operationId: updatePassword + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/UpdatePasswordRequest' + responses: + "200": + $ref: '#/responses/updatePassword' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /user/timezones: + get: + description: GetTimezoneList 获取时区列表 + operationId: getTimezoneList + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + responses: + "200": + $ref: '#/responses/getTimezoneList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user +produces: + - application/json +responses: + ErrorResponse: + description: unit err response for non 200 + schema: + properties: + error: + $ref: '#/definitions/ErrorResponse' + requestId: + type: string + x-go-name: RequestId + type: object + cancelshareProject: + description: CancelShareProjectResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + checkKeypairName: + description: CheckKeypairNameResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + checkUserConsoleAccess: + description: CheckUserConsoleAccessResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + checkUserConsoleAccessByName: + description: CheckUserConsoleAccessByNameResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + createApikey: + description: CreateApikeyResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/ApikeyId' + type: object + createInstance: + description: CreateInstanceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CreateInstanceResponse' + type: object + createKeypair: + description: CreateKeypairResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/KeyPair' + type: object + createProject: + description: CreateProjectResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/ProjectId' + type: object + deleteApikey: + description: DeleteApikeyResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteInstance: + description: DeleteInstanceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteInstances: + description: DeleteInstancesResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteKeypair: + description: DeleteKeypairResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteMessage: + description: A DeleteMessageResult is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteProject: + description: DeleteProjectResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + describeAuditLogs: + description: "" + schema: + properties: + result: + $ref: '#/definitions/AuditLogsList' + type: object + getApikeyList: + description: GetApikeyListResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/ApikeyList' + type: object + getAvailableDeviceTypes: + description: GetAvailableDeviceTypesResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + additionalProperties: + items: + $ref: '#/definitions/DeviceType' + type: array + type: object + x-go-name: Result + type: object + getConsoleAccessUserList: + description: GetConsoleAccessUserListResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + items: + $ref: '#/definitions/User' + type: array + x-go-name: Result + type: object + getCustomInfo: + description: GetCustomInfoResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + getIdcList: + description: GetIdcListResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/IdcList' + type: object + getInstanceInfo: + description: GetInstanceInfoResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/InstanceInfo' + type: object + getInstanceList: + description: GetInstanceListResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/InstancesResponse' + type: object + getInstanceListForShare: + description: GetInstanceListForShareResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + items: + $ref: '#/definitions/InstanceForShare' + type: array + x-go-name: Result + type: object + getKeypairInfo: + description: GetKeypairInfoResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/KeyPairInfo' + type: object + getKeypairList: + description: GetKeypairListResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/KeyPairsResponse' + type: object + getMessageById: + description: "" + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/MessageWithNextPrev' + type: object + getMessageList: + description: "" + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/MessageList' + type: object + getMessageStatistic: + description: "" + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/MessageStatistic' + type: object + getMessageTypes: + description: "" + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + additionalProperties: + items: + type: string + type: array + type: object + x-go-name: Result + type: object + getProject: + description: GetProjectResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/Project' + type: object + getProjectList: + description: GetProjectListResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/ProjectList' + type: object + getTimezoneList: + description: GetTimezoneListResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/GetTimezoneListResponse' + type: object + getUserInfo: + description: GetUserInfoResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/User' + type: object + hasUnreadMessage: + description: "" + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/HasUnreadMessage' + type: object + isDeviceStockEnough: + description: IsDeviceStockEnoughResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/QueryDeviceStockResponse' + type: object + lockInstance: + description: LockInstanceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + login: + description: LoginResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + logout: + description: LogoutResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyInstance: + description: ModifyInstanceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyInstances: + description: ModifyInstancesResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyKeypair: + description: ModifyKeypairResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyProject: + description: ModifyProjectResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyProjectDescription: + description: ModifyProjectDescriptionResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + moveInstances: + description: MoveInstancesResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + moveProject: + description: MoveProjectResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + queryDefaultSystemPartitions: + description: QueryDefaultSystemPartitionsResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + items: + $ref: '#/definitions/Partition' + type: array + x-go-name: Result + type: object + queryImagesByDeviceType: + description: QueryImagesByDeviceTypeResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + additionalProperties: + items: + $ref: '#/definitions/Image' + type: array + type: object + x-go-name: Result + type: object + queryVolumeRaids: + description: QueryRaidsByDeviceTypeIDAndVolumeTypeResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + items: + $ref: '#/definitions/VolumeRaid' + type: array + x-go-name: Result + type: object + readMessage: + description: A ReadMessageResult is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + reinstallInstance: + description: ReinstallInstanceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + resetInstancesPasswd: + description: ResetInstancesPasswdResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + resetPasswd: + description: ResetPasswdResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + restartInstance: + description: RestartInstanceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + restartInstances: + description: RestartInstancesResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + setCustomInfo: + description: SetCustomInfoResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + shareProject: + description: ShareProjectResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + startInstance: + description: StartInstanceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + startInstances: + description: StartInstancesResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + stopInstance: + description: StopInstanceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + stopInstances: + description: StopInstancesResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + unlockInstance: + description: UnlockInstanceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + updatePassword: + description: UpdatePasswordResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + updateUserInfo: + description: UpdateUserInfoResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object +schemes: + - http +swagger: "2.0" diff --git a/bmp-console-api/swagger_gen.sh b/bmp-console-api/swagger_gen.sh new file mode 100644 index 0000000..cbe08ed --- /dev/null +++ b/bmp-console-api/swagger_gen.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +# install goswagger: https://goswagger.io/install.html#Installing%20from%20source + +swagger version +\rm ./swagger.yml | swagger generate spec -o ./swagger.yml +# swagger validate ./swagger.yml goswagger有缺陷,且报错无法提供有效信息,建议使用https://editor.swagger.io/来校验 +# validate 和 generate命令在0.25.0版本有panic,0.30.3版本已修复 +swagger validate swagger.yml diff --git a/bmp-console-api/swagger_gen_json.sh b/bmp-console-api/swagger_gen_json.sh new file mode 100644 index 0000000..e9f33b0 --- /dev/null +++ b/bmp-console-api/swagger_gen_json.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +# install goswagger: https://goswagger.io/install.html#Installing%20from%20source + +swagger version +\rm ./swagger.json | swagger generate spec -o ./swagger.json +# swagger validate ./swagger.yml goswagger有缺陷,且报错无法提供有效信息,建议使用https://editor.swagger.io/来校验 +# validate 和 generate命令在0.25.0版本有panic,0.30.3版本已修复 +swagger validate swagger.json diff --git a/bmp-console-api/swaggermodels/CommonHeader.go b/bmp-console-api/swaggermodels/CommonHeader.go new file mode 100644 index 0000000..b24d6f0 --- /dev/null +++ b/bmp-console-api/swaggermodels/CommonHeader.go @@ -0,0 +1,17 @@ +package swaggermodels + +type ReadHeader struct { + // required: true + // in: header + TraceID string `json:"traceId"` //同APIKey + // in: header + Cookie string `json:"cookie"` +} + +type WriteHeader struct { + // required: true + // in: header + TraceID string `json:"traceId"` + // in: header + Cookie string `json:"cookie"` +} diff --git a/bmp-console-api/swaggermodels/Custom.go b/bmp-console-api/swaggermodels/Custom.go new file mode 100644 index 0000000..a82f5e5 --- /dev/null +++ b/bmp-console-api/swaggermodels/Custom.go @@ -0,0 +1,41 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/response" +) + +// swagger:parameters setCustomInfo +type SetCustomInfoRequest struct { + WriteHeader + // in:body + Body requestTypes.SetCustomInfoRequest +} + +// SetCustomInfoResponse is an response struct +// swagger:response setCustomInfo +type SetCustomInfoResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters getCustomInfo +type GetCustomInfoRequest struct { + ReadHeader + // in: query + requestTypes.QueryCustomInfoRequest +} + +// GetCustomInfoResponse is an response struct +// swagger:response getCustomInfo +type GetCustomInfoResponse struct { + + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/DeleteMessageRequest.go b/bmp-console-api/swaggermodels/DeleteMessageRequest.go new file mode 100644 index 0000000..77046c2 --- /dev/null +++ b/bmp-console-api/swaggermodels/DeleteMessageRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" +) + +// swagger:parameters deleteMessage +type DeleteMessageRequest struct { + WriteHeader + + // in: body + Body requestTypes.DeleteMessagesRequest +} diff --git a/bmp-console-api/swaggermodels/DeleteMessageResult.go b/bmp-console-api/swaggermodels/DeleteMessageResult.go new file mode 100644 index 0000000..ad54cd1 --- /dev/null +++ b/bmp-console-api/swaggermodels/DeleteMessageResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" +) + +// A DeleteMessageResult is an response struct +// swagger:response deleteMessage +type DeleteMessageResult struct { + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/DescribeAuditLogsRequest.go b/bmp-console-api/swaggermodels/DescribeAuditLogsRequest.go new file mode 100644 index 0000000..186cb4e --- /dev/null +++ b/bmp-console-api/swaggermodels/DescribeAuditLogsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" +) + +// swagger:parameters describeAuditLogs +type DescribeAuditLogsRequest struct { + ReadHeader + + // in: query + requestTypes.DescribeAuditLogsRequest +} diff --git a/bmp-console-api/swaggermodels/DescribeAuditLogsResult.go b/bmp-console-api/swaggermodels/DescribeAuditLogsResult.go new file mode 100644 index 0000000..e98a32e --- /dev/null +++ b/bmp-console-api/swaggermodels/DescribeAuditLogsResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" +) + +// swagger:response describeAuditLogs +type DescribeAuditLogsResult struct { + + // in: body + Body struct { + Result response.AuditLogsList `json:"result"` + } +} diff --git a/bmp-console-api/swaggermodels/ErrorResponse.go b/bmp-console-api/swaggermodels/ErrorResponse.go new file mode 100644 index 0000000..eeae1ad --- /dev/null +++ b/bmp-console-api/swaggermodels/ErrorResponse.go @@ -0,0 +1,13 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-console-api/controllers" + +// unit err response for non 200 +// swagger:response ErrorResponse +type ErrorResponse struct { + //In: body + Body struct { + Err controllers.ErrorResponse `json:"error"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/GetMessageByIdRequest.go b/bmp-console-api/swaggermodels/GetMessageByIdRequest.go new file mode 100644 index 0000000..18ab154 --- /dev/null +++ b/bmp-console-api/swaggermodels/GetMessageByIdRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" +) + +// swagger:parameters getMessageById +type GetMessageByIdRequest struct { + ReadHeader + + // in: query + requestTypes.GetMessageByIdRequest +} diff --git a/bmp-console-api/swaggermodels/GetMessageByIdResult.go b/bmp-console-api/swaggermodels/GetMessageByIdResult.go new file mode 100644 index 0000000..3de35f9 --- /dev/null +++ b/bmp-console-api/swaggermodels/GetMessageByIdResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + +// swagger:response getMessageById +type GetMessageByIdResult struct { + // in: body + Body struct { + Result response.MessageWithNextPrev `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/GetMessageListRequest.go b/bmp-console-api/swaggermodels/GetMessageListRequest.go new file mode 100644 index 0000000..dea0ab0 --- /dev/null +++ b/bmp-console-api/swaggermodels/GetMessageListRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" +) + +// swagger:parameters getMessageList +type GetMessageListRequest struct { + ReadHeader + + // in: query + requestTypes.QueryMessagesRequest +} diff --git a/bmp-console-api/swaggermodels/GetMessageListResult.go b/bmp-console-api/swaggermodels/GetMessageListResult.go new file mode 100644 index 0000000..7ffbf35 --- /dev/null +++ b/bmp-console-api/swaggermodels/GetMessageListResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + +// swagger:response getMessageList +type GetMessageListResult struct { + // in: body + Body struct { + Result response.MessageList `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/GetMessageStatisticRequest.go b/bmp-console-api/swaggermodels/GetMessageStatisticRequest.go new file mode 100644 index 0000000..9ae4eca --- /dev/null +++ b/bmp-console-api/swaggermodels/GetMessageStatisticRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters getMessageStatistic +type GetMessageStatisticRequest struct { + ReadHeader +} diff --git a/bmp-console-api/swaggermodels/GetMessageStatisticResult.go b/bmp-console-api/swaggermodels/GetMessageStatisticResult.go new file mode 100644 index 0000000..7ad863e --- /dev/null +++ b/bmp-console-api/swaggermodels/GetMessageStatisticResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + +// swagger:response getMessageStatistic +type GetMessageStatisticResult struct { + // in: body + Body struct { + Result response.MessageStatistic `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/GetMessageTypesRequest.go b/bmp-console-api/swaggermodels/GetMessageTypesRequest.go new file mode 100644 index 0000000..2c22a6c --- /dev/null +++ b/bmp-console-api/swaggermodels/GetMessageTypesRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters getMessageTypes +type GetMessageTypesRequest struct { + ReadHeader +} diff --git a/bmp-console-api/swaggermodels/GetMessageTypesResult.go b/bmp-console-api/swaggermodels/GetMessageTypesResult.go new file mode 100644 index 0000000..ea735c9 --- /dev/null +++ b/bmp-console-api/swaggermodels/GetMessageTypesResult.go @@ -0,0 +1,10 @@ +package swaggermodels + +// swagger:response getMessageTypes +type GetMessageTypesResult struct { + // in: body + Body struct { + Result map[string][]string `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/HasUnreadMessageRequest.go b/bmp-console-api/swaggermodels/HasUnreadMessageRequest.go new file mode 100644 index 0000000..2114316 --- /dev/null +++ b/bmp-console-api/swaggermodels/HasUnreadMessageRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters hasUnreadMessage +type HasUnreadMessageRequest struct { + ReadHeader +} diff --git a/bmp-console-api/swaggermodels/HasUnreadMessageResult.go b/bmp-console-api/swaggermodels/HasUnreadMessageResult.go new file mode 100644 index 0000000..4099185 --- /dev/null +++ b/bmp-console-api/swaggermodels/HasUnreadMessageResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" +) + +// swagger:response hasUnreadMessage +type HasUnreadMessageResult struct { + // in: body + Body struct { + Result response.HasUnreadMessage `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/ReadMessageRequest.go b/bmp-console-api/swaggermodels/ReadMessageRequest.go new file mode 100644 index 0000000..a78a1c0 --- /dev/null +++ b/bmp-console-api/swaggermodels/ReadMessageRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" +) + +// swagger:parameters readMessage +type ReadMessageRequest struct { + WriteHeader + + // in: body + Body requestTypes.ReadMessagesRequest +} diff --git a/bmp-console-api/swaggermodels/ReadMessageResult.go b/bmp-console-api/swaggermodels/ReadMessageResult.go new file mode 100644 index 0000000..c3a0a18 --- /dev/null +++ b/bmp-console-api/swaggermodels/ReadMessageResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" +) + +// A ReadMessageResult is an response struct +// swagger:response readMessage +type ReadMessageResult struct { + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/apikey.go b/bmp-console-api/swaggermodels/apikey.go new file mode 100644 index 0000000..c0352d0 --- /dev/null +++ b/bmp-console-api/swaggermodels/apikey.go @@ -0,0 +1,61 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// swagger:parameters createApikey +type CreateApikeyRequest struct { + WriteHeader + + // in:body + Body sdkModels.CreateApikeyRequest +} + +// CreateApikeyResponse is an response struct +// swagger:response createApikey +type CreateApikeyResponse struct { + // in: body + Body struct { + Result responseTypes.ApikeyId `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters getApikeyList +type GetApikeyListRequest struct { + ReadHeader + + // in: query + requestTypes.GetApikeyListRequest +} + +// GetApikeyListResponse is an response struct +// swagger:response getApikeyList +type GetApikeyListResponse struct { + // in: body + Body struct { + Result sdkModels.ApikeyList `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters deleteApikey +type DeleteApikeyRequest struct { + ReadHeader + + // in: path + ApikeyID string `json:"apikey_id"` +} + +// DeleteApikeyResponse is an response struct +// swagger:response deleteApikey +type DeleteApikeyResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/device.go b/bmp-console-api/swaggermodels/device.go new file mode 100644 index 0000000..3e1f137 --- /dev/null +++ b/bmp-console-api/swaggermodels/device.go @@ -0,0 +1,24 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/response" +) + +// swagger:parameters isDeviceStockEnough +type IsDeviceStockEnoughRequest struct { + ReadHeader + + // in: query + requestTypes.QueryDeviceStockRequest +} + +// IsDeviceStockEnoughResponse is an response struct +// swagger:response isDeviceStockEnough +type IsDeviceStockEnoughResponse struct { + // in: body + Body struct { + Result responseTypes.QueryDeviceStockResponse `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/deviceType.go b/bmp-console-api/swaggermodels/deviceType.go new file mode 100644 index 0000000..3b3fe52 --- /dev/null +++ b/bmp-console-api/swaggermodels/deviceType.go @@ -0,0 +1,24 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/response" +) + +// swagger:parameters getAvailableDeviceTypes +type GetAvailableDeviceTypesRequest struct { + ReadHeader + + // in: query + requestTypes.GetAvailableDeviceTypesRequest +} + +// GetAvailableDeviceTypesResponse is an response struct +// swagger:response getAvailableDeviceTypes +type GetAvailableDeviceTypesResponse struct { + // in: body + Body struct { + Result map[string][]responseTypes.DeviceType `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/idc.go b/bmp-console-api/swaggermodels/idc.go new file mode 100644 index 0000000..341ad6e --- /dev/null +++ b/bmp-console-api/swaggermodels/idc.go @@ -0,0 +1,22 @@ +package swaggermodels + +import ( + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// swagger:parameters getIdcList +type GetIdcListRequest struct { + ReadHeader + //in: query + ExportType string `json:"exportType"` +} + +// GetIdcListResponse is an response struct +// swagger:response getIdcList +type GetIdcListResponse struct { + // in: body + Body struct { + Result sdkModels.IdcList `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/image.go b/bmp-console-api/swaggermodels/image.go new file mode 100644 index 0000000..49eb12e --- /dev/null +++ b/bmp-console-api/swaggermodels/image.go @@ -0,0 +1,24 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// swagger:parameters queryImagesByDeviceType +type QueryImagesByDeviceTypeRequest struct { + ReadHeader + + // in: query + requestTypes.QueryImagesByDeviceTypeRequest +} + +// QueryImagesByDeviceTypeResponse is an response struct +// swagger:response queryImagesByDeviceType +type QueryImagesByDeviceTypeResponse struct { + // in: body + Body struct { + Result map[string][]*sdkModels.Image `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/instance.go b/bmp-console-api/swaggermodels/instance.go new file mode 100644 index 0000000..475c03f --- /dev/null +++ b/bmp-console-api/swaggermodels/instance.go @@ -0,0 +1,349 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// swagger:parameters createInstance +type CreateInstanceRequest struct { + WriteHeader + + // in:body + Body sdkModels.CreateInstanceRequest +} + +// CreateInstanceResponse is an response struct +// swagger:response createInstance +type CreateInstanceResponse struct { + // in: body + Body struct { + Result responseTypes.CreateInstanceResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters getInstanceList +type GetInstanceListRequest struct { + ReadHeader + + // in: query + requestTypes.QueryInstancesRequest +} + +// GetInstanceListResponse is an response struct +// swagger:response getInstanceList +type GetInstanceListResponse struct { + // in: body + Body struct { + Result responseTypes.InstancesResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters getInstanceInfo +type GetInstanceInfoRequest struct { + ReadHeader + + // in: path + InstanceID string `json:"instance_id"` +} + +// GetInstanceInfoResponse is an response struct +// swagger:response getInstanceInfo +type GetInstanceInfoResponse struct { + // in: body + Body struct { + Result responseTypes.InstanceInfo `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters startInstance +type StartInstanceRequest struct { + WriteHeader + + // in:body + Body requestTypes.StartInstanceRequest +} + +// StartInstanceResponse is an response struct +// swagger:response startInstance +type StartInstanceResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters stopInstance +type StopInstanceRequest struct { + WriteHeader + + // in:body + Body requestTypes.StopInstanceRequest +} + +// StopInstanceResponse is an response struct +// swagger:response stopInstance +type StopInstanceResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters restartInstance +type RestartInstanceRequest struct { + WriteHeader + + // in:body + Body requestTypes.RestartInstanceRequest +} + +// RestartInstanceResponse is an response struct +// swagger:response restartInstance +type RestartInstanceResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters lockInstance +type LockInstanceRequest struct { + WriteHeader + + // in:body + Body requestTypes.LockInstanceRequest +} + +// LockInstanceResponse is an response struct +// swagger:response lockInstance +type LockInstanceResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters unlockInstance +type UnlockInstanceRequest struct { + WriteHeader + + // in:body + Body requestTypes.UnLockInstanceRequest +} + +// UnlockInstanceResponse is an response struct +// swagger:response unlockInstance +type UnlockInstanceResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters modifyInstance +type ModifyInstanceRequest struct { + WriteHeader + + // in:body + Body requestTypes.ModifyInstanceRequest +} + +// ModifyInstanceResponse is an response struct +// swagger:response modifyInstance +type ModifyInstanceResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters deleteInstance +type DeleteInstanceRequest struct { + ReadHeader + + // in: path + InstanceID string `json:"instance_id"` +} + +// DeleteInstanceResponse is an response struct +// swagger:response deleteInstance +type DeleteInstanceResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters startInstances +type StartInstancesRequest struct { + WriteHeader + + // in:body + Body requestTypes.StartInstancesRequest +} + +// StartInstancesResponse is an response struct +// swagger:response startInstances +type StartInstancesResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters stopInstances +type StopInstancesRequest struct { + WriteHeader + + // in:body + Body requestTypes.StartInstancesRequest +} + +// StopInstancesResponse is an response struct +// swagger:response stopInstances +type StopInstancesResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters restartInstances +type RestartInstancesRequest struct { + WriteHeader + + // in:body + Body requestTypes.StartInstancesRequest +} + +// RestartInstancesResponse is an response struct +// swagger:response restartInstances +type RestartInstancesResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters modifyInstances +type ModifyInstancesRequest struct { + WriteHeader + + // in:body + Body requestTypes.ModifyInstancesRequest +} + +// ModifyInstancesResponse is an response struct +// swagger:response modifyInstances +type ModifyInstancesResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters deleteInstances +type DeleteInstancesRequest struct { + WriteHeader + + // in:body + Body requestTypes.StartInstancesRequest +} + +// DeleteInstancesResponse is an response struct +// swagger:response deleteInstances +type DeleteInstancesResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters resetPasswd +type ResetPasswdRequest struct { + WriteHeader + + // in:body + Body requestTypes.ResetPasswdRequest +} + +// ResetPasswdResponse is an response struct +// swagger:response resetPasswd +type ResetPasswdResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters resetInstancesPasswd +type ResetInstancesPasswdRequest struct { + WriteHeader + + // in:body + Body requestTypes.ResetInstancesPasswdRequest +} + +// ResetInstancesPasswdResponse is an response struct +// swagger:response resetInstancesPasswd +type ResetInstancesPasswdResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters reinstallInstance +type ReinstallInstanceRequest struct { + WriteHeader + + // in:body + Body requestTypes.ReinstallInstanceRequest +} + +// ReinstallInstanceResponse is an response struct +// swagger:response reinstallInstance +type ReinstallInstanceResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters getInstanceListForShare +type GetInstanceListForShareRequest struct { + ReadHeader + + // in: query + requestTypes.QueryInstancesForShareRequest +} + +// GetInstanceListForShareResponse is an response struct +// swagger:response getInstanceListForShare +type GetInstanceListForShareResponse struct { + // in: body + Body struct { + Result []*sdkModels.InstanceForShare `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/keypair.go b/bmp-console-api/swaggermodels/keypair.go new file mode 100644 index 0000000..2c911a3 --- /dev/null +++ b/bmp-console-api/swaggermodels/keypair.go @@ -0,0 +1,117 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/response" +) + +// swagger:parameters getKeypairList +type GetKeypairListRequest struct { + ReadHeader + + // in: query + requestTypes.QueryKeypairsRequest +} + +// GetKeypairListResponse is an response struct +// swagger:response getKeypairList +type GetKeypairListResponse struct { + // in: body + Body struct { + Result responseTypes.KeyPairsResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters getKeypairInfo +type GetKeypairInfoRequest struct { + ReadHeader + + // in: path + KeypairID string `json:"keypair_id"` +} + +// GetKeypairInfoResponse is an response struct +// swagger:response getKeypairInfo +type GetKeypairInfoResponse struct { + // in: body + Body struct { + Result responseTypes.KeyPairInfo `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters createKeypair +type CreateKeypairRequest struct { + WriteHeader + + // in:body + Body requestTypes.CreateKeypairRequest +} + +// CreateKeypairResponse is an response struct +// swagger:response createKeypair +type CreateKeypairResponse struct { + // in: body + Body struct { + Result responseTypes.KeyPair `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters deleteKeypair +type DeleteKeypairRequest struct { + ReadHeader + + // in: path + KeypairID string `json:"keypair_id"` +} + +// DeleteKeypairResponse is an response struct +// swagger:response deleteKeypair +type DeleteKeypairResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters modifyKeypair +type ModifyKeypairRequest struct { + ReadHeader + + // in: path + KeypairID string `json:"keypair_id"` + + // in:body + Body requestTypes.ModifyKeypairRequest +} + +// ModifyKeypairResponse is an response struct +// swagger:response modifyKeypair +type ModifyKeypairResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters checkKeypairName +type CheckKeypairNameRequest struct { + ReadHeader + + // in: query + requestTypes.QueryKeypairsRequest +} + +// CheckKeypairNameResponse is an response struct +// swagger:response checkKeypairName +type CheckKeypairNameResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/partition.go b/bmp-console-api/swaggermodels/partition.go new file mode 100644 index 0000000..946d9ca --- /dev/null +++ b/bmp-console-api/swaggermodels/partition.go @@ -0,0 +1,24 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// swagger:parameters queryDefaultSystemPartitions +type QueryDefaultSystemPartitionsRequest struct { + ReadHeader + + // in: query + requestTypes.QueryDefaultSystemPartitionRequest +} + +// QueryDefaultSystemPartitionsResponse is an response struct +// swagger:response queryDefaultSystemPartitions +type QueryDefaultSystemPartitionsResponse struct { + // in: body + Body struct { + Result []*sdkModels.Partition `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/project.go b/bmp-console-api/swaggermodels/project.go new file mode 100644 index 0000000..21ec541 --- /dev/null +++ b/bmp-console-api/swaggermodels/project.go @@ -0,0 +1,202 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// swagger:parameters createProject +type CreateProjectRequest struct { + WriteHeader + + // in:body + Body sdkModels.CreateProjectRequest +} + +// CreateProjectResponse is an response struct +// swagger:response createProject +type CreateProjectResponse struct { + // in: body + Body struct { + Result responseTypes.ProjectId `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters getProjectList +type GetProjectListRequest struct { + ReadHeader + + // in: query + requestTypes.QueryProjectsRequest +} + +// GetProjectListResponse is an response struct +// swagger:response getProjectList +type GetProjectListResponse struct { + // in: body + Body struct { + Result sdkModels.ProjectList `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters getProject +type GetProjectRequest struct { + ReadHeader + + // in: path + ProjectID string `json:"project_id"` +} + +// GetProjectResponse is an response struct +// swagger:response getProject +type GetProjectResponse struct { + // in: body + Body struct { + Result responseTypes.Project `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters modifyProject +type ModifyProjectRequest struct { + WriteHeader + + // in: path + ProjectID string `json:"project_id"` + + // in:body + Body sdkModels.ModifyProjectRequest +} + +// ModifyProjectResponse is an response struct +// swagger:response modifyProject +type ModifyProjectResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters modifyProjectDescription +type ModifyProjectDescriptionRequest struct { + WriteHeader + + // in: path + ProjectID string `json:"project_id"` + + // in:body + Body sdkModels.ModifyProjectDescriptionRequest +} + +// ModifyProjectDescriptionResponse is an response struct +// swagger:response modifyProjectDescription +type ModifyProjectDescriptionResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters deleteProject +type DeleteProjectRequest struct { + WriteHeader + + // in: path + ProjectID string `json:"project_id"` +} + +// DeleteProjectResponse is an response struct +// swagger:response deleteProject +type DeleteProjectResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters shareProject +type ShareProjectRequest struct { + WriteHeader + + // in: path + ProjectID string `json:"project_id"` + + // in:body + Body requestTypes.ShareProjectRequest +} + +// ShareProjectResponse is an response struct +// swagger:response shareProject +type ShareProjectResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters cancelshareProject +type CancelShareProjectRequest struct { + WriteHeader + + // in: path + ProjectID string `json:"project_id"` + + // in:body + Body requestTypes.ShareProjectRequest +} + +// CancelShareProjectResponse is an response struct +// swagger:response cancelshareProject +type CancelShareProjectResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters moveProject +type MoveProjectRequest struct { + WriteHeader + + // in: path + ProjectID string `json:"project_id"` + + // in:body + Body requestTypes.MoveProjectRequest +} + +// MoveProjectResponse is an response struct +// swagger:response moveProject +type MoveProjectResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters moveInstances +type MoveInstancesRequest struct { + WriteHeader + + // in:body + Body requestTypes.MoveInstancesRequest +} + +// MoveInstancesResponse is an response struct +// swagger:response moveInstances +type MoveInstancesResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/raid.go b/bmp-console-api/swaggermodels/raid.go new file mode 100644 index 0000000..67a980a --- /dev/null +++ b/bmp-console-api/swaggermodels/raid.go @@ -0,0 +1,24 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + "coding.jd.com/aidc-bmp/bmp-console-api/types/response" +) + +// swagger:parameters queryVolumeRaids +type QueryRaidsByDeviceTypeIDAndVolumeTypeRequest struct { + ReadHeader + + // in: query + requestTypes.QueryVolumeRaidsRequest +} + +// QueryRaidsByDeviceTypeIDAndVolumeTypeResponse is an response struct +// swagger:response queryVolumeRaids +type QueryRaidsByDeviceTypeIDAndVolumeTypeResponse struct { + // in: body + Body struct { + Result []*response.VolumeRaid `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/swaggermodels/swaggerinfo.go b/bmp-console-api/swaggermodels/swaggerinfo.go new file mode 100644 index 0000000..b7df69b --- /dev/null +++ b/bmp-console-api/swaggermodels/swaggerinfo.go @@ -0,0 +1,28 @@ +// Package classification bmp-console-api +// +// the purpose of this application is to provide an application +// that is using plain go code to define an API +// +// This should demonstrate all the possible comment annotations +// that are available to turn go code into a fully compliant swagger 2.0 spec +// +// Terms Of Service: +// +// there are no TOS at this moment, use at your own risk we take no responsibility +// +// Schemes: http +// Host: bmp-console-api.local +// BasePath: / +// Version: 0.0.1 +// License: MIT http://opensource.org/licenses/MIT +// Contact: minping@jd.com +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// +// swagger:meta +package swaggermodels diff --git a/bmp-console-api/swaggermodels/user.go b/bmp-console-api/swaggermodels/user.go new file mode 100644 index 0000000..2e8a6de --- /dev/null +++ b/bmp-console-api/swaggermodels/user.go @@ -0,0 +1,157 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-console-api/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +// swagger:parameters login +type LoginRequest struct { + WriteHeader + + // in:body + Body requestTypes.LoginRequest +} + +// LoginResponse is an response struct +// swagger:response login +type LoginResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters logout +type LogoutRequest struct { + WriteHeader +} + +// LogoutResponse is an response struct +// swagger:response logout +type LogoutResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters getUserInfo +type GetUserInfoRequest struct { + ReadHeader +} + +// GetUserInfoResponse is an response struct +// swagger:response getUserInfo +type GetUserInfoResponse struct { + // in: body + Body struct { + Result responseTypes.User `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters updatePassword +type UpdatePasswordRequest struct { + WriteHeader + + // in:body + Body requestTypes.UpdatePasswordRequest +} + +// UpdatePasswordResponse is an response struct +// swagger:response updatePassword +type UpdatePasswordResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters updateUserInfo +type UpdateUserInfoRequest struct { + WriteHeader + + // in:body + Body requestTypes.ModifyUserInfoRequest +} + +// UpdateUserInfoResponse is an response struct +// swagger:response updateUserInfo +type UpdateUserInfoResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters getTimezoneList +type GetTimezoneListRequest struct { + ReadHeader +} + +// GetTimezoneListResponse is an response struct +// swagger:response getTimezoneList +type GetTimezoneListResponse struct { + // in: body + Body struct { + Result responseTypes.GetTimezoneListResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters getConsoleAccessUserList +type GetConsoleAccessUserListRequest struct { + ReadHeader +} + +// GetConsoleAccessUserListResponse is an response struct +// swagger:response getConsoleAccessUserList +type GetConsoleAccessUserListResponse struct { + // in: body + Body struct { + Result []*models.User `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters checkUserConsoleAccess +type CheckUserConsoleAccessRequest struct { + ReadHeader + + // in: query + requestTypes.CheckUserConsoleAccessRequest +} + +// CheckUserConsoleAccessResponse is an response struct +// swagger:response checkUserConsoleAccess +type CheckUserConsoleAccessResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters checkUserConsoleAccessByName +type CheckUserConsoleAccessByNameRequest struct { + ReadHeader + + // in: query + requestTypes.CheckUserConsoleAccessByNameRequest +} + +// CheckUserConsoleAccessByNameResponse is an response struct +// swagger:response checkUserConsoleAccessByName +type CheckUserConsoleAccessByNameResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-console-api/test_script/curl.sh b/bmp-console-api/test_script/curl.sh new file mode 100644 index 0000000..e99fc1c --- /dev/null +++ b/bmp-console-api/test_script/curl.sh @@ -0,0 +1,57 @@ +#!/bin/bash + +curl -X PUT -H 'Authorization: JDCLOUD2-HMAC-SHA256 Credential=DD1B0BFA7BAA5DAED057ACF4817AF55B/20220424/cn-north-1/cps/jdcloud2_request, SignedHeaders=content-type;host;x-jdcloud-date;x-jdcloud-language;x-jdcloud-nonce;x-jdcloud-order-key;x-jdcloud-pin;x-jdcloud-profile, Signature=7fabd922cd7ed21259dd5aaa6a9598b71b5f3c26981df2130d7a4692331e31d6' -H 'Content-Type: application/json' -H 'User-Agent: JdcloudSdkGo/1.1.6 cps/2.5.5' -H 'X-Jdcloud-Date: 20220424T061849Z' -H 'X-Jdcloud-Language: cn' -H 'X-Jdcloud-Nonce: 288135bc-ba8b-4fc4-899a-1468bdc23331' -H 'X-Jdcloud-Order-Key: ghpmaezb-pz10-vodh-8x1g-bzu854815zfk' -H 'X-Jdcloud-Pin: MWMxODczMWZhYjdmNDkwNzg4MjM=' -H 'X-Jdcloud-Request-Id: ghpmaezb-pz10-vodh-8x1g-111111111111' -d '{ + "clientToken": null, + "instanceSpec": { + "aliasIps": null, + "az": "cn-north-1a", + "bandwidth": null, + "bandwidthPackageId": null, + "charge": { + "autoRenew": false, + "buyScenario": null, + "chargeDuration": null, + "chargeMode": "postpaid_by_duration", + "chargeUnit": null + }, + "cidr": null, + "count": 1, + "dataDiskPartitions": null, + "dataRaidTypeId": "r-l6pounvfife0njlinhk6ztf2xyio", + "description": null, + "deviceType": "cps.s.normal", + "enableInternet": "no", + "enableIpv6": null, + "extensionAliasIps": null, + "extensionBandwidth": null, + "extensionBandwidthPackageId": null, + "extensionEnableInternet": null, + "extensionEnableIpv6": null, + "extensionInternetChargeMode": null, + "extensionIpv6Address": null, + "extensionIpv6AliasIps": null, + "extensionLineType": null, + "extensionPrivateIp": null, + "extensionSubnetId": null, + "hostname": null, + "imageType": "standard", + "interfaceMode": "bond", + "internetChargeMode": null, + "ipv6Address": null, + "ipv6AliasIps": null, + "keypairId": null, + "keypairIdSos": null, + "lineType": null, + "name": "cccc", + "networkType": "retail", + "osTypeId": "i-v2xudi13m1yrdg3aencxya21bcaa", + "password": "JDyun123", + "privateIp": null, + "resourceTags": null, + "subnetId": null, + "sysRaidTypeId": "r-wtzluqacgzzxgunnabdkpnpjew3d", + "systemDiskPartitions": null, + "userData": null + }, + "regionId": "cn-north-1" +}' 'http://10.226.148.63:8000/v1/regions/cn-north-1/instances' diff --git a/bmp-console-api/test_script/curl_api.sh b/bmp-console-api/test_script/curl_api.sh new file mode 100644 index 0000000..c1ea819 --- /dev/null +++ b/bmp-console-api/test_script/curl_api.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +curl -X PUT -H 'X-Jdcloud-Pin: 1c18731fab7f49078823' -d '{"clientToken":null,"instanceSpec":{"aliasIps":null,"az":"cn-north-1a","bandwidth":null,"bandwidthPackageId":null,"charge":{"autoRenew":false,"buyScenario":null,"chargeDuration":null,"chargeMode":"postpaid_by_duration","chargeUnit":"month"},"cidr":null,"count":1,"dataDiskPartitions":null,"dataRaidTypeId":"r-l6pounvfife0njlinhk6ztf2xyio","description":null,"deviceType":"cps.s.normal","enableInternet":"no","enableIpv6":null,"extensionAliasIps":null,"extensionBandwidth":null,"extensionBandwidthPackageId":null,"extensionEnableInternet":null,"extensionEnableIpv6":null,"extensionInternetChargeMode":null,"extensionIpv6Address":null,"extensionIpv6AliasIps":null,"extensionLineType":null,"extensionPrivateIp":null,"extensionSubnetId":null,"hostname":null,"imageType":"standard","interfaceMode":"bond","internetChargeMode":null,"ipv6Address":null,"ipv6AliasIps":null,"keypairId":null,"keypairIdSos":null,"lineType":null,"name":"minping_test","networkType":"retail","osTypeId":"i-v2xudi13m1yrdg3aencxya21bcaa","password":"JDyun123","privateIp":null,"resourceTags":null,"subnetId":null,"sysRaidTypeId":"r-wtzluqacgzzxgunnabdkpnpjew3d","systemDiskPartitions":null,"userData":null},"regionId":"cn-north-1"}' 'http://127.0.0.1:8799/v1/regions/cn-north-1/instances' diff --git a/bmp-console-api/thirdpart/excel/excel.go b/bmp-console-api/thirdpart/excel/excel.go new file mode 100644 index 0000000..c70287f --- /dev/null +++ b/bmp-console-api/thirdpart/excel/excel.go @@ -0,0 +1,145 @@ +package excel + +import ( + "os" + "path/filepath" + "strconv" + + "coding.jd.com/aidc-bmp/bmp-console-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-console-api/util" + "github.com/xuri/excelize/v2" +) + +type IExcel interface { + GetSheetData() ([][]string, error) + SetSheetData(string, []string, [][]string) error + SetNewSheet(string) int + SaveFile(string) (string, error) + SetSheetHeader(string, []string) error + SetSheetDataRandom(string, string, [][]string, int) error +} + +type Excel struct { + File *excelize.File +} + +func NewExcelInstance() *Excel { + return &Excel{ + File: excelize.NewFile(), + } +} + +func LoadExcel(fileName string) (*Excel, error) { + f, err := excelize.OpenFile(fileName) + if err != nil { + return nil, err + } + return &Excel{ + File: f, + }, nil +} + +func (e *Excel) GetSheetData() ([][]string, error) { + index := e.File.GetActiveSheetIndex() + name := e.File.GetSheetName(index) + return e.File.GetRows(name) +} + +func (e *Excel) SetNewSheet(sheetName string) int { + return e.File.NewSheet(sheetName) +} + +func (e *Excel) SetSheetHeader(sheetName string, sheetHeaders []string) error { + colNum, rowNum := 1, 1 + for _, header := range sheetHeaders { + //从第一列开始获取每列第一个元素位置 + axis, err := excelize.ColumnNumberToName(colNum) + if err != nil { + return err + } + axis = axis + strconv.Itoa(rowNum) + if err = e.File.SetCellValue(sheetName, axis, header); err != nil { + return err + } + colNum++ + } + return nil +} + +func (e *Excel) SetSheetDataRandom(requestId, sheetName string, sheetData [][]string, rowNum int) error { + for _, row := range sheetData { + colNum := 1 + for _, value := range row { + axis, err := excelize.ColumnNumberToName(colNum) + if err != nil { + return err + } + axis = axis + strconv.Itoa(rowNum) + if err := e.File.SetCellValue(sheetName, axis, value); err != nil { + return err + } + colNum++ + } + rowNum++ + } + return nil +} + +func (e *Excel) SetSheetData(sheetName string, sheetHeaders []string, sheetData [][]string) error { + if err := e.SetSheetHeader(sheetName, sheetHeaders); err != nil { + return err + } + rowNum := 2 + for _, row := range sheetData { + colNum := 1 + for _, value := range row { + axis, err := excelize.ColumnNumberToName(colNum) + if err != nil { + return err + } + axis = axis + strconv.Itoa(rowNum) + if err := e.File.SetCellValue(sheetName, axis, value); err != nil { + return err + } + colNum++ + } + rowNum++ + } + return nil +} + +func (e *Excel) SaveFile(fileName string) (string, error) { + basePath, err := os.Executable() + if err != nil { + return "", err + } + res, err := filepath.EvalSymlinks(filepath.Dir(basePath)) + if err != nil { + return "", err + } + CreateDirIfNotExist(BaseLogic.LOCAL_FILE_PATH) + fileName = filepath.Join(res, BaseLogic.LOCAL_FILE_PATH, util.GenUuid()+fileName) + return fileName, e.File.SaveAs(fileName) +} + +/** +判断文件是否存在 +*/ +func CreateDirIfNotExist(fileAddr string) bool { + s, err := os.Stat(fileAddr) + if err != nil { + return CreateDir(fileAddr) + } + return s.IsDir() +} + +/** +创建文件夹 +*/ +func CreateDir(dirName string) bool { + err := os.Mkdir(dirName, 0777) + if err != nil { + return false + } + return true +} diff --git a/bmp-console-api/thirdpart/openApi/openApi.go b/bmp-console-api/thirdpart/openApi/openApi.go new file mode 100644 index 0000000..a3a62a8 --- /dev/null +++ b/bmp-console-api/thirdpart/openApi/openApi.go @@ -0,0 +1,47 @@ +package openApi + +import ( + "fmt" + + sdk "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/client" + beego "github.com/beego/beego/v2/server/web" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +var ( + SdkClient *sdk.CPS +) + +func Init() { + + host, _ := beego.AppConfig.String("openapi_host") + port, _ := beego.AppConfig.String("openapi_port") + host = fmt.Sprintf("%s:%s", host, port) + fmt.Println("openapi host:", host) + + token, _ := beego.AppConfig.String("openapi_token") + /* + cfg := sdk.TransportConfig{ + Host: host, + BasePath: "/v1", + Schemes: []string{"http"}, + } + SdkClient = sdk.NewHTTPClientWithConfig(nil, &cfg) + */ + + r := httptransport.New(host, "/v1", []string{"http"}) + r.SetDebug(true) + r.DefaultAuthentication = httptransport.BearerToken(token) + /* + r.DefaultMediaType = runtime.XMLMime + r.Consumers = map[string]runtime.Consumer{ + runtime.XMLMime: runtime.XMLConsumer(), + } + r.Producers = map[string]runtime.Producer{ + "application/xhtml+xml": runtime.XMLProducer(), + } + */ + SdkClient = sdk.New(r, strfmt.Default) + +} diff --git a/bmp-console-api/thirdpart/redis/redis.go b/bmp-console-api/thirdpart/redis/redis.go new file mode 100644 index 0000000..8adb2ab --- /dev/null +++ b/bmp-console-api/thirdpart/redis/redis.go @@ -0,0 +1,36 @@ +package redis + +import ( + "fmt" + + beego "github.com/beego/beego/v2/server/web" + + "github.com/go-redis/redis" +) + +var RedisCli *redis.Client + +// InitRedis initial redisUtil instance +func Init() error { + var host, port, password string + var dbNum int + //namespace, _ = beego.AppConfig.String("bmp_redis_namespace") + host, _ = beego.AppConfig.String("bmp_redis_host") + port, _ = beego.AppConfig.String("bmp_redis_port") + password, _ = beego.AppConfig.String("bmp_redis_password") + dbNum = beego.AppConfig.DefaultInt("bmp_redis_db", 0) + //addr := fmt.Sprintf("%s:%s", host, port) + //return redisInit.InitRedis(namespace, addr, password, dbNum) + + RedisCli = redis.NewClient(&redis.Options{ + Addr: host + ":" + port, + Password: password, // no password set + DB: dbNum, // use default DB + }) + _, err := RedisCli.Ping().Result() + if err != nil { + fmt.Println("redis connect error:", RedisCli, err) + return err + } + return nil +} diff --git a/bmp-console-api/thirdpart/session/session.go b/bmp-console-api/thirdpart/session/session.go new file mode 100644 index 0000000..5f69892 --- /dev/null +++ b/bmp-console-api/thirdpart/session/session.go @@ -0,0 +1,28 @@ +package session + +import ( + "fmt" + + beego "github.com/beego/beego/v2/server/web" +) + +func Init() error { + + cookieName, _ := beego.AppConfig.String("sessionname") + sessionLife, _ := beego.AppConfig.Int64("sessionlife") + + redisHost, _ := beego.AppConfig.String("bmp_redis_host") + redisPort, _ := beego.AppConfig.Int("bmp_redis_port") + redisPassword, _ := beego.AppConfig.String("bmp_redis_password") + redisProvider := fmt.Sprintf("%s:%d,10,%s", redisHost, redisPort, redisPassword) + fmt.Println("session.redis.provicer:", redisProvider) + + beego.BConfig.WebConfig.Session.SessionOn = true + beego.BConfig.WebConfig.Session.SessionName = cookieName + // beego.BConfig.WebConfig.Session.SessionCookieLifeTime = sessionLife + beego.BConfig.WebConfig.Session.SessionGCMaxLifetime = sessionLife + beego.BConfig.WebConfig.Session.SessionProvider = "redis" + beego.BConfig.WebConfig.Session.SessionProviderConfig = redisProvider + + return nil +} diff --git a/bmp-console-api/types/request/ApikeyRequest.go b/bmp-console-api/types/request/ApikeyRequest.go new file mode 100644 index 0000000..ba4eb9b --- /dev/null +++ b/bmp-console-api/types/request/ApikeyRequest.go @@ -0,0 +1,5 @@ +package request + +type GetApikeyListRequest struct { + PagingRequest +} diff --git a/bmp-console-api/types/request/AuditLogsRequest.go b/bmp-console-api/types/request/AuditLogsRequest.go new file mode 100644 index 0000000..e6953e3 --- /dev/null +++ b/bmp-console-api/types/request/AuditLogsRequest.go @@ -0,0 +1,20 @@ +package request + +type DescribeAuditLogsRequest struct { + PagingRequest + // instance_id + InstanceID string `json:"instanceId" validate:"required"` + // 操作名称 + Operation string `json:"operation"` + // 操作人 + UserName string `json:"userName"` + // result + Result string `json:"result"` + // 操作时间下限 + StartTime int64 `json:"startTime"` + // 操作时间上限 + EndTime int64 `json:"endTime"` + // 是否显示所有 + IsAll string `json:"isAll"` + ExportType string `json:"exportType"` // v2.27.2 0:导出全部实力;1:导出选中实例;2:导出搜索结果 +} diff --git a/bmp-console-api/types/request/BaseRequest.go b/bmp-console-api/types/request/BaseRequest.go new file mode 100644 index 0000000..972c8c7 --- /dev/null +++ b/bmp-console-api/types/request/BaseRequest.go @@ -0,0 +1,25 @@ +package request + +import ( + "errors" + + log "coding.jd.com/aidc-bmp/bmp_log" + validator "github.com/go-playground/validator/v10" +) + +var va = validator.New() + +func validate(req interface{}, logger *log.Logger) error { + if err := va.Struct(req); err != nil { + logger.Warn("Validate error:", err.Error()) + var e string + v, ok := err.(validator.ValidationErrors) + if !ok { + e = err.Error() + } else { + e = v[0].Field() + } + return errors.New(e + " param invalid") + } + return nil +} diff --git a/bmp-console-api/types/request/CustomInfoRequest.go b/bmp-console-api/types/request/CustomInfoRequest.go new file mode 100644 index 0000000..652b22f --- /dev/null +++ b/bmp-console-api/types/request/CustomInfoRequest.go @@ -0,0 +1,13 @@ +package request + +type QueryCustomInfoRequest struct { + PageKey string `json:"pageKey"` + Reload string `json:"reload"` +} +type SetCustomInfoRequest struct { + PageKey string `json:"pageKey"` + PageValue map[string]map[string]bool `json:"pageValue"` +} +type QueryPrivilegeNewRequest struct { + Pin string `json:"pin"` +} diff --git a/bmp-console-api/types/request/DeviceRequest.go b/bmp-console-api/types/request/DeviceRequest.go new file mode 100644 index 0000000..f9bc21b --- /dev/null +++ b/bmp-console-api/types/request/DeviceRequest.go @@ -0,0 +1,18 @@ +package request + +import ( + "git.jd.com/cps-golang/ironic-common/exception" + validator "github.com/go-playground/validator/v10" +) + +type QueryDeviceStockRequest struct { + IdcID string `json:"idc_id"` + DeviceTypeId string `json:"deviceTypeId"` + Count int64 `json:"count"` +} + +func (c *QueryDeviceStockRequest) Validate() { + if err := validator.New().Struct(c); err != nil { + panic(exception.CommonParamValid) + } +} diff --git a/bmp-console-api/types/request/DeviceTypesRequest.go b/bmp-console-api/types/request/DeviceTypesRequest.go new file mode 100644 index 0000000..4a23838 --- /dev/null +++ b/bmp-console-api/types/request/DeviceTypesRequest.go @@ -0,0 +1,5 @@ +package request + +type GetAvailableDeviceTypesRequest struct { + IdcID string `json:"idc_id"` +} diff --git a/bmp-console-api/types/request/HeaderRequest.go b/bmp-console-api/types/request/HeaderRequest.go new file mode 100644 index 0000000..c8c7cda --- /dev/null +++ b/bmp-console-api/types/request/HeaderRequest.go @@ -0,0 +1,6 @@ +package request + +type HeaderRequest struct { + IdcID string `json:"idc_id"` // 必填 + Token string `json:"token"` +} diff --git a/bmp-console-api/types/request/ImageRequest.go b/bmp-console-api/types/request/ImageRequest.go new file mode 100644 index 0000000..8cfc3dc --- /dev/null +++ b/bmp-console-api/types/request/ImageRequest.go @@ -0,0 +1,12 @@ +package request + +type QueryImagesByDeviceTypeRequest struct { + // Pin string `json:"pin"` + IdcID string `json:"idc_id"` + DeviceTypeID string `json:"deviceTypeId"` + // OsType string `json:"os_type"` + // OsVersion string `json:"os_version"` + // OsID string `json:"os_id"` + // Source string `json:"source"` + // ImageIds []string `json:"image_ids"` +} diff --git a/bmp-console-api/types/request/InstanceRequest.go b/bmp-console-api/types/request/InstanceRequest.go new file mode 100644 index 0000000..45fe505 --- /dev/null +++ b/bmp-console-api/types/request/InstanceRequest.go @@ -0,0 +1,133 @@ +package request + +import ( + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +type DeleteInstanceRequest struct { + HeaderRequest +} + +type GetInstanceStatusRequest struct { + InstanceID string `json:"instanceId"` +} + +type LockInstanceRequest struct { + HeaderRequest + InstanceId string `json:"instanceId"` +} + +type UnLockInstanceRequest struct { + HeaderRequest + InstanceId string `json:"instanceId"` +} + +type StopInstanceRequest struct { + HeaderRequest + InstanceId string `json:"instanceId"` + ClientToken int `json:"clientToken"` +} + +type StartInstanceRequest struct { + HeaderRequest + InstanceId string `json:"instanceId"` + ClientToken int `json:"clientToken"` +} + +type RestartInstanceRequest struct { + HeaderRequest + InstanceId string `json:"instanceId"` + ClientToken int `json:"clientToken"` +} + +type ModifyInstanceRequest struct { + HeaderRequest + + // required: true + InstanceID string `json:"instanceId"` + + Name string `json:"name"` + // required: true + Description *string `json:"description"` +} + +type QueryInstanceRequest struct { + HeaderRequest + InstanceId string `json:"instanceId" valid:"Required"` +} + +type QueryInstancesRequest struct { + PagingRequest + ProjectID string `json:"projectId"` + IdcID string `json:"idcId"` + Status string `json:"status"` // v2.27.2 状态,逗号分隔;显示所有选项,复选框选择,支持多选。旧代码:private List status string `json:""` + DeviceTypeId string `json:"deviceTypeId"` + Name string `json:"name"` // v2.27.2 实例列表搜索框支持联合搜索| 模糊搜索,单个条件值搜索 + + DeviceType string `json:"deviceType"` + + InstanceId string `json:"instanceId"` + + PrivateIp string `json:"privateIp"` + + PrivateIpv6 string `json:"privateIpv6"` + + KeypairId string `json:"keypairId"` + + Sn string `json:"sn"` // v2.18.1 新增 + + IloIp string `json:"iloIp"` // v2.27.2 带外管理IP,逗号分隔; 精确搜索,多个条件值搜索 + + //Cabinets string `json:"cabinets"` // v2.27.2 机柜编码,逗号分隔;精确搜索,多个条件值搜索;如:T4-L3-152-Test + + DeviceTypeList string `json:"deviceTypeList"` // v2.27.2 规格类型,逗号分隔;显示所有选项,复选框选择,支持多选;精确搜索,多个条件值搜索;如:cps.c2.per2.highdensity + + ExportType string `json:"exportType"` // v2.27.2 0:导出全部实力;1:导出选中实例;2:导出搜索结果 + // "1" 表示全部 + IsAll string `json:"isAll"` + + //是否安装了agent,"0"表示未安装,"1"表示已安装,不传表示全部 + IsInstallAgent string `json:"isInstallAgent"` +} + +type RemoveInstancesRequest struct { + HeaderRequest + InstanceIds []string `json:"instanceIds"` +} + +type StartInstancesRequest struct { + InstanceIDs []string `json:"instanceIds"` +} + +type ModifyInstancesRequest struct { + InstanceIDs []string `json:"instanceIds"` + InstanceName string `json:"instanceName"` +} + +type ResetPasswdRequest struct { + HeaderRequest + InstanceId string `json:"instanceId" valid:"Required"` + Password string `json:"password"` +} + +type ResetInstancesPasswdRequest struct { + HeaderRequest + InstanceIds []string `json:"instanceIds" valid:"Required"` + Password string `json:"password"` +} + +type ReinstallInstanceRequest struct { + HeaderRequest + InstanceId string `json:"instanceId" valid:"Required"` + sdkModels.ReinstallInstanceRequest +} + +type QueryInstancesForShareRequest struct { + ProjectID string `json:"projectId"` + OwnerName string `json:"ownerName"` + SharerName string `json:"sharerName"` + + //支持搜索 + InstanceName string `json:"instanceName"` + InstanceId string `json:"instanceId"` +} diff --git a/bmp-console-api/types/request/KeypairRequest.go b/bmp-console-api/types/request/KeypairRequest.go new file mode 100644 index 0000000..e45f558 --- /dev/null +++ b/bmp-console-api/types/request/KeypairRequest.go @@ -0,0 +1,32 @@ +package request + +type CheckKeypairNameRequest struct { + Name string `json:"name"` +} + +type CreateKeypairRequest struct { + Name string `json:"name"` + Key string `json:"key"` + ClientToken int `json:"clientToken"` +} + +type ModifyKeypairRequest struct { + Name string `json:"name"` + ClientToken int `json:"clientToken"` +} + +type DeleteKeypairRequest struct { + KeypairID string `json:"keypairId" valid:"Required"` +} + +type QueryKeypairsRequest struct { + PagingRequest + + Name string `json:"name"` + + KeypairIds []string `json:"keypairId"` +} + +type QueryKeypairRequest struct { + KeypairID string `json:"keypairId" valid:"Required"` +} diff --git a/bmp-console-api/types/request/MessageRequest.go b/bmp-console-api/types/request/MessageRequest.go new file mode 100644 index 0000000..673006b --- /dev/null +++ b/bmp-console-api/types/request/MessageRequest.go @@ -0,0 +1,54 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type QueryMessagesRequest struct { + PagingRequest + // 0:导出全部实力;1:导出选中实例;2:导出搜索结果 + ExportType string `json:"exportType"` + // 是否显示全部,取值为1时表示全部 + IsAll string `json:"isAll"` + //0:未读;1:已读;""不传表示全部 + HasRead string `json:"hasRead"` + // 消息类型 + MessageType string `json:"messageType"` + // 消息子类型 + MessageSubType string `json:"messageSubType"` + // 内容,支持模糊搜索 + Detail string `json:"detail"` +} + +func (req *QueryMessagesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type ReadMessagesRequest struct { + + // required: true + MessageIds []string `json:"messageIds" validate:"required"` +} + +func (req *ReadMessagesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DeleteMessagesRequest struct { + + // required: true + MessageIds []string `json:"messageIds" validate:"required"` +} + +func (req *DeleteMessagesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type GetMessageByIdRequest struct { + // required: true + MessageId string `json:"messageId" validate:"required"` +} + +func (req *GetMessageByIdRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-console-api/types/request/MonitorAlertRequest.go b/bmp-console-api/types/request/MonitorAlertRequest.go new file mode 100644 index 0000000..1adb051 --- /dev/null +++ b/bmp-console-api/types/request/MonitorAlertRequest.go @@ -0,0 +1,81 @@ +package request + +import log "coding.jd.com/aidc-bmp/bmp_log" + +type AddAlertRequest struct { + //规则名称 + RuleName string `json:"ruleName" validate:"required"` + //规则ID + // required: true + RuleID string `json:"ruleId" validate:"required"` + //实例id + // required: true + InstanceID string `json:"instanceId" validate:"required"` + //触发条件 + // required: true + Trigger string `json:"trigger" validate:"required"` + //告警值 + // required: true + AlertValue string `json:"alertValue" validate:"required"` + //告警时间戳 + // required: true + AlertTimestamp int64 `json:"alertTimestamp" validate:"required"` + //告警持续时间 + // required: true + AlertPeriod int `json:"alertPeriod" validate:"required"` +} + +func (req *AddAlertRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} + +type DescribeAlertRequest struct { + // rule uuid + // required: true + AlertID string `json:"alertId" validate:"required"` +} + +func (req *DescribeAlertRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DescribeAlertsRequest struct { + PagingRequest + ExportType string `json:"exportType"` + + // 是否显示全部,取值为1时表示全部 + IsAll string `json:"isAll"` + //user uuid + UserID string `json:"userId"` + //username + UserName string `json:"userName"` + //规则名称 + RuleName string `json:"ruleName"` + //规则uuid + RuleID string `json:"ruleId"` + //资源id,目前就是实例id + ResourceID string `json:"resourceId"` + //报警时间筛选stime + StartTime int64 `json:"startTime"` + //报警时间筛选etime + EndTime int64 `json:"endTime"` + ProjectID string `json:"projectId"` +} + +func (req *DescribeAlertsRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DeleteAlertRequest struct { + //告警id + // required: true + AlertId string `json:"alertId" validate:"required"` +} + +func (req *DeleteAlertRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} diff --git a/bmp-console-api/types/request/MonitorDataRequest.go b/bmp-console-api/types/request/MonitorDataRequest.go new file mode 100644 index 0000000..6f1314f --- /dev/null +++ b/bmp-console-api/types/request/MonitorDataRequest.go @@ -0,0 +1,16 @@ +package request + +/* +{"params":{"serviceCode":"cps-vpc","resourceId":"cps-2qtflhpvmuuw5tdodatv6ofxqcek","filters":[{"name":"metric","values":["cps.process.total"]}],"startTime":"2024-06-09T00:00:00","endTime":"2024-06-12T23:59:59","timeInterval":"1h", "downSampleType":"avg"}} +*/ +type GetMonitorDataRequest struct { + MetricName string `json:"metricName" validate:"required"` + InstanceID string `json:"instanceId" validate:"required"` + Device string `json:"device"` + StartTime int64 `json:"startTime"` + EndTime int64 `json:"endTime"` + //最近多少时间,小时为单位 + LastManyTime int64 `json:"lastManyTime"` + TimeInterval int64 `json:"timeInterval"` //s为单位 + DownSampleType string `json:"downSampleType"` //好像不支持 +} diff --git a/bmp-console-api/types/request/MonitorProxyRequest.go b/bmp-console-api/types/request/MonitorProxyRequest.go new file mode 100644 index 0000000..2de62d4 --- /dev/null +++ b/bmp-console-api/types/request/MonitorProxyRequest.go @@ -0,0 +1,26 @@ +package request + +import log "coding.jd.com/aidc-bmp/bmp_log" + +type DesrcibeAgentStatusRequest struct { + // InstanceId,多个用逗号分隔 + // required: true + InstanceId string `json:"instanceId" validate:"required"` +} + +func (req *DesrcibeAgentStatusRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DesrcibeTagsRequest struct { + // instanceId + // required: true + InstanceID string `json:"instanceId" validate:"required"` + // tagName [disk mountpoint nic] + // required: true + TagName string `json:"tagName" validate:"required,oneof=disk mountpoint nic"` +} + +func (req *DesrcibeTagsRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-console-api/types/request/MonitorRuleRequest.go b/bmp-console-api/types/request/MonitorRuleRequest.go new file mode 100644 index 0000000..ed7f0a1 --- /dev/null +++ b/bmp-console-api/types/request/MonitorRuleRequest.go @@ -0,0 +1,183 @@ +package request + +import log "coding.jd.com/aidc-bmp/bmp_log" + +type AddRuleRequest struct { + //规则名称 + // required: true + RuleName string `json:"ruleName" validate:"required"` + //维度 [instance、disk、mountpoint、nic] + // required: true + Dimension string `json:"dimension" validate:"required,oneof=instance disk mountpoint nic"` + //资源类型,目前只支持instance + // required: true + Resource string `json:"resource" validate:"required,oneof=instance"` + //触发条件 + // required: true + TriggerOption []RuleTrigger `json:"triggerOption"` + //通知策略 + // required: true + NoticeOption RuleNotice `json:"noticeOption"` + //实例id列表 + // required: true + InstanceIds []string `json:"instanceIds" validate:"required"` + //盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag"` + ProjectID string `json:"projectId"` +} + +func (req *AddRuleRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} + +//单个触发条件 +type RuleTrigger struct { + //监控指标 cps.cpu.util + // required: true + Metric string `json:"metric" validate:"required"` + //周期(分钟) [1, 2, 5, 15, 30, 60] + // required: true + Period int64 `json:"period" validate:"required,oneof=1 2 5 15 30 60"` + //计算方式 [min max avg sum] + // required: true + Calculation string `json:"calculation" validate:"required,oneof=min max avg sum"` + //计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出] + // required: true + CalculationUnit string `json:"calculationUnit"` + //比较方式 [> >= < <= == !=]或者[gt gte lt lte eq neq] + // required: true + Operation string `json:"operation" validate:"required"` + //阈值 + // required: true + Threshold float64 `json:"threshold"` + //持续周期数 [1, 2, 3, 4, 5, 10, 15, 30, 60] + // required: true + Times int64 `json:"times" validate:"required,oneof=1 2 3 4 5 10 15 30 60"` + //告警级别 [1表示一般,2表示严重,3表示紧急] + // required: true + NoticeLevel int64 `json:"noticeLevel" validate:"required,oneof=1 2 3"` +} + +//通知策略 +type RuleNotice struct { + //通知周期(分钟) [5 10 15 30 60 180 360 720 1440] + // required: true + NoticePeriod int64 `json:"noticePeriod" validate:"required,oneof=5 10 15 30 60 180 360 720 1440"` + // 有效时段开始时间 ["00:00:00"] + // required: true + EffectiveIntervalStart string `json:"effectiveIntervalStart" validate:"required"` + // 有效时段结束时间 ["23:59:59"] + // required: true + EffectiveIntervalEnd string `json:"effectiveIntervalEnd" validate:"required"` + //通知条件,可多选 [1表示报警, 2表示恢复正常] + // required: true + NoticeCondition []int64 `json:"noticeCondition" validate:"required"` + //接收渠道,可多选 [1表示站内信, 2表示邮件] + // required: true + NoticeWay []int64 `json:"noticeWay" validate:"required"` + //通知对象 + // required: true + UserID string `json:"userId" validate:"required"` +} + +type DescribeRuleRequest struct { + // rule uuid + // required: true + RuleID string `json:"ruleId" validate:"required"` +} + +func (req *DescribeRuleRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DescribeRulesRequest struct { + PagingRequest + ExportType string `json:"exportType"` + // 是否显示全部,取值为1时表示全部 + IsAll string `json:"isAll"` + //user uuid + UserId string `json:"userId"` + //username + UserName string `json:"userName"` + //规则名称 + RuleName string `json:"ruleName"` + //规则uuid + RuleId string `json:"ruleId"` + //1 正常 2 禁用 3 告警 + Status int `json:"status"` + ProjectID string `json:"projectId"` +} + +func (req *DescribeRulesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type EditRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` + //规则名称 + // required: true + RuleName string `json:"ruleName" validate:"required"` + //维度 [instance、disk、mountpoint、nic] + // required: true + Dimension string `json:"dimension" validate:"required,oneof=instance disk mountpoint nic"` + //资源类型,目前只支持instance + // required: true + Resource string `json:"resource" validate:"required,oneof=instance"` + //触发条件 + // required: true + TriggerOption []RuleTrigger `json:"triggerOption"` + //通知策略 + // required: true + NoticeOption RuleNotice `json:"noticeOption"` + //实例id列表 + // required: true + InstanceIds []string `json:"instanceIds" validate:"required"` + //盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag"` +} + +func (req *EditRuleRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} + +type EnableRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` +} + +func (req *EnableRuleRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} + +type DisableRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` +} + +func (req *DisableRuleRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} + +type DeleteRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` +} + +func (req *DeleteRuleRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} diff --git a/bmp-console-api/types/request/OsRequest.go b/bmp-console-api/types/request/OsRequest.go new file mode 100644 index 0000000..5a8b8f6 --- /dev/null +++ b/bmp-console-api/types/request/OsRequest.go @@ -0,0 +1,19 @@ +package request + +type QueryOssRequest struct { + DeviceType string `json:"deviceType"` + Region string `json:"region"` + ImageType string `json:"imageType"` +} +type QueryOsPartitionsRequest struct { + DeviceType string `json:"deviceType"` + Region string `json:"region"` + ImageId string `json:"imageId"` +} +type QueryOsMountPointsRequest struct { + VolumeType string `json:"volumeType"` + Region string `json:"region"` +} +type QueryOOSFileSystemFormatsRequest struct { + Region string `json:"region"` +} diff --git a/bmp-console-api/types/request/PagingRequest.go b/bmp-console-api/types/request/PagingRequest.go new file mode 100644 index 0000000..1eb116e --- /dev/null +++ b/bmp-console-api/types/request/PagingRequest.go @@ -0,0 +1,6 @@ +package request + +type PagingRequest struct { + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` +} diff --git a/bmp-console-api/types/request/ParseFileRequest.go b/bmp-console-api/types/request/ParseFileRequest.go new file mode 100644 index 0000000..63542a9 --- /dev/null +++ b/bmp-console-api/types/request/ParseFileRequest.go @@ -0,0 +1,9 @@ +package request + +import "mime/multipart" + +type ParseFileRequest struct { + Region string `json:"region" valid:"Required"` + Base64 bool `json:"base64" valid:"Required"` + UserDataFile multipart.File `json:"userDataFile" valid:"Required"` +} diff --git a/bmp-console-api/types/request/PartitionRequest.go b/bmp-console-api/types/request/PartitionRequest.go new file mode 100644 index 0000000..a8ba1a5 --- /dev/null +++ b/bmp-console-api/types/request/PartitionRequest.go @@ -0,0 +1,13 @@ +package request + +import log "coding.jd.com/aidc-bmp/bmp_log" + +type QueryDefaultSystemPartitionRequest struct { + ImageID string `json:"imageId" validate:"required"` + DeviceTypeID string `json:"deviceTypeId" validate:"required"` +} + +func (req *QueryDefaultSystemPartitionRequest) Validate(logger *log.Logger) error { + + return validate(req, logger) +} diff --git a/bmp-console-api/types/request/ProjectRequest.go b/bmp-console-api/types/request/ProjectRequest.go new file mode 100644 index 0000000..e79f8d1 --- /dev/null +++ b/bmp-console-api/types/request/ProjectRequest.go @@ -0,0 +1,68 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" + "git.jd.com/cps-golang/ironic-common/exception" + "github.com/go-playground/validator/v10" +) + +type CreateProjectRequest struct { + ProjectID string `json:"projectId"` // 项目id + ProjectName string `json:"projectName"` //项目名称 + IsDefault int8 `json:"isDefault"` + IsSystem int8 `json:"isSystem"` + UserID string `json:"userId"` +} +type ModifyProjectRequest struct { + ProjectName string `json:"projectName"` // 项目名称 +} + +func (req *CreateProjectRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(req); err != nil { + logger.Warn("CreateProjectRequest.Validate error:", err.Error()) + panic(exception.CommonParamValid) + } +} + +type QueryProjectsRequest struct { + ProjectName string `json:"projectName"` + PagingRequest + ExportType string `json:"exportType"` + IsAll string `json:"isAll"` + OrderByCreatetime string `json:"orderByCreatetime"` + Owned string `json:"owned"` + //新增,可选,根据用户名获取项目列表 + OwnerName string `json:"ownerName"` + //新增,可选,根据被转移用户的用户名获取它拥有的项目列表 + SharerName string `json:"sharerName"` +} + +func (req *QueryProjectsRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(req); err != nil { + logger.Warn("QueryProjectsRequest.Validate error:", err.Error()) + panic(exception.CommonParamValid) + } +} + +type ShareProjectRequest struct { + // + OwnerName string `json:"ownerName"` + SharerName string `json:"sharerName"` + //新增, 如果部分分享,instance_id逗号分隔; 如果全部分享,传all + InstanceIDs string `json:"instanceIDs" validate:"required"` //all表示项目下的全部资源,否则instance_id逗号分隔传过来 +} + +type MoveProjectRequest struct { + // + OwnerName string `json:"ownerName"` + MoverName string `json:"moverName"` +} + +type MoveInstancesRequest struct { + // + OwnerName string `json:"ownerName"` + OwnerProjectID string `json:"ownerProjectID"` + MoverName string `json:"moverName"` + MoverProjectID string `json:"moverProjectID"` + InstanceIDs string `json:"instanceIDs"` +} diff --git a/bmp-console-api/types/request/RaidRequest.go b/bmp-console-api/types/request/RaidRequest.go new file mode 100644 index 0000000..b2b1c2a --- /dev/null +++ b/bmp-console-api/types/request/RaidRequest.go @@ -0,0 +1,13 @@ +package request + +import log "coding.jd.com/aidc-bmp/bmp_log" + +type QueryVolumeRaidsRequest struct { + DeviceTypeID string `json:"deviceTypeId" validate:"required"` + VolumeType string `json:"volumeType" validate:"required"` +} + +func (req *QueryVolumeRaidsRequest) Validate(logger *log.Logger) error { + + return validate(req, logger) +} diff --git a/bmp-console-api/types/request/UserRequest.go b/bmp-console-api/types/request/UserRequest.go new file mode 100644 index 0000000..2d4e43c --- /dev/null +++ b/bmp-console-api/types/request/UserRequest.go @@ -0,0 +1,37 @@ +package request + +// 【用户管理】【编辑用户信息】 +type ModifyUserInfoRequest struct { + UserName *string `json:"userName"` // 用户名,唯一 + Email *string `json:"email"` // 邮箱 + PhonePrefix *string `json:"phonePrefix"` // 国家地区码,如86 + PhoneNumber *string `json:"phoneNumber"` // 手机号 + DefaultProjectID *string `json:"defaultProjectId"` // 所属项目uuid + Language *string `json:"language"` // 语言(中文/English) + Timezone *string `json:"timezone"` // UTC或者本时区时间 + Description *string `json:"description"` // 描述 +} + +type UpdatePasswordRequest struct { + OldPassword string `json:"oldPassword"` // + Password string `json:"password"` // 密码 +} + +type QueryUserInfoRequest struct { +} + +type LoginRequest struct { + Username string `json:"username"` + Password string `json:"password"` +} + +type CheckUserConsoleAccessRequest struct { + CheckedUserId string `json:"checkedUserId"` +} + +type CheckUserConsoleAccessByNameRequest struct { + CheckedUserName string `json:"checkedUserName"` + ProjectID string `json:"projectId"` + // [move/share] + Operation string `json:"operation"` +} diff --git a/bmp-console-api/types/response/ApiKey.go b/bmp-console-api/types/response/ApiKey.go new file mode 100644 index 0000000..66d44bf --- /dev/null +++ b/bmp-console-api/types/response/ApiKey.go @@ -0,0 +1,27 @@ +package response + +type Apikey struct { + ID int `json:"id"` + ApikeyID string `json:"apiKeyId"` // 秘钥uuid + Name string `json:"name"` // 秘钥名称 + ReadOnly int8 `json:"readOnly"` //是否支持只读,read_only =1 的时候说明这个key是只读key,不能访问写方法。 + Token string `json:"token"` // 32位字符令牌 + Type string `json:"type"` // Token类型system/user + UserID string `json:"userId"` // 所属用户 + CreatedBy string `json:"createdBy"` // 创建者 + UpdatedBy string `json:"updatedBy"` // 更新者 + CreatedTime string `json:"createdTime"` // 创建时间戳 + UpdatedTime string `json:"updatedTime"` // 更新时间戳 +} +type ApikeyList struct { + Apikeys []*Apikey `json:"apikeys"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type ApikeyInfo struct { + Apikey *Apikey `json:"apikey"` +} +type ApikeyId struct { + ApikeyId string `json:"apikeyId"` +} diff --git a/bmp-console-api/types/response/AuditLogs.go b/bmp-console-api/types/response/AuditLogs.go new file mode 100644 index 0000000..e42ac55 --- /dev/null +++ b/bmp-console-api/types/response/AuditLogs.go @@ -0,0 +1,10 @@ +package response + +import sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + +type AuditLogsList struct { + AuditLogs []*sdkModels.AuditLog `json:"messages"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} diff --git a/bmp-console-api/types/response/CommonResponse.go b/bmp-console-api/types/response/CommonResponse.go new file mode 100644 index 0000000..74186ff --- /dev/null +++ b/bmp-console-api/types/response/CommonResponse.go @@ -0,0 +1,6 @@ +package response + +//新增加或者删除返给前端的true或者false +type CommonResponse struct { + Success bool `json:"success"` +} diff --git a/bmp-console-api/types/response/DeviceResponse.go b/bmp-console-api/types/response/DeviceResponse.go new file mode 100644 index 0000000..74facee --- /dev/null +++ b/bmp-console-api/types/response/DeviceResponse.go @@ -0,0 +1,6 @@ +package response + +type QueryDeviceStockResponse struct { + Success bool `json:"success"` + AvaliableCount int64 `json:"avaliableCount"` +} diff --git a/bmp-console-api/types/response/DeviceType.go b/bmp-console-api/types/response/DeviceType.go new file mode 100644 index 0000000..47b1a06 --- /dev/null +++ b/bmp-console-api/types/response/DeviceType.go @@ -0,0 +1,27 @@ +package response + +type DeviceType struct { + Name string `json:"name"` + DeviceTypeId string `json:"deviceTypeId"` + Cpu string `json:"cpu"` + Mem string `json:"mem"` + System string `json:"system"` + Data string `json:"data"` + Nic string `json:"nic"` + Gpu string `json:"gpu"` + // IsStockAvailable 是否有库存 + AvailableStock int64 `json:"availableStock"` + DeviceSeries string `json:"deviceSeries"` + DeviceSeriesName string `json:"deviceSeriesName"` + //boot模式 + BootMode string `json:"boot_mode"` + //是否需要做raid + IsNeedRaid string `json:"isNeedRaid"` +} + +type AvailableDeviceType struct { + Computer []DeviceType `json:"computer,omitempty"` + Storage []DeviceType `json:"storage,omitempty"` + Gpu []DeviceType `json:"gpu,omitempty"` + Other []DeviceType `json:"other,omitempty"` +} diff --git a/bmp-console-api/types/response/InstanceResponse.go b/bmp-console-api/types/response/InstanceResponse.go new file mode 100644 index 0000000..9ae251d --- /dev/null +++ b/bmp-console-api/types/response/InstanceResponse.go @@ -0,0 +1,52 @@ +package response + +import ( + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" +) + +type InstancesResponse struct { + PagingResponse + Instances []Instance `json:"instances"` +} + +//详情使用 +type InstanceInfo struct { + Instance Instance `json:"instance"` +} + +type CreateInstanceResponse struct { + InstanceIDs []string `json:"instanceIds"` +} + +//列表 +type Instance struct { + sdkModels.Instance + CpuInfo string `json:"cpuInfo"` + MemInfo string `json:"memInfo"` + SystemInfo string `json:"systemInfo"` + DataInfo string `json:"dataInfo"` + NicInfo string `json:"nicInfo"` + GpuInfo string `json:"gpuInfo"` + Volumes []*sdkModels.InstanceVolumeRaid `json:"volumes"` +} + +type ModifyInstanceResponse struct { + Name string `json:"name"` + Description string `json:"description"` +} + +//监控返回 +type InstanceMonitorDiskResponse struct { + InstanceId string `json:"instanceId"` + Disk []string `json:"disk"` +} + +type InstanceMonitorMountpointsResponse struct { + InstanceId string `json:"instanceId"` + Mountpoints []string `json:"mountpoints"` +} + +type InstanceMonitorNicsResponse struct { + InstanceId string `json:"instanceId"` + Nics []string `json:"nics"` +} diff --git a/bmp-console-api/types/response/KeypairResponse.go b/bmp-console-api/types/response/KeypairResponse.go new file mode 100644 index 0000000..4b042ba --- /dev/null +++ b/bmp-console-api/types/response/KeypairResponse.go @@ -0,0 +1,32 @@ +package response + +type KeyPairsResponse struct { + PagingResponse + Keypairs []KeyPair `json:"keypairs"` +} + +//给列表用的 +type KeyPair struct { + KeypairId string `json:"keypairId"` + Name string `json:"name"` + IsCheckDelete string `json:"isCheckDelete"` + PublicKey string `json:"publicKey"` + PrivateKey string `json:"privateKey"` + FingerPrint string `json:"fingerPrint"` + CreatedTime string `json:"createdTime"` + UpdatedTime string `json:"updatedTime"` +} + +//给详情用的 +type KeyPairInfo struct { + Keypair struct { + KeypairId string `json:"keypairId"` + Name string `json:"name"` + IsCheckDelete string `json:"isCheckDelete"` + PublicKey string `json:"publicKey"` + PrivateKey string `json:"privateKey"` + FingerPrint string `json:"fingerPrint"` + CreatedTime string `json:"createdTime"` + UpdatedTime string `json:"updatedTime"` + } `json:"keypair"` +} diff --git a/bmp-console-api/types/response/Message.go b/bmp-console-api/types/response/Message.go new file mode 100644 index 0000000..1904471 --- /dev/null +++ b/bmp-console-api/types/response/Message.go @@ -0,0 +1,25 @@ +package response + +import sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + +type MessageList struct { + Messages []*sdkModels.Message `json:"messages"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} + +type MessageStatistic struct { + TotalCount int64 `json:"totalCount"` + UnreadCount int64 `json:"unreadCount"` +} + +type HasUnreadMessage struct { + HasUnread bool `json:"hasUnread"` +} + +type MessageWithNextPrev struct { + Message *sdkModels.Message `json:"message"` + NextMessageId string `json:"nextMessageId"` + PrevMessageId string `json:"prevMessageId"` +} diff --git a/bmp-console-api/types/response/PagingResponse.go b/bmp-console-api/types/response/PagingResponse.go new file mode 100644 index 0000000..00ff93c --- /dev/null +++ b/bmp-console-api/types/response/PagingResponse.go @@ -0,0 +1,9 @@ +package response + +type PagingResponse struct { + PageNumber int64 `json:"pageNumber"` + + PageSize int64 `json:"pageSize"` + + TotalCount int64 `json:"totalCount"` +} diff --git a/bmp-console-api/types/response/Project.go b/bmp-console-api/types/response/Project.go new file mode 100644 index 0000000..1110369 --- /dev/null +++ b/bmp-console-api/types/response/Project.go @@ -0,0 +1,24 @@ +package response + +type Project struct { + ID int `json:"-"` + ProjectName string `json:"projectName"` // 角色名称,唯一 + ProjectID string `json:"projectId"` // 权限 + InstanceCount int `json:"instanceCount"` + CreatedBy string `json:"createdBy"` // 创建者 + UpdatedBy string `json:"updatedBy"` // 更新者 + CreatedTime string `json:"createdTime"` // 创建时间戳 + UpdatedTime string `json:"updatedTime"` // 更新时间戳 +} +type ProjectList struct { + Projects []*Project `json:"projects"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type ProjectInfo struct { + Project *Project `json:"project"` +} +type ProjectId struct { + ProjectId string `json:"projectId"` +} diff --git a/bmp-console-api/types/response/Raid.go b/bmp-console-api/types/response/Raid.go new file mode 100644 index 0000000..d9f6a53 --- /dev/null +++ b/bmp-console-api/types/response/Raid.go @@ -0,0 +1,32 @@ +package response + +type VolumeRaid struct { + // 卷uuid + VolumeID string `gorm:"column:volume_id" json:"volumeId"` + // 设备类型uuid + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` + // 卷名称 + VolumeName string `gorm:"column:volume_name" json:"volumeName"` + // 卷类型:系统卷,数据卷 + VolumeType string `gorm:"column:volume_type" json:"volumeType"` + // 硬盘类型(SSD,HDD) + DiskType string `gorm:"column:disk_type" json:"diskType"` + // 接口类型(SATA,SAS,NVME,不限制) + InterfaceType string `gorm:"column:interface_type" json:"interfaceType"` + // 单盘大小(最小容量) + VolumeSize float64 `gorm:"column:volume_size" json:"volumeSize"` + // 硬盘单位(GB,TB) + VolumeUnit string `gorm:"column:volume_unit" json:"volumeUnit"` + // 硬盘数量(最低块数) + VolumeAmount int `gorm:"column:volume_amount" json:"volumeAmount"` + //支持的raid模式 + Raids []*Raid `json:"raids"` +} + +type Raid struct { + RaidCan string `gorm:"column:raid_can" json:"raidCan"` // RAID配置: (RAID,NO RAID) + RaidID string `gorm:"column:raid_id" json:"raidId"` // RAID模式:RAID1,RIAD10等 + RaidName string `gorm:"column:raid_name" json:"raidName"` // RAID名称 + //容量大小描述 + Detail string `json:"detail"` +} diff --git a/bmp-console-api/types/response/TagsResponse.go b/bmp-console-api/types/response/TagsResponse.go new file mode 100644 index 0000000..dc1084e --- /dev/null +++ b/bmp-console-api/types/response/TagsResponse.go @@ -0,0 +1,3 @@ +package response + +type TagsResponse []string diff --git a/bmp-console-api/types/response/UserResponse.go b/bmp-console-api/types/response/UserResponse.go new file mode 100644 index 0000000..96fbf4f --- /dev/null +++ b/bmp-console-api/types/response/UserResponse.go @@ -0,0 +1,58 @@ +package response + +import ( + "bytes" +) + +type User struct { + ID int64 `json:"id"` + UserID string `json:"userId"` // 用户uuid + RoleID string `json:"roleId"` // 角色uuid + RoleName string `json:"roleName"` // 角色名称 + UserName string `json:"userName"` // 用户名,唯一 + Email string `json:"email"` // 邮箱 + PhonePrefix string `json:"phonePrefix"` // 国家地区码,如86 + PhoneNumber string `json:"phoneNumber"` // 手机号 + DefaultProjectID string `json:"defaultProjectId"` // 所属项目uuid + DefaultProjectName string `json:"DefaultProjectName"` // 默认所属项目名称 + Language string `json:"language"` // 语言(中文/English) + Timezone string `gorm:"column:timezone" json:"timezone"` // UTC或者本时区时间 + Password string `json:"password"` // 密码,sha256非对称加密后存储 + Description string `json:"description"` // 描述 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime string `gorm:"column:createdTime" json:"createdTime"` // 创建时间戳 + UpdatedTime string `gorm:"column:updatedTime" json:"updatedTime"` // 更新时间戳 + //DeletedTime string `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + //IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 + LicenseExist bool `json:"licenseExist"` //系统是否做过授权 + LicenseModels []string `json:"licenseModels"` //授权过的模块 +} + +type GetTimezoneListResponse struct { + TimeZones OrderedJsonDict `json:"timezones"` +} + +type OrderedJsonDict struct { + M map[string]string + Keys []string +} + +func (o OrderedJsonDict) MarshalJSON() ([]byte, error) { + buf := &bytes.Buffer{} + buf.WriteByte('{') + for i, k := range o.Keys { + if i != 0 { + buf.WriteByte(',') + } + buf.WriteByte('"') + buf.WriteString(k) + buf.WriteByte('"') + buf.WriteByte(':') + buf.WriteByte('"') + buf.Write([]byte(o.M[k])) + buf.WriteByte('"') + } + buf.WriteByte('}') + return buf.Bytes(), nil +} diff --git a/bmp-console-api/types/types.go b/bmp-console-api/types/types.go new file mode 100644 index 0000000..22187b6 --- /dev/null +++ b/bmp-console-api/types/types.go @@ -0,0 +1,28 @@ +package types + +import "time" + +const TimeFormat = "2006-01-02 15:04:05" + +type LocalTime time.Time + +func (t *LocalTime) UnmarshalJSON(data []byte) (err error) { + // 空值不进行解析 + if len(data) == 2 { + *t = LocalTime(time.Time{}) + return + } + + // 指定解析的格式 + now, err := time.Parse(`"`+TimeFormat+`"`, string(data)) + *t = LocalTime(now) + return +} + +func (t LocalTime) MarshalJSON() ([]byte, error) { + b := make([]byte, 0, len(TimeFormat)+2) + b = append(b, '"') + b = time.Time(t).AppendFormat(b, TimeFormat) + b = append(b, '"') + return b, nil +} diff --git a/bmp-console-api/util/array.go b/bmp-console-api/util/array.go new file mode 100644 index 0000000..11dcf6a --- /dev/null +++ b/bmp-console-api/util/array.go @@ -0,0 +1,101 @@ +package util + +import ( + "reflect" +) + +func GetValuesByField(objs []interface{}, field string) []string { + res := []string{} + for _, obj := range objs { + r := reflect.ValueOf(obj) + if reflect.TypeOf(obj).Kind() == reflect.Ptr { + r = reflect.Indirect(r) + } + f := r.FieldByName(field).String() + res = append(res, f) + } + return res +} + +func InArrayWithIndex(val interface{}, array interface{}) (exists bool, index int) { + exists = false + index = -1 + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + index = i + exists = true + return + } + } + } + return +} + +func InArray(val interface{}, array interface{}) (exists bool) { + exists = false + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + exists = true + return + } + } + } + return +} + +//求并集 +func UnionArray(slice1, slice2 []string) []string { + m := make(map[string]int) + for _, v := range slice1 { + m[v]++ + } + + for _, v := range slice2 { + times, _ := m[v] + if times == 0 { + slice1 = append(slice1, v) + } + } + return slice1 +} + +//求交集 +func IntersectArray(slice1, slice2 []string) []string { + m := make(map[string]int) + nn := make([]string, 0) + for _, v := range slice1 { + m[v]++ + } + + for _, v := range slice2 { + times, _ := m[v] + if times == 1 { + nn = append(nn, v) + } + } + return nn +} + +//求差集 slice1-并集 +func DifferenceArray(slice1, slice2 []string) []string { + m := make(map[string]int) + nn := make([]string, 0) + inter := IntersectArray(slice1, slice2) + for _, v := range inter { + m[v]++ + } + + for _, value := range slice1 { + times, _ := m[value] + if times == 0 { + nn = append(nn, value) + } + } + return nn +} diff --git a/bmp-console-api/util/array_test.go b/bmp-console-api/util/array_test.go new file mode 100644 index 0000000..68dc442 --- /dev/null +++ b/bmp-console-api/util/array_test.go @@ -0,0 +1,14 @@ +package util + +import( + "testing" +) + +func TestInArray(t *testing.T){ + v := InArray("aaa", []string{"aaa", "bbb"}) + if !v{ + t.Fatal("not in array") + }else{ + t.Log("in array") + } +} diff --git a/bmp-console-api/util/bool.go b/bmp-console-api/util/bool.go new file mode 100644 index 0000000..39da658 --- /dev/null +++ b/bmp-console-api/util/bool.go @@ -0,0 +1,12 @@ +package util + +func Bool2Int8(b bool) int8 { + if b { + return 1 + } + return 0 +} + +func Int82Bool(i int8) bool { + return i > 0 +} diff --git a/bmp-console-api/util/common.go b/bmp-console-api/util/common.go new file mode 100644 index 0000000..9fb6822 --- /dev/null +++ b/bmp-console-api/util/common.go @@ -0,0 +1,226 @@ +package util + +import ( + "encoding/json" + "fmt" + "math/rand" + "reflect" + "regexp" + "strconv" + "strings" + "time" + "unsafe" + + "github.com/gofrs/uuid" +) + +func GenUuid() string { + return uuid.Must(uuid.NewV4()).String() +} + +/** +map或者stuct转化为json字符串 +*/ +func ObjToJsonString(obj interface{}) string { + return MapToJson(InterfaceToMap(obj)) +} + +//任意类型转化成json,最常用 +func InterfaceToJson(obj interface{}) string { + dataType, err := json.Marshal(obj) + if err != nil { + return "" + } + dataString := string(dataType) + return dataString +} + +/** +Map对象转化为json string +*/ +func MapToJson(param map[string]interface{}) string { + dataType, _ := json.Marshal(param) + dataString := string(dataType) + return dataString +} +func InterfaceToMap(obj interface{}) map[string]interface{} { + + var data = make(map[string]interface{}) + if reflect.TypeOf(obj).Kind().String() == "map" { + d := obj.(map[string]interface{}) + for k, v := range d { + if vv := ReflectValue2string(reflect.ValueOf(v)); vv != "" { + data[k] = vv + } + } + } else if reflect.TypeOf(obj).Kind().String() == "struct" { + obj1 := reflect.TypeOf(obj) + obj2 := reflect.ValueOf(obj) + for i := 0; i < obj1.NumField(); i++ { + if vv := ReflectValue2string(obj2.Field(i)); vv != "" { + tagname := obj1.Field(i).Tag.Get("json") + if tagname != "" { + data[tagname] = vv + } else { + data[obj1.Field(i).Name] = vv + } + } + } + } else { + fmt.Printf("unknown obj, type is :%s, value is:%v\n", reflect.TypeOf(obj).String(), obj) + } + return data + +} + +//ReflectValue2string 默认值都设置为"",可能会误伤,后面改的方案:1,定义成wrapper类型,2,和上下游约定字段取值不要用默认值,比如int类型取值不要出现0,bool类型不要出现false +func ReflectValue2string(obj reflect.Value) string { + var v string + switch obj.Type().Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if vv := strconv.FormatInt(obj.Int(), 10); vv != "0" { //默认值问题 + v = vv + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + if vv := strconv.FormatUint(obj.Uint(), 10); vv != "0" { //默认值问题 + v = vv + } + case reflect.Float32, reflect.Float64: + if vv := fmt.Sprintf("%f", obj.Float()); vv != "0" { //默认值问题 + v = vv + } + case reflect.String: + v = obj.String() + case reflect.Bool: + if vv := strconv.FormatBool(obj.Bool()); vv != "false" { + v = vv + } + default: + v = "" + } + return v +} + +//将下划线转为驼峰 name_en => nameEn 一维,二维均可 +func DbToObj(obj map[string]interface{}) map[string]interface{} { + mapObj := make(map[string]interface{}) + for kk, vv := range obj { + if reflect.TypeOf(vv).Kind().String() == "slice" { + //fmt.Println(vv) + //sliceArr := []interface{} + for k1, v1 := range vv.([]interface{}) { + //fmt.Println(k1,v1) + mapObj1 := make(map[string]interface{}) + for k, v := range v1.(map[string]interface{}) { + sepStr := strings.Join(strings.Split(k, "_"), " ") + arr := strings.Split(strings.Title(sepStr), " ") + arr[0] = strings.ToLower(arr[0]) //hello World Haha + mapObj1[strings.Join(arr, "")] = v + } + vv.([]interface{})[k1] = mapObj1 + } + //fmt.Println(vv) + mapObj[kk] = vv + } else { + sepStr := strings.Join(strings.Split(kk, "_"), " ") + arr := strings.Split(strings.Title(sepStr), " ") + arr[0] = strings.ToLower(arr[0]) + mapObj[strings.Join(arr, "")] = vv + } + } + return mapObj +} + +//将一维map的驼峰 key转化为下划线 +func ObjToDb(param map[string]interface{}) map[string]interface{} { + //str := "userNameTom" //转为user_name_tom + //解析正则表达式,如果成功返回解释器 + reg := regexp.MustCompile(`[A-Z]`) + if reg == nil { //解释失败,返回nil + //fmt.Println("regexp err") + return nil + } + res := make(map[string]interface{}) + for key, value := range param { + //根据规则提取关键信息 + result := reg.FindAllStringSubmatch(key, -1) + for _, v := range result { + //fmt.Println(v) + key = strings.Replace(key, v[0], "_"+strings.ToLower(v[0]), 1) + } + res[key] = value + } + //fmt.Println("result1 = ", result,str) + return res +} + +func Int64ToInt(num int64) int { + int64_num := int64(num) + // 将 int64 转化为 int + int_num := *(*int)(unsafe.Pointer(&int64_num)) + return int_num +} + +//生成8-30位随机密码 +func GenerateRandPassWord() string { + a := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"} + b := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"} + d := "0123456789()`~!@#$%&*_-+=|{}[]:\";'<>,.?/" + c := strings.Split(d, "") + rand.Seed(time.Now().UnixNano()) + x := rand.Intn(len(a)) //生成0-数组长度之间的随机整数 + y := rand.Intn(len(b)) //生成0-数组长度之间的随机整数 + z := rand.Intn(len(c)) //生成0-数组长度之间的随机整数 + //fmt.Println(c) + s := make([]string, 0) + s = append(s, a[x]) + s = append(s, b[y]) + s = append(s, c[z]) + //以上生成了3个固定长度的字符串,这是必须要有的3个 + var arr = append(append(a, b...), c...) + + for i := 1; i <= 5; i++ { + rand := rand.Intn(len(arr)) //生成0-数组长度之间的随机整数 + s = append(s, arr[rand]) + } + //以上组成了至少8位的一个随机字符,下面生成9-30之间的随机长度的字符串 + length := rand.Intn(23) //生成0-22之间的数,前闭区间,后开区间,跟前面的8位拼接,组成8-30之间的随机数 + if length != 0 { + for i := 1; i <= length; i++ { + rand := rand.Intn(len(arr)) //生成0-数组长度之间的随机整数 + s = append(s, arr[rand]) + } + } + str := "" //下面将最终的数组打乱,生成新的字符串 + for i := 0; i < len(s); i++ { + rand := rand.Intn(len(s)) + str += s[rand] + } + return str +} + +/** +时间戳根据timezone解析成时间字符串 +*/ +func TimestampToString(timestamp int64, timezone string) string { + if timestamp == 0 { + return "" + } + t := time.Unix(timestamp, 0) + local, err := time.LoadLocation(timezone) + if err != nil { + fmt.Println("timezone error:", timezone, err.Error()) + return "" + } + ts := t.In(local).String() + fmt.Println(timestamp, timezone, ts) + tsItems := strings.Split(ts, " ") + if len(tsItems) >= 2 { + ts = tsItems[0] + " " + tsItems[1] + } + return ts + //if timestamp == 0 { + // return "" + //} + //return time.Unix(timestamp, 0).UTC().Format(baseLogic.DATE_UTC_FORMAT) +} diff --git a/bmp-console-api/util/coverage.out b/bmp-console-api/util/coverage.out new file mode 100644 index 0000000..a333b69 --- /dev/null +++ b/bmp-console-api/util/coverage.out @@ -0,0 +1,155 @@ +mode: set +git.jd.com/cps-golang/ironic-api/util/ipv4.go:43.58,45.21 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:48.2,50.62 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:64.2,64.43 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:45.21,47.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:50.62,52.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:52.8,55.17 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:58.3,58.30 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:55.17,57.4 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:58.30,60.4 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:60.9,60.38 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:60.38,62.4 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:67.75,68.70 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:71.2,80.8 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:68.70,70.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:83.42,85.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:87.40,90.26 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:93.2,93.16 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:90.26,92.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:96.40,98.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:100.40,102.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:104.48,107.30 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:111.2,111.12 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:107.30,110.3 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:114.50,117.28 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:121.2,121.18 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:117.28,120.3 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:124.53,126.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:128.49,130.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:132.53,134.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:136.76,137.18 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:140.2,141.29 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:144.2,148.28 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:156.2,156.21 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:137.18,139.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:141.29,143.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:148.28,149.35 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:152.3,154.50 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:149.35,151.4 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:160.32,165.2 4 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:167.44,170.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:172.43,174.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:176.40,179.2 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:181.41,184.2 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:186.43,187.20 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:190.2,191.18 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:194.2,195.19 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:202.2,202.27 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:187.20,189.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:191.18,193.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:195.19,196.25 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:199.3,200.25 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:196.25,197.9 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:206.44,207.21 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:210.2,211.18 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:214.2,215.19 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:222.2,222.16 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:207.21,209.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:211.18,213.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:215.19,216.25 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:219.3,220.25 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:216.25,217.9 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:225.55,227.40 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:235.2,235.24 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:228.22,229.37 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:230.21,231.22 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:232.10,233.36 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:238.48,240.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:242.41,245.22 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:248.2,249.29 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:257.2,257.77 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:245.22,246.102 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:249.29,250.59 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:250.59,251.103 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:252.9,254.4 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:30.61,54.2 14 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:57.30,60.2 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:63.57,64.16 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:64.16,66.44 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:72.52,76.2 3 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:79.50,95.16 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:98.2,111.3 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:95.16,97.3 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:115.36,132.16 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:137.2,152.16 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:156.2,158.12 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:165.2,166.11 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:132.16,134.3 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:152.16,154.3 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:158.12,159.23 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:159.23,163.4 1 0 +git.jd.com/cps-golang/ironic-api/util/page.go:9.65,11.23 2 0 +git.jd.com/cps-golang/ironic-api/util/page.go:16.2,16.22 1 0 +git.jd.com/cps-golang/ironic-api/util/page.go:11.23,13.3 1 0 +git.jd.com/cps-golang/ironic-api/util/page.go:13.8,15.3 1 0 +git.jd.com/cps-golang/ironic-api/util/page.go:19.59,26.2 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:16.69,18.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:21.2,21.41 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:18.16,20.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:25.55,30.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:32.61,34.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:37.2,40.9 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:34.16,36.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:44.58,46.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:49.2,49.49 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:46.16,48.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:52.47,55.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:59.2,60.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:65.2,65.57 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:55.16,57.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:60.16,62.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:68.56,70.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:74.2,74.42 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:70.16,72.3 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:7.66,9.27 2 0 +git.jd.com/cps-golang/ironic-api/util/array.go:17.2,17.12 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:9.27,11.48 2 0 +git.jd.com/cps-golang/ironic-api/util/array.go:14.3,15.23 2 0 +git.jd.com/cps-golang/ironic-api/util/array.go:11.48,13.4 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:20.84,23.38 3 0 +git.jd.com/cps-golang/ironic-api/util/array.go:34.2,34.8 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:24.21,26.32 2 0 +git.jd.com/cps-golang/ironic-api/util/array.go:26.32,27.62 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:27.62,31.5 3 0 +git.jd.com/cps-golang/ironic-api/util/array.go:37.64,39.38 2 1 +git.jd.com/cps-golang/ironic-api/util/array.go:49.2,49.8 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:40.21,42.32 2 1 +git.jd.com/cps-golang/ironic-api/util/array.go:42.32,43.62 1 1 +git.jd.com/cps-golang/ironic-api/util/array.go:43.62,46.5 2 1 +git.jd.com/cps-golang/ironic-api/util/bool.go:3.29,4.7 1 0 +git.jd.com/cps-golang/ironic-api/util/bool.go:7.2,7.10 1 0 +git.jd.com/cps-golang/ironic-api/util/bool.go:4.7,6.3 1 0 +git.jd.com/cps-golang/ironic-api/util/bool.go:10.29,12.2 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:10.89,13.16 2 0 +git.jd.com/cps-golang/ironic-api/util/http.go:16.2,18.16 3 0 +git.jd.com/cps-golang/ironic-api/util/http.go:21.2,23.27 2 0 +git.jd.com/cps-golang/ironic-api/util/http.go:26.2,28.16 3 0 +git.jd.com/cps-golang/ironic-api/util/http.go:31.2,32.16 2 0 +git.jd.com/cps-golang/ironic-api/util/http.go:35.2,35.23 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:13.16,15.3 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:18.16,20.3 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:23.27,25.3 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:28.16,30.3 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:32.16,34.3 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:4.83,6.25 2 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:24.2,24.15 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:6.25,7.12 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:7.12,9.4 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:9.9,11.4 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:13.8,13.32 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:13.32,15.42 2 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:18.3,18.12 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:15.42,17.4 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:18.12,20.4 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:20.9,22.4 1 0 diff --git a/bmp-console-api/util/encrypt.go b/bmp-console-api/util/encrypt.go new file mode 100644 index 0000000..aa8a0b0 --- /dev/null +++ b/bmp-console-api/util/encrypt.go @@ -0,0 +1,88 @@ +package util + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "crypto/md5" + "crypto/sha512" + "encoding/base64" + "encoding/hex" + "fmt" + "time" +) + +const ( + AES_KEY = "ABCDEFGHIJKLMNOP" + AES_IV = "0123456789ABCDEF" +) + +func GetMd5(str string, salts ...string) string { + h := md5.New() + h.Write([]byte(str)) + if len(salts) == 0 { + return hex.EncodeToString(h.Sum(nil)) + } else { + for _, salt := range salts { + h.Write([]byte(salt)) + } + return hex.EncodeToString(h.Sum(nil)) + } +} + +func Base64Encrypt(str []byte) string { + return base64.StdEncoding.EncodeToString(str) +} + +func Base64Decrypt(data string) ([]byte, error) { + return base64.StdEncoding.DecodeString(data) +} + +func GetSha512(str string) string { + return fmt.Sprintf("%x", sha512.Sum512([]byte(str))) +} + +func AesEncrypt(data []byte) ([]byte, error) { + aesBlockEncrypt, err := aes.NewCipher([]byte(AES_KEY)) + if err != nil { + println(err.Error()) + return nil, err + } + + content := PKCS7Padding2(data, aesBlockEncrypt.BlockSize()) + cipherBytes := make([]byte, len(content)) + aesEncrypt := cipher.NewCBCEncrypter(aesBlockEncrypt, []byte(AES_IV)) + aesEncrypt.CryptBlocks(cipherBytes, content) + return cipherBytes, nil +} + +func AesDecrypt(src []byte) (data []byte, err error) { + decrypted := make([]byte, len(src)) + var aesBlockDecrypt cipher.Block + aesBlockDecrypt, err = aes.NewCipher([]byte(AES_KEY)) + if err != nil { + println(err.Error()) + return nil, err + } + aesDecrypt := cipher.NewCBCDecrypter(aesBlockDecrypt, []byte(AES_IV)) + aesDecrypt.CryptBlocks(decrypted, src) + return PKCS7UnPadding2(decrypted), nil +} + +//PKCS7Padding 使用PKCS7进行填充 +func PKCS7Padding2(ciphertext []byte, blockSize int) []byte { + padding := blockSize - len(ciphertext)%blockSize + padText := bytes.Repeat([]byte{byte(padding)}, padding) + return append(ciphertext, padText...) +} + +//PKCS7UnPadding 解PKCS7填充 +func PKCS7UnPadding2(origData []byte) []byte { + length := len(origData) + unPadding := int(origData[length-1]) + if length < unPadding { + fmt.Println(time.Now().String(), "PKCS7UnPadding error") + return nil + } + return origData[:(length - unPadding)] +} diff --git a/bmp-console-api/util/error.go b/bmp-console-api/util/error.go new file mode 100644 index 0000000..c69828f --- /dev/null +++ b/bmp-console-api/util/error.go @@ -0,0 +1,55 @@ +package util + +import ( + "fmt" + "reflect" + + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-console-sdk/models" + apiRuntime "github.com/go-openapi/runtime" +) + +/* +sdk的原因,写了此GetOpenapiError用来解析openapi的返回err。err如果已知,为具体类型(比如GetUserListDefault)或者APIError类型(多了一层),如果未知解析失败,第二个参数为false + +type GetUserListDefault struct { + _statusCode int + TraceID string + Payload *GetUserListDefaultBody + } + + type GetUserListDefaultBody struct { + + // error + Error *models.ErrorResponse `json:"error,omitempty"` +} + +APIError{ + OperationName: opName, + Response: interface{}(GetUserListDefault), + Code: code, +} + +*/ + +func GetOpenapiError(err error) (*sdkModels.ErrorResponse, bool) { + + var v interface{} + e, ok := err.(*apiRuntime.APIError) + if ok { + v = e.Response + } else { + v = err + } + if reflect.ValueOf(v).MethodByName("GetPayload").IsValid() { + val := reflect.ValueOf(v).MethodByName("GetPayload").Call([]reflect.Value{}) + if reflect.Indirect(val[0]).FieldByName("Error").IsValid() { + err1, ok := reflect.Indirect(val[0]).FieldByName("Error").Interface().(*sdkModels.ErrorResponse) + if ok { + fmt.Println(err1.Code, err1.Message, err1.Status) + return err1, true + } + } + } + return nil, false + +} diff --git a/bmp-console-api/util/file.go b/bmp-console-api/util/file.go new file mode 100644 index 0000000..dabf23c --- /dev/null +++ b/bmp-console-api/util/file.go @@ -0,0 +1,54 @@ +package util + +import ( + "bufio" + "fmt" + "io" + "io/ioutil" + "mime/multipart" + "os" + "path/filepath" +) + +//GetBaseDir 获取项目根目录 +func GetBaseDir() (string, error) { + basePath, err := os.Executable() + if err != nil { + return "", err + } + res, err := filepath.EvalSymlinks(filepath.Dir(basePath)) + if err != nil { + return "", err + } + + return res, nil +} + +func SaveToLocal(localFileName string, uploadFile multipart.File) error { + fmt.Println(localFileName) + + f, err := os.OpenFile(localFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) + if err != nil { + return err + } + defer f.Close() + buf := bufio.NewWriter(f) + if _, err = io.Copy(f, uploadFile); err != nil { + return err + } + //将文件指针指回文件开头则可重新读取文件 + if _, err = uploadFile.Seek(0, io.SeekStart); err != nil { + return err + } + if err = buf.Flush(); err != nil { + return err + } + return nil +} +func ReadFileContent(filePth string) ([]byte, error) { + f, err := os.Open(filePth) + if err != nil { + return nil, err + } + return ioutil.ReadAll(f) +} diff --git a/bmp-console-api/util/http.go b/bmp-console-api/util/http.go new file mode 100644 index 0000000..7300012 --- /dev/null +++ b/bmp-console-api/util/http.go @@ -0,0 +1,229 @@ +package util + +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "net" + "net/http" + "reflect" + "strings" + "time" + + log "coding.jd.com/aidc-bmp/bmp_log" +) + +/* +func DoHttpGet(logger *log.Logger, url string, header map[string]string, data interface{}) ([]byte, error) { + + rpclogger := log.New("./logs/ironic-console-rpc.log") + defer rpclogger.Flush() + defer rpclogger.TimeEnd("cost") + rpclogger.SetStableFields([]string{"url", "method", "cost", "header", "request", "status", "statusCode", "response"}) + + rpclogger.Point("logid", logger.GetPoint("logid")) + rpclogger.Point("url", url) + rpclogger.Point("method", "GET") + rpclogger.Point("header", header) + rpclogger.TimeStart("cost") + + var bytesData []byte + if reflect.TypeOf(data).Kind() == reflect.String { + bytesData = []byte(data.(string)) + } else { + var err error + bytesData, err = json.Marshal(data) + if err != nil { + return nil, err + } + } + rpclogger.Point("request", string(bytesData)) + reader := bytes.NewReader(bytesData) + + request, err := http.NewRequest("GET", url, reader) + if err != nil { + return nil, err + } + q := request.URL.Query() + + param := InterfaceToMap(data) + fmt.Println(data, param) + for key, value := range param { + q.Add(key, value) + } + request.URL.RawQuery = q.Encode() + fmt.Println("get请求的最终url:", request.URL.String()) + defer request.Body.Close() + //务必带 X-Jdcloud-Requestid + for k, v := range header { + //fmt.Println(k,v) + request.Header.Set(k, v) + } + //if header["host"] != "" { + request.Host = header["Host"] + //} + client := http.Client{} + resp, err := client.Do(request) + if err != nil { + return nil, err + } + rpclogger.Point("status", resp.Status) + rpclogger.Point("statusCode", resp.StatusCode) + respBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + fmt.Println("状态码:", resp.Status, resp.StatusCode) + rpclogger.Point("response", string(respBytes)) + return respBytes, nil +} + +func DoHttpPost(logger *log.Logger, url string, header map[string]string, data interface{}) ([]byte, error) { + + rpclogger := log.New("./logs/ironic-console-rpc.log") + defer rpclogger.Flush() + defer rpclogger.TimeEnd("cost") + rpclogger.SetStableFields([]string{"url", "method", "cost", "header", "request", "status", "statusCode", "response"}) + + rpclogger.Point("logid", logger.GetPoint("logid").(string)) + rpclogger.Point("url", url) + rpclogger.Point("method", "POST") + rpclogger.Point("header", header) + rpclogger.TimeStart("cost") + + var bytesData []byte + if reflect.TypeOf(data).Kind() == reflect.String { + bytesData = []byte(data.(string)) + } else { + var err error + bytesData, err = json.Marshal(data) + if err != nil { + return nil, err + } + } + rpclogger.Point("request", string(bytesData)) + reader := bytes.NewReader(bytesData) + request, err := http.NewRequest("POST", url, reader) + if err != nil { + return nil, err + } + defer request.Body.Close() + //务必带 X-Jdcloud-Request-Id + for k, v := range header { + request.Header.Set(k, v) + } + client := http.Client{} + resp, err := client.Do(request) + if err != nil { + return nil, err + } + fmt.Println("状态码:", resp.Status, resp.StatusCode) + rpclogger.Point("status", resp.Status) + rpclogger.Point("statusCode", resp.StatusCode) + //if resp.StatusCode != 200 { + // fmt.Println("ironic-api接口异常") + // return nil,err + //} + respBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + rpclogger.Point("response", string(respBytes)) + return respBytes, nil +} +*/ +func DoHttp(logger *log.Logger, url string, header map[string]string, data interface{}, method string) ([]byte, error) { + + rpclogger := log.New("./log/ironic-console-rpc.log") + defer rpclogger.Flush() + defer rpclogger.TimeEnd("cost") + rpclogger.SetStableFields([]string{"url", "method", "cost", "header", "request", "status", "statusCode", "response"}) + + rpclogger.Point("logid", logger.GetPoint("logid")) + rpclogger.Point("url", url) + rpclogger.Point("method", method) + rpclogger.Point("header", header) + rpclogger.TimeStart("cost") + + var bytesData []byte + if data != nil { + fmt.Println("当前参数类型", reflect.TypeOf(data).Kind()) + if reflect.TypeOf(data).Kind() == reflect.String { + bytesData = []byte(data.(string)) + } else { + var err error + bytesData, err = json.Marshal(data) + if err != nil { + return nil, err + } + } + } + + // byteHeader, _ := json.Marshal(header) + // fmt.Println("请求header", string(byteHeader)) + fmt.Println("ironicapi请求url", url) + fmt.Println("ironicapi请求method", method) + fmt.Println("ironicapi请求body", string(bytesData)) + rpclogger.Point("request", string(bytesData)) + reader := bytes.NewReader(bytesData) + + request, err := http.NewRequest(method, url, reader) + if err != nil { + return nil, err + } + if method == "GET" && data != nil { + param := InterfaceToMap(data) + q := request.URL.Query() + for key, value := range param { + q.Add(key, value.(string)) + } + request.URL.RawQuery = q.Encode() + } + fmt.Println("ironicapi请求url:", request.URL.String()) + defer request.Body.Close() + //务必带 X-Jdcloud-Request-Id + for k, v := range header { + //fmt.Println(k,v) + request.Header.Set(k, v) + } + + fmt.Println("dohttp request header:", request.Header) + + // request.Header.Set("x-jdcloud-erp", "ZXJw") + if header["Host"] != "" { + request.Host = header["Host"] + } + client := http.Client{} + resp, err := client.Do(request) + if err != nil { + return nil, err + } + rpclogger.Point("status", resp.Status) + rpclogger.Point("statusCode", resp.StatusCode) + respBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + // fmt.Println("状态码:", resp.Status, resp.StatusCode) + fmt.Println("ironicapi响应:", string(respBytes)) + rpclogger.Point("response", string(respBytes)) + return respBytes, nil +} + +func CheckIpPort(ipPort string) error { + ipPort = strings.TrimLeft(ipPort, "http://") + ipPort = strings.TrimLeft(ipPort, "https://") + conn, err := net.DialTimeout("tcp", ipPort, 3*time.Second) + if err != nil { + return err + } else { + if conn != nil { + conn.Close() + return nil + } else { + return fmt.Errorf("%s dial failed", ipPort) + } + } +} diff --git a/bmp-console-api/util/ipv4.go b/bmp-console-api/util/ipv4.go new file mode 100644 index 0000000..b188cb5 --- /dev/null +++ b/bmp-console-api/util/ipv4.go @@ -0,0 +1,166 @@ +package util + +import ( + "encoding/hex" + "fmt" + "net" + "strconv" + "strings" + + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +const ( + IP_NETWORK_SPLIT = "/" + IP_ADDRESS_REGEX = `^(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))$` + IP_WIDTH int32 = 32 + IP_MAX_VALUE int64 = 0xffffffff + IP_MIN_VALUE int64 = 0 +) + +func Gateway(cidr string) string { + ip, _, err := net.ParseCIDR(cidr) + if err != nil { + panic(err.Error()) + } + IncrIP(ip) + return ip.String() +} + +func Mask(mask net.IPMask) string { + m, _ := hex.DecodeString(mask.String()) + return net.IP([]byte(m)).String() +} + +// IP地址自增 +func IncrIP(ip net.IP) { + for i := len(ip) - 1; i >= 0; i-- { + ip[i]++ + if ip[i] > 0 { + break + } + } +} + +// IP地址自减 +func DecrIP(ip net.IP) { + length := len(ip) + for i := length - 1; i >= 0; i-- { + ip[length-1]-- + if ip[length-1] < 0xFF { + break + } + for j := 1; j < length; j++ { + ip[length-j-1]-- + if ip[length-j-1] < 0xFF { + return + } + } + } +} + +// RandomMacAddress 生成随机mac地址 +func RandomMacAddress() string { + + uuid := commonUtil.GetRandString("", 12, false, false, true) + first_part := uuid[0:4] + first_part_num, _ := strconv.ParseInt("0x"+first_part, 16, 32) + first_hex_string := strconv.FormatInt(first_part_num&0xfeff, 16) + part := []string{fmt.Sprintf("%04x", first_hex_string), uuid[4:8], uuid[8:12]} + return strings.Join(part, "-") +} + +/* + * 列举一个CIDR段中的所有IP列表 + */ +func GetAllHostIPs(cidr string) []string { + //不过不包含掩码位,就当做32位IP对待 + if !strings.Contains(cidr, "/") { + return []string{cidr} + } + ip := strings.Split(cidr, "/")[0] + ipSegs := strings.Split(ip, ".") + maskLen, _ := strconv.Atoi(strings.Split(cidr, "/")[1]) + if maskLen <= 0 { + return []string{} + } + if maskLen == 32 { + return []string{ip} + } + seg1MinIp, seg1MaxIp := getIpSeg1Range(ipSegs[0], maskLen) + seg2MinIp, seg2MaxIp := getIpSeg2Range(ipSegs[1], maskLen) + seg3MinIp, seg3MaxIp := getIpSeg3Range(ipSegs[2], maskLen) + seg4MinIp, seg4MaxIp := getIpSeg4Range(ipSegs[3], maskLen) + + var ipList []string + for seg1Ip := seg1MinIp; seg1Ip <= seg1MaxIp; seg1Ip++ { + for seg2Ip := seg2MinIp; seg2Ip <= seg2MaxIp; seg2Ip++ { + for seg3Ip := seg3MinIp; seg3Ip <= seg3MaxIp; seg3Ip++ { + for seg4Ip := seg4MinIp; seg4Ip <= seg4MaxIp; seg4Ip++ { + oneIp := fmt.Sprintf("%d.%d.%d.%d", seg1Ip, seg2Ip, seg3Ip, seg4Ip) + ipList = append(ipList, oneIp) + } + } + } + } + return ipList +} + +/* + * 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)3部分的最小值和最大值 + */ +func getIpSeg1Range(ipSeg string, maskLen int) (int, int) { + //如果掩码位>16,此时说明掩码只会影响到seg2,seg3,seg4,seg1直接返回 + if maskLen > 8 { + segIp, _ := strconv.Atoi(ipSeg) + return segIp, segIp + } + ipSegNum, _ := strconv.Atoi(ipSeg) + return getIpSegRange(uint8(ipSegNum), uint8(8-maskLen)) +} + +/* +* 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)3部分的最小值和最大值 + */ +func getIpSeg2Range(ipSeg string, maskLen int) (int, int) { + //如果掩码位>16,此时说明掩码只会影响到seg3,seg4,seg2直接返回 + if maskLen > 16 { + segIp, _ := strconv.Atoi(ipSeg) + return segIp, segIp + } + ipSegNum, _ := strconv.Atoi(ipSeg) + return getIpSegRange(uint8(ipSegNum), uint8(16-maskLen)) +} + +/* +* 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)3部分的最小值和最大值 + */ +func getIpSeg3Range(ipSeg string, maskLen int) (int, int) { + //如果掩码位>24,此时说明掩码只会影响到seg4,seg3直接返回 + if maskLen > 24 { + segIp, _ := strconv.Atoi(ipSeg) + return segIp, segIp + } + ipSegNum, _ := strconv.Atoi(ipSeg) + return getIpSegRange(uint8(ipSegNum), uint8(24-maskLen)) +} + +/* + * 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)4部分的最小值和最大值 + */ +func getIpSeg4Range(ipSeg string, maskLen int) (int, int) { + ipSegNum, _ := strconv.Atoi(ipSeg) + segMinIp, segMaxIp := getIpSegRange(uint8(ipSegNum), uint8(32-maskLen)) + if segMinIp == 0 { + segMinIp = segMinIp + 1 //最后一段的IP不能是0,否则就会变为网段 + } + return segMinIp, segMaxIp +} + +func getIpSegRange(userSegIp, offset uint8) (int, int) { + var ipSegMax uint8 = 255 + netSegIp := ipSegMax << offset + segMinIp := netSegIp & userSegIp + segMaxIp := userSegIp&(255< target_len { //裁剪 + if ahead { //保留左边 + return string(r[:target_len]) + } else { //保留右边 + return string(r[len(r)-target_len:]) + } + + } else if len(r) < target_len { //填充 + pads := []rune{} + for i := 0; i < target_len-len(r); i++ { + pads = append(pads, padding_char) + } + if ahead { //左向填充 + return string(append(pads, r...)) + } else { //右向填充 + return string(append(r, pads...)) + } + } + return source + +} + +func String2int8(v string) int8 { + i, err := strconv.ParseInt(v, 10, 32) + if err != nil { + panic(fmt.Sprintf("String2int8 error:%s", err.Error())) + } + return int8(i) +} + +func String2int(v string) int { + i, err := strconv.ParseInt(v, 10, 32) + if err != nil { + panic(fmt.Sprintf("String2int8 error:%s", err.Error())) + } + return int(i) +} + +func String2Bool(v string) bool { + if strings.ToLower(v) == "true" { + return true + } + return false +} + +//GetRandString 借鉴RandomStringUtils.random包生成随机字符串 +// length 随机字符串的长度(不包括前缀) +// uletter 随机字符串是否包含大写字母字符 +// dletter 随机字符串是否包含小写字母字符 +// number 随机字符串是否包含数字字符 +func GetRandString(prefix string, length int32, uletter, dletter, number bool) string { + rand.Seed(time.Now().UnixNano()) + uletters := []rune("ABCDEFGHIGKLMNOPQRSTUVWXYZ") + dletters := []rune("abcdefghijklmnopqrstuvwxyz") + numbers := []rune("0123456789") + source := []rune{} + if uletter { + source = append(source, uletters...) + } + if dletter { + source = append(source, dletters...) + } + if number { + source = append(source, numbers...) + } + if len(source) == 0 { + return "atLeastContainsLetterOrNumber" + } + b := make([]rune, length) + for i := range b { + b[i] = source[rand.Intn(len(source))] + } + return prefix + string(b) +} + +// 跟现有环境一致,格式:aafc4d1b-f696-4ec2-924f-6fd012aa8345 +func GenerateRandUuid() string { + s := GetRandString("", 32, false, true, true) + runes := []rune(s) + return string(runes[0:8]) + "-" + string(runes[8:12]) + "-" + string(runes[12:16]) + "-" + string(runes[16:20]) + "-" + string(runes[20:32]) +} diff --git a/bmp-console-api/util/time.go b/bmp-console-api/util/time.go new file mode 100644 index 0000000..679f809 --- /dev/null +++ b/bmp-console-api/util/time.go @@ -0,0 +1,104 @@ +package util + +import ( + "time" +) + +//ParseTimeToDate 解析time格式为date格式 +func ParseTimeToDate(str, timeLayout, dateLayout string) (time.Time, error) { + var res time.Time + + t, err := time.Parse(timeLayout, str) + if err != nil { + return res, err + } + res, err = time.Parse(dateLayout, t.Format(dateLayout)) + if err != nil { + return res, err + } + return res, nil +} + +//GetFirstDayOfMonth 获取某个月份第一天 +func GetFirstDayOfMonth(month, monthLayout string) (time.Time, error) { + var res time.Time + + t, err := time.Parse(monthLayout, month) + if err != nil { + return res, err + } + return t.AddDate(0, 0, -t.Day()+1), nil +} + +//GetLastDayOfMonth 获取某个月份最后一天 +func GetLastDayOfMonth(month, monthLayout string) (time.Time, error) { + var res time.Time + + t, err := time.Parse(monthLayout, month) + if err != nil { + return res, err + } + return t.AddDate(0, 1, -t.Day()), nil +} + +//GetDateSubDays 获取某两个时间的差值 +func GetDateSubDays(dateStart, dateEnd time.Time) int { + return int(dateEnd.Sub(dateStart).Hours()/24) + 1 +} + +//GetMonthDays 获取某个月份总天数 +func GetMonthDays(month, monthLayout string) (int, error) { + dateStart, err := GetFirstDayOfMonth(month, monthLayout) + if err != nil { + return 0, err + } + dateEnd, err := GetLastDayOfMonth(month, monthLayout) + if err != nil { + return 0, err + } + + return GetDateSubDays(dateStart, dateEnd), nil +} + +//GetMonthCount 获取某两个月份之间的个数,包含这2个月份 +//ex: 2021-07和2021-09之间包含3个月 +func GetMonthCount(startMonth, endMonth, monthLayout string) (int, error) { + startMonthTime, err := time.Parse(monthLayout, startMonth) + if err != nil { + return 0, err + } + endMonthTime, err := time.Parse(monthLayout, endMonth) + if err != nil { + return 0, err + } + + startYear := startMonthTime.Year() + endYear := endMonthTime.Year() + startM := int(startMonthTime.Month()) + endM := int(endMonthTime.Month()) + yearInterval := endYear - startYear + + if endM <= startM { + yearInterval-- + } + + monthInterval := (endM + 12 - startM) % 12 + return yearInterval*12 + monthInterval + 1, nil +} + +//GetMonthSub 获取某两个月份之间的月份,包含这2个月份 +func GetMonthSub(startMonth, endMonth, monthLayout string) ([]string, error) { + months, err := GetMonthCount(startMonth, endMonth, monthLayout) + if err != nil { + return nil, err + } + startMonthTime, err := time.Parse(monthLayout, startMonth) + if err != nil { + return nil, err + } + monthArr := make([]string, 0) + for i := 0; i < months; i++ { + monthArr = append(monthArr, startMonthTime.AddDate(0, i, 0).Format(monthLayout)) + } + return monthArr, nil +} diff --git a/bmp-console-web/.env b/bmp-console-web/.env new file mode 100644 index 0000000..55b5d36 --- /dev/null +++ b/bmp-console-web/.env @@ -0,0 +1,2 @@ +NODE_ENV="development" +VUE_APP_ENV="dev" \ No newline at end of file diff --git a/bmp-console-web/.env.dev b/bmp-console-web/.env.dev new file mode 100644 index 0000000..685b073 --- /dev/null +++ b/bmp-console-web/.env.dev @@ -0,0 +1,2 @@ +NODE_ENV="production" +VUE_APP_ENV="dev" \ No newline at end of file diff --git a/bmp-console-web/.env.pre b/bmp-console-web/.env.pre new file mode 100644 index 0000000..8a522ef --- /dev/null +++ b/bmp-console-web/.env.pre @@ -0,0 +1,2 @@ +NODE_ENV="production" +VUE_APP_ENV="pre" \ No newline at end of file diff --git a/bmp-console-web/.env.prod b/bmp-console-web/.env.prod new file mode 100644 index 0000000..78d1602 --- /dev/null +++ b/bmp-console-web/.env.prod @@ -0,0 +1,2 @@ +NODE_ENV="production" +VUE_APP_ENV="prod" \ No newline at end of file diff --git a/bmp-console-web/.env.test b/bmp-console-web/.env.test new file mode 100644 index 0000000..71a96fc --- /dev/null +++ b/bmp-console-web/.env.test @@ -0,0 +1,2 @@ +NODE_ENV="production" +VUE_APP_ENV="test" \ No newline at end of file diff --git a/bmp-console-web/.eslintrc.js b/bmp-console-web/.eslintrc.js new file mode 100644 index 0000000..1491481 --- /dev/null +++ b/bmp-console-web/.eslintrc.js @@ -0,0 +1,50 @@ +module.exports = { + root: true, + env: { + 'node': true + }, + // eslint关闭 + rules: { + 'no-unused-vars': 'off', + 'linebreak-style': ['error', 'windows'], + 'no-console': 'off', // 禁用console + 'no-debugger': 'off', // 禁用debugger + 'space-before-function-paren': 'off', // 强制在function的左括号之前使用一致的空格 + 'no-underscore-dangle': 'off', // 禁止标识符中有悬空下划线 + 'no-param-reassign': 'off', // 禁止对函数参数再赋值 + 'func-names': 'off', // 禁止命名的 function 表达式 + 'no-bitwise': 'off', // 禁止使用按位操作符 + 'prefer-rest-params': 'off', // 建议使用剩余参数代替 arguments + 'no-trailing-spaces': 'off', // 禁用行尾空格 + 'comma-dangle': 'off', // 禁止使用拖尾逗号 + 'quote-props': 'off', // 要求对象字面量属性名称使用引号 + 'consistent-return': 'off', // 要求return语句要么总是指定返回的值,要么不指定 + 'no-plusplus': 'off', // 禁用一元操作符++和-- + 'prefer-spread': 'warn', // 要求使用扩展运算符而非.apply() + 'semi': 'warn', // 要求使用分号代替ASI + 'indent': ['warn', 'tab'], // 强制使用一致的缩进 + 'no-tabs': 'warn', // 禁用tab风格字符 + 'no-unused-vars': 'warn', // 禁止出现未使用过的变量 + 'quotes': 'warn', // 强制使用一致的反勾号、双引号或单引号 + 'no-void': 'off', // 禁止使用void操作符 + 'no-nested-ternary': 'off', // 禁止使用嵌套的三元表达式 + 'import/no-unresolved': 'off', + 'no-return-assign': 'warn', // 禁止在return语句中使用赋值语句 + 'linebreak-style': 'off', // 强制使用一致的换行符风格 + 'prefer-destructuring': 'off', // 优先使用数组和对象解构 + 'no-restricted-syntax': 'warn', // 禁止使用特定的语法 + 'arrow-parens': 'off', // 要求箭头函数的参数使用圆括号 + 'import/extensions': 'off', + 'import/named': 'off', + 'import/no-deprecated': 'off', + 'import/no-extraneous-dependencies': 'off', + 'fecs-no-require': 'off', + 'fecs-valid-jsdoc': 'off' + }, + parserOptions: { + 'parser': 'babel-eslint' + }, + extends: [ + 'plugin:@typescript-eslint/no-unused-vars' + ] +}; diff --git a/bmp-console-web/.gitignore b/bmp-console-web/.gitignore new file mode 100644 index 0000000..837579e --- /dev/null +++ b/bmp-console-web/.gitignore @@ -0,0 +1,23 @@ +.DS_Store +node_modules +/dist +package-lock.json + +# local env files +.env.local +.env.*.local + +# Log files +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* + +# Editor directories and files +.idea +.vscode +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/bmp-console-web/.gitmodules b/bmp-console-web/.gitmodules new file mode 100644 index 0000000..506f24c --- /dev/null +++ b/bmp-console-web/.gitmodules @@ -0,0 +1,3 @@ +[submodule "bmp-deploy"] + path = bmp-deploy + url = git@coding.jd.com:aidc-bmp/bmp-deploy.git diff --git a/bmp-console-web/README.md b/bmp-console-web/README.md new file mode 100644 index 0000000..5b2c51b --- /dev/null +++ b/bmp-console-web/README.md @@ -0,0 +1,34 @@ +# bmp-console-web-私有化物理机管理平台项目 + +English | [简体中文](README.zh-CN.md) +## Introduction +* This project is built based on @vue/cli 4 (vue3 + ts + pinia) + +## Introduction to directory and file functions +* The config directory stores webpack related configurations +* The public directory is created by @vue/cli by default and stores some static resources that do not need to be packaged by webpack +* public/robots.txt- is a plain text file that can declare the parts of the website that you do not want to be accessed by search engines, or specify that search engines only include specified content +* The src directory stores project development files +* App.vue root component +* The api directory stores interface-related configurations and calling methods based on routing +* The common directory stores public methods and regular expressions +* The components directory stores common components for pages +* The src/config directory stores third-party class libraries and plug-in references other than the vue family bucket, currently including element-plus, filters, vue-i18n, mitt, and pinia references +* The reuqest directory stores axios secondary encapsulation +* The router directory stores routing configuration files +* The store directory stores the state management library pinia +* main.ts project entry ts +* assets public resource association: pictures, styles, fonts +* views directory stores page components divided by routes +* .env file configures global environment variables +* .eslintrsc file configures eslint detection code related rules +* .gitignore file specifies ignore rules +* shims-vue.d.ts This file is an adaptation definition file for typescript +* package.json configuration file +* tsconfig.json ts file configuration +* babel.config.js configures babel to parse and convert js code related rules, parse es6 optional chain syntax +* vue.config.js configures webpack, cross-domain related + +## Local development +* npm run dev, the interface goes to the test environment interface, see the proxy configuration in dev.server.js for the specific url +* Or npm i —-legacy-peer-deps to avoid dependency version issues, npm run dev [use this command to specify the node version as 16.19.0, no need to switch] \ No newline at end of file diff --git a/bmp-console-web/README.zh-CN.md b/bmp-console-web/README.zh-CN.md new file mode 100644 index 0000000..2f33ce5 --- /dev/null +++ b/bmp-console-web/README.zh-CN.md @@ -0,0 +1,35 @@ +# bmp-console-web-私有化物理机管理平台项目 + +[English](README.md) | 简体中文 + +## 简介 +* 本工程基于@vue/cli 4搭建而成(vue3 + ts + pinia) + +## 目录及文件功能简介 +* config目录存放webpack相关配置 +* public目录由@vue/cli默认创建生成,存放一些不需要经过webpack打包处理的静态资源 +* public/robots.txt-是一个纯文本文件,可以声明该网站中不想被搜索引擎访问的部分,或者指定搜索引擎只收录指定的内容 +* src目录存放项目开发文件 +* App.vue根组件 +* api目录存放根据路由划分接口相关配置及调用方法 +* common目录存放公共方法、正则表达式 +* components目录存放页面通用组件 +* src/config目录存放除vue全家桶以外的第三方类库及插件引用,当前包含element-plus、filters、vue-i18n、mitt、pinia的引用 +* reuqest目录存放axios二次封装 +* router目录存放路由配置文件 +* store目录存放状态管理库pinia +* main.ts工程入口ts +* assets公共资源关联:图片、样式、字体 +* views目录存储根据路由划分的页面组件 +* .env文件配置全局环境变量 +* .eslintrsc文件配置eslint检测代码相关规则 +* .gitignore文件 指定忽略规则 +* shims-vue.d.ts 该文件是为了 typescript 做的适配定义文件 +* package.json 配置文件 +* tsconfig.json ts文件的一些配置 +* babel.config.js配置babel解析转换js代码相关规则、解析es6可选链式语法 +* vue.config.js配置webpack、跨域相关 + +## 本地开发 +* npm run dev, 接口走测试环境的接口,具体url见dev.server.js中的代理配置 +* 或者npm i —-legacy-peer-deps 避免各依赖版本问题,npm run dev[用这个命令node版本指定为16.19.0即可,不用切换] diff --git a/bmp-console-web/babel.config.js b/bmp-console-web/babel.config.js new file mode 100644 index 0000000..ecedfee --- /dev/null +++ b/bmp-console-web/babel.config.js @@ -0,0 +1,9 @@ +module.exports = { + presets: [ + '@vue/cli-plugin-babel/preset' + ], + plugins: [ + // 解析es6可选链式语法 + ['@babel/plugin-proposal-optional-chaining'] + ] +} diff --git a/bmp-console-web/bmp-console-web.Dockerfile b/bmp-console-web/bmp-console-web.Dockerfile new file mode 100644 index 0000000..1b2d8c1 --- /dev/null +++ b/bmp-console-web/bmp-console-web.Dockerfile @@ -0,0 +1,8 @@ +FROM node:16.19-alpine3.16 AS builder +WORKDIR /usr/src/bmp-console-web +COPY . . +RUN npm config set registry https://registry.npmmirror.com && npm install --legacy-peer-deps && npm run build-pre + +FROM nginx:1.22-alpine +WORKDIR /home/bmp/bmp-console-web +COPY --from=builder /usr/src/bmp-console-web/dist . diff --git a/bmp-console-web/config/devServer.js b/bmp-console-web/config/devServer.js new file mode 100644 index 0000000..bd2df59 --- /dev/null +++ b/bmp-console-web/config/devServer.js @@ -0,0 +1,23 @@ +module.exports = { + devServer: { + open: true, // 是否直接打开浏览器 + host: 'localhost', // 本地服务器 + port: 8089, // 端口号 + proxy: { // 跨域 + '/console-web': { + target: 'http://bmp-console.bmp.local', + changeOrigin: true, // 是否需要跨域 + }, + '/oob-alert': { + target:'http://bmp-oob-alert.bmp.local', + changeOrigin: true, // 是否需要跨域 + pathRewrite: { + '^/oob-alert': '' //需要rewrite的, + } + } + }, + sockHost: 'localhost', + disableHostCheck: true, + progress: false + } +}; diff --git a/bmp-console-web/config/noParse.js b/bmp-console-web/config/noParse.js new file mode 100644 index 0000000..48df4f0 --- /dev/null +++ b/bmp-console-web/config/noParse.js @@ -0,0 +1,5 @@ +module.exports = (config) => { + // 减少不必要的解析,让 Webpack 忽略对部分没采用模块化的文件的递归解析处理,这样做的好处是能提高构建性能 + config.module.noParse = '/^(vue|vue-router|vue-i18n)$/'; + return config +}; diff --git a/bmp-console-web/config/runtimeChunk.js b/bmp-console-web/config/runtimeChunk.js new file mode 100644 index 0000000..8bb2e65 --- /dev/null +++ b/bmp-console-web/config/runtimeChunk.js @@ -0,0 +1,5 @@ +// 避免文件的频繁变更导致浏览器缓存失效,更好的利用缓存。提升用户体验 +module.exports = (config) => { + config.optimization.runtimeChunk = true; + return config; +}; diff --git a/bmp-console-web/config/setAlias.js b/bmp-console-web/config/setAlias.js new file mode 100644 index 0000000..867a590 --- /dev/null +++ b/bmp-console-web/config/setAlias.js @@ -0,0 +1,20 @@ +const path = require('path'); +const resolve = (dir) => path.join(__dirname, '..', dir); + +// 设置alias别名、配置简化路径 +module.exports = (config) => { + config.resolve.alias + .set('@', resolve('src')) + .set('api', resolve('src/api')) + .set('assets',resolve('src/assets')) + .set('utils', resolve('src/utils')) + .set('components', resolve('src/components')) + .set('hooks', resolve('src/hooks')) + .set('lib', resolve('src/lib')) + .set('request', resolve('src/request')) + .set('router', resolve('src/router')) + .set('store', resolve('src/store')) + .set('views', resolve('src/views')) + .set('vue-i18n', 'vue-i18n/dist/vue-i18n.cjs.js') // 解决控制台警告 + return config; +}; diff --git a/bmp-console-web/config/speedMeasure.js b/bmp-console-web/config/speedMeasure.js new file mode 100644 index 0000000..37fb9d8 --- /dev/null +++ b/bmp-console-web/config/speedMeasure.js @@ -0,0 +1,9 @@ +// 这个插件可以看到启动时候的耗时模块,方便后续做优化使用 +const SpeedMeasurePlugin = require('speed-measure-webpack-plugin'); + +module.exports = (config) => { + config.plugins.push( + new SpeedMeasurePlugin() + ); + return config; +} diff --git a/bmp-console-web/config/terserPlugin.js b/bmp-console-web/config/terserPlugin.js new file mode 100644 index 0000000..3fcca89 --- /dev/null +++ b/bmp-console-web/config/terserPlugin.js @@ -0,0 +1,23 @@ +// 移除console +const TerserPlugin = require('terser-webpack-plugin'); + +module.exports = (config) => { + if (process.env.VUE_APP_ENV === 'prod') { + config.optimization.minimizer([ + new TerserPlugin({ + test: /\.js(\?.*)?$/i, + terserOptions: { + compress: { + drop_console: true, + pure_funcs: ['console.log'] + } + } + }) + ]) + } + else { + // 在其他环境期间禁用优化以加快速度 + config.optimization.minimize(false); + } + return config; +} diff --git a/bmp-console-web/package.json b/bmp-console-web/package.json new file mode 100644 index 0000000..2164076 --- /dev/null +++ b/bmp-console-web/package.json @@ -0,0 +1,52 @@ +{ + "name": "bmp-console-web", + "version": "1.0.0", + "private": true, + "scripts": { + "dev": "vue-cli-service serve", + "build": "vue-cli-service build --report", + "build-pre": "vue-cli-service build --mode pre", + "build-test": "vue-cli-service build --mode test", + "build-prod": "vue-cli-service build --mode prod" + }, + "dependencies": { + "@element-plus/icons": "0.0.11", + "axios": "0.25.0", + "core-js": "^3.6.5", + "crypto-js": "^4.1.1", + "default-passive-events": "^2.0.0", + "echarts": "^5.5.0", + "element-plus": "2.0.0", + "mitt": "3.0.0", + "pinia": "2.0.21", + "pinia-plugin-persistedstate": "^3.2.1", + "vue": "3.2.25", + "vue-clipboard3": "^2.0.0", + "vue-cookies": "^1.8.1", + "vue-echarts": "^6.7.2", + "vue-i18n": "9.1.10", + "vue-router": "4.0.3", + "vue3-eventbus": "^2.0.0" + }, + "devDependencies": { + "@babel/plugin-proposal-optional-chaining": "7.18.9", + "@types/echarts": "^4.9.22", + "@vue/cli-plugin-babel": "~4.5.15", + "@vue/cli-plugin-pwa": "~4.5.15", + "@vue/cli-plugin-router": "~4.5.15", + "@vue/cli-plugin-typescript": "~4.5.0", + "@vue/cli-service": "~4.5.15", + "@vue/compiler-sfc": "^3.0.0", + "babel-eslint": "10.1.0", + "sass": "1.26.5", + "sass-loader": "^8.0.2", + "speed-measure-webpack-plugin": "^1.5.0", + "terser-webpack-plugin": "^5.3.6", + "typescript": "~4.1.5" + }, + "browserslist": [ + "> 1%", + "last 2 versions", + "not dead" + ] +} diff --git a/bmp-console-web/public/img/icons/android-chrome-192x192.png b/bmp-console-web/public/img/icons/android-chrome-192x192.png new file mode 100644 index 0000000..b02aa64 Binary files /dev/null and b/bmp-console-web/public/img/icons/android-chrome-192x192.png differ diff --git a/bmp-console-web/public/index.html b/bmp-console-web/public/index.html new file mode 100644 index 0000000..c9f3582 --- /dev/null +++ b/bmp-console-web/public/index.html @@ -0,0 +1,18 @@ + + + + + + + + + + <%= htmlWebpackPlugin.options.title %> + + + + +
+ + + diff --git a/bmp-console-web/public/robots.txt b/bmp-console-web/public/robots.txt new file mode 100644 index 0000000..9c502b1 --- /dev/null +++ b/bmp-console-web/public/robots.txt @@ -0,0 +1,3 @@ +User-agent: * +Disallow: /index.html +Disallow: /? diff --git a/bmp-console-web/src/App.vue b/bmp-console-web/src/App.vue new file mode 100644 index 0000000..8efbef4 --- /dev/null +++ b/bmp-console-web/src/App.vue @@ -0,0 +1,32 @@ + + + diff --git a/bmp-console-web/src/api/config.ts b/bmp-console-web/src/api/config.ts new file mode 100644 index 0000000..c27b0fe --- /dev/null +++ b/bmp-console-web/src/api/config.ts @@ -0,0 +1,164 @@ +interface TotalUrlPathTypes { + loginUrl: string; + userUrl: string; + timeZoneUrl: string; + instanceCloseUrl: string; + instanceDeleteUrl: string; + instanceOpenUrl: string; + instanceRestartUrl: string; + instanceLockUrl: string; + instanceUnlockUrl: string; + instanceRepasswordUrl: string; + apiKeyCreateUrl: string; + apiKeyDeleteUrl: string; + sshKeyDeleteUrl: string; + sshKeyCreateUrl: string; + sshKeyEditUrl: string; + projectCreateUrl: string; + projectEditUrl: string; + projectDeleteUrl: string; + azUrl: string; + deviceTypeUrl: string; + osTypeUrl: string; + raidUrl: string; + systemDiskPartitionUrl: string; + isDeviceStockEnoughUrl: string; + createInstanceUrl: string; + instanceListUrl: string; + instanceDetailUrl: string; + setUserUrl: string; + changePasswordUrl: string; + sshKeyUrl: string; + apiKeyUrl: string; + projectListUrl: string; + logOutUrl: string; + setCustomListUrl: string; + setAlarmCustomListUrl: string; + customListUrl: string; + alarmCustomListUrl: string; + editInstanceUrl: string; + editProjectUrl: string; + projectDetailUrl: string; + relatedUserAddUrl: string; + relatedUserDeleteUrl: string; + transferUserUrl: string; + transferUserCheckUrl: string; + relatedUserCheckUrl: string; + batchCloseUrl: string; + batchOpenUrl: string; + batchRestartUrl: string; + batchDeleteUrl: string; + batchRenameUrl: string; + batchRepasswordUrl: string; + hardWareStatusUrl: string; + alarmLogListUrl: string; + alarmLogListExportUrl: string; + resystemInstanceUrl: string; + shareInstanceListUrl: string; + transferPartUserUrl: string; + messageListUrl: string; + messageDetailUrl: string; + messageTypeUrl: string; + messageReadUrl: string; + getMessageStatisticUrl: string; + messageUnreadUrl: string; + messageDeleteUrl: string; + operationLogTypeListUrl: string; + operationLogListUrl: string; + operationLogListExportUrl: string; + deviceTagUrl: string; + addRuleUrl: string; + alarmRuleListUrl: string; + alarmRuleDetailUrl: string; + ruleEnableUrl: string; + ruleDisableUrl: string; + ruleDeleteUrl: string; + editRuleUrl: string; + getAgentStateUrl: string; + alarmHistoryUrl: string; + monitorDataUrl: string; +}; + +const urlPath: TotalUrlPathTypes = { + loginUrl: '/login', // 登录 + userUrl: '/user', // 用户详情 + timeZoneUrl: '/user/timezones', // 时区信息 + instanceCloseUrl: '/instance/stopInstance', // 关机 + instanceDeleteUrl: '/instance/', // 删除 + instanceOpenUrl: '/instance/startInstance', // 开机 + instanceRestartUrl: '/instance/restartInstance', // 重启 + instanceLockUrl: '/instance/lockInstance', // 锁定 + instanceUnlockUrl: '/instance/unlockInstance', // 解除锁定 + instanceRepasswordUrl: '/instance/resetPasswd', // 重置密码 + apiKeyCreateUrl: '/apikey', // api密钥创建 + apiKeyDeleteUrl: '/apikey/', // api密钥删除 + sshKeyDeleteUrl: '/keypair/', // ssh密钥删除 + sshKeyCreateUrl: '/keypair', // ssh密钥创建 + sshKeyEditUrl: '/keypair/', // ssh密钥编辑 + projectCreateUrl: '/project', // 项目创建 + projectEditUrl: '/project/', // 项目编辑 + projectDeleteUrl: '/project/', // 项目删除 + azUrl: '/idc', // 机房信息 + deviceTypeUrl: '/deviceType/getAvailableDeviceTypes', // 机型信息 + osTypeUrl: '/image/queryImagesByDeviceType', // 镜像信息 + raidUrl: '/raid/queryRaidsByDeviceTypeIDAndVolumeType', // 系统盘信息 + systemDiskPartitionUrl: '/partition/queryDefaultSystemPartitions', // 系统盘分区信息 + isDeviceStockEnoughUrl: '/device/isDeviceStockEnough', // 查询库存 + createInstanceUrl: '/instance', // 创建实例 + instanceListUrl: '/instance', // 实例列表 + instanceDetailUrl: '/instance/', // 实例详情 + setUserUrl: '/user', // 用户编辑 + changePasswordUrl: '/user/password', // 用户修改密码 + sshKeyUrl: '/keypair', // ssh密钥列表 + apiKeyUrl: '/apikey', // api密钥列表 + projectListUrl: '/project', // 获取项目列表 + logOutUrl: '/logout', // 登出 + setCustomListUrl: '/custom/setCustomInfo', // 设置自定义列表 + setAlarmCustomListUrl: '/v1/oob-alert/custom/set-custom-info', + customListUrl: '/custom/getCustomInfo', // 获取自定义列表 + alarmCustomListUrl: '/v1/oob-alert/custom/get-custom-info', // 获取报警日志自定义列表 + editInstanceUrl: '/instance/modifyInstance', // 实例编辑描述 + editProjectUrl: '/project/', //项目编辑描述 + projectDetailUrl: '/project/', //项目详情 + relatedUserAddUrl: '/project/', //添加共享用户 + relatedUserDeleteUrl: '/project/', //删除共享用户 + transferUserUrl: '/project/', //转移用户 + transferUserCheckUrl: '/user/checkUserConsoleAccessByName', //验证转移用户 + relatedUserCheckUrl: '/user/checkUserConsoleAccessByName', //验证共享用户 + batchCloseUrl: '/instance/stopInstances', //批量关机实例 + batchOpenUrl: '/instance/startInstances', //批量开机实例 + batchRestartUrl: '/instance/restartInstances', //批量重启实例 + batchDeleteUrl: '/instance/deleteInstances', //批量删除实例 + batchRenameUrl: '/instance/modifyInstances', //批量编辑实例名称实例 + batchRepasswordUrl: '/instance/batchResetPasswd', //批量重置密码实例 + hardWareStatusUrl: '/v1/oob-alert/device/status', //硬件设备状态 + alarmLogListUrl: '/v1/oob-alert/consolelogs', //报警日志列表 + alarmLogListExportUrl: '/v1/oob-alert/consolelogs', //报警日志导出列表 + resystemInstanceUrl: '/instance/reinstallInstance', //实例重装系统 + shareInstanceListUrl: '/instance/forshare/list', //共享实例列表 + transferPartUserUrl: '/project/move/instances', //转移部分实例 + messageListUrl: '/messages', // 消息列表 + messageDetailUrl: '/messages/getMessageById', // 消息详情 + messageTypeUrl: '/messages/getMessageTypes', // 消息类型 + messageReadUrl: '/messages/doRead', // 消息已读 + getMessageStatisticUrl: '/messages/statistic', // 消息未读数 + messageUnreadUrl: '/messages/hasUnreadMessage', // 消息是否有未读 + messageDeleteUrl: '/messages/delete', // 消息删除 + operationLogTypeListUrl: '/auditLogs/types', // 操作日志类型 + operationLogListUrl: '/auditLogs', // 操作日志列表 + operationLogListExportUrl: '/auditLogs', // 操作日志下载 + deviceTagUrl: '/monitorProxy/desrcibeTags', // devicetag列表 + addRuleUrl: '/monitorRule/addRule', // 添加报警规则 + alarmRuleListUrl: '/monitorRule/describeRules', // 报警规则列表 + alarmRuleDetailUrl: '/monitorRule/describeRule', // 报警规则详情 + ruleEnableUrl: '/monitorRule/enableRule', // 启用报警规则 + ruleDisableUrl: '/monitorRule/disableRule', // 禁用报警规则 + ruleDeleteUrl: '/monitorRule/deleteRule', // 删除报警规则 + editRuleUrl: '/monitorRule/editRule', // 编辑报警规则 + getAgentStateUrl: '/monitorProxy/desrcibeAgentStatus', // 获取agent状态 + alarmHistoryUrl: '/monitorAlert/describeAlerts', // 报警历史列表 + monitorDataUrl: '/monitorData', // 带内监控 +} + + +export default urlPath; diff --git a/bmp-console-web/src/api/request.ts b/bmp-console-web/src/api/request.ts new file mode 100644 index 0000000..e7e3bad --- /dev/null +++ b/bmp-console-web/src/api/request.ts @@ -0,0 +1,1498 @@ +import request from 'request/index.ts'; +import {AxiosPromise} from 'axios'; +import urlPath from 'api/config.ts'; + +type SysPartitionType = { + format: string; + point: string; + size: number; +} +type SetType = T extends {} ? any : T; + +export interface TotalTypes { + LoginType: { + username: string; + password: string; + }, + UserType:{}, + timeZoneType:{}, + instanceCloseType:{ + instanceId: string; + idcId: string + }, + instanceDeleteType:{ + instanceId: string; + }, + instanceOpenType:{ + instanceId: string; + idcId: string + }, + instanceRestartType:{ + instanceId: string; + idcId: string + }, + instanceLockType:{ + instanceId: string; + idcId: string + }, + instanceUnlockType:{ + instanceId: string; + idcId: string + }, + instanceRepasswordType:{ + instanceId: string; + idcId: string; + password: string + }, + apiKeyCreateType:{ + keyName: string; + readOnly: number; + type: string; + }, + apiKeyDeleteType:{ + apikeyId: string + }, + sshKeyDeleteType:{ + keypairId: string + }, + sshKeyCreateType:{ + key: string; + name: string + }, + sshKeyEditType:{ + name: string; + keypairId: string + }, + projectCreateType:{ + isDefault?: 0; + isSystem?: 0; + projectId: string; + projectName: string; + userId: string; + }, + projectEditType: { + projectId: string; + }, + projectDeleteType:{ + projectId: string; + }, + az:{}, + deviceType:{ + idcId: string; + }, + osType:{ + idcId: string; + deviceTypeId: string; + }, + raid:{ + deviceTypeId: string; + volumeType: string; + }, + systemDiskPartition:{ + imageId: string; + deviceTypeId: string; + }, + createInstance:{ + count: number; + deviceTypeId: string; + hostname?: string; + idcId: string; + imageId: string + instanceName: string; + password?: string; + sshKeyId?: string; + systemVolumeRaidId: string; + projectId: string; + systemPartition: SysPartitionType[]; + username: string + }, + isDeviceStockEnough:{ + idcId: string; + deviceTypeId: string; + count: string + }, + instanceList:{ + pageNumber?: number; + pageSize?: number; + projectId: string; + status: string; + exportType?: string; + isAll?: string + }, + instanceDetail:{ + instanceId: string; + }, + areaCode:{}, + setUser:{ + defaultProjectId: string; + description?: string; + email: string; + language: string; + phoneNumber: string; + phonePrefix: string; + timezone: string; + userName: string; + }, + changePassword:{ + oldPassword: string; + password: string; + }, + sshKey:{ + pageNumber: number; + pageSize: number; + }, + apiKey:{ + pageNumber: number; + pageSize: number; + }, + projectList:{ + projectName?: string; + pageNumber: number; + pageSize: number; + isAll?: string; + }, + logOutType:{}, + setCustomListType: Required<{pageKey: string; pageValue: SetType<{}>;}>, + setAlarmLogCustomListType: Required<{page_key: string; page_value: SetType<{}>;}>, + customListType: Omit, + alarmLogCustomListType: { + page_key: string; + }, + projectListExportType: { + exportType: string; + isAll: string; + }, + instanceListExportType: { + exportType: string; + projectId: string; + isAll: string; + }, + editInstanceType: { + instanceId: string, + idcId: string, + description?: string, + name?: string + }, + editProjectType: { + projectId: string, + description?: string, + name?: string + }, + projectDetail: { + projectId: string; + }, + relatedUserAddType: { + projectId: string; + ownerName: string; + shareName: string + }, + relatedUserDeleteType: { + projectId: string; + ownerName: string; + shareName: string + }, + transferUserType: { + projectId: string; + ownerName: string; + moverName: string + }, + transferUserCheckType: { + projectId: string; + checkedUserName: string; + operation: string; + }, + relatedUserCheckType: { + projectId: string; + checkedUserName: string; + operation: string; + }, + relatedUserList: { + + }, + batchCloseType: { + instanceIds: [] + }, + batchOpenType: { + instanceIds: [] + }, + batchRestartType: { + instanceIds: [] + }, + batchDeleteType: { + instanceIds: [] + }, + batchRenameType: { + instanceIds: [], + instanceName: string + }, + batchRepasswordType: { + instanceIds: [], + password: string + }, + hardWareStatusType: { + sn: string + }, + alarmLogListType: { + page_size: number, + page_num: number, + sn: string + }, + alarmLogListExportType: { + + }, + resystemInstance: { + bootMode: string; + instanceId: string; + instanceName: string; + hostname?: string; + imageId: string + password?: string; + sshKeyId?: string; + systemVolumeRaidId: string; + projectId: string; + systemPartition: SysPartitionType[]; + }, + shareInstanceListType: { + projectId: string; + ownerName: string; + sharerName: string; + }, + transferPartUserType: { + instanceIDs: string, + moverName: string, + moverProjectID: string, + ownerName: string, + ownerProjectID: string + }, + messageType: { + content: string, + detail: string, + has_read: number, + is_del: number, + message_id: string, + message_sub_type: string, + message_type: string, + }, + messageDetail: { + content: string, + detail: string, + has_read: number, + is_del: number, + messageId: string, + message_sub_type: string, + message_type: string, + }, + messageReadType: { + messageIds: string + }, + messageDeleteType: { + messageIds: string + }, + messageListExportType: { + exportType: string; + }, + operationLogType: { + instanceId: string; + pageSize: string; + pageNumber: string; + operation?: string; + username?: string + }, + operationLogListExportType: { + all: string; + exportType: string; + }, + deviceTagType: { + instanceId: string; + tagName: string; + }, + addRuleType: { + + }, + alarmRuleListType: {}, + ruleEnableType: { + ruleId: string + }, + monitorDataType: [], + +} + +/** + * 登录接口 + * @param {Object} data 请求需要的参数 +*/ +export function loginAPI(data: TotalTypes['LoginType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.loginUrl, + method: 'post', + data + }); +} + +/** + * 用户接口 + * @param {Object} params 请求需要的参数 +*/ +export function userAPI(params: TotalTypes['UserType']): AxiosPromise { + return request({ + isrepeat: true, + isBusinessProcessing: false, + url: urlPath.userUrl, + method: 'get', + params + }); +} +/** + * 时区获取接口 + * @param {Object} params 请求需要的参数 +*/ +export function timeZoneAPI(params: TotalTypes['timeZoneType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.timeZoneUrl, + method: 'get', + params + }); +} + +/** + * 实例关机接口 + * @param {Object} data 请求需要的参数 +*/ +export function instanceCloseAPI(data: TotalTypes['instanceCloseType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.instanceCloseUrl, + method: 'post', + data + }); +} + +/** + * 实例删除接口 + * @param {Object} params 请求需要的参数 +*/ +export function instanceDeleteAPI(params: TotalTypes['instanceDeleteType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.instanceDeleteUrl + params.instanceId, + method: 'delete', + params + }); +} + +/** + * 实例开机接口 + * @param {Object} data 请求需要的参数 +*/ +export function instanceOpenAPI(data: TotalTypes['instanceOpenType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.instanceOpenUrl, + method: 'post', + data + }); +} + +/** + * 实例重启接口 + * @param {Object} data 请求需要的参数 +*/ +export function instanceRestartAPI(data: TotalTypes['instanceRestartType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.instanceRestartUrl, + method: 'post', + data + }); +} + +/** + * 实例锁定接口 + * @param {Object} data 请求需要的参数 +*/ +export function instanceLockAPI(data: TotalTypes['instanceLockType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.instanceLockUrl, + method: 'post', + data + }); +} + +/** + * 实例解除锁定接口 + * @param {Object} data 请求需要的参数 +*/ +export function instanceUnlockAPI(data: TotalTypes['instanceUnlockType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.instanceUnlockUrl, + method: 'post', + data + }); +} + +/** + * 实例重置密码接口 + * @param {Object} data 请求需要的参数 +*/ +export function instanceRepasswordAPI(data: TotalTypes['instanceRepasswordType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.instanceRepasswordUrl, + method: 'post', + data + }); +} + +/** + * api密钥创建接口 + * @param {Object} data 请求需要的参数 +*/ +export function apiKeyCreateAPI(data: TotalTypes['apiKeyCreateType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.apiKeyCreateUrl, + method: 'put', + data + }); +} + +/** + * api密钥删除接口 + * @param {Object} params 请求需要的参数 +*/ +export function apiKeyDeleteAPI(params: TotalTypes['apiKeyDeleteType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.apiKeyDeleteUrl + params.apikeyId, + method: 'delete', + params + }); +} + +/** + * ssh密钥删除接口 + * @param {Object} params 请求需要的参数 +*/ +export function sshKeyDeleteAPI(params: TotalTypes['sshKeyDeleteType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.sshKeyDeleteUrl + params.keypairId, + method: 'delete', + params + }); +} + +/** + * ssh密钥创建接口 + * @param {Object} data 请求需要的参数 +*/ +export function sshKeyCreateAPI(data: TotalTypes['sshKeyCreateType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.sshKeyCreateUrl, + method: 'put', + data + }); +} + +/** + * ssh密钥编辑接口 + * @param {Object} data 请求需要的参数 +*/ +export function sshKeyEditAPI(data: TotalTypes['sshKeyEditType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.sshKeyEditUrl + data.keypairId, + method: 'put', + data + }); +} + +/** + * 项目创建接口 + * @param {Object} data 请求需要的参数 +*/ +export function projectCreateAPI(data: TotalTypes['projectCreateType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.projectCreateUrl, + method: 'put', + data + }); +} + +/** + * 项目编辑接口 + * @param {Object} data 请求需要的参数 +*/ +export function projectEditAPI(data: TotalTypes['projectEditType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.projectEditUrl + data.projectId, + method: 'post', + data + }); +} + +/** + * 项目删除接口 + * @param {Object} params 请求需要的参数 +*/ +export function projectDeleteAPI(params: TotalTypes['projectDeleteType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.projectDeleteUrl + params.projectId, + method: 'delete', + params + }); +} + +/** + * 机房信息接口 + * @param {Object} params 请求需要的参数 +*/ +export function azAPI(params: TotalTypes['az']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.azUrl, + method: 'get', + params + }); +} + +/** + * 机型信息接口 + * @param {Object} params 请求需要的参数 +*/ +export function deviceTypeAPI(params: TotalTypes['deviceType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.deviceTypeUrl, + method: 'get', + params + }); +} + +/** + * 镜像信息接口 + * @param {Object} params 请求需要的参数 +*/ +export function osTypeAPI(params: TotalTypes['osType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.osTypeUrl, + method: 'get', + params + }); +} + +/** + * 系统盘信息接口 + * @param {Object} params 请求需要的参数 +*/ +export function raidAPI(params: TotalTypes['raid']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.raidUrl, + method: 'get', + params + }); +} + +/** + * 系统盘分区信息接口 + * @param {Object} params 请求需要的参数 +*/ +export function systemDiskPartitionAPI(params: TotalTypes['systemDiskPartition']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.systemDiskPartitionUrl, + method: 'get', + params + }); +} + +/** + * 创建实例接口 + * @param {Object} data 请求需要的参数 +*/ +export function createInstanceAPI(data: TotalTypes['createInstance']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.createInstanceUrl, + method: 'put', + data + }); +} + +/** + * 实例库存接口 + * @param {Object} params 请求需要的参数 +*/ +export function isDeviceStockEnoughAPI(params: TotalTypes['isDeviceStockEnough']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.isDeviceStockEnoughUrl, + method: 'get', + params + }); +} + +/** + * 实例列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function instanceListAPI(params: TotalTypes['instanceList']): AxiosPromise { + return request({ + isrepeat: true, + isBusinessProcessing: false, + url: urlPath.instanceListUrl, + method: 'get', + params + }); +} + +/** + * 实例详情接口 + * @param {Object} params 请求需要的参数 +*/ +export function instanceDetailAPI(params: TotalTypes['instanceDetail']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.instanceDetailUrl + params.instanceId, + method: 'get', + params + }); +} + +/** + * 保存用户接口 + * @param {Object} data 请求需要的参数 +*/ +export function setUserAPI(data: TotalTypes['setUser']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.setUserUrl, + method: 'put', + data + }); +} + +/** + * 更改密码接口 + * @param {Object} data 请求需要的参数 +*/ +export function changePasswordAPI(data: TotalTypes['changePassword']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.changePasswordUrl, + method: 'put', + data + }); +} + +/** + * ssh个人密钥接口 + * @param {Object} params 请求需要的参数 +*/ +export function sshKeyAPI(params: TotalTypes['sshKey']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.sshKeyUrl, + method: 'get', + params + }); +} + +/** + * api个人密钥接口 + * @param {Object} params 请求需要的参数 +*/ +export function apiKeyAPI(params: TotalTypes['apiKey']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.apiKeyUrl, + method: 'get', + params + }); +} + +/** + * 项目列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function projectListAPI(params: TotalTypes['projectList']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.projectListUrl, + method: 'get', + params + }); +} + +/** + * 用户登出接口 + * @param {Object} data 请求需要的参数 +*/ +export function logOutAPI(data: TotalTypes['logOutType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.logOutUrl, + method: 'post', + data + }); +} + +/** + * 自定义列表接口 + * @param {Object} data 请求需要的参数 +*/ +export function setCustomListAPI(data: TotalTypes['setCustomListType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.setCustomListUrl, + method: 'post', + data + }); +} + +/** + * 报警日志自定义列表接口 + * @param {Object} data 请求需要的参数 +*/ +export function setAlarmCustomListAPI(data: TotalTypes['setAlarmLogCustomListType']): AxiosPromise { + return request({ + baseURL: '/oob-alert', + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.setAlarmCustomListUrl, + method: 'post', + data + }); +} +/** + * 获取自定义列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function customListAPI(params: TotalTypes['customListType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.customListUrl, + method: 'get', + params + }); +} + +/** + * 获取报警日志自定义列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function alarmCustomListAPI(params: TotalTypes['alarmLogCustomListType']): AxiosPromise { + return request({ + baseURL: '/oob-alert', + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.alarmCustomListUrl, + method: 'get', + params + }); +} + +/** + * 项目列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +export function projectListExportAPI(params: TotalTypes['projectListExportType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.projectListUrl, + method: 'get', + params, + // 服务器响应的数据类型,默认json + responseType: 'blob' + }); +}; + +/** + * 项目列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +export function instanceListExportAPI(params: TotalTypes['instanceListExportType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.instanceListUrl, + method: 'get', + params, + // 服务器响应的数据类型,默认json + responseType: 'blob' + }); +}; + + +/** + * 编辑实例接口 + * @param {Object} data 请求需要的参数 +*/ +export function editInstanceAPI(data: TotalTypes['editInstanceType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.editInstanceUrl, + method: 'post', + data + }); +} + +/** + * 编辑项目接口 + * @param {Object} data 请求需要的参数 +*/ +export function editProjectAPI(data: TotalTypes['editProjectType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.editProjectUrl + data.projectId + '/description', + method: 'post', + data + }); +} + +/** + * 项目详情接口 + * @param {Object} params 请求需要的参数 +*/ +export function projectDetailAPI(params: TotalTypes['projectDetail']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.projectDetailUrl + params.projectId, + method: 'get', + params + }); +} + +/** + * 添加共享用户接口 + * @param {Object} data 请求需要的参数 +*/ +export function relatedUserAddAPI(data: TotalTypes['relatedUserAddType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.relatedUserAddUrl + data.projectId + '/share', + method: 'put', + data + }); +} + +/** + * 删除共享用户接口 + * @param {Object} data 请求需要的参数 +*/ +export function relatedUserDeleteAPI(data: TotalTypes['relatedUserDeleteType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.relatedUserDeleteUrl + data.projectId + '/cancelShare', + method: 'put', + data + }); +} + +/** + * 转移共享用户接口 + * @param {Object} data 请求需要的参数 +*/ +export function transferUserAPI(data: TotalTypes['transferUserType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.transferUserUrl + data.projectId + '/move', + method: 'put', + data + }); +} + +/** + * 验证转移用户接口 + * @param {Object} params 请求需要的参数 +*/ +export function transferUserCheckAPI(params: TotalTypes['transferUserCheckType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.transferUserCheckUrl, + method: 'get', + params + }); +} + +/** + * 验证关联用户接口 + * @param {Object} params 请求需要的参数 +*/ +export function relatedUserCheckAPI(params: TotalTypes['relatedUserCheckType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.relatedUserCheckUrl, + method: 'get', + params + }); +} + +/** + * 批量关机接口 + * @param {Object} data 请求需要的参数 +*/ +export function batchCloseAPI(data: TotalTypes['batchCloseType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.batchCloseUrl, + method: 'post', + data + }); +} + +/** + * 批量开机接口 + * @param {Object} data 请求需要的参数 +*/ +export function batchOpenAPI(data: TotalTypes['batchOpenType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.batchOpenUrl, + method: 'post', + data + }); +} + +/** + * 批量重启接口 + * @param {Object} data 请求需要的参数 +*/ +export function batchRestartAPI(data: TotalTypes['batchRestartType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.batchRestartUrl, + method: 'post', + data + }); +} + +/** + * 批量删除接口 + * @param {Object} data 请求需要的参数 +*/ +export function batchDeleteAPI(data: TotalTypes['batchDeleteType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.batchDeleteUrl, + method: 'delete', + data + }); +} + +/** + * 批量重置密码接口 + * @param {Object} data 请求需要的参数 +*/ +export function batchRepasswordAPI(data: TotalTypes['batchRepasswordType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.batchRepasswordUrl, + method: 'post', + data + }); +} + +/** + * 批量编辑实例名称接口 + * @param {Object} data 请求需要的参数 +*/ +export function batchRenameAPI(data: TotalTypes['batchRenameType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.batchRenameUrl, + method: 'post', + data + }); +} + +/** + * 硬件设备状态接口 + * @param {Object} params 请求需要的参数 +*/ +export function hardWareStatusAPI(params: TotalTypes['hardWareStatusType']): AxiosPromise { + return request({ + baseURL: '/oob-alert', + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.hardWareStatusUrl, + method: 'get', + params + }); +} + +/** + * 报警日志列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function alarmLogListAPI(params: TotalTypes['alarmLogListType']): AxiosPromise { + return request({ + baseURL: '/oob-alert', + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.alarmLogListUrl, + method: 'get', + params + }); +} + +/** + * 报警日志列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +export function alarmLogListExportAPI(params: TotalTypes['alarmLogListExportType']): AxiosPromise { + return request({ + baseURL: '/oob-alert', + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.alarmLogListExportUrl, + method: 'get', + params, + // 服务器响应的数据类型,默认json + responseType: 'blob' + }); +}; + +/** + * 重装系统实例接口 + * @param {Object} data 请求需要的参数 +*/ +export function resystemInstanceAPI(data: TotalTypes['resystemInstance']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.resystemInstanceUrl, + method: 'post', + data + }); +} + +/** + * 共享实例列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function shareInstanceListAPI(params: TotalTypes['shareInstanceListType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.shareInstanceListUrl, + method: 'get', + params + }); +} + +/** + * 转移部分共享用户接口 + * @param {Object} data 请求需要的参数 +*/ +export function transferPartUserAPI(data: TotalTypes['transferPartUserType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.transferPartUserUrl, + method: 'put', + data + }); +} + +/** + * 消息列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function messageListAPI(params: TotalTypes['messageType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.messageListUrl, + method: 'get', + params + }); +} + +/** + * 消息详情接口 + * @param {Object} params 请求需要的参数 +*/ +export function messageDetailAPI(params: TotalTypes['messageDetail']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.messageDetailUrl, + method: 'get', + params + }); +} + +/** + * 消息类型接口 + * @param {Object} params 请求需要的参数 +*/ +export function messageTypeAPI(params: TotalTypes['messageType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.messageTypeUrl, + method: 'get', + params + }); +} + +/** + * 消息已读接口 + * @param {Object} data 请求需要的参数 +*/ +export function messageReadAPI(data: TotalTypes['messageReadType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.messageReadUrl, + method: 'put', + data + }); +} + + +/** + * 消息类型接口 + * @param {Object} params 请求需要的参数 +*/ +export function getMessageStatisticAPI(): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.getMessageStatisticUrl, + method: 'get', + }); +} + +/** + * 消息未读接口 + * @param {Object} params 请求需要的参数 +*/ +export function messageUnreadAPI(): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.messageUnreadUrl, + method: 'get', + }); +} + +/** + * 消息删除接口 + * @param {Object} data 请求需要的参数 +*/ +export function messageDeleteAPI(data: TotalTypes['messageDeleteType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.messageDeleteUrl, + method: 'delete', + data + }); +} + +/** + * 消息列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +export function messageListExportAPI(params: TotalTypes['messageListExportType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.messageListUrl, + method: 'get', + params, + // 服务器响应的数据类型,默认json + responseType: 'blob' + }); +}; + +/** + * 操作日志类型接口 + * @param {Object} params 请求需要的参数 +*/ +export function operationLogTypeListAPI(): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.operationLogTypeListUrl, + method: 'get', + }); +} + +/** + * 操作日志列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function operationLogListAPI(params: TotalTypes['operationLogType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.operationLogListUrl, + method: 'get', + params + }); +} + +/** + * 操作日志列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +export function operationLogListExportAPI(params: TotalTypes['operationLogListExportType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.operationLogListExportUrl, + method: 'get', + params, + // 服务器响应的数据类型,默认json + responseType: 'blob' + }); +}; + +/** + * 添加报警规则deviceTag接口 + * @param {Object} params 请求需要的参数 +*/ +export function deviceTagAPI(params: TotalTypes['deviceTagType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.deviceTagUrl, + method: 'get', + params + }); +} + +/** + * 添加报警规则列表接口 + * @param {Object} data 请求需要的参数 +*/ +export function addRuleAPI(data: TotalTypes['addRuleType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.addRuleUrl, + method: 'post', + data + }); +} + +/** + * 报警规则列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function alarmRuleListAPI(params: TotalTypes['alarmRuleListType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.alarmRuleListUrl, + method: 'get', + params + }); +} + +/** + * 报警规则列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +export function alarmRuleListExportAPI(params: TotalTypes['operationLogListExportType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.alarmRuleListUrl, + method: 'get', + params, + // 服务器响应的数据类型,默认json + responseType: 'blob' + }); +}; + + +/** + * 报警规则详情接口 + * @param {Object} params 请求需要的参数 +*/ +export function alarmRuleDetailAPI(params: TotalTypes['alarmRuleListType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.alarmRuleDetailUrl, + method: 'get', + params + }); +} + +/** + * 报警规则启用接口 + * @param {Object} data 请求需要的参数 +*/ +export function ruleEnableAPI(data: TotalTypes['ruleEnableType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.ruleEnableUrl, + method: 'put', + data + }); +} + +/** + * 报警规则禁用接口 + * @param {Object} data 请求需要的参数 +*/ +export function ruleDisableAPI(data: TotalTypes['ruleEnableType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.ruleDisableUrl, + method: 'put', + data + }); +} + +/** + * 报警规则删除接口 + * @param {Object} data 请求需要的参数 +*/ +export function ruleDeleteAPI(data: TotalTypes['ruleEnableType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.ruleDeleteUrl, + method: 'delete', + data + }); +} + +/** + * 报警规则编辑接口 + * @param {Object} data 请求需要的参数 +*/ +export function editRuleAPI(data: TotalTypes['ruleEnableType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: true, + url: urlPath.editRuleUrl, + method: 'put', + data + }); +} + + +/** + * 获取agent状态接口 + * @param {Object} params 请求需要的参数 +*/ +export function getAgentStateAPI(params: TotalTypes['alarmRuleListType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.getAgentStateUrl, + method: 'get', + params + }); +} + +/** + * 获取报警历史列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function alarmHistoryAPI(params: TotalTypes['alarmRuleListType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.alarmHistoryUrl, + method: 'get', + params + }); +} + +/** + * 操作日志列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +export function alarmHistoryListExportAPI(params: TotalTypes['operationLogListExportType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.alarmHistoryUrl, + method: 'get', + params, + // 服务器响应的数据类型,默认json + responseType: 'blob' + }); +}; + +/** + * 获取带内监控列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function monitorDataAPI(params: TotalTypes['monitorDataType']): AxiosPromise { + return request({ + isrepeat: false, + isBusinessProcessing: false, + url: urlPath.monitorDataUrl, + method: 'get', + params + }); +} \ No newline at end of file diff --git a/bmp-console-web/src/assets/css/addButton.scss b/bmp-console-web/src/assets/css/addButton.scss new file mode 100644 index 0000000..66b680b --- /dev/null +++ b/bmp-console-web/src/assets/css/addButton.scss @@ -0,0 +1,13 @@ +.add-button-style { + background-color: #108EF9; + width: auto; + min-width: 90px; + height: 30px; + border-radius: 45px; + margin-left: 30px; + font-size: 12px; +} + +.w140 { + width: 140px; +} \ No newline at end of file diff --git a/bmp-console-web/src/assets/css/batch-table.scss b/bmp-console-web/src/assets/css/batch-table.scss new file mode 100644 index 0000000..709195e --- /dev/null +++ b/bmp-console-web/src/assets/css/batch-table.scss @@ -0,0 +1,118 @@ +.batch-table-content { + margin: 20px 29px; + .el-table { + overflow: auto; + max-height: 160px !important; + font-size: 12px; + color: #333333; + border-radius: 5px; + //--el-table-border-color: white; + //--el-table-border: 1px solid white; + &--border { + &::after, + &::before { + display: none; + } + } + + &__border-left-patch { + display: none; + } + + &-column--selection { + border-left: 0 !important; + border-right: 0 !important; + } + &-fixed-column--left { + border-left: 0 !important; + border-color: #fff !important; + // border-right: 0 !important; + } + + } + + .el-table__inner-wrapper { + + &::after, + &::before { + display: none; + } + } + + .el-table__inner-wrapper tr:first-child td:first-child{ + border-left: 0 !important; + border-color: #fff !important; + } + + .cell { + padding: 0 16px; + } + + .el-table__body-wrapper { + border-top: 2px solid white; + } + + .el-table__header-wrapper { + .cell { + color: #333333; + display: flex; + align-items: center; + justify-content: center; + .el-table__column-filter-trigger { + width: 16px; + height: 16px; + background: url('~@/assets/img/arrowDown.png') center center no-repeat; + background-size: 100% auto; + margin-left: 5px; + margin-bottom: -3px; + + i { + display: none; + } + } + } + } + + .el-scrollbar__bar.is-horizontal { + display: none; + } + + .el-table th { + background-color: #E8F4FD !important; + } + + .el-table td { + border: none; + } + + .el-table tr { + height: 50px; + } + + .el-table__row { + height: 50px; + } + + .el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf{ + text-align: center; + border-color: #fff; + } +} + +.el-tag { + padding: 14px; + border-radius: 19px; +} + +::-webkit-scrollbar-button { + display: none; +} + +.no-table-scroll { + .el-scrollbar__bar.is-vertical { + display: none; + } + .el-scrollbar__bar.is-horizontal { + display: none; + } +} \ No newline at end of file diff --git a/bmp-console-web/src/assets/css/bmp-step.scss b/bmp-console-web/src/assets/css/bmp-step.scss new file mode 100644 index 0000000..9377602 --- /dev/null +++ b/bmp-console-web/src/assets/css/bmp-step.scss @@ -0,0 +1,80 @@ +.bmp-step { + width: 400px; + margin: 0 auto 20px auto; + // 步骤条 + .el-step{ + .el-step__icon { + width: 26px; + height: 26px; + + } + + // 填写中 + .el-step__head.is-process { + .el-step__icon.is-text { + background-color: #108EF9; + border-color: #108EF9 !important; + .el-step__icon-inner { + color: #fff; + font-weight: 400 !important; + } + } + } + + // 未填写 + .el-step__head.is-wait { + .el-step__icon.is-text { + background-color: #999999; + border-color: #999999 !important; + .el-step__icon-inner { + color: #fff; + font-weight: 400 !important; + } + } + } + + // 已填写 + .el-step__head.is-success { + .el-step__icon.is-text { + background-color: #E8F4FD !important; + border-color: #108EF9 !important; + border-width: 0.5px; + .el-step__icon-inner { + color: #108EF9 !important; + font-weight: 400 !important; + } + } + } + + // 步骤条目 + .el-step__main { + // 填写中 + .el-step__title.is-process { + color: #666666; + font-size: 12px !important; + } + // 未填写 + .el-step__title.is-wait { + color: #666666; + font-size: 12px !important; + } + // 已填写 + .el-step__title.is-success { + color: #666666; + font-size: 12px !important; + } + } + + } + + .el-step.is-center .el-step__line { + height: 1px; + left: 60%; + right: -40%; + background-color: #D4D4D4; + border-color: #D4D4D4; + .el-step__line-inner { + border-width: 0px; + } + } +} \ No newline at end of file diff --git a/bmp-console-web/src/assets/css/clear.scss b/bmp-console-web/src/assets/css/clear.scss new file mode 100644 index 0000000..458d712 --- /dev/null +++ b/bmp-console-web/src/assets/css/clear.scss @@ -0,0 +1,148 @@ +* { + margin: 0; + padding: 0; +} + +li { + list-style: none; +} + +img { + vertical-align: top; + border: none; +} + +body { + font-family: "Microsoft YaHei"; + font-size: 14px; + color: #333; +} + +html, body { + height: 100%; + width: 100%; +} + +h1, +h2, +h3, +h4, +h5, +h6 { + font-size: 100%; + font-weight: normal; +} + +address, +cite, +dfn, +em, +var { + font-style: normal; +} + +/* 将斜体扶正 */ +code, +kbd, +pre, +samp { + font-family: courier new, courier, monospace; +} + +/* 统一等宽字体 */ +small { + font-size: 12px; +} + +/* 小于 12px 的中文很难阅读, 让 small 正常化 */ + +/** 重置列表元素 **/ +ul, +ol { + list-style: none; +} + +/** 重置文本格式元素 **/ +a { + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + +sup { + vertical-align: text-top; +} + +/* 重置, 减少对行高的影响 */ + +sub { + vertical-align: text-bottom; +} + +/** 重置表单元素 **/ +legend { + color: #000; +} + +fieldset, +img { + border: 0; +} + +button, +input, +select, +textarea { + font-size: 100%; +} + +/* 使得表单元素在 ie 下能继承字体大小 */ + +/* 重置 HTML5 元素 */ +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +menu, +nav, +section, +summary, +time, +mark, +audio, +video { + display: block; + margin: 0; + padding: 0; +} + +mark { + background: #ff0; +} + +/* 设置placeholder的默认样式 */ +:-moz-placeholder { + color: #ddd; + opacity: 1; +} + +::-moz-placeholder { + color: #ddd; + opacity: 1; +} + +input:-ms-input-placeholder { + color: #ddd; + opacity: 1; +} + +input::-webkit-input-placeholder { + color: #ddd; + opacity: 1; +} diff --git a/bmp-console-web/src/assets/css/global.scss b/bmp-console-web/src/assets/css/global.scss new file mode 100644 index 0000000..2a9aa5b --- /dev/null +++ b/bmp-console-web/src/assets/css/global.scss @@ -0,0 +1,328 @@ +/*自定义类,下拉菜单是否可选*/ +.bmp-item-disabled { + color: #999 !important; + cursor: not-allowed !important; + pointer-events: all !important; +} + +a{ + text-decoration: none; + &:hover { + text-decoration: none; + } +} + +.mouse-point { + cursor: pointer; +} + +.mt5 { + margin-top: 5px; +} +.mt6 { + margin-top: 6px; +} +.mt-40 { + margin-top: -40px !important; +} +.ml5 { + margin-left: 5px; +} +.ml10 { + margin-left: 10px !important; +} +.ml15 { + margin-left: 15px; +} +.ml20 { + margin-left: 20px; +} +.ml22 { + margin-left: 22px; +} +.ml24 { + margin-left: 24px; +} +.ml32 { + margin-left: 32px; +} +.ml38 { + margin-left: 38px; +} +.ml40 { + margin-left: 40px; +} +.ml60 { + margin-left: 60px; +} +.ml100 { + margin-left: 100px; +} +.mr10 { + margin-right: 10px; +} +.mr5 { + margin-right: 5px; +} +.mt3 { + margin-top: 3px !important; +} +.mt4 { + margin-top: 4px !important; +} +.mt12 { + margin-top: 12px; +} +.mt16 { + margin-top: 16px !important; +} +.mt30 { + margin-top: 30px !important; +} +.mt45 { + margin-top: 45px; +} +.mt60 { + margin-top: 60px !important; +} +.mt2 { + margin-top: 2px; +} +.pt7 { + padding-top: 7px !important; +} +.mb12 { + margin-bottom: 12px; +} +.mb18 { + margin-bottom: 18px; +} +.mb20 { + margin-bottom: 20px !important; +} +.mb50 { + margin-bottom: 50px !important; +} +.mb42 { + margin-bottom: 42px !important; +} +.mb57 { + margin-bottom: 57px !important; +} +.m0 { + margin: 0 !important; +} +.f12 { + font-size: 12px !important; +} +.c999 { + color: #999999 !important; +} +.c333 { + color: #333333 !important; +} +.default-color { + color: #108ef9 !important; +} +.none-display { + display: none; +} +.block-display { + display: block; +} +.change-line { + word-wrap:break-word; + padding-right: -7px; +} +.can-scroll { + overflow: auto !important; +} +.display-flex { + display: flex !important; +} +.pos-fixed { + //position: fixed !important; +} +.t110 { + top: 110px !important; +} + +.t2 { + top:2px; + position: relative; +} + +.t120 { + top: 120px !important; +} + +.b2 { + bottom:2px; + position: relative; +} + +.c333 { + color: #333333; +} + +.mt52 { + margin-top: 52px; +} +.mt32 { + margin-top: 32px; +} +.mt22 { + margin-top: 22px; +} +.pb5 { + padding-bottom: 5px !important; +} +.mb0 { + margin-bottom: 0 !important; +} +.mb28 { + margin-bottom: 28px !important; +} +.mb30 { + margin-bottom: 30px !important; +} +.mb32 { + margin-bottom: 32px !important; +} +.mb6 { + margin-bottom: 6px !important; +} +.mb10 { + margin-bottom: 10px !important; +} +.mt-10 { + margin-top: -10px; +} +.mt10 { + margin-top: 10px; +} +.mt20 { + margin-top: 20px; +} +.mt25 { + margin-top: 25px !important; +} + +.mt50 { + margin-top: 50px; +} +.ml30 { + margin-left: 30px; +} +.ml36{ + margin-left: 36px !important; +} +.ml55 { + margin-left: 55px; +} +.ml22 { + margin-left: 22px; +} +.ml0 { + margin-left: 0 !important; +} +.mr0 { + margin-right: 0 !important; +} +.ml-5 { + margin-left: -5px; +} +.m21 { + margin:0 21px; +} +.pt37 { + padding-top: 37px; +} +.pt40 { + padding-top: 40px; +} +.pt24 { + padding-top: 24px !important; +} +.pt43 { + padding-top: 43px; +} +.pt45 { + padding-top: 45px; +} +.pr7 { + padding-right: 7px; +} + +.mw78 { + min-width: 78px; +} + +.mw114 { + min-width: 114px; +} + +.w350 { + width: 350px; +} + +.w390 { + width: 390px; +} + +.h50 { + height: 50px !important; +} + +.lh12{ + line-height: 12px !important; +} + +.lh22{ + line-height: 22px !important; +} +.lh24{ + line-height: 24px !important; +} +::-webkit-scrollbar { + width: 7px; +} +::-webkit-scrollbar-thumb { + cursor: pointer; + border-radius: 10px; + background:#dcdfe6; + &:hover { + background:#c0c4cc; + + } +} +::-webkit-scrollbar-track { + border-radius: 0; + opacity: 0; +} +.long-row { + font-size: 12px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + float: center; + +} + +.fl { + float: left; +} + +.ta-l { + text-align: left; +} + +:root { + --el-text-color-regular: #333333 !important; +} +.red { + color: #FF4D4F; +} +.h-max { + max-height: 100% !important; +} \ No newline at end of file diff --git a/bmp-console-web/src/assets/css/icon.scss b/bmp-console-web/src/assets/css/icon.scss new file mode 100644 index 0000000..4fccb20 --- /dev/null +++ b/bmp-console-web/src/assets/css/icon.scss @@ -0,0 +1,234 @@ +/*CentOS*/ +.CentOS { + background: url('~@/assets/img/centos@2x.png') no-repeat; + background-size: 35px; +} + +/*Ubuntu*/ +.Ubuntu { + background: url('~@/assets/img/ubuntu@2x.png') no-repeat; + background-size: 35px; +} + +/*Window*/ +.Windows { + background: url('~@/assets/img/windows@2x.png') no-repeat ; + background-size: 35px; +} + +/*Debian*/ +.Debian { + background: url('~@/assets/img/debian@2x.png') no-repeat; + background-size: 35px; +} + +/*OpenEuler*/ +.OpenEuler { + background: url('~@/assets/img/openeuler@2x.png') no-repeat ; + background-size: 35px; +} + +/*Other*/ +.Other { + background: url('~@/assets/img/other-image.png') no-repeat ; + background-size: 35px; +} + + +/*tick*/ +.tick { + background: url('~@/assets/img/tick.png') no-repeat ; + background-size: 16px; +} + +/*已售罄标志*/ +.soldout-zh-i { + background: url('~@/assets/img/soldout-zh-i.png') no-repeat ; + background-size: 40px; +} +.soldout-zh { + background: url('~@/assets/img/soldout-zh.png') no-repeat ; + background-size: 40px; +} +.soldout-en-i { + background: url('~@/assets/img/soldout-en-i.png') no-repeat ; + background-size: 40px; +} +.soldout-en { + background: url('~@/assets/img/soldout-en.png') no-repeat ; + background-size: 40px; +} + +/*computer*/ +.computer { + background: url('~@/assets/img/compute@2x.png') no-repeat ; + vertical-align: middle; + background-size: 14px; +} + +/*GPU*/ +.gpu { + background: url('~@/assets/img/gpu.png') no-repeat ; + vertical-align: middle; + background-size: 15px; +} +/*存储型*/ +.storage { + background: url('~@/assets/img/memory.png') no-repeat ; + vertical-align: middle; + background-size: 15px; +} +/*其它*/ +.other { + background: url('~@/assets/img/other.png') no-repeat ; + vertical-align: middle; + background-size: 15px; +} + +.apiKey { + background: url('~@/assets/img/apiKey.png') no-repeat ; + background-size: 16px; +} + +.apiKeyGrey { + background: url('~@/assets/img/apiKeyGrey.png') no-repeat ; + background-size: 16px; +} + +.sshKey { + background: url('~@/assets/img/sshKey.png') no-repeat ; + background-size: 16px; +} + +.sshKeyGrey { + background: url('~@/assets/img/sshKeyGrey.png') no-repeat ; + background-size: 16px; +} + +.security { + background: url('~@/assets/img/security.png') no-repeat ; + background-size: 16px; +} + +.securityGrey { + background: url('~@/assets/img/securityGrey.png') no-repeat ; + background-size: 16px; +} + +.user { + background: url('~@/assets/img/user.png') no-repeat ; + background-size: 16px; +} + +.userGrey { + background: url('~@/assets/img/userGrey.png') no-repeat ; + background-size: 16px; +} + +.license { + background: url('~@/assets/img/license.png') no-repeat ; + background-size: 16px; +} + +.licenseGrey { + background: url('~@/assets/img/licenseGrey.png') no-repeat ; + background-size: 16px; +} + +.error { + background: url('~@/assets/img/error.png') no-repeat ; + background-size: 13px; +} +.success-icon { + background: url('~@/assets/img/success.png') no-repeat ; + background-size: 16px; +} + +.fail-icon { + background: url('~@/assets/img/fail.png') no-repeat ; + background-size: 16px; +} + +.doing { + background: url('~@/assets/img/doing.png') no-repeat ; + background-size: 16px; +} + +.list { + background: url('~@/assets/img/list.png') no-repeat ; + background-size: 16px; +} + +.desc { + background: url('~@/assets/img/describe.png') no-repeat ; + background-size: 16px; +} + +.folder { + background: url('~@/assets/img/folder.png') no-repeat ; + background-size: 16px; +} + +.settings { + background: url('~@/assets/img/setting.png') no-repeat; + background-size: 16px; +} + +.logout { + background: url('~@/assets/img/logout.png') no-repeat ; + background-size: 16px; +} + +.noData { + // background: url('~@/assets/img/noData.png') no-repeat; + width: 400px; + height: 200px; + margin:0 auto; + margin-top: 100px; + display: none; +} + +.no-data-list { + display: none; +} + +.monitor { + background: url('~@/assets/img/monitor.png') no-repeat ; + background-size: 16px; + &:hover { + background: url('~@/assets/img/monitorHover.png') no-repeat ; + background-size: 16px; + } +} + +.dialog-icon { + display: inline-block; + width: 16px; + height: 16px; + margin-right: 10px; + vertical-align: sub; +} + +.error-icon { + display: inline-block; + width: 16px; + height: 16px; + margin-right: 10px; + vertical-align: middle; +} + +.list-icon { + display: inline-block; + width: 16px; + height: 16px; + margin-right: 5px; + vertical-align: sub; +} + +.instance-list-icon { + display: inline-block; + width: 16px; + height: 16px; + vertical-align: sub; + cursor: pointer; +} \ No newline at end of file diff --git a/bmp-console-web/src/assets/css/list.scss b/bmp-console-web/src/assets/css/list.scss new file mode 100644 index 0000000..1c337fe --- /dev/null +++ b/bmp-console-web/src/assets/css/list.scss @@ -0,0 +1,106 @@ +.operation-header { + .setting-position { + display: flex; + height: 30px; + margin-right: 30px; + margin-top: -10px; + float: right; + .operate-ipt { + display: flex; + align-items: center; + margin-top: 22px; + margin-right: 30px; + } + .el-button--text { + &:hover{ + color: #108EF9 !important; + } + } + .operate-refresh, + .operate-set-up, + .no-export, + .operate-export { + display: flex; + align-items: center; + margin-right: 20px; + margin-top: 22px; + cursor: pointer; + + .my-update-gray, + .my-settings-gray, + .my-download-gray { + width: 16px; + height: 16px; + background-size: 100% auto !important; + background-position: center center; + background-repeat: no-repeat; + margin-right: 5px; + } + + .refresh-title, + .set-up-title, + .export-title { + font-size: 12px; + } + + &:hover { + color: #108EF9; + } + } + + .operate-refresh { + .my-update-gray { + background-image: url('~@/assets/img/updateGray.png'); + } + + &:hover { + .my-update-gray { + background-image: url('~@/assets/img/update.png'); + } + } + } + + .operate-set-up { + .my-settings-gray { + background-image: url('~@/assets/img/settingGray.png'); + } + + &:hover { + .my-settings-gray { + background-image: url('~@/assets/img/setting.png'); + } + } + } + + .no-export { + margin-right: 0; + pointer-events: none; + color: #333; + + .my-download-gray { + background-image: url('~@/assets/img/downloadGray.png'); + } + + &:hover { + color: #333; + .my-download-gray { + background-image: url('~@/assets/img/download.png'); + } + } + } + + .operate-export { + margin-right: 0; + + .my-download-gray { + background-image: url('~@/assets/img/downloadGray.png'); + } + + &:hover { + .my-download-gray { + background-image: url('~@/assets/img/download.png'); + } + } + } + } +} diff --git a/bmp-console-web/src/assets/css/middleDialog.scss b/bmp-console-web/src/assets/css/middleDialog.scss new file mode 100644 index 0000000..33fd6aa --- /dev/null +++ b/bmp-console-web/src/assets/css/middleDialog.scss @@ -0,0 +1,96 @@ +.middle-dialog { + .my-title { + height: 26px; + font-size: 14px; + color: #108EE9; + } + .close-button { + width: 23px; + height: 23px; + position: absolute; + right: -10px; + top: -10px; + box-shadow:0 1px 3px 0 #000000 0.5; + &:hover { + background-color: rgba(255,255,255,0.8); + border-color: rgba(255,255,255,0.8); + box-shadow:0 1px 3px 0 #000000 0.5; + } + } + .el-overlay { + background-color: rgba(217,217,221,0.6); + } + .error-tip-content { + padding: 10px; + background-color: #F9ECEE; + font-size: 12px; + } + .el-overlay-dialog { + display: flex; + } + .el-dialog { + background-color: rgba(255,255,255,0.8); + --el-dialog-width: 640px; + min-height: 360px; + margin: auto; + border-radius: 10px; + box-shadow:0 1px 3px 0 #000000 0.5; + backdrop-filter: blur(13px); + .el-dialog__header { + padding: 14px 0 10px 0; + margin: 0 20px 10px 20px; + text-align: left; + border-bottom: 1px solid #F0F0F0; + } + .el-dialog__body { + min-height: 190px; + padding: 10px 20px 30px 20px; + + .el-select { + width: 204px; + } + .el-input { + width: 204px; + } + .el-textarea { + width: 483px; + font-size: 12px; + } + } + .dialog-body-content { + position: relative; + } + .el-dialog__footer { + padding: 20px; + margin: 0 20px; + border-top: 1px solid #F0F0F0; + .el-button { + width: 100px; + height: 30px; + font-size: 12px; + border-radius: 4px; + } + .el-button+.el-button { + margin-left: 20px; + } + + .cancel-button { + background-color: #EEEEEE; + border-color: #EEEEEE; + color: #666666; + &:active { + background-color: #DFDFDF; + border-color: #DFDFDF; + } + &:hover { + border-color: #EEEEEE; + } + } + } + } + .el-form-item__error { + text-align: left; + line-height: 14px; + } + +} \ No newline at end of file diff --git a/bmp-console-web/src/assets/css/page.scss b/bmp-console-web/src/assets/css/page.scss new file mode 100644 index 0000000..57b75dc --- /dev/null +++ b/bmp-console-web/src/assets/css/page.scss @@ -0,0 +1,180 @@ +.page-position { + background-color: #EFF2F5; + height: calc(100vh); + --el-text-color-regular:#333333; +} + +.page-content { + position: relative; + background-color: white; + clear: both; + width: 1200px; + min-height: calc(100vh - 160px); + top: 137px; + left: 0; + right: 0; + bottom: 20px; + margin: 0 auto; + padding-top: 30px; + padding-bottom: 50px; + box-shadow:0 1px 3px 0 #000000 0.5; + border-radius:10px; + .el-button--primary { + &:hover { + background-color: #108EF9; + border-color: #108EF9; + } + &:focus { + background-color: #108EF9; + border-color: #108EF9; + } + &:active { + background-color: #0F81D4; + border-color: #0F81D4; + } + + } + .el-button--primary:hover { + &.is-disabled { + background-color: #91D5FF !important; + border-color: #91D5FF !important; + } + } + .el-input { + border-color: #979797; + } + .el-radio-button__inner { + border-color: #979797; + } + + // 表单验证提示位置修改 + .el-form-item.is-error { + margin-bottom: 42px; + } + // 表单验证提示位置修改 + .el-form-item__error { + margin-top: 5px; + line-height: normal !important; + } +} + +.section-title { + height: 20px; + font-weight: bold; + color: #108EF9; + padding: 0 0 0 20px; + margin-bottom: 20px; + border-left: 2px solid #108EF9; + span { + font-weight: 400; + font-size: 12px; + color: #333; + line-height: 20px; + vertical-align: bottom; + } +} + +.detail-header { + position: relative; + top: 122px; + left: 0; + right: 0; + margin: 0 auto; + padding-bottom: 10px; + width: 1200px; +} + +a { + text-decoration:none; + color: #108EF9; +} + +a :hover { + text-decoration:none !important +} +.f14 { + font-size: 14px !important; +} +.fw400 { + font-weight: 400; +} +.fw600 { + font-weight: 600; +} +:root { + --el-color-primary: #108EF9; + --el-border-color-hover:#108EF9 +} + +.el-radio-button { + --el-radio-button-checked-border-color:#108EF9; +} + +.el-radio-button :hover { + border-color: #108EF9; + &.is-disabled { + border-color: #666666; + } +} + +.el-radio-button__inner :hover { + border-left:1px soild #108EF9 ; + border-color: #108EF9 !important; +} + + +.el-form-item__label { + font-size: 12px; +} + +.el-input__inner { + font-size: 12px; +} + +.el-select-dropdown__item { + font-size: 12px; +} + +.batch-operation-button { + vertical-align: middle; + font-size: 12px; + color: #108EF9; + margin-bottom: 4px; +} + +.operate-export { + +} + +.no-export { + pointer-events: none; +} + +.el-textarea { + .el-textarea__inner { + resize: none; + } +} + +.el-popper.is-pure { + .el-checkbox__label { + font-size: 12px; + } + + .el-table-filter__bottom { + display: flex; + justify-content: space-around; + + button { + font-size: 12px; + } + } + + .el-menu--popup { + min-width: 100px; + .el-menu-item { + justify-content: center; + font-size: 14px; + } + } +} \ No newline at end of file diff --git a/bmp-console-web/src/assets/css/smallDialog.scss b/bmp-console-web/src/assets/css/smallDialog.scss new file mode 100644 index 0000000..1b5954a --- /dev/null +++ b/bmp-console-web/src/assets/css/smallDialog.scss @@ -0,0 +1,127 @@ +.small-dialog { + --el-button-hover-bg-color: #108EF9; + --el-button-hover-border-color: #108EF9; + & .ta-l { + .el-dialog { + .el-dialog__body { + text-align: left !important; + } + } + } + .my-title { + height: 26px; + font-size: 14px; + color: #108EF9; + } + .close-button { + width: 23px; + height: 23px; + position: absolute; + right: -10px; + top: -10px; + box-shadow:0 1px 3px 0 #000000 0.5; + &:hover { + background-color: rgba(255,255,255,0.8); + border-color: rgba(255,255,255,0.8); + box-shadow:0 1px 3px 0 #000000 0.5; + } + } + .el-overlay { + background-color: rgba(217,217,221,0.6); + } + .error-tip-content { + padding: 10px; + background-color: #F9ECEE; + font-size: 12px; + } + .el-overlay-dialog { + display: flex; + } + .el-dialog { + background-color: rgba(255,255,255,0.8); + --el-dialog-width: 520px; + height:292px; + margin: auto; + border-radius: 10px; + box-shadow:0 1px 3px 0 #000000 0.5; + backdrop-filter: blur(13px); + .el-dialog__header { + padding: 14px 0 10px 0; + margin: 0 20px 10px 20px; + text-align: left; + border-bottom: 1px solid #F0F0F0; + } + .el-dialog__body { + height: 122px; + padding: 10px 20px 30px 20px; + text-align: center; + .el-select{ + width: 204px; + } + .el-input{ + width: 204px; + } + } + .dialog-body-content { + position: relative; + top: 50%; + transform: translateY(-70%); + } + .el-dialog__footer { + padding: 20px; + margin: 0 20px; + border-top: 1px solid #F0F0F0; + .el-button { + width: 100px; + height: 30px; + font-size: 12px; + border-radius: 4px; + } + .el-button+.el-button { + margin-left: 20px; + } + + .cancel-button { + background-color: #EEEEEE !important; + border-color: #EEEEEE !important; + color: #666666; + &:active { + background-color: #DFDFDF !important; + border-color: #DFDFDF !important; + } + &:hover { + background-color: #EEEEEE !important; + border-color: #EEEEEE !important; + } + } + + .confirm-button { + background-color: #108EF9 !important; + border-color: #108EF9 !important; + color: #EEEEEE; + &:active { + background-color: #108EF9 !important; + border-color: #108EF9 !important; + } + &:hover { + background-color: #108EF9 !important; + border-color: #108EF9 !important; + } + } + } + } + .el-form-item__error { + text-align: left; + line-height: 14px; + } + +} + +.no-center { + .el-dialog { + .dialog-body-content { + top: 0; + transform: translateY(0%); + } + } +} \ No newline at end of file diff --git a/bmp-console-web/src/assets/css/table.scss b/bmp-console-web/src/assets/css/table.scss new file mode 100644 index 0000000..02fe9bc --- /dev/null +++ b/bmp-console-web/src/assets/css/table.scss @@ -0,0 +1,123 @@ +.table-content { + margin: 20px 29px; + .el-table { + //overflow: auto; + //max-height: calc(100vh - 300px); + height: 100%; + font-size: 12px; + color: #333333; + border-radius: 5px; + //--el-table-border-color: white; + //--el-table-border: 1px solid white; + &--border { + &::after, + &::before { + display: none; + } + } + + &__border-left-patch { + display: none; + } + + &-column--selection { + border-left: 0 !important; + border-right: 0 !important; + } + &-fixed-column--left { + border-left: 0 !important; + border-color: #fff !important; + // border-right: 0 !important; + } + + } + + .el-table__inner-wrapper { + + &::after, + &::before { + display: none; + } + } + + .el-table__inner-wrapper tr:first-child td:first-child{ + border-left: 0 !important; + border-color: #fff !important; + } + + .cell { + padding: 0 16px; + } + + .el-table__body-wrapper { + border-top: 2px solid white; + } + + .el-table__header-wrapper { + .cell { + color: #333333; + display: flex; + align-items: center; + justify-content: center; + .el-table__column-filter-trigger { + width: 16px; + height: 16px; + background: url('~@/assets/img/arrowDown.png') center center no-repeat; + background-size: 100% auto; + margin-left: 5px; + margin-bottom: -3px; + + i { + display: none; + } + } + } + } + + // .el-scrollbar__bar.is-vertical { + // display: none; + // } + + .el-table th { + background-color: #E8F4FD !important; + } + + .el-table td { + border: none; + } + + .el-table tr { + height: 50px; + } + + .el-table__row { + height: 50px; + } + + .el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf{ + text-align: center; + border-color: #fff; + } +} + +.el-table-filter { + inset: 14px -20px auto auto !important; +} + +.el-tag { + padding: 14px; + border-radius: 19px; +} + +::-webkit-scrollbar-button { + display: none; +} + +.no-table-scroll { + .el-scrollbar__bar.is-vertical { + display: none; + } + .el-scrollbar__bar.is-horizontal { + display: none; + } +} \ No newline at end of file diff --git a/bmp-console-web/src/assets/css/tagColor.scss b/bmp-console-web/src/assets/css/tagColor.scss new file mode 100644 index 0000000..cc1a5a1 --- /dev/null +++ b/bmp-console-web/src/assets/css/tagColor.scss @@ -0,0 +1,39 @@ +.el-tag--plain.el-tag--success { + --el-tag-border-color:#43B561; + --el-tag-text-color:#43B561; +} + +.el-tag--plain.el-tag--info { + --el-tag-border-color:#999999; + --el-tag-text-color:#999999; +} + +.el-tag--plain.el-tag--danger { + --el-tag-border-color:#ff4d4f; + --el-tag-text-color:#ff4d4f; +} +.el-tag--plain { + --el-tag-border-color:#9254DE; + --el-tag-text-color:#9254DE; +} + +.el-tag--dark.el-tag--success { + --el-tag-bg-color: #43B561; + --el-tag-border-color: #43B561; + --el-tag-text-color: #fff; + --el-tag-hover-color: #43B561; +} + +.el-tag--dark.el-tag--warning { + --el-tag-bg-color: #999999; + --el-tag-border-color: #999999; + --el-tag-text-color: #fff; + --el-tag-hover-color: #999999; +} + +.el-tag--dark.el-tag--danger { + --el-tag-bg-color: #ff4d4f; + --el-tag-border-color: #ff4d4f; + --el-tag-text-color: #fff; + --el-tag-hover-color: #ff4d4f; +} \ No newline at end of file diff --git a/bmp-console-web/src/assets/img/add-default.png b/bmp-console-web/src/assets/img/add-default.png new file mode 100644 index 0000000..813ebb4 Binary files /dev/null and b/bmp-console-web/src/assets/img/add-default.png differ diff --git a/bmp-console-web/src/assets/img/add-hover-active.png b/bmp-console-web/src/assets/img/add-hover-active.png new file mode 100644 index 0000000..6776349 Binary files /dev/null and b/bmp-console-web/src/assets/img/add-hover-active.png differ diff --git a/bmp-console-web/src/assets/img/apiKey.png b/bmp-console-web/src/assets/img/apiKey.png new file mode 100644 index 0000000..10faf0d Binary files /dev/null and b/bmp-console-web/src/assets/img/apiKey.png differ diff --git a/bmp-console-web/src/assets/img/apiKeyGrey.png b/bmp-console-web/src/assets/img/apiKeyGrey.png new file mode 100644 index 0000000..bdafd44 Binary files /dev/null and b/bmp-console-web/src/assets/img/apiKeyGrey.png differ diff --git a/bmp-console-web/src/assets/img/arrow-bottom.png b/bmp-console-web/src/assets/img/arrow-bottom.png new file mode 100644 index 0000000..5e4ad03 Binary files /dev/null and b/bmp-console-web/src/assets/img/arrow-bottom.png differ diff --git a/bmp-console-web/src/assets/img/arrow.png b/bmp-console-web/src/assets/img/arrow.png new file mode 100644 index 0000000..870ca65 Binary files /dev/null and b/bmp-console-web/src/assets/img/arrow.png differ diff --git a/bmp-console-web/src/assets/img/arrowDown.png b/bmp-console-web/src/assets/img/arrowDown.png new file mode 100644 index 0000000..58254d6 Binary files /dev/null and b/bmp-console-web/src/assets/img/arrowDown.png differ diff --git a/bmp-console-web/src/assets/img/arrowLeft.png b/bmp-console-web/src/assets/img/arrowLeft.png new file mode 100644 index 0000000..0e908c6 Binary files /dev/null and b/bmp-console-web/src/assets/img/arrowLeft.png differ diff --git a/bmp-console-web/src/assets/img/big-size.png b/bmp-console-web/src/assets/img/big-size.png new file mode 100644 index 0000000..e82467c Binary files /dev/null and b/bmp-console-web/src/assets/img/big-size.png differ diff --git a/bmp-console-web/src/assets/img/centos@2x.png b/bmp-console-web/src/assets/img/centos@2x.png new file mode 100644 index 0000000..5039870 Binary files /dev/null and b/bmp-console-web/src/assets/img/centos@2x.png differ diff --git a/bmp-console-web/src/assets/img/clear.png b/bmp-console-web/src/assets/img/clear.png new file mode 100644 index 0000000..7323cf1 Binary files /dev/null and b/bmp-console-web/src/assets/img/clear.png differ diff --git a/bmp-console-web/src/assets/img/clearInput.png b/bmp-console-web/src/assets/img/clearInput.png new file mode 100644 index 0000000..0d1afde Binary files /dev/null and b/bmp-console-web/src/assets/img/clearInput.png differ diff --git a/bmp-console-web/src/assets/img/close-eye.png b/bmp-console-web/src/assets/img/close-eye.png new file mode 100644 index 0000000..1652324 Binary files /dev/null and b/bmp-console-web/src/assets/img/close-eye.png differ diff --git a/bmp-console-web/src/assets/img/compute.png b/bmp-console-web/src/assets/img/compute.png new file mode 100644 index 0000000..1bba4ee Binary files /dev/null and b/bmp-console-web/src/assets/img/compute.png differ diff --git a/bmp-console-web/src/assets/img/compute@2x.png b/bmp-console-web/src/assets/img/compute@2x.png new file mode 100644 index 0000000..94f0057 Binary files /dev/null and b/bmp-console-web/src/assets/img/compute@2x.png differ diff --git a/bmp-console-web/src/assets/img/copy.png b/bmp-console-web/src/assets/img/copy.png new file mode 100644 index 0000000..506a329 Binary files /dev/null and b/bmp-console-web/src/assets/img/copy.png differ diff --git a/bmp-console-web/src/assets/img/debian@2x.png b/bmp-console-web/src/assets/img/debian@2x.png new file mode 100644 index 0000000..e142ffc Binary files /dev/null and b/bmp-console-web/src/assets/img/debian@2x.png differ diff --git a/bmp-console-web/src/assets/img/default.png b/bmp-console-web/src/assets/img/default.png new file mode 100644 index 0000000..e232f1a Binary files /dev/null and b/bmp-console-web/src/assets/img/default.png differ diff --git a/bmp-console-web/src/assets/img/describe.png b/bmp-console-web/src/assets/img/describe.png new file mode 100644 index 0000000..cd76e31 Binary files /dev/null and b/bmp-console-web/src/assets/img/describe.png differ diff --git a/bmp-console-web/src/assets/img/doing.png b/bmp-console-web/src/assets/img/doing.png new file mode 100644 index 0000000..c0ec39b Binary files /dev/null and b/bmp-console-web/src/assets/img/doing.png differ diff --git a/bmp-console-web/src/assets/img/download.png b/bmp-console-web/src/assets/img/download.png new file mode 100644 index 0000000..1e676b7 Binary files /dev/null and b/bmp-console-web/src/assets/img/download.png differ diff --git a/bmp-console-web/src/assets/img/downloadGray.png b/bmp-console-web/src/assets/img/downloadGray.png new file mode 100644 index 0000000..870b73f Binary files /dev/null and b/bmp-console-web/src/assets/img/downloadGray.png differ diff --git a/bmp-console-web/src/assets/img/error.png b/bmp-console-web/src/assets/img/error.png new file mode 100644 index 0000000..160c9cf Binary files /dev/null and b/bmp-console-web/src/assets/img/error.png differ diff --git a/bmp-console-web/src/assets/img/fail.png b/bmp-console-web/src/assets/img/fail.png new file mode 100644 index 0000000..702ca13 Binary files /dev/null and b/bmp-console-web/src/assets/img/fail.png differ diff --git a/bmp-console-web/src/assets/img/failedTip.png b/bmp-console-web/src/assets/img/failedTip.png new file mode 100644 index 0000000..4206b21 Binary files /dev/null and b/bmp-console-web/src/assets/img/failedTip.png differ diff --git a/bmp-console-web/src/assets/img/folder.png b/bmp-console-web/src/assets/img/folder.png new file mode 100644 index 0000000..774d226 Binary files /dev/null and b/bmp-console-web/src/assets/img/folder.png differ diff --git a/bmp-console-web/src/assets/img/gpu.png b/bmp-console-web/src/assets/img/gpu.png new file mode 100644 index 0000000..12a2314 Binary files /dev/null and b/bmp-console-web/src/assets/img/gpu.png differ diff --git a/bmp-console-web/src/assets/img/gpuGray.png b/bmp-console-web/src/assets/img/gpuGray.png new file mode 100644 index 0000000..4aef957 Binary files /dev/null and b/bmp-console-web/src/assets/img/gpuGray.png differ diff --git a/bmp-console-web/src/assets/img/have-message-tip.png b/bmp-console-web/src/assets/img/have-message-tip.png new file mode 100644 index 0000000..e60358d Binary files /dev/null and b/bmp-console-web/src/assets/img/have-message-tip.png differ diff --git a/bmp-console-web/src/assets/img/license.png b/bmp-console-web/src/assets/img/license.png new file mode 100644 index 0000000..62d9e44 Binary files /dev/null and b/bmp-console-web/src/assets/img/license.png differ diff --git a/bmp-console-web/src/assets/img/licenseGrey.png b/bmp-console-web/src/assets/img/licenseGrey.png new file mode 100644 index 0000000..6bdc368 Binary files /dev/null and b/bmp-console-web/src/assets/img/licenseGrey.png differ diff --git a/bmp-console-web/src/assets/img/list.png b/bmp-console-web/src/assets/img/list.png new file mode 100644 index 0000000..797b408 Binary files /dev/null and b/bmp-console-web/src/assets/img/list.png differ diff --git a/bmp-console-web/src/assets/img/logout.png b/bmp-console-web/src/assets/img/logout.png new file mode 100644 index 0000000..cfd6a04 Binary files /dev/null and b/bmp-console-web/src/assets/img/logout.png differ diff --git a/bmp-console-web/src/assets/img/memory.png b/bmp-console-web/src/assets/img/memory.png new file mode 100644 index 0000000..6c6e466 Binary files /dev/null and b/bmp-console-web/src/assets/img/memory.png differ diff --git a/bmp-console-web/src/assets/img/memoryGray.png b/bmp-console-web/src/assets/img/memoryGray.png new file mode 100644 index 0000000..a03928b Binary files /dev/null and b/bmp-console-web/src/assets/img/memoryGray.png differ diff --git a/bmp-console-web/src/assets/img/monitor.png b/bmp-console-web/src/assets/img/monitor.png new file mode 100644 index 0000000..20eed61 Binary files /dev/null and b/bmp-console-web/src/assets/img/monitor.png differ diff --git a/bmp-console-web/src/assets/img/monitorHover.png b/bmp-console-web/src/assets/img/monitorHover.png new file mode 100644 index 0000000..bce30db Binary files /dev/null and b/bmp-console-web/src/assets/img/monitorHover.png differ diff --git a/bmp-console-web/src/assets/img/no-message-tip.png b/bmp-console-web/src/assets/img/no-message-tip.png new file mode 100644 index 0000000..481ba03 Binary files /dev/null and b/bmp-console-web/src/assets/img/no-message-tip.png differ diff --git a/bmp-console-web/src/assets/img/open-eye.png b/bmp-console-web/src/assets/img/open-eye.png new file mode 100644 index 0000000..511354a Binary files /dev/null and b/bmp-console-web/src/assets/img/open-eye.png differ diff --git a/bmp-console-web/src/assets/img/openeuler@2x.png b/bmp-console-web/src/assets/img/openeuler@2x.png new file mode 100644 index 0000000..1e9e4cd Binary files /dev/null and b/bmp-console-web/src/assets/img/openeuler@2x.png differ diff --git a/bmp-console-web/src/assets/img/other-image.png b/bmp-console-web/src/assets/img/other-image.png new file mode 100644 index 0000000..2bc4b05 Binary files /dev/null and b/bmp-console-web/src/assets/img/other-image.png differ diff --git a/bmp-console-web/src/assets/img/other.png b/bmp-console-web/src/assets/img/other.png new file mode 100644 index 0000000..90360d0 Binary files /dev/null and b/bmp-console-web/src/assets/img/other.png differ diff --git a/bmp-console-web/src/assets/img/otherGray.png b/bmp-console-web/src/assets/img/otherGray.png new file mode 100644 index 0000000..755b63b Binary files /dev/null and b/bmp-console-web/src/assets/img/otherGray.png differ diff --git a/bmp-console-web/src/assets/img/reduce-default.png b/bmp-console-web/src/assets/img/reduce-default.png new file mode 100644 index 0000000..d21dfcb Binary files /dev/null and b/bmp-console-web/src/assets/img/reduce-default.png differ diff --git a/bmp-console-web/src/assets/img/reduce-grey.png b/bmp-console-web/src/assets/img/reduce-grey.png new file mode 100644 index 0000000..e8ec8fc Binary files /dev/null and b/bmp-console-web/src/assets/img/reduce-grey.png differ diff --git a/bmp-console-web/src/assets/img/reduce-hover.png b/bmp-console-web/src/assets/img/reduce-hover.png new file mode 100644 index 0000000..90b487b Binary files /dev/null and b/bmp-console-web/src/assets/img/reduce-hover.png differ diff --git a/bmp-console-web/src/assets/img/refresh.png b/bmp-console-web/src/assets/img/refresh.png new file mode 100644 index 0000000..85bb2d2 Binary files /dev/null and b/bmp-console-web/src/assets/img/refresh.png differ diff --git a/bmp-console-web/src/assets/img/search-icon.png b/bmp-console-web/src/assets/img/search-icon.png new file mode 100644 index 0000000..bc33098 Binary files /dev/null and b/bmp-console-web/src/assets/img/search-icon.png differ diff --git a/bmp-console-web/src/assets/img/security.png b/bmp-console-web/src/assets/img/security.png new file mode 100644 index 0000000..66e3ef1 Binary files /dev/null and b/bmp-console-web/src/assets/img/security.png differ diff --git a/bmp-console-web/src/assets/img/securityGrey.png b/bmp-console-web/src/assets/img/securityGrey.png new file mode 100644 index 0000000..f9cbb66 Binary files /dev/null and b/bmp-console-web/src/assets/img/securityGrey.png differ diff --git a/bmp-console-web/src/assets/img/setting.png b/bmp-console-web/src/assets/img/setting.png new file mode 100644 index 0000000..481b2de Binary files /dev/null and b/bmp-console-web/src/assets/img/setting.png differ diff --git a/bmp-console-web/src/assets/img/settingGray.png b/bmp-console-web/src/assets/img/settingGray.png new file mode 100644 index 0000000..22452cf Binary files /dev/null and b/bmp-console-web/src/assets/img/settingGray.png differ diff --git a/bmp-console-web/src/assets/img/settings.png b/bmp-console-web/src/assets/img/settings.png new file mode 100644 index 0000000..8277efa Binary files /dev/null and b/bmp-console-web/src/assets/img/settings.png differ diff --git a/bmp-console-web/src/assets/img/soldout-en-i.png b/bmp-console-web/src/assets/img/soldout-en-i.png new file mode 100644 index 0000000..5822eaa Binary files /dev/null and b/bmp-console-web/src/assets/img/soldout-en-i.png differ diff --git a/bmp-console-web/src/assets/img/soldout-en.png b/bmp-console-web/src/assets/img/soldout-en.png new file mode 100644 index 0000000..d1416b4 Binary files /dev/null and b/bmp-console-web/src/assets/img/soldout-en.png differ diff --git a/bmp-console-web/src/assets/img/soldout-zh-i.png b/bmp-console-web/src/assets/img/soldout-zh-i.png new file mode 100644 index 0000000..821902e Binary files /dev/null and b/bmp-console-web/src/assets/img/soldout-zh-i.png differ diff --git a/bmp-console-web/src/assets/img/soldout-zh.png b/bmp-console-web/src/assets/img/soldout-zh.png new file mode 100644 index 0000000..dfa823d Binary files /dev/null and b/bmp-console-web/src/assets/img/soldout-zh.png differ diff --git a/bmp-console-web/src/assets/img/sshKey.png b/bmp-console-web/src/assets/img/sshKey.png new file mode 100644 index 0000000..c4506ed Binary files /dev/null and b/bmp-console-web/src/assets/img/sshKey.png differ diff --git a/bmp-console-web/src/assets/img/sshKeyGrey.png b/bmp-console-web/src/assets/img/sshKeyGrey.png new file mode 100644 index 0000000..81050b3 Binary files /dev/null and b/bmp-console-web/src/assets/img/sshKeyGrey.png differ diff --git a/bmp-console-web/src/assets/img/success.png b/bmp-console-web/src/assets/img/success.png new file mode 100644 index 0000000..1cb825a Binary files /dev/null and b/bmp-console-web/src/assets/img/success.png differ diff --git a/bmp-console-web/src/assets/img/switch.png b/bmp-console-web/src/assets/img/switch.png new file mode 100644 index 0000000..450e41b Binary files /dev/null and b/bmp-console-web/src/assets/img/switch.png differ diff --git a/bmp-console-web/src/assets/img/tick.png b/bmp-console-web/src/assets/img/tick.png new file mode 100644 index 0000000..bc6b435 Binary files /dev/null and b/bmp-console-web/src/assets/img/tick.png differ diff --git a/bmp-console-web/src/assets/img/tooltip.png b/bmp-console-web/src/assets/img/tooltip.png new file mode 100644 index 0000000..2472ee4 Binary files /dev/null and b/bmp-console-web/src/assets/img/tooltip.png differ diff --git a/bmp-console-web/src/assets/img/ubuntu@2x.png b/bmp-console-web/src/assets/img/ubuntu@2x.png new file mode 100644 index 0000000..1c4651c Binary files /dev/null and b/bmp-console-web/src/assets/img/ubuntu@2x.png differ diff --git a/bmp-console-web/src/assets/img/update.png b/bmp-console-web/src/assets/img/update.png new file mode 100644 index 0000000..85bb2d2 Binary files /dev/null and b/bmp-console-web/src/assets/img/update.png differ diff --git a/bmp-console-web/src/assets/img/updateGray.png b/bmp-console-web/src/assets/img/updateGray.png new file mode 100644 index 0000000..a86c73c Binary files /dev/null and b/bmp-console-web/src/assets/img/updateGray.png differ diff --git a/bmp-console-web/src/assets/img/user-icon.png b/bmp-console-web/src/assets/img/user-icon.png new file mode 100644 index 0000000..33f7eb9 Binary files /dev/null and b/bmp-console-web/src/assets/img/user-icon.png differ diff --git a/bmp-console-web/src/assets/img/user-login.png b/bmp-console-web/src/assets/img/user-login.png new file mode 100644 index 0000000..6189fe4 Binary files /dev/null and b/bmp-console-web/src/assets/img/user-login.png differ diff --git a/bmp-console-web/src/assets/img/user.png b/bmp-console-web/src/assets/img/user.png new file mode 100644 index 0000000..ea3f73e Binary files /dev/null and b/bmp-console-web/src/assets/img/user.png differ diff --git a/bmp-console-web/src/assets/img/userGrey.png b/bmp-console-web/src/assets/img/userGrey.png new file mode 100644 index 0000000..ed02327 Binary files /dev/null and b/bmp-console-web/src/assets/img/userGrey.png differ diff --git a/bmp-console-web/src/assets/img/warning-tip.png b/bmp-console-web/src/assets/img/warning-tip.png new file mode 100644 index 0000000..292842b Binary files /dev/null and b/bmp-console-web/src/assets/img/warning-tip.png differ diff --git a/bmp-console-web/src/assets/img/windows@2x.png b/bmp-console-web/src/assets/img/windows@2x.png new file mode 100644 index 0000000..e7e8bcc Binary files /dev/null and b/bmp-console-web/src/assets/img/windows@2x.png differ diff --git a/bmp-console-web/src/assets/logo.png b/bmp-console-web/src/assets/logo.png new file mode 100644 index 0000000..f3d2503 Binary files /dev/null and b/bmp-console-web/src/assets/logo.png differ diff --git a/bmp-console-web/src/components/AlarmRuleOperate/alarmRuleDelete.vue b/bmp-console-web/src/components/AlarmRuleOperate/alarmRuleDelete.vue new file mode 100644 index 0000000..8f01656 --- /dev/null +++ b/bmp-console-web/src/components/AlarmRuleOperate/alarmRuleDelete.vue @@ -0,0 +1,132 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/AlarmRuleOperate/alarmRuleDisable.vue b/bmp-console-web/src/components/AlarmRuleOperate/alarmRuleDisable.vue new file mode 100644 index 0000000..ac4a9b1 --- /dev/null +++ b/bmp-console-web/src/components/AlarmRuleOperate/alarmRuleDisable.vue @@ -0,0 +1,132 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/AlarmRuleOperate/alarmRuleEnable.vue b/bmp-console-web/src/components/AlarmRuleOperate/alarmRuleEnable.vue new file mode 100644 index 0000000..871101e --- /dev/null +++ b/bmp-console-web/src/components/AlarmRuleOperate/alarmRuleEnable.vue @@ -0,0 +1,132 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/AlarmRuleOperate/alarmRuleHistory.vue b/bmp-console-web/src/components/AlarmRuleOperate/alarmRuleHistory.vue new file mode 100644 index 0000000..3f608c5 --- /dev/null +++ b/bmp-console-web/src/components/AlarmRuleOperate/alarmRuleHistory.vue @@ -0,0 +1,546 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/BmpHeader/bmpHeader.scss b/bmp-console-web/src/components/BmpHeader/bmpHeader.scss new file mode 100644 index 0000000..df89730 --- /dev/null +++ b/bmp-console-web/src/components/BmpHeader/bmpHeader.scss @@ -0,0 +1,215 @@ +.bmp-content { + height: 57px; + background: #fff; + box-shadow: 0 0 5px 0 hsl(0deg 0% 60% / 50%); + display: flex; + align-items: center; + justify-content: space-between; + position: fixed; + width: 100%; + z-index: 10; +} +.header-content { + display: flex; + align-items: center; + justify-content: flex-end; + width: 1435px; + margin: 0 auto; + height: 70px; + .bmp-logo { + display: flex; + align-items: center; + cursor: pointer; + .bmp-img { + width: 18px; + height: 18px; + transform: scale(2); + margin-right: 20px; + } + .message-img { + width: 16px; + height: 16px; + margin-right: 20px; + } + } +} + +.logo-content { + height: 30px; + margin-right: 30px; + font-size: 22px; + +} + +.icon-size { + width: 17px; + height: 17px; +} + +.mr15 { + margin-right: 15px; +} + +.menu-size { + margin-right: auto; + +} + +.el-dropdown__popper .el-dropdown-menu--default { + max-height: 288px; + overflow-y: auto; + overflow-x: hidden; +} + +.button-change { + color: #999999 ; + margin-right: 15px; + .el-button--text { + color: #999999 ; + margin-right: 12px; + } + + .el-button--text:focus, .el-button--text:hover { + background-color: #FFFFFF; + border-color: #FFFFFF; + color: #333333; + } + + .header-disabled { + font-size: 12px; + color: #999; + font-weight: 400; + } + + .header-optional { + font-size: 12px; + color: #333; + font-weight: 600; + } +} + +.personal-menu-content { + float: right; +} +.el-dropdown { + cursor: pointer; +} +.el-dropdown-menu--default { + width: 150px; + border-radius: 5px !important; + padding: 0 !important; +} + +.el-dropdown-menu--large { + width: 200px; + border-radius: 5px !important; + padding: 0 !important; + +} + +.el-dropdown-menu--small { + min-width: 100px; + border-radius: 5px !important; + padding: 0 !important; +} + +.el-dropdown-menu__item { + font-size: 12px !important; + display: block !important; + text-align: center; + line-height: 26px !important; + + &:hover { + color: #108EE9 !important; + background-color: #F7F7F7 !important; + } + p { + overflow: hidden; + text-overflow: ellipsis; + } +} + +.quit { + background-color: #108EE9 !important; + border-radius: 0 0 5px 5px !important; + .el-dropdown-menu__item { + color: #FFFFFF !important; + &:hover { + border-radius: 0 0 5px 5px !important; + background-color: #0F81D4 !important; + } + } + +} + +.user-mid { + margin-top: 10px; + text-align: center; +} + +.operate-header-login { + width: 36px; + height: 36px; +} + +.operate-header-down { + width: 46px; + height: 46px; +} + +.divider-type { + border-top: 1px solid #E9E9E9 !important; + margin:12px 0 0 0!important +} + +.font-style { + font-size: 10px; + margin-right: 10px; + color: #979797; + font-weight: 300; +} + +.font-style-line { + font-size: 14px; + margin: 0 10px; + color: #979797; + font-weight: 500; +} + +.project-dropdown { + margin-left: 20px; + display: flex; + align-items: center; + cursor: pointer; + .arrow-img { + margin-left: 9px; + width:24px; + height: 24px; + cursor: pointer; + } +} + +.long-project-name { + overflow: hidden; + text-overflow: ellipsis; + max-width: 100px; + white-space: nowrap; +} + +.long-project-title { + height: 20px; + overflow: hidden; + text-overflow: ellipsis; + max-width: 100px; + white-space: nowrap; + margin-top: 6px; +} + +.default-img { + position: absolute; + float: right; + margin-top:-21px; + margin-left: 51px; + width: 16px; + height: 16px; +} diff --git a/bmp-console-web/src/components/BmpHeader/bmpHeader.vue b/bmp-console-web/src/components/BmpHeader/bmpHeader.vue new file mode 100644 index 0000000..e20847d --- /dev/null +++ b/bmp-console-web/src/components/BmpHeader/bmpHeader.vue @@ -0,0 +1,454 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/DropdownOperation/DropdownOperation.vue b/bmp-console-web/src/components/DropdownOperation/DropdownOperation.vue new file mode 100644 index 0000000..b0ea620 --- /dev/null +++ b/bmp-console-web/src/components/DropdownOperation/DropdownOperation.vue @@ -0,0 +1,93 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/InstanceOperate/editDescription.vue b/bmp-console-web/src/components/InstanceOperate/editDescription.vue new file mode 100644 index 0000000..36288e9 --- /dev/null +++ b/bmp-console-web/src/components/InstanceOperate/editDescription.vue @@ -0,0 +1,170 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/InstanceOperate/editName.vue b/bmp-console-web/src/components/InstanceOperate/editName.vue new file mode 100644 index 0000000..5be159d --- /dev/null +++ b/bmp-console-web/src/components/InstanceOperate/editName.vue @@ -0,0 +1,298 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/InstanceOperate/instanceClose.vue b/bmp-console-web/src/components/InstanceOperate/instanceClose.vue new file mode 100644 index 0000000..a065397 --- /dev/null +++ b/bmp-console-web/src/components/InstanceOperate/instanceClose.vue @@ -0,0 +1,129 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/InstanceOperate/instanceDelete.vue b/bmp-console-web/src/components/InstanceOperate/instanceDelete.vue new file mode 100644 index 0000000..1fb42e7 --- /dev/null +++ b/bmp-console-web/src/components/InstanceOperate/instanceDelete.vue @@ -0,0 +1,132 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/InstanceOperate/instanceLock.vue b/bmp-console-web/src/components/InstanceOperate/instanceLock.vue new file mode 100644 index 0000000..b111552 --- /dev/null +++ b/bmp-console-web/src/components/InstanceOperate/instanceLock.vue @@ -0,0 +1,133 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/InstanceOperate/instanceOpen.vue b/bmp-console-web/src/components/InstanceOperate/instanceOpen.vue new file mode 100644 index 0000000..78eaff6 --- /dev/null +++ b/bmp-console-web/src/components/InstanceOperate/instanceOpen.vue @@ -0,0 +1,130 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/InstanceOperate/instanceResetPassword.vue b/bmp-console-web/src/components/InstanceOperate/instanceResetPassword.vue new file mode 100644 index 0000000..6019cd5 --- /dev/null +++ b/bmp-console-web/src/components/InstanceOperate/instanceResetPassword.vue @@ -0,0 +1,343 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/InstanceOperate/instanceRestart.vue b/bmp-console-web/src/components/InstanceOperate/instanceRestart.vue new file mode 100644 index 0000000..2ef3849 --- /dev/null +++ b/bmp-console-web/src/components/InstanceOperate/instanceRestart.vue @@ -0,0 +1,128 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/InstanceOperate/instanceResystem/instanceResystem.scss b/bmp-console-web/src/components/InstanceOperate/instanceResystem/instanceResystem.scss new file mode 100644 index 0000000..3e2d403 --- /dev/null +++ b/bmp-console-web/src/components/InstanceOperate/instanceResystem/instanceResystem.scss @@ -0,0 +1,406 @@ + +.resystem-form { + .password-change { + margin-top: -2px; + .el-form-item__content { + display: block; + } + } + .image-gap { + .el-form-item--default { + margin-bottom: 11px; + } + } + .el-form-item__label { + font-weight: bold; + font-size: 12px; + } + + .el-form-item--default { + margin-bottom: 30px; + } + + .el-form-item.is-error { + margin-bottom: 30px !important; + } + + .el-form-item__error { + position: static; + display: flex; + align-items: center; + word-break: keep-all; + word-wrap: break-word; + } + + .el-radio-button { + margin-right: 30px; + .el-radio-button__inner { + font-size: 12px; + min-width: 110px; + height: 36px; + padding: 10px 15px; + border-left-color: #979797 !important; + border-radius: 5px; + + &:hover { + border-left-color: #108EF9 !important; + } + + } + + &.is-disabled { + .el-radio-button__inner { + font-size: 12px; + min-width: 110px; + height: 36px; + border-left-color:#979797 !important; + border-radius: 5px; + + &:hover { + border-left-color: #666666 !important; + } + + } + } + + &.is-active { + .el-radio-button__inner { + font-size: 12px; + min-width: 110px; + height: 36px; + border-left-color: #108EF9 !important; + border-radius: 5px; + + &:hover { + border-left-color:#108EF9 !important; + } + + } + } + } + + .el-radio-button :hover .model-picture-grey{ + border-color: #108EF9; + -webkit-filter: grayscale(0%); + /* Chrome, Safari, Opera */ + filter: grayscale(0%); + } + + .el-radio-button.is-active { + border-color: #108EF9; + .model-picture-grey{ + -webkit-filter: grayscale(0%); + /* Chrome, Safari, Opera */ + filter: grayscale(0%); + } + .divider-line { + border-top: 1px solid #108EF9; + } + + } + + .el-radio-button.is-active.is-disabled{ + border-color: #666666; + .model-picture-grey{ + -webkit-filter: grayscale(100%); + /* Chrome, Safari, Opera */ + filter: grayscale(100%); + } + .divider-line { + border-top: 1px solid #666666 ; + } + + } + + .el-radio-button.is-disabled{ + border-color: #666666; + .model-picture-grey{ + -webkit-filter: grayscale(80%); + /* Chrome, Safari, Opera */ + filter: grayscale(80%); + } + .divider-line { + border-top: 1px solid #979797; + } + + } + + // 机型选择hover时,边框图形变蓝 + .el-radio-button :hover .divider-line{ + border-color: #108EF9; + } + + // 机型选择hover时,disable边框图形不变蓝 + .el-radio-button.is-disabled :hover .divider-line{ + border-color: #666666 !important; + } + + // 机型选择hover时,边框图形变蓝 + .el-radio-button :hover .raid-down{ + border-color: #108EF9; + } + + .el-radio-button:first-child .el-radio-button__inner { + border-radius: 5px; + } + + .el-radio-button:last-child .el-radio-button__inner { + border-radius: 5px; + } + + // 镜像类型样式 + .image-content { + width: 1004px; + overflow: hidden; + transition: max-height .3s; + + .el-radio-button { + border-radius: 50px; + margin-right: 30px; + margin-bottom: 10px; + } + + .el-radio-button { + width: 240px; + height: 62px !important; + } + + .el-radio-button__inner { + width: 240px; + padding: 15px 15px 10px 15px; + height: 62px !important; + background:white; + text-align: left; + color: #666666; + + } + .el-select .el-input { + display: flex; + width: 170px; + } + + .icon-size { + width: 35px; + height: 35px; + } + + .inline-position { + margin: 0 10px 0 0; + float: left; + } + + .el-input { + max-width: 170px !important; + } + + .el-input__inner { + max-width: 148px !important; + overflow: hidden; + text-overflow: ellipsis; + border: none; + padding: 0; + } + } + + .image-tick { + position: absolute; + height: 14px; + margin-top: -6px; + margin-left: 208px; + } + + .arrow-text { + position: absolute; + width: 29px; + height: 29px; + top: 16px; + left: 540px; + color: #999999; + border-color: #999999; + &:hover { + color: #FFFFFF; + border-color: #108EF9; + background-color: #108EF9; + } + &:active { + color: #FFFFFF; + border-color: #108EF9; + background-color: #108EF9; + } + } + + // 系统盘样式 + .system-raid-content { + .el-radio-button { + width: 150px; + height: 90px; + margin-right: 30px; + } + + .el-radio-button__inner { + width: 150px !important; + height: 25px !important; + padding: 5px 5px 10px 5px !important; + font-weight: 600 !important; + border-radius:5px 5px 0 0 !important + } + .system-down { + border: 1px solid #979797; + border-top: none; + border-radius:0 0 5px 5px; + margin: 7px 0 0 -6px; + padding: 15px 10px 0 10px; + width: 128.4px; + color: #333333; + } + .system-down-active { + border: 1px solid #108EF9; + border-top: none; + border-radius:0 0 5px 5px; + margin: 7px 0 0 -6px; + padding: 15px 10px 0 10px; + width: 128.4px; + color: #333333; + } + } + + .raid-tick { + margin-left: 123px; + } + + // 系统盘分区样式 + .chamfer-position { + margin-right: 30px; + } + + .chamfer { + width:70px; + height:90px; + padding: 1px; + background: + linear-gradient(-135deg, transparent 20px, #979797 0) top right, ; + background-repeat: no-repeat; + border-radius: 5px; + font-size: 12px; + } + .chamfer-inner { + width: 100%; + height: 100%; + background: + linear-gradient(-135deg, transparent 20px, white 0) top right, ; + background-repeat: no-repeat; + border-radius: 5px; + } + + .chamfer-up { + margin-left: 5px; + width: 60px; + border-bottom: 1px solid #979797 ; + } + + .chamfer-down { + width: 60px; + margin: 5px 5px 0px 5px; + line-height:18px; + text-align: center; + } + + .instance-message { + .el-input { + width: 340px !important; + } + } + + .password-size { + .el-radio { + .el-radio__label { + font-size: 12px; + } + } + } + + .password-label .el-form-item__label{ + line-height: 18px; + } +} + +.resystem-shape { + .el-dialog { + --el-dialog-width: 806px !important; + .el-dialog__body { + height: 508px; + overflow-y: auto; + } + } + + .notice-change { + word-break: keep-all; + margin: 4px 5px 0 0; + color: #FF4D4F; + } +} + +.long-volume { + font-weight: 400; + margin-bottom: 10px; + overflow: hidden; + text-overflow: ellipsis; + max-width: 150px; + white-space: nowrap; +} + +.long-system-detail { + font-weight: 400; + margin: 5px 0; + overflow: hidden; + text-overflow: ellipsis; + max-width: 150px; + white-space: nowrap; +} + +.password-tip { + font-size: 12px; + color: #999999; + width: 550px; +} + +.long-name-title { + overflow: hidden; + text-overflow: ellipsis; + max-width: 180px; + white-space: nowrap; +} + +.create-key-tip { + width: 631px; + text-align: center; + margin-top: 10px; + font-size: 12px; + color: #333333; + +} + +.download-monitorAgent-conetnt { + .el-checkbox__label { + font-size: 12px; + } + + .el-checkbox__input.is-checked+.el-checkbox__label { + color: #333333; + } +} + +.refresh-img { + margin-left: 5px; + margin-top: 2px; + width:12px; + height: 12px; + cursor: pointer; +} + +.tooltip-img { + width: 16px; + height: 16px; + margin-top: 2px; + margin-left: 5px; +} \ No newline at end of file diff --git a/bmp-console-web/src/components/InstanceOperate/instanceResystem/instanceResystem.vue b/bmp-console-web/src/components/InstanceOperate/instanceResystem/instanceResystem.vue new file mode 100644 index 0000000..8a481de --- /dev/null +++ b/bmp-console-web/src/components/InstanceOperate/instanceResystem/instanceResystem.vue @@ -0,0 +1,1130 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/InstanceOperate/instanceResystemConfirm.vue b/bmp-console-web/src/components/InstanceOperate/instanceResystemConfirm.vue new file mode 100644 index 0000000..8bcd446 --- /dev/null +++ b/bmp-console-web/src/components/InstanceOperate/instanceResystemConfirm.vue @@ -0,0 +1,125 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/InstanceOperate/instanceUnlock.vue b/bmp-console-web/src/components/InstanceOperate/instanceUnlock.vue new file mode 100644 index 0000000..78f808d --- /dev/null +++ b/bmp-console-web/src/components/InstanceOperate/instanceUnlock.vue @@ -0,0 +1,128 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/MenuBar/menuBar.vue b/bmp-console-web/src/components/MenuBar/menuBar.vue new file mode 100644 index 0000000..732e1bd --- /dev/null +++ b/bmp-console-web/src/components/MenuBar/menuBar.vue @@ -0,0 +1,247 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/OperateUnit/operateUnit.vue b/bmp-console-web/src/components/OperateUnit/operateUnit.vue new file mode 100644 index 0000000..d79b971 --- /dev/null +++ b/bmp-console-web/src/components/OperateUnit/operateUnit.vue @@ -0,0 +1,84 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/Pagination/MyPagination.vue b/bmp-console-web/src/components/Pagination/MyPagination.vue new file mode 100644 index 0000000..4b63257 --- /dev/null +++ b/bmp-console-web/src/components/Pagination/MyPagination.vue @@ -0,0 +1,557 @@ + + + + + diff --git a/bmp-console-web/src/components/PersonalCentreOperate/apiKeyCreate.vue b/bmp-console-web/src/components/PersonalCentreOperate/apiKeyCreate.vue new file mode 100644 index 0000000..95e2c67 --- /dev/null +++ b/bmp-console-web/src/components/PersonalCentreOperate/apiKeyCreate.vue @@ -0,0 +1,309 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/PersonalCentreOperate/apiKeyDelete.vue b/bmp-console-web/src/components/PersonalCentreOperate/apiKeyDelete.vue new file mode 100644 index 0000000..bb3d5eb --- /dev/null +++ b/bmp-console-web/src/components/PersonalCentreOperate/apiKeyDelete.vue @@ -0,0 +1,127 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/PersonalCentreOperate/sshKeyDelete.vue b/bmp-console-web/src/components/PersonalCentreOperate/sshKeyDelete.vue new file mode 100644 index 0000000..ce978f3 --- /dev/null +++ b/bmp-console-web/src/components/PersonalCentreOperate/sshKeyDelete.vue @@ -0,0 +1,128 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/PersonalCentreOperate/sshKeyEdit.vue b/bmp-console-web/src/components/PersonalCentreOperate/sshKeyEdit.vue new file mode 100644 index 0000000..d905cb4 --- /dev/null +++ b/bmp-console-web/src/components/PersonalCentreOperate/sshKeyEdit.vue @@ -0,0 +1,356 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/ProjectOperate/ProjectTransfer/projectTransfer.scss b/bmp-console-web/src/components/ProjectOperate/ProjectTransfer/projectTransfer.scss new file mode 100644 index 0000000..1ce28e5 --- /dev/null +++ b/bmp-console-web/src/components/ProjectOperate/ProjectTransfer/projectTransfer.scss @@ -0,0 +1,59 @@ +.dialog-trans { + .share-tip-position { + display: flex; + margin-bottom: 20px; + } + .dialog-width952 { + .el-dialog { + width: 952px; + height: 550px; + .el-dialog__body { + height: 420px; + padding: 10px 40px 0 40px !important; + .el-input { + width: 304px !important; + } + .el-select { + width: 304px !important; + } + } + } + + .el-table { + border-bottom: 1px solid #EAEAEA; + .el-table__header { + border-right: 2px solid #E8F4FD; + } + .el-scrollbar{ + border-left: 1px solid #EAEAEA; + border-right: 1px solid #EAEAEA; + } + } + } + + .dialog-body-content { + .el-form-item.is-error { + margin-bottom: 32px; + } + } + + .password-size { + .el-radio { + .el-radio__label { + font-size: 12px; + } + } + } + + .warning-location { + margin-top: 1px; + display: inline; + vertical-align: middle; + } + + .warning-tips { + white-space: nowrap; + color: #FF4D4F; + } + +} \ No newline at end of file diff --git a/bmp-console-web/src/components/ProjectOperate/ProjectTransfer/projectTransfer.vue b/bmp-console-web/src/components/ProjectOperate/ProjectTransfer/projectTransfer.vue new file mode 100644 index 0000000..51a1873 --- /dev/null +++ b/bmp-console-web/src/components/ProjectOperate/ProjectTransfer/projectTransfer.vue @@ -0,0 +1,679 @@ + + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/ProjectOperate/RelateUserAdd/relateUserAdd.scss b/bmp-console-web/src/components/ProjectOperate/RelateUserAdd/relateUserAdd.scss new file mode 100644 index 0000000..2e0c161 --- /dev/null +++ b/bmp-console-web/src/components/ProjectOperate/RelateUserAdd/relateUserAdd.scss @@ -0,0 +1,51 @@ +.dialog-pading-change { + .share-tip-position { + display: flex; + margin-bottom: 20px; + } + .dialog-width952 { + .el-dialog { + width: 952px; + height: 550px; + .el-dialog__body { + height: 420px; + padding: 10px 40px 0 40px !important; + .el-input { + width: 304px !important; + } + .el-select { + width: 304px !important; + } + + } + } + + .el-table { + border-bottom: 1px solid #EAEAEA; + .el-table__header { + border-right: 2px solid #E8F4FD; + } + .el-scrollbar{ + border-left: 1px solid #EAEAEA; + border-right: 1px solid #EAEAEA; + } + } + } + + .dialog-body-content { + .el-form-item.is-error { + margin-bottom: 32px; + } + } + + .warning-location { + margin-top: 1px; + display: inline; + vertical-align: middle; + } + + .warning-tips { + white-space: nowrap; + color: #FF4D4F; + } +} \ No newline at end of file diff --git a/bmp-console-web/src/components/ProjectOperate/RelateUserAdd/relateUserAdd.vue b/bmp-console-web/src/components/ProjectOperate/RelateUserAdd/relateUserAdd.vue new file mode 100644 index 0000000..54072f7 --- /dev/null +++ b/bmp-console-web/src/components/ProjectOperate/RelateUserAdd/relateUserAdd.vue @@ -0,0 +1,557 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/ProjectOperate/editDescription.vue b/bmp-console-web/src/components/ProjectOperate/editDescription.vue new file mode 100644 index 0000000..1407d9c --- /dev/null +++ b/bmp-console-web/src/components/ProjectOperate/editDescription.vue @@ -0,0 +1,172 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/ProjectOperate/editName.vue b/bmp-console-web/src/components/ProjectOperate/editName.vue new file mode 100644 index 0000000..13c6eb7 --- /dev/null +++ b/bmp-console-web/src/components/ProjectOperate/editName.vue @@ -0,0 +1,318 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/ProjectOperate/projectCreate.vue b/bmp-console-web/src/components/ProjectOperate/projectCreate.vue new file mode 100644 index 0000000..1f3c147 --- /dev/null +++ b/bmp-console-web/src/components/ProjectOperate/projectCreate.vue @@ -0,0 +1,304 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/ProjectOperate/projectDelete.vue b/bmp-console-web/src/components/ProjectOperate/projectDelete.vue new file mode 100644 index 0000000..5a7d74f --- /dev/null +++ b/bmp-console-web/src/components/ProjectOperate/projectDelete.vue @@ -0,0 +1,128 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/ProjectOperate/relatedUserDelete.vue b/bmp-console-web/src/components/ProjectOperate/relatedUserDelete.vue new file mode 100644 index 0000000..5efac28 --- /dev/null +++ b/bmp-console-web/src/components/ProjectOperate/relatedUserDelete.vue @@ -0,0 +1,136 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/SearchInput/searchInput.scss b/bmp-console-web/src/components/SearchInput/searchInput.scss new file mode 100644 index 0000000..c6f523d --- /dev/null +++ b/bmp-console-web/src/components/SearchInput/searchInput.scss @@ -0,0 +1,260 @@ + +$height: 28px; +$center: center; + +.set-instance { + input { + width: 420px; + padding-right: 165px; + } + .input-select { + &-count { + .el-input__inner { + width: 115px; + padding: 0; + } + } + } + + .input-search-clear { + right: 143px; + } +} + +.set-input { + input { + width: 485px; + padding-right: 220px; + } + + .el-input__inner { + margin-right: 8px !important; + } + + .input-select { + &-count { + .el-input__inner { + width: 185px; + padding-right: 20px; + padding-left: 8px; + } + } + } + + .input-search-clear { + right: 207px + } + + .el-input__suffix { + right: 16px !important; + } +} + +.small-input { + input { + width: 415px; + padding-right: 160px; + } + + .input-select { + &-count { + .el-input__inner { + width: 115px; + padding: 0; + } + } + } + + .input-search-clear { + right: 138px; + } + + .input-select-division-line { + left: -3px !important; + } +} + +.operate-management-input { + input { + width: 320px; + padding-right: 130px; + } + .input-select { + &-count { + .el-input__inner { + width: 100px; + padding: 0; + } + } + } + + .input-search-clear { + right: 123px; + } +} + +.set-input, +.small-input, +.set-instance, +.operate-management-input { + display: flex; + align-items: $center; + position: relative; + + input { + height: $height; + border: 1.05px solid #999; + border-radius: 14px !important; + overflow-x: auto; + font-size: 12px; + padding-left: 36px; + + &::placeholder { + font-size: 12px; + color: #999; + font-weight: 400; + } + + &:hover { + border-color: #979797; + } + + &:focus, + &:active { + border-color: #108ee9; + } + } + + .el-input-group__append { + position: absolute; + left: 0px; + top: 50%; + transform: translateY(-50%); + border: 0; + background: transparent; + + .search-icon { + width: 15px; + height: 15px; + margin-left: -7px; + margin-top: 2px; + cursor: pointer; + } + } + + .input-select { + display: flex; + align-items: $center; + position: absolute; + right: 0; + top: 50%; + transform: translateY(-50%); + + input { + border: 0; + outline: 0; + } + + span { + font-size: 12px; + color: #666; + } + + &-division-line { + width: 0.5px; + height: 11.5px; + margin-top: 2px; + background: #999; + position: absolute; + left: -3px; + } + + &-count { + height: $height; + + .el-input__inner { + background: transparent; + font-size: 12px !important; + line-height: 1; + text-align: center; + margin-right: 14px; + } + + .el-input__suffix { + right: 8px; + } + } + } + + .input-search-clear { + width: 16px; + height: 16px; + position: absolute; + } +} + +.operate-content { + + &-ipt { + width: 344px; + height: 40px; + display: flex; + align-items: center; + margin-bottom: 7px; + + input { + padding-left: 57px; + height: 40px; + border: 1px solid #979797; + border-radius: 4px; + padding-right: 32px; + + &:hover { + border-color: #979797; + } + + &:focus, + &:active { + border-color: #108ee9; + } + } + + &-open-eye, + &-close-eye { + cursor: pointer; + } + + &-user-img, + &-open-eye, + &-close-eye { + width: 32px; + height: 32px; + transform: scale(.5); + position: absolute; + left: 15px; + z-index: 9; + } + + &-clear { + width: 32px; + height: 32px; + transform: scale(.5); + position: absolute; + right: 5px; + cursor: pointer; + } + } +} + +.input-select-count { + .el-input__suffix { + .el-input__suffix-inner { + i { + svg { + color: #666; + margin-top: -3px; + } + } + } + } +} \ No newline at end of file diff --git a/bmp-console-web/src/components/SearchInput/searchInput.vue b/bmp-console-web/src/components/SearchInput/searchInput.vue new file mode 100644 index 0000000..42deb3e --- /dev/null +++ b/bmp-console-web/src/components/SearchInput/searchInput.vue @@ -0,0 +1,146 @@ + + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/common/alarmLogList/alarmLogList.scss b/bmp-console-web/src/components/common/alarmLogList/alarmLogList.scss new file mode 100644 index 0000000..74a947c --- /dev/null +++ b/bmp-console-web/src/components/common/alarmLogList/alarmLogList.scss @@ -0,0 +1,18 @@ +.alarm-log-list { + .status-processed { + color: #43B561; + } + .status-notprocessed { + color: #FF4D4F; + } + + .operate-refresh, + .operate-set-up, + .no-export, + .operate-export { + margin-top: 0 !important; + } +} + + + diff --git a/bmp-console-web/src/components/common/alarmLogList/alarmLogList.vue b/bmp-console-web/src/components/common/alarmLogList/alarmLogList.vue new file mode 100644 index 0000000..99c5152 --- /dev/null +++ b/bmp-console-web/src/components/common/alarmLogList/alarmLogList.vue @@ -0,0 +1,436 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/common/chooseInstance/chooseInstance.scss b/bmp-console-web/src/components/common/chooseInstance/chooseInstance.scss new file mode 100644 index 0000000..02a4928 --- /dev/null +++ b/bmp-console-web/src/components/common/chooseInstance/chooseInstance.scss @@ -0,0 +1,218 @@ +.choose-instance { + display: flex; + .el-checkbox__inner { + width: 10px; + height: 10px; + margin-top: 1px; + border-radius: 2px; + border: 1px solid #333; + + &:hover, + &:focus, + &:active { + border-color: #108EF9 !important; + } + + &::after { + height: 5px; + left: 2px; + top: 0px; + } + } + + .switch-img { + width:14px; + height: 12px; + margin: auto 30px; + padding-top: 12px; + } + + .clear-img { + vertical-align: sub; + color: #108EF9 !important; + } + + .table-search { + .el-table__body { + margin-top: 46px; + } + + .el-table tr { + height: 40px; + } + + .el-table__row { + height: 28px; + } + + .selectAllbtnDis { + .el-checkbox__inner { + display: none; + } + } + .is-checked, + .is-focus { + .el-checkbox__inner { + border: 1px solid #108EF9; + } + } + .el-checkbox__inner { + width: 10px; + height: 10px; + margin-top: 1px; + border-radius: 2px; + border: 1px solid #333; + + &:hover, + &:focus, + &:active { + border-color: #108EF9 !important; + } + + &::after { + height: 5px; + left: 2px; + top: 0px; + } + } + + .is-disabled { + + .el-checkbox__label { + font-size: 12px; + color: #999 !important; + font-weight: 400; + } + .el-checkbox__inner { + background: #999 !important; + border: 1px solid #999 !important; + border-radius: 2px; + + &:hover, + &:focus, + &:active { + border-color: #999 !important; + } + + &::after { + border-color: #fff !important; + } + } + } + + .el-checkbox__label { + overflow: hidden; + text-overflow: ellipsis; + font-size: 12px; + color: #333 !important; + font-weight: 400; + max-width: 80px; + } + } + + .table-change { + .el-table tr { + height: 28px; + } + + .el-table__row { + height: 28px; + } + + .el-table__header { + height: 40px; + } + + .el-table .el-table__cell { + padding: 0; + } + + .cell { + padding: 0 10px; + } + } + + .search-position { + position: absolute; + background-color: #fff; + z-index: 3; + top: 65px; + padding: 12px 8px 6px 7px; + border-left: 1px solid #EAEAEA; + border-right: 1px solid #EAEAEA; + input { + height: 28px; + width: 380px !important; + border: 1.05px solid #999; + border-radius: 14px !important; + overflow-x: auto; + font-size: 12px; + padding-left: 36px; + + &::placeholder { + font-size: 12px; + color: #999; + font-weight: 400; + } + + &:hover { + border-color: #979797; + } + + &:focus, + &:active { + border-color: #108ee9; + } + + + } + + .el-input__inner { + padding: 0 31px; + } + + .el-input-group__append { + position: absolute; + left: 0px; + top: 50%; + transform: translateY(-50%); + border: 0; + background: transparent; + + .search-icon { + width: 15px; + height: 15px; + margin-left: -7px; + margin-top: 2px; + cursor: pointer; + } + } + + .input-search-clear { + width: 16px; + height: 16px; + right: 16px; + top: 60%; + transform: translateY(-50%); + position: absolute; + } + + } + + .clear-position { + position: absolute; + z-index: 3; + right: 2px; + top: 36px; + font-size: 12px; + } + + .select-column { + .cell { + padding: 0; + .el-checkbox { + top:2px + } + } + } +} \ No newline at end of file diff --git a/bmp-console-web/src/components/common/chooseInstance/chooseInstance.vue b/bmp-console-web/src/components/common/chooseInstance/chooseInstance.vue new file mode 100644 index 0000000..30cbe49 --- /dev/null +++ b/bmp-console-web/src/components/common/chooseInstance/chooseInstance.vue @@ -0,0 +1,377 @@ + + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/common/hardwareStatus/hardwareStatus.scss b/bmp-console-web/src/components/common/hardwareStatus/hardwareStatus.scss new file mode 100644 index 0000000..6c36c7a --- /dev/null +++ b/bmp-console-web/src/components/common/hardwareStatus/hardwareStatus.scss @@ -0,0 +1,75 @@ +.hardware-status { + display: flex; + //justify-content: space-between; + flex-wrap: wrap; +} + +.gap-content { + justify-content: space-between; + .hardware-card { + margin-right: 0; + } +} + +.hardware-card { + display: inline-block; + width: auto; + margin-right: 30px; + margin-bottom: 28px; + .hardware-card-body { + width: auto; + background-color: #F7F7F7; + border-radius: 7px; + padding: 12px 10px; + .device-name { + font-size: 20px; + padding-right: 10px; + //border-right: 2px solid #00000026; + } + + } +} + +.status-icon { + width: 16px !important; + height: 16px !important; + display: inline-block; + margin-left: 10px; + margin-right: 10px; + border-radius: 100%; +} + +.div-content { + height: 16px; + margin: 0; + vertical-align: baseline; + border-left: 2px solid #333333 +} + +.status-success { + display: inline-block; + line-height: 26px; + height: 26px; + color: #43B561 !important; + font-size: 18px; + .status-icon { + background: #43B561 !important; + } + .status-text { + vertical-align: text-bottom; + } +} + +.status-error { + display: inline-block; + line-height: 26px; + height: 26px; + color: #FF4D4F !important; + font-size: 18px; + .status-icon { + background: #FF4D4F !important; + } + .status-text { + vertical-align: text-bottom; + } +} \ No newline at end of file diff --git a/bmp-console-web/src/components/common/hardwareStatus/hardwareStatus.vue b/bmp-console-web/src/components/common/hardwareStatus/hardwareStatus.vue new file mode 100644 index 0000000..792df95 --- /dev/null +++ b/bmp-console-web/src/components/common/hardwareStatus/hardwareStatus.vue @@ -0,0 +1,53 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/common/maxCollapseTagsSelect/maxCollapseTagsSelect.vue b/bmp-console-web/src/components/common/maxCollapseTagsSelect/maxCollapseTagsSelect.vue new file mode 100644 index 0000000..17f6535 --- /dev/null +++ b/bmp-console-web/src/components/common/maxCollapseTagsSelect/maxCollapseTagsSelect.vue @@ -0,0 +1,62 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/common/performanceMonitoring/css/deviceEcharts.scss b/bmp-console-web/src/components/common/performanceMonitoring/css/deviceEcharts.scss new file mode 100644 index 0000000..3239a2b --- /dev/null +++ b/bmp-console-web/src/components/common/performanceMonitoring/css/deviceEcharts.scss @@ -0,0 +1,128 @@ +@import 'assets/css/list.scss'; + +.echarts-search-count { + .search-radio-count { + margin-bottom: 20px; + margin-left: 32px; + :deep(.el-radio__label) { + display: flex; + align-items: center; + font-size: 12px; + padding-left: 13px; + } + + :deep(.el-select) { + .el-input__inner { + width: 130px; + height: 30px; + margin-left: 10px; + } + } + + .common-img { + width: 16px; + height: 16px; + margin-left: 3px; + } + } + + + .echarts-count { + display: flex; + flex-wrap: wrap; + margin-left: -27px; + + :deep(.el-loading-mask) { + border-radius: 8px; + } + } + + :deep(.seach-opt-count) { + display: flex; + margin: 0 0 20px 0; + position: relative; + + .set-alarm-rules { + position: absolute; + right: 30px; + top: 7px; + font-size: 12px; + + span { + cursor: pointer; + color: #108EF9; + } + } + + .el-range-input { + font-size: 12px; + } + + .radio-active { + margin-right: 16px; + .el-radio-button__inner { + height: 30px; + font-size: 12px; + border-color:#dcdfe6; + } + } + + .el-range-editor { + height: 30px; + + .el-range-separator { + font-size: 12px; + } + } + + .operate-management-content-operate2 { + width: auto; + margin-bottom: 0 !important; + padding: 0 16px 0 30px; + + &-right { + margin-top: 0; + } + + .list-data-operate0 { + margin-right: 0; + } + } + + .operate-refresh { + display: flex; + align-items: center; + margin-right: 10px; + cursor: pointer; + + .my-update-gray { + width: 16px; + height: 16px; + background-size: 100% auto !important; + background-position: center center; + background-repeat: no-repeat; + margin-right: 5px; + } + + .refresh-title{ + font-size: 12px; + } + + &:hover { + color: #108EF9; + } + } + + .operate-refresh { + .my-update-gray { + background-image: url('~@/assets/img/updateGray.png'); + } + + &:hover { + .my-update-gray { + background-image: url('~@/assets/img/update.png'); + } + } + } + } +} \ No newline at end of file diff --git a/bmp-console-web/src/components/common/performanceMonitoring/css/echartsBig.scss b/bmp-console-web/src/components/common/performanceMonitoring/css/echartsBig.scss new file mode 100644 index 0000000..34bb5cd --- /dev/null +++ b/bmp-console-web/src/components/common/performanceMonitoring/css/echartsBig.scss @@ -0,0 +1,97 @@ +.big-size-echarts { + width: 100%; + position: fixed; + background: rgba(212, 217, 221, .6); + z-index: 99; + height: 100%; + left: 0; + top: 0; + + .header { + width: 100%; + position: relative; + margin-top: 14px; + + .close-button { + width: 23px; + height: 23px; + position: absolute; + right: -12px; + top: -29px; + background: #fff; + + &:hover, + &:active, + &:focus { + background: #fff; + border-color: #fff; + color: #108ee9; + } + + .el-icon { + margin-left: 1px; + } + } + .title { + font-size: 14px; + color: #333; + margin-left: 30px; + margin-top: 9px; + margin-bottom: 9px; + } + + .count { + display: flex; + align-items: center; + font-size: 12px; + margin-left: 30px; + + p { + &:first-child { + margin-right: 20px; + } + } + + + :deep(.el-select) { + .el-input__inner { + width: 85px; + height: 18px; + font-size: 12px; + } + } + } + } + + .size-continer { + width: 75%; + height: 400px; + background-color: #fff; + box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .50); + border-radius: 10px; + position: absolute; + left: 50%; + top: 50%; + transform: translate(-50%, -50%); + display: flex; + flex-direction: column; + align-items: center; + } + + #bigSize { + width: 100%; + height: 300px; + :deep(div) { + canvas { + padding: 0 30px !important; + } + } + // :deep { + // div { + // canvas { + // padding: 0 30px !important; + // } + // } + // } + } +} \ No newline at end of file diff --git a/bmp-console-web/src/components/common/performanceMonitoring/css/echartsPage.scss b/bmp-console-web/src/components/common/performanceMonitoring/css/echartsPage.scss new file mode 100644 index 0000000..ff53b10 --- /dev/null +++ b/bmp-console-web/src/components/common/performanceMonitoring/css/echartsPage.scss @@ -0,0 +1,91 @@ +.echart-bar { + width: 359px; + height: 314px; + background: #fff; + flex-direction: column; + border: 1.05px solid #d2d2d2; + border-radius: 8px; + display: flex; + align-items: flex-end; + margin-left: 27px; + margin-bottom: 20px; + + &:hover { + border-color: #108ee9; + + .header { + .big { + opacity: 1; + transition: all 1s; + background-image: url('~@/assets/img/big-size.png'); + background-size: 100% auto; + background-repeat: no-repeat; + } + } + } + + .header { + width: 100%; + position: relative; + + .big { + position: absolute; + right: 20px; + top: 7px; + opacity: 0; + + &:hover { + cursor: pointer; + } + } + + .title { + font-size: 14px; + color: #333; + margin-left: 20px; + margin-top: 9px; + margin-bottom: 9px; + } + + .count { + display: flex; + align-items: center; + font-size: 12px; + margin-left: 20px; + + p { + &:first-child { + margin-right: 20px; + } + } + + :deep(.el-select) { + .el-input__inner { + width: 55px; + height: 18px; + font-size: 12px; + padding-right: 0; + } + + .el-input__suffix { + right: 4px; + transform: scale(.8); + } + } + } + } + + .echart-context { + top: -15px; + margin-top: 14px; + // width: 355px; + width: 100%; + height: 243px; + } + + .common-img{ + margin-left: 3px; + width: 16px; + height: 16px; + } +} \ No newline at end of file diff --git a/bmp-console-web/src/components/common/performanceMonitoring/echartsBig.vue b/bmp-console-web/src/components/common/performanceMonitoring/echartsBig.vue new file mode 100644 index 0000000..eef7c7e --- /dev/null +++ b/bmp-console-web/src/components/common/performanceMonitoring/echartsBig.vue @@ -0,0 +1,63 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/common/performanceMonitoring/echartsData.ts b/bmp-console-web/src/components/common/performanceMonitoring/echartsData.ts new file mode 100644 index 0000000..26050a4 --- /dev/null +++ b/bmp-console-web/src/components/common/performanceMonitoring/echartsData.ts @@ -0,0 +1,460 @@ +/** + * @file + * @author +*/ +import i18n from 'lib/i18n/index.ts'; // 国际化 + +import { + Ref, + ref, + reactive, + watch, + nextTick +} from 'vue'; +import echarts from './utils/publicQuote'; +import RuleFormOpt from './utils/ruleForm'; +import publicConfigOpt from './utils/publicConfig'; +import InitStaticData from './utils/initStaticData'; +import {intervalTime, getMonthHoursMinutes} from 'utils/index.ts'; +import {publicOption, seriesDataObj, echartsOpt} from './options'; +import {monitorDataAPI, deviceTagAPI} from 'api/request.ts'; +import {NewDataType, NewTimeType, HourRangesType, ReactiveArrType, EchartsDataObjType} from './type'; +const {global} = i18n; + +class EchartsOpt extends RuleFormOpt { + cycle: Ref = ref('1min'); + readioSearch: Ref = ref(global.t('monitorEcharts.radio.instance')); + hours: Ref = ref(global.t('monitorEcharts.tabs.h1')); + value1: Ref = ref(''); + selectValForm = reactive({ + disk: [], + mountpoint: [], + nic: [] + }) + diskVal: Ref = ref(''); + mountpointVal: Ref = ref(''); + nicVal: Ref = ref(''); + reactiveArr: ReactiveArrType = reactive({ + aggregationMethod: publicConfigOpt.aggregationMethod, + isLoadingObj: {}, + echartsParamsData: InitStaticData.echartsParamsData, + // @ts-ignore + echartsData: InitStaticData.echartsData + }); + instanceId + fn; + + constructor( instanceId: string, fn: Function ) { + super(); + const that = this; + for (let index in this.ruleForm) { + (this.reactiveArr.isLoadingObj[`${index}` as keyof typeof that.reactiveArr.isLoadingObj] as boolean) = true; + } + this.instanceId = instanceId; + this.fn = fn; + this.initEchartsParamsData(); + this.watchDetail(); + this.watchRadio(); + this.watchHours(); + this.watchValue1(); + } + + watchValue1 = () => { + watch(() => this.value1, (newValue) => { + this.value1Val(newValue.value); + if (newValue.value?.length) { + this.hours.value = ''; + const {diskVal, mountpointVal, nicVal} = this; + let obj: Record = {}; + obj['diskVal'] = diskVal.value; + obj['mountpointVal'] = mountpointVal.value; + obj['nicVal'] = nicVal.value; + let str: string = ''; + let newValS: string = ''; + if (Object.is(this.readioSearch.value, global.t('monitorEcharts.radio.instance'))) { + str = ''; + } + else { + for (const index in obj) { + if (obj[index] !== '') { + str = index; + newValS = obj[index]; + } + } + } + this.strVal(str, newValS); + } + }, {deep: true}) + } + + value1Val = (value: string) => { + if (value !== null) { + // intervalTime 计算两个时间之间的时间差 多少天时分秒 + const val = intervalTime(value[0], value[1]); + const objData = [ + [ + () => !val.days, + () => { + const hourRanges: HourRangesType = { + '0': '1min', + '6': '5min', + '12': '10min', + '24': '1min' + }; + // @ts-ignore + const cycleValue = hourRanges[Math.floor(val.hours / 6) * 6] || ''; + if (cycleValue?.length) { + this.cycle.value = cycleValue; + } + } + ], + [ + () => val.days, + () => { + this.cycle.value = val.days >= 14 ? '180min' : val.days >= 7 ? '120min' : val.days >= 3 ? '60min' : '20min'; + } + ] + ]; + outer: for (const key of objData) { + // @ts-ignore + if (key[0]()) { + key[1](); + break outer; + } + } + return; + } + this.hours.value = global.t('monitorEcharts.tabs.h1'); + this.cycle.value = '1min'; + } + + isLoading = (type: string) => { + const that = this; + return this.reactiveArr.isLoadingObj[`${type}` as keyof typeof that.reactiveArr.isLoadingObj]; + } + + strVal = (str: string, newValS: string) => { + if (!str?.length) { + this.initData(); + return; + } + const newData = this.reactiveArr.echartsData.filter((item) => item.status?.includes(str)); + for (const key of newData) { + this.getEcharts(key, 'small', {device: newValS}); + } + } + + watchHours = () => { + watch(() => this.hours, (newValue: {value: string}) => { + if (newValue.value.length) { + if (this.value1.value?.length) { + this.value1.value = '' + } + } + const val: {value: string} = InitStaticData.radioData.filter((item: {label: string}) => item.label === newValue.value)[0]; + if (!Object.is(val, void 0)) { + this.cycle.value = val.value; + this.refresh(); + } + }, { + deep: true + }) + } + + initEchartsParamsData = () => { + const that = this; + for (const key of this.reactiveArr.echartsParamsData) { + key.model = this.ruleForm[`${key.type}` as keyof typeof that.ruleForm]; + key.bigClickVal.model = this.ruleForm[`${key.type}` as keyof typeof that.ruleForm]; + } + } + + watchDetail = () => { + this.initData(); + // watch(() => this.props.detail.instanceId, () => { + // this.initData(); + // }, { + // deep: true + // }) + } + + watchRadio = () => { + watch(() => this.readioSearch, (newValue: {value: string}) => { + const objData = [ + [ + (value: string) => Object.is(value, global.t('monitorEcharts.radio.instance')), + () => { + this.diskVal.value = ''; + this.nicVal.value = ''; + this.mountpointVal.value = ''; + this.initData(); + } + ], + [ + (value: string) => Object.is(value, global.t('monitorEcharts.radio.disk')), + (value: string) => { + this.nicVal.value = ''; + this.mountpointVal.value = ''; + this.initTagName(this.getTagName(value)!, 'diskVal') + } + ], + [ + (value: string) => Object.is(value, global.t('monitorEcharts.radio.diskPartition')), + (value: string) => { + this.diskVal.value = ''; + this.nicVal.value = ''; + this.initTagName(this.getTagName(value)!, 'mountpointVal') + } + ], + [ + (value: string) => Object.is(value, global.t('monitorEcharts.radio.netWorkInterface')), + (value: string) => { + this.diskVal.value = ''; + this.mountpointVal.value = ''; + this.initTagName(this.getTagName(value)!, 'nicVal') + } + ] + ] + outer: for (const key of objData) { + // @ts-ignore + if (key[0](newValue.value)) { + key[1](newValue.value) + break outer; + } + } + }, {deep: true}) + } + + initData = () => { + if (Array.isArray(this.reactiveArr.echartsData)) { + for (const key of this.reactiveArr.echartsData) { + // 循环体 + this.getEcharts(key); + } + } + else { + throw new Error('数据格式出错,不是一个数组') + } + } + + refresh = () => { + const value = this.readioSearch.value; + const objData = [ + [ + () => Object.is(value, global.t('monitorEcharts.radio.instance')), + () => this.initData() + ], + [ + () => Object.is(value, global.t('monitorEcharts.radio.disk')), + () => this.disk(this.diskVal.value) + ], + [ + () => Object.is(value, global.t('monitorEcharts.radio.diskPartition')), + () => this.mountpoint(this.mountpointVal.value) + ], + [ + () => Object.is(value, global.t('monitorEcharts.radio.netWorkInterface')), + () => this.nic(this.nicVal.value) + ] + ]; + for (const key of objData) { + // @ts-ignore + if (key[0]()) { + return key[1](); + } + } + } + + getTagName = (value: string) => { + const tagName = new Map([ + [global.t('monitorEcharts.radio.disk'), 'disk'], + [global.t('monitorEcharts.radio.diskPartition'), 'mountpoint'], + [global.t('monitorEcharts.radio.netWorkInterface'), 'nic'] + ]); + return tagName.get(value); + } + + disabledDate = (time: any) => { + return time.getTime() > Date.now() || time.getTime() < Date.now() - 3600 * 1000 * 24 * 30; + } + + disk = (val: string) => { + this.selectData('diskVal', val); + } + + mountpoint = (val: string) => { + this.selectData('mountpointVal', val); + } + + nic = (val: string) => { + this.selectData('nicVal', val); + } + + selectData = (type: string, val: string) => { + const newData = this.reactiveArr.echartsData.filter((item) => item.status?.includes(type)); + for (const key of newData) { + this.getEcharts(key, 'small', {device: val}); + } + } + + initTagName = async (tagName: string, value: T) => { + const that = this; + const params = { + instanceId: this.instanceId, + tagName + }; + try { + const res = await deviceTagAPI(params); + if (res?.data?.result?.length) { + this.selectValForm[`${tagName}` as keyof typeof that.selectValForm] = res.data.result; + // @ts-ignore + this[value].value = res.data.result[0]; + // @ts-ignore + const val = this[value].value; + this.mountpointVal.value?.length && this.mountpoint(val); + this.diskVal.value?.length && this.disk(val); + this.nicVal.value?.length && this.nic(val); + } + } + catch { + throw new Error('error'); + } + } + + getEcharts = async (key: T, size = 'small', selectParams: any = {}) => { + Object.is(size, 'small') ? this.setLoading(key.typeVal, true) : this.fn(true); + const param = { + metricName: this.getMetricName(key), + instanceId: this.instanceId, + ...selectParams, + // 周期 + timeInterval: Number(this.cycle.value.split('min')[0]) * 60, + } + const otherParams = !this.value1.value ? {lastManyTime: Number(this.setTabsParams())} : this.setDateParams(); + try { + const allParams = { + ...param, + ...otherParams, + downSampleType: key.aggregationMethod + } + const res = await monitorDataAPI(allParams); + if (res?.data?.result?.length) { + if (!['main6', 'main7', 'main8', 'main9'].includes(key.id)) { + const [data] = res.data.result; + const initTimeData = data.data.map((item: {timestamp: number}) => (item.timestamp)); + key.data = data.data.map((item: {value: string}) => parseFloat(Number(item.value).toFixed(2))); + key.timeData = data.data.map((item: {timestamp: number}) => getMonthHoursMinutes(item.timestamp)); + this.setData(key, size, initTimeData); + } + else { + const newData: NewDataType[] = Array.from(res.data.result, (item: {data: {map: NewDataType['map']}}) => { + return item.data.map((ite: {value: string}) => { + const value = parseFloat(ite.value); + return isNaN(value) ? NaN : value; + }); + }); + const newTimes: NewTimeType[] = Array.from(res.data.result, (item: {data: {map: NewTimeType['map']}}) => { + return item.data.map((ite: {timestamp: number}) => getMonthHoursMinutes(ite.timestamp)); + }); + const newArrData = newData.map((item) => { + return item.map((t) => parseFloat(Number(t).toFixed(2))) + }); + const initTimes: NewTimeType[] = Array.from(res.data.result, (item: {data: {map: NewTimeType['map']}}) => { + return item.data.map((ite: {timestamp: number}) => (ite.timestamp)); + }); + key.data = newArrData; + key.timeData = [newTimes[0]]; + this.setData(key, size, initTimes[0]); + } + return; + } + throw new Error(''); + } + catch { + key.data = []; + key.timeData = []; + this.setData(key, size, []); + } + finally { + Object.is('bigSize', size) ? this.fn(false) : this.setLoading(key.typeVal, false); + } + } + + setLoading = (type: string, bol: boolean) => { + const that = this; + for (let index in this.reactiveArr.isLoadingObj) { + if (index === type) { + (this.reactiveArr.isLoadingObj[`${index}` as keyof typeof that.reactiveArr.isLoadingObj] as boolean) = bol; + } + } + } + + getMetricName = (key: T) => { + if (this.mountpointVal.value?.length) { + return key.paramsMetricName; + } + return typeof key.metricName === 'string' ? key.metricName : key.metricName.join(',') + } + + setDateParams = () => { + return { + // @ts-ignore + startTime: this.value1.value[0].getTime() / 1000, endTime: this.value1.value[1].getTime() / 1000 + }; + } + + setTabsParams = () => { + const obj = new Map([ + [global.t('monitorEcharts.tabs.h1'), '1'], + [global.t('monitorEcharts.tabs.h6'), '6'], + [global.t('monitorEcharts.tabs.h12'), '12'], + [global.t('monitorEcharts.tabs.d1'), '24'], + [global.t('monitorEcharts.tabs.d3'), '72'], + [global.t('monitorEcharts.tabs.d7'), '168'], + [global.t('monitorEcharts.tabs.d14'), '336'] + ]) + return obj.get(this.hours.value); + } + + setData = (key: any, size: string, data: number[] | NewTimeType) => { + let id: string = ''; + nextTick(() => { + if (document.getElementById(key.id)) { + id = Object.is(size, 'small') ? key.id : 'bigSize'; + this.reqEcharts(id, key.data, key.type, key.timeData, key.unit, key.hoverUnit, data) + } + }) + } + + reqEcharts = (id: string, ...args: any) => { + const newData = !Array.isArray(args[1]) ? [ + seriesDataObj(args[1], args[0], publicConfigOpt.singleColor) + ] : [ + ...this.setEcharts(args[1], args[0]) + ]; + const myChart: echarts.ECharts | undefined = echarts?.getInstanceByDom(document.getElementById(id) as HTMLElement); + publicOption([args[1]], args[2], args[3], newData, args[0], args[4], id, args[5]).then((res: any) => { + echartsOpt(res, id, myChart); + }) + .catch((err) => { + throw new Error(err) + }) + } + + setEcharts = (data: string[], args: number[][]) => { + let newData = []; + for (let i = 0; i < data.length; i++) { + newData.push(seriesDataObj(data[i], args[i], publicConfigOpt.moreColor[i])); + } + return newData; + } + + selectChange = (val: string, value: string) => { + const that = this; + this.ruleForm[`${val}` as keyof typeof that.ruleForm] = value; + // @ts-ignore + publicConfigOpt.smallBigSet(that, val, 'small', value); + } +} + +export default EchartsOpt; \ No newline at end of file diff --git a/bmp-console-web/src/components/common/performanceMonitoring/echartsPage.vue b/bmp-console-web/src/components/common/performanceMonitoring/echartsPage.vue new file mode 100644 index 0000000..5630f74 --- /dev/null +++ b/bmp-console-web/src/components/common/performanceMonitoring/echartsPage.vue @@ -0,0 +1,64 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/common/performanceMonitoring/options.ts b/bmp-console-web/src/components/common/performanceMonitoring/options.ts new file mode 100644 index 0000000..de01b40 --- /dev/null +++ b/bmp-console-web/src/components/common/performanceMonitoring/options.ts @@ -0,0 +1,230 @@ +/** + * @file + * @author +*/ + +import echarts from './utils/publicQuote'; + +const kb: number = 1000; +const mb: number = kb * 1000; +const gb: number = mb * 1000; +const tb: number = gb * 1000; +const pb: number = tb * 1000; +const eb: number = pb * 1000; + +const reg = (str: string) => str.replace(/\.00$/, ''); +let newMyChart: any; +const publicOption = (legendData: string[], ...args: any) => { + + const status = Object.is(args[5], 'bigSize'); + return new Promise((resolve) => { + resolve({ + title: { + top: '10px', + textStyle: { + fontSize: 14 + } + }, + tooltip: { + trigger: 'axis', + formatter: function (params: {seriesName: string; value: number; color: string; axisValue: string;}[]) { + let res: string = ''; + for (let i = 0, l = params.length; i < l; i++) { + const yearSecond = new Date(args[6][i] * 1000); + const monthDateTime = params[i].axisValue.replace(/\n/g, ','); + const seconds = yearSecond.getSeconds() < 10 ? '0' + yearSecond.getSeconds() : yearSecond.getSeconds(); + res += `

${yearSecond.getFullYear()}-${monthDateTime.split(',').reverse()[0] + ' ' + monthDateTime.split(',').reverse()[1] + ':' + seconds}

` + res += ''; + // res += symbol + ' ' + params[i].seriesName + ' : ' + params[i].value + (args[1] === 'custom' ? flag === '1' ? 'M' : flag === '2' ? 'G' : 'K' : args[4]) +'' + '
'; + // (args[1] === 'custom' ? convertBytesUnit(Number(params[i].value)) : ) + res += ' ' + params[i].seriesName + ' : ' + setUnit(args, params[i].value) + '
'; + } + return res; + }, + textStyle: { + color: '#333', + fontSize: 12 + } + }, + legend: { + data: isMultiDimensional(legendData) ? legendData[0] : legendData, + left: status ? '-5px' : '13px', + top: '5%', + itemWidth: 16, + itemHeight: 8, + textStyle: { + color: '#333', + fontSize: 12 + }, + }, + grid: { + left: status ? '0' : '4.7%', + // left: status ? '2.2%' : isMultiDimensional(args[3]) ? args[2].map((item: {data: number[]}) => item.data).flat().some((t: number) => t > 100) ? '4%' : '3%' : args[3].some((t: number) => t > 100) ? '5%' : '4%', + // left: status ? '2.2%' : isMultiDimensional(args[3]) ? args[2].map((item: {data: number[]}) => item.data).flat().some((t: number) => t > 100) ? '5%' : '1%' : Object.is(args[1], '%') && args[3].some((item: number) => item < 100) ? '5%' : args[3].some((item: number) => item > 100) ? '4%' : '3%', + // right: '7%', + bottom: '3%', + containLabel: true + }, + xAxis: { + type: 'category', + boundaryGap: false, + data: isMultiDimensional(args[0]) ? args[0][0].map(function (str: string) { + return str.replace(' ', '\n'); + }) : args[0].map(function (str: string) { + return str.replace(' ', '\n'); + }), + }, + yAxis: { + type: 'value', + // min: isMultiDimensional(args[3]) ? 0 : Math.min(...args[3]), + min: isMultiDimensional(args[3]) ? 0 : args[3].every((item: number) => item <= 0) ? '' : args[3].every((item: number) => item < 100) ? 0 : Math.min(...args[3]), + max: isMultiDimensional(args[3]) ? '' : args[3].every((item: number) => item <= 0) ? '' : args[3].every((item: number) => item < 100) ? 100 : '', + // min: isMultiDimensional(args[3]) ? 0 : Object.is(args[1], '%') && args[3].some((item: number) => item > 100) ? 0 : Math.min(...args[3]), + // max: isMultiDimensional(args[3]) ? setData(args[3]).some((item: number) => item > 100) ? '' : args[3].some((item: number) => item > 100) ? '' : 100 : Object.is(args[1], '%') && args[2][0]?.data?.length ? 100 : '', + axisLabel: { + formatter: function(value: number) { + return setFormAtter(args, value) + } + } + }, + dataZoom: [ + { + type: 'inside', + show: false, + start: Math.min(...args[6]), + end: Math.max(...args[6]), + } + ], + series: args[2] + }) + }) +}; + +const addSymbol = (num: string) => { + return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'); +}; + +const setFormAtter = (args: any, value: number) => { + const objData = [ + [ + () => ['custom'].includes(args[1]), + () => {return `${convertBytesUnit(value)}`} + ], + [ + () => ['个', '次/秒', '个/秒'].includes(args[1]), + () => { + if (value >= 1000) { + return reg(addSymbol(parseFloat(String(value / 1000)).toFixed(2))) + 'K'; + } + return `${reg(value.toFixed(2))}` + } + ], + [ + () => args[1] || !args[1], + () => {return `${reg(value.toFixed(2))}`} + ] + ]; + for (const key of objData) { + if (key[0]()) { + return key[1](); + } + } +} + +// const setData = (data: number[][]): number[] => { +// let newData: number[] = []; +// data.forEach((item) => { +// newData.push(...item) +// }) +// return newData; +// } + +const setUnit = (args: any, value: T) => { + if (['custom'].includes(args[1])) { + return convertBytesUnit(Number(value)); + } + else if (['个', '次/秒', '个/秒'].includes(args[1])) { + if (value >= 1000) { + return reg(addSymbol(parseFloat(String(value / 1000)).toFixed(2))) + 'K'; + } + return `${value}个`; + } + else { + return reg(value.toFixed(2)) + args[4]; + } +} + + +const convertBytesUnit = (bytes: number) => { + const dataList = [ + [ + () => bytes < kb, + () => {return reg(String(bytes)) + ' B';} + ], + [ + () => bytes < mb, + () => {return reg((bytes / kb).toFixed(2)) + ' K';} + ], + [ + () => bytes < gb, + () => {return reg((bytes / mb).toFixed(2)) + ' M';} + ], + [ + () => bytes < tb, + () => {return reg((bytes / gb).toFixed(2)) + ' G';} + ], + [ + () => bytes < pb, + () => {return reg((bytes / tb).toFixed(2)) + ' T';} + ], + [ + () => bytes < eb, + () => {return reg((bytes / pb).toFixed(2)) + ' P';} + ] + ]; + for (const key of dataList) { + if (key[0]()) { + return key[1](); + } + } +} + + +const isMultiDimensional = (arr: string[] | number[][]) => { + return Array.isArray(arr) && arr.some((item: any) => Array.isArray(item)); +} + +const seriesDataObj = (name: any, ...args: any) => { + return { + name, + type: 'line', + smooth: true, + data: args[0], + itemStyle: { + color: args[1], // 点的颜色 + lineStyle: { + color: args[1] // 线的颜色 + } + }, + }; +} + +const echartsOpt = (res: any, type: string, myChart: any) => { + if (!res.yAxis.max) { + Reflect.deleteProperty(res.yAxis, 'max') + } + if (myChart === void 0) { + myChart = echarts.init(document.getElementById(type)); + newMyChart = myChart; + // window.addEventListener('resize', () => size(myChart)) + // window.removeEventListener('resize', () => size(myChart)) + } + res && myChart.setOption(res); +} + +export { + newMyChart, + publicOption, + seriesDataObj, + echartsOpt +}; diff --git a/bmp-console-web/src/components/common/performanceMonitoring/performanceMonitoring.vue b/bmp-console-web/src/components/common/performanceMonitoring/performanceMonitoring.vue new file mode 100644 index 0000000..b76d69e --- /dev/null +++ b/bmp-console-web/src/components/common/performanceMonitoring/performanceMonitoring.vue @@ -0,0 +1,205 @@ + + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/common/performanceMonitoring/type.ts b/bmp-console-web/src/components/common/performanceMonitoring/type.ts new file mode 100644 index 0000000..69efd24 --- /dev/null +++ b/bmp-console-web/src/components/common/performanceMonitoring/type.ts @@ -0,0 +1,96 @@ +/** + * @file + * @author +*/ + +interface NewDataType { + map: (args: (ite: {value: string;}) => number) => NewDataType; +}[]; + +interface NewTimeType { + map: (args: (ite: {timestamp: number;}) => number) => NewTimeType; +}[]; + +interface HourRangesType { + '0': string; + '6': string; + '12': string; + '24': string; +}; + +type EchartsParamsDataType = { + title: string; + showType: string[]; + model: string; + type: string; + id: string; + bigClickVal: { + type: string; + title: string; + model: string; + } +}[]; + + +type PublicType = { + typeVal: T; + id: string; + data: NewDataType[]; + type: string | string[]; + timeData: NewTimeType[]; + aggregationMethod: string; + metricName: string | string[]; + unit: string; + hoverUnit: string; + status?: string[] | undefined; + + paramsMetricName?: string; +}; + +interface EchartsDataType extends PublicType { + filter(arg0: (item: {status: string}) => boolean): []; +}; + +interface EchartsDataObjType extends PublicType {}; + +interface ReactiveArrType { + aggregationMethod: string[]; + isLoadingObj: {[x: string]: boolean} | {}; + echartsParamsData: EchartsParamsDataType; + echartsData: EchartsDataType; +}; + +type FormType1 = { + cpu: string; + mem: string; + memUsage: string; + diskUsage: string; + diskUsageRate: string; +}; + +type FormType2 = { + diskReadWriteTraffic: string; + diskReadWriteIOPS: string; + netWorkBps: string; + netWorkPackagesNum: string; + averageLoad1Min: string; +}; + +interface RuleFormType extends FormType1, FormType2 { + averageLoad5Min: string; + averageLoad15Min: string; + totalTCPConnections: string; + normalTCPConnections: string; + totalNumberOfProcesses: string; +}; + +export { + NewDataType, + NewTimeType, + RuleFormType, + HourRangesType, + EchartsDataType, + ReactiveArrType, + EchartsDataObjType, + EchartsParamsDataType +} \ No newline at end of file diff --git a/bmp-console-web/src/components/common/performanceMonitoring/utils/echartsBigOpt.ts b/bmp-console-web/src/components/common/performanceMonitoring/utils/echartsBigOpt.ts new file mode 100644 index 0000000..dddc9dc --- /dev/null +++ b/bmp-console-web/src/components/common/performanceMonitoring/utils/echartsBigOpt.ts @@ -0,0 +1,51 @@ +/** + * @file + * @author +*/ +import { + ref, + Ref +} from 'vue'; +import {RuleFormType} from '../type'; +import publicConfigOpt from './publicConfig'; + +class EchartsBigOpt { + diaLog: Ref = ref(false); + sizeBigTitle: Ref = ref(''); + sizeRef: Ref = ref(''); + bigSizeLoading: Ref = ref(true); + props; + + constructor(props: any) { + this.props = props; + } + + closeClick = (val: string) => { + const that = this; + this.diaLog.value = !this.diaLog.value; + this.props.ruleForm[`${val}` as keyof typeof that.props.ruleForm] = this.props.ruleForm[`${this.sizeRef.value}` as keyof typeof that.props.ruleForm]; + const newVals = this.props.reactiveArr.echartsParamsData.filter((item: {type: string}) => item.type === val)[0]; + newVals.model = this.props.ruleForm[`${val}` as keyof typeof that.props.ruleForm]; + const newData = this.props.reactiveArr.echartsData.filter((item: {typeVal: string}) => item.typeVal === val) + const {diskVal, mountpointVal, nicVal} = this.props; + const deviceVal = diskVal.value ? {device: diskVal.value} : mountpointVal.value ? {device: mountpointVal.value} : nicVal.value ? {device: nicVal.value} : {}; + publicConfigOpt.clearEmptyObj(deviceVal); + for (const key of newData) { + key.aggregationMethod = this.props.ruleForm[`${this.sizeRef.value}` as keyof typeof that.props.ruleForm]; + this.props.getEcharts(key, 'small', deviceVal); + } + } + + bigClickOpt = (value: string, ...args: string[]) => { + this.sizeRef.value = value; + this.sizeBigTitle.value = args[0]; + this.diaLog.value = !this.diaLog.value; + publicConfigOpt.smallBigSet(this.props, value, 'bigSize', '') + } + + bigSizeChange = (val: string, obj: RuleFormType, value: string) => { + publicConfigOpt.smallBigSet(this.props, val, 'bigSize', obj[`${value}` as keyof typeof obj]) + } +} + +export default EchartsBigOpt; \ No newline at end of file diff --git a/bmp-console-web/src/components/common/performanceMonitoring/utils/initStaticData.ts b/bmp-console-web/src/components/common/performanceMonitoring/utils/initStaticData.ts new file mode 100644 index 0000000..c8e4618 --- /dev/null +++ b/bmp-console-web/src/components/common/performanceMonitoring/utils/initStaticData.ts @@ -0,0 +1,428 @@ +/** + * @file + * @author +*/ +import i18n from 'lib/i18n/index.ts'; // 国际化 +// 国际化 +const {global} = i18n; + +import {EchartsDataType, EchartsParamsDataType} from '../type'; + +type CurrencyType8 = {value: string; label: string;}; +type NewEchartsDataStaticType = Omit[] + +class InitStaticData { + static echartsData: NewEchartsDataStaticType = [ + { + typeVal: 'cpu', + id: 'main', + data: [], + type: global.t('monitorEcharts.echartsCount.cpu'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.cpu.util', + unit: '%', + hoverUnit: '%' + }, + { + typeVal: 'mem', + id: 'main2', + data: [], + type: global.t('monitorEcharts.echartsCount.mem'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.memory.util', + unit: '%', + hoverUnit: '%' + }, + { + typeVal: 'memUsage', + id: 'main3', + data: [], + type: global.t('monitorEcharts.echartsCount.memUsage'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.memory.used', + unit: 'GB', + hoverUnit: 'GB' + }, + { + typeVal: 'diskUsage', + id: 'main4', + data: [], + type: global.t('monitorEcharts.echartsCount.diskUsage'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.disk.used', + paramsMetricName: 'bmp.disk.partition.used', + unit: 'GB', + hoverUnit: 'GB', + status: ['diskVal', 'mountpointVal'] + }, + { + typeVal: 'diskUsageRate', + id: 'main5', + data: [], + type: global.t('monitorEcharts.echartsCount.diskUsageRate'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.disk.util', + paramsMetricName: 'bmp.disk.partition.util', + unit: '%', + hoverUnit: '%', + status: ['diskVal', 'mountpointVal'] + }, + { + typeVal: 'diskReadWriteTraffic', + id: 'main6', + data: [], + type: [ + global.t('monitorEcharts.echartsCount.diskReadTraffic'), + global.t('monitorEcharts.echartsCount.diskWriteTraffic') + ], + timeData: [], + aggregationMethod: 'avg', + metricName: ['bmp.disk.bytes.read', 'bmp.disk.bytes.write'], + //unit: 'M', + hoverUnit: '', + unit: 'custom', + status: ['diskVal'] + }, + { + typeVal: 'diskReadWriteIOPS', + id: 'main7', + data: [], + type: [ + global.t('monitorEcharts.echartsCount.diskReadIOPS'), + global.t('monitorEcharts.echartsCount.diskWriteIOPS') + ], + timeData: [], + aggregationMethod: 'avg', + metricName: ['bmp.disk.counts.read', 'bmp.disk.counts.write'], + unit: '次/秒', + hoverUnit: '次/秒', + status: ['diskVal'] + }, + { + typeVal: 'netWorkBps', + id: 'main8', + data: [], + type: [ + global.t('monitorEcharts.echartsCount.netWorkIn'), + global.t('monitorEcharts.echartsCount.netWorkOut') + ], + timeData: [], + aggregationMethod: 'avg', + metricName: ['bmp.network.bytes.ingress', 'bmp.network.bytes.egress'], + //unit: '', + unit: 'custom', + hoverUnit: '', + status: ['nicVal'] + }, + { + typeVal: 'netWorkPackagesNum', + id: 'main9', + data: [], + type: [ + global.t('monitorEcharts.echartsCount.netWorkInPackageNum'), + global.t('monitorEcharts.echartsCount.netWorkOutPackageNum') + ], + timeData: [], + aggregationMethod: 'avg', + metricName: ['bmp.network.packets.ingress', 'bmp.network.packets.egress'], + unit: '个/秒', + hoverUnit: '个/秒', + status: ['nicVal'] + }, + { + typeVal: 'averageLoad1Min', + id: 'main10', + data: [], + type: global.t('monitorEcharts.echartsCount.averageLoad1Min'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.avg.load1', + unit: '', + hoverUnit: '' + }, + { + typeVal: 'averageLoad5Min', + id: 'main11', + data: [], + type: global.t('monitorEcharts.echartsCount.averageLoad5Min'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.avg.load5', + unit: '', + hoverUnit: '' + }, + { + typeVal: 'averageLoad15Min', + id: 'main12', + data: [], + type: global.t('monitorEcharts.echartsCount.averageLoad15Min'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.avg.load15', + unit: '', + hoverUnit: '' + }, + { + typeVal: 'totalTCPConnections', + id: 'main13', + data: [], + type: global.t('monitorEcharts.echartsCount.totalTCPConnections'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.tcp.connect.total', + unit: '个', + hoverUnit: '个' + }, + { + typeVal: 'normalTCPConnections', + id: 'main14', + data: [], + type: global.t('monitorEcharts.echartsCount.normalTCPConnections'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.tcp.connect.established', + unit: '个', + hoverUnit: '个' + }, + { + typeVal: 'totalNumberOfProcesses', + id: 'main15', + data: [], + type: global.t('monitorEcharts.echartsCount.totalNumberOfProcesses'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.process.total', + unit: '个', + hoverUnit: '个' + } + ]; + + static radioData: CurrencyType8[] = [ + { + label: global.t('monitorEcharts.tabs.h1'), + value: '1min' + }, + { + label: global.t('monitorEcharts.tabs.h6'), + value: '5min' + }, + { + label: global.t('monitorEcharts.tabs.h12'), + value: '10 min' + }, + { + label: global.t('monitorEcharts.tabs.d1'), + value: '20 min' + }, + { + label: global.t('monitorEcharts.tabs.d3'), + value: '60min' + }, + { + label: global.t('monitorEcharts.tabs.d7'), + value: '120min' + }, + { + label: global.t('monitorEcharts.tabs.d14'), + value: '180min' + } + ]; + + static echartsParamsData: EchartsParamsDataType = [ + { + title: global.t('monitorEcharts.echartsCount.cpuUnit'), + showType: [global.t('monitorEcharts.radio.instance')], + model: '', + type: 'cpu', + id: 'main', + bigClickVal: { + type: 'cpu', + title: global.t('monitorEcharts.echartsCount.cpuUnit'), + model: '' + } + }, + { + title: global.t('monitorEcharts.echartsCount.memUnit'), + showType: [global.t('monitorEcharts.radio.instance')], + model: '', + type: 'mem', + id: 'main2', + bigClickVal: { + type: 'mem', + title: global.t('monitorEcharts.echartsCount.memUnit'), + model: '' + } + }, + { + title: global.t('monitorEcharts.echartsCount.memUsageUnit'), + showType: [global.t('monitorEcharts.radio.instance')], + model: '', + type: 'memUsage', + id: 'main3', + bigClickVal: { + type: 'memUsage', + title: global.t('monitorEcharts.echartsCount.memUsageUnit'), + model: '' + } + }, + { + title: global.t('monitorEcharts.echartsCount.diskUsageUnit'), + showType: [ + global.t('monitorEcharts.radio.instance'), + global.t('monitorEcharts.radio.disk'), + global.t('monitorEcharts.radio.diskPartition') + ], + model: '', + type: 'diskUsage', + id: 'main4', + bigClickVal: { + type: 'diskUsage', + title: global.t('monitorEcharts.echartsCount.diskUsageUnit'), + model: '' + } + }, + { + title: global.t('monitorEcharts.echartsCount.diskUsageRateUnit'), + showType: [ + global.t('monitorEcharts.radio.instance'), + global.t('monitorEcharts.radio.disk'), + global.t('monitorEcharts.radio.diskPartition') + ], + model: '', + type: 'diskUsageRate', + id: 'main5', + bigClickVal: { + type: 'diskUsageRate', + title: global.t('monitorEcharts.echartsCount.diskUsageRateUnit'), + model: '' + } + }, + { + title: global.t('monitorEcharts.echartsCount.diskReadWriteTrafficUnit'), + showType: [global.t('monitorEcharts.radio.instance'), global.t('monitorEcharts.radio.disk')], + model: '', + type: 'diskReadWriteTraffic', + id: 'main6', + bigClickVal: { + type: 'diskReadWriteTraffic', + title: global.t('monitorEcharts.echartsCount.diskReadWriteTrafficUnit'), + model: '' + } + }, + { + title: global.t('monitorEcharts.echartsCount.diskReadWriteIOPSUnit'), + showType: [global.t('monitorEcharts.radio.instance'), global.t('monitorEcharts.radio.disk')], + model: '', + type: 'diskReadWriteIOPS', + id: 'main7', + bigClickVal: { + type: 'diskReadWriteIOPS', + title: global.t('monitorEcharts.echartsCount.diskReadWriteIOPSUnit'), + model: '' + } + }, + { + title: global.t('monitorEcharts.echartsCount.netWorkBpsUnit'), + showType: [global.t('monitorEcharts.radio.instance'), global.t('monitorEcharts.radio.netWorkInterface')], + model: '', + type: 'netWorkBps', + id: 'main8', + bigClickVal: { + type: 'netWorkBps', + title: global.t('monitorEcharts.echartsCount.netWorkBpsUnit'), + model: '' + } + }, + { + title: global.t('monitorEcharts.echartsCount.netWorkPackagesNumUnit'), + showType: [global.t('monitorEcharts.radio.instance'), global.t('monitorEcharts.radio.netWorkInterface')], + model: '', + type: 'netWorkPackagesNum', + id: 'main9', + bigClickVal: { + type: 'netWorkPackagesNum', + title: global.t('monitorEcharts.echartsCount.netWorkPackagesNumUnit'), + model: '' + } + }, + { + title: global.t('monitorEcharts.echartsCount.averageLoad1MinUnit'), + showType: [global.t('monitorEcharts.radio.instance')], + model: '', + type: 'averageLoad1Min', + id: 'main10', + bigClickVal: { + type: 'averageLoad1Min', + title: global.t('monitorEcharts.echartsCount.averageLoad1MinUnit'), + model: '' + } + }, + { + title: global.t('monitorEcharts.echartsCount.averageLoad5MinUnit'), + showType: [global.t('monitorEcharts.radio.instance')], + model: '', + type: 'averageLoad5Min', + id: 'main11', + bigClickVal: { + type: 'averageLoad5Min', + title: global.t('monitorEcharts.echartsCount.averageLoad5MinUnit'), + model: '' + } + }, + { + title: global.t('monitorEcharts.echartsCount.averageLoad15MinUnit'), + showType: [global.t('monitorEcharts.radio.instance')], + model: '', + type: 'averageLoad15Min', + id: 'main12', + bigClickVal: { + type: 'averageLoad15Min', + title: global.t('monitorEcharts.echartsCount.averageLoad15MinUnit'), + model: '' + } + }, + { + title: global.t('monitorEcharts.echartsCount.totalTCPConnectionsUnit'), + showType: [global.t('monitorEcharts.radio.instance')], + model: '', + type: 'totalTCPConnections', + id: 'main13', + bigClickVal: { + type: 'totalTCPConnections', + title: global.t('monitorEcharts.echartsCount.totalTCPConnectionsUnit'), + model: '' + } + }, + { + title: global.t('monitorEcharts.echartsCount.normalTCPConnectionsUnit'), + showType: [global.t('monitorEcharts.radio.instance')], + model: '', + type: 'normalTCPConnections', + id: 'main14', + bigClickVal: { + type: 'normalTCPConnections', + title: global.t('monitorEcharts.echartsCount.normalTCPConnectionsUnit'), + model: '' + } + }, + { + title: global.t('monitorEcharts.echartsCount.totalNumberOfProcessesUnit'), + showType: [global.t('monitorEcharts.radio.instance')], + model: '', + type: 'totalNumberOfProcesses', + id: 'main15', + bigClickVal: { + type: 'totalNumberOfProcesses', + title: global.t('monitorEcharts.echartsCount.totalNumberOfProcessesUnit'), + model: '' + } + } + ] +} + +export default InitStaticData; diff --git a/bmp-console-web/src/components/common/performanceMonitoring/utils/publicConfig.ts b/bmp-console-web/src/components/common/performanceMonitoring/utils/publicConfig.ts new file mode 100644 index 0000000..570ee54 --- /dev/null +++ b/bmp-console-web/src/components/common/performanceMonitoring/utils/publicConfig.ts @@ -0,0 +1,54 @@ +/** + * @file + * @author +*/ +import {EchartsDataType, EchartsDataObjType} from '../type'; + +type ObjType = { + reactiveArr: { + echartsData: EchartsDataType[]; + }; + diskVal: { + value: string; + }; + mountpointVal: { + value: string; + }; + nicVal: { + value: string; + }; + getEcharts(arg0: EchartsDataObjType, arg1: string, arg2: { device: string; } | { device?: undefined; }): void; +} + +class PublicConfigOpt { + singleColor: string = '#108ee9'; + moreColor: string[] = [ + '#108ee9', + '#29d1d3' + ]; + + aggregationMethod: string[] = ['avg', 'max', 'min', 'sum']; + + clearEmptyObj = (deviceVal: T) => { + if (!Object.keys(deviceVal).length) { + Reflect.deleteProperty(deviceVal, 'device') + } + } + + smallBigSet = (obj: ObjType, val: string, type: string, value: string) => { + const newData = obj.reactiveArr.echartsData.filter((item: {typeVal: string}) => item.typeVal === val); + const {diskVal, mountpointVal, nicVal} = obj; + const deviceVal = diskVal.value ? {device: diskVal.value} : mountpointVal.value ? {device: mountpointVal.value} : nicVal.value ? {device: nicVal.value} : {}; + this.clearEmptyObj(deviceVal); + for (const key of newData) { + if (value?.length) { + key.aggregationMethod = value; + } + obj.getEcharts(key, type, deviceVal); + } + } +} + +const publicConfigOpt = new PublicConfigOpt(); + +export default publicConfigOpt; \ No newline at end of file diff --git a/bmp-console-web/src/components/common/performanceMonitoring/utils/publicQuote.ts b/bmp-console-web/src/components/common/performanceMonitoring/utils/publicQuote.ts new file mode 100644 index 0000000..1ea6f50 --- /dev/null +++ b/bmp-console-web/src/components/common/performanceMonitoring/utils/publicQuote.ts @@ -0,0 +1,28 @@ +/** + * @file + * @author +*/ + +// 按需引入引入echarts核心模块 +import * as echarts from 'echarts/core'; +// 引入折线图 +import {LineChart} from 'echarts/charts'; +// 引入必需的组件 +import {TitleComponent, TooltipComponent, LegendComponent, GridComponent} from 'echarts/components'; +// 引入Canvas渲染器 +import {CanvasRenderer} from 'echarts/renderers'; + // 引入缩放组件 +import {DataZoomComponent} from 'echarts/components'; + +// 注册必需组件 +echarts.use([ + TitleComponent, + TooltipComponent, + LegendComponent, + GridComponent, + LineChart, + CanvasRenderer, + DataZoomComponent +]); + +export default echarts; diff --git a/bmp-console-web/src/components/common/performanceMonitoring/utils/ruleForm.ts b/bmp-console-web/src/components/common/performanceMonitoring/utils/ruleForm.ts new file mode 100644 index 0000000..52ce0ee --- /dev/null +++ b/bmp-console-web/src/components/common/performanceMonitoring/utils/ruleForm.ts @@ -0,0 +1,29 @@ +/** + * @file + * @author +*/ +import {RuleFormType} from '../type'; +import { + reactive, +} from 'vue'; +class RuleFormOpt { + ruleForm: RuleFormType = reactive({ + cpu: 'avg', + mem: 'avg', + memUsage: 'avg', + diskUsage: 'avg', + diskUsageRate: 'avg', + diskReadWriteTraffic: 'avg', + diskReadWriteIOPS: 'avg', + netWorkBps: 'avg', + netWorkPackagesNum: 'avg', + averageLoad1Min: 'avg', + averageLoad5Min: 'avg', + averageLoad15Min: 'avg', + totalTCPConnections: 'avg', + normalTCPConnections: 'avg', + totalNumberOfProcesses: 'avg' + }) +} + +export default RuleFormOpt; diff --git a/bmp-console-web/src/components/custom/custom.vue b/bmp-console-web/src/components/custom/custom.vue new file mode 100644 index 0000000..db7a318 --- /dev/null +++ b/bmp-console-web/src/components/custom/custom.vue @@ -0,0 +1,278 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/logout/logout.vue b/bmp-console-web/src/components/logout/logout.vue new file mode 100644 index 0000000..805b390 --- /dev/null +++ b/bmp-console-web/src/components/logout/logout.vue @@ -0,0 +1,111 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/multipleOperate/batchClose.vue b/bmp-console-web/src/components/multipleOperate/batchClose.vue new file mode 100644 index 0000000..4e0ffae --- /dev/null +++ b/bmp-console-web/src/components/multipleOperate/batchClose.vue @@ -0,0 +1,138 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/multipleOperate/batchDelete.vue b/bmp-console-web/src/components/multipleOperate/batchDelete.vue new file mode 100644 index 0000000..7d5e939 --- /dev/null +++ b/bmp-console-web/src/components/multipleOperate/batchDelete.vue @@ -0,0 +1,147 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/multipleOperate/batchDropdown.vue b/bmp-console-web/src/components/multipleOperate/batchDropdown.vue new file mode 100644 index 0000000..a20c6a1 --- /dev/null +++ b/bmp-console-web/src/components/multipleOperate/batchDropdown.vue @@ -0,0 +1,137 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/multipleOperate/batchOpen.vue b/bmp-console-web/src/components/multipleOperate/batchOpen.vue new file mode 100644 index 0000000..76e3257 --- /dev/null +++ b/bmp-console-web/src/components/multipleOperate/batchOpen.vue @@ -0,0 +1,138 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/multipleOperate/batchRename.vue b/bmp-console-web/src/components/multipleOperate/batchRename.vue new file mode 100644 index 0000000..407b7fc --- /dev/null +++ b/bmp-console-web/src/components/multipleOperate/batchRename.vue @@ -0,0 +1,275 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/multipleOperate/batchRepassword.vue b/bmp-console-web/src/components/multipleOperate/batchRepassword.vue new file mode 100644 index 0000000..de2e8f9 --- /dev/null +++ b/bmp-console-web/src/components/multipleOperate/batchRepassword.vue @@ -0,0 +1,332 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/multipleOperate/batchRestart.vue b/bmp-console-web/src/components/multipleOperate/batchRestart.vue new file mode 100644 index 0000000..a511c9a --- /dev/null +++ b/bmp-console-web/src/components/multipleOperate/batchRestart.vue @@ -0,0 +1,138 @@ + + + \ No newline at end of file diff --git a/bmp-console-web/src/components/multipleOperate/batchTable.vue b/bmp-console-web/src/components/multipleOperate/batchTable.vue new file mode 100644 index 0000000..94774bb --- /dev/null +++ b/bmp-console-web/src/components/multipleOperate/batchTable.vue @@ -0,0 +1,109 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/hooks/useCurrentInstance.ts b/bmp-console-web/src/hooks/useCurrentInstance.ts new file mode 100644 index 0000000..97d4dd5 --- /dev/null +++ b/bmp-console-web/src/hooks/useCurrentInstance.ts @@ -0,0 +1,8 @@ +import { ComponentInternalInstance, getCurrentInstance } from 'vue' +export default function useCurrentInstance() { + const { appContext } = getCurrentInstance() as ComponentInternalInstance + const globalProperties = appContext.config.globalProperties + return { + globalProperties + } +} \ No newline at end of file diff --git a/bmp-console-web/src/lib/element/index.ts b/bmp-console-web/src/lib/element/index.ts new file mode 100644 index 0000000..2ec96e6 --- /dev/null +++ b/bmp-console-web/src/lib/element/index.ts @@ -0,0 +1,4 @@ +import ElementPlus from 'element-plus'; +import 'element-plus/dist/index.css'; + +export default ElementPlus; diff --git a/bmp-console-web/src/lib/filters/filter.ts b/bmp-console-web/src/lib/filters/filter.ts new file mode 100644 index 0000000..f84cc93 --- /dev/null +++ b/bmp-console-web/src/lib/filters/filter.ts @@ -0,0 +1,46 @@ +// ComponentCustomProperties用于扩充组件实例类型以支持自定义全局属性,否则会报警告。 + +declare module 'vue' { + export interface ComponentCustomProperties { + $filter: any; + } +} +const filter = (app: any) => app.config.globalProperties.$filter = { +/* eslint-disable indent */ + withClonZh(value: string): string { + return value + ':'; + }, + + withClon(value: string): string { + return value + ':'; + }, + + emptyFilter(value: string | null | undefined): string { + switch (value) { + case '': + case undefined: + case null: + return '--'; + default: + return value; + } + }, + + numberEmptyFilter(value: string | null | undefined): string { + switch (value) { + case '': + case undefined: + case null: + return '0'; + default: + return value; + } + }, + + paginationEllipsis(value: string): string { + return value + '...'; + }, +}; + +export default filter; +/* eslint-enable indent */ \ No newline at end of file diff --git a/bmp-console-web/src/lib/i18n/en-US.ts b/bmp-console-web/src/lib/i18n/en-US.ts new file mode 100644 index 0000000..43e686b --- /dev/null +++ b/bmp-console-web/src/lib/i18n/en-US.ts @@ -0,0 +1,725 @@ +export default { + personCentre: { + personCentre: 'Personal Center', + account: 'My Profile', + securitySettings: 'Security Settings', + sshKey: 'Personal SSH Keys', + apiKey: 'Personal API Keys', + quit: 'Logout', + noData: 'No key, you can ', + logout: 'Log Out', + form: { + user: 'User name', + userId: 'User ID', + email: 'Email', + phoneNumber: 'Mobile Phone', + language: 'Language', + timeZone: 'Timezone', + defaultProject: 'Default Project', + basicInformation: 'Account basics', + preferences: 'Console preferences', + save: 'Save', + saving: 'Saving', + selectLanguage: 'Please select a language', + selectTimeZone: 'Please select a timezone', + selectProject: 'Please select a project', + currentPassword: 'Current password', + newPassword: 'New password', + confirmPassword: 'Confirm Password', + change: 'Save Changes', + changing: 'Saving Changes', + createSshKey: 'Create a SSH Key', + createApiKey: 'Create an API Key', + create: 'Create a SSH Key', + keyName: 'Key Name', + createdTime: 'Created Time', + updatedTime: 'Updated Time', + operation: 'Actions', + power: 'Permissions', + keyPairName: 'SSH Key Name', + publicKey: 'Public Key', + editionName: 'Version name', + editionNumber: 'Version number', + invalid: 'Invalid', + efficient: 'Valid', + expired: 'Expired' + }, + operate: { + edit: 'Edit', + copy: 'Copy', + transfer: 'Transfer', + delete: 'Delete', + createSshKey: 'Add a SSH key', + editSshKey: 'Edit the SSH Key', + deleteSshKey: 'Delete the SSH key', + createApiKey: 'Create an API key', + deleteApiKey: 'Delete the API key', + }, + content: { + stringVerification: '1-64 characters, only numbers, letters, underscore “_” and hyphen “-” are supported.', + stringChineseVerification: '1-64 characters, only Chinese, numbers, letters, underscore "_" and hyphen "-" are supported.', + projectNameExist: 'Duplicate project name', + keyNameExist: 'Duplicate key name', + instanceNameExist: 'Duplicate instance name', + passwordVerification: "8-30 characters, and simultaneously including three types (Capital letters, lowercase letters, numbers or special characters()`~!{'@'}#{'{'}{'}'}{'$'}%&*_-+={'|'}[]:\";\'<>,.?/)", + instanceVerification: 'It contains 2-128 characters, beginning with uppercase and lowercase' + + ' letters or Chinese characters, and may contain numbers, ".", "_", ":" or "-".', + hostnameVerification: 'It contains 2-64 characters in length and can be segmented into ' + + 'several' + ' sections with the separator (.). Uppercase and lowercase letters, numbers or ' + + 'hyphens (-)' + ' can be used in each section, but the dot (.) or the hyphen (-) cannot be ' + + 'continuously ' + 'used in each section. It cannot start or end with a dot (.) or a hyphen ' + + '(-).', + publicKeyExample: 'Public key format: ssh-rsa AAAB3NzaCtyc2...', + copySuccess: 'Copied', + fixSuccess: 'Modified Successfully', + operateSuccess: 'Operated Successfully', + operateFailed: 'Operation failed', + operateDoing: 'Doing', + createSuccess: 'Created Successfully', + deleteApiKey: 'Confirm to delete the key: 【{0}】?', + logOut: 'Confirm to log out?', + operateNoModel: 'You have not yet activated this module', + }, + toolTip: { + formSubmit: 'Username does not exist or password is wrong', + emptyEmail: 'Email number cannot be empty', + errorEmail: 'Please enter the correct email address', + emptyPhone: 'Mobile phone number cannot be empty', + errorPhone: 'Please enter the correct mobile phone number', + errorPhoneHongkong: 'Please enter the correct mobile phone number in Hong Kong, China', + errorPhoneMacao: 'Please enter the correct mobile phone number in Macao, China', + errorPhoneTaiwan: 'Please enter the correct mobile phone number in Taiwan, China', + emptyCurrentPassword: 'Current password cannot be empty', + errorCurrentPassword: 'Please enter the correct current password', + emptyNewPassword: 'New password cannot be empty', + emptyconfirmPassword: 'Confirm password cannot be empty', + passNotSame: 'Confirmation password is inconsistent with password', + emptyKeyPassword: 'Please select the SSH Key', + passNotMeetRequire: 'Password does not comply with requirements', + emptyProjectName: 'Project name cannot be empty', + emptyKeyName: 'Key name cannot be empty', + emptyKeyPower: 'Key permission cannot be empty', + emptyPublicKey: 'Public key cannot be empty', + emptyInstanceName: 'Instance name cannot be empty', + emptyHostName: 'Host name cannot be empty', + emptyRelateUser: 'Select shared user cannot be empty', + emptyPower: 'permission cannot be empty', + relateUserTip0: 'Notice : ', + relateUserTip1: '1. Sharing scope: the associated users only include users with the user role who can access the console', + relateUserTip2: '2. Sharing method: Enter the correct user name. After the verification is successful, the user can see the shared project in the project management ', + relateUserTip3: '3. Sharing permission: the shared user can access and manage all resources in the project', + relateUserDeleteTip: 'After removal, the user will not be able to view and operate the resources of this project, please operate with caution', + }, + phoneData: { + chineseMainland: 'Chinese Mainland +86', + chineseHongKong: 'HongKong, China +852', + chineseMacao: 'Macao, China +853', + chineseTaiwan: 'Taiwan, China +886', + Argentina: 'Argentina +54', + Australia: 'Australia +61', + Brazil: 'Brazil +55', + Germany: 'Germany +49', + France: 'France +33', + SouthKorea: 'South Korea +82', + Canada: 'Canada +1', + USA: 'USA +1', + Mexico: 'Mexico +52', + SouthAfrica: 'South Africa +27', + Japan: 'Japan +81', + SaudiArabia: 'Saudi Arabia +966', + Turkey: 'Turkey +90', + Italy: 'Italy +39', + India: 'India +91', + Indonesia: 'Indonesia +62', + UnitedKiongdom: 'United Kiongdom +44', + }, + language: { + chinese: 'Chinese' + }, + apiPower: { + writeAndRead: 'Read/Write', + read: 'Only Read' + }, + placeholder: { + projectName: 'Please enter the project name', + keyPair: 'Please enter the SSH Key', + apiKey: 'Please enter the Key name', + description: 'Please enter the description', + select: 'Please select' + }, + tip: { + createSshKey: 'Only supports creating 2 keypairs', + createApiKey: 'Only supports creating 2 API keys', + }, + detail: { + projectDetail: 'Project Detail', + projectName: 'Project Name', + projectId: 'Project ID', + projectStatus: 'Project Collaboration Status', + creater: 'Creator', + owner: 'Owner', + createdTime: 'Created Time', + updatedTime: 'Updated Time', + addUpdatedUser: 'Add shared user', + relatedUser: 'Associate shared users', + chooseRelateUser: 'Select shared users', + deleteRelatedUser: 'Remove shared users', + userName: 'User Name', + userId: 'User ID', + power: 'Permissions', + delete: 'Remove', + noData: 'There is no associated shared user, you can add ', + } + }, + list: { + back: 'Back', + settings: 'Settings', + update: 'Refresh', + download: 'Export', + createdProject: 'Create a Project', + cancel: 'Cancel', + confirm: 'Confirm', + clear: 'Clear', + search: 'Search', + previousStep: 'Previous', + nextStep: 'Next step', + chooseUser: 'Select user', + chooseResource: 'Select resources', + chooseProject: 'Select project', + project: { + projectMangement: 'Project Settings', + projectName: 'Project Name', + projectId: 'Project ID', + relatedState: 'Project Collaboration Status', + instanceNumber: 'Instances', + noData: 'No projects, you can ', + owner: 'Owner', + cooperate: 'Collaborator', + choosetransferUser: 'Select Transfer User', + resourceChoose: 'Resource selection', + allTransfer: 'Transfer all', + partTransfer: 'Partial transfer', + chooseResource: 'Select resources', + }, + operate: { + open: 'Start up', + close: 'Shutdown', + restart: 'Reboot', + delete: 'Delete', + lock: 'Lock', + unlock: 'Unlock', + resetPassword: 'Reset password', + resystem: 'Reinstall the system', + resystemConfi: 'Reinstall system configuration', + createProject: 'Create a project', + editProject: 'Edit the project', + deleteProject: 'Delete the project', + transferProject: 'Transfer project', + customList: 'Edit Columns', + more: 'More', + bacthClose: 'Batch Shutdown', + bacthOpen: 'Batch Startup', + bacthRestart: 'Batch Reboot', + bacthDelete: 'Batch Delete ', + batchResetPassword: 'Batch Reset Password', + bacthRename: 'Edit instance name in batches', + rename: 'Edit instance name', + resystemSure: 'Instructions for reinstalling the system' + }, + content: { + open: 'Confirm to start up the instance 【{0}】?', + close: 'Confirm to shutdown the instance【{0}】?', + restart: 'Confirm to reboot the instance【{0}】?', + delete: 'Confirm to delete the instance【{0}】?', + lock: 'Confirm to lock the instance【{0}】?', + unlock: 'Confirm to unlock the instance【{0}】?', + deleteProject: 'Confirm to delete the project【{0}】?', + customListMessage: 'Please select the column items to display: ', + repasswordTip: 'Notice:After resetting the password, the instance can only be powered on in the console/operation platform for it to take effect', + batchresetPasswordTip0: 'Notice: ', + batchresetPasswordTip1: '1. Multiple instances of resetting passwords through this method have the same password', + batchresetPasswordTip2: '2. After resetting the password, the instance needs to be powered on on the console/operation platform to take effect', + lockTip: 'The "Delete" action is forbidden after the instance is locked. If you want to use it, you need to unlock it in advance.', + deleteTip: 'Note: Deleting will clear all data on the instance. Please be cautious.', + createError: 'Insufficient inventory', + relateUserDelete: 'Are you sure whether to 【{0}】remove the shared item【{1}】?', + batchContent: 'The', + bacthCloseContent: 'instances you selected will be shutdown, Are you sure about the action?', + bacthOpenContent: 'instances you selected will be startup, Are you sure about the action?', + bacthRestartContent: 'instances you selected will be reboot, Are you sure about the action?', + bacthResetPasswordContent: 'instances you have selected will perform a password reset operation. Are you sure you want to proceed?', + bacthRenameContent: 'instances you selected will be Edit instance name, Are you sure about the action?', + bacthDeleteContent: 'instances you selected will be delete, Are you sure about the action?', + bacthRenameTip: 'Notice: The names of multiple instances edited in this way are named consecutively', + resystemContent: 'The instance you have selected 【{0}】will perform a system reinstallation operation. Are you sure you want to proceed?', + resystemTips: + '1. Reinstallation of the system is an operation that initializes the system disk and replaces the operating system. This operation cannot be restored, please operate with caution!
'+ + '2. This operation will clear all data on the instance system disk. Please backup the data before performing the system reinstallation operation to avoid data loss and causing losses to you.
'+ + '3. After reinstalling the system, the system will not configure IPv6 addresses for the instance by default, and you need to manually configure them.
', + notice: 'Note:', + allInstance: 'All instances ({0} in total)', + selectInstance: 'Selected instances ({0} in total)', + transformAllTip: 'After all resources in a project are transferred, all instance alarm rules in the project will be cleared and no alarm notifications will be received.', + transformPartTip: 'After resources are transferred, the associated alarm rules will be unlinked from the resource and no alarm notifications will be received.', + }, + placeholder: { + instanceName: 'Please enter the insatnce name', + hostName: 'Optional, computer name within the operating system', + description: 'Please enter a description', + chooseRelateUser: 'Please enter a shared username', + transferUser: 'Please enter the username for transfer', + }, + tip: { + delete: 'The project cannot be deleted, please delete the resources in the project first', + deleteOnly: 'Keep at least 1 project, otherwise the resource cannot be created', + ownedOnly: 'Only the owner supports operations', + statusError: 'Operation failed, please contact the administrator', + transferUserTip0: 'Notice : ', + transferUserTip1: '1. Transfer user selection range: The selected users only include users with access to the user role of the console', + transferUserTip2: '2. Transfer method: Enter the correct username, and after successful verification, the user can see the shared project in project management ', + transferUserTip3: '3. The recipient can access and manage all resources within the project, including the operation of the project itself ', + emptyTransferUser: 'The selected transfer user cannot be empty', + emptyResoure: 'Select resources cannot be empty', + }, + status: { + stopped: 'Stopped', + running: 'Running', + creationFailed: 'Creation failed', + locked: 'Locked', + unlocked: 'Unlocked', + } + }, + instance: { + list: { + create: 'Create an instance', + instanceName: 'Instance Name/ID', + state: 'Status', + model: 'Instance type', + mirror: 'Image', + osSystem: 'Operating System', + outBandIp: 'Out-of-band IP', + intranetIpv4: 'Private IPv4(eth0)', + intranetIpv6: 'Private IPv6(eth0)', + intranetIpv4eth1: 'Private IPv4(eth1)', + intranetIpv6eth1: 'Private IPv6(eth1)', + config: 'Configuration', + createdTime: 'Created Time', + noData: 'No instances, you can ', + searchNoResult: 'Find {0} resource matching the search and filter criteria, please change the search keywords or ', + searchHasResult: 'Find {0} resource matching the search and filter criteria, please ', + backList: 'go back to the list', + newInstanceName: 'New instance name', + + }, + detail: { + instance: 'Instance', + instanceList: 'Instance List', + instanceDetail: 'Instance Detail', + instanceMessage: 'Instance Details', + hardwareInformation: 'Hardware Details', + netInformation: 'Network Details', + datasInformation: 'Data volume information', + instanceName: 'Instance Name', + instanceId: 'Instance ID', + sn: 'SN', + computerName: 'DataCenter Name', + deviceName: 'Type Name', + mirror: 'Image', + createdTime: 'Created Time', + description: 'Description', + cpu: 'CPU', + memory: 'Memory', + systemDiskRaid: 'System volume RAID', + systemDisk: 'System volume', + dataDisk: 'Data Volume', + networkCard: 'NIC', + gpu: 'GPU', + intranetIpv4: 'Private IPv4(eth0)', + intranetIpv6: 'Private IPv6(eth0)', + intranetIpv4eth1: 'Private IPv4(eth1)', + intranetIpv6eth1: 'Private IPv6(eth1)', + outBandIp: 'Out-of-band IP', + editDescription: 'Edit Description', + lockStatus: 'Locked Status', + hardwareMonitoring: 'Hardware monitoring', + hardwareState: 'Hardware Device Status', + alarmLogList: 'Alarm Log List', + normal: 'Normal', + abnormal: 'Abnormal', + hardDisk: 'Hard disk', + power: 'Power', + other: 'Other', + number: 'S/N', + faultType: 'Fault Type', + faultDesc: 'Fault Description', + faultAlarmTime: 'Fault alarm time', + updatedTime: 'Update time', + alarmNumbers: 'Number of alarms', + status: 'Status', + unhandled: "Unhandled", + recovered: "Recovered", + ignored: "Ignored", + performanceMonitoring: 'Performance Monitoring', + operationLog: 'Operation log', + logTip: '(The following list includes operation records from the past 90 days)', + logId: 'LogID', + operationName: 'Operation Name', + operator: 'Operator', + operationTime: 'Operation time', + operationFeedback: 'Operation feedback', + faultWord: 'Error code', + }, + create: { + engine: 'DataCenter', + model: 'Instance Type', + image: 'Image Type', + guideMode: 'Boot Mode', + systemDisk: 'System Volume', + systemRoll: 'System Volume', + dataRoll: 'Data Volume', + rollName: 'Volume name', + raidModel: 'RAID mode', + harddiskNumber: 'Number of hard drives', + harddiskVolume: 'Single hard drive capacity', + useVolume: 'Available hard drive capacity', + harddiskType: 'Hard drive type', + systemRollRaid: 'System volume RAID', + noSystemDisk: 'RAID is not configured', + systemDiskShort: 'Sys Vol', + dataDiskShort: 'Data Vol', + memoryShort: 'Mem', + systemDiskPartition: 'System Volume Partition', + systemRollPartition: 'System volume partition', + instanceName: 'Instance Name', + hostName: 'HostName', + userName: 'Username', + setPassword: ' Set Password', + password: 'Password', + confirmPassword: 'Password Confirmed', + customPassword: 'Customized Password', + keyPasswordLogin: 'Key pair login', + keyPassword: 'Key pair', + quantity: 'Quantity', + cancel: 'Cancel', + create: 'Launch at once', + select: 'Select', + noData: 'No Data', + noMatchKey: 'If no proper key is available. ', + createdKey: 'Create a new key pair ', + remain: 'Total remaining', + series: { + computeType: 'Compute Class', + storageType: 'Storage Class', + gpuType: 'GPU Class', + otherType: 'Other Class' + } + }, + tip: { + open: 'Only support in stopped status', + close: 'Only support in running status', + restart: 'Only support in running status', + delete: 'Only support in stopped status and Creation failed status', + locking: 'Unable to lock the instance', + unlocking: 'Unable to unlock the instance', + locked: 'The instance is locked', + chooseInstance: 'Please select a resource', + allSell: 'All instance types have been sold out and cannot be created', + }, + placeholder: { + instanceName: 'Please enter the instance name to search', + instanceId: 'Please enter the instance ID to search', + outBandIp: 'Please enter the OOB IP to search', + intranetIpv4: 'Please enter the Private IPv4(eth0) to search', + intranetIpv6: 'Please enter the Private IPv6(eth0) to search', + instanceNameOrId: 'Please enter the instance name or ID to search', + operationName: 'Please enter the operation name', + operator: 'Please enter the operator', + startTime: 'Start date', + endTime: 'End date' + + } + }, + login: { + header: { + title: 'BMP-Console', + title2: 'BMP-Console' + }, + formSubmit: { + title: 'Welcome Back', + login: 'Login', + placeholder: { + userName: 'Please enter in Username', + passWord: 'Please enter in Password' + } + } + }, + uiPagination: { + total: 'Total {0}', + page: 'Total {0} page', + piecesAndPage: '{0} / page' + }, + messageCentre: { + message: 'Message Center', + messageList: 'Message List', + list: { + messageContent: 'Message content', + receivingTime: 'Receiving time', + messageType: 'Message type', + messageSubtype: 'Message Subtype', + all: 'All', + unread: 'Unread', + read: 'Read', + confirm: 'Confirm', + reset: 'Reset', + toolTip: { + messageContent: 'Please enter the message content to search for', + inputSubtype: 'Please enter the message subtype', + unreadTip1: ' (0 messages in total, ', + unreadTip2: ' of which are unread)' + }, + + }, + operate: { + delete: 'Delete', + markedRead: 'Mark as read' + }, + detail: { + messageDetail: 'Message Details', + greetingMessage: 'Hello {0}!', + operateOverview: 'Here is an overview of the operation:', + operateDetail: 'The following are the details of the operation content:', + faultDetail: 'The following are the fault details:', + operateContent: 'Operation content', + operator: 'Operator', + operateTime: 'Operation time', + instanceName:'Instance Name', + instanceId: 'Instance ID', + number: 'SN', + faultType: 'Fault Type', + faultDes: 'Fault Description', + faultTime: 'Fault alarm time', + faultTimes: 'Number of alarms', + faultContent: 'Failure notification', + remindContent: 'Tip', + alarmRemindContent: 'Alarm Reminder', + lastStep: 'Previous', + nextStep: 'Next', + faultMessage: 'oob-monitor', + operateMessage: 'operation', + alarmMessage: 'inbond-alert', + } + }, + alarm: { + monitor: { + monitor: 'Monitoring', + viewMonitor: 'View monitoring', + montiorState: 'Monitor Agent status', + downloadMonitorAgent: 'Install monitoring agent', + monitorTip: 'Provide real-time fault alarm', + alarmMonitor: 'Monitoring Alarm', + }, + alarmManagement: 'Alarm Management', + alarmRules: 'Alarm rules', + alarmHistory: 'Alarm history', + alarmRule: { + addRule: 'Add alarm rule', + editRule: 'Edit alarm rule', + ruleName: 'Rule Name', + ruleId: 'Rule ID', + resourceType: 'Resource Type', + instanceNumber: 'Instance associated number', + triggeringCondition: 'Triggering conditions', + status: 'Status', + noData: 'There is no alarm rule yet. You can ', + alarmTime: 'Alarm time', + alarmResource: 'Alarm Resources', + alarmResourceId: 'Alarm Resources ID', + alarmValue: 'Alarm value', + alarmLevel: 'Alarm level', + continueTime: 'Duration', + alarmDetail: 'Alarm rule details', + dimension: 'Dimensions', + notificationPolicy: 'Notification strategy', + noticePeriod: 'Notification cycle', + validPeriod: 'Effective period', + noticeCondition: 'Notification conditions', + acceptChannel: 'Receiving channel', + noticeObject: 'Notification object', + instance: 'Instance', + disk: 'Disk device name/drive letter', + mountpoint: 'Disk mount point/drive letter', + nic: 'Network port', + cpuUtil: "CPU Usage", + memoryUsage: "Memory Usage", + memoryUsed: "Memory Used", + diskUsed: "Disk Used", + diskUsage: "Disk Usage", + diskReadTraffic: "Disk Read Traffic", + diskWriteTraffic: "Disk Write Traffic ", + diskReadIOPS: "Disk Read IOPS", + diskWriteIOPS: "Disk Write IOPS", + networkIngressTraffic: "Network Ingress Traffic", + networkEgressTraffic: "Network Egress Traffic", + networkIngressPackets: "Network Ingress Packets", + networkEgressPackets: "Network Egress Packets", + loadAverage1min: "Load Average 1min", + loadAverage5min: "Load Average 5min", + loadAverage15min: "Load Average 15min", + totalTCPConnections: "Total TCP Connections", + establishedTCPConnections: "Established TCP Connections", + totalProcessCount: "Total Process Count", + diskUsedMountPoint: "Disk Used MountPoint", + diskUsageMountPoint: "Disk Usage MountPoint", + oneM: '1 minute', + twoM: '2 minutes', + fiveM: '5 minutes', + fifteenM: '15 minutes', + halfH: '30 minutes', + oneH: '1 hour', + max: 'max', + min: 'min', + avg: 'avg', + sum: 'sum', + continuePeriod: 'Continued for {0} cycles', + normal: 'General', + serious: 'Serious', + urgent: 'Emergency', + minute: '{0} minute(s)', + hour: '{0} hour(s)', + alarm: 'Alarm', + beNormal: 'Restore to normal', + inEmail: 'Internal message', + email: 'Email', + currentContacts: 'Current account contact', + addTriggeringCondition: 'Add trigger conditions', + regular: 'Normal', + forbid: 'Disabled', + total: '{0} in total,', + allDevice: 'all device', + or: 'or ', + }, + placeHolder: { + ruleName: 'Please enter a rule name', + ruleId: 'Please enter a rule ID', + threshold: 'Please enter a threshold', + chooseInstance: 'Please select an instance', + + }, + tip: { + contact1: 'Note: To modify account personal information, please go to ', + myUser: 'Personal Center-My Account', + contact2: '', + noticePeriodTip: 'If the alarm does not return to normal after it occurs, how often the alarm notification will be sent again', + validPeriodTip: 'Emails or in-site messages are sent within the specified time range', + emptyRuleName: 'Rule name input cannot be empty', + chooseNoticeCondition: 'Please select notification conditions', + chooseAcceptChannel: 'Please select a receiving channel', + ruleThresholdVerification: 'The threshold must be numeric and larger than or equal to 0, and the precision contains up to two digits after the decimal point', + ruleThresholdPercentVerification: 'Percentage should be <=100', + triggerOptionRepeat: 'Duplicate triggering conditions', + + }, + operate: { + disable: { + dialogName: 'Disable alarm rule prompts', + dialogContent: 'Please confirm to disable the [{0}] alarm rule?', + name: 'Disable', + tip: '' + }, + enable: { + dialogName: 'Enable alarm rule prompts', + dialogContent: 'Please confirm to enable the [{0}] alarm rule?', + name: 'Enable', + tip: '' + }, + edit: { + name: 'Edit', + tip: '' + }, + history: { + name: 'Alarm history', + tip: '' + }, + delete: { + dialogName: 'Delete alarm rule prompt', + dialogContent: 'Please confirm to delete the [{0}] alarm rule?', + name: 'Delete', + tip: '' + } + + }, + message: { + instance: 'Examples of', + current: ' Current ', + rule: ', rule: ', + check: 'please check it in time.', + } + }, + monitorEcharts: { + tabs: { + h1: '1h', + h6: '6h', + h12: '12h', + d1: '1d', + d3: '3d', + d7: '7d', + d14: '14d' + }, + datePicker: { + startDate: 'Start Date', + endDate: 'End Date' + }, + radio: { + instance: 'Instance', + disk: 'Disk', + diskPartition: 'Disk Partition', + netWorkInterface: 'Network Interface' + }, + diskTip: 'Linux OS reports by DeviceName, and Windows OS reports by DriveLetter', + diskPartitionTip: 'Linux OS reports by MountPoint, and Windows OS reports by DriveLetter', + echartsCount: { + period: 'Period', + aggregationMethod: 'Aggregation Method', + cpuUnit: 'CPU Usage(%)', + cpu: 'CPU Usage', + memUnit: 'Memory Usage(%)', + mem: 'Memory Usage', + memUsageUnit: 'Memory Used(GB)', + memUsage: 'Memory Used', + diskUsageUnit: 'Disk Used(GB)', + diskUsage: 'Disk Used', + diskUsageRateUnit: 'Disk Usage(%)', + diskUsageRate: 'Disk Usage', + diskReadWriteTrafficUnit: 'Disk Read/Write Traffic (Bps)', + diskReadWriteTraffic: 'Disk Read/Write Traffic', + diskReadTraffic: 'Disk Read Traffic ', + diskWriteTraffic: 'Disk Write Traffic ', + diskReadWriteIOPSUnit: 'Disk Read/Write IOPS(次/秒)', + diskReadWriteIOPS: 'Disk Read/Write IOPS', + diskReadIOPS: 'Disk Read IOPS', + diskWriteIOPS: 'Disk Write IOPS', + netWorkBpsUnit: 'Network Ingress/Egress Traffic (bps)', + netWorkBps: 'Network Ingress/Egress Traffic ', + netWorkIn: 'Network Ingress Traffic', + netWorkOut: 'Network Egress Traffic', + netWorkPackagesNumUnit: 'Network Ingress/Egress Packets(个/秒)', + netWorkPackagesNumber: 'Network Ingress/Egress Packets', + netWorkInPackageNum: 'Network Ingress Packets', + netWorkOutPackageNum: 'Network Egress Packets', + averageLoad1MinUnit: 'Load Average 1min', + averageLoad1Min: 'Load Average 1min', + averageLoad5MinUnit: 'Load Average 5min', + averageLoad5Min: 'Load Average 5min', + averageLoad15MinUnit: 'Load Average 15min', + averageLoad15Min: 'Load Average 15min', + totalTCPConnectionsUnit: 'Total TCP Connections(个)', + totalTCPConnections: 'Total TCP Connections', + normalTCPConnectionsUnit: 'Established TCP Connections(个)', + normalTCPConnections: 'Established TCP Connections', + totalNumberOfProcessesUnit: 'Total Process Count(个)', + totalNumberOfProcesses: 'Total Process Count' + }, + goRuleMangement: 'Go to Alarm Management to', + goAlarmRule: 'Set Alarm Rules' + }, +}; diff --git a/bmp-console-web/src/lib/i18n/index.ts b/bmp-console-web/src/lib/i18n/index.ts new file mode 100644 index 0000000..a8d7ae8 --- /dev/null +++ b/bmp-console-web/src/lib/i18n/index.ts @@ -0,0 +1,63 @@ +import {createI18n, I18n} from 'vue-i18n'; +import zh from 'lib/i18n/zh-CN.ts'; +import en from 'lib/i18n/en-US.ts'; +import zhLocale from 'element-plus/lib/locale/lang/zh-cn'; +import enLocale from 'element-plus/lib/locale/lang/en'; +import VueCookies from 'vue-cookies'; + +/** + * 配置对象-国际化 +*/ +const messages = { + en_US: { + ...en, + ...enLocale + }, + zh_CN: { + ...zh, + ...zhLocale + } +}; + +/** + * 获取语言类型 + * @return {string} key 语言种类 + * @return {string} isCookie 语言种类 + * @return {string} zh_CN 语言种类 +*/ +const getLocale = () => { + const isCookie = (VueCookies as any).get('X-Jdcloud-Language'); + // 初次进入页面,cookie里面还未获取到值 + if (isCookie === null) { + // 浏览器语言 + const language: string = navigator.language.toLocaleLowerCase(); + // message语言 + const locale: string[] = Object.keys(messages); + for (const key of locale) { + // 如果浏览器语言类型包括message里面的类型 + if (language.indexOf(key) > -1) { + // 返回 + return key; + } + } + } + // 有cookie,优先用cookie里面的 + else if (isCookie) { + return isCookie; + } + // 默认语言 + return 'zh_CN'; +}; + +/** + * 首先从缓存里拿,没有的话就用浏览器语言 +*/ +const i18n: I18n = createI18n({ + legacy: false, // 使用 vue3 组合式API 时必须设置为 false + locale: getLocale(), // 本地语言 + globalInjection: true, // 全局注入 $t 函数 + fallbackLocale: 'zh_CN', // 设置备用语言 + messages // 配置对象 +}); + +export default i18n; diff --git a/bmp-console-web/src/lib/i18n/zh-CN.ts b/bmp-console-web/src/lib/i18n/zh-CN.ts new file mode 100644 index 0000000..bae479f --- /dev/null +++ b/bmp-console-web/src/lib/i18n/zh-CN.ts @@ -0,0 +1,723 @@ +export default { + personCentre: { + personCentre: '个人中心', + account: '我的账户', + securitySettings: '安全设置', + sshKey: '个人SSH密钥', + apiKey: '个人API密钥', + quit: '退出登录', + noData: '暂无密钥,您可以', + logout: '退出登录', + form: { + user: '用户名', + userId: '用户ID', + email: '邮箱', + phoneNumber: '手机号', + language: '语言', + timeZone: '时区', + defaultProject: '默认项目', + basicInformation: '基本信息', + preferences: '偏好设置', + save: '保存', + saving: '保存中', + selectLanguage: '请选择语言', + selectTimeZone: '请选择时区', + selectProject: '请选择项目', + currentPassword: '当前密码', + newPassword: '新密码', + confirmPassword: '确认密码', + change: '更改', + changing: '更改中', + createSshKey: '创建密钥', + createApiKey: '创建密钥', + create: '创建密钥', + keyName: '密钥名称', + createdTime: '创建时间', + updatedTime: '更新时间', + operation: '操作', + power: '权限', + keyPairName: '密钥对名称', + publicKey: '公钥', + editionName: '版本名称', + editionNumber: '版本号', + invalid: '未生效', + efficient: '有效', + expired: '已过期' + }, + operate: { + edit: '编辑', + copy: '复制', + transfer: '转移', + delete: '删除', + createSshKey: '创建SSH密钥', + editSshKey: '编辑SSH密钥', + deleteSshKey: '删除SSH密钥', + createApiKey: '创建API密钥', + deleteApiKey: '删除API密钥', + }, + content: { + stringVerification: '1-64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-”', + stringChineseVerification: '1-64字符,只支持中文、数字、大小写字母、英文下划线"_"及中划线 "-"', + projectNameExist: '项目名称重复', + keyNameExist: '密钥名称重复', + instanceNameExist: '实例名称重复', + passwordVerification: "8-30个字符\,且同时包含三项(大写字母,小写字母,数字或特殊符号()`~!{'@'}#{'{'}{'}'}{'$'}%&*_-+={'|'}[]:\";\'<>,.?/)", + instanceVerification: '2-128个字符,以大小写字母或中文开头,可包含数字、"."、"_"、":" 或 "-"', + hostnameVerification: '长度为2-64个字符,允许使用点号(.)分隔字符成多段,每段允许使用大小写字母、' + + '数字或连字符(-),但不能连续使用点号(.)或连字符(-)。不能以点号(.)或连字符(-)开头或结尾.', + publicKeyExample: '公钥格式:ssh-rsa AAAB3NzaCtyc2...', + copySuccess: '复制成功', + fixSuccess: '修改成功', + createSuccess: '创建成功', + operateSuccess: '操作成功', + operateFailed: '操作失败', + operateDoing: '操作中', + deleteApiKey: '确定是否删除密钥:【{0}】 ?', + logOut: '确定退出登录?', + operateNoModel: '您尚未开通此项模块', + }, + toolTip: { + formSubmit: '用户名不存在或密码错误', + emptyEmail: '邮箱地址输入不能为空', + errorEmail: '请输入正确的邮箱地址', + emptyPhone: '手机号输入不能为空', + errorPhone: '请输入正确的手机号', + errorPhoneHongkong: '请输入正确的中国香港手机号', + errorPhoneMacao: '请输入正确的中国澳门手机号', + errorPhoneTaiwan: '请输入正确的中国台湾手机号', + emptyCurrentPassword: '当前密码输入不能为空', + errorCurrentPassword: '请输入正确的当前密码', + emptyNewPassword: '新密码输入不能为空', + emptyconfirmPassword: '确认密码输入不能为空', + passNotSame: '确认密码与密码不相同', + emptyKeyPassword: '请选择密钥', + passNotMeetRequire: '密码不符合要求', + emptyProjectName: '项目名称输入不能为空', + emptyKeyName: '密钥名称输入不能为空', + emptyKeyPower: '密钥权限不能为空', + emptyPublicKey: '公钥输入不能为空', + emptyInstanceName: '实例名称输入不能为空', + emptyHostName: 'HostName输入不能为空', + emptyRelateUser: '选择共享用户不能为空', + emptyPower: '权限不能为空', + relateUserTip0: '注意 : ', + relateUserTip1: '1. 共享范围:关联的用户仅包含能够访问控制台的user角色的用户', + relateUserTip2: '2. 共享方式:输入正确的用户名,校验成功后该用户可在项目管理能够看到被共享的项目', + relateUserTip3: '3. 共享权限:被共享的用户能够访问和管理该项目内的所有资源', + relateUserDeleteTip: '移除后,该用户将不能查看和操作此项目的资源,请谨慎操作', + }, + phoneData: { + chineseMainland: '中国大陆 +86', + chineseHongKong: '中国香港 +852', + chineseMacao: '中国澳门 +853', + chineseTaiwan: '中国台湾 +886', + Argentina: '阿根廷 +54', + Australia: '澳大利亚 +61', + Brazil: '巴西 +55', + Germany: '德国 +49', + France: '法国 +33', + SouthKorea: '韩国 +82', + Canada: '加拿大 +1', + USA: '美国 +1', + Mexico: '墨西哥 +52', + SouthAfrica: '南非 +27', + Japan: '日本 +81', + SaudiArabia: '沙特阿拉伯 +966', + Turkey: '土耳其 +90 ', + Italy: '意大利 +39 ', + India: '印度 +91', + Indonesia: '印度尼西亚 +62', + UnitedKiongdom: '英国 +44', + }, + language: { + chinese: '中文' + }, + apiPower: { + writeAndRead: '读/写', + read: '只读' + }, + placeholder: { + projectName: '请输入项目名称', + keyPair: '请输入密钥对名称', + apiKey: '请输入密钥名称', + select: '请选择' + }, + tip: { + createSshKey: '支持创建2个SSH密钥', + createApiKey: '支持创建2个API密钥', + }, + detail: { + projectDetail: '项目详情', + projectName: '项目名称', + projectId: '项目ID', + projectStatus: '项目协作状态', + creater: '创建者', + owner: '拥有者', + createdTime: '创建时间', + updatedTime: '更新时间', + addUpdatedUser: '添加共享用户', + relatedUser: '关联共享用户', + chooseRelateUser: '选择共享用户', + deleteRelatedUser: '移除共享用户', + userName: '用户名', + userId: '用户ID', + power: '权限', + delete: '移除', + noData: '暂无关联共享用户,您可以', + } + }, + list: { + back: '返回', + settings: '设置', + update: '刷新', + download: '导出', + createdProject: '创建项目', + cancel: '取消', + confirm: '确定', + clear: '清空', + search: '搜索', + previousStep: '上一步', + nextStep: '下一步', + chooseUser: '选择用户', + chooseResource: '选择资源', + chooseProject: '选择项目', + project: { + projectMangement: '项目管理', + projectName: '项目名称', + projectId: '项目ID', + relatedState: '项目协作状态', + instanceNumber: '实例数', + noData: '暂无项目,您可以', + owner: '拥有者', + cooperate: '协作者', + choosetransferUser: '选择转移用户', + resourceChoose: '资源选择', + allTransfer: '全部转移', + partTransfer: '部分转移', + chooseResource: '选择资源', + }, + operate: { + open: '开机', + close: '关机', + restart: '重启', + delete: '删除', + lock: '锁定', + unlock: '解锁', + resetPassword: '重置密码', + resystem: '重装系统', + resystemConfi: '重装系统配置', + createProject: '创建项目', + editProject: '编辑项目', + deleteProject: '删除项目', + transferProject: '转移项目', + customList: '自定义列表', + more: '更多', + bacthClose: '批量关机', + bacthOpen: '批量开机', + bacthRestart: '批量重启', + bacthDelete: '批量删除', + batchResetPassword: '批量重置密码', + bacthRename: '批量编辑实例名称', + rename: '编辑实例名称', + resystemSure: '重装系统须知' + }, + content: { + open: '确定开启实例 【{0}】?', + close: '确定关闭实例【{0}】?', + restart: '确定重启实例【{0}】?', + delete: '确定删除实例【{0}】?', + lock: '确定锁定实例【{0}】?', + unlock: '确定解锁实例【{0}】?', + deleteProject: '请确定是否删除项目【{0}】?', + customListMessage: '请选择要显示在列表的信息:', + lockTip: '锁定实例后“删除”操作不可用,如需使用需提前解锁', + repasswordTip: '注意:重置密码后,只有在控制台/运营平台内对实例进行开机才能生效', + batchresetPasswordTip0: '注意:', + batchresetPasswordTip1: '1. 通过此方式重置密码的多个实例密码均相同', + batchresetPasswordTip2: '2. 重置密码后,需要在控制台/运营平台对实例进行开机才能生效', + deleteTip: '注意:删除操作会清空实例上的所有数据,请谨慎操作。', + createError: '库存不足', + relateUserDelete: '确认是否将【{0}】移除共享项目【{1}】', + batchContent: '您选择的', + bacthCloseContent: '台实例将执行关机操作,您是否确定操作?', + bacthOpenContent: '台实例将执行开机操作,您是否确定操作?', + bacthRestartContent: '台实例将执行重启操作,您是否确定操作?', + bacthResetPasswordContent: '台实例将执行重置密码操作,您是否确定操作?', + bacthRenameContent: '台实例将执行编辑实例名称操作,您是否确定操作?', + bacthDeleteContent: '台实例将执行删除操作,您是否确定操作?', + bacthRenameTip: '注意:通过此方式编辑的多台实例名称为连续命名', + resystemContent: '您选择的实例【{0}】将执行重装系统操作,您是否确定操作?', + resystemTips: + '1. 重装系统是针对系统盘做初始化,更换操作系统的操作,该操作不可恢复,请谨慎操作!
'+ + '2. 该操作会清空实例系统盘所有数据,请备份好数据再执行重装系统操作,以免数据丢失给您造成损失。
'+ + '3. 重装系统后,系统默认不会为实例配置IPv6地址,您需要手工进行配置。
', + notice: '注意:', + allInstance: '全部实例 (共{0}个)', + selectInstance: '已选实例 (共{0}个)', + transformAllTip: '项目内资源全部转移后,该项目内的实例报警规则会全部清空,不再接受报警通知。', + transformPartTip: '资源转移后,关联的报警规则会解除与该资源的关联关系,同时不再接收报警通知。', + }, + placeholder: { + instanceName: '请输入实例名称', + hostName: '可选填,操作系统内部的计算机名', + description: '请输入描述', + chooseRelateUser: '请输入共享的用户名', + transferUser: '请输入转移的用户名', + }, + tip: { + delete: '无法删除项目,请先删除该项目内的资源', + deleteOnly: '至少保留1个项目, 否则无法创建资源', + ownedOnly: '仅拥有者支持操作', + statusError: '操作失败,请联系管理员处理', + transferUserTip0: '注意 : ', + transferUserTip1: '1. 转移用户选择范围: 选择的用户仅包含能够访问控制台的user角色的用户 ', + transferUserTip2: '2. 转移方式:输入正确的用户名,校验成功后该用户可在项目管理能够看到被共享的项目', + transferUserTip3: '3. 接受者能够访问和管理该项目内的所有资源,包含项目本身的操作。', + emptyTransferUser: '选择转移用户不能为空', + emptyResoure: '选择资源不能为空', + }, + status: { + stopped: '已关机', + running: '运行', + creationFailed: '创建失败', + locked: '已锁定', + unlocked: '未锁定', + } + + }, + instance: { + list: { + create: '创建实例', + instanceName: '实例名称/ID', + state: '状态', + model: '机型', + mirror: '镜像', + osSystem: '操作系统', + outBandIp: '带外IP', + intranetIpv4: '内网IPv4(eth0)', + intranetIpv6: '内网IPv6(eth0)', + intranetIpv4eth1: '内网IPv4(eth1)', + intranetIpv6eth1: '内网IPv6(eth1)', + config: '配置', + createdTime: '创建时间', + noData: '暂无实例,您可以', + searchNoResult: '查询到符合搜索及筛选条件的资源共 {0} 条, 请更换搜索关键字或', + searchHasResult: '查询到符合搜索及筛选条件的资源共 {0} 条, ', + backList: '返回列表', + newInstanceName: '新实例名称', + }, + detail: { + instance: '实例', + instanceList: '实例列表', + instanceDetail: '实例详情', + instanceMessage: '实例信息', + hardwareInformation: '硬件信息', + datasInformation: '数据卷信息', + netInformation: '网络信息', + instanceName: '实例名称', + instanceId: '实例ID', + sn: 'SN', + computerName: '机房名称', + deviceName: '机型名称', + mirror: '镜像', + createdTime: '创建时间', + description: '描述', + cpu: 'CPU', + gpu: 'GPU', + memory: '内存', + systemDiskRaid: '系统盘RAID', + systemDisk: '系统盘', + dataDisk: '数据盘', + networkCard: '网卡', + intranetIpv4: '内网IPv4(eth0)', + intranetIpv6: '内网IPv6(eth0)', + intranetIpv4eth1: '内网IPv4(eth1)', + intranetIpv6eth1: '内网IPv6(eth1)', + outBandIp: '带外IP', + editDescription: '修改描述', + lockStatus: '锁定状态', + hardwareMonitoring: '硬件监控', + hardwareState: '硬件设备状态', + alarmLogList: '报警日志列表', + normal: '正常', + abnormal: '异常', + hardDisk: '硬盘', + power: '电源', + other: '其他', + number: '序号', + faultType: '故障类型', + faultDesc: '故障描述', + faultAlarmTime: '故障报警时间', + updatedTime: '更新时间', + alarmNumbers: '报警次数', + status: '状态', + unhandled: "未处理", + recovered: "已恢复", + ignored: "已忽略", + performanceMonitoring: '性能监控', + operationLog: '操作日志', + logTip: '(以下列表包括了近 90 天的操作记录)', + logId: 'LogID', + operationName: '操作名称', + operator: '操作人', + operationTime: '操作时间', + operationFeedback: '操作反馈', + faultWord: '错误码', + + }, + create: { + engine: '机房', + model: '机型类型', + image: '镜像类型', + guideMode: '引导模式', + systemDisk: '系统盘', + systemRoll: '系统卷', + dataRoll: '数据卷', + rollName: '卷名称', + raidModel: 'RAID模式', + harddiskNumber: '硬盘数量', + harddiskVolume: '单个硬盘容量', + useVolume: '可用硬盘容量', + harddiskType: '硬盘类型', + systemRollRaid: '系统卷RAID', + noSystemDisk: '未配置RAID', + systemDiskShort: '系统卷', + dataDiskShort: '数据卷', + memoryShort: '内存', + systemDiskPartition: '系统盘分区', + systemRollPartition: '系统卷分区', + instanceName: '实例名称', + hostName: 'HostName', + userName: '用户名', + setPassword: '设置密码', + password: '密码', + confirmPassword: '确认密码', + customPassword: '自定义密码', + keyPasswordLogin: '密钥登录', + keyPassword: '密钥', + quantity: '数量', + cancel: '取消', + create: '立即创建', + select: '请选择', + noData: '无数据', + noMatchKey: '如无合适密钥,可以', + createdKey: '创建密钥', + remain: '剩余全部', + series: { + computeType: '计算型', + storageType: '存储型', + gpuType: 'GPU', + otherType: '其它' + } + }, + tip: { + open: '仅关机状态支持', + close: '仅运行状态支持', + restart: '仅运行状态支持', + delete: '仅关机和创建失败状态支持', + locking: '无法锁定该实例', + unlocking: '无法解锁该实例', + locked: '实例已锁定', + chooseInstance: '请选择资源', + allSell: '所有机型皆已售罄,无法创建实例', + }, + placeholder: { + instanceName: '请输入实例名称搜索', + instanceId: '请输入实例ID搜索', + outBandIp: '请输入带外IP搜索', + intranetIpv4: '请输入内网IPv4(eth0)搜索', + intranetIpv6: '请输入内网IPv6(eth0)搜索', + instanceNameOrId: '请输入实例名称/ID搜索', + operationName: '请输入操作名称', + operator: '请输入操作人', + startTime: '开始日期', + endTime: '结束日期' + } + }, + login: { + header: { + title: '裸金属管理平台(标准版)', + title2: '裸金属管理平台(专业版)' + }, + formSubmit: { + title: '欢迎回来', + login: '登录', + placeholder: { + userName: '请输入用户名', + passWord: '请输入密码' + } + } + }, + uiPagination: { + total: '共 {0} 条', + page: '共 {0} 页', + piecesAndPage: '{0} 条/页' + }, + messageCentre: { + message: '消息中心', + messageList: '消息列表', + list: { + messageContent: '消息内容', + receivingTime: '接收时间', + messageType: '消息类型', + messageSubtype: '消息子类型', + all: '全部', + unread: '未读', + read: '已读', + confirm: '筛选', + reset: '重置', + toolTip: { + messageContent: '请输入消息内容搜索', + inputSubtype: '请输入消息子类型', + unreadTip1: '(共 {0} 条,其中 ', + unreadTip2:' 条未读)' + }, + + }, + operate: { + delete: '删除', + markedRead: '标为已读' + }, + detail: { + messageDetail: '消息详情', + greetingMessage: '用户{0}您好!', + operateOverview: '以下为操作概览:', + operateDetail: '以下为操作内容详情:', + faultDetail: '以下为故障详情:', + operateContent: '操作内容', + operator: '操作人', + operateTime: '操作时间', + instanceName:'实例名称', + instanceId: '实例ID', + number: '序号', + faultType: '故障类型', + faultDes: '故障描述', + faultTime: '故障报警时间', + faultTimes: '报警次数', + faultContent: '失败通知', + remindContent: '提醒', + alarmRemindContent: '报警提醒', + lastStep: '上一条', + nextStep: '下一条', + faultMessage: '故障消息', + operateMessage: '操作消息', + alarmMessage: '报警消息', + } + }, + alarm: { + monitor: { + monitor: '监控', + viewMonitor: '查看监控', + montiorState: '监控Agent状态', + downloadMonitorAgent: '安装监控Agent', + monitorTip: '提供实时故障告警', + alarmMonitor: '监控报警', + + }, + alarmManagement: '报警管理', + alarmRules: '报警规则', + alarmHistory: '报警历史', + alarmRule: { + addRule: '添加报警规则', + editRule: '编辑报警规则', + ruleName: '规则名称', + ruleId: '规则ID', + resourceType: '资源类型', + instanceNumber: '实例关联数量', + triggeringCondition: '触发条件', + status: '状态', + noData: '暂无报警规则,您可以', + alarmTime: '报警时间', + alarmResource: '报警资源', + alarmResourceId: '报警资源ID', + alarmValue: '报警值', + alarmLevel: '报警级别', + continueTime: '持续时间', + alarmDetail: '报警规则详情', + dimension: '维度', + notificationPolicy: '通知策略', + noticePeriod: '通知周期', + validPeriod: '有效时段', + noticeCondition: '通知条件', + acceptChannel: '接受渠道', + noticeObject: '通知对象', + instance: '实例', + disk: '磁盘设备名/盘符', + mountpoint: '磁盘挂载点/盘符', + nic: '网口', + cpuUtil: "CPU使用率", + memoryUsage: "内存使用率", + memoryUsed: "内存使用量", + diskUsed: "磁盘使用量", + diskUsage: "磁盘使用率", + diskReadTraffic: "磁盘读流量", + diskWriteTraffic: "磁盘写流量", + diskReadIOPS: "磁盘读IOPS", + diskWriteIOPS: "磁盘写IOPS", + networkIngressTraffic: "网口进流量", + networkEgressTraffic: "网口出流量", + networkIngressPackets: "网口进包数量", + networkEgressPackets: "网口出包数量", + loadAverage1min: "平均负载均衡1min", + loadAverage5min: "平均负载均衡5min", + loadAverage15min: "平均负载均衡15min", + totalTCPConnections: "TCP总连接数", + establishedTCPConnections: "TCP正常接数", + totalProcessCount: "总进程数", + diskUsedMountPoint: "硬盘使用量", + diskUsageMountPoint: "硬盘使用率", + oneM: '1分钟', + twoM: '2分钟', + fiveM: '5分钟', + fifteenM: '15分钟', + halfH: '30分钟', + oneH: '1小时', + max: '最大值', + min: '最小值', + avg: '平均值', + sum: '总和', + continuePeriod: '持续{0}个周期', + normal: '一般', + serious: '严重', + urgent: '紧急', + minute: '{0}分钟', + hour: '{0}小时', + alarm: '报警', + beNormal: '恢复正常', + inEmail: '站内信', + email: '邮件', + currentContacts: '当前账号联系人', + addTriggeringCondition: '添加触发条件', + regular: '正常', + forbid: '已禁用', + total: '共{0}个,', + allDevice: '全部device', + or: '或 ', + + }, + placeHolder: { + ruleName: '请输入规则名称', + ruleId: '请输入规则ID', + threshold: '请输入阈值', + chooseInstance: '请选择实例', + + }, + tip: { + contact1: '注:修改账号个人信息请在', + myUser: '个人中心-我的账户', + contact2: '里操作', + noticePeriodTip: '指报警发生后如果未恢复正常,间隔多久重复发送一次报警通知', + validPeriodTip: '邮件或站内信在指定时间范围内发送', + emptyRuleName: '规则名称输入不能为空', + chooseNoticeCondition: '请选择通知条件', + chooseAcceptChannel: '请选择接收渠道', + ruleThresholdVerification: '阈值只支持数字类型且阈值>=0,精度至多保留为小数点后2位', + ruleThresholdPercentVerification: '百分比应<=100', + triggerOptionRepeat: '触发条件重复', + + + }, + operate: { + disable: { + dialogName: '禁用报警规则提示', + dialogContent: '请确认禁用【{0}】报警规则?', + name: '禁用', + tip: '' + }, + enable: { + dialogName: '启用报警规则提示', + dialogContent: '请确认启用【{0}】报警规则?', + name: '启用', + tip: '' + }, + edit: { + name: '编辑', + tip: '' + }, + history: { + name: '报警历史', + tip: '' + }, + delete: { + dialogName: '删除报警规则提示', + dialogContent: '请确认删除【{0}】报警规则?', + name: '删除', + tip: '' + } + + }, + message: { + instance: '的实例', + current: ' 当前', + rule: ',所属规则:{0},', + check: '请你及时查看。', + } + }, + monitorEcharts: { + tabs: { + h1: '1小时', + h6: '6小时', + h12: '12小时', + d1: '1天', + d3: '3天', + d7: '7天', + d14: '14天' + }, + datePicker: { + startDate: '开始日期', + endDate: '结束日期' + }, + radio: { + instance: '实例', + disk: '磁盘', + diskPartition: '磁盘用量', + netWorkInterface: '网口' + }, + diskTip: 'Linux系统按设备名上报, Windows系统按盘符上报', + diskPartitionTip: 'Linux系统按分区挂载点上报,Windows系统按盘符上报', + echartsCount: { + period: '周期', + aggregationMethod: '聚合方式', + cpuUnit: 'CPU使用率(%)', + cpu: 'CPU使用率', + memUnit: '内存使用率(%)', + mem: '内存使用率', + memUsageUnit: '内存使用量(GB)', + memUsage: '内存使用量', + diskUsageUnit: '磁盘使用量(GB)', + diskUsage: '磁盘使用量', + diskUsageRateUnit: '磁盘使用率(%)', + diskUsageRate: '磁盘使用率', + diskReadWriteTrafficUnit: '磁盘读/写流量(Bps)', + diskReadWriteTraffic: '磁盘读/写流量', + diskReadTraffic: '磁盘读流量', + diskWriteTraffic: '磁盘写流量', + diskReadWriteIOPSUnit: '磁盘读/写IOPS(次/秒)', + diskReadWriteIOPS: '磁盘读/写IOPS', + diskReadIOPS: '磁盘读IOPS', + diskWriteIOPS: '磁盘写IOPS', + netWorkBpsUnit: '网口进/出流量(bps)', + netWorkBps: '网口进/出流量', + netWorkIn: '网口进流量', + netWorkOut: '网口出流量', + netWorkPackagesNumUnit: '网络进/出包数量(个/秒)', + netWorkPackagesNumber: '网络进/出包数量', + netWorkInPackageNum: '网络进包量', + netWorkOutPackageNum: '网络出包量', + averageLoad1MinUnit: '平均负载1min', + averageLoad1Min: '平均负载1min', + averageLoad5MinUnit: '平均负载5min', + averageLoad5Min: '平均负载5min', + averageLoad15MinUnit: '平均负载15min', + averageLoad15Min: '平均负载15min', + totalTCPConnectionsUnit: 'TCP总连接数(个)', + totalTCPConnections: 'TCP总连接数', + normalTCPConnectionsUnit: 'TCP正常连接数(个)', + normalTCPConnections: 'TCP正常连接数', + totalNumberOfProcessesUnit: '总进程数(个)', + totalNumberOfProcesses: '总进程数' + }, + goRuleMangement: '可前往报警管理', + goAlarmRule: '设置报警规则' + }, +}; diff --git a/bmp-console-web/src/lib/mitt/mitt.ts b/bmp-console-web/src/lib/mitt/mitt.ts new file mode 100644 index 0000000..e654819 --- /dev/null +++ b/bmp-console-web/src/lib/mitt/mitt.ts @@ -0,0 +1,13 @@ +import mitt, {Emitter, EventType} from 'mitt'; // 事件总线-兄弟间传值 + +const mit: Emitter> = mitt(); + +// ComponentCustomProperties用于扩充组件实例类型以支持自定义全局属性,否则会报警告。 +declare module 'vue' { + export interface ComponentCustomProperties { + $Bus: typeof mit; + } +} +const mittCommunication: (app: any) => Emitter> = (app: any) => app.config.globalProperties.$Bus = mit; + +export default mittCommunication; diff --git a/bmp-console-web/src/lib/pinia/pinia.ts b/bmp-console-web/src/lib/pinia/pinia.ts new file mode 100644 index 0000000..7962e51 --- /dev/null +++ b/bmp-console-web/src/lib/pinia/pinia.ts @@ -0,0 +1,8 @@ +import {createPinia, Pinia} from 'pinia'; +import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' + +const pinia: Pinia = createPinia(); +// 数据持久化 +pinia.use(piniaPluginPersistedstate) +export default pinia; + diff --git a/bmp-console-web/src/main.ts b/bmp-console-web/src/main.ts new file mode 100644 index 0000000..287886f --- /dev/null +++ b/bmp-console-web/src/main.ts @@ -0,0 +1,20 @@ +import {createApp} from 'vue'; // 返回一个提供应用上下文的应用实例。应用实例挂载的整个组件树共享同一个上下文 +import App from '@/App.vue'; // 根组件 +import router from 'router/index.ts'; // 路由 +import i18n from 'lib/i18n/index.ts'; // 国际化 +import ElementPlus from 'lib/element/index.ts'; // elementui +import pinia from 'lib/pinia/pinia.ts'; // pinia-store状态库 +import filter from 'lib/filters/filter.ts'; // 过滤方法 +import mittCommunication from 'lib/mitt/mitt.ts'; // mitt-跨组件通信 +import * as ElementPlusIconsVue from '@element-plus/icons-vue'; // Element-plus-icon使用 +import VueCookies from 'vue-cookies'; + +const app = createApp(App); +// 全局挂载 +app.config.globalProperties.$cookies = VueCookies; +filter(app); +mittCommunication(app); +app.use(router).use(pinia).use(ElementPlus).use(i18n).mount('#app'); +for (const [key, component] of Object.entries(ElementPlusIconsVue)) { + app.component(key, component) +}; \ No newline at end of file diff --git a/bmp-console-web/src/request/index.ts b/bmp-console-web/src/request/index.ts new file mode 100644 index 0000000..ddb5afb --- /dev/null +++ b/bmp-console-web/src/request/index.ts @@ -0,0 +1,139 @@ +import axios, { + AxiosInstance, + AxiosRequestConfig, + AxiosResponse, + AxiosRequestHeaders, + AxiosError, + CancelTokenStatic, + AxiosResponseHeaders // axios相应头信息 +} from 'axios'; +import {ElMessage} from 'element-plus'; +import VueCookies from 'vue-cookies'; +import router from '@/router/index.ts'; // 路由 +interface RepeatRequestArrType { + methodUrl: string; + params: any; + f: Function; +}; + +/** + * cookie ts规范校验 +*/ +const cookie: { + [x: string]: unknown; + get?: Function; + set?: Function; +} = VueCookies; + +/** + * 国际化 + */ + const vueCookiesLanguage: string = cookie?.get && cookie.get('X-Jdcloud-Language'); + +const server: AxiosInstance = axios.create({ + baseURL: '/console-web', + timeout: 10 * 1000, + headers: { + 'Content-Type': 'application/json; charset=utf-8', + 'X-Jdcloud-Language': vueCookiesLanguage || 'zh_CN' + } +}); + +// 获取取消请求的cancel方法 +const Cancel: CancelTokenStatic = axios.CancelToken; +// 接收重复请求的数组 +let repeatRequestArr: RepeatRequestArrType[] = []; + +/** + * 删除重复请求 + * @param {Object} config 请求头信息 +*/ +function removeRequest(config: any): void { + // 数组遍历 item 当前请求的接口地址+请求类型 index数组的下标 arr要处理的重复请求接口数组 + repeatRequestArr.map((item, index, arr) => { + // methodUrl 是当前请求的地址+方式,如果参数也相同 + if (item.methodUrl === config.url + '&' + config.method) { + if (judgeParamsEquality(config?.data || config?.params, item.params)) { + // 走到这里面说明多次请求了 + // f()是内置的取消请求的方法,此处执行 + item.f(); + // 删除当前请求的这一项 + arr.splice(index, 1); + } + } + return config; + }) +}; + +/** + * 判断请求参数是否相等 +*/ +function judgeParamsEquality(param1: any, param2: any) { + for (const key in param1) { + if (param1[key] !== param2[key]) { + return false; + } + } + return true; +}; + +/** + * 请求拦截器 +*/ +server?.interceptors?.request?.use( + (config: any): AxiosRequestHeaders | object => { + if(!config?.isrepeat) { + // 删除重复请求(isrepreat:false为不可重复,true为可以重复) + removeRequest(config) + } + // 这个c就是取消请求的方法 + config.cancelToken = new Cancel((c: Function) => { + // 添加到数组里面,methodUrl-url请求地址+method请求方式 + repeatRequestArr.push({methodUrl: config.url + '&' + config.method, params: config?.data || config?.params, f: c}) + }); + return config; + }, + (error: AxiosError): Promise | Function => { + return Promise.reject(error); + } +); + +/** + * 响应拦截器 +*/ +server?.interceptors?.response?.use( + (response: AxiosResponse): Promise | void => { + // 每成功一次,数组边为空,否则其他接口重复请求会数据一直叠加 + repeatRequestArr = []; + const {data, headers} : {data: any, headers: AxiosResponseHeaders} = response; + // 登录用户名称 + const userId: string = headers['x-jdcloud-userid']; + // 接口成功并且业务不需要自己处理返回 + return Promise.resolve({data, userId}); + + }, + (err: AxiosError | any): Promise | void => { + const {response} = err; + const errInfo = JSON.parse(JSON.stringify(err)); + const {config, message} : {config: AxiosRequestConfig | any, message: string} = errInfo; + const errorMsg: string = response?.data?.error?.message; + // 402登录过期-未登录 + if (response?.status === 402) { + // 跳转地址-用户最后一次访问的地址 + const pathUrl: string = window.btoa(router.currentRoute.value.fullPath); + // 设置地址-存储到coolie + cookie?.set && cookie.set('path_url', pathUrl); + window.open('/Login/login', '_self'); + } + // isBusinessProcessing 为 true,业务catch不用再做error提示 + else if (response?.config?.isBusinessProcessing || config?.isBusinessProcessing) { + ElMessage.error(errorMsg || message || '请求失败'); + } + else { + // isBusinessProcessing 为 false,需要业务自己处理catch里内容 + return Promise.reject({message: errorMsg || message, status: response?.status}); + } + } +); + +export default server; diff --git a/bmp-console-web/src/router/index.ts b/bmp-console-web/src/router/index.ts new file mode 100644 index 0000000..025e58b --- /dev/null +++ b/bmp-console-web/src/router/index.ts @@ -0,0 +1,12 @@ +import {createRouter, createWebHistory, Router, RouterHistory} from 'vue-router'; +import routes from 'router/routes.ts'; //导入router目录下的routes.ts + +// createWebHistory -- history模式 +// createWebHashHistory -- hash模式 +const webHistory: RouterHistory = createWebHistory(); + +const router: Router = createRouter({ + history: webHistory, + routes +}); +export default router; diff --git a/bmp-console-web/src/router/routes.ts b/bmp-console-web/src/router/routes.ts new file mode 100644 index 0000000..e4439bc --- /dev/null +++ b/bmp-console-web/src/router/routes.ts @@ -0,0 +1,154 @@ +import {RouteRecordRaw} from 'vue-router'; + +const LoginPage: () => void = () => import (/* webpackChunkName: "Login" */ 'views/Login/login.vue'); +const PersonalCentrePage: () => void = () => import (/* webpackChunkName: "PersonalCentre" */ 'views/PersonalCentre/personalCentre.vue'); +const ProjectManagement: () => void = () => import (/* webpackChunkName: "ProjectManagement" */ 'views/ProjectManagement/projectManagement.vue'); +const ProjectManagementDetail: () => void = () => import (/* webpackChunkName: "ProjectManagementDetail" */ 'views/ProjectManagementDetail/projectManagementDetail.vue'); +const InstanceList: () => void = () => import (/* webpackChunkName: "InstanceList" */ 'views/InstanceList/instanceList.vue'); +const InstanceDetail: () => void = () => import (/* webpackChunkName: "InstanceDetail" */ 'views/InstanceDetail/instanceDetail.vue'); +const InstanceCreate: () => void = () => import (/* webpackChunkName: "InstanceCreate" */ 'views/InstanceCreate/instanceCreate.vue'); +const MessageList: () => void = () => import (/* webpackChunkName: "MessageList" */ 'views/MessageList/messageList.vue'); +const MessageDetail: () => void = () => import (/* webpackChunkName: "MessageDetail" */ 'views/MessageDetail/messageDetail.vue'); +const AlarmHistory: () => void = () => import (/* webpackChunkName: "AlarmHistory" */ 'views/AlarmHistory/alarmHistory.vue'); +const AlarmRuleList: () => void = () => import (/* webpackChunkName: "AlarmRuleList" */ 'views/AlarmRuleList/alarmRuleList.vue'); +const AlarmRuleDetail: () => void = () => import (/* webpackChunkName: "AlarmRuleDetail" */ 'views/AlarmRuleDetail/alarmRuleDetail.vue'); +const AlarmRuleCreate: () => void = () => import (/* webpackChunkName: "AlarmRuleCreate" */ 'views/AlarmRuleCreate/alarmRuleCreate.vue'); + + +const routes: Array = [ + { + path: '/:pathMatch(.*)', + redirect: '/management' + }, + { + name: 'Login', + path: '/Login/login', + meta: { + showvalues: true, + }, + component: LoginPage + }, + { + name: 'PersonalCentrePage', + path: '/user', + meta: { + name: 'user', + noShowBack: true, + routeDirect: '1' + }, + component: PersonalCentrePage + }, + { + name: 'ProjectManagement', + path: '/management', + meta: { + name: 'management', + noShowBack: true, + routeDirect: '1' + }, + component: ProjectManagement + }, + { + name: 'ProjectManagementDetail', + path: '/management/detail', + meta: { + name: 'management', + noShowBack: false, + routeDirect: '1' + }, + component: ProjectManagementDetail + }, + { + name: 'InstanceList', + path: '/instance/list', + meta: { + name: 'instance', + noShowBack: false, + routeDirect: '1' + }, + component: InstanceList + }, + { + name: 'InstanceDetail', + path: '/instance/detail', + meta: { + name: 'instance', + noShowBack: false, + routeDirect: '1' + }, + component: InstanceDetail + }, + { + name: 'InstanceCreate', + path: '/instance/create', + meta: { + name: 'instance', + noShowBack: false, + routeDirect: '1' + }, + component: InstanceCreate + }, + { + name: 'MessageList', + path: '/message/list', + meta: { + name: 'message', + noShowBack: true, + routeDirect: '1' + }, + component: MessageList + }, + { + name: 'MessageDetail', + path: '/message/detail', + meta: { + name: 'message', + noShowBack: false, + routeDirect: '1' + }, + component: MessageDetail + }, + { + name: 'AlarmRule', + path: '/instance/rules/list', + meta: { + name: 'alarm', + noShowBack: false, + routeDirect: '2-1' + }, + component: AlarmRuleList + }, + { + name: 'AlarmRuleDetail', + path: '/instance/rules/detail', + meta: { + name: 'alarm', + noShowBack: false, + routeDirect: '2-1' + }, + component: AlarmRuleDetail + }, + { + name: 'AlarmRuleCreate', + path: '/instance/rules/create', + meta: { + name: 'alarm', + noShowBack: false, + routeDirect: '2-1' + }, + component: AlarmRuleCreate + }, + { + name: 'AlarmHistory', + path: '/instance/history/list', + meta: { + name: 'alarm', + noShowBack: false, + routeDirect: '2-2' + }, + component: AlarmHistory + }, + +]; + +export default routes; \ No newline at end of file diff --git a/bmp-console-web/src/shims-vue.d.ts b/bmp-console-web/src/shims-vue.d.ts new file mode 100644 index 0000000..7237fed --- /dev/null +++ b/bmp-console-web/src/shims-vue.d.ts @@ -0,0 +1,18 @@ +/* eslint-disable */ + +// shims-vue.d.ts是为了 typescript 做的适配定义文件 +// 因为.vue 文件不是一个常规的文件类型,ts 是不能理解 vue 文件的作用 +// 加这一段是是告诉 ts,vue 文件是这种类型的,如果不写,import引入.vue文件会报错,其他同理 +declare module '*.vue' { // declare声明宣告 + import { ComponentOptions } from 'vue'; + const componentOptions: ComponentOptions; + export default componentOptions; +} + + +declare module '*.js'; +declare module '*.ts'; +// 解决ts文件引入图片报错 +declare module '*.png'; +declare module '*.jpg'; +declare module '*.jpeg'; diff --git a/bmp-console-web/src/store/index.ts b/bmp-console-web/src/store/index.ts new file mode 100644 index 0000000..2dfee71 --- /dev/null +++ b/bmp-console-web/src/store/index.ts @@ -0,0 +1,219 @@ +import {defineStore} from 'pinia'; // 定义容器名 +import STORE_NAMES from 'store/storeName.ts'; + +import {customListAPI, alarmCustomListAPI} from 'api/request.ts'; +import { + porjectCustomInfo, // 项目列表自定义初始数据 + instanceCustomInfo, // 实例自定义初始信息 + alarmLogCustomInfo, // 报警日志列表初始信息 +} from 'utils/constants.ts'; + + + +/** + * 自定义列表-数据信息-类 +*/ +type CustomDataInfoType = { + pageKey: string; + data: Record +}; + +interface IndexStateType { + customDataInfo: CustomDataInfoType[]; +}; +/** + * 通用状态类 +*/ +type CurrencyStatusType = { + required: boolean; + selected: boolean; +}; + +type OsStoreType = { + filterParams: string; + showInfo: string; + text: string; + value: number; +}; + +type NameType = { + name: string; + label: string; +}; + +type CheckListArrType = NameType[] & Omit[] & {disabled: boolean}[]; + +// defineStore定义容器 +// 参数1:是对仓库的命名,名称必须具备唯一性; +// 参数2:配置的选项对象,即state、getters、actions +// 其中state的写法必须是函数,为了避免在服务端交叉请求导致的状态数据污染,而且必须是箭头函数,为了更好的TS类型推导 +const publicIndexStore = defineStore(STORE_NAMES.PUBLICK_INDEX, { + state: (): IndexStateType => { + return { + customDataInfo: [ + { + pageKey: 'projectList', + data: porjectCustomInfo + }, + { + pageKey: 'instanceList', + data: instanceCustomInfo + }, + { + pageKey: 'deviceAlertLogList', + data: alarmLogCustomInfo, + + } + ] + } + }, + actions: { + /** + * 自定义列表 + * @param {string} pageKey 不同列表不同key + * @param {Object} reactiveArr.hasCustomInfo 对应列表信息,用来接收接口返回的状态 + * @param {Array} checkListArr 根据接口返回的信息做数据处理 + */ + customList( + pageKey: string, + reactiveArr: { + hasCustomInfo: Record, + checkListArr: CheckListArrType + } + ) { + customListAPI( + { + pageKey + } + ).then(({data} : {data: {result: {customInfo: Record}}}) => { + if (data?.result && Object.keys(data?.result?.customInfo)?.length) { + reactiveArr.hasCustomInfo = data.result.customInfo; + return; + } + return Promise.reject(); + }) + .catch(() => { + for (const key of this.customDataInfo) { + if (key.pageKey === pageKey) { + reactiveArr.hasCustomInfo = key.data; + } + } + }) + .finally(() => { + // 列表展示数据 + const checkListArr: CheckListArrType = reactiveArr.checkListArr; + // 遍历列表展示数据 + for (const key of checkListArr) { + // 遍历自定义信息数据 + for (const index in reactiveArr.hasCustomInfo) { + // 点击的当前项等于对应数据的那一项 + if (index === key.label) { + // 状态赋值 + key.disabled = reactiveArr.hasCustomInfo[index].required; + key.selected = reactiveArr.hasCustomInfo[index].selected; + } + } + } + }); + }, + alarmLogCustomList( + page_key: string, + reactiveArr: { + hasCustomInfo: Record, + checkListArr: CheckListArrType + }, + + ) { + + alarmCustomListAPI( + { + page_key + } + ).then(({data} : {data: {result: {custom_info: Record}}}) => { + if (data?.result && Object.keys(data?.result?.custom_info)?.length) { + reactiveArr.hasCustomInfo = data.result.custom_info; + return; + } + return Promise.reject(); + }) + .catch(() => { + for (const key of this.customDataInfo) { + if (key.pageKey === page_key) { + reactiveArr.hasCustomInfo = key.data; + } + } + }) + .finally(() => { + // 列表展示数据 + const checkListArr: CheckListArrType = reactiveArr.checkListArr; + // 遍历列表展示数据 + for (const key of checkListArr) { + // 遍历自定义信息数据 + for (const index in reactiveArr.hasCustomInfo) { + // 点击的当前项等于对应数据的那一项 + if (index === key.label) { + // 状态赋值 + key.disabled = reactiveArr.hasCustomInfo[index].required; + key.selected = reactiveArr.hasCustomInfo[index].selected; + } + } + } + }); + }, + /** + * 过滤参数-filter-筛选 + * @param {Object} filter 筛选的参数 + * @param {Object} ossStore 筛选的值 + * @param {Object} reactiveArr.filterParams 需要筛选的参数 + * @param {Object} filterParams 当前筛选的参数 + * @return {Function} reoslve() 成功的返回 + */ + filterParams( + filter: {[x: string]: number[]}, + ossStore: Record, + reactiveArr: {filterParams: {[x: string]: string}}, + filterParams: {[x: string]: string}, + currentStore: any, + ) { + if (!Object.keys(filter).length) { + return Promise.reject(); + } + else { + const tag: string[] = []; + for (const key in filter) { + if (key === filterParams[key]) { + for (const item of filter[key]) { + if(ossStore[filterParams[key]]) { + tag.push(ossStore[filterParams[key]][item - 1].filterParams); + } else { + tag.push(currentStore[item - 1].filterParams); + } + + } + // filter[key]?.forEach((item: number) => { + // tag.push(ossStore[filterParams[key]][item - 1].filterParams); + // }); + // 找到匹配的对应参数,如果多选,数组转字符串,用逗号分隔 + reactiveArr.filterParams[filterParams[key]] = tag.join(','); + } + } + this.deleteEmtpyData(reactiveArr.filterParams); + return Promise.resolve(); + } + }, + + /** + * 删除空数据 + * @param {Object} params 当前操作的数据 + */ + deleteEmtpyData(params: {[x: string]: string}): void { + Object.keys(params).forEach((item: string) => { + if (!params[item]) { + delete params[item]; + } + }); + } + } +}); + +export default publicIndexStore; \ No newline at end of file diff --git a/bmp-console-web/src/store/loginInfo.ts b/bmp-console-web/src/store/loginInfo.ts new file mode 100644 index 0000000..bb7f19f --- /dev/null +++ b/bmp-console-web/src/store/loginInfo.ts @@ -0,0 +1,29 @@ +import {defineStore} from 'pinia'; +import STORE_NAMES from 'store/storeName.ts'; + +interface StateType { + loginUserName: string; +} +interface UserType { + userId: string; +} + +// defineStore定义容器 +// 参数1:是对仓库的命名,名称必须具备唯一性; +// 参数2:配置的选项对象,即state、getters、actions +// 其中state的写法必须是函数,为了避免在服务端交叉请求导致的状态数据污染,而且必须是箭头函数,为了更好的TS类型推导 +export const loginInfoStore = defineStore(STORE_NAMES.LOGIN_INFO, { + state: (): StateType => { + return { + loginUserName: '' + } + } +}); + +export const projectListStore = defineStore(STORE_NAMES.PROJECT_LIST, { + state: (): UserType => { + return { + userId: '' + } + } +}); diff --git a/bmp-console-web/src/store/modules/headerDetail.ts b/bmp-console-web/src/store/modules/headerDetail.ts new file mode 100644 index 0000000..ef7ff18 --- /dev/null +++ b/bmp-console-web/src/store/modules/headerDetail.ts @@ -0,0 +1,71 @@ +import {defineStore} from 'pinia'; +import STORE_NAMES from 'store/storeName.ts'; +import {projectListAPI, userAPI} from 'api/request.ts'; // 项目,用户接口 + +interface StateType { + projectList: any; + projectListName: any; + userForm: any; + monitor: boolean; + inMonitor: boolean; + moveLive: string; +} + +// defineStore定义容器 +// 参数1:是对仓库的命名,名称必须具备唯一性; +// 参数2:配置的选项对象,即state、getters、actions +// 其中state的写法必须是函数,为了避免在服务端交叉请求导致的状态数据污染,而且必须是箭头函数,为了更好的TS类型推导 + const allProjectStore = defineStore(STORE_NAMES.ALLPROJECT, { + state: (): StateType => { + return { + projectList: [], + projectListName: [], + userForm: {}, + monitor: false, + inMonitor: false, + moveLive: 'test数据' + } + }, + getters: { + + }, + actions: { + test(): void { + this.moveLive = '1'; + }, + requestObject(): void { + return projectListAPI({ + isAll:'1' + }).then(({data} : {data: any}) => { + if (data?.result?.projects?.length) { + this.projectList = data.result.projects; + this.projectListName = data.result.projects.map((item: any) => item.projectName); + return + } + this.projectList = []; + this.projectListName = []; + }).catch(() => { + this.projectList = []; + this.projectListName = []; + }); + }, + requestUser(): void { + userAPI({ + }).then(({data} : {data: any}) => { + if(data?.result){ + this.userForm = data.result; + return + } + this.userForm = {} + }).catch(()=>{ + this.userForm = {} + }) + .finally(() => { + }); + } + }, + // 数据持久化 + persist: true, +}); + +export default allProjectStore; \ No newline at end of file diff --git a/bmp-console-web/src/store/modules/modelDetail.ts b/bmp-console-web/src/store/modules/modelDetail.ts new file mode 100644 index 0000000..267fb66 --- /dev/null +++ b/bmp-console-web/src/store/modules/modelDetail.ts @@ -0,0 +1,25 @@ +import {defineStore} from 'pinia'; // 定义容器名 +import { + manageMentStatus // 管理状态 +} from 'utils/constants.ts'; +import STORE_NAMES from 'store/storeName.ts'; // 容器名 + +interface StateType { + status: any; + deviceSeries: any; +}; + +// defineStore定义容器 +// 参数1:是对仓库的命名,名称必须具备唯一性; +// 参数2:配置的选项对象,即state、getters、actions +// 其中state的写法必须是函数,为了避免在服务端交叉请求导致的状态数据污染,而且必须是箭头函数,为了更好的TS类型推导 +const modelDetailStore = defineStore(STORE_NAMES.MODEL_DETAIL, { + state: (): StateType => { + return { + status: manageMentStatus, + deviceSeries: [] + } + }, +}); + +export default modelDetailStore; diff --git a/bmp-console-web/src/store/modules/projectDetail.ts b/bmp-console-web/src/store/modules/projectDetail.ts new file mode 100644 index 0000000..12a3164 --- /dev/null +++ b/bmp-console-web/src/store/modules/projectDetail.ts @@ -0,0 +1,25 @@ +import {defineStore} from 'pinia'; // 定义容器名 +import { + projectRelatedStatus // 管理状态 +} from 'utils/constants.ts'; +import STORE_NAMES from 'store/storeName.ts'; // 容器名 + +interface StateType { + status: any; +}; + + + +// defineStore定义容器 +// 参数1:是对仓库的命名,名称必须具备唯一性; +// 参数2:配置的选项对象,即state、getters、actions +// 其中state的写法必须是函数,为了避免在服务端交叉请求导致的状态数据污染,而且必须是箭头函数,为了更好的TS类型推导 +const projectDetailStore = defineStore(STORE_NAMES.PROJECT_DETAIL, { + state: (): StateType => { + return { + status: projectRelatedStatus, + } + }, +}); + +export default projectDetailStore; diff --git a/bmp-console-web/src/store/modules/projectId.ts b/bmp-console-web/src/store/modules/projectId.ts new file mode 100644 index 0000000..6365f9d --- /dev/null +++ b/bmp-console-web/src/store/modules/projectId.ts @@ -0,0 +1,38 @@ + +import { defineStore } from 'pinia'; +import STORE_NAMES from 'store/storeName.ts'; // 容器名 + +const useProjectStore = defineStore(STORE_NAMES.PROJECT_ID, { + state: () => ({ + projectId: '', + projectName: '' + }), + actions: { + setProject(id: string, name: string) { + this.projectId = id; + this.projectName = name; + // 同时存储到localStorage以保持页面刷新后数据依然存在 + localStorage.setItem('project', JSON.stringify({ projectId: id, projectName: name })); + }, + clearProject() { + this.projectId = ''; + this.projectName = ''; + // 清除localStorage中的数据 + localStorage.removeItem('project'); + }, + initProject() { + // 从localStorage中读取项目数据 + const project = localStorage.getItem('project'); + if (project) { + const { projectId, projectName } = JSON.parse(project); + this.projectId = projectId; + this.projectName = projectName; + } + } + + }, + // 数据持久化 + persist: true, +}); + +export default useProjectStore; \ No newline at end of file diff --git a/bmp-console-web/src/store/storeName.ts b/bmp-console-web/src/store/storeName.ts new file mode 100644 index 0000000..ee03795 --- /dev/null +++ b/bmp-console-web/src/store/storeName.ts @@ -0,0 +1,21 @@ +interface StoreNamesTypes { + LOGIN_INFO: string; + PROJECT_LIST: string; + ALLPROJECT: string; + PUBLICK_INDEX: string; + MODEL_DETAIL: string; + PROJECT_DETAIL: string; + PROJECT_ID: string +} + +const STORE_NAMES: StoreNamesTypes = { + LOGIN_INFO: 'loginInfo', + PROJECT_LIST: 'projectList', + ALLPROJECT: 'allProject', + PUBLICK_INDEX: 'publicIndex', + MODEL_DETAIL: 'modelDetail', + PROJECT_DETAIL: 'projectDetail', + PROJECT_ID: 'peojectId', +} + +export default STORE_NAMES; diff --git a/bmp-console-web/src/utils/constants.ts b/bmp-console-web/src/utils/constants.ts new file mode 100644 index 0000000..6a80dd7 --- /dev/null +++ b/bmp-console-web/src/utils/constants.ts @@ -0,0 +1,1248 @@ +import i18n from 'lib/i18n/index.ts'; // 国际化 +/** + * 国际化 +*/ +const {global} = i18n; + +/** + * 自定义列表类 +*/ +type optionArrType = { + name: string; + selected: boolean; + disabled: boolean; + label?: string; +}; + +type radioArrType = { + label: string; + value: string; +}; + +/** + * 通用状态类 +*/ +type CurrencyStatusType = { + required: boolean; + selected: boolean; +}; + +/** + * 通用状态 +*/ +const currencyStatus: CurrencyStatusType = { + required: false, + selected: true +}; + +/** + * 禁止更改状态 +*/ +const prohibitChangesStatus: CurrencyStatusType = { + required: true, + selected: true +}; + +/** + * 自定义数据信息类 +*/ +type InfoType = Record>; + +/** + * 通用类-列表 +*/ +type CurrencyType = { + text: string; + label: string | number; + info: any; + filterParams: string; +}; + +/** + * 类集合 +*/ + interface StaticDataType { + NormalDataType: { + value: number | string; + text?: string; + label?: string | number; + id?: string | number; + }; + porjectCustomType: InfoType; + alarmLogCustomType: InfoType; + operationCustomType: InfoType; + CurrencyListType: Required<{value: number | string;}> & Partial; + +}; + +/** + * 手机号 +*/ +export const cellPhoneType: StaticDataType['NormalDataType'][] = [ + { + value: '086', + label: global.t('personCentre.phoneData.chineseMainland') // 中国大陆 + }, + { + value: '852', + label: global.t('personCentre.phoneData.chineseHongKong') // 中国香港 + }, + { + value: '853', + label: global.t('personCentre.phoneData.chineseMacao') // 中国澳门 + }, + { + value: '886', + label: global.t('personCentre.phoneData.chineseTaiwan') // 中国台湾 + }, + { + value: '54', + label: global.t('personCentre.phoneData.Argentina') // 阿根廷 + }, + { + value: '61', + label: global.t('personCentre.phoneData.Australia') // 澳大利亚 + }, + { + value: '55', + label: global.t('personCentre.phoneData.Brazil') // 巴西 + }, + { + value: '49', + label: global.t('personCentre.phoneData.Germany') // 德国 + }, + { + value: '33', + label: global.t('personCentre.phoneData.France') // 法国 + }, + { + value: '82', + label: global.t('personCentre.phoneData.SouthKorea') // 韩国 + }, + { + value: '01', + label: global.t('personCentre.phoneData.Canada') // 加拿大 + }, + { + value: '1', + label: global.t('personCentre.phoneData.USA') // 美国 + }, + { + value: '52', + label: global.t('personCentre.phoneData.Mexico') // 墨西哥 + }, + { + value: '27', + label: global.t('personCentre.phoneData.SouthAfrica') // 南非 + }, + { + value: '81', + label: global.t('personCentre.phoneData.Japan') // 日本 + }, + { + value: '966', + label: global.t('personCentre.phoneData.SaudiArabia') // 沙特阿拉伯 + }, + { + value: '90', + label: global.t('personCentre.phoneData.Turkey') // 土耳其 + }, + { + value: '39', + label: global.t('personCentre.phoneData.Italy') // 意大利 + }, + { + value: '91', + label: global.t('personCentre.phoneData.India') // 印度 + }, + { + value: '62', + label: global.t('personCentre.phoneData.Indonesia') // 印度尼西亚 + }, + { + value: '44', + label: global.t('personCentre.phoneData.UnitedKiongdom') // 英国 + } +]; + +/** + * 语言 +*/ +export const languageType: StaticDataType['NormalDataType'][] = [ + { + value: 'zh_CN', + label: global.t('personCentre.language.chinese') // 中文 + },{ + value: 'en_US', + label: 'English' // 英语 + }, + +]; +/** + * api权限 +*/ +export const apiKeyType: StaticDataType['NormalDataType'][] = [ + { + value: 0, + label: global.t('personCentre.apiPower.writeAndRead') // 读/写 + }, + { + value: 1, + label: global.t('personCentre.apiPower.read') // 只读 + }, + + +]; +/** + * api创建权限 +*/ +export const apiKeyCreateType: StaticDataType['NormalDataType'][] = [ + { + value: 0, + label: global.t('personCentre.apiPower.writeAndRead') // 读/写 + }, + // { + // value: 1, + // label: global.t('personCentre.apiPower.read') // 只读 + // }, + + +]; +/** + * 添加共享用户权限 +*/ +export const relateUserPowerType: StaticDataType['NormalDataType'][] = [ + { + value: 0, + label: global.t('personCentre.apiPower.writeAndRead') // 读/写 + }, + // { + // value: 1, + // label: global.t('personCentre.apiPower.read') // 只读 + // }, + + +]; +/** + * 中间态 +*/ +export const intermediate: string[] = ['creating', 'starting', 'stopping', 'restarting', 'resetting_password', 'destroying', 'upgrading', 'reinstalling','Creating', 'Starting', 'Stopping', 'Restarting', 'Resetting_password', 'Destroying', 'Upgrading', 'Reinstalling']; + +/** + * 镜像类型 +*/ +export const imageType: string[] = ['CentOS', 'Ubuntu', 'Windows', 'Debian', 'OpenEuler']; + +/** + * 项目列表自定义信息 +*/ +export const porjectCustomIntro: StaticDataType['porjectCustomType'] = { + projectName: currencyStatus, // 项目名称 + projectId: prohibitChangesStatus, // id + owned: currencyStatus, // 项目协作状态 + instanceCount: currencyStatus, // 实例数 + createdTime: currencyStatus, // 创建时间 + updatedTime: currencyStatus, // 更新时间 + operation: prohibitChangesStatus, // 操作 + +}; +/** + * 项目列表自定义项 + */ +export const porjectCustomInfo: optionArrType[]= [ + { + // 项目名称 + name: global.t('list.project.projectName'), + selected: true, + disabled: false, + label: 'projectName' + }, + { + // id + name: global.t('list.project.projectId'), + selected: true, + disabled: true, + label: 'projectId' + }, + { + // 项目协作状态 + name: global.t('list.project.relatedState'), + selected: true, + disabled: false, + label: 'owned' + }, + { + // 实例数 + name: global.t(('list.project.instanceNumber')), + selected: true, + disabled: false, + label: 'instanceCount' + }, + { + // 创建时间 + name: global.t('personCentre.form.createdTime'), + selected: true, + disabled: false, + label: 'createdTime' + + }, + { + // 更新时间 + name: global.t('personCentre.form.updatedTime'), + selected: true, + disabled: false, + label: 'updatedTime' + + }, + { + // 操作 + name: global.t('personCentre.form.operation'), + selected: true, + disabled: true, + label: 'operation' + } +]; + +/** + * 项目列表自定义信息 +*/ +export const instanceCustomIntro: StaticDataType['porjectCustomType'] = { + instanceName: prohibitChangesStatus, // 实例名称 + monitor: prohibitChangesStatus, // 监控 + status: currencyStatus, // 状态 + deviceTypeName: currencyStatus, // 机型 + imageName: currencyStatus, // 镜像 + iloIp: currencyStatus, // 带外IP + privateIpv4: currencyStatus, // 内网IPv4(eth0) + privateEth1Ipv4: currencyStatus, // 内网IPv4(eth1) + privateIpv6: currencyStatus, // 内网IPv6(eth0) + privateEth1Ipv6: currencyStatus, // 内网IPv6(eth1) + config: currencyStatus, // 配置 + createdTime: currencyStatus, // 创建时间 + operation: prohibitChangesStatus, // 操作 + +}; + +/** + * 实例列表自定义项 + */ + export const instanceCustomInfo: optionArrType[]= [ + { + // 实例名称/ID + name: global.t('instance.list.instanceName'), + selected: true, + disabled: true, + label: 'instanceName', + }, + { + // 监控 + name: global.t('alarm.monitor.monitor'), + selected: true, + disabled: true, + label: 'monitor', + }, + { + // 状态 + name: global.t('instance.list.state'), + selected: true, + disabled: false, + label: 'status', + }, + { + // 机型 + name: global.t(('instance.list.model')), + selected: true, + disabled: false, + label: 'deviceTypeName', + }, + { + // 镜像 + name: global.t(('instance.list.mirror')), + selected: true, + disabled: false, + label: 'imageName', + }, + { + // 带外IP + name: global.t(('instance.list.outBandIp')), + selected: true, + disabled: false, + label: 'iloIp', + }, + { + // 内网IPv4(eth0) + name: global.t('instance.list.intranetIpv4'), + selected: true, + disabled: false, + label: 'privateIpv4', + + }, + { + // 内网IPv4(eth1) + name: global.t('instance.list.intranetIpv4eth1'), + selected: true, + disabled: false, + label: 'privateEth1Ipv4', + + }, + { + // 内网IPv6(eth0) + name: global.t('instance.list.intranetIpv6'), + selected: true, + disabled: false, + label: 'privateIpv6', + + }, + { + // 内网IPv6(eth1) + name: global.t('instance.list.intranetIpv6eth1'), + selected: true, + disabled: false, + label: 'privateEth1Ipv6', + + }, + { + // 配置 + name: global.t('instance.list.config'), + selected: true, + disabled: false, + label: 'config', + + }, + { + // 创建时间 + name: global.t('instance.list.createdTime'), + selected: true, + disabled: false, + label: 'createdTime', + + }, + { + // 操作 + name: global.t('personCentre.form.operation'), + selected: true, + disabled: true, + label: 'operation', + } +]; + +/** + * 管理状态 +*/ +export const manageMentStatus: StaticDataType['CurrencyListType'][] = [ // 管理状态filter数据 + { + filterParams: 'running', + text: global.t('list.status.running'), + value: 1 + }, + { + filterParams: 'stopped', + text: global.t('list.status.stopped'), + value: 2 + }, + { + filterParams: 'Creation failed', + text: global.t('list.status.creationFailed'), + value: 3 + }, + +]; + +/** + * 锁定状态 + */ +export const lockedStatus = { + 'locked': global.t('list.status.locked'), + 'unlocked': global.t('list.status.unlocked') +} + +/** + * 项目协作状态 +*/ +export const projectRelatedStatus: StaticDataType['CurrencyListType'][] = [ // 管理状态filter数据 + { + filterParams: '1', + text: global.t('list.project.owner'), + value: 1 + }, + { + filterParams: '2', + text: global.t('list.project.cooperate'), + value: 2 + } + +]; + +/** + * 批量操作提示 + */ + export const batchOperationTip = { + 'close': global.t('list.content.bacthCloseContent'), + 'open': global.t('list.content.bacthOpenContent'), + 'restart': global.t('list.content.bacthRestartContent'), + 'resetPassword': global.t('list.content.bacthResetPasswordContent'), + 'rename': global.t('list.content.bacthRenameContent'), + 'delete': global.t('list.content.bacthDeleteContent') +} + +/** + * 报警日志列表自定义信息 +*/ +export const alarmLogCustomIntro: StaticDataType['alarmLogCustomType'] = { + logid: prohibitChangesStatus, // 序号 + alert_type: currencyStatus, // 故障类型 + alert_desc: currencyStatus, // 故障描述 + event_time: currencyStatus, // 故障报警时间 + update_time: currencyStatus, // 更新时间 + count: currencyStatus, // 报警次数 + status: currencyStatus, // 状态 + +}; + +/** + * 报警日志列表自定义项 + */ + export const alarmLogCustomInfo: optionArrType[]= [ + { + // 序号 + name: global.t('instance.detail.number'), + selected: true, + disabled: true, + label: 'logid', + }, + { + // 故障类型 + name: global.t('instance.detail.faultType'), + selected: true, + disabled: false, + label: 'alertType', + }, + { + // 故障描述 + name: global.t(('instance.detail.faultDesc')), + selected: true, + disabled: false, + label: 'alertDesc', + }, + { + // 故障报警时间 + name: global.t(('instance.detail.faultAlarmTime')), + selected: true, + disabled: false, + label: 'eventTime', + }, + { + // 更新时间 + name: global.t(('instance.detail.updatedTime')), + selected: true, + disabled: false, + label: 'updateTime', + }, + { + // 报警次数 + name: global.t('instance.detail.alarmNumbers'), + selected: true, + disabled: false, + label: 'count', + + }, + { + // 状态 + name: global.t('instance.detail.status'), + selected: true, + disabled: false, + label: 'status', + + } +]; + +/** + * 报警日志状态 + */ + export const alarmStatusConstant = { + 0: global.t('instance.detail.unhandled'), /* 未处理 */ + 1: global.t('instance.detail.recovered'), /* 已恢复 */ + 2: global.t('instance.detail.ignored'), /* 已忽略 */ +} + +/** + * 消息列表分组 + */ + export const groupingMessageListConstant: radioArrType[] = [ + { + label: global.t('messageCentre.list.all'), + value: '2' + },{ + label: global.t('messageCentre.list.unread'), + value: '0' + },{ + label: global.t('messageCentre.list.read'), + value: '1' + } + ] + + /** + * 消息列表自定义信息 +*/ +export const messageCustomIntro: StaticDataType['porjectCustomType'] = { + detail: prohibitChangesStatus, // 消息内容 + finish_time: currencyStatus, // 接收时间 + message_type: currencyStatus, // 消息类型 + message_sub_type: currencyStatus, // 消息子类型 +}; + +/** + * 消息列表自定义项 + */ + export const messageCustomInfo: optionArrType[]= [ + { + // 消息内容 + name: global.t('messageCentre.list.messageContent'), + selected: true, + disabled: true, + label: 'detail', + }, + { + // 接受时间 + name: global.t('messageCentre.list.receivingTime'), + selected: true, + disabled: false, + label: 'finish_time', + }, + { + // 消息类型 + name: global.t(('messageCentre.list.messageType')), + selected: true, + disabled: false, + label: 'message_type', + }, + { + // 消息子类型 + name: global.t(('messageCentre.list.messageSubtype')), + selected: true, + disabled: false, + label: 'message_sub_type', + }, +]; + +/** + * 通知状态 + */ + export const messageContentConstant = { + 'failed': global.t('messageCentre.detail.faultContent'), /* 失败 */ +} + +/** + * 操作日志列表自定义信息 +*/ +export const operationCustomIntro: StaticDataType['operationCustomType'] = { + logId: prohibitChangesStatus, // 序号 + operation: currencyStatus, // 操作名称 + username: currencyStatus, // 操作人 + operationTime: currencyStatus, // 操作时间 + operationFeedback: currencyStatus, // 操作反馈 + faultWord: currencyStatus, // 错误码 + +} + +/** + * 操作日志列表自定义项 + */ + export const operationCustomInfo: optionArrType[]= [ + { + // LogID + name: global.t('instance.detail.logId'), + selected: true, + disabled: true, + label: 'logid', + }, + { + // 操作名称 + name: global.t('instance.detail.operationName'), + selected: true, + disabled: false, + label: 'operationName', + }, + { + // 操作人 + name: global.t(('instance.detail.operator')), + selected: true, + disabled: false, + label: 'userName', + }, + { + // 操作时间 + name: global.t(('instance.detail.operationTime')), + selected: true, + disabled: false, + label: 'operateTime', + }, + { + // 操作反馈 + name: global.t(('instance.detail.operationFeedback')), + selected: true, + disabled: false, + label: 'result', + }, + { + // 错误码 + name: global.t('instance.detail.faultWord'), + selected: true, + disabled: false, + label: 'failReason', + + } +]; + + +/** + * 操作反馈状态 +*/ +export const operationLogStatus: StaticDataType['CurrencyListType'][] = [ // 操作反馈filter数据 + { + filterParams: 'success', + text: global.t('personCentre.content.operateSuccess'), + value: 'success' + }, + { + filterParams: 'fail', + text: global.t('personCentre.content.operateFailed'), + value: 'fail' + }, + { + filterParams: 'doing', + text: global.t('personCentre.content.operateDoing'), + value: 'doing' + }, +]; + +/** + * 操作反馈状态 + */ + export const operationLogStatusConstant = { + 'success': global.t('personCentre.content.operateSuccess'), /* 操作成功 */ + 'fail': global.t('personCentre.content.operateFailed'), /* 操作失败 */ + 'doing': global.t('personCentre.content.operateDoing'), /* 操作中 */ +} + +/** + * 报警规则列表自定义信息 +*/ +export const alarmRuleCustomIntro: StaticDataType['operationCustomType'] = { + ruleName: prohibitChangesStatus, // 序号 + ruleId: currencyStatus, // 操作名称 + resourceName: currencyStatus, // 操作人 + instanceCount: currencyStatus, // 操作时间 + triggerDescription: currencyStatus, // 操作反馈 + statusName: currencyStatus, // 错误码 + operation: prohibitChangesStatus, // 操作 + +} + +/** + * 报警规则列表自定义项 + */ + export const alarmRuleCustomInfo: optionArrType[]= [ + { + // 规则名称 + name: global.t('alarm.alarmRule.ruleName'), + selected: true, + disabled: true, + label: 'ruleName', + }, + { + // 规则ID + name: global.t('alarm.alarmRule.ruleId'), + selected: true, + disabled: false, + label: 'ruleId', + }, + { + // 资源类型 + name: global.t(('alarm.alarmRule.resourceType')), + selected: true, + disabled: false, + label: 'resourceName', + }, + { + // 关联实例类型 + name: global.t(('alarm.alarmRule.instanceNumber')), + selected: true, + disabled: false, + label: 'instanceCount', + }, + { + // 触发条件 + name: global.t(('alarm.alarmRule.triggeringCondition')), + selected: true, + disabled: false, + label: 'triggerDescription', + }, + { + // 状态 + name: global.t('alarm.alarmRule.status'), + selected: true, + disabled: false, + label: 'statusName', + + }, + { + // 操作 + name: global.t('personCentre.form.operation'), + selected: true, + disabled: true, + label: 'operation' + } +]; + +/** + * 报警资源类型 +*/ +export const resourceData: StaticDataType['CurrencyListType'][] = [ // 管理状态filter数据 + { + text: global.t('instance.detail.instance'), + value: 'instance' + } + +]; + +/** + * 维度下拉状态 + */ + export const dimentionState = { + 'disk': global.t('alarm.alarmRule.disk'), + 'mountpoint': global.t('alarm.alarmRule.mountpoint'), + 'nic': global.t('alarm.alarmRule.nic'), + +} + +/** + * 实例监控指标类型 +*/ +export const metricInstanceData: StaticDataType['CurrencyListType'][] = [ + { + text: global.t('alarm.alarmRule.cpuUtil'), + value: 'bmp.cpu.util' + }, + { + text: global.t('alarm.alarmRule.memoryUsage'), + value: 'bmp.memory.util' + }, + { + text: global.t('alarm.alarmRule.memoryUsed'), + value: 'bmp.memory.used' + }, + { + text: global.t('alarm.alarmRule.diskUsed'), + value: 'bmp.disk.used' + }, + { + text: global.t('alarm.alarmRule.diskUsage'), + value: 'bmp.disk.util' + }, + { + text: global.t('alarm.alarmRule.diskReadTraffic'), + value: 'bmp.disk.bytes.read' + }, + { + text: global.t('alarm.alarmRule.diskWriteTraffic'), + value: 'bmp.disk.bytes.write' + }, + { + text: global.t('alarm.alarmRule.diskReadIOPS'), + value: 'bmp.disk.counts.read' + }, + { + text: global.t('alarm.alarmRule.diskWriteIOPS'), + value: 'bmp.disk.counts.write' + }, + { + text: global.t('alarm.alarmRule.networkIngressTraffic'), + value: 'bmp.network.bytes.ingress' + }, + { + text: global.t('alarm.alarmRule.networkEgressTraffic'), + value: 'bmp.network.bytes.egress' + }, + { + text: global.t('alarm.alarmRule.networkIngressPackets'), + value: 'bmp.network.packets.ingress' + }, + { + text: global.t('alarm.alarmRule.networkEgressPackets'), + value: 'bmp.network.packets.egress' + }, + { + text: global.t('alarm.alarmRule.loadAverage1min'), + value: 'bmp.avg.load1' + }, + { + text: global.t('alarm.alarmRule.loadAverage5min'), + value: 'bmp.avg.load5' + }, + { + text: global.t('alarm.alarmRule.loadAverage15min'), + value: 'bmp.avg.load15' + }, + { + text: global.t('alarm.alarmRule.totalTCPConnections'), + value: 'bmp.tcp.connect.total' + }, + { + text: global.t('alarm.alarmRule.establishedTCPConnections'), + value: 'bmp.tcp.connect.established' + }, + { + text: global.t('alarm.alarmRule.totalProcessCount'), + value: 'bmp.process.total' + }, + + +]; + +/** + * 磁盘监控指标类型 +*/ +export const metricDiskData: StaticDataType['CurrencyListType'][] = [ + { + text: global.t('alarm.alarmRule.diskUsed'), + value: 'bmp.disk.used' + }, + { + text: global.t('alarm.alarmRule.diskUsage'), + value: 'bmp.disk.util' + }, + { + text: global.t('alarm.alarmRule.diskReadTraffic'), + value: 'bmp.disk.bytes.read' + }, + { + text: global.t('alarm.alarmRule.diskWriteTraffic'), + value: 'bmp.disk.bytes.write' + }, + { + text: global.t('alarm.alarmRule.diskReadIOPS'), + value: 'bmp.disk.counts.read' + }, +] + +/** + * 磁盘用量监控指标类型 +*/ +export const metricMountpointData: StaticDataType['CurrencyListType'][] = [ + { + text: global.t('alarm.alarmRule.diskUsedMountPoint'), + value: 'bmp.disk.partition.used' + }, + { + text: global.t('alarm.alarmRule.diskUsageMountPoint'), + value: 'bmp.disk.partition.util' + } +] + +/** + * 网口监控指标类型 +*/ +export const metricNetworkData: StaticDataType['CurrencyListType'][] = [ + { + text: global.t('alarm.alarmRule.networkIngressTraffic'), + value: 'bmp.network.bytes.ingress' + }, + { + text: global.t('alarm.alarmRule.networkEgressTraffic'), + value: 'bmp.network.bytes.egress' + }, + { + text: global.t('alarm.alarmRule.networkIngressPackets'), + value: 'bmp.network.packets.ingress' + }, + { + text: global.t('alarm.alarmRule.networkEgressPackets'), + value: 'bmp.network.packets.egress' + }, +] + +/** + * 周期类型 +*/ +export const periodData: StaticDataType['CurrencyListType'][] = [ + { + text: global.t('alarm.alarmRule.oneM'), + value: 1 + }, + { + text: global.t('alarm.alarmRule.twoM'), + value: 2 + }, + { + text: global.t('alarm.alarmRule.fiveM'), + value: 5 + }, + { + text: global.t('alarm.alarmRule.fifteenM'), + value: 15 + }, + { + text: global.t('alarm.alarmRule.halfH'), + value: 30 + }, + { + text: global.t('alarm.alarmRule.oneH'), + value: 60 + }, +] + +/** + * 计算方式类型 +*/ +export const calculationData: StaticDataType['CurrencyListType'][] = [ + { + text: global.t('alarm.alarmRule.max'), + value: 'max' + }, + { + text: global.t('alarm.alarmRule.min'), + value: 'min' + }, + { + text: global.t('alarm.alarmRule.avg'), + value: 'avg' + }, + { + text: global.t('alarm.alarmRule.sum'), + value: 'sum' + }, +] + +/** + * 比较类型 +*/ +export const operationData: StaticDataType['CurrencyListType'][] = [ + { + text: '>', + value: 'gt' + }, + { + text: '>=', + value: 'gte' + }, + { + text: '<', + value: 'lt' + }, + { + text: '<=', + value: 'lte' + }, + { + text: '==', + value: 'eq' + }, + { + text: '!=', + value: 'neq' + }, +] + +/** + * 计算单位类型 +*/ +export const calculationUnitData: StaticDataType['NormalDataType'][] = [ + { id: 'bmp.cpu.util', value: '%', text: '%' }, + { id: 'bmp.memory.util', value: '%', text: '%' }, + { id: 'bmp.memory.used', value: 'GB', text: 'GB' }, + { id: 'bmp.disk.used', value: 'GB', text: 'GB' }, + { id: 'bmp.disk.util', value: '%', text: '%' }, + { id: 'bmp.disk.bytes.read', value: 'Bps', text: 'Bps' }, + { id: 'bmp.disk.bytes.write', value: 'Bps', text: 'Bps' }, + { id: 'bmp.disk.counts.read', value: '次/秒', text: '次/秒' }, + { id: 'bmp.disk.counts.write', value: '次/秒', text: '次/秒' }, + { id: 'bmp.network.bytes.ingress', value: 'bps', text: 'bps' }, + { id: 'bmp.network.bytes.egress', value: 'bps', text: 'bps' }, + { id: 'bmp.network.packets.ingress', value: '个', text: '个/秒' }, + { id: 'bmp.network.packets.egress', value: '个', text: '个/秒' }, + { id: 'bmp.avg.load1', value: '', text: ' ' }, + { id: 'bmp.avg.load5', value: '', text: ' ' }, + { id: 'bmp.avg.load15', value: '', text: ' ' }, + { id: 'bmp.tcp.connect.total', value: '个', text: '个' }, + { id: 'bmp.tcp.connect.established', value: '个', text: '个' }, + { id: 'bmp.process.total', value: '个', text: '个' }, + { id: 'bmp.disk.partition.used', value: 'GB', text: 'GB' }, + { id: 'bmp.disk.partition.util', value: '%', text: '%' }, +]; + +/** + * 持续周期类型 +*/ +export const timesData: StaticDataType['CurrencyListType'][] = [ + { + text: global.t('alarm.alarmRule.continuePeriod',[1]) , + value: 1 + }, + { + text: global.t('alarm.alarmRule.continuePeriod',[2]), + value: 2 + }, + { + text: global.t('alarm.alarmRule.continuePeriod',[3]), + value: 3 + }, + { + text: global.t('alarm.alarmRule.continuePeriod',[4]), + value: 4 + }, + { + text: global.t('alarm.alarmRule.continuePeriod',[5]), + value: 5 + }, + { + text: global.t('alarm.alarmRule.continuePeriod',[10]), + value: 10 + }, + { + text: global.t('alarm.alarmRule.continuePeriod',[15]), + value: 15 + }, + { + text: global.t('alarm.alarmRule.continuePeriod',[30]), + value: 30 + }, + { + text: global.t('alarm.alarmRule.continuePeriod',[60]), + value: 60 + }, +] + +/** + * 告警级别类型 +*/ +export const noticeLevelData: StaticDataType['CurrencyListType'][] = [ + { + text: global.t('alarm.alarmRule.normal'), + value: 1 + }, + { + text: global.t('alarm.alarmRule.serious'), + value: 2 + }, + { + text: global.t('alarm.alarmRule.urgent'), + value: 3 + }, +] + +/** + * 通知周期类型 +*/ +export const noticePeriodData: StaticDataType['CurrencyListType'][] = [ + { + text: global.t('alarm.alarmRule.minute',[5]) , + value: 5 + }, + { + text: global.t('alarm.alarmRule.minute',[10]), + value: 10 + }, + { + text: global.t('alarm.alarmRule.minute',[15]), + value: 15 + }, + { + text: global.t('alarm.alarmRule.minute',[30]), + value: 30 + }, + { + text: global.t('alarm.alarmRule.hour',[1]), + value: 60 + }, + { + text: global.t('alarm.alarmRule.hour',[3]), + value: 180 + }, + { + text: global.t('alarm.alarmRule.hour',[6]), + value: 360 + }, + { + text: global.t('alarm.alarmRule.hour',[12]), + value: 720 + }, + { + text: global.t('alarm.alarmRule.hour',[24]), + value: 1440 + }, +] + +/** + * 通知条件类型 +*/ +export const noticeConditionData: StaticDataType['CurrencyListType'][] = [ + { + text: global.t('alarm.alarmRule.alarm'), + value: 1 + }, + { + text: global.t('alarm.alarmRule.beNormal'), + value: 2 + }, +] + +/** + * 接收渠道类型 +*/ +export const noticeWayData: StaticDataType['CurrencyListType'][] = [ + { + text: global.t('alarm.alarmRule.inEmail'), + value: 1 + }, + { + text: global.t('alarm.alarmRule.email'), + value: 2 + }, +] + +/** + * 报警规则状态 +*/ +export const alarmRuleStatus: StaticDataType['CurrencyListType'][] = [ // 报警规则状态filter数据 + { + filterParams: '1', + text: global.t('alarm.alarmRule.regular'), + value: 1 + }, + { + filterParams: '2', + text: global.t('alarm.alarmRule.forbid'), + value: 2 + }, + { + filterParams: '3', + text: global.t('alarm.alarmRule.alarm'), + value: 3 + }, +]; + +/** + * 维度类型 +*/ +export const dimensionData: StaticDataType['CurrencyListType'][] = [ + { + text: global.t('alarm.alarmRule.instance'), + value: 'instance' + }, + { + text: global.t('alarm.alarmRule.disk'), + value: 'disk' + }, + { + text: global.t('alarm.alarmRule.mountpoint'), + value: 'mountpoint' + }, + { + text: global.t('alarm.alarmRule.nic'), + value: 'nic' + }, +] + + + diff --git a/bmp-console-web/src/utils/index.ts b/bmp-console-web/src/utils/index.ts new file mode 100644 index 0000000..a02d250 --- /dev/null +++ b/bmp-console-web/src/utils/index.ts @@ -0,0 +1,561 @@ +import VueCookies from 'vue-cookies'; // cookie +import { ref, onUnmounted } from 'vue'; +import en from 'element-plus/lib/locale/lang/en'; // 英文 +import zhCn from 'element-plus/lib/locale/lang/zh-cn'; // 中文 +const CryptoJS = require('crypto-js'); + +/** + * AES加密 +*/ +export const encrypt = (str: string, keyStr: string, ivStr: string) => { + let key: string = CryptoJS.enc.Utf8.parse(keyStr); + let iv: string = CryptoJS.enc.Utf8.parse(ivStr); + let srcs: string = CryptoJS.enc.Utf8.parse(str); + let encrypt: {ciphertext: string} = CryptoJS.AES.encrypt(srcs, key, { + iv, + mode: CryptoJS.mode.CBC, // AES加密模式 + padding: CryptoJS.pad.Pkcs7 + }); + return CryptoJS.enc.Base64.stringify(encrypt.ciphertext); +} + +/** + * AES解密 +*/ +export const decrypt = (str: string, keyStr: string, ivStr: string) => { + let key: string = CryptoJS.enc.Utf8.parse(keyStr); + let iv: string = CryptoJS.enc.Utf8.parse(ivStr); + let base64: string = CryptoJS.enc.Base64.parse(str); + let src: string = CryptoJS.enc.Base64.stringify(base64); + let decrypt = CryptoJS.AES.decrypt(src, key, { + iv, + mode: CryptoJS.mode.CBC, // AES解密模式 + padding: CryptoJS.pad.Pkcs7 + }); + return decrypt.toString(CryptoJS.enc.Utf8).toString(); +}; + +/** + * 深拷贝 + * @param {Object | Array | number | string | null} target 需要拷贝的数据 + * @return {number | string | null | undefined} data 深拷贝的数据 + * @return {Object | Array} result 深拷贝的数据 +*/ +export function deepCopy(data: {[x: string]: any; hasOwnProperty: (arg0: string) => any} | null) { + if (typeof data !== 'object' || data === null) { + return data; + } + // 判断是数组还是对象 + const result: [] | {} = data instanceof Array ? [] : {}; + for (const key in data) { + // 只拷贝对象自身的属性 + if (data.hasOwnProperty(key)) { + (result as any)[key] = deepCopy(data[key]); + } + } + return result; +} + +/** + * 获取cookie里面的语言 +*/ +const vueCookiesInfo = (VueCookies as any).get('X-Jdcloud-Language') || 'zh_CN'; + +/** + * 语言切换 + * @return {string} zhCn | en 中文|英文 +*/ +export const languageSwitch = (): string | unknown => { + return vueCookiesInfo === 'zh_CN' ? zhCn : en; +}; + +/** + * 获取日期 + * @return {string} xxx 年-月-日 +*/ +export const getDate = (): string => { + const year: number = new Date().getFullYear(); + const month: number = new Date().getMonth() + 1; + const day: number = new Date().getDate(); + return `${year}-${month}-${day}` +}; + +/** + * 获取日期时分秒 + * @return {string} xxx 年-月-日-时分秒 +*/ +export const getDateMinutes = (params: T): string => { + if ([undefined, null].includes((params as undefined))) return '--'; + const newParams: number = (params as number) * 1000; + const year: number = new Date(newParams).getFullYear(); + const month: number = new Date(newParams).getMonth() + 1; + const day: number = new Date(newParams).getDate(); + const hours: number = new Date(newParams).getHours(); + const minutes: number = new Date(newParams).getMinutes(); + const mill: number = new Date(newParams).getSeconds(); + return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${mill < 10 ? '0' + mill : mill}` +}; + +/** + * 生成随机数字 + * @param {number} num 随机数位数 + * @return {string} xxx 生成的随机数 +*/ +export const generateRandomNum = (num: number): string => { + let randomNum: string = '' + for(let i: number = 0; i < num; i++) { + randomNum += String(Math.floor(Math.random() * 10)); + } + return randomNum; +}; + +export const hasShowTooltip = (event: Event, row: {showTooltip: boolean}, text: string, num: number = 0, type: string) =>{ + // event为鼠标移入时的事件对象 + // textWidth 为文本在页面中所占的宽度,创建标签,加入到页面,获取textWidth ,最后在移除 + const createSpan: HTMLSpanElement = document.createElement('span'); + // 文本内容 + createSpan.innerText = text; + // 文本class类 + createSpan.className = 'getTextWidth'; + // body里添加 + document?.querySelector('body')?.appendChild(createSpan); + // 类型断言,获取文本offsetWidth + const textWidth: number = (document?.querySelector('.getTextWidth') as HTMLElement)?.offsetWidth; + // 移除 + document?.querySelector('.getTextWidth')?.remove(); + // tableWidth为表格容器的宽度、类型断言 + const tableWidth: number = (event?.target as HTMLElement)?.offsetWidth; + // 列表页中tableWidth固定,详情页不固定 + if(type === 'detail') { + tableWidth <= num ? row.showTooltip = false : row.showTooltip = true; + }else{ + // 当文本宽度小于等于容器宽度两倍时,这块会有点小误差,根据业务来换算,代表文本显示未超过两行 + textWidth <= Math.ceil(num * tableWidth) ? row.showTooltip = false : row.showTooltip = true; + } +}; + +/** + * 过滤重复数据 + * @param {Array} data 需要过滤的数据 + * @return {Array} newArr 过滤完毕的数据 +*/ +export const filterData = (data: any[], filterType: string) => { + const newArr: string[] = [] + const map: Map = new Map(); + for(let i: number = 0; i < data.length; i++){ + // 如果 map里面不包含,就设置进去 + if (!map.has(data[i][filterType])) { + map.set(data[i][filterType], true); + newArr.push( + { + [filterType]: data[i][filterType], + ...data[i] + } + ); + } + }; + return newArr; +}; + +/** + * 防抖函数 + * @param {Any} fn 需要加上防抖的函数 + * @param {Any} delay 延迟的时间 +*/ +export function debounce(fn:any, delay:any) { + let timer:any = null; // 形成闭包 + return function () { + if (timer) { + clearTimeout(timer); // 防抖 + } + timer = setTimeout(() => { + fn(); // 执行传入的函数 + }, delay); + }; +} + +/** + * 合并两个对象,如果两个对象中有相同的键,且第二个对象中对应的值为非空, + * 则使用第二个对象中的值覆盖第一个对象中的空值。 + * + * @param {T} obj1 第一个对象 + * @param {U} obj2 第二个对象,其值可能会覆盖第一个对象中的空值 + * @returns {T & U} 返回一个新的对象,包含合并后的键值对 + */ + export const mergeObjectsWithNonEmptyOverride = (obj1: T, obj2: U): T & U => { + // 创建一个新对象,初始包含obj1的所有键值对 + const result: Partial = { ...obj1 }; + + // 遍历obj2的键值对 + Object.entries(obj2).forEach(([key, value]) => { + // 检查obj2中的值是否为非空(不是空字符串、null或undefined) + const isValueNonEmpty = value !== "" && value !== null && value !== undefined; + + // 获取result中对应键的值 + const originalValue = result[key as keyof typeof result]; + + // 检查原对象中的值是否为空(空字符串、null或undefined) + // 首先确保originalValue是一个字符串,然后检查是否为空字符串 + const isOriginalValueEmpty = typeof originalValue === 'string' && originalValue === "" || originalValue === null || originalValue === undefined; + + // 如果obj2中的值为非空,或者obj1中对应的键的值为空,则使用obj2的值 + if (isValueNonEmpty || isOriginalValueEmpty) { + result[key as keyof typeof result] = value; + } + }); + + // 返回合并后的新对象 + return result as T & U; +}; + +type TimeStrings = [string, string]; +interface TimeObject { + [key: string]: number; +} + +/** + * 将包含两个日期字符串的数组转换为一个对象,对象包含两个键值对, + * 键由参数指定,值为日期字符串对应的时间戳。 + * + * @param operationTimeStrings - 包含两个日期字符串的数组。 + * @param startKey - 转换后对象的起始时间键名。 + * @param endKey - 转换后对象的结束时间键名。 + * @returns 返回一个对象,包含起始和结束时间的时间戳。 + */ + export const convertStringsToTimestampObject = (operationTimeStrings: TimeStrings, startKey: string, endKey: string): TimeObject => { + if (operationTimeStrings.length !== 2) { + throw new Error('operationTimeStrings数组必须恰好包含两个元素。'); + } + + const [startString, endString] = operationTimeStrings; + const startTime = new Date(startString); + const endTime = new Date(endString); + + if (isNaN(startTime.getTime()) || isNaN(endTime.getTime())) { + throw new Error('提供的日期字符串无效。'); + } + + return { + [startKey]: startTime.getTime() /1000, + [endKey]: endTime.getTime()/1000, + }; +}; + +/** + * 创建一个延时动作,该动作在指定延时后执行,并且如果在延时期间再次被触发,则重新计时。 + * + * @param action - 要执行的动作,一个无参数的函数。 + * @param delay - 延时时间,单位为毫秒。 + * @returns 一个触发延时动作的函数。 + */ +export const useDebouncedAction = (action: () => void, delay: number) => { + // 存储当前的延时器 ID + const timeoutId = ref(undefined); + + /** + * 清除当前的延时器。 + */ + const clearTimer = () => { + if (timeoutId.value) { + clearTimeout(timeoutId.value); + timeoutId.value = undefined; + } + }; + + /** + * 触发延时动作。如果在延时期间再次被触发,则重新计时。 + */ + const trigger = () => { + clearTimer(); + timeoutId.value = window.setTimeout(() => { + action(); + clearTimer(); + }, delay); + }; + + // 组件卸载时清除延时器 + onUnmounted(clearTimer); + + return trigger; +}; + +/** + * 将日期字符串数组转换为一个对象,该对象包含 'start' 和 'end' 属性。 + * 这些属性代表日期字符串中的时间部分(HH:MM:SS)。 + * + * @param dateStrings - 需要转换的日期字符串数组。 + * @returns 一个对象,包含从输入日期中提取的 'start' 和 'end' 时间部分。 + */ +export const createTimeObjectFromDateStringArray = (dateStrings: string[]): { start: string, end: string } => { + // 如果dateStrings为null或undefined,返回start和end为空 + if (!dateStrings || dateStrings.length === 0) { + return { start: '', end: '' }; + } + /** + * 将日期字符串解析为 Date 对象。 + * + * @param dateString - 需要解析的日期字符串。 + * @returns 从输入字符串解析得到的 Date 对象。 + */ + const parseDate = (dateString: string): Date => new Date(dateString); + + /** + * 从 Date 对象中提取时间部分。 + * + * @param date - 需要从中提取时间的 Date 对象。 + * @returns 代表 Date 对象时间部分(HH:MM:SS)的字符串。 + */ + const getTimeFromDate = (date: Date): string => date.toTimeString().split(' ')[0]; + + // 将输入的日期字符串转换为 Date 对象数组 + const dates = dateStrings.map(parseDate); + + // 返回一个包含日期 'start' 和 'end' 时间部分的对象 + return { + start: getTimeFromDate(dates[0]), + end: getTimeFromDate(dates[1]) + }; + }; + + + +type Item = { +// 假设这是你的对象的类型,可以根据实际情况添加其他属性 +[key: string]: any; +}; + + /** + * 给对象数组中的每个对象添加一个独一无二的ID。 + * ID生成策略是结合当前时间戳和数组索引。 + * + * @param items - 待处理的对象数组。 + * @returns 返回一个新的数组,每个对象都包含一个唯一的ID。 + */ +export const addUniqueId = (items: Item[]): Item[] => { + return items.map((item, index) => ({ + ...item, + id: `unique_${Date.now()}_${index}` // 使用当前时间戳和索引生成一个简单的唯一ID + })); +}; + +// 假设的Item类型定义,这里我们假设每个对象都可能有一个id属性 +type IdItem = { + id?: string; + [key: string]: any; +}; + +/** + * 移除对象数组中每个对象的id属性。 + * + * @param items - 包含id属性的对象数组。 + * @returns 返回一个新的数组,每个对象都不包含id属性。 + */ +export const removeIdFromItems = (items: IdItem[]): Item[] => { + return items.map(({ id, ...rest }) => rest); +}; + +/** + * 将包含方括号的时间字符串转换为 Date 对象数组。 + * + * @param startTime - 开始时间字符串,格式为 'HH:MM:SS'。 + * @param endTime - 结束时间字符串,格式为 'HH:MM:SS'。 + * @returns 返回一个包含两个 Date 对象的数组,分别对应开始时间和结束时间。 + */ +export const convertBracketedTimeStringsToDateArray = (startTime: string, endTime: string): Date[] => { + // 移除时间字符串中的方括号并解析时间 + const parseTime = (time: string) => { + const [hours, minutes, seconds] = time.split(':').map(Number); + return new Date(0, 0, 0, hours, minutes, seconds); + }; + + // 使用 parseTime 函数转换开始和结束时间 + const startDate = parseTime(startTime); + const endDate = parseTime(endTime); + + // 返回包含两个日期对象的数组 + return [startDate, endDate]; +}; + +/** + * 将原始数组转换为对象数组,每个对象包含指定的键和值。 + * + * @param array - 原始数组,其元素将被用作对象数组中的值。 + * @param keys - 需要的键数组,可以是字符串或者是一个包含键名和转换函数的对象。 + * @returns 返回一个对象数组,每个对象包含指定的键和值。 + * + * 示例 + * const originalArray = ['Apple', 'Banana', 'Cherry']; + * const keys = [ + * 'original', // 直接使用数组元素作为值 + * { key: 'lowercase', value: (item: string) => item.toLowerCase() }, // 使用函数转换值 + * { key: 'length', value: (item: string) => item.length } // 使用函数转换值 + * ]; + */ +export const convertArrayToObjectArray = ( + array: T[], + keys: (string | { key: string, value: (item: T) => any })[] + ): Object[] => { + return array.map(item => { + const obj: { [key: string]: any } = {}; + keys.forEach(key => { + if (typeof key === 'string') { + // 如果 key 是字符串,直接使用数组元素作为值 + obj[key] = item; + } else { + // 如果 key 是对象,使用提供的函数来计算值 + obj[key.key] = key.value(item); + } + }); + return obj; + }); +}; + + +/** + * 从一个对象中移除指定的键 + * @param {Object} obj - 需要操作的对象 + * @param {string} key - 需要移除的键 + * @returns {Object} - 移除指定键后的新对象 + */ +export const removeObjectKey = ( + obj: T, + key: K + ): Omit => { + const { [key]: _, ...rest } = obj; + return rest; +}; + + +/** + * 根据给定的键和值在对象数组中查找,返回另一个指定键的值。 + * + * @param items - 对象数组 + * @param keyToFind - 要匹配的键 + * @param valueToFind - 要匹配的键的值 + * @param keyToReturn - 找到对象后要返回的键的值 + * @returns 找到的对象中指定键的值,如果没有找到则返回 undefined + */ + export const findValueByKey = ( + items: T[], + keyToFind: K1, + valueToFind: T[K1], + keyToReturn: K2 +): T[K2] | undefined => items.find(item => item[keyToFind] === valueToFind)?.[keyToReturn]; + +/** + * 根据给定的键和值数组在对象数组中查找,返回另一个指定键的值数组。 + * + * @param items - 对象数组 + * @param keyToFind - 要匹配的键 + * @param valuesToFind - 要匹配的键的值数组 + * @param keyToReturn - 找到对象后要返回的键的值 + * @returns 找到的对象中指定键的值数组,如果某个值没有找到则跳过 + */ + export const findValuesByKey = ( + items: T[], + keyToFind: K1, + valuesToFind: T[K1][], + keyToReturn: K2 + ): T[K2][] => { + return valuesToFind.reduce((acc: T[K2][], valueToFind) => { + const foundItem = items.find(item => item[keyToFind] === valueToFind); + if (foundItem) { + acc.push(foundItem[keyToReturn]); + } + return acc; + }, []); + }; + +/** + * 渲染数组内容,每个元素变成唯一对象 + */ +export const renderItemsWithBreaks = (items: any) => { + return items.map((item: any) => ({ item, key: hashCode(item) })); +}; + +/** + * 一个简单的哈希函数,用于生成字符串的哈希值。 + * 它将给定的值转换为字符串,然后计算该字符串的哈希值。 + * + * @param value - 任何可以被JSON.stringify的值。 + * @returns 哈希值的字符串表示。 + */ + export const hashCode = (value: any): string => { + let hash = 0; + const str = JSON.stringify(value); // 将对象转换为字符串 + if (str.length === 0) return hash.toString(); + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = (hash << 5) - hash + char; + hash |= 0; // 将hash转换为32位整数 + } + return hash.toString(); +}; + + +/** + * 查找并返回数组中最长的字符串。 + * 如果数组为空,返回`undefined`。 + * 如果有多个最长的字符串,返回第一个遇到的。 + * + * @param arr - 一个字符串数组。 + * @returns 返回数组中最长的字符串,或者在数组为空时返回`undefined`。 + */ +export const findLongestString = (arr: string[]): string | undefined => { + if (arr.length === 0) return undefined; + return arr.reduce((longest, current) => { + return current.length > longest.length ? current : longest; + }); +}; + +/** + * 计算两个时间之间的时间差 多少天时分秒 + * @param {number} startTime 开始时间 + * @param {number} endTime 结束时间 + * @return {string} days hours 计算出相差天数 计算出小时数 +*/ +export const intervalTime = (startTime: number, endTime: number) => { + // 开始时间 + const date1 = startTime / 1000; + // 结束时间 + const date2 = endTime / 1000; + // 时间差的毫秒数 + const date3 = (date2- date1) * 1000; + // 计算出相差天数 + const days = Math.floor(date3 / (24 * 3600 * 1000)); + // 计算出小时数 + // 计算天数后剩余的毫秒数 + const leave1 = date3 % (24 * 3600 * 1000); + const hours = Math.floor(leave1 / (3600 * 1000)); + return { + days, + hours + } +} + +/** + * 获取日期时分 + * @return {string} xxx 月-日-时分 +*/ +export const getMonthHoursMinutes = (params: T): string => { + if ([undefined, null].includes((params as undefined))) return '--'; + const newParams: number = (params as number) * 1000; + // const year: number = new Date(newParams).getFullYear(); + const month: number = new Date(newParams).getMonth() + 1; + const day: number = new Date(newParams).getDate(); + const hours: number = new Date(newParams).getHours(); + const minutes: number = new Date(newParams).getMinutes(); + // const mill: number = new Date(newParams).getSeconds(); + return `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes} ${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}` +}; +export function arrayToStringWithPlus(arr: any[]): string { + return arr.join(' + '); +} + +export function joinObjectKeyValues(array: T[] | undefined, key: keyof T): string { + // 如果数组是undefined或空数组,返回空字符串 + if (!array || array.length === 0) { + return ''; + } + return array.map(item => String(item[key])).join('+'); + } \ No newline at end of file diff --git a/bmp-console-web/src/utils/regular.ts b/bmp-console-web/src/utils/regular.ts new file mode 100644 index 0000000..c1c74d5 --- /dev/null +++ b/bmp-console-web/src/utils/regular.ts @@ -0,0 +1,64 @@ +/** + * 中国大陆手机号正则 +*/ +export const phoneReg: RegExp = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/; + +/** + * 中国香港手机号正则 +*/ +export const hongKongPhoneReg: RegExp = /^([5|6|9])\d{7}$/; + +/** + * 中国澳门手机号正则 +*/ +export const aOmenPhoneReg: RegExp = /^6\d{7}$/; + +/** + * 中国台湾手机号正则 +*/ +export const taiWanPhoneReg: RegExp = /^[0][9]\d{8}$/; + +/** + * 其他国家手机号正则 +*/ +export const otherPhoneReg: RegExp = /^\d*$/; + +/** + * 邮箱正则 +*/ +export const emailReg: RegExp = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + +/** + * 密码正则 + */ +export const passwordReg: RegExp = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[\d\*\(\)`~!@#\$%&_\-+=\|\{\}\[\]:\";\'<>,.\?\/\)])[a-zA-Z\d\*\(\)`~!@#\$%&_\-+=\|\{\}\[\]:\";\'<>,.\?\/\)]{8,30}$/; + +/** + * 用户名正则 +*/ +export const userNameReg: RegExp = /^[-0-9a-zA-Z_]{1,64}$/; + +/** + * 用户名正则 +*/ +export const projectNameReg: RegExp = /^[-0-9a-zA-Z\u4e00-\u9fa5_]{1,64}$/; + +/** + * 实例名称正则 +*/ +export const instanceNameReg: RegExp = /^[a-zA-Z\u4e00-\u9fa5]([0-9a-zA-Z\u4e00-\u9fa5-_.:]{1,127})$/; + +/** + * host名称正则 +*/ +export const hostNameReg: RegExp = /(^((?!(^-)|(-$)|(--+)|(^\\.)|(\\.$)|(\\.\\.+))[0-9A-Za-z-.]){2,64}$)|(^\s*$)/; + +/** + * 规则名阈值正则 +*/ +export const ruleThresholdReg: RegExp = /^(0|[1-9]\d*)(\.\d{1,2})?$/; + +/** + * 规则名阈值%正则 +*/ +export const ruleThresholdPrecentReg: RegExp = /^(100(\.0+)?|[0-9]{1,2}(\.\d+)?)$/; diff --git a/bmp-console-web/src/views/AlarmHistory/alarmHistory.scss b/bmp-console-web/src/views/AlarmHistory/alarmHistory.scss new file mode 100644 index 0000000..3e47362 --- /dev/null +++ b/bmp-console-web/src/views/AlarmHistory/alarmHistory.scss @@ -0,0 +1,36 @@ +.alarm-history-list { + .operation-search { + margin-left: 30px; + height: 30px; + .el-date-editor { + width: 260px; + .el-range-input { + font-size: 12px; + } + } + .alarm-history-search-button { + margin-left: 20px; + display: inline-block; + vertical-align: bottom; + .el-button { + font-size: 12px; + } + } + } +} + +.long-instance-name { + font-size: 12px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + float: center; + cursor: pointer; + color: #108ef9; + +} + +.search-result { + font-size: 12px; + margin-bottom: 10px; +} \ No newline at end of file diff --git a/bmp-console-web/src/views/AlarmHistory/alarmHistory.vue b/bmp-console-web/src/views/AlarmHistory/alarmHistory.vue new file mode 100644 index 0000000..b2835a1 --- /dev/null +++ b/bmp-console-web/src/views/AlarmHistory/alarmHistory.vue @@ -0,0 +1,574 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/views/AlarmRuleCreate/alarmRuleCreate.scss b/bmp-console-web/src/views/AlarmRuleCreate/alarmRuleCreate.scss new file mode 100644 index 0000000..73df86e --- /dev/null +++ b/bmp-console-web/src/views/AlarmRuleCreate/alarmRuleCreate.scss @@ -0,0 +1,228 @@ +.alarm-rule-create .el-form-item { + margin-left: 0px; + margin-bottom: 16px; +} + + +.alarm-form-content { + margin-left: 37px; + margin-bottom: 30px; + .el-form-item__label { + font-weight: bold; + font-size: 12px; + } + .el-form-item { + .el-form-item__content { + .el-input { + width: 500px; + height: 36px; + .el-input__inner { + height: 36px; + line-height: 36px + } + } + .el-radio__label { + font-size: 12px; + } + .el-checkbox__inner { + width: 12px; + height: 12px; + } + .el-checkbox__label { + font-size: 12px; + } + + } + } + //确认按钮样式 + .create-confirm { + margin-left: 30%; + .create-confirm-button { + font-size: 12px; + margin-right: 20px; + width: 150px; + height: 36px; + + &.is-disabled { + background-color: #BCBCBC!important; + border-color: #BCBCBC !important; + &:hover { + background-color: #BCBCBC!important; + border-color: #BCBCBC !important; + } + } + + &:hover { + background-color: #108EF9 !important; + border-color: #108EF9 !important; + } + } + + .cancel-button { + background-color: #EEEEEE; + border-color: #EEEEEE; + color: #666666; + &:active { + background-color: #DFDFDF !important; + border-color: #DFDFDF !important; + } + &:hover { + background-color: #EEEEEE !important; + border-color: #EEEEEE !important; + } + } + } + +} + +.instance-content { + .instance-message-list-input { + .el-input__inner { + border-radius: 0; + border-top: none; + border-left: none; + border-right: none; + } + + } + .el-checkbox__inner { + width: 12px; + height: 12px; + } + .el-table tr { + height: 30px; + } + + .el-table__row { + height: 30px; + } +} + +.choose-instance-name { + .el-tag { + padding: 12px; + .el-select__tags-text { + height: 16px; + } + } +} + +.trigger-card { + width: 1020px; + margin-bottom: 20px; + .el-card__body { + padding: 16px 0 0 20px; + } + &:hover { + border-color: #108EF9; + } + .trigger-close-button { + width: 16px; + height: 16px; + font-size: 18px; + color: #979797; + position: absolute; + border: none; + left: 1070px; + margin-top: -25px; + &:hover { + color: #108EF9; + } + } +} + +.trigger-condition-content { + .long150 .el-input { + width: 150px !important; + height: 30px; + margin-right: 16px; + .el-input__inner { + height: 30px; + line-height: 30px + } + } + .long100 .el-input { + width: 100px !important; + height: 30px; + margin-right: 16px; + .el-input__inner { + height: 30px; + line-height: 30px + } + } + .long90 .el-input { + width: 90px !important; + height: 30px; + margin-right: 16px; + .el-input__inner { + height: 30px; + line-height: 30px + } + } + .threshold-content { + display:inline-block; + margin-right: 8px; + .el-input { + width: 90px !important; + height: 30px; + .el-input__inner { + height: 30px; + line-height: 30px + } + } + .el-form-item__error { + white-space: nowrap; + } + } + .threshold-en-content { + display:inline-block; + margin-right: 8px; + .el-input { + width: 90px !important; + height: 30px; + .el-input__inner { + height: 30px; + line-height: 30px + } + } + .el-form-item__error { + white-space: pre-line; + width: 350px; + } + } + .calculation-unit { + font-size: 12px; + margin-right: 16px; + } +} +.trigger-button { + margin: 0 0 32px 0; +} + +.contact-content { + width: 775px; + margin: 0 0 0 150px !important; + +} + +.trigger-button-content { + font-size: 12px; +} + +.create-key-tip { + margin-top: 10px; + font-size: 12px; + color: #333333; +} + +.notice-period-tip { + font-size: 12px; + color: #999999; + width: 600px; +} +.no-requrie-label { + margin-left: 10px !important; + .el-form-item__label { + width: 140px !important; + } +} \ No newline at end of file diff --git a/bmp-console-web/src/views/AlarmRuleCreate/alarmRuleCreate.vue b/bmp-console-web/src/views/AlarmRuleCreate/alarmRuleCreate.vue new file mode 100644 index 0000000..948dd12 --- /dev/null +++ b/bmp-console-web/src/views/AlarmRuleCreate/alarmRuleCreate.vue @@ -0,0 +1,1254 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/views/AlarmRuleDetail/alarmRuleDetail.scss b/bmp-console-web/src/views/AlarmRuleDetail/alarmRuleDetail.scss new file mode 100644 index 0000000..a426955 --- /dev/null +++ b/bmp-console-web/src/views/AlarmRuleDetail/alarmRuleDetail.scss @@ -0,0 +1,155 @@ +.operation-position{ + float: right; + .active-operate { + margin-top: 2px; + .el-button--primary { + background: none; + color: #108EE9; + font-size: 12px; + height: 28px; + border-radius: 14px; + border-color: #108EE9; + margin: 0 20px; + + + } + } + .inactive-operate { + margin-top: 2px; + .el-button--primary { + background: none; + color: #333333; + font-size: 12px; + height: 28px; + border-radius: 14px; + border-color: #333333; + margin: 0 20px; + &:hover { + color: #108EE9; + border-color: #108EE9; + } + } + } +} + +.success { + color: #43B561 !important; +} +.info { + color: #999999 !important; +} +.intermediate { + color:#9254DE !important +} +.danger { + color:#ff4d4f !important +} +.long-name { + font-size: 12px; + overflow: hidden; + text-overflow: ellipsis; + max-width: 250px; + white-space: nowrap; + float: left; +} + +.long-name-title { + overflow: hidden; + text-overflow: ellipsis; + max-width: 180px; + white-space: nowrap; +} + +.desc-type { + width: 16px; + margin-left: 5px; +} + +.back-button { + color: #666666; + margin-left: 32px; + span { + margin-left: 10px !important; + } + +} + +.operate-btn { + width: 80px; + color: #333333; + font-size: 12px; +} + +.desc-tooltip-popper { + max-width: 300px; +} + +.alarm-detail-content { + padding-top: 0 !important; + .el-tabs { + border: none; + margin: 10px; + padding: 20px; + min-height: calc(100vh - 160px); + box-shadow: none; + } + .tab-info { + .el-tabs__active-bar { + background: #108ef9; + } + + .el-tabs__header { + background-color: #fff; + margin-bottom: 28px; + } + + .el-tabs__content { + padding: 0; + } + .el-tabs__item { + font-size: 14px; + color: #333; + font-weight: 400; + padding: 0 25px; + + &:hover { + color: #108ef9; + } + // text-align: center; + // margin: 0; + // margin-right: 34px; + // margin-right: 17px; + } + + .el-tabs__nav-wrap::after { + height: 1px !important; + } + + .el-tabs__item.is-active { + color: #108ef9; + font-weight: 400; + border-right-color: #fff; + border-left-color: #fff; + border-bottom-color: #108ef9; + } + + + .el-tabs__nav-wrap { + &::after { + background: #f0f0f0; + } + } + } +} + +.triggering-condition-detail { + font-size: 12px; + margin-left: 22px; + line-height: 36px; + .el-tag { + border-radius: 5px; + padding: 0 9px; + height: 24px; + --el-icon-size: 14px; + } +} \ No newline at end of file diff --git a/bmp-console-web/src/views/AlarmRuleDetail/alarmRuleDetail.vue b/bmp-console-web/src/views/AlarmRuleDetail/alarmRuleDetail.vue new file mode 100644 index 0000000..fe311aa --- /dev/null +++ b/bmp-console-web/src/views/AlarmRuleDetail/alarmRuleDetail.vue @@ -0,0 +1,950 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/views/AlarmRuleList/alarmRuleList.scss b/bmp-console-web/src/views/AlarmRuleList/alarmRuleList.scss new file mode 100644 index 0000000..be50a75 --- /dev/null +++ b/bmp-console-web/src/views/AlarmRuleList/alarmRuleList.scss @@ -0,0 +1,42 @@ +.alarm-rule-list { + .one-line-drop { + margin-left: 5px; + margin-right: 5px; + display: inline-block; + } +} + +.long-instance-name { + font-size: 12px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + float: center; + cursor: pointer; + color: #108ef9; + +} +.triggering-condition-row { + font-size: 12px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.success { + color: #43B561 !important; +} +.info { + color: #999999 !important; +} +.intermediate { + color:#9254DE !important +} +.danger { + color:#ff4d4f !important +} + +.search-result { + font-size: 12px; + margin-bottom: 10px; +} \ No newline at end of file diff --git a/bmp-console-web/src/views/AlarmRuleList/alarmRuleList.vue b/bmp-console-web/src/views/AlarmRuleList/alarmRuleList.vue new file mode 100644 index 0000000..0e78691 --- /dev/null +++ b/bmp-console-web/src/views/AlarmRuleList/alarmRuleList.vue @@ -0,0 +1,1056 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/views/InstanceCreate/instanceCreate.scss b/bmp-console-web/src/views/InstanceCreate/instanceCreate.scss new file mode 100644 index 0000000..5835b07 --- /dev/null +++ b/bmp-console-web/src/views/InstanceCreate/instanceCreate.scss @@ -0,0 +1,980 @@ +.pt0 { + padding-top: 0 !important; +} + +.instance-create .el-form-item { + margin-left: 0px; + margin-bottom: 20px; + .el-checkbox__inner { + width: 12px; + height: 12px; + } +} + +// 关于表单样式 +.form-content { + margin-left: 37px; + margin-bottom: 30px; + .el-form-item__label { + font-weight: bold; + font-size: 12px; + } + + .el-radio-button { + margin-right: 30px; + + } + .el-carousel__item.is-active { + .el-radio-button { + .el-radio-button__inner { + border-left-color: #979797 !important; + &:hover { + border-left-color: #108EF9 !important; + color:#108EF9 + } + } + &.is-active { + .el-radio-button__inner { + border-left: 1px solid #108EF9 !important; + } + } + &.is-disabled{ + .el-radio-button__inner { + border-color: #666666 !important; + &:hover { + border-left-color: #666666 !important; + color:#666666 + } + } + } + } + } + + .el-radio-button { + .el-radio-button__inner { + font-size: 12px; + min-width: 110px; + height: 36px; + padding: 10px 15px; + border-left-color: #979797 !important; + border-radius: 5px; + + &:hover { + border-left-color: #108EF9 !important; + } + + } + + &.is-disabled { + .el-radio-button__inner { + font-size: 12px; + min-width: 110px; + height: 36px; + border-left-color:#979797 !important; + border-radius: 5px; + + &:hover { + border-left-color: #666666 !important; + } + + } + } + + &.is-active { + .el-radio-button__inner { + font-size: 12px; + min-width: 110px; + height: 36px; + border-left-color: #108EF9 !important; + border-radius: 5px; + + &:hover { + border-left-color:#108EF9 !important; + } + + } + } + } + + .el-radio-button :hover .model-picture-grey{ + border-color: #108EF9; + -webkit-filter: grayscale(0%); + /* Chrome, Safari, Opera */ + filter: grayscale(0%); + } + + .el-radio-button.is-active { + border-color: #108EF9; + .model-picture-grey{ + -webkit-filter: grayscale(0%); + /* Chrome, Safari, Opera */ + filter: grayscale(0%); + } + .divider-line { + border-top: 1px solid #108EF9; + } + + } + + .el-radio-button.is-active.is-disabled{ + border-color: #666666; + .model-picture-grey{ + -webkit-filter: grayscale(100%); + /* Chrome, Safari, Opera */ + filter: grayscale(100%); + } + .divider-line { + border-top: 1px solid #666666 ; + } + + } + + .el-radio-button.is-disabled{ + border-color: #666666; + .model-picture-grey{ + -webkit-filter: grayscale(80%); + /* Chrome, Safari, Opera */ + filter: grayscale(80%); + } + .divider-line { + border-top: 1px solid #979797; + } + + } + + // 机型选择hover时,边框图形变蓝 + .el-radio-button :hover .divider-line{ + border-color: #108EF9; + } + + // 机型选择hover时,disable边框图形不变蓝 + .el-radio-button.is-disabled :hover .divider-line{ + border-color: #666666 !important; + } + + // 机型选择hover时,边框图形变蓝 + .el-radio-button :hover .raid-down{ + border-color: #108EF9; + } + + .el-radio-button:first-child .el-radio-button__inner { + border-radius: 5px; + } + + .el-radio-button:last-child .el-radio-button__inner { + border-radius: 5px; + } + + .lh90 .el-form-item__label{ + line-height: 90px; + } + + .lh60 .el-form-item__label{ + line-height: 60px; + } + + .system-partition-label .el-form-item__label{ + margin-top: 30px; + line-height: 18px; + } + + .empty-system-partition-label .el-form-item__label{ + line-height: 18px; + } + + .password-label .el-form-item__label{ + line-height: 18px; + } + + .h240 { + height: 240px; + } + .h265 { + height: 265px; + } + + // 机型选择中机型样式 + .model-content { + display: flex; + width: 100%; + overflow-x: auto; + scrollbar-width: none;/* firefox */ + -ms-overflow-style: none; /* IE 10+ */ + + .el-carousel{ + width: 1094px; + --el-carousel-arrow-background:white; + --el-carousel-arrow-hover-background:#108EF9; + --el-carousel-indicator-width:20px; + --el-carousel-indicator-height:3px; + --el-carousel-indicator-out-color:#108EF9; + } + .el-radio-button { + border-radius: 50px; + margin-right: 30px; + } + .el-carousel__container { + height: 220px; + .el-carousel__item { + left:0 + } + } + .el-carousel__indicators--outside { + margin-right: -80px; + } + + .indicators-none { + .el-carousel__indicators { + display: none; + } + .el-carousel__arrow--left { + display: none; + } + .el-carousel__arrow--right { + display: none; + } + } + + .indicators-none-left { + .el-carousel__arrow--left { + display: none; + } + } + + .indicators-none-right { + .el-carousel__arrow--right { + display: none; + } + } + + .el-carousel__item { + margin-left: 110px; + } + + .el-carousel__arrow--left { + margin-left: 38px; + } + .el-carousel__arrow--right { + margin-right: 0; + } + + .el-carousel__arrow { + width: 29px; + height: 29px; + font-size: 16px; + color: #979797; + border: 1px solid #979797; + .el-icon { + margin-top: 3px; + } + &:hover { + background-color: #EEEEEE; + } + + } + + .el-radio-button { + width: 205px; + height: 210px; + font-size: 14px !important; + &.is-active { + .el-radio-button__inner { + color: #108EF9; + } + } + .el-radio-button__inner { + width: 205px; + height: 210px !important; + background:white; + color: #979797; + font-size: 14px !important; + border-radius:5px !important + } + &.is-disabled { + .el-radio-button__inner { + color: #979797 !important; + } + + &.is-active { + .el-radio-button__inner { + color: #666666 !important; + } + } + } + } + + .raid-down { + border: none; + font-size: 12px; + border-radius:0 0 5px 5px; + margin: 10px 0 0 -16px; + padding: 0 10px 0 10px; + width: 183px; + line-height: 12px; + color: #666666; + } + + .divider-line { + padding-top: 5px; + border-top: 1px solid #979797; + text-align: left; + } + } + // 隐藏滚动条 + .model-content::-webkit-scrollbar { + display: none; /* Chrome Safari */ + } + + .model-picture-grey { + -webkit-filter: grayscale(100%); + /* Chrome, Safari, Opera */ + filter: grayscale(100%); + } + + .model-tick { + margin-left: 179px; + } + + .model-soldout { + position: absolute; + margin-left: 154px; + margin-top: -29px; + font-size: 40px; + height: 40px; + + } + + .arrow-left-position { + margin: 80px 0 0 -40px; + position: absolute; + display: inline; + } + + .arrow-right-position { + margin: 80px 0 0 91%; + position: absolute; + display: inline; + } + // 镜像类型样式 + .image-content { + width: 1004px; + overflow: hidden; + transition: max-height .8s; + .el-carousel{ + width: 100%; + --el-carousel-arrow-background:white; + --el-carousel-arrow-hover-background:#108EF9; + --el-carousel-indicator-width:20px; + --el-carousel-indicator-height:3px; + --el-carousel-indicator-out-color:#108EF9; + } + + .el-radio-button { + border-radius: 50px; + margin-right: 30px; + } + + .el-carousel__container { + margin-left: 110px; + height: 70px; + + } + + .el-carousel__indicators--outside { + margin-right: -80px; + } + + .indicators-none { + .el-carousel__indicators { + display: none; + } + .el-carousel__arrow--left { + display: none; + } + .el-carousel__arrow--right { + display: none; + } + } + + .indicators-none-left { + .el-carousel__arrow--left { + display: none; + } + } + + .indicators-none-right { + .el-carousel__arrow--right { + display: none; + } + } + + .el-carousel__arrow--left { + margin-top: -4px; + left: -42px; + } + .el-carousel__arrow--right { + margin-top: -4px; + margin-right: -15px; + } + + .el-carousel__arrow { + width: 29px; + height: 29px; + font-size: 16px; + color: #979797; + border: 1px solid #979797; + .el-icon { + margin-top: 3px; + } + &:hover { + background-color: #EEEEEE; + } + + } + + .el-radio-button { + width: 240px; + height: 62px !important; + } + + .el-radio-button__inner { + width: 240px; + padding: 15px 15px 10px 15px; + height: 62px !important; + background:white; + text-align: left; + color: #666666; + + } + .el-select .el-input { + display: flex; + width: 170px; + } + + .icon-size { + width: 35px; + height: 35px; + } + + .inline-position { + margin: 0 10px 0 0; + float: left; + } + + .el-input__inner { + max-width: 148px; + overflow: hidden; + text-overflow: ellipsis; + border: none; + padding: 0; + } + } + + .image-tick { + position: absolute; + height: 14px; + margin-top: -6px; + margin-left: 208px; + } + + .arrow-text { + position: absolute; + width: 29px; + height: 29px; + top: 16px; + left: 830px; + color: #999999; + border-color: #999999; + &:hover { + color: #FFFFFF; + border-color: #108EF9; + background-color: #108EF9; + } + &:active { + color: #FFFFFF; + border-color: #108EF9; + background-color: #108EF9; + } + } + + // 系统盘样式 + .system-raid-content { + .el-radio-button { + width: 150px; + height: 90px; + margin-right: 30px; + } + + .el-radio-button__inner { + width: 150px !important; + height: 25px !important; + padding: 5px 5px 10px 5px !important; + font-weight: 600 !important; + border-radius:5px 5px 0 0 !important + } + .system-down { + border: 1px solid #979797; + border-top: none; + border-radius:0 0 5px 5px; + margin: 7px 0 0 -5.8px; + padding: 15px 10px 0 10px; + width: 128.4px; + color: #333333; + } + .system-down-active { + border: 1px solid #108EF9; + border-top: none; + border-radius:0 0 5px 5px; + margin: 7px 0 0 -5.8px; + padding: 15px 10px 0 10px; + width: 128.4px; + color: #333333; + } + } + + .raid-tick { + margin-left: 123px; + } + + .instance-message { + .el-input { + width: 340px; + } + } + + // 系统盘分区样式 + .chamfer-position { + margin-right: 30px; + } + + .chamfer { + width:70px; + height:90px; + padding: 1px; + background: + linear-gradient(-135deg, transparent 20px, #979797 0) top right, ; + background-repeat: no-repeat; + border-radius: 5px; + font-size: 12px; + } + .chamfer-inner { + width: 100%; + height: 100%; + background: + linear-gradient(-135deg, transparent 20px, white 0) top right, ; + background-repeat: no-repeat; + border-radius: 5px; + } + + .chamfer-up { + margin-left: 5px; + width: 60px; + border-bottom: 1px solid #979797 ; + } + + .chamfer-down { + width: 60px; + margin: 5px 5px 0px 5px; + line-height:18px; + text-align: center; + } + + .password-size { + .el-radio { + .el-radio__label { + font-size: 12px; + } + } + } + + //确认按钮样式 + .create-confirm { + margin-left: 30%; + .create-confirm-button { + font-size: 12px; + margin-right: 20px; + width: 150px; + height: 36px; + + &.is-disabled { + background-color: #BCBCBC!important; + border-color: #BCBCBC !important; + &:hover { + background-color: #BCBCBC!important; + border-color: #BCBCBC !important; + } + } + + &:hover { + background-color: #108EF9 !important; + border-color: #108EF9 !important; + } + } + + .cancel-button { + background-color: #EEEEEE; + border-color: #EEEEEE; + color: #666666; + &:active { + background-color: #DFDFDF !important; + border-color: #DFDFDF !important; + } + &:hover { + background-color: #EEEEEE !important; + border-color: #EEEEEE !important; + } + } + } + +} + +.long-volume { + font-weight: 400; + margin-bottom: 10px; + overflow: hidden; + text-overflow: ellipsis; + max-width: 150px; + white-space: nowrap; +} + +.long-system-detail { + font-weight: 400; + margin: 10px 0; + overflow: hidden; + text-overflow: ellipsis; + max-width: 150px; + white-space: nowrap; +} + +.long-item { + overflow: hidden; + text-overflow: ellipsis; + max-width: 200px; + white-space: nowrap; + margin: 12px 0; +} + +.long-device-item { + overflow: hidden; + text-overflow: ellipsis; + max-width: 200px; + white-space: nowrap; +} + +.long-name-title { + overflow: hidden; + text-overflow: ellipsis; + max-width: 180px; + white-space: nowrap; +} +.display-block { + .el-form-item__content { + position: absolute; + display: inline-block; + } + +} + +.create-key-tip { + width: 631px; + text-align: center; + margin-top: 10px; + font-size: 12px; + color: #333333; +} + +.lh36 { + .el-form-item__label { + line-height: 36px; + } +} + +.password-tip { + font-size: 12px; + color: #999999; + width: 550px; +} + +.download-monitorAgent-conetnt { + .el-checkbox__label { + font-size: 12px; + } + + .el-checkbox__input.is-checked+.el-checkbox__label { + color: #333333; + } +} + +.disabled-input-number { + .el-form-item__content { + .el-input-number { + + .el-input-number__increase { + width: 33px; + background: #eee; + font-size: 14px; + font-weight: 400; + + &:hover { + top: 1px; + bottom: 1px; + right: 1px; + + i { + width: 16px; + height: 16px; + background: url('~@/assets/img/add-default.png') no-repeat center center; + background-size: 100% auto; + svg { + display: none; + } + } + } + + &:hover, + &:active { + background: #eee; + } + + i { + width: 16px; + height: 16px; + background: url('~@/assets/img/add-default.png') no-repeat center center; + background-size: 100% auto; + + svg { + display: none; + } + } + } + + } + } +} + +.change-input-number { + .el-form-item__content { + .el-input-number { + .el-input-number__increase { + width: 33px; + color: #666; + background: #fff; + border-left: .53px solid #979797; + + &:hover { + top: 0px; + bottom: 0px; + right: 0px; + + i { + width: 16px; + height: 16px; + background: url('~@/assets/img/add-hover-active.png') no-repeat center center; + background-size: 100% auto; + svg { + display: none; + } + } + } + + &:hover{ + background: #108ee9; + } + &:active { + background: #0f81d4; + } + + i { + width: 16px; + height: 16px; + background: url('~@/assets/img/add-default.png') no-repeat center center; + background-size: 100% auto; + + svg { + display: none; + } + } + } + + .el-input-number__decrease { + background: #fff; + width: 33px; + color: #666; + border-right: 0.53px solid #979797; + + + + i { + width: 16px; + height: 16px; + background: url('~@/assets/img/reduce-default.png') no-repeat center center; + background-size: 100% auto; + + svg { + display: none; + } + } + + &:hover { + background: #108ee9; + top: 0; + bottom: 0; + left: 0; + + i { + width: 16px; + height: 16px; + background: url('~@/assets/img/reduce-hover.png') no-repeat center center; + background-size: 100% auto; + + svg { + display: none; + } + } + } + + &:active { + background: #0f81d4; + } + } + } + } +} + + +.change-input-number { + .el-form-item__content { + .el-input-number { + width: 100px !important; + + &:hover { + border-color: #0f8fe9; + } + + .el-input-number__decrease.is-disabled { + width: 33px; + background: #eee !important; + font-size: 14px; + font-weight: 400; + border-right: 0.53px solid #c7c7c7; + + &:hover { + top: 1px; + bottom: 1px; + left: 1px; + + i { + width: 16px !important; + height: 16px !important; + background: url('~@/assets/img/reduce-grey.png') no-repeat center center !important; + background-size: 100% auto !important; + + svg { + display: none !important; + } + } + } + + i { + width: 16px; + height: 16px; + background: url('~@/assets/img/reduce-grey.png') no-repeat center center; + background-size: 100% auto; + + svg { + display: none; + } + } + } + + .el-input-number__increase.is-disabled { + width: 33px; + background: #eee !important; + font-size: 14px; + font-weight: 400; + border-right: 0.53px solid #c7c7c7; + right: 0.1px; + &:hover { + top: 1px; + bottom: 1px; + right: 0.1pxpx; + + i { + width: 16px !important; + height: 16px !important; + background: url('~@/assets/img/add-default.png') no-repeat center center !important; + background-size: 100% auto !important; + + svg { + display: none !important; + } + } + } + + i { + width: 16px; + height: 16px; + background: url('~@/assets/img/add-default.png') no-repeat center center; + background-size: 100% auto; + + svg { + display: none; + } + } + } + + + + input { + width: 100%; + height: 34px; + background: #fff; + border: 0.53px solid #979797; + padding: 0 5px 0 8px; + color: #666; + + &:focus { + border-color: #0f8fe9; + } + } + } + } +} + +.back-btn { + color: #666666; + padding-top: 6px; + margin-left: 32px; +} + +.textarea-label1 { + margin-bottom: 30px !important; +} + +.image-select-count { + .el-input__suffix { + .el-input__suffix-inner { + i { + svg { + color: #333; + margin-top: -3px; + } + } + } + } +} + +.refresh-img { + margin-left: 5px; + margin-top: 2px; + width:12px; + height: 12px; + cursor: pointer; +} + +.tooltip-img { + width: 16px; + height: 16px; + margin-top: 2px; + margin-left: 5px; +} diff --git a/bmp-console-web/src/views/InstanceCreate/instanceCreate.vue b/bmp-console-web/src/views/InstanceCreate/instanceCreate.vue new file mode 100644 index 0000000..3c3af6d --- /dev/null +++ b/bmp-console-web/src/views/InstanceCreate/instanceCreate.vue @@ -0,0 +1,1828 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/views/InstanceDetail/instanceDetail.scss b/bmp-console-web/src/views/InstanceDetail/instanceDetail.scss new file mode 100644 index 0000000..f157984 --- /dev/null +++ b/bmp-console-web/src/views/InstanceDetail/instanceDetail.scss @@ -0,0 +1,193 @@ +.pt0 { + padding-top: 0 !important; +} + +.mlr0 { + margin-left: 0 !important; + margin-right: 0 !important; +} +.operation-search-content { + display: flex; + height: 50px; + justify-content: space-between; + .operation-search-items{ + display: flex; + .operation-search-item { + margin-right: 62px; + .el-input { + width: 160px; + font-size: 12px; + } + .el-date-editor { + width: 260px; + .el-range-input { + font-size: 12px; + } + } + .operation-name { + font-size: 12px; + margin-right: 10px; + } + .operation-name-date { + font-size: 12px; + margin-right: 10px; + vertical-align: text-top; + } + } + } + + .operation-search-button { + .el-button { + width: 70px; + font-size: 12px; + } + } +} + +.operation-position{ + float: right; + .active-operate { + margin-top: 2px; + .el-button--primary { + background: none; + color: #108EE9; + font-size: 12px; + height: 28px; + border-radius: 14px; + border-color: #108EE9; + margin: 0 20px; + + + } + } + .inactive-operate { + margin-top: 2px; + .el-button--primary { + background: none; + color: #333333; + font-size: 12px; + height: 28px; + border-radius: 14px; + border-color: #333333; + margin: 0 20px; + &:hover { + color: #108EE9; + border-color: #108EE9; + } + } + } +} + +.success { + color: #43B561 !important; +} +.info { + color: #999999 !important; +} +.intermediate { + color:#9254DE !important +} +.danger { + color:#ff4d4f !important +} +.long-name { + font-size: 12px; + overflow: hidden; + text-overflow: ellipsis; + max-width: 260px; + white-space: nowrap; + float: left; +} + +.long-name-title { + overflow: hidden; + text-overflow: ellipsis; + max-width: 180px; + white-space: nowrap; +} + +.desc-type { + width: 16px; + margin-left: 5px; +} + +.back-button { + color: #666666; + margin-left: 32px; + span { + margin-left: 10px !important; + } + +} + +.operate-btn { + width: 80px; + color: #333333; + font-size: 12px; +} + +.desc-tooltip-popper { + max-width: 300px; +} + +.instance-detail-content { + padding-top: 0 !important; + .el-tabs { + border: none; + margin: 10px; + padding: 20px; + min-height: calc(100vh - 160px); + box-shadow: none; + } + .instance-tab-info { + .el-tabs__active-bar { + background: #108ef9; + } + + .el-tabs__header { + background-color: #fff; + margin-bottom: 28px; + } + + .el-tabs__content { + padding: 0; + } + .el-tabs__item { + font-size: 14px; + color: #333; + font-weight: 400; + padding: 0 25px !important; + + &:hover { + color: #108ef9; + } + // text-align: center; + // margin: 0; + // margin-right: 34px; + // margin-right: 17px; + } + + .el-tabs__nav-wrap::after { + height: 1px !important; + } + + .el-tabs__item.is-active { + color: #108ef9; + font-weight: 400; + border-right-color: #fff; + border-left-color: #fff; + border-bottom-color: #108ef9; + } + + + .el-tabs__nav-wrap { + &::after { + background: #f0f0f0; + } + } + } +} + +.setting-content { + height: 28px; +} diff --git a/bmp-console-web/src/views/InstanceDetail/instanceDetail.vue b/bmp-console-web/src/views/InstanceDetail/instanceDetail.vue new file mode 100644 index 0000000..1a8537d --- /dev/null +++ b/bmp-console-web/src/views/InstanceDetail/instanceDetail.vue @@ -0,0 +1,2136 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/views/InstanceList/instanceList.scss b/bmp-console-web/src/views/InstanceList/instanceList.scss new file mode 100644 index 0000000..47a2c12 --- /dev/null +++ b/bmp-console-web/src/views/InstanceList/instanceList.scss @@ -0,0 +1,140 @@ +.instance-list { + .instance-name-height { + margin: 4px 0; + height: 50px; + .el-button { + height: 22px; + } + } +} + +.el-checkbox__inner { + width: 10px; + height: 10px; + margin-top: 1px; + border-radius: 2px; + border: 1px solid #333; + + &:hover, + &:focus, + &:active { + border-color: #108EF9 !important; + } + + &::after { + height: 5px; + left: 2px; + top: 0px; + } +} + +.long-instance-name { + font-size: 12px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + float: center; + cursor: pointer; + color: #108ef9; + +} + +.search-result { + font-size: 12px; + margin-bottom: 10px; +} + +.warning-tip { + width: 16px; + height: 16px; + position:absolute; + cursor: pointer; +} +.change-show-style { + cursor: pointer; +} +.one-line-drop { + margin-left: 5px; + margin-right: 5px; + display: inline-block; +} +.disabled-currency-style { + cursor: no-drop; + color: #999999 !important; +} + +.no-click { + color: #999999 !important; + cursor: no-drop; +} +.can-click { + color: #333333 !important; + cursor: pointer; +} + + + +.tag-content { + .el-tag__content { + display: contents; + .is-loading { + margin-left: 3px; + cursor: auto; + font-size: calc(var(--el-icon-size) - 2px) !important; + animation: rotating 2s linear infinite; + } + } + +} +.no-data-jump { + width: 100%; + text-align: center; +} + +.el-table__empty-text { + width: 100%; +} + +.batch-operate { + display: inline-block; + margin-left: 50px; + margin-top: 8px; + .el-checkbox { + margin-right: 30px; + height: 24px; + vertical-align: middle; + } + .el-button { + &--primary { + min-width: 50px; + height: 24px; + font-size: 12px; + margin-right: 10px; + --el-button-bg-color: #108ee9 !important; + --el-button-text-color: #fff; + + &:focus, + &:hover { + --el-button-hover-bg-color: #108ee9 !important; + --el-button-hover-text-color: #fff; + } + + &:active { + --el-button-active-bg-color: #0f81d4 !important; + } + --el-button-disabled-bg-color: #91D5FF !important; + --el-button-disabled-border-color: #91D5FF !important; + } + } + + .batch-drop-down { + display: inline-block; + vertical-align: middle; + } +} + +.page-change { + display: inline-block; + float: right; + margin-right: 50px; +} \ No newline at end of file diff --git a/bmp-console-web/src/views/InstanceList/instanceList.vue b/bmp-console-web/src/views/InstanceList/instanceList.vue new file mode 100644 index 0000000..f648710 --- /dev/null +++ b/bmp-console-web/src/views/InstanceList/instanceList.vue @@ -0,0 +1,1889 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/views/Login/login.scss b/bmp-console-web/src/views/Login/login.scss new file mode 100644 index 0000000..51c5650 --- /dev/null +++ b/bmp-console-web/src/views/Login/login.scss @@ -0,0 +1,133 @@ +.operate-content { + width: 100%; + height: 100%; + display: flex; + flex-direction: column; + justify-content: space-between; + user-select: none; + -ms-user-select: none; + -moz-user-select: none; + overflow-y: auto; + position: relative; + + &-header { + display: flex; + align-items: center; + justify-content: flex-start; + margin: 29px 0px 30px 57px; + } + + &-img { + width: 18px; + height: 18px; + transform: scale(2.5); + margin-right: 28px; + } + + &-title { + font-size: 26px; + color: #333; + font-weight: 500; + } + + &-ipt { + + width: 344px; + height: 40px; + display: flex; + align-items: center; + margin-bottom: 7px; + + input { + padding-left: 57px; + height: 40px; + border: 1px solid #979797; + border-radius: 4px; + + &:hover { + border-color: #979797; + } + + &:focus, + &:active { + border-color: #108EF9 ; + } + } + + &-open-eye, + &-close-eye { + cursor: pointer; + } + + + &-user-img, + &-open-eye, + &-close-eye { + width: 32px; + height: 32px; + transform: scale(.5); + position: absolute; + left: 15px; + z-index: 9; + } + + &-clear { + width: 32px; + height: 32px; + transform: scale(.5); + position: absolute; + right: 5px; + cursor: pointer; + } + } + + .operate-login-ruleForm { + margin: 6px auto 0; + } + + .operate-login { + width: 556px; + background: #fff; + box-shadow: 0 1px 6px 0 rgba(153, 153, 153, 0.50); + border-radius: 10px; + margin: 10px auto 30px; + display: flex; + flex-direction: column; + min-height: 370px; + &-title { + font-size: 16px; + color: #666; + text-align: center; + font-weight: 400; + margin-top: 36px; + margin-bottom: 40px; + } + } + + .operate-login-button { + background-color: #108EF9 ; + border-color: #108EF9 ; + width: 344px; + height: 40px; + margin: 30px auto 0; + &:hover { + background-color: #108EF9 ; + border-color: #108EF9 ; + } + } + + .error-tooltip { + color: #f56c6c; + margin: -10px 0; + } + + .operate-footer { + font-size: 12px; + color: #666; + text-align: center; + font-weight: 500; + display: flex; + flex-direction: column; + margin-bottom: 26px; + } +} diff --git a/bmp-console-web/src/views/Login/login.vue b/bmp-console-web/src/views/Login/login.vue new file mode 100644 index 0000000..1bdad2f --- /dev/null +++ b/bmp-console-web/src/views/Login/login.vue @@ -0,0 +1,295 @@ + + + + diff --git a/bmp-console-web/src/views/MessageDetail/messageDetail.scss b/bmp-console-web/src/views/MessageDetail/messageDetail.scss new file mode 100644 index 0000000..e46626c --- /dev/null +++ b/bmp-console-web/src/views/MessageDetail/messageDetail.scss @@ -0,0 +1,69 @@ +.message-detail { + padding-top: 24px !important; + .header-detail { + position: relative; + left: 0; + right: 0; + margin: 0 auto; + padding-left: 36px; + width: 1200px; + border-bottom: 1px solid #F0F0F0; + } + .message-content { + margin: 0 36px 0 36px; + .message-tip { + margin-top: 27px; + font-size: 14px; + font-weight: 600; + color: #FF4D4F ; + } + .message-greeting { + margin-top: 20px; + font-size: 12px; + } + .operate-content { + margin: 20px 0 0 0 !important; + .el-table { + margin-bottom: 20px; + } + .el-table tr { + background-color: #F7F7F7 !important; + } + .el-table__body-wrapper { + border-top: none; + } + } + } + .message-detail-button { + width: 230px; + margin: 60px auto 0 auto; + .el-button { + width: 100px; + height: 36px; + font-size: 12px; + color: #FFFFFF; + background-color: #108EF9 !important; + border-color: #108EF9 !important; + &.is-disabled { + background-color: #91D5FF!important; + border-color: #91D5FF !important; + &:hover { + background-color: #91D5FF!important; + border-color: #91D5FF !important; + } + } + + &:hover { + background-color: #108EF9 !important; + border-color: #108EF9 !important; + } + } + .el-button+.el-button { + margin-left: 30px; + } + } + .point-click { + cursor: pointer; + color: #108ef9; + } +} \ No newline at end of file diff --git a/bmp-console-web/src/views/MessageDetail/messageDetail.vue b/bmp-console-web/src/views/MessageDetail/messageDetail.vue new file mode 100644 index 0000000..a2d2d2d --- /dev/null +++ b/bmp-console-web/src/views/MessageDetail/messageDetail.vue @@ -0,0 +1,455 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/views/MessageList/messageList.scss b/bmp-console-web/src/views/MessageList/messageList.scss new file mode 100644 index 0000000..9fee56b --- /dev/null +++ b/bmp-console-web/src/views/MessageList/messageList.scss @@ -0,0 +1,292 @@ +.message-list { + .message-list-title { + height: 30px; + margin-bottom: 30px; + padding-left: 34px; + border-bottom: 1px solid #F0F0F0; + .section-title { + font-weight: bold; + color: #333333; + display: inline-block; + padding-left: 20px; + border-left: 2px solid #108EF9; + } + } + .instance-name-height { + margin: 4px 0; + height: 50px; + .el-button { + height: 22px; + } + } + + .group-list-choose { + display: inline-block; + margin-left: 30px; + .el-radio-button :hover { + border-color: #979797; + color: #333; + } + .el-radio-button__original-radio:checked + .el-radio-button__inner:hover { + border-color: #108EF9; + color: #fff; + } + .el-radio-button { + .el-radio-button__inner { + font-size: 12px; + } + + } + } + + .el-table { + max-height: calc(100vh - 380px) !important; + } + + +} + +.el-checkbox__inner { + width: 10px; + height: 10px; + margin-top: 1px; + border-radius: 2px; + border: 1px solid #333; + + &:hover, + &:focus, + &:active { + border-color: #108EF9 !important; + } + + &::after { + height: 5px; + left: 2px; + top: 0px; + } +} + +.unread-message-content { + font-size: 12px; + font-weight: 600; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + float: center; + cursor: pointer; + color: #333333; + + &:hover .text-underline { + padding-bottom: 3px; + border-bottom: 1px solid #666666; + } +} + +.read-message-content { + font-size: 12px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + float: center; + cursor: pointer; + color: #666666; + + + &:hover .text-underline { + padding-bottom: 3px; + border-bottom: 1px solid #999999; + } + +} + +.search-result { + font-size: 12px; + margin-bottom: 10px; +} + +.warning-tip { + width: 16px; + height: 16px; + position:absolute; + cursor: pointer; +} +.change-show-style { + cursor: pointer; +} +.one-line-drop { + margin-left: 5px; + margin-right: 5px; + display: inline-block; +} +.disabled-currency-style { + cursor: no-drop; + color: #999999 !important; +} + +.no-click { + color: #999999 !important; + cursor: no-drop; +} +.can-click { + color: #333333 !important; + cursor: pointer; +} + + + +.tag-content { + .el-tag__content { + display: contents; + .is-loading { + margin-left: 3px; + cursor: auto; + font-size: calc(var(--el-icon-size) - 2px) !important; + animation: rotating 2s linear infinite; + } + } + +} +.no-data-jump { + width: 100%; + text-align: center; +} + +.el-table__empty-text { + width: 100%; +} + +.batch-operate { + display: inline-block; + margin-left: 50px; + margin-top: 8px; + .el-checkbox { + margin-right: 30px; + height: 24px; + vertical-align: middle; + } + .el-button { + &--primary { + min-width: 50px; + height: 24px; + font-size: 12px; + margin-right: 10px; + --el-button-bg-color: #108ee9 !important; + --el-button-text-color: #fff; + + &:focus, + &:hover { + --el-button-hover-bg-color: #108ee9 !important; + --el-button-hover-text-color: #fff; + } + + &:active { + --el-button-active-bg-color: #0f81d4 !important; + } + --el-button-disabled-bg-color: #91D5FF !important; + --el-button-disabled-border-color: #91D5FF !important; + } + } + + .batch-drop-down { + display: inline-block; + vertical-align: middle; + } +} + +.page-change { + display: inline-block; + float: right; + margin-right: 50px; +} + +.column-left { + text-align: left !important; +} + +.border-none { + border-left: 0 !important; + border-right: 0 !important; +} + + +.dot { + width: 4px; + height: 4px; + border-radius: 100%; + background: #108EF9; + box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .2); +} + +.filter-content { + position: absolute; + top: 208px; + .filter-content-fixed { + position: fixed; + .filter-message-list-checkbox { + max-height: 200px; + overflow: auto; + margin: 5px 0; + .el-checkbox-group { + display: grid; + } + .el-checkbox { + margin-right: 0; + padding-left: 10px; + height: 28px; + &:hover { + background-color: #F7F7F7; + } + } + } + + } + .filter-message-list-input { + .el-input__inner { + border-radius: 0; + border-top: none; + border-left: none; + border-right: none; + } + + } + .input-zh { + .el-input { + width: 142px ; + } + } + .input-en { + .el-input { + width: 172px ; + } + } + .filter-message-list-button { + display: flex; + justify-content:space-between; + border-top: .5px solid #c4c4c4; + .el-button { + width: 50%; + font-size: 12px; + color: #333333; + &:hover { + color: #108EF9; + } + &.is-disabled { + color: #999999; + } + } + } +} + +.right-zh { + right: 200px; +} +.right-en { + right: 230px; +} +.change-blue { + color: #108EF9; +} + +.el-table-filter__list-item { + font-size: 12px; +} \ No newline at end of file diff --git a/bmp-console-web/src/views/MessageList/messageList.vue b/bmp-console-web/src/views/MessageList/messageList.vue new file mode 100644 index 0000000..b6090ff --- /dev/null +++ b/bmp-console-web/src/views/MessageList/messageList.vue @@ -0,0 +1,1268 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/views/PersonalCentre/personalCentre.scss b/bmp-console-web/src/views/PersonalCentre/personalCentre.scss new file mode 100644 index 0000000..bed131b --- /dev/null +++ b/bmp-console-web/src/views/PersonalCentre/personalCentre.scss @@ -0,0 +1,149 @@ +.item-position { + padding-top: 0 !important; + padding-bottom: 0 !important; + .el-form-item { + margin-left: 25px; + margin-bottom: 20px; + } + .el-tabs__item { + height: 50px; + margin: 4px 0 4px 36px; + padding: 5px 35px; + font-weight:400; + color: #333333; + &:hover { + color: #333333; + background: #F7F7F7; + border-radius: 25px 0 0 25px; + } + } + .el-tabs__item.is-active { + color: #108EF9; + background: #E8F4FD; + border-radius: 25px 0 0 25px; + } + + .el-tabs--left .el-tabs__item.is-left { + text-align: left; + } + + .el-tabs--left .el-tabs__header.is-left { + padding-top: 26px; + margin-right: 0; + } + + .el-tabs__nav-wrap:after { + background: #F0F0F0; + z-index: 3; + } + + .el-tabs--left .el-tabs__nav-wrap.is-left { + margin-right: -2px; + } + .el-tabs--left{ + height: 95%; + } + +} + +.pane-content { + min-height: calc(100vh); + border-left: 2px solid #F0F0F0; + .el-input__inner { + width: 400px; + height: 36px; + } + +} + +.custom-tabs-label { + .personal-title { + bottom: 2px; + margin-left: 29px; + position: relative; + } +} + +.button-style { + font-size: 12px; + background-color: #108EF9; + width: 130px; + height: 36px; + margin-left: 105px; +} + +.phone-select { + .el-input__inner { + width: 265px; + } + .el-input-group__prepend { + background-color: white; + } + .el-select .el-input.is-focus .el-input__inner { + border-color: white !important; + } + .el-select .el-input { + .el-input__inner { + width: 135px; + color: #333; + &:focus { + border: none; + } + } + } +} + +.language-width { + .el-input__inner { + width: 135px; + } +} + + +.lh22 { + line-height: 22px; +} + +.lh18 { + .el-form-item__label { + line-height: 18px; + } +} + +.password-tip { + font-size: 12px; + color: #999999; + width: 550px; +} + +.el-divider--horizontal { + margin: 32px 0; +} + +.input-change { + .el-input.is-disabled .el-input__inner { + background-color: #f3f3f3; + color: #333; + cursor: text; + } +} + +.tag-state { + .el-tag { + height: 17px; + padding: 0 6px; + border-radius: 5px; + } +} + +.license-content { + .el-form-item__label { + font-size: 14px; + font-weight: 600; + } + + .el-form-item { + margin-left: 23px; + margin-bottom: 12px; + } +} \ No newline at end of file diff --git a/bmp-console-web/src/views/PersonalCentre/personalCentre.vue b/bmp-console-web/src/views/PersonalCentre/personalCentre.vue new file mode 100644 index 0000000..74de1cb --- /dev/null +++ b/bmp-console-web/src/views/PersonalCentre/personalCentre.vue @@ -0,0 +1,1599 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/views/ProjectManagement/projectManagement.scss b/bmp-console-web/src/views/ProjectManagement/projectManagement.scss new file mode 100644 index 0000000..98fb37b --- /dev/null +++ b/bmp-console-web/src/views/ProjectManagement/projectManagement.scss @@ -0,0 +1,16 @@ + +.project-list { + .project-name-content { + cursor: pointer; + color: #108ef9; + } + + .change-show-style { + cursor: pointer; + } + + .disabled-currency-style { + cursor: no-drop; + color: #999999 !important; + } +} \ No newline at end of file diff --git a/bmp-console-web/src/views/ProjectManagement/projectManagement.vue b/bmp-console-web/src/views/ProjectManagement/projectManagement.vue new file mode 100644 index 0000000..0de41f5 --- /dev/null +++ b/bmp-console-web/src/views/ProjectManagement/projectManagement.vue @@ -0,0 +1,757 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/src/views/ProjectManagementDetail/projectManagementDetail.scss b/bmp-console-web/src/views/ProjectManagementDetail/projectManagementDetail.scss new file mode 100644 index 0000000..426132c --- /dev/null +++ b/bmp-console-web/src/views/ProjectManagementDetail/projectManagementDetail.scss @@ -0,0 +1,202 @@ +.pt0 { + padding-top: 0 !important; +} +.project-detail-content { + padding-top: 0 !important; + top: 117px !important; + position: relative; + background-color: white; + clear: both; + width: 1200px; + min-height: calc(100vh - 160px); + top: 137px; + left: 0; + right: 0; + bottom: 20px; + margin: 0 auto; + padding-top: 30px; + padding-bottom: 50px; + box-shadow:0 1px 3px 0 #000000 0.5; + border-radius:10px; + .el-button--primary { + &:hover { + background-color: #108EF9; + border-color: #108EF9; + } + &:focus { + background-color: #108EF9; + border-color: #108EF9; + } + &:active { + background-color: #0F81D4; + border-color: #0F81D4; + } + + } + .el-button--primary:hover { + &.is-disabled { + background-color: #91D5FF !important; + border-color: #91D5FF !important; + } + } + .el-input { + border-color: #979797; + } + .el-radio-button__inner { + border-color: #979797; + } + + // 表单验证提示位置修改 + .el-form-item.is-error { + margin-bottom: 32px; + } + // 表单验证提示位置修改 + .el-form-item__error { + margin-top: 5px; + line-height: normal !important; + } + .el-tabs { + border: none; + margin: 10px; + padding: 20px; + min-height: calc(100vh - 160px); + box-shadow: none; + } + .tab-info { + .el-tabs__active-bar { + background: #108ef9; + } + + .el-tabs__header { + background-color: #fff; + margin-bottom: 28px; + } + + .el-tabs__content { + padding: 0; + } + .el-tabs__item { + font-size: 14px; + color: #333; + font-weight: 400; + padding: 0 25px; + + &:hover { + color: #108ef9; + } + // text-align: center; + // margin: 0; + // margin-right: 34px; + // margin-right: 17px; + } + + .el-tabs__nav-wrap::after { + height: 1px !important; + } + + .el-tabs__item.is-active { + color: #108ef9; + font-weight: 400; + border-right-color: #fff; + border-left-color: #fff; + border-bottom-color: #108ef9; + } + + + .el-tabs__nav-wrap { + &::after { + background: #f0f0f0; + } + } + } +} + +.operation-position{ + float: right; + .active-operate { + margin-top: 2px; + .el-button--primary { + background: none; + color: #108EE9; + font-size: 12px; + height: 28px; + border-radius: 14px; + border-color: #108EE9; + margin: 0 20px; + + + } + } + .inactive-operate { + margin-top: 2px; + .el-button--primary { + background: none; + color: #333333; + font-size: 12px; + height: 28px; + border-radius: 14px; + border-color: #333333; + margin: 0 20px; + &:hover { + color: #108EE9; + border-color: #108EE9; + } + } + } +} + +.success { + color: #43B561 !important; +} +.info { + color: #999999 !important; +} +.intermediate { + color:#9254DE !important +} +.danger { + color:#ff4d4f !important +} +.long-name { + font-size: 12px; + overflow: hidden; + text-overflow: ellipsis; + max-width: 260px; + white-space: nowrap; + float: left; +} + +.long-name-title { + overflow: hidden; + text-overflow: ellipsis; + max-width: 180px; + white-space: nowrap; +} + +.desc-type { + width: 16px; + margin-left: 5px; +} + +.back-button { + color: #666666; + margin-left: 32px; + span { + margin-left: 10px !important; + } + +} + +.operate-btn { + width: 80px; + color: #333333; + font-size: 12px; +} + +.desc-tooltip-popper { + max-width: 300px; +} + +.bl-none { + border-left: none !important; +} \ No newline at end of file diff --git a/bmp-console-web/src/views/ProjectManagementDetail/projectManagementDetail.vue b/bmp-console-web/src/views/ProjectManagementDetail/projectManagementDetail.vue new file mode 100644 index 0000000..d4678a6 --- /dev/null +++ b/bmp-console-web/src/views/ProjectManagementDetail/projectManagementDetail.vue @@ -0,0 +1,855 @@ + + + + + \ No newline at end of file diff --git a/bmp-console-web/tsconfig.json b/bmp-console-web/tsconfig.json new file mode 100644 index 0000000..91c646c --- /dev/null +++ b/bmp-console-web/tsconfig.json @@ -0,0 +1,37 @@ +{ + "compilerOptions": { + "target": "esnext", // 指定 ECMAScript 目标版本 + "module": "esnext", // 指定使用模块 + "strict": true, // 启用所有严格类型检查选项 + "jsx": "preserve", // 指定 jsx 代码的生成: preserve + "importHelpers": true, // 从 tslib 导入辅助工具函数 + "moduleResolution": "node", // 选择模块解析策略:node + "skipLibCheck": true, // 跳过库检查 + "esModuleInterop": true, //允许使用commonjs的方式import默认文件 + "allowSyntheticDefaultImports": true, // 允许从没有设置默认导出的模块中默认导入 + "sourceMap": true, // 生成相应的.map文件 + "baseUrl": "/", // 工作根目录 + "noUnusedLocals": true, // 有未使用的变量时,抛出错误 + "noUnusedParameters": true, // 有未使用的参数时,抛出错误 + "suppressImplicitAnyIndexErrors":true,//屏蔽语法检查 + "types": [ // 需要包含的类型声明文件名列表 + "webpack-env" + ], + "paths": { // 模块名到基于 baseUrl 的路径映射的列表 + "@": ["src"] + }, + "lib": [ // 指定要包含在编译中的库文件 + "esnext", + "dom", + "dom.iterable", + "scripthost" + ] + }, + "include": [ // 指定编译需要编译的文件或目录 + "src/**/*" // *匹配零个或者多个字符 + ], + "exclude": [ // 用于指定当解析include选项时,需要忽略的文件列表 + "node_modules", + "dist" + ] +} \ No newline at end of file diff --git a/bmp-console-web/vue.config.js b/bmp-console-web/vue.config.js new file mode 100644 index 0000000..bdeb7bb --- /dev/null +++ b/bmp-console-web/vue.config.js @@ -0,0 +1,31 @@ +// 页面路径 +const setAlias = require('./config/setAlias'); +// 跨域配置 +const devServer = require('./config/devServer'); +// 避免文件的频繁变更导致浏览器缓存失效,更好的利用缓存。提升用户体验 +const runtimeChunk = require('./config/runtimeChunk'); +// 可以看到启动时的消耗模块,方便后续做优化 +const speedMeasure = require('./config/speedMeasure'); +// prod环境移除console +const terserPlugin = require('./config/terserPlugin'); +// 减少不必要的解析 +const noParse = require('./config/noParse'); + +module.exports = { + productionSourceMap: false, // 是否在构建生产包时生成 sourceMap 文件,false将提高构建速度 + // 修改默认的webpack的配置 + configureWebpack: config => { + runtimeChunk(config); + speedMeasure(config); + noParse(config); + }, + // 调整内部的webpack配置 + chainWebpack: config => { + // 配置alias别名 + setAlias(config); + // 删除懒加载模块的prefetch,降低带宽压力 + config.plugins.delete('prefetch'); + terserPlugin(config); + }, + ...devServer +}; diff --git a/bmp-deploy/.env b/bmp-deploy/.env new file mode 100644 index 0000000..11d1fd3 --- /dev/null +++ b/bmp-deploy/.env @@ -0,0 +1,57 @@ +BMP_HOST_IP=10.0.0.2 + +# bmp registry +BMP_REGISTRY=quay.io/jdcloudbmp + +# db middleware registry eg: mysql:5.7-debian +# if you cannot pull from docker.io please change docker.io to other Container image repository +BASE_REGISTRY=quay.io/jdcloudbmp + +BMP_VERSION='v1.0' +COMPOSE_PROJECT_NAME=bmp + +BMP_DB_HOST=bmp-db +BMP_DB_PORT=3306 +BMP_DB_USER=bmp_rw +BMP_DB_PASSWORD='LpK9Jq12Zf' +BMP_DB_NAME=bmp + +BMP_REDIS_HOST=bmp-redis +BMP_REDIS_PORT=6379 +BMP_REDIS_PASSWORD='LpK9Jq12Zf' + +BMP_MQ_HOST=bmp-mq +BMP_MQ_PORT=5672 +BMP_MQ_USER=bmp +BMP_MQ_PASSWORD='LpK9Jq12Zf' +BMP_MQ_VHOST=/bmp + +BMP_OMAPI_HOST=bmp-dhcp-agent +BMP_OMAPI_PORT=7911 +BMP_OMAPI_TOKEN="LpK9Jq12Zf" + +BMP_OPENAPI_HOST=bmp-openapi +BMP_OPENAPI_PORT=8801 +BMP_OPENAPI_CONSOLE_HOST=bmp-openapi-console +BMP_OPENAPI_CONSOLE_PORT=8802 + +BMP_OOB_ALERT_HOST=bmp-oob-alert +BMP_OOB_ALERT_PORT=8804 + +BMP_MQ_EXCHANGE_ROUTING_KEY=idc-vm4xsulx1k2d9z4xkctrttig02zl +BMP_IMAGE_PORT=10000 +BMP_MONITOR_PROXY_PORT=8805 + +BMP_PROMETHEUS_HOST=bmp-prometheus +BMP_PROMETHEUS_PORT=9090 +BMP_PROMETHEUS_DATA_DIR=/data/prometheus + +BMP_PUSHGATEWAY_HOST=bmp-pushgateway +BMP_PUSHGATEWAY_PORT=9091 + +BMP_ALERTMANAGER_HOST=bmp-alertmanager +BMP_ALERTMANAGER_PORT=9093 + +BMP_PRONOEA_HOST=bmp-pronoea +BMP_PRONOEA_PORT=9999 +BMP_RSYSLOG_PORT=1514 diff --git a/bmp-deploy/.gitignore b/bmp-deploy/.gitignore new file mode 100644 index 0000000..b0798ff --- /dev/null +++ b/bmp-deploy/.gitignore @@ -0,0 +1,2 @@ +.cmd +cache/ diff --git a/bmp-deploy/.idea/.gitignore b/bmp-deploy/.idea/.gitignore new file mode 100644 index 0000000..eaf91e2 --- /dev/null +++ b/bmp-deploy/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/bmp-deploy/.idea/bmp-deploy-f07fb62.iml b/bmp-deploy/.idea/bmp-deploy-f07fb62.iml new file mode 100644 index 0000000..18ec59d --- /dev/null +++ b/bmp-deploy/.idea/bmp-deploy-f07fb62.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/bmp-deploy/.idea/misc.xml b/bmp-deploy/.idea/misc.xml new file mode 100644 index 0000000..6e86672 --- /dev/null +++ b/bmp-deploy/.idea/misc.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/bmp-deploy/.idea/modules.xml b/bmp-deploy/.idea/modules.xml new file mode 100644 index 0000000..ccba559 --- /dev/null +++ b/bmp-deploy/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/bmp-deploy/README.md b/bmp-deploy/README.md new file mode 100644 index 0000000..8516fc4 --- /dev/null +++ b/bmp-deploy/README.md @@ -0,0 +1,3 @@ +# [BMP Installation Guide](doc/main.md) + + diff --git a/bmp-deploy/README.zh-CN.md b/bmp-deploy/README.zh-CN.md new file mode 100644 index 0000000..2c3d310 --- /dev/null +++ b/bmp-deploy/README.zh-CN.md @@ -0,0 +1 @@ +# [bmp安装指导](doc/zh/main.md) diff --git a/bmp-deploy/arch_bak/aarch64.env b/bmp-deploy/arch_bak/aarch64.env new file mode 100644 index 0000000..34e6614 --- /dev/null +++ b/bmp-deploy/arch_bak/aarch64.env @@ -0,0 +1,2 @@ +BMP_DB_IMAGE="mysql:8.1-oracle" +BMP_TFTP_IMAGE="jdcloudbmp/bmp-tftp:latest-arm" diff --git a/bmp-deploy/arch_bak/common.env b/bmp-deploy/arch_bak/common.env new file mode 100644 index 0000000..5947dc2 --- /dev/null +++ b/bmp-deploy/arch_bak/common.env @@ -0,0 +1,5 @@ +BMP_DB_IMAGE="mysql:5.7-debian" +BMP_REDIS_IMAGE="redis:7.0-alpine" +BMP_MQ_IMAGE="rabbitmq:3.11-management-alpine" +BMP_TFTP_IMAGE="pghalliday/tftp" +BMP_IMAGE_IMAGE="nginx:1.22-alpine" \ No newline at end of file diff --git a/bmp-deploy/arch_bak/loongarch64.env b/bmp-deploy/arch_bak/loongarch64.env new file mode 100644 index 0000000..e71b4a5 --- /dev/null +++ b/bmp-deploy/arch_bak/loongarch64.env @@ -0,0 +1,5 @@ +BMP_DB_IMAGE="cr.loongnix.cn/library/mysql:5.7.39" +BMP_REDIS_IMAGE="cr.loongnix.cn/library/redis:7.0-alpine" +BMP_MQ_IMAGE="cr.loongnix.cn/library/rabbitmq:3.8.2-management-alpine" +BMP_TFTP_IMAGE="jdcloudbmp/bmp-tftp:latest-loongarch64" +BMP_IMAGE_IMAGE="cr.loongnix.cn/library/nginx:1.23.1-alpine" diff --git a/bmp-deploy/arch_bak/x86_64.env b/bmp-deploy/arch_bak/x86_64.env new file mode 100644 index 0000000..41fa535 --- /dev/null +++ b/bmp-deploy/arch_bak/x86_64.env @@ -0,0 +1,2 @@ +BMP_DB_IMAGE="mysql:5.7-debian" +BMP_TFTP_IMAGE="pghalliday/tftp" diff --git a/bmp-deploy/ark_bak/build.sh b/bmp-deploy/ark_bak/build.sh new file mode 100644 index 0000000..0ddfa8b --- /dev/null +++ b/bmp-deploy/ark_bak/build.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e +SCRIPTS_DIR=$(dirname $(realpath $0)) +APP_NAME=$1 + +mkdir -p output/bin +mkdir -p output/src +cp $SCRIPTS_DIR/control output/bin/ +#cp -r bmp-deploy output/ +find . -maxdepth 1 ! -regex '\.' ! -regex '\./output' ! -regex '\./\.git' ! -regex '\./bmp-deploy.*' ! -regex '\./tmp_build.*\.sh' | xargs -I {} cp -r {} output/src +echo APP_NAME=$APP_NAME >> output/bin/app.properties +echo COMPILER_VERSION=$COMPILER_VERSION >> output/bin/app.properties diff --git a/bmp-deploy/ark_bak/control b/bmp-deploy/ark_bak/control new file mode 100644 index 0000000..11588aa --- /dev/null +++ b/bmp-deploy/ark_bak/control @@ -0,0 +1,100 @@ +#!/bin/bash +set -uex + +CURRENT_DIR=$(pwd) +DEPLOY_DIR=/home/bmp/bmp-deploy +SCRITP_DIR=$(dirname $(realpath $0)) +[ -f $SCRITP_DIR/app.properties ] && . $SCRITP_DIR/app.properties +[ -n "$APP_NAME" ] || exit 1 +[ -e /etc/profile.d/bmp.sh ] && . /etc/profile.d/bmp.sh +TAG="" +[ -n "$TAG" ] || TAG=$BMP_VERSION +[ -n "$TAG" ] || { + echo "TAG must be set" + exit 1 +} +ARCH=$(uname -i) +DOCKER_FILE=$DEPLOY_DIR/dockerfile/${APP_NAME}.Dockerfile +[ -e $DEPLOY_DIR/dockerfile/${APP_NAME}_${ARCH}.Dockerfile ] && DOCKER_FILE=$DEPLOY_DIR/dockerfile/${APP_NAME}_${ARCH}.Dockerfile +DOCKER_IMAGE=jdcloudbmp/$APP_NAME:$TAG +#COMPOSE_FILE=$DEPLOY_DIR/bmp-deploy/docker-compose.yml +DEPLOY_BIN=$DEPLOY_DIR/bmp-deploy.sh +[ -v APP_CODE_DIR ] || APP_CODE_DIR=$CURRENT_DIR/src +DOCKER_IMAGE_OLD_ID="" +DOCKER_IMAGE_NEW_ID="" + +help(){ + echo "${0} " + exit 1 +} + + +checkhealth(){ + $DEPLOY_BIN status $APP_NAME + if [[ $? -eq 0 ]];then + echo "$APP_NAME is running" + return 0 + fi + echo "$APP_NAME is not running" + return 1 + +} + +build(){ + if [ -e $DOCKER_FILE ]; then + if [ -e "$APP_CODE_DIR" ]; then + docker build -t $DOCKER_IMAGE -f $DOCKER_FILE $APP_CODE_DIR + else + docker build -t $DOCKER_IMAGE -f $DOCKER_FILE . + fi + fi +} + +clean(){ + if [ -n "$DOCKER_IMAGE_OLD_ID" ] && [ "$DOCKER_IMAGE_OLD_ID" != "$DOCKER_IMAGE_NEW_ID" ]; then + docker rmi $DOCKER_IMAGE_OLD_ID + fi +} + +start(){ + checkhealth && return 0 + # [ -e $DEPLOY_DIR ] && rm -rf $DEPLOY_DIR + # cp -r $CURRENT_DIR/bmp-deploy $DEPLOY_DIR + cd $DEPLOY_DIR && git pull + build + DOCKER_IMAGE_OLD_ID=$($DEPLOY_BIN images $APP_NAME | awk 'NR==2{print $4}') + $DEPLOY_BIN start $APP_NAME + DOCKER_IMAGE_NEW_ID=$($DEPLOY_BIN images $APP_NAME | awk 'NR==2{print $4}') + clean +} + +stop(){ + checkhealth || return 0 + $DEPLOY_BIN stop $APP_NAME + sleep 2 + checkhealth || return 0 + return 1 +} + + +[ -e $DEPLOY_BIN ] && chmod +x $DEPLOY_BIN +case "${1}" in + start) + start + ;; + stop) + stop + ;; + status|health|checkhealth) + checkhealth + ;; + restart) + stop && start + ;; + build) + build + ;; + *) + help + ;; +esac \ No newline at end of file diff --git a/bmp-deploy/ark_bak/loongarch64/pre_build.sh b/bmp-deploy/ark_bak/loongarch64/pre_build.sh new file mode 100644 index 0000000..b3a075f --- /dev/null +++ b/bmp-deploy/ark_bak/loongarch64/pre_build.sh @@ -0,0 +1,20 @@ +#!/bin/bash +CODE_DIR=$1 +APP_NMAE=$2 + +[ -n "$CODE_DIR" ] || { + echo "CODE_DIR is null" + exit 1 +} +[ -n "$APP_NMAE" ] || { + echo "APP_NMAE is null" + exit 1 +} + +cd $CODE_DIR +if [ -e go.mod ]; then + sed -i 's/go 1.15/go 1.17/g' go.mod + go get github.com/prometheus/procfs + go mod tidy || go mod tidy -compat=1.17 + go mod vendor +fi \ No newline at end of file diff --git a/bmp-deploy/ark_bak/middleware_build.sh b/bmp-deploy/ark_bak/middleware_build.sh new file mode 100644 index 0000000..b5023d6 --- /dev/null +++ b/bmp-deploy/ark_bak/middleware_build.sh @@ -0,0 +1,11 @@ +#!/bin/bash +set -e +SCRIPTS_DIR=$(dirname $(realpath $0)) +APP_NAME=$1 + +mkdir -p output/bin +cp $SCRIPTS_DIR/control output/bin/ +#mkdir output/bmp-deploy +#find . -maxdepth 1 ! -regex '\.' ! -regex '\./output' ! -regex '\./\.git' ! -regex '\./tmp_build.*\.sh' | xargs -I {} cp -r {} output/bmp-deploy/ +echo APP_NAME=$APP_NAME >> output/bin/app.properties +echo COMPILER_VERSION=$COMPILER_VERSION >> output/bin/app.properties diff --git a/bmp-deploy/bmp-build-image.sh b/bmp-deploy/bmp-build-image.sh new file mode 100644 index 0000000..d9a5c38 --- /dev/null +++ b/bmp-deploy/bmp-build-image.sh @@ -0,0 +1,124 @@ +#!/bin/bash +set -ue +WORKSPACE=$(cd $(dirname $0); pwd) +set -a +. $WORKSPACE/.env +. $WORKSPACE/config/image.cfg +. $WORKSPACE/config/service.cfg +set +a + +parse() +{ + POSITIONAL_ARGS=() + DEFAULT=NO + while [[ $# -gt 0 ]]; do + case $1 in + -h|--help) + usage + exit 0 + ;; + -*|--*) + echo "Unknown option $1" + exit 1 + ;; + *) + POSITIONAL_ARGS+=("$1") # save positional arg + shift # past argument + ;; + esac + done +} + +usage(){ + help=' +Usage: ./bmp-build-image.sh build SERVICE... + +COMMAND: + build Build image + +SERVICE: + all All SERVICES +' + for s in ${bmp_service_app[@]}; do + help="${help} $s\n" + done + for s in ${bmp_service_other[@]}; do + help="${help} $s\n" + done + + + printf "$help" +} + + +parse $@ +if [ ${#POSITIONAL_ARGS[@]} -lt 2 ]; then + usage +fi + +#check command +COMMAND=${POSITIONAL_ARGS[0]} +if [[ "build" != "$COMMAND" ]]; then + echo "COMMAND $COMMAND is not support!" + usage + exit 1 +fi + +ALL_SERVICES=("${bmp_service_app[@]}" "${bmp_service_other[@]}") +if [ "${POSITIONAL_ARGS[1]}" = "all" ]; then + SERVICES=(${ALL_SERVICES[@]}) +else + SERVICES=(${POSITIONAL_ARGS[@]:1}) + for s in ${SERVICES[@]}; do + if [[ ! " ${ALL_SERVICES[@]} " =~ " $s " ]]; then + echo "service $s is not support!" + usage + exit 1 + fi + done +fi + +# build image +bmp_code_dir=$(dirname ${WORKSPACE}) +for service_name in ${SERVICES[@]}; do + dockerfile_name=${bmp_code_dir}/${service_name}/${service_name}.Dockerfile + docker_tag=${BMP_REGISTRY}/${service_name}:${BMP_VERSION} + build_code_dir=${bmp_code_dir}/${service_name} + + if [ ${service_name} == "bmp-tftp" ] || [ ${service_name} == "bmp-rsyslog" ];then + dockerfile_name=${WORKSPACE}/dockerfile/${service_name}.Dockerfile + docker_tag=${BMP_REGISTRY}/${service_name}:${BMP_VERSION} + build_code_dir=${bmp_code_dir} + + elif [ ${service_name} == "bmp-oob-agent" ];then + dockerfile_name=${bmp_code_dir}/oob-log-agent/oob-log-agent.Dockerfile + docker_tag=${BMP_REGISTRY}/oob-log-agent:${BMP_VERSION} + build_code_dir=${bmp_code_dir}/oob-log-agent + + elif [ ${service_name} == "bmp-oob-alert" ];then + dockerfile_name=${bmp_code_dir}/oob-log-alert/oob-log-alert.Dockerfile + docker_tag=${BMP_REGISTRY}/oob-log-alert:${BMP_VERSION} + build_code_dir=${bmp_code_dir}/ + + elif [ ${service_name} == "bmp-console-api" ] || [ ${service_name} == "bmp-operation-api" ];then + dockerfile_name=${bmp_code_dir}/${service_name}/${service_name}.Dockerfile + docker_tag=${BMP_REGISTRY}/${service_name}:${BMP_VERSION} + build_code_dir=${bmp_code_dir}/ + + else + dockerfile_name=${bmp_code_dir}/${service_name}/${service_name}.Dockerfile + docker_tag=${BMP_REGISTRY}/${service_name}:${BMP_VERSION} + build_code_dir=${bmp_code_dir}/${service_name} + fi + + if [ ! -f "${dockerfile_name}" ];then + echo ${service_name} dockerfile : "${dockerfile_name}" do not exists!! + exit 1 + fi + echo "${service_name} begin build image ... " + echo "image name: ${docker_tag}" + echo "build code path: ${build_code_dir}" + docker build -f ${dockerfile_name} -t ${docker_tag} ${build_code_dir} + echo "build success !!" + echo "---------------------------------------------------------" +done diff --git a/bmp-deploy/bmp-deploy-precheck.sh b/bmp-deploy/bmp-deploy-precheck.sh new file mode 100644 index 0000000..3b84d80 --- /dev/null +++ b/bmp-deploy/bmp-deploy-precheck.sh @@ -0,0 +1,245 @@ +#! /bin/bash + +set -e + +script_dir=$(cd $(dirname "$0") && pwd) + +#load env +#set -a +#. $WORKSPACE/.env +#set +a + +# 帮助文档 +show_help() { + echo "Usage: $0 [-h|--help] [-e|--env ]" + echo + echo "Options:" + echo " -h, --help Show this help message and exit" + echo " -e, --env Set the environment to 'public' or 'private'" +} + +# 初始化变量 +deploy_env="" + +# 解析命令行参数 +while [[ "$#" -gt 0 ]]; do + case $1 in + -h|--help) + show_help + exit 0 + ;; + -e|--env) + if [[ -n "$2" ]]; then + if [[ "$2" == "public" || "$2" == "private" ]]; then + deploy_env="$2" + shift + else + echo "Error: The -e|--env option can only be 'public' or 'private'." + exit 1 + fi + else + echo "Error: The -e|--env option requires an argument." + exit 1 + fi + ;; + *) + echo "Error: Invalid option $1" + show_help + exit 1 + ;; + esac + shift +done + +if [[ -n "$deploy_env" ]]; then + echo "Environment set to: $deploy_env" +else + echo "No environment set." + echo " -e, --env Set the environment to 'public' or 'private'" + exit 1 +fi + +function check_docker(){ + # 检查 Docker 是否安装 + if ! docker version &> /dev/null; then + echo "Error: Docker is not installed." + # offline install + if [ -d $script_dir/docker_install_files/docker ];then + echo "Now starting offline installation of Docker." + cp $script_dir/docker_install_files/docker/bin/* /usr/bin/ + cp $script_dir/docker_install_files/docker/docker.service /etc/systemd/system/ + chmod +x /usr/bin/docker* + chmod 644 /etc/systemd/system/docker.service + systemctl daemon-reload &> /dev/null + systemctl enable docker &> /dev/null + systemctl start docker &> /dev/null + if [ $? -nq 0]; then + echo "Error: Docker installation failed, please install manually or contact technical support." + exit 1 + fi + echo "Docker installation success." + fi + fi + + if ! (docker-compose version &>/dev/null || docker compose version &>/dev/null); then + echo "Docker Compose is not installed." + # offline install + if [ -d $script_dir/docker_install_files/docker-compose ];then + echo "Now starting offline installation of Docker-compose." + cp $script_dir/docker_install_files/docker-compose/* /usr/bin/ + chmod u+x $script_dir/docker_install_files/docker-compose/* + docker-compose version &>/dev/null + if [ $? -nq 0 ]; then + echo "Error: Docker-compose installation failed, please install manually or contact technical support." + exit 1 + fi + echo "Docker-compose installation success." + fi + fi + # 获取 Docker 版本 + # docker_version=$(docker --version 2>&1) + + # 使用正则表达式从版本字符串中提取主要版本号 + #major_version=$(echo "$docker_version" | grep -oP 'Docker version \K(\d+)') + + # 比较主要版本号 + #if (( $major_version < 2 )); then + # echo "Error: Docker version is too low. Please update to latest version." + # exit 1 + # fi + + echo "Docker and docker compose are installed." +} + +function check_port(){ + port_list=$(grep -E -o "\- ([0-9]+):([0-9]+)" docker-compose.yml | awk -F "[ :]" '{print $2}') + check_port_res=0 + for every_port in ${port_list[@]};do + if (lsof -i :$every_port | grep -E "LISTEN|UDP" &> /dev/null);then + echo "port $every_port is already in use. " + check_port_res=1 + fi + done + if [ $check_port_res -ne 0 ];then + echo "ERROR: The BMP system needs to use these ports, but these ports is already in use. Please confirm." + exit 1 + fi + echo "All ports are available." +} + + +function update_env_ip(){ + # 获取本机的所有 IP 地址 + ips=$(ip addr show | awk '/^[0-9]+: / {}; /inet.*global/ {print $2}' | cut -d '/' -f 1) + + # 如果有多个 IP 地址,提示用户选择一个作为主 IP + if [[ $(echo "$ips" | wc -l) -gt 1 ]]; then + echo "This machine has multiple IP addresses:" + echo "$ips" + while true; do + read -p "Please enter the IP address to use as the main IP for external communication: " main_ip + if echo "$ips" | grep -q "$main_ip"; then + echo "$main_ip is a valid IP address" + break; + else + echo "$main_ip is not a valid IP address, please check the spelling and re-enter" + fi + done + else + # 如果只有一个 IP 地址,直接使用它作为主 IP + main_ip=$ips + fi + sed -i "s/^BMP_HOST_IP=.*/BMP_HOST_IP=$main_ip/g" $script_dir/.env + echo "The main IP address for external communication is: $main_ip" +} + + +function private_load_docker_images(){ + docker_image=$script_dir/private_deploy_docker_images/bmp-image.tar.gz + if [ ! -f $docker_image ];then + echo "$docker_image does not exist. Please confirm whether the file download is correct, or contact the BMP colleague." + exit 1 + fi + docker load -i $docker_image + if [ $? -ne 0 ]; then + echo "Failed to load Docker image: $docker_image" >&2 + exit 1 + fi +} + +function public_load_docker_images(){ + . $script_dir/.env + . $script_dir/config/image.cfg + images_list=( + bmp_rsyslog_image + bmp_driver_image + bmp_dhcp_agent_image + bmp_openapi_image + bmp_openapi_console_image + bmp_scheduler_image + bmp_console_api_image + bmp_operation_api_image + bmp_console_web_image + bmp_operation_web_image + bmp_monitor_proxy_image + bmp_pronoea_image + bmp_tftp_image + oob_log_alert_image + oob_log_agent_image + bmp_redis_image + bmp_mq_image + bmp_image_image + bmp_pushgateway_image + bmp_alertmanager_image + bmp_prometheus_image + bmp_db_image + ) + for image_var in "${images_list[@]}"; do + image_name=${!image_var} + echo "begin docker pull ${image_name}" + if docker images --format "{{.Repository}}:{{.Tag}}" | grep -q "^${image_name}$"; then + echo "Image ${image_name} already exists locally. Skipping docker pull." + else + docker pull ${image_name} + if [ $? -ne 0 ];then + echo "docker pull failed" + exit 1 + fi + echo "docker pull ${!image_var} success!" + fi + done +} + + + +function main(){ + echo -ne "Step 1: Check if docker is installed.\n" + echo "" + check_docker + echo "-------------------------------------------------" + echo -ne "Step 2: Check if port is available.\n" + echo "" + check_port + echo "-------------------------------------------------" + echo -ne "Step 3: update ip in .env \n" + echo "" + # update_env_ip + echo "-------------------------------------------------" + echo -ne "Step 4: docker load images \n" + echo "" + if [[ "$deploy_env" == "private" ]]; then + private_load_docker_images + elif [[ "$deploy_env" == "public" ]]; then + public_load_docker_images + else + echo "No valid environment set." + exit 1 + fi + echo " + now bmp-deploy-precheck.sh success + please run: bash bmp-deploy.sh start all + + " +} + +main diff --git a/bmp-deploy/bmp-deploy.sh b/bmp-deploy/bmp-deploy.sh new file mode 100644 index 0000000..48fca66 --- /dev/null +++ b/bmp-deploy/bmp-deploy.sh @@ -0,0 +1,449 @@ +#!/bin/bash +set -ue +WORKSPACE=$(cd $(dirname $0); pwd) +set -a +. $WORKSPACE/config/service.cfg +set +a + +# +## third-party service + #bmp_service_thirdparty=( + # bmp-db + # bmp-redis + # bmp-mq + # bmp-image + # bmp-pushgateway + # bmp-alertmanager + # bmp-prometheus + #) + # + ## app serveice + #bmp_service_app=( + # bmp-console-web + # bmp-operation-web + # bmp-console-api + # bmp-operation-api + # bmp-openapi + # bmp-openapi-console + # bmp-scheduler + # bmp-driver + # bmp-dhcp-agent + # bmp-oob-alert + # bmp-oob-agent + # bmp-monitor-proxy + # bmp-pronoea + #) + # + ## other service + #bmp_service_other=( + # bmp-tftp + # bmp-rsyslog + #) + # + #bmp_service_all=( + # ${bmp_service_thirdparty[@]} + # ${bmp_service_other[@]} + # ${bmp_service_app[@]} + #) +# +# + + +SERVICES_ALL=(${bmp_service_all[@]}) +COMMANDS_ALL=( + start + stop + restart + status + images + uninstall + reinstall + config +) +ALL_SERVICE=false +COMMAND="" +SERVICES=() +export TAG="" + +# x86-64 arm +ARCH=$(uname -i) + +# set docker compose cmdline +if docker compose version &> /dev/null;then + COMPOSE="docker compose" +elif docker-compose version &> /dev/null;then + COMPOSE="docker-compose" +else + echo "docker compose is not find" + exit 1 +fi + + +COMPOSE_OPTS="--project-directory $WORKSPACE" +COMPOSE_FILE=$WORKSPACE/docker-compose.yml +COMPOSE_OPTS="$COMPOSE_OPTS -f $COMPOSE_FILE" + +# env-file +compose_version=$($COMPOSE version | head -n 1 | awk -F ' |,|-' '{print $4}') +compose_version=${compose_version#*v} +compose_v1=$(echo $compose_version | awk -F '.' '{print $1}') +compose_v2=$(echo $compose_version | awk -F '.' '{print $2}') +if [ $compose_v1 -lt 2 ];then + echo "docker compose version $compose_v1 is not supported" + exit +else + COMPOSE_OPTS="$COMPOSE_OPTS --env-file $WORKSPACE/.env" +fi + +#load env +set -a +. $WORKSPACE/.env +set +a + +export BMP_OMAPI_KEY=$(echo -n "$BMP_OMAPI_TOKEN" | base64) + +usage(){ + help=' +Usage: ./bmp-deploy.sh [-t|--tag TAG] COMMAND SERVICE... + +COMMAND: + start Install and start SERVICE + stop Stop SERVICE + restart restart SERVICE + status check SERVICE status + images display SERVICE image + uninstall uninstall SERVICE + reinstall reinstall SERVICE + config get SERVICE config + +SERVICE: + all All SERVICES +' + for s in ${SERVICES_ALL[@]}; do + help="${help} $s\n" + done + + printf "$help" +} + +parse() +{ + POSITIONAL_ARGS=() + DEFAULT=NO + while [[ $# -gt 0 ]]; do + case $1 in + -h|--help) + usage + exit 0 + ;; + -t|--tag) + TAG="$2" + shift + shift + ;; + -*|--*) + echo "Unknown option $1" + exit 1 + ;; + *) + POSITIONAL_ARGS+=("$1") # save positional arg + shift # past argument + ;; + esac + done +} + +init(){ + #parse parameters + parse $@ + if [ ${#POSITIONAL_ARGS[@]} -lt 2 ]; then + usage + fi + + #check command + COMMAND=${POSITIONAL_ARGS[0]} + if [[ ! " ${COMMANDS_ALL[@]} " =~ " $COMMAND " ]]; then + echo "COMMAND $COMMAND is not support!" + usage + exit 1 + fi + + #check services + if [ "${POSITIONAL_ARGS[1]}" = "all" ]; then + ALL_SERVICE=true + SERVICES=(${SERVICES_ALL[@]}) + else + SERVICES=(${POSITIONAL_ARGS[@]:1}) + fi + + for s in ${SERVICES[@]}; do + if [[ ! " ${SERVICES_ALL[@]} " =~ " $s " ]]; then + echo "service $s is not support!" + usage + exit 1 + fi + done + + #set tag + # [ -n "$TAG" ] || TAG=${BMP_VERSION:-latest} + [ -n "$TAG" ] || TAG=${BMP_VERSION} + [ -n "$TAG" ] || { + echo "TAG must be set" + usage + exit 1 + } + + # arch tag + #if [ "$ARCH" != "x86_64" ] && [[ ! "$TAG" =~ "$ARCH" ]];then + # TAG=${TAG}-${ARCH} + #fi + + #check BMP_HOST_IP + if [ ! -n "$BMP_HOST_IP" ] || ! ip addr show | grep "inet $BMP_HOST_IP" > /dev/null; then + echo "BMP_HOST_IP=$BMP_HOST_IP" is not a local ip + exit + fi + + # load image config + set -a + . $WORKSPACE/config/image.cfg + set +a + + # set umask + umask 0022 + + # create cache dir + [ -d $WORKSPACE/$bmp_cache_dir ] || mkdir $WORKSPACE/$bmp_cache_dir +} + +pre_start(){ + local service=$1 + + # download bootloader images + if [ "$service" == "bmp-tftp" ]; then + for image in ${bmp_bootloader_images[@]};do + if [ ! -e $WORKSPACE/${bmp_cache_dir}/${image} ];then + echo "downloading ${bmp_oss_url}/${bmp_bootloader_prefix}/${image} ..." + curl -sf ${bmp_oss_url}/${bmp_bootloader_prefix}/${image} -o $WORKSPACE/${bmp_cache_dir}/${image} || { + echo download ${bmp_oss_url}/${bmp_bootloader_prefix}/${image} fail! + exit 1 + } + fi + done + fi + + # download LiveOS images + if [ "$service" == "bmp-tftp" ]; then + for image in ${bmp_liveos_images[@]};do + if [ ! -e $WORKSPACE/${bmp_cache_dir}/${image} ];then + echo "downloading ${bmp_oss_url}/${bmp_oss_liveos_prefix}/${image} ..." + curl -sf ${bmp_oss_url}/${bmp_oss_liveos_prefix}/${image} -o $WORKSPACE/${bmp_cache_dir}/${image} || { + echo download ${bmp_oss_url}/${bmp_oss_liveos_prefix}/${image} fail! + exit 1 + } + fi + done + fi + + # download GuestOS images + if [ "$service" == "bmp-image" ]; then + for image in ${bmp_guestos_images[@]};do + if [ ! -e $WORKSPACE/${bmp_cache_dir}/${image} ];then + echo "downloading ${bmp_oss_url}/${bmp_oss_guestos_prefix}/${image} ..." + curl -sf ${bmp_oss_url}/${bmp_oss_guestos_prefix}/${image} -o $WORKSPACE/${bmp_cache_dir}/${image} || { + echo download ${bmp_oss_url}/${bmp_oss_guestos_prefix}/${image} fail! + exit 1 + } + fi + done + fi + + # download bmp-agent + if [ "$service" == "bmp-image" ]; then + for image in ${bmp_agent_images[@]};do + if [ ! -e $WORKSPACE/${bmp_cache_dir}/${image} ];then + echo "downloading ${bmp_oss_url}/${bmp_oss_agent_prefix}/${image} ..." + curl -sf ${bmp_oss_url}/${bmp_oss_agent_prefix}/${image} -o $WORKSPACE/${bmp_cache_dir}/${image} || { + echo download ${bmp_oss_url}/${bmp_oss_agent_prefix}/${image} fail! + exit 1 + } + fi + done + fi + + return 0 +} + +post_start(){ + local service=$1 + + # init bootloader + if [ "$service" == "bmp-tftp" ]; then + #legacy x86_64 + [ -e $WORKSPACE/${bmp_cache_dir}/pxelinux.0 ] && cp -f $WORKSPACE/${bmp_cache_dir}/pxelinux.0 /var/lib/bmp/bmp-tftp/ + + #uefi x86_64 + mkdir -p /var/lib/bmp/bmp-tftp/uefi/x86_64 + [ -e $WORKSPACE/${bmp_cache_dir}/grubx64.efi ] && cp -f $WORKSPACE/${bmp_cache_dir}/grubx64.efi /var/lib/bmp/bmp-tftp/uefi/x86_64/grubx64.efi + + #arm64 + mkdir -p /var/lib/bmp/bmp-tftp/uefi/arm64 + [ -e $WORKSPACE/${bmp_cache_dir}/grubaa64.efi ] && cp -f $WORKSPACE/${bmp_cache_dir}/grubaa64.efi /var/lib/bmp/bmp-tftp/uefi/arm64/grubaa64.efi + + #loongarch64 + mkdir -p /var/lib/bmp/bmp-tftp/uefi/loongarch64 + [ -e $WORKSPACE/${bmp_cache_dir}/BOOTLOONGARCH64.EFI ] && cp -f $WORKSPACE/${bmp_cache_dir}/BOOTLOONGARCH64.EFI /var/lib/bmp/bmp-tftp/uefi/loongarch64/BOOTLOONGARCH64.EFI + fi + + + # init LiveOS images + if [ "$service" == "bmp-tftp" ]; then + # x86_64 + [ -e $WORKSPACE/${bmp_cache_dir}/${bmp_kernel_name_x86} ] && cp -f $WORKSPACE/${bmp_cache_dir}/${bmp_kernel_name_x86} /var/lib/bmp/bmp-tftp/ + [ -e $WORKSPACE/${bmp_cache_dir}/${bmp_initramfs_name_x86} ] && cp -f $WORKSPACE/${bmp_cache_dir}/${bmp_initramfs_name_x86} /var/lib/bmp/bmp-tftp/ + + #arm64 + mkdir -p /var/lib/bmp/bmp-tftp/images/arm64 + [ -e $WORKSPACE/${bmp_cache_dir}/${bmp_kernel_name_arm64} ] && cp -f $WORKSPACE/${bmp_cache_dir}/${bmp_kernel_name_arm64} /var/lib/bmp/bmp-tftp/images/arm64/${bmp_kernel_name_arm64} + [ -e $WORKSPACE/${bmp_cache_dir}/${bmp_initramfs_name_arm64} ] && cp -f $WORKSPACE/${bmp_cache_dir}/${bmp_initramfs_name_arm64} /var/lib/bmp/bmp-tftp/images/arm64/${bmp_initramfs_name_arm64} + + #loongarch64 + mkdir -p /var/lib/bmp/bmp-tftp/images/loongarch64 + [ -e $WORKSPACE/${bmp_cache_dir}/${bmp_kernel_name_loonarch64} ] && cp -f $WORKSPACE/${bmp_cache_dir}/${bmp_kernel_name_loonarch64} /var/lib/bmp/bmp-tftp/images/loongarch64/${bmp_kernel_name_loonarch64} + [ -e $WORKSPACE/${bmp_cache_dir}/${bmp_initramfs_name_loonarch64} ] && cp -f $WORKSPACE/${bmp_cache_dir}/${bmp_initramfs_name_loonarch64} /var/lib/bmp/bmp-tftp/images/loongarch64/${bmp_initramfs_name_loonarch64} + fi + + # init GuestOS image && device_import template && bmp-agent + if [ "$service" == "bmp-image" ]; then + # copy GuestOS + for image in ${bmp_guestos_images[@]};do + [ -e /var/lib/bmp/bmp-image/${image} ] || cp $WORKSPACE/${bmp_cache_dir}/${image} /var/lib/bmp/bmp-image/ + done + images=$(find /var/lib/bmp/bmp-image/ -name "*.tar.xz") + [ -z "$images" ] && echo "error image not find" && exit 1 + + # copy device_import template + [ -e $WORKSPACE/${bmp_data_dir}/device_import.xlsx ] && cp -f $WORKSPACE/${bmp_data_dir}/device_import.xlsx /var/lib/bmp/bmp-image/ + + # copy bmp-agent + for image in ${bmp_agent_images[@]}; do + [ -e /var/lib/bmp/bmp-image/${image} ] || cp $WORKSPACE/${bmp_cache_dir}/${image} /var/lib/bmp/bmp-image/ + done + fi + + #init db + if [ "$service" == "bmp-db" ]; then + if [ -e $WORKSPACE/sql/bmp.sql ];then + #wait for db to be ready + container_name="bmp-bmp-db-1" + [ "$compose_v1" -lt 2 ] && container_name="bmp_bmp-db_1" + retry=60 + while [ $retry -gt 0 ];do + docker exec -i $container_name sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD" $MYSQL_DATABASE -e "show tables"' &> /dev/null && break + retry=$(($retry-1)) + sleep 2; + done + if [ $retry -le 0 ]; then + echo "error! bmp-db is not ready" + return 1 + fi + + # 检测数据库是否存在,防止数据被覆盖 + n=$(docker exec -i $container_name sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD" $MYSQL_DATABASE -e "show tables"' 2>/dev/null | wc -l) + if [ $n -lt 2 ]; then + echo "exec sql ..." + docker exec -i $container_name sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD" $MYSQL_DATABASE' < $WORKSPACE/sql/bmp.sql || true + fi + fi + fi + + # check status + n=$($COMPOSE $COMPOSE_OPTS ps $service | grep -P 'running|Up' | wc -l) + if [ $n -eq 0 ]; then + $COMPOSE $COMPOSE_OPTS up -d --quiet-pull $service + echo "$service start again" + fi + + return +} + +do_start(){ + for service in ${SERVICES[@]};do + pre_start $service + done + echo ${bmp_db_image} + $COMPOSE $COMPOSE_OPTS up -d --quiet-pull ${SERVICES[@]} + for service in ${SERVICES[@]};do + post_start $service + done +} + +do_stop(){ + $COMPOSE $COMPOSE_OPTS stop ${SERVICES[@]} +} + +do_restart(){ + do_stop + do_start +} + +do_clean(){ + for service in ${SERVICES[@]}; do + [ -e /var/lib/bmp/$service ] && rm -rf /var/lib/bmp/$service + [ -e /var/log/bmp/$service ] && rm -rf /var/log/bmp/$service + done + echo do_clean done +} + +do_uninstall(){ + do_stop + for s in ${SERVICES[@]};do + container_id=$($COMPOSE $COMPOSE_OPTS ps -a -q $s) + image=$($COMPOSE $COMPOSE_OPTS images $s | awk 'NR==2{print $2":"$3}') + [ -n "$container_id" ] && docker rm $container_id + [ -n "$image" ] && docker rmi $image + done + do_clean +} + +do_reinstall(){ + do_uninstall + do_start +} + +do_status(){ + is_ok=true + for s in ${SERVICES[@]}; do + n=$($COMPOSE $COMPOSE_OPTS ps $s | grep -P 'running|Up' | wc -l) + if [ $n -eq 1 ]; then + status="running" + else + status="not running" + fi + printf "%-20s%s\n" "$s" "$status" + [ "$status" != "running" ] && is_ok=false + done + [ "$is_ok" = "false" ] && return 1 + return 0 +} + +do_images(){ + $COMPOSE $COMPOSE_OPTS images ${SERVICES[@]} +} + +do_config(){ + $COMPOSE $COMPOSE_OPTS config ${SERVICES[@]} +} + +main(){ + init $@ + do_$COMMAND +} + +# 支持多架构 +if [ "$ARCH" == "x86_64" ] || [ "$ARCH" == "aarch64" ] || [ "$ARCH" == "loongarch64" ];then + main $@ +else + echo "architecture $ARCH is not supported!" + exit 1 +fi diff --git a/bmp-deploy/config/image.cfg b/bmp-deploy/config/image.cfg new file mode 100644 index 0000000..b56aae9 --- /dev/null +++ b/bmp-deploy/config/image.cfg @@ -0,0 +1,118 @@ +# oss +# internal +bmp_oss_url=https://bmp.s3-internal.cn-north-1.jdcloud-oss.com +# public network +bmp_oss_url=https://bmp.s3.cn-north-1.jdcloud-oss.com + +# local cache dir +bmp_cache_dir=cache + +# local data dir +bmp_data_dir=data + +# bootloader +bmp_bootloader_prefix=bootloader +bmp_bootloader_images=( + BOOTLOONGARCH64.EFI + grubaa64.efi + grubx64.efi + pxelinux.0 +) + +# LiveOS image +bmp_oss_liveos_prefix=LiveOS + +bmp_kernel_name_x86=v2.0.7-centos_7_9-2024082914-vmlinuz +bmp_initramfs_name_x86=v2.0.7-centos_7_9-2024082914-initramfs.gz + +bmp_kernel_name_arm64=v2.0.7-centos_7_9_arm64-2024082914-vmlinuz +bmp_initramfs_name_arm64=v2.0.7-centos_7_9_arm64-2024082914-initramfs.gz + +bmp_kernel_name_loonarch64=vmlinuz-loongarch +bmp_initramfs_name_loonarch64=initramfs-loongarch.gz + +bmp_liveos_images=( + ${bmp_kernel_name_x86} + ${bmp_initramfs_name_x86} + ${bmp_kernel_name_arm64} + ${bmp_initramfs_name_arm64} + ${bmp_kernel_name_loonarch64} + ${bmp_initramfs_name_loonarch64} +) + +# GuestOS image +bmp_oss_guestos_prefix=GuestOS +bmp_images_x86=( + v1.7.0-centos-7.9-2022070716.tar.xz + v1.7.0-ubuntu-18.04-2022062709.tar.xz +) +bmp_images_arm64=( + v1.7.0-centos-7.9-arm-2023080716.tar.xz + v1.7.0-ubuntu-18.04-arm-2023081111.tar.xz +) +bmp_images_loonarch64=( + v1.7.0-loongnix-8.4-2023110218.tar.xz +) +bmp_guestos_images=( + ${bmp_images_x86[@]} + ${bmp_images_arm64[@]} + ${bmp_images_loonarch64[@]} +) + +# app image +[ -v TAG ] || TAG=${BMP_VERSION} +bmp_registry=bmp-cn-north-1.jcr.service.jdcloud.com +[ -v BMP_REGISTRY ] && bmp_registry=$BMP_REGISTRY +bmp_rsyslog_image=${bmp_registry}/bmp-rsyslog:${TAG} +bmp_driver_image=${bmp_registry}/bmp-driver:${TAG} +bmp_dhcp_agent_image=${bmp_registry}/bmp-dhcp-agent:${TAG} +bmp_openapi_image=${bmp_registry}/bmp-openapi:${TAG} +bmp_openapi_console_image=${bmp_registry}/bmp-openapi-console:${TAG} +bmp_scheduler_image=${bmp_registry}/bmp-scheduler:${TAG} +bmp_console_api_image=${bmp_registry}/bmp-console-api:${TAG} +bmp_operation_api_image=${bmp_registry}/bmp-operation-api:${TAG} +bmp_console_web_image=${bmp_registry}/bmp-console-web:${TAG} +bmp_operation_web_image=${bmp_registry}/bmp-operation-web:${TAG} +bmp_oob_alert_image=${bmp_registry}/oob-log-alert:${TAG} +bmp_oob_agent_image=${bmp_registry}/oob-log-agent:${TAG} + +bmp_monitor_proxy_image=${bmp_registry}/bmp-monitor-proxy:${TAG} +bmp_pronoea_image=${bmp_registry}/bmp-pronoea:${TAG} +bmp_tftp_image=${bmp_registry}/bmp-tftp:${TAG} + +oob_log_alert_image=${bmp_oob_alert_image} +oob_log_agent_image=${bmp_oob_agent_image} + +# middleware image +[ -v BASE_REGISTRY ] && base_registry=$BASE_REGISTRY +ARCH=$(uname -i) + bmp_redis_image=${base_registry}/redis:7.0-alpine + bmp_mq_image=${base_registry}/rabbitmq:3.11-management-alpine + bmp_image_image=${base_registry}/nginx:1.22-alpine + bmp_pushgateway_image=quay.io/prometheus/pushgateway:v1.9.0 + bmp_alertmanager_image=quay.io/prometheus/alertmanager:v0.27.0 + bmp_prometheus_image=quay.io/prometheus/prometheus:v2.52.0 + +case $ARCH in + x86_64) + bmp_db_image=${base_registry}/mysql:5.7-debian + ;; + aarch64) + bmp_db_image=${base_registry}/mysql:8.1-oracle + ;; + loonarch64) + bmp_db_image=cr.loongnix.cn/library/mysql:5.7.39 + bmp_redis_image=cr.loongnix.cn/library/redis:7.0-alpine + bmp_mq_image=cr.loongnix.cn/library/rabbitmq:3.8.2-management-alpine + bmp_tftp_image=${bmp_registry}/jdcloudbmp/bmp-tftp:latest-loongarch64 + bmp_image_image=cr.loongnix.cn/library/nginx:1.23.1-alpine + ;; +esac + +# bmp-agent +bmp_oss_agent_prefix=others +bmp_agent_images=( + bmp-agent.bin + bmp-agent.bin.arm + bmp-agent-windows.tgz +) diff --git a/bmp-deploy/config/service.cfg b/bmp-deploy/config/service.cfg new file mode 100644 index 0000000..44247ed --- /dev/null +++ b/bmp-deploy/config/service.cfg @@ -0,0 +1,39 @@ +# third-party service +bmp_service_thirdparty=( + bmp-db + bmp-redis + bmp-mq + bmp-image + bmp-pushgateway + bmp-alertmanager + bmp-prometheus +) + +# app serveice +bmp_service_app=( + bmp-console-web + bmp-operation-web + bmp-console-api + bmp-operation-api + bmp-openapi + bmp-openapi-console + bmp-scheduler + bmp-driver + bmp-dhcp-agent + bmp-oob-alert + bmp-oob-agent + bmp-monitor-proxy + bmp-pronoea +) + +# other service +bmp_service_other=( + bmp-tftp + bmp-rsyslog +) + +bmp_service_all=( + ${bmp_service_thirdparty[@]} + ${bmp_service_other[@]} + ${bmp_service_app[@]} +) \ No newline at end of file diff --git a/bmp-deploy/data/device_import.xlsx b/bmp-deploy/data/device_import.xlsx new file mode 100644 index 0000000..b1d3f49 Binary files /dev/null and b/bmp-deploy/data/device_import.xlsx differ diff --git a/bmp-deploy/doc/bm-deploy.md b/bmp-deploy/doc/bm-deploy.md new file mode 100644 index 0000000..7f7e885 --- /dev/null +++ b/bmp-deploy/doc/bm-deploy.md @@ -0,0 +1,22 @@ +# [BMP Installation Guide](main.md) - BM Node Deployment Process +The BMP BM node deployment process is shown in the following diagram: + + +![Deployment Process](picture/bm-deploy.png) +BMP BM Node Deployment Process Diagram + +## Deployment Process Explanation +1. The client (bmp-console-web) initiates a deployment request, which is received by bmp-console-api. +2. bmp-console-api checks the request parameters, and if they pass, forwards the request to bmp-openapi. +3. bmp-openapi performs permission checks and other operations, generates deployment parameters, and sends them to bmp-scheduler. +4. bmp-scheduler schedules the deployment task, generates a series of deployment instructions, and sends them to bmp-dhcp-agent, bmp-driver, and bmp-agent through the bmp-mq service. +5. bmp-dhcp-agent receives the instructions, sets up its built-in DHCP server so that the BM node can obtain the correct IP configuration and TFTP address (bmp-tftp address) during the PXE boot phase. +6. bmp-driver receives the instructions, sets the BM node to PXE boot, and restarts it. +7. The BM node performs a PXE boot, and the PXEClient built into the network card starts up, sending a DHCP request broadcast. The built-in DHCP server in bmp-dhcp-agent receives the DHCP request and responds with the corresponding IP configuration and TFTP address. +8. The PXEClient configures its own IP, and then downloads the PXE boot program and executes it. The PXE boot program continues to download other boot parameters from bmp-tftp, downloads the kernel and initramfs, starts the memory operating system, and the bmp-agent service built into the memory operating system begins to start up. +9. bmp-agent receives the instructions and performs subsequent BM node deployment operations, such as setting up RAID and partitioning. +10. bmp-agent downloads the customer operating system image file from bmp-image, writes it to the BM node's disk, and then initializes the customer operating system. +11. bmp-agent executes a restart, completing the operating system installation. + +### Previous section [Service Management](service-manage.md) +### Next section [Troubleshooting](troubleshoot.md) \ No newline at end of file diff --git a/bmp-deploy/doc/bmp-deploy.md b/bmp-deploy/doc/bmp-deploy.md new file mode 100644 index 0000000..92ad39d --- /dev/null +++ b/bmp-deploy/doc/bmp-deploy.md @@ -0,0 +1,30 @@ +# bmp-deploy文件和目录说明 +## 文件和目录列表 +~~~ +bmp-deploy目录 +├── bmp-deploy.sh +├── cache +├── config +├── data +├── docker-compose.yml +├── env +├── .env +├── ReleaseNotes +├── script +├── sql +├── template +└── tool +~~~ +## 文件和目录说明 +* bmp-deploy.sh 主部署脚本 +* cache GuestOS镜像和LiveOS镜像缓存目录 +* config 配置目录 +* data 其它二进制文件缓存目录,包含pxe引导程序,设备导入模板 +* docker-compose.yml docker-compose服务编排文件 +* env 各组件环境变量目录 +* .env docker-compose环境变量主配置文件 +* ReleaseNotes 版本发布信息 +* script 各组件初始化脚本目录 +* sql 数据库初始化脚本目录 +* template 模板文件目录 +* tool 工具目录 diff --git a/bmp-deploy/doc/config.md b/bmp-deploy/doc/config.md new file mode 100644 index 0000000..f69b1cb --- /dev/null +++ b/bmp-deploy/doc/config.md @@ -0,0 +1,85 @@ +# [BMP Installation Guide](main.md) - Configuration Management +The `.env` file contains various configuration parameters for BMP. +~~~ +BMP_HOST_IP=xxx.xxx.xxx.xxx +BMP_VERSION=dev +COMPOSE_PROJECT_NAME=bmp +BMP_DB_HOST=bmp-db +BMP_DB_PORT=3306 +BMP_DB_USER=bmp_rw +BMP_DB_PASSWORD='LpK9Jq12Zf' +BMP_DB_NAME=bmp +BMP_REDIS_HOST=bmp-redis +BMP_REDIS_PORT=6379 +BMP_REDIS_PASSWORD='LpK9Jq12Zf' +BMP_MQ_HOST=bmp-mq +BMP_MQ_PORT=5672 +BMP_MQ_USER=bmp +BMP_MQ_PASSWORD='LpK9Jq12Zf' +BMP_MQ_VHOST=/bmp +BMP_OMAPI_HOST=bmp-dhcp-agent +BMP_OMAPI_PORT=7911 +BMP_OMAPI_TOKEN="LpK9Jq12Zf" +BMP_OPENAPI_HOST=bmp-openapi +BMP_OPENAPI_PORT=8801 +BMP_OPENAPI_CONSOLE_HOST=bmp-openapi-console +BMP_OPENAPI_CONSOLE_PORT=8802 +BMP_OOB_ALERT_HOST=bmp-oob-alert +BMP_OOB_ALERT_PORT=8804 +BMP_MQ_EXCHANGE_ROUTING_KEY=idc-vm4xsulx1k2d9z4xkctrttig02zl +BMP_IMAGE_PORT=10000 +BMP_MONITOR_PROXY_PORT=8805 +BMP_PROMETHEUS_HOST=bmp-prometheus +BMP_PROMETHEUS_PORT=9090 +BMP_PROMETHEUS_DATA_DIR=/data/prometheus +BMP_PUSHGATEWAY_HOST=bmp-pushgateway +BMP_PUSHGATEWAY_PORT=9091 +BMP_ALERTMANAGER_HOST=bmp-alertmanager +BMP_ALERTMANAGER_PORT=9093 +BMP_PRONOEA_HOST=bmp-pronoea +BMP_PRONOEA_PORT=9999 +~~~ + +## Configuration Explanation: +| Configuration Name | Description | +|-------------------------------------------|--------------------------------------------------------| +| BMP_HOST_IP | Manager node IP, please configure it as the management network card IP, BMP various service components listen on this IP | +| BMP_VERSION | The version of BMP to be installed, please do not modify it randomly | +| COMPOSE_PROJECT_NAME | Docker Compose project name, default value is bmp, please do not modify | +| BMP_DB_HOST | BMP-DB IP/hostname, please do not modify | +| BMP_DB_PORT | BMP-DB port, please do not modify | +| BMP_DB_USER | BMP-DB username | +| BMP_DB_PASSWORD | BMP-DB user password | +| BMP_DB_NAME | BMP-DB database name, please do not modify | +| BMP_REDIS_HOST | BMP-Redis IP/hostname, please do not modify | +| BMP_REDIS_PORT | BMP-Redis port, please do not modify | +| BMP_REDIS_PASSWORD | BMP-Redis password | +| BMP_MQ_HOST | BMP-MQ IP/hostname, please do not modify | +| BMP_MQ_PORT | BMP-MQ port, please do not modify | +| BMP_MQ_USER | BMP-MQ username | +| BMP_MQ_PASSWORD | BMP-MQ password | +| BMP_MQ_VHOST | BMP-MQ vhost name, please do not modify | +| BMP_OMAPI_HOST | DHCP OMAPI service IP/hostname, please do not modify | +| BMP_OMAPI_PORT | DHCP OMAPI service port, please do not modify | +| BMP_OMAPI_TOKEN | DHCP OMAPI authentication token | +| BMP_OPENAPI_HOST | BMP-OpenAPI IP/hostname, please do not modify | +| BMP_OPENAPI_PORT | BMP-OpenAPI port, please do not modify | +| BMP_OPENAPI_CONSOLE_HOST | BMP-OpenAPI-Console IP/hostname, please do not modify | +| BMP_OPENAPI_CONSOLE_PORT | BMP-OpenAPI-Console port, please do not modify | +| BMP_OOB_ALERT_HOST | BMP-OOB-Alert IP/hostname, please do not modify | +| BMP_OOB_ALERT_PORT | BMP-OOB-Alert port, please do not modify | +| BMP_MQ_EXCHANGE_ROUTING_KEY | MQ routing key, this value should be equal to idc_id, please do not modify | +| BMP_IMAGE_PORT | BMP image server port, please do not modify | +| BMP_MONITOR_PROXY_PORT | BMP-monitor-proxy port, please do not modify | +| BMP_PROMETHEUS_HOST | BMP-Prometheus IP/hostname, please do not modify | +| BMP_PROMETHEUS_PORT | BMP-Prometheus port, please do not modify | +| BMP_PROMETHEUS_DATA_DIR | BMP-Prometheus data storage path, this path requires a large amount of storage space, please modify according to actual needs | +| BMP_PUSHGATEWAY_HOST | BMP-Pushgateway IP/hostname, please do not modify | +| BMP_PUSHGATEWAY_PORT | BMP-Pushgateway port, please do not modify | +| BMP_ALERTMANAGER_HOST | BMP-Alertmanager IP/hostname, please do not modify | +| BMP_ALERTMANAGER_PORT | BMP-Alertmanager port, please do not modify | +| BMP_PRONOEA_HOST | BMP-Pronoea IP/hostname, please do not modify | +| BMP_PRONOEA_PORT | BMP-Pronoea port, please do not modify | + +## Note +* The values of BMP_DB_PASSWORD, BMP_REDIS_PASSWORD, BMP_MQ_PASSWORD, and BMP_OMAPI_TOKEN can only consist of **uppercase and lowercase letters and digits**. Including special characters may cause errors. \ No newline at end of file diff --git a/bmp-deploy/doc/deploy-architecture.md b/bmp-deploy/doc/deploy-architecture.md new file mode 100644 index 0000000..d3917f7 --- /dev/null +++ b/bmp-deploy/doc/deploy-architecture.md @@ -0,0 +1,32 @@ +# [BMP Installation Guide](main.md) - Deployment Architecture + +The standard deployment architecture consists of one manager node and multiple BM nodes. The manager node runs all BMP components (except for BMP-agent); the BM nodes only run BMP-agent (running in LiveOS) during the operating system installation phase, performing various operations required for installing GuestOS, and after installation, the BM nodes are taken over by GuestOS. + +![Deployment Architecture](picture/bmp-deplopy-architecture.png) + +## Component Description + +* bmp-console-web: Control console front-end pages. Built using the Vue3 scaffolding, it includes login pages, project management pages, personal center pages, instance management pages, and other page functions. +* bmp-console-api: Control console API. Go language back-end business, calling openapi interfaces to implement control console-related interfaces. Assembles various data needed by bmp-console-web, requiring multi-language adaptation. +* bmp-operation-web: Operation platform front-end pages. Built using the Vue3 scaffolding, it includes login pages, data center management pages, machine model management pages, image management pages, device management pages, role management pages, user management pages, and other page functions. +* bmp-operation-api: Operation platform API. Go language back-end business, calling openapi interfaces to implement operation platform-related interfaces. Assembles various data needed by bmp-operation-web, requiring multi-language adaptation. +* bmp-openapi: bmp-openapi is the core module of BMP. It implements RESTful API format interfaces that comply with the Swagger 2.0 specification. It provides all basic functions of BMP externally. Internally, it performs database operations and calls bmp-scheduler to complete instance lifecycle management-related operations. +* bmp-scheduler: Installation scheduling module. It receives instance lifecycle management requests from bmp-openapi, converts the upper-layer requests into corresponding commands, and drives the commands to execute, coordinating with the lower-level bmp-driver and bmp-agent to complete installation, reinstallation, power on, power off, and other functions. +* bmp-driver: Single data center application, which needs to be deployed in multiple sets in the case of multiple data centers. It receives MQ messages and performs power on, power off, restart, and PXE boot setting operations on servers in its own data center. +* bmp-dhcp-agent: Single data center application. Before installation, it needs to update the DHCP configuration in advance, storing the MAC-IP association relationship in the DHCP configuration. Subsequently, LiveOS can obtain the IP address from DHCP. +* bmp-db: Database +* bmp-redis: Redis cache +* bmp-mq: Message middleware +* bmp-tftp: TFTP server, storing PXE boot-related files, including the PXE boot program, PXE boot configuration, LiveOS kernel, and initramfs. +* bmp-image: HTTP server, storing GuestOS image files +* bmp-rsyslog: rsyslog log component +* bmp-oob-alert: Out-of-band alert component +* bmp-oob-agent: Out-of-band monitoring information collection component +* bmp-monitor-proxy: In-band monitoring forwarding component +* bmp-prometheus: Monitoring data collection component +* bmp-pushgateway: Collects monitoring data from bmp-monitor-proxy and pushes it to Prometheus +* bmp-alertmanager: Alert component +* bmp-pronoea: Receives alert information from bmp-alertmanager, converts the format, and transmits it to bmp-openapi + +### Previous section [Overview](overview.md) +### Next section [Network Architecture](network-architecture.md) \ No newline at end of file diff --git a/bmp-deploy/doc/deploy.md b/bmp-deploy/doc/deploy.md new file mode 100644 index 0000000..ade3eac --- /dev/null +++ b/bmp-deploy/doc/deploy.md @@ -0,0 +1,87 @@ +# [BMP Installation Guide](main.md) - Deploying BMP +## Deployment Instructions +* All commands are executed with root privileges +## Example Explanation +This example includes one manager node and one BM node, with the network structure shown below: + +![Example Network Structure](picture/network-deploy.png) +In this network structure, tor1 represents the upstream switch of the BM node's eth0 network card. +* Manager node + eth0 IP: 192.168.14.80/27 +* BM node + ipmi IP: 192.168.11.130/27 +* tor1 + VLAN ID: 200 + VLAN 200 interface IP: 192.168.12.129/27 + +## Deploying Manager Node +* SSH into the manager node +* Install docker-compose + * CentOS 7 +~~~ +yum install -y yum-utils +yum-config-manager \ + --add-repo \ + https://download.docker.com/linux/centos/docker-ce.repo +yum install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin +systemctl start docker +~~~ +* Loongnix 8.4 +~~~ +yum install -y docker-ce docker-ce-cli containerd.io +curl https://bmp.s3-internal.cn-north-1.jdcloud-oss.com/data/docker-compose_v2.20.2_loongarch64 -o /usr/local/bin/docker-compose +chmod +x /usr/local/bin/docker-compose +systemctl start docker +~~~ + +* Download the deployment script, extract it, and enter the corresponding directory +~~~ +curl https://bmp.s3-internal.cn-north-1.jdcloud-oss.com/release/bmp-deploy_${version}.tar.gz -o bmp-deploy.tar.gz +mkdir bmp-deploy +tar -xvf bmp-deploy.tar.gz -C./bmp-deploy +cd bmp-deploy +~~~ +Directory contents explanation: [bmp-deploy Files and Directories Explanation](bmp-deploy.md) + +* Modify the configuration + Edit the.env file and modify BMP_HOST_IP to the manager node's management network card IP. In this example, it is xxx.xxx.xxx.xxx +~~~ +BMP_HOST_IP=xxx.xxx.xxx.xxx +~~~ +For more configuration options, please refer to [Configuration Management](config.md) +* Install BMP +~~~ +chmod +x./bmp-deploy.sh +./bmp-deploy.sh start all +~~~ + +* Check the status of each service +~~~ +./bmp-deploy.sh status all +~~~ +In normal circumstances, the status of all services should be running. If some services are not running, please refer to [Troubleshooting](troubleshoot.md) +## Accessing BMP +Note: Default username: admin, password: df9Ydfd$c + +Control Console: http://manager_ip:8080. In this example, it is http://xxx.xxx.xxx.xxx:8080. + +Operation Platform: http://manager_ip:8081. In this example, it is http://xxx.xxx.xxx.xxx:8081. + +## Uninstalling BMP +~~~ +./bmp-deploy.sh uninstall all +~~~ + +## Configuring DHCP Relay (not required if the manager and node management network cards are on the same 2-layer network) +* Log in to tor1 and view the DHCP relay for VLAN 200. Check if the relay address is the manager node's management network card IP (xxx.xxx.xxx.xxx in this example) + ![Viewing tor1 Example](picture/example-tor1.png) + +## Adding BM Node to BMP Platform +Log in to the BMP Operation Platform, go to the Device Management interface, and import BM node information +### Note: +* Internal IPv4, network subnet mask, and gateway: Please fill in the correct addresses so that PXEClient, LiveOS, and GuestOS running on the BM node can normally access the manager network. In this example, Internal IPv4 can be any available IP in VLAN 200 (10.208.12.130 - 10.208.12.158), such as 10.208.12.130, and the subnet mask and gateway should be filled with the VLAN 200 subnet mask and gateway (255.255.255.224 and 10.208.12.129 in this example) +* [Device Information Table for This Example](device_import.xlsx) + + +### Previous section [Network Architecture](network-architecture.md) +### Next section [Service Management](service-manage.md) \ No newline at end of file diff --git a/bmp-deploy/doc/main.md b/bmp-deploy/doc/main.md new file mode 100644 index 0000000..5afb1db --- /dev/null +++ b/bmp-deploy/doc/main.md @@ -0,0 +1,10 @@ +# BMP Installation Guide +## [Overview](overview.md) +## [Deployment Architecture](deploy-architecture.md) +## [Network Architecture](network-architecture.md) +## [Deploying BMP](deploy.md) +## [Service Management](service-manage.md) +## [BM Deployment Process](bm-deploy.md) +## [Troubleshooting](troubleshoot.md) +## [Practical Tools](tool.md) +## [Configuration Management](config.md) diff --git a/bmp-deploy/doc/network-architecture.md b/bmp-deploy/doc/network-architecture.md new file mode 100644 index 0000000..c8d4183 --- /dev/null +++ b/bmp-deploy/doc/network-architecture.md @@ -0,0 +1,18 @@ +# [BMP Installation Guide](main.md) - Network Architecture +The standard network architecture of BMP is shown in the following diagram: + +![Network Architecture Diagram](picture/network-architecture.png) + +* The out-of-band network card ipmi, management network card eth0 of the physical machine, and the management network card eth0 of the manager node are all in the same 3-layer management network. +* The various BMP components running inside the manager node are containerized and expose their service ports to the management network through docker-proxy and the eth0 network card. +* The BMC management system built into the BM node exposes itself to the management network through the ipmi network card. +* Other services running on the BM node expose themselves to the management network through the eth0 network card. +* To ensure that the system running on the BM node can obtain IP configuration from the DHCP server built into the bmp-dhcp-agent container on the manager node, the upstream switch of the BM node's eth0 network card may need to be configured with DHCP relay, with the relay address set to the management IP of the manager node. +* At the beginning of the installation process, bmp-driver accesses the BM node's out-of-band IP through the management network to set the boot mode and control power on/off. +* During the PXE boot stage, the PXEClient built into the BM node's eth0 network card accesses the DHCP server built into the bmp-dhcp-agent container through the management network to obtain IP configuration and the download address of the PXE boot program, sets the eth0 IP, and downloads the LiveOS kernel and initramfs from bmp-tftp, and then starts LiveOS. +* When LiveOS starts, it also obtains IP configuration from the DHCP server built into the bmp-dhcp-agent container and sets the eth0 IP. +* During the GuestOS installation stage, bmp-agent can obtain the necessary installation information from bmp-mq and can also download the GuestOS image from bmp-tftp. +* Regardless of whether PXEClient, LiveOS, or GuestOS is running, the IP address of the BM node's management network card eth0 remains the same, and the specific IP address is set in the Operation Platform - Device Management section. Please assign the correct IP address to the BM node to ensure that the system running on the BM node in each stage can work normally. + +### Previous section [Deployment Architecture](deploy-architecture.md) +### Next section [Deploying BMP](deploy.md) \ No newline at end of file diff --git a/bmp-deploy/doc/overview.md b/bmp-deploy/doc/overview.md new file mode 100644 index 0000000..86b0cb4 --- /dev/null +++ b/bmp-deploy/doc/overview.md @@ -0,0 +1,30 @@ +# [BMP Installation Guide](main.md) - Overview +## Glossary +* Manager node: The BMP management server, which runs all BMP components (except for BMP-agent) +* BM node: A bare metal server, a physical server used for normal operation, without an operating system before installation, running LiveOS during the installation process, and running GuestOS after installation +* GuestOS: The normal working operating system +* LiveOS: An in-memory operating system, which has BMP-agent pre-installed +* Out-of-band network card: A special network card on the physical server used for communication with BMC, also known as the IPMI network card +* Management network card: The standard network card on the physical server, located in the management network +* Management network: A 3-layer network, where the manager node's management network card communicates with the BM node's management network card through the management network +## Deployment Environment Requirements +### Manager Node +* Resource requirements + * CPU: 4 cores + * Memory: 8 GB + * Disk: 40 GB +* Operating system: CentOS 7.3+ +* Network requirements + * Must be able to access the public network + * Needs to open ports accessible by client browsers: 8080, 8081 + * Needs to open ports accessible by the management network: 10000, 5672, 67/udp, 69/udp +### BM Node +* Resource requirements + * CPU: 1 core + * Memory: 2 GB + * Disk: 40 GB + * Must have one out-of-band network card and one management network card + + +### Previous section [BMP Installation Guide](main.md) +### Next section [Deployment Architecture](deploy-architecture.md) \ No newline at end of file diff --git a/bmp-deploy/doc/picture/bm-deploy.png b/bmp-deploy/doc/picture/bm-deploy.png new file mode 100644 index 0000000..2bbed12 Binary files /dev/null and b/bmp-deploy/doc/picture/bm-deploy.png differ diff --git a/bmp-deploy/doc/picture/bmp-deplopy-architecture.png b/bmp-deploy/doc/picture/bmp-deplopy-architecture.png new file mode 100644 index 0000000..0563f6e Binary files /dev/null and b/bmp-deploy/doc/picture/bmp-deplopy-architecture.png differ diff --git a/bmp-deploy/doc/picture/example-network.png b/bmp-deploy/doc/picture/example-network.png new file mode 100644 index 0000000..77f8638 Binary files /dev/null and b/bmp-deploy/doc/picture/example-network.png differ diff --git a/bmp-deploy/doc/picture/example-tor1.png b/bmp-deploy/doc/picture/example-tor1.png new file mode 100644 index 0000000..d85bb5c Binary files /dev/null and b/bmp-deploy/doc/picture/example-tor1.png differ diff --git a/bmp-deploy/doc/picture/network-architecture.png b/bmp-deploy/doc/picture/network-architecture.png new file mode 100644 index 0000000..5c4a05b Binary files /dev/null and b/bmp-deploy/doc/picture/network-architecture.png differ diff --git a/bmp-deploy/doc/picture/network-deploy.png b/bmp-deploy/doc/picture/network-deploy.png new file mode 100644 index 0000000..f935d75 Binary files /dev/null and b/bmp-deploy/doc/picture/network-deploy.png differ diff --git a/bmp-deploy/doc/service-manage.md b/bmp-deploy/doc/service-manage.md new file mode 100644 index 0000000..bb1a31b --- /dev/null +++ b/bmp-deploy/doc/service-manage.md @@ -0,0 +1,129 @@ +# [BMP Installation Guide](main.md) - Service Management +bmp-deploy.sh Usage Instructions +~~~ +#./bmp-deploy.sh -h + +Usage: ./bmp-deploy.sh [-t|--tag TAG] COMMAND SERVICE... + +COMMAND: + start Install and start SERVICE + stop Stop SERVICE + restart Restart SERVICE + status Check SERVICE status + images Display SERVICE image + uninstall Uninstall SERVICE + reinstall Reinstall SERVICE + config Get SERVICE config + +SERVICE: + all All SERVICES + bmp-db + bmp-redis + bmp-mq + bmp-image + bmp-pushgateway + bmp-alertmanager + bmp-prometheus + bmp-tftp + bmp-rsyslog + bmp-console-web + bmp-operation-web + bmp-console-api + bmp-operation-api + bmp-openapi + bmp-openapi-console + bmp-scheduler + bmp-driver + bmp-dhcp-agent + bmp-oob-alert + bmp-oob-agent + bmp-monitor-proxy + bmp-pronoea +~~~ +## Stop Services +./bmp-deploy.sh stop all | [service...] +~~~ +# Stop the bmp-console-web service +./bmp-deploy.sh stop bmp-console-web + +# Stop the bmp-console-web and bmp-operation-web services +./bmp-deploy.sh stop bmp-console-web bmp-operation-web + +# Stop all services +./bmp-deploy.sh stop all +~~~ + +## Start Services +./bmp-deploy.sh start all | [service...] +~~~ +# Start the bmp-console-web service +./bmp-deploy.sh start bmp-console-web + +# Start the bmp-console-web and bmp-operation-web services +./bmp-deploy.sh start bmp-console-web bmp-operation-web + +# Start all services +./bmp-deploy.sh start all +~~~ + +## Restart Services +./bmp-deploy.sh restart all | [service...] +~~~ +# Restart the bmp-console-web service +./bmp-deploy.sh restart bmp-console-web +~~~ + +## Check Service Status +./bmp-deploy.sh status all | [service...] +~~~ +# Check the status of all services +./bmp-deploy.sh status all +~~~ + +## Check Service-Related Container Images +./bmp-deploy.sh images all | [service...] +~~~ +# Check the container image related to the bmp-console-web service +./bmp-deploy.sh images bmp-console-web +~~~ + +## Uninstall Services +./bmp-deploy.sh uninstall all | [service...] + +Note: Related data will also be deleted +~~~ +# Uninstall a single service, such as bmp-console-web +./bmp-deploy.sh uninstall bmp-console-web + +# Uninstall all services +./bmp-deploy.sh uninstall all +~~~ + +## Uninstall BMP (Uninstall All Services) +~~~ +cd /root/bmp-deploy/ +./bmp-deploy.sh uninstall all +cd /root +rm -rf bmp-deploy bmp-deploy*.tar.gz +rm -rf /var/log/bmp +~~~ + +## Reinstall Services (Uninstall + Install) +./bmp-deploy.sh reinstall all | [service...] +~~~ +# Reinstall a single service, such as bmp-console-web +./bmp-deploy.sh reinstall bmp-console-web +~~~ + +## Get Service Configuration +./bmp-deploy.sh config all | [service...] + +## Deploy BMP with a Specific Version +./bmp-deploy.sh start all | [service...] -t|--tag TAG +~~~ +# Deploy version 1.0 +./bmp-deploy.sh start all --tag 1.0 +~~~ + +### Previous section [Deploying BMP](deploy.md) +### Next section [BM Node Deployment Process](bm-deploy.md) \ No newline at end of file diff --git a/bmp-deploy/doc/tool.md b/bmp-deploy/doc/tool.md new file mode 100644 index 0000000..086c03a --- /dev/null +++ b/bmp-deploy/doc/tool.md @@ -0,0 +1,47 @@ +# [BMP Installation Guide](main.md) - Useful Tools +The `tool` directory contains various tool scripts for collecting device information, etc. + +## Collecting Device Information +`collect_device_info.sh` Usage Guide +~~~ +./collect_device_info.sh -h + +Usage: ./collect_device_info.sh --sn SN --iloIp iloIp --iloUser iloUser --iloPassword iloPassword --ip ip --mask mask --gateway gateway --mac MAC [--raidDriver raidDriver] + +~~~ + +Parameter Explanation: +~~~ +SN Device SN +iloIp Device iLO IP +iloUser Device iLO management username +iloPassword Device iLO management password +ip Device management interface 1 IP +mask Device management interface 1 IP subnet mask +gateway Device management interface 1 IP subnet gateway +MAC Device management interface 1 MAC +raidDriver Device RAID card driver, currently supported drivers include: sas2ircu sas3ircu megacli64 storcli64 perccli64 arcconf no_raid, default is megacli64 +~~~ + +Example: +~~~ +./collect_device_info.sh --sn 210235A3P6N1830002MH --iloIp 192.168.0.2 --iloUser xxx --iloPassword 'xxx' --ip 10.208.14.170 --mask 255.255.255.224 --gateway 10.208.14.161 --mac '3C:FD:FE:5E:C6:74' +~~~ + +After the device information collection task is completed (which may take 2-5 minutes), a file `/var/log/bmp/bmp-scheduler/disk_location_dir/SN` will be generated. This file contains the device's disk slot information. +~~~ +# cat /var/log/bmp/bmp-scheduler/disk_location_dir/210235A3P6N1830002MH +{"controllers":[{"adapter_id":"1","disk_info":"Controllers found: 1\n----------------------------------------------------------------------\nController information\n----------------------------------------------------------------------\n Controller Status : Optimal\n Controller Mode : Mixed\n Channel description : SCSI\n Controller Model : Adaptec SmartIOC 8i\n Controller Serial Number : Unknown\n Controller World Wide Name : 5600B036FAEDD000\n Physical Slot : 255\n Temperature : 61 C/ 141 F (Normal)\n Power Consumption : Not Applicable\n Power Mode : Unknown\n Power Mode Operational : Unknown\n Survival Mode : Unknown\n Host bus type : PCIe 3.0\n Host bus speed : 7880 MBps\n Host bus link width : 8 bit(s)/link(s)\n PCI Address (Bus:Device:Function) : 0:1:0:0\n I2C Address : 0xDE\n I2C Clock Speed...... +~~~ + +## Retry Command +`retry_command.sh` Usage Guide +~~~ +./retry_command.sh -h + +Usage: ./retry_command.sh Command_id + +~~~ + +### Previous section [Troubleshooting](troubleshoot.md) +### Next section [Configuration Management](config.md) diff --git a/bmp-deploy/doc/troubleshoot.md b/bmp-deploy/doc/troubleshoot.md new file mode 100644 index 0000000..f235e9f --- /dev/null +++ b/bmp-deploy/doc/troubleshoot.md @@ -0,0 +1,14 @@ +# [BMP Installation Guide](main.md) - Troubleshooting +* PXE boot failure +1. Is the boot mode of the machine set to BIOS? +2. Is the out-of-band network of the machine correctly configured? +3. Is the BMC (Baseboard Management Controller) of the machine functioning normally? +4. Are the network cables of the machine connected correctly? +* A service is not running normally +~~~ +./bmp-deploy.sh status all # Check which services are not running normally +./bmp-deploy.sh start ServiceName # Start the service +~~~ + +### Previous section [BM Node Deployment Process](bm-deploy.md) +### Next section [Practical Tools](tool.md) diff --git a/bmp-deploy/doc/zh/bm-deploy.md b/bmp-deploy/doc/zh/bm-deploy.md new file mode 100644 index 0000000..4994c97 --- /dev/null +++ b/bmp-deploy/doc/zh/bm-deploy.md @@ -0,0 +1,22 @@ +# [bmp安装指导](main.md) - 装机流程 +bmp装机流程如下图所示 + + +![装机流程](picture/bm-deploy.png) +bmp装机流程图 + +## 装机流程说明 +1.客户端(bmp-console-web)发起装机请求,bmp-console-api接收请求 +2.bmp-console-api检查请求参数,通过后将请求转发给bmp-openapi +3.bmp-openapi执行权限检查等操作,生成装机参数,发送给bmp-scheduler +4.bmp-scheduler调度装机任务,生成一系列装机指令,通过bmp-mq服务发送给bmp-dhcp-agent、bmp-driver和bmp-agent +5.bmp-dhcp-agent收到指令,设置内置的dhcp服务器,使得bm节点在pxe启动阶段能够获取正确的ip配置和tftp地址(bmp-tftp地址) +6.bmp-driver收到指令后,将bm节点设置为pxe启动并重启 +7.bm节点执行pxe启动,内置在网卡内的PXEClient启动,发送dhcp请求广播,bmp-dhcp-agent内置的dhcp服务器收到dhcp请求后,响应相应的ip配置和tftp地址 +8.PXEClient配置自身ip,之后从bmp-tftp下载pxe引导程序并执行,pxe引导程序继续从bmp-tftp获取其它引导参数,下载内核和initramfs,启动内存操作系统,内置在内存操作系统中bmp-agent服务开始启动 +9.bmp-agent接收指令,执行后续bm装机操作,如:设置raid,分区等 +10.bmp-agent从bmp-image下载客户操作系统镜像文件,写到bm节点磁盘中,然后初始化客户操作系统 +11.bmp-agent执行重启,完成操作系统安装 + +# 上一节 [服务管理](service-manage.md) +# 下一节 [故障排查](troubleshoot.md) \ No newline at end of file diff --git a/bmp-deploy/doc/zh/bmp-deploy.md b/bmp-deploy/doc/zh/bmp-deploy.md new file mode 100644 index 0000000..92ad39d --- /dev/null +++ b/bmp-deploy/doc/zh/bmp-deploy.md @@ -0,0 +1,30 @@ +# bmp-deploy文件和目录说明 +## 文件和目录列表 +~~~ +bmp-deploy目录 +├── bmp-deploy.sh +├── cache +├── config +├── data +├── docker-compose.yml +├── env +├── .env +├── ReleaseNotes +├── script +├── sql +├── template +└── tool +~~~ +## 文件和目录说明 +* bmp-deploy.sh 主部署脚本 +* cache GuestOS镜像和LiveOS镜像缓存目录 +* config 配置目录 +* data 其它二进制文件缓存目录,包含pxe引导程序,设备导入模板 +* docker-compose.yml docker-compose服务编排文件 +* env 各组件环境变量目录 +* .env docker-compose环境变量主配置文件 +* ReleaseNotes 版本发布信息 +* script 各组件初始化脚本目录 +* sql 数据库初始化脚本目录 +* template 模板文件目录 +* tool 工具目录 diff --git a/bmp-deploy/doc/zh/config.md b/bmp-deploy/doc/zh/config.md new file mode 100644 index 0000000..e45bfa4 --- /dev/null +++ b/bmp-deploy/doc/zh/config.md @@ -0,0 +1,88 @@ +# [bmp安装指导](main.md) - 配置管理 +.env文件包含bmp各种配置参数 +~~~ +BMP_HOST_IP=xxx.xxx.xxx.xxx +BMP_VERSION=dev +COMPOSE_PROJECT_NAME=bmp +BMP_DB_HOST=bmp-db +BMP_DB_PORT=3306 +BMP_DB_USER=bmp_rw +BMP_DB_PASSWORD='LpK9Jq12Zf' +BMP_DB_NAME=bmp +BMP_REDIS_HOST=bmp-redis +BMP_REDIS_PORT=6379 +BMP_REDIS_PASSWORD='LpK9Jq12Zf' +BMP_MQ_HOST=bmp-mq +BMP_MQ_PORT=5672 +BMP_MQ_USER=bmp +BMP_MQ_PASSWORD='LpK9Jq12Zf' +BMP_MQ_VHOST=/bmp +BMP_OMAPI_HOST=bmp-dhcp-agent +BMP_OMAPI_PORT=7911 +BMP_OMAPI_TOKEN="LpK9Jq12Zf" +BMP_OPENAPI_HOST=bmp-openapi +BMP_OPENAPI_PORT=8801 +BMP_OPENAPI_CONSOLE_HOST=bmp-openapi-console +BMP_OPENAPI_CONSOLE_PORT=8802 +BMP_OOB_ALERT_HOST=bmp-oob-alert +BMP_OOB_ALERT_PORT=8804 +BMP_MQ_EXCHANGE_ROUTING_KEY=idc-vm4xsulx1k2d9z4xkctrttig02zl +BMP_IMAGE_PORT=10000 +BMP_MONITOR_PROXY_PORT=8805 +BMP_PROMETHEUS_HOST=bmp-prometheus +BMP_PROMETHEUS_PORT=9090 +BMP_PROMETHEUS_DATA_DIR=/data/prometheus +BMP_PUSHGATEWAY_HOST=bmp-pushgateway +BMP_PUSHGATEWAY_PORT=9091 +BMP_ALERTMANAGER_HOST=bmp-alertmanager +BMP_ALERTMANAGER_PORT=9093 +BMP_PRONOEA_HOST=bmp-pronoea +BMP_PRONOEA_PORT=9999 +~~~ + +## 配置说明: +| 配置名 | 说明 | +|-----------------------------|-----------------------------------------------| +| BMP_HOST_IP | manager节点ip, 请配置为管理网卡ip,bmp各服务组件监听此ip | +| BMP_VERSION | 待安装的bmp版本,请勿随便修改 | +| COMPOSE_PROJECT_NAME | docker compose 项目名,默认值是bmp,请勿修改 | +| BMP_DB_HOST | bmp-db ip/域名,请勿修改 | +| BMP_DB_PORT | bmp-db 端口,请勿修改 | +| BMP_DB_USER | bmp-db 用户名 | +| BMP_DB_PASSWORD | bmp-db 用户密码 | +| BMP_DB_NAME | bmp-db 数据库名,请勿修改 | +| BMP_REDIS_HOST | bmp-redis ip/域名,请勿修改 | +| BMP_REDIS_PORT | bmp-redis 端口,请勿修改 | +| BMP_REDIS_PASSWORD | bmp-redis 密码 | +| BMP_MQ_HOST | bmp-mq ip/域名,请勿修改 | +| BMP_MQ_PORT | bmp-mq 端口,请勿修改 | +| BMP_MQ_USER | bmp-mq 用户名 | +| BMP_MQ_PASSWORD | bmp-mq 密码 | +| BMP_MQ_VHOST | bmp-mq vhost名,请勿修改 | +| BMP_OMAPI_HOST | dhcp omapi服务 ip/域名,请勿修改 | +| BMP_OMAPI_PORT | dhcp omapi服务端口,请勿修改 | +| BMP_OMAPI_TOKEN | dhcp omapi认证token | +| BMP_OPENAPI_HOST | bmp-openapi ip/域名,请勿修改 | +| BMP_OPENAPI_PORT | bmp-openapi 端口,请勿修改 | +| BMP_OPENAPI_CONSOLE_HOST | bmp-openapi-console ip/域名,请勿修改 | +| BMP_OPENAPI_CONSOLE_PORT | bmp-openapi-console 端口,请勿修改 | +| BMP_OOB_ALERT_HOST | bmp-oob-alert ip/域名,请勿修改 | +| BMP_OOB_ALERT_PORT | bmp-oob-alert 端口,请勿修改 | +| BMP_MQ_EXCHANGE_ROUTING_KEY | mq routing key, 此值应该等于idc_id,请勿修改 | +| BMP_IMAGE_PORT | bmp 镜像服务器端口, 请勿修改 | +| BMP_MONITOR_PROXY_PORT | bmp-monitor-proxy 端口,请勿修改 | +| BMP_PROMETHEUS_HOST | bmp_prometheus ip/域名,请勿修改 | +| BMP_PROMETHEUS_PORT | bmp_prometheus 端口,请勿修改 | +| BMP_PROMETHEUS_DATA_DIR | bmp_prometheus 数据存储路径,此路径需要的存储空间较大,建议根据实际情况修改 | +| BMP_PUSHGATEWAY_HOST | bmp_pushgateway ip/域名,请勿修改 | +| BMP_PUSHGATEWAY_PORT | bmp_pushgateway 端口,请勿修改 | +| BMP_ALERTMANAGER_HOST | bmp_alertmanager ip/域名,请勿修改 | +| BMP_ALERTMANAGER_PORT | bmp_alertmanager 端口,请勿修改 | +| BMP_PRONOEA_HOST | bmp_pronoea ip/域名,请勿修改 | +| BMP_PRONOEA_PORT | bmp_pronoea 端口,请勿修改 | + +## 注意 +* BMP_DB_PASSWORD, BMP_REDIS_PASSWORD, BMP_MQ_PASSWORD, BMP_OMAPI_TOKEN的值只能由 **大小字母和数字** 组成,包含特殊字符可能会导致错误。 + +# 上一节 [实用工具](tool.md) + diff --git a/bmp-deploy/doc/zh/deploy-architecture.md b/bmp-deploy/doc/zh/deploy-architecture.md new file mode 100644 index 0000000..e269e48 --- /dev/null +++ b/bmp-deploy/doc/zh/deploy-architecture.md @@ -0,0 +1,36 @@ +# [bmp安装指导](main.md) - 部署架构 + +标准部署架构由一个manger节点和多个bm节点组成。manager节点运行着所有bmp组件(除了bmp-agent);bm节点只在安装操作系统阶段运行着bmp-agent(运行在LiveOS中),执行安装GuestOS需要的各种操作,安装完成后会重启bm节点,之后bm节点被GusetOS接管。 + + +![部署架构](picture/bmp-deplopy-architecture.png) + +## 组件说明 + +* bmp-console-web 控制台前端页面。使用vue3脚手架搭建。包含登录页、项目管理页、个人中心页、实例管理页等页面功能。 +* bmp-console-api 控制台api。go语言后端业务,调用openapi接口实现控制台相关接口。为bmp-console-web拼装各类需要的数据,需要进行多语言适配。 +* bmp-operation-web 运营平台前端页面。使用vue3脚手架搭建,包含登录页、机房管理页、机型管理页、镜像管理页、设备管理页、角色管理页、用户管理页等页面功能。 +* bmp-operation-api 运营平台api。go语言后端业务,调用openapi接口实现运营平台相关接口。为bmp-operation-web拼装各类需要的数据,需要进行多语言适配。 +* bmp-openapi bmp-openapi是bmp的核心模块。实现了满足swagger2.0规范的restful api格式接口。对外提供了bmp所有基础功能。对内进行数据库操作、调用bmp-scheduler完成实例生命周期管理的相关操作。 +* bmp-scheduler 装机调度模块。承接bmp-openapi的实例生命周期管理请求,将上层请求转换为对应的commands,并且驱动commands执行,协同下层的bmp-driver,bmp-agent共同完成装机、重装、开机、关机等功能。 +* bmp-driver 单机房应用,在有多个机房情况下需要部署多套bmp-driver服务,接收mq,对本机房的服务器进行开机、关机、重启、设置pxe启动等操作。 +* bmp-dhcp-agent 单机房应用,装机之前需要提前更新dhcp配置,将Mac-IP关联关系存入dhcp配置中。之后liveOS才能从dhcp中获取到ip地址。 +* bmp-db 数据库 +* bmp-redis redis缓存 +* bmp-mq 消息中间件 +* bmp-tftp tftp服务器,存储着pxe引导需要的相关文件,包括pxe引导程序,pxe引导配置,LiveOS的内核和initramfs。 +* bmp-image http服务器,存储着GuestOS镜像 +* bmp-rsyslog rsyslog 日志组件 +* bmp-oob-alert 带外告警组件 +* bmp-oob-agent 带外监控信息采集组件 +* bmp-monitor-proxy 带内监控转发组件 +* bmp-prometheus 监控数据收集组件 +* bmp-pushgateway 从bmp-monitor-proxy收集监控数据,并推送到 Prometheus +* bmp-alertmanager 告警组件 +* bmp-pronoea 从bmp-alertmanager接收告警信息并转换格式,传到给bmp-openapi + +# 上一节 [概述](overview.md) +# 下一节 [网络架构](network-architecture.md) + + + diff --git a/bmp-deploy/doc/zh/deploy.md b/bmp-deploy/doc/zh/deploy.md new file mode 100644 index 0000000..eaab1cc --- /dev/null +++ b/bmp-deploy/doc/zh/deploy.md @@ -0,0 +1,87 @@ +# [bmp安装指导](main.md) - 部署bmp +## 部署说明 +* 所有命令用root权限执行 +## 示例说明 +本示例包含一个manager节点和一个bm节点,网络结构如下 + +![示例网络结构](picture/network-deploy.png) +此网络结构中,tor1分别代表bm节点eth0网卡上联交换机。 +* manager节点 +eth0 ip: 192.168.14.80/27 +* bm节点 +ipmi ip: 192.168.11.130/27 +* tor1 +vlan id: 200 +vlan 200接口ip: 192.168.12.129/27 + +## 部署manager节点 +* ssh登陆manager节点 +* 安装docker-compose + * centos 7 +~~~ +yum install -y yum-utils +yum-config-manager \ + --add-repo \ + https://download.docker.com/linux/centos/docker-ce.repo +yum install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin +systemctl start docker +~~~ + * loongnix 8.4 +~~~ +yum install -y docker-ce docker-ce-cli containerd.io +curl https://bmp.s3-internal.cn-north-1.jdcloud-oss.com/data/docker-compose_v2.20.2_loongarch64 -o /usr/local/bin/docker-compose +chmod +x /usr/local/bin/docker-compose +systemctl start docker +~~~ + +* 下载部署脚本,解压并进入到相应目录 +~~~ +curl https://bmp.s3-internal.cn-north-1.jdcloud-oss.com/release/bmp-deploy_${version}.tar.gz -o bmp-deploy.tar.gz +mkdir bmp-deploy +tar -xvf bmp-deploy.tar.gz -C ./bmp-deploy +cd bmp-deploy +~~~ +目录内文件说明:[bmp-deploy文件和目录说明](bmp-deploy.md) + +* 修改配置 +编辑.env文件,修改BMP_HOST_IP为manager节点管理网卡ip。本示例为xxx.xxx.xxx.xxx +~~~ +BMP_HOST_IP=xxx.xxx.xxx.xxx +~~~ +更多配置请参考[配置管理](config.md) +* 安装bmp +~~~ +chmod +x ./bmp-deploy.sh +./bmp-deploy.sh start all +~~~ + +* 检查各服务状态 +~~~ +./bmp-deploy.sh status all +~~~ +正常情况下所有服务的状态都是running,如果某些服务未运行,参考[故障排查](troubleshoot.md) +## 访问bmp +注:默认账号:admin,密码:df9Ydfd$c + +控制台:http://manager_ip:8080。本示例是http://xxx.xxx.xxx.xxx:8080。 + +运营平台: http://manager_ip:8081。本示例是http://xxx.xxx.xxx.xxx:8081。 + +## 卸载bmp +~~~ +./bmp-deploy.sh uninstall all +~~~ + +## 配置dhcp中继(manager与node的管理网口处于同一2层网络无需此步骤) +* 登陆tor1,查看vlan 200的dhcp中继,检查中继地址是否为manager节点管理网卡ip(本示例为xxx.xxx.xxx.xxx) +![查看tor1示例](picture/example-tor1.png) + +## 将bm节点添加到bmp平台 + 登陆bmp运营平台,进入设备管理界面,导入bmp节点信息 + ### 注意: + * 内网IPv4,网络子网掩码和网关 请填写正确的地址,使得运行在bm节点的PXEClient,LiveOS,GuestOS能够正常的访问manager网络。本示例中,内网IPv4 可选择vlan 200内任意可用ip(10.208.12.130 - 10.208.12.158),比如10.208.12.130,子网掩码和网关分别填写vlan 200子网掩码和网关(本示例是255.255.255.224和10.208.12.129) + * [本示例设备信息表](device_import.xlsx) + + +# 上一节 [网络架构](network-architecture.md) +# 下一节 [服务管理](service-manage.md) \ No newline at end of file diff --git a/bmp-deploy/doc/zh/main.md b/bmp-deploy/doc/zh/main.md new file mode 100644 index 0000000..6607353 --- /dev/null +++ b/bmp-deploy/doc/zh/main.md @@ -0,0 +1,10 @@ +# bmp安装指导 +## [概述](overview.md) +## [部署架构](deploy-architecture.md) +## [网络架构](network-architecture.md) +## [部署bmp](deploy.md) +## [服务管理](service-manage.md) +## [装机流程](bm-deploy.md) +## [故障排查](troubleshoot.md) +## [实用工具](tool.md) +## [配置管理](config.md) diff --git a/bmp-deploy/doc/zh/network-architecture.md b/bmp-deploy/doc/zh/network-architecture.md new file mode 100644 index 0000000..efaa774 --- /dev/null +++ b/bmp-deploy/doc/zh/network-architecture.md @@ -0,0 +1,19 @@ +# [bmp安装指导](main.md) - 网络架构 +bmp标准网络架构如下图所示 + +![网络架构图](picture/network-architecture.png) + +* 物理机的带外网卡ipmi、管理网卡eth0和manager节点的管理网卡eth0都在同一个3层管理网络中。 +* manager节点内各个bmp组件以容器方式运行,通过docker-proxy和eth0 +网卡将服务端口暴露给管理网络访问。 +* bm节点内置的bmc管理系统通过ipmi网卡暴露给管理网络访问 +* bm节点运行的其它服务通过eth0网卡暴露给管理网络访问 +* 为了确保bm节点运行的系统能够从manager节点的bmp-dhcp-agent容器内置的dhcp服务器获取ip配置,bm节点eth0网卡的上联交换机可能需要配置dhcp中继,中继地址为manager节点管理ip。 +* 装机开始时,bmp-driver通过管理网络访问bm节点的带外ip,设置物理机的引导模式和控制开关机。 +* pxe引导阶段,bm节点的eth0网卡内置的PXEClient通过管理网络访问bmp-dhcp-agent内置的dhcp服务器,获取ip配置和pxe引导程序下载地址,设置eth0 ip,并从bmp-tftp下载LiveOS内核和initramfs,之后启动LiveOS。 +* LiveOS启动时,也会从bmp-dhcp-agent内置的dhcp服务器获取ip配置并设置eth0 ip。 +* 安装GuesOS阶段,bmp-agent可以从bmp-mq获取所需安装信息,也可以从bmp-tftp下载GuestOS镜像 +* 无论运行的是PXEClient、LiveOS还是GustOS,bm节点的管理网卡eth0的ip都是一样的,具体ip地址是在运营平台-设备管理中设置。请给bm节点分配正确的ip地址,确保bm节点在各个阶段运行的系统都能正常工作。 + +# 上一节 [部署架构](deploy-architecture.md) +# 下一节 [部署bmp](deploy.md) \ No newline at end of file diff --git a/bmp-deploy/doc/zh/overview.md b/bmp-deploy/doc/zh/overview.md new file mode 100644 index 0000000..f2aba33 --- /dev/null +++ b/bmp-deploy/doc/zh/overview.md @@ -0,0 +1,29 @@ +# [bmp安装指导](main.md) - 概述 +## 名词解释 +* manager节点: bmp管理服务器,运行着所有bmp组件(除了bmp-agent) +* bm节点:裸金属服务器,正常工作用的物理服务器,未装机前无操作系统,装机阶段运行LiveOS,装机完成后运行GuestOS +* GuestOS: 正常工作的操作系统 +* LiveOS: 内存操作系统,里面预装了bmp-agent +* 带外网卡:物理服务器上用于与bmc通信的特殊网卡,又称ipmi网卡 +* 管理网卡:物理服务器的标准的网卡,处在管理网络中 +* 管理网络: 3层网络,manager节点的管理网卡与bm节点的管理网卡通过管理网络通信 +## 部署环境要求 +### manager节点 + * 资源要求 + * cpu: 4 核 + * 内存: 8 GB + * 磁盘: 40 GB + * 操作系统:CentOS 7.3+ + * 网络要求 + * 能够访问公网 + * 需要开放给客户端浏览器访问的端口:8080,8081 + * 需要开放给管理网络访问的端口: 10000, 5672,67/udp, 69/udp +### bm节点 + * 资源要求 + * cpu: 1 核 + * 内存: 2 GB + * 磁盘: 40 GB + * 拥有一个带外网卡和管理网卡 + +# 上一节 [bmp安装指导](main.md) +# 下一节 [部署架构](deploy-architecture.md) \ No newline at end of file diff --git a/bmp-deploy/doc/zh/picture/bm-deploy.png b/bmp-deploy/doc/zh/picture/bm-deploy.png new file mode 100644 index 0000000..2bbed12 Binary files /dev/null and b/bmp-deploy/doc/zh/picture/bm-deploy.png differ diff --git a/bmp-deploy/doc/zh/picture/bmp-deplopy-architecture.png b/bmp-deploy/doc/zh/picture/bmp-deplopy-architecture.png new file mode 100644 index 0000000..0563f6e Binary files /dev/null and b/bmp-deploy/doc/zh/picture/bmp-deplopy-architecture.png differ diff --git a/bmp-deploy/doc/zh/picture/example-network.png b/bmp-deploy/doc/zh/picture/example-network.png new file mode 100644 index 0000000..77f8638 Binary files /dev/null and b/bmp-deploy/doc/zh/picture/example-network.png differ diff --git a/bmp-deploy/doc/zh/picture/example-tor1.png b/bmp-deploy/doc/zh/picture/example-tor1.png new file mode 100644 index 0000000..d85bb5c Binary files /dev/null and b/bmp-deploy/doc/zh/picture/example-tor1.png differ diff --git a/bmp-deploy/doc/zh/picture/network-architecture.png b/bmp-deploy/doc/zh/picture/network-architecture.png new file mode 100644 index 0000000..5c4a05b Binary files /dev/null and b/bmp-deploy/doc/zh/picture/network-architecture.png differ diff --git a/bmp-deploy/doc/zh/picture/network-deploy.png b/bmp-deploy/doc/zh/picture/network-deploy.png new file mode 100644 index 0000000..f935d75 Binary files /dev/null and b/bmp-deploy/doc/zh/picture/network-deploy.png differ diff --git a/bmp-deploy/doc/zh/service-manage.md b/bmp-deploy/doc/zh/service-manage.md new file mode 100644 index 0000000..77e3d21 --- /dev/null +++ b/bmp-deploy/doc/zh/service-manage.md @@ -0,0 +1,129 @@ +# [bmp安装指导](main.md) - 服务管理 +bmp-deploy.sh 使用说明 +~~~ +# ./bmp-deploy.sh -h + +Usage: ./bmp-deploy.sh [-t|--tag TAG] COMMAND SERVICE... + +COMMAND: + start Install and start SERVICE + stop Stop SERVICE + restart restart SERVICE + status check SERVICE status + images display SERVICE image + uninstall uninstall SERVICE + reinstall reinstall SERVICE + config get SERVICE config + +SERVICE: + all All SERVICES + bmp-db + bmp-redis + bmp-mq + bmp-image + bmp-pushgateway + bmp-alertmanager + bmp-prometheus + bmp-tftp + bmp-rsyslog + bmp-console-web + bmp-operation-web + bmp-console-api + bmp-operation-api + bmp-openapi + bmp-openapi-console + bmp-scheduler + bmp-driver + bmp-dhcp-agent + bmp-oob-alert + bmp-oob-agent + bmp-monitor-proxy + bmp-pronoea +~~~ +## 停止服务 +./bmp-deploy.sh stop all | [service...] +~~~ +#停止bmp-console-web服务 +./bmp-deploy.sh stop bmp-console-web + +#停止bmp-console-web和bmp-operation-web服务 +./bmp-deploy.sh stop bmp-console-web bmp-operation-web + +#停止所有服务 +./bmp-deploy.sh stop all +~~~ + +## 启动服务 +./bmp-deploy.sh start all | [service...] +~~~ +#启动bmp-console-web服务 +./bmp-deploy.sh start bmp-console-web + +#启动bmp-console-web和bmp-operation-web服务 +./bmp-deploy.sh start bmp-console-web bmp-operation-web + +#启动所有服务 +./bmp-deploy.sh start all +~~~ + +## 重启服务 +./bmp-deploy.sh restart all | [service...] +~~~ +#重启bmp-console-web服务 +./bmp-deploy.sh restart bmp-console-web +~~~ + +## 查看服务运行状态 +./bmp-deploy.sh status all | [service...] +~~~ +#查看所有服务运行状态 +./bmp-deploy.sh status all +~~~ + +## 查看服务关联的容器镜像 +./bmp-deploy.sh images all | [service...] +~~~ +#查看bmp-console-web服务关联的容器镜像 +./bmp-deploy.sh images bmp-console-web +~~~ + +## 删除服务 +./bmp-deploy.sh uninstall all | [service...] + +说明: 相关数据也会一并删除 +~~~ +#删除单个服务,如bmp-console-web +./bmp-deploy.sh uninstall bmp-console-web + +#删除所有服务 +./bmp-deploy.sh uninstall all +~~~ + +## 卸载bmp(删除所有服务) +~~~ +cd /root/bmp-deploy/ +./bmp-deploy.sh uninstall all +cd /root +rm -rf bmp-deploy bmp-deploy*.tar.gz +rm -rf /var/log/bmp +~~~ + +## 重装服务(删除+按装) +./bmp-deploy.sh reinstall all | [service...] +~~~ +#重装单个服务,如bmp-console-web +./bmp-deploy.sh reinstall bmp-console-web +~~~ + +## 获取服务配置 +./bmp-deploy.sh config all | [service...] + +## 部署bmp时指定版本 +./bmp-deploy.sh start all | [service...] -t|--tag TAG +~~~ +#部署1.0版本 +./bmp-deploy.sh start all --tag 1.0 +~~~ + +# 上一节 [部署bmp](deploy.md) +# 下一节 [装机流程](bm-deploy.md) \ No newline at end of file diff --git a/bmp-deploy/doc/zh/tool.md b/bmp-deploy/doc/zh/tool.md new file mode 100644 index 0000000..085f2e4 --- /dev/null +++ b/bmp-deploy/doc/zh/tool.md @@ -0,0 +1,47 @@ +# [bmp安装指导](main.md) - 实用工具 +tool目录下包含一些工具脚本,用于采集设备信息等 + +## 采集设备信息 +collect_device_info.sh 使用说明 +~~~ +./collect_device_info.sh -h + +Usage: ./collect_device_info.sh --sn SN --iloIp iloIp --iloUser iloUser --iloPassword iloPassword --ip ip --mask mask --gateway gateway --mac MAC [--raidDriver raidDriver] + +~~~ + +参数说明: +~~~ +SN 设备sn +iloIp 设备带外网口ip +iloUser 设备带外管理用户名 +iloPassword 设备带外管理密码 +ip 设备管理网口1 ip +mask 设备管理网口1 ip所属子网掩码 +gateway 设备管理网口1 ip所属子网网关 +MAC 设备管理网口1 mac +raidDriver 设备raid卡驱动,目前支持的驱动有:sas2ircu sas3ircu megacli64 storcli64 perccli64 arcconf no_raid,默认使用megacli64 +~~~ + +示例: +~~~ +./collect_device_info.sh --sn 210235A3P6N1830002MH --iloIp 192.168.0.2 --iloUser xxx --iloPassword 'xxx' --ip 10.208.14.170 --mask 255.255.255.224 --gateway 10.208.14.161 --mac '3C:FD:FE:5E:C6:74' +~~~ + +采集设备信息任务完成后(需要等待2-5分钟),会生成文件 /var/log/bmp/bmp-scheduler/disk_location_dir/SN,该文件包含设备磁盘插槽信息。 +~~~ +# cat /var/log/bmp/bmp-scheduler/disk_location_dir/210235A3P6N1830002MH +{"controllers":[{"adapter_id":"1","disk_info":"Controllers found: 1\n----------------------------------------------------------------------\nController information\n----------------------------------------------------------------------\n Controller Status : Optimal\n Controller Mode : Mixed\n Channel description : SCSI\n Controller Model : Adaptec SmartIOC 8i\n Controller Serial Number : Unknown\n Controller World Wide Name : 5600B036FAEDD000\n Physical Slot : 255\n Temperature : 61 C/ 141 F (Normal)\n Power Consumption : Not Applicable\n Power Mode : Unknown\n Power Mode Operational : Unknown\n Survival Mode : Unknown\n Host bus type : PCIe 3.0\n Host bus speed : 7880 MBps\n Host bus link width : 8 bit(s)/link(s)\n PCI Address (Bus:Device:Function) : 0:1:0:0\n I2C Address : 0xDE\n I2C Clock Speed ...... +~~~ + +## 重试指令 +retry_command.sh 使用说明 +~~~ + ./retry_command.sh -h + +Usage: ./retry_command.sh Command_id + +~~~ + +# 上一节 [故障排查](troubleshoot.md) +# 下一节 [配置管理](config.md) diff --git a/bmp-deploy/doc/zh/troubleshoot.md b/bmp-deploy/doc/zh/troubleshoot.md new file mode 100644 index 0000000..422249f --- /dev/null +++ b/bmp-deploy/doc/zh/troubleshoot.md @@ -0,0 +1,14 @@ +# [bmp安装指导](main.md) - 故障排查 +* pxe引导失败 +1. 机器的引导模式是否为bios +2. 机器带外网络是否正确 +3. 机器的bmc是否正常 +4. 机器的网口连线是否正确 +* 某个服务未正常运行 +~~~ +./bmp-deploy.sh status all #检查哪些服务未正常运行 +./bmp-deploy.sh start ServiceName #启动服务 +~~~ + +# 上一节 [装机流程](bm-deploy.md) +# 下一节 [实用工具](tool.md) \ No newline at end of file diff --git a/bmp-deploy/docker-compose.yml b/bmp-deploy/docker-compose.yml new file mode 100644 index 0000000..c9617b4 --- /dev/null +++ b/bmp-deploy/docker-compose.yml @@ -0,0 +1,241 @@ +services: + bmp-db: + image: "${bmp_db_image}" + env_file: + - ./env/bmp-db.env + ports: + - 3306:3306 + volumes: + - /var/lib/bmp/bmp-db:/var/lib/mysql + bmp-redis: + image: "${bmp_redis_image}" + env_file: + - ./env/bmp-redis.env + ports: + - 6379:6379 + volumes: + - /var/lib/bmp/bmp-redis:/data + - ./template/redis.conf.tpl:/redis.conf.tpl + - ./script/redis_init.sh:/redis_init.sh + command: ["sh", "/redis_init.sh"] + bmp-mq: + image: "${bmp_mq_image}" + env_file: + - ./env/bmp-mq.env + ports: + - 5672:5672 + - 15672:15672 + volumes: + - /var/lib/bmp/bmp-mq:/var/lib/rabbitmq + - ./script/rabbitmq_init.sh:/rabbitmq_init.sh + command: ["sh", "-x", "/rabbitmq_init.sh"] + hostname: bmp-mq + bmp-tftp: + image: "${bmp_tftp_image}" + env_file: + - ./env/bmp-tftp.env + ports: + - 69:69/udp + volumes: + - /var/lib/bmp/bmp-tftp:/var/tftpboot + - ./script/tftp_init.sh:/tftp_init.sh + - ./template/pxelinux.tpl:/pxelinux.tpl + - ./template/grub_x86_64.cfg.tpl:/grub_x86_64.cfg.tpl + - ./template/grub_arm64.cfg.tpl:/grub_arm64.cfg.tpl + - ./template/grub_loongarch64.cfg.tpl:/grub_loongarch64.cfg.tpl + entrypoint: "" + command: ["sh", "/tftp_init.sh"] + bmp-image: + image: "${bmp_image_image}" + env_file: + - ./env/bmp-image.env + ports: + - 10000:80 + volumes: + - /var/lib/bmp/bmp-image:/usr/share/nginx/html + bmp-rsyslog: + image: "${bmp_rsyslog_image}" + env_file: + - ./env/bmp-rsyslog.env + ports: + - 1514:514/udp + volumes: + - /var/log/bmp/bmp-rsyslog:/var/log/bmp/bmp-rsyslog + - ./template/bmp-rsyslog.conf.tpl:/etc/rsyslog.d/bmp-rsyslog.conf + bmp-driver: + image: "${bmp_driver_image}" + env_file: + - ./env/bmp-driver.env + volumes: + - /var/log/bmp/bmp-driver:/var/log/bmp/bmp-driver + depends_on: + - bmp-mq + bmp-dhcp-agent: + image: "${bmp_dhcp_agent_image}" + env_file: + - ./env/bmp-dhcp-agent.env + volumes: + - /var/log/bmp/bmp-dhcp-agent:/var/log/bmp/bmp-dhcp-agent + - /var/lib/bmp/bmp-dhcp-agent:/data + - ./template/dhcpd.conf.tpl:/dhcpd.conf.tpl + - ./script/dhcpd_control.sh:/dhcpd_control.sh + - /var/lib/bmp/bmp-tftp:/var/tftpboot + depends_on: + - bmp-mq + network_mode: "host" + bmp-openapi: + image: "${bmp_openapi_image}" + env_file: + - ./env/bmp-openapi.env + ports: + - 8801:8801 + volumes: + - /var/log/bmp/bmp-openapi:/var/log/bmp/bmp-openapi + - /dev/mem:/dev/mem + depends_on: + - bmp-db + - bmp-redis + - bmp-mq + privileged: true + bmp-openapi-console: + image: "${bmp_openapi_console_image}" + env_file: + - ./env/bmp-openapi-console.env + ports: + - 8802:8802 + volumes: + - /var/log/bmp/bmp-openapi-console:/var/log/bmp/bmp-openapi-console + - /dev/mem:/dev/mem + depends_on: + - bmp-db + - bmp-redis + - bmp-mq + privileged: true + bmp-scheduler: + image: "${bmp_scheduler_image}" + env_file: + - ./env/bmp-scheduler.env + volumes: + - /var/log/bmp/bmp-scheduler:/var/log/bmp/bmp-scheduler + depends_on: + - bmp-db + - bmp-redis + - bmp-mq + bmp-console-api: + image: "${bmp_console_api_image}" + env_file: + - ./env/bmp-console-api.env + ports: + - 8800:8800 + volumes: + - /var/log/bmp/bmp-console-api:/var/log/bmp/bmp-console-api + depends_on: + - bmp-db + - bmp-redis + bmp-operation-api: + image: "${bmp_operation_api_image}" + env_file: + - ./env/bmp-operation-api.env + ports: + - 8799:8799 + volumes: + - /var/log/bmp/bmp-operation-api:/var/log/bmp/bmp-operation-api + - /var/lib/bmp/bmp-image:/home/bmp/bmp-operation-api/data + depends_on: + - bmp-db + - bmp-redis + bmp-console-web: + image: "${bmp_console_web_image}" + env_file: + - ./env/bmp-console-web.env + ports: + - 8080:8080 + volumes: + - ./template/bmp-console-web.nginx.tpl:/etc/nginx/templates/bmp-console-web.conf.template + depends_on: + - bmp-console-api + bmp-operation-web: + image: "${bmp_operation_web_image}" + env_file: + - ./env/bmp-operation-web.env + ports: + - 8081:8081 + volumes: + - ./template/bmp-operation-web.nginx.tpl:/etc/nginx/templates/bmp-operation-web.conf.template + - /var/lib/bmp/bmp-image:/home/bmp/bmp-operation-web/data + depends_on: + - bmp-operation-api + bmp-oob-alert: + image: "${bmp_oob_alert_image}" + env_file: + - ./env/bmp-oob-alert.env + ports: + - 8804:8804 + volumes: + - /var/log/bmp/bmp-oob-alert:/var/log/bmp/bmp-oob-alert + depends_on: + - bmp-db + - bmp-redis + bmp-oob-agent: + image: "${bmp_oob_agent_image}" + env_file: + - ./env/bmp-oob-agent.env + volumes: + - /var/log/bmp/bmp-oob-agent:/var/log/bmp/bmp-oob-agent + depends_on: + - bmp-redis + bmp-monitor-proxy: + image: "${bmp_monitor_proxy_image}" + env_file: + - ./env/bmp-monitor-proxy.env + ports: + - 8805:8805 + volumes: + - /var/log/bmp/bmp-monitor-proxy:/var/log/bmp/bmp-monitor-proxy + depends_on: + - bmp-redis + bmp-pushgateway: + image: "${bmp_pushgateway_image}" + ports: + - 9091:9091 + command: ["--web.enable-admin-api"] + bmp-alertmanager: + image: "${bmp_alertmanager_image}" + env_file: + - ./env/bmp-alertmanager.env + ports: + - 9093:9093 + volumes: + - ./script/alertmanager_init.sh:/alertmanager_init.sh + - ./template/alertmanager.tpl:/alertmanager.tpl + entrypoint: "" + command: ["sh", "/alertmanager_init.sh"] + bmp-prometheus: + image: "${bmp_prometheus_image}" + env_file: + - ./env/bmp-prometheus.env + ports: + - 9090:9090 + volumes: + - /var/lib/bmp/bmp-prometheus/conf:/var/lib/prometheus/conf + - ./script/prometheus_init.sh:/prometheus_init.sh + - ./template/prometheus.tpl:/prometheus.tpl + - ${BMP_PROMETHEUS_DATA_DIR}:/var/lib/prometheus/data + entrypoint: "" + command: ["sh", "/prometheus_init.sh"] + user: root + depends_on: + - bmp-pushgateway + - bmp-alertmanager + bmp-pronoea: + image: "${bmp_pronoea_image}" + env_file: + - ./env/bmp-pronoea.env + ports: + - 9999:9999 + volumes: + - /var/log/bmp/bmp-pronoea:/var/log/bmp/bmp-pronoea + - /var/lib/bmp/bmp-prometheus/conf:/var/lib/prometheus/conf + depends_on: + - bmp-pushgateway + - bmp-prometheus diff --git a/bmp-deploy/docker_install_files/docker-compose/docker-compose b/bmp-deploy/docker_install_files/docker-compose/docker-compose new file mode 100755 index 0000000..e1f5818 Binary files /dev/null and b/bmp-deploy/docker_install_files/docker-compose/docker-compose differ diff --git a/bmp-deploy/docker_install_files/docker/bin/containerd b/bmp-deploy/docker_install_files/docker/bin/containerd new file mode 100755 index 0000000..e139f52 Binary files /dev/null and b/bmp-deploy/docker_install_files/docker/bin/containerd differ diff --git a/bmp-deploy/docker_install_files/docker/bin/containerd-shim-runc-v2 b/bmp-deploy/docker_install_files/docker/bin/containerd-shim-runc-v2 new file mode 100755 index 0000000..4ee3966 Binary files /dev/null and b/bmp-deploy/docker_install_files/docker/bin/containerd-shim-runc-v2 differ diff --git a/bmp-deploy/docker_install_files/docker/bin/ctr b/bmp-deploy/docker_install_files/docker/bin/ctr new file mode 100755 index 0000000..7e314b4 Binary files /dev/null and b/bmp-deploy/docker_install_files/docker/bin/ctr differ diff --git a/bmp-deploy/docker_install_files/docker/bin/docker b/bmp-deploy/docker_install_files/docker/bin/docker new file mode 100755 index 0000000..b050313 Binary files /dev/null and b/bmp-deploy/docker_install_files/docker/bin/docker differ diff --git a/bmp-deploy/docker_install_files/docker/bin/docker-init b/bmp-deploy/docker_install_files/docker/bin/docker-init new file mode 100755 index 0000000..0b0dae8 Binary files /dev/null and b/bmp-deploy/docker_install_files/docker/bin/docker-init differ diff --git a/bmp-deploy/docker_install_files/docker/bin/docker-proxy b/bmp-deploy/docker_install_files/docker/bin/docker-proxy new file mode 100755 index 0000000..5737006 Binary files /dev/null and b/bmp-deploy/docker_install_files/docker/bin/docker-proxy differ diff --git a/bmp-deploy/docker_install_files/docker/bin/dockerd b/bmp-deploy/docker_install_files/docker/bin/dockerd new file mode 100755 index 0000000..b88aa30 Binary files /dev/null and b/bmp-deploy/docker_install_files/docker/bin/dockerd differ diff --git a/bmp-deploy/docker_install_files/docker/bin/runc b/bmp-deploy/docker_install_files/docker/bin/runc new file mode 100755 index 0000000..fa80ef1 Binary files /dev/null and b/bmp-deploy/docker_install_files/docker/bin/runc differ diff --git a/bmp-deploy/docker_install_files/docker/docker.service b/bmp-deploy/docker_install_files/docker/docker.service new file mode 100644 index 0000000..4fb4987 --- /dev/null +++ b/bmp-deploy/docker_install_files/docker/docker.service @@ -0,0 +1,47 @@ +[Unit] +Description=Docker Application Container Engine +Documentation=https://docs.docker.com +After=network-online.target docker.socket firewalld.service +Wants=network-online.target + +[Service] +Type=notify +# the default is not to use systemd for cgroups because the delegate issues still +# exists and systemd currently does not support the cgroup feature set required +# for containers run by docker +ExecStart=/usr/bin/dockerd +ExecReload=/bin/kill -s HUP $MAINPID +TimeoutSec=0 +RestartSec=2 +Restart=always + +# Note that StartLimit* options were moved from "Service" to "Unit" in systemd 229. +# Both the old, and new location are accepted by systemd 229 and up, so using the old location +# to make them work for either version of systemd. +StartLimitBurst=3 + +# Note that StartLimitInterval was renamed to StartLimitIntervalSec in systemd 230. +# Both the old, and new name are accepted by systemd 230 and up, so using the old name to make +# this option work for either version of systemd. +StartLimitInterval=60s + +# Having non-zero Limit*s causes performance problems due to accounting overhead +# in the kernel. We recommend using cgroups to do container-local accounting. +LimitNOFILE=infinity +LimitNPROC=infinity +LimitCORE=infinity + +# Comment TasksMax if your systemd version does not support it. +# Only systemd 226 and above support this option. +TasksMax=infinity + +# set delegate yes so that systemd does not reset the cgroups of docker containers +Delegate=yes + +# kill only the docker process, not all processes in the cgroup +KillMode=process +OOMScoreAdjust=-500 + +[Install] +WantedBy=multi-user.target + diff --git a/bmp-deploy/dockerfile/bmp-rsyslog.Dockerfile b/bmp-deploy/dockerfile/bmp-rsyslog.Dockerfile new file mode 100644 index 0000000..a1c2147 --- /dev/null +++ b/bmp-deploy/dockerfile/bmp-rsyslog.Dockerfile @@ -0,0 +1,5 @@ +FROM alpine:3.16 +RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories \ + && apk --no-cache update \ + && apk add --no-cache rsyslog +CMD ["rsyslogd", "-n"] diff --git a/bmp-deploy/dockerfile/bmp-tftp.Dockerfile b/bmp-deploy/dockerfile/bmp-tftp.Dockerfile new file mode 100644 index 0000000..c7d08f0 --- /dev/null +++ b/bmp-deploy/dockerfile/bmp-tftp.Dockerfile @@ -0,0 +1,5 @@ +FROM alpine:3.16 +RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories \ + && apk --no-cache update \ + && apk add --no-cache tftp-hpa +CMD ["sh", "/tftp_init.sh"] diff --git a/bmp-deploy/env/bmp-alertmanager.env b/bmp-deploy/env/bmp-alertmanager.env new file mode 100644 index 0000000..8f96cb9 --- /dev/null +++ b/bmp-deploy/env/bmp-alertmanager.env @@ -0,0 +1,2 @@ +BMP_PRONOEA_HOST +BMP_PRONOEA_PORT diff --git a/bmp-deploy/env/bmp-console-api.env b/bmp-deploy/env/bmp-console-api.env new file mode 100644 index 0000000..4ea5e7d --- /dev/null +++ b/bmp-deploy/env/bmp-console-api.env @@ -0,0 +1,10 @@ +BMP_DB_HOST +BMP_DB_PORT +BMP_DB_USER +BMP_DB_PASSWORD +BMP_DB_NAME +BMP_REDIS_HOST +BMP_REDIS_PORT +BMP_REDIS_PASSWORD +BMP_OPENAPI_CONSOLE_HOST +BMP_OPENAPI_CONSOLE_PORT diff --git a/bmp-deploy/env/bmp-console-web.env b/bmp-deploy/env/bmp-console-web.env new file mode 100644 index 0000000..e69de29 diff --git a/bmp-deploy/env/bmp-db.env b/bmp-deploy/env/bmp-db.env new file mode 100644 index 0000000..0a9fe6a --- /dev/null +++ b/bmp-deploy/env/bmp-db.env @@ -0,0 +1,4 @@ +MYSQL_ROOT_PASSWORD=$BMP_DB_PASSWORD +MYSQL_DATABASE=$BMP_DB_NAME +MYSQL_USER=$BMP_DB_USER +MYSQL_PASSWORD=$BMP_DB_PASSWORD diff --git a/bmp-deploy/env/bmp-dhcp-agent.env b/bmp-deploy/env/bmp-dhcp-agent.env new file mode 100644 index 0000000..354a5ba --- /dev/null +++ b/bmp-deploy/env/bmp-dhcp-agent.env @@ -0,0 +1,23 @@ +BMP_MQ_HOST=${BMP_HOST_IP} +BMP_MQ_PORT +BMP_MQ_USER +BMP_MQ_PASSWORD +BMP_MQ_VHOST +BMP_OMAPI_HOST=${BMP_HOST_IP} +BMP_OMAPI_PORT +BMP_OMAPI_KEY +BMP_MQ_EXCHANGE_ROUTING_KEY +BMP_HOST_IP +BMP_DHCP_CONFIG_DIR=/data +BMP_DHCP_CONTROL_BIN=/dhcpd_control.sh +BMP_TFTP_CONFIG_DIR=/var/tftpboot +BMP_TFTP_MQ_HOST=${BMP_HOST_IP} +BMP_TFTP_MQ_PORT=${BMP_MQ_PORT} +BMP_TFTP_MQ_USER=${BMP_MQ_USER} +BMP_TFTP_MQ_PASSWORD=${BMP_MQ_PASSWORD} +BMP_TFTP_MQ_VHOST=${BMP_MQ_VHOST} +BMP_TFTP_MQ_EXCHANGE_ROUTING_KEY=${BMP_MQ_EXCHANGE_ROUTING_KEY} +BMP_TFTP_IMAGE_HOST=${BMP_HOST_IP} +BMP_TFTP_IMAGE_PORT=${BMP_IMAGE_PORT} +BMP_TFTP_RSYSLOG_HSOT=${BMP_HOST_IP} +BMP_TFTP_RSYSLOG_PORT=${BMP_RSYSLOG_PORT} diff --git a/bmp-deploy/env/bmp-driver.env b/bmp-deploy/env/bmp-driver.env new file mode 100644 index 0000000..d0a3e64 --- /dev/null +++ b/bmp-deploy/env/bmp-driver.env @@ -0,0 +1,5 @@ +BMP_MQ_HOST +BMP_MQ_PORT +BMP_MQ_USER +BMP_MQ_PASSWORD +BMP_MQ_VHOST diff --git a/bmp-deploy/env/bmp-image.env b/bmp-deploy/env/bmp-image.env new file mode 100644 index 0000000..e69de29 diff --git a/bmp-deploy/env/bmp-monitor-proxy.env b/bmp-deploy/env/bmp-monitor-proxy.env new file mode 100644 index 0000000..ea15e37 --- /dev/null +++ b/bmp-deploy/env/bmp-monitor-proxy.env @@ -0,0 +1,7 @@ +BMP_REDIS_HOST +BMP_REDIS_PORT +BMP_REDIS_PASSWORD +BMP_OPENAPI_HOST +BMP_OPENAPI_PORT +BMP_PUSHGATEWAY_HOST +BMP_PUSHGATEWAY_PORT diff --git a/bmp-deploy/env/bmp-mq.env b/bmp-deploy/env/bmp-mq.env new file mode 100644 index 0000000..668a26f --- /dev/null +++ b/bmp-deploy/env/bmp-mq.env @@ -0,0 +1,3 @@ +BMP_MQ_USER +BMP_MQ_PASSWORD +BMP_MQ_VHOST diff --git a/bmp-deploy/env/bmp-oob-agent.env b/bmp-deploy/env/bmp-oob-agent.env new file mode 100644 index 0000000..10c5f99 --- /dev/null +++ b/bmp-deploy/env/bmp-oob-agent.env @@ -0,0 +1,4 @@ +BMP_REDIS_HOST +BMP_REDIS_PORT +BMP_REDIS_PASSWORD + diff --git a/bmp-deploy/env/bmp-oob-alert.env b/bmp-deploy/env/bmp-oob-alert.env new file mode 100644 index 0000000..41322c4 --- /dev/null +++ b/bmp-deploy/env/bmp-oob-alert.env @@ -0,0 +1,11 @@ +BMP_DB_HOST +BMP_DB_PORT +BMP_DB_USER +BMP_DB_PASSWORD +BMP_DB_NAME +BMP_REDIS_HOST +BMP_REDIS_PORT +BMP_REDIS_PASSWORD +BMP_OPENAPI_HOST +BMP_OPENAPI_PORT +BMP_IDC=${BMP_MQ_EXCHANGE_ROUTING_KEY} diff --git a/bmp-deploy/env/bmp-openapi-console.env b/bmp-deploy/env/bmp-openapi-console.env new file mode 100644 index 0000000..43fa613 --- /dev/null +++ b/bmp-deploy/env/bmp-openapi-console.env @@ -0,0 +1,19 @@ +BMP_DB_HOST +BMP_DB_PORT +BMP_DB_USER +BMP_DB_PASSWORD +BMP_DB_NAME +BMP_REDIS_HOST +BMP_REDIS_PORT +BMP_REDIS_PASSWORD +BMP_MQ_HOST +BMP_MQ_PORT +BMP_MQ_USER +BMP_MQ_PASSWORD +BMP_MQ_VHOST +BMP_IMAGE_HOST=${BMP_HOST_IP} +BMP_IMAGE_PORT +BMP_MONITOR_PROXY_HOST=${BMP_HOST_IP} +BMP_MONITOR_PROXY_PORT +BMP_PRONOEA_HOST +BMP_PRONOEA_PORT diff --git a/bmp-deploy/env/bmp-openapi.env b/bmp-deploy/env/bmp-openapi.env new file mode 100644 index 0000000..bee7d05 --- /dev/null +++ b/bmp-deploy/env/bmp-openapi.env @@ -0,0 +1,19 @@ +BMP_DB_HOST +BMP_DB_PORT +BMP_DB_USER +BMP_DB_PASSWORD +BMP_DB_NAME +BMP_REDIS_HOST +BMP_REDIS_PORT +BMP_REDIS_PASSWORD +BMP_MQ_HOST +BMP_MQ_PORT +BMP_MQ_USER +BMP_MQ_PASSWORD +BMP_MQ_VHOST +BMP_MONITOR_PROXY_HOST=${BMP_HOST_IP} +BMP_MONITOR_PROXY_PORT +BMP_PRONOEA_HOST +BMP_PRONOEA_PORT +BMP_IMAGE_HOST=${BMP_HOST_IP} +BMP_IMAGE_PORT diff --git a/bmp-deploy/env/bmp-operation-api.env b/bmp-deploy/env/bmp-operation-api.env new file mode 100644 index 0000000..6e3d067 --- /dev/null +++ b/bmp-deploy/env/bmp-operation-api.env @@ -0,0 +1,12 @@ +BMP_DB_HOST +BMP_DB_PORT +BMP_DB_USER +BMP_DB_PASSWORD +BMP_DB_NAME +BMP_REDIS_HOST +BMP_REDIS_PORT +BMP_REDIS_PASSWORD +BMP_OPENAPI_HOST +BMP_OPENAPI_PORT +BMP_OOB_ALERT_HOST +BMP_OOB_ALERT_PORT diff --git a/bmp-deploy/env/bmp-operation-web.env b/bmp-deploy/env/bmp-operation-web.env new file mode 100644 index 0000000..e69de29 diff --git a/bmp-deploy/env/bmp-prometheus.env b/bmp-deploy/env/bmp-prometheus.env new file mode 100644 index 0000000..0c204ca --- /dev/null +++ b/bmp-deploy/env/bmp-prometheus.env @@ -0,0 +1,4 @@ +BMP_PUSHGATEWAY_HOST +BMP_PUSHGATEWAY_PORT +BMP_ALERTMANAGER_HOST +BMP_ALERTMANAGER_PORT diff --git a/bmp-deploy/env/bmp-pronoea.env b/bmp-deploy/env/bmp-pronoea.env new file mode 100644 index 0000000..47403ff --- /dev/null +++ b/bmp-deploy/env/bmp-pronoea.env @@ -0,0 +1,6 @@ +BMP_OPENAPI_CONSOLE_HOST +BMP_OPENAPI_CONSOLE_PORT +BMP_PUSHGATEWAY_HOST +BMP_PUSHGATEWAY_PORT +BMP_PROMETHEUS_HOST +BMP_PROMETHEUS_PORT diff --git a/bmp-deploy/env/bmp-redis.env b/bmp-deploy/env/bmp-redis.env new file mode 100644 index 0000000..d4eec2a --- /dev/null +++ b/bmp-deploy/env/bmp-redis.env @@ -0,0 +1 @@ +BMP_REDIS_PASSWORD diff --git a/bmp-deploy/env/bmp-rsyslog.env b/bmp-deploy/env/bmp-rsyslog.env new file mode 100644 index 0000000..e69de29 diff --git a/bmp-deploy/env/bmp-scheduler.env b/bmp-deploy/env/bmp-scheduler.env new file mode 100644 index 0000000..0df928e --- /dev/null +++ b/bmp-deploy/env/bmp-scheduler.env @@ -0,0 +1,13 @@ +BMP_DB_HOST +BMP_DB_PORT +BMP_DB_USER +BMP_DB_PASSWORD +BMP_DB_NAME +BMP_REDIS_HOST +BMP_REDIS_PORT +BMP_REDIS_PASSWORD +BMP_MQ_HOST +BMP_MQ_PORT +BMP_MQ_USER +BMP_MQ_PASSWORD +BMP_MQ_VHOST diff --git a/bmp-deploy/env/bmp-tftp.env b/bmp-deploy/env/bmp-tftp.env new file mode 100644 index 0000000..ca3ec8a --- /dev/null +++ b/bmp-deploy/env/bmp-tftp.env @@ -0,0 +1,14 @@ +BMP_HOST_IP +BMP_MQ_PORT +BMP_MQ_USER +BMP_MQ_PASSWORD +BMP_MQ_VHOST +BMP_MQ_EXCHANGE_ROUTING_KEY +BMP_IMAGE_PORT +BMP_KERNEL_PATH_x86=/${bmp_kernel_name_x86} +BMP_INITRAMFS_PATH_x86=/${bmp_initramfs_name_x86} +BMP_KERNEL_PATH_arm64=/images/arm64/${bmp_kernel_name_arm64} +BMP_INITRAMFS_PATH_arm64=/images/arm64/${bmp_initramfs_name_arm64} +BMP_KERNEL_PATH_loonarch64=/images/loongarch64/${bmp_kernel_name_loonarch64} +BMP_INITRAMFS_PATH_loonarch64=/images/loongarch64/${bmp_initramfs_name_loonarch64} +BMP_RSYSLOG_PORT diff --git a/bmp-deploy/script/alertmanager_init.sh b/bmp-deploy/script/alertmanager_init.sh new file mode 100644 index 0000000..6f5c619 --- /dev/null +++ b/bmp-deploy/script/alertmanager_init.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -e +eval "echo \"$(cat /alertmanager.tpl)\"" > /etc/alertmanager/alertmanager.yml +exec /bin/alertmanager --config.file=/etc/alertmanager/alertmanager.yml --storage.path=/alertmanager --log.level=debug \ No newline at end of file diff --git a/bmp-deploy/script/dhcpd_control.sh b/bmp-deploy/script/dhcpd_control.sh new file mode 100755 index 0000000..4afc7b1 --- /dev/null +++ b/bmp-deploy/script/dhcpd_control.sh @@ -0,0 +1,70 @@ +#!/bin/sh +set -ue + +[ -z "$BMP_DHCP_CONFIG_DIR" ] && echo "error! BMP_DHCP_CONFIG_DIR is unset!" && exit 1 + +if [ ! -e $BMP_DHCP_CONFIG_DIR/dhcpd.conf ] && [ -e /dhcpd.conf.tpl ]; then + eval "echo \"$(cat /dhcpd.conf.tpl)\"" > $BMP_DHCP_CONFIG_DIR/dhcpd.conf +fi + +LOG_FILE=/var/log/bmp/bmp-dhcp-agent/dhcpd.log +exec_file=/usr/sbin/dhcpd +data_dir=$BMP_DHCP_CONFIG_DIR +dhcpd_conf="$data_dir/dhcpd.conf" +PID="" +if [ ! -r "$dhcpd_conf" ]; then + echo "Please ensure '$dhcpd_conf' exists and is readable." + echo "Run the container with arguments 'man dhcpd.conf' if you need help with creating the configuration." + exit 1 +fi + +[ -e "$data_dir/dhcpd.leases" ] || touch "$data_dir/dhcpd.leases" + + +help(){ + echo "${0} " + exit 1 +} + +get_pid() +{ + local pid="" + pid=$(ps -ef | grep "$exec_file" | grep -v 'grep' | awk '{print $1}') + PID=$pid +} + +checkhealth(){ + get_pid + [ X"$PID" != X"" ] && echo "dhcpd is running" && return 0 + echo "dhcpd is not running" && return 1 +} + +start(){ + /usr/sbin/dhcpd -f -d --no-pid -cf "$data_dir/dhcpd.conf" -lf "$data_dir/dhcpd.leases" >> $LOG_FILE 2>&1 & +} + +stop(){ + checkhealth || return 0 + [ X"$PID" != X"" ] && kill $PID + sleep 2 + checkhealth || return 0 + return 1 +} + +case "${1}" in + start) + start + ;; + stop) + stop + ;; + status|health|checkhealth) + checkhealth + ;; + restart) + stop && start + ;; + *) + help + ;; +esac diff --git a/bmp-deploy/script/prometheus_init.sh b/bmp-deploy/script/prometheus_init.sh new file mode 100644 index 0000000..a471679 --- /dev/null +++ b/bmp-deploy/script/prometheus_init.sh @@ -0,0 +1,10 @@ +#!/bin/bash +set -e +mkdir -p /var/lib/prometheus/conf/rules +mkdir -p /var/lib/prometheus/data +eval "echo \"$(cat /prometheus.tpl)\"" > /var/lib/prometheus/conf/prometheus.yml +exec /bin/prometheus --config.file=/var/lib/prometheus/conf/prometheus.yml \ + --storage.tsdb.path=/var/lib/prometheus/data \ + --web.console.libraries=/usr/share/prometheus/console_libraries \ + --web.console.templates=/usr/share/prometheus/consoles \ + --web.enable-lifecycle \ No newline at end of file diff --git a/bmp-deploy/script/rabbitmq_init.sh b/bmp-deploy/script/rabbitmq_init.sh new file mode 100644 index 0000000..b4de588 --- /dev/null +++ b/bmp-deploy/script/rabbitmq_init.sh @@ -0,0 +1,9 @@ +#!/bin/sh +(sleep 10 +rabbitmqctl add_vhost $BMP_MQ_VHOST +rabbitmqctl add_user $BMP_MQ_USER "$BMP_MQ_PASSWORD" +rabbitmqctl set_user_tags $BMP_MQ_USER administrator +rabbitmqctl set_permissions -p "$BMP_MQ_VHOST" $BMP_MQ_USER '.*' '.*' '.*' +rabbitmqctl list_users +rabbitmqctl change_password $BMP_MQ_USER "$BMP_MQ_PASSWORD")& +rabbitmq-server \ No newline at end of file diff --git a/bmp-deploy/script/redis_init.sh b/bmp-deploy/script/redis_init.sh new file mode 100644 index 0000000..d25dd49 --- /dev/null +++ b/bmp-deploy/script/redis_init.sh @@ -0,0 +1,6 @@ +#!/bin/sh +set -e +if [ ! -e /data/redis.conf ] && [ -e /redis.conf.tpl ]; then + eval "echo \"$(cat /redis.conf.tpl)\"" > /data/redis.conf +fi +redis-server /data/redis.conf \ No newline at end of file diff --git a/bmp-deploy/script/tftp_init.sh b/bmp-deploy/script/tftp_init.sh new file mode 100644 index 0000000..845abbb --- /dev/null +++ b/bmp-deploy/script/tftp_init.sh @@ -0,0 +1,20 @@ +#!/bin/bash +set -e + +# legacy for x86_64 +mkdir -p /var/tftpboot/pxelinux.cfg +eval "echo \"$(cat /pxelinux.tpl)\"" > /var/tftpboot/pxelinux.cfg/default + +#uefi for x86_64 +mkdir -p /var/tftpboot/uefi/x86_64 +eval "echo \"$(cat /grub_x86_64.cfg.tpl)\"" > /var/tftpboot/uefi/x86_64/grub.cfg + +#uefi for arm64 +mkdir -p /var/tftpboot/uefi/arm64 +eval "echo \"$(cat /grub_arm64.cfg.tpl)\"" > /var/tftpboot/uefi/arm64/grub.cfg + +#uefi for loongarch64 +mkdir -p /var/tftpboot/uefi/loongarch64 +eval "echo \"$(cat /grub_loongarch64.cfg.tpl)\"" > /var/tftpboot/uefi/loongarch64/grub.cfg + +exec in.tftpd -L --secure /var/tftpboot \ No newline at end of file diff --git a/bmp-deploy/sql/bmp.sql b/bmp-deploy/sql/bmp.sql new file mode 100644 index 0000000..0fefee0 --- /dev/null +++ b/bmp-deploy/sql/bmp.sql @@ -0,0 +1,1481 @@ +-- MySQL dump 10.14 Distrib 5.5.68-MariaDB, for Linux (x86_64) +-- +-- Host: 10.208.12.72 Database: bmp +-- ------------------------------------------------------ +-- Server version 5.7.40 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `apikey` +-- + +DROP TABLE IF EXISTS `apikey`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `apikey` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `apikey_id` varchar(255) NOT NULL DEFAULT '' COMMENT '秘钥对UUID', + `name` varchar(255) NOT NULL DEFAULT '' COMMENT '秘钥对名称', + `read_only` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否支持只读,read_only =1 的时候说明这个key是只读key,不能访问写方法。', + `token` varchar(255) NOT NULL DEFAULT '' COMMENT '32位字符令牌', + `type` varchar(10) NOT NULL DEFAULT '' COMMENT 'Token类型system/user', + `user_id` varchar(255) NOT NULL DEFAULT '' COMMENT '所属用户', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `source` varchar(255) NOT NULL DEFAULT '' COMMENT 'create from console/operation', + PRIMARY KEY (`id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=90 DEFAULT CHARSET=utf8 COMMENT='api秘钥'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `apikey` +-- + +LOCK TABLES `apikey` WRITE; +/*!40000 ALTER TABLE `apikey` DISABLE KEYS */; +INSERT INTO `apikey` VALUES (1,'apikey-xdghjr4cvikabs5g95mejh24fx5d','default-console-api',0,'Ym1wLWNvbnNvbGUtYXBp','system','','admin','admin',1667274361,1667274361,0,0,''),(2,'apikey-23df9fjs9dxc9dchhd925vhlnusg','default-operation-api',0,'Ym1wLW9wZXJhdGlvbi1hcGk=','system','','admin','admin',1667274361,1667274361,0,0,''),(3,'apikey-sinojr4cvicabs5g95mejh24v587','default-alert-api',0,'Ac13LWNvdrpxkGUtxxfcp','alert','','admin','admin',1667274361,1667274361,0,0,''); +/*!40000 ALTER TABLE `apikey` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `audit_logs` +-- + +DROP TABLE IF EXISTS `audit_logs`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `audit_logs` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `logid` varchar(255) NOT NULL DEFAULT '' COMMENT 'log uuid', + `sn` varchar(255) NOT NULL DEFAULT '', + `device_id` varchar(255) NOT NULL DEFAULT '', + `instance_id` varchar(255) NOT NULL DEFAULT '', + `operation` varchar(255) NOT NULL DEFAULT '' COMMENT 'action', + `operate_user_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'user_id', + `operate_user_name` varchar(255) NOT NULL DEFAULT '' COMMENT 'user_name', + `result` varchar(255) NOT NULL DEFAULT '' COMMENT 'success/fail', + `fail_reason` varchar(255) NOT NULL DEFAULT '' COMMENT 'reason for fail', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + PRIMARY KEY (`id`) USING BTREE, + KEY `i_sn` (`sn`), + KEY `i_device_id` (`device_id`), + KEY `i_instance_id` (`instance_id`), + KEY `i_operation` (`operation`) +) ENGINE=InnoDB AUTO_INCREMENT=105921 DEFAULT CHARSET=utf8 COMMENT='audit_logs'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `audit_logs` +-- + +LOCK TABLES `audit_logs` WRITE; +/*!40000 ALTER TABLE `audit_logs` DISABLE KEYS */; +/*!40000 ALTER TABLE `audit_logs` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `collect` +-- + +DROP TABLE IF EXISTS `collect`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `collect` ( + `id` int(32) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `collect_method` tinyint(32) unsigned NOT NULL, + `kernel_name` varchar(255) NOT NULL DEFAULT '' COMMENT 'kernel_name', + `initramfs_name` varchar(255) NOT NULL DEFAULT '' COMMENT 'initramfs_name', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + PRIMARY KEY (`id`) USING BTREE, + KEY `rule_id_idx` (`collect_method`), + KEY `sn_idx` (`kernel_name`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `collect` +-- + +LOCK TABLES `collect` WRITE; +/*!40000 ALTER TABLE `collect` DISABLE KEYS */; +INSERT INTO `collect` VALUES (1,1,'v2.0.4-centos_7_9-2024080513-vmlinuz','v2.0.4-centos_7_9-2024080513-initramfs.gz',0),(2,2,'v2.0.7-ubuntu_2204-2024082914-vmlinuz','v2.0.7-ubuntu_2204-2024082914-initramfs.gz',0); +/*!40000 ALTER TABLE `collect` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `command` +-- + +DROP TABLE IF EXISTS `command`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `command` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `request_id` varchar(64) NOT NULL DEFAULT '' COMMENT '请求ID', + `sn` varchar(64) NOT NULL DEFAULT '' COMMENT '设备SN', + `instance_id` varchar(36) NOT NULL DEFAULT '' COMMENT '实例Id', + `action` varchar(32) NOT NULL DEFAULT '' COMMENT '操作', + `type` varchar(16) NOT NULL DEFAULT '' COMMENT '操作类型:agent, driver, network', + `status` varchar(16) NOT NULL DEFAULT '' COMMENT '状态: wait,running,finish,error', + `parent_command_id` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '父指令Id', + `execute_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '执行次数', + `timeout_time` datetime DEFAULT NULL COMMENT 'timeout time', + `timeout_policy` varchar(16) NOT NULL DEFAULT '' COMMENT 'timeout policy', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `task` varchar(128) DEFAULT '', + PRIMARY KEY (`id`) USING BTREE, + KEY `i_command_request_id` (`request_id`) USING BTREE, + KEY `i_command_sn` (`sn`) USING BTREE, + KEY `i_command_instance_id` (`instance_id`) USING BTREE, + KEY `i_command_status` (`status`) USING BTREE, + KEY `i_parent_command_id` (`parent_command_id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=3503 DEFAULT CHARSET=utf8 COMMENT='指令'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `command` +-- + +LOCK TABLES `command` WRITE; +/*!40000 ALTER TABLE `command` DISABLE KEYS */; +/*!40000 ALTER TABLE `command` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cps_fault_rules` +-- + +DROP TABLE IF EXISTS `cps_fault_rules`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `cps_fault_rules` ( + `id` int(32) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `name` varchar(52) NOT NULL DEFAULT '' COMMENT '故障名称', + `parts` varchar(12) NOT NULL DEFAULT '' COMMENT '故障配件', + `fault_type` varchar(10) NOT NULL DEFAULT '' COMMENT '故障类型', + `condition` varchar(20) NOT NULL DEFAULT '' COMMENT '判定条件', + `threshold` varchar(52) NOT NULL DEFAULT '' COMMENT '判定阀值', + `level` varchar(16) NOT NULL DEFAULT '' COMMENT '故障等级', + `desc` varchar(152) NOT NULL DEFAULT '' COMMENT '故障描述', + `is_push` tinyint(1) NOT NULL DEFAULT '0' COMMENT '故障是否推送 0-否 1-是', + `is_use` tinyint(1) NOT NULL DEFAULT '0' COMMENT '规则是否启动 0-否 1-是', + `is_default_push` tinyint(1) NOT NULL DEFAULT '0' COMMENT '故障是否默认推送 0-否 1-是', + `is_default_use` tinyint(1) NOT NULL DEFAULT '0' COMMENT '规则是否默认启动 0-否 1-是', + `is_del` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否删除 0-否 1-是', + `create_time` timestamp NULL DEFAULT NULL COMMENT '创建时间', + `owned` varchar(12) NOT NULL DEFAULT '', + PRIMARY KEY (`id`), + KEY `is_push_idx` (`is_push`), + KEY `is_use_idx` (`is_use`), + KEY `parts_idx` (`parts`), + KEY `owned_idx` (`owned`) +) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `cps_fault_rules` +-- + +LOCK TABLES `cps_fault_rules` WRITE; +/*!40000 ALTER TABLE `cps_fault_rules` DISABLE KEYS */; +INSERT INTO `cps_fault_rules` VALUES (1,'power-supply-failure-detected','电源','电力故障','Power Supply','Failure detected','Critical','检测到电源故障(power-supply-failure-detected)',1,1,1,1,0,'2022-12-02 03:30:49','power'),(2,'power-supply-predictive-failure','电源','电力故障','Power Supply','Predictive failure','Warning','预期电源供电即将异常(power-supply-predictive-failure)',1,1,0,1,0,'2022-12-02 03:30:49','power'),(3,'power-supply-ac-lost','电源','电力故障','Power Supply','Power Supply AC lost','Critical','电源动力丢失(power-supply-ac-lost)',1,1,1,1,0,'2022-12-02 03:30:49','power'),(4,'power-supply-redundant-lost','电源','电力故障','Power Supply','Redundant Lost','Critical','电源冗余丢失(power-supply-redundant-lost',1,1,1,1,0,'2022-12-02 03:30:49','power'),(5,'temperature-upper-non-critical','温度','温控故障','Temperature','Upper Non-Critical','Warning','非严重级别温度过高(temperature-upper-non-critical)',1,1,0,1,0,'2022-12-02 03:30:49','other'),(6,'temperature-upper-critical','温度','温控故障','Temperature','Upper Critical','Critical','严重级别温度过高(temperature-upper-critical)',1,1,1,1,0,'2022-12-02 03:30:49','other'),(7,'processor-ierr','CPU','CPU故障','Processor','IERR','Critical','CPU内部错误(processor-ierr)',1,1,1,1,0,'2022-12-02 03:30:49','cpu'),(8,'processor-thermal-trip','CPU','CPU故障','Processor','Thermal Trip','Critical','CPU过热强制关机(processor-thermal-trip)',1,1,1,1,0,'2022-12-02 03:30:49','cpu'),(9,'processor-configuration-error','CPU','CPU故障','Processor','Configuration Error','Critical','CPU配置错误(processor-configuration-error)',1,1,1,1,0,'2022-12-02 03:30:49','cpu'),(10,'processor-uncorrectable-machine-check','CPU','CPU故障','Processor','Uncorrectable machine check exception','Critical','CPU不可纠正的自检故障(processor-uncorrectable-machine-check)',1,1,1,1,0,'2022-12-02 03:30:49','cpu'),(11,'processor-correctable-machine-check','CPU','CPU故障','Processor','Correctable machine check error','Warning','CPU可纠正的自检故障(processor-correctable-machine-check)',0,1,0,1,0,'2022-12-02 03:30:49','cpu'),(12,'memory-uncorrectable-ecc','内存','内存故障','Memory','Uncorrectable ECC','Critical','内存不可纠正的ECC故障(memory-uncorrectable-ecc)',1,1,1,1,0,'2022-12-02 03:30:49','mem'),(13,'memory-correctable-ecc','内存','内存故障','Memory','Correctable ECC','Warning','内存可纠正的ECC故障(memory-correctable-ecc)',0,1,0,1,0,'2022-12-02 03:30:49','mem'),(14,'memory-configuration-error','内存','内存故障','Memory','Configuration Error','Critical','内存配置错误(memory-configuration-error)',1,1,1,1,0,'2022-12-02 03:30:49','mem'),(15,'memory-critical-overtemperature','内存','内存故障','Memory','Critical Overtemperature','Critical','严重级别内存温度过高(memory-critical-overtemperature)',1,1,1,1,0,'2022-12-02 03:30:49','mem'),(16,'memory-device-disabled','内存','内存故障','Memory','Memory Device Disabled','Critical','内存设备禁用故障(memory-device-disabled)',1,1,1,1,0,'2022-12-02 03:30:49','mem'),(17,'disk-predictive-failure','硬盘','硬盘故障','Drive Slot / Bay','Predictive Failure','Warning','预期磁盘即将故障(disk-predictive-failure)',0,1,0,1,0,'2022-12-02 03:30:49','disk'),(18,'disk-drive-fault','硬盘','硬盘故障','Drive Slot / Bay','Drive Fault','Critical','磁盘驱动器故障(disk-drive-fault)',0,1,1,1,0,'2022-12-02 03:30:49','disk'),(19,'disk-in-critical-array','硬盘','硬盘故障','Drive Slot / Bay','In Critical Array','Critical','磁盘所在阵列严重级别故障(disk-in-critical-array)',0,1,1,1,0,'2022-12-02 03:30:49','disk'),(20,'disk-in-failed-array','硬盘','硬盘故障','Drive Slot / Bay','In Failed Array','Critical','磁盘所在阵列失效(disk-in-failed-array)',0,1,1,1,0,'2022-12-02 03:30:49','disk'),(21,'voltage-upper-non-critical','电压','电力故障','Voltage','Upper Non-Critical','Warning','非严重级别电压过高(voltage-upper-non-critical)',0,1,0,1,0,'2022-12-02 03:30:49','power'),(22,'voltage-upper-critical','电压','电力故障','Voltage','Upper Critical','Critical','严重级别电压过高(voltage-upper-critical)',1,1,1,1,0,'2022-12-02 03:30:49','power'),(23,'voltage-upper-non-recoverable','电压','电力故障','Voltage','Upper Non-Recoverable','Warning','电压不可恢复过高(voltage-upper-non-recoverable)',0,1,0,1,0,'2022-12-02 03:30:49','power'),(24,'voltage-lower-non-critical','电压','电力故障','Voltage','Lower Non-Critical','Warning','非严重级别电压过低(voltage-lower-non-critical)',0,1,0,1,0,'2022-12-02 03:30:49','power'),(25,'voltage-lower-critical','电压','电力故障','Voltage','Lower Critical','Critical','严重级别电压过低(voltage-lower-critical)',1,1,1,1,0,'2022-12-02 03:30:49','power'),(26,'voltage-lower-non-recoverable','电压','电力故障','Voltage','Lower Non-Recoverable','Warning','电压不可恢复过低(voltage-lower-non-recoverable)',0,1,0,1,0,'2022-12-02 03:30:49','power'),(27,'fan-lower-critical','风扇','温控故障','Fan','Lower Critical','Critical','严重级别风扇转速过低(fan-lower-critical)',1,1,1,1,0,'2022-12-02 03:30:49','other'),(28,'pcie-bus-fatal-error','PCIE总线','其他故障','Critical Interrupt','Bus Fatal Error','Critical','PCI 总线致命错误(pcie-bus-fatal-error)',1,1,1,1,0,'2022-12-02 03:30:49','other'),(29,'disk-drive-present-deassert','硬盘','硬盘故障','Drive Slot / Bay','Drive Present () | Deasserted','Critical','磁盘驱动器不存在(disk-drive-present-deassert)',0,1,1,1,0,'2022-12-02 03:30:49','disk'),(31,'disk-drive-present-deassert','硬盘','disk error','Drive','Drive','Critical','disk',0,1,1,1,1,'2022-12-02 03:30:49','disk'); +/*!40000 ALTER TABLE `cps_fault_rules` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cps_log_content_collection` +-- + +DROP TABLE IF EXISTS `cps_log_content_collection`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `cps_log_content_collection` ( + `id` int(32) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `content` varchar(256) NOT NULL DEFAULT '', + `fault_conf_id` int(32) unsigned NOT NULL, + `is_del` tinyint(1) NOT NULL DEFAULT '0' COMMENT ': 0,; 1,', + `sn` varchar(32) NOT NULL DEFAULT '' COMMENT 'sn', + `count` int(32) unsigned NOT NULL COMMENT 'count', + `level` varchar(16) NOT NULL DEFAULT '', + `event_time` timestamp NULL DEFAULT NULL, + `collect_time` timestamp NULL DEFAULT NULL, + `update_time` timestamp NULL DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `idx_isdel` (`is_del`), + KEY `rule_id_idx` (`fault_conf_id`), + KEY `sn_idx` (`sn`), + KEY `level_idx` (`level`) +) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `cps_log_content_collection` +-- + +LOCK TABLES `cps_log_content_collection` WRITE; +/*!40000 ALTER TABLE `cps_log_content_collection` DISABLE KEYS */; +/*!40000 ALTER TABLE `cps_log_content_collection` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cps_log_items` +-- + +DROP TABLE IF EXISTS `cps_log_items`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `cps_log_items` ( + `id` int(32) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `collection_id` int(32) unsigned NOT NULL COMMENT 'id', + `collect_time` timestamp NULL DEFAULT NULL, + `event_time` timestamp NULL DEFAULT NULL, + `is_dealed` tinyint(1) NOT NULL DEFAULT '0' COMMENT ': 0,, 1,', + `is_del` tinyint(1) NOT NULL DEFAULT '0' COMMENT ': 0,; 1,', + `sn` varchar(32) NOT NULL DEFAULT '' COMMENT 'sn', + PRIMARY KEY (`id`), + KEY `idx_isdel` (`is_del`), + KEY `collection_id_idx` (`collection_id`), + KEY `is_dealed_idx` (`is_dealed`), + KEY `sn_idx` (`sn`) +) ENGINE=InnoDB AUTO_INCREMENT=231 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `cps_log_items` +-- + +LOCK TABLES `cps_log_items` WRITE; +/*!40000 ALTER TABLE `cps_log_items` DISABLE KEYS */; +/*!40000 ALTER TABLE `cps_log_items` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `device` +-- + +DROP TABLE IF EXISTS `device`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `device` ( + `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '设备ID编号', + `sn` varchar(255) NOT NULL DEFAULT '' COMMENT '设备SN', + `device_id` varchar(255) NOT NULL DEFAULT '' COMMENT '设备uuid', + `instance_id` varchar(255) NOT NULL DEFAULT '' COMMENT '实例id', + `user_id` varchar(255) NOT NULL DEFAULT '' COMMENT '实例id', + `user_name` varchar(255) NOT NULL DEFAULT '' COMMENT '用户名', + `idc_id` varchar(255) NOT NULL DEFAULT '' COMMENT '机型uuid', + `device_type_id` varchar(255) NOT NULL DEFAULT '' COMMENT '设备类型uuid', + `manage_status` varchar(16) NOT NULL DEFAULT '' COMMENT '设备状态: in=已入库|putway=已上架|putawaying=上架中|putawayfail=上架失败|created=已创建|removed=已移除', + `device_series` varchar(255) NOT NULL DEFAULT '' COMMENT '机型类型,如computer,storage,gpu,other', + `reason` varchar(255) NOT NULL DEFAULT '' COMMENT '设备状态变更失败原因', + `cabinet` varchar(64) NOT NULL DEFAULT '' COMMENT '机柜编码', + `brand` varchar(255) NOT NULL DEFAULT '' COMMENT '品牌', + `model` varchar(255) NOT NULL DEFAULT '' COMMENT '型号', + `u_position` varchar(64) NOT NULL DEFAULT '' COMMENT 'U位', + `ilo_ip` varchar(32) NOT NULL DEFAULT '' COMMENT '带外管理IP', + `ilo_user` varchar(32) NOT NULL DEFAULT '' COMMENT '带外账号', + `ilo_password` varchar(255) NOT NULL DEFAULT '' COMMENT '带外账号密码', + `mac1` varchar(64) NOT NULL DEFAULT '' COMMENT 'MAC1(eth0)', + `mac2` varchar(64) NOT NULL DEFAULT '' COMMENT 'MAC2(eth2)', + `switch_ip1` varchar(255) NOT NULL DEFAULT '' COMMENT '交换机1ip', + `switch_port1` varchar(255) NOT NULL DEFAULT '' COMMENT '交换机1port', + `switch_ip2` varchar(255) NOT NULL DEFAULT '' COMMENT '交换机2ip', + `switch_port2` varchar(255) NOT NULL DEFAULT '' COMMENT '交换机2port', + `switch_user1` varchar(255) NOT NULL DEFAULT '' COMMENT '交换机1登录账号,如果为空,取所在机房的值', + `switch_password1` varchar(255) NOT NULL DEFAULT '' COMMENT '交换机1登录密码', + `switch_user2` varchar(255) NOT NULL DEFAULT '' COMMENT '交换机2登录账号,如果为空,取所在机房的值', + `switch_password2` varchar(255) NOT NULL DEFAULT '' COMMENT '交换机2登录密码', + `description` varchar(1024) NOT NULL DEFAULT '' COMMENT '描述', + `switch_ip` varchar(255) NOT NULL DEFAULT '' COMMENT '网口交换机IP', + `mask` varchar(255) NOT NULL DEFAULT '' COMMENT '子网掩码', + `gateway` varchar(255) NOT NULL DEFAULT '' COMMENT '网关地址', + `private_ipv4` varchar(255) NOT NULL DEFAULT '' COMMENT '内网IPV4', + `private_ipv6` varchar(255) NOT NULL DEFAULT '' COMMENT '内网IPV6', + `gateway6` varchar(255) NOT NULL DEFAULT '' COMMENT 'IPV6网关地址', + `adapter_id` int(11) NOT NULL DEFAULT '0' COMMENT 'adapter_id', + `raid_driver` varchar(255) NOT NULL DEFAULT '' COMMENT 'raid工具:(megacli64等)', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `private_eth1_ipv4` varchar(255) NOT NULL DEFAULT '' COMMENT 'eth1 IPV4', + `private_eth1_ipv6` varchar(255) NOT NULL DEFAULT '' COMMENT 'eth1 IPV6', + `mask_eth1` varchar(255) NOT NULL DEFAULT '' COMMENT '子网掩码 for eth1', + `current_boot_mode` varchar(255) NOT NULL DEFAULT '' COMMENT 'uefi/bios', + `collect_fail_reason` varchar(255) NOT NULL DEFAULT '', + `collect_status` varchar(255) NOT NULL DEFAULT '' COMMENT '1->collected success, 2->not collected, 3-> collecting, 4-> collected failed', + `architecture` varchar(255) NOT NULL DEFAULT '' COMMENT 'from agent.response when collect,x86_64 or aarch64 or something else', + `collect_method` tinyint(4) DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + KEY `sn_idx` (`sn`), + KEY `isdel_idx` (`is_del`) +) ENGINE=InnoDB AUTO_INCREMENT=118 DEFAULT CHARSET=utf8 COMMENT='设备信息'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `device` +-- + +LOCK TABLES `device` WRITE; +/*!40000 ALTER TABLE `device` DISABLE KEYS */; +/*!40000 ALTER TABLE `device` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `device_hints` +-- + +DROP TABLE IF EXISTS `device_hints`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `device_hints` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增id', + `volume_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'volume uuid', + `sn` varchar(64) NOT NULL COMMENT '设备SN', + `size` bigint(20) NOT NULL DEFAULT '0' COMMENT '以GiB为单位的设备尺寸', + `rotational` tinyint(4) NOT NULL DEFAULT '0' COMMENT '转动,可以区分HDDs(旋转-磁盘)和SSDs(非旋转-固态硬盘)', + `wwn` varchar(128) DEFAULT NULL COMMENT '唯一的存储标识符', + `name` varchar(64) NOT NULL COMMENT '设备名称,例如/dev/md0', + `wwn_vendor_extension` varchar(128) DEFAULT NULL COMMENT '唯一的供应商存储标识符', + `wwn_with_extension` varchar(128) DEFAULT NULL COMMENT '带有供应商附加扩展的唯一的存储标识符', + `model` varchar(64) DEFAULT NULL COMMENT '设备标识符', + `serial` varchar(64) DEFAULT NULL COMMENT '磁盘序列号', + `hctl` varchar(64) DEFAULT NULL COMMENT 'SCSI地址(主机名、channel通道、Target和Lun)', + `by_path` varchar(128) DEFAULT NULL COMMENT '磁盘by_path路径', + `vendor` varchar(64) DEFAULT NULL COMMENT '设备供应商', + `create_time` datetime NOT NULL COMMENT '创建时间', + `update_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除(0-未删, 1-已删)', + `volume_type` varchar(255) NOT NULL DEFAULT '' COMMENT 'system|data', + UNIQUE KEY `primary_id` (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=1407 DEFAULT CHARSET=utf8 COMMENT='设备各盘符(卷)所在磁盘'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `device_hints` +-- + +LOCK TABLES `device_hints` WRITE; +/*!40000 ALTER TABLE `device_hints` DISABLE KEYS */; +/*!40000 ALTER TABLE `device_hints` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `device_type` +-- + +DROP TABLE IF EXISTS `device_type`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `device_type` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', + `idc_id` varchar(255) NOT NULL DEFAULT '' COMMENT '机房id', + `device_type_id` varchar(255) NOT NULL DEFAULT '' COMMENT '设备类型uuid', + `name` varchar(100) NOT NULL DEFAULT '' COMMENT '机型名称,如计算效能型,标准计算型', + `device_type` varchar(255) NOT NULL DEFAULT '' COMMENT '机型规格, cps.c.normal', + `device_series` varchar(255) NOT NULL DEFAULT '' COMMENT '机型类型,如计算型,存储型', + `architecture` varchar(255) NOT NULL DEFAULT '' COMMENT '体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64', + `height` int(11) NOT NULL DEFAULT '0' COMMENT '【高度(U)】:显示机型高度', + `description` varchar(1024) NOT NULL DEFAULT '' COMMENT '描述', + `cpu_spec` varchar(256) NOT NULL DEFAULT '' COMMENT 'cpu规格是预置还是其它,预置:common,其它:user_defined', + `cpu_amount` int(11) NOT NULL DEFAULT '0' COMMENT 'cpu数量', + `cpu_cores` int(11) NOT NULL DEFAULT '0' COMMENT '单个cpu内核数', + `cpu_manufacturer` varchar(16) NOT NULL DEFAULT '' COMMENT 'cpu厂商', + `cpu_model` varchar(16) NOT NULL DEFAULT '' COMMENT 'cpu处理器型号', + `cpu_frequency` varchar(8) NOT NULL DEFAULT '' COMMENT 'cpu频率(G)', + `mem_spec` varchar(256) NOT NULL DEFAULT '' COMMENT 'mem规格是预置还是其它,预置:common,其它:user_defined', + `mem_type` varchar(4) NOT NULL DEFAULT '' COMMENT '内存接口(如DDR3,DDR4)', + `mem_size` int(11) NOT NULL DEFAULT '0' COMMENT '单个内存大小(GB)', + `mem_amount` int(11) NOT NULL DEFAULT '0' COMMENT '内存数量', + `mem_frequency` int(11) NOT NULL DEFAULT '0' COMMENT '内存主频(MHz)', + `nic_amount` int(11) NOT NULL DEFAULT '0' COMMENT '网卡数量', + `nic_rate` int(11) NOT NULL DEFAULT '0' COMMENT '网卡传输速率(GE)', + `interface_mode` varchar(255) NOT NULL DEFAULT '' COMMENT '【网口模式】【网络设置】: bond单网口,dual双网口', + `system_volume_type` varchar(16) NOT NULL DEFAULT '' COMMENT '系统盘类型(SSD,HDD)', + `system_volume_interface_type` varchar(16) NOT NULL DEFAULT '' COMMENT '系统盘接口类型(SATA,SAS,NVME)', + `system_volume_size` int(11) NOT NULL DEFAULT '0' COMMENT '系统盘单盘大小', + `system_volume_unit` varchar(16) NOT NULL DEFAULT '0' COMMENT '系统盘单盘单位', + `system_volume_amount` int(11) NOT NULL DEFAULT '0' COMMENT '系统盘数量', + `gpu_amount` int(11) NOT NULL DEFAULT '0' COMMENT 'gpu数量', + `gpu_manufacturer` varchar(16) NOT NULL DEFAULT '' COMMENT 'gpu厂商', + `gpu_model` varchar(16) NOT NULL DEFAULT '' COMMENT 'gpu处理器型号', + `data_volume_type` varchar(16) NOT NULL DEFAULT '' COMMENT '数据盘类型(SSD,HDD)', + `data_volume_interface_type` varchar(16) NOT NULL DEFAULT '' COMMENT '数据盘接口类型(SATA,SAS,NVME)', + `data_volume_size` int(11) NOT NULL DEFAULT '0' COMMENT '数据盘单盘大小', + `data_volume_unit` varchar(16) NOT NULL DEFAULT '0' COMMENT '数据盘单盘单位', + `data_volume_amount` int(11) NOT NULL DEFAULT '0' COMMENT '数据盘数量', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(255) NOT NULL DEFAULT '0' COMMENT '创建时间', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `boot_mode` varchar(32) NOT NULL DEFAULT '' COMMENT 'boot_type:bios/uefi', + `raid_can` varchar(16) NOT NULL DEFAULT '' COMMENT 'raid_can (RAID)/(NO RAID)', + `is_need_raid` varchar(16) NOT NULL DEFAULT '' COMMENT 'need_raid|no_need_raid', + `nics` text CHARACTER SET utf8mb4, + PRIMARY KEY (`id`) USING BTREE, + KEY `i_device_type_type` (`device_type`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=256 DEFAULT CHARSET=utf8 COMMENT='设备型号详情,此表并未使用'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `device_type` +-- + +LOCK TABLES `device_type` WRITE; +/*!40000 ALTER TABLE `device_type` DISABLE KEYS */; +/*!40000 ALTER TABLE `device_type` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `disk` +-- + +DROP TABLE IF EXISTS `disk`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `disk` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `disk_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'disk uuid', + `device_id` varchar(256) NOT NULL COMMENT '设备uuid', + `enclosure` varchar(256) NOT NULL DEFAULT '' COMMENT 'enclosure', + `slot` int(11) NOT NULL DEFAULT '0' COMMENT '卡槽槽位', + `disk_type` varchar(256) NOT NULL COMMENT '磁盘类型:system,data', + `types` varchar(256) NOT NULL DEFAULT '' COMMENT 'control/mvme/panfu', + `size` varchar(256) NOT NULL DEFAULT '' COMMENT '硬盘大小,不确定精度(非nvme盘)', + `size_unit` varchar(256) NOT NULL DEFAULT '' COMMENT '硬盘大小单位 MB GB TB ,1024进制', + `pd_type` varchar(256) NOT NULL DEFAULT '' COMMENT '盘类型:接口、nvme、盘符', + `adapter_id` int(11) NOT NULL DEFAULT '0' COMMENT '适配ID', + `media_type` varchar(256) NOT NULL DEFAULT '' COMMENT 'SDD', + `device_path` varchar(256) NOT NULL DEFAULT '' COMMENT 'effective when pd_type=NVME', + `index` int(11) NOT NULL DEFAULT '0' COMMENT 'NVME索引', + `serial_number` varchar(256) NOT NULL DEFAULT '' COMMENT 'effective when pd_type=NVME', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `name` varchar(255) NOT NULL DEFAULT '' COMMENT 'disk name/ nvme name / panfu name', + PRIMARY KEY (`id`) USING BTREE, + KEY `i_disk_id` (`disk_id`) USING BTREE, + KEY `i_device_id` (`device_id`) USING BTREE, + KEY `i_pd_type` (`pd_type`) USING BTREE, + KEY `i_is_del` (`is_del`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=2511 DEFAULT CHARSET=utf8 COMMENT='设备磁盘卡槽信息'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `disk` +-- + +LOCK TABLES `disk` WRITE; +/*!40000 ALTER TABLE `disk` DISABLE KEYS */; +/*!40000 ALTER TABLE `disk` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `idc` +-- + +DROP TABLE IF EXISTS `idc`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `idc` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `idc_id` varchar(50) NOT NULL DEFAULT '' COMMENT '机房uuid', + `name` varchar(200) NOT NULL DEFAULT '' COMMENT '机房名称', + `name_en` varchar(200) NOT NULL DEFAULT '' COMMENT '机房英文名称', + `shortname` varchar(200) NOT NULL DEFAULT '' COMMENT '机房名称缩写', + `level` varchar(200) NOT NULL DEFAULT '' COMMENT '机房等级', + `address` varchar(512) NOT NULL COMMENT '机房地址', + `ilo_user` varchar(255) NOT NULL DEFAULT '' COMMENT '带外登录账号', + `ilo_password` varchar(255) NOT NULL DEFAULT '' COMMENT '带外登录密码', + `switch_user1` varchar(255) NOT NULL DEFAULT '' COMMENT '交换机1登录账号', + `switch_password1` varchar(255) NOT NULL DEFAULT '' COMMENT '交换机1登录密码', + `switch_user2` varchar(255) NOT NULL DEFAULT '' COMMENT '交换机2登录账号', + `switch_password2` varchar(255) NOT NULL DEFAULT '' COMMENT '交换机2登录密码', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + PRIMARY KEY (`id`) USING BTREE, + KEY `i_os_uuid` (`idc_id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='os'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `idc` +-- + +LOCK TABLES `idc` WRITE; +/*!40000 ALTER TABLE `idc` DISABLE KEYS */; +INSERT INTO `idc` VALUES (1,'idc-vm4xsulx1k2d9z4xkctrttig02zl','默认机房','default_idc','default_idc','T4','北京市经济开发区京东总部2号楼','jdcps','cPs@Cp2019U','','','','','system','admin',1666099361,1726126235,0,0); +/*!40000 ALTER TABLE `idc` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `image` +-- + +DROP TABLE IF EXISTS `image`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `image` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `image_id` varchar(255) NOT NULL DEFAULT '' COMMENT '镜像uuid', + `image_name` varchar(255) NOT NULL DEFAULT '' COMMENT '镜像名称', + `os_id` varchar(36) NOT NULL DEFAULT '' COMMENT 'OSID', + `format` varchar(16) NOT NULL DEFAULT '' COMMENT '镜像格式(qcow2、tar)', + `filename` varchar(64) NOT NULL DEFAULT '' COMMENT '镜像文件名称', + `url` varchar(256) NOT NULL DEFAULT '' COMMENT '镜像源路径', + `hash` varchar(128) NOT NULL DEFAULT '' COMMENT '镜像校验码', + `source` varchar(20) NOT NULL DEFAULT '' COMMENT '镜像来源(common通用、customize定制、user_defined自定义)', + `description` varchar(512) NOT NULL DEFAULT '' COMMENT '描述', + `system_partition` varchar(4096) NOT NULL DEFAULT '' COMMENT '系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap)', + `data_partition` varchar(4096) NOT NULL DEFAULT '' COMMENT '数据分区信息', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `boot_mode` varchar(32) NOT NULL DEFAULT '' COMMENT 'boot_type:bios/uefi', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `i_image_uuid` (`image_id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=46 DEFAULT CHARSET=utf8 COMMENT='镜像'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `image` +-- + +LOCK TABLES `image` WRITE; +/*!40000 ALTER TABLE `image` DISABLE KEYS */; +INSERT INTO `image` VALUES (1,'i-haxcsxs570fhqew36zuuilks5w6v','CentOS 7.9 64-bit','o-3iqgx4yf6o5gfxerglpwkh3ej8h1','tar','v1.7.0-centos-7.9-2022070716.tar.xz','{host}/v1.7.0-centos-7.9-2022070716.tar.xz','760711ba6ae6e386d46314caf775ca14','common','centos7.9','[{\"format\":\"xfs\",\"point\":\"/\",\"size\":51200},{\"format\":\"swap\",\"point\":\"swap\",\"size\":10240}]','','admin','admin',1675325216,1675325216,0,0,'Legacy/BIOS,UEFI'),(2,'i-1bt811r0feavi4sfln5nyyz8qgvg','Ubuntu 18.04-64bit','o-04uay5mh6549w703schf1zsk3z29','tar','v1.7.0-ubuntu-18.04-2022062709.tar.xz','{host}/v1.7.0-ubuntu-18.04-2022062709.tar.xz','fcd77d7f8b22a3ff98671bf9890af46d','common','18.04','[{\"format\":\"xfs\",\"point\":\"/\",\"size\":51200},{\"format\":\"swap\",\"point\":\"swap\",\"size\":10240}]','','admin','admin',1675325530,1675325530,0,0,'Legacy/BIOS,UEFI'); +/*!40000 ALTER TABLE `image` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `instance` +-- + +DROP TABLE IF EXISTS `instance`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `instance` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `instance_id` varchar(255) NOT NULL DEFAULT '' COMMENT '实例ID(uuid)', + `idc_id` varchar(255) NOT NULL DEFAULT '' COMMENT '机房uuid', + `project_id` varchar(255) NOT NULL DEFAULT '' COMMENT '项目id', + `user_id` varchar(255) NOT NULL DEFAULT '' COMMENT '用户uuid', + `instance_name` varchar(255) NOT NULL DEFAULT '' COMMENT '实例名称', + `device_id` varchar(255) NOT NULL DEFAULT '' COMMENT '设备uuid', + `device_type_id` varchar(255) NOT NULL DEFAULT '' COMMENT '机型uuid', + `hostname` varchar(255) NOT NULL DEFAULT '' COMMENT '主机名', + `status` varchar(255) NOT NULL DEFAULT '' COMMENT '运行状态', + `reason` varchar(255) NOT NULL DEFAULT '' COMMENT '失败原因', + `image_id` varchar(255) NOT NULL DEFAULT '' COMMENT '镜像uuid', + `system_volume_raid_id` varchar(255) NOT NULL DEFAULT '' COMMENT '系统盘raid', + `locked` char(255) NOT NULL DEFAULT '' COMMENT '是否锁定解锁锁定:locked,解锁unlocked', + `data_volume_raid_id` varchar(255) NOT NULL DEFAULT '' COMMENT '数据盘raid', + `description` varchar(2048) NOT NULL DEFAULT '' COMMENT '描述', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `boot_mode` varchar(32) NOT NULL DEFAULT '' COMMENT 'boot_type:bios/uefi', + `is_installed_agent` varchar(255) NOT NULL DEFAULT '' COMMENT '0-> uninstalled, 1-> installed', + PRIMARY KEY (`id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=105 DEFAULT CHARSET=utf8 COMMENT='实例表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `instance` +-- + +LOCK TABLES `instance` WRITE; +/*!40000 ALTER TABLE `instance` DISABLE KEYS */; +/*!40000 ALTER TABLE `instance` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `instance_partition` +-- + +DROP TABLE IF EXISTS `instance_partition`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `instance_partition` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `instance_id` varchar(36) NOT NULL DEFAULT '' COMMENT '实例ID', + `image_id` varchar(36) NOT NULL DEFAULT '' COMMENT '镜像ID', + `device_type_id` varchar(100) NOT NULL DEFAULT '' COMMENT '设备类型', + `boot_mode` varchar(32) NOT NULL DEFAULT '' COMMENT 'boot类型:bios、uefi', + `partition_type` varchar(32) NOT NULL DEFAULT '' COMMENT '分区类型:root、boot、system、data', + `partition_size` int(11) NOT NULL DEFAULT '0' COMMENT '分区大小,单位MB', + `partition_fs_type` varchar(32) NOT NULL DEFAULT '' COMMENT '文件系统类型:xfs', + `partition_mount_point` varchar(32) NOT NULL DEFAULT '' COMMENT '分区目录', + `partition_label` varchar(32) NOT NULL DEFAULT '' COMMENT '分区标签:l_分区目录', + `system_disk_label` varchar(30) NOT NULL DEFAULT '' COMMENT '系统盘分区格式:gpt、msdos(做完RAID系统盘大于4T必用gpt)', + `data_disk_label` varchar(32) NOT NULL DEFAULT '' COMMENT '数据盘分区格式:gpt、msdos', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除(0-未删, 1-已删)', + `instance_partition_id` varchar(36) NOT NULL DEFAULT '' COMMENT 'instance_partition_uuid', + `number` int(11) unsigned NOT NULL DEFAULT '0' COMMENT 'instance_partition_number', + `volume_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'volume uuid', + `volume_type` varchar(255) NOT NULL DEFAULT '' COMMENT 'system|data', + PRIMARY KEY (`id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=624 DEFAULT CHARSET=utf8 COMMENT='实例分区关系表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `instance_partition` +-- + +LOCK TABLES `instance_partition` WRITE; +/*!40000 ALTER TABLE `instance_partition` DISABLE KEYS */; +/*!40000 ALTER TABLE `instance_partition` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `interface` +-- + +DROP TABLE IF EXISTS `interface`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `interface` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `interface_name` varchar(16) DEFAULT NULL, + `interface_type` varchar(16) DEFAULT NULL COMMENT 'lan/wan', + `sn` varchar(64) NOT NULL COMMENT 'SN', + `mac` varchar(32) NOT NULL COMMENT 'MAC', + `switch_ip` varchar(32) NOT NULL COMMENT 'IP', + `switch_port` varchar(32) DEFAULT NULL COMMENT 'Port', + `create_time` datetime NOT NULL, + `update_time` datetime DEFAULT NULL, + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '(0-1-)', + `ipv6_address` varchar(64) DEFAULT NULL, + `nic_number` tinyint(3) unsigned DEFAULT NULL COMMENT '1234....', + `ipv4_address` varchar(32) CHARACTER SET utf8mb4 DEFAULT NULL, + `bus_info` varchar(64) CHARACTER SET utf8mb4 DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `i_interface_ssi` (`switch_ip`,`switch_port`,`is_del`), + KEY `i_interface_sn` (`sn`) +) ENGINE=InnoDB AUTO_INCREMENT=3302 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `interface` +-- + +LOCK TABLES `interface` WRITE; +/*!40000 ALTER TABLE `interface` DISABLE KEYS */; +/*!40000 ALTER TABLE `interface` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `mail_message` +-- + +DROP TABLE IF EXISTS `mail_message`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `mail_message` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `server_addr` varchar(255) NOT NULL DEFAULT '' COMMENT '服务器地址', + `server_port` varchar(255) NOT NULL DEFAULT '' COMMENT '服务器端口', + `admin_addr` varchar(255) NOT NULL DEFAULT '' COMMENT '管理员邮箱', + `admin_pass` varchar(255) NOT NULL DEFAULT '' COMMENT '管理员邮箱密码', + `is_push` varchar(16) NOT NULL DEFAULT '0' COMMENT 'is push mail', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `to` varchar(255) NOT NULL DEFAULT '', + `is_pass` varchar(16) NOT NULL DEFAULT '0' COMMENT 'is checked send ok', + PRIMARY KEY (`id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=555 DEFAULT CHARSET=utf8 COMMENT='mail_message'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `mail_message` +-- + +LOCK TABLES `mail_message` WRITE; +/*!40000 ALTER TABLE `mail_message` DISABLE KEYS */; +INSERT INTO `mail_message` VALUES (554,'','','','','1',0,'',''); +/*!40000 ALTER TABLE `mail_message` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `monitor_alerts` +-- + +DROP TABLE IF EXISTS `monitor_alerts`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `monitor_alerts` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `alert_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'alert uuid', + `alert_time` int(11) NOT NULL DEFAULT '0' COMMENT '告警时间戳', + `resource` varchar(255) NOT NULL DEFAULT '' COMMENT '资源类型 [只支持instance一种]', + `resource_id` varchar(255) NOT NULL DEFAULT '' COMMENT '资源id,目前就是实例id', + `resource_name` varchar(255) NOT NULL DEFAULT '' COMMENT '资源名称,目前就是实例名称', + `trigger` varchar(255) NOT NULL DEFAULT '' COMMENT '触发条件,接口需要翻译', + `alert_value` varchar(255) NOT NULL DEFAULT '' COMMENT '报警值', + `alert_level` tinyint(4) NOT NULL DEFAULT '0' COMMENT '1表示一般,2表示严重,3表示紧急', + `alert_period` int(11) NOT NULL DEFAULT '0' COMMENT '告警持续时间(分钟为单位)', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `rule_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'rule uuid', + `user_id` varchar(255) NOT NULL DEFAULT '' COMMENT '通知对象 userid', + `user_name` varchar(255) NOT NULL DEFAULT '' COMMENT 'notice username', + `rule_name` varchar(255) NOT NULL DEFAULT '' COMMENT 'rule name', + `calculation_unit` varchar(255) NOT NULL DEFAULT '' COMMENT '%,GB,bps', + `is_recover` tinyint(4) NOT NULL DEFAULT '0' COMMENT '0->alert, 1->recover', + `project_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'project uuid', + PRIMARY KEY (`id`) USING BTREE, + KEY `i_rule_id` (`alert_id`) +) ENGINE=InnoDB AUTO_INCREMENT=1773 DEFAULT CHARSET=utf8 COMMENT='告警历史表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `monitor_alerts` +-- + +LOCK TABLES `monitor_alerts` WRITE; +/*!40000 ALTER TABLE `monitor_alerts` DISABLE KEYS */; +/*!40000 ALTER TABLE `monitor_alerts` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `monitor_rules` +-- + +DROP TABLE IF EXISTS `monitor_rules`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `monitor_rules` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `rule_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'rule uuid', + `enabled` tinyint(4) NOT NULL DEFAULT '0' COMMENT '1表示启用 2表示不启用', + `rule_name` varchar(255) NOT NULL DEFAULT '' COMMENT '规则名称', + `dimension` varchar(255) NOT NULL DEFAULT '' COMMENT '维度 [instance disk mountpoint nic]', + `resource` varchar(255) NOT NULL DEFAULT '' COMMENT '资源类型 [只支持instance一种]', + `trigger_option` varchar(8192) NOT NULL DEFAULT '' COMMENT '触发条件, json', + `notice_option` varchar(255) NOT NULL DEFAULT '' COMMENT '通知策略, json', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `user_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'user uuid', + `tags` varchar(255) NOT NULL DEFAULT '' COMMENT 'disk/mountpoint/nic tag', + `user_name` varchar(255) NOT NULL DEFAULT '' COMMENT 'user name', + `status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '1->enable,2->disable,3->alerted', + `project_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'project uuid', + PRIMARY KEY (`id`) USING BTREE, + KEY `i_rule_id` (`rule_id`) +) ENGINE=InnoDB AUTO_INCREMENT=119 DEFAULT CHARSET=utf8 COMMENT='带内监控规则表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `monitor_rules` +-- + +LOCK TABLES `monitor_rules` WRITE; +/*!40000 ALTER TABLE `monitor_rules` DISABLE KEYS */; +/*!40000 ALTER TABLE `monitor_rules` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `os` +-- + +DROP TABLE IF EXISTS `os`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `os` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `os_id` varchar(255) NOT NULL DEFAULT '' COMMENT '操作系统uuid', + `os_name` varchar(255) NOT NULL DEFAULT '' COMMENT '操作系统名称', + `os_type` varchar(16) NOT NULL DEFAULT '' COMMENT '操作系统分类:linux/windows', + `architecture` varchar(16) NOT NULL DEFAULT '' COMMENT '架构:x86/x64/i386/', + `bits` int(11) NOT NULL DEFAULT '0' COMMENT '指令宽度:64/32位', + `os_version` varchar(256) NOT NULL DEFAULT '' COMMENT '操作系统版本', + `sys_user` varchar(16) NOT NULL DEFAULT '' COMMENT '管理员账户', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + PRIMARY KEY (`id`) USING BTREE, + KEY `i_os_uuid` (`os_id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=46 DEFAULT CHARSET=utf8 COMMENT='os'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `os` +-- + +LOCK TABLES `os` WRITE; +/*!40000 ALTER TABLE `os` DISABLE KEYS */; +INSERT INTO `os` VALUES (1,'o-3iqgx4yf6o5gfxerglpwkh3ej8h1','CentOS 7.9 64-bit','CentOS','x86_64',64,'7.9','root','admin','admin',1675325216,1675325216,0,0),(2,'o-04uay5mh6549w703schf1zsk3z29','Ubuntu 18.04-64bit','Ubuntu','x86_64',64,'18.04','root','admin','admin',1675325530,1675325530,0,0); +/*!40000 ALTER TABLE `os` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `project` +-- + +DROP TABLE IF EXISTS `project`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `project` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `project_id` varchar(255) NOT NULL DEFAULT '' COMMENT '项目uuid', + `project_name` varchar(255) NOT NULL DEFAULT '' COMMENT '项目名称', + `is_default` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否默认项目0否 1是', + `is_system` tinyint(4) NOT NULL COMMENT '是否系统项目 0否 1是', + `user_id` varchar(255) NOT NULL DEFAULT '' COMMENT '项目拥有者用户id', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `description` varchar(255) NOT NULL DEFAULT '' COMMENT 'project description', + PRIMARY KEY (`id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=utf8 COMMENT='项目'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `project` +-- + +LOCK TABLES `project` WRITE; +/*!40000 ALTER TABLE `project` DISABLE KEYS */; +INSERT INTO `project` VALUES (1,'project-vtdz6jyqux7gxgglzk5fsdiyqy8k','default project',1,1,'user-ta5c5tsos2wkm8d2qtmvx3vufr2h','admin','admin',1678342000,1722335468,1722335468,0,''); +/*!40000 ALTER TABLE `project` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `r_device_type_image` +-- + +DROP TABLE IF EXISTS `r_device_type_image`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `r_device_type_image` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `image_id` varchar(255) NOT NULL DEFAULT '' COMMENT '镜像ID', + `device_type_id` varchar(255) NOT NULL DEFAULT '' COMMENT '设备类型id', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(255) NOT NULL DEFAULT '0' COMMENT '创建时间', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + PRIMARY KEY (`id`) USING BTREE, + KEY `i_r_device_type` (`device_type_id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=299 DEFAULT CHARSET=utf8 COMMENT='device_type/image关系'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `r_device_type_image` +-- + +LOCK TABLES `r_device_type_image` WRITE; +/*!40000 ALTER TABLE `r_device_type_image` DISABLE KEYS */; +/*!40000 ALTER TABLE `r_device_type_image` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `r_device_type_image_partition` +-- + +DROP TABLE IF EXISTS `r_device_type_image_partition`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `r_device_type_image_partition` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `image_id` varchar(36) NOT NULL DEFAULT '' COMMENT '镜像ID', + `device_type_id` varchar(100) NOT NULL DEFAULT '' COMMENT '设备类型', + `boot_mode` varchar(32) NOT NULL DEFAULT '' COMMENT 'boot类型:bios、uefi', + `partition_type` varchar(32) NOT NULL DEFAULT '' COMMENT '分区类型:root、boot、system、data', + `partition_size` int(11) NOT NULL DEFAULT '0' COMMENT '分区大小,单位MB', + `partition_fs_type` varchar(32) NOT NULL DEFAULT '' COMMENT '文件系统类型:xfs', + `partition_mount_point` varchar(32) NOT NULL DEFAULT '' COMMENT '分区目录', + `partition_label` varchar(32) NOT NULL DEFAULT '' COMMENT '分区标签:l_分区目录', + `system_disk_label` varchar(30) NOT NULL DEFAULT '' COMMENT '系统盘分区格式:gpt、msdos(做完RAID系统盘大于4T必用gpt)', + `data_disk_label` varchar(32) NOT NULL DEFAULT '' COMMENT '数据盘分区格式:gpt、msdos', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除(0-未删, 1-已删)', + PRIMARY KEY (`id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=506 DEFAULT CHARSET=utf8 COMMENT='device_type/image分区关系表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `r_device_type_image_partition` +-- + +LOCK TABLES `r_device_type_image_partition` WRITE; +/*!40000 ALTER TABLE `r_device_type_image_partition` DISABLE KEYS */; +/*!40000 ALTER TABLE `r_device_type_image_partition` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `r_device_volume_disks` +-- + +DROP TABLE IF EXISTS `r_device_volume_disks`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `r_device_volume_disks` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', + `device_id` varchar(255) NOT NULL DEFAULT '' COMMENT '设备uuid', + `volume_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'volume uuid', + `disk_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'disk uuid', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(255) NOT NULL DEFAULT '0' COMMENT '创建时间', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `volume_type` varchar(255) NOT NULL DEFAULT '' COMMENT 'data|system', + PRIMARY KEY (`id`) USING BTREE, + KEY `i_device_id` (`device_id`) USING BTREE, + KEY `i_volume_id` (`volume_id`) USING BTREE, + KEY `i_disk_id` (`disk_id`) USING BTREE, + KEY `i_is_del` (`is_del`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=1083 DEFAULT CHARSET=utf8 COMMENT='设备-卷-磁盘 关系表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `r_device_volume_disks` +-- + +LOCK TABLES `r_device_volume_disks` WRITE; +/*!40000 ALTER TABLE `r_device_volume_disks` DISABLE KEYS */; +INSERT INTO `r_device_volume_disks` VALUES (1018,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-f2lfzmkllmbr5761067uico754xy','disk-y14tuk1sp29e27mq3c7hbpkrh66e','admin','admin',1726034901,1726034901,0,1,'system'),(1019,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-f2lfzmkllmbr5761067uico754xy','disk-38wl5et15pbaav3vy3tfy8iokk45','admin','admin',1726034901,1726034901,0,1,'system'),(1020,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-f2lfzmkllmbr5761067uico754xy','disk-ajauiohh19msr3k7hb3avdnuvggu','admin','admin',1726034901,1726034901,0,1,'system'),(1021,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-tril2lumeqijcthvrdulmuiw3vps','disk-zlap1sbe3j6wphx35rubc1yfq0wg','admin','admin',1726034901,1726034901,0,1,'data'),(1022,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-tril2lumeqijcthvrdulmuiw3vps','disk-u7sbhfdopeb7v3rnizijm1k7hgng','admin','admin',1726034901,1726034901,0,1,'data'),(1023,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-tril2lumeqijcthvrdulmuiw3vps','disk-5ycq3r8zy2ib5f3ej1hnlgbtoeoz','admin','admin',1726034901,1726034901,0,1,'data'),(1024,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-10s5phbaizv3e68ic94r3vy0yrty','disk-y14tuk1sp29e27mq3c7hbpkrh66e','admin','admin',1726040988,1726040988,0,1,'system'),(1025,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-10s5phbaizv3e68ic94r3vy0yrty','disk-38wl5et15pbaav3vy3tfy8iokk45','admin','admin',1726040988,1726040988,0,1,'system'),(1026,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-10s5phbaizv3e68ic94r3vy0yrty','disk-ajauiohh19msr3k7hb3avdnuvggu','admin','admin',1726040988,1726040988,0,1,'system'),(1027,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-md8cup28q0uxoj6h2798xu899kp5','disk-zlap1sbe3j6wphx35rubc1yfq0wg','admin','admin',1726040988,1726040988,0,1,'data'),(1028,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-md8cup28q0uxoj6h2798xu899kp5','disk-u7sbhfdopeb7v3rnizijm1k7hgng','admin','admin',1726040988,1726040988,0,1,'data'),(1029,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-md8cup28q0uxoj6h2798xu899kp5','disk-5ycq3r8zy2ib5f3ej1hnlgbtoeoz','admin','admin',1726040988,1726040988,0,1,'data'),(1030,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-9hxfqwx7guzyxmhuvtosuz0iu9iw','disk-y14tuk1sp29e27mq3c7hbpkrh66e','admin','admin',1726042102,1726042102,0,1,'system'),(1031,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-9hxfqwx7guzyxmhuvtosuz0iu9iw','disk-38wl5et15pbaav3vy3tfy8iokk45','admin','admin',1726042102,1726042102,0,1,'system'),(1032,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-f4gkqpm76zj1bq8pibg1rzxmusci','disk-ajauiohh19msr3k7hb3avdnuvggu','admin','admin',1726042102,1726042102,0,1,'data'),(1033,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-f4gkqpm76zj1bq8pibg1rzxmusci','disk-zlap1sbe3j6wphx35rubc1yfq0wg','admin','admin',1726042102,1726042102,0,1,'data'),(1034,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-9hxfqwx7guzyxmhuvtosuz0iu9iw','disk-y14tuk1sp29e27mq3c7hbpkrh66e','admin','admin',1726050714,1726050714,0,1,'system'),(1035,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-9hxfqwx7guzyxmhuvtosuz0iu9iw','disk-38wl5et15pbaav3vy3tfy8iokk45','admin','admin',1726050714,1726050714,0,1,'system'),(1036,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-f4gkqpm76zj1bq8pibg1rzxmusci','disk-ajauiohh19msr3k7hb3avdnuvggu','admin','admin',1726050714,1726050714,0,1,'data'),(1037,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-f4gkqpm76zj1bq8pibg1rzxmusci','disk-zlap1sbe3j6wphx35rubc1yfq0wg','admin','admin',1726050714,1726050714,0,1,'data'),(1038,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-9hxfqwx7guzyxmhuvtosuz0iu9iw','disk-y14tuk1sp29e27mq3c7hbpkrh66e','admin','admin',1726050965,1726050965,0,1,'system'),(1039,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-9hxfqwx7guzyxmhuvtosuz0iu9iw','disk-38wl5et15pbaav3vy3tfy8iokk45','admin','admin',1726050965,1726050965,0,1,'system'),(1040,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-f4gkqpm76zj1bq8pibg1rzxmusci','disk-zlap1sbe3j6wphx35rubc1yfq0wg','admin','admin',1726050965,1726050965,0,1,'data'),(1041,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-f4gkqpm76zj1bq8pibg1rzxmusci','disk-ajauiohh19msr3k7hb3avdnuvggu','admin','admin',1726050965,1726050965,0,1,'data'),(1042,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-9hxfqwx7guzyxmhuvtosuz0iu9iw','disk-y14tuk1sp29e27mq3c7hbpkrh66e','admin','admin',1726051070,1726051070,0,1,'system'),(1043,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-9hxfqwx7guzyxmhuvtosuz0iu9iw','disk-ajauiohh19msr3k7hb3avdnuvggu','admin','admin',1726051070,1726051070,0,1,'system'),(1044,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-f4gkqpm76zj1bq8pibg1rzxmusci','disk-38wl5et15pbaav3vy3tfy8iokk45','admin','admin',1726051070,1726051070,0,1,'data'),(1045,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-f4gkqpm76zj1bq8pibg1rzxmusci','disk-zlap1sbe3j6wphx35rubc1yfq0wg','admin','admin',1726051070,1726051070,0,1,'data'),(1046,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-9hxfqwx7guzyxmhuvtosuz0iu9iw','disk-y14tuk1sp29e27mq3c7hbpkrh66e','admin','admin',1726051124,1726051124,0,1,'system'),(1047,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-9hxfqwx7guzyxmhuvtosuz0iu9iw','disk-ajauiohh19msr3k7hb3avdnuvggu','admin','admin',1726051124,1726051124,0,1,'system'),(1048,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-f4gkqpm76zj1bq8pibg1rzxmusci','disk-38wl5et15pbaav3vy3tfy8iokk45','admin','admin',1726051124,1726051124,0,1,'data'),(1049,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-f4gkqpm76zj1bq8pibg1rzxmusci','disk-u7sbhfdopeb7v3rnizijm1k7hgng','admin','admin',1726051124,1726051124,0,1,'data'),(1050,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-9hxfqwx7guzyxmhuvtosuz0iu9iw','disk-y14tuk1sp29e27mq3c7hbpkrh66e','admin','admin',1726107009,1726107009,0,1,'system'),(1051,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-9hxfqwx7guzyxmhuvtosuz0iu9iw','disk-38wl5et15pbaav3vy3tfy8iokk45','admin','admin',1726107009,1726107009,0,1,'system'),(1052,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-f4gkqpm76zj1bq8pibg1rzxmusci','disk-ajauiohh19msr3k7hb3avdnuvggu','admin','admin',1726107009,1726107009,0,1,'data'),(1053,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-f4gkqpm76zj1bq8pibg1rzxmusci','disk-zlap1sbe3j6wphx35rubc1yfq0wg','admin','admin',1726107009,1726107009,0,1,'data'),(1054,'d-4omuvfyprcalrbh7euvotavi0bqq','vl-e14318rf9peds0lqqzpsg18gz3ob','disk-oldkxkr9d620oui7jruvmduo13vx','admin','admin',1726126872,1726126872,0,1,'system'),(1055,'d-4omuvfyprcalrbh7euvotavi0bqq','vl-e14318rf9peds0lqqzpsg18gz3ob','disk-dirka822l9fxziwqc12toenfzhy4','admin','admin',1726126872,1726126872,0,1,'system'),(1056,'d-4omuvfyprcalrbh7euvotavi0bqq','vl-e14318rf9peds0lqqzpsg18gz3ob','disk-eyof6e2fgalbpu2e42i950kqdfi6','admin','admin',1726126872,1726126872,0,1,'system'),(1057,'d-4omuvfyprcalrbh7euvotavi0bqq','vl-e14318rf9peds0lqqzpsg18gz3ob','disk-6ha0dr3xbigczzi8el7v5rg199r4','admin','admin',1726126872,1726126872,0,1,'system'),(1058,'d-4omuvfyprcalrbh7euvotavi0bqq','vl-xwwibm0c9nsuac3hizh3t9t181ca','disk-hcwk1qjt5yqm8slnh4kxl6p2dz6b','admin','admin',1726126872,1726126872,0,1,'data'),(1059,'d-4omuvfyprcalrbh7euvotavi0bqq','vl-xwwibm0c9nsuac3hizh3t9t181ca','disk-fwkx8ibkrtmkfel0z03njm13sh17','admin','admin',1726126872,1726126872,0,1,'data'),(1060,'d-4omuvfyprcalrbh7euvotavi0bqq','vl-xwwibm0c9nsuac3hizh3t9t181ca','disk-yqc6121eja29u7ckgci2zwzood63','admin','admin',1726126872,1726126872,0,1,'data'),(1061,'d-4omuvfyprcalrbh7euvotavi0bqq','vl-xwwibm0c9nsuac3hizh3t9t181ca','disk-f503j9hn8l2d6ihumceryp8tgkmn','admin','admin',1726126872,1726126872,0,1,'data'),(1062,'d-brj02kttnzcatjs6iynhw2icxzbg','vl-e14318rf9peds0lqqzpsg18gz3ob','disk-72dkds4vvqrlh847y0mmrencez11','admin','admin',1726127260,1726127260,0,0,'system'),(1063,'d-brj02kttnzcatjs6iynhw2icxzbg','vl-e14318rf9peds0lqqzpsg18gz3ob','disk-6d0h79kogkeyxjabezca42ij4cc9','admin','admin',1726127260,1726127260,0,0,'system'),(1064,'d-brj02kttnzcatjs6iynhw2icxzbg','vl-xwwibm0c9nsuac3hizh3t9t181ca','disk-ssa0m02jb2beujguea7kjwhnephi','admin','admin',1726127260,1726127260,0,0,'data'),(1065,'d-brj02kttnzcatjs6iynhw2icxzbg','vl-xwwibm0c9nsuac3hizh3t9t181ca','disk-e44c992gpjmcd29m3wdw102o04tt','admin','admin',1726127260,1726127260,0,0,'data'),(1066,'d-kxqwytjua091giupgjk8hqiky7ml','vl-e5cdm3q8h8kovbqstp9rh9vfh5u6','disk-5nfaqrm9kl6mg7u8lc5w84avu2vl','admin','admin',1726129391,1726129391,0,1,'system'),(1067,'d-kxqwytjua091giupgjk8hqiky7ml','vl-e5cdm3q8h8kovbqstp9rh9vfh5u6','disk-5nfaqrm9kl6mg7u8lc5w84avu2vl','admin','admin',1726130391,1726130391,0,1,'system'),(1068,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-7a6m0y03b5144nfcwxgukytwgaam','disk-kp1soakbm4u58oi2rkh6jj9ksny2','admin','admin',1726142501,1726142501,0,1,'system'),(1069,'d-4omuvfyprcalrbh7euvotavi0bqq','vl-wlrgrcmpk5rkfg0gs7lbkz9cqopa','disk-q349uunnl4dz4z0lk851yjbm46pc','admin','admin',1726142700,1726142700,0,0,'system'),(1070,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-191o946aefsmgi7lmeo0e62xrct2','disk-tvm6jqyly0i7khpjswzpzw9spip8','admin','admin',1726143815,1726143815,0,0,'system'),(1071,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-191o946aefsmgi7lmeo0e62xrct2','disk-g4s92psenzdrsysf3pxejuze7i34','admin','admin',1726143815,1726143815,0,0,'system'),(1072,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-191o946aefsmgi7lmeo0e62xrct2','disk-c3sgf073fbg9xk0umyjh7v6i6b0c','admin','admin',1726143815,1726143815,0,0,'system'),(1073,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-191o946aefsmgi7lmeo0e62xrct2','disk-ebnvdjqhatm58h2e2as5o6csdane','admin','admin',1726143815,1726143815,0,0,'system'),(1074,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-191o946aefsmgi7lmeo0e62xrct2','disk-bx10c0oxobyms6l5xafcfix90zb6','admin','admin',1726143815,1726143815,0,0,'system'),(1075,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-191o946aefsmgi7lmeo0e62xrct2','disk-pnem7w4crdyv9l253it877nbiaye','admin','admin',1726143815,1726143815,0,0,'system'),(1076,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-191o946aefsmgi7lmeo0e62xrct2','disk-l8gbjleigazlr1m8obop82z96opy','admin','admin',1726143815,1726143815,0,0,'system'),(1077,'d-nca3rvyoc2s67hoqcu597nl2pd6k','vl-191o946aefsmgi7lmeo0e62xrct2','disk-ux763wfd8697hoopj0ibqserp3xm','admin','admin',1726143815,1726143815,0,0,'system'),(1078,'d-kxqwytjua091giupgjk8hqiky7ml','vl-wlrgrcmpk5rkfg0gs7lbkz9cqopa','disk-kydj8bf60rfrduo94kmx4ntjb2f5','admin','admin',1726143831,1726143831,0,1,'system'),(1079,'d-kxqwytjua091giupgjk8hqiky7ml','vl-wlrgrcmpk5rkfg0gs7lbkz9cqopa','disk-ymkygj5n2gpkfvd0i8tuzl1txfaa','admin','admin',1726145157,1726145157,0,1,'system'),(1080,'d-kxqwytjua091giupgjk8hqiky7ml','vl-wlrgrcmpk5rkfg0gs7lbkz9cqopa','disk-kydj8bf60rfrduo94kmx4ntjb2f5','admin','admin',1726211007,1726211007,0,1,'system'),(1081,'d-kxqwytjua091giupgjk8hqiky7ml','vl-wlrgrcmpk5rkfg0gs7lbkz9cqopa','disk-r5vepgotjkru7y34y1xjrl2sutu5','admin','admin',1726221183,1726221183,0,1,'system'),(1082,'d-kxqwytjua091giupgjk8hqiky7ml','vl-wlrgrcmpk5rkfg0gs7lbkz9cqopa','disk-3y24cy5fr6f5zijucyc4io996qy6','admin','admin',1726221196,1726221196,0,0,'system'); +/*!40000 ALTER TABLE `r_device_volume_disks` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `r_instance_sshkey` +-- + +DROP TABLE IF EXISTS `r_instance_sshkey`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `r_instance_sshkey` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `instance_id` varchar(255) NOT NULL DEFAULT '' COMMENT '实例ID', + `sshkey_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'sshkeyid', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(255) NOT NULL DEFAULT '0' COMMENT '创建时间', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + PRIMARY KEY (`id`) USING BTREE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='实例ssh秘钥关系表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `r_instance_sshkey` +-- + +LOCK TABLES `r_instance_sshkey` WRITE; +/*!40000 ALTER TABLE `r_instance_sshkey` DISABLE KEYS */; +/*!40000 ALTER TABLE `r_instance_sshkey` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `r_instance_volume_raid` +-- + +DROP TABLE IF EXISTS `r_instance_volume_raid`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `r_instance_volume_raid` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', + `instance_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'instance uuid', + `volume_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'volume uuid', + `volume_type` varchar(255) NOT NULL DEFAULT '' COMMENT 'data|system', + `raid_can` varchar(16) NOT NULL DEFAULT '' COMMENT 'RAID配置: (RAID,NO RAID)', + `raid_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'RAID模式:raidid,一个一条', + `raid_name` varchar(255) NOT NULL DEFAULT '' COMMENT 'RAID名称', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(255) NOT NULL DEFAULT '0' COMMENT '创建时间', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + PRIMARY KEY (`id`) USING BTREE, + KEY `i_instance_id` (`instance_id`) USING BTREE, + KEY `i_volume_type` (`volume_type`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=62 DEFAULT CHARSET=utf8 COMMENT='实例每个数据卷选择的raid'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `r_instance_volume_raid` +-- + +LOCK TABLES `r_instance_volume_raid` WRITE; +/*!40000 ALTER TABLE `r_instance_volume_raid` DISABLE KEYS */; +/*!40000 ALTER TABLE `r_instance_volume_raid` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `r_monitor_rules_instance` +-- + +DROP TABLE IF EXISTS `r_monitor_rules_instance`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `r_monitor_rules_instance` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `rule_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'rule uuid', + `rule_name` varchar(255) NOT NULL DEFAULT '' COMMENT '规则名称', + `instance_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'instance uuid', + `instance_name` varchar(255) NOT NULL DEFAULT '' COMMENT 'instance name', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `tags` varchar(255) NOT NULL DEFAULT '' COMMENT 'disk/mountpoint/nic tag', + `project_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'project uuid', + PRIMARY KEY (`id`) USING BTREE, + KEY `i_rule_id` (`rule_id`), + KEY `i_instance_id` (`instance_id`) +) ENGINE=InnoDB AUTO_INCREMENT=215 DEFAULT CHARSET=utf8 COMMENT='带内监控规则-实例关联表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `r_monitor_rules_instance` +-- + +LOCK TABLES `r_monitor_rules_instance` WRITE; +/*!40000 ALTER TABLE `r_monitor_rules_instance` DISABLE KEYS */; +/*!40000 ALTER TABLE `r_monitor_rules_instance` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `r_volume_raid` +-- + +DROP TABLE IF EXISTS `r_volume_raid`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `r_volume_raid` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', + `volume_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'volume uuid', + `device_type_id` varchar(255) NOT NULL DEFAULT '' COMMENT '设备类型uuid', + `raid_can` varchar(16) NOT NULL DEFAULT '' COMMENT 'RAID配置: (RAID,NO RAID)', + `raid_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'RAID模式:raidid,一个一条', + `raid_name` varchar(255) NOT NULL DEFAULT '' COMMENT 'RAID名称', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(255) NOT NULL DEFAULT '0' COMMENT '创建时间', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `volume_type` varchar(255) NOT NULL DEFAULT '' COMMENT 'data|system', + PRIMARY KEY (`id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=822 DEFAULT CHARSET=utf8 COMMENT='卷管理表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `r_volume_raid` +-- + +LOCK TABLES `r_volume_raid` WRITE; +/*!40000 ALTER TABLE `r_volume_raid` DISABLE KEYS */; +/*!40000 ALTER TABLE `r_volume_raid` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `raid` +-- + +DROP TABLE IF EXISTS `raid`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `raid` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', + `raid_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'raid uuid', + `name` varchar(16) NOT NULL DEFAULT '' COMMENT 'raid类型 noraid,raid0,raid1,raid10', + `description_en` varchar(512) NOT NULL DEFAULT '' COMMENT 'RAID英文描述', + `description_zh` varchar(256) NOT NULL DEFAULT '' COMMENT 'RAID中文描述', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `i_raid_uuid` (`raid_id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='raid'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `raid` +-- + +LOCK TABLES `raid` WRITE; +/*!40000 ALTER TABLE `raid` DISABLE KEYS */; +INSERT INTO `raid` VALUES (1,'r-qytwf9r5h0yn9x4evjkyr0n1cwyb','NO RAID','NO RAID means that each physical disk is displayed independently as a logical disk. There is no block stripping and no data redundancy.','NO RAID是每个物理磁盘独立显示为一个逻辑盘,没有数据块分条(no block stripping),不提供数据冗余。','','',0,0,0,0),(2,'r-sfykwibcvcyztuez3mk1klyha9nn','RAID0','RAID0 means that the entire logical disk data is striped among multiple physical disks, it allows read/write in parallel and provides the fastest speed with no redundancy.','RAID0是整个逻辑盘的数据是被分条(stripped)分布在多个物理磁盘上,可以并行读/写,提供最快的速度,但没有冗余能力。','','',0,0,0,0),(3,'r-wtzluqacgzzxgunnabdkpnpjew3d','RAID1','RAID1 also known as mirroring method, provides data redundancy. In the entire mirroring process, only half of the disk capacity is valid, the other half is used to store the same data. RAID1 has taken security into consideration with half capacity and full speed.','RAID1又称镜像方式,提供数据的冗余。在整个镜像过程中,只有一半的磁盘容量是有效的(另一半磁盘容量用来存放同样的数据),RAID1考虑了安全性,容量减半、速度不变。','','',0,0,0,0),(4,'r-l6pounvfife0njlinhk6ztf2xyio','RAID10','RAID10 is used for achieving the high speed and security purposes. RAID 10 can be simply interpreted as the RAID 0 array composed of several disks, which then provides the image.','RAID10是为了达到既高速又安全,可以把RAID 10简单地理解成由多个磁盘组成的RAID 0阵列再进行镜像。','','',0,0,0,0),(5,'r-lowdd8nf8y7v6jk5ocr5paqhvhre','RAID51H','RAID 5+1 hotspare offers you a resolution featuring high performance, data security and reasonable cost in storage, with added hot backup disks for better data security.','RAID 5+1 hotspare是一种存储性能、数据安全和存储成本兼顾的存储解决方案,同时增加热备盘来提升数据安全。','','',0,0,0,1),(6,'r-493obv9i0fyubxfgnuatrffj5qy0','RAID5','raid5 is...','raid5 是一种。。。','','',0,0,0,0); +/*!40000 ALTER TABLE `raid` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `role` +-- + +DROP TABLE IF EXISTS `role`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `role` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `role_id` varchar(255) NOT NULL DEFAULT '' COMMENT '角色uuid', + `role_name_en` varchar(255) NOT NULL DEFAULT '' COMMENT '角色名称,唯一', + `role_name_cn` varchar(255) NOT NULL DEFAULT '' COMMENT '角色名称,唯一', + `description_en` varchar(255) NOT NULL DEFAULT '' COMMENT '权限描述', + `description_cn` varchar(255) NOT NULL DEFAULT '' COMMENT '权限描述', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + PRIMARY KEY (`id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='角色'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `role` +-- + +LOCK TABLES `role` WRITE; +/*!40000 ALTER TABLE `role` DISABLE KEYS */; +INSERT INTO `role` VALUES (1,'role-admin-uuid-01','Owner','平台拥有者','Possess access to the console & operation platform, and all operation rights.','拥有访问控制台&运营平台访问权限,全部操作权限。','admin','admin',1666275445,1666275445,0,0),(2,'role-operator-uuid-01','Operator','运营人员','Possess access rights to the operation platform, all operation rights (except user management and role management).','拥有运营平台访问权限,所有操作权限(除用户管理和角色管理)。','admin','admin',1666278266,1666278266,0,0),(3,'role-user-uuid-01','User','普通用户','Have access to the console, all operations, no access to the operating platform.','拥有控制台访问权限,所有操作权限,无运营平台访问权限。','admin','admin',1666275474,1666275474,0,0); +/*!40000 ALTER TABLE `role` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `sharing_project` +-- + +DROP TABLE IF EXISTS `sharing_project`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `sharing_project` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `project_id` varchar(255) NOT NULL DEFAULT '' COMMENT '项目uuid', + `owner_user_id` varchar(255) NOT NULL DEFAULT '' COMMENT '项目拥有者用户id', + `shared_user_id` varchar(255) NOT NULL DEFAULT '' COMMENT '项目共享者用户id', + `owner_user_name` varchar(255) NOT NULL DEFAULT '' COMMENT '项目拥有者用户名', + `shared_user_name` varchar(255) NOT NULL DEFAULT '' COMMENT '项目拥有者用户名', + `is_default` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否默认项目0否 1是', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `project_name` varchar(255) NOT NULL DEFAULT '', + `premission` varchar(64) NOT NULL DEFAULT '' COMMENT 'read or write premission', + `shared_instance_ids` text NOT NULL COMMENT 'sharding instances', + PRIMARY KEY (`id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='共享项目'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `sharing_project` +-- + +LOCK TABLES `sharing_project` WRITE; +/*!40000 ALTER TABLE `sharing_project` DISABLE KEYS */; +/*!40000 ALTER TABLE `sharing_project` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `sms_Logs` +-- + +DROP TABLE IF EXISTS `sms_Logs`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `sms_Logs` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `service_provider` varchar(255) NOT NULL, + `content` text NOT NULL, + `phone` varchar(16) DEFAULT NULL, + `send_time` int(11) NOT NULL, + `is_success` varchar(255) NOT NULL, + `err_msg` text NOT NULL, + `is_del` varchar(11) NOT NULL, + `phone_prefix` varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=116 DEFAULT CHARSET=utf8mb4; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `sms_Logs` +-- + +LOCK TABLES `sms_Logs` WRITE; +/*!40000 ALTER TABLE `sms_Logs` DISABLE KEYS */; +/*!40000 ALTER TABLE `sms_Logs` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `sms_template` +-- + +DROP TABLE IF EXISTS `sms_template`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `sms_template` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `name` varchar(255) NOT NULL, + `service_provider` varchar(255) NOT NULL, + `secret_id` varchar(255) NOT NULL, + `secret_key` varchar(255) NOT NULL, + `sign_code` varchar(255) NOT NULL, + `template_id` varchar(255) NOT NULL, + `tencent_app_id` varchar(255) NOT NULL, + `hw_from` varchar(255) NOT NULL, + `hw_callback_url` varchar(255) NOT NULL, + `is_push` varchar(255) NOT NULL, + `is_del` varchar(255) NOT NULL, + `is_pass` varchar(255) NOT NULL, + `created_time` int(11) NOT NULL, + `updated_time` int(11) NOT NULL, + `deleted_time` int(11) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `name` (`name`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `sms_template` +-- + +LOCK TABLES `sms_template` WRITE; +/*!40000 ALTER TABLE `sms_template` DISABLE KEYS */; +/*!40000 ALTER TABLE `sms_template` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `ssh_key` +-- + +DROP TABLE IF EXISTS `ssh_key`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `ssh_key` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `sshkey_id` varchar(255) NOT NULL DEFAULT '' COMMENT '秘钥uuid', + `user_id` varchar(255) NOT NULL DEFAULT '' COMMENT '用户uuid', + `name` varchar(255) NOT NULL DEFAULT '' COMMENT '秘钥名称', + `key` varchar(1024) NOT NULL DEFAULT '0' COMMENT '公钥,格式:ssh-rsa AAA', + `finger_print` varchar(255) NOT NULL DEFAULT '' COMMENT '公钥指纹', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + PRIMARY KEY (`id`) USING BTREE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='秘钥'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `ssh_key` +-- + +LOCK TABLES `ssh_key` WRITE; +/*!40000 ALTER TABLE `ssh_key` DISABLE KEYS */; +/*!40000 ALTER TABLE `ssh_key` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `user` +-- + +DROP TABLE IF EXISTS `user`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `user` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `user_id` varchar(255) NOT NULL DEFAULT '' COMMENT '用户uuid', + `role_id` varchar(255) NOT NULL DEFAULT '' COMMENT '角色uuid', + `user_name` varchar(255) NOT NULL DEFAULT '' COMMENT '用户名,唯一', + `email` varchar(255) NOT NULL DEFAULT '' COMMENT '邮箱', + `phone_prefix` varchar(255) NOT NULL DEFAULT '' COMMENT '国家地区码,如86', + `phone_number` varchar(255) NOT NULL DEFAULT '' COMMENT '手机号', + `default_project_id` varchar(255) NOT NULL DEFAULT '' COMMENT '所属项目uuid', + `language` varchar(255) DEFAULT NULL COMMENT '语言(中文/English)', + `timezone` varchar(64) NOT NULL DEFAULT 'Asia/Shanghai' COMMENT 'timezone', + `password` varchar(255) NOT NULL DEFAULT '' COMMENT '密码,sha256非对称加密后存储', + `description` varchar(1024) NOT NULL DEFAULT '' COMMENT '描述', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间戳', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间戳', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间戳', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + PRIMARY KEY (`id`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8 COMMENT='用户'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `user` +-- + +LOCK TABLES `user` WRITE; +/*!40000 ALTER TABLE `user` DISABLE KEYS */; +INSERT INTO `user` VALUES (1,'user-ta5c5tsos2wkm8d2qtmvx3vufr2h','role-admin-uuid-01','admin','','','','project-vtdz6jyqux7gxgglzk5fsdiyqy8k','zh_CN','Asia/Shanghai','$2a$10$vl6tEXezDh32egRS5/xkFePmKbS.6D70BaGoR9s180iKJbsdfoaqm','默认管理员','admin','admin',1674959410,1725521379,1675664498,0); +/*!40000 ALTER TABLE `user` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `volume` +-- + +DROP TABLE IF EXISTS `volume`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `volume` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', + `volume_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'volume uuid', + `device_type_id` varchar(255) NOT NULL DEFAULT '' COMMENT '设备类型uuid', + `volume_name` varchar(100) NOT NULL DEFAULT '' COMMENT '卷名称', + `volume_type` varchar(255) NOT NULL DEFAULT '' COMMENT '卷类型:系统卷,数据卷', + `disk_type` varchar(16) NOT NULL DEFAULT '' COMMENT '硬盘类型(SSD,HDD)', + `interface_type` varchar(16) NOT NULL DEFAULT '' COMMENT '接口类型(SATA,SAS,NVME,不限制)', + `volume_size` varchar(50) NOT NULL DEFAULT '0' COMMENT '单盘大小(最小容量)', + `volume_unit` varchar(16) NOT NULL DEFAULT '0' COMMENT '硬盘单位(GB,TB)', + `volume_amount` int(11) NOT NULL DEFAULT '0' COMMENT '硬盘数量(最低块数)', + `created_by` varchar(255) NOT NULL DEFAULT '' COMMENT '创建者', + `updated_by` varchar(255) NOT NULL DEFAULT '' COMMENT '更新者', + `created_time` int(255) NOT NULL DEFAULT '0' COMMENT '创建时间', + `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间', + `deleted_time` int(11) NOT NULL DEFAULT '0' COMMENT '删除时间', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + PRIMARY KEY (`id`) USING BTREE, + KEY `i_device_type_type` (`volume_type`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=722 DEFAULT CHARSET=utf8 COMMENT='卷管理表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `volume` +-- + +LOCK TABLES `volume` WRITE; +/*!40000 ALTER TABLE `volume` DISABLE KEYS */; +/*!40000 ALTER TABLE `volume` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `web_message` +-- + +DROP TABLE IF EXISTS `web_message`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `web_message` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `message_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'message_id', + `user_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'user_id', + `resource_type` varchar(255) NOT NULL DEFAULT '' COMMENT '资源类型', + `result` varchar(255) NOT NULL DEFAULT '' COMMENT '操作结果', + `finish_time` int(11) NOT NULL DEFAULT '0' COMMENT '完成时间戳', + `has_read` tinyint(4) NOT NULL DEFAULT '0' COMMENT '0未读, 1已读', + `is_del` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除0未删除 1已删除', + `message_type` varchar(255) NOT NULL DEFAULT '', + `message_sub_type` varchar(255) NOT NULL DEFAULT '', + `instance_id` varchar(255) NOT NULL DEFAULT '', + `sn` varchar(255) NOT NULL DEFAULT '', + `detail` varchar(4096) NOT NULL DEFAULT '', + `fault_type` varchar(255) NOT NULL DEFAULT '' COMMENT 'oob-alert spec field', + `content` varchar(4096) NOT NULL DEFAULT '' COMMENT 'oob-alert spec field', + `logid` varchar(255) NOT NULL DEFAULT '' COMMENT 'oob-alert spec field', + `alert_time` int(11) NOT NULL DEFAULT '0' COMMENT 'oob-alert spec field', + `alert_count` int(11) NOT NULL DEFAULT '0' COMMENT 'oob-alert spec field', + `license_name` varchar(255) NOT NULL DEFAULT '' COMMENT 'license spec field', + `license_number` varchar(255) NOT NULL DEFAULT '' COMMENT 'license spec field', + `license_start_time` int(11) NOT NULL DEFAULT '0' COMMENT 'license spec field', + `license_end_time` int(11) NOT NULL DEFAULT '0' COMMENT 'license spec field', + `instance_name` varchar(255) NOT NULL DEFAULT '', + `user_name` varchar(255) NOT NULL DEFAULT '' COMMENT 'user_name', + `rule_id` varchar(255) NOT NULL DEFAULT '' COMMENT 'inbond_rule_id', + `rule_name` varchar(255) NOT NULL DEFAULT '' COMMENT 'inbond_rule_name', + `is_recover` tinyint(4) NOT NULL DEFAULT '0' COMMENT '0->alert, 1->recover', + PRIMARY KEY (`id`) USING BTREE, + KEY `i_message_userid` (`user_id`), + KEY `i_message_read` (`has_read`), + KEY `message_type_idx` (`message_type`), + KEY `message_sub_type_idx` (`message_sub_type`), + KEY `has_read_idx` (`has_read`), + KEY `userid_idx` (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=7648 DEFAULT CHARSET=utf8 COMMENT='web_message'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `web_message` +-- + +LOCK TABLES `web_message` WRITE; +/*!40000 ALTER TABLE `web_message` DISABLE KEYS */; +/*!40000 ALTER TABLE `web_message` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2024-09-14 9:10:50 diff --git a/bmp-deploy/template/alertmanager.tpl b/bmp-deploy/template/alertmanager.tpl new file mode 100644 index 0000000..048b1c7 --- /dev/null +++ b/bmp-deploy/template/alertmanager.tpl @@ -0,0 +1,45 @@ +global: + resolve_timeout: 5s +route: + group_by: ['alertname'] + group_wait: 0s + group_interval: 60m + repeat_interval: 10s + receiver: 'bmpAlertReceiver' + routes: + - receiver: 'bmpAlertReceiver' + group_interval: 5m + match: + noticePeriodLabel: NoticePeriod-5m + - receiver: 'bmpAlertReceiver' + group_interval: 10m + match: + noticePeriodLabel: NoticePeriod-10m + - receiver: 'bmpAlertReceiver' + group_interval: 15m + match: + noticePeriodLabel: NoticePeriod-15m + - receiver: 'bmpAlertReceiver' + group_interval: 30m + match: + noticePeriodLabel: NoticePeriod-30m + - receiver: 'bmpAlertReceiver' + group_interval: 60m + match: + noticePeriodLabel: NoticePeriod-60m + - receiver: 'bmpAlertReceiver' + group_interval: 180m + match: + noticePeriodLabel: NoticePeriod-180m + - receiver: 'bmpAlertReceiver' + group_interval: 720m + match: + noticePeriodLabel: NoticePeriod-720m + - receiver: 'bmpAlertReceiver' + group_interval: 1440m + match: + noticePeriodLabel: NoticePeriod-1440m +receivers: + - name: 'bmpAlertReceiver' + webhook_configs: + - url: 'http://${BMP_PRONOEA_HOST}:${BMP_PRONOEA_PORT}/api/alert/receiver' \ No newline at end of file diff --git a/bmp-deploy/template/bmp-console-web.nginx.tpl b/bmp-deploy/template/bmp-console-web.nginx.tpl new file mode 100644 index 0000000..be1b356 --- /dev/null +++ b/bmp-deploy/template/bmp-console-web.nginx.tpl @@ -0,0 +1,44 @@ +log_format main1 '$time_local | $remote_addr | $upstream_addr | $http_host | $status | $body_bytes_sent | $upstream_response_time | $request_time | $http_host | $request | $http_referer'; + +server { + listen 8080; + server_name bmp-console.bmp.local; + charset utf-8; + access_log /var/log/nginx/access.log main1; + + error_page 500 502 503 504 /50x.html; + location = /50x.html { + root html; + } + + root /home/bmp/bmp-console-web; + index index.html; + + location /console-web/ { + resolver 127.0.0.11 ipv6=off valid=2s; + set $bmp_console_api "bmp-console-api:8800"; + rewrite ^/console-web/(.*) /$1 break; + proxy_pass http://$bmp_console_api; + } + + location /oob-alert/ { + client_max_body_size 51200M; + resolver 127.0.0.11 ipv6=off valid=2s; + set $bmp_oob_alert "bmp-oob-alert:8804"; + rewrite ^/oob-alert/(.*) /$1 break; + proxy_pass http://$bmp_oob_alert; + } + + location / { + try_files $uri $uri/ @router; + index index.html; + } + + location @router { + rewrite ^.*$ /index.html last; + } + location ~.*\.(html)$ { + add_header Cache-Control no-cache; + } + +} \ No newline at end of file diff --git a/bmp-deploy/template/bmp-operation-web.nginx.tpl b/bmp-deploy/template/bmp-operation-web.nginx.tpl new file mode 100644 index 0000000..f159ea4 --- /dev/null +++ b/bmp-deploy/template/bmp-operation-web.nginx.tpl @@ -0,0 +1,54 @@ +log_format main1 '$time_local | $remote_addr | $upstream_addr | $http_host | $status | $body_bytes_sent | $upstream_response_time | $request_time | $http_host | $request | $http_referer'; + +server { + listen 8081; + server_name bmp-operation.bmp.local; + charset utf-8; + access_log /var/log/nginx/access.log main1; + + error_page 500 502 503 504 /50x.html; + location = /50x.html { + root html; + } + + root /home/bmp/bmp-operation-web; + index index.html; + + # compression-webpack-plugin 配置 + #gzip on; + #gzip_min_length 1k; + #gzip_comp_level 9; + #gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript applicationx-httpd-php image/jpeg image/gif image/png; + #gzip_vary on; + # 配置禁用 gzip 条件,支持正则,此处表示 ie6 及以下不启用 gzip(因为ie低版本不支持) + #gzip_disable "MSIE [1-6]\."; + + location /operation-web/ { + client_max_body_size 51200M; + resolver 127.0.0.11 ipv6=off valid=2s; + set $bmp_operation_api "bmp-operation-api:8799"; + rewrite ^/operation-web/(.*) /$1 break; + proxy_pass http://$bmp_operation_api; + } + + location /oob-alert/ { + client_max_body_size 51200M; + resolver 127.0.0.11 ipv6=off valid=2s; + set $bmp_oob_alert "bmp-oob-alert:8804"; + rewrite ^/oob-alert/(.*) /$1 break; + proxy_pass http://$bmp_oob_alert; + } + + location / { + try_files $uri $uri/ @router; + index index.html; + } + + location @router { + rewrite ^.*$ /index.html last; + } + location ~.*\.(html)$ { + add_header Cache-Control no-cache; + } + +} diff --git a/bmp-deploy/template/bmp-rsyslog.conf.tpl b/bmp-deploy/template/bmp-rsyslog.conf.tpl new file mode 100644 index 0000000..abe1be8 --- /dev/null +++ b/bmp-deploy/template/bmp-rsyslog.conf.tpl @@ -0,0 +1,8 @@ +module(load="imudp") # needs to be done just once +input(type="imudp" port="514") + +$template RemoteLogs,"/var/log/bmp/bmp-rsyslog/%fromhost-ip%/%PROGRAMNAME%-%$YEAR%-%$MONTH%-%$DAY%.log" +$template DynamicDir,"/var/log/bmp/bmp-rsyslog/%fromhost-ip%" +:syslogtag, startswith, "ip" ?DynamicDir +if $fromhost-ip != "127.0.0.1" then ?RemoteLogs +& ~ \ No newline at end of file diff --git a/bmp-deploy/template/dhcpd.conf.tpl b/bmp-deploy/template/dhcpd.conf.tpl new file mode 100644 index 0000000..834930e --- /dev/null +++ b/bmp-deploy/template/dhcpd.conf.tpl @@ -0,0 +1,42 @@ +ddns-update-style none; +ignore client-updates; +ddns-update-style none; +ignore client-updates; + +next-server ${BMP_HOST_IP}; +filename \"pxelinux.0\"; + +default-lease-time 600; +max-lease-time 1200; +option domain-name \"localhost\"; +option domain-name-servers 114.114.114.114,8.8.8.8; + +#pxe +option client-system-architecture code 93 = unsigned integer 16; +class \"pxe-clients\" { + match if (substring (option vendor-class-identifier, 0, 9) = \"PXEClient\") or + (substring (option vendor-class-identifier, 0, 9) = \"HW-Client\"); + if option client-system-architecture = 00:00 { + filename \"pxelinux.0\"; + }else if option client-system-architecture = 00:07 { + filename \"/uefi/x86_64/grubx64.efi\"; + }else if option client-system-architecture = 00:0b { + filename \"/uefi/arm64/grubaa64.efi\"; + }else if option client-system-architecture = 00:0c { + filename \"/uefi/loongarch64/BOOTLOONGARCH64.EFI\"; + }else if option client-system-architecture = 00:27 { + filename \"/uefi/loongarch64/BOOTLOONGARCH64.EFI\"; + } +} + +key omapi_key { + algorithm hmac-md5; + secret ${BMP_OMAPI_KEY}; +}; +omapi-key omapi_key; +omapi-port ${BMP_OMAPI_PORT}; + +subnet ${BMP_HOST_IP} netmask 255.255.255.255 { + +} + diff --git a/bmp-deploy/template/grub_arm64.cfg.tpl b/bmp-deploy/template/grub_arm64.cfg.tpl new file mode 100644 index 0000000..b3beb5f --- /dev/null +++ b/bmp-deploy/template/grub_arm64.cfg.tpl @@ -0,0 +1,6 @@ +set timeout=1 +set default=1 +menuentry "bmp agent arm64 uefi" { + linux ${BMP_KERNEL_PATH_arm64} console=ttyAMA0 console=tty0 net.ifnames=0 biosdevname=0 ksdevice=bootif kssendmac text BMP_MQ_HOST=${BMP_HOST_IP} BMP_MQ_PORT=${BMP_MQ_PORT} BMP_MQ_USER=${BMP_MQ_USER} BMP_MQ_PASSWORD='${BMP_MQ_PASSWORD}' BMP_MQ_VHOST=${BMP_MQ_VHOST} BMP_MQ_EXCHANGE_ROUTING_KEY=${BMP_MQ_EXCHANGE_ROUTING_KEY} BMP_IMAGE_HOST=${BMP_HOST_IP} BMP_IMAGE_PORT=${BMP_IMAGE_PORT} + initrd ${BMP_INITRAMFS_PATH_arm64} +} diff --git a/bmp-deploy/template/grub_loongarch64.cfg.tpl b/bmp-deploy/template/grub_loongarch64.cfg.tpl new file mode 100644 index 0000000..322d13a --- /dev/null +++ b/bmp-deploy/template/grub_loongarch64.cfg.tpl @@ -0,0 +1,6 @@ +set timeout=1 +set default=1 +menuentry 'bmp agent loongarch64 uefi' { + linux ${BMP_KERNEL_PATH_loonarch64} console=ttyS0,115200 console=tty0 net.ifnames=0 biosdevname=0 ksdevice=bootif kssendmac text BMP_MQ_HOST=${BMP_HOST_IP} BMP_MQ_PORT=${BMP_MQ_PORT} BMP_MQ_USER=${BMP_MQ_USER} BMP_MQ_PASSWORD='${BMP_MQ_PASSWORD}' BMP_MQ_VHOST=${BMP_MQ_VHOST} BMP_MQ_EXCHANGE_ROUTING_KEY=${BMP_MQ_EXCHANGE_ROUTING_KEY} BMP_IMAGE_HOST=${BMP_HOST_IP} BMP_IMAGE_PORT=${BMP_IMAGE_PORT} + initrd ${BMP_INITRAMFS_PATH_loonarch64} +} diff --git a/bmp-deploy/template/grub_x86_64.cfg.tpl b/bmp-deploy/template/grub_x86_64.cfg.tpl new file mode 100644 index 0000000..742e8ef --- /dev/null +++ b/bmp-deploy/template/grub_x86_64.cfg.tpl @@ -0,0 +1,6 @@ +set timeout=1 +set default=1 +menuentry 'bmp agent x86_64 uefi' { + linuxefi ${BMP_KERNEL_PATH_x86} net.ifnames=0 biosdevname=0 ksdevice=bootif kssendmac text BMP_MQ_HOST=${BMP_HOST_IP} BMP_MQ_PORT=${BMP_MQ_PORT} BMP_MQ_USER=${BMP_MQ_USER} BMP_MQ_PASSWORD='${BMP_MQ_PASSWORD}' BMP_MQ_VHOST=${BMP_MQ_VHOST} BMP_MQ_EXCHANGE_ROUTING_KEY=${BMP_MQ_EXCHANGE_ROUTING_KEY} BMP_IMAGE_HOST=${BMP_HOST_IP} BMP_IMAGE_PORT=${BMP_IMAGE_PORT} + initrdefi ${BMP_INITRAMFS_PATH_x86} +} diff --git a/bmp-deploy/template/prometheus.tpl b/bmp-deploy/template/prometheus.tpl new file mode 100644 index 0000000..2985dfb --- /dev/null +++ b/bmp-deploy/template/prometheus.tpl @@ -0,0 +1,13 @@ +scrape_configs: + - job_name: 'pushgateway' + scrape_interval: 60s + honor_labels: true + static_configs: + - targets: ['${BMP_PUSHGATEWAY_HOST}:${BMP_PUSHGATEWAY_PORT}'] +alerting: + alertmanagers: + - static_configs: + - targets: ['${BMP_ALERTMANAGER_HOST}:${BMP_ALERTMANAGER_PORT}'] + +rule_files: + - /var/lib/prometheus/conf/rules/*.yml \ No newline at end of file diff --git a/bmp-deploy/template/pxelinux.tpl b/bmp-deploy/template/pxelinux.tpl new file mode 100644 index 0000000..924827a --- /dev/null +++ b/bmp-deploy/template/pxelinux.tpl @@ -0,0 +1,6 @@ +default bmp agent + prompt 0 + timeout 1 + label bmp agent + kernel ${BMP_KERNEL_PATH_x86} + append initrd=${BMP_INITRAMFS_PATH_x86} net.ifnames=0 biosdevname=0 BMP_MQ_HOST=${BMP_HOST_IP} BMP_MQ_PORT=${BMP_MQ_PORT} BMP_MQ_USER=${BMP_MQ_USER} BMP_MQ_PASSWORD='${BMP_MQ_PASSWORD}' BMP_MQ_VHOST=${BMP_MQ_VHOST} BMP_MQ_EXCHANGE_ROUTING_KEY=${BMP_MQ_EXCHANGE_ROUTING_KEY} BMP_IMAGE_HOST=${BMP_HOST_IP} BMP_IMAGE_PORT=${BMP_IMAGE_PORT} BMP_RSYSLOG_HSOT=${BMP_HOST_IP} BMP_RSYSLOG_PORT=${BMP_RSYSLOG_PORT} \ No newline at end of file diff --git a/bmp-deploy/template/redis.conf.tpl b/bmp-deploy/template/redis.conf.tpl new file mode 100644 index 0000000..c912f16 --- /dev/null +++ b/bmp-deploy/template/redis.conf.tpl @@ -0,0 +1,4 @@ +requirepass ${BMP_REDIS_PASSWORD} + +# only arm +ignore-warnings ARM64-COW-BUG \ No newline at end of file diff --git a/bmp-deploy/tool/collect_device_info.sh b/bmp-deploy/tool/collect_device_info.sh new file mode 100644 index 0000000..9d739b8 --- /dev/null +++ b/bmp-deploy/tool/collect_device_info.sh @@ -0,0 +1,97 @@ +#!/bin/bash + +RAID_DRIVER_ALL=(sas2ircu sas3ircu megacli64 storcli64 perccli64 arcconf no_raid) + +SCRIPT_NAME=${0##*/} +usage(){ + help=" +Usage: ./${SCRIPT_NAME} --sn SN --iloIp iloIp --iloUser iloUser --iloPassword iloPassword --ip ip --mask mask --gateway gateway --mac MAC [--raidDriver raidDriver] + +" + printf "$help" +} + +parse_parameters() +{ + #parse parameters + POSITIONAL_ARGS=() + while [[ $# -gt 0 ]]; do + case $1 in + -h|--help) + usage + exit 0 + ;; + --sn) + sn="$2" + shift + shift + ;; + --iloIp) + iloIp="$2" + shift + shift + ;; + --iloUser) + iloUser="$2" + shift + shift + ;; + --iloPassword) + iloPassword="$2" + shift + shift + ;; + --ip) + ip="$2" + shift + shift + ;; + --mask) + mask="$2" + shift + shift + ;; + --gateway) + gateway="$2" + shift + shift + ;; + --mac) + mac="$2" + shift + shift + ;; + --raidDriver) + raidDriver="$2" + shift + shift + ;; + -*|--*) + echo "Unknown option $1" + exit 1 + ;; + *) + POSITIONAL_ARGS+=("$1") # save positional arg + shift # past argument + ;; + esac + done + + #check parameters + [ -n "$sn" ] || { echo "sn is null"; usage; exit 1; } + [ -n "$iloIp" ] || { echo "iloIp is null"; usage; exit 1; } + [ -n "$iloUser" ] || { echo "iloUser is null"; usage; exit 1; } + [ -n "$iloPassword" ] || { echo "iloPassword is null"; usage; exit 1; } + [ -n "$ip" ] || { echo "ip is null"; usage; exit 1; } + [ -n "$mask" ] || { echo "mask is null"; usage; exit 1; } + [ -n "$gateway" ] || { echo "gateway is null"; usage; exit 1; } + [ -n "$mac" ] || { echo "mac is null"; usage; exit 1; } +# [ -n "$raidDriver" ] || raidDriver="megacli64" + [ -n "$raidDriver" ] && [[ ! " ${RAID_DRIVER_ALL[@]} " =~ " $raidDriver " ]] && { echo "raidDriver $raidDriver is not supported! must be one of ${RAID_DRIVER_ALL[@]}"; exit 1; } +} + +parse_parameters $@ +cat << EOF | curl -X POST -H "Content-Type: application/json; charset=utf-8" --data-binary @- 'http://127.0.0.1:8801/v1/collect/collectDeviceInfo' +{"collects":[{"sn":"$sn", "raidDriver":"$raidDriver", "allowOverride":true, "adapterId":0, "iloIp":"$iloIp", "iloUser":"$iloUser", "iloPassword":"$iloPassword", "mac1":"$mac", "privateIpv4":"$ip", "mask":"$mask","gateway":"$gateway"}]} +EOF + diff --git a/bmp-deploy/tool/retry_command.sh b/bmp-deploy/tool/retry_command.sh new file mode 100644 index 0000000..e19d815 --- /dev/null +++ b/bmp-deploy/tool/retry_command.sh @@ -0,0 +1,17 @@ +#!/bin/bash +set -e +SCRIPT_NAME=${0##*/} +usage(){ + help=" +Usage: ./${SCRIPT_NAME} Command_id + +" + printf "$help" +} + +command_id=$1 +[ -n "$command_id" ] || { command_id is null; usage; exit 1; } +[ "$command_id" == "-h" ] && { usage; exit 0; } +cat << EOF | curl -X PUT "127.0.0.1:8801/commands/retryCommand" --data-binary @- +{"offset_command_id":$command_id} +EOF diff --git a/bmp-dhcp-agent/.dockerignore b/bmp-dhcp-agent/.dockerignore new file mode 100644 index 0000000..15d1eaf --- /dev/null +++ b/bmp-dhcp-agent/.dockerignore @@ -0,0 +1,26 @@ +# eclipse meta +.classpath +.project +.settings/ +.DS_Store +bin/ + +# vscode +.vscode/ + +# Log file +*.log + + +# python +*.eggs/ +*.egg-info/ +dist/ +build/ +*.pyc +.stestr +pylintrc +.tox + +# dev +dev.sh \ No newline at end of file diff --git a/bmp-dhcp-agent/.stestr.conf b/bmp-dhcp-agent/.stestr.conf new file mode 100644 index 0000000..5e7bd56 --- /dev/null +++ b/bmp-dhcp-agent/.stestr.conf @@ -0,0 +1,3 @@ +[DEFAULT] +test_path=${OS_TEST_PATH:-./bmpda/tests/unit} +top_dir=./ \ No newline at end of file diff --git a/bmp-dhcp-agent/Changelog.md b/bmp-dhcp-agent/Changelog.md new file mode 100644 index 0000000..0242c3d --- /dev/null +++ b/bmp-dhcp-agent/Changelog.md @@ -0,0 +1,13 @@ +# Changelog + +## [2.0.2] - 2024-07-31 +### Added +- 新增tftp grub 配置下发 + +## [2.0.1] - 2024-07-24 +### Added +- 此项目同时支持bmp、cps、jdstack + +## [2.0.0] - 2024-01-18 +### Added +- 升级到python3 \ No newline at end of file diff --git a/bmp-dhcp-agent/Dockerfile b/bmp-dhcp-agent/Dockerfile new file mode 100644 index 0000000..66ed0b2 --- /dev/null +++ b/bmp-dhcp-agent/Dockerfile @@ -0,0 +1,10 @@ +FROM python:3.6.8-alpine +WORKDIR /home/bmp/bmp-dhcp-agent +ARG PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple +COPY . . +RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.jd.com/g' /etc/apk/repositories \ + && apk add dhcp \ + && apk add gcc musl-dev linux-headers \ + && pip install -r requirements.txt -i $PIP_INDEX_URL +ENV PYTHONPATH /home/bmp/bmp-dhcp-agent +CMD ["python3", "./bmpda/cmd/server.py"] diff --git a/bmp-dhcp-agent/MANIFEST.in b/bmp-dhcp-agent/MANIFEST.in new file mode 100755 index 0000000..cb79749 --- /dev/null +++ b/bmp-dhcp-agent/MANIFEST.in @@ -0,0 +1,3 @@ +include README.md +include docs/*.md +include template/*.tpl \ No newline at end of file diff --git a/bmp-dhcp-agent/Makefile b/bmp-dhcp-agent/Makefile new file mode 100755 index 0000000..e3de7b3 --- /dev/null +++ b/bmp-dhcp-agent/Makefile @@ -0,0 +1,48 @@ +.PHONY: clean-pyc clean-build clean + +help: + @echo "clean - remove all build, test, coverage and Python artifacts" + @echo "clean-build - remove build artifacts" + @echo "clean-pyc - remove Python file artifacts" + @echo "clean-test - remove test and coverage artifacts" + @echo "lint - check style with flake8" + @echo "test - run tests quickly with the default Python" + @echo "test-all - run tests on every Python version with tox" + @echo "install - install the package to the active Python's site-packages" + @echo "develop - build the package to the develop Python's site-packages" + +clean: clean-build clean-pyc clean-test + +clean-build: + rm -fr build/ + rm -fr dist/ + rm -fr .eggs/ + find . -name '*.egg-info' -exec rm -rf {} + + find . -name '*.egg' -exec rm -rf {} + + find . -name '*.log' -exec rm -rf {} + + +clean-pyc: + find . -name '*.pyc' -exec rm -f {} + + find . -name '*.pyo' -exec rm -f {} + + find . -name '*~' -exec rm -f {} + + find . -name '__pycache__' -exec rm -fr {} + + +clean-test: + rm -fr .tox/ + rm -f .coverage + rm -fr htmlcov/ + +lint: + flake8 leviathan_serving tests + +test: + python3 setup.py test + +test-all: + tox + +install: clean + python3 setup.py install + +develop: clean + python3 setup.py develop \ No newline at end of file diff --git a/bmp-dhcp-agent/README.md b/bmp-dhcp-agent/README.md new file mode 100755 index 0000000..5d1afe0 --- /dev/null +++ b/bmp-dhcp-agent/README.md @@ -0,0 +1,22 @@ +# BMP DHCP Agent +English | [简体中文](README.zh-CN.md) + +Receive the scheduler's commands through MQ and control the DHCP service + +## Core Features +- MAC Address Binding to IP, Assign a fixed IP address to a device based on its MAC address. Example: +``` +host b0-26-28-43-85-b0 { + dynamic; + hardware ethernet b0:26:28:43:85:b0; + fixed-address 10.208.16.4; +} +``` + +- Subnet Configuration: Configure DHCP settings for a specific subnet. Example: +``` +subnet 10.208.16.0 netmask 255.255.255.224 { + option subnet-mask 255.255.255.224; + option routers 10.208.16.1; +} +``` \ No newline at end of file diff --git a/bmp-dhcp-agent/README.zh-CN.md b/bmp-dhcp-agent/README.zh-CN.md new file mode 100755 index 0000000..5126b8c --- /dev/null +++ b/bmp-dhcp-agent/README.zh-CN.md @@ -0,0 +1,22 @@ +# BMP DHCP Agent +[English](README.md) | 简体中文 + +用于接受调度器的命令,对dhcp服务进行控制 + +## 核心特性 +- MAC地址绑定IP,设置特定 MAC 地址的设备绑定固定IP。例如: +``` +host b0-26-28-43-85-b0 { + dynamic; + hardware ethernet b0:26:28:43:85:b0; + fixed-address 10.208.16.4; +} +``` + +- 网段配置,设置DHCP服务的网段和相关选项。例如 +``` +subnet 10.208.16.0 netmask 255.255.255.224 { + option subnet-mask 255.255.255.224; + option routers 10.208.16.1; +} +``` \ No newline at end of file diff --git a/bmp-dhcp-agent/bmp-dhcp-agent.Dockerfile b/bmp-dhcp-agent/bmp-dhcp-agent.Dockerfile new file mode 100644 index 0000000..24443fc --- /dev/null +++ b/bmp-dhcp-agent/bmp-dhcp-agent.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.6-alpine +WORKDIR /home/bmp/bmp-dhcp-agent +COPY . . +RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories \ + && apk add dhcp \ + && pip install -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple -r requirements.txt +ENV PYTHONPATH /home/bmp/bmp-dhcp-agent +CMD ["python3", "./bmpda/cmd/server.py"] diff --git a/bmp-dhcp-agent/bmpda/__init__.py b/bmp-dhcp-agent/bmpda/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/bmp-dhcp-agent/bmpda/agent.py b/bmp-dhcp-agent/bmpda/agent.py new file mode 100644 index 0000000..3483537 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/agent.py @@ -0,0 +1,160 @@ +import logging +import os +import signal +import sys +import threading +import time +from typing import Optional + +from filelock import FileLock + +from bmpda.command import command_service +from bmpda.command.common import Command +from bmpda import config +from bmpda import constants +from bmpda.service import node +from bmpda.utils import dhcp +from bmpda.utils import net + + +LOG = logging.getLogger(__name__) + + +class Agent: + + def __init__(self): + super(Agent, self).__init__() + self.__init_protocol() + self.__init_dhcp() + self._stopped: Optional[threading.Event] = None + + def start(self): + self.__init_node() + self.__init_thread() + self.__bind_signal() + + def stop(self): + LOG.info('stopped...') + self._stopped.set() + self.__unbind_signal() + LOG.info('stopped.') + + def __init_node(self): + node_id = "%(prefix)s-%(host_ip)s" % { + "prefix": config.mq_queue_name_pefix_consumer, + "host_ip": net.get_host_ip() + } + node.set_node_id(node_id) + + def __init_thread(self): + self._stopped = threading.Event() + __protocol_start_thread = threading.Thread( + name='ProtocalStartThread', + target=self.__protocol_start, + daemon=True) + __heartbeat_thread = threading.Thread(name='HeartbeatThread', + target=self.__heartbeat, + daemon=True) + __command_dispatch_thread = threading.Thread( + name='CommandDispatchThread', + target=self.__command_dispatch, + daemon=True) + + __command_query_thread = threading.Thread(name='CommandQueryThread', + target=self.__command_query, + daemon=True) + + __dhcp_ctl_thread = threading.Thread(name='DHCPCtlThread', + target=self.__dhcp_ctl, + daemon=True) + __protocol_start_thread.start() + __heartbeat_thread.start() + __command_dispatch_thread.start() + __command_query_thread.start() + __dhcp_ctl_thread.start() + + def __bind_signal(self): + # bind signal + self.hold_sigint = signal.signal(signal.SIGINT, self.__handler_signal) + self.hold_sigterm = signal.signal(signal.SIGTERM, + self.__handler_signal) + + def __unbind_signal(self): + # unbind signal + signal.signal(signal.SIGINT, self.hold_sigint) + signal.signal(signal.SIGTERM, self.hold_sigterm) + + def __handler_signal(self, signum, frame): + LOG.info("Receive a kill signal %s=%s.", signum, frame) + self.stop() + sys.exit() + + def __heartbeat(self): + LOG.info("Start heartbeat.") + wait = base = config.heart_period + while not self._stopped.is_set(): + try: + __protocol.heartbeat() + wait = base # reset to base wait time on success + LOG.info("Trigger a heart period %d.", wait) + except Exception as exc: + LOG.error(str(exc)) + wait = min(20, wait * 2 or 1) + + time.sleep(wait) + + def __command_dispatch(self): + LOG.info("Start command dispatch.") + command_service.dispatch() + + def __command_query(self): + LOG.info("Start command query.") + while not self._stopped.is_set(): + __protocol.receive_command() + + def __protocol_start(self): + __protocol.start() + + def __init_protocol(self): + global __protocol + if config.protocol == constants.PROTOCAL_RABBITMQ: + from bmpda.protocol.rabbitmq import RabbitmqProtocol + __protocol = RabbitmqProtocol() + LOG.info("Init protocol %s.", config.protocol) + + def send_command(command: Command): + __protocol.send_command(command) + + def __init_dhcp(self): + dhcp_config_path = os.path.join(config.dhcp_config_dir, + "dhcpd.conf") + dhcp_config_lock_path = "%s.lock" % dhcp_config_path + node.set_dhcp_config_path(dhcp_config_path) + node.set_dhcp_config_lock_path(dhcp_config_lock_path) + os.chmod(config.dhcp_control_bin, 0o755) + dhcp.dhcp_ctl('start') + LOG.info("Init dhcp") + + def __dhcp_ctl(self): + dhcp_period = 6 + while not self._stopped.is_set(): + try: + # Only set need_restart_dhcp=False here, + # so no need to lock when obtaining the value. + if node.get_need_restart_dhcp(): + success = dhcp.dhcp_ctl('restart') + if success: + lock_dhcp = FileLock( + node.get_dhcp_config_lock_path(), timeout=3) + with lock_dhcp: + node.set_need_restart_dhcp(False) + else: + LOG.error( + "DHCP restart failed. retry after %d seconds.", + dhcp_period, + exc_info=1) + LOG.info("Trigger a dhcp heart period %d.", dhcp_period) + time.sleep(dhcp_period) + except Exception as e: + LOG.error("DHCP restart failed:%s.", e) + time.sleep(dhcp_period) diff --git a/bmp-dhcp-agent/bmpda/cfg/cps-cn-east-jdr1a b/bmp-dhcp-agent/bmpda/cfg/cps-cn-east-jdr1a new file mode 100644 index 0000000..b4f0462 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/cfg/cps-cn-east-jdr1a @@ -0,0 +1,13 @@ +BMP_MQ_HOST=10.179.27.162 +BMP_MQ_PORT=5672 +BMP_MQ_USER=cps_admin +BMP_MQ_PASSWORD=cps@cHdAiN4mWIyD +BMP_MQ_VHOST=/cps +BMP_MQ_EXCHANGE=CPS_IRONIC_SCHEDULER +BMP_MQ_EXCHANGE_ROUTING_KEY=cn-east-jdr1a +BMP_MQ_QUEUE_NAME_PEFIX_CONSUMER=dhcp-cn-east-jdr1a +BMP_LOG_PATH=/var/log/bmp/bmpda/bmp-dhcp-agent.log +BMP_DHCP_CONFIG_DIR=/etc/dhcp +BMP_OMAPI_KEY=SkR5dW4xMjM= +BMP_RSYSLOG_HSOT=10.179.27.162 +BMP_RSYSLOG_PORT=1514 \ No newline at end of file diff --git a/bmp-dhcp-agent/bmpda/cfg/cps-cn-east-jdr1a-t b/bmp-dhcp-agent/bmpda/cfg/cps-cn-east-jdr1a-t new file mode 100644 index 0000000..7fa231a --- /dev/null +++ b/bmp-dhcp-agent/bmpda/cfg/cps-cn-east-jdr1a-t @@ -0,0 +1,13 @@ +BMP_MQ_HOST=10.208.12.194 +BMP_MQ_PORT=5672 +BMP_MQ_USER=cps_admin +BMP_MQ_PASSWORD=cps@nakfiZHklVf9 +BMP_MQ_VHOST=/cps +BMP_MQ_EXCHANGE=CPS_IRONIC_SCHEDULER +BMP_MQ_EXCHANGE_ROUTING_KEY=cn-east-jdr1a +BMP_MQ_QUEUE_NAME_PEFIX_CONSUMER=dhcp-cn-east-jdr1a +BMP_LOG_PATH=/var/log/bmp/bmpda/bmp-dhcp-agent.log +BMP_DHCP_CONFIG_DIR=/etc/dhcp +BMP_OMAPI_KEY=SkR5dW4xMjM= +BMP_RSYSLOG_HSOT==10.208.12.194 +BMP_RSYSLOG_PORT=1514 \ No newline at end of file diff --git a/bmp-dhcp-agent/bmpda/client/__init__.py b/bmp-dhcp-agent/bmpda/client/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/bmp-dhcp-agent/bmpda/client/rabbitmq.py b/bmp-dhcp-agent/bmpda/client/rabbitmq.py new file mode 100644 index 0000000..d038caf --- /dev/null +++ b/bmp-dhcp-agent/bmpda/client/rabbitmq.py @@ -0,0 +1,464 @@ +import logging +from queue import Empty +from queue import Queue +import time + +import pika + +from bmpda import config +from bmpda.utils import strutils + +LOG = logging.getLogger(__name__) + + +class Consumer(object): + + def __init__(self): + + self.queue = Queue() + # type: pika.connection.Connection + self.connection = None + # type: pika.channel.Channel + self.channel = None + self.consumer_tag = None + + self.username = None + self.password = None + self.host = None + self.port = None + self.vhost = None + self.exchange = None + self.exchange_type = None + self.queue_name = None + self.routing_key = None + + def init(self, queue_name: str): + self.queue_name = queue_name + self.routing_key = config.mq_exchange_routing_key + self.username = config.mq_username + self.password = config.mq_password + self.host = config.mq_host + self.port = config.mq_port + self.vhost = config.mq_vhost + self.exchange = config.mq_exchange_consumer + self.exchange_type = config.mq_exchange_type + + def start(self): + wait = base = 2 + while True: + try: + self._build_connection() + LOG.info('Begin to comsume message.') + self.consumer_tag = self.channel.basic_consume( + queue=self.queue_name, + on_message_callback=self._on_message) + self.channel.start_consuming() + wait = base + except Exception as e: + wait = min(1024, wait * 2) + time.sleep(wait) + LOG.error("Comsume message failed. %s", e, exc_info=1) + finally: + try: + self._stop() + except Exception as e: + LOG.error( + "Close consumer connection failed. " + "retry to reconnect, %s", + e, + exc_info=1) + + def get_message(self): + try: + message = self.queue.get() + # LOG.info("Get message :%s.", message) + LOG.info("Get message :%s.", strutils.mask_password(message.decode('utf-8'))) + return message + except Exception as e: + LOG.warn("Get message error:%s.", str(e)) + return None + + def stop(self): + self._stop() + + def _connection_parameters(self): + credentials = pika.PlainCredentials(self.username, self.password) + return pika.ConnectionParameters(host=self.host, + port=self.port, + virtual_host=self.vhost, + credentials=credentials, + connection_attempts=1, + retry_delay=5, + socket_timeout=5, + heartbeat=5) + + def _build_connection(self): + """This method connects to RabbitMQ, returning the connection handle. + + When the connection is established, the on_connection_open method + will be invoked by pika. + + :rtype: pika.SelectConnection + """ + parameters = self._connection_parameters() + LOG.info('Connecting to %s', parameters) + self._connection = pika.BlockingConnection(parameters=parameters) + self.channel = self._connection.channel() + self._setup_exchange(self.channel, self.exchange, self.exchange_type) + self._setup_queue(self.channel, self.queue_name) + self._bind_queue_to_exchange(self.channel, self.exchange, + self.queue_name, self.routing_key) + + def _setup_exchange(self, channel, exchange_name, exchange_type): + """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC + + command. When it is complete, the on_exchange_declareok method will + be invoked by pika. + + :param str|unicode exchange_name: The name of the exchange to declare + """ + LOG.info('Declaring exchange : %s', exchange_name) + # Note: using functools.partial is not required, it is demonstrating + # how arbitrary data can be passed to the callback when it is called + channel.exchange_declare(exchange=exchange_name, + exchange_type=exchange_type, + durable=True) + + def _setup_queue(self, channel, queue_name, auto_delete=False): + """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC + + command. When it is complete, the on_queue_declareok method will + be invoked by pika. + + :param str|unicode queue_name: The name of the queue to declare. + """ + LOG.info('Declaring queue %s', queue_name) + channel.queue_declare(queue=queue_name, + durable=True, + auto_delete=auto_delete) + + def _bind_queue_to_exchange(self, channel, exchange, queue_name, + routing_key): + """Method invoked by pika when the Queue.Declare RPC call made in + + setup_queue has completed. In this method we will bind the queue + and exchange together with the routing key by issuing the Queue.Bind + RPC command. When this command is complete, the on_bindok method will + be invoked by pika. + + :param pika.frame.Method method_frame: The Queue.DeclareOk frame + :param str|unicode queue_name: Extra user data (queue name) + """ + LOG.info('Binding %s to %s with %s', exchange, queue_name, + routing_key) + channel.queue_bind(queue=queue_name, + exchange=exchange, + routing_key=routing_key) + + def start_consuming(self): + """This method sets up the consumer by first calling + + add_on_cancel_callback so that the object is notified if RabbitMQ + cancels the consumer. It then issues the Basic.Consume RPC command + which returns the consumer tag that is used to uniquely identify the + consumer with RabbitMQ. We keep the value to use it when we want to + cancel consuming. The on_message method is passed in as a callback pika + will invoke when a message is fully received. + """ + try: + LOG.info('Issuing consumer related RPC commands') + self.consumer_tag = self.channel.basic_consume( + queue=self.receive_queue_name, + on_message_callback=self.on_message) + self.channel.start_consuming() + except Exception as e: + try: + self._stop() + self._build_connection() + finally: + message = ("Connect failed. : %s") % str(e) + LOG.error("Connect failed. %s", message, exc_info=1) + + def _on_message(self, unused_channel, basic_deliver, properties, body): + """Invoked by pika when a message is delivered from RabbitMQ. The + + channel is passed for your convenience. The basic_deliver object that + is passed in carries the exchange, routing key, delivery tag and + a redelivered flag for the message. The properties passed in is an + instance of BasicProperties with the message properties and the body + is the message that was sent. + + :param pika.channel.Channel unused_channel: The channel object + :param pika.Spec.Basic.Deliver: basic_deliver method + :param pika.Spec.BasicProperties: properties + :param str|unicode body: The message body + """ + LOG.info('Received message # %s from %s: %s', + basic_deliver.delivery_tag, properties.app_id, strutils.mask_password(body.decode('utf-8'))) + self.queue.put(body) + self._acknowledge_message(basic_deliver.delivery_tag) + + def _acknowledge_message(self, delivery_tag): + """Acknowledge the message delivery from RabbitMQ by sending a + + Basic.Ack RPC method for the delivery tag. + + :param int delivery_tag: The delivery tag from the Basic.Deliver frame + """ + LOG.info('Acknowledging message %s', delivery_tag) + self.channel.basic_ack(delivery_tag) + + def _stop(self): + """Cleanly shutdown the connection to RabbitMQ by stopping the consumer + + with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok + will be invoked by pika, which will then closing the channel and + connection. The IOLoop is started again because this method is invoked + when CTRL-C is pressed raising a KeyboardInterrupt exception. This + exception stops the IOLoop which needs to be running for pika to + communicate with RabbitMQ. All of the commands issued prior to starting + the IOLoop will be buffered but not processed. + """ + + LOG.info('Stopping') + self._stop_consuming() + self._close_channel(self.channel) + self._close_connection(self.connection) + LOG.info('Stopped') + + def _stop_consuming(self): + """Tell RabbitMQ that you would like to stop consuming by sending the + + Basic.Cancel RPC command. + """ + if self.channel and self.channel.is_open: + LOG.info('Sending a Basic.Cancel RPC command to RabbitMQ') + self.channel.basic_cancel(consumer_tag=self.consumer_tag) + LOG.info("Stop consuming") + + def _close_channel(self, channel): + """Call to close the channel with RabbitMQ cleanly by issuing the + + Channel.Close RPC command. + """ + LOG.info('Closing the channel') + if channel and channel.is_open: + channel.close() + + def _close_connection(self, connection): + """This method closes the connection to RabbitMQ.""" + LOG.info('Closing connection') + if connection and connection.is_open: + connection.close() + + def __enter__(self): + return self + + def __exit__(self, exception_type, exception_value, traceback): + if exception_type is not None: + LOG.error("%s, %s, %s", exception_type, exception_value, + traceback) + + +class Publisher(object): + + def __init__(self): + + self.queue = Queue() + self.queue_name = None + self.routing_key = None + # type: pika.connection.Connection + self.connection = None + # type: pika.channel.Channel + self.channel = None + self.consumer_tag = None + + self.username = None + self.password = None + self.host = None + self.port = None + self.vhost = None + self.exchange = None + self.exchange_type = None + + def init(self, routing_key): + self.queue_name = config.mq_exchange + self.routing_key = routing_key + + self.username = config.mq_username + self.password = config.mq_password + self.host = config.mq_host + self.port = config.mq_port + self.vhost = config.mq_vhost + self.exchange = config.mq_exchange + self.exchange_type = config.mq_exchange_type_publish + + def publish_message(self, message): + self.queue.put(message) + + def start(self): + self._build_connection() + while True: + try: + message = self.queue.get(timeout=0.2) + if not message: + LOG.warn("get a None message from publish queue.") + continue + try: + # 未收到ack确认信息时会抛出异常 + self.channel.basic_publish( + exchange=self.exchange, + routing_key=self.routing_key, + body=message, + properties=pika.BasicProperties( + content_type='application/json', + app_id=self.queue_name, + delivery_mode=2)) + + LOG.debug("deliver message to %s %s %s", self.exchange, + self.routing_key, strutils.mask_password(message)) + except Exception as e: + LOG.error( + "Publish message:%s failed, put message into queue. %s", + message, + e, + exc_info=1) + self.queue.put(message) + self._close_channel(self.channel) + self._close_connection(self.connection) + time.sleep(1) + self._build_connection() + time.sleep(1) + except Empty: + LOG.debug("Publish queue is empty.") + time.sleep(1) + continue + except Exception as e: + LOG.error("Publish message failed. %s", e, exc_info=1) + time.sleep(1) + continue + + def stop(self): + self._stop() + + def is_connect(self): + if self.channel and self.channel.is_open: + LOG.debug("RabbitMQ connection is open") + return True + else: + LOG.debug("RabbitMQ connection is closed") + return False + + def _connection_parameters(self): + credentials = pika.PlainCredentials(self.username, self.password) + return pika.ConnectionParameters(host=self.host, + port=self.port, + virtual_host=self.vhost, + credentials=credentials, + connection_attempts=1, + retry_delay=5, + socket_timeout=5, + heartbeat=5) + + def _build_connection(self): + """This method connects to RabbitMQ, returning the connection handle. + + When the connection is established, the on_connection_open method + will be invoked by pika. + + :rtype: pika.SelectConnection + """ + parameters = self._connection_parameters() + LOG.info('Connecting to %s', parameters) + self._connection = pika.BlockingConnection(parameters=parameters) + self.channel = self._connection.channel() + self._setup_exchange(self.channel, self.exchange, self.exchange_type) + self._setup_queue(self.channel, self.queue_name) + self._bind_queue_to_exchange(self.channel, self.exchange, + self.queue_name, self.routing_key) + + def _setup_exchange(self, channel, exchange_name, exchange_type): + """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC + + command. When it is complete, the on_exchange_declareok method will + be invoked by pika. + + :param str|unicode exchange_name: The name of the exchange to declare + """ + LOG.info('Declaring exchange : %s', exchange_name) + # Note: using functools.partial is not required, it is demonstrating + # how arbitrary data can be passed to the callback when it is called + channel.exchange_declare(exchange=exchange_name, + exchange_type=exchange_type, + durable=True) + + def _setup_queue(self, channel, queue_name, auto_delete=False): + """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC + + command. When it is complete, the on_queue_declareok method will + be invoked by pika. + + :param str|unicode queue_name: The name of the queue to declare. + """ + LOG.info('Declaring queue %s', queue_name) + channel.queue_declare(queue=queue_name, + durable=True, + auto_delete=auto_delete) + + def _bind_queue_to_exchange(self, channel, exchange, queue_name, + routing_key): + """Method invoked by pika when the Queue.Declare RPC call made in + + setup_queue has completed. In this method we will bind the queue + and exchange together with the routing key by issuing the Queue.Bind + RPC command. When this command is complete, the on_bindok method will + be invoked by pika. + + :param pika.frame.Method method_frame: The Queue.DeclareOk frame + :param str|unicode queue_name: Extra user data (queue name) + """ + LOG.info('Binding %s to %s with %s', exchange, queue_name, + routing_key) + channel.queue_bind(queue=queue_name, + exchange=exchange, + routing_key=routing_key) + + def _stop(self): + """Cleanly shutdown the connection to RabbitMQ by stopping the consumer + + with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok + will be invoked by pika, which will then closing the channel and + connection. The IOLoop is started again because this method is invoked + when CTRL-C is pressed raising a KeyboardInterrupt exception. This + exception stops the IOLoop which needs to be running for pika to + communicate with RabbitMQ. All of the commands issued prior to starting + the IOLoop will be buffered but not processed. + """ + + LOG.info('Stopping') + self._close_channel(self.channel) + self._close_connection(self.connection) + LOG.info('Stopped') + + def _close_channel(self, channel): + """Call to close the channel with RabbitMQ cleanly by issuing the + + Channel.Close RPC command. + """ + LOG.info('Closing the channel') + if channel and channel.is_open: + channel.close() + + def _close_connection(self, connection): + """This method closes the connection to RabbitMQ.""" + LOG.info('Closing connection') + if connection and connection.is_open: + connection.close() + + def __enter__(self): + return self + + def __exit__(self, exception_type, exception_value, traceback): + if exception_type is not None: + LOG.error("%s, %s, %s", exception_type, exception_value, + traceback) diff --git a/bmp-dhcp-agent/bmpda/cmd/__init__.py b/bmp-dhcp-agent/bmpda/cmd/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/bmp-dhcp-agent/bmpda/cmd/server.py b/bmp-dhcp-agent/bmpda/cmd/server.py new file mode 100755 index 0000000..f88ee3d --- /dev/null +++ b/bmp-dhcp-agent/bmpda/cmd/server.py @@ -0,0 +1,35 @@ +import logging +import threading +import time + +from bmpda import agent +from bmpda import config +from bmpda import log + +LOG = logging.getLogger('bmpda') + +ascii_snake = """\ +============================================================================================= + + --..,_ _,.--. + `'.'. .'`__ o `;__. + '.'. .'.'` '---'` ` BMP Agent + '.`'--....--'`.' + `'--....--'` + +============================================================================================= +""" + + +def run(): + print(ascii_snake) + log.init() + LOG.debug("Env %s.", config.env) + eng = agent.Agent() + eng.start() + LOG.info("Agent is running.") + time.sleep(threading.TIMEOUT_MAX) + + +if __name__ == '__main__': + run() diff --git a/bmp-dhcp-agent/bmpda/command/__init__.py b/bmp-dhcp-agent/bmpda/command/__init__.py new file mode 100644 index 0000000..9923852 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/command/__init__.py @@ -0,0 +1,3 @@ +from bmpda.command.command_service import CommandService + +command_service = CommandService() diff --git a/bmp-dhcp-agent/bmpda/command/command_service.py b/bmp-dhcp-agent/bmpda/command/command_service.py new file mode 100755 index 0000000..6637b9d --- /dev/null +++ b/bmp-dhcp-agent/bmpda/command/command_service.py @@ -0,0 +1,69 @@ +import logging +from queue import Queue, Empty + +from bmpda import agent +from bmpda.command.common import COMMAND_MAP +from bmpda.command.common import SystemCommandError +from bmpda.errors import UnkownCommandError +from bmpda import serialize +from bmpda.service import node +from bmpda.utils import classloader +from bmpda.utils import strutils + + +LOG = logging.getLogger(__name__) + + +class CommandService: + + def __init__(self) -> None: + self._commands = Queue() + self.decoder = serialize.DefaultJsonDecoder() + + def dispatch(self): + LOG.info('Command dispatch start.') + while True: + command_str = None + action = None + request_id = None + try: + command_str = self._commands.get() + if not command_str: + LOG.warn("Get a None message: %.", command_str) + continue + command_str = command_str.decode('utf8') + LOG.info('Command: %s', strutils.mask_password(command_str)) + command = self.decoder.decode(command_str) + request_id = command.get('request_id', None) + if type(command) is dict and "action" in command.keys(): + action = command.get('action') + if action in COMMAND_MAP: + class_path = COMMAND_MAP.get(action) + command_clazz = classloader.load_class(class_path) + command_object = command_clazz(**command) + + command_object.run() + agent.Agent.send_command(command_object) + continue + + LOG.error("Unknow command action : %s.", + strutils.mask_password(command_str)) + raise UnkownCommandError( + details=strutils.mask_password(command_str)) + except Empty: + continue + except Exception as e: + LOG.error("Process command failed : %s.", + str(e), + exc_info=1) + cmd = SystemCommandError(sn=node.get_node_id(), + action=action or 'SystemCommandError', + code=getattr(e, 'code', 500), + type=e.__class__.__name__, + details=getattr(e, 'details', None), + message=getattr(e, 'message', str(e)), + request_id=request_id) + agent.Agent.send_command(cmd) + + def receive_command(self, command): + self._commands.put(command) diff --git a/bmp-dhcp-agent/bmpda/command/common.py b/bmp-dhcp-agent/bmpda/command/common.py new file mode 100755 index 0000000..42982ae --- /dev/null +++ b/bmp-dhcp-agent/bmpda/command/common.py @@ -0,0 +1,116 @@ +import logging + +import bmpda.errors as errors +from bmpda.serialize import Serializable +import bmpda.utils.validates as validates + + +LOG = logging.getLogger(__name__) + +OK = 200 + +OK_STRING = "OK" +ERROR_STRING = "ERROR" + +COMMAND_MAP = { + "Heart": "bmpda.command.common.Heart", + "PingHost": "bmpda.command.ping.PingHost", + "DHCPConfigAddHost": "bmpda.command.dhcp_config.DHCPConfigAddHost", + "DHCPConfigDelHost": "bmpda.command.dhcp_config.DHCPConfigDelHost", + "DHCPConfigAddSubnet": "bmpda.command.dhcp_config.DHCPConfigAddSubnet", + "DHCPConfigDelSubnet": "bmpda.command.dhcp_config.DHCPConfigDelSubnet", + "TFTPConfigAddGrub": "bmpda.command.grub_config.TFTPConfigAddGrub", +} + + +class Command(Serializable): + + serializable_fields = ('sn', 'action', 'code', 'type', 'message', + 'details', 'data', 'request_id', 'status') + + def __init__(self, + sn: str = None, + action: str = None, + code: int = OK, + message: str = None, + request_id: str = None, + status=OK_STRING, + **kwargs): + + self.sn = sn # required + self.action = action # required + self.code = code + self.message = message + self.type = kwargs.get('type', None) + self.details = kwargs.get('details', None) + self.request_id = request_id + self.data = kwargs.get('data', None) + self.status = status + + def validate_common_param(self): + validates.is_required(self.sn, 'Sn') + validates.is_required(self.action, 'Action') + + def validate(self): + pass + + def run(self): + try: + try: + self.validate_common_param() + self.validate() + self.execute_before() + self.execute() + self.__handle_success() + except Exception as e: + self.__handle_exception(e) + finally: + self.data = self.data or dict() + self.execute_after() + except Exception as e: + self.__handle_exception(e) + + def execute_before(self): + pass + + def execute(self): + raise errors.CommandExecutionError("{}not impl execute method.".format( + self.__class__.__name__)) + + def execute_after(self): + pass + + def __handle_success(self): + message = "Run {} success.".format(type(self).__name__) + self.status = OK_STRING + self.message = message + + LOG.info(message) + + def __handle_exception(self, exec): + self.status = ERROR_STRING + self.code = getattr(exec, 'code', 500) + self.type = exec.__class__.__name__ + self.message = getattr(exec, 'message', None) + self.details = getattr(exec, 'details', None) + LOG.error("Run {} failed:{}.".format( + type(self).__name__, str(exec)), + exc_info=1) + raise exec + + +class SystemCommandError(Command): + """agent to scheduler command""" + + def __init__(self, sn: str, action: str, **kwargs): + super(SystemCommandError, self).__init__(sn=sn, + action=action, + status=ERROR_STRING, + **kwargs) + + +class Heart(Command): + """agent to scheduler command""" + + def __init__(self, **kwargs): + super(Heart, self).__init__(action=self.__class__.__name__, **kwargs) diff --git a/bmp-dhcp-agent/bmpda/command/dhcp_config.py b/bmp-dhcp-agent/bmpda/command/dhcp_config.py new file mode 100644 index 0000000..2f6ba34 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/command/dhcp_config.py @@ -0,0 +1,95 @@ +import logging + +from bmpda.command.common import Command +from bmpda.service import dhcp_config +from bmpda.utils import validates + +LOG = logging.getLogger(__name__) + + +class DHCPConfigAddHost(Command): + """scheduler to agent command""" + + serializable_fields = Command.serializable_fields + ('ip', 'mac') + + def __init__(self, ip, mac, **kwargs): + super(DHCPConfigAddHost, self).__init__(**kwargs) + + self.ip = ip + self.mac = mac + validates.is_required(self.ip, "ip") + validates.is_required(self.mac, "mac") + + def execute_before(self): + pass + + def execute(self): + dhcp_config.add_host(ip=self.ip, mac=self.mac) + + def execute_after(self): + self.data['mac'] = self.mac + self.data['ip'] = self.ip + + +class DHCPConfigDelHost(Command): + """scheduler to agent command""" + + def __init__(self, mac, ip=None, **kwargs): + super(DHCPConfigDelHost, self).__init__(**kwargs) + self.mac = mac + validates.is_required(self.mac, "mac") + + def execute_before(self): + pass + + def execute(self): + dhcp_config.del_host(mac=self.mac) + + def execute_after(self): + self.data['mac'] = self.mac + + +class DHCPConfigAddSubnet(Command): + """scheduler to agent command""" + + def __init__(self, subnet, subnet_mask, routes, **kwargs): + super(DHCPConfigAddSubnet, self).__init__(**kwargs) + + self.subnet = subnet + self.subnet_mask = subnet_mask + self.routes = routes + + validates.is_required(self.subnet, "subnet") + validates.is_required(self.subnet_mask, "subnet_mask") + validates.is_required(self.routes, "routes") + + def execute_before(self): + pass + + def execute(self): + dhcp_config.add_subnet( + subnet=self.subnet, subnet_mask=self.subnet_mask, routes=self.routes) + + def execute_after(self): + self.data['subnet'] = self.subnet + self.data['subnet_mask'] = self.subnet_mask + self.data['routes'] = self.routes + + +class DHCPConfigDelSubnet(Command): + """scheduler to agent command""" + + def __init__(self, subnet, **kwargs): + super(DHCPConfigDelSubnet, self).__init__(**kwargs) + + self.subnet = subnet + validates.is_required(self.subnet, "subnet") + + def execute_before(self): + pass + + def execute(self): + dhcp_config.del_subnet(subnet=self.subnet) + + def execute_after(self): + self.data['subnet'] = self.subnet diff --git a/bmp-dhcp-agent/bmpda/command/grub_config.py b/bmp-dhcp-agent/bmpda/command/grub_config.py new file mode 100644 index 0000000..9ed9db0 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/command/grub_config.py @@ -0,0 +1,59 @@ +import logging + +from bmpda.command.common import Command +from bmpda.service import grub_config +from bmpda.utils import validates + +LOG = logging.getLogger(__name__) + + +class TFTPConfigAddGrub(Command): + """scheduler to agent command""" + + def __init__(self, mac, kernel_name, initramfs_name, boot_mode=None, arch=None, **kwargs): + super(TFTPConfigAddGrub, self).__init__(**kwargs) + + self.mac = mac + self.kernel_name = kernel_name + self.initramfs_name = initramfs_name + self.boot_mode = boot_mode + self.arch = arch + validates.is_required(self.mac, "mac") + validates.is_required(self.kernel_name, "kernel_name") + validates.is_required(self.initramfs_name, "initramfs_name") + if boot_mode is not None: + if boot_mode not in grub_config.boot_modes: + raise ValueError("boot_mode must be one of %s" % + grub_config.boot_modes) + + if arch is not None: + if arch not in grub_config.archs: + raise ValueError("arch must be one of %s" % grub_config.arch) + + def execute_before(self): + pass + + def execute(self): + grub_config.add_grub(mac=self.mac, kernel_name=self.kernel_name, + initramfs_name=self.initramfs_name, boot_mode=self.boot_mode, arch=self.arch) + + def execute_after(self): + self.data['mac'] = self.mac + + +class TFTPConfigDelGrub(Command): + """scheduler to agent command""" + + def __init__(self, mac, **kwargs): + super(TFTPConfigDelGrub, self).__init__(**kwargs) + self.mac = mac + validates.is_required(self.mac, "mac") + + def execute_before(self): + pass + + def execute(self): + grub_config.del_grub(mac=self.mac) + + def execute_after(self): + self.data['mac'] = self.mac diff --git a/bmp-dhcp-agent/bmpda/command/ping.py b/bmp-dhcp-agent/bmpda/command/ping.py new file mode 100755 index 0000000..50af908 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/command/ping.py @@ -0,0 +1,28 @@ +import logging + +from bmpda.command.common import Command +from bmpda.utils import executor +from bmpda.utils import validates + +LOG = logging.getLogger(__name__) + + +class Ping(Command): + """Detect mq communication. + + Avoid high concurrency and the issue of message loss + when establishing a connection for the first time. + + """ + + def __init__(self, ip, **kwargs): + super(Ping, self).__init__(**kwargs) + self.ip = ip + + validates.is_required(self.password, 'password') + + def execute(self): + ip = self.ip + cmd = ["ping", "-c", "3", self.ip] + executor.execute(*cmd) + LOG.info("ping %s successfully", ip) diff --git a/bmp-dhcp-agent/bmpda/config.py b/bmp-dhcp-agent/bmpda/config.py new file mode 100755 index 0000000..1143607 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/config.py @@ -0,0 +1,56 @@ +import os + +from bmpda import constants +from bmpda.utils import utils + +env: str = os.getenv('ENV') +if env: + cfg_path = os.path.join('cfg', env) + AGENT_PARAMS: dict = utils.get_agent_params( + utils.get_relative_path(cfg_path)) +else: + AGENT_PARAMS = os.environ +heart_period: int = int(AGENT_PARAMS.get('BMP_HEART_PERIOD', 10)) +mq_host: str = AGENT_PARAMS.get('BMP_MQ_HOST') # required +mq_port: int = int(AGENT_PARAMS.get('BMP_MQ_PORT', 5672)) +mq_username: str = AGENT_PARAMS.get('BMP_MQ_USER') # required +mq_password: str = AGENT_PARAMS.get('BMP_MQ_PASSWORD') # required +mq_password = mq_password.strip("'") +mq_vhost: str = AGENT_PARAMS.get('BMP_MQ_VHOST', '/bmp') +mq_exchange: str = AGENT_PARAMS.get('BMP_MQ_EXCHANGE', 'BMP_SCHEDULER') +mq_exchange_type: str = AGENT_PARAMS.get('BMP_MQ_EXCHANGE_TYPE', 'topic') +mq_exchange_type_publish: str = AGENT_PARAMS.get( + 'BMP_MQ_EXCHANGE_TYPE_PUBLISH', 'direct') +mq_exchange_routing_key: str = AGENT_PARAMS.get( + 'BMP_MQ_EXCHANGE_ROUTING_KEY', 'az') +mq_exchange_consumer: str = AGENT_PARAMS.get( + 'BMP_MQ_EXCHANGE_CONSUMER', 'BMP_SCHEDULER_TOPIC') +mq_queue_name_pefix_consumer: str = AGENT_PARAMS.get( + 'BMP_MQ_QUEUE_NAME_PEFIX_CONSUMER', 'dhcp-az') +omapi_host = AGENT_PARAMS.get('BMP_OMAPI_HOST', '127.0.0.1') +omapi_port = AGENT_PARAMS.get('BMP_OMAPI_PORT', 7911) +omapi_key = AGENT_PARAMS.get('BMP_OMAPI_KEY', '') +dhcp_config_dir = AGENT_PARAMS.get('BMP_DHCP_CONFIG_DIR', '/data') +dhcp_control_bin_path = utils.get_relative_path('shell/dhcpd_control.sh') +dhcp_control_bin = AGENT_PARAMS.get( + 'BMP_DHCP_CONTROL_BIN', dhcp_control_bin_path) +protocol: str = AGENT_PARAMS.get('BMP_PROTOCAL', constants.PROTOCAL_RABBITMQ) +log_path: str = AGENT_PARAMS.get('BMP_LOG_PATH', + '/var/log/bmp/bmp-dhcp-agent/bmp-dhcp-agent.log') +# DEBUG,INFO,WARNING +logging_level = AGENT_PARAMS.get('LOGGING_LEVEL', 'INFO') + +# tftp +tftp_config_dir = AGENT_PARAMS.get('BMP_TFTP_CONFIG_DIR', '/data') +tftp_mq_host: str = AGENT_PARAMS.get('BMP_TFTP_MQ_HOST') +tftp_mq_port: int = int(AGENT_PARAMS.get('BMP_TFTP_MQ_PORT', 5672)) +tftp_mq_user: str = AGENT_PARAMS.get('BMP_TFTP_MQ_USER') +tftp_mq_password: str = AGENT_PARAMS.get('BMP_TFTP_MQ_PASSWORD') +tftp_mq_password = tftp_mq_password.strip("'") +tftp_mq_vhost: str = AGENT_PARAMS.get('BMP_TFTP_MQ_VHOST', '/bmp') +tftp_mq_exchange_routing_key: str = AGENT_PARAMS.get( + 'BMP_TFTP_MQ_EXCHANGE_ROUTING_KEY', '') +tftp_image_host: str = AGENT_PARAMS.get('BMP_TFTP_IMAGE_HOST', '') +tftp_image_port: str = AGENT_PARAMS.get('BMP_TFTP_IMAGE_PORT', '') +tftp_rsyslog_host: str = AGENT_PARAMS.get('BMP_TFTP_RSYSLOG_HSOT', '') +tftp_rsyslog_port: str = AGENT_PARAMS.get('BMP_TFTP_RSYSLOG_PORT', '') diff --git a/bmp-dhcp-agent/bmpda/constants.py b/bmp-dhcp-agent/bmpda/constants.py new file mode 100644 index 0000000..e0dcf0f --- /dev/null +++ b/bmp-dhcp-agent/bmpda/constants.py @@ -0,0 +1,2 @@ +PROTOCAL_RABBITMQ = 'rabbitmq' +PROTOCAL_HTTP = 'http' diff --git a/bmp-dhcp-agent/bmpda/errors.py b/bmp-dhcp-agent/bmpda/errors.py new file mode 100644 index 0000000..11ecefb --- /dev/null +++ b/bmp-dhcp-agent/bmpda/errors.py @@ -0,0 +1,51 @@ +from bmpda import serialize + + +class RESTError(Exception, serialize.Serializable): + """Base class for errors.""" + message = 'Internal Server Error.' + details = 'An unexpected error occurred. Please try back later.' + status_code = 500 + serializable_fields = ('type', 'code', 'message', 'details') + + def __init__(self, details: str = None, *args, **kwargs): + super(RESTError, self).__init__(*args, **kwargs) + self.type = self.__class__.__name__ + self.code = self.status_code + if details: + self.details = details + + def __str__(self): + return "{}: {}".format(self.message, self.details) + + def __repr__(self): + return "{}('{}')".format(self.__class__.__name__, self.__str__()) + + +class UnkownCommandError(RESTError): + """Error which occurs if not has the command.""" + message = 'Not found' + status_code = 404 + details = 'The Command was not found.' + + def __init__(self, details: str = None): + if details: + self.details = details + super(UnkownCommandError, self).__init__(details) + + +class InvalidArgumentError(RESTError): + + message = 'Invalid Argument error.' + + def __init__(self, details): + super(InvalidArgumentError, self).__init__(details) + + +class BmpError(RESTError): + """Error bmp error.""" + + message = 'Bmp error.' + + def __init__(self, details): + super(BmpError, self).__init__(details) diff --git a/bmp-dhcp-agent/bmpda/log.py b/bmp-dhcp-agent/bmpda/log.py new file mode 100644 index 0000000..e879e28 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/log.py @@ -0,0 +1,48 @@ +import functools +import logging +from logging.handlers import TimedRotatingFileHandler +import os + +import bmpda.config as config +import bmpda.utils.file as file + +app_name = 'bmpda' + + +def _setupLogging(name='bmpda'): + log_path = config.log_path + log_dir = os.path.dirname(log_path) + file.ensure_dir(log_dir) + + logger = logging.getLogger(name) + logger.setLevel(logging.getLevelName(config.logging_level)) + formatter = logging.Formatter( + '%(asctime)s %(name)s/%(filename)s[line:%(lineno)d] %(levelname)s %(message)s') + + file_handler = TimedRotatingFileHandler( + log_path, when='D', interval=1, backupCount=90, encoding='utf-8') + file_handler.setFormatter(formatter) + + stream_handler = logging.StreamHandler() + stream_handler.setFormatter(formatter) + + logger.addHandler(file_handler) + logger.addHandler(stream_handler) + + +def init(name='bmpda'): + global app_name + app_name = name + _setupLogging(name) + + +def log_complete(func): + + @functools.wraps(func) + def wrapper(*args, **kwargs): + result = func(*args, **kwargs) + logger = logging.getLogger(app_name) + logger.info("%s complete.", func.__name__) + return result + + return wrapper diff --git a/bmp-dhcp-agent/bmpda/protocol/__init__.py b/bmp-dhcp-agent/bmpda/protocol/__init__.py new file mode 100755 index 0000000..0207237 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/protocol/__init__.py @@ -0,0 +1,23 @@ +from abc import ABC, abstractmethod + +from bmpda.command.common import Command + + +class BaseProtocol(ABC): + + @abstractmethod + def send_command(self, command: Command): + raise NotImplementedError() + + @abstractmethod + def receive_command(self, command: str): + raise NotImplementedError() + + +class Protocol(BaseProtocol): + + def start(): + pass + + def stop(self): + pass diff --git a/bmp-dhcp-agent/bmpda/protocol/rabbitmq.py b/bmp-dhcp-agent/bmpda/protocol/rabbitmq.py new file mode 100644 index 0000000..f552957 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/protocol/rabbitmq.py @@ -0,0 +1,63 @@ + +import logging +import threading + +from bmpda.client.rabbitmq import Consumer +from bmpda.client.rabbitmq import Publisher +from bmpda.command import command_service +from bmpda.command.common import Command +from bmpda.command.common import Heart +from bmpda.protocol import Protocol +from bmpda.serialize import DefaultJsonEncoder +from bmpda.service import node + +LOG = logging.getLogger(__name__) + + +class RabbitmqProtocol(Protocol): + + def __init__(self): + self.consumer = Consumer() + self.publisher = Publisher() + self.encoder = DefaultJsonEncoder() + + def start(self): + __consumer_thread = threading.Thread(name='ConsumerThread', + target=self._start_consumer, + daemon=True) + + __consumer_thread.start() + self._start_publisher() + + def stop(self): + self.consumer.stop() + + def send_command(self, command: Command): + message = self.encoder.encode(command.serialize()) + LOG.info("Send command: %s", message) + self.publisher.publish_message(message) + + def receive_command(self): + LOG.info('Receive command.') + message = self.consumer.get_message() + if message is not None: + command_service.receive_command(message) + + def _is_connect(self): + return self.publisher.is_connect() + + def heartbeat(self): + if self._is_connect(): + heart = Heart(sn=node.get_node_id()) + self.send_command(heart) + else: + LOG.warning("RabbitMQ is not connect, not send heartbeat.") + + def _start_consumer(self): + LOG.info("Comsumer qeue name %s.", node.get_node_id()) + self.consumer.init(node.get_node_id()) + self.consumer.start() + + def _start_publisher(self): + self.publisher.init(routing_key=node.get_node_id()) + self.publisher.start() diff --git a/bmp-dhcp-agent/bmpda/serialize.py b/bmp-dhcp-agent/bmpda/serialize.py new file mode 100755 index 0000000..185da74 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/serialize.py @@ -0,0 +1,70 @@ +import json +import uuid + + +class Serializable(object): + """Base class for things that can be serialized.""" + serializable_fields = () + + def serialize(self): + """Turn this object into a dict.""" + return dict((f, getattr(self, f)) for f in self.serializable_fields + if (hasattr(self, f) and getattr(self, f) is not None)) + + +class SerializableComparable(Serializable): + """A Serializable class which supports some comparison operators + + This class supports the '__eq__' and '__ne__' comparison operators, but + intentionally disables the '__hash__' operator as some child classes may be + mutable. The addition of these comparison operators is mainly used to + assist with unit testing. + """ + + __hash__ = None + + def __eq__(self, other): + return self.serialize() == other.serialize() + + def __ne__(self, other): + return self.serialize() != other.serialize() + + +class DefaultJsonEncoder(json.JSONEncoder): + """A slightly customized JSON encoder.""" + + def __init__(self, **kwargs): + super(DefaultJsonEncoder, self).__init__(**kwargs) + + def encode(self, o): + """Turn an object into JSON. + + Appends a newline to responses when configured to pretty-print, + in order to make use of curl less painful from most shells. + """ + delimiter = '' + + # if indent is None, newlines are still inserted, so we should too. + if self.indent is not None: + delimiter = '\n' + + return super(DefaultJsonEncoder, self).encode(o) + delimiter + + def default(self, o): + """Turn an object into a serializable object. + + In particular, by calling :meth:`.Serializable.serialize` on `o`. + """ + if isinstance(o, Serializable): + return o.serialize() + elif isinstance(o, uuid.UUID): + return str(o) + else: + return json.JSONEncoder.default(self, o) + + +class DefaultJsonDecoder(json.JSONDecoder): + """Customized JSON decoder.""" + + def __init__(self, **kwargs): + super(DefaultJsonDecoder, self).__init__(**kwargs) diff --git a/bmp-dhcp-agent/bmpda/service/__init__.py b/bmp-dhcp-agent/bmpda/service/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bmp-dhcp-agent/bmpda/service/dhcp_config.py b/bmp-dhcp-agent/bmpda/service/dhcp_config.py new file mode 100644 index 0000000..ba4bff8 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/service/dhcp_config.py @@ -0,0 +1,136 @@ +import logging + +from filelock import FileLock + +from bmpda import config +from bmpda.errors import InvalidArgumentError +from bmpda.service import node +import bmpda.utils.dhcp_editor +import bmpda.utils.executor +import bmpda.utils.omapi + +LOG = logging.getLogger(__name__) + + +def add_host(ip, mac): + lock = FileLock(node.get_dhcp_config_lock_path(), timeout=3) + omapi_key = config.omapi_key + host = config.omapi_host + port = config.omapi_port + omapi = bmpda.utils.omapi.OmapiClient(omapi_key=omapi_key, + host=host, + port=port) + with lock: + if omapi.exists_host(mac): + omapi.delete_host(mac) + message = "DHCP config add host, mac:%(mac)s or ip:%(ip)s is exist." % { + 'mac': mac, + 'ip': ip + } + LOG.warn(message) + try: + omapi.add_host(ip, mac) + LOG.info("DHCP add host success.") + except Exception as e: + LOG.error("DHCP add host error:%s." % str(e)) + + LOG.info("DHCP config add host ip:%(ip)s, mac:%(mac)s completely.", + { + 'ip': ip, + 'mac': mac + }) + + +def del_host(mac): + lock = FileLock(node.get_dhcp_config_lock_path(), timeout=3) + omapi_key = config.omapi_key + host = config.omapi_host + port = config.omapi_port + omapi = bmpda.utils.omapi.OmapiClient(omapi_key=omapi_key, + host=host, + port=port) + with lock: + try: + if omapi.exists_host(mac) is False: + message = "DHCP config del host, mac:%(mac)s is not exist." % { + 'mac': mac + } + LOG.error(message) + raise InvalidArgumentError(message) + omapi.delete_host(mac) + + if omapi.exists_host(mac): + message = "DHCP config del host, mac:%(mac)s error." % { + 'mac': mac + } + LOG.error(message) + raise InvalidArgumentError(message) + else: + LOG.info("DHCP add host success.") + except Exception as e: + message = "DHCP config del host, mac:%(mac)s error:%(err)s." % { + 'mac': mac, + 'err': str(e) + } + LOG.error(message) + + LOG.info("DHCP config del host mac:%(mac)s completely.", + {'mac': mac}) + + +def add_subnet(subnet, subnet_mask, routes): + dhcp_config_path = node.get_dhcp_config_path() + dhcpeditor = bmpda.utils.dhcp_editor.DHCPEditor(dhcp_config_path) + dhcp_config_lock_path = node.get_dhcp_config_lock_path() + lock = FileLock(dhcp_config_lock_path, timeout=10) + with lock: + if dhcpeditor.exists_subnet(subnet): + message = "Subnet:%(subnet)s is exist." % {'subnet': subnet} + LOG.error(message) + dhcpeditor.delete_subnet(subnet) + try: + dhcpeditor.add_subnet(subnet, subnet_mask, routes) + node.set_need_restart_dhcp(True) + LOG.info("DHCP config add subnet %s success.", subnet) + except Exception as e: + message = "DHCP config add subnet, subnet:%(subnet)s error:%(err)s." % { + 'subnet': subnet, + 'err': str(e) + } + LOG.error(message) + + LOG.info("DHCP config add subnet subnet:%(subnet)s completely.", + {'subnet': subnet}) + + +def del_subnet(subnet): + dhcp_config_path = node.get_dhcp_config_path() + dhcpeditor = bmpda.utils.dhcp_editor.DHCPEditor(dhcp_config_path) + dhcp_config_lock_path = node.get_dhcp_config_lock_path() + lock = FileLock(dhcp_config_lock_path, timeout=10) + with lock: + try: + if dhcpeditor.exists_subnet(subnet) is False: + message = "DHCP config delete subnet, subnet:%(subnet)s is not exist." % { + 'subnet': subnet + } + LOG.error(message) + raise InvalidArgumentError(message) + dhcpeditor.delete_subnet(subnet) + + if dhcpeditor.exists_subnet(subnet): + message = "DHCP config delete subnet, subnet:%(subnet)s error." % { + 'subnet': subnet + } + LOG.error(message) + raise InvalidArgumentError(message) + node.set_need_restart_dhcp(True) + except Exception as e: + message = "DHCP config delete subnet, subnet:%(subnet)s error:%(err)s." % { + 'subnet': subnet, + 'err': str(e) + } + LOG.error(message) + + LOG.info("DHCP config delete subnet subnet:%(subnet)s completely.", + {'subnet': subnet}) diff --git a/bmp-dhcp-agent/bmpda/service/grub_config.py b/bmp-dhcp-agent/bmpda/service/grub_config.py new file mode 100644 index 0000000..6a58326 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/service/grub_config.py @@ -0,0 +1,149 @@ +import logging +import os + +from filelock import FileLock + +from bmpda import config +from bmpda.errors import BmpError +from bmpda.utils import file +from bmpda.utils import paths +from bmpda.utils import system + + +LOG = logging.getLogger(__name__) + +boot_modes = {"uefi", "bios"} +archs = {"x86_64", "aarch64", "loongarch64"} + +grub_config_maps = { + "bios": { + "x86_64": { + "config_dir": "pxelinux.cfg", + "image_dir": "" + } + }, + "uefi": { + "x86_64": { + "config_dir": "uefi/x86_64", + "image_dir": "" + }, + "aarch64": { + "config_dir": "uefi/arm64", + "image_dir": "images/arm64" + }, + "loongarch64": { + "config_dir": "uefi/loongarch64", + "image_dir": "images/loongarch64" + } + } +} + + +def get_lock_file(mac): + lock_dir = os.path.join(config.tftp_config_dir, 'lock') + if not os.path.exists(lock_dir): + file.ensure_dir(lock_dir) + + return os.path.join(lock_dir, f"{mac}.lock") + + +def add_grub(mac, boot_mode, arch, kernel_name, initramfs_name): + lock_file = get_lock_file(mac) + lock = FileLock(lock_file, timeout=3) + with lock: + try: + boot_mode_set = {boot_mode} if boot_mode is not None else boot_modes + for item_boot_mode in boot_mode_set: + arch_set = {arch} if arch is not None else grub_config_maps.get( + item_boot_mode).keys() + LOG.info(f"Arch set:{arch_set}") + for item_arch in arch_set: + write_grub_config(mac=mac, boot_mode=item_boot_mode, arch=item_arch, + kernel_name=kernel_name, initramfs_name=initramfs_name) + except Exception as e: + LOG.error("TFTP add grub config mac:%s error:%s.", mac, e) + raise BmpError("TFTP add grub config mac:{mac} error: {e}.") + os.remove(lock_file) + LOG.info(f"TFTP config add mac:{mac} completely.") + + +def del_grub(mac): + lock_file = get_lock_file(mac) + lock = FileLock(lock_file, timeout=3) + with lock: + try: + boot_mode_set = boot_modes + for item_boot_mode in boot_mode_set: + arch_set = grub_config_maps.get(item_boot_mode).keys() + for item_arch in arch_set: + file_path = get_absolute_grub_config_path( + mac=mac, boot_mode=item_boot_mode, arch=item_arch) + if os.path.exists(file_path): + os.remove(file_path) + LOG.info(f"{file_path} was remove.") + + except Exception as e: + LOG.error("TFTP delete grub config mac:%s error:%s.", mac, e) + raise BmpError("TFTP delete grub config mac:{mac} error: {e}.") + os.remove(lock_file) + LOG.info(f"TFTP config delete grub mac:{mac} completely.") + + +def write_grub_config(mac, boot_mode, arch, kernel_name, initramfs_name): + LOG.info(f"Add file {mac} {boot_mode} {arch} " + f"{kernel_name} {initramfs_name}.") + config_data = get_grub_config_data( + boot_mode=boot_mode, arch=arch, kernel_name=kernel_name, initramfs_name=initramfs_name) + absolute_config_path = get_absolute_grub_config_path(mac, boot_mode, arch) + with open(absolute_config_path, "w") as json_file: + json_file.write(config_data) + LOG.info(f"Add file {absolute_config_path} .") + + +def get_absolute_grub_config_path(mac, boot_mode, arch): + def get_grub_file_name(boot_mode, mac): + mac_formatted = mac.replace(":", "-") + if boot_mode == "bios": + return f"01-{mac_formatted}" + return f"grub.cfg-01-{mac_formatted}" + + grub_confg_map = get_grub_config(boot_mode, arch) + config_dir = grub_confg_map.get("config_dir") + grub_file_name = get_grub_file_name(boot_mode, mac) + grub_file_path = os.path.join(config_dir.lstrip("/"), grub_file_name) + absolute_config_path = paths.target_path( + config.tftp_config_dir, grub_file_path) + return absolute_config_path + + +def get_grub_config_data(boot_mode, arch, kernel_name, initramfs_name): + if boot_mode == "bios": + tpl_path = 'template/tftp/default.tpl' + else: + tpl_path = 'template/tftp/grub.cfg.tpl' + grub_conf_template_file_path = system.get_relative_path(tpl_path) + grub_confg_map = get_grub_config(boot_mode, arch) + image_dir = grub_confg_map.get('image_dir') + kernel_path = os.path.join(image_dir, kernel_name) + initramfs_path = os.path.join(image_dir, initramfs_name) + grub_config = system.render_template( + grub_conf_template_file_path, { + 'kernel_path': kernel_path, + 'initramfs_path': initramfs_path, + 'bmp_mq_host': config.tftp_mq_host, + 'bmp_mq_port': config.tftp_mq_port, + 'bmp_mq_user': config.tftp_mq_user, + 'bmp_mq_password': config.tftp_mq_password, + 'bmp_mq_vhost': config.tftp_mq_vhost, + 'bmp_mq_exchange_routing_key': config.tftp_mq_exchange_routing_key, + 'bmp_image_host': config.tftp_image_host, + 'bmp_image_port': config.tftp_image_port, + 'bmp_rsyslog_host': config.tftp_rsyslog_host, + 'bmp_rsyslog_port': config.tftp_rsyslog_port, + }) + return grub_config + + +def get_grub_config(boot_mode, arch): + LOG.info(f"Boot mode:{boot_mode} arch:{arch}") + return grub_config_maps.get(boot_mode).get(arch) diff --git a/bmp-dhcp-agent/bmpda/service/node.py b/bmp-dhcp-agent/bmpda/service/node.py new file mode 100644 index 0000000..79502c7 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/service/node.py @@ -0,0 +1,37 @@ +import logging + +LOG = logging.getLogger(__name__) + +NODE = dict() + + +def set_node_id(serial_number: str): + NODE['serial_number'] = serial_number + + +def get_node_id() -> str: + return NODE.get('serial_number', None) + + +def set_need_restart_dhcp(need_restart_dhcp: bool): + NODE['need_restart_dhcp'] = need_restart_dhcp + + +def get_need_restart_dhcp() -> bool: + return NODE.get('need_restart_dhcp', None) + + +def set_dhcp_config_path(dhcp_config_path: str): + NODE['dhcp_config_path'] = dhcp_config_path + + +def get_dhcp_config_path() -> str: + return NODE.get('dhcp_config_path', None) + + +def set_dhcp_config_lock_path(dhcp_config_lock_path: str): + NODE['dhcp_config_lock_path'] = dhcp_config_lock_path + + +def get_dhcp_config_lock_path() -> str: + return NODE.get('dhcp_config_lock_path', None) diff --git a/bmp-dhcp-agent/bmpda/shell/dhcpd_control.sh b/bmp-dhcp-agent/bmpda/shell/dhcpd_control.sh new file mode 100644 index 0000000..e083bf1 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/shell/dhcpd_control.sh @@ -0,0 +1,71 @@ +#!/bin/sh +set -ue + +[ -z "$BMP_DHCP_CONFIG_DIR" ] && echo "error! BMP_DHCP_CONFIG_DIR is unset!" && exit 1 + +if [ ! -e $BMP_DHCP_CONFIG_DIR/dhcpd.conf ] && [ -e /dhcpd.conf.tpl ]; then + eval "echo \"$(cat /dhcpd.conf.tpl)\"" > $BMP_DHCP_CONFIG_DIR/dhcpd.conf +fi + +LOG_FILE=/var/log/bmp/bmpda/dhcpd.log +exec_file=/usr/sbin/dhcpd +data_dir=$BMP_DHCP_CONFIG_DIR +dhcpd_conf="$data_dir/dhcpd.conf" +PID="" +if [ ! -r "$dhcpd_conf" ]; then + echo "Please ensure '$dhcpd_conf' exists and is readable." + echo "Run the container with arguments 'man dhcpd.conf' if you need help with creating the configuration." + exit 1 +fi + +[ -e "$data_dir/dhcpd.leases" ] || touch "$data_dir/dhcpd.leases" + + +help(){ + echo "${0} " + exit 1 +} + +get_pid() +{ + local pid="" + pid=$(ps -ef | grep "$exec_file" | grep -v 'grep' | awk '{print $1}') + PID=$pid +} + +checkhealth(){ + get_pid + [ X"$PID" != X"" ] && echo "dhcpd is running" && return 0 + echo "dhcpd is not running" && return 1 +} + +start(){ + /usr/sbin/dhcpd -f -d --no-pid -cf "$data_dir/dhcpd.conf" -lf "$data_dir/dhcpd.leases" >> $LOG_FILE 2>&1 & +} + +stop(){ + checkhealth || return 0 + [ X"$PID" != X"" ] && kill $PID + sleep 2 + checkhealth || return 0 + return 1 +} + +case "${1}" in + start) + stop && start + ;; + stop) + stop + ;; + status|health|checkhealth) + checkhealth + ;; + restart) + stop && start + ;; + *) + help + ;; +esac + diff --git a/bmp-dhcp-agent/bmpda/template/tftp/default.tpl b/bmp-dhcp-agent/bmpda/template/tftp/default.tpl new file mode 100644 index 0000000..5b9ba0f --- /dev/null +++ b/bmp-dhcp-agent/bmpda/template/tftp/default.tpl @@ -0,0 +1,6 @@ +default bmp agent + prompt 0 + timeout 1 + label bmp agent + kernel {{kernel_path}} + append initrd={{initramfs_path}} net.ifnames=0 biosdevname=0 BMP_MQ_HOST={{bmp_mq_host}} BMP_MQ_PORT={{bmp_mq_port}} BMP_MQ_USER={{bmp_mq_user}} BMP_MQ_PASSWORD='{{bmp_mq_password}}' BMP_MQ_VHOST={{bmp_mq_vhost}} BMP_MQ_EXCHANGE_ROUTING_KEY={{bmp_mq_exchange_routing_key}} BMP_IMAGE_HOST={{bmp_image_host}} BMP_IMAGE_PORT={{bmp_image_port}} BMP_RSYSLOG_HSOT={{bmp_rsyslog_host}} BMP_RSYSLOG_PORT={{bmp_rsyslog_port}} \ No newline at end of file diff --git a/bmp-dhcp-agent/bmpda/template/tftp/grub.cfg.tpl b/bmp-dhcp-agent/bmpda/template/tftp/grub.cfg.tpl new file mode 100644 index 0000000..1ec362a --- /dev/null +++ b/bmp-dhcp-agent/bmpda/template/tftp/grub.cfg.tpl @@ -0,0 +1,6 @@ +set timeout=1 +set default=1 +menuentry 'bmp agent {{arch}} uefi' { + linuxefi {{kernel_path}} {{console}} net.ifnames=0 biosdevname=0 ksdevice=bootif kssendmac text BMP_MQ_HOST={{bmp_mq_host}} BMP_MQ_PORT={{bmp_mq_port}} BMP_MQ_USER={{bmp_mq_user}} BMP_MQ_PASSWORD='{{bmp_mq_password}}' BMP_MQ_VHOST={{bmp_mq_vhost}} BMP_MQ_EXCHANGE_ROUTING_KEY={{bmp_mq_exchange_routing_key}} BMP_IMAGE_HOST={{bmp_image_host}} BMP_IMAGE_PORT={{bmp_image_port}} BMP_RSYSLOG_HSOT={{bmp_rsyslog_host}} BMP_RSYSLOG_PORT={{bmp_rsyslog_port}} + initrdefi {{initramfs_path}} +} \ No newline at end of file diff --git a/bmp-dhcp-agent/bmpda/tests/__init__.py b/bmp-dhcp-agent/bmpda/tests/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/bmp-dhcp-agent/bmpda/tests/unit/__init__.py b/bmp-dhcp-agent/bmpda/tests/unit/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/bmp-dhcp-agent/bmpda/tests/unit/test_config.py b/bmp-dhcp-agent/bmpda/tests/unit/test_config.py new file mode 100644 index 0000000..0f82c87 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/tests/unit/test_config.py @@ -0,0 +1,6 @@ +import unittest + + +class TestEmptyTestCase(unittest.TestCase): + def test_empty_test_case(self): + pass diff --git a/bmp-dhcp-agent/bmpda/utils/__init__.py b/bmp-dhcp-agent/bmpda/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bmp-dhcp-agent/bmpda/utils/classloader.py b/bmp-dhcp-agent/bmpda/utils/classloader.py new file mode 100755 index 0000000..1bef6be --- /dev/null +++ b/bmp-dhcp-agent/bmpda/utils/classloader.py @@ -0,0 +1,4 @@ +def load_class(class_path): + parts = class_path.rsplit('.', 1) + module = __import__(parts[0], fromlist=parts[1]) + return getattr(module, parts[1]) diff --git a/bmp-dhcp-agent/bmpda/utils/dhcp.py b/bmp-dhcp-agent/bmpda/utils/dhcp.py new file mode 100644 index 0000000..9f6c45d --- /dev/null +++ b/bmp-dhcp-agent/bmpda/utils/dhcp.py @@ -0,0 +1,34 @@ + +import logging + +from bmpda import config +from bmpda.utils import executor + +LOG = logging.getLogger(__name__) + + +def dhcp_ctl(option='start'): + """Control dhcp status + + option: start stop restart status + """ + dhcp_control_bin = config.dhcp_control_bin + cmd = (dhcp_control_bin, option) + try: + stdout, stderr = executor.execute(*cmd, + attempts_times=3) + LOG.info("DHCP %s .", option) + if stderr is not None: + message = "DHCP %(option)s error:%(err)s, exit code:(exit_code)s." % { + 'option': option, + 'err': stdout} + LOG.error(message) + return False + except Exception as e: + message = "DHCP %(option)s error:%(err)s." % { + 'option': option, + 'err': str(e) + } + LOG.error(message) + return False + return True diff --git a/bmp-dhcp-agent/bmpda/utils/dhcp_editor.py b/bmp-dhcp-agent/bmpda/utils/dhcp_editor.py new file mode 100644 index 0000000..beda7f0 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/utils/dhcp_editor.py @@ -0,0 +1,124 @@ +import re + + +class DHCPEditor(object): + config_file = '' + + def __init__(self, config_file_path): + self.config_file = config_file_path + + def add_host(self, hostname, ip, mac): + with open(self.config_file, 'a') as dhcp_list: + host_body = ' {\n\thardware ethernet ' + mac + \ + ';\n\tfixed-address ' + ip + '; \n' + dhcp_list.write('host ' + hostname + host_body) + + def delete_host(self, mac): + """Can delete entries either by mac. + + IT CANNOT DELETE ANYTHING BY HOSTNAME. + """ + mac_format = re.compile(r'(.*)hardware(\s+)ethernet(\s+)%s;' % mac) + intext = [] + with open(self.config_file, 'r') as dhcp_list: + intext = dhcp_list.readlines() + wait_delete_line_num = [] + for i in range(len(intext)): + if mac_format.match(intext[i]) is not None: + for j in range(i, len(intext)): + if intext[j].find('}') != -1: + wait_delete_line_num.append(j) + break + + wait_delete_line_num.append(j) + + for k in range(i, -1, -1): + if intext[k].find('{') != -1: + wait_delete_line_num.append(k) + break + + wait_delete_line_num.append(k) + + with open(self.config_file, 'w') as dhcp_file: + for i in range(len(intext)): + if i not in wait_delete_line_num: + dhcp_file.write(intext[i]) + + def exists_host(self, mac): # search by mac + with open(self.config_file, 'r') as dhcp_list: + mac_format = re.compile(r'(.*)hardware(\s+)ethernet(\s+)%s;' % mac) + intext = dhcp_list.readlines() + for i in range(len(intext)): + if mac_format.match(intext[i]) is not None: + return True + return False + + def exists_hostname(self, hostname): # search by hostname + with open(self.config_file, 'r') as dhcp_list: + intext = dhcp_list.readlines() + for i in range(len(intext)): + if hostname in intext[i]: + return True + return False + + def exists_subnet(self, subnet): + with open(self.config_file, 'r') as dhcp_list: + pattern = re.compile(r'^[\s]*subnet(\s+)%s(\s+)netmask' % subnet) + intext = dhcp_list.readlines() + for i in range(len(intext)): + if pattern.match(intext[i]) is not None: + return True + return False + + def add_subnet(self, subnet, subnet_mask, routes): + with open(self.config_file, 'a') as dhcp_list: + subnet_body = ' {\n\toption subnet-mask ' + subnet_mask + \ + ';\n\toption routers ' + routes + '; \n}\n' + dhcp_list.write( + 'subnet %(subnet)s netmask %(subnet_mask)s %(subnet_body)s' % { + 'subnet': subnet, + 'subnet_mask': subnet_mask, + 'subnet_body': subnet_body + }) + + def delete_subnet(self, subnet): + """Can delete entries either by subnet. + + subnet x.x.x.x netmask y.y.y.y { + } + """ + pattern = re.compile(r'^[\s]*subnet(\s+)%s(\s+)netmask' % subnet) + self.delete_obj_by_pattern(pattern) + + def delete_obj_by_pattern(self, pattern): + """Delete obj by pattern + + obj: + xxx { + + } + """ + intext = [] + with open(self.config_file, 'r') as dhcp_list: + intext = dhcp_list.readlines() + wait_delete_line_num = [] + for i in range(len(intext)): + if pattern.match(intext[i]) is not None: + for j in range(i, len(intext)): + if intext[j].find('}') != -1: + wait_delete_line_num.append(j) + break + + wait_delete_line_num.append(j) + + for k in range(i, -1, -1): + if intext[k].find('{') != -1: + wait_delete_line_num.append(k) + break + + wait_delete_line_num.append(k) + + with open(self.config_file, 'w') as dhcp_file: + for i in range(len(intext)): + if i not in wait_delete_line_num: + dhcp_file.write(intext[i]) diff --git a/bmp-dhcp-agent/bmpda/utils/encode.py b/bmp-dhcp-agent/bmpda/utils/encode.py new file mode 100755 index 0000000..c196a2e --- /dev/null +++ b/bmp-dhcp-agent/bmpda/utils/encode.py @@ -0,0 +1,12 @@ +def to_utf8(text): + """Encode Unicode to UTF-8, return bytes unchanged. + + Raise TypeError if text is not a bytes string or a Unicode string. + """ + if isinstance(text, bytes): + return text + elif isinstance(text, str): + return text.encode('utf-8') + else: + raise TypeError('bytes or Unicode expected, got %s' % + type(text).__name__) diff --git a/bmp-dhcp-agent/bmpda/utils/executor.py b/bmp-dhcp-agent/bmpda/utils/executor.py new file mode 100755 index 0000000..0c78aed --- /dev/null +++ b/bmp-dhcp-agent/bmpda/utils/executor.py @@ -0,0 +1,250 @@ +import logging +import os +import subprocess +import time + +from bmpda.utils import encode + +LOG = logging.getLogger(__name__) + + +class UnknownArgumentError(Exception): + + def __init__(self, message=None): + super(UnknownArgumentError, self).__init__(message) + + +class ProcessExecutionError(Exception): + + def __init__(self, + stdout=None, + stderr=None, + exit_code=None, + cmd=None, + description=None): + super(ProcessExecutionError, self).__init__(stdout, stderr, exit_code, + cmd, description) + self.stdout = stdout + self.stderr = stderr + self.exit_code = exit_code + self.cmd = cmd + self.description = description + + def __str__(self): + description = self.description + if description is None: + description = "Unexpected error while running command." + + exit_code = self.exit_code + if exit_code is None: + exit_code = '-' + + message_param = { + 'description': description, + 'cmd': self.cmd, + 'exit_code': exit_code, + 'stdout': self.stdout + } + message = ('%(description)s\n' + 'Command: %(cmd)s\n' + 'Exit code: %(exit_code)s\n' + 'Stdout: %(stdout)r') % message_param + return message + + +class NoRootPermissionError(ProcessExecutionError): + + def __init__(self, **kwargs): + super(NoRootPermissionError, self).__init__(**kwargs) + + +def try_execute(*cmd, **kwargs): + """The same as execute but returns None on error. + + Instead of raising an exception on failure, this method simply + returns None in case of failure. + + :param *cmd: positional arguments to pass to execute() + :param **kwargs: keyword arguments to pass to processutils.execute() + :raises: UnknownArgumentException on receiving unknown arguments + :returns: tuple of (stdout, stderr) or None in some error cases + """ + try: + return execute(*cmd, **kwargs) + except (ProcessExecutionError, OSError) as e: + LOG.info('Command failed: %s', e) + + +def execute(*cmd, **kwargs): + """Helper method to shell out and execute a command through subprocess. + + Allows optional. + + :param cmd: Passed to subprocess.Popen. + :type cmd: string + + :param cwd: Set the current working directory + :type cwd: string + + :param target: Chroot dir + :type target: string + + :type std_input: string or bytes + + :param env_variables: Environment variables and their values that + will be set for the process. + :type env_variables: dict + + :param check_exit_code: Single bool, int, or list of allowed exit + codes. Defaults to [0]. Raise + :class:`ProcessExecutionException` unless + program exits with one of these code. + :type check_exit_code: boolean, int, or [int] + + + :param delay_on_retry: True | False. Defaults to True. If set to True, + wait a short amount of time before retrying. + :type delay_on_retry: boolean + + :param attempts_times: How many times to retry cmd. + :type attempts_times: int + + :param run_as_root: True | False. Defaults to False. If set to True, + the command is prefixed by the command specified + in the root_helper kwarg. + :type run_as_root: boolean + + :param shell: whether or not there should be a shell used to + execute this command. Defaults to True. + :type shell: boolean + + :param binary: On Python 3, return stdout and stderr as bytes if + binary is True, as Unicode otherwise. + :type binary: boolean + + :param use_standard_locale: keyword-only argument. True | False. + Defaults to True. If set to True, + execute command with standard locale + added to environment variables. + :type boolean + + :returns: (status, stdout, stderr) from process execution + """ + + target = kwargs.pop('target', '/') + chroot_args = [] if target == '/' else ['chroot', target] + cmd = [str(c) for c in cmd] + cmd = chroot_args + cmd + cmd_text = ' '.join(cmd) + use_standard_locale = kwargs.pop('use_standard_locale', True) + if use_standard_locale: + environ = os.environ.copy() + environ['PATH'] = '%s:/bin' % environ['PATH'] + env = kwargs.pop('env_variables', environ) + env['LC_ALL'] = 'C' + kwargs['env_variables'] = env + + cwd = kwargs.pop('cwd', None) + + std_input = kwargs.pop('std_input', None) + if std_input is not None: + std_input = encode.to_utf8(std_input) + + env_variables = kwargs.pop('env_variables', None) + + ignore_exit_code = False + check_exit_code = kwargs.pop('check_exit_code', [0]) + if isinstance(check_exit_code, bool): + ignore_exit_code = not check_exit_code + check_exit_code = [0] + elif isinstance(check_exit_code, int): + check_exit_code = [check_exit_code] + + delay_on_retry = kwargs.pop('delay_on_retry', True) + + attempts_times = kwargs.pop('attempts_times', 1) + + run_as_root = kwargs.pop('run_as_root', False) + if run_as_root and hasattr(os, 'geteuid') and os.geteuid() != 0: + raise NoRootPermissionError( + cmd=cmd_text, + description='Command requested root, but did not ' + 'specify a root helper.') + + shell = kwargs.pop('shell', False) + + binary = kwargs.pop('binary', False) + + if kwargs: + raise UnknownArgumentError('Got unknown keyword args: %r' % kwargs) + + temp_attempts_times = attempts_times + while temp_attempts_times > 0: + temp_attempts_times -= 1 + + LOG.info("ready to run %s", cmd_text) + try: + _PIPE = subprocess.PIPE + obj = subprocess.Popen(cmd, + stdin=_PIPE, + stdout=_PIPE, + stderr=subprocess.STDOUT, + close_fds=True, + preexec_fn=None, + shell=shell, + cwd=cwd, + env=env_variables) + result = obj.communicate(std_input) + obj.stdin.close() + _returncode = obj.returncode + if not ignore_exit_code and _returncode not in check_exit_code: + (stdout, stderr) = result + stdout = os.fsdecode(stdout) if stdout is not None else None + stderr = os.fsdecode(stderr) if stderr is not None else None + raise ProcessExecutionError(exit_code=_returncode, + stdout=stdout, + stderr=stderr, + cmd=cmd) + if not binary and result is not None: + (stdout, stderr) = result + # Decode from the locale using using the surrogateescape error + # handler (decoding cannot fail) + stdout = os.fsdecode(stdout) if stdout is not None else None + stderr = os.fsdecode(stderr) if stderr is not None else None + return (stdout, stderr) + else: + return result + except (ProcessExecutionError, OSError) as e: + if isinstance(e, ProcessExecutionError): + LOG.error( + "%(desc)r\ncommand: %(cmd)r\nexit code: %(code)r\n' \ + stdout: %(stdout)r\n" % { + "desc": e.description, + "cmd": e.cmd, + "code": e.exit_code, + "stdout": e.stdout + }) + else: + LOG.error( + 'Got an OSError, command: %(cmd)r, errno: %(errno)r' % { + "cmd": cmd_text, + "errno": e.strerror + }) + if delay_on_retry and temp_attempts_times > 0: + attempts_period = 0.5 * 2**(attempts_times - + temp_attempts_times) + LOG.info("retry to run `%s` after %.2f seconds" % + (cmd, attempts_period)) + time.sleep(attempts_period) + continue + raise + + finally: + # this appears to be necessary to let the subprocess + # call clean something up in between calls, without + # it two execute calls in a row hangs the second one + # Above is probably specific to the eventlet subprocess + # module eventlet subprocess module, but since we still + # have to support that we're leaving the sleep. It won't + # hurt anything in the stdlib case anyway. + time.sleep(0) diff --git a/bmp-dhcp-agent/bmpda/utils/file.py b/bmp-dhcp-agent/bmpda/utils/file.py new file mode 100644 index 0000000..35cced8 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/utils/file.py @@ -0,0 +1,20 @@ +import hashlib +import os + + +def ensure_dir(path, mode=None): + if path == "": + path = "." + if not os.path.exists(path): + os.makedirs(path) + + if mode is not None: + os.chmod(path, mode) + + +def md5sum(path): + hashlib_md5 = hashlib.md5() + with open(path, 'rb') as f: + for chunk in iter(lambda: f.read(4096), b""): + hashlib_md5.update(chunk) + return hashlib_md5.hexdigest() diff --git a/bmp-dhcp-agent/bmpda/utils/net.py b/bmp-dhcp-agent/bmpda/utils/net.py new file mode 100644 index 0000000..24850ca --- /dev/null +++ b/bmp-dhcp-agent/bmpda/utils/net.py @@ -0,0 +1,16 @@ +import socket + + +def get_host_ip(): + """Get the local machine's IP address. + + :return: ip + """ + try: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.connect(('8.8.8.8', 80)) + ip = s.getsockname()[0] + finally: + s.close() + + return ip diff --git a/bmp-dhcp-agent/bmpda/utils/omapi.py b/bmp-dhcp-agent/bmpda/utils/omapi.py new file mode 100644 index 0000000..be471a8 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/utils/omapi.py @@ -0,0 +1,28 @@ +from pypureomapi import (Omapi) + + +class OmapiClient(object): + def __init__(self, omapi_key, host='127.0.0.1', port=7911): + self._omapi = Omapi( + host, + int(port), + b"omapi_key", + omapi_key.encode("ascii"), + ) + + def add_host(self, ip, mac): + name = self._name_from_mac(mac) + self._omapi.add_host_supersede(ip, mac, name) + + def delete_host(self, mac): + self._omapi.del_host(mac) + + def exists_host(self, mac): + try: + self._omapi.lookup_host_host(mac) + return True + except Exception: + return False + + def _name_from_mac(self, mac): + return mac.replace(":", "-").encode("ascii") diff --git a/bmp-dhcp-agent/bmpda/utils/paths.py b/bmp-dhcp-agent/bmpda/utils/paths.py new file mode 100644 index 0000000..b9d3252 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/utils/paths.py @@ -0,0 +1,15 @@ +import os + + +def target_path(target, path=None): + if target in (None, ""): + target = "/" + + target = os.path.abspath(target) + + if not path: + return target + + path = path.lstrip("/") + + return os.path.join(target, path) diff --git a/bmp-dhcp-agent/bmpda/utils/strutils.py b/bmp-dhcp-agent/bmpda/utils/strutils.py new file mode 100755 index 0000000..3dd18b2 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/utils/strutils.py @@ -0,0 +1,2 @@ +def mask_password(message, secret="***"): + return message diff --git a/bmp-dhcp-agent/bmpda/utils/system.py b/bmp-dhcp-agent/bmpda/utils/system.py new file mode 100755 index 0000000..13aa64c --- /dev/null +++ b/bmp-dhcp-agent/bmpda/utils/system.py @@ -0,0 +1,42 @@ +import logging +import os + +from jinja2 import DictLoader +from jinja2 import Environment +from jinja2 import FileSystemLoader + + +LOG = logging.getLogger(__name__) + + +def get_relative_path(script): + """Get the relative path of a script which ships with bmpa. + + :param script: The script name as a string. + :returns: The relative path of the script. + """ + cwd = os.path.dirname(os.path.realpath(__file__)) + return os.path.join(cwd, '..', script) + + +def render_template(template, params=None, is_file=True): + """Renders Jinja2 template file with given parameters. + + :param template: full path to the Jinja2 template file + :param params: dictionary with parameters to use when rende ring + :param is_file: whether template is file or string with template itself + :returns: the rendered template as a string + """ + if is_file: + tmpl_path, tmpl_name = os.path.split(template) + loader = FileSystemLoader(tmpl_path) + else: + tmpl_name = 'template' + loader = DictLoader({tmpl_name: template}) + env = Environment(loader=loader) + tmpl = env.get_template(tmpl_name) + + if params is not None: + return tmpl.render(params, enumerate=enumerate) + else: + return tmpl.render() diff --git a/bmp-dhcp-agent/bmpda/utils/utils.py b/bmp-dhcp-agent/bmpda/utils/utils.py new file mode 100755 index 0000000..632f01d --- /dev/null +++ b/bmp-dhcp-agent/bmpda/utils/utils.py @@ -0,0 +1,37 @@ +import os + + +def _read_params_from_file(filepath: str): + """Extract key=value pairs from a file. + + :param filepath: path to a file containing key=value pairs separated by + whitespace or newlines. + :returns: a dictionary representing the content of the file + """ + with open(filepath) as f: + cmdline = f.read() + + options = cmdline.split() + params = {} + for option in options: + if '=' not in option: + continue + k, v = option.split('=', 1) + params[k] = v + + return params + + +def get_agent_params(cmdline_path: str = '/proc/cmdline'): + """Gets parameters passed to the agent via kernel cmdline.""" + return _read_params_from_file(cmdline_path) + + +def get_relative_path(script): + """Get the relative path of a script which ships with bmpda + + :param script: The script name as a string. + :returns: The relative path of the script. + """ + cwd = os.path.dirname(os.path.realpath(__file__)) + return os.path.join(cwd, '..', script) diff --git a/bmp-dhcp-agent/bmpda/utils/validates.py b/bmp-dhcp-agent/bmpda/utils/validates.py new file mode 100644 index 0000000..17e7942 --- /dev/null +++ b/bmp-dhcp-agent/bmpda/utils/validates.py @@ -0,0 +1,35 @@ +from typing import Dict + + +def is_required(arg: object, param_name): + not_null(arg, param_name) + not_empty(arg, param_name) + + +def check_field(dict_obj: Dict, field: str): + not_field(dict_obj, field) + not_null(dict_obj[field], field) + not_empty(dict_obj[field], field) + + +def not_field(dict_obj: Dict, field: str): + if field not in dict_obj: + raise ValueError('Missing field: [{0}]'.format(field)) + + +def not_null(arg: object, param_name: str): + if arg is None: + raise ValueError("Parameter `{param_name}` cannot not be None".format( + param_name=param_name)) + + +def not_empty(arg: object, param_name: str): + if arg == '': + raise ValueError("Parameter `{param_name}` cannot be empty".format( + param_name=param_name)) + + +def sn_match(sn, sn_now): + if sn != sn_now: + raise ValueError("Sn `{sn}` not match `{sn_now}`".format( + sn=sn, sn_now=sn_now)) diff --git a/bmp-dhcp-agent/dhcpd.conf.tpl b/bmp-dhcp-agent/dhcpd.conf.tpl new file mode 100644 index 0000000..834930e --- /dev/null +++ b/bmp-dhcp-agent/dhcpd.conf.tpl @@ -0,0 +1,42 @@ +ddns-update-style none; +ignore client-updates; +ddns-update-style none; +ignore client-updates; + +next-server ${BMP_HOST_IP}; +filename \"pxelinux.0\"; + +default-lease-time 600; +max-lease-time 1200; +option domain-name \"localhost\"; +option domain-name-servers 114.114.114.114,8.8.8.8; + +#pxe +option client-system-architecture code 93 = unsigned integer 16; +class \"pxe-clients\" { + match if (substring (option vendor-class-identifier, 0, 9) = \"PXEClient\") or + (substring (option vendor-class-identifier, 0, 9) = \"HW-Client\"); + if option client-system-architecture = 00:00 { + filename \"pxelinux.0\"; + }else if option client-system-architecture = 00:07 { + filename \"/uefi/x86_64/grubx64.efi\"; + }else if option client-system-architecture = 00:0b { + filename \"/uefi/arm64/grubaa64.efi\"; + }else if option client-system-architecture = 00:0c { + filename \"/uefi/loongarch64/BOOTLOONGARCH64.EFI\"; + }else if option client-system-architecture = 00:27 { + filename \"/uefi/loongarch64/BOOTLOONGARCH64.EFI\"; + } +} + +key omapi_key { + algorithm hmac-md5; + secret ${BMP_OMAPI_KEY}; +}; +omapi-key omapi_key; +omapi-port ${BMP_OMAPI_PORT}; + +subnet ${BMP_HOST_IP} netmask 255.255.255.255 { + +} + diff --git a/bmp-dhcp-agent/doc/command.md b/bmp-dhcp-agent/doc/command.md new file mode 100755 index 0000000..173785c --- /dev/null +++ b/bmp-dhcp-agent/doc/command.md @@ -0,0 +1,83 @@ +指令实例模板 +=========================================== + +### ping ip + +```json +{ + "sn" : "0", + "action" : "PingHost", + "ip" : "10.0.0.2" +} +``` + +### dhcp config add host + +```json +{ + "action": "DHCPConfigAddHost", + "sn": "0", + "ip": "10.0.0.2", + "mac": "00:01:6C:06:A6:29" +} + +``` + +### dhcp config delete host + +```json +{ + "action": "DHCPConfigDelHost", + "sn": "0", + "ip": "10.0.0.2", + "mac":"00:01:6C:06:A6:29" +} +``` + +### dhcp config add subnet + +```json +{ + "action": "DHCPConfigAddSubnet", + "sn": "0", + "subnet": "10.0.0.1", + "subnet_mask": "255.255.255.255", + "routes": "10.209.10.1" +} + +``` + +### dhcp config delete subnet + +```json +{ + "action": "DHCPConfigDelSubnet", + "sn": "0", + "subnet": "10.0.0.1" +} +``` + +### tftp config add grub + +```json +{ + "action": "TFTPConfigAddGrub", + "sn": "0", + "mac": "00:01:6C:06:A6:29", //此mac和DHCPConfigAddHost的mac要一致 + "boot_mode": "bios", //bios、uefi。不传此参数则同时配置所有 + "arch": "x86_64", //系统架构 x86_64、aarch64、loongarch64。不传此参数则同时配置所有 + "kernel_name": "v2.0.3-centos_7_9-2024072217-vmlinuz", + "initramfs_name": "v2.0.3-centos_7_9-2024072217-initramfs.gz" +} +``` +备注:采集时可以不传boot_mode和arch参数,这样就会生成多个配置文件,满足当前机器在每个架构下的配置 + +### tftp config delete grub + +```json +{ + "action": "TFTPConfigDelGrub", + "sn": "0", + "mac":"00:01:6C:06:A6:29" +} +``` \ No newline at end of file diff --git a/bmp-dhcp-agent/requirements.txt b/bmp-dhcp-agent/requirements.txt new file mode 100755 index 0000000..cdd4263 --- /dev/null +++ b/bmp-dhcp-agent/requirements.txt @@ -0,0 +1,5 @@ +pika>=1.3.1 +six>=1.16.0 +filelock>=3.0.12 +pypureomapi>=0.8 +jinja2 \ No newline at end of file diff --git a/bmp-dhcp-agent/setup.py b/bmp-dhcp-agent/setup.py new file mode 100755 index 0000000..09aba24 --- /dev/null +++ b/bmp-dhcp-agent/setup.py @@ -0,0 +1,45 @@ +import io +import os +import sys + +from setuptools import setup, find_packages + +NAME = "bmpda" +DESCRIPTION = "BMP DHCP Agent" +URL = "" +EMAIL = "" +AUTHOR = "JD Cloud Pysical System" +REQUIRES_PYTHON = ">=3.6" +VERSION = "2.0.1" + +here = os.path.abspath(os.path.dirname(__file__)) + + +# What packages are required for this module to be executed +def read_requires(): + with open(os.path.join(here, "requirements.txt")) as f: + return f.read().splitlines() + + +setup( + name=NAME, + version=VERSION, + description=DESCRIPTION, + author=AUTHOR, + author_email=EMAIL, + platforms="any", + python_requires=REQUIRES_PYTHON, + url=URL, + packages=find_packages( + exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), + entry_points={ + "console_scripts": [ + "bmp-agent = bmpda.cmd.agent:run", + ], + }, + install_requires=read_requires(), + # These files are included via the MANIFEST.in will be + # automatically installed with your package + include_package_data=True, + ## license="", + zip_safe=False) diff --git a/bmp-dhcp-agent/test-requirements.txt b/bmp-dhcp-agent/test-requirements.txt new file mode 100755 index 0000000..c2a8eaf --- /dev/null +++ b/bmp-dhcp-agent/test-requirements.txt @@ -0,0 +1,8 @@ +# The order of packages is significant, because pip processes them in the order +# of appearance. Changing the order has an impact on the overall integration +# process, which may cause wedges in the gate later. + +coverage!=4.4,>=4.0 # Apache-2.0 +testtools>=2.2.0 # MIT +stestr>=1.0.0 # Apache-2.0 +mock>=1.2 \ No newline at end of file diff --git a/bmp-dhcp-agent/tox.ini b/bmp-dhcp-agent/tox.ini new file mode 100755 index 0000000..a0755e5 --- /dev/null +++ b/bmp-dhcp-agent/tox.ini @@ -0,0 +1,74 @@ +[tox] +skipsdist = True +envlist = python3,pep8 +ignore_basepython_conflict=true + +[testenv] +usedevelop = True +setenv = + VIRTUAL_ENV={envdir} + PYTHONDONTWRITEBYTECODE = 1 + OS_TEST_PATH=./bmpda/tests/unit + LANGUAGE=en_US + LC_ALL=en_US.utf-8 +deps = + -r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt +commands = stestr run {posargs} +passenv = http_proxy, HTTP_PROXY, https_proxy, HTTPS_PROXY, no_proxy, NO_PROXY + +[testenv:cover] +setenv = VIRTUAL_ENV={envdir} + PYTHON=coverage run --source bmpda --omit='*tests*' --parallel-mode +commands = + coverage erase + stestr run {posargs} + coverage combine + coverage report --omit='*tests*' + coverage html -d ./cover --omit='*tests*' + +[testenv:venv] +setenv = PYTHONHASHSEED=0 +commands = {posargs:} + +[testenv:pep8] +basepython = python3 +usedevelop = False +deps= + hacking>=4.1.0 # Apache-2.0 + bashate>=0.5.1 # Apache-2.0 + flake8>=3.8.0 + flake8-import-order>=0.17.1 # LGPLv3 + doc8>=0.8.1 # Apache-2.0 +allowlist_externals = bash +commands = flake8 {posargs:bmpda} + # Run bashate during pep8 runs to ensure violations are caught by + # the check and gate queues. + +[flake8] +# [E129] visually indented line with same indent as next logical line. +# [W503] Line break before binary operator. +# [E999] SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers +# [H301] one import per line +# [W605] invalid escape sequence '\g' +# [E501] line too long(> 79 characters) +# [W504] line break after binary operator +# [H237] module thread is removed in Python 3 +# [H216] he unittest.mock module should be used rather than the third party mock package unless actually needed. If so, disable the H216 check in hacking config and ensure mock is declared in the project's requirements. +# [F821] undefined name '_' +# [E121] continuation line under-indented for hanging indent +# [E126] continuation line over-indented for hanging indent +ignore = E129,W503,E999,H301,W605,E501,W504,H237,H216,F821,E121,E126 +exclude = .venv,.git,.tox,dist,*lib/python*,*egg,imagebuild +import-order-style = pep8 +application-import-names = bmpda +# [H106] Don't put vim configuration in source files. +# [H203] Use assertIs(Not)None to check for None. +# [H204] Use assert(Not)Equal to check for equality. +# [H205] Use assert(Greater|Less)(Equal) for comparison. +# [H210] Require 'autospec', 'spec', or 'spec_set' in mock.patch/mock.patch.object calls +# [H904] Delay string interpolations at logging calls. +enable-extensions=H106,H203,H204,H205,H210 + + + diff --git a/bmp-driver/.cmd b/bmp-driver/.cmd new file mode 100644 index 0000000..ced32d3 --- /dev/null +++ b/bmp-driver/.cmd @@ -0,0 +1 @@ +rm -rf vendor diff --git a/bmp-driver/.gitmodules b/bmp-driver/.gitmodules new file mode 100644 index 0000000..506f24c --- /dev/null +++ b/bmp-driver/.gitmodules @@ -0,0 +1,3 @@ +[submodule "bmp-deploy"] + path = bmp-deploy + url = git@coding.jd.com:aidc-bmp/bmp-deploy.git diff --git a/bmp-driver/Dockerfile b/bmp-driver/Dockerfile new file mode 100644 index 0000000..5be0066 --- /dev/null +++ b/bmp-driver/Dockerfile @@ -0,0 +1,16 @@ +FROM centos:7.9.2009 + +MAINTAINER minping@jd.com +USER root +RUN groupadd -g 2001 ironic-driver +RUN useradd -d /home/ironic-driver -u 2001 -g 2001 ironic-driver + +WORKDIR /home/ironic-driver + +ADD ./ironic-driver /home/ironic-driver/ +RUN mkdir -p /home/ironic-driver/conf +ADD ./conf/* /home/ironic-driver/conf/ + +RUN chmod 755 /home/ironic-driver/ironic-driver +USER ironic-driver +CMD ./ironic-driver \ No newline at end of file diff --git a/bmp-driver/Makefile b/bmp-driver/Makefile new file mode 100644 index 0000000..db0a0a0 --- /dev/null +++ b/bmp-driver/Makefile @@ -0,0 +1,10 @@ + +BUILD_TIME := $(shell date +%Y%m%d%H%M%S) +VERSION := $(shell git describe --tags --always) +COMMITID := $(shell git rev-parse ${VERSION} | cut -c 1-32) +APP_NAME := ironic-driver-golang + +#GOARCH=amd64 GOOS=linux +ldflags ="-s -X main.VERSION=${COMMITID} -X main.BUILD_TIME=${BUILD_TIME}" +all: + GOARCH=amd64 GOOS=linux go build -ldflags ${ldflags} -o ${APP_NAME} main.go diff --git a/bmp-driver/README.md b/bmp-driver/README.md new file mode 100644 index 0000000..ee39170 --- /dev/null +++ b/bmp-driver/README.md @@ -0,0 +1,20 @@ +# bmp-driver + + +English | [简体中文](README.zh-CN.md) + +## Introduction + +The out-of-band control module receives action messages sent by bmp-scheduler via MQ and sends out-of-band remote commands to the device via ipmitool. + +The position of bmp-driver in the entire bmp architecture is shown in:[bmp arch](../bmp-scheduler/README.md) + + + +## 2,Core Features + + +- Instance startup:Send a remote out-of-band command to power on the system. +- Instance shutdown:Send a remote out-of-band command to shut down the system. +- Instance restart:Send a remote out-of-band command to reboot. + diff --git a/bmp-driver/README.zh-CN.md b/bmp-driver/README.zh-CN.md new file mode 100644 index 0000000..7dd429a --- /dev/null +++ b/bmp-driver/README.zh-CN.md @@ -0,0 +1,20 @@ +# bmp-driver + + +[English](README.md) | 简体中文 + +## 介绍 + +带外控制模块,向上承接bmp-scheduler经mq发送过来的动作消息,向下通过ipmitool往设备发送带外远程命令。 + +bmp-driver在整个bmp架构中的位置见:[bmp架构图](../bmp-scheduler/README.zh-CN.md) + + + +## 2,核心功能 + + +- 实例开机:发送远程带外命令开机。 +- 实例关机:发送远程带外命令关机。 +- 实例重启:发送远程带外命令重启。 + diff --git a/bmp-driver/bmp-driver.Dockerfile b/bmp-driver/bmp-driver.Dockerfile new file mode 100644 index 0000000..f82713a --- /dev/null +++ b/bmp-driver/bmp-driver.Dockerfile @@ -0,0 +1,13 @@ +FROM golang:1.17-alpine AS builder +ENV GOPROXY https://goproxy.cn +WORKDIR /usr/src/bmp-driver +COPY . . +RUN go build -o /tmp/bmp-driver . + +FROM alpine:3.16 +RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories \ + && apk add --no-cache ipmitool +WORKDIR /home/bmp/bmp-driver +COPY --from=builder /tmp/bmp-driver . +COPY ./conf ./conf +CMD ["./bmp-driver"] diff --git a/bmp-driver/bmp_vendor/bmp-scheduler/go.mod b/bmp-driver/bmp_vendor/bmp-scheduler/go.mod new file mode 100644 index 0000000..6e49b56 --- /dev/null +++ b/bmp-driver/bmp_vendor/bmp-scheduler/go.mod @@ -0,0 +1,3 @@ +module coding.jd.com/aidc-bmp/bmp-scheduler + +go 1.17 diff --git a/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/AddDHCPConfigHost.go b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/AddDHCPConfigHost.go new file mode 100644 index 0000000..a59e78e --- /dev/null +++ b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/AddDHCPConfigHost.go @@ -0,0 +1,19 @@ +package driver + +import "encoding/json" + +type AddDHCPConfigHost struct { + Action string `json:"action"` + Sn string `json:"sn"` + Mac string `json:"mac"` + Ip string `json:"ip"` +} + +//解决struct不能设置默认值的问题 +func (d AddDHCPConfigHost) MarshalJSON() ([]byte, error) { + type Alias AddDHCPConfigHost + if d.Action == "" { + d.Action = "DHCPConfigAddHost" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/CheckInitConfig.go b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/CheckInitConfig.go new file mode 100644 index 0000000..412cea1 --- /dev/null +++ b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/CheckInitConfig.go @@ -0,0 +1,24 @@ +package driver + +import "encoding/json" + +type CheckInitConfig struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` + Privilege string `json:"privilege"` //用户权限:Administrator, User, Operator + SubnetGateway string `json:"subnet_gateway"` + Mac1 string `json:"mac1"` + Mac2 string `json:"mac2"` +} + +//解决struct不能设置默认值的问题 +func (d CheckInitConfig) MarshalJSON() ([]byte, error) { + type Alias CheckInitConfig + if d.Action == "" { + d.Action = "CheckInitConfig" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/DHCPRestart.go b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/DHCPRestart.go new file mode 100644 index 0000000..e285438 --- /dev/null +++ b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/DHCPRestart.go @@ -0,0 +1,17 @@ +package driver + +import "encoding/json" + +type DHCPRestart struct { + Action string `json:"action"` + Sn string `json:"sn"` +} + +//解决struct不能设置默认值的问题 +func (d DHCPRestart) MarshalJSON() ([]byte, error) { + type Alias DHCPRestart + if d.Action == "" { + d.Action = "DHCPRestart" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/DelDHCPConfigHost.go b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/DelDHCPConfigHost.go new file mode 100644 index 0000000..f3557be --- /dev/null +++ b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/DelDHCPConfigHost.go @@ -0,0 +1,19 @@ +package driver + +import "encoding/json" + +type DelDHCPConfigHost struct { + Action string `json:"action"` + Sn string `json:"sn"` + Mac string `json:"mac"` + Ip string `json:"ip"` +} + +//解决struct不能设置默认值的问题 +func (d DelDHCPConfigHost) MarshalJSON() ([]byte, error) { + type Alias DelDHCPConfigHost + if d.Action == "" { + d.Action = "DHCPConfigDelHost" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/PingHost.go b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/PingHost.go new file mode 100644 index 0000000..4c842d4 --- /dev/null +++ b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/PingHost.go @@ -0,0 +1,18 @@ +package driver + +import "encoding/json" + +type PingHost struct { + Action string `json:"action"` + Sn string `json:"sn"` + Ip string `json:"ip"` +} + +//解决struct不能设置默认值的问题 +func (d PingHost) MarshalJSON() ([]byte, error) { + type Alias PingHost + if d.Action == "" { + d.Action = "PingHost" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/PowerCycle.go b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/PowerCycle.go new file mode 100644 index 0000000..e7ca733 --- /dev/null +++ b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/PowerCycle.go @@ -0,0 +1,20 @@ +package driver + +import "encoding/json" + +type PowerCycle struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` +} + +//解决struct不能设置默认值的问题 +func (d PowerCycle) MarshalJSON() ([]byte, error) { + type Alias PowerCycle + if d.Action == "" { + d.Action = "PowerCycle" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/PowerOff.go b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/PowerOff.go new file mode 100644 index 0000000..c2d2679 --- /dev/null +++ b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/PowerOff.go @@ -0,0 +1,20 @@ +package driver + +import "encoding/json" + +type PowerOff struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` +} + +//解决struct不能设置默认值的问题 +func (d PowerOff) MarshalJSON() ([]byte, error) { + type Alias PowerOff + if d.Action == "" { + d.Action = "PowerOff" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/PowerOn.go b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/PowerOn.go new file mode 100644 index 0000000..adb0ce7 --- /dev/null +++ b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/PowerOn.go @@ -0,0 +1,20 @@ +package driver + +import "encoding/json" + +type PowerOn struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` +} + +//解决struct不能设置默认值的问题 +func (d PowerOn) MarshalJSON() ([]byte, error) { + type Alias PowerOn + if d.Action == "" { + d.Action = "PowerOn" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/PowerReset.go b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/PowerReset.go new file mode 100644 index 0000000..7555260 --- /dev/null +++ b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/PowerReset.go @@ -0,0 +1,20 @@ +package driver + +import "encoding/json" + +type PowerReset struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` +} + +//解决struct不能设置默认值的问题 +func (d PowerReset) MarshalJSON() ([]byte, error) { + type Alias PowerReset + if d.Action == "" { + d.Action = "PowerReset" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/SetDISKBoot.go b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/SetDISKBoot.go new file mode 100644 index 0000000..9aa4df5 --- /dev/null +++ b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/SetDISKBoot.go @@ -0,0 +1,20 @@ +package driver + +import "encoding/json" + +type SetDISKBoot struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` +} + +//解决struct不能设置默认值的问题 +func (d SetDISKBoot) MarshalJSON() ([]byte, error) { + type Alias SetDISKBoot + if d.Action == "" { + d.Action = "SetDISKBoot" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/SetPXEBoot.go b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/SetPXEBoot.go new file mode 100644 index 0000000..b2cf32a --- /dev/null +++ b/bmp-driver/bmp_vendor/bmp-scheduler/types/driver/SetPXEBoot.go @@ -0,0 +1,22 @@ +package driver + +import ( + "encoding/json" +) + +type SetPXEBoot struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` +} + +//解决struct不能设置默认值的问题 +func (d SetPXEBoot) MarshalJSON() ([]byte, error) { + type Alias SetPXEBoot + if d.Action == "" { + d.Action = "SetPXEBoot" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-driver/bmp_vendor/ironic-common/go.mod b/bmp-driver/bmp_vendor/ironic-common/go.mod new file mode 100644 index 0000000..5364f89 --- /dev/null +++ b/bmp-driver/bmp_vendor/ironic-common/go.mod @@ -0,0 +1,3 @@ +module git.jd.com/cps-golang/ironic-common + +go 1.17 diff --git a/bmp-driver/bmp_vendor/ironic-common/ironic/util/util.go b/bmp-driver/bmp_vendor/ironic-common/ironic/util/util.go new file mode 100644 index 0000000..5aca77e --- /dev/null +++ b/bmp-driver/bmp_vendor/ironic-common/ironic/util/util.go @@ -0,0 +1,77 @@ +package util + +import ( + "encoding/json" + "errors" + "fmt" + "math/rand" + "reflect" + "strconv" + "time" +) + +//GetRandString 借鉴RandomStringUtils.random包生成随机字符串 +// length 随机字符串的长度(不包括前缀) +// uletter 随机字符串是否包含大写字母字符 +// dletter 随机字符串是否包含小写字母字符 +// number 随机字符串是否包含数字字符 +func GetRandString(prefix string, length int32, uletter, dletter, number bool) string { + rand.Seed(time.Now().UnixNano()) + uletters := []rune("ABCDEFGHIGKLMNOPQRSTUVWXYZ") + dletters := []rune("abcdefghijklmnopqrstuvwxyz") + numbers := []rune("0123456789") + source := []rune{} + if uletter { + source = append(source, uletters...) + } + if dletter { + source = append(source, dletters...) + } + if number { + source = append(source, numbers...) + } + if len(source) == 0 { + return "atLeastContainsLetterOrNumber" + } + b := make([]rune, length) + for i := range b { + b[i] = source[rand.Intn(len(source))] + } + return prefix + string(b) +} + +// 跟现有环境一致,格式:aafc4d1b-f696-4ec2-924f-6fd012aa8345 +func GenerateRandUuid() string { + s := GetRandString("", 32, false, true, true) + runes := []rune(s) + return string(runes[0:8]) + "-" + string(runes[8:12]) + "-" + string(runes[12:16]) + "-" + string(runes[16:20]) + "-" + string(runes[20:32]) +} + +func Convert2String(val interface{}) (msg string, err error) { + + if val == nil{ + return "", nil + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool: + msg = strconv.FormatBool(val.(bool)) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + msg = fmt.Sprintf("%v", val) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + msg = fmt.Sprintf("%v", val) + case reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + msg = fmt.Sprintf("%v", val) + case reflect.String: + msg = val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + s, err := json.Marshal(val) + if err == nil { + msg = string(s) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + err = errors.New(fmt.Sprintf("type %s not support convert to string", reflect.TypeOf(val).String())) + default: + err = errors.New(fmt.Sprintf("type %s not support convert to string", reflect.TypeOf(val).String())) + } + return +} diff --git a/bmp-driver/bmp_vendor/log/.cmd b/bmp-driver/bmp_vendor/log/.cmd new file mode 100644 index 0000000..5c2f328 --- /dev/null +++ b/bmp-driver/bmp_vendor/log/.cmd @@ -0,0 +1 @@ +rm test.log.FATAL test.log.INFO test.log.WARN diff --git a/bmp-driver/bmp_vendor/log/README.md b/bmp-driver/bmp_vendor/log/README.md new file mode 100644 index 0000000..f39a094 --- /dev/null +++ b/bmp-driver/bmp_vendor/log/README.md @@ -0,0 +1,6 @@ +精简日志库,用于打点统计,监控,告警等场景 +- WARN,FATAL等等级的日志即时打印落盘 + - 一个流量可以打印多条WARN,FATAL日志 +- INFO,DEBUG等级的日志,一个流量只落一条日志 + - 支持字段顺序自定义,便于正则匹配做监控等场景 + - 支持自定义代码段耗时打印,便于后续性能统计分析 diff --git a/bmp-driver/bmp_vendor/log/go.mod b/bmp-driver/bmp_vendor/log/go.mod new file mode 100644 index 0000000..83d5129 --- /dev/null +++ b/bmp-driver/bmp_vendor/log/go.mod @@ -0,0 +1,3 @@ +module git.jd.com/cps-golang/log + +go 1.17 diff --git a/bmp-driver/bmp_vendor/log/log.go b/bmp-driver/bmp_vendor/log/log.go new file mode 100644 index 0000000..6e5b79c --- /dev/null +++ b/bmp-driver/bmp_vendor/log/log.go @@ -0,0 +1,249 @@ +package cps_log + +import ( + "encoding/json" + "fmt" + "io" + "log" + "os" + "reflect" + "strings" + "time" +) + +// Level type +type Level uint32 + +const ( + // TraceLevel level. Designates finer-grained informational events than the Debug. + TraceLevel Level = iota + // DebugLevel level. Usually only enabled when debugging. Very verbose logging. + DebugLevel + // InfoLevel level. General operational entries about what's going on inside the + // application. + InfoLevel + // WarnLevel level. Non-critical entries that deserve eyes. + WarnLevel + // ErrorLevel level. Logs. Used for errors that should definitely be noted. + // Commonly used for hooks to send errors to an error tracking service. + ErrorLevel + // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the + // logging level is set to Panic. + FatalLevel + // PanicLevel level, highest level of severity. Logs and then calls panic with the + // message passed to Debug, Info, ... + PanicLevel +) + +var globalDefinedKeys = []string{"time", "logid", "self_t", "all_t"} + +type Logger struct { + data map[string]interface{} + level Level + fileName string + definedKeys []string +} + +func New(filename string) *Logger { + if filename == "" { + log.Fatal("filename must be provided !!!") + return nil + } + l := &Logger{ + data: make(map[string]interface{}), + fileName: filename, + } + l.definedKeys = append([]string{}, globalDefinedKeys...) + l.data["time"] = time.Now().Format("2006-01-02T15:04:05") + return l +} + +func NewLoggerWithConfig(filename string, level Level, definedKeys []string) *Logger { + l := New(filename) + l.SetLevel(level) + l.SetStableFields(definedKeys) + return l +} + +func (l *Logger) SetLevel(level Level) { + l.level = level +} + +//SetStableFields 需要固定每条日志的字段时,通过此接口设置,global在前,userdefined在后 +func (l *Logger) SetStableFields(fields []string) { + l.definedKeys = append(l.definedKeys, fields...) +} + +func (l *Logger) Point(key string, val interface{}) { + l.data[key] = val +} + +func (l *Logger) GetPoint(key string) interface{} { + return l.data[key] +} + +func (l *Logger) TimeStart(key string) { + if _, ok := l.data[key]; ok { + log.Print(fmt.Sprintf("point %s TimeStart more than once, check !!!", key)) + } + l.data[key] = time.Now() + +} + +func (l *Logger) TimeEnd(key string) { + if t, ok := l.data[key]; ok { + v := time.Now().Sub(t.(time.Time)).Milliseconds() + l.data[key] = fmt.Sprintf("%f", float64(v)/1000.0) + } else { + log.Print(fmt.Sprintf("missing call TimeStart before TimeEnd when point %s, check it!!!", key)) + } + +} + +func (l *Logger) PushPoint(key string, val interface{}) { + if _, ok := l.data[key]; !ok { + l.data[key] = []interface{}{} + } + d := l.data[key].([]interface{}) + d = append(d, val) +} + +func (l *Logger) Info(v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Infof(format string, v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warn(v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warnf(format string, v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatal(v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatalf(format string, v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Flush() { + if l.level > DebugLevel { + return + } + var beforeStr, afterStr string + for _, key := range l.definedKeys { + if val, ok := l.data[key]; ok { + if key == "time" { + beforeStr = val.(string) + continue + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + beforeStr = beforeStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + beforeStr = beforeStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + beforeStr = beforeStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Printf("val for %s unknown type!!!", key)) + + } + } + } + for key, val := range l.data { + if exist, _ := inArray(key, l.definedKeys); !exist { + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + afterStr = afterStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + afterStr = afterStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + afterStr = afterStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Sprintf("val for %s unknown type!!!", key)) + } + } + } + + line := strings.TrimSpace(beforeStr) + " " + strings.TrimSpace(afterStr) + "\r\n" + filename := fmt.Sprintf("%s.DEBUG", l.fileName) + WriteFile(filename, line) +} + +func WriteFile(filename, line string) { + TimeStamp := time.Now() + str := filename + "." + TimeStamp.Format("2006-01-02") + logf, err := os.OpenFile(str, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + if err != nil { + log.Fatal("open filename error:", err.Error()) + } + defer logf.Close() + if _, err := io.WriteString(logf, line); err != nil { + log.Fatal("write line error:", err.Error()) + } +} + +func inArray(val interface{}, array interface{}) (exists bool, index int) { + exists = false + index = -1 + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + index = i + exists = true + return + } + } + } + return +} diff --git a/bmp-driver/command/CheckInitConfig.go b/bmp-driver/command/CheckInitConfig.go new file mode 100644 index 0000000..a579333 --- /dev/null +++ b/bmp-driver/command/CheckInitConfig.go @@ -0,0 +1,131 @@ +package command + +import ( + "fmt" + "os/exec" + "strings" + + "coding.jd.com/aidc-bmp/bmp-driver/errors" + ipmitool "coding.jd.com/aidc-bmp/bmp-driver/ipmitool" + "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" +) + +type CheckInitConfig struct { + *BaseCommand + driver.CheckInitConfig +} + +func init() { + + commands = append(commands, &CheckInitConfig{}) +} + +func (d *CheckInitConfig) Accept(action string) (Commandor, bool) { + if action == "CheckInitConfig" { + return &CheckInitConfig{BaseCommand: &BaseCommand{}}, true + } + return nil, false +} + +func (d *CheckInitConfig) ExecuteBefore() { + //TODO + +} + +func (d *CheckInitConfig) Execute() (err error) { + err = d.checkIloipStatus(d.IloIp) + if err != nil { + return + } + if d.SubnetGateway != "" { + err = d.checkSubnetGatewayStatus(d.SubnetGateway) + if err != nil { + return + } + } + err = d.checkIPMIPrivilege(d.IloIp, d.Username, d.Password, d.Privilege) + if err != nil { + return + } + return +} + +func (d *CheckInitConfig) ExecuteAfter() { + //TODO + +} + +func (d *CheckInitConfig) checkIPMIPrivilege(ip, username, password, privilege string) (err error) { + curPrivilege, err := d.getIPMIUserPrivilege(ip, username, password) + if err != nil { + return + } + if strings.ToLower(curPrivilege) == strings.ToLower(privilege) { + return + } + errMsg := fmt.Sprintf(errors.USER_PRIVILEGE_ERROR_MESSAGE, username, curPrivilege, privilege) + err = errors.NewBmpError(errors.USER_PRIVILEGE_ERROR_CODE, errMsg, nil) + d.Logger.Warn(err.Error()) + return +} + +func (d *CheckInitConfig) checkSubnetGatewayStatus(subnetGateway string) (err error) { + err = d.checkNetWorkStatus(subnetGateway) + if err != nil { + err = errors.NewBmpError(errors.PING_SUBNET_GATEWAY_ERROR_CODE, errors.PING_SUBNET_GATEWAY_ERROR_MESSAGE, err) + d.Logger.Warn(err.Error()) + } + return +} + +func (d *CheckInitConfig) checkIloipStatus(iloIP string) (err error) { + err = d.checkNetWorkStatus(iloIP) + if err != nil { + err = errors.NewBmpError(errors.PING_ILOIP_ERROR_CODE, errors.PING_ILOIP_ERROR_MESSAGE, err) + d.Logger.Warn(err.Error()) + } + return +} + +func (d *CheckInitConfig) checkNetWorkStatus(address string) (err error) { + cmd := exec.Command("ping", address, "-c", "1", "-W", "5") + res, err := cmd.CombinedOutput() + if err != nil { + errMsg := fmt.Sprintf(errors.NETWORK_STATUS_ERROR_MESSAGE, string(res[:])) + err = errors.NewBmpError(errors.NETWORK_STATUS_ERROR_CODE, errMsg, err) + d.Logger.Warn(err.Error()) + } + return +} + +func (d *CheckInitConfig) getIPMIUserPrivilege(ip, username, password string) (privilege string, err error) { + + res, retCode, err := ipmitool.UserList(d.Logger, ip, username, password) + if err != nil { + errMsg := fmt.Sprintf(errors.USERNAME_OR_PASSWORD_ERROR_MESSAGE, res) + err = errors.NewBmpError(errors.USERNAME_OR_PASSWORD_ERROR_CODE, errMsg, err) + d.Logger.Warn(err.Error()) + return + } + d.Logger.Info("Get ipmi user list res"+ip, fmt.Sprintf("%d__%s", retCode, res)) + //Return csv data format + //1,,true,false,false,NO ACCESS + //2,jdroot,true,true,true,USER + //3,jdcps,true,true,true,ADMINISTRATOR + userListSlice := strings.Split(string(res), "\n") + + for _, v := range userListSlice { + vSlice := strings.Split(v, ",") + if len(vSlice) < 6 { + continue + } + if vSlice[1] == username { + privilege = vSlice[5] + return + } + } + errMsg := fmt.Sprintf(errors.USERNAME_OR_PASSWORD_ERROR_MESSAGE, username) + err = errors.NewBmpError(errors.USERNAME_OR_PASSWORD_ERROR_CODE, errMsg, nil) + d.Logger.Warn(err.Error()) + return +} diff --git a/bmp-driver/command/DHCPConfigAddHost.go b/bmp-driver/command/DHCPConfigAddHost.go new file mode 100644 index 0000000..a0aaa03 --- /dev/null +++ b/bmp-driver/command/DHCPConfigAddHost.go @@ -0,0 +1,30 @@ +package command + +type DHCPConfigAddHost struct { + *BaseCommand +} + +func init() { + + commands = append(commands, &DHCPConfigAddHost{}) +} + +func (d *DHCPConfigAddHost) Accept(action string) (Commandor, bool) { + if action == "DHCPConfigAddHost" { + return &DHCPConfigAddHost{BaseCommand: &BaseCommand{}}, true + } + return nil, false +} + +func (d *DHCPConfigAddHost) ExecuteBefore() { + //TODO +} + +func (d *DHCPConfigAddHost) Execute() error { + //TODO + return nil +} + +func (d *DHCPConfigAddHost) ExecuteAfter() { + //TODO +} diff --git a/bmp-driver/command/DHCPConfigDelHost.go b/bmp-driver/command/DHCPConfigDelHost.go new file mode 100644 index 0000000..f0ea0ea --- /dev/null +++ b/bmp-driver/command/DHCPConfigDelHost.go @@ -0,0 +1,30 @@ +package command + +type DHCPConfigDelHost struct { + *BaseCommand +} + +func init() { + + commands = append(commands, &DHCPConfigDelHost{}) +} + +func (d *DHCPConfigDelHost) Accept(action string) (Commandor, bool) { + if action == "DHCPConfigDelHost" { + return &DHCPConfigDelHost{BaseCommand: &BaseCommand{}}, true + } + return nil, false +} + +func (d *DHCPConfigDelHost) ExecuteBefore() { + //TODO +} + +func (d *DHCPConfigDelHost) Execute() error { + //TODO + return nil +} + +func (d *DHCPConfigDelHost) ExecuteAfter() { + //TODO +} diff --git a/bmp-driver/command/DHCPRestart.go b/bmp-driver/command/DHCPRestart.go new file mode 100644 index 0000000..4b244fd --- /dev/null +++ b/bmp-driver/command/DHCPRestart.go @@ -0,0 +1,30 @@ +package command + +type DHCPRestart struct { + *BaseCommand +} + +func init() { + + commands = append(commands, &DHCPRestart{}) +} + +func (d *DHCPRestart) Accept(action string) (Commandor, bool) { + if action == "DHCPRestart" { + return &DHCPRestart{BaseCommand: &BaseCommand{}}, true + } + return nil, false +} + +func (d *DHCPRestart) ExecuteBefore() { + //TODO +} + +func (d *DHCPRestart) Execute() error { + //TODO + return nil +} + +func (d *DHCPRestart) ExecuteAfter() { + //TODO +} diff --git a/bmp-driver/command/Heart.go b/bmp-driver/command/Heart.go new file mode 100644 index 0000000..bd0e276 --- /dev/null +++ b/bmp-driver/command/Heart.go @@ -0,0 +1,53 @@ +package command + +import ( + mq "coding.jd.com/aidc-bmp/bmp-driver/service/rabbit_mq" + "coding.jd.com/aidc-bmp/bmp-driver/util" + log "git.jd.com/cps-golang/log" + beego "github.com/beego/beego/v2/server/web" +) + +type Heart struct { + *BaseCommand + Sn string `json:"sn,omitempty"` +} + +func init() { + + commands = append(commands, &Heart{}) +} + +func (d *Heart) Accept(action string) (Commandor, bool) { + if action == "Heart" { + return &Heart{BaseCommand: &BaseCommand{}}, true + } + return nil, false +} + +func (d *Heart) Execute() error { + //TODO + return nil +} + +func (d *Heart) ExecuteBefore() { + //TODO +} + +func (d *Heart) ExecuteAfter() { + //TODO +} + +func Heartbeat() { + logPath, _ := beego.AppConfig.String("log.path") + logger := log.New(logPath + "/bmp-driver.log") + msg := map[string]interface{}{ + "sn": mq.RoutingKey, + "config": mq.C, + "heart_period": 300, + } //心跳格式待再次确认 + if err := mq.SendToIronicScheduler(msg); err != nil { + logger.Warnf("Heartbeat.SendToIronicScheduler error:%s", err.Error()) + } else { + logger.Infof("send heart message to ironicScheduler success, msg:%s", util.ObjToJson(msg)) + } +} diff --git a/bmp-driver/command/PingHost.go b/bmp-driver/command/PingHost.go new file mode 100644 index 0000000..a882628 --- /dev/null +++ b/bmp-driver/command/PingHost.go @@ -0,0 +1,32 @@ +package command + +type PingHost struct { + *BaseCommand +} + +func init() { + + commands = append(commands, &PingHost{}) +} + +func (d *PingHost) Accept(action string) (Commandor, bool) { + if action == "PingHost" { + return &PingHost{BaseCommand: &BaseCommand{}}, true + } + return nil, false +} + +func (d *PingHost) ExecuteBefore() { + //TODO + +} + +func (d *PingHost) Execute() error { + //TODO + return nil +} + +func (d *PingHost) ExecuteAfter() { + //TODO + +} diff --git a/bmp-driver/command/PowerCycle.go b/bmp-driver/command/PowerCycle.go new file mode 100644 index 0000000..7846a14 --- /dev/null +++ b/bmp-driver/command/PowerCycle.go @@ -0,0 +1,77 @@ +package command + +import ( + "fmt" + "strings" + "time" + + constant "coding.jd.com/aidc-bmp/bmp-driver/constant" + ipmitool "coding.jd.com/aidc-bmp/bmp-driver/ipmitool" + "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" +) + +type PowerCycle struct { + *BaseCommand + driver.PowerCycle +} + +func init() { + + commands = append(commands, &PowerCycle{}) +} + +func (d *PowerCycle) Accept(action string) (Commandor, bool) { + if action == "PowerCycle" { + return &PowerCycle{BaseCommand: &BaseCommand{}}, true + } + return nil, false +} + +func (d *PowerCycle) ExecuteBefore() { + //TODO + +} + +func (d *PowerCycle) Execute() error { + res, ret_code, err := ipmitool.SetBootDevice(d.Logger, d.IloIp, d.Username, d.Password, constant.DISK) + if err != nil { + d.Logger.Warn("PowerCycle SetBootDevice "+d.IloIp+" execute error:", err.Error()) + return err + } + d.Logger.Info("PowerCycle_SetBootDevice_res"+d.IloIp, fmt.Sprintf("%d__%s", ret_code, res)) + time.Sleep(4 * time.Second) + + res, _, err = ipmitool.PowerStatus(d.Logger, d.IloIp, d.Username, d.Password) + if err != nil { + d.Logger.Warn("PowerCycle_PowerStatus "+d.IloIp+" execute error:", err.Error()) + return err + } + res = strings.TrimSpace(res) + + // fmt.Println("getIloipPowerStatus debug...", iloip, retStr) + items := strings.Split(res, " ") + status := strings.ToLower(items[len(items)-1]) + if status != "on" { + res, ret_code, err = ipmitool.PowerOn(d.Logger, d.IloIp, d.Username, d.Password) + if err != nil { + d.Logger.Warn("PowerCycle_PowerOn "+d.IloIp+" execute error:", err.Error()) + return err + } + time.Sleep(3 * time.Second) + } + + res, ret_code, err = ipmitool.PowerCycle(d.Logger, d.IloIp, d.Username, d.Password) + if err != nil { + d.Logger.Warn("PowerCycle_PowerCycle "+d.IloIp+" execute error:", err.Error()) + return err + } + time.Sleep(3 * time.Second) + d.Logger.Info("PowerCycle_PowerCycle_res "+d.IloIp, fmt.Sprintf("%d__%s", ret_code, res)) + return nil + +} + +func (d *PowerCycle) ExecuteAfter() { + //TODO + +} diff --git a/bmp-driver/command/PowerOff.go b/bmp-driver/command/PowerOff.go new file mode 100644 index 0000000..6ac68a7 --- /dev/null +++ b/bmp-driver/command/PowerOff.go @@ -0,0 +1,70 @@ +package command + +import ( + "fmt" + "strings" + "time" + + ipmitool "coding.jd.com/aidc-bmp/bmp-driver/ipmitool" + "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" +) + +type PowerOff struct { + *BaseCommand + driver.PowerOff +} + +func init() { + + commands = append(commands, &PowerOff{}) +} + +func (d *PowerOff) Accept(action string) (Commandor, bool) { + if action == "PowerOff" { + return &PowerOff{BaseCommand: &BaseCommand{}}, true + } + return nil, false +} + +func (d *PowerOff) ExecuteBefore() { + //TODO + +} + +func (d *PowerOff) Execute() error { + + res, _, err := ipmitool.PowerStatus(d.Logger, d.IloIp, d.Username, d.Password) + if err != nil { + d.Logger.Warn("PowerOff PowerStatus "+d.IloIp+" execute error:", err.Error()) + return err + } + res = strings.TrimSpace(res) + + // fmt.Println("getIloipPowerStatus debug...", iloip, retStr) + items := strings.Split(res, " ") + status := strings.ToLower(items[len(items)-1]) + if status != "off" { + res, ret_code, err := ipmitool.PowerSoft(d.Logger, d.IloIp, d.Username, d.Password) + if err != nil { + d.Logger.Warn("PowerOff PowerSoft "+d.IloIp+" execute error:", err.Error()) + return err + } + time.Sleep(1 * time.Second) + d.Logger.Info("PowerOff_PowerSoft_res "+d.IloIp, fmt.Sprintf("%d__%s", ret_code, res)) + res, ret_code, err = ipmitool.PowerOff(d.Logger, d.IloIp, d.Username, d.Password) + if err != nil { + d.Logger.Warn("PowerOff PowerOff "+d.IloIp+" execute error:", err.Error()) + return err + } + d.Logger.Info("PowerOff_PowerOff_res "+d.IloIp, fmt.Sprintf("%d__%s", ret_code, res)) + time.Sleep(3 * time.Second) + + } + d.Logger.Info("PowerOff_execute success " + d.IloIp) + return nil +} + +func (d *PowerOff) ExecuteAfter() { + //TODO + +} diff --git a/bmp-driver/command/PowerOn.go b/bmp-driver/command/PowerOn.go new file mode 100644 index 0000000..dc78964 --- /dev/null +++ b/bmp-driver/command/PowerOn.go @@ -0,0 +1,47 @@ +package command + +import ( + "fmt" + "time" + + ipmitool "coding.jd.com/aidc-bmp/bmp-driver/ipmitool" + "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" +) + +type PowerOn struct { + *BaseCommand + driver.PowerOn +} + +func init() { + + commands = append(commands, &PowerOn{}) +} + +func (d *PowerOn) Accept(action string) (Commandor, bool) { + if action == "PowerOn" { + return &PowerOn{BaseCommand: &BaseCommand{}}, true + } + return nil, false +} + +func (d *PowerOn) ExecuteBefore() { + //TODO + +} + +func (d *PowerOn) Execute() error { + res, ret_code, err := ipmitool.PowerOn(d.Logger, d.IloIp, d.Username, d.Password) + if err != nil { + d.Logger.Warn("PowerOn PowerOn "+d.IloIp+" execute error:", err.Error()) + return err + } + time.Sleep(3 * time.Second) + d.Logger.Info("PowerOn_PowerOn_res "+d.IloIp, fmt.Sprintf("%d__%s", ret_code, res)) + return nil +} + +func (d *PowerOn) ExecuteAfter() { + //TODO + +} diff --git a/bmp-driver/command/PowerReset.go b/bmp-driver/command/PowerReset.go new file mode 100644 index 0000000..59bc395 --- /dev/null +++ b/bmp-driver/command/PowerReset.go @@ -0,0 +1,54 @@ +package command + +import ( + "fmt" + "time" + + constant "coding.jd.com/aidc-bmp/bmp-driver/constant" + ipmitool "coding.jd.com/aidc-bmp/bmp-driver/ipmitool" + "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" +) + +type PowerReset struct { + *BaseCommand + driver.PowerReset +} + +func init() { + commands = append(commands, &PowerReset{}) +} + +func (d *PowerReset) Accept(action string) (Commandor, bool) { + if action == "PowerReset" { + return &PowerReset{BaseCommand: &BaseCommand{}}, true + } + return nil, false +} + +func (d *PowerReset) ExecuteBefore() { + //TODO + +} + +func (d *PowerReset) Execute() error { + res, ret_code, err := ipmitool.SetBootDevice(d.Logger, d.IloIp, d.Username, d.Password, constant.DISK) + if err != nil { + d.Logger.Warn("PowerReset SetBootDevice "+d.IloIp+" execute error:", err.Error()) + return err + } + d.Logger.Info("PowerReset_SetBootDevice_res "+d.IloIp, fmt.Sprintf("%d__%s", ret_code, res)) + time.Sleep(4 * time.Second) + res, ret_code, err = ipmitool.PowerReset(d.Logger, d.IloIp, d.Username, d.Password) + if err != nil { + d.Logger.Warn("PowerReset PowerReset "+d.IloIp+" execute error:", err.Error()) + return err + } + time.Sleep(3 * time.Second) + d.Logger.Info("PowerReset_PowerReset_res "+d.IloIp, fmt.Sprintf("%d__%s", ret_code, res)) + return nil +} + +func (d *PowerReset) ExecuteAfter() { + //TODO + +} diff --git a/bmp-driver/command/PowerSoft.go b/bmp-driver/command/PowerSoft.go new file mode 100644 index 0000000..e978a94 --- /dev/null +++ b/bmp-driver/command/PowerSoft.go @@ -0,0 +1,32 @@ +package command + +type PowerSoft struct { + *BaseCommand +} + +func init() { + + commands = append(commands, &PowerSoft{}) +} + +func (d *PowerSoft) Accept(action string) (Commandor, bool) { + if action == "PowerSoft" { + return &PowerSoft{BaseCommand: &BaseCommand{}}, true + } + return nil, false +} + +func (d *PowerSoft) ExecuteBefore() { + //TODO + +} + +func (d *PowerSoft) Execute() error { + //TODO + return nil +} + +func (d *PowerSoft) ExecuteAfter() { + //TODO + +} diff --git a/bmp-driver/command/SetDISKBoot.go b/bmp-driver/command/SetDISKBoot.go new file mode 100644 index 0000000..4e0ed13 --- /dev/null +++ b/bmp-driver/command/SetDISKBoot.go @@ -0,0 +1,63 @@ +package command + +import ( + "fmt" + "time" + + "coding.jd.com/aidc-bmp/bmp-driver/constant" + ipmitool "coding.jd.com/aidc-bmp/bmp-driver/ipmitool" + "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" +) + +type SetDISKBoot struct { + *BaseCommand + driver.SetDISKBoot +} + +func init() { + + commands = append(commands, &SetDISKBoot{}) +} + +func (d *SetDISKBoot) Accept(action string) (Commandor, bool) { + if action == "SetDISKBoot" { + return &SetDISKBoot{BaseCommand: &BaseCommand{}}, true + } + return nil, false +} + +func (d *SetDISKBoot) ExecuteBefore() { + //TODO + +} + +func (d *SetDISKBoot) Execute() error { + res, ret_code, err := ipmitool.SetBootDevice(d.Logger, d.IloIp, d.Username, d.Password, constant.DISK) + if err != nil { + d.Logger.Warn("SetDISKBoot SetBootDevice "+d.IloIp+" execute error:", err.Error()) + return err + } + d.Logger.Info("SetDISKBoot_SetBootDevice_res"+d.IloIp, fmt.Sprintf("%d__%s", ret_code, res)) + time.Sleep(3 * time.Second) + res, ret_code, err = ipmitool.PowerOn(d.Logger, d.IloIp, d.Username, d.Password) + if err != nil { + d.Logger.Warn("SetDISKBoot PowerOn "+d.IloIp+" execute error:", err.Error()) + return err + } + d.Logger.Info("SetDISKBoot_PowerOn_res"+d.IloIp, fmt.Sprintf("%d__%s", ret_code, res)) + time.Sleep(3 * time.Second) + // res, ret_code, err = ipmitool.PowerReset(d.IloIp, d.Username, d.Password) + // if err != nil { + // d.Logger.Warn("SetDISKBoot PowerReset execute error:", err.Error()) + // panic(err) + // } + // time.Sleep(3 * time.Second) + d.Logger.Info("SetDISKBoot_PowerReset_res"+d.IloIp, fmt.Sprintf("%d__%s", ret_code, res)) + return nil + +} + +func (d *SetDISKBoot) ExecuteAfter() { + //TODO + +} diff --git a/bmp-driver/command/SetPXEBoot.go b/bmp-driver/command/SetPXEBoot.go new file mode 100644 index 0000000..51648d1 --- /dev/null +++ b/bmp-driver/command/SetPXEBoot.go @@ -0,0 +1,61 @@ +package command + +import ( + "fmt" + "time" + + constant "coding.jd.com/aidc-bmp/bmp-driver/constant" + ipmitool "coding.jd.com/aidc-bmp/bmp-driver/ipmitool" + "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" +) + +type SetPXEBoot struct { + *BaseCommand + driver.SetPXEBoot +} + +func init() { + commands = append(commands, &SetPXEBoot{}) +} + +func (d *SetPXEBoot) Accept(action string) (Commandor, bool) { + if action == "SetPXEBoot" { + return &SetPXEBoot{BaseCommand: &BaseCommand{}}, true + } + return nil, false +} + +func (d *SetPXEBoot) ExecuteBefore() { + +} + +func (d *SetPXEBoot) Execute() error { + + res, ret_code, err := ipmitool.SetBootDevice(d.Logger, d.IloIp, d.Username, d.Password, constant.PXE) + if err != nil { + d.Logger.Warn("SetPXEBoot SetBootDevice "+d.IloIp+" execute error:", err.Error()) + return err + } + d.Logger.Info("SetPXEBoot_SetBootDevice_res"+d.IloIp, fmt.Sprintf("%d__%s", ret_code, res)) + time.Sleep(3 * time.Second) + res, ret_code, err = ipmitool.PowerOn(d.Logger, d.IloIp, d.Username, d.Password) + if err != nil { + d.Logger.Warn("SetPXEBoot PowerOn "+d.IloIp+" execute error:", err.Error()) + return err + } + d.Logger.Info("SetPXEBoot_PowerOn_res"+d.IloIp, fmt.Sprintf("%d__%s", ret_code, res)) + time.Sleep(3 * time.Second) + res, ret_code, err = ipmitool.PowerReset(d.Logger, d.IloIp, d.Username, d.Password) + if err != nil { + d.Logger.Warn("SetPXEBoot PowerReset "+d.IloIp+" execute error:", err.Error()) + return err + } + time.Sleep(10 * time.Second) + d.Logger.Info("SetPXEBoot_PowerReset_res"+d.IloIp, fmt.Sprintf("%d__%s", ret_code, res)) + return nil + +} + +func (d SetPXEBoot) ExecuteAfter() { + return +} diff --git a/bmp-driver/command/command.go b/bmp-driver/command/command.go new file mode 100644 index 0000000..1ef176a --- /dev/null +++ b/bmp-driver/command/command.go @@ -0,0 +1,150 @@ +package command + +import ( + "encoding/json" + "fmt" + "reflect" + + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + beego "github.com/beego/beego/v2/server/web" + + mq "coding.jd.com/aidc-bmp/bmp-driver/service/rabbit_mq" + log "git.jd.com/cps-golang/log" + + "coding.jd.com/aidc-bmp/bmp-driver/errors" + "coding.jd.com/aidc-bmp/bmp-driver/util" +) + +const ( + OK = "OK" + ERROR = "ERROR" +) + +var commands []Commandor = []Commandor{} + +type Commandor interface { + ExecuteBefore() + Execute() error + ExecuteAfter() + Accept(string) (Commandor, bool) +} + +type BaseCommand struct { + Logger *log.Logger `json:"-"` +} + +func getCommandor(action string) Commandor { + for _, v := range commands { + if c, selected := v.Accept(action); selected { + return c + } + } + return nil +} + +func (b *BaseCommand) Prepare(m map[string]interface{}) { + logPath, _ := beego.AppConfig.String("log.path") + logger := log.New(logPath + "/bmp-driver.log") + logger.TimeStart("all_t") + logger.TimeStart("self_t") + for k, v := range m { + logger.Point(k, v) + } + b.Logger = logger +} + +func (b *BaseCommand) Finish() { + b.Logger.TimeEnd("self_t") + b.Logger.TimeEnd("all_t") + b.Logger.Flush() +} + +func Run(msg []byte) { + logPath, _ := beego.AppConfig.String("log.path") + logger := log.New(logPath + "/bmp-driver.log") + logger.Info("ReceiveFromIronicScheduler msg: ", string(msg)) + fmt.Println("ReceiveFromIronicScheduler msg: ", string(msg)) + tmp := map[string]interface{}{} + if err := json.Unmarshal(msg, &tmp); err != nil { + logger.Warnf("unmarshal ironic-scheduler message error, msg:%s, error:%s", string(msg), err.Error()) + return + } + iAction, ok := tmp["action"] + if !ok || reflect.TypeOf(iAction).Kind() != reflect.String { + logger.Warn("unknow command action :", string(msg)) + return + } + action := iAction.(string) + iSn, ok := tmp["sn"] + if !ok || reflect.TypeOf(iSn).Kind() != reflect.String { + logger.Warn("unknow command Sn :", string(msg)) + return + } + sn := iSn.(string) + var c Commandor = getCommandor(action) + if c == nil { + logger.Warn("unknow command action :", string(msg)) + return + } + m := reflect.ValueOf(c).Elem().FieldByName("BaseCommand").MethodByName("Prepare") + preData := map[string]interface{}{ + "msg": string(msg), + "logid": commonUtil.GenerateRandUuid(), + } + m.Call([]reflect.Value{reflect.ValueOf(preData)}) + if err := json.Unmarshal(msg, c); err != nil { + logger.Warn("command unmarshal error :", err.Error()) + return + } + + var notice map[string]interface{} + defer func() { + if err := mq.SendToIronicScheduler(notice); err != nil { + logger.Warn("send message to ironicScheduler error, msg:%s, error:%s", util.ObjToJson(notice), err.Error()) + } else { + logger.Infof("send message to ironicScheduler success, msg:%s", util.ObjToJson(notice)) + } + }() + //TODO 后面放开 + // defer func() { + // if r := recover(); r != nil { + // t := make([]byte, 1<<16) + // runtime.Stack(t, true) + // notice = map[string]interface{}{ + // "sn": mq.C.Mq.Connection.ReceiveRoutingKey, + // "action": action, + // "status": ERROR, + // "message": fmt.Sprintf("run %s failed : %s", action, string(t)), + // } + // } + + // }() + + defer func() { + m := reflect.ValueOf(c).Elem().FieldByName("BaseCommand").MethodByName("Finish") + m.Call(nil) + }() + + c.ExecuteBefore() + err := c.Execute() + c.ExecuteAfter() + var status, message string + if err != nil { + status = ERROR + message = fmt.Sprintf("run %s error:%s.", action, err.Error()) + if errError, ok := err.(errors.Error); ok { + status = errError.ErrorCode() + message = fmt.Sprintf("run %s error:%s.", action, errError.Error()) + } + } else { + status = OK + message = fmt.Sprintf("run %s success.", action) + } + notice = map[string]interface{}{ + "sn": sn, + "action": action, + "status": status, + "message": message, + } + return +} diff --git a/bmp-driver/conf/app.conf b/bmp-driver/conf/app.conf new file mode 100644 index 0000000..e69de29 diff --git a/bmp-driver/conf/bmp-driver-test.ini b/bmp-driver/conf/bmp-driver-test.ini new file mode 100644 index 0000000..17a3a38 --- /dev/null +++ b/bmp-driver/conf/bmp-driver-test.ini @@ -0,0 +1,14 @@ +runmode = "test" +[test] + +# RabbitMQ +bmp_mq_host=${BMP_MQ_HOST||10.226.192.72} +bmp_mq_port=${BMP_MQ_PORT||15672} +bmp_mq_user=${BMP_MQ_USER||bmp} +bmp_mq_password=${BMP_MQ_PASSWORD||LE&oN$9wHB} +bmp_mq_vhost=${BMP_MQ_VHOST||/bmp} +bmp_mq_exchange=CPS_IRONIC_SCHEDULER +bmp_mq_receive_routing_key=idc-vm4xsulx1k2d9z4xkctrttig02zl + + + diff --git a/bmp-driver/conf/bmp-driver.ini b/bmp-driver/conf/bmp-driver.ini new file mode 100644 index 0000000..aab4c82 --- /dev/null +++ b/bmp-driver/conf/bmp-driver.ini @@ -0,0 +1,22 @@ +appname = bmp-driver +autorender = false +copyrequestbody = true +EnableDocs = true + +# RabbitMQ +bmp_mq_host=${BMP_MQ_HOST} +bmp_mq_port=${BMP_MQ_PORT} +bmp_mq_user=${BMP_MQ_USER} +bmp_mq_password=${BMP_MQ_PASSWORD} +bmp_mq_vhost=${BMP_MQ_VHOST} +bmp_mq_exchange=CPS_IRONIC_SCHEDULER +bmp_mq_receive_routing_key=idc-vm4xsulx1k2d9z4xkctrttig02zl + +# log +log.level=DEBUG +log.max.history=10 +log.path=/var/log/bmp/bmp-driver + +#如果在本地环境测试,启用下面的文件,改成自己的本地环境配置 +#include "bmp-driver-test.ini" + diff --git a/bmp-driver/constant/bootDevice.go b/bmp-driver/constant/bootDevice.go new file mode 100644 index 0000000..5a62e03 --- /dev/null +++ b/bmp-driver/constant/bootDevice.go @@ -0,0 +1,11 @@ +package constant + +const ( + PXE = "pxe" //"Boot from PXE boot" + DISK = "disk" //"Boot from default Hard-drive" + CDROM = "cdrom" //"Boot from CD/DVD" + BIOS = "bios" //"Boot into BIOS setup" + SAFE = "safe" //"Boot from default Hard-drive, request Safe Mode" + WANBOOT = "wanboot" //"Boot from Wide Area Network" + ISCSIBOOT = "iscsiboot" //"Boot from iSCSI volume" +) diff --git a/bmp-driver/cron/cleanLog.go b/bmp-driver/cron/cleanLog.go new file mode 100644 index 0000000..e3bdc86 --- /dev/null +++ b/bmp-driver/cron/cleanLog.go @@ -0,0 +1,49 @@ +package cron + +import ( + "fmt" + "os" + "path/filepath" + "regexp" + "time" + + beego "github.com/beego/beego/v2/server/web" +) + +const REGEX_FILE_NAME string = `^.*\.202[0-9]{7}$` +const LOG_DIR = "./log" + +func doCleanLogCron() error { + + files := []string{} + infos := []os.FileInfo{} + + remainDays, _ := beego.AppConfig.Int("logs.remainDays") + if remainDays == 0 { + remainDays = 3 //测试时默认3天 + } + + if err := filepath.Walk(LOG_DIR, func(path string, info os.FileInfo, err error) error { + files = append(files, path) + infos = append(infos, info) + return nil + }); err != nil { + fmt.Println("doCleanLogCron.Walk error:", err.Error()) + return err + } + + for _, info := range infos { + if info.IsDir() { + continue + } + if match, _ := regexp.MatchString(REGEX_FILE_NAME, info.Name()); match { + modifySince := time.Now().Unix() - info.ModTime().Unix() + if modifySince > int64(remainDays)*24*3600 { + if err := os.Remove(LOG_DIR + string(os.PathSeparator) + info.Name()); err != nil { + fmt.Printf("os.Remove error, file:%s, error:%s\n", info.Name(), err.Error()) + } + } + } + } + return nil +} diff --git a/bmp-driver/cron/cron.go b/bmp-driver/cron/cron.go new file mode 100644 index 0000000..543bd51 --- /dev/null +++ b/bmp-driver/cron/cron.go @@ -0,0 +1,14 @@ +package cron + +import ( + "github.com/beego/beego/v2/adapter/toolbox" +) + +func Run() { + + c1 := toolbox.NewTask("CleanLogCron", "0 5 */1 * * *", doCleanLogCron) + toolbox.AddTask("CleanLogCron", c1) + + toolbox.StartTask() + defer toolbox.StopTask() +} diff --git a/bmp-driver/errors/bmp_error.go b/bmp-driver/errors/bmp_error.go new file mode 100644 index 0000000..2bb8a94 --- /dev/null +++ b/bmp-driver/errors/bmp_error.go @@ -0,0 +1,64 @@ +package errors + +import "fmt" + +const ( + DEFAULT_BMP_ERROR_CODE = "ERROR" + DEFAULT_BMP_ERROR_MESSAGE = "Error" + USERNAME_OR_PASSWORD_ERROR_CODE = "USERNAME_OR_PASSWORD_ERROR" + USERNAME_OR_PASSWORD_ERROR_MESSAGE = "User name or password error:%s" + USER_PRIVILEGE_ERROR_CODE = "USER_PRIVILEGE_ERROR" + USER_PRIVILEGE_ERROR_MESSAGE = "Current user:%s privilege is %s not %s" + PING_ILOIP_ERROR_CODE = "PING_ILOIP_ERROR" + PING_ILOIP_ERROR_MESSAGE = "Ping iloip error." + PING_SUBNET_GATEWAY_ERROR_CODE = "PING_SUBNET_GATEWAY_ERROR" + PING_SUBNET_GATEWAY_ERROR_MESSAGE = "Ping subnet gateway error." + NETWORK_STATUS_ERROR_CODE = "NETWORK_STATUS_ERROR_CODE" + NETWORK_STATUS_ERROR_MESSAGE = "Network status error:%s." + MAC1_ERROR_CODE = "MAC1_ERROR" + MAC1_ERROR_MESSAGE = "Mac1 connectivity error" + MAC2_ERROR_CODE = "MAC2_ERROR" + MAC2_ERROR_MESSAGE = "Mac2 connectivity error" +) + +type BmpError struct { + errorCode string + message string + originError error +} + +func NewBmpError(errorCode, message string, originError error) Error { + return &BmpError{ + errorCode: errorCode, + message: message, + originError: originError, + } +} + +func (err *BmpError) ErrorCode() string { + if err.errorCode == "" { + return DEFAULT_BMP_ERROR_CODE + } else { + return err.errorCode + } +} + +func (err *BmpError) Error() string { + bmpErrMsg := fmt.Sprintf("[%s] %s", err.ErrorCode(), err.message) + if err.originError != nil { + return bmpErrMsg + "\ncaused by:\n" + err.originError.Error() + } + return bmpErrMsg +} + +func (err *BmpError) OriginError() error { + return err.originError +} + +func (err *BmpError) Message() string { + return err.message +} + +func (err *BmpError) String() string { + return err.Error() +} diff --git a/bmp-driver/errors/error.go b/bmp-driver/errors/error.go new file mode 100644 index 0000000..c30b4e3 --- /dev/null +++ b/bmp-driver/errors/error.go @@ -0,0 +1,8 @@ +package errors + +type Error interface { + error + ErrorCode() string + Message() string + OriginError() error +} diff --git a/bmp-driver/go.mod b/bmp-driver/go.mod new file mode 100644 index 0000000..af1c9b9 --- /dev/null +++ b/bmp-driver/go.mod @@ -0,0 +1,18 @@ +module coding.jd.com/aidc-bmp/bmp-driver + +go 1.15 + +require ( + coding.jd.com/aidc-bmp/bmp-scheduler v0.0.0-00010101000000-000000000000 + git.jd.com/cps-golang/ironic-common v0.0.0-00010101000000-000000000000 + git.jd.com/cps-golang/log v0.0.0-00010101000000-000000000000 + github.com/beego/beego/v2 v2.0.1 + github.com/streadway/amqp v1.0.0 + gopkg.in/yaml.v2 v2.4.0 // indirect +) + +replace coding.jd.com/aidc-bmp/bmp-scheduler => ./bmp_vendor/bmp-scheduler + +replace git.jd.com/cps-golang/ironic-common => ./bmp_vendor/ironic-common + +replace git.jd.com/cps-golang/log => ./bmp_vendor/log diff --git a/bmp-driver/go.sum b/bmp-driver/go.sum new file mode 100644 index 0000000..e7ee856 --- /dev/null +++ b/bmp-driver/go.sum @@ -0,0 +1,271 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= +github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk= +github.com/beego/beego/v2 v2.0.1 h1:07a7Z0Ok5vbqyqh+q53sDPl9LdhKh0ZDy3gbyGrhFnE= +github.com/beego/beego/v2 v2.0.1/go.mod h1:8zyHi1FnWO1mZLwTn62aKRIZF/aIKvkCBB2JYs+eqQI= +github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ= +github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60= +github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= +github.com/coreos/etcd v3.3.25+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U= +github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= +github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= +github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= +github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk= +github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDuKuq+uX4v1fulaMbA/7ZLLhjc85h7chZGBCQ= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mitchellh/mapstructure v1.3.3 h1:SzB1nHZ2Xi+17FP0zVQBHIZqvwRN9408fJO8h+eeNA8= +github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= +github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.7.0 h1:wCi7urQOGBsYcQROHqpUUX4ct84xp40t9R9JX0FuA/U= +github.com/prometheus/client_golang v1.7.0/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.10.0 h1:RyRA7RzGXQZiW+tGMr7sxa85G1z0yOpM1qq5c8lNawc= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.1.3 h1:F0+tqvhOksq22sc6iCHF5WGlWjdwj92p0udFh1VFBS8= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= +github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= +github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s= +github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE= +github.com/streadway/amqp v1.0.0 h1:kuuDrUJFZL1QYL9hUNuCxNObNzB0bV/ZG5jV3RWAQgo= +github.com/streadway/amqp v1.0.0/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= +github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= +go.etcd.io/etcd v3.3.25+incompatible/go.mod h1:yaeTdrJi5lOmYerz05bd8+V7KubZs8YSFZfzsF9A6aI= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f h1:+Nyd8tzPX9R7BWHguqsrbFdRx3WQ/1ib8I44HXV5yTA= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58 h1:1Bs6RVeBFtLZ8Yi1Hk07DiOqzvwLD/4hln4iahvFlag= +golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.5/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= diff --git a/bmp-driver/ipmitool/PowerCycle.go b/bmp-driver/ipmitool/PowerCycle.go new file mode 100644 index 0000000..f725f0a --- /dev/null +++ b/bmp-driver/ipmitool/PowerCycle.go @@ -0,0 +1,9 @@ +package ipmitool + +import log "git.jd.com/cps-golang/log" + +// 注意power cycle 和power reset的区别在于前者从掉电到上电有1秒钟的间隔,而后者是很快上电 +func PowerCycle(logger *log.Logger, ip, username, password string) (res string, ret_code int, err error) { + res, ret_code, err = execCommand(logger, ipmiToolPath, "-I", "lanplus", "-H", ip, "-U", username, "-P", password, "chassis", "power", "cycle") + return +} diff --git a/bmp-driver/ipmitool/PowerOff.go b/bmp-driver/ipmitool/PowerOff.go new file mode 100644 index 0000000..2203c79 --- /dev/null +++ b/bmp-driver/ipmitool/PowerOff.go @@ -0,0 +1,8 @@ +package ipmitool + +import log "git.jd.com/cps-golang/log" + +func PowerOff(logger *log.Logger, ip, username, password string) (res string, ret_code int, err error) { + res, ret_code, err = execCommand(logger, ipmiToolPath, "-I", "lanplus", "-H", ip, "-U", username, "-P", password, "chassis", "power", "off") + return +} diff --git a/bmp-driver/ipmitool/PowerOn.go b/bmp-driver/ipmitool/PowerOn.go new file mode 100644 index 0000000..1afd065 --- /dev/null +++ b/bmp-driver/ipmitool/PowerOn.go @@ -0,0 +1,8 @@ +package ipmitool + +import log "git.jd.com/cps-golang/log" + +func PowerOn(logger *log.Logger, ip, username, password string) (res string, ret_code int, err error) { + res, ret_code, err = execCommand(logger, ipmiToolPath, "-I", "lanplus", "-H", ip, "-U", username, "-P", password, "chassis", "power", "on") + return +} diff --git a/bmp-driver/ipmitool/PowerReset.go b/bmp-driver/ipmitool/PowerReset.go new file mode 100644 index 0000000..40051ad --- /dev/null +++ b/bmp-driver/ipmitool/PowerReset.go @@ -0,0 +1,8 @@ +package ipmitool + +import log "git.jd.com/cps-golang/log" + +func PowerReset(logger *log.Logger, ip, username, password string) (res string, ret_code int, err error) { + res, ret_code, err = execCommand(logger, ipmiToolPath, "-I", "lanplus", "-H", ip, "-U", username, "-P", password, "chassis", "power", "reset") + return +} diff --git a/bmp-driver/ipmitool/PowerSoft.go b/bmp-driver/ipmitool/PowerSoft.go new file mode 100644 index 0000000..072c516 --- /dev/null +++ b/bmp-driver/ipmitool/PowerSoft.go @@ -0,0 +1,8 @@ +package ipmitool + +import log "git.jd.com/cps-golang/log" + +func PowerSoft(logger *log.Logger, ip, username, password string) (res string, ret_code int, err error) { + res, ret_code, err = execCommand(logger, ipmiToolPath, "-I", "lanplus", "-H", ip, "-U", username, "-P", password, "chassis", "power", "soft") + return +} diff --git a/bmp-driver/ipmitool/PowerStatus.go b/bmp-driver/ipmitool/PowerStatus.go new file mode 100644 index 0000000..81a9e66 --- /dev/null +++ b/bmp-driver/ipmitool/PowerStatus.go @@ -0,0 +1,8 @@ +package ipmitool + +import log "git.jd.com/cps-golang/log" + +func PowerStatus(logger *log.Logger, ip, username, password string) (res string, ret_code int, err error) { + res, ret_code, err = execCommand(logger, ipmiToolPath, "-I", "lanplus", "-H", ip, "-U", username, "-P", password, "chassis", "power", "status") + return +} diff --git a/bmp-driver/ipmitool/SetBootDevice.go b/bmp-driver/ipmitool/SetBootDevice.go new file mode 100644 index 0000000..690428b --- /dev/null +++ b/bmp-driver/ipmitool/SetBootDevice.go @@ -0,0 +1,8 @@ +package ipmitool + +import log "git.jd.com/cps-golang/log" + +func SetBootDevice(logger *log.Logger, ip, username, password, boot_device string) (res string, ret_code int, err error) { + res, ret_code, err = execCommand(logger, ipmiToolPath, "-I", "lanplus", "-H", ip, "-U", username, "-P", password, "chassis", "bootdev", boot_device) + return +} diff --git a/bmp-driver/ipmitool/UserList.go b/bmp-driver/ipmitool/UserList.go new file mode 100644 index 0000000..6e374e7 --- /dev/null +++ b/bmp-driver/ipmitool/UserList.go @@ -0,0 +1,8 @@ +package ipmitool + +import log "git.jd.com/cps-golang/log" + +func UserList(logger *log.Logger, ip, username, password string) (res string, ret_code int, err error) { + res, ret_code, err = execCommand(logger, ipmiToolPath, "-c", "-I", "lanplus", "-H", ip, "-U", username, "-P", password, "user", "list") + return +} diff --git a/bmp-driver/ipmitool/executor.go b/bmp-driver/ipmitool/executor.go new file mode 100644 index 0000000..fbc2068 --- /dev/null +++ b/bmp-driver/ipmitool/executor.go @@ -0,0 +1,76 @@ +package ipmitool + +import ( + "errors" + "fmt" + "os/exec" + "regexp" + "strings" + "syscall" + + log "git.jd.com/cps-golang/log" +) + +var ipmiToolPath = "/usr/sbin/ipmitool" + +// ExecCommand function to execute command +func execCommand(logger *log.Logger, cmdStr string, params ...string) (retStr string, ret int, err error) { + logger.Info("execCommand:", cmdStr+" "+strings.Join(params, " ")) + // check command injection + r := regexp.MustCompile(`[&\|;]+`) + if matched := r.MatchString(cmdStr); matched { + return "", -1, errors.New("command can not contain [&|;], ignore execute") + } + for _, param := range params { + if matched := r.MatchString(param); matched { + return "", -1, errors.New("params can not contain [&|;], ignore execute") + } + } + fmt.Println("指令:", cmdStr+" "+strings.Join(params, " ")) + cmd := exec.Command(cmdStr, params...) + + // execute + //out, err := cmd.StdoutPipe() + //if err != nil { + // fmt.Println("StdoutPipe error: ", err.Error()) + // logger.Warn("StdoutPipe error: ", err.Error()) + // return "", 0, err + //} + //// fmt.Printf("stdout>%v\n", string(out)) + //defer out.Close() // 保证关闭输出流 + //for i := 1; i <= 4; i++ { + // if err := cmd.Start(); err != nil { // 运行命令 + // //log.Fatal(err) + // if i <= 3 { + // fmt.Println("exec Start error: ", err.Error(), i) + // logger.Warn("exec Start error: ", err.Error(), i) + // time.Sleep(time.Minute) + // continue + // } + // return "", 0, err + // } + //} + // + //bytes, _ := ioutil.ReadAll(out) + //for i := 1; i <= 4; i++ { + out, err := cmd.CombinedOutput() + if err != nil { + fmt.Println("CombinedOutput error, command:", cmdStr, params, "error:", err.Error(), "out:", string(out)) + logger.Warn("CombinedOutput error, command:", cmdStr, params, "error:", err.Error(), "out:", string(out)) + return string(out[:]), 0, err + } + //} + fmt.Println("exec output: ", string(out[:])) + logger.Info("exec output: ", string(out[:])) + //return string(bytes) + // get exit code + ret = cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus() + if ret != 0 { + err = errors.New(strings.TrimSpace(string(out[:]))) + logger.Warn("exec WaitStatus error: ", err.Error()) + return "", 0, err + } + // fmt.Printf("cmd>%+v \n", cmd) + + return string(out[:]), ret, err +} diff --git a/bmp-driver/main.go b/bmp-driver/main.go new file mode 100644 index 0000000..73e14f5 --- /dev/null +++ b/bmp-driver/main.go @@ -0,0 +1,112 @@ +package main + +import ( + "flag" + "fmt" + "os" + "time" + + "coding.jd.com/aidc-bmp/bmp-driver/command" + "coding.jd.com/aidc-bmp/bmp-driver/cron" + mq "coding.jd.com/aidc-bmp/bmp-driver/service/rabbit_mq" + beego "github.com/beego/beego/v2/server/web" +) + +var run_mode string + +type Config struct { + Heart string +} + +var ( + VERSION = "should be compiled with make." + BUILD_TIME = "should be compiled with make." + PERIOD = 300 +) + +const ( + defaultConfigFile = "conf/bmp-driver.ini" +) + +var configFile = flag.String("c", defaultConfigFile, "specify config file") +var versionFlag = flag.Bool("v", false, "show version") + +func main() { + + flag.Parse() + + // initial Config From file + if err := beego.LoadAppConfig("ini", *configFile); err != nil { + panic(fmt.Sprintf("LoadAppConfig Error:%s", err.Error())) + } + + if *versionFlag { + fmt.Println("commit_id:", VERSION, "build_time:", BUILD_TIME) + os.Exit(0) + } + + fmt.Println("[bmp-driver] start...") + defer fmt.Println("[bmp-driver] endding...") + + if err := mq.InitMqTemplate(); err != nil { + fmt.Println("initMqTemplate error:", err.Error()) + panic(err) + } + defer mq.DestroyTemplate() + + //go func() { + // ticker := time.NewTicker(time.Duration(300) * time.Second) + // defer ticker.Stop() + // for range ticker.C { + // command.Heartbeat() + // } + //}() + + go cron.Run() + + //从ironic-api获取任务 + var errChan chan int = make(chan int) + go doReceiveFromIronicScheduler(errChan) + for range errChan { + go doReceiveFromIronicScheduler(errChan) + time.Sleep(10 * time.Second) + } +} + +func doReceiveFromIronicScheduler(errChan chan int) { + + // defer func() { + // fmt.Println("doReceiveFromIronicScheduler ch error ......") + // errChan <- 1 + // }() + + ch, err := mq.ReceiveFromIronicScheduler() + if err != nil { + fmt.Println(time.Now().String()+"ReceiveFromIronicScheduler.ch error:", err.Error()) + errChan <- 1 + } + for v := range ch { + fmt.Println(time.Now().String()+"receive message from ironic-scheduler:", string(v.Body)) + go command.Run(v.Body) + } + //这里chan已经关闭,表示异常 + errChan <- 1 +} + +//func initMqConf() error { +// //run_mode = os.Getenv("IRONIC_DRIVER_MODE") +// // +// //if run_mode == "" { +// // run_mode = "dev" +// //} +// //fmt.Println("IRONIC_DRIVER_MODE is:", run_mode) +// //b, err := ioutil.ReadFile(fmt.Sprintf("./conf/config-%s.yml", run_mode)) +// //if err != nil { +// // return err +// //} +// // +// //if err := yaml.Unmarshal(b, &mq.C); err != nil { +// // return err +// //} +// return mq.InitMqTemplate() +//} diff --git a/bmp-driver/service/rabbit_mq/consumer.go b/bmp-driver/service/rabbit_mq/consumer.go new file mode 100644 index 0000000..eb9777d --- /dev/null +++ b/bmp-driver/service/rabbit_mq/consumer.go @@ -0,0 +1,65 @@ +package rabbit_mq + +import ( + "errors" + "fmt" + "time" + + "github.com/streadway/amqp" +) + +//ironic scheduler consumer +func ReceiveFromIronicScheduler() (<-chan amqp.Delivery, error) { + + if ironicChannel == nil { + return nil, errors.New("ironicChannel nil") + } + q, err := queueDeclare(ironicChannel, QueueName) + if err != nil { + fmt.Println(time.Now(), "queueDeclare error:", err.Error()) + return nil, err + } + if err := queueBind(ironicChannel, q.Name, RoutingKey, Exchange); err != nil { + fmt.Println(time.Now(), "queueBind error:", err.Error()) + return nil, err + } + msgChan, err := doConsume(ironicChannel, q.Name) + if err != nil { + fmt.Println(time.Now(), "doConsume error:", err.Error()) + return nil, err + } + return msgChan, nil +} + +func queueDeclare(ch *amqp.Channel, queueName string) (amqp.Queue, error) { + return ch.QueueDeclare( + queueName, // name + false, // durable + false, // delete when unused + false, // exclusive + false, // no-wait + nil, // arguments + ) +} + +func queueBind(ch *amqp.Channel, queueName, binding_key, exchange string) error { + return ch.QueueBind( + queueName, // queue name + binding_key, // binding key + exchange, // exchange + false, + nil, + ) +} + +func doConsume(ch *amqp.Channel, queueName string) (<-chan amqp.Delivery, error) { + return ch.Consume( + queueName, // queue + "", // consumer + true, // auto ack + false, // exclusive + false, // no local + false, // no wait + nil, // args + ) +} diff --git a/bmp-driver/service/rabbit_mq/producer.go b/bmp-driver/service/rabbit_mq/producer.go new file mode 100644 index 0000000..1486efc --- /dev/null +++ b/bmp-driver/service/rabbit_mq/producer.go @@ -0,0 +1,31 @@ +package rabbit_mq + +import ( + "fmt" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + "github.com/streadway/amqp" + "time" +) + +func SendToIronicScheduler(message interface{}) error { + fmt.Println(time.Now(), "处理结果回传给scheduler", message, "exchange", Exchange, "routing_key", Exchange) + return doPublish(ironicChannel, Exchange, Exchange, message) +} + +func doPublish(c *amqp.Channel, exchangeName string, routingKey string, val interface{}) (err error) { + msg, err := commonUtil.Convert2String(val) + if err != nil { + return err + } + err = c.Publish( + exchangeName, // exchange + routingKey, // routing key + false, // mandatory + false, // immediate + amqp.Publishing{ + ContentType: "application/json", + Body: []byte(msg), + }) + + return +} diff --git a/bmp-driver/service/rabbit_mq/rabbit_mq.go b/bmp-driver/service/rabbit_mq/rabbit_mq.go new file mode 100644 index 0000000..61321ed --- /dev/null +++ b/bmp-driver/service/rabbit_mq/rabbit_mq.go @@ -0,0 +1,181 @@ +package rabbit_mq + +import ( + "fmt" + "time" + + beego "github.com/beego/beego/v2/server/web" + + "github.com/streadway/amqp" +) + +const ( + TOPIC = "direct" + QueueName = "IRONIC_DRIVER" +) + +var C Conf + +var ( + Exchange string + RoutingKey string + + ironicUrl string + ironicConn *amqp.Connection + ironicChannel *amqp.Channel +) + +type Conf struct { + Heart struct { + Period int `yaml:"period"` + } `yaml:"heart"` + Mq struct { + Hosts []struct { + Host string `yaml:"host"` + Port int `yaml:"port"` + } `yaml:"hosts"` + Connection struct { + Username string `yaml:"username"` + Password string `yaml:"password"` + Vhost string `yaml:"vhost"` + Exchange string `yaml:"exchange"` + ReceiveRoutingKey string `yaml:"receive_routing_key"` + } `yaml:"connection"` + } `yaml:"mq"` + Log struct { + LogPath string `yaml:"logPath"` + } `yaml:"log"` +} + +func DestroyTemplate() { + ironicChannel.Close() + ironicConn.Close() +} + +//exchange receive_routing_key 用于ironicmq +func InitMqTemplate() (err error) { + + //ironicUrls := []string{} + //hosts := C.Mq.Hosts + //for _, v := range hosts { + // url := "amqp://" + C.Mq.Connection.Username + ":" + C.Mq.Connection.Password + "@" + v.Host + ":" + strconv.Itoa(v.Port) + "/" + C.Mq.Connection.Vhost + // ironicUrls = append(ironicUrls, url) + //} + // + //Exchange = C.Mq.Connection.Exchange + //RoutingKey = C.Mq.Connection.ReceiveRoutingKey + //for _, v := range ironicUrls { //多地址挑一个能dial通的 + host, _ := beego.AppConfig.String("bmp_mq_host") + port, _ := beego.AppConfig.String("bmp_mq_port") + user, _ := beego.AppConfig.String("bmp_mq_user") + password, _ := beego.AppConfig.String("bmp_mq_password") + vhost, _ := beego.AppConfig.String("bmp_mq_vhost") + Exchange, _ = beego.AppConfig.String("bmp_mq_exchange") + RoutingKey, _ = beego.AppConfig.String("bmp_mq_receive_routing_key") + ironicUrl = "amqp://" + user + ":" + password + "@" + host + ":" + port + "/" + vhost + fmt.Println("ironicUrl mq url:", ironicUrl, Exchange, RoutingKey) + if err := InitIronicMq(); err != nil { + fmt.Println("InitMqTemplate.InitIronicMq error:%s", err.Error()) + } + + go keepAliveConn() + return nil +} + +//初始化connection和channel +func InitIronicMq() error { + + var err error + ironicConn, err = amqp.Dial(ironicUrl) + if err != nil { + return err + } + ironicChannel, err = ironicConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(ironicChannel, Exchange, TOPIC) + if err != nil { + return err + } + return nil +} + +//连接正常,信道异常时,获取新信道 +func InitIronicMqForNewChannel() error { + + var err error + ironicChannel, err = ironicConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(ironicChannel, Exchange, TOPIC) + if err != nil { + return err + } + return nil +} + +//连接保活,断开时重连 +func keepAliveConn() error { + + var ironicCloseChan chan *amqp.Error + var ironicNotifyClose chan *amqp.Error + + for { + + if ironicConn == nil || ironicConn.IsClosed() { //连接已断开,需要重连 + fmt.Printf(time.Now().String() + "ironic conn is closed\n") + //新建连接和信道 + if err := InitIronicMq(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitIronicMq error:%s\n", err.Error()) + goto END + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitIronicMq success\n") + } + } + + ironicCloseChan = make(chan *amqp.Error, 1) + ironicNotifyClose = ironicChannel.NotifyClose(ironicCloseChan) //一旦消费者的channel有错误,产生一个amqp.Error,channel监听并捕捉到这个错误 + select { + case <-ironicNotifyClose: + fmt.Printf(time.Now().String() + "ironic channel error\n") + if ironicConn == nil || ironicConn.IsClosed() { //连接已断开,需要重连 + fmt.Printf(time.Now().String() + "ironic conn is closed\n") + time.Sleep(5 * time.Second) + //新建连接和信道 + if err := InitIronicMq(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitIronicMq error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitIronicMq success\n") + } + + } else { //连接还在,只是信道异常,需要获取新信道 + fmt.Printf(time.Now().String() + "ironic conn is open but channel is bad\n") + time.Sleep(5 * time.Second) + //获取新信道 + if err := InitIronicMqForNewChannel(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitIronicMqForNewChannel error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitIronicMqForNewChannel success\n") + } + } + + } + END: + fmt.Printf(time.Now().String() + "keepAliveConn once done\n") + time.Sleep(10 * time.Second) + } +} + +func exchangeDeclare(ch *amqp.Channel, exchange, topicType string) error { + return ch.ExchangeDeclare( + exchange, // name + topicType, // type + true, // durable + false, // auto-deleted + false, // internal + false, // no-wait + nil, // arguments + ) +} diff --git a/bmp-driver/util/array.go b/bmp-driver/util/array.go new file mode 100644 index 0000000..70009b8 --- /dev/null +++ b/bmp-driver/util/array.go @@ -0,0 +1,12 @@ +package util + +import "encoding/json" + +func ObjToJson(obj interface{}) string { + dataType, err := json.Marshal(obj) + if err != nil { + return "" + } + dataString := string(dataType) + return dataString +} diff --git a/bmp-monitor-agent/.cmd b/bmp-monitor-agent/.cmd new file mode 100644 index 0000000..ced32d3 --- /dev/null +++ b/bmp-monitor-agent/.cmd @@ -0,0 +1 @@ +rm -rf vendor diff --git a/bmp-monitor-agent/Makefile b/bmp-monitor-agent/Makefile new file mode 100644 index 0000000..b5d459b --- /dev/null +++ b/bmp-monitor-agent/Makefile @@ -0,0 +1,87 @@ +GO = go +GOCLEAN=$(GO) clean +GOBUILD = $(GO) build +GOFMT ?= gofmt "-s" +EXE ?= $(shell $(GO) env GOEXE) + +AGENT = bmp-agent +PROXY = cps-agent-proxy + +PACKAGES ?= $(shell go list ./... | grep -v vendor | grep -v tools) +GOFILES := $(shell find . -name "*.go" -type f -not -path "./vendor/*" -not -path "./proxy/*" -not -path "./tools/*" ) +PROXY_GOFILES := $(shell find . -name "*.go" -type f -not -path "./vendor/*" -not -path "./agent/*" -not -path "./tools/*" ) + +BUILD_TIME := $(shell date +%Y%m%d%H%M%S) +VERSION := $(shell git describe --tags --always) +COMMITID := $(shell git rev-parse ${VERSION} | cut -c 1-32) +# CHECKSUM := $(shell md5sum conf/agent.json.prod | cut -c 1-32) +# CHECKSUM_DEBUG := $(shell md5sum conf/agent.json.dev | cut -c 1-32) + +.PHONY: all vet fmt check clean +all: $(AGENT) $(PROXY) + +vet: + go vet $(PACKAGES) + +fmt: + $(GOFMT) -w $(GOFILES) + +clean: + @rm -f $(AGENT)$(EXE) $(PROXY)$(EXE) + +clean-cps-agent-proxy: + $(GOCLEAN) + +build-cps-agent-proxy: $(PROXY_GOFILES) + $(GOBUILD) -v -gcflags "-N -l" -o $@$(EXE) main.go + +check: + # get all go files and run go fmt on them + @diff=$$($(GOFMT) -d $(GOFILES)); \ + if [ -n "$$diff" ]; then \ + echo "Please run 'make fmt' and commit the result:"; \ + echo "$${diff}"; \ + exit 1; \ + fi; + +$(AGENT): $(GOFILES) + @go run tools/config-crypt.go -k $(COMMITID) -f conf/agent.json.dev -o conf/agent.json + @go-bindata -debug -nomemcopy -nometadata -o global/global_debug.go -pkg global -tags !release conf/ + $(GOBUILD) -v -ldflags "-X cps-agent/agent.VERSION=$(VERSION) -X cps-agent/agent.BUILD_TIME=$(BUILD_TIME) -X cps-agent/agent.COMMITID=$(COMMITID) -X cps-agent/agent.CHECKSUM=$(CHECKSUM)" -gcflags "-N -l" -o $@$(EXE) + +$(PROXY): $(PROXY_GOFILES) + $(GOBUILD) -v -gcflags "-N -l" -o $@$(EXE) cps-agent/proxy + +linux: $(GOFILES) + @mkdir -p build/linux + GOARCH=amd64 GOOS=linux $(GOBUILD) -o build/linux/${AGENT} main.go + @cp -f bmpd build/linux/ + @tar czf build/bmp-agent.tgz -C build/linux ./ + @cat bmp-agent-install.sh build/bmp-agent.tgz > build/$(AGENT).bin + # @rm -rf build/bmp-agent.tgz build/linux + @chmod +x build/$(AGENT).bin + +windows: $(GOFILES) + @mkdir -p build/windows/internal + GOARCH=amd64 GOOS=windows $(GOBUILD) -o build/windows/internal/${AGENT}.exe ./main.go + GOARCH=amd64 GOOS=windows $(GOBUILD) -o build/windows/${AGENT}-install.exe ./bmp-agent-install-windows.go + @cp -f srvany.exe build/windows/internal/ + @tar czf build/bmp-agent-windows.tgz -C build/windows ./ + @rm -rf build/windows + +windows_debug: $(GOFILES) + @mkdir -p build/windows/internal + @go run tools/config-crypt.go -k $(COMMITID) -f conf/agent.json.dev -o conf/agent.json + @go-bindata -nomemcopy -nometadata -o global/global_release.go -pkg global -tags release conf/agent.json + GOARCH=amd64 GOOS=windows $(GOBUILD) -v -tags release -ldflags "-X cps-agent/agent.VERSION=$(VERSION) -X cps-agent/agent.BUILD_TIME=$(BUILD_TIME) -X cps-agent/agent.COMMITID=$(COMMITID) -X cps-agent/agent.CHECKSUM=$(CHECKSUM_DEBUG) -w -s " -o build/windows/internal/${AGENT}.exe main.go + GOARCH=amd64 GOOS=windows $(GOBUILD) -o build/windows/${AGENT}_install.exe bmp-agent-install-windows.go + @cp -f srvany.exe build/windows/internal/ + @tar czf build/bmp-agent-windows.tgz -C build/windows ./ + @rm -rf build/windows + + + + + +release: linux + diff --git a/bmp-monitor-agent/README.zh-CN.md b/bmp-monitor-agent/README.zh-CN.md new file mode 100644 index 0000000..473671f --- /dev/null +++ b/bmp-monitor-agent/README.zh-CN.md @@ -0,0 +1,38 @@ +# 带内监控bmp-monitor-agent + +[English](README.md) | 简体中文 + +## 介绍 + +带内监控agent模块,运行在bm操作系统上,采集bm的磁盘,网络等数据,上报到bmp-monitor-proxy。 + +bmp-monitor-agent在整个bmp架构中的位置见:[bmp架构图](../bmp-scheduler/README.zh-CN.md) + + + +## 2,核心功能 + +- 设备磁盘,网络等数据的采集,并上报监控数据到bmp-monitor-proxy。 + + + +## 3,使用 + +打包linux amd x_64版本agent: +make linux +打包windows版本agent: +make windows + +下载agent: +curl -O http://..../download/agent/bmp-agent.bin + +增加操作权限: +chmod +x bmp-agent.bin + +运行: +./bmp-agent.bin + +服务名称:bmpd +查看服务状态:service bmpd status +start服务:service start bmpd +stop服务:service stop bmpd diff --git a/bmp-monitor-agent/api/api.go b/bmp-monitor-agent/api/api.go new file mode 100644 index 0000000..5548d1a --- /dev/null +++ b/bmp-monitor-agent/api/api.go @@ -0,0 +1,155 @@ +package api + +import ( + "crypto/sha512" + "fmt" + "time" + + "coding.jd.com/bmp/cps-agent/api/models" + + "github.com/astaxie/beego/logs" +) + +// PutToMonitor post MonitorPut to monitor +func PutToMonitor(url, access, token string, o models.MonitorPut) error { + if url == "" || access == "" || token == "" { + return fmt.Errorf("parameter nil") + } + + req := Post(url) + if req == nil { + return fmt.Errorf("Init HttpClient Error") + } + + if body, err := o.JSON(); err != nil { + logs.Warn("PutToMonitor JSON Error: %+v", err) + return err + } else { + req.Body(body).Header("Accept", "application/json").Header("Content-Type", "application/json; charset=utf-8") + } + + timestamp := fmt.Sprintf("%d", time.Now().Unix()) + str := access + token + timestamp + tmp := fmt.Sprintf("Sign %s %x %s", access, sha512.Sum512([]byte(str)), timestamp) + req.Header("Authorization", tmp) + + req.Debug(true) + + resp := models.MonitorPutResponse{} + if err := req.ToJSON(&resp); err != nil { + logs.Warn("PutToMonitor Response Error: %+v", err) + return err + } + + if resp.StatusCode != 200 { + return fmt.Errorf("PutToMonitor Response Error %+v", resp) + } + + return nil +} + +// Put post ProxyPut object to proxy +func Put(url string, o models.ProxyPut) error { + if url == "" { + return fmt.Errorf("url nil") + } + + req := ProxyPost(url) + if req == nil { + return fmt.Errorf("Init HttpClient Error") + } + + if body, err := o.JSON(); err != nil { + return err + } else { + req.Body(body).Header("Content-Type", "application/json") + } + + resp := &ProxyResponse{} + if err := req.ToJSON(resp); err != nil { + return err + } + + if resp.Error != nil { + return fmt.Errorf("Error: Code=%d, Message=%s", resp.Error.Code, resp.Error.Message) + } + + return nil +} + +// Heartbeat post AgentStatus object to proxy +func Heartbeat(url string, o models.AgentStatus) error { + if url == "" { + return fmt.Errorf("url nil") + } + + req := ProxyPost(url) + if req == nil { + return fmt.Errorf("Init HttpClient Error") + } + + if body, err := o.JSON(); err != nil { + return err + } else { + req.Body(body).Header("Content-Type", "application/json") + } + + resp := &ProxyResponse{} + if err := req.ToJSON(resp); err != nil { + return err + } + + if resp.Error != nil { + return fmt.Errorf("Error: Code=%d, Message=%s", resp.Error.Code, resp.Error.Message) + } + + return nil +} + +// PutToProxy post MonitorPut object to proxy, used to send to monitor through proxy +func PutToProxy(url string, o models.MonitorPut, ca, cert, key []byte) error { + if url == "" { + return fmt.Errorf("url nil") + } + + req := ProxyPost(url) + if req == nil { + return fmt.Errorf("Init HttpClient Error") + } + + if body, err := o.JSON(); err != nil { + return err + } else { + req.Body(body).Header("Content-Type", "application/json") + } + + resp := &ProxyResponse{} + if err := req.ToJSON(resp); err != nil { + return err + } + + if resp.Error != nil { + return fmt.Errorf("Error: Code=%d, Message=%s", resp.Error.Code, resp.Error.Message) + } + + return nil +} + +// GetInstanceID get InstanceID from cps-api +func GetInstanceID(url, sn string) (*models.Instance, error) { + if sn == "" || url == "" { + return nil, fmt.Errorf("url nil") + } + + req := Get(url) + if req == nil { + return nil, fmt.Errorf("Init HttpClient Error") + } + + instance := &models.Instance{} + if err := req.Param("sn", sn).ToJSON(instance); err != nil { + return nil, err + } + + return instance, nil +} diff --git a/bmp-monitor-agent/api/client.go b/bmp-monitor-agent/api/client.go new file mode 100644 index 0000000..3d987ce --- /dev/null +++ b/bmp-monitor-agent/api/client.go @@ -0,0 +1,67 @@ +package api + +import ( + "time" + + "github.com/astaxie/beego/httplib" +) + +type HttpClient struct { + *httplib.BeegoHTTPRequest +} + +func NewHttpClient(url, method string) *HttpClient { + req := httplib.NewBeegoRequest(url, method) + if req == nil { + return nil + } + + req.SetTimeout(1*time.Second, 1*time.Second) + req.SetUserAgent("JDCPS-AGENT") + req.DumpBody(true) + req.SetEnableCookie(false) + req.Retries(3) + + return &HttpClient{BeegoHTTPRequest: req} +} + +func Post(url string) *HttpClient { + return NewHttpClient(url, "POST") +} + +func Get(url string) *HttpClient { + return NewHttpClient(url, "GET") +} + +type ProxyClient struct { + *httplib.BeegoHTTPRequest +} + +func NewProxyClient(url, method string) *ProxyClient { + + defaultSetting := httplib.BeegoHTTPSettings{ + UserAgent: "JDCPS-AGENT", + ConnectTimeout: 1 * time.Second, + ReadWriteTimeout: 1 * time.Second, + Gzip: true, + DumpBody: true, + EnableCookie: false, + Retries: 3, + } + + r := httplib.NewBeegoRequest(url, method) + if r == nil { + return nil + } + r = r.Setting(defaultSetting) + + return &ProxyClient{BeegoHTTPRequest: r} +} + +func ProxyPost(url string) *ProxyClient { + return NewProxyClient(url, "POST") +} + +func ProxyGet(url string) *ProxyClient { + return NewProxyClient(url, "GET") +} diff --git a/bmp-monitor-agent/api/const.go b/bmp-monitor-agent/api/const.go new file mode 100644 index 0000000..72be2c0 --- /dev/null +++ b/bmp-monitor-agent/api/const.go @@ -0,0 +1,40 @@ +package api + +const ( + API_OK = iota + API_NO_PARAMETER + API_PARAMETER + API_NORESULT + API_REMOTE_ERROR + API_UNKNOWN = 99 + API_URL_ERROR = 403 +) + +var APICodeMap = map[int]string{ + API_OK: "Success", + API_NO_PARAMETER: "No Parameter", + API_PARAMETER: "Parameter Error", + API_NORESULT: "No Result", + API_REMOTE_ERROR: "Remote Error", + API_UNKNOWN: "Unknown", + API_URL_ERROR: "url error", +} + +type ErrorResponse struct { + // 错误码 + Code int `json:"code"` + // 错误信息 + Message string `json:"message"` + // 错误状态 + Status string `json:"status"` +} + +type ProxyResponse struct { + // 操作失败结果。成功时有此结构 + Result interface{} `json:"result,omitempty"` + // 操作失败结果。失败时有此结构 + Error *ErrorResponse `json:"error,omitempty"` + // 请求traceId + // required: true + RequestId string `json:"requestId"` +} diff --git a/bmp-monitor-agent/api/models/AgentStatus.go b/bmp-monitor-agent/api/models/AgentStatus.go new file mode 100644 index 0000000..9c1a0e0 --- /dev/null +++ b/bmp-monitor-agent/api/models/AgentStatus.go @@ -0,0 +1,40 @@ +package models + +import ( + "encoding/json" + "fmt" +) + +const ( + AGENT_UNKNOWN = iota + AGENT_OK + AGENT_STOP +) + +type AgentStatus struct { + InstanceID string `json:"instance_id"` + SN string `json:"sn"` + AgentVersion string `json:"agent_version"` + Timestamp int64 `json:"timestamp"` + Status int `json:"status"` +} + +func (o AgentStatus) JSON() ([]byte, error) { + + if json, err := json.Marshal(o); err != nil { + fmt.Println("AgentStatus to JSON error:" + err.Error()) + return nil, err + } else { + return json, nil + } +} + +func (o *AgentStatus) FromJSON(str []byte) error { + + if err := json.Unmarshal(str, o); err != nil { + fmt.Println("From JSON to AgentStatus error:" + err.Error()) + return err + } else { + return nil + } +} diff --git a/bmp-monitor-agent/api/models/Instance.go b/bmp-monitor-agent/api/models/Instance.go new file mode 100644 index 0000000..817a48f --- /dev/null +++ b/bmp-monitor-agent/api/models/Instance.go @@ -0,0 +1,64 @@ +package models + +import ( + "encoding/json" + "fmt" +) + +type Instance struct { + RequestID string `json:"requestId"` + Result struct { + Az string `json:"az,omitempty"` + Bandwidth int `json:"bandwidth,omitempty"` + Charge struct { + ChargeStatus string `json:"chargeStatus,omitempty"` + } `json:"charge,omitempty"` + DataRaidType string `json:"dataRaidType,omitempty"` + DataRaidTypeID string `json:"dataRaidTypeId,omitempty"` + Description string `json:"description,omitempty"` + DeviceType string `json:"deviceType,omitempty"` + EnableInternet string `json:"enableInternet,omitempty"` + EnableIpv6 string `json:"enableIpv6,omitempty"` + ImageType string `json:"imageType,omitempty"` + InstanceID string `json:"instanceId,omitempty"` + LineType string `json:"lineType,omitempty"` + Name string `json:"name,omitempty"` + NetworkType string `json:"networkType,omitempty"` + OsName string `json:"osName,omitempty"` + OsType string `json:"osType,omitempty"` + OsTypeID string `json:"osTypeId,omitempty"` + OsVersion string `json:"osVersion,omitempty"` + PrivateIP string `json:"privateIp,omitempty"` + PublicIP string `json:"publicIp,omitempty"` + Region string `json:"region,omitempty"` + Status string `json:"status,omitempty"` + SubnetID string `json:"subnetId,omitempty"` + SysRaidType string `json:"sysRaidType,omitempty"` + SysRaidTypeID string `json:"sysRaidTypeId,omitempty"` + } `json:"result,omitempty"` + Error struct { + Code int `json:"code,omitempty"` + Status string `json:"status,omitempty"` + Message string `json:"message,omitempty"` + } `json:"error,omitempty"` +} + +func (o Instance) JSON() ([]byte, error) { + + if json, err := json.Marshal(o); err != nil { + fmt.Println("Instance to JSON error:" + err.Error()) + return nil, err + } else { + return json, nil + } +} + +func (o *Instance) FromJSON(str []byte) error { + + if err := json.Unmarshal(str, o); err != nil { + fmt.Println("From JSON to Instance error:" + err.Error()) + return err + } else { + return nil + } +} diff --git a/bmp-monitor-agent/api/models/MonitorPut.go b/bmp-monitor-agent/api/models/MonitorPut.go new file mode 100644 index 0000000..e313cfb --- /dev/null +++ b/bmp-monitor-agent/api/models/MonitorPut.go @@ -0,0 +1,51 @@ +package models + +import ( + "encoding/json" + "fmt" + + sdkmodels "git.jd.com/jcloud-api-gateway/jcloud-sdk-go/services/monitor/models" +) + +type MonitorPut struct { + Source string `json:"source"` + Region string `json:"region,omitempty"` + InstanceId string `json:"instance_id,omitempty"` + SN string `json:"sn,omitempty"` + DataPoints []sdkmodels.DataPointX `json:"data_points"` +} + +type MonitorPutResponse struct { + RequestId string `json:"request_id,omitempty"` + Data string `json:"data,omitempty"` + Message string `json:"message,omitempty"` + StatusCode int `json:"status_code"` +} + +type MonitoCloudPutResponse struct { + RequestId string `json:"requestId,omitempty"` + Result struct { + Failed int `json:"failed,omitempty"` + Success int `json:"success,omitempty"` + } `json:"result,omitempty"` +} + +func (o MonitorPut) JSON() ([]byte, error) { + + if json, err := json.Marshal(o); err != nil { + fmt.Println("MonitorPut to JSON error:" + err.Error()) + return nil, err + } else { + return json, nil + } +} + +func (o *MonitorPut) FromJSON(str []byte) error { + + if err := json.Unmarshal(str, o); err != nil { + fmt.Println("From JSON to MonitorPut error:" + err.Error()) + return err + } else { + return nil + } +} diff --git a/bmp-monitor-agent/api/models/ProxyPut.go b/bmp-monitor-agent/api/models/ProxyPut.go new file mode 100644 index 0000000..fb92220 --- /dev/null +++ b/bmp-monitor-agent/api/models/ProxyPut.go @@ -0,0 +1,33 @@ +package models + +import ( + "encoding/json" + "fmt" + + sdkmodels "git.jd.com/jcloud-api-gateway/jcloud-sdk-go/services/monitor/models" +) + +type ProxyPut struct { + SN string `json:"sn"` + DataPoints []sdkmodels.DataPointX `json:"dataPoints"` +} + +func (o ProxyPut) JSON() ([]byte, error) { + + if json, err := json.Marshal(o); err != nil { + fmt.Println("ProxyPut to JSON error:" + err.Error()) + return nil, err + } else { + return json, nil + } +} + +func (o *ProxyPut) FromJSON(str []byte) error { + + if err := json.Unmarshal(str, o); err != nil { + fmt.Println("From JSON to ProxyPut error:" + err.Error()) + return err + } else { + return nil + } +} diff --git a/bmp-monitor-agent/api/models/const.go b/bmp-monitor-agent/api/models/const.go new file mode 100644 index 0000000..c6a1a56 --- /dev/null +++ b/bmp-monitor-agent/api/models/const.go @@ -0,0 +1,28 @@ +package models + +const ( + APP_CODE string = "jcloud" + SERVICE_CODE string = "cps" + + METRIC_CPU_UTIL string = "bmp.cpu.util" + METRIC_MEMORY_USED string = "bmp.memory.used" + METRIC_MEMORY_UTIL string = "bmp.memory.util" + METRIC_DISK_USED string = "bmp.disk.used" + METRIC_DISK_UTIL string = "bmp.disk.util" + METRIC_DISK_MOUNTPOINT_USED string = "bmp.disk.partition.used" //新增 + METRIC_DISK_MOUNTPOINT_UTIL string = "bmp.disk.partition.util" //新增 + METRIC_DISK_BYTES_READ string = "bmp.disk.bytes.read" + METRIC_DISK_BYTES_WRITE string = "bmp.disk.bytes.write" + METRIC_DISK_IOPS_READ string = "bmp.disk.counts.read" + METRIC_DISK_IOPS_WRITE string = "bmp.disk.counts.write" + METRIC_NETWORK_BYTES_IN string = "bmp.network.bytes.ingress" + METRIC_NETWORK_BYTES_OUT string = "bmp.network.bytes.egress" + METRIC_NETWORK_PACKETS_IN string = "bmp.network.packets.ingress" + METRIC_NETWORK_PACKETS_OUT string = "bmp.network.packets.egress" + METRIC_AVG_LOAD1 string = "bmp.avg.load1" + METRIC_AVG_LOAD5 string = "bmp.avg.load5" + METRIC_AVG_LOAD15 string = "bmp.avg.load15" + METRIC_TCP_CONNECT_TOTAL string = "bmp.tcp.connect.total" + METRIC_TCP_CONNECT_ESTABLISHED string = "bmp.tcp.connect.established" + METRIC_PROCESS_TOTAL string = "bmp.process.total" +) diff --git a/bmp-monitor-agent/api/models/device_tags.go b/bmp-monitor-agent/api/models/device_tags.go new file mode 100644 index 0000000..d9ba9a0 --- /dev/null +++ b/bmp-monitor-agent/api/models/device_tags.go @@ -0,0 +1,108 @@ +package models + +import ( + "encoding/json" + "fmt" + + "coding.jd.com/bmp/cps-agent/util" + + "github.com/astaxie/beego/logs" +) + +// DeviceTagsResponse api返回结构 +type DeviceTagsResponse struct { + Code int + Message string + Data interface{} +} + +var TagsMap = map[string]string{ + "disk": "CPS_TAGS_DISK", + "mountpoint": "CPS_TAGS_MOUNTPOINT", + "nic": "CPS_TAGS_NIC", +} + +// GetDeviceTagsFromRedis read CPS list from redis, according IDC ID in config file +func GetDeviceTagsFromRedis(key string, filed string) ([]string, error) { + + tags := []string{} + data, err := util.HGetObjectFromRedis(key, filed) + if err != nil { + logs.Warn("get device tags by sn error. %s", err.Error()) + return []string{}, err + } + err = json.Unmarshal([]byte(data), &tags) + if err != nil { + logs.Warn("get device tags json unmarshal error. %s", err.Error()) + return []string{}, err + } + return tags, nil +} + +// PutDeviceTags2Redis ... +func PutDeviceTags2Redis(instanceID string, reqObj ProxyPut) error { + devicestags := []string{} + mountpointTags := []string{} + nicTags := []string{} + for _, dataPointX := range reqObj.DataPoints { + if dataPointX.Metric == "cps.disk.bytes.read" { + if tagsMap, ok := (*dataPointX.Tags).(map[string]interface{}); ok { + if devicestag, ok := tagsMap["device"]; ok { + devicestags = append(devicestags, devicestag.(string)) + } + } + } else if dataPointX.Metric == "cps.disk.partition.used" { + if tagsMap, ok := (*dataPointX.Tags).(map[string]interface{}); ok { + if mountpointTag, ok := tagsMap["device"]; ok { + mountpointTags = append(mountpointTags, mountpointTag.(string)) + } + } + } else if dataPointX.Metric == "cps.network.bytes.ingress" { + if tagsMap, ok := (*dataPointX.Tags).(map[string]interface{}); ok { + if nicTag, ok := tagsMap["device"]; ok { + nicTags = append(nicTags, nicTag.(string)) + } + } + } else { + continue + } + } + + datas := map[string]interface{}{} + if len(devicestags) > 0 { + tagByte, err := json.Marshal(devicestags) + if err != nil { + logs.Warn("putDeviceTags2Redis marshal error:", err.Error()) + } else { + datas["disk"] = string(tagByte) + } + } + if len(mountpointTags) > 0 { + tagByte, err := json.Marshal(mountpointTags) + if err != nil { + logs.Warn("putMountpointTags2Redis marshal error:", err.Error()) + } else { + datas["mountpoint"] = string(tagByte) + } + } + if len(nicTags) > 0 { + tagByte, err := json.Marshal(nicTags) + if err != nil { + logs.Warn("putNicTags2Redis marshal error:", err.Error()) + } else { + datas["nic"] = string(tagByte) + } + } + + vv, _ := json.Marshal(datas) + fmt.Println("final tags is:", string(vv)) + + if len(datas) > 0 { + if err := util.HMSetObjectToRedis(instanceID, datas); err != nil { + logs.Warn("HMSetObjectToRedis error:", err.Error()) + return err + } + } + + return nil +} diff --git a/bmp-monitor-agent/api/openapi.go b/bmp-monitor-agent/api/openapi.go new file mode 100644 index 0000000..e2756ce --- /dev/null +++ b/bmp-monitor-agent/api/openapi.go @@ -0,0 +1,13 @@ +package api + +// var ( +// cpsClient *CpsClient +// ) + +func init() { + // accessKey := "35DDDCFFB86CF2D494F0F3B6B0B3EF68" + // secretKey := "93C107EF1F3A0C46C6329C04F561A29E" + // credentials := core.NewCredentials(accessKey, secretKey) + + // CpsClient = client.NewCpsClient(credentials) +} diff --git a/bmp-monitor-agent/bmp-agent-install-windows.go b/bmp-monitor-agent/bmp-agent-install-windows.go new file mode 100644 index 0000000..562bbf9 --- /dev/null +++ b/bmp-monitor-agent/bmp-agent-install-windows.go @@ -0,0 +1,210 @@ +package main + +import ( + "fmt" + "os" + "os/exec" + "os/user" + "strings" + "time" +) + +//安装目录固定为 C:\Program Files (x86)\bmp-agent 不可选 +const CPS_AGENT_DIR = `C:\Program Files (x86)\bmp-agent` + +const ( + RUNNING = "RUNNING" + STOPPING = "STOPPING" + STOPPED = "STOPPED" + START_PENDING = "START_PENDING" +) + +/* sc query 输出: +SERVICE_NAME: bmp-agent +TYPE : 10 WIN32_OWN_PROCESS +STATE : 1 STOPPED +WIN32_EXIT_CODE : 0 (0x0) +SERVICE_EXIT_CODE : 0 (0x0) +CHECKPOINT : 0x0 +WAIT_HINT : 0x0 +*/ + +type ServiceScInfo struct { + ServiceName string + Type string + State string + Win32ExitCode string + ServiceExitCode string +} + +func main() { + u, _ := user.Current() + if !strings.HasSuffix(u.Username, "Administrator") { + fmt.Fprintf(os.Stdout, "请切换至Administrator用户安装bmp-agent服务") + os.Exit(1) + } + + fmt.Fprintf(os.Stdout, "bmp-agent安装中...\n") + + v, err := getCpsAgentInfo() + if err != nil && strings.Contains(err.Error(), "status 1060") { + //未安装 + if err := installCpsAgent(); err != nil { + fmt.Fprintf(os.Stdout, "bmpAgent安装失败:"+err.Error()) + os.Exit(1) + } + if err := startCpsAgent(); err != nil { + fmt.Fprintf(os.Stdout, "bmpAgent启动失败:"+err.Error()) + os.Exit(1) + } + } else { + //已安装 + switch v.State { + case RUNNING: + if err := stopCpsAgent(); err != nil { + fmt.Fprintf(os.Stdout, "stopBmpAgent error:"+err.Error()) + os.Exit(1) + } + if err := uninstallCpsAgent(); err != nil { + fmt.Fprintf(os.Stdout, "uninstallBmpAgent error:"+err.Error()) + os.Exit(1) + } + if err := installCpsAgent(); err != nil { + fmt.Fprintf(os.Stdout, "installBmpAgent error:"+err.Error()) + os.Exit(1) + } + if err := startCpsAgent(); err != nil { + fmt.Fprintf(os.Stdout, "startBmpAgent error:"+err.Error()) + os.Exit(1) + } + case STOPPED: + if err := uninstallCpsAgent(); err != nil { + fmt.Fprintf(os.Stdout, "uninstallBmpAgent error:"+err.Error()) + os.Exit(1) + } + if err := installCpsAgent(); err != nil { + fmt.Fprintf(os.Stdout, "installBmpAgent error:"+err.Error()) + os.Exit(1) + } + if err := startCpsAgent(); err != nil { + fmt.Fprintf(os.Stdout, "startBmpAgent error:"+err.Error()) + os.Exit(1) + } + case START_PENDING: + fmt.Fprintf(os.Stdout, "bmp-agent server is starting, please wait......") + time.Sleep(60 * time.Second) + default: + stopCpsAgent() + uninstallCpsAgent() + installCpsAgent() + startCpsAgent() + } + + } + + v, err = getCpsAgentInfo() + if err != nil { + fmt.Fprintf(os.Stdout, "bmp-agent server unknown error") + os.Exit(1) + } + + var finalState = v.State + if v.State == START_PENDING { //5s检测一次,检测100s + for i := 0; i < 20; i++ { + time.Sleep(5 * time.Second) + if v, _ = getCpsAgentInfo(); v.State == RUNNING { + finalState = RUNNING + break + } + } + } + + if finalState != RUNNING { + fmt.Fprintf(os.Stdout, "bmp-agent安装失败!") + os.Exit(1) + } + + fmt.Fprintf(os.Stdout, "bmp-agent安装并启动成功\n") + time.Sleep(2 * time.Second) + os.Exit(0) + +} + +func getCpsAgentInfo() (*ServiceScInfo, error) { + output, err := execute("cmd", "/C", "sc", "query", "bmp-agent") + if err != nil { + return nil, err + } + + lines := strings.Split(output, "\n") + obj := &ServiceScInfo{} + for _, line := range lines { + tmp := strings.Split(line, ":") + if strings.Contains(tmp[0], "SERVICE_NAME") { + obj.ServiceName = strings.TrimSpace(tmp[1]) + } + if strings.Contains(tmp[0], "STATE") { + statuses := strings.Split(strings.TrimSpace(tmp[1]), " ") + obj.State = statuses[len(statuses)-1] + } + if strings.Contains(tmp[0], "ServiceExitCode") { + obj.ServiceExitCode = strings.TrimSpace(tmp[1]) + } + } + return obj, nil + +} + +func uninstallCpsAgent() error { + _, err := execute("cmd", "/C", "sc", "delete", "bmp-agent") + if err != nil { + return err + } + return nil +} + +// +func installCpsAgent() error { + //sc create bmp-agent binPath= "C:\Program Files (x86)\Windows Resource Kits\Tools\srvany.exe" start= auto + //reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\bmp-agent\Parameters /v Application /t REG_SZ /d "C:\minping\bmp-agent.exe" /f + execute("cmd", "/C", "mkdir", CPS_AGENT_DIR) + srvanyFile := fmt.Sprintf(`%s\srvany.exe`, CPS_AGENT_DIR) + cpsAgentFile := fmt.Sprintf(`%s\bmp-agent.exe`, CPS_AGENT_DIR) + execute("cmd", "/C", "del", srvanyFile) + execute("cmd", "/C", "del", cpsAgentFile) + if _, err := execute("cmd", "/C", "copy", "internal\\srvany.exe", srvanyFile); err != nil { + return err + } + if _, err := execute("cmd", "/C", "copy", "internal\\bmp-agent.exe", cpsAgentFile); err != nil { + return err + } + if _, err := execute("cmd", "/C", "sc", "create", "bmp-agent", "binPath=", fmt.Sprintf(`"%s"`, srvanyFile), "start=", "auto"); err != nil { + return err + } + if _, err := execute("cmd", "/C", "reg", "add", `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\bmp-agent\Parameters`, `/v`, `Application`, `/t`, `REG_SZ`, `/d`, cpsAgentFile, `/f`); err != nil { + return err + } + return nil +} + +func startCpsAgent() error { + _, err := execute("cmd", "/C", "sc", "start", "bmp-agent") + if err != nil { + return err + } + return nil +} + +func stopCpsAgent() error { + _, err := execute("cmd", "/C", "sc", "stop", "bmp-agent") + if err != nil { + return err + } + return nil +} + +func execute(name string, arg ...string) (string, error) { + command := exec.Command(name, arg...) + output, err := command.CombinedOutput() + return string(output), err +} diff --git a/bmp-monitor-agent/bmp-agent-install.sh b/bmp-monitor-agent/bmp-agent-install.sh new file mode 100644 index 0000000..1d5e9e1 --- /dev/null +++ b/bmp-monitor-agent/bmp-agent-install.sh @@ -0,0 +1,72 @@ +#!/bin/bash + +tmp_file=/tmp/bmp-agentd.tgz +target_dir=/opt/bmp + +if [[ $(id -u) -ne 0 ]]; then + echo "ERROR: Insufficient privilege - SUPER privileges required"; + exit 1 +fi + +sed -n -e '1,/^exit 0$/!p' $0 > ${tmp_file} 2>/dev/null + +tar xzf ${tmp_file} -C /tmp + +if [ "$1" = "-v=true" ]; then # 加上-v=true参数时,只打印版本号就退出 + res=$(/tmp/bmp-agent -v=true) + echo $res + exit 0 +fi + +# remove old version +if [ -f /etc/init.d/bmpd ]; then + if which chkconfig >/dev/null 2>&1; then + service bmpd stop + chkconfig --del bmpd + elif which update-rc.d >/dev/null 2>&1; then + service bmpd stop + update-rc.d -f bmpd remove + else + echo "ERROR: Stop BMP Agent Failed"; + fi + /bin/rm -f /etc/init.d/bmpd +fi + +if [ -d ${target_dir} ]; then + /bin/rm -rf ${target_dir} +fi + +# unarchive tar and install +# tar xzf ${tmp_file} -C /tmp +mkdir -p ${target_dir}/bin +cp -f /tmp/bmp-agent ${target_dir}/bin/ +cp -f /tmp/bmpd ${target_dir}/bin/ +ln -fs ${target_dir}/bin/bmpd /etc/init.d/bmpd + +#auto start +if which chkconfig >/dev/null 2>&1; then + chkconfig --add bmpd + chkconfig bmpd on +elif which update-rc.d >/dev/null 2>&1; then + update-rc.d bmpd defaults 90 +else + echo "ERROR: Auto Start JD CPS Agent Failed"; +fi + +# start +if which service >/dev/null 2>&1; then + service bmpd start + sleep 1 + service bmpd status +else + echo "ERROR: Start JD CPS Agent Failed"; +fi + +if [ $? -ne 0 ]; then + echo "ERROR: Start JD CPS Agent Failed"; +fi + +# clean +/bin/rm -rf /tmp/bmp-agent /tmp/bmpd ${tmp_file} + +exit 0 diff --git a/bmp-monitor-agent/bmp-agent.bin b/bmp-monitor-agent/bmp-agent.bin new file mode 100755 index 0000000..efc6e1e Binary files /dev/null and b/bmp-monitor-agent/bmp-agent.bin differ diff --git a/bmp-monitor-agent/bmp-agent.bin.arm b/bmp-monitor-agent/bmp-agent.bin.arm new file mode 100755 index 0000000..6f268cb Binary files /dev/null and b/bmp-monitor-agent/bmp-agent.bin.arm differ diff --git a/bmp-monitor-agent/bmp-monitor-agent b/bmp-monitor-agent/bmp-monitor-agent new file mode 100755 index 0000000..b5418e9 Binary files /dev/null and b/bmp-monitor-agent/bmp-monitor-agent differ diff --git a/bmp-monitor-agent/bmp_vendor/jcloud-sdk-go/go.mod b/bmp-monitor-agent/bmp_vendor/jcloud-sdk-go/go.mod new file mode 100644 index 0000000..a888c72 --- /dev/null +++ b/bmp-monitor-agent/bmp_vendor/jcloud-sdk-go/go.mod @@ -0,0 +1,3 @@ +module git.jd.com/jcloud-api-gateway/jcloud-sdk-go + +go 1.17 diff --git a/bmp-monitor-agent/bmp_vendor/jcloud-sdk-go/services/monitor/models/DataPointX.go b/bmp-monitor-agent/bmp_vendor/jcloud-sdk-go/services/monitor/models/DataPointX.go new file mode 100644 index 0000000..9ac8867 --- /dev/null +++ b/bmp-monitor-agent/bmp_vendor/jcloud-sdk-go/services/monitor/models/DataPointX.go @@ -0,0 +1,33 @@ +// Copyright 2018 JDCLOUD.COM +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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. +// +// NOTE: This class is auto generated by the jdcloud code generator program. + +package models + + +type DataPointX struct { + + /* 监控指标名称,长度不超过255字节,只允许英文、数字、下划线_、点., [0-9][a-z] [A-Z] [. _ ], 其它会返回err */ + Metric string `json:"metric"` + + /* 数据维度,数据类型为map类型,最多五个标签,尽量不传或少传。总长度不大于255字节,只允许英文、数字、下划线_、点., [0-9][a-z] [A-Z] [. _ ], 其它会返回err (Optional) */ + Tags *interface{} `json:"tags"` + + /* 秒级时间戳,早于当前时间30天的不能写入;建议的上报时间戳:上报时间间隔的整数倍,如上报间隔为5s,则建议上报的时间戳为 timestamp = current timestamp - (current timestamp % time interval) = 1487647187 - (1487647187 % 5) = 1487647187 -2 = 1487647185 */ + Timestamp int64 `json:"timestamp"` + + /* 监控的值。number or string。最大值为long.MAX_VALUE=9223372036854775807=263-1。累计类型的指标,累计到最大值后需要翻转为0,重新开始计数。翻转后不影响速率的计算。 */ + Value interface{} `json:"value"` +} diff --git a/bmp-monitor-agent/bmpd b/bmp-monitor-agent/bmpd new file mode 100755 index 0000000..5c60bb3 --- /dev/null +++ b/bmp-monitor-agent/bmpd @@ -0,0 +1,128 @@ +#!/bin/bash + +### BEGIN INIT INFO +# Provides: bmp-agentd +# RequiRED-Start: $local_fs +# RequiRED-Stop: $local_fs +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# chkconfig: 2345 95 05 +# Description: startup script for bmp-agentd +### END INIT INFO + +set -o nounset + +unset IFS +unset LD_PRELOAD +unset LD_LIBRARY_PATH + +readonly RED="\\e[31m" +readonly GREEN="\\e[32m" +readonly YELLOW="\\e[33m" +readonly BLACK="\\e[0m" +readonly POS="\\e[60G" + +readonly bmp_AGENT_DIR=$(cd $(dirname $(readlink -e $0))/.. && pwd) +readonly bmp_AGENT_SBIN_DIR=$bmp_AGENT_DIR/bin +readonly bmp_AGENT="$bmp_AGENT_SBIN_DIR/bmp-agent" +readonly STOP_TIMEOUT=30 + +function usage() +{ + echo "usage: bmp-agentd command" + echo "command is show as follows:" + echo " start start bmp_agentd" + echo " stop stop bmp_agentd" + echo " restart restart bmp_agentd" + echo " status check bmp_agentd status whether it is running" + echo "AUTHORS: Zhou Guiqing" +} + +ok_msg(){ + echo -e "${1}${POS}${BLACK}[${GREEN} OK ${BLACK}]" +} + +failed_msg(){ + echo -e "${1}${POS}${BLACK}[${RED}FAILED${BLACK}]" + exit -1 +} + +function get_pid() +{ + echo $(ps -aux | grep "bmp-agent$" | awk '{print $2}') +} + +# grep -P 1 -f 经常获取不到pid,不知道为啥 +# function get_pid() +# { +# local ppid=1 +# local pid_agent=$(pgrep -P 1 -f "^${bmp_AGENT}$") + +# echo "$pid_agent" +# } + +function check() +{ + local all_pids=$(get_pid) + [ -n "${all_pids}" ] && return 0 + return 1 +} + +function start() +{ + check && { + ok_msg "start" + return 0 + } + + setsid $bmp_AGENT /dev/null 2>&1 & + sleep 1 + check || failed_msg "start" + ok_msg "start" +} + +function signal() +{ + local SIGNAL=$1 + local i=0 + while [ "${i}" -le "${STOP_TIMEOUT}" ]; do + local all_pids=$(get_pid) + [ -z "${all_pids}" ] && return 0 + kill $SIGNAL ${all_pids} + sleep 1 + i="`expr "${i}" + 1`" + done + return 1 +} + +function stop() +{ + signal -SIGUSR1 || signal -KILL || failed_msg "stop" + ok_msg "stop" +} + +function status() +{ + check || failed_msg 'not running' + ok_msg 'running' +} + +case "$1" in + start) + start + ;; + stop) + stop + ;; + restart) + stop + start + ;; + status) + status + ;; + *) + usage + ;; +esac +exit $? diff --git a/bmp-monitor-agent/build/.cmd b/bmp-monitor-agent/build/.cmd new file mode 100644 index 0000000..0549e86 --- /dev/null +++ b/bmp-monitor-agent/build/.cmd @@ -0,0 +1 @@ +rm root@10.208.14.113 diff --git a/bmp-monitor-agent/build/bmp-agent-windows.tgz b/bmp-monitor-agent/build/bmp-agent-windows.tgz new file mode 100644 index 0000000..ce15922 Binary files /dev/null and b/bmp-monitor-agent/build/bmp-agent-windows.tgz differ diff --git a/bmp-monitor-agent/build/bmp-agent.bin b/bmp-monitor-agent/build/bmp-agent.bin new file mode 100755 index 0000000..efc6e1e Binary files /dev/null and b/bmp-monitor-agent/build/bmp-agent.bin differ diff --git a/bmp-monitor-agent/build/bmp-agent.tgz b/bmp-monitor-agent/build/bmp-agent.tgz new file mode 100644 index 0000000..4e04991 Binary files /dev/null and b/bmp-monitor-agent/build/bmp-agent.tgz differ diff --git a/bmp-monitor-agent/build/jdcps-agent.bin b/bmp-monitor-agent/build/jdcps-agent.bin new file mode 100755 index 0000000..3435066 Binary files /dev/null and b/bmp-monitor-agent/build/jdcps-agent.bin differ diff --git a/bmp-monitor-agent/build/jdcps-agent.tgz b/bmp-monitor-agent/build/jdcps-agent.tgz new file mode 100644 index 0000000..038a769 Binary files /dev/null and b/bmp-monitor-agent/build/jdcps-agent.tgz differ diff --git a/bmp-monitor-agent/build/linux/bmp-agent b/bmp-monitor-agent/build/linux/bmp-agent new file mode 100755 index 0000000..9af4217 Binary files /dev/null and b/bmp-monitor-agent/build/linux/bmp-agent differ diff --git a/bmp-monitor-agent/build/linux/bmpd b/bmp-monitor-agent/build/linux/bmpd new file mode 100755 index 0000000..5c60bb3 --- /dev/null +++ b/bmp-monitor-agent/build/linux/bmpd @@ -0,0 +1,128 @@ +#!/bin/bash + +### BEGIN INIT INFO +# Provides: bmp-agentd +# RequiRED-Start: $local_fs +# RequiRED-Stop: $local_fs +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# chkconfig: 2345 95 05 +# Description: startup script for bmp-agentd +### END INIT INFO + +set -o nounset + +unset IFS +unset LD_PRELOAD +unset LD_LIBRARY_PATH + +readonly RED="\\e[31m" +readonly GREEN="\\e[32m" +readonly YELLOW="\\e[33m" +readonly BLACK="\\e[0m" +readonly POS="\\e[60G" + +readonly bmp_AGENT_DIR=$(cd $(dirname $(readlink -e $0))/.. && pwd) +readonly bmp_AGENT_SBIN_DIR=$bmp_AGENT_DIR/bin +readonly bmp_AGENT="$bmp_AGENT_SBIN_DIR/bmp-agent" +readonly STOP_TIMEOUT=30 + +function usage() +{ + echo "usage: bmp-agentd command" + echo "command is show as follows:" + echo " start start bmp_agentd" + echo " stop stop bmp_agentd" + echo " restart restart bmp_agentd" + echo " status check bmp_agentd status whether it is running" + echo "AUTHORS: Zhou Guiqing" +} + +ok_msg(){ + echo -e "${1}${POS}${BLACK}[${GREEN} OK ${BLACK}]" +} + +failed_msg(){ + echo -e "${1}${POS}${BLACK}[${RED}FAILED${BLACK}]" + exit -1 +} + +function get_pid() +{ + echo $(ps -aux | grep "bmp-agent$" | awk '{print $2}') +} + +# grep -P 1 -f 经常获取不到pid,不知道为啥 +# function get_pid() +# { +# local ppid=1 +# local pid_agent=$(pgrep -P 1 -f "^${bmp_AGENT}$") + +# echo "$pid_agent" +# } + +function check() +{ + local all_pids=$(get_pid) + [ -n "${all_pids}" ] && return 0 + return 1 +} + +function start() +{ + check && { + ok_msg "start" + return 0 + } + + setsid $bmp_AGENT /dev/null 2>&1 & + sleep 1 + check || failed_msg "start" + ok_msg "start" +} + +function signal() +{ + local SIGNAL=$1 + local i=0 + while [ "${i}" -le "${STOP_TIMEOUT}" ]; do + local all_pids=$(get_pid) + [ -z "${all_pids}" ] && return 0 + kill $SIGNAL ${all_pids} + sleep 1 + i="`expr "${i}" + 1`" + done + return 1 +} + +function stop() +{ + signal -SIGUSR1 || signal -KILL || failed_msg "stop" + ok_msg "stop" +} + +function status() +{ + check || failed_msg 'not running' + ok_msg 'running' +} + +case "$1" in + start) + start + ;; + stop) + stop + ;; + restart) + stop + start + ;; + status) + status + ;; + *) + usage + ;; +esac +exit $? diff --git a/bmp-monitor-agent/build/linux/jdcps-agent b/bmp-monitor-agent/build/linux/jdcps-agent new file mode 100755 index 0000000..4a9be8c Binary files /dev/null and b/bmp-monitor-agent/build/linux/jdcps-agent differ diff --git a/bmp-monitor-agent/build/linux/jdcpsd b/bmp-monitor-agent/build/linux/jdcpsd new file mode 100755 index 0000000..d97a4ac --- /dev/null +++ b/bmp-monitor-agent/build/linux/jdcpsd @@ -0,0 +1,128 @@ +#!/bin/bash + +### BEGIN INIT INFO +# Provides: jdcps-agentd +# RequiRED-Start: $local_fs +# RequiRED-Stop: $local_fs +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# chkconfig: 2345 95 05 +# Description: startup script for jdcps-agentd +### END INIT INFO + +set -o nounset + +unset IFS +unset LD_PRELOAD +unset LD_LIBRARY_PATH + +readonly RED="\\e[31m" +readonly GREEN="\\e[32m" +readonly YELLOW="\\e[33m" +readonly BLACK="\\e[0m" +readonly POS="\\e[60G" + +readonly JDCPS_AGENT_DIR=$(cd $(dirname $(readlink -e $0))/.. && pwd) +readonly JDCPS_AGENT_SBIN_DIR=$JDCPS_AGENT_DIR/bin +readonly JDCPS_AGENT="$JDCPS_AGENT_SBIN_DIR/jdcps-agent" +readonly STOP_TIMEOUT=30 + +function usage() +{ + echo "usage: jdcps-agentd command" + echo "command is show as follows:" + echo " start start jdcps_agentd" + echo " stop stop jdcps_agentd" + echo " restart restart jdcps_agentd" + echo " status check jdcps_agentd status whether it is running" + echo "AUTHORS: Zhou Guiqing" +} + +ok_msg(){ + echo -e "${1}${POS}${BLACK}[${GREEN} OK ${BLACK}]" +} + +failed_msg(){ + echo -e "${1}${POS}${BLACK}[${RED}FAILED${BLACK}]" + exit -1 +} + +function get_pid() +{ + echo $(ps -aux | grep "jdcps-agent$" | awk '{print $2}') +} + +# grep -P 1 -f 经常获取不到pid,不知道为啥 +# function get_pid() +# { +# local ppid=1 +# local pid_agent=$(pgrep -P 1 -f "^${JDCPS_AGENT}$") + +# echo "$pid_agent" +# } + +function check() +{ + local all_pids=$(get_pid) + [ -n "${all_pids}" ] && return 0 + return 1 +} + +function start() +{ + check && { + ok_msg "start" + return 0 + } + + setsid $JDCPS_AGENT /dev/null 2>&1 & + sleep 1 + check || failed_msg "start" + ok_msg "start" +} + +function signal() +{ + local SIGNAL=$1 + local i=0 + while [ "${i}" -le "${STOP_TIMEOUT}" ]; do + local all_pids=$(get_pid) + [ -z "${all_pids}" ] && return 0 + kill $SIGNAL ${all_pids} + sleep 1 + i="`expr "${i}" + 1`" + done + return 1 +} + +function stop() +{ + signal -SIGUSR1 || signal -KILL || failed_msg "stop" + ok_msg "stop" +} + +function status() +{ + check || failed_msg 'not running' + ok_msg 'running' +} + +case "$1" in + start) + start + ;; + stop) + stop + ;; + restart) + stop + start + ;; + status) + status + ;; + *) + usage + ;; +esac +exit $? diff --git a/bmp-monitor-agent/collector/collector.go b/bmp-monitor-agent/collector/collector.go new file mode 100644 index 0000000..04db8ef --- /dev/null +++ b/bmp-monitor-agent/collector/collector.go @@ -0,0 +1,65 @@ +package collector + +import ( + "time" + + "coding.jd.com/bmp/cps-agent/global" + + sdkmodels "git.jd.com/jcloud-api-gateway/jcloud-sdk-go/services/monitor/models" + + "github.com/astaxie/beego/logs" +) + +var ( + Collectors map[string]Collector +) + +func init() { + Collectors = make(map[string]Collector) +} + +type Collector interface { + Collect() []sdkmodels.DataPointX +} + +func Register(name string, c Collector) { + Collectors[name] = c +} + +func Collect(timeout time.Duration) []sdkmodels.DataPointX { + var dps []sdkmodels.DataPointX + + done := make(chan []sdkmodels.DataPointX) + + for k, v := range Collectors { + + go func(name string, c Collector) { + logs.Debug("collector %s Start", name) + done <- c.Collect() + }(k, v) + + select { + case <-time.After(timeout): + logs.Warn("collector %s Timeout", k) + case dp := <-done: + if len(dp) > 0 { + dps = append(dps, dp...) + } + logs.Debug("collector %s Finish", k) + } + + } + + // align timestamp + curr := time.Now().Unix() + t := curr - (curr % global.DefaultInt64(global.AgentConfig.Monitor.TimestampAlign, 60)) + + for i := range dps { + dps[i].Timestamp = t + // if dps[i].Tags == nil { + // dps[i].Tags = &map[string]interface{}{} + // } + } + + return dps +} diff --git a/bmp-monitor-agent/collector/cpu.go b/bmp-monitor-agent/collector/cpu.go new file mode 100644 index 0000000..8eea92f --- /dev/null +++ b/bmp-monitor-agent/collector/cpu.go @@ -0,0 +1,42 @@ +package collector + +import ( + "coding.jd.com/bmp/cps-agent/api/models" + "coding.jd.com/bmp/cps-agent/util" + + sdkmodels "git.jd.com/jcloud-api-gateway/jcloud-sdk-go/services/monitor/models" + + "github.com/astaxie/beego/logs" + "github.com/shirou/gopsutil/cpu" +) + +func init() { + Register("cpu", &CPUCollector{}) +} + +type CPUCollector struct { +} + +func (c *CPUCollector) Collect() []sdkmodels.DataPointX { + var dps []sdkmodels.DataPointX + + cpuUtil, err := cpu.Percent(0, false) + if err != nil { + logs.Warn("Collect CPU Error: %s", err.Error()) + return dps + } + + var cpuTags interface{} = map[string]interface{}{} + for _, c := range cpuUtil { + dps = append(dps, sdkmodels.DataPointX{ + Metric: models.METRIC_CPU_UTIL, + // ValueType: "float", + Value: util.FloatRound(c, 2), + Tags: &cpuTags, + // Tags: map[string]interface{}{"core": fmt.Sprintf("%d", i)}, + }) + + } + + return dps +} diff --git a/bmp-monitor-agent/collector/disk.go b/bmp-monitor-agent/collector/disk.go new file mode 100644 index 0000000..9edce07 --- /dev/null +++ b/bmp-monitor-agent/collector/disk.go @@ -0,0 +1,8 @@ +package collector + +func init() { + Register("disk", &DiskCollector{}) +} + +type DiskCollector struct { +} diff --git a/bmp-monitor-agent/collector/disk_darwin.go b/bmp-monitor-agent/collector/disk_darwin.go new file mode 100644 index 0000000..ca88274 --- /dev/null +++ b/bmp-monitor-agent/collector/disk_darwin.go @@ -0,0 +1,83 @@ +//go:build darwin +// +build darwin + +package collector + +import ( + "coding.jd.com/bmp/cps-agent/api/models" + "coding.jd.com/bmp/cps-agent/util" + sdkmodels "git.jd.com/jcloud-api-gateway/jcloud-sdk-go/services/monitor/models" + + "github.com/astaxie/beego/logs" + "github.com/shirou/gopsutil/disk" +) + +func (c *DiskCollector) Collect() []sdkmodels.DataPointX { + var dps []sdkmodels.DataPointX + + dp, err := disk.Partitions(true) + if err != nil { + logs.Warn("Collect Disk Error: %s", err.Error()) + return dps + } + + for _, tmp := range dp { + du, duErr := disk.Usage(tmp.Mountpoint) + if duErr != nil { + logs.Warn("Collect Disk Usage Error: %s", err.Error()) + continue + } + + dio, dioErr := disk.IOCounters(tmp.Device) + if dioErr != nil { + logs.Warn("Collect Disk IO Error: %s", err.Error()) + continue + } + + /* + METRIC_DISK_USED + METRIC_DISK_UTIL + METRIC_DISK_BYTES_READ + METRIC_DISK_BYTES_WRITE + METRIC_DISK_IOPS_READ + METRIC_DISK_IOPS_WRITE + */ + var diskTags interface{} + diskTags = map[string]interface{}{"device": dev} + dps = append(dps, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_USED, + Value: du.Used, + Tags: &diskTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_UTIL, + Value: util.FloatRound(du.UsedPercent, 2), + Tags: &diskTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_BYTES_READ, + Value: dio[tmp.Device].ReadBytes, + Tags: &diskTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_BYTES_WRITE, + Value: dio[tmp.Device].WriteBytes, + Tags: &diskTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_IOPS_READ, + Value: dio[tmp.Device].ReadCount, + Tags: &diskTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_IOPS_WRITE, + Value: dio[tmp.Device].WriteCount, + Tags: &diskTags, + }, + ) + + } + + return dps +} diff --git a/bmp-monitor-agent/collector/disk_linux.go b/bmp-monitor-agent/collector/disk_linux.go new file mode 100644 index 0000000..9025dc6 --- /dev/null +++ b/bmp-monitor-agent/collector/disk_linux.go @@ -0,0 +1,233 @@ +//go:build linux +// +build linux + +package collector + +import ( + "os/exec" + "path/filepath" + "strings" + + "coding.jd.com/bmp/cps-agent/api/models" + "coding.jd.com/bmp/cps-agent/util" + + sdkmodels "git.jd.com/jcloud-api-gateway/jcloud-sdk-go/services/monitor/models" + + "github.com/astaxie/beego/logs" + "github.com/shirou/gopsutil/disk" +) + +var DISK_DEVICE_IGNORE = map[string]struct{}{ + "cgroup": {}, + "debugfs": {}, + "devpts": {}, + "devtmpfs": {}, + "rpc_pipefs": {}, + "rootfs": {}, + "overlay": {}, + "tmpfs": {}, + "none": {}, + "nodev": {}, + "proc": {}, + "hugetlbfs": {}, + "mqueue": {}, +} + +var FSFILE_PREFIX_IGNORE = []string{ + "/sys", + "/net", + "/misc", + "/proc", + "/lib", + "/boot", +} + +type DiskStat struct { + Device string + Used uint64 + Usage float64 + ReadBytes uint64 + WriteBytes uint64 + ReadCounts uint64 + WriteCounts uint64 +} + +func (c *DiskCollector) Collect() []sdkmodels.DataPointX { + var dps []sdkmodels.DataPointX + + // 获取硬盘 + disks, diskErr := getDisks() + if diskErr != nil { + logs.Warn("Collect Disk Error: %s", diskErr.Error()) + return dps + } + + // 获取分区 + var partitions []disk.PartitionStat + dp, errp := disk.Partitions(false) + if errp != nil { + logs.Warn("Collect Partition Error: %s", errp.Error()) + return dps + } + + for _, p := range dp { + if _, exist := DISK_DEVICE_IGNORE[p.Device]; exist { + continue + } + + if strings.HasPrefix(p.Fstype, "fuse") { + continue + } + + if ignoreFsFile(p.Mountpoint) { + continue + } + + // Fix Bug JCYFBUG-1467, mountinfo duplicate, recalc disk used bytes + isDuplicated := false + for _, p2 := range partitions { + if strings.EqualFold(p.Device, p2.Device) { + isDuplicated = true + } + } + if isDuplicated { + continue + } + // END fix Bug JCYFBUG-1467 + + partitions = append(partitions, p) + } + + for _, d := range disks { + dio, dioErr := disk.IOCounters(d.Device) + if dioErr != nil { + logs.Warn("Collect Disk IO Error: %s", dioErr.Error()) + continue + } + + d.ReadBytes = dio[filepath.Base(d.Device)].ReadBytes + d.WriteBytes = dio[filepath.Base(d.Device)].WriteBytes + d.ReadCounts = dio[filepath.Base(d.Device)].ReadCount + d.WriteCounts = dio[filepath.Base(d.Device)].WriteCount + + total := uint64(0) + used := uint64(0) + for _, p := range partitions { + + // /dev/sda1 has /dev/sda prefix + if strings.HasPrefix(p.Device, d.Device) { + + du, duErr := disk.Usage(p.Mountpoint) + if duErr != nil { + logs.Warn("Collect Disk Usage Error: %s", duErr.Error()) + continue + } + + if du.Total != 0 { + var diskTags interface{} = map[string]interface{}{"device": p.Mountpoint} + dps = append(dps, + sdkmodels.DataPointX{ //新增 + Metric: models.METRIC_DISK_MOUNTPOINT_USED, + Value: du.Used, + Tags: &diskTags, + }, + sdkmodels.DataPointX{ //新增 + Metric: models.METRIC_DISK_MOUNTPOINT_UTIL, + Value: util.FloatRound(float64(du.Used)/float64(du.Total), 2) * 100, + Tags: &diskTags, + }, + ) + } + total += du.Total + used += du.Used + } + } + d.Used = used + if total != 0 { + d.Usage = float64(used) / float64(total) + } + + /* + METRIC_DISK_USED + METRIC_DISK_UTIL + METRIC_DISK_BYTES_READ + METRIC_DISK_BYTES_WRITE + METRIC_DISK_IOPS_READ + METRIC_DISK_IOPS_WRITE + */ + dev := filepath.Base(d.Device) + var diskTags interface{} = map[string]interface{}{"device": dev} + dps = append(dps, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_USED, + Value: d.Used, + Tags: &diskTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_UTIL, + Value: util.FloatRound(d.Usage, 2) * 100, + Tags: &diskTags, + }, + + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_BYTES_READ, + Value: d.ReadBytes, + Tags: &diskTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_BYTES_WRITE, + Value: d.WriteBytes, + Tags: &diskTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_IOPS_READ, + Value: d.ReadCounts, + Tags: &diskTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_IOPS_WRITE, + Value: d.WriteCounts, + Tags: &diskTags, + }, + ) + } + + return dps +} + +func ignoreFsFile(fs_file string) bool { + for _, prefix := range FSFILE_PREFIX_IGNORE { + if strings.HasPrefix(fs_file, prefix) { + return true + } + } + + return false +} + +func getDisks() ([]DiskStat, error) { + ret := []DiskStat{} + + lsblk, err := exec.LookPath("lsblk") + if err != nil { + return ret, err + } + cmd := exec.Command(lsblk, "-bn") + + out, err := cmd.Output() + if err != nil { + return ret, err + } + + for _, line := range strings.Split(string(out), "\n") { + fields := strings.Fields(line) + if len(fields) < 6 { + continue + } + if strings.EqualFold(strings.TrimSpace(fields[5]), "disk") { + ret = append(ret, DiskStat{Device: "/dev/" + fields[0]}) + } + } + + return ret, nil +} diff --git a/bmp-monitor-agent/collector/disk_windows.go b/bmp-monitor-agent/collector/disk_windows.go new file mode 100644 index 0000000..8083757 --- /dev/null +++ b/bmp-monitor-agent/collector/disk_windows.go @@ -0,0 +1,95 @@ +//go:build windows +// +build windows + +package collector + +import ( + "coding.jd.com/bmp/cps-agent/api/models" + "coding.jd.com/bmp/cps-agent/util" + + sdkmodels "git.jd.com/jcloud-api-gateway/jcloud-sdk-go/services/monitor/models" + + "github.com/astaxie/beego/logs" + "github.com/shirou/gopsutil/disk" +) + +// TODO: IOCounters需要修改gopsutil源码 +func (c *DiskCollector) Collect() []sdkmodels.DataPointX { + var dps []sdkmodels.DataPointX + + dp, err := disk.Partitions(true) + if err != nil { + logs.Warn("Collect Disk Error: %s", err.Error()) + return dps + } + + for _, tmp := range dp { + du, duErr := disk.Usage(tmp.Mountpoint) + if duErr != nil { + logs.Warn("Collect Disk Usage Error: %s", duErr.Error()) + continue + } + + dio, dioErr := disk.IOCounters(tmp.Device) + if dioErr != nil { + logs.Warn("Collect Disk IO Error: %s", dioErr.Error()) + continue + } + + /* + METRIC_DISK_USED + METRIC_DISK_UTIL + METRIC_DISK_BYTES_READ + METRIC_DISK_BYTES_WRITE + METRIC_DISK_IOPS_READ + METRIC_DISK_IOPS_WRITE + */ + var diskTags interface{} + diskTags = map[string]interface{}{"device": tmp.Mountpoint} + dps = append(dps, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_USED, + Value: du.Used, + Tags: &diskTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_UTIL, + Value: util.FloatRound(du.UsedPercent, 2), + Tags: &diskTags, + }, + sdkmodels.DataPointX{ //新增 + Metric: models.METRIC_DISK_MOUNTPOINT_USED, + Value: du.Used, + Tags: &diskTags, + }, + sdkmodels.DataPointX{ //新增 + Metric: models.METRIC_DISK_MOUNTPOINT_UTIL, + Value: util.FloatRound(du.UsedPercent, 2), + Tags: &diskTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_BYTES_READ, + Value: dio[tmp.Device].ReadBytes, + Tags: &diskTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_BYTES_WRITE, + Value: dio[tmp.Device].WriteBytes, + Tags: &diskTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_IOPS_READ, + Value: dio[tmp.Device].ReadCount, + Tags: &diskTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_DISK_IOPS_WRITE, + Value: dio[tmp.Device].WriteCount, + Tags: &diskTags, + }, + ) + + } + + return dps +} diff --git a/bmp-monitor-agent/collector/load.go b/bmp-monitor-agent/collector/load.go new file mode 100644 index 0000000..a8dbc8a --- /dev/null +++ b/bmp-monitor-agent/collector/load.go @@ -0,0 +1,61 @@ +package collector + +import ( + "runtime" + + "coding.jd.com/bmp/cps-agent/api/models" + "coding.jd.com/bmp/cps-agent/util" + + sdkmodels "git.jd.com/jcloud-api-gateway/jcloud-sdk-go/services/monitor/models" + + "github.com/astaxie/beego/logs" + "github.com/shirou/gopsutil/load" +) + +func init() { + Register("load", &LoadCollector{}) +} + +type LoadCollector struct { +} + +func (c *LoadCollector) Collect() []sdkmodels.DataPointX { + + var dps []sdkmodels.DataPointX + var loadTags interface{} = map[string]interface{}{} + if runtime.GOOS == "windows" { + return dps + } + + if v, err := load.Avg(); err != nil { + logs.Warn("Collect LOAD Error: %s", err.Error()) + return dps + } else { + /* + METRIC_AVG_LOAD1 + METRIC_AVG_LOAD5 string = "cps.avg.load5" + METRIC_AVG_LOAD15 string = "cps.avg.load15" + */ + + dps = append(dps, + sdkmodels.DataPointX{ + Metric: models.METRIC_AVG_LOAD1, + Value: util.FloatRound(v.Load1, 2), + Tags: &loadTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_AVG_LOAD5, + Value: util.FloatRound(v.Load5, 2), + Tags: &loadTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_AVG_LOAD15, + Value: util.FloatRound(v.Load15, 2), + Tags: &loadTags, + }, + ) + } + + return dps + +} diff --git a/bmp-monitor-agent/collector/mem.go b/bmp-monitor-agent/collector/mem.go new file mode 100644 index 0000000..71e938a --- /dev/null +++ b/bmp-monitor-agent/collector/mem.go @@ -0,0 +1,49 @@ +package collector + +import ( + "coding.jd.com/bmp/cps-agent/api/models" + "coding.jd.com/bmp/cps-agent/util" + + sdkmodels "git.jd.com/jcloud-api-gateway/jcloud-sdk-go/services/monitor/models" + + "github.com/astaxie/beego/logs" + "github.com/shirou/gopsutil/mem" +) + +func init() { + Register("mem", &MemCollector{}) +} + +type MemCollector struct { +} + +func (c *MemCollector) Collect() []sdkmodels.DataPointX { + + var dps []sdkmodels.DataPointX + var memTags interface{} = map[string]interface{}{} + if v, err := mem.VirtualMemory(); err != nil { + logs.Warn("Collect MEM Error: %s", err.Error()) + return dps + } else { + /* + METRIC_MEMORY_USED string = "cps.memory.used" + METRIC_MEMORY_UTIL string = "cps.memory.usage" + */ + + dps = append(dps, + sdkmodels.DataPointX{ + Metric: models.METRIC_MEMORY_USED, + Value: v.Used, + Tags: &memTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_MEMORY_UTIL, + Value: util.FloatRound(v.UsedPercent, 2), + Tags: &memTags, + }, + ) + } + + return dps + +} diff --git a/bmp-monitor-agent/collector/net.go b/bmp-monitor-agent/collector/net.go new file mode 100644 index 0000000..f746afa --- /dev/null +++ b/bmp-monitor-agent/collector/net.go @@ -0,0 +1,144 @@ +package collector + +import ( + "coding.jd.com/bmp/cps-agent/api/models" + + sdkmodels "git.jd.com/jcloud-api-gateway/jcloud-sdk-go/services/monitor/models" + "github.com/astaxie/beego/logs" + "github.com/shirou/gopsutil/net" +) + +var ( + NETWORK_FLAGS_IGNORE = map[string]struct{}{ + "loopback": {}, + } + NETWORK_FLAGS_INCLUDE = map[string]struct{}{ + "up": {}, + } +) + +func init() { + Register("network", &NetCollector{}) +} + +type NetCollector struct { +} + +func (c *NetCollector) Collect() []sdkmodels.DataPointX { + var dps []sdkmodels.DataPointX + + retNI := map[string]net.InterfaceStat{} + nv, err := net.Interfaces() + if err != nil { + logs.Warn("Collect NET Error: %s", err.Error()) + return dps + } + + for _, tmp := range nv { + if tmp.HardwareAddr == "" { + continue + } + + if ignoreNetworkInterface(tmp.Flags) { + continue + } + + retNI[tmp.Name] = tmp + + } + + nio, errIO := net.IOCounters(true) + if errIO != nil { + logs.Warn("Collect NETIO Error: %s", errIO.Error()) + return dps + } + + var allNio = net.IOCountersStat{ + Name: "all", + } + for _, v := range nio { + if _, exist := retNI[v.Name]; exist { + allNio.BytesSent += v.BytesSent + allNio.BytesRecv += v.BytesRecv + allNio.PacketsSent += v.PacketsSent + allNio.PacketsRecv += v.PacketsRecv + } + } + /* + METRIC_NETWORK_BYTES_IN string = "cps.network.bytes.incoming" + METRIC_NETWORK_BYTES_OUT string = "cps.network.bytes.outgoing" + METRIC_NETWORK_PACKETS_IN string = "cps.network.packets.incoming" + METRIC_NETWORK_PACKETS_OUT string = "cps.network.packets.outgoing" + */ + //汇总 + var allnetTags interface{} = map[string]interface{}{} + dps = append(dps, + sdkmodels.DataPointX{ + Metric: models.METRIC_NETWORK_BYTES_IN, + Value: allNio.BytesRecv, + Tags: &allnetTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_NETWORK_BYTES_OUT, + Value: allNio.BytesSent, + Tags: &allnetTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_NETWORK_PACKETS_IN, + Value: allNio.PacketsRecv, + Tags: &allnetTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_NETWORK_PACKETS_OUT, + Value: allNio.PacketsSent, + Tags: &allnetTags, + }, + ) + + //分网卡 + for _, v := range nio { + var netTags interface{} = map[string]interface{}{"device": v.Name} + if _, exist := retNI[v.Name]; exist { + dps = append(dps, + sdkmodels.DataPointX{ + Metric: models.METRIC_NETWORK_BYTES_IN, + Value: v.BytesRecv, + Tags: &netTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_NETWORK_BYTES_OUT, + Value: v.BytesSent, + Tags: &netTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_NETWORK_PACKETS_IN, + Value: v.PacketsRecv, + Tags: &netTags, + }, + sdkmodels.DataPointX{ + Metric: models.METRIC_NETWORK_PACKETS_OUT, + Value: v.PacketsSent, + Tags: &netTags, + }, + ) + } + } + + return dps +} + +func ignoreNetworkInterface(ni []string) bool { + for _, v := range ni { + if _, exist := NETWORK_FLAGS_IGNORE[v]; exist { + return true + } + } + + for _, v := range ni { + if _, exist := NETWORK_FLAGS_INCLUDE[v]; exist { + return false + } + } + + return true +} diff --git a/bmp-monitor-agent/collector/process.go b/bmp-monitor-agent/collector/process.go new file mode 100644 index 0000000..efd8a7b --- /dev/null +++ b/bmp-monitor-agent/collector/process.go @@ -0,0 +1,41 @@ +package collector + +import ( + "coding.jd.com/bmp/cps-agent/api/models" + + sdkmodels "git.jd.com/jcloud-api-gateway/jcloud-sdk-go/services/monitor/models" + "github.com/astaxie/beego/logs" + "github.com/shirou/gopsutil/host" +) + +func init() { + Register("process", &ProcessCollector{}) +} + +type ProcessCollector struct { +} + +func (c *ProcessCollector) Collect() []sdkmodels.DataPointX { + + var dps []sdkmodels.DataPointX + var processTags interface{} = map[string]interface{}{} + + if v, err := host.Info(); err != nil { + logs.Warn("Collect HOST Error: %s", err.Error()) + return dps + } else { + /* + METRIC_PROCESS_TOTAL string = "cps.process.total" + */ + + dps = append(dps, sdkmodels.DataPointX{ + Metric: models.METRIC_PROCESS_TOTAL, + Value: v.Procs, + Tags: &processTags, + }) + + } + + return dps + +} diff --git a/bmp-monitor-agent/collector/tcp.go b/bmp-monitor-agent/collector/tcp.go new file mode 100644 index 0000000..aa196c0 --- /dev/null +++ b/bmp-monitor-agent/collector/tcp.go @@ -0,0 +1,54 @@ +package collector + +import ( + "coding.jd.com/bmp/cps-agent/api/models" + + sdkmodels "git.jd.com/jcloud-api-gateway/jcloud-sdk-go/services/monitor/models" + "github.com/astaxie/beego/logs" + "github.com/shirou/gopsutil/net" +) + +func init() { + Register("tcp", &TcpCollector{}) +} + +type TcpCollector struct { +} + +func (c *TcpCollector) Collect() []sdkmodels.DataPointX { + + var dps []sdkmodels.DataPointX + var tcpTags interface{} = map[string]interface{}{} + + if conns, err := net.Connections("tcp"); err != nil { + logs.Warn("Collect TCP Error: %s", err.Error()) + return dps + } else { + total := len(conns) + established := 0 + for _, conn := range conns { + if conn.Status == "ESTABLISHED" { + established++ + } + } + /* + METRIC_TCP_CONNECT_TOTAL string = "cps.tcp.connect.total" + METRIC_TCP_CONNECT_ESTABLISHED string = "cps.tcp.connect.established" + */ + + dps = append(dps, sdkmodels.DataPointX{ + Metric: models.METRIC_TCP_CONNECT_TOTAL, + Value: total, + Tags: &tcpTags, + }) + + dps = append(dps, sdkmodels.DataPointX{ + Metric: models.METRIC_TCP_CONNECT_ESTABLISHED, + Value: established, + Tags: &tcpTags, + }) + } + + return dps + +} diff --git a/bmp-monitor-agent/global/config.go b/bmp-monitor-agent/global/config.go new file mode 100644 index 0000000..5936b86 --- /dev/null +++ b/bmp-monitor-agent/global/config.go @@ -0,0 +1,172 @@ +package global + +import ( + "encoding/json" + "fmt" + "os" + "os/signal" + "path" + "runtime" + "strings" + "syscall" + + "coding.jd.com/bmp/cps-agent/util" + + "github.com/astaxie/beego/logs" + "github.com/gofrs/flock" +) + +type Config struct { + Monitor struct { + TimestampAlign int `json:"timestamp.align"` + } `json:"monitor"` + Agent struct { + Collect struct { + Scheduler string `json:"scheduler"` + Timeout int `json:"timeout"` + } `json:"collect"` + Heartbeat struct { + Scheduler string `json:"scheduler"` + } `json:"heartbeat"` + Pid string `json:"pid"` + Log string `json:"log"` + } `json:"agent"` + Proxy struct { + URL string `json:"url"` + } `json:"proxy"` +} + +var ( + SerialNumber string + AgentConfig Config + fileLock *flock.Flock + Debug bool + SignalChan chan os.Signal +) + +func init() { + AgentConfig = Config{} + SignalChan = make(chan os.Signal, 1) +} + +func DefaultString(v, d string) string { + if strings.TrimSpace(v) != "" { + return v + } + return d +} + +func DefaultInt(v, d int) int { + if v != 0 { + return v + } + return d +} + +func DefaultInt64(v int, d int64) int64 { + if v != 0 { + return int64(v) + } + return d +} + +func Init() { + + if strings.TrimSpace(SerialNumber) == "" { + if hostInfo, err := util.SN(); err != nil || hostInfo.SerialNumber == "" { + fmt.Fprintln(os.Stderr, "Read Host SerialNumber Error, Exit...") + os.Exit(1) + } else { + SerialNumber = hostInfo.SerialNumber + } + } + +} + +func InitApp(conf string) { + runtime.GOMAXPROCS(1) + + initConfig(conf) + if runtime.GOOS == "linux" { + initLog() + initPid() + } + + signal.Ignore( + syscall.SIGHUP, syscall.SIGQUIT, + syscall.SIGILL, syscall.SIGTRAP, syscall.SIGABRT, + syscall.SIGBUS, syscall.SIGFPE, syscall.SIGSEGV, + syscall.SIGPIPE, syscall.SIGALRM, syscall.SIGTERM) + signal.Notify(SignalChan, syscall.Signal(0xa), syscall.SIGINT) +} + +func UninitApp() { + if fileLock != nil && fileLock.Locked() { + fileLock.Unlock() + os.Remove(fileLock.Path()) + } + util.RemovePID() +} + +func initPid() { + + if !Debug { + //util.Daemon() + } + + if err := os.MkdirAll(path.Dir(AgentConfig.Agent.Pid), os.ModePerm); err != nil { + fmt.Fprintln(os.Stderr, "Create Directory Failed, Exit...", err.Error()) + os.Exit(1) + } + + fileLock = flock.New(AgentConfig.Agent.Pid + ".lock") + locked, err := fileLock.TryLock() + + if err != nil || !locked || fileLock == nil { + fmt.Fprintln(os.Stderr, "Init Failed, already running, Exit...") + os.Exit(0) + } + util.NewPID(AgentConfig.Agent.Pid) +} + +func initConfig(conf string) { + + c := `{ + "monitor": { + "timestamp.align": 60 + }, + "agent": { + "collect": { + "scheduler": "0/60 * * * * *", + "timeout": 3 + }, + "heartbeat": { + "scheduler": "0/60 * * * * *" + }, + "pid": "/var/run/bmp-agent.pid", + "log": "/var/log/bmp-agent.log" + }, + "proxy": { + "url": "http://bmp-agent-proxy:8805/api/v1/agent/" + } + }` + + if err := json.Unmarshal([]byte(c), &AgentConfig); err != nil { + fmt.Fprintln(os.Stderr, "Config Format Error, Exit...") + os.Exit(1) + } + // // TODO remove + // logs.Debug("Config %+v", AgentConfig) + +} + +func initLog() { + if Debug { + logs.SetLogger(logs.AdapterConsole, `{"level":7,"color":true}`) + logs.EnableFuncCallDepth(true) + } else { + logConfig := `{"filename":"` + DefaultString(AgentConfig.Agent.Log, "./jdcps-agent.log") + `","level":5}` + logs.SetLogger(logs.AdapterFile, logConfig) + logs.EnableFuncCallDepth(false) + } +} diff --git a/bmp-monitor-agent/global/version.go b/bmp-monitor-agent/global/version.go new file mode 100644 index 0000000..059fb2d --- /dev/null +++ b/bmp-monitor-agent/global/version.go @@ -0,0 +1,8 @@ +package global + +var ( + VERSION = "" + BUILD_TIME = "" + COMMITID = "" + CHECKSUM = "" +) diff --git a/bmp-monitor-agent/go.mod b/bmp-monitor-agent/go.mod new file mode 100644 index 0000000..86981b2 --- /dev/null +++ b/bmp-monitor-agent/go.mod @@ -0,0 +1,25 @@ +module coding.jd.com/bmp/cps-agent + +go 1.17 + +require ( + git.jd.com/jcloud-api-gateway/jcloud-sdk-go v0.0.0-00010101000000-000000000000 + github.com/StackExchange/wmi v1.2.1 + github.com/VividCortex/godaemon v1.0.0 + github.com/astaxie/beego v1.12.3 + github.com/go-redis/redis v6.14.2+incompatible + github.com/gofrs/flock v0.8.1 + github.com/shirou/gopsutil v3.21.11+incompatible +) + +require ( + github.com/go-ole/go-ole v1.2.6 // indirect + github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect + github.com/tklauser/go-sysconf v0.3.9 // indirect + github.com/tklauser/numcpus v0.3.0 // indirect + github.com/yusufpapurcu/wmi v1.2.2 // indirect + golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71 // indirect + gopkg.in/yaml.v2 v2.2.8 // indirect +) + +replace git.jd.com/jcloud-api-gateway/jcloud-sdk-go => ./bmp_vendor/jcloud-sdk-go diff --git a/bmp-monitor-agent/go.sum b/bmp-monitor-agent/go.sum new file mode 100644 index 0000000..358083e --- /dev/null +++ b/bmp-monitor-agent/go.sum @@ -0,0 +1,189 @@ +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/StackExchange/wmi v1.2.1 h1:VIkavFPXSjcnS+O8yTq7NI32k0R5Aj+v39y29VYDOSA= +github.com/StackExchange/wmi v1.2.1/go.mod h1:rcmrprowKIVzvc+NUiLncP2uuArMWLCbu9SBzvHz7e8= +github.com/VividCortex/godaemon v1.0.0 h1:aHYrScWvgaSOdAoYCdObWXLm+e1rldP9Pwb1ZvuZkQw= +github.com/VividCortex/godaemon v1.0.0/go.mod h1:hBWe/72KbGt/lb95E+Sh9ersdYbB57Dt6CG66S1YPno= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= +github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk= +github.com/astaxie/beego v1.12.3 h1:SAQkdD2ePye+v8Gn1r4X6IKZM1wd28EyUOVQ3PDSOOQ= +github.com/astaxie/beego v1.12.3/go.mod h1:p3qIm0Ryx7zeBHLljmd7omloyca1s4yu1a8kM1FkpIA= +github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ= +github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60= +github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= +github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U= +github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= +github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= +github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= +github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-ole/go-ole v1.2.5/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-redis/redis v6.14.2+incompatible h1:UE9pLhzmWf+xHNmZsoccjXosPicuiNaInPgym8nzfg0= +github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= +github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDuKuq+uX4v1fulaMbA/7ZLLhjc85h7chZGBCQ= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.0 h1:Iw5WCbBcaAAd0fpRb1c9r5YCylv4XDoCSigm1zLevwU= +github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= +github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.7.0/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= +github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= +github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= +github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= +github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s= +github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/tklauser/go-sysconf v0.3.9 h1:JeUVdAOWhhxVcU6Eqr/ATFHgXk/mmiItdKeJPev3vTo= +github.com/tklauser/go-sysconf v0.3.9/go.mod h1:11DU/5sG7UexIrp/O6g35hrWzu0JxlwQ3LSFUzyeuhs= +github.com/tklauser/numcpus v0.3.0 h1:ILuRUQBtssgnxw0XXIjKUC56fgnOrFoQQ/4+DeU2biQ= +github.com/tklauser/numcpus v0.3.0/go.mod h1:yFGUr7TUHQRAhyqBcEg0Ge34zDBAsIvJJcyE6boqnA8= +github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= +github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc= +github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= +github.com/yusufpapurcu/wmi v1.2.2 h1:KBNDSne4vP5mbSWnJbO+51IMOXJB67QiYCSBrubbPRg= +github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71 h1:ikCpsnYR+Ew0vu99XlDp55lGgDJdIMx3f4a18jfse/s= +golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/bmp-monitor-agent/log/run.log b/bmp-monitor-agent/log/run.log new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/bmp-monitor-agent/log/run.log @@ -0,0 +1 @@ + diff --git a/bmp-monitor-agent/main b/bmp-monitor-agent/main new file mode 100755 index 0000000..9af4217 Binary files /dev/null and b/bmp-monitor-agent/main differ diff --git a/bmp-monitor-agent/main.go b/bmp-monitor-agent/main.go new file mode 100644 index 0000000..3db8012 --- /dev/null +++ b/bmp-monitor-agent/main.go @@ -0,0 +1,99 @@ +package main + +import ( + "flag" + "fmt" + "io" + "os" + "runtime" + "time" + + "coding.jd.com/bmp/cps-agent/global" + "coding.jd.com/bmp/cps-agent/task" + + "github.com/astaxie/beego/logs" + "github.com/shirou/gopsutil/process" +) + +var ( + helpFlag bool + versionFlag bool + configFile string +) + +func init() { + flag.BoolVar(&helpFlag, "h", false, "show help") + flag.BoolVar(&versionFlag, "v", false, "show version and build") + flag.BoolVar(&global.Debug, "d", true, "run in debug mode") + flag.StringVar(&global.SerialNumber, "s", "", "SerialNumber") + flag.StringVar(&configFile, "c", "global/config.go", "specify config file") + + flag.Usage = usage +} + +func writeFile(line string) { + + logf, err := os.OpenFile("testddd"+"."+time.Now().Format("2006010215"), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + if err != nil { + fmt.Println("open filename error:", err.Error()) + } + defer logf.Close() + if _, err := io.WriteString(logf, line); err != nil { + fmt.Println("write line error:", err.Error()) + } +} + +func main() { + + if runtime.GOOS == "windows" { + pn, _ := process.NewProcess(int32(os.Getppid())) + pName, _ := pn.Name() + if pName != "srvany.exe" { + fmt.Fprint(os.Stdout, "cps-agent.exe不支持独立启动!") + time.Sleep(2 * time.Second) + os.Exit(1) + } + } + + flag.Parse() + + if helpFlag { + flag.Usage() + } + + global.Init() + if versionFlag { + version() + } + + global.InitApp(configFile) + + logs.Notice("========Agent Start========") + + task.Start() + <-global.SignalChan + logs.Notice("========Agent Exit========") + + task.Shutdown() + if runtime.GOOS == "linux" { + global.UninitApp() + } + + time.Sleep(500 * time.Millisecond) + os.Exit(0) +} + +func usage() { + fmt.Fprintf(os.Stdout, `jdcps-agent version: %s +Usage: jdcps-agent [-chvds] + +Options: +`, global.VERSION) + flag.PrintDefaults() + os.Exit(0) +} + +func version() { + fmt.Fprintf(os.Stdout, "Version:%s.%s\nSerialNumber:%s\n", global.VERSION, global.BUILD_TIME, global.SerialNumber) + os.Exit(0) +} diff --git a/bmp-monitor-agent/readme.md b/bmp-monitor-agent/readme.md new file mode 100644 index 0000000..b572fdc --- /dev/null +++ b/bmp-monitor-agent/readme.md @@ -0,0 +1,37 @@ +# bmp-monitor-agent + +English | [简体中文](README.zh-CN.md) + +## 1,Introduction + +The in-band monitoring agent module runs on the bm operating system, collects bm's disk, network and other data, and reports it to bmp-monitor-proxy. + +The position of bmp-monitor-agent in the entire bmp architecture is shown in:[bmp arch](../bmp-scheduler/README.md) + + + +## 2,Core Features + +Collects data from device disks, networks, etc., and reports the monitoring data to bmp-monitor-proxy. + + +## 3,Usage + +Package linux amd x_64 version agent: +make linux +Package the Windows version agent: +make windows + +download bmp-monitor-agent: +curl -O http://..../download/agent/bmp-agent.bin + +Adding operation permissions : +chmod +x bmp-agent.bin + +run: +./bmp-agent.bin + +service name:bmpd +service status:service bmpd status +start service:service start bmpd +stop service:service stop bmpd diff --git a/bmp-monitor-agent/srvany.exe b/bmp-monitor-agent/srvany.exe new file mode 100644 index 0000000..c6c106b Binary files /dev/null and b/bmp-monitor-agent/srvany.exe differ diff --git a/bmp-monitor-agent/task/task.go b/bmp-monitor-agent/task/task.go new file mode 100644 index 0000000..4e3a5f6 --- /dev/null +++ b/bmp-monitor-agent/task/task.go @@ -0,0 +1,45 @@ +package task + +import ( + "github.com/astaxie/beego/toolbox" +) + +var ( + Tasks map[string]Task +) + +func init() { + Tasks = make(map[string]Task) +} + +type Task interface { + Name() string + Spec() string + TaskFunc() error + Shutdown() error +} + +func Register(t Task) { + Tasks[t.Name()] = t +} + +func Start() { + for _, v := range Tasks { + task := toolbox.NewTask(v.Name(), v.Spec(), v.TaskFunc) + task.Run() + toolbox.AddTask(v.Name(), task) + } + + toolbox.StartTask() +} + +func Stop() { + toolbox.StopTask() +} + +func Shutdown() { + toolbox.StopTask() + for _, v := range Tasks { + v.Shutdown() + } +} diff --git a/bmp-monitor-agent/task/task_collect.go b/bmp-monitor-agent/task/task_collect.go new file mode 100644 index 0000000..4986475 --- /dev/null +++ b/bmp-monitor-agent/task/task_collect.go @@ -0,0 +1,59 @@ +package task + +import ( + "time" + + // "encoding/json" + // "fmt" + // "os" + + "coding.jd.com/bmp/cps-agent/api" + "coding.jd.com/bmp/cps-agent/api/models" + "coding.jd.com/bmp/cps-agent/collector" + "coding.jd.com/bmp/cps-agent/global" + + "github.com/astaxie/beego/logs" +) + +type CollectTask struct { +} + +func init() { + Register(&CollectTask{}) +} + +func (t *CollectTask) Name() string { + return "CollectTask" +} + +func (t *CollectTask) Spec() string { + return global.DefaultString(global.AgentConfig.Agent.Collect.Scheduler, "0/60 * * * * *") +} + +func (t *CollectTask) TaskFunc() error { + logs.Debug("Collect") + + timeout := time.Duration(global.DefaultInt(global.AgentConfig.Agent.Collect.Timeout, 1)) * time.Second + dataPoints := collector.Collect(timeout) + + // v, _ := json.Marshal(dataPoints) + // fmt.Println("collect datapoints is:", string(v)) + + // fmt.Println("put url is:", global.AgentConfig.Proxy.URL) + + url := global.AgentConfig.Proxy.URL + "put" + // global.SerialNumber = "minping-mock-sn" //TODO 记得注释掉 + o := models.ProxyPut{SN: global.SerialNumber, DataPoints: dataPoints} + + if err := api.Put(url, o); err != nil { + logs.Warn("Post Put Error:%s", err.Error()) + } else { + logs.Info("Post Put success, url:%s, sn:%s", global.AgentConfig.Proxy.URL, global.SerialNumber) + } + + return nil +} + +func (t *CollectTask) Shutdown() error { + return nil +} diff --git a/bmp-monitor-agent/task/task_heartbeat.go b/bmp-monitor-agent/task/task_heartbeat.go new file mode 100644 index 0000000..b143e55 --- /dev/null +++ b/bmp-monitor-agent/task/task_heartbeat.go @@ -0,0 +1,51 @@ +package task + +import ( + "fmt" + "time" + + "coding.jd.com/bmp/cps-agent/api" + "coding.jd.com/bmp/cps-agent/api/models" + "coding.jd.com/bmp/cps-agent/global" + + "github.com/astaxie/beego/logs" +) + +type HeartbeatTask struct { +} + +func init() { + Register(&HeartbeatTask{}) +} + +func (t *HeartbeatTask) Name() string { + return "HeartbeatTask" +} + +func (t *HeartbeatTask) Spec() string { + return global.DefaultString(global.AgentConfig.Agent.Heartbeat.Scheduler, "0/60 * * * * *") +} + +func (t *HeartbeatTask) TaskFunc() error { + + logs.Debug("Heartbeat") + url := global.AgentConfig.Proxy.URL + "heartbeat" + version := fmt.Sprintf("%s.%s", global.VERSION, global.BUILD_TIME) + // global.SerialNumber = "minping-mock-sn" //TODO 记得注释掉 + status := models.AgentStatus{SN: global.SerialNumber, AgentVersion: version, Timestamp: time.Now().Unix(), Status: models.AGENT_OK} + + if err := api.Heartbeat(url, status); err != nil { + logs.Info("Post Heartbeat Error:%s", err.Error()) + } + return nil +} + +func (t *HeartbeatTask) Shutdown() error { + logs.Debug("Heartbeat Shutdown") + url := global.AgentConfig.Proxy.URL + "heartbeat" + version := fmt.Sprintf("%s.%s", global.VERSION, global.BUILD_TIME) + status := models.AgentStatus{SN: global.SerialNumber, AgentVersion: version, Timestamp: time.Now().Unix(), Status: models.AGENT_STOP} + + api.Heartbeat(url, status) + return nil +} diff --git a/bmp-monitor-agent/tools/config-crypt.go b/bmp-monitor-agent/tools/config-crypt.go new file mode 100644 index 0000000..891901f --- /dev/null +++ b/bmp-monitor-agent/tools/config-crypt.go @@ -0,0 +1,105 @@ +package main + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "encoding/base64" + "flag" + "fmt" + "io/ioutil" + "os" + "strings" +) + +var ( + helpFlag bool + key string + configFile string + outFile string +) + +func init() { + flag.BoolVar(&helpFlag, "h", false, "show help") + flag.StringVar(&key, "k", "", "AES key, must 16/24/32 bytes.") + flag.StringVar(&configFile, "f", "config.in", "config file to encrypt") + flag.StringVar(&outFile, "o", "config.out", "output file") + +} + +func main() { + flag.Parse() + + if helpFlag { + flag.PrintDefaults() + } + + if strings.TrimSpace(key) == "" || strings.TrimSpace(configFile) == "" || strings.TrimSpace(outFile) == "" { + fmt.Fprintln(os.Stderr, "Specify Parameter") + flag.PrintDefaults() + os.Exit(1) + } + + if fileByte, err := ioutil.ReadFile(configFile); err != nil { + fmt.Fprintf(os.Stderr, "Read file Error:%s\n", err.Error()) + os.Exit(2) + } else { + if encryptStr, e := AesEncrypt(fileByte, key); e != nil { + fmt.Fprintf(os.Stderr, "Read file Error:%s\n", e.Error()) + os.Exit(3) + } else { + if errWrite := ioutil.WriteFile(outFile, []byte(encryptStr), os.ModePerm); errWrite != nil { + fmt.Fprintf(os.Stderr, "Read file Error:%s\n", errWrite.Error()) + os.Exit(3) + } + } + } + + os.Exit(0) + +} + +func AesEncrypt(orig []byte, key string) (string, error) { + origData := orig + k := []byte(key) + if block, err := aes.NewCipher(k); err != nil { + return "", err + } else { + blockSize := block.BlockSize() + origData = pkcs7Padding(origData, blockSize) + blockMode := cipher.NewCBCEncrypter(block, k[:blockSize]) + cryted := make([]byte, len(origData)) + blockMode.CryptBlocks(cryted, origData) + return base64.StdEncoding.EncodeToString(cryted), nil + } +} + +func AesDecrypt(cryted string, key string) (string, error) { + if crytedByte, err := base64.StdEncoding.DecodeString(cryted); err != nil { + return "", err + } else { + k := []byte(key) + if block, e := aes.NewCipher(k); e != nil { + return "", e + } else { + blockSize := block.BlockSize() + blockMode := cipher.NewCBCDecrypter(block, k[:blockSize]) + orig := make([]byte, len(crytedByte)) + blockMode.CryptBlocks(orig, crytedByte) + orig = pkcs7UnPadding(orig) + return string(orig), nil + } + } +} + +func pkcs7Padding(ciphertext []byte, blocksize int) []byte { + padding := blocksize - len(ciphertext)%blocksize + padtext := bytes.Repeat([]byte{byte(padding)}, padding) + return append(ciphertext, padtext...) +} + +func pkcs7UnPadding(origData []byte) []byte { + length := len(origData) + unpadding := int(origData[length-1]) + return origData[:(length - unpadding)] +} diff --git a/bmp-monitor-agent/util/crypto.go b/bmp-monitor-agent/util/crypto.go new file mode 100644 index 0000000..c7c5a09 --- /dev/null +++ b/bmp-monitor-agent/util/crypto.go @@ -0,0 +1,68 @@ +package util + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "encoding/base64" +) + +// AesEncrypt AES encrypt method. key must 128/192/256 bits. +// +// example: +// orig := "hello world" +// key := "12345678123456781234567812345678" +// fmt.Println("原文:", orig) +// encryptCode,_ := AesEncrypt(orig, key) +// fmt.Println("密文:" , encryptCode) +func AesEncrypt(orig string, key string) (string, error) { + origData := []byte(orig) + k := []byte(key) + if block, err := aes.NewCipher(k); err != nil { + return "", err + } else { + blockSize := block.BlockSize() + origData = pkcs7Padding(origData, blockSize) + blockMode := cipher.NewCBCEncrypter(block, k[:blockSize]) + cryted := make([]byte, len(origData)) + blockMode.CryptBlocks(cryted, origData) + return base64.StdEncoding.EncodeToString(cryted), nil + } +} + +// AedDecrypt AES decrypt.key must 128/192/256 bits. +// +// example: +// key := "12345678123456781234567812345678" +// data := bpIjQ4yVwCt0RMI0JDOfTA== +// decryptCode,_ := AesDecrypt(data, key) +// fmt.Println("解密结果:", decryptCode) +func AesDecrypt(cryted string, key string) (string, error) { + if crytedByte, err := base64.StdEncoding.DecodeString(cryted); err != nil { + return "", err + } else { + k := []byte(key) + if block, e := aes.NewCipher(k); e != nil { + return "", e + } else { + blockSize := block.BlockSize() + blockMode := cipher.NewCBCDecrypter(block, k[:blockSize]) + orig := make([]byte, len(crytedByte)) + blockMode.CryptBlocks(orig, crytedByte) + orig = pkcs7UnPadding(orig) + return string(orig), nil + } + } +} + +func pkcs7Padding(ciphertext []byte, blocksize int) []byte { + padding := blocksize - len(ciphertext)%blocksize + padtext := bytes.Repeat([]byte{byte(padding)}, padding) + return append(ciphertext, padtext...) +} + +func pkcs7UnPadding(origData []byte) []byte { + length := len(origData) + unpadding := int(origData[length-1]) + return origData[:(length - unpadding)] +} diff --git a/bmp-monitor-agent/util/daemon.go b/bmp-monitor-agent/util/daemon.go new file mode 100644 index 0000000..c7d8682 --- /dev/null +++ b/bmp-monitor-agent/util/daemon.go @@ -0,0 +1 @@ +package util diff --git a/bmp-monitor-agent/util/daemon_darwin.go b/bmp-monitor-agent/util/daemon_darwin.go new file mode 100644 index 0000000..b198db3 --- /dev/null +++ b/bmp-monitor-agent/util/daemon_darwin.go @@ -0,0 +1,10 @@ +// +build darwin + +package util + +import "github.com/VividCortex/godaemon" + +func Daemon() error { + _, _, err := godaemon.MakeDaemon(&godaemon.DaemonAttr{}) + return err +} diff --git a/bmp-monitor-agent/util/daemon_linux.go b/bmp-monitor-agent/util/daemon_linux.go new file mode 100644 index 0000000..d3df6fe --- /dev/null +++ b/bmp-monitor-agent/util/daemon_linux.go @@ -0,0 +1,13 @@ +// +build linux + +package util + +import "github.com/VividCortex/godaemon" + +// import "fmt" + +func Daemon() error { + _, _, err := godaemon.MakeDaemon(&godaemon.DaemonAttr{}) + // panic("MakeDaemon error:" + err.Error()) + return err +} diff --git a/bmp-monitor-agent/util/daemon_windows.go b/bmp-monitor-agent/util/daemon_windows.go new file mode 100644 index 0000000..a657eab --- /dev/null +++ b/bmp-monitor-agent/util/daemon_windows.go @@ -0,0 +1,11 @@ +// +build windows + +package util + +import "errors" + +var ErrNotImplemented = errors.New("Not implemented") + +func Daemon() error { + return ErrNotImplemented +} diff --git a/bmp-monitor-agent/util/float.go b/bmp-monitor-agent/util/float.go new file mode 100644 index 0000000..4b2a55b --- /dev/null +++ b/bmp-monitor-agent/util/float.go @@ -0,0 +1,10 @@ +package util + +import ( + "math" +) + +func FloatRound(f float64, n int) float64 { + n10 := math.Pow10(n) + return math.Trunc((f+0.5/n10)*n10) / n10 +} diff --git a/bmp-monitor-agent/util/host.go b/bmp-monitor-agent/util/host.go new file mode 100644 index 0000000..ab30305 --- /dev/null +++ b/bmp-monitor-agent/util/host.go @@ -0,0 +1,6 @@ +package util + +type HostInfo struct { + Manufacturer string + SerialNumber string +} diff --git a/bmp-monitor-agent/util/host_darwin.go b/bmp-monitor-agent/util/host_darwin.go new file mode 100644 index 0000000..7a19ae4 --- /dev/null +++ b/bmp-monitor-agent/util/host_darwin.go @@ -0,0 +1,39 @@ +// +build darwin + +package util + +import ( + "os/exec" + "strings" +) + +func SN() (HostInfo, error) { + ret := HostInfo{} + + ioreg, err := exec.LookPath("/usr/sbin/ioreg") + if err != nil { + return ret, err + } + cmd := exec.Command(ioreg, "-l") + + out, err := cmd.Output() + if err != nil { + return ret, err + } + for _, line := range strings.Split(string(out), "\n") { + if len(ret.SerialNumber) == 0 && strings.Contains(line, "\"IOPlatformSerialNumber\"") { + s := strings.Split(line, "=") + ret.SerialNumber = strings.ReplaceAll(s[len(s)-1], "\"", "") + println("SerialNumber:" + ret.SerialNumber) + continue + } + + if len(ret.Manufacturer) == 0 && strings.Contains(line, "\"Manufacturer\"") { + s := strings.Split(line, "=") + ret.Manufacturer = strings.ReplaceAll(s[len(s)-1], "\"", "") + println("Manufacturer:" + ret.Manufacturer) + continue + } + } + return ret, nil +} diff --git a/bmp-monitor-agent/util/host_linux.go b/bmp-monitor-agent/util/host_linux.go new file mode 100644 index 0000000..ffabc1f --- /dev/null +++ b/bmp-monitor-agent/util/host_linux.go @@ -0,0 +1,38 @@ +// +build linux + +package util + +import ( + "os/exec" + "strings" +) + +func SN() (HostInfo, error) { + ret := HostInfo{} + + dmidcode, err := exec.LookPath("dmidecode") + if err != nil { + return ret, err + } + cmd := exec.Command(dmidcode, "-t", "1") + + out, err := cmd.Output() + if err != nil { + return ret, err + } + + for _, line := range strings.Split(string(out), "\n") { + tmp := strings.SplitN(line, ":", 2) + if strings.EqualFold(strings.TrimSpace(tmp[0]), "Serial Number") { + ret.SerialNumber = strings.TrimSpace(tmp[1]) + continue + } + + if strings.EqualFold(strings.TrimSpace(tmp[0]), "Manufacturer:") { + ret.Manufacturer = strings.TrimSpace(tmp[1]) + continue + } + } + + return ret, nil +} diff --git a/bmp-monitor-agent/util/host_windows.go b/bmp-monitor-agent/util/host_windows.go new file mode 100644 index 0000000..8b475b9 --- /dev/null +++ b/bmp-monitor-agent/util/host_windows.go @@ -0,0 +1,69 @@ +// +build windows + +package util + +import ( + "context" + "errors" + "time" + + "github.com/StackExchange/wmi" +) + +var ( + Timeout = 30 * time.Second + ErrTimeout = errors.New("command timed out") +) + +type Win32_BIOS struct { + Manufacturer string + SerialNumber string +} + +func SN() (HostInfo, error) { + var dst []Win32_BIOS + + ret := HostInfo{} + err := WMIQuery("SELECT * FROM Win32_BIOS", &dst) + if err != nil { + return ret, err + } + + for _, d := range dst { + if len(d.SerialNumber) == 0 { + continue + } + + ret.Manufacturer = d.Manufacturer + ret.SerialNumber = d.SerialNumber + } + if ret.SerialNumber == "" { + ret.SerialNumber = "empty_sn_mocked" //有些虚拟机没有sn时mock,测试方便。TODO 上线前放开 + } + return ret, nil +} + +func WMIQuery(query string, dst interface{}, connectServerArgs ...interface{}) error { + return WMIQueryWithContext(context.Background(), query, dst, connectServerArgs...) +} + +// WMIQueryWithContext - wraps wmi.Query with a timed-out context to avoid hanging +func WMIQueryWithContext(ctx context.Context, query string, dst interface{}, connectServerArgs ...interface{}) error { + if _, ok := ctx.Deadline(); !ok { + ctxTimeout, cancel := context.WithTimeout(ctx, Timeout) + defer cancel() + ctx = ctxTimeout + } + + errChan := make(chan error, 1) + go func() { + errChan <- wmi.Query(query, dst, connectServerArgs...) + }() + + select { + case <-ctx.Done(): + return ctx.Err() + case err := <-errChan: + return err + } +} diff --git a/bmp-monitor-agent/util/pid.go b/bmp-monitor-agent/util/pid.go new file mode 100644 index 0000000..b7874e2 --- /dev/null +++ b/bmp-monitor-agent/util/pid.go @@ -0,0 +1,45 @@ +package util + +import ( + "os" + "strconv" + + "github.com/astaxie/beego/logs" +) + +type Pidfile struct { + Pathfile string +} + +var _localpid *Pidfile + +func NewPID(pathfile string) { + _localpid = New(pathfile) +} + +// New creates a new Pidfile and writes the current PID +func New(pathfile string) *Pidfile { + file, err := os.OpenFile(pathfile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModeExclusive|os.ModePerm) + if err != nil { + logs.Warn("pidfile: failed to open %s (%s)", pathfile, err) + return nil + } + defer file.Close() + pid := strconv.Itoa(os.Getpid()) + logs.Info("start process pid:%v --> %s", pid, pathfile) + file.WriteString(pid) + return &Pidfile{pathfile} +} + +func (pf *Pidfile) Remove() { + err := os.Remove(pf.Pathfile) + if err != nil { + logs.Warn("pidfile: failed to remove %s (%s)", pf.Pathfile, err) + } +} +func RemovePID() { + defer func() { recover() }() + if _localpid != nil { + _localpid.Remove() + } +} diff --git a/bmp-monitor-agent/util/redis.go b/bmp-monitor-agent/util/redis.go new file mode 100644 index 0000000..94ea1bd --- /dev/null +++ b/bmp-monitor-agent/util/redis.go @@ -0,0 +1,178 @@ +package util + +import ( + "fmt" + "sync" + "time" + + "github.com/go-redis/redis" +) + +var redisMonitorNamespace string + +var redisOnce sync.Once + +type redisUtil struct { + *redis.Client +} + +// RedisUtil singleton redis util +var RedisUtil *redisUtil + +// InitRedis initial redisUtil instance +func InitRedis(namespace, addr, passwd string, db int) error { + redisOnce.Do(func() { + if RedisUtil == nil { + + RedisUtil = &redisUtil{ + redis.NewClient(&redis.Options{ + Addr: addr, + Password: passwd, // no password set + DB: db, // use default DB + }), + } + + redisMonitorNamespace = namespace + + } + }) + + return RedisUtil.Ping().Err() +} + +// SetObjectToRedisWithExpire set string object with a expiration +func SetObjectToRedisWithExpire(key, value string, sec int) error { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + err := RedisUtil.Set(fullKey, value, time.Second*time.Duration(sec)).Err() + if err != nil { + return err + } + + return nil +} + +// SetObjectToRedis set object to Redis +func SetObjectToRedis(key string, value string) error { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + fmt.Println("redis set full key is:" + fullKey) + fmt.Println("redis set value is:" + value) + err := RedisUtil.Set(fullKey, value, 0).Err() + if err != nil { + return err + } + + return nil +} + +// GetObjectFromRedis Get object from Redis +func GetObjectFromRedis(key string) (string, error) { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + ret, err := RedisUtil.Get(fullKey).Result() + if err != nil { + return "", err + } + + return ret, nil +} + +func DelObjectFromRedis(keys []string) error { + + if len(keys) <= 0 { + return nil + } + + var fullKeys []string + for _, v := range keys { + if v != "" { + fullKeys = append(fullKeys, redisMonitorNamespace+":"+v) + } + } + + if len(fullKeys) > 0 { + err := RedisUtil.Del(fullKeys...).Err() + if err != nil { + return err + } + } + + return nil +} + +// HSetObjectToRedis hash set object to Redis +func HSetObjectToRedis(key, field, value string) error { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + err := RedisUtil.HSet(fullKey, field, value).Err() + if err != nil { + return err + } + + return nil +} + +// HSetObjectToRedis hash set object to Redis +func HMSetObjectToRedis(key string, data map[string]interface{}) error { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + err := RedisUtil.HMSet(fullKey, data).Err() + if err != nil { + return err + } + + return nil +} + +// HGetObjectFromRedis hash get from redis +func HGetObjectFromRedis(key, field string) (string, error) { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + ret, err := RedisUtil.HGet(fullKey, field).Result() + if err != nil { + return "", err + } + return ret, nil +} + +func HDelObjectFromRedis(key string, fields []string) error { + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + if len(fields) <= 0 { + return nil + } + + err := RedisUtil.HDel(fullKey, fields...).Err() + + if err != nil { + return err + } + return nil +} diff --git a/bmp-monitor-proxy/.cmd b/bmp-monitor-proxy/.cmd new file mode 100644 index 0000000..ced32d3 --- /dev/null +++ b/bmp-monitor-proxy/.cmd @@ -0,0 +1 @@ +rm -rf vendor diff --git a/bmp-monitor-proxy/.gitmodules b/bmp-monitor-proxy/.gitmodules new file mode 100644 index 0000000..506f24c --- /dev/null +++ b/bmp-monitor-proxy/.gitmodules @@ -0,0 +1,3 @@ +[submodule "bmp-deploy"] + path = bmp-deploy + url = git@coding.jd.com:aidc-bmp/bmp-deploy.git diff --git a/bmp-monitor-proxy/Makefile b/bmp-monitor-proxy/Makefile new file mode 100644 index 0000000..f8f5faa --- /dev/null +++ b/bmp-monitor-proxy/Makefile @@ -0,0 +1,101 @@ +GO = go +GOCLEAN=$(GO) clean +GOBUILD = $(GO) build +GOFMT ?= gofmt "-s" +EXE ?= $(shell $(GO) env GOEXE) + +AGENT = jdcps-agent +PROXY = cps-agent-proxy + +PACKAGES ?= $(shell go list ./... | grep -v vendor | grep -v tools) +GOFILES := $(shell find . -name "*.go" -type f -not -path "./vendor/*" -not -path "./proxy/*" -not -path "./tools/*" ) +PROXY_GOFILES := $(shell find . -name "*.go" -type f -not -path "./vendor/*" -not -path "./agent/*" -not -path "./tools/*" ) + +BUILD_TIME := $(shell date +%Y%m%d%H%M%S) +VERSION := $(shell git describe --tags --always) +COMMITID := $(shell git rev-parse ${VERSION} | cut -c 1-32) +CHECKSUM := $(shell md5sum conf/agent.json.prod | cut -c 1-32) +CHECKSUM_DEBUG := $(shell md5sum conf/agent.json.dev | cut -c 1-32) + +.PHONY: all vet fmt check clean +all: $(AGENT) $(PROXY) + +vet: + go vet $(PACKAGES) + +fmt: + $(GOFMT) -w $(GOFILES) + +clean: + @rm -f $(AGENT)$(EXE) $(PROXY)$(EXE) + +clean-cps-agent-proxy: + $(GOCLEAN) + +build-cps-agent-proxy: $(PROXY_GOFILES) + $(GOBUILD) -v -gcflags "-N -l" -o $@$(EXE) main.go + +check: + # get all go files and run go fmt on them + @diff=$$($(GOFMT) -d $(GOFILES)); \ + if [ -n "$$diff" ]; then \ + echo "Please run 'make fmt' and commit the result:"; \ + echo "$${diff}"; \ + exit 1; \ + fi; + +$(AGENT): $(GOFILES) + @go run tools/config-crypt.go -k $(COMMITID) -f conf/agent.json.dev -o conf/agent.json + @go-bindata -debug -nomemcopy -nometadata -o agent/global/global_debug.go -pkg global -tags !release conf/ conf/cert/ + $(GOBUILD) -v -ldflags "-X cps-agent/agent.VERSION=$(VERSION) -X cps-agent/agent.BUILD_TIME=$(BUILD_TIME) -X cps-agent/agent.COMMITID=$(COMMITID) -X cps-agent/agent.CHECKSUM=$(CHECKSUM)" -gcflags "-N -l" -o $@$(EXE) + +$(PROXY): $(PROXY_GOFILES) + $(GOBUILD) -v -gcflags "-N -l" -o $@$(EXE) cps-agent/proxy + + +windows: $(GOFILES) + @mkdir -p build/windows/internal + @go run tools/config-crypt.go -k $(COMMITID) -f conf/agent.json.prod -o conf/agent.json + @go-bindata -nomemcopy -nometadata -o agent/global/global_release.go -pkg global -tags release conf/agent.json conf/cert/ca.crt conf/cert/client.crt conf/cert/client.key + GOARCH=amd64 GOOS=windows $(GOBUILD) -v -tags release -ldflags "-X cps-agent/agent.VERSION=$(VERSION) -X cps-agent/agent.BUILD_TIME=$(BUILD_TIME) -X cps-agent/agent.COMMITID=$(COMMITID) -X cps-agent/agent.CHECKSUM=$(CHECKSUM) -w -s " -o build/windows/internal/${AGENT}.exe main.go + GOARCH=amd64 GOOS=windows $(GOBUILD) -o build/windows/${AGENT}_install.exe jdcps-agent-install-windows.go + @cp -f srvany.exe build/windows/internal/ + @tar czf build/jdcps-agent-windows.tgz -C build/windows ./ + @rm -rf build/windows + +windows_debug: $(GOFILES) + @mkdir -p build/windows/internal + @go run tools/config-crypt.go -k $(COMMITID) -f conf/agent.json.dev -o conf/agent.json + @go-bindata -nomemcopy -nometadata -o agent/global/global_release.go -pkg global -tags release conf/agent.json conf/cert/ca.crt conf/cert/client.crt conf/cert/client.key + GOARCH=amd64 GOOS=windows $(GOBUILD) -v -tags release -ldflags "-X cps-agent/agent.VERSION=$(VERSION) -X cps-agent/agent.BUILD_TIME=$(BUILD_TIME) -X cps-agent/agent.COMMITID=$(COMMITID) -X cps-agent/agent.CHECKSUM=$(CHECKSUM_DEBUG) -w -s " -o build/windows/internal/${AGENT}.exe main.go + GOARCH=amd64 GOOS=windows $(GOBUILD) -o build/windows/${AGENT}_install.exe jdcps-agent-install-windows.go + @cp -f srvany.exe build/windows/internal/ + @tar czf build/jdcps-agent-windows.tgz -C build/windows ./ + @rm -rf build/windows + + + +linux: $(GOFILES) + @mkdir -p build/linux + @go run tools/config-crypt.go -k $(COMMITID) -f conf/agent.json.prod -o conf/agent.json + @go-bindata -nomemcopy -nometadata -o agent/global/global_release.go -pkg global -tags release conf/agent.json conf/cert/ca.crt conf/cert/client.crt conf/cert/client.key + GOARCH=amd64 GOOS=linux $(GOBUILD) -v -tags release -ldflags "-X cps-agent/agent.VERSION=$(VERSION) -X cps-agent/agent.BUILD_TIME=$(BUILD_TIME) -X cps-agent/agent.COMMITID=$(COMMITID) -X cps-agent/agent.CHECKSUM=$(CHECKSUM) -w -s " -o build/linux/${AGENT} main.go + @cp -f jdcpsd build/linux/ + @tar czf build/jdcps-agent.tgz -C build/linux ./ + @cat jdcps-agent-install.sh build/jdcps-agent.tgz > build/$(AGENT).bin + @rm -rf build/jdcps-agent.tgz build/linux + @chmod +x build/$(AGENT).bin + +linux_debug: $(GOFILES) + @mkdir -p build/linux + @go run tools/config-crypt.go -k $(COMMITID) -f conf/agent.json.dev -o conf/agent.json + @go-bindata -nomemcopy -nometadata -o agent/global/global_release.go -pkg global -tags release conf/agent.json conf/cert/ca.crt conf/cert/client.crt conf/cert/client.key + GOARCH=amd64 GOOS=linux $(GOBUILD) -v -tags release -ldflags "-X cps-agent/agent.VERSION=$(VERSION) -X cps-agent/agent.BUILD_TIME=$(BUILD_TIME) -X cps-agent/agent.COMMITID=$(COMMITID) -X cps-agent/agent.CHECKSUM=$(CHECKSUM_DEBUG) -w -s " -o build/linux/${AGENT} main.go + @cp -f jdcpsd build/linux/ + @tar czf build/jdcps-agent.tgz -C build/linux ./ + @cat jdcps-agent-install.sh build/jdcps-agent.tgz > build/$(AGENT).bin + @rm -rf build/jdcps-agent.tgz build/linux + @chmod +x build/$(AGENT).bin + +release: linux + diff --git a/bmp-monitor-proxy/README.md b/bmp-monitor-proxy/README.md new file mode 100644 index 0000000..ce98ca8 --- /dev/null +++ b/bmp-monitor-proxy/README.md @@ -0,0 +1,17 @@ +# bmp-monitor-proxy + + +English | [简体中文](README.zh-CN.md) + +## Introduction + +The in-band monitoring proxy module receives monitoring data reported by the bmp-monitor-agent of each device, processes it, and reports it to the push-gateway module. + +The position of bmp-monitor-proxy in the entire bmp architecture is shown in:[bmp arch](../bmp-scheduler/README.md) + + + +## 2,Core Features + +- Receive monitoring data reported by bmp-monitor-agent of each device. +- After processing and cleaning, report to the push-gateway module. \ No newline at end of file diff --git a/bmp-monitor-proxy/README.zh-CN.md b/bmp-monitor-proxy/README.zh-CN.md new file mode 100644 index 0000000..bde9cc5 --- /dev/null +++ b/bmp-monitor-proxy/README.zh-CN.md @@ -0,0 +1,18 @@ +# bmp-monitor-proxy + +[English](README.md) | 简体中文 + + +## 介绍 + +带内监控proxy模块,接收各设备bmp-monitor-agent上报的监控数据,处理后上报到push-gateway模块。 + +bmp-monitor-proxy在整个bmp架构中的位置见:[bmp架构图](../bmp-scheduler/README.zh-CN.md) + + + +## 2,核心功能 + +- 接收各设备bmp-monitor-agent上报的监控数据 +- 处理清洗后上报到push-gateway模块。 + diff --git a/bmp-monitor-proxy/agent-proxy-deploy.sh b/bmp-monitor-proxy/agent-proxy-deploy.sh new file mode 100755 index 0000000..2fa04ab --- /dev/null +++ b/bmp-monitor-proxy/agent-proxy-deploy.sh @@ -0,0 +1,21 @@ +#!/bin/bash +export PATH=$PATH:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/export/server/php/sbin:/export/server/go/bin:/Doorgod/users/.local/bin:/Doorgod/users/bin +export PATH=/export/servers/go/bin/:$PATH + +BIN_PATH=/export/servers/cps-agent-proxy +mkdir -p $BIN_PATH/log +APP_NAME=cps-agent-proxy +echo "Start $APP_NAME ..." + +if [[ ! -d "$BIN_PATH" ]];then + mkdir -p ${BIN_PATH} +fi + +NUM=`ps aux | grep -E ${APP_NAME} | grep -v grep |wc -l` +if [[ "${NUM}" -ge "1" ]];then + echo "cps-agent-proxy Process is running, shuting down first... " + PID=`ps aux | grep -E ${APP_NAME} | grep -v grep | awk -F " " '{print $2}'` + kill ${PID} +fi +echo "Start $APP_NAME again ..." +nohup ${BIN_PATH}/${APP_NAME} -c ${BIN_PATH}/conf/proxy.ini > ${BIN_PATH}/log/proxy.log 2>&1 & diff --git a/bmp-monitor-proxy/agent-proxy-jdstack b/bmp-monitor-proxy/agent-proxy-jdstack new file mode 100755 index 0000000..ccb0acd Binary files /dev/null and b/bmp-monitor-proxy/agent-proxy-jdstack differ diff --git a/bmp-monitor-proxy/api/api.go b/bmp-monitor-proxy/api/api.go new file mode 100644 index 0000000..35f54b3 --- /dev/null +++ b/bmp-monitor-proxy/api/api.go @@ -0,0 +1,161 @@ +package api + +import ( + "encoding/json" + "errors" + "fmt" + + "coding.jd.com/bmp/agent-proxy-jdstack/api/models" + "github.com/beego/beego/v2/server/web" + + log "git.jd.com/cps-golang/log" +) + +// Put post ProxyPut object to proxy +func Put(url string, o models.ProxyPut, ca, cert, key []byte) error { + if url == "" { + return fmt.Errorf("url nil") + } + + req := ProxyPost(url, ca, cert, key) + if req == nil { + return fmt.Errorf("Init HttpClient Error") + } + + if body, err := o.JSON(); err != nil { + return err + } else { + req.Body(body).Header("Content-Type", "application/json") + } + + resp := &ProxyResponse{} + if err := req.ToJSON(resp); err != nil { + return err + } + + if resp.Code != 0 { + return fmt.Errorf("Error: Code=%d, Message=%s", resp.Code, resp.Message) + } + + return nil +} + +// Heartbeat post AgentStatus object to proxy +func Heartbeat(url string, o models.AgentStatus, ca, cert, key []byte) error { + if url == "" { + return fmt.Errorf("url nil") + } + + req := ProxyPost(url, ca, cert, key) + if req == nil { + return fmt.Errorf("Init HttpClient Error") + } + + if body, err := o.JSON(); err != nil { + return err + } else { + req.Body(body).Header("Content-Type", "application/json") + } + + resp := &ProxyResponse{} + if err := req.ToJSON(resp); err != nil { + return err + } + + if resp.Code != 0 { + return fmt.Errorf("Error: Code=%d, Message=%s", resp.Code, resp.Message) + } + + return nil +} + +// PutToProxy post MonitorPut object to proxy, used to send to monitor through proxy +func PutToProxy(url string, o models.MonitorPut, ca, cert, key []byte) error { + if url == "" { + return fmt.Errorf("url nil") + } + + req := ProxyPost(url, ca, cert, key) + if req == nil { + return fmt.Errorf("Init HttpClient Error") + } + + if body, err := o.JSON(); err != nil { + return err + } else { + req.Body(body).Header("Content-Type", "application/json") + } + + resp := &ProxyResponse{} + if err := req.ToJSON(resp); err != nil { + return err + } + + if resp.Code != 0 { + return fmt.Errorf("Error: Code=%d, Message=%s", resp.Code, resp.Message) + } + + return nil +} + +// GetInstanceID get InstanceID from cps-api +func GetInstanceID(logger *log.Logger, sn string) (*models.Instance, error) { + + if sn == "minping-mock-sn" { //10.226.192.114测试专用 + return &models.Instance{ + Result: models.InstanceResult{ + Instance: models.InstanceDetail{ + InstanceID: "minping-mock-instanceId", + InstanceName: "minping-mock", + Sn: "minping-mock-sn", + }, + }, + }, nil + } + + openapi, _ := web.AppConfig.String("openapi_host") + openapiPort, _ := web.AppConfig.String("openapi_port") + cpsApi, _ := web.AppConfig.String("api.cps") + url := fmt.Sprintf("http://%s:%s%s", openapi, openapiPort, cpsApi) + + if sn == "" || url == "" { + return nil, fmt.Errorf("url nil") + } + + req := Get(url) + if req == nil { + return nil, fmt.Errorf("Init HttpClient Error") + } + + instance := &models.Instance{} + if err := req.Param("sn", sn).ToJSON(instance); err != nil { + return nil, err + } + + v, _ := json.Marshal(instance) + logger.Infof("GetInstanceID.instance success, sn:%s, instance:%s", sn, string(v)) + + return instance, nil +} + +// GetInstanceID get InstanceID from cps-api +func GetPinByTenant(url, tenant string) (*models.PinResult, error) { + if tenant == "" || url == "" { + return nil, fmt.Errorf("url nil") + } + + req := Get(url) + if req == nil { + return nil, fmt.Errorf("Init HttpClient Error") + } + + pinRes := &models.PinResult{} + if err := req.Param("tenant", tenant).ToJSON(pinRes); err != nil { + return nil, err + } + if pinRes.Result.Pin == "" { + return nil, errors.New("empty pin") + } + + return pinRes, nil +} diff --git a/bmp-monitor-proxy/api/client.go b/bmp-monitor-proxy/api/client.go new file mode 100644 index 0000000..4539828 --- /dev/null +++ b/bmp-monitor-proxy/api/client.go @@ -0,0 +1,82 @@ +package api + +import ( + "crypto/tls" + "crypto/x509" + "time" + + "github.com/beego/beego/v2/client/httplib" +) + +type HttpClient struct { + *httplib.BeegoHTTPRequest +} + +func NewHttpClient(url, method string) *HttpClient { + req := httplib.NewBeegoRequest(url, method) + if req == nil { + return nil + } + + req.SetTimeout(1*time.Second, 1*time.Second) + req.SetUserAgent("JDCPS-AGENT") + // req.DumpBody(true) + req.SetEnableCookie(false) + req.Retries(3) + + return &HttpClient{BeegoHTTPRequest: req} +} + +func Post(url string) *HttpClient { + return NewHttpClient(url, "POST") +} + +func Get(url string) *HttpClient { + return NewHttpClient(url, "GET") +} + +type ProxyClient struct { + *httplib.BeegoHTTPRequest +} + +func NewProxyClient(url, method string, caCrt, cert, key []byte) *ProxyClient { + pool := x509.NewCertPool() + + pool.AppendCertsFromPEM(caCrt) + + cliCrt, err := tls.X509KeyPair(cert, key) + if err != nil { + return nil + } + + tlsConfig := &tls.Config{ + RootCAs: pool, + Certificates: []tls.Certificate{cliCrt}, + } + + defaultSetting := httplib.BeegoHTTPSettings{ + UserAgent: "JDCPS-AGENT", + ConnectTimeout: 1 * time.Second, + ReadWriteTimeout: 1 * time.Second, + Gzip: true, + EnableCookie: false, + TLSClientConfig: tlsConfig, + Retries: 3, + } + + r := httplib.NewBeegoRequest(url, method) + if r == nil { + return nil + } + r = r.Setting(defaultSetting) + + return &ProxyClient{BeegoHTTPRequest: r} +} + +func ProxyPost(url string, caCrt, cert, key []byte) *ProxyClient { + return NewProxyClient(url, "POST", caCrt, cert, key) +} + +func ProxyGet(url string, caCrt, cert, key []byte) *ProxyClient { + return NewProxyClient(url, "GET", caCrt, cert, key) +} diff --git a/bmp-monitor-proxy/api/const.go b/bmp-monitor-proxy/api/const.go new file mode 100644 index 0000000..1a67db0 --- /dev/null +++ b/bmp-monitor-proxy/api/const.go @@ -0,0 +1,28 @@ +package api + +const ( + API_OK = iota + API_NO_PARAMETER + API_PARAMETER + API_NORESULT + API_REMOTE_ERROR + API_UNKNOWN = 99 + API_URL_ERROR = 403 +) + +var APICodeMap = map[int]string{ + API_OK: "Success", + API_NO_PARAMETER: "No Parameter", + API_PARAMETER: "Parameter Error", + API_NORESULT: "No Result", + API_REMOTE_ERROR: "Remote Error", + API_UNKNOWN: "Unknown", + API_URL_ERROR: "url error", +} + +type ProxyResponse struct { + Code int `json:"code"` + Message string `json:"message"` + Data interface{} `json:"data"` + RequestId string `json:"requestId"` +} diff --git a/bmp-monitor-proxy/api/models/AgentStatus.go b/bmp-monitor-proxy/api/models/AgentStatus.go new file mode 100644 index 0000000..bb91473 --- /dev/null +++ b/bmp-monitor-proxy/api/models/AgentStatus.go @@ -0,0 +1,37 @@ +package models + +import ( + "encoding/json" +) + +const ( + AGENT_UNKNOWN = iota + AGENT_OK + AGENT_STOP +) + +type AgentStatus struct { + InstanceID string `json:"instance_id"` + SN string `json:"sn"` + AgentVersion string `json:"agent_version"` + Timestamp int64 `json:"timestamp"` + Status int `json:"status"` +} + +func (o AgentStatus) JSON() ([]byte, error) { + + if json, err := json.Marshal(o); err != nil { + return nil, err + } else { + return json, nil + } +} + +func (o *AgentStatus) FromJSON(str []byte) error { + + if err := json.Unmarshal(str, o); err != nil { + return err + } else { + return nil + } +} diff --git a/bmp-monitor-proxy/api/models/Instance.go b/bmp-monitor-proxy/api/models/Instance.go new file mode 100644 index 0000000..93d09f9 --- /dev/null +++ b/bmp-monitor-proxy/api/models/Instance.go @@ -0,0 +1,60 @@ +package models + +import ( + "encoding/json" +) + +type Instance struct { + RequestID string `json:"requestId"` + Result InstanceResult `json:"result,omitempty"` + Error struct { + Code int `json:"code,omitempty"` + Status string `json:"status,omitempty"` + Message string `json:"message,omitempty"` + } `json:"error,omitempty"` +} + +type InstanceResult struct { + Instance InstanceDetail `json:"instance"` +} + +type InstanceDetail struct { + // 实例uuid + InstanceID string `json:"instanceId"` // 实例ID(uuid) + // 机房uuid + IDcID string `json:"idcId"` + // 机房名称 + IdcName string `json:"idcName"` + // 实例所属项目UUID + ProjectID string `json:"projectId"` + // 实例所属用户UUID + UserID string `json:"userId"` + // 实例名称 + InstanceName string `json:"instanceName"` + // 设备uuid + DeviceID string `json:"deviceId"` + // 设备SN + Sn string `json:"sn"` + // 带外管理IP + IloIP string `json:"iloIp"` + // 机型uuid + DeviceTypeID string `json:"deviceTypeId"` +} + +func (o Instance) JSON() ([]byte, error) { + + if json, err := json.Marshal(o); err != nil { + return nil, err + } else { + return json, nil + } +} + +func (o *Instance) FromJSON(str []byte) error { + + if err := json.Unmarshal(str, o); err != nil { + return err + } else { + return nil + } +} diff --git a/bmp-monitor-proxy/api/models/MonitorPut.go b/bmp-monitor-proxy/api/models/MonitorPut.go new file mode 100644 index 0000000..ae55e63 --- /dev/null +++ b/bmp-monitor-proxy/api/models/MonitorPut.go @@ -0,0 +1,48 @@ +package models + +import ( + "encoding/json" + + sdkmodels "git.jd.com/jcloud-api-gateway/jcloud-sdk-go/services/monitor/models" +) + +type MonitorPut struct { + Source string `json:"source"` + Region string `json:"region,omitempty"` + InstanceId string `json:"instance_id,omitempty"` + SN string `json:"sn,omitempty"` + DataPoints []sdkmodels.DataPointX `json:"data_points"` +} + +type MonitorPutResponse struct { + RequestId string `json:"request_id,omitempty"` + Data string `json:"data,omitempty"` + Message string `json:"message,omitempty"` + StatusCode int `json:"status_code"` +} + +type MonitoCloudPutResponse struct { + RequestId string `json:"requestId,omitempty"` + Result struct { + Failed int `json:"failed,omitempty"` + Success int `json:"success,omitempty"` + } `json:"result,omitempty"` +} + +func (o MonitorPut) JSON() ([]byte, error) { + + if json, err := json.Marshal(o); err != nil { + return nil, err + } else { + return json, nil + } +} + +func (o *MonitorPut) FromJSON(str []byte) error { + + if err := json.Unmarshal(str, o); err != nil { + return err + } else { + return nil + } +} diff --git a/bmp-monitor-proxy/api/models/Pin.go b/bmp-monitor-proxy/api/models/Pin.go new file mode 100644 index 0000000..9188221 --- /dev/null +++ b/bmp-monitor-proxy/api/models/Pin.go @@ -0,0 +1,14 @@ +package models + +type PinResult struct { + RequestID string `json:"requestId"` + Result struct { + Pin string `json:"pin,omitempty"` + Tenant string `json:"tenant,omitempty"` + } `json:"result,omitempty"` + Error struct { + Code int `json:"code,omitempty"` + Status string `json:"status,omitempty"` + Message string `json:"message,omitempty"` + } `json:"error,omitempty"` +} diff --git a/bmp-monitor-proxy/api/models/ProxyPut.go b/bmp-monitor-proxy/api/models/ProxyPut.go new file mode 100644 index 0000000..18d4fc6 --- /dev/null +++ b/bmp-monitor-proxy/api/models/ProxyPut.go @@ -0,0 +1,43 @@ +package models + +import ( + "encoding/json" +) + +type ProxyPut struct { + SN string `json:"sn"` + DataPoints []DataPointA `json:"dataPoints"` +} + +type DataPointA struct { + + /* 监控指标名称,长度不超过255字节,只允许英文、数字、下划线_、点., [0-9][a-z] [A-Z] [. _ ], 其它会返回err */ + Metric string `json:"metric"` + + /* 数据维度,数据类型为map类型,最多五个标签,尽量不传或少传。总长度不大于255字节,只允许英文、数字、下划线_、点., [0-9][a-z] [A-Z] [. _ ], 其它会返回err (Optional) */ + Tags map[string]string `json:"tags"` + + /* 秒级时间戳,早于当前时间30天的不能写入;建议的上报时间戳:上报时间间隔的整数倍,如上报间隔为5s,则建议上报的时间戳为 timestamp = current timestamp - (current timestamp % time interval) = 1487647187 - (1487647187 % 5) = 1487647187 -2 = 1487647185 */ + Timestamp int64 `json:"timestamp"` + + /* 监控的值。number or string。最大值为long.MAX_VALUE=9223372036854775807=263-1。累计类型的指标,累计到最大值后需要翻转为0,重新开始计数。翻转后不影响速率的计算。 */ + Value float64 `json:"value"` +} + +func (o ProxyPut) JSON() ([]byte, error) { + + if json, err := json.Marshal(o); err != nil { + return nil, err + } else { + return json, nil + } +} + +func (o *ProxyPut) FromJSON(str []byte) error { + + if err := json.Unmarshal(str, o); err != nil { + return err + } else { + return nil + } +} diff --git a/bmp-monitor-proxy/api/models/const.go b/bmp-monitor-proxy/api/models/const.go new file mode 100644 index 0000000..93eae7d --- /dev/null +++ b/bmp-monitor-proxy/api/models/const.go @@ -0,0 +1,28 @@ +package models + +const ( + APP_CODE string = "jcloud" + SERVICE_CODE string = "bmp" + + METRIC_CPU_UTIL string = "bmp.cpu.util" + METRIC_MEMORY_USED string = "bmp.memory.used" + METRIC_MEMORY_UTIL string = "bmp.memory.util" + METRIC_DISK_USED string = "bmp.disk.used" + METRIC_DISK_UTIL string = "bmp.disk.util" + METRIC_DISK_MOUNTPOINT_USED string = "bmp.disk.partition.used" //新增 + METRIC_DISK_MOUNTPOINT_UTIL string = "bmp.disk.partition.util" //新增 + METRIC_DISK_BYTES_READ string = "bmp.disk.bytes.read" + METRIC_DISK_BYTES_WRITE string = "bmp.disk.bytes.write" + METRIC_DISK_IOPS_READ string = "bmp.disk.counts.read" + METRIC_DISK_IOPS_WRITE string = "bmp.disk.counts.write" + METRIC_NETWORK_BYTES_IN string = "bmp.network.bytes.ingress" + METRIC_NETWORK_BYTES_OUT string = "bmp.network.bytes.egress" + METRIC_NETWORK_PACKETS_IN string = "bmp.network.packets.ingress" + METRIC_NETWORK_PACKETS_OUT string = "bmp.network.packets.egress" + METRIC_AVG_LOAD1 string = "bmp.avg.load1" + METRIC_AVG_LOAD5 string = "bmp.avg.load5" + METRIC_AVG_LOAD15 string = "bmp.avg.load15" + METRIC_TCP_CONNECT_TOTAL string = "bmp.tcp.connect.total" + METRIC_TCP_CONNECT_ESTABLISHED string = "bmp.tcp.connect.established" + METRIC_PROCESS_TOTAL string = "bmp.process.total" +) diff --git a/bmp-monitor-proxy/api/models/device_tags.go b/bmp-monitor-proxy/api/models/device_tags.go new file mode 100644 index 0000000..7add54f --- /dev/null +++ b/bmp-monitor-proxy/api/models/device_tags.go @@ -0,0 +1,84 @@ +package models + +import ( + "encoding/json" + + "coding.jd.com/bmp/agent-proxy-jdstack/util" + log "git.jd.com/cps-golang/log" +) + +// GetDeviceTagsFromRedis read CPS list from redis, according IDC ID in config file +func GetDeviceTagsFromRedis(logger *log.Logger, key string, filed string) ([]string, error) { + + tags := []string{} + data, err := util.HGetObjectFromRedis(key, filed) + if err != nil { + logger.Warnf("get device tags by sn error, key: %s, field: %s, error: %s", key, filed, err.Error()) + return []string{}, err + } + err = json.Unmarshal([]byte(data), &tags) + if err != nil { + logger.Warnf("get device tags json unmarshal error: %s, origin msg: %s", err.Error(), data) + return []string{}, err + + } + return tags, nil +} + +// PutDeviceTags2Redis ... +func PutDeviceTags2Redis(logger *log.Logger, instanceID string, reqObj ProxyPut) error { + devicestags := []string{} + mountpointTags := []string{} + nicTags := []string{} + for _, dataPointX := range reqObj.DataPoints { + if dataPointX.Metric == "bmp.disk.bytes.read" { + if dataPointX.Tags["device"] != "" { + devicestags = append(devicestags, dataPointX.Tags["device"]) + } + } else if dataPointX.Metric == "bmp.disk.partition.used" { + if dataPointX.Tags["device"] != "" { + mountpointTags = append(mountpointTags, dataPointX.Tags["device"]) + } + + } else if dataPointX.Metric == "bmp.network.bytes.ingress" { + if dataPointX.Tags["device"] != "" { + nicTags = append(nicTags, dataPointX.Tags["device"]) + } + } + } + + datas := map[string]interface{}{} + if len(devicestags) > 0 { + tagByte, err := json.Marshal(devicestags) + if err != nil { + logger.Warnf("putDeviceTags2Redis marshal error:%s", err.Error()) + } else { + datas["disk"] = string(tagByte) + } + } + if len(mountpointTags) > 0 { + tagByte, err := json.Marshal(mountpointTags) + if err != nil { + logger.Warnf("putMountpointTags2Redis marshal error:%s", err.Error()) + } else { + datas["mountpoint"] = string(tagByte) + } + } + if len(nicTags) > 0 { + tagByte, err := json.Marshal(nicTags) + if err != nil { + logger.Warnf("putNicTags2Redis marshal error:%s", err.Error()) + } else { + datas["nic"] = string(tagByte) + } + } + + if len(datas) > 0 { + if err := util.HMSetObjectToRedis(instanceID, datas); err != nil { + logger.Warnf("HMSetObjectToRedis error:", err.Error()) + return err + } + } + + return nil +} diff --git a/bmp-monitor-proxy/api/openapi.go b/bmp-monitor-proxy/api/openapi.go new file mode 100644 index 0000000..e2756ce --- /dev/null +++ b/bmp-monitor-proxy/api/openapi.go @@ -0,0 +1,13 @@ +package api + +// var ( +// cpsClient *CpsClient +// ) + +func init() { + // accessKey := "35DDDCFFB86CF2D494F0F3B6B0B3EF68" + // secretKey := "93C107EF1F3A0C46C6329C04F561A29E" + // credentials := core.NewCredentials(accessKey, secretKey) + + // CpsClient = client.NewCpsClient(credentials) +} diff --git a/bmp-monitor-proxy/bmp-monitor-proxy b/bmp-monitor-proxy/bmp-monitor-proxy new file mode 100755 index 0000000..0dd7d29 Binary files /dev/null and b/bmp-monitor-proxy/bmp-monitor-proxy differ diff --git a/bmp-monitor-proxy/bmp-monitor-proxy.Dockerfile b/bmp-monitor-proxy/bmp-monitor-proxy.Dockerfile new file mode 100644 index 0000000..5937857 --- /dev/null +++ b/bmp-monitor-proxy/bmp-monitor-proxy.Dockerfile @@ -0,0 +1,11 @@ +FROM golang:1.17-alpine AS builder +ENV GOPROXY https://goproxy.cn +WORKDIR /usr/src/bmp-monitor-proxy +COPY . . +RUN go build -o /tmp/bmp-monitor-proxy . + +FROM alpine:3.16 +WORKDIR /home/bmp/bmp-monitor-proxy +COPY --from=builder /tmp/bmp-monitor-proxy . +COPY ./conf ./conf +CMD ["./bmp-monitor-proxy"] diff --git a/bmp-monitor-proxy/bmp_vendor/ironic-common/go.mod b/bmp-monitor-proxy/bmp_vendor/ironic-common/go.mod new file mode 100644 index 0000000..5364f89 --- /dev/null +++ b/bmp-monitor-proxy/bmp_vendor/ironic-common/go.mod @@ -0,0 +1,3 @@ +module git.jd.com/cps-golang/ironic-common + +go 1.17 diff --git a/bmp-monitor-proxy/bmp_vendor/ironic-common/ironic/common/ErrorCode/ErrorCode.go b/bmp-monitor-proxy/bmp_vendor/ironic-common/ironic/common/ErrorCode/ErrorCode.go new file mode 100644 index 0000000..68743e6 --- /dev/null +++ b/bmp-monitor-proxy/bmp_vendor/ironic-common/ironic/common/ErrorCode/ErrorCode.go @@ -0,0 +1,134 @@ +package ErrorCode + +const ( + // 此操作需要的预置条件不满足 400 + FAILED_PRECONDITION = "FAILED_PRECONDITION" + + // 参数错误 400 + INVALID_ARGUMENT = "INVALID_ARGUMENT" + + // 缺少参数 400 + MISSING_ARGUMENT = "MISSING_ARGUMENT" + + // 参数类型不匹配400 + MISMATCH_ARGUMENT_TYPE = "MISMATCH_ARGUMENT_TYPE" + + // 无效的action 400 + INVALID_ACTION = "INVALID_ACTION" + + // 参数超出范围 400 + OUT_OF_RANGE = "OUT_OF_RANGE" + + // 缺少Multipart 400 + MISSING_MULTIPART = "MISSING_MULTIPART" + + // 缺少header信息 400 + MISSING_HEADER = "MISSING_HEADER" + + // pathVariable参数错误 400 + INVALID_PATHVARIABLE = "INVALID_PATHVARIABLE" + + // 验证失败 401 + UNAUTHENTICATED = "UNAUTHENTICATED" + + // 用户未激活 402 + USER_NOT_ACTIVE = "USER_NOT_ACTIVE" + + // 没有权限 403 + HTTP_FORBIDDEN = "HTTP_FORBIDDEN" + + // 找不到对象 404 + NOT_FOUND = "NOT_FOUND" + + // 操作终止 409 + ABORTED = "ABORTED" + + // 对象已存在 409 + ALREADY_EXISTS = "ALREADY_EXISTS" + + // 媒体类型不支持 415 + UNSUPPORTED_MEDIA_TYPE = "UNSUPPORTED_MEDIA_TYPE" + + // 不支持的请求方法 405 + UNSUPPORTED_HTTP_REQUEST_METHOD = "UNSUPPORTED_HTTP_REQUEST_METHOD" + + // 配额不足 429 + QUOTA_EXCEEDED = "QUOTA_EXCEEDED" + + // 库存不足429 + STOCK_SHORTAGE = "STOCK_SHORTAGE" + + // 未知错误 500 + UNKNOWN = "UNKNOWN" + + // 内部错误 500 + INTERNAL = "INTERNAL" + + // 服务不可用 503 + UNAVAILABLE = "UNAVAILABLE" + + // 会话网关 Timeout 504 + SESSION_GATEWAY_TIMEOUT = "SESSION_GATEWAY_TIMEOUT" + + // 参数错误 + PARAMETER_ERROR = "PARAMETER_ERROR" + + //com.jcloud.cps.ironic.common.ErrorCode + UNSUPPORTED_OPERATION = "UNSUPPORTED_OPERATION" + + // 子网没有可用的内网IP可以分配 400 + EXHAUSTED_SUBNET = "EXHAUSTED_SUBNET" + + EXHAUSTED_PUBLIC_IP = "EXHAUSTED_PUBLIC_IP" + + UNSUPPORTED_RAID_TYPE = "UNSUPPORTED_RAID_TYPE" + + CHANGE_ARE_NOT_ALLOWED = "CHANGE_ARE_NOT_ALLOWED" + + // 权限校验失败 + NO_PERMISSION = "NO_PERMISSION" + + // 资源被占用 + RESOURCE_IN_USE = "RESOURCE_IN_USE" + + // 内网IP超出范围 + PRIVATE_IP_NOT_IN_SUBNET = "PRIVATE_IP_NOT_IN_SUBNET" + + // EIP已经绑定 + EIP_ALREADY_ASSOCIATE = "EIP_ALREADY_ASSOCIATE" + + // EIP未绑定 + EIP_HAS_NOT_ASSOCIATE = "EIP_HAS_NOT_ASSOCIATE" + + // 子网未开通IPv6 + SUBNET_HAS_NOT_ASSIGN_IPV6 = "SUBNET_HAS_NOT_ASSIGN_IPV6" + + // IPV6已经被分配 + IPV6_ALREADY_ASSIGN = "IPV6_ALREADY_ASSIGN" + + // 实例已经绑定EIP + INSTANCE_ALREADY_ASSOCIATE_EIP = "INSTANCE_ALREADY_ASSOCIATE_EIP" + + // 实例还没有绑定EIP + INSTANCE_HAS_NOT_ASSOCIATE_EIP = "INSTANCE_HAS_NOT_ASSOCIATE_EIP" + + // 实例已经绑定IPV6 + INSTANCE_ALREADY_ASSOCIATE_IPV6 = "INSTANCE_ALREADY_ASSOCIATE_IPV6" + + // 基础网路不支持EIP + UNSUPPORTED_EIP_IN_BASIC_NETWORK = "UNSUPPORTED_EIP_IN_BASIC_NETWORK" + + // VPC网络不支持调整带宽 + UNSUPPORTED_MODIFY_BANDWIDTH_IN_VPC_NETWORK = "UNSUPPORTED_MODIFY_BANDWIDTH_IN_VPC_NETWORK" + + // 不支持批量指定内网IP + UNSUPPORTED_BATCH_SPECIFYING_PRIVATE_IP = "UNSUPPORTED_BATCH_SPECIFYING_PRIVATE_IP" + + // 不支持批量指定别名IP + UNSUPPORTED_BATCH_SPECIFYING_ALIAS_IP = "UNSUPPORTED_BATCH_SPECIFYING_ALIAS_IP" + + // 密钥对正在被实例使用 + KEYPAIR_IS_USING_BY_INSTANCE = "KEYPAIR_IS_USING_BY_INSTANCE" + + ARGUMENT_ERROR = "ARGUMENT_ERROR" +) diff --git a/bmp-monitor-proxy/bmp_vendor/ironic-common/ironic/enums/HttpStatus/HttpStatus.go b/bmp-monitor-proxy/bmp_vendor/ironic-common/ironic/enums/HttpStatus/HttpStatus.go new file mode 100644 index 0000000..243c37c --- /dev/null +++ b/bmp-monitor-proxy/bmp_vendor/ironic-common/ironic/enums/HttpStatus/HttpStatus.go @@ -0,0 +1,66 @@ +package HttpStatus + +// refer https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpStatus.html +const ( + ACCEPTED = 202 //Accepted. + ALREADY_REPORTED = 208 //Already Reported. + BAD_GATEWAY = 502 //Bad Gateway. + BAD_REQUEST = 400 //Bad Request. + BANDWIDTH_LIMIT_EXCEEDED = 509 //Bandwidth Limit Exceeded + CHECKPOINT = 103 //Checkpoint. + CONFLICT = 409 //Conflict. + CONTINUE = 100 //Continue. + CREATED = 201 //Created. + EXPECTATION_FAILED = 417 //Expectation Failed. + FAILED_DEPENDENCY = 424 //Failed Dependency. + FORBIDDEN = 403 //Forbidden. + FOUND = 302 //Found. + GATEWAY_TIMEOUT = 504 //Gateway Timeout. + GONE = 410 //Gone. + HTTP_VERSION_NOT_SUPPORTED = 505 //HTTP Version Not Supported. + I_AM_A_TEAPOT = 418 //I'm a teapot. + IM_USED = 226 //IM Used. + INSUFFICIENT_STORAGE = 507 //Insufficient Storage + INTERNAL_SERVER_ERROR = 500 //Internal Server Error. + LENGTH_REQUIRED = 411 //Length Required. + LOCKED = 423 //Locked. + LOOP_DETECTED = 508 //Loop Detected + METHOD_NOT_ALLOWED = 405 //Method Not Allowed. + MOVED_PERMANENTLY = 301 //Moved Permanently. = MOVE//D_TEMPORARILY Deprecated in favor of FOUND which will be returned from HttpStatusvalueOf(302). + MULTI_STATUS = 207 //Multi-Status. + MULTIPLE_CHOICES = 300 //Multiple Choices. + NETWORK_AUTHENTICATION_REQUIRED = 511 //Network Authentication Required. + NO_CONTENT = 204 //No Content. + NON_AUTHORITATIVE_INFORMATION = 203 //Non-Authoritative Information. + NOT_ACCEPTABLE = 406 //Not Acceptable. + NOT_EXTENDED = 510 //Not Extended + NOT_FOUND = 404 //Not Found. + NOT_IMPLEMENTED = 501 //Not Implemented. + NOT_MODIFIED = 304 //Not Modified. + OK = 200 //OK. + PARTIAL_CONTENT = 206 //Partial Content. + PAYLOAD_TOO_LARGE = 413 //Payload Too Large. + PAYMENT_REQUIRED = 402 //Payment Required. + PERMANENT_REDIRECT = 308 //Permanent Redirect. + PRECONDITION_FAILED = 412 //Precondition failed. + PRECONDITION_REQUIRED = 428 //Precondition Required. + PROCESSING = 102 //Processing. + PROXY_AUTHENTICATION_REQUIRED = 407 //Proxy Authentication Required. + REQUEST_HEADER_FIELDS_TOO_LARGE = 431 //Request Header Fields Too Large. + REQUEST_TIMEOUT = 408 //Request Timeout. + REQUESTED_RANGE_NOT_SATISFIABLE = 416 //Requested Range Not Satisfiable. + RESET_CONTENT = 205 //Reset Content. + SEE_OTHER = 303 //See Other. + SERVICE_UNAVAILABLE = 503 //Service Unavailable. + SWITCHING_PROTOCOLS = 101 //Switching Protocols. + TEMPORARY_REDIRECT = 307 //Temporary Redirect. + TOO_EARLY = 425 //Too Early. + TOO_MANY_REQUESTS = 429 //Too Many Requests. + UNAUTHORIZED = 401 //Unauthorized. + UNAVAILABLE_FOR_LEGAL_REASONS = 451 //Unavailable For Legal Reasons. + UNPROCESSABLE_ENTITY = 422 //Unprocessable Entity. + UNSUPPORTED_MEDIA_TYPE = 415 //Unsupported Media Type. + UPGRADE_REQUIRED = 426 //Upgrade Required. + URI_TOO_LONG = 414 //URI Too Long USE_PROXY Deprecated due to security concerns regarding in-band configuration of a proxy + VARIANT_ALSO_NEGOTIATES = 506 //Variant Also Negotiates +) diff --git a/bmp-monitor-proxy/bmp_vendor/ironic-common/ironic/util/util.go b/bmp-monitor-proxy/bmp_vendor/ironic-common/ironic/util/util.go new file mode 100644 index 0000000..5aca77e --- /dev/null +++ b/bmp-monitor-proxy/bmp_vendor/ironic-common/ironic/util/util.go @@ -0,0 +1,77 @@ +package util + +import ( + "encoding/json" + "errors" + "fmt" + "math/rand" + "reflect" + "strconv" + "time" +) + +//GetRandString 借鉴RandomStringUtils.random包生成随机字符串 +// length 随机字符串的长度(不包括前缀) +// uletter 随机字符串是否包含大写字母字符 +// dletter 随机字符串是否包含小写字母字符 +// number 随机字符串是否包含数字字符 +func GetRandString(prefix string, length int32, uletter, dletter, number bool) string { + rand.Seed(time.Now().UnixNano()) + uletters := []rune("ABCDEFGHIGKLMNOPQRSTUVWXYZ") + dletters := []rune("abcdefghijklmnopqrstuvwxyz") + numbers := []rune("0123456789") + source := []rune{} + if uletter { + source = append(source, uletters...) + } + if dletter { + source = append(source, dletters...) + } + if number { + source = append(source, numbers...) + } + if len(source) == 0 { + return "atLeastContainsLetterOrNumber" + } + b := make([]rune, length) + for i := range b { + b[i] = source[rand.Intn(len(source))] + } + return prefix + string(b) +} + +// 跟现有环境一致,格式:aafc4d1b-f696-4ec2-924f-6fd012aa8345 +func GenerateRandUuid() string { + s := GetRandString("", 32, false, true, true) + runes := []rune(s) + return string(runes[0:8]) + "-" + string(runes[8:12]) + "-" + string(runes[12:16]) + "-" + string(runes[16:20]) + "-" + string(runes[20:32]) +} + +func Convert2String(val interface{}) (msg string, err error) { + + if val == nil{ + return "", nil + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool: + msg = strconv.FormatBool(val.(bool)) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + msg = fmt.Sprintf("%v", val) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + msg = fmt.Sprintf("%v", val) + case reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + msg = fmt.Sprintf("%v", val) + case reflect.String: + msg = val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + s, err := json.Marshal(val) + if err == nil { + msg = string(s) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + err = errors.New(fmt.Sprintf("type %s not support convert to string", reflect.TypeOf(val).String())) + default: + err = errors.New(fmt.Sprintf("type %s not support convert to string", reflect.TypeOf(val).String())) + } + return +} diff --git a/bmp-monitor-proxy/bmp_vendor/jcloud-sdk-go/go.mod b/bmp-monitor-proxy/bmp_vendor/jcloud-sdk-go/go.mod new file mode 100644 index 0000000..a888c72 --- /dev/null +++ b/bmp-monitor-proxy/bmp_vendor/jcloud-sdk-go/go.mod @@ -0,0 +1,3 @@ +module git.jd.com/jcloud-api-gateway/jcloud-sdk-go + +go 1.17 diff --git a/bmp-monitor-proxy/bmp_vendor/jcloud-sdk-go/services/monitor/models/DataPointX.go b/bmp-monitor-proxy/bmp_vendor/jcloud-sdk-go/services/monitor/models/DataPointX.go new file mode 100644 index 0000000..9ac8867 --- /dev/null +++ b/bmp-monitor-proxy/bmp_vendor/jcloud-sdk-go/services/monitor/models/DataPointX.go @@ -0,0 +1,33 @@ +// Copyright 2018 JDCLOUD.COM +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// 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. +// +// NOTE: This class is auto generated by the jdcloud code generator program. + +package models + + +type DataPointX struct { + + /* 监控指标名称,长度不超过255字节,只允许英文、数字、下划线_、点., [0-9][a-z] [A-Z] [. _ ], 其它会返回err */ + Metric string `json:"metric"` + + /* 数据维度,数据类型为map类型,最多五个标签,尽量不传或少传。总长度不大于255字节,只允许英文、数字、下划线_、点., [0-9][a-z] [A-Z] [. _ ], 其它会返回err (Optional) */ + Tags *interface{} `json:"tags"` + + /* 秒级时间戳,早于当前时间30天的不能写入;建议的上报时间戳:上报时间间隔的整数倍,如上报间隔为5s,则建议上报的时间戳为 timestamp = current timestamp - (current timestamp % time interval) = 1487647187 - (1487647187 % 5) = 1487647187 -2 = 1487647185 */ + Timestamp int64 `json:"timestamp"` + + /* 监控的值。number or string。最大值为long.MAX_VALUE=9223372036854775807=263-1。累计类型的指标,累计到最大值后需要翻转为0,重新开始计数。翻转后不影响速率的计算。 */ + Value interface{} `json:"value"` +} diff --git a/bmp-monitor-proxy/bmp_vendor/log/.cmd b/bmp-monitor-proxy/bmp_vendor/log/.cmd new file mode 100644 index 0000000..5c2f328 --- /dev/null +++ b/bmp-monitor-proxy/bmp_vendor/log/.cmd @@ -0,0 +1 @@ +rm test.log.FATAL test.log.INFO test.log.WARN diff --git a/bmp-monitor-proxy/bmp_vendor/log/README.md b/bmp-monitor-proxy/bmp_vendor/log/README.md new file mode 100644 index 0000000..f39a094 --- /dev/null +++ b/bmp-monitor-proxy/bmp_vendor/log/README.md @@ -0,0 +1,6 @@ +精简日志库,用于打点统计,监控,告警等场景 +- WARN,FATAL等等级的日志即时打印落盘 + - 一个流量可以打印多条WARN,FATAL日志 +- INFO,DEBUG等级的日志,一个流量只落一条日志 + - 支持字段顺序自定义,便于正则匹配做监控等场景 + - 支持自定义代码段耗时打印,便于后续性能统计分析 diff --git a/bmp-monitor-proxy/bmp_vendor/log/go.mod b/bmp-monitor-proxy/bmp_vendor/log/go.mod new file mode 100644 index 0000000..83d5129 --- /dev/null +++ b/bmp-monitor-proxy/bmp_vendor/log/go.mod @@ -0,0 +1,3 @@ +module git.jd.com/cps-golang/log + +go 1.17 diff --git a/bmp-monitor-proxy/bmp_vendor/log/log.go b/bmp-monitor-proxy/bmp_vendor/log/log.go new file mode 100644 index 0000000..e22e077 --- /dev/null +++ b/bmp-monitor-proxy/bmp_vendor/log/log.go @@ -0,0 +1,249 @@ +package cps_log + +import ( + "encoding/json" + "fmt" + "io" + "log" + "os" + "reflect" + "strings" + "time" +) + +// Level type +type Level uint32 + +const ( + // TraceLevel level. Designates finer-grained informational events than the Debug. + TraceLevel Level = iota + // DebugLevel level. Usually only enabled when debugging. Very verbose logging. + DebugLevel + // InfoLevel level. General operational entries about what's going on inside the + // application. + InfoLevel + // WarnLevel level. Non-critical entries that deserve eyes. + WarnLevel + // ErrorLevel level. Logs. Used for errors that should definitely be noted. + // Commonly used for hooks to send errors to an error tracking service. + ErrorLevel + // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the + // logging level is set to Panic. + FatalLevel + // PanicLevel level, highest level of severity. Logs and then calls panic with the + // message passed to Debug, Info, ... + PanicLevel +) + +var globalDefinedKeys = []string{"time", "logid", "self_t", "all_t"} + +type Logger struct { + data map[string]interface{} + level Level + fileName string + definedKeys []string +} + +func New(filename string) *Logger { + if filename == "" { + log.Fatal("filename must be provided !!!") + return nil + } + l := &Logger{ + data: make(map[string]interface{}), + fileName: filename, + } + l.definedKeys = append([]string{}, globalDefinedKeys...) + l.data["time"] = time.Now().Format("2006-01-02T15:04:05") + return l +} + +func NewLoggerWithConfig(filename string, level Level, definedKeys []string) *Logger { + l := New(filename) + l.SetLevel(level) + l.SetStableFields(definedKeys) + return l +} + +func (l *Logger) SetLevel(level Level) { + l.level = level +} + +//SetStableFields 需要固定每条日志的字段时,通过此接口设置,global在前,userdefined在后 +func (l *Logger) SetStableFields(fields []string) { + l.definedKeys = append(l.definedKeys, fields...) +} + +func (l *Logger) Point(key string, val interface{}) { + l.data[key] = val +} + +func (l *Logger) GetPoint(key string) interface{} { + return l.data[key] +} + +func (l *Logger) TimeStart(key string) { + if _, ok := l.data[key]; ok { + log.Print(fmt.Sprintf("point %s TimeStart more than once, check !!!", key)) + } + l.data[key] = time.Now() + +} + +func (l *Logger) TimeEnd(key string) { + if t, ok := l.data[key]; ok { + v := time.Now().Sub(t.(time.Time)).Milliseconds() + l.data[key] = fmt.Sprintf("%f", float64(v)/1000.0) + } else { + log.Print(fmt.Sprintf("missing call TimeStart before TimeEnd when point %s, check it!!!", key)) + } + +} + +func (l *Logger) PushPoint(key string, val interface{}) { + if _, ok := l.data[key]; !ok { + l.data[key] = []interface{}{} + } + d := l.data[key].([]interface{}) + d = append(d, val) +} + +func (l *Logger) Info(v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Infof(format string, v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warn(v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warnf(format string, v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatal(v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatalf(format string, v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Flush() { + if l.level > DebugLevel { + return + } + var beforeStr, afterStr string + for _, key := range l.definedKeys { + if val, ok := l.data[key]; ok { + if key == "time" { + beforeStr = val.(string) + continue + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + beforeStr = beforeStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + beforeStr = beforeStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + beforeStr = beforeStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Printf("val for %s unknown type!!!", key)) + + } + } + } + for key, val := range l.data { + if exist, _ := inArray(key, l.definedKeys); !exist { + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + afterStr = afterStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + afterStr = afterStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + afterStr = afterStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Sprintf("val for %s unknown type!!!", key)) + } + } + } + + line := strings.TrimSpace(beforeStr) + " " + strings.TrimSpace(afterStr) + "\r\n" + filename := fmt.Sprintf("%s.DEBUG", l.fileName) + WriteFile(filename, line) +} + +func WriteFile(filename, line string) { + TimeStamp := time.Now() + str := filename + "." + TimeStamp.Format("2006010215") + logf, err := os.OpenFile(str, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + if err != nil { + log.Fatal("open filename error:", err.Error()) + } + defer logf.Close() + if _, err := io.WriteString(logf, line); err != nil { + log.Fatal("write line error:", err.Error()) + } +} + +func inArray(val interface{}, array interface{}) (exists bool, index int) { + exists = false + index = -1 + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + index = i + exists = true + return + } + } + } + return +} diff --git a/bmp-monitor-proxy/build.sh b/bmp-monitor-proxy/build.sh new file mode 100644 index 0000000..f8595d8 --- /dev/null +++ b/bmp-monitor-proxy/build.sh @@ -0,0 +1,124 @@ +#!/bin/bash +############################################################################### +#编译脚本的原理是将编译结果放到output目录中,这个样例模版提供一个产生 +#一个最基本golang运行程序包的编译脚本,对于特殊的需求请酌情考虑 +# +#1、该脚本支持参数化,参数将传入build_package函数(内容为最终执行的编译命令) +# ,用$1,$2....表示,第1,2...个参数 +#2、部署需要启动程序,所以需要提供control文件放在当前目录中,用于启动和 +# 监控程序状态 + +###############用户修改部分################ +readonly PROJECT_NAME="cps-agent-proxy" #项目名称,相对于$GOPATH/src文件夹所在的目录,可选项 +readonly PACKAGE_DIR_NAME=main.go #main文件相对于src文件夹所在的目录,可选项 +readonly PACKAGE_BIN_NAME=cps-agent-proxy #定义产出的运行程序名,必填项 +readonly CONF_DIR_NAME="conf" #定义配置文件目录,此路径为相对路径,可选项 +readonly OTHERS_DIR_NAME="" #定义其它文件目录,多个目录以空格区分,此路径为相对路径,可选项 +#最终的抽包路径为$OUTPUT +########################################### + +if [[ "${PACKAGE_BIN_NAME}" == "" ]];then + echo "Please set "PACKAGE_BIN_NAME" value" + exit 1 +fi + +function set_work_dir +{ + readonly OUTPUT=$(pwd)/output + readonly WORKSPACE_DIR=$(pwd) +} + +#清理编译构建目录操作 +function clean_before_build +{ + cd ${WORKSPACE_DIR} + rm -rf bin pkg + rm -rf ${OUTPUT} +} + +#初始化编译环境 +function prepare_package() +{ + if [ ! -z "$PROJECT_NAME" ];then + mkdir -p src/$PROJECT_NAME + copy_files=`ls |grep -vw 'src'` + cp -rf $copy_files src/$PROJECT_NAME/ + fi +} + +#实际的编译命令 +#这个函数中可使用$1,$2...获取第1,2...个参数 +function build_package() +{ + cd ${WORKSPACE_DIR} + # export GOPATH=$(pwd) + go clean + echo $(pwd) + echo $(ls) + go build -v -gcflags="-N -l" -o ${PACKAGE_BIN_NAME} ${PACKAGE_DIR_NAME} || return 1 +} + +#建立最终发布的目录 +function build_dir +{ + mkdir -p ${OUTPUT}/bin || return 1 +} + +function dir_not_empty() +{ + if [[ ! -d $1 ]];then + return 1 + fi + if [[ $(ls $1|wc -l) -eq 0 ]];then + return 1 + fi + return 0 +} + +#拷贝编译结果到发布的目录 +function copy_result +{ + cd ${WORKSPACE_DIR} + cp -r ${PACKAGE_BIN_NAME} ${OUTPUT}/bin/ || return 1 + cp -r ./control ${OUTPUT}/bin || return 1 + dir_not_empty ${WORKSPACE_DIR}/${CONF_DIR_NAME} && mkdir -p ${OUTPUT}/${CONF_DIR_NAME} + cp -rf ./${CONF_DIR_NAME}/* ${OUTPUT}/${CONF_DIR_NAME}/ + test -z "$OTHERS_DIR_NAME" || cp -rf $OTHERS_DIR_NAME ${OUTPUT}/ + return 0 +} + +#执行 +function main() +{ + cd $(dirname $0) + set_work_dir + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Cleaning...' + clean_before_build || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Clean completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'preparng...' + prepare_package || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'prepare completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Building...' + build_package $@ || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Build completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Making dir...' + build_dir || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Make completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy result to publish dir...' + copy_result || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy completed' + echo + + exit 0 +} + +main $@ diff --git a/bmp-monitor-proxy/build/jdcps-agent-v1.0.0.bin b/bmp-monitor-proxy/build/jdcps-agent-v1.0.0.bin new file mode 100755 index 0000000..4b223ee Binary files /dev/null and b/bmp-monitor-proxy/build/jdcps-agent-v1.0.0.bin differ diff --git a/bmp-monitor-proxy/build/jdcps-agent-v2.0.0.bin b/bmp-monitor-proxy/build/jdcps-agent-v2.0.0.bin new file mode 100755 index 0000000..0cd1ddf Binary files /dev/null and b/bmp-monitor-proxy/build/jdcps-agent-v2.0.0.bin differ diff --git a/bmp-monitor-proxy/build/jdcps-agent-v3.0.0.bin b/bmp-monitor-proxy/build/jdcps-agent-v3.0.0.bin new file mode 100755 index 0000000..471b97a Binary files /dev/null and b/bmp-monitor-proxy/build/jdcps-agent-v3.0.0.bin differ diff --git a/bmp-monitor-proxy/build/jdcps-agent-windows.tgz b/bmp-monitor-proxy/build/jdcps-agent-windows.tgz new file mode 100644 index 0000000..af8fb5f Binary files /dev/null and b/bmp-monitor-proxy/build/jdcps-agent-windows.tgz differ diff --git a/bmp-monitor-proxy/build/jdcps-agent.bin b/bmp-monitor-proxy/build/jdcps-agent.bin new file mode 100755 index 0000000..409675f Binary files /dev/null and b/bmp-monitor-proxy/build/jdcps-agent.bin differ diff --git a/bmp-monitor-proxy/conf/proxy.ini b/bmp-monitor-proxy/conf/proxy.ini new file mode 100644 index 0000000..4b12814 --- /dev/null +++ b/bmp-monitor-proxy/conf/proxy.ini @@ -0,0 +1,74 @@ + +appname = bmp-monitor-proxy +runmode = "${BMP_MONITOR_PROXY_RUNMODE||dev}" +sessionon = false +autorender = false +graceful = true +httpaddr = "" +httpport = 8805 +copyrequestbody = true +servername = "BMP_MONITOR_PROXY" + + +app.agent.heartbeat.timeout = 300 + + +log.level=DEBUG +log.max.history=10 +log.path=/var/log/bmp/bmp-monitor-proxy + + + +[dev] +recoverpanic = false +enablegzip = false +enableerrorsshow = true +enableadmin = true +adminport = 9201 + + + +bmp_redis_host=${BMP_REDIS_HOST||10.226.192.72} +bmp_redis_port=${BMP_REDIS_PORT||16379} +bmp_redis_db=${BMP_REDIS_DB||1} +bmp_redis_namespace=${BMP_REDIS_DB||BMP:OOB:AGENT} +bmp_redis_password=${BMP_REDIS_PASSWORD||LpK9Jq12Zf} + +openapi_host=${BMP_OPENAPI_HOST||10.208.12.72} +openapi_port=${BMP_OPENAPI_PORT||8801} + + +api.cps = "/v1/offline/instance/queryBySn" +prometheus_gateway_host = ${BMP_PUSHGATEWAY_HOST||10.208.12.75} +prometheus_gateway_port = ${BMP_PUSHGATEWAY_PORT||9091} + + + + + + + + + +[prod] +recoverpanic = true +enablegzip = true +enableerrorsshow = false +enableerrorsrender = false +enableadmin = true +adminport = 9201 + +bmp_redis_host=${BMP_REDIS_HOST||10.226.192.72} +bmp_redis_port=${BMP_REDIS_PORT||16379} +bmp_redis_db=${BMP_REDIS_DB||1} +bmp_redis_namespace=${BMP_REDIS_DB||BMP:OOB:AGENT} +bmp_redis_password=${BMP_REDIS_PASSWORD||LpK9Jq12Zf} + +openapi_host=${BMP_OPENAPI_HOST||10.208.12.72} +openapi_port=${BMP_OPENAPI_PORT||8801} + + +api.cps = "/v1/offline/instance/queryBySn" +prometheus_gateway_host = ${BMP_PUSHGATEWAY_HOST||10.208.12.75} +prometheus_gateway_port = ${BMP_PUSHGATEWAY_PORT||9091} + diff --git a/bmp-monitor-proxy/constant/constant.go b/bmp-monitor-proxy/constant/constant.go new file mode 100644 index 0000000..739936d --- /dev/null +++ b/bmp-monitor-proxy/constant/constant.go @@ -0,0 +1,151 @@ +package constant + +import "fmt" + +var ( + OK RespMsg + INVALID_ARGUMENT RespMsg + INVALID_ARGUMENT_WITH_ARGS RespMsg + NO_LOGIN_PIN RespMsg + AUTH_NOT_LOGIN RespMsg + AUTH_BASIC_AUTH_ERROR RespMsg + AUTH_ERROR_FOR_AUTH_AND_USERID RespMsg + INVALID_ARGUMENT_OUT_OF_RANGE RespMsg + RATE_LIMIT RespMsg + INTERNAL_ERROR RespMsg + NOT_FOUND RespMsg + NOT_FOUND_WITH_ARGS RespMsg + CANCELLED RespMsg + CANCELLEDWithArgs RespMsg + PermissionDenyForObject RespMsg + NOT_SUPPORTED RespMsg +) + +type RespMsg struct { + Code int `json:"code"` + MessageEn string `json:"message_en"` + Messagech string `json:"message_ch"` + Status string `json:"status"` +} + +func init() { + OK = RespMsg{ + 200, + "OK", + "成功", + "OK", + } + INVALID_ARGUMENT = RespMsg{ + 400, + "Parameters error", + "参数错误", + "INVALID_ARGUMENT", + } + INVALID_ARGUMENT_WITH_ARGS = RespMsg{ + 400, + "%s", + "%s", + "INVALID_ARGUMENT", + } + AUTH_NOT_LOGIN = RespMsg{ + 400, + "Login Please", + "请先登录", + "AUTH_NOT_LOGIN", + } + AUTH_BASIC_AUTH_ERROR = RespMsg{ + 401, + "Unauthorized", + "认证失败或者权限错误", + "AUTH_ERROR_OR_PERMISSION_DENIED", + } + AUTH_ERROR_FOR_AUTH_AND_USERID = RespMsg{ + 401, + "Unauthorized", + "认证失败,auth和userid信息不一致", + "AUTH_ERROR_FOR_INVALID_AUTH_USERID", + } + RATE_LIMIT = RespMsg{ + 429, + "Requests are too frequent", + "请求过于频繁", + "RATE_LIMIT", + } + INTERNAL_ERROR = RespMsg{ + 500, + "Internal error", + "内部错误", + "INTERNAL", + } + NOT_FOUND = RespMsg{ + 404, + "Not found", + "找不到对象", + "NOT_FOUND", + } + NOT_FOUND_WITH_ARGS = RespMsg{ + 404, + "%s Not found", + "%s 找不到对象", + "NOT_FOUND", + } + CANCELLED = RespMsg{ + 400, + "Operation cancelled", + "取消操作", + "CANCELLED", + } + NOT_SUPPORTED = RespMsg{ + 400, + "Operation not allowed", + "不支持此操作", + "NOT ALLOWEDS", + } + CANCELLEDWithArgs = RespMsg{ + 400, + "%s", + "%s", + "CANCELLED", + } + PermissionDenyForObject = RespMsg{ + 401, + "permission denied", + "无操作权限", + "PERMISSION DENIED", + } +} + +func BuildNotFoundWithArgs(c, e string) RespMsg { + return RespMsg{ + 404, + fmt.Sprintf("%s Not found", e), + fmt.Sprintf("%s 找不到对象", c), + "NOT_FOUND", + } +} +func BuildCANCELLEDWithArgs(c, e string) RespMsg { + return RespMsg{ + 400, + e, + c, + "CANCEL", + } +} + +func BuildInvalidArgumentWithArgs(c, e string) RespMsg { + return RespMsg{ + 400, + e, + c, + "INVALID_ARGUMENT", + } +} + +func BuildAuthTokenAuthError(c, e string) RespMsg { + return RespMsg{ + 401, + e, + c, + "AUTH_TOKEN_AUTH_ERROR", + } +} diff --git a/bmp-monitor-proxy/control b/bmp-monitor-proxy/control new file mode 100644 index 0000000..eefe8fa --- /dev/null +++ b/bmp-monitor-proxy/control @@ -0,0 +1,127 @@ +#!/bin/bash +set -x +cd "$(dirname $0)"/.. +BASE_DIR=`pwd` +if [ -f default_env.sh ];then + source default_env.sh +fi + +PROC_NAME=cps-agent-proxy # 进程名 一般就是二进制的名字java类程序一般就是java +PROC_PORT=8805 # 程序占用的端口,建议写,程序不占用端口的话只用ps来判断进程是否启动,机器上有同名程序是可能有问题 +WAIT_TIME=60 # 执行START_COMMAND后到程序能完全启动listen端口需要花的时间 + +USER=nginx +app_dir=/home/$USER/$PROC_NAME +mkdir -p $app_dir/log + +START_COMMAND="$app_dir/bin/cps-agent-proxy -c $app_dir/conf/proxy.ini" #在output目录下启动你程序的命令 + + +help(){ + echo "${0} " + exit 1 +} + +checkhealth(){ + if [[ -n "$PROC_PORT" ]] ; then + PORT_PROC=$(/usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d |awk '{print $NF}' |grep -oP '".*"' |sed "s/\"//g" |uniq) + if [ X"$PORT_PROC" = X"$PROC_NAME" ] ; then + echo "1 running" + return 0 + fi + echo "1 not running" + return 1 + else + ps -eo comm,pid |grep -P "^$PROC_NAME" + if [ "$?" = 0 ] ; then + echo "2 running" + return 0 + fi + echo "2 not running" + return 1 + fi +} + + +start(){ + checkhealth + if [ $? = 0 ]; then + echo "[WARN] $PROC_NAME is aleady running!" + return 0 + fi + + + + [ -d "$app_dir" ] && cd $app_dir && rm -rf `ls ${app_dir} | grep -v log` + cp -r $BASE_DIR/* ${app_dir}/ + chown -R $USER:$USER ${app_dir} + su $USER -c "nohup $START_COMMAND > ${app_dir}/log/cps-agent-proxy.log 2>&1 &" + + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ $? = 0 ]; then + echo "Start $PROC_NAME success" + return 0 + fi + done + echo "[ERROR] Start $PROC_NAME failed" + return 1 +} + +stop(){ + if [[ -n "$PROC_PORT" ]] ; then + PROC_ID=$( /usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d | awk '{print $NF}' | grep -oP ',.*,' | grep -oP "\d+" | uniq ) + else + PROC_ID=$(ps -eo comm,pid | grep "^$PROC_NAME" |awk '{print $2}') + fi + + if [[ -z "$PROC_ID" ]] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + + checkhealth + if [ "$?" != "0" ] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + kill $PROC_ID + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + done + + kill -9 $PROC_ID + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + + echo "[ERROR] Stop $PROC_NAME failed" + return 1 +} + +case "${1}" in + start) + start + ;; + stop) + stop + ;; + status|health|checkhealth) + checkhealth + ;; + restart) + stop && start + ;; + *) + help + ;; +esac diff --git a/bmp-monitor-proxy/controllers/baseController.go b/bmp-monitor-proxy/controllers/baseController.go new file mode 100644 index 0000000..7f17321 --- /dev/null +++ b/bmp-monitor-proxy/controllers/baseController.go @@ -0,0 +1,151 @@ +package controllers + +import ( + "encoding/json" + "fmt" + "strconv" + + util "coding.jd.com/bmp/agent-proxy-jdstack/util" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + log "git.jd.com/cps-golang/log" + "github.com/beego/beego/v2/server/web" + beego "github.com/beego/beego/v2/server/web" +) + +type BaseController struct { + beego.Controller + logPoints *log.Logger + Res Response + pageable util.Pageable +} + +type ErrorResponse struct { + // 错误码 + Code int `json:"code"` + // 错误信息 + Message string `json:"message"` + // 错误状态 + Status string `json:"status"` +} + +type Response struct { + // 操作失败结果。成功时有此结构 + Result interface{} `json:"result,omitempty"` + // 操作失败结果。失败时有此结构 + Error *ErrorResponse `json:"error,omitempty"` + // 请求traceId + // required: true + RequestId string `json:"requestId"` +} + +func (b *BaseController) SetErrorResponse(code int, message, status string) { + b.Res.Error = &ErrorResponse{ + Code: code, + Message: message, + Status: status, + } +} + +func (b *BaseController) Prepare() { + web.ReadFromRequest(&b.Controller) + logPath, _ := web.AppConfig.String("log.path") + b.logPoints = log.New(logPath + "/monitor-proxy.log") + b.logPoints.SetStableFields([]string{"method", "uri", "header", "request", "response"}) + b.logPoints.Point("uri", b.Ctx.Request.RequestURI) + b.logPoints.Point("method", b.Ctx.Request.Method) + b.logPoints.Point("header", b.Ctx.Request.Header) + b.logPoints.Point("language", b.GetLanguage()) + + b.logPoints.Point("request", string(b.Ctx.Input.RequestBody)) + b.logPoints.TimeStart("all_t") + b.logPoints.TimeStart("self_t") + traceId := b.GetTraceID() + + b.logPoints.Point("logid", traceId) + b.Ctx.Output.Header("TraceId", traceId) + b.Res = Response{} + + b.pageable = util.Pageable{ + PageNumber: b.getPageNumber(), + PageSize: b.getPageSize(), + } + b.logPoints.Info("url:", b.Ctx.Request.URL) + b.logPoints.Info("body:", string(b.Ctx.Input.RequestBody)) + fmt.Println("[DEBUG MINPING]url:", b.Ctx.Request.URL) + fmt.Println("[DEBUG MINPING]method", b.Ctx.Request.Method) + fmt.Println("[DEBUG MINPING]header", b.Ctx.Request.Header) + fmt.Println("[DEBUG MINPING]body:", string(b.Ctx.Input.RequestBody)) + fmt.Println("[DEBUG MINPING]all header", b.GetAllHeader()) +} + +func (b *BaseController) Finish() { + + b.Res.RequestId = b.GetTraceID() + b.Data["json"] = b.Res + + if b.Res.Error != nil { + b.Ctx.Output.Status = b.Res.Error.Code + } + b.ServeJSON() + + b.logPoints.TimeEnd("self_t") + b.logPoints.TimeEnd("all_t") + b.logPoints.Point("response", b.Data["json"]) + + v, _ := json.Marshal(b.Data["json"]) + b.logPoints.Info("response:", string(v)) + fmt.Println("[DEBUG MINPING]response:", string(v)) + + b.logPoints.Flush() +} + +func (b *BaseController) GetRequestID() string { + if b.Ctx.Request.Header["X-Jdcloud-Request-Id"] != nil { + return b.Ctx.Request.Header["X-Jdcloud-Request-Id"][0] + } + //生成随机字符串logid + logid := commonUtil.GenerateRandUuid() + b.Ctx.Request.Header["X-Jdcloud-Request-Id"] = []string{logid} + return logid +} + +func (b *BaseController) GetLanguage() string { + if b.Ctx.Request.Header["Bmplanguage"] != nil { + language := b.Ctx.Request.Header["Bmplanguage"][0] + return language + } + return "" +} + +func (b *BaseController) GetTraceID() string { + if b.Ctx.Request.Header["Traceid"] != nil { + return b.Ctx.Request.Header["Traceid"][0] + } + //生成随机字符串logid + logid := commonUtil.GenerateRandUuid() + b.Ctx.Request.Header["Traceid"] = []string{logid} + return logid +} + +func (b *BaseController) getPageNumber() int64 { + if l := b.GetString("pageNumber"); l != "" { + if v, err := strconv.ParseInt(l, 10, 64); err == nil { + return v + } + } + return 1 +} + +func (b *BaseController) getPageSize() int64 { + if l := b.GetString("pageSize"); l != "" { + if v, err := strconv.ParseInt(l, 10, 64); err == nil { + return v + } + } + return 20 +} + +func (b *BaseController) GetAllHeader() string { + v, _ := json.Marshal(b.Ctx.Request.Header) + return string(v) +} diff --git a/bmp-monitor-proxy/controllers/device_tags.go b/bmp-monitor-proxy/controllers/device_tags.go new file mode 100644 index 0000000..3c0fb93 --- /dev/null +++ b/bmp-monitor-proxy/controllers/device_tags.go @@ -0,0 +1,93 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/bmp/agent-proxy-jdstack/api/models" + requestTypes "coding.jd.com/bmp/agent-proxy-jdstack/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTagController ... +type DeviceTagController struct { + BaseController +} + +type GetDeviceTagsRequest struct { + InstanceID string `json:"instanceId"` + Metric string `json:"metric"` +} + +// GetDeviceTags ... +func (d *DeviceTagController) GetDeviceTags() { + + req := &requestTypes.GetDeviceTagsRequest{} + + if err := json.Unmarshal(d.Ctx.Input.RequestBody, req); err != nil { + d.logPoints.Warn("DescribeAgentStatus parse body error:", err.Error()) + d.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + req.Validate(d.logPoints) + + var tags []string + var err error + + tags, err = models.GetDeviceTagsFromRedis(d.logPoints, req.InstanceID, req.Metric) + if err != nil { + d.logPoints.Warnf("GetDeviceTagsFromRedis error, instanceID :%s, metric: %s, error: %s", req.InstanceID, req.Metric, err.Error()) + d.Res.Result = map[string][]string{ + "tags": tags, + } + return + } + + //根据原型要求调整默认顺序 + //挂载点默认/,其他 + //网卡默认bond0,没有的话默认eth0,其他 + switch req.Metric { + case "mountpoint": + for k, v := range tags { + if v == "/" { + var part1 []string + var part2 []string + part1 = tags[:k] + if k < len(tags)-1 { + part2 = tags[k+1:] + } + tags = append(append([]string{v}, part1...), part2...) + break + } + } + case "nic": + flag := false + for _, v := range tags { + if v == "bond0" { + tags = []string{v} + flag = true + break + } + } + if !flag { + for k, v := range tags { + if v == "eth0" { + var part1 []string + var part2 []string + part1 = tags[:k] + if k < len(tags)-1 { + part2 = tags[k+1:] + } + tags = append(append([]string{v}, part1...), part2...) + break + } + } + } + } + + d.Res.Result = map[string][]string{ + "tags": tags, + } + return +} diff --git a/bmp-monitor-proxy/controllers/error.go b/bmp-monitor-proxy/controllers/error.go new file mode 100644 index 0000000..12a4b62 --- /dev/null +++ b/bmp-monitor-proxy/controllers/error.go @@ -0,0 +1,5 @@ +package controllers + +type ErrorController struct { + BaseController +} diff --git a/bmp-monitor-proxy/controllers/proxy.go b/bmp-monitor-proxy/controllers/proxy.go new file mode 100644 index 0000000..d6e7ecd --- /dev/null +++ b/bmp-monitor-proxy/controllers/proxy.go @@ -0,0 +1,196 @@ +package controllers + +import ( + "encoding/json" + "time" + + "coding.jd.com/bmp/agent-proxy-jdstack/api" + "coding.jd.com/bmp/agent-proxy-jdstack/api/models" + "coding.jd.com/bmp/agent-proxy-jdstack/logic" + + "coding.jd.com/bmp/agent-proxy-jdstack/global" + responseTypes "coding.jd.com/bmp/agent-proxy-jdstack/types/response" + + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +type ProxyController struct { + BaseController +} + +// Put 上传metric,将SN转换为实例ID,调用Monitor的Put接口 +func (c *ProxyController) Put() { + c.logPoints.Infof("put api start, time:%d", time.Now().Unix()) + req := c.Ctx.Input.RequestBody + + reqObj := models.ProxyPut{} + var instance *models.Instance + + if err := json.Unmarshal(req, &reqObj); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + reqObj = modifyPutDataPoint(reqObj) + c.logPoints.Infof("put api start11, time:%d", time.Now().Unix()) + if v, found := global.Get(reqObj.SN); !found { + if ins, err := api.GetInstanceID(c.logPoints, reqObj.SN); err != nil || ins == nil { + c.logPoints.Warnf("%s GetInstanceID Error: %+v", reqObj.SN, err) + c.SetErrorResponse(httpStatus.BAD_REQUEST, "sn invalid", errorCode.INVALID_ARGUMENT) + return + } else { + // logs.Debug("%s GetInstanceID Response: %+v", reqObj.SN, ins) + if ins.Error.Code > 0 { + c.SetErrorResponse(httpStatus.BAD_REQUEST, ins.Error.Message, errorCode.INVALID_ARGUMENT) + return + } + instance = ins + global.Set(reqObj.SN, instance) + } + } else { + instance = v.(*models.Instance) + } + c.logPoints.Infof("put api start22, time:%d", time.Now().Unix()) + + if instance == nil || instance.Result.Instance.InstanceID == "" { + c.logPoints.Warnf("%s GetInstanceID empty", reqObj.SN) + c.SetErrorResponse(httpStatus.BAD_REQUEST, "sn invalid", errorCode.INVALID_ARGUMENT) + return + } + + models.PutDeviceTags2Redis(c.logPoints, instance.Result.Instance.InstanceID, reqObj) + c.logPoints.Infof("put api start33, time:%d", time.Now().Unix()) + + //上报云监控 + err := logic.PushGateway(c.logPoints, instance, reqObj) + if err != nil { + c.logPoints.Warnf("ProxyController.Put.pushCloudMonitor error:%s", err.Error()) + } + c.logPoints.Infof("put api start44, time:%d", time.Now().Unix()) + + c.Res.Result = responseTypes.CommonResponse{ + Success: err == nil, + } +} + +func (c *ProxyController) Heartbeat() { + + req := c.Ctx.Input.RequestBody + agentStatus := &models.AgentStatus{} + var instance *models.Instance + + if err := json.Unmarshal(req, &agentStatus); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, "body invalid", errorCode.INVALID_ARGUMENT) + + return + } + + if v, found := global.Get(agentStatus.SN); !found { + if ins, err := api.GetInstanceID(c.logPoints, agentStatus.SN); err != nil || ins == nil { + c.logPoints.Warnf("%s GetInstanceID Error: %+v", agentStatus.SN, err) + c.SetErrorResponse(httpStatus.BAD_REQUEST, "sn invalid", errorCode.INVALID_ARGUMENT) + return + } else { + c.logPoints.Infof("%s GetInstanceID Response: %+v", agentStatus.SN, ins) + if ins.Error.Code > 0 { + c.SetErrorResponse(httpStatus.BAD_REQUEST, "sn invalid", errorCode.INVALID_ARGUMENT) + return + } + instance = ins + global.Set(agentStatus.SN, instance) + } + } else { + instance = v.(*models.Instance) + } + + global.Set(instance.Result.Instance.InstanceID, agentStatus) + + c.Res.Result = responseTypes.CommonResponse{ + Success: true, + } + return + +} + +// 客户端升级不便,为了应对业务快速迭代,在procy层对于上报过来的数据点做修正,目前的修正包括如下: +// 1,网卡部分,如果tag中有bond0,则只上报bond0,否则全部上报 +func modifyPutDataPoint(reqObj models.ProxyPut) models.ProxyPut { + + var exist func(string, []string) bool = func(item string, items []string) bool { + for _, i := range items { + if i == item { + return true + } + } + return false + } + + newReqObj := models.ProxyPut{ + SN: reqObj.SN, + DataPoints: []models.DataPointA{}, + } + + netMetrics := []string{"bmp.network.bytes.ingress", "bmp.network.bytes.egress", "bmp.network.packets.ingress", "bmp.network.packets.egress"} + + nicMetrics := []models.DataPointA{} + for _, point := range reqObj.DataPoints { + if exist(point.Metric, netMetrics) { + nicMetrics = append(nicMetrics, point) + } else { + newReqObj.DataPoints = append(newReqObj.DataPoints, point) + } + } + + hasBond0 := false + bond0Metrics := []models.DataPointA{} + + for _, point := range nicMetrics { + if point.Tags != nil { + if point.Tags["device"] == "bond0" { + hasBond0 = true + bond0Metrics = append(bond0Metrics, point) + } + + } + } + + if hasBond0 { + newReqObj.DataPoints = append(newReqObj.DataPoints, bond0Metrics...) + } else { + newReqObj.DataPoints = append(newReqObj.DataPoints, nicMetrics...) + } + + return newReqObj +} + +// func pushCloudMonitor(logger *log.Logger, instance *models.Instance, reqObj models.ProxyPut) (*monitorSdkApis.PutResponse, error) { +// accessKey := beego.AppConfig.DefaultString("openapi.ak", "") +// secretKey := beego.AppConfig.DefaultString("openapi.sk", "") +// credentials := core.NewCredentials(accessKey, secretKey) + +// config := core.NewConfig() +// config.SetScheme(core.SchemeHttp) + +// gateWay := beego.AppConfig.DefaultString("openapi.host", "") +// config.SetEndpoint(gateWay) +// config.SetTimeout(20 * time.Second) + +// monitorClient := monitorSdkClient.NewMonitorClient(credentials) +// monitorClient.SetConfig(config) +// appCode := beego.AppConfig.DefaultString("openapi.appCode", "") +// serviceCode := beego.AppConfig.DefaultString("openapi.serviceCode", "") +// region := instance.Result.Region +// resourceId := instance.Result.InstanceID +// dataPoints := reqObj.DataPoints + +// req1 := monitorSdkApis.NewPutRequest(appCode, serviceCode, region, resourceId, dataPoints) + +// resp1, err := monitorClient.Put(req1) +// logger.Infof("%s Put endpoint: %s, cloudmonitor Response:%+v", reqObj.SN, gateWay, resp1) +// if err != nil { +// logger.Warnf("%s cloudmonitor put Error: %+v", reqObj.SN, resp1.Error) +// return nil, err +// } +// return resp1, nil +// } diff --git a/bmp-monitor-proxy/controllers/status.go b/bmp-monitor-proxy/controllers/status.go new file mode 100644 index 0000000..9f71dc9 --- /dev/null +++ b/bmp-monitor-proxy/controllers/status.go @@ -0,0 +1,62 @@ +package controllers + +import ( + "encoding/json" + "time" + + "coding.jd.com/bmp/agent-proxy-jdstack/api/models" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" + + "coding.jd.com/bmp/agent-proxy-jdstack/global" + + beego "github.com/beego/beego/v2/server/web" +) + +type StatusController struct { + BaseController +} + +type DescribeAgentStatusRequest struct { + InstanceIds []string `json:"instanceIds"` +} + +func (c *StatusController) DescribeAgentStatus() { + + req := DescribeAgentStatusRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.logPoints.Warn("DescribeAgentStatus parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if len(req.InstanceIds) == 0 { + c.SetErrorResponse(httpStatus.BAD_REQUEST, "instanceId empty, invalid", errorCode.INVALID_ARGUMENT) + + return + } + + var tmp *models.AgentStatus + var o []*models.AgentStatus + var ok bool + var ids = req.InstanceIds + for _, id := range ids { + if v, found := global.Get(id); !found { + tmp = &models.AgentStatus{InstanceID: id, Status: models.AGENT_UNKNOWN} + } else { + tmp, ok = v.(*models.AgentStatus) + if tmp == nil || !ok { + tmp = &models.AgentStatus{InstanceID: id, Status: models.AGENT_UNKNOWN} + } else { + tmp.InstanceID = id + if time.Now().Unix()-tmp.Timestamp > beego.AppConfig.DefaultInt64("app.agent.heartbeat.timeout", 300) && tmp.Status == models.AGENT_OK { + tmp.Status = models.AGENT_UNKNOWN + } + } + } + + o = append(o, tmp) + } + + c.Res.Result = o +} diff --git a/bmp-monitor-proxy/doc/API.md b/bmp-monitor-proxy/doc/API.md new file mode 100644 index 0000000..1aa453c --- /dev/null +++ b/bmp-monitor-proxy/doc/API.md @@ -0,0 +1,222 @@ + +### 查询Agent状态 +> schema +> +> HTTP +> +> url +> +> /api/v1/describeAgentStatus +> +> method +> +> POST +> +> request +> +> instance: 实例ID, 多个ID以逗号分隔 +> +> response +> +> 成功: +> ```json +> { +> "code": 0, +> "message": "Success", +> "data": [ +> { +> "instance_id": "cps-h1mtnemztijtpgbmjfexpj0dovm4", +> "sn": "xxxx", +> "version": "v1.0.0-xxx", +> "timestamp": 1553151660, +> "status": 0 +> }, +> { +> "instance_id": "cps-h1mtnemztijtpgbmjfexpj0dovm3", +> "sn": "", +> "version": "", +> "timestamp": 0, +> "status": 2 +> } +> ...... +> ] +> } +> ``` +> 失败: +> ```json +> { +> "code": 1, +> "message": "No Parameter", +> "data": null +> } +> ``` + + +### 代理上报接口 Put +> schema +> +> Mutual TLS +> +> url +> +> /api/v1/put +> +> method +> +> POST +> +> request +> ```json +> { +> "sn": "PF11ZXQG", +> "dataPoints": [ +> { +> "metric": "cps.network.packets.egress", +> "timestamp": 1553151660, +> "value": 1281955, +> "tags": {} +> }, +> { +> "metric": "cps.process.total", +> "timestamp": 1553151660, +> "value": 319, +> "tags": {} +> }, +> ...... +> ] +> } +> ``` +> +> response +> +> 成功: +> ```json +> { +> "code": 0, +> "message": "Success", +> "data": {} +> } +> ``` +> 失败: +> ```json +> { +> "code": 1, +> "message": "No Parameter", +> "data": {} +> } +> ``` +> + + +### Agent心跳上报 Heartbeat +> schema +> +> Mutual TLS +> +> url +> +> /api/v1/heartbeat +> +> method +> +> POST +> +> request +> ```json +> { +> "sn": "PF11ZXQG", +> "agent_version": "0.0.1-v0.0.2-5-g202dea7-dirty-20190321145703", +> "timestamp": 1553151692, +> "status": 0 +> } +> ``` +> +> response +> +> 成功: +> ```json +> { +> "code": 0, +> "message": "Success", +> "data": {} +> } +> ``` +> 失败: +> ```json +> { +> "code": 1, +> "message": "No Parameter", +> "data": {} +> } +> ``` +> + +### 边缘节点代理上报接口 ProxyPut (边缘节点Proxy调用,暂未使用) +> schema +> +> Mutual TLS +> +> url +> +> /api/v1/proxyPut +> +> method +> +> POST +> +> request +> ```json +> { +> "appCode": "jcloud", +> "serviceCode": "cps", +> "dataCenter": null, +> "resourceId": "cps-h1mtnemztijtpgbmjfexpj0dovm4", +> "region": "cn-north-1", +> "dataPoints": [ +> { +> "metric": "cps.network.packets.egress", +> "timestamp": 1553151660, +> "value": 1281955, +> "tags": {} +> }, +> { +> "metric": "cps.process.total", +> "timestamp": 1553151660, +> "value": 319, +> "tags": {} +> }, +> ...... +> ] +> } +> ``` +> +> response +> +> 成功: +> ```json +> { +> "code": 0, +> "message": "Success", +> "data": {} +> } +> ``` +> 失败: +> ```json +> { +> "code": 1, +> "message": "No Parameter", +> "data": {} +> } +> ``` + + +### response code +> +> |Code|含义| +> |-----|----| +> |0|成功| +> |1|缺少参数| +> |2|参数错误| +> |3|无结果| +> |4|远程接口错误| +> |99|未知错误| \ No newline at end of file diff --git a/bmp-monitor-proxy/doc/Metric.md b/bmp-monitor-proxy/doc/Metric.md new file mode 100644 index 0000000..2b88a31 --- /dev/null +++ b/bmp-monitor-proxy/doc/Metric.md @@ -0,0 +1,24 @@ +# 云物理服务器 + + +metric中文展示名称 |metric英文展示名称 | metric名字 | 值类型 | downsample-aggregator | grouping-aggregator | 变化率展示 | tags(必须/不必须) | 上报时间间隔 | 上报 | monitor展示 | 单位转换公式(convertFrom/convertTo) | 前端是否展示 | 是否可用于创建告警规则 | 创建报警规则的特殊需求 | 漏报检查(每小时)预期/阈值 +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ----| ----| ---- | ---- +CPU使用率 | CPU Usage | cps.cpu.util | 时刻 | avg | | n | - | 60s | % | % | | y | y | 无 | +内存使用率 | Memory Usage | cps.memory.util | 时刻 | avg | | n | - | 60s | % | % | | y | y | 无 | +内存使用量 | Memory Used | cps.memory.used | 时刻 | avg | | n | - | 60s |Byte| GB |1/1000000000 | y | y | 无 | +硬盘使用量 | Disk Used | cps.disk.used | 时刻 | avg | | n | device | 60s | Byte | GB | 1/1000000000 | y | y | 无 | +硬盘使用率 | Disk Usage | cps.disk.util | 时刻 | avg | | n | device | 60s | % | % | | y | y | 无 | +硬盘读流量 | Disk Read Traffic | cps.disk.bytes.read | 累计 | last | | y | device | 60s | Byte | Bps | | y | y | 无 | +硬盘写流量 | Disk Write Traffic | cps.disk.bytes.write | 累计 | last | | y | device | 60s | Byte | Bps | | y | y | 无 | +硬盘读IOPS | Disk Read IOPS | cps.disk.counts.read | 累计 | last | | y | device | 60s | 次 | 次/秒 | | y | y | 无 | +硬盘写IOPS | Disk Write IOPS | cps.disk.counts.write | 累计 | last | | y | device | 60s | 次 | 次/秒 | | y | y | 无 | +网卡进流量 | Network Ingress Traffic | cps.network.bytes.ingress | 累计 | last | | y | - | 60s | Byte | bps |8/1 | y | y | 无 | +网卡出流量 | Network Egress Traffic | cps.network.bytes.egress | 累计 | last | | y | - | 60s | Byte | bps | 8/1 | y | y | 无 | +网络进包量 | Network Ingress Packets | cps.network.packets.ingress | 累计 | last | | y | - | 60s | 个 | 个/秒 | | y | y | 无 | +网络出包量 | Network Egress Packets | cps.network.packets.egress | 累计 | last | | y | - | 60s | 个 | 个/秒 | | y | y | 无 | +平均负载1min | Load Average 1min | cps.avg.load1 | 时刻 | avg | | n | - | 60s | - | 无 | | y | y | 无 | +平均负载5min | Load Average 5min | cps.avg.load5 | 时刻 | avg | | n | - | 60s | - | 无 | | y | y | 无 | +平均负载15min | Load Average 15min | cps.avg.load15 | 时刻 | avg | | n | - | 60s | - | 无 | | y | y | 无 | +TCP总连接数 | Total TCP Connections | cps.tcp.connect.total | 时刻 | avg | | n | - | 60s | 个 | 个 | | y | y | 无 | +TCP正常连接数 | Established TCP Connections | cps.tcp.connect.established | 时刻 | avg | | n | - | 60s | 个 | 个 | | y | y | 无 | +总进程数 | Total Process Count | cps.process.total | 时刻 | avg | | n | - | 60s | 个 | 个 | | y | y | 无 | diff --git a/bmp-monitor-proxy/doc/Monitor.md b/bmp-monitor-proxy/doc/Monitor.md new file mode 100644 index 0000000..95165f3 --- /dev/null +++ b/bmp-monitor-proxy/doc/Monitor.md @@ -0,0 +1,355 @@ +# CPS监控接入——接口定义 + +Table of Contents +================= +* [指标上报](#指标上报) +* [查询指标](#查询指标) + + +变更日期 | 变更内容 +---- | ---- +2019-05-09 | 初始化 +2019-05-16 | 接口调整,按照运维平台监控适配 +2019-05-21 | 接口调整,根据前端组件,优化接口格式 +2019-05-23 | 接口调整,去掉Tags,转移到MetricName中 + + +## 指标上报 + +### url + +```http +/put +``` + +### method + +```http +POST +``` + +### 请求参数 + +参数名称 | 类型 | 说明 +---- | ---- | ----- +source | String | 必传参数,云物理机:cps +region | String | 必选参数,如:cn-north-1 +instanceId | String | 必选参数,实例ID +sn | String | 可选参数,云物理机必选参数 +dataPoints | List\ | 必选参数,监控数据 + +**DataPoint** + +参数名称 | 类型 | 说明 +---- | ---- | ----- +metric | String | 写入的指标名称 +timestamp | Long | 秒级时间戳。建议的上报时间戳:上报时间间隔的整数倍,如上报间隔为5s,则建议上报的时间戳为 timestamp = current timestamp - (current timestamp % time interval) = 1487647187 - (1487647187 % 5) = 1487647187 -2 = 1487647185 +valueType | String | int,float +value | Int,float | 监控的值。最大值为long.MAX_VALUE=9223372036854775807=263-1。累计类型的指标,累计到最大值后需要翻转为0,重新开始计数。翻转后不影响速率的计算。 +tags | Map | 标签,0个或多个。最多5个。 + +#### Request + +```json +{ + "source": "cps", + "region": "cn-north-1", + "instanceId": "cps-97fzedyq3fhk7dilhgqgtmiservg", + "sn": "J33WRF1", + "dataPoints": [ + { + "metric": "cps.cpu.util", + "timestamp": 1558060300, + "valueType": "float", + "value": 5.51, + "tags": {} + }, + { + "metric": "cps.disk.used", + "timestamp": 1558060300, + "valueType": "int", + "value": 3221225472, + "tags": { + "device": "sda" + } + }, + { + "metric": "cps.disk.used", + "timestamp": 1558060300, + "valueType": "int", + "value": 64424509440, + "tags": { + "device": "sdb" + } + } + ] +} +``` + +### 响应参数 + + +参数名称 | 类型 | 说明 +---- | ---- | ----- +requestId | String | 请求ID +result | Result | 结果 + +**Result** + +参数名称 | 类型 | 说明 +---- | ---- | ----- +code | Int | 结果码 +message | String | 结果描述 + +#### Response + +```json +{ + "requestId": "bjehoueq3tiu7c5ie6bha2pufsw16a7d", + "result": { + "code": 0, + "message": "success" + } +} +``` + +## 查询接口 + +### url + +```http +/describeMetricData +``` + +### method + +```http +POST +``` + +### 请求参数 + + +参数名称 | 类型 | 说明 +---- | ---- | ---- +source | String | 云物理机:cps +region | String | 地域:可用地域列表。注:该字段将覆盖dataCenter字段 +instanceId | String | 实例ID +metrics | List | 希望获取的指标列表,如为空默认为全部 +startTime | String | 查询时间范围的开始时间, UTC时间,格式:2016-12-11T00:00:00+0800(早于30d时,将被重置为30d)(注意在url中+要转译为%2B故url中为2016-12-11T00:00:00%2B0800) +endTime | String | 查询时间范围的结束时间, UTC时间,格式:2016-12-11T00:00:00+0800(为空时,将由startTime与timeInterval计算得出)(注意在url中+要转译为%2B故url中为2016-12-11T00:00:00%2B0800) +timeInterval | String | 时间间隔:1h,6h,12h,1d,3d,7d,14d固定时间间隔使用固定的聚合粒度 + + +#### Request + +**固定时间间隔** +```json +{ + "source": "cps", + "region": "cn-north-1", + "instanceId": "cps-97fzedyq3fhk7dilhgqgtmiservg", + "metrics": [ + "cps.disk.bytes.read", + "cps.disk.bytes.write" + ], + "timeInterval": "1h" +} +``` +**自定义时间间隔** +```json +{ + "source": "cps", + "region": "cn-north-1", + "instanceId": "cps-97fzedyq3fhk7dilhgqgtmiservg", + "metrics": [ + "cps.disk.bytes.read", + "cps.disk.bytes.write" + ], + "startTime": "2019-05-01T00:00:00+0800", + "endTime": "2019-05-18T00:00:00+0800" +} +``` + +### 响应参数 + +参数名称 | 类型 | 说明 +---- | ---- | ---- +requestId | String | 请求ID +result | Map | 结果 + +**MetricData** + +参数名称 | 类型 | 说明 +---- | ---- | ---- +metric | Metric | Metric信息 +data | List | 监控数据组成的列表 + +**Metric** + +参数名称 | 类型 | 说明 +---- | ---- | ---- +aggregator | String | 聚合类型:last、avg +calculateUnit | String | 单位 +metric | String | metric名称 +metricName | String | tag+metric显示名称 +period | String | 聚合周期 + +**Dps** + +参数名称 | 类型 | 说明 +---- | ---- | ---- +timestamp | Long | 豪秒级时间戳。 +value | float | 监控的值。 + + +#### Response + +**无tags的指标** +```json +{ + "requestId": "bjehoueq3tiu7c5ie6bha2pufsw16a7d", + "result": { + "metricDatas": [ + { + "data": [ + { + "timestamp": 1557990900000, + "value": "0.0000" + }, + { + "timestamp": 1557990960000, + "value": "0.0000" + }, + { + "timestamp": 1557991020000, + "value": "0.0000" + }, + ………… + ], + "metric": { + "calculateUnit": "%", + "metric": "cps.cpu.util", + "metricName": "CPU Usage", + "aggregator": "avg", + "period": "1min" + } + } + ] + } +} + +``` + +**带tags的指标** +```json +{ + "requestId": "bjehoueq3tiu7c5ie6bha2pufsw16a7d", + "result": { + "metricDatas": [ + { + "data": [ + { + "timestamp": 1557990900000, + "value": "0.0000" + }, + { + "timestamp": 1557990960000, + "value": "0.0000" + }, + { + "timestamp": 1557991020000, + "value": "0.0000" + }, + ………… + ], + "tags": [ + { + "tagKey": "device", + "tagValue": "sda" + } + ], + "metric": { + "calculateUnit": "Bps", + "metric": "cps.disk.bytes.read", + "metricName": "sda Disk Read Traffic", + "aggregator": "last", + "period": "1min" + } + }, + { + "data": [ + { + "timestamp": 1557990900000, + "value": "4505.6000" + }, + { + "timestamp": 1557990960000, + "value": "10513.0667" + }, + { + "timestamp": 1557991020000, + "value": "4642.1333" + }, + ………… + ], + "metric": { + "calculateUnit": "Bps", + "metric": "cps.disk.bytes.read", + "metricName": "sdb Disk Read Traffic", + "aggregator": "last", + "period": "1min" + } + }, + { + "data": [ + { + "timestamp": 1557990900000, + "value": "0.0000" + }, + { + "timestamp": 1557990960000, + "value": "0.0000" + }, + { + "timestamp": 1557991020000, + "value": "0.0000" + }, + ………… + ], + "metric": { + "calculateUnit": "Bps", + "metric": "cps.disk.bytes.write", + "metricName": "sda Disk Write Traffic", + "aggregator": "last", + "period": "1min" + } + }, + { + "data": [ + { + "timestamp": 1557990900000, + "value": "4505.6000" + }, + { + "timestamp": 1557990960000, + "value": "10513.0667" + }, + { + "timestamp": 1557991020000, + "value": "4642.1333" + }, + ………… + ], + "metric": { + "calculateUnit": "Bps", + "metric": "cps.disk.bytes.write", + "metricName": "sdb Disk Write Traffic", + "aggregator": "last", + "period": "1min" + } + } + ] + } +} +``` diff --git a/bmp-monitor-proxy/doc/OpenSSL.md b/bmp-monitor-proxy/doc/OpenSSL.md new file mode 100644 index 0000000..dcd0b61 --- /dev/null +++ b/bmp-monitor-proxy/doc/OpenSSL.md @@ -0,0 +1,113 @@ + +# OpenSSL证书生成 + +[TOC] + +## 1. **CA根证书** + +* ca.crt +```bash +openssl genrsa -out conf/cert/ca.pem 2048 +openssl ecparam -genkey -name secp384r1 -out conf/cert/ca.pem +openssl req -config conf/cert/ca.cnf -newkey rsa:2048 -x509 -days 36500 -key conf/cert/ca.pem -out conf/cert/ca.crt +``` + +* ca.cnf +```yaml +[req] +req_extensions = v3_req +distinguished_name = req_distinguished_name +prompt = no + +[req_distinguished_name] +countryName = CN +stateOrProvinceName = Beijing +localityName = Beijing +postalCode = 100105 +streetAddress = CNCC, No.7 Tianchen East Road, Chaoyang District +organizationName = JD Cloud +organizationalUnitName = CPS Dept. +emailAddress = zhouguiqing3@jd.com +0.commonName = jdcps + +[v3_req] +keyUsage = keyEncipherment, dataEncipherment +extendedKeyUsage = serverAuth + +``` + +## 2. **Server证书** +* 生成server.key,server.crt (添加了extfile.cnf) +```bash +openssl genrsa -out conf/cert/server.key 2048 +openssl ecparam -genkey -name secp384r1 -out conf/cert/server.key +openssl req -config conf/cert/server.cnf -new -key conf/cert/server.key -out conf/cert/server_reqout.txt +openssl x509 -req -in conf/cert/server_reqout.txt -days 36500 -sha1 -CAcreateserial -CA conf/cert/ca.crt -CAkey conf/cert/ca.pem -out conf/cert/server.crt -extfile conf/cert/extfile.cnf +``` + +* extfile.cnf +```yaml +subjectAltName = @alt_names +[alt_names] +IP.1 = 127.0.0.1 +DNS.1 = localhost +``` + +* server.cnf +```yaml +[req] +req_extensions = v3_req +distinguished_name = req_distinguished_name +prompt = no + +[req_distinguished_name] +countryName = CN +stateOrProvinceName = Beijing +localityName = Beijing +postalCode = 100105 +streetAddress = CNCC, No.7 Tianchen East Road, Chaoyang District +organizationName = JD Cloud +organizationalUnitName = CPS Dept. +emailAddress = zhouguiqing3@jd.com +0.commonName = jdcps-proxy.jdcloud.com + +[v3_req] +keyUsage = keyEncipherment, dataEncipherment +extendedKeyUsage = serverAuth + +``` + +## 3. **Client证书** +* 生成client.key client.crt +```bash +openssl genrsa -out conf/cert/client.key 2048 +openssl ecparam -genkey -name secp384r1 -out conf/cert/client.key +openssl req -config conf/cert/client.cnf -new -key conf/cert/client.key -out conf/cert/client_reqout.txt +openssl x509 -req -in conf/cert/client_reqout.txt -days 36500 -sha1 -CAcreateserial -CA conf/cert/ca.crt -CAkey conf/cert/ca.pem -out conf/cert/client.crt +``` + +* client.cnf +```yaml +[req] +req_extensions = v3_req +distinguished_name = req_distinguished_name +prompt = no + +[req_distinguished_name] +countryName = CN +stateOrProvinceName = Beijing +localityName = Beijing +postalCode = 100105 +streetAddress = CNCC, No.7 Tianchen East Road, Chaoyang District +organizationName = JD Cloud +organizationalUnitName = CPS Dept. +emailAddress = zhouguiqing3@jd.com +0.commonName = agent + +[ v3_req ] +keyUsage = keyEncipherment, dataEncipherment +extendedKeyUsage = clientAuth + +``` + +### commonName 即CN,ca和client、server的配置中,不能一样 \ No newline at end of file diff --git a/bmp-monitor-proxy/doc/monitor.http b/bmp-monitor-proxy/doc/monitor.http new file mode 100644 index 0000000..6fd0b83 --- /dev/null +++ b/bmp-monitor-proxy/doc/monitor.http @@ -0,0 +1,13 @@ +GET http://example.com/comments/1 + +### +POST https://example.com/comments HTTP/1.1 +content-type: application/json + +{ + "name": "sample", + "time": "Wed, 21 Oct 2015 18:27:50 GMT" +} +### + +{{$guid}}, {{$randomInt min max}}, {{$timestamp [offset option]}}, {{$datetime rfc1123|iso8601 [offset option]}}, and {{$aadToken [new] [public|cn|de|us|ppe] [] [aud:]}} \ No newline at end of file diff --git a/bmp-monitor-proxy/global/global.go b/bmp-monitor-proxy/global/global.go new file mode 100644 index 0000000..88158c3 --- /dev/null +++ b/bmp-monitor-proxy/global/global.go @@ -0,0 +1,30 @@ +package global + +import ( + "time" + + "github.com/patrickmn/go-cache" +) + +var ( + Cache *cache.Cache +) + +func init() { + Cache = cache.New(10*time.Minute, 1*time.Minute) +} + +func Set(k string, v interface{}) { + if Cache == nil { + return + } + + Cache.Set(k, v, cache.DefaultExpiration) +} + +func Get(k string) (interface{}, bool) { + if Cache == nil { + return nil, false + } + return Cache.Get(k) +} diff --git a/bmp-monitor-proxy/go.mod b/bmp-monitor-proxy/go.mod new file mode 100644 index 0000000..c0220ff --- /dev/null +++ b/bmp-monitor-proxy/go.mod @@ -0,0 +1,54 @@ +module coding.jd.com/bmp/agent-proxy-jdstack + +go 1.17 + +require ( + github.com/StackExchange/wmi v1.2.1 + github.com/VividCortex/godaemon v1.0.0 + github.com/beego/beego/v2 v2.0.6 + github.com/go-redis/redis v6.15.9+incompatible + github.com/go-sql-driver/mysql v1.7.0 + github.com/patrickmn/go-cache v2.1.0+incompatible + github.com/prometheus/client_golang v1.18.0 +) + +require ( + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/go-ole/go-ole v1.2.5 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/google/go-cmp v0.6.0 // indirect + github.com/hashicorp/golang-lru v0.5.4 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/onsi/ginkgo v1.16.5 // indirect + github.com/onsi/gomega v1.33.1 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/prometheus/client_model v0.5.0 // indirect + github.com/prometheus/common v0.45.0 // indirect + github.com/prometheus/procfs v0.12.0 // indirect + github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18 // indirect + golang.org/x/crypto v0.22.0 // indirect + golang.org/x/net v0.24.0 // indirect + golang.org/x/sys v0.19.0 // indirect + golang.org/x/text v0.14.0 // indirect + google.golang.org/protobuf v1.33.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) + +require ( + git.jd.com/cps-golang/ironic-common v0.0.0-00010101000000-000000000000 + git.jd.com/cps-golang/log v0.0.0-00010101000000-000000000000 + git.jd.com/jcloud-api-gateway/jcloud-sdk-go v0.0.0-00010101000000-000000000000 + github.com/go-playground/validator/v10 v10.4.1 +) + +replace git.jd.com/cps-golang/log => ./bmp_vendor/log + +replace git.jd.com/cps-golang/ironic-common => ./bmp_vendor/ironic-common + +replace git.jd.com/jcloud-api-gateway/jcloud-sdk-go => ./bmp_vendor/jcloud-sdk-go diff --git a/bmp-monitor-proxy/go.sum b/bmp-monitor-proxy/go.sum new file mode 100644 index 0000000..daba515 --- /dev/null +++ b/bmp-monitor-proxy/go.sum @@ -0,0 +1,2133 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= +cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.44.3/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= +cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= +cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= +cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= +cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= +cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= +cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= +cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= +cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= +cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= +cloud.google.com/go v0.75.0/go.mod h1:VGuuCn7PG0dwsd5XPVm2Mm3wlh3EL55/79EKB6hlPTY= +cloud.google.com/go v0.78.0/go.mod h1:QjdrLG0uq+YwhjoVOLsS1t7TW8fs36kLs4XO5R5ECHg= +cloud.google.com/go v0.79.0/go.mod h1:3bzgcEeQlzbuEAYu4mrWhKqWjmpprinYgKJLgKHnbb8= +cloud.google.com/go v0.81.0/go.mod h1:mk/AM35KwGk/Nm2YSeZbxXdrNK3KZOYHmLkOqC2V6E0= +cloud.google.com/go v0.83.0/go.mod h1:Z7MJUsANfY0pYPdw0lbnivPx4/vhy/e2FEkSkF7vAVY= +cloud.google.com/go v0.84.0/go.mod h1:RazrYuxIK6Kb7YrzzhPoLmCVzl7Sup4NrbKPg8KHSUM= +cloud.google.com/go v0.87.0/go.mod h1:TpDYlFy7vuLzZMMZ+B6iRiELaY7z/gJPaqbMx6mlWcY= +cloud.google.com/go v0.90.0/go.mod h1:kRX0mNRHe0e2rC6oNakvwQqzyDmg57xJ+SZU1eT2aDQ= +cloud.google.com/go v0.93.3/go.mod h1:8utlLll2EF5XMAV15woO4lSbWQlk8rer9aLOfLh7+YI= +cloud.google.com/go v0.94.1/go.mod h1:qAlAugsXlC+JWO+Bke5vCtc9ONxjQT3drlTTnAplMW4= +cloud.google.com/go v0.97.0/go.mod h1:GF7l59pYBVlXQIBLx3a761cZ41F9bBH3JUlihCt2Udc= +cloud.google.com/go v0.99.0/go.mod h1:w0Xx2nLzqWJPuozYQX+hFfCSI8WioryfRDzkoI/Y2ZA= +cloud.google.com/go v0.100.1/go.mod h1:fs4QogzfH5n2pBXBP9vRiU+eCny7lD2vmFZy79Iuw1U= +cloud.google.com/go v0.100.2/go.mod h1:4Xra9TjzAeYHrl5+oeLlzbM2k3mjVhZh4UqTZ//w99A= +cloud.google.com/go v0.102.0/go.mod h1:oWcCzKlqJ5zgHQt9YsaeTY9KzIvjyy0ArmiBUgpQ+nc= +cloud.google.com/go v0.102.1/go.mod h1:XZ77E9qnTEnrgEOvr4xzfdX5TRo7fB4T2F4O6+34hIU= +cloud.google.com/go v0.104.0/go.mod h1:OO6xxXdJyvuJPcEPBLN9BJPD+jep5G1+2U5B5gkRYtA= +cloud.google.com/go v0.105.0/go.mod h1:PrLgOJNe5nfE9UMxKxgXj4mD3voiP+YQ6gdt6KMFOKM= +cloud.google.com/go v0.107.0/go.mod h1:wpc2eNrD7hXUTy8EKS10jkxpZBjASrORK7goS+3YX2I= +cloud.google.com/go v0.110.0/go.mod h1:SJnCLqQ0FCFGSZMUNUf84MV3Aia54kn7pi8st7tMzaY= +cloud.google.com/go v0.110.2/go.mod h1:k04UEeEtb6ZBRTv3dZz4CeJC3jKGxyhl0sAiVVquxiw= +cloud.google.com/go/accessapproval v1.4.0/go.mod h1:zybIuC3KpDOvotz59lFe5qxRZx6C75OtwbisN56xYB4= +cloud.google.com/go/accessapproval v1.5.0/go.mod h1:HFy3tuiGvMdcd/u+Cu5b9NkO1pEICJ46IR82PoUdplw= +cloud.google.com/go/accessapproval v1.6.0/go.mod h1:R0EiYnwV5fsRFiKZkPHr6mwyk2wxUJ30nL4j2pcFY2E= +cloud.google.com/go/accesscontextmanager v1.3.0/go.mod h1:TgCBehyr5gNMz7ZaH9xubp+CE8dkrszb4oK9CWyvD4o= +cloud.google.com/go/accesscontextmanager v1.4.0/go.mod h1:/Kjh7BBu/Gh83sv+K60vN9QE5NJcd80sU33vIe2IFPE= +cloud.google.com/go/accesscontextmanager v1.6.0/go.mod h1:8XCvZWfYw3K/ji0iVnp+6pu7huxoQTLmxAbVjbloTtM= +cloud.google.com/go/accesscontextmanager v1.7.0/go.mod h1:CEGLewx8dwa33aDAZQujl7Dx+uYhS0eay198wB/VumQ= +cloud.google.com/go/aiplatform v1.22.0/go.mod h1:ig5Nct50bZlzV6NvKaTwmplLLddFx0YReh9WfTO5jKw= +cloud.google.com/go/aiplatform v1.24.0/go.mod h1:67UUvRBKG6GTayHKV8DBv2RtR1t93YRu5B1P3x99mYY= +cloud.google.com/go/aiplatform v1.27.0/go.mod h1:Bvxqtl40l0WImSb04d0hXFU7gDOiq9jQmorivIiWcKg= +cloud.google.com/go/aiplatform v1.35.0/go.mod h1:7MFT/vCaOyZT/4IIFfxH4ErVg/4ku6lKv3w0+tFTgXQ= +cloud.google.com/go/aiplatform v1.36.1/go.mod h1:WTm12vJRPARNvJ+v6P52RDHCNe4AhvjcIZ/9/RRHy/k= +cloud.google.com/go/aiplatform v1.37.0/go.mod h1:IU2Cv29Lv9oCn/9LkFiiuKfwrRTq+QQMbW+hPCxJGZw= +cloud.google.com/go/analytics v0.11.0/go.mod h1:DjEWCu41bVbYcKyvlws9Er60YE4a//bK6mnhWvQeFNI= +cloud.google.com/go/analytics v0.12.0/go.mod h1:gkfj9h6XRf9+TS4bmuhPEShsh3hH8PAZzm/41OOhQd4= +cloud.google.com/go/analytics v0.17.0/go.mod h1:WXFa3WSym4IZ+JiKmavYdJwGG/CvpqiqczmL59bTD9M= +cloud.google.com/go/analytics v0.18.0/go.mod h1:ZkeHGQlcIPkw0R/GW+boWHhCOR43xz9RN/jn7WcqfIE= +cloud.google.com/go/analytics v0.19.0/go.mod h1:k8liqf5/HCnOUkbawNtrWWc+UAzyDlW89doe8TtoDsE= +cloud.google.com/go/apigateway v1.3.0/go.mod h1:89Z8Bhpmxu6AmUxuVRg/ECRGReEdiP3vQtk4Z1J9rJk= +cloud.google.com/go/apigateway v1.4.0/go.mod h1:pHVY9MKGaH9PQ3pJ4YLzoj6U5FUDeDFBllIz7WmzJoc= +cloud.google.com/go/apigateway v1.5.0/go.mod h1:GpnZR3Q4rR7LVu5951qfXPJCHquZt02jf7xQx7kpqN8= +cloud.google.com/go/apigeeconnect v1.3.0/go.mod h1:G/AwXFAKo0gIXkPTVfZDd2qA1TxBXJ3MgMRBQkIi9jc= +cloud.google.com/go/apigeeconnect v1.4.0/go.mod h1:kV4NwOKqjvt2JYR0AoIWo2QGfoRtn/pkS3QlHp0Ni04= +cloud.google.com/go/apigeeconnect v1.5.0/go.mod h1:KFaCqvBRU6idyhSNyn3vlHXc8VMDJdRmwDF6JyFRqZ8= +cloud.google.com/go/apigeeregistry v0.4.0/go.mod h1:EUG4PGcsZvxOXAdyEghIdXwAEi/4MEaoqLMLDMIwKXY= +cloud.google.com/go/apigeeregistry v0.5.0/go.mod h1:YR5+s0BVNZfVOUkMa5pAR2xGd0A473vA5M7j247o1wM= +cloud.google.com/go/apigeeregistry v0.6.0/go.mod h1:BFNzW7yQVLZ3yj0TKcwzb8n25CFBri51GVGOEUcgQsc= +cloud.google.com/go/apikeys v0.4.0/go.mod h1:XATS/yqZbaBK0HOssf+ALHp8jAlNHUgyfprvNcBIszU= +cloud.google.com/go/apikeys v0.5.0/go.mod h1:5aQfwY4D+ewMMWScd3hm2en3hCj+BROlyrt3ytS7KLI= +cloud.google.com/go/apikeys v0.6.0/go.mod h1:kbpXu5upyiAlGkKrJgQl8A0rKNNJ7dQ377pdroRSSi8= +cloud.google.com/go/appengine v1.4.0/go.mod h1:CS2NhuBuDXM9f+qscZ6V86m1MIIqPj3WC/UoEuR1Sno= +cloud.google.com/go/appengine v1.5.0/go.mod h1:TfasSozdkFI0zeoxW3PTBLiNqRmzraodCWatWI9Dmak= +cloud.google.com/go/appengine v1.6.0/go.mod h1:hg6i0J/BD2cKmDJbaFSYHFyZkgBEfQrDg/X0V5fJn84= +cloud.google.com/go/appengine v1.7.0/go.mod h1:eZqpbHFCqRGa2aCdope7eC0SWLV1j0neb/QnMJVWx6A= +cloud.google.com/go/appengine v1.7.1/go.mod h1:IHLToyb/3fKutRysUlFO0BPt5j7RiQ45nrzEJmKTo6E= +cloud.google.com/go/area120 v0.5.0/go.mod h1:DE/n4mp+iqVyvxHN41Vf1CR602GiHQjFPusMFW6bGR4= +cloud.google.com/go/area120 v0.6.0/go.mod h1:39yFJqWVgm0UZqWTOdqkLhjoC7uFfgXRC8g/ZegeAh0= +cloud.google.com/go/area120 v0.7.0/go.mod h1:a3+8EUD1SX5RUcCs3MY5YasiO1z6yLiNLRiFrykbynY= +cloud.google.com/go/area120 v0.7.1/go.mod h1:j84i4E1RboTWjKtZVWXPqvK5VHQFJRF2c1Nm69pWm9k= +cloud.google.com/go/artifactregistry v1.6.0/go.mod h1:IYt0oBPSAGYj/kprzsBjZ/4LnG/zOcHyFHjWPCi6SAQ= +cloud.google.com/go/artifactregistry v1.7.0/go.mod h1:mqTOFOnGZx8EtSqK/ZWcsm/4U8B77rbcLP6ruDU2Ixk= +cloud.google.com/go/artifactregistry v1.8.0/go.mod h1:w3GQXkJX8hiKN0v+at4b0qotwijQbYUqF2GWkZzAhC0= +cloud.google.com/go/artifactregistry v1.9.0/go.mod h1:2K2RqvA2CYvAeARHRkLDhMDJ3OXy26h3XW+3/Jh2uYc= +cloud.google.com/go/artifactregistry v1.11.1/go.mod h1:lLYghw+Itq9SONbCa1YWBoWs1nOucMH0pwXN1rOBZFI= +cloud.google.com/go/artifactregistry v1.11.2/go.mod h1:nLZns771ZGAwVLzTX/7Al6R9ehma4WUEhZGWV6CeQNQ= +cloud.google.com/go/artifactregistry v1.12.0/go.mod h1:o6P3MIvtzTOnmvGagO9v/rOjjA0HmhJ+/6KAXrmYDCI= +cloud.google.com/go/artifactregistry v1.13.0/go.mod h1:uy/LNfoOIivepGhooAUpL1i30Hgee3Cu0l4VTWHUC08= +cloud.google.com/go/asset v1.5.0/go.mod h1:5mfs8UvcM5wHhqtSv8J1CtxxaQq3AdBxxQi2jGW/K4o= +cloud.google.com/go/asset v1.7.0/go.mod h1:YbENsRK4+xTiL+Ofoj5Ckf+O17kJtgp3Y3nn4uzZz5s= +cloud.google.com/go/asset v1.8.0/go.mod h1:mUNGKhiqIdbr8X7KNayoYvyc4HbbFO9URsjbytpUaW0= +cloud.google.com/go/asset v1.9.0/go.mod h1:83MOE6jEJBMqFKadM9NLRcs80Gdw76qGuHn8m3h8oHQ= +cloud.google.com/go/asset v1.10.0/go.mod h1:pLz7uokL80qKhzKr4xXGvBQXnzHn5evJAEAtZiIb0wY= +cloud.google.com/go/asset v1.11.1/go.mod h1:fSwLhbRvC9p9CXQHJ3BgFeQNM4c9x10lqlrdEUYXlJo= +cloud.google.com/go/asset v1.12.0/go.mod h1:h9/sFOa4eDIyKmH6QMpm4eUK3pDojWnUhTgJlk762Hg= +cloud.google.com/go/asset v1.13.0/go.mod h1:WQAMyYek/b7NBpYq/K4KJWcRqzoalEsxz/t/dTk4THw= +cloud.google.com/go/assuredworkloads v1.5.0/go.mod h1:n8HOZ6pff6re5KYfBXcFvSViQjDwxFkAkmUFffJRbbY= +cloud.google.com/go/assuredworkloads v1.6.0/go.mod h1:yo2YOk37Yc89Rsd5QMVECvjaMKymF9OP+QXWlKXUkXw= +cloud.google.com/go/assuredworkloads v1.7.0/go.mod h1:z/736/oNmtGAyU47reJgGN+KVoYoxeLBoj4XkKYscNI= +cloud.google.com/go/assuredworkloads v1.8.0/go.mod h1:AsX2cqyNCOvEQC8RMPnoc0yEarXQk6WEKkxYfL6kGIo= +cloud.google.com/go/assuredworkloads v1.9.0/go.mod h1:kFuI1P78bplYtT77Tb1hi0FMxM0vVpRC7VVoJC3ZoT0= +cloud.google.com/go/assuredworkloads v1.10.0/go.mod h1:kwdUQuXcedVdsIaKgKTp9t0UJkE5+PAVNhdQm4ZVq2E= +cloud.google.com/go/automl v1.5.0/go.mod h1:34EjfoFGMZ5sgJ9EoLsRtdPSNZLcfflJR39VbVNS2M0= +cloud.google.com/go/automl v1.6.0/go.mod h1:ugf8a6Fx+zP0D59WLhqgTDsQI9w07o64uf/Is3Nh5p8= +cloud.google.com/go/automl v1.7.0/go.mod h1:RL9MYCCsJEOmt0Wf3z9uzG0a7adTT1fe+aObgSpkCt8= +cloud.google.com/go/automl v1.8.0/go.mod h1:xWx7G/aPEe/NP+qzYXktoBSDfjO+vnKMGgsApGJJquM= +cloud.google.com/go/automl v1.12.0/go.mod h1:tWDcHDp86aMIuHmyvjuKeeHEGq76lD7ZqfGLN6B0NuU= +cloud.google.com/go/baremetalsolution v0.3.0/go.mod h1:XOrocE+pvK1xFfleEnShBlNAXf+j5blPPxrhjKgnIFc= +cloud.google.com/go/baremetalsolution v0.4.0/go.mod h1:BymplhAadOO/eBa7KewQ0Ppg4A4Wplbn+PsFKRLo0uI= +cloud.google.com/go/baremetalsolution v0.5.0/go.mod h1:dXGxEkmR9BMwxhzBhV0AioD0ULBmuLZI8CdwalUxuss= +cloud.google.com/go/batch v0.3.0/go.mod h1:TR18ZoAekj1GuirsUsR1ZTKN3FC/4UDnScjT8NXImFE= +cloud.google.com/go/batch v0.4.0/go.mod h1:WZkHnP43R/QCGQsZ+0JyG4i79ranE2u8xvjq/9+STPE= +cloud.google.com/go/batch v0.7.0/go.mod h1:vLZN95s6teRUqRQ4s3RLDsH8PvboqBK+rn1oevL159g= +cloud.google.com/go/beyondcorp v0.2.0/go.mod h1:TB7Bd+EEtcw9PCPQhCJtJGjk/7TC6ckmnSFS+xwTfm4= +cloud.google.com/go/beyondcorp v0.3.0/go.mod h1:E5U5lcrcXMsCuoDNyGrpyTm/hn7ne941Jz2vmksAxW8= +cloud.google.com/go/beyondcorp v0.4.0/go.mod h1:3ApA0mbhHx6YImmuubf5pyW8srKnCEPON32/5hj+RmM= +cloud.google.com/go/beyondcorp v0.5.0/go.mod h1:uFqj9X+dSfrheVp7ssLTaRHd2EHqSL4QZmH4e8WXGGU= +cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= +cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= +cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= +cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= +cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= +cloud.google.com/go/bigquery v1.42.0/go.mod h1:8dRTJxhtG+vwBKzE5OseQn/hiydoQN3EedCaOdYmxRA= +cloud.google.com/go/bigquery v1.43.0/go.mod h1:ZMQcXHsl+xmU1z36G2jNGZmKp9zNY5BUua5wDgmNCfw= +cloud.google.com/go/bigquery v1.44.0/go.mod h1:0Y33VqXTEsbamHJvJHdFmtqHvMIY28aK1+dFsvaChGc= +cloud.google.com/go/bigquery v1.47.0/go.mod h1:sA9XOgy0A8vQK9+MWhEQTY6Tix87M/ZurWFIxmF9I/E= +cloud.google.com/go/bigquery v1.48.0/go.mod h1:QAwSz+ipNgfL5jxiaK7weyOhzdoAy1zFm0Nf1fysJac= +cloud.google.com/go/bigquery v1.49.0/go.mod h1:Sv8hMmTFFYBlt/ftw2uN6dFdQPzBlREY9yBh7Oy7/4Q= +cloud.google.com/go/bigquery v1.50.0/go.mod h1:YrleYEh2pSEbgTBZYMJ5SuSr0ML3ypjRB1zgf7pvQLU= +cloud.google.com/go/billing v1.4.0/go.mod h1:g9IdKBEFlItS8bTtlrZdVLWSSdSyFUZKXNS02zKMOZY= +cloud.google.com/go/billing v1.5.0/go.mod h1:mztb1tBc3QekhjSgmpf/CV4LzWXLzCArwpLmP2Gm88s= +cloud.google.com/go/billing v1.6.0/go.mod h1:WoXzguj+BeHXPbKfNWkqVtDdzORazmCjraY+vrxcyvI= +cloud.google.com/go/billing v1.7.0/go.mod h1:q457N3Hbj9lYwwRbnlD7vUpyjq6u5U1RAOArInEiD5Y= +cloud.google.com/go/billing v1.12.0/go.mod h1:yKrZio/eu+okO/2McZEbch17O5CB5NpZhhXG6Z766ss= +cloud.google.com/go/billing v1.13.0/go.mod h1:7kB2W9Xf98hP9Sr12KfECgfGclsH3CQR0R08tnRlRbc= +cloud.google.com/go/binaryauthorization v1.1.0/go.mod h1:xwnoWu3Y84jbuHa0zd526MJYmtnVXn0syOjaJgy4+dM= +cloud.google.com/go/binaryauthorization v1.2.0/go.mod h1:86WKkJHtRcv5ViNABtYMhhNWRrD1Vpi//uKEy7aYEfI= +cloud.google.com/go/binaryauthorization v1.3.0/go.mod h1:lRZbKgjDIIQvzYQS1p99A7/U1JqvqeZg0wiI5tp6tg0= +cloud.google.com/go/binaryauthorization v1.4.0/go.mod h1:tsSPQrBd77VLplV70GUhBf/Zm3FsKmgSqgm4UmiDItk= +cloud.google.com/go/binaryauthorization v1.5.0/go.mod h1:OSe4OU1nN/VswXKRBmciKpo9LulY41gch5c68htf3/Q= +cloud.google.com/go/certificatemanager v1.3.0/go.mod h1:n6twGDvcUBFu9uBgt4eYvvf3sQ6My8jADcOVwHmzadg= +cloud.google.com/go/certificatemanager v1.4.0/go.mod h1:vowpercVFyqs8ABSmrdV+GiFf2H/ch3KyudYQEMM590= +cloud.google.com/go/certificatemanager v1.6.0/go.mod h1:3Hh64rCKjRAX8dXgRAyOcY5vQ/fE1sh8o+Mdd6KPgY8= +cloud.google.com/go/channel v1.8.0/go.mod h1:W5SwCXDJsq/rg3tn3oG0LOxpAo6IMxNa09ngphpSlnk= +cloud.google.com/go/channel v1.9.0/go.mod h1:jcu05W0my9Vx4mt3/rEHpfxc9eKi9XwsdDL8yBMbKUk= +cloud.google.com/go/channel v1.11.0/go.mod h1:IdtI0uWGqhEeatSB62VOoJ8FSUhJ9/+iGkJVqp74CGE= +cloud.google.com/go/channel v1.12.0/go.mod h1:VkxCGKASi4Cq7TbXxlaBezonAYpp1GCnKMY6tnMQnLU= +cloud.google.com/go/cloudbuild v1.3.0/go.mod h1:WequR4ULxlqvMsjDEEEFnOG5ZSRSgWOywXYDb1vPE6U= +cloud.google.com/go/cloudbuild v1.4.0/go.mod h1:5Qwa40LHiOXmz3386FrjrYM93rM/hdRr7b53sySrTqA= +cloud.google.com/go/cloudbuild v1.6.0/go.mod h1:UIbc/w9QCbH12xX+ezUsgblrWv+Cv4Tw83GiSMHOn9M= +cloud.google.com/go/cloudbuild v1.7.0/go.mod h1:zb5tWh2XI6lR9zQmsm1VRA+7OCuve5d8S+zJUul8KTg= +cloud.google.com/go/cloudbuild v1.9.0/go.mod h1:qK1d7s4QlO0VwfYn5YuClDGg2hfmLZEb4wQGAbIgL1s= +cloud.google.com/go/clouddms v1.3.0/go.mod h1:oK6XsCDdW4Ib3jCCBugx+gVjevp2TMXFtgxvPSee3OM= +cloud.google.com/go/clouddms v1.4.0/go.mod h1:Eh7sUGCC+aKry14O1NRljhjyrr0NFC0G2cjwX0cByRk= +cloud.google.com/go/clouddms v1.5.0/go.mod h1:QSxQnhikCLUw13iAbffF2CZxAER3xDGNHjsTAkQJcQA= +cloud.google.com/go/cloudtasks v1.5.0/go.mod h1:fD92REy1x5woxkKEkLdvavGnPJGEn8Uic9nWuLzqCpY= +cloud.google.com/go/cloudtasks v1.6.0/go.mod h1:C6Io+sxuke9/KNRkbQpihnW93SWDU3uXt92nu85HkYI= +cloud.google.com/go/cloudtasks v1.7.0/go.mod h1:ImsfdYWwlWNJbdgPIIGJWC+gemEGTBK/SunNQQNCAb4= +cloud.google.com/go/cloudtasks v1.8.0/go.mod h1:gQXUIwCSOI4yPVK7DgTVFiiP0ZW/eQkydWzwVMdHxrI= +cloud.google.com/go/cloudtasks v1.9.0/go.mod h1:w+EyLsVkLWHcOaqNEyvcKAsWp9p29dL6uL9Nst1cI7Y= +cloud.google.com/go/cloudtasks v1.10.0/go.mod h1:NDSoTLkZ3+vExFEWu2UJV1arUyzVDAiZtdWcsUyNwBs= +cloud.google.com/go/compute v0.1.0/go.mod h1:GAesmwr110a34z04OlxYkATPBEfVhkymfTBXtfbBFow= +cloud.google.com/go/compute v1.3.0/go.mod h1:cCZiE1NHEtai4wiufUhW8I8S1JKkAnhnQJWM7YD99wM= +cloud.google.com/go/compute v1.5.0/go.mod h1:9SMHyhJlzhlkJqrPAc839t2BZFTSk6Jdj6mkzQJeu0M= +cloud.google.com/go/compute v1.6.0/go.mod h1:T29tfhtVbq1wvAPo0E3+7vhgmkOYeXjhFvz/FMzPu0s= +cloud.google.com/go/compute v1.6.1/go.mod h1:g85FgpzFvNULZ+S8AYq87axRKuf2Kh7deLqV/jJ3thU= +cloud.google.com/go/compute v1.7.0/go.mod h1:435lt8av5oL9P3fv1OEzSbSUe+ybHXGMPQHHZWZxy9U= +cloud.google.com/go/compute v1.10.0/go.mod h1:ER5CLbMxl90o2jtNbGSbtfOpQKR0t15FOtRsugnLrlU= +cloud.google.com/go/compute v1.12.0/go.mod h1:e8yNOBcBONZU1vJKCvCoDw/4JQsA0dpM4x/6PIIOocU= +cloud.google.com/go/compute v1.12.1/go.mod h1:e8yNOBcBONZU1vJKCvCoDw/4JQsA0dpM4x/6PIIOocU= +cloud.google.com/go/compute v1.13.0/go.mod h1:5aPTS0cUNMIc1CE546K+Th6weJUNQErARyZtRXDJ8GE= +cloud.google.com/go/compute v1.14.0/go.mod h1:YfLtxrj9sU4Yxv+sXzZkyPjEyPBZfXHUvjxega5vAdo= +cloud.google.com/go/compute v1.15.1/go.mod h1:bjjoF/NtFUrkD/urWfdHaKuOPDR5nWIs63rR+SXhcpA= +cloud.google.com/go/compute v1.18.0/go.mod h1:1X7yHxec2Ga+Ss6jPyjxRxpu2uu7PLgsOVXvgU0yacs= +cloud.google.com/go/compute v1.19.0/go.mod h1:rikpw2y+UMidAe9tISo04EHNOIf42RLYF/q8Bs93scU= +cloud.google.com/go/compute v1.19.3/go.mod h1:qxvISKp/gYnXkSAD1ppcSOveRAmzxicEv/JlizULFrI= +cloud.google.com/go/compute v1.20.1/go.mod h1:4tCnrn48xsqlwSAiLf1HXMQk8CONslYbdiEZc9FEIbM= +cloud.google.com/go/compute/metadata v0.1.0/go.mod h1:Z1VN+bulIf6bt4P/C37K4DyZYZEXYonfTBHHFPO/4UU= +cloud.google.com/go/compute/metadata v0.2.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= +cloud.google.com/go/compute/metadata v0.2.1/go.mod h1:jgHgmJd2RKBGzXqF5LR2EZMGxBkeanZ9wwa75XHJgOM= +cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= +cloud.google.com/go/contactcenterinsights v1.3.0/go.mod h1:Eu2oemoePuEFc/xKFPjbTuPSj0fYJcPls9TFlPNnHHY= +cloud.google.com/go/contactcenterinsights v1.4.0/go.mod h1:L2YzkGbPsv+vMQMCADxJoT9YiTTnSEd6fEvCeHTYVck= +cloud.google.com/go/contactcenterinsights v1.6.0/go.mod h1:IIDlT6CLcDoyv79kDv8iWxMSTZhLxSCofVV5W6YFM/w= +cloud.google.com/go/container v1.6.0/go.mod h1:Xazp7GjJSeUYo688S+6J5V+n/t+G5sKBTFkKNudGRxg= +cloud.google.com/go/container v1.7.0/go.mod h1:Dp5AHtmothHGX3DwwIHPgq45Y8KmNsgN3amoYfxVkLo= +cloud.google.com/go/container v1.13.1/go.mod h1:6wgbMPeQRw9rSnKBCAJXnds3Pzj03C4JHamr8asWKy4= +cloud.google.com/go/container v1.14.0/go.mod h1:3AoJMPhHfLDxLvrlVWaK57IXzaPnLaZq63WX59aQBfM= +cloud.google.com/go/container v1.15.0/go.mod h1:ft+9S0WGjAyjDggg5S06DXj+fHJICWg8L7isCQe9pQA= +cloud.google.com/go/containeranalysis v0.5.1/go.mod h1:1D92jd8gRR/c0fGMlymRgxWD3Qw9C1ff6/T7mLgVL8I= +cloud.google.com/go/containeranalysis v0.6.0/go.mod h1:HEJoiEIu+lEXM+k7+qLCci0h33lX3ZqoYFdmPcoO7s4= +cloud.google.com/go/containeranalysis v0.7.0/go.mod h1:9aUL+/vZ55P2CXfuZjS4UjQ9AgXoSw8Ts6lemfmxBxI= +cloud.google.com/go/containeranalysis v0.9.0/go.mod h1:orbOANbwk5Ejoom+s+DUCTTJ7IBdBQJDcSylAx/on9s= +cloud.google.com/go/datacatalog v1.3.0/go.mod h1:g9svFY6tuR+j+hrTw3J2dNcmI0dzmSiyOzm8kpLq0a0= +cloud.google.com/go/datacatalog v1.5.0/go.mod h1:M7GPLNQeLfWqeIm3iuiruhPzkt65+Bx8dAKvScX8jvs= +cloud.google.com/go/datacatalog v1.6.0/go.mod h1:+aEyF8JKg+uXcIdAmmaMUmZ3q1b/lKLtXCmXdnc0lbc= +cloud.google.com/go/datacatalog v1.7.0/go.mod h1:9mEl4AuDYWw81UGc41HonIHH7/sn52H0/tc8f8ZbZIE= +cloud.google.com/go/datacatalog v1.8.0/go.mod h1:KYuoVOv9BM8EYz/4eMFxrr4DUKhGIOXxZoKYF5wdISM= +cloud.google.com/go/datacatalog v1.8.1/go.mod h1:RJ58z4rMp3gvETA465Vg+ag8BGgBdnRPEMMSTr5Uv+M= +cloud.google.com/go/datacatalog v1.12.0/go.mod h1:CWae8rFkfp6LzLumKOnmVh4+Zle4A3NXLzVJ1d1mRm0= +cloud.google.com/go/datacatalog v1.13.0/go.mod h1:E4Rj9a5ZtAxcQJlEBTLgMTphfP11/lNaAshpoBgemX8= +cloud.google.com/go/dataflow v0.6.0/go.mod h1:9QwV89cGoxjjSR9/r7eFDqqjtvbKxAK2BaYU6PVk9UM= +cloud.google.com/go/dataflow v0.7.0/go.mod h1:PX526vb4ijFMesO1o202EaUmouZKBpjHsTlCtB4parQ= +cloud.google.com/go/dataflow v0.8.0/go.mod h1:Rcf5YgTKPtQyYz8bLYhFoIV/vP39eL7fWNcSOyFfLJE= +cloud.google.com/go/dataform v0.3.0/go.mod h1:cj8uNliRlHpa6L3yVhDOBrUXH+BPAO1+KFMQQNSThKo= +cloud.google.com/go/dataform v0.4.0/go.mod h1:fwV6Y4Ty2yIFL89huYlEkwUPtS7YZinZbzzj5S9FzCE= +cloud.google.com/go/dataform v0.5.0/go.mod h1:GFUYRe8IBa2hcomWplodVmUx/iTL0FrsauObOM3Ipr0= +cloud.google.com/go/dataform v0.6.0/go.mod h1:QPflImQy33e29VuapFdf19oPbE4aYTJxr31OAPV+ulA= +cloud.google.com/go/dataform v0.7.0/go.mod h1:7NulqnVozfHvWUBpMDfKMUESr+85aJsC/2O0o3jWPDE= +cloud.google.com/go/datafusion v1.4.0/go.mod h1:1Zb6VN+W6ALo85cXnM1IKiPw+yQMKMhB9TsTSRDo/38= +cloud.google.com/go/datafusion v1.5.0/go.mod h1:Kz+l1FGHB0J+4XF2fud96WMmRiq/wj8N9u007vyXZ2w= +cloud.google.com/go/datafusion v1.6.0/go.mod h1:WBsMF8F1RhSXvVM8rCV3AeyWVxcC2xY6vith3iw3S+8= +cloud.google.com/go/datalabeling v0.5.0/go.mod h1:TGcJ0G2NzcsXSE/97yWjIZO0bXj0KbVlINXMG9ud42I= +cloud.google.com/go/datalabeling v0.6.0/go.mod h1:WqdISuk/+WIGeMkpw/1q7bK/tFEZxsrFJOJdY2bXvTQ= +cloud.google.com/go/datalabeling v0.7.0/go.mod h1:WPQb1y08RJbmpM3ww0CSUAGweL0SxByuW2E+FU+wXcM= +cloud.google.com/go/dataplex v1.3.0/go.mod h1:hQuRtDg+fCiFgC8j0zV222HvzFQdRd+SVX8gdmFcZzA= +cloud.google.com/go/dataplex v1.4.0/go.mod h1:X51GfLXEMVJ6UN47ESVqvlsRplbLhcsAt0kZCCKsU0A= +cloud.google.com/go/dataplex v1.5.2/go.mod h1:cVMgQHsmfRoI5KFYq4JtIBEUbYwc3c7tXmIDhRmNNVQ= +cloud.google.com/go/dataplex v1.6.0/go.mod h1:bMsomC/aEJOSpHXdFKFGQ1b0TDPIeL28nJObeO1ppRs= +cloud.google.com/go/dataproc v1.7.0/go.mod h1:CKAlMjII9H90RXaMpSxQ8EU6dQx6iAYNPcYPOkSbi8s= +cloud.google.com/go/dataproc v1.8.0/go.mod h1:5OW+zNAH0pMpw14JVrPONsxMQYMBqJuzORhIBfBn9uI= +cloud.google.com/go/dataproc v1.12.0/go.mod h1:zrF3aX0uV3ikkMz6z4uBbIKyhRITnxvr4i3IjKsKrw4= +cloud.google.com/go/dataqna v0.5.0/go.mod h1:90Hyk596ft3zUQ8NkFfvICSIfHFh1Bc7C4cK3vbhkeo= +cloud.google.com/go/dataqna v0.6.0/go.mod h1:1lqNpM7rqNLVgWBJyk5NF6Uen2PHym0jtVJonplVsDA= +cloud.google.com/go/dataqna v0.7.0/go.mod h1:Lx9OcIIeqCrw1a6KdO3/5KMP1wAmTc0slZWwP12Qq3c= +cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/datastore v1.10.0/go.mod h1:PC5UzAmDEkAmkfaknstTYbNpgE49HAgW2J1gcgUfmdM= +cloud.google.com/go/datastore v1.11.0/go.mod h1:TvGxBIHCS50u8jzG+AW/ppf87v1of8nwzFNgEZU1D3c= +cloud.google.com/go/datastream v1.2.0/go.mod h1:i/uTP8/fZwgATHS/XFu0TcNUhuA0twZxxQ3EyCUQMwo= +cloud.google.com/go/datastream v1.3.0/go.mod h1:cqlOX8xlyYF/uxhiKn6Hbv6WjwPPuI9W2M9SAXwaLLQ= +cloud.google.com/go/datastream v1.4.0/go.mod h1:h9dpzScPhDTs5noEMQVWP8Wx8AFBRyS0s8KWPx/9r0g= +cloud.google.com/go/datastream v1.5.0/go.mod h1:6TZMMNPwjUqZHBKPQ1wwXpb0d5VDVPl2/XoS5yi88q4= +cloud.google.com/go/datastream v1.6.0/go.mod h1:6LQSuswqLa7S4rPAOZFVjHIG3wJIjZcZrw8JDEDJuIs= +cloud.google.com/go/datastream v1.7.0/go.mod h1:uxVRMm2elUSPuh65IbZpzJNMbuzkcvu5CjMqVIUHrww= +cloud.google.com/go/deploy v1.4.0/go.mod h1:5Xghikd4VrmMLNaF6FiRFDlHb59VM59YoDQnOUdsH/c= +cloud.google.com/go/deploy v1.5.0/go.mod h1:ffgdD0B89tToyW/U/D2eL0jN2+IEV/3EMuXHA0l4r+s= +cloud.google.com/go/deploy v1.6.0/go.mod h1:f9PTHehG/DjCom3QH0cntOVRm93uGBDt2vKzAPwpXQI= +cloud.google.com/go/deploy v1.8.0/go.mod h1:z3myEJnA/2wnB4sgjqdMfgxCA0EqC3RBTNcVPs93mtQ= +cloud.google.com/go/dialogflow v1.15.0/go.mod h1:HbHDWs33WOGJgn6rfzBW1Kv807BE3O1+xGbn59zZWI4= +cloud.google.com/go/dialogflow v1.16.1/go.mod h1:po6LlzGfK+smoSmTBnbkIZY2w8ffjz/RcGSS+sh1el0= +cloud.google.com/go/dialogflow v1.17.0/go.mod h1:YNP09C/kXA1aZdBgC/VtXX74G/TKn7XVCcVumTflA+8= +cloud.google.com/go/dialogflow v1.18.0/go.mod h1:trO7Zu5YdyEuR+BhSNOqJezyFQ3aUzz0njv7sMx/iek= +cloud.google.com/go/dialogflow v1.19.0/go.mod h1:JVmlG1TwykZDtxtTXujec4tQ+D8SBFMoosgy+6Gn0s0= +cloud.google.com/go/dialogflow v1.29.0/go.mod h1:b+2bzMe+k1s9V+F2jbJwpHPzrnIyHihAdRFMtn2WXuM= +cloud.google.com/go/dialogflow v1.31.0/go.mod h1:cuoUccuL1Z+HADhyIA7dci3N5zUssgpBJmCzI6fNRB4= +cloud.google.com/go/dialogflow v1.32.0/go.mod h1:jG9TRJl8CKrDhMEcvfcfFkkpp8ZhgPz3sBGmAUYJ2qE= +cloud.google.com/go/dlp v1.6.0/go.mod h1:9eyB2xIhpU0sVwUixfBubDoRwP+GjeUoxxeueZmqvmM= +cloud.google.com/go/dlp v1.7.0/go.mod h1:68ak9vCiMBjbasxeVD17hVPxDEck+ExiHavX8kiHG+Q= +cloud.google.com/go/dlp v1.9.0/go.mod h1:qdgmqgTyReTz5/YNSSuueR8pl7hO0o9bQ39ZhtgkWp4= +cloud.google.com/go/documentai v1.7.0/go.mod h1:lJvftZB5NRiFSX4moiye1SMxHx0Bc3x1+p9e/RfXYiU= +cloud.google.com/go/documentai v1.8.0/go.mod h1:xGHNEB7CtsnySCNrCFdCyyMz44RhFEEX2Q7UD0c5IhU= +cloud.google.com/go/documentai v1.9.0/go.mod h1:FS5485S8R00U10GhgBC0aNGrJxBP8ZVpEeJ7PQDZd6k= +cloud.google.com/go/documentai v1.10.0/go.mod h1:vod47hKQIPeCfN2QS/jULIvQTugbmdc0ZvxxfQY1bg4= +cloud.google.com/go/documentai v1.16.0/go.mod h1:o0o0DLTEZ+YnJZ+J4wNfTxmDVyrkzFvttBXXtYRMHkM= +cloud.google.com/go/documentai v1.18.0/go.mod h1:F6CK6iUH8J81FehpskRmhLq/3VlwQvb7TvwOceQ2tbs= +cloud.google.com/go/domains v0.6.0/go.mod h1:T9Rz3GasrpYk6mEGHh4rymIhjlnIuB4ofT1wTxDeT4Y= +cloud.google.com/go/domains v0.7.0/go.mod h1:PtZeqS1xjnXuRPKE/88Iru/LdfoRyEHYA9nFQf4UKpg= +cloud.google.com/go/domains v0.8.0/go.mod h1:M9i3MMDzGFXsydri9/vW+EWz9sWb4I6WyHqdlAk0idE= +cloud.google.com/go/edgecontainer v0.1.0/go.mod h1:WgkZ9tp10bFxqO8BLPqv2LlfmQF1X8lZqwW4r1BTajk= +cloud.google.com/go/edgecontainer v0.2.0/go.mod h1:RTmLijy+lGpQ7BXuTDa4C4ssxyXT34NIuHIgKuP4s5w= +cloud.google.com/go/edgecontainer v0.3.0/go.mod h1:FLDpP4nykgwwIfcLt6zInhprzw0lEi2P1fjO6Ie0qbc= +cloud.google.com/go/edgecontainer v1.0.0/go.mod h1:cttArqZpBB2q58W/upSG++ooo6EsblxDIolxa3jSjbY= +cloud.google.com/go/errorreporting v0.3.0/go.mod h1:xsP2yaAp+OAW4OIm60An2bbLpqIhKXdWR/tawvl7QzU= +cloud.google.com/go/essentialcontacts v1.3.0/go.mod h1:r+OnHa5jfj90qIfZDO/VztSFqbQan7HV75p8sA+mdGI= +cloud.google.com/go/essentialcontacts v1.4.0/go.mod h1:8tRldvHYsmnBCHdFpvU+GL75oWiBKl80BiqlFh9tp+8= +cloud.google.com/go/essentialcontacts v1.5.0/go.mod h1:ay29Z4zODTuwliK7SnX8E86aUF2CTzdNtvv42niCX0M= +cloud.google.com/go/eventarc v1.7.0/go.mod h1:6ctpF3zTnaQCxUjHUdcfgcA1A2T309+omHZth7gDfmc= +cloud.google.com/go/eventarc v1.8.0/go.mod h1:imbzxkyAU4ubfsaKYdQg04WS1NvncblHEup4kvF+4gw= +cloud.google.com/go/eventarc v1.10.0/go.mod h1:u3R35tmZ9HvswGRBnF48IlYgYeBcPUCjkr4BTdem2Kw= +cloud.google.com/go/eventarc v1.11.0/go.mod h1:PyUjsUKPWoRBCHeOxZd/lbOOjahV41icXyUY5kSTvVY= +cloud.google.com/go/filestore v1.3.0/go.mod h1:+qbvHGvXU1HaKX2nD0WEPo92TP/8AQuCVEBXNY9z0+w= +cloud.google.com/go/filestore v1.4.0/go.mod h1:PaG5oDfo9r224f8OYXURtAsY+Fbyq/bLYoINEK8XQAI= +cloud.google.com/go/filestore v1.5.0/go.mod h1:FqBXDWBp4YLHqRnVGveOkHDf8svj9r5+mUDLupOWEDs= +cloud.google.com/go/filestore v1.6.0/go.mod h1:di5unNuss/qfZTw2U9nhFqo8/ZDSc466dre85Kydllg= +cloud.google.com/go/firestore v1.9.0/go.mod h1:HMkjKHNTtRyZNiMzu7YAsLr9K3X2udY2AMwDaMEQiiE= +cloud.google.com/go/functions v1.6.0/go.mod h1:3H1UA3qiIPRWD7PeZKLvHZ9SaQhR26XIJcC0A5GbvAk= +cloud.google.com/go/functions v1.7.0/go.mod h1:+d+QBcWM+RsrgZfV9xo6KfA1GlzJfxcfZcRPEhDDfzg= +cloud.google.com/go/functions v1.8.0/go.mod h1:RTZ4/HsQjIqIYP9a9YPbU+QFoQsAlYgrwOXJWHn1POY= +cloud.google.com/go/functions v1.9.0/go.mod h1:Y+Dz8yGguzO3PpIjhLTbnqV1CWmgQ5UwtlpzoyquQ08= +cloud.google.com/go/functions v1.10.0/go.mod h1:0D3hEOe3DbEvCXtYOZHQZmD+SzYsi1YbI7dGvHfldXw= +cloud.google.com/go/functions v1.12.0/go.mod h1:AXWGrF3e2C/5ehvwYo/GH6O5s09tOPksiKhz+hH8WkA= +cloud.google.com/go/functions v1.13.0/go.mod h1:EU4O007sQm6Ef/PwRsI8N2umygGqPBS/IZQKBQBcJ3c= +cloud.google.com/go/gaming v1.5.0/go.mod h1:ol7rGcxP/qHTRQE/RO4bxkXq+Fix0j6D4LFPzYTIrDM= +cloud.google.com/go/gaming v1.6.0/go.mod h1:YMU1GEvA39Qt3zWGyAVA9bpYz/yAhTvaQ1t2sK4KPUA= +cloud.google.com/go/gaming v1.7.0/go.mod h1:LrB8U7MHdGgFG851iHAfqUdLcKBdQ55hzXy9xBJz0+w= +cloud.google.com/go/gaming v1.8.0/go.mod h1:xAqjS8b7jAVW0KFYeRUxngo9My3f33kFmua++Pi+ggM= +cloud.google.com/go/gaming v1.9.0/go.mod h1:Fc7kEmCObylSWLO334NcO+O9QMDyz+TKC4v1D7X+Bc0= +cloud.google.com/go/gkebackup v0.2.0/go.mod h1:XKvv/4LfG829/B8B7xRkk8zRrOEbKtEam6yNfuQNH60= +cloud.google.com/go/gkebackup v0.3.0/go.mod h1:n/E671i1aOQvUxT541aTkCwExO/bTer2HDlj4TsBRAo= +cloud.google.com/go/gkebackup v0.4.0/go.mod h1:byAyBGUwYGEEww7xsbnUTBHIYcOPy/PgUWUtOeRm9Vg= +cloud.google.com/go/gkeconnect v0.5.0/go.mod h1:c5lsNAg5EwAy7fkqX/+goqFsU1Da/jQFqArp+wGNr/o= +cloud.google.com/go/gkeconnect v0.6.0/go.mod h1:Mln67KyU/sHJEBY8kFZ0xTeyPtzbq9StAVvEULYK16A= +cloud.google.com/go/gkeconnect v0.7.0/go.mod h1:SNfmVqPkaEi3bF/B3CNZOAYPYdg7sU+obZ+QTky2Myw= +cloud.google.com/go/gkehub v0.9.0/go.mod h1:WYHN6WG8w9bXU0hqNxt8rm5uxnk8IH+lPY9J2TV7BK0= +cloud.google.com/go/gkehub v0.10.0/go.mod h1:UIPwxI0DsrpsVoWpLB0stwKCP+WFVG9+y977wO+hBH0= +cloud.google.com/go/gkehub v0.11.0/go.mod h1:JOWHlmN+GHyIbuWQPl47/C2RFhnFKH38jH9Ascu3n0E= +cloud.google.com/go/gkehub v0.12.0/go.mod h1:djiIwwzTTBrF5NaXCGv3mf7klpEMcST17VBTVVDcuaw= +cloud.google.com/go/gkemulticloud v0.3.0/go.mod h1:7orzy7O0S+5kq95e4Hpn7RysVA7dPs8W/GgfUtsPbrA= +cloud.google.com/go/gkemulticloud v0.4.0/go.mod h1:E9gxVBnseLWCk24ch+P9+B2CoDFJZTyIgLKSalC7tuI= +cloud.google.com/go/gkemulticloud v0.5.0/go.mod h1:W0JDkiyi3Tqh0TJr//y19wyb1yf8llHVto2Htf2Ja3Y= +cloud.google.com/go/grafeas v0.2.0/go.mod h1:KhxgtF2hb0P191HlY5besjYm6MqTSTj3LSI+M+ByZHc= +cloud.google.com/go/gsuiteaddons v1.3.0/go.mod h1:EUNK/J1lZEZO8yPtykKxLXI6JSVN2rg9bN8SXOa0bgM= +cloud.google.com/go/gsuiteaddons v1.4.0/go.mod h1:rZK5I8hht7u7HxFQcFei0+AtfS9uSushomRlg+3ua1o= +cloud.google.com/go/gsuiteaddons v1.5.0/go.mod h1:TFCClYLd64Eaa12sFVmUyG62tk4mdIsI7pAnSXRkcFo= +cloud.google.com/go/iam v0.1.0/go.mod h1:vcUNEa0pEm0qRVpmWepWaFMIAI8/hjB9mO8rNCJtF6c= +cloud.google.com/go/iam v0.3.0/go.mod h1:XzJPvDayI+9zsASAFO68Hk07u3z+f+JrT2xXNdp4bnY= +cloud.google.com/go/iam v0.5.0/go.mod h1:wPU9Vt0P4UmCux7mqtRu6jcpPAb74cP1fh50J3QpkUc= +cloud.google.com/go/iam v0.6.0/go.mod h1:+1AH33ueBne5MzYccyMHtEKqLE4/kJOibtffMHDMFMc= +cloud.google.com/go/iam v0.7.0/go.mod h1:H5Br8wRaDGNc8XP3keLc4unfUUZeyH3Sfl9XpQEYOeg= +cloud.google.com/go/iam v0.8.0/go.mod h1:lga0/y3iH6CX7sYqypWJ33hf7kkfXJag67naqGESjkE= +cloud.google.com/go/iam v0.11.0/go.mod h1:9PiLDanza5D+oWFZiH1uG+RnRCfEGKoyl6yo4cgWZGY= +cloud.google.com/go/iam v0.12.0/go.mod h1:knyHGviacl11zrtZUoDuYpDgLjvr28sLQaG0YB2GYAY= +cloud.google.com/go/iam v0.13.0/go.mod h1:ljOg+rcNfzZ5d6f1nAUJ8ZIxOaZUVoS14bKCtaLZ/D0= +cloud.google.com/go/iap v1.4.0/go.mod h1:RGFwRJdihTINIe4wZ2iCP0zF/qu18ZwyKxrhMhygBEc= +cloud.google.com/go/iap v1.5.0/go.mod h1:UH/CGgKd4KyohZL5Pt0jSKE4m3FR51qg6FKQ/z/Ix9A= +cloud.google.com/go/iap v1.6.0/go.mod h1:NSuvI9C/j7UdjGjIde7t7HBz+QTwBcapPE07+sSRcLk= +cloud.google.com/go/iap v1.7.0/go.mod h1:beqQx56T9O1G1yNPph+spKpNibDlYIiIixiqsQXxLIo= +cloud.google.com/go/iap v1.7.1/go.mod h1:WapEwPc7ZxGt2jFGB/C/bm+hP0Y6NXzOYGjpPnmMS74= +cloud.google.com/go/ids v1.1.0/go.mod h1:WIuwCaYVOzHIj2OhN9HAwvW+DBdmUAdcWlFxRl+KubM= +cloud.google.com/go/ids v1.2.0/go.mod h1:5WXvp4n25S0rA/mQWAg1YEEBBq6/s+7ml1RDCW1IrcY= +cloud.google.com/go/ids v1.3.0/go.mod h1:JBdTYwANikFKaDP6LtW5JAi4gubs57SVNQjemdt6xV4= +cloud.google.com/go/iot v1.3.0/go.mod h1:r7RGh2B61+B8oz0AGE+J72AhA0G7tdXItODWsaA2oLs= +cloud.google.com/go/iot v1.4.0/go.mod h1:dIDxPOn0UvNDUMD8Ger7FIaTuvMkj+aGk94RPP0iV+g= +cloud.google.com/go/iot v1.5.0/go.mod h1:mpz5259PDl3XJthEmh9+ap0affn/MqNSP4My77Qql9o= +cloud.google.com/go/iot v1.6.0/go.mod h1:IqdAsmE2cTYYNO1Fvjfzo9po179rAtJeVGUvkLN3rLE= +cloud.google.com/go/kms v1.4.0/go.mod h1:fajBHndQ+6ubNw6Ss2sSd+SWvjL26RNo/dr7uxsnnOA= +cloud.google.com/go/kms v1.5.0/go.mod h1:QJS2YY0eJGBg3mnDfuaCyLauWwBJiHRboYxJ++1xJNg= +cloud.google.com/go/kms v1.6.0/go.mod h1:Jjy850yySiasBUDi6KFUwUv2n1+o7QZFyuUJg6OgjA0= +cloud.google.com/go/kms v1.8.0/go.mod h1:4xFEhYFqvW+4VMELtZyxomGSYtSQKzM178ylFW4jMAg= +cloud.google.com/go/kms v1.9.0/go.mod h1:qb1tPTgfF9RQP8e1wq4cLFErVuTJv7UsSC915J8dh3w= +cloud.google.com/go/kms v1.10.0/go.mod h1:ng3KTUtQQU9bPX3+QGLsflZIHlkbn8amFAMY63m8d24= +cloud.google.com/go/kms v1.10.1/go.mod h1:rIWk/TryCkR59GMC3YtHtXeLzd634lBbKenvyySAyYI= +cloud.google.com/go/language v1.4.0/go.mod h1:F9dRpNFQmJbkaop6g0JhSBXCNlO90e1KWx5iDdxbWic= +cloud.google.com/go/language v1.6.0/go.mod h1:6dJ8t3B+lUYfStgls25GusK04NLh3eDLQnWM3mdEbhI= +cloud.google.com/go/language v1.7.0/go.mod h1:DJ6dYN/W+SQOjF8e1hLQXMF21AkH2w9wiPzPCJa2MIE= +cloud.google.com/go/language v1.8.0/go.mod h1:qYPVHf7SPoNNiCL2Dr0FfEFNil1qi3pQEyygwpgVKB8= +cloud.google.com/go/language v1.9.0/go.mod h1:Ns15WooPM5Ad/5no/0n81yUetis74g3zrbeJBE+ptUY= +cloud.google.com/go/lifesciences v0.5.0/go.mod h1:3oIKy8ycWGPUyZDR/8RNnTOYevhaMLqh5vLUXs9zvT8= +cloud.google.com/go/lifesciences v0.6.0/go.mod h1:ddj6tSX/7BOnhxCSd3ZcETvtNr8NZ6t/iPhY2Tyfu08= +cloud.google.com/go/lifesciences v0.8.0/go.mod h1:lFxiEOMqII6XggGbOnKiyZ7IBwoIqA84ClvoezaA/bo= +cloud.google.com/go/logging v1.6.1/go.mod h1:5ZO0mHHbvm8gEmeEUHrmDlTDSu5imF6MUP9OfilNXBw= +cloud.google.com/go/logging v1.7.0/go.mod h1:3xjP2CjkM3ZkO73aj4ASA5wRPGGCRrPIAeNqVNkzY8M= +cloud.google.com/go/longrunning v0.1.1/go.mod h1:UUFxuDWkv22EuY93jjmDMFT5GPQKeFVJBIF6QlTqdsE= +cloud.google.com/go/longrunning v0.3.0/go.mod h1:qth9Y41RRSUE69rDcOn6DdK3HfQfsUI0YSmW3iIlLJc= +cloud.google.com/go/longrunning v0.4.1/go.mod h1:4iWDqhBZ70CvZ6BfETbvam3T8FMvLK+eFj0E6AaRQTo= +cloud.google.com/go/managedidentities v1.3.0/go.mod h1:UzlW3cBOiPrzucO5qWkNkh0w33KFtBJU281hacNvsdE= +cloud.google.com/go/managedidentities v1.4.0/go.mod h1:NWSBYbEMgqmbZsLIyKvxrYbtqOsxY1ZrGM+9RgDqInM= +cloud.google.com/go/managedidentities v1.5.0/go.mod h1:+dWcZ0JlUmpuxpIDfyP5pP5y0bLdRwOS4Lp7gMni/LA= +cloud.google.com/go/maps v0.1.0/go.mod h1:BQM97WGyfw9FWEmQMpZ5T6cpovXXSd1cGmFma94eubI= +cloud.google.com/go/maps v0.6.0/go.mod h1:o6DAMMfb+aINHz/p/jbcY+mYeXBoZoxTfdSQ8VAJaCw= +cloud.google.com/go/maps v0.7.0/go.mod h1:3GnvVl3cqeSvgMcpRlQidXsPYuDGQ8naBis7MVzpXsY= +cloud.google.com/go/mediatranslation v0.5.0/go.mod h1:jGPUhGTybqsPQn91pNXw0xVHfuJ3leR1wj37oU3y1f4= +cloud.google.com/go/mediatranslation v0.6.0/go.mod h1:hHdBCTYNigsBxshbznuIMFNe5QXEowAuNmmC7h8pu5w= +cloud.google.com/go/mediatranslation v0.7.0/go.mod h1:LCnB/gZr90ONOIQLgSXagp8XUW1ODs2UmUMvcgMfI2I= +cloud.google.com/go/memcache v1.4.0/go.mod h1:rTOfiGZtJX1AaFUrOgsMHX5kAzaTQ8azHiuDoTPzNsE= +cloud.google.com/go/memcache v1.5.0/go.mod h1:dk3fCK7dVo0cUU2c36jKb4VqKPS22BTkf81Xq617aWM= +cloud.google.com/go/memcache v1.6.0/go.mod h1:XS5xB0eQZdHtTuTF9Hf8eJkKtR3pVRCcvJwtm68T3rA= +cloud.google.com/go/memcache v1.7.0/go.mod h1:ywMKfjWhNtkQTxrWxCkCFkoPjLHPW6A7WOTVI8xy3LY= +cloud.google.com/go/memcache v1.9.0/go.mod h1:8oEyzXCu+zo9RzlEaEjHl4KkgjlNDaXbCQeQWlzNFJM= +cloud.google.com/go/metastore v1.5.0/go.mod h1:2ZNrDcQwghfdtCwJ33nM0+GrBGlVuh8rakL3vdPY3XY= +cloud.google.com/go/metastore v1.6.0/go.mod h1:6cyQTls8CWXzk45G55x57DVQ9gWg7RiH65+YgPsNh9s= +cloud.google.com/go/metastore v1.7.0/go.mod h1:s45D0B4IlsINu87/AsWiEVYbLaIMeUSoxlKKDqBGFS8= +cloud.google.com/go/metastore v1.8.0/go.mod h1:zHiMc4ZUpBiM7twCIFQmJ9JMEkDSyZS9U12uf7wHqSI= +cloud.google.com/go/metastore v1.10.0/go.mod h1:fPEnH3g4JJAk+gMRnrAnoqyv2lpUCqJPWOodSaf45Eo= +cloud.google.com/go/monitoring v1.7.0/go.mod h1:HpYse6kkGo//7p6sT0wsIC6IBDET0RhIsnmlA53dvEk= +cloud.google.com/go/monitoring v1.8.0/go.mod h1:E7PtoMJ1kQXWxPjB6mv2fhC5/15jInuulFdYYtlcvT4= +cloud.google.com/go/monitoring v1.12.0/go.mod h1:yx8Jj2fZNEkL/GYZyTLS4ZtZEZN8WtDEiEqG4kLK50w= +cloud.google.com/go/monitoring v1.13.0/go.mod h1:k2yMBAB1H9JT/QETjNkgdCGD9bPF712XiLTVr+cBrpw= +cloud.google.com/go/networkconnectivity v1.4.0/go.mod h1:nOl7YL8odKyAOtzNX73/M5/mGZgqqMeryi6UPZTk/rA= +cloud.google.com/go/networkconnectivity v1.5.0/go.mod h1:3GzqJx7uhtlM3kln0+x5wyFvuVH1pIBJjhCpjzSt75o= +cloud.google.com/go/networkconnectivity v1.6.0/go.mod h1:OJOoEXW+0LAxHh89nXd64uGG+FbQoeH8DtxCHVOMlaM= +cloud.google.com/go/networkconnectivity v1.7.0/go.mod h1:RMuSbkdbPwNMQjB5HBWD5MpTBnNm39iAVpC3TmsExt8= +cloud.google.com/go/networkconnectivity v1.10.0/go.mod h1:UP4O4sWXJG13AqrTdQCD9TnLGEbtNRqjuaaA7bNjF5E= +cloud.google.com/go/networkconnectivity v1.11.0/go.mod h1:iWmDD4QF16VCDLXUqvyspJjIEtBR/4zq5hwnY2X3scM= +cloud.google.com/go/networkmanagement v1.4.0/go.mod h1:Q9mdLLRn60AsOrPc8rs8iNV6OHXaGcDdsIQe1ohekq8= +cloud.google.com/go/networkmanagement v1.5.0/go.mod h1:ZnOeZ/evzUdUsnvRt792H0uYEnHQEMaz+REhhzJRcf4= +cloud.google.com/go/networkmanagement v1.6.0/go.mod h1:5pKPqyXjB/sgtvB5xqOemumoQNB7y95Q7S+4rjSOPYY= +cloud.google.com/go/networksecurity v0.5.0/go.mod h1:xS6fOCoqpVC5zx15Z/MqkfDwH4+m/61A3ODiDV1xmiQ= +cloud.google.com/go/networksecurity v0.6.0/go.mod h1:Q5fjhTr9WMI5mbpRYEbiexTzROf7ZbDzvzCrNl14nyU= +cloud.google.com/go/networksecurity v0.7.0/go.mod h1:mAnzoxx/8TBSyXEeESMy9OOYwo1v+gZ5eMRnsT5bC8k= +cloud.google.com/go/networksecurity v0.8.0/go.mod h1:B78DkqsxFG5zRSVuwYFRZ9Xz8IcQ5iECsNrPn74hKHU= +cloud.google.com/go/notebooks v1.2.0/go.mod h1:9+wtppMfVPUeJ8fIWPOq1UnATHISkGXGqTkxeieQ6UY= +cloud.google.com/go/notebooks v1.3.0/go.mod h1:bFR5lj07DtCPC7YAAJ//vHskFBxA5JzYlH68kXVdk34= +cloud.google.com/go/notebooks v1.4.0/go.mod h1:4QPMngcwmgb6uw7Po99B2xv5ufVoIQ7nOGDyL4P8AgA= +cloud.google.com/go/notebooks v1.5.0/go.mod h1:q8mwhnP9aR8Hpfnrc5iN5IBhrXUy8S2vuYs+kBJ/gu0= +cloud.google.com/go/notebooks v1.7.0/go.mod h1:PVlaDGfJgj1fl1S3dUwhFMXFgfYGhYQt2164xOMONmE= +cloud.google.com/go/notebooks v1.8.0/go.mod h1:Lq6dYKOYOWUCTvw5t2q1gp1lAp0zxAxRycayS0iJcqQ= +cloud.google.com/go/optimization v1.1.0/go.mod h1:5po+wfvX5AQlPznyVEZjGJTMr4+CAkJf2XSTQOOl9l4= +cloud.google.com/go/optimization v1.2.0/go.mod h1:Lr7SOHdRDENsh+WXVmQhQTrzdu9ybg0NecjHidBq6xs= +cloud.google.com/go/optimization v1.3.1/go.mod h1:IvUSefKiwd1a5p0RgHDbWCIbDFgKuEdB+fPPuP0IDLI= +cloud.google.com/go/orchestration v1.3.0/go.mod h1:Sj5tq/JpWiB//X/q3Ngwdl5K7B7Y0KZ7bfv0wL6fqVA= +cloud.google.com/go/orchestration v1.4.0/go.mod h1:6W5NLFWs2TlniBphAViZEVhrXRSMgUGDfW7vrWKvsBk= +cloud.google.com/go/orchestration v1.6.0/go.mod h1:M62Bevp7pkxStDfFfTuCOaXgaaqRAga1yKyoMtEoWPQ= +cloud.google.com/go/orgpolicy v1.4.0/go.mod h1:xrSLIV4RePWmP9P3tBl8S93lTmlAxjm06NSm2UTmKvE= +cloud.google.com/go/orgpolicy v1.5.0/go.mod h1:hZEc5q3wzwXJaKrsx5+Ewg0u1LxJ51nNFlext7Tanwc= +cloud.google.com/go/orgpolicy v1.10.0/go.mod h1:w1fo8b7rRqlXlIJbVhOMPrwVljyuW5mqssvBtU18ONc= +cloud.google.com/go/osconfig v1.7.0/go.mod h1:oVHeCeZELfJP7XLxcBGTMBvRO+1nQ5tFG9VQTmYS2Fs= +cloud.google.com/go/osconfig v1.8.0/go.mod h1:EQqZLu5w5XA7eKizepumcvWx+m8mJUhEwiPqWiZeEdg= +cloud.google.com/go/osconfig v1.9.0/go.mod h1:Yx+IeIZJ3bdWmzbQU4fxNl8xsZ4amB+dygAwFPlvnNo= +cloud.google.com/go/osconfig v1.10.0/go.mod h1:uMhCzqC5I8zfD9zDEAfvgVhDS8oIjySWh+l4WK6GnWw= +cloud.google.com/go/osconfig v1.11.0/go.mod h1:aDICxrur2ogRd9zY5ytBLV89KEgT2MKB2L/n6x1ooPw= +cloud.google.com/go/oslogin v1.4.0/go.mod h1:YdgMXWRaElXz/lDk1Na6Fh5orF7gvmJ0FGLIs9LId4E= +cloud.google.com/go/oslogin v1.5.0/go.mod h1:D260Qj11W2qx/HVF29zBg+0fd6YCSjSqLUkY/qEenQU= +cloud.google.com/go/oslogin v1.6.0/go.mod h1:zOJ1O3+dTU8WPlGEkFSh7qeHPPSoxrcMbbK1Nm2iX70= +cloud.google.com/go/oslogin v1.7.0/go.mod h1:e04SN0xO1UNJ1M5GP0vzVBFicIe4O53FOfcixIqTyXo= +cloud.google.com/go/oslogin v1.9.0/go.mod h1:HNavntnH8nzrn8JCTT5fj18FuJLFJc4NaZJtBnQtKFs= +cloud.google.com/go/phishingprotection v0.5.0/go.mod h1:Y3HZknsK9bc9dMi+oE8Bim0lczMU6hrX0UpADuMefr0= +cloud.google.com/go/phishingprotection v0.6.0/go.mod h1:9Y3LBLgy0kDTcYET8ZH3bq/7qni15yVUoAxiFxnlSUA= +cloud.google.com/go/phishingprotection v0.7.0/go.mod h1:8qJI4QKHoda/sb/7/YmMQ2omRLSLYSu9bU0EKCNI+Lk= +cloud.google.com/go/policytroubleshooter v1.3.0/go.mod h1:qy0+VwANja+kKrjlQuOzmlvscn4RNsAc0e15GGqfMxg= +cloud.google.com/go/policytroubleshooter v1.4.0/go.mod h1:DZT4BcRw3QoO8ota9xw/LKtPa8lKeCByYeKTIf/vxdE= +cloud.google.com/go/policytroubleshooter v1.5.0/go.mod h1:Rz1WfV+1oIpPdN2VvvuboLVRsB1Hclg3CKQ53j9l8vw= +cloud.google.com/go/policytroubleshooter v1.6.0/go.mod h1:zYqaPTsmfvpjm5ULxAyD/lINQxJ0DDsnWOP/GZ7xzBc= +cloud.google.com/go/privatecatalog v0.5.0/go.mod h1:XgosMUvvPyxDjAVNDYxJ7wBW8//hLDDYmnsNcMGq1K0= +cloud.google.com/go/privatecatalog v0.6.0/go.mod h1:i/fbkZR0hLN29eEWiiwue8Pb+GforiEIBnV9yrRUOKI= +cloud.google.com/go/privatecatalog v0.7.0/go.mod h1:2s5ssIFO69F5csTXcwBP7NPFTZvps26xGzvQ2PQaBYg= +cloud.google.com/go/privatecatalog v0.8.0/go.mod h1:nQ6pfaegeDAq/Q5lrfCQzQLhubPiZhSaNhIgfJlnIXs= +cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= +cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= +cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= +cloud.google.com/go/pubsub v1.26.0/go.mod h1:QgBH3U/jdJy/ftjPhTkyXNj543Tin1pRYcdcPRnFIRI= +cloud.google.com/go/pubsub v1.27.1/go.mod h1:hQN39ymbV9geqBnfQq6Xf63yNhUAhv9CZhzp5O6qsW0= +cloud.google.com/go/pubsub v1.28.0/go.mod h1:vuXFpwaVoIPQMGXqRyUQigu/AX1S3IWugR9xznmcXX8= +cloud.google.com/go/pubsub v1.30.0/go.mod h1:qWi1OPS0B+b5L+Sg6Gmc9zD1Y+HaM0MdUr7LsupY1P4= +cloud.google.com/go/pubsublite v1.5.0/go.mod h1:xapqNQ1CuLfGi23Yda/9l4bBCKz/wC3KIJ5gKcxveZg= +cloud.google.com/go/pubsublite v1.6.0/go.mod h1:1eFCS0U11xlOuMFV/0iBqw3zP12kddMeCbj/F3FSj9k= +cloud.google.com/go/pubsublite v1.7.0/go.mod h1:8hVMwRXfDfvGm3fahVbtDbiLePT3gpoiJYJY+vxWxVM= +cloud.google.com/go/recaptchaenterprise v1.3.1/go.mod h1:OdD+q+y4XGeAlxRaMn1Y7/GveP6zmq76byL6tjPE7d4= +cloud.google.com/go/recaptchaenterprise/v2 v2.1.0/go.mod h1:w9yVqajwroDNTfGuhmOjPDN//rZGySaf6PtFVcSCa7o= +cloud.google.com/go/recaptchaenterprise/v2 v2.2.0/go.mod h1:/Zu5jisWGeERrd5HnlS3EUGb/D335f9k51B/FVil0jk= +cloud.google.com/go/recaptchaenterprise/v2 v2.3.0/go.mod h1:O9LwGCjrhGHBQET5CA7dd5NwwNQUErSgEDit1DLNTdo= +cloud.google.com/go/recaptchaenterprise/v2 v2.4.0/go.mod h1:Am3LHfOuBstrLrNCBrlI5sbwx9LBg3te2N6hGvHn2mE= +cloud.google.com/go/recaptchaenterprise/v2 v2.5.0/go.mod h1:O8LzcHXN3rz0j+LBC91jrwI3R+1ZSZEWrfL7XHgNo9U= +cloud.google.com/go/recaptchaenterprise/v2 v2.6.0/go.mod h1:RPauz9jeLtB3JVzg6nCbe12qNoaa8pXc4d/YukAmcnA= +cloud.google.com/go/recaptchaenterprise/v2 v2.7.0/go.mod h1:19wVj/fs5RtYtynAPJdDTb69oW0vNHYDBTbB4NvMD9c= +cloud.google.com/go/recommendationengine v0.5.0/go.mod h1:E5756pJcVFeVgaQv3WNpImkFP8a+RptV6dDLGPILjvg= +cloud.google.com/go/recommendationengine v0.6.0/go.mod h1:08mq2umu9oIqc7tDy8sx+MNJdLG0fUi3vaSVbztHgJ4= +cloud.google.com/go/recommendationengine v0.7.0/go.mod h1:1reUcE3GIu6MeBz/h5xZJqNLuuVjNg1lmWMPyjatzac= +cloud.google.com/go/recommender v1.5.0/go.mod h1:jdoeiBIVrJe9gQjwd759ecLJbxCDED4A6p+mqoqDvTg= +cloud.google.com/go/recommender v1.6.0/go.mod h1:+yETpm25mcoiECKh9DEScGzIRyDKpZ0cEhWGo+8bo+c= +cloud.google.com/go/recommender v1.7.0/go.mod h1:XLHs/W+T8olwlGOgfQenXBTbIseGclClff6lhFVe9Bs= +cloud.google.com/go/recommender v1.8.0/go.mod h1:PkjXrTT05BFKwxaUxQmtIlrtj0kph108r02ZZQ5FE70= +cloud.google.com/go/recommender v1.9.0/go.mod h1:PnSsnZY7q+VL1uax2JWkt/UegHssxjUVVCrX52CuEmQ= +cloud.google.com/go/redis v1.7.0/go.mod h1:V3x5Jq1jzUcg+UNsRvdmsfuFnit1cfe3Z/PGyq/lm4Y= +cloud.google.com/go/redis v1.8.0/go.mod h1:Fm2szCDavWzBk2cDKxrkmWBqoCiL1+Ctwq7EyqBCA/A= +cloud.google.com/go/redis v1.9.0/go.mod h1:HMYQuajvb2D0LvMgZmLDZW8V5aOC/WxstZHiy4g8OiA= +cloud.google.com/go/redis v1.10.0/go.mod h1:ThJf3mMBQtW18JzGgh41/Wld6vnDDc/F/F35UolRZPM= +cloud.google.com/go/redis v1.11.0/go.mod h1:/X6eicana+BWcUda5PpwZC48o37SiFVTFSs0fWAJ7uQ= +cloud.google.com/go/resourcemanager v1.3.0/go.mod h1:bAtrTjZQFJkiWTPDb1WBjzvc6/kifjj4QBYuKCCoqKA= +cloud.google.com/go/resourcemanager v1.4.0/go.mod h1:MwxuzkumyTX7/a3n37gmsT3py7LIXwrShilPh3P1tR0= +cloud.google.com/go/resourcemanager v1.5.0/go.mod h1:eQoXNAiAvCf5PXxWxXjhKQoTMaUSNrEfg+6qdf/wots= +cloud.google.com/go/resourcemanager v1.6.0/go.mod h1:YcpXGRs8fDzcUl1Xw8uOVmI8JEadvhRIkoXXUNVYcVo= +cloud.google.com/go/resourcemanager v1.7.0/go.mod h1:HlD3m6+bwhzj9XCouqmeiGuni95NTrExfhoSrkC/3EI= +cloud.google.com/go/resourcesettings v1.3.0/go.mod h1:lzew8VfESA5DQ8gdlHwMrqZs1S9V87v3oCnKCWoOuQU= +cloud.google.com/go/resourcesettings v1.4.0/go.mod h1:ldiH9IJpcrlC3VSuCGvjR5of/ezRrOxFtpJoJo5SmXg= +cloud.google.com/go/resourcesettings v1.5.0/go.mod h1:+xJF7QSG6undsQDfsCJyqWXyBwUoJLhetkRMDRnIoXA= +cloud.google.com/go/retail v1.8.0/go.mod h1:QblKS8waDmNUhghY2TI9O3JLlFk8jybHeV4BF19FrE4= +cloud.google.com/go/retail v1.9.0/go.mod h1:g6jb6mKuCS1QKnH/dpu7isX253absFl6iE92nHwlBUY= +cloud.google.com/go/retail v1.10.0/go.mod h1:2gDk9HsL4HMS4oZwz6daui2/jmKvqShXKQuB2RZ+cCc= +cloud.google.com/go/retail v1.11.0/go.mod h1:MBLk1NaWPmh6iVFSz9MeKG/Psyd7TAgm6y/9L2B4x9Y= +cloud.google.com/go/retail v1.12.0/go.mod h1:UMkelN/0Z8XvKymXFbD4EhFJlYKRx1FGhQkVPU5kF14= +cloud.google.com/go/run v0.2.0/go.mod h1:CNtKsTA1sDcnqqIFR3Pb5Tq0usWxJJvsWOCPldRU3Do= +cloud.google.com/go/run v0.3.0/go.mod h1:TuyY1+taHxTjrD0ZFk2iAR+xyOXEA0ztb7U3UNA0zBo= +cloud.google.com/go/run v0.8.0/go.mod h1:VniEnuBwqjigv0A7ONfQUaEItaiCRVujlMqerPPiktM= +cloud.google.com/go/run v0.9.0/go.mod h1:Wwu+/vvg8Y+JUApMwEDfVfhetv30hCG4ZwDR/IXl2Qg= +cloud.google.com/go/scheduler v1.4.0/go.mod h1:drcJBmxF3aqZJRhmkHQ9b3uSSpQoltBPGPxGAWROx6s= +cloud.google.com/go/scheduler v1.5.0/go.mod h1:ri073ym49NW3AfT6DZi21vLZrG07GXr5p3H1KxN5QlI= +cloud.google.com/go/scheduler v1.6.0/go.mod h1:SgeKVM7MIwPn3BqtcBntpLyrIJftQISRrYB5ZtT+KOk= +cloud.google.com/go/scheduler v1.7.0/go.mod h1:jyCiBqWW956uBjjPMMuX09n3x37mtyPJegEWKxRsn44= +cloud.google.com/go/scheduler v1.8.0/go.mod h1:TCET+Y5Gp1YgHT8py4nlg2Sew8nUHMqcpousDgXJVQc= +cloud.google.com/go/scheduler v1.9.0/go.mod h1:yexg5t+KSmqu+njTIh3b7oYPheFtBWGcbVUYF1GGMIc= +cloud.google.com/go/secretmanager v1.6.0/go.mod h1:awVa/OXF6IiyaU1wQ34inzQNc4ISIDIrId8qE5QGgKA= +cloud.google.com/go/secretmanager v1.8.0/go.mod h1:hnVgi/bN5MYHd3Gt0SPuTPPp5ENina1/LxM+2W9U9J4= +cloud.google.com/go/secretmanager v1.9.0/go.mod h1:b71qH2l1yHmWQHt9LC80akm86mX8AL6X1MA01dW8ht4= +cloud.google.com/go/secretmanager v1.10.0/go.mod h1:MfnrdvKMPNra9aZtQFvBcvRU54hbPD8/HayQdlUgJpU= +cloud.google.com/go/security v1.5.0/go.mod h1:lgxGdyOKKjHL4YG3/YwIL2zLqMFCKs0UbQwgyZmfJl4= +cloud.google.com/go/security v1.7.0/go.mod h1:mZklORHl6Bg7CNnnjLH//0UlAlaXqiG7Lb9PsPXLfD0= +cloud.google.com/go/security v1.8.0/go.mod h1:hAQOwgmaHhztFhiQ41CjDODdWP0+AE1B3sX4OFlq+GU= +cloud.google.com/go/security v1.9.0/go.mod h1:6Ta1bO8LXI89nZnmnsZGp9lVoVWXqsVbIq/t9dzI+2Q= +cloud.google.com/go/security v1.10.0/go.mod h1:QtOMZByJVlibUT2h9afNDWRZ1G96gVywH8T5GUSb9IA= +cloud.google.com/go/security v1.12.0/go.mod h1:rV6EhrpbNHrrxqlvW0BWAIawFWq3X90SduMJdFwtLB8= +cloud.google.com/go/security v1.13.0/go.mod h1:Q1Nvxl1PAgmeW0y3HTt54JYIvUdtcpYKVfIB8AOMZ+0= +cloud.google.com/go/securitycenter v1.13.0/go.mod h1:cv5qNAqjY84FCN6Y9z28WlkKXyWsgLO832YiWwkCWcU= +cloud.google.com/go/securitycenter v1.14.0/go.mod h1:gZLAhtyKv85n52XYWt6RmeBdydyxfPeTrpToDPw4Auc= +cloud.google.com/go/securitycenter v1.15.0/go.mod h1:PeKJ0t8MoFmmXLXWm41JidyzI3PJjd8sXWaVqg43WWk= +cloud.google.com/go/securitycenter v1.16.0/go.mod h1:Q9GMaLQFUD+5ZTabrbujNWLtSLZIZF7SAR0wWECrjdk= +cloud.google.com/go/securitycenter v1.18.1/go.mod h1:0/25gAzCM/9OL9vVx4ChPeM/+DlfGQJDwBy/UC8AKK0= +cloud.google.com/go/securitycenter v1.19.0/go.mod h1:LVLmSg8ZkkyaNy4u7HCIshAngSQ8EcIRREP3xBnyfag= +cloud.google.com/go/servicecontrol v1.4.0/go.mod h1:o0hUSJ1TXJAmi/7fLJAedOovnujSEvjKCAFNXPQ1RaU= +cloud.google.com/go/servicecontrol v1.5.0/go.mod h1:qM0CnXHhyqKVuiZnGKrIurvVImCs8gmqWsDoqe9sU1s= +cloud.google.com/go/servicecontrol v1.10.0/go.mod h1:pQvyvSRh7YzUF2efw7H87V92mxU8FnFDawMClGCNuAA= +cloud.google.com/go/servicecontrol v1.11.0/go.mod h1:kFmTzYzTUIuZs0ycVqRHNaNhgR+UMUpw9n02l/pY+mc= +cloud.google.com/go/servicecontrol v1.11.1/go.mod h1:aSnNNlwEFBY+PWGQ2DoM0JJ/QUXqV5/ZD9DOLB7SnUk= +cloud.google.com/go/servicedirectory v1.4.0/go.mod h1:gH1MUaZCgtP7qQiI+F+A+OpeKF/HQWgtAddhTbhL2bs= +cloud.google.com/go/servicedirectory v1.5.0/go.mod h1:QMKFL0NUySbpZJ1UZs3oFAmdvVxhhxB6eJ/Vlp73dfg= +cloud.google.com/go/servicedirectory v1.6.0/go.mod h1:pUlbnWsLH9c13yGkxCmfumWEPjsRs1RlmJ4pqiNjVL4= +cloud.google.com/go/servicedirectory v1.7.0/go.mod h1:5p/U5oyvgYGYejufvxhgwjL8UVXjkuw7q5XcG10wx1U= +cloud.google.com/go/servicedirectory v1.8.0/go.mod h1:srXodfhY1GFIPvltunswqXpVxFPpZjf8nkKQT7XcXaY= +cloud.google.com/go/servicedirectory v1.9.0/go.mod h1:29je5JjiygNYlmsGz8k6o+OZ8vd4f//bQLtvzkPPT/s= +cloud.google.com/go/servicemanagement v1.4.0/go.mod h1:d8t8MDbezI7Z2R1O/wu8oTggo3BI2GKYbdG4y/SJTco= +cloud.google.com/go/servicemanagement v1.5.0/go.mod h1:XGaCRe57kfqu4+lRxaFEAuqmjzF0r+gWHjWqKqBvKFo= +cloud.google.com/go/servicemanagement v1.6.0/go.mod h1:aWns7EeeCOtGEX4OvZUWCCJONRZeFKiptqKf1D0l/Jc= +cloud.google.com/go/servicemanagement v1.8.0/go.mod h1:MSS2TDlIEQD/fzsSGfCdJItQveu9NXnUniTrq/L8LK4= +cloud.google.com/go/serviceusage v1.3.0/go.mod h1:Hya1cozXM4SeSKTAgGXgj97GlqUvF5JaoXacR1JTP/E= +cloud.google.com/go/serviceusage v1.4.0/go.mod h1:SB4yxXSaYVuUBYUml6qklyONXNLt83U0Rb+CXyhjEeU= +cloud.google.com/go/serviceusage v1.5.0/go.mod h1:w8U1JvqUqwJNPEOTQjrMHkw3IaIFLoLsPLvsE3xueec= +cloud.google.com/go/serviceusage v1.6.0/go.mod h1:R5wwQcbOWsyuOfbP9tGdAnCAc6B9DRwPG1xtWMDeuPA= +cloud.google.com/go/shell v1.3.0/go.mod h1:VZ9HmRjZBsjLGXusm7K5Q5lzzByZmJHf1d0IWHEN5X4= +cloud.google.com/go/shell v1.4.0/go.mod h1:HDxPzZf3GkDdhExzD/gs8Grqk+dmYcEjGShZgYa9URw= +cloud.google.com/go/shell v1.6.0/go.mod h1:oHO8QACS90luWgxP3N9iZVuEiSF84zNyLytb+qE2f9A= +cloud.google.com/go/spanner v1.41.0/go.mod h1:MLYDBJR/dY4Wt7ZaMIQ7rXOTLjYrmxLE/5ve9vFfWos= +cloud.google.com/go/spanner v1.44.0/go.mod h1:G8XIgYdOK+Fbcpbs7p2fiprDw4CaZX63whnSMLVBxjk= +cloud.google.com/go/spanner v1.45.0/go.mod h1:FIws5LowYz8YAE1J8fOS7DJup8ff7xJeetWEo5REA2M= +cloud.google.com/go/speech v1.6.0/go.mod h1:79tcr4FHCimOp56lwC01xnt/WPJZc4v3gzyT7FoBkCM= +cloud.google.com/go/speech v1.7.0/go.mod h1:KptqL+BAQIhMsj1kOP2la5DSEEerPDuOP/2mmkhHhZQ= +cloud.google.com/go/speech v1.8.0/go.mod h1:9bYIl1/tjsAnMgKGHKmBZzXKEkGgtU+MpdDPTE9f7y0= +cloud.google.com/go/speech v1.9.0/go.mod h1:xQ0jTcmnRFFM2RfX/U+rk6FQNUF6DQlydUSyoooSpco= +cloud.google.com/go/speech v1.14.1/go.mod h1:gEosVRPJ9waG7zqqnsHpYTOoAS4KouMRLDFMekpJ0J0= +cloud.google.com/go/speech v1.15.0/go.mod h1:y6oH7GhqCaZANH7+Oe0BhgIogsNInLlz542tg3VqeYI= +cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= +cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= +cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= +cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= +cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= +cloud.google.com/go/storage v1.22.1/go.mod h1:S8N1cAStu7BOeFfE8KAQzmyyLkK8p/vmRq6kuBTW58Y= +cloud.google.com/go/storage v1.23.0/go.mod h1:vOEEDNFnciUMhBeT6hsJIn3ieU5cFRmzeLgDvXzfIXc= +cloud.google.com/go/storage v1.27.0/go.mod h1:x9DOL8TK/ygDUMieqwfhdpQryTeEkhGKMi80i/iqR2s= +cloud.google.com/go/storage v1.28.1/go.mod h1:Qnisd4CqDdo6BGs2AD5LLnEsmSQ80wQ5ogcBBKhU86Y= +cloud.google.com/go/storage v1.29.0/go.mod h1:4puEjyTKnku6gfKoTfNOU/W+a9JyuVNxjpS5GBrB8h4= +cloud.google.com/go/storagetransfer v1.5.0/go.mod h1:dxNzUopWy7RQevYFHewchb29POFv3/AaBgnhqzqiK0w= +cloud.google.com/go/storagetransfer v1.6.0/go.mod h1:y77xm4CQV/ZhFZH75PLEXY0ROiS7Gh6pSKrM8dJyg6I= +cloud.google.com/go/storagetransfer v1.7.0/go.mod h1:8Giuj1QNb1kfLAiWM1bN6dHzfdlDAVC9rv9abHot2W4= +cloud.google.com/go/storagetransfer v1.8.0/go.mod h1:JpegsHHU1eXg7lMHkvf+KE5XDJ7EQu0GwNJbbVGanEw= +cloud.google.com/go/talent v1.1.0/go.mod h1:Vl4pt9jiHKvOgF9KoZo6Kob9oV4lwd/ZD5Cto54zDRw= +cloud.google.com/go/talent v1.2.0/go.mod h1:MoNF9bhFQbiJ6eFD3uSsg0uBALw4n4gaCaEjBw9zo8g= +cloud.google.com/go/talent v1.3.0/go.mod h1:CmcxwJ/PKfRgd1pBjQgU6W3YBwiewmUzQYH5HHmSCmM= +cloud.google.com/go/talent v1.4.0/go.mod h1:ezFtAgVuRf8jRsvyE6EwmbTK5LKciD4KVnHuDEFmOOA= +cloud.google.com/go/talent v1.5.0/go.mod h1:G+ODMj9bsasAEJkQSzO2uHQWXHHXUomArjWQQYkqK6c= +cloud.google.com/go/texttospeech v1.4.0/go.mod h1:FX8HQHA6sEpJ7rCMSfXuzBcysDAuWusNNNvN9FELDd8= +cloud.google.com/go/texttospeech v1.5.0/go.mod h1:oKPLhR4n4ZdQqWKURdwxMy0uiTS1xU161C8W57Wkea4= +cloud.google.com/go/texttospeech v1.6.0/go.mod h1:YmwmFT8pj1aBblQOI3TfKmwibnsfvhIBzPXcW4EBovc= +cloud.google.com/go/tpu v1.3.0/go.mod h1:aJIManG0o20tfDQlRIej44FcwGGl/cD0oiRyMKG19IQ= +cloud.google.com/go/tpu v1.4.0/go.mod h1:mjZaX8p0VBgllCzF6wcU2ovUXN9TONFLd7iz227X2Xg= +cloud.google.com/go/tpu v1.5.0/go.mod h1:8zVo1rYDFuW2l4yZVY0R0fb/v44xLh3llq7RuV61fPM= +cloud.google.com/go/trace v1.3.0/go.mod h1:FFUE83d9Ca57C+K8rDl/Ih8LwOzWIV1krKgxg6N0G28= +cloud.google.com/go/trace v1.4.0/go.mod h1:UG0v8UBqzusp+z63o7FK74SdFE+AXpCLdFb1rshXG+Y= +cloud.google.com/go/trace v1.8.0/go.mod h1:zH7vcsbAhklH8hWFig58HvxcxyQbaIqMarMg9hn5ECA= +cloud.google.com/go/trace v1.9.0/go.mod h1:lOQqpE5IaWY0Ixg7/r2SjixMuc6lfTFeO4QGM4dQWOk= +cloud.google.com/go/translate v1.3.0/go.mod h1:gzMUwRjvOqj5i69y/LYLd8RrNQk+hOmIXTi9+nb3Djs= +cloud.google.com/go/translate v1.4.0/go.mod h1:06Dn/ppvLD6WvA5Rhdp029IX2Mi3Mn7fpMRLPvXT5Wg= +cloud.google.com/go/translate v1.5.0/go.mod h1:29YDSYveqqpA1CQFD7NQuP49xymq17RXNaUDdc0mNu0= +cloud.google.com/go/translate v1.6.0/go.mod h1:lMGRudH1pu7I3n3PETiOB2507gf3HnfLV8qlkHZEyos= +cloud.google.com/go/translate v1.7.0/go.mod h1:lMGRudH1pu7I3n3PETiOB2507gf3HnfLV8qlkHZEyos= +cloud.google.com/go/video v1.8.0/go.mod h1:sTzKFc0bUSByE8Yoh8X0mn8bMymItVGPfTuUBUyRgxk= +cloud.google.com/go/video v1.9.0/go.mod h1:0RhNKFRF5v92f8dQt0yhaHrEuH95m068JYOvLZYnJSw= +cloud.google.com/go/video v1.12.0/go.mod h1:MLQew95eTuaNDEGriQdcYn0dTwf9oWiA4uYebxM5kdg= +cloud.google.com/go/video v1.13.0/go.mod h1:ulzkYlYgCp15N2AokzKjy7MQ9ejuynOJdf1tR5lGthk= +cloud.google.com/go/video v1.14.0/go.mod h1:SkgaXwT+lIIAKqWAJfktHT/RbgjSuY6DobxEp0C5yTQ= +cloud.google.com/go/video v1.15.0/go.mod h1:SkgaXwT+lIIAKqWAJfktHT/RbgjSuY6DobxEp0C5yTQ= +cloud.google.com/go/videointelligence v1.6.0/go.mod h1:w0DIDlVRKtwPCn/C4iwZIJdvC69yInhW0cfi+p546uU= +cloud.google.com/go/videointelligence v1.7.0/go.mod h1:k8pI/1wAhjznARtVT9U1llUaFNPh7muw8QyOUpavru4= +cloud.google.com/go/videointelligence v1.8.0/go.mod h1:dIcCn4gVDdS7yte/w+koiXn5dWVplOZkE+xwG9FgK+M= +cloud.google.com/go/videointelligence v1.9.0/go.mod h1:29lVRMPDYHikk3v8EdPSaL8Ku+eMzDljjuvRs105XoU= +cloud.google.com/go/videointelligence v1.10.0/go.mod h1:LHZngX1liVtUhZvi2uNS0VQuOzNi2TkY1OakiuoUOjU= +cloud.google.com/go/vision v1.2.0/go.mod h1:SmNwgObm5DpFBme2xpyOyasvBc1aPdjvMk2bBk0tKD0= +cloud.google.com/go/vision/v2 v2.2.0/go.mod h1:uCdV4PpN1S0jyCyq8sIM42v2Y6zOLkZs+4R9LrGYwFo= +cloud.google.com/go/vision/v2 v2.3.0/go.mod h1:UO61abBx9QRMFkNBbf1D8B1LXdS2cGiiCRx0vSpZoUo= +cloud.google.com/go/vision/v2 v2.4.0/go.mod h1:VtI579ll9RpVTrdKdkMzckdnwMyX2JILb+MhPqRbPsY= +cloud.google.com/go/vision/v2 v2.5.0/go.mod h1:MmaezXOOE+IWa+cS7OhRRLK2cNv1ZL98zhqFFZaaH2E= +cloud.google.com/go/vision/v2 v2.6.0/go.mod h1:158Hes0MvOS9Z/bDMSFpjwsUrZ5fPrdwuyyvKSGAGMY= +cloud.google.com/go/vision/v2 v2.7.0/go.mod h1:H89VysHy21avemp6xcf9b9JvZHVehWbET0uT/bcuY/0= +cloud.google.com/go/vmmigration v1.2.0/go.mod h1:IRf0o7myyWFSmVR1ItrBSFLFD/rJkfDCUTO4vLlJvsE= +cloud.google.com/go/vmmigration v1.3.0/go.mod h1:oGJ6ZgGPQOFdjHuocGcLqX4lc98YQ7Ygq8YQwHh9A7g= +cloud.google.com/go/vmmigration v1.5.0/go.mod h1:E4YQ8q7/4W9gobHjQg4JJSgXXSgY21nA5r8swQV+Xxc= +cloud.google.com/go/vmmigration v1.6.0/go.mod h1:bopQ/g4z+8qXzichC7GW1w2MjbErL54rk3/C843CjfY= +cloud.google.com/go/vmwareengine v0.1.0/go.mod h1:RsdNEf/8UDvKllXhMz5J40XxDrNJNN4sagiox+OI208= +cloud.google.com/go/vmwareengine v0.2.2/go.mod h1:sKdctNJxb3KLZkE/6Oui94iw/xs9PRNC2wnNLXsHvH8= +cloud.google.com/go/vmwareengine v0.3.0/go.mod h1:wvoyMvNWdIzxMYSpH/R7y2h5h3WFkx6d+1TIsP39WGY= +cloud.google.com/go/vpcaccess v1.4.0/go.mod h1:aQHVbTWDYUR1EbTApSVvMq1EnT57ppDmQzZ3imqIk4w= +cloud.google.com/go/vpcaccess v1.5.0/go.mod h1:drmg4HLk9NkZpGfCmZ3Tz0Bwnm2+DKqViEpeEpOq0m8= +cloud.google.com/go/vpcaccess v1.6.0/go.mod h1:wX2ILaNhe7TlVa4vC5xce1bCnqE3AeH27RV31lnmZes= +cloud.google.com/go/webrisk v1.4.0/go.mod h1:Hn8X6Zr+ziE2aNd8SliSDWpEnSS1u4R9+xXZmFiHmGE= +cloud.google.com/go/webrisk v1.5.0/go.mod h1:iPG6fr52Tv7sGk0H6qUFzmL3HHZev1htXuWDEEsqMTg= +cloud.google.com/go/webrisk v1.6.0/go.mod h1:65sW9V9rOosnc9ZY7A7jsy1zoHS5W9IAXv6dGqhMQMc= +cloud.google.com/go/webrisk v1.7.0/go.mod h1:mVMHgEYH0r337nmt1JyLthzMr6YxwN1aAIEc2fTcq7A= +cloud.google.com/go/webrisk v1.8.0/go.mod h1:oJPDuamzHXgUc+b8SiHRcVInZQuybnvEW72PqTc7sSg= +cloud.google.com/go/websecurityscanner v1.3.0/go.mod h1:uImdKm2wyeXQevQJXeh8Uun/Ym1VqworNDlBXQevGMo= +cloud.google.com/go/websecurityscanner v1.4.0/go.mod h1:ebit/Fp0a+FWu5j4JOmJEV8S8CzdTkAS77oDsiSqYWQ= +cloud.google.com/go/websecurityscanner v1.5.0/go.mod h1:Y6xdCPy81yi0SQnDY1xdNTNpfY1oAgXUlcfN3B3eSng= +cloud.google.com/go/workflows v1.6.0/go.mod h1:6t9F5h/unJz41YqfBmqSASJSXccBLtD1Vwf+KmJENM0= +cloud.google.com/go/workflows v1.7.0/go.mod h1:JhSrZuVZWuiDfKEFxU0/F1PQjmpnpcoISEXH2bcHC3M= +cloud.google.com/go/workflows v1.8.0/go.mod h1:ysGhmEajwZxGn1OhGOGKsTXc5PyxOc0vfKf5Af+to4M= +cloud.google.com/go/workflows v1.9.0/go.mod h1:ZGkj1aFIOd9c8Gerkjjq7OW7I5+l6cSvT3ujaO/WwSA= +cloud.google.com/go/workflows v1.10.0/go.mod h1:fZ8LmRmZQWacon9UCX1r/g/DfAXx5VcPALq2CxzdePw= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +gioui.org v0.0.0-20210308172011-57750fc8a0a6/go.mod h1:RSH6KIUZ0p2xy5zHDxgAM4zumjgTw83q2ge/PI+yyw8= +git.sr.ht/~sbinet/gg v0.3.1/go.mod h1:KGYtlADtqsqANL9ueOFkWymvzUvLMQllU5Ixo+8v3pc= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c/go.mod h1:X0CRv0ky0k6m906ixxpzmDRLvX58TFUKS2eePweuyxk= +github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= +github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= +github.com/StackExchange/wmi v1.2.1 h1:VIkavFPXSjcnS+O8yTq7NI32k0R5Aj+v39y29VYDOSA= +github.com/StackExchange/wmi v1.2.1/go.mod h1:rcmrprowKIVzvc+NUiLncP2uuArMWLCbu9SBzvHz7e8= +github.com/VividCortex/godaemon v1.0.0 h1:aHYrScWvgaSOdAoYCdObWXLm+e1rldP9Pwb1ZvuZkQw= +github.com/VividCortex/godaemon v1.0.0/go.mod h1:hBWe/72KbGt/lb95E+Sh9ersdYbB57Dt6CG66S1YPno= +github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= +github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c= +github.com/ajstarks/deck v0.0.0-20200831202436-30c9fc6549a9/go.mod h1:JynElWSGnm/4RlzPXRlREEwqTHAN3T56Bv2ITsFT3gY= +github.com/ajstarks/deck/generate v0.0.0-20210309230005-c3f852c02e19/go.mod h1:T13YZdzov6OU0A1+RfKZiZN9ca6VeKdBdyDV+BY97Tk= +github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw= +github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b/go.mod h1:1KcenG0jGWcpt8ov532z81sp/kMMUG485J2InIOyADM= +github.com/alecthomas/kingpin/v2 v2.3.1/go.mod h1:oYL5vtsvEHZGHxU7DMp32Dvx+qL+ptGn6lWaot2vCNE= +github.com/alecthomas/kingpin/v2 v2.3.2/go.mod h1:0gyi0zQnjuFk8xrkNKamJoyUo382HRL7ATRpFZCw6tE= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= +github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= +github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= +github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk= +github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/apache/arrow/go/v10 v10.0.1/go.mod h1:YvhnlEePVnBS4+0z3fhPfUy7W1Ikj0Ih0vcRo/gZ1M0= +github.com/apache/arrow/go/v11 v11.0.0/go.mod h1:Eg5OsL5H+e299f7u5ssuXsuHQVEGC4xei5aX110hRiI= +github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= +github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= +github.com/apache/thrift v0.16.0/go.mod h1:PHK3hniurgQaNMZYaCLEqXKsYK8upmhPbmdP2FXSqgU= +github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= +github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= +github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/aryann/difflib v0.0.0-20170710044230-e206f873d14a/go.mod h1:DAHtR1m6lCRdSC2Tm3DSWRPvIPr6xNKyeHdqDQSQT+A= +github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU= +github.com/aws/aws-sdk-go v1.27.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= +github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= +github.com/beego/beego/v2 v2.0.6 h1:21Aqz3+RzUE1yP9a5xdU6LK54n9Z7NLEJtR4PE7NrPQ= +github.com/beego/beego/v2 v2.0.6/go.mod h1:CH2/JIaB4ceGYVQlYqTAFft4pVk/ol1ZkakUrUvAyns= +github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/boombuler/barcode v1.0.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= +github.com/boombuler/barcode v1.0.1/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= +github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA= +github.com/casbin/casbin v1.9.1/go.mod h1:z8uPsfBJGUsnkagrt3G8QvjgTKFMBJ32UP8HpZllfog= +github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= +github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/census-instrumentation/opencensus-proto v0.3.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/census-instrumentation/opencensus-proto v0.4.1/go.mod h1:4T9NM4+4Vw91VeyqjLS6ao50K5bOcLKN6Q42XnYaRYw= +github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= +github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/chromedp/cdproto v0.0.0-20230802225258-3cf4e6d46a89/go.mod h1:GKljq0VrfU4D5yc+2qA6OVr8pmO/MBbPEWqWQ/oqGEs= +github.com/chromedp/chromedp v0.9.2/go.mod h1:LkSXJKONWTCHAfQasKFUZI+mxqS4tZqhmtGzzhLsnLs= +github.com/chromedp/sysutil v1.0.0/go.mod h1:kgWmDdq8fTzXYcKIBqIYvRRTnYb9aNS9moAV0xufSww= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/logex v1.2.1/go.mod h1:JLbx6lG2kDbNRFnfkgvh4eRJRPX1QCoOIWomwysCBrQ= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8= +github.com/clbanning/x2j v0.0.0-20191024224557-825249438eec/go.mod h1:jMjuTZXRI4dUb/I5gc9Hdhagfvm9+RyrPryS/auMzxE= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= +github.com/cncf/udpa/go v0.0.0-20220112060539-c52dc94e7fbe/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= +github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20220314180256-7f1daf1720fc/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20230105202645-06c439db220b/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20230310173818-32f1caf87195/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= +github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= +github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/couchbase/go-couchbase v0.1.0/go.mod h1:+/bddYDxXsf9qt0xpDUtRR47A2GjaXmGGAqQ/k3GJ8A= +github.com/couchbase/gomemcached v0.1.3/go.mod h1:mxliKQxOv84gQ0bJWbI+w9Wxdpt9HjDvgW9MjCym5Vo= +github.com/couchbase/goutils v0.1.0/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= +github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= +github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= +github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= +github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/elastic/go-elasticsearch/v6 v6.8.10/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= +github.com/elazarl/go-bindata-assetfs v1.0.1 h1:m0kkaHRKEu7tUIUFVwhGGGYClXvyl4RE03qmvRTNfbw= +github.com/elazarl/go-bindata-assetfs v1.0.1/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= +github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= +github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= +github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= +github.com/envoyproxy/go-control-plane v0.10.3/go.mod h1:fJJn/j26vwOu972OllsvAgJJM//w9BV6Fxbg2LuVd34= +github.com/envoyproxy/go-control-plane v0.11.0/go.mod h1:VnHyVMpzcLvCFt9yUz1UnCwHLhwx1WguiVDV7pTG/tI= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/envoyproxy/protoc-gen-validate v0.6.7/go.mod h1:dyJXwwfPK2VSqiB9Klm1J6romD608Ba7Hij42vrOBCo= +github.com/envoyproxy/protoc-gen-validate v0.9.1/go.mod h1:OKNgG7TCp5pF4d6XftA0++PMirau2/yoOwVac3AbF2w= +github.com/envoyproxy/protoc-gen-validate v0.10.0/go.mod h1:DRjgyB0I43LtJapqN6NiRwroiAU2PaFuvk/vjgh61ss= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= +github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= +github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4= +github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= +github.com/go-fonts/dejavu v0.1.0/go.mod h1:4Wt4I4OU2Nq9asgDCteaAaWZOV24E+0/Pwo0gppep4g= +github.com/go-fonts/latin-modern v0.2.0/go.mod h1:rQVLdDMK+mK1xscDwsqM5J8U2jrRa3T0ecnM9pNujks= +github.com/go-fonts/liberation v0.1.1/go.mod h1:K6qoJYypsmfVjWg8KOVDQhLc8UDgIK2HYqyqAO9z7GY= +github.com/go-fonts/liberation v0.2.0/go.mod h1:K6qoJYypsmfVjWg8KOVDQhLc8UDgIK2HYqyqAO9z7GY= +github.com/go-fonts/stix v0.1.0/go.mod h1:w/c1f0ldAUlJmLBvlbkvVXLAD+tAMqobIIQpmnUIzUY= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.10.0/go.mod h1:xUsJbQ/Fp4kEt7AFgCuvyX4a71u8h9jB8tj/ORgOZ7o= +github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= +github.com/go-kit/log v0.2.0/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= +github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= +github.com/go-latex/latex v0.0.0-20210118124228-b3d85cf34e07/go.mod h1:CO1AlKB2CSIqUrmQPqA0gdRIlnLEY0gK5JGjh37zN5U= +github.com/go-latex/latex v0.0.0-20210823091927-c0d11ff05a81/go.mod h1:SX0U8uGpxhq9o2S/CELCSUxEWWAuoCUcVCQWv7G2OCk= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-ole/go-ole v1.2.5 h1:t4MGB5xEDZvXI+0rMjjsfBsD7yAgp/s9ZDkL1JndXwY= +github.com/go-ole/go-ole v1.2.5/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-pdf/fpdf v0.5.0/go.mod h1:HzcnA+A23uwogo0tp9yU+l3V+KXhiESpt1PMayhOh5M= +github.com/go-pdf/fpdf v0.6.0/go.mod h1:HzcnA+A23uwogo0tp9yU+l3V+KXhiESpt1PMayhOh5M= +github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= +github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= +github.com/go-redis/redis v6.15.9+incompatible h1:K0pv1D7EQUjfyoMql+r/jZqCLizCGKFlFgcHWWmHQjg= +github.com/go-redis/redis v6.15.9+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= +github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= +github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc= +github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= +github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= +github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM= +github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/ws v1.2.1/go.mod h1:hRKAFb8wOxFROYNsT1bqfWnhX+b5MFeJM9r2ZSwg/KY= +github.com/goccy/go-json v0.9.11/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= +github.com/golang/glog v1.1.0/go.mod h1:pfYeQZ3JWZoXTV5sFc986z3HTpwQs9At6P4ImfuP3NQ= +github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= +github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= +github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.1/go.mod h1:DopwsBzvsk0Fs44TXzsVbJyPhcCPeIwnvohx4u74HPM= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/flatbuffers v2.0.8+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/martian/v3 v3.2.1/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk= +github.com/google/martian/v3 v3.3.2/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20240424215950-a892ee059fd6/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/s2a-go v0.1.0/go.mod h1:OJpEgntRZo8ugHpF9hkoLJbS5dSI20XZeXJ9JVywLlM= +github.com/google/s2a-go v0.1.3/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= +github.com/google/s2a-go v0.1.4/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= +github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/enterprise-certificate-proxy v0.0.0-20220520183353-fd19c99a87aa/go.mod h1:17drOmN3MwGY7t0e+Ei9b45FFGA3fBs3x36SsCg1hq8= +github.com/googleapis/enterprise-certificate-proxy v0.1.0/go.mod h1:17drOmN3MwGY7t0e+Ei9b45FFGA3fBs3x36SsCg1hq8= +github.com/googleapis/enterprise-certificate-proxy v0.2.0/go.mod h1:8C0jb7/mgJe/9KK8Lm7X9ctZC2t60YyIpYEI16jx0Qg= +github.com/googleapis/enterprise-certificate-proxy v0.2.1/go.mod h1:AwSRAtLfXpU5Nm3pW+v7rGDHp09LsPtGY9MduiEsR9k= +github.com/googleapis/enterprise-certificate-proxy v0.2.3/go.mod h1:AwSRAtLfXpU5Nm3pW+v7rGDHp09LsPtGY9MduiEsR9k= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pfu6SK+H1/DsU0= +github.com/googleapis/gax-go/v2 v2.1.1/go.mod h1:hddJymUZASv3XPyGkUpKj8pPO47Rmb0eJc8R6ouapiM= +github.com/googleapis/gax-go/v2 v2.2.0/go.mod h1:as02EH8zWkzwUoLbBaFeQ+arQaj/OthfcblKl4IGNaM= +github.com/googleapis/gax-go/v2 v2.3.0/go.mod h1:b8LNqSzNabLiUpXKkY7HAR5jr6bIT99EXz9pXxye9YM= +github.com/googleapis/gax-go/v2 v2.4.0/go.mod h1:XOTVJ59hdnfJLIP/dh8n5CGryZR2LxK9wbMD5+iXC6c= +github.com/googleapis/gax-go/v2 v2.5.1/go.mod h1:h6B0KMMFNtI2ddbGJn3T3ZbwkeT6yqEF02fYlzkUCyo= +github.com/googleapis/gax-go/v2 v2.6.0/go.mod h1:1mjbznJAPHFpesgE5ucqfYEscaz5kMdcIDwU/6+DDoY= +github.com/googleapis/gax-go/v2 v2.7.0/go.mod h1:TEop28CZZQ2y+c0VxMUmu1lV+fQx57QpBWsYpwqHJx8= +github.com/googleapis/gax-go/v2 v2.7.1/go.mod h1:4orTrqY6hXxxaUL4LHIPl6lGo8vAE38/qKbhSAKP6QI= +github.com/googleapis/gax-go/v2 v2.8.0/go.mod h1:4orTrqY6hXxxaUL4LHIPl6lGo8vAE38/qKbhSAKP6QI= +github.com/googleapis/gax-go/v2 v2.10.0/go.mod h1:4UOEnMCrxsSqQ940WnTiD6qJ63le2ev3xfyagutxiPw= +github.com/googleapis/gax-go/v2 v2.11.0/go.mod h1:DxmR61SGKkGLa2xigwuZIQpkCI2S5iydzRfb3peWZJI= +github.com/googleapis/go-type-adapters v1.0.0/go.mod h1:zHW75FOG2aur7gAO2B+MLby+cLsWGBF62rFAi7WjWO4= +github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= +github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0/go.mod h1:hgWBS7lorOAVIJEQMi4ZsPv9hVvWI6+ch50m39Pf2Ks= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.11.3/go.mod h1:o//XUCC/F+yRGJoPO/VU0GSB0f8Nhgmxx0VIRUvaC0w= +github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE= +github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= +github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= +github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= +github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= +github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= +github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= +github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= +github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= +github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= +github.com/iancoleman/strcase v0.2.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/ianlancetaylor/demangle v0.0.0-20240312041847-bd984b5ce465/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw= +github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= +github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.8/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= +github.com/jung-kurt/gofpdf v1.0.0/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= +github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= +github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= +github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/asmfmt v1.3.2/go.mod h1:AG8TuvYojzulgDAMCnYn50l/5QV3Bs/tp6j0HLHbNSE= +github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDuKuq+uX4v1fulaMbA/7ZLLhjc85h7chZGBCQ= +github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs= +github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/lib/pq v1.10.5/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= +github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= +github.com/lyft/protoc-gen-star v0.6.0/go.mod h1:TGAoBVkt8w7MPG72TrKIu85MIdXwDuzJYeZuUPFPNwA= +github.com/lyft/protoc-gen-star v0.6.1/go.mod h1:TGAoBVkt8w7MPG72TrKIu85MIdXwDuzJYeZuUPFPNwA= +github.com/lyft/protoc-gen-star/v2 v2.0.1/go.mod h1:RcCdONR2ScXaYnQC5tUzxzlpA3WVYF7/opLeUgcQs/o= +github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-sqlite3 v1.14.7/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= +github.com/mattn/go-sqlite3 v1.14.14/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= +github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= +github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 h1:jWpvCLoY8Z/e3VKvlsiIGKtc+UG6U5vzxaoagmhXfyg= +github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0/go.mod h1:QUyp042oQthUoa9bqDv0ER0wrtXnBruoNd7aNjkbP+k= +github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= +github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8/go.mod h1:mC1jAcsrzbxHt8iiaC+zU4b1ylILSosueou12R++wfY= +github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3/go.mod h1:RagcQ7I8IeTMnF8JTXieKnO4Z6JCsikNEzj0DwauVzE= +github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= +github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= +github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= +github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= +github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/mapstructure v1.4.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= +github.com/nats-io/jwt v0.3.2/go.mod h1:/euKqTS1ZD+zzjYrY7pseZrTtWQSjujC7xjPc8wL6eU= +github.com/nats-io/nats-server/v2 v2.1.2/go.mod h1:Afk+wRZqkMQs/p45uXdrVLuab3gwv3Z8C4HTBu8GD/k= +github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w= +github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= +github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= +github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= +github.com/oklog/oklog v0.3.2/go.mod h1:FCV+B7mhrz4o+ueLpx+KqkyXRGMWOYEvfiXtdGtbWGs= +github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= +github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= +github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= +github.com/onsi/ginkgo/v2 v2.1.4/go.mod h1:um6tUpWM/cxCK3/FK8BXqEiUMUwRgSM4JXG47RKZmLU= +github.com/onsi/ginkgo/v2 v2.1.6/go.mod h1:MEH45j8TBi6u9BMogfbp0stKC5cdGjumZj5Y7AG4VIk= +github.com/onsi/ginkgo/v2 v2.3.0/go.mod h1:Eew0uilEqZmIEZr8JrvYlvOM7Rr6xzTmMV8AyFNU9d0= +github.com/onsi/ginkgo/v2 v2.4.0/go.mod h1:iHkDK1fKGcBoEHT5W7YBq4RFWaQulw+caOMkAt4OrFo= +github.com/onsi/ginkgo/v2 v2.5.0/go.mod h1:Luc4sArBICYCS8THh8v3i3i5CuSZO+RaQRaJoeNwomw= +github.com/onsi/ginkgo/v2 v2.7.0/go.mod h1:yjiuMwPokqY1XauOgju45q3sJt6VzQ/Fict1LFVcsAo= +github.com/onsi/ginkgo/v2 v2.8.1/go.mod h1:N1/NbDngAFcSLdyZ+/aYTYGSlq9qMCS/cNKGJjy+csc= +github.com/onsi/ginkgo/v2 v2.9.0/go.mod h1:4xkjoL/tZv4SMWeww56BU5kAt19mVB47gTWxmrTcxyk= +github.com/onsi/ginkgo/v2 v2.9.1/go.mod h1:FEcmzVcCHl+4o9bQZVab+4dC9+j+91t2FHSzmGAPfuo= +github.com/onsi/ginkgo/v2 v2.9.2/go.mod h1:WHcJJG2dIlcCqVfBAwUCrJxSPFb6v4azBwgxeMeDuts= +github.com/onsi/ginkgo/v2 v2.9.5/go.mod h1:tvAoo1QUJwNEU2ITftXTpR7R1RbCzoZUOs3RonqW57k= +github.com/onsi/ginkgo/v2 v2.9.7/go.mod h1:cxrmXWykAwTwhQsJOPfdIDiJ+l2RYq7U8hFU+M/1uw0= +github.com/onsi/ginkgo/v2 v2.11.0/go.mod h1:ZhrRA5XmEE3x3rhlzamx/JJvujdZoJ2uvgI7kR0iZvM= +github.com/onsi/ginkgo/v2 v2.13.0/go.mod h1:TE309ZR8s5FsKKpuB1YAQYBzCaAfUgatB/xlT/ETL/o= +github.com/onsi/ginkgo/v2 v2.17.1/go.mod h1:llBI3WDLL9Z6taip6f33H76YcWtJv+7R3HigUjbIBOs= +github.com/onsi/ginkgo/v2 v2.17.2/go.mod h1:nP2DPOQoNsQmsVyv5rDA8JkXQoCs6goXIvr/PRJ1eCc= +github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= +github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= +github.com/onsi/gomega v1.20.1/go.mod h1:DtrZpjmvpn2mPm4YWQa0/ALMDj9v4YxLgojwPeREyVo= +github.com/onsi/gomega v1.21.1/go.mod h1:iYAIXgPSaDHak0LCMA+AWBpIKBr8WZicMxnE8luStNc= +github.com/onsi/gomega v1.22.1/go.mod h1:x6n7VNe4hw0vkyYUM4mjIXx3JbLiPaBPNgB7PRQ1tuM= +github.com/onsi/gomega v1.24.0/go.mod h1:Z/NWtiqwBrwUt4/2loMmHL63EDLnYHmVbuBpDr2vQAg= +github.com/onsi/gomega v1.24.1/go.mod h1:3AOiACssS3/MajrniINInwbfOOtfZvplPzuRSmvt1jM= +github.com/onsi/gomega v1.26.0/go.mod h1:r+zV744Re+DiYCIPRlYOTxn0YkOLcAnW8k1xXdMPGhM= +github.com/onsi/gomega v1.27.1/go.mod h1:aHX5xOykVYzWOV4WqQy0sy8BQptgukenXpCXfadcIAw= +github.com/onsi/gomega v1.27.3/go.mod h1:5vG284IBtfDAmDyrK+eGyZmUgUlmi+Wngqo557cZ6Gw= +github.com/onsi/gomega v1.27.4/go.mod h1:riYq/GJKh8hhoM01HN6Vmuy93AarCXCBGpvFDK3q3fQ= +github.com/onsi/gomega v1.27.6/go.mod h1:PIQNjfQwkP3aQAH7lf7j87O/5FiNr+ZR8+ipb+qQlhg= +github.com/onsi/gomega v1.27.7/go.mod h1:1p8OOlwo2iUUDsHnOrjE5UKYJ+e3W8eQ3qSlRahPmr4= +github.com/onsi/gomega v1.27.8/go.mod h1:2J8vzI/s+2shY9XHRApDkdgPo1TKT7P2u6fXeJKFnNQ= +github.com/onsi/gomega v1.27.10/go.mod h1:RsS8tutOdbdgzbPtzzATp12yT7kM5I5aElG3evPbQ0M= +github.com/onsi/gomega v1.30.0/go.mod h1:9sxs+SwGrKI0+PWe4Fxa9tFQQBG5xSsSbMXOI8PPpoQ= +github.com/onsi/gomega v1.33.0/go.mod h1:+925n5YtiFsLzzafLUHzVMBpvvRAzrydIBiSIxjX3wY= +github.com/onsi/gomega v1.33.1 h1:dsYjIxxSR755MDmKVsaFQTE22ChNBcuuTWgkUDSubOk= +github.com/onsi/gomega v1.33.1/go.mod h1:U4R44UsT+9eLIaYRB2a5qajjtQYn0hauxvRm16AVYg0= +github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= +github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492/go.mod h1:Ngi6UdF0k5OKD5t5wlmGhe/EDKPoUM3BXZSSfIuJbis= +github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74= +github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxSfWAKL3wpBW7V8scJMt8N8gnaMCS9E/cA= +github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= +github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= +github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= +github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0= +github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM= +github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= +github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= +github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= +github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= +github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.9.2/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= +github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= +github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= +github.com/phpdave11/gofpdf v1.4.2/go.mod h1:zpO6xFn9yxo3YLyMvW8HcKWVdbNqgIfOOp2dXMnm1mY= +github.com/phpdave11/gofpdi v1.0.12/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI= +github.com/phpdave11/gofpdi v1.0.13/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI= +github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= +github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= +github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= +github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= +github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= +github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= +github.com/prometheus/client_golang v1.11.1/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= +github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY= +github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.1/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= +github.com/prometheus/client_golang v1.17.0/go.mod h1:VeL+gMmOAxkS2IqfCq0ZmHSL+LjWfWDUmp1mBz9JgUY= +github.com/prometheus/client_golang v1.18.0 h1:HzFfmkOzH5Q8L8G+kSJKUx5dtG87sewO+FoDDqP5Tbk= +github.com/prometheus/client_golang v1.18.0/go.mod h1:T+GXkCk5wSJyOqMIzVgvvjFDlkOQntgjkJWKrN5txjA= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.1.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= +github.com/prometheus/client_model v0.4.0/go.mod h1:oMQmHW1/JoDwqLtg57MGgP/Fb1CJEYF2imWWhWtMkYU= +github.com/prometheus/client_model v0.4.1-0.20230718164431-9a2bf3000d16/go.mod h1:oMQmHW1/JoDwqLtg57MGgP/Fb1CJEYF2imWWhWtMkYU= +github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw= +github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI= +github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= +github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= +github.com/prometheus/common v0.37.0/go.mod h1:phzohg0JFMnBEFGxTDbfu3QyL5GI8gTQJFhYO5B3mfA= +github.com/prometheus/common v0.42.0/go.mod h1:xBwqVerjNdUDjgODMpudtOMwlOwf2SaTr1yjz4b7Zbc= +github.com/prometheus/common v0.44.0/go.mod h1:ofAIvZbQ1e/nugmZGz4/qCb9Ap1VoSTIO7x0VV9VvuY= +github.com/prometheus/common v0.45.0 h1:2BGz0eBc2hdMDLnO/8n0jeB3oPrt2D08CekT0lneoxM= +github.com/prometheus/common v0.45.0/go.mod h1:YJmSTw9BoKxJplESWWxlbyttQR4uaEcGyv9MZjVOJsY= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= +github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= +github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0uaxHdg830/4= +github.com/prometheus/procfs v0.9.0/go.mod h1:+pB4zwohETzFnmlpe6yd2lSc+0/46IYZRB/chUwxUZY= +github.com/prometheus/procfs v0.11.1/go.mod h1:eesXgaPo1q7lBpVMoMy0ZOFTth9hBn4W/y0/p/ScXhY= +github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo= +github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo= +github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/ruudk/golang-pdf417 v0.0.0-20181029194003-1af4ab5afa58/go.mod h1:6lfFZQK844Gfx8o5WFuvpxWRwnSoipWe/p622j1v06w= +github.com/ruudk/golang-pdf417 v0.0.0-20201230142125-a7e3863a1245/go.mod h1:pQAZKsJ8yyVxGRWYNEm9oFB8ieLgKFnamEyDmSA0BRk= +github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= +github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= +github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18 h1:DAYUYH5869yV94zvCES9F51oYtN5oGlwjxJJz7ZCnik= +github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= +github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s= +github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= +github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= +github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/spf13/afero v1.3.3/go.mod h1:5KUK8ByomD5Ti5Artl0RtHeI5pTF7MIDuXL3yY520V4= +github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= +github.com/spf13/afero v1.9.2/go.mod h1:iUV7ddyEEZPO5gA3zD4fJt6iStLlL+Lg4m2cihcDf8Y= +github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE= +github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= +github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= +github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= +github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= +github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= +github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= +github.com/xhit/go-str2duration v1.2.0/go.mod h1:3cPSlfZlUHVlneIVfePFWcJZsuwf+P1v2SRTV4cUmp4= +github.com/xhit/go-str2duration/v2 v2.1.0/go.mod h1:ohY8p+0f07DiV6Em5LKB0s2YpLtXVyJfNt1+BlmyAsU= +github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= +github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= +github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= +github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= +go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= +go.etcd.io/etcd/api/v3 v3.5.4/go.mod h1:5GB2vv4A4AOn3yk7MftYGHkUfGtDHnEraIjym4dYz5A= +go.etcd.io/etcd/client/pkg/v3 v3.5.4/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= +go.etcd.io/etcd/client/v3 v3.5.4/go.mod h1:ZaRkVgBZC+L+dLCjTcF1hRXpgZXQPOvnA/Ak/gq3kiY= +go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= +go.opencensus.io v0.20.2/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= +go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= +go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= +go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +go.opentelemetry.io/otel v1.8.0/go.mod h1:2pkj+iMj0o03Y+cW6/m8Y4WkRdYN3AvCXCnzRMp9yvM= +go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.8.0/go.mod h1:ztncjvKpotSUQq7rlgPibGt8kZfSI3/jI8EO7JjuY2c= +go.opentelemetry.io/otel/sdk v1.8.0/go.mod h1:uPSfc+yfDH2StDM/Rm35WE8gXSNdvCg023J6HeGNO0c= +go.opentelemetry.io/otel/trace v1.8.0/go.mod h1:0Bt3PXY8w+3pheS3hQUt+wow8b1ojPaTBoTCh2zIFI4= +go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= +go.opentelemetry.io/proto/otlp v0.15.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI405h3+duxN4U= +go.opentelemetry.io/proto/otlp v0.19.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI405h3+duxN4U= +go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= +go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= +go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220314234659-1baeb1ce4c0b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw= +golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0= +golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= +golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= +golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= +golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= +golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= +golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190125153040-c74c464bbbf2/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= +golang.org/x/exp v0.0.0-20191002040644-a1355ae1e2c3/go.mod h1:NOZ3BPKG0ec/BKJQgnvsSFpcKLM5xXVWnvZS97DWHgE= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/exp v0.0.0-20220827204233-334a2380cb91/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= +golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20200119044424-58c23975cae1/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20200430140353-33d19683fad8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20200618115811-c13761719519/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20201208152932-35266b937fa6/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20210216034530-4410531fe030/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20210607152325-775e3b0c77b9/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM= +golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM= +golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM= +golang.org/x/image v0.0.0-20220302094943-723b81ca9867/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.5.0/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= +golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= +golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.6.0/go.mod h1:4mET923SAdbXp2ki8ey+zGs1SLqsuM2Y0uvdZR/fUNI= +golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= +golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220325170049-de3da57026de/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220412020605-290c469a71a5/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20220617184016-355a448f1bc9/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20220909164309-bea034e7d591/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= +golang.org/x/net v0.0.0-20221012135044-0b7e1fb9d458/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= +golang.org/x/net v0.0.0-20221014081412-f15817d10f9b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= +golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= +golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= +golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= +golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= +golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= +golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= +golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= +golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= +golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= +golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210805134026-6f1e6394065a/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= +golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= +golang.org/x/oauth2 v0.0.0-20220411215720-9780585627b5/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= +golang.org/x/oauth2 v0.0.0-20220608161450-d0670ef3b1eb/go.mod h1:jaDAt6Dkxork7LmZnYtzbRWj0W47D86a3TGe0YHBvmE= +golang.org/x/oauth2 v0.0.0-20220622183110-fd043fe589d2/go.mod h1:jaDAt6Dkxork7LmZnYtzbRWj0W47D86a3TGe0YHBvmE= +golang.org/x/oauth2 v0.0.0-20220822191816-0ebed06d0094/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= +golang.org/x/oauth2 v0.0.0-20220909003341-f21342109be1/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= +golang.org/x/oauth2 v0.0.0-20221006150949-b44042a4b9c1/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= +golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= +golang.org/x/oauth2 v0.4.0/go.mod h1:RznEsdpjGAINPTOF0UH/t+xJ75L18YO3Ho6Pyn+uRec= +golang.org/x/oauth2 v0.5.0/go.mod h1:9/XBHVqLaWO3/BRHs5jbpYCnOZVjj5V0ndyaAM7KB4I= +golang.org/x/oauth2 v0.6.0/go.mod h1:ycmewcwgD4Rpr3eZJLSB4Kyyljb3qDh40vJ8STE5HKw= +golang.org/x/oauth2 v0.7.0/go.mod h1:hPLQkd9LyjfXTiRohC/41GhcFqxisoUQ99sCUOHO9x4= +golang.org/x/oauth2 v0.8.0/go.mod h1:yr7u4HXZRm1R1kBWqr/xKNqewf0plRYoB7sla+BCIXE= +golang.org/x/oauth2 v0.12.0/go.mod h1:A74bZ3aGXgCY0qaIC9Ahg6Lglin4AMAco8cIv9baba4= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220929204114-8fcdb60fdcc0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.2.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210304124612-50617c2ba197/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210603125802-9665404d3644/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210816183151-1e6c022a8912/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220328115105-d36c6a25d886/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220502124256-b6088ccd6cba/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220624220833-87e55d714810/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220829200755-d48e67d00261/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= +golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= +golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= +golang.org/x/term v0.4.0/go.mod h1:9P2UbLfCdcvo3p/nzKvsmas4TnlujnuoV9hGgYzW1lQ= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o= +golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= +golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= +golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= +golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= +golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= +golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58= +golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk= +golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20220922220347-f3bd1da661af/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.1.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190927191325-030b2cf1153e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= +golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= +golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.2.0/go.mod h1:y4OqIKeOV/fWJetJ8bXPU1sEVniLMIyDAZWeHdV+NTA= +golang.org/x/tools v0.3.0/go.mod h1:/rWhSS2+zyEVwoJf8YAX6L2f0ntZ7Kn/mGgAWcipA5k= +golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s= +golang.org/x/tools v0.9.1/go.mod h1:owI94Op576fPu3cIGQeHs3joujW/2Oc6MtlxbF5dfNc= +golang.org/x/tools v0.9.3/go.mod h1:owI94Op576fPu3cIGQeHs3joujW/2Oc6MtlxbF5dfNc= +golang.org/x/tools v0.12.0/go.mod h1:Sc0INKfu04TlqNoRA1hgpFZbhYXHPr4V5DzpSBTPqQM= +golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= +golang.org/x/tools v0.17.0/go.mod h1:xsh6VxdV005rRVaS6SSAf9oiAqljS7UZUacMZ8Bnsps= +golang.org/x/tools v0.20.0/go.mod h1:WvitBU7JJf6A4jOdg4S1tviW9bhUxkgeCui/0JHctQg= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +gonum.org/v1/gonum v0.0.0-20180816165407-929014505bf4/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= +gonum.org/v1/gonum v0.8.2/go.mod h1:oe/vMfY3deqTw+1EZJhuvEW2iwGF1bW9wwu7XCu0+v0= +gonum.org/v1/gonum v0.9.3/go.mod h1:TZumC3NeyVQskjXqmyWt4S3bINhy7B4eYwW69EbyX+0= +gonum.org/v1/gonum v0.11.0/go.mod h1:fSG4YDCxxUZQJ7rKsQrj0gMOg00Il0Z96/qMA4bVQhA= +gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw= +gonum.org/v1/plot v0.0.0-20190515093506-e2840ee46a6b/go.mod h1:Wt8AAjI+ypCyYX3nZBvf6cAIx93T+c/OS2HFAYskSZc= +gonum.org/v1/plot v0.9.0/go.mod h1:3Pcqqmp6RHvJI72kgb8fThyUnav364FOsdDo2aGW5lY= +gonum.org/v1/plot v0.10.1/go.mod h1:VZW5OlhkL1mysU9vaqNHnsy86inf6Ot+jB3r+BczCEo= +google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= +google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= +google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= +google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= +google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= +google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= +google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= +google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= +google.golang.org/api v0.48.0/go.mod h1:71Pr1vy+TAZRPkPs/xlCf5SsU8WjuAWv1Pfjbtukyy4= +google.golang.org/api v0.50.0/go.mod h1:4bNT5pAuq5ji4SRZm+5QIkjny9JAyVD/3gaSihNefaw= +google.golang.org/api v0.51.0/go.mod h1:t4HdrdoNgyN5cbEfm7Lum0lcLDLiise1F8qDKX00sOU= +google.golang.org/api v0.54.0/go.mod h1:7C4bFFOvVDGXjfDTAsgGwDgAxRDeQ4X8NvUedIt6z3k= +google.golang.org/api v0.55.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqivdVE= +google.golang.org/api v0.56.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqivdVE= +google.golang.org/api v0.57.0/go.mod h1:dVPlbZyBo2/OjBpmvNdpn2GRm6rPy75jyU7bmhdrMgI= +google.golang.org/api v0.61.0/go.mod h1:xQRti5UdCmoCEqFxcz93fTl338AVqDgyaDRuOZ3hg9I= +google.golang.org/api v0.63.0/go.mod h1:gs4ij2ffTRXwuzzgJl/56BdwJaA194ijkfn++9tDuPo= +google.golang.org/api v0.67.0/go.mod h1:ShHKP8E60yPsKNw/w8w+VYaj9H6buA5UqDp8dhbQZ6g= +google.golang.org/api v0.70.0/go.mod h1:Bs4ZM2HGifEvXwd50TtW70ovgJffJYw2oRCOFU/SkfA= +google.golang.org/api v0.71.0/go.mod h1:4PyU6e6JogV1f9eA4voyrTY2batOLdgZ5qZ5HOCc4j8= +google.golang.org/api v0.74.0/go.mod h1:ZpfMZOVRMywNyvJFeqL9HRWBgAuRfSjJFpe9QtRRyDs= +google.golang.org/api v0.75.0/go.mod h1:pU9QmyHLnzlpar1Mjt4IbapUCy8J+6HD6GeELN69ljA= +google.golang.org/api v0.77.0/go.mod h1:pU9QmyHLnzlpar1Mjt4IbapUCy8J+6HD6GeELN69ljA= +google.golang.org/api v0.78.0/go.mod h1:1Sg78yoMLOhlQTeF+ARBoytAcH1NNyyl390YMy6rKmw= +google.golang.org/api v0.80.0/go.mod h1:xY3nI94gbvBrE0J6NHXhxOmW97HG7Khjkku6AFB3Hyg= +google.golang.org/api v0.84.0/go.mod h1:NTsGnUFJMYROtiquksZHBWtHfeMC7iYthki7Eq3pa8o= +google.golang.org/api v0.85.0/go.mod h1:AqZf8Ep9uZ2pyTvgL+x0D3Zt0eoT9b5E8fmzfu6FO2g= +google.golang.org/api v0.90.0/go.mod h1:+Sem1dnrKlrXMR/X0bPnMWyluQe4RsNoYfmNLhOIkzw= +google.golang.org/api v0.93.0/go.mod h1:+Sem1dnrKlrXMR/X0bPnMWyluQe4RsNoYfmNLhOIkzw= +google.golang.org/api v0.95.0/go.mod h1:eADj+UBuxkh5zlrSntJghuNeg8HwQ1w5lTKkuqaETEI= +google.golang.org/api v0.96.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ13s= +google.golang.org/api v0.97.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ13s= +google.golang.org/api v0.98.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ13s= +google.golang.org/api v0.99.0/go.mod h1:1YOf74vkVndF7pG6hIHuINsM7eWwpVTAfNMNiL91A08= +google.golang.org/api v0.100.0/go.mod h1:ZE3Z2+ZOr87Rx7dqFsdRQkRBk36kDtp/h+QpHbB7a70= +google.golang.org/api v0.102.0/go.mod h1:3VFl6/fzoA+qNuS1N1/VfXY4LjoXN/wzeIp7TweWwGo= +google.golang.org/api v0.103.0/go.mod h1:hGtW6nK1AC+d9si/UBhw8Xli+QMOf6xyNAyJw4qU9w0= +google.golang.org/api v0.106.0/go.mod h1:2Ts0XTHNVWxypznxWOYUeI4g3WdP9Pk2Qk58+a/O9MY= +google.golang.org/api v0.107.0/go.mod h1:2Ts0XTHNVWxypznxWOYUeI4g3WdP9Pk2Qk58+a/O9MY= +google.golang.org/api v0.108.0/go.mod h1:2Ts0XTHNVWxypznxWOYUeI4g3WdP9Pk2Qk58+a/O9MY= +google.golang.org/api v0.110.0/go.mod h1:7FC4Vvx1Mooxh8C5HWjzZHcavuS2f6pmJpZx60ca7iI= +google.golang.org/api v0.111.0/go.mod h1:qtFHvU9mhgTJegR31csQ+rwxyUTHOKFqCKWp1J0fdw0= +google.golang.org/api v0.114.0/go.mod h1:ifYI2ZsFK6/uGddGfAD5BMxlnkBqCmqHSDUVi45N5Yg= +google.golang.org/api v0.118.0/go.mod h1:76TtD3vkgmZ66zZzp72bUUklpmQmKlhh6sYtIjYK+5E= +google.golang.org/api v0.122.0/go.mod h1:gcitW0lvnyWjSp9nKxAbdHKIZ6vF4aajGueeslZOyms= +google.golang.org/api v0.124.0/go.mod h1:xu2HQurE5gi/3t1aFCvhPD781p0a3p11sdunTJ2BlP4= +google.golang.org/api v0.126.0/go.mod h1:mBwVAtz+87bEN6CbA1GtZPDOqY2R5ONPqJeIlvyo4Aw= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190530194941-fb225487d101/go.mod h1:z3L6/3dTEVtUr6QSP8miRzeRqwQOioJ9I66odjN4I7s= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= +google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= +google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210222152913-aa3ee6e6a81c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210329143202-679c6ae281ee/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= +google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= +google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210604141403-392c879c8b08/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210608205507-b6d2f5bf0d7d/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= +google.golang.org/genproto v0.0.0-20210713002101-d411969a0d9a/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k= +google.golang.org/genproto v0.0.0-20210716133855-ce7ef5c701ea/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k= +google.golang.org/genproto v0.0.0-20210728212813-7823e685a01f/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48= +google.golang.org/genproto v0.0.0-20210805201207-89edb61ffb67/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48= +google.golang.org/genproto v0.0.0-20210813162853-db860fec028c/go.mod h1:cFeNkxwySK631ADgubI+/XFU/xp8FD5KIVV4rj8UC5w= +google.golang.org/genproto v0.0.0-20210821163610-241b8fcbd6c8/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210831024726-fe130286e0e2/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210903162649-d08c68adba83/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210909211513-a8c4777a87af/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210924002016-3dee208752a0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211206160659-862468c7d6e0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211221195035-429b39de9b1c/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220126215142-9970aeb2e350/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220207164111-0872dc986b00/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220218161850-94dd64e39d7c/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220222213610-43724f9ea8cf/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220304144024-325a89244dc8/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220310185008-1973136f34c6/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220324131243-acbaeb5b85eb/go.mod h1:hAL49I2IFola2sVEjAn7MEwsja0xp51I0tlGAf9hz4E= +google.golang.org/genproto v0.0.0-20220329172620-7be39ac1afc7/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220407144326-9054f6ed7bac/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220413183235-5e96e2839df9/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220414192740-2d67ff6cf2b4/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220421151946-72621c1f0bd3/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220429170224-98d788798c3e/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220502173005-c8bf987b8c21/go.mod h1:RAyBrSAP7Fh3Nc84ghnVLDPuV51xc9agzmm4Ph6i0Q4= +google.golang.org/genproto v0.0.0-20220505152158-f39f71e6c8f3/go.mod h1:RAyBrSAP7Fh3Nc84ghnVLDPuV51xc9agzmm4Ph6i0Q4= +google.golang.org/genproto v0.0.0-20220518221133-4f43b3371335/go.mod h1:RAyBrSAP7Fh3Nc84ghnVLDPuV51xc9agzmm4Ph6i0Q4= +google.golang.org/genproto v0.0.0-20220523171625-347a074981d8/go.mod h1:RAyBrSAP7Fh3Nc84ghnVLDPuV51xc9agzmm4Ph6i0Q4= +google.golang.org/genproto v0.0.0-20220608133413-ed9918b62aac/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= +google.golang.org/genproto v0.0.0-20220616135557-88e70c0c3a90/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= +google.golang.org/genproto v0.0.0-20220617124728-180714bec0ad/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= +google.golang.org/genproto v0.0.0-20220624142145-8cd45d7dbd1f/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= +google.golang.org/genproto v0.0.0-20220628213854-d9e0b6570c03/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= +google.golang.org/genproto v0.0.0-20220722212130-b98a9ff5e252/go.mod h1:GkXuJDJ6aQ7lnJcRF+SJVgFdQhypqgl3LB1C9vabdRE= +google.golang.org/genproto v0.0.0-20220801145646-83ce21fca29f/go.mod h1:iHe1svFLAZg9VWz891+QbRMwUv9O/1Ww+/mngYeThbc= +google.golang.org/genproto v0.0.0-20220815135757-37a418bb8959/go.mod h1:dbqgFATTzChvnt+ujMdZwITVAJHFtfyN1qUhDqEiIlk= +google.golang.org/genproto v0.0.0-20220817144833-d7fd3f11b9b1/go.mod h1:dbqgFATTzChvnt+ujMdZwITVAJHFtfyN1qUhDqEiIlk= +google.golang.org/genproto v0.0.0-20220822174746-9e6da59bd2fc/go.mod h1:dbqgFATTzChvnt+ujMdZwITVAJHFtfyN1qUhDqEiIlk= +google.golang.org/genproto v0.0.0-20220829144015-23454907ede3/go.mod h1:dbqgFATTzChvnt+ujMdZwITVAJHFtfyN1qUhDqEiIlk= +google.golang.org/genproto v0.0.0-20220829175752-36a9c930ecbf/go.mod h1:dbqgFATTzChvnt+ujMdZwITVAJHFtfyN1qUhDqEiIlk= +google.golang.org/genproto v0.0.0-20220913154956-18f8339a66a5/go.mod h1:0Nb8Qy+Sk5eDzHnzlStwW3itdNaWoZA5XeSG+R3JHSo= +google.golang.org/genproto v0.0.0-20220914142337-ca0e39ece12f/go.mod h1:0Nb8Qy+Sk5eDzHnzlStwW3itdNaWoZA5XeSG+R3JHSo= +google.golang.org/genproto v0.0.0-20220915135415-7fd63a7952de/go.mod h1:0Nb8Qy+Sk5eDzHnzlStwW3itdNaWoZA5XeSG+R3JHSo= +google.golang.org/genproto v0.0.0-20220916172020-2692e8806bfa/go.mod h1:0Nb8Qy+Sk5eDzHnzlStwW3itdNaWoZA5XeSG+R3JHSo= +google.golang.org/genproto v0.0.0-20220919141832-68c03719ef51/go.mod h1:0Nb8Qy+Sk5eDzHnzlStwW3itdNaWoZA5XeSG+R3JHSo= +google.golang.org/genproto v0.0.0-20220920201722-2b89144ce006/go.mod h1:ht8XFiar2npT/g4vkk7O0WYS1sHOHbdujxbEp7CJWbw= +google.golang.org/genproto v0.0.0-20220926165614-551eb538f295/go.mod h1:woMGP53BroOrRY3xTxlbr8Y3eB/nzAvvFM83q7kG2OI= +google.golang.org/genproto v0.0.0-20220926220553-6981cbe3cfce/go.mod h1:woMGP53BroOrRY3xTxlbr8Y3eB/nzAvvFM83q7kG2OI= +google.golang.org/genproto v0.0.0-20221010155953-15ba04fc1c0e/go.mod h1:3526vdqwhZAwq4wsRUaVG555sVgsNmIjRtO7t/JH29U= +google.golang.org/genproto v0.0.0-20221014173430-6e2ab493f96b/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= +google.golang.org/genproto v0.0.0-20221014213838-99cd37c6964a/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= +google.golang.org/genproto v0.0.0-20221024153911-1573dae28c9c/go.mod h1:9qHF0xnpdSfF6knlcsnpzUu5y+rpwgbvsyGAZPBMg4s= +google.golang.org/genproto v0.0.0-20221024183307-1bc688fe9f3e/go.mod h1:9qHF0xnpdSfF6knlcsnpzUu5y+rpwgbvsyGAZPBMg4s= +google.golang.org/genproto v0.0.0-20221027153422-115e99e71e1c/go.mod h1:CGI5F/G+E5bKwmfYo09AXuVN4dD894kIKUFmVbP2/Fo= +google.golang.org/genproto v0.0.0-20221109142239-94d6d90a7d66/go.mod h1:rZS5c/ZVYMaOGBfO68GWtjOw/eLaZM1X6iVtgjZ+EWg= +google.golang.org/genproto v0.0.0-20221114212237-e4508ebdbee1/go.mod h1:rZS5c/ZVYMaOGBfO68GWtjOw/eLaZM1X6iVtgjZ+EWg= +google.golang.org/genproto v0.0.0-20221117204609-8f9c96812029/go.mod h1:rZS5c/ZVYMaOGBfO68GWtjOw/eLaZM1X6iVtgjZ+EWg= +google.golang.org/genproto v0.0.0-20221118155620-16455021b5e6/go.mod h1:rZS5c/ZVYMaOGBfO68GWtjOw/eLaZM1X6iVtgjZ+EWg= +google.golang.org/genproto v0.0.0-20221201164419-0e50fba7f41c/go.mod h1:rZS5c/ZVYMaOGBfO68GWtjOw/eLaZM1X6iVtgjZ+EWg= +google.golang.org/genproto v0.0.0-20221201204527-e3fa12d562f3/go.mod h1:rZS5c/ZVYMaOGBfO68GWtjOw/eLaZM1X6iVtgjZ+EWg= +google.golang.org/genproto v0.0.0-20221202195650-67e5cbc046fd/go.mod h1:cTsE614GARnxrLsqKREzmNYJACSWWpAWdNMwnD7c2BE= +google.golang.org/genproto v0.0.0-20221227171554-f9683d7f8bef/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= +google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= +google.golang.org/genproto v0.0.0-20230112194545-e10362b5ecf9/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= +google.golang.org/genproto v0.0.0-20230113154510-dbe35b8444a5/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= +google.golang.org/genproto v0.0.0-20230123190316-2c411cf9d197/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= +google.golang.org/genproto v0.0.0-20230124163310-31e0e69b6fc2/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= +google.golang.org/genproto v0.0.0-20230125152338-dcaf20b6aeaa/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= +google.golang.org/genproto v0.0.0-20230127162408-596548ed4efa/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= +google.golang.org/genproto v0.0.0-20230209215440-0dfe4f8abfcc/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= +google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44/go.mod h1:8B0gmkoRebU8ukX6HP+4wrVQUY1+6PkQ44BSyIlflHA= +google.golang.org/genproto v0.0.0-20230222225845-10f96fb3dbec/go.mod h1:3Dl5ZL0q0isWJt+FVcfpQyirqemEuLAK/iFvg1UP1Hw= +google.golang.org/genproto v0.0.0-20230223222841-637eb2293923/go.mod h1:3Dl5ZL0q0isWJt+FVcfpQyirqemEuLAK/iFvg1UP1Hw= +google.golang.org/genproto v0.0.0-20230303212802-e74f57abe488/go.mod h1:TvhZT5f700eVlTNwND1xoEZQeWTB2RY/65kplwl/bFA= +google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230323212658-478b75c54725/go.mod h1:UUQDJDOlWu4KYeJZffbWgBkS1YFobzKbLVfK69pe0Ak= +google.golang.org/genproto v0.0.0-20230330154414-c0448cd141ea/go.mod h1:UUQDJDOlWu4KYeJZffbWgBkS1YFobzKbLVfK69pe0Ak= +google.golang.org/genproto v0.0.0-20230331144136-dcfb400f0633/go.mod h1:UUQDJDOlWu4KYeJZffbWgBkS1YFobzKbLVfK69pe0Ak= +google.golang.org/genproto v0.0.0-20230403163135-c38d8f061ccd/go.mod h1:UUQDJDOlWu4KYeJZffbWgBkS1YFobzKbLVfK69pe0Ak= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= +google.golang.org/genproto v0.0.0-20230525234025-438c736192d0/go.mod h1:9ExIQyXL5hZrHzQceCwuSYwZZ5QZBazOcprJ5rgs3lY= +google.golang.org/genproto v0.0.0-20230530153820-e85fd2cbaebc/go.mod h1:xZnkP7mREFX5MORlOPEzLMr+90PPZQ2QWzrVTWfAq64= +google.golang.org/genproto/googleapis/api v0.0.0-20230525234020-1aefcd67740a/go.mod h1:ts19tUU+Z0ZShN1y3aPyq2+O3d5FUNNgT6FtOzmrNn8= +google.golang.org/genproto/googleapis/api v0.0.0-20230525234035-dd9d682886f9/go.mod h1:vHYtlOoi6TsQ3Uk2yxR7NI5z8uoV+3pZtR4jmHIkRig= +google.golang.org/genproto/googleapis/api v0.0.0-20230526203410-71b5a4ffd15e/go.mod h1:vHYtlOoi6TsQ3Uk2yxR7NI5z8uoV+3pZtR4jmHIkRig= +google.golang.org/genproto/googleapis/api v0.0.0-20230530153820-e85fd2cbaebc/go.mod h1:vHYtlOoi6TsQ3Uk2yxR7NI5z8uoV+3pZtR4jmHIkRig= +google.golang.org/genproto/googleapis/bytestream v0.0.0-20230530153820-e85fd2cbaebc/go.mod h1:ylj+BE99M198VPbBh6A8d9n3w8fChvyLK3wwBOjXBFA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20230525234015-3fc162c6f38a/go.mod h1:xURIpW9ES5+/GZhnV6beoEtxQrnkRGIfP5VQG2tCBLc= +google.golang.org/genproto/googleapis/rpc v0.0.0-20230525234030-28d5490b6b19/go.mod h1:66JfowdXAEgad5O9NnYcsNPLCPZJD++2L9X0PCMODrA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20230526203410-71b5a4ffd15e/go.mod h1:66JfowdXAEgad5O9NnYcsNPLCPZJD++2L9X0PCMODrA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20230530153820-e85fd2cbaebc/go.mod h1:66JfowdXAEgad5O9NnYcsNPLCPZJD++2L9X0PCMODrA= +google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.22.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= +google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.39.0/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= +google.golang.org/grpc v1.39.1/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= +google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= +google.golang.org/grpc v1.40.1/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= +google.golang.org/grpc v1.42.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= +google.golang.org/grpc v1.44.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= +google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= +google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc v1.46.2/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc v1.47.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc v1.48.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc v1.49.0/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= +google.golang.org/grpc v1.50.0/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= +google.golang.org/grpc v1.50.1/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= +google.golang.org/grpc v1.51.0/go.mod h1:wgNDFcnuBGmxLKI/qn4T+m5BtEBYXJPvibbUPsAIPww= +google.golang.org/grpc v1.52.0/go.mod h1:pu6fVzoFb+NBYNAvQL08ic+lvB2IojljRYuun5vorUY= +google.golang.org/grpc v1.53.0/go.mod h1:OnIrk0ipVdj4N5d9IUoFUx72/VlD7+jUsHwZgwSMQpw= +google.golang.org/grpc v1.54.0/go.mod h1:PUSEXI6iWghWaB6lXM4knEgpJNu2qUcKfDtNci3EC2g= +google.golang.org/grpc v1.55.0/go.mod h1:iYEXKGkEBhg1PjZQvoYEVPTDkHo1/bjTnfwTeGONTY8= +google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.29.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= +google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= +gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= +gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.1.3/go.mod h1:NgwopIslSNH47DimFoV78dnkksY2EFtX0ajyb3K/las= +lukechampine.com/uint128 v1.1.1/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= +lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= +modernc.org/cc/v3 v3.36.0/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI= +modernc.org/cc/v3 v3.36.2/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI= +modernc.org/cc/v3 v3.36.3/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI= +modernc.org/ccgo/v3 v3.0.0-20220428102840-41399a37e894/go.mod h1:eI31LL8EwEBKPpNpA4bU1/i+sKOwOrQy8D87zWUcRZc= +modernc.org/ccgo/v3 v3.0.0-20220430103911-bc99d88307be/go.mod h1:bwdAnOoaIt8Ax9YdWGjxWsdkPcZyRPHqrOvJxaKAKGw= +modernc.org/ccgo/v3 v3.16.4/go.mod h1:tGtX0gE9Jn7hdZFeU88slbTh1UtCYKusWOoCJuvkWsQ= +modernc.org/ccgo/v3 v3.16.6/go.mod h1:tGtX0gE9Jn7hdZFeU88slbTh1UtCYKusWOoCJuvkWsQ= +modernc.org/ccgo/v3 v3.16.8/go.mod h1:zNjwkizS+fIFDrDjIAgBSCLkWbJuHF+ar3QRn+Z9aws= +modernc.org/ccgo/v3 v3.16.9/go.mod h1:zNMzC9A9xeNUepy6KuZBbugn3c0Mc9TeiJO4lgvkJDo= +modernc.org/ccorpus v1.11.6/go.mod h1:2gEUTrWqdpH2pXsmTM1ZkjeSrUWDpjMu2T6m29L/ErQ= +modernc.org/httpfs v1.0.6/go.mod h1:7dosgurJGp0sPaRanU53W4xZYKh14wfzX420oZADeHM= +modernc.org/libc v0.0.0-20220428101251-2d5f3daf273b/go.mod h1:p7Mg4+koNjc8jkqwcoFBJx7tXkpj00G77X7A72jXPXA= +modernc.org/libc v1.16.0/go.mod h1:N4LD6DBE9cf+Dzf9buBlzVJndKr/iJHG97vGLHYnb5A= +modernc.org/libc v1.16.1/go.mod h1:JjJE0eu4yeK7tab2n4S1w8tlWd9MxXLRzheaRnAKymU= +modernc.org/libc v1.16.17/go.mod h1:hYIV5VZczAmGZAnG15Vdngn5HSF5cSkbvfz2B7GRuVU= +modernc.org/libc v1.16.19/go.mod h1:p7Mg4+koNjc8jkqwcoFBJx7tXkpj00G77X7A72jXPXA= +modernc.org/libc v1.17.0/go.mod h1:XsgLldpP4aWlPlsjqKRdHPqCxCjISdHfM/yeWC5GyW0= +modernc.org/libc v1.17.1/go.mod h1:FZ23b+8LjxZs7XtFMbSzL/EhPxNbfZbErxEHc7cbD9s= +modernc.org/mathutil v1.2.2/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= +modernc.org/mathutil v1.4.1/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= +modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= +modernc.org/memory v1.1.1/go.mod h1:/0wo5ibyrQiaoUoH7f9D8dnglAmILJ5/cxZlRECf+Nw= +modernc.org/memory v1.2.0/go.mod h1:/0wo5ibyrQiaoUoH7f9D8dnglAmILJ5/cxZlRECf+Nw= +modernc.org/memory v1.2.1/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU= +modernc.org/opt v0.1.1/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= +modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= +modernc.org/sqlite v1.18.1/go.mod h1:6ho+Gow7oX5V+OiOQ6Tr4xeqbx13UZ6t+Fw9IRUG4d4= +modernc.org/strutil v1.1.1/go.mod h1:DE+MQQ/hjKBZS2zNInV5hhcipt5rLPWkmpbGeW5mmdw= +modernc.org/strutil v1.1.3/go.mod h1:MEHNA7PdEnEwLvspRMtWTNnp2nnyvMfkimT1NKNAGbw= +modernc.org/tcl v1.13.1/go.mod h1:XOLfOwzhkljL4itZkK6T72ckMgvj0BDsnKNdZVUOecw= +modernc.org/token v1.0.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= +modernc.org/z v1.5.1/go.mod h1:eWFB510QWW5Th9YGZT81s+LwvaAs3Q2yr4sP0rmLkv8= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= +rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= +rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= +sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= +sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc= +sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= diff --git a/bmp-monitor-proxy/log/.cmd b/bmp-monitor-proxy/log/.cmd new file mode 100644 index 0000000..aa7fe97 --- /dev/null +++ b/bmp-monitor-proxy/log/.cmd @@ -0,0 +1 @@ +rm proxy.2024060316.001.log proxy.2024060317.002.log proxy.2024060318.003.log proxy.2024060319.004.log proxy.2024060320.005.log proxy.2024060321.006.log proxy.2024060322.007.log proxy.2024060323.008.log proxy.2024060400.009.log proxy.2024060401.010.log proxy.2024060402.011.log proxy.2024060403.012.log proxy.2024060404.013.log proxy.2024060405.014.log proxy.2024060406.015.log proxy.2024060407.016.log proxy.2024060408.017.log proxy.2024060409.018.log proxy.2024060410.019.log proxy.log diff --git a/bmp-monitor-proxy/log/proxy.log b/bmp-monitor-proxy/log/proxy.log new file mode 100755 index 0000000..bdd4158 --- /dev/null +++ b/bmp-monitor-proxy/log/proxy.log @@ -0,0 +1,61 @@ +2024/06/20 16:00:00.096 [D] [router.go:1305] | 10.226.192.114| 200 | 680.662µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:00:00.318 [D] [router.go:1305] | 10.226.192.114| 200 | 117.127249ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:01:00.072 [D] [router.go:1305] | 10.226.192.114| 200 | 971.03µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:01:00.375 [D] [router.go:1305] | 10.226.192.114| 200 | 144.442401ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:02:00.066 [D] [router.go:1305] | 10.226.192.114| 200 | 792.254µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:02:00.368 [D] [router.go:1305] | 10.226.192.114| 200 | 133.68883ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:03:00.073 [D] [router.go:1305] | 10.226.192.114| 200 | 794.769µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:03:00.358 [D] [router.go:1305] | 10.226.192.114| 200 | 136.499242ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:04:00.043 [D] [router.go:1305] | 10.226.192.114| 200 | 794.849µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:04:00.346 [D] [router.go:1305] | 10.226.192.114| 200 | 129.858838ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:05:00.066 [D] [router.go:1305] | 10.226.192.114| 200 | 752.925µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:05:00.308 [D] [router.go:1305] | 10.226.192.114| 200 | 105.496145ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:06:00.065 [D] [router.go:1305] | 10.226.192.114| 200 | 790.197µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:06:00.361 [D] [router.go:1305] | 10.226.192.114| 200 | 147.793577ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:07:00.087 [D] [router.go:1305] | 10.226.192.114| 200 | 644.465µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:07:00.366 [D] [router.go:1305] | 10.226.192.114| 200 | 145.198916ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:08:00.086 [D] [router.go:1305] | 10.226.192.114| 200 | 900.528µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:08:00.391 [D] [router.go:1305] | 10.226.192.114| 200 | 135.278993ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:09:00.102 [D] [router.go:1305] | 10.226.192.114| 200 | 633.352µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:09:00.360 [D] [router.go:1305] | 10.226.192.114| 200 | 130.482662ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:10:00.063 [D] [router.go:1305] | 10.226.192.114| 200 | 942.357µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:10:00.336 [D] [router.go:1305] | 10.226.192.114| 200 | 122.29559ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:11:00.066 [D] [router.go:1305] | 10.226.192.114| 200 | 883.133µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:11:00.397 [D] [router.go:1305] | 10.226.192.114| 200 | 145.762995ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:12:00.062 [D] [router.go:1305] | 10.226.192.114| 200 | 839.263µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:12:00.364 [D] [router.go:1305] | 10.226.192.114| 200 | 133.896412ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:13:00.092 [D] [router.go:1305] | 10.226.192.114| 200 | 985.624µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:13:00.363 [D] [router.go:1305] | 10.226.192.114| 200 | 135.704382ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:14:00.078 [D] [router.go:1305] | 10.226.192.114| 200 | 931.062µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:14:00.348 [D] [router.go:1305] | 10.226.192.114| 200 | 146.46706ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:15:00.087 [D] [router.go:1305] | 10.226.192.114| 200 | 1.068677ms| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:15:00.328 [D] [router.go:1305] | 10.226.192.114| 200 | 119.641633ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:16:00.093 [D] [router.go:1305] | 10.226.192.114| 200 | 2.274053ms| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:16:00.341 [D] [router.go:1305] | 10.226.192.114| 200 | 123.333538ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:17:00.082 [D] [router.go:1305] | 10.226.192.114| 200 | 687.933µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:17:00.360 [D] [router.go:1305] | 10.226.192.114| 200 | 142.072902ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:18:00.071 [D] [router.go:1305] | 10.226.192.114| 200 | 569.088µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:18:00.283 [D] [router.go:1305] | 10.226.192.114| 200 | 103.374303ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:19:00.072 [D] [router.go:1305] | 10.226.192.114| 200 | 691.859µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:19:00.349 [D] [router.go:1305] | 10.226.192.114| 200 | 128.700949ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:20:00.082 [D] [router.go:1305] | 10.226.192.114| 200 | 953.949µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:20:00.318 [D] [router.go:1305] | 10.226.192.114| 200 | 111.671284ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:21:00.031 [D] [router.go:1305] | 10.226.192.114| 200 | 481.328µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:21:00.257 [D] [router.go:1305] | 10.226.192.114| 200 | 106.581358ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:22:00.062 [D] [router.go:1305] | 10.226.192.114| 200 | 1.035984ms| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:22:00.327 [D] [router.go:1305] | 10.226.192.114| 200 | 113.713985ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:23:00.064 [D] [router.go:1305] | 10.226.192.114| 200 | 735.17µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:23:00.328 [D] [router.go:1305] | 10.226.192.114| 200 | 133.716735ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:24:00.051 [D] [router.go:1305] | 10.226.192.114| 200 | 737.445µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:24:00.298 [D] [router.go:1305] | 10.226.192.114| 200 | 129.311431ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:25:00.096 [D] [router.go:1305] | 10.226.192.114| 200 | 746.492µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:25:00.336 [D] [router.go:1305] | 10.226.192.114| 200 | 117.199365ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:26:00.076 [D] [router.go:1305] | 10.226.192.114| 200 | 709.36µs| match| POST  /api/v1/agent/heartbeat r:/api/v1/agent/heartbeat +2024/06/20 16:26:00.334 [D] [router.go:1305] | 10.226.192.114| 200 | 117.645122ms| match| POST  /api/v1/agent/put r:/api/v1/agent/put +2024/06/20 16:26:08.196 [I] [main.go:115] ========BMP-MONITOR-PROXY Exit======== +2024/07/02 16:05:33.215 [I] [main.go:60] ========BMP-MONITOR-PROXY Start======== +2024/07/02 16:05:36.222 [W] [main.go:73] Redis Connect Error, Ping result : dial tcp 10.226.192.72:16379: connect: connection timed out +2024/07/02 16:17:07.348 [I] [main.go:60] ========BMP-MONITOR-PROXY Start======== +2024/07/02 16:17:10.354 [W] [main.go:73] Redis Connect Error, Ping result : dial tcp 10.226.192.72:16379: connect: connection timed out +2024/07/02 16:17:51.160 [I] [main.go:60] ========BMP-MONITOR-PROXY Start======== +2024/07/02 16:17:54.170 [W] [main.go:73] Redis Connect Error, Ping result : dial tcp 10.226.192.72:16379: connect: connection timed out diff --git a/bmp-monitor-proxy/log/run.log b/bmp-monitor-proxy/log/run.log new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/bmp-monitor-proxy/log/run.log @@ -0,0 +1 @@ + diff --git a/bmp-monitor-proxy/logic/pushGateway.go b/bmp-monitor-proxy/logic/pushGateway.go new file mode 100644 index 0000000..28842d1 --- /dev/null +++ b/bmp-monitor-proxy/logic/pushGateway.go @@ -0,0 +1,132 @@ +package logic + +import ( + "fmt" + + "coding.jd.com/bmp/agent-proxy-jdstack/api/models" + "coding.jd.com/bmp/agent-proxy-jdstack/util" + log "git.jd.com/cps-golang/log" + + "github.com/beego/beego/v2/server/web" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/push" +) + +var gatewayUrl string + +func Init() error { + gateWayHost, err := web.AppConfig.String("prometheus_gateway_host") + if err != nil { + return err + } + gateWayPort, err := web.AppConfig.String("prometheus_gateway_port") + if err != nil { + return err + } + gatewayUrl = fmt.Sprintf("http://%s:%s", gateWayHost, gateWayPort) + return nil +} + +func PushGateway(logger *log.Logger, instance *models.Instance, reqObj models.ProxyPut) error { + + datas := reqObj.DataPoints + counterMetrics := []string{ + "bmp.disk.bytes.read", + "bmp.disk.bytes.write", + "bmp.disk.counts.read", + "bmp.disk.counts.write", + "bmp.network.bytes.ingress", + "bmp.network.bytes.egress", + "bmp.network.packets.ingress", + "bmp.network.packets.egress", + } + + // currentCacheData := map[string]interface{}{} + + // prevCache, err := util.HGetAllFromRedis("PushGatewayCache_" + instance.Result.Instance.InstanceID) + // if err != nil { + // logger.Warnf("PushGateway.HGetAllFromRedis error, instanceId:%s, error:%s", instance.Result.Instance.InstanceID, err.Error()) + // } else { + // tmm, _ := json.Marshal(prevCache) + // logger.Infof("push.getCacheData instanceId:%s, data:%s", instance.Result.Instance.InstanceID, string(tmm)) + // } + + for _, data := range datas { + isCounter := false + if util.InArray4String(data.Metric, counterMetrics) { + isCounter = true + } + + var vvv float64 + // if isCounter { //counter指标 + // var tagJoinKey string = data.Metric + // for k, v := range data.Tags { + // tagJoinKey += fmt.Sprintf("_%s_%s", k, v) + // } + // currentCacheData[tagJoinKey] = data.Value + + // s, err := strconv.ParseFloat(prevCache[tagJoinKey], 64) + // logger.Infof("debug here", s) + // if err != nil { + // logger.Warnf("PushGateway.ParseFloat error,key:%s v:%s, error:%s", tagJoinKey, prevCache[tagJoinKey], err.Error()) + // // continue + // } else { + // // vvv = data.Value - s //做差值 + // vvv = data.Value //不做差值 + // } + + // } else { //gause指标 + // vvv = data.Value + // } + vvv = data.Value + var pusher *push.Pusher + logger.Infof("metric is:%s, tag is:%v, isCounter:%v, value:%f, onput_value:%f", data.Metric, data.Tags, isCounter, vvv, data.Value) + if isCounter { + + c := prometheus.NewCounter(prometheus.CounterOpts{ + Name: "bmp_monitor_counter", + Help: "bmp-monitor-counter-data, store it", + }) + c.Add(vvv) + pusher = push.New(gatewayUrl, "bmp_monitor_counter"). // push.New("pushgateway地址", "job名称") + Collector(c) + } else { + g := prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "bmp_monitor_gauge", + Help: "bmp-monitor-gauge-data, store it", + }) + g.Set(vvv) // set可以设置任意值(float64) + pusher = push.New(gatewayUrl, "bmp_monitor_gauge"). // push.New("pushgateway地址", "job名称") + Collector(g) + } + + pusher.Grouping("instance_id", instance.Result.Instance.InstanceID).Grouping("metric_name", data.Metric) + for k, v := range data.Tags { + pusher.Grouping(k, v) // 给指标添加标签,可以添加多个 + } + // logger.Infof("puuuuuuuu start time:%d", time.Now().Unix()) + err := pusher.Push() + // logger.Infof("puuuuuuuu end time:%d", time.Now().Unix()) + if err != nil { + logger.Warnf("Could not push completion time to Pushgateway error:%s", err.Error()) + } else { + logger.Infof("instance_id:%s metric:%s push to gateway success, url:%s", instance.Result.Instance.InstanceID, data.Metric, gatewayUrl) + } + + } + + // if len(currentCacheData) > 0 { + // if err := util.HMSetObjectToRedis("PushGatewayCache_"+instance.Result.Instance.InstanceID, currentCacheData); err != nil { + // logger.Warnf("PushGateway.HMSetObjectToRedis error, instanceId:%s, error:%s", instance.Result.Instance.InstanceID, err.Error()) + // } else { + // tmm, _ := json.Marshal(currentCacheData) + // logger.Infof("push.setCacheData succ, instanceId:%s, data:%s", instance.Result.Instance.InstanceID, string(tmm)) + // } + // if err := util.SetObjectWithExpire("PushGatewayCache_"+instance.Result.Instance.InstanceID, 100); err != nil { //过期时间100s正好卡在1分钟后2分钟前 + // logger.Warnf("PushGateway.SetObjectWithExpire error, instanceId:%s, error:%s", instance.Result.Instance.InstanceID, err.Error()) + // } + // } + + return nil + +} diff --git a/bmp-monitor-proxy/main.go b/bmp-monitor-proxy/main.go new file mode 100644 index 0000000..68c135a --- /dev/null +++ b/bmp-monitor-proxy/main.go @@ -0,0 +1,122 @@ +package main + +import ( + "encoding/json" + "flag" + "fmt" + "os" + "os/signal" + "syscall" + + "coding.jd.com/bmp/agent-proxy-jdstack/logic" + _ "coding.jd.com/bmp/agent-proxy-jdstack/routers" + "coding.jd.com/bmp/agent-proxy-jdstack/util" + + "github.com/beego/beego/v2/core/logs" + "github.com/beego/beego/v2/server/web" + _ "github.com/go-sql-driver/mysql" +) + +const ( + defaultConfigFile = "conf/proxy.ini" +) + +type LoggerConfig struct { + FileName string `json:"filename"` //将日志保存到的文件名及路径 + Level int `json:"level"` // 日志保存的时候的级别,默认是 Trace 级别 + Maxlines int `json:"maxlines"` // 每个文件保存的最大行数,若文件超过maxlines,则将日志保存到下个文件中,为0表示不设置。默认值 1000000 + Maxsize int `json:"maxsize"` // 每个文件保存的最大尺寸,若文件超过maxsize,则将日志保存到下个文件中,为0表示不设置。默认值是 1 << 28, //256 MB + // Daily bool `json:"daily"` // 设置日志是否每天分割一次,默认是 true + Hourly bool `json:"hourly"` // 设置日志是否每小时分割一次,默认是 true + // Maxdays int `json:"maxdays"` // 设置保存最近几天的日志文件,超过天数的日志文件被删除,为0表示不设置,默认保存 7 天 + MaxHours int `json:"maxhours"` + Rotate bool `json:"rotate"` // 是否开启 logrotate,默认是 true + Perm string `json:"perm"` // 日志文件权限 + RotatePerm string `json:"rotateperm"` + EnableFuncCallDepth bool `json:"-"` // 输出文件名和行号 + LogFuncCallDepth int `json:"-"` // 函数调用层级 +} + +func main() { + + var configFile = flag.String("c", defaultConfigFile, "specify config file") + var helpFlag = flag.Bool("h", false, "print help") + + flag.Parse() + + if *helpFlag { + flag.PrintDefaults() + os.Exit(0) + } + + web.LoadAppConfig("ini", *configFile) + + // logConfig := "{\"filename\":\"" + beego.AppConfig.DefaultString("app.log-file", "log/cps-ops-web.log") + "\",\"level\":" + beego.AppConfig.DefaultString("app.log-level", "7") + "}" + // logs.SetLogger(logs.AdapterFile, logConfig) + // logs.SetLogger(logs.AdapterConsole, `{"level":8,"color":true}`) + // logs.EnableFuncCallDepth(true) + LogsInit() + + logs.Info("========BMP-MONITOR-PROXY Start========") + initApp() + + // initial redis + rNamespace, _ := web.AppConfig.String("bmp_redis_namespace") + rIdc, _ := web.AppConfig.String("app.idc") + rhost, _ := web.AppConfig.String("bmp_redis_host") + rport, _ := web.AppConfig.String("bmp_redis_port") + rAddr := fmt.Sprintf("%s:%s", rhost, rport) + rPasswd, _ := web.AppConfig.String("bmp_redis_password") + rDb, _ := web.AppConfig.Int("bmp_redis_db") + + if err := util.InitRedis(rNamespace, rIdc, rAddr, rPasswd, rDb); err != nil { + logs.Warn("Redis Connect Error, Ping result : %s", err.Error()) + os.Exit(0) + } + defer util.RedisUtil.Close() + + if err := logic.Init(); err != nil { + logs.Warn("prometheus.gateway init Error%s", err.Error()) + } + + web.Run() + +} + +// LogsInit 日志init +func LogsInit() { + logCfg := LoggerConfig{ + FileName: "log/proxy.log", + Level: logs.LevelDebug, + Hourly: true, + MaxHours: 7 * 24, + EnableFuncCallDepth: true, + LogFuncCallDepth: 3, + RotatePerm: "777", + Perm: "777", + } + + // 设置beego log库的配置 + b, _ := json.Marshal(logCfg) + _ = logs.SetLogger(logs.AdapterFile, string(b)) + // logs.Async(1e3) //异步输出允许设置缓冲 chan 的大小 +} + +func initApp() { + + // Signal + signalChan := make(chan os.Signal, 1) + signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL) + go func() { + <-signalChan + exit(0) + }() + +} + +func exit(result int) { + + logs.Info("========BMP-MONITOR-PROXY Exit========") + + os.Exit(result) +} diff --git a/bmp-monitor-proxy/routers/router.go b/bmp-monitor-proxy/routers/router.go new file mode 100644 index 0000000..6eb2f86 --- /dev/null +++ b/bmp-monitor-proxy/routers/router.go @@ -0,0 +1,35 @@ +package router + +import ( + "coding.jd.com/bmp/agent-proxy-jdstack/controllers" + + beego "github.com/beego/beego/v2/server/web" +) + +func init() { + beego.ErrorController(&controllers.ErrorController{}) + + // api namespace router + ns := + beego.NewNamespace("/api/v1/agent", + beego.NSRouter("/put", &controllers.ProxyController{}, "post:Put"), + beego.NSRouter("/heartbeat", &controllers.ProxyController{}, "post:Heartbeat"), + ) + + beego.AddNamespace(ns) + + apiNS := + beego.NewNamespace("/api/v1/", + beego.NSRouter("/describeAgentStatus", &controllers.StatusController{}, "post:DescribeAgentStatus"), + ) + beego.AddNamespace(apiNS) + + // api namespace router + tagsNs := + beego.NewNamespace("/api/v1/tags", + beego.NSRouter("/", &controllers.DeviceTagController{}, "post:GetDeviceTags"), + ) + + beego.AddNamespace(tagsNs) + +} diff --git a/bmp-monitor-proxy/tools/config-crypt.go b/bmp-monitor-proxy/tools/config-crypt.go new file mode 100644 index 0000000..891901f --- /dev/null +++ b/bmp-monitor-proxy/tools/config-crypt.go @@ -0,0 +1,105 @@ +package main + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "encoding/base64" + "flag" + "fmt" + "io/ioutil" + "os" + "strings" +) + +var ( + helpFlag bool + key string + configFile string + outFile string +) + +func init() { + flag.BoolVar(&helpFlag, "h", false, "show help") + flag.StringVar(&key, "k", "", "AES key, must 16/24/32 bytes.") + flag.StringVar(&configFile, "f", "config.in", "config file to encrypt") + flag.StringVar(&outFile, "o", "config.out", "output file") + +} + +func main() { + flag.Parse() + + if helpFlag { + flag.PrintDefaults() + } + + if strings.TrimSpace(key) == "" || strings.TrimSpace(configFile) == "" || strings.TrimSpace(outFile) == "" { + fmt.Fprintln(os.Stderr, "Specify Parameter") + flag.PrintDefaults() + os.Exit(1) + } + + if fileByte, err := ioutil.ReadFile(configFile); err != nil { + fmt.Fprintf(os.Stderr, "Read file Error:%s\n", err.Error()) + os.Exit(2) + } else { + if encryptStr, e := AesEncrypt(fileByte, key); e != nil { + fmt.Fprintf(os.Stderr, "Read file Error:%s\n", e.Error()) + os.Exit(3) + } else { + if errWrite := ioutil.WriteFile(outFile, []byte(encryptStr), os.ModePerm); errWrite != nil { + fmt.Fprintf(os.Stderr, "Read file Error:%s\n", errWrite.Error()) + os.Exit(3) + } + } + } + + os.Exit(0) + +} + +func AesEncrypt(orig []byte, key string) (string, error) { + origData := orig + k := []byte(key) + if block, err := aes.NewCipher(k); err != nil { + return "", err + } else { + blockSize := block.BlockSize() + origData = pkcs7Padding(origData, blockSize) + blockMode := cipher.NewCBCEncrypter(block, k[:blockSize]) + cryted := make([]byte, len(origData)) + blockMode.CryptBlocks(cryted, origData) + return base64.StdEncoding.EncodeToString(cryted), nil + } +} + +func AesDecrypt(cryted string, key string) (string, error) { + if crytedByte, err := base64.StdEncoding.DecodeString(cryted); err != nil { + return "", err + } else { + k := []byte(key) + if block, e := aes.NewCipher(k); e != nil { + return "", e + } else { + blockSize := block.BlockSize() + blockMode := cipher.NewCBCDecrypter(block, k[:blockSize]) + orig := make([]byte, len(crytedByte)) + blockMode.CryptBlocks(orig, crytedByte) + orig = pkcs7UnPadding(orig) + return string(orig), nil + } + } +} + +func pkcs7Padding(ciphertext []byte, blocksize int) []byte { + padding := blocksize - len(ciphertext)%blocksize + padtext := bytes.Repeat([]byte{byte(padding)}, padding) + return append(ciphertext, padtext...) +} + +func pkcs7UnPadding(origData []byte) []byte { + length := len(origData) + unpadding := int(origData[length-1]) + return origData[:(length - unpadding)] +} diff --git a/bmp-monitor-proxy/types/request/BaseRequest.go b/bmp-monitor-proxy/types/request/BaseRequest.go new file mode 100644 index 0000000..52c6f92 --- /dev/null +++ b/bmp-monitor-proxy/types/request/BaseRequest.go @@ -0,0 +1,58 @@ +package request + +import ( + "fmt" + "reflect" + "strings" + + "coding.jd.com/bmp/agent-proxy-jdstack/constant" + log "git.jd.com/cps-golang/log" + validator "github.com/go-playground/validator/v10" +) + +type Pageable struct { + // 页码 + PageNumber int64 `json:"pageNumber"` + // 每页数量 + PageSize int64 `json:"pageSize"` +} + +var va = validator.New() + +func InitValidator() { + va.RegisterTagNameFunc(func(fld reflect.StructField) string { + name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] + + // if name == "-" { + // return "" + // } + + return name + }) + + if err := va.RegisterValidation("required_in_ptr", ValidateRequiredInPtr); err != nil { + fmt.Println("required_in_ptr register error!!!") + } else { + fmt.Println("required_in_ptr register success!!!") + } +} + +func ValidateRequiredInPtr(fl validator.FieldLevel) bool { + + return true +} + +func validate(req interface{}, logger *log.Logger) { + if err := va.Struct(req); err != nil { + fmt.Println(err, err.Error()) + logger.Warn("Validate error:", err.Error()) + var e string + v, ok := err.(validator.ValidationErrors) + if !ok { + e = err.Error() + } else { + e = v[0].Field() + } + panic(constant.BuildInvalidArgumentWithArgs(e+" 非法", e+" invalid")) + } +} diff --git a/bmp-monitor-proxy/types/request/DeviceTag.go b/bmp-monitor-proxy/types/request/DeviceTag.go new file mode 100644 index 0000000..2a1c221 --- /dev/null +++ b/bmp-monitor-proxy/types/request/DeviceTag.go @@ -0,0 +1,16 @@ +package request + +import ( + log "git.jd.com/cps-golang/log" +) + +type GetDeviceTagsRequest struct { + InstanceID string `json:"instanceId" validate:"required"` + Metric string `json:"metric" validate:"required"` +} + +func (req *GetDeviceTagsRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} diff --git a/bmp-monitor-proxy/types/request/MonitorDataRequest.go b/bmp-monitor-proxy/types/request/MonitorDataRequest.go new file mode 100644 index 0000000..e44020b --- /dev/null +++ b/bmp-monitor-proxy/types/request/MonitorDataRequest.go @@ -0,0 +1,22 @@ +package request + +import log "git.jd.com/cps-golang/log" + +/* +{"params":{"serviceCode":"cps-vpc","resourceId":"cps-2qtflhpvmuuw5tdodatv6ofxqcek","filters":[{"name":"metric","values":["cps.process.total"]}],"startTime":"2024-06-09T00:00:00","endTime":"2024-06-12T23:59:59","timeInterval":"1h", "downSampleType":"avg"}} +*/ +type GetMonitorDataRequest struct { + MetricName string `json:"metricName" validate:"required"` + InstanceID string `json:"instanceId" validate:"required"` + Device string `json:"device"` + StartTime int64 `json:"startTime"` + EndTime int64 `json:"endTime"` + TimeInterval int `json:"timeInterval"` //s为单位 + DownSampleType string `json:"downSampleType"` //好像不支持 +} + +func (req *GetMonitorDataRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} diff --git a/bmp-monitor-proxy/types/response/BaseResponse.go b/bmp-monitor-proxy/types/response/BaseResponse.go new file mode 100644 index 0000000..4570707 --- /dev/null +++ b/bmp-monitor-proxy/types/response/BaseResponse.go @@ -0,0 +1,6 @@ +package response + +type CommonResponse struct { + // 操作是否成功 [true/false] + Success bool `json:"success"` +} diff --git a/bmp-monitor-proxy/types/response/MonitorDataResponse.go b/bmp-monitor-proxy/types/response/MonitorDataResponse.go new file mode 100644 index 0000000..dcb836e --- /dev/null +++ b/bmp-monitor-proxy/types/response/MonitorDataResponse.go @@ -0,0 +1,13 @@ +package response + +type GetMonitorDataResponse struct { + MetricName string `json:"metricName" ` + InstanceID string `json:"instanceId" ` + Device string `json:"device"` + Datas []MonitorDataItem `json:"datas"` +} + +type MonitorDataItem struct { + Timestamp int64 `json:"timestamp"` + Value float64 `json:"value"` +} diff --git a/bmp-monitor-proxy/util/crypto.go b/bmp-monitor-proxy/util/crypto.go new file mode 100644 index 0000000..c7c5a09 --- /dev/null +++ b/bmp-monitor-proxy/util/crypto.go @@ -0,0 +1,68 @@ +package util + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "encoding/base64" +) + +// AesEncrypt AES encrypt method. key must 128/192/256 bits. +// +// example: +// orig := "hello world" +// key := "12345678123456781234567812345678" +// fmt.Println("原文:", orig) +// encryptCode,_ := AesEncrypt(orig, key) +// fmt.Println("密文:" , encryptCode) +func AesEncrypt(orig string, key string) (string, error) { + origData := []byte(orig) + k := []byte(key) + if block, err := aes.NewCipher(k); err != nil { + return "", err + } else { + blockSize := block.BlockSize() + origData = pkcs7Padding(origData, blockSize) + blockMode := cipher.NewCBCEncrypter(block, k[:blockSize]) + cryted := make([]byte, len(origData)) + blockMode.CryptBlocks(cryted, origData) + return base64.StdEncoding.EncodeToString(cryted), nil + } +} + +// AedDecrypt AES decrypt.key must 128/192/256 bits. +// +// example: +// key := "12345678123456781234567812345678" +// data := bpIjQ4yVwCt0RMI0JDOfTA== +// decryptCode,_ := AesDecrypt(data, key) +// fmt.Println("解密结果:", decryptCode) +func AesDecrypt(cryted string, key string) (string, error) { + if crytedByte, err := base64.StdEncoding.DecodeString(cryted); err != nil { + return "", err + } else { + k := []byte(key) + if block, e := aes.NewCipher(k); e != nil { + return "", e + } else { + blockSize := block.BlockSize() + blockMode := cipher.NewCBCDecrypter(block, k[:blockSize]) + orig := make([]byte, len(crytedByte)) + blockMode.CryptBlocks(orig, crytedByte) + orig = pkcs7UnPadding(orig) + return string(orig), nil + } + } +} + +func pkcs7Padding(ciphertext []byte, blocksize int) []byte { + padding := blocksize - len(ciphertext)%blocksize + padtext := bytes.Repeat([]byte{byte(padding)}, padding) + return append(ciphertext, padtext...) +} + +func pkcs7UnPadding(origData []byte) []byte { + length := len(origData) + unpadding := int(origData[length-1]) + return origData[:(length - unpadding)] +} diff --git a/bmp-monitor-proxy/util/daemon.go b/bmp-monitor-proxy/util/daemon.go new file mode 100644 index 0000000..c7d8682 --- /dev/null +++ b/bmp-monitor-proxy/util/daemon.go @@ -0,0 +1 @@ +package util diff --git a/bmp-monitor-proxy/util/daemon_darwin.go b/bmp-monitor-proxy/util/daemon_darwin.go new file mode 100644 index 0000000..b198db3 --- /dev/null +++ b/bmp-monitor-proxy/util/daemon_darwin.go @@ -0,0 +1,10 @@ +// +build darwin + +package util + +import "github.com/VividCortex/godaemon" + +func Daemon() error { + _, _, err := godaemon.MakeDaemon(&godaemon.DaemonAttr{}) + return err +} diff --git a/bmp-monitor-proxy/util/daemon_linux.go b/bmp-monitor-proxy/util/daemon_linux.go new file mode 100644 index 0000000..d3df6fe --- /dev/null +++ b/bmp-monitor-proxy/util/daemon_linux.go @@ -0,0 +1,13 @@ +// +build linux + +package util + +import "github.com/VividCortex/godaemon" + +// import "fmt" + +func Daemon() error { + _, _, err := godaemon.MakeDaemon(&godaemon.DaemonAttr{}) + // panic("MakeDaemon error:" + err.Error()) + return err +} diff --git a/bmp-monitor-proxy/util/daemon_windows.go b/bmp-monitor-proxy/util/daemon_windows.go new file mode 100644 index 0000000..a657eab --- /dev/null +++ b/bmp-monitor-proxy/util/daemon_windows.go @@ -0,0 +1,11 @@ +// +build windows + +package util + +import "errors" + +var ErrNotImplemented = errors.New("Not implemented") + +func Daemon() error { + return ErrNotImplemented +} diff --git a/bmp-monitor-proxy/util/float.go b/bmp-monitor-proxy/util/float.go new file mode 100644 index 0000000..4b2a55b --- /dev/null +++ b/bmp-monitor-proxy/util/float.go @@ -0,0 +1,10 @@ +package util + +import ( + "math" +) + +func FloatRound(f float64, n int) float64 { + n10 := math.Pow10(n) + return math.Trunc((f+0.5/n10)*n10) / n10 +} diff --git a/bmp-monitor-proxy/util/host.go b/bmp-monitor-proxy/util/host.go new file mode 100644 index 0000000..ab30305 --- /dev/null +++ b/bmp-monitor-proxy/util/host.go @@ -0,0 +1,6 @@ +package util + +type HostInfo struct { + Manufacturer string + SerialNumber string +} diff --git a/bmp-monitor-proxy/util/host_darwin.go b/bmp-monitor-proxy/util/host_darwin.go new file mode 100644 index 0000000..7a19ae4 --- /dev/null +++ b/bmp-monitor-proxy/util/host_darwin.go @@ -0,0 +1,39 @@ +// +build darwin + +package util + +import ( + "os/exec" + "strings" +) + +func SN() (HostInfo, error) { + ret := HostInfo{} + + ioreg, err := exec.LookPath("/usr/sbin/ioreg") + if err != nil { + return ret, err + } + cmd := exec.Command(ioreg, "-l") + + out, err := cmd.Output() + if err != nil { + return ret, err + } + for _, line := range strings.Split(string(out), "\n") { + if len(ret.SerialNumber) == 0 && strings.Contains(line, "\"IOPlatformSerialNumber\"") { + s := strings.Split(line, "=") + ret.SerialNumber = strings.ReplaceAll(s[len(s)-1], "\"", "") + println("SerialNumber:" + ret.SerialNumber) + continue + } + + if len(ret.Manufacturer) == 0 && strings.Contains(line, "\"Manufacturer\"") { + s := strings.Split(line, "=") + ret.Manufacturer = strings.ReplaceAll(s[len(s)-1], "\"", "") + println("Manufacturer:" + ret.Manufacturer) + continue + } + } + return ret, nil +} diff --git a/bmp-monitor-proxy/util/host_linux.go b/bmp-monitor-proxy/util/host_linux.go new file mode 100644 index 0000000..ffabc1f --- /dev/null +++ b/bmp-monitor-proxy/util/host_linux.go @@ -0,0 +1,38 @@ +// +build linux + +package util + +import ( + "os/exec" + "strings" +) + +func SN() (HostInfo, error) { + ret := HostInfo{} + + dmidcode, err := exec.LookPath("dmidecode") + if err != nil { + return ret, err + } + cmd := exec.Command(dmidcode, "-t", "1") + + out, err := cmd.Output() + if err != nil { + return ret, err + } + + for _, line := range strings.Split(string(out), "\n") { + tmp := strings.SplitN(line, ":", 2) + if strings.EqualFold(strings.TrimSpace(tmp[0]), "Serial Number") { + ret.SerialNumber = strings.TrimSpace(tmp[1]) + continue + } + + if strings.EqualFold(strings.TrimSpace(tmp[0]), "Manufacturer:") { + ret.Manufacturer = strings.TrimSpace(tmp[1]) + continue + } + } + + return ret, nil +} diff --git a/bmp-monitor-proxy/util/host_windows.go b/bmp-monitor-proxy/util/host_windows.go new file mode 100644 index 0000000..8b475b9 --- /dev/null +++ b/bmp-monitor-proxy/util/host_windows.go @@ -0,0 +1,69 @@ +// +build windows + +package util + +import ( + "context" + "errors" + "time" + + "github.com/StackExchange/wmi" +) + +var ( + Timeout = 30 * time.Second + ErrTimeout = errors.New("command timed out") +) + +type Win32_BIOS struct { + Manufacturer string + SerialNumber string +} + +func SN() (HostInfo, error) { + var dst []Win32_BIOS + + ret := HostInfo{} + err := WMIQuery("SELECT * FROM Win32_BIOS", &dst) + if err != nil { + return ret, err + } + + for _, d := range dst { + if len(d.SerialNumber) == 0 { + continue + } + + ret.Manufacturer = d.Manufacturer + ret.SerialNumber = d.SerialNumber + } + if ret.SerialNumber == "" { + ret.SerialNumber = "empty_sn_mocked" //有些虚拟机没有sn时mock,测试方便。TODO 上线前放开 + } + return ret, nil +} + +func WMIQuery(query string, dst interface{}, connectServerArgs ...interface{}) error { + return WMIQueryWithContext(context.Background(), query, dst, connectServerArgs...) +} + +// WMIQueryWithContext - wraps wmi.Query with a timed-out context to avoid hanging +func WMIQueryWithContext(ctx context.Context, query string, dst interface{}, connectServerArgs ...interface{}) error { + if _, ok := ctx.Deadline(); !ok { + ctxTimeout, cancel := context.WithTimeout(ctx, Timeout) + defer cancel() + ctx = ctxTimeout + } + + errChan := make(chan error, 1) + go func() { + errChan <- wmi.Query(query, dst, connectServerArgs...) + }() + + select { + case <-ctx.Done(): + return ctx.Err() + case err := <-errChan: + return err + } +} diff --git a/bmp-monitor-proxy/util/page.go b/bmp-monitor-proxy/util/page.go new file mode 100644 index 0000000..dfa80e8 --- /dev/null +++ b/bmp-monitor-proxy/util/page.go @@ -0,0 +1,26 @@ +package util + +type Pageable struct { + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} + +func (p Pageable) Pageable2offset() (offset int64, limit int64) { + limit = p.PageSize + if p.PageNumber == 0 { + offset = 0 + } else { + offset = (p.PageNumber - 1) * p.PageSize + } + return offset, limit +} + +func Offset2Pageable(total, limit, offset int64) Pageable { + pageNumber := offset/limit + 1 + return Pageable{ + PageNumber: pageNumber, + PageSize: limit, + TotalCount: total, + } +} diff --git a/bmp-monitor-proxy/util/pid.go b/bmp-monitor-proxy/util/pid.go new file mode 100644 index 0000000..cb45a52 --- /dev/null +++ b/bmp-monitor-proxy/util/pid.go @@ -0,0 +1,45 @@ +package util + +import ( + "os" + "strconv" + + "github.com/beego/beego/v2/core/logs" +) + +type Pidfile struct { + Pathfile string +} + +var _localpid *Pidfile + +func NewPID(pathfile string) { + _localpid = New(pathfile) +} + +// New creates a new Pidfile and writes the current PID +func New(pathfile string) *Pidfile { + file, err := os.OpenFile(pathfile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModeExclusive|os.ModePerm) + if err != nil { + logs.Warn("pidfile: failed to open %s (%s)", pathfile, err) + return nil + } + defer file.Close() + pid := strconv.Itoa(os.Getpid()) + logs.Info("start process pid:%v --> %s", pid, pathfile) + file.WriteString(pid) + return &Pidfile{pathfile} +} + +func (pf *Pidfile) Remove() { + err := os.Remove(pf.Pathfile) + if err != nil { + logs.Warn("pidfile: failed to remove %s (%s)", pf.Pathfile, err) + } +} +func RemovePID() { + defer func() { recover() }() + if _localpid != nil { + _localpid.Remove() + } +} diff --git a/bmp-monitor-proxy/util/redis.go b/bmp-monitor-proxy/util/redis.go new file mode 100644 index 0000000..f07d9a2 --- /dev/null +++ b/bmp-monitor-proxy/util/redis.go @@ -0,0 +1,212 @@ +package util + +import ( + "fmt" + "sync" + "time" + + "github.com/go-redis/redis" +) + +var redisMonitorNamespace string + +var redisOnce sync.Once + +type redisUtil struct { + *redis.Client +} + +// RedisUtil singleton redis util +var RedisUtil *redisUtil + +// InitRedis initial redisUtil instance +func InitRedis(namespace, idc, addr, passwd string, db int) error { + redisOnce.Do(func() { + if RedisUtil == nil { + + RedisUtil = &redisUtil{ + redis.NewClient(&redis.Options{ + Addr: addr, + Password: passwd, // no password set + DB: db, // use default DB + }), + } + + redisMonitorNamespace = namespace + if idc != "" { + redisMonitorNamespace = namespace + ":" + idc + } + + } + }) + + return RedisUtil.Ping().Err() +} + +// SetObjectToRedisWithExpire set string object with a expiration +func SetObjectToRedisWithExpire(key, value string, sec int) error { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + err := RedisUtil.Set(fullKey, value, time.Second*time.Duration(sec)).Err() + if err != nil { + return err + } + + return nil +} + +// SetObjectToRedisWithExpire set string object with a expiration +func SetObjectWithExpire(key string, sec int) error { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + err := RedisUtil.Expire(fullKey, time.Second*time.Duration(sec)).Err() + if err != nil { + return err + } + + return nil +} + +// SetObjectToRedis set object to Redis +func SetObjectToRedis(key string, value string) error { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + fmt.Println("redis set full key is:" + fullKey) + fmt.Println("redis set value is:" + value) + err := RedisUtil.Set(fullKey, value, 0).Err() + if err != nil { + return err + } + + return nil +} + +// GetObjectFromRedis Get object from Redis +func GetObjectFromRedis(key string) (string, error) { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + ret, err := RedisUtil.Get(fullKey).Result() + if err != nil { + return "", err + } + + return ret, nil +} + +func DelObjectFromRedis(keys []string) error { + + if len(keys) <= 0 { + return nil + } + + var fullKeys []string + for _, v := range keys { + if v != "" { + fullKeys = append(fullKeys, redisMonitorNamespace+":"+v) + } + } + + if len(fullKeys) > 0 { + err := RedisUtil.Del(fullKeys...).Err() + if err != nil { + return err + } + } + + return nil +} + +// HSetObjectToRedis hash set object to Redis +func HSetObjectToRedis(key, field, value string) error { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + err := RedisUtil.HSet(fullKey, field, value).Err() + if err != nil { + return err + } + + return nil +} + +// HSetObjectToRedis hash set object to Redis +func HMSetObjectToRedis(key string, data map[string]interface{}) error { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + err := RedisUtil.HMSet(fullKey, data).Err() + if err != nil { + return err + } + + return nil +} + +// HGetObjectFromRedis hash get from redis +func HGetAllFromRedis(key string) (map[string]string, error) { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + ret, err := RedisUtil.HGetAll(fullKey).Result() + if err != nil { + return nil, err + } + return ret, nil +} + +// HGetObjectFromRedis hash get from redis +func HGetObjectFromRedis(key, field string) (string, error) { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + ret, err := RedisUtil.HGet(fullKey, field).Result() + if err != nil { + return "", err + } + return ret, nil +} + +func HDelObjectFromRedis(key string, fields []string) error { + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + if len(fields) <= 0 { + return nil + } + + err := RedisUtil.HDel(fullKey, fields...).Err() + + if err != nil { + return err + } + return nil +} diff --git a/bmp-monitor-proxy/util/strings.go b/bmp-monitor-proxy/util/strings.go new file mode 100644 index 0000000..5803f33 --- /dev/null +++ b/bmp-monitor-proxy/util/strings.go @@ -0,0 +1,10 @@ +package util + +func InArray4String(str string, arr []string) bool { + for _, v := range arr { + if str == v { + return true + } + } + return false +} diff --git a/bmp-openapi-console/.cmd b/bmp-openapi-console/.cmd new file mode 100644 index 0000000..ced32d3 --- /dev/null +++ b/bmp-openapi-console/.cmd @@ -0,0 +1 @@ +rm -rf vendor diff --git a/bmp-openapi-console/.gitmodules b/bmp-openapi-console/.gitmodules new file mode 100644 index 0000000..506f24c --- /dev/null +++ b/bmp-openapi-console/.gitmodules @@ -0,0 +1,3 @@ +[submodule "bmp-deploy"] + path = bmp-deploy + url = git@coding.jd.com:aidc-bmp/bmp-deploy.git diff --git a/bmp-openapi-console/.idea/.gitignore b/bmp-openapi-console/.idea/.gitignore new file mode 100644 index 0000000..35410ca --- /dev/null +++ b/bmp-openapi-console/.idea/.gitignore @@ -0,0 +1,8 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/bmp-openapi-console/.idea/bmp-openapi.iml b/bmp-openapi-console/.idea/bmp-openapi.iml new file mode 100644 index 0000000..7ee078d --- /dev/null +++ b/bmp-openapi-console/.idea/bmp-openapi.iml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/bmp-openapi-console/.idea/modules.xml b/bmp-openapi-console/.idea/modules.xml new file mode 100644 index 0000000..e7df1a4 --- /dev/null +++ b/bmp-openapi-console/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/bmp-openapi-console/.idea/vcs.xml b/bmp-openapi-console/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/bmp-openapi-console/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/bmp-openapi-console/Dockerfile b/bmp-openapi-console/Dockerfile new file mode 100644 index 0000000..1c8e901 --- /dev/null +++ b/bmp-openapi-console/Dockerfile @@ -0,0 +1,17 @@ +FROM centos:7.9.2009 + +MAINTAINER minping@jd.com +USER root +RUN groupadd -g 2001 ironic-api +RUN useradd -d /home/ironic-api -u 2001 -g 2001 ironic-api + +WORKDIR /home/ironic-api + +ADD ./ironic-api /home/ironic-api/ +RUN mkdir -p /home/ironic-api/conf +ADD ./conf/* /home/ironic-api/conf/ + +RUN chmod 755 /home/ironic-api/ironic-api +USER ironic-api +EXPOSE 9999 +CMD ./ironic-api \ No newline at end of file diff --git a/bmp-openapi-console/Makefile b/bmp-openapi-console/Makefile new file mode 100644 index 0000000..19c38c9 --- /dev/null +++ b/bmp-openapi-console/Makefile @@ -0,0 +1,10 @@ + +BUILD_TIME := $(shell date +%Y%m%d%H%M%S) +VERSION := $(shell git describe --tags --always) +COMMITID := $(shell git rev-parse ${VERSION} | cut -c 1-32) +APP_NAME := ironic-api-golang + +#GOARCH=amd64 GOOS=linux +ldflags ="-s -X main.VERSION=${COMMITID} -X main.BUILD_TIME=${BUILD_TIME}" +all: + GOARCH=amd64 GOOS=linux go build -ldflags ${ldflags} -o ${APP_NAME} main.go diff --git a/bmp-openapi-console/README.md b/bmp-openapi-console/README.md new file mode 100644 index 0000000..6d19a7e --- /dev/null +++ b/bmp-openapi-console/README.md @@ -0,0 +1,22 @@ +# bmp-openapi-console + + +English | [简体中文](README.zh-CN.md) + +## Introduction + +The core interface layer of the console focuses on the life cycle of the instance, provides interfaces for bmp-openapi-console and developers, and transmits user actions to bmp-scheduler through intermediate keys such as mq and redis. + +The location of bmp-openapi-console in the entire bmp architecture is shown in:[bmp arch](../bmp-scheduler/README.md) + + + +## 2,Core Features + +- Instance create:In the console, you can specify various configurations for the listed devices to create a physical machine running an operating system. +- Instance destroy:Destroy the system disk of the physical machine running the operating system and restore it to a bare metal device. +- Instance reinstall:Reinstall the operating system on a device that has an operating system installed. +- Instance startup:Send a remote out-of-band command to power on the system. +- Instance shutdown:Send a remote out-of-band command to shut down the system. +- Instance restart:Send a remote out-of-band command to reboot. +- Instance reset password:Reset the root user login password of the operating system. \ No newline at end of file diff --git a/bmp-openapi-console/README.zh-CN.md b/bmp-openapi-console/README.zh-CN.md new file mode 100644 index 0000000..6053a00 --- /dev/null +++ b/bmp-openapi-console/README.zh-CN.md @@ -0,0 +1,23 @@ +# bmp-openapi-console + + +[English](README.md) | 简体中文 + +## 介绍 + +控制台核心接口层,围绕实例的生命周期,向上为bmp-openapi-console和开发者提供接口,向下通过mq、redis等中间键将用户动作传递到bmp-scheduler。 + +bmp-openapi-console在整个bmp架构中的位置见:[bmp架构图](../bmp-scheduler/README.zh-CN.md) + + + +## 2,核心功能 + +- 创建实例:在控制台可以将上架的设备指定各种配置,创建成一台运行操作系统的物理机。 +- 销毁实例:将运行操作系统的物理机销毁系统盘,还原成裸金属设备。 +- 重装实例:对已安装操作系统的设备重新安装操作系统。 +- 实例开机:发送远程带外命令开机。 +- 实例关机:发送远程带外命令关机。 +- 实例重启:发送远程带外命令重启。 +- 实例重置密码:重置操作系统root用户登陆密码。 + diff --git a/bmp-openapi-console/bmp-openapi-console.Dockerfile b/bmp-openapi-console/bmp-openapi-console.Dockerfile new file mode 100644 index 0000000..42c5ec2 --- /dev/null +++ b/bmp-openapi-console/bmp-openapi-console.Dockerfile @@ -0,0 +1,14 @@ +FROM golang:1.17-alpine AS builder +ENV GOPROXY https://goproxy.cn +WORKDIR /usr/src/bmp-openapi-console +COPY . . +RUN go build -o /tmp/bmp-openapi-console . + +FROM alpine:3.16 +RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories \ + && apk add tzdata \ + && apk add dmidecode +WORKDIR /home/bmp/bmp-openapi-console +COPY --from=builder /tmp/bmp-openapi-console . +COPY ./conf ./conf +CMD ["./bmp-openapi-console"] diff --git a/bmp-openapi-console/bmp-openapi-console.md b/bmp-openapi-console/bmp-openapi-console.md new file mode 100755 index 0000000..f5dc823 --- /dev/null +++ b/bmp-openapi-console/bmp-openapi-console.md @@ -0,0 +1,2720 @@ + +

bmp-openapi-console

+ + + +# deviceType + +## /deviceTypes + +### 基本信息 + +**Path:** /v1/deviceTypes + +**Method:** GET + +**接口描述:** +DescribeDeviceTypes 获取机型列表 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| pageNumber | 否 | | 页码 | +| pageSize | 否 | | 每页数量 | +| deviceTypeId | 否 | | 机型id | +| deviceType | 否 | | 机型规格 | +| idcId | 否 | | 机房id | +| name | 否 | | 机型名称 | +| deviceSeries | 否 | | 机型类型 | +| isAll | 否 | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ deviceTypesobject []非必须机型列表

item 类型: object

├─ architecturestring非必须体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64
├─ boot_modestring非必须boot模式
├─ cpuAmountinteger非必须cpu数量

format: int64

├─ cpuCoresinteger非必须单个cpu内核数

format: int64

├─ cpuFrequencystring非必须cpu频率(G)
├─ cpuInfostring非必须拼装信息
├─ cpuManufacturerstring非必须cpu厂商
├─ cpuModelstring非必须cpu处理器型号
├─ cpuSpecstring非必须CPU 规格,预置还是其它
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ dataVolumeAmountinteger非必须数据盘数量

format: int64

├─ dataVolumeInterfaceTypestring非必须数据盘接口类型(SATA,SAS,NVME)
├─ dataVolumeSizeinteger非必须数据盘单盘大小

format: int64

├─ dataVolumeTypestring非必须数据盘类型(SSD,HDD)
├─ dataVolumeUnitstring非必须数据盘单位(GB,TB)
├─ descriptionstring非必须描述
├─ deviceCountinteger非必须

format: int64

├─ deviceSeriesstring非必须机型类型,如计算型,存储型
├─ deviceSeriesNamestring非必须机型类型,如计算型,存储型
├─ deviceTypestring非必须机型规格, cps.c.normal
├─ deviceTypeIdstring非必须机型uuid
├─ dvInfostring非必须
├─ gpuAmountinteger非必须gpu数量

format: int64

├─ gpuInfostring非必须
├─ gpuManufacturerstring非必须gpu厂商
├─ gpuModelstring非必须gpu处理器型号
├─ heightinteger非必须显示机型高度

format: int64

├─ idinteger非必须

format: int64

├─ idcIdstring非必须机房uuid
├─ idcNamestring非必须机房名称
├─ idcNameEnstring非必须机房名称
├─ instanceCountinteger非必须

format: int64

├─ instanceStatusstring []非必须

item 类型: string

├─ 非必须
├─ interfaceModestring非必须bond单网口,dual双网口
├─ memAmountinteger非必须内存数量

format: int64

├─ memFrequencyinteger非必须内存主频(MHz)

format: int64

├─ memInfostring非必须
├─ memSizeinteger非必须单个内存大小(GB)

format: int64

├─ memSpecstring非必须内存 规格,预置还是其它
├─ memTypestring非必须内存接口(如DDR3,DDR4)
├─ namestring非必须机型名称,如计算效能型,标准计算型
├─ nicAmountinteger非必须网卡数量

format: int64

├─ nicInfostring非必须
├─ nicRateinteger非必须网卡传输速率(GE)

format: int64

├─ raidstring非必须系统盘raid
├─ stockAvailableinteger非必须StockAvailable 可用库存

format: int64

├─ svInfostring非必须
├─ systemVolumeAmountinteger非必须系统盘数量

format: int64

├─ systemVolumeInterfaceTypestring非必须系统盘接口类型(SATA,SAS,NVME)
├─ systemVolumeSizeinteger非必须系统盘单盘大小

format: int64

├─ systemVolumeTypestring非必须系统盘类型(SSD,HDD)
├─ systemVolumeUnitstring非必须系统盘单位(GB,TB)
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ pageNumberinteger非必须

format: int64

├─ pageSizeinteger非必须

format: int64

├─ totalCountinteger非必须

format: int64

+ +## /deviceTypes/deviceTypeImage + +### 基本信息 + +**Path:** /v1/deviceTypes/deviceTypeImage + +**Method:** GET + +**接口描述:** +QueryDeviceTypeImage 根据机型获取镜像 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| pageNumber | 否 | | 页码 | +| pageSize | 否 | | 每页数量 | +| deviceTypeId | 否 | | 机型id | +| imageId | 否 | | 镜像id | +| architecture | 否 | | 体系架构 | +| osType | 否 | | 操作系统平台 | +| imageName | 否 | | 镜像名称 | +| version | 否 | | 版本号 | +| osId | 否 | | 操作系统ID | +| source | 否 | | 镜像类型,预置,自定义 | +| isAll | 否 | | 是否显示全部 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ imagesobject []非必须镜像实体列表

item 类型: object

├─ architecturestring非必须架构:x86/x64/i386/
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ dataPartitionstring非必须数据分区信息
├─ descriptionstring非必须描述
├─ deviceTypeNuminteger非必须绑定了机型数量

format: int64

├─ filenamestring非必须镜像文件名称
├─ formatstring非必须镜像格式(qcow2、tar)
├─ hashstring非必须镜像校验码
├─ idinteger非必须

format: uint64

├─ imageIdstring非必须镜像uuid
├─ imageNamestring非必须镜像名称
├─ isBindboolean非必须是否绑定了某个机型
├─ osIdstring非必须源os uuid
├─ osNamestring非必须CentOS 7.2 64-bit
├─ osTypestring非必须操作系统分类:linux/windows
├─ osVersionstring非必须操作系统版本
├─ sourcestring非必须镜像来源(common通用、customize定制、user_defined自定义)
├─ sourceNamestring非必须镜像来源(common通用、customize定制、user_defined自定义)
├─ systemPartitionstring非必须系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap)
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ urlstring非必须镜像源路径
├─ pageNumberinteger非必须页数

format: int64

├─ pageSizeinteger非必须页大小

format: int64

├─ totalCountinteger非必须总条数

format: int64

+ +## /deviceTypes/deviceTypeImagePartition + +### 基本信息 + +**Path:** /v1/deviceTypes/deviceTypeImagePartition + +**Method:** GET + +**接口描述:** +QueryDeviceTypeImagePartition 根据机型,镜像,获取分区 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| deviceTypeId | 否 | | 机型id | +| imageId | 否 | | 镜像id | +| isAll | 否 | | 是否显示所有,isAll=1显示所有 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ dataPartitionobject []非必须数据盘分区列表

item 类型: object

├─ formatstring非必须format,如[swap, xfs]
├─ pointstring非必须point,如[swap, /, /var]
├─ sizeinteger非必须分区大小, MB为单位

format: int64

├─ systemPartitionobject []非必须系统盘分区列表

item 类型: object

├─ formatstring非必须format,如[swap, xfs]
├─ pointstring非必须point,如[swap, /, /var]
├─ sizeinteger非必须分区大小, MB为单位

format: int64

+ +## /deviceTypes/deviceTypeRaid + +### 基本信息 + +**Path:** /v1/deviceTypes/deviceTypeRaid + +**Method:** GET + +**接口描述:** +DescribeDeviceTypeRaids 根据机型获取raid + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| deviceTypeId | 否 | | 机型id | +| volumeType | 否 | | 系统盘还是数据盘 | +| raidId | 否 | | raidID | +| isAll | 否 | | 是否显示所有 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject []非必须

item 类型: object

├─ DiskInterfaceTypestring非必须磁盘类型:SAS/SATA/SSD/NVME
├─ availableValueinteger非必须可用分区值,单位GB

format: int64

├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ deviceTypeIdstring非必须设备类型id
├─ diskTypestring非必须磁盘类型:SAS/SATA/SSD/NVME
├─ raidIdstring非必须RAID uuid
├─ systemPartitionCountinteger非必须系统盘noraid模式真实数量;此模式多块盘只能用一块

format: int64

├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ volumeDetailstring非必须磁盘详细信息
├─ volumeTypestring非必须磁盘类型 system/data
+ +## /deviceTypes/{device_type_id} + +### 基本信息 + +**Path:** /v1/deviceTypes/{device_type_id} + +**Method:** GET + +**接口描述:** +DescribeDeviceType 获取机型详情 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| device_type_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ deviceTypeobject非必须
├─ architecturestring非必须体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64
├─ boot_modestring非必须boot模式
├─ cpuAmountinteger非必须cpu数量

format: int64

├─ cpuCoresinteger非必须单个cpu内核数

format: int64

├─ cpuFrequencystring非必须cpu频率(G)
├─ cpuInfostring非必须拼装信息
├─ cpuManufacturerstring非必须cpu厂商
├─ cpuModelstring非必须cpu处理器型号
├─ cpuSpecstring非必须CPU 规格,预置还是其它
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ dataVolumeAmountinteger非必须数据盘数量

format: int64

├─ dataVolumeInterfaceTypestring非必须数据盘接口类型(SATA,SAS,NVME)
├─ dataVolumeSizeinteger非必须数据盘单盘大小

format: int64

├─ dataVolumeTypestring非必须数据盘类型(SSD,HDD)
├─ dataVolumeUnitstring非必须数据盘单位(GB,TB)
├─ descriptionstring非必须描述
├─ deviceCountinteger非必须

format: int64

├─ deviceSeriesstring非必须机型类型,如计算型,存储型
├─ deviceSeriesNamestring非必须机型类型,如计算型,存储型
├─ deviceTypestring非必须机型规格, cps.c.normal
├─ deviceTypeIdstring非必须机型uuid
├─ dvInfostring非必须
├─ gpuAmountinteger非必须gpu数量

format: int64

├─ gpuInfostring非必须
├─ gpuManufacturerstring非必须gpu厂商
├─ gpuModelstring非必须gpu处理器型号
├─ heightinteger非必须显示机型高度

format: int64

├─ idinteger非必须

format: int64

├─ idcIdstring非必须机房uuid
├─ idcNamestring非必须机房名称
├─ idcNameEnstring非必须机房名称
├─ instanceCountinteger非必须

format: int64

├─ instanceStatusstring []非必须

item 类型: string

├─ 非必须
├─ interfaceModestring非必须bond单网口,dual双网口
├─ memAmountinteger非必须内存数量

format: int64

├─ memFrequencyinteger非必须内存主频(MHz)

format: int64

├─ memInfostring非必须
├─ memSizeinteger非必须单个内存大小(GB)

format: int64

├─ memSpecstring非必须内存 规格,预置还是其它
├─ memTypestring非必须内存接口(如DDR3,DDR4)
├─ namestring非必须机型名称,如计算效能型,标准计算型
├─ nicAmountinteger非必须网卡数量

format: int64

├─ nicInfostring非必须
├─ nicRateinteger非必须网卡传输速率(GE)

format: int64

├─ raidstring非必须系统盘raid
├─ stockAvailableinteger非必须StockAvailable 可用库存

format: int64

├─ svInfostring非必须
├─ systemVolumeAmountinteger非必须系统盘数量

format: int64

├─ systemVolumeInterfaceTypestring非必须系统盘接口类型(SATA,SAS,NVME)
├─ systemVolumeSizeinteger非必须系统盘单盘大小

format: int64

├─ systemVolumeTypestring非必须系统盘类型(SSD,HDD)
├─ systemVolumeUnitstring非必须系统盘单位(GB,TB)
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
+ +# device + +## /devices + +### 基本信息 + +**Path:** /v1/devices + +**Method:** GET + +**接口描述:** +DescribeDevices 获取设备列表 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| pageNumber | 否 | | 页码 | +| pageSize | 否 | | 每页数量 | +| idcId | 否 | | 机房id | +| sn | 否 | | 设备sn | +| instanceId | 否 | | 实例id | +| deviceTypeId | 否 | | 机型id | +| manageStatus | 否 | | 设备管理状态 | +| iloIp | 否 | | 带外ip | +| ipv4 | 否 | | ipv4 | +| ipv6 | 否 | | ipv6 | +| deviceSeries | 否 | | 机型类型 | +| userId | 否 | | 所属用户id | +| userName | 否 | | 所属用户 | +| isAll | 否 | | 是否显示全部,1不分页 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ devicesobject []非必须设备列表

item 类型: object

├─ Enclosure2string非必须系统盘2背板号
├─ adapterIdinteger非必须adapter_id

format: int64

├─ architecturestring非必须体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64
├─ brandstring非必须品牌
├─ cabinetstring非必须机柜编码
├─ cpuAmountinteger非必须cpu数量

format: int64

├─ cpuCoresinteger非必须单个cpu内核数

format: int64

├─ cpuFrequencystring非必须cpu频率(G)
├─ cpuInfostring非必须拼装信息
├─ cpuManufacturerstring非必须cpu厂商
├─ cpuModelstring非必须cpu处理器型号
├─ cpuRoadsinteger非必须单个cpu路数

format: int8

├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ dataVolumeAmountinteger非必须数据盘数量

format: int64

├─ dataVolumeInterfaceTypestring非必须数据盘接口类型(SATA,SAS,NVME)
├─ dataVolumeSizeinteger非必须数据盘单盘大小

format: int64

├─ dataVolumeTypestring非必须数据盘类型(SSD,HDD)
├─ descriptionstring非必须描述
├─ deviceIdstring非必须设备uuid
├─ deviceSeriesstring非必须计算型,存储型
├─ deviceSeriesNamestring非必须计算型,存储型
├─ deviceTypestring非必须型号,机型规格cps.normal
├─ deviceTypeIdstring非必须机型uuid
├─ deviceTypeNamestring非必须机型名称
├─ dvInfostring非必须
├─ enclosure1string非必须添加到disk表, 系统盘1背板号
├─ gatewaystring非必须网关地址
├─ gpuAmountinteger非必须gpu数量

format: int64

├─ gpuInfostring非必须
├─ gpuManufacturerstring非必须gpu厂商
├─ gpuModelstring非必须gpu处理器型号
├─ idinteger非必须设备ID编号

format: int64

├─ idcIdstring必须机房uuid
├─ idcNamestring非必须机房名称
├─ idcNameEnstring非必须idcname
├─ iloIpstring非必须带外管理IP
├─ iloPasswordstring非必须带外账号密码
├─ iloUserstring非必须带外账号
├─ imageNamestring非必须实例镜像名称
├─ instanceCreatedTimestring非必须实例创建时间
├─ instanceDescriptionstring非必须实例描述
├─ instanceIdstring非必须实例id
├─ instanceNamestring非必须实例名称
├─ instanceReasonstring非必须实例失败原因
├─ instanceStatusstring非必须实例状态
├─ instanceStatusNamestring非必须实例状态
├─ interfaceModestring非必须【网口模式】【网络设置】: bond单网口,dual双网口
├─ lockedstring非必须实例是否锁定 锁定locked 未锁定unlocked
├─ mac1string非必须MAC1(eth0)
├─ mac2string非必须MAC2(eth2)
├─ manageStatusstring非必须设备状态: 未装机,已装机
├─ manageStatusNamestring非必须设备状态: 未装机,已装机
├─ maskstring非必须子网掩码
├─ memAmountinteger非必须内存数量

format: int64

├─ memFrequencyinteger非必须内存主频(MHz)

format: int64

├─ memInfostring非必须
├─ memSizeinteger非必须单个内存大小(GB)

format: int64

├─ memTypestring非必须内存接口(如DDR3,DDR4)
├─ modelstring非必须型号
├─ nicAmountinteger非必须网卡数量

format: int64

├─ nicInfostring非必须
├─ nicRateinteger非必须网卡传输速率(GE)

format: int64

├─ privateIpv4string非必须内网IPV4
├─ privateIpv6string非必须内网IPV6
├─ raidDriverstring非必须raid工具:(megacli64等)
├─ reasonstring非必须设备状态变更失败原因
├─ slot1integer非必须系统盘1槽位

format: int64

├─ slot2integer非必须系统盘2槽位

format: int64

├─ snstring非必须设备SN
├─ svInfostring非必须
├─ switchIpstring非必须网口交换机IP
├─ switchIp1string非必须交换机1ip
├─ switchIp2string非必须交换机2ip
├─ switchPassword1string非必须交换机1登录密码
├─ switchPassword2string非必须交换机2登录密码
├─ switchPort1string非必须交换机1port
├─ switchPort2string非必须交换机2port
├─ switchUser1string非必须交换机1登录账号,如果为空,取所在机房的值
├─ switchUser2string非必须交换机2登录账号,如果为空,取所在机房的值
├─ systemVolumeAmountinteger非必须系统盘数量

format: int64

├─ systemVolumeInterfaceTypestring非必须系统盘接口类型(SATA,SAS,NVME)
├─ systemVolumeSizeinteger非必须系统盘单盘大小

format: int64

├─ systemVolumeTypestring非必须系统盘类型(SSD,HDD)
├─ uPositionstring非必须U位
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ userIdstring非必须实例归属用户uuid
├─ userNamestring非必须实例归属用户名称
├─ pageNumberinteger非必须

format: int64

├─ pageSizeinteger非必须

format: int64

├─ totalCountinteger非必须

format: int64

+ +## /devices/stock + +### 基本信息 + +**Path:** /v1/devices/stock + +**Method:** DELETE + +**接口描述:** +DescribeDeviceStock 获取指定机型的设备库存 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| deviceTypeId | 否 | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ stocksinteger非必须库存量

format: int64

+ +## /devices/{device_id} + +### 基本信息 + +**Path:** /v1/devices/{device_id} + +**Method:** GET + +**接口描述:** +DescribeDevice 获取设备详情 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| device_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ deviceobject非必须
├─ Enclosure2string非必须系统盘2背板号
├─ adapterIdinteger非必须adapter_id

format: int64

├─ architecturestring非必须体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64
├─ brandstring非必须品牌
├─ cabinetstring非必须机柜编码
├─ cpuAmountinteger非必须cpu数量

format: int64

├─ cpuCoresinteger非必须单个cpu内核数

format: int64

├─ cpuFrequencystring非必须cpu频率(G)
├─ cpuInfostring非必须拼装信息
├─ cpuManufacturerstring非必须cpu厂商
├─ cpuModelstring非必须cpu处理器型号
├─ cpuRoadsinteger非必须单个cpu路数

format: int8

├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ dataVolumeAmountinteger非必须数据盘数量

format: int64

├─ dataVolumeInterfaceTypestring非必须数据盘接口类型(SATA,SAS,NVME)
├─ dataVolumeSizeinteger非必须数据盘单盘大小

format: int64

├─ dataVolumeTypestring非必须数据盘类型(SSD,HDD)
├─ descriptionstring非必须描述
├─ deviceIdstring非必须设备uuid
├─ deviceSeriesstring非必须计算型,存储型
├─ deviceSeriesNamestring非必须计算型,存储型
├─ deviceTypestring非必须型号,机型规格cps.normal
├─ deviceTypeIdstring非必须机型uuid
├─ deviceTypeNamestring非必须机型名称
├─ dvInfostring非必须
├─ enclosure1string非必须添加到disk表, 系统盘1背板号
├─ gatewaystring非必须网关地址
├─ gpuAmountinteger非必须gpu数量

format: int64

├─ gpuInfostring非必须
├─ gpuManufacturerstring非必须gpu厂商
├─ gpuModelstring非必须gpu处理器型号
├─ idinteger非必须设备ID编号

format: int64

├─ idcIdstring必须机房uuid
├─ idcNamestring非必须机房名称
├─ idcNameEnstring非必须idcname
├─ iloIpstring非必须带外管理IP
├─ iloPasswordstring非必须带外账号密码
├─ iloUserstring非必须带外账号
├─ imageNamestring非必须实例镜像名称
├─ instanceCreatedTimestring非必须实例创建时间
├─ instanceDescriptionstring非必须实例描述
├─ instanceIdstring非必须实例id
├─ instanceNamestring非必须实例名称
├─ instanceReasonstring非必须实例失败原因
├─ instanceStatusstring非必须实例状态
├─ instanceStatusNamestring非必须实例状态
├─ interfaceModestring非必须【网口模式】【网络设置】: bond单网口,dual双网口
├─ lockedstring非必须实例是否锁定 锁定locked 未锁定unlocked
├─ mac1string非必须MAC1(eth0)
├─ mac2string非必须MAC2(eth2)
├─ manageStatusstring非必须设备状态: 未装机,已装机
├─ manageStatusNamestring非必须设备状态: 未装机,已装机
├─ maskstring非必须子网掩码
├─ memAmountinteger非必须内存数量

format: int64

├─ memFrequencyinteger非必须内存主频(MHz)

format: int64

├─ memInfostring非必须
├─ memSizeinteger非必须单个内存大小(GB)

format: int64

├─ memTypestring非必须内存接口(如DDR3,DDR4)
├─ modelstring非必须型号
├─ nicAmountinteger非必须网卡数量

format: int64

├─ nicInfostring非必须
├─ nicRateinteger非必须网卡传输速率(GE)

format: int64

├─ privateIpv4string非必须内网IPV4
├─ privateIpv6string非必须内网IPV6
├─ raidDriverstring非必须raid工具:(megacli64等)
├─ reasonstring非必须设备状态变更失败原因
├─ slot1integer非必须系统盘1槽位

format: int64

├─ slot2integer非必须系统盘2槽位

format: int64

├─ snstring非必须设备SN
├─ svInfostring非必须
├─ switchIpstring非必须网口交换机IP
├─ switchIp1string非必须交换机1ip
├─ switchIp2string非必须交换机2ip
├─ switchPassword1string非必须交换机1登录密码
├─ switchPassword2string非必须交换机2登录密码
├─ switchPort1string非必须交换机1port
├─ switchPort2string非必须交换机2port
├─ switchUser1string非必须交换机1登录账号,如果为空,取所在机房的值
├─ switchUser2string非必须交换机2登录账号,如果为空,取所在机房的值
├─ systemVolumeAmountinteger非必须系统盘数量

format: int64

├─ systemVolumeInterfaceTypestring非必须系统盘接口类型(SATA,SAS,NVME)
├─ systemVolumeSizeinteger非必须系统盘单盘大小

format: int64

├─ systemVolumeTypestring非必须系统盘类型(SSD,HDD)
├─ uPositionstring非必须U位
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ userIdstring非必须实例归属用户uuid
├─ userNamestring非必须实例归属用户名称
+ +# idc + +## /idcs + +### 基本信息 + +**Path:** /v1/idcs + +**Method:** GET + +**接口描述:** +DescribeIdcs 获取idc列表 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| pageNumber | 否 | | 页码 | +| pageSize | 否 | | 每页数量 | +| name | 否 | | 机房名称 | +| nameEn | 否 | | 机房英文名称 | +| level | 否 | | 机房等级 | +| isAll | 否 | | 是否显示所有 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ idcsobject []非必须机房列表

item 类型: object

├─ addressstring非必须机房地址
├─ createTimestring非必须创建时间
├─ createdBystring非必须创建者
├─ idinteger非必须

format: int64

├─ idcIdstring非必须机房uuid
├─ iloPasswordstring非必须机房公用带外管理password
├─ iloUserstring非必须机房公用带外管理user
├─ levelstring非必须机房等级
├─ namestring非必须机房名称
├─ nameEnstring非必须机房名称en
├─ shortnamestring非必须shortname
├─ switchPassword1string非必须交换机密码1
├─ switchPassword2string非必须交换机密码2
├─ switchUser1string非必须交换机用户名1
├─ switchUser2string非必须交换机用户名2
├─ updateTimestring非必须修改时间
├─ updatedBystring非必须修改用户
├─ pageNumberinteger非必须页数

format: int64

├─ pageSizeinteger非必须页大小

format: int64

├─ totalCountinteger非必须总条数

format: int64

+ +## /idcs/{idc_id} + +### 基本信息 + +**Path:** /v1/idcs/{idc_id} + +**Method:** GET + +**接口描述:** +DescribeIdc 获取idc详情 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| idc_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ idcobject非必须
├─ addressstring非必须机房地址
├─ createTimestring非必须创建时间
├─ createdBystring非必须创建者
├─ idinteger非必须

format: int64

├─ idcIdstring非必须机房uuid
├─ iloPasswordstring非必须机房公用带外管理password
├─ iloUserstring非必须机房公用带外管理user
├─ levelstring非必须机房等级
├─ namestring非必须机房名称
├─ nameEnstring非必须机房名称en
├─ shortnamestring非必须shortname
├─ switchPassword1string非必须交换机密码1
├─ switchPassword2string非必须交换机密码2
├─ switchUser1string非必须交换机用户名1
├─ switchUser2string非必须交换机用户名2
├─ updateTimestring非必须修改时间
├─ updatedBystring非必须修改用户
+ +# image + +## /images + +### 基本信息 + +**Path:** /v1/images + +**Method:** GET + +**接口描述:** +DescribeImages 获取镜像列表 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| pageNumber | 否 | | 页码 | +| pageSize | 否 | | 每页数量 | +| imageId | 否 | | 镜像ID | +| imageName | 否 | | 镜像名称 | +| deviceTypeId | 否 | | 设备类型id | +| version | 否 | | 版本号 | +| osId | 否 | | 操作系统ID | +| imageIds | 否 | | 镜像ID,数组,支持多个 | +| source | 否 | | 镜像类型,预置,自定义 | +| architecture | 否 | | 体系架构 | +| osType | 否 | | 操作系统平台 | +| isAll | 否 | | 是否显示全部 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ imagesobject []非必须镜像实体列表

item 类型: object

├─ architecturestring非必须架构:x86/x64/i386/
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ dataPartitionstring非必须数据分区信息
├─ descriptionstring非必须描述
├─ deviceTypeNuminteger非必须绑定了机型数量

format: int64

├─ filenamestring非必须镜像文件名称
├─ formatstring非必须镜像格式(qcow2、tar)
├─ hashstring非必须镜像校验码
├─ idinteger非必须

format: uint64

├─ imageIdstring非必须镜像uuid
├─ imageNamestring非必须镜像名称
├─ isBindboolean非必须是否绑定了某个机型
├─ osIdstring非必须源os uuid
├─ osNamestring非必须CentOS 7.2 64-bit
├─ osTypestring非必须操作系统分类:linux/windows
├─ osVersionstring非必须操作系统版本
├─ sourcestring非必须镜像来源(common通用、customize定制、user_defined自定义)
├─ sourceNamestring非必须镜像来源(common通用、customize定制、user_defined自定义)
├─ systemPartitionstring非必须系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap)
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ urlstring非必须镜像源路径
├─ pageNumberinteger非必须页数

format: int64

├─ pageSizeinteger非必须页大小

format: int64

├─ totalCountinteger非必须总条数

format: int64

+ +## /images/imageDeviceTypes + +### 基本信息 + +**Path:** /v1/images/imageDeviceTypes + +**Method:** GET + +**接口描述:** +DescribeImageDeviceTypes 查看镜像绑定的机型 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| pageNumber | 否 | | 页码 | +| pageSize | 否 | | 每页数量 | +| imageId | 是 | | 镜像ID | +| architecture | 否 | | 体系架构 | +| isBind | 否 | | 镜像是否绑定了机型,0查询该镜像没有绑定的机型列表 1查询该镜像已经绑定了的机型列表 | +| isAll | 否 | | 是否显示全部 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ deviceTypesobject []非必须机型列表

item 类型: object

├─ architecturestring非必须体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64
├─ boot_modestring非必须boot模式
├─ cpuAmountinteger非必须cpu数量

format: int64

├─ cpuCoresinteger非必须单个cpu内核数

format: int64

├─ cpuFrequencystring非必须cpu频率(G)
├─ cpuInfostring非必须拼装信息
├─ cpuManufacturerstring非必须cpu厂商
├─ cpuModelstring非必须cpu处理器型号
├─ cpuSpecstring非必须CPU 规格,预置还是其它
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ dataVolumeAmountinteger非必须数据盘数量

format: int64

├─ dataVolumeInterfaceTypestring非必须数据盘接口类型(SATA,SAS,NVME)
├─ dataVolumeSizeinteger非必须数据盘单盘大小

format: int64

├─ dataVolumeTypestring非必须数据盘类型(SSD,HDD)
├─ dataVolumeUnitstring非必须数据盘单位(GB,TB)
├─ descriptionstring非必须描述
├─ deviceCountinteger非必须

format: int64

├─ deviceSeriesstring非必须机型类型,如计算型,存储型
├─ deviceSeriesNamestring非必须机型类型,如计算型,存储型
├─ deviceTypestring非必须机型规格, cps.c.normal
├─ deviceTypeIdstring非必须机型uuid
├─ dvInfostring非必须
├─ gpuAmountinteger非必须gpu数量

format: int64

├─ gpuInfostring非必须
├─ gpuManufacturerstring非必须gpu厂商
├─ gpuModelstring非必须gpu处理器型号
├─ heightinteger非必须显示机型高度

format: int64

├─ idinteger非必须

format: int64

├─ idcIdstring非必须机房uuid
├─ idcNamestring非必须机房名称
├─ idcNameEnstring非必须机房名称
├─ instanceCountinteger非必须

format: int64

├─ instanceStatusstring []非必须

item 类型: string

├─ 非必须
├─ interfaceModestring非必须bond单网口,dual双网口
├─ memAmountinteger非必须内存数量

format: int64

├─ memFrequencyinteger非必须内存主频(MHz)

format: int64

├─ memInfostring非必须
├─ memSizeinteger非必须单个内存大小(GB)

format: int64

├─ memSpecstring非必须内存 规格,预置还是其它
├─ memTypestring非必须内存接口(如DDR3,DDR4)
├─ namestring非必须机型名称,如计算效能型,标准计算型
├─ nicAmountinteger非必须网卡数量

format: int64

├─ nicInfostring非必须
├─ nicRateinteger非必须网卡传输速率(GE)

format: int64

├─ raidstring非必须系统盘raid
├─ stockAvailableinteger非必须StockAvailable 可用库存

format: int64

├─ svInfostring非必须
├─ systemVolumeAmountinteger非必须系统盘数量

format: int64

├─ systemVolumeInterfaceTypestring非必须系统盘接口类型(SATA,SAS,NVME)
├─ systemVolumeSizeinteger非必须系统盘单盘大小

format: int64

├─ systemVolumeTypestring非必须系统盘类型(SSD,HDD)
├─ systemVolumeUnitstring非必须系统盘单位(GB,TB)
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ pageNumberinteger非必须

format: int64

├─ pageSizeinteger非必须

format: int64

├─ totalCountinteger非必须

format: int64

+ +## /images/{image_id} + +### 基本信息 + +**Path:** /v1/images/{image_id} + +**Method:** GET + +**接口描述:** +DescribeImage 获取镜像详情 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| image_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ imageobject非必须
├─ architecturestring非必须架构:x86/x64/i386/
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ dataPartitionstring非必须数据分区信息
├─ descriptionstring非必须描述
├─ deviceTypeNuminteger非必须绑定了机型数量

format: int64

├─ filenamestring非必须镜像文件名称
├─ formatstring非必须镜像格式(qcow2、tar)
├─ hashstring非必须镜像校验码
├─ idinteger非必须

format: uint64

├─ imageIdstring非必须镜像uuid
├─ imageNamestring非必须镜像名称
├─ isBindboolean非必须是否绑定了某个机型
├─ osIdstring非必须源os uuid
├─ osNamestring非必须CentOS 7.2 64-bit
├─ osTypestring非必须操作系统分类:linux/windows
├─ osVersionstring非必须操作系统版本
├─ sourcestring非必须镜像来源(common通用、customize定制、user_defined自定义)
├─ sourceNamestring非必须镜像来源(common通用、customize定制、user_defined自定义)
├─ systemPartitionstring非必须系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap)
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ urlstring非必须镜像源路径
+ +# user + +## /local/users + +### 基本信息 + +**Path:** /v1/local/users + +**Method:** GET + +**接口描述:** +DescribeLocalUser 控制台获取用户详情 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
errorobject非必须
├─ codeinteger非必须错误码

format: int64

├─ messagestring非必须错误信息
├─ statusstring非必须错误状态
resultobject非必须
├─ userobject非必须
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ defaultProjectIdstring非必须用户默认项目uuid
├─ defaultProjectNamestring非必须用户默认项目名称
├─ descriptionstring非必须描述
├─ emailstring非必须邮箱
├─ idinteger非必须用户id

format: int64

├─ languagestring非必须默认语言(en_US/zh_CN)
├─ phoneNumberstring非必须手机号
├─ phonePrefixstring非必须国家地区码,如86
├─ roleIdstring非必须角色uuid
├─ roleNamestring非必须角色名称
├─ timezonestring非必须时区
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ userIdstring非必须用户uuid
├─ userNamestring非必须用户名,唯一
+ +## /local/users + +### 基本信息 + +**Path:** /v1/local/users + +**Method:** PUT + +**接口描述:** +ModifyLocalUser 控制台修改除密码外的个人信息 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
defaultProjectIdstring非必须用户默认项目uuid
emailstring非必须邮箱
languagestring非必须语言[en_US, zh_CN]
phoneNumberstring非必须手机号
phonePrefixstring非必须国家地区码,如86
timezonestring非必须时区 Asia/Shanghai
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /local/users/password + +### 基本信息 + +**Path:** /v1/local/users/password + +**Method:** PUT + +**接口描述:** +ModifyLocalUserPassword 控制台修改个人密码 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
oldPasswordstring必须旧密码,明文
passwordstring必须新密码 明文,密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30}
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /users + +### 基本信息 + +**Path:** /v1/users + +**Method:** GET + +**接口描述:** +DescribeUsers 获取用户列表 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| pageNumber | 否 | | 页码 | +| pageSize | 否 | | 每页数量 | +| roleId | 否 | | 角色uuid | +| defaultProjectId | 否 | | 项目uuid | +| userName | 否 | | 用户名 | +| isAll | 否 | | 是否显示全部, isAll=1表示全部 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ pageNumberinteger非必须页数

format: int64

├─ pageSizeinteger非必须页大小

format: int64

├─ totalCountinteger非必须总条数

format: int64

├─ usersobject []非必须user实体列表

item 类型: object

├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ defaultProjectIdstring非必须用户默认项目uuid
├─ defaultProjectNamestring非必须用户默认项目名称
├─ descriptionstring非必须描述
├─ emailstring非必须邮箱
├─ idinteger非必须用户id

format: int64

├─ languagestring非必须默认语言(en_US/zh_CN)
├─ phoneNumberstring非必须手机号
├─ phonePrefixstring非必须国家地区码,如86
├─ roleIdstring非必须角色uuid
├─ roleNamestring非必须角色名称
├─ timezonestring非必须时区
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ userIdstring非必须用户uuid
├─ userNamestring非必须用户名,唯一
+ +## /users/getUserByName + +### 基本信息 + +**Path:** /v1/users/getUserByName + +**Method:** GET + +**接口描述:** +DescribeUserByName 根据用户名获取用户详情 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| userName | 是 | | 用户名,唯一 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ userobject非必须
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ defaultProjectIdstring非必须用户默认项目uuid
├─ defaultProjectNamestring非必须用户默认项目名称
├─ descriptionstring非必须描述
├─ emailstring非必须邮箱
├─ idinteger非必须用户id

format: int64

├─ languagestring非必须默认语言(en_US/zh_CN)
├─ phoneNumberstring非必须手机号
├─ phonePrefixstring非必须国家地区码,如86
├─ roleIdstring非必须角色uuid
├─ roleNamestring非必须角色名称
├─ timezonestring非必须时区
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ userIdstring非必须用户uuid
├─ userNamestring非必须用户名,唯一
+ +## /users/verify + +### 基本信息 + +**Path:** /v1/users/verify + +**Method:** POST + +**接口描述:** +VerifyUser 鉴定用户 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
passwordstring必须密码
roleIdstring必须角色uuid
userNamestring必须用户名,唯一
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /users/{user_id} + +### 基本信息 + +**Path:** /v1/users/{user_id} + +**Method:** GET + +**接口描述:** +DescribeUser 获取用户详情 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| user_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
errorobject非必须
├─ codeinteger非必须错误码

format: int64

├─ messagestring非必须错误信息
├─ statusstring非必须错误状态
resultobject非必须
├─ userobject非必须
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ defaultProjectIdstring非必须用户默认项目uuid
├─ defaultProjectNamestring非必须用户默认项目名称
├─ descriptionstring非必须描述
├─ emailstring非必须邮箱
├─ idinteger非必须用户id

format: int64

├─ languagestring非必须默认语言(en_US/zh_CN)
├─ phoneNumberstring非必须手机号
├─ phonePrefixstring非必须国家地区码,如86
├─ roleIdstring非必须角色uuid
├─ roleNamestring非必须角色名称
├─ timezonestring非必须时区
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ userIdstring非必须用户uuid
├─ userNamestring非必须用户名,唯一
+ +## /users/{user_id} + +### 基本信息 + +**Path:** /v1/users/{user_id} + +**Method:** PUT + +**接口描述:** +ModifyUser 修改用户信息 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| user_id | | | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
descriptionstring非必须描述
emailstring非必须邮箱
phoneNumberstring非必须手机号
phonePrefixstring非必须国家地区码,如86
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +# os + +## /oss + +### 基本信息 + +**Path:** /v1/oss + +**Method:** GET + +**接口描述:** +DescribeOSs 获取os列表(暂不启用) + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| osName | 否 | | 操作系统名称 | +| osType | 否 | | 操作系统平台 | +| osVersion | 否 | | 操作系统版本 | +| isAll | 否 | | 是否显示所有 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ ossobject []非必须操作系统列表

item 类型: object

├─ architecturestring非必须架构:x86/x64/i386/
├─ bitsinteger非必须指令宽度:64/32位

format: int64

├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ deletedTimestring非必须删除时间
├─ idinteger非必须ID

format: uint64

├─ isDelinteger非必须是否删除0未删除 1已删除

format: int8

├─ osIdstring非必须操作系统uuid
├─ osNamestring非必须操作系统名称
├─ osTypestring非必须操作系统分类:linux/windows
├─ osVersionstring非必须操作系统版本
├─ sysUserstring非必须管理员账户
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
+ +## /oss/{os_id} + +### 基本信息 + +**Path:** /v1/oss/{os_id} + +**Method:** GET + +**接口描述:** +DescribeOS 获取os系统详情(暂不启用) + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| os_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ osobject非必须
├─ architecturestring非必须架构:x86/x64/i386/
├─ bitsinteger非必须指令宽度:64/32位

format: int64

├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ deletedTimestring非必须删除时间
├─ idinteger非必须ID

format: uint64

├─ isDelinteger非必须是否删除0未删除 1已删除

format: int8

├─ osIdstring非必须操作系统uuid
├─ osNamestring非必须操作系统名称
├─ osTypestring非必须操作系统分类:linux/windows
├─ osVersionstring非必须操作系统版本
├─ sysUserstring非必须管理员账户
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
+ +# instance + +## /project/instances + +### 基本信息 + +**Path:** /v1/project/instances + +**Method:** GET + +**接口描述:** +DescribeProjectInstances 获取实例列表 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| pageNumber | 否 | | 页码 | +| pageSize | 否 | | 每页数量 | +| instanceId | 否 | | 实例ID | +| instanceName | 否 | | 实例名称,模糊搜索 | +| deviceTypeId | 否 | | 设备类型ID | +| status | 否 | | 运行状态 | +| deviceId | 否 | | 设备ID | +| sn | 否 | | SN | +| idcId | 否 | | 机房ID | +| projectId | 否 | | 项目ID | +| ilo_ip | 否 | | 带外ip,精确搜索 | +| ipv4 | 否 | | ipv4,精确搜索 | +| ipv6 | 否 | | ipv6,精确搜索 | +| isAll | 否 | | 是否显示全部,取值为1时表示全部 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ instancesobject []非必须instance实体数组

item 类型: object

├─ DataVolumeRaidNamestring非必须数据盘raid名称
├─ cpuAmountinteger非必须cpu数量

format: int64

├─ cpuCoresinteger非必须单个cpu内核数

format: int64

├─ cpuFrequencystring非必须cpu频率(GHz)
├─ cpuManufacturerstring非必须cpu厂商
├─ cpuModelstring非必须cpu处理器型号
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ dataVolumeAmountinteger非必须数据盘数量

format: int64

├─ dataVolumeInterfaceTypestring非必须数据盘接口类型(SATA,SAS,NVME)
├─ dataVolumeRaidIdstring非必须数据盘raidId
├─ dataVolumeSizeinteger非必须数据盘单盘大小

format: int64

├─ dataVolumeTypestring非必须数据盘类型(SSD,HDD)
├─ dataVolumeUnitstring非必须系统盘单位
├─ descriptionstring非必须实例描述
├─ deviceIdstring非必须设备uuid
├─ deviceSeriesstring非必须机型类型,如computer
├─ deviceSeriesNamestring非必须机型类型,如计算型,存储型
├─ deviceTypestring非必须机型规格, cps.c.normal
├─ deviceTypeIdstring非必须机型uuid
├─ deviceTypeNamestring非必须机型名称,如计算效能型,标准计算型
├─ gpuAmountinteger非必须gpu数量

format: int64

├─ gpuManufacturerstring非必须gpu厂商
├─ gpuModelstring非必须gpu处理器型号
├─ hostnamestring非必须主机名
├─ idcIdstring非必须机房uuid
├─ idcNamestring非必须机房名称
├─ iloIpstring非必须带外管理IP
├─ imageIdstring非必须镜像uuid
├─ imageNamestring非必须镜像名称
├─ instanceIdstring非必须实例uuid
├─ instanceNamestring非必须实例名称
├─ interfaceModestring非必须【网口模式】【网络设置】: bond单网口,dual双网口
├─ lockedstring非必须是否锁定解锁锁定:locked,解锁unlocked
├─ lockedNamestring非必须是否锁定解锁锁定:已解锁,已锁定
├─ memAmountinteger非必须内存数量

format: int64

├─ memFrequencyinteger非必须内存主频(MHz)

format: int64

├─ memSizeinteger非必须单个内存大小(GB)

format: int64

├─ memTypestring非必须内存接口(如DDR3,DDR4)
├─ nicAmountinteger非必须网卡数量

format: int64

├─ nicRateinteger非必须网卡传输速率(GE)

format: int64

├─ privateIpv4string非必须内网IPV4
├─ privateIpv6string非必须内网IPV6
├─ projectIdstring非必须实例所属项目UUID
├─ reasonstring非必须实例错误状态时的错误原因
├─ snstring非必须设备SN
├─ statusstring非必须运行状态
├─ statusNamestring非必须运行状态中文名字
├─ systemVolumeAmountinteger非必须系统盘数量

format: int64

├─ systemVolumeInterfaceTypestring非必须系统盘接口类型(SATA,SAS,NVME)
├─ systemVolumeRaidIdstring非必须系统盘raidId
├─ systemVolumeRaidNamestring非必须系统盘raid名称
├─ systemVolumeSizeinteger非必须系统盘单盘大小

format: int64

├─ systemVolumeTypestring非必须系统盘类型(SSD,HDD)
├─ systemVolumeUnitstring非必须系统盘单位
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ userIdstring非必须实例所属用户UUID
├─ pageNumberinteger非必须

format: int64

├─ pageSizeinteger非必须

format: int64

├─ totalCountinteger非必须

format: int64

+ +## /project/instances + +### 基本信息 + +**Path:** /v1/project/instances + +**Method:** POST + +**接口描述:** +CreateProjectInstance 创建实例 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
boot_modestring非必须
countinteger非必须创建数量

format: int64

descriptionstring非必须描述
deviceTypeIdstring必须设备类型ID
hostnamestring非必须主机名称
idcIdstring必须机房ID
imageIdstring必须镜像ID
instanceNamestring必须实例名称
passwordstring非必须密码
projectIdstring必须项目ID
sshKeyIdstring非必须秘钥ID
systemPartitionobject []非必须系统盘分区

item 类型: object

├─ formatstring非必须format,如[swap, xfs]
├─ pointstring非必须point,如[swap, /, /var]
├─ sizeinteger非必须分区大小, MB为单位

format: int64

systemVolumeRaidIdstring必须系统盘RAID ID
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ instanceIdsstring []非必须instanceId 列表

item 类型: string

├─ 非必须
+ +## /project/instances/batch/instances:deleteInstances + +### 基本信息 + +**Path:** /v1/project/instances/batch/instances:deleteInstances + +**Method:** DELETE + +**接口描述:** +DeleteInstances 批量删除实例 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
instance_idsstring []非必须实例id列表

item 类型: string

├─ 非必须
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /project/instances/batch/instances:modifyInstances + +### 基本信息 + +**Path:** /v1/project/instances/batch/instances:modifyInstances + +**Method:** PUT + +**接口描述:** +ModifyInstances 批量修改实例名称 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
instanceNamestring非必须实例名称
instance_idsstring []非必须实例id列表

item 类型: string

├─ 非必须
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /project/instances/batch/instances:restartInstances + +### 基本信息 + +**Path:** /v1/project/instances/batch/instances:restartInstances + +**Method:** PUT + +**接口描述:** +StartInstances 批量重启 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
instanceIdsstring []非必须

item 类型: string

├─ 非必须
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /project/instances/batch/instances:startInstances + +### 基本信息 + +**Path:** /v1/project/instances/batch/instances:startInstances + +**Method:** PUT + +**接口描述:** +StartInstances 批量开机 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
instanceIdsstring []非必须

item 类型: string

├─ 非必须
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /project/instances/batch/instances:stopInstances + +### 基本信息 + +**Path:** /v1/project/instances/batch/instances:stopInstances + +**Method:** PUT + +**接口描述:** +StartInstances 批量关机 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
instanceIdsstring []非必须

item 类型: string

├─ 非必须
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /project/instances/{instance_id} + +### 基本信息 + +**Path:** /v1/project/instances/{instance_id} + +**Method:** GET + +**接口描述:** +DescribeProjectInstance 获取实例详情 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| instance_id | | 实例uuid | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ instanceobject非必须
├─ DataVolumeRaidNamestring非必须数据盘raid名称
├─ cpuAmountinteger非必须cpu数量

format: int64

├─ cpuCoresinteger非必须单个cpu内核数

format: int64

├─ cpuFrequencystring非必须cpu频率(GHz)
├─ cpuManufacturerstring非必须cpu厂商
├─ cpuModelstring非必须cpu处理器型号
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ dataVolumeAmountinteger非必须数据盘数量

format: int64

├─ dataVolumeInterfaceTypestring非必须数据盘接口类型(SATA,SAS,NVME)
├─ dataVolumeRaidIdstring非必须数据盘raidId
├─ dataVolumeSizeinteger非必须数据盘单盘大小

format: int64

├─ dataVolumeTypestring非必须数据盘类型(SSD,HDD)
├─ dataVolumeUnitstring非必须系统盘单位
├─ descriptionstring非必须实例描述
├─ deviceIdstring非必须设备uuid
├─ deviceSeriesstring非必须机型类型,如computer
├─ deviceSeriesNamestring非必须机型类型,如计算型,存储型
├─ deviceTypestring非必须机型规格, cps.c.normal
├─ deviceTypeIdstring非必须机型uuid
├─ deviceTypeNamestring非必须机型名称,如计算效能型,标准计算型
├─ gpuAmountinteger非必须gpu数量

format: int64

├─ gpuManufacturerstring非必须gpu厂商
├─ gpuModelstring非必须gpu处理器型号
├─ hostnamestring非必须主机名
├─ idcIdstring非必须机房uuid
├─ idcNamestring非必须机房名称
├─ iloIpstring非必须带外管理IP
├─ imageIdstring非必须镜像uuid
├─ imageNamestring非必须镜像名称
├─ instanceIdstring非必须实例uuid
├─ instanceNamestring非必须实例名称
├─ interfaceModestring非必须【网口模式】【网络设置】: bond单网口,dual双网口
├─ lockedstring非必须是否锁定解锁锁定:locked,解锁unlocked
├─ lockedNamestring非必须是否锁定解锁锁定:已解锁,已锁定
├─ memAmountinteger非必须内存数量

format: int64

├─ memFrequencyinteger非必须内存主频(MHz)

format: int64

├─ memSizeinteger非必须单个内存大小(GB)

format: int64

├─ memTypestring非必须内存接口(如DDR3,DDR4)
├─ nicAmountinteger非必须网卡数量

format: int64

├─ nicRateinteger非必须网卡传输速率(GE)

format: int64

├─ privateIpv4string非必须内网IPV4
├─ privateIpv6string非必须内网IPV6
├─ projectIdstring非必须实例所属项目UUID
├─ reasonstring非必须实例错误状态时的错误原因
├─ snstring非必须设备SN
├─ statusstring非必须运行状态
├─ statusNamestring非必须运行状态中文名字
├─ systemVolumeAmountinteger非必须系统盘数量

format: int64

├─ systemVolumeInterfaceTypestring非必须系统盘接口类型(SATA,SAS,NVME)
├─ systemVolumeRaidIdstring非必须系统盘raidId
├─ systemVolumeRaidNamestring非必须系统盘raid名称
├─ systemVolumeSizeinteger非必须系统盘单盘大小

format: int64

├─ systemVolumeTypestring非必须系统盘类型(SSD,HDD)
├─ systemVolumeUnitstring非必须系统盘单位
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ userIdstring非必须实例所属用户UUID
+ +## /project/instances/{instance_id} + +### 基本信息 + +**Path:** /v1/project/instances/{instance_id} + +**Method:** PUT + +**接口描述:** +ModifyProjectInstance 修改实例信息 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| instance_id | | | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
descriptionstring非必须描述
instanceNamestring非必须实例名称
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /project/instances/{instance_id} + +### 基本信息 + +**Path:** /v1/project/instances/{instance_id} + +**Method:** DELETE + +**接口描述:** +DeleteProjectInstance 删除实例 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| instance_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /project/instances/{instance_id}/lock + +### 基本信息 + +**Path:** /v1/project/instances/{instance_id}/lock + +**Method:** PUT + +**接口描述:** +LockProjectInstance 锁定实例 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| instance_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /project/instances/{instance_id}/resetStatus + +### 基本信息 + +**Path:** /v1/project/instances/{instance_id}/resetStatus + +**Method:** PUT + +**接口描述:** +ResetInstanceStatus 重置实例状态 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| instance_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /project/instances/{instance_id}/restart + +### 基本信息 + +**Path:** /v1/project/instances/{instance_id}/restart + +**Method:** PUT + +**接口描述:** +RestartProjectInstance 实例重启 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| instance_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /project/instances/{instance_id}/start + +### 基本信息 + +**Path:** /v1/project/instances/{instance_id}/start + +**Method:** PUT + +**接口描述:** +StartProjectInstance 实例开机 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| instance_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /project/instances/{instance_id}/stop + +### 基本信息 + +**Path:** /v1/project/instances/{instance_id}/stop + +**Method:** PUT + +**接口描述:** +StopProjectInstance 实例关机 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| instance_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /project/instances/{instance_id}/unlock + +### 基本信息 + +**Path:** /v1/project/instances/{instance_id}/unlock + +**Method:** PUT + +**接口描述:** +UnLockProjectInstance 解锁实例 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| instance_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +# raid + +## /raids + +### 基本信息 + +**Path:** /v1/raids + +**Method:** GET + +**接口描述:** +DescribeRaids 获取raid列表 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ raidsobject []非必须raid实体列表

item 类型: object

├─ availableValueinteger非必须可用分区值,单位GB

format: int64

├─ descriptionEnstring非必须中文描述
├─ descriptionZhstring非必须description
├─ deviceTypeIdstring非必须设备类型uuid
├─ diskTypestring非必须磁盘类型:SAS/SATA/SSD/NVME
├─ namestring非必须raid 名称
├─ raidIdstring非必须raid uuid
├─ systemPartitionCountinteger非必须系统盘分区数量

format: int64

├─ volumeDetailstring非必须磁盘详细信息
├─ volumeTypestring非必须磁盘类型
+ +## /raids/{raid_id} + +### 基本信息 + +**Path:** /v1/raids/{raid_id} + +**Method:** GET + +**接口描述:** +DescribeRaid 获取raid详情 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| raid_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ availableValueinteger非必须可用分区值,单位GB

format: int64

├─ descriptionEnstring非必须中文描述
├─ descriptionZhstring非必须description
├─ deviceTypeIdstring非必须设备类型uuid
├─ diskTypestring非必须磁盘类型:SAS/SATA/SSD/NVME
├─ namestring非必须raid 名称
├─ raidIdstring非必须raid uuid
├─ systemPartitionCountinteger非必须系统盘分区数量

format: int64

├─ volumeDetailstring非必须磁盘详细信息
├─ volumeTypestring非必须磁盘类型
+ +# resource + +## /resources + +### 基本信息 + +**Path:** /v1/resources + +**Method:** GET + +**接口描述:** +DescribeResources 根据某个字段值精确查询对应的资源列表(如根据imageName查询镜像列表,根据idcName查询机房列表) + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| name | 否 | | 机房名称
IdcName string `json:"idcName"`
机房英文名称
IdcNameEn string `json:"idcNameEn"`*/
机型名称 | +| deviceType | 否 | | 机型规格 | +| imageName | 否 | | 镜像名称 | +| userName | 否 | | 用户名称 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +# role + +## /roles + +### 基本信息 + +**Path:** /v1/roles + +**Method:** GET + +**接口描述:** +DescribeRoles 获取角色列表 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| pageNumber | 否 | | 页码 | +| pageSize | 否 | | 每页数量 | +| isAll | 否 | | 是否显示所有 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ pageNumberinteger非必须

format: int64

├─ pageSizeinteger非必须

format: int64

├─ rolesobject []非必须角色实体列表

item 类型: object

├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ descriptionCnstring非必须description
├─ descriptionEnstring非必须权限描述
├─ permissionstring非必须权限
├─ roleIdstring非必须角色uuid
├─ roleNamestring非必须角色名称
├─ roleNameCnstring非必须角色名称,唯一
├─ roleNameEnstring非必须角色名称,唯一
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ userCountinteger非必须用户数

format: int64

├─ totalCountinteger非必须

format: int64

+ +## /roles/roleInfo/current + +### 基本信息 + +**Path:** /v1/roles/roleInfo/current + +**Method:** GET + +**接口描述:** +CurrentRole 获取当前登录用户的角色 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ roleobject非必须
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ descriptionCnstring非必须description
├─ descriptionEnstring非必须权限描述
├─ permissionstring非必须权限
├─ roleIdstring非必须角色uuid
├─ roleNamestring非必须角色名称
├─ roleNameCnstring非必须角色名称,唯一
├─ roleNameEnstring非必须角色名称,唯一
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ userCountinteger非必须用户数

format: int64

+ +## /roles/{role_id} + +### 基本信息 + +**Path:** /v1/roles/{role_id} + +**Method:** GET + +**接口描述:** +DescribeRole 获取角色详情 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| role_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ roleobject非必须
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ descriptionCnstring非必须description
├─ descriptionEnstring非必须权限描述
├─ permissionstring非必须权限
├─ roleIdstring非必须角色uuid
├─ roleNamestring非必须角色名称
├─ roleNameCnstring非必须角色名称,唯一
├─ roleNameEnstring非必须角色名称,唯一
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ userCountinteger非必须用户数

format: int64

+ +# apiKey + +## /user/apikeys + +### 基本信息 + +**Path:** /v1/user/apikeys + +**Method:** GET + +**接口描述:** +DescribeUserAPIKeys 获取APIKey列表 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| pageNumber | 否 | | 页码 | +| pageSize | 否 | | 每页数量 | +| name | 否 | | 秘钥对名称 | +| type | 否 | | Token类型, [system/user] | +| isAll | 否 | | 是否查询全部/导出 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ apikeysobject []非必须

item 类型: object

├─ apiKeyIdstring必须apikey uuid
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ idinteger非必须

format: int64

├─ namestring必须名称
├─ readOnlyinteger必须是否支持只读, [0/1], 1表示只读

format: int8

├─ tokenstring必须32位字符令牌,使用token来独立访问openapi
├─ typestring必须apikey的类型,[system/user]
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ userIdstring必须所属用户uuid
├─ pageNumberinteger非必须

format: int64

├─ pageSizeinteger非必须

format: int64

├─ totalCountinteger非必须

format: int64

+ +## /user/apikeys + +### 基本信息 + +**Path:** /v1/user/apikeys + +**Method:** POST + +**接口描述:** +CreateUserApikey 创建apikey + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
namestring必须秘钥对名称
readOnlyinteger必须是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法

format: int8

typestring必须Token类型, [system/user]
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ apikeyIdstring必须apikey uuid
+ +## /user/apikeys/{apikey_id} + +### 基本信息 + +**Path:** /v1/user/apikeys/{apikey_id} + +**Method:** GET + +**接口描述:** +DescribeUserAPIKey 获取apikey详情 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| apikey_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ apikeyobject非必须
├─ apiKeyIdstring必须apikey uuid
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ idinteger非必须

format: int64

├─ namestring必须名称
├─ readOnlyinteger必须是否支持只读, [0/1], 1表示只读

format: int8

├─ tokenstring必须32位字符令牌,使用token来独立访问openapi
├─ typestring必须apikey的类型,[system/user]
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ userIdstring必须所属用户uuid
+ +## /user/apikeys/{apikey_id} + +### 基本信息 + +**Path:** /v1/user/apikeys/{apikey_id} + +**Method:** PUT + +**接口描述:** +ModifyUserApikey 修改apikey(暂不启用) + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| apikey_id | | | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
namestring必须秘钥对名称
readOnlyinteger必须是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法

format: int8

+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /user/apikeys/{apikey_id} + +### 基本信息 + +**Path:** /v1/user/apikeys/{apikey_id} + +**Method:** DELETE + +**接口描述:** +DeleteUserApikey 删除某个apikey + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| apikey_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +# project + +## /user/projects + +### 基本信息 + +**Path:** /v1/user/projects + +**Method:** GET + +**接口描述:** +DescribeUserProjects 获取项目列表 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| pageNumber | 否 | | 页码 | +| pageSize | 否 | | 每页数量 | +| projectName | 否 | | 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” | +| owned | 否 | | 0表示全部,1表示拥有者,2表示被共享者 | +| isAll | 否 | | | +| orderByCreatetime | 否 | | 按创建时间asc/desc排列 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ pageNumberinteger非必须页数

format: int64

├─ pageSizeinteger非必须页大小

format: int64

├─ projectsobject []非必须项目实体列表

item 类型: object

├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ descriptionstring非必须项目描述,新增
├─ instanceCountinteger非必须项目下实例数量

format: int64

├─ ownedinteger非必须此项目的共享标志位,1为拥有,2为共享

format: int64

├─ projectIdstring非必须项目uuid
├─ projectNamestring非必须项目名称
├─ shareProjectsobject []非必须共享

item 类型: object

├─ createdTimestring非必须创建时间
├─ ownerUserIdstring非必须项目拥有者用户id
├─ ownerUserNamestring非必须项目拥有者用户名
├─ projectIdstring非必须项目uuid
├─ projectNamestring非必须项目名称
├─ shareProjects []非必须
├─ 非必须
├─ sharedUserIdstring非必须项目共享者用户id
├─ sharedUserNamestring非必须项目拥有者用户名
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ totalCountinteger非必须总条数

format: int64

+ +## /user/projects + +### 基本信息 + +**Path:** /v1/user/projects + +**Method:** POST + +**接口描述:** +CreateUserProject 创建项目 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
isDefaultinteger非必须是否作为该用户的默认项目, [0/1], 默认为0

format: int8

isSysteminteger非必须是否作为系统项目, [0/1], 默认为0

format: int8

projectNamestring必须ProjectName 1~64字符,只支持数字、大小写字母、中英文下划线“_”及中划线“-”
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ projectIdstring非必须项目uuid
+ +## /user/projects/{project_id} + +### 基本信息 + +**Path:** /v1/user/projects/{project_id} + +**Method:** GET + +**接口描述:** +DescribeUserProject 获取项目详情 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| project_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ projectobject非必须
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ descriptionstring非必须项目描述,新增
├─ instanceCountinteger非必须项目下实例数量

format: int64

├─ ownedinteger非必须此项目的共享标志位,1为拥有,2为共享

format: int64

├─ projectIdstring非必须项目uuid
├─ projectNamestring非必须项目名称
├─ shareProjectsobject []非必须共享

item 类型: object

├─ createdTimestring非必须创建时间
├─ ownerUserIdstring非必须项目拥有者用户id
├─ ownerUserNamestring非必须项目拥有者用户名
├─ projectIdstring非必须项目uuid
├─ projectNamestring非必须项目名称
├─ shareProjects []非必须
├─ 非必须
├─ sharedUserIdstring非必须项目共享者用户id
├─ sharedUserNamestring非必须项目拥有者用户名
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
+ +## /user/projects/{project_id} + +### 基本信息 + +**Path:** /v1/user/projects/{project_id} + +**Method:** PUT + +**接口描述:** +ModifyUserProject 修改项目信息 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| project_id | | | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
projectNamestring必须项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-”
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /user/projects/{project_id} + +### 基本信息 + +**Path:** /v1/user/projects/{project_id} + +**Method:** DELETE + +**接口描述:** +DeleteUserProject 删除项目 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| project_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /user/projects/{project_id}/cancelShare + +### 基本信息 + +**Path:** /v1/user/projects/{project_id}/cancelShare + +**Method:** PUT + +**接口描述:** +CancelShareUserProject 取消共享项目 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| project_id | | | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
ownerIDstring必须from user_id
sharerIDstring必须to user_id
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /user/projects/{project_id}/describeSharProject + +### 基本信息 + +**Path:** /v1/user/projects/{project_id}/describeSharProject + +**Method:** GET + +**接口描述:** +DescribeShareUserProject 获取共享项目详情 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| project_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ projectIdstring非必须项目实体
├─ sharesobject []非必须

item 类型: object

├─ created_bystring非必须
├─ created_timeinteger非必须

format: int64

├─ deleted_timeinteger非必须

format: int64

├─ is_defaultinteger非必须

format: int8

├─ is_delinteger非必须

format: int8

├─ owner_user_idstring非必须
├─ owner_user_namestring非必须
├─ premissionstring非必须
├─ project_idstring非必须
├─ project_namestring非必须
├─ shared_user_idstring非必须
├─ shared_user_namestring非必须
├─ updated_bystring非必须
├─ updated_timeinteger非必须

format: int64

+ +## /user/projects/{project_id}/description + +### 基本信息 + +**Path:** /v1/user/projects/{project_id}/description + +**Method:** PUT + +**接口描述:** +ModifyUserProject 修改项目信息 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| project_id | | | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
descriptionstring必须项目描述
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /user/projects/{project_id}/share + +### 基本信息 + +**Path:** /v1/user/projects/{project_id}/share + +**Method:** PUT + +**接口描述:** +ShareUserProject 共享项目 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| project_id | | | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
ownerIDstring必须from user_id
sharerIDstring必须to user_id
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +# sshkey + +## /user/sshkeys + +### 基本信息 + +**Path:** /v1/user/sshkeys + +**Method:** GET + +**接口描述:** +DescribeUserSshKeys 获取个人sshkey列表 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Query** + +| 参数名称 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | +| pageNumber | 否 | | 页码 | +| pageSize | 否 | | 每页数量 | +| name | 否 | | 秘钥名称 | +| isAll | 否 | | 是否显示全部 | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ pageNumberinteger非必须页数

format: int64

├─ pageSizeinteger非必须页大小

format: int64

├─ sshkeysobject []非必须sshkey实体列表

item 类型: object

├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ fingerPrintstring非必须公钥指纹
├─ idinteger非必须id

format: int64

├─ keystring非必须公钥,格式:ssh-rsa AAA
├─ namestring非必须秘钥名称
├─ sshkeyIdstring非必须秘钥uuid
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ userIdstring非必须所属用户uuid
├─ totalCountinteger非必须总条数

format: int64

+ +## /user/sshkeys + +### 基本信息 + +**Path:** /v1/user/sshkeys + +**Method:** POST + +**接口描述:** +CreateUserSshkey 创建个人sshkey + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
keystring必须公钥内容,格式:^ssh-rsa AAAAB3NzaC1yc2.*
namestring必须秘钥名称
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ sshkeyIdstring非必须sshkey uuid
+ +## /user/sshkeys/instances/{sshkey_id} + +### 基本信息 + +**Path:** /v1/user/sshkeys/instances/{sshkey_id} + +**Method:** GET + +**接口描述:** +GetInstancesBySshkey 根据sshkey获取实例列表 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| sshkey_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ instanceIdsstring []非必须实例Id列表

item 类型: string

├─ 非必须
+ +## /user/sshkeys/{sshkey_id} + +### 基本信息 + +**Path:** /v1/user/sshkeys/{sshkey_id} + +**Method:** GET + +**接口描述:** +DescribeUserSshKey 获取sshkey详情 + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid, deprecated | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| sshkey_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ sshkeyobject非必须
├─ createdBystring非必须创建者
├─ createdTimestring非必须创建时间
├─ fingerPrintstring非必须公钥指纹
├─ idinteger非必须id

format: int64

├─ keystring非必须公钥,格式:ssh-rsa AAA
├─ namestring非必须秘钥名称
├─ sshkeyIdstring非必须秘钥uuid
├─ updatedBystring非必须更新者
├─ updatedTimestring非必须更新时间
├─ userIdstring非必须所属用户uuid
+ +## /user/sshkeys/{sshkey_id} + +### 基本信息 + +**Path:** /v1/user/sshkeys/{sshkey_id} + +**Method:** PUT + +**接口描述:** +ModifyUserSshkey 修改sshkey + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| sshkey_id | | | +**Body** + + + + + + + + +
名称类型是否必须默认值备注其他信息
namestring非必须秘钥名称
+ +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ +## /user/sshkeys/{sshkey_id} + +### 基本信息 + +**Path:** /v1/user/sshkeys/{sshkey_id} + +**Method:** DELETE + +**接口描述:** +DeleteUserSshkey 删除sshkey + +### 请求参数 +**Headers** + +| 参数名称 | 参数值 | 是否必须 | 示例 | 备注 | +| ------------ | ------------ | ------------ | ------------ | ------------ | +| Content-Type | application/json | 是 | | | +| traceId | | 是 | | 流量唯一id | +| authorization | | 是 | | demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token | +| bmpUserId | | 否 | | 用户uuid | +| bmpLanguage | | 否 | | 用户语言 [zh_CN, en_US] | +**路径参数** + +| 参数名称 | 示例 | 备注 | +| ------------ | ------------ | ------------ | +| sshkey_id | | | + +### 返回数据 + + + + + + + + +
名称类型是否必须默认值备注其他信息
resultobject非必须
├─ successboolean非必须操作是否成功 [true/false]
+ \ No newline at end of file diff --git a/bmp-openapi-console/bmp_vendor/bmp_log/README.md b/bmp-openapi-console/bmp_vendor/bmp_log/README.md new file mode 100644 index 0000000..f39a094 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/bmp_log/README.md @@ -0,0 +1,6 @@ +精简日志库,用于打点统计,监控,告警等场景 +- WARN,FATAL等等级的日志即时打印落盘 + - 一个流量可以打印多条WARN,FATAL日志 +- INFO,DEBUG等级的日志,一个流量只落一条日志 + - 支持字段顺序自定义,便于正则匹配做监控等场景 + - 支持自定义代码段耗时打印,便于后续性能统计分析 diff --git a/bmp-openapi-console/bmp_vendor/bmp_log/go.mod b/bmp-openapi-console/bmp_vendor/bmp_log/go.mod new file mode 100644 index 0000000..410b4d1 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/bmp_log/go.mod @@ -0,0 +1,3 @@ +module coding.jd.com/aidc-bmp/bmp_log + +go 1.17 diff --git a/bmp-openapi-console/bmp_vendor/bmp_log/log.go b/bmp-openapi-console/bmp_vendor/bmp_log/log.go new file mode 100644 index 0000000..6e5b79c --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/bmp_log/log.go @@ -0,0 +1,249 @@ +package cps_log + +import ( + "encoding/json" + "fmt" + "io" + "log" + "os" + "reflect" + "strings" + "time" +) + +// Level type +type Level uint32 + +const ( + // TraceLevel level. Designates finer-grained informational events than the Debug. + TraceLevel Level = iota + // DebugLevel level. Usually only enabled when debugging. Very verbose logging. + DebugLevel + // InfoLevel level. General operational entries about what's going on inside the + // application. + InfoLevel + // WarnLevel level. Non-critical entries that deserve eyes. + WarnLevel + // ErrorLevel level. Logs. Used for errors that should definitely be noted. + // Commonly used for hooks to send errors to an error tracking service. + ErrorLevel + // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the + // logging level is set to Panic. + FatalLevel + // PanicLevel level, highest level of severity. Logs and then calls panic with the + // message passed to Debug, Info, ... + PanicLevel +) + +var globalDefinedKeys = []string{"time", "logid", "self_t", "all_t"} + +type Logger struct { + data map[string]interface{} + level Level + fileName string + definedKeys []string +} + +func New(filename string) *Logger { + if filename == "" { + log.Fatal("filename must be provided !!!") + return nil + } + l := &Logger{ + data: make(map[string]interface{}), + fileName: filename, + } + l.definedKeys = append([]string{}, globalDefinedKeys...) + l.data["time"] = time.Now().Format("2006-01-02T15:04:05") + return l +} + +func NewLoggerWithConfig(filename string, level Level, definedKeys []string) *Logger { + l := New(filename) + l.SetLevel(level) + l.SetStableFields(definedKeys) + return l +} + +func (l *Logger) SetLevel(level Level) { + l.level = level +} + +//SetStableFields 需要固定每条日志的字段时,通过此接口设置,global在前,userdefined在后 +func (l *Logger) SetStableFields(fields []string) { + l.definedKeys = append(l.definedKeys, fields...) +} + +func (l *Logger) Point(key string, val interface{}) { + l.data[key] = val +} + +func (l *Logger) GetPoint(key string) interface{} { + return l.data[key] +} + +func (l *Logger) TimeStart(key string) { + if _, ok := l.data[key]; ok { + log.Print(fmt.Sprintf("point %s TimeStart more than once, check !!!", key)) + } + l.data[key] = time.Now() + +} + +func (l *Logger) TimeEnd(key string) { + if t, ok := l.data[key]; ok { + v := time.Now().Sub(t.(time.Time)).Milliseconds() + l.data[key] = fmt.Sprintf("%f", float64(v)/1000.0) + } else { + log.Print(fmt.Sprintf("missing call TimeStart before TimeEnd when point %s, check it!!!", key)) + } + +} + +func (l *Logger) PushPoint(key string, val interface{}) { + if _, ok := l.data[key]; !ok { + l.data[key] = []interface{}{} + } + d := l.data[key].([]interface{}) + d = append(d, val) +} + +func (l *Logger) Info(v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Infof(format string, v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warn(v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warnf(format string, v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatal(v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatalf(format string, v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Flush() { + if l.level > DebugLevel { + return + } + var beforeStr, afterStr string + for _, key := range l.definedKeys { + if val, ok := l.data[key]; ok { + if key == "time" { + beforeStr = val.(string) + continue + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + beforeStr = beforeStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + beforeStr = beforeStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + beforeStr = beforeStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Printf("val for %s unknown type!!!", key)) + + } + } + } + for key, val := range l.data { + if exist, _ := inArray(key, l.definedKeys); !exist { + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + afterStr = afterStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + afterStr = afterStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + afterStr = afterStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Sprintf("val for %s unknown type!!!", key)) + } + } + } + + line := strings.TrimSpace(beforeStr) + " " + strings.TrimSpace(afterStr) + "\r\n" + filename := fmt.Sprintf("%s.DEBUG", l.fileName) + WriteFile(filename, line) +} + +func WriteFile(filename, line string) { + TimeStamp := time.Now() + str := filename + "." + TimeStamp.Format("2006-01-02") + logf, err := os.OpenFile(str, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + if err != nil { + log.Fatal("open filename error:", err.Error()) + } + defer logf.Close() + if _, err := io.WriteString(logf, line); err != nil { + log.Fatal("write line error:", err.Error()) + } +} + +func inArray(val interface{}, array interface{}) (exists bool, index int) { + exists = false + index = -1 + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + index = i + exists = true + return + } + } + } + return +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/exception/exception.go b/bmp-openapi-console/bmp_vendor/ironic-common/exception/exception.go new file mode 100644 index 0000000..daf985f --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/exception/exception.go @@ -0,0 +1,24 @@ +package exception + +import ( + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +type Exception struct { + Status int `json:"code"` + ErrorCode string `json:"status"` + Msg string `json:"message"` +} + +var CommonParamValid = Exception{ + Status: httpStatus.BAD_REQUEST, + ErrorCode: errorCode.INVALID_ARGUMENT, + Msg: "param invalid", +} + +var InternalError = Exception{ + Status: httpStatus.INTERNAL_SERVER_ERROR, + ErrorCode: errorCode.INTERNAL, + Msg: "内部错误", +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/go.mod b/bmp-openapi-console/bmp_vendor/ironic-common/go.mod new file mode 100644 index 0000000..5364f89 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/go.mod @@ -0,0 +1,3 @@ +module git.jd.com/cps-golang/ironic-common + +go 1.17 diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/common/ErrorCode/ErrorCode.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/common/ErrorCode/ErrorCode.go new file mode 100644 index 0000000..68743e6 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/common/ErrorCode/ErrorCode.go @@ -0,0 +1,134 @@ +package ErrorCode + +const ( + // 此操作需要的预置条件不满足 400 + FAILED_PRECONDITION = "FAILED_PRECONDITION" + + // 参数错误 400 + INVALID_ARGUMENT = "INVALID_ARGUMENT" + + // 缺少参数 400 + MISSING_ARGUMENT = "MISSING_ARGUMENT" + + // 参数类型不匹配400 + MISMATCH_ARGUMENT_TYPE = "MISMATCH_ARGUMENT_TYPE" + + // 无效的action 400 + INVALID_ACTION = "INVALID_ACTION" + + // 参数超出范围 400 + OUT_OF_RANGE = "OUT_OF_RANGE" + + // 缺少Multipart 400 + MISSING_MULTIPART = "MISSING_MULTIPART" + + // 缺少header信息 400 + MISSING_HEADER = "MISSING_HEADER" + + // pathVariable参数错误 400 + INVALID_PATHVARIABLE = "INVALID_PATHVARIABLE" + + // 验证失败 401 + UNAUTHENTICATED = "UNAUTHENTICATED" + + // 用户未激活 402 + USER_NOT_ACTIVE = "USER_NOT_ACTIVE" + + // 没有权限 403 + HTTP_FORBIDDEN = "HTTP_FORBIDDEN" + + // 找不到对象 404 + NOT_FOUND = "NOT_FOUND" + + // 操作终止 409 + ABORTED = "ABORTED" + + // 对象已存在 409 + ALREADY_EXISTS = "ALREADY_EXISTS" + + // 媒体类型不支持 415 + UNSUPPORTED_MEDIA_TYPE = "UNSUPPORTED_MEDIA_TYPE" + + // 不支持的请求方法 405 + UNSUPPORTED_HTTP_REQUEST_METHOD = "UNSUPPORTED_HTTP_REQUEST_METHOD" + + // 配额不足 429 + QUOTA_EXCEEDED = "QUOTA_EXCEEDED" + + // 库存不足429 + STOCK_SHORTAGE = "STOCK_SHORTAGE" + + // 未知错误 500 + UNKNOWN = "UNKNOWN" + + // 内部错误 500 + INTERNAL = "INTERNAL" + + // 服务不可用 503 + UNAVAILABLE = "UNAVAILABLE" + + // 会话网关 Timeout 504 + SESSION_GATEWAY_TIMEOUT = "SESSION_GATEWAY_TIMEOUT" + + // 参数错误 + PARAMETER_ERROR = "PARAMETER_ERROR" + + //com.jcloud.cps.ironic.common.ErrorCode + UNSUPPORTED_OPERATION = "UNSUPPORTED_OPERATION" + + // 子网没有可用的内网IP可以分配 400 + EXHAUSTED_SUBNET = "EXHAUSTED_SUBNET" + + EXHAUSTED_PUBLIC_IP = "EXHAUSTED_PUBLIC_IP" + + UNSUPPORTED_RAID_TYPE = "UNSUPPORTED_RAID_TYPE" + + CHANGE_ARE_NOT_ALLOWED = "CHANGE_ARE_NOT_ALLOWED" + + // 权限校验失败 + NO_PERMISSION = "NO_PERMISSION" + + // 资源被占用 + RESOURCE_IN_USE = "RESOURCE_IN_USE" + + // 内网IP超出范围 + PRIVATE_IP_NOT_IN_SUBNET = "PRIVATE_IP_NOT_IN_SUBNET" + + // EIP已经绑定 + EIP_ALREADY_ASSOCIATE = "EIP_ALREADY_ASSOCIATE" + + // EIP未绑定 + EIP_HAS_NOT_ASSOCIATE = "EIP_HAS_NOT_ASSOCIATE" + + // 子网未开通IPv6 + SUBNET_HAS_NOT_ASSIGN_IPV6 = "SUBNET_HAS_NOT_ASSIGN_IPV6" + + // IPV6已经被分配 + IPV6_ALREADY_ASSIGN = "IPV6_ALREADY_ASSIGN" + + // 实例已经绑定EIP + INSTANCE_ALREADY_ASSOCIATE_EIP = "INSTANCE_ALREADY_ASSOCIATE_EIP" + + // 实例还没有绑定EIP + INSTANCE_HAS_NOT_ASSOCIATE_EIP = "INSTANCE_HAS_NOT_ASSOCIATE_EIP" + + // 实例已经绑定IPV6 + INSTANCE_ALREADY_ASSOCIATE_IPV6 = "INSTANCE_ALREADY_ASSOCIATE_IPV6" + + // 基础网路不支持EIP + UNSUPPORTED_EIP_IN_BASIC_NETWORK = "UNSUPPORTED_EIP_IN_BASIC_NETWORK" + + // VPC网络不支持调整带宽 + UNSUPPORTED_MODIFY_BANDWIDTH_IN_VPC_NETWORK = "UNSUPPORTED_MODIFY_BANDWIDTH_IN_VPC_NETWORK" + + // 不支持批量指定内网IP + UNSUPPORTED_BATCH_SPECIFYING_PRIVATE_IP = "UNSUPPORTED_BATCH_SPECIFYING_PRIVATE_IP" + + // 不支持批量指定别名IP + UNSUPPORTED_BATCH_SPECIFYING_ALIAS_IP = "UNSUPPORTED_BATCH_SPECIFYING_ALIAS_IP" + + // 密钥对正在被实例使用 + KEYPAIR_IS_USING_BY_INSTANCE = "KEYPAIR_IS_USING_BY_INSTANCE" + + ARGUMENT_ERROR = "ARGUMENT_ERROR" +) diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/common/NamespacePrefixs/NamespacePrefixs.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/common/NamespacePrefixs/NamespacePrefixs.go new file mode 100644 index 0000000..57aa84a --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/common/NamespacePrefixs/NamespacePrefixs.go @@ -0,0 +1,38 @@ +package NamespacePrefixs + +const ( + // api + INSTANCE_ID_PREFIX = "cps-" + + INSTANCE_ID_LENGTH = 28 + + // subnet + SUBNET_ID_PREFIX = "n-" + + SUBNET_ID_LENGTH = 28 + + // wan_subnet + WAN_SUBNET_ID_PREFIX = "wn-" + + WAN_SUBNET_LENGTH = 28 + + // raid + RAID_ID_PREFIX = "r-" + + RAID_ID_LENGTH = 28 + + // image + IMAGE_ID_PREFIX = "o-" + + IMAGE_ID_LENGTH = 28 + + // tenant + TENANT_ID_PREFIX = "t-" + + TENANT_ID_LENGTH = 28 + + // keypair + KEYPAIR_ID_PREFIX = "k-" + + KEYPAIR_ID_LENGTH = 28 +) diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/common/Validation/Validation.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/common/Validation/Validation.go new file mode 100644 index 0000000..9c6f3dc --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/common/Validation/Validation.go @@ -0,0 +1,16 @@ +package Validation + +const ( + REGEX_ID string = `^[a-zA-Z0-9-_]{2,36}$` + REGEX_RAID_VOLUME_TYPE string = `^system$|^data$` + REGEX_NETWORK_TYPE string = `^basic$|^vpc$|^retail$` + INTERFACE_MODE string = `^bond$|^dual$` + REGEX_IP_ADDRESS string = `(^127\.0\.0\.1)|(^192\.168)|(^10\.)|(^172\.1[6-9])|(^172\.2[0-9])|(^172\.3[0-1])` + REGEX_CIDR string = `(10|11|172|192)\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,3})` + REGEX_PASSWORD string = "^(?=.*[a-z])(?=.*[A-Z])(?=.*[\\d\\* \\(\\)`~!@#\\$%&_\\-+=\\|\\{\\}\\[\\]:\";\\'<>,.\\?\\/\\)])[a-zA-Z\\d\\* \\(\\)`~!@#\\$%&_\\-+=\\|\\{\\}\\[\\]:\";\\'<>,.\\?\\/\\)]{8,30}$" + REGEX_DEVICE_STATUS string = "^putawaying$|^creating$|^starting$|^running$|^stopping$|^stopped$|^restarting$|^error$|^upgrading$|^reinstalling$|^destroying$|^resetting_password$" + REGEX_RSA_PUBLIC_KEY string = "^ssh-rsa AAAAB3NzaC1yc2.*" + REGEX_MAIL_TYPE string = "^api_error$|^command_warning$" + REGEX_EMAIL string = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}" + REGEX_SOURCE_TYPE string = "^common$|^customize$|^user_defined$" +) diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/enums/AuditLogsType/AuditLogsType.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/enums/AuditLogsType/AuditLogsType.go new file mode 100644 index 0000000..7b44e06 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/enums/AuditLogsType/AuditLogsType.go @@ -0,0 +1,23 @@ +package AuditLogsType + +const ( + //操作消息类型 + + AuditLogsPutaway = "PutawayDevice" //上架 + AuditLogsUnPutaway = "UnPutawayDevice" //下架 + AuditLogsStartInstances = "StartInstances" //开机 + AuditLogsStopInstances = "StopInstances" //关机 + AuditLogsRestartInstances = "RestartInstances" //重启 + AuditLogsResetInstanceStatus = "ResetInstances" //重置实例状态(新增) + AuditLogsRemoveDevice = "RemoveDevice" //设备移除(新增) + AuditLogsDeleteDevice = "DeleteDevice" //设备删除(新增) + AuditLogsDeleteInstance = "DeleteInstance" //回收实例 + AuditLogsInstanceResetPassword = "InstanceResetPassword" //重置密码 + AuditLogsReinstallInstance = "ReinstallInstance" //重装系统 + AuditLogsEditInstanceName = "EditInstanceName" //编辑实例名称(新增) + AuditLogsCollectHardwareInfo = "CollectHardwareInfo" //设备采集 + AuditLogsTypeCreateInstances = "CreateInstances" //创建实例 + AuditLogsTypeDropInstances = "DropInstances" //删除实例(不走销毁流程,新增) + AuditLogsTypeLockInstances = "LockInstances" //锁定实例(新增) + +) diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/enums/HttpStatus/HttpStatus.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/enums/HttpStatus/HttpStatus.go new file mode 100644 index 0000000..243c37c --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/enums/HttpStatus/HttpStatus.go @@ -0,0 +1,66 @@ +package HttpStatus + +// refer https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpStatus.html +const ( + ACCEPTED = 202 //Accepted. + ALREADY_REPORTED = 208 //Already Reported. + BAD_GATEWAY = 502 //Bad Gateway. + BAD_REQUEST = 400 //Bad Request. + BANDWIDTH_LIMIT_EXCEEDED = 509 //Bandwidth Limit Exceeded + CHECKPOINT = 103 //Checkpoint. + CONFLICT = 409 //Conflict. + CONTINUE = 100 //Continue. + CREATED = 201 //Created. + EXPECTATION_FAILED = 417 //Expectation Failed. + FAILED_DEPENDENCY = 424 //Failed Dependency. + FORBIDDEN = 403 //Forbidden. + FOUND = 302 //Found. + GATEWAY_TIMEOUT = 504 //Gateway Timeout. + GONE = 410 //Gone. + HTTP_VERSION_NOT_SUPPORTED = 505 //HTTP Version Not Supported. + I_AM_A_TEAPOT = 418 //I'm a teapot. + IM_USED = 226 //IM Used. + INSUFFICIENT_STORAGE = 507 //Insufficient Storage + INTERNAL_SERVER_ERROR = 500 //Internal Server Error. + LENGTH_REQUIRED = 411 //Length Required. + LOCKED = 423 //Locked. + LOOP_DETECTED = 508 //Loop Detected + METHOD_NOT_ALLOWED = 405 //Method Not Allowed. + MOVED_PERMANENTLY = 301 //Moved Permanently. = MOVE//D_TEMPORARILY Deprecated in favor of FOUND which will be returned from HttpStatusvalueOf(302). + MULTI_STATUS = 207 //Multi-Status. + MULTIPLE_CHOICES = 300 //Multiple Choices. + NETWORK_AUTHENTICATION_REQUIRED = 511 //Network Authentication Required. + NO_CONTENT = 204 //No Content. + NON_AUTHORITATIVE_INFORMATION = 203 //Non-Authoritative Information. + NOT_ACCEPTABLE = 406 //Not Acceptable. + NOT_EXTENDED = 510 //Not Extended + NOT_FOUND = 404 //Not Found. + NOT_IMPLEMENTED = 501 //Not Implemented. + NOT_MODIFIED = 304 //Not Modified. + OK = 200 //OK. + PARTIAL_CONTENT = 206 //Partial Content. + PAYLOAD_TOO_LARGE = 413 //Payload Too Large. + PAYMENT_REQUIRED = 402 //Payment Required. + PERMANENT_REDIRECT = 308 //Permanent Redirect. + PRECONDITION_FAILED = 412 //Precondition failed. + PRECONDITION_REQUIRED = 428 //Precondition Required. + PROCESSING = 102 //Processing. + PROXY_AUTHENTICATION_REQUIRED = 407 //Proxy Authentication Required. + REQUEST_HEADER_FIELDS_TOO_LARGE = 431 //Request Header Fields Too Large. + REQUEST_TIMEOUT = 408 //Request Timeout. + REQUESTED_RANGE_NOT_SATISFIABLE = 416 //Requested Range Not Satisfiable. + RESET_CONTENT = 205 //Reset Content. + SEE_OTHER = 303 //See Other. + SERVICE_UNAVAILABLE = 503 //Service Unavailable. + SWITCHING_PROTOCOLS = 101 //Switching Protocols. + TEMPORARY_REDIRECT = 307 //Temporary Redirect. + TOO_EARLY = 425 //Too Early. + TOO_MANY_REQUESTS = 429 //Too Many Requests. + UNAUTHORIZED = 401 //Unauthorized. + UNAVAILABLE_FOR_LEGAL_REASONS = 451 //Unavailable For Legal Reasons. + UNPROCESSABLE_ENTITY = 422 //Unprocessable Entity. + UNSUPPORTED_MEDIA_TYPE = 415 //Unsupported Media Type. + UPGRADE_REQUIRED = 426 //Upgrade Required. + URI_TOO_LONG = 414 //URI Too Long USE_PROXY Deprecated due to security concerns regarding in-band configuration of a proxy + VARIANT_ALSO_NEGOTIATES = 506 //Variant Also Negotiates +) diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/enums/InstanceStatus/InstanceStatus.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/enums/InstanceStatus/InstanceStatus.go new file mode 100644 index 0000000..7703e00 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/enums/InstanceStatus/InstanceStatus.go @@ -0,0 +1,102 @@ +package InstanceStatus + +const ( + /** + * 创建中 + */ + CREATING = "creating" + + /** + * 开机中 + */ + STARTING = "starting" + + /** + * 运行 + */ + RUNNING = "running" + + /** + * 关机中 + */ + STOPPING = "stopping" + + /** + * 关机 + */ + STOPPED = "stopped" + + /** + * 重启中 + */ + RESTARTING = "restarting" + + /** + * 重置密码中 + */ + RESETTING_PASSWORD = "resetting_password" + + /** + * 销毁中 + */ + DESTROYING = "destroying" + + /** + * 已销毁 + */ + DESTROYED = "destroyed" + + /** + * 错误 + */ + ERROR = "error" + + /** + * 调整配置中 + */ + UPGRADING = "upgrading" + + /** + * 重装系统中 + */ + REINSTALLING = "reinstalling" + + // 创建失败 + CREATE_ERROR = "Creation failed" + // 开机失败 + START_ERROR = "Startup failed" + // 关机失败 + STOP_ERROR = "Shutdown failed" + // 重启失败 + RESTART_ERROR = "Reboot failed" + // 销毁失败 + DESTROY_ERROR = "Delete failed" + // 重装失败 + REINSTALL_ERROR = "Reinstall failed" + //重置密码失败 + RESETPASSWD_ERROR = "Resetpasswd failed" +) + +var Instance_To_Error_Status map[string]string = map[string]string{ + // "CollectHardwareInfo" : NewCollectHardwareInfoActor() + "CreateInstances": CREATE_ERROR, + // "CutDeviceStock" : NewCutDeviceStockActor() + "DeleteInstance": DESTROY_ERROR, + // "InstanceResetPassword" : NewInstanceResetPasswordActor() + // "ModifyBandwidth" : NewModifyBandwidthActor() + // "ReinstallInstance" : NewReinstallInstanceActor() + // "ResetSwitchConfig" : NewResetSwitchConfigActor() + // "RestartDhcp" : NewRestartDhcpActor() + "RestartInstances": RESTART_ERROR, + "StartInstances": START_ERROR, + "StopInstances": STOP_ERROR, + "ReinstallInstance": REINSTALL_ERROR, + "InstanceResetPassword": RESETPASSWD_ERROR, +} + +var Error_Instance_To_Reset_Status map[string]string = map[string]string{ + START_ERROR: STOPPED, + STOP_ERROR: RUNNING, + RESTART_ERROR: RUNNING, + DESTROY_ERROR: STOPPED, +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/enums/MessageType/MessageType.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/enums/MessageType/MessageType.go new file mode 100644 index 0000000..0b482b0 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/enums/MessageType/MessageType.go @@ -0,0 +1,57 @@ +package MessageType + +const ( + //操作消息 + MessageTypeOperation = "operation" + //系统消息 + MessageTypeSystem = "system" + //监控消息 + MessageTypeOobMonitor = "oob-monitor" + //带内告警 + MessageTypeInBondAlert = "inbond-alert" +) + +const ( + //操作消息类型 + MessageSubTypeCollectHardwareInfo = "CollectHardwareInfo" + MessageSubTypeCreateDevices = "CreateDevices" + MessageSubTypeCreateInstances = "CreateInstances" + MessageSubTypeCutDeviceStock = "CutDeviceStock" + MessageSubTypeDeleteInstance = "DeleteInstance" + MessageSubTypeInstanceResetPassword = "InstanceResetPassword" + MessageSubTypePutawayDevice = "PutawayDevice" + MessageSubTypeReinstallInstance = "ReinstallInstance" + MessageSubTypeRestartInstances = "RestartInstances" + MessageSubTypeStartInstances = "StartInstances" + MessageSubTypeStopInstances = "StopInstances" + //系统消息类型 + MessageSubTypeLicenseNearTimeout = "LicenseNearTimeout" + //带外监控消息类型 + MessageSubTypePowerFault = "电力故障" + MessageSubTypeTemperatureFault = "温控故障" + MessageSubTypeCPUFault = "CPU故障" + MessageSubTypeMemFault = "内存故障" + MessageSubTypeDiskFault = "硬盘故障" + MessageSubTypeOtherFault = "其他故障" + + //带内告警类型 + MessageSubTypeCPUUsage = "bmp.cpu.util" + MessageSubTypeMemoryUsage = "bmp.memory.util" + MessageSubTypeMemoryUsed = "bmp.memory.used" + MessageSubTypeDiskUsed = "bmp.disk.used" + MessageSubTypeDiskUsage = "bmp.disk.util" + MessageSubTypeDiskReadTraffic = "bmp.disk.bytes.read" + MessageSubTypeDiskWriteTraffic = "bmp.disk.bytes.write" + MessageSubTypeDiskReadIOPS = "bmp.disk.counts.read" + MessageSubTypeDiskWriteIOPS = "bmp.disk.counts.write" + MessageSubTypeNetworkIngressTraffic = "bmp.network.bytes.ingress" + MessageSubTypeNetworkEgressTraffic = "bmp.network.bytes.egress" + MessageSubTypeNetworkIngressPackets = "bmp.network.packets.ingress" + MessageSubTypeNetworkEgressPackets = "bmp.network.packets.egress" + MessageSubTypeLoadAverage1min = "bmp.avg.load1" + MessageSubTypeLoadAverage5min = "bmp.avg.load5" + MessageSubTypeLoadAverage15min = "bmp.avg.load15" + MessageSubTypeTotalTCPConnections = "bmp.tcp.connect.total" + MessageSubTypeEstablishedTCPConnections = "bmp.tcp.connect.established" + MessageSubTypeTotalProcessCount = "bmp.process.total" +) diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/AllocRetailPrivateIpMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/AllocRetailPrivateIpMessage.go new file mode 100644 index 0000000..6744995 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/AllocRetailPrivateIpMessage.go @@ -0,0 +1,9 @@ +package api + +type AllocRetailPrivateIpMessage struct { + ApiMessage +} + +func (c AllocRetailPrivateIpMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.AllocRetailPrivateIpMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/ApiMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/ApiMessage.go new file mode 100644 index 0000000..9062508 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/ApiMessage.go @@ -0,0 +1,9 @@ +package api + +type ApiMessage struct { + RequestId string `json:"request_id"` +} + +func (c ApiMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.ApiMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/CollectHardwareInfoMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/CollectHardwareInfoMessage.go new file mode 100644 index 0000000..9b90a5b --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/CollectHardwareInfoMessage.go @@ -0,0 +1,13 @@ +package api + +type CollectHardwareInfoMessage struct { + ApiMessage + Sns []string `json:"sns"` + //是否清空raid + AllowOverride bool `json:"allowOverride"` + NetworkType string `json:"network_type"` +} + +func (c CollectHardwareInfoMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.CollectHardwareInfoMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/CreateDevicesMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/CreateDevicesMessage.go new file mode 100644 index 0000000..1726211 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/CreateDevicesMessage.go @@ -0,0 +1,14 @@ +package api + +type CreateDevicesMessage struct { + ApiMessage + Action string `json:"action"` + Sn string `json:"sn"` + Subnet string `json:"subnet"` + SubnetMask string `json:"subnet_mask"` + Routes string `json:"routes"` +} + +func (c CreateDevicesMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.CreateDevicesMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/CreateInstancesMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/CreateInstancesMessage.go new file mode 100644 index 0000000..d763005 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/CreateInstancesMessage.go @@ -0,0 +1,14 @@ +package api + +type CreateInstancesMessage struct { + ApiMessage + InstanceIds []string `json:"instance_ids"` + Password string `json:"password"` + UserData string `json:"user_data"` + AliasIps interface{} `json:"alias_ips"` //本来是[]AliasIP,依赖太深,直接定义成interface{} + ExtensionAliasIps interface{} `json:"extension_alias_ips"` //本来是[]AliasIP,依赖太深,直接定义成interface{} +} + +func (c CreateInstancesMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.CreateInstancesMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/CutDeviceStockMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/CutDeviceStockMessage.go new file mode 100644 index 0000000..6b61fb3 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/CutDeviceStockMessage.go @@ -0,0 +1,10 @@ +package api + +type CutDeviceStockMessage struct { + ApiMessage + Sns []string `json:"sns"` +} + +func (c CutDeviceStockMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.CutDeviceStockMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/DeleteInstanceMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/DeleteInstanceMessage.go new file mode 100644 index 0000000..952471b --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/DeleteInstanceMessage.go @@ -0,0 +1,10 @@ +package api + +type DeleteInstanceMessage struct { + ApiMessage + InstanceId string `json:"instance_id"` +} + +func (c DeleteInstanceMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.DeleteInstanceMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/InstanceResetPasswordMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/InstanceResetPasswordMessage.go new file mode 100644 index 0000000..c8e2ea8 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/InstanceResetPasswordMessage.go @@ -0,0 +1,12 @@ +package api + +type InstanceResetPasswordMessage struct { + ApiMessage + InstanceId string `json:"instance_id"` + Password string `json:"password"` + Action string `json:"action"` +} + +func (c InstanceResetPasswordMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.InstanceResetPasswordMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/ModifyBandwidthMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/ModifyBandwidthMessage.go new file mode 100644 index 0000000..05b94ea --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/ModifyBandwidthMessage.go @@ -0,0 +1,12 @@ +package api + +type ModifyBandwidthMessage struct { + ApiMessage + InstanceId string `json:"instance_id"` + Bandwidth int32 `json:"bandwidth"` + InstanceStatus string `json:"instance_status"` +} + +func (c ModifyBandwidthMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.ModifyBandwidthMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/PutawayDeviceMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/PutawayDeviceMessage.go new file mode 100644 index 0000000..2856c7f --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/PutawayDeviceMessage.go @@ -0,0 +1,11 @@ +package api + +//设备上架 +type PutawayDeviceMessage struct { + ApiMessage + Sn string `json:"sn"` +} + +func (c PutawayDeviceMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.PutawayDeviceMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/ReinstallInstanceMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/ReinstallInstanceMessage.go new file mode 100644 index 0000000..1b81a3e --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/ReinstallInstanceMessage.go @@ -0,0 +1,13 @@ +package api + +type ReinstallInstanceMessage struct { + ApiMessage + InstanceId string `json:"instance_id"` + KeepData bool `json:"keep_data"` + Password string `json:"password"` + UserData string `json:"user_data"` +} + +func (c ReinstallInstanceMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.ReinstallInstanceMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/ResetSwitchConfigMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/ResetSwitchConfigMessage.go new file mode 100644 index 0000000..ceced55 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/ResetSwitchConfigMessage.go @@ -0,0 +1,10 @@ +package api + +type ResetSwitchConfigMessage struct { + ApiMessage + InstanceIds []string `json:"instance_ids"` +} + +func (c ResetSwitchConfigMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.ResetSwitchConfigMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/RestartDhcpMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/RestartDhcpMessage.go new file mode 100644 index 0000000..2c27222 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/RestartDhcpMessage.go @@ -0,0 +1,10 @@ +package api + +type RestartDhcpMessage struct { + ApiMessage + Az string `json:"az"` +} + +func (c RestartDhcpMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.RestartDhcpMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/RestartInstancesMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/RestartInstancesMessage.go new file mode 100644 index 0000000..058e73b --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/RestartInstancesMessage.go @@ -0,0 +1,10 @@ +package api + +type RestartInstancesMessage struct { + ApiMessage + InstanceIds []string `json:"instance_ids"` +} + +func (c RestartInstancesMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.RestartInstancesMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/SDNCallbackMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/SDNCallbackMessage.go new file mode 100644 index 0000000..2b54eb7 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/SDNCallbackMessage.go @@ -0,0 +1,15 @@ +package api + +type SDNCallbackMessage struct { + ApiMessage + InstanceId string `json:"instance_id"` + Sn string `json:"sn"` + Action string `json:"action"` + Status string `json:"status"` + Message string `json:"message"` + Data interface{} `json:"data"` +} + +func (c SDNCallbackMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.SDNCallbackMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/StartInstancesMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/StartInstancesMessage.go new file mode 100644 index 0000000..1ffdbde --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/StartInstancesMessage.go @@ -0,0 +1,10 @@ +package api + +type StartInstancesMessage struct { + ApiMessage + InstanceIds []string `json:"instance_ids"` +} + +func (c StartInstancesMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.StartInstancesMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/StopInstancesMessage.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/StopInstancesMessage.go new file mode 100644 index 0000000..254f477 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/api/StopInstancesMessage.go @@ -0,0 +1,10 @@ +package api + +type StopInstancesMessage struct { + ApiMessage + InstanceIds []string `json:"instance_ids"` +} + +func (c StopInstancesMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.StopInstancesMessage" +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/event.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/event.go new file mode 100644 index 0000000..6343216 --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/event/event.go @@ -0,0 +1,33 @@ +package event + +import ( + "time" + + "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +type Event struct { + EventUuid string `json:"event_uuid"` + ClazzName string `json:"clazz_name"` + Body string `json:"body"` + Time int64 `json:"time"` + UserID string `json:"user_id"` +} + +type CpsRabbitMsg interface { + ClazzName() string +} + +func NewEvent(msg CpsRabbitMsg, logid string, userId string) (*Event, error) { + b, err := util.Convert2String(msg) + if err != nil { + return nil, err + } + return &Event{ + EventUuid: logid, + ClazzName: msg.ClazzName(), + Body: string(b), + Time: time.Now().UnixNano() / 1e6, + UserID: userId, + }, nil +} diff --git a/bmp-openapi-console/bmp_vendor/ironic-common/ironic/util/util.go b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/util/util.go new file mode 100644 index 0000000..5aca77e --- /dev/null +++ b/bmp-openapi-console/bmp_vendor/ironic-common/ironic/util/util.go @@ -0,0 +1,77 @@ +package util + +import ( + "encoding/json" + "errors" + "fmt" + "math/rand" + "reflect" + "strconv" + "time" +) + +//GetRandString 借鉴RandomStringUtils.random包生成随机字符串 +// length 随机字符串的长度(不包括前缀) +// uletter 随机字符串是否包含大写字母字符 +// dletter 随机字符串是否包含小写字母字符 +// number 随机字符串是否包含数字字符 +func GetRandString(prefix string, length int32, uletter, dletter, number bool) string { + rand.Seed(time.Now().UnixNano()) + uletters := []rune("ABCDEFGHIGKLMNOPQRSTUVWXYZ") + dletters := []rune("abcdefghijklmnopqrstuvwxyz") + numbers := []rune("0123456789") + source := []rune{} + if uletter { + source = append(source, uletters...) + } + if dletter { + source = append(source, dletters...) + } + if number { + source = append(source, numbers...) + } + if len(source) == 0 { + return "atLeastContainsLetterOrNumber" + } + b := make([]rune, length) + for i := range b { + b[i] = source[rand.Intn(len(source))] + } + return prefix + string(b) +} + +// 跟现有环境一致,格式:aafc4d1b-f696-4ec2-924f-6fd012aa8345 +func GenerateRandUuid() string { + s := GetRandString("", 32, false, true, true) + runes := []rune(s) + return string(runes[0:8]) + "-" + string(runes[8:12]) + "-" + string(runes[12:16]) + "-" + string(runes[16:20]) + "-" + string(runes[20:32]) +} + +func Convert2String(val interface{}) (msg string, err error) { + + if val == nil{ + return "", nil + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool: + msg = strconv.FormatBool(val.(bool)) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + msg = fmt.Sprintf("%v", val) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + msg = fmt.Sprintf("%v", val) + case reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + msg = fmt.Sprintf("%v", val) + case reflect.String: + msg = val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + s, err := json.Marshal(val) + if err == nil { + msg = string(s) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + err = errors.New(fmt.Sprintf("type %s not support convert to string", reflect.TypeOf(val).String())) + default: + err = errors.New(fmt.Sprintf("type %s not support convert to string", reflect.TypeOf(val).String())) + } + return +} diff --git a/bmp-openapi-console/build.sh b/bmp-openapi-console/build.sh new file mode 100644 index 0000000..2ba4b0f --- /dev/null +++ b/bmp-openapi-console/build.sh @@ -0,0 +1,124 @@ +#!/bin/bash +############################################################################### +#编译脚本的原理是将编译结果放到output目录中,这个样例模版提供一个产生 +#一个最基本golang运行程序包的编译脚本,对于特殊的需求请酌情考虑 +# +#1、该脚本支持参数化,参数将传入build_package函数(内容为最终执行的编译命令) +# ,用$1,$2....表示,第1,2...个参数 +#2、部署需要启动程序,所以需要提供control文件放在当前目录中,用于启动和 +# 监控程序状态 + +###############用户修改部分################ +readonly PROJECT_NAME="cps-ironic-api" #项目名称,相对于$GOPATH/src文件夹所在的目录,可选项 +readonly PACKAGE_DIR_NAME=main.go #main文件相对于src文件夹所在的目录,可选项 +readonly PACKAGE_BIN_NAME=cps-ironic-api #定义产出的运行程序名,必填项 +readonly CONF_DIR_NAME="conf" #定义配置文件目录,此路径为相对路径,可选项 +readonly OTHERS_DIR_NAME="" #定义其它文件目录,多个目录以空格区分,此路径为相对路径,可选项 +#最终的抽包路径为$OUTPUT +########################################### + +if [[ "${PACKAGE_BIN_NAME}" == "" ]];then + echo "Please set "PACKAGE_BIN_NAME" value" + exit 1 +fi + +function set_work_dir +{ + readonly OUTPUT=$(pwd)/output + readonly WORKSPACE_DIR=$(pwd) +} + +#清理编译构建目录操作 +function clean_before_build +{ + cd ${WORKSPACE_DIR} + rm -rf bin pkg + rm -rf ${OUTPUT} +} + +#初始化编译环境 +function prepare_package() +{ + if [ ! -z "$PROJECT_NAME" ];then + mkdir -p src/$PROJECT_NAME + copy_files=`ls |grep -vw 'src'` + cp -rf $copy_files src/$PROJECT_NAME/ + fi +} + +#实际的编译命令 +#这个函数中可使用$1,$2...获取第1,2...个参数 +function build_package() +{ + cd ${WORKSPACE_DIR} + # export GOPATH=$(pwd) + go clean + echo $(pwd) + echo $(ls) + go build -v -gcflags="-N -l" -o ${PACKAGE_BIN_NAME} ${PACKAGE_DIR_NAME} || return 1 +} + +#建立最终发布的目录 +function build_dir +{ + mkdir -p ${OUTPUT}/bin || return 1 +} + +function dir_not_empty() +{ + if [[ ! -d $1 ]];then + return 1 + fi + if [[ $(ls $1|wc -l) -eq 0 ]];then + return 1 + fi + return 0 +} + +#拷贝编译结果到发布的目录 +function copy_result +{ + cd ${WORKSPACE_DIR} + cp -r ${PACKAGE_BIN_NAME} ${OUTPUT}/bin/ || return 1 + cp -r ./control ${OUTPUT}/bin || return 1 + dir_not_empty ${WORKSPACE_DIR}/${CONF_DIR_NAME} && mkdir -p ${OUTPUT}/${CONF_DIR_NAME} + cp -rf ./${CONF_DIR_NAME}/* ${OUTPUT}/${CONF_DIR_NAME}/ + test -z "$OTHERS_DIR_NAME" || cp -rf $OTHERS_DIR_NAME ${OUTPUT}/ + return 0 +} + +#执行 +function main() +{ + cd $(dirname $0) + set_work_dir + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Cleaning...' + clean_before_build || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Clean completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'preparng...' + prepare_package || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'prepare completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Building...' + build_package $@ || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Build completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Making dir...' + build_dir || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Make completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy result to publish dir...' + copy_result || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy completed' + echo + + exit 0 +} + +main $@ diff --git a/bmp-openapi-console/conf/app.conf b/bmp-openapi-console/conf/app.conf new file mode 100644 index 0000000..e69de29 diff --git a/bmp-openapi-console/conf/bmp-openapi-test.ini b/bmp-openapi-console/conf/bmp-openapi-test.ini new file mode 100644 index 0000000..825a5ca --- /dev/null +++ b/bmp-openapi-console/conf/bmp-openapi-test.ini @@ -0,0 +1,27 @@ +runmode = "test" +[test] + +httpport = 8802 +# mysql +bmp_db_host=${BMP_DB_HOST||10.226.192.72} +bmp_db_port=${BMP_DB_PORT||13306} +bmp_db_user=${BMP_DB_USER||bmp_rw} +bmp_db_password=${BMP_DB_PASSWORD||LE&oN$9wHB} +bmp_db_name=${BMP_DB_NAME||bmp} + +bmp_redis_host=${BMP_REDIS_HOST||10.226.192.72} +bmp_redis_port=${BMP_REDIS_PORT||16379} +bmp_redis_password=${BMP_REDIS_PASSWORD||LE&oN$9wHB} + + +# RabbitMQ for Ironic +bmp_mq_host=${BMP_MQ_HOST||10.226.192.72} +bmp_mq_port=${BMP_MQ_PORT||15672} +bmp_mq_user=${BMP_MQ_USER||bmp} +bmp_mq_password=${BMP_MQ_PASSWORD||LE&oN$9wHB} +bmp_mq_vhost=${BMP_MQ_VHOST||/bmp} +bmp_mq_exchange=CPS_IRONIC_SCHEDULER +bmp_mq_receive_routing_key=/test + + + diff --git a/bmp-openapi-console/conf/bmp-openapi.ini b/bmp-openapi-console/conf/bmp-openapi.ini new file mode 100644 index 0000000..1c44d00 --- /dev/null +++ b/bmp-openapi-console/conf/bmp-openapi.ini @@ -0,0 +1,47 @@ +appname = bmp-openapi-console +autorender = false +copyrequestbody = true +EnableDocs = true + + +httpport = 8802 +# mysql +jdbc.url= +bmp_db_host=${BMP_DB_HOST} +bmp_db_port=${BMP_DB_PORT} +bmp_db_user=${BMP_DB_USER} +bmp_db_password=${BMP_DB_PASSWORD} +bmp_db_name=${BMP_DB_NAME} + +bmp_redis_host=${BMP_REDIS_HOST} +bmp_redis_port=${BMP_REDIS_PORT} +bmp_redis_password=${BMP_REDIS_PASSWORD} + +bmp_image_host=${BMP_IMAGE_HOST||10.208.12.72} +bmp_image_port=${BMP_IMAGE_PORT||10000} + +bmp_monitor_proxy_host=${BMP_MONITOR_PROXY_HOST||10.208.12.72} +bmp_monitor_proxy_port=${BMP_MONITOR_PROXY_PORT||8805} + +bmp_pronoea_host=${BMP_PRONOEA_HOST||10.208.12.75} +bmp_pronoea_port=${BMP_PRONOEA_PORT||9999} + + +# RabbitMQ for Ironic +bmp_mq_host=${BMP_MQ_HOST} +bmp_mq_port=${BMP_MQ_PORT} +bmp_mq_user=${BMP_MQ_USER} +bmp_mq_password=${BMP_MQ_PASSWORD} +bmp_mq_vhost=${BMP_MQ_VHOST} +bmp_mq_exchange=CPS_IRONIC_SCHEDULER +bmp_mq_receive_routing_key=/test + +# log +log.level=DEBUG +log.max.history=10 +log.path=/var/log/bmp/bmp-openapi-console +# ipv6默认网关 +gateway6=2403:1EC0:8549:60C0::1 +#如果在本地环境测试,启用下面的文件,改成自己的本地环境配置 +; include "bmp-openapi-console-test.ini" + diff --git a/bmp-openapi-console/conf/license b/bmp-openapi-console/conf/license new file mode 100644 index 0000000..92a0395 --- /dev/null +++ b/bmp-openapi-console/conf/license @@ -0,0 +1 @@ ++gkxY4GeG+g8udxYBVicBjFYeeE/WGIrdkKhqUmaHgb8VoUAIAMjyK88AE3PvxbHHo34tZtBOFOigWJ4opvHpjDTLtYdmwD3/uopbzXJxYy2KuCjpJxJ/8fK0nVnVmD6bN7sO0cALVIMc+V4hHeiXs2aAxj61wVP+bd11Dkzl5o= \ No newline at end of file diff --git a/bmp-openapi-console/conf/machine_info b/bmp-openapi-console/conf/machine_info new file mode 100644 index 0000000..f18ff17 --- /dev/null +++ b/bmp-openapi-console/conf/machine_info @@ -0,0 +1,6 @@ +{ + "app_name": "bmp", + "app_version": "v1.1", + "machine_id": "your_machine_id", + "expire_date": "20230550" +} \ No newline at end of file diff --git a/bmp-openapi-console/constant/constant.go b/bmp-openapi-console/constant/constant.go new file mode 100644 index 0000000..739936d --- /dev/null +++ b/bmp-openapi-console/constant/constant.go @@ -0,0 +1,151 @@ +package constant + +import "fmt" + +var ( + OK RespMsg + INVALID_ARGUMENT RespMsg + INVALID_ARGUMENT_WITH_ARGS RespMsg + NO_LOGIN_PIN RespMsg + AUTH_NOT_LOGIN RespMsg + AUTH_BASIC_AUTH_ERROR RespMsg + AUTH_ERROR_FOR_AUTH_AND_USERID RespMsg + INVALID_ARGUMENT_OUT_OF_RANGE RespMsg + RATE_LIMIT RespMsg + INTERNAL_ERROR RespMsg + NOT_FOUND RespMsg + NOT_FOUND_WITH_ARGS RespMsg + CANCELLED RespMsg + CANCELLEDWithArgs RespMsg + PermissionDenyForObject RespMsg + NOT_SUPPORTED RespMsg +) + +type RespMsg struct { + Code int `json:"code"` + MessageEn string `json:"message_en"` + Messagech string `json:"message_ch"` + Status string `json:"status"` +} + +func init() { + OK = RespMsg{ + 200, + "OK", + "成功", + "OK", + } + INVALID_ARGUMENT = RespMsg{ + 400, + "Parameters error", + "参数错误", + "INVALID_ARGUMENT", + } + INVALID_ARGUMENT_WITH_ARGS = RespMsg{ + 400, + "%s", + "%s", + "INVALID_ARGUMENT", + } + AUTH_NOT_LOGIN = RespMsg{ + 400, + "Login Please", + "请先登录", + "AUTH_NOT_LOGIN", + } + AUTH_BASIC_AUTH_ERROR = RespMsg{ + 401, + "Unauthorized", + "认证失败或者权限错误", + "AUTH_ERROR_OR_PERMISSION_DENIED", + } + AUTH_ERROR_FOR_AUTH_AND_USERID = RespMsg{ + 401, + "Unauthorized", + "认证失败,auth和userid信息不一致", + "AUTH_ERROR_FOR_INVALID_AUTH_USERID", + } + RATE_LIMIT = RespMsg{ + 429, + "Requests are too frequent", + "请求过于频繁", + "RATE_LIMIT", + } + INTERNAL_ERROR = RespMsg{ + 500, + "Internal error", + "内部错误", + "INTERNAL", + } + NOT_FOUND = RespMsg{ + 404, + "Not found", + "找不到对象", + "NOT_FOUND", + } + NOT_FOUND_WITH_ARGS = RespMsg{ + 404, + "%s Not found", + "%s 找不到对象", + "NOT_FOUND", + } + CANCELLED = RespMsg{ + 400, + "Operation cancelled", + "取消操作", + "CANCELLED", + } + NOT_SUPPORTED = RespMsg{ + 400, + "Operation not allowed", + "不支持此操作", + "NOT ALLOWEDS", + } + CANCELLEDWithArgs = RespMsg{ + 400, + "%s", + "%s", + "CANCELLED", + } + PermissionDenyForObject = RespMsg{ + 401, + "permission denied", + "无操作权限", + "PERMISSION DENIED", + } +} + +func BuildNotFoundWithArgs(c, e string) RespMsg { + return RespMsg{ + 404, + fmt.Sprintf("%s Not found", e), + fmt.Sprintf("%s 找不到对象", c), + "NOT_FOUND", + } +} +func BuildCANCELLEDWithArgs(c, e string) RespMsg { + return RespMsg{ + 400, + e, + c, + "CANCEL", + } +} + +func BuildInvalidArgumentWithArgs(c, e string) RespMsg { + return RespMsg{ + 400, + e, + c, + "INVALID_ARGUMENT", + } +} + +func BuildAuthTokenAuthError(c, e string) RespMsg { + return RespMsg{ + 401, + e, + c, + "AUTH_TOKEN_AUTH_ERROR", + } +} diff --git a/bmp-openapi-console/control b/bmp-openapi-console/control new file mode 100644 index 0000000..d7d8eaa --- /dev/null +++ b/bmp-openapi-console/control @@ -0,0 +1,125 @@ +#!/bin/bash +set -x +cd "$(dirname $0)"/.. +BASE_DIR=`pwd` +if [ -f default_env.sh ];then + source default_env.sh +fi + +PROC_NAME=cps-ironic-api # 进程名 一般就是二进制的名字java类程序一般就是java +PROC_PORT=8808 # 程序占用的端口,建议写,程序不占用端口的话只用ps来判断进程是否启动,机器上有同名程序是可能有问题 +WAIT_TIME=60 # 执行START_COMMAND后到程序能完全启动listen端口需要花的时间 + +USER=nginx +app_dir=/home/$USER/$PROC_NAME +mkdir -p $app_dir/log + +START_COMMAND="$app_dir/bin/cps-ironic-api -c $app_dir/conf/ironic-api.ini" #在output目录下启动你程序的命令 + +help(){ + echo "${0} " + exit 1 +} + +checkhealth(){ + if [[ -n "$PROC_PORT" ]] ; then + PORT_PROC=$(/usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d |awk '{print $NF}' |grep -oP '".*"' |sed "s/\"//g" |uniq) + if [ X"$PORT_PROC" = X"$PROC_NAME" ] ; then + echo "1 running" + return 0 + fi + echo "1 not running" + return 1 + else + ps -eo comm,pid |grep -P "^$PROC_NAME" + if [ "$?" = 0 ] ; then + echo "2 running" + return 0 + fi + echo "2 not running" + return 1 + fi +} + + +start(){ + checkhealth + if [ $? = 0 ]; then + echo "[WARN] $PROC_NAME is aleady running!" + return 0 + fi + + [ -d "$app_dir" ] && cd $app_dir && rm -rf `ls ${app_dir} | grep -v log` + cp -r $BASE_DIR/* ${app_dir}/ + chown -R $USER:$USER ${app_dir} + su $USER -c "nohup $START_COMMAND > ${app_dir}/log/cps-ironic-api.log 2>&1 &" + + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ $? = 0 ]; then + echo "Start $PROC_NAME success" + return 0 + fi + done + echo "[ERROR] Start $PROC_NAME failed" + return 1 +} + +stop(){ + if [[ -n "$PROC_PORT" ]] ; then + PROC_ID=$( /usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d | awk '{print $NF}' | grep -oP ',.*,' | grep -oP "\d+" | uniq ) + else + PROC_ID=$(ps -eo comm,pid | grep "^$PROC_NAME" |awk '{print $2}') + fi + + if [[ -z "$PROC_ID" ]] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + + checkhealth + if [ "$?" != "0" ] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + kill $PROC_ID + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + done + + kill -9 $PROC_ID + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + + echo "[ERROR] Stop $PROC_NAME failed" + return 1 +} + +case "${1}" in + start) + start + ;; + stop) + stop + ;; + status|health|checkhealth) + checkhealth + ;; + restart) + stop && start + ;; + *) + help + ;; +esac + diff --git a/bmp-openapi-console/controllers/apikeyController.go b/bmp-openapi-console/controllers/apikeyController.go new file mode 100644 index 0000000..dae2535 --- /dev/null +++ b/bmp-openapi-console/controllers/apikeyController.go @@ -0,0 +1,151 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/apikeyLogic" + + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type ApikeyController struct { + BaseController +} + +// CreateAPIkey ... +// swagger:route POST /user/apikeys apiKey createUserApikey +// +// CreateUserApikey 创建apikey +// +// Responses: +// 200: createUserApikey +// default: ErrorResponse + +func (c *ApikeyController) CreateUserApikey() { + defer c.CatchException() + req := &requestTypes.CreateApikeyRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateAPIkey parse pAPIkeyt body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + uuid, err := apikeyLogic.CreateApikey(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ApikeyId{ + ApikeyId: uuid, + } +} + +// QueryByAPIkeyIds ... +// swagger:route GET /user/apikeys apiKey describeUserAPIKeys +// +// DescribeUserAPIKeys 获取APIKey列表 +// +// Responses: +// 200: describeUserAPIKeys +// default: ErrorResponse +func (c *ApikeyController) DescribeUserAPIKeys() { + defer c.CatchException() + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.QueryApikeysRequest{ + Name: c.GetString("name"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + res, count, err := apikeyLogic.GetApikeyList(c.logPoints, *req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ApikeyList{ + Apikeys: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } + +} + +// DescribeUserAPIKey ... +// swagger:route GET /user/apikeys/{apikey_id} apiKey describeUserAPIKey +// +// DescribeUserAPIKey 获取apikey详情 +// +// Responses: +// 200: describeUserAPIKey +// default: ErrorResponse +func (c *ApikeyController) DescribeUserAPIKey() { + defer c.CatchException() + apikeyId := c.Ctx.Input.Param(":apikey_id") + res, err := apikeyLogic.GetApikeyById(c.logPoints, apikeyId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + c.Res.Result = response.ApikeyInfo{ + Apikey: res, + } +} + +// ModifyAPIkey ... +// swagger:route PUT /user/apikeys/{apikey_id} apiKey modifyUserApikey +// +// ModifyUserApikey 修改apikey(暂不启用) +// +// Responses: +// 200: modifyUserApikey +// default: ErrorResponse + +func (c *ApikeyController) ModifyUserApikey() { + defer c.CatchException() + apikeyId := c.Ctx.Input.Param(":apikey_id") + req := &requestTypes.ModifyApikeyRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyAPIkey parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := apikeyLogic.ModifyApikey(c.logPoints, req, apikeyId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// DeleteAPIkey ... +// swagger:route DELETE /user/apikeys/{apikey_id} apiKey deleteUserApikey +// +// DeleteUserApikey 删除某个apikey +// +// Responses: +// 200: deleteUserApikey +// default: ErrorResponse + +func (c *ApikeyController) DeleteUserApikey() { + defer c.CatchException() + apikeyId := c.Ctx.Input.Param(":apikey_id") + if err := apikeyLogic.DeleteApikey(c.logPoints, apikeyId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} diff --git a/bmp-openapi-console/controllers/auditLogsController.go b/bmp-openapi-console/controllers/auditLogsController.go new file mode 100644 index 0000000..642d5c4 --- /dev/null +++ b/bmp-openapi-console/controllers/auditLogsController.go @@ -0,0 +1,69 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/logic/auditLogLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// AuditLogsController operations for auditlog +type AuditLogsController struct { + BaseController +} + +// swagger:route GET /auditLogs auditLog describeAuditLogs +// DescribeAuditLogs 获取审计日志列表 +// Responses: +// 200: describeAuditLogs +// default: ErrorResponse + +func (c *AuditLogsController) DescribeAuditLogs() { + defer c.CatchException() + req := &requestTypes.DescribeAuditLogsRequest{ + InstanceID: c.GetString("instance_id"), + Operation: c.GetString("operation"), + UserName: c.GetString("username"), + IsAll: c.GetString("isAll"), + Result: c.GetString("result"), + } + st, _ := c.GetInt("startTime") + et, _ := c.GetInt("endTime") + req.StartTime = st + req.EndTime = et + + req.Validate(c.logPoints) + + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + //device_types, err := deviceTypeLogic.QueryByRequest(c.logPoints, req) + res, count, err := auditLogLogic.QueryAuditLogs(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.AuditLogList{ + AuditLogs: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } +} + +// swagger:route GET /auditLogs/types auditLog describeAuditLogTypes +// DescribeAuditLogTypes 获取审计日志类型 +// Responses: +// 200: describeAuditLogTypes +// default: ErrorResponse + +func (c *AuditLogsController) DescribeAuditLogTypes() { + + //device_types, err := deviceTypeLogic.QueryByRequest(c.logPoints, req) + res := auditLogLogic.DescribeAuditLogsTypes(c.logPoints) + + c.Res.Result = res +} diff --git a/bmp-openapi-console/controllers/baseController.go b/bmp-openapi-console/controllers/baseController.go new file mode 100644 index 0000000..6c9c5b1 --- /dev/null +++ b/bmp-openapi-console/controllers/baseController.go @@ -0,0 +1,480 @@ +package controllers + +import ( + "encoding/json" + "fmt" + "reflect" + "runtime" + "strconv" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/apikeyLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/userLogic" + + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" + + util "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + "github.com/beego/beego/v2/server/web" +) + +type ErrorResponse struct { + // 错误码 + Code int `json:"code"` + // 错误信息 + Message string `json:"message"` + // 错误状态 + Status string `json:"status"` +} + +type Response struct { + // 操作失败结果。成功时有此结构 + Result interface{} `json:"result,omitempty"` + // 操作失败结果。失败时有此结构 + Error *ErrorResponse `json:"error,omitempty"` + // 请求traceId + // required: true + RequestId string `json:"requestId"` +} + +// SubnetController operations for Subnet +type BaseController struct { + web.Controller + logPoints *log.Logger + Res Response + pageable util.Pageable +} + +func (b *BaseController) SetErrorResponse(code int, message, status string) { + b.Res.Error = &ErrorResponse{ + Code: code, + Message: message, + Status: status, + } +} + +func (b *BaseController) Prepare() { + + web.ReadFromRequest(&b.Controller) + logPath, _ := web.AppConfig.String("log.path") + b.logPoints = log.New(logPath + "/bmp-openapi.log") + b.logPoints.SetStableFields([]string{"method", "uri", "header", "request", "response"}) + b.logPoints.Point("uri", b.Ctx.Request.RequestURI) + b.logPoints.Point("method", b.Ctx.Request.Method) + b.logPoints.Point("header", b.Ctx.Request.Header) + b.logPoints.Point("language", b.GetLanguage()) + b.logPoints.Point("timezone", b.GetTimezone()) + + b.logPoints.Point("request", string(b.Ctx.Input.RequestBody)) + b.logPoints.TimeStart("all_t") + b.logPoints.TimeStart("self_t") + traceId := b.GetTraceID() + + b.logPoints.Point("logid", traceId) + b.Ctx.Output.Header("TraceId", traceId) + b.Res = Response{} + + //鉴定用户/系统apikey,补全流量的用户信息,操作权限 + if !strings.HasPrefix(b.Ctx.Input.URI(), "/v1/users/verify") && !strings.HasPrefix(b.Ctx.Input.URI(), "/v1/users/getUserByName") && !strings.HasPrefix(b.Ctx.Input.URI(), "/commands/retryCommand") && !strings.HasPrefix(b.Ctx.Input.URI(), "/v1/collect/collectDeviceInfo") && !strings.HasPrefix(b.Ctx.Input.URI(), "/v1/license") && !strings.HasPrefix(b.Ctx.Input.URI(), "/v1/offline") { + + err := b.ValidateAuth() + if err != nil { + b.logPoints.Warn("ValidateAuth error:", err.Messagech) + b.Res.Error = &ErrorResponse{ + Code: err.Code, + Message: err.Messagech, + Status: err.Status, + } + if b.logPoints.GetPoint("language").(string) == baseLogic.EN_US { + b.Res.Error.Message = err.MessageEn + } + + b.Res.RequestId = traceId + b.Data["json"] = b.Res + if b.Res.Error != nil { + b.Ctx.Output.Status = b.Res.Error.Code + } + b.ServeJSON() + return + } + + } + + b.pageable = util.Pageable{ + PageNumber: b.getPageNumber(), + PageSize: b.getPageSize(), + } + b.logPoints.Info("url:", b.Ctx.Request.URL) + b.logPoints.Info("body:", string(b.Ctx.Input.RequestBody)) + fmt.Println("[DEBUG MINPING]url:", b.Ctx.Request.URL) + fmt.Println("[DEBUG MINPING]method", b.Ctx.Request.Method) + fmt.Println("[DEBUG MINPING]header", b.Ctx.Request.Header) + fmt.Println("[DEBUG MINPING]body:", string(b.Ctx.Input.RequestBody)) + fmt.Println("[DEBUG MINPING]all header", b.GetAllHeader()) +} + +func (b *BaseController) Finish() { + b.Res.RequestId = b.GetTraceID() + b.Data["json"] = b.Res + + if b.Res.Error != nil { + b.Ctx.Output.Status = b.Res.Error.Code + } + b.ServeJSON() + + b.logPoints.TimeEnd("self_t") + b.logPoints.TimeEnd("all_t") + b.logPoints.Point("response", b.Data["json"]) + + v, _ := json.Marshal(b.Data["json"]) + b.logPoints.Info("response:", string(v)) + fmt.Println("[DEBUG MINPING]response:", string(v)) + + b.logPoints.Flush() +} + +func (b *BaseController) GetString(key string) string { + return b.Controller.GetString(key, "") +} + +// getCurrentGoroutineStack 获取当前Goroutine的调用栈,便于排查panic异常 +func getCurrentGoroutineStack() string { + + const defaultStackSize = 4096 + + var buf [defaultStackSize]byte + n := runtime.Stack(buf[:], false) + return string(buf[:n]) +} + +//业务代码可以直接panic终止运行 +func (b *BaseController) CatchException() { + // if r := recover(); r != nil { + // // t := make([]byte, 1<<16) + // // runtime.Stack(t, true) + // t, _ := json.Marshal(r) + // b.logPoints.Warn(string(t)) + // if reflect.TypeOf(r).String() == "exception.Exception" { + // b.Res["result"] = r + // } else { //非预期panic输出统一化 + // b.Res["result"] = exception.InternalError + // } + // } + if r := recover(); r != nil { + b.logPoints.Warnf("BaseController.CatchException catch exception, error:%v, stack:%s", r, getCurrentGoroutineStack()) + //b.Res["result"] = int(reflect.ValueOf(r).Field(0).Int()) + //if reflect.ValueOf(r).Field(1).String() == "" { //重要返回,如果errno不写,那么默认的errno和msg在这里设置 + // b.Res["error"] = 40000 + // b.Res["m"] = reflect.ValueOf(r).Field(2).String() + // return + //} + //errno, err := strconv.Atoi(reflect.ValueOf(r).Field(1).String()) //如果errno不写 + //if err != nil { //字符串转整形失败 + // b.Res["errno"] = 40001 + // b.Res["errmsg"] = reflect.ValueOf(r).Field(2).String() + // return + //} + var ( + code int + chMessage string + enMessage string + status string + ) + if reflect.ValueOf(r).Field(0).Int() == 0 { + code = httpStatus.BAD_REQUEST //默认httpcode 400 + } else { + code = int(reflect.ValueOf(r).Field(0).Int()) + } + //en_message + if reflect.ValueOf(r).Field(1).String() == "" { + enMessage = errorCode.INVALID_ARGUMENT //参数错误 + } else { + enMessage = reflect.ValueOf(r).Field(1).String() + } + + //ch_message + if reflect.ValueOf(r).Field(2).String() == "" { + chMessage = errorCode.INVALID_ARGUMENT //参数错误 + } else { + chMessage = reflect.ValueOf(r).Field(2).String() + } + + //status + if reflect.ValueOf(r).Field(3).String() == "" { + status = errorCode.INVALID_ARGUMENT //参数错误 + } else { + status = reflect.ValueOf(r).Field(3).String() //具体的报错信息err.error() + } + fmt.Println("recover info:", code, chMessage, enMessage, status) + if b.logPoints.GetPoint("language").(string) == baseLogic.EN_US { + b.SetErrorResponse(code, enMessage, status) + } else { + b.SetErrorResponse(code, chMessage, status) + } + + } +} + +func (b *BaseController) GetAllHeader() string { + v, _ := json.Marshal(b.Ctx.Request.Header) + return string(v) +} + +func (b *BaseController) ValidateAuth() *constant.RespMsg { + + auth := "" + if b.Ctx.Request.Header["Authorization"] != nil { + auth = b.Ctx.Request.Header["Authorization"][0] + } + items := strings.Split(auth, "Bearer ") + if len(items) != 2 { + b.logPoints.Warnf("ValidateAuth.token type invalided, token:%s", auth) + err := constant.AUTH_BASIC_AUTH_ERROR + return &err + } + token := items[1] + apiKeyEntity, err := apikeyLogic.ValidateApiKey(b.logPoints, token) + if err != nil { + b.logPoints.Warnf("ValidateAuth.ValidateApiKey error, auth:%s, error:%s", auth, err.Error()) + err := constant.AUTH_BASIC_AUTH_ERROR + return &err + } + if apiKeyEntity == nil { + b.logPoints.Warnf("ValidateAuth.apiKeyEntity empty,auth:%s", auth) + err := constant.AUTH_BASIC_AUTH_ERROR + return &err + } + + // 只读的apikey不允许做非get操作 + if apiKeyEntity.ReadOnly == 1 && b.logPoints.GetPoint("method").(string) != "GET" { + b.logPoints.Warn("readonly apikey try do modify operation", token, b.Ctx.Input.Method(), b.Ctx.Input.URI()) + err := constant.PermissionDenyForObject + return &err + } + + //如果是个人apikey,可以不传userId + var userId string + if apiKeyEntity.Type == "user" { + b.logPoints.Point("traffic_source", "api") + if apiKeyEntity.UserID != b.GetUserId() { + b.logPoints.Warn("userid in auth and header not match") + // err := constant.AUTH_ERROR_FOR_AUTH_AND_USERID + // return &err + } + userId = apiKeyEntity.UserID + } else if apiKeyEntity.Type == "alert" { //监控告警系统上报过来的数据 + b.logPoints.Point("traffic_source", "alert-api") + if b.Ctx.Input.URI() == "/v1/monitorAlert/addAlert" { + return nil //由业务侧补用户信息 + } else { + err := constant.NOT_SUPPORTED + return &err + } + } else { //系统apikey时,userId必须要经header传过来 + b.logPoints.Point("traffic_source", "web") + userId = b.GetUserId() + } + if userId == "" { + err := constant.AUTH_NOT_LOGIN + return &err + } + u, err := userLogic.GetUserById(b.logPoints, userId) + if err != nil { + b.logPoints.Warn("apikey for user invalid", err.Error()) + err := constant.AUTH_NOT_LOGIN + return &err + } + + if apiKeyEntity.Type == "user" && apiKeyEntity.Source != "console" { + //个人apikey且不是在console上创建的 + err := constant.PermissionDenyForObject + return &err + } + + //接口请求的控制台用户,镜像,机型等接口的写权限禁用 + if apiKeyEntity.Type == "user" && u.RoleID == baseLogic.ROLE_USER_UUID && b.logPoints.GetPoint("method").(string) != "GET" { + forbidUrl := []string{ + "/v1/devices", + "/v1/deviceTypes", + "v1/idcs", + "/v1/oss", + "/v1/images", + "/v1/raids", + "/v1/users", + "/v1/roles", + } + for _, pre := range forbidUrl { + if strings.HasPrefix(b.Ctx.Input.URI(), pre) { + b.logPoints.Warnf("api user request permission denied, userId:%s, url:%s", u.UserID, b.Ctx.Input.URI()) + err := constant.PermissionDenyForObject + return &err + } + } + } + + // 非amdin无运营平台role和users的权限 + if u.RoleID != baseLogic.ROLE_ADMIN_UUID { + if strings.HasPrefix(b.Ctx.Input.URI(), "/v1/roles") && b.logPoints.GetPoint("method").(string) != "GET" { + if !strings.HasPrefix(b.Ctx.Input.URI(), "/v1/roles/roleInfo/current") { + b.logPoints.Warn("role method for non-admin user invalid, userId:", u.UserID) + err := constant.PermissionDenyForObject + return &err + } + + } + + if strings.HasPrefix(b.Ctx.Input.URI(), "/v1/users") && b.logPoints.GetPoint("method").(string) != "GET" { + b.logPoints.Warn("role method for non-admin user invalid, userId:", u.UserID) + err := constant.PermissionDenyForObject + return &err + } + } + + fmt.Println("baseauth.username is", u.UserName) + fmt.Println("baseauth.user_id is", userId) + fmt.Println("baseauth.timezone is", u.Timezone) + fmt.Println("baseauth.language is", u.Language) + fmt.Println("language-header", b.logPoints.GetPoint("language").(string)) + b.logPoints.Point("userId", userId) + b.logPoints.Point("username", u.UserName) + b.logPoints.Point("userRole", u.RoleID) + if b.logPoints.GetPoint("language").(string) == "" { //页面上没有设置语言时,用用户的默认语言 + b.logPoints.Point("language", u.Language) + } + fmt.Println("language-final", b.logPoints.GetPoint("language").(string)) + b.logPoints.Point("timezone", u.Timezone) + + return nil +} + +func (b *BaseController) GetTraceID() string { + if b.Ctx.Request.Header["Traceid"] != nil { + return b.Ctx.Request.Header["Traceid"][0] + } + //生成随机字符串logid + logid := commonUtil.GenerateRandUuid() + b.Ctx.Request.Header["Traceid"] = []string{logid} + return logid +} + +func (b *BaseController) GetLanguage() string { + if b.Ctx.Request.Header["Bmplanguage"] != nil { + language := b.Ctx.Request.Header["Bmplanguage"][0] + return language + } + return "" +} + +func (b *BaseController) GetTimezone() string { + if b.Ctx.Request.Header["X-Bmp-Timezone"] != nil { + tz := b.Ctx.Request.Header["X-Bmp-Timezone"][0] + return tz + } + return "Asia/Shanghai" +} + +func (b *BaseController) GetUserId() string { + if b.Ctx.Request.Header["Bmpuserid"] != nil { + userId := b.Ctx.Request.Header["Bmpuserid"][0] + return userId + } + return "" +} +func (b *BaseController) GetUserName() string { + user, _ := userLogic.GetUserById(b.logPoints, b.GetUserId()) //报错 + if user != nil { + return user.UserName + } else { + return "" + } +} +func (b *BaseController) GetFields() (fields []string) { + // fields: col1,col2,entity.col3 + if v := b.GetString("fields"); v != "" { + fields = strings.Split(v, ",") + } + return +} + +func (b *BaseController) GetSortBy() (sortby []string) { + // sortby: col1,col2 + if v := b.GetString("sortby"); v != "" { + sortby = strings.Split(v, ",") + } + return +} + +func (b *BaseController) GetOrder() (order []string) { + // order: desc,asc + if v := b.GetString("order"); v != "" { + order = strings.Split(v, ",") + } + return +} + +// GetOffset 默认返回0 +func (b *BaseController) GetOffset() int64 { + if o := b.GetString("pageNumber"); o != "" { + if v, err := strconv.ParseInt(o, 10, 64); err == nil { + //第2页 每页10条 offset=10 + //第1页, 每页10条,offset=0 + if v > 0 { + return (v - 1) * b.GetLimit() + } + } + } + return 0 +} + +// GetOffset 默认返回10 +func (b *BaseController) GetLimit() int64 { + if l := b.GetString("pageSize"); l != "" { + if v, err := strconv.ParseInt(l, 10, 64); err == nil { + return v + } + } + return 20 +} + +func (b *BaseController) getPageNumber() int64 { + if l := b.GetString("pageNumber"); l != "" { + if v, err := strconv.ParseInt(l, 10, 64); err == nil { + return v + } + } + return 1 +} + +func (b *BaseController) getPageSize() int64 { + if l := b.GetString("pageSize"); l != "" { + if v, err := strconv.ParseInt(l, 10, 64); err == nil { + return v + } + } + if strings.HasPrefix(b.Ctx.Request.RequestURI, "/devices") { + return 10 + } + if strings.HasPrefix(b.Ctx.Request.RequestURI, "/instances") { + return 10 + } + if strings.HasPrefix(b.Ctx.Request.RequestURI, "/subnets") { + return 10 + } + return 20 +} + +func restfulResponseException(code int, status string, msg string) map[string]interface{} { + return map[string]interface{}{ + "error": map[string]interface{}{ + "code": code, + "status": status, + "message": msg, + }, + } +} diff --git a/bmp-openapi-console/controllers/deviceController.go b/bmp-openapi-console/controllers/deviceController.go new file mode 100644 index 0000000..657039f --- /dev/null +++ b/bmp-openapi-console/controllers/deviceController.go @@ -0,0 +1,94 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/deviceLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceController operations for Device +type DeviceController struct { + BaseController +} + +// swagger:route GET /devices device describeDevices +// +// DescribeDevices 获取设备列表 +// +// Responses: +// 200: describeDevices +// default: ErrorResponse + +func (c *DeviceController) DescribeDevices() { + defer c.CatchException() + param := requestTypes.QueryDevicesRequest{ + IDcID: c.GetString("idcId"), + Sn: c.GetString("sn"), + DeviceSeries: c.GetString("deviceSeries"), + DeviceTypeID: c.GetString("deviceTypeId"), + ManageStatus: c.GetString("manageStatus"), + + IloIP: c.GetString("iloIp"), + InstanceID: c.GetString("instanceId"), + UserID: c.GetString("user_id"), + UserName: c.GetString("userName"), + IsAll: c.GetString("isAll"), + } + + res, count, err := deviceLogic.QueryDevices(c.logPoints, param, c.pageable) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.DeviceList{ + Devices: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } +} + +// swagger:route GET /devices/{device_id} device describeDevice +// +// DescribeDevice 获取设备详情 +// +// Responses: +// 200: describeDevice +// default: ErrorResponse + +func (c *DeviceController) DescribeDevice() { + defer c.CatchException() + deviceId := c.Ctx.Input.Param(":device_id") + //id, err := strconv.ParseInt(idStr, 10, 64) + //if err != nil { + // c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + // return + //} + res, err := deviceLogic.GetById(c.logPoints, deviceId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.DeviceInfo{ + Device: res, + } +} + +// swagger:route DELETE /devices/stock device describeDeviceStock +// DescribeDeviceStock 获取指定机型的设备库存 +// Responses: +// 200: describeDeviceStock +// default: ErrorResponse +func (c *DeviceController) DescribeDeviceStock() { + defer c.CatchException() + list := deviceLogic.GetAllDevices(c.logPoints, map[string]interface{}{ + "manage_status": baseLogic.PUTAWAY, + "device_type_id": c.GetString("deviceTypeId"), + }, []string{}, []string{}, []string{}) + c.Res.Result = response.DeviceStock{ + Stocks: len(list), + } +} diff --git a/bmp-openapi-console/controllers/deviceTypeController.go b/bmp-openapi-console/controllers/deviceTypeController.go new file mode 100644 index 0000000..82fe0ee --- /dev/null +++ b/bmp-openapi-console/controllers/deviceTypeController.go @@ -0,0 +1,157 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/logic/deviceTypeLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type DeviceTypeController struct { + BaseController +} + +// swagger:route GET /deviceTypes deviceType describeDeviceTypes +// DescribeDeviceTypes 获取机型列表 +// Responses: +// 200: describeDeviceTypes +// default: ErrorResponse + +func (c *DeviceTypeController) DescribeDeviceTypes() { + defer c.CatchException() + req := &requestTypes.QueryDeviceTypesRequest{ + DeviceTypeID: c.GetString("deviceTypeId"), + DeviceType: c.GetString("deviceType"), + IdcID: c.GetString("idcId"), + Name: c.GetString("name"), + DeviceSeries: c.GetString("deviceSeries"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + //device_types, err := deviceTypeLogic.QueryByRequest(c.logPoints, req) + res, count, err := deviceTypeLogic.QueryDeviceTypes(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.DeviceTypeList{ + DeviceTypes: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } +} + +// swagger:route GET /deviceTypes/{device_type_id} deviceType describeDeviceType +// +// +// DescribeDeviceType 获取机型详情 +// +// Responses: +// 200: describeDeviceType +// default: ErrorResponse + +func (c *DeviceTypeController) DescribeDeviceType() { + defer c.CatchException() + req := &requestTypes.QueryDeviceTypesRequest{ + DeviceTypeID: c.Ctx.Input.Param(":device_type_id"), + } + req.Validate(c.logPoints) + res, err := deviceTypeLogic.QueryDeviceType(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.DeviceTypeInfo{ + DeviceType: res, + } +} + +// swagger:route GET /deviceTypes/deviceTypeImage deviceType describeDeviceTypeImages +// +// QueryDeviceTypeImage 根据机型获取镜像 +// +// Responses: +// 200: describeDeviceTypeImages +// default: ErrorResponse + +func (c *DeviceTypeController) DescribeDeviceTypeImages() { + req := &requestTypes.QueryDeviceTypeImageRequest{ + DeviceTypeID: c.GetString("deviceTypeId"), + ImageID: c.GetString("imageId"), + Architecture: c.GetString("architecture"), + OsType: c.GetString("osType"), + + ImageName: c.GetString("imageName"), + Version: c.GetString("version"), + OsID: c.GetString("osId"), + //ImageIDs: strings.Split(c.GetString("imageIds"), ","), + Source: c.GetString("source"), + IsAll: c.GetString("isAll"), + } + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + res, count, err := deviceTypeLogic.QueryDeviceTypeImage(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ImageList{ + Images: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } +} + +// swagger:route GET /deviceTypes/volumesRaids deviceType describeVolumesRaids +// +// DescribeVolumesRaids 根据机型获取卷和raid信息 (deviceTypeRaid->volumesRaids) +// +// Responses: +// 200: describeVolumesRaids +// default: ErrorResponse + +func (c *DeviceTypeController) DescribeVolumesRaids() { + req := &requestTypes.QueryVolumesRaidsRequest{ + DeviceTypeID: c.GetString("deviceTypeId"), + VolumeType: c.GetString("volumeType"), + } + res, err := deviceTypeLogic.QueryVolumesRaids(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route GET /deviceTypes/deviceTypeImagePartition deviceType describeDeviceTypeImagePartitions +// +// QueryDeviceTypeImagePartition 根据机型,镜像,获取分区 +// +// Responses: +// 200: describeDeviceTypeImagePartitions +// default: ErrorResponse + +func (c *DeviceTypeController) DescribeDeviceTypeImagePartitions() { + req := &requestTypes.QueryDeviceTypeImagePartitionRequest{ + DeviceTypeID: c.GetString("deviceTypeId"), + ImageID: c.GetString("imageId"), + } + req.Validate(c.logPoints) + res, err := deviceTypeLogic.QueryDeviceTypeImagePartition(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-openapi-console/controllers/idcController.go b/bmp-openapi-console/controllers/idcController.go new file mode 100644 index 0000000..d178c1f --- /dev/null +++ b/bmp-openapi-console/controllers/idcController.go @@ -0,0 +1,70 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/logic/idcLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type IdcController struct { + BaseController +} + +// DescribeIdcs ... +// swagger:route GET /idcs idc describeIdcs +// DescribeIdcs 获取idc列表 +// Responses: +// 200: describeIdcs +// default: ErrorResponse + +func (c *IdcController) DescribeIdcs() { + defer c.CatchException() + req := &requestTypes.QueryIdcsRequest{ + Name: c.GetString("name"), + Level: c.GetString("level"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + c.logPoints.Point("QueryIdcsRequest req", req) + res, count, err := idcLogic.QueryIdcs(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.IdcList{ + Idcs: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } +} + +// swagger:route GET /idcs/{idc_id} idc describeIdc +// DescribeIdc 获取idc详情 +// Responses: +// 200: describeIdc +// default: ErrorResponse + +func (c *IdcController) DescribeIdc() { + defer c.CatchException() + req := &requestTypes.QueryIdcRequest{ + IDcID: c.Ctx.Input.Param(":idc_id"), + } + req.Validate(c.logPoints) + c.logPoints.Point("QueryIdcRequest req", req) + res, err := idcLogic.QueryIdcById(c.logPoints, req.IDcID) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-openapi-console/controllers/imageController.go b/bmp-openapi-console/controllers/imageController.go new file mode 100644 index 0000000..4052e08 --- /dev/null +++ b/bmp-openapi-console/controllers/imageController.go @@ -0,0 +1,119 @@ +package controllers + +import ( + "regexp" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + + imageLogic "coding.jd.com/aidc-bmp/bmp-openapi/logic/imageLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + validation "git.jd.com/cps-golang/ironic-common/ironic/common/Validation" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type ImageController struct { + BaseController +} + +// DescribeImages ... +// swagger:route GET /images image describeImages +// DescribeImages 获取镜像列表 +// Responses: +// 200: describeImages +// default: ErrorResponse + +func (c *ImageController) DescribeImages() { + defer c.CatchException() + req := &requestTypes.QueryImagesRequest{ + ImageID: c.GetString("imageId"), + DeviceTypeID: c.GetString("deviceTypeId"), + ImageName: c.GetString("imageName"), + Version: c.GetString("version"), + OsID: c.GetString("osId"), + ImageIDs: strings.Split(c.GetString("imageIds"), ","), + Source: c.GetString("source"), + Architecture: c.GetString("architecture"), + OsType: c.GetString("osType"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + res, count, err := imageLogic.DescribeImages(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ImageList{ + Images: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } +} + +// DescribeImage ... +// swagger:route GET /images/{image_id} image describeImage +// DescribeImage 获取镜像详情 +// Responses: +// 200: describeImage +// default: ErrorResponse + +func (c *ImageController) DescribeImage() { + defer c.CatchException() + image_id := c.Ctx.Input.Param(":image_id") + if match, err := regexp.MatchString(validation.REGEX_ID, image_id); !match { + if err != nil { + c.logPoints.Warn("DescribeImage regexp match source error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + } + //image, err := imageDao.GetImageByUuid(image_id) + res, err := imageLogic.GetByImageId(c.logPoints, image_id) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ImageInfo{ + Image: res, + } +} + +// DescribeImageDeviceTypes ... +// swagger:route GET /images/imageDeviceTypes image describeImageDeviceTypes +// DescribeImageDeviceTypes 查看镜像绑定的机型 +// Responses: +// 200: describeImageDeviceTypes +// default: ErrorResponse + +func (c *ImageController) DescribeImageDeviceTypes() { + defer c.CatchException() + req := &requestTypes.QueryImageDeviceTypesRequest{ + ImageID: c.GetString("imageId"), + Architecture: c.GetString("architecture"), + IsBind: c.GetString("isBind"), + IsAll: c.GetString("isAll"), + } + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + res, count, err := imageLogic.QueryImageDeviceTypes(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.DeviceTypeList{ + DeviceTypes: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } +} diff --git a/bmp-openapi-console/controllers/instanceController.go b/bmp-openapi-console/controllers/instanceController.go new file mode 100644 index 0000000..9462d5b --- /dev/null +++ b/bmp-openapi-console/controllers/instanceController.go @@ -0,0 +1,590 @@ +package controllers + +import ( + "encoding/json" + "errors" + "fmt" + "regexp" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/instanceLogic" + log "coding.jd.com/aidc-bmp/bmp_log" + + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + validation "git.jd.com/cps-golang/ironic-common/ironic/common/Validation" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type InstanceController struct { + BaseController +} + +func ValidateLocalUserProjectInstances(logger *log.Logger, projectId string, InstanceIds []string) error { + userId := logger.GetPoint("userId").(string) + query := map[string]interface{}{ + "user_id": userId, + "project_id": projectId, + "is_del": 0, + } + if len(InstanceIds) > 0 { + query["instance_id.in"] = InstanceIds + } + c, err := instanceLogic.GetInstanceCount(logger, query) + if err != nil { + return err + } + if c == 0 || c != int64(len(InstanceIds)) { + return errors.New("权限不够") + } + return nil +} + +// Instance ... +// swagger:route POST /project/instances instance createProjectInstance +// +// CreateProjectInstance 创建实例 +// Responses: +// 200: createProjectInstance +// default: ErrorResponse + +func (c *InstanceController) CreateProjectInstance() { + defer c.CatchException() + c.logPoints.Infof("CreateProjectInstance body:%s", string(c.Ctx.Input.RequestBody)) + req := &requestTypes.CreateInstanceRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateInstance parse pInstancet body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + instanceIds, err := instanceLogic.CreateInstance(c.logPoints, *req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.InstanceIds{ + InstanceIds: instanceIds, + } +} + +// GetInstanceList ... +// swagger:route GET /project/instances instance describeProjectInstances +// +// DescribeProjectInstances 获取实例列表 +// Responses: +// 200: describeProjectInstances +// default: ErrorResponse + +func (c *InstanceController) DescribeProjectInstances() { + defer c.CatchException() + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.QueryInstancesRequest{ + InstanceName: c.GetString("instanceName"), + InstanceID: c.GetString("instanceId"), + Sn: c.GetString("sn"), + ProjectID: c.GetString("projectId"), + IdcID: c.GetString("idcId"), + DeviceTypeID: c.GetString("deviceTypeId"), + DeviceID: c.GetString("deviceId"), + Status: c.GetString("status"), + IloIP: c.GetString("ilo_ip"), + IPV4: c.GetString("ipv4"), + IPV6: c.GetString("ipv6"), + IsAll: c.GetString("isAll"), + IsInstallAgent: c.GetString("isInstallAgent"), + } + req.Validate(c.logPoints) + res, count, err := instanceLogic.GetInstanceList(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.InstanceList{ + Instances: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } + +} + +// DescribeInstance ... +// swagger:route GET /project/instances/{instance_id} instance describeProjectInstance +// DescribeProjectInstance 获取实例详情 +// +// Responses: +// 200: describeProjectInstance +// default: ErrorResponse + +func (c *InstanceController) DescribeProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + res, err := instanceLogic.GetInstanceById(c.logPoints, instanceId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.InstanceInfo{ + Instance: res, + } +} + +// ModifyInstance ... +// swagger:route PUT /project/instances/{instance_id} instance modifyProjectInstance +// ModifyProjectInstance 修改实例信息 +// +// Responses: +// 200: modifyProjectInstance +// default: ErrorResponse + +func (c *InstanceController) ModifyProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + req := &requestTypes.ModifyInstanceRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyInstance parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := instanceLogic.ModifyProjectInstance(c.logPoints, req, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// LockInstance ... +// swagger:route PUT /project/instances/{instance_id}/lock instance lockProjectInstance +// +// LockProjectInstance 锁定实例 +// Responses: +// 200: lockProjectInstance +// default: ErrorResponse + +func (c *InstanceController) LockProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + if err := instanceLogic.LockInstance(c.logPoints, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// LockInstance ... +// swagger:route PUT /project/instances/{instance_id}/unlock instance unLockProjectInstance +// +// UnLockProjectInstance 解锁实例 +// Responses: +// 200: unLockProjectInstance +// default: ErrorResponse + +func (c *InstanceController) UnLockProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + if err := instanceLogic.UnLockInstance(c.logPoints, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// StartInstance ... +// swagger:route PUT /project/instances/{instance_id}/start instance startProjectInstance +// +// StartProjectInstance 实例开机 +// Responses: +// 200: startProjectInstance +// default: ErrorResponse + +func (c *InstanceController) StartProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + if err := instanceLogic.StartInstance(c.logPoints, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// StopInstance ... +// swagger:route PUT /project/instances/{instance_id}/stop instance stopProjectInstance +// +// StopProjectInstance 实例关机 +// Responses: +// 200: stopProjectInstance +// default: ErrorResponse + +func (c *InstanceController) StopProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + if err := instanceLogic.StopInstance(c.logPoints, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// RestartInstance ... +// swagger:route PUT /project/instances/{instance_id}/restart instance restartProjectInstance +// +// RestartProjectInstance 实例重启 +// Responses: +// 200: restartProjectInstance +// default: ErrorResponse + +func (c *InstanceController) RestartProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + if err := instanceLogic.RestartInstance(c.logPoints, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// DeleteInstance ... +// swagger:route DELETE /project/instances/{instance_id} instance deleteProjectInstance +// +// DeleteProjectInstance 删除实例 +// Responses: +// 200: deleteProjectInstance +// default: ErrorResponse + +func (c *InstanceController) DeleteProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + if err := instanceLogic.DeleteInstance(c.logPoints, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// ResetInstanceStatus ... +// swagger:route PUT /project/instances/{instance_id}/resetStatus instance resetInstanceStatus +// +// ResetInstanceStatus 重置实例状态 +// Responses: +// 200: resetInstanceStatus +// default: ErrorResponse +func (c *InstanceController) ResetInstanceStatus() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + if err := instanceLogic.ResetInstanceStatus(c.logPoints, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /project/instances/batch/instances:startInstances instance startInstances +// +// StartInstances 批量开机 +// Responses: +// 200: startInstances +// default: ErrorResponse +func (c *InstanceController) StartInstances() { + + defer c.CatchException() + instancesAndOperation := c.Ctx.Input.Param(":param") + if instancesAndOperation != "instances:startInstances" { + c.SetErrorResponse(httpStatus.BAD_REQUEST, fmt.Sprintf("url %s parse error", instancesAndOperation), errorCode.INVALID_ARGUMENT) + return + } + + req := requestTypes.StartInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + req.Validate(c.logPoints) + + if err := instanceLogic.StartInstances(c.logPoints, req.InstanceIds); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /project/instances/batch/instances:stopInstances instance stopInstances +// +// StartInstances 批量关机 +// Responses: +// 200: stopInstances +// default: ErrorResponse +func (c *InstanceController) StopInstances() { + + defer c.CatchException() + instancesAndOperation := c.Ctx.Input.Param(":param") + if instancesAndOperation != "instances:stopInstances" { + c.SetErrorResponse(httpStatus.BAD_REQUEST, fmt.Sprintf("url %s parse error", instancesAndOperation), errorCode.INVALID_ARGUMENT) + return + } + req := requestTypes.StopInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + req.Validate(c.logPoints) + + if err := instanceLogic.StopInstances(c.logPoints, req.InstanceIds); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /project/instances/batch/instances:restartInstances instance restartInstances +// +// StartInstances 批量重启 +// Responses: +// 200: restartInstances +// default: ErrorResponse +func (c *InstanceController) RestartInstances() { + + defer c.CatchException() + instancesAndOperation := c.Ctx.Input.Param(":param") + if instancesAndOperation != "instances:restartInstances" { + c.SetErrorResponse(httpStatus.BAD_REQUEST, fmt.Sprintf("url %s parse error", instancesAndOperation), errorCode.INVALID_ARGUMENT) + return + } + req := requestTypes.RestartInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + req.Validate(c.logPoints) + + if err := instanceLogic.RestartInstances(c.logPoints, req.InstanceIds); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /project/instances/batch/instances:modifyInstances instance modifyInstances +// +// ModifyInstances 批量修改实例名称 +// Responses: +// 200: modifyInstances +// default: ErrorResponse +func (c *InstanceController) ModifyInstances() { + + defer c.CatchException() + instancesAndOperation := c.Ctx.Input.Param(":param") + if instancesAndOperation != "instances:modifyInstances" { + c.SetErrorResponse(httpStatus.BAD_REQUEST, fmt.Sprintf("url %s parse error", instancesAndOperation), errorCode.INVALID_ARGUMENT) + return + } + req := requestTypes.ModifyInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + req.Validate(c.logPoints) + + if err := instanceLogic.ModifyInstances(c.logPoints, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// DeleteInstances ... +// swagger:route DELETE /project/instances/batch/instances:deleteInstances instance deleteInstances +// +// DeleteInstances 批量删除实例 +// Responses: +// 200: deleteInstances +// default: ErrorResponse + +func (c *InstanceController) DeleteInstances() { + defer c.CatchException() + + defer c.CatchException() + instancesAndOperation := c.Ctx.Input.Param(":param") + if instancesAndOperation != "instances:deleteInstances" { + c.SetErrorResponse(httpStatus.BAD_REQUEST, fmt.Sprintf("url %s parse error", instancesAndOperation), errorCode.INVALID_ARGUMENT) + return + } + req := requestTypes.DeleteInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + req.Validate(c.logPoints) + + if err := instanceLogic.DeleteInstances(c.logPoints, req.InstanceIDs); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// ResetPasswd ... +// swagger:route PUT /project/instances/{instance_id}/resetpasswd instance resetProjectInstancePasswd +// +// ResetPasswd 重置密码 +// Responses: +// 200: resetProjectInstancePasswd +// default: ErrorResponse + +func (c *InstanceController) ResetPasswd() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + + req := requestTypes.ResetInstancePasswdRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + req.Validate(c.logPoints) + + if err := instanceLogic.ResetInstancePasswd(c.logPoints, instanceId, req.Password); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// StartInstance ... +// swagger:route PUT /project/instances/batch/instances:resetPasswd instance resetProjectInstancesPasswd +// +// ResetInstancesPasswd 批量重置密码 +// Responses: +// 200: resetProjectInstancesPasswd +// default: ErrorResponse + +func (c *InstanceController) ResetInstancesPasswd() { + defer c.CatchException() + + req := requestTypes.ResetInstancesPasswdRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + req.Validate(c.logPoints) + + if err := instanceLogic.ResetInstancesPasswd(c.logPoints, req.InstanceIDs, req.Password); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// ReinstallInstance ... +// swagger:route PUT /project/instances/{instance_id}/reinstallInstance instance reinstallProjectInstance +// +// ReinstallInstance 重装实例 +// Responses: +// 200: reinstallProjectInstance +// default: ErrorResponse +func (c *InstanceController) ReinstallInstance() { + defer c.CatchException() + instance_id := c.Ctx.Input.Param(":instance_id") + if match, err := regexp.MatchString(validation.REGEX_ID, instance_id); !match { + if err != nil { + c.logPoints.Warn("ReinstallInstance path error:", err.Error()) + } + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req := &requestTypes.ReinstallInstanceRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("parse post body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + if err := req.Validate(c.logPoints); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + if err := instanceLogic.ReinstallInstance(c.logPoints, instance_id, req); err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// GetInstanceList ... +// swagger:route GET /project/instances/share/describeInstances instance describeInstancesByProjectIdAndOwnerNameAndSharerName +// +// DescribeInstancesByProjectIdAndOwnerNameAndSharerName 根据projectid,ownername,username来获取实例列表。为了支持部分资源转移中的实例列表 +// Responses: +// 200: describeInstancesByProjectIdAndOwnerNameAndSharerName +// default: ErrorResponse + +func (c *InstanceController) DescribeInstancesByProjectIdAndOwnerNameAndSharerName() { + defer c.CatchException() + + req := &requestTypes.DescribeInstancesByProjectIdAndOwnerNameAndSharerNameRequest{ + + ProjectID: c.GetString("projectId"), + // IsAll: c.GetString("isAll"), + OwnerName: c.GetString("ownerName"), + SharerName: c.GetString("sharerName"), + + InstanceName: c.GetString("instanceName"), + InstanceID: c.GetString("instanceId"), + } + req.Validate(c.logPoints) + res, err := instanceLogic.GetInstanceListByProjectIdAndOwnerNameAndSharerName(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.InstanceForShareList{ + Instances: res, + } + +} diff --git a/bmp-openapi-console/controllers/messageController.go b/bmp-openapi-console/controllers/messageController.go new file mode 100644 index 0000000..aa86bc7 --- /dev/null +++ b/bmp-openapi-console/controllers/messageController.go @@ -0,0 +1,202 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/messageLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type MessageController struct { + BaseController +} + +// HasUnreadMessage ... +// swagger:route GET /messages/hasUnreadMessage message hasUnreadMessage +// +// HasUnreadMessage 获取有没有未读消息 +// +// Responses: +// 200: hasUnreadMessage +// default: ErrorResponse + +func (c *MessageController) HasUnreadMessage() { + defer c.CatchException() + + res, err := messageLogic.HasUnreadMessage(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.HasUnreadMessage{ + HasUnread: res, + } +} + +// GetMessageList ... +// swagger:route GET /messages message getMessageList +// +// GetMessageList 获取message列表(分页) +// +// Responses: +// 200: getMessageList +// default: ErrorResponse +func (c *MessageController) GetMessageList() { + defer c.CatchException() + + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + + req := &requestTypes.QueryMessagesRequest{ + IsAll: c.GetString("isAll"), + HasRead: c.GetString("hasRead"), + MessageType: c.GetString("messageType"), + MessageSubType: c.GetString("messageSubType"), + Detail: c.GetString("detail"), + } + req.Validate(c.logPoints) + + res, cnt, err := messageLogic.GetPageMessages(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.MessageList{ + Messages: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: cnt, + } +} + +// GetMessageStatistic ... +// swagger:route GET /messages/statistic message getMessageStatistic +// +// GetMessageStatistic 获取message总数和未读数 +// +// Responses: +// 200: getMessageStatistic +// default: ErrorResponse +func (c *MessageController) GetMessageStatistic() { + defer c.CatchException() + + total, unread, err := messageLogic.GetMessageStatistic(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = response.MessageStatistic{ + + TotalCount: total, + UnreadCount: unread, + } +} + +// ReadMessage ... +// swagger:route PUT /messages/doRead message readMessage +// +// ReadMessage 将消息设置为已读(可多条) +// +// Responses: +// 200: readMessage +// default: ErrorResponse +func (c *MessageController) ReadMessage() { + defer c.CatchException() + + req := &requestTypes.ReadMessagesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ReadMessage parse ReadMessagesRequest body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := messageLogic.ReadMessages(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// GetMessageById ... +// swagger:route GET /messages/getMessageById message getMessageById +// +// GetMessageById 获取消息详情,包括上一条/下一条的messageid +// +// Responses: +// 200: getMessageById +// default: ErrorResponse + +func (c *MessageController) GetMessageById() { + defer c.CatchException() + + req := &requestTypes.GetMessageByIdRequest{ + MessageID: c.GetString("messageId"), + } + req.Validate(c.logPoints) + msg, nextMsgId, prevMsgId, err := messageLogic.GetMessageById(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.MessageWithNextPrev{ + Message: msg, + NextMessageId: nextMsgId, + PrevMessageId: prevMsgId, + } +} + +// GetMessageTypes ... +// swagger:route GET /messages/getMessageTypes message getMessageTypes +// +// GetMessageTypes 获取消息类型/子类型 +// +// Responses: +// 200: getMessageTypes +// default: ErrorResponse + +func (c *MessageController) GetMessageTypes() { + defer c.CatchException() + + res := messageLogic.GetMessageTypes(c.logPoints) + + c.Res.Result = res +} + +// DeleteMessage ... +// swagger:route DELETE /messages/delete message deleteMessage +// +// DeleteMessage 删除消息(可多条) +// +// Responses: +// 200: deleteMessage +// default: ErrorResponse +func (c *MessageController) DeleteMessage() { + defer c.CatchException() + + req := &requestTypes.DeleteMessagesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DeleteMessage parse ReadMessagesRequest body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := messageLogic.DeleteMessages(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} diff --git a/bmp-openapi-console/controllers/monitorAlertController.go b/bmp-openapi-console/controllers/monitorAlertController.go new file mode 100644 index 0000000..49c7f35 --- /dev/null +++ b/bmp-openapi-console/controllers/monitorAlertController.go @@ -0,0 +1,144 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorAlertLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorAlertController 告警 +type MonitorAlertController struct { + BaseController +} + +// swagger:route POST /monitorAlert/addAlert monitorAlert addAlert +// +// AddAlert 添加(接收)告警 +// +// Responses: +// 200: addAlert +// default: ErrorResponse +func (c *MonitorAlertController) AddAlert() { + defer c.CatchException() + c.logPoints.Infof("AddAlert body:%s", string(c.Ctx.Input.RequestBody)) + + body := string(c.Ctx.Input.RequestBody) + //赛迪改成trigger单独urlencode + // body, err := url.QueryUnescape(body) + // if err != nil { + // c.logPoints.Warn("AddAlert.QueryUnescape error:", err.Error()) + // c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + // return + // } + req := &request.AddAlertRequest{} + if err := json.Unmarshal([]byte(body), req); err != nil { + c.logPoints.Warn("AddAlert parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + for _, v := range req.Alerts { + c.logPoints.Infof("alert.trigger is:%s", v.Trigger) + } + + res, err := monitorAlertLogic.AddAlert(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route GET /monitorAlert/describeAlert monitorAlert describeAlert +// +// DescribeAlert 告警详情 +// +// Responses: +// 200: describeAlert +// default: ErrorResponse +func (c *MonitorAlertController) DescribeAlert() { + defer c.CatchException() + req := request.DescribeAlertRequest{ + AlertID: c.GetString("alertId"), + } + req.Validate(c.logPoints) + res, err := monitorAlertLogic.DescribeAlert(c.logPoints, req.AlertID) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route GET /monitorAlert/describeAlerts monitorAlert describeAlerts +// +// DescribeAlerts 告警列表 +// +// Responses: +// 200: describeAlerts +// default: ErrorResponse +func (c *MonitorAlertController) DescribeAlerts() { + defer c.CatchException() + + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + + stime, _ := c.GetInt64("startTime") + etime, _ := c.GetInt64("endTime") + req := &request.DescribeAlertsRequest{ + IsAll: c.GetString("isAll"), + UserName: c.GetString("userName"), + UserID: c.GetString("userId"), + RuleName: c.GetString("ruleName"), + RuleID: c.GetString("ruleId"), + ResourceID: c.GetString("resourceId"), + StartTime: stime, + EndTime: etime, + ProjectID: c.GetString("projectId"), + } + req.Validate(c.logPoints) + + res, err := monitorAlertLogic.DescribeAlerts(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route DELETE /monitorAlert/deleteAlert monitorAlert deleteAlert +// +// DeleteAlert 删除告警 +// +// Responses: +// 200: deleteAlert +// default: ErrorResponse +func (c *MonitorAlertController) DeleteAlert() { + defer c.CatchException() + c.logPoints.Infof("DeleteAlert body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.DeleteAlertRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DeleteAlert parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorAlertLogic.DeleteAlert(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} diff --git a/bmp-openapi-console/controllers/monitorDataController.go b/bmp-openapi-console/controllers/monitorDataController.go new file mode 100644 index 0000000..3ad3821 --- /dev/null +++ b/bmp-openapi-console/controllers/monitorDataController.go @@ -0,0 +1,47 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorDataLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorDataController 读取监控数据 +type MonitorDataController struct { + BaseController +} + +// swagger:route GET /monitorData monitorData getMonitorData +// +// GetMonitorData 获取图表监控数据 +// +// Responses: +// 200: getMonitorData +// default: ErrorResponse +func (c *MonitorDataController) GetMonitorData() { + + stime, _ := c.GetInt64("startTime") + etime, _ := c.GetInt64("endTime") + ti, _ := c.GetInt("timeInterval") + lastManyTime, _ := c.GetInt("lastManyTime") + req := requestTypes.GetMonitorDataRequest{ + MetricName: c.GetString("metricName"), + InstanceID: c.GetString("instanceId"), + Device: c.GetString("device"), + StartTime: stime, + EndTime: etime, + LastManyTime: lastManyTime, + TimeInterval: ti, + DownSampleType: c.GetString("downSampleType"), + } + req.Validate(c.logPoints) + + res, err := monitorDataLogic.GetMonitorData(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res + +} diff --git a/bmp-openapi-console/controllers/monitorProxyController.go b/bmp-openapi-console/controllers/monitorProxyController.go new file mode 100644 index 0000000..6b257aa --- /dev/null +++ b/bmp-openapi-console/controllers/monitorProxyController.go @@ -0,0 +1,55 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorProxyLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorProxyController 从monitorproxy服务读取数据,包括agent状态,tag列表等 +type MonitorProxyController struct { + BaseController +} + +// swagger:route GET /monitorProxy/desrcibeAgentStatus monitorProxy desrcibeAgentStatus +// +// DesrcibeAgentStatus 获取agent状态 +// +// Responses: +// 200: desrcibeAgentStatus +// default: ErrorResponse +func (c *MonitorProxyController) DesrcibeAgentStatus() { + req := &request.DesrcibeAgentStatusRequest{ + InstanceID: c.GetString("instanceId"), + } + req.Validate(c.logPoints) + res, err := monitorProxyLogic.DescribeAgentStatus(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res + +} + +// swagger:route GET /monitorProxy/desrcibeTags monitorProxy desrcibeTags +// +// DesrcibeAgentStatus 获取tag列表 +// +// Responses: +// 200: desrcibeTags +// default: ErrorResponse +func (c *MonitorProxyController) DesrcibeTags() { + req := &request.DesrcibeTagsRequest{ + InstanceID: c.GetString("instanceId"), + TagName: c.GetString("tagName"), + } + req.Validate(c.logPoints) + res, err := monitorProxyLogic.DescribeDeviceTags(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-openapi-console/controllers/monitorRuleController.go b/bmp-openapi-console/controllers/monitorRuleController.go new file mode 100644 index 0000000..745a479 --- /dev/null +++ b/bmp-openapi-console/controllers/monitorRuleController.go @@ -0,0 +1,238 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorRuleLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorRuleController 告警规则 +type MonitorRuleController struct { + BaseController +} + +// swagger:route POST /monitorRule/addRule monitorRule addRule +// +// AddRule 添加规则 +// +// Responses: +// 200: addRule +// default: ErrorResponse +func (c *MonitorRuleController) AddRule() { + defer c.CatchException() + c.logPoints.Infof("AddRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.AddRuleRequest{} + + body := string(c.Ctx.Input.RequestBody) + //前端没有urlencode + // body, err := url.QueryUnescape(body) + // if err != nil { + // c.logPoints.Warn("AddRule.QueryUnescape error:", err.Error()) + // c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + // return + // } + + if err := json.Unmarshal([]byte(body), req); err != nil { + c.logPoints.Warn("AddRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.AddRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route GET /monitorRule/describeRule monitorRule describeRule +// +// DescribeRule 规则详情 +// +// Responses: +// 200: describeRule +// default: ErrorResponse +func (c *MonitorRuleController) DescribeRule() { + defer c.CatchException() + req := request.DescribeRuleRequest{ + RuleID: c.GetString("ruleId"), + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.DescribeRule(c.logPoints, req.RuleID) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route GET /monitorRule/describeRules monitorRule describeRules +// +// DescribeRules 规则列表 +// +// Responses: +// 200: describeRules +// default: ErrorResponse +func (c *MonitorRuleController) DescribeRules() { + defer c.CatchException() + + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + s, err := c.GetInt("status") + if err != nil { + c.logPoints.Warnf("DescribeRules.status parse error:%s", err.Error()) + } + + req := &request.DescribeRulesRequest{ + IsAll: c.GetString("isAll"), + UserName: c.GetString("userName"), + UserID: c.GetString("userId"), + RuleName: c.GetString("ruleName"), + RuleID: c.GetString("ruleId"), + Status: s, + ProjectID: c.GetString("projectId"), + } + req.Validate(c.logPoints) + + res, err := monitorRuleLogic.DescribeRules(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route PUT /monitorRule/editRule monitorRule editRule +// +// EditRule 编辑规则 +// +// Responses: +// 200: editRule +// default: ErrorResponse +func (c *MonitorRuleController) EditRule() { + defer c.CatchException() + c.logPoints.Infof("EditRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.EditRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("EditRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.EditRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route PUT /monitorRule/enableRule monitorRule enableRule +// +// EnableRule 启用规则 +// +// Responses: +// 200: enableRule +// default: ErrorResponse +func (c *MonitorRuleController) EnableRule() { + defer c.CatchException() + c.logPoints.Infof("EnableRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.EnableRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("EnableRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.EnableRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route PUT /monitorRule/disableRule monitorRule disableRule +// +// DisableRule 禁用规则 +// +// Responses: +// 200: disableRule +// default: ErrorResponse +func (c *MonitorRuleController) DisableRule() { + defer c.CatchException() + c.logPoints.Infof("DisableRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.DisableRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DisableRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.DisableRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route DELETE /monitorRule/deleteRule monitorRule deleteRule +// +// DeleteRule 删除规则 +// +// Responses: +// 200: deleteRule +// default: ErrorResponse +func (c *MonitorRuleController) DeleteRule() { + defer c.CatchException() + c.logPoints.Infof("EnableRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.DeleteRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DeleteRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.DeleteRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +//内部接口,查询Pronoea侧和数据库中规则是否一致 +func (c *MonitorRuleController) CheckDiffFromPronoea() { + defer c.CatchException() + c.logPoints.Infof("CheckDiffFromPronoea body:%s", string(c.Ctx.Input.RequestBody)) + + res, err := monitorRuleLogic.CheckDiffFromPronoea(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-openapi-console/controllers/osController.go b/bmp-openapi-console/controllers/osController.go new file mode 100644 index 0000000..ec4d503 --- /dev/null +++ b/bmp-openapi-console/controllers/osController.go @@ -0,0 +1,67 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/logic/osLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type OsController struct { + BaseController +} + +// DescribeOS ... +// swagger:route GET /oss/{os_id} os describeOS +// DescribeOS 获取os系统详情(暂不启用) +// +// Responses: +// 200: describeOS +// default: ErrorResponse + +func (c *OsController) DescribeOS() { + defer c.CatchException() + osId := c.Ctx.Input.Param(":os_id") + res, err := osLogic.GetByOsId(c.logPoints, osId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.OsInfo{ + Os: res, + } +} + +// DescribeOSs ... +// swagger:route GET /oss os describeOSs +// DescribeOSs 获取os列表(暂不启用) +// +// Responses: +// 200: describeOSs +// default: ErrorResponse + +func (c *OsController) DescribeOSs() { + defer c.CatchException() + //ids := strings.Split(c.GetString("ids"), ",") + req := &requestTypes.QueryOssRequest{ + OsName: c.GetString("osName"), + OsType: c.GetString("osType"), + OsVersion: c.GetString("osVersion"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + res, err := osLogic.DescribeOSs(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.OsList{ + Oss: res, + //PageNumber: c.pageable.PageNumber, + //PageSize: c.pageable.PageSize, + //TotalCount: count, + } + +} diff --git a/bmp-openapi-console/controllers/projectController.go b/bmp-openapi-console/controllers/projectController.go new file mode 100644 index 0000000..9cd33f8 --- /dev/null +++ b/bmp-openapi-console/controllers/projectController.go @@ -0,0 +1,312 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/projectLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// ProjectController operations for project +type ProjectController struct { + BaseController +} + +// CreateUserProject ... +// swagger:route POST /user/projects project createUserProject +// CreateUserProject 创建项目 +// +// Responses: +// 200: createUserProject +// default: ErrorResponse + +func (c *ProjectController) CreateUserProject() { + defer c.CatchException() + req := &requestTypes.CreateProjectRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateProject parse pProjectt body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + uuid, err := projectLogic.CreateProject(c.logPoints, req, "") + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ProjectId{ + ProjectId: uuid, + } +} + +// swagger:route GET /user/projects project describeUserProjects +// +// DescribeUserProjects 获取项目列表 +// Responses: +// 200: describeUserProjects +// default: ErrorResponse + +func (c *ProjectController) DescribeUserProjects() { + defer c.CatchException() + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + owned, _ := c.GetInt("owned") + req := &requestTypes.QueryProjectsRequest{ + ProjectName: c.GetString("projectName"), + IsAll: c.GetString("isAll"), + Owned: owned, + OwnerName: c.GetString("ownerName"), + SharerName: c.GetString("sharerName"), + } + if c.GetString("orderByCreatetime") == "desc" { + req.OrderByCreatetime = "desc" + } else { + req.OrderByCreatetime = "asc" + } + req.Validate(c.logPoints) + res, count, err := projectLogic.GetProjectList(c.logPoints, *req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ProjectList{ + Projects: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } + +} + +// swagger:route GET /user/projects/{project_id} project describeUserProject +// +// DescribeUserProject 获取项目详情 +// Responses: +// 200: describeUserProject +// default: ErrorResponse + +func (c *ProjectController) DescribeUserProject() { + defer c.CatchException() + ProjectId := c.Ctx.Input.Param(":project_id") + res, err := projectLogic.GetProjectById(c.logPoints, ProjectId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ProjectInfo{ + Project: res, + } +} + +// swagger:route PUT /user/projects/{project_id} project modifyUserProject +// +// ModifyUserProject 修改项目信息 +// Responses: +// 200: modifyUserProject +// default: ErrorResponse + +func (c *ProjectController) ModifyUserProject() { + defer c.CatchException() + ProjectId := c.Ctx.Input.Param(":project_id") + req := &requestTypes.ModifyProjectRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyProject parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := projectLogic.ModifyProject(c.logPoints, req, ProjectId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// swagger:route PUT /user/projects/{project_id}/description project modifyUserProjectDescription +// +// ModifyUserProject 修改项目信息 +// Responses: +// 200: modifyUserProjectDescription +// default: ErrorResponse + +func (c *ProjectController) ModifyUserProjectDescription() { + defer c.CatchException() + ProjectId := c.Ctx.Input.Param(":project_id") + req := &requestTypes.ModifyProjectDescriptionRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyProjectDescription parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := projectLogic.ModifyProjectDescription(c.logPoints, req, ProjectId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// swagger:route DELETE /user/projects/{project_id} project deleteUserProject +// +// DeleteUserProject 删除项目 +// Responses: +// 200: deleteUserProject +// default: ErrorResponse + +func (c *ProjectController) DeleteUserProject() { + defer c.CatchException() + ProjectId := c.Ctx.Input.Param(":project_id") + if err := projectLogic.DeleteProject(c.logPoints, ProjectId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /user/projects/{project_id}/share project shareUserProject +// +// ShareUserProject 共享项目 +// Responses: +// 200: shareUserProject +// default: ErrorResponse + +func (c *ProjectController) ShareUserProject() { + defer c.CatchException() + + ProjectId := c.Ctx.Input.Param(":project_id") + req := &requestTypes.ShareProjectRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyProject parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := projectLogic.AddShareProject(c.logPoints, ProjectId, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// swagger:route PUT /user/projects/{project_id}/cancelShare project cancelShareUserProject +// +// CancelShareUserProject 取消共享项目 +// Responses: +// 200: cancelShareUserProject +// default: ErrorResponse + +func (c *ProjectController) CancelShareUserProject() { + defer c.CatchException() + + ProjectId := c.Ctx.Input.Param(":project_id") + req := &requestTypes.CalcelShareProjectRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyProject parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := projectLogic.CancelShareProject(c.logPoints, ProjectId, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// swagger:route GET /user/projects/{project_id}/describeSharProject project describeShareProject +// +// DescribeShareUserProject 获取共享项目详情 +// Responses: +// 200: describeShareProject +// default: ErrorResponse + +func (c *ProjectController) DescribeShareUserProject() { + defer c.CatchException() + + ProjectId := c.Ctx.Input.Param(":project_id") + + res, err := projectLogic.DescribeShareProject(c.logPoints, ProjectId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ShareProjectInfo{ + ProjectID: ProjectId, + Shares: res, + } +} + +// swagger:route PUT /user/projects/{project_id}/move project moveUserProject +// +// MoveUserProject 转移项目 +// Responses: +// 200: moveUserProject +// default: ErrorResponse + +func (c *ProjectController) MoveUserProject() { + defer c.CatchException() + + ProjectId := c.Ctx.Input.Param(":project_id") + req := &requestTypes.MoveProjectRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("MoveProject parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := projectLogic.MoveProject(c.logPoints, ProjectId, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// swagger:route PUT /user/projects/move/instances project moveUserInstances +// +// MoveUserInstances 转移项目下的某些实例 +// Responses: +// 200: moveUserInstances +// default: ErrorResponse + +func (c *ProjectController) MoveUserInstances() { + defer c.CatchException() + + req := &requestTypes.MoveInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("MoveProject parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := projectLogic.MoveInstances(c.logPoints, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} diff --git a/bmp-openapi-console/controllers/rabbitmqController.go b/bmp-openapi-console/controllers/rabbitmqController.go new file mode 100644 index 0000000..a85e8bf --- /dev/null +++ b/bmp-openapi-console/controllers/rabbitmqController.go @@ -0,0 +1,31 @@ +package controllers + +import ( + "time" + + util "coding.jd.com/aidc-bmp/bmp-openapi/util" +) + +// DeviceController operations for Device +type RabbitMqController struct { + BaseController +} + +// QueryDevices ... +// @router / [get] +func (c *RabbitMqController) Send() { + + rabbitmq := util.NewRabbitMQSimple("cn-north-1c") + rabbitmq.PublishSimple("Hello goFrame!" + time.Now().Format("2006-01-02 15:04:05")) + + return +} +func (c *RabbitMqController) Receive() { + + //util.Receive() + rabbitmq := util.NewRabbitMQSimple("cn-north-1c") + + rabbitmq.ConsumeSimple() + + return +} diff --git a/bmp-openapi-console/controllers/resourceController.go b/bmp-openapi-console/controllers/resourceController.go new file mode 100644 index 0000000..5cf4fa1 --- /dev/null +++ b/bmp-openapi-console/controllers/resourceController.go @@ -0,0 +1,45 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/logic/resourceLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +type ResourceController struct { + BaseController +} + +// swagger:route GET /resources resource describeResources +// +// DescribeResources 根据某个字段值精确查询对应的资源列表(如根据imageName查询镜像列表,根据idcName查询机房列表) +// +// Responses: +// 200: describeResources +// default: ErrorResponse +func (c *ResourceController) DescribeResources() { + defer c.CatchException() + req := &requestTypes.QueryResourcesRequest{ + Name: c.GetString("name"), + DeviceType: c.GetString("deviceType"), + ImageName: c.GetString("imageName"), + UserName: c.GetString("userName"), + } + count, err := resourceLogic.DescribeResources(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + if count > 0 { + c.Res.Result = response.CommonResponse{ + Success: true, + } + } else { + c.Res.Result = response.CommonResponse{ + Success: false, + } + } + +} diff --git a/bmp-openapi-console/controllers/roleController.go b/bmp-openapi-console/controllers/roleController.go new file mode 100644 index 0000000..6cbad6b --- /dev/null +++ b/bmp-openapi-console/controllers/roleController.go @@ -0,0 +1,89 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/logic/roleLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// RoleController operations for role +type RoleController struct { + BaseController +} + +// GetRoleList ... +// swagger:route GET /roles role describeRoles +// DescribeRoles 获取角色列表 +// +// Responses: +// 200: describeRoles +// default: ErrorResponse + +func (c *RoleController) DescribeRoles() { + defer c.CatchException() + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.QueryRolesRequest{ + //RoleName: c.GetString("roleName"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + res, count, err := roleLogic.GetRoleList(c.logPoints, *req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.RoleList{ + Roles: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } + +} + +// DescribeRole ... +// swagger:route GET /roles/{role_id} role describeRole +// +// DescribeRole 获取角色详情 +// Responses: +// 200: describeRole +// default: ErrorResponse + +func (c *RoleController) DescribeRole() { + defer c.CatchException() + roleId := c.Ctx.Input.Param(":role_id") + res, err := roleLogic.GetRoleById(c.logPoints, roleId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.RoleInfo{ + Role: res, + } +} + +// swagger:route GET /roles/roleInfo/current role currentRole +// +// CurrentRole 获取当前登录用户的角色 +// Responses: +// 200: currentRole +// default: ErrorResponse + +func (c *RoleController) CurrentRole() { + defer c.CatchException() + + res, err := roleLogic.CurrentRole(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.RoleInfo{ + Role: res, + } +} diff --git a/bmp-openapi-console/controllers/sshkeyController.go b/bmp-openapi-console/controllers/sshkeyController.go new file mode 100644 index 0000000..7320717 --- /dev/null +++ b/bmp-openapi-console/controllers/sshkeyController.go @@ -0,0 +1,168 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/sshkeyLogic" + + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// SshkeyController operations for sshkey +type SshkeyController struct { + BaseController +} + +// CreateSshkey ... +// swagger:route POST /user/sshkeys sshkey createUserSshkey +// +// CreateUserSshkey 创建个人sshkey +// Responses: +// 200: createUserSshkey +// default: ErrorResponse + +func (c *SshkeyController) CreateUserSshkey() { + defer c.CatchException() + req := &requestTypes.CreateSshkeyRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateSshkey parse pSshkeyt body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + uuid, err := sshkeyLogic.CreateSshkey(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.SshkeyId{ + SshkeyId: uuid, + } +} + +// QueryBySshkeyIds ... +// swagger:route GET /user/sshkeys sshkey describeUserSshKeys +// +// DescribeUserSshKeys 获取个人sshkey列表 +// Responses: +// 200: describeUserSshKeys +// default: ErrorResponse + +func (c *SshkeyController) DescribeUserSshKeys() { + defer c.CatchException() + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.QuerySshkeysRequest{ + Name: c.GetString("name"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + res, count, err := sshkeyLogic.GetSshkeyList(c.logPoints, *req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.SshkeyList{ + Sshkeys: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } + +} + +// GetInstancesBySshkey ... +// swagger:route GET /user/sshkeys/instances/{sshkey_id} sshkey getInstancesBySshkey +// GetInstancesBySshkey 根据sshkey获取实例列表 +// +// Responses: +// 200: getInstancesBySshkey +// default: ErrorResponse + +func (c *SshkeyController) GetInstancesBySshkey() { + defer c.CatchException() + //req := &requestTypes.QueryInstancesSshkeyRequest{ + // SshkeyId: c.Ctx.Input.Param(":sshkey_id"), + //} + //req.Validate(c.logPoints) + ids := sshkeyLogic.GetInstancesBySshkey(c.logPoints, c.Ctx.Input.Param(":sshkey_id")) + c.Res.Result = response.InstancesSshkeyInfoResponse{ + InstanceIds: ids, + } + +} + +// DescribeSshkey ... +// swagger:route GET /user/sshkeys/{sshkey_id} sshkey describeUserSshKey +// +// DescribeUserSshKey 获取sshkey详情 +// Responses: +// 200: describeUserSshKey +// default: ErrorResponse + +func (c *SshkeyController) DescribeUserSshKey() { + defer c.CatchException() + sshkeyId := c.Ctx.Input.Param(":sshkey_id") + res, err := sshkeyLogic.GetSshkeyById(c.logPoints, sshkeyId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.SshkeyInfo{ + Sshkey: res, + } +} + +// ModifySshkey ... +// swagger:route PUT /user/sshkeys/{sshkey_id} sshkey modifyUserSshkey +// +// ModifyUserSshkey 修改sshkey +// Responses: +// 200: modifyUserSshkey +// default: ErrorResponse + +func (c *SshkeyController) ModifyUserSshkey() { + defer c.CatchException() + sshkeyId := c.Ctx.Input.Param(":sshkey_id") + req := &requestTypes.ModifySshkeyRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifySshkey parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := sshkeyLogic.ModifySshkey(c.logPoints, req, sshkeyId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// DeleteSshkey ... +// swagger:route DELETE /user/sshkeys/{sshkey_id} sshkey deleteUserSshkey +// DeleteUserSshkey 删除sshkey +// +// Responses: +// 200: deleteUserSshkey +// default: ErrorResponse + +func (c *SshkeyController) DeleteUserSshkey() { + defer c.CatchException() + sshkeyId := c.Ctx.Input.Param(":sshkey_id") + if err := sshkeyLogic.DeleteSshkey(c.logPoints, sshkeyId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} diff --git a/bmp-openapi-console/controllers/userController.go b/bmp-openapi-console/controllers/userController.go new file mode 100644 index 0000000..70f30ad --- /dev/null +++ b/bmp-openapi-console/controllers/userController.go @@ -0,0 +1,216 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/userLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type UserController struct { + BaseController +} + +// swagger:route GET /users user describeUsers +// DescribeUsers 获取用户列表 +// Responses: +// 200: describeUsers +// default: ErrorResponse + +func (c *UserController) DescribeUsers() { + defer c.CatchException() + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.QueryUsersRequest{ + UserName: c.GetString("userName"), + RoleID: c.GetString("roleId"), + DefaultProjectID: c.GetString("defaultProjectId"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + res, count, err := userLogic.GetUserList(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.UserList{ + Users: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } + +} + +// swagger:route GET /users/{user_id} user describeUser +// DescribeUser 获取用户详情 +// Responses: +// 200: describeUser +// default: ErrorResponse + +func (c *UserController) DescribeUser() { + defer c.CatchException() + userId := c.Ctx.Input.Param(":user_id") + res, err := userLogic.GetUserById(c.logPoints, userId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.UserInfo{ + User: res, + } +} + +// GetUserByName ... +// swagger:route GET /users/getUserByName user describeUserByName +// DescribeUserByName 根据用户名获取用户详情 +// Responses: +// 200: describeUserByName +// default: ErrorResponse +func (c *UserController) DescribeUserByName() { + defer c.CatchException() + req := &requestTypes.GetUserByNameRequest{ + UserName: c.GetString("userName"), + } + req.Validate(c.logPoints) + + res, err := userLogic.GetUserByName(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.UserInfo{ + User: res, + } +} + +// ModifyUser ... +// swagger:route PUT /users/{user_id} user modifyUser +// ModifyUser 修改用户信息 +// Responses: +// 200: modifyUser +// default: ErrorResponse + +func (c *UserController) ModifyUser() { + defer c.CatchException() + userId := c.Ctx.Input.Param(":user_id") + req := &requestTypes.ModifyUserRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyUser parse pUsert body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := userLogic.ModifyUser(c.logPoints, req, userId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// VerifyUser ... +// swagger:route POST /users/verify user verifyUser +// +// VerifyUser 鉴定用户 +// +// Responses: +// 200: verifyUser +// default: ErrorResponse + +func (c *UserController) VerifyUser() { + defer c.CatchException() + req := &requestTypes.VerifyUserRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateUser parse pUsert body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + isTrue := userLogic.VerifyUser(c.logPoints, req) + + c.Res.Result = response.CommonResponse{ + Success: isTrue, + } +} + +// DescribeLocalUser ... +// swagger:route GET /local/users user describeLocalUser +// DescribeLocalUser 控制台获取用户详情 +// Responses: +// 200: describeLocalUser +// default: ErrorResponse + +func (c *UserController) DescribeLocalUser() { + defer c.CatchException() + userId := c.logPoints.GetPoint("userId").(string) + res, err := userLogic.GetUserById(c.logPoints, userId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.UserInfo{ + User: res, + } +} + +// swagger:route PUT /local/users user modifyLocalUser +// +// ModifyLocalUser 控制台修改除密码外的个人信息 +// Responses: +// 200: modifyLocalUser +// default: ErrorResponse + +func (c *UserController) ModifyLocalUser() { + defer c.CatchException() + req := &requestTypes.ModifyLocalUserRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyUser parse pUsert body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := userLogic.ModifyLocalUser(c.logPoints, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// swagger:route PUT /local/users/password user modifyLocalUserPassword +// +// ModifyLocalUserPassword 控制台修改个人密码 +// Responses: +// 200: modifyLocalUserPassword +// default: ErrorResponse + +func (c *UserController) ModifyLocalUserPassword() { + defer c.CatchException() + req := &requestTypes.ModifyUserPasswordRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyLocalUserPassword parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := userLogic.ModifyUserPassword(c.logPoints, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} diff --git a/bmp-openapi-console/dao/apikeyDao/apikeyDao.go b/bmp-openapi-console/dao/apikeyDao/apikeyDao.go new file mode 100644 index 0000000..09b09a8 --- /dev/null +++ b/bmp-openapi-console/dao/apikeyDao/apikeyDao.go @@ -0,0 +1,124 @@ +package apikeyDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +// Apikey Apikey +type Apikey struct { + ID int `gorm:"primaryKey;column:id" json:"-"` + ApikeyID string `gorm:"column:apikey_id" json:"apikeyId"` // 秘钥对UUID + Name string `gorm:"column:name" json:"name"` // 秘钥对名称 + ReadOnly int8 `gorm:"column:read_only" json:"readOnly"` // 是否支持只读,read_only =1 的时候说明这个key是只读key,不能访问写方法。 + Token string `gorm:"column:token" json:"token"` // 32位字符令牌 + Type string `gorm:"column:type" json:"type"` // Token类型system/user + UserID string `gorm:"column:user_id" json:"userId"` // 所属用户 + Source string `gorm:"column:source" json:"source"` // 从console创建的还是从operation创建的 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Apikey) TableName() string { + return "apikey" +} + +// AddApikey insert a new Apikey into database and returns +// last inserted Id on success. +func AddApikey(logger *log.Logger, m *Apikey) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetApikeyById retrieves Apikey by Id. Returns error if +// Id doesn't exist +func GetApikeyById(logger *log.Logger, ApikeyId string) (v *Apikey, err error) { + v = &Apikey{} + err = dao.Where(logger, dao.IronicRdb, "apikey_id = ? and is_del = 0", ApikeyId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetApikeyByToken(logger *log.Logger, token string) (v *Apikey, err error) { + v = &Apikey{} + err = dao.Where(logger, dao.IronicRdb, "token = ? and is_del = 0", token).Take(v).Error + if err == gorm.ErrRecordNotFound { + return nil, nil + } + if err != nil { + return nil, err + } + + return v, nil +} + +// GetApikeyByUuid retrieves Apikey by Uuid. Returns error if +// Id doesn't exist +func GetApikeyCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Apikey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAllApikey retrieves all Apikey matches certain condition. Returns empty list if +// no records exist +func GetAllApikey(logger *log.Logger, query map[string]interface{}) (ml []*Apikey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Apikey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiApikey retrieves all Apikey matches certain condition. Returns empty list if +// no records exist +func GetMultiApikey(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Apikey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Apikey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateApikey updates Apikey by Id and returns error if +// the record to be updated doesn't exist +func UpdateApikeyById(logger *log.Logger, m *Apikey) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Apikey{}).Where("apikey_id = ?", m.ApikeyID).Updates(m).Error +} diff --git a/bmp-openapi-console/dao/auditLogsDao/auditLogsDao.go b/bmp-openapi-console/dao/auditLogsDao/auditLogsDao.go new file mode 100644 index 0000000..01abf22 --- /dev/null +++ b/bmp-openapi-console/dao/auditLogsDao/auditLogsDao.go @@ -0,0 +1,155 @@ +package auditLogsDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// 操作日志 +type AuditLogs struct { + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + Logid string `gorm:"column:logid;type:varchar(255);not null" json:"logid"` // log uuid + Sn string `gorm:"index:i_sn;column:sn;type:varchar(255);not null" json:"sn"` + DeviceID string `gorm:"index:i_device_id;column:device_id;type:varchar(255);not null" json:"device_id"` + InstanceID string `gorm:"index:i_instance_id;column:instance_id;type:varchar(255);not null" json:"instance_id"` + Operation string `gorm:"index:i_operation;column:operation;type:varchar(255);not null" json:"operation"` // action + OperateUserID string `gorm:"column:operate_user_id;type:varchar(255);not null" json:"operate_user_id"` // user_id + OperateUserName string `gorm:"column:operate_user_name;type:varchar(255);not null" json:"operate_user_name"` // user_name + Result string `gorm:"column:result;type:varchar(255);not null" json:"result"` // success/fail + FailReason string `gorm:"column:fail_reason;type:varchar(255);not null" json:"fail_reason"` // reason for fail // 完成时间戳 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 +} + +//var db *gorm.DB = dao.IronicRdb + +func (t *AuditLogs) TableName() string { + return "audit_logs" +} + +// AddCommand insert a new Command into database and returns +// last inserted Id on success. +func AddAuditLogs(logger *log.Logger, m *AuditLogs) (id int64, err error) { + m.CreatedTime = int(time.Now().Unix()) + m.UpdatedTime = int(time.Now().Unix()) + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetCommandById retrieves Command by Id. Returns error if +// Id doesn't exist +func GetAuditLogsById(logger *log.Logger, id int64) (v *AuditLogs, err error) { + v = &AuditLogs{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetCommandById retrieves Command by parentId. Returns error if +// Id doesn't exist +// GetCommandById retrieves Command by parentId. Returns error if +// Id doesn't exist +func GetAuditLogsByUUId(logger *log.Logger, uuid string) (v *AuditLogs, err error) { + v = &AuditLogs{} + err = dao.Where(logger, dao.IronicRdb, "logid = ? and is_del = 0", uuid).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetAuditLogsCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + db, err := dao.WhereBuild(dao.Model(logger, dao.IronicRdb, AuditLogs{}), query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} + +func GetAllAuditLogs(logger *log.Logger, query map[string]interface{}) (ml []*AuditLogs, err error) { + g := dao.Model(logger, dao.IronicRdb, AuditLogs{}) + g, err = dao.WhereBuild(g, query) + if err != nil { + return nil, err + } + err = g.Find(&ml).Error + return + +} + +// GetMultiCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetMultiAuditLogs(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*AuditLogs, err error) { + + var db = dao.Model(logger, dao.IronicRdb, AuditLogs{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func QueryAuditLogs(logger *log.Logger, query map[string]interface{}, offset, limit int64) (ml []*AuditLogs, err error) { + return GetMultiAuditLogs(logger, query, nil, []string{"created_time"}, []string{"desc"}, offset, limit) + /*var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return*/ +} + +func GetOneAuditLogs(logger *log.Logger, query map[string]interface{}) (l *AuditLogs, err error) { + l = &AuditLogs{} + var db = dao.Model(logger, dao.IronicRdb, AuditLogs{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// UpdateCommand updates Command by Id and returns error if +// the record to be updated doesn't exist +func UpdateAuditLogsById(logger *log.Logger, m *AuditLogs) (err error) { + + m.UpdatedTime = int(time.Now().Unix()) + err = dao.Model(logger, dao.IronicWdb, AuditLogs{}).Where("id = ?", m.ID).Updates(m).Error + return +} + +func UpdateMultiAuditLogs(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, AuditLogs{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} diff --git a/bmp-openapi-console/dao/baseDao.go b/bmp-openapi-console/dao/baseDao.go new file mode 100644 index 0000000..d91ac7c --- /dev/null +++ b/bmp-openapi-console/dao/baseDao.go @@ -0,0 +1,164 @@ +package dao + +import ( + "fmt" + "reflect" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + beego "github.com/beego/beego/v2/server/web" + + clog "coding.jd.com/aidc-bmp/bmp_log" + log "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +var ( + IronicRdb *gorm.DB + IronicWdb *gorm.DB +) + +type gLogger struct { + traceid string +} + +func (g *gLogger) Print(values ...interface{}) { + var ( + level = values[0] + // source = values[1] + ) + logPath, _ := beego.AppConfig.String("log.path") + logger := clog.New(logPath + "/bmp-openapi-sql.log") + defer logger.Flush() + logger.SetStableFields([]string{"sql", "args", "cost"}) + logger.Point("logid", g.traceid) + + if level == "sql" { + logger.Point("sql", values[3]) + logger.Point("args", values[4]) + logger.Point("cost", fmt.Sprint(values[2])) + } else { + logger.Point("trace", values) + } +} + +func InitGormDb(conn string) { + + doInit(conn) + //初始化时没有完成的,择机完成初始化 + go func() { + for { + time.Sleep(10 * time.Second) + if IronicRdb != nil && IronicRdb.DB().Stats().OpenConnections == 0 { + fmt.Println(time.Now().String(), "IronicRdb reInit......") + doInitIronicRdb(conn) + } + if IronicWdb != nil && IronicWdb.DB().Stats().OpenConnections == 0 { + fmt.Println(time.Now().String(), "IronicWdb reInit......") + doInitIronicWdb(conn) + } + } + }() + +} + +func doInit(conn string) { + doInitIronicRdb(conn) + doInitIronicWdb(conn) +} + +func doInitIronicRdb(conn string) { + var err error + IronicRdb, err = gorm.Open("mysql", conn) + if err != nil { + fmt.Println(time.Now(), "IronicRdb init error:", err.Error()) + return + } + IronicRdb.LogMode(true) + IronicRdb.DB().SetMaxOpenConns(100) + IronicRdb.DB().SetMaxIdleConns(20) +} + +func doInitIronicWdb(conn string) { + var err error + IronicWdb, err = gorm.Open("mysql", conn) + if err != nil { + fmt.Println(time.Now(), "IronicWdb init error:", err.Error()) + return + } + IronicWdb.LogMode(true) + IronicWdb.DB().SetMaxOpenConns(100) + IronicWdb.DB().SetMaxIdleConns(20) +} + +func GetGormTx(logger *clog.Logger) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := IronicWdb.New() + db.SetLogger(gl) + return db +} + +type NullType byte + +const ( + _ NullType = iota + // IsNull the same as `is null` + IsNull + // IsNotNull the same as `is not null` + IsNotNull +) + +// sql build where +func WhereBuild(g *gorm.DB, query map[string]interface{}) (*gorm.DB, error) { + logger := log.New("./log/ironic-api.log") + query["is_del"] = baseLogic.IS_NOT_DEL + for k, v := range query { + if reflect.TypeOf(v).Kind() == reflect.String { + if v.(string) == "" { + continue + } + } + ks := strings.Split(k, ".") + if len(ks) > 2 { + fmt.Println(time.Now(), fmt.Errorf("Error in query condition: %s. ", k)) + logger.Warn(fmt.Errorf("Error in query condition: %s. ", k)) + + return g, fmt.Errorf("Error in query condition: %s. ", k) + } + switch len(ks) { + case 1: + g = g.Where(fmt.Sprintf("%s = ?", k), v) + break + case 2: + k = ks[0] + switch ks[1] { + case "=": + g = g.Where(fmt.Sprintf("%s = ?", k), v) + break + case ">", "gt": + g = g.Where(fmt.Sprintf("%s > ?", k), v) + case ">=", "gte": + g = g.Where(fmt.Sprintf("%s >= ?", k), v) + break + case "<", "lt": + g = g.Where(fmt.Sprintf("%s < ?", k), v) + break + case "<=", "lte": + g = g.Where(fmt.Sprintf("%s <= ?", k), v) + break + case "!=", "<>": + g = g.Where(fmt.Sprintf("%s <> ?", k), v) + break + case "in": + g = g.Where(fmt.Sprintf("%s IN (?)", k), v) + break + case "like": + g = g.Where(fmt.Sprintf("%s LIKE ?", k), v) + break + } + break + } + } + return g, nil +} diff --git a/bmp-openapi-console/dao/commandDao/commandDao.go b/bmp-openapi-console/dao/commandDao/commandDao.go new file mode 100644 index 0000000..a6e6230 --- /dev/null +++ b/bmp-openapi-console/dao/commandDao/commandDao.go @@ -0,0 +1,129 @@ +package commandDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Command 指令 +type Command struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + RequestID string `gorm:"index:i_command_request_id;column:request_id;type:varchar(64);not null" json:"requestId"` // 请求ID + Sn string `gorm:"index:i_command_sn;column:sn;type:varchar(64);not null" json:"sn"` // 设备SN + InstanceID string `gorm:"index:i_command_instance_id;column:instance_id;type:varchar(36)" json:"instance_id"` // 实例Id + Action string `gorm:"column:action;type:varchar(32);not null" json:"action"` // 操作 + Type string `gorm:"column:type;type:varchar(16);not null" json:"type"` // 操作类型:agent, driver, network + Status string `gorm:"index:i_command_status;column:status;type:varchar(16)" json:"status"` // 状态: wait,running,finish,error + ParentCommandID int64 `gorm:"index:i_parent_command_id;column:parent_command_id;type:bigint(20) unsigned" json:"parent_command_id"` // 父指令Id + ExecuteCount int `gorm:"column:execute_count;type:int(10) unsigned;not null" json:"execute_count"` // 执行次数 + TimeoutTime time.Time `gorm:"column:timeout_time;type:datetime" json:"timeout_time"` // timeout time + TimeoutPolicy string `gorm:"column:timeout_policy;type:varchar(16)" json:"timeout_policy"` // timeout policy + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +//var db *gorm.DB = dao.IronicRdb + +func (t *Command) TableName() string { + return "command" +} + +// AddCommand insert a new Command into database and returns +// last inserted Id on success. +func AddCommand(logger *log.Logger, m *Command) (id int64, err error) { + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetCommandById retrieves Command by Id. Returns error if +// Id doesn't exist +func GetCommandById(logger *log.Logger, id int64) (v *Command, err error) { + v = &Command{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetCommandById retrieves Command by parentId. Returns error if +// Id doesn't exist +func GetCommandByParentId(logger *log.Logger, parentId int64) (v *Command, err error) { + v = &Command{} + err = dao.Where(logger, dao.IronicRdb, "parent_command_id = ? and is_del = 0", parentId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +//TODO map[string]string gorm为什么不支持 +func GetCommandCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + var db = dao.Model(logger, dao.IronicWdb, Command{}) + db, err = dao.WhereBuild(db, query) + err = db.Count(&n).Error + return +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetAllCommand(logger *log.Logger, query map[string]interface{}) (ml []*Command, err error) { + + var db = dao.Model(logger, dao.IronicWdb, Command{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetMultiCommand(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Command, err error) { + + var db = dao.Model(logger, dao.IronicWdb, Command{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateCommand updates Command by Id and returns error if +// the record to be updated doesn't exist +func UpdateCommandById(logger *log.Logger, m *Command) (err error) { + //m.UpdateTime = time.Now() + err = dao.Model(logger, dao.IronicWdb, Command{}).Where("id = ?", m.ID).Updates(m).Error + return +} + +func DeleteCommandBySn(logger *log.Logger, sn string) (err error) { + //m.UpdateTime = time.Now() + err = dao.Model(logger, dao.IronicWdb, Command{}).Where("sn = ? and status <> ?", sn, "finish").Update("is_del", 1).Error + return +} + +func DeleteCommandByInstanceId(logger *log.Logger, instanceId string) (err error) { + //m.UpdateTime = time.Now() + err = dao.Model(logger, dao.IronicWdb, Command{}).Where("instance_id = ? and status <> ?", instanceId, "finish").Update("is_del", 1).Error + return +} diff --git a/bmp-openapi-console/dao/createDao.go b/bmp-openapi-console/dao/createDao.go new file mode 100644 index 0000000..d7f5ade --- /dev/null +++ b/bmp-openapi-console/dao/createDao.go @@ -0,0 +1,36 @@ +package dao + +import ( + clog "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +// 插入单条记录,v2版本才支持插入多条记录? +//eg. db.Create(logger, rdb, u) +func Create(logger *clog.Logger, gdb *gorm.DB, out interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Create(out) +} + +//插入并获取刚插入数据的自增Id +//eg. db.CreateAndGetId(logger, rdb, u) +func CreateAndGetId(logger *clog.Logger, gdb *gorm.DB, out interface{}) (int64, error) { + // 事务约束,否则并发下可能获取到的是错误的id + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + tx := db.Begin() + if err := tx.Create(out).Error; err != nil { + tx.Rollback() + return 0, err + } + var id []int64 + if err := tx.Raw("select LAST_INSERT_ID() as id").Pluck("id", &id).Error; err != nil { + tx.Rollback() + return 0, err + } + tx.Commit() + return id[0], nil +} diff --git a/bmp-openapi-console/dao/deleteDao.go b/bmp-openapi-console/dao/deleteDao.go new file mode 100644 index 0000000..190aba8 --- /dev/null +++ b/bmp-openapi-console/dao/deleteDao.go @@ -0,0 +1,21 @@ +package dao + +import ( + clog "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +//删除记录 +//eg1.根据模型删除 +/* +food := Food{} +dao.Where(logger, rdb, "id = ?", 2).Take(&food).Delete(&food) +*/ +//eg2.根据Where条件删除数据 +// dao.Where(logger, rdb, "type = ?", 5).Delete(&Food{})//注意这里Delete函数需要传递一个空的模型变量指针 +func Delete(logger *clog.Logger, gdb *gorm.DB, value interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Delete(value, where...) +} diff --git a/bmp-openapi-console/dao/deviceDao/deviceDao.go b/bmp-openapi-console/dao/deviceDao/deviceDao.go new file mode 100644 index 0000000..d7f147a --- /dev/null +++ b/bmp-openapi-console/dao/deviceDao/deviceDao.go @@ -0,0 +1,382 @@ +package deviceDao + +import ( + "fmt" + "strconv" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/diskDao" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type Device struct { + ID int `gorm:"primaryKey;column:id" json:"id"` // 设备ID编号 + Sn string `gorm:"column:sn" json:"sn"` // 设备SN + DeviceID string `gorm:"column:device_id" json:"deviceId"` // 设备uuid + InstanceID string `gorm:"column:instance_id" json:"instanceId"` // 实例id + IDcID string `gorm:"column:idc_id" json:"idcId"` // 机型uuid + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型uuid + ManageStatus string `gorm:"column:manage_status" json:"manageStatus"` // 设备状态: 未装机,已装机 + UserId string `gorm:"column:user_id" json:"userId"` // 设备状态: 未装机,已装机 + UserName string `gorm:"column:user_name" json:"userName"` // 设备状态: 未装机,已装机 + Brand string `gorm:"column:brand" json:"brand"` // 品牌 + Model string `gorm:"column:model" json:"model"` // 型号 + DeviceSeries string `gorm:"column:device_series" json:"deviceSeries"` // 机型类型,如计算型,存储型 + Reason string `gorm:"column:reason" json:"reason"` // 设备状态变更失败原因 + Cabinet string `gorm:"column:cabinet" json:"cabinet"` // 机柜编码 + UPosition string `gorm:"column:u_position" json:"uPosition"` // U位 + IloIP string `gorm:"column:ilo_ip" json:"iloIp"` // 带外管理IP + IloUser string `gorm:"column:ilo_user" json:"iloUser"` // 带外账号 + IloPassword string `gorm:"column:ilo_password" json:"iloPassword"` // 带外账号密码 + Mac1 string `gorm:"column:mac1" json:"mac1"` // MAC1(eth0) + Mac2 string `gorm:"column:mac2" json:"mac2"` // MAC2(eth2) + SwitchIP1 string `gorm:"column:switch_ip1" json:"switchIp1"` // 交换机1ip + SwitchPort1 string `gorm:"column:switch_port1" json:"switchPort1"` // 交换机1port + SwitchIP2 string `gorm:"column:switch_ip2" json:"switchIp2"` // 交换机2ip + SwitchPort2 string `gorm:"column:switch_port2" json:"switchPort2"` // 交换机2port + SwitchUser1 string `gorm:"column:switch_user1" json:"switchUser1"` // 交换机1登录账号,如果为空,取所在机房的值 + SwitchPassword1 string `gorm:"column:switch_password1" json:"switchPassword1"` // 交换机1登录密码 + SwitchUser2 string `gorm:"column:switch_user2" json:"switchUser2"` // 交换机2登录账号,如果为空,取所在机房的值 + SwitchPassword2 string `gorm:"column:switch_password2" json:"switchPassword2"` // 交换机2登录密码 + Description string `gorm:"column:description" json:"description"` // 描述 + SwitchIP string `gorm:"column:switch_ip" json:"switchIp"` // 网口交换机IP + Mask string `gorm:"column:mask" json:"mask"` // 子网掩码 + MaskEth1 string `gorm:"column:mask_eth1" json:"mask_eth1"` // eth1子网掩码 + Gateway string `gorm:"column:gateway" json:"gateway"` // 网关地址 + PrivateIPv4 string `gorm:"column:private_ipv4" json:"privateIpv4"` // 内网IPV4 + PrivateEth1IPv4 string `gorm:"column:private_eth1_ipv4" json:"privateEth1Ipv4"` // eth1内网IPV4 + PrivateIPv6 string `gorm:"column:private_ipv6" json:"privateIpv6"` // 内网IPV6 + PrivateEth1IPv6 string `gorm:"column:private_eth1_ipv6" json:"privateEth1Ipv6"` // eth1内网IPV6 + Gateway6 string `gorm:"column:gateway6" json:"gateway6"` // IPV6网关地址 + AdapterID int `gorm:"column:adapter_id" json:"adapterId"` // adapter_id + RaidDriver string `gorm:"column:raid_driver" json:"raidDriver"` // raid工具:(megacli64等) + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 + Architecture string `gorm:"column:architecture" json:"architecture"` // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 +} + +func (t *Device) TableName() string { + return "device" +} + +func GetBySn(logger *log.Logger, sn string) (v *Device, err error) { + v = &Device{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and is_del = 0", sn).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetOneDevice(logger *log.Logger, query map[string]interface{}) (l *Device, err error) { + l = &Device{} + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetDeviceCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} + +// AddDevice insert a new Device into database and returns +// last inserted Id on success. +func AddDevice(logger *log.Logger, m *Device) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// //TODO 有时间试试gorm v2支持的批量插入 +func AddMultiDevice(logger *log.Logger, m []*Device) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, device := range m { + //device.CreateTime = time.Now() + //device.UpdateTime = time.Now() + if err := tx.Create(device).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} +func CreateDeviceAndDisk(logger *log.Logger, m []*Device, disks1, disks2 map[string]*diskDao.Disk) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, device := range m { + //device.CreateTime = time.Now() + //device.UpdateTime = time.Now() + if err := tx.Create(device).Error; err != nil { + tx.Rollback() + return 0, err + } + diskDao.AddDisk(logger, disks1[device.DeviceID]) + if disks2[device.DeviceID].Slot != 0 && disks2[device.DeviceID].Enclosure != "" { + diskDao.AddDisk(logger, disks2[device.DeviceID]) + } + + } + tx.Commit() + return int64(len(m)), nil +} + +// GetDeviceById retrieves Device by Id. Returns error if +// Id doesn't exist +func GetDeviceById(logger *log.Logger, deviceId string) (v *Device, err error) { + v = &Device{} + err = dao.Where(logger, dao.IronicRdb, "device_id = ? and is_del = 0", deviceId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetDeviceBySn retrieves Device by Sn. Returns error if +// Sn doesn't exist +func GetDeviceBySn(logger *log.Logger, sn string) (v *Device, err error) { + v = &Device{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and is_del = 0", sn).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +//获取所有设备,支持排序 +func GetAllDevices(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string) (ml []*Device, err error) { + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Find(&ml).Error + return +} + +// GetMultiDevice retrieves all Device matches certain condition. Returns empty list if +// no records exist +func GetMultiDevice(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Device, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// GetMultiDevice retrieves all Device matches certain condition. Returns empty list if +// no records exist +func GetAllDevice(logger *log.Logger, query map[string]interface{}) (ml []*Device, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetSingleDevice(logger *log.Logger, query map[string]interface{}) (l *Device, err error) { + l = &Device{} + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func UpdateMultiDevices(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +// UpdateDevice updates Device by Id and returns error if +// the record to be updated doesn't exist +func UpdateDeviceById(logger *log.Logger, m *Device) (err error) { + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicRdb, Device{}).Where("device_id = ?", m.DeviceID).Updates(m).Error +} +func SaveDevice(logger *log.Logger, m *Device) (err error) { + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicRdb, Device{}).Where("device_id = ?", m.DeviceID).Save(m).Error +} +func UpdateDeviceByDeviceTypeId(logger *log.Logger, m *Device) (err error) { + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicRdb, Device{}).Where("device_type_id = ? AND is_del = ?", m.DeviceTypeID, baseLogic.IS_NOT_DEL).Update(m).Error +} +func UpdateDeviceBySn(logger *log.Logger, m *Device) (err error) { + sql := `update device set instance_id='',user_id = '',user_name = '',manage_status="` + m.ManageStatus + `",reason='' ,updated_time = ` + strconv.Itoa(int(time.Now().Unix())) + ` where sn="` + m.Sn + `" and is_del = 0` + err = dao.IronicWdb.Exec(sql).Error + fmt.Println("UpdateDeviceBySn err", err) + return + //return dao.Model(logger, dao.IronicWdb, Device{}).Where("sn=? and is_del=?", m.Sn, "0").Save(m).Error +} +func GetFirstVersionDeviceSns(logger *log.Logger) (sns []string, err error) { + sql := `select distinct d.sn from device d left join command c on d.sn = c.sn where d.is_del=0 and d.sale_status = 'sold' and d.region = 'cn-north-1' and d.az != 'cn-north-1c'` + + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&sns).Error + return +} + +func GetFirstVersionAndReInstallDeviceSns(logger *log.Logger) (sns []string, err error) { + + sql := `select distinct d.sn from device d left join command c on d.sn = c.sn where d.is_del = 0 and d.sale_status = 'sold' and d.region = 'cn-north-1' and d.az != 'cn-north-1c' and c.action = 'WriteImage' and c.status = 'finish' and c.is_del = 0` + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&sns).Error + return +} + +type DeviceStock struct { + Total int64 `json:"total"` + Used int64 `json:"used"` + Available int64 `json:"available"` + Region string `json:"region"` + Az string `json:"az"` + DeviceType string `json:"device_type"` +} + +func GetDeviceStock(logger *log.Logger, device_type, region, az string) (ml []*DeviceStock, err error) { + + sql := `select region, az, device_type, count(id) as total, sum(if(sale_status = 'sold', 1, 0)) as used, sum(if(sale_status = 'selling', 1, 0)) as available from device where 1=1` + if region != "" { + sql = sql + fmt.Sprintf(" and region = '%s'", region) + } + if az != "" { + sql = sql + fmt.Sprintf(" and az = '%s'", az) + } + if device_type != "" { + sql = sql + fmt.Sprintf(" and device_type = '%s'", device_type) + } + sql = sql + " and is_del = 0 group by region,az,device_type" + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} + +type DDeviceIncludeSwitchIp struct { + *Device + SwitchIp string `json:"switch_ip"` +} + +func QueryIncludeSwitchIpByParam(logger *log.Logger, az, device_type, sale_status string) (ml []*DDeviceIncludeSwitchIp, err error) { + + sql := `select distinct switch_ip, d.* from device d left join interface i on d.sn = i.sn where 1=1` + if device_type != "" { + sql = sql + fmt.Sprintf(" and d.device_type = '%s'", device_type) + } + // if az != "" { + // sql = sql + fmt.Sprintf(" and d.az = '%s'", az) + // } + if sale_status != "" { + sql = sql + fmt.Sprintf(" and d.sale_status = '%s'", sale_status) + } + sql = sql + ` and d.is_del = 0 and i.is_del = 0` + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return + +} + +func DescribeInstanceStock(logger *log.Logger, param map[string][]string) (ml []*Device, err error) { + sql := `select id,sn,region,az,device_type,manufacturer_id,u_position,cabinet,ilo_ip,sale_status,create_time,update_time,is_del from device where 1=1` + + if param["regions"] != nil { + regions := []string{} + for _, v := range param["regions"] { + regions = append(regions, fmt.Sprintf("'%s'", v)) + } + sql = sql + fmt.Sprintf(" and region in (%s)", strings.Join(regions, ",")) + } + + if param["azs"] != nil { + azs := []string{} + for _, v := range param["azs"] { + azs = append(azs, fmt.Sprintf("'%s'", v)) + } + sql = sql + fmt.Sprintf(" and az in (%s)", strings.Join(azs, ",")) + } + + if param["deviceTypes"] != nil { + deviceTypes := []string{} + for _, v := range param["deviceTypes"] { + deviceTypes = append(deviceTypes, fmt.Sprintf("'%s'", v)) + } + sql = sql + fmt.Sprintf(" and device_type in (%s)", strings.Join(deviceTypes, ",")) + } + + if param["saleStatus"] != nil { + saleStatus := []string{} + for _, v := range param["saleStatus"] { + saleStatus = append(saleStatus, fmt.Sprintf("'%s'", v)) + } + sql = sql + fmt.Sprintf(" and sale_status in (%s)", strings.Join(saleStatus, ",")) + } else { + sql = sql + " and sale_status = 'selling'" + } + sql += " and is_del = 0" + + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-openapi-console/dao/deviceHintsDao/deviceHintsDao.go b/bmp-openapi-console/dao/deviceHintsDao/deviceHintsDao.go new file mode 100644 index 0000000..98f7479 --- /dev/null +++ b/bmp-openapi-console/dao/deviceHintsDao/deviceHintsDao.go @@ -0,0 +1,113 @@ +package deviceHintsDao + +import ( + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// DeviceHints 根设备所在磁盘 +type DeviceHints struct { + ID int64 `gorm:"unique;column:id;type:bigint(20) unsigned;not null" json:"id"` // 设备ID编号 + + Sn string `gorm:"column:sn;type:varchar(64);not null" json:"sn"` // 设备SN + //volume UUID + VolumeId string `gorm:"column:volume_id;type:varchar(128)" json:"volume_id"` + VolumeType string `gorm:"column:volume_type" json:"volumeType"` // 卷类型:系统卷,数据卷 + Size int64 `gorm:"column:size;type:bigint(20);not null" json:"size"` // 以GiB为单位的设备尺寸 + Rotational int8 `gorm:"column:rotational;type:tinyint(4);not null" json:"rotational"` // 转动,可以区分HDDs(旋转-磁盘)和SSDs(非旋转-固态硬盘) + Wwn string `gorm:"column:wwn;type:varchar(128)" json:"wwn"` // 唯一的存储标识符 + Name string `gorm:"column:name;type:varchar(64);not null" json:"name"` // 设备名称,例如/dev/md0 + WwnVendorExtension string `gorm:"column:wwn_vendor_extension;type:varchar(64)" json:"wwn_vendor_extension"` // 唯一的供应商存储标识符 + WwnWithExtension string `gorm:"column:wwn_with_extension;type:varchar(64)" json:"wwn_with_extension"` // 带有供应商附加扩展的唯一的存储标识符 + Model string `gorm:"column:model;type:varchar(64)" json:"model"` // 设备标识符 + Serial string `gorm:"column:serial;type:varchar(64)" json:"serial"` // 磁盘序列号 + Hctl string `gorm:"column:hctl;type:varchar(64)" json:"hctl"` // SCSI地址(主机名、channel通道、Target和Lun) + ByPath string `gorm:"column:by_path;type:varchar(128)" json:"by_path"` // 磁盘by_path路径 + Vendor string `gorm:"column:vendor;type:varchar(64)" json:"vendor"` // 设备供应商 + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *DeviceHints) TableName() string { + return "device_hints" +} + +// AddDeviceHints insert a new DeviceHints into database and returns +// last inserted Id on success. +func AddDeviceHints(logger *log.Logger, m *DeviceHints) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetDeviceHintsById retrieves DeviceHints by Id. Returns error if +// Id doesn't exist +func GetDeviceHintsById(logger *log.Logger, id int) (v *DeviceHints, err error) { + v = &DeviceHints{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetSystemVolumnDeviceHintsBySn(logger *log.Logger, sn string) (v *DeviceHints, err error) { + v = &DeviceHints{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and volume_type = 'system' and is_del = 0", sn).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetDeviceHintsBySnAndVolumeId(logger *log.Logger, sn, volume_id string) (v *DeviceHints, err error) { + v = &DeviceHints{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and volume_id = ? and is_del = 0", sn, volume_id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllDeviceHints retrieves all DeviceHints matches certain condition. Returns empty list if +// no records exist +func GetAllDeviceHints(logger *log.Logger, query map[string]interface{}) (ml []*DeviceHints, err error) { + + var db = dao.Model(logger, dao.IronicRdb, DeviceHints{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// UpdateDeviceHintsById updates DeviceHints by Id and returns error if +// the record to be updated doesn't exist +func UpdateDeviceHintsById(logger *log.Logger, m *DeviceHints) (err error) { + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, DeviceHints{}).Where("id = ?", m.ID).Updates(m).Error +} + +func DeleteDeviceHintsBySn(logger *log.Logger, sn string) (err error) { + + var db = dao.Model(logger, dao.IronicWdb, DeviceHints{}) + query := map[string]interface{}{ + "sn": sn, + "is_del": 0, + } + updates := map[string]interface{}{ + "is_del": 1, + "update_time": time.Now(), + } + + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} diff --git a/bmp-openapi-console/dao/deviceTypeDao/deviceTypeDao.go b/bmp-openapi-console/dao/deviceTypeDao/deviceTypeDao.go new file mode 100644 index 0000000..7989852 --- /dev/null +++ b/bmp-openapi-console/dao/deviceTypeDao/deviceTypeDao.go @@ -0,0 +1,198 @@ +package deviceTypeDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type DeviceType struct { + ID int `gorm:"primaryKey;column:id" json:"-"` // 主键 + IDcID string `gorm:"column:idc_id" json:"idcId"` // 机房id + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型uuid + Name string `gorm:"column:name" json:"name"` // 机型名称,如计算效能型,标准计算型 + DeviceType string `gorm:"column:device_type" json:"deviceType"` // 机型规格, cps.c.normal + DeviceSeries string `gorm:"column:device_series" json:"deviceSeries"` // 机型类型,如计算型,存储型 + Architecture string `gorm:"column:architecture" json:"architecture"` // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Height int `gorm:"column:height" json:"height"` // 【高度(U)】:显示机型高度 + Description string `gorm:"column:description" json:"description"` // 描述 + CpuSpec string `gorm:"column:cpu_spec" json:"cpuSpec"` // cpu预置类型 + CPUAmount int `gorm:"column:cpu_amount" json:"cpuAmount"` // cpu数量 + CPUCores int `gorm:"column:cpu_cores" json:"cpuCores"` // 单个cpu内核数 + CPUManufacturer string `gorm:"column:cpu_manufacturer" json:"cpuManufacturer"` // cpu厂商 + CPUModel string `gorm:"column:cpu_model" json:"cpuModel"` // cpu处理器型号 + CPUFrequency string `gorm:"column:cpu_frequency" json:"cpuFrequency"` // cpu频率(G) + MemSpec string `gorm:"column:mem_spec" json:"memSpec"` // cpu预置类型 + MemType string `gorm:"column:mem_type" json:"memType"` // 内存接口(如DDR3,DDR4) + MemSize int `gorm:"column:mem_size" json:"memSize"` // 单个内存大小(GB) + MemAmount int `gorm:"column:mem_amount" json:"memAmount"` // 内存数量 + MemFrequency int `gorm:"column:mem_frequency" json:"memFrequency"` // 内存主频(MHz) + NicAmount int `gorm:"column:nic_amount" json:"nicAmount"` // 网卡数量 + NicRate int `gorm:"column:nic_rate" json:"nicRate"` // 网卡传输速率(GE) + InterfaceMode string `gorm:"column:interface_mode" json:"interfaceMode"` // 【网口模式】【网络设置】: bond单网口,dual双网口 + SystemVolumeType string `gorm:"column:system_volume_type" json:"systemVolumeType"` // 系统盘类型(SSD,HDD) + SystemVolumeInterfaceType string `gorm:"column:system_volume_interface_type" json:"systemVolumeInterfaceType"` // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeSize int `gorm:"column:system_volume_size" json:"systemVolumeSize"` // 系统盘单盘大小 + SystemVolumeUnit string `gorm:"column:system_volume_unit" json:"systemVolumeUnit"` // 系统盘单盘大小单位 + SystemVolumeAmount int `gorm:"column:system_volume_amount" json:"systemVolumeAmount"` // 系统盘数量 + RaidCan string `gorm:"column:raid_can" json:"raidCan"` // 系统盘是否做raid【RAID/NO RAID】 + GpuAmount int `gorm:"column:gpu_amount" json:"gpuAmount"` // gpu数量 + GpuManufacturer string `gorm:"column:gpu_manufacturer" json:"gpuManufacturer"` // gpu厂商 + GpuModel string `gorm:"column:gpu_model" json:"gpuModel"` // gpu处理器型号 + DataVolumeType string `gorm:"column:data_volume_type" json:"dataVolumeType"` // 数据盘类型(SSD,HDD) + DataVolumeInterfaceType string `gorm:"column:data_volume_interface_type" json:"dataVolumeInterfaceType"` // 数据盘接口类型(SATA,SAS,NVME) + DataVolumeSize int `gorm:"column:data_volume_size" json:"dataVolumeSize"` // 数据盘单盘大小 + DataVolumeUnit string `gorm:"column:data_volume_unit" json:"dataVolumeUnit"` // 系统盘单盘大小单位 + DataVolumeAmount int `gorm:"column:data_volume_amount" json:"dataVolumeAmount"` // 数据盘数量 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间 + BootMode string `gorm:"column:boot_mode" json:"bootMode"` // boot类型:bios、uefi + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 + IsNeedRaid string `gorm:"column:is_need_raid" json:"isNeedRaid"` // 是否配置了阵列卡 +} + +func (t *DeviceType) TableName() string { + return "device_type" +} + +// AddDeviceType insert a new DeviceType into database and returns +// last inserted Id on success. +func AddDeviceType(logger *log.Logger, m *DeviceType) (id int64, err error) { + return dao.CreateAndGetId(logger, dao.IronicRdb, m) +} + +// GetDeviceTypeById retrieves DeviceType by Id. Returns error if +// Id doesn't exist +func GetDeviceTypeById(logger *log.Logger, deviceTypeId string) (v *DeviceType, err error) { + v = &DeviceType{} + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and is_del = 0", deviceTypeId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func QueryDeviceTypesCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} +func QueryAllDeviceTypes(logger *log.Logger, query map[string]interface{}) (ml []*DeviceType, err error) { //如果需要排序,在下面的代码中定义 + return GetMultiDeviceType(logger, query, nil, []string{"created_time"}, []string{"desc"}, 0, 0) +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func QueryDeviceTypes(logger *log.Logger, query map[string]interface{}, offset, limit int64) (ml []*DeviceType, err error) { + return GetMultiDeviceType(logger, query, nil, []string{"created_time"}, []string{"desc"}, offset, limit) + /*var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return*/ +} + +func GetOneDeviceType(logger *log.Logger, query map[string]interface{}) (l *DeviceType, err error) { + l = &DeviceType{} + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// GetMultiDeviceType retrieves all DeviceType matches certain condition. Returns empty list if +// no records exist +func GetMultiDeviceType(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*DeviceType, err error) { + + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateDeviceType updates DeviceType by Id and returns error if +// the record to be updated doesn't exist +func UpdateDeviceTypeByDeviceTypeID(logger *log.Logger, m *DeviceType, deviceTypeID string) (err error) { + //m.UpdateUser = logger.GetPoint("username").(string) + err = dao.Model(logger, dao.IronicWdb, DeviceType{}).Where("device_type_id = ?", deviceTypeID).Save(m).Error + return +} + +// GetAllDeviceTyp retrieves all DeviceTyp matches certain condition. Returns empty list if +// no records exist +func GetAllDeviceType(logger *log.Logger, query map[string]interface{}) (ml []*DeviceType, err error) { + + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} +func GetByAzAndDeviceType(logger *log.Logger, az, deviceType string) (l *DeviceType, err error) { + l = &DeviceType{} + query := map[string]interface{}{ + "is_del": "0", + "device_type": deviceType, + // "az": az, + } + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func QueryByAz(logger *log.Logger, az string) (ml []*DeviceType, err error) { + query := map[string]interface{}{ + "is_del": "0", + // "az": az, + } + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} diff --git a/bmp-openapi-console/dao/diskDao/diskDao.go b/bmp-openapi-console/dao/diskDao/diskDao.go new file mode 100644 index 0000000..148fb72 --- /dev/null +++ b/bmp-openapi-console/dao/diskDao/diskDao.go @@ -0,0 +1,110 @@ +package diskDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Disk Disk +type Disk struct { + ID int `gorm:"primaryKey;column:id" json:"-"` // ID + DeviceID string `gorm:"column:device_id" json:"deviceId"` // 设备uuid + Enclosure string `gorm:"column:enclosure" json:"enclosure"` // enclosure + Slot int `gorm:"column:slot" json:"slot"` // 卡槽槽位 + DiskType string `gorm:"column:disk_type" json:"diskType"` // 磁盘类型:system,data + Size string `gorm:"column:size" json:"size"` // 硬盘大小,不确定精度(非nvme盘) + SizeUnit string `gorm:"column:size_unit" json:"sizeUnit"` // 硬盘大小单位 MB GB TB ,1024进制 + PdType string `gorm:"column:pd_type" json:"pdType"` // 硬盘类型 + AdapterID int `gorm:"column:adapter_id" json:"adapterId"` // 适配ID + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Disk) TableName() string { + return "disk" +} + +// AddDisk insert a new Disk into database and returns +// last inserted Id on success. +func AddDisk(logger *log.Logger, m *Disk) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetDiskById retrieves Disk by Id. Returns error if +// Id doesn't exist +func GetDiskById(logger *log.Logger, id int64) (v *Disk, err error) { + v = &Disk{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetDiskByUuid retrieves Disk by Uuid. Returns error if +// Id doesn't exist +func GetDiskByUuid(logger *log.Logger, uuid string) (v *Disk, err error) { + v = &Disk{} + err = dao.Where(logger, dao.IronicRdb, "Disk_id = ? and is_del = 0", uuid).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllDisk retrieves all Disk matches certain condition. Returns empty list if +// no records exist +func GetAllDisk(logger *log.Logger, query map[string]interface{}) (ml []*Disk, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Disk{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiDisk retrieves all Disk matches certain condition. Returns empty list if +// no records exist +func GetMultiDisk(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Disk, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Disk{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateDisk updates Disk by Id and returns error if +// the record to be updated doesn't exist +func UpdateDiskById(logger *log.Logger, m *Disk) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Disk{}).Where("device_id = ?", m.DeviceID).Updates(m).Error +} diff --git a/bmp-openapi-console/dao/idcDao/idcDao.go b/bmp-openapi-console/dao/idcDao/idcDao.go new file mode 100644 index 0000000..6423547 --- /dev/null +++ b/bmp-openapi-console/dao/idcDao/idcDao.go @@ -0,0 +1,134 @@ +package idcDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type Idc struct { + ID int `gorm:"primaryKey;column:id" json:"id"` // ID + IDcID string `gorm:"column:idc_id" json:"idcId"` // 机房uuid + Name string `gorm:"column:name" json:"name"` + NameEn string `gorm:"column:name_en" json:"nameEn"` + Shortname string `gorm:"column:shortname" json:"shortname"` // 机房名称缩写 + Level string `gorm:"column:level" json:"level"` // 机房等级 + Address string `gorm:"column:address" json:"address"` // 机房地址 + IloUser string `gorm:"column:ilo_user" json:"iloUser"` // 带外登录账号 + IloPassword string `gorm:"column:ilo_password" json:"iloPassword"` // 带外登录密码 + SwitchUser1 string `gorm:"column:switch_user1" json:"switchUser1"` // 交换机1登录账号 + SwitchPassword1 string `gorm:"column:switch_password1" json:"switchPassword1"` // 交换机1登录密码 + SwitchUser2 string `gorm:"column:switch_user2" json:"switchUser2"` // 交换机2登录账号 + SwitchPassword2 string `gorm:"column:switch_password2" json:"switchPassword2"` // 交换机2登录密码 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Idc) TableName() string { + return "idc" +} + +// AddIdc insert a new Idc into database and returns +// last inserted Id on success. +func CreateIdc(logger *log.Logger, m *Idc) (id int64, err error) { + return dao.CreateAndGetId(logger, dao.IronicRdb, m) +} + +// GetIdcById retrieves Idc by Id. Returns error if +// Id doesn't exist +func GetIdcById(logger *log.Logger, idcId string) (v *Idc, err error) { + v = &Idc{} + err = dao.Where(logger, dao.IronicRdb, "idc_id = ? and is_del = 0", idcId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetOneIdc(logger *log.Logger, query map[string]interface{}) (l *Idc, err error) { + l = &Idc{} + var db = dao.Model(logger, dao.IronicRdb, Idc{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// GetAllIdc retrieves all Idc matches certain condition. Returns empty list if +// no records exist +func GetAllIdc(logger *log.Logger, query map[string]interface{}) (ml []*Idc, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Idc{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiIdc retrieves all Idc matches certain condition. Returns empty list if +// no records exist +func GetMultiIdc(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Idc, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Idc{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetIdcCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Idc{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return + +} + +// UpdateIdc updates Idc by Id and returns error if +// the record to be updated doesn't exist +func UpdateIdcById(logger *log.Logger, m *Idc, dcId string) (err error) { + return dao.Model(logger, dao.IronicWdb, Idc{}).Where("idc_id = ?", dcId).Save(m).Error +} + +//func DeleteIdcById(logger *log.Logger, m *Idc) (err error) { +// m.UpdatedBy = logger.GetPoint("username").(string) +// //m.UpdatedAt = time.Now().Unix() +// //m.De = time.Now().Unix() +// return dao.Model(logger, dao.IronicWdb, Idc{}).Where("idc_id = ?", m.DcId).Update(m).Error +//} + +func QueryByParam(logger *log.Logger, query map[string]interface{}, offset, limit int64) (ml []*Idc, err error) { + return GetMultiIdc(logger, query, nil, []string{"id"}, []string{"desc"}, offset, limit) +} diff --git a/bmp-openapi-console/dao/imageDao/imageDao.go b/bmp-openapi-console/dao/imageDao/imageDao.go new file mode 100644 index 0000000..a17bcdf --- /dev/null +++ b/bmp-openapi-console/dao/imageDao/imageDao.go @@ -0,0 +1,256 @@ +package imageDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Image 镜像 +type Image struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像uuid + ImageName string `gorm:"column:image_name" json:"imageName"` // 镜像名称 + //ImageVersion string `gorm:"column:image_version" json:"imageVersion"` // 镜像版本 + OsID string `gorm:"column:os_id" json:"osId"` // OSID + Format string `gorm:"column:format" json:"format"` // 镜像格式(qcow2、tar) + BootMode string `gorm:"column:boot_mode" json:"bootMode"` // boot类型:UEFI Legacy/BIOS + Filename string `gorm:"column:filename" json:"filename"` // 镜像文件名称 + URL string `gorm:"column:url" json:"url"` // 镜像源路径 + Hash string `gorm:"column:hash" json:"hash"` // 镜像校验码 + Source string `gorm:"column:source" json:"source"` // 镜像来源(common通用、customize定制、user_defined自定义) + Description string `gorm:"column:description" json:"description"` // 描述 + SystemPartition string `gorm:"column:system_partition" json:"systemPartition"` // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + DataPartition string `gorm:"column:data_partition" json:"dataPartition"` // 数据分区信息 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Image) TableName() string { + return "image" +} + +// AddImage insert a new Image into database and returns +// last inserted Id on success. +func AddImage(logger *log.Logger, m *Image) (id int64, err error) { + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetImageById retrieves Image by Id. Returns error if +// Id doesn't exist +func GetImageById(logger *log.Logger, id int64) (v *Image, err error) { + v = &Image{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetImageByUuid retrieves Image by Uuid. Returns error if +// Id doesn't exist +func GetImageByUuid(logger *log.Logger, imageId string) (v *Image, err error) { + v = &Image{} + err = dao.Where(logger, dao.IronicRdb, "image_id = ? and is_del = 0", imageId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} +func QueryImagesCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Image{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} +func GetAllImage(logger *log.Logger, query map[string]interface{}) (ml []*Image, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Image{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiImage retrieves all Image matches certain condition. Returns empty list if +// no records exist +func GetMultiImage(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Image, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Image{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateImage updates Image by Id and returns error if +// the record to be updated doesn't exist +func UpdateImageById(logger *log.Logger, m *Image) (err error) { + return dao.Model(logger, dao.IronicWdb, Image{}).Where("image_id = ?", m.ImageID).Save(m).Error +} + +type DImage struct { + ID uint64 `gorm:"primaryKey;column:id" json:"id"` // ID + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像uuid + ImageName string `gorm:"column:image_name" json:"imageName"` // 镜像名称 + //ImageVersion string `gorm:"column:image_version" json:"imageVersion"` // 镜像版本 + //OsID string `gorm:"column:os_id" json:"osId"` // OSID + Format string `gorm:"column:format" json:"format"` // 镜像格式(qcow2、tar) + BootMode string `gorm:"column:boot_mode" json:"bootMode"` // boot类型:UEFI Legacy/BIOS + Filename string `gorm:"column:filename" json:"filename"` // 镜像文件名称 + URL string `gorm:"column:url" json:"url"` // 镜像源路径 + Hash string `gorm:"column:hash" json:"hash"` // 镜像校验码 + Source string `gorm:"column:source" json:"source"` // 镜像来源(common通用、customize定制、user_defined自定义) + Description string `gorm:"column:description" json:"description"` // 描述 + SystemPartition string `gorm:"column:system_partition" json:"systemPartition"` // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + DataPartition string `gorm:"column:data_partition" json:"dataPartition"` // 数据分区信息 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 + + OsID string `json:"OsId"` + OsName string `json:"osName"` + OsVersion string `json:"osVersion"` + OsType string `json:"osType"` + //Platform string `json:"platform"` + Architecture string `json:"architecture"` + Bits int32 `json:"bits"` + //CreatedBy int `json:"createdBy"` + //UpdatedBy int `json:"updatedBy"` + //CreatedTime int `json:"createdTime"` + //UpdatedTime int `json:"updatedTime"` +} + +func ConvertIn(str string) string { + arr := strings.Split(str, ",") + sqlIn := "" + for _, v := range arr { + sqlIn = sqlIn + "'" + v + "'" + "," + } + sqlIn = strings.Trim(sqlIn, ",") + return "(" + sqlIn + ")" +} + +// QueryByDeviceOsType ... +func GetImageAndOsList(logger *log.Logger, param map[string]interface{}, count bool, offset int64, limit int64) (ml []*DImage, n int64, err error) { + raw := "*" + if count { + raw = "count(*)" + } + sql := `select ` + raw + ` FROM image i,os o where i.os_id=o.os_id and i.is_del=0 and o.is_del=0` + //fmt.Println(param) + if param["image_id"] != nil && param["image_id"] != "" { + sql = sql + " and i.image_id=" + fmt.Sprintf("'%s'", param["image_id"]) + } + if param["image_name"] != nil && param["image_name"] != "" { + sql = sql + " and i.image_name like \"%" + param["image_name"].(string) + "%\"" + } + if param["source"] != nil && param["source"] != "" { + sql = sql + " and i.source in " + ConvertIn(param["source"].(string)) + } + if param["os_type"] != nil && param["os_type"] != "" { + sql = sql + " and o.os_type in " + ConvertIn(param["os_type"].(string)) + } + if param["architecture"] != nil && param["architecture"] != "" { + sql = sql + " and o.architecture in " + ConvertIn(param["architecture"].(string)) + } + if param["device_type_id"] != nil && param["device_type_id"] != "" { + sql = sql + " and i.image_id not in (select image_id from r_device_type_image where device_type_id = '" + param["device_type_id"].(string) + "' and is_del = 0)" + } + sql = sql + " order by i.created_time desc" + if count { + err = dao.Raw(logger, dao.IronicRdb, sql).Count(&n).Error + return + } + if offset == 0 && limit == 0 { + fmt.Println(sql) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return + } + fmt.Println(sql) + logger.Info("查询镜像,os sql:", sql) + err = dao.Raw(logger, dao.IronicRdb, sql).Offset(offset).Limit(limit).Scan(&ml).Error + return +} + +// QueryByDeviceOsType ... +func QueryByDeviceOsType(logger *log.Logger, param map[string]string) (ml []*DImage, err error) { + + sql := `select i.id,i.image_id,i.image_name,i.image_version,i.format,i.boot_mode,i.url,i.filename,i.description,i.os_id,i.hash,i.source, + i.created_by,i.updated_by,i.created_time,i.updated_time FROM image i` + if param["device_type"] != "" { + sql = sql + " LEFT JOIN r_device_type_image rd on i.uuid=rd.image_id" + } + if param["region"] != "" { + sql = sql + " LEFT JOIN r_region_image re on i.uuid=re.image_id" + } + sql = sql + " LEFT JOIN os o on i.os_id=o.os_id" + where := " where 1 = 1" + if param["device_type"] != "" { + where = where + " and rd.device_type=" + fmt.Sprintf("'%s'", param["device_type"]) + } + if param["region"] != "" { + where = where + " and re.region=" + fmt.Sprintf("'%s'", param["region"]) + } + if param["os_type"] != "" { + where = where + " and o.os_type=" + fmt.Sprintf("'%s'", param["os_type"]) + } + if param["os_version"] != "" { + where = where + " and o.os_version=" + fmt.Sprintf("'%s'", param["os_version"]) + } + if param["os_id"] != "" { + where = where + " and i.os_id=" + fmt.Sprintf("'%s'", param["os_id"]) + } + if param["name_en"] != "" { + where = where + fmt.Sprintf(" and i.name_en LIKE '%%s%'", param["name_en"]) + } + if param["image_ids"] != "" { + imageIds := strings.Split(param["image_ids"], ",") + for idx, v := range imageIds { + imageIds[idx] = fmt.Sprintf("'%s'", v) + } + inSql := fmt.Sprintf("(%s)", strings.Join(imageIds, ",")) + where = where + fmt.Sprintf(" and i.uuid in %s", inSql) + } + if param["source"] != "" { + where = where + fmt.Sprintf(" and i.source='%s'", param["source"]) + } + if param["device_type"] != "" { + where = where + " and rd.is_del=0" + } + if param["region"] != "" { + where = where + " and re.is_del=0" + } + sql = sql + where + " and i.is_del=0 and o.is_del=0" + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-openapi-console/dao/instanceDao/instanceDao.go b/bmp-openapi-console/dao/instanceDao/instanceDao.go new file mode 100644 index 0000000..c1d1b2a --- /dev/null +++ b/bmp-openapi-console/dao/instanceDao/instanceDao.go @@ -0,0 +1,180 @@ +package instanceDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Instance Instance +type Instance struct { + ID int `gorm:"primaryKey;column:id" json:"-"` + InstanceID string `gorm:"column:instance_id" json:"instanceId"` // 实例ID(uuid) + IDcID string `gorm:"column:idc_id" json:"idcId"` // 机房uuid + ProjectID string `gorm:"column:project_id" json:"projectId"` // 项目id + UserID string `gorm:"column:user_id" json:"userId"` // 用户uuid + InstanceName string `gorm:"column:instance_name" json:"instanceName"` // 实例名称 + DeviceID string `gorm:"column:device_id" json:"deviceId"` // 设备uuid + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 机型uuid + Hostname string `gorm:"column:hostname" json:"hostname"` // 主机名 + Status string `gorm:"column:status" json:"status"` // 失败原因 + Reason string `gorm:"column:reason" json:"reason"` // 运行状态 + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像uuid + SystemVolumeRaidID string `gorm:"column:system_volume_raid_id" json:"systemVolumeRaidId"` // 系统盘raid + Locked string `gorm:"column:locked" json:"locked"` // 是否锁定解锁锁定:locked,解锁unlocked + DataVolumeRaidID string `gorm:"column:data_volume_raid_id" json:"dataVolumeRaidId"` // 数据盘raid + Description string `gorm:"column:description" json:"description"` // 描述 + BootMode string `gorm:"column:boot_mode" json:"bootMode"` // boot类型:UEFI Legacy/BIOS + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 + //是否安装了agent,0->未安装,1->已安装 + IsInstalledAgent string `gorm:"column:is_installed_agent" json:"isInstalledAgent"` +} + +func (t *Instance) TableName() string { + return "instance" +} + +// AddInstance insert a new Instance into database and returns +// last inserted Id on success. +func AddInstance(logger *log.Logger, m *Instance) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetInstanceById retrieves Instance by Id. Returns error if +// Id doesn't exist +func GetInstanceByName(logger *log.Logger, name string) (v *Instance, err error) { + v = &Instance{} + err = dao.Where(logger, dao.IronicRdb, "instance_name = ? and is_del = 0", name).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetInstanceById retrieves Instance by Id. Returns error if +// Id doesn't exist +func GetInstanceById(logger *log.Logger, InstanceId string) (v *Instance, err error) { + v = &Instance{} + err = dao.Where(logger, dao.IronicRdb, "instance_id = ? and is_del = 0", InstanceId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetInstancesByIds retrieves Instance by Ids. Returns error if +// Id doesn't exist +func GetInstancesByIds(logger *log.Logger, InstanceIds []string) (v []*Instance, err error) { + q := map[string]interface{}{ + "instance_id.in": InstanceIds, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, q) + if err != nil { + return nil, err + } + err = db.Find(&v).Error + return +} + +// GetInstanceById retrieves Instance by Id. Returns error if +// Id doesn't exist +func GetInstanceByDeviceId(logger *log.Logger, DeviceId string) (v *Instance, err error) { + v = &Instance{} + err = dao.Where(logger, dao.IronicRdb, "device_id = ? and is_del = 0", DeviceId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetInstanceByUuid retrieves Instance by Uuid. Returns error if +// Id doesn't exist +func GetInstanceCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAllInstance retrieves all Instance matches certain condition. Returns empty list if +// no records exist +func GetAllInstance(logger *log.Logger, query map[string]interface{}) (ml []*Instance, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiInstance retrieves all Instance matches certain condition. Returns empty list if +// no records exist +func GetMultiInstance(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Instance, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateInstance updates Instance by Id and returns error if +// the record to be updated doesn't exist +func UpdateInstanceById(logger *log.Logger, m *Instance) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Instance{}).Where("instance_id = ?", m.InstanceID).Updates(m).Error +} + +// description为空也有可能 +func UpdateInstanceAnywhere(logger *log.Logger, m *Instance) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Instance{}).Save(m).Error +} + +func UpdateInstances(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return + +} diff --git a/bmp-openapi-console/dao/instancePartitionDao/instancePartitionDao.go b/bmp-openapi-console/dao/instancePartitionDao/instancePartitionDao.go new file mode 100644 index 0000000..62799c3 --- /dev/null +++ b/bmp-openapi-console/dao/instancePartitionDao/instancePartitionDao.go @@ -0,0 +1,142 @@ +package instancePartitionDao + +import ( + "time" + + log "coding.jd.com/aidc-bmp/bmp_log" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" +) + +// InstancePartition 实例分区表 +type InstancePartition struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + InstanceID string `gorm:"column:instance_id" json:"instanceId"` // 实例ID + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像ID + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型 + BootMode string `gorm:"column:boot_mode" json:"bootMode"` // boot类型:bios、uefi + PartitionType string `gorm:"column:partition_type" json:"partitionType"` // 分区类型:root、boot、system、data + PartitionSize int `gorm:"column:partition_size" json:"partitionSize"` // 分区大小,单位MB + PartitionFsType string `gorm:"column:partition_fs_type" json:"partitionFsType"` // 文件系统类型:xfs + PartitionMountPoint string `gorm:"column:partition_mount_point" json:"partitionMountPoint"` // 分区目录 + PartitionLabel string `gorm:"column:partition_label" json:"partitionLabel"` // 分区标签:l_分区目录 + SystemDiskLabel string `gorm:"column:system_disk_label" json:"systemDiskLabel"` // 系统盘分区格式:gpt、msdos(做完RAID系统盘大于4T必用gpt) + DataDiskLabel string `gorm:"column:data_disk_label" json:"dataDiskLabel"` // 数据盘分区格式:gpt、msdos + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除(0-未删, 1-已删) + InstancePartitionID string `gorm:"column:instance_partition_id" json:"instancePartitionId"` // 实例分区uuID + Number int `gorm:"column:number" json:"number"` // 每个实例的分区序号 +} + +func (t *InstancePartition) TableName() string { + return "instance_partition" +} + +// AddInstancePartition insert a new InstancePartition into database and returns +// last inserted Id on success. +func AddInstancePartition(logger *log.Logger, m *InstancePartition) (id int64, err error) { + + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// //TODO 有时间试试gorm v2支持的批量插入 +func AddMultiInstancePartition(logger *log.Logger, m []*InstancePartition) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, instancePartition := range m { + if err := tx.Create(instancePartition).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetInstancePartitionById retrieves InstancePartition by Id. Returns error if +// Id doesn't exist +func GetInstancePartitionById(logger *log.Logger, id int64) (v *InstancePartition, err error) { + v = &InstancePartition{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllInstancePartition retrieves all InstancePartition matches certain condition. Returns empty list if +// no records exist +func GetAllInstancePartition(logger *log.Logger, query map[string]interface{}) (ml []*InstancePartition, err error) { + + var db = dao.Model(logger, dao.IronicRdb, InstancePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetOneInstancePartition(logger *log.Logger, query map[string]interface{}) (l *InstancePartition, err error) { + l = &InstancePartition{} + var db = dao.Model(logger, dao.IronicRdb, InstancePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// UpdateInterface updates Interface by Id and returns error if +// the record to be updated doesn't exist +func UpdateInstancePartitionById(logger *log.Logger, m *InstancePartition) (err error) { + return dao.Model(logger, dao.IronicWdb, InstancePartition{}).Where(logger, dao.IronicRdb, "id = ?", m.ID).Updates(m).Error +} + +func GetBySn(logger *log.Logger, sn string) (ml []*InstancePartition, err error) { + ml = []*InstancePartition{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and is_del = 0", sn).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil + +} + +func GetByInstanceId(logger *log.Logger, instanceId string) (ml []*InstancePartition, err error) { + ml = []*InstancePartition{} + err = dao.Where(logger, dao.IronicRdb, "instance_id = ? and is_del = 0", instanceId).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil + +} + +func DeletePartitionsByInstanceId(logger *log.Logger, instanceId string) (err error) { + + query := map[string]interface{}{ + "instance_id": instanceId, + } + + updates := map[string]interface{}{ + "is_del": 1, + "updated_time": time.Now().Unix(), + } + var db = dao.Model(logger, dao.IronicWdb, InstancePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} diff --git a/bmp-openapi-console/dao/instanceUserDataDao/instanceUserDataDao.go b/bmp-openapi-console/dao/instanceUserDataDao/instanceUserDataDao.go new file mode 100644 index 0000000..2c3d69b --- /dev/null +++ b/bmp-openapi-console/dao/instanceUserDataDao/instanceUserDataDao.go @@ -0,0 +1,104 @@ +package instanceUserDataDao + +import ( + "time" + + log "coding.jd.com/aidc-bmp/bmp_log" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" +) + +// InstanceUserData 用户自定义脚本表 +type InstanceUserData struct { + ID uint64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"-"` // ID + InstanceID string `gorm:"unique;column:instance_id;type:varchar(36);not null" json:"instance_id"` // 实例ID + UserData string `gorm:"column:user_data;type:mediumtext" json:"user_data"` // 用户自定义脚本 + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(3) unsigned;not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *InstanceUserData) TableName() string { + return "instance_user_data" +} + +// AddInstanceUserData insert a new InstanceUserData into database and returns +// last inserted Id on success. +func AddInstanceUserData(logger *log.Logger, m *InstanceUserData) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// //TODO 有时间试试gorm v2支持的批量插入 +func AddMultiInstanceUserData(logger *log.Logger, m []*InstanceUserData) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, instanceUserData := range m { + instanceUserData.CreateTime = time.Now() + instanceUserData.UpdateTime = time.Now() + if err := tx.Create(instanceUserData).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetInstanceUserDataById retrieves InstanceUserData by Id. Returns error if +// Id doesn't exist +func GetInstanceUserDataById(logger *log.Logger, id int64) (v *InstanceUserData, err error) { + v = &InstanceUserData{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllInstanceUserData retrieves all InstanceUserData matches certain condition. Returns empty list if +// no records exist +func GetAllInstanceUserData(logger *log.Logger, query map[string]interface{}) (ml []*InstanceUserData, err error) { + + var db = dao.Model(logger, dao.IronicRdb, InstanceUserData{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetOneInstanceUserData(logger *log.Logger, query map[string]interface{}) (l *InstanceUserData, err error) { + l = &InstanceUserData{} + var db = dao.Model(logger, dao.IronicRdb, InstanceUserData{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// UpdateInstanceUserDataById updates InstanceUserData by Id and returns error if +// the record to be updated doesn't exist +func UpdateInstanceUserDataById(logger *log.Logger, m *InstanceUserData) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, InstanceUserData{}).Where(logger, dao.IronicRdb, "id = ?", m.ID).Updates(m).Error +} + +func GetByInstanceId(logger *log.Logger, instanceId string) (l *InstanceUserData, err error) { + l = &InstanceUserData{} + err = dao.Where(logger, dao.IronicRdb, "instance_id = ? and is_del = 0", instanceId).Take(l).Error + if err != nil { + return nil, err + } + return l, nil + +} diff --git a/bmp-openapi-console/dao/interfaceDao/interfaceDao.go b/bmp-openapi-console/dao/interfaceDao/interfaceDao.go new file mode 100644 index 0000000..dbf3690 --- /dev/null +++ b/bmp-openapi-console/dao/interfaceDao/interfaceDao.go @@ -0,0 +1,157 @@ +package interfaceDao + +import ( + "fmt" + "strings" + "time" + + log "coding.jd.com/aidc-bmp/bmp_log" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" +) + +type Interface struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + InterfaceName string `gorm:"column:interface_name;type:varchar(16)" json:"interface_name"` // 网卡名称 + InterfaceType string `gorm:"column:interface_type;type:varchar(16)" json:"interface_type"` // 网卡类型:lan/wan + Sn string `gorm:"index:i_interface_sn;column:sn;type:varchar(64);not null" json:"sn"` // 设备SN + Mac string `gorm:"column:mac;type:varchar(32);not null" json:"mac"` // MAC + SwitchIP string `gorm:"column:switch_ip;type:varchar(32);not null" json:"switch_ip"` // 内网交换机IP + SwitchPort string `gorm:"column:switch_port;type:varchar(32);default:null" json:"switch_port"` // 内网交换机Port + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删。1-已删) +} + +func (t *Interface) TableName() string { + return "interface" +} + +// AddInterface insert a new Interface into database and returns +// last inserted Id on success. +func AddInterface(logger *log.Logger, m *Interface) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetInterfaceById retrieves Interface by Id. Returns error if +// Id doesn't exist +func GetInterfaceById(logger *log.Logger, id int64) (v *Interface, err error) { + v = &Interface{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetAllInterface(logger *log.Logger, query map[string]interface{}) (ml []*Interface, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Interface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetOneInterface(logger *log.Logger, query map[string]interface{}) (l *Interface, err error) { + l = &Interface{} + var db = dao.Model(logger, dao.IronicRdb, Interface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// GetAllInterface retrieves all Interface matches certain condition. Returns empty list if +// no records exist +func GetMultiInterface(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Interface, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Interface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateInterface updates Interface by Id and returns error if +// the record to be updated doesn't exist +func UpdateInterfaceById(logger *log.Logger, m *Interface) (err error) { + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Interface{}).Where(logger, dao.IronicRdb, "id = ?", m.ID).Updates(m).Error +} +func DeleteInterfaceBySn(logger *log.Logger, m *Interface) (err error) { + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Interface{}).Where("sn = ?", m.Sn).Delete(m).Error +} +func UpdateMultiInterfaces(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["update_time"] = time.Now() + var db = dao.Model(logger, dao.IronicWdb, Interface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +type DInterface struct { + Sn string `json:"sn"` + InterfaceName string `json:"interface_name"` + InterfaceType string `json:"interface_type"` + Mac string `json:"mac"` + SwitchIp string `json:"switch_ip"` + SwitchPort string `json:"switch_port"` + PodName string `json:"pod_name"` + PodRoom string `json:"pod_room"` + CreateTime time.Time `json:"create_time"` + UpdateTime time.Time `json:"update_time"` +} + +func GetBySn(logger *log.Logger, sn string) (ml []*Interface, err error) { + + ml = []*Interface{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and is_del = 0", sn).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil + +} + +func GetBySns(logger *log.Logger, sns []string) (ml []*DInterface, err error) { + + sql := `select i.sn,i.interface_name,i.interface_type,i.mac,i.switch_ip,i.switch_port,i.create_time,i.update_time,n.name as pod_name,n.room as pod_room FROM interface i LEFT JOIN jd_switch j ON i.switch_ip = j.switch_ip LEFT JOIN net_pod n ON j.pod_id=n.id where 1=1` + for idx, v := range sns { + sns[idx] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and i.sn in (%s) and i.is_del=0 and j.is_del=0 and n.is_del=0", strings.Join(sns, ",")) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-openapi-console/dao/jdBondInterfaceDao/jdBondInterfaceDao.go b/bmp-openapi-console/dao/jdBondInterfaceDao/jdBondInterfaceDao.go new file mode 100644 index 0000000..65bff0f --- /dev/null +++ b/bmp-openapi-console/dao/jdBondInterfaceDao/jdBondInterfaceDao.go @@ -0,0 +1,90 @@ +package jdBondInterfaceDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// JdBondInterface 零售中台网络端口Bond表 +type JdBondInterface struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // 自增id + GroupID int `gorm:"column:group_id;type:int(11)" json:"group_id"` // 端口聚合组ID + Sn string `gorm:"index:i_sn;column:sn;type:varchar(64);not null" json:"sn"` // 设备sn + SwitchIP string `gorm:"index:i_switchIp;column:switch_ip;type:varchar(32);not null" json:"switch_ip"` // 交换机ip + PrivateIP string `gorm:"column:private_ip;type:varchar(30)" json:"private_ip"` // 内网IP + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime;not null" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(2);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *JdBondInterface) TableName() string { + return "jd_bond_interface" +} + +// AddJdBondInterface insert a new JdBondInterface into database and returns +// last inserted Id on success. +func AddJdBondInterface(logger *log.Logger, m *JdBondInterface) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetJdBondInterfaceById retrieves JdBondInterface by Id. Returns error if +// Id doesn't exist +func GetJdBondInterfaceById(logger *log.Logger, id int64) (v *JdBondInterface, err error) { + v = &JdBondInterface{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetAllJdBondInterface(logger *log.Logger, query map[string]interface{}) (ml []*JdBondInterface, err error) { + + var db = dao.Model(logger, dao.IronicRdb, JdBondInterface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiJdBondInterface retrieves all JdBondInterface matches certain condition. Returns empty list if +// no records exist +func GetMultiJdBondInterface(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*JdBondInterface, err error) { + + var db = dao.Model(logger, dao.IronicRdb, JdBondInterface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateJdBondInterface updates JdBondInterface by Id and returns error if +// the record to be updated doesn't exist +func UpdateJdBondInterfaceById(logger *log.Logger, m *JdBondInterface) (err error) { + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, JdBondInterface{}).Where(logger, dao.IronicRdb, "id = ?", m.ID).Updates(m).Error //update 有问题,参考下面这个方法 +} +func DeleteJdBondInterfaceBySn(logger *log.Logger, m *JdBondInterface) (err error) { + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, JdBondInterface{}).Where("sn = ?", m.Sn).Updates(m).Error +} diff --git a/bmp-openapi-console/dao/jdSwitchDao/jdSwitchDao.go b/bmp-openapi-console/dao/jdSwitchDao/jdSwitchDao.go new file mode 100644 index 0000000..9de7b17 --- /dev/null +++ b/bmp-openapi-console/dao/jdSwitchDao/jdSwitchDao.go @@ -0,0 +1,125 @@ +package jdSwitchDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// JdSwitch 零售中台网络交换机表 +type JdSwitch struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // 自增id + Region string `gorm:"unique;column:region;type:varchar(32);not null" json:"region"` // region + SwitchIP string `gorm:"unique;column:switch_ip;type:varchar(32);not null" json:"switch_ip"` // 交换机ip + Cidr string `gorm:"column:cidr;type:varchar(32)" json:"cidr"` // 配置的内网cidr + Mask string `gorm:"column:mask;type:varchar(32)" json:"mask"` // 配置的内网掩码 + Gateway string `gorm:"column:gateway;type:varchar(32)" json:"gateway"` // 配置的网关 + PodID int `gorm:"column:pod_id;type:int(11)" json:"pod_id"` // pod网络id + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime;not null" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(2);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *JdSwitch) TableName() string { + return "jd_switch" +} + +// AddJdSwitch insert a new JdSwitch into database and returns +// last inserted Id on success. +func AddJdSwitch(logger *log.Logger, m *JdSwitch) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetJdSwitchById retrieves JdSwitch by Id. Returns error if +// Id doesn't exist +func GetJdSwitchById(logger *log.Logger, id int64) (v *JdSwitch, err error) { + v = &JdSwitch{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetOneJdSwitch(logger *log.Logger, query map[string]interface{}) (l *JdSwitch, err error) { + l = &JdSwitch{} + var db = dao.Model(logger, dao.IronicRdb, JdSwitch{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetSwitchCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, JdSwitch{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return + +} + +// GetAllJdSwitch retrieves all JdSwitch matches certain condition. Returns empty list if +// no records exist +func GetAllJdSwitch(logger *log.Logger, query map[string]interface{}) (ml []*JdSwitch, err error) { + + var db = dao.Model(logger, dao.IronicRdb, JdSwitch{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiJdSwitch retrieves pages JdSwitch matches certain condition. Returns empty list if +// no records exist +func GetMultiJdSwitch(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*JdSwitch, err error) { + + var db = dao.Model(logger, dao.IronicRdb, JdSwitch{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateJdSwitch updates JdSwitch by Id and returns error if +// the record to be updated doesn't exist +func UpdateJdSwitchById(logger *log.Logger, m *JdSwitch) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, JdSwitch{}).Where("id = ?", m.ID).Updates(m).Error +} + +func GetBySwitchIp(logger *log.Logger, switch_ip string) (v *JdSwitch, err error) { + v = &JdSwitch{} + err = dao.Where(logger, dao.IronicRdb, "switch_ip = ? and is_del = 0", switch_ip).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} diff --git a/bmp-openapi-console/dao/mailDao/mailDao.go b/bmp-openapi-console/dao/mailDao/mailDao.go new file mode 100644 index 0000000..41b590e --- /dev/null +++ b/bmp-openapi-console/dao/mailDao/mailDao.go @@ -0,0 +1,68 @@ +package mailDao + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// MailMessage message +type MailMessage struct { + //以下为消息通用字段 + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + // 邮件服务器地址 + ServerAddr string `gorm:"column:server_addr;type:varchar(255);not null" json:"server_addr"` + // 邮件服务器端口 + ServerPort string `gorm:"column:server_port;type:varchar(255);not null" json:"server_port"` + // 管理员邮箱 + AdminAddr string `gorm:"column:admin_addr;type:varchar(255);not null" json:"admin_addr"` + // 管理员邮箱密码 + AdminPass string `gorm:"column:admin_pass;type:varchar(255);not null" json:"admin_pass"` + //收件人邮箱 + To string `gorm:"column:to;type:varchar(255);not null" json:"to"` + // 是否推送邮件告警0不推送,1推送 + IsPush string `gorm:"column:is_push;type:type:varchar(8);not null" json:"is_push"` + // 是否删除0未删除 1已删除 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` +} + +func (t *MailMessage) TableName() string { + return "mail_message" +} + +// AddMailMessage insert a new Os into database and returns +// last inserted Id on success. +func AddMailMessage(logger *log.Logger, m *MailMessage) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetMailMessage retrieves Os by Id. Returns error if +// Id doesn't exist +func GetMailMessage(logger *log.Logger) (v *MailMessage, err error) { + v = &MailMessage{} + err = dao.Where(logger, dao.IronicRdb, "is_del = 0").Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func UpdateMailMessage(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, MailMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func UpdateMailAnywhere(logger *log.Logger, m *MailMessage) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, MailMessage{}).Save(m).Error +} diff --git a/bmp-openapi-console/dao/manufacturerDao/manufacturerDao.go b/bmp-openapi-console/dao/manufacturerDao/manufacturerDao.go new file mode 100644 index 0000000..37d39af --- /dev/null +++ b/bmp-openapi-console/dao/manufacturerDao/manufacturerDao.go @@ -0,0 +1,87 @@ +package manufacturerDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Manufacturer 产品型号信息 +type Manufacturer struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + DeviceType string `gorm:"column:device_type;type:varchar(100);not null" json:"device_type"` // 设备类型 + Manufacturer string `gorm:"column:manufacturer;type:varchar(64);not null" json:"manufacturer"` // 厂商 + ProductName string `gorm:"column:product_name;type:varchar(128);not null" json:"product_name"` // 产品型号名称 + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除:1删除,0未删除 +} + +func (t *Manufacturer) TableName() string { + return "manufacturer" +} + +// AddManufacturer insert a new Manufacturer into database and returns +// last inserted Id on success. +func AddManufacturer(logger *log.Logger, m *Manufacturer) (id int64, err error) { + + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetManufacturerById retrieves Manufacturer by Id. Returns error if +// Id doesn't exist +func GetManufacturerById(logger *log.Logger, id int64) (v *Manufacturer, err error) { + v = &Manufacturer{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllManufacturer retrieves all Manufacturer matches certain condition. Returns empty list if +// no records exist +func GetAllManufacturer(logger *log.Logger, query map[string]interface{}) (ml []*Manufacturer, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Manufacturer{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetMultiManufacturer(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Manufacturer, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Manufacturer{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateManufacturer updates Manufacturer by Id and returns error if +// the record to be updated doesn't exist +func UpdateManufacturerById(logger *log.Logger, m *Manufacturer) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Manufacturer{}).Where("id = ?", m.ID).Updates(m).Error +} diff --git a/bmp-openapi-console/dao/messageDao/messageDao.go b/bmp-openapi-console/dao/messageDao/messageDao.go new file mode 100644 index 0000000..5b8f941 --- /dev/null +++ b/bmp-openapi-console/dao/messageDao/messageDao.go @@ -0,0 +1,208 @@ +package messageDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// WebMessage message +type WebMessage struct { + //以下为消息通用字段 + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + // message uuid + MessageID string `gorm:"column:message_id;type:varchar(255);not null" json:"message_id"` + // user_id + UserID string `gorm:"index:i_message_userid;column:user_id;type:varchar(255);not null" json:"user_id"` + // user_name + UserName string `gorm:"column:user_name;type:varchar(255);not null" json:"user_name"` + // 资源类型 实例/设备 + ResourceType string `gorm:"column:resource_type;type:varchar(255);not null" json:"resource_type"` + // 操作结果 fail/succ + Result string `gorm:"column:result;type:varchar(255);not null" json:"result"` + // 消息时间戳 + FinishTime int `gorm:"column:finish_time;type:int(11);not null" json:"finish_time"` + // 0未读, 1已读 + HasRead int8 `gorm:"index:i_message_read;column:has_read;type:tinyint(4);not null" json:"has_read"` + // 是否删除0未删除 1已删除 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` + // 消息类型 + MessageType string `gorm:"column:message_type;type:varchar(255);not null" json:"message_type"` + // 消息子类型 + MessageSubType string `gorm:"column:message_sub_type;type:varchar(255);not null" json:"message_sub_type"` + //实例id + InstanceID string `gorm:"column:instance_id;type:varchar(255);not null" json:"instance_id"` + // 实例name + InstanceName string `gorm:"column:instance_name;type:varchar(255);not null" json:"instance_name"` + //设备sn + SN string `gorm:"column:sn;type:varchar(255);not null" json:"sn"` + // 详情, 带外监控日志的详情请用content + Detail string `gorm:"column:detail;type:varchar(4096);not null" json:"detail"` + + //故障类型, 带外故障消息专属字段 + FaultType string `gorm:"column:fault_type;type:varchar(10);not null" json:"fault_type"` + //故障内容,带外故障消息专属字段 + Content string `gorm:"column:content;type:varchar(4096);not null" json:"content"` + //系统原始日志id, 带外故障消息专属字段 + LogID string `gorm:"column:logid;type:varchar(256);not null" json:"logid"` + //故障告警时间,带外故障消息专属字段 + AlertTime int `gorm:"column:alert_time;type:int(11);not null" json:"alert_time"` + //告警次数,始终为1,带外故障消息专属字段 + AlertCount int `gorm:"column:alert_count;type:int(11);not null" json:"alert_count"` + + //版本名称, 许可证到期消息专属字段 + LicenseName string `gorm:"column:license_name;type:varchar(64);not null" json:"license_name"` + //版本号, 许可证到期消息专属字段 + LicenseNumber string `gorm:"column:license_number;type:varchar(64);not null" json:"license_number"` + //开始时间, 许可证到期消息专属字段 + LienseStartTime int `gorm:"column:license_start_time;type:int(11);not null" json:"license_start_time"` + //结束时间, 许可证到期消息专属字段 + LienseEndTime int `gorm:"column:license_end_time;type:int(11);not null" json:"license_end_time"` + //inbond rule uuid + RuleID string `gorm:"column:rule_id;type:varchar(256);not null" json:"rule_id"` + //inbond rule name + RuleName string `gorm:"column:rule_name;type:varchar(256);not null" json:"rule_name"` + IsRecover int8 `gorm:"column:is_recover;type:tinyint(4);not null" json:"is_recover"` // 是否为恢复通知,0不是,1是 +} + +func (t *WebMessage) TableName() string { + return "web_message" +} + +// AddWebMessage insert a new Os into database and returns +// last inserted Id on success. +func AddWebMessage(logger *log.Logger, m *WebMessage) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetOsById retrieves Os by Id. Returns error if +// Id doesn't exist +func GetLatestUnreadWebMessageByUserId(logger *log.Logger, userId string) (v *WebMessage, err error) { + v = &WebMessage{} + err = dao.Where(logger, dao.IronicRdb, "user_id = ? and has_read = 0 and is_del = 0", userId).Order("id desc").Limit(1).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// func GetLatestUnreadWebMessageByUserId(logger *log.Logger, userId string) (v *WebMessage, err error) { +// v = &WebMessage{} +// err = dao.Where(logger, dao.IronicRdb, "user_id = ? and is_del = 0", userId).Take(v).Error +// if err != nil { +// return nil, err +// } +// return v, nil +// } + +// GetAllOs retrieves all os matches certain condition. Returns empty list if +// no records exist +func GetAllWebMessagesByUserId(logger *log.Logger, userId string) (ml []*WebMessage, err error) { + + query := map[string]interface{}{ + "user_id": userId, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicRdb, WebMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return + +} + +func GetWebMessagesByUserIdCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, WebMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetMultiOs retrieves all Os matches certain condition. Returns empty list if +// no records exist +func GetMultiWebMessagesByUserId(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*WebMessage, err error) { + + var db = dao.Model(logger, dao.IronicRdb, WebMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetAllWebMessages(logger *log.Logger, query map[string]interface{}) (ml []*WebMessage, err error) { + + var db = dao.Model(logger, dao.IronicRdb, WebMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// UpdateOs updates Os by Id and returns error if +// the record to be updated doesn't exist +func UpdateWebMessageId(logger *log.Logger, m *WebMessage) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, WebMessage{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateWebMessages(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, WebMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return + +} + +// GetOsById retrieves Os by Id. Returns error if +// Id doesn't exist +func GetOneWebMessage(logger *log.Logger, query map[string]interface{}, idOrder string) (v *WebMessage, err error) { + v = &WebMessage{} + var db = dao.Model(logger, dao.IronicWdb, WebMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if idOrder == "desc" { + err = db.Order("id desc").Limit(1).Take(v).Error + } else { + err = db.Order("id asc").Limit(1).Take(v).Error + } + + if err != nil { + return nil, err + } + return v, nil +} diff --git a/bmp-openapi-console/dao/monitorAlertDao/monitorAlertDao.go b/bmp-openapi-console/dao/monitorAlertDao/monitorAlertDao.go new file mode 100644 index 0000000..4d96e21 --- /dev/null +++ b/bmp-openapi-console/dao/monitorAlertDao/monitorAlertDao.go @@ -0,0 +1,156 @@ +package monitorAlertDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// MonitorAlerts 告警历史表 +type MonitorAlerts struct { + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + AlertID string `gorm:"index:i_rule_id;column:alert_id;type:varchar(255);not null" json:"alert_id"` // alert uuid + AlertTime int `gorm:"column:alert_time;type:int(11);not null" json:"alert_time"` // 告警时间戳 + RuleID string `gorm:"index:i_rule_id;column:rule_id;type:varchar(255);not null" json:"rule_id"` // rule uuid + RuleName string `gorm:"column:rule_name;type:varchar(255);not null" json:"rule_name"` // rule name + Resource string `gorm:"column:resource;type:varchar(255);not null" json:"resource"` // 资源类型 [只支持instance一种] + ResourceID string `gorm:"column:resource_id;type:varchar(255);not null" json:"resource_id"` // 资源id,目前就是实例id + ResourceName string `gorm:"column:resource_name;type:varchar(255);not null" json:"resource_name"` // 资源名称,目前就是实例名称 + Trigger string `gorm:"column:trigger;type:varchar(255);not null" json:"trigger"` // 触发条件,接口需要翻译 + AlertValue string `gorm:"column:alert_value;type:varchar(255);not null" json:"alert_value"` // 报警值 + CalculationUnit string `gorm:"column:calculation_unit;type:varchar(255);not null" json:"calculation_unit"` // 单位,%,GB,bps等,个没有单位 + AlertLevel int8 `gorm:"column:alert_level;type:tinyint(4);not null" json:"alert_level"` // 1表示一般,2表示严重,3表示紧急 + AlertPeriod int `gorm:"column:alert_period;type:int(11);not null" json:"alert_period"` // 告警持续时间(分钟为单位) + UserID string `gorm:"column:user_id;type:varchar(255);not null" json:"user_id"` // 通知对象 userid + UserName string `gorm:"column:user_name;type:varchar(255);not null" json:"user_name"` // 通知对象 用户名 + CreatedTime int `gorm:"column:created_time;type:int(11);not null" json:"created_time"` // 创建时间戳 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 + IsRecover int8 `gorm:"column:is_recover;type:tinyint(4);not null" json:"is_recover"` // 是否为恢复通知,0不是,1是 + ProjectID string `gorm:"column:project_id" json:"project_id"` // 项目uuid +} + +func (t *MonitorAlerts) TableName() string { + return "monitor_alerts" +} + +// AddWebMessage insert a new Os into database and returns +// last inserted Id on success. +func AddMonitorAlerts(logger *log.Logger, m *MonitorAlerts) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func GetMonitorAlertsById(logger *log.Logger, alertId string) (v *MonitorAlerts, err error) { + v = &MonitorAlerts{} + err = dao.Where(logger, dao.IronicRdb, "alert_id = ? and is_del = 0", alertId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllOs retrieves all os matches certain condition. Returns empty list if +// no records exist +func GetAllMonitorAlertsByUserId(logger *log.Logger, userId string) (ml []*MonitorAlerts, err error) { + + query := map[string]interface{}{ + "user_id": userId, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicRdb, MonitorAlerts{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return + +} + +func GetAllMonitorAlertsByRuleId(logger *log.Logger, RuleId string) (ml []*MonitorAlerts, err error) { + + query := map[string]interface{}{ + "rule_id": RuleId, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicRdb, MonitorAlerts{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return + +} + +func GetMonitorAlertsCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, MonitorAlerts{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetMultiOs retrieves all Os matches certain condition. Returns empty list if +// no records exist +func GetMultiMonitorAlerts(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*MonitorAlerts, err error) { + + var db = dao.Model(logger, dao.IronicRdb, MonitorAlerts{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetAllMonitorAlerts(logger *log.Logger, query map[string]interface{}) (ml []*MonitorAlerts, err error) { + + var db = dao.Model(logger, dao.IronicRdb, MonitorAlerts{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// UpdateOs updates Os by Id and returns error if +// the record to be updated doesn't exist +func UpdateMonitorAlerts(logger *log.Logger, m *MonitorAlerts) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, MonitorAlerts{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateMultiMonitorAlerts(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, MonitorAlerts{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return + +} diff --git a/bmp-openapi-console/dao/monitorRuleDao/monitorRuleDao.go b/bmp-openapi-console/dao/monitorRuleDao/monitorRuleDao.go new file mode 100644 index 0000000..e3ddbc6 --- /dev/null +++ b/bmp-openapi-console/dao/monitorRuleDao/monitorRuleDao.go @@ -0,0 +1,136 @@ +package monitorRuleDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// MonitorRules 带内监控规则表 +type MonitorRules struct { + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + RuleID string `gorm:"index:i_rule_id;column:rule_id;type:varchar(255);not null" json:"rule_id"` // rule uuid + Status int8 `gorm:"column:status;type:tinyint(4);not null" json:"status"` // 1表示启用 2表示不启用 3表示已告警 + RuleName string `gorm:"column:rule_name;type:varchar(255);not null" json:"rule_name"` // 规则名称 + Dimension string `gorm:"column:dimension;type:varchar(255);not null" json:"dimension"` // 维度 [instance disk mountpoint nic] + Resource string `gorm:"column:resource;type:varchar(255);not null" json:"resource"` // 资源类型 [只支持instance一种] + TriggerOption string `gorm:"column:trigger_option;type:varchar(255);not null" json:"trigger_option"` // 触发条件, json + NoticeOption string `gorm:"column:notice_option;type:varchar(255);not null" json:"notice_option"` // 通知策略, json + CreatedTime int `gorm:"column:created_time;type:int(11);not null" json:"created_time"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time;type:int(11);not null" json:"updated_time"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time;type:int(11);not null" json:"deleted_time"` // 更新时间戳 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 + UserID string `gorm:"column:user_id;type:varchar(255);not null" json:"user_id"` // user uuid + UserName string `gorm:"column:user_name;type:varchar(255);not null" json:"user_name"` // user name + ProjectID string `gorm:"column:project_id" json:"project_id"` // 项目uuid +} + +func (t *MonitorRules) TableName() string { + return "monitor_rules" +} + +// AddWebMessage insert a new Os into database and returns +// last inserted Id on success. +func AddMonitorRules(logger *log.Logger, m *MonitorRules) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func GetMonitorRuleById(logger *log.Logger, ruleId string) (v *MonitorRules, err error) { + v = &MonitorRules{} + err = dao.Where(logger, dao.IronicRdb, "rule_id = ? and is_del = 0", ruleId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllOs retrieves all os matches certain condition. Returns empty list if +// no records exist +func GetAllMonitorRulesByUserId(logger *log.Logger, userId string) (ml []*MonitorRules, err error) { + + query := map[string]interface{}{ + "user_id": userId, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicRdb, MonitorRules{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return + +} + +func GetMonitorRulesCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, MonitorRules{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetMultiOs retrieves all Os matches certain condition. Returns empty list if +// no records exist +func GetMultiMonitorRules(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*MonitorRules, err error) { + + var db = dao.Model(logger, dao.IronicRdb, MonitorRules{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetAllMonitorRules(logger *log.Logger, query map[string]interface{}) (ml []*MonitorRules, err error) { + + var db = dao.Model(logger, dao.IronicRdb, MonitorRules{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// UpdateOs updates Os by Id and returns error if +// the record to be updated doesn't exist +func UpdateMonitorRules(logger *log.Logger, m *MonitorRules) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, MonitorRules{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateMultiMonitorRules(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, MonitorRules{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return + +} diff --git a/bmp-openapi-console/dao/osDao/osDao.go b/bmp-openapi-console/dao/osDao/osDao.go new file mode 100644 index 0000000..1e8be30 --- /dev/null +++ b/bmp-openapi-console/dao/osDao/osDao.go @@ -0,0 +1,110 @@ +package osDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Os os +type Os struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + OsID string `gorm:"column:os_id" json:"osId"` // 操作系统uuid + OsName string `gorm:"column:os_name" json:"OsName"` // 操作系统名称 + OsType string `gorm:"column:os_type" json:"osType"` // 操作系统分类:linux/windows + //Platform string `gorm:"column:platform" json:"platform"` // suse/centos/ubuntu + Architecture string `gorm:"column:architecture" json:"architecture"` // 架构:x86/x64/i386/ + Bits int `gorm:"column:bits" json:"bits"` // 指令宽度:64/32位 + OsVersion string `gorm:"column:os_version" json:"osVersion"` // 操作系统版本 + SysUser string `gorm:"column:sys_user" json:"sysUser"` // 管理员账户 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Os) TableName() string { + return "os" +} + +// AddOs insert a new Os into database and returns +// last inserted Id on success. +func AddOs(logger *log.Logger, m *Os) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetOsById retrieves Os by Id. Returns error if +// Id doesn't exist +func GetOsById(logger *log.Logger, id int64) (v *Os, err error) { + v = &Os{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetOsByUuid retrieves Os by Uuid. Returns error if +// Id doesn't exist +func GetOsByUuid(logger *log.Logger, uuid string) (v *Os, err error) { + v = &Os{} + err = dao.Where(logger, dao.IronicRdb, "os_id = ? and is_del = 0", uuid).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllOs retrieves all os matches certain condition. Returns empty list if +// no records exist +func GetAllOs(logger *log.Logger, query map[string]interface{}) (ml []*Os, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Os{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiOs retrieves all Os matches certain condition. Returns empty list if +// no records exist +func GetMultiOs(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Os, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Os{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateOs updates Os by Id and returns error if +// the record to be updated doesn't exist +func UpdateOsById(logger *log.Logger, m *Os) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Os{}).Where("os_id = ?", m.OsID).Updates(m).Error +} diff --git a/bmp-openapi-console/dao/projectDao/projectDao.go b/bmp-openapi-console/dao/projectDao/projectDao.go new file mode 100644 index 0000000..064d119 --- /dev/null +++ b/bmp-openapi-console/dao/projectDao/projectDao.go @@ -0,0 +1,220 @@ +package projectDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Project Project +type Project struct { + ID int `gorm:"primaryKey;column:id" json:"-"` + ProjectID string `gorm:"column:project_id" json:"projectId"` // 项目uuid + ProjectName string `gorm:"column:project_name" json:"projectName"` // 项目名称 + Description string `gorm:"column:description" json:"description"` // 项目描述 + IsDefault int8 `gorm:"column:is_default" json:"isDefault"` // 是否默认项目0否 1是 + IsSystem int8 `gorm:"column:is_system" json:"isSystem"` // 是否系统项目 0否 1是 + UserID string `gorm:"column:user_id" json:"userId"` // 项目拥有者用户id + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Project) TableName() string { + return "project" +} + +// AddProject insert a new Project into database and returns +// last inserted Id on success. +func AddProject(logger *log.Logger, m *Project) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetProjectById retrieves Project by Id. Returns error if +// Id doesn't exist +func GetProjectById(logger *log.Logger, ProjectId string) (v *Project, err error) { + v = &Project{} + err = dao.Where(logger, dao.IronicRdb, "project_id = ? and is_del = 0", ProjectId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetProjectByUuid retrieves Project by Uuid. Returns error if +// Id doesn't exist +func GetProjectCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Project{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +type AllProject struct { + Project + //1表示拥有,2表示共享 + Owned int `gorm:"column:owned" json:"owned"` +} + +// GetProjectAndSharedCount retrieves Project by Uuid. Returns error if +// Id doesn't exist +func GetProjectAndSharedCount(logger *log.Logger, user_id string, owned int) (n int64, err error) { + leftsql := fmt.Sprintf(`select a.project_id, a.project_name, a.user_id, a.created_time, 1 as owned from project a where a.is_del = 0 and a.user_id = '%s'`, user_id) + rightsql := fmt.Sprintf(`select b.project_id, b.project_name, b.shared_user_id as user_id, b.created_time, 2 as owned from sharing_project b where b.is_del = 0 and b.shared_user_id = '%s'`, user_id) + var sql string + if owned == 1 { //只查有拥有权的项目 + sql = fmt.Sprintf(`select count(*) from (%s) c`, leftsql) + } else if owned == 2 { //只查有共享权的项目 + sql = fmt.Sprintf(`select count(*) from (%s) c`, rightsql) + } else { //查有拥有权和共享权的项目 + sql = fmt.Sprintf(`select count(*) from (%s union %s) c`, leftsql, rightsql) + } + err = dao.Raw(logger, dao.IronicRdb, sql).Count(&n).Error + return +} + +// GetAllProject retrieves all Project matches certain condition. Returns empty list if +// no records exist +func GetAllProject(logger *log.Logger, query map[string]interface{}) (ml []*Project, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Project{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Order("id ASC").Find(&ml).Error + return +} + +func GetAllProjectByUserId(logger *log.Logger, userId string) (ml []*Project, err error) { + + query := map[string]interface{}{ + "user_id": userId, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicRdb, Project{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Order("id ASC").Find(&ml).Error + return +} + +func GetAllProjectIncludeShare(logger *log.Logger, user_id string, owned int) (ml []*AllProject, err error) { + + leftsql := fmt.Sprintf(`select a.is_default, a.project_id, a.project_name, a.user_id, a.created_time, a.updated_time, 1 as owned from project a where a.is_del = 0 and a.user_id = '%s'`, user_id) + rightsql := fmt.Sprintf(`select 0 as is_default, b.project_id, b.project_name, b.shared_user_id as user_id, m.created_time as created_time, m.updated_time as updated_time, 2 as owned from sharing_project b join project m on b.project_id = m.project_id where b.is_del = 0 and b.shared_user_id = '%s'`, user_id) + var sql string + if owned == 1 { //只查有拥有权的项目 + sql = fmt.Sprintf(`select c.* from (%s) c`, leftsql) + } else if owned == 2 { //只查有共享权的项目,暂时还用不到 + sql = fmt.Sprintf(`select c.* from (%s) c`, rightsql) + } else { //查有拥有权和共享权的项目 + sql = fmt.Sprintf(`select c.* from (%s union %s) c order by c.created_time desc`, leftsql, rightsql) + } + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} + +// GetMultiProject retrieves all Project matches certain condition. Returns empty list if +// no records exist +func GetMultiProject(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Project, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Project{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetMultiProjectIncludeShare(logger *log.Logger, user_id string, owned int, sortby []string, order []string, + offset int64, limit int64) (ml []*AllProject, err error) { + + leftsql := fmt.Sprintf(`select a.is_default, a.project_id, a.project_name, a.user_id, a.created_time, a.updated_time, 1 as owned from project a where a.is_del = 0 and a.user_id = '%s'`, user_id) + rightsql := fmt.Sprintf(`select 0 as is_default, b.project_id, b.project_name, b.shared_user_id as user_id, m.created_time as created_time, m.updated_time as updated_time, 2 as owned from sharing_project b join project m on b.project_id = m.project_id where b.is_del = 0 and b.shared_user_id = '%s'`, user_id) + var sql string + if owned == 1 { //只查有拥有权的项目 + sql = fmt.Sprintf(`select c.* from (%s) c`, leftsql) + } else if owned == 2 { //只查有共享权的项目,暂时还用不到 + sql = fmt.Sprintf(`select c.* from (%s) c`, rightsql) + } else { //查有拥有权和共享权的项目 + sql = fmt.Sprintf(`select c.* from (%s union %s) c`, leftsql, rightsql) + } + + db := dao.Raw(logger, dao.IronicRdb, sql) + + // if len(sortby) == 0 { + // db = db.Order("c.created_time desc") + // } else { + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + // } + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateProject updates Project by Id and returns error if +// the record to be updated doesn't exist +func UpdateProjectById(logger *log.Logger, m *Project) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Project{}).Where("project_id = ?", m.ProjectID).Updates(m).Error +} + +func UpdateProjectByMap(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + var db = dao.Model(logger, dao.IronicWdb, Project{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func UpdateUserDefaultProject(logger *log.Logger, userId, projectId string) error { + err := dao.IronicWdb.Exec("update project set is_default = 0 where is_del = 0 and user_id = ?", userId).Error + if err != nil { + return err + } + + err = dao.IronicWdb.Exec("update project set is_default = 1 where project_id = ?", projectId).Error + if err != nil { + return err + } + return nil +} diff --git a/bmp-openapi-console/dao/queryDao.go b/bmp-openapi-console/dao/queryDao.go new file mode 100644 index 0000000..8931f0c --- /dev/null +++ b/bmp-openapi-console/dao/queryDao.go @@ -0,0 +1,131 @@ +package dao + +import ( + clog "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +// SELECT * FROM `foods` LIMIT 1 +//eg. db.Take(logger, rdb, &food) +func Take(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Take(out, where...) +} + +// SELECT * FROM `foods` ORDER BY `foods`.`id` ASC LIMIT 1 +//eg. db.First(logger, rdb, &food) +func First(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.First(out, where...) +} + +// SELECT * FROM `foods` ORDER BY `foods`.`id` DESC LIMIT 1 +//eg. db.Last(logger, rdb, &food) +func Last(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Last(out, where...) +} + +// SELECT * FROM `foods` 可单可复 +//eg. db.Find(logger, rdb, &foods) +func Find(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Find(out, where...) +} + +// // 查询一列值 +//eg. Model(Food{}).Pluck("title", &titles) +// func Pluck(logger *clog.Logger, model interface{}, column string, target interface{}) error { +// //等价于:SELECT title FROM `foods` 提取了title字段,保存到titles变量 +// //这里Model函数是为了绑定一个模型实例,可以从里面提取表名。 +// gl := &gLogger{traceid: logger.GetPoint("logid").(string)} +// db := gdb.New() +// db.SetLogger(gl) +// return gdb.Model(model).Pluck("title", target).Error +// } + +// 设置where条件 +//eg. dao.Where(logger, rdb, "id = ?", 10).Take(&food) +//eg. dao.Where(logger, rdb, "id in (?)", []int{1,2,5,6}).Take(&food) +//eg. dao.Where(logger, rdb, "create_time >= ? and create_time <= ?", "2018-11-06 00:00:00", "2018-11-06 23:59:59").Find(&foods) +//eg. dao.Where(logger, rdb, "title like ?", "%可乐%").Find(&foods) +func Where(logger *clog.Logger, gdb *gorm.DB, query interface{}, args ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Where(query, args...) +} + +// 指定返回的字段 +//eg. dao.Select(logger, rdb, "id,title").Where("id = ?", 1).Take(&food) +//eg. dao.Model(logger, rdb, Food{}).Select("count(*) as total").Pluck("total", &total) +func Select(logger *clog.Logger, gdb *gorm.DB, query interface{}, args ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Select(query, args...) +} + +// 指定绑定的模型,一般和Pluck一起使用 +//eg. dao.Model(logger, rdb, Food{}).Select("count(*) as total").Pluck("total", &total) +func Model(logger *clog.Logger, gdb *gorm.DB, value interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + //db.Callback().Update().Remove("gorm:update_time_stamp") + //db.Callback().Update().Remove("gorm:delete_time_stamp") + return db.Model(value) +} + +// 指定order +//eg. dao.Order(logger, rdb, "create_time desc").Limit(10).Offset(0).Find(&foods) +//eg. dao.Where(logger, rdb, "create_time >= ?", "2018-11-06 00:00:00").Order("create_time desc").Find(&foods) +func Order(logger *clog.Logger, gdb *gorm.DB, value interface{}, reorder ...bool) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Order(value, reorder...) +} + +// limit +//eg. dao.Order(logger, rdb, "create_time desc").Limit(10).Offset(0).Find(&foods) +//eg. dao.Limit(logger, rdb, 10).Offset(0).Find(&foods) +func Limit(logger *clog.Logger, gdb *gorm.DB, limit interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Limit(limit) +} + +// Offset +//eg. dao.Order(logger, rdb, "create_time desc").Limit(10).Offset(0).Find(&foods) +//eg. dao.Offset(logger, rdb, 10).Find(&foods) +func Offset(logger *clog.Logger, gdb *gorm.DB, limit interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Offset(limit) +} + +//eg. dao.Model(logger, rdb, Food{}).Count(&total) +// COUNT + +//eg. dao.Model(logger, rdb, Food{}).Select("type, count(*) as total").Group("type").Having("total > 0").Scan(&results) +//group by,必须要搭配select一起使用 + +//Raw +//eg. dao.Raw(logger, rdb, sql, "2018-11-06 00:00:00").Scan(&results) +func Raw(logger *clog.Logger, gdb *gorm.DB, sql string, values ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Raw(sql, values...) +} diff --git a/bmp-openapi-console/dao/rDeviceTypeImageDao/rDeviceTypeImageDao.go b/bmp-openapi-console/dao/rDeviceTypeImageDao/rDeviceTypeImageDao.go new file mode 100644 index 0000000..2e8c657 --- /dev/null +++ b/bmp-openapi-console/dao/rDeviceTypeImageDao/rDeviceTypeImageDao.go @@ -0,0 +1,295 @@ +package rDeviceTypeImageDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceTypeDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/imageDao" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// RDeviceTypeImage device_type/image关系 +type RDeviceTypeImage struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像ID + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型id + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *RDeviceTypeImage) TableName() string { + return "r_device_type_image" +} + +// AddRDeviceTypeImage insert a new RDeviceTypeImage into database and returns +// last inserted Id on success. +func AddRDeviceTypeImage(logger *log.Logger, m *RDeviceTypeImage) (id int64, err error) { + // + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func AddMultiRDeviceTypeImage(logger *log.Logger, m []*RDeviceTypeImage) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, r := range m { + //r.CreateTime = time.Now() + //r.UpdateTime = time.Now() + if err := tx.Create(r).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetRDeviceTypeImageById retrieves RDeviceTypeImage by Id. Returns error if +// Id doesn't exist +func GetRDeviceTypeImageById(logger *log.Logger, id int64) (v *RDeviceTypeImage, err error) { + v = &RDeviceTypeImage{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetAllRDeviceTypeImage(logger *log.Logger, query map[string]interface{}) (ml []*RDeviceTypeImage, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiRDeviceTypeImage retrieves all RDeviceTypeImage matches certain condition. Returns empty list if +// no records exist +func GetMultiRDeviceTypeImage(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*RDeviceTypeImage, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateRDeviceTypeImage updates RDeviceTypeImage by Id and returns error if +// the record to be updated doesn't exist +func UpdateRDeviceTypeImageById(logger *log.Logger, m *RDeviceTypeImage, deviceTypeId, imageId string) (err error) { + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RDeviceTypeImage{}).Where("device_type_id = ? and image_id = ? and is_del = ?", deviceTypeId, imageId, baseLogic.IS_NOT_DEL).Update(m).Error +} + +func UpdateMultiRDeviceTypeImage(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["updated_time"] = int(time.Now().Unix()) + var db = dao.Model(logger, dao.IronicWdb, RDeviceTypeImage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func AssociatedImageMultiRDeviceTypeImage(logger *log.Logger, items []*RDeviceTypeImage) (err error) { + //paris := []string{} + for _, item := range items { + //paris = append(paris, fmt.Sprintf("('%s', '%s')", item.DeviceTypeID, item.ImageID)) + err = dao.Model(logger, dao.IronicRdb, RDeviceTypeImage{}).Where("device_type_id = ? and image_id = ? and is_del = 0", item.DeviceTypeID, item.ImageID).Update(item).Error + } + //fmt.Sprintf(`(device_type_id, image_id) in (%s)`, strings.Join(paris, ",")) + + //updates := map[string]interface{}{ + // "is_del": 0, + // "updated_time": time.Now(), + //} + return +} + +func GetOneRDeviceTypeImage(logger *log.Logger, query map[string]interface{}) (l *RDeviceTypeImage, err error) { + l = &RDeviceTypeImage{} + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetByDeviceTypeIDAndImageID(logger *log.Logger, deviceTypeID, imageID string) (l *RDeviceTypeImage, err error) { + l = &RDeviceTypeImage{} + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and image_id = ? and is_del = ?", deviceTypeID, imageID, baseLogic.IS_NOT_DEL).Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} +func GetByDeviceTypeID(logger *log.Logger, deviceTypeID string) (l []*RDeviceTypeImage, err error) { + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and is_del = ?", deviceTypeID, baseLogic.IS_NOT_DEL).Find(&l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetByDeviceTypeAndImageIdPatition(logger *log.Logger, device_type, image_id string) (ml []*RDeviceTypeImage, err error) { + + sql := fmt.Sprintf("select r from r_device_type_image r where (device_type='%s' or device_type='common') and image_id='%s' and is_del=0", device_type, image_id) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} +func QueryDeviceTypeImagesCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} + +func ConvertIn(str string) string { + arr := strings.Split(str, ",") + sqlIn := "" + for _, v := range arr { + sqlIn = sqlIn + "'" + v + "'" + "," + } + sqlIn = strings.Trim(sqlIn, ",") + return "(" + sqlIn + ")" +} + +// QueryByDeviceOsType ... +func GetDeviceTypeImageAndOsList(logger *log.Logger, param map[string]interface{}, count bool, offset int64, limit int64) (ml []*imageDao.DImage, n int64, err error) { + raw := "*" + if count { + raw = "count(*)" + } + sql := `select ` + raw + ` FROM image i,os o,r_device_type_image r where i.os_id=o.os_id and r.image_id=i.image_id and r.is_del=0 and i.is_del=0 and o.is_del=0` + sql = sql + ` and r.device_type_id=` + "'" + param["device_type_id"].(string) + "'" + //image i 放在前面,如果有相同字段,以前面这为主,由于都有添加时间字段,如果要获取镜像的添加时间,所以要以image表的created_time为准 + //fmt.Println(param) + if param["image_id"] != nil && param["image_id"] != "" { + sql = sql + " and i.image_id in " + ConvertIn(param["image_id"].(string)) + } + if param["source"] != nil && param["source"] != "" { + sql = sql + " and i.source in " + ConvertIn(param["source"].(string)) + } + if param["image_name"] != nil && param["image_name"] != "" { + sql = sql + " and i.image_name in " + ConvertIn(param["image_name"].(string)) + } + if param["version"] != nil && param["version"] != "" { + sql = sql + " and o.os_version in " + ConvertIn(param["version"].(string)) + } + if param["os_type"] != nil && param["os_type"] != "" { + sql = sql + " and o.os_type in " + ConvertIn(param["os_type"].(string)) + } + if param["architecture"] != nil && param["architecture"] != "" { + sql = sql + " and o.architecture in " + ConvertIn(param["architecture"].(string)) + } + sql = sql + " order by i.created_time desc" + fmt.Println(sql) + logger.Info("查询机型关联镜像sql:", sql) + //os.Exit(1) + if count { + err = dao.Raw(logger, dao.IronicRdb, sql).Count(&n).Error + return + } + if offset == 0 && limit == 0 { + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return + } + fmt.Println(sql) + err = dao.Raw(logger, dao.IronicRdb, sql).Offset(offset).Limit(limit).Scan(&ml).Error + return +} + +//查询镜像绑定的机型列表 +func GetImageDeviceTypeList(logger *log.Logger, param map[string]interface{}, count bool, offset int64, limit int64) (ml []*deviceTypeDao.DeviceType, n int64, err error) { + raw := "*" + if count { + raw = "count(*)" + } + + sql := "" + //查询已绑定的机型 + if param["is_bind"] != nil && param["is_bind"] == "1" { + sql = `select ` + raw + ` FROM device_type dt,r_device_type_image r where dt.device_type_id=r.device_type_id and dt.is_del=0 and r.is_del=0` + if param["image_id"] != nil && param["image_id"] != "" { + sql = sql + " and r.image_id in " + ConvertIn(param["image_id"].(string)) + } + } else { //未绑定 + if param["image_id"] != nil && param["image_id"] != "" { + sql = `select ` + raw + ` FROM device_type dt where dt.is_del=0` + sql = sql + " and dt.device_type_id not in (select device_type_id from r_device_type_image where image_id = '" + param["image_id"].(string) + "' and is_del = 0)" + } + } + + //if param["source"] != nil && param["source"] != "" { + // sql = sql + " and i.source in " + ConvertIn(param["source"].(string)) + //} + //if param["image_name"] != nil && param["image_name"] != "" { + // sql = sql + " and i.image_name in " + ConvertIn(param["image_name"].(string)) + //} + //if param["version"] != nil && param["version"] != "" { + // sql = sql + " and o.os_version in " + ConvertIn(param["version"].(string)) + //} + //if param["os_type"] != nil && param["os_type"] != "" { + // sql = sql + " and o.os_type in " + ConvertIn(param["os_type"].(string)) + //} + if param["architecture"] != nil && param["architecture"] != "" { + sql = sql + " and dt.architecture in " + ConvertIn(param["architecture"].(string)) + } + sql = sql + " order by dt.created_time desc" + fmt.Println(sql) + logger.Info("查询机型关联镜像sql:", sql) + //os.Exit(1) + if count { + err = dao.Raw(logger, dao.IronicRdb, sql).Count(&n).Error + return + } + if offset == 0 && limit == 0 { + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return + } + fmt.Println(sql) + err = dao.Raw(logger, dao.IronicRdb, sql).Offset(offset).Limit(limit).Scan(&ml).Error + return +} diff --git a/bmp-openapi-console/dao/rDeviceTypeImagePartitionDao/rDeviceTypeImagePartitionDao.go b/bmp-openapi-console/dao/rDeviceTypeImagePartitionDao/rDeviceTypeImagePartitionDao.go new file mode 100644 index 0000000..57f25e9 --- /dev/null +++ b/bmp-openapi-console/dao/rDeviceTypeImagePartitionDao/rDeviceTypeImagePartitionDao.go @@ -0,0 +1,142 @@ +package rDeviceTypeImagePartitionDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// RDeviceTypeImagePartition device_type/image +type RDeviceTypeImagePartition struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像ID + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型 + BootMode string `gorm:"column:boot_mode" json:"bootMode"` // boot类型:bios、uefi + PartitionType string `gorm:"column:partition_type" json:"partitionType"` // 分区类型:root、boot、system、data + PartitionSize int `gorm:"column:partition_size" json:"partitionSize"` // 分区大小,单位MB + PartitionFsType string `gorm:"column:partition_fs_type" json:"partitionFsType"` // 文件系统类型:xfs + PartitionMountPoint string `gorm:"column:partition_mount_point" json:"partitionMountPoint"` // 分区目录 + PartitionLabel string `gorm:"column:partition_label" json:"partitionLabel"` // 分区标签:l_分区目录 + SystemDiskLabel string `gorm:"column:system_disk_label" json:"systemDiskLabel"` // 系统盘分区格式:gpt、msdos(做完RAID系统盘大于4T必用gpt) + DataDiskLabel string `gorm:"column:data_disk_label" json:"dataDiskLabel"` // 数据盘分区格式:gpt、msdos + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除(0-未删, 1-已删) +} + +func (t *RDeviceTypeImagePartition) TableName() string { + return "r_device_type_image_partition" +} + +// AddRDeviceTypeImage insert a new RDeviceTypeImage into database and returns +// last inserted Id on success. +func AddRDeviceTypeImagePartition(logger *log.Logger, m *RDeviceTypeImagePartition) (id int64, err error) { + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func AddMultiRDeviceTypeImagePartition(logger *log.Logger, m []*RDeviceTypeImagePartition) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, r := range m { + if err := tx.Create(r).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetRDeviceTypeImageById retrieves RDeviceTypeImage by Id. Returns error if +// Id doesn't exist +func GetRDeviceTypeImagePartitionById(logger *log.Logger, id int64) (v *RDeviceTypeImagePartition, err error) { + v = &RDeviceTypeImagePartition{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetAllRDeviceTypeImagePartition(logger *log.Logger, query map[string]interface{}) (ml []*RDeviceTypeImagePartition, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImagePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiRDeviceTypeImage retrieves all RDeviceTypeImage matches certain condition. Returns empty list if +// no records exist +func GetMultiRDeviceTypeImagePartition(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*RDeviceTypeImagePartition, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImagePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateRDeviceTypeImage updates RDeviceTypeImage by Id and returns error if +// the record to be updated doesn't exist +func UpdateRDeviceTypeImagePartitionById(logger *log.Logger, m *RDeviceTypeImagePartition) (err error) { + return dao.Model(logger, dao.IronicWdb, RDeviceTypeImagePartition{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateMultiRDeviceTypeImagePartition(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + //updates["updated_time"] = time.Now() + var db = dao.Model(logger, dao.IronicWdb, RDeviceTypeImagePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func GetOneRDeviceTypeImagePartition(logger *log.Logger, query map[string]interface{}) (l *RDeviceTypeImagePartition, err error) { + l = &RDeviceTypeImagePartition{} + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImagePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetByDeviceTypeAndImageId(logger *log.Logger, deviceTypeId, imageId string) (ml []*RDeviceTypeImagePartition, err error) { + sql := fmt.Sprintf("select * from r_device_type_image_partition r where device_type_id='%s' and image_id='%s' and is_del=0", deviceTypeId, imageId) //or device_type='common' + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-openapi-console/dao/rDeviceVolumeDisksDao/rDeviceVolumeDisksDao.go b/bmp-openapi-console/dao/rDeviceVolumeDisksDao/rDeviceVolumeDisksDao.go new file mode 100644 index 0000000..20cb4fb --- /dev/null +++ b/bmp-openapi-console/dao/rDeviceVolumeDisksDao/rDeviceVolumeDisksDao.go @@ -0,0 +1,76 @@ +package rDeviceVolumeDisksDao + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// RDeviceVolumeDisks 设备-卷-磁盘 关系表 +type RDeviceVolumeDisks struct { + ID uint32 `gorm:"primary_key;column:id;type:int(11) unsigned;not null" json:"-"` // 主键 + DeviceID string `gorm:"index:i_device_id;column:device_id;type:varchar(255);not null" json:"device_id"` // 设备uuid + VolumeID string `gorm:"index:i_volume_id;column:volume_id;type:varchar(255);not null" json:"volume_id"` // volume uuid + DiskID string `gorm:"index:i_disk_id;column:disk_id;type:varchar(255);not null" json:"disk_id"` // disk uuid + CreatedBy string `gorm:"column:created_by;type:varchar(255);not null" json:"created_by"` // 创建者 + UpdatedBy string `gorm:"column:updated_by;type:varchar(255);not null" json:"updated_by"` // 更新者 + CreatedTime int `gorm:"column:created_time;type:int(255);not null" json:"created_time"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time;type:int(11);not null" json:"updated_time"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time;type:int(11);not null" json:"deleted_time"` // 删除时间 + IsDel int8 `gorm:"index:i_is_del;column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 +} + +func (t *RDeviceVolumeDisks) TableName() string { + return "r_device_volume_disks" +} + +// GetAllRDeviceTypeRaid retrieves all raid matches certain condition. Returns empty list if +// no records exist +func GetAllRDeviceVolumeDisks(logger *log.Logger, query map[string]interface{}) (ml []*RDeviceVolumeDisks, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RDeviceVolumeDisks{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetRDeviceTypeRaidById retrieves RDeviceTypeRaid by Id. Returns error if +// Id doesn't exist +func GetRDeviceVolumeDiskByVolumeIdDiskId(logger *log.Logger, volumeId, diskId string) (v *RDeviceVolumeDisks, err error) { + v = &RDeviceVolumeDisks{} + err = dao.Where(logger, dao.IronicRdb, "volume_id = ? and disk_id = ? and is_del = 0", volumeId, diskId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func UpdateMultiRDeviceVolumeDisk(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = int(time.Now().Unix()) + var db = dao.Model(logger, dao.IronicWdb, RDeviceVolumeDisks{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func AddMultiRDeviceVolumeDisk(logger *log.Logger, m []*RDeviceVolumeDisks) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, r := range m { + //r.CreateTime = time.Now() + //r.UpdateTime = time.Now() + if err := tx.Create(r).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} diff --git a/bmp-openapi-console/dao/rInstanceSshkeyDao/rInstanceSshkey.go b/bmp-openapi-console/dao/rInstanceSshkeyDao/rInstanceSshkey.go new file mode 100644 index 0000000..0e83d59 --- /dev/null +++ b/bmp-openapi-console/dao/rInstanceSshkeyDao/rInstanceSshkey.go @@ -0,0 +1,190 @@ +package rInstanceSshkeyDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// rInstanceSshkey device_type/image关系 +type RInstanceSshkey struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + InstanceID string `gorm:"column:instance_id" json:"instanceId"` // 实例ID + SSHkeyID string `gorm:"column:sshkey_id" json:"sshkeyId"` // sshkeyid + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *RInstanceSshkey) TableName() string { + return "r_instance_sshkey" +} + +// AddrInstanceSshkey insert a new rInstanceSshkey into database and returns +// last inserted Id on success. +func AddrInstanceSshkey(logger *log.Logger, m *RInstanceSshkey) (id int64, err error) { + // + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func AddMultirInstanceSshkey(logger *log.Logger, m []*RInstanceSshkey) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, r := range m { + //r.CreateTime = time.Now() + //r.UpdateTime = time.Now() + if err := tx.Create(r).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetrInstanceSshkeyById retrieves rInstanceSshkey by Id. Returns error if +// Id doesn't exist +func GetrInstanceSshkeyById(logger *log.Logger, id int64) (v *RInstanceSshkey, err error) { + v = &RInstanceSshkey{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetAllrInstanceSshkey(logger *log.Logger, query map[string]interface{}) (ml []*RInstanceSshkey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RInstanceSshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultirInstanceSshkey retrieves all rInstanceSshkey matches certain condition. Returns empty list if +// no records exist +func GetMultirInstanceSshkey(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*RInstanceSshkey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RInstanceSshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdaterInstanceSshkey updates rInstanceSshkey by Id and returns error if +// the record to be updated doesn't exist +func UpdaterInstanceSshkeyById(logger *log.Logger, m *RInstanceSshkey) (err error) { + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RInstanceSshkey{}).Where("instance_id = ? and is_del = 0", m.InstanceID).Update(m).Error + +} + +func DeleteInstanceSshkeyByInstanceID(logger *log.Logger, instanceID string) (err error) { + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RInstanceSshkey{}).Where("instance_id = ? and is_del = 0", instanceID).Update("is_del", 1).Error +} + +func UpdateMultirInstanceSshkey(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, RInstanceSshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +//func AssociatedImageMultirInstanceSshkey(logger *log.Logger, items []*RInstanceSshkey) (err error) { +// //paris := []string{} +// for _, item := range items { +// //paris = append(paris, fmt.Sprintf("('%s', '%s')", item.DeviceTypeID, item.ImageID)) +// err = dao.Model(logger, dao.IronicRdb, RInstanceSshkey{}).Where("device_type_id = ? and image_id = ? and is_del = 0", item.DeviceTypeID, item.ImageID).Update(item).Error +// } +// //fmt.Sprintf(`(device_type_id, image_id) in (%s)`, strings.Join(paris, ",")) +// +// //updates := map[string]interface{}{ +// // "is_del": 0, +// // "updated_time": time.Now(), +// //} +// return +//} + +func GetOnerInstanceSshkey(logger *log.Logger, query map[string]interface{}) (l *RInstanceSshkey, err error) { + l = &RInstanceSshkey{} + var db = dao.Model(logger, dao.IronicRdb, RInstanceSshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetByDeviceTypeIDAndImageID(logger *log.Logger, deviceTypeID, imageID string) (l *RInstanceSshkey, err error) { + l = &RInstanceSshkey{} + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and image_id = ? and is_del = ?", deviceTypeID, imageID, baseLogic.IS_NOT_DEL).Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} +func GetByDeviceTypeID(logger *log.Logger, deviceTypeID string) (l []*RInstanceSshkey, err error) { + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and is_del = ?", deviceTypeID, baseLogic.IS_NOT_DEL).Find(&l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetByDeviceTypeAndImageIdPatition(logger *log.Logger, device_type, image_id string) (ml []*RInstanceSshkey, err error) { + + sql := fmt.Sprintf("select r from r_device_type_image r where (device_type='%s' or device_type='common') and image_id='%s' and is_del=0", device_type, image_id) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} +func QueryDeviceTypeImagesCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, RInstanceSshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} diff --git a/bmp-openapi-console/dao/rInstanceVolumeRaidDao/rInstanceVolumeRaidDao.go b/bmp-openapi-console/dao/rInstanceVolumeRaidDao/rInstanceVolumeRaidDao.go new file mode 100644 index 0000000..295a47c --- /dev/null +++ b/bmp-openapi-console/dao/rInstanceVolumeRaidDao/rInstanceVolumeRaidDao.go @@ -0,0 +1,83 @@ +package rInstanceVolumeRaidDao + +import ( + + //"coding.jd.com/aidc-bmp/bmp-scheduler/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// RInstanceVolumeRaid 实例每个数据卷选择的raid +type RInstanceVolumeRaid struct { + ID int `gorm:"primary_key;column:id;type:int(11) unsigned;not null" json:"-"` // 主键 + InstanceID string `gorm:"index:i_instance_id;column:instance_id;type:varchar(255);not null" json:"instance_id"` // instance uuid + VolumeID string `gorm:"column:volume_id;type:varchar(255);not null" json:"volume_id"` // volume uuid + VolumeType string `gorm:"index:i_volume_type;column:volume_type;type:varchar(255);not null" json:"volume_type"` // data|system + RaidCan string `gorm:"column:raid_can;type:varchar(16);not null" json:"raid_can"` // RAID配置: (RAID,NO RAID) + RaidID string `gorm:"column:raid_id;type:varchar(255);not null" json:"raid_id"` // RAID模式:raidid,一个一条 + RaidName string `gorm:"column:raid_name;type:varchar(255);not null" json:"raid_name"` // RAID名称 + CreatedBy string `gorm:"column:created_by;type:varchar(255);not null" json:"created_by"` // 创建者 + UpdatedBy string `gorm:"column:updated_by;type:varchar(255);not null" json:"updated_by"` // 更新者 + CreatedTime int `gorm:"column:created_time;type:int(255);not null" json:"created_time"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time;type:int(11);not null" json:"updated_time"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time;type:int(11);not null" json:"deleted_time"` // 删除时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 +} + +func (t *RInstanceVolumeRaid) TableName() string { + return "r_instance_volume_raid" +} + +// AddVolume insert a new Volume into database and returns +// last inserted Id on success. +func AddRInstanceVolumeRaid(logger *log.Logger, m *RInstanceVolumeRaid) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetVolumeById retrieves Volume by Id. Returns error if +// Id doesn't exist +func GetRInstanceVolumeRaids(logger *log.Logger, instanceId string) (ml []*RInstanceVolumeRaid, err error) { + ml = []*RInstanceVolumeRaid{} + err = dao.Where(logger, dao.IronicRdb, "instance_id = ? and is_del = 0", instanceId).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil +} + +// UpdateVolume updates Volume by Id and returns error if +// the record to be updated doesn't exist +func UpdateRInstanceVolumeRaidById(logger *log.Logger, m *RInstanceVolumeRaid) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RInstanceVolumeRaid{}).Where("id = ?", m.ID).Save(m).Error +} + +func AddMultiRInstanceVolumeRaid(logger *log.Logger, m []*RInstanceVolumeRaid) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, r := range m { + //r.CreateTime = time.Now() + //r.UpdateTime = time.Now() + if err := tx.Create(r).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +func GetRInstanceVolumeRaidByInstanceId(logger *log.Logger, instanceId string) (ml []*RInstanceVolumeRaid, err error) { + ml = []*RInstanceVolumeRaid{} + err = dao.Where(logger, dao.IronicRdb, "instance_id = ? and is_del = 0", instanceId).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil +} diff --git a/bmp-openapi-console/dao/rMonitorRulesInstanceDao/rMonitorRulesInstanceDao.go b/bmp-openapi-console/dao/rMonitorRulesInstanceDao/rMonitorRulesInstanceDao.go new file mode 100644 index 0000000..a9a3ed1 --- /dev/null +++ b/bmp-openapi-console/dao/rMonitorRulesInstanceDao/rMonitorRulesInstanceDao.go @@ -0,0 +1,137 @@ +package rMonitorRulesInstanceDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// RMonitorRulesInstance 带内监控规则-实例关联表 +type RMonitorRulesInstance struct { + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + RuleID string `gorm:"index:i_rule_id;column:rule_id;type:varchar(255);not null" json:"rule_id"` // rule uuid + RuleName string `gorm:"column:rule_name;type:varchar(255);not null" json:"rule_name"` // 规则名称 + InstanceID string `gorm:"index:i_instance_id;column:instance_id;type:varchar(255);not null" json:"instance_id"` // instance uuid + InstanceName string `gorm:"column:instance_name;type:varchar(255);not null" json:"instance_name"` // instance name + Tags string `gorm:"column:tags;type:varchar(255);not null" json:"tags"` // disk/mountpoint/nic tag + CreatedTime int `gorm:"column:created_time;type:int(11);not null" json:"created_time"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time;type:int(11);not null" json:"updated_time"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time;type:int(11);not null" json:"deleted_time"` // 更新时间戳 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 + ProjectID string `gorm:"column:project_id" json:"project_id"` // 项目uuid +} + +func (t *RMonitorRulesInstance) TableName() string { + return "r_monitor_rules_instance" +} + +// AddWebMessage insert a new Os into database and returns +// last inserted Id on success. +func AddRMonitorRulesInstance(logger *log.Logger, m *RMonitorRulesInstance) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func AddMultiRMonitorRulesInstance(logger *log.Logger, ml []*RMonitorRulesInstance) (err error) { + for _, v := range ml { + if _, err := dao.CreateAndGetId(logger, dao.IronicWdb, v); err != nil { + logger.Warnf("AddMultiRMonitorRulesInstance error, v:%s, error:%s", util.InterfaceToJson(v), err.Error()) + } + } + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return nil +} + +func GetRMonitorRulesInstanceCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, RMonitorRulesInstance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetMultiOs retrieves all Os matches certain condition. Returns empty list if +// no records exist +func GetMultiRMonitorRulesInstance(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*RMonitorRulesInstance, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RMonitorRulesInstance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetAllRMonitorRulesInstance(logger *log.Logger, query map[string]interface{}) (ml []*RMonitorRulesInstance, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RMonitorRulesInstance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// UpdateOs updates Os by Id and returns error if +// the record to be updated doesn't exist +func UpdateRMonitorRulesInstance(logger *log.Logger, m *RMonitorRulesInstance) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RMonitorRulesInstance{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateMultiRMonitorRulesInstance(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, RMonitorRulesInstance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return + +} + +func DeleteMonitorRuleInstanceByInstanceID(logger *log.Logger, instanceID string) (err error) { + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RMonitorRulesInstance{}).Where("instance_id = ? and is_del = 0", instanceID).Update("is_del", 1).Error +} + +type RuleInstance struct { + RuleID string `json:"rule_id"` + RuleName string `json:"rule_name"` + InstanceId string `json:"instance_id"` + InstanceName string `json:"instance_name"` + Status int `json:"status"` +} + +func GetAllRMonitorRulesInstanceEffective(logger *log.Logger) (ml []*RuleInstance, err error) { + + sql := `select j.rule_id ,j.rule_name, j.instance_id, j.instance_name, i.status FROM monitor_rules i INNER JOIN r_monitor_rules_instance j ON i.rule_id = j.rule_id where 1=1 and i.is_del = 0 and j.is_del = 0 and i.status in (1, 3)` + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-openapi-console/dao/rVolumeRaidDao/rVolumeRaidDao.go b/bmp-openapi-console/dao/rVolumeRaidDao/rVolumeRaidDao.go new file mode 100644 index 0000000..2e521c3 --- /dev/null +++ b/bmp-openapi-console/dao/rVolumeRaidDao/rVolumeRaidDao.go @@ -0,0 +1,131 @@ +package rVolumeRaidDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Volume RAID 关联关系表 +type RVolumeRaid struct { + ID int `gorm:"primaryKey;column:id" json:"-"` // 主键 + VolumeID string `gorm:"column:volume_id" json:"volumeId"` // 卷uuid + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型uuid + + RaidCan string `gorm:"column:raid_can" json:"raidCan"` // RAID配置: (RAID,NO RAID) + RaidID string `gorm:"column:raid_id" json:"raidId"` // RAID模式:RAID1,RIAD10等 + RaidName string `gorm:"column:raid_name" json:"raidName"` // RAID名称 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *RVolumeRaid) TableName() string { + return "r_volume_raid" +} + +// AddVolume insert a new Volume into database and returns +// last inserted Id on success. +func AddRVolumeRaid(logger *log.Logger, m *RVolumeRaid) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetVolumeById retrieves Volume by Id. Returns error if +// Id doesn't exist +func GetRVolumeRaidsByVId(logger *log.Logger, VolumeId string) (ml []*RVolumeRaid, err error) { + ml = []*RVolumeRaid{} + err = dao.Where(logger, dao.IronicRdb, "volume_id = ? and is_del = 0", VolumeId).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil +} + +// GetVolumeByUuid retrieves Volume by Uuid. Returns error if +// Id doesn't exist +func GetRVolumeRaidCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, RVolumeRaid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAllVolume retrieves all Volume matches certain condition. Returns empty list if +// no records exist +func GetAllRVolumeRaid(logger *log.Logger, query map[string]interface{}) (ml []*RVolumeRaid, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RVolumeRaid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiVolume retrieves all Volume matches certain condition. Returns empty list if +// no records exist +func GetMultiRVolumeRaid(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*RVolumeRaid, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RVolumeRaid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateVolume updates Volume by Id and returns error if +// the record to be updated doesn't exist +func UpdateRVolumeRaidById(logger *log.Logger, m *RVolumeRaid) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RVolumeRaid{}).Where("id = ?", m.ID).Save(m).Error +} + +func UpdateRVolumeRaidByWhere(logger *log.Logger, query map[string]interface{}, updates *RVolumeRaid) (err error) { + var db = dao.Model(logger, dao.IronicWdb, RVolumeRaid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func GetSystemVolumeRaid(logger *log.Logger, deviceTypeId string) (ml []*RVolumeRaid, err error) { + ml = []*RVolumeRaid{} + + sql := `select a.* from r_volume_raid a inner join volume b on a.volume_id = b.volume_id and b.volume_type = 'system' and a.is_del = 0 and b.is_del = 0` + + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + if err != nil { + return nil, err + } + return ml, nil +} diff --git a/bmp-openapi-console/dao/raidDao/raidDao.go b/bmp-openapi-console/dao/raidDao/raidDao.go new file mode 100644 index 0000000..f3e53a0 --- /dev/null +++ b/bmp-openapi-console/dao/raidDao/raidDao.go @@ -0,0 +1,138 @@ +package raidDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Raid raid +type Raid struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + RaidID string `gorm:"column:raid_id" json:"raidId"` // raid uuid + Name string `gorm:"column:name" json:"name"` // raid类型 noraid,raid0,raid1,raid10 + DescriptionEn string `gorm:"column:description_en" json:"descriptionEn"` // RAID英文描述 + DescriptionZh string `gorm:"column:description_zh" json:"descriptionZh"` // RAID中文描述 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Raid) TableName() string { + return "raid" +} + +// AddRaid insert a new Raid into database and returns +// last inserted Id on success. +func AddRaid(logger *log.Logger, m *Raid) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetRaidById retrieves Raid by Id. Returns error if +// Id doesn't exist +func GetRaidById(logger *log.Logger, raidId string) (v *Raid, err error) { + v = &Raid{} + err = dao.Where(logger, dao.IronicRdb, "raid_id = ? and is_del = 0", raidId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetRaidByUuid retrieves Raid by Id. Returns error if +// Id doesn't exist +func GetRaidByUuid(logger *log.Logger, uuid string) (v *Raid, err error) { + v = &Raid{} + err = dao.Where(logger, dao.IronicRdb, "raid_id = ? and is_del = 0", uuid).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllRaid retrieves all raid matches certain condition. Returns empty list if +// no records exist +func GetAllRaid(logger *log.Logger, query map[string]interface{}) (ml []*Raid, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Raid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiRaid retrieves all Raid matches certain condition. Returns empty list if +// no records exist +func GetMultiRaid(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Raid, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Raid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateRaid updates Raid by Id and returns error if +// the record to be updated doesn't exist +func UpdateRaidById(logger *log.Logger, m *Raid) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Raid{}).Where("raid_id = ?", m.RaidID).Updates(m).Error +} + +type DRaid struct { + RaidId string `json:"raid_id"` + NameEn string `json:"name_en"` + NameZh string `json:"name_zh"` + DeviceType string `json:"device_type"` + VolumeType string `json:"volume_type"` + VolumeDetail string `json:"volume_detail"` + DescriptionZh string `json:"description_zh"` + DescriptionEn string `json:"description_en"` + SystemPartitionCount int `json:"system_partition_count"` + AvailableValue int `json:"available_value"` + DiskType string `json:"disk_type"` +} + +func GetAllRraidDevice(logger *log.Logger, raid_id, device_type, volume_type string) (ml []*DRaid, err error) { + + sql := `select t1.uuid as raid_id, t1.name_en, t1.name_zh, t1.description_zh, t1.description_en, t2.device_type, t2.volume_type, t2.volume_detail, t2.system_partition_count,t2.available_value,t2.disk_type from raid t1 left join r_device_type_raid t2 on t1.uuid = t2.raid_id where t1.is_del = 0 and t2.is_del = 0` + if raid_id != "" { + sql = sql + fmt.Sprintf(" and t1.uuid = '%s'", raid_id) + } + if device_type != "" { + sql = sql + fmt.Sprintf(" and t2.device_type = '%s'", device_type) + } + if volume_type != "" { + sql = sql + fmt.Sprintf(" and t2.volume_type = '%s'", volume_type) + } + + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return + +} diff --git a/bmp-openapi-console/dao/roleDao/roleDao.go b/bmp-openapi-console/dao/roleDao/roleDao.go new file mode 100644 index 0000000..04924eb --- /dev/null +++ b/bmp-openapi-console/dao/roleDao/roleDao.go @@ -0,0 +1,108 @@ +package roleDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Role Role +type Role struct { + ID int `gorm:"primaryKey;column:id" json:"-"` + RoleID string `gorm:"column:role_id" json:"roleId"` // 角色uuid + RoleNameEn string `gorm:"column:role_name_en" json:"roleNameEn"` // 角色名称,唯一 + RoleNameCn string `gorm:"column:role_name_cn" json:"roleNameCn"` // 角色名称,唯一 + DescriptionEn string `gorm:"column:description_en" json:"descriptionEn"` // 权限描述 + DescriptionCn string `gorm:"column:description_cn" json:"descriptionCn"` // 权限描述 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Role) TableName() string { + return "role" +} + +// AddRole insert a new Role into database and returns +// last inserted Id on success. +func AddRole(logger *log.Logger, m *Role) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetRoleById retrieves Role by Id. Returns error if +// Id doesn't exist +func GetRoleById(logger *log.Logger, RoleId string) (v *Role, err error) { + v = &Role{} + err = dao.Where(logger, dao.IronicRdb, "role_id = ? and is_del = 0", RoleId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetRoleByUuid retrieves Role by Uuid. Returns error if +// Id doesn't exist +func GetRoleCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Role{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAllRole retrieves all Role matches certain condition. Returns empty list if +// no records exist +func GetAllRole(logger *log.Logger, query map[string]interface{}) (ml []*Role, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Role{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiRole retrieves all Role matches certain condition. Returns empty list if +// no records exist +func GetMultiRole(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Role, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Role{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateRole updates Role by Id and returns error if +// the record to be updated doesn't exist +func UpdateRoleById(logger *log.Logger, m *Role) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Role{}).Where("role_id = ?", m.RoleID).Updates(m).Error +} diff --git a/bmp-openapi-console/dao/sharingProjectDao/sharingProjectDao.go b/bmp-openapi-console/dao/sharingProjectDao/sharingProjectDao.go new file mode 100644 index 0000000..5d57df2 --- /dev/null +++ b/bmp-openapi-console/dao/sharingProjectDao/sharingProjectDao.go @@ -0,0 +1,113 @@ +package sharingProjectDao + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// SharingProject 共享项目 +type SharingProject struct { + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + ProjectID string `gorm:"column:project_id;type:varchar(255);not null" json:"project_id"` // 项目uuid + ProjectName string `gorm:"column:project_name;type:varchar(255);not null" json:"project_name"` // 项目名称 + OwnerUserID string `gorm:"column:owner_user_id;type:varchar(255);not null" json:"owner_user_id"` // 项目拥有者用户id + SharedUserID string `gorm:"column:shared_user_id;type:varchar(255);not null" json:"shared_user_id"` // 项目共享者用户id + OwnerUserName string `gorm:"column:owner_user_name;type:varchar(255);not null" json:"owner_user_name"` // 项目拥有者用户名 + SharedUserName string `gorm:"column:shared_user_name;type:varchar(255);not null" json:"shared_user_name"` // 项目拥有者用户名 + IsDefault int8 `gorm:"column:is_default;type:tinyint(4);not null" json:"is_default"` // 是否默认项目0否 1是 + CreatedBy string `gorm:"column:created_by;type:varchar(255);not null" json:"created_by"` // 创建者 + UpdatedBy string `gorm:"column:updated_by;type:varchar(255);not null" json:"updated_by"` // 更新者 + CreatedTime int `gorm:"column:created_time;type:int(11);not null" json:"created_time"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time;type:int(11);not null" json:"updated_time"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time;type:int(11);not null" json:"deleted_time"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 + Premission string `gorm:"column:premission;type:varchar(64);not null" json:"premission"` // 读/写权限 + SharedInstanceIDs string `gorm:"column:shared_instance_ids;type:text;not null" json:"shared_instance_ids"` // sharding instances +} + +func (t *SharingProject) TableName() string { + return "sharing_project" +} + +// AddProject insert a new Project into database and returns +// last inserted Id on success. +func AddSharingProject(logger *log.Logger, m *SharingProject) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func GetSharingsByProjectId(logger *log.Logger, project_id string) (ml []*SharingProject, err error) { + + err = dao.Where(logger, dao.IronicRdb, "project_id = ? and is_del = 0", project_id).Find(&ml).Error + return +} + +func GetSharingProjectIdsBySharding(logger *log.Logger, user_id string) (ml []*SharingProject, err error) { + err = dao.Where(logger, dao.IronicRdb, "shared_user_id = ? and is_del = 0", user_id).Find(&ml).Error + return +} + +func GetOneSharingProject(logger *log.Logger, project_id string, owner_id string, shard_id string) (l *SharingProject, err error) { + l = &SharingProject{} + err = dao.Where(logger, dao.IronicRdb, "project_id = ? and shared_user_id = ? and is_del = 0", project_id, shard_id).Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func DeleteOneSharingProject(logger *log.Logger, p *SharingProject) (err error) { + p.IsDel = 1 + err = dao.Save(logger, dao.IronicWdb, p).Error + return +} + +func DeleteSharingProjectByProjectId(logger *log.Logger, project_id string) (err error) { + m := map[string]interface{}{ + "is_del": 1, + } + return dao.Model(logger, dao.IronicWdb, SharingProject{}).Where("project_id = ? and is_del = 0", project_id).Updates(m).Error + +} + +// GetAllShareProjects +func GetAllShareProjects(logger *log.Logger, query map[string]interface{}) (ml []*SharingProject, err error) { + + var db = dao.Model(logger, dao.IronicRdb, SharingProject{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func UpdateMultiShareProjects(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + var db = dao.Model(logger, dao.IronicWdb, SharingProject{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func UpdateShareProjectById(logger *log.Logger, m *SharingProject) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, SharingProject{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateShareProjectByMap(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + var db = dao.Model(logger, dao.IronicWdb, SharingProject{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} diff --git a/bmp-openapi-console/dao/sshkeyDao/sshkeyDao.go b/bmp-openapi-console/dao/sshkeyDao/sshkeyDao.go new file mode 100644 index 0000000..1e60e09 --- /dev/null +++ b/bmp-openapi-console/dao/sshkeyDao/sshkeyDao.go @@ -0,0 +1,108 @@ +package sshkeyDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Sshkey Sshkey +type Sshkey struct { + ID int64 `gorm:"id" json:"id"` + SshkeyId string `gorm:"sshkey_id" json:"sshkeyId"` // 秘钥uuid + UserId string `gorm:"user_id" json:"userId"` // 用户id + Name string `gorm:"name" json:"name"` // 秘钥名称 + Key string `gorm:"key" json:"key"` // 公钥,格式:ssh-rsa AAA + FingerPrint string `gorm:"finger_print" json:"fingerPrint"` // 公钥指纹 + CreatedBy string `gorm:"created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Sshkey) TableName() string { + return "ssh_key" +} + +// AddSshkey insert a new Sshkey into database and returns +// last inserted Id on success. +func AddSshkey(logger *log.Logger, m *Sshkey) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetSshkeyById retrieves Sshkey by Id. Returns error if +// Id doesn't exist +func GetSshkeyById(logger *log.Logger, SshkeyId string) (v *Sshkey, err error) { + v = &Sshkey{} + err = dao.Where(logger, dao.IronicRdb, "sshkey_id = ? and is_del = 0", SshkeyId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetSshkeyByUuid retrieves Sshkey by Uuid. Returns error if +// Id doesn't exist +func GetSshkeyCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Sshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAllSshkey retrieves all Sshkey matches certain condition. Returns empty list if +// no records exist +func GetAllSshkey(logger *log.Logger, query map[string]interface{}) (ml []*Sshkey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Sshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiSshkey retrieves all Sshkey matches certain condition. Returns empty list if +// no records exist +func GetMultiSshkey(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Sshkey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Sshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateSshkey updates Sshkey by Id and returns error if +// the record to be updated doesn't exist +func UpdateSshkeyById(logger *log.Logger, m *Sshkey) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Sshkey{}).Where("sshkey_id = ?", m.SshkeyId).Updates(m).Error +} diff --git a/bmp-openapi-console/dao/subnetDao/subnetDao.go b/bmp-openapi-console/dao/subnetDao/subnetDao.go new file mode 100644 index 0000000..db82f14 --- /dev/null +++ b/bmp-openapi-console/dao/subnetDao/subnetDao.go @@ -0,0 +1,181 @@ +package subnetDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Subnet 子网 +type Subnet struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + UUID string `gorm:"unique;column:uuid;type:varchar(36);not null" json:"uuid"` // 子网ID + Az string `gorm:"column:az;type:varchar(32);not null" json:"az"` // az + Tenant string `gorm:"index:i_subnet_tenant;column:tenant;type:varchar(64);not null" json:"tenant"` // 租户 + Name string `gorm:"column:name;type:varchar(32)" json:"name"` + Cidr string `gorm:"column:cidr;type:varchar(32);not null" json:"cidr"` // 子网网段 + VxlanID int64 `gorm:"column:vxlan_id;type:bigint(20) unsigned;not null" json:"vxlan_id"` // vxlan_id + Gateway string `gorm:"column:gateway;type:varchar(32);not null" json:"gateway"` // 子网网关 + Mask string `gorm:"column:mask;type:varchar(32);not null" json:"mask"` // 子网掩码 + Mac string `gorm:"column:mac;type:varchar(32);not null" json:"mac"` // MAC + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *Subnet) TableName() string { + return "subnet" +} + +// AddSubnet insert a new Subnet into database and returns +// last inserted Id on success. +func AddSubnet(logger *log.Logger, m *Subnet) (id int64, err error) { + + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicRdb, m) +} + +// GetSubnetById retrieves Subnet by Id. Returns error if +// Id doesn't exist +func GetSubnetById(logger *log.Logger, id int64) (v *Subnet, err error) { + v = &Subnet{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetOneSubnet(logger *log.Logger, query map[string]interface{}) (v *Subnet, err error) { + v = &Subnet{} + var db = dao.Model(logger, dao.IronicRdb, Subnet{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetSubnetCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Subnet{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return + +} + +// GetAllRaid retrieves all raid matches certain condition. Returns empty list if +// no records exist +func GetAllSubnet(logger *log.Logger, query map[string]interface{}) (ml []*Subnet, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Subnet{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiSubnet retrieves all Subnet matches certain condition. Returns empty list if +// no records exist +func GetMultiSubnet(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Subnet, err error) { + var db = dao.Model(logger, dao.IronicRdb, Subnet{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateSubnet updates Subnet by Id and returns error if +// the record to be updated doesn't exist +func UpdateSubnetById(logger *log.Logger, m *Subnet) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Subnet{}).Where("id = ?", m.ID).Updates(m).Error +} + +func GetBySubnetIdAndTenant(logger *log.Logger, subnet_id, tenant string) (v *Subnet, err error) { + v = &Subnet{} + // err = dao.Where(logger, dao.IronicRdb, "uuid = ? and tenant = ? and is_del = 0", subnet_id, tenant).Take(&v).Error + err = dao.Where(logger, dao.IronicRdb, "uuid = ? and is_del = 0", subnet_id).Take(&v).Error + if err != nil { + return nil, err + } + return v, nil + +} + +func QueryByTenant(logger *log.Logger, tenant, az string) (ml []*Subnet, err error) { + // err = dao.Where(logger, dao.IronicRdb, "az = ? and tenant = ? and is_del = 0", az, tenant).Find(&ml).Error + err = dao.Where(logger, dao.IronicRdb, "is_del = 0").Find(&ml).Error + return +} + +func CountByParam(logger *log.Logger, az, tenant, name string, subnet_ids []string) (n int64, err error) { + sql := `select count(1) from subnet t where 1=1` + // if az != "" { + // sql = sql + fmt.Sprintf(" and t.az = '%s'", az) + // } + // if tenant != "" { + // sql = sql + fmt.Sprintf(" and t.tenant = '%s'", tenant) + // } + if name != "" { + sql = sql + fmt.Sprintf(" and t.name LIKE CONCAT('%%', '%s', '%%')", name) + } + if len(subnet_ids) > 0 { + for k, v := range subnet_ids { + subnet_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t.uuid in (%s)", strings.Join(subnet_ids, ",")) + } + sql = sql + " and t.is_del = 0" + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&n).Error + return +} + +func QueryByParam(logger *log.Logger, az, tenant, name string, subnet_ids []string, offset, limit int64) (ml []*Subnet, err error) { + sql := `select * from subnet t where 1=1` + // if az != "" { + // sql = sql + fmt.Sprintf(" and t.az = '%s'", az) + // } + // if tenant != "" { + // sql = sql + fmt.Sprintf(" and t.tenant = '%s'", tenant) + // } + if name != "" { + sql = sql + fmt.Sprintf(" and t.name LIKE CONCAT('%%', '%s', '%%')", name) + } + if len(subnet_ids) > 0 { + for k, v := range subnet_ids { + subnet_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t.uuid in (%s)", strings.Join(subnet_ids, ",")) + } + sql = sql + fmt.Sprintf(" and t.is_del = 0 limit %d ,%d", offset, limit) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-openapi-console/dao/updateDao.go b/bmp-openapi-console/dao/updateDao.go new file mode 100644 index 0000000..e65b9d6 --- /dev/null +++ b/bmp-openapi-console/dao/updateDao.go @@ -0,0 +1,53 @@ +package dao + +import ( + clog "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +//更新 根据主键id,更新所有模型字段值。查询->set->save +//eg. dao.Save(logger, rdb, &food) +func Save(logger *clog.Logger, gdb *gorm.DB, value interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Save(value) +} + +//更新单个字段值 +//eg1.更新一条记录(根据主键) dao.Model(logger, rdb, &food).Update("price", 25) +//eg2.更新所有记录 dao.Model(logger, rdb, Food{}).Update("price", 25) +//eg3.根据自定义条件更新记录 dao.Model(logger, rdb, Food{}).Where("create_time > ?", "2018-11-06 20:00:00").Update("price", 25) +func Update(logger *clog.Logger, gdb *gorm.DB, attrs ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Update(attrs...) +} + +//更新多个字段值 +/* +updataFood := Food{ + Stock:120, + Title:"柠檬雪碧", + //Age:0 +} +*/ +//eg1. 通过结构体变量设置更新字段 dao.Model(logger, rdb, &food).Updates(&updataFood) 问题是:这样只会更新updataFood中字段为非默认值的字段,比如updataFood定义时就算加上了Age:0,这个字段也不会被更新成目标0 +//eg2. 根据自定义条件更新记录 dao.Model(logger, rdb, Food{}).Where("price > ?", 10).Updates(&updataFood) 问题同上 +//eg3. 想更新所有字段值,包括零值,就是不想忽略掉空值字段时,使用map类型替代上面的结构体变量 +/* +data := make(map[string]interface{}) +data["stock"] = 0 //零值字段 +data["price"] = 35 +dao.Model(logger, rdb, Food{}).Where("id = ?", 2).Updates(data) +*/ +func Updates(logger *clog.Logger, gdb *gorm.DB, values interface{}, ignoreProtectedAttrs ...bool) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Updates(values, ignoreProtectedAttrs...) +} + +//更新表达式 +//eg. db.Model(&food).Update("stock", gorm.Expr("stock + 1")) 等价于UPDATE `foods` SET `stock` = stock + 1 WHERE `foods`.`id` = '2' diff --git a/bmp-openapi-console/dao/userDao/userDao.go b/bmp-openapi-console/dao/userDao/userDao.go new file mode 100644 index 0000000..8cdc613 --- /dev/null +++ b/bmp-openapi-console/dao/userDao/userDao.go @@ -0,0 +1,123 @@ +package userDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// user user +type User struct { + ID int `gorm:"primaryKey;column:id" json:"-"` + UserID string `gorm:"column:user_id" json:"userId"` // 用户uuid + RoleID string `gorm:"column:role_id" json:"roleId"` // 角色uuid + UserName string `gorm:"column:user_name" json:"userName"` // 用户名,唯一 + Email string `gorm:"column:email" json:"email"` // 邮箱 + PhonePrefix string `gorm:"column:phone_prefix" json:"phonePrefix"` // 国家地区码,如86 + PhoneNumber string `gorm:"column:phone_number" json:"phoneNumber"` // 手机号 + DefaultProjectID string `gorm:"column:default_project_id" json:"defaultProjectId"` // 所属项目uuid + Language string `gorm:"column:language" json:"language"` // 语言(中文/English) + Timezone string `gorm:"column:timezone;type:varchar(64);not null" json:"timezone"` // timezone + Password string `gorm:"column:password" json:"password"` // 密码,sha256非对称加密后存储 + Description string `gorm:"column:description" json:"description"` // 描述 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *User) TableName() string { + return "user" +} + +// Adduser insert a new user into database and returns +// last inserted Id on success. +func Adduser(logger *log.Logger, m *User) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetuserById retrieves user by Id. Returns error if +// Id doesn't exist +func GetUserById(logger *log.Logger, userId string) (v *User, err error) { + v = &User{} + err = dao.Where(logger, dao.IronicRdb, "user_id = ? and is_del = 0", userId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetUserByName(logger *log.Logger, userName string) (v *User, err error) { + v = &User{} + err = dao.Where(logger, dao.IronicRdb, "user_name = ? and is_del = 0", userName).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetuserByUuid retrieves user by Uuid. Returns error if +// Id doesn't exist +func GetUserCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, User{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAlluser retrieves all user matches certain condition. Returns empty list if +// no records exist +func GetAllUser(logger *log.Logger, query map[string]interface{}) (ml []*User, err error) { + + var db = dao.Model(logger, dao.IronicRdb, User{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiuser retrieves all user matches certain condition. Returns empty list if +// no records exist +func GetMultiUser(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*User, err error) { + + var db = dao.Model(logger, dao.IronicRdb, User{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// Updateuser updates user by Id and returns error if +// the record to be updated doesn't exist +func UpdateUserById(logger *log.Logger, m *User) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, User{}).Where("user_id = ?", m.UserID).Save(m).Error +} diff --git a/bmp-openapi-console/dao/volumeDao/volumeDao.go b/bmp-openapi-console/dao/volumeDao/volumeDao.go new file mode 100644 index 0000000..fc1d6a9 --- /dev/null +++ b/bmp-openapi-console/dao/volumeDao/volumeDao.go @@ -0,0 +1,162 @@ +package volumeDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Volume 卷管理表 +type Volume struct { + ID int `gorm:"primaryKey;column:id" json:"-"` // 主键 + // 卷uuid + VolumeID string `gorm:"column:volume_id" json:"volumeId"` + // 设备类型uuid + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` + // 卷名称 + VolumeName string `gorm:"column:volume_name" json:"volumeName"` + // 卷类型:系统卷,数据卷 + VolumeType string `gorm:"column:volume_type" json:"volumeType"` + // 硬盘类型(SSD,HDD) + DiskType string `gorm:"column:disk_type" json:"diskType"` + // 接口类型(SATA,SAS,NVME,不限制) + InterfaceType string `gorm:"column:interface_type" json:"interfaceType"` + // 单盘大小(最小容量) + VolumeSize string `gorm:"column:volume_size" json:"volumeSize"` + // 硬盘单位(GB,TB) + VolumeUnit string `gorm:"column:volume_unit" json:"volumeUnit"` + // 硬盘数量(最低块数) + VolumeAmount int `gorm:"column:volume_amount" json:"volumeAmount"` + //RaidCan string `gorm:"column:raid_can" json:"raidCan"` // RAID配置: (RAID,NO RAID) + //Raid string `gorm:"column:raid" json:"raid"` // RAID模式:RAID1,RIAD10等 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Volume) TableName() string { + return "volume" +} + +// AddVolume insert a new Volume into database and returns +// last inserted Id on success. +func AddVolume(logger *log.Logger, m *Volume) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetVolumeById retrieves Volume by Id. Returns error if +// Id doesn't exist +func GetVolumeById(logger *log.Logger, VolumeId string) (v *Volume, err error) { + v = &Volume{} + err = dao.Where(logger, dao.IronicRdb, "volume_id = ? and is_del = 0", VolumeId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetVolumeByName(logger *log.Logger, VolumeName string) (v *Volume, err error) { + v = &Volume{} + err = dao.Where(logger, dao.IronicRdb, "volume_name = ? and is_del = 0", VolumeName).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetVolumeByUuid retrieves Volume by Uuid. Returns error if +// Id doesn't exist +func GetVolumeCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Volume{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAllVolume retrieves all Volume matches certain condition. Returns empty list if +// no records exist +func GetAllVolume(logger *log.Logger, query map[string]interface{}) (ml []*Volume, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Volume{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiVolume retrieves all Volume matches certain condition. Returns empty list if +// no records exist +func GetMultiVolume(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Volume, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Volume{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateVolume updates Volume by Id and returns error if +// the record to be updated doesn't exist +func UpdateVolumeById(logger *log.Logger, m *Volume) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Volume{}).Where("id = ?", m.ID).Save(m).Error +} + +func UpdateVolumeByWhere(logger *log.Logger, query map[string]interface{}, updates *Volume) (err error) { + var db = dao.Model(logger, dao.IronicWdb, Volume{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +// GetrInstanceSshkeyById retrieves rInstanceSshkey by Id. Returns error if +// Id doesn't exist +func GetSystemVolumeByDeviceTypeId(logger *log.Logger, device_type_id string) (v *Volume, err error) { + v = &Volume{} + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and is_del = 0 and volume_type = 'system'", device_type_id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetAllVolumeByDeviceTypeId(logger *log.Logger, device_type_id string) (ml []*Volume, err error) { + ml = []*Volume{} + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and is_del = 0", device_type_id).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil +} diff --git a/bmp-openapi-console/dao/vxlanDao/vxlanDao.go b/bmp-openapi-console/dao/vxlanDao/vxlanDao.go new file mode 100644 index 0000000..58db9b3 --- /dev/null +++ b/bmp-openapi-console/dao/vxlanDao/vxlanDao.go @@ -0,0 +1,138 @@ +package vxlanDao + +import ( + "errors" + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Vxlan vxlan +type Vxlan struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + VxlanID int64 `gorm:"column:vxlan_id;type:bigint(20) unsigned" json:"vxlan_id"` // vxlan_id + Tenant string `gorm:"index:i_vxlan_tenant;column:tenant;type:varchar(64);not null" json:"tenant"` // 租户 + Az string `gorm:"column:az;type:varchar(32)" json:"az"` + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *Vxlan) TableName() string { + return "vxlan" +} + +// AddVxlan insert a new Vxlan into database and returns +// last inserted Id on success. +func AddVxlan(logger *log.Logger, m *Vxlan) (id int64, err error) { + + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetVxlanById retrieves Vxlan by Id. Returns error if +// Id doesn't exist +func GetVxlanById(logger *log.Logger, id int64) (v *Vxlan, err error) { + v = &Vxlan{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +//GetMaxVxlanID 没找到max方法,自己写 +func GetMaxVxlanId(logger *log.Logger, cloumn string) (n int64, err error) { + + sql := fmt.Sprintf("select max(%s) from vxlan", cloumn) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&n).Error + return +} + +func GetOrCreateVxlan(logger *log.Logger, query map[string]interface{}) (l *Vxlan, err error) { + l = &Vxlan{} + var db = dao.Model(logger, dao.IronicRdb, Vxlan{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err == nil { + return + } + //not found + maxVlanID, _ := GetMaxVxlanId(logger, "vxlan_id") + if maxVlanID < 0 { + return nil, errors.New("get max vxlan_id error!!") + } + s := Vxlan{ + // Az: query["az"].(string), + // Tenant: query["tenant"].(string), + VxlanID: maxVlanID + 1, + } + n, err := dao.CreateAndGetId(logger, dao.IronicRdb, s) + if err != nil { + return nil, err + } + s.ID = n + return &s, nil +} + +func GetOneVxlan(logger *log.Logger, query map[string]interface{}) (l *Vxlan, err error) { + l = &Vxlan{} + var db = dao.Model(logger, dao.IronicRdb, Vxlan{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// GetMultiVxlan retrieves all Vxlan matches certain condition. Returns empty list if +// no records exist +func GetMultiVxlan(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Vxlan, err error) { + var db = dao.Model(logger, dao.IronicRdb, Vxlan{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateVxlan updates Vxlan by Id and returns error if +// the record to be updated doesn't exist +func UpdateVxlanById(logger *log.Logger, m *Vxlan) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Vxlan{}).Where("id = ?", m.ID).Updates(m).Error +} + +func GetByTenant(logger *log.Logger, tanant, az string) (l *Vxlan, err error) { + l = &Vxlan{} + // err = dao.Where(logger, dao.IronicRdb, "tenant = ? and az = ? and is_del = 0", tanant, az).Take(l).Error + err = dao.Where(logger, dao.IronicRdb, "is_del = 0").Take(l).Error + + if err != nil { + return nil, err + } + return l, nil +} diff --git a/bmp-openapi-console/dao/wanIpDao/wanIpDao.go b/bmp-openapi-console/dao/wanIpDao/wanIpDao.go new file mode 100644 index 0000000..b2e5a26 --- /dev/null +++ b/bmp-openapi-console/dao/wanIpDao/wanIpDao.go @@ -0,0 +1,143 @@ +package wanIpDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// WanIP 外网ip +type WanIp struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + Az string `gorm:"unique_index:i_wan_ip_az_ip;column:az;type:varchar(32);not null" json:"az"` // az + WanSubnetID string `gorm:"column:wan_subnet_id;type:varchar(36);not null" json:"wan_subnet_id"` // 外网网段ID + IP string `gorm:"unique_index:i_wan_ip_az_ip;column:ip;type:varchar(32);not null" json:"ip"` // 外网ip + Status int8 `gorm:"column:status;type:tinyint(4);not null" json:"status"` // 是否已使用(0-未使用, 1-已使用) + LineType string `gorm:"column:line_type;type:varchar(20)" json:"line_type"` // 链路类型:bgp、dynamic_bgp + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *WanIp) TableName() string { + return "wan_ip" +} + +// AddWanIp insert a new WanIp into database and returns +// last inserted Id on success. +func AddWanIp(logger *log.Logger, m *WanIp) (id int64, err error) { + + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// AddMultiWanIp insert a new WanIp into database and returns +// last inserted Id on success. +func AddMultiWanIp(logger *log.Logger, m []*WanIp) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, device := range m { + device.CreateTime = time.Now() + device.UpdateTime = time.Now() + if err := tx.Create(device).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetWanIpById retrieves WanIp by Id. Returns error if +// Id doesn't exist +func GetWanIpById(logger *log.Logger, id int64) (v *WanIp, err error) { + + v = &WanIp{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetAllWanIp(logger *log.Logger, query map[string]interface{}) (ml []*WanIp, err error) { + + var db = dao.Model(logger, dao.IronicRdb, WanIp{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiWanIp retrieves all WanIp matches certain condition. Returns empty list if +// no records exist +func GetMultiWanIp(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*WanIp, err error) { + + var db = dao.Model(logger, dao.IronicRdb, WanIp{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateWanIp updates WanIp by Id and returns error if +// the record to be updated doesn't exist +func UpdateWanIpById(logger *log.Logger, m *WanIp) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, WanIp{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateMultiWanIps(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + updates["update_time"] = time.Now() + var db = dao.Model(logger, dao.IronicWdb, WanIp{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func QueryUnusedByAz(logger *log.Logger, az string, offset, limit int64) (ml []*WanIp, err error) { + + // err = dao.Where(logger, dao.IronicRdb, "az = ? and status = 0 and is_del = 0", az).Find(&ml).Error + err = dao.Where(logger, dao.IronicRdb, "status = 0 and is_del = 0").Find(&ml).Error + return + +} + +func QueryByAzAndIP(logger *log.Logger, az string, ips []string) (ml []*WanIp, err error) { + query := map[string]interface{}{ + "ip.in": ips, + // "az": az, + "is_del": "0", + } + var db = dao.Model(logger, dao.IronicRdb, WanIp{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + + err = db.Find(&ml).Error + return +} diff --git a/bmp-openapi-console/dao/wanSubnetDao/wanSubnetDao.go b/bmp-openapi-console/dao/wanSubnetDao/wanSubnetDao.go new file mode 100644 index 0000000..ef93aa9 --- /dev/null +++ b/bmp-openapi-console/dao/wanSubnetDao/wanSubnetDao.go @@ -0,0 +1,78 @@ +package wanSubnetDao + +import ( + "fmt" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// WanSubnet 外网网段 +type WanSubnet struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + UUID string `gorm:"column:uuid;type:varchar(36);not null" json:"uuid"` // 外网网段ID + Az string `gorm:"column:az;type:varchar(32);not null" json:"az"` // az + Cidr string `gorm:"column:cidr;type:varchar(32);not null" json:"cidr"` // 外网网段 + Gateway string `gorm:"column:gateway;type:varchar(32);not null" json:"gateway"` // 外网网关 + Mask string `gorm:"column:mask;type:varchar(32);not null" json:"mask"` // 外网掩码 + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *WanSubnet) TableName() string { + return "wan_subnet" +} + +// AddWanSubnet insert a new WanSubnet into database and returns +// last inserted Id on success. +func AddWanSubnet(logger *log.Logger, m *WanSubnet) (id int64, err error) { + + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicRdb, m) +} + +// GetWanSubnetById retrieves WanSubnet by Id. Returns error if +// Id doesn't exist +func GetWanSubnetById(logger *log.Logger, id int64) (v *WanSubnet, err error) { + + v = &WanSubnet{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllWanSubnet retrieves all WanSubnet matches certain condition. Returns empty list if +// no records exist +func GetMultiWanSubnet(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*WanSubnet, err error) { + var db = dao.Model(logger, dao.IronicRdb, WanSubnet{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + for _, v := range orderConditions { + db = db.Order(v) + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateWanSubnet updates WanSubnet by Id and returns error if +// the record to be updated doesn't exist +func UpdateWanSubnetById(logger *log.Logger, m *WanSubnet) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, WanSubnet{}).Where("id = ?", m.ID).Updates(m).Error +} diff --git a/bmp-openapi-console/go.mod b/bmp-openapi-console/go.mod new file mode 100644 index 0000000..74fda6f --- /dev/null +++ b/bmp-openapi-console/go.mod @@ -0,0 +1,28 @@ +module coding.jd.com/aidc-bmp/bmp-openapi + +go 1.15 + +require github.com/beego/beego/v2 v2.0.1 + +require ( + coding.jd.com/aidc-bmp/bmp_log v0.0.0-00010101000000-000000000000 + git.jd.com/cps-golang/ironic-common v0.0.0-00010101000000-000000000000 + github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df + github.com/go-playground/validator/v10 v10.4.1 + github.com/go-redis/redis v6.15.1+incompatible + github.com/go-sql-driver/mysql v1.5.0 + github.com/google/go-cmp v0.5.5 // indirect + github.com/jinzhu/gorm v1.9.16 + github.com/jinzhu/now v1.1.2 // indirect + github.com/streadway/amqp v1.0.0 + golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 + gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect + gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect + gopkg.in/goyy/goyy.v0 v0.0.0-20190218140538-82e7740e526e +) + +replace github.com/astaxie/beego => github.com/beego/beego v1.12.3 + +replace git.jd.com/cps-golang/ironic-common => ./bmp_vendor/ironic-common + +replace coding.jd.com/aidc-bmp/bmp_log => ./bmp_vendor/bmp_log diff --git a/bmp-openapi-console/go.sum b/bmp-openapi-console/go.sum new file mode 100644 index 0000000..7fd585b --- /dev/null +++ b/bmp-openapi-console/go.sum @@ -0,0 +1,323 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= +github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk= +github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y= +github.com/beego/beego/v2 v2.0.1 h1:07a7Z0Ok5vbqyqh+q53sDPl9LdhKh0ZDy3gbyGrhFnE= +github.com/beego/beego/v2 v2.0.1/go.mod h1:8zyHi1FnWO1mZLwTn62aKRIZF/aIKvkCBB2JYs+eqQI= +github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ= +github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60= +github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= +github.com/coreos/etcd v3.3.25+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U= +github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= +github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= +github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd h1:83Wprp6ROGeiHFAP8WJdI2RoxALQYgdllERc3N5N2DM= +github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= +github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= +github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk= +github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y= +github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0= +github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= +github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df h1:Bao6dhmbTA1KFVxmJ6nBoMuOJit2yjEgLJpIMYpop0E= +github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df/go.mod h1:GJr+FCSXshIwgHBtLglIg9M2l2kQSi6QjVAngtzI08Y= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= +github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= +github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= +github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= +github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis v6.15.1+incompatible h1:BZ9s4/vHrIqwOb0OPtTQ5uABxETJ3NRuUNoSUurnkew= +github.com/go-redis/redis v6.15.1+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= +github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o= +github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/jinzhu/now v1.1.2 h1:eVKgfIdy9b6zbWBMgFpfDPoAMifwSZagU9HmEU6zgiI= +github.com/jinzhu/now v1.1.2/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDuKuq+uX4v1fulaMbA/7ZLLhjc85h7chZGBCQ= +github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= +github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.1.1 h1:sJZmqHoEaY7f+NPP8pgLB/WxulyR3fewgCM2qaSlBb4= +github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus= +github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U= +github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mitchellh/mapstructure v1.3.3 h1:SzB1nHZ2Xi+17FP0zVQBHIZqvwRN9408fJO8h+eeNA8= +github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.0 h1:Iw5WCbBcaAAd0fpRb1c9r5YCylv4XDoCSigm1zLevwU= +github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= +github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.7.0 h1:wCi7urQOGBsYcQROHqpUUX4ct84xp40t9R9JX0FuA/U= +github.com/prometheus/client_golang v1.7.0/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.10.0 h1:RyRA7RzGXQZiW+tGMr7sxa85G1z0yOpM1qq5c8lNawc= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.1.3 h1:F0+tqvhOksq22sc6iCHF5WGlWjdwj92p0udFh1VFBS8= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= +github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= +github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s= +github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE= +github.com/streadway/amqp v1.0.0 h1:kuuDrUJFZL1QYL9hUNuCxNObNzB0bV/ZG5jV3RWAQgo= +github.com/streadway/amqp v1.0.0/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= +github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= +go.etcd.io/etcd v3.3.25+incompatible/go.mod h1:yaeTdrJi5lOmYerz05bd8+V7KubZs8YSFZfzsF9A6aI= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f h1:+Nyd8tzPX9R7BWHguqsrbFdRx3WQ/1ib8I44HXV5yTA= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58 h1:1Bs6RVeBFtLZ8Yi1Hk07DiOqzvwLD/4hln4iahvFlag= +golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk= +gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE= +gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw= +gopkg.in/goyy/goyy.v0 v0.0.0-20190218140538-82e7740e526e h1:gtdbyLCHNaTi70xKjFhe89/vCZvQ/rlPcRyQNgtiArY= +gopkg.in/goyy/goyy.v0 v0.0.0-20190218140538-82e7740e526e/go.mod h1:0xBRLJ/WNDqMy7AGJ/CtRXvdKgU94c7uZ2oeqMR1FgA= +gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.5/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= diff --git a/bmp-openapi-console/logic/apikeyLogic/apikeyLogic.go b/bmp-openapi-console/logic/apikeyLogic/apikeyLogic.go new file mode 100644 index 0000000..3bda0e7 --- /dev/null +++ b/bmp-openapi-console/logic/apikeyLogic/apikeyLogic.go @@ -0,0 +1,186 @@ +package apikeyLogic + +import ( + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/apikeyDao" + + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + namespacePrefix "git.jd.com/cps-golang/ironic-common/ironic/common/NamespacePrefixs" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +func ApikeyEntity2Apikey(logger *log.Logger, o *apikeyDao.Apikey) *responseTypes.Apikey { + + tz := logger.GetPoint("timezone").(string) + return &responseTypes.Apikey{ + ID: o.ID, + ApikeyID: o.ApikeyID, + Name: o.Name, + ReadOnly: o.ReadOnly, + Token: o.Token, + Type: o.Type, + UserID: o.UserID, + CreatedBy: o.CreatedBy, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + UpdatedBy: o.UpdatedBy, + UpdatedTime: util.TimestampToString(int64(o.UpdatedTime), tz), + } +} + +func GetApikeyById(logger *log.Logger, apikeyId string) (*responseTypes.Apikey, error) { + userId := logger.GetPoint("userId").(string) + entity, err := apikeyDao.GetApikeyById(logger, apikeyId) + if err != nil { + logger.Warn("GetapikeyByUuid sql error:", apikeyId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if entity.UserID != userId { + panic(constant.BuildInvalidArgumentWithArgs("无此apikey的访问权限", "cannot access apiKey")) + } + return ApikeyEntity2Apikey(logger, entity), nil +} + +func CreateApikey(logger *log.Logger, param *requestTypes.CreateApikeyRequest) (string, error) { + + userId := logger.GetPoint("userId").(string) + + v, _ := apikeyDao.GetAllApikey(logger, map[string]interface{}{ + "user_id": userId, + "is_del": baseLogic.IS_NOT_DEL, + "source": "console", + }) + if len(v) >= 2 { + logger.Warn("two apikey already exists", userId) + panic(constant.BuildCANCELLEDWithArgs("支持创建2个API密钥", "Only supports creating 2 keypairs")) + } + + list, _ := apikeyDao.GetAllApikey(logger, map[string]interface{}{ + "name": param.Name, + "user_id": userId, + "is_del": baseLogic.IS_NOT_DEL, + "source": "console", + }) + if len(list) != 0 { + logger.Warn("apikey name exist:", param.Name) + panic(constant.BuildCANCELLEDWithArgs("apikey名称已存在", "apikey name exist")) + } + apikeyEntity := &apikeyDao.Apikey{ + Name: param.Name, + ReadOnly: param.ReadOnly, + Token: commonUtil.GetRandString("", 32, false, true, true), + Type: param.Type, + Source: "console", + UserID: userId, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + apikeyEntity.ApikeyID = commonUtil.GetRandString("apikey-", namespacePrefix.INSTANCE_ID_LENGTH, false, true, true) + if _, err := apikeyDao.AddApikey(logger, apikeyEntity); err != nil { + logger.Warnf("Createapikey Addapikey sql error, entity:%s, error:%s", util.ObjToJson(apikeyEntity), err.Error()) + return "", err + } + return apikeyEntity.ApikeyID, nil +} + +func ModifyApikey(logger *log.Logger, param *requestTypes.ModifyApikeyRequest, apikeyId string) error { + userId := logger.GetPoint("userId").(string) + list, _ := apikeyDao.GetAllApikey(logger, map[string]interface{}{ + "name": param.Name, + "user_id": userId, + "is_del": baseLogic.IS_NOT_DEL, + }) + if len(list) != 0 { + logger.Warn("apikey name exist:", param.Name) + panic(constant.BuildCANCELLEDWithArgs("apikey名称已存在", "apikey name exist")) + } + + k, err := apikeyDao.GetApikeyById(logger, apikeyId) + if err != nil { + logger.Warn("GetapikeyByUuid sql error:", apikeyId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if userId != k.UserID { + panic(constant.BuildInvalidArgumentWithArgs("无权修改此apikey", "cannot modify apikey")) + } + k.Name = param.Name + k.ReadOnly = param.ReadOnly + if err := apikeyDao.UpdateApikeyById(logger, k); err != nil { + logger.Warn("Modifyapikey UpdateapikeyById sql error:", apikeyId, err.Error()) + return err + } + return nil +} + +func DeleteApikey(logger *log.Logger, apikeyId string) error { + userId := logger.GetPoint("userId").(string) + entity, err := apikeyDao.GetApikeyById(logger, apikeyId) + if err != nil { + logger.Warn("GetapikeyByUuid sql error:", apikeyId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if entity.UserID != userId { + panic(constant.BuildInvalidArgumentWithArgs("无权删除此apikey", "cannot delete apikey")) + } + entity.IsDel = 1 + entity.UpdatedTime = int(time.Now().Unix()) + entity.DeletedTime = int(time.Now().Unix()) + if err := apikeyDao.UpdateApikeyById(logger, entity); err != nil { + logger.Warn("Deleteapikey UpdateapikeyById sql error:", apikeyId, err.Error()) + return err + } + return nil +} + +func GetApikeyList(logger *log.Logger, param requestTypes.QueryApikeysRequest, p util.Pageable) ([]*responseTypes.Apikey, int64, error) { + userId := logger.GetPoint("userId").(string) + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "name": param.Name, + //"apikey_id": param.apikeyID, + //"default_project_id": param.DefaultProjectID, + "user_id": userId, + "is_del": 0, + "source": "console", + } + count, err := apikeyDao.GetApikeyCount(logger, query) + if err != nil { + logger.Warnf("GetapikeyCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*apikeyDao.Apikey{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = apikeyDao.GetMultiApikey(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = apikeyDao.GetMultiApikey(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("QueryByapikeyIds GetAllapikey sql error:", err.Error()) + return nil, 0, err + } + apikeys := []*responseTypes.Apikey{} + for _, entity := range entityList { + apikeys = append(apikeys, ApikeyEntity2Apikey(logger, entity)) + } + return apikeys, count, nil +} + +func ValidateApiKey(logger *log.Logger, key string) (*apikeyDao.Apikey, error) { + k, err := apikeyDao.GetApikeyByToken(logger, key) + if err != nil { + return nil, err + } + if k == nil { + return nil, nil + } + return k, nil +} diff --git a/bmp-openapi-console/logic/auditLogLogic/auditLogLogic.go b/bmp-openapi-console/logic/auditLogLogic/auditLogLogic.go new file mode 100644 index 0000000..872c3d2 --- /dev/null +++ b/bmp-openapi-console/logic/auditLogLogic/auditLogLogic.go @@ -0,0 +1,251 @@ +package auditLogLogic + +import ( + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/auditLogsDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + "git.jd.com/cps-golang/ironic-common/ironic/enums/AuditLogsType" +) + +var auditLogsTypeEnMap = map[string]string{ + AuditLogsType.AuditLogsPutaway: "putaway", + AuditLogsType.AuditLogsUnPutaway: "unPutaway", + AuditLogsType.AuditLogsStartInstances: "startInstance", + AuditLogsType.AuditLogsStopInstances: "stopInstance", + AuditLogsType.AuditLogsRestartInstances: "restartInstance", + AuditLogsType.AuditLogsResetInstanceStatus: "resetInstanceStatus", + AuditLogsType.AuditLogsRemoveDevice: "removeDevice", + AuditLogsType.AuditLogsInstanceResetPassword: "resetInstancePassword", + AuditLogsType.AuditLogsReinstallInstance: "reinstallInstance", + AuditLogsType.AuditLogsDeleteDevice: "deleteDevice", + AuditLogsType.AuditLogsEditInstanceName: "editInstanceName", + AuditLogsType.AuditLogsCollectHardwareInfo: "collectDevice", + AuditLogsType.AuditLogsTypeCreateInstances: "createInstance", + AuditLogsType.AuditLogsDeleteInstance: "deleteInstance", + AuditLogsType.AuditLogsTypeLockInstances: "lockInstance", +} + +// +var auditLogsTypeZhMap = map[string]string{ + AuditLogsType.AuditLogsPutaway: "设备上架", + AuditLogsType.AuditLogsUnPutaway: "设备下架", + AuditLogsType.AuditLogsStartInstances: "实例开机", + AuditLogsType.AuditLogsStopInstances: "实例关机", + AuditLogsType.AuditLogsRestartInstances: "实例重启", + AuditLogsType.AuditLogsResetInstanceStatus: "重置实例状态", + AuditLogsType.AuditLogsRemoveDevice: "设备移除", + AuditLogsType.AuditLogsInstanceResetPassword: "重置密码", + AuditLogsType.AuditLogsReinstallInstance: "重装系统", + AuditLogsType.AuditLogsDeleteDevice: "设备删除", + AuditLogsType.AuditLogsEditInstanceName: "编辑实例名称", + AuditLogsType.AuditLogsCollectHardwareInfo: "设备采集", + AuditLogsType.AuditLogsTypeCreateInstances: "创建实例", + AuditLogsType.AuditLogsDeleteInstance: "实例删除", + AuditLogsType.AuditLogsTypeLockInstances: "实例锁定", +} + +func SaveAuditLogs(logger *log.Logger, deviceId string, instanceId string, msgType string) error { + + userID := logger.GetPoint("userId").(string) + var username string + if userID != "" { + userEntity, err := userDao.GetUserById(logger, userID) + if err != nil { + logger.Warnf("SaveAuditLogs.GetUserById error, user_id:%s, error:%s", userID, err.Error()) + } else { + username = userEntity.UserName + } + } + + deviceEntity, err := deviceDao.GetDeviceById(logger, deviceId) + if err != nil { + logger.Warnf("SaveAuditLogs.GetBySn error, device_id:%s, error:%s", deviceId, err.Error()) + } + + al := &auditLogsDao.AuditLogs{ + Logid: util.GetUuid("al-"), + Sn: deviceEntity.Sn, + DeviceID: deviceEntity.DeviceID, + InstanceID: instanceId, + Operation: msgType, + OperateUserID: userID, + OperateUserName: username, + CreatedTime: int(time.Now().Unix()), + Result: "success", + } + _, err = auditLogsDao.AddAuditLogs(logger, al) + if err != nil { + logger.Warnf("SaveAuditLogs.AddAuditLogs error, al:%s, error:%s", util.ObjToJson(al), err.Error()) + } else { + logger.Infof("SaveAuditLogs.AddAuditLogs success, al:%s", util.ObjToJson(al)) + } + return err +} + +func QueryAuditLogs(logger *log.Logger, param *requestTypes.DescribeAuditLogsRequest, p util.Pageable) ([]*responseTypes.AuditLog, int64, error) { + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "instance_id": param.InstanceID, + "is_del": 0, + } + if param.Operation != "" { + query["operation.in"] = strings.Split(param.Operation, ",") + } + if param.UserName != "" { + query["operate_user_name"] = param.UserName + } + if param.StartTime != 0 { + query["created_time.gte"] = param.StartTime + } + if param.EndTime != 0 { + query["created_time.lte"] = param.EndTime + } + if param.Result != "" { + query["result.in"] = strings.Split(param.Result, ",") + } + + count, err := auditLogsDao.GetAuditLogsCount(logger, query) + if err != nil { + logger.Warnf("QueryAuditLogs.GetAuditLogsCount sql error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + dts := []*auditLogsDao.AuditLogs{} + if param.IsAll == baseLogic.IS_ALL { + dts, err = auditLogsDao.GetAllAuditLogs(logger, query) + } else { + dts, err = auditLogsDao.QueryAuditLogs(logger, query, offset, limit) + } + if err != nil { + logger.Warnf("QueryAuditLogs sql err, param:%s, error:%s", util.ObjToJson(param), err.Error()) + return nil, 0, err + } + res := []*responseTypes.AuditLog{} + + for _, value := range dts { + v := AuditLogEntity2AuditLog(logger, value) + + res = append(res, v) + } + return res, count, err +} + +func AuditLogEntity2AuditLog(logger *log.Logger, param *auditLogsDao.AuditLogs) *responseTypes.AuditLog { + res := &responseTypes.AuditLog{ + ID: param.ID, + LogID: param.Logid, + Operation: param.Operation, + UserName: param.OperateUserName, + UserID: param.OperateUserID, + Sn: param.Sn, + DeviceID: param.DeviceID, + InstanceID: param.InstanceID, + Result: param.Result, + FailReason: param.FailReason, + OperateTime: param.CreatedTime, + FinishTime: param.UpdatedTime, + } + var reason string + if logger.GetPoint("language").(string) == baseLogic.EN_US { + res.OperationName = auditLogsTypeEnMap[param.Operation] + reason = baseLogic.InstanceReasonEn[res.FailReason] + } else { + res.OperationName = auditLogsTypeZhMap[param.Operation] + reason = baseLogic.InstanceReason[res.FailReason] + } + if reason == "" { + reason = res.FailReason + } + res.FailReason = reason + + return res +} + +func DescribeAuditLogsTypes(logger *log.Logger) []responseTypes.AuditLogsType { + if logger.GetPoint("language").(string) == baseLogic.EN_US { + return []responseTypes.AuditLogsType{ + { + Operation: AuditLogsType.AuditLogsStartInstances, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsStartInstances], + }, + { + Operation: AuditLogsType.AuditLogsStopInstances, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsStopInstances], + }, + { + Operation: AuditLogsType.AuditLogsRestartInstances, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsRestartInstances], + }, + { + Operation: AuditLogsType.AuditLogsTypeLockInstances, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsTypeLockInstances], + }, + { + Operation: AuditLogsType.AuditLogsInstanceResetPassword, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsInstanceResetPassword], + }, + { + Operation: AuditLogsType.AuditLogsReinstallInstance, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsReinstallInstance], + }, + { + Operation: AuditLogsType.AuditLogsEditInstanceName, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsEditInstanceName], + }, + { + Operation: AuditLogsType.AuditLogsTypeCreateInstances, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsTypeCreateInstances], + }, + { + Operation: AuditLogsType.AuditLogsDeleteInstance, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsDeleteInstance], + }, + } + } else { + return []responseTypes.AuditLogsType{ + { + Operation: AuditLogsType.AuditLogsStartInstances, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsStartInstances], + }, + { + Operation: AuditLogsType.AuditLogsStopInstances, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsStopInstances], + }, + { + Operation: AuditLogsType.AuditLogsRestartInstances, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsRestartInstances], + }, + { + Operation: AuditLogsType.AuditLogsTypeLockInstances, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsTypeLockInstances], + }, + { + Operation: AuditLogsType.AuditLogsInstanceResetPassword, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsInstanceResetPassword], + }, + { + Operation: AuditLogsType.AuditLogsReinstallInstance, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsReinstallInstance], + }, + { + Operation: AuditLogsType.AuditLogsEditInstanceName, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsEditInstanceName], + }, + { + Operation: AuditLogsType.AuditLogsTypeCreateInstances, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsTypeCreateInstances], + }, + { + Operation: AuditLogsType.AuditLogsDeleteInstance, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsDeleteInstance], + }, + } + } +} diff --git a/bmp-openapi-console/logic/baseLogic/baseLogic.go b/bmp-openapi-console/logic/baseLogic/baseLogic.go new file mode 100644 index 0000000..2c50cbe --- /dev/null +++ b/bmp-openapi-console/logic/baseLogic/baseLogic.go @@ -0,0 +1,280 @@ +package baseLogic + +var ( + DeviceManageStatus = map[string]string{ + IN: "已入库", + PUTAWAY: "已上架", + UNPUTAWAY: "已下架", + CREATED: "已创建", + PUTAWAYING: "上架中", + PUTAWAYFAIL: "上架失败", + UNPUTAWAYING: "下架中", + REMOVED: "已移除", + } + DeviceManageStatusEn = map[string]string{ + IN: "Stocked", + PUTAWAY: "Mounted", + UNPUTAWAY: "Unmounted", + CREATED: "created", + PUTAWAYING: "Mounting", + PUTAWAYFAIL: "Mount failed", + UNPUTAWAYING: "Unmounting", + REMOVED: "removed", + } + DeviceReason = map[string]string{ + DEFAULT_BMP_ERROR_CODE: "未知错误", + PING_ILOIP_ERROR: "ping带外不通", + USERNAME_OR_PASSWORD_ERROR: "带外用户名或密码错误", + USER_PRIVILEGE_ERROR: "用户权限错误", + PING_SUBNET_GATEWAY_ERROR: "ping子网网关错误", + MAC1_ERROR: "mac1地址有误", + MAC2_ERROR: "mac2地址有误", + } + DeviceReasonEn = map[string]string{ + DEFAULT_BMP_ERROR_CODE: "unknown error message", + PING_ILOIP_ERROR: "ping OOB fails", + USERNAME_OR_PASSWORD_ERROR: "OOB Username does not exist or password is wrong", + USER_PRIVILEGE_ERROR: "User permission error", + PING_SUBNET_GATEWAY_ERROR: "ping subnet gateway error", + MAC1_ERROR: "mac1 address is wrong", + MAC2_ERROR: "mac2 address is wrong", + } + InstanceReason = map[string]string{ + DEFAULT_BMP_ERROR_CODE: "未知错误", + MakeRaidError: "raid失败", + MakePartitionsError: "分区失败", + WriteImageTarError: "写入镜像失败", + SetPasswordError: "设置密码失败", + SetCloudinitConfError: "cloudinit初始化失败", + + SetNocloudUserDataError: "设置用户自定义指令失败", + SetNocloudMetaDataError: "设置metadata失败", + SetNocloudNetworkError: "设置网络失败", + PingError: "PXE启动失败", + + DHCPConfigAddHostError: "设置DHCP配置失败", + DHCPConfigDelHostError: "删除DHCP配置失败", + SetDISKBootError: "设置硬盘启动失败", + PowerCycleError: "重启失败", + PowerOffError: "关机失败", + PowerOnError: "开机失败", + SetPXEBootError: "设置PXE启动失败", + + InitRootDeviceError: "初始化设备信息失败", + //windows专用指令 + WriteImageError: "写入镜像失败", + SetMetaDataError: "设置metadata失败", + SetNetworkDataError: "设置网络失败", + } + InstanceReasonEn = map[string]string{ + DEFAULT_BMP_ERROR_CODE: "unknown error message", + MakeRaidError: "raid failed", + MakePartitionsError: "Partition failed", + WriteImageTarError: "Failed to import image", + SetPasswordError: "Failed to set password", + SetCloudinitConfError: "cloudinit initialization failed", + + SetNocloudUserDataError: "Failed to set user-defined directive", + SetNocloudMetaDataError: "Failed to set metadata", + SetNocloudNetworkError: "Network setup failed", + PingError: "PXE start failed", + + DHCPConfigAddHostError: "Add dhcp failed", + DHCPConfigDelHostError: "Del dhcp failed", + SetDISKBootError: "Set disk boot failed", + PowerCycleError: "PowerCycle failed", + PowerOffError: "PowerOff failed", + PowerOnError: "PowerOn failed", + SetPXEBootError: "SetPXEBoot failed", + + InitRootDeviceError: "InitRootDevice failed", + //windows专用指令 + WriteImageError: "Failed to import image", + SetMetaDataError: "Failed to set metadata", + SetNetworkDataError: "Network setup failed", + } + InstanceLock = map[string]string{ + LOCKED: "锁定", + UNLOCKED: "解锁", + } + InstanceLockEn = map[string]string{ + LOCKED: "Locked", + UNLOCKED: "Unlocked", + } + InstanceStatus = map[string]string{ + CREATING: "创建中", + STARTING: "开机中", + RUNNING: "运行", + STOPPING: "关机中", + STOPPED: "已关机", + RESTARTING: "重启中", + RESETTING_PASSWORD: "重置密码中", + DESTROYING: "删除中", + DESTROYED: "已删除", + ERROR: "错误", + // 创建失败 + CREATE_ERROR: "创建失败", + // 开机失败 + START_ERROR: "开机失败", + // 关机失败 + STOP_ERROR: "关机失败", + // 重启失败 + RESTART_ERROR: "重启失败", + //重装失败 + REINSTALL_ERROR: "重装失败", + //重置密码失败 + RESETPASSWD_ERROR: "重置密码失败", + // 销毁失败 + DESTROY_ERROR: "删除失败", + UPGRADING: "调整配置中", + REINSTALLING: "重装系统中", + } + InstanceStatusEn = map[string]string{ + CREATING: "Creating", + STARTING: "Starting up", + RUNNING: "running", + STOPPING: "Shutting Down", + STOPPED: "Shut Down", + RESTARTING: "Rebooting", + RESETTING_PASSWORD: "Resetting password", + DESTROYING: "Destroying", + DESTROYED: "destroyed", + ERROR: "Error", + // 创建失败 + CREATE_ERROR: "Creation failed", + // 开机失败 + START_ERROR: "Startup failed", + // 关机失败 + STOP_ERROR: "Shutdown failed", + // 重启失败 + RESTART_ERROR: "Reboot failed", + //重装失败 + REINSTALL_ERROR: "Reinstall failed", + //重置密码失败 + RESETPASSWD_ERROR: "Resetpasswd failed", + // 销毁失败 + DESTROY_ERROR: "Delete failed", + UPGRADING: "Upgrading", + REINSTALLING: "Reinstalling System", + } + DeviceTypeSeries = map[string]string{ + COMPUTER: "计算型", + STORAGE: "存储型", + GPU: "GPU", + OTHER: "其它", + } + DeviceTypeSeriesEn = map[string]string{ + COMPUTER: "Computer Class", + STORAGE: "Storage Class", + GPU: "GPU", + OTHER: "Other Classes", + } + Source = map[string]string{ + COMMON: "预置镜像", + USER_DEFINED: "自定义镜像", + } + SourceEn = map[string]string{ + COMMON: "Preset image", + USER_DEFINED: "Custom image", + } +) + +const ( + IS_DEL = 1 + IS_NOT_DEL = 0 + DATE_FORMAT = "2006-01-02 15:04:05" + DATE_UTC_FORMAT = "2006-01-02T15:04:05Z" + IS_ALL = "1" + IS_NOT_ALL = "" + + EN_US = "en_US" + ZH_CN = "zh_CN" + + IN = "in" //已入库 + PUTAWAY = "putaway" //已上架 + CREATED = "created" //已创建 + PUTAWAYING = "putawaying" //上架中 + PUTAWAYFAIL = "putawayfail" //上架失败 + UNPUTAWAY = "unputaway" //下架 + UNPUTAWAYING = "unputawaying" //下架中,将“已上架”的设备执行“下架”操作的中间过程状态 + REMOVED = "removed" //已移除 + + DEFAULT_BMP_ERROR_CODE = "ERROR" + USERNAME_OR_PASSWORD_ERROR = "USERNAME_OR_PASSWORD_ERROR" + USER_PRIVILEGE_ERROR = "USER_PRIVILEGE_ERROR" + PING_ILOIP_ERROR = "PING_ILOIP_ERROR" + PING_SUBNET_GATEWAY_ERROR = "PING_SUBNET_GATEWAY_ERROR" + MAC1_ERROR = "MAC1_ERROR" + MAC2_ERROR = "MAC2_ERROR" + + //instance error + DHCPConfigAddHostError = "DHCPConfigAddHostError" + DHCPConfigDelHostError = "DHCPConfigDelHostError" + SetDISKBootError = "SetDISKBootError" + PowerCycleError = "PowerCycleError" + PowerOffError = "PowerOffError" + PowerOnError = "PowerOnError" + SetPXEBootError = "SetPXEBootError" + + InitRootDeviceError = "InitRootDeviceError" + //windows专用指令 + WriteImageError = "WriteImageError" + SetMetaDataError = "SetMetaDataError" + SetNetworkDataError = "SetNetworkDataError" + + PingError = "PingError" + MakeRaidError = "MakeRaidError" + + MakePartitionsError = "MakePartitionsError" + WriteImageTarError = "WriteImageTarError" + SetPasswordError = "SetPasswordError" + SetCloudinitConfError = "SetCloudinitConfError" + + SetNocloudUserDataError = "SetNocloudUserDataError" + SetNocloudMetaDataError = "SetNocloudMetaDataError" + SetNocloudNetworkError = "SetNocloudNetworkError" + + LOCKED = "locked" + UNLOCKED = "unlocked" + DEFAULTPROJECTNAME = "默认项目" + DEFAULTPROJECTNAME_EN = "default project" + //实例状态相关 + CREATING = "creating" + STARTING = "starting" + RUNNING = "running" + STOPPING = "stopping" + STOPPED = "stopped" + RESTARTING = "restarting" + RESETTING_PASSWORD = "resetting_password" + DESTROYING = "destroying" + DESTROYED = "destroyed" + ERROR = "error" + // 创建失败 + CREATE_ERROR = "Creation failed" + // 开机失败 + START_ERROR = "Startup failed" + // 关机失败 + STOP_ERROR = "Shutdown failed" + // 重启失败 + RESTART_ERROR = "Reboot failed" + // 重装失败 + REINSTALL_ERROR = "Reinstall failed" + //重置密码失败 + RESETPASSWD_ERROR = "Resetpasswd failed" + // 销毁失败 + DESTROY_ERROR = "Delete failed" + UPGRADING = "upgrading" + REINSTALLING = "reinstalling" + //机型相关 + COMPUTER = "computer" + STORAGE = "storage" + GPU = "gpu" + OTHER = "other" + + COMMON = "common" //内置镜像 + USER_DEFINED = "user_defined" //自定义 + + ROLE_ADMIN_UUID = "role-admin-uuid-01" //平台拥有着 + ROLE_OPERATOR_UUID = "role-operator-uuid-01" //运营平台 + ROLE_USER_UUID = "role-user-uuid-01" //控制台 +) diff --git a/bmp-openapi-console/logic/deviceLogic/deviceLogic.go b/bmp-openapi-console/logic/deviceLogic/deviceLogic.go new file mode 100644 index 0000000..a142093 --- /dev/null +++ b/bmp-openapi-console/logic/deviceLogic/deviceLogic.go @@ -0,0 +1,797 @@ +package deviceLogic + +import ( + "strconv" + "strings" + "sync" + "time" + + beego "github.com/beego/beego/v2/server/web" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/imageDao" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceTypeDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/diskDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + namespacePrefix "git.jd.com/cps-golang/ironic-common/ironic/common/NamespacePrefixs" + + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + + deviceDao "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceDao" + idcApi "coding.jd.com/aidc-bmp/bmp-openapi/service/idc_api" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateDeviceMq struct { + Action string `json:"action"` + Sn string `json:"sn"` + Subnet string `json:"subnet"` + SubnetMask string `json:"subnet_mask"` + Routes string `json:"routes"` +} + +//检测设备状态,给driver发消息 ,验证带外等信息是否正确 +type CheckDeviceMq struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` + Privilege string `json:"privilege"` +} + +var wg sync.WaitGroup + +func buildDeviceEntity(logger *log.Logger, c *requestTypes.CreateDeviceSpec, deviceType *deviceTypeDao.DeviceType) *deviceDao.Device { + ipv6, _ := beego.AppConfig.String("gateway6") + return &deviceDao.Device{ + DeviceID: commonUtil.GetRandString("d-", namespacePrefix.IMAGE_ID_LENGTH, false, true, true), + InstanceID: "", + IDcID: deviceType.IDcID, + DeviceTypeID: deviceType.DeviceTypeID, + ManageStatus: baseLogic.IN, //导入设备以后,默认已入库 + + Brand: c.Brand, + Model: c.Model, + DeviceSeries: deviceType.DeviceSeries, + Cabinet: c.Cabinet, + UPosition: c.UPosition, + Sn: c.Sn, + IloUser: c.IloUser, + IloPassword: c.IloPassword, + IloIP: c.IloIP, + Description: c.Description, + + Mac1: c.Mac1, + Mac2: c.Mac2, + SwitchIP1: c.SwitchIP1, + SwitchPort1: c.SwitchPort1, + SwitchIP2: c.SwitchIP2, + SwitchPort2: c.SwitchPort2, + + SwitchUser1: c.SwitchUser1, + SwitchPassword1: c.SwitchPassword1, + SwitchUser2: c.SwitchUser2, + SwitchPassword2: c.SwitchPassword2, + SwitchIP: c.SwitchIP, + + Mask: c.Mask, + Gateway: c.Gateway, + PrivateIPv4: c.PrivateIPv4, + PrivateIPv6: c.PrivateIPv6, + Gateway6: ipv6, + AdapterID: *c.AdapterID, + + RaidDriver: c.RaidDriver, + CreatedBy: logger.GetPoint("username").(string), + UpdatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + } +} + +func DeviceEntity2Device(logger *log.Logger, d *deviceDao.Device, idcMap map[string]idcDao.Idc, deviceTypeMap map[string]deviceTypeDao.DeviceType, deviceTypeMapInfo map[string]map[string]string, instanceMap map[string]instanceDao.Instance, imageMap map[string]imageDao.Image) *responseTypes.Device { + + tz := logger.GetPoint("timezone").(string) + //idc, err := idcDao.GetIdcById(logger, d.IDcID) //获取机房信息 + //if err != nil { + // idc = &idcDao.Idc{} + //} + idc := idcMap[d.IDcID] + //entity, err := deviceTypeDao.GetOneDeviceType(logger, map[string]interface{}{"device_type_id": d.DeviceTypeID}) + //if err != nil { + // entity = &deviceTypeDao.DeviceType{} + //} + entity := deviceTypeMap[d.DeviceTypeID] + //instance, err := instanceDao.GetInstanceById(logger, d.InstanceID) + //if instance == nil { + // instance = &instanceDao.Instance{} + //} + instance := instanceMap[d.InstanceID] + //image, err := imageDao.GetImageByUuid(logger, instance.ImageID) + //if image == nil { + // image = &imageDao.Image{} + //} + image := imageMap[instance.ImageID] + //user, _ := userDao.GetUserById(logger, instance.UserID) + //if user == nil { + // user = &userDao.User{} + //} + language := logger.GetPoint("language").(string) + reason := baseLogic.DeviceReason[d.Reason] + if language == baseLogic.EN_US { + reason = baseLogic.DeviceReasonEn[d.Reason] + } + instanceStatusName := baseLogic.InstanceStatus[instance.Status] + if language == baseLogic.EN_US { + instanceStatusName = baseLogic.InstanceStatusEn[instance.Status] + } + instanceReason := baseLogic.InstanceReason[instance.Reason] + if language == baseLogic.EN_US { + instanceReason = baseLogic.InstanceReasonEn[instance.Reason] + } + deviceManageStatusName := baseLogic.DeviceManageStatus[d.ManageStatus] + if language == baseLogic.EN_US { + deviceManageStatusName = baseLogic.DeviceManageStatusEn[d.ManageStatus] + } + deviceSeriesName := baseLogic.DeviceTypeSeries[d.DeviceSeries] + if language == baseLogic.EN_US { + deviceSeriesName = baseLogic.DeviceTypeSeriesEn[d.DeviceSeries] + } + idcName := idc.Name + if language == baseLogic.EN_US { + idcName = idc.NameEn + } + var ( + iloUser string + iloPassword string + switchUser1 string + switchUser2 string + switchPassword1 string + switchPassword2 string + encloure1 string + slot1 int + encloure2 string + slot2 int + ) + //disk, _ := diskDao.GetAllDisk(logger, map[string]interface{}{"device_id": d.DeviceID}) + //if len(disk) == 1 { + // encloure1 = disk[0].Enclosure + // slot1 = disk[0].Slot + //} else if len(disk) == 2 { + // encloure1 = disk[0].Enclosure + // slot1 = disk[0].Slot + // encloure2 = disk[1].Enclosure + // slot2 = disk[1].Slot + //} + if d.IloUser == "" { + iloUser = idc.IloUser + } else { + iloUser = d.IloUser + } + if d.IloPassword == "" { + iloPassword = idc.IloPassword + } else { + iloPassword = d.IloPassword + } + if d.SwitchUser1 == "" { + switchUser1 = idc.SwitchUser1 + } else { + switchUser1 = d.SwitchUser1 + } + if d.SwitchPassword1 == "" { + switchPassword1 = idc.SwitchPassword1 + } else { + switchPassword1 = d.SwitchPassword1 + } + if d.SwitchUser2 == "" { + switchUser2 = idc.SwitchUser2 + } else { + switchUser2 = d.SwitchUser2 + } + if d.SwitchPassword2 == "" { + switchPassword2 = idc.SwitchPassword2 + } else { + switchPassword2 = d.SwitchPassword2 + } + return &responseTypes.Device{ + ID: d.ID, + DeviceID: d.DeviceID, + IdcID: d.IDcID, + InstanceID: d.InstanceID, + InstanceName: instance.InstanceName, + InstanceStatus: instance.Status, + InstanceStatusName: instanceStatusName, + InstanceReason: instanceReason, + Locked: instance.Locked, + //InstanceOwer: user.UserName, + UserId: d.UserId, + UserName: d.UserName, + InstanceCreatedTime: util.TimestampToString(int64(instance.CreatedTime), tz), + InstanceDescription: instance.Description, + + DeviceTypeID: d.DeviceTypeID, + ManageStatus: d.ManageStatus, + ManageStatusName: deviceManageStatusName, + + ImageName: image.ImageName, + + Brand: d.Brand, + Model: d.Model, + Reason: reason, + Cabinet: d.Cabinet, + UPosition: d.UPosition, + Sn: d.Sn, + Description: d.Description, + + Mac1: d.Mac1, + Mac2: d.Mac2, + SwitchIP1: d.SwitchIP1, + SwitchPort1: d.SwitchPort1, + SwitchIP2: d.SwitchIP2, + SwitchPort2: d.SwitchPort2, + //如果设备不存在,从idc中获取 + IloUser: iloUser, + IloPassword: iloPassword, + IloIP: d.IloIP, //必填 + SwitchUser1: switchUser1, + SwitchPassword1: switchPassword1, + SwitchUser2: switchUser2, + SwitchPassword2: switchPassword2, + SwitchIP: d.SwitchIP, + + Mask: d.Mask, + Gateway: d.Gateway, + PrivateIPv4: d.PrivateIPv4, + PrivateIPv6: d.PrivateIPv6, + AdapterID: d.AdapterID, + + Enclosure1: encloure1, + Slot1: slot1, + Enclosure2: encloure2, + Slot2: slot2, + RaidDriver: d.RaidDriver, + CreatedBy: d.CreatedBy, + UpdatedBy: d.UpdatedBy, + CreatedTime: util.TimestampToString(int64(d.CreatedTime), tz), + UpdatedTime: util.TimestampToString(int64(d.UpdatedTime), tz), + + //以下字段从其他表中获取 + //idc + IdcName: idcName, + IDcNameEn: idc.NameEn, + //deviceType + + DeviceType: entity.DeviceType, + DeviceSeries: d.DeviceSeries, + DeviceSeriesName: deviceSeriesName, + + DeviceTypeName: entity.Name, + Architecture: entity.Architecture, + CPUAmount: entity.CPUAmount, + CPUCores: entity.CPUCores, + CPUFrequency: entity.CPUFrequency, + CPUManufacturer: entity.CPUManufacturer, + CPUModel: entity.CPUModel, + + MemType: entity.MemType, + MemAmount: entity.MemAmount, + MemSize: entity.MemSize, + MemFrequency: entity.MemFrequency, + NicAmount: entity.NicAmount, + NicRate: entity.NicRate, + InterfaceMode: entity.InterfaceMode, + SystemVolumeType: entity.SystemVolumeType, + SystemVolumeInterfaceType: entity.DataVolumeInterfaceType, + SystemVolumeAmount: entity.SystemVolumeAmount, + SystemVolumeSize: entity.SystemVolumeSize, + DataVolumeType: entity.DataVolumeType, + DataVolumeInterfaceType: entity.SystemVolumeInterfaceType, + DataVolumeAmount: entity.DataVolumeAmount, + DataVolumeSize: entity.DataVolumeSize, + GpuAmount: entity.GpuAmount, + GpuManufacturer: entity.GpuManufacturer, + GpuModel: entity.GpuModel, + + //拼装信息 + CpuInfo: deviceTypeMapInfo[entity.DeviceTypeID]["cpu_"], + MemInfo: deviceTypeMapInfo[entity.DeviceTypeID]["mem_"], + SvInfo: deviceTypeMapInfo[entity.DeviceTypeID]["sv_"], + DvInfo: deviceTypeMapInfo[entity.DeviceTypeID]["dv_"], + GpuInfo: deviceTypeMapInfo[entity.DeviceTypeID]["gpu_"], + NicInfo: deviceTypeMapInfo[entity.DeviceTypeID]["nic_"], + } +} +func GetDeviceTypeInfo(logger *log.Logger, v *deviceTypeDao.DeviceType) map[string]string { + language := logger.GetPoint("language").(string) + + cpu_ := v.CPUManufacturer + " " + v.CPUModel + "(" + strconv.Itoa(int(v.CPUAmount)) + "*" + strconv.Itoa(int(v.CPUCores)) + "物理核," + v.CPUFrequency + "GHz)" + if language == baseLogic.EN_US { + cpu_ = v.CPUManufacturer + " " + v.CPUModel + "(" + strconv.Itoa(int(v.CPUAmount)) + "*" + strconv.Itoa(int(v.CPUCores)) + "cores," + v.CPUFrequency + "GHz)" + } + mem_ := strconv.Itoa(int(v.MemAmount)*int(v.MemSize)) + "GB(" + strconv.Itoa(int(v.MemSize)) + "GB*" + strconv.Itoa(int(v.MemAmount)) + ")" + v.MemType + " " + strconv.Itoa(int(v.MemFrequency)) + "MHz" + // 系统盘:显示总容量 (单块容量 接口类型 类型*数量 RAID 模式) + // 240GB 240GB SATA SSD*2 RAID1 + sv_ := strconv.Itoa(int(v.SystemVolumeAmount)*int(v.SystemVolumeSize)) + "GB(" + strconv.Itoa(int(v.SystemVolumeSize)) + "GB " + v.SystemVolumeInterfaceType + " " + v.SystemVolumeType + "*" + strconv.Itoa(int(v.SystemVolumeAmount)) + ")" + if v.SystemVolumeUnit == "TB" { + sv_ = Trim(strconv.FormatFloat(float64(v.SystemVolumeAmount)*float64(v.SystemVolumeSize)/1000, 'f', 2, 64)) + "TB(" + Trim(strconv.FormatFloat(float64(v.SystemVolumeSize)/1000, 'f', 2, 64)) + "TB " + v.SystemVolumeInterfaceType + " " + v.SystemVolumeType + "*" + strconv.Itoa(int(v.SystemVolumeAmount)) + ")" + } + // 数据盘:显示总容量 (单块容量 接口类型 类型*数量 RAID 模式) + dv_ := strconv.Itoa(int(v.DataVolumeAmount)*int(v.DataVolumeSize)) + "GB(" + strconv.Itoa(int(v.DataVolumeSize)) + "GB " + v.DataVolumeInterfaceType + " " + v.DataVolumeType + "*" + strconv.Itoa(int(v.DataVolumeAmount)) + ")" + if v.DataVolumeUnit == "TB" { + dv_ = Trim(strconv.FormatFloat(float64(v.DataVolumeAmount)*float64(v.DataVolumeSize)/1000, 'f', 2, 64)) + "TB(" + Trim(strconv.FormatFloat(float64(v.DataVolumeSize)/1000, 'f', 2, 64)) + "TB " + v.DataVolumeInterfaceType + " " + v.DataVolumeType + "*" + strconv.Itoa(int(v.DataVolumeAmount)) + ")" // + "," + deviceTypeRaid + ")" + } + if v.DataVolumeAmount == 0 { + dv_ = "" + } + // 显示品牌 显卡型号 个数,例 NVIDIA P40 * 4 + gpu_ := v.GpuManufacturer + " " + v.GpuModel + "*" + strconv.Itoa(int(v.GpuAmount)) + if v.GpuAmount == 0 { + gpu_ = "" + } + nic_ := strconv.Itoa(int(v.NicAmount)) + "*" + strconv.Itoa(int(v.NicRate)) + "GE" + return map[string]string{ + "cpu_": cpu_, + "mem_": mem_, + "sv_": sv_, + "dv_": dv_, + "gpu_": gpu_, + "nic_": nic_, + } +} +func Trim(str string) string { + s := strings.TrimRight(str, "0") + s = strings.TrimRight(s, ".") + return s +} +func QueryDevices(logger *log.Logger, param requestTypes.QueryDevicesRequest, p util.Pageable) ([]*responseTypes.Device, int64, error) { + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "idc_id": param.IDcID, + "is_del": 0, + //如果还需要查询条件,继续在下面添加条件 + } + if param.DeviceSeries != "" { + query["device_series.in"] = strings.Split(param.DeviceSeries, ",") + } + if param.Sn != "" { + query["sn.like"] = "%" + param.Sn + "%" + } + if param.InstanceID != "" { + query["instance_id"] = param.InstanceID + } + if param.DeviceTypeID != "" { + query["device_type_id.in"] = strings.Split(param.DeviceTypeID, ",") + } + if param.ManageStatus != "" { + query["manage_status.in"] = strings.Split(param.ManageStatus, ",") + } + if param.UserID != "" { + query["user_id"] = param.UserID + } + if param.UserName != "" { + query["user_name.like"] = "%" + param.UserName + "%" + } + if param.IloIP != "" { + query["ilo_ip"] = param.IloIP + } + if param.IPV4 != "" { + query["private_ipv4"] = param.IPV4 + } + if param.IPV6 != "" { + query["private_ipv6"] = param.IPV6 + } + + count, err := deviceDao.GetDeviceCount(logger, query) + if err != nil { + logger.Warn("GetDeviceCount dao error:", err.Error()) + return nil, 0, err + } + entityList := []*deviceDao.Device{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = deviceDao.GetMultiDevice(logger, query, nil, []string{"created_time"}, []string{"desc"}, 0, 0) + } else { + entityList, err = deviceDao.GetMultiDevice(logger, query, nil, []string{"created_time"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("GetMultiDevice dao error:", err.Error()) + return nil, 0, err + } + var deviceList = []*responseTypes.Device{} + idcALl, _ := idcDao.GetAllIdc(logger, map[string]interface{}{"is_del": baseLogic.IS_NOT_DEL}) + idcMap := map[string]idcDao.Idc{} + for _, v := range idcALl { + idcMap[v.IDcID] = *v + } + deviceTypeALl, _ := deviceTypeDao.GetAllDeviceType(logger, map[string]interface{}{"is_del": baseLogic.IS_NOT_DEL}) + deviceTypeMap := map[string]deviceTypeDao.DeviceType{} + deviceTypeMapInfo := map[string]map[string]string{} + + for _, v := range deviceTypeALl { + + info := GetDeviceTypeInfo(logger, v) + deviceTypeMap[v.DeviceTypeID] = *v + //fmt.Println(info, util.ObjToJson(info), info["nic_"]) + //拼装数据,给上层api直接使用 + deviceTypeMapInfo[v.DeviceTypeID] = map[string]string{ + "cpu_": info["cpu_"], + "mem_": info["mem_"], + "sv_": info["sv_"], + "dv_": info["dv_"], + "gpu_": info["gpu_"], + "nic_": info["nic_"], + } + + } + instanceALl, _ := instanceDao.GetAllInstance(logger, map[string]interface{}{"is_del": baseLogic.IS_NOT_DEL}) + instanceMap := map[string]instanceDao.Instance{} + for _, v := range instanceALl { + instanceMap[v.InstanceID] = *v + } + imageALl, _ := imageDao.GetAllImage(logger, map[string]interface{}{"is_del": baseLogic.IS_NOT_DEL}) + imageMap := map[string]imageDao.Image{} + for _, v := range imageALl { + imageMap[v.ImageID] = *v + } + //userALl, _ := userDao.GetAllUser(logger, map[string]interface{}{"is_del": baseLogic.IS_NOT_DEL}) + //userMap := map[string]userDao.User{} + //for _, v := range userALl { + // userMap[v.UserID] = v + //} + + for _, entity := range entityList { + device := DeviceEntity2Device(logger, entity, idcMap, deviceTypeMap, deviceTypeMapInfo, instanceMap, imageMap) + deviceList = append(deviceList, device) + } + return deviceList, count, err +} + +func btoi(b bool) int { + if b { + return 1 + } + return 0 +} + +func ModifyDeviceByDeviceId(logger *log.Logger, param *requestTypes.ModifyAllDevicesRequest, DeviceID string) error { + _, err := deviceDao.GetOneDevice(logger, map[string]interface{}{ + "device_id": DeviceID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Warn("GetDeviceTypeByUuid sql error:", DeviceID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + entity := &deviceDao.Device{ + DeviceID: DeviceID, + ManageStatus: param.ManageStatus, + InstanceID: param.InstanceID, + UserId: param.UserId, + UserName: param.UserName, + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if err := deviceDao.UpdateDeviceById(logger, entity); err != nil { + logger.Warnf("ModifyDevice sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) + return err + } + //接下来修改其他信息,比如需不需要发mq之类的 + return nil +} + +func QueryDeviceStock(logger *log.Logger, region, az, deviceType string) ([]*deviceDao.DeviceStock, error) { + deviceStocks, err := deviceDao.GetDeviceStock(logger, deviceType, region, az) + if err != nil { + logger.Warn("GetDeviceStock GetAllDevice sql error:", deviceType, err.Error()) + return nil, err + } + return deviceStocks, nil +} + +func GetAndCheckById(logger *log.Logger, DeviceID string) (*responseTypes.Device, error) { + device, err := GetById(logger, DeviceID) + if err != nil { + return nil, err + } + return device, nil +} + +//设备详情 +func GetById(logger *log.Logger, DeviceID string) (*responseTypes.Device, error) { + entity, err := deviceDao.GetDeviceById(logger, DeviceID) + if err != nil { + logger.Warn("GetById GetDeviceById sql error:", DeviceID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + v, err := deviceTypeDao.GetDeviceTypeById(logger, entity.DeviceTypeID) + if err != nil { + v = &deviceTypeDao.DeviceType{} + } + //目的是获取拼装出来的机型数据 + info := GetDeviceTypeInfo(logger, v) + + //fmt.Println(info, util.ObjToJson(info), info["nic_"]) + //拼装数据,给上层api直接使用 + deviceTypeMapInfo := map[string]map[string]string{} + deviceTypeMapInfo[v.DeviceTypeID] = map[string]string{ + "cpu_": info["cpu_"], + "mem_": info["mem_"], + "sv_": info["sv_"], + "dv_": info["dv_"], + "gpu_": info["gpu_"], + "nic_": info["nic_"], + } + device := DeviceEntity2DeviceOne(logger, entity, deviceTypeMapInfo) + return device, nil +} +func IDevice2DeviceEntity(i idcApi.IDevice) *deviceDao.Device { + return &deviceDao.Device{ + Sn: i.Sn, + IloIP: i.IloIP, + Cabinet: i.Cabinet, + UPosition: i.UPosition, + } +} + +//获取所有符合条件的设备,可以用于查询库存,查询所有设备接口使用 +func GetAllDevices(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string) []*deviceDao.Device { + list, err := deviceDao.GetAllDevices(logger, query, fields, sortby, order) + if err != nil { + logger.Warn("GetAllDevices error:", err.Error()) + return nil + } + return list +} + +func GetStockByDeviceTypeIds(logger *log.Logger, deviceTypeIds []string) (map[string]int, error) { + query := map[string]interface{}{ + "is_del": 0, + "device_type_id.in": deviceTypeIds, + "manage_status": "putaway", + } + list, err := deviceDao.GetAllDevices(logger, query, nil, nil, nil) + if err != nil { + logger.Warn("GetAllDevices error:", err.Error()) + return nil, err + } + res := map[string]int{} + for _, v := range list { + _, ok := res[v.DeviceTypeID] + if ok { + res[v.DeviceTypeID] += 1 + } else { + res[v.DeviceTypeID] = 1 + } + } + return res, nil +} + +//查询设备详情单独使用 +func DeviceEntity2DeviceOne(logger *log.Logger, d *deviceDao.Device, deviceTypeMapInfo map[string]map[string]string) *responseTypes.Device { + + tz := logger.GetPoint("timezone").(string) + idc, err := idcDao.GetIdcById(logger, d.IDcID) //获取机房信息 + if err != nil { + idc = &idcDao.Idc{} + } + //idc := idcMap[d.IDcID] + entity, err := deviceTypeDao.GetOneDeviceType(logger, map[string]interface{}{"device_type_id": d.DeviceTypeID}) + if err != nil { + entity = &deviceTypeDao.DeviceType{} + } + //entity := deviceTypMap[d.DeviceTypeID] + instance, err := instanceDao.GetInstanceById(logger, d.InstanceID) + if instance == nil { + instance = &instanceDao.Instance{} + } + //instance := instanceMap[d.InstanceID] + image, err := imageDao.GetImageByUuid(logger, instance.ImageID) + if image == nil { + image = &imageDao.Image{} + } + //image := imageMap[instance.ImageID] + //user, _ := userDao.GetUserById(logger, instance.UserID) + //if user == nil { + // user = &userDao.User{} + //} + language := logger.GetPoint("language").(string) + reason := baseLogic.DeviceReason[d.Reason] + if language == baseLogic.EN_US { + reason = baseLogic.DeviceReasonEn[d.Reason] + } + instanceStatusName := baseLogic.InstanceStatus[instance.Status] + if language == baseLogic.EN_US { + instanceStatusName = baseLogic.InstanceStatusEn[instance.Status] + } + instanceReason := baseLogic.InstanceReason[instance.Reason] + if language == baseLogic.EN_US { + instanceReason = baseLogic.InstanceReasonEn[instance.Reason] + } + deviceManageStatusName := baseLogic.DeviceManageStatus[d.ManageStatus] + if language == baseLogic.EN_US { + deviceManageStatusName = baseLogic.DeviceManageStatusEn[d.ManageStatus] + } + deviceSeriesName := baseLogic.DeviceTypeSeries[d.DeviceSeries] + if language == baseLogic.EN_US { + deviceSeriesName = baseLogic.DeviceTypeSeriesEn[d.DeviceSeries] + } + idcName := idc.Name + if language == baseLogic.EN_US { + idcName = idc.NameEn + } + var ( + iloUser string + iloPassword string + switchUser1 string + switchUser2 string + switchPassword1 string + switchPassword2 string + encloure1 string + slot1 int + encloure2 string + slot2 int + ) + disk, _ := diskDao.GetAllDisk(logger, map[string]interface{}{"device_id": d.DeviceID}) + if len(disk) == 1 { + encloure1 = disk[0].Enclosure + slot1 = disk[0].Slot + } else if len(disk) == 2 { + encloure1 = disk[0].Enclosure + slot1 = disk[0].Slot + encloure2 = disk[1].Enclosure + slot2 = disk[1].Slot + } + if d.IloUser == "" { + iloUser = idc.IloUser + } else { + iloUser = d.IloUser + } + if d.IloPassword == "" { + iloPassword = idc.IloPassword + } else { + iloPassword = d.IloPassword + } + if d.SwitchUser1 == "" { + switchUser1 = idc.SwitchUser1 + } else { + switchUser1 = d.SwitchUser1 + } + if d.SwitchPassword1 == "" { + switchPassword1 = idc.SwitchPassword1 + } else { + switchPassword1 = d.SwitchPassword1 + } + if d.SwitchUser2 == "" { + switchUser2 = idc.SwitchUser2 + } else { + switchUser2 = d.SwitchUser2 + } + if d.SwitchPassword2 == "" { + switchPassword2 = idc.SwitchPassword2 + } else { + switchPassword2 = d.SwitchPassword2 + } + return &responseTypes.Device{ + ID: d.ID, + DeviceID: d.DeviceID, + IdcID: d.IDcID, + InstanceID: d.InstanceID, + InstanceName: instance.InstanceName, + InstanceStatus: instance.Status, + InstanceStatusName: instanceStatusName, + InstanceReason: instanceReason, + Locked: instance.Locked, + UserId: d.UserId, + UserName: d.UserName, + InstanceCreatedTime: util.TimestampToString(int64(instance.CreatedTime), tz), + InstanceDescription: instance.Description, + + DeviceTypeID: d.DeviceTypeID, + ManageStatus: d.ManageStatus, + ManageStatusName: deviceManageStatusName, + + ImageName: image.ImageName, + + Brand: d.Brand, + Model: d.Model, + Reason: reason, + Cabinet: d.Cabinet, + UPosition: d.UPosition, + Sn: d.Sn, + Description: d.Description, + + Mac1: d.Mac1, + Mac2: d.Mac2, + SwitchIP1: d.SwitchIP1, + SwitchPort1: d.SwitchPort1, + SwitchIP2: d.SwitchIP2, + SwitchPort2: d.SwitchPort2, + //如果设备不存在,从idc中获取 + IloUser: iloUser, + IloPassword: iloPassword, + IloIP: d.IloIP, //必填 + SwitchUser1: switchUser1, + SwitchPassword1: switchPassword1, + SwitchUser2: switchUser2, + SwitchPassword2: switchPassword2, + SwitchIP: d.SwitchIP, + + Mask: d.Mask, + Eth1Mask: d.MaskEth1, + Gateway: d.Gateway, + PrivateIPv4: d.PrivateIPv4, + PrivateEth1IPv4: d.PrivateEth1IPv4, + PrivateIPv6: d.PrivateIPv6, + PrivateEth1IPv6: d.PrivateEth1IPv6, + AdapterID: d.AdapterID, + + Enclosure1: encloure1, + Slot1: slot1, + Enclosure2: encloure2, + Slot2: slot2, + RaidDriver: d.RaidDriver, + CreatedBy: d.CreatedBy, + UpdatedBy: d.UpdatedBy, + CreatedTime: util.TimestampToString(int64(d.CreatedTime), tz), + UpdatedTime: util.TimestampToString(int64(d.UpdatedTime), tz), + + //以下字段从其他表中获取 + //idc + IdcName: idcName, + IDcNameEn: idc.NameEn, + //deviceType + + DeviceType: entity.DeviceType, + DeviceSeries: d.DeviceSeries, + DeviceSeriesName: deviceSeriesName, + + DeviceTypeName: entity.Name, + Architecture: entity.Architecture, + CPUAmount: entity.CPUAmount, + CPUCores: entity.CPUCores, + CPUFrequency: entity.CPUFrequency, + CPUManufacturer: entity.CPUManufacturer, + CPUModel: entity.CPUModel, + + MemType: entity.MemType, + MemAmount: entity.MemAmount, + MemSize: entity.MemSize, + MemFrequency: entity.MemFrequency, + NicAmount: entity.NicAmount, + NicRate: entity.NicRate, + InterfaceMode: entity.InterfaceMode, + SystemVolumeType: entity.SystemVolumeType, + SystemVolumeInterfaceType: entity.DataVolumeInterfaceType, + SystemVolumeAmount: entity.SystemVolumeAmount, + SystemVolumeSize: entity.SystemVolumeSize, + DataVolumeType: entity.DataVolumeType, + DataVolumeInterfaceType: entity.SystemVolumeInterfaceType, + DataVolumeAmount: entity.DataVolumeAmount, + DataVolumeSize: entity.DataVolumeSize, + GpuAmount: entity.GpuAmount, + GpuManufacturer: entity.GpuManufacturer, + GpuModel: entity.GpuModel, + + //拼装信息 + CpuInfo: deviceTypeMapInfo[entity.DeviceTypeID]["cpu_"], + MemInfo: deviceTypeMapInfo[entity.DeviceTypeID]["mem_"], + SvInfo: deviceTypeMapInfo[entity.DeviceTypeID]["sv_"], + DvInfo: deviceTypeMapInfo[entity.DeviceTypeID]["dv_"], + GpuInfo: deviceTypeMapInfo[entity.DeviceTypeID]["gpu_"], + NicInfo: deviceTypeMapInfo[entity.DeviceTypeID]["nic_"], + } +} + +func GetGlobalDeviceCount(logger *log.Logger) (int64, error) { + q := map[string]interface{}{ + "is_del": 0, + } + return deviceDao.GetDeviceCount(logger, q) +} diff --git a/bmp-openapi-console/logic/deviceTypeLogic/deviceTypeLogic.go b/bmp-openapi-console/logic/deviceTypeLogic/deviceTypeLogic.go new file mode 100644 index 0000000..20df82b --- /dev/null +++ b/bmp-openapi-console/logic/deviceTypeLogic/deviceTypeLogic.go @@ -0,0 +1,471 @@ +package deviceTypeLogic + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rVolumeRaidDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/volumeDao" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceTypeDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/imageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rDeviceTypeImageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rDeviceTypeImagePartitionDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/imageLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +var K int = 1 + +func BuildDeviceTypeEntity(logger *log.Logger, param *requestTypes.CreateDeviceTypeRequest) *deviceTypeDao.DeviceType { + var systemVolumeSize, dataVolumeSize int + if param.SystemVolumeUnit == "TB" { + systemVolumeSize = param.SystemVolumeSize * K + } else { + systemVolumeSize = param.SystemVolumeSize + } + if param.DataVolumeUnit == "TB" { + dataVolumeSize = param.DataVolumeSize * K + } else { + dataVolumeSize = param.DataVolumeSize + } + fmt.Println("开始校验") + if param.GpuManufacturer == "" { + if param.GpuModel != "" || param.GpuAmount != 0 { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.GpuModel == "" { + if param.GpuManufacturer != "" || param.GpuAmount != 0 { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.GpuAmount == 0 { + if param.GpuManufacturer != "" || param.GpuModel != "" { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.DataVolumeType == "" { + if param.DataVolumeInterfaceType != "" || param.DataVolumeAmount != 0 || param.DataVolumeSize != 0 { + panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + } + } + if param.DataVolumeInterfaceType == "" { + if param.DataVolumeType != "" || param.DataVolumeAmount != 0 || param.DataVolumeSize != 0 { + panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + } + } + if param.DataVolumeAmount == 0 { + if param.DataVolumeInterfaceType != "" || param.DataVolumeType != "" || param.DataVolumeSize != 0 { + panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + } + } + if param.DataVolumeSize == 0 { + if param.DataVolumeInterfaceType != "" || param.DataVolumeAmount != 0 || param.DataVolumeType != "" { + panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + } + } + + var bootmode string + if param.BootMode == "" { + //用户缺失此参数时,如果x86的默认为bios + if param.Architecture == "x86_64" { + bootmode = "Legacy/BIOS" + } else { + bootmode = "UEFI" + } + } else { + bootmode = param.BootMode + } + + return &deviceTypeDao.DeviceType{ + IDcID: param.IDcID, + DeviceTypeID: util.GetUuid("dt-"), + DeviceType: param.DeviceType, + Name: param.Name, + DeviceSeries: param.DeviceSeries, + Height: param.Height, + Architecture: param.Architecture, + Description: param.Description, + + CPUAmount: param.CPUAmount, + CPUCores: param.CPUCores, + CPUFrequency: param.CPUFrequency, + CPUManufacturer: param.CPUManufacturer, + CPUModel: param.CPUModel, + + MemAmount: param.MemAmount, + MemSize: param.MemSize, + MemFrequency: param.MemFrequency, + MemType: param.MemType, + NicAmount: param.NicAmount, + NicRate: param.NicRate, + InterfaceMode: param.InterfaceMode, + GpuAmount: param.GpuAmount, + GpuManufacturer: param.GpuManufacturer, + GpuModel: param.GpuModel, + + SystemVolumeType: param.SystemVolumeType, + SystemVolumeInterfaceType: param.SystemVolumeInterfaceType, + SystemVolumeAmount: param.SystemVolumeAmount, + SystemVolumeSize: systemVolumeSize, + SystemVolumeUnit: param.SystemVolumeUnit, + + DataVolumeType: param.DataVolumeType, + DataVolumeInterfaceType: param.DataVolumeInterfaceType, + DataVolumeAmount: param.DataVolumeAmount, + DataVolumeSize: dataVolumeSize, + DataVolumeUnit: param.DataVolumeUnit, + CreatedBy: logger.GetPoint("username").(string), + UpdatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + CpuSpec: param.CpuSpec, + MemSpec: param.MemSpec, + BootMode: bootmode, + } +} +func QueryDeviceTypes(logger *log.Logger, param *requestTypes.QueryDeviceTypesRequest, p util.Pageable) ([]*responseTypes.DeviceType, int64, error) { + + language := logger.GetPoint("language").(string) + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "idc_id": param.IdcID, + "is_del": 0, + } + if param.Name != "" { + query["name.like"] = "%" + param.Name + "%" + } + if param.DeviceType != "" { + query["device_type.in"] = strings.Split(param.DeviceType, ",") + } + if param.DeviceTypeID != "" { + query["device_type_id.in"] = strings.Split(param.DeviceTypeID, ",") + } + if param.DeviceSeries != "" { + query["device_series.in"] = strings.Split(param.DeviceSeries, ",") + } + + count, err := deviceTypeDao.QueryDeviceTypesCount(logger, query) + if err != nil { + logger.Warnf("DescribeDeviceTypes_GetDeviceTypeCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + dts := []*deviceTypeDao.DeviceType{} + if param.IsAll == baseLogic.IS_ALL { + dts, err = deviceTypeDao.QueryAllDeviceTypes(logger, query) + } else { + dts, err = deviceTypeDao.QueryDeviceTypes(logger, query, offset, limit) + } + if err != nil { + logger.Warnf("QueryDeviceTypes sql err, param:%s, error:%s", util.ObjToJson(param), err.Error()) + return nil, 0, err + } + res := []*responseTypes.DeviceType{} + deviceTypeIds := []string{} + for _, value := range dts { + deviceTypeIds = append(deviceTypeIds, value.DeviceTypeID) + } + + deviceTypeId2Stock := map[string]int{} + if len(deviceTypeIds) != 0 { + deviceTypeId2Stock, err = deviceLogic.GetStockByDeviceTypeIds(logger, deviceTypeIds) + if err != nil { + logger.Warnf("GetStockByDeviceTypeIds error:%s", err.Error()) + } + } + + for _, value := range dts { + v := DeviceTypeEntity2DeviceType(logger, value) + stock, ok := deviceTypeId2Stock[v.DeviceTypeID] + if ok { + v.StockAvailable = stock + } else { + v.StockAvailable = 0 + } + volumes, err := volumeDao.GetAllVolume(logger, map[string]interface{}{ + "is_del": 0, + "device_type_id": v.DeviceTypeID, + }) + if err != nil { + logger.Warnf("QueryDeviceTypes.GetAllVolumeByDeviceType error, device_type_id:%s, error:%s", v.DeviceTypeID, err.Error()) + } + for k1, v1 := range volumes { + if language != baseLogic.EN_US { + if v1.DiskType == "notLimited" { + v1.DiskType = "无限制" + } + if v1.InterfaceType == "notLimited" { + v1.InterfaceType = "无限制" + } + + } + volumes[k1] = v1 + } + v.Volumes = volumes + res = append(res, v) + } + return res, count, err +} +func QueryDeviceType(logger *log.Logger, param *requestTypes.QueryDeviceTypesRequest) (*responseTypes.DeviceType, error) { + query := map[string]interface{}{ + "is_del": 0, + } + //if param.Id != 0 { + // query["id"] = param.Id + //} + if param.DeviceType != "" { + query["device_type"] = param.DeviceType + } + if param.DeviceTypeID != "" { + query["device_type_id"] = param.DeviceTypeID + } + dts, err := deviceTypeDao.GetOneDeviceType(logger, query) + if err != nil { + logger.Warnf("QueryDeviceType sql err, param:%s, error:%s", util.ObjToJson(param), err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + res := DeviceTypeEntity2DeviceType(logger, dts) + return res, err +} +func QueryDeviceTypeById(logger *log.Logger, deviceTypeId string) (*responseTypes.DeviceType, error) { + + deviceType, err := deviceTypeDao.GetDeviceTypeById(logger, deviceTypeId) + if err != nil { + logger.Warnf("QueryDeviceType sql err, deviceTypeId:%s, error:%s", deviceTypeId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + res := DeviceTypeEntity2DeviceType(logger, deviceType) + return res, err +} + +func DeviceTypeEntity2DeviceType(logger *log.Logger, entity *deviceTypeDao.DeviceType) *responseTypes.DeviceType { + language := logger.GetPoint("language").(string) + tz := logger.GetPoint("timezone").(string) + + info := deviceLogic.GetDeviceTypeInfo(logger, entity) + + deviceSeries := baseLogic.DeviceTypeSeries[entity.DeviceSeries] + if language == baseLogic.EN_US { + deviceSeries = baseLogic.DeviceTypeSeriesEn[entity.DeviceSeries] + } + idc, err := idcDao.GetIdcById(logger, entity.IDcID) //获取机房信息 + if err != nil { + idc = &idcDao.Idc{} + } + idcName := idc.Name + if language == baseLogic.EN_US { + idcName = idc.NameEn + } + + instance, _ := instanceDao.GetAllInstance(logger, map[string]interface{}{ + "device_type_id": entity.DeviceTypeID, + }) + device, _ := deviceDao.GetAllDevice(logger, map[string]interface{}{ + "device_type_id": entity.DeviceTypeID, + }) + return &responseTypes.DeviceType{ + ID: entity.ID, + IDcID: entity.IDcID, + IDcName: idcName, + IDcNameEn: idc.NameEn, + DeviceType: entity.DeviceType, + DeviceTypeID: entity.DeviceTypeID, + Name: entity.Name, + Description: entity.Description, + DeviceSeries: entity.DeviceSeries, + DeviceSeriesName: deviceSeries, + Architecture: entity.Architecture, + Height: entity.Height, + CPUAmount: entity.CPUAmount, + CPUCores: entity.CPUCores, + CPUFrequency: entity.CPUFrequency, + CPUManufacturer: entity.CPUManufacturer, + CPUModel: entity.CPUModel, + + MemType: entity.MemType, + MemAmount: entity.MemAmount, + MemSize: entity.MemSize, + MemFrequency: entity.MemFrequency, + NicAmount: entity.NicAmount, + NicRate: entity.NicRate, + InterfaceMode: entity.InterfaceMode, + GpuAmount: entity.GpuAmount, + GpuManufacturer: entity.GpuManufacturer, + GpuModel: entity.GpuModel, + CreatedTime: util.TimestampToString(int64(entity.CreatedTime), tz), + UpdatedTime: util.TimestampToString(int64(entity.UpdatedTime), tz), + CreatedBy: entity.CreatedBy, + UpdatedBy: entity.UpdatedBy, + RaidCan: entity.RaidCan, + // Raid: strings.Trim(raid, ","), + CpuSpec: entity.CpuSpec, + MemSpec: entity.MemSpec, + BootMode: entity.BootMode, + + //拼装信息 + CpuInfo: info["cpu_"], + MemInfo: info["mem_"], + SvInfo: info["sv_"], + DvInfo: info["dv_"], + GpuInfo: info["gpu_"], + NicInfo: info["nic_"], + InstanceCount: len(instance), + DeviceCount: len(device), + IsNeedRaid: entity.IsNeedRaid, + } +} + +func QueryDeviceTypeImage(logger *log.Logger, param *requestTypes.QueryDeviceTypeImageRequest, p util.Pageable) ([]*responseTypes.Image, int64, error) { + tz := logger.GetPoint("timezone").(string) + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "image_id": param.ImageID, + "device_type_id": param.DeviceTypeID, + "image_name": param.ImageName, + "version": param.Version, + "os_id": param.OsID, + //"image_ids": strings.Join(param.ImageIds, ","), + "source": param.Source, + "architecture": param.Architecture, + "os_type": param.OsType, + "is_del": baseLogic.IS_NOT_DEL, + } + //queryList := query + //query["count"] = true + _, count, err := rDeviceTypeImageDao.GetDeviceTypeImageAndOsList(logger, query, true, 0, 0) + //os.Exit(1) + if err != nil { + logger.Warnf("DescribeDeviceTypes_GetDeviceTypeCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*imageDao.DImage{} + if param.IsAll == baseLogic.IS_ALL { + //entityList, err = imageDao.GetMultiImage(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + fmt.Println("获取全部", query) + entityList, _, err = rDeviceTypeImageDao.GetDeviceTypeImageAndOsList(logger, query, false, 0, 0) + } else { + //entityList, err = imageDao.GetMultiImage(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + entityList, _, err = rDeviceTypeImageDao.GetDeviceTypeImageAndOsList(logger, query, false, offset, limit) + } + if err != nil { + logger.Warn("imageDao.QueryByDeviceOsType sql error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + images := []*responseTypes.Image{} + for _, image := range entityList { + isBind := false + if param.DeviceTypeID != "" { + deviceTypeImageNum, _ := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, map[string]interface{}{ + "image_id": image.ImageID, + "device_type_id": param.DeviceTypeID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if deviceTypeImageNum != 0 { + isBind = true + } + } + //fmt.Println(util.InterfaceToJson(image), image.ImageID, image.CreatedTime) + //os, err := osLogic.GetByOsId(logger, image.OsID) + //if err != nil && os == nil { + // os = &responseTypes.Os{} //如果没有找到os,默认为空 + //} + deviceTypeNum, err := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, map[string]interface{}{ + "image_id": image.ImageID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Warn("获取镜像对应的机型个数错误", image.OsID, err.Error()) + return nil, 0, err + } + images = append(images, imageLogic.ImageEntityWithOs2Image(logger, image, int(deviceTypeNum), isBind, tz)) + } + return images, count, nil +} + +func QueryVolumesRaids(logger *log.Logger, param *requestTypes.QueryVolumesRaidsRequest) ([]*responseTypes.VolumeRaids, error) { + language := logger.GetPoint("language").(string) + //offset, limit := p.Pageable2offset() + // tz := logger.GetPoint("timezone").(string) + query := map[string]interface{}{ + "device_type_id": param.DeviceTypeID, + "volume_type": param.VolumeType, + "is_del": 0, + } + volumeEntities, err := volumeDao.GetAllVolume(logger, query) + if err != nil { + logger.Warnf("QueryVolumesRaids.GetAllVolume error, device_type_id:%s, error:%s", param.DeviceTypeID, err.Error()) + return nil, err + } + res := []*responseTypes.VolumeRaids{} + for _, v := range volumeEntities { + if language != baseLogic.EN_US { + if v.DiskType == "notLimited" { + v.DiskType = "无限制" + } + if v.InterfaceType == "notLimited" { + v.InterfaceType = "无限制" + } + + } + rVolumeRaidEntities, err := rVolumeRaidDao.GetRVolumeRaidsByVId(logger, v.VolumeID) + if err != nil { + logger.Warnf("QueryVolumesRaids.GetRVolumeRaidsByVId error, volume_id:%s, error:%s", v.VolumeID, err.Error()) + } + item := &responseTypes.VolumeRaids{ + Volume: *v, + Raids: rVolumeRaidEntities, + } + res = append(res, item) + + } + return res, err +} + +func QueryDeviceTypeImagePartition(logger *log.Logger, param *requestTypes.QueryDeviceTypeImagePartitionRequest) (*responseTypes.QueryDeviceTypeImagePartitionResponse, error) { + entities, err := rDeviceTypeImagePartitionDao.GetByDeviceTypeAndImageId(logger, param.DeviceTypeID, param.ImageID) + if err != nil { + logger.Warnf("GetByDeviceTypeAndImageId error:", param.DeviceTypeID, param.ImageID) + return nil, err + } + res := &responseTypes.QueryDeviceTypeImagePartitionResponse{ + SystemPartition: []responseTypes.Partition{}, + DataPartition: []responseTypes.Partition{}, + } + for _, entity := range entities { + if strings.EqualFold("data", entity.PartitionType) { + res.DataPartition = append(res.DataPartition, responseTypes.Partition{ + Size: entity.PartitionSize, + FsType: entity.PartitionFsType, + MountPoint: entity.PartitionMountPoint, + //Label: entity.PartitionLabel, + }) + } else { + res.SystemPartition = append(res.SystemPartition, responseTypes.Partition{ + Size: entity.PartitionSize, + FsType: entity.PartitionFsType, + MountPoint: entity.PartitionMountPoint, + //Label: entity.PartitionLabel, + }) + } + } + + return res, nil + +} +func Trim(str string) string { + s := strings.TrimRight(str, "0") + s = strings.TrimRight(s, ".") + return s +} diff --git a/bmp-openapi-console/logic/diskLogic/diskLogic.go b/bmp-openapi-console/logic/diskLogic/diskLogic.go new file mode 100644 index 0000000..0e3e3c6 --- /dev/null +++ b/bmp-openapi-console/logic/diskLogic/diskLogic.go @@ -0,0 +1,118 @@ +package diskLogic + +//func OsEntity2OS(o *osDao.Os) *responseTypes.OS { +// return &responseTypes.OS{ +// ID: o.ID, +// OsID: o.OsID, +// OsName: o.OsName, +// OsType: o.OsType, +// OsVersion: o.OsVersion, +// Platform: o.Platform, +// Architecture: o.Architecture, +// Bits: o.Bits, +// CreatedTime: util.TimestampToUtc(int64(o.CreatedTime)), +// } +//} +// +//func GetByOsId(logger *log.Logger, osId string) (*responseTypes.OS, error) { +// entity, err := osDao.GetOsByUuid(logger, osId) +// if err != nil { +// logger.Warn("GetOsByUuid sql error:", osId, err.Error()) +// return nil, err +// } +// return OsEntity2OS(entity), nil +//} +//func GetOsByUuid(logger *log.Logger, osid string) (o *osDao.Os, err error) { +// entity, err := osDao.GetOsByUuid(logger, osid) +// return entity, err +//} +// +//func GetAndCheckById(logger *log.Logger, os_id string) (*responseTypes.OS, error) { +// os, err := GetByOsId(logger, os_id) +// if err != nil { +// return nil, err +// } +// return os, nil +// +//} +// +//func CreateDisk(logger *log.Logger, param *requestTypes.CreateD) (string, error) { +// os_entity := &osDao.Os{ +// OsName: param.OsName, +// OsType: param.OsType, +// Platform: param.Platform, +// Architecture: param.Architecture, +// Bits: param.Bits, +// OsVersion: param.OsVersion, +// SysUser: param.SysUser, +// CreatedBy: logger.GetPoint("username").(string), +// CreatedTime: int(time.Now().Unix()), +// } +// os_entity.OsID = commonUtil.GetRandString(namespacePrefix.IMAGE_ID_PREFIX, namespacePrefix.INSTANCE_ID_LENGTH, false, true, true) +// if _, err := osDao.AddOs(logger, os_entity); err != nil { +// logger.Warnf("CreateOs AddOs sql error, entity:%s, error:%s", util.ObjToJson(os_entity), err.Error()) +// return "", err +// } +// return os_entity.OsID, nil +//} +// +//func ModifyOS(logger *log.Logger, param *requestTypes.ModifyOSRequest, osId string) error { +// +// entity, err := osDao.GetOsByUuid(logger, osId) +// if err != nil { +// logger.Warn("GetOsByUuid sql error:", osId, err.Error()) +// return err +// } +// +// entity.OsName = param.OsName +// entity.OsType = param.OsType +// entity.Platform = param.Platform +// entity.Architecture = param.Architecture +// entity.Bits = param.Bits +// entity.OsVersion = param.OsVersion +// entity.SysUser = param.SysUser +// entity.UpdatedBy = logger.GetPoint("username").(string) +// entity.UpdatedTime = int(time.Now().Unix()) +// if err := osDao.UpdateOsById(logger, entity); err != nil { +// logger.Warn("ModifyOS UpdateOsById sql error:", osId, err.Error()) +// return err +// } +// return nil +//} +// +//func DeleteOS(logger *log.Logger, osId string) error { +// entity, err := osDao.GetOsByUuid(logger, osId) +// if err != nil { +// logger.Warn("GetOsByUuid sql error:", osId, err.Error()) +// return err +// } +// entity.IsDel = 1 +// entity.UpdatedTime = int(time.Now().Unix()) +// entity.DeletedTime = int(time.Now().Unix()) +// if err := osDao.UpdateOsById(logger, entity); err != nil { +// logger.Warn("DeleteOS UpdateOsById sql error:", osId, err.Error()) +// return err +// } +// return nil +//} +// +//func DescribeOSs(logger *log.Logger, param *requestTypes.QueryOssRequest) ([]*responseTypes.OS, error) { +// +// query := map[string]interface{}{ +// "os_name": param.OsName, +// "os_type": param.OsType, +// "os_version": param.OsVersion, +// "platform": param.Platform, +// "is_del": 0, +// } +// os_entity_list, err := osDao.GetMultiOs(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 1000) +// if err != nil { +// logger.Warn("QueryByOsIds GetAllOs sql error:", err.Error()) +// return nil, err +// } +// oss := []*responseTypes.OS{} +// for _, entity := range os_entity_list { +// oss = append(oss, OsEntity2OS(entity)) +// } +// return oss, nil +//} diff --git a/bmp-openapi-console/logic/idcLogic/idcLogic.go b/bmp-openapi-console/logic/idcLogic/idcLogic.go new file mode 100644 index 0000000..d314e18 --- /dev/null +++ b/bmp-openapi-console/logic/idcLogic/idcLogic.go @@ -0,0 +1,104 @@ +package idcLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func GetOneIdc(logger *log.Logger) (*responseTypes.Idc, error) { + + var tz string + if logger.GetPoint("timezone") == nil { + tz = "Asia/Shanghai" + } else { + tz = logger.GetPoint("timezone").(string) + } + query := map[string]interface{}{ + "is_del": 0, + } + idc, err := idcDao.GetOneIdc(logger, query) + if err != nil { + return nil, err + } + return IdcEntity2Idc(logger, idc, tz), nil +} + +func QueryIdcs(logger *log.Logger, param *requestTypes.QueryIdcsRequest, p util.Pageable) ([]*responseTypes.Idc, int64, error) { + tz := logger.GetPoint("timezone").(string) + offset, limit := p.Pageable2offset() + //tenant := logger.GetPoint("tenant").(string) + //region := logger.GetPoint("region").(string) + //az := logger.GetPoint("az").(string) + //name := param.IdcNo + query := map[string]interface{}{ + "is_del": 0, + } + //if tenant != "" { + // query["tenant"] = tenant + //} + count, err := idcDao.GetIdcCount(logger, query) + if err != nil { + logger.Warnf("DescribeIdcs_GetIdcCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*idcDao.Idc{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = idcDao.GetMultiIdc(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = idcDao.GetMultiIdc(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warnf("DescribeIdcs_QueryByParam error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + Idcs := []*responseTypes.Idc{} + for _, entity := range entityList { + Idcs = append(Idcs, IdcEntity2Idc(logger, entity, tz)) + } + return Idcs, count, nil +} + +func IdcEntity2Idc(logger *log.Logger, k *idcDao.Idc, tz string) *responseTypes.Idc { + v := &responseTypes.Idc{ + ID: k.ID, + IDcID: k.IDcID, + Name: k.Name, + NameEn: k.NameEn, + Shortname: k.Shortname, + Level: k.Level, + Address: k.Address, + IloUser: k.IloUser, + IloPassword: k.IloPassword, + SwitchUser1: k.SwitchUser1, + SwitchPassword1: k.SwitchPassword1, + SwitchUser2: k.SwitchUser2, + SwitchPassword2: k.SwitchPassword2, + CreateTime: util.TimestampToString(int64(k.CreatedTime), tz), + UpdateTime: util.TimestampToString(int64(k.UpdatedTime), tz), + CreatedBy: k.CreatedBy, + UpdatedBy: k.UpdatedBy, + } + //if logger.GetPoint("language").(string) == baseLogic.EN_US { + // v.Name = k.NameEn + //} + return v +} + +func QueryIdcById(logger *log.Logger, idcId string) (*responseTypes.IdcInfo, error) { + tz := logger.GetPoint("timezone").(string) + idc, err := idcDao.GetIdcById(logger, idcId) + if err != nil { + logger.Warnf("DescribeIdc dao error, error:%s", err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + Idc := IdcEntity2Idc(logger, idc, tz) + return &responseTypes.IdcInfo{ + Idc: Idc, + }, nil +} diff --git a/bmp-openapi-console/logic/imageLogic/imageLogic.go b/bmp-openapi-console/logic/imageLogic/imageLogic.go new file mode 100644 index 0000000..f70f28b --- /dev/null +++ b/bmp-openapi-console/logic/imageLogic/imageLogic.go @@ -0,0 +1,268 @@ +package imageLogic + +import ( + "fmt" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceTypeDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rDeviceTypeImageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + imageDao "coding.jd.com/aidc-bmp/bmp-openapi/dao/imageDao" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func DImageEntity2Image(d *imageDao.DImage, tz string) *responseTypes.Image { + return &responseTypes.Image{ + ID: d.ID, + ImageID: d.ImageID, + ImageName: d.ImageName, + Format: d.Format, + Filename: d.Filename, + URL: d.URL, + Hash: d.Hash, + Source: d.Source, + Description: d.Description, + SystemPartition: d.SystemPartition, + DataPartition: d.DataPartition, + //Platform: d.Platform, + OsVersion: d.OsVersion, + CreatedTime: util.TimestampToString(int64(d.CreatedTime), tz), + + //Os: responseTypes.OS{ + // Id: d.OsId, + // NameEn: d.OsNameEn, + // NameZh: d.OsNameZh, + // Version: d.OsVersion, + // Type: d.OsType, + // Bits: int(d.OsBits), + // Architecture: d.OsArchitecture, + // Platform: d.OsPlatform, + //}, + } +} + +func ImageEntityWithOs2Image(logger *log.Logger, d *imageDao.DImage, deviceTypeNum int, isBind bool, tz string) *responseTypes.Image { + image := &responseTypes.Image{ + ID: d.ID, + ImageID: d.ImageID, + ImageName: d.ImageName, + Format: d.Format, + BootMode: d.BootMode, + Filename: d.Filename, + URL: d.URL, + Hash: d.Hash, + Source: d.Source, + SourceName: baseLogic.Source[d.Source], + Architecture: d.Architecture, + Description: d.Description, + SystemPartition: d.SystemPartition, + DataPartition: d.DataPartition, + OsID: d.OsID, + OsType: d.OsType, + OsName: d.OsName, + OsVersion: d.OsVersion, + CreatedBy: d.CreatedBy, + UpdatedBy: d.UpdatedBy, + CreatedTime: util.TimestampToString(int64(d.CreatedTime), tz), + UpdatedTime: util.TimestampToString(int64(d.UpdatedTime), tz), + DeviceTypeNum: deviceTypeNum, + IsBind: isBind, + } + if logger.GetPoint("language").(string) == baseLogic.EN_US { + image.SourceName = baseLogic.SourceEn[d.Source] + } + return image +} + +func DescribeImages(logger *log.Logger, param *requestTypes.QueryImagesRequest, p util.Pageable) ([]*responseTypes.Image, int64, error) { + tz := logger.GetPoint("timezone").(string) + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "image_id": param.ImageID, + "image_name": param.ImageName, + "version": param.Version, + "os_id": param.OsID, + //"image_ids": strings.Join(param.ImageIds, ","), + "source": param.Source, + "architecture": param.Architecture, + "os_type": param.OsType, + "is_del": baseLogic.IS_NOT_DEL, + "device_type_id": param.DeviceTypeID, + } + //queryList := query + //query["count"] = true + _, count, err := imageDao.GetImageAndOsList(logger, query, true, 0, 0) + if err != nil { + logger.Warnf("DescribeDeviceTypes_GetDeviceTypeCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*imageDao.DImage{} + if param.IsAll == baseLogic.IS_ALL { + //entityList, err = imageDao.GetMultiImage(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + fmt.Println("获取全部", query) + entityList, _, err = imageDao.GetImageAndOsList(logger, query, false, 0, 0) + } else { + //entityList, err = imageDao.GetMultiImage(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + entityList, _, err = imageDao.GetImageAndOsList(logger, query, false, offset, limit) + } + if err != nil { + logger.Warn("imageDao.QueryByDeviceOsType sql error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + images := []*responseTypes.Image{} + for _, image := range entityList { + isBind := false + if param.DeviceTypeID != "" { + deviceTypeImageNum, _ := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, map[string]interface{}{ + "image_id": image.ImageID, + "device_type_id": param.DeviceTypeID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if deviceTypeImageNum != 0 { + isBind = true + } + } + + //os, err := osLogic.GetByOsId(logger, image.OsID) + //if err != nil && os == nil { + // os = &responseTypes.Os{} //如果没有找到os,默认为空 + //} + deviceTypeNum, err := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, map[string]interface{}{ + "image_id": image.ImageID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Warn("获取镜像对应的机型个数错误", image.OsID, err.Error()) + return nil, 0, err + } + images = append(images, ImageEntityWithOs2Image(logger, image, int(deviceTypeNum), isBind, tz)) + } + return images, count, nil +} + +func GetByImageId(logger *log.Logger, imageId string) (*responseTypes.Image, error) { + tz := logger.GetPoint("timezone").(string) + entity, _, err := imageDao.GetImageAndOsList(logger, map[string]interface{}{"image_id": imageId}, false, 0, 1) + if err != nil { + logger.Warn("GetImageByUuid sql error:", imageId, err.Error()) + return nil, err + } + if len(entity) == 0 { + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + //os, err := osLogic.GetByOsId(logger, entity.OsID) + //if err != nil { + // logger.Warn("GetByOsId sql error:", entity.OsID, err.Error()) + // return nil, err + //} + deviceTypeNum, err := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, map[string]interface{}{ + "image_id": imageId, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Warn("获取镜像对应的机型个数错误", imageId, err.Error()) + return nil, err + } + return ImageEntityWithOs2Image(logger, entity[0], int(deviceTypeNum), false, tz), nil +} + +func QueryImageDeviceTypes(logger *log.Logger, param *requestTypes.QueryImageDeviceTypesRequest, p util.Pageable) ([]*responseTypes.DeviceType, int64, error) { + //tz := logger.GetPoint("timezone").(string) + language := logger.GetPoint("language").(string) + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "image_id": param.ImageID, + "architecture": param.Architecture, + "is_del": baseLogic.IS_NOT_DEL, + "is_bind": param.IsBind, + } + //queryList := query + //query["count"] = true + _, count, err := rDeviceTypeImageDao.GetImageDeviceTypeList(logger, query, true, 0, 0) + //os.Exit(1) + if err != nil { + logger.Warnf("DescribeDeviceTypes_GetDeviceTypeCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*deviceTypeDao.DeviceType{} + if param.IsAll == baseLogic.IS_ALL { + //entityList, err = imageDao.GetMultiImage(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + fmt.Println("获取全部", query) + entityList, _, err = rDeviceTypeImageDao.GetImageDeviceTypeList(logger, query, false, 0, 0) + } else { + //entityList, err = imageDao.GetMultiImage(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + entityList, _, err = rDeviceTypeImageDao.GetImageDeviceTypeList(logger, query, false, offset, limit) + } + if err != nil { + logger.Warn("imageDao.QueryByDeviceOsType sql error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + fmt.Println(entityList) + deviceTypes := []*responseTypes.DeviceType{} + for _, entity := range entityList { + //isBind := false + //if param.DeviceTypeID != "" { + // deviceTypeImageNum, _ := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, map[string]interface{}{ + // "image_id": image.ImageID, + // "device_type_id": param.DeviceTypeID, + // "is_del": baseLogic.IS_NOT_DEL, + // }) + // if deviceTypeImageNum != 0 { + // isBind = true + // } + //} + //deviceTypeNum, err := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, map[string]interface{}{ + // "image_id": image.ImageID, + // "is_del": baseLogic.IS_NOT_DEL, + //}) + //if err != nil { + // logger.Warn("获取镜像对应的机型个数错误", image.OsID, err.Error()) + // return nil, 0, err + //} + //deviceType.DeviceTypeID + idc, err := idcDao.GetIdcById(logger, entity.IDcID) //获取机房信息 + if err != nil { + idc = &idcDao.Idc{} + } + idcName := idc.Name + if language == baseLogic.EN_US { + idcName = idc.NameEn + } + instanceList, err := instanceDao.GetAllInstance(logger, map[string]interface{}{ + "device_type_id": entity.DeviceTypeID, + "image_id": param.ImageID, + }) + instanceStatus := []string{} + for _, v := range instanceList { + instanceStatus = append(instanceStatus, v.Status) + } + deviceSeries := baseLogic.DeviceTypeSeries[entity.DeviceSeries] + if language == baseLogic.EN_US { + deviceSeries = baseLogic.DeviceTypeSeriesEn[entity.DeviceSeries] + } + deviceType := &responseTypes.DeviceType{ + ID: entity.ID, + IDcID: entity.IDcID, + IDcName: idcName, + IDcNameEn: idc.NameEn, + DeviceType: entity.DeviceType, + DeviceTypeID: entity.DeviceTypeID, + Name: entity.Name, + Description: entity.Description, + DeviceSeries: entity.DeviceSeries, + DeviceSeriesName: deviceSeries, + Architecture: entity.Architecture, + InstanceStatus: instanceStatus, + } + fmt.Println(deviceType) + deviceTypes = append(deviceTypes, deviceType) //deviceTypeLogic.DeviceTypeEntity2DeviceType(logger, deviceType) + } + return deviceTypes, count, nil +} diff --git a/bmp-openapi-console/logic/instanceLogic/InstanceLogic.go b/bmp-openapi-console/logic/instanceLogic/InstanceLogic.go new file mode 100644 index 0000000..dcdee64 --- /dev/null +++ b/bmp-openapi-console/logic/instanceLogic/InstanceLogic.go @@ -0,0 +1,1856 @@ +package instanceLogic + +import ( + "encoding/base64" + "errors" + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceHintsDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceTypeDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/imageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instancePartitionDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/projectDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rDeviceTypeImageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rDeviceTypeImagePartitionDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rInstanceSshkeyDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rInstanceVolumeRaidDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rMonitorRulesInstanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rVolumeRaidDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/raidDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/sharingProjectDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/volumeDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/auditLogLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/deviceTypeLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/idcLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/imageLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/raidLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/sshkeyLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/userLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-openapi/service/rabbit_mq" + namespacePrefix "git.jd.com/cps-golang/ironic-common/ironic/common/NamespacePrefixs" + "git.jd.com/cps-golang/ironic-common/ironic/enums/AuditLogsType" + instanceStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/InstanceStatus" + rabbitEvent "git.jd.com/cps-golang/ironic-common/ironic/event" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + beego "github.com/beego/beego/v2/server/web" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +var NoOpForLock []string = []string{instanceStatus.CREATE_ERROR, instanceStatus.CREATING, instanceStatus.DESTROYING, instanceStatus.DESTROY_ERROR} + +func InstanceEntity2Instance(logger *log.Logger, o *instanceDao.Instance, vrs []*response.InstanceVolumeRaid) *responseTypes.Instance { + //logger := &log.Logger{} + + language := logger.GetPoint("language").(string) + + tz := logger.GetPoint("timezone").(string) + idc, _ := idcDao.GetIdcById(logger, o.IDcID) + if idc == nil { + idc = &idcDao.Idc{} + } + device, _ := deviceDao.GetDeviceById(logger, o.DeviceID) + if device == nil { + device = &deviceDao.Device{} + } + deviceType, _ := deviceTypeDao.GetDeviceTypeById(logger, o.DeviceTypeID) + if deviceType == nil { + deviceType = &deviceTypeDao.DeviceType{} + } + image, _ := imageDao.GetImageByUuid(logger, o.ImageID) + if image == nil { + image = &imageDao.Image{} + } + raidSys, _ := raidDao.GetRaidById(logger, o.SystemVolumeRaidID) + if raidSys == nil { + raidSys = &raidDao.Raid{} + } + raidData, _ := raidDao.GetRaidById(logger, o.DataVolumeRaidID) + if raidData == nil { + raidData = &raidDao.Raid{} + } + reason := baseLogic.InstanceReason[o.Reason] + if language == baseLogic.EN_US { + reason = baseLogic.InstanceReasonEn[o.Reason] + } + //字典不全,兜底 + if reason == "" { + reason = o.Reason + } + + v := &responseTypes.Instance{ + ID: o.ID, + InstanceName: o.InstanceName, + InstanceID: o.InstanceID, + UserID: o.UserID, + ProjectID: o.ProjectID, + + IDcID: o.IDcID, + IdcName: idc.Name, + DeviceID: o.DeviceID, + Sn: device.Sn, + + IloIP: device.IloIP, + Mask: device.Mask, + Eth1Mask: device.MaskEth1, + PrivateIPv4: device.PrivateIPv4, + PrivateEth1IPv4: device.PrivateEth1IPv4, + PrivateEth1IPv6: device.PrivateEth1IPv6, + PrivateIPv6: device.PrivateIPv6, + + DeviceTypeID: o.DeviceTypeID, + DeviceTypeName: deviceType.Name, + DeviceType: deviceType.DeviceType, + DeviceSeries: deviceType.DeviceSeries, + DeviceSeriesName: baseLogic.DeviceTypeSeries[deviceType.DeviceSeries], + CPUAmount: deviceType.CPUAmount, + CPUCores: deviceType.CPUCores, + CPUManufacturer: deviceType.CPUManufacturer, + CPUModel: deviceType.CPUModel, + CPUFrequency: deviceType.CPUFrequency, + MemType: deviceType.MemType, + MemSize: deviceType.MemSize, + MemAmount: deviceType.MemAmount, + MemFrequency: deviceType.MemFrequency, + NicAmount: deviceType.NicAmount, + NicRate: deviceType.NicRate, + InterfaceMode: deviceType.InterfaceMode, + + GpuAmount: deviceType.GpuAmount, + GpuManufacturer: deviceType.GpuManufacturer, + GpuModel: deviceType.GpuModel, + + Hostname: o.Hostname, + Status: o.Status, + Reason: reason, + StatusName: baseLogic.InstanceStatus[o.Status], + ImageID: o.ImageID, + ImageName: image.ImageName, + + SystemVolumeRaidID: o.SystemVolumeRaidID, + SystemVolumeRaidName: raidSys.Name, + Locked: o.Locked, + LockedName: baseLogic.InstanceLock[o.Locked], + InstanceVolumeRaids: vrs, + + Description: o.Description, + + CreatedBy: o.CreatedBy, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + UpdatedBy: o.UpdatedBy, + UpdatedTime: util.TimestampToString(int64(o.UpdatedTime), tz), + BootMode: o.BootMode, + IsNeedRaid: deviceType.IsNeedRaid, + } + if language == baseLogic.EN_US { + v.StatusName = baseLogic.InstanceStatusEn[o.Status] + } + + logger.Infof("instance_info:%s", util.InterfaceToJson(v)) + + return v +} + +func GetInstanceById(logger *log.Logger, InstanceId string) (*responseTypes.Instance, error) { + language := logger.GetPoint("language").(string) + instanceEntity, err := instanceDao.GetInstanceById(logger, InstanceId) + if err != nil { + logger.Warn("GetInstanceByUuid sql error:", InstanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + vrs := []*response.InstanceVolumeRaid{} + volumeEntities, err := volumeDao.GetAllVolumeByDeviceTypeId(logger, instanceEntity.DeviceTypeID) + if err != nil { + logger.Warnf("GetInstanceById.GetAllVolumeByDeviceTypeId error, InstanceId:%s, error:%s", InstanceId, err.Error()) + } + //有些是盘符,就没有raid,这种情况行不通 + rInstanceVolumeRaidEntities, err := rInstanceVolumeRaidDao.GetRInstanceVolumeRaidByInstanceId(logger, InstanceId) + if err != nil { + logger.Warnf("GetInstanceById.GetRVolumeRaidsByInstanceId error, instance_id:%s, error:%s", InstanceId, err.Error()) + } + for _, volumeEntity := range volumeEntities { + if language != baseLogic.EN_US { + if volumeEntity.DiskType == "notLimited" { + volumeEntity.DiskType = "无限制" + } + if volumeEntity.InterfaceType == "notLimited" { + volumeEntity.InterfaceType = "无限制" + } + + } + + var tRaid *raidDao.Raid + for _, rInstanceVolumeRaidEntity := range rInstanceVolumeRaidEntities { + if rInstanceVolumeRaidEntity.VolumeID == volumeEntity.VolumeID { + tRaid = &raidDao.Raid{ + RaidID: rInstanceVolumeRaidEntity.RaidID, + Name: rInstanceVolumeRaidEntity.RaidName, + } + break + } + } + vrs = append(vrs, &response.InstanceVolumeRaid{ + Volume: volumeEntity, + Raid: tRaid, + }) + + } + + return InstanceEntity2Instance(logger, instanceEntity, vrs), nil +} + +func CreateInstance(logger *log.Logger, param requestTypes.CreateInstanceRequest) (ids []string, err error) { + + if param.Password == "" && param.SshKeyID == "" { + panic(constant.BuildInvalidArgumentWithArgs("密码和sshkeyid不能同时为空", "password and sshkeyID both empty")) + } + if param.Password != "" && param.SshKeyID != "" { + panic(constant.BuildInvalidArgumentWithArgs("密码和sshkeyid不能同时存在", "password and sshkeyID invalidate")) + } + idc, err := idcLogic.QueryIdcById(logger, param.IdcID) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("idcId非法", "idc invalidate")) + } + project, err := projectDao.GetProjectById(logger, param.ProjectID) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("projectId非法", "projectId invalidate")) + } + if project != nil && project.UserID != logger.GetPoint("userId").(string) { //项目要么是自己所有的,要么是共享的 + s, _ := sharingProjectDao.GetOneSharingProject(logger, project.ProjectID, project.UserID, logger.GetPoint("userId").(string)) + if s == nil { + panic(constant.BuildInvalidArgumentWithArgs("项目ID和用户ID不匹配", "projectID not match userID")) + } + } + deviceType, err := deviceTypeLogic.QueryDeviceTypeById(logger, param.DeviceTypeID) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("deviceTypeId非法", "deviceTypeId invalidate")) + } + if deviceType.IDcID != param.IdcID { + panic(constant.BuildInvalidArgumentWithArgs("idcId和deviceTypeId不匹配", "idcId not match deviceTypeId")) + } + imageEntity, err := imageLogic.GetByImageId(logger, param.ImageID) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("imageId非法", "imageId invalidate")) + } + //检查devicetype和image是否绑定 + q := map[string]interface{}{ + "image_id": param.ImageID, + "device_type_id": param.DeviceTypeID, + "is_del": baseLogic.IS_NOT_DEL, + } + n, _ := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, q) + if n == 0 { + panic(constant.BuildInvalidArgumentWithArgs("此机型和镜像未绑定", "devicetype and image do not associated")) + } + + if deviceType.IsNeedRaid != "no_need_raid" { //配置了阵列卡,需要做raid(包括NORAID) + _, err = raidLogic.GetRaidEntityByRaidId(logger, param.SystemVolumeRaidID) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("systemVolumeRaidId非法", "systemVolumeRaidId invalidate")) + } + + //检查devicetype和raid是否绑定 + + systemRolumeRaidEntities, err := rVolumeRaidDao.GetSystemVolumeRaid(logger, param.DeviceTypeID) + if err != nil { + logger.Warnf("createInstance.GetSystemVolumeRaid error, device_type_id:%s, error:%s", param.DeviceTypeID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs("此机型系统盘和raid未绑定", "devicetype systemdisk and raid do not associated")) + } + selected := false + for _, v := range systemRolumeRaidEntities { + if v.RaidID == param.SystemVolumeRaidID { + selected = true + break + } + } + if !selected { + logger.Warnf("此机型系统盘和raid未绑定, error, device_type_id:%s, raid_id:%s", param.DeviceTypeID, param.SystemVolumeRaidID) + panic(constant.BuildInvalidArgumentWithArgs("此机型系统盘和raid未绑定", "devicetype systemdisk and raid do not associated")) + } + } + + if param.SshKeyID != "" { + sshkeys := strings.Split(param.SshKeyID, ",") + for _, sshkey := range sshkeys { + _, err := sshkeyLogic.GetSshkeyById(logger, strings.TrimSpace(sshkey)) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("sshKeyId非法", "sshKeyId invalidate")) + } + } + + } + deviceConditions := deviceLogic.GetAllDevices(logger, map[string]interface{}{ + "manage_status": baseLogic.PUTAWAY, + "is_del": baseLogic.IS_NOT_DEL, + "device_type_id": param.DeviceTypeID, + }, []string{}, []string{}, []string{}) + if err != nil { + return nil, err + } + if len(deviceConditions) < param.Count { + logger.Warn("设备库存不足") + panic(constant.BuildInvalidArgumentWithArgs("设备库存不足", "device stock is not enough")) + } + userId := logger.GetPoint("userId").(string) + + list, _ := instanceDao.GetAllInstance(logger, map[string]interface{}{ + "instance_name": param.InstanceName, + "user_id": userId, + "is_del": 0, + }) + if len(list) != 0 { + logger.Warn("instanceName exist:", param.InstanceName) + panic(constant.BuildInvalidArgumentWithArgs("实例名称已存在", "projectName exist")) + } + + if param.HostName == "" { + list, _ := instanceDao.GetAllInstance(logger, map[string]interface{}{ + "hostname.like": "%" + idc.Idc.Shortname + "-" + deviceType.DeviceType + "%", + "user_id": userId, + "is_del": baseLogic.IS_NOT_DEL, + }) + param.HostName = fmt.Sprintf("%s-%s-%d", idc.Idc.Shortname, deviceType.DeviceType, len(list)+1) + param.HostName = strings.ReplaceAll(param.HostName, ".", "-") //机型规格里面的.替换成-,如c1.normal=> c1-normal + param.HostName = strings.ReplaceAll(param.HostName, "_", "-") + } + + var bootmode string = param.BootMode //优先取用户指定的 + if strings.ToLower(imageEntity.Format) == "qcow2" { + //qcow2镜像没有分区信息,通常给windows使用 + } else { //tar包镜像 + //从r_devicetype_image_partition表获取bootmode + imagePartitions, _ := rDeviceTypeImagePartitionDao.GetByDeviceTypeAndImageId(logger, param.DeviceTypeID, param.ImageID) + if len(imagePartitions) == 0 { + panic(constant.BuildInvalidArgumentWithArgs("r_device_type_image_partition配置错误", "r_device_type_image_partition config error")) + } + + if bootmode == "" { + bootmode = imagePartitions[0].BootMode + } + } + + // deviceCount, err := deviceDao.GetDeviceCount(logger, map[string]interface{}{ + // "is_del": 0, + // }) + // if err != nil { + // logger.Warnf("createInstance.GetDeviceCount error:%s", err.Error()) + // } + + //user, err := userLogic.GetUserById(logger, userId) + //if err != nil { + // panic(constant.BuildInvalidArgumentWithArgs("用户id不存在", "userId not exist")) + //} + entities := []*instanceDao.Instance{} // instanceCreator.Create(logger, param) + //ids := []string{} + for i := 0; i < param.Count; i++ { + instanceName := fmt.Sprintf("%s-%d", param.InstanceName, i) + if param.Count == 1 { + instanceName = param.InstanceName + } + //instanceList, err := instanceDao.GetAllInstance(logger, map[string]interface{}{ + // "instance_name": instanceName, + // "user_id": logger.GetPoint("userId").(string), + // "is_del": baseLogic.IS_NOT_DEL, + //}) + //if len(instanceList) != 0 { + // logger.Warn("instanceName exist:", instanceName) + // panic(constant.BuildInvalidArgumentWithArgs("实例名称已存在", "instanceName exist")) + //} + entity := &instanceDao.Instance{ + IDcID: param.IdcID, + InstanceID: commonUtil.GetRandString("bmp-", namespacePrefix.IMAGE_ID_LENGTH, false, true, true), + ProjectID: param.ProjectID, + UserID: userId, + DeviceTypeID: param.DeviceTypeID, + InstanceName: instanceName, + Hostname: param.HostName, + Description: param.Description, + ImageID: param.ImageID, + SystemVolumeRaidID: param.SystemVolumeRaidID, + Status: instanceStatus.CREATING, + DeviceID: deviceConditions[i].DeviceID, + Locked: baseLogic.UNLOCKED, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + BootMode: bootmode, + } + if param.InstallBmpAgent { + entity.IsInstalledAgent = "1" + } else { + entity.IsInstalledAgent = "0" + } + + //if entity.Hostname == "" { + // entity.Hostname = fmt.Sprintf("%s-%s-%d", idc.Idc.Name, deviceType.Name, i) + //} + + //还要写进实例分区表,实例秘钥表 todo + partitionsObj := param.SystemPartition + //if len(partitionsObj) == 0 { + // panic(constant.BuildInvalidArgumentWithArgs("系统分区不能为空", "SystemPartition is empty")) + //} + for i := 0; i < len(partitionsObj); i++ { //数组的结构体partitionObj,不能用range遍历?? + + var partitionType string + if strings.EqualFold(partitionsObj[i].MountPoint, "/") { + partitionType = "root" + } else if strings.EqualFold(partitionsObj[i].MountPoint, "/boot") { + partitionType = "boot" + } else { + partitionType = "system" + } + var partitionLabel string + if strings.EqualFold(partitionsObj[i].MountPoint, "/") { + partitionLabel = "l_root" + } else if strings.EqualFold(partitionsObj[i].MountPoint, "swap") { + partitionLabel = "l_swap" + } else { + label := strings.Replace(partitionsObj[i].MountPoint, "/", "l_", -1) + partitionLabel = label + } + + _, err = instancePartitionDao.AddInstancePartition(logger, &instancePartitionDao.InstancePartition{ + InstanceID: entity.InstanceID, + ImageID: param.ImageID, + DeviceTypeID: param.DeviceTypeID, + BootMode: bootmode, + PartitionType: partitionType, + PartitionSize: partitionsObj[i].Size, + PartitionFsType: partitionsObj[i].FsType, + PartitionLabel: partitionLabel, + PartitionMountPoint: partitionsObj[i].MountPoint, + SystemDiskLabel: "gpt", + DataDiskLabel: "gpt", + + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + InstancePartitionID: commonUtil.GetRandString("ipt-", namespacePrefix.IMAGE_ID_LENGTH, false, true, true), + Number: i + 1, + }) + if err != nil { + logger.Warnf("add instance partition error,instanceId:%s,partition%s,error:%s", entity.InstanceID, util.InterfaceToJson(param.SystemPartition), err.Error()) + return nil, err + } + } + if param.SshKeyID != "" { + for _, sshkeyId := range strings.Split(param.SshKeyID, ",") { + sshkeyId = strings.TrimSpace(sshkeyId) + if sshkeyId == "" { + panic(constant.BuildInvalidArgumentWithArgs("秘钥ID不能为空", "sshkeyID is empty")) + } + _, err = rInstanceSshkeyDao.AddrInstanceSshkey(logger, &rInstanceSshkeyDao.RInstanceSshkey{ + InstanceID: entity.InstanceID, + SSHkeyID: sshkeyId, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + }) + if err != nil { + logger.Warn("add r_instance_sshkey error:", err.Error()) + return nil, err + } + } + } + _, err = instanceDao.AddInstance(logger, entity) + + if err != nil { + logger.Warn("createInstance error:", err.Error()) + return nil, err + } + if err := deviceLogic.ModifyDeviceByDeviceId(logger, &requestTypes.ModifyAllDevicesRequest{ + ManageStatus: baseLogic.CREATED, + InstanceID: entity.InstanceID, + UserId: userId, + UserName: logger.GetPoint("username").(string), + }, deviceConditions[i].DeviceID); err != nil { + logger.Warn("modifyDevice instanceId error:", err.Error()) + return nil, err + } + + if deviceType.IsNeedRaid != "no_need_raid" { //配置了阵列卡,需要做raid(包括NORAID) + systemVolumeEntity, err := volumeDao.GetSystemVolumeByDeviceTypeId(logger, entity.DeviceTypeID) + if err != nil { + logger.Warnf("createInstance.GetSystemVolumeByDeviceId error, device_type_id:%s, error:%s", entity.DeviceTypeID, err.Error()) + } + + raidEntity, err := raidDao.GetRaidByUuid(logger, param.SystemVolumeRaidID) + if err != nil { + logger.Warnf("createInstance.GetRaidByUuid error, raid_id:%s, error:%s", param.SystemVolumeRaidID, err.Error()) + } + rInstanceVolumeRaidDaoEntities := []*rInstanceVolumeRaidDao.RInstanceVolumeRaid{ + &rInstanceVolumeRaidDao.RInstanceVolumeRaid{ + InstanceID: entity.InstanceID, + VolumeID: systemVolumeEntity.VolumeID, + VolumeType: systemVolumeEntity.VolumeType, + RaidID: param.SystemVolumeRaidID, + RaidCan: "", //TODO + RaidName: raidEntity.Name, + }, + } + for _, v := range param.VolumeRaIDs { + if v.VolumeID == "" { + logger.Warnf("createInstance.VolumeRaIDs.volumeId empty, instance_id:%s", entity.InstanceID) + continue + } + + if v.VolumeType == "system" { + continue //TODO + } + raidEntity, err := raidDao.GetRaidByUuid(logger, v.RaidID) + if err != nil { + logger.Warnf("createInstance.GetRaidByUuid error, raid_id:%s, error:%s", v.RaidID, err.Error()) + } + e := &rInstanceVolumeRaidDao.RInstanceVolumeRaid{ + InstanceID: entity.InstanceID, + VolumeID: v.VolumeID, + VolumeType: v.VolumeType, + RaidID: v.RaidID, + RaidCan: v.RaidCan, + RaidName: raidEntity.Name, + } + rInstanceVolumeRaidDaoEntities = append(rInstanceVolumeRaidDaoEntities, e) + } + if len(rInstanceVolumeRaidDaoEntities) > 0 { + if _, err := rInstanceVolumeRaidDao.AddMultiRInstanceVolumeRaid(logger, rInstanceVolumeRaidDaoEntities); err != nil { + logger.Warnf("createInstance.AddMultiRInstanceVolumeRaid error, instance_id:%s, error:%s", entity.InstanceID, err.Error()) + } + } + } + + entities = append(entities, entity) + //ids = append(ids, entity.InstanceID) + } + return afterCreateInstances(logger, entities, param) +} + +func getInstanceUserData(logger *log.Logger, param requestTypes.CreateInstanceRequest, installBmpAgent bool) string { + + if installBmpAgent { + + bmpImageHost, err := beego.AppConfig.String("bmp_image_host") + if err != nil { + logger.Warnf("getInstanceUserData.get bmp_image_host error:%s", err.Error()) + } + bmpImagePort, err := beego.AppConfig.String("bmp_image_port") + if err != nil { + logger.Warnf("getInstanceUserData.get bmp_image_port error:%s", err.Error()) + } + + tpl := `#!/bin/bash + + readonly WORKSPACE_DIR=/tmp/ + AGENT_BIN=bmp-agent.bin + ########################################### + + cd ${WORKSPACE_DIR} + echo "10.208.12.72 bmp-agent-proxy" >> /etc/hosts + AGENT_URL=http://bmp-agent-proxy:10000/${AGENT_BIN} + + + + curl ${AGENT_URL} -O + chmod +x ${AGENT_BIN} + sh +x ${AGENT_BIN}` + + content := strings.Replace(tpl, "10.208.12.72", bmpImageHost, -1) + content = strings.Replace(content, "10000", bmpImagePort, -1) + return base64.StdEncoding.EncodeToString([]byte(content)) + + } + return "" + +} + +func afterCreateInstances(logger *log.Logger, entities []*instanceDao.Instance, param requestTypes.CreateInstanceRequest) ([]string, error) { + + instance_ids := []string{} + for _, v := range entities { + instance_ids = append(instance_ids, v.InstanceID) + } + + userData := getInstanceUserData(logger, param, param.InstallBmpAgent) + + err := sendCreateInstanceEvent(logger, instance_ids, param.Password, userData) //param.UserData, param.AliasIPs, param.ExtensionAliasIps + if err != nil { + return nil, err + } + if len(entities) == 1 { + //instance := entities[0] + //if param.AliasIPs != nil { + // saveAliasIPs(logger, instance.InstanceID, instance.SubnetID, param.AliasIPs) + //} + //if param.ExtensionAliasIps != nil { + // saveAliasIPs(logger, instance.InstanceID, instance.ExtensionSubnetID, param.ExtensionAliasIps) + //} + } + return instance_ids, nil +} + +func sendCreateInstanceEvent(logger *log.Logger, instance_ids []string, password string, userData string) error { + + logid := logger.GetPoint("logid").(string) + msg := rabbitIronicMsgApi.CreateInstancesMessage{ + ApiMessage: rabbitIronicMsgApi.ApiMessage{ + RequestId: logid, + }, + InstanceIds: instance_ids, + Password: password, + UserData: userData, + //AliasIps: alias_ips, + //ExtensionAliasIps: extension_alias_ips, + } + userId := logger.GetPoint("userId").(string) + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("RetryCommand convert event msg error:", instance_ids, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warnf("RetryCommand UpdateCommandById sql error, msg:%s, error:%s", util.ObjToJson(event), err.Error()) + return err + } else { + logger.Infof("sendCreateInstanceEvent SendToScheduler success, msg:%s", util.ObjToJson(event)) + } + return nil +} + +func checkInstanceNameUnique(logger *log.Logger, name string, existsNames []string) error { + + if util.InArrayString(name, existsNames) { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例名称 %s 已经存在", name), fmt.Sprintf("instanceName %s already exist", name))) + } + return nil +} + +func ModifyInstance(logger *log.Logger, param *requestTypes.ModifyInstanceRequest, instanceId string) error { + q := map[string]interface{}{ + "is_del": 0, + } + its, _ := instanceDao.GetAllInstance(logger, q) + var existNames []string + var instance *instanceDao.Instance + for _, item := range its { + if item.InstanceID == instanceId { + instance = item + } + existNames = append(existNames, item.InstanceName) + } + + if instance == nil { + logger.Warnf("GetInstanceByUuid sql not found, uuid:%s", instanceId) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + if err := checkInstanceNameUnique(logger, param.InstanceName, existNames); err != nil { + return err + } + + //instance.InstanceName = param.InstanceName + if param.Description != nil { + instance.Description = *param.Description + } + instance.UpdatedBy = logger.GetPoint("username").(string) + instance.UpdatedTime = int(time.Now().Unix()) + if err := instanceDao.UpdateInstanceAnywhere(logger, instance); err != nil { + logger.Warn("ModifyInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + return nil +} + +// 批量编辑实例名称 +func ModifyInstances(logger *log.Logger, param requestTypes.ModifyInstancesRequest) error { + + var instances []*instanceDao.Instance + + q := map[string]interface{}{ + "is_del": 0, + } + aits, _ := instanceDao.GetAllInstance(logger, q) + var existNames []string + for _, v := range aits { + if !util.InArrayString(v.InstanceID, param.InstanceIDs) { + existNames = append(existNames, v.InstanceName) + } else { + if !InstanceOwnedCheck(logger, v) { + panic(constant.PermissionDenyForObject) + } + instances = append(instances, v) + } + } + for idx, _ := range instances { + var instanceName string + if idx == 0 { + instanceName = param.InstanceName + } else { + instanceName = fmt.Sprintf("%s_%d", param.InstanceName, idx) + } + + instances[idx].InstanceName = instanceName + if err := checkInstanceNameUnique(logger, instanceName, existNames); err != nil { + return err + } + } + + for _, v := range instances { + v.UpdatedBy = logger.GetPoint("username").(string) + if err := instanceDao.UpdateInstanceById(logger, v); err != nil { + logger.Warnf("ModifyInstances.UpdateInstanceById error, instance_id:%s, instance_name:%s", v.InstanceID, v.InstanceName) + } + auditLogLogic.SaveAuditLogs(logger, v.DeviceID, v.InstanceID, AuditLogsType.AuditLogsEditInstanceName) + } + return nil +} + +func ModifyProjectInstance(logger *log.Logger, param *requestTypes.ModifyInstanceRequest, instanceId string) error { + q := map[string]interface{}{ + "is_del": 0, + } + its, _ := instanceDao.GetAllInstance(logger, q) + var existNames []string + var v *instanceDao.Instance + for _, item := range its { + if item.InstanceID == instanceId { + v = item + } + existNames = append(existNames, item.InstanceName) + } + + if v == nil { + logger.Warnf("GetInstanceByUuid not found, uuid:%s", instanceId) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, v) { + panic(constant.PermissionDenyForObject) + } + + if err := checkInstanceNameUnique(logger, param.InstanceName, existNames); err != nil { + return err + } + if param.Description != nil { + v.Description = *param.Description + } + if param.InstanceName != "" { + v.InstanceName = param.InstanceName + } + + if err := instanceDao.UpdateInstanceAnywhere(logger, v); err != nil { + logger.Warn("ModifyInstance UpdateInstanceAnywhere sql error:", instanceId, err.Error()) + return err + } + auditLogLogic.SaveAuditLogs(logger, v.DeviceID, v.InstanceID, AuditLogsType.AuditLogsEditInstanceName) + + return nil +} + +func LockInstance(logger *log.Logger, instanceId string) error { + instance, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warn("GetInstanceByUuid sql error:", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + deviceEntity, err := deviceDao.GetDeviceById(logger, instance.DeviceID) + if err != nil { + logger.Warnf("LockInstance.GetDeviceById sql error, device_id:%s, error:%s", instance.DeviceID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + if instance.Locked == baseLogic.LOCKED { + logger.Warnf("Instance %s already locked", instanceId) + panic(constant.NOT_SUPPORTED) + } + + if util.InArray(instance.Status, NoOpForLock) { + logger.Warnf("unsupported lock error status instance %s", instanceId) + panic(constant.NOT_SUPPORTED) + } + + entity := &instanceDao.Instance{ + InstanceID: instanceId, + Locked: baseLogic.LOCKED, + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("ModifyInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + + auditLogLogic.SaveAuditLogs(logger, deviceEntity.DeviceID, instanceId, AuditLogsType.AuditLogsTypeLockInstances) + return nil +} + +func UnLockInstance(logger *log.Logger, instanceId string) error { + instance, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warn("GetInstanceById sql error:", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + if instance.Locked == baseLogic.UNLOCKED { + logger.Warnf("instance %s already unlocked.", instanceId) + panic(constant.NOT_SUPPORTED) + } + + if util.InArray(instance.Status, NoOpForLock) { + logger.Warnf("unsupported lock error status instance %s", instanceId) + panic(constant.NOT_SUPPORTED) + } + + entity := &instanceDao.Instance{ + InstanceID: instanceId, + Locked: baseLogic.UNLOCKED, + UpdatedBy: "admin", + UpdatedTime: int(time.Now().Unix()), + } + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("ModifyInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + return nil +} + +func StartInstance(logger *log.Logger, instanceId string) error { + instance, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warn("GetInstanceByUuid sql error:", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + //可以在此增加一些逻辑判断,比如,只能处在关机模式下才可以开机,其他状态不可以。。。后续再处理这块 + if instance.Status != instanceStatus.STOPPED { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是关机", instanceId), fmt.Sprintf("unsupported start instance %s", instanceId))) + } + entity := &instanceDao.Instance{ + InstanceID: instanceId, + Status: instanceStatus.STARTING, + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("StartInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + return sendStartInstanceEvent(logger, []string{instanceId}) +} +func sendStartInstanceEvent(logger *log.Logger, instance_ids []string) error { + + logid := logger.GetPoint("logid").(string) + msg := rabbitIronicMsgApi.StartInstancesMessage{} + msg.ApiMessage.RequestId = logid + msg.InstanceIds = instance_ids + userId := logger.GetPoint("userId").(string) + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("convert StartInstancesMessage 2 event error:", instance_ids, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warnf("StartInstancesMessage SendToScheduler error, msg:%s, error:%s", util.ObjToJson(msg), err.Error()) + return err + } else { + logger.Infof("StartInstancesMessage SendToScheduler success, msg:%s", util.ObjToJson(msg)) + } + return nil +} +func StopInstance(logger *log.Logger, instanceId string) error { + instance, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warn("GetInstanceByUuid sql error:", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + + } + + if instance.Status != instanceStatus.RUNNING { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是运行", instanceId), fmt.Sprintf("unsupported stop instance %s", instanceId))) + } + entity := &instanceDao.Instance{ + InstanceID: instanceId, + Status: instanceStatus.STOPPING, + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("StopInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + return sendStopInstanceEvent(logger, []string{instanceId}) +} +func sendStopInstanceEvent(logger *log.Logger, instance_ids []string) error { + + logid := logger.GetPoint("logid").(string) + msg := rabbitIronicMsgApi.StopInstancesMessage{} + msg.ApiMessage.RequestId = logger.GetPoint("logid").(string) + msg.InstanceIds = instance_ids + userId := logger.GetPoint("userId").(string) + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("convert StopInstancesMessage 2 event error:", instance_ids, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warnf("sendStopInstanceEvent SendToScheduler error, msg:%s, error:%s", util.ObjToJson(event), err.Error()) + return err + } else { + logger.Infof("sendStopInstanceEvent SendToScheduler success, msg:%s", util.ObjToJson(event)) + } + return nil +} +func RestartInstance(logger *log.Logger, instanceId string) error { + instance, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warn("GetInstanceByUuid sql error:", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + if instance.Status != instanceStatus.RUNNING { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是运行", instanceId), fmt.Sprintf("unsupported restart instance %s", instanceId))) + } + entity := &instanceDao.Instance{ + InstanceID: instanceId, + Status: instanceStatus.RESTARTING, + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("RestartInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + return sendRestartInstanceEvent(logger, []string{instanceId}) +} +func sendRestartInstanceEvent(logger *log.Logger, instance_ids []string) error { + + logid := logger.GetPoint("logid").(string) + msg := rabbitIronicMsgApi.RestartInstancesMessage{} + msg.ApiMessage.RequestId = logid + msg.InstanceIds = instance_ids + userId := logger.GetPoint("userId").(string) + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("convert RestartInstancesMessage 2 event error:", instance_ids, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warn("sendRestartInstanceEvent SendToScheduler error, msg:%s, error:%s", util.ObjToJson(event), err.Error()) + return err + } else { + logger.Infof("sendRestartInstanceEvent SendToScheduler success, msg:%s", util.ObjToJson(event)) + } + return nil +} + +func ResetInstanceStatus(logger *log.Logger, instanceId string) error { + instance, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warn("GetInstanceByUuid sql error:", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + //可以在此增加一些逻辑判断,比如,只能处在关机模式下才可以开机 + resetArr := []string{instanceStatus.START_ERROR, instanceStatus.STOP_ERROR, instanceStatus.RESTART_ERROR, instanceStatus.DESTROY_ERROR} + if !util.InArray(instance.Status, resetArr) { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态错误", instanceId), fmt.Sprintf("unsupported start instance %s", instanceId))) + } + entity := &instanceDao.Instance{ + InstanceID: instanceId, + Status: instanceStatus.Error_Instance_To_Reset_Status[instance.Status], + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + + if err := commandDao.DeleteCommandByInstanceId(logger, instanceId); err != nil { + logger.Warn("ResetInstanceStatus DeleteCommandByInstanceId sql error:", instanceId, err.Error()) + } + + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("ResetInstanceStatus UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + + return nil +} + +func DeleteInstance(logger *log.Logger, instanceId string) error { + entity, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warn("GetInstanceByUuid sql error:", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, entity) { + panic(constant.PermissionDenyForObject) + } + + // 已锁定实例不允许删除 + if entity.Locked == baseLogic.LOCKED { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("已锁定实例 %s 不能被删除", instanceId), fmt.Sprintf("locked instance %s not allowed delete", instanceId))) + } + + if !util.InArray(entity.Status, []string{instanceStatus.STOPPED, instanceStatus.CREATE_ERROR}) { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是关机和创建失败,不允许被删除", instanceId), fmt.Sprintf("unsupported delete instance %s", instanceId))) + } + + if entity.Status == instanceStatus.CREATE_ERROR { //创建错误的实例,不用走完整的删除逻辑,直接释放各种资源就行 + //释放销毁实例使用的各种资源 + if err := rInstanceSshkeyDao.DeleteInstanceSshkeyByInstanceID(logger, entity.InstanceID); err != nil { + logger.Warn("DeleteInstance DeleteInstanceSshkeyByInstanceID sql error:", instanceId, err.Error()) + } + deviceEntiry, err := deviceDao.GetDeviceById(logger, entity.DeviceID) + if err != nil { + logger.Warnf("delete error status instance.GetDeviceById error, device_id:%s, error:%s", entity.DeviceID, err.Error()) + return err + } + device := &deviceDao.Device{ + Sn: deviceEntiry.Sn, + ManageStatus: baseLogic.PUTAWAY, //删除实例以后,设备表的某些状态更改 + } + if err := deviceDao.UpdateDeviceBySn(logger, device); err != nil { + logger.Warnf("update device error,deviceSN:%s, error:%s", device.Sn, err.Error()) + return err + } + if err := commandDao.DeleteCommandBySn(logger, deviceEntiry.Sn); err != nil { + logger.Warn("DeleteInstance DeleteCommandBySn sql error:", instanceId, err.Error()) + } + + entity.IsDel = 1 + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("DeleteInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + + if err := deviceHintsDao.DeleteDeviceHintsBySn(logger, deviceEntiry.Sn); err != nil { + logger.Warn("DeleteInstance DeleteRootDeviceHintsBySn sql error:", instanceId, err.Error()) + return err + } + + return nil + } + + entity.Status = instanceStatus.DESTROYING + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + entity.DeletedTime = int(time.Now().Unix()) + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("DeleteInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + //释放销毁实例使用的各种资源 + if err := rInstanceSshkeyDao.DeleteInstanceSshkeyByInstanceID(logger, entity.InstanceID); err != nil { + logger.Warn("DeleteInstance DeleteInstanceSshkeyByInstanceID sql error:", instanceId, err.Error()) + } + if err := rMonitorRulesInstanceDao.DeleteMonitorRuleInstanceByInstanceID(logger, entity.InstanceID); err != nil { + logger.Warn("DeleteInstance DeleteMonitorRuleInstanceByInstanceID sql error:", instanceId, err.Error()) + } + return sendDeleteInstanceEvent(logger, instanceId) +} + +//批量删除实例 +func DeleteInstances(logger *log.Logger, instanceIds []string) error { + + instances := []*instanceDao.Instance{} + + for _, instanceId := range instanceIds { + entity, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warn("GetInstanceByUuid sql error:", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, entity) { + panic(constant.PermissionDenyForObject) + } + + // 已锁定实例不允许删除 + if entity.Locked == baseLogic.LOCKED { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("已锁定实例 %s 不能被删除", instanceId), fmt.Sprintf("locked instance %s not allowed delete", instanceId))) + } + + if !util.InArray(entity.Status, []string{instanceStatus.STOPPED, instanceStatus.CREATE_ERROR}) { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是关机和创建失败,不允许被删除", instanceId), fmt.Sprintf("unsupported delete instance %s", instanceId))) + } + instances = append(instances, entity) + } + + for _, entity := range instances { + if entity.Status == instanceStatus.CREATE_ERROR { //创建错误的实例,不用走完整的删除逻辑,直接释放各种资源就行 + //释放销毁实例使用的各种资源 + if err := rInstanceSshkeyDao.DeleteInstanceSshkeyByInstanceID(logger, entity.InstanceID); err != nil { + logger.Warn("DeleteInstance DeleteInstanceSshkeyByInstanceID sql error:", entity.InstanceID, err.Error()) + } + deviceEntiry, err := deviceDao.GetDeviceById(logger, entity.DeviceID) + if err != nil { + logger.Warnf("delete error status instance.GetDeviceById error, device_id:%s, error:%s", entity.DeviceID, err.Error()) + return err + } + device := &deviceDao.Device{ + Sn: deviceEntiry.Sn, + ManageStatus: baseLogic.PUTAWAY, //删除实例以后,设备表的某些状态更改 + } + if err := deviceDao.UpdateDeviceBySn(logger, device); err != nil { + logger.Warnf("update device error,deviceSN:%s, error:%s", device.Sn, err.Error()) + return err + } + if err := commandDao.DeleteCommandBySn(logger, deviceEntiry.Sn); err != nil { + logger.Warn("DeleteInstance DeleteCommandBySn sql error:", entity.InstanceID, err.Error()) + } + + entity.IsDel = 1 + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("DeleteInstance UpdateInstanceById sql error:", entity.InstanceID, err.Error()) + return err + } + + return nil + } + + entity.Status = instanceStatus.DESTROYING + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + entity.DeletedTime = int(time.Now().Unix()) + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("DeleteInstance UpdateInstanceById sql error:", entity.InstanceID, err.Error()) + return err + } + //释放销毁实例使用的各种资源 + if err := rInstanceSshkeyDao.DeleteInstanceSshkeyByInstanceID(logger, entity.InstanceID); err != nil { + logger.Warn("DeleteInstance DeleteInstanceSshkeyByInstanceID sql error:", entity.InstanceID, err.Error()) + } + if err := sendDeleteInstanceEvent(logger, entity.InstanceID); err != nil { + logger.Warnf("DeleteInstances.sendDeleteInstanceEvent error, instance_id:%s, error:%s", entity.InstanceID, err.Error()) + } + } + + return nil + +} + +func sendDeleteInstanceEvent(logger *log.Logger, instance_id string) error { + + logid := logger.GetPoint("logid").(string) + msg := rabbitIronicMsgApi.DeleteInstanceMessage{} + msg.ApiMessage.RequestId = logid + msg.InstanceId = instance_id + userId := logger.GetPoint("userId").(string) + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("convert DeleteInstanceMessage 2 event error:", instance_id, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warn("sendDeleteInstanceEvent SendToScheduler error, msg:%s, error:%s", util.ObjToJson(event), err.Error()) + return err + } else { + logger.Infof("sendDeleteInstanceEvent SendToScheduler success, msg:%s", util.ObjToJson(event)) + } + return nil +} + +func GetInstanceCount(logger *log.Logger, query map[string]interface{}) (int64, error) { + count, err := instanceDao.GetInstanceCount(logger, query) + if err != nil { + logger.Warnf("GetInstanceCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return 0, err + } + return count, nil +} + +func GetInstanceList(logger *log.Logger, param *requestTypes.QueryInstancesRequest, p util.Pageable) ([]*responseTypes.Instance, int64, error) { + userId := logger.GetPoint("userId").(string) + offset, limit := p.Pageable2offset() + + var deviceId string + if param.IloIP != "" || param.IPV4 != "" || param.IPV6 != "" { + q := requestTypes.QueryDevicesRequest{ + IDcID: param.IdcID, + IsAll: baseLogic.IS_ALL, + } + if param.IloIP != "" { + q.IloIP = param.IloIP + } + if param.IPV4 != "" { + q.IPV4 = param.IPV4 + } + if param.IPV6 != "" { + q.IPV6 = param.IPV6 + } + devices, _, err := deviceLogic.QueryDevices(logger, q, util.Pageable{}) + if err != nil { + logger.Warnf("GetInstanceList deviceLogic.QueryDevices error:%s", err.Error()) + return nil, 0, err + } + if len(devices) != 1 { + logger.Warnf("GetInstanceList deviceLogic.QueryDevices not one, data is:%s", util.InterfaceToJson(devices)) + return nil, 0, err + } + deviceId = devices[0].DeviceID + } + + var profileInstanceIds []string + projectEntity, err := projectDao.GetProjectById(logger, param.ProjectID) + if projectEntity.UserID != userId { //非所属关系,看是否为被共享关系 + q1 := map[string]interface{}{ + "project_id": param.ProjectID, + "shared_user_id": userId, + "is_del": 0, + } + sharesProjects, _ := sharingProjectDao.GetAllShareProjects(logger, q1) + if len(sharesProjects) > 0 { + pInstanceIds := sharesProjects[0].SharedInstanceIDs + profileInstanceIds = strings.Split(pInstanceIds, ",") + + } else { //project既不归属于当前用户,又没有共享给当前用户 + logger.Warnf("GetInstanceList project_id validate error, project_id:%s, user_id:%s", param.ProjectID, userId) + return nil, 0, err + } + } + + // q2 := map[string]interface{}{ + // "project_id": param.ProjectID, + // "owner_user_id": userId, + // "is_del": 0, + // } + // sharesProjects, _ = sharingProjectDao.GetAllShareProjects(logger, q2) + // sharedids := []string{} + // for _, v := range sharesProjects { + // sharedids = append(sharedids, v.OwnerUserID, v.SharedUserID) + // } + + query := map[string]interface{}{ + "is_del": 0, + //"sn": c.GetString("sn"), + "project_id": param.ProjectID, + // "user_id.in": append(append([]string{userId}, ownerids...), sharedids...), //当前用户可以是共享用户,也可以是owner用户 + "idc_id": param.IdcID, + } + if param.DeviceID != "" { + query["device_id"] = param.DeviceID + } else if deviceId != "" { + query["device_id"] = deviceId + } + + if param.InstanceID != "" { + query["instance_id"] = param.InstanceID + } + + if len(profileInstanceIds) > 0 { + query["instance_id.in"] = profileInstanceIds + } + + if param.InstanceName != "" { + query["instance_name.like"] = "%" + param.InstanceName + "%" + } + + if param.DeviceTypeID != "" { + query["device_type_id.in"] = strings.Split(param.DeviceTypeID, ",") + } + if param.Status != "" { + query["status.in"] = strings.Split(param.Status, ",") + } + + if param.IsInstallAgent != "" { + query["is_installed_agent"] = param.IsInstallAgent + } + + count, err := instanceDao.GetInstanceCount(logger, query) + if err != nil { + logger.Warnf("GetInstanceCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*instanceDao.Instance{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = instanceDao.GetMultiInstance(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = instanceDao.GetMultiInstance(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("QueryByInstanceIds GetAllInstance sql error:", err.Error()) + return nil, 0, err + } + + instances := []*responseTypes.Instance{} + for _, entity := range entityList { + instances = append(instances, InstanceEntity2Instance(logger, entity, nil)) //列表不用raidcan信息。。。。 + } + + return instances, count, nil +} + +func StartInstances(logger *log.Logger, instanceIds []string) error { + + instances, err := instanceDao.GetInstancesByIds(logger, instanceIds) + if err != nil { + logger.Warn("GetInstancesByIds sql error:", instanceIds, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + for _, instance := range instances { + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + //可以在此增加一些逻辑判断,比如,只能处在关机模式下才可以开机,其他状态不可以。。。后续再处理这块 + if instance.Status != instanceStatus.STOPPED { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是关机", instance.InstanceID), fmt.Sprintf("unsupported start instance %s", instance.InstanceID))) + } + } + + query := map[string]interface{}{ + "instance_id.in": instanceIds, + "is_del": 0, + } + updates := map[string]interface{}{ + "status": instanceStatus.STARTING, + "updatedBy": logger.GetPoint("username").(string), + } + if err := instanceDao.UpdateInstances(logger, query, updates); err != nil { + logger.Warn("StartInstance UpdateInstanceById sql error:", instanceIds, err.Error()) + return err + } + return sendStartInstanceEvent(logger, instanceIds) +} + +func StopInstances(logger *log.Logger, instanceIds []string) error { + + instances, err := instanceDao.GetInstancesByIds(logger, instanceIds) + if err != nil { + logger.Warn("GetInstancesByIds sql error:", instanceIds, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + for _, instance := range instances { + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + //可以在此增加一些逻辑判断,比如,只能处在关机模式下才可以开机,其他状态不可以。。。后续再处理这块 + if instance.Status != instanceStatus.RUNNING { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是运行中", instance.InstanceID), fmt.Sprintf("unsupported stop instance %s", instance.InstanceID))) + } + } + + query := map[string]interface{}{ + "instance_id.in": instanceIds, + "is_del": 0, + } + updates := map[string]interface{}{ + "status": instanceStatus.STOPPING, + "updatedBy": logger.GetPoint("username").(string), + } + if err := instanceDao.UpdateInstances(logger, query, updates); err != nil { + logger.Warn("StopInstance UpdateInstanceById sql error:", instanceIds, err.Error()) + return err + } + return sendStopInstanceEvent(logger, instanceIds) +} + +//logger里面的userid为当前操作用户的userId,拥有者和共享者都有权限操作 +func InstanceOwnedCheck(logger *log.Logger, instance *instanceDao.Instance) bool { + + userId := logger.GetPoint("userId").(string) + + u, err := userDao.GetUserById(logger, userId) + if err != nil { + logger.Warnf("InstanceOwnedCheck.GetUserById error, userid:%s, error:%s", userId, err.Error()) + return false + } + if u.RoleID == baseLogic.ROLE_ADMIN_UUID { //超级管理员有权限管理一切 + return true + } + + if instance == nil { + return false + } + if instance.UserID == userId { + return true + } + + q := map[string]interface{}{ + "project_id": instance.ProjectID, + "shared_user_id": userId, + "is_del": 0, + } + + sha, err := sharingProjectDao.GetAllShareProjects(logger, q) + if sha != nil && len(sha) != 0 { + return true + } + + return false + +} + +func RestartInstances(logger *log.Logger, instanceIds []string) error { + + instances, err := instanceDao.GetInstancesByIds(logger, instanceIds) + if err != nil { + logger.Warn("GetInstancesByIds sql error:", instanceIds, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + for _, instance := range instances { + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + //可以在此增加一些逻辑判断,比如,只能处在关机模式下才可以开机,其他状态不可以。。。后续再处理这块 + if instance.Status != instanceStatus.RUNNING { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是运行中", instance.InstanceID), fmt.Sprintf("unsupported restart instance %s", instance.InstanceID))) + } + } + + query := map[string]interface{}{ + "instance_id.in": instanceIds, + "is_del": 0, + } + updates := map[string]interface{}{ + "status": instanceStatus.RESTARTING, + "updatedBy": logger.GetPoint("username").(string), + } + if err := instanceDao.UpdateInstances(logger, query, updates); err != nil { + logger.Warn("restartInstances UpdateInstanceById sql error:", instanceIds, err.Error()) + return err + } + return sendRestartInstanceEvent(logger, instanceIds) +} + +func ResetInstancePasswd(logger *log.Logger, instance_id string, passwd string) error { + instance, err := instanceDao.GetInstanceById(logger, instance_id) + if err != nil { + return err + } + if instance.Status != instanceStatus.STOPPED { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是已关机", instance.InstanceID), fmt.Sprintf("unsupported reset password instance %s", instance.InstanceID))) + + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + instance.Status = instanceStatus.RESETTING_PASSWORD + instance.UpdatedBy = logger.GetPoint("username").(string) + instance.UpdatedTime = int(time.Now().Unix()) + if err := instanceDao.UpdateInstanceById(logger, instance); err != nil { + logger.Warn("UpdateInstanceById error:", instance_id, err.Error()) + return err + } + if err := resetPasswordSendMq(logger, instance_id, passwd, "ResetPassword"); err != nil { + return err + } + + return nil +} + +func ResetInstancesPasswd(logger *log.Logger, instanceIds []string, passwd string) error { + instanceEntities := []*instanceDao.Instance{} + for _, v := range instanceIds { + instance, err := instanceDao.GetInstanceById(logger, v) + if err != nil { + return err + } + if instance.Status != instanceStatus.STOPPED { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是已关机", instance.InstanceID), fmt.Sprintf("unsupported reset password instance %s", instance.InstanceID))) + + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + instanceEntities = append(instanceEntities, instance) + } + + query := map[string]interface{}{ + "instance_id.in": instanceIds, + "is_del": 0, + } + updates := map[string]interface{}{ + "status": instanceStatus.RESETTING_PASSWORD, + "updatedBy": logger.GetPoint("username").(string), + } + if err := instanceDao.UpdateInstances(logger, query, updates); err != nil { + logger.Warnf("resetInstancesPasswd UpdateInstances sql error, instanceIds:%s, error:%s", strings.Join(instanceIds, ","), err.Error()) + return err + } + for _, instanceId := range instanceIds { + if err := resetPasswordSendMq(logger, instanceId, passwd, "ResetPassword"); err != nil { + logger.Warnf("resetInstancesPasswd resetPasswordSendMq error, instanceId:%s, error:%s", instanceId, err.Error()) + } + } + return nil +} + +func resetPasswordSendMq(logger *log.Logger, instance_id, password, action string) error { + + logid := logger.GetPoint("logid").(string) + msg := rabbitIronicMsgApi.InstanceResetPasswordMessage{} + msg.ApiMessage.RequestId = logid + msg.InstanceId = instance_id + msg.Password = password + msg.Action = action + userId := logger.GetPoint("userId").(string) + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("convert InstanceResetPasswordMessage 2 event error:", instance_id, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warnf("resetPasswordSendMq SendToScheduler error, msg:%s, error:%s", util.ObjToJson(event), err.Error()) + return err + } else { + logger.Infof("resetPasswordSendMq SendToScheduler success, msg:%s", util.ObjToJson(event)) + } + return nil +} + +func ReinstallInstance(logger *log.Logger, instance_id string, param *requestTypes.ReinstallInstanceRequest) error { + + instance, _ := instanceDao.GetInstanceById(logger, instance_id) + if instance == nil || !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + if instance.Status != instanceStatus.STOPPED { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是已关机", instance.InstanceID), fmt.Sprintf("unsupported reset password instance %s", instance.InstanceID))) + } + + image_instance, _ := imageLogic.GetByImageId(logger, param.ImageID) + if image_instance == nil { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 所选镜像信息错误", instance.InstanceID), fmt.Sprintf("unsupported image for instance %s", instance.InstanceID))) + + } + + // if image_instance.Format == imageFormat.QCOW2 && image_param.Format != imageFormat.QCOW2 { + // //EMPTY + // } + device, err := deviceLogic.GetAndCheckById(logger, instance.DeviceID) + if err != nil { + return err + } + + q := requestTypes.QueryDeviceTypeImageRequest{ + DeviceTypeID: device.DeviceTypeID, + ImageID: param.ImageID, + } + p := util.Pageable{ + PageSize: 1, + } + imageE, _, _ := deviceTypeLogic.QueryDeviceTypeImage(logger, &q, p) + if imageE == nil { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 所选镜像和机型不匹配", instance.InstanceID), fmt.Sprintf("selected image and device_type not match for instance %s", instance.InstanceID))) + + } + instance.ImageID = param.ImageID + + var keep_data bool = true //默认保留数据 + + if param.SshKeyID != "" { + ssh, _ := sshkeyLogic.GetSshkeyById(logger, param.SshKeyID) + if ssh == nil { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 所选sshkey非法", instance.InstanceID), fmt.Sprintf("validated sshkey for instance %s", instance.InstanceID))) + + } + } + if param.HostName != "" { + instance.Hostname = param.HostName + } + if param.Password != "" { + param.SshKeyID = "" //如果设置了自定义密码,keypairId变为空 + } + if param.Password == "" && param.SshKeyID == "" { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 所选password和sshkey不能同时为空", instance.InstanceID), fmt.Sprintf("password and sshkey cannot both empty for instance %s", instance.InstanceID))) + + } + if param.BootMode != "" { + instance.BootMode = param.BootMode + } + // if param.SystemVolumeRaidID != "" { + // instance.SystemVolumeRaidID = param.SystemVolumeRaidID + // } + instance.Status = instanceStatus.REINSTALLING + instance.UpdatedTime = int(time.Now().Unix()) + if err := instanceDao.UpdateInstanceById(logger, instance); err != nil { + logger.Warn("UpdateInstanceById error:", instance_id, err.Error()) + return err + } + //释放销毁实例使用的sshkey资源 + if err := rInstanceSshkeyDao.DeleteInstanceSshkeyByInstanceID(logger, instance_id); err != nil { + logger.Warn("DeleteInstance ReinstallInstanceSshkeyByInstanceID sql error:", instance_id, err.Error()) + } + if param.SshKeyID != "" { + for _, sshkeyId := range strings.Split(param.SshKeyID, ",") { + sshkeyId = strings.TrimSpace(sshkeyId) + if sshkeyId == "" { + panic(constant.BuildInvalidArgumentWithArgs("秘钥ID不能为空", "sshkeyID is empty")) + } + _, err = rInstanceSshkeyDao.AddrInstanceSshkey(logger, &rInstanceSshkeyDao.RInstanceSshkey{ + InstanceID: instance_id, + SSHkeyID: sshkeyId, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + }) + if err != nil { + logger.Warnf("add r_instance_sshkey error, instance_id:%s, sshkeyId:%s, error:%s", instance_id, sshkeyId, err.Error()) + return err + } + } + } + saveInstancePartitions(logger, param, instance, device.DeviceTypeID) + userData := getInstanceUserData(logger, requestTypes.CreateInstanceRequest{}, param.InstallBmpAgent) + return sendReinstallInstanceEvent(logger, instance_id, keep_data, param.Password, userData) +} + +func sendReinstallInstanceEvent(logger *log.Logger, instance_id string, keep_data bool, password string, userData string) error { + + logid := logger.GetPoint("logid").(string) + msg := rabbitIronicMsgApi.ReinstallInstanceMessage{} + msg.ApiMessage.RequestId = logid + msg.InstanceId = instance_id + msg.KeepData = keep_data + msg.Password = password + msg.UserData = userData + userId := logger.GetPoint("userId").(string) + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("convert ReinstallInstanceMessage 2 event error:", instance_id, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warnf("sendReinstallInstanceEvent SendToScheduler error, msg:%s, error:%s", util.ObjToJson(event), err.Error()) + return err + } else { + logger.Infof("sendReinstallInstanceEvent SendToScheduler success, msg:%s", util.ObjToJson(event)) + } + return nil +} + +//针对重装的情况 +func saveInstancePartitions(logger *log.Logger, param *requestTypes.ReinstallInstanceRequest, instance *instanceDao.Instance, deviceTypeId string) error { + partitions, err := buildPartitions(logger, param, instance, deviceTypeId) + if err != nil { + logger.Warnf("buildPartitions %s error:%s", instance.InstanceID, err.Error()) + return err + } + for idx, v := range partitions { + v.InstancePartitionID = commonUtil.GetRandString("ipt-", namespacePrefix.IMAGE_ID_LENGTH, false, true, true) + v.Number = idx + 1 + partitions[idx] = v + } + + if err := instancePartitionDao.DeletePartitionsByInstanceId(logger, instance.InstanceID); err != nil { + logger.Warnf("DeletePartitionsByInstanceId %s error:%s", instance.InstanceID, err.Error()) + } + if len(partitions) > 0 { + if _, err := instancePartitionDao.AddMultiInstancePartition(logger, partitions); err != nil { + logger.Warnf("AddMultiInstancePartition error, partitions:%s, error:%s", util.ObjToJson(partitions), err.Error()) + return err + } + logger.Infof("AddMultiInstancePartition success, instanceId:%s", instance.InstanceID) + } + return nil +} + +func buildPartitions(logger *log.Logger, param *requestTypes.ReinstallInstanceRequest, instance *instanceDao.Instance, deviceTypeId string) ([]*instancePartitionDao.InstancePartition, error) { + if len(param.SystemPartition) == 0 && len(param.DataPartition) == 0 { + return nil, nil + } + image_partitions, err := rDeviceTypeImagePartitionDao.GetByDeviceTypeAndImageId(logger, deviceTypeId, param.ImageID) + if err != nil { + logger.Warn("buildPartitions.GetByDeviceTypeAndImageId error:", deviceTypeId, param.ImageID, err.Error()) + } + if len(image_partitions) == 0 { + return nil, nil + } + imagePartitionEntity := image_partitions[0] + partitions := []*instancePartitionDao.InstancePartition{} + if len(param.SystemPartition) > 0 { + for _, partition := range param.SystemPartition { + system_partition := PartitionInfo2Entity(partition) + system_partition.InstanceID = instance.InstanceID + system_partition.ImageID = instance.ImageID + system_partition.DeviceTypeID = deviceTypeId + system_partition.BootMode = imagePartitionEntity.BootMode + if strings.EqualFold(system_partition.PartitionMountPoint, "/") { + system_partition.PartitionType = "root" + } else if strings.EqualFold(system_partition.PartitionMountPoint, "/boot") { + system_partition.PartitionType = "boot" + } else { + system_partition.PartitionType = "system" + } + partitions = append(partitions, &system_partition) + } + } + + if len(param.DataPartition) > 0 { + for _, partition := range param.DataPartition { + data_partition := PartitionInfo2Entity(partition) + data_partition.InstanceID = instance.InstanceID + data_partition.ImageID = instance.ImageID + data_partition.DeviceTypeID = deviceTypeId + data_partition.BootMode = imagePartitionEntity.BootMode + data_partition.PartitionType = "data" + partitions = append(partitions, &data_partition) + } + } + + return partitions, nil + +} + +func PartitionInfo2Entity(param requestTypes.Partition) instancePartitionDao.InstancePartition { + res := instancePartitionDao.InstancePartition{ + PartitionSize: param.Size, + PartitionFsType: param.FsType, + PartitionMountPoint: param.MountPoint, + } + if strings.EqualFold(param.MountPoint, "/") { + res.PartitionLabel = "l_root" + } else if strings.EqualFold(param.MountPoint, "swap") { + res.PartitionLabel = "l_swap" + } else { + label := strings.Replace(param.MountPoint, "/", "l_", -1) + res.PartitionLabel = label + } + res.SystemDiskLabel = "gpt" + res.DataDiskLabel = "gpt" + return res +} + +func GetInstanceListByProjectIdAndOwnerNameAndSharerName(logger *log.Logger, param *requestTypes.DescribeInstancesByProjectIdAndOwnerNameAndSharerNameRequest) ([]*responseTypes.InstanceForShare, error) { + userId := logger.GetPoint("userId").(string) + + q := map[string]interface{}{ + "is_del": 0, + "project_id": param.ProjectID, + "user_id": userId, + } + + if param.InstanceName != "" { + q["instance_name.like"] = "%" + param.InstanceName + "%" + } + if param.InstanceID != "" { + q["instance_id.like"] = "%" + param.InstanceID + "%" + } + + //获取当前用户指定项目下的所有实例列表 + instanceEntities, _ := instanceDao.GetAllInstance(logger, q) + + sharerUser, _ := userLogic.GetUserByName(logger, &requestTypes.GetUserByNameRequest{ + UserName: param.SharerName, + }) + if sharerUser == nil { + return nil, errors.New("param sharerName invalided") + } + + var hasSharedInstanceIds []string + + sharesProject, _ := sharingProjectDao.GetOneSharingProject(logger, param.ProjectID, userId, sharerUser.UserID) + if sharesProject != nil { + tt := sharesProject.SharedInstanceIDs + hasSharedInstanceIds = strings.Split(tt, ",") + } else { //整个项目没有被共享过 + //empty + } + logger.Info("hasSharedInstanceIds is:", hasSharedInstanceIds) + // q2 := map[string]interface{}{ + // "project_id": param.ProjectID, + // "owner_user_id": userId, + // "is_del": 0, + // } + // sharesProjects, _ = sharingProjectDao.GetAllShareProjects(logger, q2) + // sharedids := []string{} + // for _, v := range sharesProjects { + // sharedids = append(sharedids, v.OwnerUserID, v.SharedUserID) + // } + + instances := InstanceEntitys2ShareInstances(instanceEntities, hasSharedInstanceIds) + return instances, nil +} + +func InstanceEntitys2ShareInstances(entitys []*instanceDao.Instance, hasSharedInstanceIds []string) []*responseTypes.InstanceForShare { + res1 := []*responseTypes.InstanceForShare{} //已共享 + res2 := []*responseTypes.InstanceForShare{} //未共享 + for _, entity := range entitys { + v := &responseTypes.InstanceForShare{ + InstanceID: entity.InstanceID, + InstanceName: entity.InstanceName, + } + if len(hasSharedInstanceIds) == 1 && hasSharedInstanceIds[0] == "" { + v.HasShared = false + } else { + if inArray(v.InstanceID, hasSharedInstanceIds) { + v.HasShared = true + } + } + if v.HasShared { + res1 = append(res1, v) + } else { + res2 = append(res2, v) + } + } + + res := append(res1, res2...) + + return res + +} + +func inArray(a string, arr []string) bool { + for _, v := range arr { + if v == a { + return true + } + } + return false +} diff --git a/bmp-openapi-console/logic/mailLogic/MailUtil.go b/bmp-openapi-console/logic/mailLogic/MailUtil.go new file mode 100644 index 0000000..b2e1fb6 --- /dev/null +++ b/bmp-openapi-console/logic/mailLogic/MailUtil.go @@ -0,0 +1,90 @@ +package mailLogic + +import ( + "bytes" + "crypto/tls" + "errors" + "html/template" + "strconv" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/mailDao" + log "coding.jd.com/aidc-bmp/bmp_log" + + "github.com/go-gomail/gomail" +) + +// SendMail use smtp to send mail +func SendMail(logger *log.Logger, subject, msg string, receivers string) error { + + mailEntity, err := mailDao.GetMailMessage(logger) + if err != nil { + logger.Warnf("SendMail.GetMail error:%s", err.Error()) + return err + } + tos := mailEntity.To + from := mailEntity.AdminAddr + smtpHost := mailEntity.ServerAddr + smtpPort, err := strconv.Atoi(mailEntity.ServerPort) + if err != nil { + logger.Warnf("SendMail.ServerPort invalid, port:%s", mailEntity.ServerPort) + return err + } + username := strings.Split(from, "@")[0] + password := mailEntity.AdminPass + + m := gomail.NewMessage() + + to := strings.Split(tos, ",") + if receivers != "" { //如果设置了收件人,就用设置的收件人,否则用系统收件人 + to = strings.Split(receivers, ",") + } + s := BaseSubjest + m.SetHeader("From", from) + m.SetHeader("To", to...) + m.SetHeader("Subject", s+":"+subject) + m.SetBody("text/html", msg) + + d := gomail.NewPlainDialer( + smtpHost, + smtpPort, + username, + password) + + if d == nil { + return errors.New("Initialize Dialer Error") + } + + d.TLSConfig = &tls.Config{ServerName: d.Host, InsecureSkipVerify: true} + + // Send the email. + if err := d.DialAndSend(m); err != nil { + logger.Warnf("SendMail msg=%s : %s\n", msg, err.Error()) + return err + } + return nil +} + +//SendMailByTpl send template mail +func SendMailByTpl(logger *log.Logger, tplName, subject string, obj interface{}, receivers string) error { + tpl, errParse := template.New("Mail").Parse(tplName) + if errParse != nil { + logger.Warnf("Parse Template Error:%s\n", errParse.Error()) + return errParse + } + + byteW := new(bytes.Buffer) + err := tpl.Execute(byteW, obj) + if err != nil { + logger.Warnf("Execute Template Error:%s\n", err.Error()) + return err + } + + errMail := SendMail(logger, subject, byteW.String(), receivers) + if errMail != nil { + logger.Warnf("Send Mail Error:%s\n", errMail.Error()) + return errMail + } + + return nil +} diff --git a/bmp-openapi-console/logic/mailLogic/template.go b/bmp-openapi-console/logic/mailLogic/template.go new file mode 100644 index 0000000..2c500a4 --- /dev/null +++ b/bmp-openapi-console/logic/mailLogic/template.go @@ -0,0 +1,129 @@ +package mailLogic + +const BaseSubjest string = "[BMP消息中心]" + +const MessageInBondAlertTemplate string = ` + + + + + + + + 报警消息 + + + +
+
+ BMP裸金属管理平台 +
+
+

尊敬的用户 {{.UserName}},您好!

+

+ 【监控报警】:默认机房 的实例{{.InstanceName}}/{{.InstanceID}}当前{{.MessageSubType}} - 告警值 {{.AlertValue}},持续时间:{{.AlertPeriod}}分钟,所属规则:{{.RuleName}},请您及时查看。 +

+
+ +
+ + +` + +type InbondAlertMailMessage struct { + MessageID string + SN string + MessageType string + MessageSubType string + ResourceType string + AlertTime string + AlertPeriod int + AlertValue string + Trigger string + UserID string + UserName string + InstanceID string + InstanceName string + Metric string + MetricName string + IsRecover int + RuleName string + RuleID string +} diff --git a/bmp-openapi-console/logic/messageLogic/messageLogic.go b/bmp-openapi-console/logic/messageLogic/messageLogic.go new file mode 100644 index 0000000..02b1150 --- /dev/null +++ b/bmp-openapi-console/logic/messageLogic/messageLogic.go @@ -0,0 +1,698 @@ +package messageLogic + +import ( + "errors" + "strconv" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/messageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/projectDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + messageType "git.jd.com/cps-golang/ironic-common/ironic/enums/MessageType" +) + +var Types2ShowEn = map[string]string{ + //操作消息 + messageType.MessageTypeOperation: "operation", + //系统消息 + messageType.MessageTypeSystem: "system", + //监控消息 + messageType.MessageTypeOobMonitor: "oob-monitor", + //带内报警消息 + messageType.MessageTypeInBondAlert: "inbond-alert", + //操作消息类型 + messageType.MessageSubTypeCollectHardwareInfo: "CollectHardwareInfo", + messageType.MessageSubTypeCreateDevices: "CreateDevices", + messageType.MessageSubTypeCreateInstances: "CreateInstances", + messageType.MessageSubTypeCutDeviceStock: "CutDeviceStock", + messageType.MessageSubTypeDeleteInstance: "DeleteInstance", + messageType.MessageSubTypeInstanceResetPassword: "InstanceResetPassword", + messageType.MessageSubTypePutawayDevice: "PutawayDevice", + messageType.MessageSubTypeReinstallInstance: "ReinstallInstance", + messageType.MessageSubTypeRestartInstances: "RestartInstances", + messageType.MessageSubTypeStartInstances: "StartInstances", + messageType.MessageSubTypeStopInstances: "StopInstances", + //系统消息类型 + messageType.MessageSubTypeLicenseNearTimeout: "LicenseNearTimeout", + //监控消息类型 + messageType.MessageSubTypePowerFault: "Power Fault", + messageType.MessageSubTypeTemperatureFault: "Temp Fault", + messageType.MessageSubTypeCPUFault: "CPU Fault", + messageType.MessageSubTypeMemFault: "Mem Fault", + messageType.MessageSubTypeDiskFault: "Disk Fault", + messageType.MessageSubTypeOtherFault: "Other Fault", + + //带内告警 + messageType.MessageSubTypeCPUUsage: "CPU Usage", + messageType.MessageSubTypeMemoryUsage: "Memory Usage", + messageType.MessageSubTypeMemoryUsed: "Memory Used", + messageType.MessageSubTypeDiskUsed: "Disk Used", + messageType.MessageSubTypeDiskUsage: "Disk Usage", + messageType.MessageSubTypeDiskReadTraffic: "Disk Read Traffic", + messageType.MessageSubTypeDiskWriteTraffic: "Disk Write Traffic", + messageType.MessageSubTypeDiskReadIOPS: "Disk Read IOPS", + messageType.MessageSubTypeDiskWriteIOPS: "Disk Write IOPS", + messageType.MessageSubTypeNetworkIngressTraffic: "Network Ingress Traffic", + messageType.MessageSubTypeNetworkEgressTraffic: "Network Egress Traffic", + messageType.MessageSubTypeNetworkIngressPackets: "Network Ingress Packets", + messageType.MessageSubTypeNetworkEgressPackets: "Network Egress Packets", + messageType.MessageSubTypeLoadAverage1min: "Load Average 1min", + messageType.MessageSubTypeLoadAverage5min: "Load Average 5min", + messageType.MessageSubTypeLoadAverage15min: "Load Average 15min", + messageType.MessageSubTypeTotalTCPConnections: "Total TCP Connections", + messageType.MessageSubTypeEstablishedTCPConnections: "Established TCP Connections", + messageType.MessageSubTypeTotalProcessCount: "Total Process Count", +} + +var Types2ShowZh = map[string]string{ + //操作消息 + messageType.MessageTypeOperation: "操作消息", + //系统消息 + messageType.MessageTypeSystem: "系统消息", + //监控消息 + messageType.MessageTypeOobMonitor: "故障消息", + //带内告警消息 + messageType.MessageTypeInBondAlert: "报警消息", + + //操作消息类型 + messageType.MessageSubTypeCollectHardwareInfo: "采集", + messageType.MessageSubTypeCreateDevices: "上传设备", + messageType.MessageSubTypeCreateInstances: "创建实例", + messageType.MessageSubTypeCutDeviceStock: "削减库存", + messageType.MessageSubTypeDeleteInstance: "删除实例", + messageType.MessageSubTypeInstanceResetPassword: "重置密码", + messageType.MessageSubTypePutawayDevice: "设备上架", + messageType.MessageSubTypeReinstallInstance: "重装系统", + messageType.MessageSubTypeRestartInstances: "重启实例", + messageType.MessageSubTypeStartInstances: "开机", + messageType.MessageSubTypeStopInstances: "关机", + //系统消息类型 + messageType.MessageSubTypeLicenseNearTimeout: "许可证到期提醒", + //监控消息类型 + messageType.MessageSubTypePowerFault: "电力故障", + messageType.MessageSubTypeTemperatureFault: "温控故障", + messageType.MessageSubTypeCPUFault: "CPU故障", + messageType.MessageSubTypeMemFault: "内存故障", + messageType.MessageSubTypeDiskFault: "硬盘故障", + messageType.MessageSubTypeOtherFault: "其他故障", + + //带内告警 + messageType.MessageSubTypeCPUUsage: "CPU使用率", + messageType.MessageSubTypeMemoryUsage: "内存使用率", + messageType.MessageSubTypeMemoryUsed: "内存使用量", + messageType.MessageSubTypeDiskUsed: "磁盘使用量", + messageType.MessageSubTypeDiskUsage: "磁盘使用率", + messageType.MessageSubTypeDiskReadTraffic: "磁盘读流量", + messageType.MessageSubTypeDiskWriteTraffic: "磁盘写流量", + messageType.MessageSubTypeDiskReadIOPS: "磁盘读IOPS", + messageType.MessageSubTypeDiskWriteIOPS: "磁盘写IOPS", + messageType.MessageSubTypeNetworkIngressTraffic: "网卡进流量", + messageType.MessageSubTypeNetworkEgressTraffic: "网卡出流量", + messageType.MessageSubTypeNetworkIngressPackets: "网络进包数量", + messageType.MessageSubTypeNetworkEgressPackets: "网络出包数量", + messageType.MessageSubTypeLoadAverage1min: "平均负载均衡1min", + messageType.MessageSubTypeLoadAverage5min: "平均负载均衡5min", + messageType.MessageSubTypeLoadAverage15min: "平均负载均衡15min", + messageType.MessageSubTypeTotalTCPConnections: "TCP总连接数", + messageType.MessageSubTypeEstablishedTCPConnections: "TCP正常接数", + messageType.MessageSubTypeTotalProcessCount: "总进程数", +} + +var ShowEn2Types = map[string]string{ + //操作消息 + "operation": messageType.MessageTypeOperation, + //系统消息 + "system": messageType.MessageTypeSystem, + //监控消息 + "oob-monitor": messageType.MessageTypeOobMonitor, + //带内告警消息 + "inbond-alert": messageType.MessageTypeInBondAlert, + + //操作消息类型 + "CollectHardwareInfo": messageType.MessageSubTypeCollectHardwareInfo, + "CreateDevices": messageType.MessageSubTypeCreateDevices, + "CreateInstances": messageType.MessageSubTypeCreateInstances, + "CutDeviceStock": messageType.MessageSubTypeCutDeviceStock, + "DeleteInstance": messageType.MessageSubTypeDeleteInstance, + "InstanceResetPassword": messageType.MessageSubTypeInstanceResetPassword, + "PutawayDevice": messageType.MessageSubTypePutawayDevice, + "ReinstallInstance": messageType.MessageSubTypeReinstallInstance, + "RestartInstances": messageType.MessageSubTypeRestartInstances, + "StartInstances": messageType.MessageSubTypeStartInstances, + "StopInstances": messageType.MessageSubTypeStopInstances, + //系统消息类型 + "LicenseNearTimeout": messageType.MessageSubTypeLicenseNearTimeout, + //监控消息类型 + "Power Fault": messageType.MessageSubTypePowerFault, + "Temp Fault": messageType.MessageSubTypeTemperatureFault, + "CPU Fault": messageType.MessageSubTypeCPUFault, + "Mem Fault": messageType.MessageSubTypeMemFault, + "Disk Fault": messageType.MessageSubTypeDiskFault, + "Other Fault": messageType.MessageSubTypeOtherFault, + //带内监控告警 + "CPU Usage": messageType.MessageSubTypeCPUUsage, + "Memory Usage": messageType.MessageSubTypeMemoryUsage, + "Memory Used": messageType.MessageSubTypeMemoryUsed, + "Disk Used": messageType.MessageSubTypeDiskUsed, + "Disk Usage": messageType.MessageSubTypeDiskUsage, + "Disk Read Traffic": messageType.MessageSubTypeDiskReadTraffic, + "Disk Write Traffic": messageType.MessageSubTypeDiskWriteTraffic, + "Disk Read IOPS": messageType.MessageSubTypeDiskReadIOPS, + "Disk Write IOPS": messageType.MessageSubTypeDiskWriteIOPS, + "Network Ingress Traffic": messageType.MessageSubTypeNetworkIngressTraffic, + "Network Egress Traffic": messageType.MessageSubTypeNetworkEgressTraffic, + "Network Ingress Packets": messageType.MessageSubTypeNetworkIngressPackets, + "Network Egress Packets": messageType.MessageSubTypeNetworkEgressPackets, + "Load Average 1min": messageType.MessageSubTypeLoadAverage1min, + "Load Average 5min": messageType.MessageSubTypeLoadAverage5min, + "Load Average 15min": messageType.MessageSubTypeLoadAverage15min, + "Total TCP Connections": messageType.MessageSubTypeTotalTCPConnections, + "Established TCP Connections": messageType.MessageSubTypeEstablishedTCPConnections, + "Total Process Count": messageType.MessageSubTypeTotalProcessCount, +} + +var ShowZh2Types = map[string]string{ + //操作消息 + "操作消息": messageType.MessageTypeOperation, + //系统消息 + "系统消息": messageType.MessageTypeSystem, + //监控消息 + "故障消息": messageType.MessageTypeOobMonitor, + //带内告警消息 + "报警消息": messageType.MessageTypeInBondAlert, + + //操作消息类型 + "采集": messageType.MessageSubTypeCollectHardwareInfo, + "上传设备": messageType.MessageSubTypeCreateDevices, + "创建实例": messageType.MessageSubTypeCreateInstances, + "削减库存": messageType.MessageSubTypeCutDeviceStock, + "删除实例": messageType.MessageSubTypeDeleteInstance, + "重置密码": messageType.MessageSubTypeInstanceResetPassword, + "设备上架": messageType.MessageSubTypePutawayDevice, + "重装系统": messageType.MessageSubTypeReinstallInstance, + "重启实例": messageType.MessageSubTypeRestartInstances, + "开机": messageType.MessageSubTypeStartInstances, + "关机": messageType.MessageSubTypeStopInstances, + //系统消息类型 + "许可证到期提醒": messageType.MessageSubTypeLicenseNearTimeout, + //监控消息类型 + "电力故障": messageType.MessageSubTypePowerFault, + "温控故障": messageType.MessageSubTypeTemperatureFault, + "CPU故障": messageType.MessageSubTypeCPUFault, + "内存故障": messageType.MessageSubTypeMemFault, + "硬盘故障": messageType.MessageSubTypeDiskFault, + "其他故障": messageType.MessageSubTypeOtherFault, + + //带内告警 + "CPU使用率": messageType.MessageSubTypeCPUUsage, + "内存使用率": messageType.MessageSubTypeMemoryUsage, + "内存使用量": messageType.MessageSubTypeMemoryUsed, + "磁盘使用量": messageType.MessageSubTypeDiskUsed, + "磁盘使用率": messageType.MessageSubTypeDiskUsage, + "磁盘读流量": messageType.MessageSubTypeDiskReadTraffic, + "磁盘写流量": messageType.MessageSubTypeDiskWriteTraffic, + "磁盘读IOPS": messageType.MessageSubTypeDiskReadIOPS, + "磁盘写IOPS": messageType.MessageSubTypeDiskWriteIOPS, + "网卡进流量": messageType.MessageSubTypeNetworkIngressTraffic, + "网卡出流量": messageType.MessageSubTypeNetworkEgressTraffic, + "网络进包数量": messageType.MessageSubTypeNetworkIngressPackets, + "网络出包数量": messageType.MessageSubTypeNetworkEgressPackets, + "平均负载均衡1min": messageType.MessageSubTypeLoadAverage1min, + "平均负载均衡5min": messageType.MessageSubTypeLoadAverage5min, + "平均负载均衡15min": messageType.MessageSubTypeLoadAverage15min, + "TCP总连接数": messageType.MessageSubTypeTotalTCPConnections, + "TCP正常接数": messageType.MessageSubTypeEstablishedTCPConnections, + "总进程数": messageType.MessageSubTypeTotalProcessCount, +} + +var IncludeMessagetypes []string = []string{ + + messageType.MessageSubTypeCreateInstances, + + messageType.MessageSubTypeDeleteInstance, + messageType.MessageSubTypeInstanceResetPassword, + messageType.MessageSubTypeReinstallInstance, + messageType.MessageSubTypeRestartInstances, + messageType.MessageSubTypeStartInstances, + messageType.MessageSubTypeStopInstances, + messageType.MessageSubTypePowerFault, + messageType.MessageSubTypeTemperatureFault, + messageType.MessageSubTypeCPUFault, + messageType.MessageSubTypeMemFault, + messageType.MessageSubTypeDiskFault, + messageType.MessageSubTypeOtherFault, + + messageType.MessageSubTypeCPUUsage, + messageType.MessageSubTypeMemoryUsed, + messageType.MessageSubTypeMemoryUsage, + messageType.MessageSubTypeDiskUsed, + messageType.MessageSubTypeDiskUsage, + messageType.MessageSubTypeDiskReadTraffic, + messageType.MessageSubTypeDiskWriteTraffic, + messageType.MessageSubTypeDiskReadIOPS, + messageType.MessageSubTypeDiskWriteIOPS, + messageType.MessageSubTypeNetworkIngressTraffic, + messageType.MessageSubTypeNetworkEgressTraffic, + messageType.MessageSubTypeNetworkIngressPackets, + messageType.MessageSubTypeNetworkEgressPackets, + messageType.MessageSubTypeLoadAverage1min, + messageType.MessageSubTypeLoadAverage5min, + messageType.MessageSubTypeLoadAverage15min, + messageType.MessageSubTypeTotalTCPConnections, + messageType.MessageSubTypeEstablishedTCPConnections, + messageType.MessageSubTypeTotalProcessCount, +} + +func MessageEntity2Message(logger *log.Logger, msgEntity *messageDao.WebMessage, isDetail bool) *response.Message { + if msgEntity == nil { + return nil + } + res := &response.Message{ + WebMessage: *msgEntity, + } + + if isDetail { + + if msgEntity.InstanceID != "" { + instanceEntity, err := instanceDao.GetInstanceById(logger, msgEntity.InstanceID) + if err != nil { + logger.Warnf("MessageEntity2Message.GetInstanceById error, instanceId:%s, error:%s", msgEntity.InstanceID, err.Error()) + } else { + res.IDcID = instanceEntity.IDcID + res.DeviceID = instanceEntity.DeviceID + idcEntity, err := idcDao.GetIdcById(logger, instanceEntity.IDcID) + if err != nil { + logger.Warnf("MessageEntity2Message.GetIdcById error, idcId:%s, error:%s", instanceEntity.IDcID, err.Error()) + } else { + res.IDcName = idcEntity.Name + if logger.GetPoint("language").(string) == baseLogic.EN_US { + res.IDcName = idcEntity.NameEn + } + } + res.ProjectID = instanceEntity.ProjectID + projectEntity, err := projectDao.GetProjectById(logger, instanceEntity.ProjectID) + if err != nil { + logger.Warnf("MessageEntity2Message.GetProjectById error, ProjectId:%s, error:%s", instanceEntity.ProjectID, err.Error()) + } else { + res.ProjectName = projectEntity.ProjectName + } + } + } else if msgEntity.SN != "" { + deviceEntity, err := deviceDao.GetDeviceBySn(logger, msgEntity.SN) + if err != nil { + logger.Warnf("MessageEntity2Message.GetDeviceBySn error, sn:%s, error:%s", msgEntity.SN, err.Error()) + } else { + res.IDcID = deviceEntity.IDcID + res.DeviceID = deviceEntity.DeviceID + idcEntity, err := idcDao.GetIdcById(logger, deviceEntity.IDcID) + if err != nil { + logger.Warnf("MessageEntity2Message.GetIdcById error, idcId:%s, error:%s", deviceEntity.IDcID, err.Error()) + } else { + res.IDcName = idcEntity.Name + if logger.GetPoint("language").(string) == baseLogic.EN_US { + res.IDcName = idcEntity.NameEn + } + } + + } + } + + } + return res + +} + +func HasUnreadMessage(logger *log.Logger) (bool, error) { + userId := logger.GetPoint("userId").(string) + q := map[string]interface{}{ + "is_del": 0, + "user_id": userId, + "has_read": 0, + } + cnt, err := messageDao.GetWebMessagesByUserIdCount(logger, q) + if err != nil { + logger.Warnf("HasUnreadMessage.GetWebMessagesByUserIdCount error, userid:%s, error:%s", userId, err.Error()) + return false, err + } + return cnt != 0, nil +} + +func GetPageMessages(logger *log.Logger, param *requestTypes.QueryMessagesRequest, p util.Pageable) ([]*response.Message, int64, error) { + + userId := logger.GetPoint("userId").(string) + offset, limit := p.Pageable2offset() + + q := map[string]interface{}{ + "is_del": 0, + "user_id": userId, + } + if param.HasRead != "" { + r, err := strconv.Atoi(param.HasRead) + if err != nil { + logger.Warnf("GetPageMessages.HasRead param error, user_id:%s, error:%s", userId, err.Error()) + return nil, 0, errors.New("param hasRead error") + } + q["has_read"] = r + } + if param.MessageType != "" { + mt := ShowEn2Types[param.MessageType] + if mt == "" { + mt = ShowZh2Types[param.MessageType] + } + if mt == "" { + mt = param.MessageType + } + q["message_type"] = mt + } + if param.MessageSubType != "" { + mts := []string{} + items := strings.Split(param.MessageSubType, ",") + for _, item := range items { + mt := ShowEn2Types[item] + if mt == "" { + mt = ShowZh2Types[item] + } + if mt == "" { + mt = item + } + mts = append(mts, mt) + } + + q["message_sub_type.in"] = mts + } else { + q["message_sub_type.in"] = IncludeMessagetypes + } + + if param.Detail != "" { + q["detail.like"] = "%" + strings.TrimSpace(param.Detail) + "%" + } + cnt, err := messageDao.GetWebMessagesByUserIdCount(logger, q) + if err != nil { + logger.Warnf("GetPageMessages.GetWebMessagesByUserIdCount error, user_id:%s, error:%s", userId, err.Error()) + return nil, 0, err + } + + var entityList []*messageDao.WebMessage + if param.IsAll == baseLogic.IS_ALL { + entityList, err = messageDao.GetMultiWebMessagesByUserId(logger, q, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = messageDao.GetMultiWebMessagesByUserId(logger, q, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("GetPageMessages GetMultiWebMessagesByUserId sql error:", err.Error()) + return nil, 0, err + } + res := []*response.Message{} + for _, v := range entityList { + var mt, mst string + if logger.GetPoint("language").(string) == baseLogic.EN_US { + mt = Types2ShowEn[v.MessageType] + mst = Types2ShowEn[v.MessageSubType] + } else { + mt = Types2ShowZh[v.MessageType] + mst = Types2ShowZh[v.MessageSubType] + } + if mt == "" { + mt = v.MessageType + } + if mst == "" { + mst = v.MessageSubType + } + v.MessageType = mt + v.MessageSubType = mst + v.FaultType = v.MessageSubType + res = append(res, MessageEntity2Message(logger, v, false)) + } + + return res, cnt, nil + +} + +func GetMessageStatistic(logger *log.Logger) (int64, int64, error) { + + userId := logger.GetPoint("userId").(string) + + q1 := map[string]interface{}{ + "is_del": 0, + "user_id": userId, + "message_sub_type.in": IncludeMessagetypes, + } + q2 := map[string]interface{}{ + "is_del": 0, + "user_id": userId, + "has_read": 0, + "message_sub_type.in": IncludeMessagetypes, + } + + all, err := messageDao.GetWebMessagesByUserIdCount(logger, q1) + if err != nil { + logger.Warnf("GetMessageStatistic.GetWebMessagesByUserIdCount error, user_id:%s, error:%s", userId, err.Error()) + return 0, 0, err + } + unread, err := messageDao.GetWebMessagesByUserIdCount(logger, q2) + if err != nil { + logger.Warnf("GetMessageStatistic.GetWebMessagesByUserIdCount error, user_id:%s, error:%s", userId, err.Error()) + return 0, 0, err + } + return all, unread, nil + +} + +func ReadMessages(logger *log.Logger, param *requestTypes.ReadMessagesRequest) (bool, error) { + userId := logger.GetPoint("userId").(string) + //校验messages和userid的归属关系 + q := map[string]interface{}{ + "is_del": 0, + "user_id": userId, + "message_id.in": param.MessageIds, + } + + msgs, err := messageDao.GetAllWebMessages(logger, q) + if err != nil { + logger.Warnf("ReadMessages.GetAllWebMessages error, query:%v, error:%s", q, err.Error()) + } + if len(msgs) < len(param.MessageIds) { + logger.Warnf("ReadMessages.message_ids invalided, user_id:%s, message_ids:%s", userId, param.MessageIds) + panic(constant.BuildInvalidArgumentWithArgs("参数messageIds非法", "param messageIds invalid")) + } + + u := map[string]interface{}{ + "has_read": 1, + } + if err := messageDao.UpdateWebMessages(logger, q, u); err != nil { + logger.Warnf("ReadMessages.UpdateWebMessages error, query:%v, error:%s", q, err.Error()) + return false, err + } + return true, nil +} + +func GetMessageById(logger *log.Logger, param *requestTypes.GetMessageByIdRequest) (*response.Message, string, string, error) { + + var nextMessageId, prevMessageId string + + userId := logger.GetPoint("userId").(string) + //校验messages和userid的归属关系 + q := map[string]interface{}{ + "is_del": 0, + "user_id": userId, + "message_id": param.MessageID, + } + + msg, err := messageDao.GetOneWebMessage(logger, q, "asc") + if err != nil { + logger.Warnf("GetOneMoreMessage.GetOneWebMessage error, user_id:%s, message_id:%s, error:%s", userId, param.MessageID, err.Error()) + return nil, "", "", err + } + if msg != nil { + + if logger.GetPoint("language").(string) == baseLogic.EN_US { + msg.MessageType = Types2ShowEn[msg.MessageType] + msg.MessageSubType = Types2ShowEn[msg.MessageSubType] + } else { + msg.MessageType = Types2ShowZh[msg.MessageType] + msg.MessageSubType = Types2ShowZh[msg.MessageSubType] + } + msg.FaultType = msg.MessageSubType + if msg.UserName == "" { + msg.UserName = "admin" + } + + mid := msg.ID + nextQ := map[string]interface{}{ + "is_del": 0, + "user_id": userId, + "id.gt": mid, + } + nextMsg, err := messageDao.GetOneWebMessage(logger, nextQ, "asc") + if err != nil { + logger.Warnf("GetOneMoreMessage.getNextmsg error:%s", err.Error()) + } + + prevQ := map[string]interface{}{ + "is_del": 0, + "user_id": userId, + "id.lt": mid, + } + prevMsg, err := messageDao.GetOneWebMessage(logger, prevQ, "desc") + if err != nil { + logger.Warnf("GetOneMoreMessage.getPrevmsg error:%s", err.Error()) + } + + if nextMsg != nil { + nextMessageId = nextMsg.MessageID + } + if prevMsg != nil { + prevMessageId = prevMsg.MessageID + } + return MessageEntity2Message(logger, msg, true), nextMessageId, prevMessageId, nil + + } + return nil, "", "", nil + +} + +func GetMessageTypes(logger *log.Logger) response.MessageTypesResp { + if logger.GetPoint("language").(string) == baseLogic.EN_US { + return response.MessageTypesResp{ + Types2ShowEn[messageType.MessageTypeOperation]: []string{ + // Types2ShowEn[messageType.MessageSubTypeCollectHardwareInfo], + // Types2ShowEn[messageType.MessageSubTypeCreateDevices], + Types2ShowEn[messageType.MessageSubTypeCreateInstances], + // Types2ShowEn[messageType.MessageSubTypeCutDeviceStock], + Types2ShowEn[messageType.MessageSubTypeDeleteInstance], + Types2ShowEn[messageType.MessageSubTypeInstanceResetPassword], + // Types2ShowEn[messageType.MessageSubTypePutawayDevice], + Types2ShowEn[messageType.MessageSubTypeReinstallInstance], + Types2ShowEn[messageType.MessageSubTypeRestartInstances], + Types2ShowEn[messageType.MessageSubTypeStartInstances], + Types2ShowEn[messageType.MessageSubTypeStopInstances], + }, + // Types2ShowEn[messageType.MessageTypeSystem]: []string{ + // Types2ShowEn[messageType.MessageSubTypeLicenseNearTimeout], + // }, + Types2ShowEn[messageType.MessageTypeOobMonitor]: []string{ + Types2ShowEn[messageType.MessageSubTypePowerFault], + Types2ShowEn[messageType.MessageSubTypeTemperatureFault], + Types2ShowEn[messageType.MessageSubTypeCPUFault], + Types2ShowEn[messageType.MessageSubTypeMemFault], + Types2ShowEn[messageType.MessageSubTypeDiskFault], + Types2ShowEn[messageType.MessageSubTypeOtherFault], + }, + Types2ShowEn[messageType.MessageTypeInBondAlert]: []string{ + Types2ShowEn[messageType.MessageSubTypeCPUUsage], + Types2ShowEn[messageType.MessageSubTypeMemoryUsed], + Types2ShowEn[messageType.MessageSubTypeDiskUsed], + Types2ShowEn[messageType.MessageSubTypeDiskUsage], + Types2ShowEn[messageType.MessageSubTypeDiskReadTraffic], + Types2ShowEn[messageType.MessageSubTypeDiskWriteTraffic], + Types2ShowEn[messageType.MessageSubTypeDiskReadIOPS], + Types2ShowEn[messageType.MessageSubTypeDiskWriteIOPS], + Types2ShowEn[messageType.MessageSubTypeNetworkIngressTraffic], + Types2ShowEn[messageType.MessageSubTypeNetworkEgressTraffic], + Types2ShowEn[messageType.MessageSubTypeNetworkIngressPackets], + Types2ShowEn[messageType.MessageSubTypeNetworkEgressPackets], + Types2ShowEn[messageType.MessageSubTypeLoadAverage1min], + Types2ShowEn[messageType.MessageSubTypeLoadAverage5min], + Types2ShowEn[messageType.MessageSubTypeLoadAverage15min], + Types2ShowEn[messageType.MessageSubTypeTotalTCPConnections], + Types2ShowEn[messageType.MessageSubTypeEstablishedTCPConnections], + Types2ShowEn[messageType.MessageSubTypeTotalProcessCount], + }, + } + } else { + return response.MessageTypesResp{ + Types2ShowZh[messageType.MessageTypeOperation]: []string{ + // Types2ShowZh[messageType.MessageSubTypeCollectHardwareInfo], + // Types2ShowZh[messageType.MessageSubTypeCreateDevices], + Types2ShowZh[messageType.MessageSubTypeCreateInstances], + // Types2ShowZh[messageType.MessageSubTypeCutDeviceStock], + Types2ShowZh[messageType.MessageSubTypeDeleteInstance], + Types2ShowZh[messageType.MessageSubTypeInstanceResetPassword], + // Types2ShowZh[messageType.MessageSubTypePutawayDevice], + Types2ShowZh[messageType.MessageSubTypeReinstallInstance], + Types2ShowZh[messageType.MessageSubTypeRestartInstances], + Types2ShowZh[messageType.MessageSubTypeStartInstances], + Types2ShowZh[messageType.MessageSubTypeStopInstances], + }, + // Types2ShowZh[messageType.MessageTypeSystem]: []string{ + // Types2ShowZh[messageType.MessageSubTypeLicenseNearTimeout], + // }, + Types2ShowZh[messageType.MessageTypeOobMonitor]: []string{ + Types2ShowZh[messageType.MessageSubTypePowerFault], + Types2ShowZh[messageType.MessageSubTypeTemperatureFault], + Types2ShowZh[messageType.MessageSubTypeCPUFault], + Types2ShowZh[messageType.MessageSubTypeMemFault], + Types2ShowZh[messageType.MessageSubTypeDiskFault], + Types2ShowZh[messageType.MessageSubTypeOtherFault], + }, + Types2ShowZh[messageType.MessageTypeInBondAlert]: []string{ + Types2ShowZh[messageType.MessageSubTypeCPUUsage], + Types2ShowZh[messageType.MessageSubTypeMemoryUsed], + Types2ShowZh[messageType.MessageSubTypeDiskUsed], + Types2ShowZh[messageType.MessageSubTypeDiskUsage], + Types2ShowZh[messageType.MessageSubTypeDiskReadTraffic], + Types2ShowZh[messageType.MessageSubTypeDiskWriteTraffic], + Types2ShowZh[messageType.MessageSubTypeDiskReadIOPS], + Types2ShowZh[messageType.MessageSubTypeDiskWriteIOPS], + Types2ShowZh[messageType.MessageSubTypeNetworkIngressTraffic], + Types2ShowZh[messageType.MessageSubTypeNetworkEgressTraffic], + Types2ShowZh[messageType.MessageSubTypeNetworkIngressPackets], + Types2ShowZh[messageType.MessageSubTypeNetworkEgressPackets], + Types2ShowZh[messageType.MessageSubTypeLoadAverage1min], + Types2ShowZh[messageType.MessageSubTypeLoadAverage5min], + Types2ShowZh[messageType.MessageSubTypeLoadAverage15min], + Types2ShowZh[messageType.MessageSubTypeTotalTCPConnections], + Types2ShowZh[messageType.MessageSubTypeEstablishedTCPConnections], + Types2ShowZh[messageType.MessageSubTypeTotalProcessCount], + }, + } + } + +} + +func DeleteMessages(logger *log.Logger, param *requestTypes.DeleteMessagesRequest) (bool, error) { + userId := logger.GetPoint("userId").(string) + //校验messages和userid的归属关系 + q := map[string]interface{}{ + "is_del": 0, + "user_id": userId, + "message_id.in": param.MessageIds, + } + + msgs, err := messageDao.GetAllWebMessages(logger, q) + if err != nil { + logger.Warnf("DeleteMessages.GetAllWebMessages error, query:%v, error:%s", q, err.Error()) + } + if len(msgs) < len(param.MessageIds) { + logger.Warnf("DeleteMessages.message_ids invalided, user_id:%s, message_ids:%s", userId, param.MessageIds) + panic(constant.BuildInvalidArgumentWithArgs("参数messageIds非法", "param messageIds invalid")) + } + + u := map[string]interface{}{ + "is_del": 1, + } + if err := messageDao.UpdateWebMessages(logger, q, u); err != nil { + logger.Warnf("DeleteMessages.UpdateWebMessages error, query:%v, error:%s", q, err.Error()) + return false, err + } + return true, nil +} + +func AddWebMessage(logger *log.Logger, webMsg *messageDao.WebMessage) error { + + if _, err := messageDao.AddWebMessage(logger, webMsg); err != nil { + logger.Warnf("AddWebMessage error, msg:%s, error:%s", util.InterfaceToJson(webMsg), err.Error()) + return err + } + logger.Infof("AddWebMessage success, msg:%s", util.InterfaceToJson(webMsg)) + return nil + +} diff --git a/bmp-openapi-console/logic/monitorAlertLogic/monitorAlertLogic.go b/bmp-openapi-console/logic/monitorAlertLogic/monitorAlertLogic.go new file mode 100644 index 0000000..f774f25 --- /dev/null +++ b/bmp-openapi-console/logic/monitorAlertLogic/monitorAlertLogic.go @@ -0,0 +1,416 @@ +package monitorAlertLogic + +import ( + "encoding/json" + "fmt" + "net/url" + "strconv" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/messageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/monitorAlertDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/monitorRuleDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/mailLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/messageLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorRuleLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + messageType "git.jd.com/cps-golang/ironic-common/ironic/enums/MessageType" +) + +func AlertEntity2Alert(logger *log.Logger, entity *monitorAlertDao.MonitorAlerts, isDetail bool) *response.Alert { + + rt := &response.RuleTrigger{} + if err := json.Unmarshal([]byte(entity.Trigger), rt); err != nil { + logger.Warnf("AlertEntity2Alert unmarshal Trigger error, value:%s, error:%s", entity.Trigger, err.Error()) + return nil + } + + res := &response.Alert{ + AlertID: entity.AlertID, + AlertTime: int64(entity.AlertTime), + Resource: entity.Resource, + // 资源id,目前就是实例id + ResourceID: entity.ResourceID, + // 资源名称,目前就是实例名称 + ResourceName: entity.ResourceName, + // 触发条件,接口需要翻译 + Trigger: entity.Trigger, + TriggerDescription: monitorRuleLogic.Trigger2Description(logger, rt), + // 报警值 + AlertValue: entity.AlertValue + entity.CalculationUnit, + // 1表示一般,2表示严重,3表示紧急 + AlertLevel: int64(entity.AlertLevel), + // 告警持续时间(分钟为单位) + AlertPeriod: int64(entity.AlertPeriod), + // 通知对象 userid + UserID: entity.UserID, + // 通知对象 用户名 + UserName: entity.UserName, + // 创建时间戳 + CreatedTime: int64(entity.CreatedTime), + } + + if logger.GetPoint("language").(string) != baseLogic.EN_US { + //TODO trans trigger\level ... + res.Resource = monitorRuleLogic.ResourceMapZh[entity.Resource] + res.AlertLevelDescription = monitorRuleLogic.RuleAlertLevelMapZh[res.AlertLevel] + } else { + + res.AlertLevelDescription = monitorRuleLogic.RuleAlertLevelMapEn[res.AlertLevel] + } + if isDetail { + ruleEntity, err := monitorRuleDao.GetMonitorRuleById(logger, entity.RuleID) + if err != nil { + logger.Warnf("AlertEntity2Alert.GetMonitorRuleById error, ruleId:%s, error:%s", entity.RuleID, err.Error()) + } else { + res.Rule = monitorRuleLogic.RuleEntity2Rule(logger, ruleEntity, true) + } + + instanceEntity, err := instanceDao.GetInstanceById(logger, entity.ResourceID) + if err != nil { + logger.Warnf("AlertEntity2Alert.GetInstanceById error, instanceId:%s, error:%s", entity.ResourceID, err.Error()) + } else { + res.Instance = instanceLogic.InstanceEntity2Instance(logger, instanceEntity, nil) + } + + } else { + res.Rule = &response.Rule{ + RuleID: entity.RuleID, + RuleName: entity.RuleName, + } + } + + return res +} + +func AddAlert(logger *log.Logger, paramOrigin *request.AddAlertRequest) (bool, error) { + + for _, param := range paramOrigin.Alerts { + + ruleId := param.RuleID + ruleEntity, err := monitorRuleDao.GetMonitorRuleById(logger, ruleId) + if err != nil { + logger.Warnf("AddAlert.GetMonitorRuleById error, ruleId:%s, error:%s", ruleId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("ruleId %s 不存在", ruleId), fmt.Sprintf("ruleId %s notFound", ruleId))) + } + //对接的第三方服务,需要在这里补齐一些信息 + logger.Point("userId", ruleEntity.UserID) + logger.Point("username", ruleEntity.UserName) + + rt := request.RuleTrigger{} + ro := request.RuleNotice{} + //trigger里面有%>=!=等各种特殊字符,约定赛迪对trigger做urlencode,所以这里需要做一次urldecode操作 + param.Trigger, err = url.QueryUnescape(param.Trigger) + if err != nil { + logger.Warnf("AddAlert.QueryUnescape error:%s", err.Error()) + return false, err + } + if err := json.Unmarshal([]byte(param.Trigger), &rt); err != nil { + logger.Warnf("AddAlert param.Trigger unmarshal error, value:%s, error:%s", param.Trigger, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs("param.Trigger 格式错误", "param.Trigger invalid")) + } + if err := json.Unmarshal([]byte(ruleEntity.NoticeOption), &ro); err != nil { + logger.Warnf("AddAlert NoticeOption unmarshal error, value:%s, error:%s", ruleEntity.NoticeOption, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs("ruleEntity.NoticeOption 格式错误", "ruleEntity.NoticeOption invalid")) + } + + instanceId := param.InstanceID + instanceEntity, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warnf("AddAlert.GetInstanceById error, instanceId:%s, error:%s", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("instanceId %s 不存在", instanceId), fmt.Sprintf("instanceId %s notFound", instanceId))) + } + alertEntity := &monitorAlertDao.MonitorAlerts{ + AlertID: util.GetUuid("ma_"), + AlertTime: int(param.AlertTimestamp), + RuleID: param.RuleID, + RuleName: ruleEntity.RuleName, + Resource: "instance", + ResourceID: param.InstanceID, + ResourceName: instanceEntity.InstanceName, + Trigger: param.Trigger, + AlertValue: param.AlertValue, + CalculationUnit: param.CalculationUnit, + AlertLevel: int8(rt.NoticeLevel), + AlertPeriod: param.AlertPeriod, + UserID: ruleEntity.UserID, + UserName: ruleEntity.UserName, + CreatedTime: int(time.Now().Unix()), + IsRecover: int8(param.IsRecover), + ProjectID: ruleEntity.ProjectID, + } + if param.IsRecover == 0 { //0表示告警,1表示恢复 + if _, err := monitorAlertDao.AddMonitorAlerts(logger, alertEntity); err != nil { + logger.Warnf("AddAlert.AddMonitorAlerts error:%s", err.Error()) + return false, err + } + + ruleEntity.Status = 3 + if err := monitorRuleDao.UpdateMonitorRules(logger, ruleEntity); err != nil { + logger.Warnf("AddAlert.UpdateMonitorRules error:%s", err.Error()) + } + } + + if !judgeIsPublish(logger, ro) { + logger.Warn("judgeIsPublish passed!") + continue + } + + if err := NoticeAlert(logger, alertEntity, ruleEntity, instanceEntity); err != nil { + logger.Warnf("AddAlert.NoticeAlert error, alertId:%s, error:%s", alertEntity.AlertID, err.Error()) + return false, err + } + } + + return true, nil +} + +//规则制定了哪个时间段告警需要通知,不在此时间段的告警不做通知。true表示需要通知,false不需要 +func judgeIsPublish(logger *log.Logger, ro request.RuleNotice) bool { + tz := logger.GetPoint("timezone").(string) + if tz == "" { + tz = "Asia/Shanghai" + } + //2024-07-15 09:27:23只取09:27:23 + timeStr := strings.Split(util.TimestampToString(time.Now().Unix(), tz), " ")[1] + start := ro.EffectiveIntervalStart + end := ro.EffectiveIntervalEnd + + // + timeStrItems := strings.Split(timeStr, ":") + startItems := strings.Split(start, ":") + endItems := strings.Split(end, ":") + + logger.Infof("judgeIsPublish info, nowTime:%s, noticeStartTime:%s, noticeEndTime:%s", timeStrItems, startItems, endItems) + + t1, _ := strconv.Atoi(timeStrItems[0]) + t2, _ := strconv.Atoi(timeStrItems[1]) + t3, _ := strconv.Atoi(timeStrItems[2]) + tReal := t1*3600 + t2*60 + t3 + + s1, _ := strconv.Atoi(startItems[0]) + s2, _ := strconv.Atoi(startItems[1]) + s3, _ := strconv.Atoi(startItems[2]) + sReal := s1*3600 + s2*60 + s3 + + e1, _ := strconv.Atoi(endItems[0]) + e2, _ := strconv.Atoi(endItems[1]) + e3, _ := strconv.Atoi(endItems[2]) + eReal := e1*3600 + e2*60 + e3 + + if tReal >= sReal && tReal <= eReal { + return true + } + return false +} + +func NoticeAlert(logger *log.Logger, alertEntity *monitorAlertDao.MonitorAlerts, ruleEntity *monitorRuleDao.MonitorRules, instanceEntity *instanceDao.Instance) error { + logger.Infof("addAlert.DEBUG, ruleEntity:%s", util.InterfaceToJson(ruleEntity)) + + rt := request.RuleTrigger{} + ro := request.RuleNotice{} + if err := json.Unmarshal([]byte(alertEntity.Trigger), &rt); err != nil { + logger.Warnf("NoticeAlert param.Trigger unmarshal error, value:%s, error:%s", alertEntity.Trigger, err.Error()) + return nil + } + if err := json.Unmarshal([]byte(ruleEntity.NoticeOption), &ro); err != nil { + logger.Warnf("NoticeAlert NoticeOption unmarshal error, value:%s, error:%s", ruleEntity.NoticeOption, err.Error()) + return nil + } + + deviceEntity, err := deviceDao.GetDeviceById(logger, instanceEntity.DeviceID) + if err != nil { + logger.Warnf("NoticeAlert.GetDeviceById error, deviceId:%s, error:%s", instanceEntity.DeviceID, err.Error()) + return nil + } + + noticeWays := ro.NoticeWay + alertR := AlertEntity2Alert(logger, alertEntity, true) + userEntity, err := userDao.GetUserById(logger, ruleEntity.UserID) + logger.Infof("addAlert.DEBUG, user:%s", util.InterfaceToJson(userEntity)) + if err != nil { + logger.Warnf("NoticeAlert.GetUserById error, userId:%s, error:%s", ruleEntity.UserID, err.Error()) + } + + if util.InArray(int64(1), noticeWays) { //1表示站内信 + //专门为带内监控定制的消息detail格式 + type OT struct { + Trigger string `json:"trigger"` + AlertTime int `json:"alertTime"` + AlertPeriod int `json:"alertPeriod"` + AlertValue string `json:"alertValue"` + } + d := OT{ + Trigger: alertEntity.Trigger, + AlertTime: alertEntity.AlertTime, + AlertPeriod: alertEntity.AlertPeriod, + AlertValue: alertEntity.AlertValue + alertEntity.CalculationUnit, + } + detail := fmt.Sprintf("触发规则:%s, 告警值:%s, 告警持续时间:%d分钟", alertR.TriggerDescription, d.AlertValue, d.AlertPeriod) + + if userEntity != nil && userEntity.Language == baseLogic.EN_US { + detail = fmt.Sprintf("trigger condition:%s, alert value:%s, alert continue time:%dminutes", alertR.TriggerDescription, d.AlertValue, d.AlertPeriod) + } + + if alertEntity.IsRecover == 1 { //0表示告警,1表示恢复 + detail = "【恢复】" + detail + } + + webMsg := &messageDao.WebMessage{ + MessageID: util.GetUuid("m-"), + SN: deviceEntity.Sn, + MessageType: messageType.MessageTypeInBondAlert, + MessageSubType: rt.Metric, + ResourceType: "inBondAlert", + FinishTime: d.AlertTime, + Detail: detail, + Content: detail, + UserID: ruleEntity.UserID, + UserName: ruleEntity.UserName, + InstanceID: instanceEntity.InstanceID, + InstanceName: instanceEntity.InstanceName, + Result: "success", + RuleID: ruleEntity.RuleID, + RuleName: ruleEntity.RuleName, + IsRecover: alertEntity.IsRecover, + } + if webMsg.IsRecover == 0 { //0表示告警,1表示恢复 + if err := messageLogic.AddWebMessage(logger, webMsg); err != nil { + logger.Warnf("NoticeAlert.AddWebMessage error:%s", err.Error()) + } + } + + } + if util.InArray(int64(2), noticeWays) { //2表示邮件 + + //发送邮件通知 + obj := &mailLogic.InbondAlertMailMessage{ + MessageType: messageLogic.Types2ShowZh[messageType.MessageTypeInBondAlert], + MessageSubType: messageLogic.Types2ShowZh[rt.Metric], + ResourceType: "instance", + AlertTime: time.Unix(int64(alertEntity.AlertTime), 0).Format("2006-01-02 15:04:05"), + AlertPeriod: alertEntity.AlertPeriod, + Trigger: alertR.TriggerDescription, + AlertValue: alertEntity.AlertValue + alertEntity.CalculationUnit, + SN: deviceEntity.Sn, + UserID: ruleEntity.UserID, + UserName: ruleEntity.UserName, + InstanceID: instanceEntity.InstanceID, + InstanceName: instanceEntity.InstanceName, + IsRecover: int(alertEntity.IsRecover), + RuleName: ruleEntity.RuleName, + RuleID: ruleEntity.RuleID, + } + subject := fmt.Sprintf("%s-%s DEBUG", messageLogic.Types2ShowZh[messageType.MessageTypeInBondAlert], messageLogic.Types2ShowZh[rt.Metric]) + if obj.IsRecover == 1 { //0表示告警,1表示恢复 + subject = subject + "-恢复" + } + logger.Infof("addAlert.DEBUG, subject:%s, email:%s", util.InterfaceToJson(userEntity), userEntity.Email) + err = mailLogic.SendMailByTpl(logger, mailLogic.MessageInBondAlertTemplate, subject, obj, userEntity.Email) + if err != nil { + logger.Warnf("addAlert.SendMail error:%s", err.Error()) + } else { + logger.Infof("addAlert.SendMail success, receiver:%s", userEntity.Email) + } + } + + return nil +} + +func DescribeAlert(logger *log.Logger, AlertId string) (*response.Alert, error) { + alertEntity, err := monitorAlertDao.GetMonitorAlertsById(logger, AlertId) + if err != nil { + logger.Warnf("DescribeAlert.GetMonitorAlertsById error, AlertId:%s, error:%s", AlertId, err.Error()) + return nil, err + } + res := AlertEntity2Alert(logger, alertEntity, true) + return res, nil + +} + +func DescribeAlerts(logger *log.Logger, param *request.DescribeAlertsRequest, p util.Pageable) (*response.AlertList, error) { + userId := logger.GetPoint("userId").(string) + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "is_del": 0, + } + if param.UserID != "" { + query["user_id"] = param.UserID + } else { + query["user_id"] = userId + } + if param.UserName != "" { + query["user_name"] = param.UserName + } + if param.RuleID != "" { + query["rule_id"] = param.RuleID + } + if param.ResourceID != "" { + query["resource_id"] = param.ResourceID + } + if param.StartTime != 0 { + query["alert_time.>="] = param.StartTime + } + if param.EndTime != 0 { + query["alert_time.<="] = param.EndTime + } + if param.ProjectID != "" { + query["project_id"] = param.ProjectID + } + count, err := monitorAlertDao.GetMonitorAlertsCount(logger, query) + if err != nil { + logger.Warnf("DescribeAlerts.GetMonitorAlertsCount error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, err + } + entityList := []*monitorAlertDao.MonitorAlerts{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = monitorAlertDao.GetMultiMonitorAlerts(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = monitorAlertDao.GetMultiMonitorAlerts(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("DescribeAlerts.GetMultiMonitorAlerts sql error:", err.Error()) + return nil, err + } + items := []*response.Alert{} + for _, alertEntity := range entityList { + item := AlertEntity2Alert(logger, alertEntity, false) + items = append(items, item) + } + resp := &response.AlertList{ + Alerts: items, + PageNumber: p.PageNumber, + PageSize: p.PageSize, + TotalCount: count, + } + + return resp, nil +} + +func DeleteAlert(logger *log.Logger, param *request.DeleteAlertRequest) (bool, error) { + + alertId := param.AlertId + entity, err := monitorAlertDao.GetMonitorAlertsById(logger, alertId) + if err != nil { + logger.Warnf("DeleteAlert.GetMonitorAlertsById error, alertId:%s, error:%s", alertId, err.Error()) + return false, err + } + + entity.IsDel = 1 + if err := monitorAlertDao.UpdateMonitorAlerts(logger, entity); err != nil { + logger.Warnf("DeleteAlert.UpdateMonitorAlerts error, ruleId:%s, error:%s", alertId, err.Error()) + return false, err + } + return true, nil + +} diff --git a/bmp-openapi-console/logic/monitorDataLogic/monitorDataLogic.go b/bmp-openapi-console/logic/monitorDataLogic/monitorDataLogic.go new file mode 100644 index 0000000..8eef3c2 --- /dev/null +++ b/bmp-openapi-console/logic/monitorDataLogic/monitorDataLogic.go @@ -0,0 +1,178 @@ +package monitorDataLogic + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorProxyLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorRuleLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + beego "github.com/beego/beego/v2/server/web" +) + +var pronoeaUrl string + +func Init() error { + bmp_pronoea_host, err := beego.AppConfig.String("bmp_pronoea_host") + if err != nil { + return err + } + bmp_pronoea_port, _ := beego.AppConfig.String("bmp_pronoea_port") + if err != nil { + return err + } + pronoeaUrl = fmt.Sprintf("http://%s:%s/api/query", bmp_pronoea_host, bmp_pronoea_port) + return nil +} + +type PronoeaMonitorDataResponse struct { + Code int `json:"Code"` + RequestID string `json:"RequestId"` + Message string `json:"Message"` + Result []*response.DataEveryMetric `json:"Result"` +} + +// func getSampleMethod(logger *log.Logger, metric string) string { +// rateMetrics := []string{ +// "bmp.disk.counts.read", +// "bmp.disk.counts.write", +// "bmp.network.packets.ingress", +// "bmp.network.packets.egress", +// "bmp.disk.bytes.read", +// "bmp.disk.bytes.write", +// "bmp.network.bytes.ingress", +// "bmp.network.bytes.egress", +// } +// increaseMetrics := []string{} +// if util.InArrayString(metric, rateMetrics) { +// return "rate" +// } +// if util.InArrayString(metric, increaseMetrics) { +// return "increase" +// } +// return "" + +// } + +func getTagNameByMetric(metric string) string { + mountpointMetrics := []string{ + + "bmp.disk.partition.used", + "bmp.disk.partition.util", + } + diskMetrics := []string{ + "bmp.disk.used", + "bmp.disk.util", + "bmp.disk.bytes.read", + "bmp.disk.bytes.write", + "bmp.disk.counts.read", + "bmp.disk.counts.write", + } + nicMetrics := []string{ + "bmp.network.bytes.ingress", + "bmp.network.bytes.egress", + "bmp.network.packets.ingress", + "bmp.network.packets.egress", + } + if util.InArrayString(metric, mountpointMetrics) { + return "mountpoint" + } + if util.InArrayString(metric, diskMetrics) { + return "disk" + } + if util.InArrayString(metric, nicMetrics) { + return "nic" + } + return "" +} + +func GetMonitorData(logger *log.Logger, param request.GetMonitorDataRequest) ([]*response.DataEveryMetric, error) { + url := pronoeaUrl + + metrics := strings.Split(param.MetricName, ",") + if len(metrics) == 0 { + panic(constant.BuildCANCELLEDWithArgs("param metricName错误", "param metricName invalid")) + } + tableName := monitorRuleLogic.MapMetric2Table[metrics[0]] + if tableName == "" { + tableName = "bmp_monitor_gauge" + } + req := response.MonitorDataQuery{ + TableName: tableName, + SampleMethod: param.DownSampleType, + StartTime: param.StartTime, + EndTime: param.EndTime, + Step: param.TimeInterval, + } + if strings.Contains(param.MetricName, "bmp.memory.used") || strings.Contains(param.MetricName, "bmp.disk.used") || strings.Contains(param.MetricName, "bmp.disk.partition.used") { + req.Func = map[string]int{ + "/": 1000000000, + } + } + if strings.Contains(param.MetricName, "bmp.network.bytes.ingress") || strings.Contains(param.MetricName, "bmp.network.bytes.egress") { + req.Func = map[string]int{ + "*": 8, + } + } + + //支持多个,传参格式 metric_name = "(cps.disk.partition.used)|(cps.disk.partition.util)" + metricNames := strings.Split(param.MetricName, ",") + if len(metricNames) > 1 { + kw := []string{} + for _, mn := range metricNames { + kw = append(kw, fmt.Sprintf("(%s)", mn)) + } + param.MetricName = strings.Join(kw, "|") + } + labels := map[string]string{ + "metric_name": param.MetricName, + "instance_id": param.InstanceID, + } + + if param.Device != "" { + labels["device"] = param.Device + } else { //磁盘和网口相关的指标,当没有给tag时(监控图首页),给一个默认tag,否则前端展示有问题 + tagName := getTagNameByMetric(metricNames[0]) + if tagName != "" { + tagValues, err := monitorProxyLogic.DescribeDeviceTags(logger, &request.DesrcibeTagsRequest{ + InstanceID: param.InstanceID, + TagName: tagName, + }) + if err != nil || tagValues == nil || len(tagValues.Tags) == 0 { + logger.Warnf("GetMonitorData.DescribeDeviceTags error, instanceId:%s", param.InstanceID) + } else { + labels["device"] = tagValues.Tags[0] + } + } + + } + req.Labels = labels + if param.LastManyTime != 0 { + req.EndTime = time.Now().Unix() + req.StartTime = time.Now().Add(time.Duration(0-param.LastManyTime) * time.Hour).Unix() + } + logger.Infof("GetMonitorData.DoHttpPost request:%s", util.InterfaceToJson(req)) + + header := map[string]string{ + "Traceid": logger.GetPoint("logid").(string), + } + resp, err := util.DoHttpPost(logger, url, header, req) + if err != nil { + logger.Warnf("DescribeDeviceTags post error, instanceIds:%s, error:%s", param.InstanceID, err.Error()) + return nil, err + } + logger.Infof("GetMonitorData.DoHttpPost response:%s", string(resp)) + + res := PronoeaMonitorDataResponse{} + if err := json.Unmarshal(resp, &res); err != nil { + logger.Warnf("GetMonitorData post body parse error, instanceIds:%s, error:%s", param.InstanceID, err.Error()) + return nil, err + } + return res.Result, nil +} diff --git a/bmp-openapi-console/logic/monitorProxyLogic/monitorProxyLogic.go b/bmp-openapi-console/logic/monitorProxyLogic/monitorProxyLogic.go new file mode 100644 index 0000000..f3ab2dd --- /dev/null +++ b/bmp-openapi-console/logic/monitorProxyLogic/monitorProxyLogic.go @@ -0,0 +1,129 @@ +package monitorProxyLogic + +import ( + "encoding/json" + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + beego "github.com/beego/beego/v2/server/web" +) + +const ( + agentStatusUrl string = "/api/v1/describeAgentStatus" + deviceTagsUrl string = "/api/v1/tags" +) + +var AgentStatusMapZh map[int]string = map[int]string{ + 0: "未安装", + 1: "正常", + 2: "异常", +} +var AgentStatusMapEn map[int]string = map[int]string{ + 0: "Not Installed", + 1: "Normal", + 2: "Abnormal", +} + +var monitorProxyServer string + +func Init() error { + bmp_monitor_proxy_host, err := beego.AppConfig.String("bmp_monitor_proxy_host") + if err != nil { + return err + } + bmp_monitor_proxy_port, err := beego.AppConfig.String("bmp_monitor_proxy_port") + if err != nil { + return err + } + monitorProxyServer = fmt.Sprintf("http://%s:%s", bmp_monitor_proxy_host, bmp_monitor_proxy_port) + return nil +} + +type DescribeAgentStatusResponse struct { + // 操作失败结果。成功时有此结构 + Result []response.AgentStatusItem `json:"result"` + // 操作失败结果。失败时有此结构 + Error interface{} `json:"error"` + // 请求traceId + // required: true + RequestId string `json:"requestId"` +} + +func DescribeAgentStatus(logger *log.Logger, param *request.DesrcibeAgentStatusRequest) (*response.AgentStatusResponse, error) { + url := monitorProxyServer + agentStatusUrl + instanceIds := strings.Split(param.InstanceID, ",") + body := map[string]interface{}{ + "instanceIds": instanceIds, + } + header := map[string]string{ + "Traceid": logger.GetPoint("logid").(string), + } + logger.Infof("DescribeAgentStatus.request:%s", util.InterfaceToJson(body)) + resp, err := util.DoHttpPost(logger, url, header, body) + if err != nil { + logger.Warnf("DescribeAgentStatus post error, instanceIds:%s, error:%s", param.InstanceID, err.Error()) + return nil, err + } + logger.Infof("DescribeAgentStatus.resp:%s", string(resp)) + + res := DescribeAgentStatusResponse{} + if err := json.Unmarshal(resp, &res); err != nil { + logger.Warnf("DescribeAgentStatus post body parse error, instanceIds:%s, error:%s", param.InstanceID, err.Error()) + return nil, err + } + + for idx, item := range res.Result { + if logger.GetPoint("language").(string) == baseLogic.EN_US { + item.StatusName = AgentStatusMapEn[item.Status] + } else { + item.StatusName = AgentStatusMapZh[item.Status] + } + res.Result[idx] = item + } + + return &response.AgentStatusResponse{ + AgentStatus: res.Result, + }, nil + +} + +type DescribeDeviceTagsResponse struct { + // 操作失败结果。成功时有此结构 + Result response.TagsResponse `json:"result"` + // 操作失败结果。失败时有此结构 + Error interface{} `json:"error"` + // 请求traceId + // required: true + RequestId string `json:"requestId"` +} + +func DescribeDeviceTags(logger *log.Logger, param *request.DesrcibeTagsRequest) (*response.TagsResponse, error) { + url := monitorProxyServer + deviceTagsUrl + + body := map[string]interface{}{ + "instanceId": param.InstanceID, + "metric": param.TagName, + } + header := map[string]string{ + "Traceid": logger.GetPoint("logid").(string), + } + resp, err := util.DoHttpPost(logger, url, header, body) + if err != nil { + logger.Warnf("DescribeDeviceTags post error, instanceIds:%s, error:%s", param.InstanceID, err.Error()) + return nil, err + } + + res := DescribeDeviceTagsResponse{} + if err := json.Unmarshal(resp, &res); err != nil { + logger.Warnf("DescribeDeviceTags post body parse error, instanceIds:%s, error:%s", param.InstanceID, err.Error()) + return nil, err + } + return &response.TagsResponse{ + Tags: res.Result.Tags, + }, nil +} diff --git a/bmp-openapi-console/logic/monitorRuleLogic/monitorRuleLogic.go b/bmp-openapi-console/logic/monitorRuleLogic/monitorRuleLogic.go new file mode 100644 index 0000000..80d5b6e --- /dev/null +++ b/bmp-openapi-console/logic/monitorRuleLogic/monitorRuleLogic.go @@ -0,0 +1,826 @@ +package monitorRuleLogic + +import ( + "encoding/json" + "errors" + "fmt" + "strconv" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/monitorRuleDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/projectDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rMonitorRulesInstanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/messageLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + beego "github.com/beego/beego/v2/server/web" +) + +var monitorRuleSendUrl string +var monitorRuleDelUrl string +var monitorRuleListUrl string + +func Init() error { + bmp_pronoea_host, err := beego.AppConfig.String("bmp_pronoea_host") + if err != nil { + return err + } + bmp_pronoea_port, _ := beego.AppConfig.String("bmp_pronoea_port") + if err != nil { + return err + } + monitorRuleSendUrl = fmt.Sprintf("http://%s:%s/api/rules/write", bmp_pronoea_host, bmp_pronoea_port) + monitorRuleDelUrl = fmt.Sprintf("http://%s:%s/api/rules/delete", bmp_pronoea_host, bmp_pronoea_port) + monitorRuleListUrl = fmt.Sprintf("http://%s:%s/api/rules/list", bmp_pronoea_host, bmp_pronoea_port) + return nil +} + +var MapMetric2Table map[string]string = map[string]string{ + "bmp.disk.bytes.read": "bmp_monitor_counter", + "bmp.disk.bytes.write": "bmp_monitor_counter", + "bmp.disk.counts.read": "bmp_monitor_counter", + "bmp.disk.counts.write": "bmp_monitor_counter", + "bmp.network.bytes.ingress": "bmp_monitor_counter", + "bmp.network.bytes.egress": "bmp_monitor_counter", + "bmp.network.packets.ingress": "bmp_monitor_counter", + "bmp.network.packets.egress": "bmp_monitor_counter", +} + +var DimensionMapZh map[string]string = map[string]string{ + "disk": "盘符", + "mountpoint": "挂载点", + "nic": "网卡", +} + +var RuleStatusMapZh map[int64]string = map[int64]string{ + 1: "正常", + 2: "已禁用", + 3: "报警", +} + +var RuleStatusMapEn map[int64]string = map[int64]string{ + 1: "Normal", + 2: "Disabled", + 3: "Alert", +} + +// 1表示一般,2表示严重,3表示紧急 +var RuleAlertLevelMapZh map[int64]string = map[int64]string{ + 1: "一般", + 2: "严重", + 3: "紧急", +} + +var RuleAlertLevelMapEn map[int64]string = map[int64]string{ + 1: "General", + 2: "Serious", + 3: "Emergency", +} + +var RuleTriggerCalculationEn map[string]string = map[string]string{ + "min": "Min", + "max": "Max", + "avg": "Avg", + "sum": "Sum", +} + +var RuleTriggerCalculationZh map[string]string = map[string]string{ + "min": "最小值", + "max": "最大值", + "avg": "平均值", + "sum": "总和", +} + +var RuleTriggerOperation map[string]string = map[string]string{ + "gt": ">", + "gte": ">=", + "lt": "<", + "lte": "<=", + "eq": "==", + "neq": "!=", +} + +var ResourceMapZh map[string]string = map[string]string{ + "instance": "实例", +} + +type DeleteRuleToPronoeaRequest struct { + RuleIDs string `json:"ruleIds"` + Source string `json:"source"` +} + +type SendRuleToPronoeaRequest struct { + Source string `json:"source"` + Rules []*response.Rule `json:"rules"` +} + +func Trigger2Description(logger *log.Logger, trigger *response.RuleTrigger) string { + + var tpl string //统计周期5分钟 CPU使用率 平均值 >= 1% 持续1个周期 + var metricName string + var staticName string + var operationName string + if logger.GetPoint("language").(string) != baseLogic.EN_US { + tpl = "统计周期 %d分钟 %s %s %s %s%s 持续 %d个周期" + metricName = messageLogic.Types2ShowZh[trigger.Metric] + staticName = RuleTriggerCalculationZh[trigger.Calculation] + } else { + tpl = "static period %dminutes %s %s %s %s%s continue %dperiods" + metricName = messageLogic.Types2ShowEn[trigger.Metric] + staticName = RuleTriggerCalculationEn[trigger.Calculation] + } + operationName = RuleTriggerOperation[trigger.Operation] + if operationName == "" { + operationName = trigger.Operation + } + var threshold string + if float64(int(trigger.Threshold)) == trigger.Threshold { //直接取整 + threshold = strconv.Itoa(int(trigger.Threshold)) + } else { + threshold = strconv.FormatFloat(trigger.Threshold, 'f', 2, 64) + } + + return fmt.Sprintf(tpl, trigger.Period, metricName, staticName, operationName, threshold, trigger.CalculationUnit, trigger.Times) +} + +func RuleEntity2Rule(logger *log.Logger, entity *monitorRuleDao.MonitorRules, idDetail bool) *response.Rule { + + res := &response.Rule{ + RuleID: entity.RuleID, + RuleName: entity.RuleName, + Dimension: entity.Dimension, + DimensionName: entity.Dimension, + Resource: entity.Resource, + ResourceName: entity.Resource, + Status: int64(entity.Status), + } + if logger.GetPoint("language").(string) != baseLogic.EN_US { + res.DimensionName = DimensionMapZh[entity.Dimension] + res.ResourceName = ResourceMapZh[entity.Resource] + } + + trOption := []*response.RuleTrigger{} + if err := json.Unmarshal([]byte(entity.TriggerOption), &trOption); err != nil { + logger.Warnf("RuleEntity2Rule.Unmarshal error, rule_id:%s, error:%s", entity.RuleID, err.Error()) + } else { + res.TriggerOption = trOption + } + triggerDescriptions := []string{} + for idx, v := range trOption { + item := Trigger2Description(logger, v) + triggerDescriptions = append(triggerDescriptions, item) + trOption[idx].Description = item + trOption[idx].TableName = MapMetric2Table[v.Metric] + if trOption[idx].TableName == "" { + trOption[idx].TableName = "bmp_monitor_gauge" + } + } + res.TriggerDescription = triggerDescriptions + + notifyOption := &response.RuleNotice{} + if err := json.Unmarshal([]byte(entity.NoticeOption), notifyOption); err != nil { + logger.Warnf("RuleEntity2Rule.Unmarshal error, rule_id:%s, error:%s", entity.RuleID, err.Error()) + } else { + res.NoticeOption = notifyOption + } + + q := map[string]interface{}{ + "is_del": 0, + "rule_id": entity.RuleID, + } + rRuleInstanceEntities, err := rMonitorRulesInstanceDao.GetAllRMonitorRulesInstance(logger, q) + if err != nil { + logger.Warnf("DescribeRule.GetAllRMonitorRulesInstance error, ruleId:%s, error:%s", entity.RuleID, err.Error()) + } + instanceIds := []string{} + for _, v := range rRuleInstanceEntities { + instanceIds = append(instanceIds, v.InstanceID) + } + res.InstanceIds = instanceIds + res.InstanceCount = int64(len(instanceIds)) + + if idDetail { + iq := map[string]interface{}{ + "is_del": 0, + "instance_id.in": instanceIds, + } + instanceEntities, err := instanceDao.GetAllInstance(logger, iq) + if err != nil { + logger.Warnf("RuleEntity2Rule.GetAllInstance error:%s", err.Error()) + } else { + instances := []*response.Instance{} + for _, v := range instanceEntities { + instances = append(instances, instanceLogic.InstanceEntity2Instance(logger, v, nil)) + } + res.Instances = instances + } + + if res.NoticeOption != nil { + noticeUserId := res.NoticeOption.UserID + userEntity, err := userDao.GetUserById(logger, noticeUserId) + if err != nil { + logger.Warnf("RuleEntity2Rule.GetUserById error, userid:%s, error:%s", noticeUserId, err.Error()) + } + res.NoticeOption.UserName = userEntity.UserName + } + + } + + relatedResourceCount := int64(len(rRuleInstanceEntities)) + res.RelatedResourceCount = relatedResourceCount + if relatedResourceCount > 0 { + res.DeviceTag = rRuleInstanceEntities[0].Tags + } + + if logger.GetPoint("language").(string) == baseLogic.EN_US { + res.StatusName = RuleStatusMapEn[res.Status] + + } else { + res.StatusName = RuleStatusMapZh[res.Status] + } + + return res + +} + +func AddRule(logger *log.Logger, param *request.AddRuleRequest) (bool, error) { + instanceIds := param.InstanceIds + + q := map[string]interface{}{ + "is_del": 0, + "instance_id.in": instanceIds, + } + instanceEntities, err := instanceDao.GetAllInstance(logger, q) + if err != nil { + logger.Warnf("AddRule.GetAllInstance error, instance_ids:%v, error:%s", instanceIds, err.Error()) + return false, err + } + if len(instanceEntities) < len(instanceIds) { + logger.Warnf("AddRule.GetAllInstance number lt, instance_ids:%v", instanceIds) + return false, errors.New("instanceIds param error") + } + entity := &monitorRuleDao.MonitorRules{ + RuleID: util.GetUuid("mr_"), + Status: 1, + RuleName: param.RuleName, + Dimension: param.Dimension, + Resource: param.Resource, + ProjectID: param.ProjectID, + // TriggerOption: , + // NoticeOption: , + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + UserID: logger.GetPoint("userId").(string), + UserName: logger.GetPoint("username").(string), + } + v, _ := json.Marshal(param.TriggerOption) + entity.TriggerOption = string(v) + v1, _ := json.Marshal(param.NoticeOption) + entity.NoticeOption = string(v1) + if _, err := monitorRuleDao.AddMonitorRules(logger, entity); err != nil { + logger.Warnf("AddRule.dao.AddMonitorRules error:%s", err.Error()) + return false, err + } else { + rEntities := []*rMonitorRulesInstanceDao.RMonitorRulesInstance{} + for _, instanceEntity := range instanceEntities { + rEntity := &rMonitorRulesInstanceDao.RMonitorRulesInstance{ + RuleID: entity.RuleID, + RuleName: entity.RuleName, + InstanceID: instanceEntity.InstanceID, + InstanceName: instanceEntity.InstanceName, + Tags: param.DeviceTag, + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + ProjectID: param.ProjectID, + } + rEntities = append(rEntities, rEntity) + } + if len(rEntities) > 0 { + if err := rMonitorRulesInstanceDao.AddMultiRMonitorRulesInstance(logger, rEntities); err != nil { + logger.Warnf("AddRule.AddMultiRMonitorRulesInstance error:%s", err.Error()) + return false, err + } + } + } + + rule := RuleEntity2Rule(logger, entity, false) + if err := sendRuleToPronoea(logger, rule); err != nil { + logger.Warnf("AddRule.sendRuleToPronoea error, rule_id:%s, error:%s", entity.RuleID, err.Error()) + return false, err + } + return true, nil + +} + +func DescribeRule(logger *log.Logger, ruleId string) (*response.Rule, error) { + ruleEntity, err := monitorRuleDao.GetMonitorRuleById(logger, ruleId) + if err != nil { + logger.Warnf("DescribeRule.GetMonitorRuleById error, ruleId:%s, error:%s", ruleId, err.Error()) + return nil, err + } + res := RuleEntity2Rule(logger, ruleEntity, true) + return res, nil + +} + +func DescribeRules(logger *log.Logger, param *request.DescribeRulesRequest, p util.Pageable) (*response.RuleList, error) { + + if param.ProjectID != "" { + projectEntity, err := projectDao.GetProjectById(logger, param.ProjectID) + if err != nil { + logger.Warnf("DescribeRules.GetProjectById error, projectId:%s, error:%s", param.ProjectID, err.Error()) + return nil, err + } + if projectEntity.UserID != logger.GetPoint("userId").(string) { + logger.Warnf("DescribeRules.project.userid not equal traffic.userId, pass") + return nil, nil + } + } + + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "is_del": 0, + } + if param.UserID != "" { + query["user_id"] = param.UserID + } + if param.UserName != "" { + query["user_name"] = param.UserName + } + if param.RuleID != "" { + query["rule_id"] = param.RuleID + } + if param.RuleName != "" { + query["rule_name.like"] = "%" + param.RuleName + "%" + } + if param.Status != 0 { + query["status"] = param.Status + } + if param.ProjectID != "" { + query["project_id"] = param.ProjectID + } + count, err := monitorRuleDao.GetMonitorRulesCount(logger, query) + if err != nil { + logger.Warnf("GetSshkeyCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, err + } + entityList := []*monitorRuleDao.MonitorRules{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = monitorRuleDao.GetMultiMonitorRules(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = monitorRuleDao.GetMultiMonitorRules(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("DescribeRules.GetMultiMonitorRules sql error:", err.Error()) + return nil, err + } + items := []*response.Rule{} + for _, ruleEntity := range entityList { + item := RuleEntity2Rule(logger, ruleEntity, false) + items = append(items, item) + } + resp := &response.RuleList{ + Rules: items, + PageNumber: p.PageNumber, + PageSize: p.PageSize, + TotalCount: count, + } + + return resp, nil +} + +func EditRule(logger *log.Logger, param *request.EditRuleRequest) (bool, error) { + + ruleId := param.RuleId + entity, err := monitorRuleDao.GetMonitorRuleById(logger, ruleId) + if err != nil { + logger.Warnf("EditRule.GetMonitorRuleById error, ruleId:%s, error:%s", ruleId, err.Error()) + return false, err + } + + instanceIds := param.InstanceIds + + q := map[string]interface{}{ + "is_del": 0, + "instance_id.in": instanceIds, + } + instanceEntities, err := instanceDao.GetAllInstance(logger, q) + if err != nil { + logger.Warnf("EditRule.GetAllInstance error, instance_ids:%v, error:%s", instanceIds, err.Error()) + return false, err + } + if len(instanceEntities) < len(instanceIds) { + logger.Warnf("EditRule.GetAllInstance number lt, instance_ids:%v", instanceIds) + return false, errors.New("instanceIds param error") + } + + // entity.Status = 1 + + // alertEntities, _ := monitorAlertDao.GetAllMonitorAlertsByRuleId(logger, param.RuleId) + // if len(alertEntities) > 0 { + // entity.Status = 3 //已告警 + // } + + entity.RuleName = param.RuleName + entity.Dimension = param.Dimension + entity.Resource = param.Resource + entity.UpdatedTime = int(time.Now().Unix()) + entity.UserID = logger.GetPoint("userId").(string) + v, _ := json.Marshal(param.TriggerOption) + entity.TriggerOption = string(v) + v1, _ := json.Marshal(param.NoticeOption) + entity.NoticeOption = string(v1) + if err := monitorRuleDao.UpdateMonitorRules(logger, entity); err != nil { + logger.Warnf("EditRule.dao.UpdateMonitorRules error:%s", err.Error()) + return false, err + } else { + q := map[string]interface{}{ + "is_del": 0, + "rule_id": param.RuleId, + } + u := map[string]interface{}{ + "is_del": 1, + } + if err := rMonitorRulesInstanceDao.UpdateMultiRMonitorRulesInstance(logger, q, u); err != nil { + logger.Warnf("EditRule.UpdateMultiRMonitorRulesInstance error, rule_id:%s, error:%s", param.RuleId, err.Error()) + } + + rEntities := []*rMonitorRulesInstanceDao.RMonitorRulesInstance{} + for _, instanceEntity := range instanceEntities { + rEntity := &rMonitorRulesInstanceDao.RMonitorRulesInstance{ + RuleID: entity.RuleID, + RuleName: entity.RuleName, + InstanceID: instanceEntity.InstanceID, + InstanceName: instanceEntity.InstanceName, + Tags: param.DeviceTag, + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + } + rEntities = append(rEntities, rEntity) + } + if len(rEntities) > 0 { + if err := rMonitorRulesInstanceDao.AddMultiRMonitorRulesInstance(logger, rEntities); err != nil { + logger.Warnf("EditRule.AddMultiRMonitorRulesInstance error:%s", err.Error()) + return false, err + } + } + } + rule := RuleEntity2Rule(logger, entity, true) + if err := sendRuleToPronoea(logger, rule); err != nil { + logger.Warnf("EditRule.sendRuleToPronoea error, rule_id:%s, error:%s", param.RuleId, err.Error()) + return false, err + } + return true, nil + +} + +func EnableRule(logger *log.Logger, param *request.EnableRuleRequest) (bool, error) { + + ruleId := param.RuleId + entity, err := monitorRuleDao.GetMonitorRuleById(logger, ruleId) + if err != nil { + logger.Warnf("EnableRule.GetMonitorRuleById error, ruleId:%s, error:%s", ruleId, err.Error()) + return false, err + } + if entity.Status != 2 { + logger.Warnf("EnableRule.rule enablestatus now %d not allowed enable", entity.Status) + panic(constant.NOT_SUPPORTED) + } + entity.Status = 1 //如果之前已经告警了呢? + entity.UpdatedTime = int(time.Now().Unix()) + if err := monitorRuleDao.UpdateMonitorRules(logger, entity); err != nil { + logger.Warnf("EnableRule.UpdateMonitorRules error, ruleId:%s, error:%s", ruleId, err.Error()) + return false, err + } + rule := RuleEntity2Rule(logger, entity, true) + if err := sendRuleToPronoea(logger, rule); err != nil { + logger.Warnf("EnableRule.sendRuleToPronoea error, rule_id:%s, error:%s", param.RuleId, err.Error()) + return false, err + } + return true, nil + +} + +func DisableRule(logger *log.Logger, param *request.DisableRuleRequest) (bool, error) { + + ruleId := param.RuleId + entity, err := monitorRuleDao.GetMonitorRuleById(logger, ruleId) + if err != nil { + logger.Warnf("DisableRule.GetMonitorRuleById error, ruleId:%s, error:%s", ruleId, err.Error()) + return false, err + } + if entity.Status == 2 { //已经是禁用状态 + logger.Warnf("DisableRule.rule enablestatus now %d not allowed enable", entity.Status) + panic(constant.NOT_SUPPORTED) + } + entity.Status = 2 + entity.UpdatedTime = int(time.Now().Unix()) + if err := monitorRuleDao.UpdateMonitorRules(logger, entity); err != nil { + logger.Warnf("DisableRule.UpdateMonitorRules error, ruleId:%s, error:%s", ruleId, err.Error()) + return false, err + } + if err := DelRuleToPronoea(logger, param.RuleId); err != nil { + logger.Warnf("DisableRule.DelRuleToPronoea error, rule_id:%s, error:%s", param.RuleId, err.Error()) + return false, err + } + return true, nil + +} + +func DeleteRule(logger *log.Logger, param *request.DeleteRuleRequest) (bool, error) { + + ruleId := param.RuleId + entity, err := monitorRuleDao.GetMonitorRuleById(logger, ruleId) + if err != nil { + logger.Warnf("DeleteRule.GetMonitorRuleById error, ruleId:%s, error:%s", ruleId, err.Error()) + return false, err + } + if entity.Status != 2 { + panic(constant.BuildInvalidArgumentWithArgs("禁用状态的规则才允许删除", "enabled rule not allow delete")) + } + + entity.IsDel = 1 + if err := monitorRuleDao.UpdateMonitorRules(logger, entity); err != nil { + logger.Warnf("DeleteRule.UpdateMonitorRules error, ruleId:%s, error:%s", ruleId, err.Error()) + return false, err + } + // if err := DelRuleToPronoea(logger, param.RuleId); err != nil { + // logger.Warnf("DeleteRule.DelRuleToPronoea error, rule_id:%s, error:%s", param.RuleId, err.Error()) + // return false, err + // } + return true, nil + +} + +func sendRuleToPronoea(logger *log.Logger, rule *response.Rule) error { + rules := []*response.Rule{rule} + return sendRulesToPronoea(logger, rules) + +} + +func sendRulesToPronoea(logger *log.Logger, rules []*response.Rule) error { + url := monitorRuleSendUrl + req := SendRuleToPronoeaRequest{ + Source: "bmpInBand", + Rules: rules, + } + logger.Infof("sendRuleToPronoea.request:%s", util.InterfaceToJson(req)) + header := map[string]string{ + "Traceid": logger.GetPoint("logid").(string), + } + resp, err := util.DoHttpPost(logger, url, header, req) + if err != nil { + logger.Warnf("sendRuleToPronoea post error, query:%s, error:%s", util.InterfaceToJson(rules), err.Error()) + return err + } + logger.Infof("sendRuleToPronoea resp:%s", string(resp)) + return nil + +} + +func DelRuleToPronoea(logger *log.Logger, ruleId string) error { + url := monitorRuleDelUrl + req := DeleteRuleToPronoeaRequest{ + RuleIDs: ruleId, + Source: "bmpInBand", + } + logger.Infof("DelRuleToPronoea.request:%s", util.InterfaceToJson(req)) + header := map[string]string{ + "Traceid": logger.GetPoint("logid").(string), + } + resp, err := util.DoHttpPost(logger, url, header, req) + if err != nil { + logger.Warnf("DelRuleToPronoea post error, rule_id:%s, error:%s", ruleId, err.Error()) + return err + } + logger.Infof("DelRuleToPronoea resp:%s", string(resp)) + return nil + +} + +func DelMonitorRulesByProjectID(logger *log.Logger, projectId string) error { + q := map[string]interface{}{ + "is_del": 0, + "project_id": projectId, + } + ruleEntities, err := monitorRuleDao.GetAllMonitorRules(logger, q) + if err != nil { + logger.Warnf("DelMonitorRulesByProjectID.GetAllMonitorRules error, query:%s, error:%s", util.InterfaceToJson(q), err.Error()) + return err + } + if len(ruleEntities) == 0 { + logger.Infof("DelMonitorRulesByProjectID rule empty, projectId:%s", projectId) + return nil + } + ruleIds := []string{} + for _, ruleEntity := range ruleEntities { + ruleIds = append(ruleIds, ruleEntity.RuleID) + } + q1 := map[string]interface{}{ + "is_del": 0, + "rule_id.in": ruleIds, + } + u := map[string]interface{}{ + "is_del": 1, + } + if err := monitorRuleDao.UpdateMultiMonitorRules(logger, q1, u); err != nil { + logger.Warnf("DelMonitorRulesByProjectID.UpdateMultiMonitorRules error, query:%s, error:%s", util.InterfaceToJson(q1), err.Error()) + return err + } + + //TODO 下发配置到proea + ruleidStr := strings.TrimRight(strings.Join(ruleIds, ","), ",") + if err := DelRuleToPronoea(logger, ruleidStr); err != nil { + logger.Warnf("DelMonitorRulesByProjectID.DelRuleToPronoea error, ruleIds:%s, err:%s", ruleidStr, err.Error()) + } + return nil +} + +//先删除规则,再重新下发规则 +func DelRMonitorRuleInstances(logger *log.Logger, projectId string, instanceIds string) error { + + q1 := map[string]interface{}{ + "is_del": 0, + "project_id": projectId, + "instance_id.in": strings.Split(instanceIds, ","), + } + rRuleInstanceEntities, err := rMonitorRulesInstanceDao.GetAllRMonitorRulesInstance(logger, q1) + if err != nil { + logger.Warnf("DelRMonitorRuleInstances.GetAllRMonitorRulesInstance error, query:%s, error:%s", util.InterfaceToJson(q1), err.Error()) + } + + ri := map[string][]string{} + for _, rRuleInstanceEntity := range rRuleInstanceEntities { + _, ok := ri[rRuleInstanceEntity.RuleID] + if ok { + ri[rRuleInstanceEntity.RuleID] = append(ri[rRuleInstanceEntity.RuleID], rRuleInstanceEntity.InstanceID) + } else { + ri[rRuleInstanceEntity.RuleID] = []string{rRuleInstanceEntity.InstanceID} + } + } + + ruleIds := []string{} + for k, _ := range ri { + ruleIds = append(ruleIds, k) + } + qAll := map[string]interface{}{ + "is_del": 0, + "project_id": projectId, + "rule_id.in": ruleIds, + } + rRuleInstanceEntitiesAll, err := rMonitorRulesInstanceDao.GetAllRMonitorRulesInstance(logger, qAll) + if err != nil { + logger.Warnf("DelRMonitorRuleInstances.GetAllRMonitorRulesInstance2 error, query:%s, error:%s", util.InterfaceToJson(q1), err.Error()) + } + + //数据库动作 + u := map[string]interface{}{ + "is_del": 1, + } + if err := rMonitorRulesInstanceDao.UpdateMultiRMonitorRulesInstance(logger, q1, u); err != nil { + logger.Warnf("DelRMonitorRuleInstances.UpdateMultiRMonitorRulesInstance error, query:%s, error:%s", util.InterfaceToJson(q1), err.Error()) + return err + } + + riAll := map[string][]string{} + for _, rRuleInstanceEntity := range rRuleInstanceEntitiesAll { + _, ok := riAll[rRuleInstanceEntity.RuleID] + if ok { + riAll[rRuleInstanceEntity.RuleID] = append(riAll[rRuleInstanceEntity.RuleID], rRuleInstanceEntity.InstanceID) + } else { + riAll[rRuleInstanceEntity.RuleID] = []string{rRuleInstanceEntity.InstanceID} + } + } + + remainRuleInstances := map[string]struct{}{} + for k, v := range riAll { + v1 := ri[k] + if len(v1) == len(v) { //删除规则 + continue + } else { //规则里面还有其他实例,需要删除后重新下发 + remainRuleInstances[k] = struct{}{} + } + } + + //下发配置到proea + ruleidsStr := strings.Join(ruleIds, ",") + if err := DelRuleToPronoea(logger, ruleidsStr); err != nil { + logger.Warnf("DelRMonitorRuleInstances.DelRuleToPronoea error, ruleIds:%s, err:%s", ruleidsStr, err.Error()) + } + + toSendRules := []*response.Rule{} + for k, _ := range remainRuleInstances { + ruleEntity, err := monitorRuleDao.GetMonitorRuleById(logger, k) + + if err != nil { + logger.Warnf("DelRMonitorRuleInstances.GetMonitorRuleById error, ruleId:%s, error:%s", k, err.Error()) + continue + } + rule := RuleEntity2Rule(logger, ruleEntity, false) //这里会查ruleInstance表,所以上面的删除ruleInstance动作要放上面 + toSendRules = append(toSendRules, rule) + } + if len(toSendRules) > 0 { + if err := sendRulesToPronoea(logger, toSendRules); err != nil { + logger.Warnf("DelRMonitorRuleInstances.sendRulesToPronoea error, rules:%s, error:%s", util.InterfaceToJson(toSendRules), err.Error()) + } + } + + return nil +} + +type PronoeaRuleListRequest struct { + Source string `json:"source"` +} + +type PronoeaRuleListResponse struct { + Code int `json:"Code"` + RequestID string `json:"RequestId"` + Message string `json:"Message"` + Result PronoeaRulesList `json:"Result"` +} + +type PronoeaRulesList struct { + Rules []PronoeaRuleListItem `json:"rules"` +} + +type PronoeaRuleListItem struct { + RuleID string `json:"ruleId"` + InstanceIDs []string `json:"instanceIds"` +} + +type RuleDiffResponseItem struct { + PronoeaExist bool `json:"pronoeaExist"` + DaoExist bool `json:"daoExist"` +} + +func CheckDiffFromPronoea(logger *log.Logger) (map[string]map[string]RuleDiffResponseItem, error) { + url := monitorRuleListUrl + req := PronoeaRuleListRequest{ + Source: "bmpInBand", + } + logger.Infof("CheckDiffFromPronoea.PronoeaRuleListRequest:%s", util.InterfaceToJson(req)) + header := map[string]string{ + "Traceid": logger.GetPoint("logid").(string), + } + resp, err := util.DoHttpGet(logger, url, header, req) + if err != nil { + logger.Warnf("sendRuleToPronoea post error:%s", err.Error()) + return nil, err + } + logger.Infof("sendRuleToPronoea resp:%s", string(resp)) + pronoeaRes := &PronoeaRuleListResponse{} + if err := json.Unmarshal(resp, pronoeaRes); err != nil { + logger.Warnf("CheckDiffFromPronoea.PronoeaRuleListResponse unmarshal error:%s", err.Error()) + return nil, err + } + + finalRes := make(map[string]map[string]RuleDiffResponseItem) + for _, rule := range pronoeaRes.Result.Rules { + _, ok := finalRes[rule.RuleID] + if !ok { + finalRes[rule.RuleID] = make(map[string]RuleDiffResponseItem) + } + for _, instanceId := range rule.InstanceIDs { + v, ok := finalRes[rule.RuleID][instanceId] + if !ok { + finalRes[rule.RuleID][instanceId] = RuleDiffResponseItem{ + PronoeaExist: true, + } + } else { + v.PronoeaExist = true + finalRes[rule.RuleID][instanceId] = v + } + } + } + + rMonitorRulesInstanceEntities, err := rMonitorRulesInstanceDao.GetAllRMonitorRulesInstanceEffective(logger) + if err != nil { + logger.Warnf("CheckDiffFromPronoea.GetAllRMonitorRulesInstance error:%s", err.Error()) + return nil, err + } + for _, rMonitorRulesInstanceEntity := range rMonitorRulesInstanceEntities { + _, ok := finalRes[rMonitorRulesInstanceEntity.RuleID] + if !ok { + finalRes[rMonitorRulesInstanceEntity.RuleID] = make(map[string]RuleDiffResponseItem) + } + instanceId := rMonitorRulesInstanceEntity.InstanceId + v, ok := finalRes[rMonitorRulesInstanceEntity.RuleID][instanceId] + if !ok { + finalRes[rMonitorRulesInstanceEntity.RuleID][instanceId] = RuleDiffResponseItem{ + DaoExist: true, + } + } else { + v.DaoExist = true + finalRes[rMonitorRulesInstanceEntity.RuleID][instanceId] = v + } + } + return finalRes, nil +} diff --git a/bmp-openapi-console/logic/osLogic/osLogic.go b/bmp-openapi-console/logic/osLogic/osLogic.go new file mode 100644 index 0000000..e066314 --- /dev/null +++ b/bmp-openapi-console/logic/osLogic/osLogic.go @@ -0,0 +1,68 @@ +package osLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + osDao "coding.jd.com/aidc-bmp/bmp-openapi/dao/osDao" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func OsEntity2OS(o *osDao.Os, tz string) *responseTypes.Os { + return &responseTypes.Os{ + ID: o.ID, + OsID: o.OsID, + OsName: o.OsName, + OsType: o.OsType, + OsVersion: o.OsVersion, + + Architecture: o.Architecture, + Bits: o.Bits, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + } +} + +func GetByOsId(logger *log.Logger, osId string) (*responseTypes.Os, error) { + tz := logger.GetPoint("timezone").(string) + entity, err := osDao.GetOsByUuid(logger, osId) + if err != nil { + logger.Warn("GetOsByUuid sql error:", osId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + return OsEntity2OS(entity, tz), nil +} +func GetOsByUuid(logger *log.Logger, osid string) (o *osDao.Os, err error) { + entity, err := osDao.GetOsByUuid(logger, osid) + return entity, err +} + +func GetAndCheckById(logger *log.Logger, os_id string) (*responseTypes.Os, error) { + os, err := GetByOsId(logger, os_id) + if err != nil { + return nil, err + } + return os, nil + +} + +func DescribeOSs(logger *log.Logger, param *requestTypes.QueryOssRequest) ([]*responseTypes.Os, error) { + + tz := logger.GetPoint("timezone").(string) + query := map[string]interface{}{ + "os_name": param.OsName, + "os_type": param.OsType, + "os_version": param.OsVersion, + "is_del": 0, + } + os_entity_list, err := osDao.GetAllOs(logger, query) //osDao.GetMultiOs(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 1000) + if err != nil { + logger.Warn("QueryByOsIds GetAllOs sql error:", err.Error()) + return nil, err + } + oss := []*responseTypes.Os{} + for _, entity := range os_entity_list { + oss = append(oss, OsEntity2OS(entity, tz)) + } + return oss, nil +} diff --git a/bmp-openapi-console/logic/projectLogic/projectLogic.go b/bmp-openapi-console/logic/projectLogic/projectLogic.go new file mode 100644 index 0000000..fe61157 --- /dev/null +++ b/bmp-openapi-console/logic/projectLogic/projectLogic.go @@ -0,0 +1,798 @@ +package projectLogic + +import ( + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/projectDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/sharingProjectDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorRuleLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/userLogic" + + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + namespacePrefix "git.jd.com/cps-golang/ironic-common/ironic/common/NamespacePrefixs" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +func ProjectEntity2Project(logger *log.Logger, o *projectDao.Project, shareproject []*sharingProjectDao.SharingProject) *responseTypes.Project { + + u, err := userLogic.GetUserById(logger, o.UserID) + if err != nil { + logger.Warnf("Project.UserID get invalid, project_id:%s, user_id:%s, err:%s", o.ProjectID, o.UserID, err.Error()) + return nil + } + + tz := logger.GetPoint("timezone").(string) + shares := []responseTypes.ShareProject{} + owned := 2 + + var cnt int64 + if logger.GetPoint("userId").(string) == o.UserID { //拥有者身份 + //拥有者 + owned = 1 + query := map[string]interface{}{ + "is_del": 0, + "project_id": o.ProjectID, + } + cnt, err = instanceLogic.GetInstanceCount(logger, query) + if err != nil { + logger.Warnf("instanceLogic.GetInstanceCount error:%s", err.Error()) + } + + for _, v := range shareproject { + shares = append(shares, responseTypes.ShareProject{ + ProjectName: v.ProjectName, + ProjectID: v.ProjectID, + OwnerUserID: v.OwnerUserID, + OwnerUserName: v.OwnerUserName, + SharedUserID: v.SharedUserID, + SharedUserName: v.SharedUserName, + CreatedTime: util.TimestampToString(int64(v.CreatedTime), tz), + SharedInstanceIDs: v.SharedInstanceIDs, + }) + } + } else { //协作者身份 + for _, v := range shareproject { + if v.SharedUserID == logger.GetPoint("userId").(string) { + if v.SharedInstanceIDs != "" { + cnt = int64(len(strings.Split(v.SharedInstanceIDs, ","))) + } + } + } + } + + return &responseTypes.Project{ + ID: o.ID, + ProjectName: o.ProjectName, + Description: o.Description, + ProjectID: o.ProjectID, + InstanceCount: cnt, + ShareProjects: shares, + Owned: owned, + CreatedBy: o.CreatedBy, + OwnedBy: u.UserName, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + UpdatedBy: o.UpdatedBy, + UpdatedTime: util.TimestampToString(int64(o.UpdatedTime), tz), + } +} + +//只带owned标志位,不关心sharing具体内容 +func ProjectListEntity2Project(logger *log.Logger, o *projectDao.AllProject) *responseTypes.Project { + + userId := logger.GetPoint("userId").(string) + tz := logger.GetPoint("timezone").(string) + query := map[string]interface{}{ + "is_del": 0, + "project_id": o.ProjectID, + } + var cnt int64 + var err error + var shareAll bool + if o.Owned == 2 { //共享,考虑部分共享的情况 + s, err := sharingProjectDao.GetOneSharingProject(logger, o.ProjectID, "", userId) + if err != nil { + logger.Warnf("GetOneSharingProject error:%s", err.Error()) + } + if s.SharedInstanceIDs == "" { + cnt = 0 + } else { + instanceids := strings.Split(s.SharedInstanceIDs, ",") + cnt = int64(len(instanceids)) + } + } + + if o.Owned == 1 || shareAll { + cnt, err = instanceLogic.GetInstanceCount(logger, query) + if err != nil { + logger.Warnf("instanceLogic.GetInstanceCount error:%s", err.Error()) + } + } + + shares := []responseTypes.ShareProject{} + + return &responseTypes.Project{ + ID: o.ID, + ProjectName: o.ProjectName, + ProjectID: o.ProjectID, + InstanceCount: cnt, + ShareProjects: shares, + Owned: o.Owned, + CreatedBy: o.CreatedBy, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + UpdatedBy: o.UpdatedBy, + UpdatedTime: util.TimestampToString(int64(o.UpdatedTime), tz), + } +} + +func GetProjectById(logger *log.Logger, ProjectId string) (*responseTypes.Project, error) { + entity, err := projectDao.GetProjectById(logger, ProjectId) + if err != nil { + logger.Warn("GetProjectByUuid sql error:", ProjectId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + shareEntity, err := sharingProjectDao.GetSharingsByProjectId(logger, ProjectId) + if err != nil { + logger.Warnf("GetProjectById.GetSharingsByProjectId error, project_id:%s, error:%s", ProjectId, err.Error()) + } + return ProjectEntity2Project(logger, entity, shareEntity), nil +} + +func CreateProject(logger *log.Logger, param *requestTypes.CreateProjectRequest, extraUserId string) (string, error) { + + var userId string + if extraUserId == "" { + userId = logger.GetPoint("userId").(string) + } else { + userId = extraUserId //兼容创建用户时创建默认项目,因为此时项目所属的userid不是当前登录用户的userid + } + // project_name不做唯一性限制 + // list, _ := projectDao.GetAllProject(logger, map[string]interface{}{ + // "project_name": param.ProjectName, + // "user_id": userId, + // "is_del": 0, + // }) + // if len(list) != 0 { + // logger.Warn("projectName exist:", param.ProjectName) + // panic(constant.BuildInvalidArgumentWithArgs("项目名称已存在", "projectName exist")) + // } + if param.IsDefault == 1 { + list, _ := projectDao.GetAllProject(logger, map[string]interface{}{ + "is_default": 1, + "user_id": userId, + "is_del": 0, + }) + if len(list) != 0 { + logger.Warn("默认项目 exist:", param.ProjectName) + panic(constant.BuildInvalidArgumentWithArgs("默认项目只能有一个", "defaultProject only exist one")) + } + } + ProjectEntity := &projectDao.Project{ + UserID: userId, + ProjectName: param.ProjectName, + IsDefault: param.IsDefault, + IsSystem: param.IsSystem, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + ProjectEntity.ProjectID = commonUtil.GetRandString("project-", namespacePrefix.INSTANCE_ID_LENGTH, false, true, true) + + if _, err := projectDao.AddProject(logger, ProjectEntity); err != nil { + logger.Warnf("CreateProject AddProject sql error, entity:%s, error:%s", util.ObjToJson(ProjectEntity), err.Error()) + return "", err + } + return ProjectEntity.ProjectID, nil +} + +func ModifyProject(logger *log.Logger, param *requestTypes.ModifyProjectRequest, ProjectId string) error { + userId := logger.GetPoint("userId").(string) + p, err := projectDao.GetProjectById(logger, ProjectId) + if err != nil { + logger.Warn("GetProjectByUuid sql error:", ProjectId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if p.UserID != userId { + panic(constant.PermissionDenyForObject) + } + + // list, _ := projectDao.GetAllProject(logger, map[string]interface{}{ + // "project_name": param.ProjectName, + // "user_id": userId, + // "is_del": 0, + // }) + // if len(list) != 0 { + // logger.Warn("projectName exist:", param.ProjectName) + // panic(constant.BuildInvalidArgumentWithArgs("项目名称已存在", "projectName exist")) + // } + + p.ProjectName = param.ProjectName + p.UpdatedBy = logger.GetPoint("username").(string) + p.UpdatedTime = int(time.Now().Unix()) + if err := projectDao.UpdateProjectById(logger, p); err != nil { + logger.Warn("ModifyProject UpdateProjectById sql error:", ProjectId, err.Error()) + return err + } + + q := map[string]interface{}{ + "is_del": 0, + "project_id": p.ProjectID, + } + u := map[string]interface{}{ + "project_name": param.ProjectName, + } + if err := sharingProjectDao.UpdateMultiShareProjects(logger, q, u); err != nil { + logger.Warn("ModifyProject UpdateMultiShareProjects sql error:", ProjectId, err.Error()) + return err + } + + return nil +} + +func ModifyProjectDescription(logger *log.Logger, param *requestTypes.ModifyProjectDescriptionRequest, ProjectId string) error { + userId := logger.GetPoint("userId").(string) + p, err := projectDao.GetProjectById(logger, ProjectId) + if err != nil { + logger.Warn("GetProjectByUuid sql error:", ProjectId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if p.UserID != userId { + panic(constant.PermissionDenyForObject) + } + + p.Description = param.Description + p.UpdatedBy = logger.GetPoint("username").(string) + p.UpdatedTime = int(time.Now().Unix()) + if err := projectDao.UpdateProjectById(logger, p); err != nil { + logger.Warn("ModifyProjectDescription UpdateProjectById sql error:", ProjectId, err.Error()) + return err + } + return nil +} + +/* + 删除项目时,有如下要求: + 1,默认项目也可以删除。如果删除的是默认项目,则自动选一个最早的项目作为默认项目 + 2,每个用户至少保留一个项目。 + 3,项目下如果有资源则不可删除 +*/ + +func DeleteProject(logger *log.Logger, ProjectId string) error { + userId := logger.GetPoint("userId").(string) + query := map[string]interface{}{ + "user_id": userId, + "is_del": 0, + } + entities, err := projectDao.GetAllProject(logger, query) + if err != nil { + panic(constant.INTERNAL_ERROR) + } + idx := -1 + for i, entity := range entities { + if entity.ProjectID == ProjectId { + idx = i + } + } + if idx == -1 { + panic(constant.PermissionDenyForObject) + } + if len(entities) < 2 { + panic(constant.BuildCANCELLEDWithArgs("每个用户至少保留一个项目", "at least one project remained for user")) + } + + instanceQuery := map[string]interface{}{ + "project_id": ProjectId, + "is_del": 0, + } + instanceCnt, err := instanceDao.GetInstanceCount(logger, instanceQuery) + if err != nil { + panic(constant.INTERNAL_ERROR) + } + if instanceCnt > 0 { + panic(constant.BuildCANCELLEDWithArgs("项目下有资源不可删除", "project contains resource, please release resource first")) + } + + deleteEntity := entities[idx] + defaultEntity := entities[0] + if idx == 0 { + defaultEntity = entities[1] + } + + deleteEntity.IsDel = 1 + deleteEntity.UpdatedTime = int(time.Now().Unix()) + deleteEntity.DeletedTime = int(time.Now().Unix()) + if err := projectDao.UpdateProjectById(logger, deleteEntity); err != nil { + logger.Warn("DeleteProject1 UpdateProjectById sql error:", ProjectId, err.Error()) + return err + } + defaultEntity.IsDefault = 1 + defaultEntity.UpdatedTime = int(time.Now().Unix()) + defaultEntity.DeletedTime = int(time.Now().Unix()) + if err := projectDao.UpdateProjectById(logger, defaultEntity); err != nil { + logger.Warn("DeleteProject2 UpdateProjectById sql error:", ProjectId, err.Error()) + return err + } + + //删除项目时,此项目的共享关系都删除 + if err := sharingProjectDao.DeleteSharingProjectByProjectId(logger, ProjectId); err != nil { + logger.Warn("DeleteSharingProjectByProjectId sql error:", ProjectId, err.Error()) + return err + } + + userEntity, err := userDao.GetUserById(logger, userId) + if err != nil { + logger.Warn("DeleteProject GetUserById error:", userId, err.Error()) + return err + } + userEntity.DefaultProjectID = defaultEntity.ProjectID + if err := userDao.UpdateUserById(logger, userEntity); err != nil { + logger.Warn("DeleteProject UpdateUser's defaultProjectById error:", userId, ProjectId, err.Error()) + return err + } + + return nil +} + +func GetProjectList(logger *log.Logger, param requestTypes.QueryProjectsRequest, p util.Pageable) ([]*responseTypes.Project, int64, error) { + userId := logger.GetPoint("userId").(string) + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "user_id": userId, + "is_del": 0, + } + if param.ProjectName != "" { + query["project_name"] = param.ProjectName + } + //新增按用户名查找拥有的项目列表 + if param.OwnerName != "" { + ownerUser, _ := userLogic.GetUserByName(logger, &requestTypes.GetUserByNameRequest{ + UserName: param.OwnerName, + }) + if ownerUser != nil { + userId = ownerUser.UserID + param.Owned = 1 + } + } + //新增按被转移用户的用户名查找它拥有的项目列表 + if param.SharerName != "" { + sharerUser, _ := userLogic.GetUserByName(logger, &requestTypes.GetUserByNameRequest{ + UserName: param.SharerName, + }) + if sharerUser != nil { + userId = sharerUser.UserID + param.Owned = 1 + } + } + + count, err := projectDao.GetProjectAndSharedCount(logger, userId, param.Owned) + if err != nil { + logger.Warnf("GetProjectCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + var entityList []*projectDao.AllProject + + var sortby []string + var order []string + if param.OrderByCreatetime == "desc" { + sortby = []string{"c.created_time"} + order = []string{"desc"} + } else { + sortby = []string{"c.created_time"} + order = []string{"asc"} + } + + if param.IsAll == baseLogic.IS_ALL { + entityList, err = projectDao.GetMultiProjectIncludeShare(logger, userId, param.Owned, sortby, order, 0, 0) + } else { + entityList, err = projectDao.GetMultiProjectIncludeShare(logger, userId, param.Owned, sortby, order, offset, limit) + } + + if err != nil { + logger.Warnf("GetMultiProjectIncludeShare sql error, user_id:%s, error:%s", userId, err.Error()) + return nil, 0, err + } + Projects := []*responseTypes.Project{} + var defaultProject *responseTypes.Project + for _, entity := range entityList { + // shareEntity, err := sharingProjectDao.GetSharingsByProjectId(logger, entity.ProjectID) + if err != nil { + logger.Warnf("GetProjectList.GetSharingsByProjectId error, project_id:%s, error:%s", entity.ProjectID, err.Error()) + } + if entity.IsDefault == 1 { + defaultProject = ProjectListEntity2Project(logger, entity) + } else { + Projects = append(Projects, ProjectListEntity2Project(logger, entity)) + } + } + if defaultProject == nil { + return Projects, count, nil + } + + return append([]*responseTypes.Project{defaultProject}, Projects...), count, nil +} + +func AddShareProject(logger *log.Logger, projectID string, param *requestTypes.ShareProjectRequest) error { + project, err := projectDao.GetProjectById(logger, projectID) + if err != nil { + logger.Warnf("addShareProject.GetProjectById error, project_id:%s, error:%s", projectID, err.Error()) + panic(constant.BuildCANCELLEDWithArgs("项目不存在", "project not found")) + } + owner, err := userDao.GetUserById(logger, param.OwnerID) + if err != nil { + logger.Warnf("addShareProject.GetUserById error, owner_id:%s, error:%s", param.OwnerID, err.Error()) + panic(constant.BuildCANCELLEDWithArgs("用户不存在", "user not found")) + } + sharer, err := userDao.GetUserById(logger, param.SharerID) + if err != nil { + logger.Warnf("addShareProject.GetUserById error, sharer_id:%s, error:%s", param.OwnerID, err.Error()) + panic(constant.BuildCANCELLEDWithArgs("用户不存在", "user not found")) + } + + if project.UserID == param.SharerID { + panic(constant.BuildCANCELLEDWithArgs("项目不能分享给自己", "project can not shared to the project owner")) + } + + //只有分享给控制台用户 + if sharer.RoleID == baseLogic.ROLE_OPERATOR_UUID { + panic(constant.BuildCANCELLEDWithArgs("目标用户没有控制台访问权限", "target user access denied for console")) + } + + q1 := map[string]interface{}{ + "is_del": 0, + "project_id": projectID, + } + instanceEntities, err := instanceDao.GetAllInstance(logger, q1) + if err != nil { + logger.Warnf("AddShareProject.GetAllInstance error, query.project_id:%s, error:%s", projectID, err.Error()) + } + + nowInstanceIds := make([]string, len(instanceEntities)) + for idx, instanceEntity := range instanceEntities { + nowInstanceIds[idx] = instanceEntity.InstanceID + } + + if param.InstanceIDs == "all" { + + param.InstanceIDs = strings.Join(nowInstanceIds, ",") + } else if param.InstanceIDs != "" { //校验instanceid合法性 + instanceIds := strings.Split(param.InstanceIDs, ",") + + if len(instanceIds) > len(nowInstanceIds) { + logger.Warnf("实例id参数校验错误, instanceIds:%v", instanceIds) + panic(constant.BuildCANCELLEDWithArgs("实例id参数校验错误", "instanceId param error")) + } + for _, v := range instanceIds { + if !util.InArray(v, nowInstanceIds) { + logger.Warnf("实例id参数校验错误, instanceId:%s", v) + panic(constant.BuildCANCELLEDWithArgs("实例id参数校验错误", "instanceId param error")) + } + } + } + + spEntity, err := sharingProjectDao.GetOneSharingProject(logger, projectID, param.OwnerID, param.SharerID) + + if spEntity == nil { //新增 + sp := &sharingProjectDao.SharingProject{ + ProjectID: projectID, + OwnerUserID: param.OwnerID, + SharedUserID: param.SharerID, + OwnerUserName: owner.UserName, + SharedUserName: sharer.UserName, + // Premission: param.Premisson, //本版本只支持write + Premission: "write", //本版本只支持write + ProjectName: project.ProjectName, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + SharedInstanceIDs: param.InstanceIDs, + } + _, err = sharingProjectDao.AddSharingProject(logger, sp) + if err != nil { + logger.Warnf("addShareProject.AddSharingProject error, project_id:%s, owner_id:%s, sharer_id:%s, error:%s", projectID, param.OwnerID, param.SharerID, err.Error()) + panic(constant.INTERNAL_ERROR) + } + } else { //修改 + q := map[string]interface{}{ + "is_del": 0, + "project_id": projectID, + "owner_user_id": param.OwnerID, + "shared_user_id": param.SharerID, + } + u := map[string]interface{}{ + "shared_instance_ids": param.InstanceIDs, + } + err = sharingProjectDao.UpdateShareProjectByMap(logger, q, u) + if err != nil { + logger.Warnf("addShareProject.UpdateShareProjectByMap error, project_id:%s, owner_id:%s, sharer_id:%s, error:%s", projectID, param.OwnerID, param.SharerID, err.Error()) + panic(constant.INTERNAL_ERROR) + } + } + + return nil +} + +func CancelShareProject(logger *log.Logger, projectID string, param *requestTypes.CalcelShareProjectRequest) (err error) { + + sp, err := sharingProjectDao.GetOneSharingProject(logger, projectID, param.OwnerID, param.SharerID) + if err != nil { + logger.Warnf("shared project not found, projectID:%s, OwnerID:%s, SharerID:%s, error:%s", projectID, param.OwnerID, param.SharerID, err.Error()) + panic(constant.BuildCANCELLEDWithArgs("共享项目不存在", "shared project not found")) + } + err = sharingProjectDao.DeleteOneSharingProject(logger, sp) + if err != nil { + logger.Warnf("CreateShareProject.DeleteSharingProject error, project_id:%s, owner_id:%s, sharer_id:%s, error:%s", projectID, param.OwnerID, param.SharerID, err.Error()) + panic(constant.INTERNAL_ERROR) + } + return nil +} + +func DescribeShareProject(logger *log.Logger, projectID string) ([]*sharingProjectDao.SharingProject, error) { + q := map[string]interface{}{ + "is_del": 0, + "project_id": projectID, + } + + return sharingProjectDao.GetAllShareProjects(logger, q) + +} + +//项目转移时,项目下面的规则全部失效 +func MoveProject(logger *log.Logger, projectID string, param *requestTypes.MoveProjectRequest) error { + + project, err := projectDao.GetProjectById(logger, projectID) + if err != nil { + logger.Warnf("CreateShareProject.GetProjectById error, project_id:%s, error:%s", projectID, err.Error()) + panic(constant.BuildCANCELLEDWithArgs("项目不存在", "project not found")) + } + owner, err := userDao.GetUserById(logger, param.OwnerID) + if err != nil { + logger.Warnf("CreateShareProject.GetUserById error, owner_id:%s, error:%s", param.OwnerID, err.Error()) + panic(constant.BuildCANCELLEDWithArgs("用户不存在", "user not found")) + } + mover, err := userDao.GetUserById(logger, param.MoverID) + if err != nil { + logger.Warnf("CreateShareProject.GetUserById error, sharer_id:%s, error:%s", param.OwnerID, err.Error()) + panic(constant.BuildCANCELLEDWithArgs("用户不存在", "user not found")) + } + + if project.UserID == param.MoverID { + panic(constant.BuildCANCELLEDWithArgs("项目不能转移给自己", "project can not shared to the project owner")) + } + + //只有转移给控制台用户 + if mover.RoleID == baseLogic.ROLE_OPERATOR_UUID { + panic(constant.BuildCANCELLEDWithArgs("目标用户没有控制台访问权限", "target user access denied for console")) + } + + //如果只有一个项目,禁止转移 + projects, _ := projectDao.GetAllProjectByUserId(logger, param.OwnerID) + if len(projects) == 0 { + panic(constant.BuildCANCELLEDWithArgs("目标用户下无项目", "no project for current user")) + } + if len(projects) == 1 { + panic(constant.BuildCANCELLEDWithArgs("目标用户只此一个项目,不支持转移", "operation denied, only one project for current user")) + } + + sp, _ := sharingProjectDao.GetOneSharingProject(logger, projectID, param.OwnerID, param.MoverID) + if sp != nil { + //TODO 需要删除共享信息 + sp.IsDel = 1 + err = sharingProjectDao.DeleteOneSharingProject(logger, sp) + if err != nil { + logger.Warnf("CreateShareProject.DeleteOneSharingProject error, project_id:%s, owner_id:%s, sharer_id:%s, error:%s", projectID, param.OwnerID, param.MoverID, err.Error()) + panic(constant.INTERNAL_ERROR) + } + } + + // 更改该project的其他已有共享信息 + q := map[string]interface{}{ + "is_del": 0, + "project_id": projectID, + } + u := map[string]interface{}{ + "owner_user_id": param.MoverID, + "owner_user_name": mover.UserName, + } + if err := sharingProjectDao.UpdateMultiShareProjects(logger, q, u); err != nil { + logger.Warnf("CreateShareProject.UpdateMultiShareProjects error, project_id:%s, owner_id:%s, sharer_id:%s, error:%s", projectID, param.OwnerID, param.MoverID, err.Error()) + panic(constant.INTERNAL_ERROR) + } + + //project下实例的user_id更新 + iq := map[string]interface{}{ + "is_del": 0, + "project_id": projectID, + } + iu := map[string]interface{}{ + "user_id": param.MoverID, + } + if err := instanceDao.UpdateInstances(logger, iq, iu); err != nil { + logger.Warnf("moveProject.UpdateInstances error, project_id:%s, error:%s", projectID, err.Error()) + } + + //项目改成非默认项目 + u = map[string]interface{}{ + "user_id": param.MoverID, + "is_default": 0, + } + if err := projectDao.UpdateProjectByMap(logger, q, u); err != nil { + logger.Warnf("moveProject.UpdateProjectByMap error, project_id:%s, owner_id:%s, mover_id:%s, error:%s", projectID, param.OwnerID, param.MoverID, err.Error()) + panic(constant.INTERNAL_ERROR) + } + if project.IsDefault == 1 { //如果是默认项目被转移的话,需要选一个新的默认项目 + newDefaultProject := projects[0] + if newDefaultProject.ProjectID == projectID { + newDefaultProject = projects[1] + } + newDefaultProject.IsDefault = 1 + if err := projectDao.UpdateProjectById(logger, newDefaultProject); err != nil { + logger.Warnf("moveProject.UpdatedefaultProject error, project_id:%s, owner_id:%s, mover_id:%s, error:%s, new_default_project_id:%s", projectID, param.OwnerID, param.MoverID, err.Error(), newDefaultProject.ProjectID) + // panic(constant.INTERNAL_ERROR) + } + owner.DefaultProjectID = newDefaultProject.ProjectID + if err := userDao.UpdateUserById(logger, owner); err != nil { + logger.Warnf("moveProject.UpdatedefaultProjectfor user error, project_id:%s, owner_id:%s, mover_id:%s, error:%s, new_default_project_id:%s", projectID, param.OwnerID, param.MoverID, err.Error(), newDefaultProject.ProjectID) + // panic(constant.INTERNAL_ERROR) + } + } + + if err := monitorRuleLogic.DelMonitorRulesByProjectID(logger, projectID); err != nil { + logger.Warnf("moveProject.DelMonitorRulesByProjectID error, project_id:%s, owner_id:%s, mover_id:%s, error:%s", projectID, param.OwnerID, param.MoverID, err.Error()) + } + + return nil +} + +//项目部分转移时,规则下面的被转移实例被摘除 +func MoveInstances(logger *log.Logger, param *requestTypes.MoveInstancesRequest) error { + + ownerProject, err := projectDao.GetProjectById(logger, param.OwnerProjectID) + if err != nil { + logger.Warnf("MoveInstances.GetProjectById error, project_id:%s, error:%s", param.OwnerProjectID, err.Error()) + panic(constant.BuildCANCELLEDWithArgs("项目不存在", "project not found")) + } + _, err = userDao.GetUserById(logger, param.OwnerID) + if err != nil { + logger.Warnf("MoveInstances.GetUserById error, owner_id:%s, error:%s", param.OwnerID, err.Error()) + panic(constant.BuildCANCELLEDWithArgs("用户不存在", "user not found")) + } + if ownerProject.UserID != param.OwnerID { + logger.Warnf("MoveInstances ower_id not match with owner_project_id, owner_id:%s, owner_project_id:%s", param.OwnerID, param.OwnerProjectID) + panic(constant.BuildCANCELLEDWithArgs("owner用户和项目不匹配", "owner user not match with project")) + } + + moverProject, err := projectDao.GetProjectById(logger, param.MoverProjectID) + if err != nil { + logger.Warnf("MoveInstances.GetProjectById error, project_id:%s, error:%s", param.OwnerProjectID, err.Error()) + panic(constant.BuildCANCELLEDWithArgs("项目不存在", "project not found")) + } + mover, err := userDao.GetUserById(logger, param.MoverID) + if err != nil { + logger.Warnf("CreateShareProject.GetUserById error, sharer_id:%s, error:%s", param.OwnerID, err.Error()) + panic(constant.BuildCANCELLEDWithArgs("用户不存在", "user not found")) + } + if moverProject.UserID != param.MoverID { + logger.Warnf("MoveInstances mover not match with mover_project_id, mover_id:%s, mover_project_id:%s", param.MoverID, param.MoverProjectID) + panic(constant.BuildCANCELLEDWithArgs("mover用户和项目不匹配", "move user not match with project")) + } + + // if moverProject.UserID == param.MoverID { + // panic(constant.BuildCANCELLEDWithArgs("项目不能转移给自己", "project can not shared to the project owner")) + // } + + //只有转移给控制台用户 + if mover.RoleID == baseLogic.ROLE_OPERATOR_UUID { + panic(constant.BuildCANCELLEDWithArgs("目标用户没有控制台访问权限", "target user access denied for console")) + } + + moveInstanceIds := []string{} + if param.InstanceIDs != "" { + moveInstanceIds = strings.Split(param.InstanceIDs, ",") + } + //直接将instance改成新的project_id + q := map[string]interface{}{ + "is_del": 0, + "instance_id.in": moveInstanceIds, + } + updates := map[string]interface{}{ + "project_id": param.MoverProjectID, + "user_id": param.MoverID, + } + if err := instanceDao.UpdateInstances(logger, q, updates); err != nil { + logger.Warnf("moveInstance.UpdateInstances error, instance_ids:%s, project_id:%s, user_id:%s, error:%s", param.InstanceIDs, param.MoverProjectID, param.MoverID, err.Error()) + panic(constant.INTERNAL_ERROR) + } + + //param.InstanceIDs 之前如果被共享给其他用户,则共享关系也要改变,实例的原共享关系废除,新共享关系建立 + q2 := map[string]interface{}{ + "project_id": param.OwnerProjectID, + "owner_user_id": param.OwnerID, + } + shareProjectEntities, err := sharingProjectDao.GetAllShareProjects(logger, q2) + if err != nil { + logger.Warnf("MoveInstances.GetAllShareProjects error, project_id:%s, owner_user_id:%s, error:%s", param.OwnerProjectID, param.OwnerID, err.Error()) + } + for _, spEntity := range shareProjectEntities { + shareInstanceIds := []string{} + + if spEntity.SharedInstanceIDs != "" { + shareInstanceIds = strings.Split(spEntity.SharedInstanceIDs, ",") + } + + innerInstanceIds := util.IntersectArray(shareInstanceIds, moveInstanceIds) //交集 + //innerInstanceIds这部分从老的shareproject移除 + remainShareInstancesIds := util.DifferenceArray(shareInstanceIds, innerInstanceIds) + spEntity.SharedInstanceIDs = strings.Join(remainShareInstancesIds, ",") + //spEntity.SharedInstanceIDs可能为空,所以用UpdateShareProjectByMap,不用UpdateShareProjectById + + tq := map[string]interface{}{ + "project_id": spEntity.ProjectID, + "shared_user_id": spEntity.SharedUserID, + "is_del": 0, + } + tu := map[string]interface{}{ + "shared_instance_ids": spEntity.SharedInstanceIDs, + } + if err := sharingProjectDao.UpdateShareProjectByMap(logger, tq, tu); err != nil { + logger.Warnf("moveInstance.UpdateShareProjectByMap.ShareInstancesIds error, project_id:%s, owner_user_id:%s, shareInstanceIds:%v, error:%s", param.OwnerProjectID, param.OwnerID, spEntity.SharedInstanceIDs, err.Error()) + } + + //innerInstanceIds这部分的ownerid要变更,需更新/插入shareproject + if param.MoverID == spEntity.SharedUserID { //之前的共享人和现在的拥有者是同一个人的话,不用再添加共享 + continue + } + sp1, _ := sharingProjectDao.GetOneSharingProject(logger, param.MoverProjectID, param.MoverID, spEntity.SharedUserID) + if sp1 != nil { //更新 + shareInstanceIds := util.UnionArray(innerInstanceIds, strings.Split(sp1.SharedInstanceIDs, ",")) + sp1.SharedInstanceIDs = strings.TrimSpace(strings.Join(shareInstanceIds, ",")) + tq := map[string]interface{}{ + "project_id": sp1.ProjectID, + "shared_user_id": sp1.SharedUserID, + "is_del": 0, + } + tu := map[string]interface{}{ + "shared_instance_ids": sp1.SharedInstanceIDs, + } + if err := sharingProjectDao.UpdateShareProjectByMap(logger, tq, tu); err != nil { + logger.Warnf("moveInstance.UpdateShareProject.UpdateShareProjectByMap2 error, project_id:%s, owner_user_id:%s, shareInstanceIds:%v, error:%s", param.MoverProjectID, param.MoverID, sp1.SharedInstanceIDs, err.Error()) + } + + } else { //插入 + sp := &sharingProjectDao.SharingProject{ + ProjectID: param.MoverProjectID, + OwnerUserID: param.MoverID, + SharedUserID: spEntity.SharedUserID, + OwnerUserName: mover.UserName, + SharedUserName: spEntity.SharedUserName, + // Premission: param.Premisson, //本版本只支持write + Premission: "write", //本版本只支持write + ProjectName: spEntity.ProjectName, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + SharedInstanceIDs: strings.TrimSpace(strings.Join(innerInstanceIds, ",")), + } + _, err = sharingProjectDao.AddSharingProject(logger, sp) + if err != nil { + logger.Warnf("moveInstance.AddSharingProject error, project_id:%s, owner_id:%s, sharer_id:%s, shareInstanceids:%v, error:%s", param.MoverProjectID, param.MoverID, spEntity.SharedUserID, innerInstanceIds, err.Error()) + } + } + } + + if err := monitorRuleLogic.DelRMonitorRuleInstances(logger, param.OwnerProjectID, param.InstanceIDs); err != nil { + logger.Warnf("moveInstance.DelRMonitorRuleInstances error, project_id:%s, owner_id:%s, mover_id:%s, instanceids:%v, error:%s", param.MoverProjectID, param.OwnerID, param.MoverID, param.InstanceIDs, err.Error()) + } + + return nil +} diff --git a/bmp-openapi-console/logic/raidLogic/raidLogic.go b/bmp-openapi-console/logic/raidLogic/raidLogic.go new file mode 100644 index 0000000..a6f8c7f --- /dev/null +++ b/bmp-openapi-console/logic/raidLogic/raidLogic.go @@ -0,0 +1,31 @@ +package raidLogic + +import ( + raidDao "coding.jd.com/aidc-bmp/bmp-openapi/dao/raidDao" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func DRaid2Raid(d *raidDao.DRaid) *responseTypes.Raid { + return &responseTypes.Raid{ + //RaidID: d.RaidId, + //Name: d.Name, + //DescriptionEn: d.DescriptionEn, + //DescriptionZh: d.DescriptionZh, + //DeviceType: d.DeviceType, + //VolumeType: d.VolumeType, + //VolumeDetail: d.VolumeDetail, + //SystemPartitionCount: d.SystemPartitionCount, + //AvailableValue: d.AvailableValue, + //DiskType: d.DiskType, + } +} + +func GetRaidEntityByRaidId(logger *log.Logger, raidId string) (*raidDao.Raid, error) { + entity, err := raidDao.GetRaidByUuid(logger, raidId) + if err != nil { + logger.Warn("GetRaidByUuid sql error:", raidId, err.Error()) + return nil, err + } + return entity, nil +} diff --git a/bmp-openapi-console/logic/resourceLogic/resourceLogic.go b/bmp-openapi-console/logic/resourceLogic/resourceLogic.go new file mode 100644 index 0000000..2ac9d24 --- /dev/null +++ b/bmp-openapi-console/logic/resourceLogic/resourceLogic.go @@ -0,0 +1,56 @@ +package resourceLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceTypeDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/imageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + "fmt" +) + +func DescribeResources(logger *log.Logger, param *requestTypes.QueryResourcesRequest) (int, error) { + query := map[string]interface{}{} + if param.Name != "" { + query["name"] = param.Name + list, err := deviceTypeDao.GetAllDeviceType(logger, query) + if err != nil { + logger.Warnf("GetAllDeviceType error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return 0, err + } + fmt.Println("查询到的数量", len(list)) + return len(list), err + } + if param.DeviceType != "" { + query["device_type"] = param.DeviceType + list, err := deviceTypeDao.GetAllDeviceType(logger, query) + if err != nil { + logger.Warnf("GetAllDeviceType error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return 0, err + } + fmt.Println("查询到的数量", len(list)) + return len(list), err + } + if param.ImageName != "" { + query["image_name"] = param.ImageName + list, err := imageDao.GetAllImage(logger, query) + if err != nil { + logger.Warnf("GetAllImage error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return 0, err + } + fmt.Println("查询到的数量", len(list)) + return len(list), err + } + if param.UserName != "" { + query["user_name"] = param.UserName + list, err := userDao.GetAllUser(logger, query) + if err != nil { + logger.Warnf("GetAllUser error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return 0, err + } + fmt.Println("查询到的数量", len(list)) + return len(list), err + } + return 0, nil +} diff --git a/bmp-openapi-console/logic/roleLogic/roleLogic.go b/bmp-openapi-console/logic/roleLogic/roleLogic.go new file mode 100644 index 0000000..cda54f2 --- /dev/null +++ b/bmp-openapi-console/logic/roleLogic/roleLogic.go @@ -0,0 +1,99 @@ +package roleLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/roleDao" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func RoleEntity2Role(logger *log.Logger, o *roleDao.Role) *responseTypes.Role { + tz := logger.GetPoint("timezone").(string) + userCount, _ := userDao.GetUserCount(logger, map[string]interface{}{ + "role_id": o.RoleID, + }) + roleName := o.RoleNameCn + if logger.GetPoint("language").(string) == baseLogic.EN_US { + roleName = o.RoleNameEn + } + permission := o.DescriptionCn + if logger.GetPoint("language").(string) == baseLogic.EN_US { + permission = o.DescriptionEn + } + return &responseTypes.Role{ + ID: o.ID, + RoleName: roleName, + Permission: permission, + RoleNameEn: o.RoleNameEn, + RoleNameCn: o.RoleNameCn, + RoleID: o.RoleID, + UserCount: int(userCount), + DescriptionEn: o.DescriptionEn, + DescriptionCn: o.DescriptionCn, + CreatedBy: o.CreatedBy, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + UpdatedBy: o.UpdatedBy, + UpdatedTime: util.TimestampToString(int64(o.UpdatedTime), tz), + } +} + +func GetRoleById(logger *log.Logger, RoleId string) (*responseTypes.Role, error) { + entity, err := roleDao.GetRoleById(logger, RoleId) + if err != nil { + logger.Warn("GetRoleByUuid sql error:", RoleId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + return RoleEntity2Role(logger, entity), nil +} + +func CurrentRole(logger *log.Logger) (*responseTypes.Role, error) { + + userId := logger.GetPoint("userId").(string) + u, err := userDao.GetUserById(logger, userId) + if err != nil { + logger.Warn("GurrentRole.GetUserById sql error:", userId, err.Error()) + panic(constant.INVALID_ARGUMENT) + } + + entity, err := roleDao.GetRoleById(logger, u.RoleID) + if err != nil { + logger.Warn("GurrentRole.GetRoleByUuid sql error:", u.RoleID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + return RoleEntity2Role(logger, entity), nil +} + +func GetRoleList(logger *log.Logger, param requestTypes.QueryRolesRequest, p util.Pageable) ([]*responseTypes.Role, int64, error) { + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + //"role_name": param.RoleName, + //"role_id": param.RoleID, + //"default_project_id": param.DefaultProjectID, + "is_del": 0, + } + count, err := roleDao.GetRoleCount(logger, query) + if err != nil { + logger.Warnf("GetRoleCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*roleDao.Role{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = roleDao.GetMultiRole(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = roleDao.GetMultiRole(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("QueryByRoleIds GetAllRole sql error:", err.Error()) + return nil, 0, err + } + Roles := []*responseTypes.Role{} + for _, entity := range entityList { + Roles = append(Roles, RoleEntity2Role(logger, entity)) + } + return Roles, count, nil +} diff --git a/bmp-openapi-console/logic/sshkeyLogic/sshkeyLogic.go b/bmp-openapi-console/logic/sshkeyLogic/sshkeyLogic.go new file mode 100644 index 0000000..b1ee01f --- /dev/null +++ b/bmp-openapi-console/logic/sshkeyLogic/sshkeyLogic.go @@ -0,0 +1,213 @@ +package sshkeyLogic + +import ( + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rInstanceSshkeyDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/sshkeyDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + namespacePrefix "git.jd.com/cps-golang/ironic-common/ironic/common/NamespacePrefixs" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +func SshkeyEntity2Sshkey(logger *log.Logger, o *sshkeyDao.Sshkey) *responseTypes.Sshkey { + tz := logger.GetPoint("timezone").(string) + return &responseTypes.Sshkey{ + Id: o.ID, + SshkeyId: o.SshkeyId, + UserId: o.UserId, + Name: o.Name, + FingerPrint: o.FingerPrint, + Key: o.Key, + CreatedBy: o.CreatedBy, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + UpdatedBy: o.UpdatedBy, + UpdatedTime: util.TimestampToString(int64(o.UpdatedTime), tz), + } +} + +func GetSshkeyById(logger *log.Logger, SshkeyId string) (*responseTypes.Sshkey, error) { + entity, err := sshkeyDao.GetSshkeyById(logger, SshkeyId) + if err != nil { + logger.Warn("GetSshkeyByUuid sql error:", SshkeyId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + return SshkeyEntity2Sshkey(logger, entity), nil +} + +func CreateSshkey(logger *log.Logger, param *requestTypes.CreateSshkeyRequest) (string, error) { + + userId := logger.GetPoint("userId").(string) + + v, _ := sshkeyDao.GetAllSshkey(logger, map[string]interface{}{ + "user_id": userId, + "is_del": 0, + }) + if len(v) >= 2 { + logger.Warn("two sshkey already exists", userId) + panic(constant.BuildCANCELLEDWithArgs("支持创建2个SSH密钥", "Only supports creating 2 keypairs")) + + } + + list, _ := sshkeyDao.GetAllSshkey(logger, map[string]interface{}{ + "name": param.Name, + "user_id": userId, + "is_del": 0, + }) + if len(list) != 0 { + logger.Warn("sshkey Name exist:", param.Name) + panic(constant.BuildCANCELLEDWithArgs("秘钥名称已存在", "sshkey name exist")) + + } + + finger_print, err := util.GetFingerprint(param.Key) + if err != nil { + logger.Warn("GetFingerprint error:", param.Key, err.Error()) + return "", err + } + + sshkeyEntity := &sshkeyDao.Sshkey{ + UserId: userId, + Name: param.Name, + Key: param.Key, + FingerPrint: finger_print, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + sshkeyEntity.SshkeyId = commonUtil.GetRandString("sshkey-", namespacePrefix.INSTANCE_ID_LENGTH, false, true, true) + if _, err := sshkeyDao.AddSshkey(logger, sshkeyEntity); err != nil { + logger.Warnf("CreateSshkey AddSshkey sql error, entity:%s, error:%s", util.ObjToJson(sshkeyEntity), err.Error()) + return "", err + } + return sshkeyEntity.SshkeyId, nil +} + +func ModifySshkey(logger *log.Logger, param *requestTypes.ModifySshkeyRequest, SshkeyId string) error { + userId := logger.GetPoint("userId").(string) + s, err := sshkeyDao.GetSshkeyById(logger, SshkeyId) + if err != nil { + logger.Warn("GetSshkeyByUuid sql error:", SshkeyId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if s.UserId != userId { + panic(constant.PermissionDenyForObject) + } + + list, _ := sshkeyDao.GetAllSshkey(logger, map[string]interface{}{ + "name": param.Name, + "user_id": userId, + "is_del": 0, + }) + if len(list) != 0 && list[0].SshkeyId != SshkeyId { + logger.Warn("sshkey Name exist:", param.Name) + panic(constant.BuildCANCELLEDWithArgs("秘钥名称已存在", "sshkey name exist")) + } + if param.Name != nil { + s.Name = *param.Name + } + s.UpdatedBy = logger.GetPoint("username").(string) + s.UpdatedTime = int(time.Now().Unix()) + if err := sshkeyDao.UpdateSshkeyById(logger, s); err != nil { + logger.Warn("ModifySshkey UpdateSshkeyById sql error:", SshkeyId, err.Error()) + return err + } + return nil +} + +func DeleteSshkey(logger *log.Logger, sshkeyId string) error { + + userId := logger.GetPoint("userId").(string) + entity, err := sshkeyDao.GetSshkeyById(logger, sshkeyId) + if err != nil { + logger.Warn("GetSshkeyByUuid sql error:", sshkeyId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if entity.UserId != userId { + panic(constant.PermissionDenyForObject) + } + + instanctIds := GetInstancesBySshkey(logger, sshkeyId) + if len(instanctIds) > 0 { + q := map[string]interface{}{ + "instance_id.in": instanctIds, + "sshkey_id": sshkeyId, + "is_del": 0, + } + u := map[string]interface{}{ + "is_del": 1, + } + if err := rInstanceSshkeyDao.UpdateMultirInstanceSshkey(logger, q, u); err != nil { + logger.Warnf("DeleteSshkey.UpdateMultirInstanceSshkey error, instanceIds:%s, sshkeyId:%s, error:%s", strings.Join(instanctIds, ","), sshkeyId, err.Error()) + return err + } + } + + entity.IsDel = 1 + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + entity.DeletedTime = int(time.Now().Unix()) + if err := sshkeyDao.UpdateSshkeyById(logger, entity); err != nil { + logger.Warn("DeleteSshkey UpdateSshkeyById sql error:", sshkeyId, err.Error()) + return err + } + return nil +} +func GetInstancesBySshkey(logger *log.Logger, sshkeyId string) []string { + entity, _ := rInstanceSshkeyDao.GetAllrInstanceSshkey(logger, map[string]interface{}{ + "sshkey_id": sshkeyId, + "is_del": 0, + }) + //if err != nil { + // logger.Warn("GetInstancesBySshkey sql error:", sshkeyId, err.Error()) + // return err + //} + if entity == nil { + return []string{} + } + ids := []string{} + for _, v := range entity { + ids = append(ids, v.InstanceID) + } + return ids +} +func GetSshkeyList(logger *log.Logger, param requestTypes.QuerySshkeysRequest, p util.Pageable) ([]*responseTypes.Sshkey, int64, error) { + userId := logger.GetPoint("userId").(string) + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "name": param.Name, + "user_id": userId, + //"Sshkey_id": param.SshkeyID, + //"default_project_id": param.DefaultProjectID, + "is_del": 0, + } + count, err := sshkeyDao.GetSshkeyCount(logger, query) + if err != nil { + logger.Warnf("GetSshkeyCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*sshkeyDao.Sshkey{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = sshkeyDao.GetMultiSshkey(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = sshkeyDao.GetMultiSshkey(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("QueryBySshkeyIds GetAllSshkey sql error:", err.Error()) + return nil, 0, err + } + sshkeys := []*responseTypes.Sshkey{} + for _, entity := range entityList { + sshkeys = append(sshkeys, SshkeyEntity2Sshkey(logger, entity)) + } + return sshkeys, count, nil +} diff --git a/bmp-openapi-console/logic/userLogic/userLogic.go b/bmp-openapi-console/logic/userLogic/userLogic.go new file mode 100644 index 0000000..2184a70 --- /dev/null +++ b/bmp-openapi-console/logic/userLogic/userLogic.go @@ -0,0 +1,226 @@ +package userLogic + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/projectDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/roleDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + userDao "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func userEntity2user(logger *log.Logger, o *userDao.User) *responseTypes.User { + + tz := logger.GetPoint("timezone").(string) + if tz == "" { + tz = o.Timezone + } + role, _ := roleDao.GetRoleById(logger, o.RoleID) + if role == nil { + role = &roleDao.Role{} + } + project, _ := projectDao.GetProjectById(logger, o.DefaultProjectID) + if project == nil { + project = &projectDao.Project{} + } + roleName := role.RoleNameCn + if logger.GetPoint("language") == baseLogic.EN_US { + roleName = role.RoleNameEn + } + return &responseTypes.User{ + ID: o.ID, + UserName: o.UserName, + Password: o.Password, + UserID: o.UserID, + RoleID: o.RoleID, + RoleName: roleName, + PhonePrefix: o.PhonePrefix, + PhoneNumber: o.PhoneNumber, + DefaultProjectID: o.DefaultProjectID, + DefaultProjectName: project.ProjectName, + Timezone: o.Timezone, + Language: o.Language, + Email: o.Email, + Description: o.Description, + CreatedBy: o.CreatedBy, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + UpdatedBy: o.UpdatedBy, + UpdatedTime: util.TimestampToString(int64(o.UpdatedTime), tz), + } +} + +func GetUserById(logger *log.Logger, userId string) (*responseTypes.User, error) { + entity, err := userDao.GetUserById(logger, userId) + if err != nil { + logger.Warn("GetuserByUuid sql error:", userId, err.Error()) + return nil, err + } + return userEntity2user(logger, entity), nil +} + +func GetUserByName(logger *log.Logger, param *requestTypes.GetUserByNameRequest) (*responseTypes.User, error) { + entity, err := userDao.GetUserByName(logger, param.UserName) + if err != nil { + logger.Warn("GetuserByName sql error:", param.UserName, err.Error()) + return nil, err + } + return userEntity2user(logger, entity), nil +} + +func ModifyUser(logger *log.Logger, param *requestTypes.ModifyUserRequest, userId string) error { + + entity, err := userDao.GetUserById(logger, userId) + if err != nil { + logger.Warn("GetuserByUuid sql error:", userId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if param.Description != nil { + entity.Description = *param.Description + } + if param.PhonePrefix != nil { + entity.PhonePrefix = *param.PhonePrefix + } + if param.PhoneNumber != nil { + entity.PhoneNumber = *param.PhoneNumber + } + if param.Email != nil { + entity.Email = *param.Email + } + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + if err := userDao.UpdateUserById(logger, entity); err != nil { + logger.Warn("Modifyuser UpdateuserById sql error:", userId, err.Error()) + return err + } + return nil +} + +func ModifyLocalUser(logger *log.Logger, param *requestTypes.ModifyLocalUserRequest) error { + + userId := logger.GetPoint("userId").(string) + u, err := userDao.GetUserById(logger, userId) + if err != nil { + logger.Warn("GetuserByUuid sql error:", userId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if param.DefaultProjectID != nil { + u.DefaultProjectID = *param.DefaultProjectID + } + if param.Email != nil { + u.Email = *param.Email + } + if param.PhonePrefix != nil { + u.PhonePrefix = *param.PhonePrefix + } + if param.PhoneNumber != nil { + u.PhoneNumber = *param.PhoneNumber + } + if param.Language != nil { + u.Language = *param.Language + } + if param.Timezone != nil { + u.Timezone = *param.Timezone + } + + u.UpdatedBy = logger.GetPoint("username").(string) + u.UpdatedTime = int(time.Now().Unix()) + if err := userDao.UpdateUserById(logger, u); err != nil { + logger.Warn("Modifyuser UpdateuserById sql error:", userId, err.Error()) + return err + } + if param.DefaultProjectID != nil { + if err := projectDao.UpdateUserDefaultProject(logger, userId, *param.DefaultProjectID); err != nil { + logger.Warn("Modifyuser UpdateUserDefaultProject sql error:", userId, err.Error()) + return err + } + } + return nil +} + +func GetUserList(logger *log.Logger, param *requestTypes.QueryUsersRequest, p util.Pageable) ([]*responseTypes.User, int64, error) { + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "user_name.like": "%" + param.UserName + "%", + "default_project_id": param.DefaultProjectID, + "is_del": 0, + } + if param.RoleID != "" { + query["role_id.in"] = strings.Split(param.RoleID, ",") + } + count, err := userDao.GetUserCount(logger, query) + if err != nil { + logger.Warnf("GetUserCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*userDao.User{} + fmt.Println(param.IsAll) + if param.IsAll == baseLogic.IS_ALL { + entityList, err = userDao.GetMultiUser(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = userDao.GetMultiUser(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("QueryByuserIds GetAlluser sql error:", err.Error()) + return nil, 0, err + } + users := []*responseTypes.User{} + for _, entity := range entityList { + users = append(users, userEntity2user(logger, entity)) + } + return users, count, nil +} + +func VerifyUser(logger *log.Logger, req *requestTypes.VerifyUserRequest) bool { + entity, _ := userDao.GetAllUser(logger, map[string]interface{}{ + "user_name": req.UserName, + "is_del": baseLogic.IS_NOT_DEL, + }) + if len(entity) == 0 { //说明用户名不存在 + panic(constant.BuildInvalidArgumentWithArgs("用户名不存在", "userName not exist")) + } + + permit := false + for _, v := range entity { + if v.RoleID == req.RoleID || v.RoleID == "role-admin-uuid-01" { + permit = true + break + } + } + + if !permit { //无权限 + panic(constant.BuildInvalidArgumentWithArgs("用户权限不足", "permission denied")) + } + logger.Info("请求信息", util.ObjToJson(req), "数据库hash值", entity[0].Password) + res := util.BcryptVerify(req.Password, entity[0].Password) + if !res { + panic(constant.BuildInvalidArgumentWithArgs("密码错误", "password error")) + } else { + return true + } +} + +func ModifyUserPassword(logger *log.Logger, param *requestTypes.ModifyUserPasswordRequest) error { + userId := logger.GetPoint("userId").(string) + u, err := userDao.GetUserById(logger, userId) + if err != nil { + logger.Warn("GetuserByUuid sql error:", userId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if !util.BcryptVerify(param.OldPassword, u.Password) { + panic(constant.BuildInvalidArgumentWithArgs("旧密码输入错误", "oldPassword error")) + } + u.Password = util.BcryptEncode(param.Password) + if err := userDao.UpdateUserById(logger, u); err != nil { + logger.Warn("ModifyUserPassword UpdateuserById sql error:", userId, err.Error()) + return err + } + return nil +} diff --git a/bmp-openapi-console/main.go b/bmp-openapi-console/main.go new file mode 100644 index 0000000..08fbe42 --- /dev/null +++ b/bmp-openapi-console/main.go @@ -0,0 +1,169 @@ +package main + +import ( + "flag" + "fmt" + "os" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorDataLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorProxyLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorRuleLogic" + _ "coding.jd.com/aidc-bmp/bmp-openapi/routers" + rabbitMq "coding.jd.com/aidc-bmp/bmp-openapi/service/rabbit_mq" + redis "coding.jd.com/aidc-bmp/bmp-openapi/service/redis" + _ "coding.jd.com/aidc-bmp/bmp-openapi/swaggermodels" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + + "log" + + beego "github.com/beego/beego/v2/server/web" + _ "github.com/go-sql-driver/mysql" + + schedulerCron "coding.jd.com/aidc-bmp/bmp-openapi/scheduler/cron" + + _ "coding.jd.com/aidc-bmp/bmp-openapi/constant" +) + +////// + +const ( + defaultConfigFile = "conf/bmp-openapi.ini" +) + +var ( + VERSION = "should be compiled with make." + BUILD_TIME = "should be compiled with make." +) + +var configFile = flag.String("c", defaultConfigFile, "specify config file") +var versionFlag = flag.Bool("v", false, "show version") + +func main() { + + time.LoadLocation("Asia/Shanghai") + flag.Parse() + + if *versionFlag { + fmt.Println("commit_id:", VERSION, "build_time:", BUILD_TIME) + os.Exit(0) + } + + hour := time.Now().Local().Hour() + minute := time.Now().Local().Minute() + second := time.Now().Local().Second() + fmt.Println("=============time now is:", hour, minute, second) + + log.Println("[ironic-api] start...") + + // initial Config From file + if err := beego.LoadAppConfig("ini", *configFile); err != nil { + fmt.Println(time.Now(), "LoadAppConfig Error:", err.Error()) + return + } + if err := initRedis(); err != nil { + fmt.Println(time.Now(), "initRedis Error: ", err.Error()) + // return + } + + initGormDB() + + if err := initRabbitMqTemplate(); err != nil { + fmt.Println(time.Now(), "initRabbitMqTemplate Error:", err.Error()) + // return + } + defer rabbitMq.DestroyTemplate() + + request.InitValidator() + + // if err := initIdcApiConfig(); err != nil { + // fmt.Println("initIdcApiConfig Error:", err.Error()) + // return + // } + + // if err := initSdnApiConfig(); err != nil { + // fmt.Println("initSdnApiConfig Error:", err.Error()) + // return + // } + + if err := monitorDataLogic.Init(); err != nil { + fmt.Println(time.Now(), "monitorDataLogic Init Error:", err.Error()) + + } + if err := monitorRuleLogic.Init(); err != nil { + fmt.Println(time.Now(), "monitorRuleLogic Init Error:", err.Error()) + + } + if err := monitorProxyLogic.Init(); err != nil { + fmt.Println(time.Now(), "monitorProxyLogic Init Error:", err.Error()) + + } + go schedulerCron.Run() + + beego.Run() +} + +func initRedis() error { + // initial redis + var namespace, host, port, password string + var dbNum int + namespace, _ = beego.AppConfig.String("bmp_redis_namespace") + host, _ = beego.AppConfig.String("bmp_redis_host") + port, _ = beego.AppConfig.String("bmp_redis_port") + password, _ = beego.AppConfig.String("bmp_redis_password") + dbNum = beego.AppConfig.DefaultInt("bmp_redis_db", 0) + addr := fmt.Sprintf("%s:%s", host, port) + return redis.InitRedis(namespace, addr, password, dbNum) +} + +func initGormDB() { + // initial mysql + host, _ := beego.AppConfig.String("bmp_db_host") + port, _ := beego.AppConfig.String("bmp_db_port") + user, _ := beego.AppConfig.String("bmp_db_user") + password, _ := beego.AppConfig.String("bmp_db_password") + name, _ := beego.AppConfig.String("bmp_db_name") + //root:admin@tcp(10.226.192.113:3306)/aidc_bmp?charset=utf8&parseTime=true&charset=utf8&loc=Asia%2FShanghai + sqlconn := user + ":" + password + "@tcp(" + host + ":" + port + ")/" + name + "?charset=utf8&parseTime=true&loc=Local" + dao.InitGormDb(sqlconn) +} + +func initRabbitMqTemplate() error { + host, _ := beego.AppConfig.String("bmp_mq_host") + port, _ := beego.AppConfig.String("bmp_mq_port") + user, _ := beego.AppConfig.String("bmp_mq_user") + password, _ := beego.AppConfig.String("bmp_mq_password") + vhost, _ := beego.AppConfig.String("bmp_mq_vhost") + mqUrl := "amqp://" + user + ":" + password + "@" + host + ":" + port + "/" + vhost + // exchange, _ := beego.AppConfig.String("rabbit.mq.ironic.exchange") + // receive_routing_key, _ := beego.AppConfig.String("rabbit.mq.ironic.receive_routing_key") + return rabbitMq.InitMqTemplate(mqUrl) +} + +// func initIdcApiConfig() error { +// host, _ := beego.AppConfig.String("idc.host") +// user, _ := beego.AppConfig.String("idc.user") +// token, _ := beego.AppConfig.String("idc.token") +// return idcApi.InitIdcApiConfig(host, user, token) +// } + +// func initSdnApiConfig() error { +// cn_east_1, _ := beego.AppConfig.String("sdn.configs.cn-east-1.ip") +// cn_east_jdr1, _ := beego.AppConfig.String("sdn.configs.cn-east-jdr1.ip") +// cn_north_1, _ := beego.AppConfig.String("sdn.configs.cn-north-1.ip") +// cn_east_tz1, _ := beego.AppConfig.String("sdn.configs.cn-east-tz1.ip") +// cn_east_jn1, _ := beego.AppConfig.String("sdn.configs.cn-east-jn1.ip") +// cn_east_11, _ := beego.AppConfig.String("sdn.configs.cn-east-11.ip") + +// c := map[string]string{ +// "cn-east-1": cn_east_1, +// "cn-east-jdr1": cn_east_jdr1, +// "cn-north-1": cn_north_1, +// "cn-east-tz1": cn_east_tz1, +// "cn-east-jn1": cn_east_jn1, +// "cn-east-11": cn_east_11, +// } +// return sdnApi.InitSdnApiConfig(c) + +// } diff --git a/bmp-openapi-console/nginx_log/access.log b/bmp-openapi-console/nginx_log/access.log new file mode 100644 index 0000000..d557d15 --- /dev/null +++ b/bmp-openapi-console/nginx_log/access.log @@ -0,0 +1,39 @@ +{"@timestamp": "2022-11-02T13:59:54+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 502,"body_bytes_sent": 173,"request_time": 0.003,"upstream_response_time": 0.003,"upstream_connect_time": 0.003,"request_method": "GET","uri": "/v1/users","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-02T14:00:38+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 1534,"request_time": 0.013,"upstream_response_time": 0.014,"upstream_connect_time": 0.014,"request_method": "GET","uri": "/v1/users","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-02T14:07:24+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 154,"request_time": 0.005,"upstream_response_time": 0.005,"upstream_connect_time": 0.005,"request_method": "GET","uri": "/v1/users","args": "defaultProjectId=first_project&isAll=1","server_protocol": "HTTP/1.1","request": "GET /v1/users?defaultProjectId=first_project&isAll=1 HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-02T16:20:42+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 1534,"request_time": 0.012,"upstream_response_time": 0.012,"upstream_connect_time": 0.012,"request_method": "GET","uri": "/v1/users","args": "userName=%E5%BC%A0%E4%B8%89","server_protocol": "HTTP/1.1","request": "GET /v1/users?userName=%E5%BC%A0%E4%B8%89 HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-02T16:24:54+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 1534,"request_time": 0.012,"upstream_response_time": 0.012,"upstream_connect_time": 0.012,"request_method": "GET","uri": "/v1/users","args": "userName=%E5%BC%A0%E4%B8%89","server_protocol": "HTTP/1.1","request": "GET /v1/users?userName=%E5%BC%A0%E4%B8%89 HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-02T16:27:26+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 1534,"request_time": 0.011,"upstream_response_time": 0.011,"upstream_connect_time": 0.011,"request_method": "GET","uri": "/v1/users","args": "userName=%E5%BC%A0%E4%B8%89","server_protocol": "HTTP/1.1","request": "GET /v1/users?userName=%E5%BC%A0%E4%B8%89 HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-02T16:30:47+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 846,"request_time": 0.008,"upstream_response_time": 0.008,"upstream_connect_time": 0.008,"request_method": "GET","uri": "/v1/users","args": "userName=%E5%BC%A0%E4%B8%89","server_protocol": "HTTP/1.1","request": "GET /v1/users?userName=%E5%BC%A0%E4%B8%89 HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-02T16:33:11+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 846,"request_time": 0.009,"upstream_response_time": 0.009,"upstream_connect_time": 0.009,"request_method": "GET","uri": "/v1/users","args": "userName=%E5%BC%A0%E4%B8%89","server_protocol": "HTTP/1.1","request": "GET /v1/users?userName=%E5%BC%A0%E4%B8%89 HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-02T16:34:05+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 846,"request_time": 0.006,"upstream_response_time": 0.006,"upstream_connect_time": 0.006,"request_method": "GET","uri": "/v1/users","args": "userName=%E5%BC%A0%E4%B8%89","server_protocol": "HTTP/1.1","request": "GET /v1/users?userName=%E5%BC%A0%E4%B8%89 HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-02T16:37:25+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 846,"request_time": 0.008,"upstream_response_time": 0.008,"upstream_connect_time": 0.008,"request_method": "GET","uri": "/v1/users","args": "userName=%E5%BC%A0%E4%B8%89","server_protocol": "HTTP/1.1","request": "GET /v1/users?userName=%E5%BC%A0%E4%B8%89 HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-02T16:38:00+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 846,"request_time": 0.008,"upstream_response_time": 0.008,"upstream_connect_time": 0.008,"request_method": "GET","uri": "/v1/users","args": "userName=%E5%BC%A0%E4%B8%89","server_protocol": "HTTP/1.1","request": "GET /v1/users?userName=%E5%BC%A0%E4%B8%89 HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-02T16:44:57+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 855,"request_time": 0.009,"upstream_response_time": 0.009,"upstream_connect_time": 0.009,"request_method": "GET","uri": "/v1/users","args": "userName=%E5%BC%A0%E4%B8%89","server_protocol": "HTTP/1.1","request": "GET /v1/users?userName=%E5%BC%A0%E4%B8%89 HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-02T18:22:09+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 126,"request_time": 0.010,"upstream_response_time": 0.011,"upstream_connect_time": 0.011,"request_method": "POST","uri": "/v1/users","args": "-","server_protocol": "HTTP/1.1","request": "POST /v1/users HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-02T18:22:48+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 126,"request_time": 0.010,"upstream_response_time": 0.009,"upstream_connect_time": 0.009,"request_method": "POST","uri": "/v1/users","args": "-","server_protocol": "HTTP/1.1","request": "POST /v1/users HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-02T18:22:59+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 126,"request_time": 0.009,"upstream_response_time": 0.009,"upstream_connect_time": 0.009,"request_method": "POST","uri": "/v1/users","args": "-","server_protocol": "HTTP/1.1","request": "POST /v1/users HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-03T15:19:27+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 4178,"request_time": 0.023,"upstream_response_time": 0.024,"upstream_connect_time": 0.024,"request_method": "GET","uri": "/v1/users","args": "userName=minping","server_protocol": "HTTP/1.1","request": "GET /v1/users?userName=minping HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-03T15:33:07+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 4178,"request_time": 0.022,"upstream_response_time": 0.022,"upstream_connect_time": 0.022,"request_method": "GET","uri": "/v1/users","args": "userName=minping","server_protocol": "HTTP/1.1","request": "GET /v1/users?userName=minping HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-03T15:36:03+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 4178,"request_time": 0.019,"upstream_response_time": 0.019,"upstream_connect_time": 0.019,"request_method": "GET","uri": "/v1/users","args": "userName=minping","server_protocol": "HTTP/1.1","request": "GET /v1/users?userName=minping HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-03T15:47:33+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 4178,"request_time": 0.020,"upstream_response_time": 0.019,"upstream_connect_time": 0.019,"request_method": "GET","uri": "/v1/users","args": "userName=minping","server_protocol": "HTTP/1.1","request": "GET /v1/users?userName=minping HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-03T15:48:03+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 126,"request_time": 0.010,"upstream_response_time": 0.010,"upstream_connect_time": 0.010,"request_method": "POST","uri": "/v1/users","args": "-","server_protocol": "HTTP/1.1","request": "POST /v1/users HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-09T14:21:17+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 4178,"request_time": 0.035,"upstream_response_time": 0.035,"upstream_connect_time": 0.035,"request_method": "GET","uri": "/v1/users","args": "userName=minping","server_protocol": "HTTP/1.1","request": "GET /v1/users?userName=minping HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T17:26:01+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 4123,"request_time": 0.039,"upstream_response_time": 0.038,"upstream_connect_time": 0.038,"request_method": "GET","uri": "/v1/users","args": "userName=minping","server_protocol": "HTTP/1.1","request": "GET /v1/users?userName=minping HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T17:27:02+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 658,"request_time": 0.009,"upstream_response_time": 0.009,"upstream_connect_time": 0.009,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T17:28:22+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 658,"request_time": 0.010,"upstream_response_time": 0.010,"upstream_connect_time": 0.010,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T17:28:31+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 658,"request_time": 0.009,"upstream_response_time": 0.009,"upstream_connect_time": 0.009,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T17:32:38+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 658,"request_time": 0.009,"upstream_response_time": 0.009,"upstream_connect_time": 0.009,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T17:34:25+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 400,"body_bytes_sent": 658,"request_time": 0.011,"upstream_response_time": 0.011,"upstream_connect_time": 0.011,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T17:34:57+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 658,"request_time": 0.012,"upstream_response_time": 0.012,"upstream_connect_time": 0.012,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T17:39:57+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 400,"body_bytes_sent": 658,"request_time": 0.010,"upstream_response_time": 0.011,"upstream_connect_time": 0.011,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T17:40:29+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 658,"request_time": 0.012,"upstream_response_time": 0.011,"upstream_connect_time": 0.011,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T17:43:06+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 658,"request_time": 0.008,"upstream_response_time": 0.009,"upstream_connect_time": 0.009,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T17:43:32+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 400,"body_bytes_sent": 658,"request_time": 0.012,"upstream_response_time": 0.011,"upstream_connect_time": 0.011,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T17:45:03+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 400,"body_bytes_sent": 658,"request_time": 0.009,"upstream_response_time": 0.009,"upstream_connect_time": 0.009,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T17:45:30+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 658,"request_time": 0.011,"upstream_response_time": 0.011,"upstream_connect_time": 0.011,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T18:00:48+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 658,"request_time": 0.011,"upstream_response_time": 0.011,"upstream_connect_time": 0.011,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T18:03:19+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 41,"request_time": 0.010,"upstream_response_time": 0.010,"upstream_connect_time": 0.010,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T18:04:03+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 658,"request_time": 0.012,"upstream_response_time": 0.012,"upstream_connect_time": 0.012,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T18:05:17+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 41,"request_time": 0.008,"upstream_response_time": 0.008,"upstream_connect_time": 0.008,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} +{"@timestamp": "2022-11-18T18:10:10+08:00","remote_addr": "127.0.0.1","upstream_addr": "127.0.0.1:9901","http_host": "cps-openapi.bmp.local","status": 200,"body_bytes_sent": 41,"request_time": 0.009,"upstream_response_time": 0.009,"upstream_connect_time": 0.009,"request_method": "GET","uri": "/v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp","args": "-","server_protocol": "HTTP/1.1","request": "GET /v1/users/user-yjtjfxudquxoy2uhoo6im2as3hbp HTTP/1.1","http_referer": "-","http_user_agent": "Go-http-client/1.1"} diff --git a/bmp-openapi-console/nginx_log/error.log b/bmp-openapi-console/nginx_log/error.log new file mode 100644 index 0000000..a785913 --- /dev/null +++ b/bmp-openapi-console/nginx_log/error.log @@ -0,0 +1 @@ +2022/11/02 13:59:54 [error] 13443#0: *2528109 upstream prematurely closed connection while reading response header from upstream, client: 127.0.0.1, server: cps-openapi.bmp.local, request: "GET /v1/users HTTP/1.1", upstream: "http://127.0.0.1:9901/v1/users", host: "cps-openapi.bmp.local" diff --git a/bmp-openapi-console/routers/router.go b/bmp-openapi-console/routers/router.go new file mode 100644 index 0000000..de37b55 --- /dev/null +++ b/bmp-openapi-console/routers/router.go @@ -0,0 +1,279 @@ +// @APIVersion 1.0.0 +// @Title beego Test API +// @Description beego has a very cool tools to autogenerate documents for your API +// @Contact astaxie@gmail.com +// @TermsOfServiceUrl http://beego.me/ +// @License Apache 2.0 +// @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html +package routers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/controllers" + + beego "github.com/beego/beego/v2/server/web" +) + +func init() { + + //subnetNS := beego.NewNamespace("/subnets", + // beego.NSRouter("/", &controllers.SubnetController{}, "get:QuerySubnets"), + // beego.NSRouter("/?:subnet_id", &controllers.SubnetController{}, "get:GetSubnet"), + // beego.NSRouter("/", &controllers.SubnetController{}, "post:CreateSubnet"), + // beego.NSRouter("/?:subnet_id", &controllers.SubnetController{}, "put:ModifySubnet"), + // beego.NSRouter("/?:subnet_id", &controllers.SubnetController{}, "delete:DeleteSubnet"), + //) + //beego.AddNamespace(subnetNS) + // + //wanSubnetNS := beego.NewNamespace("/wanSubnet", + // beego.NSRouter("/", &controllers.WanSubnetController{}, "post:CreateWanSubnet"), + //) + //beego.AddNamespace(wanSubnetNS) + + deviceNS := beego.NewNamespace("/v1/devices", + beego.NSRouter("/", &controllers.DeviceController{}, "get:DescribeDevices"), + beego.NSRouter("/", &controllers.DeviceController{}, "post:DescribeDevices"), + beego.NSRouter("/stock", &controllers.DeviceController{}, "get:DescribeDeviceStock"), + beego.NSRouter("/?:device_id", &controllers.DeviceController{}, "get:DescribeDevice"), + ) + beego.AddNamespace(deviceNS) + + DeviceTypeNS := beego.NewNamespace("/v1/deviceTypes", + beego.NSRouter("/", &controllers.DeviceTypeController{}, "get:DescribeDeviceTypes"), + beego.NSRouter("/?:device_type_id", &controllers.DeviceTypeController{}, "get:DescribeDeviceType"), + beego.NSRouter("/deviceTypeImage", &controllers.DeviceTypeController{}, "get:DescribeDeviceTypeImages"), + beego.NSRouter("/volumesRaids", &controllers.DeviceTypeController{}, "get:DescribeVolumesRaids"), + beego.NSRouter("/deviceTypeImagePartition", &controllers.DeviceTypeController{}, "get:DescribeDeviceTypeImagePartitions"), + ) + beego.AddNamespace(DeviceTypeNS) + + IdcNS := beego.NewNamespace("v1/idcs", + + beego.NSRouter("/", &controllers.IdcController{}, "get:DescribeIdcs"), + beego.NSRouter("/?:idc_id", &controllers.IdcController{}, "get:DescribeIdc"), + ) + + beego.AddNamespace(IdcNS) + + OsNS := beego.NewNamespace("/v1/oss", + beego.NSRouter("/", &controllers.OsController{}, "get:DescribeOSs"), + beego.NSRouter("/?:os_id", &controllers.OsController{}, "get:DescribeOS"), + ) + beego.AddNamespace(OsNS) + + ImageNS := beego.NewNamespace("/v1/images", + beego.NSRouter("/", &controllers.ImageController{}, "get:DescribeImages"), + beego.NSRouter("/?:image_id", &controllers.ImageController{}, "get:DescribeImage"), + beego.NSRouter("/imageDeviceTypes", &controllers.ImageController{}, "get:DescribeImageDeviceTypes"), + ) + beego.AddNamespace(ImageNS) + + RabbitMq := beego.NewNamespace("/rabbitmq", + beego.NSRouter("/send", &controllers.RabbitMqController{}, "post:Send"), + beego.NSRouter("/receive", &controllers.RabbitMqController{}, "get:Receive"), + ) + beego.AddNamespace(RabbitMq) + + /*InterfaceNs := beego.NewNamespace("/interfaces", + beego.NSRouter("/", &controllers.InterfaceController{}, "post:CreateInterface"), + beego.NSRouter("/", &controllers.InterfaceController{}, "get:QueryInterfaces"), + beego.NSRouter("/", &controllers.InterfaceController{}, "delete:DeleteInterface"), + ) + beego.AddNamespace(InterfaceNs) + + SwitchNs := beego.NewNamespace("/switches", + beego.NSRouter("/", &controllers.JdSwitchController{}, "put:CreateSwitch"), + beego.NSRouter("/", &controllers.JdSwitchController{}, "post:UpdateSwitch"), + beego.NSRouter("/", &controllers.JdSwitchController{}, "get:QuerySwitches"), + ) + beego.AddNamespace(SwitchNs)*/ + + //KeypairNS := beego.NewNamespace("/keypairs", + // beego.NSRouter("/", &controllers.KeypairController{}, "post:CreateKeypair"), + // beego.NSRouter("/?:keypair_id", &controllers.KeypairController{}, "delete:DeleteKeypair"), + // beego.NSRouter("/", &controllers.KeypairController{}, "get:DescribeKeyPairs"), + // beego.NSRouter("/?:keypair_id", &controllers.KeypairController{}, "get:DescribeKeyPair"), + // beego.NSRouter("/getKeypairByname/?:keypair_name", &controllers.KeypairController{}, "get:DescribeKeyPairByName"), + //) + //beego.AddNamespace(KeypairNS) + + /*MailNS := beego.NewNamespace("/mail", + beego.NSRouter("/addReceiver", &controllers.MailReceiverController{}, "put:AddReceiver"), + beego.NSRouter("/removeReceiver", &controllers.MailReceiverController{}, "put:RemoveReceiver"), + beego.NSRouter("/listReceivers", &controllers.MailReceiverController{}, "get:QueryReceivers"), + ) + beego.AddNamespace(MailNS)*/ + + InstanceNS := beego.NewNamespace("/v1/project/instances", + beego.NSRouter("/", &controllers.InstanceController{}, "post:CreateProjectInstance"), + beego.NSRouter("/", &controllers.InstanceController{}, "get:DescribeProjectInstances"), + beego.NSRouter("/?:instance_id", &controllers.InstanceController{}, "get:DescribeProjectInstance"), + beego.NSRouter("/?:instance_id", &controllers.InstanceController{}, "put:ModifyProjectInstance"), + beego.NSRouter("/?:instance_id", &controllers.InstanceController{}, "delete:DeleteProjectInstance"), + beego.NSRouter("/?:instance_id/lock", &controllers.InstanceController{}, "put:LockProjectInstance"), //锁定 + beego.NSRouter("/?:instance_id/unlock", &controllers.InstanceController{}, "put:UnLockProjectInstance"), //解锁定 + beego.NSRouter("/?:instance_id/start", &controllers.InstanceController{}, "put:StartProjectInstance"), //开机 + beego.NSRouter("/?:instance_id/stop", &controllers.InstanceController{}, "put:StopProjectInstance"), //关机 + beego.NSRouter("/?:instance_id/restart", &controllers.InstanceController{}, "put:RestartProjectInstance"), //重启 + beego.NSRouter("/?:instance_id/resetpasswd", &controllers.InstanceController{}, "put:ResetPasswd"), //重置密码 + beego.NSRouter("/?:instance_id/resetStatus", &controllers.InstanceController{}, "put:ResetInstanceStatus"), //重置状态 + //批量开机 + beego.NSRouter("/batch/:param(instances[:]{1}startInstances)", &controllers.InstanceController{}, "put:StartInstances"), + // //批量关机 + beego.NSRouter("/batch/:param(instances[:]{1}stopInstances)", &controllers.InstanceController{}, "put:StopInstances"), + // //批量重启 + beego.NSRouter("/batch/:param(instances[:]{1}restartInstances)", &controllers.InstanceController{}, "put:RestartInstances"), + // //批量编辑实例名称 + beego.NSRouter("/batch/:param(instances[:]{1}modifyInstances)", &controllers.InstanceController{}, "put:ModifyInstances"), + // //批量删除实例 + beego.NSRouter("/batch/:param(instances[:]{1}deleteInstances)", &controllers.InstanceController{}, "delete:DeleteInstances"), + // //批量重置密码 + beego.NSRouter("/batch/:param(instances[:]{1}resetPasswd)", &controllers.InstanceController{}, "put:ResetInstancesPasswd"), + // 实例重装 + beego.NSRouter("/?:instance_id/reinstallInstance", &controllers.InstanceController{}, "put:ReinstallInstance"), + //部分共享,获取实例列表 + beego.NSRouter("/share/describeInstances", &controllers.InstanceController{}, "get:DescribeInstancesByProjectIdAndOwnerNameAndSharerName"), + ) + beego.AddNamespace(InstanceNS) + + offlineNs := beego.NewNamespace("/v1/offline", + beego.NSRouter("/monitorRules/checkDiffFromPronoea", &controllers.MonitorRuleController{}, "get:CheckDiffFromPronoea"), + ) + + beego.AddNamespace(offlineNs) + + UserNS := beego.NewNamespace("/v1/users", + beego.NSRouter("/verify", &controllers.UserController{}, "post:VerifyUser"), + beego.NSRouter("/", &controllers.UserController{}, "get:DescribeUsers"), + beego.NSRouter("/getUserByName", &controllers.UserController{}, "get:DescribeUserByName"), + beego.NSRouter("/?:user_id", &controllers.UserController{}, "get:DescribeUser"), + beego.NSRouter("/?:user_id", &controllers.UserController{}, "put:ModifyUser"), + ) + beego.AddNamespace(UserNS) + + // 控制台个人中心 + LocalUserNS := beego.NewNamespace("/v1/local/users", + beego.NSRouter("/", &controllers.UserController{}, "get:DescribeLocalUser"), + beego.NSRouter("/", &controllers.UserController{}, "put:ModifyLocalUser"), + beego.NSRouter("/password", &controllers.UserController{}, "put:ModifyLocalUserPassword"), + ) + beego.AddNamespace(LocalUserNS) + + RoleSN := beego.NewNamespace("/v1/roles", + beego.NSRouter("/", &controllers.RoleController{}, "get:DescribeRoles"), + beego.NSRouter("/?:role_id", &controllers.RoleController{}, "get:DescribeRole"), + beego.NSRouter("/roleInfo/current", &controllers.RoleController{}, "get:CurrentRole"), + ) + beego.AddNamespace(RoleSN) + + ProjectSN := beego.NewNamespace("/v1/user/projects", + beego.NSRouter("/", &controllers.ProjectController{}, "post:CreateUserProject"), + beego.NSRouter("/", &controllers.ProjectController{}, "get:DescribeUserProjects"), + beego.NSRouter("/?:project_id/share", &controllers.ProjectController{}, "put:ShareUserProject"), + beego.NSRouter("/?:project_id/cancelShare", &controllers.ProjectController{}, "put:CancelShareUserProject"), + beego.NSRouter("/?:project_id/move", &controllers.ProjectController{}, "put:MoveUserProject"), + beego.NSRouter("/?:project_id", &controllers.ProjectController{}, "get:DescribeUserProject"), + beego.NSRouter("/?:project_id", &controllers.ProjectController{}, "put:ModifyUserProject"), + beego.NSRouter("/?:project_id/description", &controllers.ProjectController{}, "put:ModifyUserProjectDescription"), + beego.NSRouter("/?:project_id", &controllers.ProjectController{}, "delete:DeleteUserProject"), + beego.NSRouter("/?:project_id/describeSharProject", &controllers.ProjectController{}, "get:DescribeShareUserProject"), + beego.NSRouter("/move/instances", &controllers.ProjectController{}, "put:MoveUserInstances"), + ) + beego.AddNamespace(ProjectSN) + SshkeySN := beego.NewNamespace("/v1/user/sshkeys", + beego.NSRouter("/", &controllers.SshkeyController{}, "post:CreateUserSshkey"), + beego.NSRouter("/", &controllers.SshkeyController{}, "get:DescribeUserSshKeys"), + beego.NSRouter("/?:sshkey_id", &controllers.SshkeyController{}, "get:DescribeUserSshKey"), + beego.NSRouter("/?:sshkey_id", &controllers.SshkeyController{}, "put:ModifyUserSshkey"), + beego.NSRouter("/?:sshkey_id", &controllers.SshkeyController{}, "delete:DeleteUserSshkey"), + beego.NSRouter("/instances/?:sshkey_id", &controllers.SshkeyController{}, "get:GetInstancesBySshkey"), + ) + beego.AddNamespace(SshkeySN) + ApikeySN := beego.NewNamespace("/v1/user/apikeys", + beego.NSRouter("/", &controllers.ApikeyController{}, "post:CreateUserApikey"), + beego.NSRouter("/", &controllers.ApikeyController{}, "get:DescribeUserAPIKeys"), + beego.NSRouter("/?:apikey_id", &controllers.ApikeyController{}, "get:DescribeUserAPIKey"), + beego.NSRouter("/?:apikey_id", &controllers.ApikeyController{}, "put:ModifyUserApikey"), + beego.NSRouter("/?:apikey_id", &controllers.ApikeyController{}, "delete:DeleteUserApikey"), + ) + beego.AddNamespace(ApikeySN) + resource := beego.NewNamespace("/v1/resources", + beego.NSRouter("/", &controllers.ResourceController{}, "get:DescribeResources"), + ) + beego.AddNamespace(resource) + + // license := beego.NewNamespace("/v1/license", + // beego.NSRouter("/content", &controllers.LicenseController{}, "get:DescribeLicenseContent"), + // ) + // beego.AddNamespace(license) + + messageNS := beego.NewNamespace("/v1/messages", + beego.NSRouter("/hasUnreadMessage", &controllers.MessageController{}, "get:HasUnreadMessage"), + beego.NSRouter("/", &controllers.MessageController{}, "get:GetMessageList"), + beego.NSRouter("/statistic", &controllers.MessageController{}, "get:GetMessageStatistic"), + beego.NSRouter("/doRead", &controllers.MessageController{}, "put:ReadMessage"), + beego.NSRouter("/delete", &controllers.MessageController{}, "delete:DeleteMessage"), + beego.NSRouter("/getMessageById", &controllers.MessageController{}, "get:GetMessageById"), + beego.NSRouter("/getMessageTypes", &controllers.MessageController{}, "get:GetMessageTypes"), + ) + beego.AddNamespace(messageNS) + + auditLogNS := beego.NewNamespace("/v1/auditLogs", + beego.NSRouter("/", &controllers.AuditLogsController{}, "get:DescribeAuditLogs"), + beego.NSRouter("/types", &controllers.AuditLogsController{}, "get:DescribeAuditLogTypes"), + ) + beego.AddNamespace(auditLogNS) + + //报警规则相关 + monitorRuleNs := + beego.NewNamespace("/v1/monitorRule", + //添加规则 + beego.NSRouter("/addRule", &controllers.MonitorRuleController{}, "post:AddRule"), + //规则详情 + beego.NSRouter("/describeRule", &controllers.MonitorRuleController{}, "get:DescribeRule"), + //规则列表 + beego.NSRouter("/describeRules", &controllers.MonitorRuleController{}, "get:DescribeRules"), + //编辑规则 + beego.NSRouter("/editRule", &controllers.MonitorRuleController{}, "put:EditRule"), + //启用规则 + beego.NSRouter("/enableRule", &controllers.MonitorRuleController{}, "put:EnableRule"), + //禁用规则 + beego.NSRouter("/disableRule", &controllers.MonitorRuleController{}, "put:DisableRule"), + //删除规则 + beego.NSRouter("/deleteRule", &controllers.MonitorRuleController{}, "delete:DeleteRule"), + ) + + beego.AddNamespace(monitorRuleNs) + + //监控报警相关 + monitorAlertNs := + beego.NewNamespace("/v1/monitorAlert", + //添加告警 + beego.NSRouter("/addAlert", &controllers.MonitorAlertController{}, "post:AddAlert"), + //告警详情 + beego.NSRouter("/describeAlert", &controllers.MonitorAlertController{}, "get:DescribeAlert"), + //告警列表 + beego.NSRouter("/describeAlerts", &controllers.MonitorAlertController{}, "get:DescribeAlerts"), + //删除告警 + beego.NSRouter("/deleteAlert", &controllers.MonitorAlertController{}, "delete:DeleteAlert"), + ) + + beego.AddNamespace(monitorAlertNs) + + //带内监控-图表数据获取 + monitorDataNs := + beego.NewNamespace("/v1/monitorData", + beego.NSRouter("/", &controllers.MonitorDataController{}, "get:GetMonitorData"), + ) + + beego.AddNamespace(monitorDataNs) + + //带内监控-获取agent状态、获取tag列表 + monitorProxyNs := + beego.NewNamespace("/v1/monitorProxy", + beego.NSRouter("/desrcibeAgentStatus", &controllers.MonitorProxyController{}, "get:DesrcibeAgentStatus"), + beego.NSRouter("/desrcibeTags", &controllers.MonitorProxyController{}, "get:DesrcibeTags"), + ) + + beego.AddNamespace(monitorProxyNs) + +} diff --git a/bmp-openapi-console/scheduler/cron/cleanLog.go b/bmp-openapi-console/scheduler/cron/cleanLog.go new file mode 100644 index 0000000..e3bdc86 --- /dev/null +++ b/bmp-openapi-console/scheduler/cron/cleanLog.go @@ -0,0 +1,49 @@ +package cron + +import ( + "fmt" + "os" + "path/filepath" + "regexp" + "time" + + beego "github.com/beego/beego/v2/server/web" +) + +const REGEX_FILE_NAME string = `^.*\.202[0-9]{7}$` +const LOG_DIR = "./log" + +func doCleanLogCron() error { + + files := []string{} + infos := []os.FileInfo{} + + remainDays, _ := beego.AppConfig.Int("logs.remainDays") + if remainDays == 0 { + remainDays = 3 //测试时默认3天 + } + + if err := filepath.Walk(LOG_DIR, func(path string, info os.FileInfo, err error) error { + files = append(files, path) + infos = append(infos, info) + return nil + }); err != nil { + fmt.Println("doCleanLogCron.Walk error:", err.Error()) + return err + } + + for _, info := range infos { + if info.IsDir() { + continue + } + if match, _ := regexp.MatchString(REGEX_FILE_NAME, info.Name()); match { + modifySince := time.Now().Unix() - info.ModTime().Unix() + if modifySince > int64(remainDays)*24*3600 { + if err := os.Remove(LOG_DIR + string(os.PathSeparator) + info.Name()); err != nil { + fmt.Printf("os.Remove error, file:%s, error:%s\n", info.Name(), err.Error()) + } + } + } + } + return nil +} diff --git a/bmp-openapi-console/scheduler/cron/cron.go b/bmp-openapi-console/scheduler/cron/cron.go new file mode 100644 index 0000000..543bd51 --- /dev/null +++ b/bmp-openapi-console/scheduler/cron/cron.go @@ -0,0 +1,14 @@ +package cron + +import ( + "github.com/beego/beego/v2/adapter/toolbox" +) + +func Run() { + + c1 := toolbox.NewTask("CleanLogCron", "0 5 */1 * * *", doCleanLogCron) + toolbox.AddTask("CleanLogCron", c1) + + toolbox.StartTask() + defer toolbox.StopTask() +} diff --git a/bmp-openapi-console/service/idc_api/idc_api.go b/bmp-openapi-console/service/idc_api/idc_api.go new file mode 100644 index 0000000..861c37b --- /dev/null +++ b/bmp-openapi-console/service/idc_api/idc_api.go @@ -0,0 +1,73 @@ +package idc_api + +import ( + "encoding/json" + "errors" + "fmt" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + "git.jd.com/cps-golang/ironic-common/exception" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" + "gopkg.in/goyy/goyy.v0/util/crypto/hmac" +) + +//返回数据格式 https://cf.jd.com/pages/viewpage.action?pageId=103918804 +type IdcDevicesResp struct { + StatusCode int32 `json:"status_code"` + Data map[string]IDevice `json:"data"` +} + +type IDevice struct { + Sn string `json:"sn"` + IloIP string `json:"ilo_ip"` + Cabinet string `json:"cabinet"` + UPosition string `json:"u_position"` + Department string `json:"department"` + Model string `json:"model"` + Manufacturer string `json:"manufacturer"` + UpDown string `json:"up_down"` + Idc string `json:"idc"` +} + +var host, user, token string + +func InitIdcApiConfig(idcHost, idcUser, idcToken string) error { + if idcHost == "" || idcUser == "" || idcToken == "" { + return errors.New("host|user|token missing...") + } + host = idcHost + user = idcUser + token = idcToken + return nil +} + +func QueryDevices(logger *log.Logger, sns []string) map[string]IDevice { + + t := fmt.Sprint(time.Now().Unix()) + auth, _ := hmac.Md5Hex(fmt.Sprintf("%s%s%s", user, token, t), "key") + CMDB_GET_DEVICE_INFO_BY_SNS := fmt.Sprintf("http://%s/v1.0/search/device_info/sns?user=%s&auth=%s×tamp=%s", host, user, auth, t) + + header := map[string]string{ + "Host": host, + "Content-Type": "application/json", + "X-Jdcloud-Request-Id": logger.GetPoint("logid").(string), + } + resp, err := util.DoHttpPost(logger, CMDB_GET_DEVICE_INFO_BY_SNS, header, sns) + if err != nil { + logger.Warn("idc_api QueryDevices error:", sns, err.Error()) + panic(exception.Exception{httpStatus.INTERNAL_SERVER_ERROR, errorCode.INTERNAL, "queryDevices from idc fail"}) + } + logger.Point("idc_api_resp", string(resp)) + var res = IdcDevicesResp{} + if err = json.Unmarshal(resp, &res); err != nil { + logger.Warn("idc_api QueryDevices response parse error:", sns, err.Error()) + panic(exception.Exception{httpStatus.INTERNAL_SERVER_ERROR, errorCode.INTERNAL, "queryDevices from idc fail"}) + } + if res.StatusCode != 200 { + panic(exception.Exception{httpStatus.INTERNAL_SERVER_ERROR, errorCode.INTERNAL, "queryDevices from idc is empty"}) + } + return res.Data +} diff --git a/bmp-openapi-console/service/rabbit_mq/producer.go b/bmp-openapi-console/service/rabbit_mq/producer.go new file mode 100644 index 0000000..628d13b --- /dev/null +++ b/bmp-openapi-console/service/rabbit_mq/producer.go @@ -0,0 +1,30 @@ +package rabbit_mq + +import ( + "fmt" + + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + "github.com/streadway/amqp" +) + +func SendToApi2Scheduler(obj interface{}) error { + return doPublish(ironicChannel, IRONIC_EXCHANGE, API_TO_SCHEDULER_ROUTING_KEY, obj) +} + +func doPublish(c *amqp.Channel, exchangeName string, routingKey string, val interface{}) (err error) { + msg, err := commonUtil.Convert2String(val) + if err != nil { + return err + } + err = c.Publish( + exchangeName, // exchange + routingKey, // routing key + false, // mandatory + false, // immediate + amqp.Publishing{ + ContentType: "application/json", + Body: []byte(msg), + }) + fmt.Println(exchangeName, routingKey, msg) + return +} diff --git a/bmp-openapi-console/service/rabbit_mq/rabbit_mq.go b/bmp-openapi-console/service/rabbit_mq/rabbit_mq.go new file mode 100644 index 0000000..d36e690 --- /dev/null +++ b/bmp-openapi-console/service/rabbit_mq/rabbit_mq.go @@ -0,0 +1,212 @@ +package rabbit_mq + +import ( + "fmt" + "time" + + "github.com/streadway/amqp" +) + +const ( + //********************ironic******************** + IRONIC_EXCHANGE = "CPS_IRONIC_SCHEDULER" + IRONIC_TOPIC = "direct" + + API_TO_SCHEDULER_QUEUE_NAME = "CPS_IRONIC_API_TO_SCHEDULER" + API_TO_SCHEDULER_ROUTING_KEY = "CPS_IRONIC_INNER_ROUTING_KEY" + SCHEDULER_QUEUE_NAME = "CPS_IRONIC_SCHEDULER" + SCHEDULER_ROUTING_KEY = "CPS_IRONIC_SCHEDULER" + + //********************openapi******************** + OPENAPI_EXCHANGE = "CPS_OPENAPI_EXCHANGE" + OPENAPI_TOPIC = "direct" + + OPENAPI_CALLBACK_QUEUE_NAME = "CPS_OPENAPI_CALLBACK_QUEUE" + OPENAPI_CALLBACK_ROUTING_KEY = "CPS_OPENAPI_CALLBACK_ROUTING_KEY" + + IRONIC_4TOPIC_EXCHANGE = "BMP_SCHEDULER_TOPIC" +) + +var ( + openapiUrl string + ironicUrl string + ironicConn *amqp.Connection + ironicChannel *amqp.Channel + openapiConn *amqp.Connection + openapiChannel *amqp.Channel +) + +func DestroyTemplate() { + ironicChannel.Close() + ironicConn.Close() + //openapiChannel.Close() + //openapiConn.Close() +} + +//连接保活,断开时重连 +func keepAliveConn() { + + var ironicCloseChan chan *amqp.Error + var ironicNotifyClose chan *amqp.Error + + for { + + if ironicConn == nil || ironicConn.IsClosed() { //连接已断开,需要重连 + fmt.Printf(time.Now().String() + "ironic conn is closed\n") + //新建连接和信道 + if err := InitIronicMq(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitIronicMq error:%s\n", err.Error()) + goto END + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitIronicMq success\n") + } + } + + ironicCloseChan = make(chan *amqp.Error, 1) + //openapiCloseChan := make(chan *amqp.Error, 1) + ironicNotifyClose = ironicChannel.NotifyClose(ironicCloseChan) //一旦消费者的channel有错误,产生一个amqp.Error,channel监听并捕捉到这个错误 + //openapiNotifyClose := openapiChannel.NotifyClose(openapiCloseChan) + select { + case <-ironicNotifyClose: + fmt.Printf(time.Now().String() + "ironic channel error\n") + if ironicConn == nil || ironicConn.IsClosed() { //连接已断开,需要重连 + fmt.Printf(time.Now().String() + "ironic conn is closed\n") + time.Sleep(5 * time.Second) + //新建连接和信道 + if err := InitIronicMq(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitIronicMq error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitIronicMq success\n") + } + + } else { //连接还在,只是信道异常,需要获取新信道 + fmt.Printf(time.Now().String() + "ironic conn is open but channel is bad\n") + time.Sleep(5 * time.Second) + //获取新信道 + if err := InitIronicMqForNewChannel(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitIronicMqForNewChannel error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitIronicMqForNewChannel success\n") + } + } + /*case <-openapiNotifyClose: + + fmt.Printf(time.Now().String() + "openapi channel error\n") + if openapiConn == nil || openapiConn.IsClosed() { //连接已断开,需要重连 + fmt.Printf(time.Now().String() + "openapi conn is closed\n") + time.Sleep(5 * time.Second) + //新建连接和信道 + if err := InitOpenapiMq(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitOpenapiMq error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitOpenapiMq success\n") + } + + } else { //连接还在,只是信道异常,需要获取新信道 + fmt.Printf(time.Now().String() + "openapi conn is open but channel is bad\n") + time.Sleep(5 * time.Second) + //获取新信道 + if err := InitOpenapiMqForNewChannel(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitOpenapiMqForNewChannel error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitOpenapiMqForNewChannel success\n") + } + }*/ + } + END: + fmt.Printf(time.Now().String() + "keepAliveConn once done\n") + time.Sleep(10 * time.Second) + + } + +} + +//exchange receive_routing_key 用于ironicmq +func InitMqTemplate(ironic string) (err error) { + ironicUrl = ironic + if err := InitIronicMq(); err != nil { + fmt.Printf(time.Now().String()+" InitMqTemplate error:%s\n", err.Error()) + // return err + } + go keepAliveConn() + //******************************************* + return nil +} + +func InitIronicMq() error { + + var err error + ironicConn, err = amqp.Dial(ironicUrl) + if err != nil { + return err + } + ironicChannel, err = ironicConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(ironicChannel, IRONIC_EXCHANGE, IRONIC_TOPIC) + if err != nil { + return err + } + return nil +} + +//连接正常,信道异常时,获取新信道 +func InitIronicMqForNewChannel() error { + + var err error + ironicChannel, err = ironicConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(ironicChannel, IRONIC_EXCHANGE, IRONIC_TOPIC) + if err != nil { + return err + } + return nil +} + +func InitOpenapiMq() error { + + var err error + openapiConn, err = amqp.Dial(openapiUrl) + if err != nil { + return err + } + openapiChannel, err = openapiConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(openapiChannel, OPENAPI_EXCHANGE, OPENAPI_TOPIC) + if err != nil { + return err + } + return nil +} + +//连接正常,信道异常时,获取新信道 +func InitOpenapiMqForNewChannel() error { + + var err error + openapiChannel, err = openapiConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(openapiChannel, OPENAPI_EXCHANGE, OPENAPI_TOPIC) + if err != nil { + return err + } + return nil +} + +func exchangeDeclare(ch *amqp.Channel, exchange, topicType string) error { + return ch.ExchangeDeclare( + exchange, // name + topicType, // type + true, // durable + false, // auto-deleted + false, // internal + false, // no-wait + nil, // arguments + ) +} diff --git a/bmp-openapi-console/service/redis/redis.go b/bmp-openapi-console/service/redis/redis.go new file mode 100644 index 0000000..f966fbe --- /dev/null +++ b/bmp-openapi-console/service/redis/redis.go @@ -0,0 +1,261 @@ +package redis + +import ( + "sync" + "time" + + "github.com/go-redis/redis" +) + +var redisMonitorNamespace string + +var redisOnce sync.Once + +type redisUtil struct { + *redis.Client +} + +// RedisUtil singleton redis util +var RedisUtil *redisUtil + +// InitRedis initial redisUtil instance +func InitRedis(namespace, addr, passwd string, db int) error { + redisOnce.Do(func() { + if RedisUtil == nil { + + RedisUtil = &redisUtil{ + redis.NewClient(&redis.Options{ + Addr: addr, + Password: passwd, // no password set + DB: db, // use default DB + }), + } + + redisMonitorNamespace = namespace + + } + }) + return RedisUtil.Ping().Err() +} + +// SetObjectToRedisWithExpire set string object with a expiration +func SetObjectToRedisWithExpire(key, value string, sec int) error { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + err := RedisUtil.Set(fullKey, value, time.Second*time.Duration(sec)).Err() + if err != nil { + return err + } + + return nil +} + +// SetObjectToRedis set object to Redis +func SetObjectToRedis(key string, value string) error { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + err := RedisUtil.Set(fullKey, value, 0).Err() + if err != nil { + return err + } + + return nil +} + +// GetObjectFromRedis Get object from Redis +func GetObjectFromRedis(key string) (string, error) { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + ret, err := RedisUtil.Get(fullKey).Result() + if err != nil { + return "", err + } + + return ret, nil +} + +func DelObjectFromRedis(keys []string) error { + + if len(keys) <= 0 { + return nil + } + + var fullKeys []string + for _, v := range keys { + if v != "" { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = v + } else { + fullKey = redisMonitorNamespace + if v != "" { + fullKey = redisMonitorNamespace + ":" + v + } + } + fullKeys = append(fullKeys, fullKey) + } + } + + if len(fullKeys) > 0 { + err := RedisUtil.Del(fullKeys...).Err() + if err != nil { + return err + } + } + + return nil +} + +// HSetObjectToRedis hash set object to Redis +func HSetObjectToRedis(key, field, value string) error { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + err := RedisUtil.HSet(fullKey, field, value).Err() + if err != nil { + return err + } + + return nil +} + +// HGetObjectFromRedis hash get from redis +func HGetObjectFromRedis(key, field string) (string, error) { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + ret, err := RedisUtil.HGet(fullKey, field).Result() + if err != nil { + return "", err + } + return ret, nil +} + +func HDelObjectFromRedis(key string, fields []string) error { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + if len(fields) <= 0 { + return nil + } + + err := RedisUtil.HDel(fullKey, fields...).Err() + + if err != nil { + return err + } + return nil +} + +func SaddObjectToRedis(key string, members []interface{}) error { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + if len(members) <= 0 { + return nil + } + + err := RedisUtil.SAdd(fullKey, members...).Err() + + if err != nil { + return err + } + return nil +} + +func SremObjectFromRedis(key string, members []interface{}) error { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + if len(members) <= 0 { + return nil + } + + err := RedisUtil.SRem(fullKey, members...).Err() + + if err != nil { + return err + } + return nil +} + +func SmembersFromRedis(key string) ([]string, error) { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + members, err := RedisUtil.SMembers(fullKey).Result() + + if err != nil { + return nil, err + } + return members, nil +} diff --git a/bmp-openapi-console/swagger.json b/bmp-openapi-console/swagger.json new file mode 100644 index 0000000..8331395 --- /dev/null +++ b/bmp-openapi-console/swagger.json @@ -0,0 +1,12526 @@ +{ + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "schemes": [ + "http" + ], + "swagger": "2.0", + "info": { + "description": "the purpose of this application is to provide an application\nthat is using plain go code to define an API\n\nThis should demonstrate all the possible comment annotations\nthat are available to turn go code into a fully compliant swagger 2.0 spec", + "title": "CPS", + "termsOfService": "there are no TOS at this moment, use at your own risk we take no responsibility", + "contact": { + "email": "minping@jd.com" + }, + "license": { + "name": "MIT", + "url": "http://opensource.org/licenses/MIT" + }, + "version": "0.0.1" + }, + "host": "bmp-openapi-console.bmp.local", + "basePath": "/v1", + "paths": { + "/auditLogs": { + "get": { + "description": "DescribeAuditLogs 获取审计日志列表", + "tags": [ + "auditLog" + ], + "operationId": "describeAuditLogs", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "description": "instance_id", + "name": "instance_id", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Operation", + "description": "操作名称", + "name": "operation", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserName", + "description": "操作人", + "name": "username", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Result", + "description": "result", + "name": "result", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "StartTime", + "description": "操作时间下限", + "name": "startTime", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "EndTime", + "description": "操作时间上限", + "name": "endTime", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示所有", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeAuditLogs" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/auditLogs/types": { + "get": { + "description": "DescribeAuditLogTypes 获取审计日志类型", + "tags": [ + "auditLog" + ], + "operationId": "describeAuditLogTypes", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeAuditLogTypes" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/deviceTypes": { + "get": { + "description": "DescribeDeviceTypes 获取机型列表", + "tags": [ + "deviceType" + ], + "operationId": "describeDeviceTypes", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "description": "机型id", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceType", + "description": "机型规格", + "name": "deviceType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IdcID", + "description": "机房id", + "name": "idcId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Name", + "description": "机型名称", + "name": "name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceSeries", + "description": "机型类型", + "name": "deviceSeries", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDeviceTypes" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/deviceTypes/deviceTypeImage": { + "get": { + "description": "QueryDeviceTypeImage 根据机型获取镜像", + "tags": [ + "deviceType" + ], + "operationId": "describeDeviceTypeImages", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "description": "机型id", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ImageID", + "description": "镜像id", + "name": "imageId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Architecture", + "description": "体系架构", + "name": "architecture", + "in": "query" + }, + { + "type": "string", + "x-go-name": "OsType", + "description": "操作系统平台", + "name": "osType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ImageName", + "description": "镜像名称", + "name": "imageName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Version", + "description": "版本号", + "name": "version", + "in": "query" + }, + { + "type": "string", + "x-go-name": "OsID", + "description": "操作系统ID", + "name": "osId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Source", + "description": "镜像类型,预置,自定义", + "name": "source", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDeviceTypeImages" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/deviceTypes/deviceTypeImagePartition": { + "get": { + "description": "QueryDeviceTypeImagePartition 根据机型,镜像,获取分区", + "tags": [ + "deviceType" + ], + "operationId": "describeDeviceTypeImagePartitions", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "description": "机型id", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ImageID", + "description": "镜像id", + "name": "imageId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示所有,isAll=1显示所有", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDeviceTypeImagePartitions" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/deviceTypes/volumesRaids": { + "get": { + "description": "DescribeVolumesRaids 根据机型获取卷和raid信息 (deviceTypeRaid-\u003evolumesRaids)", + "tags": [ + "deviceType" + ], + "operationId": "describeVolumesRaids", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "description": "机型id", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "VolumeType", + "description": "系统盘还是数据盘", + "name": "volumeType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示所有", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeVolumesRaids" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/deviceTypes/{device_type_id}": { + "get": { + "description": "DescribeDeviceType 获取机型详情", + "tags": [ + "deviceType" + ], + "operationId": "describeDeviceType", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "name": "device_type_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDeviceType" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/devices": { + "get": { + "description": "DescribeDevices 获取设备列表", + "tags": [ + "device" + ], + "operationId": "describeDevices", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IDcID", + "description": "机房id", + "name": "idcId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Sn", + "description": "设备sn", + "name": "sn", + "in": "query" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "description": "实例id", + "name": "instanceId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "description": "机型id", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ManageStatus", + "description": "设备管理状态", + "name": "manageStatus", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IloIP", + "description": "带外ip", + "name": "iloIp", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IPV4", + "description": "ipv4", + "name": "ipv4", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IPV6", + "description": "ipv6", + "name": "ipv6", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceSeries", + "description": "机型类型", + "name": "deviceSeries", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserID", + "description": "所属用户id", + "name": "userId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserName", + "description": "所属用户", + "name": "userName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部,1不分页", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDevices" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/devices/stock": { + "delete": { + "description": "DescribeDeviceStock 获取指定机型的设备库存", + "tags": [ + "device" + ], + "operationId": "describeDeviceStock", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "name": "deviceTypeId", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDeviceStock" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/devices/{device_id}": { + "get": { + "description": "DescribeDevice 获取设备详情", + "tags": [ + "device" + ], + "operationId": "describeDevice", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceID", + "name": "device_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDevice" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/idcs": { + "get": { + "description": "DescribeIdcs 获取idc列表", + "tags": [ + "idc" + ], + "operationId": "describeIdcs", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Name", + "description": "机房名称", + "name": "name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "NameEn", + "description": "机房英文名称", + "name": "nameEn", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Level", + "description": "机房等级", + "name": "level", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示所有", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeIdcs" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/idcs/{idc_id}": { + "get": { + "description": "DescribeIdc 获取idc详情", + "tags": [ + "idc" + ], + "operationId": "describeIdc", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "IdcID", + "name": "idc_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeIdc" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/images": { + "get": { + "description": "DescribeImages 获取镜像列表", + "tags": [ + "image" + ], + "operationId": "describeImages", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ImageID", + "description": "镜像ID", + "name": "imageId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ImageName", + "description": "镜像名称", + "name": "imageName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "description": "设备类型id", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Version", + "description": "版本号", + "name": "version", + "in": "query" + }, + { + "type": "string", + "x-go-name": "OsID", + "description": "操作系统ID", + "name": "osId", + "in": "query" + }, + { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "ImageIDs", + "description": "镜像ID,数组,支持多个", + "name": "imageIds", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Source", + "description": "镜像类型,预置,自定义", + "name": "source", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Architecture", + "description": "体系架构", + "name": "architecture", + "in": "query" + }, + { + "type": "string", + "x-go-name": "OsType", + "description": "操作系统平台", + "name": "osType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeImages" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/images/imageDeviceTypes": { + "get": { + "description": "DescribeImageDeviceTypes 查看镜像绑定的机型", + "tags": [ + "image" + ], + "operationId": "describeImageDeviceTypes", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ImageID", + "description": "镜像ID", + "name": "imageId", + "in": "query", + "required": true + }, + { + "type": "string", + "x-go-name": "Architecture", + "description": "体系架构", + "name": "architecture", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsBind", + "description": "镜像是否绑定了机型,0查询该镜像没有绑定的机型列表 1查询该镜像已经绑定了的机型列表", + "name": "isBind", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeImageDeviceTypes" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/images/{image_id}": { + "get": { + "description": "DescribeImage 获取镜像详情", + "tags": [ + "image" + ], + "operationId": "describeImage", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ImageID", + "name": "image_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeImage" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/license/content": { + "get": { + "description": "DescribeLicenseContent 获取授权详情", + "tags": [ + "license" + ], + "operationId": "describeLicenseContent", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeLicenseContent" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/local/users": { + "get": { + "description": "DescribeLocalUser 控制台获取用户详情", + "tags": [ + "user" + ], + "operationId": "describeLocalUser", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeLocalUser" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyLocalUser 控制台修改除密码外的个人信息", + "tags": [ + "user" + ], + "operationId": "modifyLocalUser", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyLocalUserRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyLocalUser" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/local/users/password": { + "put": { + "description": "ModifyLocalUserPassword 控制台修改个人密码", + "tags": [ + "user" + ], + "operationId": "modifyLocalUserPassword", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyUserPasswordRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyLocalUserPassword" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages": { + "get": { + "description": "GetMessageList 获取message列表(分页)", + "tags": [ + "message" + ], + "operationId": "getMessageList", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部,取值为1时表示全部", + "name": "isAll", + "in": "query" + }, + { + "type": "string", + "x-go-name": "HasRead", + "description": "0:未读;1:已读;\"\"不传表示全部", + "name": "hasRead", + "in": "query" + }, + { + "type": "string", + "x-go-name": "MessageType", + "description": "消息类型", + "name": "messageType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "MessageSubType", + "description": "消息子类型", + "name": "messageSubType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Detail", + "description": "内容模糊搜索", + "name": "detail", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getMessageList" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages/delete": { + "delete": { + "description": "DeleteMessage 删除消息(可多条)", + "tags": [ + "message" + ], + "operationId": "deleteMessage", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/DeleteMessagesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteMessage" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages/doRead": { + "put": { + "description": "ReadMessage 将消息设置为已读(可多条)", + "tags": [ + "message" + ], + "operationId": "readMessage", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ReadMessagesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/readMessage" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages/getMessageById": { + "get": { + "description": "GetMessageById 获取消息详情,包括上一条/下一条的messageid", + "tags": [ + "message" + ], + "operationId": "getMessageById", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "MessageID", + "name": "messageId", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/getMessageById" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages/getMessageTypes": { + "get": { + "description": "GetMessageTypes 获取消息类型/子类型", + "tags": [ + "message" + ], + "operationId": "getMessageTypes", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getMessageTypes" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages/hasUnreadMessage": { + "get": { + "description": "HasUnreadMessage 获取有没有未读消息", + "tags": [ + "message" + ], + "operationId": "hasUnreadMessage", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/hasUnreadMessage" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages/statistic": { + "get": { + "description": "GetMessageStatistic 获取message总数和未读数", + "tags": [ + "message" + ], + "operationId": "getMessageStatistic", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getMessageStatistic" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorAlert/addAlert": { + "post": { + "description": "AddAlert 添加(接收)告警", + "tags": [ + "monitorAlert" + ], + "operationId": "addAlert", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/AddAlertRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/addAlert" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorAlert/deleteAlert": { + "delete": { + "description": "DeleteAlert 删除告警", + "tags": [ + "monitorAlert" + ], + "operationId": "deleteAlert", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/DeleteAlertRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteAlert" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorAlert/describeAlert": { + "get": { + "description": "DescribeAlert 告警详情", + "tags": [ + "monitorAlert" + ], + "operationId": "describeAlert", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "AlertID", + "description": "rule uuid", + "name": "alertId", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeAlert" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorAlert/describeAlerts": { + "get": { + "description": "DescribeAlerts 告警列表", + "tags": [ + "monitorAlert" + ], + "operationId": "describeAlerts", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部,取值为1时表示全部", + "name": "isAll", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserID", + "description": "user uuid", + "name": "userId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserName", + "description": "username", + "name": "userName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "RuleName", + "description": "规则名称", + "name": "ruleName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "RuleID", + "description": "规则uuid", + "name": "ruleId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ResourceID", + "description": "资源id,目前就是实例id", + "name": "resourceId", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "StartTime", + "description": "报警时间筛选stime", + "name": "startTime", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "EndTime", + "description": "报警时间筛选etime", + "name": "endTime", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "description": "project uuid", + "name": "projectId", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeAlerts" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorData": { + "get": { + "description": "GetMonitorData 获取图表监控数据", + "tags": [ + "monitorData" + ], + "operationId": "getMonitorData", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "MetricName", + "description": "指标名称,支持多个,用逗号隔离开", + "name": "metricName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "description": "实例id", + "name": "instanceId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Device", + "description": "标签值", + "name": "device", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "StartTime", + "description": "开始时间戳", + "name": "startTime", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "EndTime", + "description": "结束时间戳", + "name": "endTime", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "TimeInterval", + "description": "间隔多久一个点 s为单位", + "name": "timeInterval", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "LastManyTime", + "description": "最近多少时间,小时为单位", + "name": "lastManyTime", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DownSampleType", + "description": "avg, min, max, sum", + "name": "downSampleType", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getMonitorData" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorProxy/desrcibeAgentStatus": { + "get": { + "description": "DesrcibeAgentStatus 获取agent状态", + "tags": [ + "monitorProxy" + ], + "operationId": "desrcibeAgentStatus", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "description": "InstanceId,多个用逗号分隔", + "name": "instanceId", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/desrcibeAgentStatus" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorProxy/desrcibeTags": { + "get": { + "description": "DesrcibeAgentStatus 获取tag列表", + "tags": [ + "monitorProxy" + ], + "operationId": "desrcibeTags", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "description": "instanceId", + "name": "instanceId", + "in": "query", + "required": true + }, + { + "type": "string", + "x-go-name": "TagName", + "description": "tagName [disk mountpoint nic]", + "name": "tagName", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/desrcibeTags" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorRule/addRule": { + "post": { + "description": "AddRule 添加规则", + "tags": [ + "monitorRule" + ], + "operationId": "addRule", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/AddRuleRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/addRule" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorRule/deleteRule": { + "delete": { + "description": "DeleteRule 删除规则", + "tags": [ + "monitorRule" + ], + "operationId": "deleteRule", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/DeleteRuleRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteRule" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorRule/describeRule": { + "get": { + "description": "DescribeRule 规则详情", + "tags": [ + "monitorRule" + ], + "operationId": "describeRule", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "RuleID", + "description": "rule uuid", + "name": "ruleId", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeRule" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorRule/describeRules": { + "get": { + "description": "DescribeRules 规则列表", + "tags": [ + "monitorRule" + ], + "operationId": "describeRules", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部,取值为1时表示全部", + "name": "isAll", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserID", + "description": "user uuid", + "name": "userId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserName", + "description": "username", + "name": "userName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "RuleName", + "description": "规则名称,模糊搜索", + "name": "ruleName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "RuleID", + "description": "规则uuid", + "name": "ruleId", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "Status", + "description": "规则状态[1-\u003e正常,2-\u003e禁用,3-\u003e报警]", + "name": "status", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "description": "project uuid", + "name": "projectId", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeRules" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorRule/disableRule": { + "put": { + "description": "DisableRule 禁用规则", + "tags": [ + "monitorRule" + ], + "operationId": "disableRule", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/DisableRuleRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/disableRule" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorRule/editRule": { + "put": { + "description": "EditRule 编辑规则", + "tags": [ + "monitorRule" + ], + "operationId": "editRule", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/EditRuleRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/editRule" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorRule/enableRule": { + "put": { + "description": "EnableRule 启用规则", + "tags": [ + "monitorRule" + ], + "operationId": "enableRule", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/EnableRuleRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/enableRule" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/oss": { + "get": { + "description": "DescribeOSs 获取os列表(暂不启用)", + "tags": [ + "os" + ], + "operationId": "describeOSs", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "OsName", + "description": "操作系统名称", + "name": "osName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "OsType", + "description": "操作系统平台", + "name": "osType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "OsVersion", + "description": "操作系统版本", + "name": "osVersion", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示所有", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeOSs" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/oss/{os_id}": { + "get": { + "description": "DescribeOS 获取os系统详情(暂不启用)", + "tags": [ + "os" + ], + "operationId": "describeOS", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "OsID", + "name": "os_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeOS" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances": { + "get": { + "description": "DescribeProjectInstances 获取实例列表", + "tags": [ + "instance" + ], + "operationId": "describeProjectInstances", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "description": "实例ID", + "name": "instanceId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "InstanceName", + "description": "实例名称,模糊搜索", + "name": "instanceName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "description": "设备类型ID", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Status", + "description": "运行状态", + "name": "status", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceID", + "description": "设备ID", + "name": "deviceId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Sn", + "description": "SN", + "name": "sn", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IdcID", + "description": "机房ID", + "name": "idcId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "description": "项目ID", + "name": "projectId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IloIP", + "description": "带外ip,精确搜索", + "name": "ilo_ip", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IPV4", + "description": "ipv4,精确搜索", + "name": "ipv4", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IPV6", + "description": "ipv6,精确搜索", + "name": "ipv6", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部,取值为1时表示全部", + "name": "isAll", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsInstallAgent", + "description": "是否安装了agent,\"0\"表示未安装,\"1\"表示已安装,不传表示全部", + "name": "isInstallAgent", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeProjectInstances" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateProjectInstance 创建实例", + "tags": [ + "instance" + ], + "operationId": "createProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateInstanceRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/batch/instances:deleteInstances": { + "delete": { + "description": "DeleteInstances 批量删除实例", + "tags": [ + "instance" + ], + "operationId": "deleteInstances", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/DeleteInstancesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteInstances" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/batch/instances:modifyInstances": { + "put": { + "description": "ModifyInstances 批量修改实例名称", + "tags": [ + "instance" + ], + "operationId": "modifyInstances", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyInstancesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyInstances" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/batch/instances:resetPasswd": { + "put": { + "description": "ResetInstancesPasswd 批量重置密码", + "tags": [ + "instance" + ], + "operationId": "resetProjectInstancesPasswd", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ResetInstancesPasswdRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/resetProjectInstancesPasswd" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/batch/instances:restartInstances": { + "put": { + "description": "StartInstances 批量重启", + "tags": [ + "instance" + ], + "operationId": "restartInstances", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/RestartInstancesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/restartInstances" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/batch/instances:startInstances": { + "put": { + "description": "StartInstances 批量开机", + "tags": [ + "instance" + ], + "operationId": "startInstances", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/StartInstancesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/startInstances" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/batch/instances:stopInstances": { + "put": { + "description": "StartInstances 批量关机", + "tags": [ + "instance" + ], + "operationId": "stopInstances", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/StopInstancesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/stopInstances" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/share/describeInstances": { + "get": { + "description": "DescribeInstancesByProjectIdAndOwnerNameAndSharerName 根据projectid,ownername,username来获取实例列表。为了支持部分资源转移中的实例列表", + "tags": [ + "instance" + ], + "operationId": "describeInstancesByProjectIdAndOwnerNameAndSharerName", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "description": "项目ID", + "name": "projectId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "name": "isAll", + "in": "query" + }, + { + "type": "string", + "x-go-name": "OwnerName", + "name": "ownerName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "SharerName", + "name": "sharerName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "InstanceName", + "description": "这两项支持模糊搜索", + "name": "instanceName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instanceId", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeInstancesByProjectIdAndOwnerNameAndSharerName" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}": { + "get": { + "description": "DescribeProjectInstance 获取实例详情", + "tags": [ + "instance" + ], + "operationId": "describeProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "description": "实例uuid", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyProjectInstance 修改实例信息", + "tags": [ + "instance" + ], + "operationId": "modifyProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyInstanceRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteProjectInstance 删除实例", + "tags": [ + "instance" + ], + "operationId": "deleteProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/lock": { + "put": { + "description": "LockProjectInstance 锁定实例", + "tags": [ + "instance" + ], + "operationId": "lockProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/lockProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/reinstallInstance": { + "put": { + "description": "ReinstallInstance 重装实例", + "tags": [ + "instance" + ], + "operationId": "reinstallProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ReinstallInstanceRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/reinstallProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/resetStatus": { + "put": { + "description": "ResetInstanceStatus 重置实例状态", + "tags": [ + "instance" + ], + "operationId": "resetInstanceStatus", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/resetInstanceStatus" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/resetpasswd": { + "put": { + "description": "ResetPasswd 重置密码", + "tags": [ + "instance" + ], + "operationId": "resetProjectInstancePasswd", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ResetInstancePasswdRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/resetProjectInstancePasswd" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/restart": { + "put": { + "description": "RestartProjectInstance 实例重启", + "tags": [ + "instance" + ], + "operationId": "restartProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/restartProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/start": { + "put": { + "description": "StartProjectInstance 实例开机", + "tags": [ + "instance" + ], + "operationId": "startProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/startProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/stop": { + "put": { + "description": "StopProjectInstance 实例关机", + "tags": [ + "instance" + ], + "operationId": "stopProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/stopProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/unlock": { + "put": { + "description": "UnLockProjectInstance 解锁实例", + "tags": [ + "instance" + ], + "operationId": "unLockProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/unLockProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/resources": { + "get": { + "description": "DescribeResources 根据某个字段值精确查询对应的资源列表(如根据imageName查询镜像列表,根据idcName查询机房列表)", + "tags": [ + "resource" + ], + "operationId": "describeResources", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "Name", + "description": "机房名称\nIdcName string `json:\"idcName\"`\n机房英文名称\nIdcNameEn string `json:\"idcNameEn\"`*/\n机型名称", + "name": "name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceType", + "description": "机型规格", + "name": "deviceType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ImageName", + "description": "镜像名称", + "name": "imageName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserName", + "description": "用户名称", + "name": "userName", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeResources" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/roles": { + "get": { + "description": "DescribeRoles 获取角色列表", + "tags": [ + "role" + ], + "operationId": "describeRoles", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示所有", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeRoles" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/roles/roleInfo/current": { + "get": { + "description": "CurrentRole 获取当前登录用户的角色", + "tags": [ + "role" + ], + "operationId": "currentRole", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/currentRole" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/roles/{role_id}": { + "get": { + "description": "DescribeRole 获取角色详情", + "tags": [ + "role" + ], + "operationId": "describeRole", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "RoleID", + "name": "role_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeRole" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/apikeys": { + "get": { + "description": "DescribeUserAPIKeys 获取APIKey列表", + "tags": [ + "apiKey" + ], + "operationId": "describeUserAPIKeys", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Name", + "description": "秘钥对名称", + "name": "name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Type", + "description": "Token类型, [system/user]", + "name": "type", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否查询全部/导出", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUserAPIKeys" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateUserApikey 创建apikey", + "tags": [ + "apiKey" + ], + "operationId": "createUserApikey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateApikeyRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createUserApikey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/apikeys/{apikey_id}": { + "get": { + "description": "DescribeUserAPIKey 获取apikey详情", + "tags": [ + "apiKey" + ], + "operationId": "describeUserAPIKey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ApikeyID", + "name": "apikey_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUserAPIKey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyUserApikey 修改apikey(暂不启用)", + "tags": [ + "apiKey" + ], + "operationId": "modifyUserApikey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ApikeyID", + "name": "apikey_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyApikeyRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyUserApikey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteUserApikey 删除某个apikey", + "tags": [ + "apiKey" + ], + "operationId": "deleteUserApikey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ApikeyID", + "name": "apikey_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteUserApikey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/projects": { + "get": { + "description": "DescribeUserProjects 获取项目列表", + "tags": [ + "project" + ], + "operationId": "describeUserProjects", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ProjectName", + "description": "项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-”", + "name": "projectName", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "Owned", + "description": "0表示全部,1表示拥有者,2表示被共享者", + "name": "owned", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "name": "isAll", + "in": "query" + }, + { + "type": "string", + "x-go-name": "OrderByCreatetime", + "description": "按创建时间asc/desc排列", + "name": "orderByCreatetime", + "in": "query" + }, + { + "type": "string", + "x-go-name": "OwnerName", + "description": "新增可选,按用户名查找", + "name": "ownerName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "SharerName", + "description": "新增可选,按被转移用户的用户名查找它拥有的项目", + "name": "sharerName", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUserProjects" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateUserProject 创建项目", + "tags": [ + "project" + ], + "operationId": "createUserProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateProjectRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createUserProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/projects/move/instances": { + "put": { + "description": "MoveUserInstances 转移项目下的某些实例", + "tags": [ + "project" + ], + "operationId": "moveUserInstances", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/MoveInstancesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/moveUserInstances" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/projects/{project_id}": { + "get": { + "description": "DescribeUserProject 获取项目详情", + "tags": [ + "project" + ], + "operationId": "describeUserProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUserProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyUserProject 修改项目信息", + "tags": [ + "project" + ], + "operationId": "modifyUserProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyProjectRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyUserProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteUserProject 删除项目", + "tags": [ + "project" + ], + "operationId": "deleteUserProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteUserProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/projects/{project_id}/cancelShare": { + "put": { + "description": "CancelShareUserProject 取消共享项目", + "tags": [ + "project" + ], + "operationId": "cancelShareUserProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CalcelShareProjectRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/cancelShareUserProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/projects/{project_id}/describeSharProject": { + "get": { + "description": "DescribeShareUserProject 获取共享项目详情", + "tags": [ + "project" + ], + "operationId": "describeShareProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeShareProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/projects/{project_id}/description": { + "put": { + "description": "ModifyUserProject 修改项目信息", + "tags": [ + "project" + ], + "operationId": "modifyUserProjectDescription", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyProjectDescriptionRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyUserProjectDescription" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/projects/{project_id}/move": { + "put": { + "description": "MoveUserProject 转移项目", + "tags": [ + "project" + ], + "operationId": "moveUserProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/MoveProjectRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/moveUserProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/projects/{project_id}/share": { + "put": { + "description": "ShareUserProject 共享项目", + "tags": [ + "project" + ], + "operationId": "shareUserProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ShareProjectRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/shareUserProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/sshkeys": { + "get": { + "description": "DescribeUserSshKeys 获取个人sshkey列表", + "tags": [ + "sshkey" + ], + "operationId": "describeUserSshKeys", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Name", + "description": "秘钥名称", + "name": "name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUserSshKeys" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateUserSshkey 创建个人sshkey", + "tags": [ + "sshkey" + ], + "operationId": "createUserSshkey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateSshkeyRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createUserSshkey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/sshkeys/instances/{sshkey_id}": { + "get": { + "description": "GetInstancesBySshkey 根据sshkey获取实例列表", + "tags": [ + "sshkey" + ], + "operationId": "getInstancesBySshkey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "SshkeyID", + "name": "sshkey_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/getInstancesBySshkey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/sshkeys/{sshkey_id}": { + "get": { + "description": "DescribeUserSshKey 获取sshkey详情", + "tags": [ + "sshkey" + ], + "operationId": "describeUserSshKey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "SshkeyID", + "name": "sshkey_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUserSshKey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyUserSshkey 修改sshkey", + "tags": [ + "sshkey" + ], + "operationId": "modifyUserSshkey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "SshkeyID", + "name": "sshkey_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifySshkeyRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyUserSshkey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteUserSshkey 删除sshkey", + "tags": [ + "sshkey" + ], + "operationId": "deleteUserSshkey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "SshkeyID", + "name": "sshkey_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteUserSshkey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/users": { + "get": { + "description": "DescribeUsers 获取用户列表", + "tags": [ + "user" + ], + "operationId": "describeUsers", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "RoleID", + "description": "角色uuid", + "name": "roleId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DefaultProjectID", + "description": "项目uuid", + "name": "defaultProjectId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserName", + "description": "用户名", + "name": "userName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部, isAll=1表示全部", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUsers" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/users/getUserByName": { + "get": { + "description": "DescribeUserByName 根据用户名获取用户详情", + "tags": [ + "user" + ], + "operationId": "describeUserByName", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "UserName", + "description": "用户名,唯一", + "name": "userName", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUserByName" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/users/verify": { + "post": { + "description": "VerifyUser 鉴定用户", + "tags": [ + "user" + ], + "operationId": "verifyUser", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/VerifyUserRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/verifyUser" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/users/{user_id}": { + "get": { + "description": "DescribeUser 获取用户详情", + "tags": [ + "user" + ], + "operationId": "describeUser", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "UserID", + "name": "user_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUser" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyUser 修改用户信息", + "tags": [ + "user" + ], + "operationId": "modifyUser", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "UserID", + "name": "user_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyUserRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyUser" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + } + }, + "definitions": { + "AddAlertItem": { + "type": "object", + "required": [ + "ruleId", + "instanceId", + "trigger", + "alertValue", + "alertTimestamp", + "alertPeriod" + ], + "properties": { + "alertPeriod": { + "description": "告警持续时间", + "type": "integer", + "format": "int64", + "x-go-name": "AlertPeriod" + }, + "alertTimestamp": { + "description": "告警时间戳", + "type": "integer", + "format": "int64", + "x-go-name": "AlertTimestamp" + }, + "alertValue": { + "description": "告警值", + "type": "string", + "x-go-name": "AlertValue" + }, + "calculationUnit": { + "description": "计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出]", + "type": "string", + "x-go-name": "CalculationUnit" + }, + "instanceId": { + "description": "实例id", + "type": "string", + "x-go-name": "InstanceID" + }, + "isRecover": { + "description": "是否为恢复通知,0为不是,1为是", + "type": "integer", + "format": "int64", + "x-go-name": "IsRecover" + }, + "ruleId": { + "description": "规则ID", + "type": "string", + "x-go-name": "RuleID" + }, + "ruleName": { + "description": "规则名称", + "type": "string", + "x-go-name": "RuleName" + }, + "trigger": { + "description": "触发条件", + "type": "string", + "x-go-name": "Trigger" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "AddAlertRequest": { + "type": "object", + "properties": { + "alerts": { + "type": "array", + "items": { + "$ref": "#/definitions/AddAlertItem" + }, + "x-go-name": "Alerts" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "AddRuleRequest": { + "type": "object", + "required": [ + "projectId", + "ruleName", + "dimension", + "resource", + "triggerOption", + "noticeOption", + "instanceIds" + ], + "properties": { + "deviceTag": { + "description": "盘符、挂载点、网口列表", + "type": "string", + "x-go-name": "DeviceTag" + }, + "dimension": { + "description": "维度 [instance、disk、mountpoint、nic]", + "type": "string", + "x-go-name": "Dimension" + }, + "instanceIds": { + "description": "实例id列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + }, + "noticeOption": { + "$ref": "#/definitions/RuleNotice" + }, + "projectId": { + "description": "规则所属的项目uuid", + "type": "string", + "x-go-name": "ProjectID" + }, + "resource": { + "description": "资源类型,目前只支持instance", + "type": "string", + "x-go-name": "Resource" + }, + "ruleName": { + "description": "规则名称", + "type": "string", + "x-go-name": "RuleName" + }, + "triggerOption": { + "description": "触发条件", + "type": "array", + "items": { + "$ref": "#/definitions/RuleTrigger" + }, + "x-go-name": "TriggerOption" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "AgentStatusItem": { + "type": "object", + "properties": { + "agent_version": { + "type": "string", + "x-go-name": "AgentVersion" + }, + "instance_id": { + "type": "string", + "x-go-name": "InstanceID" + }, + "sn": { + "type": "string", + "x-go-name": "SN" + }, + "status": { + "description": "1-\u003erunning 2-\u003estopped 0-\u003eunknown", + "type": "integer", + "format": "int64", + "x-go-name": "Status" + }, + "statusName": { + "description": "status 运行 停止 未知", + "type": "string", + "x-go-name": "StatusName" + }, + "timestamp": { + "type": "integer", + "format": "int64", + "x-go-name": "Timestamp" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "AgentStatusResponse": { + "type": "object", + "properties": { + "agentStatus": { + "type": "array", + "items": { + "$ref": "#/definitions/AgentStatusItem" + }, + "x-go-name": "AgentStatus" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Alert": { + "type": "object", + "properties": { + "alertId": { + "description": "alert uuid", + "type": "string", + "x-go-name": "AlertID" + }, + "alertLevel": { + "description": "1表示一般,2表示严重,3表示紧急", + "type": "integer", + "format": "int64", + "x-go-name": "AlertLevel" + }, + "alertLevelDescription": { + "description": "级别描述", + "type": "string", + "x-go-name": "AlertLevelDescription" + }, + "alertPeriod": { + "description": "告警持续时间(分钟为单位)", + "type": "integer", + "format": "int64", + "x-go-name": "AlertPeriod" + }, + "alertTime": { + "description": "告警时间戳", + "type": "integer", + "format": "int64", + "x-go-name": "AlertTime" + }, + "alertValue": { + "description": "报警值", + "type": "string", + "x-go-name": "AlertValue" + }, + "createdTime": { + "description": "创建时间戳", + "type": "integer", + "format": "int64", + "x-go-name": "CreatedTime" + }, + "instance": { + "$ref": "#/definitions/Instance" + }, + "resource": { + "description": "资源类型 [只支持instance一种]", + "type": "string", + "x-go-name": "Resource" + }, + "resourceId": { + "description": "资源id,目前就是实例id", + "type": "string", + "x-go-name": "ResourceID" + }, + "resourceName": { + "description": "资源名称,目前就是实例名称", + "type": "string", + "x-go-name": "ResourceName" + }, + "rule": { + "$ref": "#/definitions/Rule" + }, + "trigger": { + "description": "触发条件,接口需要翻译", + "type": "string", + "x-go-name": "Trigger" + }, + "triggerDescription": { + "description": "触发条件描述", + "type": "string", + "x-go-name": "TriggerDescription" + }, + "userId": { + "description": "通知对象 userid", + "type": "string", + "x-go-name": "UserID" + }, + "userName": { + "description": "通知对象 用户名", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "AlertList": { + "type": "object", + "properties": { + "instances": { + "description": "rules数组", + "type": "array", + "items": { + "$ref": "#/definitions/Alert" + }, + "x-go-name": "Alerts" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Apikey": { + "type": "object", + "required": [ + "apiKeyId", + "name", + "readOnly", + "token", + "type", + "userId" + ], + "properties": { + "apiKeyId": { + "description": "apikey uuid", + "type": "string", + "x-go-name": "ApikeyID" + }, + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "id": { + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "name": { + "description": "名称", + "type": "string", + "x-go-name": "Name" + }, + "readOnly": { + "description": "是否支持只读, [0/1], 1表示只读", + "type": "integer", + "format": "int8", + "x-go-name": "ReadOnly" + }, + "token": { + "description": "32位字符令牌,使用token来独立访问openapi", + "type": "string", + "x-go-name": "Token" + }, + "type": { + "description": "apikey的类型,[system/user]", + "type": "string", + "x-go-name": "Type" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "userId": { + "description": "所属用户uuid", + "type": "string", + "x-go-name": "UserID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ApikeyId": { + "type": "object", + "required": [ + "apikeyId" + ], + "properties": { + "apikeyId": { + "description": "apikey uuid", + "type": "string", + "x-go-name": "ApikeyId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ApikeyInfo": { + "type": "object", + "properties": { + "apikey": { + "$ref": "#/definitions/Apikey" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ApikeyList": { + "type": "object", + "properties": { + "apikeys": { + "type": "array", + "items": { + "$ref": "#/definitions/Apikey" + }, + "x-go-name": "Apikeys" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "AuditLog": { + "type": "object", + "properties": { + "deviceId": { + "description": "device_id", + "type": "string", + "x-go-name": "DeviceID" + }, + "failReason": { + "description": "失败原因", + "type": "string", + "x-go-name": "FailReason" + }, + "finishTime": { + "description": "完成时间", + "type": "integer", + "format": "int64", + "x-go-name": "FinishTime" + }, + "id": { + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "instanceId": { + "description": "instance_id", + "type": "string", + "x-go-name": "InstanceID" + }, + "logid": { + "description": "日志uuid", + "type": "string", + "x-go-name": "LogID" + }, + "operateTime": { + "description": "操作时间", + "type": "integer", + "format": "int64", + "x-go-name": "OperateTime" + }, + "operation": { + "description": "操作", + "type": "string", + "x-go-name": "Operation" + }, + "operationName": { + "description": "操作名称", + "type": "string", + "x-go-name": "OperationName" + }, + "result": { + "description": "结果 success/fail", + "type": "string", + "x-go-name": "Result" + }, + "sn": { + "description": "sn", + "type": "string", + "x-go-name": "Sn" + }, + "userID": { + "description": "操作人", + "type": "string", + "x-go-name": "UserID" + }, + "userName": { + "description": "操作人", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "AuditLogList": { + "type": "object", + "properties": { + "auditLogs": { + "description": "机型列表", + "type": "array", + "items": { + "$ref": "#/definitions/AuditLog" + }, + "x-go-name": "AuditLogs" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "AuditLogsType": { + "type": "object", + "properties": { + "name": { + "description": "name,自动适配中英文", + "type": "string", + "x-go-name": "Name" + }, + "operation": { + "description": "数据库中存储的operation", + "type": "string", + "x-go-name": "Operation" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "CalcelShareProjectRequest": { + "type": "object", + "required": [ + "ownerID", + "sharerID" + ], + "properties": { + "ownerID": { + "description": "from user_id", + "type": "string", + "x-go-name": "OwnerID" + }, + "sharerID": { + "description": "to user_id", + "type": "string", + "x-go-name": "SharerID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CommonResponse": { + "type": "object", + "properties": { + "success": { + "description": "操作是否成功 [true/false]", + "type": "boolean", + "x-go-name": "Success" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "CreateApikeyRequest": { + "type": "object", + "required": [ + "name", + "readOnly", + "type" + ], + "properties": { + "name": { + "description": "秘钥对名称", + "type": "string", + "x-go-name": "Name" + }, + "readOnly": { + "description": "是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法", + "type": "integer", + "format": "int8", + "x-go-name": "ReadOnly" + }, + "type": { + "description": "Token类型, [system/user]", + "type": "string", + "x-go-name": "Type" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateInstanceRequest": { + "type": "object", + "required": [ + "projectId", + "idcId", + "deviceTypeId", + "imageId", + "systemVolumeRaidId", + "instanceName" + ], + "properties": { + "VolumeRaids": { + "description": "数据卷和选择的raidid", + "type": "array", + "items": { + "$ref": "#/definitions/VolumeRaID" + }, + "x-go-name": "VolumeRaIDs" + }, + "bootMode": { + "description": "启动模式", + "type": "string", + "x-go-name": "BootMode" + }, + "count": { + "description": "创建数量", + "type": "integer", + "format": "int64", + "x-go-name": "Count" + }, + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description" + }, + "deviceTypeId": { + "description": "设备类型ID", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "hostname": { + "description": "主机名称", + "type": "string", + "x-go-name": "HostName" + }, + "idcId": { + "description": "机房ID", + "type": "string", + "x-go-name": "IdcID" + }, + "imageId": { + "description": "镜像ID", + "type": "string", + "x-go-name": "ImageID" + }, + "installBmpAgent": { + "description": "是否安装bmp-agent", + "type": "boolean", + "x-go-name": "InstallBmpAgent" + }, + "instanceName": { + "description": "实例名称", + "type": "string", + "x-go-name": "InstanceName" + }, + "password": { + "description": "密码", + "type": "string", + "x-go-name": "Password" + }, + "projectId": { + "description": "项目ID", + "type": "string", + "x-go-name": "ProjectID" + }, + "sshKeyId": { + "description": "秘钥ID", + "type": "string", + "x-go-name": "SshKeyID" + }, + "systemPartition": { + "description": "系统盘分区", + "type": "array", + "items": { + "$ref": "#/definitions/Partition" + }, + "x-go-name": "SystemPartition" + }, + "systemVolumeRaidId": { + "description": "系统盘RAID ID", + "type": "string", + "x-go-name": "SystemVolumeRaidID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateProjectRequest": { + "type": "object", + "required": [ + "projectName" + ], + "properties": { + "isDefault": { + "description": "是否作为该用户的默认项目, [0/1], 默认为0", + "type": "integer", + "format": "int8", + "x-go-name": "IsDefault" + }, + "isSystem": { + "description": "是否作为系统项目, [0/1], 默认为0", + "type": "integer", + "format": "int8", + "x-go-name": "IsSystem" + }, + "projectName": { + "description": "ProjectName 1~64字符,只支持数字、大小写字母、中英文下划线“_”及中划线“-”", + "type": "string", + "x-go-name": "ProjectName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateSshkeyRequest": { + "type": "object", + "required": [ + "name", + "key" + ], + "properties": { + "key": { + "description": "公钥内容,格式:^ssh-rsa AAAAB3NzaC1yc2.*", + "type": "string", + "x-go-name": "Key" + }, + "name": { + "description": "秘钥名称", + "type": "string", + "x-go-name": "Name" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "DataEveryMetric": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/MonitorDataItem" + }, + "x-go-name": "Data" + }, + "query": { + "$ref": "#/definitions/MonitorDataQuery" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeleteAlertRequest": { + "type": "object", + "required": [ + "alertId" + ], + "properties": { + "alertId": { + "description": "告警id", + "type": "string", + "x-go-name": "AlertId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "DeleteInstancesRequest": { + "description": "批量删除实例", + "type": "object", + "properties": { + "instance_ids": { + "description": "实例id列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIDs" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "DeleteMessagesRequest": { + "type": "object", + "required": [ + "messageIds" + ], + "properties": { + "messageIds": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "MessageIds" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "DeleteRuleRequest": { + "type": "object", + "required": [ + "ruleId" + ], + "properties": { + "ruleId": { + "description": "规则id", + "type": "string", + "x-go-name": "RuleId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "Device": { + "type": "object", + "required": [ + "idcId" + ], + "properties": { + "Enclosure2": { + "description": "系统盘2背板号", + "type": "string" + }, + "adapterId": { + "description": "adapter_id", + "type": "integer", + "format": "int64", + "x-go-name": "AdapterID" + }, + "architecture": { + "description": "体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64", + "type": "string", + "x-go-name": "Architecture" + }, + "brand": { + "description": "品牌", + "type": "string", + "x-go-name": "Brand" + }, + "cabinet": { + "description": "机柜编码", + "type": "string", + "x-go-name": "Cabinet" + }, + "cpuAmount": { + "description": "cpu数量", + "type": "integer", + "format": "int64", + "x-go-name": "CPUAmount" + }, + "cpuCores": { + "description": "单个cpu内核数", + "type": "integer", + "format": "int64", + "x-go-name": "CPUCores" + }, + "cpuFrequency": { + "description": "cpu频率(G)", + "type": "string", + "x-go-name": "CPUFrequency" + }, + "cpuInfo": { + "description": "拼装信息", + "type": "string", + "x-go-name": "CpuInfo" + }, + "cpuManufacturer": { + "description": "cpu厂商", + "type": "string", + "x-go-name": "CPUManufacturer" + }, + "cpuModel": { + "description": "cpu处理器型号", + "type": "string", + "x-go-name": "CPUModel" + }, + "cpuRoads": { + "description": "单个cpu路数", + "type": "integer", + "format": "int8", + "x-go-name": "CPURoads" + }, + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "dataVolumeAmount": { + "description": "数据盘数量", + "type": "integer", + "format": "int64", + "x-go-name": "DataVolumeAmount" + }, + "dataVolumeInterfaceType": { + "description": "数据盘接口类型(SATA,SAS,NVME)", + "type": "string", + "x-go-name": "DataVolumeInterfaceType" + }, + "dataVolumeSize": { + "description": "数据盘单盘大小", + "type": "integer", + "format": "int64", + "x-go-name": "DataVolumeSize" + }, + "dataVolumeType": { + "description": "数据盘类型(SSD,HDD)", + "type": "string", + "x-go-name": "DataVolumeType" + }, + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description" + }, + "deviceId": { + "description": "设备uuid", + "type": "string", + "x-go-name": "DeviceID" + }, + "deviceSeries": { + "description": "计算型,存储型", + "type": "string", + "x-go-name": "DeviceSeries" + }, + "deviceSeriesName": { + "description": "计算型,存储型", + "type": "string", + "x-go-name": "DeviceSeriesName" + }, + "deviceType": { + "description": "型号,机型规格cps.normal", + "type": "string", + "x-go-name": "DeviceType" + }, + "deviceTypeId": { + "description": "机型uuid", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "deviceTypeName": { + "description": "机型名称", + "type": "string", + "x-go-name": "DeviceTypeName" + }, + "dvInfo": { + "type": "string", + "x-go-name": "DvInfo" + }, + "enclosure1": { + "description": "添加到disk表, 系统盘1背板号", + "type": "string", + "x-go-name": "Enclosure1" + }, + "eth1Mask": { + "description": "eth1子网掩码", + "type": "string", + "x-go-name": "Eth1Mask" + }, + "gateway": { + "description": "网关地址", + "type": "string", + "x-go-name": "Gateway" + }, + "gpuAmount": { + "description": "gpu数量", + "type": "integer", + "format": "int64", + "x-go-name": "GpuAmount" + }, + "gpuInfo": { + "type": "string", + "x-go-name": "GpuInfo" + }, + "gpuManufacturer": { + "description": "gpu厂商", + "type": "string", + "x-go-name": "GpuManufacturer" + }, + "gpuModel": { + "description": "gpu处理器型号", + "type": "string", + "x-go-name": "GpuModel" + }, + "id": { + "description": "设备ID编号", + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "idcId": { + "description": "机房uuid", + "type": "string", + "x-go-name": "IdcID" + }, + "idcName": { + "description": "机房名称", + "type": "string", + "x-go-name": "IdcName" + }, + "idcNameEn": { + "description": "idcname", + "type": "string", + "x-go-name": "IDcNameEn" + }, + "iloIp": { + "description": "带外管理IP", + "type": "string", + "x-go-name": "IloIP" + }, + "iloPassword": { + "description": "带外账号密码", + "type": "string", + "x-go-name": "IloPassword" + }, + "iloUser": { + "description": "带外账号", + "type": "string", + "x-go-name": "IloUser" + }, + "imageName": { + "description": "实例镜像名称", + "type": "string", + "x-go-name": "ImageName" + }, + "instanceCreatedTime": { + "description": "实例创建时间", + "type": "string", + "x-go-name": "InstanceCreatedTime" + }, + "instanceDescription": { + "description": "实例描述", + "type": "string", + "x-go-name": "InstanceDescription" + }, + "instanceId": { + "description": "实例id", + "type": "string", + "x-go-name": "InstanceID" + }, + "instanceName": { + "description": "实例名称", + "type": "string", + "x-go-name": "InstanceName" + }, + "instanceReason": { + "description": "实例失败原因", + "type": "string", + "x-go-name": "InstanceReason" + }, + "instanceStatus": { + "description": "实例状态", + "type": "string", + "x-go-name": "InstanceStatus" + }, + "instanceStatusName": { + "description": "实例状态", + "type": "string", + "x-go-name": "InstanceStatusName" + }, + "interfaceMode": { + "description": "【网口模式】【网络设置】: bond单网口,dual双网口", + "type": "string", + "x-go-name": "InterfaceMode" + }, + "locked": { + "description": "实例是否锁定 锁定locked 未锁定unlocked", + "type": "string", + "x-go-name": "Locked" + }, + "mac1": { + "description": "MAC1(eth0)", + "type": "string", + "x-go-name": "Mac1" + }, + "mac2": { + "description": "MAC2(eth2)", + "type": "string", + "x-go-name": "Mac2" + }, + "manageStatus": { + "description": "设备状态: 未装机,已装机", + "type": "string", + "x-go-name": "ManageStatus" + }, + "manageStatusName": { + "description": "设备状态: 未装机,已装机", + "type": "string", + "x-go-name": "ManageStatusName" + }, + "mask": { + "description": "子网掩码", + "type": "string", + "x-go-name": "Mask" + }, + "memAmount": { + "description": "内存数量", + "type": "integer", + "format": "int64", + "x-go-name": "MemAmount" + }, + "memFrequency": { + "description": "内存主频(MHz)", + "type": "integer", + "format": "int64", + "x-go-name": "MemFrequency" + }, + "memInfo": { + "type": "string", + "x-go-name": "MemInfo" + }, + "memSize": { + "description": "单个内存大小(GB)", + "type": "integer", + "format": "int64", + "x-go-name": "MemSize" + }, + "memType": { + "description": "内存接口(如DDR3,DDR4)", + "type": "string", + "x-go-name": "MemType" + }, + "model": { + "description": "型号", + "type": "string", + "x-go-name": "Model" + }, + "nicAmount": { + "description": "网卡数量", + "type": "integer", + "format": "int64", + "x-go-name": "NicAmount" + }, + "nicInfo": { + "type": "string", + "x-go-name": "NicInfo" + }, + "nicRate": { + "description": "网卡传输速率(GE)", + "type": "integer", + "format": "int64", + "x-go-name": "NicRate" + }, + "privateEth1Ipv4": { + "description": "eth1内网IPV4", + "type": "string", + "x-go-name": "PrivateEth1IPv4" + }, + "privateEth1Ipv6": { + "description": "eth1内网IPV6", + "type": "string", + "x-go-name": "PrivateEth1IPv6" + }, + "privateIpv4": { + "description": "内网IPV4", + "type": "string", + "x-go-name": "PrivateIPv4" + }, + "privateIpv6": { + "description": "内网IPV6", + "type": "string", + "x-go-name": "PrivateIPv6" + }, + "raidDriver": { + "description": "raid工具:(megacli64等)", + "type": "string", + "x-go-name": "RaidDriver" + }, + "reason": { + "description": "设备状态变更失败原因", + "type": "string", + "x-go-name": "Reason" + }, + "slot1": { + "description": "系统盘1槽位", + "type": "integer", + "format": "int64", + "x-go-name": "Slot1" + }, + "slot2": { + "description": "系统盘2槽位", + "type": "integer", + "format": "int64", + "x-go-name": "Slot2" + }, + "sn": { + "description": "设备SN", + "type": "string", + "x-go-name": "Sn" + }, + "svInfo": { + "type": "string", + "x-go-name": "SvInfo" + }, + "switchIp": { + "description": "网口交换机IP", + "type": "string", + "x-go-name": "SwitchIP" + }, + "switchIp1": { + "description": "交换机1ip", + "type": "string", + "x-go-name": "SwitchIP1" + }, + "switchIp2": { + "description": "交换机2ip", + "type": "string", + "x-go-name": "SwitchIP2" + }, + "switchPassword1": { + "description": "交换机1登录密码", + "type": "string", + "x-go-name": "SwitchPassword1" + }, + "switchPassword2": { + "description": "交换机2登录密码", + "type": "string", + "x-go-name": "SwitchPassword2" + }, + "switchPort1": { + "description": "交换机1port", + "type": "string", + "x-go-name": "SwitchPort1" + }, + "switchPort2": { + "description": "交换机2port", + "type": "string", + "x-go-name": "SwitchPort2" + }, + "switchUser1": { + "description": "交换机1登录账号,如果为空,取所在机房的值", + "type": "string", + "x-go-name": "SwitchUser1" + }, + "switchUser2": { + "description": "交换机2登录账号,如果为空,取所在机房的值", + "type": "string", + "x-go-name": "SwitchUser2" + }, + "systemVolumeAmount": { + "description": "系统盘数量", + "type": "integer", + "format": "int64", + "x-go-name": "SystemVolumeAmount" + }, + "systemVolumeInterfaceType": { + "description": "系统盘接口类型(SATA,SAS,NVME)", + "type": "string", + "x-go-name": "SystemVolumeInterfaceType" + }, + "systemVolumeSize": { + "description": "系统盘单盘大小", + "type": "integer", + "format": "int64", + "x-go-name": "SystemVolumeSize" + }, + "systemVolumeType": { + "description": "系统盘类型(SSD,HDD)", + "type": "string", + "x-go-name": "SystemVolumeType" + }, + "uPosition": { + "description": "U位", + "type": "string", + "x-go-name": "UPosition" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "userId": { + "description": "实例归属用户uuid", + "type": "string", + "x-go-name": "UserId" + }, + "userName": { + "description": "实例归属用户名称", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeviceInfo": { + "type": "object", + "properties": { + "device": { + "$ref": "#/definitions/Device" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeviceList": { + "type": "object", + "properties": { + "devices": { + "description": "设备列表", + "type": "array", + "items": { + "$ref": "#/definitions/Device" + }, + "x-go-name": "Devices" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeviceStock": { + "type": "object", + "properties": { + "stocks": { + "description": "库存量", + "type": "integer", + "format": "int64", + "x-go-name": "Stocks" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeviceType": { + "type": "object", + "properties": { + "architecture": { + "description": "体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64", + "type": "string", + "x-go-name": "Architecture" + }, + "boot_mode": { + "description": "boot模式", + "type": "string", + "x-go-name": "BootMode" + }, + "cpuAmount": { + "description": "cpu数量", + "type": "integer", + "format": "int64", + "x-go-name": "CPUAmount" + }, + "cpuCores": { + "description": "单个cpu内核数", + "type": "integer", + "format": "int64", + "x-go-name": "CPUCores" + }, + "cpuFrequency": { + "description": "cpu频率(G)", + "type": "string", + "x-go-name": "CPUFrequency" + }, + "cpuInfo": { + "description": "拼装信息", + "type": "string", + "x-go-name": "CpuInfo" + }, + "cpuManufacturer": { + "description": "cpu厂商", + "type": "string", + "x-go-name": "CPUManufacturer" + }, + "cpuModel": { + "description": "cpu处理器型号", + "type": "string", + "x-go-name": "CPUModel" + }, + "cpuSpec": { + "description": "CPU 规格,预置还是其它", + "type": "string", + "x-go-name": "CpuSpec" + }, + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description" + }, + "deviceCount": { + "type": "integer", + "format": "int64", + "x-go-name": "DeviceCount" + }, + "deviceSeries": { + "description": "机型类型,如计算型,存储型", + "type": "string", + "x-go-name": "DeviceSeries" + }, + "deviceSeriesName": { + "description": "机型类型,如计算型,存储型", + "type": "string", + "x-go-name": "DeviceSeriesName" + }, + "deviceType": { + "description": "机型规格, cps.c.normal", + "type": "string", + "x-go-name": "DeviceType" + }, + "deviceTypeId": { + "description": "机型uuid", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "dvInfo": { + "type": "string", + "x-go-name": "DvInfo" + }, + "gpuAmount": { + "description": "gpu数量", + "type": "integer", + "format": "int64", + "x-go-name": "GpuAmount" + }, + "gpuInfo": { + "type": "string", + "x-go-name": "GpuInfo" + }, + "gpuManufacturer": { + "description": "gpu厂商", + "type": "string", + "x-go-name": "GpuManufacturer" + }, + "gpuModel": { + "description": "gpu处理器型号", + "type": "string", + "x-go-name": "GpuModel" + }, + "height": { + "description": "显示机型高度", + "type": "integer", + "format": "int64", + "x-go-name": "Height" + }, + "id": { + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "idcId": { + "description": "机房uuid", + "type": "string", + "x-go-name": "IDcID" + }, + "idcName": { + "description": "机房名称", + "type": "string", + "x-go-name": "IDcName" + }, + "idcNameEn": { + "description": "机房名称", + "type": "string", + "x-go-name": "IDcNameEn" + }, + "instanceCount": { + "type": "integer", + "format": "int64", + "x-go-name": "InstanceCount" + }, + "instanceStatus": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceStatus" + }, + "interfaceMode": { + "description": "bond单网口,dual双网口", + "type": "string", + "x-go-name": "InterfaceMode" + }, + "isNeedRaid": { + "description": "是否配置了阵列卡", + "type": "string", + "x-go-name": "IsNeedRaid" + }, + "memAmount": { + "description": "内存数量", + "type": "integer", + "format": "int64", + "x-go-name": "MemAmount" + }, + "memFrequency": { + "description": "内存主频(MHz)", + "type": "integer", + "format": "int64", + "x-go-name": "MemFrequency" + }, + "memInfo": { + "type": "string", + "x-go-name": "MemInfo" + }, + "memSize": { + "description": "单个内存大小(GB)", + "type": "integer", + "format": "int64", + "x-go-name": "MemSize" + }, + "memSpec": { + "description": "内存 规格,预置还是其它", + "type": "string", + "x-go-name": "MemSpec" + }, + "memType": { + "description": "内存接口(如DDR3,DDR4)", + "type": "string", + "x-go-name": "MemType" + }, + "name": { + "description": "机型名称,如计算效能型,标准计算型", + "type": "string", + "x-go-name": "Name" + }, + "nicAmount": { + "description": "网卡数量", + "type": "integer", + "format": "int64", + "x-go-name": "NicAmount" + }, + "nicInfo": { + "type": "string", + "x-go-name": "NicInfo" + }, + "nicRate": { + "description": "网卡传输速率(GE)", + "type": "integer", + "format": "int64", + "x-go-name": "NicRate" + }, + "raid": { + "description": "系统盘raid", + "type": "string", + "x-go-name": "Raid" + }, + "raidCan": { + "description": "raid配置", + "type": "string", + "x-go-name": "RaidCan" + }, + "stockAvailable": { + "description": "StockAvailable 可用库存", + "type": "integer", + "format": "int64", + "x-go-name": "StockAvailable" + }, + "svInfo": { + "type": "string", + "x-go-name": "SvInfo" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "volumes": { + "description": "机型的卷信息", + "type": "array", + "items": { + "$ref": "#/definitions/Volume" + }, + "x-go-name": "Volumes" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeviceTypeInfo": { + "type": "object", + "properties": { + "deviceType": { + "$ref": "#/definitions/DeviceType" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeviceTypeList": { + "type": "object", + "properties": { + "deviceTypes": { + "description": "机型列表", + "type": "array", + "items": { + "$ref": "#/definitions/DeviceType" + }, + "x-go-name": "DeviceTypes" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DisableRuleRequest": { + "type": "object", + "required": [ + "ruleId" + ], + "properties": { + "ruleId": { + "description": "规则id", + "type": "string", + "x-go-name": "RuleId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "EditRuleRequest": { + "type": "object", + "required": [ + "ruleId", + "ruleName", + "dimension", + "resource", + "triggerOption", + "noticeOption", + "instanceIds" + ], + "properties": { + "deviceTag": { + "description": "盘符、挂载点、网口列表", + "type": "string", + "x-go-name": "DeviceTag" + }, + "dimension": { + "description": "维度 [instance、disk、mountpoint、nic]", + "type": "string", + "x-go-name": "Dimension" + }, + "instanceIds": { + "description": "实例id列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + }, + "noticeOption": { + "$ref": "#/definitions/RuleNotice" + }, + "resource": { + "description": "资源类型,目前只支持instance", + "type": "string", + "x-go-name": "Resource" + }, + "ruleId": { + "description": "规则id", + "type": "string", + "x-go-name": "RuleId" + }, + "ruleName": { + "description": "规则名称", + "type": "string", + "x-go-name": "RuleName" + }, + "triggerOption": { + "description": "触发条件", + "type": "array", + "items": { + "$ref": "#/definitions/RuleTrigger" + }, + "x-go-name": "TriggerOption" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "EnableRuleRequest": { + "type": "object", + "required": [ + "ruleId" + ], + "properties": { + "ruleId": { + "description": "规则id", + "type": "string", + "x-go-name": "RuleId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ErrorResponse": { + "type": "object", + "properties": { + "code": { + "description": "错误码", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "错误信息", + "type": "string", + "x-go-name": "Message" + }, + "status": { + "description": "错误状态", + "type": "string", + "x-go-name": "Status" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/controllers" + }, + "HasUnreadMessage": { + "type": "object", + "properties": { + "hasUnread": { + "type": "boolean", + "x-go-name": "HasUnread" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Idc": { + "type": "object", + "properties": { + "address": { + "description": "机房地址", + "type": "string", + "x-go-name": "Address" + }, + "createTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreateTime" + }, + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "id": { + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "idcId": { + "description": "机房uuid", + "type": "string", + "x-go-name": "IDcID" + }, + "iloPassword": { + "description": "机房公用带外管理password", + "type": "string", + "x-go-name": "IloPassword" + }, + "iloUser": { + "description": "机房公用带外管理user", + "type": "string", + "x-go-name": "IloUser" + }, + "level": { + "description": "机房等级", + "type": "string", + "x-go-name": "Level" + }, + "name": { + "description": "机房名称", + "type": "string", + "x-go-name": "Name" + }, + "nameEn": { + "description": "机房名称en", + "type": "string", + "x-go-name": "NameEn" + }, + "shortname": { + "description": "shortname", + "type": "string", + "x-go-name": "Shortname" + }, + "switchPassword1": { + "description": "交换机密码1", + "type": "string", + "x-go-name": "SwitchPassword1" + }, + "switchPassword2": { + "description": "交换机密码2", + "type": "string", + "x-go-name": "SwitchPassword2" + }, + "switchUser1": { + "description": "交换机用户名1", + "type": "string", + "x-go-name": "SwitchUser1" + }, + "switchUser2": { + "description": "交换机用户名2", + "type": "string", + "x-go-name": "SwitchUser2" + }, + "updateTime": { + "description": "修改时间", + "type": "string", + "x-go-name": "UpdateTime" + }, + "updatedBy": { + "description": "修改用户", + "type": "string", + "x-go-name": "UpdatedBy" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "IdcInfo": { + "type": "object", + "properties": { + "idc": { + "$ref": "#/definitions/Idc" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "IdcList": { + "type": "object", + "properties": { + "idcs": { + "description": "机房列表", + "type": "array", + "items": { + "$ref": "#/definitions/Idc" + }, + "x-go-name": "Idcs" + }, + "pageNumber": { + "description": "页数", + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "description": "页大小", + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "description": "总条数", + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Image": { + "type": "object", + "properties": { + "architecture": { + "description": "架构:x86/x64/i386/", + "type": "string", + "x-go-name": "Architecture" + }, + "bootMode": { + "description": "引导模式 【UEFI Legacy/BIOS】", + "type": "string", + "x-go-name": "BootMode" + }, + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "dataPartition": { + "description": "数据分区信息", + "type": "string", + "x-go-name": "DataPartition" + }, + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description" + }, + "deviceTypeNum": { + "description": "绑定了机型数量", + "type": "integer", + "format": "int64", + "x-go-name": "DeviceTypeNum" + }, + "filename": { + "description": "镜像文件名称", + "type": "string", + "x-go-name": "Filename" + }, + "format": { + "description": "镜像格式(qcow2、tar)", + "type": "string", + "x-go-name": "Format" + }, + "hash": { + "description": "镜像校验码", + "type": "string", + "x-go-name": "Hash" + }, + "id": { + "type": "integer", + "format": "uint64", + "x-go-name": "ID" + }, + "imageId": { + "description": "镜像uuid", + "type": "string", + "x-go-name": "ImageID" + }, + "imageName": { + "description": "镜像名称", + "type": "string", + "x-go-name": "ImageName" + }, + "isBind": { + "description": "是否绑定了某个机型", + "type": "boolean", + "x-go-name": "IsBind" + }, + "osId": { + "description": "源os uuid", + "type": "string", + "x-go-name": "OsID" + }, + "osName": { + "description": "CentOS 7.2 64-bit", + "type": "string", + "x-go-name": "OsName" + }, + "osType": { + "description": "操作系统分类:linux/windows", + "type": "string", + "x-go-name": "OsType" + }, + "osVersion": { + "description": "操作系统版本", + "type": "string", + "x-go-name": "OsVersion" + }, + "source": { + "description": "镜像来源(common通用、customize定制、user_defined自定义)", + "type": "string", + "x-go-name": "Source" + }, + "sourceName": { + "description": "镜像来源(common通用、customize定制、user_defined自定义)", + "type": "string", + "x-go-name": "SourceName" + }, + "systemPartition": { + "description": "系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap)", + "type": "string", + "x-go-name": "SystemPartition" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "url": { + "description": "镜像源路径", + "type": "string", + "x-go-name": "URL" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ImageInfo": { + "type": "object", + "properties": { + "image": { + "$ref": "#/definitions/Image" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ImageList": { + "type": "object", + "properties": { + "images": { + "description": "镜像实体列表", + "type": "array", + "items": { + "$ref": "#/definitions/Image" + }, + "x-go-name": "Images" + }, + "pageNumber": { + "description": "页数", + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "description": "页大小", + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "description": "总条数", + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Instance": { + "type": "object", + "properties": { + "bootMode": { + "description": "引导模式 [UEFI Legacy/BIOS]", + "type": "string", + "x-go-name": "BootMode" + }, + "cpuAmount": { + "description": "cpu数量", + "type": "integer", + "format": "int64", + "x-go-name": "CPUAmount" + }, + "cpuCores": { + "description": "单个cpu内核数", + "type": "integer", + "format": "int64", + "x-go-name": "CPUCores" + }, + "cpuFrequency": { + "description": "cpu频率(GHz)", + "type": "string", + "x-go-name": "CPUFrequency" + }, + "cpuManufacturer": { + "description": "cpu厂商", + "type": "string", + "x-go-name": "CPUManufacturer" + }, + "cpuModel": { + "description": "cpu处理器型号", + "type": "string", + "x-go-name": "CPUModel" + }, + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "description": { + "description": "实例描述", + "type": "string", + "x-go-name": "Description" + }, + "deviceId": { + "description": "设备uuid", + "type": "string", + "x-go-name": "DeviceID" + }, + "deviceSeries": { + "description": "机型类型,如computer", + "type": "string", + "x-go-name": "DeviceSeries" + }, + "deviceSeriesName": { + "description": "机型类型,如计算型,存储型", + "type": "string", + "x-go-name": "DeviceSeriesName" + }, + "deviceType": { + "description": "机型规格, cps.c.normal", + "type": "string", + "x-go-name": "DeviceType" + }, + "deviceTypeId": { + "description": "机型uuid", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "deviceTypeName": { + "description": "机型名称,如计算效能型,标准计算型", + "type": "string", + "x-go-name": "DeviceTypeName" + }, + "eth1Mask": { + "type": "string", + "x-go-name": "Eth1Mask" + }, + "gpuAmount": { + "description": "gpu数量", + "type": "integer", + "format": "int64", + "x-go-name": "GpuAmount" + }, + "gpuManufacturer": { + "description": "gpu厂商", + "type": "string", + "x-go-name": "GpuManufacturer" + }, + "gpuModel": { + "description": "gpu处理器型号", + "type": "string", + "x-go-name": "GpuModel" + }, + "hostname": { + "description": "主机名", + "type": "string", + "x-go-name": "Hostname" + }, + "idcId": { + "description": "机房uuid", + "type": "string", + "x-go-name": "IDcID" + }, + "idcName": { + "description": "机房名称", + "type": "string", + "x-go-name": "IdcName" + }, + "iloIp": { + "description": "带外管理IP", + "type": "string", + "x-go-name": "IloIP" + }, + "imageId": { + "description": "镜像uuid", + "type": "string", + "x-go-name": "ImageID" + }, + "imageName": { + "description": "镜像名称", + "type": "string", + "x-go-name": "ImageName" + }, + "instanceId": { + "description": "实例uuid", + "type": "string", + "x-go-name": "InstanceID" + }, + "instanceName": { + "description": "实例名称", + "type": "string", + "x-go-name": "InstanceName" + }, + "interfaceMode": { + "description": "【网口模式】【网络设置】: bond单网口,dual双网口", + "type": "string", + "x-go-name": "InterfaceMode" + }, + "isNeedRaid": { + "description": "所属的机型是否需要配置raid,页面有用", + "type": "string", + "x-go-name": "IsNeedRaid" + }, + "locked": { + "description": "是否锁定解锁锁定:locked,解锁unlocked", + "type": "string", + "x-go-name": "Locked" + }, + "lockedName": { + "description": "是否锁定解锁锁定:已解锁,已锁定", + "type": "string", + "x-go-name": "LockedName" + }, + "mask": { + "type": "string", + "x-go-name": "Mask" + }, + "memAmount": { + "description": "内存数量", + "type": "integer", + "format": "int64", + "x-go-name": "MemAmount" + }, + "memFrequency": { + "description": "内存主频(MHz)", + "type": "integer", + "format": "int64", + "x-go-name": "MemFrequency" + }, + "memSize": { + "description": "单个内存大小(GB)", + "type": "integer", + "format": "int64", + "x-go-name": "MemSize" + }, + "memType": { + "description": "内存接口(如DDR3,DDR4)", + "type": "string", + "x-go-name": "MemType" + }, + "nicAmount": { + "description": "网卡数量", + "type": "integer", + "format": "int64", + "x-go-name": "NicAmount" + }, + "nicRate": { + "description": "网卡传输速率(GE)", + "type": "integer", + "format": "int64", + "x-go-name": "NicRate" + }, + "privateEth1Ipv4": { + "description": "eth1内网IPV4", + "type": "string", + "x-go-name": "PrivateEth1IPv4" + }, + "privateEth1Ipv6": { + "description": "eth1内网IPV6", + "type": "string", + "x-go-name": "PrivateEth1IPv6" + }, + "privateIpv4": { + "description": "内网IPV4", + "type": "string", + "x-go-name": "PrivateIPv4" + }, + "privateIpv6": { + "description": "内网IPV6", + "type": "string", + "x-go-name": "PrivateIPv6" + }, + "projectId": { + "description": "实例所属项目UUID", + "type": "string", + "x-go-name": "ProjectID" + }, + "reason": { + "description": "实例错误状态时的错误原因", + "type": "string", + "x-go-name": "Reason" + }, + "sn": { + "description": "设备SN", + "type": "string", + "x-go-name": "Sn" + }, + "status": { + "description": "运行状态", + "type": "string", + "x-go-name": "Status" + }, + "statusName": { + "description": "运行状态中文名字", + "type": "string", + "x-go-name": "StatusName" + }, + "systemVolumeRaidId": { + "description": "系统盘raidId", + "type": "string", + "x-go-name": "SystemVolumeRaidID" + }, + "systemVolumeRaidName": { + "description": "系统盘raid名称", + "type": "string", + "x-go-name": "SystemVolumeRaidName" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "userId": { + "description": "实例所属用户UUID", + "type": "string", + "x-go-name": "UserID" + }, + "volumeRaid": { + "description": "实例的volume和raid信息", + "type": "array", + "items": { + "$ref": "#/definitions/InstanceVolumeRaid" + }, + "x-go-name": "InstanceVolumeRaids" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "InstanceForShare": { + "type": "object", + "properties": { + "hasShared": { + "description": "新增,是否已经被共享过", + "type": "boolean", + "x-go-name": "HasShared" + }, + "instanceId": { + "description": "实例uuid", + "type": "string", + "x-go-name": "InstanceID" + }, + "instanceName": { + "description": "实例名称", + "type": "string", + "x-go-name": "InstanceName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "InstanceForShareList": { + "type": "object", + "properties": { + "instances": { + "description": "instance实体数组", + "type": "array", + "items": { + "$ref": "#/definitions/InstanceForShare" + }, + "x-go-name": "Instances" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "InstanceIds": { + "type": "object", + "properties": { + "instanceIds": { + "description": "instanceId 列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "InstanceInfo": { + "type": "object", + "properties": { + "instance": { + "$ref": "#/definitions/Instance" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "InstanceList": { + "type": "object", + "properties": { + "instances": { + "description": "instance实体数组", + "type": "array", + "items": { + "$ref": "#/definitions/Instance" + }, + "x-go-name": "Instances" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "InstanceVolumeRaid": { + "type": "object", + "properties": { + "raid": { + "$ref": "#/definitions/Raid" + }, + "volume": { + "$ref": "#/definitions/Volume" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "InstancesSshkeyInfoResponse": { + "type": "object", + "properties": { + "instanceIds": { + "description": "实例Id列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "LicenseContent": { + "type": "object", + "properties": { + "end_time": { + "type": "integer", + "format": "int64", + "x-go-name": "EndTime" + }, + "hardwareinfo": { + "type": "string", + "x-go-name": "HardWare" + }, + "license_name": { + "type": "string", + "x-go-name": "LicenseName" + }, + "license_type": { + "type": "string", + "x-go-name": "LicenseType" + }, + "models": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "Models" + }, + "nodes_num": { + "type": "integer", + "format": "int64", + "x-go-name": "NodesNum" + }, + "start_time": { + "type": "integer", + "format": "int64", + "x-go-name": "StartTime" + }, + "used_nodes_num": { + "type": "integer", + "format": "int64", + "x-go-name": "UsedNodesNum" + }, + "version": { + "type": "string", + "x-go-name": "Version" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Message": { + "type": "object", + "properties": { + "alert_count": { + "description": "告警次数,始终为1,带外故障消息专属字段", + "type": "integer", + "format": "int64", + "x-go-name": "AlertCount" + }, + "alert_time": { + "description": "故障告警时间,带外故障消息专属字段", + "type": "integer", + "format": "int64", + "x-go-name": "AlertTime" + }, + "content": { + "description": "故障内容,带外故障消息专属字段", + "type": "string", + "x-go-name": "Content" + }, + "detail": { + "description": "详情, 带外监控日志的详情请用content", + "type": "string", + "x-go-name": "Detail" + }, + "device_id": { + "type": "string", + "x-go-name": "DeviceID" + }, + "fault_type": { + "description": "故障类型, 带外故障消息专属字段", + "type": "string", + "x-go-name": "FaultType" + }, + "finish_time": { + "description": "消息时间戳", + "type": "integer", + "format": "int64", + "x-go-name": "FinishTime" + }, + "has_read": { + "description": "0未读, 1已读", + "type": "integer", + "format": "int8", + "x-go-name": "HasRead" + }, + "idc_id": { + "description": "独一处的下划线,跟sdk一致", + "type": "string", + "x-go-name": "IDcID" + }, + "idc_name": { + "type": "string", + "x-go-name": "IDcName" + }, + "instance_id": { + "description": "实例id", + "type": "string", + "x-go-name": "InstanceID" + }, + "instance_name": { + "description": "实例name", + "type": "string", + "x-go-name": "InstanceName" + }, + "is_del": { + "description": "是否删除0未删除 1已删除", + "type": "integer", + "format": "int8", + "x-go-name": "IsDel" + }, + "is_recover": { + "type": "integer", + "format": "int8", + "x-go-name": "IsRecover" + }, + "license_end_time": { + "description": "结束时间, 许可证到期消息专属字段", + "type": "integer", + "format": "int64", + "x-go-name": "LienseEndTime" + }, + "license_name": { + "description": "版本名称, 许可证到期消息专属字段", + "type": "string", + "x-go-name": "LicenseName" + }, + "license_number": { + "description": "版本号, 许可证到期消息专属字段", + "type": "string", + "x-go-name": "LicenseNumber" + }, + "license_start_time": { + "description": "开始时间, 许可证到期消息专属字段", + "type": "integer", + "format": "int64", + "x-go-name": "LienseStartTime" + }, + "logid": { + "description": "系统原始日志id, 带外故障消息专属字段", + "type": "string", + "x-go-name": "LogID" + }, + "message_id": { + "description": "message uuid", + "type": "string", + "x-go-name": "MessageID" + }, + "message_sub_type": { + "description": "消息子类型", + "type": "string", + "x-go-name": "MessageSubType" + }, + "message_type": { + "description": "消息类型", + "type": "string", + "x-go-name": "MessageType" + }, + "project_id": { + "type": "string", + "x-go-name": "ProjectID" + }, + "project_name": { + "type": "string", + "x-go-name": "ProjectName" + }, + "resource_type": { + "description": "资源类型 实例/设备", + "type": "string", + "x-go-name": "ResourceType" + }, + "result": { + "description": "操作结果 fail/succ", + "type": "string", + "x-go-name": "Result" + }, + "rule_id": { + "description": "inbond rule uuid", + "type": "string", + "x-go-name": "RuleID" + }, + "rule_name": { + "description": "inbond rule name", + "type": "string", + "x-go-name": "RuleName" + }, + "sn": { + "description": "设备sn", + "type": "string", + "x-go-name": "SN" + }, + "user_id": { + "description": "user_id", + "type": "string", + "x-go-name": "UserID" + }, + "user_name": { + "description": "user_name", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "MessageList": { + "type": "object", + "properties": { + "messages": { + "type": "array", + "items": { + "$ref": "#/definitions/Message" + }, + "x-go-name": "Messages" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "MessageStatistic": { + "type": "object", + "properties": { + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + }, + "unreadCount": { + "type": "integer", + "format": "int64", + "x-go-name": "UnreadCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "MessageTypesResp": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "MessageWithNextPrev": { + "type": "object", + "properties": { + "message": { + "$ref": "#/definitions/Message" + }, + "nextMessageId": { + "type": "string", + "x-go-name": "NextMessageId" + }, + "prevMessageId": { + "type": "string", + "x-go-name": "PrevMessageId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ModifyApikeyRequest": { + "type": "object", + "required": [ + "name", + "readOnly" + ], + "properties": { + "name": { + "description": "秘钥对名称", + "type": "string", + "x-go-name": "Name" + }, + "readOnly": { + "description": "是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法", + "type": "integer", + "format": "int8", + "x-go-name": "ReadOnly" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyInstanceRequest": { + "type": "object", + "properties": { + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description", + "x-nullable": true + }, + "instanceName": { + "description": "实例名称", + "type": "string", + "x-go-name": "InstanceName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyInstancesRequest": { + "description": "批量修改实例名称", + "type": "object", + "properties": { + "instanceName": { + "description": "实例名称", + "type": "string", + "x-go-name": "InstanceName" + }, + "instance_ids": { + "description": "实例id列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIDs" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyLocalUserRequest": { + "type": "object", + "properties": { + "defaultProjectId": { + "description": "用户默认项目uuid", + "type": "string", + "x-go-name": "DefaultProjectID", + "x-nullable": true + }, + "email": { + "description": "邮箱", + "type": "string", + "x-go-name": "Email", + "x-nullable": true + }, + "language": { + "description": "语言[en_US, zh_CN]", + "type": "string", + "x-go-name": "Language", + "x-nullable": true + }, + "phoneNumber": { + "description": "手机号", + "type": "string", + "x-go-name": "PhoneNumber", + "x-nullable": true + }, + "phonePrefix": { + "description": "国家地区码,如86", + "type": "string", + "x-go-name": "PhonePrefix", + "x-nullable": true + }, + "timezone": { + "description": "时区 Asia/Shanghai", + "type": "string", + "x-go-name": "Timezone", + "x-nullable": true + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyProjectDescriptionRequest": { + "type": "object", + "required": [ + "description" + ], + "properties": { + "description": { + "description": "项目描述", + "type": "string", + "x-go-name": "Description" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyProjectRequest": { + "type": "object", + "required": [ + "projectName" + ], + "properties": { + "projectName": { + "description": "项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-”", + "type": "string", + "x-go-name": "ProjectName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifySshkeyRequest": { + "type": "object", + "properties": { + "name": { + "description": "秘钥名称", + "type": "string", + "x-go-name": "Name", + "x-nullable": true + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyUserPasswordRequest": { + "type": "object", + "required": [ + "oldPassword", + "password" + ], + "properties": { + "oldPassword": { + "description": "旧密码,明文", + "type": "string", + "x-go-name": "OldPassword" + }, + "password": { + "description": "新密码 明文,密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30}", + "type": "string", + "x-go-name": "Password" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyUserRequest": { + "type": "object", + "properties": { + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description", + "x-nullable": true + }, + "email": { + "description": "邮箱", + "type": "string", + "x-go-name": "Email", + "x-nullable": true + }, + "phoneNumber": { + "description": "手机号", + "type": "string", + "x-go-name": "PhoneNumber", + "x-nullable": true + }, + "phonePrefix": { + "description": "国家地区码,如86", + "type": "string", + "x-go-name": "PhonePrefix", + "x-nullable": true + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "MonitorDataItem": { + "type": "object", + "properties": { + "timestamp": { + "type": "integer", + "format": "int64", + "x-go-name": "Timestamp" + }, + "value": { + "type": "string", + "x-go-name": "Value" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "MonitorDataQuery": { + "type": "object", + "properties": { + "endTime": { + "type": "integer", + "format": "int64", + "x-go-name": "EndTime" + }, + "func": { + "description": "跟赛迪约定,转换单位放这里实现", + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int64" + }, + "x-go-name": "Func" + }, + "labels": { + "description": "metric都放这里了", + "type": "object", + "additionalProperties": { + "type": "string" + }, + "x-go-name": "Labels" + }, + "sampleMethod": { + "description": "MetricName string `json:\"metricName\"`\n[rate, increase]", + "type": "string", + "x-go-name": "SampleMethod" + }, + "startTime": { + "type": "integer", + "format": "int64", + "x-go-name": "StartTime" + }, + "step": { + "type": "integer", + "format": "int64", + "x-go-name": "Step" + }, + "tableName": { + "description": "[bmp_monitor_counter bmp_monitor_gauge]", + "type": "string", + "x-go-name": "TableName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "MoveInstancesRequest": { + "type": "object", + "required": [ + "instanceIDs", + "ownerProjectID", + "moverProjectID", + "ownerID", + "moverID" + ], + "properties": { + "instanceIDs": { + "description": "instanceIDs", + "type": "string", + "x-go-name": "InstanceIDs" + }, + "moverID": { + "description": "to user_id", + "type": "string", + "x-go-name": "MoverID" + }, + "moverProjectID": { + "description": "to project_id", + "type": "string", + "x-go-name": "MoverProjectID" + }, + "ownerID": { + "description": "from user_id", + "type": "string", + "x-go-name": "OwnerID" + }, + "ownerProjectID": { + "description": "from project_id", + "type": "string", + "x-go-name": "OwnerProjectID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "MoveProjectRequest": { + "type": "object", + "required": [ + "ownerID", + "moverID" + ], + "properties": { + "moverID": { + "description": "to user_id", + "type": "string", + "x-go-name": "MoverID" + }, + "ownerID": { + "description": "from user_id", + "type": "string", + "x-go-name": "OwnerID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "Os": { + "type": "object", + "properties": { + "architecture": { + "description": "架构:x86/x64/i386/", + "type": "string", + "x-go-name": "Architecture" + }, + "bits": { + "description": "指令宽度:64/32位", + "type": "integer", + "format": "int64", + "x-go-name": "Bits" + }, + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "deletedTime": { + "description": "删除时间", + "type": "string", + "x-go-name": "DeletedTime" + }, + "id": { + "description": "ID", + "type": "integer", + "format": "uint64", + "x-go-name": "ID" + }, + "isDel": { + "description": "是否删除0未删除 1已删除", + "type": "integer", + "format": "int8", + "x-go-name": "IsDel" + }, + "osId": { + "description": "操作系统uuid", + "type": "string", + "x-go-name": "OsID" + }, + "osName": { + "description": "操作系统名称", + "type": "string", + "x-go-name": "OsName" + }, + "osType": { + "description": "操作系统分类:linux/windows", + "type": "string", + "x-go-name": "OsType" + }, + "osVersion": { + "description": "操作系统版本", + "type": "string", + "x-go-name": "OsVersion" + }, + "sysUser": { + "description": "管理员账户", + "type": "string", + "x-go-name": "SysUser" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "OsInfo": { + "type": "object", + "properties": { + "os": { + "$ref": "#/definitions/Os" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "OsList": { + "type": "object", + "properties": { + "oss": { + "description": "操作系统列表", + "type": "array", + "items": { + "$ref": "#/definitions/Os" + }, + "x-go-name": "Oss" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Partition": { + "description": "镜像默认分区\n[{\"format\":\"swap\",\"point\":\"swap\",\"size\":10240},{\"format\":\"xfs\",\"point\":\"/\",\"size\":51200}]", + "type": "object", + "properties": { + "format": { + "description": "format,如[swap, xfs]", + "type": "string", + "x-go-name": "FsType" + }, + "point": { + "description": "point,如[swap, /, /var]", + "type": "string", + "x-go-name": "MountPoint" + }, + "size": { + "description": "分区大小, MB为单位", + "type": "integer", + "format": "int64", + "x-go-name": "Size" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Project": { + "type": "object", + "properties": { + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "description": { + "description": "项目描述,新增", + "type": "string", + "x-go-name": "Description" + }, + "instanceCount": { + "description": "项目下实例数量", + "type": "integer", + "format": "int64", + "x-go-name": "InstanceCount" + }, + "owned": { + "description": "此项目的共享标志位,1为拥有,2为共享", + "type": "integer", + "format": "int64", + "x-go-name": "Owned" + }, + "ownedBy": { + "description": "拥有者", + "type": "string", + "x-go-name": "OwnedBy" + }, + "projectId": { + "description": "项目uuid", + "type": "string", + "x-go-name": "ProjectID" + }, + "projectName": { + "description": "项目名称", + "type": "string", + "x-go-name": "ProjectName" + }, + "shareProjects": { + "description": "共享", + "type": "array", + "items": { + "$ref": "#/definitions/ShareProject" + }, + "x-go-name": "ShareProjects" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ProjectId": { + "type": "object", + "properties": { + "projectId": { + "description": "项目uuid", + "type": "string", + "x-go-name": "ProjectId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ProjectInfo": { + "type": "object", + "properties": { + "project": { + "$ref": "#/definitions/Project" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ProjectList": { + "type": "object", + "properties": { + "pageNumber": { + "description": "页数", + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "description": "页大小", + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "projects": { + "description": "项目实体列表", + "type": "array", + "items": { + "$ref": "#/definitions/Project" + }, + "x-go-name": "Projects" + }, + "totalCount": { + "description": "总条数", + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "QueryDeviceTypeImagePartitionResponse": { + "type": "object", + "properties": { + "dataPartition": { + "description": "数据盘分区列表", + "type": "array", + "items": { + "$ref": "#/definitions/Partition" + }, + "x-go-name": "DataPartition" + }, + "systemPartition": { + "description": "系统盘分区列表", + "type": "array", + "items": { + "$ref": "#/definitions/Partition" + }, + "x-go-name": "SystemPartition" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "RVolumeRaid": { + "description": "Volume RAID 关联关系表", + "type": "object", + "properties": { + "createdBy": { + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "type": "integer", + "format": "int64", + "x-go-name": "CreatedTime" + }, + "deletedTime": { + "type": "integer", + "format": "int64", + "x-go-name": "DeletedTime" + }, + "deviceTypeId": { + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "isDel": { + "type": "integer", + "format": "int8", + "x-go-name": "IsDel" + }, + "raidCan": { + "type": "string", + "x-go-name": "RaidCan" + }, + "raidId": { + "type": "string", + "x-go-name": "RaidID" + }, + "raidName": { + "type": "string", + "x-go-name": "RaidName" + }, + "updatedBy": { + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "type": "integer", + "format": "int64", + "x-go-name": "UpdatedTime" + }, + "volumeId": { + "type": "string", + "x-go-name": "VolumeID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/dao/rVolumeRaidDao" + }, + "Raid": { + "description": "Raid raid", + "type": "object", + "properties": { + "createdBy": { + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "type": "integer", + "format": "int64", + "x-go-name": "CreatedTime" + }, + "deletedTime": { + "type": "integer", + "format": "int64", + "x-go-name": "DeletedTime" + }, + "descriptionEn": { + "type": "string", + "x-go-name": "DescriptionEn" + }, + "descriptionZh": { + "type": "string", + "x-go-name": "DescriptionZh" + }, + "isDel": { + "type": "integer", + "format": "int8", + "x-go-name": "IsDel" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "raidId": { + "type": "string", + "x-go-name": "RaidID" + }, + "updatedBy": { + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "type": "integer", + "format": "int64", + "x-go-name": "UpdatedTime" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/dao/raidDao" + }, + "ReadMessagesRequest": { + "type": "object", + "required": [ + "messageIds" + ], + "properties": { + "messageIds": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "MessageIds" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ReinstallInstanceRequest": { + "type": "object", + "required": [ + "imageId", + "systemVolumeRaidId", + "instanceName", + "bootMode" + ], + "properties": { + "bootMode": { + "description": "引导模式 [UEFI Legacy/BIOS]", + "type": "string", + "x-go-name": "BootMode" + }, + "dataPartition": { + "description": "数据盘分区", + "type": "array", + "items": { + "$ref": "#/definitions/Partition" + }, + "x-go-name": "DataPartition" + }, + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description" + }, + "hostname": { + "description": "主机名称", + "type": "string", + "x-go-name": "HostName" + }, + "imageId": { + "description": "镜像ID", + "type": "string", + "x-go-name": "ImageID" + }, + "installBmpAgent": { + "description": "是否安装bmp-agent", + "type": "boolean", + "x-go-name": "InstallBmpAgent" + }, + "instanceName": { + "description": "实例名称", + "type": "string", + "x-go-name": "InstanceName" + }, + "password": { + "description": "密码", + "type": "string", + "x-go-name": "Password" + }, + "sshKeyId": { + "description": "秘钥ID", + "type": "string", + "x-go-name": "SshKeyID" + }, + "systemPartition": { + "description": "系统盘分区", + "type": "array", + "items": { + "$ref": "#/definitions/Partition" + }, + "x-go-name": "SystemPartition" + }, + "systemVolumeRaidId": { + "description": "系统盘RAID ID", + "type": "string", + "x-go-name": "SystemVolumeRaidID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ResetInstancePasswdRequest": { + "description": "重置实例密码", + "type": "object", + "properties": { + "password": { + "description": "新密码", + "type": "string", + "x-go-name": "Password" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ResetInstancesPasswdRequest": { + "description": "批量重置实例密码", + "type": "object", + "properties": { + "instance_ids": { + "description": "实例id列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIDs" + }, + "password": { + "description": "新密码", + "type": "string", + "x-go-name": "Password" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "RestartInstancesRequest": { + "type": "object", + "properties": { + "instanceIds": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "Role": { + "type": "object", + "properties": { + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "descriptionCn": { + "description": "description", + "type": "string", + "x-go-name": "DescriptionCn" + }, + "descriptionEn": { + "description": "权限描述", + "type": "string", + "x-go-name": "DescriptionEn" + }, + "permission": { + "description": "权限", + "type": "string", + "x-go-name": "Permission" + }, + "roleId": { + "description": "角色uuid", + "type": "string", + "x-go-name": "RoleID" + }, + "roleName": { + "description": "角色名称", + "type": "string", + "x-go-name": "RoleName" + }, + "roleNameCn": { + "description": "角色名称,唯一", + "type": "string", + "x-go-name": "RoleNameCn" + }, + "roleNameEn": { + "description": "角色名称,唯一", + "type": "string", + "x-go-name": "RoleNameEn" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "userCount": { + "description": "用户数", + "type": "integer", + "format": "int64", + "x-go-name": "UserCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "RoleInfo": { + "type": "object", + "properties": { + "role": { + "$ref": "#/definitions/Role" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "RoleList": { + "type": "object", + "properties": { + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "roles": { + "description": "角色实体列表", + "type": "array", + "items": { + "$ref": "#/definitions/Role" + }, + "x-go-name": "Roles" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Rule": { + "type": "object", + "properties": { + "deviceTag": { + "description": "盘符、挂载点、网口列表", + "type": "string", + "x-go-name": "DeviceTag" + }, + "dimension": { + "description": "维度 [instance、disk、mountpoint、nic]", + "type": "string", + "x-go-name": "Dimension" + }, + "dimensionName": { + "description": "维度名称 [实例、盘符、挂载点、网卡]", + "type": "string", + "x-go-name": "DimensionName" + }, + "instanceCount": { + "description": "关联的实例个数", + "type": "integer", + "format": "int64", + "x-go-name": "InstanceCount" + }, + "instanceIds": { + "description": "实例id列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + }, + "instances": { + "description": "实例详细信息", + "type": "array", + "items": { + "$ref": "#/definitions/Instance" + }, + "x-go-name": "Instances" + }, + "noticeOption": { + "$ref": "#/definitions/RuleNotice" + }, + "relatedResourceCount": { + "description": "此规则关联的资源数", + "type": "integer", + "format": "int64", + "x-go-name": "RelatedResourceCount" + }, + "resource": { + "description": "资源类型,目前只支持instance", + "type": "string", + "x-go-name": "Resource" + }, + "resourceName": { + "description": "资源类型名称 实例", + "type": "string", + "x-go-name": "ResourceName" + }, + "ruleId": { + "description": "规则uuid", + "type": "string", + "x-go-name": "RuleID" + }, + "ruleName": { + "description": "规则名称", + "type": "string", + "x-go-name": "RuleName" + }, + "status": { + "description": "状态 [1启用 2不启用 3告警]", + "type": "integer", + "format": "int64", + "x-go-name": "Status" + }, + "statusName": { + "description": "规则状态名称", + "type": "string", + "x-go-name": "StatusName" + }, + "triggerDescription": { + "description": "触发条件描述", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "TriggerDescription" + }, + "triggerOption": { + "description": "触发条件", + "type": "array", + "items": { + "$ref": "#/definitions/RuleTrigger" + }, + "x-go-name": "TriggerOption" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "RuleList": { + "type": "object", + "properties": { + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "rules": { + "description": "rules数组", + "type": "array", + "items": { + "$ref": "#/definitions/Rule" + }, + "x-go-name": "Rules" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "RuleNotice": { + "description": "通知策略", + "type": "object", + "required": [ + "noticePeriod", + "effectiveIntervalStart", + "effectiveIntervalEnd", + "noticeCondition", + "noticeWay", + "userId" + ], + "properties": { + "effectiveIntervalEnd": { + "description": "有效时段结束时间 [\"23:59:59\"]", + "type": "string", + "x-go-name": "EffectiveIntervalEnd" + }, + "effectiveIntervalStart": { + "description": "有效时段开始时间 [\"00:00:00\"]", + "type": "string", + "x-go-name": "EffectiveIntervalStart" + }, + "noticeCondition": { + "description": "通知条件,可多选 [1表示报警, 2表示恢复正常]", + "type": "array", + "items": { + "type": "integer", + "format": "int64" + }, + "x-go-name": "NoticeCondition" + }, + "noticePeriod": { + "description": "通知周期(分钟) [5 10 15 30 60 180 360 720 1440]", + "type": "integer", + "format": "int64", + "x-go-name": "NoticePeriod" + }, + "noticeWay": { + "description": "接收渠道,可多选 [1表示站内信, 2表示邮件]", + "type": "array", + "items": { + "type": "integer", + "format": "int64" + }, + "x-go-name": "NoticeWay" + }, + "userId": { + "description": "通知对象用户Id", + "type": "string", + "x-go-name": "UserID" + }, + "userName": { + "description": "通知对象用户", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "RuleTrigger": { + "description": "单个触发条件", + "type": "object", + "required": [ + "metric", + "period", + "calculation", + "operation", + "threshold", + "times", + "noticeLevel" + ], + "properties": { + "calculation": { + "description": "计算方式 [min max avg sum]", + "type": "string", + "x-go-name": "Calculation" + }, + "calculationUnit": { + "description": "计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出]", + "type": "string", + "x-go-name": "CalculationUnit" + }, + "description": { + "description": "对此rule的描述", + "type": "string", + "x-go-name": "Description" + }, + "metric": { + "description": "监控指标 cps.cpu.util", + "type": "string", + "x-go-name": "Metric" + }, + "metricName": { + "description": "监控指标名称 CPU使用率", + "type": "string", + "x-go-name": "MetricName" + }, + "noticeLevel": { + "description": "告警级别 [1表示一般,2表示严重,3表示紧急]", + "type": "integer", + "format": "int64", + "x-go-name": "NoticeLevel" + }, + "operation": { + "description": "比较方式 [\u003e \u003e= \u003c \u003c= == !=]或者[gt gte lt lte eq neq]", + "type": "string", + "x-go-name": "Operation" + }, + "period": { + "description": "周期 5(分钟)", + "type": "integer", + "format": "int64", + "x-go-name": "Period" + }, + "tableName": { + "description": "[bmp_monitor_counter, bmp_monitor_gauge]", + "type": "string", + "x-go-name": "TableName" + }, + "threshold": { + "description": "阈值", + "type": "number", + "format": "double", + "x-go-name": "Threshold" + }, + "times": { + "description": "持续周期数 [1, 2, 3, 5, 10, 15, 30, 60]", + "type": "integer", + "format": "int64", + "x-go-name": "Times" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ShareProject": { + "type": "object", + "properties": { + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "ownerUserId": { + "description": "项目拥有者用户id", + "type": "string", + "x-go-name": "OwnerUserID" + }, + "ownerUserName": { + "description": "项目拥有者用户名", + "type": "string", + "x-go-name": "OwnerUserName" + }, + "projectId": { + "description": "项目uuid", + "type": "string", + "x-go-name": "ProjectID" + }, + "projectName": { + "description": "项目名称", + "type": "string", + "x-go-name": "ProjectName" + }, + "sharedInstanceIds": { + "type": "string", + "x-go-name": "SharedInstanceIDs" + }, + "sharedUserId": { + "description": "项目共享者用户id", + "type": "string", + "x-go-name": "SharedUserID" + }, + "sharedUserName": { + "description": "项目拥有者用户名", + "type": "string", + "x-go-name": "SharedUserName" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ShareProjectInfo": { + "type": "object", + "properties": { + "projectId": { + "description": "项目实体", + "type": "string", + "x-go-name": "ProjectID" + }, + "shares": { + "type": "array", + "items": { + "$ref": "#/definitions/SharingProject" + }, + "x-go-name": "Shares" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ShareProjectRequest": { + "type": "object", + "required": [ + "ownerID", + "sharerID", + "instanceIDs" + ], + "properties": { + "instanceIDs": { + "description": "如果部分分享,instance_id逗号分隔; 如果全部分享,传all", + "type": "string", + "x-go-name": "InstanceIDs" + }, + "ownerID": { + "description": "from user_id", + "type": "string", + "x-go-name": "OwnerID" + }, + "sharerID": { + "description": "to user_id", + "type": "string", + "x-go-name": "SharerID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "SharingProject": { + "description": "SharingProject 共享项目", + "type": "object", + "properties": { + "created_by": { + "type": "string", + "x-go-name": "CreatedBy" + }, + "created_time": { + "type": "integer", + "format": "int64", + "x-go-name": "CreatedTime" + }, + "deleted_time": { + "type": "integer", + "format": "int64", + "x-go-name": "DeletedTime" + }, + "is_default": { + "type": "integer", + "format": "int8", + "x-go-name": "IsDefault" + }, + "is_del": { + "type": "integer", + "format": "int8", + "x-go-name": "IsDel" + }, + "owner_user_id": { + "type": "string", + "x-go-name": "OwnerUserID" + }, + "owner_user_name": { + "type": "string", + "x-go-name": "OwnerUserName" + }, + "premission": { + "type": "string", + "x-go-name": "Premission" + }, + "project_id": { + "type": "string", + "x-go-name": "ProjectID" + }, + "project_name": { + "type": "string", + "x-go-name": "ProjectName" + }, + "shared_instance_ids": { + "type": "string", + "x-go-name": "SharedInstanceIDs" + }, + "shared_user_id": { + "type": "string", + "x-go-name": "SharedUserID" + }, + "shared_user_name": { + "type": "string", + "x-go-name": "SharedUserName" + }, + "updated_by": { + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updated_time": { + "type": "integer", + "format": "int64", + "x-go-name": "UpdatedTime" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/dao/sharingProjectDao" + }, + "Sshkey": { + "type": "object", + "properties": { + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "fingerPrint": { + "description": "公钥指纹", + "type": "string", + "x-go-name": "FingerPrint" + }, + "id": { + "description": "id", + "type": "integer", + "format": "int64", + "x-go-name": "Id" + }, + "key": { + "description": "公钥,格式:ssh-rsa AAA", + "type": "string", + "x-go-name": "Key" + }, + "name": { + "description": "秘钥名称", + "type": "string", + "x-go-name": "Name" + }, + "sshkeyId": { + "description": "秘钥uuid", + "type": "string", + "x-go-name": "SshkeyId" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "userId": { + "description": "所属用户uuid", + "type": "string", + "x-go-name": "UserId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "SshkeyId": { + "type": "object", + "properties": { + "sshkeyId": { + "description": "sshkey uuid", + "type": "string", + "x-go-name": "SshkeyId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "SshkeyInfo": { + "type": "object", + "properties": { + "sshkey": { + "$ref": "#/definitions/Sshkey" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "SshkeyList": { + "type": "object", + "properties": { + "pageNumber": { + "description": "页数", + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "description": "页大小", + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "sshkeys": { + "description": "sshkey实体列表", + "type": "array", + "items": { + "$ref": "#/definitions/Sshkey" + }, + "x-go-name": "Sshkeys" + }, + "totalCount": { + "description": "总条数", + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "StartInstancesRequest": { + "type": "object", + "properties": { + "instanceIds": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "StopInstancesRequest": { + "type": "object", + "properties": { + "instanceIds": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "TagsResponse": { + "type": "object", + "properties": { + "tags": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "Tags" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "User": { + "type": "object", + "properties": { + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "defaultProjectId": { + "description": "用户默认项目uuid", + "type": "string", + "x-go-name": "DefaultProjectID" + }, + "defaultProjectName": { + "description": "用户默认项目名称", + "type": "string", + "x-go-name": "DefaultProjectName" + }, + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description" + }, + "email": { + "description": "邮箱", + "type": "string", + "x-go-name": "Email" + }, + "id": { + "description": "用户id", + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "language": { + "description": "默认语言(en_US/zh_CN)", + "type": "string", + "x-go-name": "Language" + }, + "phoneNumber": { + "description": "手机号", + "type": "string", + "x-go-name": "PhoneNumber" + }, + "phonePrefix": { + "description": "国家地区码,如86", + "type": "string", + "x-go-name": "PhonePrefix" + }, + "roleId": { + "description": "角色uuid", + "type": "string", + "x-go-name": "RoleID" + }, + "roleName": { + "description": "角色名称", + "type": "string", + "x-go-name": "RoleName" + }, + "timezone": { + "description": "时区", + "type": "string", + "x-go-name": "Timezone" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "userId": { + "description": "用户uuid", + "type": "string", + "x-go-name": "UserID" + }, + "userName": { + "description": "用户名,唯一", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "UserInfo": { + "type": "object", + "properties": { + "user": { + "$ref": "#/definitions/User" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "UserList": { + "type": "object", + "properties": { + "pageNumber": { + "description": "页数", + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "description": "页大小", + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "description": "总条数", + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + }, + "users": { + "description": "user实体列表", + "type": "array", + "items": { + "$ref": "#/definitions/User" + }, + "x-go-name": "Users" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "VerifyUserRequest": { + "type": "object", + "required": [ + "userName", + "password", + "roleId" + ], + "properties": { + "password": { + "description": "密码", + "type": "string", + "x-go-name": "Password" + }, + "roleId": { + "description": "角色uuid", + "type": "string", + "x-go-name": "RoleID" + }, + "userName": { + "description": "用户名,唯一", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "Volume": { + "description": "Volume 卷管理表", + "type": "object", + "properties": { + "createdBy": { + "description": "RaidCan string `gorm:\"column:raid_can\" json:\"raidCan\"` // RAID配置: (RAID,NO RAID)\nRaid string `gorm:\"column:raid\" json:\"raid\"` // RAID模式:RAID1,RIAD10等", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "type": "integer", + "format": "int64", + "x-go-name": "CreatedTime" + }, + "deletedTime": { + "type": "integer", + "format": "int64", + "x-go-name": "DeletedTime" + }, + "deviceTypeId": { + "description": "设备类型uuid", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "diskType": { + "description": "硬盘类型(SSD,HDD)", + "type": "string", + "x-go-name": "DiskType" + }, + "interfaceType": { + "description": "接口类型(SATA,SAS,NVME,不限制)", + "type": "string", + "x-go-name": "InterfaceType" + }, + "isDel": { + "type": "integer", + "format": "int8", + "x-go-name": "IsDel" + }, + "updatedBy": { + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "type": "integer", + "format": "int64", + "x-go-name": "UpdatedTime" + }, + "volumeAmount": { + "description": "硬盘数量(最低块数)", + "type": "integer", + "format": "int64", + "x-go-name": "VolumeAmount" + }, + "volumeId": { + "description": "卷uuid", + "type": "string", + "x-go-name": "VolumeID" + }, + "volumeName": { + "description": "卷名称", + "type": "string", + "x-go-name": "VolumeName" + }, + "volumeSize": { + "description": "单盘大小(最小容量)", + "type": "string", + "x-go-name": "VolumeSize" + }, + "volumeType": { + "description": "卷类型:系统卷,数据卷", + "type": "string", + "x-go-name": "VolumeType" + }, + "volumeUnit": { + "description": "硬盘单位(GB,TB)", + "type": "string", + "x-go-name": "VolumeUnit" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/dao/volumeDao" + }, + "VolumeRaID": { + "type": "object", + "properties": { + "raidCan": { + "type": "string", + "x-go-name": "RaidCan" + }, + "raidId": { + "description": "raid uuid", + "type": "string", + "x-go-name": "RaidID" + }, + "volumeId": { + "description": "卷 uuid", + "type": "string", + "x-go-name": "VolumeID" + }, + "volumeType": { + "description": "system|data", + "type": "string", + "x-go-name": "VolumeType" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "VolumeRaids": { + "type": "object", + "properties": { + "createdBy": { + "description": "RaidCan string `gorm:\"column:raid_can\" json:\"raidCan\"` // RAID配置: (RAID,NO RAID)\nRaid string `gorm:\"column:raid\" json:\"raid\"` // RAID模式:RAID1,RIAD10等", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "type": "integer", + "format": "int64", + "x-go-name": "CreatedTime" + }, + "deletedTime": { + "type": "integer", + "format": "int64", + "x-go-name": "DeletedTime" + }, + "deviceTypeId": { + "description": "设备类型uuid", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "diskType": { + "description": "硬盘类型(SSD,HDD)", + "type": "string", + "x-go-name": "DiskType" + }, + "interfaceType": { + "description": "接口类型(SATA,SAS,NVME,不限制)", + "type": "string", + "x-go-name": "InterfaceType" + }, + "isDel": { + "type": "integer", + "format": "int8", + "x-go-name": "IsDel" + }, + "raids": { + "type": "array", + "items": { + "$ref": "#/definitions/RVolumeRaid" + }, + "x-go-name": "Raids" + }, + "updatedBy": { + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "type": "integer", + "format": "int64", + "x-go-name": "UpdatedTime" + }, + "volumeAmount": { + "description": "硬盘数量(最低块数)", + "type": "integer", + "format": "int64", + "x-go-name": "VolumeAmount" + }, + "volumeId": { + "description": "卷uuid", + "type": "string", + "x-go-name": "VolumeID" + }, + "volumeName": { + "description": "卷名称", + "type": "string", + "x-go-name": "VolumeName" + }, + "volumeSize": { + "description": "单盘大小(最小容量)", + "type": "string", + "x-go-name": "VolumeSize" + }, + "volumeType": { + "description": "卷类型:系统卷,数据卷", + "type": "string", + "x-go-name": "VolumeType" + }, + "volumeUnit": { + "description": "硬盘单位(GB,TB)", + "type": "string", + "x-go-name": "VolumeUnit" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + } + }, + "responses": { + "ErrorResponse": { + "description": "unit err response for non 200", + "schema": { + "type": "object", + "required": [ + "error", + "requestId" + ], + "properties": { + "error": { + "$ref": "#/definitions/ErrorResponse" + }, + "requestId": { + "description": "流量ID", + "type": "string", + "x-go-name": "RequestId" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "addAlert": { + "description": "A AddAlertResult is an response struct that is used to describe create Alert result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "addRule": { + "description": "A AddRuleResult is an response struct that is used to describe create rule result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "cancelShareUserProject": { + "description": "A CancelShareUserProjectResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createProjectInstance": { + "description": "A CreateProjectInstanceResult is an response struct that is used to describe create instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/InstanceIds" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createUserApikey": { + "description": "A CreateUserApikeyResult is an response struct that is used to describe create apikey result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ApikeyId" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createUserProject": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ProjectId" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createUserSshkey": { + "description": "A CreateUserSshkeyResult is an response struct that is used to describe create sshkey result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/SshkeyId" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "currentRole": { + "description": "A CurrentRoleResult is an response struct that is used to describe role.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/RoleInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteAlert": { + "description": "A DeleteAlertResult is an response struct that is used to describe create alert result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteInstances": { + "description": "A DeleteInstancesResult is an response struct that is used to describe modify instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteMessage": { + "description": "A DeleteMessageResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteProjectInstance": { + "description": "A DeleteProjectInstanceResult is an response struct that is used to delete stop instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteRule": { + "description": "A DeleteRuleResult is an response struct that is used to describe create rule result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteUserApikey": { + "description": "A DeleteUserApikeyResult is an response struct that is used to describe delete Apikey result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteUserProject": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteUserSshkey": { + "description": "A DeleteUserSshkeyResult is an response struct that is used to describe delete sshkey result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeAlert": { + "description": "A DescribeAlertResult is an response struct that is used to describe get Alert.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/Alert" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeAlerts": { + "description": "A DescribeAlertsResult is an response struct that is used to describe get Alert.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/AlertList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeAuditLogTypes": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "type": "array", + "items": { + "$ref": "#/definitions/AuditLogsType" + }, + "x-go-name": "Result" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeAuditLogs": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/AuditLogList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDevice": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/DeviceInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDeviceStock": { + "description": "A GetDeviceStockResult is an response struct that is used to get device stock.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/DeviceStock" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDeviceType": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/DeviceTypeInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDeviceTypeImagePartitions": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/QueryDeviceTypeImagePartitionResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDeviceTypeImages": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ImageList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDeviceTypes": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/DeviceTypeList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDevices": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/DeviceList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeIdc": { + "description": "A DescribeIdcResult is an response struct that is used to describe idc.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/IdcInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeIdcs": { + "description": "A DescribIdcsResult is an response struct that is used to describe idcs.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/IdcList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeImage": { + "description": "A DescribeImageResult is an response struct that is used to describe image.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ImageInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeImageDeviceTypes": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/DeviceTypeList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeImages": { + "description": "A DescribeImagesResult is an response struct that is used to describe images.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ImageList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeInstancesByProjectIdAndOwnerNameAndSharerName": { + "description": "A DescribeInstancesByProjectIdAndOwnerNameAndSharerNameResult is an response struct that is used to get instance list.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/InstanceForShareList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeLicenseContent": { + "description": "A DescribeLicenseContentResult is an response struct that is used to describe getuser.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/LicenseContent" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeLocalUser": { + "description": "A DescribeLocalUserResult is an response struct that is used to describe getuser.", + "schema": { + "type": "object", + "properties": { + "error": { + "$ref": "#/definitions/ErrorResponse" + }, + "result": { + "$ref": "#/definitions/UserInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeOS": { + "description": "A DescribeOsResult is an response struct that is used to describe os.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/OsInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeOSs": { + "description": "A DescribeOssResult is an response struct that is used to describe oss.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/OsList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeProjectInstance": { + "description": "A GetInstanceResult is an response struct that is used to describe instance.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/InstanceInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeProjectInstances": { + "description": "A DescribeProjectInstancesResult is an response struct that is used to get instance list.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/InstanceList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeResources": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeRole": { + "description": "A GetRoleResult is an response struct that is used to describe role.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/RoleInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeRoles": { + "description": "A GetRoleListResult is an response struct that is used to describe get role list.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/RoleList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeRule": { + "description": "A DescribeRuleResult is an response struct that is used to describe get rule.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/Rule" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeRules": { + "description": "A DescribeRuleResult is an response struct that is used to describe get rule.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/RuleList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeShareProject": { + "description": "A DescribeShareProjectResult is an response struct that is used to describe getapikey.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ShareProjectInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUser": { + "description": "", + "schema": { + "type": "object", + "properties": { + "error": { + "$ref": "#/definitions/ErrorResponse" + }, + "result": { + "$ref": "#/definitions/UserInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUserAPIKey": { + "description": "A DescribeUserAPIKeyResult is an response struct that is used to describe getapikey.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ApikeyInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUserAPIKeys": { + "description": "A DescribeUserAPIKeysResult is an response struct that is used to describe getapikeylist.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ApikeyList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUserByName": { + "description": "A GetUserByNameResult is an response struct that is used to describe user.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/UserInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUserProject": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ProjectInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUserProjects": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ProjectList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUserSshKey": { + "description": "A DescribeUserSshKeyResult is an response struct that is used to describe sshkey.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/SshkeyInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUserSshKeys": { + "description": "A DescribeUserSshKeysResult is an response struct that is used to describe get sshkey list.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/SshkeyList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUsers": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/UserList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeVolumesRaids": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "type": "array", + "items": { + "$ref": "#/definitions/VolumeRaids" + }, + "x-go-name": "Result" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "desrcibeAgentStatus": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/AgentStatusResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "desrcibeTags": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/TagsResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "disableRule": { + "description": "A DisableRuleResult is an response struct that is used to describe create rule result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "editRule": { + "description": "A EditRuleResult is an response struct that is used to describe create rule result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "enableRule": { + "description": "A EnableRuleResult is an response struct that is used to describe create rule result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "getInstancesBySshkey": { + "description": "A GetInstancesBySshkeyResult is an response struct that is used to get instance list by sshkey.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/InstancesSshkeyInfoResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "getMessageById": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/MessageWithNextPrev" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "getMessageList": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/MessageList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "getMessageStatistic": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/MessageStatistic" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "getMessageTypes": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/MessageTypesResp" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "getMonitorData": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "type": "array", + "items": { + "$ref": "#/definitions/DataEveryMetric" + }, + "x-go-name": "Result" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "hasUnreadMessage": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/HasUnreadMessage" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "lockProjectInstance": { + "description": "A LockProjectInstanceResult is an response struct that is used to describe lock instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyInstances": { + "description": "A ModifyInstancesResult is an response struct that is used to describe modify instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyLocalUser": { + "description": "A ModifyLocalUserResult is an response struct that is used to describe getuser.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyLocalUserPassword": { + "description": "A ModifyLocalUserPasswordResult is an response struct that is used to describe getuser.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyProjectInstance": { + "description": "A ModifyProjectInstanceResult is an response struct that is used to describe modify instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyUser": { + "description": "A GetUserResult is an response struct that is used to describe getuser.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyUserApikey": { + "description": "A ModifyUserApikeyResult is an response struct that is used to describe modifyApikey result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyUserProject": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyUserProjectDescription": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyUserSshkey": { + "description": "A ModifyUserSshkeyResult is an response struct that is used to modify sshkey result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "moveUserInstances": { + "description": "A MoveInstanceResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "moveUserProject": { + "description": "A MoveProjectResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "readMessage": { + "description": "A ReadMessageResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "reinstallProjectInstance": { + "description": "A ReinstallProjectInstanceResult is an response struct that is used to describe reinstall instance.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "resetInstanceStatus": { + "description": "A ResetInstanceStatusResult is an response struct that is used to describe restart instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "resetProjectInstancePasswd": { + "description": "A ResetProjectInstancePasswdResult is an response struct that is used to describe reset instance password.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "resetProjectInstancesPasswd": { + "description": "A ResetProjectInstancesPasswdResult is an response struct that is used to describe reset instance password.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "restartInstances": { + "description": "A RestartInstancesResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "restartProjectInstance": { + "description": "A RestartProjectInstanceResult is an response struct that is used to describe restart instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "shareUserProject": { + "description": "A ShareUserProjectResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "startInstances": { + "description": "A StartInstancesResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "startProjectInstance": { + "description": "A StartProjectInstanceResult is an response struct that is used to describe start instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "stopInstances": { + "description": "A StopInstancesResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "stopProjectInstance": { + "description": "A StopProjectInstanceResult is an response struct that is used to describe stop instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "unLockProjectInstance": { + "description": "A UnLockProjectInstanceResult is an response struct that is used to describe unlock instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "verifyUser": { + "description": "A VerifyUserResult is an response struct that is used to describe verify user result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + } + }, + "securityDefinitions": { + "api_key": { + "type": "apiKey", + "name": "bmp-ak", + "in": "header" + } + }, + "security": [ + { + "api_key": [] + } + ], + "x-meta-array": [ + "value1", + "value2" + ], + "x-meta-array-obj": [ + { + "name": "obj", + "value": "field" + } + ], + "x-meta-value": "value" +} \ No newline at end of file diff --git a/bmp-openapi-console/swagger.yml b/bmp-openapi-console/swagger.yml new file mode 100644 index 0000000..1aeb1bb --- /dev/null +++ b/bmp-openapi-console/swagger.yml @@ -0,0 +1,9219 @@ +basePath: /v1 +consumes: + - application/json + - application/xml +definitions: + AddAlertItem: + properties: + alertPeriod: + description: 告警持续时间 + format: int64 + type: integer + x-go-name: AlertPeriod + alertTimestamp: + description: 告警时间戳 + format: int64 + type: integer + x-go-name: AlertTimestamp + alertValue: + description: 告警值 + type: string + x-go-name: AlertValue + calculationUnit: + description: 计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出] + type: string + x-go-name: CalculationUnit + instanceId: + description: 实例id + type: string + x-go-name: InstanceID + isRecover: + description: 是否为恢复通知,0为不是,1为是 + format: int64 + type: integer + x-go-name: IsRecover + ruleId: + description: 规则ID + type: string + x-go-name: RuleID + ruleName: + description: 规则名称 + type: string + x-go-name: RuleName + trigger: + description: 触发条件 + type: string + x-go-name: Trigger + required: + - ruleId + - instanceId + - trigger + - alertValue + - alertTimestamp + - alertPeriod + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + AddAlertRequest: + properties: + alerts: + items: + $ref: '#/definitions/AddAlertItem' + type: array + x-go-name: Alerts + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + AddRuleRequest: + properties: + deviceTag: + description: 盘符、挂载点、网口列表 + type: string + x-go-name: DeviceTag + dimension: + description: 维度 [instance、disk、mountpoint、nic] + type: string + x-go-name: Dimension + instanceIds: + description: 实例id列表 + items: + type: string + type: array + x-go-name: InstanceIds + noticeOption: + $ref: '#/definitions/RuleNotice' + projectId: + description: 规则所属的项目uuid + type: string + x-go-name: ProjectID + resource: + description: 资源类型,目前只支持instance + type: string + x-go-name: Resource + ruleName: + description: 规则名称 + type: string + x-go-name: RuleName + triggerOption: + description: 触发条件 + items: + $ref: '#/definitions/RuleTrigger' + type: array + x-go-name: TriggerOption + required: + - projectId + - ruleName + - dimension + - resource + - triggerOption + - noticeOption + - instanceIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + AgentStatusItem: + properties: + agent_version: + type: string + x-go-name: AgentVersion + instance_id: + type: string + x-go-name: InstanceID + sn: + type: string + x-go-name: SN + status: + description: 1->running 2->stopped 0->unknown + format: int64 + type: integer + x-go-name: Status + statusName: + description: status 运行 停止 未知 + type: string + x-go-name: StatusName + timestamp: + format: int64 + type: integer + x-go-name: Timestamp + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + AgentStatusResponse: + properties: + agentStatus: + items: + $ref: '#/definitions/AgentStatusItem' + type: array + x-go-name: AgentStatus + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Alert: + properties: + alertId: + description: alert uuid + type: string + x-go-name: AlertID + alertLevel: + description: 1表示一般,2表示严重,3表示紧急 + format: int64 + type: integer + x-go-name: AlertLevel + alertLevelDescription: + description: 级别描述 + type: string + x-go-name: AlertLevelDescription + alertPeriod: + description: 告警持续时间(分钟为单位) + format: int64 + type: integer + x-go-name: AlertPeriod + alertTime: + description: 告警时间戳 + format: int64 + type: integer + x-go-name: AlertTime + alertValue: + description: 报警值 + type: string + x-go-name: AlertValue + createdTime: + description: 创建时间戳 + format: int64 + type: integer + x-go-name: CreatedTime + instance: + $ref: '#/definitions/Instance' + resource: + description: 资源类型 [只支持instance一种] + type: string + x-go-name: Resource + resourceId: + description: 资源id,目前就是实例id + type: string + x-go-name: ResourceID + resourceName: + description: 资源名称,目前就是实例名称 + type: string + x-go-name: ResourceName + rule: + $ref: '#/definitions/Rule' + trigger: + description: 触发条件,接口需要翻译 + type: string + x-go-name: Trigger + triggerDescription: + description: 触发条件描述 + type: string + x-go-name: TriggerDescription + userId: + description: 通知对象 userid + type: string + x-go-name: UserID + userName: + description: 通知对象 用户名 + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + AlertList: + properties: + instances: + description: rules数组 + items: + $ref: '#/definitions/Alert' + type: array + x-go-name: Alerts + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Apikey: + properties: + apiKeyId: + description: apikey uuid + type: string + x-go-name: ApikeyID + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + id: + format: int64 + type: integer + x-go-name: ID + name: + description: 名称 + type: string + x-go-name: Name + readOnly: + description: 是否支持只读, [0/1], 1表示只读 + format: int8 + type: integer + x-go-name: ReadOnly + token: + description: 32位字符令牌,使用token来独立访问openapi + type: string + x-go-name: Token + type: + description: apikey的类型,[system/user] + type: string + x-go-name: Type + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + userId: + description: 所属用户uuid + type: string + x-go-name: UserID + required: + - apiKeyId + - name + - readOnly + - token + - type + - userId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ApikeyId: + properties: + apikeyId: + description: apikey uuid + type: string + x-go-name: ApikeyId + required: + - apikeyId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ApikeyInfo: + properties: + apikey: + $ref: '#/definitions/Apikey' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ApikeyList: + properties: + apikeys: + items: + $ref: '#/definitions/Apikey' + type: array + x-go-name: Apikeys + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + AuditLog: + properties: + deviceId: + description: device_id + type: string + x-go-name: DeviceID + failReason: + description: 失败原因 + type: string + x-go-name: FailReason + finishTime: + description: 完成时间 + format: int64 + type: integer + x-go-name: FinishTime + id: + format: int64 + type: integer + x-go-name: ID + instanceId: + description: instance_id + type: string + x-go-name: InstanceID + logid: + description: 日志uuid + type: string + x-go-name: LogID + operateTime: + description: 操作时间 + format: int64 + type: integer + x-go-name: OperateTime + operation: + description: 操作 + type: string + x-go-name: Operation + operationName: + description: 操作名称 + type: string + x-go-name: OperationName + result: + description: 结果 success/fail + type: string + x-go-name: Result + sn: + description: sn + type: string + x-go-name: Sn + userID: + description: 操作人 + type: string + x-go-name: UserID + userName: + description: 操作人 + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + AuditLogList: + properties: + auditLogs: + description: 机型列表 + items: + $ref: '#/definitions/AuditLog' + type: array + x-go-name: AuditLogs + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + AuditLogsType: + properties: + name: + description: name,自动适配中英文 + type: string + x-go-name: Name + operation: + description: 数据库中存储的operation + type: string + x-go-name: Operation + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + CalcelShareProjectRequest: + properties: + ownerID: + description: from user_id + type: string + x-go-name: OwnerID + sharerID: + description: to user_id + type: string + x-go-name: SharerID + required: + - ownerID + - sharerID + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CommonResponse: + properties: + success: + description: 操作是否成功 [true/false] + type: boolean + x-go-name: Success + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + CreateApikeyRequest: + properties: + name: + description: 秘钥对名称 + type: string + x-go-name: Name + readOnly: + description: 是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法 + format: int8 + type: integer + x-go-name: ReadOnly + type: + description: Token类型, [system/user] + type: string + x-go-name: Type + required: + - name + - readOnly + - type + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateInstanceRequest: + properties: + VolumeRaids: + description: 数据卷和选择的raidid + items: + $ref: '#/definitions/VolumeRaID' + type: array + x-go-name: VolumeRaIDs + bootMode: + description: 启动模式 + type: string + x-go-name: BootMode + count: + description: 创建数量 + format: int64 + type: integer + x-go-name: Count + description: + description: 描述 + type: string + x-go-name: Description + deviceTypeId: + description: 设备类型ID + type: string + x-go-name: DeviceTypeID + hostname: + description: 主机名称 + type: string + x-go-name: HostName + idcId: + description: 机房ID + type: string + x-go-name: IdcID + imageId: + description: 镜像ID + type: string + x-go-name: ImageID + installBmpAgent: + description: 是否安装bmp-agent + type: boolean + x-go-name: InstallBmpAgent + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + password: + description: 密码 + type: string + x-go-name: Password + projectId: + description: 项目ID + type: string + x-go-name: ProjectID + sshKeyId: + description: 秘钥ID + type: string + x-go-name: SshKeyID + systemPartition: + description: 系统盘分区 + items: + $ref: '#/definitions/Partition' + type: array + x-go-name: SystemPartition + systemVolumeRaidId: + description: 系统盘RAID ID + type: string + x-go-name: SystemVolumeRaidID + required: + - projectId + - idcId + - deviceTypeId + - imageId + - systemVolumeRaidId + - instanceName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateProjectRequest: + properties: + isDefault: + description: 是否作为该用户的默认项目, [0/1], 默认为0 + format: int8 + type: integer + x-go-name: IsDefault + isSystem: + description: 是否作为系统项目, [0/1], 默认为0 + format: int8 + type: integer + x-go-name: IsSystem + projectName: + description: ProjectName 1~64字符,只支持数字、大小写字母、中英文下划线“_”及中划线“-” + type: string + x-go-name: ProjectName + required: + - projectName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateSshkeyRequest: + properties: + key: + description: 公钥内容,格式:^ssh-rsa AAAAB3NzaC1yc2.* + type: string + x-go-name: Key + name: + description: 秘钥名称 + type: string + x-go-name: Name + required: + - name + - key + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + DataEveryMetric: + properties: + data: + items: + $ref: '#/definitions/MonitorDataItem' + type: array + x-go-name: Data + query: + $ref: '#/definitions/MonitorDataQuery' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeleteAlertRequest: + properties: + alertId: + description: 告警id + type: string + x-go-name: AlertId + required: + - alertId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + DeleteInstancesRequest: + description: 批量删除实例 + properties: + instance_ids: + description: 实例id列表 + items: + type: string + type: array + x-go-name: InstanceIDs + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + DeleteMessagesRequest: + properties: + messageIds: + items: + type: string + type: array + x-go-name: MessageIds + required: + - messageIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + DeleteRuleRequest: + properties: + ruleId: + description: 规则id + type: string + x-go-name: RuleId + required: + - ruleId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + Device: + properties: + Enclosure2: + description: 系统盘2背板号 + type: string + adapterId: + description: adapter_id + format: int64 + type: integer + x-go-name: AdapterID + architecture: + description: 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + type: string + x-go-name: Architecture + brand: + description: 品牌 + type: string + x-go-name: Brand + cabinet: + description: 机柜编码 + type: string + x-go-name: Cabinet + cpuAmount: + description: cpu数量 + format: int64 + type: integer + x-go-name: CPUAmount + cpuCores: + description: 单个cpu内核数 + format: int64 + type: integer + x-go-name: CPUCores + cpuFrequency: + description: cpu频率(G) + type: string + x-go-name: CPUFrequency + cpuInfo: + description: 拼装信息 + type: string + x-go-name: CpuInfo + cpuManufacturer: + description: cpu厂商 + type: string + x-go-name: CPUManufacturer + cpuModel: + description: cpu处理器型号 + type: string + x-go-name: CPUModel + cpuRoads: + description: 单个cpu路数 + format: int8 + type: integer + x-go-name: CPURoads + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + dataVolumeAmount: + description: 数据盘数量 + format: int64 + type: integer + x-go-name: DataVolumeAmount + dataVolumeInterfaceType: + description: 数据盘接口类型(SATA,SAS,NVME) + type: string + x-go-name: DataVolumeInterfaceType + dataVolumeSize: + description: 数据盘单盘大小 + format: int64 + type: integer + x-go-name: DataVolumeSize + dataVolumeType: + description: 数据盘类型(SSD,HDD) + type: string + x-go-name: DataVolumeType + description: + description: 描述 + type: string + x-go-name: Description + deviceId: + description: 设备uuid + type: string + x-go-name: DeviceID + deviceSeries: + description: 计算型,存储型 + type: string + x-go-name: DeviceSeries + deviceSeriesName: + description: 计算型,存储型 + type: string + x-go-name: DeviceSeriesName + deviceType: + description: 型号,机型规格cps.normal + type: string + x-go-name: DeviceType + deviceTypeId: + description: 机型uuid + type: string + x-go-name: DeviceTypeID + deviceTypeName: + description: 机型名称 + type: string + x-go-name: DeviceTypeName + dvInfo: + type: string + x-go-name: DvInfo + enclosure1: + description: 添加到disk表, 系统盘1背板号 + type: string + x-go-name: Enclosure1 + eth1Mask: + description: eth1子网掩码 + type: string + x-go-name: Eth1Mask + gateway: + description: 网关地址 + type: string + x-go-name: Gateway + gpuAmount: + description: gpu数量 + format: int64 + type: integer + x-go-name: GpuAmount + gpuInfo: + type: string + x-go-name: GpuInfo + gpuManufacturer: + description: gpu厂商 + type: string + x-go-name: GpuManufacturer + gpuModel: + description: gpu处理器型号 + type: string + x-go-name: GpuModel + id: + description: 设备ID编号 + format: int64 + type: integer + x-go-name: ID + idcId: + description: 机房uuid + type: string + x-go-name: IdcID + idcName: + description: 机房名称 + type: string + x-go-name: IdcName + idcNameEn: + description: idcname + type: string + x-go-name: IDcNameEn + iloIp: + description: 带外管理IP + type: string + x-go-name: IloIP + iloPassword: + description: 带外账号密码 + type: string + x-go-name: IloPassword + iloUser: + description: 带外账号 + type: string + x-go-name: IloUser + imageName: + description: 实例镜像名称 + type: string + x-go-name: ImageName + instanceCreatedTime: + description: 实例创建时间 + type: string + x-go-name: InstanceCreatedTime + instanceDescription: + description: 实例描述 + type: string + x-go-name: InstanceDescription + instanceId: + description: 实例id + type: string + x-go-name: InstanceID + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + instanceReason: + description: 实例失败原因 + type: string + x-go-name: InstanceReason + instanceStatus: + description: 实例状态 + type: string + x-go-name: InstanceStatus + instanceStatusName: + description: 实例状态 + type: string + x-go-name: InstanceStatusName + interfaceMode: + description: '【网口模式】【网络设置】: bond单网口,dual双网口' + type: string + x-go-name: InterfaceMode + locked: + description: 实例是否锁定 锁定locked 未锁定unlocked + type: string + x-go-name: Locked + mac1: + description: MAC1(eth0) + type: string + x-go-name: Mac1 + mac2: + description: MAC2(eth2) + type: string + x-go-name: Mac2 + manageStatus: + description: '设备状态: 未装机,已装机' + type: string + x-go-name: ManageStatus + manageStatusName: + description: '设备状态: 未装机,已装机' + type: string + x-go-name: ManageStatusName + mask: + description: 子网掩码 + type: string + x-go-name: Mask + memAmount: + description: 内存数量 + format: int64 + type: integer + x-go-name: MemAmount + memFrequency: + description: 内存主频(MHz) + format: int64 + type: integer + x-go-name: MemFrequency + memInfo: + type: string + x-go-name: MemInfo + memSize: + description: 单个内存大小(GB) + format: int64 + type: integer + x-go-name: MemSize + memType: + description: 内存接口(如DDR3,DDR4) + type: string + x-go-name: MemType + model: + description: 型号 + type: string + x-go-name: Model + nicAmount: + description: 网卡数量 + format: int64 + type: integer + x-go-name: NicAmount + nicInfo: + type: string + x-go-name: NicInfo + nicRate: + description: 网卡传输速率(GE) + format: int64 + type: integer + x-go-name: NicRate + privateEth1Ipv4: + description: eth1内网IPV4 + type: string + x-go-name: PrivateEth1IPv4 + privateEth1Ipv6: + description: eth1内网IPV6 + type: string + x-go-name: PrivateEth1IPv6 + privateIpv4: + description: 内网IPV4 + type: string + x-go-name: PrivateIPv4 + privateIpv6: + description: 内网IPV6 + type: string + x-go-name: PrivateIPv6 + raidDriver: + description: raid工具:(megacli64等) + type: string + x-go-name: RaidDriver + reason: + description: 设备状态变更失败原因 + type: string + x-go-name: Reason + slot1: + description: 系统盘1槽位 + format: int64 + type: integer + x-go-name: Slot1 + slot2: + description: 系统盘2槽位 + format: int64 + type: integer + x-go-name: Slot2 + sn: + description: 设备SN + type: string + x-go-name: Sn + svInfo: + type: string + x-go-name: SvInfo + switchIp: + description: 网口交换机IP + type: string + x-go-name: SwitchIP + switchIp1: + description: 交换机1ip + type: string + x-go-name: SwitchIP1 + switchIp2: + description: 交换机2ip + type: string + x-go-name: SwitchIP2 + switchPassword1: + description: 交换机1登录密码 + type: string + x-go-name: SwitchPassword1 + switchPassword2: + description: 交换机2登录密码 + type: string + x-go-name: SwitchPassword2 + switchPort1: + description: 交换机1port + type: string + x-go-name: SwitchPort1 + switchPort2: + description: 交换机2port + type: string + x-go-name: SwitchPort2 + switchUser1: + description: 交换机1登录账号,如果为空,取所在机房的值 + type: string + x-go-name: SwitchUser1 + switchUser2: + description: 交换机2登录账号,如果为空,取所在机房的值 + type: string + x-go-name: SwitchUser2 + systemVolumeAmount: + description: 系统盘数量 + format: int64 + type: integer + x-go-name: SystemVolumeAmount + systemVolumeInterfaceType: + description: 系统盘接口类型(SATA,SAS,NVME) + type: string + x-go-name: SystemVolumeInterfaceType + systemVolumeSize: + description: 系统盘单盘大小 + format: int64 + type: integer + x-go-name: SystemVolumeSize + systemVolumeType: + description: 系统盘类型(SSD,HDD) + type: string + x-go-name: SystemVolumeType + uPosition: + description: U位 + type: string + x-go-name: UPosition + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + userId: + description: 实例归属用户uuid + type: string + x-go-name: UserId + userName: + description: 实例归属用户名称 + type: string + x-go-name: UserName + required: + - idcId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeviceInfo: + properties: + device: + $ref: '#/definitions/Device' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeviceList: + properties: + devices: + description: 设备列表 + items: + $ref: '#/definitions/Device' + type: array + x-go-name: Devices + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeviceStock: + properties: + stocks: + description: 库存量 + format: int64 + type: integer + x-go-name: Stocks + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeviceType: + properties: + architecture: + description: 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + type: string + x-go-name: Architecture + boot_mode: + description: boot模式 + type: string + x-go-name: BootMode + cpuAmount: + description: cpu数量 + format: int64 + type: integer + x-go-name: CPUAmount + cpuCores: + description: 单个cpu内核数 + format: int64 + type: integer + x-go-name: CPUCores + cpuFrequency: + description: cpu频率(G) + type: string + x-go-name: CPUFrequency + cpuInfo: + description: 拼装信息 + type: string + x-go-name: CpuInfo + cpuManufacturer: + description: cpu厂商 + type: string + x-go-name: CPUManufacturer + cpuModel: + description: cpu处理器型号 + type: string + x-go-name: CPUModel + cpuSpec: + description: CPU 规格,预置还是其它 + type: string + x-go-name: CpuSpec + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + description: + description: 描述 + type: string + x-go-name: Description + deviceCount: + format: int64 + type: integer + x-go-name: DeviceCount + deviceSeries: + description: 机型类型,如计算型,存储型 + type: string + x-go-name: DeviceSeries + deviceSeriesName: + description: 机型类型,如计算型,存储型 + type: string + x-go-name: DeviceSeriesName + deviceType: + description: 机型规格, cps.c.normal + type: string + x-go-name: DeviceType + deviceTypeId: + description: 机型uuid + type: string + x-go-name: DeviceTypeID + dvInfo: + type: string + x-go-name: DvInfo + gpuAmount: + description: gpu数量 + format: int64 + type: integer + x-go-name: GpuAmount + gpuInfo: + type: string + x-go-name: GpuInfo + gpuManufacturer: + description: gpu厂商 + type: string + x-go-name: GpuManufacturer + gpuModel: + description: gpu处理器型号 + type: string + x-go-name: GpuModel + height: + description: 显示机型高度 + format: int64 + type: integer + x-go-name: Height + id: + format: int64 + type: integer + x-go-name: ID + idcId: + description: 机房uuid + type: string + x-go-name: IDcID + idcName: + description: 机房名称 + type: string + x-go-name: IDcName + idcNameEn: + description: 机房名称 + type: string + x-go-name: IDcNameEn + instanceCount: + format: int64 + type: integer + x-go-name: InstanceCount + instanceStatus: + items: + type: string + type: array + x-go-name: InstanceStatus + interfaceMode: + description: bond单网口,dual双网口 + type: string + x-go-name: InterfaceMode + isNeedRaid: + description: 是否配置了阵列卡 + type: string + x-go-name: IsNeedRaid + memAmount: + description: 内存数量 + format: int64 + type: integer + x-go-name: MemAmount + memFrequency: + description: 内存主频(MHz) + format: int64 + type: integer + x-go-name: MemFrequency + memInfo: + type: string + x-go-name: MemInfo + memSize: + description: 单个内存大小(GB) + format: int64 + type: integer + x-go-name: MemSize + memSpec: + description: 内存 规格,预置还是其它 + type: string + x-go-name: MemSpec + memType: + description: 内存接口(如DDR3,DDR4) + type: string + x-go-name: MemType + name: + description: 机型名称,如计算效能型,标准计算型 + type: string + x-go-name: Name + nicAmount: + description: 网卡数量 + format: int64 + type: integer + x-go-name: NicAmount + nicInfo: + type: string + x-go-name: NicInfo + nicRate: + description: 网卡传输速率(GE) + format: int64 + type: integer + x-go-name: NicRate + raid: + description: 系统盘raid + type: string + x-go-name: Raid + raidCan: + description: raid配置 + type: string + x-go-name: RaidCan + stockAvailable: + description: StockAvailable 可用库存 + format: int64 + type: integer + x-go-name: StockAvailable + svInfo: + type: string + x-go-name: SvInfo + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + volumes: + description: 机型的卷信息 + items: + $ref: '#/definitions/Volume' + type: array + x-go-name: Volumes + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeviceTypeInfo: + properties: + deviceType: + $ref: '#/definitions/DeviceType' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeviceTypeList: + properties: + deviceTypes: + description: 机型列表 + items: + $ref: '#/definitions/DeviceType' + type: array + x-go-name: DeviceTypes + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DisableRuleRequest: + properties: + ruleId: + description: 规则id + type: string + x-go-name: RuleId + required: + - ruleId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + EditRuleRequest: + properties: + deviceTag: + description: 盘符、挂载点、网口列表 + type: string + x-go-name: DeviceTag + dimension: + description: 维度 [instance、disk、mountpoint、nic] + type: string + x-go-name: Dimension + instanceIds: + description: 实例id列表 + items: + type: string + type: array + x-go-name: InstanceIds + noticeOption: + $ref: '#/definitions/RuleNotice' + resource: + description: 资源类型,目前只支持instance + type: string + x-go-name: Resource + ruleId: + description: 规则id + type: string + x-go-name: RuleId + ruleName: + description: 规则名称 + type: string + x-go-name: RuleName + triggerOption: + description: 触发条件 + items: + $ref: '#/definitions/RuleTrigger' + type: array + x-go-name: TriggerOption + required: + - ruleId + - ruleName + - dimension + - resource + - triggerOption + - noticeOption + - instanceIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + EnableRuleRequest: + properties: + ruleId: + description: 规则id + type: string + x-go-name: RuleId + required: + - ruleId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ErrorResponse: + properties: + code: + description: 错误码 + format: int64 + type: integer + x-go-name: Code + message: + description: 错误信息 + type: string + x-go-name: Message + status: + description: 错误状态 + type: string + x-go-name: Status + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/controllers + HasUnreadMessage: + properties: + hasUnread: + type: boolean + x-go-name: HasUnread + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Idc: + properties: + address: + description: 机房地址 + type: string + x-go-name: Address + createTime: + description: 创建时间 + type: string + x-go-name: CreateTime + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + id: + format: int64 + type: integer + x-go-name: ID + idcId: + description: 机房uuid + type: string + x-go-name: IDcID + iloPassword: + description: 机房公用带外管理password + type: string + x-go-name: IloPassword + iloUser: + description: 机房公用带外管理user + type: string + x-go-name: IloUser + level: + description: 机房等级 + type: string + x-go-name: Level + name: + description: 机房名称 + type: string + x-go-name: Name + nameEn: + description: 机房名称en + type: string + x-go-name: NameEn + shortname: + description: shortname + type: string + x-go-name: Shortname + switchPassword1: + description: 交换机密码1 + type: string + x-go-name: SwitchPassword1 + switchPassword2: + description: 交换机密码2 + type: string + x-go-name: SwitchPassword2 + switchUser1: + description: 交换机用户名1 + type: string + x-go-name: SwitchUser1 + switchUser2: + description: 交换机用户名2 + type: string + x-go-name: SwitchUser2 + updateTime: + description: 修改时间 + type: string + x-go-name: UpdateTime + updatedBy: + description: 修改用户 + type: string + x-go-name: UpdatedBy + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + IdcInfo: + properties: + idc: + $ref: '#/definitions/Idc' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + IdcList: + properties: + idcs: + description: 机房列表 + items: + $ref: '#/definitions/Idc' + type: array + x-go-name: Idcs + pageNumber: + description: 页数 + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + description: 页大小 + format: int64 + type: integer + x-go-name: PageSize + totalCount: + description: 总条数 + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Image: + properties: + architecture: + description: 架构:x86/x64/i386/ + type: string + x-go-name: Architecture + bootMode: + description: 引导模式 【UEFI Legacy/BIOS】 + type: string + x-go-name: BootMode + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + dataPartition: + description: 数据分区信息 + type: string + x-go-name: DataPartition + description: + description: 描述 + type: string + x-go-name: Description + deviceTypeNum: + description: 绑定了机型数量 + format: int64 + type: integer + x-go-name: DeviceTypeNum + filename: + description: 镜像文件名称 + type: string + x-go-name: Filename + format: + description: 镜像格式(qcow2、tar) + type: string + x-go-name: Format + hash: + description: 镜像校验码 + type: string + x-go-name: Hash + id: + format: uint64 + type: integer + x-go-name: ID + imageId: + description: 镜像uuid + type: string + x-go-name: ImageID + imageName: + description: 镜像名称 + type: string + x-go-name: ImageName + isBind: + description: 是否绑定了某个机型 + type: boolean + x-go-name: IsBind + osId: + description: 源os uuid + type: string + x-go-name: OsID + osName: + description: CentOS 7.2 64-bit + type: string + x-go-name: OsName + osType: + description: 操作系统分类:linux/windows + type: string + x-go-name: OsType + osVersion: + description: 操作系统版本 + type: string + x-go-name: OsVersion + source: + description: 镜像来源(common通用、customize定制、user_defined自定义) + type: string + x-go-name: Source + sourceName: + description: 镜像来源(common通用、customize定制、user_defined自定义) + type: string + x-go-name: SourceName + systemPartition: + description: 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + type: string + x-go-name: SystemPartition + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + url: + description: 镜像源路径 + type: string + x-go-name: URL + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ImageInfo: + properties: + image: + $ref: '#/definitions/Image' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ImageList: + properties: + images: + description: 镜像实体列表 + items: + $ref: '#/definitions/Image' + type: array + x-go-name: Images + pageNumber: + description: 页数 + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + description: 页大小 + format: int64 + type: integer + x-go-name: PageSize + totalCount: + description: 总条数 + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Instance: + properties: + bootMode: + description: 引导模式 [UEFI Legacy/BIOS] + type: string + x-go-name: BootMode + cpuAmount: + description: cpu数量 + format: int64 + type: integer + x-go-name: CPUAmount + cpuCores: + description: 单个cpu内核数 + format: int64 + type: integer + x-go-name: CPUCores + cpuFrequency: + description: cpu频率(GHz) + type: string + x-go-name: CPUFrequency + cpuManufacturer: + description: cpu厂商 + type: string + x-go-name: CPUManufacturer + cpuModel: + description: cpu处理器型号 + type: string + x-go-name: CPUModel + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + description: + description: 实例描述 + type: string + x-go-name: Description + deviceId: + description: 设备uuid + type: string + x-go-name: DeviceID + deviceSeries: + description: 机型类型,如computer + type: string + x-go-name: DeviceSeries + deviceSeriesName: + description: 机型类型,如计算型,存储型 + type: string + x-go-name: DeviceSeriesName + deviceType: + description: 机型规格, cps.c.normal + type: string + x-go-name: DeviceType + deviceTypeId: + description: 机型uuid + type: string + x-go-name: DeviceTypeID + deviceTypeName: + description: 机型名称,如计算效能型,标准计算型 + type: string + x-go-name: DeviceTypeName + eth1Mask: + type: string + x-go-name: Eth1Mask + gpuAmount: + description: gpu数量 + format: int64 + type: integer + x-go-name: GpuAmount + gpuManufacturer: + description: gpu厂商 + type: string + x-go-name: GpuManufacturer + gpuModel: + description: gpu处理器型号 + type: string + x-go-name: GpuModel + hostname: + description: 主机名 + type: string + x-go-name: Hostname + idcId: + description: 机房uuid + type: string + x-go-name: IDcID + idcName: + description: 机房名称 + type: string + x-go-name: IdcName + iloIp: + description: 带外管理IP + type: string + x-go-name: IloIP + imageId: + description: 镜像uuid + type: string + x-go-name: ImageID + imageName: + description: 镜像名称 + type: string + x-go-name: ImageName + instanceId: + description: 实例uuid + type: string + x-go-name: InstanceID + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + interfaceMode: + description: '【网口模式】【网络设置】: bond单网口,dual双网口' + type: string + x-go-name: InterfaceMode + isNeedRaid: + description: 所属的机型是否需要配置raid,页面有用 + type: string + x-go-name: IsNeedRaid + locked: + description: 是否锁定解锁锁定:locked,解锁unlocked + type: string + x-go-name: Locked + lockedName: + description: 是否锁定解锁锁定:已解锁,已锁定 + type: string + x-go-name: LockedName + mask: + type: string + x-go-name: Mask + memAmount: + description: 内存数量 + format: int64 + type: integer + x-go-name: MemAmount + memFrequency: + description: 内存主频(MHz) + format: int64 + type: integer + x-go-name: MemFrequency + memSize: + description: 单个内存大小(GB) + format: int64 + type: integer + x-go-name: MemSize + memType: + description: 内存接口(如DDR3,DDR4) + type: string + x-go-name: MemType + nicAmount: + description: 网卡数量 + format: int64 + type: integer + x-go-name: NicAmount + nicRate: + description: 网卡传输速率(GE) + format: int64 + type: integer + x-go-name: NicRate + privateEth1Ipv4: + description: eth1内网IPV4 + type: string + x-go-name: PrivateEth1IPv4 + privateEth1Ipv6: + description: eth1内网IPV6 + type: string + x-go-name: PrivateEth1IPv6 + privateIpv4: + description: 内网IPV4 + type: string + x-go-name: PrivateIPv4 + privateIpv6: + description: 内网IPV6 + type: string + x-go-name: PrivateIPv6 + projectId: + description: 实例所属项目UUID + type: string + x-go-name: ProjectID + reason: + description: 实例错误状态时的错误原因 + type: string + x-go-name: Reason + sn: + description: 设备SN + type: string + x-go-name: Sn + status: + description: 运行状态 + type: string + x-go-name: Status + statusName: + description: 运行状态中文名字 + type: string + x-go-name: StatusName + systemVolumeRaidId: + description: 系统盘raidId + type: string + x-go-name: SystemVolumeRaidID + systemVolumeRaidName: + description: 系统盘raid名称 + type: string + x-go-name: SystemVolumeRaidName + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + userId: + description: 实例所属用户UUID + type: string + x-go-name: UserID + volumeRaid: + description: 实例的volume和raid信息 + items: + $ref: '#/definitions/InstanceVolumeRaid' + type: array + x-go-name: InstanceVolumeRaids + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + InstanceForShare: + properties: + hasShared: + description: 新增,是否已经被共享过 + type: boolean + x-go-name: HasShared + instanceId: + description: 实例uuid + type: string + x-go-name: InstanceID + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + InstanceForShareList: + properties: + instances: + description: instance实体数组 + items: + $ref: '#/definitions/InstanceForShare' + type: array + x-go-name: Instances + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + InstanceIds: + properties: + instanceIds: + description: instanceId 列表 + items: + type: string + type: array + x-go-name: InstanceIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + InstanceInfo: + properties: + instance: + $ref: '#/definitions/Instance' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + InstanceList: + properties: + instances: + description: instance实体数组 + items: + $ref: '#/definitions/Instance' + type: array + x-go-name: Instances + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + InstanceVolumeRaid: + properties: + raid: + $ref: '#/definitions/Raid' + volume: + $ref: '#/definitions/Volume' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + InstancesSshkeyInfoResponse: + properties: + instanceIds: + description: 实例Id列表 + items: + type: string + type: array + x-go-name: InstanceIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + LicenseContent: + properties: + end_time: + format: int64 + type: integer + x-go-name: EndTime + hardwareinfo: + type: string + x-go-name: HardWare + license_name: + type: string + x-go-name: LicenseName + license_type: + type: string + x-go-name: LicenseType + models: + items: + type: string + type: array + x-go-name: Models + nodes_num: + format: int64 + type: integer + x-go-name: NodesNum + start_time: + format: int64 + type: integer + x-go-name: StartTime + used_nodes_num: + format: int64 + type: integer + x-go-name: UsedNodesNum + version: + type: string + x-go-name: Version + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Message: + properties: + alert_count: + description: 告警次数,始终为1,带外故障消息专属字段 + format: int64 + type: integer + x-go-name: AlertCount + alert_time: + description: 故障告警时间,带外故障消息专属字段 + format: int64 + type: integer + x-go-name: AlertTime + content: + description: 故障内容,带外故障消息专属字段 + type: string + x-go-name: Content + detail: + description: 详情, 带外监控日志的详情请用content + type: string + x-go-name: Detail + device_id: + type: string + x-go-name: DeviceID + fault_type: + description: 故障类型, 带外故障消息专属字段 + type: string + x-go-name: FaultType + finish_time: + description: 消息时间戳 + format: int64 + type: integer + x-go-name: FinishTime + has_read: + description: 0未读, 1已读 + format: int8 + type: integer + x-go-name: HasRead + idc_id: + description: 独一处的下划线,跟sdk一致 + type: string + x-go-name: IDcID + idc_name: + type: string + x-go-name: IDcName + instance_id: + description: 实例id + type: string + x-go-name: InstanceID + instance_name: + description: 实例name + type: string + x-go-name: InstanceName + is_del: + description: 是否删除0未删除 1已删除 + format: int8 + type: integer + x-go-name: IsDel + is_recover: + format: int8 + type: integer + x-go-name: IsRecover + license_end_time: + description: 结束时间, 许可证到期消息专属字段 + format: int64 + type: integer + x-go-name: LienseEndTime + license_name: + description: 版本名称, 许可证到期消息专属字段 + type: string + x-go-name: LicenseName + license_number: + description: 版本号, 许可证到期消息专属字段 + type: string + x-go-name: LicenseNumber + license_start_time: + description: 开始时间, 许可证到期消息专属字段 + format: int64 + type: integer + x-go-name: LienseStartTime + logid: + description: 系统原始日志id, 带外故障消息专属字段 + type: string + x-go-name: LogID + message_id: + description: message uuid + type: string + x-go-name: MessageID + message_sub_type: + description: 消息子类型 + type: string + x-go-name: MessageSubType + message_type: + description: 消息类型 + type: string + x-go-name: MessageType + project_id: + type: string + x-go-name: ProjectID + project_name: + type: string + x-go-name: ProjectName + resource_type: + description: 资源类型 实例/设备 + type: string + x-go-name: ResourceType + result: + description: 操作结果 fail/succ + type: string + x-go-name: Result + rule_id: + description: inbond rule uuid + type: string + x-go-name: RuleID + rule_name: + description: inbond rule name + type: string + x-go-name: RuleName + sn: + description: 设备sn + type: string + x-go-name: SN + user_id: + description: user_id + type: string + x-go-name: UserID + user_name: + description: user_name + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + MessageList: + properties: + messages: + items: + $ref: '#/definitions/Message' + type: array + x-go-name: Messages + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + MessageStatistic: + properties: + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + unreadCount: + format: int64 + type: integer + x-go-name: UnreadCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + MessageTypesResp: + additionalProperties: + items: + type: string + type: array + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + MessageWithNextPrev: + properties: + message: + $ref: '#/definitions/Message' + nextMessageId: + type: string + x-go-name: NextMessageId + prevMessageId: + type: string + x-go-name: PrevMessageId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ModifyApikeyRequest: + properties: + name: + description: 秘钥对名称 + type: string + x-go-name: Name + readOnly: + description: 是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法 + format: int8 + type: integer + x-go-name: ReadOnly + required: + - name + - readOnly + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyInstanceRequest: + properties: + description: + description: 描述 + type: string + x-go-name: Description + x-nullable: true + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyInstancesRequest: + description: 批量修改实例名称 + properties: + instance_ids: + description: 实例id列表 + items: + type: string + type: array + x-go-name: InstanceIDs + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyLocalUserRequest: + properties: + defaultProjectId: + description: 用户默认项目uuid + type: string + x-go-name: DefaultProjectID + x-nullable: true + email: + description: 邮箱 + type: string + x-go-name: Email + x-nullable: true + language: + description: 语言[en_US, zh_CN] + type: string + x-go-name: Language + x-nullable: true + phoneNumber: + description: 手机号 + type: string + x-go-name: PhoneNumber + x-nullable: true + phonePrefix: + description: 国家地区码,如86 + type: string + x-go-name: PhonePrefix + x-nullable: true + timezone: + description: 时区 Asia/Shanghai + type: string + x-go-name: Timezone + x-nullable: true + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyProjectDescriptionRequest: + properties: + description: + description: 项目描述 + type: string + x-go-name: Description + required: + - description + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyProjectRequest: + properties: + projectName: + description: 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + type: string + x-go-name: ProjectName + required: + - projectName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifySshkeyRequest: + properties: + name: + description: 秘钥名称 + type: string + x-go-name: Name + x-nullable: true + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyUserPasswordRequest: + properties: + oldPassword: + description: 旧密码,明文 + type: string + x-go-name: OldPassword + password: + description: 新密码 明文,密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + type: string + x-go-name: Password + required: + - oldPassword + - password + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyUserRequest: + properties: + description: + description: 描述 + type: string + x-go-name: Description + x-nullable: true + email: + description: 邮箱 + type: string + x-go-name: Email + x-nullable: true + phoneNumber: + description: 手机号 + type: string + x-go-name: PhoneNumber + x-nullable: true + phonePrefix: + description: 国家地区码,如86 + type: string + x-go-name: PhonePrefix + x-nullable: true + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + MonitorDataItem: + properties: + timestamp: + format: int64 + type: integer + x-go-name: Timestamp + value: + type: string + x-go-name: Value + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + MonitorDataQuery: + properties: + endTime: + format: int64 + type: integer + x-go-name: EndTime + func: + additionalProperties: + format: int64 + type: integer + description: 跟赛迪约定,转换单位放这里实现 + type: object + x-go-name: Func + labels: + additionalProperties: + type: string + description: metric都放这里了 + type: object + x-go-name: Labels + sampleMethod: + description: |- + MetricName string `json:"metricName"` + [rate, increase] + type: string + x-go-name: SampleMethod + startTime: + format: int64 + type: integer + x-go-name: StartTime + step: + format: int64 + type: integer + x-go-name: Step + tableName: + description: '[bmp_monitor_counter bmp_monitor_gauge]' + type: string + x-go-name: TableName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + MoveInstancesRequest: + properties: + instanceIDs: + description: instanceIDs + type: string + x-go-name: InstanceIDs + moverID: + description: to user_id + type: string + x-go-name: MoverID + moverProjectID: + description: to project_id + type: string + x-go-name: MoverProjectID + ownerID: + description: from user_id + type: string + x-go-name: OwnerID + ownerProjectID: + description: from project_id + type: string + x-go-name: OwnerProjectID + required: + - instanceIDs + - ownerProjectID + - moverProjectID + - ownerID + - moverID + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + MoveProjectRequest: + properties: + moverID: + description: to user_id + type: string + x-go-name: MoverID + ownerID: + description: from user_id + type: string + x-go-name: OwnerID + required: + - ownerID + - moverID + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + Os: + properties: + architecture: + description: 架构:x86/x64/i386/ + type: string + x-go-name: Architecture + bits: + description: 指令宽度:64/32位 + format: int64 + type: integer + x-go-name: Bits + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + deletedTime: + description: 删除时间 + type: string + x-go-name: DeletedTime + id: + description: ID + format: uint64 + type: integer + x-go-name: ID + isDel: + description: 是否删除0未删除 1已删除 + format: int8 + type: integer + x-go-name: IsDel + osId: + description: 操作系统uuid + type: string + x-go-name: OsID + osName: + description: 操作系统名称 + type: string + x-go-name: OsName + osType: + description: 操作系统分类:linux/windows + type: string + x-go-name: OsType + osVersion: + description: 操作系统版本 + type: string + x-go-name: OsVersion + sysUser: + description: 管理员账户 + type: string + x-go-name: SysUser + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + OsInfo: + properties: + os: + $ref: '#/definitions/Os' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + OsList: + properties: + oss: + description: 操作系统列表 + items: + $ref: '#/definitions/Os' + type: array + x-go-name: Oss + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Partition: + description: |- + 镜像默认分区 + [{"format":"swap","point":"swap","size":10240},{"format":"xfs","point":"/","size":51200}] + properties: + format: + description: format,如[swap, xfs] + type: string + x-go-name: FsType + point: + description: point,如[swap, /, /var] + type: string + x-go-name: MountPoint + size: + description: 分区大小, MB为单位 + format: int64 + type: integer + x-go-name: Size + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Project: + properties: + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + description: + description: 项目描述,新增 + type: string + x-go-name: Description + instanceCount: + description: 项目下实例数量 + format: int64 + type: integer + x-go-name: InstanceCount + owned: + description: 此项目的共享标志位,1为拥有,2为共享 + format: int64 + type: integer + x-go-name: Owned + ownedBy: + description: 拥有者 + type: string + x-go-name: OwnedBy + projectId: + description: 项目uuid + type: string + x-go-name: ProjectID + projectName: + description: 项目名称 + type: string + x-go-name: ProjectName + shareProjects: + description: 共享 + items: + $ref: '#/definitions/ShareProject' + type: array + x-go-name: ShareProjects + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ProjectId: + properties: + projectId: + description: 项目uuid + type: string + x-go-name: ProjectId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ProjectInfo: + properties: + project: + $ref: '#/definitions/Project' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ProjectList: + properties: + pageNumber: + description: 页数 + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + description: 页大小 + format: int64 + type: integer + x-go-name: PageSize + projects: + description: 项目实体列表 + items: + $ref: '#/definitions/Project' + type: array + x-go-name: Projects + totalCount: + description: 总条数 + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + QueryDeviceTypeImagePartitionResponse: + properties: + dataPartition: + description: 数据盘分区列表 + items: + $ref: '#/definitions/Partition' + type: array + x-go-name: DataPartition + systemPartition: + description: 系统盘分区列表 + items: + $ref: '#/definitions/Partition' + type: array + x-go-name: SystemPartition + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + RVolumeRaid: + description: Volume RAID 关联关系表 + properties: + createdBy: + type: string + x-go-name: CreatedBy + createdTime: + format: int64 + type: integer + x-go-name: CreatedTime + deletedTime: + format: int64 + type: integer + x-go-name: DeletedTime + deviceTypeId: + type: string + x-go-name: DeviceTypeID + isDel: + format: int8 + type: integer + x-go-name: IsDel + raidCan: + type: string + x-go-name: RaidCan + raidId: + type: string + x-go-name: RaidID + raidName: + type: string + x-go-name: RaidName + updatedBy: + type: string + x-go-name: UpdatedBy + updatedTime: + format: int64 + type: integer + x-go-name: UpdatedTime + volumeId: + type: string + x-go-name: VolumeID + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/dao/rVolumeRaidDao + Raid: + description: Raid raid + properties: + createdBy: + type: string + x-go-name: CreatedBy + createdTime: + format: int64 + type: integer + x-go-name: CreatedTime + deletedTime: + format: int64 + type: integer + x-go-name: DeletedTime + descriptionEn: + type: string + x-go-name: DescriptionEn + descriptionZh: + type: string + x-go-name: DescriptionZh + isDel: + format: int8 + type: integer + x-go-name: IsDel + name: + type: string + x-go-name: Name + raidId: + type: string + x-go-name: RaidID + updatedBy: + type: string + x-go-name: UpdatedBy + updatedTime: + format: int64 + type: integer + x-go-name: UpdatedTime + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/dao/raidDao + ReadMessagesRequest: + properties: + messageIds: + items: + type: string + type: array + x-go-name: MessageIds + required: + - messageIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ReinstallInstanceRequest: + properties: + bootMode: + description: 引导模式 [UEFI Legacy/BIOS] + type: string + x-go-name: BootMode + dataPartition: + description: 数据盘分区 + items: + $ref: '#/definitions/Partition' + type: array + x-go-name: DataPartition + description: + description: 描述 + type: string + x-go-name: Description + hostname: + description: 主机名称 + type: string + x-go-name: HostName + imageId: + description: 镜像ID + type: string + x-go-name: ImageID + installBmpAgent: + description: 是否安装bmp-agent + type: boolean + x-go-name: InstallBmpAgent + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + password: + description: 密码 + type: string + x-go-name: Password + sshKeyId: + description: 秘钥ID + type: string + x-go-name: SshKeyID + systemPartition: + description: 系统盘分区 + items: + $ref: '#/definitions/Partition' + type: array + x-go-name: SystemPartition + systemVolumeRaidId: + description: 系统盘RAID ID + type: string + x-go-name: SystemVolumeRaidID + required: + - imageId + - systemVolumeRaidId + - instanceName + - bootMode + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ResetInstancePasswdRequest: + description: 重置实例密码 + properties: + password: + description: 新密码 + type: string + x-go-name: Password + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ResetInstancesPasswdRequest: + description: 批量重置实例密码 + properties: + instance_ids: + description: 实例id列表 + items: + type: string + type: array + x-go-name: InstanceIDs + password: + description: 新密码 + type: string + x-go-name: Password + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + RestartInstancesRequest: + properties: + instanceIds: + items: + type: string + type: array + x-go-name: InstanceIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + Role: + properties: + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + descriptionCn: + description: description + type: string + x-go-name: DescriptionCn + descriptionEn: + description: 权限描述 + type: string + x-go-name: DescriptionEn + permission: + description: 权限 + type: string + x-go-name: Permission + roleId: + description: 角色uuid + type: string + x-go-name: RoleID + roleName: + description: 角色名称 + type: string + x-go-name: RoleName + roleNameCn: + description: 角色名称,唯一 + type: string + x-go-name: RoleNameCn + roleNameEn: + description: 角色名称,唯一 + type: string + x-go-name: RoleNameEn + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + userCount: + description: 用户数 + format: int64 + type: integer + x-go-name: UserCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + RoleInfo: + properties: + role: + $ref: '#/definitions/Role' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + RoleList: + properties: + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + roles: + description: 角色实体列表 + items: + $ref: '#/definitions/Role' + type: array + x-go-name: Roles + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Rule: + properties: + deviceTag: + description: 盘符、挂载点、网口列表 + type: string + x-go-name: DeviceTag + dimension: + description: 维度 [instance、disk、mountpoint、nic] + type: string + x-go-name: Dimension + dimensionName: + description: 维度名称 [实例、盘符、挂载点、网卡] + type: string + x-go-name: DimensionName + instanceCount: + description: 关联的实例个数 + format: int64 + type: integer + x-go-name: InstanceCount + instanceIds: + description: 实例id列表 + items: + type: string + type: array + x-go-name: InstanceIds + instances: + description: 实例详细信息 + items: + $ref: '#/definitions/Instance' + type: array + x-go-name: Instances + noticeOption: + $ref: '#/definitions/RuleNotice' + relatedResourceCount: + description: 此规则关联的资源数 + format: int64 + type: integer + x-go-name: RelatedResourceCount + resource: + description: 资源类型,目前只支持instance + type: string + x-go-name: Resource + resourceName: + description: 资源类型名称 实例 + type: string + x-go-name: ResourceName + ruleId: + description: 规则uuid + type: string + x-go-name: RuleID + ruleName: + description: 规则名称 + type: string + x-go-name: RuleName + status: + description: 状态 [1启用 2不启用 3告警] + format: int64 + type: integer + x-go-name: Status + statusName: + description: 规则状态名称 + type: string + x-go-name: StatusName + triggerDescription: + description: 触发条件描述 + items: + type: string + type: array + x-go-name: TriggerDescription + triggerOption: + description: 触发条件 + items: + $ref: '#/definitions/RuleTrigger' + type: array + x-go-name: TriggerOption + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + RuleList: + properties: + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + rules: + description: rules数组 + items: + $ref: '#/definitions/Rule' + type: array + x-go-name: Rules + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + RuleNotice: + description: 通知策略 + properties: + effectiveIntervalEnd: + description: 有效时段结束时间 ["23:59:59"] + type: string + x-go-name: EffectiveIntervalEnd + effectiveIntervalStart: + description: 有效时段开始时间 ["00:00:00"] + type: string + x-go-name: EffectiveIntervalStart + noticeCondition: + description: 通知条件,可多选 [1表示报警, 2表示恢复正常] + items: + format: int64 + type: integer + type: array + x-go-name: NoticeCondition + noticePeriod: + description: 通知周期(分钟) [5 10 15 30 60 180 360 720 1440] + format: int64 + type: integer + x-go-name: NoticePeriod + noticeWay: + description: 接收渠道,可多选 [1表示站内信, 2表示邮件] + items: + format: int64 + type: integer + type: array + x-go-name: NoticeWay + userId: + description: 通知对象用户Id + type: string + x-go-name: UserID + userName: + description: 通知对象用户 + type: string + x-go-name: UserName + required: + - noticePeriod + - effectiveIntervalStart + - effectiveIntervalEnd + - noticeCondition + - noticeWay + - userId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + RuleTrigger: + description: 单个触发条件 + properties: + calculation: + description: 计算方式 [min max avg sum] + type: string + x-go-name: Calculation + calculationUnit: + description: 计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出] + type: string + x-go-name: CalculationUnit + description: + description: 对此rule的描述 + type: string + x-go-name: Description + metric: + description: 监控指标 cps.cpu.util + type: string + x-go-name: Metric + metricName: + description: 监控指标名称 CPU使用率 + type: string + x-go-name: MetricName + noticeLevel: + description: 告警级别 [1表示一般,2表示严重,3表示紧急] + format: int64 + type: integer + x-go-name: NoticeLevel + operation: + description: 比较方式 [> >= < <= == !=]或者[gt gte lt lte eq neq] + type: string + x-go-name: Operation + period: + description: 周期 5(分钟) + format: int64 + type: integer + x-go-name: Period + tableName: + description: '[bmp_monitor_counter, bmp_monitor_gauge]' + type: string + x-go-name: TableName + threshold: + description: 阈值 + format: double + type: number + x-go-name: Threshold + times: + description: 持续周期数 [1, 2, 3, 5, 10, 15, 30, 60] + format: int64 + type: integer + x-go-name: Times + required: + - metric + - period + - calculation + - operation + - threshold + - times + - noticeLevel + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ShareProject: + properties: + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + ownerUserId: + description: 项目拥有者用户id + type: string + x-go-name: OwnerUserID + ownerUserName: + description: 项目拥有者用户名 + type: string + x-go-name: OwnerUserName + projectId: + description: 项目uuid + type: string + x-go-name: ProjectID + projectName: + description: 项目名称 + type: string + x-go-name: ProjectName + sharedInstanceIds: + type: string + x-go-name: SharedInstanceIDs + sharedUserId: + description: 项目共享者用户id + type: string + x-go-name: SharedUserID + sharedUserName: + description: 项目拥有者用户名 + type: string + x-go-name: SharedUserName + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ShareProjectInfo: + properties: + projectId: + description: 项目实体 + type: string + x-go-name: ProjectID + shares: + items: + $ref: '#/definitions/SharingProject' + type: array + x-go-name: Shares + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ShareProjectRequest: + properties: + instanceIDs: + description: 如果部分分享,instance_id逗号分隔; 如果全部分享,传all + type: string + x-go-name: InstanceIDs + ownerID: + description: from user_id + type: string + x-go-name: OwnerID + sharerID: + description: to user_id + type: string + x-go-name: SharerID + required: + - ownerID + - sharerID + - instanceIDs + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + SharingProject: + description: SharingProject 共享项目 + properties: + created_by: + type: string + x-go-name: CreatedBy + created_time: + format: int64 + type: integer + x-go-name: CreatedTime + deleted_time: + format: int64 + type: integer + x-go-name: DeletedTime + is_default: + format: int8 + type: integer + x-go-name: IsDefault + is_del: + format: int8 + type: integer + x-go-name: IsDel + owner_user_id: + type: string + x-go-name: OwnerUserID + owner_user_name: + type: string + x-go-name: OwnerUserName + premission: + type: string + x-go-name: Premission + project_id: + type: string + x-go-name: ProjectID + project_name: + type: string + x-go-name: ProjectName + shared_instance_ids: + type: string + x-go-name: SharedInstanceIDs + shared_user_id: + type: string + x-go-name: SharedUserID + shared_user_name: + type: string + x-go-name: SharedUserName + updated_by: + type: string + x-go-name: UpdatedBy + updated_time: + format: int64 + type: integer + x-go-name: UpdatedTime + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/dao/sharingProjectDao + Sshkey: + properties: + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + fingerPrint: + description: 公钥指纹 + type: string + x-go-name: FingerPrint + id: + description: id + format: int64 + type: integer + x-go-name: Id + key: + description: 公钥,格式:ssh-rsa AAA + type: string + x-go-name: Key + name: + description: 秘钥名称 + type: string + x-go-name: Name + sshkeyId: + description: 秘钥uuid + type: string + x-go-name: SshkeyId + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + userId: + description: 所属用户uuid + type: string + x-go-name: UserId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + SshkeyId: + properties: + sshkeyId: + description: sshkey uuid + type: string + x-go-name: SshkeyId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + SshkeyInfo: + properties: + sshkey: + $ref: '#/definitions/Sshkey' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + SshkeyList: + properties: + pageNumber: + description: 页数 + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + description: 页大小 + format: int64 + type: integer + x-go-name: PageSize + sshkeys: + description: sshkey实体列表 + items: + $ref: '#/definitions/Sshkey' + type: array + x-go-name: Sshkeys + totalCount: + description: 总条数 + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + StartInstancesRequest: + properties: + instanceIds: + items: + type: string + type: array + x-go-name: InstanceIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + StopInstancesRequest: + properties: + instanceIds: + items: + type: string + type: array + x-go-name: InstanceIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + TagsResponse: + properties: + tags: + items: + type: string + type: array + x-go-name: Tags + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + User: + properties: + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + defaultProjectId: + description: 用户默认项目uuid + type: string + x-go-name: DefaultProjectID + defaultProjectName: + description: 用户默认项目名称 + type: string + x-go-name: DefaultProjectName + description: + description: 描述 + type: string + x-go-name: Description + email: + description: 邮箱 + type: string + x-go-name: Email + id: + description: 用户id + format: int64 + type: integer + x-go-name: ID + language: + description: 默认语言(en_US/zh_CN) + type: string + x-go-name: Language + phoneNumber: + description: 手机号 + type: string + x-go-name: PhoneNumber + phonePrefix: + description: 国家地区码,如86 + type: string + x-go-name: PhonePrefix + roleId: + description: 角色uuid + type: string + x-go-name: RoleID + roleName: + description: 角色名称 + type: string + x-go-name: RoleName + timezone: + description: 时区 + type: string + x-go-name: Timezone + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + userId: + description: 用户uuid + type: string + x-go-name: UserID + userName: + description: 用户名,唯一 + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + UserInfo: + properties: + user: + $ref: '#/definitions/User' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + UserList: + properties: + pageNumber: + description: 页数 + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + description: 页大小 + format: int64 + type: integer + x-go-name: PageSize + totalCount: + description: 总条数 + format: int64 + type: integer + x-go-name: TotalCount + users: + description: user实体列表 + items: + $ref: '#/definitions/User' + type: array + x-go-name: Users + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + VerifyUserRequest: + properties: + password: + description: 密码 + type: string + x-go-name: Password + roleId: + description: 角色uuid + type: string + x-go-name: RoleID + userName: + description: 用户名,唯一 + type: string + x-go-name: UserName + required: + - userName + - password + - roleId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + Volume: + description: Volume 卷管理表 + properties: + createdBy: + description: |- + RaidCan string `gorm:"column:raid_can" json:"raidCan"` // RAID配置: (RAID,NO RAID) + Raid string `gorm:"column:raid" json:"raid"` // RAID模式:RAID1,RIAD10等 + type: string + x-go-name: CreatedBy + createdTime: + format: int64 + type: integer + x-go-name: CreatedTime + deletedTime: + format: int64 + type: integer + x-go-name: DeletedTime + deviceTypeId: + description: 设备类型uuid + type: string + x-go-name: DeviceTypeID + diskType: + description: 硬盘类型(SSD,HDD) + type: string + x-go-name: DiskType + interfaceType: + description: 接口类型(SATA,SAS,NVME,不限制) + type: string + x-go-name: InterfaceType + isDel: + format: int8 + type: integer + x-go-name: IsDel + updatedBy: + type: string + x-go-name: UpdatedBy + updatedTime: + format: int64 + type: integer + x-go-name: UpdatedTime + volumeAmount: + description: 硬盘数量(最低块数) + format: int64 + type: integer + x-go-name: VolumeAmount + volumeId: + description: 卷uuid + type: string + x-go-name: VolumeID + volumeName: + description: 卷名称 + type: string + x-go-name: VolumeName + volumeSize: + description: 单盘大小(最小容量) + type: string + x-go-name: VolumeSize + volumeType: + description: 卷类型:系统卷,数据卷 + type: string + x-go-name: VolumeType + volumeUnit: + description: 硬盘单位(GB,TB) + type: string + x-go-name: VolumeUnit + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/dao/volumeDao + VolumeRaID: + properties: + raidCan: + type: string + x-go-name: RaidCan + raidId: + description: raid uuid + type: string + x-go-name: RaidID + volumeId: + description: 卷 uuid + type: string + x-go-name: VolumeID + volumeType: + description: system|data + type: string + x-go-name: VolumeType + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + VolumeRaids: + properties: + createdBy: + description: |- + RaidCan string `gorm:"column:raid_can" json:"raidCan"` // RAID配置: (RAID,NO RAID) + Raid string `gorm:"column:raid" json:"raid"` // RAID模式:RAID1,RIAD10等 + type: string + x-go-name: CreatedBy + createdTime: + format: int64 + type: integer + x-go-name: CreatedTime + deletedTime: + format: int64 + type: integer + x-go-name: DeletedTime + deviceTypeId: + description: 设备类型uuid + type: string + x-go-name: DeviceTypeID + diskType: + description: 硬盘类型(SSD,HDD) + type: string + x-go-name: DiskType + interfaceType: + description: 接口类型(SATA,SAS,NVME,不限制) + type: string + x-go-name: InterfaceType + isDel: + format: int8 + type: integer + x-go-name: IsDel + raids: + items: + $ref: '#/definitions/RVolumeRaid' + type: array + x-go-name: Raids + updatedBy: + type: string + x-go-name: UpdatedBy + updatedTime: + format: int64 + type: integer + x-go-name: UpdatedTime + volumeAmount: + description: 硬盘数量(最低块数) + format: int64 + type: integer + x-go-name: VolumeAmount + volumeId: + description: 卷uuid + type: string + x-go-name: VolumeID + volumeName: + description: 卷名称 + type: string + x-go-name: VolumeName + volumeSize: + description: 单盘大小(最小容量) + type: string + x-go-name: VolumeSize + volumeType: + description: 卷类型:系统卷,数据卷 + type: string + x-go-name: VolumeType + volumeUnit: + description: 硬盘单位(GB,TB) + type: string + x-go-name: VolumeUnit + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response +host: bmp-openapi-console.bmp.local +info: + contact: + email: minping@jd.com + description: |- + the purpose of this application is to provide an application + that is using plain go code to define an API + + This should demonstrate all the possible comment annotations + that are available to turn go code into a fully compliant swagger 2.0 spec + license: + name: MIT + url: http://opensource.org/licenses/MIT + termsOfService: there are no TOS at this moment, use at your own risk we take no responsibility + title: CPS + version: 0.0.1 +paths: + /auditLogs: + get: + description: DescribeAuditLogs 获取审计日志列表 + operationId: describeAuditLogs + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: instance_id + in: query + name: instance_id + type: string + x-go-name: InstanceID + - description: 操作名称 + in: query + name: operation + type: string + x-go-name: Operation + - description: 操作人 + in: query + name: username + type: string + x-go-name: UserName + - description: result + in: query + name: result + type: string + x-go-name: Result + - description: 操作时间下限 + format: int64 + in: query + name: startTime + type: integer + x-go-name: StartTime + - description: 操作时间上限 + format: int64 + in: query + name: endTime + type: integer + x-go-name: EndTime + - description: 是否显示所有 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeAuditLogs' + default: + $ref: '#/responses/ErrorResponse' + tags: + - auditLog + /auditLogs/types: + get: + description: DescribeAuditLogTypes 获取审计日志类型 + operationId: describeAuditLogTypes + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/describeAuditLogTypes' + default: + $ref: '#/responses/ErrorResponse' + tags: + - auditLog + /deviceTypes: + get: + description: DescribeDeviceTypes 获取机型列表 + operationId: describeDeviceTypes + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 机型id + in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - description: 机型规格 + in: query + name: deviceType + type: string + x-go-name: DeviceType + - description: 机房id + in: query + name: idcId + type: string + x-go-name: IdcID + - description: 机型名称 + in: query + name: name + type: string + x-go-name: Name + - description: 机型类型 + in: query + name: deviceSeries + type: string + x-go-name: DeviceSeries + - in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeDeviceTypes' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/{device_type_id}: + get: + description: DescribeDeviceType 获取机型详情 + operationId: describeDeviceType + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: device_type_id + required: true + type: string + x-go-name: DeviceTypeID + responses: + "200": + $ref: '#/responses/describeDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/deviceTypeImage: + get: + description: QueryDeviceTypeImage 根据机型获取镜像 + operationId: describeDeviceTypeImages + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 机型id + in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - description: 镜像id + in: query + name: imageId + type: string + x-go-name: ImageID + - description: 体系架构 + in: query + name: architecture + type: string + x-go-name: Architecture + - description: 操作系统平台 + in: query + name: osType + type: string + x-go-name: OsType + - description: 镜像名称 + in: query + name: imageName + type: string + x-go-name: ImageName + - description: 版本号 + in: query + name: version + type: string + x-go-name: Version + - description: 操作系统ID + in: query + name: osId + type: string + x-go-name: OsID + - description: 镜像类型,预置,自定义 + in: query + name: source + type: string + x-go-name: Source + - description: 是否显示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeDeviceTypeImages' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/deviceTypeImagePartition: + get: + description: QueryDeviceTypeImagePartition 根据机型,镜像,获取分区 + operationId: describeDeviceTypeImagePartitions + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 机型id + in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - description: 镜像id + in: query + name: imageId + type: string + x-go-name: ImageID + - description: 是否显示所有,isAll=1显示所有 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeDeviceTypeImagePartitions' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/volumesRaids: + get: + description: DescribeVolumesRaids 根据机型获取卷和raid信息 (deviceTypeRaid->volumesRaids) + operationId: describeVolumesRaids + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 机型id + in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - description: 系统盘还是数据盘 + in: query + name: volumeType + type: string + x-go-name: VolumeType + - description: 是否显示所有 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeVolumesRaids' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /devices: + get: + description: DescribeDevices 获取设备列表 + operationId: describeDevices + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 机房id + in: query + name: idcId + type: string + x-go-name: IDcID + - description: 设备sn + in: query + name: sn + type: string + x-go-name: Sn + - description: 实例id + in: query + name: instanceId + type: string + x-go-name: InstanceID + - description: 机型id + in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - description: 设备管理状态 + in: query + name: manageStatus + type: string + x-go-name: ManageStatus + - description: 带外ip + in: query + name: iloIp + type: string + x-go-name: IloIP + - description: ipv4 + in: query + name: ipv4 + type: string + x-go-name: IPV4 + - description: ipv6 + in: query + name: ipv6 + type: string + x-go-name: IPV6 + - description: 机型类型 + in: query + name: deviceSeries + type: string + x-go-name: DeviceSeries + - description: 所属用户id + in: query + name: userId + type: string + x-go-name: UserID + - description: 所属用户 + in: query + name: userName + type: string + x-go-name: UserName + - description: 是否显示全部,1不分页 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeDevices' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/{device_id}: + get: + description: DescribeDevice 获取设备详情 + operationId: describeDevice + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: device_id + required: true + type: string + x-go-name: DeviceID + responses: + "200": + $ref: '#/responses/describeDevice' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/stock: + delete: + description: DescribeDeviceStock 获取指定机型的设备库存 + operationId: describeDeviceStock + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + responses: + "200": + $ref: '#/responses/describeDeviceStock' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /idcs: + get: + description: DescribeIdcs 获取idc列表 + operationId: describeIdcs + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 机房名称 + in: query + name: name + type: string + x-go-name: Name + - description: 机房英文名称 + in: query + name: nameEn + type: string + x-go-name: NameEn + - description: 机房等级 + in: query + name: level + type: string + x-go-name: Level + - description: 是否显示所有 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeIdcs' + default: + $ref: '#/responses/ErrorResponse' + tags: + - idc + /idcs/{idc_id}: + get: + description: DescribeIdc 获取idc详情 + operationId: describeIdc + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: idc_id + required: true + type: string + x-go-name: IdcID + responses: + "200": + $ref: '#/responses/describeIdc' + default: + $ref: '#/responses/ErrorResponse' + tags: + - idc + /images: + get: + description: DescribeImages 获取镜像列表 + operationId: describeImages + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 镜像ID + in: query + name: imageId + type: string + x-go-name: ImageID + - description: 镜像名称 + in: query + name: imageName + type: string + x-go-name: ImageName + - description: 设备类型id + in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - description: 版本号 + in: query + name: version + type: string + x-go-name: Version + - description: 操作系统ID + in: query + name: osId + type: string + x-go-name: OsID + - description: 镜像ID,数组,支持多个 + in: query + items: + type: string + name: imageIds + type: array + x-go-name: ImageIDs + - description: 镜像类型,预置,自定义 + in: query + name: source + type: string + x-go-name: Source + - description: 体系架构 + in: query + name: architecture + type: string + x-go-name: Architecture + - description: 操作系统平台 + in: query + name: osType + type: string + x-go-name: OsType + - description: 是否显示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeImages' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + /images/{image_id}: + get: + description: DescribeImage 获取镜像详情 + operationId: describeImage + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: image_id + required: true + type: string + x-go-name: ImageID + responses: + "200": + $ref: '#/responses/describeImage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + /images/imageDeviceTypes: + get: + description: DescribeImageDeviceTypes 查看镜像绑定的机型 + operationId: describeImageDeviceTypes + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 镜像ID + in: query + name: imageId + required: true + type: string + x-go-name: ImageID + - description: 体系架构 + in: query + name: architecture + type: string + x-go-name: Architecture + - description: 镜像是否绑定了机型,0查询该镜像没有绑定的机型列表 1查询该镜像已经绑定了的机型列表 + in: query + name: isBind + type: string + x-go-name: IsBind + - description: 是否显示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeImageDeviceTypes' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + /license/content: + get: + description: DescribeLicenseContent 获取授权详情 + operationId: describeLicenseContent + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/describeLicenseContent' + default: + $ref: '#/responses/ErrorResponse' + tags: + - license + /local/users: + get: + description: DescribeLocalUser 控制台获取用户详情 + operationId: describeLocalUser + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/describeLocalUser' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + put: + description: ModifyLocalUser 控制台修改除密码外的个人信息 + operationId: modifyLocalUser + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyLocalUserRequest' + responses: + "200": + $ref: '#/responses/modifyLocalUser' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /local/users/password: + put: + description: ModifyLocalUserPassword 控制台修改个人密码 + operationId: modifyLocalUserPassword + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyUserPasswordRequest' + responses: + "200": + $ref: '#/responses/modifyLocalUserPassword' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /messages: + get: + description: GetMessageList 获取message列表(分页) + operationId: getMessageList + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 是否显示全部,取值为1时表示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + - description: 0:未读;1:已读;""不传表示全部 + in: query + name: hasRead + type: string + x-go-name: HasRead + - description: 消息类型 + in: query + name: messageType + type: string + x-go-name: MessageType + - description: 消息子类型 + in: query + name: messageSubType + type: string + x-go-name: MessageSubType + - description: 内容模糊搜索 + in: query + name: detail + type: string + x-go-name: Detail + responses: + "200": + $ref: '#/responses/getMessageList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/delete: + delete: + description: DeleteMessage 删除消息(可多条) + operationId: deleteMessage + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/DeleteMessagesRequest' + responses: + "200": + $ref: '#/responses/deleteMessage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/doRead: + put: + description: ReadMessage 将消息设置为已读(可多条) + operationId: readMessage + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/ReadMessagesRequest' + responses: + "200": + $ref: '#/responses/readMessage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/getMessageById: + get: + description: GetMessageById 获取消息详情,包括上一条/下一条的messageid + operationId: getMessageById + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: query + name: messageId + required: true + type: string + x-go-name: MessageID + responses: + "200": + $ref: '#/responses/getMessageById' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/getMessageTypes: + get: + description: GetMessageTypes 获取消息类型/子类型 + operationId: getMessageTypes + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/getMessageTypes' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/hasUnreadMessage: + get: + description: HasUnreadMessage 获取有没有未读消息 + operationId: hasUnreadMessage + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/hasUnreadMessage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/statistic: + get: + description: GetMessageStatistic 获取message总数和未读数 + operationId: getMessageStatistic + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/getMessageStatistic' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /monitorAlert/addAlert: + post: + description: AddAlert 添加(接收)告警 + operationId: addAlert + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/AddAlertRequest' + responses: + "200": + $ref: '#/responses/addAlert' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorAlert + /monitorAlert/deleteAlert: + delete: + description: DeleteAlert 删除告警 + operationId: deleteAlert + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/DeleteAlertRequest' + responses: + "200": + $ref: '#/responses/deleteAlert' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorAlert + /monitorAlert/describeAlert: + get: + description: DescribeAlert 告警详情 + operationId: describeAlert + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: rule uuid + in: query + name: alertId + required: true + type: string + x-go-name: AlertID + responses: + "200": + $ref: '#/responses/describeAlert' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorAlert + /monitorAlert/describeAlerts: + get: + description: DescribeAlerts 告警列表 + operationId: describeAlerts + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 是否显示全部,取值为1时表示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + - description: user uuid + in: query + name: userId + type: string + x-go-name: UserID + - description: username + in: query + name: userName + type: string + x-go-name: UserName + - description: 规则名称 + in: query + name: ruleName + type: string + x-go-name: RuleName + - description: 规则uuid + in: query + name: ruleId + type: string + x-go-name: RuleID + - description: 资源id,目前就是实例id + in: query + name: resourceId + type: string + x-go-name: ResourceID + - description: 报警时间筛选stime + format: int64 + in: query + name: startTime + type: integer + x-go-name: StartTime + - description: 报警时间筛选etime + format: int64 + in: query + name: endTime + type: integer + x-go-name: EndTime + - description: project uuid + in: query + name: projectId + type: string + x-go-name: ProjectID + responses: + "200": + $ref: '#/responses/describeAlerts' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorAlert + /monitorData: + get: + description: GetMonitorData 获取图表监控数据 + operationId: getMonitorData + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 指标名称,支持多个,用逗号隔离开 + in: query + name: metricName + type: string + x-go-name: MetricName + - description: 实例id + in: query + name: instanceId + type: string + x-go-name: InstanceID + - description: 标签值 + in: query + name: device + type: string + x-go-name: Device + - description: 开始时间戳 + format: int64 + in: query + name: startTime + type: integer + x-go-name: StartTime + - description: 结束时间戳 + format: int64 + in: query + name: endTime + type: integer + x-go-name: EndTime + - description: 间隔多久一个点 s为单位 + format: int64 + in: query + name: timeInterval + type: integer + x-go-name: TimeInterval + - description: 最近多少时间,小时为单位 + format: int64 + in: query + name: lastManyTime + type: integer + x-go-name: LastManyTime + - description: avg, min, max, sum + in: query + name: downSampleType + type: string + x-go-name: DownSampleType + responses: + "200": + $ref: '#/responses/getMonitorData' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorData + /monitorProxy/desrcibeAgentStatus: + get: + description: DesrcibeAgentStatus 获取agent状态 + operationId: desrcibeAgentStatus + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: InstanceId,多个用逗号分隔 + in: query + name: instanceId + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/desrcibeAgentStatus' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorProxy + /monitorProxy/desrcibeTags: + get: + description: DesrcibeAgentStatus 获取tag列表 + operationId: desrcibeTags + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: instanceId + in: query + name: instanceId + required: true + type: string + x-go-name: InstanceID + - description: tagName [disk mountpoint nic] + in: query + name: tagName + required: true + type: string + x-go-name: TagName + responses: + "200": + $ref: '#/responses/desrcibeTags' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorProxy + /monitorRule/addRule: + post: + description: AddRule 添加规则 + operationId: addRule + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/AddRuleRequest' + responses: + "200": + $ref: '#/responses/addRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/deleteRule: + delete: + description: DeleteRule 删除规则 + operationId: deleteRule + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/DeleteRuleRequest' + responses: + "200": + $ref: '#/responses/deleteRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/describeRule: + get: + description: DescribeRule 规则详情 + operationId: describeRule + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: rule uuid + in: query + name: ruleId + required: true + type: string + x-go-name: RuleID + responses: + "200": + $ref: '#/responses/describeRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/describeRules: + get: + description: DescribeRules 规则列表 + operationId: describeRules + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 是否显示全部,取值为1时表示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + - description: user uuid + in: query + name: userId + type: string + x-go-name: UserID + - description: username + in: query + name: userName + type: string + x-go-name: UserName + - description: 规则名称,模糊搜索 + in: query + name: ruleName + type: string + x-go-name: RuleName + - description: 规则uuid + in: query + name: ruleId + type: string + x-go-name: RuleID + - description: 规则状态[1->正常,2->禁用,3->报警] + format: int64 + in: query + name: status + type: integer + x-go-name: Status + - description: project uuid + in: query + name: projectId + type: string + x-go-name: ProjectID + responses: + "200": + $ref: '#/responses/describeRules' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/disableRule: + put: + description: DisableRule 禁用规则 + operationId: disableRule + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/DisableRuleRequest' + responses: + "200": + $ref: '#/responses/disableRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/editRule: + put: + description: EditRule 编辑规则 + operationId: editRule + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/EditRuleRequest' + responses: + "200": + $ref: '#/responses/editRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/enableRule: + put: + description: EnableRule 启用规则 + operationId: enableRule + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/EnableRuleRequest' + responses: + "200": + $ref: '#/responses/enableRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /oss: + get: + description: DescribeOSs 获取os列表(暂不启用) + operationId: describeOSs + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 操作系统名称 + in: query + name: osName + type: string + x-go-name: OsName + - description: 操作系统平台 + in: query + name: osType + type: string + x-go-name: OsType + - description: 操作系统版本 + in: query + name: osVersion + type: string + x-go-name: OsVersion + - description: 是否显示所有 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeOSs' + default: + $ref: '#/responses/ErrorResponse' + tags: + - os + /oss/{os_id}: + get: + description: DescribeOS 获取os系统详情(暂不启用) + operationId: describeOS + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: os_id + required: true + type: string + x-go-name: OsID + responses: + "200": + $ref: '#/responses/describeOS' + default: + $ref: '#/responses/ErrorResponse' + tags: + - os + /project/instances: + get: + description: DescribeProjectInstances 获取实例列表 + operationId: describeProjectInstances + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 实例ID + in: query + name: instanceId + type: string + x-go-name: InstanceID + - description: 实例名称,模糊搜索 + in: query + name: instanceName + type: string + x-go-name: InstanceName + - description: 设备类型ID + in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - description: 运行状态 + in: query + name: status + type: string + x-go-name: Status + - description: 设备ID + in: query + name: deviceId + type: string + x-go-name: DeviceID + - description: SN + in: query + name: sn + type: string + x-go-name: Sn + - description: 机房ID + in: query + name: idcId + type: string + x-go-name: IdcID + - description: 项目ID + in: query + name: projectId + type: string + x-go-name: ProjectID + - description: 带外ip,精确搜索 + in: query + name: ilo_ip + type: string + x-go-name: IloIP + - description: ipv4,精确搜索 + in: query + name: ipv4 + type: string + x-go-name: IPV4 + - description: ipv6,精确搜索 + in: query + name: ipv6 + type: string + x-go-name: IPV6 + - description: 是否显示全部,取值为1时表示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + - description: 是否安装了agent,"0"表示未安装,"1"表示已安装 + in: query + name: isInstallAgent + type: string + x-go-name: IsInstallAgent + responses: + "200": + $ref: '#/responses/describeProjectInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + post: + description: CreateProjectInstance 创建实例 + operationId: createProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateInstanceRequest' + responses: + "200": + $ref: '#/responses/createProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}: + delete: + description: DeleteProjectInstance 删除实例 + operationId: deleteProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/deleteProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + get: + description: DescribeProjectInstance 获取实例详情 + operationId: describeProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 实例uuid + in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/describeProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + put: + description: ModifyProjectInstance 修改实例信息 + operationId: modifyProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyInstanceRequest' + responses: + "200": + $ref: '#/responses/modifyProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/lock: + put: + description: LockProjectInstance 锁定实例 + operationId: lockProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/lockProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/reinstallInstance: + put: + description: ReinstallInstance 重装实例 + operationId: reinstallProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + - in: body + name: Body + schema: + $ref: '#/definitions/ReinstallInstanceRequest' + responses: + "200": + $ref: '#/responses/reinstallProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/resetStatus: + put: + description: ResetInstanceStatus 重置实例状态 + operationId: resetInstanceStatus + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/resetInstanceStatus' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/resetpasswd: + put: + description: ResetPasswd 重置密码 + operationId: resetProjectInstancePasswd + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + - in: body + name: Body + schema: + $ref: '#/definitions/ResetInstancePasswdRequest' + responses: + "200": + $ref: '#/responses/resetProjectInstancePasswd' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/restart: + put: + description: RestartProjectInstance 实例重启 + operationId: restartProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/restartProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/start: + put: + description: StartProjectInstance 实例开机 + operationId: startProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/startProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/stop: + put: + description: StopProjectInstance 实例关机 + operationId: stopProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/stopProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/unlock: + put: + description: UnLockProjectInstance 解锁实例 + operationId: unLockProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/unLockProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/batch/instances:deleteInstances: + delete: + description: DeleteInstances 批量删除实例 + operationId: deleteInstances + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/DeleteInstancesRequest' + responses: + "200": + $ref: '#/responses/deleteInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/batch/instances:modifyInstances: + put: + description: ModifyInstances 批量修改实例名称 + operationId: modifyInstances + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyInstancesRequest' + responses: + "200": + $ref: '#/responses/modifyInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/batch/instances:resetPasswd: + put: + description: ResetInstancesPasswd 批量重置密码 + operationId: resetProjectInstancesPasswd + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/ResetInstancesPasswdRequest' + responses: + "200": + $ref: '#/responses/resetProjectInstancesPasswd' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/batch/instances:restartInstances: + put: + description: StartInstances 批量重启 + operationId: restartInstances + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/RestartInstancesRequest' + responses: + "200": + $ref: '#/responses/restartInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/batch/instances:startInstances: + put: + description: StartInstances 批量开机 + operationId: startInstances + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/StartInstancesRequest' + responses: + "200": + $ref: '#/responses/startInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/batch/instances:stopInstances: + put: + description: StartInstances 批量关机 + operationId: stopInstances + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/StopInstancesRequest' + responses: + "200": + $ref: '#/responses/stopInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/share/describeInstances: + get: + description: DescribeInstancesByProjectIdAndOwnerNameAndSharerName 根据projectid,ownername,username来获取实例列表。为了支持部分资源转移中的实例列表 + operationId: describeInstancesByProjectIdAndOwnerNameAndSharerName + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 项目ID + in: query + name: projectId + type: string + x-go-name: ProjectID + - in: query + name: isAll + type: string + x-go-name: IsAll + - in: query + name: ownerName + type: string + x-go-name: OwnerName + - in: query + name: sharerName + type: string + x-go-name: SharerName + - description: 这两项支持模糊搜索 + in: query + name: instanceName + type: string + x-go-name: InstanceName + - in: query + name: instanceId + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/describeInstancesByProjectIdAndOwnerNameAndSharerName' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /resources: + get: + description: DescribeResources 根据某个字段值精确查询对应的资源列表(如根据imageName查询镜像列表,根据idcName查询机房列表) + operationId: describeResources + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: |- + 机房名称 + IdcName string `json:"idcName"` + 机房英文名称 + IdcNameEn string `json:"idcNameEn"`*/ + 机型名称 + in: query + name: name + type: string + x-go-name: Name + - description: 机型规格 + in: query + name: deviceType + type: string + x-go-name: DeviceType + - description: 镜像名称 + in: query + name: imageName + type: string + x-go-name: ImageName + - description: 用户名称 + in: query + name: userName + type: string + x-go-name: UserName + responses: + "200": + $ref: '#/responses/describeResources' + default: + $ref: '#/responses/ErrorResponse' + tags: + - resource + /roles: + get: + description: DescribeRoles 获取角色列表 + operationId: describeRoles + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 是否显示所有 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeRoles' + default: + $ref: '#/responses/ErrorResponse' + tags: + - role + /roles/{role_id}: + get: + description: DescribeRole 获取角色详情 + operationId: describeRole + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: role_id + required: true + type: string + x-go-name: RoleID + responses: + "200": + $ref: '#/responses/describeRole' + default: + $ref: '#/responses/ErrorResponse' + tags: + - role + /roles/roleInfo/current: + get: + description: CurrentRole 获取当前登录用户的角色 + operationId: currentRole + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/currentRole' + default: + $ref: '#/responses/ErrorResponse' + tags: + - role + /user/apikeys: + get: + description: DescribeUserAPIKeys 获取APIKey列表 + operationId: describeUserAPIKeys + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 秘钥对名称 + in: query + name: name + type: string + x-go-name: Name + - description: Token类型, [system/user] + in: query + name: type + type: string + x-go-name: Type + - description: 是否查询全部/导出 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeUserAPIKeys' + default: + $ref: '#/responses/ErrorResponse' + tags: + - apiKey + post: + description: CreateUserApikey 创建apikey + operationId: createUserApikey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateApikeyRequest' + responses: + "200": + $ref: '#/responses/createUserApikey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - apiKey + /user/apikeys/{apikey_id}: + delete: + description: DeleteUserApikey 删除某个apikey + operationId: deleteUserApikey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: apikey_id + required: true + type: string + x-go-name: ApikeyID + responses: + "200": + $ref: '#/responses/deleteUserApikey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - apiKey + get: + description: DescribeUserAPIKey 获取apikey详情 + operationId: describeUserAPIKey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: apikey_id + required: true + type: string + x-go-name: ApikeyID + responses: + "200": + $ref: '#/responses/describeUserAPIKey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - apiKey + put: + description: ModifyUserApikey 修改apikey(暂不启用) + operationId: modifyUserApikey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: apikey_id + required: true + type: string + x-go-name: ApikeyID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyApikeyRequest' + responses: + "200": + $ref: '#/responses/modifyUserApikey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - apiKey + /user/projects: + get: + description: DescribeUserProjects 获取项目列表 + operationId: describeUserProjects + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + in: query + name: projectName + type: string + x-go-name: ProjectName + - description: 0表示全部,1表示拥有者,2表示被共享者 + format: int64 + in: query + name: owned + type: integer + x-go-name: Owned + - in: query + name: isAll + type: string + x-go-name: IsAll + - description: 按创建时间asc/desc排列 + in: query + name: orderByCreatetime + type: string + x-go-name: OrderByCreatetime + - description: 新增可选,按用户名查找 + in: query + name: ownerName + type: string + x-go-name: OwnerName + - description: 新增可选,按被转移用户的用户名查找它拥有的项目 + in: query + name: sharerName + type: string + x-go-name: SharerName + responses: + "200": + $ref: '#/responses/describeUserProjects' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + post: + description: CreateUserProject 创建项目 + operationId: createUserProject + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateProjectRequest' + responses: + "200": + $ref: '#/responses/createUserProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /user/projects/{project_id}: + delete: + description: DeleteUserProject 删除项目 + operationId: deleteUserProject + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + responses: + "200": + $ref: '#/responses/deleteUserProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + get: + description: DescribeUserProject 获取项目详情 + operationId: describeUserProject + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + responses: + "200": + $ref: '#/responses/describeUserProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + put: + description: ModifyUserProject 修改项目信息 + operationId: modifyUserProject + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyProjectRequest' + responses: + "200": + $ref: '#/responses/modifyUserProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /user/projects/{project_id}/cancelShare: + put: + description: CancelShareUserProject 取消共享项目 + operationId: cancelShareUserProject + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + - in: body + name: Body + schema: + $ref: '#/definitions/CalcelShareProjectRequest' + responses: + "200": + $ref: '#/responses/cancelShareUserProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /user/projects/{project_id}/describeSharProject: + get: + description: DescribeShareUserProject 获取共享项目详情 + operationId: describeShareProject + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + responses: + "200": + $ref: '#/responses/describeShareProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /user/projects/{project_id}/description: + put: + description: ModifyUserProject 修改项目信息 + operationId: modifyUserProjectDescription + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyProjectDescriptionRequest' + responses: + "200": + $ref: '#/responses/modifyUserProjectDescription' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /user/projects/{project_id}/move: + put: + description: MoveUserProject 转移项目 + operationId: moveUserProject + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + - in: body + name: Body + schema: + $ref: '#/definitions/MoveProjectRequest' + responses: + "200": + $ref: '#/responses/moveUserProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /user/projects/{project_id}/share: + put: + description: ShareUserProject 共享项目 + operationId: shareUserProject + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + - in: body + name: Body + schema: + $ref: '#/definitions/ShareProjectRequest' + responses: + "200": + $ref: '#/responses/shareUserProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /user/projects/move/instances: + put: + description: MoveUserInstances 转移项目下的某些实例 + operationId: moveUserInstances + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/MoveInstancesRequest' + responses: + "200": + $ref: '#/responses/moveUserInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /user/sshkeys: + get: + description: DescribeUserSshKeys 获取个人sshkey列表 + operationId: describeUserSshKeys + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 秘钥名称 + in: query + name: name + type: string + x-go-name: Name + - description: 是否显示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeUserSshKeys' + default: + $ref: '#/responses/ErrorResponse' + tags: + - sshkey + post: + description: CreateUserSshkey 创建个人sshkey + operationId: createUserSshkey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateSshkeyRequest' + responses: + "200": + $ref: '#/responses/createUserSshkey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - sshkey + /user/sshkeys/{sshkey_id}: + delete: + description: DeleteUserSshkey 删除sshkey + operationId: deleteUserSshkey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: sshkey_id + required: true + type: string + x-go-name: SshkeyID + responses: + "200": + $ref: '#/responses/deleteUserSshkey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - sshkey + get: + description: DescribeUserSshKey 获取sshkey详情 + operationId: describeUserSshKey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: sshkey_id + required: true + type: string + x-go-name: SshkeyID + responses: + "200": + $ref: '#/responses/describeUserSshKey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - sshkey + put: + description: ModifyUserSshkey 修改sshkey + operationId: modifyUserSshkey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: sshkey_id + required: true + type: string + x-go-name: SshkeyID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifySshkeyRequest' + responses: + "200": + $ref: '#/responses/modifyUserSshkey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - sshkey + /user/sshkeys/instances/{sshkey_id}: + get: + description: GetInstancesBySshkey 根据sshkey获取实例列表 + operationId: getInstancesBySshkey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: sshkey_id + required: true + type: string + x-go-name: SshkeyID + responses: + "200": + $ref: '#/responses/getInstancesBySshkey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - sshkey + /users: + get: + description: DescribeUsers 获取用户列表 + operationId: describeUsers + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 角色uuid + in: query + name: roleId + type: string + x-go-name: RoleID + - description: 项目uuid + in: query + name: defaultProjectId + type: string + x-go-name: DefaultProjectID + - description: 用户名 + in: query + name: userName + type: string + x-go-name: UserName + - description: 是否显示全部, isAll=1表示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeUsers' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /users/{user_id}: + get: + description: DescribeUser 获取用户详情 + operationId: describeUser + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: user_id + required: true + type: string + x-go-name: UserID + responses: + "200": + $ref: '#/responses/describeUser' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + put: + description: ModifyUser 修改用户信息 + operationId: modifyUser + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: user_id + required: true + type: string + x-go-name: UserID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyUserRequest' + responses: + "200": + $ref: '#/responses/modifyUser' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /users/getUserByName: + get: + description: DescribeUserByName 根据用户名获取用户详情 + operationId: describeUserByName + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 用户名,唯一 + in: query + name: userName + required: true + type: string + x-go-name: UserName + responses: + "200": + $ref: '#/responses/describeUserByName' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /users/verify: + post: + description: VerifyUser 鉴定用户 + operationId: verifyUser + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/VerifyUserRequest' + responses: + "200": + $ref: '#/responses/verifyUser' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user +produces: + - application/json + - application/xml +responses: + ErrorResponse: + description: unit err response for non 200 + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + error: + $ref: '#/definitions/ErrorResponse' + requestId: + description: 流量ID + type: string + x-go-name: RequestId + required: + - error + - requestId + type: object + addAlert: + description: A AddAlertResult is an response struct that is used to describe create Alert result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + addRule: + description: A AddRuleResult is an response struct that is used to describe create rule result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + cancelShareUserProject: + description: A CancelShareUserProjectResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + createProjectInstance: + description: A CreateProjectInstanceResult is an response struct that is used to describe create instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/InstanceIds' + type: object + createUserApikey: + description: A CreateUserApikeyResult is an response struct that is used to describe create apikey result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ApikeyId' + type: object + createUserProject: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ProjectId' + type: object + createUserSshkey: + description: A CreateUserSshkeyResult is an response struct that is used to describe create sshkey result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/SshkeyId' + type: object + currentRole: + description: A CurrentRoleResult is an response struct that is used to describe role. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/RoleInfo' + type: object + deleteAlert: + description: A DeleteAlertResult is an response struct that is used to describe create alert result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteInstances: + description: A DeleteInstancesResult is an response struct that is used to describe modify instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteMessage: + description: A DeleteMessageResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteProjectInstance: + description: A DeleteProjectInstanceResult is an response struct that is used to delete stop instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteRule: + description: A DeleteRuleResult is an response struct that is used to describe create rule result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteUserApikey: + description: A DeleteUserApikeyResult is an response struct that is used to describe delete Apikey result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteUserProject: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteUserSshkey: + description: A DeleteUserSshkeyResult is an response struct that is used to describe delete sshkey result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + describeAlert: + description: A DescribeAlertResult is an response struct that is used to describe get Alert. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/Alert' + type: object + describeAlerts: + description: A DescribeAlertsResult is an response struct that is used to describe get Alert. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/AlertList' + type: object + describeAuditLogTypes: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + items: + $ref: '#/definitions/AuditLogsType' + type: array + x-go-name: Result + type: object + describeAuditLogs: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/AuditLogList' + type: object + describeDevice: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/DeviceInfo' + type: object + describeDeviceStock: + description: A GetDeviceStockResult is an response struct that is used to get device stock. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/DeviceStock' + type: object + describeDeviceType: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/DeviceTypeInfo' + type: object + describeDeviceTypeImagePartitions: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/QueryDeviceTypeImagePartitionResponse' + type: object + describeDeviceTypeImages: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ImageList' + type: object + describeDeviceTypes: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/DeviceTypeList' + type: object + describeDevices: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/DeviceList' + type: object + describeIdc: + description: A DescribeIdcResult is an response struct that is used to describe idc. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/IdcInfo' + type: object + describeIdcs: + description: A DescribIdcsResult is an response struct that is used to describe idcs. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/IdcList' + type: object + describeImage: + description: A DescribeImageResult is an response struct that is used to describe image. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ImageInfo' + type: object + describeImageDeviceTypes: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/DeviceTypeList' + type: object + describeImages: + description: A DescribeImagesResult is an response struct that is used to describe images. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ImageList' + type: object + describeInstancesByProjectIdAndOwnerNameAndSharerName: + description: A DescribeInstancesByProjectIdAndOwnerNameAndSharerNameResult is an response struct that is used to get instance list. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/InstanceForShareList' + type: object + describeLicenseContent: + description: A DescribeLicenseContentResult is an response struct that is used to describe getuser. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/LicenseContent' + type: object + describeLocalUser: + description: A DescribeLocalUserResult is an response struct that is used to describe getuser. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + error: + $ref: '#/definitions/ErrorResponse' + result: + $ref: '#/definitions/UserInfo' + type: object + describeOS: + description: A DescribeOsResult is an response struct that is used to describe os. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/OsInfo' + type: object + describeOSs: + description: A DescribeOssResult is an response struct that is used to describe oss. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/OsList' + type: object + describeProjectInstance: + description: A GetInstanceResult is an response struct that is used to describe instance. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/InstanceInfo' + type: object + describeProjectInstances: + description: A DescribeProjectInstancesResult is an response struct that is used to get instance list. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/InstanceList' + type: object + describeResources: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + describeRole: + description: A GetRoleResult is an response struct that is used to describe role. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/RoleInfo' + type: object + describeRoles: + description: A GetRoleListResult is an response struct that is used to describe get role list. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/RoleList' + type: object + describeRule: + description: A DescribeRuleResult is an response struct that is used to describe get rule. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/Rule' + type: object + describeRules: + description: A DescribeRuleResult is an response struct that is used to describe get rule. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/RuleList' + type: object + describeShareProject: + description: A DescribeShareProjectResult is an response struct that is used to describe getapikey. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ShareProjectInfo' + type: object + describeUser: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + error: + $ref: '#/definitions/ErrorResponse' + result: + $ref: '#/definitions/UserInfo' + type: object + describeUserAPIKey: + description: A DescribeUserAPIKeyResult is an response struct that is used to describe getapikey. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ApikeyInfo' + type: object + describeUserAPIKeys: + description: A DescribeUserAPIKeysResult is an response struct that is used to describe getapikeylist. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ApikeyList' + type: object + describeUserByName: + description: A GetUserByNameResult is an response struct that is used to describe user. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/UserInfo' + type: object + describeUserProject: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ProjectInfo' + type: object + describeUserProjects: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ProjectList' + type: object + describeUserSshKey: + description: A DescribeUserSshKeyResult is an response struct that is used to describe sshkey. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/SshkeyInfo' + type: object + describeUserSshKeys: + description: A DescribeUserSshKeysResult is an response struct that is used to describe get sshkey list. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/SshkeyList' + type: object + describeUsers: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/UserList' + type: object + describeVolumesRaids: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + items: + $ref: '#/definitions/VolumeRaids' + type: array + x-go-name: Result + type: object + desrcibeAgentStatus: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/AgentStatusResponse' + type: object + desrcibeTags: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/TagsResponse' + type: object + disableRule: + description: A DisableRuleResult is an response struct that is used to describe create rule result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + editRule: + description: A EditRuleResult is an response struct that is used to describe create rule result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + enableRule: + description: A EnableRuleResult is an response struct that is used to describe create rule result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + getInstancesBySshkey: + description: A GetInstancesBySshkeyResult is an response struct that is used to get instance list by sshkey. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/InstancesSshkeyInfoResponse' + type: object + getMessageById: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/MessageWithNextPrev' + type: object + getMessageList: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/MessageList' + type: object + getMessageStatistic: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/MessageStatistic' + type: object + getMessageTypes: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/MessageTypesResp' + type: object + getMonitorData: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + items: + $ref: '#/definitions/DataEveryMetric' + type: array + x-go-name: Result + type: object + hasUnreadMessage: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/HasUnreadMessage' + type: object + lockProjectInstance: + description: A LockProjectInstanceResult is an response struct that is used to describe lock instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyInstances: + description: A ModifyInstancesResult is an response struct that is used to describe modify instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyLocalUser: + description: A ModifyLocalUserResult is an response struct that is used to describe getuser. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyLocalUserPassword: + description: A ModifyLocalUserPasswordResult is an response struct that is used to describe getuser. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyProjectInstance: + description: A ModifyProjectInstanceResult is an response struct that is used to describe modify instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyUser: + description: A GetUserResult is an response struct that is used to describe getuser. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyUserApikey: + description: A ModifyUserApikeyResult is an response struct that is used to describe modifyApikey result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyUserProject: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyUserProjectDescription: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyUserSshkey: + description: A ModifyUserSshkeyResult is an response struct that is used to modify sshkey result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + moveUserInstances: + description: A MoveInstanceResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + moveUserProject: + description: A MoveProjectResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + readMessage: + description: A ReadMessageResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + reinstallProjectInstance: + description: A ReinstallProjectInstanceResult is an response struct that is used to describe reinstall instance. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + resetInstanceStatus: + description: A ResetInstanceStatusResult is an response struct that is used to describe restart instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + resetProjectInstancePasswd: + description: A ResetProjectInstancePasswdResult is an response struct that is used to describe reset instance password. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + resetProjectInstancesPasswd: + description: A ResetProjectInstancesPasswdResult is an response struct that is used to describe reset instance password. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + restartInstances: + description: A RestartInstancesResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + restartProjectInstance: + description: A RestartProjectInstanceResult is an response struct that is used to describe restart instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + shareUserProject: + description: A ShareUserProjectResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + startInstances: + description: A StartInstancesResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + startProjectInstance: + description: A StartProjectInstanceResult is an response struct that is used to describe start instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + stopInstances: + description: A StopInstancesResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + stopProjectInstance: + description: A StopProjectInstanceResult is an response struct that is used to describe stop instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + unLockProjectInstance: + description: A UnLockProjectInstanceResult is an response struct that is used to describe unlock instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + verifyUser: + description: A VerifyUserResult is an response struct that is used to describe verify user result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object +schemes: + - http +security: + - api_key: [] +securityDefinitions: + api_key: + in: header + name: bmp-ak + type: apiKey +swagger: "2.0" +x-meta-array: + - value1 + - value2 +x-meta-array-obj: + - name: obj + value: field +x-meta-value: value diff --git a/bmp-openapi-console/swagger_gen.sh b/bmp-openapi-console/swagger_gen.sh new file mode 100644 index 0000000..c8cd238 --- /dev/null +++ b/bmp-openapi-console/swagger_gen.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +# install goswagger: https://goswagger.io/install.html#Installing%20from%20source + +swagger version +\rm ./swagger.yml | swagger generate spec -o ./swagger.yml +# swagger validate ./swagger.yml goswagger有缺陷,且报错无法提供有效信息,建议使用https://editor.swagger.io/来校验 +# validate 和 generate命令在0.25.0版本有panic,0.30.3版本已修复 +swagger validate swagger.yml +\rm -rf ../bmp-openapi-console-sdk/client && \rm -rf ../bmp-openapi-console-sdk/models +swagger generate client -f swagger.yml --target=../bmp-openapi-console-sdk diff --git a/bmp-openapi-console/swagger_gen_from_yml.sh b/bmp-openapi-console/swagger_gen_from_yml.sh new file mode 100644 index 0000000..635f18b --- /dev/null +++ b/bmp-openapi-console/swagger_gen_from_yml.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +# install goswagger: https://goswagger.io/install.html#Installing%20from%20source + +swagger version +# swagger validate ./swagger.yml goswagger有缺陷,且报错无法提供有效信息,建议使用https://editor.swagger.io/来校验 +# validate 和 generate命令在0.25.0版本有panic,0.30.3版本已修复 +swagger validate swagger.yml +\rm -rf ../bmp-openapi-console-sdk/client && \rm -rf ../bmp-openapi-console-sdk/models +swagger generate client -f swagger.yml --target=../bmp-openapi-console-sdk diff --git a/bmp-openapi-console/swagger_gen_json.sh b/bmp-openapi-console/swagger_gen_json.sh new file mode 100644 index 0000000..526b128 --- /dev/null +++ b/bmp-openapi-console/swagger_gen_json.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +# install goswagger: https://goswagger.io/install.html#Installing%20from%20source + +swagger version +\rm ./swagger.json | swagger generate spec -o ./swagger.json +# swagger validate ./swagger.yml goswagger有缺陷,且报错无法提供有效信息,建议使用https://editor.swagger.io/来校验 +# validate 和 generate命令在0.25.0版本有panic,0.30.3版本已修复 +swagger validate swagger.json +#\rm -rf ../bmp-openapi-sdk/client && \rm -rf ../bmp-openapi-sdk/models +#swagger generate client -f swagger.yml --target=../bmp-openapi-sdk diff --git a/bmp-openapi-console/swaggermodels/AddAlertRequest.go b/bmp-openapi-console/swaggermodels/AddAlertRequest.go new file mode 100644 index 0000000..e927f24 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/AddAlertRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters addAlert +type AddAlertRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.AddAlertRequest +} diff --git a/bmp-openapi-console/swaggermodels/AddAlertResult.go b/bmp-openapi-console/swaggermodels/AddAlertResult.go new file mode 100644 index 0000000..0d9dcc9 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/AddAlertResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A AddAlertResult is an response struct that is used to describe create Alert result. +// swagger:response addAlert +type AddAlertResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/AddRuleRequest.go b/bmp-openapi-console/swaggermodels/AddRuleRequest.go new file mode 100644 index 0000000..4ca2f82 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/AddRuleRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters addRule +type AddRuleRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.AddRuleRequest +} diff --git a/bmp-openapi-console/swaggermodels/AddRuleResult.go b/bmp-openapi-console/swaggermodels/AddRuleResult.go new file mode 100644 index 0000000..8bd8547 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/AddRuleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A AddRuleResult is an response struct that is used to describe create rule result. +// swagger:response addRule +type AddRuleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/CancelShareUserProjectRequest.go b/bmp-openapi-console/swaggermodels/CancelShareUserProjectRequest.go new file mode 100644 index 0000000..fbbec27 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/CancelShareUserProjectRequest.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters cancelShareUserProject +type CancelShareUserProjectRequest struct { + WriteRequestHeader + // in: path + ProjectID string `json:"project_id"` + // in: body + Body requestTypes.CalcelShareProjectRequest +} diff --git a/bmp-openapi-console/swaggermodels/CancelShareUserProjectResult.go b/bmp-openapi-console/swaggermodels/CancelShareUserProjectResult.go new file mode 100644 index 0000000..b1e3770 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/CancelShareUserProjectResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A CancelShareUserProjectResult is an response struct +// swagger:response cancelShareUserProject +type CancelShareUserProjectResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/Common.go b/bmp-openapi-console/swaggermodels/Common.go new file mode 100644 index 0000000..31f8573 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/Common.go @@ -0,0 +1,61 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/controllers" +) + +type ReadRequestHeader struct { + // 流量唯一id + // required: true + // in: header + TraceID string `json:"traceId"` + // demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + // required: true + // in: header + Authorization string `json:"authorization"` + // 用户uuid, deprecated + // in: header + BmpUserID string `json:"bmpUserId"` + // 用户语言 [zh_CN, en_US] + // in: header + BmpLanguage string `json:"bmpLanguage"` +} + +type WriteRequestHeader struct { + // 流量唯一id + // required: true + // in: header + TraceID string `json:"traceId"` + // demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + // required: true + // in: header + Authorization string `json:"authorization"` + // 用户uuid + // in: header + BmpUserID string `json:"bmpUserId"` + // 用户语言 [zh_CN, en_US] + // in: header + BmpLanguage string `json:"bmpLanguage"` +} + +// unit err response for non 200 +// swagger:response ErrorResponse +type ErrorResponse struct { + ResponseHeader + //In: body + Body struct { + // 错误信息 + // required: true + Err controllers.ErrorResponse `json:"error"` + // 流量ID + // required: true + RequestId string `json:"requestId"` + } +} + +// 返回body里面的公共字段 +type ResponseHeader struct { + // 流量ID + // in: header + TraceID string `json:"traceId"` +} diff --git a/bmp-openapi-console/swaggermodels/CreateProjectInstanceRequest.go b/bmp-openapi-console/swaggermodels/CreateProjectInstanceRequest.go new file mode 100644 index 0000000..4689422 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/CreateProjectInstanceRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createProjectInstance +type CreateProjectInstanceRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateInstanceRequest +} diff --git a/bmp-openapi-console/swaggermodels/CreateProjectInstanceResult.go b/bmp-openapi-console/swaggermodels/CreateProjectInstanceResult.go new file mode 100644 index 0000000..d8adc16 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/CreateProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A CreateProjectInstanceResult is an response struct that is used to describe create instance result. +// swagger:response createProjectInstance +type CreateProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.InstanceIds `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/CreateUserApikeyRequest.go b/bmp-openapi-console/swaggermodels/CreateUserApikeyRequest.go new file mode 100644 index 0000000..3f6740c --- /dev/null +++ b/bmp-openapi-console/swaggermodels/CreateUserApikeyRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createUserApikey +type CreateUserApikeyRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateApikeyRequest +} diff --git a/bmp-openapi-console/swaggermodels/CreateUserApikeyResult.go b/bmp-openapi-console/swaggermodels/CreateUserApikeyResult.go new file mode 100644 index 0000000..0c2ace6 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/CreateUserApikeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A CreateUserApikeyResult is an response struct that is used to describe create apikey result. +// swagger:response createUserApikey +type CreateUserApikeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ApikeyId `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/CreateUserProjectRequest.go b/bmp-openapi-console/swaggermodels/CreateUserProjectRequest.go new file mode 100644 index 0000000..3af1e8d --- /dev/null +++ b/bmp-openapi-console/swaggermodels/CreateUserProjectRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createUserProject +type CreateUserProjectRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateProjectRequest +} diff --git a/bmp-openapi-console/swaggermodels/CreateUserProjectResult.go b/bmp-openapi-console/swaggermodels/CreateUserProjectResult.go new file mode 100644 index 0000000..eb8a0b4 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/CreateUserProjectResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// swagger:response createUserProject +type CreateUserProjectResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ProjectId `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/CreateUserSshkeyRequest.go b/bmp-openapi-console/swaggermodels/CreateUserSshkeyRequest.go new file mode 100644 index 0000000..208a99f --- /dev/null +++ b/bmp-openapi-console/swaggermodels/CreateUserSshkeyRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createUserSshkey +type CreateUserSshkeyRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateSshkeyRequest +} diff --git a/bmp-openapi-console/swaggermodels/CreateUserSshkeyResult.go b/bmp-openapi-console/swaggermodels/CreateUserSshkeyResult.go new file mode 100644 index 0000000..c84557f --- /dev/null +++ b/bmp-openapi-console/swaggermodels/CreateUserSshkeyResult.go @@ -0,0 +1,13 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// A CreateUserSshkeyResult is an response struct that is used to describe create sshkey result. +// swagger:response createUserSshkey +type CreateUserSshkeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.SshkeyId `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/CurrentRoleRequest.go b/bmp-openapi-console/swaggermodels/CurrentRoleRequest.go new file mode 100644 index 0000000..349db0b --- /dev/null +++ b/bmp-openapi-console/swaggermodels/CurrentRoleRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters currentRole +type CurrentRoleRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi-console/swaggermodels/CurrentRoleResult.go b/bmp-openapi-console/swaggermodels/CurrentRoleResult.go new file mode 100644 index 0000000..23f3ea6 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/CurrentRoleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A CurrentRoleResult is an response struct that is used to describe role. +// swagger:response currentRole +type CurrentRoleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.RoleInfo `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DeleteAlertRequest.go b/bmp-openapi-console/swaggermodels/DeleteAlertRequest.go new file mode 100644 index 0000000..f72819c --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteAlertRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters deleteAlert +type DeleteAlertRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.DeleteAlertRequest +} diff --git a/bmp-openapi-console/swaggermodels/DeleteAlertResult.go b/bmp-openapi-console/swaggermodels/DeleteAlertResult.go new file mode 100644 index 0000000..1029c1f --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteAlertResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteAlertResult is an response struct that is used to describe create alert result. +// swagger:response deleteAlert +type DeleteAlertResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DeleteInstancesRequest.go b/bmp-openapi-console/swaggermodels/DeleteInstancesRequest.go new file mode 100644 index 0000000..58eac32 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteInstancesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters deleteInstances +type DeleteInstancesRequest struct { + ReadRequestHeader + + // in: body + Body requestTypes.DeleteInstancesRequest +} diff --git a/bmp-openapi-console/swaggermodels/DeleteInstancesResult.go b/bmp-openapi-console/swaggermodels/DeleteInstancesResult.go new file mode 100644 index 0000000..304a49a --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteInstancesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteInstancesResult is an response struct that is used to describe modify instance result. +// swagger:response deleteInstances +type DeleteInstancesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DeleteMessageRequest.go b/bmp-openapi-console/swaggermodels/DeleteMessageRequest.go new file mode 100644 index 0000000..81d7bf9 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteMessageRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters deleteMessage +type DeleteMessageRequest struct { + WriteRequestHeader + + // in: body + Body requestTypes.DeleteMessagesRequest +} diff --git a/bmp-openapi-console/swaggermodels/DeleteMessageResult.go b/bmp-openapi-console/swaggermodels/DeleteMessageResult.go new file mode 100644 index 0000000..fde37dc --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteMessageResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteMessageResult is an response struct +// swagger:response deleteMessage +type DeleteMessageResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DeleteProjectInstanceRequest.go b/bmp-openapi-console/swaggermodels/DeleteProjectInstanceRequest.go new file mode 100644 index 0000000..9b34ac5 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteProjectInstanceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteProjectInstance +type DeleteProjectInstanceRequest struct { + WriteRequestHeader + + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DeleteProjectInstanceResult.go b/bmp-openapi-console/swaggermodels/DeleteProjectInstanceResult.go new file mode 100644 index 0000000..2abc940 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteProjectInstanceResult is an response struct that is used to delete stop instance result. +// swagger:response deleteProjectInstance +type DeleteProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DeleteRuleRequest.go b/bmp-openapi-console/swaggermodels/DeleteRuleRequest.go new file mode 100644 index 0000000..c42df6d --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteRuleRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters deleteRule +type DeleteRuleRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.DeleteRuleRequest +} diff --git a/bmp-openapi-console/swaggermodels/DeleteRuleResult.go b/bmp-openapi-console/swaggermodels/DeleteRuleResult.go new file mode 100644 index 0000000..8175161 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteRuleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteRuleResult is an response struct that is used to describe create rule result. +// swagger:response deleteRule +type DeleteRuleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DeleteUserApikeyRequest.go b/bmp-openapi-console/swaggermodels/DeleteUserApikeyRequest.go new file mode 100644 index 0000000..ded116b --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteUserApikeyRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteUserApikey +type DeleteUserApikeyRequest struct { + WriteRequestHeader + + // in: path + ApikeyID string `json:"apikey_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DeleteUserApikeyResult.go b/bmp-openapi-console/swaggermodels/DeleteUserApikeyResult.go new file mode 100644 index 0000000..f36d2ba --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteUserApikeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteUserApikeyResult is an response struct that is used to describe delete Apikey result. +// swagger:response deleteUserApikey +type DeleteUserApikeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DeleteUserProjectRequest.go b/bmp-openapi-console/swaggermodels/DeleteUserProjectRequest.go new file mode 100644 index 0000000..b3ded70 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteUserProjectRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteUserProject +type DeleteUserProjectRequest struct { + WriteRequestHeader + + // in: path + ProjectID string `json:"project_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DeleteUserProjectResult.go b/bmp-openapi-console/swaggermodels/DeleteUserProjectResult.go new file mode 100644 index 0000000..17fe5b9 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteUserProjectResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response deleteUserProject +type DeleteUserProjectResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DeleteUserSshkeyRequest.go b/bmp-openapi-console/swaggermodels/DeleteUserSshkeyRequest.go new file mode 100644 index 0000000..1d5fa9f --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteUserSshkeyRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteUserSshkey +type DeleteUserSshkeyRequest struct { + WriteRequestHeader + + // in: path + SshkeyID string `json:"sshkey_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DeleteUserSshkeyResult.go b/bmp-openapi-console/swaggermodels/DeleteUserSshkeyResult.go new file mode 100644 index 0000000..ce05045 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DeleteUserSshkeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteUserSshkeyResult is an response struct that is used to describe delete sshkey result. +// swagger:response deleteUserSshkey +type DeleteUserSshkeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeAlertRequest.go b/bmp-openapi-console/swaggermodels/DescribeAlertRequest.go new file mode 100644 index 0000000..e2eb916 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeAlertRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeAlert +type DescribeAlertRequest struct { + ReadRequestHeader + + // in: query + requestTypes.DescribeAlertRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeAlertResult.go b/bmp-openapi-console/swaggermodels/DescribeAlertResult.go new file mode 100644 index 0000000..e6eaec0 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeAlertResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeAlertResult is an response struct that is used to describe get Alert. +// swagger:response describeAlert +type DescribeAlertResult struct { + ResponseHeader + // in: body + Body struct { + Result response.Alert `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeAlertsRequest.go b/bmp-openapi-console/swaggermodels/DescribeAlertsRequest.go new file mode 100644 index 0000000..3e9e4af --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeAlertsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeAlerts +type DescribeAlertsRequest struct { + ReadRequestHeader + + // in: query + requestTypes.DescribeAlertsRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeAlertsResult.go b/bmp-openapi-console/swaggermodels/DescribeAlertsResult.go new file mode 100644 index 0000000..33be981 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeAlertsResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeAlertsResult is an response struct that is used to describe get Alert. +// swagger:response describeAlerts +type DescribeAlertsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.AlertList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeAuditLogTypesRequest.go b/bmp-openapi-console/swaggermodels/DescribeAuditLogTypesRequest.go new file mode 100644 index 0000000..7d56f67 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeAuditLogTypesRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters describeAuditLogTypes +type DescribeAuditLogTypesRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi-console/swaggermodels/DescribeAuditLogTypesResult.go b/bmp-openapi-console/swaggermodels/DescribeAuditLogTypesResult.go new file mode 100644 index 0000000..29be235 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeAuditLogTypesResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeAuditLogTypes +type DescribeAuditLogTypesResult struct { + ResponseHeader + // in: body + Body struct { + Result []response.AuditLogsType `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeAuditLogsRequest.go b/bmp-openapi-console/swaggermodels/DescribeAuditLogsRequest.go new file mode 100644 index 0000000..c34f18d --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeAuditLogsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeAuditLogs +type DescribeAuditLogsRequest struct { + ReadRequestHeader + + // in: query + requestTypes.DescribeAuditLogsRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeAuditLogsResult.go b/bmp-openapi-console/swaggermodels/DescribeAuditLogsResult.go new file mode 100644 index 0000000..adced77 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeAuditLogsResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeAuditLogs +type DescribeAuditLogsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.AuditLogList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeDeviceRequest.go b/bmp-openapi-console/swaggermodels/DescribeDeviceRequest.go new file mode 100644 index 0000000..8adad9e --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeDeviceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeDevice +type DescribeDeviceRequest struct { + ReadRequestHeader + + // in: path + DeviceID string `json:"device_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DescribeDeviceResult.go b/bmp-openapi-console/swaggermodels/DescribeDeviceResult.go new file mode 100644 index 0000000..cf319e1 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeDeviceResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeDevice +type DescribeDeviceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.DeviceInfo `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeDeviceStockRequest.go b/bmp-openapi-console/swaggermodels/DescribeDeviceStockRequest.go new file mode 100644 index 0000000..b65a0e4 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeDeviceStockRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeDeviceStock +type DescribeDeviceStockRequest struct { + ReadRequestHeader + + // in: query + DeviceTypeID string `json:"deviceTypeId"` +} diff --git a/bmp-openapi-console/swaggermodels/DescribeDeviceStockResult.go b/bmp-openapi-console/swaggermodels/DescribeDeviceStockResult.go new file mode 100644 index 0000000..f632dfe --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeDeviceStockResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetDeviceStockResult is an response struct that is used to get device stock. +// swagger:response describeDeviceStock +type DescribeDeviceStockResult struct { + ResponseHeader + // in: body + Body struct { + Result response.DeviceStock `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeDeviceTypeImagePartitionsRequest.go b/bmp-openapi-console/swaggermodels/DescribeDeviceTypeImagePartitionsRequest.go new file mode 100644 index 0000000..ebd7fe8 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeDeviceTypeImagePartitionsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeDeviceTypeImagePartitions +type DescribeDeviceTypeImagePartitionsRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryDeviceTypeImagePartitionRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeDeviceTypeImagePartitionsResult.go b/bmp-openapi-console/swaggermodels/DescribeDeviceTypeImagePartitionsResult.go new file mode 100644 index 0000000..62a2ef2 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeDeviceTypeImagePartitionsResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeDeviceTypeImagePartitions +type DescribeDeviceTypeImagePartitionsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.QueryDeviceTypeImagePartitionResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeDeviceTypeImagesRequest.go b/bmp-openapi-console/swaggermodels/DescribeDeviceTypeImagesRequest.go new file mode 100644 index 0000000..979bfec --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeDeviceTypeImagesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeDeviceTypeImages +type DescribeDeviceTypeImagesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryDeviceTypeImageRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeDeviceTypeImagesResult.go b/bmp-openapi-console/swaggermodels/DescribeDeviceTypeImagesResult.go new file mode 100644 index 0000000..c11584a --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeDeviceTypeImagesResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeDeviceTypeImages +type DescribeDeviceTypeImagesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ImageList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeDeviceTypeRequest.go b/bmp-openapi-console/swaggermodels/DescribeDeviceTypeRequest.go new file mode 100644 index 0000000..f899cba --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeDeviceTypeRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeDeviceType +type DescribeDeviceTypeRequest struct { + ReadRequestHeader + + // in: path + DeviceTypeID string `json:"device_type_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DescribeDeviceTypeResult.go b/bmp-openapi-console/swaggermodels/DescribeDeviceTypeResult.go new file mode 100644 index 0000000..96448e7 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeDeviceTypeResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeDeviceType +type DescribeDeviceTypeResult struct { + ResponseHeader + // in: body + Body struct { + Result response.DeviceTypeInfo `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeDeviceTypesRequest.go b/bmp-openapi-console/swaggermodels/DescribeDeviceTypesRequest.go new file mode 100644 index 0000000..00c50c0 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeDeviceTypesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeDeviceTypes +type DescribeDeviceTypesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryDeviceTypesRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeDeviceTypesResult.go b/bmp-openapi-console/swaggermodels/DescribeDeviceTypesResult.go new file mode 100644 index 0000000..7a7f1b1 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeDeviceTypesResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeDeviceTypes +type DescribeDeviceTypesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.DeviceTypeList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeDevicesRequest.go b/bmp-openapi-console/swaggermodels/DescribeDevicesRequest.go new file mode 100644 index 0000000..1ded9a7 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeDevicesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeDevices +type DescribeDevicesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryDevicesRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeDevicesResult.go b/bmp-openapi-console/swaggermodels/DescribeDevicesResult.go new file mode 100644 index 0000000..76700e6 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeDevicesResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeDevices +type DescribeDevicesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.DeviceList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeIdcRequest.go b/bmp-openapi-console/swaggermodels/DescribeIdcRequest.go new file mode 100644 index 0000000..9b4d158 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeIdcRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeIdc +type DescribeIdcRequest struct { + ReadRequestHeader + + // in: path + IdcID string `json:"idc_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DescribeIdcResult.go b/bmp-openapi-console/swaggermodels/DescribeIdcResult.go new file mode 100644 index 0000000..88de6d4 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeIdcResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeIdcResult is an response struct that is used to describe idc. +// swagger:response describeIdc +type DescribeIdcResult struct { + ResponseHeader + // in: body + Body struct { + Result response.IdcInfo `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeIdcsRequest.go b/bmp-openapi-console/swaggermodels/DescribeIdcsRequest.go new file mode 100644 index 0000000..cc49dfa --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeIdcsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeIdcs +type DescribIdcsRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryIdcsRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeIdcsResult.go b/bmp-openapi-console/swaggermodels/DescribeIdcsResult.go new file mode 100644 index 0000000..fca09c2 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeIdcsResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribIdcsResult is an response struct that is used to describe idcs. +// swagger:response describeIdcs +type DescribIdcsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.IdcList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeImageDeviceTypesRequest.go b/bmp-openapi-console/swaggermodels/DescribeImageDeviceTypesRequest.go new file mode 100644 index 0000000..2ff4e7b --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeImageDeviceTypesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeImageDeviceTypes +type DescribeImageDeviceTypesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryImageDeviceTypesRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeImageDeviceTypesResult.go b/bmp-openapi-console/swaggermodels/DescribeImageDeviceTypesResult.go new file mode 100644 index 0000000..27dc379 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeImageDeviceTypesResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeImageDeviceTypes +type DescribeImageDeviceTypesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.DeviceTypeList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeImageRequest.go b/bmp-openapi-console/swaggermodels/DescribeImageRequest.go new file mode 100644 index 0000000..4a83942 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeImageRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeImage +type DescribeImageRequest struct { + ReadRequestHeader + + // in: path + ImageID string `json:"image_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DescribeImageResult.go b/bmp-openapi-console/swaggermodels/DescribeImageResult.go new file mode 100644 index 0000000..9fa9d20 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeImageResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeImageResult is an response struct that is used to describe image. +// swagger:response describeImage +type DescribeImageResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ImageInfo `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeImagesRequest.go b/bmp-openapi-console/swaggermodels/DescribeImagesRequest.go new file mode 100644 index 0000000..0479001 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeImagesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeImages +type DescribeImagesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryImagesRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeImagesResult.go b/bmp-openapi-console/swaggermodels/DescribeImagesResult.go new file mode 100644 index 0000000..b99f619 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeImagesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeImagesResult is an response struct that is used to describe images. +// swagger:response describeImages +type DescribeImagesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ImageList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeLicenseContentResult.go b/bmp-openapi-console/swaggermodels/DescribeLicenseContentResult.go new file mode 100644 index 0000000..72e2ba3 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeLicenseContentResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeLicenseContentResult is an response struct that is used to describe getuser. +// swagger:response describeLicenseContent +type DescribeLicenseContentResult struct { + ResponseHeader + // in: body + Body struct { + Result response.LicenseContent `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeLocalUserResult.go b/bmp-openapi-console/swaggermodels/DescribeLocalUserResult.go new file mode 100644 index 0000000..a8d461b --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeLocalUserResult.go @@ -0,0 +1,17 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/controllers" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeLocalUserResult is an response struct that is used to describe getuser. +// swagger:response describeLocalUser +type DescribeLocalUserResult struct { + ResponseHeader + // in: body + Body struct { + Result response.UserInfo `json:"result"` + Err *controllers.ErrorResponse `json:"error"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeOsRequest.go b/bmp-openapi-console/swaggermodels/DescribeOsRequest.go new file mode 100644 index 0000000..0f41a68 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeOsRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeOS +type DescribeOsRequest struct { + ReadRequestHeader + + // in: path + OsID string `json:"os_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DescribeOsResult.go b/bmp-openapi-console/swaggermodels/DescribeOsResult.go new file mode 100644 index 0000000..64d8575 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeOsResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeOsResult is an response struct that is used to describe os. +// swagger:response describeOS +type DescribeOsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.OsInfo `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeOssRequest.go b/bmp-openapi-console/swaggermodels/DescribeOssRequest.go new file mode 100644 index 0000000..199f8f3 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeOssRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeOSs +type DescribeOssRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryOssRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeOssResult.go b/bmp-openapi-console/swaggermodels/DescribeOssResult.go new file mode 100644 index 0000000..a3b2c7a --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeOssResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeOssResult is an response struct that is used to describe oss. +// swagger:response describeOSs +type DescribeOssResult struct { + ResponseHeader + // in: body + Body struct { + Result response.OsList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeProjectInstanceRequest.go b/bmp-openapi-console/swaggermodels/DescribeProjectInstanceRequest.go new file mode 100644 index 0000000..0beb2a4 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeProjectInstanceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeProjectInstance +type DescribeProjectInstanceRequest struct { + ReadRequestHeader + // 实例uuid + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DescribeProjectInstanceResult.go b/bmp-openapi-console/swaggermodels/DescribeProjectInstanceResult.go new file mode 100644 index 0000000..aeb5c76 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetInstanceResult is an response struct that is used to describe instance. +// swagger:response describeProjectInstance +type GetInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.InstanceInfo `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeProjectInstancesRequest.go b/bmp-openapi-console/swaggermodels/DescribeProjectInstancesRequest.go new file mode 100644 index 0000000..96d4f89 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeProjectInstancesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeProjectInstances +type DescribeProjectInstancesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryInstancesRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeProjectInstancesResult.go b/bmp-openapi-console/swaggermodels/DescribeProjectInstancesResult.go new file mode 100644 index 0000000..3ebe075 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeProjectInstancesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeProjectInstancesResult is an response struct that is used to get instance list. +// swagger:response describeProjectInstances +type DescribeProjectInstancesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.InstanceList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeResourcesRequest.go b/bmp-openapi-console/swaggermodels/DescribeResourcesRequest.go new file mode 100644 index 0000000..efc7cb5 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeResourcesRequest.go @@ -0,0 +1,11 @@ +package swaggermodels + +import requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + +// swagger:parameters describeResources +type DescribeResourcesRequest struct { + ReadRequestHeader + + // in: path + requestTypes.QueryResourcesRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeResourcesResult.go b/bmp-openapi-console/swaggermodels/DescribeResourcesResult.go new file mode 100644 index 0000000..2c8e6ae --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeResourcesResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeResources +type DescribeResourcesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeRoleRequest.go b/bmp-openapi-console/swaggermodels/DescribeRoleRequest.go new file mode 100644 index 0000000..5e04b93 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeRoleRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeRole +type DescribeRoleRequest struct { + ReadRequestHeader + + // in: path + RoleID string `json:"role_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DescribeRoleResult.go b/bmp-openapi-console/swaggermodels/DescribeRoleResult.go new file mode 100644 index 0000000..4273e52 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeRoleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetRoleResult is an response struct that is used to describe role. +// swagger:response describeRole +type DescribeRoleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.RoleInfo `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeRolesRequest.go b/bmp-openapi-console/swaggermodels/DescribeRolesRequest.go new file mode 100644 index 0000000..5a7c281 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeRolesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeRoles +type DescribeRolesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryRolesRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeRolesResult.go b/bmp-openapi-console/swaggermodels/DescribeRolesResult.go new file mode 100644 index 0000000..f47f334 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeRolesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetRoleListResult is an response struct that is used to describe get role list. +// swagger:response describeRoles +type DescribeRolesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.RoleList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeRuleRequest.go b/bmp-openapi-console/swaggermodels/DescribeRuleRequest.go new file mode 100644 index 0000000..9eda0e5 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeRuleRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeRule +type DescribeRuleRequest struct { + ReadRequestHeader + + // in: query + requestTypes.DescribeRuleRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeRuleResult.go b/bmp-openapi-console/swaggermodels/DescribeRuleResult.go new file mode 100644 index 0000000..d0685d3 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeRuleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeRuleResult is an response struct that is used to describe get rule. +// swagger:response describeRule +type DescribeRuleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.Rule `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeRulesRequest.go b/bmp-openapi-console/swaggermodels/DescribeRulesRequest.go new file mode 100644 index 0000000..1487520 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeRulesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeRules +type DescribeRulesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.DescribeRulesRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeRulesResult.go b/bmp-openapi-console/swaggermodels/DescribeRulesResult.go new file mode 100644 index 0000000..3355909 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeRulesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeRuleResult is an response struct that is used to describe get rule. +// swagger:response describeRules +type DescribeRulesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.RuleList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeShareProjectRequest.go b/bmp-openapi-console/swaggermodels/DescribeShareProjectRequest.go new file mode 100644 index 0000000..d2c8757 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeShareProjectRequest.go @@ -0,0 +1,8 @@ +package swaggermodels + +// swagger:parameters describeShareProject +type DescribeShareProjectRequest struct { + ReadRequestHeader + // in: path + ProjectID string `json:"project_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DescribeShareProjectResult.go b/bmp-openapi-console/swaggermodels/DescribeShareProjectResult.go new file mode 100644 index 0000000..a9c005d --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeShareProjectResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeShareProjectResult is an response struct that is used to describe getapikey. +// swagger:response describeShareProject +type DescribeShareProjectResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ShareProjectInfo `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserAPIKeyRequest.go b/bmp-openapi-console/swaggermodels/DescribeUserAPIKeyRequest.go new file mode 100644 index 0000000..e344412 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserAPIKeyRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeUserAPIKey +type DescribeUserAPIKeyRequest struct { + ReadRequestHeader + // required: true + // in: path + ApikeyID string `json:"apikey_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserAPIKeyResult.go b/bmp-openapi-console/swaggermodels/DescribeUserAPIKeyResult.go new file mode 100644 index 0000000..b998b93 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserAPIKeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeUserAPIKeyResult is an response struct that is used to describe getapikey. +// swagger:response describeUserAPIKey +type DescribeUserAPIKeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ApikeyInfo `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserAPIKeysRequest.go b/bmp-openapi-console/swaggermodels/DescribeUserAPIKeysRequest.go new file mode 100644 index 0000000..06ecd60 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserAPIKeysRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeUserAPIKeys +type DescribeUserAPIKeysRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryApikeysRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserAPIKeysResult.go b/bmp-openapi-console/swaggermodels/DescribeUserAPIKeysResult.go new file mode 100644 index 0000000..3f39d3a --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserAPIKeysResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeUserAPIKeysResult is an response struct that is used to describe getapikeylist. +// swagger:response describeUserAPIKeys +type DescribeUserAPIKeysResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ApikeyList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserByNameRequest.go b/bmp-openapi-console/swaggermodels/DescribeUserByNameRequest.go new file mode 100644 index 0000000..045e3dc --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserByNameRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeUserByName +type DescribeUserByNameRequest struct { + ReadRequestHeader + + // in: query + requestTypes.GetUserByNameRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserByNameResult.go b/bmp-openapi-console/swaggermodels/DescribeUserByNameResult.go new file mode 100644 index 0000000..5b12e3e --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserByNameResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetUserByNameResult is an response struct that is used to describe user. +// swagger:response describeUserByName +type DescribeUserByNameResult struct { + ResponseHeader + // in: body + Body struct { + Result response.UserInfo `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserProjectRequest.go b/bmp-openapi-console/swaggermodels/DescribeUserProjectRequest.go new file mode 100644 index 0000000..ff17e0d --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserProjectRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeUserProject +type DescribeUserProjectRequest struct { + ReadRequestHeader + + // in: path + ProjectID string `json:"project_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserProjectResult.go b/bmp-openapi-console/swaggermodels/DescribeUserProjectResult.go new file mode 100644 index 0000000..a35fbf3 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserProjectResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeUserProject +type DescribeUserProjectResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ProjectInfo `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserProjectsRequest.go b/bmp-openapi-console/swaggermodels/DescribeUserProjectsRequest.go new file mode 100644 index 0000000..6830897 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserProjectsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeUserProjects +type DescribeUserProjectsRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryProjectsRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserProjectsResult.go b/bmp-openapi-console/swaggermodels/DescribeUserProjectsResult.go new file mode 100644 index 0000000..fc08986 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserProjectsResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeUserProjects +type DescribeUserProjectsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ProjectList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserRequest.go b/bmp-openapi-console/swaggermodels/DescribeUserRequest.go new file mode 100644 index 0000000..1ed7030 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeUser +type DescribeUserRequest struct { + ReadRequestHeader + + // in: path + UserID string `json:"user_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserResult.go b/bmp-openapi-console/swaggermodels/DescribeUserResult.go new file mode 100644 index 0000000..293b478 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserResult.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/controllers" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeUser +type DescribeUserResult struct { + ResponseHeader + // in: body + Body struct { + Result response.UserInfo `json:"result"` + Err *controllers.ErrorResponse `json:"error"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserSshKeyRequest.go b/bmp-openapi-console/swaggermodels/DescribeUserSshKeyRequest.go new file mode 100644 index 0000000..3b56f94 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserSshKeyRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeUserSshKey +type DescribeUserSshKeyRequest struct { + ReadRequestHeader + + // in: path + SshkeyID string `json:"sshkey_id"` +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserSshKeyResult.go b/bmp-openapi-console/swaggermodels/DescribeUserSshKeyResult.go new file mode 100644 index 0000000..e349d2e --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserSshKeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeUserSshKeyResult is an response struct that is used to describe sshkey. +// swagger:response describeUserSshKey +type DescribeUserSshKeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.SshkeyInfo `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserSshKeysRequest.go b/bmp-openapi-console/swaggermodels/DescribeUserSshKeysRequest.go new file mode 100644 index 0000000..3b751e4 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserSshKeysRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeUserSshKeys +type DescribeUserSshKeysRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QuerySshkeysRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUserSshKeysResult.go b/bmp-openapi-console/swaggermodels/DescribeUserSshKeysResult.go new file mode 100644 index 0000000..cc0df4e --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUserSshKeysResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeUserSshKeysResult is an response struct that is used to describe get sshkey list. +// swagger:response describeUserSshKeys +type DescribeUserSshKeysResult struct { + ResponseHeader + // in: body + Body struct { + Result response.SshkeyList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUsersRequest.go b/bmp-openapi-console/swaggermodels/DescribeUsersRequest.go new file mode 100644 index 0000000..cb09b6f --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUsersRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeUsers +type DescribeUsersRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryUsersRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeUsersResult.go b/bmp-openapi-console/swaggermodels/DescribeUsersResult.go new file mode 100644 index 0000000..62fa3e1 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeUsersResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeUsers +type DescribeUsersResult struct { + ResponseHeader + // in: body + Body struct { + Result response.UserList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DescribeVolumesRaidsRequest.go b/bmp-openapi-console/swaggermodels/DescribeVolumesRaidsRequest.go new file mode 100644 index 0000000..44c8158 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeVolumesRaidsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeVolumesRaids +type DescribeVolumesRaidsRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryVolumesRaidsRequest +} diff --git a/bmp-openapi-console/swaggermodels/DescribeVolumesRaidsResult.go b/bmp-openapi-console/swaggermodels/DescribeVolumesRaidsResult.go new file mode 100644 index 0000000..41df11a --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DescribeVolumesRaidsResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeVolumesRaids +type DescribeDeviceTypeRaidsResult struct { + ResponseHeader + // in: body + Body struct { + Result []*responseTypes.VolumeRaids `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DesrcibeAgentStatusRequest.go b/bmp-openapi-console/swaggermodels/DesrcibeAgentStatusRequest.go new file mode 100644 index 0000000..2bf9749 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DesrcibeAgentStatusRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters desrcibeAgentStatus +type DesrcibeAgentStatusRequest struct { + ReadRequestHeader + + // in: query + requestTypes.DesrcibeAgentStatusRequest +} diff --git a/bmp-openapi-console/swaggermodels/DesrcibeAgentStatusResult.go b/bmp-openapi-console/swaggermodels/DesrcibeAgentStatusResult.go new file mode 100644 index 0000000..445b3a1 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DesrcibeAgentStatusResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response desrcibeAgentStatus +type DesrcibeAgentStatusResult struct { + ResponseHeader + // in: body + Body struct { + Result responseTypes.AgentStatusResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DesrcibeTagsRequest.go b/bmp-openapi-console/swaggermodels/DesrcibeTagsRequest.go new file mode 100644 index 0000000..ec0ca85 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DesrcibeTagsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters desrcibeTags +type DesrcibeTagsRequest struct { + ReadRequestHeader + + // in: query + requestTypes.DesrcibeTagsRequest +} diff --git a/bmp-openapi-console/swaggermodels/DesrcibeTagsResult.go b/bmp-openapi-console/swaggermodels/DesrcibeTagsResult.go new file mode 100644 index 0000000..a849b89 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DesrcibeTagsResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response desrcibeTags +type DesrcibeTagsResult struct { + ResponseHeader + // in: body + Body struct { + Result responseTypes.TagsResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/DisableRuleRequest.go b/bmp-openapi-console/swaggermodels/DisableRuleRequest.go new file mode 100644 index 0000000..6bd6c89 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DisableRuleRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters disableRule +type DisableRuleRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.DisableRuleRequest +} diff --git a/bmp-openapi-console/swaggermodels/DisableRuleResult.go b/bmp-openapi-console/swaggermodels/DisableRuleResult.go new file mode 100644 index 0000000..6686f8f --- /dev/null +++ b/bmp-openapi-console/swaggermodels/DisableRuleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DisableRuleResult is an response struct that is used to describe create rule result. +// swagger:response disableRule +type DisableRuleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/EditRuleRequest.go b/bmp-openapi-console/swaggermodels/EditRuleRequest.go new file mode 100644 index 0000000..39611f1 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/EditRuleRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters editRule +type EditRuleRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.EditRuleRequest +} diff --git a/bmp-openapi-console/swaggermodels/EditRuleResult.go b/bmp-openapi-console/swaggermodels/EditRuleResult.go new file mode 100644 index 0000000..3b0b23c --- /dev/null +++ b/bmp-openapi-console/swaggermodels/EditRuleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A EditRuleResult is an response struct that is used to describe create rule result. +// swagger:response editRule +type EditRuleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/EnableRuleRequest.go b/bmp-openapi-console/swaggermodels/EnableRuleRequest.go new file mode 100644 index 0000000..dc267df --- /dev/null +++ b/bmp-openapi-console/swaggermodels/EnableRuleRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters enableRule +type EnableRuleRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.EnableRuleRequest +} diff --git a/bmp-openapi-console/swaggermodels/EnableRuleResult.go b/bmp-openapi-console/swaggermodels/EnableRuleResult.go new file mode 100644 index 0000000..a7b2cbb --- /dev/null +++ b/bmp-openapi-console/swaggermodels/EnableRuleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A EnableRuleResult is an response struct that is used to describe create rule result. +// swagger:response enableRule +type EnableRuleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/GetInstancesBySshkeyRequest.go b/bmp-openapi-console/swaggermodels/GetInstancesBySshkeyRequest.go new file mode 100644 index 0000000..83a98c0 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/GetInstancesBySshkeyRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters getInstancesBySshkey +type GetInstancesBySshkey struct { + ReadRequestHeader + + // in: path + SshkeyID string `json:"sshkey_id"` +} diff --git a/bmp-openapi-console/swaggermodels/GetInstancesBySshkeyResult.go b/bmp-openapi-console/swaggermodels/GetInstancesBySshkeyResult.go new file mode 100644 index 0000000..2c8c154 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/GetInstancesBySshkeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetInstancesBySshkeyResult is an response struct that is used to get instance list by sshkey. +// swagger:response getInstancesBySshkey +type GetInstancesBySshkeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.InstancesSshkeyInfoResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/GetMessageByIdRequest.go b/bmp-openapi-console/swaggermodels/GetMessageByIdRequest.go new file mode 100644 index 0000000..cd54637 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/GetMessageByIdRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters getMessageById +type GetMessageByIdRequest struct { + ReadRequestHeader + + // in: query + requestTypes.GetMessageByIdRequest +} diff --git a/bmp-openapi-console/swaggermodels/GetMessageByIdResult.go b/bmp-openapi-console/swaggermodels/GetMessageByIdResult.go new file mode 100644 index 0000000..8397377 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/GetMessageByIdResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// swagger:response getMessageById +type GetMessageByIdResult struct { + ResponseHeader + // in: body + Body struct { + Result response.MessageWithNextPrev `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/GetMessageListRequest.go b/bmp-openapi-console/swaggermodels/GetMessageListRequest.go new file mode 100644 index 0000000..9b5dce3 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/GetMessageListRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters getMessageList +type GetMessageListRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryMessagesRequest +} diff --git a/bmp-openapi-console/swaggermodels/GetMessageListResult.go b/bmp-openapi-console/swaggermodels/GetMessageListResult.go new file mode 100644 index 0000000..d43b5cf --- /dev/null +++ b/bmp-openapi-console/swaggermodels/GetMessageListResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// swagger:response getMessageList +type GetMessageListResult struct { + ResponseHeader + // in: body + Body struct { + Result response.MessageList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/GetMessageStatisticRequest.go b/bmp-openapi-console/swaggermodels/GetMessageStatisticRequest.go new file mode 100644 index 0000000..4d1cbcd --- /dev/null +++ b/bmp-openapi-console/swaggermodels/GetMessageStatisticRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters getMessageStatistic +type GetMessageStatisticRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi-console/swaggermodels/GetMessageStatisticResult.go b/bmp-openapi-console/swaggermodels/GetMessageStatisticResult.go new file mode 100644 index 0000000..4f65e6b --- /dev/null +++ b/bmp-openapi-console/swaggermodels/GetMessageStatisticResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// swagger:response getMessageStatistic +type GetMessageStatisticResult struct { + ResponseHeader + // in: body + Body struct { + Result response.MessageStatistic `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/GetMessageTypesRequest.go b/bmp-openapi-console/swaggermodels/GetMessageTypesRequest.go new file mode 100644 index 0000000..bfb50d2 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/GetMessageTypesRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters getMessageTypes +type GetMessageTypesRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi-console/swaggermodels/GetMessageTypesResult.go b/bmp-openapi-console/swaggermodels/GetMessageTypesResult.go new file mode 100644 index 0000000..adc3404 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/GetMessageTypesResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// swagger:response getMessageTypes +type GetMessageTypesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.MessageTypesResp `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/GetMonitorDataRequest.go b/bmp-openapi-console/swaggermodels/GetMonitorDataRequest.go new file mode 100644 index 0000000..84a40fa --- /dev/null +++ b/bmp-openapi-console/swaggermodels/GetMonitorDataRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters getMonitorData +type GetMonitorDataRequest struct { + ReadRequestHeader + + // in: query + requestTypes.GetMonitorDataRequest +} diff --git a/bmp-openapi-console/swaggermodels/GetMonitorDataResult.go b/bmp-openapi-console/swaggermodels/GetMonitorDataResult.go new file mode 100644 index 0000000..4947f8c --- /dev/null +++ b/bmp-openapi-console/swaggermodels/GetMonitorDataResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response getMonitorData +type GetMonitorDataResult struct { + ResponseHeader + // in: body + Body struct { + Result []*responseTypes.DataEveryMetric `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/HasUnreadMessageRequest.go b/bmp-openapi-console/swaggermodels/HasUnreadMessageRequest.go new file mode 100644 index 0000000..6a215ba --- /dev/null +++ b/bmp-openapi-console/swaggermodels/HasUnreadMessageRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters hasUnreadMessage +type HasUnreadMessageRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi-console/swaggermodels/HasUnreadMessageResult.go b/bmp-openapi-console/swaggermodels/HasUnreadMessageResult.go new file mode 100644 index 0000000..b170e87 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/HasUnreadMessageResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response hasUnreadMessage +type HasUnreadMessageResult struct { + ResponseHeader + // in: body + Body struct { + Result response.HasUnreadMessage `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/LockProjectInstanceRequest.go b/bmp-openapi-console/swaggermodels/LockProjectInstanceRequest.go new file mode 100644 index 0000000..552fe7c --- /dev/null +++ b/bmp-openapi-console/swaggermodels/LockProjectInstanceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters lockProjectInstance +type LockProjectInstanceRequest struct { + WriteRequestHeader + + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi-console/swaggermodels/LockProjectInstanceResult.go b/bmp-openapi-console/swaggermodels/LockProjectInstanceResult.go new file mode 100644 index 0000000..8c86466 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/LockProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A LockProjectInstanceResult is an response struct that is used to describe lock instance result. +// swagger:response lockProjectInstance +type LockProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ModifyInstancesRequest.go b/bmp-openapi-console/swaggermodels/ModifyInstancesRequest.go new file mode 100644 index 0000000..a3e81ad --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyInstancesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyInstances +type ModifyInstancesRequest struct { + ReadRequestHeader + + // in: body + Body requestTypes.ModifyInstancesRequest +} diff --git a/bmp-openapi-console/swaggermodels/ModifyInstancesResult.go b/bmp-openapi-console/swaggermodels/ModifyInstancesResult.go new file mode 100644 index 0000000..865968d --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyInstancesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyInstancesResult is an response struct that is used to describe modify instance result. +// swagger:response modifyInstances +type ModifyInstancesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ModifyLocalUserPasswordRequest.go b/bmp-openapi-console/swaggermodels/ModifyLocalUserPasswordRequest.go new file mode 100644 index 0000000..32b1514 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyLocalUserPasswordRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyLocalUserPassword +type ModifyLocalUserPasswordRequest struct { + ReadRequestHeader + + // in: body + Body requestTypes.ModifyUserPasswordRequest +} diff --git a/bmp-openapi-console/swaggermodels/ModifyLocalUserPasswordResult.go b/bmp-openapi-console/swaggermodels/ModifyLocalUserPasswordResult.go new file mode 100644 index 0000000..a7286b3 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyLocalUserPasswordResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyLocalUserPasswordResult is an response struct that is used to describe getuser. +// swagger:response modifyLocalUserPassword +type ModifyLocalUserPasswordResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ModifyLocalUserRequest.go b/bmp-openapi-console/swaggermodels/ModifyLocalUserRequest.go new file mode 100644 index 0000000..f99b952 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyLocalUserRequest.go @@ -0,0 +1,12 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyLocalUser +type ModifyLocalUserRequest struct { + ReadRequestHeader + // in: body + Body requestTypes.ModifyLocalUserRequest +} diff --git a/bmp-openapi-console/swaggermodels/ModifyLocalUserResult.go b/bmp-openapi-console/swaggermodels/ModifyLocalUserResult.go new file mode 100644 index 0000000..34c8354 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyLocalUserResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyLocalUserResult is an response struct that is used to describe getuser. +// swagger:response modifyLocalUser +type ModifyLocalUserResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ModifyProjectInstanceRequest.go b/bmp-openapi-console/swaggermodels/ModifyProjectInstanceRequest.go new file mode 100644 index 0000000..f5bf73f --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyProjectInstanceRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyProjectInstance +type ModifyProjectInstanceRequest struct { + ReadRequestHeader + + // in: path + InstanceID string `json:"instance_id"` + + // in: body + Body requestTypes.ModifyInstanceRequest +} diff --git a/bmp-openapi-console/swaggermodels/ModifyProjectInstanceResult.go b/bmp-openapi-console/swaggermodels/ModifyProjectInstanceResult.go new file mode 100644 index 0000000..270af3a --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyProjectInstanceResult is an response struct that is used to describe modify instance result. +// swagger:response modifyProjectInstance +type ModifyProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ModifyUserApikeyRequest.go b/bmp-openapi-console/swaggermodels/ModifyUserApikeyRequest.go new file mode 100644 index 0000000..037f72c --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyUserApikeyRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyUserApikey +type ModifyUserApikeyRequest struct { + ReadRequestHeader + + // in: path + ApikeyID string `json:"apikey_id"` + + // in: body + Body requestTypes.ModifyApikeyRequest +} diff --git a/bmp-openapi-console/swaggermodels/ModifyUserApikeyResult.go b/bmp-openapi-console/swaggermodels/ModifyUserApikeyResult.go new file mode 100644 index 0000000..8004193 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyUserApikeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyUserApikeyResult is an response struct that is used to describe modifyApikey result. +// swagger:response modifyUserApikey +type ModifyUserApikeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ModifyUserProjectDescriptionRequest.go b/bmp-openapi-console/swaggermodels/ModifyUserProjectDescriptionRequest.go new file mode 100644 index 0000000..b6e91d5 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyUserProjectDescriptionRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyUserProjectDescription +type ModifyUserProjectDescriptionRequest struct { + WriteRequestHeader + + // in: path + ProjectID string `json:"project_id"` + + // in: body + Body requestTypes.ModifyProjectDescriptionRequest +} diff --git a/bmp-openapi-console/swaggermodels/ModifyUserProjectDescriptionResult.go b/bmp-openapi-console/swaggermodels/ModifyUserProjectDescriptionResult.go new file mode 100644 index 0000000..57f88de --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyUserProjectDescriptionResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response modifyUserProjectDescription +type ModifyUserProjectDescriptionResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ModifyUserProjectRequest.go b/bmp-openapi-console/swaggermodels/ModifyUserProjectRequest.go new file mode 100644 index 0000000..5ec6aca --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyUserProjectRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyUserProject +type ModifyUserProjectRequest struct { + ReadRequestHeader + + // in: path + ProjectID string `json:"project_id"` + + // in: body + Body requestTypes.ModifyProjectRequest +} diff --git a/bmp-openapi-console/swaggermodels/ModifyUserProjectResult.go b/bmp-openapi-console/swaggermodels/ModifyUserProjectResult.go new file mode 100644 index 0000000..708d240 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyUserProjectResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response modifyUserProject +type ModifyUserProjectResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ModifyUserRequest.go b/bmp-openapi-console/swaggermodels/ModifyUserRequest.go new file mode 100644 index 0000000..885448a --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyUserRequest.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyUser +type ModifyUserRequest struct { + ReadRequestHeader + + // in: path + UserID string `json:"user_id"` + // in: body + Body requestTypes.ModifyUserRequest +} diff --git a/bmp-openapi-console/swaggermodels/ModifyUserResult.go b/bmp-openapi-console/swaggermodels/ModifyUserResult.go new file mode 100644 index 0000000..4316a00 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyUserResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetUserResult is an response struct that is used to describe getuser. +// swagger:response modifyUser +type ModifyUserResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ModifyUserSshkeyRequest.go b/bmp-openapi-console/swaggermodels/ModifyUserSshkeyRequest.go new file mode 100644 index 0000000..2b77a37 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyUserSshkeyRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyUserSshkey +type ModifyUserSshkeyRequest struct { + WriteRequestHeader + + // in: path + SshkeyID string `json:"sshkey_id"` + + // in: body + Body requestTypes.ModifySshkeyRequest +} diff --git a/bmp-openapi-console/swaggermodels/ModifyUserSshkeyResult.go b/bmp-openapi-console/swaggermodels/ModifyUserSshkeyResult.go new file mode 100644 index 0000000..6fe8595 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ModifyUserSshkeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyUserSshkeyResult is an response struct that is used to modify sshkey result. +// swagger:response modifyUserSshkey +type ModifyUserSshkeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/MoveInstanceRequest.go b/bmp-openapi-console/swaggermodels/MoveInstanceRequest.go new file mode 100644 index 0000000..acdd64f --- /dev/null +++ b/bmp-openapi-console/swaggermodels/MoveInstanceRequest.go @@ -0,0 +1,12 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters moveUserInstances +type MoveInstanceRequest struct { + WriteRequestHeader + // in: body + Body requestTypes.MoveInstancesRequest +} diff --git a/bmp-openapi-console/swaggermodels/MoveInstanceResult.go b/bmp-openapi-console/swaggermodels/MoveInstanceResult.go new file mode 100644 index 0000000..b8e806a --- /dev/null +++ b/bmp-openapi-console/swaggermodels/MoveInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A MoveInstanceResult is an response struct +// swagger:response moveUserInstances +type MoveInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/MoveProjectRequest.go b/bmp-openapi-console/swaggermodels/MoveProjectRequest.go new file mode 100644 index 0000000..a781142 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/MoveProjectRequest.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters moveUserProject +type MoveProjectRequest struct { + WriteRequestHeader + // in: path + ProjectID string `json:"project_id"` + // in: body + Body requestTypes.MoveProjectRequest +} diff --git a/bmp-openapi-console/swaggermodels/MoveProjectResult.go b/bmp-openapi-console/swaggermodels/MoveProjectResult.go new file mode 100644 index 0000000..4549408 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/MoveProjectResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A MoveProjectResult is an response struct +// swagger:response moveUserProject +type MoveProjectResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ReStartInstancesResult.go b/bmp-openapi-console/swaggermodels/ReStartInstancesResult.go new file mode 100644 index 0000000..1c4a709 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ReStartInstancesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A RestartInstancesResult is an response struct +// swagger:response restartInstances +type RestartInstancesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ReadMessageRequest.go b/bmp-openapi-console/swaggermodels/ReadMessageRequest.go new file mode 100644 index 0000000..98d6927 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ReadMessageRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters readMessage +type ReadMessageRequest struct { + WriteRequestHeader + + // in: body + Body requestTypes.ReadMessagesRequest +} diff --git a/bmp-openapi-console/swaggermodels/ReadMessageResult.go b/bmp-openapi-console/swaggermodels/ReadMessageResult.go new file mode 100644 index 0000000..e6b5f7e --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ReadMessageResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ReadMessageResult is an response struct +// swagger:response readMessage +type ReadMessageResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ReinstallProjectInstanceRequest.go b/bmp-openapi-console/swaggermodels/ReinstallProjectInstanceRequest.go new file mode 100644 index 0000000..99bae52 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ReinstallProjectInstanceRequest.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters reinstallProjectInstance +type ReinstallProjectInstanceRequest struct { + ReadRequestHeader + + // in: path + InstanceID string `json:"instance_id"` + // in: body + Body requestTypes.ReinstallInstanceRequest +} diff --git a/bmp-openapi-console/swaggermodels/ReinstallProjectInstanceResult.go b/bmp-openapi-console/swaggermodels/ReinstallProjectInstanceResult.go new file mode 100644 index 0000000..4a5fe1a --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ReinstallProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ReinstallProjectInstanceResult is an response struct that is used to describe reinstall instance. +// swagger:response reinstallProjectInstance +type ReinstallProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ResetInstancePasswdRequest.go b/bmp-openapi-console/swaggermodels/ResetInstancePasswdRequest.go new file mode 100644 index 0000000..362ab08 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ResetInstancePasswdRequest.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters resetProjectInstancePasswd +type ResetInstancePasswdRequest struct { + ReadRequestHeader + + // in: path + InstanceID string `json:"instance_id"` + // in: body + Body requestTypes.ResetInstancePasswdRequest +} diff --git a/bmp-openapi-console/swaggermodels/ResetInstancePasswdResult.go b/bmp-openapi-console/swaggermodels/ResetInstancePasswdResult.go new file mode 100644 index 0000000..5422dd7 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ResetInstancePasswdResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ResetProjectInstancePasswdResult is an response struct that is used to describe reset instance password. +// swagger:response resetProjectInstancePasswd +type ResetProjectInstancePasswdResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ResetInstanceStatusRequest.go b/bmp-openapi-console/swaggermodels/ResetInstanceStatusRequest.go new file mode 100644 index 0000000..be85f4e --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ResetInstanceStatusRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters resetInstanceStatus +type ResetInstanceStatusRequest struct { + WriteRequestHeader + + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi-console/swaggermodels/ResetInstanceStatusResult.go b/bmp-openapi-console/swaggermodels/ResetInstanceStatusResult.go new file mode 100644 index 0000000..03581d0 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ResetInstanceStatusResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ResetInstanceStatusResult is an response struct that is used to describe restart instance result. +// swagger:response resetInstanceStatus +type ResetInstanceStatusResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ResetInstancesPasswdRequest.go b/bmp-openapi-console/swaggermodels/ResetInstancesPasswdRequest.go new file mode 100644 index 0000000..f3aba53 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ResetInstancesPasswdRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters resetProjectInstancesPasswd +type ResetProjectInstancesPasswdRequest struct { + WriteRequestHeader + + // in: body + Body requestTypes.ResetInstancesPasswdRequest +} diff --git a/bmp-openapi-console/swaggermodels/ResetInstancesPasswdResult.go b/bmp-openapi-console/swaggermodels/ResetInstancesPasswdResult.go new file mode 100644 index 0000000..416fe91 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ResetInstancesPasswdResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ResetProjectInstancesPasswdResult is an response struct that is used to describe reset instance password. +// swagger:response resetProjectInstancesPasswd +type ResetProjectInstancesPasswdResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/RestartInstancesRequest.go b/bmp-openapi-console/swaggermodels/RestartInstancesRequest.go new file mode 100644 index 0000000..7b317af --- /dev/null +++ b/bmp-openapi-console/swaggermodels/RestartInstancesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters startInstances +type StartInstancesRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.StartInstancesRequest +} diff --git a/bmp-openapi-console/swaggermodels/RestartProjectInstanceRequest.go b/bmp-openapi-console/swaggermodels/RestartProjectInstanceRequest.go new file mode 100644 index 0000000..109d436 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/RestartProjectInstanceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters restartProjectInstance +type RestartProjectInstanceRequest struct { + WriteRequestHeader + + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi-console/swaggermodels/RestartProjectInstanceResult.go b/bmp-openapi-console/swaggermodels/RestartProjectInstanceResult.go new file mode 100644 index 0000000..bf11a02 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/RestartProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A RestartProjectInstanceResult is an response struct that is used to describe restart instance result. +// swagger:response restartProjectInstance +type RestartProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/ShareUserProjectRequest.go b/bmp-openapi-console/swaggermodels/ShareUserProjectRequest.go new file mode 100644 index 0000000..6389d71 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ShareUserProjectRequest.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters shareUserProject +type ShareUserProjectRequest struct { + WriteRequestHeader + // in: path + ProjectID string `json:"project_id"` + // in: body + Body requestTypes.ShareProjectRequest +} diff --git a/bmp-openapi-console/swaggermodels/ShareUserProjectResult.go b/bmp-openapi-console/swaggermodels/ShareUserProjectResult.go new file mode 100644 index 0000000..c79aa9e --- /dev/null +++ b/bmp-openapi-console/swaggermodels/ShareUserProjectResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ShareUserProjectResult is an response struct +// swagger:response shareUserProject +type ShareUserProjectResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/StartInstancesRequest.go b/bmp-openapi-console/swaggermodels/StartInstancesRequest.go new file mode 100644 index 0000000..3d04b6a --- /dev/null +++ b/bmp-openapi-console/swaggermodels/StartInstancesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters restartInstances +type RestartInstancesRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.RestartInstancesRequest +} diff --git a/bmp-openapi-console/swaggermodels/StartInstancesResult.go b/bmp-openapi-console/swaggermodels/StartInstancesResult.go new file mode 100644 index 0000000..9871c92 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/StartInstancesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A StartInstancesResult is an response struct +// swagger:response startInstances +type StartInstancesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/StartProjectInstanceRequest.go b/bmp-openapi-console/swaggermodels/StartProjectInstanceRequest.go new file mode 100644 index 0000000..23bfe78 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/StartProjectInstanceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters startProjectInstance +type StartProjectInstanceRequest struct { + WriteRequestHeader + + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi-console/swaggermodels/StartProjectInstanceResult.go b/bmp-openapi-console/swaggermodels/StartProjectInstanceResult.go new file mode 100644 index 0000000..0c175ac --- /dev/null +++ b/bmp-openapi-console/swaggermodels/StartProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A StartProjectInstanceResult is an response struct that is used to describe start instance result. +// swagger:response startProjectInstance +type StartProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/StopInstancesRequest.go b/bmp-openapi-console/swaggermodels/StopInstancesRequest.go new file mode 100644 index 0000000..9ffc38b --- /dev/null +++ b/bmp-openapi-console/swaggermodels/StopInstancesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters stopInstances +type StopInstancesRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.StopInstancesRequest +} diff --git a/bmp-openapi-console/swaggermodels/StopInstancesResult.go b/bmp-openapi-console/swaggermodels/StopInstancesResult.go new file mode 100644 index 0000000..a2a250d --- /dev/null +++ b/bmp-openapi-console/swaggermodels/StopInstancesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A StopInstancesResult is an response struct +// swagger:response stopInstances +type StopInstancesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/StopProjectInstanceRequest.go b/bmp-openapi-console/swaggermodels/StopProjectInstanceRequest.go new file mode 100644 index 0000000..8a583ab --- /dev/null +++ b/bmp-openapi-console/swaggermodels/StopProjectInstanceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters stopProjectInstance +type StopProjectInstanceRequest struct { + WriteRequestHeader + + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi-console/swaggermodels/StopProjectInstanceResult.go b/bmp-openapi-console/swaggermodels/StopProjectInstanceResult.go new file mode 100644 index 0000000..b4cb42e --- /dev/null +++ b/bmp-openapi-console/swaggermodels/StopProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A StopProjectInstanceResult is an response struct that is used to describe stop instance result. +// swagger:response stopProjectInstance +type StopProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/UnLockProjectInstanceRequest.go b/bmp-openapi-console/swaggermodels/UnLockProjectInstanceRequest.go new file mode 100644 index 0000000..9c05f2b --- /dev/null +++ b/bmp-openapi-console/swaggermodels/UnLockProjectInstanceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters unLockProjectInstance +type UnLockProjectInstanceResultRequest struct { + WriteRequestHeader + + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi-console/swaggermodels/UnLockProjectInstanceResult.go b/bmp-openapi-console/swaggermodels/UnLockProjectInstanceResult.go new file mode 100644 index 0000000..702301a --- /dev/null +++ b/bmp-openapi-console/swaggermodels/UnLockProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A UnLockProjectInstanceResult is an response struct that is used to describe unlock instance result. +// swagger:response unLockProjectInstance +type UnLockProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/VerifyUserRequest.go b/bmp-openapi-console/swaggermodels/VerifyUserRequest.go new file mode 100644 index 0000000..a5f14a5 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/VerifyUserRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters verifyUser +type VerifyUserRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.VerifyUserRequest +} diff --git a/bmp-openapi-console/swaggermodels/VerifyUserResult.go b/bmp-openapi-console/swaggermodels/VerifyUserResult.go new file mode 100644 index 0000000..01776b5 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/VerifyUserResult.go @@ -0,0 +1,13 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// A VerifyUserResult is an response struct that is used to describe verify user result. +// swagger:response verifyUser +type VerifyUserResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/describeInstancesByProjectIdAndOwnerNameAndSharerNameRequest.go b/bmp-openapi-console/swaggermodels/describeInstancesByProjectIdAndOwnerNameAndSharerNameRequest.go new file mode 100644 index 0000000..98d2970 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/describeInstancesByProjectIdAndOwnerNameAndSharerNameRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeInstancesByProjectIdAndOwnerNameAndSharerName +type DescribeInstancesByProjectIdAndOwnerNameAndSharerNameRequest struct { + ReadRequestHeader + + // in: query + requestTypes.DescribeInstancesByProjectIdAndOwnerNameAndSharerNameRequest +} diff --git a/bmp-openapi-console/swaggermodels/describeInstancesByProjectIdAndOwnerNameAndSharerNameResult.go b/bmp-openapi-console/swaggermodels/describeInstancesByProjectIdAndOwnerNameAndSharerNameResult.go new file mode 100644 index 0000000..39dc6d7 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/describeInstancesByProjectIdAndOwnerNameAndSharerNameResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeInstancesByProjectIdAndOwnerNameAndSharerNameResult is an response struct that is used to get instance list. +// swagger:response describeInstancesByProjectIdAndOwnerNameAndSharerName +type DescribeInstancesByProjectIdAndOwnerNameAndSharerNameResult struct { + ResponseHeader + // in: body + Body struct { + Result response.InstanceForShareList `json:"result"` + } +} diff --git a/bmp-openapi-console/swaggermodels/describeLicenseContentRequest.go b/bmp-openapi-console/swaggermodels/describeLicenseContentRequest.go new file mode 100644 index 0000000..0166995 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/describeLicenseContentRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters describeLicenseContent +type DescribeLicenseContentRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi-console/swaggermodels/describeLocalUserRequest.go b/bmp-openapi-console/swaggermodels/describeLocalUserRequest.go new file mode 100644 index 0000000..494117a --- /dev/null +++ b/bmp-openapi-console/swaggermodels/describeLocalUserRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters describeLocalUser +type DescribeLocalUserRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi-console/swaggermodels/swaggerinfo.go b/bmp-openapi-console/swaggermodels/swaggerinfo.go new file mode 100644 index 0000000..b50c028 --- /dev/null +++ b/bmp-openapi-console/swaggermodels/swaggerinfo.go @@ -0,0 +1,47 @@ +// Package classification CPS +// +// the purpose of this application is to provide an application +// that is using plain go code to define an API +// +// This should demonstrate all the possible comment annotations +// that are available to turn go code into a fully compliant swagger 2.0 spec +// +// Terms Of Service: +// +// there are no TOS at this moment, use at your own risk we take no responsibility +// +// Schemes: http +// Host: bmp-openapi-console.bmp.local +// BasePath: /v1 +// Version: 0.0.1 +// License: MIT http://opensource.org/licenses/MIT +// Contact: minping@jd.com +// +// Consumes: +// - application/json +// - application/xml +// +// Produces: +// - application/json +// - application/xml +// +// Security: +// - api_key: +// +// SecurityDefinitions: +// api_key: +// type: apiKey +// name: bmp-ak +// in: header +// +// Extensions: +// x-meta-value: value +// x-meta-array: +// - value1 +// - value2 +// x-meta-array-obj: +// - name: obj +// value: field +// +// swagger:meta +package swaggermodels diff --git a/bmp-openapi-console/types/request/ApikeyRequest.go b/bmp-openapi-console/types/request/ApikeyRequest.go new file mode 100644 index 0000000..4eed3b0 --- /dev/null +++ b/bmp-openapi-console/types/request/ApikeyRequest.go @@ -0,0 +1,81 @@ +package request + +import ( + "regexp" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateApikeyRequest struct { + // 秘钥对名称 + // required: true + Name string `json:"name" validate:"required"` + // 是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法 + // required: true + ReadOnly int8 `json:"readOnly" validate:"oneof=0 1"` + // Token类型, [system/user] + // required: true + Type string `json:"type" validate:"required,oneof=system user"` +} +type ModifyApikeyRequest struct { + // 秘钥对名称 + // required: true + Name string `json:"name" validate:"required"` // 秘钥对名称 + // 是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法 + // required: true + ReadOnly int8 `json:"readOnly" validate:"oneof=0 1"` +} +type QueryApikeysRequest struct { + Pageable + // 秘钥对名称 + Name string `json:"name"` + // Token类型, [system/user] + Type string `json:"type" validate:"omitempty,oneof=system user"` + // 是否查询全部/导出 + IsAll string `json:"isAll"` +} + +func (req *CreateApikeyRequest) Validate(logger *log.Logger) { + + validate(req, logger) + + if req.ReadOnly != 0 && req.ReadOnly != 1 { + panic(constant.BuildInvalidArgumentWithArgs("readonly范围不正确", "readonly param error")) + } + + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 + specialMatch := regexp.MustCompile("^[\u4e00-\u9fa5_a-zA-Z0-9_-]{1,64}$").MatchString + if !specialMatch(req.Name) { + panic(constant.BuildInvalidArgumentWithArgs("name格式不正确", "Name invalidate")) + } + +} + +func (req *ModifyApikeyRequest) Validate(logger *log.Logger) { + + validate(req, logger) + + if req.ReadOnly != 0 && req.ReadOnly != 1 { + panic(constant.BuildInvalidArgumentWithArgs("readonly范围不正确", "readonly param error")) + } + + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 + specialMatch := regexp.MustCompile("^[\u4e00-\u9fa5_a-zA-Z0-9_-]{1,64}$").MatchString + if !specialMatch(req.Name) { + panic(constant.BuildInvalidArgumentWithArgs("name格式不正确", "Name invalidate")) + } + +} +func (req *QueryApikeysRequest) Validate(logger *log.Logger) { + + validate(req, logger) + if req.Name != "" { + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 + specialMatch := regexp.MustCompile("^[\u4e00-\u9fa5_a-zA-Z0-9_-]{1,64}$").MatchString + if !specialMatch(req.Name) { + panic(constant.BuildInvalidArgumentWithArgs("name格式不正确", "Name invalidate")) + } + } + +} diff --git a/bmp-openapi-console/types/request/AuditLogsRequest.go b/bmp-openapi-console/types/request/AuditLogsRequest.go new file mode 100644 index 0000000..c1921ff --- /dev/null +++ b/bmp-openapi-console/types/request/AuditLogsRequest.go @@ -0,0 +1,25 @@ +package request + +import log "coding.jd.com/aidc-bmp/bmp_log" + +type DescribeAuditLogsRequest struct { + // instance_id + InstanceID string `json:"instance_id" validate:"required"` + // 操作名称 + Operation string `json:"operation"` + // 操作人 + UserName string `json:"username"` + // result + Result string `json:"result"` + // 操作时间下限 + StartTime int `json:"startTime"` + // 操作时间上限 + EndTime int `json:"endTime"` + // 是否显示所有 + IsAll string `json:"isAll"` + Pageable +} + +func (req *DescribeAuditLogsRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi-console/types/request/BaseRequest.go b/bmp-openapi-console/types/request/BaseRequest.go new file mode 100644 index 0000000..f08acce --- /dev/null +++ b/bmp-openapi-console/types/request/BaseRequest.go @@ -0,0 +1,58 @@ +package request + +import ( + "fmt" + "reflect" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" + validator "github.com/go-playground/validator/v10" +) + +type Pageable struct { + // 页码 + PageNumber int64 `json:"pageNumber"` + // 每页数量 + PageSize int64 `json:"pageSize"` +} + +var va = validator.New() + +func InitValidator() { + va.RegisterTagNameFunc(func(fld reflect.StructField) string { + name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] + + // if name == "-" { + // return "" + // } + + return name + }) + + if err := va.RegisterValidation("required_in_ptr", ValidateRequiredInPtr); err != nil { + fmt.Println("required_in_ptr register error!!!") + } else { + fmt.Println("required_in_ptr register success!!!") + } +} + +func ValidateRequiredInPtr(fl validator.FieldLevel) bool { + + return true +} + +func validate(req interface{}, logger *log.Logger) { + if err := va.Struct(req); err != nil { + fmt.Println(err, err.Error()) + logger.Warn("Validate error:", err.Error()) + var e string + v, ok := err.(validator.ValidationErrors) + if !ok { + e = err.Error() + } else { + e = v[0].Field() + } + panic(constant.BuildInvalidArgumentWithArgs(e+" 非法", e+" invalid")) + } +} diff --git a/bmp-openapi-console/types/request/CollectDeviceInfoRequest.go b/bmp-openapi-console/types/request/CollectDeviceInfoRequest.go new file mode 100644 index 0000000..b0413eb --- /dev/null +++ b/bmp-openapi-console/types/request/CollectDeviceInfoRequest.go @@ -0,0 +1,103 @@ +package request + +import ( + "net" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + + log "coding.jd.com/aidc-bmp/bmp_log" + validator "github.com/go-playground/validator/v10" +) + +type CollectDeviceInfoRequest struct { + // 待采集项 + // required: true + Collects []CollectItem `json:"collects" validate:"required"` +} + +type CollectItem struct { + // sn + // required: true + Sn string `json:"sn"` + // 带外IP + // required: true + IloIP string `json:"iloIp"` // 带外管理IP + // 带外账号 + // required: true + IloUser string `json:"iloUser"` // 带外账号 + // 带外密码 + // required: true + IloPassword string `json:"iloPassword"` // 带外账号密码 + // MAC1(eth0) + // required: true + Mac1 string `json:"mac1"` // MAC1(eth0) + // 内网IPV4 + // required: true + PrivateIPv4 string `json:"privateIpv4"` // 内网IPV4 + + // 掩码 + // required: true + Mask string `json:"mask"` + + // 网关地址 + // required: true + Gateway string `json:"gateway"` + + // raid_driver可选参数。传参:sas2ircu,sas3ircu,megacli64,storcli64,perccli64,no_raid。不传参数则只可采集已适配机型,如果未适配则采集失败 + // Extensions: + // x-nullable: true + RaidDriver string `json:"raidDriver"` + // 可选参数。 传参:True, False 。True表示传入的raid_driver值将覆盖已适配机器的raid_driver + // Extensions: + // x-nullable: true + AllowOverride bool `json:"allowOverride"` +} + +func (c *CollectDeviceInfoRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("CollectDeviceInfoRequest Validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } + if c.Collects != nil { + for _, v := range c.Collects { + if v.RaidDriver != "" { + arrs := []string{"sas2ircu", "sas3ircu", "megacli64", "storcli64", "perccli64", "no_raid", "arcconf"} + if !util.InArray(v.RaidDriver, arrs) { + logger.Warn("CollectDeviceInfoRequest Validate error:raid_driver invalid") + panic(constant.BuildInvalidArgumentWithArgs("raid_driver invalid", "raid_driver 非法")) + } + } + if net.ParseIP(v.IloIP) == nil { + logger.Warn("CollectDeviceInfoRequest Validate error:iloip invalid") + panic(constant.BuildInvalidArgumentWithArgs("iloip invalid", "iloip 非法")) + } + if net.ParseIP(v.Mask) == nil { + logger.Warn("CollectDeviceInfoRequest Validate error:mask invalid") + panic(constant.BuildInvalidArgumentWithArgs("mask invalid", "mask 非法")) + } + if net.ParseIP(v.Gateway) == nil { + logger.Warn("CollectDeviceInfoRequest Validate error:gateway invalid") + panic(constant.BuildInvalidArgumentWithArgs("gateway invalid", "gateway 非法")) + } + if v.IloUser == "" { + logger.Warn("CollectDeviceInfoRequest Validate error:ilouser invalid") + panic(constant.BuildInvalidArgumentWithArgs("ilouser invalid", "ilouser 非法")) + } + if v.IloPassword == "" { + logger.Warn("CollectDeviceInfoRequest Validate error:ilopassword invalid") + panic(constant.BuildInvalidArgumentWithArgs("ilopassword invalid", "ilopassword 非法")) + } + if v.Mac1 == "" { + logger.Warn("CollectDeviceInfoRequest Validate error:mac1 invalid") + panic(constant.BuildInvalidArgumentWithArgs("mac1 invalid", "mac1 非法")) + } + if net.ParseIP(v.PrivateIPv4) == nil { + logger.Warn("CollectDeviceInfoRequest Validate error:privateipv4 invalid") + panic(constant.BuildInvalidArgumentWithArgs("privateipv4 invalid", "privateipv4 非法")) + } + + } + } + +} diff --git a/bmp-openapi-console/types/request/CommandsRequest.go b/bmp-openapi-console/types/request/CommandsRequest.go new file mode 100644 index 0000000..9cc0120 --- /dev/null +++ b/bmp-openapi-console/types/request/CommandsRequest.go @@ -0,0 +1,36 @@ +package request + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" + "github.com/go-playground/validator/v10" +) + +type CancelCommandsRequest struct { + Sn string `json:"sn"` +} +type RetryCommandRequest struct { + OffsetCommandId *int64 `json:"offset_command_id" validate:"required"` +} + +func (c *RetryCommandRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("RetryCommandRequest.Validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } +} + +type QueryCommandsRequest struct { + RequestId string + Sn string + InstanceId string + PageNumber int + PageSize int +} + +func (c *QueryCommandsRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("QueryCommandsRequest.Validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } +} diff --git a/bmp-openapi-console/types/request/DeviceExcelBean.go b/bmp-openapi-console/types/request/DeviceExcelBean.go new file mode 100644 index 0000000..a5871af --- /dev/null +++ b/bmp-openapi-console/types/request/DeviceExcelBean.go @@ -0,0 +1,18 @@ +package request + +type DeviceExcelBean struct { + Id int `xlsx:"0"` //序号 + Region string `xlsx:"1"` //region + Az string `xlsx:"2"` //az + Sn string `xlsx:"3"` //SN号 + SystemIp string `xlsx:"4"` //系统IP + IloIp string `xlsx:"5"` //管理IP + DeviceType string `xlsx:"6"` //型号 + Cabinet string `xlsx:"7"` //机柜 + UPosition string `xlsx:"8"` //U位 + Mac1 string `xlsx:"9"` //mac1 + Mac2 string `xlsx:"10"` //mac2 + SwitchIp string `xlsx:"11"` //switchIp +} + +var DeviceExcelColumn []string = []string{"序号", "region", "az", "SN号", "系统IP", "管理IP", "型号", "机柜", "U位", "Mac1", "Mac2", "switchIP"} diff --git a/bmp-openapi-console/types/request/DeviceRequest.go b/bmp-openapi-console/types/request/DeviceRequest.go new file mode 100644 index 0000000..7cc61a8 --- /dev/null +++ b/bmp-openapi-console/types/request/DeviceRequest.go @@ -0,0 +1,186 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateDevicesRequest struct { + // 机房uuid + // required: true + IDcID string `json:"idcId" validate:"required"` // 机房uuid + // 机型uuid + // required: true + DeviceTypeID string `json:"deviceTypeId" validate:"required"` // 设备类型uuid + // 设备信息 + // required: true + Devices []*CreateDeviceSpec `json:"devices" validate:"required"` +} + +func (req *CreateDevicesRequest) Validate(logger *log.Logger) { + //validate(req, logger) + //if err := validator.New().Struct(c); err != nil { + // logger.Warn("CreateDevicesRequest.Validate error:", err.Error()) + // panic(constant.INVALID_ARGUMENT) + //} + for _, v := range req.Devices { //符合属性需要单独调用 + v.Validate(logger) + } +} + +type CreateDeviceSpec struct { + InstanceID string `json:"instanceId"` // 实例id + // 设备SN + // required: true + Sn string `json:"sn" validate:"required,min=1,max=128"` // 设备SN + // 设备状态,默认已入库 + ManageStatus string `json:"manageStatus"` // 设备状态: 未装机,已装机 + // 品牌 + // required: true + Brand string `json:"brand" validate:"required,min=1,max=128"` //品牌 + // 型号 + // required: true + Model string `json:"model" validate:"required,min=1,max=128"` //型号 + // 机柜编码 + // required: true + Cabinet string `json:"cabinet" validate:"required,min=1,max=128"` // 机柜编码 + // 所在U位 + // required: true + UPosition string `json:"uPosition" validate:"required,min=1,max=128"` // U位 + // 带外IP + // required: true + IloIP string `json:"iloIp" validate:"required,min=1,max=128"` // 带外管理IP + // 带外账号 + IloUser string `json:"iloUser"` // 带外账号 + // 带外密码 + IloPassword string `json:"iloPassword"` // 带外账号密码 + // MAC1(eth0) + // required: true + Mac1 string `json:"mac1" validate:"required,min=1,max=128"` // MAC1(eth0) + // MAC2(eth1) + // required: true + Mac2 string `json:"mac2" validate:"required,min=1,max=128"` // MAC2(eth1) + // 交换机1ip + // required: true + SwitchIP1 string `json:"switchIp1" validate:"required,min=1,max=128"` // 交换机1ip + // 交换机1port + // required: true + SwitchPort1 string `json:"switchPort1" validate:"required,min=1,max=128"` // 交换机1port + // 交换机2ip + // required: true + SwitchIP2 string `json:"switchIp2" validate:"required,min=1,max=128"` // 交换机2ip + // 交换机2port + // required: true + SwitchPort2 string `json:"switchPort2" validate:"required,min=1,max=128"` // 交换机2port + // 交换机1登录账号 + SwitchUser1 string `json:"switchUser1"` // 交换机1登录账号,如果为空,取所在机房的值 + // 交换机1登录密码 + SwitchPassword1 string `json:"switchPassword1"` // 交换机1登录密码 + // 交换机2登录账号 + SwitchUser2 string `son:"switchUser2"` // 交换机2登录账号,如果为空,取所在机房的值 + // 交换机2登录密码 + SwitchPassword2 string `json:"switchPassword2"` // 交换机2登录密码 + // 描述 + Description string `json:"description"` // 描述 + // 网口交换机IP + SwitchIP string `json:"switchIp"` // 网口交换机IP + // 子网掩码 + // required: true + Mask string `json:"mask" validate:"required,min=1,max=128"` // 子网掩码 + // 网关地址 + // required: true + Gateway string `json:"gateway" validate:"required,min=1,max=128"` // 网关地址 + // 内网IPV4 + // required: true + PrivateIPv4 string `json:"privateIpv4" validate:"required,min=1,max=128"` // 内网IPV4 + // 内网IPV6 + PrivateIPv6 string `json:"privateIpv6"` // 内网IPV6 + // adapter_id + // required: true + AdapterID *int `json:"adapterId" validate:"required,min=0,max=10000"` // adapter_id + // raid工具:(megacli128等) + RaidDriver string `json:"raidDriver" validate:"max=64"` // raid工具:(megacli128等) + // 系统盘1背板号 + // required: true + Enclosure1 string `json:"enclosure1" validate:"required,min=0,max=10000"` //系统盘1背板号 + // 系统盘1槽位 + // required: true + Slot1 *int `json:"slot1" validate:"required,min=0,max=10000"` //系统盘1槽位 + // 系统盘2背板号 + Enclosure2 string `json:"Enclosure2" validate:"max=64"` //系统盘2背板号 + // 系统盘2槽位 + Slot2 int `json:"slot2" validate:"max=10000"` //系统盘2槽位 + //以后还能还有数据盘,todo +} + +func (req *CreateDeviceSpec) Validate(logger *log.Logger) { + validate(req, logger) +} + +type ModifyAllDevicesRequest struct { + InstanceID string `json:"instanceId"` // 实例id + ManageStatus string `json:"manageStatus"` + UserId string `json:"userId"` + UserName string `json:"userName"` +} +type ModifyDevicesRequest struct { + // 修改设备描述 + // Extensions: + // x-nullable: true + Description *string `json:"description" validate:"omitempty,max=256"` +} + +func (req *ModifyDevicesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type MountDevicesRequest struct { + // 设备uuid + // required: true + DeviceID string `json:"deviceId" validate:"required"` +} + +func (req *MountDevicesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type UnMountDevicesRequest struct { + // 设备uuid + // required: true + DeviceID string `json:"deviceId" validate:"required"` +} + +func (req *UnMountDevicesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryDevicesRequest struct { + Pageable + // 机房id + IDcID string `json:"idcId"` + // 设备sn + Sn string `json:"sn"` + // 实例id + InstanceID string `json:"instanceId"` + // 机型id + DeviceTypeID string `json:"deviceTypeId"` + // 设备管理状态 + ManageStatus string `json:"manageStatus"` + // 带外ip + IloIP string `json:"iloIp"` + // ipv4 + IPV4 string `json:"ipv4"` + // ipv6 + IPV6 string `json:"ipv6"` + // 机型类型 + DeviceSeries string `json:"deviceSeries"` + // 所属用户id + UserID string `json:"userId"` + // 所属用户 + UserName string `json:"userName"` + // 是否显示全部,1不分页 + IsAll string `json:"isAll"` +} + +func (req *QueryDevicesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi-console/types/request/DeviceTypeRaidRequest.go b/bmp-openapi-console/types/request/DeviceTypeRaidRequest.go new file mode 100644 index 0000000..e48cfe9 --- /dev/null +++ b/bmp-openapi-console/types/request/DeviceTypeRaidRequest.go @@ -0,0 +1,39 @@ +package request + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" + "github.com/go-playground/validator/v10" +) + +type CreateDeviceTypeRaidRequest struct { + RaidID string `json:"raidId"` + DeviceType string `json:"deviceType"` + DeviceTypeID string `json:"DeviceTypeId"` + VolumeType string `json:"volumeType"` + VolumeDetail string `json:"volumeDetail"` + AvailableValue int `json:"availableValue"` + SystemPartitionCount int `json:"systemPartitionCount"` + DiskType string `json:"diskType"` +} + +func (c *CreateDeviceTypeRaidRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("CreateDeviceTypeRaidRequest.Validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } +} + +type DeleteDeviceTypeRaidRequest struct { + RaidId string `json:"raidId"` + DeviceType string `json:"deviceType"` + VolumeType string `json:"volumeType"` + VolumeDetail string `json:"volumeDetail"` +} + +func (c *DeleteDeviceTypeRaidRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("DeleteDeviceTypeRaidRequest.Validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } +} diff --git a/bmp-openapi-console/types/request/DeviceTypeRequest.go b/bmp-openapi-console/types/request/DeviceTypeRequest.go new file mode 100644 index 0000000..b3f712f --- /dev/null +++ b/bmp-openapi-console/types/request/DeviceTypeRequest.go @@ -0,0 +1,502 @@ +package request + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateDeviceTypeRequest struct { + // 机房id + // required: true + IDcID string `json:"idcId"` + // 机型名称1-64 + // required: true + Name string `json:"name" validate:"required,min=1,max=64"` + // 机型规格1-64 + // required: true + DeviceType string `json:"deviceType" validate:"required,min=1,max=64"` + // 机型类型,如computer storage gpu other + // required: true + DeviceSeries string `json:"deviceSeries" validate:"required,oneof=computer storage gpu other"` + // 体系架构,1-64 + // required: true + Architecture string `json:"architecture" validate:"required,oneof=x86_64 ARM64(aarch64) i386"` + // 【高度(U)】:显示机型高度 2,4 + // required: true + Height int `json:"height" validate:"required,oneof=2 4"` + // 描述0-256 + Description string `json:"description" validate:"max=256"` + // cpu数量1,10000 + // required: true + CPUAmount int `json:"cpuAmount" validate:"required,min=1,max=10000"` + // 单个cpu内核数1,10000 + // required: true + CPUCores int `json:"cpuCores" validate:"required,min=1,max=10000"` + // cpu厂商1-64 + // required: true + CPUManufacturer string `json:"cpuManufacturer" validate:"required,min=1,max=64"` + // cpu处理器型号1-64 + // required: true + CPUModel string `json:"cpuModel" validate:"required,min=1,max=64"` + // cpu频率(G)1-64 + // required: true + CPUFrequency string `json:"cpuFrequency" validate:"required,min=1,max=64"` + // 内存接口(DDR DDR2 DDR3 DDR4 DDR5) + // required: true + MemType string `json:"memType" validate:"required,oneof=DDR DDR2 DDR3 DDR4 DDR5"` + // 单个内存大小1,10000(GB) + // required: true + MemSize int `json:"memSize" validate:"required,min=1,max=10000"` + // 内存数量1-10000 + // required: true + MemAmount int `json:"memAmount" validate:"required,min=1,max=10000"` + // 内存主频(MHz)1-10000 + // required: true + MemFrequency int `json:"memFrequency" validate:"required,min=1,max=10000"` + // 网卡数量1-10000 + // required: true + NicAmount int `json:"nicAmount" validate:"required,min=1,max=10000"` + // 网卡传输速率(GE) 1-10000 + // required: true + NicRate int `json:"nicRate" validate:"required,min=1,max=10000"` + // 【网口模式】【网络设置】: bond,dual + // required: true + InterfaceMode string `json:"interfaceMode" validate:"required,oneof=bond dual"` + // 系统盘类型(SSD,HDD) + // required: true + SystemVolumeType string `json:"systemVolumeType" validate:"required,oneof=SSD HDD"` + // 系统盘接口类型(SATA,SAS,NVME) + // required: true + SystemVolumeInterfaceType string `json:"systemVolumeInterfaceType" validate:"required,oneof=SATA SAS NVME"` + // 系统盘单盘大小1-100000 + // required: true + SystemVolumeSize int `json:"systemVolumeSize" validate:"required,min=1,max=100000"` + // 系统盘单盘大小单位 GB,TB + // required: true + SystemVolumeUnit string `json:"systemVolumeUnit" validate:"required,oneof=GB TB"` + // 系统盘数量1-10000 + // required: true + SystemVolumeAmount int `json:"systemVolumeAmount" validate:"required,min=1,max=10000"` + // gpu数量0-1000 + GpuAmount int `json:"gpuAmount" validate:"min=0,max=1000"` + // gpu品牌0-64 + GpuManufacturer string `json:"gpuManufacturer" validate:"min=0,max=64"` + // gpu型号0-64 + GpuModel string `json:"gpuModel" validate:"min=0,max=64"` + // 数据盘类型0-64 + DataVolumeType string `json:"dataVolumeType" validate:"min=0,max=64"` + // 数据盘接口类型0-64 + DataVolumeInterfaceType string `json:"dataVolumeInterfaceType" validate:"min=0,max=64"` + // 数据盘单盘大小0-100000 + DataVolumeSize int `json:"dataVolumeSize" validate:"min=0,max=100000"` + // 数据盘单盘大小单位GB TB + DataVolumeUnit string `json:"dataVolumeUnit" validate:"min=0,max=2"` + // 数据盘数量0-10000 + DataVolumeAmount int `json:"dataVolumeAmount" validate:"min=0,max=10000"` + // 系统盘raid,支持多选,英文逗号分隔 + // required: true + RaidID string `json:"raidId" validate:"required"` + // CPU 预置规格 + // required: true + CpuSpec string `json:"cpuSpec" validate:"required,oneof=common user_defined"` + // 内存 预置规格 + // required: true + MemSpec string `json:"memSpec" validate:"required,oneof=common user_defined"` + //boot模式 + BootMode string `json:"boot_mode" validate:"omitempty"` +} + +func (param *CreateDeviceTypeRequest) Validate(logger *log.Logger) { + validate(param, logger) + if param.GpuManufacturer == "" { + if param.GpuModel != "" || param.GpuAmount != 0 { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.GpuModel == "" { + if param.GpuManufacturer != "" || param.GpuAmount != 0 { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.GpuAmount == 0 { + if param.GpuManufacturer != "" || param.GpuModel != "" { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.DataVolumeType == "" { + if param.DataVolumeInterfaceType != "" || param.DataVolumeAmount != 0 || param.DataVolumeSize != 0 { + panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + } + } + if param.DataVolumeInterfaceType == "" { + if param.DataVolumeType != "" || param.DataVolumeAmount != 0 || param.DataVolumeSize != 0 { + panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + } + } + if param.DataVolumeAmount == 0 { + if param.DataVolumeInterfaceType != "" || param.DataVolumeType != "" || param.DataVolumeSize != 0 { + panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + } + } + if param.DataVolumeSize == 0 { + if param.DataVolumeInterfaceType != "" || param.DataVolumeAmount != 0 || param.DataVolumeType != "" { + panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + } + } +} + +type ModifyDeviceTypeRequest struct { + // 机房id + // Extensions: + // x-nullable: true + IDcID *string `json:"idcId" validate:"omitempty,min=1,max=64"` + // 机型名称 + // Extensions: + // x-nullable: true + Name *string `json:"name" validate:"omitempty,min=1,max=64"` + // 机型规格 + // Extensions: + // x-nullable: true + DeviceType *string `json:"deviceType" validate:"omitempty,min=1,max=64"` + // 机型类型,如计算型,存储型 + // Extensions: + // x-nullable: true + DeviceSeries *string `json:"deviceSeries" validate:"omitempty,oneof=computer storage gpu other"` + // 体系架构,如i386/x86_64/ ARM64(aarch64),默认 x86_64 + // Extensions: + // x-nullable: true + Architecture *string `json:"architecture" validate:"omitempty,oneof=x86_64 'ARM64(aarch64)' i386"` + // 【高度(U)】:显示机型高度 + // Extensions: + // x-nullable: true + Height *int `json:"height" validate:"omitempty,oneof=2 4"` + // 描述 + // Extensions: + // x-nullable: true + Description *string `json:"description" validate:"omitempty,min=0,max=256"` + // cpu数量 + // Extensions: + // x-nullable: true + CPUAmount *int `json:"cpuAmount" validate:"omitempty,min=0,max=10000"` + // 单个cpu内核数 + // Extensions: + // x-nullable: true + CPUCores *int `json:"cpuCores" validate:"omitempty,min=0,max=10000"` + // cpu厂商 + // Extensions: + // x-nullable: true + CPUManufacturer *string `json:"cpuManufacturer" validate:"omitempty,min=1,max=64"` + // cpu处理器型号 + // Extensions: + // x-nullable: true + CPUModel *string `json:"cpuModel" validate:"omitempty,min=1,max=64"` + // cpu频率(G) + // Extensions: + // x-nullable: true + CPUFrequency *string `json:"cpuFrequency" validate:"omitempty,min=1,max=64"` + // 内存接口(如DDR3,DDR4) + // Extensions: + // x-nullable: true + MemType *string `json:"memType" validate:"omitempty,oneof=DDR DDR2 DDR3 DDR4 DDR5"` + // 单个内存大小(GB) + // Extensions: + // x-nullable: true + MemSize *int `json:"memSize" validate:"omitempty,min=0,max=10000"` + // 内存数量 + // Extensions: + // x-nullable: true + MemAmount *int `json:"memAmount" validate:"omitempty,min=0,max=10000"` + // 内存主频(MHz) + // Extensions: + // x-nullable: true + MemFrequency *int `json:"memFrequency" validate:"omitempty,min=0,max=10000"` + // 网卡数量 + // Extensions: + // x-nullable: true + NicAmount *int `json:"nicAmount" validate:"omitempty,min=0,max=10000"` + // 网卡传输速率(GE) + // Extensions: + // x-nullable: true + NicRate *int `json:"nicRate" validate:"omitempty,min=0,max=10000"` + // 【网口模式】【网络设置】: 单网口,双网口bond + // Extensions: + // x-nullable: true + InterfaceMode *string `json:"interfaceMode" validate:"omitempty,oneof=bond dual"` + // 系统盘类型(SSD,HDD) + // Extensions: + // x-nullable: true + SystemVolumeType *string `json:"systemVolumeType" validate:"omitempty,oneof=SSD HDD"` + // 系统盘接口类型(SATA,SAS,NVME) + // Extensions: + // x-nullable: true + SystemVolumeInterfaceType *string `json:"systemVolumeInterfaceType" validate:"omitempty,oneof=SATA SAS NVME"` + // 系统盘单盘大小 + // Extensions: + // x-nullable: true + SystemVolumeSize *int `json:"systemVolumeSize" validate:"omitempty,min=0,max=100000"` + // 系统盘单盘大小单位 + // Extensions: + // x-nullable: true + SystemVolumeUnit *string `json:"systemVolumeUnit" validate:"omitempty,oneof=GB TB"` + // 系统盘数量 + // Extensions: + // x-nullable: true + SystemVolumeAmount *int `json:"systemVolumeAmount" validate:"omitempty,min=0,max=10000"` + // gpu数量 + // Extensions: + // x-nullable: true + GpuAmount *int `json:"gpuAmount" validate:"omitempty,min=0,max=10000"` + // gpu厂商 + // Extensions: + // x-nullable: true + GpuManufacturer *string `json:"gpuManufacturer" validate:"omitempty,min=0,max=64"` + // gpu处理器型号 + // Extensions: + // x-nullable: true + GpuModel *string `json:"gpuModel" validate:"omitempty,min=0,max=64"` + // 数据盘类型 + // Extensions: + // x-nullable: true + DataVolumeType *string `json:"dataVolumeType" validate:"omitempty,oneof='' SSD HDD"` + // 数据盘接口类型 + // Extensions: + // x-nullable: true + DataVolumeInterfaceType *string `json:"dataVolumeInterfaceType" validate:"omitempty,oneof='' SATA SAS NVME"` + // 数据盘单盘大小 + // Extensions: + // x-nullable: true + DataVolumeSize *int `json:"dataVolumeSize" validate:"omitempty,min=0,max=100000"` + // 数据盘单盘大小单位 + // Extensions: + // x-nullable: true + DataVolumeUnit *string `json:"dataVolumeUnit" validate:"omitempty,oneof='' GB TB"` + // 数据盘数量 + // Extensions: + // x-nullable: true + DataVolumeAmount *int `json:"dataVolumeAmount" validate:"omitempty,min=0,max=10000"` + // 系统盘raid,支持多选,英文逗号分隔 + // Extensions: + // x-nullable: true + RaidID *string `json:"raidId"` + // CPU 预置规格 + // Extensions: + // x-nullable: true + CpuSpec *string `json:"cpuSpec" validate:"omitempty,oneof=common user_defined"` + // 内存 预置规格 + // Extensions: + // x-nullable: true + MemSpec *string `json:"memSpec" validate:"omitempty,oneof=common user_defined"` +} + +func (param *ModifyDeviceTypeRequest) Validate(logger *log.Logger) { + validate(param, logger) + //fmt.Println("开始校验") + ////对于必填项校验方法 + //fmt.Println(util.ObjToJson(param)) + //if param.Name != nil && (len(*param.Name) < 1 || len(*param.Name) > 64) { + // panic(constant.BuildInvalidArgumentWithArgs("机型名称不合法", "Name invalidate")) + //} + //if param.DeviceType != nil && (len(*param.DeviceType) < 1 || len(*param.DeviceType) > 64) { + // panic(constant.BuildInvalidArgumentWithArgs("DeviceType 不合法", "DeviceType invalidate")) + //} + //if param.DeviceSeries != nil && !util.InArray(*param.DeviceSeries, []string{"computer", "storage", "gpu", "other"}) { + // //fmt.Println(!util.InArray(param.DeviceSeries, []string{"computer", "storage", "gpu", "other"})) + // panic(constant.BuildInvalidArgumentWithArgs("DeviceSeries 不合法", "DeviceSeries invalidate")) + //} + //if param.Architecture != nil && (len(*param.Architecture) < 1 || len(*param.Architecture) > 64) { + // panic(constant.BuildInvalidArgumentWithArgs("Architecture 不合法", "Architecture invalidate")) + //} + //if param.Height != nil && !util.InArray(*param.Height, []int{2, 4}) { + // panic(constant.BuildInvalidArgumentWithArgs("Height 不合法", "Height invalidate")) + //} + // + //if param.CPUAmount != nil && (*param.CPUAmount < 1 || *param.CPUAmount > 10000) { + // panic(constant.BuildInvalidArgumentWithArgs("CPUAmount 不合法", "CPUAmount invalidate")) + //} + //if param.CPUCores != nil && (*param.CPUCores < 1 || *param.CPUCores > 10000) { + // panic(constant.BuildInvalidArgumentWithArgs("CPUCores 不合法", "CPUCores invalidate")) + //} + //if param.CPUManufacturer != nil && (len(*param.CPUManufacturer) < 1 || len(*param.CPUManufacturer) > 64) { + // panic(constant.BuildInvalidArgumentWithArgs("CPUManufacturer 不合法", "CPUManufacturer invalidate")) + //} + //if param.CPUModel != nil && (len(*param.CPUModel) < 1 || len(*param.CPUModel) > 64) { + // panic(constant.BuildInvalidArgumentWithArgs("CPUModel 不合法", "CPUModel invalidate")) + //} + //if param.CPUFrequency != nil && (len(*param.CPUFrequency) < 1 || len(*param.CPUFrequency) > 64) { + // panic(constant.BuildInvalidArgumentWithArgs("CPUFrequency 不合法", "CPUFrequency invalidate")) + //} + // + //if param.MemType != nil && !util.InArray(*param.MemType, []string{"DDR", "DDR2", "DDR3", "DDR4", "DDR5"}) { + // panic(constant.BuildInvalidArgumentWithArgs("MemType 不合法", "MemType invalidate")) + //} + //if param.MemSize != nil && (*param.MemSize < 1 || *param.MemSize > 10000) { + // panic(constant.BuildInvalidArgumentWithArgs("MemSize 不合法", "MemSize invalidate")) + //} + //if param.MemAmount != nil && (*param.MemAmount < 1 || *param.MemAmount > 1000) { + // panic(constant.BuildInvalidArgumentWithArgs("MemAmount 不合法", "MemAmount invalidate")) + //} + //if param.MemFrequency != nil && (*param.MemFrequency < 1 || *param.MemFrequency > 10000) { + // panic(constant.BuildInvalidArgumentWithArgs("MemFrequency 不合法", "MemFrequency invalidate")) + //} + //if param.NicAmount != nil && (*param.NicAmount < 1 || *param.NicAmount > 10000) { + // panic(constant.BuildInvalidArgumentWithArgs("NicAmount 不合法", "NicAmount invalidate")) + //} + //if param.NicRate != nil && (*param.NicRate < 1 || *param.NicRate > 10000) { + // panic(constant.BuildInvalidArgumentWithArgs("NicRate 不合法", "NicRate invalidate")) + //} + // + //if param.InterfaceMode != nil && !util.InArray(*param.InterfaceMode, []string{"bond", "dual"}) { + // panic(constant.BuildInvalidArgumentWithArgs("InterfaceMode 不合法", "InterfaceMode invalidate")) + //} + // + //if param.SystemVolumeType != nil && !util.InArray(*param.SystemVolumeType, []string{"SSD", "HDD"}) { + // panic(constant.BuildInvalidArgumentWithArgs("SystemVolumeType 不合法", "SystemVolumeType invalidate")) + //} + //if param.SystemVolumeInterfaceType != nil && !util.InArray(*param.SystemVolumeInterfaceType, []string{"SATA", "SAS", "NVME"}) { + // panic(constant.BuildInvalidArgumentWithArgs("SystemVolumeInterfaceType 不合法", "SystemVolumeInterfaceType invalidate")) + //} + //if param.SystemVolumeSize != nil && (*param.SystemVolumeSize < 1 || *param.SystemVolumeSize > 100000) { + // panic(constant.BuildInvalidArgumentWithArgs("SystemVolumeSize 不合法", "SystemVolumeSize invalidate")) + //} + //if param.SystemVolumeAmount != nil && (*param.SystemVolumeAmount < 1 || *param.SystemVolumeAmount > 10000) { + // panic(constant.BuildInvalidArgumentWithArgs("SystemVolumeAmount 不合法", "SystemVolumeAmount invalidate")) + //} + //if param.SystemVolumeUnit != nil && !util.InArray(*param.SystemVolumeUnit, []string{"GB", "TB"}) { + // panic(constant.BuildInvalidArgumentWithArgs("SystemVolumeUnit 不合法", "SystemVolumeUnit invalidate")) + //} + // + ////非必填校验方法 + //if param.GpuManufacturer != nil && len(*param.GpuManufacturer) > 64 { + // panic(constant.BuildInvalidArgumentWithArgs("GpuManufacturer 不合法", "GpuManufacturer invalidate")) + //} + //if param.GpuModel != nil && len(*param.GpuModel) > 64 { + // panic(constant.BuildInvalidArgumentWithArgs("GpuModel 不合法", "GpuModel invalidate")) + //} + //if param.GpuAmount != nil && *param.GpuAmount > 10000 { + // panic(constant.BuildInvalidArgumentWithArgs("GpuAmount 不合法", "GpuAmount invalidate")) + //} + //if param.DataVolumeType != nil && !util.InArray(*param.DataVolumeType, []string{"", "SSD", "HDD"}) { + // panic(constant.BuildInvalidArgumentWithArgs("DataVolumeType 不合法", "DataVolumeType invalidate")) + //} + //if param.DataVolumeInterfaceType != nil && !util.InArray(*param.DataVolumeInterfaceType, []string{"", "SATA", "SAS", "NVME"}) { + // panic(constant.BuildInvalidArgumentWithArgs("DataVolumeInterfaceType 不合法", "DataVolumeInterfaceType invalidate")) + //} + //if param.DataVolumeSize != nil && *param.DataVolumeSize > 100000 { + // panic(constant.BuildInvalidArgumentWithArgs("DataVolumeSize 不合法", "DataVolumeSize invalidate")) + //} + //if param.DataVolumeAmount != nil && *param.DataVolumeAmount > 10000 { + // panic(constant.BuildInvalidArgumentWithArgs("DataVolumeAmount 不合法", "DataVolumeAmount invalidate")) + //} + //if param.DataVolumeUnit != nil && !util.InArray(*param.DataVolumeUnit, []string{"", "GB", "TB"}) { + // panic(constant.BuildInvalidArgumentWithArgs("DataVolumeUnit 不合法", "DataVolumeUnit invalidate")) + //} + // + //其他逻辑校验 + + if param.GpuManufacturer != nil && *param.GpuManufacturer == "" { + if param.GpuModel != nil && *param.GpuModel != "" || param.GpuAmount != nil && *param.GpuAmount != 0 { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.GpuModel != nil && *param.GpuModel == "" { + if param.GpuManufacturer != nil && *param.GpuManufacturer != "" || param.GpuAmount != nil && *param.GpuAmount != 0 { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.GpuAmount != nil && *param.GpuAmount == 0 { + if param.GpuManufacturer != nil && *param.GpuManufacturer != "" || param.GpuModel != nil && *param.GpuModel != "" { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.DataVolumeType != nil && *param.DataVolumeType == "" { + if param.DataVolumeInterfaceType != nil && *param.DataVolumeInterfaceType != "" || param.DataVolumeAmount != nil && *param.DataVolumeAmount != 0 || param.DataVolumeSize != nil && *param.DataVolumeSize != 0 { + panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + } + } + if param.DataVolumeInterfaceType != nil && *param.DataVolumeInterfaceType == "" { + if param.DataVolumeType != nil && *param.DataVolumeType != "" || param.DataVolumeAmount != nil && *param.DataVolumeAmount != 0 || param.DataVolumeSize != nil && *param.DataVolumeSize != 0 { + panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + } + } + if param.DataVolumeAmount != nil && *param.DataVolumeAmount == 0 { + if param.DataVolumeInterfaceType != nil && *param.DataVolumeInterfaceType != "" || param.DataVolumeType != nil && *param.DataVolumeType != "" || param.DataVolumeSize != nil && *param.DataVolumeSize != 0 { + panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + } + } + if param.DataVolumeSize != nil && *param.DataVolumeSize == 0 { + if param.DataVolumeInterfaceType != nil && *param.DataVolumeInterfaceType != "" || param.DataVolumeAmount != nil && *param.DataVolumeAmount != 0 || param.DataVolumeType != nil && *param.DataVolumeType != "" { + panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + } + } +} + +type QueryDeviceTypesRequest struct { + // 机型id + DeviceTypeID string `json:"deviceTypeId"` + // 机型规格 + DeviceType string `json:"deviceType"` + // 机房id + IdcID string `json:"idcId"` + // 机型名称 + Name string `json:"name"` + // 机型类型 + DeviceSeries string `json:"deviceSeries"` + Pageable + IsAll string `json:"isAll"` +} + +func (req *QueryDeviceTypesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryDeviceTypeImageRequest struct { + // 机型id + DeviceTypeID string `json:"deviceTypeId"` + // 镜像id + ImageID string `json:"imageId"` + // 体系架构 + Architecture string `json:"architecture"` + // 操作系统平台 + OsType string `json:"osType"` + // 镜像名称 + ImageName string `json:"imageName"` + // 版本号 + Version string `json:"version"` + // 操作系统ID + OsID string `json:"osId"` + // 镜像类型,预置,自定义 + Source string `json:"source"` + Pageable + // 是否显示全部 + IsAll string `json:"isAll"` +} + +func (req *QueryDeviceTypeImageRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryVolumesRaidsRequest struct { + // 机型id + DeviceTypeID string `json:"deviceTypeId"` + // 系统盘还是数据盘 + VolumeType string `json:"volumeType"` + // 是否显示所有 + IsAll string `json:"isAll"` +} + +func (req *QueryVolumesRaidsRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryDeviceTypeImagePartitionRequest struct { + // 机型id + DeviceTypeID string `json:"deviceTypeId"` //validate:"required" + // 镜像id + ImageID string `json:"imageId"` //validate:"required" + // 是否显示所有,isAll=1显示所有 + IsAll string `json:"isAll"` +} + +func (req *QueryDeviceTypeImagePartitionRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi-console/types/request/DiskRequest.go b/bmp-openapi-console/types/request/DiskRequest.go new file mode 100644 index 0000000..6d4f0f6 --- /dev/null +++ b/bmp-openapi-console/types/request/DiskRequest.go @@ -0,0 +1,31 @@ +package request + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" + "github.com/go-playground/validator/v10" +) + +type CreateDiskRequest struct { + DeviceID string `gorm:"column:device_id" json:"deviceId"` // 设备uuid + Enclosure string `gorm:"column:enclosure" json:"enclosure"` // enclosure + Slot int `gorm:"column:slot" json:"slot"` // 卡槽槽位 + DiskType string `gorm:"column:disk_type" json:"diskType"` // 磁盘类型:system,data + Size string `gorm:"column:size" json:"size"` // 硬盘大小,不确定精度(非nvme盘) + SizeUnit string `gorm:"column:size_unit" json:"sizeUnit"` // 硬盘大小单位 MB GB TB ,1024进制 + PdType string `gorm:"column:pd_type" json:"pdType"` // 硬盘类型 + AdapterID string `gorm:"column:adapter_id" json:"adapterId"` // 适配ID + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + //DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + //IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (c *CreateDiskRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("CreateDiskRequest validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } +} diff --git a/bmp-openapi-console/types/request/IdcDevicesRequest.go b/bmp-openapi-console/types/request/IdcDevicesRequest.go new file mode 100644 index 0000000..215fcb5 --- /dev/null +++ b/bmp-openapi-console/types/request/IdcDevicesRequest.go @@ -0,0 +1,19 @@ +package request + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" + validator "github.com/go-playground/validator/v10" +) + +type CreateIdcDevicesRequest struct { + Sns []string `json:"sns" validate:"required"` + DeviceType string `json:"device_type"` +} + +func (c *CreateIdcDevicesRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("CreateIdcDevicesRequest.Validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } +} diff --git a/bmp-openapi-console/types/request/IdcRequest.go b/bmp-openapi-console/types/request/IdcRequest.go new file mode 100644 index 0000000..31e5f71 --- /dev/null +++ b/bmp-openapi-console/types/request/IdcRequest.go @@ -0,0 +1,161 @@ +package request + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" + "regexp" +) + +type CreateIdcRequest struct { + // 机房名称 1-64 + // required: true + Name string `json:"name" validate:"required,min=1,max=64"` + // 机房英文名称 1-64 + // required: true + NameEn string `json:"nameEn" validate:"required,min=1,max=64"` + // 机房缩写 1-64 + // required: true + Shortname string `json:"shortname" validate:"required,min=1,max=64"` + // 机房等级 1-64 + // required: true + Level string `json:"level" validate:"required,min=1,max=64"` + // 机房地址 0-256 + Address string `json:"address" validate:"max=256"` + // 带外用户名 0-64 + IloUser string `json:"iloUser" validate:"max=64"` + // 带外密码 0-64 + IloPassword string `json:"iloPassword" validate:"max=64"` + // 交换机用户1 0-64 + SwitchUser1 string `json:"switchUser1" validate:"max=64"` + // 交换机密码1 0-64 + SwitchPassword1 string `json:"switchPassword1" validate:"max=64"` + // 交换机用户2 0-64 + SwitchUser2 string `json:"switchUser2" validate:"max=64"` + // 交换机密码2 0-64 + SwitchPassword2 string `json:"switchPassword2" validate:"max=64"` +} + +func (req *CreateIdcRequest) Validate(logger *log.Logger) { + validate(req, logger) + specialMatch := regexp.MustCompile("^[a-zA-Z0-9_`{};:\"!~#$%@^&*()+-]+$").MatchString + if !specialMatch(req.NameEn) { + panic(constant.BuildInvalidArgumentWithArgs("机房英文名称不合法", "nameEn invalidate")) + } +} + +type ModifyIdcRequest struct { + // 机房名称 1-64 + // Extensions: + // x-nullable: true + Name *string `json:"name" validate:"omitempty,min=1,max=64"` + // 机房英文名称 1-64 + // Extensions: + // x-nullable: true + NameEn *string `json:"nameEn" validate:"omitempty,min=1,max=64"` + // 机房缩写 1-64 + // Extensions: + // x-nullable: true + Shortname *string `json:"shortname" validate:"omitempty,min=1,max=64"` + // 机房等级 1-64 + // Extensions: + // x-nullable: true + Level *string `json:"level" validate:"omitempty,min=1,max=64"` + // 机房地址 0-256 + // Extensions: + // x-nullable: true + Address *string `json:"address" validate:"omitempty,min=0,max=256"` + // 带外用户名 0-64 + // Extensions: + // x-nullable: true + IloUser *string `json:"iloUser" validate:"omitempty,min=0,max=64"` + // 带外密码 0-64 + // Extensions: + // x-nullable: true + IloPassword *string `json:"iloPassword" validate:"omitempty,min=0,max=64"` + // 交换机用户1 0-64 + // Extensions: + // x-nullable: true + SwitchUser1 *string `json:"switchUser1" validate:"omitempty,min=0,max=64"` + // 交换机密码1 0-64 + // Extensions: + // x-nullable: true + SwitchPassword1 *string `json:"switchPassword1" validate:"omitempty,min=0,max=64"` + // 交换机用户2 0-64 + // Extensions: + // x-nullable: true + SwitchUser2 *string `json:"switchUser2" validate:"omitempty,min=0,max=64"` + // 交换机2密码 0-64 + // Extensions: + // x-nullable: true + SwitchPassword2 *string `json:"switchPassword2" validate:"omitempty,min=0,max=64"` +} + +func (req *ModifyIdcRequest) Validate(logger *log.Logger) { + validate(req, logger) + specialMatch := regexp.MustCompile("^[a-zA-Z0-9_`{};:\"!~#$%@^&*()+-]+$").MatchString + if req.NameEn != nil && !specialMatch(*req.NameEn) { + panic(constant.BuildInvalidArgumentWithArgs("机房英文名称不合法", "nameEn invalidate")) + } + //对于必填项校验方法 + //if param.Name != nil && (len(*param.Name) < 1 || len(*param.Name) > 64) { + // panic(constant.BuildInvalidArgumentWithArgs("机房名称不合法", "idcName invalidate")) + //} + //fmt.Println(len(*param.NameEn)) + //if param.NameEn != nil && (len(*param.NameEn) < 1 || len(*param.NameEn) > 64) { + // panic(constant.BuildInvalidArgumentWithArgs("机房英文名称不合法", "idc nameEn invalidate")) + //} + //if param.Shortname != nil && (len(*param.Shortname) < 1 || len(*param.Shortname) > 64) { + // panic(constant.BuildInvalidArgumentWithArgs("机房名称缩写不合法", "idc shortName invalidate")) + //} + //if param.Level != nil && (len(*param.Level) < 1 || len(*param.Level) > 64) { + // panic(constant.BuildInvalidArgumentWithArgs("机房等级不合法", "idc level invalidate")) + //} + ////非必填校验方法 + //if param.Address != nil && len(*param.Address) > 256 { + // panic(constant.BuildInvalidArgumentWithArgs("地址长度不合法", "idc address invalidate")) + //} + //if param.IloUser != nil && len(*param.IloUser) > 64 { + // panic(constant.BuildInvalidArgumentWithArgs("带外用户名长度不合法", "IloUser invalidate")) + //} + //if param.IloPassword != nil && len(*param.IloPassword) > 64 { + // panic(constant.BuildInvalidArgumentWithArgs("带外密码长度不合法", "IloPassword invalidate")) + //} + //if param.SwitchUser1 != nil && len(*param.SwitchUser1) > 64 { + // panic(constant.BuildInvalidArgumentWithArgs("SwitchUser1 长度不合法", "SwitchUser1 invalidate")) + //} + //if param.SwitchPassword1 != nil && len(*param.SwitchPassword1) > 64 { + // panic(constant.BuildInvalidArgumentWithArgs("SwitchPassword1 长度不合法", "SwitchPassword1 invalidate")) + //} + //if param.SwitchUser2 != nil && len(*param.SwitchUser2) > 64 { + // panic(constant.BuildInvalidArgumentWithArgs("SwitchUser2 长度不合法", "SwitchUser2 invalidate")) + //} + //if param.SwitchPassword2 != nil && len(*param.SwitchPassword2) > 64 { + // panic(constant.BuildInvalidArgumentWithArgs("SwitchPassword2 长度不合法", "SwitchPassword2 invalidate")) + //} +} + +type QueryIdcsRequest struct { + // 机房名称 + Name string `json:"name"` + // 机房英文名称 + NameEn string `json:"nameEn"` + // 机房等级 + Level string `json:"level"` + Pageable + // 是否显示所有 + IsAll string `json:"isAll"` +} + +func (req *QueryIdcsRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryIdcRequest struct { + // 机房ID + // required: true + IDcID string `json:"idcId" validate:"required"` +} + +func (req *QueryIdcRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi-console/types/request/ImageRequest.go b/bmp-openapi-console/types/request/ImageRequest.go new file mode 100644 index 0000000..2ccaa10 --- /dev/null +++ b/bmp-openapi-console/types/request/ImageRequest.go @@ -0,0 +1,170 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateImageRequest struct { + // 镜像名称 + // required: true + ImageName string `json:"imageName" validate:"required,min=1,max=200"` + // 体系架构 + // required: true + Architecture string `json:"architecture" validate:"required,oneof=x86_64 ARM64(aarch64) i386"` + // 操作系统平台 + // required: true + OsType string `json:"osType" validate:"required"` + // 版本号 + // required: true + Version string `json:"Version" validate:"required"` + // 镜像文件类型 + // required: true + Format string `json:"format" validate:"required"` + // 镜像文件名称 + // required: true + Filename string `json:"filename" validate:"required"` + // 镜像上传地址 + // required: true + Url string `json:"url" validate:"required"` + // 文件hash值 + // required: true + Hash string `json:"hash"` + // 镜像类型,预置,自定义 + Source string `json:"source" validate:"oneof=common user_defined"` + // 描述 + Description string `json:"description"` + // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:50GiB,swap) + SystemPartition string `json:"systemPartition"` + // 数据分区信息 + DataPartition string `json:"dataPartition"` +} + +func (req *CreateImageRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +//镜像默认分区 +//[{"format":"swap","point":"swap","size":10240},{"format":"xfs","point":"/","size":51200}] +type Partition struct { + FsType string `json:"format"` //format + MountPoint string `json:"point"` //point + Size int `json:"size"` +} + +type ModifyImageRequest struct { + // 修改设备描述 + // Extensions: + // x-nullable: true + Description *string `json:"description" validate:"omitempty,max=256"` +} + +//// 镜像名称 +//ImageName string `json:"imageName" validate:"min=1,max=200"` +//// 操作系统id +//OsID string `json:"osId" validate:"omitempty,max=256"` +//// 文件类型 +//Format string `json:"format" validate:"omitempty,max=256"` +//// 文件名称 +//Filename string `json:"filename" validate:"omitempty,max=256"` +//// 镜像上传地址 +//Url string `json:"url" validate:"omitempty,max=500"` +//// 文件hash值 +//Hash string `json:"hash" validate:"omitempty,max=256"` +//// 镜像类型,预置,自定义 +//Source string `json:"source" validate:"omitempty,oneof=common user_defined"` +//// 修改设备描述 +//// Extensions: +//// x-nullable: true +//Description *string `json:"description" validate:"omitempty,max=256"` +//// 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:50GiB,swap) +//SystemPartition string `json:"systemPartition" validate:"omitempty,max=256"` +//// 数据分区信息 +//DataPartition string `json:"dataPartition" validate:"omitempty,max=256"` + +func (req *ModifyImageRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryImagesRequest struct { + // 镜像ID + ImageID string `json:"imageId"` + // 镜像名称 + ImageName string `json:"imageName"` + // 设备类型id + DeviceTypeID string `json:"deviceTypeId"` + // 版本号 + Version string `json:"version"` + // 操作系统ID + OsID string `json:"osId"` + // 镜像ID,数组,支持多个 + ImageIDs []string `json:"imageIds"` + // 镜像类型,预置,自定义 + Source string `json:"source"` + // 体系架构 + Architecture string `json:"architecture"` + // 操作系统平台 + OsType string `json:"osType"` + Pageable + // 是否显示全部 + IsAll string `json:"isAll"` +} + +func (req *QueryImagesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type AssociateImageRequest struct { + // 设备类型id + // required: true + DeviceTypeID string `json:"deviceTypeId" validate:"required"` + // 镜像ID,数组,支持多个 + // required: true + ImageIDs []string `json:"imageIds" validate:"required"` +} + +func (req *AssociateImageRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DissociatedImageRequest struct { + // 设备类型id + // required: true + DeviceTypeID string `json:"deviceTypeId" validate:"required"` + // 镜像ID + // required: true + ImageID string `json:"imageId" validate:"required"` +} + +func (req *DissociatedImageRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type AssociateDeviceTypeRequest struct { + // 镜像ID, + // required: true + ImageID string `json:"imageId" validate:"required"` + // 设备类型id,数组,支持多个 + // required: true + DeviceTypeIDs []string `json:"deviceTypeIds" validate:"required"` +} + +func (req *AssociateDeviceTypeRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryImageDeviceTypesRequest struct { + // 镜像ID + // required: true + ImageID string `json:"imageId" validate:"required"` + // 体系架构 + Architecture string `json:"architecture"` + Pageable + //镜像是否绑定了机型,0查询该镜像没有绑定的机型列表 1查询该镜像已经绑定了的机型列表 + IsBind string `json:"isBind"` + // 是否显示全部 + IsAll string `json:"isAll"` +} + +func (req *QueryImageDeviceTypesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi-console/types/request/InstanceRequest.go b/bmp-openapi-console/types/request/InstanceRequest.go new file mode 100644 index 0000000..22d4083 --- /dev/null +++ b/bmp-openapi-console/types/request/InstanceRequest.go @@ -0,0 +1,430 @@ +package request + +import ( + "errors" + "fmt" + "regexp" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + + log "coding.jd.com/aidc-bmp/bmp_log" + validation "git.jd.com/cps-golang/ironic-common/ironic/common/Validation" + "github.com/go-playground/validator/v10" +) + +type CreateInstanceRequest struct { + // 项目ID + // required: true + ProjectID string `json:"projectId" validate:"required"` + // 机房ID + // required: true + IdcID string `json:"idcId" validate:"required"` + // 设备类型ID + // required: true + DeviceTypeID string `json:"deviceTypeId" validate:"required"` + // 镜像ID + // required: true + ImageID string `json:"imageId" validate:"required"` + // 系统盘RAID ID + // required: true + SystemVolumeRaidID string `json:"systemVolumeRaidId"` //使用盘符时,这个为空 + // 系统盘分区 + SystemPartition []Partition `json:"systemPartition"` + // 实例名称 + // required: true + InstanceName string `json:"instanceName" validate:"required"` + // 主机名称 + HostName string `json:"hostname"` + // 密码 + Password string `json:"password"` + // 秘钥ID + SshKeyID string `json:"sshKeyId"` + // 创建数量 + Count int `json:"count" validate:"gte=1"` + // 描述 + Description string `json:"description" validate:"omitempty,max=256"` + //启动模式 + BootMode string `json:"bootMode" validate:"required` + //数据卷和选择的raidid + VolumeRaIDs []VolumeRaID `json:"VolumeRaids"` + //是否安装bmp-agent + InstallBmpAgent bool `json:"installBmpAgent"` +} + +type VolumeRaID struct { + // system|data + VolumeType string `json:"volumeType"` + //卷 uuid + VolumeID string `json:"volumeId"` + RaidCan string `json:"raidCan"` + //raid uuid + RaidID string `json:"raidId"` +} + +func (req *CreateInstanceRequest) Validate(logger *log.Logger) { + validate(req, logger) + //name条件:2-128 个字符,以大小写字母或中文开头,可包含数字、“.”、“_”、“:”或“-” + specialMatch := regexp.MustCompile("^[.:\u4e00-\u9fa5_a-zA-Z0-9_-]{2,128}$").MatchString + if !specialMatch(req.InstanceName) { + panic(constant.BuildInvalidArgumentWithArgs("instanceName格式不正确", "Name invalidate")) + } + + if req.HostName != "" { + //hostname条件:长度为 2-64 个字符,允许使用点号(.)分隔字符成多段,每段允许使 用大小写字母、数字或连字符(-),但不能连续使用点号(.)或连字符(-)。不能以点号(.)或连字符(-)开头或结尾 + specialMatch := regexp.MustCompile("^[.a-zA-Z0-9-]{2,64}$").MatchString + if !specialMatch(req.HostName) { + panic(constant.BuildInvalidArgumentWithArgs("hostName格式不正确", "hostName invalidate")) + } + if strings.HasPrefix(req.HostName, ".") || strings.HasPrefix(req.HostName, "-") || strings.HasSuffix(req.HostName, ".") || strings.HasSuffix(req.HostName, "-") || strings.Contains(req.HostName, "..") || strings.Contains(req.HostName, "--") { + panic(constant.BuildInvalidArgumentWithArgs("hostName格式不正确", "hostName invalidate")) + } + + } + + b := strings.TrimSpace(req.BootMode) + if b != "UEFI" && b != "Legacy/BIOS" { + panic(constant.BuildInvalidArgumentWithArgs("boot_mode invalid", "boot_mode 非法")) + } + + //if req.UserName != "" { + // specialMatch := regexp.MustCompile("^[a-zA-Z0-9_-]{1,64}$").MatchString + // if !specialMatch(req.UserName) { + // panic(constant.BuildInvalidArgumentWithArgs("userName格式不正确", "userName invalidate")) + // } + //} + + if req.Password != "" { + //密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + lowercaseMatch := regexp.MustCompile(`[a-z]`).MatchString + uppercaseMatch := regexp.MustCompile(`[A-Z]`).MatchString + digitMatch := regexp.MustCompile(`\d`).MatchString + //()`~!@#$%&*_-+=|{}[]:";'<>,.?/ + specialMatch := regexp.MustCompile("[()`~!@#$%&*\\_\\-+=|{}\\[\\]:\";'<>,.?/]").MatchString + total := 0 + if lowercaseMatch(req.Password) { + total += 1 + } + if uppercaseMatch(req.Password) { + total += 1 + } + if digitMatch(req.Password) { + total += 1 + } + if specialMatch(req.Password) { + total += 1 + } + + if total >= 3 && len(req.Password) >= 8 && len(req.Password) <= 30 { + //pass + } else { + panic(constant.BuildInvalidArgumentWithArgs("password格式不正确", "password invalidate")) + } + } + + if len(req.SystemPartition) > 0 { + fsTypes := []string{"swap", "xfs", "ext2", "ext3", "ext4"} + for _, v := range req.SystemPartition { + if !util.InArray(v.FsType, fsTypes) { + logger.Warnf("CreateInstanceRequest.SystemPartition.format invalid:%s", v.FsType) + panic(constant.BuildInvalidArgumentWithArgs("format格式不正确", "format invalidate")) + } + if !util.InArray(v.MountPoint, []string{"swap", "/boot", "/var", "/", "/export", "/data0", "/home"}) { + logger.Warnf("CreateInstanceRequest.SystemPartition.MountPoint invalid:%s", v.MountPoint) + panic(constant.BuildInvalidArgumentWithArgs("point格式不正确", "point invalidate")) + } + if v.Size <= 0 { + logger.Warnf("CreateInstanceRequest.SystemPartition.Size invalid:%s", v.MountPoint) + panic(constant.BuildInvalidArgumentWithArgs("size格式不正确", "size invalidate")) + } + } + } + +} + +type ModifyInstanceRequest struct { + // 实例名称 + InstanceName string `json:"instanceName"` + // 描述 + // Extensions: + // x-nullable: true + Description *string `json:"description" validate:"omitempty,max=256"` +} + +func (c *ModifyInstanceRequest) Validate(logger *log.Logger) { + validate(c, logger) + if c.InstanceName != "" { + //name条件:2-128 个字符,以大小写字母或中文开头,可包含数字、“.”、“_”、“:”或“-” + specialMatch := regexp.MustCompile("^[.:\u4e00-\u9fa5_a-zA-Z0-9_-]{2,128}$").MatchString + if !specialMatch(c.InstanceName) { + panic(constant.BuildInvalidArgumentWithArgs("instanceName格式不正确", "Name invalidate")) + } + } + +} + +// 批量修改实例名称 +type ModifyInstancesRequest struct { + // 实例名称 + InstanceName string `json:"instanceName" validate:"required"` + // 实例id列表 + InstanceIDs []string `json:"instance_ids" validate:"required"` +} + +func (c *ModifyInstancesRequest) Validate(logger *log.Logger) { + validate(c, logger) + if c.InstanceName != "" { + //name条件:2-128 个字符,以大小写字母或中文开头,可包含数字、“.”、“_”、“:”或“-” + specialMatch := regexp.MustCompile("^[.:\u4e00-\u9fa5_a-zA-Z0-9_-]{2,128}$").MatchString + if !specialMatch(c.InstanceName) { + panic(constant.BuildInvalidArgumentWithArgs("instanceName格式不正确", "Name invalidate")) + } + } + +} + +// 批量删除实例 +type DeleteInstancesRequest struct { + // 实例id列表 + InstanceIDs []string `json:"instance_ids" validate:"required"` +} + +func (c *DeleteInstancesRequest) Validate(logger *log.Logger) { + validate(c, logger) +} + +type QueryInstancesRequest struct { + Pageable + // 实例ID + InstanceID string `json:"instanceId"` + // 实例名称,模糊搜索 + InstanceName string `json:"instanceName"` + // 设备类型ID + DeviceTypeID string `json:"deviceTypeId"` + // 运行状态 + Status string `json:"status"` + // 设备ID + DeviceID string `json:"deviceId"` + // SN + Sn string `json:"sn"` + // 机房ID + IdcID string `json:"idcId"` + // 项目ID + ProjectID string `json:"projectId"` + // 带外ip,精确搜索 + IloIP string `json:"ilo_ip"` + // ipv4,精确搜索 + IPV4 string `json:"ipv4"` + // ipv6,精确搜索 + IPV6 string `json:"ipv6"` + // 是否显示全部,取值为1时表示全部 + IsAll string `json:"isAll"` + //是否安装了agent,"0"表示未安装,"1"表示已安装,不传表示全部 + IsInstallAgent string `json:"isInstallAgent"` +} + +func (req *QueryInstancesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type RetryInstallInstanceRequest struct { + Password string `json:"password"` + UserData string `json:"user_data"` + //AliasIps []AliasIP `json:"alias_ips"` +} +type RetryReinstallInstanceRequest struct { + KeepData *bool `json:"keep_data" validate:"required"` + Password string `json:"password"` + UserData string `json:"user_data"` +} + +func (c *RetryReinstallInstanceRequest) Validate(logger *log.Logger) { + validate(c, logger) +} + +type RetryStartInstanceRequest struct { + InstanceIds []string `json:"instance_ids" validate:"required"` +} + +func (c *RetryStartInstanceRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("RetryStartInstanceRequest.Validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } + for _, instance_id := range c.InstanceIds { + if match, _ := regexp.MatchString(validation.REGEX_ID, instance_id); !match { + logger.Warn("RetryStartInstanceRequest.InstanceIds inValid:", c.InstanceIds) + panic(constant.INVALID_ARGUMENT) + } + } +} + +type StartInstancesRequest struct { + InstanceIds []string `json:"instanceIds" validate:"required"` +} + +func (req *StartInstancesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type StopInstancesRequest struct { + InstanceIds []string `json:"instanceIds" validate:"required"` +} + +func (req *StopInstancesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type RestartInstancesRequest struct { + InstanceIds []string `json:"instanceIds" validate:"required"` +} + +func (req *RestartInstancesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +// 重置实例密码 +type ResetInstancePasswdRequest struct { + // 新密码 + Password string `json:"password" validate:"required"` +} + +func (req *ResetInstancePasswdRequest) Validate(logger *log.Logger) { + validate(req, logger) + + if req.Password != "" { + //密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + lowercaseMatch := regexp.MustCompile(`[a-z]`).MatchString + uppercaseMatch := regexp.MustCompile(`[A-Z]`).MatchString + digitMatch := regexp.MustCompile(`\d`).MatchString + //()`~!@#$%&*_-+=|{}[]:";'<>,.?/ + specialMatch := regexp.MustCompile("[()`~!@#$%&*\\_\\-+=|{}\\[\\]:\";'<>,.?/]").MatchString + total := 0 + if lowercaseMatch(req.Password) { + total += 1 + } + if uppercaseMatch(req.Password) { + total += 1 + } + if digitMatch(req.Password) { + total += 1 + } + if specialMatch(req.Password) { + total += 1 + } + + if total >= 3 && len(req.Password) >= 8 && len(req.Password) <= 30 { + //pass + } else { + panic(constant.BuildInvalidArgumentWithArgs("password格式不正确", "password invalidate")) + } + } +} + +// 批量重置实例密码 +type ResetInstancesPasswdRequest struct { + // 实例id列表 + InstanceIDs []string `json:"instance_ids" validate:"required"` + // 新密码 + Password string `json:"password" validate:"required"` +} + +func (req *ResetInstancesPasswdRequest) Validate(logger *log.Logger) { + validate(req, logger) + + if req.Password != "" { + //密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + lowercaseMatch := regexp.MustCompile(`[a-z]`).MatchString + uppercaseMatch := regexp.MustCompile(`[A-Z]`).MatchString + digitMatch := regexp.MustCompile(`\d`).MatchString + //()`~!@#$%&*_-+=|{}[]:";'<>,.?/ + specialMatch := regexp.MustCompile("[()`~!@#$%&*\\_\\-+=|{}\\[\\]:\";'<>,.?/]").MatchString + total := 0 + if lowercaseMatch(req.Password) { + total += 1 + } + if uppercaseMatch(req.Password) { + total += 1 + } + if digitMatch(req.Password) { + total += 1 + } + if specialMatch(req.Password) { + total += 1 + } + + if total >= 3 && len(req.Password) >= 8 && len(req.Password) <= 30 { + //pass + } else { + panic(constant.BuildInvalidArgumentWithArgs("password格式不正确", "password invalidate")) + } + } +} + +type ReinstallInstanceRequest struct { + // 镜像ID + // required: true + ImageID string `json:"imageId" validate:"required"` + // 系统盘RAID ID + // required: true + SystemVolumeRaidID string `json:"systemVolumeRaidId"` //使用盘符装时不传此字段 + // 系统盘分区 + SystemPartition []Partition `json:"systemPartition"` + // 数据盘分区 + DataPartition []Partition `json:"dataPartition"` + // 实例名称 + // required: true + InstanceName string `json:"instanceName" validate:"required"` + // 主机名称 + HostName string `json:"hostname"` + // 密码 + Password string `json:"password"` + // 秘钥ID + SshKeyID string `json:"sshKeyId"` + // 描述 + Description string `json:"description" validate:"omitempty,max=256"` + // 引导模式 [UEFI Legacy/BIOS] + // required: true + BootMode string `json:"bootMode"` + + //是否安装bmp-agent + InstallBmpAgent bool `json:"installBmpAgent"` +} + +func (req *ReinstallInstanceRequest) Validate(logger *log.Logger) error { + if err := validator.New().Struct(req); err != nil { + logger.Warn("ReinstallInstanceRequest.Validate error:", err.Error()) + return fmt.Errorf("parameter validate error:%s", err.Error()) + } + + if match, _ := regexp.MatchString(validation.REGEX_ID, req.ImageID); !match { + logger.Warn("ReinstallInstanceRequest.ImageId invalid:", req.ImageID) + return errors.New("parameter ImageId invalid") + } + + b := strings.TrimSpace(req.BootMode) + if b != "UEFI" && b != "Legacy/BIOS" { + panic(constant.BuildInvalidArgumentWithArgs("boot_mode invalid", "boot_mode 非法")) + } + + return nil + +} + +type DescribeInstancesByProjectIdAndOwnerNameAndSharerNameRequest struct { + Pageable + // 项目ID + ProjectID string `json:"projectId"` + IsAll string `json:"isAll"` + OwnerName string `json:"ownerName"` + SharerName string `json:"sharerName"` + + //这两项支持模糊搜索 + InstanceName string `json:"instanceName"` + InstanceID string `json:"instanceId"` +} + +func (req *DescribeInstancesByProjectIdAndOwnerNameAndSharerNameRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi-console/types/request/InstanceSshkeyRequest.go b/bmp-openapi-console/types/request/InstanceSshkeyRequest.go new file mode 100644 index 0000000..81ef33c --- /dev/null +++ b/bmp-openapi-console/types/request/InstanceSshkeyRequest.go @@ -0,0 +1,18 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type QueryInstancesSshkeyRequest struct { + // 实例Id + InstanceId string `json:"instanceId"` + // 秘钥Id + SshkeyId string `json:"sshkeyId"` + // 是否显示全部 + IsAll string `json:"isAll"` +} + +func (req *QueryInstancesSshkeyRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi-console/types/request/MessageRequest.go b/bmp-openapi-console/types/request/MessageRequest.go new file mode 100644 index 0000000..8520272 --- /dev/null +++ b/bmp-openapi-console/types/request/MessageRequest.go @@ -0,0 +1,52 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type QueryMessagesRequest struct { + Pageable + // 是否显示全部,取值为1时表示全部 + IsAll string `json:"isAll"` + //0:未读;1:已读;""不传表示全部 + HasRead string `json:"hasRead"` + // 消息类型 + MessageType string `json:"messageType"` + // 消息子类型 + MessageSubType string `json:"messageSubType"` + // 内容模糊搜索 + Detail string `json:"detail"` +} + +func (req *QueryMessagesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type ReadMessagesRequest struct { + + // required: true + MessageIds []string `json:"messageIds" validate:"required"` +} + +func (req *ReadMessagesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DeleteMessagesRequest struct { + + // required: true + MessageIds []string `json:"messageIds" validate:"required"` +} + +func (req *DeleteMessagesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type GetMessageByIdRequest struct { + // required: true + MessageID string `json:"messageId" validate:"required"` +} + +func (req *GetMessageByIdRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi-console/types/request/MonitorAlertRequest.go b/bmp-openapi-console/types/request/MonitorAlertRequest.go new file mode 100644 index 0000000..ed4988a --- /dev/null +++ b/bmp-openapi-console/types/request/MonitorAlertRequest.go @@ -0,0 +1,88 @@ +package request + +import log "coding.jd.com/aidc-bmp/bmp_log" + +type AddAlertRequest struct { + Alerts []*AddAlertItem `json:"alerts"` +} + +type AddAlertItem struct { + //规则名称 + RuleName string `json:"ruleName" validate:"required"` + //规则ID + // required: true + RuleID string `json:"ruleId" validate:"required"` + //实例id + // required: true + InstanceID string `json:"instanceId" validate:"required"` + //触发条件 + // required: true + Trigger string `json:"trigger" validate:"required"` + //告警值 + // required: true + AlertValue string `json:"alertValue" validate:"required"` + //计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出] + CalculationUnit string `json:"calculationUnit"` + //告警时间戳 + // required: true + AlertTimestamp int64 `json:"alertTimestamp" validate:"required"` + //告警持续时间 + // required: true + AlertPeriod int `json:"alertPeriod" validate:"required"` + //是否为恢复通知,0为不是,1为是 + IsRecover int `json:"isRecover"` +} + +func (req *AddAlertRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} + +type DescribeAlertRequest struct { + // rule uuid + // required: true + AlertID string `json:"alertId" validate:"required"` +} + +func (req *DescribeAlertRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DescribeAlertsRequest struct { + Pageable + // 是否显示全部,取值为1时表示全部 + IsAll string `json:"isAll"` + //user uuid + UserID string `json:"userId"` + //username + UserName string `json:"userName"` + //规则名称 + RuleName string `json:"ruleName"` + //规则uuid + RuleID string `json:"ruleId"` + //资源id,目前就是实例id + ResourceID string `json:"resourceId"` + //报警时间筛选stime + StartTime int64 `json:"startTime"` + //报警时间筛选etime + EndTime int64 `json:"endTime"` + //project uuid + ProjectID string `json:"projectId"` +} + +func (req *DescribeAlertsRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DeleteAlertRequest struct { + //告警id + // required: true + AlertId string `json:"alertId" validate:"required"` +} + +func (req *DeleteAlertRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} diff --git a/bmp-openapi-console/types/request/MonitorDataRequest.go b/bmp-openapi-console/types/request/MonitorDataRequest.go new file mode 100644 index 0000000..6d4d388 --- /dev/null +++ b/bmp-openapi-console/types/request/MonitorDataRequest.go @@ -0,0 +1,33 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +/* +{"params":{"serviceCode":"cps-vpc","resourceId":"cps-2qtflhpvmuuw5tdodatv6ofxqcek","filters":[{"name":"metric","values":["cps.process.total"]}],"startTime":"2024-06-09T00:00:00","endTime":"2024-06-12T23:59:59","timeInterval":"1h", "downSampleType":"avg"}} +*/ +type GetMonitorDataRequest struct { + //指标名称,支持多个,用逗号隔离开 + MetricName string `json:"metricName" validate:"required"` + //实例id + InstanceID string `json:"instanceId" validate:"required"` + //标签值 + Device string `json:"device"` + //开始时间戳 + StartTime int64 `json:"startTime"` + //结束时间戳 + EndTime int64 `json:"endTime"` + // 间隔多久一个点 s为单位 + TimeInterval int `json:"timeInterval"` + //最近多少时间,小时为单位 + LastManyTime int `json:"lastManyTime"` + //avg, min, max, sum + DownSampleType string `json:"downSampleType"` +} + +func (req *GetMonitorDataRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} diff --git a/bmp-openapi-console/types/request/MonitorProxyRequest.go b/bmp-openapi-console/types/request/MonitorProxyRequest.go new file mode 100644 index 0000000..6067594 --- /dev/null +++ b/bmp-openapi-console/types/request/MonitorProxyRequest.go @@ -0,0 +1,26 @@ +package request + +import log "coding.jd.com/aidc-bmp/bmp_log" + +type DesrcibeAgentStatusRequest struct { + // InstanceId,多个用逗号分隔 + // required: true + InstanceID string `json:"instanceId" validate:"required"` +} + +func (req *DesrcibeAgentStatusRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DesrcibeTagsRequest struct { + // instanceId + // required: true + InstanceID string `json:"instanceId" validate:"required"` + // tagName [disk mountpoint nic] + // required: true + TagName string `json:"tagName" validate:"required,oneof=disk mountpoint nic"` +} + +func (req *DesrcibeTagsRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi-console/types/request/MonitorRuleRequest.go b/bmp-openapi-console/types/request/MonitorRuleRequest.go new file mode 100644 index 0000000..ccf7b80 --- /dev/null +++ b/bmp-openapi-console/types/request/MonitorRuleRequest.go @@ -0,0 +1,186 @@ +package request + +import log "coding.jd.com/aidc-bmp/bmp_log" + +type AddRuleRequest struct { + //规则所属的项目uuid + // required: true + ProjectID string `json:"projectId"` + //规则名称 + // required: true + RuleName string `json:"ruleName" validate:"required"` + //维度 [instance、disk、mountpoint、nic] + // required: true + Dimension string `json:"dimension" validate:"required,oneof=instance disk mountpoint nic"` + //资源类型,目前只支持instance + // required: true + Resource string `json:"resource" validate:"required,oneof=instance"` + //触发条件 + // required: true + TriggerOption []RuleTrigger `json:"triggerOption"` + //通知策略 + // required: true + NoticeOption RuleNotice `json:"noticeOption"` + //实例id列表 + // required: true + InstanceIds []string `json:"instanceIds" validate:"required"` + //盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag"` +} + +func (req *AddRuleRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} + +///`{"alertname":"bmpInBand_mr_4msjd0x9vhw7owwur22j4fi4piqc_minping-mock-instanceId_bmp.cpu.util_","calculation":"avg","calculationUnit":"%","instanceId":"minping-mock-instanceId","metric":"bmp.cpu.util","noticeLevel":"1","noticePeriodLabel":"NoticePeriod-180m","operation":"gt","period":"1","ruleId":"mr_4msjd0x9vhw7owwur22j4fi4piqc","threshold":"1","times":"1"}` + +//单个触发条件 +type RuleTrigger struct { + //监控指标 cps.cpu.util + // required: true + Metric string `json:"metric" validate:"required"` + //周期(分钟) [1, 2, 5, 15, 30, 60] + // required: true + Period int64 `json:"period" validate:"required,oneof=1 2 5 15 30 60"` + //计算方式 [min max avg sum] + // required: true + Calculation string `json:"calculation" validate:"required,oneof=min max avg sum"` + //计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出] + CalculationUnit string `json:"calculationUnit"` + //比较方式 [> >= < <= == !=]或者[gt gte lt lte eq neq] + // required: true + Operation string `json:"operation" validate:"required"` + //阈值 + // required: true + Threshold float64 `json:"threshold"` + //持续周期数 [1, 2, 3, 4, 5, 10, 15, 30, 60] + // required: true + Times int64 `json:"times" validate:"required,oneof=1 2 3 4 5 10 15 30 60"` + //告警级别 [1表示一般,2表示严重,3表示紧急] + // required: true + NoticeLevel int64 `json:"noticeLevel" validate:"required,oneof=1 2 3"` +} + +//通知策略 +type RuleNotice struct { + //通知周期(分钟) [5 10 15 30 60 180 360 720 1440] + // required: true + NoticePeriod int64 `json:"noticePeriod" validate:"required,oneof=5 10 15 30 60 180 360 720 1440"` + // 有效时段开始时间 ["00:00:00"] + // required: true + EffectiveIntervalStart string `json:"effectiveIntervalStart" validate:"required"` + // 有效时段结束时间 ["23:59:59"] + // required: true + EffectiveIntervalEnd string `json:"effectiveIntervalEnd" validate:"required"` + //通知条件,可多选 [1表示报警, 2表示恢复正常] + // required: true + NoticeCondition []int64 `json:"noticeCondition" validate:"required"` + //接收渠道,可多选 [1表示站内信, 2表示邮件] + // required: true + NoticeWay []int64 `json:"noticeWay" validate:"required"` + //通知对象 + // required: true + UserID string `json:"userId" validate:"required"` +} + +type DescribeRuleRequest struct { + // rule uuid + // required: true + RuleID string `json:"ruleId" validate:"required"` +} + +func (req *DescribeRuleRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DescribeRulesRequest struct { + Pageable + // 是否显示全部,取值为1时表示全部 + IsAll string `json:"isAll"` + //user uuid + UserID string `json:"userId"` + //username + UserName string `json:"userName"` + //规则名称,模糊搜索 + RuleName string `json:"ruleName"` + //规则uuid + RuleID string `json:"ruleId"` + //规则状态[1->正常,2->禁用,3->报警] + Status int `json:"status"` + //project uuid + ProjectID string `json:"projectId"` +} + +func (req *DescribeRulesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type EditRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` + //规则名称 + // required: true + RuleName string `json:"ruleName" validate:"required"` + //维度 [instance、disk、mountpoint、nic] + // required: true + Dimension string `json:"dimension" validate:"required,oneof=instance disk mountpoint nic"` + //资源类型,目前只支持instance + // required: true + Resource string `json:"resource" validate:"required,oneof=instance"` + //触发条件 + // required: true + TriggerOption []RuleTrigger `json:"triggerOption"` + //通知策略 + // required: true + NoticeOption RuleNotice `json:"noticeOption"` + //实例id列表 + // required: true + InstanceIds []string `json:"instanceIds" validate:"required"` + //盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag"` +} + +func (req *EditRuleRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} + +type EnableRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` +} + +func (req *EnableRuleRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} + +type DisableRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` +} + +func (req *DisableRuleRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} + +type DeleteRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` +} + +func (req *DeleteRuleRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} diff --git a/bmp-openapi-console/types/request/OsRequest.go b/bmp-openapi-console/types/request/OsRequest.go new file mode 100644 index 0000000..26556d3 --- /dev/null +++ b/bmp-openapi-console/types/request/OsRequest.go @@ -0,0 +1,63 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateOSRequest struct { + // 操作系统名称 + // required: true + OsName string `json:"osName" validate:"required,min=1,max=200"` + // 操作系统平台 + // required: true + OsType string `json:"osType" validate:"required"` + // 体系架构 + // required: true + Architecture string `json:"architecture" validate:"required"` + // 位数 + // required: true + Bits int `json:"bits" validate:"required"` + // 操作系统版本 + // required: true + OsVersion string `json:"osVersion" validate:"required"` + // 系统用户 + SysUser string `json:"sysUser"` +} + +func (req *CreateOSRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type ModifyOSRequest struct { + // 操作系统名称 + OsName string `json:"osName"` + // 操作系统平台 + OsType string `json:"osType"` + // 体系架构 + Architecture string `json:"architecture"` + // 位数 + Bits int `json:"bits" ` + // 操作系统版本 + OsVersion string `json:"osVersion"` + // 系统用户 + SysUser string `json:"sysUser"` +} + +func (req *ModifyOSRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryOssRequest struct { + // 操作系统名称 + OsName string `json:"osName"` + // 操作系统平台 + OsType string `json:"osType"` + // 操作系统版本 + OsVersion string `json:"osVersion"` + // 是否显示所有 + IsAll string `json:"isAll"` +} + +func (req *QueryOssRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi-console/types/request/ProjectRequest.go b/bmp-openapi-console/types/request/ProjectRequest.go new file mode 100644 index 0000000..3efbc87 --- /dev/null +++ b/bmp-openapi-console/types/request/ProjectRequest.go @@ -0,0 +1,152 @@ +package request + +import ( + "regexp" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateProjectRequest struct { + // ProjectName 1~64字符,只支持数字、大小写字母、中英文下划线“_”及中划线“-” + // required: true + ProjectName string `json:"projectName" validate:"required"` //项目名称 + // 是否作为该用户的默认项目, [0/1], 默认为0 + IsDefault int8 `json:"isDefault" validate:"omitempty,oneof=0 1"` + // 是否作为系统项目, [0/1], 默认为0 + IsSystem int8 `json:"isSystem" validate:"omitempty,oneof=0 1"` +} + +func (req *CreateProjectRequest) Validate(logger *log.Logger) { + validate(req, logger) + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 + specialMatch := regexp.MustCompile("^[\u4e00-\u9fa5_a-zA-Z0-9_-]{1,64}$").MatchString + if !specialMatch(req.ProjectName) { + panic(constant.BuildInvalidArgumentWithArgs("projectName格式不正确", "Name invalidate")) + } + +} + +type ModifyProjectRequest struct { + // 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + // required: true + ProjectName string `json:"projectName" validate:"required"` +} + +func (req *ModifyProjectRequest) Validate(logger *log.Logger) { + validate(req, logger) + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 + specialMatch := regexp.MustCompile("^[\u4e00-\u9fa5_a-zA-Z0-9_-]{1,64}$").MatchString + if !specialMatch(req.ProjectName) { + panic(constant.BuildInvalidArgumentWithArgs("projectName格式不正确", "Name invalidate")) + } + +} + +type ModifyProjectDescriptionRequest struct { + // 项目描述 + // required: true + Description string `json:"description"` +} + +func (req *ModifyProjectDescriptionRequest) Validate(logger *log.Logger) { + validate(req, logger) + +} + +type QueryProjectsRequest struct { + // 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + ProjectName string `json:"projectName"` + //0表示全部,1表示拥有者,2表示被共享者 + Owned int `json:"owned"` + Pageable + IsAll string `json:"isAll"` + //按创建时间asc/desc排列 + OrderByCreatetime string `json:"orderByCreatetime"` + //新增可选,按用户名查找 + OwnerName string `json:"ownerName"` + //新增可选,按被转移用户的用户名查找它拥有的项目 + SharerName string `json:"sharerName"` +} + +func (req *QueryProjectsRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type ShareProjectRequest struct { + // from user_id + // required: true + OwnerID string `json:"ownerID" validate:"required"` + // to user_id + // required: true + SharerID string `json:"sharerID" validate:"required"` + // 如果部分分享,instance_id逗号分隔; 如果全部分享,传all + // required: true + InstanceIDs string `json:"instanceIDs"` //all表示项目下的全部资源,否则instance_id逗号分隔传过来 +} + +func (req *ShareProjectRequest) Validate(logger *log.Logger) { + validate(req, logger) + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 +} + +type CalcelShareProjectRequest struct { + // from user_id + // required: true + OwnerID string `json:"ownerID" validate:"required"` + // to user_id + // required: true + SharerID string `json:"sharerID" validate:"required"` +} + +func (req *CalcelShareProjectRequest) Validate(logger *log.Logger) { + validate(req, logger) + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 +} + +type MoveProjectRequest struct { + // from user_id + // required: true + OwnerID string `json:"ownerID" validate:"required"` + // to user_id + // required: true + MoverID string `json:"moverID" validate:"required"` + // 【read/write】 + // required: true + // Premisson string `json:"premission" validate:"required,oneof=read write"` +} + +func (req *MoveProjectRequest) Validate(logger *log.Logger) { + validate(req, logger) + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 +} + +type MoveInstancesRequest struct { + // instanceIDs + // required: true + InstanceIDs string `json:"instanceIDs" validate:"required"` + // from project_id + // required: true + OwnerProjectID string `json:"ownerProjectID" validate:"required"` + // to project_id + // required: true + MoverProjectID string `json:"moverProjectID" validate:"required"` + + // from user_id + // required: true + OwnerID string `json:"ownerID" validate:"required"` + + // to user_id + // required: true + MoverID string `json:"moverID" validate:"required"` + + // 【read/write】 + // required: true + // Premisson string `json:"premission" validate:"required,oneof=read write"` +} + +func (req *MoveInstancesRequest) Validate(logger *log.Logger) { + validate(req, logger) + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 +} diff --git a/bmp-openapi-console/types/request/RaidRequest.go b/bmp-openapi-console/types/request/RaidRequest.go new file mode 100644 index 0000000..5fa1696 --- /dev/null +++ b/bmp-openapi-console/types/request/RaidRequest.go @@ -0,0 +1,37 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateRaidRequest struct { + // raid名称 + // required: true + Name string `json:"name" validate:"required,min=1,max=16"` + // raid描述(中文) + // required: true + DescriptionEn string `json:"descriptionEn" validate:"required"` + // raid描述(英文) + // required: true + DescriptionZh string `json:"descriptionZh" validate:"required"` +} + +func (req *CreateRaidRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type ModifyRaidRequest struct { + // raid名称 + // required: true + Name string `json:"name" validate:"required,min=1,max=16"` + // raid描述(中文) + // required: true + DescriptionEn string `json:"descriptionEn" validate:"required"` + // raid描述(英文) + // required: true + DescriptionZh string `json:"descriptionZh" validate:"required"` +} + +func (req *ModifyRaidRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi-console/types/request/ResourceRequest.go b/bmp-openapi-console/types/request/ResourceRequest.go new file mode 100644 index 0000000..7125f8e --- /dev/null +++ b/bmp-openapi-console/types/request/ResourceRequest.go @@ -0,0 +1,24 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type QueryResourcesRequest struct { + /*// 机房名称 + IdcName string `json:"idcName"` + // 机房英文名称 + IdcNameEn string `json:"idcNameEn"`*/ + // 机型名称 + Name string `json:"name"` + // 机型规格 + DeviceType string `json:"deviceType"` + // 镜像名称 + ImageName string `json:"imageName"` + // 用户名称 + UserName string `json:"userName"` +} + +func (req *QueryResourcesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi-console/types/request/RoleRequest.go b/bmp-openapi-console/types/request/RoleRequest.go new file mode 100644 index 0000000..1e21f06 --- /dev/null +++ b/bmp-openapi-console/types/request/RoleRequest.go @@ -0,0 +1,44 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateRoleRequest struct { + // 角色英文名称 + // required: true + RoleNameEn string `json:"roleNameEn" validate:"required"` + // 角色中文名称 + // required: true + RoleNameCn string `json:"roleNameCn" validate:"required"` + // 角色描述英文名称 + // required: true + DescriptionEn string `json:"descriptionEn" validate:"required"` + // 角色描述中文名称 + // required: true + DescriptionCn string `json:"descriptionCn" validate:"required"` +} +type ModifyRoleRequest struct { + // 角色英文名称 + RoleNameEn string `json:"roleNameEn"` + // 角色中文名称 + RoleNameCn string `json:"roleNameCn"` + // 角色描述英文名称 + DescriptionEn string `json:"descriptionEn"` + // 角色描述中文名称 + DescriptionCn string `json:"descriptionCn"` +} + +func (req *CreateRoleRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryRolesRequest struct { + Pageable + // 是否显示所有 + IsAll string `json:"isAll"` +} + +func (req *QueryRolesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi-console/types/request/SshkeyRequest.go b/bmp-openapi-console/types/request/SshkeyRequest.go new file mode 100644 index 0000000..202c005 --- /dev/null +++ b/bmp-openapi-console/types/request/SshkeyRequest.go @@ -0,0 +1,61 @@ +package request + +import ( + "regexp" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +const REGEX_RSA_PUBLIC_KEY = "^ssh-rsa AAAAB3NzaC1yc2.*" + +type CreateSshkeyRequest struct { + // 秘钥名称 + // required: true + Name string `json:"name" validate:"required"` + // 公钥内容,格式:^ssh-rsa AAAAB3NzaC1yc2.* + // required: true + Key string `json:"key" validate:"required"` +} +type ModifySshkeyRequest struct { + // 秘钥名称 + // Extensions: + // x-nullable: true + Name *string `json:"name" validate:"omitempty,max=64"` +} + +func (req *CreateSshkeyRequest) Validate(logger *log.Logger) { + validate(req, logger) + //name条件:1~64 字符,只支持数字、大小写字母、英文下划线“_”及中划线 + specialMatch := regexp.MustCompile("^[a-zA-Z0-9_-]{1,64}$").MatchString + if !specialMatch(req.Name) { + panic(constant.BuildInvalidArgumentWithArgs("name格式不正确", "Name invalidate")) + } + if match, _ := regexp.MatchString(REGEX_RSA_PUBLIC_KEY, req.Key); !match { + logger.Warn("CreateKeypairRequest.PublicKey invalid", req.Key) + panic(constant.BuildInvalidArgumentWithArgs("公钥不合法", "publickey invalid")) + } + +} + +func (req *ModifySshkeyRequest) Validate(logger *log.Logger) { + validate(req, logger) + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 + specialMatch := regexp.MustCompile("^[a-zA-Z0-9_-]{1,64}$").MatchString + if req.Name != nil && !specialMatch(*req.Name) { + panic(constant.BuildInvalidArgumentWithArgs("name格式不正确", "Name invalidate")) + } + +} + +type QuerySshkeysRequest struct { + // 秘钥名称 + Name string `json:"name"` // 秘钥名称 + Pageable + // 是否显示全部 + IsAll string `json:"isAll"` +} + +func (req *QuerySshkeysRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi-console/types/request/UserRequest.go b/bmp-openapi-console/types/request/UserRequest.go new file mode 100644 index 0000000..3a356cf --- /dev/null +++ b/bmp-openapi-console/types/request/UserRequest.go @@ -0,0 +1,284 @@ +package request + +import ( + "fmt" + "regexp" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateUserRequest struct { + + // 角色uuid + // required: true + RoleID string `json:"roleId"` + // 用户名,唯一, 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + // required: true + UserName string `json:"userName" validate:"required,min=1,max=64"` + // 邮箱 + Email string `json:"email" validate:"required,email"` + // 国家地区码,如86 + PhonePrefix string `json:"phonePrefix" validate:"required,min=1,max=64"` + // 手机号 + PhoneNumber string `json:"phoneNumber" validate:"required,min=1,max=64"` + // 用户默认项目uuid + DefaultProjectID string `json:"defaultProjectId"` + // 语言[en_US, zh_CN] + Language string `json:"language" validate:"omitempty,oneof=en_US zh_CN"` + // 时区,Asia/Shanghai + Timezone string `json:"timezone"` + // 密码 明文 密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + // required: true + Password string `json:"password"` + // 描述 + Description string `json:"description" validate:"max=256"` +} + +func (req *CreateUserRequest) Validate(logger *log.Logger) { + validate(req, logger) + //matched, err := regexp.MatchString(`^[a-zA-Z-_0-9]{1,32}$`, req.UserName) + //if err != nil { + // logger.Warn("CreateUserRequest.Validate error:", err.Error()) + // panic(constant.BuildInvalidArgumentWithArgs(err.Error(), err.Error())) + //} + //if !matched { + // logger.Warn("CreateUserRequest.Validate userName error") + // panic(constant.BuildInvalidArgumentWithArgs("用户名格式不正确", "userName invalidate")) + //} + + matchedPhone, err := regexp.MatchString(`^[0-9]+$`, req.PhoneNumber) + if err != nil { + logger.Warn("CreateUserRequest.Validate error:", err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(err.Error(), err.Error())) + } + if !matchedPhone { + logger.Warn("CreateUserRequest.Validate phoneNumber error") + panic(constant.BuildInvalidArgumentWithArgs("手机格式不正确", "phoneNumber invalidate")) + } + + if req.Timezone == "" { + req.Timezone = "Asia/Shanghai" + } + passwd := req.Password + //密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + lowercaseMatch := regexp.MustCompile(`[a-z]`).MatchString + uppercaseMatch := regexp.MustCompile(`[A-Z]`).MatchString + digitMatch := regexp.MustCompile(`\d`).MatchString + //()`~!@#$%&*_-+=|{}[]:";'<>,.?/ + specialMatch := regexp.MustCompile("[()`~!@#$%&*\\_\\-+=|{}\\[\\]:\";'<>,.?/]").MatchString + total := 0 + if lowercaseMatch(passwd) { + total += 1 + } + if uppercaseMatch(passwd) { + total += 1 + } + if digitMatch(passwd) { + total += 1 + } + if specialMatch(passwd) { + total += 1 + } + + if total >= 3 && len(passwd) >= 8 && len(passwd) <= 30 { + return + } + panic(constant.BuildInvalidArgumentWithArgs("密码格式不正确", "password invalidate")) +} + +type ModifyUserRequest struct { + // 邮箱 + // Extensions: + // x-nullable: true + Email *string `json:"email" validate:"omitempty,email"` + // 国家地区码,如86 + // Extensions: + // x-nullable: true + PhonePrefix *string `json:"phonePrefix" validate:"omitempty,min=1,max=64"` + // 手机号 + // Extensions: + // x-nullable: true + PhoneNumber *string `json:"phoneNumber" validate:"omitempty,min=1,max=64"` + // 描述 + // Extensions: + // x-nullable: true + Description *string `json:"description" validate:"omitempty,min=0,max=256"` +} + +func (req *ModifyUserRequest) Validate(logger *log.Logger) { + + validate(req, logger) + //matched, err := regexp.MatchString(`^[a-zA-Z-_0-9]{1,32}$`, req.UserName) + //if err != nil { + // logger.Warn("ModifyUserRequest.Validate error:", err.Error()) + // panic(constant.BuildInvalidArgumentWithArgs(err.Error(), err.Error())) + //} + //if !matched { + // logger.Warn("ModifyUserRequest.Validate userName error") + // panic(constant.BuildInvalidArgumentWithArgs("用户名格式不正确", "userName invalidate")) + //} + + if req.PhoneNumber != nil { + matchedPhone, err := regexp.MatchString(`^[0-9]+$`, *req.PhoneNumber) + if err != nil { + logger.Warn("ModifyUserRequest.Validate error:", err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(err.Error(), err.Error())) + } + if !matchedPhone { + logger.Warn("ModifyUserRequest.Validate phoneNumber error") + panic(constant.BuildInvalidArgumentWithArgs("手机格式不正确", "phoneNumber invalidate")) + } + } + +} + +type ModifyUserPasswordRequest struct { + // 旧密码,明文 + // required: true + OldPassword string `json:"oldPassword"` + // 新密码 明文,密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + // required: true + Password string `json:"password"` +} + +func (req *ModifyUserPasswordRequest) Validate(logger *log.Logger) { + + passwd := req.Password + //密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + lowercaseMatch := regexp.MustCompile(`[a-z]`).MatchString + uppercaseMatch := regexp.MustCompile(`[A-Z]`).MatchString + digitMatch := regexp.MustCompile(`\d`).MatchString + //()`~!@#$%&*_-+=|{}[]:";'<>,.?/ + specialMatch := regexp.MustCompile("[()`~!@#$%&*\\_\\-+=|{}\\[\\]:\";'<>,.?/]").MatchString + total := 0 + if lowercaseMatch(passwd) { + total += 1 + } + if uppercaseMatch(passwd) { + total += 1 + } + if digitMatch(passwd) { + total += 1 + } + if specialMatch(passwd) { + total += 1 + } + + if total >= 3 && len(passwd) >= 8 && len(passwd) <= 30 { + return + } + panic(constant.BuildInvalidArgumentWithArgs("密码格式不正确", "password invalidate")) + +} + +type ModifyLocalUserRequest struct { + // 邮箱 + // Extensions: + // x-nullable: true + Email *string `json:"email" validate:"omitempty,email"` + // 国家地区码,如86 + // Extensions: + // x-nullable: true + PhonePrefix *string `json:"phonePrefix" validate:"omitempty,min=0,max=64"` + // 手机号 + // Extensions: + // x-nullable: true + PhoneNumber *string `json:"phoneNumber" validate:"omitempty,min=0,max=64"` + // 用户默认项目uuid + // Extensions: + // x-nullable: true + DefaultProjectID *string `json:"defaultProjectId" validate:"omitempty,min=0,max=64"` + // 语言[en_US, zh_CN] + // Extensions: + // x-nullable: true + Language *string `json:"language" validate:"omitempty,oneof=en_US zh_CN"` // 语言(中文/English) + // 时区 Asia/Shanghai + // Extensions: + // x-nullable: true + Timezone *string `json:"timezone" validate:"omitempty,min=0,max=64"` +} + +func (req *ModifyLocalUserRequest) Validate(logger *log.Logger) { + + validate(req, logger) + if req.PhonePrefix != nil { + var phoneReg string + if *req.PhonePrefix == "086" { //中国大陆手机号 + phoneReg = `^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$` + } else if *req.PhonePrefix == "852" { //中国香港 + phoneReg = `^([5|6|9])\d{7}$` + } else if *req.PhonePrefix == "853" { //中国澳门 + phoneReg = `^6\d{7}$` + } else if *req.PhonePrefix == "886" { //中国台湾 + phoneReg = `^[0][9]\d{8}$` + } else { + phoneReg = `^[0-9]{1,}$` + } + + fmt.Println("dddd", *req.PhonePrefix) + if req.PhoneNumber != nil { + matchedPhone, err := regexp.MatchString(phoneReg, *req.PhoneNumber) + if err != nil { + logger.Warn("ModifyUserRequest.Validate error:", err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(err.Error(), err.Error())) + } + if !matchedPhone { + logger.Warn("ModifyUserRequest.Validate phoneNumber error") + panic(constant.BuildInvalidArgumentWithArgs("手机格式不正确", "phoneNumber invalidate")) + } + } + } +} + +type GetUserByNameRequest struct { + + // 用户名,唯一 + // required: true + UserName string `json:"userName"` +} + +func (req *GetUserByNameRequest) Validate(logger *log.Logger) { + //matched, err := regexp.MatchString(`^[a-zA-Z-_0-9]{1,32}$`, req.UserName) + //if err != nil { + // logger.Warn("ModifyUserRequest.Validate error:", err.Error()) + // panic(constant.INVALID_ARGUMENT) + //} + //if !matched { + // logger.Warn("ModifyUserRequest.Validate projectName error") + // panic(constant.INVALID_ARGUMENT) + //} +} + +type QueryUsersRequest struct { + // 角色uuid + RoleID string `json:"roleId"` + // 项目uuid + DefaultProjectID string `json:"defaultProjectId"` + // 用户名 + UserName string `json:"userName"` + Pageable + // 是否显示全部, isAll=1表示全部 + IsAll string `json:"isAll"` +} + +func (req *QueryUsersRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type VerifyUserRequest struct { + // 用户名,唯一 + // required: true + UserName string `json:"userName" validate:"required"` // + // 密码 + // required: true + Password string `json:"password" validate:"required"` // + // 角色uuid + // required: true + RoleID string `json:"roleId" validate:"required"` +} + +func (req *VerifyUserRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi-console/types/response/ApiKey.go b/bmp-openapi-console/types/response/ApiKey.go new file mode 100644 index 0000000..be742f0 --- /dev/null +++ b/bmp-openapi-console/types/response/ApiKey.go @@ -0,0 +1,45 @@ +package response + +type Apikey struct { + ID int `json:"id"` + // apikey uuid + // required: true + ApikeyID string `json:"apiKeyId"` + // 名称 + // required: true + Name string `json:"name"` + // 是否支持只读, [0/1], 1表示只读 + // required: true + ReadOnly int8 `json:"readOnly"` + // 32位字符令牌,使用token来独立访问openapi + // required: true + Token string `json:"token"` + // apikey的类型,[system/user] + // required: true + Type string `json:"type"` + // 所属用户uuid + // required: true + UserID string `json:"userId"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` +} +type ApikeyList struct { + Apikeys []*Apikey `json:"apikeys"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type ApikeyInfo struct { + Apikey *Apikey `json:"apikey"` +} +type ApikeyId struct { + // apikey uuid + // required: true + ApikeyId string `json:"apikeyId"` +} diff --git a/bmp-openapi-console/types/response/AuditLogs.go b/bmp-openapi-console/types/response/AuditLogs.go new file mode 100644 index 0000000..d93f492 --- /dev/null +++ b/bmp-openapi-console/types/response/AuditLogs.go @@ -0,0 +1,61 @@ +package response + +import ( + "encoding/json" +) + +type AuditLog struct { + ID int `json:"id"` + // 日志uuid + LogID string `json:"logid"` + // 操作 + Operation string `json:"operation"` + // 操作名称 + OperationName string `json:"operationName"` + // 操作人 + UserName string `json:"userName"` + // 操作人 + UserID string `json:"userID"` + //sn + Sn string `json:"sn"` + //device_id + DeviceID string `json:"deviceId"` + //instance_id + InstanceID string `json:"instanceId"` + //结果 success/fail + Result string `json:"result"` + //失败原因 + FailReason string `json:"failReason"` // reason for fail + // 操作时间 + OperateTime int `json:"operateTime"` + // 完成时间 + FinishTime int `json:"finishTime"` +} + +type AuditLogList struct { + // 机型列表 + AuditLogs []*AuditLog `json:"auditLogs"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} + +func (d AuditLog) MarshalJSON() ([]byte, error) { + type Alias AuditLog + return json.Marshal(struct { + Alias + //CreateTime string `json:"create_time"` + //UpdateTime string `json:"update_time"` + }{ + Alias: Alias(d), + //CreateTime: d.CreateTime.Format("2006-01-02 15:04:05"), + //UpdateTime: d.UpdateTime.Format("2006-01-02 15:04:05"), + }) +} + +type AuditLogsType struct { + // 数据库中存储的operation + Operation string `json:"operation"` + // name,自动适配中英文 + Name string `json:"name"` +} diff --git a/bmp-openapi-console/types/response/CommonResponse.go b/bmp-openapi-console/types/response/CommonResponse.go new file mode 100644 index 0000000..070b2a1 --- /dev/null +++ b/bmp-openapi-console/types/response/CommonResponse.go @@ -0,0 +1,8 @@ +package response + +type CommonResponse struct { + // 操作是否成功 [true/false] + Success bool `json:"success"` +} +type CommonInfoResponse struct { +} diff --git a/bmp-openapi-console/types/response/Device.go b/bmp-openapi-console/types/response/Device.go new file mode 100644 index 0000000..94882b2 --- /dev/null +++ b/bmp-openapi-console/types/response/Device.go @@ -0,0 +1,236 @@ +package response + +import ( + "encoding/json" +) + +type Device struct { + // 机房uuid + // required: true + IdcID string `json:"idcId"` + //机型uuid + DeviceTypeID string `json:"deviceTypeId"` + // 设备ID编号 + ID int `json:"id"` + // 设备SN + Sn string `json:"sn"` + // 设备uuid + DeviceID string `json:"deviceId"` + // 实例id + InstanceID string `json:"instanceId"` + // 设备状态: 未装机,已装机 + ManageStatus string `json:"manageStatus"` + // 设备状态: 未装机,已装机 + ManageStatusName string `json:"manageStatusName"` + // 实例是否锁定 锁定locked 未锁定unlocked + Locked string `json:"locked"` + //品牌 + Brand string `json:"brand"` + //型号 + Model string `json:"model"` + // 设备状态变更失败原因 + Reason string `json:"reason"` + // 机柜编码 + Cabinet string `json:"cabinet"` + // U位 + UPosition string `json:"uPosition"` + // 带外管理IP + IloIP string `json:"iloIp"` + // 带外账号 + IloUser string `json:"iloUser"` + // 带外账号密码 + IloPassword string `json:"iloPassword"` + // MAC1(eth0) + Mac1 string `gorm:"column:mac1" json:"mac1"` + // MAC2(eth2) + Mac2 string `gorm:"column:mac2" json:"mac2"` + // 交换机1ip + SwitchIP1 string `gorm:"column:switch_ip1" json:"switchIp1"` + // 交换机1port + SwitchPort1 string `gorm:"column:switch_port1" json:"switchPort1"` + // 交换机2ip + SwitchIP2 string `gorm:"column:switch_ip2" json:"switchIp2"` + // 交换机2port + SwitchPort2 string `gorm:"column:switch_port2" json:"switchPort2"` + // 交换机1登录账号,如果为空,取所在机房的值 + SwitchUser1 string `json:"switchUser1"` + // 交换机1登录密码 + SwitchPassword1 string `json:"switchPassword1"` + // 交换机2登录账号,如果为空,取所在机房的值 + SwitchUser2 string `json:"switchUser2"` + // 交换机2登录密码 + SwitchPassword2 string `json:"switchPassword2"` + // 描述 + Description string `json:"description"` + // 网口交换机IP + SwitchIP string `json:"switchIp"` + // 子网掩码 + Mask string `json:"mask"` + // eth1子网掩码 + Eth1Mask string `json:"eth1Mask"` + // 网关地址 + Gateway string `json:"gateway"` + // 内网IPV4 + PrivateIPv4 string `json:"privateIpv4"` + // 内网IPV6 + PrivateIPv6 string `json:"privateIpv6"` + // eth1内网IPV4 + PrivateEth1IPv4 string `json:"privateEth1Ipv4"` + // eth1内网IPV6 + PrivateEth1IPv6 string `json:"privateEth1Ipv6"` + // adapter_id + AdapterID int `json:"adapterId"` + // raid工具:(megacli64等) + RaidDriver string `json:"raidDriver"` + //添加到disk表, 系统盘1背板号 + Enclosure1 string `json:"enclosure1"` + //系统盘1槽位 + Slot1 int `json:"slot1"` + //系统盘2背板号 + Enclosure2 string `json:"Enclosure2"` + //系统盘2槽位 + Slot2 int `json:"slot2"` + //以后还能还有数据盘,todo + + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` + //DeletedTime int `json:"deletedTime"` // 删除时间戳 + //IsDel int8 `json:"isDel"` // 是否删除0未删除 1已删除 + + //以下是通过别的表查询出来的数据,用于返回给上层 + + //机房名称 + IdcName string `json:"idcName"` + //idcname + IDcNameEn string `json:"idcNameEn"` + //机型名称 + DeviceTypeName string `json:"deviceTypeName"` + + // 实例名称 + InstanceName string `json:"instanceName"` + // 实例镜像名称 + ImageName string `json:"imageName"` + // 实例状态 + InstanceStatus string `json:"instanceStatus"` + // 实例状态 + InstanceStatusName string `json:"instanceStatusName"` + // 实例失败原因 + InstanceReason string `json:"instanceReason"` + // 实例归属用户uuid + UserId string `json:"userId"` + // 实例归属用户名称 + UserName string `json:"userName"` + // 实例创建时间 + InstanceCreatedTime string `json:"instanceCreatedTime"` + // 实例描述 + InstanceDescription string `json:"instanceDescription"` + //机型配置 + + //型号,机型规格cps.normal + DeviceType string `json:"deviceType"` + //计算型,存储型 + DeviceSeries string `json:"deviceSeries"` + //计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName"` + // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Architecture string `json:"architecture"` + // cpu数量 + CPUAmount int `json:"cpuAmount"` + // 单个cpu内核数 + CPUCores int `json:"cpuCores"` + // 单个cpu路数 + CPURoads int8 `json:"cpuRoads"` + // cpu厂商 + CPUManufacturer string `json:"cpuManufacturer"` + // cpu处理器型号 + CPUModel string `json:"cpuModel"` + // cpu频率(G) + CPUFrequency string `json:"cpuFrequency"` + // 内存接口(如DDR3,DDR4) + MemType string `json:"memType"` + // 单个内存大小(GB) + MemSize int `json:"memSize"` + // 内存数量 + MemAmount int `json:"memAmount"` + // 内存主频(MHz) + MemFrequency int `json:"memFrequency"` + // 网卡数量 + NicAmount int `json:"nicAmount"` + // 网卡传输速率(GE) + NicRate int `json:"nicRate"` + // 【网口模式】【网络设置】: bond单网口,dual双网口 + InterfaceMode string `json:"interfaceMode"` + // 系统盘类型(SSD,HDD) + SystemVolumeType string `json:"systemVolumeType"` + // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeInterfaceType string `json:"systemVolumeInterfaceType"` + // 系统盘单盘大小 + SystemVolumeSize int `json:"systemVolumeSize"` + //SystemVolumeUnit string `json:"systemVolumeUnit"` // 系统盘单位(GB,TB) + + // 系统盘数量 + SystemVolumeAmount int `json:"systemVolumeAmount"` + // gpu数量 + GpuAmount int `json:"gpuAmount"` + // gpu厂商 + GpuManufacturer string `json:"gpuManufacturer"` + // gpu处理器型号 + GpuModel string `json:"gpuModel"` + // 数据盘类型(SSD,HDD) + DataVolumeType string `json:"dataVolumeType"` + // 数据盘接口类型(SATA,SAS,NVME) + DataVolumeInterfaceType string `json:"dataVolumeInterfaceType"` + // 数据盘单盘大小 + DataVolumeSize int `json:"dataVolumeSize"` + //DataVolumeUnit string `json:"dataVolumeUnit"` // 数据盘单位(GB,TB) + + // 数据盘数量 + DataVolumeAmount int `json:"dataVolumeAmount"` + + //拼装信息 + CpuInfo string `json:"cpuInfo"` + MemInfo string `json:"memInfo"` + SvInfo string `json:"svInfo"` + DvInfo string `json:"dvInfo"` + GpuInfo string `json:"gpuInfo"` + NicInfo string `json:"nicInfo"` +} + +type DeviceList struct { + // 设备列表 + Devices []*Device `json:"devices"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type DeviceInfo struct { + // 设备 + Device *Device `json:"device"` +} +type DeviceIds struct { + // 设备id列表 + DeviceIds []string `json:"deviceIds"` +} +type DeviceStock struct { + // 库存量 + Stocks int `json:"stocks"` +} + +func (d Device) MarshalJSON() ([]byte, error) { + type Alias Device + return json.Marshal(struct { + Alias + //CreateTime string `json:"create_time"` + //UpdateTime string `json:"update_time"` + }{ + Alias: Alias(d), + //CreateTime: d.CreateTime.Format("2006-01-02 15:04:05"), + //UpdateTime: d.UpdateTime.Format("2006-01-02 15:04:05"), + }) +} diff --git a/bmp-openapi-console/types/response/DeviceType.go b/bmp-openapi-console/types/response/DeviceType.go new file mode 100644 index 0000000..7ed9574 --- /dev/null +++ b/bmp-openapi-console/types/response/DeviceType.go @@ -0,0 +1,129 @@ +package response + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/volumeDao" +) + +type DeviceType struct { + ID int `json:"id"` + // 机房uuid + IDcID string `json:"idcId"` + // 机房名称 + IDcName string `json:"idcName"` + // 机房名称 + IDcNameEn string `json:"idcNameEn"` + // 机型uuid + DeviceTypeID string `json:"deviceTypeId"` + // 机型名称,如计算效能型,标准计算型 + Name string `json:"name"` + // 机型规格, cps.c.normal + DeviceType string `json:"deviceType"` + // 机型类型,如计算型,存储型 + DeviceSeries string `json:"deviceSeries"` + // 机型类型,如计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName"` + // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Architecture string `json:"architecture"` + // 显示机型高度 + Height int `json:"height"` + // 描述 + Description string `json:"description"` + // cpu数量 + CPUAmount int `json:"cpuAmount"` + // 单个cpu内核数 + CPUCores int `json:"cpuCores"` + // cpu厂商 + CPUManufacturer string `json:"cpuManufacturer"` + // cpu处理器型号 + CPUModel string `json:"cpuModel"` + // cpu频率(G) + CPUFrequency string `json:"cpuFrequency"` + // 内存接口(如DDR3,DDR4) + MemType string `json:"memType"` + // 单个内存大小(GB) + MemSize int `json:"memSize"` + // 内存数量 + MemAmount int `json:"memAmount"` + // 内存主频(MHz) + MemFrequency int `json:"memFrequency"` + // 网卡数量 + NicAmount int `json:"nicAmount"` + // 网卡传输速率(GE) + NicRate int `json:"nicRate"` + // bond单网口,dual双网口 + InterfaceMode string `json:"interfaceMode"` + // gpu数量 + GpuAmount int `json:"gpuAmount"` + // gpu厂商 + GpuManufacturer string `json:"gpuManufacturer"` + // gpu处理器型号 + GpuModel string `json:"gpuModel"` + // 机型的卷信息 + Volumes []*volumeDao.Volume `json:"volumes"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` + // StockAvailable 可用库存 + StockAvailable int `json:"stockAvailable"` + // raid配置 + RaidCan string `json:"raidCan"` + //系统盘raid + Raid string `json:"raid"` + // CPU 规格,预置还是其它 + CpuSpec string `json:"cpuSpec"` + // 内存 规格,预置还是其它 + MemSpec string `json:"memSpec"` + + //拼装信息 + CpuInfo string `json:"cpuInfo"` + MemInfo string `json:"memInfo"` + SvInfo string `json:"svInfo"` + DvInfo string `json:"dvInfo"` + GpuInfo string `json:"gpuInfo"` + NicInfo string `json:"nicInfo"` + + InstanceCount int `json:"instanceCount"` + DeviceCount int `json:"deviceCount"` + InstanceStatus []string `json:"instanceStatus"` + //boot模式 + BootMode string `json:"boot_mode"` + // 是否配置了阵列卡 + IsNeedRaid string `json:"isNeedRaid"` +} + +type DeviceTypeList struct { + // 机型列表 + DeviceTypes []*DeviceType `json:"deviceTypes"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type DeviceTypeInfo struct { + // 机型信息 + DeviceType *DeviceType `json:"deviceType"` +} +type DeviceTypeId struct { + // 机型uuid + // required: true + DeviceTypeId string `json:"deviceTypeId"` +} + +func (d DeviceType) MarshalJSON() ([]byte, error) { + type Alias DeviceType + return json.Marshal(struct { + Alias + //CreateTime string `json:"create_time"` + //UpdateTime string `json:"update_time"` + }{ + Alias: Alias(d), + //CreateTime: d.CreateTime.Format("2006-01-02 15:04:05"), + //UpdateTime: d.UpdateTime.Format("2006-01-02 15:04:05"), + }) +} diff --git a/bmp-openapi-console/types/response/DeviceTypeImagePartitionResponse.go b/bmp-openapi-console/types/response/DeviceTypeImagePartitionResponse.go new file mode 100644 index 0000000..e102dcb --- /dev/null +++ b/bmp-openapi-console/types/response/DeviceTypeImagePartitionResponse.go @@ -0,0 +1,17 @@ +package response + +type QueryDeviceTypeImagePartitionResponse struct { + //系统盘分区列表 + SystemPartition []Partition `json:"systemPartition"` + //数据盘分区列表 + DataPartition []Partition `json:"dataPartition"` +} + +type Partition struct { + //format,如[swap, xfs] + FsType string `json:"format"` + //point,如[swap, /, /var] + MountPoint string `json:"point"` + // 分区大小, MB为单位 + Size int `json:"size"` +} diff --git a/bmp-openapi-console/types/response/Idc.go b/bmp-openapi-console/types/response/Idc.go new file mode 100644 index 0000000..7f8fae2 --- /dev/null +++ b/bmp-openapi-console/types/response/Idc.go @@ -0,0 +1,68 @@ +package response + +type Idc struct { + ID int `json:"id"` + // 机房uuid + IDcID string `json:"idcId"` + // 机房名称 + Name string `json:"name"` + // 机房名称en + NameEn string `json:"nameEn"` + // shortname + Shortname string `json:"shortname"` + // 机房等级 + Level string `json:"level"` + // 机房地址 + Address string `json:"address"` + // 机房公用带外管理user + IloUser string `json:"iloUser"` + // 机房公用带外管理password + IloPassword string `json:"iloPassword"` + // 交换机用户名1 + SwitchUser1 string `json:"switchUser1"` + // 交换机密码1 + SwitchPassword1 string `json:"switchPassword1"` + // 交换机用户名2 + SwitchUser2 string `json:"switchUser2"` + // 交换机密码2 + SwitchPassword2 string `json:"switchPassword2"` + // 创建时间 + CreateTime string `json:"createTime"` + // 修改时间 + UpdateTime string `json:"updateTime"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 修改用户 + UpdatedBy string `json:"updatedBy"` +} +type IdcList struct { + // 机房列表 + Idcs []*Idc `json:"idcs"` + // 页数 + PageNumber int64 `json:"pageNumber"` + // 页大小 + PageSize int64 `json:"pageSize"` + // 总条数 + TotalCount int64 `json:"totalCount"` +} +type IdcInfo struct { + // 机房信息 + Idc *Idc `json:"idc"` +} +type IdcID struct { + // 机房id + IdcID string `json:"idcId"` +} + +//func (d Idc) MarshalJSON() ([]byte, error) { +// type Alias Idc +// return json.Marshal(struct { +// Alias +// CreateTime string `json:"createTime"` +// UpdateTime string `json:"updateTime"` +// }{ +// Alias: Alias(d), +// //CreateTime: time.Unix(d.CreateTime,0).Format("2006-01-02 15:04:05"), +// //UpdateTime: time.Unix(d.UpdateTime,0).Format("2006-01-02 15:04:05"), +// }) +//} diff --git a/bmp-openapi-console/types/response/Image.go b/bmp-openapi-console/types/response/Image.go new file mode 100644 index 0000000..96f3fae --- /dev/null +++ b/bmp-openapi-console/types/response/Image.go @@ -0,0 +1,69 @@ +package response + +type Image struct { + ID uint64 `json:"id"` // ID + // 镜像uuid + ImageID string `json:"imageId"` + // 镜像名称 + ImageName string `json:"imageName"` + // 源os uuid + OsID string `json:"osId"` + // 镜像格式(qcow2、tar) + Format string `json:"format"` + // 引导模式 【UEFI Legacy/BIOS】 + BootMode string `json:"bootMode"` + // 镜像文件名称 + Filename string `json:"filename"` + // 镜像源路径 + URL string `json:"url"` + // 镜像校验码 + Hash string `json:"hash"` + // 镜像来源(common通用、customize定制、user_defined自定义) + Source string `json:"source"` + // 镜像来源(common通用、customize定制、user_defined自定义) + SourceName string `json:"sourceName"` + // 描述 + Description string `json:"description"` + // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + SystemPartition string `json:"systemPartition"` + // 数据分区信息 + DataPartition string `json:"dataPartition"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` + // 架构:x86/x64/i386/ + Architecture string `json:"architecture"` + //CentOS 7.2 64-bit + OsName string `json:"osName"` + // 操作系统分类:linux/windows + OsType string `json:"osType"` + // 操作系统版本 + OsVersion string `json:"osVersion"` + //绑定了机型数量 + DeviceTypeNum int `json:"deviceTypeNum"` + //是否绑定了某个机型 + IsBind bool `json:"isBind"` +} +type ImageList struct { + // 镜像实体列表 + Images []*Image `json:"images"` + // 页数 + PageNumber int64 `json:"pageNumber"` + // 页大小 + PageSize int64 `json:"pageSize"` + // 总条数 + TotalCount int64 `json:"totalCount"` +} +type ImageInfo struct { + // 镜像实体 + Image *Image `json:"image"` +} +type ImageId struct { + // 镜像uuid + ImageId string `json:"imageId"` +} diff --git a/bmp-openapi-console/types/response/Instance.go b/bmp-openapi-console/types/response/Instance.go new file mode 100644 index 0000000..30447da --- /dev/null +++ b/bmp-openapi-console/types/response/Instance.go @@ -0,0 +1,242 @@ +package response + +type Instance struct { + ID int `json:"-"` + // 实例uuid + InstanceID string `json:"instanceId"` // 实例ID(uuid) + // 机房uuid + IDcID string `json:"idcId"` + // 机房名称 + IdcName string `json:"idcName"` + // 实例所属项目UUID + ProjectID string `json:"projectId"` + // 实例所属用户UUID + UserID string `json:"userId"` + // 实例名称 + InstanceName string `json:"instanceName"` + // 设备uuid + DeviceID string `json:"deviceId"` + // 设备SN + Sn string `json:"sn"` + // 带外管理IP + IloIP string `json:"iloIp"` + Mask string `json:"mask"` + Eth1Mask string `json:"eth1Mask"` + // 内网IPV4 + PrivateIPv4 string `json:"privateIpv4"` + // 内网IPV6 + PrivateIPv6 string `json:"privateIpv6"` + // eth1内网IPV4 + PrivateEth1IPv4 string `json:"privateEth1Ipv4"` + // eth1内网IPV6 + PrivateEth1IPv6 string `json:"privateEth1Ipv6"` + // 机型uuid + DeviceTypeID string `json:"deviceTypeId"` + // 机型名称,如计算效能型,标准计算型 + DeviceTypeName string `json:"deviceTypeName"` + // 机型规格, cps.c.normal + DeviceType string `json:"deviceType"` + // 机型类型,如computer + DeviceSeries string `json:"deviceSeries"` + //机型类型,如计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName"` + // cpu数量 + CPUAmount int `json:"cpuAmount"` + // 单个cpu内核数 + CPUCores int `json:"cpuCores"` + // cpu厂商 + CPUManufacturer string `json:"cpuManufacturer"` + // cpu处理器型号 + CPUModel string `json:"cpuModel"` + // cpu频率(GHz) + CPUFrequency string `json:"cpuFrequency"` + // 内存接口(如DDR3,DDR4) + MemType string `json:"memType"` + // 单个内存大小(GB) + MemSize int `json:"memSize"` + // 内存数量 + MemAmount int `json:"memAmount"` + // 内存主频(MHz) + MemFrequency int `json:"memFrequency"` + // 网卡数量 + NicAmount int `json:"nicAmount"` + // 网卡传输速率(GE) + NicRate int `json:"nicRate"` + // 【网口模式】【网络设置】: bond单网口,dual双网口 + InterfaceMode string `json:"interfaceMode"` + // gpu数量 + GpuAmount int `json:"gpuAmount"` + // gpu厂商 + GpuManufacturer string `json:"gpuManufacturer"` + // gpu处理器型号 + GpuModel string `json:"gpuModel"` + // 主机名 + Hostname string `json:"hostname"` + // 运行状态 + Status string `json:"status"` + // 实例错误状态时的错误原因 + Reason string `json:"reason"` + // 运行状态中文名字 + StatusName string `json:"statusName"` + // 镜像uuid + ImageID string `json:"imageId"` + // 镜像名称 + ImageName string `json:"imageName"` + // 系统盘raidId + SystemVolumeRaidID string `json:"systemVolumeRaidId"` + // 系统盘raid名称 + SystemVolumeRaidName string `json:"systemVolumeRaidName"` + // 是否锁定解锁锁定:locked,解锁unlocked + Locked string `json:"locked"` + // 是否锁定解锁锁定:已解锁,已锁定 + LockedName string `json:"lockedName"` + // 实例描述 + Description string `json:"description"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` + // 引导模式 [UEFI Legacy/BIOS] + BootMode string `json:"bootMode"` + //实例的volume和raid信息 + InstanceVolumeRaids []*InstanceVolumeRaid `json:"volumeRaid"` + // 所属的机型是否需要配置raid,页面有用 + IsNeedRaid string `json:"isNeedRaid"` +} +type InstanceList struct { + // instance实体数组 + Instances []*Instance `json:"instances"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type InstanceInfo struct { + // instance实体 + Instance *Instance `json:"instance"` +} +type InstanceId struct { + InstanceId string `json:"instanceId"` +} +type InstanceIds struct { + // instanceId 列表 + InstanceIds []string `json:"instanceIds"` +} + +//func (d Instance) MarshalJSON() ([]byte, error) { +// type Alias Instance +// return json.Marshal(struct { +// Alias +// CreateTime string `json:"create_time"` +// UpdateTime string `json:"update_time"` +// }{ +// Alias: Alias(d), +// //CreateTime: d.CreateTime.Format("2006-01-02 15:04:05"), +// //UpdateTime: d.UpdateTime.Format("2006-01-02 15:04:05"), +// }) +//} + +//func Dinstance2Instance(d_instance *instanceDao.DInstance) *Instance { +// return &Instance{ +// //InstanceId: d_instance.Uuid, +// //DeviceId: d_instance.DeviceId, +// //Region: d_instance.Region, +// //Az: d_instance.Az, +// //DeviceType: d_instance.DeviceType, +// //Tenant: d_instance.Tenant, +// //Name: d_instance.Name, +// //Hostname: d_instance.Hostname, +// //Description: d_instance.Description, +// //Status: d_instance.Status, +// //ImageId: d_instance.ImageId, +// //SystemVolumeRaidId: d_instance.SystemVolumeRaidId, +// //DataVolumeRaidId: d_instance.DataVolumeRaidId, +// //NetworkType: d_instance.NetworkType, +// //SubnetId: d_instance.SubnetId, +// //PrivateIp: d_instance.PrivateIp, +// //LineType: d_instance.LineType, +// //PublicIp: d_instance.PublicIp, +// //EnableInternet: d_instance.EnableInternet, +// //EnableIpv6: d_instance.EnableIpv6, +// //Ipv6Address: d_instance.Ipv6Address, +// //EipId: d_instance.EipId, +// //Bandwidth: d_instance.Bandwidth, +// //KeypairId: d_instance.KeypairId, +// //InterfaceMode: d_instance.InterfaceMode, +// //ExtensionSubnetId: d_instance.ExtensionSubnetId, +// //ExtensionPrivateIp: d_instance.ExtensionPrivateIp, +// //ExtensionEnableInternet: d_instance.ExtensionEnableInternet, +// //ExtensionEipId: d_instance.ExtensionEipId, +// //ExtensionEnableIpv6: d_instance.ExtensionEnableIpv6, +// //ExtensionIpv6Address: d_instance.ExtensionIpv6Address, +// //Sn: d_instance.Sn, +// //UPosition: d_instance.UPosition, +// //Cabinet: d_instance.Cabinet, +// //IloIp: d_instance.IloIp, +// //SaleStatus: d_instance.SaleStatus, +// //CreateTime: d_instance.CreateTime, +// //UpdateTime: d_instance.UpdateTime, +// } +//} +// +//func DaoInstanceDevice2Instance(entity *instanceDao.Instance, device *Device) *Instance { +// return &Instance{ +// +// //InstanceId: entity.UUID, +// //DeviceId: entity.DeviceID, +// ////Region: device.Region, +// ////Az: device.Az, +// ////DeviceType: device.DeviceType, +// //Tenant: entity.Tenant, +// //Name: entity.Name, +// //Hostname: entity.Hostname, +// //Description: entity.Description, +// //Status: entity.Status, +// //ImageId: entity.ImageID, +// //SystemVolumeRaidId: entity.SystemVolumeRaidID, +// //DataVolumeRaidId: entity.DataVolumeRaidID, +// //NetworkType: entity.NetworkType, +// //SubnetId: entity.SubnetID, +// //PrivateIp: entity.PrivateIP, +// //LineType: entity.LineType, +// //PublicIp: entity.PublicIP, +// //EnableInternet: util.int2Bool(entity.EnableInternet), +// //EnableIpv6: util.int2Bool(entity.EnableIPv6), +// //Ipv6Address: entity.IPv6Address, +// //EipId: entity.EipID, +// //Bandwidth: entity.Bandwidth, +// //KeypairId: entity.KeypairID, +// //InterfaceMode: entity.InterfaceMode, +// //ExtensionSubnetId: entity.ExtensionSubnetID, +// //ExtensionPrivateIp: entity.ExtensionPrivateIP, +// //ExtensionEnableInternet: util.int2Bool(entity.ExtensionEnableInternet), +// //ExtensionEipId: entity.ExtensionEipID, +// //ExtensionEnableIpv6: util.int2Bool(entity.ExtensionEnableIPv6), +// //ExtensionIpv6Address: entity.ExtensionIPv6Address, +// //Sn: device.Sn, +// //UPosition: device.UPosition, +// //Cabinet: device.Cabinet, +// ////IloIp: device.IloIp, +// ////SaleStatus: device.SaleStatus, +// //CreateTime: entity.CreateTime, +// //UpdateTime: entity.UpdateTime, +// } +//} + +type InstanceForShare struct { + ID int `json:"-"` + // 实例uuid + InstanceID string `json:"instanceId"` // 实例ID(uuid) + // 实例名称 + InstanceName string `json:"instanceName"` + //新增,是否已经被共享过 + HasShared bool `json:"hasShared"` +} + +type InstanceForShareList struct { + // instance实体数组 + Instances []*InstanceForShare `json:"instances"` +} diff --git a/bmp-openapi-console/types/response/InstancePartitionResponse.go b/bmp-openapi-console/types/response/InstancePartitionResponse.go new file mode 100644 index 0000000..26456f8 --- /dev/null +++ b/bmp-openapi-console/types/response/InstancePartitionResponse.go @@ -0,0 +1,8 @@ +package response + +type QueryInstancePartitionResponse struct { + PartitionResult struct { + SystemPartition []Partition `json:"systemPartition"` + DataPartition []Partition `json:"dataPartition"` + } `json:"partition_result"` +} diff --git a/bmp-openapi-console/types/response/InstanceSshkey.go b/bmp-openapi-console/types/response/InstanceSshkey.go new file mode 100644 index 0000000..c0ec380 --- /dev/null +++ b/bmp-openapi-console/types/response/InstanceSshkey.go @@ -0,0 +1,17 @@ +package response + +type InstancesSshkeyResponse struct { + ID uint64 `json:"-"` // ID + InstanceID string `json:"instanceId"` // 实例ID + SSHkeyID string `json:"sshkeyId"` // sshkeyid + CreatedBy string `json:"createdBy"` // 创建者 + UpdatedBy string `json:"updatedBy"` // 更新者 + CreatedTime string `json:"createdTime"` // 创建时间 + UpdatedTime string `json:"updatedTime"` // 更新时间 +} + +type InstancesSshkeyInfoResponse struct { + // 实例Id列表 + InstanceIds []string `json:"instanceIds"` + //SshkeyIds []string `json:"sshkeyIds"` // 秘钥Id +} diff --git a/bmp-openapi-console/types/response/Interface.go b/bmp-openapi-console/types/response/Interface.go new file mode 100644 index 0000000..937a7de --- /dev/null +++ b/bmp-openapi-console/types/response/Interface.go @@ -0,0 +1,10 @@ +package response + +type Interface struct { + Sn string `json:"sn"` + InterfaceName string `json:"interface_name"` + InterfaceType string `json:"interface_type"` + Mac string `json:"mac"` + SwitchIp string `json:"switch_ip"` + SwitchPort string `json:"switch_port"` +} diff --git a/bmp-openapi-console/types/response/License.go b/bmp-openapi-console/types/response/License.go new file mode 100644 index 0000000..54c4a2c --- /dev/null +++ b/bmp-openapi-console/types/response/License.go @@ -0,0 +1,13 @@ +package response + +type LicenseContent struct { + HardWare string `json:"hardwareinfo"` + StartTime int64 `json:"start_time"` + EndTime int64 `json:"end_time"` + Models []string `json:"models"` + NodesNum int `json:"nodes_num"` + UsedNodesNum int `json:"used_nodes_num"` + Version string `json:"version"` + LicenseType string `json:"license_type"` + LicenseName string `json:"license_name"` +} diff --git a/bmp-openapi-console/types/response/Message.go b/bmp-openapi-console/types/response/Message.go new file mode 100644 index 0000000..ec6b512 --- /dev/null +++ b/bmp-openapi-console/types/response/Message.go @@ -0,0 +1,37 @@ +package response + +import "coding.jd.com/aidc-bmp/bmp-openapi/dao/messageDao" + +type Message struct { + messageDao.WebMessage + //独一处的下划线,跟sdk一致 + IDcID string `json:"idc_id"` + IDcName string `json:"idc_name"` + ProjectID string `json:"project_id"` + ProjectName string `json:"project_name"` + DeviceID string `json:"device_id"` +} + +type MessageList struct { + Messages []*Message `json:"messages"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} + +type MessageStatistic struct { + TotalCount int64 `json:"totalCount"` + UnreadCount int64 `json:"unreadCount"` +} + +type HasUnreadMessage struct { + HasUnread bool `json:"hasUnread"` +} + +type MessageWithNextPrev struct { + Message *Message `json:"message"` + NextMessageId string `json:"nextMessageId"` + PrevMessageId string `json:"prevMessageId"` +} + +type MessageTypesResp map[string][]string diff --git a/bmp-openapi-console/types/response/MonitorAlertResponse.go b/bmp-openapi-console/types/response/MonitorAlertResponse.go new file mode 100644 index 0000000..f81cea6 --- /dev/null +++ b/bmp-openapi-console/types/response/MonitorAlertResponse.go @@ -0,0 +1,44 @@ +package response + +type AlertList struct { + // rules数组 + Alerts []*Alert `json:"instances"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} + +type Alert struct { + // alert uuid + AlertID string `json:"alertId"` + // 告警时间戳 + AlertTime int64 `json:"alertTime"` + // rule obj + Rule *Rule `json:"rule"` + //涉及到哪些实例 + Instance *Instance `json:"instance"` + // 资源类型 [只支持instance一种] + Resource string `json:"resource"` + // 资源id,目前就是实例id + ResourceID string `json:"resourceId"` + // 资源名称,目前就是实例名称 + ResourceName string `json:"resourceName"` + // 触发条件,接口需要翻译 + Trigger string `json:"trigger"` + //触发条件描述 + TriggerDescription string `json:"triggerDescription"` + // 报警值 + AlertValue string `json:"alertValue"` + // 1表示一般,2表示严重,3表示紧急 + AlertLevel int64 `json:"alertLevel"` + //级别描述 + AlertLevelDescription string `json:"alertLevelDescription"` + // 告警持续时间(分钟为单位) + AlertPeriod int64 `json:"alertPeriod"` + // 通知对象 userid + UserID string `json:"userId"` + // 通知对象 用户名 + UserName string `json:"userName"` + // 创建时间戳 + CreatedTime int64 `json:"createdTime"` +} diff --git a/bmp-openapi-console/types/response/MonitorDataResponse.go b/bmp-openapi-console/types/response/MonitorDataResponse.go new file mode 100644 index 0000000..a0e0bb7 --- /dev/null +++ b/bmp-openapi-console/types/response/MonitorDataResponse.go @@ -0,0 +1,26 @@ +package response + +type DataEveryMetric struct { + Query MonitorDataQuery `json:"query"` + Data []*MonitorDataItem `json:"data"` +} + +type MonitorDataQuery struct { + //[bmp_monitor_counter bmp_monitor_gauge] + TableName string `json:"tableName"` + // MetricName string `json:"metricName"` + //[rate, increase] + SampleMethod string `json:"sampleMethod"` + //metric都放这里了 + Labels map[string]string `json:"labels"` + StartTime int64 `json:"startTime"` + EndTime int64 `json:"endTime"` + Step int `json:"step"` + //跟赛迪约定,转换单位放这里实现 + Func map[string]int `json:"func"` +} + +type MonitorDataItem struct { + Timestamp int64 `json:"timestamp"` + Value string `json:"value"` +} diff --git a/bmp-openapi-console/types/response/MonitorProxyResponse.go b/bmp-openapi-console/types/response/MonitorProxyResponse.go new file mode 100644 index 0000000..57d229e --- /dev/null +++ b/bmp-openapi-console/types/response/MonitorProxyResponse.go @@ -0,0 +1,20 @@ +package response + +type AgentStatusResponse struct { + AgentStatus []AgentStatusItem `json:"agentStatus"` +} + +type AgentStatusItem struct { + InstanceID string `json:"instance_id"` + SN string `json:"sn"` + AgentVersion string `json:"agent_version"` + Timestamp int64 `json:"timestamp"` + // 1->running 2->stopped 0->unknown + Status int `json:"status"` + //status 运行 停止 未知 + StatusName string `json:"statusName"` +} + +type TagsResponse struct { + Tags []string `json:"tags"` +} diff --git a/bmp-openapi-console/types/response/MonitorRuleResponse.go b/bmp-openapi-console/types/response/MonitorRuleResponse.go new file mode 100644 index 0000000..cf64d37 --- /dev/null +++ b/bmp-openapi-console/types/response/MonitorRuleResponse.go @@ -0,0 +1,88 @@ +package response + +type RuleList struct { + // rules数组 + Rules []*Rule `json:"rules"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} + +type Rule struct { + //状态 [1启用 2不启用 3告警] + Status int64 `json:"status"` + //规则uuid + RuleID string `json:"ruleId"` + //规则名称 + RuleName string `json:"ruleName"` + //维度 [instance、disk、mountpoint、nic] + Dimension string `json:"dimension"` + //维度名称 [实例、盘符、挂载点、网卡] + DimensionName string `json:"dimensionName"` + //资源类型,目前只支持instance + Resource string `json:"resource"` + //资源类型名称 实例 + ResourceName string `json:"resourceName"` + //触发条件 + TriggerOption []*RuleTrigger `json:"triggerOption"` + //触发条件描述 + TriggerDescription []string `json:"triggerDescription"` + //通知策略 + NoticeOption *RuleNotice `json:"noticeOption"` + //实例id列表 + InstanceIds []string `json:"instanceIds"` + //关联的实例个数 + InstanceCount int64 `json:"instanceCount"` + //实例详细信息 + Instances []*Instance `json:"instances"` + //盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag"` + //此规则关联的资源数 + RelatedResourceCount int64 `json:"relatedResourceCount"` + //规则状态名称 + StatusName string `json:"statusName"` +} + +//单个触发条件 +type RuleTrigger struct { + // [bmp_monitor_counter, bmp_monitor_gauge] + TableName string `json:"tableName"` + //监控指标 cps.cpu.util + Metric string `json:"metric"` + //监控指标名称 CPU使用率 + MetricName string `json:"metricName"` + //周期 5(分钟) + Period int `json:"period"` + //计算方式 [min max avg sum] + Calculation string `json:"calculation"` + //计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出] + CalculationUnit string `json:"calculationUnit"` + //比较方式 [> >= < <= == !=]或者[gt gte lt lte eq neq] + Operation string `json:"operation"` + //阈值 + Threshold float64 `json:"threshold"` + //持续周期数 [1, 2, 3, 5, 10, 15, 30, 60] + Times int `json:"times"` + //告警级别 [1表示一般,2表示严重,3表示紧急] + NoticeLevel int `json:"noticeLevel"` + //对此rule的描述 + Description string `json:"description"` +} + +//通知策略 +type RuleNotice struct { + //通知周期(分钟) [5 10 15 30 60 180 360 720 1440] + NoticePeriod int `json:"noticePeriod"` + // 有效时段开始时间 ["00:00:00"] + EffectiveIntervalStart string `json:"effectiveIntervalStart"` + // 有效时段结束时间 ["23:59:59"] + EffectiveIntervalEnd string `json:"effectiveIntervalEnd"` + //通知条件,可多选 [1表示报警, 2表示恢复正常] + NoticeCondition []int `json:"noticeCondition"` + //接收渠道,可多选 [1表示站内信, 2表示邮件] + NoticeWay []int `json:"noticeWay"` + //通知对象用户Id + UserID string `json:"userId"` + //通知对象用户 + UserName string `json:"userName"` +} diff --git a/bmp-openapi-console/types/response/Os.go b/bmp-openapi-console/types/response/Os.go new file mode 100644 index 0000000..30d3ea5 --- /dev/null +++ b/bmp-openapi-console/types/response/Os.go @@ -0,0 +1,45 @@ +package response + +type Os struct { + // ID + ID uint64 `json:"id"` + // 操作系统uuid + OsID string `json:"osId"` + // 操作系统名称 + OsName string `json:"osName"` + // 操作系统分类:linux/windows + OsType string `json:"osType"` + // 架构:x86/x64/i386/ + Architecture string `json:"architecture"` + // 指令宽度:64/32位 + Bits int `json:"bits"` + // 操作系统版本 + OsVersion string `json:"osVersion"` + // 管理员账户 + SysUser string `json:"sysUser"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` + // 删除时间 + DeletedTime string `json:"deletedTime"` + // 是否删除0未删除 1已删除 + IsDel int8 `json:"isDel"` +} + +type OsList struct { + // 操作系统列表 + Oss []*Os `json:"oss"` +} +type OsInfo struct { + // 操作系统实体 + Os *Os `json:"os"` +} +type OsId struct { + // 操作系统uuid + OsId string `json:"osId"` +} diff --git a/bmp-openapi-console/types/response/Project.go b/bmp-openapi-console/types/response/Project.go new file mode 100644 index 0000000..1b3e847 --- /dev/null +++ b/bmp-openapi-console/types/response/Project.go @@ -0,0 +1,53 @@ +package response + +import "coding.jd.com/aidc-bmp/bmp-openapi/dao/sharingProjectDao" + +type Project struct { + ID int `json:"-"` + // 项目名称 + ProjectName string `json:"projectName"` + // 项目uuid + ProjectID string `json:"projectId"` + // 项目下实例数量 + InstanceCount int64 `json:"instanceCount"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 拥有者 + OwnedBy string `json:"ownedBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` + // 共享 + ShareProjects []ShareProject `json:"shareProjects"` + // 此项目的共享标志位,1为拥有,2为共享 + Owned int `json:"owned"` + // 项目描述,新增 + Description string `json:"description"` +} +type ProjectList struct { + // 项目实体列表 + Projects []*Project `json:"projects"` + // 页数 + PageNumber int64 `json:"pageNumber"` + // 页大小 + PageSize int64 `json:"pageSize"` + // 总条数 + TotalCount int64 `json:"totalCount"` +} +type ProjectInfo struct { + // 项目实体 + Project *Project `json:"project"` +} +type ProjectId struct { + // 项目uuid + ProjectId string `json:"projectId"` +} + +type ShareProjectInfo struct { + // 项目实体 + ProjectID string `json:"projectId"` + Shares []*sharingProjectDao.SharingProject `json:"shares"` +} diff --git a/bmp-openapi-console/types/response/Raid.go b/bmp-openapi-console/types/response/Raid.go new file mode 100644 index 0000000..53188f0 --- /dev/null +++ b/bmp-openapi-console/types/response/Raid.go @@ -0,0 +1,39 @@ +package response + +type Raid struct { + // raid uuid + RaidID string `json:"raidId"` + // raid 名称 + Name string `json:"name"` + //设备类型uuid + DeviceTypeId string `json:"deviceTypeId"` + //磁盘类型 + VolumeType string `json:"volumeType"` + //磁盘详细信息 + VolumeDetail string `json:"volumeDetail"` + //中文描述 + DescriptionEn string `json:"descriptionEn"` + // description + DescriptionZh string `json:"descriptionZh"` + // 系统盘分区数量 + SystemPartitionCount int `json:"systemPartitionCount"` + // 可用分区值,单位GB + AvailableValue int `json:"availableValue"` + // 磁盘类型:SAS/SATA/SSD/NVME + DiskType string `json:"diskType"` +} +type RaidList struct { + //raid实体列表 + Raids []*Raid `json:"raids"` + //PageNumber int64 `json:"pageNumber"` + //PageSize int64 `json:"pageSize"` + //TotalCount int64 `json:"totalCount"` +} +type RaidInfo struct { + //raid实体 + Raid *Raid `json:"raid"` +} +type RaidId struct { + //raid uuid + RaidId string `json:"raidId"` +} diff --git a/bmp-openapi-console/types/response/Role.go b/bmp-openapi-console/types/response/Role.go new file mode 100644 index 0000000..65286df --- /dev/null +++ b/bmp-openapi-console/types/response/Role.go @@ -0,0 +1,44 @@ +package response + +type Role struct { + ID int `json:"-"` + // 角色uuid + RoleID string `json:"roleId"` + // 角色名称,唯一 + RoleNameEn string `json:"roleNameEn"` + // 角色名称,唯一 + RoleNameCn string `json:"roleNameCn"` + // 权限描述 + DescriptionEn string `json:"descriptionEn"` + // description + DescriptionCn string `json:"descriptionCn"` + // 角色名称 + RoleName string `json:"roleName"` + // 权限 + Permission string `json:"permission"` + // 用户数 + UserCount int `json:"userCount"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` +} +type RoleList struct { + //角色实体列表 + Roles []*Role `json:"roles"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type RoleInfo struct { + //角色实体 + Role *Role `json:"role"` +} +type RoleId struct { + //角色uuid + RoleId string `json:"roleId"` +} diff --git a/bmp-openapi-console/types/response/ShareProject.go b/bmp-openapi-console/types/response/ShareProject.go new file mode 100644 index 0000000..98a6109 --- /dev/null +++ b/bmp-openapi-console/types/response/ShareProject.go @@ -0,0 +1,26 @@ +package response + +type ShareProject struct { + ID int `json:"-"` + // 项目名称 + ProjectName string `json:"projectName"` + // 项目uuid + ProjectID string `json:"projectId"` + // 项目拥有者用户id + OwnerUserID string `json:"ownerUserId"` + // 项目共享者用户id + SharedUserID string `json:"sharedUserId"` + // 项目拥有者用户名 + OwnerUserName string `json:"ownerUserName"` + // 项目拥有者用户名 + SharedUserName string `json:"sharedUserName"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` + + SharedInstanceIDs string `json:"sharedInstanceIds"` + // ShareProjects []ShareProject `json:"shareProjects"` +} diff --git a/bmp-openapi-console/types/response/SshKey.go b/bmp-openapi-console/types/response/SshKey.go new file mode 100644 index 0000000..4d3c39f --- /dev/null +++ b/bmp-openapi-console/types/response/SshKey.go @@ -0,0 +1,42 @@ +package response + +type Sshkey struct { + // id + Id int64 `json:"id"` + // 秘钥uuid + SshkeyId string `json:"sshkeyId"` // 秘钥uuid + // 所属用户uuid + UserId string `json:"userId"` + // 秘钥名称 + Name string `json:"name"` + // 公钥,格式:ssh-rsa AAA + Key string `json:"key"` + // 公钥指纹 + FingerPrint string `json:"fingerPrint"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` +} +type SshkeyList struct { + // sshkey实体列表 + Sshkeys []*Sshkey `json:"sshkeys"` + // 页数 + PageNumber int64 `json:"pageNumber"` + // 页大小 + PageSize int64 `json:"pageSize"` + // 总条数 + TotalCount int64 `json:"totalCount"` +} +type SshkeyInfo struct { + // sshkey实体 + Sshkey *Sshkey `json:"sshkey"` +} +type SshkeyId struct { + // sshkey uuid + SshkeyId string `json:"sshkeyId"` +} diff --git a/bmp-openapi-console/types/response/User.go b/bmp-openapi-console/types/response/User.go new file mode 100644 index 0000000..cc1e503 --- /dev/null +++ b/bmp-openapi-console/types/response/User.go @@ -0,0 +1,57 @@ +package response + +type User struct { + // 用户id + ID int `json:"id"` + // 用户uuid + UserID string `json:"userId"` + // 角色uuid + RoleID string `json:"roleId"` + // 角色名称 + RoleName string `json:"roleName"` + // 用户名,唯一 + UserName string `json:"userName"` + // 邮箱 + Email string `json:"email"` + // 国家地区码,如86 + PhonePrefix string `json:"phonePrefix"` + // 手机号 + PhoneNumber string `json:"phoneNumber"` + // 用户默认项目uuid + DefaultProjectID string `json:"defaultProjectId"` + // 用户默认项目名称 + DefaultProjectName string `json:"defaultProjectName"` + // 默认语言(en_US/zh_CN) + Language string `json:"language"` + // 时区 + Timezone string `gorm:"column:timezone" json:"timezone"` + Password string `json:"-"` + // 描述 + Description string `json:"description"` + // 创建者 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` + // 更新者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` + // 创建时间 + CreatedTime string `gorm:"column:created_time" json:"createdTime"` + // 更新时间 + UpdatedTime string `gorm:"column:updated_time" json:"updatedTime"` +} +type UserList struct { + // user实体列表 + Users []*User `json:"users"` + // 页数 + PageNumber int64 `json:"pageNumber"` + // 页大小 + PageSize int64 `json:"pageSize"` + // 总条数 + TotalCount int64 `json:"totalCount"` +} +type UserInfo struct { + // 用户实体 + User *User `json:"user"` +} +type UserId struct { + // 用户uuid + UserId string `json:"userId"` +} diff --git a/bmp-openapi-console/types/response/VolumeRaid.go b/bmp-openapi-console/types/response/VolumeRaid.go new file mode 100644 index 0000000..b6bdc38 --- /dev/null +++ b/bmp-openapi-console/types/response/VolumeRaid.go @@ -0,0 +1,17 @@ +package response + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rVolumeRaidDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/raidDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/volumeDao" +) + +type VolumeRaids struct { + volumeDao.Volume + Raids []*rVolumeRaidDao.RVolumeRaid `json:"raids"` +} + +type InstanceVolumeRaid struct { + Volume *volumeDao.Volume `json:"volume"` + Raid *raidDao.Raid `json:"raid"` +} diff --git a/bmp-openapi-console/types/response/command.go b/bmp-openapi-console/types/response/command.go new file mode 100644 index 0000000..bd34a80 --- /dev/null +++ b/bmp-openapi-console/types/response/command.go @@ -0,0 +1,42 @@ +package response + +import ( + "encoding/json" + "time" +) + +type Command struct { + Id int64 `json:"id"` + RequestId string `json:"request_id"` + Sn string `json:"sn"` + InstanceId string `json:"instance_id"` + Action string `json:"action"` + Type string `json:"type"` + Status string `json:"status"` + ParentCommandId int64 `json:"parent_command_id"` + ExecuteCount int `json:"execute_count"` + Result string `json:"result,omitempty"` + CreateTime time.Time `json:"create_time"` + UpdateTime time.Time `json:"update_time"` +} + +type QueryCommandsResult struct { + Commands []*Command `json:"commands"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} + +//解决time.Time类型序列化时默认格式为2018-12-25T19:43:35+08:00而不是2006-01-02 15:04:05的问题 +func (d Command) MarshalJSON() ([]byte, error) { + type Alias Command + return json.Marshal(struct { + Alias + CreateTime string `json:"create_time"` + UpdateTime string `json:"update_time"` + }{ + Alias: Alias(d), + CreateTime: d.CreateTime.Format("2006-01-02 15:04:05"), + UpdateTime: d.UpdateTime.Format("2006-01-02 15:04:05"), + }) +} diff --git a/bmp-openapi-console/util/array.go b/bmp-openapi-console/util/array.go new file mode 100644 index 0000000..db2ca59 --- /dev/null +++ b/bmp-openapi-console/util/array.go @@ -0,0 +1,119 @@ +package util + +import ( + "encoding/json" + "reflect" +) + +func GetValuesByField(objs []interface{}, field string) []string { + res := []string{} + for _, obj := range objs { + r := reflect.ValueOf(obj) + if reflect.TypeOf(obj).Kind() == reflect.Ptr { + r = reflect.Indirect(r) + } + f := r.FieldByName(field).String() + res = append(res, f) + } + return res +} + +func InArrayWithIndex(val interface{}, array interface{}) (exists bool, index int) { + exists = false + index = -1 + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + index = i + exists = true + return + } + } + } + return +} + +func InArray(val interface{}, array interface{}) (exists bool) { + exists = false + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + exists = true + return + } + } + } + return +} +func InArrayString(str string, arr []string) bool { + for _, v := range arr { + if v == str && str != "" { + return true + } + } + return false +} + +//求并集 +func UnionArray(slice1, slice2 []string) []string { + m := make(map[string]int) + for _, v := range slice1 { + m[v]++ + } + + for _, v := range slice2 { + times, _ := m[v] + if times == 0 { + slice1 = append(slice1, v) + } + } + return slice1 +} + +//求交集 +func IntersectArray(slice1, slice2 []string) []string { + m := make(map[string]int) + nn := make([]string, 0) + for _, v := range slice1 { + m[v]++ + } + + for _, v := range slice2 { + times, _ := m[v] + if times == 1 { + nn = append(nn, v) + } + } + return nn +} + +//求差集 slice1-并集 +func DifferenceArray(slice1, slice2 []string) []string { + m := make(map[string]int) + nn := make([]string, 0) + inter := IntersectArray(slice1, slice2) + for _, v := range inter { + m[v]++ + } + + for _, value := range slice1 { + times, _ := m[value] + if times == 0 { + nn = append(nn, value) + } + } + return nn +} + +func ObjToJson(obj interface{}) string { + dataType, err := json.Marshal(obj) + if err != nil { + return "" + } + dataString := string(dataType) + return dataString +} diff --git a/bmp-openapi-console/util/array_test.go b/bmp-openapi-console/util/array_test.go new file mode 100644 index 0000000..68dc442 --- /dev/null +++ b/bmp-openapi-console/util/array_test.go @@ -0,0 +1,14 @@ +package util + +import( + "testing" +) + +func TestInArray(t *testing.T){ + v := InArray("aaa", []string{"aaa", "bbb"}) + if !v{ + t.Fatal("not in array") + }else{ + t.Log("in array") + } +} diff --git a/bmp-openapi-console/util/bool.go b/bmp-openapi-console/util/bool.go new file mode 100644 index 0000000..39da658 --- /dev/null +++ b/bmp-openapi-console/util/bool.go @@ -0,0 +1,12 @@ +package util + +func Bool2Int8(b bool) int8 { + if b { + return 1 + } + return 0 +} + +func Int82Bool(i int8) bool { + return i > 0 +} diff --git a/bmp-openapi-console/util/common.go b/bmp-openapi-console/util/common.go new file mode 100644 index 0000000..2f2457b --- /dev/null +++ b/bmp-openapi-console/util/common.go @@ -0,0 +1,189 @@ +package util + +import ( + "encoding/json" + "fmt" + "reflect" + "regexp" + "strconv" + "strings" + "time" + "unsafe" +) + +/** +map或者stuct转化为json字符串 +*/ +func ObjToJsonString(obj interface{}) string { + return MapToJson(InterfaceToMap(obj)) +} + +//任意类型转化成json,最常用 +func InterfaceToJson(obj interface{}) string { + dataType, err := json.Marshal(obj) + if err != nil { + return "" + } + dataString := string(dataType) + return dataString +} + +/** +Map对象转化为json string +*/ +func MapToJson(param map[string]interface{}) string { + dataType, _ := json.Marshal(param) + dataString := string(dataType) + return dataString +} +func InterfaceToMap(obj interface{}) map[string]interface{} { + + var data = make(map[string]interface{}) + if reflect.TypeOf(obj).Kind().String() == "map" { + d := obj.(map[string]interface{}) + for k, v := range d { + if vv := ReflectValue2string(reflect.ValueOf(v)); vv != "" { + data[k] = vv + } + } + } else if reflect.TypeOf(obj).Kind().String() == "struct" { + obj1 := reflect.TypeOf(obj) + obj2 := reflect.ValueOf(obj) + for i := 0; i < obj1.NumField(); i++ { + if vv := ReflectValue2string(obj2.Field(i)); vv != "" { + tagname := obj1.Field(i).Tag.Get("json") + if tagname != "" { + data[tagname] = vv + } else { + data[obj1.Field(i).Name] = vv + } + } + } + } else { + fmt.Printf("unknown obj, type is :%s, value is:%v\n", reflect.TypeOf(obj).String(), obj) + } + return data + +} + +//ReflectValue2string 默认值都设置为"",可能会误伤,后面改的方案:1,定义成wrapper类型,2,和上下游约定字段取值不要用默认值,比如int类型取值不要出现0,bool类型不要出现false +func ReflectValue2string(obj reflect.Value) string { + var v string + switch obj.Type().Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if vv := strconv.FormatInt(obj.Int(), 10); vv != "0" { //默认值问题 + v = vv + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + if vv := strconv.FormatUint(obj.Uint(), 10); vv != "0" { //默认值问题 + v = vv + } + case reflect.Float32, reflect.Float64: + if vv := fmt.Sprintf("%f", obj.Float()); vv != "0" { //默认值问题 + v = vv + } + case reflect.String: + v = obj.String() + case reflect.Bool: + if vv := strconv.FormatBool(obj.Bool()); vv != "false" { + v = vv + } + default: + v = "" + } + return v +} + +//将下划线转为驼峰 name_en => nameEn 一维,二维均可 +func DbToObj(obj map[string]interface{}) map[string]interface{} { + mapObj := make(map[string]interface{}) + for kk, vv := range obj { + if reflect.TypeOf(vv).Kind().String() == "slice" { + //fmt.Println(vv) + //sliceArr := []interface{} + for k1, v1 := range vv.([]interface{}) { + //fmt.Println(k1,v1) + mapObj1 := make(map[string]interface{}) + for k, v := range v1.(map[string]interface{}) { + sepStr := strings.Join(strings.Split(k, "_"), " ") + arr := strings.Split(strings.Title(sepStr), " ") + arr[0] = strings.ToLower(arr[0]) //hello World Haha + mapObj1[strings.Join(arr, "")] = v + } + vv.([]interface{})[k1] = mapObj1 + } + //fmt.Println(vv) + mapObj[kk] = vv + } else { + sepStr := strings.Join(strings.Split(kk, "_"), " ") + arr := strings.Split(strings.Title(sepStr), " ") + arr[0] = strings.ToLower(arr[0]) + mapObj[strings.Join(arr, "")] = vv + } + } + return mapObj +} + +//将一维map的驼峰 key转化为下划线 +func ObjToDb(param map[string]interface{}) map[string]interface{} { + //str := "userNameTom" //转为user_name_tom + //解析正则表达式,如果成功返回解释器 + reg := regexp.MustCompile(`[A-Z]`) + if reg == nil { //解释失败,返回nil + //fmt.Println("regexp err") + return nil + } + res := make(map[string]interface{}) + for key, value := range param { + //根据规则提取关键信息 + result := reg.FindAllStringSubmatch(key, -1) + for _, v := range result { + //fmt.Println(v) + key = strings.Replace(key, v[0], "_"+strings.ToLower(v[0]), 1) + } + res[key] = value + } + //fmt.Println("result1 = ", result,str) + return res +} + +func Int64ToInt(num int64) int { + int64_num := int64(num) + // 将 int64 转化为 int + int_num := *(*int)(unsafe.Pointer(&int64_num)) + return int_num +} +func StringToInt64(string string) int64 { + int64, err := strconv.ParseInt(string, 10, 64) + if err != nil { + fmt.Println("string to int64 error:", err.Error()) + return 0 + } + return int64 +} + +/** +时间戳根据timezone解析成时间字符串 +*/ +func TimestampToString(timestamp int64, timezone string) string { + if timestamp == 0 { + return "" + } + t := time.Unix(timestamp, 0) + local, err := time.LoadLocation(timezone) + if err != nil { + fmt.Println("timezone error:", timezone, err.Error()) + return "" + } + ts := t.In(local).String() + fmt.Println(timestamp, timezone, ts) + tsItems := strings.Split(ts, " ") + if len(tsItems) >= 2 { + ts = tsItems[0] + " " + tsItems[1] + } + return ts + //if timestamp == 0 { + // return "" + //} + //return time.Unix(timestamp, 0).UTC().Format(baseLogic.DATE_UTC_FORMAT) +} diff --git a/bmp-openapi-console/util/encrypt.go b/bmp-openapi-console/util/encrypt.go new file mode 100644 index 0000000..8f2e3bc --- /dev/null +++ b/bmp-openapi-console/util/encrypt.go @@ -0,0 +1,51 @@ +package util + +import ( + "crypto/md5" + "crypto/sha512" + "encoding/base64" + "encoding/hex" + "fmt" + + "golang.org/x/crypto/bcrypt" +) + +func BcryptEncode(pwd string) string { + // 第二个参数是进行哈希的次数,这里采用了默认值10,数字越大生成的密码速度越慢,成本越大。但是更安全 + // bcrypt每次生成的编码是不同的,较于md5更安全 + bytes, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost) + if err != nil { + fmt.Println("bcrypt error:", err.Error()) + return "" + } + return string(bytes) +} +func BcryptVerify(pwd, hash string) bool { + // CompareHashAndPassword 比较用户输入的明文和和数据库取出的的密码解析后是否匹配 + err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(pwd)) + return err == nil +} +func GetMd5(str string, salts ...string) string { + h := md5.New() + h.Write([]byte(str)) + if len(salts) == 0 { + return hex.EncodeToString(h.Sum(nil)) + } else { + for _, salt := range salts { + h.Write([]byte(salt)) + } + return hex.EncodeToString(h.Sum(nil)) + } +} + +func Base64Encrypt(str []byte) string { + return base64.StdEncoding.EncodeToString(str) +} + +func Base64Decrypt(data string) ([]byte, error) { + return base64.StdEncoding.DecodeString(data) +} + +func GetSha512(str string) string { + return fmt.Sprintf("%x", sha512.Sum512([]byte(str))) +} diff --git a/bmp-openapi-console/util/exec.go b/bmp-openapi-console/util/exec.go new file mode 100644 index 0000000..54bd505 --- /dev/null +++ b/bmp-openapi-console/util/exec.go @@ -0,0 +1,76 @@ +package util + +import ( + "errors" + "fmt" + "os/exec" + "regexp" + "strings" + "syscall" + + log "coding.jd.com/aidc-bmp/bmp_log" +) + +var ipmiToolPath = "/usr/sbin/ipmitool" + +// ExecCommand function to execute command +func ExecCommand(logger *log.Logger, cmdStr string, params ...string) (retStr string, ret int, err error) { + logger.Info("execCommand:", cmdStr+" "+strings.Join(params, " ")) + // check command injection + r := regexp.MustCompile(`[&\|;]+`) + if matched := r.MatchString(cmdStr); matched { + return "", -1, errors.New("command can not contain [&|;], ignore execute") + } + for _, param := range params { + if matched := r.MatchString(param); matched { + return "", -1, errors.New("params can not contain [&|;], ignore execute") + } + } + fmt.Println("指令:", cmdStr+" "+strings.Join(params, " ")) + cmd := exec.Command(cmdStr, params...) + + // execute + //out, err := cmd.StdoutPipe() + //if err != nil { + // fmt.Println("StdoutPipe error: ", err.Error()) + // logger.Warn("StdoutPipe error: ", err.Error()) + // return "", 0, err + //} + //// fmt.Printf("stdout>%v\n", string(out)) + //defer out.Close() // 保证关闭输出流 + //for i := 1; i <= 4; i++ { + // if err := cmd.Start(); err != nil { // 运行命令 + // //log.Fatal(err) + // if i <= 3 { + // fmt.Println("exec Start error: ", err.Error(), i) + // logger.Warn("exec Start error: ", err.Error(), i) + // time.Sleep(time.Minute) + // continue + // } + // return "", 0, err + // } + //} + // + //bytes, _ := ioutil.ReadAll(out) + //for i := 1; i <= 4; i++ { + out, err := cmd.CombinedOutput() + if err != nil { + fmt.Println("CombinedOutput error, command:", cmdStr, params, "error:", err.Error(), "out:", string(out)) + logger.Warn("CombinedOutput error, command:", cmdStr, params, "error:", err.Error(), "out:", string(out)) + return string(out[:]), 0, err + } + //} + fmt.Println("exec output: ", string(out[:])) + logger.Info("exec output: ", string(out[:])) + //return string(bytes) + // get exit code + ret = cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus() + if ret != 0 { + err = errors.New(strings.TrimSpace(string(out[:]))) + logger.Warn("exec WaitStatus error: ", err.Error()) + return "", 0, err + } + // fmt.Printf("cmd>%+v \n", cmd) + + return string(out[:]), ret, err +} diff --git a/bmp-openapi-console/util/http.go b/bmp-openapi-console/util/http.go new file mode 100644 index 0000000..63e3307 --- /dev/null +++ b/bmp-openapi-console/util/http.go @@ -0,0 +1,115 @@ +package util + +import ( + "bytes" + "encoding/json" + "io/ioutil" + "net/http" + "reflect" + + log "coding.jd.com/aidc-bmp/bmp_log" + "github.com/beego/beego/v2/server/web" +) + +func DoHttpPost(logger *log.Logger, url string, header map[string]string, data interface{}) ([]byte, error) { + + logPath, _ := web.AppConfig.String("log.path") + rpclogger := log.New(logPath + "/openapi-rpc.log") + defer rpclogger.Flush() + defer rpclogger.TimeEnd("cost") + rpclogger.SetStableFields([]string{"url", "method", "cost", "header", "request", "response"}) + + rpclogger.Point("logid", logger.GetPoint("logid").(string)) + rpclogger.Point("url", url) + rpclogger.Point("method", "POST") + rpclogger.Point("header", header) + rpclogger.TimeStart("cost") + + var bytesData []byte + if reflect.TypeOf(data).Kind() == reflect.String { + bytesData = []byte(data.(string)) + } else { + var err error + bytesData, err = json.Marshal(data) + if err != nil { + return nil, err + } + } + rpclogger.Point("request", string(bytesData)) + reader := bytes.NewReader(bytesData) + request, err := http.NewRequest("POST", url, reader) + if err != nil { + return nil, err + } + defer request.Body.Close() + //务必带 X-Jdcloud-Request-Id + for k, v := range header { + request.Header.Set(k, v) + } + client := http.Client{} + resp, err := client.Do(request) + if err != nil { + return nil, err + } + respBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + rpclogger.Point("response", string(respBytes)) + return respBytes, nil +} + +func DoHttpGet(logger *log.Logger, url string, header map[string]string, data interface{}) ([]byte, error) { + + logPath, _ := web.AppConfig.String("log.path") + rpclogger := log.New(logPath + "/openapi-rpc.log") + defer rpclogger.Flush() + defer rpclogger.TimeEnd("cost") + rpclogger.SetStableFields([]string{"url", "method", "cost", "header", "request", "response"}) + + rpclogger.Point("logid", logger.GetPoint("logid").(string)) + rpclogger.Point("url", url) + rpclogger.Point("method", "GET") + rpclogger.Point("header", header) + rpclogger.TimeStart("cost") + + var bytesData []byte + if reflect.TypeOf(data).Kind() == reflect.String { + bytesData = []byte(data.(string)) + } else { + var err error + bytesData, err = json.Marshal(data) + if err != nil { + return nil, err + } + } + rpclogger.Point("request", string(bytesData)) + reader := bytes.NewReader(bytesData) + request, err := http.NewRequest("GET", url, reader) + if err != nil { + return nil, err + } + q := request.URL.Query() + param := InterfaceToMap(data) + for key, value := range param { + q.Add(key, value.(string)) + } + request.URL.RawQuery = q.Encode() + + defer request.Body.Close() + //务必带 X-Jdcloud-Request-Id + for k, v := range header { + request.Header.Set(k, v) + } + client := http.Client{} + resp, err := client.Do(request) + if err != nil { + return nil, err + } + respBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + rpclogger.Point("response", string(respBytes)) + return respBytes, nil +} diff --git a/bmp-openapi-console/util/ipv4.go b/bmp-openapi-console/util/ipv4.go new file mode 100644 index 0000000..f668a89 --- /dev/null +++ b/bmp-openapi-console/util/ipv4.go @@ -0,0 +1,200 @@ +package util + +import ( + "encoding/hex" + "fmt" + "net" + "strconv" + "strings" + + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +const ( + IP_NETWORK_SPLIT = "/" + IP_ADDRESS_REGEX = `^(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))$` + IP_WIDTH int32 = 32 + IP_MAX_VALUE int64 = 0xffffffff + IP_MIN_VALUE int64 = 0 +) + +func NetworkIp(cidr string) string { + _, ipNet, _ := net.ParseCIDR(cidr) + return ipNet.IP.String() +} + +// GetNetInfo 根据cidr获取网关和掩码信息 +func GetNetInfo(cidr string) (string, string) { + _, ipNet, _ := net.ParseCIDR(cidr) + mask := getIpMask(ipNet.Mask) + gateway := getDefaultGateway(ipNet.IP.String()) + return gateway, mask +} + +// getIpMask 获取ip掩码 +func getIpMask(mask net.IPMask) string { + val := make([]byte, len(mask)) + copy(val, mask) + s := make([]string, 0) + for _, value := range val { + s = append(s, strconv.Itoa(int(value))) + } + return strings.Join(s, ".") +} + +// getDefaultGateway 获取默认网关 +func getDefaultGateway(ip string) string { + ipArr := strings.Split(ip, ".") + if len(ipArr) > 3 { + lastNum, _ := strconv.Atoi(ipArr[3]) + return ipArr[0] + "." + ipArr[1] + "." + ipArr[2] + "." + strconv.Itoa(lastNum+1) + } else { + return "" + } +} +func Gateway(cidr string) string { + ip, _, err := net.ParseCIDR(cidr) + if err != nil { + panic(err.Error()) + } + IncrIP(ip) + return ip.String() +} + +func Mask(mask net.IPMask) string { + m, _ := hex.DecodeString(mask.String()) + return net.IP([]byte(m)).String() +} + +// IP地址自增 +func IncrIP(ip net.IP) { + for i := len(ip) - 1; i >= 0; i-- { + ip[i]++ + if ip[i] > 0 { + break + } + } +} + +// IP地址自减 +func DecrIP(ip net.IP) { + length := len(ip) + for i := length - 1; i >= 0; i-- { + ip[length-1]-- + if ip[length-1] < 0xFF { + break + } + for j := 1; j < length; j++ { + ip[length-j-1]-- + if ip[length-j-1] < 0xFF { + return + } + } + } +} + +// RandomMacAddress 生成随机mac地址 +func RandomMacAddress() string { + + uuid := commonUtil.GetRandString("", 12, false, false, true) + first_part := uuid[0:4] + first_part_num, _ := strconv.ParseInt("0x"+first_part, 16, 32) + first_hex_string := strconv.FormatInt(first_part_num&0xfeff, 16) + part := []string{fmt.Sprintf("%04x", first_hex_string), uuid[4:8], uuid[8:12]} + return strings.Join(part, "-") +} + +/* + * 列举一个CIDR段中的所有IP列表 + */ +func GetAllHostIPs(cidr string) []string { + //不过不包含掩码位,就当做32位IP对待 + if !strings.Contains(cidr, "/") { + return []string{cidr} + } + ip := strings.Split(cidr, "/")[0] + ipSegs := strings.Split(ip, ".") + maskLen, _ := strconv.Atoi(strings.Split(cidr, "/")[1]) + if maskLen <= 0 { + return []string{} + } + if maskLen == 32 { + return []string{ip} + } + seg1MinIp, seg1MaxIp := getIpSeg1Range(ipSegs[0], maskLen) + seg2MinIp, seg2MaxIp := getIpSeg2Range(ipSegs[1], maskLen) + seg3MinIp, seg3MaxIp := getIpSeg3Range(ipSegs[2], maskLen) + seg4MinIp, seg4MaxIp := getIpSeg4Range(ipSegs[3], maskLen) + + var ipList []string + for seg1Ip := seg1MinIp; seg1Ip <= seg1MaxIp; seg1Ip++ { + for seg2Ip := seg2MinIp; seg2Ip <= seg2MaxIp; seg2Ip++ { + for seg3Ip := seg3MinIp; seg3Ip <= seg3MaxIp; seg3Ip++ { + for seg4Ip := seg4MinIp; seg4Ip <= seg4MaxIp; seg4Ip++ { + oneIp := fmt.Sprintf("%d.%d.%d.%d", seg1Ip, seg2Ip, seg3Ip, seg4Ip) + ipList = append(ipList, oneIp) + } + } + } + } + return ipList +} + +/* + * 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)3部分的最小值和最大值 + */ +func getIpSeg1Range(ipSeg string, maskLen int) (int, int) { + //如果掩码位>16,此时说明掩码只会影响到seg2,seg3,seg4,seg1直接返回 + if maskLen > 8 { + segIp, _ := strconv.Atoi(ipSeg) + return segIp, segIp + } + ipSegNum, _ := strconv.Atoi(ipSeg) + return getIpSegRange(uint8(ipSegNum), uint8(8-maskLen)) +} + +/* +* 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)3部分的最小值和最大值 + */ +func getIpSeg2Range(ipSeg string, maskLen int) (int, int) { + //如果掩码位>16,此时说明掩码只会影响到seg3,seg4,seg2直接返回 + if maskLen > 16 { + segIp, _ := strconv.Atoi(ipSeg) + return segIp, segIp + } + ipSegNum, _ := strconv.Atoi(ipSeg) + return getIpSegRange(uint8(ipSegNum), uint8(16-maskLen)) +} + +/* +* 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)3部分的最小值和最大值 + */ +func getIpSeg3Range(ipSeg string, maskLen int) (int, int) { + //如果掩码位>24,此时说明掩码只会影响到seg4,seg3直接返回 + if maskLen > 24 { + segIp, _ := strconv.Atoi(ipSeg) + return segIp, segIp + } + ipSegNum, _ := strconv.Atoi(ipSeg) + return getIpSegRange(uint8(ipSegNum), uint8(24-maskLen)) +} + +/* + * 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)4部分的最小值和最大值 + */ +func getIpSeg4Range(ipSeg string, maskLen int) (int, int) { + ipSegNum, _ := strconv.Atoi(ipSeg) + segMinIp, segMaxIp := getIpSegRange(uint8(ipSegNum), uint8(32-maskLen)) + if segMinIp == 0 { + segMinIp = segMinIp + 1 //最后一段的IP不能是0,否则就会变为网段 + } + return segMinIp, segMaxIp +} + +func getIpSegRange(userSegIp, offset uint8) (int, int) { + var ipSegMax uint8 = 255 + netSegIp := ipSegMax << offset + segMinIp := netSegIp & userSegIp + segMaxIp := userSegIp&(255< target_len { //裁剪 + if ahead { //保留左边 + return string(r[:target_len]) + } else { //保留右边 + return string(r[len(r)-target_len:]) + } + + } else if len(r) < target_len { //填充 + pads := []rune{} + for i := 0; i < target_len-len(r); i++ { + pads = append(pads, padding_char) + } + if ahead { //左向填充 + return string(append(pads, r...)) + } else { //右向填充 + return string(append(r, pads...)) + } + } + return source + +} +func GetUuid(pre string) string { + rand.Seed(time.Now().UnixNano()) + str := "0123456789abcdefghijklmnopqrstuvwxyz" + bytes := []byte(str) + var result []byte + for i := 0; i < 28; i++ { + result = append(result, bytes[rand.Intn(len(bytes))]) + } + return pre + string(result) +} diff --git a/bmp-openapi/.cmd b/bmp-openapi/.cmd new file mode 100644 index 0000000..ced32d3 --- /dev/null +++ b/bmp-openapi/.cmd @@ -0,0 +1 @@ +rm -rf vendor diff --git a/bmp-openapi/.gitmodules b/bmp-openapi/.gitmodules new file mode 100644 index 0000000..506f24c --- /dev/null +++ b/bmp-openapi/.gitmodules @@ -0,0 +1,3 @@ +[submodule "bmp-deploy"] + path = bmp-deploy + url = git@coding.jd.com:aidc-bmp/bmp-deploy.git diff --git a/bmp-openapi/.idea/.gitignore b/bmp-openapi/.idea/.gitignore new file mode 100644 index 0000000..35410ca --- /dev/null +++ b/bmp-openapi/.idea/.gitignore @@ -0,0 +1,8 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/bmp-openapi/.idea/bmp-openapi.iml b/bmp-openapi/.idea/bmp-openapi.iml new file mode 100644 index 0000000..7ee078d --- /dev/null +++ b/bmp-openapi/.idea/bmp-openapi.iml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/bmp-openapi/.idea/modules.xml b/bmp-openapi/.idea/modules.xml new file mode 100644 index 0000000..e7df1a4 --- /dev/null +++ b/bmp-openapi/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/bmp-openapi/.idea/vcs.xml b/bmp-openapi/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/bmp-openapi/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/bmp-openapi/Dockerfile b/bmp-openapi/Dockerfile new file mode 100644 index 0000000..1c8e901 --- /dev/null +++ b/bmp-openapi/Dockerfile @@ -0,0 +1,17 @@ +FROM centos:7.9.2009 + +MAINTAINER minping@jd.com +USER root +RUN groupadd -g 2001 ironic-api +RUN useradd -d /home/ironic-api -u 2001 -g 2001 ironic-api + +WORKDIR /home/ironic-api + +ADD ./ironic-api /home/ironic-api/ +RUN mkdir -p /home/ironic-api/conf +ADD ./conf/* /home/ironic-api/conf/ + +RUN chmod 755 /home/ironic-api/ironic-api +USER ironic-api +EXPOSE 9999 +CMD ./ironic-api \ No newline at end of file diff --git a/bmp-openapi/Makefile b/bmp-openapi/Makefile new file mode 100644 index 0000000..19c38c9 --- /dev/null +++ b/bmp-openapi/Makefile @@ -0,0 +1,10 @@ + +BUILD_TIME := $(shell date +%Y%m%d%H%M%S) +VERSION := $(shell git describe --tags --always) +COMMITID := $(shell git rev-parse ${VERSION} | cut -c 1-32) +APP_NAME := ironic-api-golang + +#GOARCH=amd64 GOOS=linux +ldflags ="-s -X main.VERSION=${COMMITID} -X main.BUILD_TIME=${BUILD_TIME}" +all: + GOARCH=amd64 GOOS=linux go build -ldflags ${ldflags} -o ${APP_NAME} main.go diff --git a/bmp-openapi/README.md b/bmp-openapi/README.md new file mode 100644 index 0000000..775f865 --- /dev/null +++ b/bmp-openapi/README.md @@ -0,0 +1,18 @@ +# bmp-openapi + + +English | [简体中文](README.zh-CN.md) + +## Introduction + +The core interface layer of the operation platform focuses on the life cycle of the device, provides interfaces for bmp-openapi and developers, and transmits user actions to bmp-scheduler through intermediate keys such as mq and redis. + +See the location of bmp-openapi in the entire bmp architecture.:[bmp arch](../bmp-scheduler/README.md) + + + +## 2,Core Features + +- Equipment import:Bare metal equipment can be imported into the BMP system through the operation platform。 +- Equipment Collection:Collect information about the disk, network card, etc. of bare metal devices. +- Equipment putaway:After collecting bare metal devices, bind them to the appropriate model and put them on the shelf. After the devices are put on the shelf, you can create instances in the console. \ No newline at end of file diff --git a/bmp-openapi/README.zh-CN.md b/bmp-openapi/README.zh-CN.md new file mode 100644 index 0000000..4e78806 --- /dev/null +++ b/bmp-openapi/README.zh-CN.md @@ -0,0 +1,19 @@ +# bmp-openapi + +[English](README.md) | 简体中文 + + +## 介绍 + +运营平台核心接口层,围绕设备的生命周期,向上为bmp-openapi和开发者提供接口,向下通过mq、redis等中间键将用户动作传递到bmp-scheduler。 + +bmp-openapi在整个bmp架构中的位置见:[bmp架构图](../bmp-scheduler/README.zh-CN.md) + + + +## 2,核心功能 + +- 设备导入:裸金属设备可经运营平台导入到bmp系统中。 +- 设备采集:采集裸金属设备的磁盘、网卡等信息。 +- 设备上架:裸金属设备采集后绑定合适机型,即可上架,上架后的设备可以在控制台创建实例。 + diff --git a/bmp-openapi/bmp-openapi.Dockerfile b/bmp-openapi/bmp-openapi.Dockerfile new file mode 100644 index 0000000..9c76de1 --- /dev/null +++ b/bmp-openapi/bmp-openapi.Dockerfile @@ -0,0 +1,14 @@ +FROM golang:1.17-alpine AS builder +ENV GOPROXY https://goproxy.cn +WORKDIR /usr/src/bmp-openapi +COPY . . +RUN go build -o /tmp/bmp-openapi . + +FROM alpine:3.16 +RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories \ +&& apk add tzdata \ +&& apk add dmidecode +WORKDIR /home/bmp/bmp-openapi +COPY --from=builder /tmp/bmp-openapi . +COPY ./conf ./conf +CMD ["./bmp-openapi"] diff --git a/bmp-openapi/bmp_vendor/bmp_log/.cmd b/bmp-openapi/bmp_vendor/bmp_log/.cmd new file mode 100644 index 0000000..5c2f328 --- /dev/null +++ b/bmp-openapi/bmp_vendor/bmp_log/.cmd @@ -0,0 +1 @@ +rm test.log.FATAL test.log.INFO test.log.WARN diff --git a/bmp-openapi/bmp_vendor/bmp_log/README.md b/bmp-openapi/bmp_vendor/bmp_log/README.md new file mode 100644 index 0000000..f39a094 --- /dev/null +++ b/bmp-openapi/bmp_vendor/bmp_log/README.md @@ -0,0 +1,6 @@ +精简日志库,用于打点统计,监控,告警等场景 +- WARN,FATAL等等级的日志即时打印落盘 + - 一个流量可以打印多条WARN,FATAL日志 +- INFO,DEBUG等级的日志,一个流量只落一条日志 + - 支持字段顺序自定义,便于正则匹配做监控等场景 + - 支持自定义代码段耗时打印,便于后续性能统计分析 diff --git a/bmp-openapi/bmp_vendor/bmp_log/go.mod b/bmp-openapi/bmp_vendor/bmp_log/go.mod new file mode 100644 index 0000000..410b4d1 --- /dev/null +++ b/bmp-openapi/bmp_vendor/bmp_log/go.mod @@ -0,0 +1,3 @@ +module coding.jd.com/aidc-bmp/bmp_log + +go 1.17 diff --git a/bmp-openapi/bmp_vendor/bmp_log/log.go b/bmp-openapi/bmp_vendor/bmp_log/log.go new file mode 100644 index 0000000..6e5b79c --- /dev/null +++ b/bmp-openapi/bmp_vendor/bmp_log/log.go @@ -0,0 +1,249 @@ +package cps_log + +import ( + "encoding/json" + "fmt" + "io" + "log" + "os" + "reflect" + "strings" + "time" +) + +// Level type +type Level uint32 + +const ( + // TraceLevel level. Designates finer-grained informational events than the Debug. + TraceLevel Level = iota + // DebugLevel level. Usually only enabled when debugging. Very verbose logging. + DebugLevel + // InfoLevel level. General operational entries about what's going on inside the + // application. + InfoLevel + // WarnLevel level. Non-critical entries that deserve eyes. + WarnLevel + // ErrorLevel level. Logs. Used for errors that should definitely be noted. + // Commonly used for hooks to send errors to an error tracking service. + ErrorLevel + // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the + // logging level is set to Panic. + FatalLevel + // PanicLevel level, highest level of severity. Logs and then calls panic with the + // message passed to Debug, Info, ... + PanicLevel +) + +var globalDefinedKeys = []string{"time", "logid", "self_t", "all_t"} + +type Logger struct { + data map[string]interface{} + level Level + fileName string + definedKeys []string +} + +func New(filename string) *Logger { + if filename == "" { + log.Fatal("filename must be provided !!!") + return nil + } + l := &Logger{ + data: make(map[string]interface{}), + fileName: filename, + } + l.definedKeys = append([]string{}, globalDefinedKeys...) + l.data["time"] = time.Now().Format("2006-01-02T15:04:05") + return l +} + +func NewLoggerWithConfig(filename string, level Level, definedKeys []string) *Logger { + l := New(filename) + l.SetLevel(level) + l.SetStableFields(definedKeys) + return l +} + +func (l *Logger) SetLevel(level Level) { + l.level = level +} + +//SetStableFields 需要固定每条日志的字段时,通过此接口设置,global在前,userdefined在后 +func (l *Logger) SetStableFields(fields []string) { + l.definedKeys = append(l.definedKeys, fields...) +} + +func (l *Logger) Point(key string, val interface{}) { + l.data[key] = val +} + +func (l *Logger) GetPoint(key string) interface{} { + return l.data[key] +} + +func (l *Logger) TimeStart(key string) { + if _, ok := l.data[key]; ok { + log.Print(fmt.Sprintf("point %s TimeStart more than once, check !!!", key)) + } + l.data[key] = time.Now() + +} + +func (l *Logger) TimeEnd(key string) { + if t, ok := l.data[key]; ok { + v := time.Now().Sub(t.(time.Time)).Milliseconds() + l.data[key] = fmt.Sprintf("%f", float64(v)/1000.0) + } else { + log.Print(fmt.Sprintf("missing call TimeStart before TimeEnd when point %s, check it!!!", key)) + } + +} + +func (l *Logger) PushPoint(key string, val interface{}) { + if _, ok := l.data[key]; !ok { + l.data[key] = []interface{}{} + } + d := l.data[key].([]interface{}) + d = append(d, val) +} + +func (l *Logger) Info(v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Infof(format string, v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warn(v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warnf(format string, v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatal(v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatalf(format string, v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Flush() { + if l.level > DebugLevel { + return + } + var beforeStr, afterStr string + for _, key := range l.definedKeys { + if val, ok := l.data[key]; ok { + if key == "time" { + beforeStr = val.(string) + continue + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + beforeStr = beforeStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + beforeStr = beforeStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + beforeStr = beforeStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Printf("val for %s unknown type!!!", key)) + + } + } + } + for key, val := range l.data { + if exist, _ := inArray(key, l.definedKeys); !exist { + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + afterStr = afterStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + afterStr = afterStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + afterStr = afterStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Sprintf("val for %s unknown type!!!", key)) + } + } + } + + line := strings.TrimSpace(beforeStr) + " " + strings.TrimSpace(afterStr) + "\r\n" + filename := fmt.Sprintf("%s.DEBUG", l.fileName) + WriteFile(filename, line) +} + +func WriteFile(filename, line string) { + TimeStamp := time.Now() + str := filename + "." + TimeStamp.Format("2006-01-02") + logf, err := os.OpenFile(str, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + if err != nil { + log.Fatal("open filename error:", err.Error()) + } + defer logf.Close() + if _, err := io.WriteString(logf, line); err != nil { + log.Fatal("write line error:", err.Error()) + } +} + +func inArray(val interface{}, array interface{}) (exists bool, index int) { + exists = false + index = -1 + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + index = i + exists = true + return + } + } + } + return +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/exception/exception.go b/bmp-openapi/bmp_vendor/ironic-common/exception/exception.go new file mode 100644 index 0000000..daf985f --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/exception/exception.go @@ -0,0 +1,24 @@ +package exception + +import ( + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +type Exception struct { + Status int `json:"code"` + ErrorCode string `json:"status"` + Msg string `json:"message"` +} + +var CommonParamValid = Exception{ + Status: httpStatus.BAD_REQUEST, + ErrorCode: errorCode.INVALID_ARGUMENT, + Msg: "param invalid", +} + +var InternalError = Exception{ + Status: httpStatus.INTERNAL_SERVER_ERROR, + ErrorCode: errorCode.INTERNAL, + Msg: "内部错误", +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/go.mod b/bmp-openapi/bmp_vendor/ironic-common/go.mod new file mode 100644 index 0000000..5364f89 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/go.mod @@ -0,0 +1,3 @@ +module git.jd.com/cps-golang/ironic-common + +go 1.17 diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/common/Constants/Constants.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/common/Constants/Constants.go new file mode 100644 index 0000000..b987bd2 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/common/Constants/Constants.go @@ -0,0 +1,145 @@ +package Constants + +const ( + SUFFIX = "%s_command_processor" + + INSTANCE_EXTRA_KEY = "ironic_instance_extra_%s" + + RESTART_DHCP_EXTRA_KEY = "restart_dhcp_extra" + + COLLECT_EXTRA_KEY = "collect_sn_extra_%s" + + INSTANCE_ALIAS_IP_KEY = "ironic_instance_alias_ip_%s_%s" + + COMMAND_RESULT = "ironic_command_result_%s" + + REDIS_KEY_CLUSTER = "ironic_cluster" + + REDIS_KEY_CHECK = "ironic_check" + + REDIS_KEY_INSTANCE = "ironic_instance" + + REDIS_KEY_STATUS = "ironic_instance_status" + + DHCP_RESTART_KEY = "dhcp_restart_key" + + REDIS_KEY_MAIL_RECEIVER_FORMAT = "ironic_mail_receiver_%s" + + REDIS_KEY_MONITOR_COMMAND_FORMAT = "ironic_monitor_command_%s_%s" + + TIMEOUT_INSTANCE_START int = 2 * 60 + + TIMEOUT_INSTANCE_STOP int = 30 + + TIMEOUT_INSTANCE_RESTART int = 3 * 60 + + TIMEOUT_INSTANCE_RESTART_WINDOWS int = 8 * 60 + + TIMEOUT_INSTANCE_STATUS int = 60 * 60 + + TIMEOUT_MONITOR_COMMAND int = 60 * 60 + + TAR_IMAGE = "tar" + + SET_PXE_BOOT_PROCESSOR_NAME = "SetPXEBoot_command_processor" + + SET_DISK_BOOT_PROCESSOR_NAME = "SetDISKBoot_command_processor" + + POWER_ON_PROCESSOR_NAME = "PowerOn_command_processor" + + POWER_OFF_PROCESSOR_NAME = "PowerOff_command_processor" + + DHCP_RESTART_PROCESSOR_NAME = "DHCPRestart_command_processor" + + POWER_RESET_PROCESSOR_NAME = "PowerReset_command_processor" + + POWER_CYCLE_PROCESSOR_NAME = "PowerCycle_command_processor" + + INIT_ROOT_DEVICE_PROCESSOR_NAME = "InitRootDevice_command_processor" + + CLEAN_RAID_PROCESSOR_NAME = "CleanRaid_command_processor" + + MAKE_RAID_PROCESSOR_NAME = "MakeRaid_command_processor" + + PING_PROCESSOR_NAME = "Ping_command_processor" + + ADD_DHCP_CONFIG_HOST_PROCESSOR_NAME = "DHCPConfigAddHost_command_processor" + + DEL_DHCP_CONFIG_HOST_PROCESSOR_NAME = "DHCPConfigDelHost_command_processor" + + WRITE_IMAGE_RAID_PROCESSOR_NAME = "WriteImage_command_processor" + + WRITE_IMAGE_TAR_PROCESSOR_NAME = "WriteImageTar_command_processor" + + QCOW2_MAKE_PARTITIONS_PROCESSOR_NAME = "Qcow2MakePartitions_command_processor" + + MAKE_PARTITIONS_PROCESSOR_NAME = "MakePartitions_command_processor" + + SET_HOSTNAME_PROCESSOR_NAME = "SetHostname_command_processor" + + SET_PASSWORD_PROCESSOR_NAME = "SetPassword_command_processor" + + SET_NETWORK_PROCESSOR_NAME = "SetNetwork_command_processor" + + SET_BOND_PROCESSOR_NAME = "SetBond_command_processor" + + SET_RETAIL_BOND_PROCESSOR_NAME = "SetRetailBond_command_processor" + + SDN_SET_NETWORK_PROCESSOR_NAME = "SetVpcNetwork_command_processor" + + SET_USER_CMD_PROCESSOR_NAME = "SetUserCmd_command_processor" + + SET_KEYPAIRS_PROCESSOR_NAME = "SetKeypairs_command_processor" + + CLEAN_BLOCK_DEVICE_PROCESSOR_NAME = "CleanBlockDevice_command_processor" + + COLLECT_HARDWARE_INFO_PROCESSOR_NAME = "CollectHardwareInfo_command_processor" + + UPLOAD_SYSTEM_LOG_PROCESSOR_NAME = "UploadSystemLog_command_processor" + + CREATE_VRF_PROCESSOR_NAME = "CreateVRF_command_processor" + + CREATE_VRF_BALANCE_PROCESSOR_NAME = "CreateVRFBalance_command_processor" + + CREATE_VSI_INTERFACE_PROCESSOR_NAME = "CreateVSIInterface_command_processor" + + CREATE_VSI_PROCESSOR_NAME = "CreateVSI_command_processor" + + BINDING_VSI_PROCESSOR_NAME = "BindingVSI_command_processor" + + UN_BINDING_VSI_PROCESSOR_NAME = "UnBindingVSI_command_processor" + + BINDING_IPV6_PROCESSOR_NAME = "BindingIPv6_command_processor" + + CREATE_VNI_PROCESSOR_NAME = "CreateVNI_command_processor" + + ADD_ARP_STATIC_PROCESSOR_NAME = "AddArpStatic_command_processor" + + CLEAN_ARP_STATIC_PROCESSOR_NAME = "CleanArpStatic_command_processor" + + SET_BANDWIDTH_PROCESSOR_NAME = "SetBandwidth_command_processor" + + CLEAN_BANDWIDTH__PROCESSOR_NAME = "CleanBandwidth_command_processor" + + SAVE_SWITCH_CONFIG_PROCESSOR_NAME = "SaveSwitchConfig_command_processor" + + SAVE_CONFIG_TO_FTP_SERVER_PROCESSOR_NAME = "SaveConfigToFtpServer_command_processor" + + SYSTEM_ERROR_COMMAND_PROCESSOR_NAME = "SystemErrorCommand_command_processor" + + SDN_REGISTER_PROCESSOR_NAME = "SDNRegister_command_processor" + + SDN_SUBNET_BINDING_PROCESSOR_NAME = "SDNSubnetBinding_command_processor" + + SDN_SUBNET_UNBINDING_PROCESSOR_NAME = "SDNSubnetUnBinding_command_processor" + + SDN_EIP_BINDING_PROCESSOR_NAME = "SDNEipBinding_command_processor" + + SDN_EIP_UNBINDING_PROCESSOR_NAME = "SDNEipUnBinding_command_processor" + + SDN_CLEAN_PROCESSOR_NAME = "SDNClean_command_processor" + + SDN_ADD_ALIAS_IP_PROCESSOR_NAME = "SDNAddAliasIP_command_processor" + + SDN_DELETE_ALIAS_IP_PROCESSOR_NAME = "SDNDeleteAliasIP_command_processor" +) diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/common/ErrorCode/ErrorCode.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/common/ErrorCode/ErrorCode.go new file mode 100644 index 0000000..68743e6 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/common/ErrorCode/ErrorCode.go @@ -0,0 +1,134 @@ +package ErrorCode + +const ( + // 此操作需要的预置条件不满足 400 + FAILED_PRECONDITION = "FAILED_PRECONDITION" + + // 参数错误 400 + INVALID_ARGUMENT = "INVALID_ARGUMENT" + + // 缺少参数 400 + MISSING_ARGUMENT = "MISSING_ARGUMENT" + + // 参数类型不匹配400 + MISMATCH_ARGUMENT_TYPE = "MISMATCH_ARGUMENT_TYPE" + + // 无效的action 400 + INVALID_ACTION = "INVALID_ACTION" + + // 参数超出范围 400 + OUT_OF_RANGE = "OUT_OF_RANGE" + + // 缺少Multipart 400 + MISSING_MULTIPART = "MISSING_MULTIPART" + + // 缺少header信息 400 + MISSING_HEADER = "MISSING_HEADER" + + // pathVariable参数错误 400 + INVALID_PATHVARIABLE = "INVALID_PATHVARIABLE" + + // 验证失败 401 + UNAUTHENTICATED = "UNAUTHENTICATED" + + // 用户未激活 402 + USER_NOT_ACTIVE = "USER_NOT_ACTIVE" + + // 没有权限 403 + HTTP_FORBIDDEN = "HTTP_FORBIDDEN" + + // 找不到对象 404 + NOT_FOUND = "NOT_FOUND" + + // 操作终止 409 + ABORTED = "ABORTED" + + // 对象已存在 409 + ALREADY_EXISTS = "ALREADY_EXISTS" + + // 媒体类型不支持 415 + UNSUPPORTED_MEDIA_TYPE = "UNSUPPORTED_MEDIA_TYPE" + + // 不支持的请求方法 405 + UNSUPPORTED_HTTP_REQUEST_METHOD = "UNSUPPORTED_HTTP_REQUEST_METHOD" + + // 配额不足 429 + QUOTA_EXCEEDED = "QUOTA_EXCEEDED" + + // 库存不足429 + STOCK_SHORTAGE = "STOCK_SHORTAGE" + + // 未知错误 500 + UNKNOWN = "UNKNOWN" + + // 内部错误 500 + INTERNAL = "INTERNAL" + + // 服务不可用 503 + UNAVAILABLE = "UNAVAILABLE" + + // 会话网关 Timeout 504 + SESSION_GATEWAY_TIMEOUT = "SESSION_GATEWAY_TIMEOUT" + + // 参数错误 + PARAMETER_ERROR = "PARAMETER_ERROR" + + //com.jcloud.cps.ironic.common.ErrorCode + UNSUPPORTED_OPERATION = "UNSUPPORTED_OPERATION" + + // 子网没有可用的内网IP可以分配 400 + EXHAUSTED_SUBNET = "EXHAUSTED_SUBNET" + + EXHAUSTED_PUBLIC_IP = "EXHAUSTED_PUBLIC_IP" + + UNSUPPORTED_RAID_TYPE = "UNSUPPORTED_RAID_TYPE" + + CHANGE_ARE_NOT_ALLOWED = "CHANGE_ARE_NOT_ALLOWED" + + // 权限校验失败 + NO_PERMISSION = "NO_PERMISSION" + + // 资源被占用 + RESOURCE_IN_USE = "RESOURCE_IN_USE" + + // 内网IP超出范围 + PRIVATE_IP_NOT_IN_SUBNET = "PRIVATE_IP_NOT_IN_SUBNET" + + // EIP已经绑定 + EIP_ALREADY_ASSOCIATE = "EIP_ALREADY_ASSOCIATE" + + // EIP未绑定 + EIP_HAS_NOT_ASSOCIATE = "EIP_HAS_NOT_ASSOCIATE" + + // 子网未开通IPv6 + SUBNET_HAS_NOT_ASSIGN_IPV6 = "SUBNET_HAS_NOT_ASSIGN_IPV6" + + // IPV6已经被分配 + IPV6_ALREADY_ASSIGN = "IPV6_ALREADY_ASSIGN" + + // 实例已经绑定EIP + INSTANCE_ALREADY_ASSOCIATE_EIP = "INSTANCE_ALREADY_ASSOCIATE_EIP" + + // 实例还没有绑定EIP + INSTANCE_HAS_NOT_ASSOCIATE_EIP = "INSTANCE_HAS_NOT_ASSOCIATE_EIP" + + // 实例已经绑定IPV6 + INSTANCE_ALREADY_ASSOCIATE_IPV6 = "INSTANCE_ALREADY_ASSOCIATE_IPV6" + + // 基础网路不支持EIP + UNSUPPORTED_EIP_IN_BASIC_NETWORK = "UNSUPPORTED_EIP_IN_BASIC_NETWORK" + + // VPC网络不支持调整带宽 + UNSUPPORTED_MODIFY_BANDWIDTH_IN_VPC_NETWORK = "UNSUPPORTED_MODIFY_BANDWIDTH_IN_VPC_NETWORK" + + // 不支持批量指定内网IP + UNSUPPORTED_BATCH_SPECIFYING_PRIVATE_IP = "UNSUPPORTED_BATCH_SPECIFYING_PRIVATE_IP" + + // 不支持批量指定别名IP + UNSUPPORTED_BATCH_SPECIFYING_ALIAS_IP = "UNSUPPORTED_BATCH_SPECIFYING_ALIAS_IP" + + // 密钥对正在被实例使用 + KEYPAIR_IS_USING_BY_INSTANCE = "KEYPAIR_IS_USING_BY_INSTANCE" + + ARGUMENT_ERROR = "ARGUMENT_ERROR" +) diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/common/NamespacePrefixs/NamespacePrefixs.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/common/NamespacePrefixs/NamespacePrefixs.go new file mode 100644 index 0000000..57aa84a --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/common/NamespacePrefixs/NamespacePrefixs.go @@ -0,0 +1,38 @@ +package NamespacePrefixs + +const ( + // api + INSTANCE_ID_PREFIX = "cps-" + + INSTANCE_ID_LENGTH = 28 + + // subnet + SUBNET_ID_PREFIX = "n-" + + SUBNET_ID_LENGTH = 28 + + // wan_subnet + WAN_SUBNET_ID_PREFIX = "wn-" + + WAN_SUBNET_LENGTH = 28 + + // raid + RAID_ID_PREFIX = "r-" + + RAID_ID_LENGTH = 28 + + // image + IMAGE_ID_PREFIX = "o-" + + IMAGE_ID_LENGTH = 28 + + // tenant + TENANT_ID_PREFIX = "t-" + + TENANT_ID_LENGTH = 28 + + // keypair + KEYPAIR_ID_PREFIX = "k-" + + KEYPAIR_ID_LENGTH = 28 +) diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/common/Validation/Validation.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/common/Validation/Validation.go new file mode 100644 index 0000000..9c6f3dc --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/common/Validation/Validation.go @@ -0,0 +1,16 @@ +package Validation + +const ( + REGEX_ID string = `^[a-zA-Z0-9-_]{2,36}$` + REGEX_RAID_VOLUME_TYPE string = `^system$|^data$` + REGEX_NETWORK_TYPE string = `^basic$|^vpc$|^retail$` + INTERFACE_MODE string = `^bond$|^dual$` + REGEX_IP_ADDRESS string = `(^127\.0\.0\.1)|(^192\.168)|(^10\.)|(^172\.1[6-9])|(^172\.2[0-9])|(^172\.3[0-1])` + REGEX_CIDR string = `(10|11|172|192)\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,3})` + REGEX_PASSWORD string = "^(?=.*[a-z])(?=.*[A-Z])(?=.*[\\d\\* \\(\\)`~!@#\\$%&_\\-+=\\|\\{\\}\\[\\]:\";\\'<>,.\\?\\/\\)])[a-zA-Z\\d\\* \\(\\)`~!@#\\$%&_\\-+=\\|\\{\\}\\[\\]:\";\\'<>,.\\?\\/\\)]{8,30}$" + REGEX_DEVICE_STATUS string = "^putawaying$|^creating$|^starting$|^running$|^stopping$|^stopped$|^restarting$|^error$|^upgrading$|^reinstalling$|^destroying$|^resetting_password$" + REGEX_RSA_PUBLIC_KEY string = "^ssh-rsa AAAAB3NzaC1yc2.*" + REGEX_MAIL_TYPE string = "^api_error$|^command_warning$" + REGEX_EMAIL string = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}" + REGEX_SOURCE_TYPE string = "^common$|^customize$|^user_defined$" +) diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/AuditLogsType/AuditLogsType.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/AuditLogsType/AuditLogsType.go new file mode 100644 index 0000000..7b44e06 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/AuditLogsType/AuditLogsType.go @@ -0,0 +1,23 @@ +package AuditLogsType + +const ( + //操作消息类型 + + AuditLogsPutaway = "PutawayDevice" //上架 + AuditLogsUnPutaway = "UnPutawayDevice" //下架 + AuditLogsStartInstances = "StartInstances" //开机 + AuditLogsStopInstances = "StopInstances" //关机 + AuditLogsRestartInstances = "RestartInstances" //重启 + AuditLogsResetInstanceStatus = "ResetInstances" //重置实例状态(新增) + AuditLogsRemoveDevice = "RemoveDevice" //设备移除(新增) + AuditLogsDeleteDevice = "DeleteDevice" //设备删除(新增) + AuditLogsDeleteInstance = "DeleteInstance" //回收实例 + AuditLogsInstanceResetPassword = "InstanceResetPassword" //重置密码 + AuditLogsReinstallInstance = "ReinstallInstance" //重装系统 + AuditLogsEditInstanceName = "EditInstanceName" //编辑实例名称(新增) + AuditLogsCollectHardwareInfo = "CollectHardwareInfo" //设备采集 + AuditLogsTypeCreateInstances = "CreateInstances" //创建实例 + AuditLogsTypeDropInstances = "DropInstances" //删除实例(不走销毁流程,新增) + AuditLogsTypeLockInstances = "LockInstances" //锁定实例(新增) + +) diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/CommandStatus/CommandStatus.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/CommandStatus/CommandStatus.go new file mode 100644 index 0000000..044688c --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/CommandStatus/CommandStatus.go @@ -0,0 +1,28 @@ +package CommandStatus + +const ( + /** + * 待执行 + */ + WAIT = "wait" + + /** + * 执行中 + */ + RUNNING = "running" + + /** + * 完成 + */ + FINISH = "finish" + + /** + * 失败 + */ + ERROR = "error" + + /** + * 取消 + */ + CANCEL = "cancel" +) diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/HttpStatus/HttpStatus.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/HttpStatus/HttpStatus.go new file mode 100644 index 0000000..243c37c --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/HttpStatus/HttpStatus.go @@ -0,0 +1,66 @@ +package HttpStatus + +// refer https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpStatus.html +const ( + ACCEPTED = 202 //Accepted. + ALREADY_REPORTED = 208 //Already Reported. + BAD_GATEWAY = 502 //Bad Gateway. + BAD_REQUEST = 400 //Bad Request. + BANDWIDTH_LIMIT_EXCEEDED = 509 //Bandwidth Limit Exceeded + CHECKPOINT = 103 //Checkpoint. + CONFLICT = 409 //Conflict. + CONTINUE = 100 //Continue. + CREATED = 201 //Created. + EXPECTATION_FAILED = 417 //Expectation Failed. + FAILED_DEPENDENCY = 424 //Failed Dependency. + FORBIDDEN = 403 //Forbidden. + FOUND = 302 //Found. + GATEWAY_TIMEOUT = 504 //Gateway Timeout. + GONE = 410 //Gone. + HTTP_VERSION_NOT_SUPPORTED = 505 //HTTP Version Not Supported. + I_AM_A_TEAPOT = 418 //I'm a teapot. + IM_USED = 226 //IM Used. + INSUFFICIENT_STORAGE = 507 //Insufficient Storage + INTERNAL_SERVER_ERROR = 500 //Internal Server Error. + LENGTH_REQUIRED = 411 //Length Required. + LOCKED = 423 //Locked. + LOOP_DETECTED = 508 //Loop Detected + METHOD_NOT_ALLOWED = 405 //Method Not Allowed. + MOVED_PERMANENTLY = 301 //Moved Permanently. = MOVE//D_TEMPORARILY Deprecated in favor of FOUND which will be returned from HttpStatusvalueOf(302). + MULTI_STATUS = 207 //Multi-Status. + MULTIPLE_CHOICES = 300 //Multiple Choices. + NETWORK_AUTHENTICATION_REQUIRED = 511 //Network Authentication Required. + NO_CONTENT = 204 //No Content. + NON_AUTHORITATIVE_INFORMATION = 203 //Non-Authoritative Information. + NOT_ACCEPTABLE = 406 //Not Acceptable. + NOT_EXTENDED = 510 //Not Extended + NOT_FOUND = 404 //Not Found. + NOT_IMPLEMENTED = 501 //Not Implemented. + NOT_MODIFIED = 304 //Not Modified. + OK = 200 //OK. + PARTIAL_CONTENT = 206 //Partial Content. + PAYLOAD_TOO_LARGE = 413 //Payload Too Large. + PAYMENT_REQUIRED = 402 //Payment Required. + PERMANENT_REDIRECT = 308 //Permanent Redirect. + PRECONDITION_FAILED = 412 //Precondition failed. + PRECONDITION_REQUIRED = 428 //Precondition Required. + PROCESSING = 102 //Processing. + PROXY_AUTHENTICATION_REQUIRED = 407 //Proxy Authentication Required. + REQUEST_HEADER_FIELDS_TOO_LARGE = 431 //Request Header Fields Too Large. + REQUEST_TIMEOUT = 408 //Request Timeout. + REQUESTED_RANGE_NOT_SATISFIABLE = 416 //Requested Range Not Satisfiable. + RESET_CONTENT = 205 //Reset Content. + SEE_OTHER = 303 //See Other. + SERVICE_UNAVAILABLE = 503 //Service Unavailable. + SWITCHING_PROTOCOLS = 101 //Switching Protocols. + TEMPORARY_REDIRECT = 307 //Temporary Redirect. + TOO_EARLY = 425 //Too Early. + TOO_MANY_REQUESTS = 429 //Too Many Requests. + UNAUTHORIZED = 401 //Unauthorized. + UNAVAILABLE_FOR_LEGAL_REASONS = 451 //Unavailable For Legal Reasons. + UNPROCESSABLE_ENTITY = 422 //Unprocessable Entity. + UNSUPPORTED_MEDIA_TYPE = 415 //Unsupported Media Type. + UPGRADE_REQUIRED = 426 //Upgrade Required. + URI_TOO_LONG = 414 //URI Too Long USE_PROXY Deprecated due to security concerns regarding in-band configuration of a proxy + VARIANT_ALSO_NEGOTIATES = 506 //Variant Also Negotiates +) diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/InstanceStatus/InstanceStatus.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/InstanceStatus/InstanceStatus.go new file mode 100644 index 0000000..7703e00 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/InstanceStatus/InstanceStatus.go @@ -0,0 +1,102 @@ +package InstanceStatus + +const ( + /** + * 创建中 + */ + CREATING = "creating" + + /** + * 开机中 + */ + STARTING = "starting" + + /** + * 运行 + */ + RUNNING = "running" + + /** + * 关机中 + */ + STOPPING = "stopping" + + /** + * 关机 + */ + STOPPED = "stopped" + + /** + * 重启中 + */ + RESTARTING = "restarting" + + /** + * 重置密码中 + */ + RESETTING_PASSWORD = "resetting_password" + + /** + * 销毁中 + */ + DESTROYING = "destroying" + + /** + * 已销毁 + */ + DESTROYED = "destroyed" + + /** + * 错误 + */ + ERROR = "error" + + /** + * 调整配置中 + */ + UPGRADING = "upgrading" + + /** + * 重装系统中 + */ + REINSTALLING = "reinstalling" + + // 创建失败 + CREATE_ERROR = "Creation failed" + // 开机失败 + START_ERROR = "Startup failed" + // 关机失败 + STOP_ERROR = "Shutdown failed" + // 重启失败 + RESTART_ERROR = "Reboot failed" + // 销毁失败 + DESTROY_ERROR = "Delete failed" + // 重装失败 + REINSTALL_ERROR = "Reinstall failed" + //重置密码失败 + RESETPASSWD_ERROR = "Resetpasswd failed" +) + +var Instance_To_Error_Status map[string]string = map[string]string{ + // "CollectHardwareInfo" : NewCollectHardwareInfoActor() + "CreateInstances": CREATE_ERROR, + // "CutDeviceStock" : NewCutDeviceStockActor() + "DeleteInstance": DESTROY_ERROR, + // "InstanceResetPassword" : NewInstanceResetPasswordActor() + // "ModifyBandwidth" : NewModifyBandwidthActor() + // "ReinstallInstance" : NewReinstallInstanceActor() + // "ResetSwitchConfig" : NewResetSwitchConfigActor() + // "RestartDhcp" : NewRestartDhcpActor() + "RestartInstances": RESTART_ERROR, + "StartInstances": START_ERROR, + "StopInstances": STOP_ERROR, + "ReinstallInstance": REINSTALL_ERROR, + "InstanceResetPassword": RESETPASSWD_ERROR, +} + +var Error_Instance_To_Reset_Status map[string]string = map[string]string{ + START_ERROR: STOPPED, + STOP_ERROR: RUNNING, + RESTART_ERROR: RUNNING, + DESTROY_ERROR: STOPPED, +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/MessageType/MessageType.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/MessageType/MessageType.go new file mode 100644 index 0000000..0b482b0 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/MessageType/MessageType.go @@ -0,0 +1,57 @@ +package MessageType + +const ( + //操作消息 + MessageTypeOperation = "operation" + //系统消息 + MessageTypeSystem = "system" + //监控消息 + MessageTypeOobMonitor = "oob-monitor" + //带内告警 + MessageTypeInBondAlert = "inbond-alert" +) + +const ( + //操作消息类型 + MessageSubTypeCollectHardwareInfo = "CollectHardwareInfo" + MessageSubTypeCreateDevices = "CreateDevices" + MessageSubTypeCreateInstances = "CreateInstances" + MessageSubTypeCutDeviceStock = "CutDeviceStock" + MessageSubTypeDeleteInstance = "DeleteInstance" + MessageSubTypeInstanceResetPassword = "InstanceResetPassword" + MessageSubTypePutawayDevice = "PutawayDevice" + MessageSubTypeReinstallInstance = "ReinstallInstance" + MessageSubTypeRestartInstances = "RestartInstances" + MessageSubTypeStartInstances = "StartInstances" + MessageSubTypeStopInstances = "StopInstances" + //系统消息类型 + MessageSubTypeLicenseNearTimeout = "LicenseNearTimeout" + //带外监控消息类型 + MessageSubTypePowerFault = "电力故障" + MessageSubTypeTemperatureFault = "温控故障" + MessageSubTypeCPUFault = "CPU故障" + MessageSubTypeMemFault = "内存故障" + MessageSubTypeDiskFault = "硬盘故障" + MessageSubTypeOtherFault = "其他故障" + + //带内告警类型 + MessageSubTypeCPUUsage = "bmp.cpu.util" + MessageSubTypeMemoryUsage = "bmp.memory.util" + MessageSubTypeMemoryUsed = "bmp.memory.used" + MessageSubTypeDiskUsed = "bmp.disk.used" + MessageSubTypeDiskUsage = "bmp.disk.util" + MessageSubTypeDiskReadTraffic = "bmp.disk.bytes.read" + MessageSubTypeDiskWriteTraffic = "bmp.disk.bytes.write" + MessageSubTypeDiskReadIOPS = "bmp.disk.counts.read" + MessageSubTypeDiskWriteIOPS = "bmp.disk.counts.write" + MessageSubTypeNetworkIngressTraffic = "bmp.network.bytes.ingress" + MessageSubTypeNetworkEgressTraffic = "bmp.network.bytes.egress" + MessageSubTypeNetworkIngressPackets = "bmp.network.packets.ingress" + MessageSubTypeNetworkEgressPackets = "bmp.network.packets.egress" + MessageSubTypeLoadAverage1min = "bmp.avg.load1" + MessageSubTypeLoadAverage5min = "bmp.avg.load5" + MessageSubTypeLoadAverage15min = "bmp.avg.load15" + MessageSubTypeTotalTCPConnections = "bmp.tcp.connect.total" + MessageSubTypeEstablishedTCPConnections = "bmp.tcp.connect.established" + MessageSubTypeTotalProcessCount = "bmp.process.total" +) diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/SaleStatus/SaleStatus.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/SaleStatus/SaleStatus.go new file mode 100644 index 0000000..a305a1b --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/enums/SaleStatus/SaleStatus.go @@ -0,0 +1,31 @@ +package SaleStatus + +const ( + /** + * 上架中 + */ + PUTAWAYING = "putawaying" + + /** + * 在售 + */ + SELLING = "selling" + + /** + * 已售 + */ + SOLD = "sold" + + /** + * 锁定 + */ + LOCK = "lock" + + IN = "in" //已入库 + PUTAWAY = "putaway" //已上架 + CREATED = "created" //已创建 + PUTAWAYFAIL = "putawayfail" //上架失败 + UNPUTAWAY = "unputaway" //下架 + UNPUTAWAYING = "unputawaying" //下架中,将“已上架”的设备执行“下架”操作的中间过程状态 + REMOVED = "removed" //已移除 +) diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/AllocRetailPrivateIpMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/AllocRetailPrivateIpMessage.go new file mode 100644 index 0000000..6744995 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/AllocRetailPrivateIpMessage.go @@ -0,0 +1,9 @@ +package api + +type AllocRetailPrivateIpMessage struct { + ApiMessage +} + +func (c AllocRetailPrivateIpMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.AllocRetailPrivateIpMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/ApiMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/ApiMessage.go new file mode 100644 index 0000000..9062508 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/ApiMessage.go @@ -0,0 +1,9 @@ +package api + +type ApiMessage struct { + RequestId string `json:"request_id"` +} + +func (c ApiMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.ApiMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/CollectHardwareInfoMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/CollectHardwareInfoMessage.go new file mode 100644 index 0000000..9b90a5b --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/CollectHardwareInfoMessage.go @@ -0,0 +1,13 @@ +package api + +type CollectHardwareInfoMessage struct { + ApiMessage + Sns []string `json:"sns"` + //是否清空raid + AllowOverride bool `json:"allowOverride"` + NetworkType string `json:"network_type"` +} + +func (c CollectHardwareInfoMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.CollectHardwareInfoMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/CreateDevicesMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/CreateDevicesMessage.go new file mode 100644 index 0000000..1726211 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/CreateDevicesMessage.go @@ -0,0 +1,14 @@ +package api + +type CreateDevicesMessage struct { + ApiMessage + Action string `json:"action"` + Sn string `json:"sn"` + Subnet string `json:"subnet"` + SubnetMask string `json:"subnet_mask"` + Routes string `json:"routes"` +} + +func (c CreateDevicesMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.CreateDevicesMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/CreateInstancesMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/CreateInstancesMessage.go new file mode 100644 index 0000000..d763005 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/CreateInstancesMessage.go @@ -0,0 +1,14 @@ +package api + +type CreateInstancesMessage struct { + ApiMessage + InstanceIds []string `json:"instance_ids"` + Password string `json:"password"` + UserData string `json:"user_data"` + AliasIps interface{} `json:"alias_ips"` //本来是[]AliasIP,依赖太深,直接定义成interface{} + ExtensionAliasIps interface{} `json:"extension_alias_ips"` //本来是[]AliasIP,依赖太深,直接定义成interface{} +} + +func (c CreateInstancesMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.CreateInstancesMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/CutDeviceStockMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/CutDeviceStockMessage.go new file mode 100644 index 0000000..6b61fb3 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/CutDeviceStockMessage.go @@ -0,0 +1,10 @@ +package api + +type CutDeviceStockMessage struct { + ApiMessage + Sns []string `json:"sns"` +} + +func (c CutDeviceStockMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.CutDeviceStockMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/DeleteInstanceMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/DeleteInstanceMessage.go new file mode 100644 index 0000000..952471b --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/DeleteInstanceMessage.go @@ -0,0 +1,10 @@ +package api + +type DeleteInstanceMessage struct { + ApiMessage + InstanceId string `json:"instance_id"` +} + +func (c DeleteInstanceMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.DeleteInstanceMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/InstanceResetPasswordMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/InstanceResetPasswordMessage.go new file mode 100644 index 0000000..c8e2ea8 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/InstanceResetPasswordMessage.go @@ -0,0 +1,12 @@ +package api + +type InstanceResetPasswordMessage struct { + ApiMessage + InstanceId string `json:"instance_id"` + Password string `json:"password"` + Action string `json:"action"` +} + +func (c InstanceResetPasswordMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.InstanceResetPasswordMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/ModifyBandwidthMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/ModifyBandwidthMessage.go new file mode 100644 index 0000000..05b94ea --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/ModifyBandwidthMessage.go @@ -0,0 +1,12 @@ +package api + +type ModifyBandwidthMessage struct { + ApiMessage + InstanceId string `json:"instance_id"` + Bandwidth int32 `json:"bandwidth"` + InstanceStatus string `json:"instance_status"` +} + +func (c ModifyBandwidthMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.ModifyBandwidthMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/PutawayDeviceMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/PutawayDeviceMessage.go new file mode 100644 index 0000000..2856c7f --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/PutawayDeviceMessage.go @@ -0,0 +1,11 @@ +package api + +//设备上架 +type PutawayDeviceMessage struct { + ApiMessage + Sn string `json:"sn"` +} + +func (c PutawayDeviceMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.PutawayDeviceMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/ReinstallInstanceMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/ReinstallInstanceMessage.go new file mode 100644 index 0000000..1b81a3e --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/ReinstallInstanceMessage.go @@ -0,0 +1,13 @@ +package api + +type ReinstallInstanceMessage struct { + ApiMessage + InstanceId string `json:"instance_id"` + KeepData bool `json:"keep_data"` + Password string `json:"password"` + UserData string `json:"user_data"` +} + +func (c ReinstallInstanceMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.ReinstallInstanceMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/ResetSwitchConfigMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/ResetSwitchConfigMessage.go new file mode 100644 index 0000000..ceced55 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/ResetSwitchConfigMessage.go @@ -0,0 +1,10 @@ +package api + +type ResetSwitchConfigMessage struct { + ApiMessage + InstanceIds []string `json:"instance_ids"` +} + +func (c ResetSwitchConfigMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.ResetSwitchConfigMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/RestartDhcpMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/RestartDhcpMessage.go new file mode 100644 index 0000000..2c27222 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/RestartDhcpMessage.go @@ -0,0 +1,10 @@ +package api + +type RestartDhcpMessage struct { + ApiMessage + Az string `json:"az"` +} + +func (c RestartDhcpMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.RestartDhcpMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/RestartInstancesMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/RestartInstancesMessage.go new file mode 100644 index 0000000..058e73b --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/RestartInstancesMessage.go @@ -0,0 +1,10 @@ +package api + +type RestartInstancesMessage struct { + ApiMessage + InstanceIds []string `json:"instance_ids"` +} + +func (c RestartInstancesMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.RestartInstancesMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/SDNCallbackMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/SDNCallbackMessage.go new file mode 100644 index 0000000..2b54eb7 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/SDNCallbackMessage.go @@ -0,0 +1,15 @@ +package api + +type SDNCallbackMessage struct { + ApiMessage + InstanceId string `json:"instance_id"` + Sn string `json:"sn"` + Action string `json:"action"` + Status string `json:"status"` + Message string `json:"message"` + Data interface{} `json:"data"` +} + +func (c SDNCallbackMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.SDNCallbackMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/StartInstancesMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/StartInstancesMessage.go new file mode 100644 index 0000000..1ffdbde --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/StartInstancesMessage.go @@ -0,0 +1,10 @@ +package api + +type StartInstancesMessage struct { + ApiMessage + InstanceIds []string `json:"instance_ids"` +} + +func (c StartInstancesMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.StartInstancesMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/StopInstancesMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/StopInstancesMessage.go new file mode 100644 index 0000000..254f477 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/api/StopInstancesMessage.go @@ -0,0 +1,10 @@ +package api + +type StopInstancesMessage struct { + ApiMessage + InstanceIds []string `json:"instance_ids"` +} + +func (c StopInstancesMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.StopInstancesMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/command/AbstractCommandMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/command/AbstractCommandMessage.go new file mode 100644 index 0000000..6b452b3 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/command/AbstractCommandMessage.go @@ -0,0 +1,10 @@ +package command + +type AbstractCommandMessage struct { + Sn string `json:"sn"` + Action string `json:"action"` +} + +func (c AbstractCommandMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.command.AbstractCommandMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/command/CallbackCommandMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/command/CallbackCommandMessage.go new file mode 100644 index 0000000..cbb981f --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/command/CallbackCommandMessage.go @@ -0,0 +1,12 @@ +package command + +type CallbackCommandMessage struct { + CommandMessage + Status string `json:"status,omitempty"` + Message string `json:"message,omitempty"` + Data interface{} `json:"data,omitempty"` +} + +func (c CallbackCommandMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.command.CallbackCommandMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/command/CommandMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/command/CommandMessage.go new file mode 100644 index 0000000..35d26b6 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/command/CommandMessage.go @@ -0,0 +1,10 @@ +package command + +type CommandMessage struct { + Sn string `json:"sn,omitempty"` + Action string `json:"action,omitempty"` +} + +func (c CommandMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.command.CommandMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/command/DefaultCommandMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/command/DefaultCommandMessage.go new file mode 100644 index 0000000..6acb4d4 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/command/DefaultCommandMessage.go @@ -0,0 +1,13 @@ +package command + +type DefaultCommandMessage struct { + CommandMessage + CommandId int64 `json:"command_id"` + RequestId string `json:"request_id"` + InstanceId string `json:"instance_id"` + Type string `json:"type"` +} + +func (c DefaultCommandMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.command.DefaultCommandMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/command/MonitorMessage.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/command/MonitorMessage.go new file mode 100644 index 0000000..104c40e --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/command/MonitorMessage.go @@ -0,0 +1,16 @@ +package command + +import "time" + +type MonitorMessage struct { + RequestId string `json:"request_id"` + Sn string `json:"sn"` + InstanceId string `json:"instance_id"` + Action string `json:"action"` + TimeoutPolicy string `json:"timeout_policy"` + Now time.Time `json:"now"` +} + +func (c MonitorMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.command.MonitorMessage" +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/event/event.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/event.go new file mode 100644 index 0000000..6343216 --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/event/event.go @@ -0,0 +1,33 @@ +package event + +import ( + "time" + + "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +type Event struct { + EventUuid string `json:"event_uuid"` + ClazzName string `json:"clazz_name"` + Body string `json:"body"` + Time int64 `json:"time"` + UserID string `json:"user_id"` +} + +type CpsRabbitMsg interface { + ClazzName() string +} + +func NewEvent(msg CpsRabbitMsg, logid string, userId string) (*Event, error) { + b, err := util.Convert2String(msg) + if err != nil { + return nil, err + } + return &Event{ + EventUuid: logid, + ClazzName: msg.ClazzName(), + Body: string(b), + Time: time.Now().UnixNano() / 1e6, + UserID: userId, + }, nil +} diff --git a/bmp-openapi/bmp_vendor/ironic-common/ironic/util/util.go b/bmp-openapi/bmp_vendor/ironic-common/ironic/util/util.go new file mode 100644 index 0000000..5aca77e --- /dev/null +++ b/bmp-openapi/bmp_vendor/ironic-common/ironic/util/util.go @@ -0,0 +1,77 @@ +package util + +import ( + "encoding/json" + "errors" + "fmt" + "math/rand" + "reflect" + "strconv" + "time" +) + +//GetRandString 借鉴RandomStringUtils.random包生成随机字符串 +// length 随机字符串的长度(不包括前缀) +// uletter 随机字符串是否包含大写字母字符 +// dletter 随机字符串是否包含小写字母字符 +// number 随机字符串是否包含数字字符 +func GetRandString(prefix string, length int32, uletter, dletter, number bool) string { + rand.Seed(time.Now().UnixNano()) + uletters := []rune("ABCDEFGHIGKLMNOPQRSTUVWXYZ") + dletters := []rune("abcdefghijklmnopqrstuvwxyz") + numbers := []rune("0123456789") + source := []rune{} + if uletter { + source = append(source, uletters...) + } + if dletter { + source = append(source, dletters...) + } + if number { + source = append(source, numbers...) + } + if len(source) == 0 { + return "atLeastContainsLetterOrNumber" + } + b := make([]rune, length) + for i := range b { + b[i] = source[rand.Intn(len(source))] + } + return prefix + string(b) +} + +// 跟现有环境一致,格式:aafc4d1b-f696-4ec2-924f-6fd012aa8345 +func GenerateRandUuid() string { + s := GetRandString("", 32, false, true, true) + runes := []rune(s) + return string(runes[0:8]) + "-" + string(runes[8:12]) + "-" + string(runes[12:16]) + "-" + string(runes[16:20]) + "-" + string(runes[20:32]) +} + +func Convert2String(val interface{}) (msg string, err error) { + + if val == nil{ + return "", nil + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool: + msg = strconv.FormatBool(val.(bool)) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + msg = fmt.Sprintf("%v", val) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + msg = fmt.Sprintf("%v", val) + case reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + msg = fmt.Sprintf("%v", val) + case reflect.String: + msg = val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + s, err := json.Marshal(val) + if err == nil { + msg = string(s) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + err = errors.New(fmt.Sprintf("type %s not support convert to string", reflect.TypeOf(val).String())) + default: + err = errors.New(fmt.Sprintf("type %s not support convert to string", reflect.TypeOf(val).String())) + } + return +} diff --git a/bmp-openapi/build.sh b/bmp-openapi/build.sh new file mode 100644 index 0000000..2ba4b0f --- /dev/null +++ b/bmp-openapi/build.sh @@ -0,0 +1,124 @@ +#!/bin/bash +############################################################################### +#编译脚本的原理是将编译结果放到output目录中,这个样例模版提供一个产生 +#一个最基本golang运行程序包的编译脚本,对于特殊的需求请酌情考虑 +# +#1、该脚本支持参数化,参数将传入build_package函数(内容为最终执行的编译命令) +# ,用$1,$2....表示,第1,2...个参数 +#2、部署需要启动程序,所以需要提供control文件放在当前目录中,用于启动和 +# 监控程序状态 + +###############用户修改部分################ +readonly PROJECT_NAME="cps-ironic-api" #项目名称,相对于$GOPATH/src文件夹所在的目录,可选项 +readonly PACKAGE_DIR_NAME=main.go #main文件相对于src文件夹所在的目录,可选项 +readonly PACKAGE_BIN_NAME=cps-ironic-api #定义产出的运行程序名,必填项 +readonly CONF_DIR_NAME="conf" #定义配置文件目录,此路径为相对路径,可选项 +readonly OTHERS_DIR_NAME="" #定义其它文件目录,多个目录以空格区分,此路径为相对路径,可选项 +#最终的抽包路径为$OUTPUT +########################################### + +if [[ "${PACKAGE_BIN_NAME}" == "" ]];then + echo "Please set "PACKAGE_BIN_NAME" value" + exit 1 +fi + +function set_work_dir +{ + readonly OUTPUT=$(pwd)/output + readonly WORKSPACE_DIR=$(pwd) +} + +#清理编译构建目录操作 +function clean_before_build +{ + cd ${WORKSPACE_DIR} + rm -rf bin pkg + rm -rf ${OUTPUT} +} + +#初始化编译环境 +function prepare_package() +{ + if [ ! -z "$PROJECT_NAME" ];then + mkdir -p src/$PROJECT_NAME + copy_files=`ls |grep -vw 'src'` + cp -rf $copy_files src/$PROJECT_NAME/ + fi +} + +#实际的编译命令 +#这个函数中可使用$1,$2...获取第1,2...个参数 +function build_package() +{ + cd ${WORKSPACE_DIR} + # export GOPATH=$(pwd) + go clean + echo $(pwd) + echo $(ls) + go build -v -gcflags="-N -l" -o ${PACKAGE_BIN_NAME} ${PACKAGE_DIR_NAME} || return 1 +} + +#建立最终发布的目录 +function build_dir +{ + mkdir -p ${OUTPUT}/bin || return 1 +} + +function dir_not_empty() +{ + if [[ ! -d $1 ]];then + return 1 + fi + if [[ $(ls $1|wc -l) -eq 0 ]];then + return 1 + fi + return 0 +} + +#拷贝编译结果到发布的目录 +function copy_result +{ + cd ${WORKSPACE_DIR} + cp -r ${PACKAGE_BIN_NAME} ${OUTPUT}/bin/ || return 1 + cp -r ./control ${OUTPUT}/bin || return 1 + dir_not_empty ${WORKSPACE_DIR}/${CONF_DIR_NAME} && mkdir -p ${OUTPUT}/${CONF_DIR_NAME} + cp -rf ./${CONF_DIR_NAME}/* ${OUTPUT}/${CONF_DIR_NAME}/ + test -z "$OTHERS_DIR_NAME" || cp -rf $OTHERS_DIR_NAME ${OUTPUT}/ + return 0 +} + +#执行 +function main() +{ + cd $(dirname $0) + set_work_dir + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Cleaning...' + clean_before_build || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Clean completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'preparng...' + prepare_package || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'prepare completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Building...' + build_package $@ || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Build completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Making dir...' + build_dir || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Make completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy result to publish dir...' + copy_result || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy completed' + echo + + exit 0 +} + +main $@ diff --git a/bmp-openapi/conf/app.conf b/bmp-openapi/conf/app.conf new file mode 100644 index 0000000..e69de29 diff --git a/bmp-openapi/conf/bmp-openapi-test.ini b/bmp-openapi/conf/bmp-openapi-test.ini new file mode 100644 index 0000000..e26eb5f --- /dev/null +++ b/bmp-openapi/conf/bmp-openapi-test.ini @@ -0,0 +1,27 @@ +runmode = "test" +[test] + +httpport = 8801 +# mysql +bmp_db_host=${BMP_DB_HOST||10.226.192.72} +bmp_db_port=${BMP_DB_PORT||13306} +bmp_db_user=${BMP_DB_USER||bmp_rw} +bmp_db_password=${BMP_DB_PASSWORD||LpK9Jq12Zf} +bmp_db_name=${BMP_DB_NAME||bmp} + +bmp_redis_host=${BMP_REDIS_HOST||10.226.192.72} +bmp_redis_port=${BMP_REDIS_PORT||16379} +bmp_redis_password=${BMP_REDIS_PASSWORD||LpK9Jq12Zf} + + +# RabbitMQ for Ironic +bmp_mq_host=${BMP_MQ_HOST||10.226.192.72} +bmp_mq_port=${BMP_MQ_PORT||15672} +bmp_mq_user=${BMP_MQ_USER||bmp} +bmp_mq_password=${BMP_MQ_PASSWORD||LpK9Jq12Zf} +bmp_mq_vhost=${BMP_MQ_VHOST||/bmp} +bmp_mq_exchange=CPS_IRONIC_SCHEDULER +bmp_mq_receive_routing_key=/test + + + diff --git a/bmp-openapi/conf/bmp-openapi.ini b/bmp-openapi/conf/bmp-openapi.ini new file mode 100644 index 0000000..abea002 --- /dev/null +++ b/bmp-openapi/conf/bmp-openapi.ini @@ -0,0 +1,47 @@ +appname = bmp-openapi +autorender = false +copyrequestbody = true +EnableDocs = true + + +httpport = 8801 +# mysql +jdbc.url= +bmp_db_host=${BMP_DB_HOST} +bmp_db_port=${BMP_DB_PORT} +bmp_db_user=${BMP_DB_USER} +bmp_db_password=${BMP_DB_PASSWORD} +bmp_db_name=${BMP_DB_NAME} + +bmp_redis_host=${BMP_REDIS_HOST} +bmp_redis_port=${BMP_REDIS_PORT} +bmp_redis_password=${BMP_REDIS_PASSWORD} + + +# RabbitMQ for Ironic +bmp_mq_host=${BMP_MQ_HOST} +bmp_mq_port=${BMP_MQ_PORT} +bmp_mq_user=${BMP_MQ_USER} +bmp_mq_password=${BMP_MQ_PASSWORD} +bmp_mq_vhost=${BMP_MQ_VHOST} +bmp_mq_exchange=CPS_IRONIC_SCHEDULER +bmp_mq_receive_routing_key=/test + +bmp_monitor_proxy_host=${BMP_MONITOR_PROXY_HOST||10.208.12.72} +bmp_monitor_proxy_port=${BMP_MONITOR_PROXY_PORT||8805} + +bmp_pronoea_host=${BMP_PRONOEA_HOST||10.208.12.75} +bmp_pronoea_port=${BMP_PRONOEA_PORT||9999} + +bmp_image_host=${BMP_IMAGE_HOST||10.208.12.72} +bmp_image_port=${BMP_IMAGE_PORT||10000} + +# log +log.level=DEBUG +log.max.history=10 +log.path=/var/log/bmp/bmp-openapi +# ipv6默认网关 +gateway6=2403:1EC0:8549:60C0::1 +#如果在本地环境测试,启用下面的文件,改成自己的本地环境配置 +; include "bmp-openapi-test.ini" + diff --git a/bmp-openapi/conf/license b/bmp-openapi/conf/license new file mode 100644 index 0000000..92a0395 --- /dev/null +++ b/bmp-openapi/conf/license @@ -0,0 +1 @@ ++gkxY4GeG+g8udxYBVicBjFYeeE/WGIrdkKhqUmaHgb8VoUAIAMjyK88AE3PvxbHHo34tZtBOFOigWJ4opvHpjDTLtYdmwD3/uopbzXJxYy2KuCjpJxJ/8fK0nVnVmD6bN7sO0cALVIMc+V4hHeiXs2aAxj61wVP+bd11Dkzl5o= \ No newline at end of file diff --git a/bmp-openapi/conf/machine_info b/bmp-openapi/conf/machine_info new file mode 100644 index 0000000..f18ff17 --- /dev/null +++ b/bmp-openapi/conf/machine_info @@ -0,0 +1,6 @@ +{ + "app_name": "bmp", + "app_version": "v1.1", + "machine_id": "your_machine_id", + "expire_date": "20230550" +} \ No newline at end of file diff --git a/bmp-openapi/constant/constant.go b/bmp-openapi/constant/constant.go new file mode 100644 index 0000000..1b74a3f --- /dev/null +++ b/bmp-openapi/constant/constant.go @@ -0,0 +1,179 @@ +package constant + +import "fmt" + +var ( + OK RespMsg + INVALID_ARGUMENT RespMsg + INVALID_ARGUMENT_WITH_ARGS RespMsg + NO_LOGIN_PIN RespMsg + AUTH_NOT_LOGIN RespMsg + AUTH_BASIC_AUTH_ERROR RespMsg + AUTH_LICENSE_ERROR RespMsg + AUTH_LICENSE_TIMEOUT_ERROR RespMsg + AUTH_LICENSE_MODULE_ERROR RespMsg + AUTH_LICENSE_NODES_EXCEED_ERROR RespMsg + AUTH_ERROR_FOR_AUTH_AND_USERID RespMsg + INVALID_ARGUMENT_OUT_OF_RANGE RespMsg + RATE_LIMIT RespMsg + INTERNAL_ERROR RespMsg + NOT_FOUND RespMsg + NOT_FOUND_WITH_ARGS RespMsg + CANCELLED RespMsg + CANCELLEDWithArgs RespMsg + PermissionDenyForObject RespMsg + NOT_SUPPORTED RespMsg +) + +type RespMsg struct { + Code int `json:"code"` + MessageEn string `json:"message_en"` + Messagech string `json:"message_ch"` + Status string `json:"status"` +} + +func init() { + OK = RespMsg{ + 200, + "OK", + "成功", + "OK", + } + INVALID_ARGUMENT = RespMsg{ + 400, + "Parameters error", + "参数错误", + "INVALID_ARGUMENT", + } + INVALID_ARGUMENT_WITH_ARGS = RespMsg{ + 400, + "%s", + "%s", + "INVALID_ARGUMENT", + } + AUTH_NOT_LOGIN = RespMsg{ + 400, + "Login Please", + "请先登录", + "AUTH_NOT_LOGIN", + } + AUTH_BASIC_AUTH_ERROR = RespMsg{ + 401, + "Unauthorized", + "认证失败或者权限错误", + "AUTH_ERROR_OR_PERMISSION_DENIED", + } + AUTH_LICENSE_ERROR = RespMsg{ + 403, + "LicenseError", + "授权认证失败", + "LICENSE_ERROR", + } + AUTH_LICENSE_TIMEOUT_ERROR = RespMsg{ + 403, + "LicenseTimeoutError", + "授权已过期,请联系客服", + "LICENSE_TIMEOUT_ERROR", + } + AUTH_LICENSE_MODULE_ERROR = RespMsg{ + 403, + "LicenseModuleError", + "该模块未开通授权,请联系客服", + "LICENSE_MODULE_ERROR", + } + AUTH_LICENSE_NODES_EXCEED_ERROR = RespMsg{ + 403, + "LicenseNodesExceedError", + "节点超过授权数,请联系客服", + "LICENSE_NODES_ERROR", + } + AUTH_ERROR_FOR_AUTH_AND_USERID = RespMsg{ + 401, + "Unauthorized", + "认证失败,auth和userid信息不一致", + "AUTH_ERROR_FOR_INVALID_AUTH_USERID", + } + RATE_LIMIT = RespMsg{ + 429, + "Requests are too frequent", + "请求过于频繁", + "RATE_LIMIT", + } + INTERNAL_ERROR = RespMsg{ + 500, + "Internal error", + "内部错误", + "INTERNAL", + } + NOT_FOUND = RespMsg{ + 404, + "Not found", + "找不到对象", + "NOT_FOUND", + } + NOT_FOUND_WITH_ARGS = RespMsg{ + 404, + "%s Not found", + "%s 找不到对象", + "NOT_FOUND", + } + CANCELLED = RespMsg{ + 400, + "Operation cancelled", + "取消操作", + "CANCELLED", + } + NOT_SUPPORTED = RespMsg{ + 400, + "Operation not allowed", + "不支持此操作", + "NOT ALLOWEDS", + } + CANCELLEDWithArgs = RespMsg{ + 400, + "%s", + "%s", + "CANCELLED", + } + PermissionDenyForObject = RespMsg{ + 401, + "permission denied", + "无操作权限", + "PERMISSION DENIED", + } +} + +func BuildNotFoundWithArgs(c, e string) RespMsg { + return RespMsg{ + 404, + fmt.Sprintf("%s Not found", e), + fmt.Sprintf("%s 找不到对象", c), + "NOT_FOUND", + } +} +func BuildCANCELLEDWithArgs(c, e string) RespMsg { + return RespMsg{ + 400, + e, + c, + "CANCEL", + } +} + +func BuildInvalidArgumentWithArgs(c, e string) RespMsg { + return RespMsg{ + 400, + e, + c, + "INVALID_ARGUMENT", + } +} + +func BuildAuthTokenAuthError(c, e string) RespMsg { + return RespMsg{ + 401, + e, + c, + "AUTH_TOKEN_AUTH_ERROR", + } +} diff --git a/bmp-openapi/control b/bmp-openapi/control new file mode 100644 index 0000000..d7d8eaa --- /dev/null +++ b/bmp-openapi/control @@ -0,0 +1,125 @@ +#!/bin/bash +set -x +cd "$(dirname $0)"/.. +BASE_DIR=`pwd` +if [ -f default_env.sh ];then + source default_env.sh +fi + +PROC_NAME=cps-ironic-api # 进程名 一般就是二进制的名字java类程序一般就是java +PROC_PORT=8808 # 程序占用的端口,建议写,程序不占用端口的话只用ps来判断进程是否启动,机器上有同名程序是可能有问题 +WAIT_TIME=60 # 执行START_COMMAND后到程序能完全启动listen端口需要花的时间 + +USER=nginx +app_dir=/home/$USER/$PROC_NAME +mkdir -p $app_dir/log + +START_COMMAND="$app_dir/bin/cps-ironic-api -c $app_dir/conf/ironic-api.ini" #在output目录下启动你程序的命令 + +help(){ + echo "${0} " + exit 1 +} + +checkhealth(){ + if [[ -n "$PROC_PORT" ]] ; then + PORT_PROC=$(/usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d |awk '{print $NF}' |grep -oP '".*"' |sed "s/\"//g" |uniq) + if [ X"$PORT_PROC" = X"$PROC_NAME" ] ; then + echo "1 running" + return 0 + fi + echo "1 not running" + return 1 + else + ps -eo comm,pid |grep -P "^$PROC_NAME" + if [ "$?" = 0 ] ; then + echo "2 running" + return 0 + fi + echo "2 not running" + return 1 + fi +} + + +start(){ + checkhealth + if [ $? = 0 ]; then + echo "[WARN] $PROC_NAME is aleady running!" + return 0 + fi + + [ -d "$app_dir" ] && cd $app_dir && rm -rf `ls ${app_dir} | grep -v log` + cp -r $BASE_DIR/* ${app_dir}/ + chown -R $USER:$USER ${app_dir} + su $USER -c "nohup $START_COMMAND > ${app_dir}/log/cps-ironic-api.log 2>&1 &" + + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ $? = 0 ]; then + echo "Start $PROC_NAME success" + return 0 + fi + done + echo "[ERROR] Start $PROC_NAME failed" + return 1 +} + +stop(){ + if [[ -n "$PROC_PORT" ]] ; then + PROC_ID=$( /usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d | awk '{print $NF}' | grep -oP ',.*,' | grep -oP "\d+" | uniq ) + else + PROC_ID=$(ps -eo comm,pid | grep "^$PROC_NAME" |awk '{print $2}') + fi + + if [[ -z "$PROC_ID" ]] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + + checkhealth + if [ "$?" != "0" ] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + kill $PROC_ID + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + done + + kill -9 $PROC_ID + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + + echo "[ERROR] Stop $PROC_NAME failed" + return 1 +} + +case "${1}" in + start) + start + ;; + stop) + stop + ;; + status|health|checkhealth) + checkhealth + ;; + restart) + stop && start + ;; + *) + help + ;; +esac + diff --git a/bmp-openapi/controllers/apikeyController.go b/bmp-openapi/controllers/apikeyController.go new file mode 100644 index 0000000..dae2535 --- /dev/null +++ b/bmp-openapi/controllers/apikeyController.go @@ -0,0 +1,151 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/apikeyLogic" + + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type ApikeyController struct { + BaseController +} + +// CreateAPIkey ... +// swagger:route POST /user/apikeys apiKey createUserApikey +// +// CreateUserApikey 创建apikey +// +// Responses: +// 200: createUserApikey +// default: ErrorResponse + +func (c *ApikeyController) CreateUserApikey() { + defer c.CatchException() + req := &requestTypes.CreateApikeyRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateAPIkey parse pAPIkeyt body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + uuid, err := apikeyLogic.CreateApikey(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ApikeyId{ + ApikeyId: uuid, + } +} + +// QueryByAPIkeyIds ... +// swagger:route GET /user/apikeys apiKey describeUserAPIKeys +// +// DescribeUserAPIKeys 获取APIKey列表 +// +// Responses: +// 200: describeUserAPIKeys +// default: ErrorResponse +func (c *ApikeyController) DescribeUserAPIKeys() { + defer c.CatchException() + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.QueryApikeysRequest{ + Name: c.GetString("name"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + res, count, err := apikeyLogic.GetApikeyList(c.logPoints, *req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ApikeyList{ + Apikeys: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } + +} + +// DescribeUserAPIKey ... +// swagger:route GET /user/apikeys/{apikey_id} apiKey describeUserAPIKey +// +// DescribeUserAPIKey 获取apikey详情 +// +// Responses: +// 200: describeUserAPIKey +// default: ErrorResponse +func (c *ApikeyController) DescribeUserAPIKey() { + defer c.CatchException() + apikeyId := c.Ctx.Input.Param(":apikey_id") + res, err := apikeyLogic.GetApikeyById(c.logPoints, apikeyId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + c.Res.Result = response.ApikeyInfo{ + Apikey: res, + } +} + +// ModifyAPIkey ... +// swagger:route PUT /user/apikeys/{apikey_id} apiKey modifyUserApikey +// +// ModifyUserApikey 修改apikey(暂不启用) +// +// Responses: +// 200: modifyUserApikey +// default: ErrorResponse + +func (c *ApikeyController) ModifyUserApikey() { + defer c.CatchException() + apikeyId := c.Ctx.Input.Param(":apikey_id") + req := &requestTypes.ModifyApikeyRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyAPIkey parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := apikeyLogic.ModifyApikey(c.logPoints, req, apikeyId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// DeleteAPIkey ... +// swagger:route DELETE /user/apikeys/{apikey_id} apiKey deleteUserApikey +// +// DeleteUserApikey 删除某个apikey +// +// Responses: +// 200: deleteUserApikey +// default: ErrorResponse + +func (c *ApikeyController) DeleteUserApikey() { + defer c.CatchException() + apikeyId := c.Ctx.Input.Param(":apikey_id") + if err := apikeyLogic.DeleteApikey(c.logPoints, apikeyId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} diff --git a/bmp-openapi/controllers/auditLogsController.go b/bmp-openapi/controllers/auditLogsController.go new file mode 100644 index 0000000..47332fb --- /dev/null +++ b/bmp-openapi/controllers/auditLogsController.go @@ -0,0 +1,83 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/logic/auditLogLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + "git.jd.com/cps-golang/ironic-common/ironic/enums/AuditLogsType" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// AuditLogsController operations for auditlog +type AuditLogsController struct { + BaseController +} + +// swagger:route GET /auditLogs auditLog describeAuditLogs +// DescribeAuditLogs 获取审计日志列表 +// Responses: +// 200: describeAuditLogs +// default: ErrorResponse + +func (c *AuditLogsController) DescribeAuditLogs() { + defer c.CatchException() + req := &requestTypes.DescribeAuditLogsRequest{ + Sn: c.GetString("sn"), + Operation: c.GetString("operation"), + UserName: c.GetString("username"), + Result: c.GetString("result"), + IsAll: c.GetString("isAll"), + } + st, _ := c.GetInt("startTime") + et, _ := c.GetInt("endTime") + req.StartTime = st + req.EndTime = et + + req.Validate(c.logPoints) + + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + //device_types, err := deviceTypeLogic.QueryByRequest(c.logPoints, req) + res, count, err := auditLogLogic.QueryAuditLogs(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.AuditLogList{ + AuditLogs: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } +} + +// swagger:route GET /auditLogs/types auditLog describeAuditLogTypes +// DescribeAuditLogTypes 获取审计日志类型 +// Responses: +// 200: describeAuditLogTypes +// default: ErrorResponse + +func (c *AuditLogsController) DescribeAuditLogTypes() { + + //device_types, err := deviceTypeLogic.QueryByRequest(c.logPoints, req) + res := auditLogLogic.DescribeAuditLogsTypes(c.logPoints) + + c.Res.Result = res +} + +func (c *AuditLogsController) MockMultiAuditLogs() { + + c.logPoints.Point("userId", "user-ta5c5tsos2wkm8d2qtmvx3vufr2h") + //device_types, err := deviceTypeLogic.QueryByRequest(c.logPoints, req) + for i := 0; i < 100000; i++ { + auditLogLogic.SaveAuditLogs(c.logPoints, "d-minping-mock-deviceid", "minping-mock-instanceId", AuditLogsType.AuditLogsStopInstances) + } + + c.Res.Result = response.CommonResponse{ + Success: true, + } +} diff --git a/bmp-openapi/controllers/baseController.go b/bmp-openapi/controllers/baseController.go new file mode 100644 index 0000000..d445ced --- /dev/null +++ b/bmp-openapi/controllers/baseController.go @@ -0,0 +1,477 @@ +package controllers + +import ( + "encoding/json" + "fmt" + "reflect" + "strconv" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/apikeyLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/userLogic" + + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" + + util "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + "github.com/beego/beego/v2/server/web" +) + +type ErrorResponse struct { + // 错误码 + Code int `json:"code"` + // 错误信息 + Message string `json:"message"` + // 错误状态 + Status string `json:"status"` +} + +type Response struct { + // 操作失败结果。成功时有此结构 + Result interface{} `json:"result,omitempty"` + // 操作失败结果。失败时有此结构 + Error *ErrorResponse `json:"error,omitempty"` + // 请求traceId + // required: true + RequestId string `json:"requestId"` +} + +// SubnetController operations for Subnet +type BaseController struct { + web.Controller + logPoints *log.Logger + Res Response + pageable util.Pageable +} + +func (b *BaseController) SetErrorResponse(code int, message, status string) { + b.Res.Error = &ErrorResponse{ + Code: code, + Message: message, + Status: status, + } +} + +func (b *BaseController) Prepare() { + + web.ReadFromRequest(&b.Controller) + logPath, _ := web.AppConfig.String("log.path") + b.logPoints = log.New(logPath + "/bmp-openapi.log") + b.logPoints.SetStableFields([]string{"method", "uri", "header", "request", "response"}) + b.logPoints.Point("uri", b.Ctx.Request.RequestURI) + b.logPoints.Point("method", b.Ctx.Request.Method) + b.logPoints.Point("header", b.Ctx.Request.Header) + b.logPoints.Point("language", b.GetLanguage()) + b.logPoints.Point("timezone", b.GetTimezone()) + + b.logPoints.Point("request", string(b.Ctx.Input.RequestBody)) + b.logPoints.TimeStart("all_t") + b.logPoints.TimeStart("self_t") + traceId := b.GetTraceID() + + b.logPoints.Point("logid", traceId) + b.Ctx.Output.Header("TraceId", traceId) + b.Res = Response{} + + //鉴定用户/系统apikey,补全流量的用户信息,操作权限 + if !strings.HasPrefix(b.Ctx.Input.URI(), "/v1/users/verify") && !strings.HasPrefix(b.Ctx.Input.URI(), "/v1/users/getUserByName") && !strings.HasPrefix(b.Ctx.Input.URI(), "/commands/retryCommand") && !strings.HasPrefix(b.Ctx.Input.URI(), "/v1/license/currentVersion") && !strings.HasPrefix(b.Ctx.Input.URI(), "/v1/offline") && !strings.HasPrefix(b.Ctx.Input.URI(), "/v1/innerTest") { + + err := b.ValidateAuth() + if err != nil { + b.logPoints.Warn("ValidateLicense error:", err.Messagech) + } else if strings.HasPrefix(b.Ctx.Input.URI(), "/v1/monitor") { + // err = licenseLogic.ValidateLicense(b.logPoints, b.Ctx.Input.URI()) + // if err != nil { + // b.logPoints.Warn("ValidateLicense error:", err.Messagech) + // } + + } + + if err != nil { + b.Res.Error = &ErrorResponse{ + Code: err.Code, + Message: err.Messagech, + Status: err.Status, + } + if b.logPoints.GetPoint("language").(string) == baseLogic.EN_US { + b.Res.Error.Message = err.MessageEn + } + + b.Res.RequestId = traceId + b.Data["json"] = b.Res + if b.Res.Error != nil { + b.Ctx.Output.Status = b.Res.Error.Code + } + b.ServeJSON() + return + } + + } + + b.pageable = util.Pageable{ + PageNumber: b.getPageNumber(), + PageSize: b.getPageSize(), + } + b.logPoints.Info("url:", b.Ctx.Request.URL) + b.logPoints.Info("body:", string(b.Ctx.Input.RequestBody)) + fmt.Println("[DEBUG MINPING]url:", b.Ctx.Request.URL) + fmt.Println("[DEBUG MINPING]method", b.Ctx.Request.Method) + fmt.Println("[DEBUG MINPING]header", b.Ctx.Request.Header) + fmt.Println("[DEBUG MINPING]body:", string(b.Ctx.Input.RequestBody)) + fmt.Println("[DEBUG MINPING]all header", b.GetAllHeader()) +} + +func (b *BaseController) Finish() { + b.Res.RequestId = b.GetTraceID() + b.Data["json"] = b.Res + + if b.Res.Error != nil { + b.Ctx.Output.Status = b.Res.Error.Code + } + b.ServeJSON() + + b.logPoints.TimeEnd("self_t") + b.logPoints.TimeEnd("all_t") + b.logPoints.Point("response", b.Data["json"]) + + v, _ := json.Marshal(b.Data["json"]) + b.logPoints.Info("response:", string(v)) + fmt.Println("[DEBUG MINPING]response:", string(v)) + + b.logPoints.Flush() +} + +func (b *BaseController) GetString(key string) string { + return b.Controller.GetString(key, "") +} + +//业务代码可以直接panic终止运行 +func (b *BaseController) CatchException() { + // if r := recover(); r != nil { + // // t := make([]byte, 1<<16) + // // runtime.Stack(t, true) + // t, _ := json.Marshal(r) + // b.logPoints.Warn(string(t)) + // if reflect.TypeOf(r).String() == "exception.Exception" { + // b.Res["result"] = r + // } else { //非预期panic输出统一化 + // b.Res["result"] = exception.InternalError + // } + // } + if r := recover(); r != nil { + t, _ := json.Marshal(r) + b.logPoints.Warn(string(t)) + //b.Res["result"] = int(reflect.ValueOf(r).Field(0).Int()) + //if reflect.ValueOf(r).Field(1).String() == "" { //重要返回,如果errno不写,那么默认的errno和msg在这里设置 + // b.Res["error"] = 40000 + // b.Res["m"] = reflect.ValueOf(r).Field(2).String() + // return + //} + //errno, err := strconv.Atoi(reflect.ValueOf(r).Field(1).String()) //如果errno不写 + //if err != nil { //字符串转整形失败 + // b.Res["errno"] = 40001 + // b.Res["errmsg"] = reflect.ValueOf(r).Field(2).String() + // return + //} + var ( + code int + chMessage string + enMessage string + status string + ) + if reflect.ValueOf(r).Field(0).Int() == 0 { + code = httpStatus.BAD_REQUEST //默认httpcode 400 + } else { + code = int(reflect.ValueOf(r).Field(0).Int()) + } + //en_message + if reflect.ValueOf(r).Field(1).String() == "" { + enMessage = errorCode.INVALID_ARGUMENT //参数错误 + } else { + enMessage = reflect.ValueOf(r).Field(1).String() + } + + //ch_message + if reflect.ValueOf(r).Field(2).String() == "" { + chMessage = errorCode.INVALID_ARGUMENT //参数错误 + } else { + chMessage = reflect.ValueOf(r).Field(2).String() + } + + //status + if reflect.ValueOf(r).Field(3).String() == "" { + status = errorCode.INVALID_ARGUMENT //参数错误 + } else { + status = reflect.ValueOf(r).Field(3).String() //具体的报错信息err.error() + } + fmt.Println("recover info:", code, chMessage, enMessage, status) + if b.logPoints.GetPoint("language").(string) == baseLogic.EN_US { + b.SetErrorResponse(code, enMessage, status) + } else { + b.SetErrorResponse(code, chMessage, status) + } + + } +} + +func (b *BaseController) GetAllHeader() string { + v, _ := json.Marshal(b.Ctx.Request.Header) + return string(v) +} + +func (b *BaseController) ValidateAuth() *constant.RespMsg { + + auth := "" + if b.Ctx.Request.Header["Authorization"] != nil { + auth = b.Ctx.Request.Header["Authorization"][0] + } + items := strings.Split(auth, "Bearer ") + if len(items) != 2 { + b.logPoints.Warnf("ValidateAuth.token type invalided, token:%s", auth) + err := constant.AUTH_BASIC_AUTH_ERROR + return &err + } + token := items[1] + apiKeyEntity, err := apikeyLogic.ValidateApiKey(b.logPoints, token) + if err != nil { + b.logPoints.Warnf("ValidateAuth.ValidateApiKey error, auth:%s, error:%s", auth, err.Error()) + err := constant.AUTH_BASIC_AUTH_ERROR + return &err + } + if apiKeyEntity == nil { + b.logPoints.Warnf("ValidateAuth.apiKeyEntity empty,auth:%s", auth) + err := constant.AUTH_BASIC_AUTH_ERROR + return &err + } + + // 只读的apikey不允许做非get操作 + if apiKeyEntity.ReadOnly == 1 && b.logPoints.GetPoint("method").(string) != "GET" { + b.logPoints.Warn("readonly apikey try do modify operation", token, b.Ctx.Input.Method(), b.Ctx.Input.URI()) + err := constant.PermissionDenyForObject + return &err + } + + //如果是个人apikey,可以不传userId + var userId string + if apiKeyEntity.Type == "user" { + b.logPoints.Point("traffic_source", "api") + if apiKeyEntity.UserID != b.GetUserId() { + b.logPoints.Warn("userid in auth and header not match") + // err := constant.AUTH_ERROR_FOR_AUTH_AND_USERID + // return &err + } + userId = apiKeyEntity.UserID + } else { //系统apikey时,userId必须要经header传过来 + b.logPoints.Point("traffic_source", "web") + userId = b.GetUserId() + } + if userId == "" { + err := constant.AUTH_NOT_LOGIN + return &err + } + u, err := userLogic.GetUserById(b.logPoints, userId) + if err != nil { + b.logPoints.Warn("apikey for user invalid", err.Error()) + err := constant.AUTH_NOT_LOGIN + return &err + } + + if apiKeyEntity.Type == "user" && u.RoleID == baseLogic.ROLE_USER_UUID { + //控制台创建的个人apikey不能访问运营平台的openapi接口 + err := constant.PermissionDenyForObject + return &err + } + + if apiKeyEntity.Type == "user" && apiKeyEntity.Source != "operation" { + //个人apikey且不是在operation上创建的 + err := constant.PermissionDenyForObject + return &err + } + + //接口请求的控制台用户,镜像,机型等接口的写权限禁用 + if apiKeyEntity.Type == "user" && u.RoleID == baseLogic.ROLE_USER_UUID && b.logPoints.GetPoint("method").(string) != "GET" { + forbidUrl := []string{ + "/v1/devices", + "/v1/deviceTypes", + "v1/idcs", + "/v1/oss", + "/v1/images", + "/v1/raids", + "/v1/users", + "/v1/roles", + } + for _, pre := range forbidUrl { + if strings.HasPrefix(b.Ctx.Input.URI(), pre) { + b.logPoints.Warnf("api user request permission denied, userId:%s, url:%s", u.UserID, b.Ctx.Input.URI()) + err := constant.PermissionDenyForObject + return &err + } + } + } + + // 非amdin无运营平台role和users的权限 + if u.RoleID != baseLogic.ROLE_ADMIN_UUID { + if strings.HasPrefix(b.Ctx.Input.URI(), "/v1/roles") { + if !strings.HasPrefix(b.Ctx.Input.URI(), "/v1/roles/roleInfo/current") { + b.logPoints.Warn("role method for non-admin user invalid, userId:", u.UserID) + err := constant.PermissionDenyForObject + return &err + } + + } + + if strings.HasPrefix(b.Ctx.Input.URI(), "/v1/users") { + b.logPoints.Warn("role method for non-admin user invalid, userId:", u.UserID) + err := constant.PermissionDenyForObject + return &err + } + } + + fmt.Println("baseauth.username is", u.UserName) + fmt.Println("baseauth.user_id is", userId) + fmt.Println("baseauth.timezone is", u.Timezone) + fmt.Println("baseauth.language is", u.Language) + fmt.Println("language-header", b.logPoints.GetPoint("language").(string)) + b.logPoints.Point("userId", userId) + b.logPoints.Point("username", u.UserName) + b.logPoints.Point("userRole", u.RoleID) + if b.logPoints.GetPoint("language").(string) == "" { //页面上没有设置语言时,用用户的默认语言 + b.logPoints.Point("language", u.Language) + } + fmt.Println("language-final", b.logPoints.GetPoint("language").(string)) + b.logPoints.Point("timezone", u.Timezone) + + return nil +} + +func (b *BaseController) GetTraceID() string { + if b.Ctx.Request.Header["Traceid"] != nil { + return b.Ctx.Request.Header["Traceid"][0] + } + //生成随机字符串logid + logid := commonUtil.GenerateRandUuid() + b.Ctx.Request.Header["Traceid"] = []string{logid} + return logid +} + +func (b *BaseController) GetLanguage() string { + if b.Ctx.Request.Header["Bmplanguage"] != nil { + language := b.Ctx.Request.Header["Bmplanguage"][0] + return language + } + return "" +} + +func (b *BaseController) GetTimezone() string { + if b.Ctx.Request.Header["X-Bmp-Timezone"] != nil { + tz := b.Ctx.Request.Header["X-Bmp-Timezone"][0] + return tz + } + return "Asia/Shanghai" +} + +func (b *BaseController) GetUserId() string { + if b.Ctx.Request.Header["Bmpuserid"] != nil { + userId := b.Ctx.Request.Header["Bmpuserid"][0] + return userId + } + return "" +} +func (b *BaseController) GetUserName() string { + user, _ := userLogic.GetUserById(b.logPoints, b.GetUserId()) //报错 + if user != nil { + return user.UserName + } else { + return "" + } +} +func (b *BaseController) GetFields() (fields []string) { + // fields: col1,col2,entity.col3 + if v := b.GetString("fields"); v != "" { + fields = strings.Split(v, ",") + } + return +} + +func (b *BaseController) GetSortBy() (sortby []string) { + // sortby: col1,col2 + if v := b.GetString("sortby"); v != "" { + sortby = strings.Split(v, ",") + } + return +} + +func (b *BaseController) GetOrder() (order []string) { + // order: desc,asc + if v := b.GetString("order"); v != "" { + order = strings.Split(v, ",") + } + return +} + +// GetOffset 默认返回0 +func (b *BaseController) GetOffset() int64 { + if o := b.GetString("pageNumber"); o != "" { + if v, err := strconv.ParseInt(o, 10, 64); err == nil { + //第2页 每页10条 offset=10 + //第1页, 每页10条,offset=0 + if v > 0 { + return (v - 1) * b.GetLimit() + } + } + } + return 0 +} + +// GetOffset 默认返回10 +func (b *BaseController) GetLimit() int64 { + if l := b.GetString("pageSize"); l != "" { + if v, err := strconv.ParseInt(l, 10, 64); err == nil { + return v + } + } + return 20 +} + +func (b *BaseController) getPageNumber() int64 { + if l := b.GetString("pageNumber"); l != "" { + if v, err := strconv.ParseInt(l, 10, 64); err == nil { + return v + } + } + return 1 +} + +func (b *BaseController) getPageSize() int64 { + if l := b.GetString("pageSize"); l != "" { + if v, err := strconv.ParseInt(l, 10, 64); err == nil { + return v + } + } + if strings.HasPrefix(b.Ctx.Request.RequestURI, "/devices") { + return 10 + } + if strings.HasPrefix(b.Ctx.Request.RequestURI, "/instances") { + return 10 + } + if strings.HasPrefix(b.Ctx.Request.RequestURI, "/subnets") { + return 10 + } + return 20 +} + +func restfulResponseException(code int, status string, msg string) map[string]interface{} { + return map[string]interface{}{ + "error": map[string]interface{}{ + "code": code, + "status": status, + "message": msg, + }, + } +} diff --git a/bmp-openapi/controllers/commandController.go b/bmp-openapi/controllers/commandController.go new file mode 100644 index 0000000..ed7cad5 --- /dev/null +++ b/bmp-openapi/controllers/commandController.go @@ -0,0 +1,69 @@ +package controllers + +import ( + "encoding/json" + + commandLogic "coding.jd.com/aidc-bmp/bmp-openapi/logic/commandLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceController operations for Device +type CommandController struct { + BaseController +} + +func (c *CommandController) Query() { + // defer c.CatchException() + req := &requestTypes.QueryCommandsRequest{} + req.RequestId = c.GetString("request_id") //用户请求带过来的参数,不是header里面标识流量的request_id + req.Sn = c.GetString("sn") + req.InstanceId = c.GetString("instance_id") + data, count, err := commandLogic.Query(c.logPoints, req, c.pageable) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.QueryCommandsResult{ + Commands: data, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } + +} + +func (c *CommandController) CancelCommand() { + // defer c.CatchException() + req := &requestTypes.CancelCommandsRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if err := commandLogic.CancelCommand(c.logPoints, req.Sn); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +func (c *CommandController) RetryCommand() { + defer c.CatchException() + req := &requestTypes.RetryCommandRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := commandLogic.RetryCommand(c.logPoints, *req.OffsetCommandId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} diff --git a/bmp-openapi/controllers/deviceController.go b/bmp-openapi/controllers/deviceController.go new file mode 100644 index 0000000..3fad1a6 --- /dev/null +++ b/bmp-openapi/controllers/deviceController.go @@ -0,0 +1,385 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/deviceLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceController operations for Device +type DeviceController struct { + BaseController +} + +// swagger:route GET /devices device describeDevices +// +// DescribeDevices 获取设备列表 +// +// Responses: +// 200: describeDevices +// default: ErrorResponse + +func (c *DeviceController) DescribeDevices() { + defer c.CatchException() + param := requestTypes.QueryDevicesRequest{ + IDcID: c.GetString("idcId"), + Sn: c.GetString("sn"), + DeviceSeries: c.GetString("deviceSeries"), + DeviceTypeID: c.GetString("deviceTypeId"), + ManageStatus: c.GetString("manageStatus"), + + IloIP: c.GetString("iloIp"), + InstanceID: c.GetString("instanceId"), + InstanceName: c.GetString("instanceName"), + UserID: c.GetString("user_id"), + UserName: c.GetString("userName"), + IsAll: c.GetString("isAll"), + CollectStatus: c.GetString("collectStatus"), + } + + res, count, err := deviceLogic.QueryDevices(c.logPoints, param, c.pageable) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.DeviceList{ + Devices: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } +} + +// swagger:route GET /devices/{device_id} device describeDevice +// +// DescribeDevice 获取设备详情 +// +// Responses: +// 200: describeDevice +// default: ErrorResponse + +func (c *DeviceController) DescribeDevice() { + defer c.CatchException() + deviceId := c.Ctx.Input.Param(":device_id") + //id, err := strconv.ParseInt(idStr, 10, 64) + //if err != nil { + // c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + // return + //} + res, err := deviceLogic.GetById(c.logPoints, deviceId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.DeviceInfo{ + Device: res, + } +} + +// swagger:route POST /devices device createDevice +// +// CreateDevice 创建设备 +// +// Responses: +// 200: createDevice +// default: ErrorResponse + +func (c *DeviceController) CreateDevice() { + defer c.CatchException() + req := &requestTypes.CreateDevicesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("parse post body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + _, err := deviceLogic.Save(c.logPoints, *req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + //c.Res.Result = response.DeviceIds{ + // DeviceIds: deviceIds, + //} + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /devices/{device_id} device modifyDevice +// +// ModifyDevice 修改设备信息 +// +// Responses: +// 200: modifyDevice +// default: ErrorResponse + +func (c *DeviceController) ModifyDevice() { + defer c.CatchException() + req := &requestTypes.ModifyDevicesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("parse post body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := deviceLogic.ModifyDeviceDescription(c.logPoints, req, c.Ctx.Input.Param(":device_id")); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /devices/mount device mountDevice +// +// MountDevice 设备上架 +// Responses: +// 200: mountDevice +// default: ErrorResponse + +func (c *DeviceController) MountDevice() { + defer c.CatchException() + req := &requestTypes.MountDevicesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("parse post body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if err := deviceLogic.ModifyDevice(c.logPoints, req.DeviceID, baseLogic.PUTAWAY); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + //defer c.CatchException() + //req := &requestTypes.PutawayDevicesRequest{} + //if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + // c.logPoints.Warn("parse post body error:", err.Error()) + // c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + // return + //} + //req.Validate(c.logPoints) + //if err := deviceLogic.Putaway(c.logPoints, req.Sns); err != nil { + // c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + // return + //} + //c.Res.Result = response.CommonResponse{ + // Success: true, + //} +} + +// swagger:route PUT /devices/unmount device unMountDevice +// +// UnMountDevice 设备下架 +// +// Responses: +// 200: unMountDevice +// default: ErrorResponse + +func (c *DeviceController) UnMountDevice() { + defer c.CatchException() + req := &requestTypes.UnMountDevicesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("parse post body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if err := deviceLogic.ModifyDevice(c.logPoints, req.DeviceID, baseLogic.UNPUTAWAY); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route DELETE /devices/{device_id} device deleteDevice +// +// DeleteDevice 删除设备 +// Responses: +// 200: deleteDevice +// default: ErrorResponse + +func (c *DeviceController) DeleteDevice() { + defer c.CatchException() + //req := &requestTypes.DeleteDevicesRequest{} + //if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + // c.logPoints.Warn("parse post body error:", err.Error()) + // c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + // return + //} + //req.Validate(c.logPoints) + if err := deviceLogic.Delete(c.logPoints, c.Ctx.Input.Param(":device_id")); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /devices/{device_id}/remove device removeDevice +// +// DeleteDevice 移除设备 +// Responses: +// 200: removeDevice +// default: ErrorResponse + +func (c *DeviceController) RemoveDevice() { + defer c.CatchException() + + device_id := c.Ctx.Input.Param(":device_id") + if err := deviceLogic.RemoveDevice(c.logPoints, device_id); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route DELETE /devices/stock device describeDeviceStock +// DescribeDeviceStock 获取指定机型的设备库存 +// Responses: +// 200: describeDeviceStock +// default: ErrorResponse +func (c *DeviceController) DescribeDeviceStock() { + defer c.CatchException() + list := deviceLogic.GetAllDevices(c.logPoints, map[string]interface{}{ + "manage_status": baseLogic.PUTAWAY, + "device_type_id": c.GetString("deviceTypeId"), + }, []string{}, []string{}, []string{}) + c.Res.Result = response.DeviceStock{ + Stocks: len(list), + } +} + +// swagger:route POST /collect/collectDeviceInfo device collectDeviceInfo +// CollectDeviceInfo 采集设备信息 +// Responses: +// 200: collectDeviceInfo +// default: ErrorResponse +func (c *DeviceController) CollectDeviceInfo() { + defer c.CatchException() + req := &requestTypes.CollectDeviceInfoRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("parse post body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := deviceLogic.CollectDeviceInfo(c.logPoints, req); err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route GET /devices/{device_id}/disksDetail device describeDeviceDisks +// +// DescribeDeviceDisks 设备详情-磁盘 +// +// Responses: +// 200: describeDeviceDisks +// default: ErrorResponse + +func (c *DeviceController) DescribeDeviceDisks() { + defer c.CatchException() + deviceId := c.Ctx.Input.Param(":device_id") + res, err := deviceLogic.GetDeviceDisksById(c.logPoints, deviceId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route PUT /devices/disks/associateDisks device associateDeviceDisks +// +// AssociateDeviceDisks 设备关联磁盘 +// +// Responses: +// 200: associateDeviceDisks +// default: ErrorResponse + +func (c *DeviceController) AssociateDeviceDisks() { + defer c.CatchException() + req := &requestTypes.AssociateDeviceDisksRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("AssociateDeviceDisks parse post body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := deviceLogic.AssociateDeviceDisks(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route GET /devices/disks/describeAssociateDisks device getAssociatedDisks +// +// GetAssociatedDisks 获取设备已关联的磁盘 +// +// Responses: +// 200: getAssociatedDisks +// default: ErrorResponse +func (c *DeviceController) GetAssociatedDisks() { + defer c.CatchException() + req := &requestTypes.GetAssociatedDisksRequest{ + DeviceID: c.GetString("deviceId"), + VolumeID: c.GetString("volumeId"), + DeviceTypeID: c.GetString("deviceTypeId"), + } + req.Validate(c.logPoints) + res, err := deviceLogic.GetAssociatedDisks(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + c.Res.Result = res +} + +// AssociateDeviceType ... +// swagger:route PUT /devices/deviceType/associate device deviceAssociateDeviceType +// +// AssociateDeviceType 设备绑定机型 +// +// Responses: +// 200: deviceAssociateDeviceType +// default: ErrorResponse + +func (c *DeviceController) DeviceAssociateDeviceType() { + defer c.CatchException() + req := &requestTypes.DeviceAssociateDeviceTypeRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("AssociateDeviceType parse post body err:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := deviceLogic.DeviceAssociateDeviceType(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} diff --git a/bmp-openapi/controllers/deviceTypeController.go b/bmp-openapi/controllers/deviceTypeController.go new file mode 100644 index 0000000..bf53e41 --- /dev/null +++ b/bmp-openapi/controllers/deviceTypeController.go @@ -0,0 +1,315 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/deviceTypeLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type DeviceTypeController struct { + BaseController +} + +// swagger:route POST /deviceTypes deviceType createDeviceType +// +// CreateDeviceType 添加机型 +// Responses: +// 200: createDeviceType +// default: ErrorResponse + +func (c *DeviceTypeController) CreateDeviceType() { + defer c.CatchException() + req := &requestTypes.CreateDeviceTypeRequest{} + err := json.Unmarshal(c.Ctx.Input.RequestBody, req) + if err != nil { + c.logPoints.Warn("CreateDeviceType parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + uuid, err := deviceTypeLogic.Create(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.DeviceTypeId{ + DeviceTypeId: uuid, + } +} + +// swagger:route GET /deviceTypes deviceType describeDeviceTypes +// DescribeDeviceTypes 获取机型列表 +// Responses: +// 200: describeDeviceTypes +// default: ErrorResponse + +func (c *DeviceTypeController) DescribeDeviceTypes() { + defer c.CatchException() + req := &requestTypes.QueryDeviceTypesRequest{ + DeviceTypeID: c.GetString("deviceTypeId"), + DeviceType: c.GetString("deviceType"), + IdcID: c.GetString("idcId"), + Name: c.GetString("name"), + DeviceSeries: c.GetString("deviceSeries"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + //device_types, err := deviceTypeLogic.QueryByRequest(c.logPoints, req) + res, count, err := deviceTypeLogic.QueryDeviceTypes(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.DeviceTypeList{ + DeviceTypes: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } +} + +// swagger:route GET /deviceTypes/{device_type_id} deviceType describeDeviceType +// +// +// DescribeDeviceType 获取机型详情 +// +// Responses: +// 200: describeDeviceType +// default: ErrorResponse + +func (c *DeviceTypeController) DescribeDeviceType() { + defer c.CatchException() + req := &requestTypes.QueryDeviceTypesRequest{ + DeviceTypeID: c.Ctx.Input.Param(":device_type_id"), + } + req.Validate(c.logPoints) + res, err := deviceTypeLogic.QueryDeviceType(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.DeviceTypeInfo{ + DeviceType: res, + } +} + +// ModifyDeviceType ... +// swagger:route PUT /deviceTypes/{device_type_id} deviceType modifyDeviceType +// +// ModifyDeviceType 修改机型信息 +// +// Responses: +// 200: modifyDeviceType +// default: ErrorResponse + +func (c *DeviceTypeController) ModifyDeviceType() { + defer c.CatchException() + req := &requestTypes.ModifyDeviceTypeRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyDeviceType parse post body err:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := deviceTypeLogic.ModifyDeviceType(c.logPoints, req, c.Ctx.Input.Param(":device_type_id")); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// DeleteDeviceType ... +// swagger:route DELETE /deviceTypes/{device_type_id} deviceType deleteDeviceType +// +// DeleteDeviceType 删除机型 +// +// Responses: +// 200: deleteDeviceType +// default: ErrorResponse + +func (c *DeviceTypeController) DeleteDeviceType() { + defer c.CatchException() + deviceTypeID := c.Ctx.Input.Param(":device_type_id") + if deviceTypeID == "" { + c.SetErrorResponse(httpStatus.BAD_REQUEST, "deviceTypeId is not empty", errorCode.INTERNAL) + return + } + if err := deviceTypeLogic.DeleteDeviceType(c.logPoints, deviceTypeID); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// AssociatedImage ... +// swagger:route POST /deviceTypes/associatedImage deviceType associatedImage +// +// AssociatedImage 机型绑定镜像 +// +// Responses: +// 200: associatedImage +// default: ErrorResponse + +func (c *DeviceTypeController) AssociatedImage() { + defer c.CatchException() + req := &requestTypes.AssociateImageRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("AssociatedImage parse post body err:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := deviceTypeLogic.AssociatedImage(c.logPoints, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// DissociatedImage ... +// swagger:route DELETE /deviceTypes/dissociatedImage deviceType dissociatedImage +// +// DissociatedImage 机型解绑镜像 +// +// Responses: +// 200: dissociatedImage +// default: ErrorResponse + +func (c *DeviceTypeController) DissociatedImage() { + defer c.CatchException() + req := &requestTypes.DissociatedImageRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DissociatedImage parse post body err:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := deviceTypeLogic.DissociatedImage(c.logPoints, req, false); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route GET /deviceTypes/deviceTypeImage deviceType describeDeviceTypeImages +// +// QueryDeviceTypeImage 根据机型获取镜像 +// +// Responses: +// 200: describeDeviceTypeImages +// default: ErrorResponse + +func (c *DeviceTypeController) DescribeDeviceTypeImages() { + req := &requestTypes.QueryDeviceTypeImageRequest{ + DeviceTypeID: c.GetString("deviceTypeId"), + ImageID: c.GetString("imageId"), + Architecture: c.GetString("architecture"), + OsType: c.GetString("osType"), + + ImageName: c.GetString("imageName"), + Version: c.GetString("version"), + OsID: c.GetString("osId"), + //ImageIDs: strings.Split(c.GetString("imageIds"), ","), + Source: c.GetString("source"), + IsAll: c.GetString("isAll"), + } + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + res, count, err := deviceTypeLogic.QueryDeviceTypeImage(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ImageList{ + Images: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } +} + +// swagger:route GET /deviceTypes/deviceTypeRaid deviceType describeDeviceTypeRaids +// +// DescribeDeviceTypeRaids 根据机型获取raid +// +// Responses: +// 200: describeDeviceTypeRaids +// default: ErrorResponse + +func (c *DeviceTypeController) DescribeDeviceTypeRaids() { + //req := &requestTypes.QueryDeviceTypeRaidRequest{ + // DeviceTypeID: c.GetString("deviceTypeId"), + // VolumeType: c.GetString("volumeType"), + // RaidID: c.GetString("raidId"), + //} + //res, err := deviceTypeLogic.QueryDeviceTypeRaid(c.logPoints, req) + //if err != nil { + // c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + // return + //} + c.Res.Result = nil //废弃 +} + +// swagger:route GET /deviceTypes/deviceTypeImagePartition deviceType describeDeviceTypeImagePartitions +// +// QueryDeviceTypeImagePartition 根据机型,镜像,获取分区 +// +// Responses: +// 200: describeDeviceTypeImagePartitions +// default: ErrorResponse + +func (c *DeviceTypeController) DescribeDeviceTypeImagePartitions() { + req := &requestTypes.QueryDeviceTypeImagePartitionRequest{ + DeviceTypeID: c.GetString("deviceTypeId"), + ImageID: c.GetString("imageId"), + } + req.Validate(c.logPoints) + res, err := deviceTypeLogic.QueryDeviceTypeImagePartition(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route GET /deviceTypes/{device_type_id}/describeVolumes deviceType describeVolumesByDeviceType +// +// DescribeVolumesByDeviceType 根据机型获取volumes +// +// Responses: +// 200: describeVolumesByDeviceType +// default: ErrorResponse + +func (c *DeviceTypeController) DescribeVolumesByDeviceType() { + req := &requestTypes.DescribeVolumesByDeviceTypeRequest{ + DeviceTypeID: c.Ctx.Input.Param(":device_type_id"), + } + + req.Validate(c.logPoints) + res, err := deviceTypeLogic.DescribeVolumesByDeviceType(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-openapi/controllers/idcController.go b/bmp-openapi/controllers/idcController.go new file mode 100644 index 0000000..e6d482d --- /dev/null +++ b/bmp-openapi/controllers/idcController.go @@ -0,0 +1,191 @@ +package controllers + +import ( + "encoding/json" + "path" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/idcLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + + deviceLogic "coding.jd.com/aidc-bmp/bmp-openapi/logic/deviceLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type IdcController struct { + BaseController +} + +func (c *IdcController) CreateDevicesFromIdc() { + defer c.CatchException() + req := &requestTypes.CreateIdcDevicesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateDevicesFromIdc parse post body err:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.logPoints.Point("createDevicesFromIdc sns", req) + if err := deviceLogic.SaveDevicesFromIdc(c.logPoints, req); err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// ImportBms ... +func (c *IdcController) DeviceBatchImport() { + defer c.CatchException() + file, information, err := c.GetFile("file") + if err != nil { + c.logPoints.Warn("ImportBms getfile error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } + defer file.Close() //关闭上传的文件,否则出现临时文件不清除的情况 + filename := information.Filename + if !util.InArray(path.Ext(filename), []string{".xls", ".xlsx"}) { + c.SetErrorResponse(httpStatus.BAD_REQUEST, "only support excel", errorCode.INVALID_ARGUMENT) + return + } + if err := deviceLogic.ImportBms(c.logPoints, file, information.Size); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// CreateIdc ... +// swagger:route POST /idcs idc createIdc +// CreateIdc 创建idc(接口废弃,不对外开放) +// Responses: +// 200: createIdc +// default: ErrorResponse + +func (c *IdcController) CreateIdc() { + defer c.CatchException() + req := &requestTypes.CreateIdcRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateIdc parse post body err:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + c.logPoints.Point("createIdc req:", req) + idcId, err := idcLogic.CreateIdc(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = response.IdcID{ + IdcID: idcId, + } +} + +// ModifyIdc ... +// swagger:route PUT /idcs/{idc_id} idc modifyIdc +// ModifyIdc 修改idc信息 +// Responses: +// 200: modifyIdc +// default: ErrorResponse + +func (c *IdcController) ModifyIdc() { + defer c.CatchException() + req := &requestTypes.ModifyIdcRequest{} + idcId := c.Ctx.Input.Param(":idc_id") + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyIdc parse post body err:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := idcLogic.ModifyIdc(c.logPoints, req, idcId); err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// DescribeIdcs ... +// swagger:route GET /idcs idc describeIdcs +// DescribeIdcs 获取idc列表 +// Responses: +// 200: describeIdcs +// default: ErrorResponse + +func (c *IdcController) DescribeIdcs() { + defer c.CatchException() + req := &requestTypes.QueryIdcsRequest{ + Name: c.GetString("name"), + Level: c.GetString("level"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + c.logPoints.Point("QueryIdcsRequest req", req) + res, count, err := idcLogic.QueryIdcs(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.IdcList{ + Idcs: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } +} + +// swagger:route GET /idcs/{idc_id} idc describeIdc +// DescribeIdc 获取idc详情 +// Responses: +// 200: describeIdc +// default: ErrorResponse + +func (c *IdcController) DescribeIdc() { + defer c.CatchException() + req := &requestTypes.QueryIdcRequest{ + IDcID: c.Ctx.Input.Param(":idc_id"), + } + req.Validate(c.logPoints) + c.logPoints.Point("QueryIdcRequest req", req) + res, err := idcLogic.QueryIdcById(c.logPoints, req.IDcID) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route DELETE /idcs/{idc_id} idc deleteIdc +// DeleteIdc 删除idc +// Responses: +// 200: deleteIdc +// default: ErrorResponse + +func (c *IdcController) DeleteIdc() { + defer c.CatchException() + req := &requestTypes.QueryIdcRequest{ + IDcID: c.Ctx.Input.Param(":idc_id"), + } + req.Validate(c.logPoints) + if err := idcLogic.DeleteIdc(c.logPoints, req.IDcID); err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} diff --git a/bmp-openapi/controllers/imageController.go b/bmp-openapi/controllers/imageController.go new file mode 100644 index 0000000..e43d47a --- /dev/null +++ b/bmp-openapi/controllers/imageController.go @@ -0,0 +1,266 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/logic/deviceTypeLogic" + "encoding/json" + "fmt" + "regexp" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + + imageLogic "coding.jd.com/aidc-bmp/bmp-openapi/logic/imageLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + validation "git.jd.com/cps-golang/ironic-common/ironic/common/Validation" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type ImageController struct { + BaseController +} + +// CreateImage ... +// swagger:route POST /images image createImage +// CreateImage 添加镜像 +// Responses: +// 200: createImage +// default: ErrorResponse + +func (c *ImageController) CreateImage() { + defer c.CatchException() + req := &requestTypes.CreateImageRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("parse CreateImage body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + uuid, err := imageLogic.CreateImage(c.logPoints, req) //返回id + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ImageId{ + ImageId: uuid, + } +} + +// DescribeImages ... +// swagger:route GET /images image describeImages +// DescribeImages 获取镜像列表 +// Responses: +// 200: describeImages +// default: ErrorResponse + +func (c *ImageController) DescribeImages() { + defer c.CatchException() + req := &requestTypes.QueryImagesRequest{ + ImageID: c.GetString("imageId"), + DeviceTypeID: c.GetString("deviceTypeId"), + ImageName: c.GetString("imageName"), + Version: c.GetString("version"), + OsID: c.GetString("osId"), + ImageIDs: strings.Split(c.GetString("imageIds"), ","), + Source: c.GetString("source"), + Architecture: c.GetString("architecture"), + OsType: c.GetString("osType"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + res, count, err := imageLogic.DescribeImages(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ImageList{ + Images: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } +} + +// DescribeImage ... +// swagger:route GET /images/{image_id} image describeImage +// DescribeImage 获取镜像详情 +// Responses: +// 200: describeImage +// default: ErrorResponse + +func (c *ImageController) DescribeImage() { + defer c.CatchException() + image_id := c.Ctx.Input.Param(":image_id") + if match, err := regexp.MatchString(validation.REGEX_ID, image_id); !match { + if err != nil { + c.logPoints.Warn("DescribeImage regexp match source error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + } + //image, err := imageDao.GetImageByUuid(image_id) + res, err := imageLogic.GetByImageId(c.logPoints, image_id) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ImageInfo{ + Image: res, + } +} + +// ModifyImage ... +// swagger:route PUT /images/{image_id} image modifyImage +// ModifyImage 修改镜像(暂不启用) +// Responses: +// 200: modifyImage +// default: ErrorResponse + +func (c *ImageController) ModifyImage() { + defer c.CatchException() + imageId := c.Ctx.Input.Param(":image_id") + if match, err := regexp.MatchString(validation.REGEX_ID, imageId); !match { + c.logPoints.Warn("DescribeImage regexp match image_id false") + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req := &requestTypes.ModifyImageRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateImage parse post body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := imageLogic.ModifyImage(c.logPoints, req, imageId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// DeleteImage ... +// swagger:route DELETE /images/{image_id} image deleteImage +// DeleteImage 删除镜像 +// Responses: +// 200: deleteImage +// default: ErrorResponse + +func (c *ImageController) DeleteImage() { + defer c.CatchException() + imageId := c.Ctx.Input.Param(":image_id") + if match, err := regexp.MatchString(validation.REGEX_ID, imageId); !match { + if err != nil { + c.logPoints.Warn("DeleteImage regexp match source error:", err.Error()) + } + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if err := imageLogic.DeleteImage(c.logPoints, imageId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// DescribeImageDeviceTypes ... +// swagger:route GET /images/imageDeviceTypes image describeImageDeviceTypes +// DescribeImageDeviceTypes 查看镜像绑定的机型 +// Responses: +// 200: describeImageDeviceTypes +// default: ErrorResponse + +func (c *ImageController) DescribeImageDeviceTypes() { + defer c.CatchException() + req := &requestTypes.QueryImageDeviceTypesRequest{ + ImageID: c.GetString("imageId"), + Architecture: c.GetString("architecture"), + IsBind: c.GetString("isBind"), + IsAll: c.GetString("isAll"), + } + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + res, count, err := imageLogic.QueryImageDeviceTypes(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.DeviceTypeList{ + DeviceTypes: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } +} + +// swagger:route POST /images/associatedDeviceType image associatedDeviceType +// +// AssociatedDeviceType 镜像绑定机型 +// +// Responses: +// 200: associatedDeviceType +// default: ErrorResponse + +func (c *ImageController) AssociatedDeviceType() { + defer c.CatchException() + req := &requestTypes.AssociateDeviceTypeRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("AssociateDeviceType parse post body err:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + for _, deviceTypeId := range req.DeviceTypeIDs { + reqNew := &requestTypes.AssociateImageRequest{ + DeviceTypeID: deviceTypeId, + ImageIDs: []string{req.ImageID}, + } + fmt.Println(reqNew) + if err := deviceTypeLogic.AssociatedImage(c.logPoints, reqNew); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + } + + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route DELETE /images/dissociatedDeviceType image dissociatedDeviceType +// +// DissociatedDeviceType 镜像解绑机型 +// +// Responses: +// 200: dissociatedDeviceType +// default: ErrorResponse + +func (c *ImageController) DissociatedDeviceType() { + defer c.CatchException() + req := &requestTypes.DissociatedImageRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DissociatedImage parse post body err:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := deviceTypeLogic.DissociatedImage(c.logPoints, req, true); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} diff --git a/bmp-openapi/controllers/instanceController.go b/bmp-openapi/controllers/instanceController.go new file mode 100644 index 0000000..3d5965b --- /dev/null +++ b/bmp-openapi/controllers/instanceController.go @@ -0,0 +1,567 @@ +package controllers + +import ( + "encoding/json" + "errors" + "fmt" + "regexp" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/instanceLogic" + log "coding.jd.com/aidc-bmp/bmp_log" + + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + validation "git.jd.com/cps-golang/ironic-common/ironic/common/Validation" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type InstanceController struct { + BaseController +} + +func ValidateLocalUserProjectInstances(logger *log.Logger, projectId string, InstanceIds []string) error { + userId := logger.GetPoint("userId").(string) + query := map[string]interface{}{ + "user_id": userId, + "project_id": projectId, + "is_del": 0, + } + if len(InstanceIds) > 0 { + query["instance_id.in"] = InstanceIds + } + c, err := instanceLogic.GetInstanceCount(logger, query) + if err != nil { + return err + } + if c == 0 || c != int64(len(InstanceIds)) { + return errors.New("权限不够") + } + return nil +} + +// Instance ... +// swagger:route POST /project/instances instance createProjectInstance +// +// CreateProjectInstance 创建实例 +// Responses: +// 200: createProjectInstance +// default: ErrorResponse + +func (c *InstanceController) CreateProjectInstance() { + defer c.CatchException() + req := &requestTypes.CreateInstanceRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateInstance parse pInstancet body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + instanceIds, err := instanceLogic.CreateInstance(c.logPoints, *req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.InstanceIds{ + InstanceIds: instanceIds, + } +} + +// GetInstanceList ... +// swagger:route GET /project/instances instance describeProjectInstances +// +// DescribeProjectInstances 获取实例列表 +// Responses: +// 200: describeProjectInstances +// default: ErrorResponse + +func (c *InstanceController) DescribeProjectInstances() { + defer c.CatchException() + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.QueryInstancesRequest{ + InstanceName: c.GetString("instanceName"), + InstanceID: c.GetString("instanceId"), + Sn: c.GetString("sn"), + ProjectID: c.GetString("projectId"), + IdcID: c.GetString("idcId"), + DeviceTypeID: c.GetString("deviceTypeId"), + DeviceID: c.GetString("deviceId"), + Status: c.GetString("status"), + IloIP: c.GetString("ilo_ip"), + IPV4: c.GetString("ipv4"), + IPV6: c.GetString("ipv6"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + res, count, err := instanceLogic.GetInstanceList(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.InstanceList{ + Instances: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } + +} + +// DescribeInstance ... +// swagger:route GET /project/instances/{instance_id} instance describeProjectInstance +// DescribeProjectInstance 获取实例详情 +// +// Responses: +// 200: describeProjectInstance +// default: ErrorResponse + +func (c *InstanceController) DescribeProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + res, err := instanceLogic.GetInstanceById(c.logPoints, instanceId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.InstanceInfo{ + Instance: res, + } +} + +// ModifyInstance ... +// swagger:route PUT /project/instances/{instance_id} instance modifyProjectInstance +// ModifyProjectInstance 修改实例信息 +// +// Responses: +// 200: modifyProjectInstance +// default: ErrorResponse + +func (c *InstanceController) ModifyProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + req := &requestTypes.ModifyInstanceRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyInstance parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := instanceLogic.ModifyProjectInstance(c.logPoints, req, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// LockInstance ... +// swagger:route PUT /project/instances/{instance_id}/lock instance lockProjectInstance +// +// LockProjectInstance 锁定实例 +// Responses: +// 200: lockProjectInstance +// default: ErrorResponse + +func (c *InstanceController) LockProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + if err := instanceLogic.LockInstance(c.logPoints, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// LockInstance ... +// swagger:route PUT /project/instances/{instance_id}/unlock instance unLockProjectInstance +// +// UnLockProjectInstance 解锁实例 +// Responses: +// 200: unLockProjectInstance +// default: ErrorResponse + +func (c *InstanceController) UnLockProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + if err := instanceLogic.UnLockInstance(c.logPoints, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// StartInstance ... +// swagger:route PUT /project/instances/{instance_id}/start instance startProjectInstance +// +// StartProjectInstance 实例开机 +// Responses: +// 200: startProjectInstance +// default: ErrorResponse + +func (c *InstanceController) StartProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + if err := instanceLogic.StartInstance(c.logPoints, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// StopInstance ... +// swagger:route PUT /project/instances/{instance_id}/stop instance stopProjectInstance +// +// StopProjectInstance 实例关机 +// Responses: +// 200: stopProjectInstance +// default: ErrorResponse + +func (c *InstanceController) StopProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + if err := instanceLogic.StopInstance(c.logPoints, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// RestartInstance ... +// swagger:route PUT /project/instances/{instance_id}/restart instance restartProjectInstance +// +// RestartProjectInstance 实例重启 +// Responses: +// 200: restartProjectInstance +// default: ErrorResponse + +func (c *InstanceController) RestartProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + if err := instanceLogic.RestartInstance(c.logPoints, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// DeleteInstance ... +// swagger:route DELETE /project/instances/{instance_id} instance deleteProjectInstance +// +// DeleteProjectInstance 删除实例 +// Responses: +// 200: deleteProjectInstance +// default: ErrorResponse + +func (c *InstanceController) DeleteProjectInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + if err := instanceLogic.DeleteInstance(c.logPoints, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// ResetInstanceStatus ... +// swagger:route PUT /project/instances/{instance_id}/resetStatus instance resetInstanceStatus +// +// ResetInstanceStatus 重置实例状态 +// Responses: +// 200: resetInstanceStatus +// default: ErrorResponse +func (c *InstanceController) ResetInstanceStatus() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + if err := instanceLogic.ResetInstanceStatus(c.logPoints, instanceId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /project/instances/batch/instances:startInstances instance startInstances +// +// StartInstances 批量开机 +// Responses: +// 200: startInstances +// default: ErrorResponse +func (c *InstanceController) StartInstances() { + + defer c.CatchException() + instancesAndOperation := c.Ctx.Input.Param(":param") + if instancesAndOperation != "instances:startInstances" { + c.SetErrorResponse(httpStatus.BAD_REQUEST, fmt.Sprintf("url %s parse error", instancesAndOperation), errorCode.INVALID_ARGUMENT) + return + } + + req := requestTypes.StartInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + req.Validate(c.logPoints) + + if err := instanceLogic.StartInstances(c.logPoints, req.InstanceIds); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /project/instances/batch/instances:stopInstances instance stopInstances +// +// StartInstances 批量关机 +// Responses: +// 200: stopInstances +// default: ErrorResponse +func (c *InstanceController) StopInstances() { + c.logPoints.Warn("InstanceController.StopInstances comming", c.Ctx.Input.Param(":param"), string(c.Ctx.Input.RequestBody)) + defer c.CatchException() + instancesAndOperation := c.Ctx.Input.Param(":param") + if instancesAndOperation != "instances:stopInstances" { + c.SetErrorResponse(httpStatus.BAD_REQUEST, fmt.Sprintf("url %s parse error", instancesAndOperation), errorCode.INVALID_ARGUMENT) + return + } + req := requestTypes.StopInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + req.Validate(c.logPoints) + + if err := instanceLogic.StopInstances(c.logPoints, req.InstanceIds); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /project/instances/batch/instances:restartInstances instance restartInstances +// +// StartInstances 批量重启 +// Responses: +// 200: restartInstances +// default: ErrorResponse +func (c *InstanceController) RestartInstances() { + + defer c.CatchException() + instancesAndOperation := c.Ctx.Input.Param(":param") + if instancesAndOperation != "instances:restartInstances" { + c.SetErrorResponse(httpStatus.BAD_REQUEST, fmt.Sprintf("url %s parse error", instancesAndOperation), errorCode.INVALID_ARGUMENT) + return + } + req := requestTypes.RestartInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + req.Validate(c.logPoints) + + if err := instanceLogic.RestartInstances(c.logPoints, req.InstanceIds); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /project/instances/batch/instances:modifyInstances instance modifyInstances +// +// ModifyInstances 批量修改实例名称 +// Responses: +// 200: modifyInstances +// default: ErrorResponse +func (c *InstanceController) ModifyInstances() { + + defer c.CatchException() + instancesAndOperation := c.Ctx.Input.Param(":param") + if instancesAndOperation != "instances:modifyInstances" { + c.SetErrorResponse(httpStatus.BAD_REQUEST, fmt.Sprintf("url %s parse error", instancesAndOperation), errorCode.INVALID_ARGUMENT) + return + } + req := requestTypes.ModifyInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + req.Validate(c.logPoints) + + if err := instanceLogic.ModifyInstances(c.logPoints, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// DeleteInstances ... +// swagger:route DELETE /project/instances/batch/instances:deleteInstances instance deleteInstances +// +// DeleteInstances 批量删除实例 +// Responses: +// 200: deleteInstances +// default: ErrorResponse + +func (c *InstanceController) DeleteInstances() { + defer c.CatchException() + + defer c.CatchException() + instancesAndOperation := c.Ctx.Input.Param(":param") + if instancesAndOperation != "instances:deleteInstances" { + c.SetErrorResponse(httpStatus.BAD_REQUEST, fmt.Sprintf("url %s parse error", instancesAndOperation), errorCode.INVALID_ARGUMENT) + return + } + req := requestTypes.DeleteInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + req.Validate(c.logPoints) + + if err := instanceLogic.DeleteInstances(c.logPoints, req.InstanceIDs); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// ResetPasswd ... +// swagger:route PUT /project/instances/{instance_id}/resetpasswd instance resetProjectInstancePasswd +// +// ResetPasswd 重置密码 +// Responses: +// 200: resetProjectInstancePasswd +// default: ErrorResponse + +func (c *InstanceController) ResetPasswd() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + + req := requestTypes.ResetInstancePasswdRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + req.Validate(c.logPoints) + + if err := instanceLogic.ResetInstancePasswd(c.logPoints, instanceId, req.Password); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// StartInstance ... +// swagger:route PUT /project/instances/batch/instances:resetPasswd instance resetProjectInstancesPasswd +// +// ResetInstancesPasswd 批量重置密码 +// Responses: +// 200: resetProjectInstancesPasswd +// default: ErrorResponse + +func (c *InstanceController) ResetInstancesPasswd() { + defer c.CatchException() + + req := requestTypes.ResetInstancesPasswdRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + req.Validate(c.logPoints) + + if err := instanceLogic.ResetInstancesPasswd(c.logPoints, req.InstanceIDs, req.Password); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// ReinstallInstance ... +// swagger:route PUT /project/instances/{instance_id}/reinstallInstance instance reinstallProjectInstance +// +// ReinstallInstance 重装实例 +// Responses: +// 200: reinstallProjectInstance +// default: ErrorResponse +func (c *InstanceController) ReinstallInstance() { + defer c.CatchException() + instance_id := c.Ctx.Input.Param(":instance_id") + if match, err := regexp.MatchString(validation.REGEX_ID, instance_id); !match { + if err != nil { + c.logPoints.Warn("ReinstallInstance path error:", err.Error()) + } + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req := &requestTypes.ReinstallInstanceRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("parse post body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + if err := req.Validate(c.logPoints); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + if err := instanceLogic.ReinstallInstance(c.logPoints, instance_id, req); err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +func (c *InstanceController) QueryInstanceBySn() { + defer c.CatchException() + sn := c.GetString("sn") + res, err := instanceLogic.GetInstanceBySn(c.logPoints, sn) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.InstanceInfo{ + Instance: res, + } +} diff --git a/bmp-openapi/controllers/messageController.go b/bmp-openapi/controllers/messageController.go new file mode 100644 index 0000000..4c5d021 --- /dev/null +++ b/bmp-openapi/controllers/messageController.go @@ -0,0 +1,277 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/messageLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type MessageController struct { + BaseController +} + +// HasUnreadMessage ... +// swagger:route GET /messages/hasUnreadMessage message hasUnreadMessage +// +// HasUnreadMessage 获取有没有未读消息 +// +// Responses: +// 200: hasUnreadMessage +// default: ErrorResponse + +func (c *MessageController) HasUnreadMessage() { + defer c.CatchException() + + res, err := messageLogic.HasUnreadMessage(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.HasUnreadMessage{ + HasUnread: res, + } +} + +// GetMessageList ... +// swagger:route GET /messages message getMessageList +// +// GetMessageList 获取message列表(分页) +// +// Responses: +// 200: getMessageList +// default: ErrorResponse +func (c *MessageController) GetMessageList() { + defer c.CatchException() + + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + + req := &requestTypes.QueryMessagesRequest{ + IsAll: c.GetString("isAll"), + HasRead: c.GetString("hasRead"), + MessageType: c.GetString("messageType"), + MessageSubType: c.GetString("messageSubType"), + Detail: c.GetString("detail"), + } + req.Validate(c.logPoints) + + res, cnt, err := messageLogic.GetPageMessages(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.MessageList{ + Messages: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: cnt, + } +} + +// GetMessageStatistic ... +// swagger:route GET /messages/statistic message getMessageStatistic +// +// GetMessageStatistic 获取message总数和未读数 +// +// Responses: +// 200: getMessageStatistic +// default: ErrorResponse +func (c *MessageController) GetMessageStatistic() { + defer c.CatchException() + + total, unread, err := messageLogic.GetMessageStatistic(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = response.MessageStatistic{ + + TotalCount: total, + UnreadCount: unread, + } +} + +// ReadMessage ... +// swagger:route PUT /messages/doRead message readMessage +// +// ReadMessage 将消息设置为已读(可多条) +// +// Responses: +// 200: readMessage +// default: ErrorResponse +func (c *MessageController) ReadMessage() { + defer c.CatchException() + + req := &requestTypes.ReadMessagesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ReadMessage parse ReadMessagesRequest body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := messageLogic.ReadMessages(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// GetMessageById ... +// swagger:route GET /messages/getMessageById message getMessageById +// +// GetMessageById 获取消息详情,包括上一条/下一条的messageid +// +// Responses: +// 200: getMessageById +// default: ErrorResponse + +func (c *MessageController) GetMessageById() { + defer c.CatchException() + + req := &requestTypes.GetMessageByIdRequest{ + MessageID: c.GetString("messageId"), + } + req.Validate(c.logPoints) + msg, nextMsgId, prevMsgId, err := messageLogic.GetMessageById(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.MessageWithNextPrev{ + Message: msg, + NextMessageId: nextMsgId, + PrevMessageId: prevMsgId, + } +} + +// GetMessageTypes ... +// swagger:route GET /messages/getMessageTypes message getMessageTypes +// +// GetMessageTypes 获取消息类型/子类型 +// +// Responses: +// 200: getMessageTypes +// default: ErrorResponse + +func (c *MessageController) GetMessageTypes() { + defer c.CatchException() + + res := messageLogic.GetMessageTypes(c.logPoints) + + c.Res.Result = res +} + +// DeleteMessage ... +// swagger:route DELETE /messages/delete message deleteMessage +// +// DeleteMessage 删除消息(可多条) +// +// Responses: +// 200: deleteMessage +// default: ErrorResponse +func (c *MessageController) DeleteMessage() { + defer c.CatchException() + + req := &requestTypes.DeleteMessagesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DeleteMessage parse ReadMessagesRequest body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := messageLogic.DeleteMessages(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// DialMail ... +// swagger:route POST /messages/dialMail message dialMail +// +// DialMail 测试邮箱设置是否正确 +// +// Responses: +// 200: dialMail +// default: ErrorResponse +func (c *MessageController) DialMail() { + defer c.CatchException() + + req := &requestTypes.MailDialRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("MailDial parse MailDialRequest body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + err := messageLogic.DialMail(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// SaveIsPushMail ... +// swagger:route POST /messages/saveIsPushMail message saveIsPushMail +// +// SaveIsPushMail 保存邮箱是否通知的设置 +// +// Responses: +// 200: saveIsPushMail +// default: ErrorResponse +func (c *MessageController) SaveIsPushMail() { + defer c.CatchException() + + req := &requestTypes.SaveIsPushMailRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("SaveMail parse SaveIsPushMailRequest body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := messageLogic.SaveIsPushMail(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// MailDetail ... +// swagger:route GET /messages/mailDetail message mailDetail +// +// MailDetail 获取邮箱设置 +// +// Responses: +// 200: mailDetail +// default: ErrorResponse +func (c *MessageController) MailDetail() { + defer c.CatchException() + + res, err := messageLogic.GetMail(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-openapi/controllers/monitorAlertController.go b/bmp-openapi/controllers/monitorAlertController.go new file mode 100644 index 0000000..7ac55e4 --- /dev/null +++ b/bmp-openapi/controllers/monitorAlertController.go @@ -0,0 +1,103 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorAlertLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorAlertController 告警 +type MonitorAlertController struct { + BaseController +} + +// swagger:route GET /monitorAlert/describeAlert monitorAlert describeAlert +// +// DescribeAlert 告警详情 +// +// Responses: +// 200: describeAlert +// default: ErrorResponse +func (c *MonitorAlertController) DescribeAlert() { + defer c.CatchException() + req := request.DescribeAlertRequest{ + AlertID: c.GetString("alertId"), + } + req.Validate(c.logPoints) + res, err := monitorAlertLogic.DescribeAlert(c.logPoints, req.AlertID) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route GET /monitorAlert/describeAlerts monitorAlert describeAlerts +// +// DescribeAlerts 告警列表 +// +// Responses: +// 200: describeAlerts +// default: ErrorResponse +func (c *MonitorAlertController) DescribeAlerts() { + defer c.CatchException() + + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + + stime, _ := c.GetInt64("startTime") + etime, _ := c.GetInt64("endTime") + req := &request.DescribeAlertsRequest{ + IsAll: c.GetString("isAll"), + UserName: c.GetString("userName"), + UserID: c.GetString("userId"), + RuleName: c.GetString("ruleName"), + RuleID: c.GetString("ruleId"), + ResourceID: c.GetString("resourceId"), + StartTime: stime, + EndTime: etime, + } + req.Validate(c.logPoints) + + res, err := monitorAlertLogic.DescribeAlerts(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route DELETE /monitorAlert/deleteAlert monitorAlert deleteAlert +// +// DeleteAlert 删除告警 +// +// Responses: +// 200: deleteAlert +// default: ErrorResponse +func (c *MonitorAlertController) DeleteAlert() { + defer c.CatchException() + c.logPoints.Infof("DeleteAlert body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.DeleteAlertRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DeleteAlert parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorAlertLogic.DeleteAlert(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} diff --git a/bmp-openapi/controllers/monitorDataController.go b/bmp-openapi/controllers/monitorDataController.go new file mode 100644 index 0000000..cf3d49d --- /dev/null +++ b/bmp-openapi/controllers/monitorDataController.go @@ -0,0 +1,50 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorDataLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorDataController 读取监控数据 +type MonitorDataController struct { + BaseController +} + +// swagger:route GET /monitorData monitorData getMonitorData +// +// GetMonitorData 获取图表监控数据 +// +// Responses: +// 200: getMonitorData +// default: ErrorResponse +func (c *MonitorDataController) GetMonitorData() { + + stime, _ := c.GetInt64("startTime") + etime, _ := c.GetInt64("endTime") + ti, _ := c.GetInt("timeInterval") + lastManyTime, _ := c.GetInt("lastManyTime") + req := requestTypes.GetMonitorDataRequest{ + MetricName: c.GetString("metricName"), + InstanceID: c.GetString("instanceId"), + Device: c.GetString("device"), + StartTime: stime, + EndTime: etime, + LastManyTime: lastManyTime, + TimeInterval: ti, + DownSampleType: c.GetString("downSampleType"), + + IdcID: c.GetString("idcID"), + UserName: c.GetString("userName"), + } + req.Validate(c.logPoints) + + res, err := monitorDataLogic.GetMonitorData(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res + +} diff --git a/bmp-openapi/controllers/monitorProxyController.go b/bmp-openapi/controllers/monitorProxyController.go new file mode 100644 index 0000000..6b257aa --- /dev/null +++ b/bmp-openapi/controllers/monitorProxyController.go @@ -0,0 +1,55 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorProxyLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorProxyController 从monitorproxy服务读取数据,包括agent状态,tag列表等 +type MonitorProxyController struct { + BaseController +} + +// swagger:route GET /monitorProxy/desrcibeAgentStatus monitorProxy desrcibeAgentStatus +// +// DesrcibeAgentStatus 获取agent状态 +// +// Responses: +// 200: desrcibeAgentStatus +// default: ErrorResponse +func (c *MonitorProxyController) DesrcibeAgentStatus() { + req := &request.DesrcibeAgentStatusRequest{ + InstanceID: c.GetString("instanceId"), + } + req.Validate(c.logPoints) + res, err := monitorProxyLogic.DescribeAgentStatus(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res + +} + +// swagger:route GET /monitorProxy/desrcibeTags monitorProxy desrcibeTags +// +// DesrcibeAgentStatus 获取tag列表 +// +// Responses: +// 200: desrcibeTags +// default: ErrorResponse +func (c *MonitorProxyController) DesrcibeTags() { + req := &request.DesrcibeTagsRequest{ + InstanceID: c.GetString("instanceId"), + TagName: c.GetString("tagName"), + } + req.Validate(c.logPoints) + res, err := monitorProxyLogic.DescribeDeviceTags(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-openapi/controllers/monitorRuleController.go b/bmp-openapi/controllers/monitorRuleController.go new file mode 100644 index 0000000..be8a017 --- /dev/null +++ b/bmp-openapi/controllers/monitorRuleController.go @@ -0,0 +1,225 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorRuleLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorRuleController 告警规则 +type MonitorRuleController struct { + BaseController +} + +// swagger:route POST /monitorRule/addRule monitorRule addRule +// +// AddRule 添加规则 +// +// Responses: +// 200: addRule +// default: ErrorResponse +func (c *MonitorRuleController) AddRule() { + defer c.CatchException() + c.logPoints.Infof("AddRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.AddRuleRequest{} + + body := string(c.Ctx.Input.RequestBody) + //前端没有urlencode + // body, err := url.QueryUnescape(body) + // if err != nil { + // c.logPoints.Warn("AddRule.QueryUnescape error:", err.Error()) + // c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + // return + // } + + if err := json.Unmarshal([]byte(body), req); err != nil { + c.logPoints.Warn("AddRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.AddRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route GET /monitorRule/describeRule monitorRule describeRule +// +// DescribeRule 规则详情 +// +// Responses: +// 200: describeRule +// default: ErrorResponse +func (c *MonitorRuleController) DescribeRule() { + defer c.CatchException() + req := request.DescribeRuleRequest{ + RuleID: c.GetString("ruleId"), + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.DescribeRule(c.logPoints, req.RuleID) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route GET /monitorRule/describeRules monitorRule describeRules +// +// DescribeRules 规则列表 +// +// Responses: +// 200: describeRules +// default: ErrorResponse +func (c *MonitorRuleController) DescribeRules() { + defer c.CatchException() + + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + + s, err := c.GetInt("status") + if err != nil { + c.logPoints.Warnf("DescribeRules.status parse error:%s", err.Error()) + } + + req := &request.DescribeRulesRequest{ + IsAll: c.GetString("isAll"), + UserName: c.GetString("userName"), + UserID: c.GetString("userId"), + RuleName: c.GetString("ruleName"), + RuleID: c.GetString("ruleId"), + Status: s, + } + req.Validate(c.logPoints) + + res, err := monitorRuleLogic.DescribeRules(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route PUT /monitorRule/editRule monitorRule editRule +// +// EditRule 编辑规则 +// +// Responses: +// 200: editRule +// default: ErrorResponse +func (c *MonitorRuleController) EditRule() { + defer c.CatchException() + c.logPoints.Infof("EditRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.EditRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("EditRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.EditRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route PUT /monitorRule/enableRule monitorRule enableRule +// +// EnableRule 启用规则 +// +// Responses: +// 200: enableRule +// default: ErrorResponse +func (c *MonitorRuleController) EnableRule() { + defer c.CatchException() + c.logPoints.Infof("EnableRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.EnableRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("EnableRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.EnableRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route PUT /monitorRule/disableRule monitorRule disableRule +// +// DisableRule 禁用规则 +// +// Responses: +// 200: disableRule +// default: ErrorResponse +func (c *MonitorRuleController) DisableRule() { + defer c.CatchException() + c.logPoints.Infof("DisableRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.DisableRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DisableRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.DisableRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route DELETE /monitorRule/deleteRule monitorRule deleteRule +// +// DeleteRule 删除规则 +// +// Responses: +// 200: deleteRule +// default: ErrorResponse +func (c *MonitorRuleController) DeleteRule() { + defer c.CatchException() + c.logPoints.Infof("EnableRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.DeleteRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DeleteRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + res, err := monitorRuleLogic.DeleteRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} diff --git a/bmp-openapi/controllers/osController.go b/bmp-openapi/controllers/osController.go new file mode 100644 index 0000000..867d3c8 --- /dev/null +++ b/bmp-openapi/controllers/osController.go @@ -0,0 +1,144 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/osLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type OsController struct { + BaseController +} + +// CreateOs ... +// swagger:route POST /oss os createOS +// CreateOS 添加操作系统(暂不启用) +// +// Responses: +// 200: createOS +// default: ErrorResponse + +func (c *OsController) CreateOS() { + defer c.CatchException() + req := &requestTypes.CreateOSRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateOs parse post body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + uuid, err := osLogic.CreateOS(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.OsId{ + OsId: uuid, + } +} + +// DescribeOS ... +// swagger:route GET /oss/{os_id} os describeOS +// DescribeOS 获取os系统详情(暂不启用) +// +// Responses: +// 200: describeOS +// default: ErrorResponse + +func (c *OsController) DescribeOS() { + defer c.CatchException() + osId := c.Ctx.Input.Param(":os_id") + res, err := osLogic.GetByOsId(c.logPoints, osId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.OsInfo{ + Os: res, + } +} + +// ModifyOS ... +// swagger:route PUT /oss/{os_id} os modifyOS +// +// ModifyOS 修改os信息(暂不启用) +// Responses: +// 200: modifyOS +// default: ErrorResponse + +func (c *OsController) ModifyOS() { + defer c.CatchException() + os_id := c.Ctx.Input.Param(":os_id") + req := &requestTypes.ModifyOSRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyOS parse post body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := osLogic.ModifyOS(c.logPoints, req, os_id); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// DeleteOS ... +// swagger:route DELETE /oss/{os_id} os deleteOS +// +// DeleteOS 删除os(暂不启用) +// Responses: +// 200: deleteOS +// default: ErrorResponse + +func (c *OsController) DeleteOS() { + defer c.CatchException() + osId := c.Ctx.Input.Param(":os_id") + if err := osLogic.DeleteOS(c.logPoints, osId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// DescribeOSs ... +// swagger:route GET /oss os describeOSs +// DescribeOSs 获取os列表(暂不启用) +// +// Responses: +// 200: describeOSs +// default: ErrorResponse + +func (c *OsController) DescribeOSs() { + defer c.CatchException() + //ids := strings.Split(c.GetString("ids"), ",") + req := &requestTypes.QueryOssRequest{ + OsName: c.GetString("osName"), + OsType: c.GetString("osType"), + OsVersion: c.GetString("osVersion"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + res, err := osLogic.DescribeOSs(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.OsList{ + Oss: res, + //PageNumber: c.pageable.PageNumber, + //PageSize: c.pageable.PageSize, + //TotalCount: count, + } + +} diff --git a/bmp-openapi/controllers/projectController.go b/bmp-openapi/controllers/projectController.go new file mode 100644 index 0000000..ac75f2b --- /dev/null +++ b/bmp-openapi/controllers/projectController.go @@ -0,0 +1,198 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/projectLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// ProjectController operations for project +type ProjectController struct { + BaseController +} + +// CreateUserProject ... +// swagger:route POST /user/projects project createUserProject +// CreateUserProject 创建项目 +// +// Responses: +// 200: createUserProject +// default: ErrorResponse + +func (c *ProjectController) CreateUserProject() { + defer c.CatchException() + req := &requestTypes.CreateProjectRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateProject parse pProjectt body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + uuid, err := projectLogic.CreateProject(c.logPoints, req, "") + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ProjectId{ + ProjectId: uuid, + } +} + +// swagger:route GET /user/projects project describeUserProjects +// +// DescribeUserProjects 获取项目列表 +// Responses: +// 200: describeUserProjects +// default: ErrorResponse + +func (c *ProjectController) DescribeUserProjects() { + defer c.CatchException() + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.QueryProjectsRequest{ + ProjectName: c.GetString("projectName"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + res, count, err := projectLogic.GetProjectList(c.logPoints, *req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ProjectList{ + Projects: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } + +} + +// swagger:route GET /user/projects/{project_id} project describeUserProject +// +// DescribeUserProject 获取项目详情 +// Responses: +// 200: describeUserProject +// default: ErrorResponse + +func (c *ProjectController) DescribeUserProject() { + defer c.CatchException() + ProjectId := c.Ctx.Input.Param(":project_id") + res, err := projectLogic.GetProjectById(c.logPoints, ProjectId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ProjectInfo{ + Project: res, + } +} + +// swagger:route PUT /user/projects/{project_id} project modifyUserProject +// +// ModifyUserProject 修改项目信息 +// Responses: +// 200: modifyUserProject +// default: ErrorResponse + +func (c *ProjectController) ModifyUserProject() { + defer c.CatchException() + ProjectId := c.Ctx.Input.Param(":project_id") + req := &requestTypes.ModifyProjectRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyProject parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := projectLogic.ModifyProject(c.logPoints, req, ProjectId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// swagger:route DELETE /user/projects/{project_id} project deleteUserProject +// +// DeleteUserProject 删除项目 +// Responses: +// 200: deleteUserProject +// default: ErrorResponse + +func (c *ProjectController) DeleteUserProject() { + defer c.CatchException() + ProjectId := c.Ctx.Input.Param(":project_id") + if err := projectLogic.DeleteProject(c.logPoints, ProjectId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route PUT /user/projects/{project_id}/share project shareUserProject +// +// ShareUserProject 共享项目 +// Responses: +// 200: shareUserProject +// default: ErrorResponse + +func (c *ProjectController) ShareUserProject() { + defer c.CatchException() + + ProjectId := c.Ctx.Input.Param(":project_id") + req := &requestTypes.ShareProjectRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyProject parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := projectLogic.CreateShareProject(c.logPoints, ProjectId, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// swagger:route PUT /user/projects/{project_id}/cancelShare project cancelShareUserProject +// +// CancelShareUserProject 取消共享项目 +// Responses: +// 200: cancelShareUserProject +// default: ErrorResponse + +func (c *ProjectController) CancelShareUserProject() { + defer c.CatchException() + + ProjectId := c.Ctx.Input.Param(":project_id") + req := &requestTypes.ShareProjectRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyProject parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := projectLogic.CancelShareProject(c.logPoints, ProjectId, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} diff --git a/bmp-openapi/controllers/rabbitmqController.go b/bmp-openapi/controllers/rabbitmqController.go new file mode 100644 index 0000000..a85e8bf --- /dev/null +++ b/bmp-openapi/controllers/rabbitmqController.go @@ -0,0 +1,31 @@ +package controllers + +import ( + "time" + + util "coding.jd.com/aidc-bmp/bmp-openapi/util" +) + +// DeviceController operations for Device +type RabbitMqController struct { + BaseController +} + +// QueryDevices ... +// @router / [get] +func (c *RabbitMqController) Send() { + + rabbitmq := util.NewRabbitMQSimple("cn-north-1c") + rabbitmq.PublishSimple("Hello goFrame!" + time.Now().Format("2006-01-02 15:04:05")) + + return +} +func (c *RabbitMqController) Receive() { + + //util.Receive() + rabbitmq := util.NewRabbitMQSimple("cn-north-1c") + + rabbitmq.ConsumeSimple() + + return +} diff --git a/bmp-openapi/controllers/raidController.go b/bmp-openapi/controllers/raidController.go new file mode 100644 index 0000000..2640bba --- /dev/null +++ b/bmp-openapi/controllers/raidController.go @@ -0,0 +1,209 @@ +package controllers + +import ( + "encoding/json" + "regexp" + + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/raidLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + validation "git.jd.com/cps-golang/ironic-common/ironic/common/Validation" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// RaidController operations for raid +type RaidController struct { + BaseController +} + +// CreateRaid ... +// swagger:route POST /raids raid createRaid +// +// CreateRaid 创建raid(暂不启用) +// Responses: +// 200: createRaid +// default: ErrorResponse + +func (c *RaidController) CreateRaid() { + defer c.CatchException() + req := &requestTypes.CreateRaidRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateRaid parse post body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + uuid, err := raidLogic.CreateRaid(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.RaidId{ + RaidId: uuid, + } +} + +// swagger:route POST /raids/deviceTypeRaid raid createDeviceTypeRaid +// +// CreateDeviceTypeRaid ... 机型和raid关联(暂不启用) +// Responses: +// 200: createDeviceTypeRaid +// default: ErrorResponse + +func (c *RaidController) CreateDeviceTypeRaid() { + //defer c.CatchException() + //req := &requestTypes.CreateDeviceTypeRaidRequest{} + //if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + // c.logPoints.Warn("CreateDeviceTypeRaid parse post body error:", err.Error()) + // c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + // return + //} + //req.Validate(c.logPoints) + //if err := raidLogic.CreateDeviceTypeRaid(c.logPoints, req); err != nil { + // c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + // return + //} + c.Res.Result = response.CommonResponse{ + Success: false, + } + +} + +// swagger:route DELETE /raids/deviceTypeRaid raid deleteDeviceTypeRaid +// +// DeleteDeviceTypeRaid ... 机型和raid解绑(暂不启用) +// Responses: +// 200: deleteDeviceTypeRaid +// default: ErrorResponse + +func (c *RaidController) DeleteDeviceTypeRaid() { + //defer c.CatchException() + //req := &requestTypes.DeleteDeviceTypeRaidRequest{} + //if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + // c.logPoints.Warn("DeleteDeviceTypeRaidRequest parse post body error:", err.Error()) + // c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + // return + //} + //req.Validate(c.logPoints) + //if err := raidLogic.DeleteDeviceTypeRaid(c.logPoints, req); err != nil { + // c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + // return + //} + c.Res.Result = response.CommonResponse{ + Success: false, + } + +} + +// QueryRaidsAll ... +// swagger:route GET /raids raid describeRaids +// +// DescribeRaids 获取raid列表 +// Responses: +// 200: describeRaids +// default: ErrorResponse + +func (c *RaidController) DescribeRaids() { + defer c.CatchException() + + data, err := raidLogic.QueryRaidsAll(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.RaidList{ + Raids: data, + } +} + +// GetRaid ... +// swagger:route GET /raids/{raid_id} raid describeRaid +// +// DescribeRaid 获取raid详情 +// Responses: +// 200: describeRaid +// default: ErrorResponse + +func (c *RaidController) DescribeRaid() { + defer c.CatchException() + raidId := c.Ctx.Input.Param(":raid_id") + if match, err := regexp.MatchString(validation.REGEX_ID, raidId); !match { + if err != nil { + c.logPoints.Warn("CreateImage validate volume_type error:", err.Error()) + } + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + raid, err := raidLogic.GetByRaidId(c.logPoints, raidId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = raid + +} + +// ModifyRaid ... +// swagger:route PUT /raids/{raid_id} raid modifyRaid +// ModifyRaid 修改raid信息(暂不启用) +// +// Responses: +// 200: modifyRaid +// default: ErrorResponse + +func (c *RaidController) ModifyRaid() { + defer c.CatchException() + + raidId := c.Ctx.Input.Param(":raid_id") + if match, err := regexp.MatchString(validation.REGEX_ID, raidId); !match { + if err != nil { + c.logPoints.Warn("CreateImage validate volume_type error:", err.Error()) + } + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req := &requestTypes.ModifyRaidRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyRaid parse post body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := raidLogic.ModifyRaid(c.logPoints, req, raidId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// DeleteRaid ... +// swagger:route DELETE /raids/{raid_id} raid deleteRaid +// +// DeleteRaid 删除raid(暂不启用) +// Responses: +// 200: deleteRaid +// default: ErrorResponse + +func (c *RaidController) DeleteRaid() { + defer c.CatchException() + raid_id := c.Ctx.Input.Param(":raid_id") + if match, err := regexp.MatchString(validation.REGEX_ID, raid_id); !match { + if err != nil { + c.logPoints.Warn("CreateImage validate volume_type error:", err.Error()) + } + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if err := raidLogic.DeleteRaid(c.logPoints, raid_id); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} diff --git a/bmp-openapi/controllers/resourceController.go b/bmp-openapi/controllers/resourceController.go new file mode 100644 index 0000000..5cf4fa1 --- /dev/null +++ b/bmp-openapi/controllers/resourceController.go @@ -0,0 +1,45 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/logic/resourceLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +type ResourceController struct { + BaseController +} + +// swagger:route GET /resources resource describeResources +// +// DescribeResources 根据某个字段值精确查询对应的资源列表(如根据imageName查询镜像列表,根据idcName查询机房列表) +// +// Responses: +// 200: describeResources +// default: ErrorResponse +func (c *ResourceController) DescribeResources() { + defer c.CatchException() + req := &requestTypes.QueryResourcesRequest{ + Name: c.GetString("name"), + DeviceType: c.GetString("deviceType"), + ImageName: c.GetString("imageName"), + UserName: c.GetString("userName"), + } + count, err := resourceLogic.DescribeResources(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + if count > 0 { + c.Res.Result = response.CommonResponse{ + Success: true, + } + } else { + c.Res.Result = response.CommonResponse{ + Success: false, + } + } + +} diff --git a/bmp-openapi/controllers/roleController.go b/bmp-openapi/controllers/roleController.go new file mode 100644 index 0000000..681d4ce --- /dev/null +++ b/bmp-openapi/controllers/roleController.go @@ -0,0 +1,166 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/roleLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// RoleController operations for role +type RoleController struct { + BaseController +} + +// CreateRole ... +// swagger:route POST /roles role createRole +// +// CreateRole 创建角色(暂不启用) +// Responses: +// 200: createRole +// default: ErrorResponse + +func (c *RoleController) CreateRole() { + defer c.CatchException() + req := &requestTypes.CreateRoleRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateRole parse pRolet body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + uuid, err := roleLogic.CreateRole(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.RoleId{ + RoleId: uuid, + } +} + +// GetRoleList ... +// swagger:route GET /roles role describeRoles +// DescribeRoles 获取角色列表 +// +// Responses: +// 200: describeRoles +// default: ErrorResponse + +func (c *RoleController) DescribeRoles() { + defer c.CatchException() + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.QueryRolesRequest{ + //RoleName: c.GetString("roleName"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + res, count, err := roleLogic.GetRoleList(c.logPoints, *req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.RoleList{ + Roles: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } + +} + +// DescribeRole ... +// swagger:route GET /roles/{role_id} role describeRole +// +// DescribeRole 获取角色详情 +// Responses: +// 200: describeRole +// default: ErrorResponse + +func (c *RoleController) DescribeRole() { + defer c.CatchException() + roleId := c.Ctx.Input.Param(":role_id") + res, err := roleLogic.GetRoleById(c.logPoints, roleId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.RoleInfo{ + Role: res, + } +} + +// ModifyRole ... +// swagger:route PUT /roles/{role_id} role modifyRole +// +// ModifyRole 修改角色信息(暂不启用) +// Responses: +// 200: modifyRole +// default: ErrorResponse + +func (c *RoleController) ModifyRole() { + defer c.CatchException() + roleId := c.Ctx.Input.Param(":role_id") + req := &requestTypes.ModifyRoleRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyRole parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + //req.Validate(c.logPoints) + if err := roleLogic.ModifyRole(c.logPoints, req, roleId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// DeleteRole ... +// swagger:route DELETE /roles/{role_id} role deleteRole +// +// DeleteRole 删除角色(暂不启用) +// Responses: +// 200: deleteRole +// default: ErrorResponse + +func (c *RoleController) DeleteRole() { + defer c.CatchException() + roleId := c.Ctx.Input.Param(":role_id") + if err := roleLogic.DeleteRole(c.logPoints, roleId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// swagger:route GET /roles/roleInfo/current role currentRole +// +// CurrentRole 获取当前登录用户的角色 +// Responses: +// 200: currentRole +// default: ErrorResponse + +func (c *RoleController) CurrentRole() { + defer c.CatchException() + + res, err := roleLogic.CurrentRole(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.RoleInfo{ + Role: res, + } +} diff --git a/bmp-openapi/controllers/sshkeyController.go b/bmp-openapi/controllers/sshkeyController.go new file mode 100644 index 0000000..7320717 --- /dev/null +++ b/bmp-openapi/controllers/sshkeyController.go @@ -0,0 +1,168 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/sshkeyLogic" + + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// SshkeyController operations for sshkey +type SshkeyController struct { + BaseController +} + +// CreateSshkey ... +// swagger:route POST /user/sshkeys sshkey createUserSshkey +// +// CreateUserSshkey 创建个人sshkey +// Responses: +// 200: createUserSshkey +// default: ErrorResponse + +func (c *SshkeyController) CreateUserSshkey() { + defer c.CatchException() + req := &requestTypes.CreateSshkeyRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateSshkey parse pSshkeyt body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + uuid, err := sshkeyLogic.CreateSshkey(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.SshkeyId{ + SshkeyId: uuid, + } +} + +// QueryBySshkeyIds ... +// swagger:route GET /user/sshkeys sshkey describeUserSshKeys +// +// DescribeUserSshKeys 获取个人sshkey列表 +// Responses: +// 200: describeUserSshKeys +// default: ErrorResponse + +func (c *SshkeyController) DescribeUserSshKeys() { + defer c.CatchException() + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.QuerySshkeysRequest{ + Name: c.GetString("name"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + res, count, err := sshkeyLogic.GetSshkeyList(c.logPoints, *req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.SshkeyList{ + Sshkeys: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } + +} + +// GetInstancesBySshkey ... +// swagger:route GET /user/sshkeys/instances/{sshkey_id} sshkey getInstancesBySshkey +// GetInstancesBySshkey 根据sshkey获取实例列表 +// +// Responses: +// 200: getInstancesBySshkey +// default: ErrorResponse + +func (c *SshkeyController) GetInstancesBySshkey() { + defer c.CatchException() + //req := &requestTypes.QueryInstancesSshkeyRequest{ + // SshkeyId: c.Ctx.Input.Param(":sshkey_id"), + //} + //req.Validate(c.logPoints) + ids := sshkeyLogic.GetInstancesBySshkey(c.logPoints, c.Ctx.Input.Param(":sshkey_id")) + c.Res.Result = response.InstancesSshkeyInfoResponse{ + InstanceIds: ids, + } + +} + +// DescribeSshkey ... +// swagger:route GET /user/sshkeys/{sshkey_id} sshkey describeUserSshKey +// +// DescribeUserSshKey 获取sshkey详情 +// Responses: +// 200: describeUserSshKey +// default: ErrorResponse + +func (c *SshkeyController) DescribeUserSshKey() { + defer c.CatchException() + sshkeyId := c.Ctx.Input.Param(":sshkey_id") + res, err := sshkeyLogic.GetSshkeyById(c.logPoints, sshkeyId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.SshkeyInfo{ + Sshkey: res, + } +} + +// ModifySshkey ... +// swagger:route PUT /user/sshkeys/{sshkey_id} sshkey modifyUserSshkey +// +// ModifyUserSshkey 修改sshkey +// Responses: +// 200: modifyUserSshkey +// default: ErrorResponse + +func (c *SshkeyController) ModifyUserSshkey() { + defer c.CatchException() + sshkeyId := c.Ctx.Input.Param(":sshkey_id") + req := &requestTypes.ModifySshkeyRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifySshkey parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := sshkeyLogic.ModifySshkey(c.logPoints, req, sshkeyId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// DeleteSshkey ... +// swagger:route DELETE /user/sshkeys/{sshkey_id} sshkey deleteUserSshkey +// DeleteUserSshkey 删除sshkey +// +// Responses: +// 200: deleteUserSshkey +// default: ErrorResponse + +func (c *SshkeyController) DeleteUserSshkey() { + defer c.CatchException() + sshkeyId := c.Ctx.Input.Param(":sshkey_id") + if err := sshkeyLogic.DeleteSshkey(c.logPoints, sshkeyId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} diff --git a/bmp-openapi/controllers/userController.go b/bmp-openapi/controllers/userController.go new file mode 100644 index 0000000..402c054 --- /dev/null +++ b/bmp-openapi/controllers/userController.go @@ -0,0 +1,264 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/userLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type UserController struct { + BaseController +} + +// CreateUser ... +// swagger:route POST /users user createUser +// +// CreateUser 创建用户 +// +// Responses: +// 200: createUser +// default: ErrorResponse + +func (c *UserController) CreateUser() { + defer c.CatchException() + req := &requestTypes.CreateUserRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateUser parse pUsert body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + uuid, err := userLogic.CreateUser(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.UserId{ + UserId: uuid, + } +} + +// swagger:route GET /users user describeUsers +// DescribeUsers 获取用户列表 +// Responses: +// 200: describeUsers +// default: ErrorResponse + +func (c *UserController) DescribeUsers() { + defer c.CatchException() + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.QueryUsersRequest{ + UserName: c.GetString("userName"), + RoleID: c.GetString("roleId"), + DefaultProjectID: c.GetString("defaultProjectId"), + IsAll: c.GetString("isAll"), + } + req.Validate(c.logPoints) + res, count, err := userLogic.GetUserList(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.UserList{ + Users: res, + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + TotalCount: count, + } + +} + +// swagger:route GET /users/{user_id} user describeUser +// DescribeUser 获取用户详情 +// Responses: +// 200: describeUser +// default: ErrorResponse + +func (c *UserController) DescribeUser() { + defer c.CatchException() + userId := c.Ctx.Input.Param(":user_id") + res, err := userLogic.GetUserById(c.logPoints, userId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.UserInfo{ + User: res, + } +} + +// GetUserByName ... +// swagger:route GET /users/getUserByName user describeUserByName +// DescribeUserByName 根据用户名获取用户详情 +// Responses: +// 200: describeUserByName +// default: ErrorResponse +func (c *UserController) DescribeUserByName() { + defer c.CatchException() + req := &requestTypes.GetUserByNameRequest{ + UserName: c.GetString("userName"), + } + req.Validate(c.logPoints) + + res, err := userLogic.GetUserByName(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.UserInfo{ + User: res, + } +} + +// ModifyUser ... +// swagger:route PUT /users/{user_id} user modifyUser +// ModifyUser 修改用户信息 +// Responses: +// 200: modifyUser +// default: ErrorResponse + +func (c *UserController) ModifyUser() { + defer c.CatchException() + userId := c.Ctx.Input.Param(":user_id") + req := &requestTypes.ModifyUserRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyUser parse pUsert body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := userLogic.ModifyUser(c.logPoints, req, userId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// DeleteUser ... +// swagger:route DELETE /users/{user_id} user deleteUser +// DeleteUser 删除用户 +// Responses: +// 200: deleteUser +// default: ErrorResponse + +func (c *UserController) DeleteUser() { + defer c.CatchException() + userId := c.Ctx.Input.Param(":user_id") + if err := userLogic.DeleteUser(c.logPoints, userId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// VerifyUser ... +// swagger:route POST /users/verify user verifyUser +// +// VerifyUser 鉴定用户 +// +// Responses: +// 200: verifyUser +// default: ErrorResponse + +func (c *UserController) VerifyUser() { + defer c.CatchException() + req := &requestTypes.VerifyUserRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateUser parse pUsert body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + isTrue := userLogic.VerifyUser(c.logPoints, req) + + c.Res.Result = response.CommonResponse{ + Success: isTrue, + } +} + +// DescribeLocalUser ... +// swagger:route GET /local/users user describeLocalUser +// DescribeLocalUser 控制台获取用户详情 +// Responses: +// 200: describeLocalUser +// default: ErrorResponse + +func (c *UserController) DescribeLocalUser() { + defer c.CatchException() + userId := c.logPoints.GetPoint("userId").(string) + res, err := userLogic.GetUserById(c.logPoints, userId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + resp := response.UserInfo{ + User: res, + } + c.Res.Result = resp +} + +// swagger:route PUT /local/users user modifyLocalUser +// +// ModifyLocalUser 控制台修改除密码外的个人信息 +// Responses: +// 200: modifyLocalUser +// default: ErrorResponse + +func (c *UserController) ModifyLocalUser() { + defer c.CatchException() + req := &requestTypes.ModifyLocalUserRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyUser parse pUsert body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := userLogic.ModifyLocalUser(c.logPoints, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} + +// swagger:route PUT /local/users/password user modifyLocalUserPassword +// +// ModifyLocalUserPassword 控制台修改个人密码 +// Responses: +// 200: modifyLocalUserPassword +// default: ErrorResponse + +func (c *UserController) ModifyLocalUserPassword() { + defer c.CatchException() + req := &requestTypes.ModifyUserPasswordRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyLocalUserPassword parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req.Validate(c.logPoints) + if err := userLogic.ModifyUserPassword(c.logPoints, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } + +} diff --git a/bmp-openapi/dao/CpsLogContentCollectionDao/CpsLogContentCollectionDao.go b/bmp-openapi/dao/CpsLogContentCollectionDao/CpsLogContentCollectionDao.go new file mode 100644 index 0000000..96bd1ff --- /dev/null +++ b/bmp-openapi/dao/CpsLogContentCollectionDao/CpsLogContentCollectionDao.go @@ -0,0 +1,39 @@ +package CpsLogContentCollectionDao + +import ( + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// CpsLogContentCollection [...] +type CpsLogContentCollection struct { + ID int `gorm:"primary_key;column:id;type:int(32) unsigned;not null" json:"-"` // ID + Content string `gorm:"column:content;type:varchar(256);not null" json:"content"` + FaultConfID int `gorm:"index:rule_id_idx;column:fault_conf_id;type:int(32) unsigned;not null" json:"fault_conf_id"` + IsDel bool `gorm:"index:idx_isdel;column:is_del;type:tinyint(1);not null" json:"is_del"` // : 0,; 1, + Sn string `gorm:"index:sn_idx;column:sn;type:varchar(32);not null" json:"sn"` // sn + Count uint32 `gorm:"column:count;type:int(32) unsigned;not null" json:"count"` // count + Level string `gorm:"index:level_idx;column:level;type:varchar(16);not null" json:"level"` + EventTime time.Time `gorm:"column:event_time;type:timestamp" json:"event_time"` + CollectTime time.Time `gorm:"column:collect_time;type:timestamp" json:"collect_time"` + UpdateTime time.Time `gorm:"column:update_time;type:timestamp" json:"update_time"` +} + +func (t *CpsLogContentCollection) TableName() string { + return "cps_log_content_collection" +} + +func UpdateCpsLogContentCollections(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, CpsLogContentCollection{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return + +} diff --git a/bmp-openapi/dao/CpsLogItemsDao/CpsLogItemsDao.go b/bmp-openapi/dao/CpsLogItemsDao/CpsLogItemsDao.go new file mode 100644 index 0000000..085a063 --- /dev/null +++ b/bmp-openapi/dao/CpsLogItemsDao/CpsLogItemsDao.go @@ -0,0 +1,36 @@ +package CpsLogItemsDao + +import ( + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// CpsLogItems [...] +type CpsLogItems struct { + ID uint32 `gorm:"primary_key;column:id;type:int(32) unsigned;not null" json:"-"` // ID + CollectionID uint32 `gorm:"index:collection_id_idx;column:collection_id;type:int(32) unsigned;not null" json:"collection_id"` // id + CollectTime time.Time `gorm:"column:collect_time;type:timestamp" json:"collect_time"` + EventTime time.Time `gorm:"column:event_time;type:timestamp" json:"event_time"` + IsDealed bool `gorm:"index:is_dealed_idx;column:is_dealed;type:tinyint(1);not null" json:"is_dealed"` // : 0,, 1, + IsDel bool `gorm:"index:idx_isdel;column:is_del;type:tinyint(1);not null" json:"is_del"` // : 0,; 1, + Sn string `gorm:"index:sn_idx;column:sn;type:varchar(32);not null" json:"sn"` // sn +} + +func (t *CpsLogItems) TableName() string { + return "cps_log_items" +} + +func UpdateCpsLogItemss(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, CpsLogItems{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return + +} diff --git a/bmp-openapi/dao/apikeyDao/apikeyDao.go b/bmp-openapi/dao/apikeyDao/apikeyDao.go new file mode 100644 index 0000000..d5d064f --- /dev/null +++ b/bmp-openapi/dao/apikeyDao/apikeyDao.go @@ -0,0 +1,124 @@ +package apikeyDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +// Apikey Apikey +type Apikey struct { + ID int `gorm:"primaryKey;column:id" json:"-"` + ApikeyID string `gorm:"column:apikey_id" json:"apikeyId"` // 秘钥对UUID + Name string `gorm:"column:name" json:"name"` // 秘钥对名称 + ReadOnly int8 `gorm:"column:read_only" json:"readOnly"` // 是否支持只读,read_only =1 的时候说明这个key是只读key,不能访问写方法。 + Token string `gorm:"column:token" json:"token"` // 32位字符令牌 + Type string `gorm:"column:type" json:"type"` // Token类型system/user + UserID string `gorm:"column:user_id" json:"userId"` // 所属用户 + Source string `gorm:"column:source" json:"source"` // apikey是通过console创建的还是通过operation创建的 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Apikey) TableName() string { + return "apikey" +} + +// AddApikey insert a new Apikey into database and returns +// last inserted Id on success. +func AddApikey(logger *log.Logger, m *Apikey) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetApikeyById retrieves Apikey by Id. Returns error if +// Id doesn't exist +func GetApikeyById(logger *log.Logger, ApikeyId string) (v *Apikey, err error) { + v = &Apikey{} + err = dao.Where(logger, dao.IronicRdb, "apikey_id = ? and is_del = 0", ApikeyId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetApikeyByToken(logger *log.Logger, token string) (v *Apikey, err error) { + v = &Apikey{} + err = dao.Where(logger, dao.IronicRdb, "token = ? and is_del = 0", token).Take(v).Error + if err == gorm.ErrRecordNotFound { + return nil, nil + } + if err != nil { + return nil, err + } + + return v, nil +} + +// GetApikeyByUuid retrieves Apikey by Uuid. Returns error if +// Id doesn't exist +func GetApikeyCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Apikey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAllApikey retrieves all Apikey matches certain condition. Returns empty list if +// no records exist +func GetAllApikey(logger *log.Logger, query map[string]interface{}) (ml []*Apikey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Apikey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiApikey retrieves all Apikey matches certain condition. Returns empty list if +// no records exist +func GetMultiApikey(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Apikey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Apikey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateApikey updates Apikey by Id and returns error if +// the record to be updated doesn't exist +func UpdateApikeyById(logger *log.Logger, m *Apikey) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Apikey{}).Where("apikey_id = ?", m.ApikeyID).Updates(m).Error +} diff --git a/bmp-openapi/dao/auditLogsDao/auditLogsDao.go b/bmp-openapi/dao/auditLogsDao/auditLogsDao.go new file mode 100644 index 0000000..01abf22 --- /dev/null +++ b/bmp-openapi/dao/auditLogsDao/auditLogsDao.go @@ -0,0 +1,155 @@ +package auditLogsDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// 操作日志 +type AuditLogs struct { + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + Logid string `gorm:"column:logid;type:varchar(255);not null" json:"logid"` // log uuid + Sn string `gorm:"index:i_sn;column:sn;type:varchar(255);not null" json:"sn"` + DeviceID string `gorm:"index:i_device_id;column:device_id;type:varchar(255);not null" json:"device_id"` + InstanceID string `gorm:"index:i_instance_id;column:instance_id;type:varchar(255);not null" json:"instance_id"` + Operation string `gorm:"index:i_operation;column:operation;type:varchar(255);not null" json:"operation"` // action + OperateUserID string `gorm:"column:operate_user_id;type:varchar(255);not null" json:"operate_user_id"` // user_id + OperateUserName string `gorm:"column:operate_user_name;type:varchar(255);not null" json:"operate_user_name"` // user_name + Result string `gorm:"column:result;type:varchar(255);not null" json:"result"` // success/fail + FailReason string `gorm:"column:fail_reason;type:varchar(255);not null" json:"fail_reason"` // reason for fail // 完成时间戳 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 +} + +//var db *gorm.DB = dao.IronicRdb + +func (t *AuditLogs) TableName() string { + return "audit_logs" +} + +// AddCommand insert a new Command into database and returns +// last inserted Id on success. +func AddAuditLogs(logger *log.Logger, m *AuditLogs) (id int64, err error) { + m.CreatedTime = int(time.Now().Unix()) + m.UpdatedTime = int(time.Now().Unix()) + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetCommandById retrieves Command by Id. Returns error if +// Id doesn't exist +func GetAuditLogsById(logger *log.Logger, id int64) (v *AuditLogs, err error) { + v = &AuditLogs{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetCommandById retrieves Command by parentId. Returns error if +// Id doesn't exist +// GetCommandById retrieves Command by parentId. Returns error if +// Id doesn't exist +func GetAuditLogsByUUId(logger *log.Logger, uuid string) (v *AuditLogs, err error) { + v = &AuditLogs{} + err = dao.Where(logger, dao.IronicRdb, "logid = ? and is_del = 0", uuid).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetAuditLogsCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + db, err := dao.WhereBuild(dao.Model(logger, dao.IronicRdb, AuditLogs{}), query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} + +func GetAllAuditLogs(logger *log.Logger, query map[string]interface{}) (ml []*AuditLogs, err error) { + g := dao.Model(logger, dao.IronicRdb, AuditLogs{}) + g, err = dao.WhereBuild(g, query) + if err != nil { + return nil, err + } + err = g.Find(&ml).Error + return + +} + +// GetMultiCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetMultiAuditLogs(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*AuditLogs, err error) { + + var db = dao.Model(logger, dao.IronicRdb, AuditLogs{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func QueryAuditLogs(logger *log.Logger, query map[string]interface{}, offset, limit int64) (ml []*AuditLogs, err error) { + return GetMultiAuditLogs(logger, query, nil, []string{"created_time"}, []string{"desc"}, offset, limit) + /*var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return*/ +} + +func GetOneAuditLogs(logger *log.Logger, query map[string]interface{}) (l *AuditLogs, err error) { + l = &AuditLogs{} + var db = dao.Model(logger, dao.IronicRdb, AuditLogs{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// UpdateCommand updates Command by Id and returns error if +// the record to be updated doesn't exist +func UpdateAuditLogsById(logger *log.Logger, m *AuditLogs) (err error) { + + m.UpdatedTime = int(time.Now().Unix()) + err = dao.Model(logger, dao.IronicWdb, AuditLogs{}).Where("id = ?", m.ID).Updates(m).Error + return +} + +func UpdateMultiAuditLogs(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, AuditLogs{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} diff --git a/bmp-openapi/dao/baseDao.go b/bmp-openapi/dao/baseDao.go new file mode 100644 index 0000000..d91ac7c --- /dev/null +++ b/bmp-openapi/dao/baseDao.go @@ -0,0 +1,164 @@ +package dao + +import ( + "fmt" + "reflect" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + beego "github.com/beego/beego/v2/server/web" + + clog "coding.jd.com/aidc-bmp/bmp_log" + log "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +var ( + IronicRdb *gorm.DB + IronicWdb *gorm.DB +) + +type gLogger struct { + traceid string +} + +func (g *gLogger) Print(values ...interface{}) { + var ( + level = values[0] + // source = values[1] + ) + logPath, _ := beego.AppConfig.String("log.path") + logger := clog.New(logPath + "/bmp-openapi-sql.log") + defer logger.Flush() + logger.SetStableFields([]string{"sql", "args", "cost"}) + logger.Point("logid", g.traceid) + + if level == "sql" { + logger.Point("sql", values[3]) + logger.Point("args", values[4]) + logger.Point("cost", fmt.Sprint(values[2])) + } else { + logger.Point("trace", values) + } +} + +func InitGormDb(conn string) { + + doInit(conn) + //初始化时没有完成的,择机完成初始化 + go func() { + for { + time.Sleep(10 * time.Second) + if IronicRdb != nil && IronicRdb.DB().Stats().OpenConnections == 0 { + fmt.Println(time.Now().String(), "IronicRdb reInit......") + doInitIronicRdb(conn) + } + if IronicWdb != nil && IronicWdb.DB().Stats().OpenConnections == 0 { + fmt.Println(time.Now().String(), "IronicWdb reInit......") + doInitIronicWdb(conn) + } + } + }() + +} + +func doInit(conn string) { + doInitIronicRdb(conn) + doInitIronicWdb(conn) +} + +func doInitIronicRdb(conn string) { + var err error + IronicRdb, err = gorm.Open("mysql", conn) + if err != nil { + fmt.Println(time.Now(), "IronicRdb init error:", err.Error()) + return + } + IronicRdb.LogMode(true) + IronicRdb.DB().SetMaxOpenConns(100) + IronicRdb.DB().SetMaxIdleConns(20) +} + +func doInitIronicWdb(conn string) { + var err error + IronicWdb, err = gorm.Open("mysql", conn) + if err != nil { + fmt.Println(time.Now(), "IronicWdb init error:", err.Error()) + return + } + IronicWdb.LogMode(true) + IronicWdb.DB().SetMaxOpenConns(100) + IronicWdb.DB().SetMaxIdleConns(20) +} + +func GetGormTx(logger *clog.Logger) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := IronicWdb.New() + db.SetLogger(gl) + return db +} + +type NullType byte + +const ( + _ NullType = iota + // IsNull the same as `is null` + IsNull + // IsNotNull the same as `is not null` + IsNotNull +) + +// sql build where +func WhereBuild(g *gorm.DB, query map[string]interface{}) (*gorm.DB, error) { + logger := log.New("./log/ironic-api.log") + query["is_del"] = baseLogic.IS_NOT_DEL + for k, v := range query { + if reflect.TypeOf(v).Kind() == reflect.String { + if v.(string) == "" { + continue + } + } + ks := strings.Split(k, ".") + if len(ks) > 2 { + fmt.Println(time.Now(), fmt.Errorf("Error in query condition: %s. ", k)) + logger.Warn(fmt.Errorf("Error in query condition: %s. ", k)) + + return g, fmt.Errorf("Error in query condition: %s. ", k) + } + switch len(ks) { + case 1: + g = g.Where(fmt.Sprintf("%s = ?", k), v) + break + case 2: + k = ks[0] + switch ks[1] { + case "=": + g = g.Where(fmt.Sprintf("%s = ?", k), v) + break + case ">", "gt": + g = g.Where(fmt.Sprintf("%s > ?", k), v) + case ">=", "gte": + g = g.Where(fmt.Sprintf("%s >= ?", k), v) + break + case "<", "lt": + g = g.Where(fmt.Sprintf("%s < ?", k), v) + break + case "<=", "lte": + g = g.Where(fmt.Sprintf("%s <= ?", k), v) + break + case "!=", "<>": + g = g.Where(fmt.Sprintf("%s <> ?", k), v) + break + case "in": + g = g.Where(fmt.Sprintf("%s IN (?)", k), v) + break + case "like": + g = g.Where(fmt.Sprintf("%s LIKE ?", k), v) + break + } + break + } + } + return g, nil +} diff --git a/bmp-openapi/dao/commandDao/commandDao.go b/bmp-openapi/dao/commandDao/commandDao.go new file mode 100644 index 0000000..3d476f0 --- /dev/null +++ b/bmp-openapi/dao/commandDao/commandDao.go @@ -0,0 +1,135 @@ +package commandDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Command 指令 +type Command struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + RequestID string `gorm:"index:i_command_request_id;column:request_id;type:varchar(64);not null" json:"requestId"` // 请求ID + Sn string `gorm:"index:i_command_sn;column:sn;type:varchar(64);not null" json:"sn"` // 设备SN + InstanceID string `gorm:"index:i_command_instance_id;column:instance_id;type:varchar(36)" json:"instance_id"` // 实例Id + Action string `gorm:"column:action;type:varchar(32);not null" json:"action"` // 操作 + Type string `gorm:"column:type;type:varchar(16);not null" json:"type"` // 操作类型:agent, driver, network + Status string `gorm:"index:i_command_status;column:status;type:varchar(16)" json:"status"` // 状态: wait,running,finish,error + ParentCommandID int64 `gorm:"index:i_parent_command_id;column:parent_command_id;type:bigint(20) unsigned" json:"parent_command_id"` // 父指令Id + ExecuteCount int `gorm:"column:execute_count;type:int(10) unsigned;not null" json:"execute_count"` // 执行次数 + TimeoutTime time.Time `gorm:"column:timeout_time;type:datetime" json:"timeout_time"` // timeout time + TimeoutPolicy string `gorm:"column:timeout_policy;type:varchar(16)" json:"timeout_policy"` // timeout policy + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +//var db *gorm.DB = dao.IronicRdb + +func (t *Command) TableName() string { + return "command" +} + +// AddCommand insert a new Command into database and returns +// last inserted Id on success. +func AddCommand(logger *log.Logger, m *Command) (id int64, err error) { + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetCommandById retrieves Command by Id. Returns error if +// Id doesn't exist +func GetCommandById(logger *log.Logger, id int64) (v *Command, err error) { + v = &Command{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetCommandById retrieves Command by parentId. Returns error if +// Id doesn't exist +func GetCommandByParentId(logger *log.Logger, parentId int64) (v *Command, err error) { + v = &Command{} + err = dao.Where(logger, dao.IronicRdb, "parent_command_id = ? and is_del = 0", parentId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +//TODO map[string]string gorm为什么不支持 +func GetCommandCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + var db = dao.Model(logger, dao.IronicWdb, Command{}) + db, err = dao.WhereBuild(db, query) + err = db.Count(&n).Error + return +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetAllCommand(logger *log.Logger, query map[string]interface{}) (ml []*Command, err error) { + + var db = dao.Model(logger, dao.IronicWdb, Command{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetMultiCommand(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Command, err error) { + + var db = dao.Model(logger, dao.IronicWdb, Command{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateCommand updates Command by Id and returns error if +// the record to be updated doesn't exist +func UpdateCommandById(logger *log.Logger, m *Command) (err error) { + //m.UpdateTime = time.Now() + err = dao.Model(logger, dao.IronicWdb, Command{}).Where("id = ?", m.ID).Updates(m).Error + return +} + +func DeleteCommandBySn(logger *log.Logger, sn string) (err error) { + //m.UpdateTime = time.Now() + err = dao.Model(logger, dao.IronicWdb, Command{}).Where("sn = ? and status <> ?", sn, "finish").Update("is_del", 1).Error + return +} + +func DeleteCommandByInstanceId(logger *log.Logger, instanceId string) (err error) { + //m.UpdateTime = time.Now() + err = dao.Model(logger, dao.IronicWdb, Command{}).Where("instance_id = ? and status <> ?", instanceId, "finish").Update("is_del", 1).Error + return +} + +func DeleteCommandByInstanceIdAndTask(logger *log.Logger, instanceId string, task string) (err error) { + //m.UpdateTime = time.Now() + err = dao.Model(logger, dao.IronicWdb, Command{}).Where("instance_id = ? and task = ? and is_del = ? and status <> ?", instanceId, task, 0, "finish").Update("is_del", 1).Error + return +} diff --git a/bmp-openapi/dao/createDao.go b/bmp-openapi/dao/createDao.go new file mode 100644 index 0000000..d7f5ade --- /dev/null +++ b/bmp-openapi/dao/createDao.go @@ -0,0 +1,36 @@ +package dao + +import ( + clog "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +// 插入单条记录,v2版本才支持插入多条记录? +//eg. db.Create(logger, rdb, u) +func Create(logger *clog.Logger, gdb *gorm.DB, out interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Create(out) +} + +//插入并获取刚插入数据的自增Id +//eg. db.CreateAndGetId(logger, rdb, u) +func CreateAndGetId(logger *clog.Logger, gdb *gorm.DB, out interface{}) (int64, error) { + // 事务约束,否则并发下可能获取到的是错误的id + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + tx := db.Begin() + if err := tx.Create(out).Error; err != nil { + tx.Rollback() + return 0, err + } + var id []int64 + if err := tx.Raw("select LAST_INSERT_ID() as id").Pluck("id", &id).Error; err != nil { + tx.Rollback() + return 0, err + } + tx.Commit() + return id[0], nil +} diff --git a/bmp-openapi/dao/deleteDao.go b/bmp-openapi/dao/deleteDao.go new file mode 100644 index 0000000..190aba8 --- /dev/null +++ b/bmp-openapi/dao/deleteDao.go @@ -0,0 +1,21 @@ +package dao + +import ( + clog "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +//删除记录 +//eg1.根据模型删除 +/* +food := Food{} +dao.Where(logger, rdb, "id = ?", 2).Take(&food).Delete(&food) +*/ +//eg2.根据Where条件删除数据 +// dao.Where(logger, rdb, "type = ?", 5).Delete(&Food{})//注意这里Delete函数需要传递一个空的模型变量指针 +func Delete(logger *clog.Logger, gdb *gorm.DB, value interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Delete(value, where...) +} diff --git a/bmp-openapi/dao/deviceDao/deviceDao.go b/bmp-openapi/dao/deviceDao/deviceDao.go new file mode 100644 index 0000000..f49a115 --- /dev/null +++ b/bmp-openapi/dao/deviceDao/deviceDao.go @@ -0,0 +1,394 @@ +package deviceDao + +import ( + "fmt" + "strconv" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/diskDao" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type Device struct { + ID int `gorm:"primaryKey;column:id" json:"id"` // 设备ID编号 + Sn string `gorm:"column:sn" json:"sn"` // 设备SN + DeviceID string `gorm:"column:device_id" json:"deviceId"` // 设备uuid + InstanceID string `gorm:"column:instance_id" json:"instanceId"` // 实例id + IDcID string `gorm:"column:idc_id" json:"idcId"` // 机型uuid + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型uuid + ManageStatus string `gorm:"column:manage_status" json:"manageStatus"` // 设备状态: 未装机,已装机 + UserId string `gorm:"column:user_id" json:"userId"` // 设备状态: 未装机,已装机 + UserName string `gorm:"column:user_name" json:"userName"` // 设备状态: 未装机,已装机 + Brand string `gorm:"column:brand" json:"brand"` // 品牌 + Model string `gorm:"column:model" json:"model"` // 型号 + DeviceSeries string `gorm:"column:device_series" json:"deviceSeries"` // 机型类型,如计算型,存储型 + Reason string `gorm:"column:reason" json:"reason"` // 设备状态变更失败原因 + Cabinet string `gorm:"column:cabinet" json:"cabinet"` // 机柜编码 + UPosition string `gorm:"column:u_position" json:"uPosition"` // U位 + IloIP string `gorm:"column:ilo_ip" json:"iloIp"` // 带外管理IP + IloUser string `gorm:"column:ilo_user" json:"iloUser"` // 带外账号 + IloPassword string `gorm:"column:ilo_password" json:"iloPassword"` // 带外账号密码 + Mac1 string `gorm:"column:mac1" json:"mac1"` // MAC1(eth0) + Mac2 string `gorm:"column:mac2" json:"mac2"` // MAC2(eth2) + SwitchIP1 string `gorm:"column:switch_ip1" json:"switchIp1"` // 交换机1ip + SwitchPort1 string `gorm:"column:switch_port1" json:"switchPort1"` // 交换机1port + SwitchIP2 string `gorm:"column:switch_ip2" json:"switchIp2"` // 交换机2ip + SwitchPort2 string `gorm:"column:switch_port2" json:"switchPort2"` // 交换机2port + SwitchUser1 string `gorm:"column:switch_user1" json:"switchUser1"` // 交换机1登录账号,如果为空,取所在机房的值 + SwitchPassword1 string `gorm:"column:switch_password1" json:"switchPassword1"` // 交换机1登录密码 + SwitchUser2 string `gorm:"column:switch_user2" json:"switchUser2"` // 交换机2登录账号,如果为空,取所在机房的值 + SwitchPassword2 string `gorm:"column:switch_password2" json:"switchPassword2"` // 交换机2登录密码 + Description string `gorm:"column:description" json:"description"` // 描述 + SwitchIP string `gorm:"column:switch_ip" json:"switchIp"` // 网口交换机IP + Mask string `gorm:"column:mask" json:"mask"` // 子网掩码 + MaskEth1 string `gorm:"column:mask_eth1" json:"mask_eth1"` // eth1子网掩码 + Gateway string `gorm:"column:gateway" json:"gateway"` // 网关地址 + PrivateIPv4 string `gorm:"column:private_ipv4" json:"privateIpv4"` // 内网IPV4 + PrivateEth1IPv4 string `gorm:"column:private_eth1_ipv4" json:"privateEth1Ipv4"` // eth1内网IPV4 + PrivateIPv6 string `gorm:"column:private_ipv6" json:"privateIpv6"` // 内网IPV6 + PrivateEth1IPv6 string `gorm:"column:private_eth1_ipv6" json:"privateEth1Ipv6"` // eth1内网IPV6 + Gateway6 string `gorm:"column:gateway6" json:"gateway6"` // IPV6网关地址 + AdapterID int `gorm:"column:adapter_id" json:"adapterId"` // adapter_id + RaidDriver string `gorm:"column:raid_driver" json:"raidDriver"` // raid工具:(megacli64等) + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 + // "1"表示已采集,"2"表示未采集. "3"表示采集中,4表示采集失败 + CollectStatus string `gorm:"column:collect_status" json:"collectStatus"` + //采集失败原因 + CollectFailReason string `gorm:"column:collect_fail_reason" json:"collectFailReason"` +} + +func (t *Device) TableName() string { + return "device" +} + +func GetBySn(logger *log.Logger, sn string) (v *Device, err error) { + v = &Device{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and is_del = 0", sn).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetOneDevice(logger *log.Logger, query map[string]interface{}) (l *Device, err error) { + l = &Device{} + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetDeviceCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} + +// AddDevice insert a new Device into database and returns +// last inserted Id on success. +func AddDevice(logger *log.Logger, m *Device) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// //TODO 有时间试试gorm v2支持的批量插入 +func AddMultiDevice(logger *log.Logger, m []*Device) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, device := range m { + //device.CreateTime = time.Now() + //device.UpdateTime = time.Now() + if err := tx.Create(device).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// deprecated 20240516 minping +func CreateDeviceAndDisk(logger *log.Logger, m []*Device, disks1, disks2 map[string]*diskDao.Disk) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, device := range m { + //device.CreateTime = time.Now() + //device.UpdateTime = time.Now() + if err := tx.Create(device).Error; err != nil { + tx.Rollback() + return 0, err + } + diskDao.AddDisk(logger, disks1[device.DeviceID]) + if disks2[device.DeviceID].Slot != 0 && disks2[device.DeviceID].Enclosure != "" { + diskDao.AddDisk(logger, disks2[device.DeviceID]) + } + + } + tx.Commit() + return int64(len(m)), nil +} + +// GetDeviceById retrieves Device by Id. Returns error if +// Id doesn't exist +func GetDeviceById(logger *log.Logger, deviceId string) (v *Device, err error) { + v = &Device{} + err = dao.Where(logger, dao.IronicRdb, "device_id = ? and is_del = 0", deviceId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetDeviceBySn retrieves Device by Sn. Returns error if +// Sn doesn't exist +func GetDeviceBySn(logger *log.Logger, sn string) (v *Device, err error) { + v = &Device{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and is_del = 0", sn).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +//获取所有设备,支持排序 +func GetAllDevices(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string) (ml []*Device, err error) { + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Find(&ml).Error + return +} + +// GetMultiDevice retrieves all Device matches certain condition. Returns empty list if +// no records exist +func GetMultiDevice(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Device, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// GetMultiDevice retrieves all Device matches certain condition. Returns empty list if +// no records exist +func GetAllDevice(logger *log.Logger, query map[string]interface{}) (ml []*Device, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetSingleDevice(logger *log.Logger, query map[string]interface{}) (l *Device, err error) { + l = &Device{} + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func UpdateMultiDevices(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +// UpdateDevice updates Device by Id and returns error if +// the record to be updated doesn't exist +func UpdateDeviceById(logger *log.Logger, m *Device) (err error) { + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicRdb, Device{}).Where("device_id = ?", m.DeviceID).Updates(m).Error +} +func SaveDevice(logger *log.Logger, m *Device) (err error) { + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicRdb, Device{}).Where("device_id = ?", m.DeviceID).Save(m).Error +} +func UpdateDeviceByDeviceTypeId(logger *log.Logger, m *Device) (err error) { + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicRdb, Device{}).Where("device_type_id = ? AND is_del = ?", m.DeviceTypeID, baseLogic.IS_NOT_DEL).Update(m).Error +} +func UpdateDeviceBySn(logger *log.Logger, m *Device) (err error) { + sql := `update device set instance_id='',user_id = '',user_name = '',manage_status="` + m.ManageStatus + `",reason='' ,updated_time = ` + strconv.Itoa(int(time.Now().Unix())) + ` where sn="` + m.Sn + `" and is_del = 0` + err = dao.IronicWdb.Exec(sql).Error + fmt.Println("UpdateDeviceBySn err", err) + return + //return dao.Model(logger, dao.IronicWdb, Device{}).Where("sn=? and is_del=?", m.Sn, "0").Save(m).Error +} +func GetFirstVersionDeviceSns(logger *log.Logger) (sns []string, err error) { + sql := `select distinct d.sn from device d left join command c on d.sn = c.sn where d.is_del=0 and d.sale_status = 'sold' and d.region = 'cn-north-1' and d.az != 'cn-north-1c'` + + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&sns).Error + return +} + +func GetFirstVersionAndReInstallDeviceSns(logger *log.Logger) (sns []string, err error) { + + sql := `select distinct d.sn from device d left join command c on d.sn = c.sn where d.is_del = 0 and d.sale_status = 'sold' and d.region = 'cn-north-1' and d.az != 'cn-north-1c' and c.action = 'WriteImage' and c.status = 'finish' and c.is_del = 0` + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&sns).Error + return +} + +type DeviceStock struct { + Total int64 `json:"total"` + Used int64 `json:"used"` + Available int64 `json:"available"` + Region string `json:"region"` + Az string `json:"az"` + DeviceType string `json:"device_type"` +} + +func GetDeviceStock(logger *log.Logger, device_type, region, az string) (ml []*DeviceStock, err error) { + + sql := `select region, az, device_type, count(id) as total, sum(if(sale_status = 'sold', 1, 0)) as used, sum(if(sale_status = 'selling', 1, 0)) as available from device where 1=1` + if region != "" { + sql = sql + fmt.Sprintf(" and region = '%s'", region) + } + if az != "" { + sql = sql + fmt.Sprintf(" and az = '%s'", az) + } + if device_type != "" { + sql = sql + fmt.Sprintf(" and device_type = '%s'", device_type) + } + sql = sql + " and is_del = 0 group by region,az,device_type" + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} + +type DDeviceIncludeSwitchIp struct { + *Device + SwitchIp string `json:"switch_ip"` +} + +func QueryIncludeSwitchIpByParam(logger *log.Logger, az, device_type, sale_status string) (ml []*DDeviceIncludeSwitchIp, err error) { + + sql := `select distinct switch_ip, d.* from device d left join interface i on d.sn = i.sn where 1=1` + if device_type != "" { + sql = sql + fmt.Sprintf(" and d.device_type = '%s'", device_type) + } + // if az != "" { + // sql = sql + fmt.Sprintf(" and d.az = '%s'", az) + // } + if sale_status != "" { + sql = sql + fmt.Sprintf(" and d.sale_status = '%s'", sale_status) + } + sql = sql + ` and d.is_del = 0 and i.is_del = 0` + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return + +} + +func DescribeInstanceStock(logger *log.Logger, param map[string][]string) (ml []*Device, err error) { + sql := `select id,sn,region,az,device_type,manufacturer_id,u_position,cabinet,ilo_ip,sale_status,create_time,update_time,is_del from device where 1=1` + + if param["regions"] != nil { + regions := []string{} + for _, v := range param["regions"] { + regions = append(regions, fmt.Sprintf("'%s'", v)) + } + sql = sql + fmt.Sprintf(" and region in (%s)", strings.Join(regions, ",")) + } + + if param["azs"] != nil { + azs := []string{} + for _, v := range param["azs"] { + azs = append(azs, fmt.Sprintf("'%s'", v)) + } + sql = sql + fmt.Sprintf(" and az in (%s)", strings.Join(azs, ",")) + } + + if param["deviceTypes"] != nil { + deviceTypes := []string{} + for _, v := range param["deviceTypes"] { + deviceTypes = append(deviceTypes, fmt.Sprintf("'%s'", v)) + } + sql = sql + fmt.Sprintf(" and device_type in (%s)", strings.Join(deviceTypes, ",")) + } + + if param["saleStatus"] != nil { + saleStatus := []string{} + for _, v := range param["saleStatus"] { + saleStatus = append(saleStatus, fmt.Sprintf("'%s'", v)) + } + sql = sql + fmt.Sprintf(" and sale_status in (%s)", strings.Join(saleStatus, ",")) + } else { + sql = sql + " and sale_status = 'selling'" + } + sql += " and is_del = 0" + + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} + +// description为空也有可能 +func UpdateDeviceAnywhere(logger *log.Logger, m *Device) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Device{}).Save(m).Error +} diff --git a/bmp-openapi/dao/deviceHintsDao/deviceHintsDao.go b/bmp-openapi/dao/deviceHintsDao/deviceHintsDao.go new file mode 100644 index 0000000..1741186 --- /dev/null +++ b/bmp-openapi/dao/deviceHintsDao/deviceHintsDao.go @@ -0,0 +1,93 @@ +package deviceHintsDao + +import ( + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// DeviceHints 根设备所在磁盘 +type DeviceHints struct { + ID int64 `gorm:"unique;column:id;type:bigint(20) unsigned;not null" json:"id"` // 设备ID编号 + + Sn string `gorm:"column:sn;type:varchar(64);not null" json:"sn"` // 设备SN + //volume UUID + VolumeId string `gorm:"column:volume_id;type:varchar(128)" json:"volume_id"` + VolumeType string `gorm:"column:volume_type" json:"volumeType"` // 卷类型:系统卷,数据卷 + Size int64 `gorm:"column:size;type:bigint(20);not null" json:"size"` // 以GiB为单位的设备尺寸 + Rotational int8 `gorm:"column:rotational;type:tinyint(4);not null" json:"rotational"` // 转动,可以区分HDDs(旋转-磁盘)和SSDs(非旋转-固态硬盘) + Wwn string `gorm:"column:wwn;type:varchar(128)" json:"wwn"` // 唯一的存储标识符 + Name string `gorm:"column:name;type:varchar(64);not null" json:"name"` // 设备名称,例如/dev/md0 + WwnVendorExtension string `gorm:"column:wwn_vendor_extension;type:varchar(64)" json:"wwn_vendor_extension"` // 唯一的供应商存储标识符 + WwnWithExtension string `gorm:"column:wwn_with_extension;type:varchar(64)" json:"wwn_with_extension"` // 带有供应商附加扩展的唯一的存储标识符 + Model string `gorm:"column:model;type:varchar(64)" json:"model"` // 设备标识符 + Serial string `gorm:"column:serial;type:varchar(64)" json:"serial"` // 磁盘序列号 + Hctl string `gorm:"column:hctl;type:varchar(64)" json:"hctl"` // SCSI地址(主机名、channel通道、Target和Lun) + ByPath string `gorm:"column:by_path;type:varchar(128)" json:"by_path"` // 磁盘by_path路径 + Vendor string `gorm:"column:vendor;type:varchar(64)" json:"vendor"` // 设备供应商 + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *DeviceHints) TableName() string { + return "device_hints" +} + +// AddDeviceHints insert a new DeviceHints into database and returns +// last inserted Id on success. +func AddDeviceHints(logger *log.Logger, m *DeviceHints) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetDeviceHintsById retrieves DeviceHints by Id. Returns error if +// Id doesn't exist +func GetDeviceHintsById(logger *log.Logger, id int) (v *DeviceHints, err error) { + v = &DeviceHints{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetSystemVolumnDeviceHintsBySn(logger *log.Logger, sn string) (v *DeviceHints, err error) { + v = &DeviceHints{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and volume_type = 'system' and is_del = 0", sn).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetDeviceHintsBySnAndVolumeId(logger *log.Logger, sn, volume_id string) (v *DeviceHints, err error) { + v = &DeviceHints{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and volume_id = ? and is_del = 0", sn, volume_id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllDeviceHints retrieves all DeviceHints matches certain condition. Returns empty list if +// no records exist +func GetAllDeviceHints(logger *log.Logger, query map[string]interface{}) (ml []*DeviceHints, err error) { + + var db = dao.Model(logger, dao.IronicRdb, DeviceHints{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// UpdateDeviceHintsById updates DeviceHints by Id and returns error if +// the record to be updated doesn't exist +func UpdateDeviceHintsById(logger *log.Logger, m *DeviceHints) (err error) { + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, DeviceHints{}).Where("id = ?", m.ID).Updates(m).Error +} diff --git a/bmp-openapi/dao/deviceTypeDao/deviceTypeDao.go b/bmp-openapi/dao/deviceTypeDao/deviceTypeDao.go new file mode 100644 index 0000000..c01f8b5 --- /dev/null +++ b/bmp-openapi/dao/deviceTypeDao/deviceTypeDao.go @@ -0,0 +1,243 @@ +package deviceTypeDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type DeviceType struct { + // 主键 + ID int `gorm:"primaryKey;column:id" json:"-"` + // 机房id + IDcID string `gorm:"column:idc_id" json:"idcId"` + // 设备类型uuid + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` + // 机型名称,如计算效能型,标准计算型 + Name string `gorm:"column:name" json:"name"` + // 机型规格, cps.c.normal + DeviceType string `gorm:"column:device_type" json:"deviceType"` + // 机型类型,如计算型,存储型 + DeviceSeries string `gorm:"column:device_series" json:"deviceSeries"` + // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Architecture string `gorm:"column:architecture" json:"architecture"` + // 【高度(U)】:显示机型高度 + Height int `gorm:"column:height" json:"height"` + // 描述 + Description string `gorm:"column:description" json:"description"` + // cpu预置类型 + CpuSpec string `gorm:"column:cpu_spec" json:"cpuSpec"` + // cpu数量 + CPUAmount int `gorm:"column:cpu_amount" json:"cpuAmount"` + // 单个cpu内核数 + CPUCores int `gorm:"column:cpu_cores" json:"cpuCores"` + // cpu厂商 + CPUManufacturer string `gorm:"column:cpu_manufacturer" json:"cpuManufacturer"` + // cpu处理器型号 + CPUModel string `gorm:"column:cpu_model" json:"cpuModel"` + // cpu频率(G) + CPUFrequency string `gorm:"column:cpu_frequency" json:"cpuFrequency"` + // cpu预置类型 + MemSpec string `gorm:"column:mem_spec" json:"memSpec"` + // 内存接口(如DDR3,DDR4) + MemType string `gorm:"column:mem_type" json:"memType"` + // 单个内存大小(GB) + MemSize int `gorm:"column:mem_size" json:"memSize"` + // 内存数量 + MemAmount int `gorm:"column:mem_amount" json:"memAmount"` + // 内存主频(MHz) + MemFrequency int `gorm:"column:mem_frequency" json:"memFrequency"` + // 网卡数量 + NicAmount int `gorm:"column:nic_amount" json:"nicAmount"` + // 网卡传输速率(GE) + NicRate int `gorm:"column:nic_rate" json:"nicRate"` + // 【网口模式】【网络设置】: bond单网口,dual双网口 + InterfaceMode string `gorm:"column:interface_mode" json:"interfaceMode"` + // 系统盘类型(SSD,HDD) + SystemVolumeType string `gorm:"column:system_volume_type" json:"systemVolumeType"` + // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeInterfaceType string `gorm:"column:system_volume_interface_type" json:"systemVolumeInterfaceType"` + // 系统盘单盘大小 + SystemVolumeSize int `gorm:"column:system_volume_size" json:"systemVolumeSize"` + // 系统盘单盘大小单位 + SystemVolumeUnit string `gorm:"column:system_volume_unit" json:"systemVolumeUnit"` + // 系统盘数量 + SystemVolumeAmount int `gorm:"column:system_volume_amount" json:"systemVolumeAmount"` + // 系统盘是否做raid【RAID/NO RAID】 + RaidCan string `gorm:"column:raid_can" json:"raidCan"` + // gpu数量 + GpuAmount int `gorm:"column:gpu_amount" json:"gpuAmount"` + // gpu厂商 + GpuManufacturer string `gorm:"column:gpu_manufacturer" json:"gpuManufacturer"` + // gpu处理器型号 + GpuModel string `gorm:"column:gpu_model" json:"gpuModel"` + // 数据盘类型(SSD,HDD) + DataVolumeType string `gorm:"column:data_volume_type" json:"dataVolumeType"` + // 数据盘接口类型(SATA,SAS,NVME) + DataVolumeInterfaceType string `gorm:"column:data_volume_interface_type" json:"dataVolumeInterfaceType"` + // 数据盘单盘大小 + DataVolumeSize int `gorm:"column:data_volume_size" json:"dataVolumeSize"` + // 系统盘单盘大小单位 + DataVolumeUnit string `gorm:"column:data_volume_unit" json:"dataVolumeUnit"` + // 数据盘数量 + DataVolumeAmount int `gorm:"column:data_volume_amount" json:"dataVolumeAmount"` + // 是否配置了阵列卡 + IsNeedRaid string `gorm:"column:is_need_raid" json:"isNeedRaid"` + // 创建者 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` + // 更新者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` + // 创建时间 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` + // 更新时间 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` + // 删除时间 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` + // boot类型:UEFI Legacy/BIOS + BootMode string `gorm:"column:boot_mode" json:"bootMode"` + // 是否删除0未删除 1已删除 + IsDel int8 `gorm:"column:is_del" json:"isDel"` +} + +func (t *DeviceType) TableName() string { + return "device_type" +} + +// AddDeviceType insert a new DeviceType into database and returns +// last inserted Id on success. +func AddDeviceType(logger *log.Logger, m *DeviceType) (id int64, err error) { + return dao.CreateAndGetId(logger, dao.IronicRdb, m) +} + +// GetDeviceTypeById retrieves DeviceType by Id. Returns error if +// Id doesn't exist +func GetDeviceTypeById(logger *log.Logger, deviceTypeId string) (v *DeviceType, err error) { + v = &DeviceType{} + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and is_del = 0", deviceTypeId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func QueryDeviceTypesCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} +func QueryAllDeviceTypes(logger *log.Logger, query map[string]interface{}) (ml []*DeviceType, err error) { //如果需要排序,在下面的代码中定义 + return GetMultiDeviceType(logger, query, nil, []string{"created_time"}, []string{"desc"}, 0, 0) +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func QueryDeviceTypes(logger *log.Logger, query map[string]interface{}, offset, limit int64) (ml []*DeviceType, err error) { + return GetMultiDeviceType(logger, query, nil, []string{"created_time"}, []string{"desc"}, offset, limit) + /*var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return*/ +} + +func GetOneDeviceType(logger *log.Logger, query map[string]interface{}) (l *DeviceType, err error) { + l = &DeviceType{} + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// GetMultiDeviceType retrieves all DeviceType matches certain condition. Returns empty list if +// no records exist +func GetMultiDeviceType(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*DeviceType, err error) { + + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateDeviceType updates DeviceType by Id and returns error if +// the record to be updated doesn't exist +func UpdateDeviceTypeByDeviceTypeID(logger *log.Logger, m *DeviceType, deviceTypeID string) (err error) { + //m.UpdateUser = logger.GetPoint("username").(string) + err = dao.Model(logger, dao.IronicWdb, DeviceType{}).Where("device_type_id = ?", deviceTypeID).Save(m).Error + return +} + +// GetAllDeviceTyp retrieves all DeviceTyp matches certain condition. Returns empty list if +// no records exist +func GetAllDeviceType(logger *log.Logger, query map[string]interface{}) (ml []*DeviceType, err error) { + + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} +func GetByAzAndDeviceType(logger *log.Logger, az, deviceType string) (l *DeviceType, err error) { + l = &DeviceType{} + query := map[string]interface{}{ + "is_del": "0", + "device_type": deviceType, + // "az": az, + } + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func QueryByAz(logger *log.Logger, az string) (ml []*DeviceType, err error) { + query := map[string]interface{}{ + "is_del": "0", + // "az": az, + } + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} diff --git a/bmp-openapi/dao/diskDao/diskDao.go b/bmp-openapi/dao/diskDao/diskDao.go new file mode 100644 index 0000000..beba056 --- /dev/null +++ b/bmp-openapi/dao/diskDao/diskDao.go @@ -0,0 +1,129 @@ +package diskDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Disk Disk +type Disk struct { + ID int `gorm:"primaryKey;column:id" json:"-"` // ID + DiskId string `gorm:"column:disk_id" json:"diskId"` //DISK UUID + Name string `gorm:"column:name" json:"name"` //DISK name + DeviceID string `gorm:"column:device_id" json:"deviceId"` // 设备uuid + Enclosure string `gorm:"column:enclosure" json:"enclosure"` // enclosure + Slot int `gorm:"column:slot" json:"slot"` // 卡槽槽位 + // 磁盘类型:system,data + DiskType string `gorm:"column:disk_type" json:"diskType"` + // control/mvme/panfu + Types string `gorm:"column:types" json:"types"` + Size string `gorm:"column:size" json:"size"` // 硬盘大小,不确定精度(非nvme盘) + SizeUnit string `gorm:"column:size_unit" json:"sizeUnit"` // 硬盘大小单位 MB GB TB ,1024进制 + PdType string `gorm:"column:pd_type" json:"pdType"` // 硬盘类型 + AdapterID int `gorm:"column:adapter_id" json:"adapterId"` // 适配ID + MediaType string `gorm:"column:media_type" json:"mediaType"` // + DevicePath string `gorm:"column:device_path" json:"devicePath"` // + Index int `gorm:"column:index" json:"index"` // + SerialNumber string `gorm:"column:serial_number" json:"serialNumber"` // + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Disk) TableName() string { + return "disk" +} + +// AddDisk insert a new Disk into database and returns +// last inserted Id on success. +func AddDisk(logger *log.Logger, m *Disk) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetDiskById retrieves Disk by Id. Returns error if +// Id doesn't exist +func GetDiskById(logger *log.Logger, id int64) (v *Disk, err error) { + v = &Disk{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetDiskByUuid retrieves Disk by Uuid. Returns error if +// Id doesn't exist +func GetDiskByUuid(logger *log.Logger, uuid string) (v *Disk, err error) { + v = &Disk{} + err = dao.Where(logger, dao.IronicRdb, "Disk_id = ? and is_del = 0", uuid).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllDisk retrieves all Disk matches certain condition. Returns empty list if +// no records exist +func GetAllDisk(logger *log.Logger, query map[string]interface{}) (ml []*Disk, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Disk{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiDisk retrieves all Disk matches certain condition. Returns empty list if +// no records exist +func GetMultiDisk(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Disk, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Disk{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateDisk updates Disk by Id and returns error if +// the record to be updated doesn't exist +func UpdateDiskById(logger *log.Logger, m *Disk) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Disk{}).Where("device_id = ?", m.DeviceID).Updates(m).Error +} + +func GetDiskWithDeviceIdVolumeId(logger *log.Logger, deviceId string, volumeId string) (ml []*Disk, err error) { + + sql := `select a.* from disk a inner join r_device_volume_disks b on a.disk_id = b.disk_id where a.is_del = 0 and b.is_del = 0 ` + + sql = sql + fmt.Sprintf(" and b.volume_id = '%s' and b.device_id = '%s'", volumeId, deviceId) + + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-openapi/dao/idcDao/idcDao.go b/bmp-openapi/dao/idcDao/idcDao.go new file mode 100644 index 0000000..6423547 --- /dev/null +++ b/bmp-openapi/dao/idcDao/idcDao.go @@ -0,0 +1,134 @@ +package idcDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type Idc struct { + ID int `gorm:"primaryKey;column:id" json:"id"` // ID + IDcID string `gorm:"column:idc_id" json:"idcId"` // 机房uuid + Name string `gorm:"column:name" json:"name"` + NameEn string `gorm:"column:name_en" json:"nameEn"` + Shortname string `gorm:"column:shortname" json:"shortname"` // 机房名称缩写 + Level string `gorm:"column:level" json:"level"` // 机房等级 + Address string `gorm:"column:address" json:"address"` // 机房地址 + IloUser string `gorm:"column:ilo_user" json:"iloUser"` // 带外登录账号 + IloPassword string `gorm:"column:ilo_password" json:"iloPassword"` // 带外登录密码 + SwitchUser1 string `gorm:"column:switch_user1" json:"switchUser1"` // 交换机1登录账号 + SwitchPassword1 string `gorm:"column:switch_password1" json:"switchPassword1"` // 交换机1登录密码 + SwitchUser2 string `gorm:"column:switch_user2" json:"switchUser2"` // 交换机2登录账号 + SwitchPassword2 string `gorm:"column:switch_password2" json:"switchPassword2"` // 交换机2登录密码 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Idc) TableName() string { + return "idc" +} + +// AddIdc insert a new Idc into database and returns +// last inserted Id on success. +func CreateIdc(logger *log.Logger, m *Idc) (id int64, err error) { + return dao.CreateAndGetId(logger, dao.IronicRdb, m) +} + +// GetIdcById retrieves Idc by Id. Returns error if +// Id doesn't exist +func GetIdcById(logger *log.Logger, idcId string) (v *Idc, err error) { + v = &Idc{} + err = dao.Where(logger, dao.IronicRdb, "idc_id = ? and is_del = 0", idcId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetOneIdc(logger *log.Logger, query map[string]interface{}) (l *Idc, err error) { + l = &Idc{} + var db = dao.Model(logger, dao.IronicRdb, Idc{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// GetAllIdc retrieves all Idc matches certain condition. Returns empty list if +// no records exist +func GetAllIdc(logger *log.Logger, query map[string]interface{}) (ml []*Idc, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Idc{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiIdc retrieves all Idc matches certain condition. Returns empty list if +// no records exist +func GetMultiIdc(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Idc, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Idc{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetIdcCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Idc{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return + +} + +// UpdateIdc updates Idc by Id and returns error if +// the record to be updated doesn't exist +func UpdateIdcById(logger *log.Logger, m *Idc, dcId string) (err error) { + return dao.Model(logger, dao.IronicWdb, Idc{}).Where("idc_id = ?", dcId).Save(m).Error +} + +//func DeleteIdcById(logger *log.Logger, m *Idc) (err error) { +// m.UpdatedBy = logger.GetPoint("username").(string) +// //m.UpdatedAt = time.Now().Unix() +// //m.De = time.Now().Unix() +// return dao.Model(logger, dao.IronicWdb, Idc{}).Where("idc_id = ?", m.DcId).Update(m).Error +//} + +func QueryByParam(logger *log.Logger, query map[string]interface{}, offset, limit int64) (ml []*Idc, err error) { + return GetMultiIdc(logger, query, nil, []string{"id"}, []string{"desc"}, offset, limit) +} diff --git a/bmp-openapi/dao/imageDao/imageDao.go b/bmp-openapi/dao/imageDao/imageDao.go new file mode 100644 index 0000000..a17bcdf --- /dev/null +++ b/bmp-openapi/dao/imageDao/imageDao.go @@ -0,0 +1,256 @@ +package imageDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Image 镜像 +type Image struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像uuid + ImageName string `gorm:"column:image_name" json:"imageName"` // 镜像名称 + //ImageVersion string `gorm:"column:image_version" json:"imageVersion"` // 镜像版本 + OsID string `gorm:"column:os_id" json:"osId"` // OSID + Format string `gorm:"column:format" json:"format"` // 镜像格式(qcow2、tar) + BootMode string `gorm:"column:boot_mode" json:"bootMode"` // boot类型:UEFI Legacy/BIOS + Filename string `gorm:"column:filename" json:"filename"` // 镜像文件名称 + URL string `gorm:"column:url" json:"url"` // 镜像源路径 + Hash string `gorm:"column:hash" json:"hash"` // 镜像校验码 + Source string `gorm:"column:source" json:"source"` // 镜像来源(common通用、customize定制、user_defined自定义) + Description string `gorm:"column:description" json:"description"` // 描述 + SystemPartition string `gorm:"column:system_partition" json:"systemPartition"` // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + DataPartition string `gorm:"column:data_partition" json:"dataPartition"` // 数据分区信息 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Image) TableName() string { + return "image" +} + +// AddImage insert a new Image into database and returns +// last inserted Id on success. +func AddImage(logger *log.Logger, m *Image) (id int64, err error) { + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetImageById retrieves Image by Id. Returns error if +// Id doesn't exist +func GetImageById(logger *log.Logger, id int64) (v *Image, err error) { + v = &Image{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetImageByUuid retrieves Image by Uuid. Returns error if +// Id doesn't exist +func GetImageByUuid(logger *log.Logger, imageId string) (v *Image, err error) { + v = &Image{} + err = dao.Where(logger, dao.IronicRdb, "image_id = ? and is_del = 0", imageId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} +func QueryImagesCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Image{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} +func GetAllImage(logger *log.Logger, query map[string]interface{}) (ml []*Image, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Image{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiImage retrieves all Image matches certain condition. Returns empty list if +// no records exist +func GetMultiImage(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Image, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Image{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateImage updates Image by Id and returns error if +// the record to be updated doesn't exist +func UpdateImageById(logger *log.Logger, m *Image) (err error) { + return dao.Model(logger, dao.IronicWdb, Image{}).Where("image_id = ?", m.ImageID).Save(m).Error +} + +type DImage struct { + ID uint64 `gorm:"primaryKey;column:id" json:"id"` // ID + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像uuid + ImageName string `gorm:"column:image_name" json:"imageName"` // 镜像名称 + //ImageVersion string `gorm:"column:image_version" json:"imageVersion"` // 镜像版本 + //OsID string `gorm:"column:os_id" json:"osId"` // OSID + Format string `gorm:"column:format" json:"format"` // 镜像格式(qcow2、tar) + BootMode string `gorm:"column:boot_mode" json:"bootMode"` // boot类型:UEFI Legacy/BIOS + Filename string `gorm:"column:filename" json:"filename"` // 镜像文件名称 + URL string `gorm:"column:url" json:"url"` // 镜像源路径 + Hash string `gorm:"column:hash" json:"hash"` // 镜像校验码 + Source string `gorm:"column:source" json:"source"` // 镜像来源(common通用、customize定制、user_defined自定义) + Description string `gorm:"column:description" json:"description"` // 描述 + SystemPartition string `gorm:"column:system_partition" json:"systemPartition"` // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + DataPartition string `gorm:"column:data_partition" json:"dataPartition"` // 数据分区信息 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 + + OsID string `json:"OsId"` + OsName string `json:"osName"` + OsVersion string `json:"osVersion"` + OsType string `json:"osType"` + //Platform string `json:"platform"` + Architecture string `json:"architecture"` + Bits int32 `json:"bits"` + //CreatedBy int `json:"createdBy"` + //UpdatedBy int `json:"updatedBy"` + //CreatedTime int `json:"createdTime"` + //UpdatedTime int `json:"updatedTime"` +} + +func ConvertIn(str string) string { + arr := strings.Split(str, ",") + sqlIn := "" + for _, v := range arr { + sqlIn = sqlIn + "'" + v + "'" + "," + } + sqlIn = strings.Trim(sqlIn, ",") + return "(" + sqlIn + ")" +} + +// QueryByDeviceOsType ... +func GetImageAndOsList(logger *log.Logger, param map[string]interface{}, count bool, offset int64, limit int64) (ml []*DImage, n int64, err error) { + raw := "*" + if count { + raw = "count(*)" + } + sql := `select ` + raw + ` FROM image i,os o where i.os_id=o.os_id and i.is_del=0 and o.is_del=0` + //fmt.Println(param) + if param["image_id"] != nil && param["image_id"] != "" { + sql = sql + " and i.image_id=" + fmt.Sprintf("'%s'", param["image_id"]) + } + if param["image_name"] != nil && param["image_name"] != "" { + sql = sql + " and i.image_name like \"%" + param["image_name"].(string) + "%\"" + } + if param["source"] != nil && param["source"] != "" { + sql = sql + " and i.source in " + ConvertIn(param["source"].(string)) + } + if param["os_type"] != nil && param["os_type"] != "" { + sql = sql + " and o.os_type in " + ConvertIn(param["os_type"].(string)) + } + if param["architecture"] != nil && param["architecture"] != "" { + sql = sql + " and o.architecture in " + ConvertIn(param["architecture"].(string)) + } + if param["device_type_id"] != nil && param["device_type_id"] != "" { + sql = sql + " and i.image_id not in (select image_id from r_device_type_image where device_type_id = '" + param["device_type_id"].(string) + "' and is_del = 0)" + } + sql = sql + " order by i.created_time desc" + if count { + err = dao.Raw(logger, dao.IronicRdb, sql).Count(&n).Error + return + } + if offset == 0 && limit == 0 { + fmt.Println(sql) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return + } + fmt.Println(sql) + logger.Info("查询镜像,os sql:", sql) + err = dao.Raw(logger, dao.IronicRdb, sql).Offset(offset).Limit(limit).Scan(&ml).Error + return +} + +// QueryByDeviceOsType ... +func QueryByDeviceOsType(logger *log.Logger, param map[string]string) (ml []*DImage, err error) { + + sql := `select i.id,i.image_id,i.image_name,i.image_version,i.format,i.boot_mode,i.url,i.filename,i.description,i.os_id,i.hash,i.source, + i.created_by,i.updated_by,i.created_time,i.updated_time FROM image i` + if param["device_type"] != "" { + sql = sql + " LEFT JOIN r_device_type_image rd on i.uuid=rd.image_id" + } + if param["region"] != "" { + sql = sql + " LEFT JOIN r_region_image re on i.uuid=re.image_id" + } + sql = sql + " LEFT JOIN os o on i.os_id=o.os_id" + where := " where 1 = 1" + if param["device_type"] != "" { + where = where + " and rd.device_type=" + fmt.Sprintf("'%s'", param["device_type"]) + } + if param["region"] != "" { + where = where + " and re.region=" + fmt.Sprintf("'%s'", param["region"]) + } + if param["os_type"] != "" { + where = where + " and o.os_type=" + fmt.Sprintf("'%s'", param["os_type"]) + } + if param["os_version"] != "" { + where = where + " and o.os_version=" + fmt.Sprintf("'%s'", param["os_version"]) + } + if param["os_id"] != "" { + where = where + " and i.os_id=" + fmt.Sprintf("'%s'", param["os_id"]) + } + if param["name_en"] != "" { + where = where + fmt.Sprintf(" and i.name_en LIKE '%%s%'", param["name_en"]) + } + if param["image_ids"] != "" { + imageIds := strings.Split(param["image_ids"], ",") + for idx, v := range imageIds { + imageIds[idx] = fmt.Sprintf("'%s'", v) + } + inSql := fmt.Sprintf("(%s)", strings.Join(imageIds, ",")) + where = where + fmt.Sprintf(" and i.uuid in %s", inSql) + } + if param["source"] != "" { + where = where + fmt.Sprintf(" and i.source='%s'", param["source"]) + } + if param["device_type"] != "" { + where = where + " and rd.is_del=0" + } + if param["region"] != "" { + where = where + " and re.is_del=0" + } + sql = sql + where + " and i.is_del=0 and o.is_del=0" + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-openapi/dao/instanceDao/instanceDao.go b/bmp-openapi/dao/instanceDao/instanceDao.go new file mode 100644 index 0000000..eac39a4 --- /dev/null +++ b/bmp-openapi/dao/instanceDao/instanceDao.go @@ -0,0 +1,193 @@ +package instanceDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Instance Instance +type Instance struct { + ID int `gorm:"primaryKey;column:id" json:"-"` + InstanceID string `gorm:"column:instance_id" json:"instanceId"` // 实例ID(uuid) + IDcID string `gorm:"column:idc_id" json:"idcId"` // 机房uuid + ProjectID string `gorm:"column:project_id" json:"projectId"` // 项目id + UserID string `gorm:"column:user_id" json:"userId"` // 用户uuid + InstanceName string `gorm:"column:instance_name" json:"instanceName"` // 实例名称 + DeviceID string `gorm:"column:device_id" json:"deviceId"` // 设备uuid + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 机型uuid + Hostname string `gorm:"column:hostname" json:"hostname"` // 主机名 + Status string `gorm:"column:status" json:"status"` // 失败原因 + Reason string `gorm:"column:reason" json:"reason"` // 运行状态 + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像uuid + SystemVolumeRaidID string `gorm:"column:system_volume_raid_id" json:"systemVolumeRaidId"` // 系统盘raid + Locked string `gorm:"column:locked" json:"locked"` // 是否锁定解锁锁定:locked,解锁unlocked + DataVolumeRaidID string `gorm:"column:data_volume_raid_id" json:"dataVolumeRaidId"` // 数据盘raid + Description string `gorm:"column:description" json:"description"` // 描述 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 + BootMode string `gorm:"column:boot_mode" json:"bootMode"` // boot类型:UEFI Legacy/BIOS +} + +func (t *Instance) TableName() string { + return "instance" +} + +// AddInstance insert a new Instance into database and returns +// last inserted Id on success. +func AddInstance(logger *log.Logger, m *Instance) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetInstanceById retrieves Instance by Id. Returns error if +// Id doesn't exist +func GetInstanceByName(logger *log.Logger, name string) (v *Instance, err error) { + v = &Instance{} + err = dao.Where(logger, dao.IronicRdb, "instance_name = ? and is_del = 0", name).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetInstanceById retrieves Instance by Id. Returns error if +// Id doesn't exist +func GetInstanceById(logger *log.Logger, InstanceId string) (v *Instance, err error) { + v = &Instance{} + err = dao.Where(logger, dao.IronicRdb, "instance_id = ? and is_del = 0", InstanceId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetInstancesByIds retrieves Instance by Ids. Returns error if +// Id doesn't exist +func GetInstancesByIds(logger *log.Logger, InstanceIds []string) (v []*Instance, err error) { + q := map[string]interface{}{ + "instance_id.in": InstanceIds, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, q) + if err != nil { + return nil, err + } + err = db.Find(&v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetInstanceById retrieves Instance by Id. Returns error if +// Id doesn't exist +func GetInstanceByDeviceId(logger *log.Logger, DeviceId string) (v *Instance, err error) { + v = &Instance{} + err = dao.Where(logger, dao.IronicRdb, "device_id = ? and is_del = 0", DeviceId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetInstanceByUuid retrieves Instance by Uuid. Returns error if +// Id doesn't exist +func GetInstanceCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAllInstance retrieves all Instance matches certain condition. Returns empty list if +// no records exist +func GetAllInstance(logger *log.Logger, query map[string]interface{}) (ml []*Instance, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiInstance retrieves all Instance matches certain condition. Returns empty list if +// no records exist +func GetMultiInstance(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Instance, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateInstance updates Instance by Id and returns error if +// the record to be updated doesn't exist +func UpdateInstanceById(logger *log.Logger, m *Instance) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Instance{}).Where("instance_id = ?", m.InstanceID).Updates(m).Error +} + +// description为空也有可能 +func UpdateInstanceAnywhere(logger *log.Logger, m *Instance) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Instance{}).Save(m).Error +} + +func UpdateInstances(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return + +} + +type UserInstanceCount struct { + UserID string `json:"user_id"` + Count int64 `json:"count"` +} + +func GetInstanceCountGroupByUser(logger *log.Logger) ([]*UserInstanceCount, error) { + ml := []*UserInstanceCount{} + sql := `select user_id, count(1) as count from instance group by user_id, is_del having is_del = 0` + err := dao.Raw(logger, dao.IronicRdb, sql).Find(&ml).Error + return ml, err +} diff --git a/bmp-openapi/dao/instancePartitionDao/instancePartitionDao.go b/bmp-openapi/dao/instancePartitionDao/instancePartitionDao.go new file mode 100644 index 0000000..62799c3 --- /dev/null +++ b/bmp-openapi/dao/instancePartitionDao/instancePartitionDao.go @@ -0,0 +1,142 @@ +package instancePartitionDao + +import ( + "time" + + log "coding.jd.com/aidc-bmp/bmp_log" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" +) + +// InstancePartition 实例分区表 +type InstancePartition struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + InstanceID string `gorm:"column:instance_id" json:"instanceId"` // 实例ID + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像ID + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型 + BootMode string `gorm:"column:boot_mode" json:"bootMode"` // boot类型:bios、uefi + PartitionType string `gorm:"column:partition_type" json:"partitionType"` // 分区类型:root、boot、system、data + PartitionSize int `gorm:"column:partition_size" json:"partitionSize"` // 分区大小,单位MB + PartitionFsType string `gorm:"column:partition_fs_type" json:"partitionFsType"` // 文件系统类型:xfs + PartitionMountPoint string `gorm:"column:partition_mount_point" json:"partitionMountPoint"` // 分区目录 + PartitionLabel string `gorm:"column:partition_label" json:"partitionLabel"` // 分区标签:l_分区目录 + SystemDiskLabel string `gorm:"column:system_disk_label" json:"systemDiskLabel"` // 系统盘分区格式:gpt、msdos(做完RAID系统盘大于4T必用gpt) + DataDiskLabel string `gorm:"column:data_disk_label" json:"dataDiskLabel"` // 数据盘分区格式:gpt、msdos + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除(0-未删, 1-已删) + InstancePartitionID string `gorm:"column:instance_partition_id" json:"instancePartitionId"` // 实例分区uuID + Number int `gorm:"column:number" json:"number"` // 每个实例的分区序号 +} + +func (t *InstancePartition) TableName() string { + return "instance_partition" +} + +// AddInstancePartition insert a new InstancePartition into database and returns +// last inserted Id on success. +func AddInstancePartition(logger *log.Logger, m *InstancePartition) (id int64, err error) { + + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// //TODO 有时间试试gorm v2支持的批量插入 +func AddMultiInstancePartition(logger *log.Logger, m []*InstancePartition) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, instancePartition := range m { + if err := tx.Create(instancePartition).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetInstancePartitionById retrieves InstancePartition by Id. Returns error if +// Id doesn't exist +func GetInstancePartitionById(logger *log.Logger, id int64) (v *InstancePartition, err error) { + v = &InstancePartition{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllInstancePartition retrieves all InstancePartition matches certain condition. Returns empty list if +// no records exist +func GetAllInstancePartition(logger *log.Logger, query map[string]interface{}) (ml []*InstancePartition, err error) { + + var db = dao.Model(logger, dao.IronicRdb, InstancePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetOneInstancePartition(logger *log.Logger, query map[string]interface{}) (l *InstancePartition, err error) { + l = &InstancePartition{} + var db = dao.Model(logger, dao.IronicRdb, InstancePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// UpdateInterface updates Interface by Id and returns error if +// the record to be updated doesn't exist +func UpdateInstancePartitionById(logger *log.Logger, m *InstancePartition) (err error) { + return dao.Model(logger, dao.IronicWdb, InstancePartition{}).Where(logger, dao.IronicRdb, "id = ?", m.ID).Updates(m).Error +} + +func GetBySn(logger *log.Logger, sn string) (ml []*InstancePartition, err error) { + ml = []*InstancePartition{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and is_del = 0", sn).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil + +} + +func GetByInstanceId(logger *log.Logger, instanceId string) (ml []*InstancePartition, err error) { + ml = []*InstancePartition{} + err = dao.Where(logger, dao.IronicRdb, "instance_id = ? and is_del = 0", instanceId).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil + +} + +func DeletePartitionsByInstanceId(logger *log.Logger, instanceId string) (err error) { + + query := map[string]interface{}{ + "instance_id": instanceId, + } + + updates := map[string]interface{}{ + "is_del": 1, + "updated_time": time.Now().Unix(), + } + var db = dao.Model(logger, dao.IronicWdb, InstancePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} diff --git a/bmp-openapi/dao/instanceUserDataDao/instanceUserDataDao.go b/bmp-openapi/dao/instanceUserDataDao/instanceUserDataDao.go new file mode 100644 index 0000000..2c3d69b --- /dev/null +++ b/bmp-openapi/dao/instanceUserDataDao/instanceUserDataDao.go @@ -0,0 +1,104 @@ +package instanceUserDataDao + +import ( + "time" + + log "coding.jd.com/aidc-bmp/bmp_log" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" +) + +// InstanceUserData 用户自定义脚本表 +type InstanceUserData struct { + ID uint64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"-"` // ID + InstanceID string `gorm:"unique;column:instance_id;type:varchar(36);not null" json:"instance_id"` // 实例ID + UserData string `gorm:"column:user_data;type:mediumtext" json:"user_data"` // 用户自定义脚本 + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(3) unsigned;not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *InstanceUserData) TableName() string { + return "instance_user_data" +} + +// AddInstanceUserData insert a new InstanceUserData into database and returns +// last inserted Id on success. +func AddInstanceUserData(logger *log.Logger, m *InstanceUserData) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// //TODO 有时间试试gorm v2支持的批量插入 +func AddMultiInstanceUserData(logger *log.Logger, m []*InstanceUserData) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, instanceUserData := range m { + instanceUserData.CreateTime = time.Now() + instanceUserData.UpdateTime = time.Now() + if err := tx.Create(instanceUserData).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetInstanceUserDataById retrieves InstanceUserData by Id. Returns error if +// Id doesn't exist +func GetInstanceUserDataById(logger *log.Logger, id int64) (v *InstanceUserData, err error) { + v = &InstanceUserData{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllInstanceUserData retrieves all InstanceUserData matches certain condition. Returns empty list if +// no records exist +func GetAllInstanceUserData(logger *log.Logger, query map[string]interface{}) (ml []*InstanceUserData, err error) { + + var db = dao.Model(logger, dao.IronicRdb, InstanceUserData{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetOneInstanceUserData(logger *log.Logger, query map[string]interface{}) (l *InstanceUserData, err error) { + l = &InstanceUserData{} + var db = dao.Model(logger, dao.IronicRdb, InstanceUserData{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// UpdateInstanceUserDataById updates InstanceUserData by Id and returns error if +// the record to be updated doesn't exist +func UpdateInstanceUserDataById(logger *log.Logger, m *InstanceUserData) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, InstanceUserData{}).Where(logger, dao.IronicRdb, "id = ?", m.ID).Updates(m).Error +} + +func GetByInstanceId(logger *log.Logger, instanceId string) (l *InstanceUserData, err error) { + l = &InstanceUserData{} + err = dao.Where(logger, dao.IronicRdb, "instance_id = ? and is_del = 0", instanceId).Take(l).Error + if err != nil { + return nil, err + } + return l, nil + +} diff --git a/bmp-openapi/dao/interfaceDao/interfaceDao.go b/bmp-openapi/dao/interfaceDao/interfaceDao.go new file mode 100644 index 0000000..dbf3690 --- /dev/null +++ b/bmp-openapi/dao/interfaceDao/interfaceDao.go @@ -0,0 +1,157 @@ +package interfaceDao + +import ( + "fmt" + "strings" + "time" + + log "coding.jd.com/aidc-bmp/bmp_log" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" +) + +type Interface struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + InterfaceName string `gorm:"column:interface_name;type:varchar(16)" json:"interface_name"` // 网卡名称 + InterfaceType string `gorm:"column:interface_type;type:varchar(16)" json:"interface_type"` // 网卡类型:lan/wan + Sn string `gorm:"index:i_interface_sn;column:sn;type:varchar(64);not null" json:"sn"` // 设备SN + Mac string `gorm:"column:mac;type:varchar(32);not null" json:"mac"` // MAC + SwitchIP string `gorm:"column:switch_ip;type:varchar(32);not null" json:"switch_ip"` // 内网交换机IP + SwitchPort string `gorm:"column:switch_port;type:varchar(32);default:null" json:"switch_port"` // 内网交换机Port + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删。1-已删) +} + +func (t *Interface) TableName() string { + return "interface" +} + +// AddInterface insert a new Interface into database and returns +// last inserted Id on success. +func AddInterface(logger *log.Logger, m *Interface) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetInterfaceById retrieves Interface by Id. Returns error if +// Id doesn't exist +func GetInterfaceById(logger *log.Logger, id int64) (v *Interface, err error) { + v = &Interface{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetAllInterface(logger *log.Logger, query map[string]interface{}) (ml []*Interface, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Interface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetOneInterface(logger *log.Logger, query map[string]interface{}) (l *Interface, err error) { + l = &Interface{} + var db = dao.Model(logger, dao.IronicRdb, Interface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// GetAllInterface retrieves all Interface matches certain condition. Returns empty list if +// no records exist +func GetMultiInterface(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Interface, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Interface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateInterface updates Interface by Id and returns error if +// the record to be updated doesn't exist +func UpdateInterfaceById(logger *log.Logger, m *Interface) (err error) { + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Interface{}).Where(logger, dao.IronicRdb, "id = ?", m.ID).Updates(m).Error +} +func DeleteInterfaceBySn(logger *log.Logger, m *Interface) (err error) { + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Interface{}).Where("sn = ?", m.Sn).Delete(m).Error +} +func UpdateMultiInterfaces(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["update_time"] = time.Now() + var db = dao.Model(logger, dao.IronicWdb, Interface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +type DInterface struct { + Sn string `json:"sn"` + InterfaceName string `json:"interface_name"` + InterfaceType string `json:"interface_type"` + Mac string `json:"mac"` + SwitchIp string `json:"switch_ip"` + SwitchPort string `json:"switch_port"` + PodName string `json:"pod_name"` + PodRoom string `json:"pod_room"` + CreateTime time.Time `json:"create_time"` + UpdateTime time.Time `json:"update_time"` +} + +func GetBySn(logger *log.Logger, sn string) (ml []*Interface, err error) { + + ml = []*Interface{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and is_del = 0", sn).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil + +} + +func GetBySns(logger *log.Logger, sns []string) (ml []*DInterface, err error) { + + sql := `select i.sn,i.interface_name,i.interface_type,i.mac,i.switch_ip,i.switch_port,i.create_time,i.update_time,n.name as pod_name,n.room as pod_room FROM interface i LEFT JOIN jd_switch j ON i.switch_ip = j.switch_ip LEFT JOIN net_pod n ON j.pod_id=n.id where 1=1` + for idx, v := range sns { + sns[idx] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and i.sn in (%s) and i.is_del=0 and j.is_del=0 and n.is_del=0", strings.Join(sns, ",")) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-openapi/dao/jdBondInterfaceDao/jdBondInterfaceDao.go b/bmp-openapi/dao/jdBondInterfaceDao/jdBondInterfaceDao.go new file mode 100644 index 0000000..65bff0f --- /dev/null +++ b/bmp-openapi/dao/jdBondInterfaceDao/jdBondInterfaceDao.go @@ -0,0 +1,90 @@ +package jdBondInterfaceDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// JdBondInterface 零售中台网络端口Bond表 +type JdBondInterface struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // 自增id + GroupID int `gorm:"column:group_id;type:int(11)" json:"group_id"` // 端口聚合组ID + Sn string `gorm:"index:i_sn;column:sn;type:varchar(64);not null" json:"sn"` // 设备sn + SwitchIP string `gorm:"index:i_switchIp;column:switch_ip;type:varchar(32);not null" json:"switch_ip"` // 交换机ip + PrivateIP string `gorm:"column:private_ip;type:varchar(30)" json:"private_ip"` // 内网IP + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime;not null" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(2);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *JdBondInterface) TableName() string { + return "jd_bond_interface" +} + +// AddJdBondInterface insert a new JdBondInterface into database and returns +// last inserted Id on success. +func AddJdBondInterface(logger *log.Logger, m *JdBondInterface) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetJdBondInterfaceById retrieves JdBondInterface by Id. Returns error if +// Id doesn't exist +func GetJdBondInterfaceById(logger *log.Logger, id int64) (v *JdBondInterface, err error) { + v = &JdBondInterface{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetAllJdBondInterface(logger *log.Logger, query map[string]interface{}) (ml []*JdBondInterface, err error) { + + var db = dao.Model(logger, dao.IronicRdb, JdBondInterface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiJdBondInterface retrieves all JdBondInterface matches certain condition. Returns empty list if +// no records exist +func GetMultiJdBondInterface(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*JdBondInterface, err error) { + + var db = dao.Model(logger, dao.IronicRdb, JdBondInterface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateJdBondInterface updates JdBondInterface by Id and returns error if +// the record to be updated doesn't exist +func UpdateJdBondInterfaceById(logger *log.Logger, m *JdBondInterface) (err error) { + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, JdBondInterface{}).Where(logger, dao.IronicRdb, "id = ?", m.ID).Updates(m).Error //update 有问题,参考下面这个方法 +} +func DeleteJdBondInterfaceBySn(logger *log.Logger, m *JdBondInterface) (err error) { + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, JdBondInterface{}).Where("sn = ?", m.Sn).Updates(m).Error +} diff --git a/bmp-openapi/dao/jdSwitchDao/jdSwitchDao.go b/bmp-openapi/dao/jdSwitchDao/jdSwitchDao.go new file mode 100644 index 0000000..9de7b17 --- /dev/null +++ b/bmp-openapi/dao/jdSwitchDao/jdSwitchDao.go @@ -0,0 +1,125 @@ +package jdSwitchDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// JdSwitch 零售中台网络交换机表 +type JdSwitch struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // 自增id + Region string `gorm:"unique;column:region;type:varchar(32);not null" json:"region"` // region + SwitchIP string `gorm:"unique;column:switch_ip;type:varchar(32);not null" json:"switch_ip"` // 交换机ip + Cidr string `gorm:"column:cidr;type:varchar(32)" json:"cidr"` // 配置的内网cidr + Mask string `gorm:"column:mask;type:varchar(32)" json:"mask"` // 配置的内网掩码 + Gateway string `gorm:"column:gateway;type:varchar(32)" json:"gateway"` // 配置的网关 + PodID int `gorm:"column:pod_id;type:int(11)" json:"pod_id"` // pod网络id + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime;not null" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(2);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *JdSwitch) TableName() string { + return "jd_switch" +} + +// AddJdSwitch insert a new JdSwitch into database and returns +// last inserted Id on success. +func AddJdSwitch(logger *log.Logger, m *JdSwitch) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetJdSwitchById retrieves JdSwitch by Id. Returns error if +// Id doesn't exist +func GetJdSwitchById(logger *log.Logger, id int64) (v *JdSwitch, err error) { + v = &JdSwitch{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetOneJdSwitch(logger *log.Logger, query map[string]interface{}) (l *JdSwitch, err error) { + l = &JdSwitch{} + var db = dao.Model(logger, dao.IronicRdb, JdSwitch{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetSwitchCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, JdSwitch{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return + +} + +// GetAllJdSwitch retrieves all JdSwitch matches certain condition. Returns empty list if +// no records exist +func GetAllJdSwitch(logger *log.Logger, query map[string]interface{}) (ml []*JdSwitch, err error) { + + var db = dao.Model(logger, dao.IronicRdb, JdSwitch{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiJdSwitch retrieves pages JdSwitch matches certain condition. Returns empty list if +// no records exist +func GetMultiJdSwitch(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*JdSwitch, err error) { + + var db = dao.Model(logger, dao.IronicRdb, JdSwitch{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateJdSwitch updates JdSwitch by Id and returns error if +// the record to be updated doesn't exist +func UpdateJdSwitchById(logger *log.Logger, m *JdSwitch) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, JdSwitch{}).Where("id = ?", m.ID).Updates(m).Error +} + +func GetBySwitchIp(logger *log.Logger, switch_ip string) (v *JdSwitch, err error) { + v = &JdSwitch{} + err = dao.Where(logger, dao.IronicRdb, "switch_ip = ? and is_del = 0", switch_ip).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} diff --git a/bmp-openapi/dao/mailDao/mailDao.go b/bmp-openapi/dao/mailDao/mailDao.go new file mode 100644 index 0000000..9a27160 --- /dev/null +++ b/bmp-openapi/dao/mailDao/mailDao.go @@ -0,0 +1,70 @@ +package mailDao + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// MailMessage message +type MailMessage struct { + //以下为消息通用字段 + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + // 邮件服务器地址 + ServerAddr string `gorm:"column:server_addr;type:varchar(255);not null" json:"server_addr"` + // 邮件服务器端口 + ServerPort string `gorm:"column:server_port;type:varchar(255);not null" json:"server_port"` + // 管理员邮箱 + AdminAddr string `gorm:"column:admin_addr;type:varchar(255);not null" json:"admin_addr"` + // 管理员邮箱密码 + AdminPass string `gorm:"column:admin_pass;type:varchar(255);not null" json:"admin_pass"` + //收件人邮箱 + To string `gorm:"column:to;type:varchar(255);not null" json:"to"` + // 是否推送邮件告警0不推送,1推送 + IsPush string `gorm:"column:is_push;type:type:varchar(8);not null" json:"is_push"` + // 是否删除0未删除 1已删除 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` + // 是否验证过邮件功能ok + IsPass string `gorm:"column:is_pass;type:type:varchar(8);not null" json:"is_pass"` +} + +func (t *MailMessage) TableName() string { + return "mail_message" +} + +// AddMailMessage insert a new Os into database and returns +// last inserted Id on success. +func AddMailMessage(logger *log.Logger, m *MailMessage) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetMailMessage retrieves Os by Id. Returns error if +// Id doesn't exist +func GetMailMessage(logger *log.Logger) (v *MailMessage, err error) { + v = &MailMessage{} + err = dao.Where(logger, dao.IronicRdb, "is_del = 0").Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func UpdateMailMessage(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, MailMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func UpdateMailAnywhere(logger *log.Logger, m *MailMessage) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, MailMessage{}).Save(m).Error +} diff --git a/bmp-openapi/dao/manufacturerDao/manufacturerDao.go b/bmp-openapi/dao/manufacturerDao/manufacturerDao.go new file mode 100644 index 0000000..37d39af --- /dev/null +++ b/bmp-openapi/dao/manufacturerDao/manufacturerDao.go @@ -0,0 +1,87 @@ +package manufacturerDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Manufacturer 产品型号信息 +type Manufacturer struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + DeviceType string `gorm:"column:device_type;type:varchar(100);not null" json:"device_type"` // 设备类型 + Manufacturer string `gorm:"column:manufacturer;type:varchar(64);not null" json:"manufacturer"` // 厂商 + ProductName string `gorm:"column:product_name;type:varchar(128);not null" json:"product_name"` // 产品型号名称 + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除:1删除,0未删除 +} + +func (t *Manufacturer) TableName() string { + return "manufacturer" +} + +// AddManufacturer insert a new Manufacturer into database and returns +// last inserted Id on success. +func AddManufacturer(logger *log.Logger, m *Manufacturer) (id int64, err error) { + + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetManufacturerById retrieves Manufacturer by Id. Returns error if +// Id doesn't exist +func GetManufacturerById(logger *log.Logger, id int64) (v *Manufacturer, err error) { + v = &Manufacturer{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllManufacturer retrieves all Manufacturer matches certain condition. Returns empty list if +// no records exist +func GetAllManufacturer(logger *log.Logger, query map[string]interface{}) (ml []*Manufacturer, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Manufacturer{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetMultiManufacturer(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Manufacturer, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Manufacturer{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateManufacturer updates Manufacturer by Id and returns error if +// the record to be updated doesn't exist +func UpdateManufacturerById(logger *log.Logger, m *Manufacturer) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Manufacturer{}).Where("id = ?", m.ID).Updates(m).Error +} diff --git a/bmp-openapi/dao/messageDao/messageDao.go b/bmp-openapi/dao/messageDao/messageDao.go new file mode 100644 index 0000000..eea12cf --- /dev/null +++ b/bmp-openapi/dao/messageDao/messageDao.go @@ -0,0 +1,196 @@ +package messageDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// WebMessage message +type WebMessage struct { + //以下为消息通用字段 + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + // message uuid + MessageID string `gorm:"column:message_id;type:varchar(255);not null" json:"message_id"` + // user_id + UserID string `gorm:"index:i_message_userid;column:user_id;type:varchar(255);not null" json:"user_id"` + // user_name + UserName string `gorm:"column:user_name;type:varchar(255);not null" json:"user_name"` + // 资源类型 实例/设备 + ResourceType string `gorm:"column:resource_type;type:varchar(255);not null" json:"resource_type"` + // 操作结果 fail/succ + Result string `gorm:"column:result;type:varchar(255);not null" json:"result"` + // 消息时间戳 + FinishTime int `gorm:"column:finish_time;type:int(11);not null" json:"finish_time"` + // 0未读, 1已读 + HasRead int8 `gorm:"index:i_message_read;column:has_read;type:tinyint(4);not null" json:"has_read"` + // 是否删除0未删除 1已删除 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` + // 消息类型 + MessageType string `gorm:"column:message_type;type:varchar(255);not null" json:"message_type"` + // 消息子类型 + MessageSubType string `gorm:"column:message_sub_type;type:varchar(255);not null" json:"message_sub_type"` + //实例id + InstanceID string `gorm:"column:instance_id;type:varchar(255);not null" json:"instance_id"` + // 实例name + InstanceName string `gorm:"column:instance_name;type:varchar(255);not null" json:"instance_name"` + //设备sn + SN string `gorm:"column:sn;type:varchar(255);not null" json:"sn"` + // 详情, 带外监控日志的详情请用content + Detail string `gorm:"column:detail;type:varchar(4096);not null" json:"detail"` + + //故障类型, 带外故障消息专属字段 + FaultType string `gorm:"column:fault_type;type:varchar(10);not null" json:"fault_type"` + //故障内容,带外故障消息专属字段 + Content string `gorm:"column:content;type:varchar(4096);not null" json:"content"` + //系统原始日志id, 带外故障消息专属字段 + LogID string `gorm:"column:logid;type:varchar(256);not null" json:"logid"` + //故障告警时间,带外故障消息专属字段 + AlertTime int `gorm:"column:alert_time;type:int(11);not null" json:"alert_time"` + //告警次数,始终为1,带外故障消息专属字段 + AlertCount int `gorm:"column:alert_count;type:int(11);not null" json:"alert_count"` + + //版本名称, 许可证到期消息专属字段 + LicenseName string `gorm:"column:license_name;type:varchar(64);not null" json:"license_name"` + //版本号, 许可证到期消息专属字段 + LicenseNumber string `gorm:"column:license_number;type:varchar(64);not null" json:"license_number"` + //开始时间, 许可证到期消息专属字段 + LienseStartTime int `gorm:"column:license_start_time;type:int(11);not null" json:"license_start_time"` + //结束时间, 许可证到期消息专属字段 + LienseEndTime int `gorm:"column:license_end_time;type:int(11);not null" json:"license_end_time"` + //inbond rule uuid + RuleID string `gorm:"column:rule_id;type:varchar(256);not null" json:"rule_id"` + //inbond rule name + RuleName string `gorm:"column:rule_name;type:varchar(256);not null" json:"rule_name"` +} + +func (t *WebMessage) TableName() string { + return "web_message" +} + +// AddWebMessage insert a new Os into database and returns +// last inserted Id on success. +func AddWebMessage(logger *log.Logger, m *WebMessage) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetOsById retrieves Os by Id. Returns error if +// Id doesn't exist +func GetWebMessageById(logger *log.Logger, id int64) (v *WebMessage, err error) { + v = &WebMessage{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllOs retrieves all os matches certain condition. Returns empty list if +// no records exist +func GetAllWebMessagesByUserId(logger *log.Logger, userId string) (ml []*WebMessage, err error) { + + query := map[string]interface{}{ + "user_id": userId, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicRdb, WebMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return + +} + +// GetMultiOs retrieves all Os matches certain condition. Returns empty list if +// no records exist +func GetMultiWebMessagesByUserId(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*WebMessage, err error) { + + var db = dao.Model(logger, dao.IronicRdb, WebMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateOs updates Os by Id and returns error if +// the record to be updated doesn't exist +func UpdateOsById(logger *log.Logger, m *WebMessage) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, WebMessage{}).Where("id = ?", m.ID).Updates(m).Error +} + +func GetOneWebMessage(logger *log.Logger, query map[string]interface{}, idOrder string) (v *WebMessage, err error) { + v = &WebMessage{} + var db = dao.Model(logger, dao.IronicWdb, WebMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if idOrder == "desc" { + err = db.Order("id desc").Limit(1).Take(v).Error + } else { + err = db.Order("id asc").Limit(1).Take(v).Error + } + + if err != nil { + return nil, err + } + return v, nil +} + +func GetWebMessagesByUserIdCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, WebMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +func GetAllWebMessages(logger *log.Logger, query map[string]interface{}) (ml []*WebMessage, err error) { + + var db = dao.Model(logger, dao.IronicRdb, WebMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func UpdateWebMessages(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, WebMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return + +} diff --git a/bmp-openapi/dao/monitorAlertDao/monitorAlertDao.go b/bmp-openapi/dao/monitorAlertDao/monitorAlertDao.go new file mode 100644 index 0000000..20d4209 --- /dev/null +++ b/bmp-openapi/dao/monitorAlertDao/monitorAlertDao.go @@ -0,0 +1,154 @@ +package monitorAlertDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// MonitorAlerts 告警历史表 +type MonitorAlerts struct { + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + AlertID string `gorm:"index:i_rule_id;column:alert_id;type:varchar(255);not null" json:"alert_id"` // alert uuid + AlertTime int `gorm:"column:alert_time;type:int(11);not null" json:"alert_time"` // 告警时间戳 + RuleID string `gorm:"index:i_rule_id;column:rule_id;type:varchar(255);not null" json:"rule_id"` // rule uuid + RuleName string `gorm:"column:rule_name;type:varchar(255);not null" json:"rule_name"` // rule name + Resource string `gorm:"column:resource;type:varchar(255);not null" json:"resource"` // 资源类型 [只支持instance一种] + ResourceID string `gorm:"column:resource_id;type:varchar(255);not null" json:"resource_id"` // 资源id,目前就是实例id + ResourceName string `gorm:"column:resource_name;type:varchar(255);not null" json:"resource_name"` // 资源名称,目前就是实例名称 + Trigger string `gorm:"column:trigger;type:varchar(255);not null" json:"trigger"` // 触发条件,接口需要翻译 + AlertValue string `gorm:"column:alert_value;type:varchar(255);not null" json:"alert_value"` // 报警值 + CalculationUnit string `gorm:"column:calculation_unit;type:varchar(255);not null" json:"calculation_unit"` // 单位,%,GB,bps等,个没有单位 + AlertLevel int8 `gorm:"column:alert_level;type:tinyint(4);not null" json:"alert_level"` // 1表示一般,2表示严重,3表示紧急 + AlertPeriod int `gorm:"column:alert_period;type:int(11);not null" json:"alert_period"` // 告警持续时间(分钟为单位) + UserID string `gorm:"column:user_id;type:varchar(255);not null" json:"user_id"` // 通知对象 userid + UserName string `gorm:"column:user_name;type:varchar(255);not null" json:"user_name"` // 通知对象 用户名 + CreatedTime int `gorm:"column:created_time;type:int(11);not null" json:"created_time"` // 创建时间戳 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 +} + +func (t *MonitorAlerts) TableName() string { + return "monitor_alerts" +} + +// AddWebMessage insert a new Os into database and returns +// last inserted Id on success. +func AddMonitorAlerts(logger *log.Logger, m *MonitorAlerts) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func GetMonitorAlertsById(logger *log.Logger, alertId string) (v *MonitorAlerts, err error) { + v = &MonitorAlerts{} + err = dao.Where(logger, dao.IronicRdb, "alert_id = ? and is_del = 0", alertId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllOs retrieves all os matches certain condition. Returns empty list if +// no records exist +func GetAllMonitorAlertsByUserId(logger *log.Logger, userId string) (ml []*MonitorAlerts, err error) { + + query := map[string]interface{}{ + "user_id": userId, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicRdb, MonitorAlerts{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return + +} + +func GetAllMonitorAlertsByRuleId(logger *log.Logger, RuleId string) (ml []*MonitorAlerts, err error) { + + query := map[string]interface{}{ + "rule_id": RuleId, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicRdb, MonitorAlerts{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return + +} + +func GetMonitorAlertsCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, MonitorAlerts{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetMultiOs retrieves all Os matches certain condition. Returns empty list if +// no records exist +func GetMultiMonitorAlerts(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*MonitorAlerts, err error) { + + var db = dao.Model(logger, dao.IronicRdb, MonitorAlerts{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetAllMonitorAlerts(logger *log.Logger, query map[string]interface{}) (ml []*MonitorAlerts, err error) { + + var db = dao.Model(logger, dao.IronicRdb, MonitorAlerts{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// UpdateOs updates Os by Id and returns error if +// the record to be updated doesn't exist +func UpdateMonitorAlerts(logger *log.Logger, m *MonitorAlerts) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, MonitorAlerts{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateMultiMonitorAlerts(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, MonitorAlerts{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return + +} diff --git a/bmp-openapi/dao/monitorRuleDao/monitorRuleDao.go b/bmp-openapi/dao/monitorRuleDao/monitorRuleDao.go new file mode 100644 index 0000000..a1a13ac --- /dev/null +++ b/bmp-openapi/dao/monitorRuleDao/monitorRuleDao.go @@ -0,0 +1,136 @@ +package monitorRuleDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// MonitorRules 带内监控规则表 +type MonitorRules struct { + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + RuleID string `gorm:"index:i_rule_id;column:rule_id;type:varchar(255);not null" json:"rule_id"` // rule uuid + Status int8 `gorm:"column:status;type:tinyint(4);not null" json:"status"` // 1表示启用 2表示不启用 3表示已告警 + RuleName string `gorm:"column:rule_name;type:varchar(255);not null" json:"rule_name"` // 规则名称 + Dimension string `gorm:"column:dimension;type:varchar(255);not null" json:"dimension"` // 维度 [instance disk mountpoint nic] + Resource string `gorm:"column:resource;type:varchar(255);not null" json:"resource"` // 资源类型 [只支持instance一种] + TriggerOption string `gorm:"column:trigger_option;type:varchar(255);not null" json:"trigger_option"` // 触发条件, json + NoticeOption string `gorm:"column:notice_option;type:varchar(255);not null" json:"notice_option"` // 通知策略, json + CreatedTime int `gorm:"column:created_time;type:int(11);not null" json:"created_time"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time;type:int(11);not null" json:"updated_time"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time;type:int(11);not null" json:"deleted_time"` // 更新时间戳 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 + UserID string `gorm:"column:user_id;type:varchar(255);not null" json:"user_id"` // user uuid + UserName string `gorm:"column:user_name;type:varchar(255);not null" json:"user_name"` // user name + +} + +func (t *MonitorRules) TableName() string { + return "monitor_rules" +} + +// AddWebMessage insert a new Os into database and returns +// last inserted Id on success. +func AddMonitorRules(logger *log.Logger, m *MonitorRules) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func GetMonitorRuleById(logger *log.Logger, ruleId string) (v *MonitorRules, err error) { + v = &MonitorRules{} + err = dao.Where(logger, dao.IronicRdb, "rule_id = ? and is_del = 0", ruleId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllOs retrieves all os matches certain condition. Returns empty list if +// no records exist +func GetAllMonitorRulesByUserId(logger *log.Logger, userId string) (ml []*MonitorRules, err error) { + + query := map[string]interface{}{ + "user_id": userId, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicRdb, MonitorRules{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return + +} + +func GetMonitorRulesCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, MonitorRules{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetMultiOs retrieves all Os matches certain condition. Returns empty list if +// no records exist +func GetMultiMonitorRules(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*MonitorRules, err error) { + + var db = dao.Model(logger, dao.IronicRdb, MonitorRules{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetAllMonitorRules(logger *log.Logger, query map[string]interface{}) (ml []*MonitorRules, err error) { + + var db = dao.Model(logger, dao.IronicRdb, MonitorRules{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// UpdateOs updates Os by Id and returns error if +// the record to be updated doesn't exist +func UpdateMonitorRules(logger *log.Logger, m *MonitorRules) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, MonitorRules{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateMultiMonitorRules(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, MonitorRules{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return + +} diff --git a/bmp-openapi/dao/osDao/osDao.go b/bmp-openapi/dao/osDao/osDao.go new file mode 100644 index 0000000..1e8be30 --- /dev/null +++ b/bmp-openapi/dao/osDao/osDao.go @@ -0,0 +1,110 @@ +package osDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Os os +type Os struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + OsID string `gorm:"column:os_id" json:"osId"` // 操作系统uuid + OsName string `gorm:"column:os_name" json:"OsName"` // 操作系统名称 + OsType string `gorm:"column:os_type" json:"osType"` // 操作系统分类:linux/windows + //Platform string `gorm:"column:platform" json:"platform"` // suse/centos/ubuntu + Architecture string `gorm:"column:architecture" json:"architecture"` // 架构:x86/x64/i386/ + Bits int `gorm:"column:bits" json:"bits"` // 指令宽度:64/32位 + OsVersion string `gorm:"column:os_version" json:"osVersion"` // 操作系统版本 + SysUser string `gorm:"column:sys_user" json:"sysUser"` // 管理员账户 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Os) TableName() string { + return "os" +} + +// AddOs insert a new Os into database and returns +// last inserted Id on success. +func AddOs(logger *log.Logger, m *Os) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetOsById retrieves Os by Id. Returns error if +// Id doesn't exist +func GetOsById(logger *log.Logger, id int64) (v *Os, err error) { + v = &Os{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetOsByUuid retrieves Os by Uuid. Returns error if +// Id doesn't exist +func GetOsByUuid(logger *log.Logger, uuid string) (v *Os, err error) { + v = &Os{} + err = dao.Where(logger, dao.IronicRdb, "os_id = ? and is_del = 0", uuid).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllOs retrieves all os matches certain condition. Returns empty list if +// no records exist +func GetAllOs(logger *log.Logger, query map[string]interface{}) (ml []*Os, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Os{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiOs retrieves all Os matches certain condition. Returns empty list if +// no records exist +func GetMultiOs(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Os, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Os{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateOs updates Os by Id and returns error if +// the record to be updated doesn't exist +func UpdateOsById(logger *log.Logger, m *Os) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Os{}).Where("os_id = ?", m.OsID).Updates(m).Error +} diff --git a/bmp-openapi/dao/projectDao/projectDao.go b/bmp-openapi/dao/projectDao/projectDao.go new file mode 100644 index 0000000..7c99356 --- /dev/null +++ b/bmp-openapi/dao/projectDao/projectDao.go @@ -0,0 +1,220 @@ +package projectDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Project Project +type Project struct { + ID int `gorm:"primaryKey;column:id" json:"-"` + ProjectID string `gorm:"column:project_id" json:"projectId"` // 项目uuid + ProjectName string `gorm:"column:project_name" json:"projectName"` // 项目名称 + IsDefault int8 `gorm:"column:is_default" json:"isDefault"` // 是否默认项目0否 1是 + IsSystem int8 `gorm:"column:is_system" json:"isSystem"` // 是否系统项目 0否 1是 + UserID string `gorm:"column:user_id" json:"userId"` // 项目拥有者用户id + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Project) TableName() string { + return "project" +} + +// AddProject insert a new Project into database and returns +// last inserted Id on success. +func AddProject(logger *log.Logger, m *Project) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetProjectById retrieves Project by Id. Returns error if +// Id doesn't exist +func GetProjectById(logger *log.Logger, ProjectId string) (v *Project, err error) { + v = &Project{} + err = dao.Where(logger, dao.IronicRdb, "project_id = ? and is_del = 0", ProjectId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetProjectByUuid retrieves Project by Uuid. Returns error if +// Id doesn't exist +func GetProjectCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Project{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +type UserProjectCount struct { + UserID string `json:"user_id"` + Count int64 `json:"count"` +} + +// GetProjectByUuid retrieves Project by Uuid. Returns error if +// Id doesn't exist +func GetProjectCountGroupByUser(logger *log.Logger) ([]*UserProjectCount, error) { + ml := []*UserProjectCount{} + sql := `select user_id, count(1) as count from project group by user_id, is_del having is_del = 0` + err := dao.Raw(logger, dao.IronicRdb, sql).Find(&ml).Error + return ml, err +} + +type AllProject struct { + Project + Owned int `gorm:"column:owned" json:"owned"` +} + +// GetProjectAndSharedCount retrieves Project by Uuid. Returns error if +// Id doesn't exist +func GetProjectAndSharedCount(logger *log.Logger, user_id string, owned int) (n int64, err error) { + leftsql := fmt.Sprintf(`select a.project_id, a.project_name, a.user_id, a.created_time, 1 as owned from project a where a.is_del = 0 and a.user_id = '%s'`, user_id) + rightsql := fmt.Sprintf(`select b.project_id, b.project_name, b.shared_user_id as user_id, b.created_time, 2 as owned from sharing_project b where b.is_del = 0 and b.shared_user_id = '%s'`, user_id) + var sql string + if owned == 1 { //只查有拥有权的项目 + sql = fmt.Sprintf(`select count(*) from (%s) c`, leftsql) + } else if owned == 2 { //只查有共享权的项目,暂时还用不到 + sql = fmt.Sprintf(`select count(*) from (%s) c`, rightsql) + } else { //查有拥有权和共享权的项目 + sql = fmt.Sprintf(`select count(*) from (%s union %s) c`, leftsql, rightsql) + } + err = dao.Raw(logger, dao.IronicRdb, sql).Count(&n).Error + return +} + +// GetAllProject retrieves all Project matches certain condition. Returns empty list if +// no records exist +func GetAllProject(logger *log.Logger, query map[string]interface{}) (ml []*Project, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Project{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Order("id ASC").Find(&ml).Error + return +} + +func GetAllProjectIncludeShare(logger *log.Logger, user_id string, owned int) (ml []*AllProject, err error) { + + leftsql := fmt.Sprintf(`select a.is_default, a.project_id, a.project_name, a.user_id, a.created_time, 1 as owned from project a where a.is_del = 0 and a.user_id = '%s'`, user_id) + rightsql := fmt.Sprintf(`select 0 as is_default, b.project_id, b.project_name, b.shared_user_id as user_id, b.created_time, 2 as owned from sharing_project b where b.is_del = 0 and b.shared_user_id = '%s'`, user_id) + var sql string + if owned == 1 { //只查有拥有权的项目 + sql = fmt.Sprintf(`select c.* from (%s) c`, leftsql) + } else if owned == 2 { //只查有共享权的项目,暂时还用不到 + sql = fmt.Sprintf(`select c.* from (%s) c`, rightsql) + } else { //查有拥有权和共享权的项目 + sql = fmt.Sprintf(`select c.* from (%s union %s) c order by c.created_time desc`, leftsql, rightsql) + } + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} + +// GetMultiProject retrieves all Project matches certain condition. Returns empty list if +// no records exist +func GetMultiProject(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Project, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Project{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetMultiProjectIncludeShare(logger *log.Logger, user_id string, owned int, sortby []string, order []string, + offset int64, limit int64) (ml []*AllProject, err error) { + + leftsql := fmt.Sprintf(`select a.is_default, a.project_id, a.project_name, a.user_id, a.created_time, 1 as owned from project a where a.is_del = 0 and a.user_id = '%s'`, user_id) + rightsql := fmt.Sprintf(`select 0 as is_default, b.project_id, b.project_name, b.shared_user_id as user_id, b.created_time, 2 as owned from sharing_project b where b.is_del = 0 and b.shared_user_id = '%s'`, user_id) + var sql string + if owned == 1 { //只查有拥有权的项目 + sql = fmt.Sprintf(`select c.* from (%s) c`, leftsql) + } else if owned == 2 { //只查有共享权的项目,暂时还用不到 + sql = fmt.Sprintf(`select c.* from (%s) c`, rightsql) + } else { //查有拥有权和共享权的项目 + sql = fmt.Sprintf(`select c.* from (%s union %s) c`, leftsql, rightsql) + } + + db := dao.Raw(logger, dao.IronicRdb, sql) + + if len(sortby) == 0 { + db = db.Order("create_time desc") + } else { + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + } + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateProject updates Project by Id and returns error if +// the record to be updated doesn't exist +func UpdateProjectById(logger *log.Logger, m *Project) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Project{}).Where("project_id = ?", m.ProjectID).Updates(m).Error +} + +func UpdateUserDefaultProject(logger *log.Logger, userId, projectId string) error { + err := dao.IronicWdb.Exec("update project set is_default = 0 where is_del = 0 and user_id = ?", userId).Error + if err != nil { + return err + } + + err = dao.IronicWdb.Exec("update project set is_default = 1 where project_id = ?", projectId).Error + if err != nil { + return err + } + return nil +} + +func UpdateProjects(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, Project{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return + +} diff --git a/bmp-openapi/dao/queryDao.go b/bmp-openapi/dao/queryDao.go new file mode 100644 index 0000000..8931f0c --- /dev/null +++ b/bmp-openapi/dao/queryDao.go @@ -0,0 +1,131 @@ +package dao + +import ( + clog "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +// SELECT * FROM `foods` LIMIT 1 +//eg. db.Take(logger, rdb, &food) +func Take(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Take(out, where...) +} + +// SELECT * FROM `foods` ORDER BY `foods`.`id` ASC LIMIT 1 +//eg. db.First(logger, rdb, &food) +func First(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.First(out, where...) +} + +// SELECT * FROM `foods` ORDER BY `foods`.`id` DESC LIMIT 1 +//eg. db.Last(logger, rdb, &food) +func Last(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Last(out, where...) +} + +// SELECT * FROM `foods` 可单可复 +//eg. db.Find(logger, rdb, &foods) +func Find(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Find(out, where...) +} + +// // 查询一列值 +//eg. Model(Food{}).Pluck("title", &titles) +// func Pluck(logger *clog.Logger, model interface{}, column string, target interface{}) error { +// //等价于:SELECT title FROM `foods` 提取了title字段,保存到titles变量 +// //这里Model函数是为了绑定一个模型实例,可以从里面提取表名。 +// gl := &gLogger{traceid: logger.GetPoint("logid").(string)} +// db := gdb.New() +// db.SetLogger(gl) +// return gdb.Model(model).Pluck("title", target).Error +// } + +// 设置where条件 +//eg. dao.Where(logger, rdb, "id = ?", 10).Take(&food) +//eg. dao.Where(logger, rdb, "id in (?)", []int{1,2,5,6}).Take(&food) +//eg. dao.Where(logger, rdb, "create_time >= ? and create_time <= ?", "2018-11-06 00:00:00", "2018-11-06 23:59:59").Find(&foods) +//eg. dao.Where(logger, rdb, "title like ?", "%可乐%").Find(&foods) +func Where(logger *clog.Logger, gdb *gorm.DB, query interface{}, args ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Where(query, args...) +} + +// 指定返回的字段 +//eg. dao.Select(logger, rdb, "id,title").Where("id = ?", 1).Take(&food) +//eg. dao.Model(logger, rdb, Food{}).Select("count(*) as total").Pluck("total", &total) +func Select(logger *clog.Logger, gdb *gorm.DB, query interface{}, args ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Select(query, args...) +} + +// 指定绑定的模型,一般和Pluck一起使用 +//eg. dao.Model(logger, rdb, Food{}).Select("count(*) as total").Pluck("total", &total) +func Model(logger *clog.Logger, gdb *gorm.DB, value interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + //db.Callback().Update().Remove("gorm:update_time_stamp") + //db.Callback().Update().Remove("gorm:delete_time_stamp") + return db.Model(value) +} + +// 指定order +//eg. dao.Order(logger, rdb, "create_time desc").Limit(10).Offset(0).Find(&foods) +//eg. dao.Where(logger, rdb, "create_time >= ?", "2018-11-06 00:00:00").Order("create_time desc").Find(&foods) +func Order(logger *clog.Logger, gdb *gorm.DB, value interface{}, reorder ...bool) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Order(value, reorder...) +} + +// limit +//eg. dao.Order(logger, rdb, "create_time desc").Limit(10).Offset(0).Find(&foods) +//eg. dao.Limit(logger, rdb, 10).Offset(0).Find(&foods) +func Limit(logger *clog.Logger, gdb *gorm.DB, limit interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Limit(limit) +} + +// Offset +//eg. dao.Order(logger, rdb, "create_time desc").Limit(10).Offset(0).Find(&foods) +//eg. dao.Offset(logger, rdb, 10).Find(&foods) +func Offset(logger *clog.Logger, gdb *gorm.DB, limit interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Offset(limit) +} + +//eg. dao.Model(logger, rdb, Food{}).Count(&total) +// COUNT + +//eg. dao.Model(logger, rdb, Food{}).Select("type, count(*) as total").Group("type").Having("total > 0").Scan(&results) +//group by,必须要搭配select一起使用 + +//Raw +//eg. dao.Raw(logger, rdb, sql, "2018-11-06 00:00:00").Scan(&results) +func Raw(logger *clog.Logger, gdb *gorm.DB, sql string, values ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Raw(sql, values...) +} diff --git a/bmp-openapi/dao/rDeviceTypeImageDao/rDeviceTypeImageDao.go b/bmp-openapi/dao/rDeviceTypeImageDao/rDeviceTypeImageDao.go new file mode 100644 index 0000000..2e8c657 --- /dev/null +++ b/bmp-openapi/dao/rDeviceTypeImageDao/rDeviceTypeImageDao.go @@ -0,0 +1,295 @@ +package rDeviceTypeImageDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceTypeDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/imageDao" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// RDeviceTypeImage device_type/image关系 +type RDeviceTypeImage struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像ID + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型id + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *RDeviceTypeImage) TableName() string { + return "r_device_type_image" +} + +// AddRDeviceTypeImage insert a new RDeviceTypeImage into database and returns +// last inserted Id on success. +func AddRDeviceTypeImage(logger *log.Logger, m *RDeviceTypeImage) (id int64, err error) { + // + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func AddMultiRDeviceTypeImage(logger *log.Logger, m []*RDeviceTypeImage) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, r := range m { + //r.CreateTime = time.Now() + //r.UpdateTime = time.Now() + if err := tx.Create(r).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetRDeviceTypeImageById retrieves RDeviceTypeImage by Id. Returns error if +// Id doesn't exist +func GetRDeviceTypeImageById(logger *log.Logger, id int64) (v *RDeviceTypeImage, err error) { + v = &RDeviceTypeImage{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetAllRDeviceTypeImage(logger *log.Logger, query map[string]interface{}) (ml []*RDeviceTypeImage, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiRDeviceTypeImage retrieves all RDeviceTypeImage matches certain condition. Returns empty list if +// no records exist +func GetMultiRDeviceTypeImage(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*RDeviceTypeImage, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateRDeviceTypeImage updates RDeviceTypeImage by Id and returns error if +// the record to be updated doesn't exist +func UpdateRDeviceTypeImageById(logger *log.Logger, m *RDeviceTypeImage, deviceTypeId, imageId string) (err error) { + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RDeviceTypeImage{}).Where("device_type_id = ? and image_id = ? and is_del = ?", deviceTypeId, imageId, baseLogic.IS_NOT_DEL).Update(m).Error +} + +func UpdateMultiRDeviceTypeImage(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["updated_time"] = int(time.Now().Unix()) + var db = dao.Model(logger, dao.IronicWdb, RDeviceTypeImage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func AssociatedImageMultiRDeviceTypeImage(logger *log.Logger, items []*RDeviceTypeImage) (err error) { + //paris := []string{} + for _, item := range items { + //paris = append(paris, fmt.Sprintf("('%s', '%s')", item.DeviceTypeID, item.ImageID)) + err = dao.Model(logger, dao.IronicRdb, RDeviceTypeImage{}).Where("device_type_id = ? and image_id = ? and is_del = 0", item.DeviceTypeID, item.ImageID).Update(item).Error + } + //fmt.Sprintf(`(device_type_id, image_id) in (%s)`, strings.Join(paris, ",")) + + //updates := map[string]interface{}{ + // "is_del": 0, + // "updated_time": time.Now(), + //} + return +} + +func GetOneRDeviceTypeImage(logger *log.Logger, query map[string]interface{}) (l *RDeviceTypeImage, err error) { + l = &RDeviceTypeImage{} + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetByDeviceTypeIDAndImageID(logger *log.Logger, deviceTypeID, imageID string) (l *RDeviceTypeImage, err error) { + l = &RDeviceTypeImage{} + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and image_id = ? and is_del = ?", deviceTypeID, imageID, baseLogic.IS_NOT_DEL).Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} +func GetByDeviceTypeID(logger *log.Logger, deviceTypeID string) (l []*RDeviceTypeImage, err error) { + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and is_del = ?", deviceTypeID, baseLogic.IS_NOT_DEL).Find(&l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetByDeviceTypeAndImageIdPatition(logger *log.Logger, device_type, image_id string) (ml []*RDeviceTypeImage, err error) { + + sql := fmt.Sprintf("select r from r_device_type_image r where (device_type='%s' or device_type='common') and image_id='%s' and is_del=0", device_type, image_id) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} +func QueryDeviceTypeImagesCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} + +func ConvertIn(str string) string { + arr := strings.Split(str, ",") + sqlIn := "" + for _, v := range arr { + sqlIn = sqlIn + "'" + v + "'" + "," + } + sqlIn = strings.Trim(sqlIn, ",") + return "(" + sqlIn + ")" +} + +// QueryByDeviceOsType ... +func GetDeviceTypeImageAndOsList(logger *log.Logger, param map[string]interface{}, count bool, offset int64, limit int64) (ml []*imageDao.DImage, n int64, err error) { + raw := "*" + if count { + raw = "count(*)" + } + sql := `select ` + raw + ` FROM image i,os o,r_device_type_image r where i.os_id=o.os_id and r.image_id=i.image_id and r.is_del=0 and i.is_del=0 and o.is_del=0` + sql = sql + ` and r.device_type_id=` + "'" + param["device_type_id"].(string) + "'" + //image i 放在前面,如果有相同字段,以前面这为主,由于都有添加时间字段,如果要获取镜像的添加时间,所以要以image表的created_time为准 + //fmt.Println(param) + if param["image_id"] != nil && param["image_id"] != "" { + sql = sql + " and i.image_id in " + ConvertIn(param["image_id"].(string)) + } + if param["source"] != nil && param["source"] != "" { + sql = sql + " and i.source in " + ConvertIn(param["source"].(string)) + } + if param["image_name"] != nil && param["image_name"] != "" { + sql = sql + " and i.image_name in " + ConvertIn(param["image_name"].(string)) + } + if param["version"] != nil && param["version"] != "" { + sql = sql + " and o.os_version in " + ConvertIn(param["version"].(string)) + } + if param["os_type"] != nil && param["os_type"] != "" { + sql = sql + " and o.os_type in " + ConvertIn(param["os_type"].(string)) + } + if param["architecture"] != nil && param["architecture"] != "" { + sql = sql + " and o.architecture in " + ConvertIn(param["architecture"].(string)) + } + sql = sql + " order by i.created_time desc" + fmt.Println(sql) + logger.Info("查询机型关联镜像sql:", sql) + //os.Exit(1) + if count { + err = dao.Raw(logger, dao.IronicRdb, sql).Count(&n).Error + return + } + if offset == 0 && limit == 0 { + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return + } + fmt.Println(sql) + err = dao.Raw(logger, dao.IronicRdb, sql).Offset(offset).Limit(limit).Scan(&ml).Error + return +} + +//查询镜像绑定的机型列表 +func GetImageDeviceTypeList(logger *log.Logger, param map[string]interface{}, count bool, offset int64, limit int64) (ml []*deviceTypeDao.DeviceType, n int64, err error) { + raw := "*" + if count { + raw = "count(*)" + } + + sql := "" + //查询已绑定的机型 + if param["is_bind"] != nil && param["is_bind"] == "1" { + sql = `select ` + raw + ` FROM device_type dt,r_device_type_image r where dt.device_type_id=r.device_type_id and dt.is_del=0 and r.is_del=0` + if param["image_id"] != nil && param["image_id"] != "" { + sql = sql + " and r.image_id in " + ConvertIn(param["image_id"].(string)) + } + } else { //未绑定 + if param["image_id"] != nil && param["image_id"] != "" { + sql = `select ` + raw + ` FROM device_type dt where dt.is_del=0` + sql = sql + " and dt.device_type_id not in (select device_type_id from r_device_type_image where image_id = '" + param["image_id"].(string) + "' and is_del = 0)" + } + } + + //if param["source"] != nil && param["source"] != "" { + // sql = sql + " and i.source in " + ConvertIn(param["source"].(string)) + //} + //if param["image_name"] != nil && param["image_name"] != "" { + // sql = sql + " and i.image_name in " + ConvertIn(param["image_name"].(string)) + //} + //if param["version"] != nil && param["version"] != "" { + // sql = sql + " and o.os_version in " + ConvertIn(param["version"].(string)) + //} + //if param["os_type"] != nil && param["os_type"] != "" { + // sql = sql + " and o.os_type in " + ConvertIn(param["os_type"].(string)) + //} + if param["architecture"] != nil && param["architecture"] != "" { + sql = sql + " and dt.architecture in " + ConvertIn(param["architecture"].(string)) + } + sql = sql + " order by dt.created_time desc" + fmt.Println(sql) + logger.Info("查询机型关联镜像sql:", sql) + //os.Exit(1) + if count { + err = dao.Raw(logger, dao.IronicRdb, sql).Count(&n).Error + return + } + if offset == 0 && limit == 0 { + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return + } + fmt.Println(sql) + err = dao.Raw(logger, dao.IronicRdb, sql).Offset(offset).Limit(limit).Scan(&ml).Error + return +} diff --git a/bmp-openapi/dao/rDeviceTypeImagePartitionDao/rDeviceTypeImagePartitionDao.go b/bmp-openapi/dao/rDeviceTypeImagePartitionDao/rDeviceTypeImagePartitionDao.go new file mode 100644 index 0000000..57f25e9 --- /dev/null +++ b/bmp-openapi/dao/rDeviceTypeImagePartitionDao/rDeviceTypeImagePartitionDao.go @@ -0,0 +1,142 @@ +package rDeviceTypeImagePartitionDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// RDeviceTypeImagePartition device_type/image +type RDeviceTypeImagePartition struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像ID + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型 + BootMode string `gorm:"column:boot_mode" json:"bootMode"` // boot类型:bios、uefi + PartitionType string `gorm:"column:partition_type" json:"partitionType"` // 分区类型:root、boot、system、data + PartitionSize int `gorm:"column:partition_size" json:"partitionSize"` // 分区大小,单位MB + PartitionFsType string `gorm:"column:partition_fs_type" json:"partitionFsType"` // 文件系统类型:xfs + PartitionMountPoint string `gorm:"column:partition_mount_point" json:"partitionMountPoint"` // 分区目录 + PartitionLabel string `gorm:"column:partition_label" json:"partitionLabel"` // 分区标签:l_分区目录 + SystemDiskLabel string `gorm:"column:system_disk_label" json:"systemDiskLabel"` // 系统盘分区格式:gpt、msdos(做完RAID系统盘大于4T必用gpt) + DataDiskLabel string `gorm:"column:data_disk_label" json:"dataDiskLabel"` // 数据盘分区格式:gpt、msdos + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除(0-未删, 1-已删) +} + +func (t *RDeviceTypeImagePartition) TableName() string { + return "r_device_type_image_partition" +} + +// AddRDeviceTypeImage insert a new RDeviceTypeImage into database and returns +// last inserted Id on success. +func AddRDeviceTypeImagePartition(logger *log.Logger, m *RDeviceTypeImagePartition) (id int64, err error) { + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func AddMultiRDeviceTypeImagePartition(logger *log.Logger, m []*RDeviceTypeImagePartition) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, r := range m { + if err := tx.Create(r).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetRDeviceTypeImageById retrieves RDeviceTypeImage by Id. Returns error if +// Id doesn't exist +func GetRDeviceTypeImagePartitionById(logger *log.Logger, id int64) (v *RDeviceTypeImagePartition, err error) { + v = &RDeviceTypeImagePartition{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetAllRDeviceTypeImagePartition(logger *log.Logger, query map[string]interface{}) (ml []*RDeviceTypeImagePartition, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImagePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiRDeviceTypeImage retrieves all RDeviceTypeImage matches certain condition. Returns empty list if +// no records exist +func GetMultiRDeviceTypeImagePartition(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*RDeviceTypeImagePartition, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImagePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateRDeviceTypeImage updates RDeviceTypeImage by Id and returns error if +// the record to be updated doesn't exist +func UpdateRDeviceTypeImagePartitionById(logger *log.Logger, m *RDeviceTypeImagePartition) (err error) { + return dao.Model(logger, dao.IronicWdb, RDeviceTypeImagePartition{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateMultiRDeviceTypeImagePartition(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + //updates["updated_time"] = time.Now() + var db = dao.Model(logger, dao.IronicWdb, RDeviceTypeImagePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func GetOneRDeviceTypeImagePartition(logger *log.Logger, query map[string]interface{}) (l *RDeviceTypeImagePartition, err error) { + l = &RDeviceTypeImagePartition{} + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImagePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetByDeviceTypeAndImageId(logger *log.Logger, deviceTypeId, imageId string) (ml []*RDeviceTypeImagePartition, err error) { + sql := fmt.Sprintf("select * from r_device_type_image_partition r where device_type_id='%s' and image_id='%s' and is_del=0", deviceTypeId, imageId) //or device_type='common' + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-openapi/dao/rDeviceVolumeDisksDao/rDeviceVolumeDisksDao.go b/bmp-openapi/dao/rDeviceVolumeDisksDao/rDeviceVolumeDisksDao.go new file mode 100644 index 0000000..6b3c080 --- /dev/null +++ b/bmp-openapi/dao/rDeviceVolumeDisksDao/rDeviceVolumeDisksDao.go @@ -0,0 +1,106 @@ +package rDeviceVolumeDisksDao + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// RDeviceVolumeDisks 设备-卷-磁盘 关系表 +type RDeviceVolumeDisks struct { + ID uint32 `gorm:"primary_key;column:id;type:int(11) unsigned;not null" json:"-"` // 主键 + DeviceID string `gorm:"index:i_device_id;column:device_id;type:varchar(255);not null" json:"device_id"` // 设备uuid + VolumeID string `gorm:"index:i_volume_id;column:volume_id;type:varchar(255);not null" json:"volume_id"` // volume uuid + VolumeType string `gorm:"column:volume_type;type:varchar(255);not null" json:"volume_type"` // data|system + DiskID string `gorm:"index:i_disk_id;column:disk_id;type:varchar(255);not null" json:"disk_id"` // disk uuid + CreatedBy string `gorm:"column:created_by;type:varchar(255);not null" json:"created_by"` // 创建者 + UpdatedBy string `gorm:"column:updated_by;type:varchar(255);not null" json:"updated_by"` // 更新者 + CreatedTime int `gorm:"column:created_time;type:int(255);not null" json:"created_time"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time;type:int(11);not null" json:"updated_time"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time;type:int(11);not null" json:"deleted_time"` // 删除时间 + IsDel int8 `gorm:"index:i_is_del;column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 +} + +func (t *RDeviceVolumeDisks) TableName() string { + return "r_device_volume_disks" +} + +// GetAllRDeviceTypeRaid retrieves all raid matches certain condition. Returns empty list if +// no records exist +func GetAllRDeviceVolumeDisks(logger *log.Logger, query map[string]interface{}) (ml []*RDeviceVolumeDisks, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RDeviceVolumeDisks{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetRDeviceTypeRaidById retrieves RDeviceTypeRaid by Id. Returns error if +// Id doesn't exist +func GetRDeviceVolumeDiskByVolumeIdDiskId(logger *log.Logger, volumeId, diskId string) (v *RDeviceVolumeDisks, err error) { + v = &RDeviceVolumeDisks{} + err = dao.Where(logger, dao.IronicRdb, "volume_id = ? and disk_id = ? and is_del = 0", volumeId, diskId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func UpdateMultiRDeviceVolumeDisk(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = int(time.Now().Unix()) + var db = dao.Model(logger, dao.IronicWdb, RDeviceVolumeDisks{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +// func AddMultiRDeviceVolumeDisk(logger *log.Logger, m []*RDeviceVolumeDisks) (id int64, err error) { + +// tx := dao.GetGormTx(logger) +// err = tx.Begin().Error +// if err != nil { +// logger.Warn("AddMultiRDeviceVolumeDisk Begin error") +// return +// } +// for _, r := range m { +// //r.CreateTime = time.Now() +// //r.UpdateTime = time.Now() +// if err := tx.Create(r).Error; err != nil { +// logger.Warnf("AddMultiRDeviceVolumeDisk Create error:%s", err.Error()) +// } +// } +// if err := tx.Commit().Error; err != nil { +// logger.Warnf("AddMultiRDeviceVolumeDisk Commit error:%s", err.Error()) +// goto ROLLBACK +// } +// return int64(len(m)), nil + +// ROLLBACK: +// tx.Rollback() +// logger.Warnf("AddMultiRDeviceVolumeDisk rollback") +// if len(m) > 0 { +// logger.Warnf("AddMultiRDeviceVolumeDisk rollback, device_id:%s", m[0].DeviceID) +// } +// return 0, errors.New("AddMultiRDeviceVolumeDisk Commit error") + +// } + +func AddMultiRDeviceVolumeDisk(logger *log.Logger, m []*RDeviceVolumeDisks) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + for _, v := range m { + _, err := dao.CreateAndGetId(logger, dao.IronicWdb, v) + if err != nil { + logger.Warn("AddMultiRDeviceVolumeDisk.CreateAndGetId ", v.DeviceID, v.DiskID, v.VolumeID) + } + } + return + +} diff --git a/bmp-openapi/dao/rInstanceSshkeyDao/rInstanceSshkey.go b/bmp-openapi/dao/rInstanceSshkeyDao/rInstanceSshkey.go new file mode 100644 index 0000000..0e83d59 --- /dev/null +++ b/bmp-openapi/dao/rInstanceSshkeyDao/rInstanceSshkey.go @@ -0,0 +1,190 @@ +package rInstanceSshkeyDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// rInstanceSshkey device_type/image关系 +type RInstanceSshkey struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + InstanceID string `gorm:"column:instance_id" json:"instanceId"` // 实例ID + SSHkeyID string `gorm:"column:sshkey_id" json:"sshkeyId"` // sshkeyid + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *RInstanceSshkey) TableName() string { + return "r_instance_sshkey" +} + +// AddrInstanceSshkey insert a new rInstanceSshkey into database and returns +// last inserted Id on success. +func AddrInstanceSshkey(logger *log.Logger, m *RInstanceSshkey) (id int64, err error) { + // + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func AddMultirInstanceSshkey(logger *log.Logger, m []*RInstanceSshkey) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, r := range m { + //r.CreateTime = time.Now() + //r.UpdateTime = time.Now() + if err := tx.Create(r).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetrInstanceSshkeyById retrieves rInstanceSshkey by Id. Returns error if +// Id doesn't exist +func GetrInstanceSshkeyById(logger *log.Logger, id int64) (v *RInstanceSshkey, err error) { + v = &RInstanceSshkey{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetAllrInstanceSshkey(logger *log.Logger, query map[string]interface{}) (ml []*RInstanceSshkey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RInstanceSshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultirInstanceSshkey retrieves all rInstanceSshkey matches certain condition. Returns empty list if +// no records exist +func GetMultirInstanceSshkey(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*RInstanceSshkey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RInstanceSshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdaterInstanceSshkey updates rInstanceSshkey by Id and returns error if +// the record to be updated doesn't exist +func UpdaterInstanceSshkeyById(logger *log.Logger, m *RInstanceSshkey) (err error) { + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RInstanceSshkey{}).Where("instance_id = ? and is_del = 0", m.InstanceID).Update(m).Error + +} + +func DeleteInstanceSshkeyByInstanceID(logger *log.Logger, instanceID string) (err error) { + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RInstanceSshkey{}).Where("instance_id = ? and is_del = 0", instanceID).Update("is_del", 1).Error +} + +func UpdateMultirInstanceSshkey(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, RInstanceSshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +//func AssociatedImageMultirInstanceSshkey(logger *log.Logger, items []*RInstanceSshkey) (err error) { +// //paris := []string{} +// for _, item := range items { +// //paris = append(paris, fmt.Sprintf("('%s', '%s')", item.DeviceTypeID, item.ImageID)) +// err = dao.Model(logger, dao.IronicRdb, RInstanceSshkey{}).Where("device_type_id = ? and image_id = ? and is_del = 0", item.DeviceTypeID, item.ImageID).Update(item).Error +// } +// //fmt.Sprintf(`(device_type_id, image_id) in (%s)`, strings.Join(paris, ",")) +// +// //updates := map[string]interface{}{ +// // "is_del": 0, +// // "updated_time": time.Now(), +// //} +// return +//} + +func GetOnerInstanceSshkey(logger *log.Logger, query map[string]interface{}) (l *RInstanceSshkey, err error) { + l = &RInstanceSshkey{} + var db = dao.Model(logger, dao.IronicRdb, RInstanceSshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetByDeviceTypeIDAndImageID(logger *log.Logger, deviceTypeID, imageID string) (l *RInstanceSshkey, err error) { + l = &RInstanceSshkey{} + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and image_id = ? and is_del = ?", deviceTypeID, imageID, baseLogic.IS_NOT_DEL).Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} +func GetByDeviceTypeID(logger *log.Logger, deviceTypeID string) (l []*RInstanceSshkey, err error) { + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and is_del = ?", deviceTypeID, baseLogic.IS_NOT_DEL).Find(&l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetByDeviceTypeAndImageIdPatition(logger *log.Logger, device_type, image_id string) (ml []*RInstanceSshkey, err error) { + + sql := fmt.Sprintf("select r from r_device_type_image r where (device_type='%s' or device_type='common') and image_id='%s' and is_del=0", device_type, image_id) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} +func QueryDeviceTypeImagesCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, RInstanceSshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} diff --git a/bmp-openapi/dao/rInstanceVolumeRaidDao/rInstanceVolumeRaidDao.go b/bmp-openapi/dao/rInstanceVolumeRaidDao/rInstanceVolumeRaidDao.go new file mode 100644 index 0000000..295a47c --- /dev/null +++ b/bmp-openapi/dao/rInstanceVolumeRaidDao/rInstanceVolumeRaidDao.go @@ -0,0 +1,83 @@ +package rInstanceVolumeRaidDao + +import ( + + //"coding.jd.com/aidc-bmp/bmp-scheduler/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// RInstanceVolumeRaid 实例每个数据卷选择的raid +type RInstanceVolumeRaid struct { + ID int `gorm:"primary_key;column:id;type:int(11) unsigned;not null" json:"-"` // 主键 + InstanceID string `gorm:"index:i_instance_id;column:instance_id;type:varchar(255);not null" json:"instance_id"` // instance uuid + VolumeID string `gorm:"column:volume_id;type:varchar(255);not null" json:"volume_id"` // volume uuid + VolumeType string `gorm:"index:i_volume_type;column:volume_type;type:varchar(255);not null" json:"volume_type"` // data|system + RaidCan string `gorm:"column:raid_can;type:varchar(16);not null" json:"raid_can"` // RAID配置: (RAID,NO RAID) + RaidID string `gorm:"column:raid_id;type:varchar(255);not null" json:"raid_id"` // RAID模式:raidid,一个一条 + RaidName string `gorm:"column:raid_name;type:varchar(255);not null" json:"raid_name"` // RAID名称 + CreatedBy string `gorm:"column:created_by;type:varchar(255);not null" json:"created_by"` // 创建者 + UpdatedBy string `gorm:"column:updated_by;type:varchar(255);not null" json:"updated_by"` // 更新者 + CreatedTime int `gorm:"column:created_time;type:int(255);not null" json:"created_time"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time;type:int(11);not null" json:"updated_time"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time;type:int(11);not null" json:"deleted_time"` // 删除时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 +} + +func (t *RInstanceVolumeRaid) TableName() string { + return "r_instance_volume_raid" +} + +// AddVolume insert a new Volume into database and returns +// last inserted Id on success. +func AddRInstanceVolumeRaid(logger *log.Logger, m *RInstanceVolumeRaid) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetVolumeById retrieves Volume by Id. Returns error if +// Id doesn't exist +func GetRInstanceVolumeRaids(logger *log.Logger, instanceId string) (ml []*RInstanceVolumeRaid, err error) { + ml = []*RInstanceVolumeRaid{} + err = dao.Where(logger, dao.IronicRdb, "instance_id = ? and is_del = 0", instanceId).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil +} + +// UpdateVolume updates Volume by Id and returns error if +// the record to be updated doesn't exist +func UpdateRInstanceVolumeRaidById(logger *log.Logger, m *RInstanceVolumeRaid) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RInstanceVolumeRaid{}).Where("id = ?", m.ID).Save(m).Error +} + +func AddMultiRInstanceVolumeRaid(logger *log.Logger, m []*RInstanceVolumeRaid) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, r := range m { + //r.CreateTime = time.Now() + //r.UpdateTime = time.Now() + if err := tx.Create(r).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +func GetRInstanceVolumeRaidByInstanceId(logger *log.Logger, instanceId string) (ml []*RInstanceVolumeRaid, err error) { + ml = []*RInstanceVolumeRaid{} + err = dao.Where(logger, dao.IronicRdb, "instance_id = ? and is_del = 0", instanceId).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil +} diff --git a/bmp-openapi/dao/rMonitorRulesInstanceDao/rMonitorRulesInstanceDao.go b/bmp-openapi/dao/rMonitorRulesInstanceDao/rMonitorRulesInstanceDao.go new file mode 100644 index 0000000..a7174fd --- /dev/null +++ b/bmp-openapi/dao/rMonitorRulesInstanceDao/rMonitorRulesInstanceDao.go @@ -0,0 +1,116 @@ +package rMonitorRulesInstanceDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// RMonitorRulesInstance 带内监控规则-实例关联表 +type RMonitorRulesInstance struct { + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + RuleID string `gorm:"index:i_rule_id;column:rule_id;type:varchar(255);not null" json:"rule_id"` // rule uuid + RuleName string `gorm:"column:rule_name;type:varchar(255);not null" json:"rule_name"` // 规则名称 + InstanceID string `gorm:"index:i_instance_id;column:instance_id;type:varchar(255);not null" json:"instance_id"` // instance uuid + InstanceName string `gorm:"column:instance_name;type:varchar(255);not null" json:"instance_name"` // instance name + Tags string `gorm:"column:tags;type:varchar(255);not null" json:"tags"` // disk/mountpoint/nic tag + CreatedTime int `gorm:"column:created_time;type:int(11);not null" json:"created_time"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time;type:int(11);not null" json:"updated_time"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time;type:int(11);not null" json:"deleted_time"` // 更新时间戳 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 +} + +func (t *RMonitorRulesInstance) TableName() string { + return "r_monitor_rules_instance" +} + +// AddWebMessage insert a new Os into database and returns +// last inserted Id on success. +func AddRMonitorRulesInstance(logger *log.Logger, m *RMonitorRulesInstance) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func AddMultiRMonitorRulesInstance(logger *log.Logger, ml []*RMonitorRulesInstance) (err error) { + for _, v := range ml { + if _, err := dao.CreateAndGetId(logger, dao.IronicWdb, v); err != nil { + logger.Warnf("AddMultiRMonitorRulesInstance error, v:%s, error:%s", util.InterfaceToJson(v), err.Error()) + } + } + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return nil +} + +func GetRMonitorRulesInstanceCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, RMonitorRulesInstance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetMultiOs retrieves all Os matches certain condition. Returns empty list if +// no records exist +func GetMultiRMonitorRulesInstance(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*RMonitorRulesInstance, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RMonitorRulesInstance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetAllRMonitorRulesInstance(logger *log.Logger, query map[string]interface{}) (ml []*RMonitorRulesInstance, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RMonitorRulesInstance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// UpdateOs updates Os by Id and returns error if +// the record to be updated doesn't exist +func UpdateRMonitorRulesInstance(logger *log.Logger, m *RMonitorRulesInstance) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RMonitorRulesInstance{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateMultiRMonitorRulesInstance(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, RMonitorRulesInstance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return + +} diff --git a/bmp-openapi/dao/rVolumeRaidDao/rVolumeRaidDao.go b/bmp-openapi/dao/rVolumeRaidDao/rVolumeRaidDao.go new file mode 100644 index 0000000..8f8c6de --- /dev/null +++ b/bmp-openapi/dao/rVolumeRaidDao/rVolumeRaidDao.go @@ -0,0 +1,120 @@ +package rVolumeRaidDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Volume RAID 关联关系表 +type RVolumeRaid struct { + ID int `gorm:"primaryKey;column:id" json:"-"` // 主键 + VolumeID string `gorm:"column:volume_id" json:"volumeId"` // 卷uuid + VolumeType string `gorm:"column:volume_type;type:varchar(255);not null" json:"volume_type"` // data|system + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型uuid + + RaidCan string `gorm:"column:raid_can" json:"raidCan"` // RAID配置: (RAID,NO RAID) + RaidID string `gorm:"column:raid_id" json:"raidId"` // RAID模式:RAID1,RIAD10等 + RaidName string `gorm:"column:raid_name" json:"raidName"` // RAID名称 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *RVolumeRaid) TableName() string { + return "r_volume_raid" +} + +// AddVolume insert a new Volume into database and returns +// last inserted Id on success. +func AddRVolumeRaid(logger *log.Logger, m *RVolumeRaid) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetVolumeById retrieves Volume by Id. Returns error if +// Id doesn't exist +func GetRVolumeRaidsByVId(logger *log.Logger, VolumeId string) (ml []*RVolumeRaid, err error) { + ml = []*RVolumeRaid{} + err = dao.Where(logger, dao.IronicRdb, "volume_id = ? and is_del = 0", VolumeId).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil +} + +// GetVolumeByUuid retrieves Volume by Uuid. Returns error if +// Id doesn't exist +func GetRVolumeRaidCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, RVolumeRaid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAllVolume retrieves all Volume matches certain condition. Returns empty list if +// no records exist +func GetAllRVolumeRaid(logger *log.Logger, query map[string]interface{}) (ml []*RVolumeRaid, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RVolumeRaid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiVolume retrieves all Volume matches certain condition. Returns empty list if +// no records exist +func GetMultiRVolumeRaid(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*RVolumeRaid, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RVolumeRaid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateVolume updates Volume by Id and returns error if +// the record to be updated doesn't exist +func UpdateRVolumeRaidById(logger *log.Logger, m *RVolumeRaid) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RVolumeRaid{}).Where("id = ?", m.ID).Save(m).Error +} + +func UpdateRVolumeRaidByWhere(logger *log.Logger, query map[string]interface{}, updates *RVolumeRaid) (err error) { + var db = dao.Model(logger, dao.IronicWdb, RVolumeRaid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} diff --git a/bmp-openapi/dao/raidDao/raidDao.go b/bmp-openapi/dao/raidDao/raidDao.go new file mode 100644 index 0000000..5868948 --- /dev/null +++ b/bmp-openapi/dao/raidDao/raidDao.go @@ -0,0 +1,147 @@ +package raidDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Raid raid +type Raid struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + RaidID string `gorm:"column:raid_id" json:"raidId"` // raid uuid + Name string `gorm:"column:name" json:"name"` // raid类型 noraid,raid0,raid1,raid10 + DescriptionEn string `gorm:"column:description_en" json:"descriptionEn"` // RAID英文描述 + DescriptionZh string `gorm:"column:description_zh" json:"descriptionZh"` // RAID中文描述 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Raid) TableName() string { + return "raid" +} + +// AddRaid insert a new Raid into database and returns +// last inserted Id on success. +func AddRaid(logger *log.Logger, m *Raid) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetRaidById retrieves Raid by Id. Returns error if +// Id doesn't exist +func GetRaidById(logger *log.Logger, raidId string) (v *Raid, err error) { + v = &Raid{} + err = dao.Where(logger, dao.IronicRdb, "raid_id = ? and is_del = 0", raidId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetRaidByUuid retrieves Raid by Id. Returns error if +// Id doesn't exist +func GetRaidByUuid(logger *log.Logger, uuid string) (v *Raid, err error) { + v = &Raid{} + err = dao.Where(logger, dao.IronicRdb, "raid_id = ? and is_del = 0", uuid).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllRaid retrieves all raid matches certain condition. Returns empty list if +// no records exist +func GetAllRaid(logger *log.Logger, query map[string]interface{}) (ml []*Raid, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Raid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiRaid retrieves all Raid matches certain condition. Returns empty list if +// no records exist +func GetMultiRaid(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Raid, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Raid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateRaid updates Raid by Id and returns error if +// the record to be updated doesn't exist +func UpdateRaidById(logger *log.Logger, m *Raid) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Raid{}).Where("raid_id = ?", m.RaidID).Updates(m).Error +} + +type DRaid struct { + RaidId string `json:"raid_id"` + NameEn string `json:"name_en"` + NameZh string `json:"name_zh"` + DeviceType string `json:"device_type"` + VolumeType string `json:"volume_type"` + VolumeDetail string `json:"volume_detail"` + DescriptionZh string `json:"description_zh"` + DescriptionEn string `json:"description_en"` + SystemPartitionCount int `json:"system_partition_count"` + AvailableValue int `json:"available_value"` + DiskType string `json:"disk_type"` +} + +func GetAllRraidDevice(logger *log.Logger, raid_id, device_type, volume_type string) (ml []*DRaid, err error) { + + sql := `select t1.uuid as raid_id, t1.name_en, t1.name_zh, t1.description_zh, t1.description_en, t2.device_type, t2.volume_type, t2.volume_detail, t2.system_partition_count,t2.available_value,t2.disk_type from raid t1 left join r_device_type_raid t2 on t1.uuid = t2.raid_id where t1.is_del = 0 and t2.is_del = 0` + if raid_id != "" { + sql = sql + fmt.Sprintf(" and t1.uuid = '%s'", raid_id) + } + if device_type != "" { + sql = sql + fmt.Sprintf(" and t2.device_type = '%s'", device_type) + } + if volume_type != "" { + sql = sql + fmt.Sprintf(" and t2.volume_type = '%s'", volume_type) + } + + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return + +} + +func GetAllRaidByVolumeId(logger *log.Logger, volumeId string) (ml []*Raid, err error) { + sql := `select a.* from raid a inner join r_volume_raid b on a.raid_id = b.raid_id where 1=1` + + sql = sql + fmt.Sprintf(" and b.volume_id = '%s'", volumeId) + + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-openapi/dao/roleDao/roleDao.go b/bmp-openapi/dao/roleDao/roleDao.go new file mode 100644 index 0000000..04924eb --- /dev/null +++ b/bmp-openapi/dao/roleDao/roleDao.go @@ -0,0 +1,108 @@ +package roleDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Role Role +type Role struct { + ID int `gorm:"primaryKey;column:id" json:"-"` + RoleID string `gorm:"column:role_id" json:"roleId"` // 角色uuid + RoleNameEn string `gorm:"column:role_name_en" json:"roleNameEn"` // 角色名称,唯一 + RoleNameCn string `gorm:"column:role_name_cn" json:"roleNameCn"` // 角色名称,唯一 + DescriptionEn string `gorm:"column:description_en" json:"descriptionEn"` // 权限描述 + DescriptionCn string `gorm:"column:description_cn" json:"descriptionCn"` // 权限描述 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Role) TableName() string { + return "role" +} + +// AddRole insert a new Role into database and returns +// last inserted Id on success. +func AddRole(logger *log.Logger, m *Role) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetRoleById retrieves Role by Id. Returns error if +// Id doesn't exist +func GetRoleById(logger *log.Logger, RoleId string) (v *Role, err error) { + v = &Role{} + err = dao.Where(logger, dao.IronicRdb, "role_id = ? and is_del = 0", RoleId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetRoleByUuid retrieves Role by Uuid. Returns error if +// Id doesn't exist +func GetRoleCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Role{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAllRole retrieves all Role matches certain condition. Returns empty list if +// no records exist +func GetAllRole(logger *log.Logger, query map[string]interface{}) (ml []*Role, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Role{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiRole retrieves all Role matches certain condition. Returns empty list if +// no records exist +func GetMultiRole(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Role, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Role{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateRole updates Role by Id and returns error if +// the record to be updated doesn't exist +func UpdateRoleById(logger *log.Logger, m *Role) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Role{}).Where("role_id = ?", m.RoleID).Updates(m).Error +} diff --git a/bmp-openapi/dao/sharingProjectDao/sharingProjectDao.go b/bmp-openapi/dao/sharingProjectDao/sharingProjectDao.go new file mode 100644 index 0000000..8411782 --- /dev/null +++ b/bmp-openapi/dao/sharingProjectDao/sharingProjectDao.go @@ -0,0 +1,93 @@ +package sharingProjectDao + +import ( + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/projectDao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// SharingProject 共享项目 +type SharingProject struct { + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + ProjectID string `gorm:"column:project_id;type:varchar(255);not null" json:"project_id"` // 项目uuid + ProjectName string `gorm:"column:project_name;type:varchar(255);not null" json:"project_name"` // 项目名称 + OwnerUserID string `gorm:"column:owner_user_id;type:varchar(255);not null" json:"owner_user_id"` // 项目拥有者用户id + SharedUserID string `gorm:"column:shared_user_id;type:varchar(255);not null" json:"shared_user_id"` // 项目共享者用户id + OwnerUserName string `gorm:"column:owner_user_name;type:varchar(255);not null" json:"owner_user_name"` // 项目拥有者用户名 + SharedUserName string `gorm:"column:shared_user_name;type:varchar(255);not null" json:"shared_user_name"` // 项目拥有者用户名 + IsDefault int8 `gorm:"column:is_default;type:tinyint(4);not null" json:"is_default"` // 是否默认项目0否 1是 + CreatedBy string `gorm:"column:created_by;type:varchar(255);not null" json:"created_by"` // 创建者 + UpdatedBy string `gorm:"column:updated_by;type:varchar(255);not null" json:"updated_by"` // 更新者 + CreatedTime int `gorm:"column:created_time;type:int(11);not null" json:"created_time"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time;type:int(11);not null" json:"updated_time"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time;type:int(11);not null" json:"deleted_time"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 + Premission string `gorm:"column:premission;type:varchar(64);not null" json:"premission"` // 读/写权限 +} + +func (t *SharingProject) TableName() string { + return "sharing_project" +} + +// AddProject insert a new Project into database and returns +// last inserted Id on success. +func AddSharingProject(logger *log.Logger, m *SharingProject) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func GetSharingsByProjectId(logger *log.Logger, project_id string) (ml []*SharingProject, err error) { + + err = dao.Where(logger, dao.IronicRdb, "project_id = ? and is_del = 0", project_id).Find(&ml).Error + return +} + +func GetSharingProjectIdsBySharding(logger *log.Logger, user_id string) (ml []*SharingProject, err error) { + err = dao.Where(logger, dao.IronicRdb, "shared_user_id = ? and is_del = 0", user_id).Find(&ml).Error + return +} + +func GetOneSharingProject(logger *log.Logger, project_id string, owner_id string, shard_id string) (l *SharingProject, err error) { + err = dao.Where(logger, dao.IronicRdb, "project_id = ? and owner_user_id = ? and shared_user_id = ? and is_del = 0", project_id, owner_id, shard_id).Take(l).Error + return +} + +func DeleteOneSharingProject(logger *log.Logger, p *SharingProject) (err error) { + p.IsDel = 1 + err = dao.Save(logger, dao.IronicWdb, p).Error + return +} + +func DeleteSharingProjectByProjectId(logger *log.Logger, project_id string) (err error) { + m := map[string]interface{}{ + "is_del": 1, + } + return dao.Model(logger, dao.IronicWdb, SharingProject{}).Where("project_id = ? and is_del = 0", project_id).Updates(m).Error + +} + +func UpdateShareProjects(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, SharingProject{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return + +} + +// GetProjectByUuid retrieves Project by Uuid. Returns error if +// Id doesn't exist +func GetShareProjectCountGroupByUser(logger *log.Logger) ([]*projectDao.UserProjectCount, error) { + ml := []*projectDao.UserProjectCount{} + sql := `select shared_user_id as user_id, count(1) as count from sharing_project group by shared_user_id, is_del having is_del = 0` + err := dao.Raw(logger, dao.IronicRdb, sql).Find(&ml).Error + return ml, err +} diff --git a/bmp-openapi/dao/sshkeyDao/sshkeyDao.go b/bmp-openapi/dao/sshkeyDao/sshkeyDao.go new file mode 100644 index 0000000..1e60e09 --- /dev/null +++ b/bmp-openapi/dao/sshkeyDao/sshkeyDao.go @@ -0,0 +1,108 @@ +package sshkeyDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Sshkey Sshkey +type Sshkey struct { + ID int64 `gorm:"id" json:"id"` + SshkeyId string `gorm:"sshkey_id" json:"sshkeyId"` // 秘钥uuid + UserId string `gorm:"user_id" json:"userId"` // 用户id + Name string `gorm:"name" json:"name"` // 秘钥名称 + Key string `gorm:"key" json:"key"` // 公钥,格式:ssh-rsa AAA + FingerPrint string `gorm:"finger_print" json:"fingerPrint"` // 公钥指纹 + CreatedBy string `gorm:"created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Sshkey) TableName() string { + return "ssh_key" +} + +// AddSshkey insert a new Sshkey into database and returns +// last inserted Id on success. +func AddSshkey(logger *log.Logger, m *Sshkey) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetSshkeyById retrieves Sshkey by Id. Returns error if +// Id doesn't exist +func GetSshkeyById(logger *log.Logger, SshkeyId string) (v *Sshkey, err error) { + v = &Sshkey{} + err = dao.Where(logger, dao.IronicRdb, "sshkey_id = ? and is_del = 0", SshkeyId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetSshkeyByUuid retrieves Sshkey by Uuid. Returns error if +// Id doesn't exist +func GetSshkeyCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Sshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAllSshkey retrieves all Sshkey matches certain condition. Returns empty list if +// no records exist +func GetAllSshkey(logger *log.Logger, query map[string]interface{}) (ml []*Sshkey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Sshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiSshkey retrieves all Sshkey matches certain condition. Returns empty list if +// no records exist +func GetMultiSshkey(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Sshkey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Sshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateSshkey updates Sshkey by Id and returns error if +// the record to be updated doesn't exist +func UpdateSshkeyById(logger *log.Logger, m *Sshkey) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Sshkey{}).Where("sshkey_id = ?", m.SshkeyId).Updates(m).Error +} diff --git a/bmp-openapi/dao/subnetDao/subnetDao.go b/bmp-openapi/dao/subnetDao/subnetDao.go new file mode 100644 index 0000000..db82f14 --- /dev/null +++ b/bmp-openapi/dao/subnetDao/subnetDao.go @@ -0,0 +1,181 @@ +package subnetDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Subnet 子网 +type Subnet struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + UUID string `gorm:"unique;column:uuid;type:varchar(36);not null" json:"uuid"` // 子网ID + Az string `gorm:"column:az;type:varchar(32);not null" json:"az"` // az + Tenant string `gorm:"index:i_subnet_tenant;column:tenant;type:varchar(64);not null" json:"tenant"` // 租户 + Name string `gorm:"column:name;type:varchar(32)" json:"name"` + Cidr string `gorm:"column:cidr;type:varchar(32);not null" json:"cidr"` // 子网网段 + VxlanID int64 `gorm:"column:vxlan_id;type:bigint(20) unsigned;not null" json:"vxlan_id"` // vxlan_id + Gateway string `gorm:"column:gateway;type:varchar(32);not null" json:"gateway"` // 子网网关 + Mask string `gorm:"column:mask;type:varchar(32);not null" json:"mask"` // 子网掩码 + Mac string `gorm:"column:mac;type:varchar(32);not null" json:"mac"` // MAC + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *Subnet) TableName() string { + return "subnet" +} + +// AddSubnet insert a new Subnet into database and returns +// last inserted Id on success. +func AddSubnet(logger *log.Logger, m *Subnet) (id int64, err error) { + + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicRdb, m) +} + +// GetSubnetById retrieves Subnet by Id. Returns error if +// Id doesn't exist +func GetSubnetById(logger *log.Logger, id int64) (v *Subnet, err error) { + v = &Subnet{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetOneSubnet(logger *log.Logger, query map[string]interface{}) (v *Subnet, err error) { + v = &Subnet{} + var db = dao.Model(logger, dao.IronicRdb, Subnet{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetSubnetCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Subnet{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return + +} + +// GetAllRaid retrieves all raid matches certain condition. Returns empty list if +// no records exist +func GetAllSubnet(logger *log.Logger, query map[string]interface{}) (ml []*Subnet, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Subnet{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiSubnet retrieves all Subnet matches certain condition. Returns empty list if +// no records exist +func GetMultiSubnet(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Subnet, err error) { + var db = dao.Model(logger, dao.IronicRdb, Subnet{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateSubnet updates Subnet by Id and returns error if +// the record to be updated doesn't exist +func UpdateSubnetById(logger *log.Logger, m *Subnet) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Subnet{}).Where("id = ?", m.ID).Updates(m).Error +} + +func GetBySubnetIdAndTenant(logger *log.Logger, subnet_id, tenant string) (v *Subnet, err error) { + v = &Subnet{} + // err = dao.Where(logger, dao.IronicRdb, "uuid = ? and tenant = ? and is_del = 0", subnet_id, tenant).Take(&v).Error + err = dao.Where(logger, dao.IronicRdb, "uuid = ? and is_del = 0", subnet_id).Take(&v).Error + if err != nil { + return nil, err + } + return v, nil + +} + +func QueryByTenant(logger *log.Logger, tenant, az string) (ml []*Subnet, err error) { + // err = dao.Where(logger, dao.IronicRdb, "az = ? and tenant = ? and is_del = 0", az, tenant).Find(&ml).Error + err = dao.Where(logger, dao.IronicRdb, "is_del = 0").Find(&ml).Error + return +} + +func CountByParam(logger *log.Logger, az, tenant, name string, subnet_ids []string) (n int64, err error) { + sql := `select count(1) from subnet t where 1=1` + // if az != "" { + // sql = sql + fmt.Sprintf(" and t.az = '%s'", az) + // } + // if tenant != "" { + // sql = sql + fmt.Sprintf(" and t.tenant = '%s'", tenant) + // } + if name != "" { + sql = sql + fmt.Sprintf(" and t.name LIKE CONCAT('%%', '%s', '%%')", name) + } + if len(subnet_ids) > 0 { + for k, v := range subnet_ids { + subnet_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t.uuid in (%s)", strings.Join(subnet_ids, ",")) + } + sql = sql + " and t.is_del = 0" + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&n).Error + return +} + +func QueryByParam(logger *log.Logger, az, tenant, name string, subnet_ids []string, offset, limit int64) (ml []*Subnet, err error) { + sql := `select * from subnet t where 1=1` + // if az != "" { + // sql = sql + fmt.Sprintf(" and t.az = '%s'", az) + // } + // if tenant != "" { + // sql = sql + fmt.Sprintf(" and t.tenant = '%s'", tenant) + // } + if name != "" { + sql = sql + fmt.Sprintf(" and t.name LIKE CONCAT('%%', '%s', '%%')", name) + } + if len(subnet_ids) > 0 { + for k, v := range subnet_ids { + subnet_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t.uuid in (%s)", strings.Join(subnet_ids, ",")) + } + sql = sql + fmt.Sprintf(" and t.is_del = 0 limit %d ,%d", offset, limit) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-openapi/dao/updateDao.go b/bmp-openapi/dao/updateDao.go new file mode 100644 index 0000000..e65b9d6 --- /dev/null +++ b/bmp-openapi/dao/updateDao.go @@ -0,0 +1,53 @@ +package dao + +import ( + clog "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +//更新 根据主键id,更新所有模型字段值。查询->set->save +//eg. dao.Save(logger, rdb, &food) +func Save(logger *clog.Logger, gdb *gorm.DB, value interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Save(value) +} + +//更新单个字段值 +//eg1.更新一条记录(根据主键) dao.Model(logger, rdb, &food).Update("price", 25) +//eg2.更新所有记录 dao.Model(logger, rdb, Food{}).Update("price", 25) +//eg3.根据自定义条件更新记录 dao.Model(logger, rdb, Food{}).Where("create_time > ?", "2018-11-06 20:00:00").Update("price", 25) +func Update(logger *clog.Logger, gdb *gorm.DB, attrs ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Update(attrs...) +} + +//更新多个字段值 +/* +updataFood := Food{ + Stock:120, + Title:"柠檬雪碧", + //Age:0 +} +*/ +//eg1. 通过结构体变量设置更新字段 dao.Model(logger, rdb, &food).Updates(&updataFood) 问题是:这样只会更新updataFood中字段为非默认值的字段,比如updataFood定义时就算加上了Age:0,这个字段也不会被更新成目标0 +//eg2. 根据自定义条件更新记录 dao.Model(logger, rdb, Food{}).Where("price > ?", 10).Updates(&updataFood) 问题同上 +//eg3. 想更新所有字段值,包括零值,就是不想忽略掉空值字段时,使用map类型替代上面的结构体变量 +/* +data := make(map[string]interface{}) +data["stock"] = 0 //零值字段 +data["price"] = 35 +dao.Model(logger, rdb, Food{}).Where("id = ?", 2).Updates(data) +*/ +func Updates(logger *clog.Logger, gdb *gorm.DB, values interface{}, ignoreProtectedAttrs ...bool) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Updates(values, ignoreProtectedAttrs...) +} + +//更新表达式 +//eg. db.Model(&food).Update("stock", gorm.Expr("stock + 1")) 等价于UPDATE `foods` SET `stock` = stock + 1 WHERE `foods`.`id` = '2' diff --git a/bmp-openapi/dao/userDao/userDao.go b/bmp-openapi/dao/userDao/userDao.go new file mode 100644 index 0000000..8cdc613 --- /dev/null +++ b/bmp-openapi/dao/userDao/userDao.go @@ -0,0 +1,123 @@ +package userDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// user user +type User struct { + ID int `gorm:"primaryKey;column:id" json:"-"` + UserID string `gorm:"column:user_id" json:"userId"` // 用户uuid + RoleID string `gorm:"column:role_id" json:"roleId"` // 角色uuid + UserName string `gorm:"column:user_name" json:"userName"` // 用户名,唯一 + Email string `gorm:"column:email" json:"email"` // 邮箱 + PhonePrefix string `gorm:"column:phone_prefix" json:"phonePrefix"` // 国家地区码,如86 + PhoneNumber string `gorm:"column:phone_number" json:"phoneNumber"` // 手机号 + DefaultProjectID string `gorm:"column:default_project_id" json:"defaultProjectId"` // 所属项目uuid + Language string `gorm:"column:language" json:"language"` // 语言(中文/English) + Timezone string `gorm:"column:timezone;type:varchar(64);not null" json:"timezone"` // timezone + Password string `gorm:"column:password" json:"password"` // 密码,sha256非对称加密后存储 + Description string `gorm:"column:description" json:"description"` // 描述 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *User) TableName() string { + return "user" +} + +// Adduser insert a new user into database and returns +// last inserted Id on success. +func Adduser(logger *log.Logger, m *User) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetuserById retrieves user by Id. Returns error if +// Id doesn't exist +func GetUserById(logger *log.Logger, userId string) (v *User, err error) { + v = &User{} + err = dao.Where(logger, dao.IronicRdb, "user_id = ? and is_del = 0", userId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetUserByName(logger *log.Logger, userName string) (v *User, err error) { + v = &User{} + err = dao.Where(logger, dao.IronicRdb, "user_name = ? and is_del = 0", userName).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetuserByUuid retrieves user by Uuid. Returns error if +// Id doesn't exist +func GetUserCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, User{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAlluser retrieves all user matches certain condition. Returns empty list if +// no records exist +func GetAllUser(logger *log.Logger, query map[string]interface{}) (ml []*User, err error) { + + var db = dao.Model(logger, dao.IronicRdb, User{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiuser retrieves all user matches certain condition. Returns empty list if +// no records exist +func GetMultiUser(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*User, err error) { + + var db = dao.Model(logger, dao.IronicRdb, User{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// Updateuser updates user by Id and returns error if +// the record to be updated doesn't exist +func UpdateUserById(logger *log.Logger, m *User) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, User{}).Where("user_id = ?", m.UserID).Save(m).Error +} diff --git a/bmp-openapi/dao/volumeDao/volumeDao.go b/bmp-openapi/dao/volumeDao/volumeDao.go new file mode 100644 index 0000000..7d465af --- /dev/null +++ b/bmp-openapi/dao/volumeDao/volumeDao.go @@ -0,0 +1,142 @@ +package volumeDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Volume 卷管理表 +type Volume struct { + ID int `gorm:"primaryKey;column:id" json:"-"` // 主键 + VolumeID string `gorm:"column:volume_id" json:"volumeId"` // 卷uuid + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型uuid + VolumeName string `gorm:"column:volume_name" json:"volumeName"` // 卷名称 + VolumeType string `gorm:"column:volume_type" json:"volumeType"` // 卷类型:系统卷,数据卷 + DiskType string `gorm:"column:disk_type" json:"diskType"` // 硬盘类型(SSD,HDD) + InterfaceType string `gorm:"column:interface_type" json:"interfaceType"` // 接口类型(SATA,SAS,NVME,不限制) + VolumeSize string `gorm:"column:volume_size" json:"volumeSize"` // 单盘大小(最小容量) + VolumeUnit string `gorm:"column:volume_unit" json:"volumeUnit"` // 硬盘单位(GB,TB) + VolumeAmount int `gorm:"column:volume_amount" json:"volumeAmount"` // 硬盘数量(最低块数) + //RaidCan string `gorm:"column:raid_can" json:"raidCan"` // RAID配置: (RAID,NO RAID) + //Raid string `gorm:"column:raid" json:"raid"` // RAID模式:RAID1,RIAD10等 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Volume) TableName() string { + return "volume" +} + +// AddVolume insert a new Volume into database and returns +// last inserted Id on success. +func AddVolume(logger *log.Logger, m *Volume) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetVolumeById retrieves Volume by Id. Returns error if +// Id doesn't exist +func GetVolumeById(logger *log.Logger, VolumeId string) (v *Volume, err error) { + v = &Volume{} + err = dao.Where(logger, dao.IronicRdb, "volume_id = ? and is_del = 0", VolumeId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetVolumeByName(logger *log.Logger, VolumeName string) (v *Volume, err error) { + v = &Volume{} + err = dao.Where(logger, dao.IronicRdb, "volume_name = ? and is_del = 0", VolumeName).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetVolumeByUuid retrieves Volume by Uuid. Returns error if +// Id doesn't exist +func GetVolumeCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Volume{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAllVolume retrieves all Volume matches certain condition. Returns empty list if +// no records exist +func GetAllVolume(logger *log.Logger, query map[string]interface{}) (ml []*Volume, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Volume{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiVolume retrieves all Volume matches certain condition. Returns empty list if +// no records exist +func GetMultiVolume(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Volume, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Volume{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateVolume updates Volume by Id and returns error if +// the record to be updated doesn't exist +func UpdateVolumeById(logger *log.Logger, m *Volume) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Volume{}).Where("id = ?", m.ID).Save(m).Error +} + +func UpdateVolumeByWhere(logger *log.Logger, query map[string]interface{}, updates *Volume) (err error) { + var db = dao.Model(logger, dao.IronicWdb, Volume{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func GetAllVolumeByDeviceTypeId(logger *log.Logger, device_type_id string) (ml []*Volume, err error) { + ml = []*Volume{} + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and is_del = 0", device_type_id).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil +} diff --git a/bmp-openapi/dao/vxlanDao/vxlanDao.go b/bmp-openapi/dao/vxlanDao/vxlanDao.go new file mode 100644 index 0000000..58db9b3 --- /dev/null +++ b/bmp-openapi/dao/vxlanDao/vxlanDao.go @@ -0,0 +1,138 @@ +package vxlanDao + +import ( + "errors" + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Vxlan vxlan +type Vxlan struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + VxlanID int64 `gorm:"column:vxlan_id;type:bigint(20) unsigned" json:"vxlan_id"` // vxlan_id + Tenant string `gorm:"index:i_vxlan_tenant;column:tenant;type:varchar(64);not null" json:"tenant"` // 租户 + Az string `gorm:"column:az;type:varchar(32)" json:"az"` + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *Vxlan) TableName() string { + return "vxlan" +} + +// AddVxlan insert a new Vxlan into database and returns +// last inserted Id on success. +func AddVxlan(logger *log.Logger, m *Vxlan) (id int64, err error) { + + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetVxlanById retrieves Vxlan by Id. Returns error if +// Id doesn't exist +func GetVxlanById(logger *log.Logger, id int64) (v *Vxlan, err error) { + v = &Vxlan{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +//GetMaxVxlanID 没找到max方法,自己写 +func GetMaxVxlanId(logger *log.Logger, cloumn string) (n int64, err error) { + + sql := fmt.Sprintf("select max(%s) from vxlan", cloumn) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&n).Error + return +} + +func GetOrCreateVxlan(logger *log.Logger, query map[string]interface{}) (l *Vxlan, err error) { + l = &Vxlan{} + var db = dao.Model(logger, dao.IronicRdb, Vxlan{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err == nil { + return + } + //not found + maxVlanID, _ := GetMaxVxlanId(logger, "vxlan_id") + if maxVlanID < 0 { + return nil, errors.New("get max vxlan_id error!!") + } + s := Vxlan{ + // Az: query["az"].(string), + // Tenant: query["tenant"].(string), + VxlanID: maxVlanID + 1, + } + n, err := dao.CreateAndGetId(logger, dao.IronicRdb, s) + if err != nil { + return nil, err + } + s.ID = n + return &s, nil +} + +func GetOneVxlan(logger *log.Logger, query map[string]interface{}) (l *Vxlan, err error) { + l = &Vxlan{} + var db = dao.Model(logger, dao.IronicRdb, Vxlan{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// GetMultiVxlan retrieves all Vxlan matches certain condition. Returns empty list if +// no records exist +func GetMultiVxlan(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Vxlan, err error) { + var db = dao.Model(logger, dao.IronicRdb, Vxlan{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateVxlan updates Vxlan by Id and returns error if +// the record to be updated doesn't exist +func UpdateVxlanById(logger *log.Logger, m *Vxlan) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Vxlan{}).Where("id = ?", m.ID).Updates(m).Error +} + +func GetByTenant(logger *log.Logger, tanant, az string) (l *Vxlan, err error) { + l = &Vxlan{} + // err = dao.Where(logger, dao.IronicRdb, "tenant = ? and az = ? and is_del = 0", tanant, az).Take(l).Error + err = dao.Where(logger, dao.IronicRdb, "is_del = 0").Take(l).Error + + if err != nil { + return nil, err + } + return l, nil +} diff --git a/bmp-openapi/dao/wanIpDao/wanIpDao.go b/bmp-openapi/dao/wanIpDao/wanIpDao.go new file mode 100644 index 0000000..b2e5a26 --- /dev/null +++ b/bmp-openapi/dao/wanIpDao/wanIpDao.go @@ -0,0 +1,143 @@ +package wanIpDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// WanIP 外网ip +type WanIp struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + Az string `gorm:"unique_index:i_wan_ip_az_ip;column:az;type:varchar(32);not null" json:"az"` // az + WanSubnetID string `gorm:"column:wan_subnet_id;type:varchar(36);not null" json:"wan_subnet_id"` // 外网网段ID + IP string `gorm:"unique_index:i_wan_ip_az_ip;column:ip;type:varchar(32);not null" json:"ip"` // 外网ip + Status int8 `gorm:"column:status;type:tinyint(4);not null" json:"status"` // 是否已使用(0-未使用, 1-已使用) + LineType string `gorm:"column:line_type;type:varchar(20)" json:"line_type"` // 链路类型:bgp、dynamic_bgp + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *WanIp) TableName() string { + return "wan_ip" +} + +// AddWanIp insert a new WanIp into database and returns +// last inserted Id on success. +func AddWanIp(logger *log.Logger, m *WanIp) (id int64, err error) { + + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// AddMultiWanIp insert a new WanIp into database and returns +// last inserted Id on success. +func AddMultiWanIp(logger *log.Logger, m []*WanIp) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, device := range m { + device.CreateTime = time.Now() + device.UpdateTime = time.Now() + if err := tx.Create(device).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetWanIpById retrieves WanIp by Id. Returns error if +// Id doesn't exist +func GetWanIpById(logger *log.Logger, id int64) (v *WanIp, err error) { + + v = &WanIp{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetAllWanIp(logger *log.Logger, query map[string]interface{}) (ml []*WanIp, err error) { + + var db = dao.Model(logger, dao.IronicRdb, WanIp{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiWanIp retrieves all WanIp matches certain condition. Returns empty list if +// no records exist +func GetMultiWanIp(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*WanIp, err error) { + + var db = dao.Model(logger, dao.IronicRdb, WanIp{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateWanIp updates WanIp by Id and returns error if +// the record to be updated doesn't exist +func UpdateWanIpById(logger *log.Logger, m *WanIp) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, WanIp{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateMultiWanIps(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + updates["update_time"] = time.Now() + var db = dao.Model(logger, dao.IronicWdb, WanIp{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func QueryUnusedByAz(logger *log.Logger, az string, offset, limit int64) (ml []*WanIp, err error) { + + // err = dao.Where(logger, dao.IronicRdb, "az = ? and status = 0 and is_del = 0", az).Find(&ml).Error + err = dao.Where(logger, dao.IronicRdb, "status = 0 and is_del = 0").Find(&ml).Error + return + +} + +func QueryByAzAndIP(logger *log.Logger, az string, ips []string) (ml []*WanIp, err error) { + query := map[string]interface{}{ + "ip.in": ips, + // "az": az, + "is_del": "0", + } + var db = dao.Model(logger, dao.IronicRdb, WanIp{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + + err = db.Find(&ml).Error + return +} diff --git a/bmp-openapi/dao/wanSubnetDao/wanSubnetDao.go b/bmp-openapi/dao/wanSubnetDao/wanSubnetDao.go new file mode 100644 index 0000000..ef93aa9 --- /dev/null +++ b/bmp-openapi/dao/wanSubnetDao/wanSubnetDao.go @@ -0,0 +1,78 @@ +package wanSubnetDao + +import ( + "fmt" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// WanSubnet 外网网段 +type WanSubnet struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + UUID string `gorm:"column:uuid;type:varchar(36);not null" json:"uuid"` // 外网网段ID + Az string `gorm:"column:az;type:varchar(32);not null" json:"az"` // az + Cidr string `gorm:"column:cidr;type:varchar(32);not null" json:"cidr"` // 外网网段 + Gateway string `gorm:"column:gateway;type:varchar(32);not null" json:"gateway"` // 外网网关 + Mask string `gorm:"column:mask;type:varchar(32);not null" json:"mask"` // 外网掩码 + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *WanSubnet) TableName() string { + return "wan_subnet" +} + +// AddWanSubnet insert a new WanSubnet into database and returns +// last inserted Id on success. +func AddWanSubnet(logger *log.Logger, m *WanSubnet) (id int64, err error) { + + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicRdb, m) +} + +// GetWanSubnetById retrieves WanSubnet by Id. Returns error if +// Id doesn't exist +func GetWanSubnetById(logger *log.Logger, id int64) (v *WanSubnet, err error) { + + v = &WanSubnet{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllWanSubnet retrieves all WanSubnet matches certain condition. Returns empty list if +// no records exist +func GetMultiWanSubnet(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*WanSubnet, err error) { + var db = dao.Model(logger, dao.IronicRdb, WanSubnet{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + for _, v := range orderConditions { + db = db.Order(v) + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateWanSubnet updates WanSubnet by Id and returns error if +// the record to be updated doesn't exist +func UpdateWanSubnetById(logger *log.Logger, m *WanSubnet) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, WanSubnet{}).Where("id = ?", m.ID).Updates(m).Error +} diff --git a/bmp-openapi/go.mod b/bmp-openapi/go.mod new file mode 100644 index 0000000..f0979f8 --- /dev/null +++ b/bmp-openapi/go.mod @@ -0,0 +1,29 @@ +module coding.jd.com/aidc-bmp/bmp-openapi + +go 1.15 + +require github.com/beego/beego/v2 v2.0.1 + +require ( + coding.jd.com/aidc-bmp/bmp_log v0.0.0-00010101000000-000000000000 + git.jd.com/cps-golang/ironic-common v0.0.0-00010101000000-000000000000 + github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df + github.com/go-playground/validator/v10 v10.4.1 + github.com/go-redis/redis v6.15.1+incompatible + github.com/go-sql-driver/mysql v1.5.0 + github.com/google/go-cmp v0.5.5 // indirect + github.com/jinzhu/gorm v1.9.16 + github.com/jinzhu/now v1.1.2 // indirect + github.com/streadway/amqp v1.0.0 + github.com/tealeg/xlsx v1.0.5 + golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 + gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect + gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect + gopkg.in/goyy/goyy.v0 v0.0.0-20190218140538-82e7740e526e +) + +replace github.com/astaxie/beego => github.com/beego/beego v1.12.3 + +replace git.jd.com/cps-golang/ironic-common => ./bmp_vendor/ironic-common + +replace coding.jd.com/aidc-bmp/bmp_log => ./bmp_vendor/bmp_log diff --git a/bmp-openapi/go.sum b/bmp-openapi/go.sum new file mode 100644 index 0000000..2adfa2e --- /dev/null +++ b/bmp-openapi/go.sum @@ -0,0 +1,325 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= +github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk= +github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y= +github.com/beego/beego/v2 v2.0.1 h1:07a7Z0Ok5vbqyqh+q53sDPl9LdhKh0ZDy3gbyGrhFnE= +github.com/beego/beego/v2 v2.0.1/go.mod h1:8zyHi1FnWO1mZLwTn62aKRIZF/aIKvkCBB2JYs+eqQI= +github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ= +github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60= +github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= +github.com/coreos/etcd v3.3.25+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U= +github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= +github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= +github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd h1:83Wprp6ROGeiHFAP8WJdI2RoxALQYgdllERc3N5N2DM= +github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= +github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= +github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk= +github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y= +github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0= +github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= +github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df h1:Bao6dhmbTA1KFVxmJ6nBoMuOJit2yjEgLJpIMYpop0E= +github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df/go.mod h1:GJr+FCSXshIwgHBtLglIg9M2l2kQSi6QjVAngtzI08Y= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= +github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= +github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= +github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= +github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis v6.15.1+incompatible h1:BZ9s4/vHrIqwOb0OPtTQ5uABxETJ3NRuUNoSUurnkew= +github.com/go-redis/redis v6.15.1+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= +github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o= +github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/jinzhu/now v1.1.2 h1:eVKgfIdy9b6zbWBMgFpfDPoAMifwSZagU9HmEU6zgiI= +github.com/jinzhu/now v1.1.2/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDuKuq+uX4v1fulaMbA/7ZLLhjc85h7chZGBCQ= +github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= +github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.1.1 h1:sJZmqHoEaY7f+NPP8pgLB/WxulyR3fewgCM2qaSlBb4= +github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus= +github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U= +github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mitchellh/mapstructure v1.3.3 h1:SzB1nHZ2Xi+17FP0zVQBHIZqvwRN9408fJO8h+eeNA8= +github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.0 h1:Iw5WCbBcaAAd0fpRb1c9r5YCylv4XDoCSigm1zLevwU= +github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= +github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.7.0 h1:wCi7urQOGBsYcQROHqpUUX4ct84xp40t9R9JX0FuA/U= +github.com/prometheus/client_golang v1.7.0/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.10.0 h1:RyRA7RzGXQZiW+tGMr7sxa85G1z0yOpM1qq5c8lNawc= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.1.3 h1:F0+tqvhOksq22sc6iCHF5WGlWjdwj92p0udFh1VFBS8= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= +github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= +github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s= +github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE= +github.com/streadway/amqp v1.0.0 h1:kuuDrUJFZL1QYL9hUNuCxNObNzB0bV/ZG5jV3RWAQgo= +github.com/streadway/amqp v1.0.0/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/tealeg/xlsx v1.0.5 h1:+f8oFmvY8Gw1iUXzPk+kz+4GpbDZPK1FhPiQRd+ypgE= +github.com/tealeg/xlsx v1.0.5/go.mod h1:btRS8dz54TDnvKNosuAqxrM1QgN1udgk9O34bDCnORM= +github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= +github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= +go.etcd.io/etcd v3.3.25+incompatible/go.mod h1:yaeTdrJi5lOmYerz05bd8+V7KubZs8YSFZfzsF9A6aI= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f h1:+Nyd8tzPX9R7BWHguqsrbFdRx3WQ/1ib8I44HXV5yTA= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58 h1:1Bs6RVeBFtLZ8Yi1Hk07DiOqzvwLD/4hln4iahvFlag= +golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk= +gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE= +gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw= +gopkg.in/goyy/goyy.v0 v0.0.0-20190218140538-82e7740e526e h1:gtdbyLCHNaTi70xKjFhe89/vCZvQ/rlPcRyQNgtiArY= +gopkg.in/goyy/goyy.v0 v0.0.0-20190218140538-82e7740e526e/go.mod h1:0xBRLJ/WNDqMy7AGJ/CtRXvdKgU94c7uZ2oeqMR1FgA= +gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.5/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= diff --git a/bmp-openapi/jcloud_order.sql b/bmp-openapi/jcloud_order.sql new file mode 100644 index 0000000..e43c328 --- /dev/null +++ b/bmp-openapi/jcloud_order.sql @@ -0,0 +1,968 @@ +[mysqldump -h 10.208.12.72 -u root -pLpK9Jq12Zf jcloud_order] is a warning command +-- MySQL dump 10.16 Distrib 10.1.17-MariaDB, for Linux (x86_64) +-- +-- Host: 10.208.12.72 Database: jcloud_order +-- ------------------------------------------------------ +-- Server version 5.7.40 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `ads_user_resource_info` +-- + +DROP TABLE IF EXISTS `ads_user_resource_info`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `ads_user_resource_info` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', + `pin` varchar(64) DEFAULT NULL COMMENT 'pin', + `type` int(11) DEFAULT NULL COMMENT '类型', + `state` char(1) DEFAULT NULL COMMENT '类型', + `resource_id` varchar(64) DEFAULT NULL COMMENT '资源ID', + `source_id` varchar(64) DEFAULT NULL COMMENT '三方id', + `order_number` varchar(64) DEFAULT NULL COMMENT '订单号', + `create_time` char(19) DEFAULT NULL COMMENT '创建时间', + `update_time` char(19) DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=565 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `ads_user_resource_info` +-- + +LOCK TABLES `ads_user_resource_info` WRITE; +/*!40000 ALTER TABLE `ads_user_resource_info` DISABLE KEYS */; +/*!40000 ALTER TABLE `ads_user_resource_info` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `business_payment` +-- + +DROP TABLE IF EXISTS `business_payment`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `business_payment` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增数据库主键', + `business_code` varchar(50) NOT NULL COMMENT '业务主体Id', + `business_name` varchar(50) NOT NULL COMMENT '业务主体名称', + `payment_method` varchar(100) NOT NULL COMMENT '支付方式(uc的dictionary表中的key字段)', + `remark` varchar(255) DEFAULT NULL COMMENT '备注', + `status` tinyint(1) DEFAULT NULL COMMENT '状态:1-上线,2-下线', + `creator` varchar(50) DEFAULT NULL COMMENT '创建者', + `created_time` datetime DEFAULT NULL COMMENT '创建时间', + `updated_time` datetime DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`id`), + KEY `index_key` (`business_code`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8 COMMENT='业务主体和支付方式关系表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `business_payment` +-- + +LOCK TABLES `business_payment` WRITE; +/*!40000 ALTER TABLE `business_payment` DISABLE KEYS */; +INSERT INTO `business_payment` VALUES (18,'612','360度','companyBankpay','企业网银',1,NULL,NULL,NULL),(19,'612','360度','personalBankPay','个人网银',1,NULL,NULL,NULL),(20,'612','360度','offLinePay','线下汇款充值',1,NULL,NULL,NULL),(23,'612','360度','jdPay','京东支付',1,NULL,NULL,NULL),(24,'612','360度','weiXinPay','微信支付',1,NULL,NULL,NULL),(25,'612','360度','balancePay','余额支付',1,NULL,NULL,NULL),(26,'543','江苏京东','companyBankpay','企业网银',1,NULL,NULL,NULL),(27,'543','江苏京东','personalBankPay','个人网银',1,NULL,NULL,NULL),(28,'543','江苏京东','jdPay','京东支付',1,NULL,NULL,NULL),(29,'656','尚科','companyBankpay','企业网银',1,NULL,NULL,NULL),(30,'656','尚科','personalBankPay','个人网银',1,NULL,NULL,NULL),(31,'656','尚科','jdPay','京东支付',1,NULL,NULL,NULL); +/*!40000 ALTER TABLE `business_payment` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `business_service` +-- + +DROP TABLE IF EXISTS `business_service`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `business_service` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增数据库主键', + `business_code` varchar(50) NOT NULL COMMENT '业务主体Id', + `business_name` varchar(50) NOT NULL COMMENT '业务主体名称', + `site_type_id` int(4) NOT NULL COMMENT '站点类型Id', + `site_type_name` varchar(50) NOT NULL COMMENT '站点类型', + `app_code` varchar(50) NOT NULL COMMENT '业务线code', + `app_name` varchar(50) NOT NULL COMMENT '业务线名称', + `service_code` varchar(50) NOT NULL COMMENT '产品code', + `service_name` varchar(50) NOT NULL COMMENT '产品名称', + `remark` varchar(255) DEFAULT NULL COMMENT '备注', + `status` tinyint(1) DEFAULT NULL COMMENT '状态:1-上线,2-下线', + `creator` varchar(50) DEFAULT NULL COMMENT '创建者', + `created_time` datetime DEFAULT NULL COMMENT '创建时间', + `updated_time` datetime DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`id`), + KEY `index_key` (`site_type_id`,`app_code`,`service_code`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=44 DEFAULT CHARSET=utf8 COMMENT='业务主体和产品关系表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `business_service` +-- + +LOCK TABLES `business_service` WRITE; +/*!40000 ALTER TABLE `business_service` DISABLE KEYS */; +INSERT INTO `business_service` VALUES (18,'612','360度',0,'主站','domain','域名','domain','域名','域名服务',1,NULL,'2017-04-18 13:01:04','2017-04-18 13:01:10'),(19,'612','360度',0,'主站','jcloud','基础云','balance','负载均衡','云主机、子网、路由器、公网IP、负载均衡、云数据库、云硬盘、云存储、防火墙、监控报警、DDoS防护,直播',1,NULL,'2015-10-27 16:10:04','2015-10-27 16:10:04'),(20,'612','360度',0,'主站','jcloud','基础云','vm','云主机','云主机、子网、路由器、公网IP、负载均衡、云数据库、云硬盘、云存储、防火墙、监控报警、DDoS防护,直播',1,NULL,'2015-10-27 16:10:04','2015-10-27 16:10:04'),(21,'612','360度',0,'主站','jcloud','基础云','ip','公网IP','云主机、子网、路由器、公网IP、负载均衡、云数据库、云硬盘、云存储、防火墙、监控报警、DDoS防护,直播',1,NULL,'2016-01-20 14:29:23','2016-01-20 14:29:25'),(22,'612','360度',0,'主站','jcloud','基础云','database','云数据库MySQL','云主机、子网、路由器、公网IP、负载均衡、云数据库、云硬盘、云存储、防火墙、监控报警、DDoS防护,直播',1,NULL,'2016-01-22 15:45:45','2017-09-08 17:28:09'),(23,'612','360度',0,'主站','jcloud','基础云','disk','云硬盘','云主机、子网、路由器、公网IP、负载均衡、云数据库、云硬盘、云存储、防火墙、监控报警、DDoS防护,直播',1,NULL,'2016-01-25 11:11:31','2016-01-25 11:11:33'),(24,'612','360度',0,'主站','jcloud','基础云','storage','云存储','云主机、子网、路由器、公网IP、负载均衡、云数据库、云硬盘、云存储、防火墙、监控报警、DDoS防护,直播',1,NULL,'2016-02-29 16:19:56','2016-02-29 16:19:56'),(25,'612','360度',0,'主站','0003','数据云','DCS','数知','为开发者提供分布式、全托管、批量和实时数据计算服务。 ',1,NULL,'2016-03-29 15:13:13','2016-03-29 15:13:13'),(26,'612','360度',0,'主站','jcloud','基础云','redis','云缓存','云主机、子网、路由器、公网IP、负载均衡、云数据库、云硬盘、云存储、防火墙、监控报警、DDoS防护,直播',1,NULL,'2016-06-07 16:59:20','2016-06-07 16:59:20'),(27,'612','360度',0,'主站','jcloud','基础云','db_ro','云数据库MySQL-只读实例','云主机、子网、路由器、公网IP、负载均衡、云数据库、云硬盘、云存储、防火墙、监控报警、DDoS防护,直播',1,NULL,'2016-07-27 19:04:52','2017-09-08 17:04:52'),(28,'612','360度',0,'主站','jcloud','基础云','cdn','CDN','云主机、子网、路由器、公网IP、负载均衡、云数据库、云硬盘、云存储、防火墙、监控报警、DDoS防护,直播',1,NULL,'2016-08-25 16:09:45','2016-08-25 16:09:45'),(29,'612','360度',0,'主站','jcloud','基础云','nat_gw','NAT网关','云主机、子网、路由器、公网IP、负载均衡、云数据库、云硬盘、云存储、防火墙、监控报警、DDoS防护,直播',1,NULL,'2016-08-30 10:28:02','2016-08-30 10:28:02'),(30,'612','360度',0,'主站','jcloud','基础云','vpn','VPN','云主机、子网、路由器、公网IP、负载均衡、云数据库、云硬盘、云存储、防火墙、监控报警、DDoS防护,直播',1,NULL,'2016-08-30 10:28:02','2016-08-30 10:28:02'),(31,'612','360度',0,'主站','jcloud','基础云','ddos','BGP高防','云主机、子网、路由器、公网IP、负载均衡、云数据库、云硬盘、云存储、防火墙、监控报警、DDoS防护,直播',1,NULL,'2017-01-17 17:17:43','2017-01-17 17:17:44'),(32,'612','360度',0,'主站','jcloud','基础云','live','直播','云主机、子网、路由器、公网IP、负载均衡、云数据库、云硬盘、云存储、防火墙、监控报警、DDoS防护,直播',1,NULL,'2017-02-08 14:24:27','2017-02-08 14:24:27'),(34,'612','360度',0,'云市场','jcloudmark','云市场','web_self','云市场产品','自营建站',1,NULL,'2017-04-18 13:01:16','2017-04-18 13:01:18'),(35,'612','360度',0,'云市场','jcloudmark','云市场','mirror_self','自营镜像','自营镜像',1,NULL,'2017-04-18 13:01:22','2017-04-18 13:01:33'),(36,'543','江苏京东',0,'云市场','jcloudmark','云市场','web_other','云市场产品','第三方建站',1,NULL,'2017-04-18 13:01:28','2017-04-18 13:01:31'),(37,'543','江苏京东',0,'云市场','jcloudmark','云市场','mirror_other','第三方镜像','第三方镜像',1,NULL,'2017-04-18 13:01:37','2017-04-18 13:01:40'),(39,'612','360度',0,'主站','jcloud','基础云','mongodb','MongoDB','可信赖的基础服务\r\n可信赖的基础服务\r\n可信赖的基础服务',1,NULL,'2017-05-12 17:35:53','2017-05-12 17:35:53'),(40,'612','360度',0,'主站','jcloud','基础云','webanti','网站高防','网站高防',1,NULL,'2017-06-09 18:31:29','2017-06-09 18:31:37'),(41,'612','360度',0,'主站','jcloud','基础云','sqlserver','云数据库SQL Server','云数据库SQL Server',1,NULL,'2017-07-24 14:24:27','2017-07-24 14:24:27'),(42,'612','360度',0,'主站','jcloud','基础云','ipanti','IP高防','IP高防',1,NULL,'2017-11-30 17:46:56','2017-11-30 17:46:56'),(43,'612','360度',0,'主站','jcloud','基础云','nativecontainer','容器服务','容器服务',1,NULL,'2017-12-25 11:24:59','2017-12-25 11:24:59'); +/*!40000 ALTER TABLE `business_service` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `failure_task` +-- + +DROP TABLE IF EXISTS `failure_task`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `failure_task` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', + `params` varchar(2000) NOT NULL COMMENT '参数', + `failure_type` tinyint(1) NOT NULL COMMENT '失败原因:1-服务异常,2-网络异常', + `bean_name` varchar(100) NOT NULL COMMENT 'bean对象名称', + `operation` varchar(200) NOT NULL COMMENT '调用失败的方法', + `protocol` varchar(100) NOT NULL COMMENT '接口协议,如jsf、http', + `url` varchar(500) DEFAULT NULL COMMENT '接口地址', + `status` tinyint(1) NOT NULL COMMENT '状态:1-成功,2-失败', + `retry_time` int(10) DEFAULT NULL COMMENT '重试次数', + `msg` varchar(2000) DEFAULT NULL COMMENT '失败信息', + `created_time` datetime DEFAULT NULL COMMENT '创建时间', + `last_time` datetime DEFAULT NULL COMMENT '最后一次重试时间', + `batch_id` varchar(100) DEFAULT NULL COMMENT '批次id', + `sequence_no` int(10) DEFAULT NULL COMMENT '序号(针对batch_id字段)', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=806 DEFAULT CHARSET=utf8 COMMENT='失败任务表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `failure_task` +-- + +LOCK TABLES `failure_task` WRITE; +/*!40000 ALTER TABLE `failure_task` DISABLE KEYS */; +/*!40000 ALTER TABLE `failure_task` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `kafka_consumer_log` +-- + +DROP TABLE IF EXISTS `kafka_consumer_log`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `kafka_consumer_log` ( + `id` int(12) NOT NULL AUTO_INCREMENT COMMENT '自增数据库主键', + `topic` varchar(255) DEFAULT NULL COMMENT '主题', + `partition` int(10) NOT NULL COMMENT '分区', + `offset` int(10) DEFAULT NULL COMMENT '站点', + `kafka_key` varchar(255) DEFAULT NULL COMMENT '消息的key值', + `kafka_value` varchar(2000) NOT NULL COMMENT '消息的value', + `md5` varchar(255) NOT NULL COMMENT '对消息value的md5 值', + `batch_id` varchar(64) DEFAULT NULL COMMENT '批次号', + `sequence_no` int(10) DEFAULT NULL COMMENT '订单信息序号', + `status` tinyint(2) NOT NULL COMMENT '消息处理的状态 1、成功 2、失败', + `create_time` datetime DEFAULT NULL COMMENT '创建时间', + PRIMARY KEY (`id`), + UNIQUE KEY `md5` (`md5`) +) ENGINE=InnoDB AUTO_INCREMENT=843348 DEFAULT CHARSET=utf8 COMMENT='kafka消费者日志'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `kafka_consumer_log` +-- + +LOCK TABLES `kafka_consumer_log` WRITE; +/*!40000 ALTER TABLE `kafka_consumer_log` DISABLE KEYS */; +/*!40000 ALTER TABLE `kafka_consumer_log` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `kafka_producer_log` +-- + +DROP TABLE IF EXISTS `kafka_producer_log`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `kafka_producer_log` ( + `id` int(12) NOT NULL AUTO_INCREMENT COMMENT '自增数据库主键', + `topic` varchar(255) DEFAULT NULL COMMENT '主题', + `kafka_value` varchar(2000) NOT NULL COMMENT '消息的value', + `md5` varchar(255) NOT NULL COMMENT '对消息value的md5 值', + `batch_id` varchar(64) DEFAULT NULL COMMENT '批次号', + `sequence_no` int(10) DEFAULT NULL COMMENT '订单信息序号', + `status` tinyint(2) NOT NULL COMMENT '消息处理的状态 1、成功 2、失败', + `create_time` datetime DEFAULT NULL COMMENT '创建时间', + PRIMARY KEY (`id`), + UNIQUE KEY `md5` (`md5`) +) ENGINE=InnoDB AUTO_INCREMENT=909203 DEFAULT CHARSET=utf8 COMMENT='kafka生产者日志'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `kafka_producer_log` +-- + +LOCK TABLES `kafka_producer_log` WRITE; +/*!40000 ALTER TABLE `kafka_producer_log` DISABLE KEYS */; +/*!40000 ALTER TABLE `kafka_producer_log` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `order` +-- + +DROP TABLE IF EXISTS `order`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `order` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增数据库主键', + `order_number` varchar(50) NOT NULL COMMENT '订单编号', + `parent_id` bigint(20) DEFAULT NULL COMMENT '父订单id,无父单时为-1', + `process_type` tinyint(1) DEFAULT '1' COMMENT '流程类型:1、主站_标准流程_V1.0(当前标准下单接口)2、服务api_预付费下单免支付_V1.0(政务云需求场景,取消对接财务系统)3、服务api_标准下单流程_V1.0(OEM需求场景,取消对接财务系统)', + `self_support_type` tinyint(1) DEFAULT '1' COMMENT '自营类型:1-自营,2-非自营,3-两者并存', + `split_type` tinyint(1) DEFAULT NULL COMMENT '拆分类型,是否有子订单:0-无子单,1-有子单', + `pin` varchar(30) NOT NULL COMMENT '用户pin', + `proposer` varchar(200) DEFAULT NULL COMMENT '申请人', + `payer` varchar(200) DEFAULT NULL COMMENT '付款人', + `site_type` tinyint(1) NOT NULL DEFAULT '0' COMMENT '站点类型 0:主站,1:国际站,2:云市场,3:API', + `order_type` tinyint(1) DEFAULT NULL COMMENT '订单类型:1-新购,2-续费,3-配置变更', + `charge_mode` tinyint(1) DEFAULT NULL COMMENT '订单计费类型:1-按配置,2-按用量,3-按包年/包月,4-一次性付费', + `app_code` varchar(50) DEFAULT NULL COMMENT '应用code:domain-域名,0003-数据云,jcloud-基础云,jcloudmark-云市场', + `service_code` varchar(50) DEFAULT NULL COMMENT '产品 code', + `item_name` varchar(255) DEFAULT NULL COMMENT '商品名称,用于订单列表显示', + `status` tinyint(1) DEFAULT NULL COMMENT '订单状态:1-已支付,2-失败,3-未支付,4-处理中,5-已取消', + `currency` tinyint(1) NOT NULL DEFAULT '1' COMMENT '币种 1:人民币,2:美元', + `pay_type` tinyint(1) NOT NULL DEFAULT '1' COMMENT '付费类型 1:预付费,2:后付费', + `activity_type` tinyint(4) NOT NULL DEFAULT '0' COMMENT '活动订单类型:0-正常订单,1-活动订单', + `activity_info` varchar(500) DEFAULT NULL COMMENT '活动信息,json串 [{"promotionType":2,"activityCode":123},{"promotionType":3,"activityCode":456}] ', + `total_fee` decimal(14,2) NOT NULL COMMENT '订单总额(原价,不考虑折扣、优惠)', + `actual_fee` decimal(14,2) DEFAULT NULL COMMENT '实际总额(如未改价则与计算总价一致,否则不一致)', + `is_actual_fee_modified` tinyint(1) NOT NULL DEFAULT '0' COMMENT '应付价格是否被修改过:0-未修改,1-已修改;', + `discount_fee` decimal(14,2) DEFAULT NULL COMMENT '优惠总额', + `paid_fee` decimal(14,2) DEFAULT NULL COMMENT '已支付总额', + `favorable_detail_json` varchar(512) DEFAULT NULL COMMENT '优惠明细,json结构,包括折扣、代金券、优惠券、商品券等促销信息的id、促销额、实际优惠额。', + `voucher_pay` decimal(14,2) DEFAULT '0.00' COMMENT '代金券支付金额', + `promotion_favorable_info` varchar(2000) DEFAULT NULL COMMENT '促销优惠明细', + `balance_pay` decimal(14,2) DEFAULT NULL COMMENT '余额支付金额', + `money_pay` decimal(14,2) DEFAULT NULL COMMENT '现金支付金额', + `payment_channel` tinyint(1) DEFAULT NULL COMMENT '支付方式:0-余额支付,1-企业网银,2-个人网银,3-微信支付,4-京东支付,5-线下汇款', + `created_time` datetime DEFAULT NULL COMMENT '订单创建时间', + `updated_time` datetime DEFAULT NULL COMMENT '订单更新时间', + `pay_time` datetime DEFAULT NULL COMMENT '支付时间', + `remark` varchar(255) DEFAULT NULL COMMENT '备注', + `origin_order_number` varchar(50) DEFAULT NULL COMMENT '原订单编号,针对升降配、续费', + `source_id` varchar(50) DEFAULT NULL COMMENT '来源标识', + `task_id` varchar(40) DEFAULT NULL COMMENT '任务id:对应于中间层任务id,打包购买时的一个事务Id', + `receipt_org_number` varchar(50) DEFAULT NULL COMMENT '收款机构编号', + `payment_number` varchar(50) DEFAULT NULL COMMENT '支付单号', + `return_url` varchar(500) DEFAULT NULL COMMENT '支付成功后的回调地址', + `source` varchar(100) DEFAULT NULL COMMENT '订单来源,PC业务订单为空,OpenAPI订单固定为‘API’', + `mod_count` int(10) DEFAULT NULL COMMENT '更改次数', + `refund_fee` decimal(14,2) DEFAULT NULL COMMENT '已退款金额', + `unique_code` varchar(100) DEFAULT NULL COMMENT 'MD5加密串', + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_order_number` (`order_number`), + UNIQUE KEY `unique_code` (`unique_code`), + KEY `idx_parent_id` (`parent_id`), + KEY `idx_pin_app_code` (`pin`,`app_code`), + KEY `idx_pay_time` (`pay_time`), + KEY `idx_source_id` (`source_id`), + KEY `idx_created_time` (`created_time`) +) ENGINE=InnoDB AUTO_INCREMENT=2876954 DEFAULT CHARSET=utf8 COMMENT='订单'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `order` +-- + +LOCK TABLES `order` WRITE; +/*!40000 ALTER TABLE `order` DISABLE KEYS */; +/*!40000 ALTER TABLE `order` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `order_configuration` +-- + +DROP TABLE IF EXISTS `order_configuration`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `order_configuration` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', + `process_type` int(4) NOT NULL COMMENT '流程类型', + `site_type` int(4) NOT NULL COMMENT '站点类型', + `app_code` varchar(50) NOT NULL COMMENT '业务线', + `service_code` varchar(50) DEFAULT NULL COMMENT '产品code', + `config_type` int(10) NOT NULL COMMENT '配置类型:1-签名key;2-配额接口域名', + `test_value` varchar(200) DEFAULT NULL COMMENT '开发测试环境用', + `online_value` varchar(200) DEFAULT NULL COMMENT '预发线上环境用', + `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态:1-开启,2-不开启', + `remark` varchar(200) DEFAULT NULL COMMENT '备注', + `created_time` datetime DEFAULT NULL COMMENT '创建时间', + `updated_time` datetime DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `unique_configuration` (`process_type`,`site_type`,`app_code`,`service_code`,`config_type`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=153 DEFAULT CHARSET=utf8 COMMENT='订单配置'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `order_configuration` +-- + +LOCK TABLES `order_configuration` WRITE; +/*!40000 ALTER TABLE `order_configuration` DISABLE KEYS */; +INSERT INTO `order_configuration` VALUES (105,1,0,'jcloud','jcloud',1,'3b41befe77a4c9cc62dd5141712a6246','0ee22ec2386f317f282701abc7fcb6cf',1,NULL,'2017-05-12 17:14:52','2017-05-12 17:14:52'),(106,1,0,'0003','0003',1,'b2cb9c22fe664a0c2600303dfe9dfecf','1f2da7d57abf331bf107efa58576743c',1,NULL,'2017-05-12 17:14:52','2017-05-12 17:14:52'),(107,1,0,'domain','domain',1,'9a539fc8de8605ca10af5d1e97d3cc67','caa6fe99f3e0fa064d18058297904f8f',1,NULL,'2017-05-12 17:14:52','2017-05-12 17:14:52'),(108,1,0,'jcloudmark','jcloudmark',1,'481b78e3e9dbd184f80859eec9ef65e1','451f679e2a2575dbca2ac21e19433e99',1,NULL,'2017-05-12 17:14:52','2017-05-12 17:14:52'),(110,1,0,'0003','DCS',3,'1','1',1,NULL,'2017-05-10 16:00:58','2017-05-10 16:00:58'),(111,1,0,'domain','domain',3,'1','1',1,NULL,'2017-05-10 16:00:58','2017-05-10 16:00:58'),(113,1,0,'jcloud','cdn',3,'1','1',1,NULL,'2017-05-10 16:00:58','2017-09-11 21:56:31'),(114,1,0,'jcloud','database',3,'1','1',1,NULL,'2017-05-10 16:00:58','2017-10-20 06:53:17'),(115,1,0,'jcloud','db_ro',3,'1','1',1,NULL,'2017-05-10 16:00:58','2017-10-20 06:54:13'),(116,1,0,'jcloud','ddos',3,'1','1',1,NULL,'2017-05-10 16:00:58','2017-09-28 18:50:13'),(119,1,0,'jcloud','live',3,'1','1',1,NULL,'2017-05-10 16:00:58','2017-09-28 14:38:03'),(120,1,0,'jcloud','nat_gw',3,'0','0',1,NULL,'2017-05-10 16:00:58','2017-05-10 16:00:58'),(122,1,0,'jcloud','storage',3,'1','1',1,NULL,'2017-05-10 16:00:58','2017-10-12 20:04:12'),(124,1,0,'jcloud','vpn',3,'0','0',1,NULL,'2017-05-10 16:00:58','2017-05-10 16:00:58'),(125,1,0,'jcloud','webanti',3,'1','1',1,NULL,'2017-05-10 16:00:58','2017-05-10 16:00:58'),(126,1,0,'jcloudmark','mirror_other',3,'1','1',1,NULL,'2017-05-10 16:00:58','2017-05-10 16:00:58'),(127,1,0,'jcloudmark','mirror_self',3,'1','1',1,NULL,'2017-05-10 16:00:58','2017-05-10 16:00:58'),(128,1,0,'jcloudmark','web_other',3,'1','1',1,NULL,'2017-05-10 16:00:58','2017-05-10 16:00:58'),(129,1,0,'jcloudmark','web_self',3,'1','1',1,NULL,'2017-05-10 16:00:58','2017-05-10 16:00:58'),(131,1,0,'jcloud','sqlserver',3,'1','1',1,NULL,'2017-07-24 14:00:58','2017-07-24 14:00:58'),(134,1,0,'jcloud','mongodb',3,'1','1',1,NULL,'2017-08-30 01:26:17','2017-08-30 01:26:17'),(135,1,0,'jcloud','redis',3,'1','1',1,NULL,'2017-08-30 11:45:44','2017-08-30 11:45:44'),(136,1,0,'jcloud','vm',2,'vpc-biz.jcloud.com','vpc-biz.jcloud.com',1,NULL,'2017-09-07 17:42:01','2017-09-07 17:42:01'),(137,1,0,'jcloud','disk',2,'vpc-biz.jcloud.com','vpc-biz.jcloud.com',1,NULL,'2017-09-07 17:42:11','2017-09-07 17:42:11'),(138,1,0,'jcloud','ip',2,'vpc-biz.jcloud.com','vpc-biz.jcloud.com',1,NULL,'2017-09-07 17:42:18','2017-09-07 17:42:18'),(139,1,0,'jcloud','balance',2,'vpc-biz.jcloud.com','vpc-biz.jcloud.com',1,NULL,'2017-09-07 17:42:27','2017-09-07 17:42:27'),(146,1,0,'jcloud','vm',3,'0','0',1,NULL,'2017-09-14 03:07:40','2017-09-14 03:07:40'),(147,1,0,'jcloud','disk',3,'0','0',1,NULL,'2017-09-14 03:07:57','2017-09-14 03:07:57'),(148,1,0,'jcloud','ip',3,'0','0',1,NULL,'2017-09-14 03:08:07','2017-09-14 03:08:07'),(149,1,0,'jcloud','balance',3,'0','0',1,NULL,'2017-09-14 03:08:16','2017-09-14 03:08:16'),(150,1,0,'jcloud','ipanti',3,'1','1',1,NULL,'2017-11-30 17:46:56','2017-11-30 17:46:56'),(151,4,0,'jcloud','jcloud',1,'4441befe77a4c9cc62dd1514712a6211','4ee22ec2386f317f323201abc7fcb611',1,NULL,'2017-12-19 16:50:03','2017-12-19 16:50:03'),(152,1,0,'jcloud','nativecontainer',3,'1','1',1,NULL,'2017-12-25 11:24:59','2017-12-25 11:24:59'); +/*!40000 ALTER TABLE `order_configuration` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `order_extra` +-- + +DROP TABLE IF EXISTS `order_extra`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `order_extra` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', + `pin` varchar(30) NOT NULL COMMENT '用户pin', + `order_number` varchar(50) NOT NULL COMMENT '订单编号', + `provider_pin` varchar(100) NOT NULL COMMENT '服务商pin', + `provider_name` varchar(200) NOT NULL COMMENT '服务商名称', + `created_time` datetime DEFAULT NULL COMMENT '创建时间', + `updated_time` datetime DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=387 DEFAULT CHARSET=utf8 COMMENT='订单扩展表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `order_extra` +-- + +LOCK TABLES `order_extra` WRITE; +/*!40000 ALTER TABLE `order_extra` DISABLE KEYS */; +/*!40000 ALTER TABLE `order_extra` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `order_item` +-- + +DROP TABLE IF EXISTS `order_item`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `order_item` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增数据库主键', + `order_number` varchar(50) DEFAULT NULL COMMENT '订单编号', + `order_item_number` varchar(50) DEFAULT NULL COMMENT '订单商品编号', + `pin` varchar(30) DEFAULT NULL COMMENT '用户pin', + `charge_mode` tinyint(1) DEFAULT NULL COMMENT '订单计费类型:1-按配置,2-按用量,3-按包年/包月,4-一次性付费(用来支持单个订单多种计费类型的情况)', + `charge_duration` int(10) DEFAULT NULL COMMENT '计费时长', + `app_code` varchar(50) DEFAULT NULL COMMENT '应用code:domain-域名,0003-数据云,jcloud-基础云,jcloudmark-云市场', + `service_code` varchar(50) DEFAULT NULL COMMENT '产品code', + `region` varchar(50) DEFAULT NULL COMMENT '资源中心', + `network_operator` tinyint(1) DEFAULT NULL COMMENT '网络类型 0: non-BGP, 1: BGP', + `item_id` varchar(50) DEFAULT NULL COMMENT '商品id', + `sku_id` varchar(50) DEFAULT NULL COMMENT 'sku code', + `item_name` varchar(100) DEFAULT NULL COMMENT '商品名称', + `item_type` varchar(50) DEFAULT NULL COMMENT '1-普通商品,2-活动商品', + `promotion_info` varchar(500) DEFAULT NULL COMMENT '促销明细,json数组: [{"promotionType":1,"activityCode":123},{"promotionType":2,"activityCode":}] ', + `resize_formula_type` tinyint(4) DEFAULT NULL COMMENT '变配明细,变配订单该字段不能为空:1-升配,2-降配,3-配置转包年包月', + `extra_info` varchar(500) DEFAULT NULL COMMENT '商品规格参数', + `quantity` int(11) DEFAULT NULL COMMENT '数量', + `formula` varchar(1000) DEFAULT NULL COMMENT '计算公式(配置细项)', + `price_snapshot` varchar(1000) DEFAULT NULL COMMENT '价格快照', + `total_fee` decimal(14,2) DEFAULT NULL COMMENT '计算总价(原价,不考虑折扣、优惠)', + `actual_fee` decimal(14,2) DEFAULT NULL COMMENT '实际总额(如未改价则与计算总价一致,否则不一致)', + `discount_fee` decimal(14,2) DEFAULT NULL COMMENT '优惠总额', + `start_time` datetime DEFAULT NULL COMMENT '订单开始计费时间', + `end_time` datetime DEFAULT NULL COMMENT '订单停止计费时间', + `favorable_detail_json` varchar(512) DEFAULT NULL COMMENT '优惠明细(按订单分摊后),json字符串结构(id、value、fee),包括折扣、代金券、优惠券、商品券等促销信息的id、促销额、实际优惠额', + `voucher_pay` decimal(14,2) DEFAULT '0.00' COMMENT '代金券支付金额', + `promotion_favorable_item_info` varchar(2000) DEFAULT NULL COMMENT '促销优惠明细', + `balance_pay` decimal(14,2) DEFAULT NULL COMMENT '余额支付金额(按订单分摊)', + `money_pay` decimal(14,2) DEFAULT NULL COMMENT '现金支付金额(按订单分摊)', + `operator_type` tinyint(1) DEFAULT NULL COMMENT '操作者类型:0-用户;1-管理员(运营);-1 系统', + `operator_name` varchar(20) DEFAULT NULL COMMENT '操作者名称', + `status` tinyint(1) DEFAULT NULL COMMENT '订单商品状态:0-创建中,1-成功,2-失败', + `created_time` datetime DEFAULT NULL COMMENT '创建时间', + `updated_time` datetime DEFAULT NULL COMMENT '更新时间', + `remark` varchar(100) DEFAULT NULL COMMENT '备注', + `unit` varchar(100) DEFAULT NULL COMMENT '计费时长单位:1-小时,2-天,3-月,4-年', + `refund_fee` decimal(14,2) DEFAULT NULL COMMENT '已退款金额', + PRIMARY KEY (`id`), + UNIQUE KEY `uni_item_number` (`order_item_number`), + KEY `idx_number_service_code` (`order_number`,`service_code`), + KEY `idx_item_id_pin` (`item_id`,`pin`) +) ENGINE=InnoDB AUTO_INCREMENT=2681011 DEFAULT CHARSET=utf8 COMMENT='订单商品'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `order_item` +-- + +LOCK TABLES `order_item` WRITE; +/*!40000 ALTER TABLE `order_item` DISABLE KEYS */; +/*!40000 ALTER TABLE `order_item` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `order_jdv_info` +-- + +DROP TABLE IF EXISTS `order_jdv_info`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `order_jdv_info` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', + `order_number` varchar(50) NOT NULL COMMENT '主单的订单编号', + `pin` varchar(50) NOT NULL COMMENT '用户pin', + `jdv_content` varchar(500) NOT NULL COMMENT '来源渠道信息字符串', + `jdv_hash` varchar(500) DEFAULT NULL COMMENT '域名希值', + `utm_source` varchar(100) DEFAULT NULL COMMENT '来源域名', + `utm_campaign` varchar(100) DEFAULT NULL COMMENT '联盟id', + `utm_media` varchar(100) DEFAULT NULL COMMENT '推广类型', + `utm_term` varchar(100) DEFAULT NULL COMMENT '推广关键词', + `rt` varchar(100) DEFAULT NULL COMMENT 'unix时间戳(毫秒)', + `remark` varchar(500) DEFAULT NULL COMMENT '备注', + `created_time` datetime DEFAULT NULL COMMENT '创建时间', + PRIMARY KEY (`id`), + KEY `IDX_COMBINED` (`order_number`,`pin`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=1338 DEFAULT CHARSET=utf8 COMMENT='渠道来源信息'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `order_jdv_info` +-- + +LOCK TABLES `order_jdv_info` WRITE; +/*!40000 ALTER TABLE `order_jdv_info` DISABLE KEYS */; +/*!40000 ALTER TABLE `order_jdv_info` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `order_receipts` +-- + +DROP TABLE IF EXISTS `order_receipts`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `order_receipts` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增数据库主键', + `pin` varchar(50) DEFAULT NULL COMMENT 'pin', + `order_number` varchar(50) DEFAULT NULL COMMENT '订单编号', + `trade_type` tinyint(1) DEFAULT NULL COMMENT '交易类型 1充值、2消费', + `payment_channel` tinyint(1) DEFAULT NULL COMMENT '支付方式:0-余额支付,1-企业网银,2-个人网银,3-微信支付,4-京东支付,5-线下汇款', + `payment_number` varchar(50) DEFAULT NULL COMMENT '支付单号', + `amount` decimal(14,2) DEFAULT NULL COMMENT '金额', + `payment_time` datetime DEFAULT NULL COMMENT '支付时间', + `created_time` datetime DEFAULT NULL COMMENT '创建时间', + `updated_time` datetime DEFAULT NULL COMMENT '更新时间', + `funds_type` tinyint(4) DEFAULT NULL COMMENT '资金类型:1:收入 2:支出', + `user_group` tinyint(4) DEFAULT NULL COMMENT '用户标识 1:其他非云鼎, 2:云鼎', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=39460 DEFAULT CHARSET=utf8 COMMENT='订单实收'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `order_receipts` +-- + +LOCK TABLES `order_receipts` WRITE; +/*!40000 ALTER TABLE `order_receipts` DISABLE KEYS */; +/*!40000 ALTER TABLE `order_receipts` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `order_record` +-- + +DROP TABLE IF EXISTS `order_record`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `order_record` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增数据库主键', + `order_number` varchar(50) DEFAULT NULL COMMENT '订单编号', + `process_type` tinyint(1) DEFAULT '1' COMMENT '流程类型:1、主站_标准流程_V1.0(当前标准下单接口)2、服务api_预付费下单免支付_V1.0(政务云需求场景,取消对接财务系统)3、服务api_标准下单流程_V1.0(OEM需求场景,取消对接财务系统)', + `self_support_type` tinyint(1) DEFAULT '1' COMMENT '自营类型:1-自营,2-非自营,3-两者并存', + `pin` varchar(30) DEFAULT NULL COMMENT '用户pin', + `site_type` tinyint(1) NOT NULL DEFAULT '1' COMMENT '站点类型 1:主站,2:国际站', + `order_type` tinyint(1) DEFAULT NULL COMMENT '订单类型:1-新购,2-续费,3-配置变更', + `charge_mode` tinyint(1) DEFAULT NULL COMMENT '订单计费类型:1-按配置,2-按用量,3-按包年/包月,4-一次性付费', + `app_code` varchar(50) DEFAULT NULL COMMENT '应用code:domain-域名,0003-数据云,jcloud-基础云,jcloudmark-云市场', + `item_name` varchar(255) DEFAULT NULL COMMENT '商品名称,用于订单列表显示', + `status` tinyint(1) DEFAULT NULL COMMENT '订单状态:1-已支付,2-失败,3-未支付,4-处理中,5-已取消,6-部分退款,7-全部退款', + `currency` tinyint(1) NOT NULL DEFAULT '1' COMMENT '币种 1:人民币,2:美元', + `pay_type` tinyint(1) NOT NULL DEFAULT '1' COMMENT '付费类型 1:预付费,2:后付费', + `total_fee` decimal(14,2) DEFAULT NULL COMMENT '订单总额(原价,不考虑折扣、优惠)', + `actual_fee` decimal(14,2) DEFAULT NULL COMMENT '实际总额(如未改价则与计算总价一致,否则不一致)', + `is_actual_fee_modified` tinyint(1) NOT NULL DEFAULT '0' COMMENT '应付价格是否被修改过:0-未修改,1-已修改;', + `discount_fee` decimal(14,2) DEFAULT NULL COMMENT '优惠总额', + `paid_fee` decimal(14,2) DEFAULT NULL COMMENT '已支付总额', + `favorable_detail_json` varchar(512) DEFAULT NULL COMMENT '优惠明细,json结构,包括折扣、代金券、优惠券、商品券等促销信息的id、促销额、实际优惠额', + `voucher_pay` decimal(14,2) DEFAULT '0.00' COMMENT '代金券支付金额', + `balance_pay` decimal(14,2) DEFAULT NULL COMMENT '余额支付金额', + `money_pay` decimal(14,2) DEFAULT NULL COMMENT '现金支付金额', + `payment_channel` tinyint(1) DEFAULT NULL COMMENT '支付方式:0-余额支付,1-企业网银,2-个人网银,3-微信支付,4-京东支付,5-线下汇款', + `created_time` datetime DEFAULT NULL COMMENT '订单创建时间', + `updated_time` datetime DEFAULT NULL COMMENT '订单更新时间', + `remark` varchar(255) DEFAULT NULL COMMENT '备注', + `origin_order` varchar(50) DEFAULT NULL COMMENT '原订单编号,针对升降配、续费', + `source_id` varchar(50) DEFAULT NULL COMMENT '来源标识', + `task_id` varchar(40) DEFAULT NULL COMMENT '任务id:对应于中间层任务id,打包购买时的一个事务Id', + `op_type` tinyint(1) DEFAULT NULL COMMENT '操作类型:0-订单提交,1-取消订单,2-支付完成,3-订单失败,4-生成完成,6-退款申请,7-退款完成', + `operator_type` tinyint(1) DEFAULT NULL COMMENT '操作者类型:0-用户,1-管理员(运营),-1 系统', + `operator_name` varchar(20) DEFAULT NULL COMMENT '操作者名称', + `ip` varchar(200) DEFAULT NULL COMMENT 'ip地址', + `device_info` varchar(2000) DEFAULT NULL COMMENT '设备信息', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=1880153 DEFAULT CHARSET=utf8 COMMENT='订单记录'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `order_record` +-- + +LOCK TABLES `order_record` WRITE; +/*!40000 ALTER TABLE `order_record` DISABLE KEYS */; +/*!40000 ALTER TABLE `order_record` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `order_record_2017` +-- + +DROP TABLE IF EXISTS `order_record_2017`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `order_record_2017` ( + `id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '自增数据库主键', + `order_number` varchar(50) DEFAULT NULL COMMENT '订单编号', + `process_type` tinyint(1) DEFAULT '1' COMMENT '流程类型:1、主站_标准流程_V1.0(当前标准下单接口)2、服务api_预付费下单免支付_V1.0(政务云需求场景,取消对接财务系统)3、服务api_标准下单流程_V1.0(OEM需求场景,取消对接财务系统)', + `self_support_type` tinyint(1) DEFAULT '1' COMMENT '自营类型:1-自营,2-非自营,3-两者并存', + `pin` varchar(30) DEFAULT NULL COMMENT '用户pin', + `site_type` tinyint(1) NOT NULL DEFAULT '1' COMMENT '站点类型 1:主站,2:国际站', + `order_type` tinyint(1) DEFAULT NULL COMMENT '订单类型:1-新购,2-续费,3-配置变更', + `charge_mode` tinyint(1) DEFAULT NULL COMMENT '订单计费类型:1-按配置,2-按用量,3-按包年/包月,4-一次性付费', + `app_code` varchar(50) DEFAULT NULL COMMENT '应用code:domain-域名,0003-数据云,jcloud-基础云,jcloudmark-云市场', + `item_name` varchar(255) DEFAULT NULL COMMENT '商品名称,用于订单列表显示', + `status` tinyint(1) DEFAULT NULL COMMENT '订单状态:1-已支付,2-失败,3-未支付,4-处理中,5-已取消,6-部分退款,7-全部退款', + `currency` tinyint(1) NOT NULL DEFAULT '1' COMMENT '币种 1:人民币,2:美元', + `pay_type` tinyint(1) NOT NULL DEFAULT '1' COMMENT '付费类型 1:预付费,2:后付费', + `total_fee` decimal(14,2) DEFAULT NULL COMMENT '订单总额(原价,不考虑折扣、优惠)', + `actual_fee` decimal(14,2) DEFAULT NULL COMMENT '实际总额(如未改价则与计算总价一致,否则不一致)', + `is_actual_fee_modified` tinyint(1) NOT NULL DEFAULT '0' COMMENT '应付价格是否被修改过:0-未修改,1-已修改;', + `discount_fee` decimal(14,2) DEFAULT NULL COMMENT '优惠总额', + `paid_fee` decimal(14,2) DEFAULT NULL COMMENT '已支付总额', + `favorable_detail_json` varchar(512) DEFAULT NULL COMMENT '优惠明细,json结构,包括折扣、代金券、优惠券、商品券等促销信息的id、促销额、实际优惠额', + `balance_pay` decimal(14,2) DEFAULT NULL COMMENT '余额支付金额', + `money_pay` decimal(14,2) DEFAULT NULL COMMENT '现金支付金额', + `payment_channel` tinyint(1) DEFAULT NULL COMMENT '支付方式:0-余额支付,1-企业网银,2-个人网银,3-微信支付,4-京东支付,5-线下汇款', + `created_time` datetime DEFAULT NULL COMMENT '订单创建时间', + `updated_time` datetime DEFAULT NULL COMMENT '订单更新时间', + `remark` varchar(255) DEFAULT NULL COMMENT '备注', + `origin_order` varchar(50) DEFAULT NULL COMMENT '原订单编号,针对升降配、续费', + `source_id` varchar(50) DEFAULT NULL COMMENT '来源标识', + `task_id` varchar(40) DEFAULT NULL COMMENT '任务id:对应于中间层任务id,打包购买时的一个事务Id', + `op_type` tinyint(1) DEFAULT NULL COMMENT '操作类型:0-订单提交,1-取消订单,2-支付完成,3-订单失败,4-生成完成,6-退款申请,7-退款完成', + `operator_type` tinyint(1) DEFAULT NULL COMMENT '操作者类型:0-用户,1-管理员(运营),-1 系统', + `operator_name` varchar(20) DEFAULT NULL COMMENT '操作者名称', + `ip` varchar(200) DEFAULT NULL COMMENT 'ip地址', + `device_info` varchar(2000) DEFAULT NULL COMMENT '设备信息' +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `order_record_2017` +-- + +LOCK TABLES `order_record_2017` WRITE; +/*!40000 ALTER TABLE `order_record_2017` DISABLE KEYS */; +/*!40000 ALTER TABLE `order_record_2017` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `order_signature` +-- + +DROP TABLE IF EXISTS `order_signature`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `order_signature` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', + `process_type` int(4) NOT NULL COMMENT '流程类型', + `site_type` int(4) NOT NULL COMMENT '站点类型', + `app_code` varchar(50) NOT NULL COMMENT '业务线', + `service_code` varchar(50) DEFAULT NULL COMMENT '产品code', + `test_sign_key` varchar(100) NOT NULL COMMENT '开发测试签名key', + `online_sign_key` varchar(100) NOT NULL COMMENT '线上签名key', + `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态:1-在线,2-下线', + `created_time` datetime DEFAULT NULL, + `updated_time` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `business_type` (`process_type`,`site_type`,`app_code`,`service_code`) +) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `order_signature` +-- + +LOCK TABLES `order_signature` WRITE; +/*!40000 ALTER TABLE `order_signature` DISABLE KEYS */; +/*!40000 ALTER TABLE `order_signature` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `order_snapshot` +-- + +DROP TABLE IF EXISTS `order_snapshot`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `order_snapshot` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增数据库主键', + `batch_id` varchar(100) NOT NULL COMMENT '快照批次id', + `pin` varchar(50) NOT NULL COMMENT '用户pin', + `snapshot` varchar(2000) NOT NULL COMMENT '订单快照', + `ip` varchar(100) DEFAULT NULL COMMENT 'ip', + `device` varchar(2000) DEFAULT NULL COMMENT '设备信息', + `created_time` datetime DEFAULT NULL COMMENT '创建时间', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=588307 DEFAULT CHARSET=utf8 COMMENT='记录订单快照表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `order_snapshot` +-- + +LOCK TABLES `order_snapshot` WRITE; +/*!40000 ALTER TABLE `order_snapshot` DISABLE KEYS */; +/*!40000 ALTER TABLE `order_snapshot` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `order_temp` +-- + +DROP TABLE IF EXISTS `order_temp`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `order_temp` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', + `batch_id` varchar(100) NOT NULL COMMENT '批次id', + `pin` varchar(50) NOT NULL COMMENT '用户pin', + `snapshot` varchar(2000) NOT NULL COMMENT '订单信息json串', + `sequence_no` int(10) NOT NULL COMMENT '订单信息序号', + `ip` varchar(100) DEFAULT NULL COMMENT 'ip', + `device` varchar(2000) DEFAULT NULL COMMENT '设备信息', + `created_time` datetime DEFAULT NULL COMMENT '创建时间', + `unique_code` varchar(100) DEFAULT NULL COMMENT 'MD5加密串', + PRIMARY KEY (`id`), + KEY `IDX_BATCHID` (`batch_id`) USING BTREE, + KEY `IDX_COMBINED` (`batch_id`,`pin`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=41471 DEFAULT CHARSET=utf8 COMMENT='临时订单表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `order_temp` +-- + +LOCK TABLES `order_temp` WRITE; +/*!40000 ALTER TABLE `order_temp` DISABLE KEYS */; +/*!40000 ALTER TABLE `order_temp` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `payment_journal` +-- + +DROP TABLE IF EXISTS `payment_journal`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `payment_journal` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', + `pin` varchar(50) DEFAULT NULL COMMENT 'pin', + `order_number` varchar(50) NOT NULL COMMENT '订单号', + `trade_type` tinyint(1) DEFAULT NULL COMMENT '交易类型 1充值、2消费', + `payment_number` varchar(50) NOT NULL COMMENT '支付单号', + `amount` decimal(14,2) NOT NULL COMMENT '订单金额', + `payment_channel` tinyint(1) DEFAULT NULL COMMENT '支付方式:0-余额支付,1-企业网银,2-个人网银,3-微信支付,4-京东支付,5-线下汇款', + `seller_account` varchar(255) DEFAULT NULL COMMENT '卖家支付帐号', + `bank_code` varchar(255) DEFAULT NULL COMMENT '银行code', + `remittance_code` varchar(255) DEFAULT NULL COMMENT '汇款识别码', + `app_code` varchar(255) DEFAULT NULL COMMENT '应用code', + `service_code` varchar(255) DEFAULT NULL COMMENT '服务code', + `created_time` datetime DEFAULT NULL COMMENT '创建时间', + `updated_time` datetime DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_payment_number` (`payment_number`) USING BTREE, + KEY `idx_order_number` (`order_number`) +) ENGINE=InnoDB AUTO_INCREMENT=59508 DEFAULT CHARSET=utf8 COMMENT='支付流水'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `payment_journal` +-- + +LOCK TABLES `payment_journal` WRITE; +/*!40000 ALTER TABLE `payment_journal` DISABLE KEYS */; +/*!40000 ALTER TABLE `payment_journal` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `payment_result` +-- + +DROP TABLE IF EXISTS `payment_result`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `payment_result` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', + `pin` varchar(50) DEFAULT NULL COMMENT 'pin', + `payment_number` varchar(50) NOT NULL COMMENT '本系统的订单编号', + `payment_channel` tinyint(1) DEFAULT NULL COMMENT '支付方式:0-余额支付,1-企业网银,2-个人网银,3-微信支付,4-京东支付,5-线下汇款', + `trade_type` tinyint(1) DEFAULT NULL COMMENT '交易类型 1充值、2消费', + `trade_status` varchar(20) DEFAULT NULL COMMENT '交易状态', + `trade_number` varchar(64) DEFAULT NULL COMMENT '支付渠道的交易号', + `subject` varchar(256) DEFAULT NULL COMMENT '商品名称', + `total_fee` decimal(14,2) NOT NULL COMMENT '支付金额', + `fee_type` tinyint(1) DEFAULT NULL COMMENT '币种:1-人民币,2-美元', + `bank_code` varchar(50) DEFAULT NULL COMMENT '付款银行', + `payment_time` datetime DEFAULT NULL COMMENT '支付完成时间', + `sent_account_status` tinyint(1) DEFAULT NULL COMMENT '是否已发送对账通知:1-未发送,2-已发送,3-发送失败', + `full_text` varchar(4000) DEFAULT NULL COMMENT '结果通知全文', + `created_time` datetime DEFAULT NULL COMMENT '创建时间', + `updated_time` datetime DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_payment_number` (`payment_number`) USING BTREE +) ENGINE=InnoDB AUTO_INCREMENT=38588 DEFAULT CHARSET=utf8 COMMENT='支付结果'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `payment_result` +-- + +LOCK TABLES `payment_result` WRITE; +/*!40000 ALTER TABLE `payment_result` DISABLE KEYS */; +/*!40000 ALTER TABLE `payment_result` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `refund_order` +-- + +DROP TABLE IF EXISTS `refund_order`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `refund_order` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增数据库主键', + `order_number` varchar(50) DEFAULT NULL COMMENT '订单编号', + `order_item_number` varchar(50) DEFAULT NULL COMMENT '订单商品编号', + `pin` varchar(30) DEFAULT NULL COMMENT '用户pin', + `refund_type` tinyint(1) DEFAULT NULL COMMENT '退款类型:1-用户退款,2-系统退款', + `total_fee` decimal(14,2) DEFAULT NULL COMMENT '退款总额', + `favorable_detail_json` varchar(512) DEFAULT NULL COMMENT '促销退款明细,json结构,包括代金券、商品券等促销信息的id、促销额、退款金额', + `balance_fee` decimal(14,2) DEFAULT NULL COMMENT '余额退款金额', + `money_fee` decimal(14,2) DEFAULT NULL COMMENT '现金退款金额', + `payment_channel` tinyint(1) DEFAULT NULL COMMENT '支付方式:0-余额支付,1-企业网银,2-个人网银,3-微信支付,4-京东支付,5-线下汇款', + `status` tinyint(1) DEFAULT NULL COMMENT '退款状态:0-申请退款,1-退款审核中,2-已退款,3-已取消,4-退款失败,5-财务审核驳回,6-财务审批通过', + `created_time` datetime DEFAULT NULL COMMENT '订单创建时间', + `updated_time` datetime DEFAULT NULL COMMENT '订单更新时间', + `remark` varchar(2000) DEFAULT NULL COMMENT '备注', + `actual_order_number` varchar(2000) DEFAULT NULL COMMENT '实际退款订单号', + `ref_id` varchar(50) DEFAULT NULL COMMENT 'UC退款业务ID', + `order_type` tinyint(1) DEFAULT NULL COMMENT '1:余额提现,2:订单退款', + `erp_order_id` varchar(50) DEFAULT NULL COMMENT 'uc充值单号', + `refund_route` tinyint(1) DEFAULT NULL COMMENT '余额提现为空 1、原路退 2、退款到余额', + PRIMARY KEY (`id`), + KEY `idx_number_ref` (`order_number`,`ref_id`) +) ENGINE=InnoDB AUTO_INCREMENT=6374 DEFAULT CHARSET=utf8 COMMENT='退款单'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `refund_order` +-- + +LOCK TABLES `refund_order` WRITE; +/*!40000 ALTER TABLE `refund_order` DISABLE KEYS */; +/*!40000 ALTER TABLE `refund_order` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `refund_order_detail` +-- + +DROP TABLE IF EXISTS `refund_order_detail`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `refund_order_detail` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id', + `order_number` varchar(50) NOT NULL COMMENT '订单号', + `refund_order_id` bigint(20) NOT NULL COMMENT '退款订单号', + `sub_order_number` varchar(50) DEFAULT NULL COMMENT '子订单号', + `item_id` varchar(50) DEFAULT NULL COMMENT '商品id', + `total_fee` decimal(14,2) NOT NULL COMMENT '退款总金额', + `balance_fee` decimal(14,2) DEFAULT NULL COMMENT '余额退款金额', + `money_fee` decimal(14,2) DEFAULT NULL COMMENT '现金退款金额', + `status` tinyint(1) DEFAULT NULL COMMENT '退款状态', + `create_time` datetime NOT NULL COMMENT '创建时间', + `creator` varchar(50) NOT NULL COMMENT '创建人', + `updated_time` datetime DEFAULT NULL COMMENT '修改时间', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=493 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `refund_order_detail` +-- + +LOCK TABLES `refund_order_detail` WRITE; +/*!40000 ALTER TABLE `refund_order_detail` DISABLE KEYS */; +/*!40000 ALTER TABLE `refund_order_detail` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `refund_order_ots` +-- + +DROP TABLE IF EXISTS `refund_order_ots`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `refund_order_ots` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增数据库主键', + `order_number` varchar(50) NOT NULL COMMENT '订单号', + `refund_fee` decimal(14,2) NOT NULL COMMENT '退款金额', + `status` tinyint(1) NOT NULL COMMENT '状态0:受理状态;-1:错误状态 ;2:成功状态 1.失败状态', + `created_time` datetime DEFAULT NULL COMMENT '创建时间', + `updated_time` datetime DEFAULT NULL COMMENT '更新时间', + `remark` varchar(500) DEFAULT NULL COMMENT '备注', + `refund_apply_id` varchar(100) DEFAULT NULL COMMENT '台账退款业务id', + `order_type` tinyint(1) DEFAULT NULL COMMENT '订单类型,1:余额提现,2:订单退款', + `info` varchar(100) DEFAULT NULL COMMENT '错误信息', + `payment_channel` tinyint(2) DEFAULT NULL COMMENT '支付渠道', + `pin` varchar(30) DEFAULT NULL COMMENT '用户pin', + PRIMARY KEY (`id`), + UNIQUE KEY `uni_refund_apply_id` (`refund_apply_id`), + KEY `idx_payment_channel` (`payment_channel`) +) ENGINE=InnoDB AUTO_INCREMENT=1062 DEFAULT CHARSET=utf8 COMMENT='退款ots表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `refund_order_ots` +-- + +LOCK TABLES `refund_order_ots` WRITE; +/*!40000 ALTER TABLE `refund_order_ots` DISABLE KEYS */; +/*!40000 ALTER TABLE `refund_order_ots` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `reverse_sterilisation` +-- + +DROP TABLE IF EXISTS `reverse_sterilisation`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `reverse_sterilisation` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增数据库主键', + `pin` varchar(30) DEFAULT NULL COMMENT '用户pin', + `order_number` varchar(50) DEFAULT NULL COMMENT '充值单ID', + `payment_number` varchar(50) DEFAULT NULL COMMENT '支付单ID', + `refund_number` varchar(50) DEFAULT NULL COMMENT '退款单ID', + `amount` decimal(14,2) DEFAULT NULL COMMENT '金额', + `status` tinyint(1) DEFAULT NULL COMMENT '冲销状态 1冲销成功 2 余额不足冲销失败', + `platform_account_status` tinyint(1) DEFAULT NULL COMMENT '台账状态 1成功 2失败', + `created_time` datetime DEFAULT NULL COMMENT '创建时间', + `updated_time` datetime DEFAULT NULL COMMENT '修改时间', + `remark` varchar(50) DEFAULT NULL COMMENT '备注', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='逆向冲销'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `reverse_sterilisation` +-- + +LOCK TABLES `reverse_sterilisation` WRITE; +/*!40000 ALTER TABLE `reverse_sterilisation` DISABLE KEYS */; +/*!40000 ALTER TABLE `reverse_sterilisation` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `settlement_detail` +-- + +DROP TABLE IF EXISTS `settlement_detail`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `settlement_detail` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增数据库主键', + `pin` varchar(50) DEFAULT NULL COMMENT 'pin', + `order_number` varchar(50) DEFAULT NULL COMMENT '订单编号', + `trade_type` tinyint(1) DEFAULT NULL COMMENT '交易类型 1充值、2消费', + `payment_channel` tinyint(1) DEFAULT NULL COMMENT '支付方式:0-余额支付,1-企业网银,2-个人网银,3-微信支付,4-京东支付,5-线下汇款', + `payment_number` varchar(255) DEFAULT NULL COMMENT '支付单号', + `amount` decimal(14,2) DEFAULT NULL COMMENT '订单金额', + `receivable` decimal(14,2) DEFAULT NULL COMMENT '应付金额', + `created_time` datetime DEFAULT NULL COMMENT '创建时间', + `updated_time` datetime DEFAULT NULL COMMENT '更新时间', + `status` tinyint(1) DEFAULT '1' COMMENT '标识对账状态 1、成功 2、失败', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=38402 DEFAULT CHARSET=utf8 COMMENT='对账凭证'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `settlement_detail` +-- + +LOCK TABLES `settlement_detail` WRITE; +/*!40000 ALTER TABLE `settlement_detail` DISABLE KEYS */; +/*!40000 ALTER TABLE `settlement_detail` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `sys_config` +-- + +DROP TABLE IF EXISTS `sys_config`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `sys_config` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', + `key` varchar(100) NOT NULL COMMENT '键', + `value` varchar(2000) NOT NULL COMMENT '值', + `sys` varchar(100) DEFAULT NULL COMMENT '系统', + `type` varchar(100) NOT NULL COMMENT '类别', + `description` varchar(2000) DEFAULT NULL COMMENT '描述', + `created_time` datetime NOT NULL COMMENT '创建时间', + `updated_time` datetime NOT NULL COMMENT '更新时间', + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COMMENT='系统配置表'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `sys_config` +-- + +LOCK TABLES `sys_config` WRITE; +/*!40000 ALTER TABLE `sys_config` DISABLE KEYS */; +INSERT INTO `sys_config` VALUES (1,'cancel_interval','15','jcloud_order','order_auto_cancel','订单自动取消时间间隔','2017-09-19 14:45:28','2017-09-19 14:45:32'),(2,'cancel_switch','1','jcloud_order','order_auto_cancel','订单自动取消开关,0为关闭,1为开启','2017-09-21 10:32:16','2017-09-21 10:49:42'),(3,'quota_switch','1','jcloud_order','order_check_quota','配额:0为关闭,1为开启','2017-09-21 10:32:16','2017-09-21 10:32:16'),(4,'signature_time','300000','jcloud_order','check_signature_time','签名时间戳有效时间,单位是ms','2017-09-21 10:32:16','2017-09-21 15:45:37'),(5,'pin','boss-01,JaneCloud002,JaneCloud003,jd_pengchang,JaneCloud007,boss-05,JaneCloud008,dujuangrace,jessesky,黑莓cc,jd_57b822db30d1c,陈令奎,bjhehuan,beesharp,skty,125752875-47861837,datajingdo_m,jd_411f536a7746e,R_gabriel,sunfire_999,JD电商云,jos-api,apatriot,auhiug,tx4808,laodang1990,yuanshuaimingtest,wangchaoyang27,lizhenzhen2015,jcloud2016,gingindini,sunimoon,jd_430e83f009d83,sqjiankong','jcloud_order','order_test_pin','测试人员的pin','2017-10-24 18:32:27','2017-10-24 18:32:27'),(6,'pin','JaneCloud005,JaneCloud004,数据云AGS,1439195762-738219,jd_4af74c4322d89,choui,仇俊宝,quning_jd,hello_yunhai,排骨虾,jd_7bf1c61b1973d,tianlei2939,jcloud_001,dataJcloudTest1,jcloud_005,pmo_cloud,xdata_ml,huyp891,jcloudiaas2,jcloudiaas3,jcloudiaas4,jcloudiaas5,商业合作部测试账号,sunbo9,yuanyuanzhang18,jcloud_iaas,区块链项目测试,Govcloud,2017徐小白来了,miamiamia1986,inf_dev,ringcjs','jcloud_order','order_test_pin','测试人员的pin','2017-10-24 18:32:27','2017-10-24 18:32:27'),(7,'pin','电销测试账号,jd_cdntest,jccstest_dx,jccstest_kf,iaas-ops,qwertyuiop8787,jcloud_ami,jd_4db1955cf8390,jd_数据库测试_00A,流岚鱼,sec365buy,wdtxliqf,jcloud_025,xingyixun,jd_18e0c2452e2c5,jd_7f0131d8b9767,jd_67668e1a8e701,jd_8669e5c5f7809,lookatmebay1,areatest,xueliang001,15110055080_p,satsuki_li,zhuhc999,pid-plat,pmo_jd_a,bz_jcloud_test,PMO_JCLOUD,jcloudhillhouse,云安全外测,jcloud-b2b-04','jcloud_order','order_test_pin','测试人员的pin','2017-10-24 18:32:27','2017-10-24 18:32:27'),(8,'pin','jcloud-b2c-03,liuxws,jd_52ca057742db6,jd_saas_pre,刘刘看看,jcloud_security,coolcole,changchuan1,JDCSolution,network_test','jcloud_order','order_test_pin','测试人员的pin','2017-10-24 18:32:27','2017-10-24 18:32:27'),(9,'notice.user.week','guojing13,zhenglei6,cuienduo,zhaojunqiang,liweijun3,yuweiwei1','jcloud_order','ews.mail','周报统计人员名单','2017-12-26 14:37:04','2017-12-26 14:37:04'),(10,'hdsh.voucherInfo.user','huangwanyue,lihuirong,zhaoyu7,daijinquan,liujia51,houchao,yuweiwei1,shiyening,cuienduo,zhaojunqiang,zhenglei6','jcloud_order','ews.mail','华东-上海代金券信息统计接收人','2017-12-27 14:41:21','2017-12-27 14:41:21'); +/*!40000 ALTER TABLE `sys_config` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2024-08-02 13:37:25 diff --git a/bmp-openapi/logic/apikeyLogic/apikeyLogic.go b/bmp-openapi/logic/apikeyLogic/apikeyLogic.go new file mode 100644 index 0000000..2fe6c85 --- /dev/null +++ b/bmp-openapi/logic/apikeyLogic/apikeyLogic.go @@ -0,0 +1,186 @@ +package apikeyLogic + +import ( + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/apikeyDao" + + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + namespacePrefix "git.jd.com/cps-golang/ironic-common/ironic/common/NamespacePrefixs" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +func ApikeyEntity2Apikey(logger *log.Logger, o *apikeyDao.Apikey) *responseTypes.Apikey { + + tz := logger.GetPoint("timezone").(string) + return &responseTypes.Apikey{ + ID: o.ID, + ApikeyID: o.ApikeyID, + Name: o.Name, + ReadOnly: o.ReadOnly, + Token: o.Token, + Type: o.Type, + UserID: o.UserID, + CreatedBy: o.CreatedBy, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + UpdatedBy: o.UpdatedBy, + UpdatedTime: util.TimestampToString(int64(o.UpdatedTime), tz), + } +} + +func GetApikeyById(logger *log.Logger, apikeyId string) (*responseTypes.Apikey, error) { + userId := logger.GetPoint("userId").(string) + entity, err := apikeyDao.GetApikeyById(logger, apikeyId) + if err != nil { + logger.Warn("GetapikeyByUuid sql error:", apikeyId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if entity.UserID != userId { + panic(constant.BuildInvalidArgumentWithArgs("无此apikey的访问权限", "cannot access apiKey")) + } + return ApikeyEntity2Apikey(logger, entity), nil +} + +func CreateApikey(logger *log.Logger, param *requestTypes.CreateApikeyRequest) (string, error) { + + userId := logger.GetPoint("userId").(string) + + v, _ := apikeyDao.GetAllApikey(logger, map[string]interface{}{ + "user_id": userId, + "is_del": baseLogic.IS_NOT_DEL, + "source": "operation", + }) + if len(v) >= 2 { + logger.Warn("two apikey already exists", userId) + panic(constant.BuildCANCELLEDWithArgs("支持创建2个API密钥", "Only supports creating 2 keypairs")) + } + + list, _ := apikeyDao.GetAllApikey(logger, map[string]interface{}{ + "name": param.Name, + "user_id": userId, + "is_del": baseLogic.IS_NOT_DEL, + "source": "operation", + }) + if len(list) != 0 { + logger.Warn("apikey name exist:", param.Name) + panic(constant.BuildCANCELLEDWithArgs("apikey名称已存在", "apikey name exist")) + } + apikeyEntity := &apikeyDao.Apikey{ + Name: param.Name, + ReadOnly: param.ReadOnly, + Token: commonUtil.GetRandString("", 32, false, true, true), + Type: param.Type, + UserID: userId, + Source: "operation", + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + apikeyEntity.ApikeyID = commonUtil.GetRandString("apikey-", namespacePrefix.INSTANCE_ID_LENGTH, false, true, true) + if _, err := apikeyDao.AddApikey(logger, apikeyEntity); err != nil { + logger.Warnf("Createapikey Addapikey sql error, entity:%s, error:%s", util.ObjToJson(apikeyEntity), err.Error()) + return "", err + } + return apikeyEntity.ApikeyID, nil +} + +func ModifyApikey(logger *log.Logger, param *requestTypes.ModifyApikeyRequest, apikeyId string) error { + userId := logger.GetPoint("userId").(string) + list, _ := apikeyDao.GetAllApikey(logger, map[string]interface{}{ + "name": param.Name, + "user_id": userId, + "is_del": baseLogic.IS_NOT_DEL, + }) + if len(list) != 0 { + logger.Warn("apikey name exist:", param.Name) + panic(constant.BuildCANCELLEDWithArgs("apikey名称已存在", "apikey name exist")) + } + + k, err := apikeyDao.GetApikeyById(logger, apikeyId) + if err != nil { + logger.Warn("GetapikeyByUuid sql error:", apikeyId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if userId != k.UserID { + panic(constant.BuildInvalidArgumentWithArgs("无权修改此apikey", "cannot modify apikey")) + } + k.Name = param.Name + k.ReadOnly = param.ReadOnly + if err := apikeyDao.UpdateApikeyById(logger, k); err != nil { + logger.Warn("Modifyapikey UpdateapikeyById sql error:", apikeyId, err.Error()) + return err + } + return nil +} + +func DeleteApikey(logger *log.Logger, apikeyId string) error { + userId := logger.GetPoint("userId").(string) + entity, err := apikeyDao.GetApikeyById(logger, apikeyId) + if err != nil { + logger.Warn("GetapikeyByUuid sql error:", apikeyId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if entity.UserID != userId { + panic(constant.BuildInvalidArgumentWithArgs("无权删除此apikey", "cannot delete apikey")) + } + entity.IsDel = 1 + entity.UpdatedTime = int(time.Now().Unix()) + entity.DeletedTime = int(time.Now().Unix()) + if err := apikeyDao.UpdateApikeyById(logger, entity); err != nil { + logger.Warn("Deleteapikey UpdateapikeyById sql error:", apikeyId, err.Error()) + return err + } + return nil +} + +func GetApikeyList(logger *log.Logger, param requestTypes.QueryApikeysRequest, p util.Pageable) ([]*responseTypes.Apikey, int64, error) { + userId := logger.GetPoint("userId").(string) + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "name": param.Name, + //"apikey_id": param.apikeyID, + //"default_project_id": param.DefaultProjectID, + "user_id": userId, + "is_del": 0, + "source": "operation", + } + count, err := apikeyDao.GetApikeyCount(logger, query) + if err != nil { + logger.Warnf("GetapikeyCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*apikeyDao.Apikey{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = apikeyDao.GetMultiApikey(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = apikeyDao.GetMultiApikey(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("QueryByapikeyIds GetAllapikey sql error:", err.Error()) + return nil, 0, err + } + apikeys := []*responseTypes.Apikey{} + for _, entity := range entityList { + apikeys = append(apikeys, ApikeyEntity2Apikey(logger, entity)) + } + return apikeys, count, nil +} + +func ValidateApiKey(logger *log.Logger, key string) (*apikeyDao.Apikey, error) { + k, err := apikeyDao.GetApikeyByToken(logger, key) + if err != nil { + return nil, err + } + if k == nil { + return nil, nil + } + return k, nil +} diff --git a/bmp-openapi/logic/auditLogLogic/auditLogLogic.go b/bmp-openapi/logic/auditLogLogic/auditLogLogic.go new file mode 100644 index 0000000..62c89ce --- /dev/null +++ b/bmp-openapi/logic/auditLogLogic/auditLogLogic.go @@ -0,0 +1,327 @@ +package auditLogLogic + +import ( + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/auditLogsDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + "git.jd.com/cps-golang/ironic-common/ironic/enums/AuditLogsType" +) + +var auditLogsTypeEnMap = map[string]string{ + AuditLogsType.AuditLogsPutaway: "putaway", + AuditLogsType.AuditLogsUnPutaway: "unPutaway", + AuditLogsType.AuditLogsStartInstances: "startInstance", + AuditLogsType.AuditLogsStopInstances: "stopInstance", + AuditLogsType.AuditLogsRestartInstances: "restartInstance", + AuditLogsType.AuditLogsResetInstanceStatus: "resetInstanceStatus", + AuditLogsType.AuditLogsRemoveDevice: "removeDevice", + AuditLogsType.AuditLogsInstanceResetPassword: "resetInstancePassword", + AuditLogsType.AuditLogsReinstallInstance: "reinstallInstance", + AuditLogsType.AuditLogsDeleteDevice: "deleteDevice", + AuditLogsType.AuditLogsEditInstanceName: "editInstanceName", + AuditLogsType.AuditLogsCollectHardwareInfo: "collectDevice", + AuditLogsType.AuditLogsTypeCreateInstances: "createInstance", + AuditLogsType.AuditLogsDeleteInstance: "deleteInstance", + AuditLogsType.AuditLogsTypeLockInstances: "lockInstance", +} + +// +var auditLogsTypeZhMap = map[string]string{ + AuditLogsType.AuditLogsPutaway: "设备上架", + AuditLogsType.AuditLogsUnPutaway: "设备下架", + AuditLogsType.AuditLogsStartInstances: "设备开机", + AuditLogsType.AuditLogsStopInstances: "设备关机", + AuditLogsType.AuditLogsRestartInstances: "设备重启", + AuditLogsType.AuditLogsResetInstanceStatus: "重置实例状态", + AuditLogsType.AuditLogsRemoveDevice: "设备移除", + AuditLogsType.AuditLogsInstanceResetPassword: "重置密码", + AuditLogsType.AuditLogsReinstallInstance: "重装系统", + AuditLogsType.AuditLogsDeleteDevice: "设备删除", + AuditLogsType.AuditLogsEditInstanceName: "编辑实例名称", + AuditLogsType.AuditLogsCollectHardwareInfo: "设备采集", + AuditLogsType.AuditLogsTypeCreateInstances: "创建实例", + AuditLogsType.AuditLogsDeleteInstance: "实例删除", + AuditLogsType.AuditLogsTypeLockInstances: "实例锁定", +} + +func SaveAuditLogs(logger *log.Logger, deviceId string, instanceId string, msgType string) error { + + userID := logger.GetPoint("userId").(string) + var username string + if userID != "" { + userEntity, err := userDao.GetUserById(logger, userID) + if err != nil { + logger.Warnf("SaveAuditLogs.GetUserById error, user_id:%s, error:%s", userID, err.Error()) + } else { + username = userEntity.UserName + } + } + + deviceEntity, err := deviceDao.GetDeviceById(logger, deviceId) + if err != nil { + logger.Warnf("SaveAuditLogs.GetBySn error, device_id:%s, error:%s", deviceId, err.Error()) + } + + al := &auditLogsDao.AuditLogs{ + Logid: util.GetUuid("al-"), + Sn: deviceEntity.Sn, + DeviceID: deviceEntity.DeviceID, + Operation: msgType, + OperateUserID: userID, + OperateUserName: username, + CreatedTime: int(time.Now().Unix()), + Result: "success", + } + _, err = auditLogsDao.AddAuditLogs(logger, al) + if err != nil { + logger.Warnf("SaveAuditLogs.AddAuditLogs error, al:%s, error:%s", util.ObjToJson(al), err.Error()) + } else { + logger.Warnf("SaveAuditLogs.AddAuditLogs success, al:%s", util.ObjToJson(al)) + } + return err +} + +func DeleteAuditLogsByDeviceId(logger *log.Logger, deviceId string) error { + + q := map[string]interface{}{ + "is_del": 0, + "device_id": deviceId, + } + u := map[string]interface{}{ + "is_del": 1, + } + err := auditLogsDao.UpdateMultiAuditLogs(logger, q, u) + if err != nil { + logger.Warnf("DeleteAuditLogsByDeviceId.UpdateMultiAuditLogs error, deviceId:%s, error:%s", deviceId, err.Error()) + } else { + logger.Warnf("DeleteAuditLogsByDeviceId.UpdateMultiAuditLogs success, deviceId:%s", deviceId) + } + return err +} + +func QueryAuditLogs(logger *log.Logger, param *requestTypes.DescribeAuditLogsRequest, p util.Pageable) ([]*responseTypes.AuditLog, int64, error) { + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "sn": param.Sn, + "is_del": 0, + } + if param.Operation != "" { + query["operation.in"] = strings.Split(param.Operation, ",") + } + if param.UserName != "" { + query["operate_user_name"] = param.UserName + } + if param.Result != "" { + query["result.in"] = strings.Split(param.Result, ",") + } + if param.StartTime != 0 { + query["created_time.gte"] = param.StartTime + } + if param.EndTime != 0 { + query["updated_time.lte"] = param.EndTime + } + + count, err := auditLogsDao.GetAuditLogsCount(logger, query) + if err != nil { + logger.Warnf("QueryAuditLogs.GetAuditLogsCount sql error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + dts := []*auditLogsDao.AuditLogs{} + if param.IsAll == baseLogic.IS_ALL { + dts, err = auditLogsDao.GetAllAuditLogs(logger, query) + } else { + dts, err = auditLogsDao.QueryAuditLogs(logger, query, offset, limit) + } + if err != nil { + logger.Warnf("QueryAuditLogs sql err, param:%s, error:%s", util.ObjToJson(param), err.Error()) + return nil, 0, err + } + res := []*responseTypes.AuditLog{} + + for _, value := range dts { + v := AuditLogEntity2AuditLog(logger, value) + + res = append(res, v) + } + return res, count, err +} + +func AuditLogEntity2AuditLog(logger *log.Logger, param *auditLogsDao.AuditLogs) *responseTypes.AuditLog { + res := &responseTypes.AuditLog{ + ID: param.ID, + LogID: param.Logid, + Operation: param.Operation, + UserName: param.OperateUserName, + UserID: param.OperateUserID, + Sn: param.Sn, + DeviceID: param.DeviceID, + InstanceID: param.InstanceID, + Result: param.Result, + FailReason: param.FailReason, + OperateTime: param.CreatedTime, + FinishTime: param.UpdatedTime, + } + var reason string + if logger.GetPoint("language").(string) == baseLogic.EN_US { + res.OperationName = auditLogsTypeEnMap[param.Operation] + reason = baseLogic.InstanceReasonEn[res.FailReason] + } else { + res.OperationName = auditLogsTypeZhMap[param.Operation] + reason = baseLogic.InstanceReason[res.FailReason] + } + if reason == "" { + reason = res.FailReason + } + res.FailReason = reason + + return res +} + +/* +AuditLogsPutaway = "PutawayDevice" //上架 + AuditLogsUnPutaway = "UnPutawayDevice" //下架 + AuditLogsStartInstances = "StartInstances" //开机 + AuditLogsStopInstances = "StopInstances" //关机 + AuditLogsRestartInstances = "RestartInstances" //重启 + AuditLogsResetInstanceStatus = "ResetInstances" //重置实例状态(新增) + AuditLogsRemoveDevice = "RemoveDevice" //设备移除(新增) + AuditLogsDeleteDevice = "DeleteDevice" //设备删除(新增) + AuditLogsDeleteInstance = "DeleteInstance" //回收实例 + AuditLogsInstanceResetPassword = "InstanceResetPassword" //重置密码 + AuditLogsReinstallInstance = "ReinstallInstance" //重装系统 + AuditLogsEditInstanceName = "EditInstanceName" //编辑实例名称(新增) + AuditLogsCollectHardwareInfo = "CollectHardwareInfo" //设备采集 + AuditLogsTypeCreateInstances = "CreateInstances" //创建实例 + AuditLogsTypeLockInstances = "LockInstances" //锁定实例(新增) +*/ + +func DescribeAuditLogsTypes(logger *log.Logger) []responseTypes.AuditLogsType { + if logger.GetPoint("language").(string) == baseLogic.EN_US { + return []responseTypes.AuditLogsType{ + { + Operation: AuditLogsType.AuditLogsPutaway, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsPutaway], + }, + { + Operation: AuditLogsType.AuditLogsUnPutaway, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsUnPutaway], + }, + { + Operation: AuditLogsType.AuditLogsStartInstances, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsStartInstances], + }, + { + Operation: AuditLogsType.AuditLogsStopInstances, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsStopInstances], + }, + { + Operation: AuditLogsType.AuditLogsRestartInstances, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsRestartInstances], + }, + { + Operation: AuditLogsType.AuditLogsResetInstanceStatus, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsResetInstanceStatus], + }, + { + Operation: AuditLogsType.AuditLogsRemoveDevice, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsRemoveDevice], + }, + { + Operation: AuditLogsType.AuditLogsInstanceResetPassword, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsInstanceResetPassword], + }, + { + Operation: AuditLogsType.AuditLogsReinstallInstance, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsReinstallInstance], + }, + { + Operation: AuditLogsType.AuditLogsDeleteDevice, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsDeleteDevice], + }, + { + Operation: AuditLogsType.AuditLogsEditInstanceName, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsEditInstanceName], + }, + { + Operation: AuditLogsType.AuditLogsCollectHardwareInfo, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsCollectHardwareInfo], + }, + { + Operation: AuditLogsType.AuditLogsTypeCreateInstances, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsTypeCreateInstances], + }, + { + Operation: AuditLogsType.AuditLogsDeleteInstance, + Name: auditLogsTypeEnMap[AuditLogsType.AuditLogsDeleteInstance], + }, + } + } else { + + return []responseTypes.AuditLogsType{ + { + Operation: AuditLogsType.AuditLogsPutaway, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsPutaway], + }, + { + Operation: AuditLogsType.AuditLogsUnPutaway, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsUnPutaway], + }, + { + Operation: AuditLogsType.AuditLogsStartInstances, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsStartInstances], + }, + { + Operation: AuditLogsType.AuditLogsStopInstances, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsStopInstances], + }, + { + Operation: AuditLogsType.AuditLogsRestartInstances, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsRestartInstances], + }, + { + Operation: AuditLogsType.AuditLogsResetInstanceStatus, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsResetInstanceStatus], + }, + { + Operation: AuditLogsType.AuditLogsRemoveDevice, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsRemoveDevice], + }, + { + Operation: AuditLogsType.AuditLogsInstanceResetPassword, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsInstanceResetPassword], + }, + { + Operation: AuditLogsType.AuditLogsReinstallInstance, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsReinstallInstance], + }, + { + Operation: AuditLogsType.AuditLogsDeleteDevice, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsDeleteDevice], + }, + { + Operation: AuditLogsType.AuditLogsEditInstanceName, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsEditInstanceName], + }, + { + Operation: AuditLogsType.AuditLogsCollectHardwareInfo, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsCollectHardwareInfo], + }, + { + Operation: AuditLogsType.AuditLogsTypeCreateInstances, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsTypeCreateInstances], + }, + { + Operation: AuditLogsType.AuditLogsDeleteInstance, + Name: auditLogsTypeZhMap[AuditLogsType.AuditLogsDeleteInstance], + }, + } + } +} diff --git a/bmp-openapi/logic/baseLogic/baseLogic.go b/bmp-openapi/logic/baseLogic/baseLogic.go new file mode 100644 index 0000000..9cd1e85 --- /dev/null +++ b/bmp-openapi/logic/baseLogic/baseLogic.go @@ -0,0 +1,324 @@ +package baseLogic + +var ( + PartitionType = map[string]string{ + "/": "root", + "swap": "system", + } + PartitionLabel = map[string]string{ + "/": "l_root", + "swap": "l_swap", + } + SystemDiskLabel = map[string]string{ + "/": "gpt", + "swap": "gpt", + } + DataDiskLabel = map[string]string{ + "/": "gpt", + "swap": "gpt", + } + DeviceManageStatus = map[string]string{ + IN: "已入库", + PUTAWAY: "已上架", + UNPUTAWAY: "已下架", + CREATED: "已创建", + PUTAWAYING: "上架中", + PUTAWAYFAIL: "上架失败", + UNPUTAWAYING: "下架中", + REMOVED: "已移除", + } + DeviceManageStatusEn = map[string]string{ + IN: "Stocked", + PUTAWAY: "Mounted", + UNPUTAWAY: "Unmounted", + CREATED: "created", + PUTAWAYING: "Mounting", + PUTAWAYFAIL: "Mount failed", + UNPUTAWAYING: "Unmounting", + REMOVED: "removed", + } + DeviceReason = map[string]string{ + DEFAULT_BMP_ERROR_CODE: "未知错误", + PING_ILOIP_ERROR: "ping带外不通", + USERNAME_OR_PASSWORD_ERROR: "带外用户名或密码错误", + USER_PRIVILEGE_ERROR: "用户权限错误", + PING_SUBNET_GATEWAY_ERROR: "ping子网网关错误", + MAC1_ERROR: "mac1地址有误", + MAC2_ERROR: "mac2地址有误", + } + DeviceReasonEn = map[string]string{ + DEFAULT_BMP_ERROR_CODE: "unknown error message", + PING_ILOIP_ERROR: "ping OOB fails", + USERNAME_OR_PASSWORD_ERROR: "OOB Username does not exist or password is wrong", + USER_PRIVILEGE_ERROR: "User permission error", + PING_SUBNET_GATEWAY_ERROR: "ping subnet gateway error", + MAC1_ERROR: "mac1 address is wrong", + MAC2_ERROR: "mac2 address is wrong", + } + InstanceReason = map[string]string{ + DEFAULT_BMP_ERROR_CODE: "未知错误", + MakeRaidError: "raid失败", + MakePartitionsError: "分区失败", + WriteImageTarError: "写入镜像失败", + SetPasswordError: "设置密码失败", + SetCloudinitConfError: "cloudinit初始化失败", + + SetNocloudUserDataError: "设置用户自定义指令失败", + SetNocloudMetaDataError: "设置metadata失败", + SetNocloudNetworkError: "设置网络失败", + PingError: "PXE启动失败", + + DHCPConfigAddHostError: "设置DHCP配置失败", + DHCPConfigDelHostError: "删除DHCP配置失败", + SetDISKBootError: "设置硬盘启动失败", + PowerCycleError: "重启失败", + PowerOffError: "关机失败", + PowerOnError: "开机失败", + SetPXEBootError: "设置PXE启动失败", + + InitRootDeviceError: "初始化设备信息失败", + //windows专用指令 + WriteImageError: "写入镜像失败", + SetMetaDataError: "设置metadata失败", + SetNetworkDataError: "设置网络失败", + } + InstanceReasonEn = map[string]string{ + DEFAULT_BMP_ERROR_CODE: "unknown error message", + MakeRaidError: "raid failed", + MakePartitionsError: "Partition failed", + WriteImageTarError: "Failed to import image", + SetPasswordError: "Failed to set password", + SetCloudinitConfError: "cloudinit initialization failed", + + SetNocloudUserDataError: "Failed to set user-defined directive", + SetNocloudMetaDataError: "Failed to set metadata", + SetNocloudNetworkError: "Network setup failed", + PingError: "PXE start failed", + + DHCPConfigAddHostError: "Add dhcp failed", + DHCPConfigDelHostError: "Del dhcp failed", + SetDISKBootError: "Set disk boot failed", + PowerCycleError: "PowerCycle failed", + PowerOffError: "PowerOff failed", + PowerOnError: "PowerOn failed", + SetPXEBootError: "SetPXEBoot failed", + + InitRootDeviceError: "InitRootDevice failed", + //windows专用指令 + WriteImageError: "Failed to import image", + SetMetaDataError: "Failed to set metadata", + SetNetworkDataError: "Network setup failed", + } + InstanceLock = map[string]string{ + LOCKED: "锁定", + UNLOCKED: "解锁", + } + InstanceLockEn = map[string]string{ + LOCKED: "Locked", + UNLOCKED: "Unlocked", + } + InstanceStatus = map[string]string{ + CREATING: "创建中", + STARTING: "开机中", + RUNNING: "运行", + STOPPING: "关机中", + STOPPED: "已关机", + RESTARTING: "重启中", + RESETTING_PASSWORD: "重置密码中", + DESTROYING: "删除中", + DESTROYED: "已删除", + ERROR: "错误", + // 创建失败 + CREATE_ERROR: "创建失败", + // 开机失败 + START_ERROR: "开机失败", + // 关机失败 + STOP_ERROR: "关机失败", + // 重启失败 + RESTART_ERROR: "重启失败", + //重装失败 + REINSTALL_ERROR: "重装失败", + //重置密码失败 + RESETPASSWD_ERROR: "重置密码失败", + // 销毁失败 + DESTROY_ERROR: "删除失败", + UPGRADING: "调整配置中", + REINSTALLING: "重装系统中", + } + InstanceStatusEn = map[string]string{ + CREATING: "Creating", + STARTING: "Starting up", + RUNNING: "running", + STOPPING: "Shutting Down", + STOPPED: "Shut Down", + RESTARTING: "Rebooting", + RESETTING_PASSWORD: "Resetting password", + DESTROYING: "Destroying", + DESTROYED: "destroyed", + ERROR: "Error", + // 创建失败 + CREATE_ERROR: "Creation failed", + // 开机失败 + START_ERROR: "Startup failed", + // 关机失败 + STOP_ERROR: "Shutdown failed", + // 重启失败 + RESTART_ERROR: "Reboot failed", + //重装失败 + REINSTALL_ERROR: "Reinstall failed", + //重置密码失败 + RESETPASSWD_ERROR: "Resetpasswd failed", + // 销毁失败 + DESTROY_ERROR: "Delete failed", + UPGRADING: "Upgrading", + REINSTALLING: "Reinstalling System", + } + DeviceTypeSeries = map[string]string{ + COMPUTER: "计算型", + STORAGE: "存储型", + GPU: "GPU", + OTHER: "其它", + } + DeviceTypeSeriesEn = map[string]string{ + COMPUTER: "Computer Class", + STORAGE: "Storage Class", + GPU: "GPU", + OTHER: "Other Classes", + } + Source = map[string]string{ + COMMON: "预置镜像", + USER_DEFINED: "自定义镜像", + } + SourceEn = map[string]string{ + COMMON: "Preset image", + USER_DEFINED: "Custom image", + } + VolumeType = map[string]string{ + VOLUME_TYPE_SYSTEM: "系统卷", + VOLUME_TYPE_DATA: "数据卷", + } + VolumeTypeEn = map[string]string{ + VOLUME_TYPE_SYSTEM: "system", + VOLUME_TYPE_DATA: "data", + } + RaidCan = map[string]string{ + RAID_CAN_NO_RAID: "NO RAID", + RAID_CAN_RAID: "RAID", + RAID_CAN_SINGLE_RAID: "单盘RIAD0", + } + RaidCanEn = map[string]string{ + RAID_CAN_NO_RAID: "NO RAID", + RAID_CAN_RAID: "RAID", + RAID_CAN_SINGLE_RAID_EN: RAID_CAN_SINGLE_RAID_EN, + } +) + +const ( + IS_DEL = 1 + IS_NOT_DEL = 0 + DATE_FORMAT = "2006-01-02 15:04:05" + DATE_UTC_FORMAT = "2006-01-02T15:04:05Z" + IS_ALL = "1" + IS_NOT_ALL = "" + + EN_US = "en_US" + ZH_CN = "zh_CN" + + IN = "in" //已入库 + PUTAWAY = "putaway" //已上架 + CREATED = "created" //已创建 + PUTAWAYING = "putawaying" //上架中 + PUTAWAYFAIL = "putawayfail" //上架失败 + UNPUTAWAY = "unputaway" //下架 + UNPUTAWAYING = "unputawaying" //下架中,将“已上架”的设备执行“下架”操作的中间过程状态 + REMOVED = "removed" //已移除 + + DEFAULT_BMP_ERROR_CODE = "ERROR" + USERNAME_OR_PASSWORD_ERROR = "USERNAME_OR_PASSWORD_ERROR" + USER_PRIVILEGE_ERROR = "USER_PRIVILEGE_ERROR" + PING_ILOIP_ERROR = "PING_ILOIP_ERROR" + PING_SUBNET_GATEWAY_ERROR = "PING_SUBNET_GATEWAY_ERROR" + MAC1_ERROR = "MAC1_ERROR" + MAC2_ERROR = "MAC2_ERROR" + + //instance error + DHCPConfigAddHostError = "DHCPConfigAddHostError" + DHCPConfigDelHostError = "DHCPConfigDelHostError" + SetDISKBootError = "SetDISKBootError" + PowerCycleError = "PowerCycleError" + PowerOffError = "PowerOffError" + PowerOnError = "PowerOnError" + SetPXEBootError = "SetPXEBootError" + + InitRootDeviceError = "InitRootDeviceError" + //windows专用指令 + WriteImageError = "WriteImageError" + SetMetaDataError = "SetMetaDataError" + SetNetworkDataError = "SetNetworkDataError" + + PingError = "PingError" + MakeRaidError = "MakeRaidError" + + MakePartitionsError = "MakePartitionsError" + WriteImageTarError = "WriteImageTarError" + SetPasswordError = "SetPasswordError" + SetCloudinitConfError = "SetCloudinitConfError" + + SetNocloudUserDataError = "SetNocloudUserDataError" + SetNocloudMetaDataError = "SetNocloudMetaDataError" + SetNocloudNetworkError = "SetNocloudNetworkError" + + LOCKED = "locked" + UNLOCKED = "unlocked" + DEFAULTPROJECTNAME = "默认项目" + DEFAULTPROJECTNAME_EN = "default project" + //实例状态相关 + CREATING = "creating" + STARTING = "starting" + RUNNING = "running" + STOPPING = "stopping" + STOPPED = "stopped" + RESTARTING = "restarting" + RESETTING_PASSWORD = "resetting_password" + DESTROYING = "destroying" + DESTROYED = "destroyed" + ERROR = "error" + // 创建失败 + CREATE_ERROR = "Creation failed" + // 开机失败 + START_ERROR = "Startup failed" + // 关机失败 + STOP_ERROR = "Shutdown failed" + // 重启失败 + RESTART_ERROR = "Reboot failed" + // 重装失败 + REINSTALL_ERROR = "Reinstall failed" + //重置密码失败 + RESETPASSWD_ERROR = "Resetpasswd failed" + // 销毁失败 + DESTROY_ERROR = "Delete failed" + UPGRADING = "upgrading" + REINSTALLING = "reinstalling" + //机型相关 + COMPUTER = "computer" + STORAGE = "storage" + GPU = "gpu" + OTHER = "other" + + COMMON = "common" //内置镜像 + USER_DEFINED = "user_defined" //自定义 + + ROLE_ADMIN_UUID = "role-admin-uuid-01" //平台拥有着 + ROLE_OPERATOR_UUID = "role-operator-uuid-01" //运营平台 + ROLE_USER_UUID = "role-user-uuid-01" //控制台 + + VOLUME_TYPE_SYSTEM = "system" //卷类型 + VOLUME_TYPE_DATA = "data" + + RAID_CAN_NO_RAID = "NO RAID" + RAID_CAN_RAID = "RAID" + RAID_CAN_SINGLE_RAID = "单盘RAID0" + RAID_CAN_SINGLE_RAID_EN = "RAID0-stripping" + + NOT_LIMITED = "notLimited" +) diff --git a/bmp-openapi/logic/commandLogic/commandLogic.go b/bmp-openapi/logic/commandLogic/commandLogic.go new file mode 100644 index 0000000..93f3b05 --- /dev/null +++ b/bmp-openapi/logic/commandLogic/commandLogic.go @@ -0,0 +1,175 @@ +package commandLogic + +import ( + "fmt" + "strings" + "time" + + commandDao "coding.jd.com/aidc-bmp/bmp-openapi/dao/commandDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-openapi/service/rabbit_mq" + "coding.jd.com/aidc-bmp/bmp-openapi/service/redis" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + constants "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + commandStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandStatus" + rabbitEvent "git.jd.com/cps-golang/ironic-common/ironic/event" + rabbitIronicMsgCommand "git.jd.com/cps-golang/ironic-common/ironic/event/command" + "github.com/jinzhu/gorm" +) + +func CommandEntity2Command(c *commandDao.Command) *responseTypes.Command { + return &responseTypes.Command{ + Id: int64(c.ID), + RequestId: c.RequestID, + Sn: c.Sn, + InstanceId: c.InstanceID, + Action: c.Action, + Type: c.Type, + Status: c.Status, + ParentCommandId: c.ParentCommandID, + ExecuteCount: c.ExecuteCount, + //CreateTime: c.CreateTime, + //UpdateTime: c.UpdateTime, + } +} + +func Query(logger *log.Logger, query *requestTypes.QueryCommandsRequest, p util.Pageable) ([]*responseTypes.Command, int64, error) { + offset, limit := p.Pageable2offset() + param := map[string]interface{}{ + "is_del": "0", + } + if query.RequestId != "" { + param["request_id"] = query.RequestId + } + if query.InstanceId != "" { + param["instance_id"] = query.InstanceId + } + if query.Sn != "" { + param["sn"] = query.Sn + } + + count, err := commandDao.GetCommandCount(logger, param) + if err != nil { + logger.Warn("GetCommandCount sql error:", err.Error()) + return nil, 0, err + } + + command_entities, err := commandDao.GetMultiCommand(logger, param, nil, nil, nil, offset, limit) + if err != nil { + logger.Warn("QueryCommands GetMultiCommand sql error:", err.Error()) + return nil, 0, err + } + resCmds := []*responseTypes.Command{} + for _, entity := range command_entities { + command := CommandEntity2Command(entity) + if strings.ToLower(entity.Status) == commandStatus.FINISH || strings.ToLower(entity.Status) == commandStatus.ERROR { + result, err := redis.GetObjectFromRedis(fmt.Sprintf(constants.COMMAND_RESULT, fmt.Sprint(entity.ID))) + if err != nil { + logger.Warnf("QueryCommands GetObjectFromRedis error, id:%d, error:%s", entity.ID, err.Error()) + } else { + command.Result = result + } + } + resCmds = append(resCmds, command) + } + return resCmds, count, nil + +} + +func CancelCommand(logger *log.Logger, sn string) error { + param := map[string]interface{}{ + "is_del": 0, + "sn": sn, + "status.in": []string{commandStatus.RUNNING, commandStatus.WAIT}, + } + + commands, err := commandDao.GetAllCommand(logger, param) + if err != nil { + logger.Warnf("CancelCommand GetMultiCommand sql error, sn:%s, error:%s", sn, err.Error()) + return err + } + + command := commands[0] + if exist := util.InArray(command.Status, []string{commandStatus.RUNNING, commandStatus.WAIT, commandStatus.ERROR}); exist { + command.Status = commandStatus.CANCEL + if err := commandDao.UpdateCommandById(logger, command); err != nil { + logger.Warnf("CancelCommand UpdateCommandById sql error, id:%d, error:%s", command.ID, err.Error()) + return err + } + } + + for command.ParentCommandID != 0 { + command, err = commandDao.GetCommandById(logger, command.ParentCommandID) + if err != nil { + logger.Warnf("CancelCommand GetCommandById sql error, id:%d, error:%s", command.ParentCommandID, err.Error()) + continue + } + + if exist := util.InArray(command.Status, []string{commandStatus.RUNNING, commandStatus.WAIT, commandStatus.ERROR}); exist { + command.Status = commandStatus.CANCEL + if err := commandDao.UpdateCommandById(logger, command); err != nil { + logger.Warnf("CancelCommand UpdateCommandById sql error, id:%d, error:%s", command.ID, err.Error()) + continue + } + } + } + return nil +} + +func RetryCommand(logger *log.Logger, offsetCommandId int64) error { + + logid := logger.GetPoint("logid").(string) + command, err := commandDao.GetCommandById(logger, offsetCommandId) + if err != nil { + logger.Warnf("RetryCommand GetCommandById sql error, id:%d, error:%s", offsetCommandId, err.Error()) + return err + } + command.Status = commandStatus.WAIT + command.TimeoutTime = time.Now() + if err := commandDao.UpdateCommandById(logger, command); err != nil { + logger.Warnf("UpdateCommandById sql error, id:%d, error:%s", command.ID, err.Error()) + return err + } + + var childCmd *commandDao.Command + childCmd, err = commandDao.GetCommandByParentId(logger, command.ID) + if err != nil { + logger.Warnf("retry command GetCommandByParentId error, id:%d, err:%s", command.ID, err.Error()) + } + for err == nil { + logger.Infof("retry command id:%d, childcmd id:%d", command.ID, childCmd.ID) + childCmd.Status = commandStatus.WAIT + childCmd.TimeoutTime = time.Time{} + if err := commandDao.UpdateCommandById(logger, childCmd); err != nil { + logger.Warnf("RetryCommand UpdateCommandById sql error, id:%d, error:%s", childCmd.ID, err.Error()) + return err + } + childCmd, err = commandDao.GetCommandByParentId(logger, childCmd.ID) + } + if !gorm.IsRecordNotFoundError(err) { + return err + } + + msg := rabbitIronicMsgCommand.CallbackCommandMessage{ + CommandMessage: rabbitIronicMsgCommand.CommandMessage{ + Sn: command.Sn, + Action: "Start", + }, + Status: "OK", + } + event, err := rabbitEvent.NewEvent(msg, logid, "") + if err != nil { + logger.Warnf("RetryCommand convert event msg error, sn:%s, error:%s", command.Sn, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warnf("RetryCommand SendToScheduler error, msg:%s, error:%s", util.ObjToJson(msg), err.Error()) + return err + } + + logger.Infof("RetryCommand SendToScheduler success, msg: %s", util.ObjToJson(msg)) + + return nil +} diff --git a/bmp-openapi/logic/deviceLogic/deviceLogic.go b/bmp-openapi/logic/deviceLogic/deviceLogic.go new file mode 100644 index 0000000..dffc19e --- /dev/null +++ b/bmp-openapi/logic/deviceLogic/deviceLogic.go @@ -0,0 +1,2278 @@ +package deviceLogic + +import ( + "fmt" + "math" + "mime/multipart" + "net" + "regexp" + "strconv" + "strings" + "sync" + "time" + + beego "github.com/beego/beego/v2/server/web" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/CpsLogContentCollectionDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/CpsLogItemsDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceHintsDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/diskDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/imageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rDeviceVolumeDisksDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rVolumeRaidDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/raidDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/volumeDao" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceTypeDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/auditLogLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + // "coding.jd.com/aidc-bmp/bmp-openapi/logic/licenseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/raidLogic" + namespacePrefix "git.jd.com/cps-golang/ironic-common/ironic/common/NamespacePrefixs" + + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/jdBondInterfaceDao" + + deviceDao "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/interfaceDao" + idcApi "coding.jd.com/aidc-bmp/bmp-openapi/service/idc_api" + rabbitMq "coding.jd.com/aidc-bmp/bmp-openapi/service/rabbit_mq" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + "git.jd.com/cps-golang/ironic-common/ironic/enums/AuditLogsType" + instanceStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/InstanceStatus" + "git.jd.com/cps-golang/ironic-common/ironic/enums/SaleStatus" + saleStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/SaleStatus" + rabbitEvent "git.jd.com/cps-golang/ironic-common/ironic/event" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + "github.com/tealeg/xlsx" +) + +type CreateDeviceMq struct { + Action string `json:"action"` + Sn string `json:"sn"` + Subnet string `json:"subnet"` + SubnetMask string `json:"subnet_mask"` + Routes string `json:"routes"` +} + +// 检测设备状态,给driver发消息 ,验证带外等信息是否正确 +type CheckDeviceMq struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` + Privilege string `json:"privilege"` +} + +var wg sync.WaitGroup + +func buildDeviceEntity(logger *log.Logger, idcId string, c *requestTypes.CreateDeviceSpec) *deviceDao.Device { + ipv6, _ := beego.AppConfig.String("gateway6") + return &deviceDao.Device{ + DeviceID: commonUtil.GetRandString("d-", namespacePrefix.IMAGE_ID_LENGTH, false, true, true), + InstanceID: "", + IDcID: idcId, + // DeviceTypeID: deviceType.DeviceTypeID, + ManageStatus: baseLogic.IN, //导入设备以后,默认已入库 + + // Brand: c.Brand, + // Model: c.Model, + // DeviceSeries: deviceType.DeviceSeries, + Cabinet: c.Cabinet, + UPosition: c.UPosition, + Sn: c.Sn, + IloUser: c.IloUser, + IloPassword: c.IloPassword, + IloIP: c.IloIP, + Description: c.Description, + + Mac1: c.Mac1, + // Mac2: c.Mac2, + // SwitchIP1: c.SwitchIP1, + // SwitchPort1: c.SwitchPort1, + // SwitchIP2: c.SwitchIP2, + // SwitchPort2: c.SwitchPort2, + + // SwitchUser1: c.SwitchUser1, + // SwitchPassword1: c.SwitchPassword1, + // SwitchUser2: c.SwitchUser2, + // SwitchPassword2: c.SwitchPassword2, + // SwitchIP: c.SwitchIP, + + Mask: c.Mask, + // MaskEth1: c.MaskEth1, + Gateway: c.Gateway, + PrivateIPv4: c.PrivateIPv4, + // PrivateEth1IPv4: c.PrivateEth1IPv4, + PrivateIPv6: c.PrivateIPv6, + // PrivateEth1IPv6: c.PrivateEth1IPv6, + Gateway6: ipv6, + // AdapterID: *c.AdapterID, + + // RaidDriver: c.RaidDriver, + CreatedBy: logger.GetPoint("username").(string), + UpdatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + } +} + +func DeviceEntity2Device(logger *log.Logger, d *deviceDao.Device, idcMap map[string]idcDao.Idc, deviceTypeMap map[string]deviceTypeDao.DeviceType, deviceTypeMapInfo map[string]map[string]string, instanceMap map[string]instanceDao.Instance, imageMap map[string]imageDao.Image) *responseTypes.Device { + + tz := logger.GetPoint("timezone").(string) + //idc, err := idcDao.GetIdcById(logger, d.IDcID) //获取机房信息 + //if err != nil { + // idc = &idcDao.Idc{} + //} + idc := idcMap[d.IDcID] + //entity, err := deviceTypeDao.GetOneDeviceType(logger, map[string]interface{}{"device_type_id": d.DeviceTypeID}) + //if err != nil { + // entity = &deviceTypeDao.DeviceType{} + //} + entity := deviceTypeMap[d.DeviceTypeID] + //instance, err := instanceDao.GetInstanceById(logger, d.InstanceID) + //if instance == nil { + // instance = &instanceDao.Instance{} + //} + instance := instanceMap[d.InstanceID] + //image, err := imageDao.GetImageByUuid(logger, instance.ImageID) + //if image == nil { + // image = &imageDao.Image{} + //} + image := imageMap[instance.ImageID] + //user, _ := userDao.GetUserById(logger, instance.UserID) + //if user == nil { + // user = &userDao.User{} + //} + language := logger.GetPoint("language").(string) + reason := baseLogic.DeviceReason[d.Reason] + if language == baseLogic.EN_US { + reason = baseLogic.DeviceReasonEn[d.Reason] + } + instanceStatusName := baseLogic.InstanceStatus[instance.Status] + if language == baseLogic.EN_US { + instanceStatusName = baseLogic.InstanceStatusEn[instance.Status] + } + instanceReason := baseLogic.InstanceReason[instance.Reason] + if language == baseLogic.EN_US { + instanceReason = baseLogic.InstanceReasonEn[instance.Reason] + } + deviceManageStatusName := baseLogic.DeviceManageStatus[d.ManageStatus] + if language == baseLogic.EN_US { + deviceManageStatusName = baseLogic.DeviceManageStatusEn[d.ManageStatus] + } + deviceSeriesName := baseLogic.DeviceTypeSeries[d.DeviceSeries] + if language == baseLogic.EN_US { + deviceSeriesName = baseLogic.DeviceTypeSeriesEn[d.DeviceSeries] + } + idcName := idc.Name + if language == baseLogic.EN_US { + idcName = idc.NameEn + } + var ( + iloUser string + iloPassword string + switchUser1 string + switchUser2 string + switchPassword1 string + switchPassword2 string + encloure1 string + slot1 int + encloure2 string + slot2 int + ) + // disk, _ := diskDao.GetAllDisk(logger, map[string]interface{}{"device_id": d.DeviceID}) + // if len(disk) == 1 { + // encloure1 = disk[0].Enclosure + // slot1 = disk[0].Slot + // } else if len(disk) == 2 { + // encloure1 = disk[0].Enclosure + // slot1 = disk[0].Slot + // encloure2 = disk[1].Enclosure + // slot2 = disk[1].Slot + // } + + if d.IloUser == "" { + iloUser = idc.IloUser + } else { + iloUser = d.IloUser + } + if d.IloPassword == "" { + iloPassword = idc.IloPassword + } else { + iloPassword = d.IloPassword + } + if d.SwitchUser1 == "" { + switchUser1 = idc.SwitchUser1 + } else { + switchUser1 = d.SwitchUser1 + } + if d.SwitchPassword1 == "" { + switchPassword1 = idc.SwitchPassword1 + } else { + switchPassword1 = d.SwitchPassword1 + } + if d.SwitchUser2 == "" { + switchUser2 = idc.SwitchUser2 + } else { + switchUser2 = d.SwitchUser2 + } + if d.SwitchPassword2 == "" { + switchPassword2 = idc.SwitchPassword2 + } else { + switchPassword2 = d.SwitchPassword2 + } + collectStatus := "2" + if d.CollectStatus != "" { + collectStatus = d.CollectStatus + } + return &responseTypes.Device{ + ID: d.ID, + DeviceID: d.DeviceID, + IdcID: d.IDcID, + InstanceID: d.InstanceID, + InstanceName: instance.InstanceName, + InstanceStatus: instance.Status, + InstanceStatusName: instanceStatusName, + InstanceReason: instanceReason, + Locked: instance.Locked, + //InstanceOwer: user.UserName, + UserId: d.UserId, + UserName: d.UserName, + InstanceCreatedTime: util.TimestampToString(int64(instance.CreatedTime), tz), + InstanceDescription: instance.Description, + + DeviceTypeID: d.DeviceTypeID, + ManageStatus: d.ManageStatus, + ManageStatusName: deviceManageStatusName, + + ImageName: image.ImageName, + + Brand: d.Brand, + Model: d.Model, + Reason: reason, + Cabinet: d.Cabinet, + UPosition: d.UPosition, + Sn: d.Sn, + Description: d.Description, + + Mac1: d.Mac1, + Mac2: d.Mac2, + SwitchIP1: d.SwitchIP1, + SwitchPort1: d.SwitchPort1, + SwitchIP2: d.SwitchIP2, + SwitchPort2: d.SwitchPort2, + //如果设备不存在,从idc中获取 + IloUser: iloUser, + IloPassword: iloPassword, + IloIP: d.IloIP, //必填 + SwitchUser1: switchUser1, + SwitchPassword1: switchPassword1, + SwitchUser2: switchUser2, + SwitchPassword2: switchPassword2, + SwitchIP: d.SwitchIP, + + Mask: d.Mask, + Gateway: d.Gateway, + PrivateIPv4: d.PrivateIPv4, + PrivateEth1IPv4: d.PrivateEth1IPv4, + PrivateIPv6: d.PrivateIPv6, + PrivateEth1IPv6: d.PrivateEth1IPv6, + AdapterID: d.AdapterID, + + Enclosure1: encloure1, + Slot1: slot1, + Enclosure2: encloure2, + Slot2: slot2, + RaidDriver: d.RaidDriver, + CreatedBy: d.CreatedBy, + UpdatedBy: d.UpdatedBy, + CreatedTime: util.TimestampToString(int64(d.CreatedTime), tz), + UpdatedTime: util.TimestampToString(int64(d.UpdatedTime), tz), + + //以下字段从其他表中获取 + //idc + IdcName: idcName, + IDcNameEn: idc.NameEn, + //deviceType + + DeviceType: entity.DeviceType, + DeviceSeries: d.DeviceSeries, + DeviceSeriesName: deviceSeriesName, + + DeviceTypeName: entity.Name, + Architecture: entity.Architecture, + CPUAmount: entity.CPUAmount, + CPUCores: entity.CPUCores, + CPUFrequency: entity.CPUFrequency, + CPUManufacturer: entity.CPUManufacturer, + CPUModel: entity.CPUModel, + + MemType: entity.MemType, + MemAmount: entity.MemAmount, + MemSize: entity.MemSize, + MemFrequency: entity.MemFrequency, + NicAmount: entity.NicAmount, + NicRate: entity.NicRate, + InterfaceMode: entity.InterfaceMode, + SystemVolumeType: entity.SystemVolumeType, + SystemVolumeInterfaceType: entity.DataVolumeInterfaceType, + SystemVolumeAmount: entity.SystemVolumeAmount, + SystemVolumeSize: entity.SystemVolumeSize, + DataVolumeType: entity.DataVolumeType, + DataVolumeInterfaceType: entity.SystemVolumeInterfaceType, + DataVolumeAmount: entity.DataVolumeAmount, + DataVolumeSize: entity.DataVolumeSize, + GpuAmount: entity.GpuAmount, + GpuManufacturer: entity.GpuManufacturer, + GpuModel: entity.GpuModel, + + //拼装信息 + CpuInfo: deviceTypeMapInfo[entity.DeviceTypeID]["cpu_"], + MemInfo: deviceTypeMapInfo[entity.DeviceTypeID]["mem_"], + SvInfo: deviceTypeMapInfo[entity.DeviceTypeID]["sv_"], + DvInfo: deviceTypeMapInfo[entity.DeviceTypeID]["dv_"], + GpuInfo: deviceTypeMapInfo[entity.DeviceTypeID]["gpu_"], + NicInfo: deviceTypeMapInfo[entity.DeviceTypeID]["nic_"], + + CollectStatus: collectStatus, + CollectFailReason: d.CollectFailReason, + IsNeedRaid: entity.IsNeedRaid, + } +} +func GetDeviceTypeInfo(logger *log.Logger, v *deviceTypeDao.DeviceType) map[string]string { + language := logger.GetPoint("language").(string) + + cpu_ := v.CPUManufacturer + " " + v.CPUModel + "(" + strconv.Itoa(int(v.CPUAmount)) + "*" + strconv.Itoa(int(v.CPUCores)) + "物理核," + v.CPUFrequency + "GHz)" + if language == baseLogic.EN_US { + cpu_ = v.CPUManufacturer + " " + v.CPUModel + "(" + strconv.Itoa(int(v.CPUAmount)) + "*" + strconv.Itoa(int(v.CPUCores)) + "cores," + v.CPUFrequency + "GHz)" + } + mem_ := strconv.Itoa(int(v.MemAmount)*int(v.MemSize)) + "GB(" + strconv.Itoa(int(v.MemSize)) + "GB*" + strconv.Itoa(int(v.MemAmount)) + ")" + v.MemType + " " + strconv.Itoa(int(v.MemFrequency)) + "MHz" + // 系统盘:显示总容量 (单块容量 接口类型 类型*数量 RAID 模式) + // 240GB 240GB SATA SSD*2 RAID1 + //sv_ := strconv.Itoa(int(v.SystemVolumeAmount)*int(v.SystemVolumeSize)) + "GB(" + strconv.Itoa(int(v.SystemVolumeSize)) + "GB " + v.SystemVolumeInterfaceType + " " + v.SystemVolumeType + "*" + strconv.Itoa(int(v.SystemVolumeAmount)) + ")" + //if v.SystemVolumeUnit == "TB" { + // sv_ = Trim(strconv.FormatFloat(float64(v.SystemVolumeAmount)*float64(v.SystemVolumeSize)/1000, 'f', 2, 64)) + "TB(" + Trim(strconv.FormatFloat(float64(v.SystemVolumeSize)/1000, 'f', 2, 64)) + "TB " + v.SystemVolumeInterfaceType + " " + v.SystemVolumeType + "*" + strconv.Itoa(int(v.SystemVolumeAmount)) + ")" + //} + //// 数据盘:显示总容量 (单块容量 接口类型 类型*数量 RAID 模式) + //dv_ := strconv.Itoa(int(v.DataVolumeAmount)*int(v.DataVolumeSize)) + "GB(" + strconv.Itoa(int(v.DataVolumeSize)) + "GB " + v.DataVolumeInterfaceType + " " + v.DataVolumeType + "*" + strconv.Itoa(int(v.DataVolumeAmount)) + ")" + //if v.DataVolumeUnit == "TB" { + // dv_ = Trim(strconv.FormatFloat(float64(v.DataVolumeAmount)*float64(v.DataVolumeSize)/1000, 'f', 2, 64)) + "TB(" + Trim(strconv.FormatFloat(float64(v.DataVolumeSize)/1000, 'f', 2, 64)) + "TB " + v.DataVolumeInterfaceType + " " + v.DataVolumeType + "*" + strconv.Itoa(int(v.DataVolumeAmount)) + ")" // + "," + deviceTypeRaid + ")" + //} + //if v.DataVolumeAmount == 0 { + // dv_ = "" + //} + //// 显示品牌 显卡型号 个数,例 NVIDIA P40 * 4 + gpu_ := v.GpuManufacturer + " " + v.GpuModel + "*" + strconv.Itoa(int(v.GpuAmount)) + if v.GpuAmount == 0 { + gpu_ = "" + } + nic_ := strconv.Itoa(int(v.NicAmount)) + "*" + strconv.Itoa(int(v.NicRate)) + "GE" + return map[string]string{ + "cpu_": cpu_, + "mem_": mem_, + //"sv_": sv_, + //"dv_": dv_, + "gpu_": gpu_, + "nic_": nic_, + } +} +func Trim(str string) string { + s := strings.TrimRight(str, "0") + s = strings.TrimRight(s, ".") + return s +} +func QueryDevices(logger *log.Logger, param requestTypes.QueryDevicesRequest, p util.Pageable) ([]*responseTypes.Device, int64, error) { + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "idc_id": param.IDcID, + "is_del": 0, + //如果还需要查询条件,继续在下面添加条件 + } + if param.DeviceSeries != "" { + query["device_series.in"] = strings.Split(param.DeviceSeries, ",") + } + if param.Sn != "" { + query["sn.like"] = "%" + param.Sn + "%" + } + if param.InstanceID != "" { + query["instance_id"] = param.InstanceID + } + var instanceIDs []string + if param.InstanceName != "" { + if _, ok := query["instance_name"]; ok { + q := map[string]interface{}{ + "instance_name": query["instance_name"], + } + instances, err := instanceDao.GetAllInstance(logger, q) + if err != nil { + logger.Warnf("QueryDevices.GetAllInstance by instance name error, instance_nameL:%s, error:%s", query["instance_name"], err.Error()) + } else { + for _, v := range instances { + instanceIDs = append(instanceIDs, v.InstanceID) + } + } + } + } + + //instance_id和instance_name两个参数都存在时,需要都检测 + if param.InstanceID != "" && param.InstanceName != "" { + if util.InArray(param.InstanceID, instanceIDs) { + query["instance_id"] = param.InstanceID + } else { //两个参数冲突,不给任何结果 + return nil, 0, fmt.Errorf("检测到instance_id 和 instance_id参数不匹配") + } + } else if param.InstanceID != "" && param.InstanceName == "" { + query["instance_id"] = param.InstanceID + } else if param.InstanceID == "" && param.InstanceName != "" { + query["instance_id.in"] = instanceIDs + } + + if param.DeviceTypeID != "" { + query["device_type_id.in"] = strings.Split(param.DeviceTypeID, ",") + } + if param.ManageStatus != "" { + query["manage_status.in"] = strings.Split(param.ManageStatus, ",") + } + if param.UserID != "" { + query["user_id"] = param.UserID + } + if param.UserName != "" { + query["user_name.like"] = "%" + param.UserName + "%" + } + if param.IloIP != "" { + query["ilo_ip"] = param.IloIP + } + if param.IPV4 != "" { + query["private_ipv4"] = param.IPV4 + } + if param.IPV6 != "" { + query["private_ipv6"] = param.IPV6 + } + + if param.CollectStatus != "" { + query["collect_status"] = param.CollectStatus + } + + count, err := deviceDao.GetDeviceCount(logger, query) + if err != nil { + logger.Warn("GetDeviceCount dao error:", err.Error()) + return nil, 0, err + } + entityList := []*deviceDao.Device{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = deviceDao.GetMultiDevice(logger, query, nil, []string{"created_time"}, []string{"desc"}, 0, 0) + } else { + entityList, err = deviceDao.GetMultiDevice(logger, query, nil, []string{"created_time"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("GetMultiDevice dao error:", err.Error()) + return nil, 0, err + } + var deviceList = []*responseTypes.Device{} + idcALl, _ := idcDao.GetAllIdc(logger, map[string]interface{}{"is_del": baseLogic.IS_NOT_DEL}) + idcMap := map[string]idcDao.Idc{} + for _, v := range idcALl { + idcMap[v.IDcID] = *v + } + deviceTypeALl, _ := deviceTypeDao.GetAllDeviceType(logger, map[string]interface{}{"is_del": baseLogic.IS_NOT_DEL}) + deviceTypeMap := map[string]deviceTypeDao.DeviceType{} + deviceTypeMapInfo := map[string]map[string]string{} + //获取raid的信息 + raidMap := make(map[string]responseTypes.Raid) // 请求一次,避免循环请求 + raidList, raidsErr := raidLogic.QueryRaidsAll(logger) + if raidsErr == nil && len(raidList) != 0 { + for _, vv := range raidList { + raidMap[vv.RaidID] = *vv + } + } + + for _, v := range deviceTypeALl { + //deviceTypeRaid, err := rDeviceTypeRaidDao.GetAllRDeviceTypeRaid(logger, map[string]interface{}{ + // "device_type_id": v.DeviceTypeID, + // "is_del": 0, + //}) + //if err != nil { + // panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + //} + //raid := "" + //if len(deviceTypeRaid) != 0 { + // for _, vv := range deviceTypeRaid { + // raid = raid + vv.RaidID + "," + // } + // raid = strings.Trim(raid, ",") + //} + ////计算raid对应map中的Name + //array := []string{} // 拆分查询 + //deviceTypeRaidName := "" + //if len(raidList) != 0 { + // array = strings.Split(raid, ",") + //} + //if len(array) != 0 { + // raid_ := "" + // for _, str := range array { + // raid_ = raid_ + raidMap[str].Name + "," // RAID0,RAID1 + // } + // deviceTypeRaidName = raid_[0 : len(raid_)-1] + //} + + info := GetDeviceTypeInfo(logger, v) + deviceTypeMap[v.DeviceTypeID] = *v + //fmt.Println(info, util.ObjToJson(info), info["nic_"]) + //拼装数据,给上层api直接使用 + deviceTypeMapInfo[v.DeviceTypeID] = map[string]string{ + "cpu_": info["cpu_"], + "mem_": info["mem_"], + //"sv_": info["sv_"], + //"dv_": info["dv_"], + "gpu_": info["gpu_"], + "nic_": info["nic_"], + } + + } + instanceALl, _ := instanceDao.GetAllInstance(logger, map[string]interface{}{"is_del": baseLogic.IS_NOT_DEL}) + instanceMap := map[string]instanceDao.Instance{} + for _, v := range instanceALl { + instanceMap[v.InstanceID] = *v + } + imageALl, _ := imageDao.GetAllImage(logger, map[string]interface{}{"is_del": baseLogic.IS_NOT_DEL}) + imageMap := map[string]imageDao.Image{} + for _, v := range imageALl { + imageMap[v.ImageID] = *v + } + //userALl, _ := userDao.GetAllUser(logger, map[string]interface{}{"is_del": baseLogic.IS_NOT_DEL}) + //userMap := map[string]userDao.User{} + //for _, v := range userALl { + // userMap[v.UserID] = v + //} + + for _, entity := range entityList { + device := DeviceEntity2Device(logger, entity, idcMap, deviceTypeMap, deviceTypeMapInfo, instanceMap, imageMap) + deviceList = append(deviceList, device) + } + return deviceList, count, err +} + +func Save(logger *log.Logger, params requestTypes.CreateDevicesRequest) ([]string, error) { + + if len(params.Devices) > 10000 { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("单次上传不能超过10000条"), fmt.Sprintf("exceed 10000"))) + } + _, err := idcDao.GetIdcById(logger, params.IDcID) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("机房不存在", "idcId not exist")) + } + + /* + deviceType, err := deviceTypeDao.GetOneDeviceType(logger, map[string]interface{}{"device_type_id": params.DeviceTypeID}) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("机型不存在", "deviceTypeId not exist")) + } + + if deviceType.NicAmount == 2 && deviceType.InterfaceMode != "bond" { + for _, v := range params.Devices { + if v.PrivateEth1IPv4 == "" || v.MaskEth1 == "" { + panic(constant.BuildInvalidArgumentWithArgs("双网口非bond时,privateEth1Ipv4和maskEth1为必填项", "dual model must have privateEth1Ipv4 and maskEth1 params")) + } + } + } + */ + + //fmt.Println(deviceType) + deviceIds := []string{} + list, err := deviceDao.GetAllDevice(logger, map[string]interface{}{ + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Warnf("createDevice.GetAllDevice error:%s", err.Error()) + } + + // var licenseNum int + // license, err := licenseLogic.GetLicenseContent(logger) + // if err != nil { + // logger.Warnf("createDevice.GetLicenseContent error:%s", err.Error()) + // } + // if license == nil || license.NodesNum == 0 { + // logger.Warn("createDevice license empty") + // panic(constant.BuildInvalidArgumentWithArgs("请联系客服授权", "please buy business license")) + // } else { + // licenseNum = license.NodesNum + // } + // if len(list)+len(params.Devices) > licenseNum { + // logger.Warnf("createDevice nodes exceed license_num, licenseNum:%d, actual num:%d", licenseNum, len(list)+len(params.Devices)) + // panic(constant.BuildInvalidArgumentWithArgs("节点数超过授权数,请联系客服", "nodes exceed than license num")) + // } + + listSn := map[string]string{} + listIloIp := map[string]string{} + listIPV6 := map[string]string{} + for _, v := range list { + listSn[v.Sn] = v.Sn + listIloIp[v.IloIP] = v.IloIP + if v.PrivateIPv6 != "" { //不为空才判断 + listIPV6[v.PrivateIPv6] = v.PrivateIPv6 + } + } + sns := []string{} + iloIps := []string{} + ipv6s := []string{} + for _, v := range params.Devices { + if util.InArrayString(v.Sn, sns) { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("文件中sn %s 重复", v.Sn), fmt.Sprintf("file sn %s repeat", v.Sn))) + } + sns = append(sns, v.Sn) + if util.InArrayString(v.IloIP, iloIps) { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("文件中带外IP %s 重复", v.IloIP), fmt.Sprintf("file iloIp %s repeat", v.IloIP))) + } + iloIps = append(iloIps, v.IloIP) + if util.InArrayString(v.PrivateIPv6, ipv6s) { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("文件中IPV6 %s 重复", v.PrivateIPv6), fmt.Sprintf("file IPV6 %s repeat", v.PrivateIPv6))) + } + ipv6s = append(ipv6s, v.PrivateIPv6) + checkDevice(logger, *v, listSn, listIloIp, listIPV6) + } + n := 200 //每个协程处理的数量 + //fmt.Println(57/n, float64(57/n), float64(57)/float64(n), math.Ceil(float64(57)/float64(n)), int(math.Floor(float64(57)/float64(n)))) + count := int(math.Ceil(float64(len(params.Devices)) / float64(n))) //协程数量 + fmt.Println("总数", len(params.Devices), "协程数", count) + for i := 0; i < count; i++ { + end := (i + 1) * n + if end > len(params.Devices) { + end = len(params.Devices) + } + wg.Add(1) + go saveDevices(logger, params.IDcID, params.Devices[i*n:end]) + } + wg.Wait() + return deviceIds, nil +} +func checkDevice(logger *log.Logger, param requestTypes.CreateDeviceSpec, listSn, listIloIp, listIPV6 map[string]string) { + specialMatch := regexp.MustCompile("^.{1,128}$").MatchString //[一-龥_a-zA-Z0-9_-] + if !specialMatch(param.Sn) { + panic(constant.BuildInvalidArgumentWithArgs("Sn 不合法", "Sn invalidate")) + } + if !specialMatch(param.Cabinet) { + panic(constant.BuildInvalidArgumentWithArgs("Cabinet 不合法", "Cabinet invalidate")) + } + if !specialMatch(param.UPosition) { + panic(constant.BuildInvalidArgumentWithArgs("UPosition 不合法", "UPosition invalidate")) + } + // if !specialMatch(param.Brand) { + // panic(constant.BuildInvalidArgumentWithArgs("Brand 不合法", "Brand invalidate")) + // } + // if !specialMatch(param.Model) { + // panic(constant.BuildInvalidArgumentWithArgs("Model 不合法", "Model invalidate")) + // } + if _, err := net.ParseMAC(param.Mac1); err != nil { + panic(constant.BuildInvalidArgumentWithArgs("Mac1 不合法", "Mac1 invalidate")) + } + // if _, err := net.ParseMAC(param.Mac2); err != nil { + // panic(constant.BuildInvalidArgumentWithArgs("Mac2 不合法", "Mac2 invalidate")) + // } + // specialMatch = regexp.MustCompile("^[a-zA-Z/0-9_-]{1,128}$").MatchString + // if !specialMatch(param.SwitchPort1) { + // panic(constant.BuildInvalidArgumentWithArgs("switchport1 不合法", "switchport1 invalidate")) + // } + // specialMatch = regexp.MustCompile("^[a-zA-Z/0-9_-]{1,128}$").MatchString + // if !specialMatch(param.SwitchPort2) { + // panic(constant.BuildInvalidArgumentWithArgs("switchport2 不合法", "switchport2 invalidate")) + // } + if net.ParseIP(param.Mask) == nil { + panic(constant.BuildInvalidArgumentWithArgs("Mask 不合法", "Mask invalidate")) + } + if net.ParseIP(param.Gateway) == nil { + panic(constant.BuildInvalidArgumentWithArgs("Gateway 不合法", "Gateway invalidate")) + } + if net.ParseIP(param.IloIP) == nil { + panic(constant.BuildInvalidArgumentWithArgs("IloIP 不合法", "IloIP invalidate")) + } + if strings.Contains(param.PrivateIPv4, ":") { + panic(constant.BuildInvalidArgumentWithArgs("PrivateIPv4 不合法", "PrivateIPv4 invalidate")) + } + if net.ParseIP(param.PrivateIPv4) == nil { + panic(constant.BuildInvalidArgumentWithArgs("PrivateIPv4 不合法", "PrivateIPv4 invalidate")) + } + if param.PrivateIPv6 != "" { + if strings.Contains(param.PrivateIPv6, "/") { //2403:1EC0:8549:60C0::1/64 + arr := strings.Split(param.PrivateIPv6, "/") + ipv6 := arr[0] + mask := arr[1] + maskCount, err := strconv.Atoi(mask) + fmt.Println(maskCount, err) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("PrivateIPv6 不合法", "PrivateIPv6 invalidate")) + } + if !strings.Contains(ipv6, ":") { + panic(constant.BuildInvalidArgumentWithArgs("PrivateIPv6 不合法", "PrivateIPv6 invalidate")) + } + if net.ParseIP(ipv6) == nil || (maskCount < 0 || maskCount > 128) { + panic(constant.BuildInvalidArgumentWithArgs("PrivateIPv6 不合法", "PrivateIPv6 invalidate")) + } + } else { + ipv6 := param.PrivateIPv6 + if !strings.Contains(ipv6, ":") { + panic(constant.BuildInvalidArgumentWithArgs("PrivateIPv6 不合法", "PrivateIPv6 invalidate")) + } + if net.ParseIP(ipv6) == nil { + panic(constant.BuildInvalidArgumentWithArgs("PrivateIPv6 不合法", "PrivateIPv6 invalidate")) + } + } + } + // if net.ParseIP(param.SwitchIP1) == nil && param.SwitchIP1 != "" { + // panic(constant.BuildInvalidArgumentWithArgs("SwitchIP1 不合法", "SwitchIP1 invalidate")) + // } + // if net.ParseIP(param.SwitchIP2) == nil && param.SwitchIP2 != "" { + // panic(constant.BuildInvalidArgumentWithArgs("SwitchIP1 不合法", "SwitchIP1 invalidate")) + // } + specialMatch = regexp.MustCompile("^.{1,128}$").MatchString + if !specialMatch(param.IloUser) && param.IloUser != "" { + panic(constant.BuildInvalidArgumentWithArgs("IloUser 不合法", "IloUser invalidate")) + } + if !specialMatch(param.IloPassword) && param.IloPassword != "" { + panic(constant.BuildInvalidArgumentWithArgs("IloPassword 不合法", "IloPassword invalidate")) + } + // if !specialMatch(param.SwitchUser1) && param.SwitchUser1 != "" { + // panic(constant.BuildInvalidArgumentWithArgs("SwitchUser1 不合法", "SwitchUser1 invalidate")) + // } + // if !specialMatch(param.SwitchPassword1) && param.SwitchPassword1 != "" { + // panic(constant.BuildInvalidArgumentWithArgs("SwitchPassword1 不合法", "SwitchPassword1 invalidate")) + // } + // if !specialMatch(param.SwitchUser2) && param.SwitchUser2 != "" { + // panic(constant.BuildInvalidArgumentWithArgs("SwitchUser2 不合法", "SwitchUser2 invalidate")) + // } + // if !specialMatch(param.SwitchPassword2) && param.SwitchPassword2 != "" { + // panic(constant.BuildInvalidArgumentWithArgs("SwitchPassword2 不合法", "SwitchPassword2 invalidate")) + // } + //list, _ := deviceDao.GetOneDevice(logger, map[string]interface{}{ + // "sn": param.Sn, + // "is_del": baseLogic.IS_NOT_DEL, + //}) + //if list != nil { + // logger.Warn("sn exist:", param.Sn) + // //snRepeat = fmt.Sprintf("sn %s 已存在", param.Sn) + // //fmt.Println(snRepeat) + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("sn %s 已存在", param.Sn), fmt.Sprintf("sn %s exist", param.Sn))) + //} + //list, _ = deviceDao.GetOneDevice(logger, map[string]interface{}{ + // "ilo_ip": param.IloIP, + // "is_del": baseLogic.IS_NOT_DEL, + //}) + //if list != nil { + // logger.Warn("iloIp exist:", param.IloIP) + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("带外IP %s 已存在", param.IloIP), fmt.Sprintf("iloIp %s exist", param.IloIP))) + //} + _, ok := listSn[param.Sn] + if ok { //如果存在 + logger.Warn("sn exist:", param.Sn) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("sn %s 已存在", param.Sn), fmt.Sprintf("sn %s exist", param.Sn))) + } + _, ok = listIloIp[param.IloIP] + if ok { //如果存在 + logger.Warn("iloIp exist:", param.IloIP) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("带外IP %s 已存在", param.IloIP), fmt.Sprintf("iloIp %s exist", param.IloIP))) + } + if param.PrivateIPv6 != "" { + _, ok = listIPV6[param.PrivateIPv6] + if ok { //如果存在 + logger.Warn("IPV6 exist:", param.PrivateIPv6) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("IPV6 %s 已存在", param.PrivateIPv6), fmt.Sprintf("IPV6 %s exist", param.PrivateIPv6))) + } + } +} +func saveDevices(logger *log.Logger, idcId string, list []*requestTypes.CreateDeviceSpec) ([]string, error) { + sns := []string{} + deviceIds := []string{} + devices := []*deviceDao.Device{} + // disks1 := map[string]*diskDao.Disk{} + // disks2 := map[string]*diskDao.Disk{} + defer wg.Done() + for _, param := range list { + if param == nil { + break + } + //checkDevice(logger, *param) + //fmt.Println("sn", k, param.Sn, param.Sn) + + sns = append(sns, param.Sn) + entity := buildDeviceEntity(logger, idcId, param) + entity.CreatedTime = int(time.Now().Unix()) + entity.UpdatedTime = int(time.Now().Unix()) + entity.ManageStatus = baseLogic.IN //默认已入库 + entity.CollectStatus = "2" //2表示未采集 + devices = append(devices, entity) + + /* + disks1[entity.DeviceID] = &diskDao.Disk{ + DeviceID: entity.DeviceID, + Enclosure: param.Enclosure1, + Slot: *param.Slot1, + DiskType: volumeType.SYSTEM, //默认只有系统盘 + Size: strconv.Itoa(deviceType.SystemVolumeSize), + SizeUnit: deviceType.SystemVolumeUnit, + PdType: deviceType.SystemVolumeInterfaceType, + AdapterID: *param.AdapterID, + CreatedBy: logger.GetPoint("username").(string), + UpdatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + } + + disks2[entity.DeviceID] = &diskDao.Disk{ + DeviceID: entity.DeviceID, + Enclosure: param.Enclosure2, + Slot: param.Slot2, + DiskType: volumeType.SYSTEM, //默认只有系统盘 + Size: strconv.Itoa(deviceType.SystemVolumeSize), + SizeUnit: deviceType.SystemVolumeUnit, + PdType: deviceType.SystemVolumeInterfaceType, + AdapterID: *param.AdapterID, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + */ + deviceIds = append(deviceIds, entity.DeviceID) + } + //countParam := map[string]interface{}{ + // "is_del": 0, + // "sn.in": sns, + //} + //count, err := deviceDao.GetDeviceCount(logger, countParam) + //if err != nil { + // logger.Warn("CreateDevices GetDeviceCount error:", sns, err.Error()) + // return []string{}, err + //} + //if count > 0 { + // panic(constant.BuildInvalidArgumentWithArgs("sn 已存在", "device sn may already exists")) + //} + //20240516 minping 磁盘信息改成在采集时自动插入 + // _, err := deviceDao.CreateDeviceAndDisk(logger, devices, disks1, disks2) + _, err := deviceDao.AddMultiDevice(logger, devices) + if err != nil { + logger.Warn("AddMultiDevice error:", err.Error()) + return []string{}, err + } + //for _, device := range list { + // _, _, err = net.ParseCIDR(device.PrivateIPv4) + // ipv4 := device.PrivateIPv4 + // if err != nil { //如果不是cird地址,先根据掩码转成cird,假如给的地址是这种格式,10.208.14.81 + // mask := net.IPMask(net.ParseIP(device.Mask).To4()) + // prefixSize, _ := mask.Size() + // ipv4 = device.PrivateIPv4 + "/" + strconv.Itoa(prefixSize) + // } + // subnet := util.NetworkIp(ipv4) + // msg := CreateDeviceMq{ + // Action: "DHCPConfigAddSubnet", + // Subnet: subnet, + // Sn: device.Sn, + // SubnetMask: device.Mask, + // Routes: device.Gateway, + // } + // res, err := rdsUtil.RedisUtil.SetNX("set_subenet_"+subnet, true, time.Second*3600).Result() + // fmt.Println("设置子网", res, err, util.ObjToJson(msg)) + // //if res { + // err = sendCreateDeviceEvent(logger, deviceType.IDcID, &msg) //param.UserData, param.AliasIPs, param.ExtensionAliasIps + // if err != nil { + // return []string{}, err + // } + //} + //} + + return deviceIds, err +} + +func btoi(b bool) int { + if b { + return 1 + } + return 0 +} + +func CollectDeviceInfo(logger *log.Logger, collects *requestTypes.CollectDeviceInfoRequest) error { + + logid := logger.GetPoint("logid").(string) + failsns := []string{} + + userId := logger.GetPoint("userId").(string) + + for _, v := range collects.Collects { + + if err := commandDao.DeleteCommandBySn(logger, v.Sn); err != nil { + logger.Warnf("CollectDeviceInfo.DeleteCommandBySn error, sn:%s, error:%s", v.Sn, err.Error()) + } + + message := rabbitIronicMsgApi.CollectHardwareInfoMessage{} + message.ApiMessage.RequestId = logid + message.Sns = []string{v.Sn} + message.AllowOverride = v.AllowOverride + message.NetworkType = "retail" + collectedStatus := "4" //4表示采集失败 + collectFailReason := "mq msg send error" + event, err := rabbitEvent.NewEvent(message, logid, userId) + if err != nil { + logger.Warnf("RetryCommand convert event msg error, sn:%s, error:%s", v.Sn, err.Error()) + failsns = append(failsns, v.Sn) + } else { + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warnf("CollectDeviceInfo SendToScheduler error, msg:%s, error:%s", util.ObjToJson(event), err.Error()) + failsns = append(failsns, v.Sn) + } else { + deviceEntity, err := deviceDao.GetBySn(logger, v.Sn) + if err != nil { + logger.Warnf("CollectDeviceInfo.GetBySn error, sn:%s, error:%s", v.Sn, err.Error()) + } else { + collectedStatus = "3" //3表示采集中 + collectFailReason = "" + deviceEntity.CollectStatus = collectedStatus + deviceEntity.CollectFailReason = collectFailReason + if err := deviceDao.UpdateDeviceAnywhere(logger, deviceEntity); err != nil { + logger.Warnf("CollectDeviceInfo.UpdateDeviceAnywhere error, sn:%s, error:%s", v.Sn, err.Error()) + } + } + } + } + + } + if len(failsns) == 0 { + return nil + } + + return fmt.Errorf("%s collect error!", strings.Join(failsns, ",")) +} + +func ModifyDevice(logger *log.Logger, DeviceID, manageStatus string) error { + if DeviceID == "" { + panic(constant.BuildInvalidArgumentWithArgs("设备ID不能为空", "deviceId invalidate")) + } + device, err := deviceDao.GetOneDevice(logger, map[string]interface{}{ + "device_id": DeviceID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Warn("GetDeviceTypeByUuid sql error:", DeviceID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + //manageStatus := param.ManageStatus + if manageStatus == baseLogic.PUTAWAY { //如果执行上架 + if device.DeviceTypeID == "" { + panic(constant.BuildInvalidArgumentWithArgs("设备必须绑定机型,才可以执行上架操作", "device must bind device_type before putaway")) + } + if device.ManageStatus != baseLogic.IN && device.ManageStatus != baseLogic.PUTAWAYFAIL { + panic(constant.BuildInvalidArgumentWithArgs("设备必须是已入库或者上架失败,才可以执行上架操作", "device manageStatus not support")) + } + manageStatus = baseLogic.PUTAWAYING //上架中 + } + if manageStatus == baseLogic.UNPUTAWAY { //如果执行下架动作 + if device.ManageStatus != baseLogic.PUTAWAY { + panic(constant.BuildInvalidArgumentWithArgs("设备必须是已上架,才可以执行下架操作", "device manageStatus error")) + } + manageStatus = baseLogic.IN //没有下架中,已下架,直接变成已入库 + + auditLogLogic.SaveAuditLogs(logger, DeviceID, "", AuditLogsType.AuditLogsUnPutaway) + } + entity := &deviceDao.Device{ + DeviceID: DeviceID, + ManageStatus: manageStatus, + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if err := deviceDao.UpdateDeviceById(logger, entity); err != nil { + logger.Warnf("ModifyDevice sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) + return err + } + //接下来修改其他信息,比如需不需要发mq之类的 + if manageStatus == baseLogic.PUTAWAYING { //如果变成了上架中 + if err := sendPutawayDeviceEvent(logger, device.Sn); err != nil { + logger.Warnf("sendPutawayDeviceEvent error, sn:%s, err:%s", device.Sn, err.Error()) + } else { + logger.Infof("sendPutawayDeviceEvent success, sn:%s", device.Sn) + } + } + return nil +} + +func sendPutawayDeviceEvent(logger *log.Logger, sn string) error { + + logid := logger.GetPoint("logid").(string) + userId := logger.GetPoint("userId").(string) + msg := rabbitIronicMsgApi.PutawayDeviceMessage{ + ApiMessage: rabbitIronicMsgApi.ApiMessage{ + RequestId: logid, + }, + Sn: sn, + } + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("rabbitEvent.NewEvent convert event msg error:", sn, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warnf("sendPutawayDeviceEvent SendToScheduler error, msg:%s, error:%s", util.ObjToJson(event), err.Error()) + return err + } else { + logger.Infof("sendPutawayDeviceEvent SendToScheduler success, msg:%s", util.ObjToJson(event)) + } + return nil +} + +func ModifyDeviceDescription(logger *log.Logger, param *requestTypes.ModifyDevicesRequest, deviceId string) error { + if deviceId == "" { + panic(constant.BuildInvalidArgumentWithArgs("设备ID不能为空", "deviceId invalidate")) + } + entity, err := deviceDao.GetOneDevice(logger, map[string]interface{}{ + "device_id": deviceId, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil || entity == nil { + logger.Warn("GetDeviceTypeByUuid sql error:", deviceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if param.Description != nil { + entity.Description = *param.Description + } + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + + if err := deviceDao.SaveDevice(logger, entity); err != nil { + logger.Warnf("ModifyDevice sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) + return err + } + return nil +} +func ModifyDeviceByWhere(logger *log.Logger, column string, newData string, deviceTypeId string) error { + _, err := deviceDao.GetOneDevice(logger, map[string]interface{}{ + "device_type_id": deviceTypeId, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Info("机型没有设备,不做device_series的修改", deviceTypeId) + //如果设备表没有对应的机型,直接返回,不做修改 + return nil + } + entity := &deviceDao.Device{ + DeviceTypeID: deviceTypeId, + } + if column == "device_series" { + entity.DeviceSeries = newData + } + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + if err := deviceDao.UpdateDeviceByDeviceTypeId(logger, entity); err != nil { + logger.Warnf("ModifyDevice sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) + return err + } + return nil +} + +func ModifyDeviceByDeviceId(logger *log.Logger, param *requestTypes.ModifyAllDevicesRequest, DeviceID string) error { + _, err := deviceDao.GetOneDevice(logger, map[string]interface{}{ + "device_id": DeviceID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Warn("GetDeviceTypeByUuid sql error:", DeviceID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + entity := &deviceDao.Device{ + DeviceID: DeviceID, + ManageStatus: param.ManageStatus, + InstanceID: param.InstanceID, + UserId: param.UserId, + UserName: param.UserName, + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if err := deviceDao.UpdateDeviceById(logger, entity); err != nil { + logger.Warnf("ModifyDevice sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) + return err + } + //接下来修改其他信息,比如需不需要发mq之类的 + return nil +} + +func Delete(logger *log.Logger, DeviceID string) error { + d, err := deviceDao.GetDeviceById(logger, DeviceID) + if err != nil { + logger.Warn("DeleteDevices GetAllDevice sql error:", DeviceID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + s := []string{SaleStatus.PUTAWAYFAIL, SaleStatus.REMOVED, SaleStatus.IN} + if !util.InArray(d.ManageStatus, s) { + panic(constant.BuildInvalidArgumentWithArgs("设备sn"+d.Sn+"状态为"+d.ManageStatus+",不允许删除", fmt.Sprintf("device %s is %s,not allow delete", d.Sn, d.ManageStatus))) + } + + d.UpdatedBy = logger.GetPoint("username").(string) + d.UpdatedTime = int(time.Now().Unix()) + d.DeletedTime = int(time.Now().Unix()) + d.IsDel = baseLogic.IS_DEL + + err = deviceDao.UpdateDeviceById(logger, d) + if err != nil { + logger.Warn("DeleteDevices UpdateMultiDevices sql error:", err.Error()) + return err + } + + auditLogLogic.DeleteAuditLogsByDeviceId(logger, DeviceID) + + if err := commandDao.DeleteCommandBySn(logger, d.Sn); err != nil { + logger.Warn("DeleteDevices DeleteCommandBySn sql error:", err.Error()) + return err + } + + q := map[string]interface{}{ + "is_del": 0, + "sn": d.Sn, + } + u := map[string]interface{}{ + "is_del": 1, + } + + if err := CpsLogItemsDao.UpdateCpsLogItemss(logger, q, u); err != nil { + logger.Warnf("DeleteDevice.UpdateCpsLogItemss error, sn:%s, error:%s", d.Sn, err.Error()) + } else { + if err := CpsLogContentCollectionDao.UpdateCpsLogContentCollections(logger, q, u); err != nil { + logger.Warnf("DeleteDevice.UpdateCpsLogContentCollections error, sn:%s, error:%s", d.Sn, err.Error()) + } + } + + return nil +} + +func RemoveDevice(logger *log.Logger, DeviceID string) error { + + d, err := deviceDao.GetDeviceById(logger, DeviceID) + if err != nil { + logger.Warn("DeleteDevices GetAllDevice sql error:", DeviceID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if d.ManageStatus != SaleStatus.CREATED { + panic(constant.BuildInvalidArgumentWithArgs("设备状态不是已创建", "device manageStatus is not created")) + } + instance, err := instanceDao.GetInstanceByDeviceId(logger, DeviceID) + if err != nil { + logger.Warn("DeleteDevices GetAllDevice sql error:", DeviceID, err.Error()) + panic(constant.NOT_SUPPORTED) + } + + s := []string{instanceStatus.RUNNING, instanceStatus.STOPPED, instanceStatus.REINSTALL_ERROR, instanceStatus.RESETPASSWD_ERROR} + if !util.InArray(instance.Status, s) { + panic(constant.BuildInvalidArgumentWithArgs("实例状态不是运行或者关机或者可移除的错误状态", "instance status is not running or stopped or supported error status")) + } + + //} + //updates := map[string]interface{}{ + // "is_del": 1, + // "updated_by": logger.GetPoint("username").(string), + // "updated_time": int(time.Now().Unix()), + //} + //err = deviceDao.UpdateMultiDevices(logger, param, updates) + d.InstanceID = "" + d.UserId = "" + d.UserName = "" + d.ManageStatus = SaleStatus.REMOVED + d.UpdatedTime = int(time.Now().Unix()) + d.UpdatedBy = logger.GetPoint("username").(string) + err = deviceDao.SaveDevice(logger, d) + if err != nil { + logger.Warn("removeDevices UpdateMultiDevices sql error:", err.Error()) + return err + } + //err = interfaceDao.UpdateMultiInterfaces(logger, param, updates) + //if err != nil { + // logger.Warn("DeleteDevices UpdateMultiInterfaces sql error:", err.Error()) + // return err + //} + instance.IsDel = baseLogic.IS_DEL + if err := instanceDao.UpdateInstanceById(logger, instance); err != nil { + logger.Warn("removeDevices deleteInstance sql error:", err.Error()) + return err + } + + if err := commandDao.DeleteCommandBySn(logger, d.Sn); err != nil { + logger.Warn("removeDevices DeleteCommandBySn sql error:", err.Error()) + return err + } + + auditLogLogic.SaveAuditLogs(logger, DeviceID, "", AuditLogsType.AuditLogsRemoveDevice) + + return nil +} + +func QueryDeviceStock(logger *log.Logger, region, az, deviceType string) ([]*deviceDao.DeviceStock, error) { + deviceStocks, err := deviceDao.GetDeviceStock(logger, deviceType, region, az) + if err != nil { + logger.Warn("GetDeviceStock GetAllDevice sql error:", deviceType, err.Error()) + return nil, err + } + return deviceStocks, nil +} + +func GetAndCheckById(logger *log.Logger, DeviceID string) (*responseTypes.Device, error) { + device, err := GetById(logger, DeviceID) + if err != nil { + return nil, err + } + return device, nil +} + +func GetFirstVersionUnavailableSns(logger *log.Logger) ([]string, error) { + sns, err := deviceDao.GetFirstVersionDeviceSns(logger) + if err != nil { + logger.Warn("GetFirstVersionUnavailableSns GetFirstVersionDeviceSns sql error:", err.Error()) + return nil, err + } + reinstall_sns, err := deviceDao.GetFirstVersionAndReInstallDeviceSns(logger) + if err != nil { + logger.Warn("GetFirstVersionUnavailableSns GetFirstVersionAndReInstallDeviceSns sql error:", err.Error()) + return nil, err + } + res := []string{} + for _, v := range sns { + if exist := util.InArray(v, reinstall_sns); !exist { + res = append(res, v) + } + } + return res, nil +} + +func RestartDhcp(logger *log.Logger, az string) error { + + logid := logger.GetPoint("logid").(string) + userId := logger.GetPoint("userId").(string) + msg := rabbitIronicMsgApi.RestartDhcpMessage{} + msg.ApiMessage.RequestId = logger.GetPoint("logid").(string) + msg.Az = az + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("RestartDhcp convert RestartDhcpMessage to event error:", err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warnf("RestartDhcp SendToScheduler error, msg:%s, error:%s", util.ObjToJson(msg), err.Error()) + return err + } + return nil +} + +// 设备详情 +func GetById(logger *log.Logger, DeviceID string) (*responseTypes.Device, error) { + entity, err := deviceDao.GetDeviceById(logger, DeviceID) + if err != nil { + logger.Warn("GetById GetDeviceById sql error:", DeviceID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + raidMap := make(map[string]responseTypes.Raid) // 请求一次,避免循环请求 + raidList, raidsErr := raidLogic.QueryRaidsAll(logger) + if raidsErr == nil && len(raidList) != 0 { + for _, vv := range raidList { + raidMap[vv.RaidID] = *vv + } + } + + //deviceTypeRaid, err := rDeviceTypeRaidDao.GetAllRDeviceTypeRaid(logger, map[string]interface{}{ + // "device_type_id": entity.DeviceTypeID, + // "is_del": 0, + //}) + //if err != nil { + // panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + //} + //raid := "" + //if len(deviceTypeRaid) != 0 { + // for _, vv := range deviceTypeRaid { + // raid = raid + vv.RaidID + "," + // } + // raid = strings.Trim(raid, ",") + //} + ////计算raid对应map中的Name + //array := []string{} // 拆分查询 + //deviceTypeRaidName := "" + //if len(raidList) != 0 { + // array = strings.Split(raid, ",") + //} + //if len(array) != 0 { + // raid_ := "" + // for _, str := range array { + // raid_ = raid_ + raidMap[str].Name + "," // RAID0,RAID1 + // } + // deviceTypeRaidName = raid_[0 : len(raid_)-1] + //} + deviceTypeMapInfo := map[string]map[string]string{} + if entity.DeviceTypeID != "" { + v, err := deviceTypeDao.GetDeviceTypeById(logger, entity.DeviceTypeID) + if err != nil { + v = &deviceTypeDao.DeviceType{} + } + //目的是获取拼装出来的机型数据 + info := GetDeviceTypeInfo(logger, v) + + //fmt.Println(info, util.ObjToJson(info), info["nic_"]) + //拼装数据,给上层api直接使用 + + deviceTypeMapInfo[v.DeviceTypeID] = map[string]string{ + "cpu_": info["cpu_"], + "mem_": info["mem_"], + //"sv_": info["sv_"], + //"dv_": info["dv_"], + "gpu_": info["gpu_"], + "nic_": info["nic_"], + } + } + + device := DeviceEntity2DeviceOne(logger, entity, deviceTypeMapInfo) + return device, nil +} +func IDevice2DeviceEntity(i idcApi.IDevice) *deviceDao.Device { + return &deviceDao.Device{ + Sn: i.Sn, + IloIP: i.IloIP, + Cabinet: i.Cabinet, + UPosition: i.UPosition, + } +} +func SaveDevicesFromIdc(logger *log.Logger, param *requestTypes.CreateIdcDevicesRequest) error { + device_map := idcApi.QueryDevices(logger, param.Sns) + toInsert := []*deviceDao.Device{} + toUpdate := []*deviceDao.Device{} + for _, i_device := range device_map { + device_entity, err := deviceDao.GetBySn(logger, i_device.Sn) + if err != nil { + logger.Warn("SaveDevicesFromIdc GetBySn sql error:", i_device.Sn, err.Error()) + device_entity = IDevice2DeviceEntity(i_device) + //device_entity.Region = logger.GetPoint("region").(string) + //device_entity.Az = logger.GetPoint("az").(string) + //device_entity.DeviceType = param.DeviceType + toInsert = append(toInsert, device_entity) + } else { + device_entity.UPosition = i_device.UPosition + device_entity.Cabinet = i_device.Cabinet + toUpdate = append(toUpdate, device_entity) + } + } + if _, err := deviceDao.AddMultiDevice(logger, toInsert); err != nil { + logger.Warn("SaveDevicesFromIdc AddMultiDevice sql error:", err.Error()) + return err + } + for _, device_entity := range toUpdate { + if err := deviceDao.UpdateDeviceById(logger, device_entity); err != nil { + logger.Warn("SaveDevicesFromIdc UpdateDeviceById sql error:", err.Error()) + return err + } + } + return nil +} + +func ImportBms(logger *log.Logger, file multipart.File, size int64) error { + beans, err := parseXlsx(logger, file, size) + if err != nil { + return err + } + toInsert := []*deviceDao.Device{} + toUpdate := []*deviceDao.Device{} + for idx, bean := range beans { + logger.Point(fmt.Sprintf("ImportBms_line_%d", idx), bean) + device_entity, err := deviceDao.GetBySn(logger, bean.Sn) + if err != nil { + logger.Warn("deviceDao.GetBySn sql error:", bean.Sn, err.Error()) + device_entity = &deviceDao.Device{ + //Region: bean.Region, + //Az: bean.Az, + //Sn: bean.Sn, + //IloIP: bean.IloIp, + //DeviceType: bean.DeviceType, + //Cabinet: bean.Cabinet, + //UPosition: bean.UPosition, + //SaleStatus: saleStatus.PUTAWAYING, + //IsDel: 0, + } + toInsert = append(toInsert, device_entity) + } else { + if device_entity.ManageStatus != saleStatus.PUTAWAYING { + logger.Warn("ImportBms sn exist:", device_entity.Sn) + continue + } + //device_entity.Region = bean.Region + //device_entity.Az = bean.Az + //device_entity.IloIP = bean.IloIp + //device_entity.DeviceType = bean.DeviceType + //device_entity.Cabinet = bean.Cabinet + //device_entity.UPosition = bean.UPosition + //device_entity.UPosition = bean.UPosition + //device_entity.SaleStatus = saleStatus.PUTAWAYING + //device_entity.IsDel = 0 + toUpdate = append(toUpdate, device_entity) + } + } + if _, err := deviceDao.AddMultiDevice(logger, toInsert); err != nil { + logger.Warn("ImportBms AddMultiDevice sql error:", err.Error()) + return err + } + for _, device_entity := range toUpdate { + if err := deviceDao.UpdateDeviceById(logger, device_entity); err != nil { + logger.Warn("ImportBms UpdateDeviceById sql error:", err.Error()) + return err + } + } + + if err = saveJDBondInterface(logger, beans); err != nil { + return err + } + if err = saveInterfaces(logger, beans); err != nil { + return err + } + return nil +} +func saveJDBondInterface(logger *log.Logger, beans []*requestTypes.DeviceExcelBean) error { + //data := []*jdBondInterfaceDao.JdBondInterface{} + for _, bean := range beans { + entity := &jdBondInterfaceDao.JdBondInterface{ + Sn: bean.Sn, + IsDel: 1, + } + err := jdBondInterfaceDao.DeleteJdBondInterfaceBySn(logger, entity) + if err != nil { + logger.Warn("delete JdBondInterface err:", bean.Sn, err.Error()) + return err + } + entity = &jdBondInterfaceDao.JdBondInterface{ + Sn: bean.Sn, + PrivateIP: bean.SystemIp, + SwitchIP: bean.SwitchIp, + IsDel: 0, + } + _, err = jdBondInterfaceDao.AddJdBondInterface(logger, entity) + if err != nil { + logger.Warn("insert JdBondInterface err:", bean.Sn, err.Error()) + return err + } + } + return nil +} +func saveInterfaces(logger *log.Logger, beans []*requestTypes.DeviceExcelBean) error { + //data := []*jdBondInterfaceDao.JdBondInterface{} + for _, bean := range beans { + entity := &interfaceDao.Interface{ + Sn: bean.Sn, + IsDel: 1, + } + err := interfaceDao.DeleteInterfaceBySn(logger, entity) + if err != nil { + logger.Warn("delete interface err:", bean.Sn, err.Error()) + return err + } + entity = &interfaceDao.Interface{ + InterfaceName: "eth0", //默认写死,对应的是mac1 + InterfaceType: "lan", //写死,以后根据需要再改 + Sn: bean.Sn, + Mac: bean.Mac1, + SwitchIP: bean.SwitchIp, + //SwitchPort: nil, + IsDel: 0, + } + _, err = interfaceDao.AddInterface(logger, entity) + if err != nil { + logger.Warn("insert interface err:", bean.Sn, err.Error()) + return err + } + entity = &interfaceDao.Interface{ + InterfaceName: "eth1", //默认写死,对应的是mac1 + InterfaceType: "lan", //写死,以后根据需要再改 + Sn: bean.Sn, + Mac: bean.Mac2, + SwitchIP: bean.SwitchIp, + //SwitchPort: "port2", + IsDel: 0, + } + _, err = interfaceDao.AddInterface(logger, entity) + if err != nil { + logger.Warn("insert interface err:", bean.Sn, err.Error()) + return err + } + } + return nil +} +func parseXlsx(logger *log.Logger, file multipart.File, size int64) ([]*requestTypes.DeviceExcelBean, error) { + xlFile, err := xlsx.OpenReaderAt(file, size) + if err != nil { + return nil, err + } + beans := []*requestTypes.DeviceExcelBean{} + for _, sheet := range xlFile.Sheets { + if sheet.Hidden { // 不读隐藏的工作区 + continue + } + for i, row := range sheet.Rows { + if i == 0 { // 头信息 + continue + } + bean := &requestTypes.DeviceExcelBean{} + if err := row.ReadStruct(bean); err != nil { + logger.Warn("parseXlsx ReadStruct error:", err.Error()) + return nil, err + } + beans = append(beans, bean) + } + break //sheet(0) + } + return beans, nil +} + +// 获取所有符合条件的设备,可以用于查询库存,查询所有设备接口使用 +func GetAllDevices(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string) []*deviceDao.Device { + list, err := deviceDao.GetAllDevices(logger, query, fields, sortby, order) + if err != nil { + logger.Warn("GetAllDevices error:", err.Error()) + return nil + } + return list +} + +func GetStockByDeviceTypeIds(logger *log.Logger, deviceTypeIds []string) (map[string]int, error) { + query := map[string]interface{}{ + "is_del": 0, + "device_type_id.in": deviceTypeIds, + "manage_status": "putaway", + } + list, err := deviceDao.GetAllDevices(logger, query, nil, nil, nil) + if err != nil { + logger.Warn("GetAllDevices error:", err.Error()) + return nil, err + } + res := map[string]int{} + for _, v := range list { + _, ok := res[v.DeviceTypeID] + if ok { + res[v.DeviceTypeID] += 1 + } else { + res[v.DeviceTypeID] = 1 + } + } + return res, nil +} + +// 查询设备详情单独使用 +func DeviceEntity2DeviceOne(logger *log.Logger, d *deviceDao.Device, deviceTypeMapInfo map[string]map[string]string) *responseTypes.Device { + + tz := logger.GetPoint("timezone").(string) + idc, err := idcDao.GetIdcById(logger, d.IDcID) //获取机房信息 + if err != nil { + idc = &idcDao.Idc{} + } + //idc := idcMap[d.IDcID] + entity := &deviceTypeDao.DeviceType{} + if d.DeviceTypeID != "" { + entity, err = deviceTypeDao.GetOneDeviceType(logger, map[string]interface{}{"device_type_id": d.DeviceTypeID}) + if err != nil { + entity = &deviceTypeDao.DeviceType{} + } + } + + //entity := deviceTypMap[d.DeviceTypeID] + instance, err := instanceDao.GetInstanceById(logger, d.InstanceID) + if instance == nil { + instance = &instanceDao.Instance{} + } + //instance := instanceMap[d.InstanceID] + image, err := imageDao.GetImageByUuid(logger, instance.ImageID) + if image == nil { + image = &imageDao.Image{} + } + //image := imageMap[instance.ImageID] + //user, _ := userDao.GetUserById(logger, instance.UserID) + //if user == nil { + // user = &userDao.User{} + //} + language := logger.GetPoint("language").(string) + reason := baseLogic.DeviceReason[d.Reason] + if language == baseLogic.EN_US { + reason = baseLogic.DeviceReasonEn[d.Reason] + } + instanceStatusName := baseLogic.InstanceStatus[instance.Status] + if language == baseLogic.EN_US { + instanceStatusName = baseLogic.InstanceStatusEn[instance.Status] + } + instanceReason := baseLogic.InstanceReason[instance.Reason] + if language == baseLogic.EN_US { + instanceReason = baseLogic.InstanceReasonEn[instance.Reason] + } + deviceManageStatusName := baseLogic.DeviceManageStatus[d.ManageStatus] + if language == baseLogic.EN_US { + deviceManageStatusName = baseLogic.DeviceManageStatusEn[d.ManageStatus] + } + deviceSeriesName := baseLogic.DeviceTypeSeries[d.DeviceSeries] + if language == baseLogic.EN_US { + deviceSeriesName = baseLogic.DeviceTypeSeriesEn[d.DeviceSeries] + } + idcName := idc.Name + if language == baseLogic.EN_US { + idcName = idc.NameEn + } + var ( + iloUser string + iloPassword string + switchUser1 string + switchUser2 string + switchPassword1 string + switchPassword2 string + encloure1 string + slot1 int + encloure2 string + slot2 int + ) + // disk, _ := diskDao.GetAllDisk(logger, map[string]interface{}{"device_id": d.DeviceID}) + // if len(disk) == 1 { + // encloure1 = disk[0].Enclosure + // slot1 = disk[0].Slot + // } else if len(disk) == 2 { + // encloure1 = disk[0].Enclosure + // slot1 = disk[0].Slot + // encloure2 = disk[1].Enclosure + // slot2 = disk[1].Slot + // } + + if d.IloUser == "" { + iloUser = idc.IloUser + } else { + iloUser = d.IloUser + } + if d.IloPassword == "" { + iloPassword = idc.IloPassword + } else { + iloPassword = d.IloPassword + } + if d.SwitchUser1 == "" { + switchUser1 = idc.SwitchUser1 + } else { + switchUser1 = d.SwitchUser1 + } + if d.SwitchPassword1 == "" { + switchPassword1 = idc.SwitchPassword1 + } else { + switchPassword1 = d.SwitchPassword1 + } + if d.SwitchUser2 == "" { + switchUser2 = idc.SwitchUser2 + } else { + switchUser2 = d.SwitchUser2 + } + if d.SwitchPassword2 == "" { + switchPassword2 = idc.SwitchPassword2 + } else { + switchPassword2 = d.SwitchPassword2 + } + collectStatus := "2" //2表示未采集 + if d.CollectStatus != "" { + collectStatus = d.CollectStatus + } + + r := &responseTypes.Device{ + ID: d.ID, + DeviceID: d.DeviceID, + IdcID: d.IDcID, + InstanceID: d.InstanceID, + InstanceName: instance.InstanceName, + InstanceStatus: instance.Status, + InstanceStatusName: instanceStatusName, + InstanceReason: instanceReason, + Locked: instance.Locked, + UserId: d.UserId, + UserName: d.UserName, + InstanceCreatedTime: util.TimestampToString(int64(instance.CreatedTime), tz), + InstanceDescription: instance.Description, + + DeviceTypeID: d.DeviceTypeID, + ManageStatus: d.ManageStatus, + ManageStatusName: deviceManageStatusName, + + ImageName: image.ImageName, + + Brand: d.Brand, + Model: d.Model, + Reason: reason, + Cabinet: d.Cabinet, + UPosition: d.UPosition, + Sn: d.Sn, + Description: d.Description, + + Mac1: d.Mac1, + Mac2: d.Mac2, + SwitchIP1: d.SwitchIP1, + SwitchPort1: d.SwitchPort1, + SwitchIP2: d.SwitchIP2, + SwitchPort2: d.SwitchPort2, + //如果设备不存在,从idc中获取 + IloUser: iloUser, + IloPassword: iloPassword, + IloIP: d.IloIP, //必填 + SwitchUser1: switchUser1, + SwitchPassword1: switchPassword1, + SwitchUser2: switchUser2, + SwitchPassword2: switchPassword2, + SwitchIP: d.SwitchIP, + + Mask: d.Mask, + Eth1Mask: d.MaskEth1, + Gateway: d.Gateway, + PrivateIPv4: d.PrivateIPv4, + PrivateEth1IPv4: d.PrivateEth1IPv4, + PrivateIPv6: d.PrivateIPv6, + PrivateEth1IPv6: d.PrivateEth1IPv6, + AdapterID: d.AdapterID, + + Enclosure1: encloure1, + Slot1: slot1, + Enclosure2: encloure2, + Slot2: slot2, + RaidDriver: d.RaidDriver, + CreatedBy: d.CreatedBy, + UpdatedBy: d.UpdatedBy, + CreatedTime: util.TimestampToString(int64(d.CreatedTime), tz), + UpdatedTime: util.TimestampToString(int64(d.UpdatedTime), tz), + + //以下字段从其他表中获取 + //idc + IdcName: idcName, + IDcNameEn: idc.NameEn, + //deviceType + + DeviceType: entity.DeviceType, + DeviceSeries: d.DeviceSeries, + DeviceSeriesName: deviceSeriesName, + + DeviceTypeName: entity.Name, + Architecture: entity.Architecture, + CPUAmount: entity.CPUAmount, + CPUCores: entity.CPUCores, + CPUFrequency: entity.CPUFrequency, + CPUManufacturer: entity.CPUManufacturer, + CPUModel: entity.CPUModel, + + MemType: entity.MemType, + MemAmount: entity.MemAmount, + MemSize: entity.MemSize, + MemFrequency: entity.MemFrequency, + NicAmount: entity.NicAmount, + NicRate: entity.NicRate, + InterfaceMode: entity.InterfaceMode, + SystemVolumeType: entity.SystemVolumeType, + SystemVolumeInterfaceType: entity.DataVolumeInterfaceType, + SystemVolumeAmount: entity.SystemVolumeAmount, + SystemVolumeSize: entity.SystemVolumeSize, + DataVolumeType: entity.DataVolumeType, + DataVolumeInterfaceType: entity.SystemVolumeInterfaceType, + DataVolumeAmount: entity.DataVolumeAmount, + DataVolumeSize: entity.DataVolumeSize, + GpuAmount: entity.GpuAmount, + GpuManufacturer: entity.GpuManufacturer, + GpuModel: entity.GpuModel, + + CollectStatus: collectStatus, + CollectFailReason: d.CollectFailReason, + IsNeedRaid: entity.IsNeedRaid, + } + //拼装信息 + if _, ok := deviceTypeMapInfo[entity.DeviceTypeID]; ok { + r.CpuInfo = deviceTypeMapInfo[entity.DeviceTypeID]["cpu_"] + r.MemInfo = deviceTypeMapInfo[entity.DeviceTypeID]["mem_"] + r.GpuInfo = deviceTypeMapInfo[entity.DeviceTypeID]["gpu_"] + r.NicInfo = deviceTypeMapInfo[entity.DeviceTypeID]["nic_"] + } + + //SvInfo: deviceTypeMapInfo[entity.DeviceTypeID]["sv_"], + //DvInfo: deviceTypeMapInfo[entity.DeviceTypeID]["dv_"], + + return r +} + +func GetGlobalDeviceCount(logger *log.Logger) (int64, error) { + q := map[string]interface{}{ + "is_del": 0, + } + return deviceDao.GetDeviceCount(logger, q) +} + +// 设备详情-磁盘 +func GetDeviceDisksById(logger *log.Logger, DeviceID string) (*responseTypes.DeviceDisks, error) { + deviceEntity, err := deviceDao.GetDeviceById(logger, DeviceID) + if err != nil { + logger.Warn("GetById GetDeviceById sql error:", DeviceID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + res := &responseTypes.DeviceDisks{ + Disks: []*diskDao.Disk{}, + Panfu: []*diskDao.Disk{}, + Volumes: []*responseTypes.VolumeIt{}, + } + + dq := map[string]interface{}{ + "is_del": 0, + "device_id": DeviceID, + } + disks, err := diskDao.GetAllDisk(logger, dq) + if err != nil { + logger.Warnf("GetDeviceDisksById.GetAllDisk error, device_id:%s, error:%s", DeviceID, err.Error()) + return nil, err + } + for _, v := range disks { + if v.Types == "nvme" || v.Types == "controller" { + res.Disks = append(res.Disks, v) + } else if v.Types == "panfu" { + res.Panfu = append(res.Panfu, v) + } + } + + if deviceEntity.DeviceTypeID != "" { + q1 := map[string]interface{}{ + "is_del": 0, + "device_type_id": deviceEntity.DeviceTypeID, + } + volumeEntities, err := volumeDao.GetAllVolume(logger, q1) //device_type_id如果为空,where就忽略了key + if err != nil { + logger.Warnf("GetDeviceDisksById.GetAllVolume error, device_type_id:%s, error:%s", deviceEntity.DeviceTypeID, err.Error()) + } + volume := responseTypes.Volume{} + for _, v := range volumeEntities { + volume.VolumeID = v.VolumeID + volume.VolumeName = v.VolumeName + volume.VolumeType = v.VolumeType + volume.VolumeSize = v.VolumeSize + volume.VolumeUnit = v.VolumeUnit + + volume.VolumeAmount = v.VolumeAmount + volume.DiskType = v.DiskType + volume.InterfaceType = v.InterfaceType + + volumeId := v.VolumeID + q2 := map[string]interface{}{ + "is_del": 0, + "volume_id": v.VolumeID, + } + volumnRaidEntities, err := rVolumeRaidDao.GetAllRVolumeRaid(logger, q2) + if err != nil { + logger.Warnf("GetDeviceDisksById.GetVolumeById error, volume_id:%s, error:%s", volumeId, err.Error()) + } + volume.RaidCan = volumnRaidEntities[0].RaidCan + raids := []*raidDao.Raid{} + for _, v2 := range volumnRaidEntities { + raids = append(raids, &raidDao.Raid{ + RaidID: v2.RaidID, + Name: v2.RaidName, + }) + } + + diskEntities, err := diskDao.GetDiskWithDeviceIdVolumeId(logger, DeviceID, volumeId) + if err != nil { + logger.Warnf("GetDeviceDisksById.GetVolumeById error, volume_id:%s, error:%s", volumeId, err.Error()) + } + + vt := &responseTypes.VolumeIt{ + Volume: volume, + Raids: raids, + Disks: diskEntities, + } + res.Volumes = append(res.Volumes, vt) + } + } + + return res, nil +} + +func AssociateDeviceDisks(logger *log.Logger, param *requestTypes.AssociateDeviceDisksRequest) (bool, error) { + + deviceEntity, err := deviceDao.GetOneDevice(logger, map[string]interface{}{ + "device_id": param.DeviceID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Warnf("AssociateDeviceDisks.GetOneDevice sql error, device_id:%s, error:%s", param.DeviceID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("deviceId %s 校验非法", param.DeviceID), fmt.Sprintf("deviceId %s check invalided", param.DeviceID))) + } + + deviceTypeEntity, err := deviceTypeDao.GetDeviceTypeById(logger, param.DeviceTypeID) + if err != nil { + logger.Warnf("GetAssociatedDisks.GetDeviceTypeById sql error, device_type_id:%s, error:%s", param.DeviceTypeID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("device_type_Id %s 校验非法", param.DeviceTypeID), fmt.Sprintf("device_type_Id %s check invalided", param.DeviceTypeID))) + } + + //manageStatus := param.ManageStatus + // if deviceEntity.ManageStatus != baseLogic.IN && deviceEntity.ManageStatus != baseLogic.PUTAWAYFAIL { + // panic(constant.BuildInvalidArgumentWithArgs("设备必须是已入库或者上架失败,才可以执行预上架操作", "device manageStatus not support")) + // } + + //验证设备的多个卷选择的diskid是否有重复 + diskIdCheck := map[string]int{} + + rEntities := []*rDeviceVolumeDisksDao.RDeviceVolumeDisks{} + fmt.Println(param.Volumes) + + //校验volumeid,diskid,deviceid的归属关系是否正确 + for _, v := range param.Volumes { + fmt.Println("sssss", v.VolumeID) + volumeId := v.VolumeID + + volumeEntity, err := volumeDao.GetVolumeById(logger, volumeId) + if err != nil { + logger.Warnf("param volumeId %s check invalid, error:%s", volumeId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("volumeId %s 校验非法", volumeId), fmt.Sprintf("volumeId %s check invalided", volumeId))) + } + if volumeEntity.DeviceTypeID != param.DeviceTypeID { + logger.Warnf("param volumeId %s and devicetype_id %s not match", volumeId, param.DeviceTypeID) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("volumeId %s 和 devicetype %s 校验非法", volumeId, param.DeviceTypeID), fmt.Sprintf("volumeId %s and devicetype %s check invalid", volumeId, param.DeviceTypeID))) + } + rVolumeRaidEntities, err := rVolumeRaidDao.GetRVolumeRaidsByVId(logger, volumeEntity.VolumeID) + logger.Infof("AssociateDeviceDisks volume_id:%s GetRVolumeRaidsByVId res:%s", volumeEntity.VolumeID, util.InterfaceToJson(rVolumeRaidEntities)) + var raidCan string + mindisks := 1 + maxdisks := math.MaxInt + fmt.Println("长度", len(rVolumeRaidEntities)) + if len(rVolumeRaidEntities) == 0 { //没有raid卡,使用盘符的情况 + mindisks = 1 + maxdisks = 1 + fmt.Println("", volumeEntity.VolumeID) + } else { + raidCan = rVolumeRaidEntities[0].RaidCan + fmt.Println(raidCan, 666) + if util.InArray(raidCan, []string{baseLogic.RAID_CAN_NO_RAID, baseLogic.RAID_CAN_SINGLE_RAID, baseLogic.RAID_CAN_SINGLE_RAID_EN}) { //nvme的情况 + mindisks = 1 + maxdisks = 1 + } else { + for _, rVolumeRaidEntity := range rVolumeRaidEntities { + fmt.Println("raidname", rVolumeRaidEntity.RaidName) + if util.InArray(rVolumeRaidEntity.RaidName, []string{"RAID0", "RAID1"}) { + mindisks = util.Max(mindisks, 2) + } else if rVolumeRaidEntity.RaidName == "RAID5" { + mindisks = util.Max(mindisks, 3) + } else if rVolumeRaidEntity.RaidName == "RAID10" { + mindisks = util.Max(mindisks, 4) + } + } + } + } + if mindisks < volumeEntity.VolumeAmount { + mindisks = volumeEntity.VolumeAmount + } + logger.Infof("volume:%s require min:%d, max:%d", volumeEntity.VolumeID, mindisks, maxdisks) + + var types string = "controller" //默认controller + //无需配置raid的机型,只能选盘符。需要配置RAID的,根据以下逻辑判断 + if deviceTypeEntity.IsNeedRaid != "no_need_raid" { // no_need_raid + //TODO 这个规则需确定 + //raidCan只存在了这个表,每个volumeID下面的raid配置肯定都是一样的,一个voulumeId下面对应多个raid,但是只有一个共同的raid模式 + if raidCan == baseLogic.RAID_CAN_SINGLE_RAID_EN || raidCan == baseLogic.RAID_CAN_RAID { //如果是单盘RAID0或者是RAID + types = "controller" + } else if raidCan == baseLogic.RAID_CAN_NO_RAID { + types = "nvme" + } + } else { + types = "panfu" + } + + diskIds := v.DiskIDs + fmt.Println(diskIds, mindisks, maxdisks) + if len(diskIds) < mindisks { //至少需要磁盘的块数校验 + logger.Warnf("param volumeId %s require at least %d disks", volumeId, mindisks) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("卷名称:%s,最少%d块盘,数量是所选RAID需要的最大盘数", volumeEntity.VolumeName, mindisks), fmt.Sprintf("volumeName:%s,At least %d disks", volumeEntity.VolumeName, mindisks))) + } + if len(diskIds) > maxdisks { //至多需要磁盘的块数校验 + logger.Warnf("param volumeId %s require at most %d disks", volumeId, maxdisks) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("卷名称:%s,仅支持1块盘", volumeEntity.VolumeName), fmt.Sprintf("volumeName:%s,Only support 1 disk", volumeEntity.VolumeName))) + } + + for _, diskId := range diskIds { + diskIdCheck[diskId] += 1 + if diskIdCheck[diskId] > 1 { //设备的多个卷选择的diskid有重复 + logger.Warnf("param diskid %s repeated, device_id:%s", diskId, param.DeviceID) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("param diskid %s repeated", diskId), fmt.Sprintf("param diskid %s repeated", diskId))) + } + + diskEntity, err := diskDao.GetDiskByUuid(logger, diskId) + if err != nil { + logger.Warnf("param diskId %s check invalid, error:%s", diskId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("diskId %s 校验非法", diskId), fmt.Sprintf("diskId %s check invalided", diskId))) + } + if diskEntity.DeviceID != param.DeviceID { + logger.Warnf("param diskId and device not match, %s error:%s", diskId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("diskId %s 和 device %s 校验非法", diskId, param.DeviceID), fmt.Sprintf("diskId %s and device %s check invalid", diskId, param.DeviceID))) + } + if diskEntity.Types != types { //磁盘类型(controllers/nvme/panfu)的校验 + logger.Warnf("param disk types invalid, volume_id:%s, disk_id:%s, disk type:%s, require type:%s", volumeId, diskId, diskEntity.Types, types) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("diskId %s 类型校验非法", diskId), fmt.Sprintf("diskId %s types check invalid", diskId))) + } + + //无需配置raid的机型,只能选非盘符的。1->need_raid;2->no_need_raid + if (deviceTypeEntity.IsNeedRaid == "no_need_raid" && diskEntity.Types != "panfu") || (deviceTypeEntity.IsNeedRaid != "no_need_raid" && diskEntity.Types == "panfu") { + logger.Warnf("param diskId not match devicetype, disk_id:%s, device_type_id:%s", diskId, deviceEntity.DeviceTypeID) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("param disk not match devicetype, disk_id:%s, device_type_id:%s", diskId, deviceEntity.DeviceTypeID), fmt.Sprintf("param diskId not match devicetype, disk_id:%s, device_type_id:%s", diskId, deviceEntity.DeviceTypeID))) + } + + } + } + + //删除原来绑定的disk + q := map[string]interface{}{ + "is_del": 0, + "device_id": param.DeviceID, + } + u := map[string]interface{}{ + "is_del": 1, + } + if err := rDeviceVolumeDisksDao.UpdateMultiRDeviceVolumeDisk(logger, q, u); err != nil { + logger.Warnf("AssociateDeviceDisks.delRDeviceVolumeDisk error, device_id:%s, error:%s", param.DeviceID, err.Error()) + } else { + logger.Infof("AssociateDeviceDisks.delMultiRDeviceVolumeDisk succ, device_id:%s", param.DeviceID) + } + + //更改设备的机型 + deviceEntity.DeviceTypeID = param.DeviceTypeID + if err := deviceDao.UpdateDeviceById(logger, deviceEntity); err != nil { + logger.Warnf("associateDisk.UpdateDeviceById error, device_id:%s, device_type_id:%s, error:%s", param.DeviceID, param.DeviceTypeID, err.Error()) + } else { + logger.Infof("AssociateDeviceDisks.UpdateDeviceTypeById succ, device_id:%s, device_type_id:%s", param.DeviceID, param.DeviceTypeID) + } + + for _, v := range param.Volumes { + volumeId := v.VolumeID + + volumeEntity, _ := volumeDao.GetVolumeById(logger, volumeId) + + diskIds := v.DiskIDs + + diskEntities := []*diskDao.Disk{} + for _, diskId := range diskIds { + diskEntity, _ := diskDao.GetDiskByUuid(logger, diskId) + diskEntities = append(diskEntities, diskEntity) + + } + if len(diskEntities) == 0 { + logger.Warnf("disk not selected, sn:%s, volume_id:%s", deviceEntity.Sn, v.VolumeID) + continue + } + + if diskEntities[0].Types == "panfu" || diskEntities[0].Types == "nvme" { //绑定盘符或者nvme盘时,新建或更新device_hints表 + + deviceHintsEntity, _ := deviceHintsDao.GetDeviceHintsBySnAndVolumeId(logger, deviceEntity.Sn, v.VolumeID) + size, _ := strconv.ParseInt(diskEntities[0].Size, 10, 64) + if deviceHintsEntity == nil { //新建 + + entity := &deviceHintsDao.DeviceHints{ + Sn: deviceEntity.Sn, + VolumeId: v.VolumeID, + Size: size, + Serial: diskEntities[0].SerialNumber, + ByPath: diskEntities[0].DevicePath, + } + + entity.VolumeType = volumeEntity.VolumeType + + if _, err := deviceHintsDao.AddDeviceHints(logger, entity); err != nil { + logger.Warnf("AssociateDeviceDisks.saveDeviceHints error, sn:%s, error:%s", deviceEntity.Sn, err.Error()) + } + } else { //更新 + deviceHintsEntity.Size = size + deviceHintsEntity.Serial = diskEntities[0].SerialNumber + deviceHintsEntity.ByPath = diskEntities[0].DevicePath + if err := deviceHintsDao.UpdateDeviceHintsById(logger, deviceHintsEntity); err != nil { + logger.Warnf("AssociateDeviceDisks.UpdateDeviceHintsById error, sn:%s, error:%s", deviceEntity.Sn, err.Error()) + } + } + } + + for _, diskId := range v.DiskIDs { + r := &rDeviceVolumeDisksDao.RDeviceVolumeDisks{ + DeviceID: param.DeviceID, + VolumeID: v.VolumeID, + VolumeType: volumeEntity.VolumeType, + DiskID: diskId, + CreatedBy: logger.GetPoint("username").(string), + UpdatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + } + rEntities = append(rEntities, r) + } + } + + if len(rEntities) > 0 { + if rDeviceVolumeDisksDao.AddMultiRDeviceVolumeDisk(logger, rEntities); err != nil { + logger.Warnf("AssociateDeviceDisks.AddMultiRDeviceVolumeDisk error, device_id:%s, error:%s", param.DeviceID, err.Error()) + return false, err + } + } + + return true, nil +} + +func GetAssociatedDisks(logger *log.Logger, param *requestTypes.GetAssociatedDisksRequest) ([]*response.Disk, error) { + volumeId := param.VolumeID + _, err := deviceDao.GetOneDevice(logger, map[string]interface{}{ + "device_id": param.DeviceID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Warnf("GetAssociatedDisks.GetOneDevice sql error, device_id:%s, error:%s", param.DeviceID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("deviceId %s 校验非法", param.DeviceID), fmt.Sprintf("deviceId %s check invalided", param.DeviceID))) + } + + deviceTypeEntity, err := deviceTypeDao.GetDeviceTypeById(logger, param.DeviceTypeID) + if err != nil { + logger.Warnf("GetAssociatedDisks.GetDeviceTypeById sql error, device_type_id:%s, error:%s", param.DeviceTypeID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("device_type_Id %s 校验非法", param.DeviceTypeID), fmt.Sprintf("device_type_Id %s check invalided", param.DeviceTypeID))) + } + + volumeEntity, err := volumeDao.GetVolumeById(logger, volumeId) + if err != nil { + logger.Warnf("GetAssociatedDisks.param volumeId %s check invalid, error:%s", volumeId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("volumeId %s 校验非法", volumeId), fmt.Sprintf("volumeId %s check invalided", volumeId))) + } + if volumeEntity.DeviceTypeID != param.DeviceTypeID { + logger.Warnf("GetAssociatedDisks.param volumeId and device not match, %s error:%s", volumeId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("volumeId %s 和 deviceId %s 校验非法", volumeId, param.DeviceID), fmt.Sprintf("volumeId %s and deviceId %s check invalid", volumeId, param.DeviceID))) + } + + types := []string{} + rVolumeRaidEntities, err := rVolumeRaidDao.GetRVolumeRaidsByVId(logger, param.VolumeID) + if err != nil { + logger.Warnf("GetAssociatedDisks.GetRVolumeRaidById error, volume_id:%s, error:%s", param.VolumeID, err.Error()) + } + + //无需配置raid的机型,只能选盘符。需要配置RAID的,根据以下逻辑判断 + if deviceTypeEntity.IsNeedRaid != "no_need_raid" { // no_need_raid + //TODO 这个规则需确定 + raidCan := rVolumeRaidEntities[0].RaidCan //raidCan只存在了这个表,每个volumeID下面的raid配置肯定都是一样的,一个voulumeId下面对应多个raid,但是只有一个共同的raid模式 + if raidCan == baseLogic.RAID_CAN_SINGLE_RAID_EN || raidCan == baseLogic.RAID_CAN_RAID { //如果是单盘RAID0或者是RAID + types = []string{"controller"} + } else if raidCan == baseLogic.RAID_CAN_NO_RAID { + types = []string{"nvme"} + } + } else { + types = []string{"panfu"} + } + if len(types) == 0 { //默认值 + types = []string{"controller"} + } + where := map[string]interface{}{ + "is_del": 0, + "device_id": param.DeviceID, + // "volume_size.gte": volumeEntity.VolumeSize, + "types.in": types, + } + if volumeEntity.InterfaceType != baseLogic.NOT_LIMITED { + where["pd_type"] = strings.ToUpper(volumeEntity.InterfaceType) + } + if types[0] == "panfu" { //lsblk命令没有pd_type + delete(where, "pd_type") + } + if volumeEntity.DiskType != baseLogic.NOT_LIMITED { + where["media_type"] = strings.ToUpper(volumeEntity.DiskType) + } + allDiskEntities, err := diskDao.GetAllDisk(logger, where) + if err != nil { + logger.Warnf("GetAssociatedDisks.GetAllDisk error, device_id:%s, types:%v, error:%s", param.DeviceID, types, err.Error()) + } + + diskEntities, err := diskDao.GetDiskWithDeviceIdVolumeId(logger, param.DeviceID, volumeId) + if err != nil { + logger.Warnf("GetAssociatedDisks.GetDiskWithVolumeId error, device_id:%s, error:%s", param.DeviceID, err.Error()) + } + diskids := []string{} + for _, v := range diskEntities { + diskids = append(diskids, v.DiskId) + } + + res := []*response.Disk{} + for _, v := range allDiskEntities { + //以GB来比较 + diskSize, _ := strconv.ParseFloat(strings.TrimSpace(v.Size), 64) + volumeSize := volumeEntity.VolumeSize + volumeSize64 := .0 + if v.SizeUnit == "TB" && volumeEntity.VolumeUnit == "GB" { //TB的换算成GB + diskSize = 1024 * diskSize + } else if v.SizeUnit == "GB" && volumeEntity.VolumeUnit == "TB" { + // ParseFloat 将字符串转换为浮点数 + // str:要转换的字符串 + // bitSize:指定浮点类型(32:float32、64:float64) + // 如果 str 是合法的格式,而且接近一个浮点值, + // 则返回浮点数的四舍五入值(依据 IEEE754 的四舍五入标准) + // 如果 str 不是合法的格式,则返回“语法错误” + // 如果转换结果超出 bitSize 范围,则返回“超出范围” + //到float64 + volumeSize64, _ := strconv.ParseFloat(volumeSize, 64) + volumeSize64 = 1024 * volumeSize64 + } + + if diskSize < volumeSize64 { + continue + } + + res = append(res, &response.Disk{ + Disk: *v, + Selected: util.InArray(v.DiskId, diskids), + }) + } + + return res, nil +} + +func DeviceAssociateDeviceType(logger *log.Logger, param *requestTypes.DeviceAssociateDeviceTypeRequest) (bool, error) { + + deviceEntity, err := deviceDao.GetOneDevice(logger, map[string]interface{}{ + "device_id": param.DeviceID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Warnf("DeviceAssociateDeviceType.GetOneDevice sql error, device_id:%s, error:%s", param.DeviceID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("deviceId %s 校验非法", param.DeviceID), fmt.Sprintf("deviceId %s check invalided", param.DeviceID))) + } + + //if deviceEntity.InstanceID != "" { + // logger.Warnf("DeviceAssociateDeviceType device_id %s with instance_id %s not empty, operation denied ", param.DeviceID, deviceEntity.InstanceID) + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("AssociateDeviceDisks device_id %s with instance_id %s not empty, operation denied ", param.DeviceID, deviceEntity.InstanceID), fmt.Sprintf("DeviceAssociateDeviceType device_id %s with instance_id %s not empty, operation denied ", param.DeviceID, deviceEntity.InstanceID))) + //} + if deviceEntity.ManageStatus == "created" { + logger.Warnf("DeviceAssociateDeviceType device_id %s has already sold", param.DeviceID) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("AssociateDeviceDisks device_id %s 已售卖", param.DeviceID), fmt.Sprintf("DeviceAssociateDeviceType device_id %s has already sold", param.DeviceID))) + } + if deviceEntity.DeviceTypeID != param.DeviceTypeID { //设备更换了机型,则r_device_volume_disk表相关数据要清空 + deviceTypeEntity, err := deviceTypeDao.GetDeviceTypeById(logger, param.DeviceTypeID) + if err != nil { + logger.Warnf("DeviceAssociateDeviceType.GetDeviceTypeById sql error, device_type_id:%s, error:%s", param.DeviceTypeID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("device_type_Id %s 校验非法", param.DeviceTypeID), fmt.Sprintf("device_type_Id %s check invalided", param.DeviceTypeID))) + } + + deviceEntity.DeviceTypeID = deviceTypeEntity.DeviceTypeID + deviceEntity.DeviceSeries = deviceTypeEntity.DeviceSeries //同步一下机型的机型类型字段到device表,目的是冗余这个字段,便于搜索 + if err := deviceDao.UpdateDeviceById(logger, deviceEntity); err != nil { + logger.Warnf("DeviceAssociateDeviceType.UpdateDeviceById error, device_id:%s, device_type_id:%s, error:%s", param.DeviceID, param.DeviceTypeID, err.Error()) + return false, err + } + + /* + 前端的绑定磁盘和绑定机型请求过来的顺序不固定,所以这里不能这样删除。。。 + q := map[string]interface{}{ + "is_del": 0, + "device_id": param.DeviceID, + } + u := map[string]interface{}{ + "is_del": 1, + } + if err := rDeviceVolumeDisksDao.UpdateMultiRDeviceVolumeDisk(logger, q, u); err != nil { + logger.Warnf("DeviceAssociateDeviceType.UpdateMultiRDeviceVolumeDisk error, device_id:%s, error:%s", param.DeviceID, err.Error()) + } + */ + } + + return true, nil +} diff --git a/bmp-openapi/logic/deviceTypeLogic/deviceTypeLogic.go b/bmp-openapi/logic/deviceTypeLogic/deviceTypeLogic.go new file mode 100644 index 0000000..a87b133 --- /dev/null +++ b/bmp-openapi/logic/deviceTypeLogic/deviceTypeLogic.go @@ -0,0 +1,1338 @@ +package deviceTypeLogic + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/diskDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rVolumeRaidDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/volumeDao" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceTypeDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/imageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/osDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rDeviceTypeImageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rDeviceTypeImagePartitionDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/raidDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/imageLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +var K int = 1 + +func Create(logger *log.Logger, param *requestTypes.CreateDeviceTypeRequest) (string, error) { + _, err := idcDao.GetIdcById(logger, param.IDcID) + if err != nil { + logger.Warn("GetIdcByUuid sql error:", param.IDcID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs("机房id不存在", "idcId not exist")) + } + //入库机型 + deviceTypeList, _ := deviceTypeDao.QueryAllDeviceTypes(logger, map[string]interface{}{ + "name": param.Name, + "is_del": baseLogic.IS_NOT_DEL, + }) + if len(deviceTypeList) != 0 { + panic(constant.BuildInvalidArgumentWithArgs("机型名称已存在", "deviceType name exist")) + } + //入库机型规格 + deviceTypeList, _ = deviceTypeDao.QueryAllDeviceTypes(logger, map[string]interface{}{ + "device_type": param.DeviceType, + "is_del": baseLogic.IS_NOT_DEL, + }) + if len(deviceTypeList) != 0 { + panic(constant.BuildInvalidArgumentWithArgs("机型规格已存在", "deviceType exist")) + } + entity := BuildDeviceTypeEntity(logger, param) + if err := addVolume(logger, entity.DeviceTypeID, param); err != nil { + logger.Warn("AddVolume error:", param.Volumes, err.Error()) + return "", err + } + //入库关联raid信息,表 r_device_type_raid,ToDo 1.2标准版以后不再这么关联机型和raid 而是改为了卷和raid的关联 + //if err := addDeviceTypeRaid(logger, entity.DeviceTypeID, param.RaidID, param.SystemVolumeUnit, param.SystemVolumeType, param.SystemVolumeInterfaceType, param.SystemVolumeSize, param.SystemVolumeAmount); err != nil { + // logger.Warn("AddDeviceTypeRaid sql error:", param.DeviceType, err.Error()) + // return "", err + //} + if _, err := deviceTypeDao.AddDeviceType(logger, entity); err != nil { + logger.Warn("AddDeviceType sql error:", param.DeviceType, err.Error()) + return "", err + } + return entity.DeviceTypeID, nil +} +func addVolume(logger *log.Logger, deviceTypeId string, deviceType *requestTypes.CreateDeviceTypeRequest) error { + for _, v := range deviceType.Volumes { + volume := &volumeDao.Volume{ + VolumeID: util.GetUuid("vl-"), + DeviceTypeID: deviceTypeId, + VolumeName: v.VolumeName, + VolumeType: v.VolumeType, + DiskType: v.DiskType, + InterfaceType: v.InterfaceType, + VolumeSize: v.VolumeSize, + VolumeUnit: v.VolumeUnit, + VolumeAmount: v.VolumeAmount, + //RaidCan: v.RaidCan, + //Raid: v.Raid, + + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if _, err := volumeDao.AddVolume(logger, volume); err != nil { + logger.Warn("AddVolume sql error:", err.Error()) + return err + } + if v.Raid != "" { + raidIdList := strings.Split(v.Raid, ",") + for _, raidId := range raidIdList { + raidInfo, err := raidDao.GetRaidById(logger, raidId) + if err != nil { + //fmt.Println(raidInfo == nil, err.Error()) + logger.Warn("raid sql error", err.Error()) + continue + } + rVolumeRaid := &rVolumeRaidDao.RVolumeRaid{ + VolumeID: volume.VolumeID, + VolumeType: v.VolumeType, + DeviceTypeID: deviceTypeId, + RaidCan: v.RaidCan, + RaidID: raidId, + RaidName: raidInfo.Name, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if _, err := rVolumeRaidDao.AddRVolumeRaid(logger, rVolumeRaid); err != nil { + logger.Warn("Add rVolumeRaidDao sql error:", err.Error()) + return err + } + } + } else { + rVolumeRaid := &rVolumeRaidDao.RVolumeRaid{ + VolumeID: volume.VolumeID, + VolumeType: v.VolumeType, + DeviceTypeID: deviceTypeId, + RaidCan: v.RaidCan, + RaidID: "", + RaidName: "", + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if _, err := rVolumeRaidDao.AddRVolumeRaid(logger, rVolumeRaid); err != nil { + logger.Warn("Add rVolumeRaidDao sql error:", err.Error()) + return err + } + } + } + return nil +} +func modifyVolume(logger *log.Logger, deviceTypeId string, deviceType *requestTypes.ModifyDeviceTypeRequest) error { + for _, v := range deviceType.Volumes { + volume := &volumeDao.Volume{ + VolumeID: util.GetUuid("vl-"), + DeviceTypeID: deviceTypeId, + VolumeName: v.VolumeName, + VolumeType: v.VolumeType, + DiskType: v.DiskType, + InterfaceType: v.InterfaceType, + VolumeSize: v.VolumeSize, + VolumeUnit: v.VolumeUnit, + VolumeAmount: v.VolumeAmount, + //RaidCan: v.RaidCan, + //Raid: v.Raid, + + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if _, err := volumeDao.AddVolume(logger, volume); err != nil { + logger.Warn("AddVolume sql error:", err.Error()) + return err + } + if v.Raid != "" { + raidIdList := strings.Split(v.Raid, ",") + for _, raidId := range raidIdList { + raidInfo, err := raidDao.GetRaidById(logger, raidId) + if err != nil { + //fmt.Println(raidInfo == nil, err.Error()) + logger.Warn("raid sql error", err.Error()) + continue + } + rVolumeRaid := &rVolumeRaidDao.RVolumeRaid{ + VolumeID: volume.VolumeID, + VolumeType: v.VolumeType, + DeviceTypeID: deviceTypeId, + RaidCan: v.RaidCan, + RaidID: raidId, + RaidName: raidInfo.Name, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if _, err := rVolumeRaidDao.AddRVolumeRaid(logger, rVolumeRaid); err != nil { + logger.Warn("Add rVolumeRaidDao sql error:", err.Error()) + return err + } + } + } else { + rVolumeRaid := &rVolumeRaidDao.RVolumeRaid{ + VolumeID: volume.VolumeID, + VolumeType: v.VolumeType, + DeviceTypeID: deviceTypeId, + RaidCan: v.RaidCan, + RaidID: "", + RaidName: "", + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if _, err := rVolumeRaidDao.AddRVolumeRaid(logger, rVolumeRaid); err != nil { + logger.Warn("Add rVolumeRaidDao sql error:", err.Error()) + return err + } + } + } + return nil +} + +func BuildDeviceTypeEntity(logger *log.Logger, param *requestTypes.CreateDeviceTypeRequest) *deviceTypeDao.DeviceType { + //var systemVolumeSize, dataVolumeSize int + //if param.SystemVolumeUnit == "TB" { + // systemVolumeSize = param.SystemVolumeSize * K + //} else { + // systemVolumeSize = param.SystemVolumeSize + //} + //if param.DataVolumeUnit == "TB" { + // dataVolumeSize = param.DataVolumeSize * K + //} else { + // dataVolumeSize = param.DataVolumeSize + //} + if param.GpuManufacturer == "" { + if param.GpuModel != "" || param.GpuAmount != 0 { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.GpuModel == "" { + if param.GpuManufacturer != "" || param.GpuAmount != 0 { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.GpuAmount == 0 { + if param.GpuManufacturer != "" || param.GpuModel != "" { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + //if param.DataVolumeType == "" { + // if param.DataVolumeInterfaceType != "" || param.DataVolumeAmount != 0 || param.DataVolumeSize != 0 { + // panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + // } + //} + //if param.DataVolumeInterfaceType == "" { + // if param.DataVolumeType != "" || param.DataVolumeAmount != 0 || param.DataVolumeSize != 0 { + // panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + // } + //} + //if param.DataVolumeAmount == 0 { + // if param.DataVolumeInterfaceType != "" || param.DataVolumeType != "" || param.DataVolumeSize != 0 { + // panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + // } + //} + //if param.DataVolumeSize == 0 { + // if param.DataVolumeInterfaceType != "" || param.DataVolumeAmount != 0 || param.DataVolumeType != "" { + // panic(constant.BuildInvalidArgumentWithArgs("数据盘不合法", "data volume invalidate")) + // } + //} + + var bootmode string + if param.BootMode == "" { + //用户缺失此参数时,如果x86的默认为bios + if param.Architecture == "x86_64" { + bootmode = "Legacy/BIOS" + } else { + bootmode = "UEFI" + } + } else { + bootmode = param.BootMode + } + + return &deviceTypeDao.DeviceType{ + IDcID: param.IDcID, + DeviceTypeID: util.GetUuid("dt-"), + DeviceType: param.DeviceType, + Name: param.Name, + DeviceSeries: param.DeviceSeries, + Height: param.Height, + Architecture: param.Architecture, + Description: param.Description, + + CPUAmount: param.CPUAmount, + CPUCores: param.CPUCores, + CPUFrequency: param.CPUFrequency, + CPUManufacturer: param.CPUManufacturer, + CPUModel: param.CPUModel, + + MemAmount: param.MemAmount, + MemSize: param.MemSize, + MemFrequency: param.MemFrequency, + MemType: param.MemType, + NicAmount: param.NicAmount, + NicRate: param.NicRate, + InterfaceMode: param.InterfaceMode, + GpuAmount: param.GpuAmount, + GpuManufacturer: param.GpuManufacturer, + GpuModel: param.GpuModel, + + //SystemVolumeType: param.SystemVolumeType, + //SystemVolumeInterfaceType: param.SystemVolumeInterfaceType, + //SystemVolumeAmount: param.SystemVolumeAmount, + //RaidCan: param.RaidCan, + //SystemVolumeSize: systemVolumeSize, + //SystemVolumeUnit: param.SystemVolumeUnit, + // + //DataVolumeType: param.DataVolumeType, + //DataVolumeInterfaceType: param.DataVolumeInterfaceType, + //DataVolumeAmount: param.DataVolumeAmount, + //DataVolumeSize: dataVolumeSize, + //DataVolumeUnit: param.DataVolumeUnit, + CreatedBy: logger.GetPoint("username").(string), + UpdatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + CpuSpec: param.CpuSpec, + MemSpec: param.MemSpec, + BootMode: bootmode, + IsNeedRaid: param.IsNeedRaid, + } +} +func QueryDeviceTypes(logger *log.Logger, param *requestTypes.QueryDeviceTypesRequest, p util.Pageable) ([]*responseTypes.DeviceType, int64, error) { + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "idc_id": param.IdcID, + "is_del": 0, + } + if param.Name != "" { + query["name.like"] = "%" + param.Name + "%" + } + if param.DeviceType != "" { + query["device_type.in"] = strings.Split(param.DeviceType, ",") + } + if param.DeviceTypeID != "" { + query["device_type_id.in"] = strings.Split(param.DeviceTypeID, ",") + } + if param.DeviceSeries != "" { + query["device_series.in"] = strings.Split(param.DeviceSeries, ",") + } + + count, err := deviceTypeDao.QueryDeviceTypesCount(logger, query) + if err != nil { + logger.Warnf("DescribeDeviceTypes_GetDeviceTypeCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + dts := []*deviceTypeDao.DeviceType{} + if param.IsAll == baseLogic.IS_ALL { + dts, err = deviceTypeDao.QueryAllDeviceTypes(logger, query) + } else { + dts, err = deviceTypeDao.QueryDeviceTypes(logger, query, offset, limit) + } + if err != nil { + logger.Warnf("QueryDeviceTypes sql err, param:%s, error:%s", util.ObjToJson(param), err.Error()) + return nil, 0, err + } + res := []*responseTypes.DeviceType{} + deviceTypeIds := []string{} + for _, value := range dts { + deviceTypeIds = append(deviceTypeIds, value.DeviceTypeID) + } + + deviceTypeId2Stock := map[string]int{} + if len(deviceTypeIds) != 0 { + deviceTypeId2Stock, err = deviceLogic.GetStockByDeviceTypeIds(logger, deviceTypeIds) + if err != nil { + logger.Warnf("GetStockByDeviceTypeIds error:%s", err.Error()) + } + } + + for _, value := range dts { + v := DeviceTypeEntity2DeviceType(logger, value) + stock, ok := deviceTypeId2Stock[v.DeviceTypeID] + if ok { + v.StockAvailable = stock + } else { + v.StockAvailable = 0 + } + res = append(res, v) + } + return res, count, err +} +func QueryDeviceType(logger *log.Logger, param *requestTypes.QueryDeviceTypesRequest) (*responseTypes.DeviceType, error) { + query := map[string]interface{}{ + "is_del": 0, + } + //if param.Id != 0 { + // query["id"] = param.Id + //} + if param.DeviceType != "" { + query["device_type"] = param.DeviceType + } + if param.DeviceTypeID != "" { + query["device_type_id"] = param.DeviceTypeID + } + dts, err := deviceTypeDao.GetOneDeviceType(logger, query) + if err != nil { + logger.Warnf("QueryDeviceType sql err, param:%s, error:%s", util.ObjToJson(param), err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + res := DeviceTypeEntity2DeviceType(logger, dts) + return res, err +} +func QueryDeviceTypeById(logger *log.Logger, deviceTypeId string) (*responseTypes.DeviceType, error) { + + deviceType, err := deviceTypeDao.GetDeviceTypeById(logger, deviceTypeId) + if err != nil { + logger.Warnf("QueryDeviceType sql err, deviceTypeId:%s, error:%s", deviceTypeId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + res := DeviceTypeEntity2DeviceType(logger, deviceType) + return res, err +} +func ModifyDeviceType(logger *log.Logger, param *requestTypes.ModifyDeviceTypeRequest, deviceTypeID string) error { + + entity, err := deviceTypeDao.GetOneDeviceType(logger, map[string]interface{}{ + "device_type_id": deviceTypeID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Warn("GetDeviceTypeByUuid sql error:", deviceTypeID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if param.IDcID != nil { + _, err = idcDao.GetIdcById(logger, *param.IDcID) + if err != nil { + logger.Warn("GetIdcByUuid sql error:", *param.IDcID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs("机房id不存在", "idcId not exist")) + } + } + //入库机型名称 + if param.Name != nil { + deviceTypeName, _ := deviceTypeDao.GetOneDeviceType(logger, map[string]interface{}{ + "name": *param.Name, + "is_del": baseLogic.IS_NOT_DEL, + }) + if deviceTypeName != nil && deviceTypeID != deviceTypeName.DeviceTypeID { + panic(constant.BuildInvalidArgumentWithArgs("机型名称已存在", "deviceType name exist")) + } + } + //入库机型规格 + if param.DeviceType != nil { + deviceType, _ := deviceTypeDao.GetOneDeviceType(logger, map[string]interface{}{ + "device_type": *param.DeviceType, + "is_del": baseLogic.IS_NOT_DEL, + }) + if deviceType != nil && deviceTypeID != deviceType.DeviceTypeID { + panic(constant.BuildInvalidArgumentWithArgs("机型规格已存在", "deviceType exist")) + } + } + + // + //if param.SystemVolumeType == nil || !util.InArray(*param.SystemVolumeType, []string{"SSD", "HDD"}) { + // panic(constant.BuildInvalidArgumentWithArgs("SystemVolumeType 不合法", "SystemVolumeType invalidate")) + //} + //if param.SystemVolumeInterfaceType == nil || !util.InArray(*param.SystemVolumeInterfaceType, []string{"SATA", "SAS", "NVME"}) { + // panic(constant.BuildInvalidArgumentWithArgs("SystemVolumeInterfaceType 不合法", "SystemVolumeInterfaceType invalidate")) + //} + //if param.DataVolumeType != nil && !util.InArray(*param.DataVolumeType, []string{"SSD", "HDD"}) { + // panic(constant.BuildInvalidArgumentWithArgs("DataVolumeType 不合法", "DataVolumeType invalidate")) + //} + //if param.DataVolumeInterfaceType != nil && !util.InArray(*param.DataVolumeInterfaceType, []string{"SATA", "SAS", "NVME"}) { + // panic(constant.BuildInvalidArgumentWithArgs("DataVolumeInterfaceType 不合法", "DataVolumeInterfaceType invalidate")) + //} + //var systemVolumeSize, dataVolumeSize int + //if param.SystemVolumeUnit != nil && *param.SystemVolumeUnit == "TB" { + // systemVolumeSize = *param.SystemVolumeSize * K + //} else { + // if param.SystemVolumeSize != nil { + // systemVolumeSize = *param.SystemVolumeSize + // } + //} + //if param.DataVolumeUnit != nil && *param.DataVolumeUnit == "TB" { + // dataVolumeSize = *param.DataVolumeSize * K + //} else { + // if param.DataVolumeSize != nil { + // dataVolumeSize = *param.DataVolumeSize + // } + //} + if param.IDcID != nil { + entity.IDcID = *param.IDcID + } + if param.DeviceType != nil { + entity.DeviceType = *param.DeviceType + } + if param.Name != nil { + entity.Name = *param.Name + } + if param.DeviceSeries != nil { + entity.DeviceSeries = *param.DeviceSeries + } + if param.Height != nil { + entity.Height = *param.Height + } + if param.Architecture != nil { + entity.Architecture = *param.Architecture + } + if param.Description != nil { + entity.Description = *param.Description + } + if param.CPUAmount != nil { + entity.CPUAmount = *param.CPUAmount + } + if param.CPUCores != nil { + entity.CPUCores = *param.CPUCores + } + if param.CPUFrequency != nil { + entity.CPUFrequency = *param.CPUFrequency + } + if param.CPUManufacturer != nil { + entity.CPUManufacturer = *param.CPUManufacturer + } + if param.CPUModel != nil { + entity.CPUModel = *param.CPUModel + } + if param.MemAmount != nil { + entity.MemAmount = *param.MemAmount + } + if param.MemSize != nil { + entity.MemSize = *param.MemSize + } + if param.MemFrequency != nil { + entity.MemFrequency = *param.MemFrequency + } + if param.MemType != nil { + entity.MemType = *param.MemType + } + if param.NicAmount != nil { + entity.NicAmount = *param.NicAmount + } + if param.NicRate != nil { + entity.NicRate = *param.NicRate + } + if param.InterfaceMode != nil { + entity.InterfaceMode = *param.InterfaceMode + } + if param.GpuAmount != nil { + entity.GpuAmount = *param.GpuAmount + } + if param.GpuManufacturer != nil { + entity.GpuManufacturer = *param.GpuManufacturer + } + if param.GpuModel != nil { + entity.GpuModel = *param.GpuModel + } + //if param.SystemVolumeType != nil { + // entity.SystemVolumeType = *param.SystemVolumeType + //} + //if param.SystemVolumeInterfaceType != nil { + // entity.SystemVolumeInterfaceType = *param.SystemVolumeInterfaceType + //} + //if param.SystemVolumeAmount != nil { + // entity.SystemVolumeAmount = *param.SystemVolumeAmount + //} + //if param.SystemVolumeSize != nil { + // entity.SystemVolumeSize = systemVolumeSize + //} + //if param.SystemVolumeUnit != nil { + // entity.SystemVolumeUnit = *param.SystemVolumeUnit + //} + + //if param.RaidCan != nil { + // entity.RaidCan = *param.RaidCan + //} + + //if param.DataVolumeType != nil { + // entity.DataVolumeType = *param.DataVolumeType + //} + //if param.DataVolumeInterfaceType != nil { + // entity.DataVolumeInterfaceType = *param.DataVolumeInterfaceType + //} + //if param.DataVolumeAmount != nil { + // entity.DataVolumeAmount = *param.DataVolumeAmount + //} + //if param.DataVolumeSize != nil { + // entity.DataVolumeSize = dataVolumeSize + //} + //if param.DataVolumeUnit != nil { + // entity.DataVolumeUnit = *param.DataVolumeUnit + //} + if param.CpuSpec != nil { + entity.CpuSpec = *param.CpuSpec + } + if param.MemSpec != nil { + entity.MemSpec = *param.MemSpec + } + if param.BootMode != "" { + entity.BootMode = param.BootMode + } + if param.IsNeedRaid != nil { + entity.IsNeedRaid = *param.IsNeedRaid + } + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + + if err := deviceTypeDao.UpdateDeviceTypeByDeviceTypeID(logger, entity, deviceTypeID); err != nil { + logger.Warnf("ModifyDeviceType UpdateDeviceTypeById sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) + return err + } + //接下来修改卷信息 + //先删掉之前的卷 + if err := volumeDao.UpdateVolumeByWhere(logger, map[string]interface{}{ + "device_type_id": deviceTypeID, + "is_del": baseLogic.IS_NOT_DEL, + }, &volumeDao.Volume{ + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + DeletedTime: int(time.Now().Unix()), + IsDel: baseLogic.IS_DEL, + }); err != nil { + logger.Warnf("del Volume error deviceTypeId:%s", entity.DeviceTypeID, err.Error()) + return err + } + //再删掉卷和raid的关联关系 + if err := rVolumeRaidDao.UpdateRVolumeRaidByWhere(logger, map[string]interface{}{ + "device_type_id": deviceTypeID, + "is_del": baseLogic.IS_NOT_DEL, + }, &rVolumeRaidDao.RVolumeRaid{ + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + DeletedTime: int(time.Now().Unix()), + IsDel: baseLogic.IS_DEL, + }); err != nil { + logger.Warnf("del Volume error deviceTypeId:%s", entity.DeviceTypeID, err.Error()) + return err + } + if err := modifyVolume(logger, entity.DeviceTypeID, param); err != nil { + logger.Warn("AddVolume error:", param.Volumes, err.Error()) + return err + } + //如果传了raidID + //if param.RaidID != nil { + // var systemVolumeType, systemVolumeInterfaceType, systemVolumeUnit string + // var systemVolumeAmount, systemVolumeSize int + // if param.SystemVolumeType != nil { + // systemVolumeType = *param.SystemVolumeType + // } else { + // systemVolumeType = entity.SystemVolumeType + // } + // if param.SystemVolumeInterfaceType != nil { + // systemVolumeInterfaceType = *param.SystemVolumeInterfaceType + // } else { + // systemVolumeInterfaceType = entity.SystemVolumeInterfaceType + // } + // if param.SystemVolumeUnit != nil { + // systemVolumeUnit = *param.SystemVolumeUnit + // } else { + // systemVolumeUnit = entity.SystemVolumeUnit + // } + // if param.SystemVolumeAmount != nil { + // systemVolumeAmount = *param.SystemVolumeAmount + // } else { + // systemVolumeAmount = entity.SystemVolumeAmount + // } + // if param.SystemVolumeSize != nil { + // systemVolumeSize = *param.SystemVolumeSize + // } else { + // systemVolumeSize = entity.SystemVolumeSize + // } + // if err := addDeviceTypeRaid(logger, deviceTypeID, *param.RaidID, systemVolumeUnit, systemVolumeType, systemVolumeInterfaceType, systemVolumeSize, systemVolumeAmount); err != nil { + // logger.Warn("AddDeviceTypeRaid sql error:", deviceTypeID, err.Error()) + // return err + // } + //} + //如果不传raidId,就不做修改 + //修改device表的device_series + if param.DeviceSeries != nil { + if err := deviceLogic.ModifyDeviceByWhere(logger, "device_series", *param.DeviceSeries, deviceTypeID); err != nil { + return err + } + } + return nil +} +func DeleteDeviceType(logger *log.Logger, deviceTypeID string) error { + entity, err := deviceTypeDao.GetOneDeviceType(logger, map[string]interface{}{ + "device_type_id": deviceTypeID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Warn("GetDeviceTypeByUuid sql error:", deviceTypeID, err.Error()) + return err + } + device, err := deviceDao.GetAllDevice(logger, map[string]interface{}{ + "device_type_id": deviceTypeID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if len(device) != 0 { + panic(constant.BuildInvalidArgumentWithArgs("机型下面还有设备,不能删除", "It has some devices in the deviceType,please delete device first")) + } + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + entity.DeletedTime = int(time.Now().Unix()) + entity.IsDel = baseLogic.IS_DEL + + if err := deviceTypeDao.UpdateDeviceTypeByDeviceTypeID(logger, entity, deviceTypeID); err != nil { + logger.Warnf("DeleteDeviceType sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) + return err + } + //rDeviceTypeRaid, err := rDeviceTypeRaidDao.GetOneRDeviceTypeRaid(logger, map[string]interface{}{ + // "device_type_id": deviceTypeID, + // "is_del": baseLogic.IS_NOT_DEL, + //}) + //if rDeviceTypeRaid != nil { //如果机型和raid关联关系存在,那么删除机型的同时,把和raid的关系也一起删掉 + // if err := rDeviceTypeRaidDao.UpdateRDeviceTypeRaidByWhere(logger, map[string]interface{}{ + // "device_type_id": deviceTypeID, + // "is_del": baseLogic.IS_NOT_DEL, + // }, &rDeviceTypeRaidDao.RDeviceTypeRaid{ + // UpdatedBy: logger.GetPoint("username").(string), + // UpdatedTime: int(time.Now().Unix()), + // DeletedTime: int(time.Now().Unix()), + // IsDel: baseLogic.IS_DEL, + // }); err != nil { + // logger.Warnf("del rdeviceTypeRaid error deviceTypeId:%s", entity.DeviceTypeID, err.Error()) + // return err + // } + //} + //删除机型镜像的绑定关系 + rDeviceTypeImage, err := rDeviceTypeImageDao.GetOneRDeviceTypeImage(logger, map[string]interface{}{ + "device_type_id": deviceTypeID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if rDeviceTypeImage != nil { + if err := rDeviceTypeImageDao.UpdateMultiRDeviceTypeImage(logger, map[string]interface{}{ + "device_type_id": deviceTypeID, + "is_del": baseLogic.IS_NOT_DEL, + }, map[string]interface{}{ + "is_del": baseLogic.IS_DEL, + "deleted_time": int(time.Now().Unix()), + }); err != nil { + return err + } + } + + return nil +} +func DeviceTypeEntity2DeviceType(logger *log.Logger, entity *deviceTypeDao.DeviceType) *responseTypes.DeviceType { + language := logger.GetPoint("language").(string) + tz := logger.GetPoint("timezone").(string) + //deviceTypeRaid, err := rDeviceTypeRaidDao.GetAllRDeviceTypeRaid(logger, map[string]interface{}{ + // "device_type_id": entity.DeviceTypeID, + // "is_del": 0, + //}) + //if err != nil { + // panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + //} + //raid := "" + //if len(deviceTypeRaid) != 0 { + // for _, v := range deviceTypeRaid { + // raid = raid + v.RaidID + "," + // } + // raid = strings.TrimRight(raid, ",") + //} + ////计算raid对应map中的Name + //array := []string{} // 拆分查询 + //deviceTypeRaidName := "" + ////获取raid的信息 + //raidMap := make(map[string]responseTypes.Raid) // 请求一次,避免循环请求 + //raidList, raidsErr := raidLogic.QueryRaidsAll(logger) + //if raidsErr == nil && len(raidList) != 0 { + // for _, vv := range raidList { + // raidMap[vv.RaidID] = *vv + // } + //} + //if len(raidList) != 0 { + // array = strings.Split(raid, ",") + //} + //if len(array) != 0 { + // raid_ := "" + // for _, str := range array { + // raid_ = raid_ + raidMap[str].Name + "," // RAID0,RAID1 + // } + // deviceTypeRaidName = raid_[0 : len(raid_)-1] + //} + info := deviceLogic.GetDeviceTypeInfo(logger, entity) + + deviceSeries := baseLogic.DeviceTypeSeries[entity.DeviceSeries] + if language == baseLogic.EN_US { + deviceSeries = baseLogic.DeviceTypeSeriesEn[entity.DeviceSeries] + } + idc, err := idcDao.GetIdcById(logger, entity.IDcID) //获取机房信息 + if err != nil { + idc = &idcDao.Idc{} + } + idcName := idc.Name + if language == baseLogic.EN_US { + idcName = idc.NameEn + } + //var systemVolumeSize, dataVolumeSize int + //if entity.SystemVolumeUnit == "TB" { + // systemVolumeSize = entity.SystemVolumeSize / K + //} else { + // systemVolumeSize = entity.SystemVolumeSize + //} + //if entity.DataVolumeUnit == "TB" { + // dataVolumeSize = entity.DataVolumeSize / K + //} else { + // dataVolumeSize = entity.DataVolumeSize + //} + instance, _ := instanceDao.GetAllInstance(logger, map[string]interface{}{ + "device_type_id": entity.DeviceTypeID, + }) + device, _ := deviceDao.GetAllDevice(logger, map[string]interface{}{ + "device_type_id": entity.DeviceTypeID, + }) + volumeList, _ := volumeDao.GetAllVolume(logger, map[string]interface{}{ + "device_type_id": entity.DeviceTypeID, + }) + volumeArr := []responseTypes.Volume{} + for _, v := range volumeList { + volume := responseTypes.Volume{} + volume.VolumeID = v.VolumeID + volume.VolumeName = v.VolumeName + volume.VolumeType = v.VolumeType + volume.DiskType = v.DiskType + volume.VolumeSize = v.VolumeSize + volume.VolumeUnit = v.VolumeUnit + volume.VolumeAmount = v.VolumeAmount + volume.InterfaceType = v.InterfaceType + + rVolumeRaid, _ := rVolumeRaidDao.GetAllRVolumeRaid(logger, map[string]interface{}{ + "volume_id": v.VolumeID, + "is_del": 0, + //"device_type_id": entity.DeviceTypeID, + }) + raidStr := "" + raidIdStr := "" + raidCan := "" + if len(rVolumeRaid) > 0 { + for _, value := range rVolumeRaid { + raidStr = raidStr + value.RaidName + "," + raidIdStr = raidIdStr + value.RaidID + "," + } + raidCan = rVolumeRaid[0].RaidCan + } + volume.RaidCan = raidCan + volume.Raid = strings.Trim(raidStr, ",") + volume.RaidId = strings.Trim(raidIdStr, ",") + volumeArr = append(volumeArr, volume) + + } + return &responseTypes.DeviceType{ + ID: entity.ID, + IDcID: entity.IDcID, + IDcName: idcName, + IDcNameEn: idc.NameEn, + DeviceType: entity.DeviceType, + DeviceTypeID: entity.DeviceTypeID, + Name: entity.Name, + Description: entity.Description, + DeviceSeries: entity.DeviceSeries, + DeviceSeriesName: deviceSeries, + Architecture: entity.Architecture, + Height: entity.Height, + CPUAmount: entity.CPUAmount, + CPUCores: entity.CPUCores, + CPUFrequency: entity.CPUFrequency, + CPUManufacturer: entity.CPUManufacturer, + CPUModel: entity.CPUModel, + + MemType: entity.MemType, + MemAmount: entity.MemAmount, + MemSize: entity.MemSize, + MemFrequency: entity.MemFrequency, + NicAmount: entity.NicAmount, + NicRate: entity.NicRate, + InterfaceMode: entity.InterfaceMode, + //SystemVolumeType: entity.SystemVolumeType, + //SystemVolumeInterfaceType: entity.SystemVolumeInterfaceType, + //SystemVolumeAmount: entity.SystemVolumeAmount, + //RaidCan: entity.RaidCan, + //SystemVolumeSize: systemVolumeSize, + //SystemVolumeUnit: entity.SystemVolumeUnit, + //DataVolumeType: entity.DataVolumeType, + //DataVolumeInterfaceType: entity.DataVolumeInterfaceType, + //DataVolumeAmount: entity.DataVolumeAmount, + //DataVolumeSize: dataVolumeSize, + //DataVolumeUnit: entity.DataVolumeUnit, + GpuAmount: entity.GpuAmount, + GpuManufacturer: entity.GpuManufacturer, + GpuModel: entity.GpuModel, + CreatedTime: util.TimestampToString(int64(entity.CreatedTime), tz), + UpdatedTime: util.TimestampToString(int64(entity.UpdatedTime), tz), + CreatedBy: entity.CreatedBy, + UpdatedBy: entity.UpdatedBy, + //Raid: strings.Trim(raid, ","), + CpuSpec: entity.CpuSpec, + MemSpec: entity.MemSpec, + BootMode: entity.BootMode, + + //拼装信息 + CpuInfo: info["cpu_"], + MemInfo: info["mem_"], + //SvInfo: info["sv_"], + //DvInfo: info["dv_"], + GpuInfo: info["gpu_"], + NicInfo: info["nic_"], + InstanceCount: len(instance), + DeviceCount: len(device), + IsNeedRaid: entity.IsNeedRaid, + Volumes: volumeArr, + } +} + +func AssociatedImage(logger *log.Logger, param *requestTypes.AssociateImageRequest) error { + toInsert := []*rDeviceTypeImageDao.RDeviceTypeImage{} + toUpdate := []*rDeviceTypeImageDao.RDeviceTypeImage{} + toDelete := []*rDeviceTypeImageDao.RDeviceTypeImage{} + deviceTypeID := param.DeviceTypeID + deviceType, err := deviceTypeDao.GetDeviceTypeById(logger, deviceTypeID) + if err != nil { + logger.Warnf("QueryDeviceType sql err, param:%s, error:%s", util.ObjToJson(param), err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + all, _ := rDeviceTypeImageDao.GetByDeviceTypeID(logger, deviceTypeID) + for _, v := range all { + if !util.InArray(v.ImageID, param.ImageIDs) { + //如果数据库中的记录不在参数中,说明是要被删除的 + entity := &rDeviceTypeImageDao.RDeviceTypeImage{ + DeviceTypeID: deviceTypeID, + ImageID: v.ImageID, + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + DeletedTime: int(time.Now().Unix()), + IsDel: baseLogic.IS_DEL, + } + toDelete = append(toDelete, entity) + } + //否则就是在数组中,走下面逻辑 + } + for _, imageID := range param.ImageIDs { + //fmt.Println(deviceTypeID, imageID) + image, err := imageDao.GetImageByUuid(logger, imageID) + if err != nil { + logger.Warnf("镜像不存在,机型id:%s,镜像id:%s,error:%s", deviceTypeID, imageID, err.Error()) + return err + } + os, err := osDao.GetOsByUuid(logger, image.OsID) + if err != nil { + logger.Warnf("OS不存在,机型id:%s,OS id:%s,error:%s", deviceTypeID, image.OsID, err.Error()) + return err + } + if deviceType.Architecture != os.Architecture { + panic(constant.BuildInvalidArgumentWithArgs("机型和镜像体系架构不匹配", "architecture not match")) + } + _, err = rDeviceTypeImageDao.GetByDeviceTypeIDAndImageID(logger, deviceTypeID, imageID) + if err != nil { + logger.Warn("AssociatedImage GetByDeviceTypeIDAndImageID sql err:", deviceTypeID, imageID, err.Error()) + entity := &rDeviceTypeImageDao.RDeviceTypeImage{ + DeviceTypeID: deviceTypeID, + ImageID: imageID, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + } + toInsert = append(toInsert, entity) + } else { + entity := &rDeviceTypeImageDao.RDeviceTypeImage{ + DeviceTypeID: deviceTypeID, + ImageID: imageID, + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + toUpdate = append(toUpdate, entity) + } + + //先将已有的机型和镜像分区关系删除,然后再新增 + err = rDeviceTypeImagePartitionDao.UpdateMultiRDeviceTypeImagePartition(logger, map[string]interface{}{ + "image_id": imageID, + "device_type_id": deviceTypeID, + "is_del": 0, + }, map[string]interface{}{ + "updated_by": logger.GetPoint("username").(string), + "updated_time": int(time.Now().Unix()), + "deleted_time": int(time.Now().Unix()), + "is_del": baseLogic.IS_DEL, + }) + if err != nil { + logger.Warnf("删除机型镜像分区表关系错误,机型id:%s,镜像id:%s,error:%s", deviceTypeID, imageID, err.Error()) + return err + } + + //“/ ” :50GiB,xfs;swap:10GiB,swap + //partition := image.SystemPartition //标准版只支持系统盘默认分区,数据盘在专业版才有,先预留 + //if json.Unmarshal([]byte(image.SystemPartition),&Partition) + var partitionsObj = []requestTypes.Partition{} //注意,这里前端给的参数默认的是json字符串,创建实例那边默认是数组 + if image.SystemPartition != "" { + if err := json.Unmarshal([]byte(image.SystemPartition), &partitionsObj); err != nil { + return err + } + } + for i := 0; i < len(partitionsObj); i++ { //数组的结构体partitionObj,不能用range遍历?? + _, err = rDeviceTypeImagePartitionDao.AddRDeviceTypeImagePartition(logger, &rDeviceTypeImagePartitionDao.RDeviceTypeImagePartition{ + ImageID: imageID, + DeviceTypeID: deviceTypeID, + BootMode: deviceType.BootMode, + PartitionType: baseLogic.PartitionType[partitionsObj[i].MountPoint], + PartitionSize: partitionsObj[i].Size, + PartitionFsType: partitionsObj[i].FsType, + PartitionLabel: baseLogic.PartitionLabel[partitionsObj[i].MountPoint], + PartitionMountPoint: partitionsObj[i].MountPoint, + SystemDiskLabel: baseLogic.SystemDiskLabel[partitionsObj[i].MountPoint], + DataDiskLabel: baseLogic.DataDiskLabel[partitionsObj[i].MountPoint], + + CreatedBy: logger.GetPoint("username").(string), + UpdatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + }) + if err != nil { + logger.Warnf("添加机型镜像分区表关系错误,机型id:%s,镜像id:%s,error:%s", deviceTypeID, imageID, err.Error()) + return err + } + } + } + //fmt.Println(util.ObjToJson(toInsert), util.ObjToJson(toUpdate), util.ObjToJson(toDelete)) + if len(all)+len(toInsert) > 20 { + logger.Warnf("AssociatedImage all amount %d,inset amount:%d", len(all), len(toInsert)) + panic(constant.BuildInvalidArgumentWithArgs("关联镜像不能超过20个", "AssociatedImage amount can't exceed 20")) + } + if len(toInsert) > 0 { + if _, err := rDeviceTypeImageDao.AddMultiRDeviceTypeImage(logger, toInsert); err != nil { + logger.Warn("AssociatedImage AddMultiRDeviceTypeImage sql err:", err.Error()) + return err + } + } + if len(toUpdate) > 0 { + if err := rDeviceTypeImageDao.AssociatedImageMultiRDeviceTypeImage(logger, toUpdate); err != nil { + logger.Warn("AssociatedImage AssociatedImageMultiRDeviceTypeImage sql err:", err.Error()) + return err + } + } + // 如果需要将原来的删掉,执行以下代码,现在和前端约定,前端给什么,之前已经选中了的,不做处理! + //if len(toDelete) > 0 { + // if err := rDeviceTypeImageDao.AssociatedImageMultiRDeviceTypeImage(logger, toDelete); err != nil { + // logger.Warn("AssociatedImage AssociatedImageMultiRDeviceTypeImage sql err:", err.Error()) + // return err + // } + //} + //绑定镜像分区,入库关联表 + return nil +} + +func DissociatedImage(logger *log.Logger, param *requestTypes.DissociatedImageRequest, isDelDeviceType bool) error { + if isDelDeviceType { //如果是镜像删除机型,需要增加一个额外的判断,判断机型下面所有的实例,没有创建中的,如果有,不允许删除 + instanceList, _ := instanceDao.GetAllInstance(logger, map[string]interface{}{ + "device_type_id": param.DeviceTypeID, + "image_id": param.ImageID, + }) + for _, v := range instanceList { + if v.Status == baseLogic.CREATING { + panic(constant.BuildInvalidArgumentWithArgs("机型下面存在创建中的实例,不允许移除", "instance status exist creating")) + } + } + } + _, err := rDeviceTypeImageDao.GetByDeviceTypeIDAndImageID(logger, param.DeviceTypeID, param.ImageID) + if err != nil { + logger.Warn("DissociatedImage GetByDeviceTypeAndImageId sql err:", param.DeviceTypeID, param.ImageID, err.Error()) + return err + } + entity := &rDeviceTypeImageDao.RDeviceTypeImage{ + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + DeletedTime: int(time.Now().Unix()), + IsDel: baseLogic.IS_DEL, + } + if err := rDeviceTypeImageDao.UpdateRDeviceTypeImageById(logger, entity, param.DeviceTypeID, param.ImageID); err != nil { + logger.Warn("DissociatedImage UpdateRDeviceTypeImageById sql error:", param.DeviceTypeID, param.ImageID, err.Error()) + return err + } + err = rDeviceTypeImagePartitionDao.UpdateMultiRDeviceTypeImagePartition(logger, map[string]interface{}{ + "image_id": param.ImageID, + "device_type_id": param.DeviceTypeID, + "is_del": 0, + }, map[string]interface{}{ + "updated_by": logger.GetPoint("username").(string), + "updated_time": int(time.Now().Unix()), + "deleted_time": int(time.Now().Unix()), + "is_del": baseLogic.IS_DEL, + }) + if err != nil { + logger.Warnf("删除机型镜像分区表关系错误,机型id:%s,镜像id:%s,error:%s", param.DeviceTypeID, param.ImageID, err.Error()) + return err + } + return nil +} +func QueryDeviceTypeImage(logger *log.Logger, param *requestTypes.QueryDeviceTypeImageRequest, p util.Pageable) ([]*responseTypes.Image, int64, error) { + tz := logger.GetPoint("timezone").(string) + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "image_id": param.ImageID, + "device_type_id": param.DeviceTypeID, + "image_name": param.ImageName, + "version": param.Version, + "os_id": param.OsID, + //"image_ids": strings.Join(param.ImageIds, ","), + "source": param.Source, + "architecture": param.Architecture, + "os_type": param.OsType, + "is_del": baseLogic.IS_NOT_DEL, + } + //queryList := query + //query["count"] = true + _, count, err := rDeviceTypeImageDao.GetDeviceTypeImageAndOsList(logger, query, true, 0, 0) + //os.Exit(1) + if err != nil { + logger.Warnf("DescribeDeviceTypes_GetDeviceTypeCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*imageDao.DImage{} + if param.IsAll == baseLogic.IS_ALL { + //entityList, err = imageDao.GetMultiImage(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + fmt.Println("获取全部", query) + entityList, _, err = rDeviceTypeImageDao.GetDeviceTypeImageAndOsList(logger, query, false, 0, 0) + } else { + //entityList, err = imageDao.GetMultiImage(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + entityList, _, err = rDeviceTypeImageDao.GetDeviceTypeImageAndOsList(logger, query, false, offset, limit) + } + if err != nil { + logger.Warn("imageDao.QueryByDeviceOsType sql error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + images := []*responseTypes.Image{} + for _, image := range entityList { + isBind := false + if param.DeviceTypeID != "" { + deviceTypeImageNum, _ := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, map[string]interface{}{ + "image_id": image.ImageID, + "device_type_id": param.DeviceTypeID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if deviceTypeImageNum != 0 { + isBind = true + } + } + //fmt.Println(util.InterfaceToJson(image), image.ImageID, image.CreatedTime) + //os, err := osLogic.GetByOsId(logger, image.OsID) + //if err != nil && os == nil { + // os = &responseTypes.Os{} //如果没有找到os,默认为空 + //} + deviceTypeNum, err := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, map[string]interface{}{ + "image_id": image.ImageID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Warn("获取镜像对应的机型个数错误", image.OsID, err.Error()) + return nil, 0, err + } + images = append(images, imageLogic.ImageEntityWithOs2Image(logger, image, int(deviceTypeNum), isBind, tz)) + } + return images, count, nil +} + +//func QueryDeviceTypeImage(logger *log.Logger, param *requestTypes.QueryDeviceTypeImageRequest) ([]*responseTypes.Image, error) { +// //offset, limit := p.Pageable2offset() +// query := map[string]interface{}{ +// "device_type_id": param.DeviceTypeID, +// "image_id": param.ImageID, +// "is_del": 0, +// } +// rDeviceTypeImage, err := rDeviceTypeImageDao.GetMultiRDeviceTypeImage(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 1000) +// if err != nil { +// logger.Warnf("DescribeDeviceTypes_GetDeviceTypeCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) +// return nil, err +// } +// images := []*responseTypes.Image{} +// for _, value := range rDeviceTypeImage { +// image, err := imageLogic.GetByImageId(logger, value.ImageID) +// if err != nil { +// logger.Warnf("GetImageById error, imageId:%s, error:%s", value.ImageID, err.Error()) +// return nil, err +// } +// if param.Architecture != "" && param.OsType != "" { +// arr := strings.Split(param.Architecture, ",") +// arr1 := strings.Split(param.OsType, ",") +// if util.InArray(image.Architecture, arr) && util.InArray(image.OsType, arr1) { +// images = append(images, image) +// } else { +// continue +// } +// } +// if param.Architecture != "" && param.OsType == "" { +// arr := strings.Split(param.Architecture, ",") +// if !util.InArray(image.Architecture, arr) { +// continue +// } else { +// images = append(images, image) +// } +// } +// if param.Architecture == "" && param.OsType != "" { +// arr := strings.Split(param.OsType, ",") +// if !util.InArray(image.OsType, arr) { +// continue +// } else { +// images = append(images, image) +// } +// } +// if param.Architecture == "" && param.OsType == "" { +// images = append(images, image) +// } +// +// } +// return images, err +//} +//func QueryDeviceTypeRaid(logger *log.Logger, param *requestTypes.QueryDeviceTypeRaidRequest) ([]*responseTypes.RDeviceTypeRaid, error) { +// //offset, limit := p.Pageable2offset() +// tz := logger.GetPoint("timezone").(string) +// query := map[string]interface{}{ +// "device_type_id": param.DeviceTypeID, +// "volume_type": param.VolumeType, +// "raid_id": param.RaidID, +// "is_del": 0, +// } +// rDeviceTypeRaid, err := rDeviceTypeRaidDao.GetAllRDeviceTypeRaid(logger, query) +// if err != nil { +// logger.Warnf("DescribeDeviceTypes_GetDeviceTypeCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) +// return nil, err +// } +// raid := &responseTypes.RDeviceTypeRaid{} +// raids := []*responseTypes.RDeviceTypeRaid{} +// for _, value := range rDeviceTypeRaid { +// raid = RDeviceTypeRaidEntityToRDeviceTypeRaid(value, tz) +// raids = append(raids, raid) +// } +// return raids, err +//} + +//表实例转为返回 +//func RDeviceTypeRaidEntityToRDeviceTypeRaid(entity *rDeviceTypeRaidDao.RDeviceTypeRaid, tz string) *responseTypes.RDeviceTypeRaid { +// return &responseTypes.RDeviceTypeRaid{ +// ID: entity.ID, +// RaidID: entity.RaidID, +// DeviceTypeID: entity.DeviceTypeID, +// VolumeType: entity.VolumeType, +// VolumeDetail: entity.VolumeDetail, +// AvailableValue: entity.AvailableValue, +// SystemPartitionCount: entity.SystemPartitionCount, +// DiskType: entity.DiskType, +// DiskInterfaceType: entity.DiskInterfaceType, +// CreatedBy: entity.CreatedBy, +// UpdatedBy: entity.UpdatedBy, +// CreatedTime: util.TimestampToString(int64(entity.CreatedTime), tz), +// UpdatedTime: util.TimestampToString(int64(entity.UpdatedTime), tz), +// } +//} +func QueryDeviceTypeImagePartition(logger *log.Logger, param *requestTypes.QueryDeviceTypeImagePartitionRequest) (*responseTypes.QueryDeviceTypeImagePartitionResponse, error) { + entities, err := rDeviceTypeImagePartitionDao.GetByDeviceTypeAndImageId(logger, param.DeviceTypeID, param.ImageID) + if err != nil { + logger.Warnf("GetByDeviceTypeAndImageId error:", param.DeviceTypeID, param.ImageID) + return nil, err + } + res := &responseTypes.QueryDeviceTypeImagePartitionResponse{ + SystemPartition: []responseTypes.Partition{}, + DataPartition: []responseTypes.Partition{}, + } + for _, entity := range entities { + if strings.EqualFold("data", entity.PartitionType) { + res.DataPartition = append(res.DataPartition, responseTypes.Partition{ + Size: entity.PartitionSize, + FsType: entity.PartitionFsType, + MountPoint: entity.PartitionMountPoint, + //Label: entity.PartitionLabel, + }) + } else { + res.SystemPartition = append(res.SystemPartition, responseTypes.Partition{ + Size: entity.PartitionSize, + FsType: entity.PartitionFsType, + MountPoint: entity.PartitionMountPoint, + //Label: entity.PartitionLabel, + }) + } + } + + return res, nil + +} +func Trim(str string) string { + s := strings.TrimRight(str, "0") + s = strings.TrimRight(s, ".") + return s +} + +func DescribeVolumesByDeviceType(logger *log.Logger, param *requestTypes.DescribeVolumesByDeviceTypeRequest) ([]*responseTypes.VolumeIt, error) { + + volumes := []*responseTypes.VolumeIt{} + q1 := map[string]interface{}{ + "is_del": 0, + "device_type_id": param.DeviceTypeID, + } + volumeEntities, err := volumeDao.GetAllVolume(logger, q1) + if err != nil { + logger.Warnf("DescribeVolumesByDeviceType.GetAllVolume error, device_type_id:%s, error:%s", param.DeviceTypeID, err.Error()) + } + volume := responseTypes.Volume{} + for _, v := range volumeEntities { + volume.VolumeID = v.VolumeID + volume.VolumeName = v.VolumeName + volume.VolumeType = v.VolumeType + volume.VolumeSize = v.VolumeSize + volume.VolumeUnit = v.VolumeUnit + + volume.VolumeAmount = v.VolumeAmount + volume.DiskType = v.DiskType + volume.InterfaceType = v.InterfaceType + + volumeId := v.VolumeID + q2 := map[string]interface{}{ + "is_del": 0, + "volume_id": v.VolumeID, + } + volumnRaidEntities, err := rVolumeRaidDao.GetAllRVolumeRaid(logger, q2) + if err != nil { + logger.Warnf("DescribeVolumesByDeviceType.GetVolumeById error, volume_id:%s, error:%s", volumeId, err.Error()) + } + volume.RaidCan = volumnRaidEntities[0].RaidCan + raids := []*raidDao.Raid{} + for _, v2 := range volumnRaidEntities { + raids = append(raids, &raidDao.Raid{ + RaidID: v2.RaidID, + Name: v2.RaidName, + }) + } + + // diskEntities, err := diskDao.GetDiskWithVolumeId(logger, volumeId) + // if err != nil { + // logger.Warnf("DescribeVolumesByDeviceType.GetVolumeById error, volume_id:%s, error:%s", volumeId, err.Error()) + // } + + vt := &responseTypes.VolumeIt{ + Volume: volume, + Raids: raids, + Disks: []*diskDao.Disk{}, //给前端一个空[] + } + volumes = append(volumes, vt) + } + return volumes, nil + +} diff --git a/bmp-openapi/logic/diskLogic/diskLogic.go b/bmp-openapi/logic/diskLogic/diskLogic.go new file mode 100644 index 0000000..0e3e3c6 --- /dev/null +++ b/bmp-openapi/logic/diskLogic/diskLogic.go @@ -0,0 +1,118 @@ +package diskLogic + +//func OsEntity2OS(o *osDao.Os) *responseTypes.OS { +// return &responseTypes.OS{ +// ID: o.ID, +// OsID: o.OsID, +// OsName: o.OsName, +// OsType: o.OsType, +// OsVersion: o.OsVersion, +// Platform: o.Platform, +// Architecture: o.Architecture, +// Bits: o.Bits, +// CreatedTime: util.TimestampToUtc(int64(o.CreatedTime)), +// } +//} +// +//func GetByOsId(logger *log.Logger, osId string) (*responseTypes.OS, error) { +// entity, err := osDao.GetOsByUuid(logger, osId) +// if err != nil { +// logger.Warn("GetOsByUuid sql error:", osId, err.Error()) +// return nil, err +// } +// return OsEntity2OS(entity), nil +//} +//func GetOsByUuid(logger *log.Logger, osid string) (o *osDao.Os, err error) { +// entity, err := osDao.GetOsByUuid(logger, osid) +// return entity, err +//} +// +//func GetAndCheckById(logger *log.Logger, os_id string) (*responseTypes.OS, error) { +// os, err := GetByOsId(logger, os_id) +// if err != nil { +// return nil, err +// } +// return os, nil +// +//} +// +//func CreateDisk(logger *log.Logger, param *requestTypes.CreateD) (string, error) { +// os_entity := &osDao.Os{ +// OsName: param.OsName, +// OsType: param.OsType, +// Platform: param.Platform, +// Architecture: param.Architecture, +// Bits: param.Bits, +// OsVersion: param.OsVersion, +// SysUser: param.SysUser, +// CreatedBy: logger.GetPoint("username").(string), +// CreatedTime: int(time.Now().Unix()), +// } +// os_entity.OsID = commonUtil.GetRandString(namespacePrefix.IMAGE_ID_PREFIX, namespacePrefix.INSTANCE_ID_LENGTH, false, true, true) +// if _, err := osDao.AddOs(logger, os_entity); err != nil { +// logger.Warnf("CreateOs AddOs sql error, entity:%s, error:%s", util.ObjToJson(os_entity), err.Error()) +// return "", err +// } +// return os_entity.OsID, nil +//} +// +//func ModifyOS(logger *log.Logger, param *requestTypes.ModifyOSRequest, osId string) error { +// +// entity, err := osDao.GetOsByUuid(logger, osId) +// if err != nil { +// logger.Warn("GetOsByUuid sql error:", osId, err.Error()) +// return err +// } +// +// entity.OsName = param.OsName +// entity.OsType = param.OsType +// entity.Platform = param.Platform +// entity.Architecture = param.Architecture +// entity.Bits = param.Bits +// entity.OsVersion = param.OsVersion +// entity.SysUser = param.SysUser +// entity.UpdatedBy = logger.GetPoint("username").(string) +// entity.UpdatedTime = int(time.Now().Unix()) +// if err := osDao.UpdateOsById(logger, entity); err != nil { +// logger.Warn("ModifyOS UpdateOsById sql error:", osId, err.Error()) +// return err +// } +// return nil +//} +// +//func DeleteOS(logger *log.Logger, osId string) error { +// entity, err := osDao.GetOsByUuid(logger, osId) +// if err != nil { +// logger.Warn("GetOsByUuid sql error:", osId, err.Error()) +// return err +// } +// entity.IsDel = 1 +// entity.UpdatedTime = int(time.Now().Unix()) +// entity.DeletedTime = int(time.Now().Unix()) +// if err := osDao.UpdateOsById(logger, entity); err != nil { +// logger.Warn("DeleteOS UpdateOsById sql error:", osId, err.Error()) +// return err +// } +// return nil +//} +// +//func DescribeOSs(logger *log.Logger, param *requestTypes.QueryOssRequest) ([]*responseTypes.OS, error) { +// +// query := map[string]interface{}{ +// "os_name": param.OsName, +// "os_type": param.OsType, +// "os_version": param.OsVersion, +// "platform": param.Platform, +// "is_del": 0, +// } +// os_entity_list, err := osDao.GetMultiOs(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 1000) +// if err != nil { +// logger.Warn("QueryByOsIds GetAllOs sql error:", err.Error()) +// return nil, err +// } +// oss := []*responseTypes.OS{} +// for _, entity := range os_entity_list { +// oss = append(oss, OsEntity2OS(entity)) +// } +// return oss, nil +//} diff --git a/bmp-openapi/logic/idcLogic/idcLogic.go b/bmp-openapi/logic/idcLogic/idcLogic.go new file mode 100644 index 0000000..2cd3f25 --- /dev/null +++ b/bmp-openapi/logic/idcLogic/idcLogic.go @@ -0,0 +1,232 @@ +package idcLogic + +import ( + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func GetOneIdc(logger *log.Logger) (*responseTypes.Idc, error) { + + var tz string + if logger.GetPoint("timezone") == nil { + tz = "Asia/Shanghai" + } else { + tz = logger.GetPoint("timezone").(string) + } + query := map[string]interface{}{ + "is_del": 0, + } + idc, err := idcDao.GetOneIdc(logger, query) + if err != nil { + return nil, err + } + return IdcEntity2Idc(logger, idc, tz), nil +} + +func QueryIdcs(logger *log.Logger, param *requestTypes.QueryIdcsRequest, p util.Pageable) ([]*responseTypes.Idc, int64, error) { + tz := logger.GetPoint("timezone").(string) + offset, limit := p.Pageable2offset() + //tenant := logger.GetPoint("tenant").(string) + //region := logger.GetPoint("region").(string) + //az := logger.GetPoint("az").(string) + //name := param.IdcNo + query := map[string]interface{}{ + "is_del": 0, + } + //if tenant != "" { + // query["tenant"] = tenant + //} + count, err := idcDao.GetIdcCount(logger, query) + if err != nil { + logger.Warnf("DescribeIdcs_GetIdcCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*idcDao.Idc{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = idcDao.GetMultiIdc(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = idcDao.GetMultiIdc(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warnf("DescribeIdcs_QueryByParam error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + Idcs := []*responseTypes.Idc{} + for _, entity := range entityList { + Idcs = append(Idcs, IdcEntity2Idc(logger, entity, tz)) + } + return Idcs, count, nil +} + +func IdcEntity2Idc(logger *log.Logger, k *idcDao.Idc, tz string) *responseTypes.Idc { + v := &responseTypes.Idc{ + ID: k.ID, + IDcID: k.IDcID, + Name: k.Name, + NameEn: k.NameEn, + Shortname: k.Shortname, + Level: k.Level, + Address: k.Address, + IloUser: k.IloUser, + IloPassword: k.IloPassword, + SwitchUser1: k.SwitchUser1, + SwitchPassword1: k.SwitchPassword1, + SwitchUser2: k.SwitchUser2, + SwitchPassword2: k.SwitchPassword2, + CreateTime: util.TimestampToString(int64(k.CreatedTime), tz), + UpdateTime: util.TimestampToString(int64(k.UpdatedTime), tz), + CreatedBy: k.CreatedBy, + UpdatedBy: k.UpdatedBy, + } + //if logger.GetPoint("language").(string) == baseLogic.EN_US { + // v.Name = k.NameEn + //} + return v +} +func CreateIdc(logger *log.Logger, param *requestTypes.CreateIdcRequest) (string, error) { + + //a, b := util.AesCBCEncrypt([]byte("hello"), []byte("mykeydsssdsdssds")) + //fmt.Println(a, string(a), "err:", b) + // + //c, d := util.AesCBCDecrypt(a, []byte("mykeydsssdsdssds")) + //fmt.Println(c, string(c), "err:", d) + + if idc, _ := idcDao.GetOneIdc(logger, map[string]interface{}{ + "name": param.Name, + "is_del": baseLogic.IS_NOT_DEL, + }); idc != nil { + panic(constant.BuildInvalidArgumentWithArgs("机房名称已存在", "idcName exist")) + } + if idc, _ := idcDao.GetOneIdc(logger, map[string]interface{}{ + "name_en": param.NameEn, + "is_del": baseLogic.IS_NOT_DEL, + }); idc != nil { + panic(constant.BuildInvalidArgumentWithArgs("机房英文名称已存在", "idcNameEn exist")) + } + + entity := &idcDao.Idc{ + IDcID: util.GetUuid("idc-"), + Name: param.Name, + NameEn: param.NameEn, + Shortname: param.Shortname, + Level: param.Level, + Address: param.Address, + IloUser: param.IloUser, + IloPassword: param.IloPassword, + SwitchUser1: param.SwitchUser1, + SwitchPassword1: param.SwitchPassword1, + SwitchUser2: param.SwitchUser2, + SwitchPassword2: param.SwitchPassword2, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + _, err := idcDao.CreateIdc(logger, entity) + if err != nil { + logger.Warnf("CreateIdc AddIdc sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) + return "", err + } + return entity.IDcID, nil + +} +func ModifyIdc(logger *log.Logger, param *requestTypes.ModifyIdcRequest, idcId string) error { + + if idc, _ := idcDao.GetOneIdc(logger, map[string]interface{}{ + "name": param.Name, + "is_del": baseLogic.IS_NOT_DEL, + }); idc != nil && idc.IDcID != idcId && *param.Name != "" { + panic(constant.BuildInvalidArgumentWithArgs("机房名称已存在", "idcName exist")) + } + if idc, _ := idcDao.GetOneIdc(logger, map[string]interface{}{ + "name_en": param.NameEn, + "is_del": baseLogic.IS_NOT_DEL, + }); idc != nil && idc.IDcID != idcId && *param.NameEn != "" { + panic(constant.BuildInvalidArgumentWithArgs("机房英文名称已存在", "idcNameEn exist")) + } + + entity, err := idcDao.GetIdcById(logger, idcId) + if err != nil { + logger.Warn("GetIdcByUuid sql error:", idcId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if param.Name != nil { + entity.Name = *param.Name + } + if param.NameEn != nil { + entity.NameEn = *param.NameEn + } + if param.Shortname != nil { + entity.Shortname = *param.Shortname + } + if param.Level != nil { + entity.Level = *param.Level + } + if param.Address != nil { + entity.Address = *param.Address + } + if param.IloUser != nil { + entity.IloUser = *param.IloUser + } + if param.IloPassword != nil { + entity.IloPassword = *param.IloPassword + } + if param.SwitchUser1 != nil { + entity.SwitchUser1 = *param.SwitchUser1 + } + if param.SwitchPassword1 != nil { + entity.SwitchPassword1 = *param.SwitchPassword1 + } + if param.SwitchUser2 != nil { + entity.SwitchUser2 = *param.SwitchUser2 + } + if param.SwitchPassword2 != nil { + entity.SwitchPassword2 = *param.SwitchPassword2 + } + + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + + if err := idcDao.UpdateIdcById(logger, entity, idcId); err != nil { + logger.Warnf("ModifyIdc UpdateIdcById sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) + return err + } + return nil +} +func QueryIdcById(logger *log.Logger, idcId string) (*responseTypes.IdcInfo, error) { + tz := logger.GetPoint("timezone").(string) + idc, err := idcDao.GetIdcById(logger, idcId) + if err != nil { + logger.Warnf("DescribeIdc dao error, error:%s", err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + Idc := IdcEntity2Idc(logger, idc, tz) + return &responseTypes.IdcInfo{ + Idc: Idc, + }, nil +} +func DeleteIdc(logger *log.Logger, idcId string) error { + entity, err := idcDao.GetIdcById(logger, idcId) + if err != nil { + logger.Warn("GetIdcByUuid sql error:", idcId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + entity.DeletedTime = int(time.Now().Unix()) + entity.IsDel = baseLogic.IS_DEL + + if err := idcDao.UpdateIdcById(logger, entity, idcId); err != nil { + logger.Warnf("DeleteIdc UpdateIdcById sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) + return err + } + return nil +} diff --git a/bmp-openapi/logic/imageLogic/imageLogic.go b/bmp-openapi/logic/imageLogic/imageLogic.go new file mode 100644 index 0000000..9e7adab --- /dev/null +++ b/bmp-openapi/logic/imageLogic/imageLogic.go @@ -0,0 +1,399 @@ +package imageLogic + +import ( + "fmt" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceTypeDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rDeviceTypeImageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + imageDao "coding.jd.com/aidc-bmp/bmp-openapi/dao/imageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/osLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + namespacePrefix "git.jd.com/cps-golang/ironic-common/ironic/common/NamespacePrefixs" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +func DImageEntity2Image(d *imageDao.DImage, tz string) *responseTypes.Image { + return &responseTypes.Image{ + ID: d.ID, + ImageID: d.ImageID, + ImageName: d.ImageName, + Format: d.Format, + Filename: d.Filename, + URL: d.URL, + Hash: d.Hash, + Source: d.Source, + Description: d.Description, + SystemPartition: d.SystemPartition, + DataPartition: d.DataPartition, + //Platform: d.Platform, + OsVersion: d.OsVersion, + CreatedTime: util.TimestampToString(int64(d.CreatedTime), tz), + + //Os: responseTypes.OS{ + // Id: d.OsId, + // NameEn: d.OsNameEn, + // NameZh: d.OsNameZh, + // Version: d.OsVersion, + // Type: d.OsType, + // Bits: int(d.OsBits), + // Architecture: d.OsArchitecture, + // Platform: d.OsPlatform, + //}, + } +} + +func ImageEntityWithOs2Image(logger *log.Logger, d *imageDao.DImage, deviceTypeNum int, isBind bool, tz string) *responseTypes.Image { + image := &responseTypes.Image{ + ID: d.ID, + ImageID: d.ImageID, + ImageName: d.ImageName, + Format: d.Format, + BootMode: d.BootMode, + Filename: d.Filename, + URL: d.URL, + Hash: d.Hash, + Source: d.Source, + SourceName: baseLogic.Source[d.Source], + Architecture: d.Architecture, + Description: d.Description, + SystemPartition: d.SystemPartition, + DataPartition: d.DataPartition, + OsID: d.OsID, + OsType: d.OsType, + OsName: d.OsName, + OsVersion: d.OsVersion, + CreatedBy: d.CreatedBy, + UpdatedBy: d.UpdatedBy, + CreatedTime: util.TimestampToString(int64(d.CreatedTime), tz), + UpdatedTime: util.TimestampToString(int64(d.UpdatedTime), tz), + DeviceTypeNum: deviceTypeNum, + IsBind: isBind, + } + if logger.GetPoint("language").(string) == baseLogic.EN_US { + image.SourceName = baseLogic.SourceEn[d.Source] + } + return image +} + +func CreateImage(logger *log.Logger, param *requestTypes.CreateImageRequest) (string, error) { + //_, err := osLogic.GetAndCheckById(logger, param.OsID) + //if err != nil { + // logger.Warnf("Os not exist:osId:%s, error:%s", param.OsID, err.Error()) + // return "", err + //} + list, _ := imageDao.GetAllImage(logger, map[string]interface{}{ + "image_name": param.ImageName, + "is_del": baseLogic.IS_NOT_DEL, + }) + if len(list) != 0 { + logger.Warn("imageName exist:", param.ImageName) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("镜像名称 %s 已存在", param.ImageName), fmt.Sprintf("imageName %s exist", param.ImageName))) + } + bits := 64 + if param.Architecture == "i386" { //特殊处理 + bits = 32 + } + osId, err := osLogic.CreateOS(logger, &requestTypes.CreateOSRequest{ + OsName: param.ImageName, + OsType: param.OsType, + Architecture: param.Architecture, + Bits: bits, //默认64位,i38是32位的! + OsVersion: param.Version, + SysUser: "root", //默认root用户 + }) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("os创建失败:"+err.Error(), "os created failed:"+err.Error())) + } + entity := &imageDao.Image{ + ImageName: param.ImageName, + //ImageVersion: param.ImageVersion, + OsID: osId, + Format: param.Format, + BootMode: param.BootMode, + Filename: param.Filename, + URL: param.Url, + Hash: param.Hash, + Source: param.Source, + Description: param.Description, + SystemPartition: param.SystemPartition, + DataPartition: param.DataPartition, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + entity.ImageID = commonUtil.GetRandString("i-", namespacePrefix.IMAGE_ID_LENGTH, false, true, true) + if _, err := imageDao.AddImage(logger, entity); err != nil { + logger.Warnf("CreateImage AddImage sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) + return "", err + } + return entity.ImageID, nil +} + +func DescribeImages(logger *log.Logger, param *requestTypes.QueryImagesRequest, p util.Pageable) ([]*responseTypes.Image, int64, error) { + tz := logger.GetPoint("timezone").(string) + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "image_id": param.ImageID, + "image_name": param.ImageName, + "version": param.Version, + "os_id": param.OsID, + //"image_ids": strings.Join(param.ImageIds, ","), + "source": param.Source, + "architecture": param.Architecture, + "os_type": param.OsType, + "is_del": baseLogic.IS_NOT_DEL, + "device_type_id": param.DeviceTypeID, + } + //queryList := query + //query["count"] = true + _, count, err := imageDao.GetImageAndOsList(logger, query, true, 0, 0) + if err != nil { + logger.Warnf("DescribeDeviceTypes_GetDeviceTypeCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*imageDao.DImage{} + if param.IsAll == baseLogic.IS_ALL { + //entityList, err = imageDao.GetMultiImage(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + fmt.Println("获取全部", query) + entityList, _, err = imageDao.GetImageAndOsList(logger, query, false, 0, 0) + } else { + //entityList, err = imageDao.GetMultiImage(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + entityList, _, err = imageDao.GetImageAndOsList(logger, query, false, offset, limit) + } + if err != nil { + logger.Warn("imageDao.QueryByDeviceOsType sql error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + images := []*responseTypes.Image{} + for _, image := range entityList { + isBind := false + if param.DeviceTypeID != "" { + deviceTypeImageNum, _ := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, map[string]interface{}{ + "image_id": image.ImageID, + "device_type_id": param.DeviceTypeID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if deviceTypeImageNum != 0 { + isBind = true + } + } + + //os, err := osLogic.GetByOsId(logger, image.OsID) + //if err != nil && os == nil { + // os = &responseTypes.Os{} //如果没有找到os,默认为空 + //} + deviceTypeNum, err := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, map[string]interface{}{ + "image_id": image.ImageID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Warn("获取镜像对应的机型个数错误", image.OsID, err.Error()) + return nil, 0, err + } + images = append(images, ImageEntityWithOs2Image(logger, image, int(deviceTypeNum), isBind, tz)) + } + return images, count, nil +} + +func GetByImageId(logger *log.Logger, imageId string) (*responseTypes.Image, error) { + tz := logger.GetPoint("timezone").(string) + entity, _, err := imageDao.GetImageAndOsList(logger, map[string]interface{}{"image_id": imageId}, false, 0, 1) + if err != nil { + logger.Warn("GetImageByUuid sql error:", imageId, err.Error()) + return nil, err + } + if len(entity) == 0 { + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + //os, err := osLogic.GetByOsId(logger, entity.OsID) + //if err != nil { + // logger.Warn("GetByOsId sql error:", entity.OsID, err.Error()) + // return nil, err + //} + deviceTypeNum, err := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, map[string]interface{}{ + "image_id": imageId, + "is_del": baseLogic.IS_NOT_DEL, + }) + if err != nil { + logger.Warn("获取镜像对应的机型个数错误", imageId, err.Error()) + return nil, err + } + return ImageEntityWithOs2Image(logger, entity[0], int(deviceTypeNum), false, tz), nil +} + +func ModifyImage(logger *log.Logger, param *requestTypes.ModifyImageRequest, imageId string) error { + //先废弃,暂时用不到这个接口 + //if param.ImageName != "" { + // image, _ := imageDao.GetAllImage(logger, map[string]interface{}{ + // "image_name": param.ImageName, + // "is_del": baseLogic.IS_NOT_DEL, + // }) + // if len(image) != 0 && image[0].ImageName != param.ImageName { + // logger.Warn("imageName exist:", param.ImageName) + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("镜像名称 %s 已存在", param.ImageName), fmt.Sprintf("imageName %s exist", param.ImageName))) + // } + //} + entity, err := imageDao.GetImageByUuid(logger, imageId) + if err != nil { + logger.Warnf("GetImageByUuid sql error, image_id:%s, error:%s", imageId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + //if param.ImageName != "" { + // if err := osLogic.ModifyOS(logger, &requestTypes.ModifyOSRequest{ + // OsName: param.ImageName, + // }, entity.OsID); err != nil { + // logger.Warnf("ModifyOS UpdateOsById sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) + // return err + // } + //} + //entity.ImageName = param.ImageName + ////entity.ImageVersion = param.ImageVersion + //entity.OsID = param.OsID + //entity.Format = param.Format + //entity.Filename = param.Filename + //entity.URL = param.Url + //entity.Hash = param.Hash + //entity.Source = param.Source + //entity.SystemPartition = param.SystemPartition + // entity.DataPartition = param.DataPartition + if param.Description != nil { + entity.Description = *param.Description + } + + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + if err := imageDao.UpdateImageById(logger, entity); err != nil { + logger.Warnf("ModifyImage UpdateImageById sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) + return err + } + return nil +} + +func DeleteImage(logger *log.Logger, imageId string) error { + entity, err := imageDao.GetImageByUuid(logger, imageId) + if err != nil { + logger.Warnf("DeleteImage %s GetImageByUuid sql error:", imageId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if entity.Source == baseLogic.COMMON { + panic(constant.BuildInvalidArgumentWithArgs("预置镜像不能删除", "preImage not allowed delete")) + } + entity.IsDel = 1 + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + entity.DeletedTime = int(time.Now().Unix()) + if err := imageDao.UpdateImageById(logger, entity); err != nil { + logger.Warnf("DeleteImage %s UpdateImageById sql error:", imageId, err.Error()) + return err + } + //同时删除os表 + if err := osLogic.DeleteOS(logger, entity.OsID); err != nil { + logger.Warnf("DeleteOs %s UpdateOsById sql error:", entity.OsID, err.Error()) + return err + } + return nil +} +func QueryImageDeviceTypes(logger *log.Logger, param *requestTypes.QueryImageDeviceTypesRequest, p util.Pageable) ([]*responseTypes.DeviceType, int64, error) { + //tz := logger.GetPoint("timezone").(string) + language := logger.GetPoint("language").(string) + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "image_id": param.ImageID, + "architecture": param.Architecture, + "is_del": baseLogic.IS_NOT_DEL, + "is_bind": param.IsBind, + } + //queryList := query + //query["count"] = true + _, count, err := rDeviceTypeImageDao.GetImageDeviceTypeList(logger, query, true, 0, 0) + //os.Exit(1) + if err != nil { + logger.Warnf("DescribeDeviceTypes_GetDeviceTypeCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*deviceTypeDao.DeviceType{} + if param.IsAll == baseLogic.IS_ALL { + //entityList, err = imageDao.GetMultiImage(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + fmt.Println("获取全部", query) + entityList, _, err = rDeviceTypeImageDao.GetImageDeviceTypeList(logger, query, false, 0, 0) + } else { + //entityList, err = imageDao.GetMultiImage(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + entityList, _, err = rDeviceTypeImageDao.GetImageDeviceTypeList(logger, query, false, offset, limit) + } + if err != nil { + logger.Warn("imageDao.QueryByDeviceOsType sql error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + fmt.Println(entityList) + deviceTypes := []*responseTypes.DeviceType{} + for _, entity := range entityList { + //isBind := false + //if param.DeviceTypeID != "" { + // deviceTypeImageNum, _ := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, map[string]interface{}{ + // "image_id": image.ImageID, + // "device_type_id": param.DeviceTypeID, + // "is_del": baseLogic.IS_NOT_DEL, + // }) + // if deviceTypeImageNum != 0 { + // isBind = true + // } + //} + //deviceTypeNum, err := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, map[string]interface{}{ + // "image_id": image.ImageID, + // "is_del": baseLogic.IS_NOT_DEL, + //}) + //if err != nil { + // logger.Warn("获取镜像对应的机型个数错误", image.OsID, err.Error()) + // return nil, 0, err + //} + //deviceType.DeviceTypeID + idc, err := idcDao.GetIdcById(logger, entity.IDcID) //获取机房信息 + if err != nil { + idc = &idcDao.Idc{} + } + idcName := idc.Name + if language == baseLogic.EN_US { + idcName = idc.NameEn + } + instanceList, err := instanceDao.GetAllInstance(logger, map[string]interface{}{ + "device_type_id": entity.DeviceTypeID, + "image_id": param.ImageID, + }) + instanceStatus := []string{} + for _, v := range instanceList { + instanceStatus = append(instanceStatus, v.Status) + } + deviceSeries := baseLogic.DeviceTypeSeries[entity.DeviceSeries] + if language == baseLogic.EN_US { + deviceSeries = baseLogic.DeviceTypeSeriesEn[entity.DeviceSeries] + } + deviceType := &responseTypes.DeviceType{ + ID: entity.ID, + IDcID: entity.IDcID, + IDcName: idcName, + IDcNameEn: idc.NameEn, + DeviceType: entity.DeviceType, + DeviceTypeID: entity.DeviceTypeID, + Name: entity.Name, + Description: entity.Description, + DeviceSeries: entity.DeviceSeries, + DeviceSeriesName: deviceSeries, + Architecture: entity.Architecture, + InstanceStatus: instanceStatus, + } + fmt.Println(deviceType) + deviceTypes = append(deviceTypes, deviceType) //deviceTypeLogic.DeviceTypeEntity2DeviceType(logger, deviceType) + } + return deviceTypes, count, nil +} diff --git a/bmp-openapi/logic/instanceLogic/InstanceLogic.go b/bmp-openapi/logic/instanceLogic/InstanceLogic.go new file mode 100644 index 0000000..c1a033b --- /dev/null +++ b/bmp-openapi/logic/instanceLogic/InstanceLogic.go @@ -0,0 +1,1622 @@ +package instanceLogic + +import ( + "encoding/base64" + "fmt" + "strings" + "time" + + beego "github.com/beego/beego/v2/server/web" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/auditLogsDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceTypeDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/imageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instancePartitionDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/projectDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rDeviceTypeImageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rDeviceTypeImagePartitionDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rInstanceSshkeyDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rInstanceVolumeRaidDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/raidDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/sharingProjectDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/volumeDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/auditLogLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/deviceTypeLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/idcLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/imageLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/raidLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/sshkeyLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-openapi/service/rabbit_mq" + namespacePrefix "git.jd.com/cps-golang/ironic-common/ironic/common/NamespacePrefixs" + "git.jd.com/cps-golang/ironic-common/ironic/enums/AuditLogsType" + instanceStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/InstanceStatus" + rabbitEvent "git.jd.com/cps-golang/ironic-common/ironic/event" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +var NoOpForLock []string = []string{instanceStatus.CREATE_ERROR, instanceStatus.CREATING, instanceStatus.DESTROYING, instanceStatus.DESTROY_ERROR} + +func InstanceEntity2Instance(logger *log.Logger, o *instanceDao.Instance, vrs []*response.InstanceVolumeRaid) *responseTypes.Instance { + //logger := &log.Logger{} + + language := logger.GetPoint("language").(string) + + tz := logger.GetPoint("timezone").(string) + idc, _ := idcDao.GetIdcById(logger, o.IDcID) + if idc == nil { + idc = &idcDao.Idc{} + } + device, _ := deviceDao.GetDeviceById(logger, o.DeviceID) + if device == nil { + device = &deviceDao.Device{} + } + deviceType, _ := deviceTypeDao.GetDeviceTypeById(logger, o.DeviceTypeID) + if deviceType == nil { + deviceType = &deviceTypeDao.DeviceType{} + } + image, _ := imageDao.GetImageByUuid(logger, o.ImageID) + if image == nil { + image = &imageDao.Image{} + } + raidSys, _ := raidDao.GetRaidById(logger, o.SystemVolumeRaidID) + if raidSys == nil { + raidSys = &raidDao.Raid{} + } + raidData, _ := raidDao.GetRaidById(logger, o.DataVolumeRaidID) + if raidData == nil { + raidData = &raidDao.Raid{} + } + reason := baseLogic.InstanceReason[o.Reason] + if language == baseLogic.EN_US { + reason = baseLogic.InstanceReasonEn[o.Reason] + } + //字典不全,兜底 + if reason == "" { + reason = o.Reason + } + + v := &responseTypes.Instance{ + ID: o.ID, + InstanceName: o.InstanceName, + InstanceID: o.InstanceID, + UserID: o.UserID, + ProjectID: o.ProjectID, + + IDcID: o.IDcID, + IdcName: idc.Name, + DeviceID: o.DeviceID, + Sn: device.Sn, + + IloIP: device.IloIP, + PrivateIPv4: device.PrivateIPv4, + PrivateIPv6: device.PrivateIPv6, + + DeviceTypeID: o.DeviceTypeID, + DeviceTypeName: deviceType.Name, + DeviceType: deviceType.DeviceType, + DeviceSeries: deviceType.DeviceSeries, + DeviceSeriesName: baseLogic.DeviceTypeSeries[deviceType.DeviceSeries], + CPUAmount: deviceType.CPUAmount, + CPUCores: deviceType.CPUCores, + CPUManufacturer: deviceType.CPUManufacturer, + CPUModel: deviceType.CPUModel, + CPUFrequency: deviceType.CPUFrequency, + MemType: deviceType.MemType, + MemSize: deviceType.MemSize, + MemAmount: deviceType.MemAmount, + MemFrequency: deviceType.MemFrequency, + NicAmount: deviceType.NicAmount, + NicRate: deviceType.NicRate, + InterfaceMode: deviceType.InterfaceMode, + SystemVolumeType: deviceType.SystemVolumeType, + SystemVolumeInterfaceType: deviceType.SystemVolumeInterfaceType, + SystemVolumeSize: deviceType.SystemVolumeSize, + SystemVolumeAmount: deviceType.SystemVolumeAmount, + SystemVolumeUnit: deviceType.SystemVolumeUnit, + GpuAmount: deviceType.GpuAmount, + GpuManufacturer: deviceType.GpuManufacturer, + GpuModel: deviceType.GpuModel, + DataVolumeType: deviceType.DataVolumeType, + DataVolumeInterfaceType: deviceType.DataVolumeInterfaceType, + DataVolumeSize: deviceType.DataVolumeSize, + DataVolumeAmount: deviceType.DataVolumeAmount, + DataVolumeUnit: deviceType.DataVolumeUnit, + + Hostname: o.Hostname, + Status: o.Status, + Reason: reason, + StatusName: baseLogic.InstanceStatus[o.Status], + ImageID: o.ImageID, + ImageName: image.ImageName, + + SystemVolumeRaidID: o.SystemVolumeRaidID, + SystemVolumeRaidName: raidSys.Name, + Locked: o.Locked, + LockedName: baseLogic.InstanceLock[o.Locked], + DataVolumeRaidID: o.DataVolumeRaidID, + DataVolumeRaidName: raidData.Name, + + Description: o.Description, + + CreatedBy: o.CreatedBy, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + UpdatedBy: o.UpdatedBy, + UpdatedTime: util.TimestampToString(int64(o.UpdatedTime), tz), + InstanceVolumeRaids: vrs, + } + if language == baseLogic.EN_US { + v.StatusName = baseLogic.InstanceStatusEn[o.Status] + } + + return v +} + +func GetInstanceById(logger *log.Logger, InstanceId string) (*responseTypes.Instance, error) { + instanceEntity, err := instanceDao.GetInstanceById(logger, InstanceId) + if err != nil { + logger.Warnf("GetInstanceByUuid sql error, uuid:%s, error:%s", InstanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + vrs := []*response.InstanceVolumeRaid{} + volumeEntities, err := volumeDao.GetAllVolumeByDeviceTypeId(logger, instanceEntity.DeviceTypeID) + if err != nil { + logger.Warnf("GetInstanceById.GetAllVolumeByDeviceTypeId error, InstanceId:%s, error:%s", InstanceId, err.Error()) + } + //有些是盘符,就没有raid,这种情况行不通 + rInstanceVolumeRaidEntities, err := rInstanceVolumeRaidDao.GetRInstanceVolumeRaidByInstanceId(logger, InstanceId) + if err != nil { + logger.Warnf("GetInstanceById.GetRVolumeRaidsByInstanceId error, instance_id:%s, error:%s", InstanceId, err.Error()) + } + for _, volumeEntity := range volumeEntities { + var tRaid *raidDao.Raid + for _, rInstanceVolumeRaidEntity := range rInstanceVolumeRaidEntities { + if rInstanceVolumeRaidEntity.VolumeID == volumeEntity.VolumeID { + tRaid = &raidDao.Raid{ + RaidID: rInstanceVolumeRaidEntity.RaidID, + Name: rInstanceVolumeRaidEntity.RaidName, + } + break + } + } + vrs = append(vrs, &response.InstanceVolumeRaid{ + Volume: volumeEntity, + Raid: tRaid, + }) + + } + return InstanceEntity2Instance(logger, instanceEntity, vrs), nil +} + +func CreateInstance(logger *log.Logger, param requestTypes.CreateInstanceRequest) (ids []string, err error) { + + if param.Password == "" && param.SshKeyID == "" { + panic(constant.BuildInvalidArgumentWithArgs("密码和sshkeyid不能同时为空", "password and sshkeyID both empty")) + } + if param.Password != "" && param.SshKeyID != "" { + panic(constant.BuildInvalidArgumentWithArgs("密码和sshkeyid不能同时存在", "password and sshkeyID invalidate")) + } + idc, err := idcLogic.QueryIdcById(logger, param.IdcID) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("idcId非法", "idc invalidate")) + } + project, err := projectDao.GetProjectById(logger, param.ProjectID) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("projectId非法", "projectId invalidate")) + } + if project != nil && project.UserID != logger.GetPoint("userId").(string) { + panic(constant.BuildInvalidArgumentWithArgs("项目ID和用户ID不匹配", "projectID not match userID")) + } + deviceType, err := deviceTypeLogic.QueryDeviceTypeById(logger, param.DeviceTypeID) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("deviceTypeId非法", "deviceTypeId invalidate")) + } + if deviceType.IDcID != param.IdcID { + panic(constant.BuildInvalidArgumentWithArgs("idcId和deviceTypeId不匹配", "idcId not match deviceTypeId")) + } + _, err = imageLogic.GetByImageId(logger, param.ImageID) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("imageId非法", "imageId invalidate")) + } + _, err = raidLogic.GetByRaidId(logger, param.SystemVolumeRaidID) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("systemVolumeRaidId非法", "systemVolumeRaidId invalidate")) + } + //检查devicetype和image是否绑定 + q := map[string]interface{}{ + "image_id": param.ImageID, + "device_type_id": param.DeviceTypeID, + "is_del": baseLogic.IS_NOT_DEL, + } + n, _ := rDeviceTypeImageDao.QueryDeviceTypeImagesCount(logger, q) + if n == 0 { + panic(constant.BuildInvalidArgumentWithArgs("此机型和镜像未绑定", "devicetype and image do not associated")) + } + //检查devicetype和raid是否绑定 + + q = map[string]interface{}{ + "raid_id": param.SystemVolumeRaidID, + "device_type_id": param.DeviceTypeID, + "is_del": baseLogic.IS_NOT_DEL, + } + //if _, err := rDeviceTypeRaidDao.GetOneRDeviceTypeRaid(logger, q); err != nil { + // panic(constant.BuildInvalidArgumentWithArgs("此机型系统盘和raid未绑定", "devicetype systemdisk and raid do not associated")) + //} + + if param.SshKeyID != "" { + sshkeys := strings.Split(param.SshKeyID, ",") + for _, sshkey := range sshkeys { + _, err := sshkeyLogic.GetSshkeyById(logger, strings.TrimSpace(sshkey)) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs("sshKeyId非法", "sshKeyId invalidate")) + } + } + + } + deviceConditions := deviceLogic.GetAllDevices(logger, map[string]interface{}{ + "manage_status": baseLogic.PUTAWAY, + "is_del": baseLogic.IS_NOT_DEL, + "device_type_id": param.DeviceTypeID, + }, []string{}, []string{}, []string{}) + if err != nil { + return nil, err + } + if len(deviceConditions) < param.Count { + logger.Warn("设备库存不足") + panic(constant.BuildInvalidArgumentWithArgs("设备库存不足", "device stock is not enough")) + } + userId := logger.GetPoint("userId").(string) + + list, _ := instanceDao.GetAllInstance(logger, map[string]interface{}{ + "instance_name": param.InstanceName, + "user_id": userId, + "is_del": 0, + }) + if len(list) != 0 { + logger.Warn("instanceName exist:", param.InstanceName) + panic(constant.BuildInvalidArgumentWithArgs("实例名称已存在", "projectName exist")) + } + + if param.HostName == "" { + list, _ := instanceDao.GetAllInstance(logger, map[string]interface{}{ + "hostname.like": "%" + idc.Idc.Shortname + "-" + deviceType.DeviceType + "%", + "user_id": userId, + "is_del": baseLogic.IS_NOT_DEL, + }) + param.HostName = fmt.Sprintf("%s-%s-%d", idc.Idc.Shortname, deviceType.DeviceType, len(list)+1) + param.HostName = strings.ReplaceAll(param.HostName, ".", "-") //机型规格里面的.替换成-,如c1.normal=> c1-normal + param.HostName = strings.ReplaceAll(param.HostName, "_", "-") + } + + //从r_devicetype_image_partition表获取bootmode + imagePartitions, _ := rDeviceTypeImagePartitionDao.GetByDeviceTypeAndImageId(logger, param.DeviceTypeID, param.ImageID) + if len(imagePartitions) == 0 { + panic(constant.BuildInvalidArgumentWithArgs("r_device_type_image_partition配置错误", "r_device_type_image_partition config error")) + } + var bootmode string //优先取用户指定的 + if param.BootMode != "" { + bootmode = param.BootMode + } else { + bootmode = imagePartitions[0].BootMode + } + + //user, err := userLogic.GetUserById(logger, userId) + //if err != nil { + // panic(constant.BuildInvalidArgumentWithArgs("用户id不存在", "userId not exist")) + //} + entities := []*instanceDao.Instance{} // instanceCreator.Create(logger, param) + //ids := []string{} + for i := 0; i < param.Count; i++ { + instanceName := fmt.Sprintf("%s-%d", param.InstanceName, i) + if param.Count == 1 { + instanceName = param.InstanceName + } + //instanceList, err := instanceDao.GetAllInstance(logger, map[string]interface{}{ + // "instance_name": instanceName, + // "user_id": logger.GetPoint("userId").(string), + // "is_del": baseLogic.IS_NOT_DEL, + //}) + //if len(instanceList) != 0 { + // logger.Warn("instanceName exist:", instanceName) + // panic(constant.BuildInvalidArgumentWithArgs("实例名称已存在", "instanceName exist")) + //} + entity := &instanceDao.Instance{ + IDcID: param.IdcID, + InstanceID: commonUtil.GetRandString("bmp-", namespacePrefix.IMAGE_ID_LENGTH, false, true, true), + ProjectID: param.ProjectID, + UserID: userId, + DeviceTypeID: param.DeviceTypeID, + InstanceName: instanceName, + Hostname: param.HostName, + Description: param.Description, + ImageID: param.ImageID, + SystemVolumeRaidID: param.SystemVolumeRaidID, + Status: instanceStatus.CREATING, + DeviceID: deviceConditions[i].DeviceID, + Locked: baseLogic.UNLOCKED, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + + //if entity.Hostname == "" { + // entity.Hostname = fmt.Sprintf("%s-%s-%d", idc.Idc.Name, deviceType.Name, i) + //} + + //还要写进实例分区表,实例秘钥表 todo + partitionsObj := param.SystemPartition + //if len(partitionsObj) == 0 { + // panic(constant.BuildInvalidArgumentWithArgs("系统分区不能为空", "SystemPartition is empty")) + //} + for i := 0; i < len(partitionsObj); i++ { //数组的结构体partitionObj,不能用range遍历?? + _, err = instancePartitionDao.AddInstancePartition(logger, &instancePartitionDao.InstancePartition{ + InstanceID: entity.InstanceID, + ImageID: param.ImageID, + DeviceTypeID: param.DeviceTypeID, + BootMode: bootmode, + PartitionType: baseLogic.PartitionType[partitionsObj[i].MountPoint], + PartitionSize: partitionsObj[i].Size, + PartitionFsType: partitionsObj[i].FsType, + PartitionLabel: baseLogic.PartitionLabel[partitionsObj[i].MountPoint], + PartitionMountPoint: partitionsObj[i].MountPoint, + SystemDiskLabel: baseLogic.SystemDiskLabel[partitionsObj[i].MountPoint], + DataDiskLabel: baseLogic.DataDiskLabel[partitionsObj[i].MountPoint], + + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + }) + if err != nil { + logger.Warnf("add instance partition error,instanceId:%s,partition%s,error:%s", entity.InstanceID, util.InterfaceToJson(param.SystemPartition), err.Error()) + return nil, err + } + } + if param.SshKeyID != "" { + for _, sshkeyId := range strings.Split(param.SshKeyID, ",") { + sshkeyId = strings.TrimSpace(sshkeyId) + if sshkeyId == "" { + panic(constant.BuildInvalidArgumentWithArgs("秘钥ID不能为空", "sshkeyID is empty")) + } + _, err = rInstanceSshkeyDao.AddrInstanceSshkey(logger, &rInstanceSshkeyDao.RInstanceSshkey{ + InstanceID: entity.InstanceID, + SSHkeyID: sshkeyId, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + }) + if err != nil { + logger.Warn("add r_instance_sshkey error:", err.Error()) + return nil, err + } + } + } + _, err = instanceDao.AddInstance(logger, entity) + + if err != nil { + logger.Warn("createInstance error:", err.Error()) + return nil, err + } + if err := deviceLogic.ModifyDeviceByDeviceId(logger, &requestTypes.ModifyAllDevicesRequest{ + ManageStatus: baseLogic.CREATED, + InstanceID: entity.InstanceID, + UserId: userId, + UserName: logger.GetPoint("username").(string), + }, deviceConditions[i].DeviceID); err != nil { + logger.Warn("modifyDevice instanceId error:", err.Error()) + return nil, err + } + entities = append(entities, entity) + //ids = append(ids, entity.InstanceID) + } + return afterCreateInstances(logger, entities, param) +} +func afterCreateInstances(logger *log.Logger, entities []*instanceDao.Instance, param requestTypes.CreateInstanceRequest) ([]string, error) { + + instance_ids := []string{} + for _, v := range entities { + instance_ids = append(instance_ids, v.InstanceID) + } + err := sendCreateInstanceEvent(logger, instance_ids, param.Password) //param.UserData, param.AliasIPs, param.ExtensionAliasIps + if err != nil { + return nil, err + } + if len(entities) == 1 { + //instance := entities[0] + //if param.AliasIPs != nil { + // saveAliasIPs(logger, instance.InstanceID, instance.SubnetID, param.AliasIPs) + //} + //if param.ExtensionAliasIps != nil { + // saveAliasIPs(logger, instance.InstanceID, instance.ExtensionSubnetID, param.ExtensionAliasIps) + //} + } + return instance_ids, nil +} + +func sendCreateInstanceEvent(logger *log.Logger, instance_ids []string, password string) error { + + logid := logger.GetPoint("logid").(string) + msg := rabbitIronicMsgApi.CreateInstancesMessage{ + ApiMessage: rabbitIronicMsgApi.ApiMessage{ + RequestId: logid, + }, + InstanceIds: instance_ids, + Password: password, + //UserData: user_data, + //AliasIps: alias_ips, + //ExtensionAliasIps: extension_alias_ips, + } + userId := logger.GetPoint("userId").(string) + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("RetryCommand convert event msg error:", instance_ids, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warnf("RetryCommand UpdateCommandById sql error, msg:%s, error:%s", util.ObjToJson(event), err.Error()) + return err + } else { + logger.Infof("sendCreateInstanceEvent SendToScheduler success, msg:%s", util.ObjToJson(event)) + } + return nil +} +func ModifyInstance(logger *log.Logger, param *requestTypes.ModifyInstanceRequest, instanceId string) error { + + q := map[string]interface{}{ + "is_del": 0, + } + its, _ := instanceDao.GetAllInstance(logger, q) + var existNames []string + var instance *instanceDao.Instance + for _, item := range its { + if item.InstanceID == instanceId { + instance = item + } + existNames = append(existNames, item.InstanceName) + } + + if instance == nil { + logger.Warnf("GetInstanceByUuid sql not found, uuid:%s", instanceId) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + if err := checkInstanceNameUnique(logger, param.InstanceName, existNames); err != nil { + return err + } + + //instance.InstanceName = param.InstanceName + if param.Description != nil { + instance.Description = *param.Description + } + instance.UpdatedBy = logger.GetPoint("username").(string) + instance.UpdatedTime = int(time.Now().Unix()) + if err := instanceDao.UpdateInstanceAnywhere(logger, instance); err != nil { + logger.Warn("ModifyInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + return nil +} + +// 批量编辑实例名称 +func ModifyInstances(logger *log.Logger, param requestTypes.ModifyInstancesRequest) error { + + var instances []*instanceDao.Instance + + q := map[string]interface{}{ + "is_del": 0, + } + aits, _ := instanceDao.GetAllInstance(logger, q) + var existNames []string + for _, v := range aits { + if !util.InArrayString(v.InstanceID, param.InstanceIDs) { + existNames = append(existNames, v.InstanceName) + } else { + if !InstanceOwnedCheck(logger, v) { + panic(constant.PermissionDenyForObject) + } + instances = append(instances, v) + } + } + for idx, _ := range instances { + var instanceName string + if idx == 0 { + instanceName = param.InstanceName + } else { + instanceName = fmt.Sprintf("%s_%d", param.InstanceName, idx) + } + + instances[idx].InstanceName = instanceName + if err := checkInstanceNameUnique(logger, instanceName, existNames); err != nil { + return err + } + } + + for _, v := range instances { + v.UpdatedBy = logger.GetPoint("username").(string) + if err := instanceDao.UpdateInstanceById(logger, v); err != nil { + logger.Warnf("ModifyInstances.UpdateInstanceById error, instance_id:%s, instance_name:%s", v.InstanceID, v.InstanceName) + } + auditLogLogic.SaveAuditLogs(logger, v.DeviceID, v.InstanceID, AuditLogsType.AuditLogsEditInstanceName) + } + return nil +} + +func checkInstanceNameUnique(logger *log.Logger, name string, existsNames []string) error { + + if util.InArrayString(name, existsNames) { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例名称 %s 已经存在", name), fmt.Sprintf("instanceName %s already exist", name))) + } + return nil +} + +func ModifyProjectInstance(logger *log.Logger, param *requestTypes.ModifyInstanceRequest, instanceId string) error { + + q := map[string]interface{}{ + "is_del": 0, + } + its, _ := instanceDao.GetAllInstance(logger, q) + var existNames []string + var v *instanceDao.Instance + for _, item := range its { + if item.InstanceID == instanceId { + v = item + } + existNames = append(existNames, item.InstanceName) + } + + if v == nil { + logger.Warnf("GetInstanceByUuid not found, uuid:%s", instanceId) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, v) { + panic(constant.PermissionDenyForObject) + } + + if err := checkInstanceNameUnique(logger, param.InstanceName, existNames); err != nil { + return err + } + + if param.Description != nil { + v.Description = *param.Description + } + if param.InstanceName != "" { + v.InstanceName = param.InstanceName + } + + if err := instanceDao.UpdateInstanceAnywhere(logger, v); err != nil { + logger.Warn("ModifyInstance UpdateInstanceAnywhere sql error:", instanceId, err.Error()) + return err + } + + auditLogLogic.SaveAuditLogs(logger, v.DeviceID, instanceId, AuditLogsType.AuditLogsEditInstanceName) + return nil +} + +func LockInstance(logger *log.Logger, instanceId string) error { + instance, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warnf("GetInstanceByUuid sql error, uuid:%s, error:%s", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + if instance.Locked == baseLogic.LOCKED { + logger.Warnf("Instance %s already locked", instanceId) + panic(constant.NOT_SUPPORTED) + } + + if util.InArray(instance.Status, NoOpForLock) { + logger.Warnf("unsupported lock error status instance %s", instanceId) + panic(constant.NOT_SUPPORTED) + } + + entity := &instanceDao.Instance{ + InstanceID: instanceId, + Locked: baseLogic.LOCKED, + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("ModifyInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + return nil +} + +func UnLockInstance(logger *log.Logger, instanceId string) error { + instance, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warn("GetInstanceById sql error:", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + if instance.Locked == baseLogic.UNLOCKED { + logger.Warnf("instance %s already unlocked.", instanceId) + panic(constant.NOT_SUPPORTED) + } + + if util.InArray(instance.Status, NoOpForLock) { + logger.Warnf("unsupported lock error status instance %s", instanceId) + panic(constant.NOT_SUPPORTED) + } + + entity := &instanceDao.Instance{ + InstanceID: instanceId, + Locked: baseLogic.UNLOCKED, + UpdatedBy: "admin", + UpdatedTime: int(time.Now().Unix()), + } + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("ModifyInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + return nil +} + +func StartInstance(logger *log.Logger, instanceId string) error { + instance, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warnf("GetInstanceByUuid sql error, uuid:%s, error:%s", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + //可以在此增加一些逻辑判断,比如,只能处在关机模式下才可以开机,其他状态不可以。。。后续再处理这块 + if instance.Status != instanceStatus.STOPPED { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是关机", instanceId), fmt.Sprintf("unsupported start instance %s", instanceId))) + } + entity := &instanceDao.Instance{ + InstanceID: instanceId, + Status: instanceStatus.STARTING, + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("StartInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + return sendStartInstanceEvent(logger, []string{instanceId}) +} +func sendStartInstanceEvent(logger *log.Logger, instance_ids []string) error { + + logid := logger.GetPoint("logid").(string) + msg := rabbitIronicMsgApi.StartInstancesMessage{} + msg.ApiMessage.RequestId = logid + msg.InstanceIds = instance_ids + userId := logger.GetPoint("userId").(string) + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("convert StartInstancesMessage 2 event error:", instance_ids, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warnf("StartInstancesMessage SendToScheduler error, msg:%s, error:%s", util.ObjToJson(msg), err.Error()) + return err + } else { + logger.Infof("StartInstancesMessage SendToScheduler success, msg:%s", util.ObjToJson(msg)) + } + return nil +} +func StopInstance(logger *log.Logger, instanceId string) error { + instance, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warnf("GetInstanceByUuid sql error, uuid:%s, error:%s", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + if instance.Status != instanceStatus.RUNNING { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是运行", instanceId), fmt.Sprintf("unsupported stop instance %s", instanceId))) + } + entity := &instanceDao.Instance{ + InstanceID: instanceId, + Status: instanceStatus.STOPPING, + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("StopInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + return sendStopInstanceEvent(logger, []string{instanceId}) +} +func sendStopInstanceEvent(logger *log.Logger, instance_ids []string) error { + + logid := logger.GetPoint("logid").(string) + msg := rabbitIronicMsgApi.StopInstancesMessage{} + msg.ApiMessage.RequestId = logger.GetPoint("logid").(string) + msg.InstanceIds = instance_ids + userId := logger.GetPoint("userId").(string) + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("convert StopInstancesMessage 2 event error:", instance_ids, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warnf("sendStopInstanceEvent SendToScheduler error, msg:%s, error:%s", util.ObjToJson(event), err.Error()) + return err + } else { + logger.Infof("sendStopInstanceEvent SendToScheduler success, msg:%s", util.ObjToJson(event)) + } + return nil +} +func RestartInstance(logger *log.Logger, instanceId string) error { + instance, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warnf("GetInstanceByUuid sql error, uuid:%s, error:%s", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + if instance.Status != instanceStatus.RUNNING { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是运行", instanceId), fmt.Sprintf("unsupported restart instance %s", instanceId))) + } + entity := &instanceDao.Instance{ + InstanceID: instanceId, + Status: instanceStatus.RESTARTING, + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("RestartInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + return sendRestartInstanceEvent(logger, []string{instanceId}) +} +func sendRestartInstanceEvent(logger *log.Logger, instance_ids []string) error { + + logid := logger.GetPoint("logid").(string) + msg := rabbitIronicMsgApi.RestartInstancesMessage{} + msg.ApiMessage.RequestId = logid + msg.InstanceIds = instance_ids + userId := logger.GetPoint("userId").(string) + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("convert RestartInstancesMessage 2 event error:", instance_ids, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warn("sendRestartInstanceEvent SendToScheduler error, msg:%s, error:%s", util.ObjToJson(event), err.Error()) + return err + } else { + logger.Infof("sendRestartInstanceEvent SendToScheduler success, msg:%s", util.ObjToJson(event)) + } + return nil +} + +func ResetInstanceStatus(logger *log.Logger, instanceId string) error { + instance, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warnf("GetInstanceByUuid sql error, uuid:%s, error:%s", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + //可以在此增加一些逻辑判断,比如,只能处在关机模式下才可以开机 + resetArr := []string{instanceStatus.START_ERROR, instanceStatus.STOP_ERROR, instanceStatus.RESTART_ERROR, instanceStatus.DESTROY_ERROR} + if !util.InArray(instance.Status, resetArr) { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态错误", instanceId), fmt.Sprintf("unsupported start instance %s", instanceId))) + } + entity := &instanceDao.Instance{ + InstanceID: instanceId, + Status: instanceStatus.Error_Instance_To_Reset_Status[instance.Status], + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + + if err := commandDao.DeleteCommandByInstanceId(logger, instanceId); err != nil { + logger.Warn("ResetInstanceStatus DeleteCommandByInstanceId sql error:", instanceId, err.Error()) + } + + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("ResetInstanceStatus UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + + auditLogLogic.SaveAuditLogs(logger, instance.DeviceID, instanceId, AuditLogsType.AuditLogsResetInstanceStatus) + + return nil +} + +func DeleteInstance(logger *log.Logger, instanceId string) error { + entity, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warnf("GetInstanceByUuid sql error, uuid:%s, error:%s", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, entity) { + panic(constant.PermissionDenyForObject) + } + + // 已锁定实例不允许删除 + if entity.Locked == baseLogic.LOCKED { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("已锁定实例 %s 不能被删除", instanceId), fmt.Sprintf("locked instance %s not allowed delete", instanceId))) + } + + if !util.InArray(entity.Status, []string{instanceStatus.STOPPED, instanceStatus.CREATE_ERROR}) { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是关机和创建失败,不允许被删除", instanceId), fmt.Sprintf("unsupported delete instance %s", instanceId))) + } + + if entity.Status == instanceStatus.CREATE_ERROR { //创建错误的实例,不用走完整的删除逻辑,直接释放各种资源就行 + //释放销毁实例使用的各种资源 + if err := rInstanceSshkeyDao.DeleteInstanceSshkeyByInstanceID(logger, entity.InstanceID); err != nil { + logger.Warn("DeleteInstance DeleteInstanceSshkeyByInstanceID sql error:", instanceId, err.Error()) + } + deviceEntiry, err := deviceDao.GetDeviceById(logger, entity.DeviceID) + if err != nil { + logger.Warnf("delete error status instance.GetDeviceById error, device_id:%s, error:%s", entity.DeviceID, err.Error()) + return err + } + device := &deviceDao.Device{ + Sn: deviceEntiry.Sn, + ManageStatus: baseLogic.PUTAWAY, //删除实例以后,设备表的某些状态更改 + } + if err := deviceDao.UpdateDeviceBySn(logger, device); err != nil { + logger.Warnf("update device error,deviceSN:%s, error:%s", device.Sn, err.Error()) + return err + } + if err := commandDao.DeleteCommandBySn(logger, deviceEntiry.Sn); err != nil { + logger.Warn("DeleteInstance DeleteCommandBySn sql error:", instanceId, err.Error()) + } + + entity.IsDel = 1 + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("DeleteInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + + return nil + } + + entity.Status = instanceStatus.DESTROYING + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + entity.DeletedTime = int(time.Now().Unix()) + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("DeleteInstance UpdateInstanceById sql error:", instanceId, err.Error()) + return err + } + //释放销毁实例使用的各种资源 + if err := rInstanceSshkeyDao.DeleteInstanceSshkeyByInstanceID(logger, entity.InstanceID); err != nil { + logger.Warn("DeleteInstance DeleteInstanceSshkeyByInstanceID sql error:", instanceId, err.Error()) + } + return sendDeleteInstanceEvent(logger, instanceId) +} + +//批量删除实例 +func DeleteInstances(logger *log.Logger, instanceIds []string) error { + + instances := []*instanceDao.Instance{} + + for _, instanceId := range instanceIds { + entity, err := instanceDao.GetInstanceById(logger, instanceId) + if err != nil { + logger.Warnf("GetInstanceByUuid sql error, uuid:%s, error:%s", instanceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + if !InstanceOwnedCheck(logger, entity) { + panic(constant.PermissionDenyForObject) + } + + // 已锁定实例不允许删除 + if entity.Locked == baseLogic.LOCKED { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("已锁定实例 %s 不能被删除", instanceId), fmt.Sprintf("locked instance %s not allowed delete", instanceId))) + } + + if !util.InArray(entity.Status, []string{instanceStatus.STOPPED, instanceStatus.CREATE_ERROR}) { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是关机和创建失败,不允许被删除", instanceId), fmt.Sprintf("unsupported delete instance %s", instanceId))) + } + instances = append(instances, entity) + } + + for _, entity := range instances { + if entity.Status == instanceStatus.CREATE_ERROR { //创建错误的实例,不用走完整的删除逻辑,直接释放各种资源就行 + //释放销毁实例使用的各种资源 + if err := rInstanceSshkeyDao.DeleteInstanceSshkeyByInstanceID(logger, entity.InstanceID); err != nil { + logger.Warn("DeleteInstance DeleteInstanceSshkeyByInstanceID sql error:", entity.InstanceID, err.Error()) + } + deviceEntiry, err := deviceDao.GetDeviceById(logger, entity.DeviceID) + if err != nil { + logger.Warnf("delete error status instance.GetDeviceById error, device_id:%s, error:%s", entity.DeviceID, err.Error()) + return err + } + device := &deviceDao.Device{ + Sn: deviceEntiry.Sn, + ManageStatus: baseLogic.PUTAWAY, //删除实例以后,设备表的某些状态更改 + } + if err := deviceDao.UpdateDeviceBySn(logger, device); err != nil { + logger.Warnf("update device error,deviceSN:%s, error:%s", device.Sn, err.Error()) + return err + } + if err := commandDao.DeleteCommandBySn(logger, deviceEntiry.Sn); err != nil { + logger.Warn("DeleteInstance DeleteCommandBySn sql error:", entity.InstanceID, err.Error()) + } + + entity.IsDel = 1 + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("DeleteInstance UpdateInstanceById sql error:", entity.InstanceID, err.Error()) + return err + } + + return nil + } + + entity.Status = instanceStatus.DESTROYING + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + entity.DeletedTime = int(time.Now().Unix()) + if err := instanceDao.UpdateInstanceById(logger, entity); err != nil { + logger.Warn("DeleteInstance UpdateInstanceById sql error:", entity.InstanceID, err.Error()) + return err + } + //释放销毁实例使用的各种资源 + if err := rInstanceSshkeyDao.DeleteInstanceSshkeyByInstanceID(logger, entity.InstanceID); err != nil { + logger.Warn("DeleteInstance DeleteInstanceSshkeyByInstanceID sql error:", entity.InstanceID, err.Error()) + } + if err := sendDeleteInstanceEvent(logger, entity.InstanceID); err != nil { + logger.Warnf("DeleteInstances.sendDeleteInstanceEvent error, instance_id:%s, error:%s", entity.InstanceID, err.Error()) + } + } + + return nil + +} + +func sendDeleteInstanceEvent(logger *log.Logger, instance_id string) error { + + logid := logger.GetPoint("logid").(string) + msg := rabbitIronicMsgApi.DeleteInstanceMessage{} + msg.ApiMessage.RequestId = logid + msg.InstanceId = instance_id + userId := logger.GetPoint("userId").(string) + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("convert DeleteInstanceMessage 2 event error:", instance_id, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warn("sendDeleteInstanceEvent SendToScheduler error, msg:%s, error:%s", util.ObjToJson(event), err.Error()) + return err + } else { + logger.Infof("sendDeleteInstanceEvent SendToScheduler success, msg:%s", util.ObjToJson(event)) + } + return nil +} + +func GetInstanceCount(logger *log.Logger, query map[string]interface{}) (int64, error) { + count, err := instanceDao.GetInstanceCount(logger, query) + if err != nil { + logger.Warnf("GetInstanceCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return 0, err + } + return count, nil +} + +func GetInstanceList(logger *log.Logger, param *requestTypes.QueryInstancesRequest, p util.Pageable) ([]*responseTypes.Instance, int64, error) { + userId := logger.GetPoint("userId").(string) + offset, limit := p.Pageable2offset() + + var deviceId string + if param.IloIP != "" || param.IPV4 != "" || param.IPV6 != "" { + q := requestTypes.QueryDevicesRequest{ + IDcID: param.IdcID, + IsAll: baseLogic.IS_ALL, + } + if param.IloIP != "" { + q.IloIP = param.IloIP + } + if param.IPV4 != "" { + q.IPV4 = param.IPV4 + } + if param.IPV6 != "" { + q.IPV6 = param.IPV6 + } + devices, _, err := deviceLogic.QueryDevices(logger, q, util.Pageable{}) + if err != nil { + logger.Warnf("GetInstanceList deviceLogic.QueryDevices error:%s", err.Error()) + return nil, 0, err + } + if len(devices) != 1 { + logger.Warnf("GetInstanceList deviceLogic.QueryDevices not one, data is:%s", util.InterfaceToJson(devices)) + return nil, 0, err + } + deviceId = devices[0].DeviceID + } + + query := map[string]interface{}{ + //"sn": c.GetString("sn"), + "project_id": param.ProjectID, + "user_id": userId, + "idc_id": param.IdcID, + } + if param.DeviceID != "" { + query["device_id"] = param.DeviceID + } else if deviceId != "" { + query["device_id"] = deviceId + } + + if param.InstanceID != "" { + query["instance_id"] = param.InstanceID + } + if param.InstanceName != "" { + query["instance_name.like"] = "%" + param.InstanceName + "%" + } + + if param.DeviceTypeID != "" { + query["device_type_id.in"] = strings.Split(param.DeviceTypeID, ",") + } + if param.Status != "" { + query["status.in"] = strings.Split(param.Status, ",") + } + count, err := instanceDao.GetInstanceCount(logger, query) + if err != nil { + logger.Warnf("GetInstanceCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*instanceDao.Instance{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = instanceDao.GetMultiInstance(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = instanceDao.GetMultiInstance(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("QueryByInstanceIds GetAllInstance sql error:", err.Error()) + return nil, 0, err + } + + instances := []*responseTypes.Instance{} + for _, entity := range entityList { + instances = append(instances, InstanceEntity2Instance(logger, entity, nil)) //列表不用raidcan信息 + } + + return instances, count, nil +} + +func StartInstances(logger *log.Logger, instanceIds []string) error { + + instances, err := instanceDao.GetInstancesByIds(logger, instanceIds) + if err != nil { + logger.Warn("GetInstancesByIds sql error:", instanceIds, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + for _, instance := range instances { + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + //可以在此增加一些逻辑判断,比如,只能处在关机模式下才可以开机,其他状态不可以。。。后续再处理这块 + if instance.Status != instanceStatus.STOPPED { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是关机", instance.InstanceID), fmt.Sprintf("unsupported start instance %s", instance.InstanceID))) + } + } + + query := map[string]interface{}{ + "instance_id.in": instanceIds, + "is_del": 0, + } + updates := map[string]interface{}{ + "status": instanceStatus.STARTING, + "updatedBy": logger.GetPoint("username").(string), + } + if err := instanceDao.UpdateInstances(logger, query, updates); err != nil { + logger.Warn("StartInstance UpdateInstanceById sql error:", instanceIds, err.Error()) + return err + } + return sendStartInstanceEvent(logger, instanceIds) +} + +func StopInstances(logger *log.Logger, instanceIds []string) error { + + instances, err := instanceDao.GetInstancesByIds(logger, instanceIds) + if err != nil { + logger.Warn("GetInstancesByIds sql error:", instanceIds, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + for _, instance := range instances { + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + //可以在此增加一些逻辑判断,比如,只能处在关机模式下才可以开机,其他状态不可以。。。后续再处理这块 + if instance.Status != instanceStatus.RUNNING { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是运行中", instance.InstanceID), fmt.Sprintf("unsupported stop instance %s", instance.InstanceID))) + } + } + + query := map[string]interface{}{ + "instance_id.in": instanceIds, + "is_del": 0, + } + updates := map[string]interface{}{ + "status": instanceStatus.STOPPING, + "updatedBy": logger.GetPoint("username").(string), + } + if err := instanceDao.UpdateInstances(logger, query, updates); err != nil { + logger.Warn("StopInstance UpdateInstanceById sql error:", instanceIds, err.Error()) + return err + } + return sendStopInstanceEvent(logger, instanceIds) +} + +//logger里面的userid为当前操作用户的userId,拥有者和共享者都有权限操作/20231218普通运营平台用户也拥有所有实例的全部操作权限 +func InstanceOwnedCheck(logger *log.Logger, instance *instanceDao.Instance) bool { + + userId := logger.GetPoint("userId").(string) + + u, err := userDao.GetUserById(logger, userId) + if err != nil { + logger.Warnf("InstanceOwnedCheck.GetUserById error, userid:%s, error:%s", userId, err.Error()) + return false + } + if u.RoleID == baseLogic.ROLE_ADMIN_UUID { //超级管理员有权限管理一切 + return true + } + if u.RoleID == baseLogic.ROLE_OPERATOR_UUID { //普通运营平台用户也有权限操作所有实例 + return true + } + + if instance == nil { + return false + } + if instance.UserID == userId { + return true + } + project, err := projectDao.GetProjectById(logger, instance.ProjectID) + if err == nil { + return false + } + if project.UserID == userId { + return true + } + + sha, _ := sharingProjectDao.GetSharingsByProjectId(logger, project.ProjectID) + for _, s := range sha { + if s.SharedUserID == userId { + return true + } + } + return false + +} + +func RestartInstances(logger *log.Logger, instanceIds []string) error { + + instances, err := instanceDao.GetInstancesByIds(logger, instanceIds) + if err != nil { + logger.Warn("GetInstancesByIds sql error:", instanceIds, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + for _, instance := range instances { + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + //可以在此增加一些逻辑判断,比如,只能处在关机模式下才可以开机,其他状态不可以。。。后续再处理这块 + if instance.Status != instanceStatus.RUNNING { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是运行中", instance.InstanceID), fmt.Sprintf("unsupported restart instance %s", instance.InstanceID))) + } + } + + query := map[string]interface{}{ + "instance_id.in": instanceIds, + "is_del": 0, + } + updates := map[string]interface{}{ + "status": instanceStatus.RESTARTING, + "updatedBy": logger.GetPoint("username").(string), + } + if err := instanceDao.UpdateInstances(logger, query, updates); err != nil { + logger.Warn("restartInstances UpdateInstanceById sql error:", instanceIds, err.Error()) + return err + } + return sendRestartInstanceEvent(logger, instanceIds) +} + +func ResetInstancePasswd(logger *log.Logger, instance_id string, passwd string) error { + instance, err := instanceDao.GetInstanceById(logger, instance_id) + if err != nil { + return err + } + if instance.Status != instanceStatus.STOPPED && instance.Status != instanceStatus.RESETPASSWD_ERROR { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是已关机或重置失败状态", instance.InstanceID), fmt.Sprintf("unsupported reset password instance %s", instance.InstanceID))) + + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + if instance.Status == instanceStatus.RESETPASSWD_ERROR { //再次重置密码,需要把上次重置的command都删除掉 + if err := commandDao.DeleteCommandByInstanceIdAndTask(logger, instance_id, "InstanceResetPassword"); err != nil { + logger.Warn("re_resetpasswd.DeleteCommandByInstanceIdAndTask error:", instance_id, err.Error()) + return err + } + } + + instance.Status = instanceStatus.RESETTING_PASSWORD + instance.UpdatedBy = logger.GetPoint("username").(string) + instance.UpdatedTime = int(time.Now().Unix()) + if err := instanceDao.UpdateInstanceById(logger, instance); err != nil { + logger.Warn("UpdateInstanceById error:", instance_id, err.Error()) + return err + } + if err := resetPasswordSendMq(logger, instance_id, passwd, "ResetPassword"); err != nil { + return err + } + + return nil +} + +func ResetInstancesPasswd(logger *log.Logger, instanceIds []string, passwd string) error { + instanceEntities := []*instanceDao.Instance{} + for _, v := range instanceIds { + instance, err := instanceDao.GetInstanceById(logger, v) + if err != nil { + return err + } + if instance.Status != instanceStatus.STOPPED { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是已关机", instance.InstanceID), fmt.Sprintf("unsupported reset password instance %s", instance.InstanceID))) + + } + + if !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + instanceEntities = append(instanceEntities, instance) + } + + query := map[string]interface{}{ + "instance_id.in": instanceIds, + "is_del": 0, + } + updates := map[string]interface{}{ + "status": instanceStatus.RESETTING_PASSWORD, + "updatedBy": logger.GetPoint("username").(string), + } + if err := instanceDao.UpdateInstances(logger, query, updates); err != nil { + logger.Warnf("resetInstancesPasswd UpdateInstances sql error, instanceIds:%s, error:%s", strings.Join(instanceIds, ","), err.Error()) + return err + } + for _, instanceId := range instanceIds { + if err := resetPasswordSendMq(logger, instanceId, passwd, "ResetPassword"); err != nil { + logger.Warnf("resetInstancesPasswd resetPasswordSendMq error, instanceId:%s, error:%s", instanceId, err.Error()) + } + } + return nil +} + +func resetPasswordSendMq(logger *log.Logger, instance_id, password, action string) error { + + logid := logger.GetPoint("logid").(string) + msg := rabbitIronicMsgApi.InstanceResetPasswordMessage{} + msg.ApiMessage.RequestId = logid + msg.InstanceId = instance_id + msg.Password = password + msg.Action = action + userId := logger.GetPoint("userId").(string) + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("convert InstanceResetPasswordMessage 2 event error:", instance_id, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warnf("resetPasswordSendMq SendToScheduler error, msg:%s, error:%s", util.ObjToJson(event), err.Error()) + return err + } else { + logger.Infof("resetPasswordSendMq SendToScheduler success, msg:%s", util.ObjToJson(event)) + } + return nil +} + +func ReinstallInstance(logger *log.Logger, instance_id string, param *requestTypes.ReinstallInstanceRequest) error { + + instance, _ := instanceDao.GetInstanceById(logger, instance_id) + if instance == nil || !InstanceOwnedCheck(logger, instance) { + panic(constant.PermissionDenyForObject) + } + + if instance.Status != instanceStatus.STOPPED && instance.Status != instanceStatus.REINSTALL_ERROR { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 状态不是已关机或重装失败状态", instance.InstanceID), fmt.Sprintf("unsupported reset password instance %s", instance.InstanceID))) + } + + image_instance, _ := imageLogic.GetByImageId(logger, param.ImageID) + if image_instance == nil { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 所选镜像信息错误", instance.InstanceID), fmt.Sprintf("unsupported image for instance %s", instance.InstanceID))) + + } + + // if image_instance.Format == imageFormat.QCOW2 && image_param.Format != imageFormat.QCOW2 { + // //EMPTY + // } + device, err := deviceLogic.GetAndCheckById(logger, instance.DeviceID) + if err != nil { + return err + } + + q := requestTypes.QueryDeviceTypeImageRequest{ + DeviceTypeID: device.DeviceTypeID, + ImageID: param.ImageID, + } + p := util.Pageable{ + PageSize: 1, + } + imageE, _, _ := deviceTypeLogic.QueryDeviceTypeImage(logger, &q, p) + if imageE == nil { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 所选镜像和机型不匹配", instance.InstanceID), fmt.Sprintf("selected image and device_type not match for instance %s", instance.InstanceID))) + + } + instance.ImageID = param.ImageID + + var keep_data bool = true //默认保留数据 + + if param.SshKeyID != "" { + ssh, _ := sshkeyLogic.GetSshkeyById(logger, param.SshKeyID) + if ssh == nil { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 所选sshkey非法", instance.InstanceID), fmt.Sprintf("validated sshkey for instance %s", instance.InstanceID))) + + } + } + if param.HostName != "" { + instance.Hostname = param.HostName + } + if param.Password != "" { + param.SshKeyID = "" //如果设置了自定义密码,keypairId变为空 + } + if param.Password == "" && param.SshKeyID == "" { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("实例 %s 所选password和sshkey不能同时为空", instance.InstanceID), fmt.Sprintf("password and sshkey cannot both empty for instance %s", instance.InstanceID))) + + } + if param.BootMode != "" { + instance.BootMode = param.BootMode + } + + if instance.Status == instanceStatus.REINSTALL_ERROR { //再次重装,需要把上次重装的command都删除掉 + if err := commandDao.DeleteCommandByInstanceIdAndTask(logger, instance_id, "ReinstallInstance"); err != nil { + logger.Warn("re_reinstallinstance.DeleteCommandByInstanceIdAndTask error:", instance_id, err.Error()) + return err + } + + //中间态的操作日志都删除掉,防止脏数据循环影响后续操作 + q := map[string]interface{}{ + "is_del": 0, + "instance_id": instance_id, + "result": "doing", + } + u := map[string]interface{}{ + "is_del": 1, + } + if err := auditLogsDao.UpdateMultiAuditLogs(logger, q, u); err != nil { + logger.Warn("re_reinstallinstance.UpdateMultiAuditLogs error:", instance_id, err.Error()) + } + } + + instance.Status = instanceStatus.REINSTALLING + instance.UpdatedTime = int(time.Now().Unix()) + if err := instanceDao.UpdateInstanceById(logger, instance); err != nil { + logger.Warn("UpdateInstanceById error:", instance_id, err.Error()) + return err + } + saveInstancePartitions(logger, param, instance, device.DeviceTypeID) + userData := getInstanceUserData(logger, requestTypes.CreateInstanceRequest{}, param.InstallBmpAgent) + return sendReinstallInstanceEvent(logger, instance_id, keep_data, param.Password, userData) +} + +func getInstanceUserData(logger *log.Logger, param requestTypes.CreateInstanceRequest, installBmpAgent bool) string { + + if installBmpAgent { + + bmpImageHost, err := beego.AppConfig.String("bmp_image_host") + if err != nil { + logger.Warnf("getInstanceUserData.get bmp_image_host error:%s", err.Error()) + } + bmpImagePort, err := beego.AppConfig.String("bmp_image_port") + if err != nil { + logger.Warnf("getInstanceUserData.get bmp_image_port error:%s", err.Error()) + } + + tpl := `#!/bin/bash + + readonly WORKSPACE_DIR=/tmp/ + AGENT_BIN=bmp-agent.bin + ########################################### + + cd ${WORKSPACE_DIR} + echo "10.208.12.72 bmp-agent-proxy" >> /etc/hosts + AGENT_URL=http://bmp-agent-proxy:10000/${AGENT_BIN} + + + + curl ${AGENT_URL} -O + chmod +x ${AGENT_BIN} + sh +x ${AGENT_BIN}` + + content := strings.Replace(tpl, "10.208.12.72", bmpImageHost, -1) + content = strings.Replace(content, "10000", bmpImagePort, -1) + return base64.StdEncoding.EncodeToString([]byte(content)) + + } + return "" + +} + +func sendReinstallInstanceEvent(logger *log.Logger, instance_id string, keep_data bool, password string, userData string) error { + + logid := logger.GetPoint("logid").(string) + msg := rabbitIronicMsgApi.ReinstallInstanceMessage{} + msg.ApiMessage.RequestId = logid + msg.InstanceId = instance_id + msg.KeepData = keep_data + msg.Password = password + msg.UserData = userData + userId := logger.GetPoint("userId").(string) + event, err := rabbitEvent.NewEvent(msg, logid, userId) + if err != nil { + logger.Warn("convert ReinstallInstanceMessage 2 event error:", instance_id, err.Error()) + return err + } + if err := rabbitMq.SendToApi2Scheduler(event); err != nil { + logger.Warnf("sendReinstallInstanceEvent SendToScheduler error, msg:%s, error:%s", util.ObjToJson(event), err.Error()) + return err + } else { + logger.Infof("sendReinstallInstanceEvent SendToScheduler success, msg:%s", util.ObjToJson(event)) + } + return nil +} + +//针对重装的情况 +func saveInstancePartitions(logger *log.Logger, param *requestTypes.ReinstallInstanceRequest, instance *instanceDao.Instance, deviceTypeId string) error { + partitions, err := buildPartitions(logger, param, instance, deviceTypeId) + if err != nil { + logger.Warnf("buildPartitions %s error:%s", instance.InstanceID, err.Error()) + return err + } + for idx, v := range partitions { + v.InstancePartitionID = commonUtil.GetRandString("ipt-", namespacePrefix.IMAGE_ID_LENGTH, false, true, true) + v.Number = idx + 1 + partitions[idx] = v + } + + if err := instancePartitionDao.DeletePartitionsByInstanceId(logger, instance.InstanceID); err != nil { + logger.Warnf("DeletePartitionsByInstanceId %s error:%s", instance.InstanceID, err.Error()) + } + if len(partitions) > 0 { + if _, err := instancePartitionDao.AddMultiInstancePartition(logger, partitions); err != nil { + logger.Warnf("AddMultiInstancePartition error, partitions:%s, error:%s", util.ObjToJson(partitions), err.Error()) + return err + } + logger.Infof("AddMultiInstancePartition success, instanceId:%s", instance.InstanceID) + } + return nil +} + +func buildPartitions(logger *log.Logger, param *requestTypes.ReinstallInstanceRequest, instance *instanceDao.Instance, deviceTypeId string) ([]*instancePartitionDao.InstancePartition, error) { + if len(param.SystemPartition) == 0 && len(param.DataPartition) == 0 { + return nil, nil + } + image_partitions, err := rDeviceTypeImagePartitionDao.GetByDeviceTypeAndImageId(logger, deviceTypeId, param.ImageID) + if err != nil { + logger.Warn("buildPartitions.GetByDeviceTypeAndImageId error:", deviceTypeId, param.ImageID, err.Error()) + } + if len(image_partitions) == 0 { + return nil, nil + } + imagePartitionEntity := image_partitions[0] + partitions := []*instancePartitionDao.InstancePartition{} + if len(param.SystemPartition) > 0 { + for _, partition := range param.SystemPartition { + system_partition := PartitionInfo2Entity(partition) + system_partition.InstanceID = instance.InstanceID + system_partition.ImageID = instance.ImageID + system_partition.DeviceTypeID = deviceTypeId + system_partition.BootMode = imagePartitionEntity.BootMode + if strings.EqualFold(system_partition.PartitionMountPoint, "/") { + system_partition.PartitionType = "root" + } else if strings.EqualFold(system_partition.PartitionMountPoint, "/boot") { + system_partition.PartitionType = "boot" + } else { + system_partition.PartitionType = "system" + } + partitions = append(partitions, &system_partition) + } + } + + if len(param.DataPartition) > 0 { + for _, partition := range param.DataPartition { + data_partition := PartitionInfo2Entity(partition) + data_partition.InstanceID = instance.InstanceID + data_partition.ImageID = instance.ImageID + data_partition.DeviceTypeID = deviceTypeId + data_partition.BootMode = imagePartitionEntity.BootMode + data_partition.PartitionType = "data" + partitions = append(partitions, &data_partition) + } + } + + return partitions, nil + +} + +func PartitionInfo2Entity(param requestTypes.Partition) instancePartitionDao.InstancePartition { + res := instancePartitionDao.InstancePartition{ + PartitionSize: param.Size, + PartitionFsType: param.FsType, + PartitionMountPoint: param.MountPoint, + } + if strings.EqualFold(param.MountPoint, "/") { + res.PartitionLabel = "l_root" + } else if strings.EqualFold(param.MountPoint, "swap") { + res.PartitionLabel = "l_swap" + } else { + label := strings.Replace(param.MountPoint, "/", "l_", -1) + res.PartitionLabel = label + } + res.SystemDiskLabel = "gpt" + res.DataDiskLabel = "gpt" + return res +} + +func GetInstanceBySn(logger *log.Logger, sn string) (*responseTypes.Instance, error) { + deviceEntity, err := deviceDao.GetBySn(logger, sn) + if err != nil { + logger.Warnf("GetInstanceBySn.GetBySn sql error, sn:%s, error:%s", sn, err.Error()) + } + deviceId := deviceEntity.DeviceID + instanceEntity, err := instanceDao.GetInstanceByDeviceId(logger, deviceId) + if err != nil { + logger.Warnf("GetInstanceByDeviceId sql error, uuid:%s, error:%s", deviceId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + return &responseTypes.Instance{ + InstanceID: instanceEntity.InstanceID, + InstanceName: instanceEntity.InstanceName, + DeviceID: instanceEntity.DeviceID, + Sn: sn, + IloIP: deviceEntity.IloIP, + DeviceTypeID: deviceEntity.DeviceTypeID, + }, nil +} diff --git a/bmp-openapi/logic/mailLogic/MailUtil.go b/bmp-openapi/logic/mailLogic/MailUtil.go new file mode 100644 index 0000000..52e70b9 --- /dev/null +++ b/bmp-openapi/logic/mailLogic/MailUtil.go @@ -0,0 +1,118 @@ +package mailLogic + +import ( + "bytes" + "crypto/tls" + "errors" + "fmt" + "html/template" + "strconv" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/mailDao" + log "coding.jd.com/aidc-bmp/bmp_log" + + "github.com/go-gomail/gomail" +) + +func DialMail(logger *log.Logger, smtpHost string, smtpPort int, from, password, tos string, subject, msg string) error { + m := gomail.NewMessage() + to := strings.Split(tos, ",") + s := BaseSubjest + m.SetHeader("From", from) + m.SetHeader("To", to...) + m.SetHeader("Subject", s+":"+subject) + m.SetBody("text/html", msg) + + username := strings.Split(from, "@")[0] + + d := gomail.NewPlainDialer( + smtpHost, + smtpPort, + username, + password) + + if d == nil { + return errors.New("Initialize Dialer Error") + } + + d.TLSConfig = &tls.Config{ServerName: d.Host, InsecureSkipVerify: true} + + // Send the email. + if err := d.DialAndSend(m); err != nil { + logger.Warnf("SendMail msg=%s : %s\n", msg, err.Error()) + return err + } + return nil +} + +// SendMail use smtp to send mail +func SendMail(logger *log.Logger, subject, msg string) error { + + mailEntity, err := mailDao.GetMailMessage(logger) + if err != nil { + logger.Warnf("SendMail.GetMail error:%s", err.Error()) + return err + } + tos := mailEntity.To + from := mailEntity.AdminAddr + smtpHost := mailEntity.ServerAddr + smtpPort, err := strconv.Atoi(mailEntity.ServerPort) + if err != nil { + logger.Warnf("SendMail.ServerPort invalid, port:%s", mailEntity.ServerPort) + return err + } + username := strings.Split(from, "@")[0] + password := mailEntity.AdminPass + + m := gomail.NewMessage() + to := strings.Split(tos, ",") + s := BaseSubjest + m.SetHeader("From", from) + m.SetHeader("To", to...) + m.SetHeader("Subject", s+"-"+subject) + m.SetBody("text/html", msg) + + d := gomail.NewPlainDialer( + smtpHost, + smtpPort, + username, + password) + + if d == nil { + return errors.New("Initialize Dialer Error") + } + + d.TLSConfig = &tls.Config{ServerName: d.Host, InsecureSkipVerify: true} + + // Send the email. + if err := d.DialAndSend(m); err != nil { + fmt.Printf("SendMail msg=%s : %s\n", msg, err.Error()) + return err + } + return nil +} + +//SendMailByTpl send template mail +func SendMailByTpl(logger *log.Logger, tplName, subject string, obj interface{}) error { + tpl, errParse := template.New("Mail").Parse(tplName) + if errParse != nil { + fmt.Printf("Parse Template Error:%s\n", errParse.Error()) + return errParse + } + + byteW := new(bytes.Buffer) + err := tpl.Execute(byteW, obj) + if err != nil { + fmt.Printf("Execute Template Error:%s\n", err.Error()) + return err + } + + errMail := SendMail(logger, subject, byteW.String()) + if errMail != nil { + fmt.Printf("Send Mail Error:%s\n", errMail.Error()) + return errMail + } + + return nil +} diff --git a/bmp-openapi/logic/mailLogic/licenseAlreadyTimeout.go b/bmp-openapi/logic/mailLogic/licenseAlreadyTimeout.go new file mode 100644 index 0000000..ab846c4 --- /dev/null +++ b/bmp-openapi/logic/mailLogic/licenseAlreadyTimeout.go @@ -0,0 +1,147 @@ +package mailLogic + +const MessageLicenseAlreadyTimeoutTemplate string = ` + + + + + + + 系统消息(已到期) + + + +
+
+ BMP裸金属管理平台 +
+
+

尊敬的用户 admin,您好!

+

+ 您的云平台许可证已于({{.LienseEndTime}})到期,续费后可继续正常使用云平台功能。详情如下: +

+ + + + + + + + + + + + + + + + + + + +
版本名称版本号开始时间到期时间许可状态
{{.LicenseName}}{{.LicenseNumber}}{{.LienseStartTime}}{{.LienseEndTime}}{{.Status}}
+
+ +
+ + +` diff --git a/bmp-openapi/logic/mailLogic/licenseNearlyTimeout.go b/bmp-openapi/logic/mailLogic/licenseNearlyTimeout.go new file mode 100644 index 0000000..d2ff21c --- /dev/null +++ b/bmp-openapi/logic/mailLogic/licenseNearlyTimeout.go @@ -0,0 +1,160 @@ +package mailLogic + +const MessageLicenseNearlyTimeoutTemplate string = ` + + + + + + 系统消息(到期前) + + + +
+
+ BMP裸金属管理平台 +
+
+

尊敬的用户 admin,您好!

+

+ 您的云平台许可证将于 {{.Detail}}天 后({{.LienseEndTime}})到期,续费后可继续正常使用云平台功能。详情如下: +

+ + + + + + + + + + + + + + + + + + + +
版本名称版本号开始时间到期时间许可状态
{{.LicenseName}}{{.LicenseNumber}}{{.LienseStartTime}}{{.LienseEndTime}}{{.Status}}
+
+ +
+ + +` + +type MailMessage struct { + MessageID string + MessageType string + MessageSubType string + ResourceType string + FinishTime string + LicenseName string + LicenseNumber string + LienseStartTime string + LienseEndTime string + Detail string + Status string +} diff --git a/bmp-openapi/logic/mailLogic/subject.go b/bmp-openapi/logic/mailLogic/subject.go new file mode 100644 index 0000000..733b1b8 --- /dev/null +++ b/bmp-openapi/logic/mailLogic/subject.go @@ -0,0 +1,5 @@ +package mailLogic + +const BaseSubjest string = "BMP裸金属管理平台" +const MailDialTestSubjest string = "测试邮件" +const MailDialTestContent string = "这是一封测试邮件" diff --git a/bmp-openapi/logic/messageLogic/messageLogic.go b/bmp-openapi/logic/messageLogic/messageLogic.go new file mode 100644 index 0000000..98b9047 --- /dev/null +++ b/bmp-openapi/logic/messageLogic/messageLogic.go @@ -0,0 +1,776 @@ +package messageLogic + +import ( + "errors" + "strconv" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/mailDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/messageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/projectDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/mailLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + messageType "git.jd.com/cps-golang/ironic-common/ironic/enums/MessageType" +) + +var Types2ShowEn = map[string]string{ + //操作消息 + messageType.MessageTypeOperation: "operation", + //系统消息 + messageType.MessageTypeSystem: "system", + //监控消息 + messageType.MessageTypeOobMonitor: "oob-monitor", + //带内告警消息 + messageType.MessageTypeInBondAlert: "inbond-alert", + + //操作消息类型 + messageType.MessageSubTypeCollectHardwareInfo: "CollectHardwareInfo", + messageType.MessageSubTypeCreateDevices: "CreateDevices", + messageType.MessageSubTypeCreateInstances: "CreateInstances", + messageType.MessageSubTypeCutDeviceStock: "CutDeviceStock", + messageType.MessageSubTypeDeleteInstance: "DeleteInstance", + messageType.MessageSubTypeInstanceResetPassword: "InstanceResetPassword", + messageType.MessageSubTypePutawayDevice: "PutawayDevice", + messageType.MessageSubTypeReinstallInstance: "ReinstallInstance", + messageType.MessageSubTypeRestartInstances: "RestartInstances", + messageType.MessageSubTypeStartInstances: "StartInstances", + messageType.MessageSubTypeStopInstances: "StopInstances", + //系统消息类型 + messageType.MessageSubTypeLicenseNearTimeout: "LicenseNearTimeout", + //监控消息类型 + messageType.MessageSubTypePowerFault: "Power Fault", + messageType.MessageSubTypeTemperatureFault: "Temp Fault", + messageType.MessageSubTypeCPUFault: "CPU Fault", + messageType.MessageSubTypeMemFault: "Mem Fault", + messageType.MessageSubTypeDiskFault: "Disk Fault", + messageType.MessageSubTypeOtherFault: "Other Fault", + + //带内告警 + messageType.MessageSubTypeCPUUsage: "CPU Usage", + messageType.MessageSubTypeMemoryUsage: "Memory Usage", + messageType.MessageSubTypeMemoryUsed: "Memory Used", + messageType.MessageSubTypeDiskUsed: "Disk Used", + messageType.MessageSubTypeDiskUsage: "Disk Usage", + messageType.MessageSubTypeDiskReadTraffic: "Disk Read Traffic", + messageType.MessageSubTypeDiskWriteTraffic: "Disk Write Traffic", + messageType.MessageSubTypeDiskReadIOPS: "Disk Read IOPS", + messageType.MessageSubTypeDiskWriteIOPS: "Disk Write IOPS", + messageType.MessageSubTypeNetworkIngressTraffic: "Network Ingress Traffic", + messageType.MessageSubTypeNetworkEgressTraffic: "Network Egress Traffic", + messageType.MessageSubTypeNetworkIngressPackets: "Network Ingress Packets", + messageType.MessageSubTypeNetworkEgressPackets: "Network Egress Packets", + messageType.MessageSubTypeLoadAverage1min: "Load Average 1min", + messageType.MessageSubTypeLoadAverage5min: "Load Average 5min", + messageType.MessageSubTypeLoadAverage15min: "Load Average 15min", + messageType.MessageSubTypeTotalTCPConnections: "Total TCP Connections", + messageType.MessageSubTypeEstablishedTCPConnections: "Established TCP Connections", + messageType.MessageSubTypeTotalProcessCount: "Total Process Count", +} + +var Types2ShowZh = map[string]string{ + //操作消息 + messageType.MessageTypeOperation: "操作消息", + //系统消息 + messageType.MessageTypeSystem: "系统消息", + //监控消息 + messageType.MessageTypeOobMonitor: "故障消息", + //带内告警消息 + messageType.MessageTypeInBondAlert: "报警消息", + + //操作消息类型 + messageType.MessageSubTypeCollectHardwareInfo: "采集", + messageType.MessageSubTypeCreateDevices: "上传设备", + messageType.MessageSubTypeCreateInstances: "创建实例", + messageType.MessageSubTypeCutDeviceStock: "削减库存", + messageType.MessageSubTypeDeleteInstance: "删除实例", + messageType.MessageSubTypeInstanceResetPassword: "重置密码", + messageType.MessageSubTypePutawayDevice: "设备上架", + messageType.MessageSubTypeReinstallInstance: "重装系统", + messageType.MessageSubTypeRestartInstances: "重启实例", + messageType.MessageSubTypeStartInstances: "开机", + messageType.MessageSubTypeStopInstances: "关机", + //系统消息类型 + messageType.MessageSubTypeLicenseNearTimeout: "许可证到期", + //监控消息类型 + messageType.MessageSubTypePowerFault: "电力故障", + messageType.MessageSubTypeTemperatureFault: "温控故障", + messageType.MessageSubTypeCPUFault: "CPU故障", + messageType.MessageSubTypeMemFault: "内存故障", + messageType.MessageSubTypeDiskFault: "硬盘故障", + messageType.MessageSubTypeOtherFault: "其他故障", + + //带内告警 + messageType.MessageSubTypeCPUUsage: "CPU使用率", + messageType.MessageSubTypeMemoryUsage: "内存使用率", + messageType.MessageSubTypeMemoryUsed: "内存使用量", + messageType.MessageSubTypeDiskUsed: "磁盘使用量", + messageType.MessageSubTypeDiskUsage: "磁盘使用率", + messageType.MessageSubTypeDiskReadTraffic: "磁盘读流量", + messageType.MessageSubTypeDiskWriteTraffic: "磁盘写流量", + messageType.MessageSubTypeDiskReadIOPS: "磁盘读IOPS", + messageType.MessageSubTypeDiskWriteIOPS: "磁盘写IOPS", + messageType.MessageSubTypeNetworkIngressTraffic: "网卡进流量", + messageType.MessageSubTypeNetworkEgressTraffic: "网卡出流量", + messageType.MessageSubTypeNetworkIngressPackets: "网络进包数量", + messageType.MessageSubTypeNetworkEgressPackets: "网络出包数量", + messageType.MessageSubTypeLoadAverage1min: "平均负载均衡1min", + messageType.MessageSubTypeLoadAverage5min: "平均负载均衡5min", + messageType.MessageSubTypeLoadAverage15min: "平均负载均衡15min", + messageType.MessageSubTypeTotalTCPConnections: "TCP总连接数", + messageType.MessageSubTypeEstablishedTCPConnections: "TCP正常接数", + messageType.MessageSubTypeTotalProcessCount: "总进程数", +} + +var ShowEn2Types = map[string]string{ + //操作消息 + "operation": messageType.MessageTypeOperation, + //系统消息 + "system": messageType.MessageTypeSystem, + //监控消息 + "oob-monitor": messageType.MessageTypeOobMonitor, + //带内告警消息 + "inbond-alert": messageType.MessageTypeInBondAlert, + + //操作消息类型 + "CollectHardwareInfo": messageType.MessageSubTypeCollectHardwareInfo, + "CreateDevices": messageType.MessageSubTypeCreateDevices, + "CreateInstances": messageType.MessageSubTypeCreateInstances, + "CutDeviceStock": messageType.MessageSubTypeCutDeviceStock, + "DeleteInstance": messageType.MessageSubTypeDeleteInstance, + "InstanceResetPassword": messageType.MessageSubTypeInstanceResetPassword, + "PutawayDevice": messageType.MessageSubTypePutawayDevice, + "ReinstallInstance": messageType.MessageSubTypeReinstallInstance, + "RestartInstances": messageType.MessageSubTypeRestartInstances, + "StartInstances": messageType.MessageSubTypeStartInstances, + "StopInstances": messageType.MessageSubTypeStopInstances, + //系统消息类型 + "LicenseNearTimeout": messageType.MessageSubTypeLicenseNearTimeout, + //监控消息类型 + "Power Fault": messageType.MessageSubTypePowerFault, + "Temp Fault": messageType.MessageSubTypeTemperatureFault, + "CPU Fault": messageType.MessageSubTypeCPUFault, + "Mem Fault": messageType.MessageSubTypeMemFault, + "Disk Fault": messageType.MessageSubTypeDiskFault, + "Other Fault": messageType.MessageSubTypeOtherFault, + + //带内告警 + "CPU Usage": messageType.MessageSubTypeCPUUsage, + "Memory Usage": messageType.MessageSubTypeMemoryUsage, + "Memory Used": messageType.MessageSubTypeMemoryUsed, + "Disk Used": messageType.MessageSubTypeDiskUsed, + "Disk Usage": messageType.MessageSubTypeDiskUsage, + "Disk Read Traffic": messageType.MessageSubTypeDiskReadTraffic, + "Disk Write Traffic": messageType.MessageSubTypeDiskWriteTraffic, + "Disk Read IOPS": messageType.MessageSubTypeDiskReadIOPS, + "Disk Write IOPS": messageType.MessageSubTypeDiskWriteIOPS, + "Network Ingress Traffic": messageType.MessageSubTypeNetworkIngressTraffic, + "Network Egress Traffic": messageType.MessageSubTypeNetworkEgressTraffic, + "Network Ingress Packets": messageType.MessageSubTypeNetworkIngressPackets, + "Network Egress Packets": messageType.MessageSubTypeNetworkEgressPackets, + "Load Average 1min": messageType.MessageSubTypeLoadAverage1min, + "Load Average 5min": messageType.MessageSubTypeLoadAverage5min, + "Load Average 15min": messageType.MessageSubTypeLoadAverage15min, + "Total TCP Connections": messageType.MessageSubTypeTotalTCPConnections, + "Established TCP Connections": messageType.MessageSubTypeEstablishedTCPConnections, + "Total Process Count": messageType.MessageSubTypeTotalProcessCount, +} + +var ShowZh2Types = map[string]string{ + //操作消息 + "操作消息": messageType.MessageTypeOperation, + //系统消息 + "系统消息": messageType.MessageTypeSystem, + //监控消息 + "故障消息": messageType.MessageTypeOobMonitor, + //带内告警消息 + "报警消息": messageType.MessageTypeInBondAlert, + + //操作消息类型 + "采集": messageType.MessageSubTypeCollectHardwareInfo, + "上传设备": messageType.MessageSubTypeCreateDevices, + "创建实例": messageType.MessageSubTypeCreateInstances, + "削减库存": messageType.MessageSubTypeCutDeviceStock, + "删除实例": messageType.MessageSubTypeDeleteInstance, + "重置密码": messageType.MessageSubTypeInstanceResetPassword, + "设备上架": messageType.MessageSubTypePutawayDevice, + "重装系统": messageType.MessageSubTypeReinstallInstance, + "重启实例": messageType.MessageSubTypeRestartInstances, + "开机": messageType.MessageSubTypeStartInstances, + "关机": messageType.MessageSubTypeStopInstances, + //系统消息类型 + "许可证到期": messageType.MessageSubTypeLicenseNearTimeout, + //监控消息类型 + "电力故障": messageType.MessageSubTypePowerFault, + "温控故障": messageType.MessageSubTypeTemperatureFault, + "CPU故障": messageType.MessageSubTypeCPUFault, + "内存故障": messageType.MessageSubTypeMemFault, + "硬盘故障": messageType.MessageSubTypeDiskFault, + "其他故障": messageType.MessageSubTypeOtherFault, + + //带内告警 + "CPU使用率": messageType.MessageSubTypeCPUUsage, + "内存使用率": messageType.MessageSubTypeMemoryUsage, + "内存使用量": messageType.MessageSubTypeMemoryUsed, + "磁盘使用量": messageType.MessageSubTypeDiskUsed, + "磁盘使用率": messageType.MessageSubTypeDiskUsage, + "磁盘读流量": messageType.MessageSubTypeDiskReadTraffic, + "磁盘写流量": messageType.MessageSubTypeDiskWriteTraffic, + "磁盘读IOPS": messageType.MessageSubTypeDiskReadIOPS, + "磁盘写IOPS": messageType.MessageSubTypeDiskWriteIOPS, + "网卡进流量": messageType.MessageSubTypeNetworkIngressTraffic, + "网卡出流量": messageType.MessageSubTypeNetworkEgressTraffic, + "网络进包数量": messageType.MessageSubTypeNetworkIngressPackets, + "网络出包数量": messageType.MessageSubTypeNetworkEgressPackets, + "平均负载均衡1min": messageType.MessageSubTypeLoadAverage1min, + "平均负载均衡5min": messageType.MessageSubTypeLoadAverage5min, + "平均负载均衡15min": messageType.MessageSubTypeLoadAverage15min, + "TCP总连接数": messageType.MessageSubTypeTotalTCPConnections, + "TCP正常接数": messageType.MessageSubTypeEstablishedTCPConnections, + "总进程数": messageType.MessageSubTypeTotalProcessCount, +} + +func MessageEntity2Message(logger *log.Logger, msgEntity *messageDao.WebMessage, isDetail bool) *response.Message { + if msgEntity == nil { + return nil + } + res := &response.Message{ + WebMessage: *msgEntity, + } + + if isDetail { + + if msgEntity.InstanceID != "" { + instanceEntity, err := instanceDao.GetInstanceById(logger, msgEntity.InstanceID) + if err != nil { + logger.Warnf("MessageEntity2Message.GetInstanceById error, instanceId:%s, error:%s", msgEntity.InstanceID, err.Error()) + } else { + res.IDcID = instanceEntity.IDcID + res.DeviceID = instanceEntity.DeviceID + idcEntity, err := idcDao.GetIdcById(logger, instanceEntity.IDcID) + if err != nil { + logger.Warnf("MessageEntity2Message.GetIdcById error, idcId:%s, error:%s", instanceEntity.IDcID, err.Error()) + } else { + res.IDcName = idcEntity.Name + if logger.GetPoint("language").(string) == baseLogic.EN_US { + res.IDcName = idcEntity.NameEn + } + } + res.ProjectID = instanceEntity.ProjectID + projectEntity, err := projectDao.GetProjectById(logger, instanceEntity.ProjectID) + if err != nil { + logger.Warnf("MessageEntity2Message.GetProjectById error, ProjectId:%s, error:%s", instanceEntity.ProjectID, err.Error()) + } else { + res.ProjectName = projectEntity.ProjectName + } + } + } else if msgEntity.SN != "" { + deviceEntity, err := deviceDao.GetDeviceBySn(logger, msgEntity.SN) + if err != nil { + logger.Warnf("MessageEntity2Message.GetDeviceBySn error, sn:%s, error:%s", msgEntity.SN, err.Error()) + } else { + res.IDcID = deviceEntity.IDcID + res.DeviceID = deviceEntity.DeviceID + idcEntity, err := idcDao.GetIdcById(logger, deviceEntity.IDcID) + if err != nil { + logger.Warnf("MessageEntity2Message.GetIdcById error, idcId:%s, error:%s", deviceEntity.IDcID, err.Error()) + } else { + res.IDcName = idcEntity.Name + if logger.GetPoint("language").(string) == baseLogic.EN_US { + res.IDcName = idcEntity.NameEn + } + } + + } + } + + } + return res + +} + +func AddLicenseNoticeMessage(logger *log.Logger, webMsg messageDao.WebMessage) error { + + if _, err := messageDao.AddWebMessage(logger, &webMsg); err != nil { + logger.Warnf("SendWebNotice error, msg:%s, error:%s", util.InterfaceToJson(webMsg), err.Error()) + return err + } + logger.Infof("SendWebNotice success, msg:%s", util.InterfaceToJson(webMsg)) + return nil + +} + +func HasUnreadMessage(logger *log.Logger) (bool, error) { + userId := logger.GetPoint("userId").(string) + q := map[string]interface{}{ + "is_del": 0, + // "user_id": userId, + "has_read": 0, + } + cnt, err := messageDao.GetWebMessagesByUserIdCount(logger, q) + if err != nil { + logger.Warnf("HasUnreadMessage.GetWebMessagesByUserIdCount error, userid:%s, error:%s", userId, err.Error()) + return false, err + } + return cnt != 0, nil +} + +func GetPageMessages(logger *log.Logger, param *requestTypes.QueryMessagesRequest, p util.Pageable) ([]*response.Message, int64, error) { + + userId := logger.GetPoint("userId").(string) + offset, limit := p.Pageable2offset() + + q := map[string]interface{}{ + "is_del": 0, + // "user_id": userId, + } + if param.HasRead != "" { + r, err := strconv.Atoi(param.HasRead) + if err != nil { + logger.Warnf("GetPageMessages.HasRead param error, user_id:%s, error:%s", userId, err.Error()) + return nil, 0, errors.New("param hasRead error") + } + q["has_read"] = r + } + if param.Detail != "" { + q["detail.like"] = "%" + strings.TrimSpace(param.Detail) + "%" + } + + if param.MessageType != "" { + mt := ShowEn2Types[param.MessageType] + if mt == "" { + mt = ShowZh2Types[param.MessageType] + } + if mt == "" { + mt = param.MessageType + } + q["message_type"] = mt + } + if param.MessageSubType != "" { + mts := []string{} + items := strings.Split(param.MessageSubType, ",") + for _, item := range items { + mt := ShowEn2Types[item] + if mt == "" { + mt = ShowZh2Types[item] + } + if mt == "" { + mt = item + } + mts = append(mts, mt) + } + + q["message_sub_type.in"] = mts + } + cnt, err := messageDao.GetWebMessagesByUserIdCount(logger, q) + if err != nil { + logger.Warnf("GetPageMessages.GetWebMessagesByUserIdCount error, user_id:%s, error:%s", userId, err.Error()) + return nil, 0, err + } + + var entityList []*messageDao.WebMessage + if param.IsAll == baseLogic.IS_ALL { + entityList, err = messageDao.GetMultiWebMessagesByUserId(logger, q, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = messageDao.GetMultiWebMessagesByUserId(logger, q, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("GetPageMessages GetMultiWebMessagesByUserId sql error:", err.Error()) + return nil, 0, err + } + + res := []*response.Message{} + + for _, v := range entityList { + var mt, mst string + + if logger.GetPoint("language").(string) == baseLogic.EN_US { + mt = Types2ShowEn[v.MessageType] + mst = Types2ShowEn[v.MessageSubType] + } else { + mt = Types2ShowZh[v.MessageType] + mst = Types2ShowZh[v.MessageSubType] + } + if mt == "" { + mt = v.MessageType + } + if mst == "" { + mst = v.MessageSubType + } + v.MessageType = mt + v.MessageSubType = mst + v.FaultType = v.MessageSubType + + res = append(res, MessageEntity2Message(logger, v, false)) + } + logger.Infof("debug minping, entityList2:%s", util.InterfaceToJson(entityList)) + return res, cnt, nil + +} + +func GetMessageStatistic(logger *log.Logger) (int64, int64, error) { + + userId := logger.GetPoint("userId").(string) + + q1 := map[string]interface{}{ + "is_del": 0, + // "user_id": userId, + } + q2 := map[string]interface{}{ + "is_del": 0, + // "user_id": userId, + "has_read": 0, + } + + all, err := messageDao.GetWebMessagesByUserIdCount(logger, q1) + if err != nil { + logger.Warnf("GetMessageStatistic.GetWebMessagesByUserIdCount error, user_id:%s, error:%s", userId, err.Error()) + return 0, 0, err + } + unread, err := messageDao.GetWebMessagesByUserIdCount(logger, q2) + if err != nil { + logger.Warnf("GetMessageStatistic.GetWebMessagesByUserIdCount error, user_id:%s, error:%s", userId, err.Error()) + return 0, 0, err + } + return all, unread, nil + +} + +func ReadMessages(logger *log.Logger, param *requestTypes.ReadMessagesRequest) (bool, error) { + userId := logger.GetPoint("userId").(string) + //校验messages和userid的归属关系 + q := map[string]interface{}{ + "is_del": 0, + // "user_id": userId, + "message_id.in": param.MessageIds, + } + + msgs, err := messageDao.GetAllWebMessages(logger, q) + if err != nil { + logger.Warnf("ReadMessages.GetAllWebMessages error, query:%v, error:%s", q, err.Error()) + } + if len(msgs) < len(param.MessageIds) { + logger.Warnf("ReadMessages.message_ids invalided, user_id:%s, message_ids:%s", userId, param.MessageIds) + panic(constant.BuildInvalidArgumentWithArgs("参数messageIds非法", "param messageIds invalid")) + } + + u := map[string]interface{}{ + "has_read": 1, + } + if err := messageDao.UpdateWebMessages(logger, q, u); err != nil { + logger.Warnf("ReadMessages.UpdateWebMessages error, query:%v, error:%s", q, err.Error()) + return false, err + } + return true, nil +} + +func GetMessageById(logger *log.Logger, param *requestTypes.GetMessageByIdRequest) (*response.Message, string, string, error) { + + var nextMessageId, prevMessageId string + + userId := logger.GetPoint("userId").(string) + //校验messages和userid的归属关系 + q := map[string]interface{}{ + "is_del": 0, + // "user_id": userId, + "message_id": param.MessageID, + } + + msg, err := messageDao.GetOneWebMessage(logger, q, "asc") + if err != nil { + logger.Warnf("GetOneMoreMessage.GetOneWebMessage error, user_id:%s, message_id:%s, error:%s", userId, param.MessageID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if msg.UserName == "" { + msg.UserName = "admin" + } + if msg != nil { + + if logger.GetPoint("language").(string) == baseLogic.EN_US { + msg.MessageType = Types2ShowEn[msg.MessageType] + msg.MessageSubType = Types2ShowEn[msg.MessageSubType] + } else { + msg.MessageType = Types2ShowZh[msg.MessageType] + msg.MessageSubType = Types2ShowZh[msg.MessageSubType] + } + + mid := msg.ID + nextQ := map[string]interface{}{ + "is_del": 0, + // "user_id": userId, + "id.gt": mid, + } + nextMsg, err := messageDao.GetOneWebMessage(logger, nextQ, "asc") + if err != nil { + logger.Warnf("GetOneMoreMessage.getNextmsg error:%s", err.Error()) + } + + prevQ := map[string]interface{}{ + "is_del": 0, + // "user_id": userId, + "id.lt": mid, + } + prevMsg, err := messageDao.GetOneWebMessage(logger, prevQ, "desc") + if err != nil { + logger.Warnf("GetOneMoreMessage.getPrevmsg error:%s", err.Error()) + } + + if nextMsg != nil { + nextMessageId = nextMsg.MessageID + } + if prevMsg != nil { + prevMessageId = prevMsg.MessageID + } + return MessageEntity2Message(logger, msg, true), nextMessageId, prevMessageId, nil + + } + return nil, "", "", nil + +} + +func GetMessageTypes(logger *log.Logger) response.MessageTypesResp { + if logger.GetPoint("language").(string) == baseLogic.EN_US { + return response.MessageTypesResp{ + Types2ShowEn[messageType.MessageTypeOperation]: []string{ + Types2ShowEn[messageType.MessageSubTypeCollectHardwareInfo], + Types2ShowEn[messageType.MessageSubTypeCreateDevices], + Types2ShowEn[messageType.MessageSubTypeCreateInstances], + Types2ShowEn[messageType.MessageSubTypeCutDeviceStock], + Types2ShowEn[messageType.MessageSubTypeDeleteInstance], + Types2ShowEn[messageType.MessageSubTypeInstanceResetPassword], + Types2ShowEn[messageType.MessageSubTypePutawayDevice], + Types2ShowEn[messageType.MessageSubTypeReinstallInstance], + Types2ShowEn[messageType.MessageSubTypeRestartInstances], + Types2ShowEn[messageType.MessageSubTypeStartInstances], + Types2ShowEn[messageType.MessageSubTypeStopInstances], + }, + Types2ShowEn[messageType.MessageTypeSystem]: []string{ + Types2ShowEn[messageType.MessageSubTypeLicenseNearTimeout], + }, + Types2ShowEn[messageType.MessageTypeOobMonitor]: []string{ + Types2ShowEn[messageType.MessageSubTypePowerFault], + Types2ShowEn[messageType.MessageSubTypeTemperatureFault], + Types2ShowEn[messageType.MessageSubTypeCPUFault], + Types2ShowEn[messageType.MessageSubTypeMemFault], + Types2ShowEn[messageType.MessageSubTypeDiskFault], + Types2ShowEn[messageType.MessageSubTypeOtherFault], + }, + Types2ShowEn[messageType.MessageTypeInBondAlert]: []string{ + Types2ShowEn[messageType.MessageSubTypeCPUUsage], + Types2ShowEn[messageType.MessageSubTypeMemoryUsed], + Types2ShowEn[messageType.MessageSubTypeDiskUsed], + Types2ShowEn[messageType.MessageSubTypeDiskUsage], + Types2ShowEn[messageType.MessageSubTypeDiskReadTraffic], + Types2ShowEn[messageType.MessageSubTypeDiskWriteTraffic], + Types2ShowEn[messageType.MessageSubTypeDiskReadIOPS], + Types2ShowEn[messageType.MessageSubTypeDiskWriteIOPS], + Types2ShowEn[messageType.MessageSubTypeNetworkIngressTraffic], + Types2ShowEn[messageType.MessageSubTypeNetworkEgressTraffic], + Types2ShowEn[messageType.MessageSubTypeNetworkIngressPackets], + Types2ShowEn[messageType.MessageSubTypeNetworkEgressPackets], + Types2ShowEn[messageType.MessageSubTypeLoadAverage1min], + Types2ShowEn[messageType.MessageSubTypeLoadAverage5min], + Types2ShowEn[messageType.MessageSubTypeLoadAverage15min], + Types2ShowEn[messageType.MessageSubTypeTotalTCPConnections], + Types2ShowEn[messageType.MessageSubTypeEstablishedTCPConnections], + Types2ShowEn[messageType.MessageSubTypeTotalProcessCount], + }, + } + } else { + return response.MessageTypesResp{ + Types2ShowZh[messageType.MessageTypeOperation]: []string{ + Types2ShowZh[messageType.MessageSubTypeCollectHardwareInfo], + Types2ShowZh[messageType.MessageSubTypeCreateDevices], + Types2ShowZh[messageType.MessageSubTypeCreateInstances], + Types2ShowZh[messageType.MessageSubTypeCutDeviceStock], + Types2ShowZh[messageType.MessageSubTypeDeleteInstance], + Types2ShowZh[messageType.MessageSubTypeInstanceResetPassword], + Types2ShowZh[messageType.MessageSubTypePutawayDevice], + Types2ShowZh[messageType.MessageSubTypeReinstallInstance], + Types2ShowZh[messageType.MessageSubTypeRestartInstances], + Types2ShowZh[messageType.MessageSubTypeStartInstances], + Types2ShowZh[messageType.MessageSubTypeStopInstances], + }, + Types2ShowZh[messageType.MessageTypeSystem]: []string{ + Types2ShowZh[messageType.MessageSubTypeLicenseNearTimeout], + }, + Types2ShowZh[messageType.MessageTypeOobMonitor]: []string{ + Types2ShowZh[messageType.MessageSubTypePowerFault], + Types2ShowZh[messageType.MessageSubTypeTemperatureFault], + Types2ShowZh[messageType.MessageSubTypeCPUFault], + Types2ShowZh[messageType.MessageSubTypeMemFault], + Types2ShowZh[messageType.MessageSubTypeDiskFault], + Types2ShowZh[messageType.MessageSubTypeOtherFault], + }, + Types2ShowZh[messageType.MessageTypeInBondAlert]: []string{ + Types2ShowZh[messageType.MessageSubTypeCPUUsage], + Types2ShowZh[messageType.MessageSubTypeMemoryUsed], + Types2ShowZh[messageType.MessageSubTypeDiskUsed], + Types2ShowZh[messageType.MessageSubTypeDiskUsage], + Types2ShowZh[messageType.MessageSubTypeDiskReadTraffic], + Types2ShowZh[messageType.MessageSubTypeDiskWriteTraffic], + Types2ShowZh[messageType.MessageSubTypeDiskReadIOPS], + Types2ShowZh[messageType.MessageSubTypeDiskWriteIOPS], + Types2ShowZh[messageType.MessageSubTypeNetworkIngressTraffic], + Types2ShowZh[messageType.MessageSubTypeNetworkEgressTraffic], + Types2ShowZh[messageType.MessageSubTypeNetworkIngressPackets], + Types2ShowZh[messageType.MessageSubTypeNetworkEgressPackets], + Types2ShowZh[messageType.MessageSubTypeLoadAverage1min], + Types2ShowZh[messageType.MessageSubTypeLoadAverage5min], + Types2ShowZh[messageType.MessageSubTypeLoadAverage15min], + Types2ShowZh[messageType.MessageSubTypeTotalTCPConnections], + Types2ShowZh[messageType.MessageSubTypeEstablishedTCPConnections], + Types2ShowZh[messageType.MessageSubTypeTotalProcessCount], + }, + } + } + +} + +func DeleteMessages(logger *log.Logger, param *requestTypes.DeleteMessagesRequest) (bool, error) { + userId := logger.GetPoint("userId").(string) + //校验messages和userid的归属关系 + q := map[string]interface{}{ + "is_del": 0, + // "user_id": userId, + "message_id.in": param.MessageIds, + } + + msgs, err := messageDao.GetAllWebMessages(logger, q) + if err != nil { + logger.Warnf("ReadMessages.GetAllWebMessages error, query:%v, error:%s", q, err.Error()) + } + if len(msgs) < len(param.MessageIds) { + logger.Warnf("ReadMessages.message_ids invalided, user_id:%s, message_ids:%s", userId, param.MessageIds) + panic(constant.BuildInvalidArgumentWithArgs("参数messageIds非法", "param messageIds invalid")) + } + + u := map[string]interface{}{ + "is_del": 1, + } + if err := messageDao.UpdateWebMessages(logger, q, u); err != nil { + logger.Warnf("DeleteMessages.UpdateWebMessages error, query:%v, error:%s", q, err.Error()) + return false, err + } + return true, nil +} + +func DialMail(logger *log.Logger, param *requestTypes.MailDialRequest) error { + + port, err := strconv.Atoi(param.ServerPort) + if err != nil { + logger.Warnf("param.server_port error:%s", err.Error()) + return err + } + + var isPass string + + checkErr := mailLogic.DialMail(logger, param.ServerAddr, port, param.AdminAddr, param.AdminPass, param.To, mailLogic.MailDialTestSubjest, mailLogic.MailDialTestContent) + if checkErr == nil { + logger.Info("dialMail.send ok") + isPass = "1" + } else { + logger.Warnf("dialMail.send error:%s", checkErr.Error()) + isPass = "0" + } + + _, err = SaveMail(logger, param, isPass) + if err != nil { + logger.Warnf("DialMail.SaveMail error:%s", err.Error()) + } + + return checkErr +} + +func SaveMail(logger *log.Logger, param *requestTypes.MailDialRequest, isPass string) (bool, error) { + + mailEntity, err := mailDao.GetMailMessage(logger) + if err != nil { + logger.Warnf("SaveMail.GetMailMessage error:%s", err.Error()) + } + if mailEntity == nil { + m := mailDao.MailMessage{ + ServerAddr: param.ServerAddr, + ServerPort: param.ServerPort, + AdminAddr: param.AdminAddr, + AdminPass: param.AdminPass, + To: param.To, + IsPass: isPass, + } + _, err := mailDao.AddMailMessage(logger, &m) + if err != nil { + logger.Warnf("SaveMail.AddMailMessage error:%s", err.Error()) + return false, err + } + } else { + mailEntity.ServerAddr = param.ServerAddr + mailEntity.ServerPort = param.ServerPort + mailEntity.AdminAddr = param.AdminAddr + mailEntity.AdminPass = param.AdminPass + mailEntity.To = param.To + mailEntity.IsPass = isPass + err := mailDao.UpdateMailAnywhere(logger, mailEntity) + if err != nil { + logger.Warnf("SaveMail.UpdateMailAnywhere error:%s", err.Error()) + return false, err + } + } + + return true, nil +} + +func GetMail(logger *log.Logger) (*responseTypes.Mail, error) { + + m, err := mailDao.GetMailMessage(logger) + if err != nil { + logger.Warnf("GetMail.GetMailMessage error:%s", err.Error()) + } + if m == nil { + return nil, err + } + return &responseTypes.Mail{ + ServerAddr: m.ServerAddr, + ServerPort: m.ServerPort, + AdminAddr: m.AdminAddr, + AdminPass: m.AdminPass, + IsPush: m.IsPush, + To: m.To, + IsPass: m.IsPass, + }, nil + +} + +func SaveIsPushMail(logger *log.Logger, param *requestTypes.SaveIsPushMailRequest) (bool, error) { + + mailEntity, err := mailDao.GetMailMessage(logger) + if err != nil { + logger.Warnf("SaveMail.GetMailMessage error:%s", err.Error()) + } + if mailEntity == nil { + m := mailDao.MailMessage{ + IsPush: param.IsPush, + } + _, err := mailDao.AddMailMessage(logger, &m) + if err != nil { + logger.Warnf("SaveIsPushMail.AddMailMessage error:%s", err.Error()) + return false, err + } + } else { + mailEntity.IsPush = param.IsPush + err := mailDao.UpdateMailAnywhere(logger, mailEntity) + if err != nil { + logger.Warnf("SaveIsPushMail.UpdateMailAnywhere error:%s", err.Error()) + return false, err + } + } + + return true, nil +} diff --git a/bmp-openapi/logic/monitorAlertLogic/monitorAlertLogic.go b/bmp-openapi/logic/monitorAlertLogic/monitorAlertLogic.go new file mode 100644 index 0000000..6d9c9c2 --- /dev/null +++ b/bmp-openapi/logic/monitorAlertLogic/monitorAlertLogic.go @@ -0,0 +1,164 @@ +package monitorAlertLogic + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/monitorAlertDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/monitorRuleDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorRuleLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func AlertEntity2Alert(logger *log.Logger, entity *monitorAlertDao.MonitorAlerts, isDetail bool) *response.Alert { + + rt := &response.RuleTrigger{} + if err := json.Unmarshal([]byte(entity.Trigger), rt); err != nil { + logger.Warnf("AlertEntity2Alert unmarshal Trigger error, value:%s, error:%s", entity.Trigger, err.Error()) + return nil + } + + res := &response.Alert{ + AlertID: entity.AlertID, + AlertTime: int64(entity.AlertTime), + Resource: entity.Resource, + // 资源id,目前就是实例id + ResourceID: entity.ResourceID, + // 资源名称,目前就是实例名称 + ResourceName: entity.ResourceName, + // 触发条件,接口需要翻译 + Trigger: entity.Trigger, + TriggerDescription: monitorRuleLogic.Trigger2Description(logger, rt), + // 报警值 + AlertValue: entity.AlertValue + entity.CalculationUnit, + // 1表示一般,2表示严重,3表示紧急 + AlertLevel: int64(entity.AlertLevel), + // 告警持续时间(分钟为单位) + AlertPeriod: int64(entity.AlertPeriod), + // 通知对象 userid + UserID: entity.UserID, + // 通知对象 用户名 + UserName: entity.UserName, + // 创建时间戳 + CreatedTime: int64(entity.CreatedTime), + } + if logger.GetPoint("language").(string) != baseLogic.EN_US { + //TODO trans trigger\level ... + res.Resource = monitorRuleLogic.ResourceMapZh[entity.Resource] + res.AlertLevelDescription = monitorRuleLogic.RuleAlertLevelMapZh[res.AlertLevel] + } else { + + res.AlertLevelDescription = monitorRuleLogic.RuleAlertLevelMapEn[res.AlertLevel] + } + if isDetail { + ruleEntity, err := monitorRuleDao.GetMonitorRuleById(logger, entity.RuleID) + if err != nil { + logger.Warnf("AlertEntity2Alert.GetMonitorRuleById error, ruleId:%s, error:%s", entity.RuleID, err.Error()) + } else { + res.Rule = monitorRuleLogic.RuleEntity2Rule(logger, ruleEntity, true) + } + + instanceEntity, err := instanceDao.GetInstanceById(logger, entity.ResourceID) + if err != nil { + logger.Warnf("AlertEntity2Alert.GetInstanceById error, instanceId:%s, error:%s", entity.ResourceID, err.Error()) + } else { + res.Instance = instanceLogic.InstanceEntity2Instance(logger, instanceEntity, nil) + } + + } else { + res.Rule = &response.Rule{ + RuleID: entity.RuleID, + RuleName: entity.RuleName, + } + } + + return res +} + +func DescribeAlert(logger *log.Logger, AlertId string) (*response.Alert, error) { + alertEntity, err := monitorAlertDao.GetMonitorAlertsById(logger, AlertId) + if err != nil { + logger.Warnf("DescribeAlert.GetMonitorAlertsById error, AlertId:%s, error:%s", AlertId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + res := AlertEntity2Alert(logger, alertEntity, true) + return res, nil + +} + +func DescribeAlerts(logger *log.Logger, param *request.DescribeAlertsRequest, p util.Pageable) (*response.AlertList, error) { + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "is_del": 0, + } + if param.UserID != "" { + query["user_id"] = param.UserID + } + if param.UserName != "" { + query["user_name"] = param.UserName + } + if param.RuleID != "" { + query["rule_id"] = param.RuleID + } + if param.ResourceID != "" { + query["resource_id"] = param.ResourceID + } + if param.StartTime != 0 { + query["alert_time.>="] = param.StartTime + } + if param.EndTime != 0 { + query["alert_time.<="] = param.EndTime + } + count, err := monitorAlertDao.GetMonitorAlertsCount(logger, query) + if err != nil { + logger.Warnf("DescribeAlerts.GetMonitorAlertsCount error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, err + } + entityList := []*monitorAlertDao.MonitorAlerts{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = monitorAlertDao.GetMultiMonitorAlerts(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = monitorAlertDao.GetMultiMonitorAlerts(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("DescribeAlerts.GetMultiMonitorAlerts sql error:", err.Error()) + return nil, err + } + items := []*response.Alert{} + for _, alertEntity := range entityList { + item := AlertEntity2Alert(logger, alertEntity, false) + items = append(items, item) + } + resp := &response.AlertList{ + Alerts: items, + PageNumber: p.PageNumber, + PageSize: p.PageSize, + TotalCount: count, + } + + return resp, nil +} + +func DeleteAlert(logger *log.Logger, param *request.DeleteAlertRequest) (bool, error) { + + alertId := param.AlertId + entity, err := monitorAlertDao.GetMonitorAlertsById(logger, alertId) + if err != nil { + logger.Warnf("DeleteAlert.GetMonitorAlertsById error, alertId:%s, error:%s", alertId, err.Error()) + return false, err + } + + entity.IsDel = 1 + if err := monitorAlertDao.UpdateMonitorAlerts(logger, entity); err != nil { + logger.Warnf("DeleteAlert.UpdateMonitorAlerts error, ruleId:%s, error:%s", alertId, err.Error()) + return false, err + } + return true, nil + +} diff --git a/bmp-openapi/logic/monitorDataLogic/monitorDataLogic.go b/bmp-openapi/logic/monitorDataLogic/monitorDataLogic.go new file mode 100644 index 0000000..1e0abd6 --- /dev/null +++ b/bmp-openapi/logic/monitorDataLogic/monitorDataLogic.go @@ -0,0 +1,197 @@ +package monitorDataLogic + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorProxyLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorRuleLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + beego "github.com/beego/beego/v2/server/web" +) + +var pronoeaUrl string + +func Init() error { + bmp_pronoea_host, err := beego.AppConfig.String("bmp_pronoea_host") + if err != nil { + return err + } + bmp_pronoea_port, _ := beego.AppConfig.String("bmp_pronoea_port") + if err != nil { + return err + } + pronoeaUrl = fmt.Sprintf("http://%s:%s/api/query", bmp_pronoea_host, bmp_pronoea_port) + return nil +} + +type PronoeaMonitorDataResponse struct { + Code int `json:"Code"` + RequestID string `json:"RequestId"` + Message string `json:"Message"` + Result []*response.DataEveryMetric `json:"Result"` +} + +// func getSampleMethod(logger *log.Logger, metric string) string { +// rateMetrics := []string{ +// "bmp.disk.counts.read", +// "bmp.disk.counts.write", +// "bmp.network.packets.ingress", +// "bmp.network.packets.egress", +// "bmp.disk.bytes.read", +// "bmp.disk.bytes.write", +// "bmp.network.bytes.ingress", +// "bmp.network.bytes.egress", +// } +// increaseMetrics := []string{} +// if util.InArrayString(metric, rateMetrics) { +// return "rate" +// } +// if util.InArrayString(metric, increaseMetrics) { +// return "increase" +// } +// return "" + +// } + +func getTagNameByMetric(metric string) string { + mountpointMetrics := []string{ + + "bmp.disk.partition.used", + "bmp.disk.partition.util", + } + diskMetrics := []string{ + "bmp.disk.used", + "bmp.disk.util", + "bmp.disk.bytes.read", + "bmp.disk.bytes.write", + "bmp.disk.counts.read", + "bmp.disk.counts.write", + } + nicMetrics := []string{ + "bmp.network.bytes.ingress", + "bmp.network.bytes.egress", + "bmp.network.packets.ingress", + "bmp.network.packets.egress", + } + if util.InArrayString(metric, mountpointMetrics) { + return "mountpoint" + } + if util.InArrayString(metric, diskMetrics) { + return "disk" + } + if util.InArrayString(metric, nicMetrics) { + return "nic" + } + return "" +} + +func GetMonitorData(logger *log.Logger, param request.GetMonitorDataRequest) ([]*response.DataEveryMetric, error) { + metrics := strings.Split(param.MetricName, ",") + if len(metrics) == 0 { + panic(constant.BuildCANCELLEDWithArgs("param metricName错误", "param metricName invalid")) + } + instanceEntity, err := instanceDao.GetInstanceById(logger, param.InstanceID) + if err != nil { + logger.Warnf("GetMonitorData.GetInstanceById error, instanceId:%s, error:%s", param.InstanceID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs("instance不存在", "instanceId not exist")) + + } + if param.IdcID != "" && instanceEntity.IDcID != param.IdcID { + panic(constant.BuildInvalidArgumentWithArgs("instance和idcId不匹配", "instanceId not match idcId")) + } + userEntity, err := userDao.GetUserById(logger, instanceEntity.UserID) + if err != nil { + logger.Warnf("GetMonitorData.GetUserById error, userId:%s, error:%s", instanceEntity.UserID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs("instance所属user不存在", "instance.user not exist")) + } + if param.UserName != "" && param.UserName != userEntity.UserName { + panic(constant.BuildInvalidArgumentWithArgs("instance和username不匹配", "instanceId not match username")) + } + + url := pronoeaUrl + tableName := monitorRuleLogic.MapMetric2Table[metrics[0]] + if tableName == "" { + tableName = "bmp_monitor_gauge" + } + req := response.MonitorDataQuery{ + TableName: tableName, + SampleMethod: param.DownSampleType, + StartTime: param.StartTime, + EndTime: param.EndTime, + Step: param.TimeInterval, + } + if strings.Contains(param.MetricName, "bmp.memory.used") || strings.Contains(param.MetricName, "bmp.disk.used") || strings.Contains(param.MetricName, "bmp.disk.partition.used") { + req.Func = map[string]int{ + "/": 1000000000, + } + } + if strings.Contains(param.MetricName, "bmp.network.bytes.ingress") || strings.Contains(param.MetricName, "bmp.network.bytes.egress") { + req.Func = map[string]int{ + "*": 8, + } + } + + //支持多个,传参格式 metric_name = "(cps.disk.partition.used)|(cps.disk.partition.util)" + metricNames := strings.Split(param.MetricName, ",") + if len(metricNames) > 1 { + kw := []string{} + for _, mn := range metricNames { + kw = append(kw, fmt.Sprintf("(%s)", mn)) + } + param.MetricName = strings.Join(kw, "|") + } + labels := map[string]string{ + "metric_name": param.MetricName, + "instance_id": param.InstanceID, + } + + if param.Device != "" { + labels["device"] = param.Device + } else { //磁盘和网口相关的指标,当没有给tag时(监控图首页),给一个默认tag,否则前端展示有问题 + tagName := getTagNameByMetric(metricNames[0]) + if tagName != "" { + tagValues, err := monitorProxyLogic.DescribeDeviceTags(logger, &request.DesrcibeTagsRequest{ + InstanceID: param.InstanceID, + TagName: tagName, + }) + if err != nil || tagValues == nil || len(tagValues.Tags) == 0 { + logger.Warnf("GetMonitorData.DescribeDeviceTags error, instanceId:%s", param.InstanceID) + } else { + labels["device"] = tagValues.Tags[0] + } + } + + } + req.Labels = labels + if param.LastManyTime != 0 { + req.EndTime = time.Now().Unix() + req.StartTime = time.Now().Add(time.Duration(0-param.LastManyTime) * time.Hour).Unix() + } + logger.Infof("GetMonitorData.DoHttpPost url:%s, request:%s", url, util.InterfaceToJson(req)) + + header := map[string]string{ + "Traceid": logger.GetPoint("logid").(string), + } + resp, err := util.DoHttpPost(logger, url, header, req) + if err != nil { + logger.Warnf("DescribeDeviceTags post error, instanceIds:%s, error:%s", param.InstanceID, err.Error()) + return nil, err + } + logger.Infof("GetMonitorData.DoHttpPost response:%s", string(resp)) + + res := PronoeaMonitorDataResponse{} + if err := json.Unmarshal(resp, &res); err != nil { + logger.Warnf("GetMonitorData post body parse error, instanceIds:%s, error:%s", param.InstanceID, err.Error()) + return nil, err + } + return res.Result, nil +} diff --git a/bmp-openapi/logic/monitorProxyLogic/monitorProxyLogic.go b/bmp-openapi/logic/monitorProxyLogic/monitorProxyLogic.go new file mode 100644 index 0000000..47c7e6a --- /dev/null +++ b/bmp-openapi/logic/monitorProxyLogic/monitorProxyLogic.go @@ -0,0 +1,130 @@ +package monitorProxyLogic + +import ( + "encoding/json" + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + beego "github.com/beego/beego/v2/server/web" +) + +const ( + agentStatusUrl string = "/api/v1/describeAgentStatus" + deviceTagsUrl string = "/api/v1/tags" +) + +var AgentStatusMapZh map[int]string = map[int]string{ + 0: "未安装", + 1: "正常", + 2: "异常", +} +var AgentStatusMapEn map[int]string = map[int]string{ + 0: "Not Installed", + 1: "Normal", + 2: "Abnormal", +} + +var monitorProxyServer string + +func Init() error { + bmp_monitor_proxy_host, err := beego.AppConfig.String("bmp_monitor_proxy_host") + if err != nil { + return err + } + bmp_monitor_proxy_port, err := beego.AppConfig.String("bmp_monitor_proxy_port") + if err != nil { + return err + } + monitorProxyServer = fmt.Sprintf("http://%s:%s", bmp_monitor_proxy_host, bmp_monitor_proxy_port) + return nil +} + +type DescribeAgentStatusResponse struct { + // 操作失败结果。成功时有此结构 + Result []response.AgentStatusItem `json:"result"` + // 操作失败结果。失败时有此结构 + Error interface{} `json:"error"` + // 请求traceId + // required: true + RequestId string `json:"requestId"` +} + +func DescribeAgentStatus(logger *log.Logger, param *request.DesrcibeAgentStatusRequest) (*response.AgentStatusResponse, error) { + url := monitorProxyServer + agentStatusUrl + instanceIds := strings.Split(param.InstanceID, ",") + body := map[string]interface{}{ + "instanceIds": instanceIds, + } + + header := map[string]string{ + "Traceid": logger.GetPoint("logid").(string), + } + logger.Infof("DescribeAgentStatus url:%s, request:%s", url, util.InterfaceToJson(body)) + resp, err := util.DoHttpPost(logger, url, header, body) + if err != nil { + logger.Warnf("DescribeAgentStatus post error, instanceIds:%s, error:%s", param.InstanceID, err.Error()) + return nil, err + } + logger.Infof("DescribeAgentStatus.response:%s", string(resp)) + + res := DescribeAgentStatusResponse{} + if err := json.Unmarshal(resp, &res); err != nil { + logger.Warnf("DescribeAgentStatus post body parse error, instanceIds:%s, error:%s", param.InstanceID, err.Error()) + return nil, err + } + for idx, item := range res.Result { + if logger.GetPoint("language").(string) == baseLogic.EN_US { + item.StatusName = AgentStatusMapEn[item.Status] + } else { + item.StatusName = AgentStatusMapZh[item.Status] + } + res.Result[idx] = item + } + return &response.AgentStatusResponse{ + AgentStatus: res.Result, + }, nil + +} + +type DescribeDeviceTagsResponse struct { + // 操作失败结果。成功时有此结构 + Result response.TagsResponse `json:"result"` + // 操作失败结果。失败时有此结构 + Error interface{} `json:"error"` + // 请求traceId + // required: true + RequestId string `json:"requestId"` +} + +func DescribeDeviceTags(logger *log.Logger, param *request.DesrcibeTagsRequest) (*response.TagsResponse, error) { + url := monitorProxyServer + deviceTagsUrl + + body := map[string]interface{}{ + "instanceId": param.InstanceID, + "metric": param.TagName, + } + header := map[string]string{ + "Traceid": logger.GetPoint("logid").(string), + } + logger.Infof("DescribeDeviceTags url:%s, request:%s", url, util.InterfaceToJson(body)) + resp, err := util.DoHttpPost(logger, url, header, body) + if err != nil { + logger.Warnf("DescribeDeviceTags post error, instanceIds:%s, error:%s", param.InstanceID, err.Error()) + return nil, err + } + logger.Infof("DescribeDeviceTags.response:%s", string(resp)) + + res := DescribeDeviceTagsResponse{} + if err := json.Unmarshal(resp, &res); err != nil { + logger.Warnf("DescribeDeviceTags post body parse error, instanceIds:%s, error:%s", param.InstanceID, err.Error()) + return nil, err + } + return &response.TagsResponse{ + Tags: res.Result.Tags, + }, nil +} diff --git a/bmp-openapi/logic/monitorRuleLogic/monitorRuleLogic.go b/bmp-openapi/logic/monitorRuleLogic/monitorRuleLogic.go new file mode 100644 index 0000000..aaf937b --- /dev/null +++ b/bmp-openapi/logic/monitorRuleLogic/monitorRuleLogic.go @@ -0,0 +1,580 @@ +package monitorRuleLogic + +import ( + "encoding/json" + "errors" + "fmt" + "strconv" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/monitorRuleDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rMonitorRulesInstanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/messageLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + beego "github.com/beego/beego/v2/server/web" +) + +var monitorRuleSendUrl string +var monitorRuleDelUrl string + +func Init() error { + bmp_pronoea_host, err := beego.AppConfig.String("bmp_pronoea_host") + if err != nil { + return err + } + bmp_pronoea_port, _ := beego.AppConfig.String("bmp_pronoea_port") + if err != nil { + return err + } + monitorRuleSendUrl = fmt.Sprintf("http://%s:%s/api/rules/write", bmp_pronoea_host, bmp_pronoea_port) + monitorRuleDelUrl = fmt.Sprintf("http://%s:%s/api/rules/delete", bmp_pronoea_host, bmp_pronoea_port) + return nil +} + +var MapMetric2Table map[string]string = map[string]string{ + "bmp.disk.bytes.read": "bmp_monitor_counter", + "bmp.disk.bytes.write": "bmp_monitor_counter", + "bmp.disk.counts.read": "bmp_monitor_counter", + "bmp.disk.counts.write": "bmp_monitor_counter", + "bmp.network.bytes.ingress": "bmp_monitor_counter", + "bmp.network.bytes.egress": "bmp_monitor_counter", + "bmp.network.packets.ingress": "bmp_monitor_counter", + "bmp.network.packets.egress": "bmp_monitor_counter", +} + +var DimensionMapZh map[string]string = map[string]string{ + "disk": "盘符", + "mountpoint": "挂载点", + "nic": "网卡", +} + +var RuleStatusMapZh map[int64]string = map[int64]string{ + 1: "正常", + 2: "已禁用", + 3: "报警", +} + +var RuleStatusMapEn map[int64]string = map[int64]string{ + 1: "Normal", + 2: "Disabled", + 3: "Alert", +} + +// 1表示一般,2表示严重,3表示紧急 +var RuleAlertLevelMapZh map[int64]string = map[int64]string{ + 1: "一般", + 2: "严重", + 3: "紧急", +} + +var RuleAlertLevelMapEn map[int64]string = map[int64]string{ + 1: "General", + 2: "Serious", + 3: "Emergency", +} + +var RuleTriggerCalculationEn map[string]string = map[string]string{ + "min": "Min", + "max": "Max", + "avg": "Avg", + "sum": "Sum", +} + +var RuleTriggerCalculationZh map[string]string = map[string]string{ + "min": "最小值", + "max": "最大值", + "avg": "平均值", + "sum": "总和", +} + +var RuleTriggerOperation map[string]string = map[string]string{ + "gt": ">", + "gte": ">=", + "lt": "<", + "lte": "<=", + "eq": "==", + "neq": "!=", +} + +var ResourceMapZh map[string]string = map[string]string{ + "instance": "实例", +} + +type DeleteRuleToPronoeaRequest struct { + RuleID string `json:"ruleId"` + Source string `json:"source"` +} + +type SendRuleToPronoeaRequest struct { + Source string `json:"source"` + response.Rule +} + +func Trigger2Description(logger *log.Logger, trigger *response.RuleTrigger) string { + + var tpl string //统计周期5分钟 CPU使用率 平均值 >= 1% 持续1个周期 + var metricName string + var staticName string + var operationName string + if logger.GetPoint("language").(string) != baseLogic.EN_US { + tpl = "统计周期 %d分钟 %s %s %s %s%s 持续 %d个周期" + metricName = messageLogic.Types2ShowZh[trigger.Metric] + staticName = RuleTriggerCalculationZh[trigger.Calculation] + } else { + tpl = "static period %dminutes %s %s %s %s%s continue %dperiods" + metricName = messageLogic.Types2ShowEn[trigger.Metric] + staticName = RuleTriggerCalculationEn[trigger.Calculation] + } + operationName = RuleTriggerOperation[trigger.Operation] + if operationName == "" { + operationName = trigger.Operation + } + var threshold string + if float64(int(trigger.Threshold)) == trigger.Threshold { //直接取整 + threshold = strconv.Itoa(int(trigger.Threshold)) + } else { + threshold = strconv.FormatFloat(trigger.Threshold, 'f', 2, 64) + } + + return fmt.Sprintf(tpl, trigger.Period, metricName, staticName, operationName, threshold, trigger.CalculationUnit, trigger.Times) +} + +func RuleEntity2Rule(logger *log.Logger, entity *monitorRuleDao.MonitorRules, idDetail bool) *response.Rule { + + res := &response.Rule{ + RuleID: entity.RuleID, + RuleName: entity.RuleName, + Dimension: entity.Dimension, + DimensionName: entity.Dimension, + Resource: entity.Resource, + ResourceName: entity.Resource, + Status: int64(entity.Status), + UserID: entity.UserID, + UserName: entity.UserName, + } + if logger.GetPoint("language").(string) != baseLogic.EN_US { + res.DimensionName = DimensionMapZh[entity.Dimension] + res.ResourceName = ResourceMapZh[entity.Resource] + } + + trOption := []*response.RuleTrigger{} + if err := json.Unmarshal([]byte(entity.TriggerOption), &trOption); err != nil { + logger.Warnf("RuleEntity2Rule.Unmarshal error, rule_id:%s, error:%s", entity.RuleID, err.Error()) + } else { + res.TriggerOption = trOption + } + triggerDescriptions := []string{} + for idx, v := range trOption { + item := Trigger2Description(logger, v) + triggerDescriptions = append(triggerDescriptions, item) + trOption[idx].Description = item + trOption[idx].TableName = MapMetric2Table[v.Metric] + if trOption[idx].TableName == "" { + trOption[idx].TableName = "bmp_monitor_gauge" + } + } + res.TriggerDescription = triggerDescriptions + + notifyOption := &response.RuleNotice{} + if err := json.Unmarshal([]byte(entity.NoticeOption), notifyOption); err != nil { + logger.Warnf("RuleEntity2Rule.Unmarshal error, rule_id:%s, error:%s", entity.RuleID, err.Error()) + } else { + res.NoticeOption = notifyOption + } + + q := map[string]interface{}{ + "is_del": 0, + "rule_id": entity.RuleID, + } + rRuleInstanceEntities, err := rMonitorRulesInstanceDao.GetAllRMonitorRulesInstance(logger, q) + if err != nil { + logger.Warnf("DescribeRule.GetAllRMonitorRulesInstance error, ruleId:%s, error:%s", entity.RuleID, err.Error()) + } + instanceIds := []string{} + for _, v := range rRuleInstanceEntities { + instanceIds = append(instanceIds, v.InstanceID) + } + res.InstanceIds = instanceIds + res.InstanceCount = int64(len(instanceIds)) + if idDetail { + iq := map[string]interface{}{ + "is_del": 0, + "instance_id.in": instanceIds, + } + instanceEntities, err := instanceDao.GetAllInstance(logger, iq) + if err != nil { + logger.Warnf("RuleEntity2Rule.GetAllInstance error:%s", err.Error()) + } else { + instances := []*response.Instance{} + for _, v := range instanceEntities { + instances = append(instances, instanceLogic.InstanceEntity2Instance(logger, v, nil)) + } + res.Instances = instances + } + + if res.NoticeOption != nil { + noticeUserId := res.NoticeOption.UserID + userEntity, err := userDao.GetUserById(logger, noticeUserId) + if err != nil { + logger.Warnf("RuleEntity2Rule.GetUserById error, userid:%s, error:%s", noticeUserId, err.Error()) + } + res.NoticeOption.UserName = userEntity.UserName + } + } + if len(rRuleInstanceEntities) > 0 { + res.DeviceTag = rRuleInstanceEntities[0].Tags + res.RelatedResourceCount = int64(len(rRuleInstanceEntities)) + } + + res.Status = int64(entity.Status) + // alertEntities, err := monitorAlertDao.GetAllMonitorAlertsByRuleId(logger, entity.RuleID) + // if err != nil { + // logger.Warnf("RuleEntity2Rule.GetAllMonitorAlertsByRuleId error, ruleId:%s, error:%s", entity.RuleID, err.Error()) + // } + // if len(alertEntities) > 0 { + // //1->正常,2->已禁用,3->报警 + // res.Status = 3 + // } + + if logger.GetPoint("language").(string) == baseLogic.EN_US { + res.StatusName = RuleStatusMapEn[res.Status] + + } else { + res.StatusName = RuleStatusMapZh[res.Status] + } + + return res + +} + +func AddRule(logger *log.Logger, param *request.AddRuleRequest) (bool, error) { + instanceIds := param.InstanceIds + + q := map[string]interface{}{ + "is_del": 0, + "instance_id.in": instanceIds, + } + instanceEntities, err := instanceDao.GetAllInstance(logger, q) + if err != nil { + logger.Warnf("AddRule.GetAllInstance error, instance_ids:%v, error:%s", instanceIds, err.Error()) + return false, err + } + if len(instanceEntities) < len(instanceIds) { + logger.Warnf("AddRule.GetAllInstance number lt, instance_ids:%v", instanceIds) + return false, errors.New("instanceIds param error") + } + entity := &monitorRuleDao.MonitorRules{ + RuleID: util.GetUuid("mr_"), + Status: 1, + RuleName: param.RuleName, + Dimension: param.Dimension, + Resource: param.Resource, + // TriggerOption: , + // NoticeOption: , + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + UserID: logger.GetPoint("userId").(string), + UserName: logger.GetPoint("username").(string), + } + v, _ := json.Marshal(param.TriggerOption) + entity.TriggerOption = string(v) + v1, _ := json.Marshal(param.NoticeOption) + entity.NoticeOption = string(v1) + if _, err := monitorRuleDao.AddMonitorRules(logger, entity); err != nil { + logger.Warnf("AddRule.dao.AddMonitorRules error:%s", err.Error()) + return false, err + } else { + rEntities := []*rMonitorRulesInstanceDao.RMonitorRulesInstance{} + for _, instanceEntity := range instanceEntities { + rEntity := &rMonitorRulesInstanceDao.RMonitorRulesInstance{ + RuleID: entity.RuleID, + RuleName: entity.RuleName, + InstanceID: instanceEntity.InstanceID, + InstanceName: instanceEntity.InstanceName, + Tags: param.DeviceTag, + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + } + rEntities = append(rEntities, rEntity) + } + if len(rEntities) > 0 { + if err := rMonitorRulesInstanceDao.AddMultiRMonitorRulesInstance(logger, rEntities); err != nil { + logger.Warnf("AddRule.AddMultiRMonitorRulesInstance error:%s", err.Error()) + return false, err + } + } + } + + rule := RuleEntity2Rule(logger, entity, false) + if err := sendRuleToPronoea(logger, rule); err != nil { + logger.Warnf("AddRule.sendRuleToPronoea error, rule_id:%s, error:%s", entity.RuleID, err.Error()) + return false, err + } + return true, nil + +} + +func DescribeRule(logger *log.Logger, ruleId string) (*response.Rule, error) { + ruleEntity, err := monitorRuleDao.GetMonitorRuleById(logger, ruleId) + if err != nil { + logger.Warnf("DescribeRule.GetMonitorRuleById error, ruleId:%s, error:%s", ruleId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + res := RuleEntity2Rule(logger, ruleEntity, true) + return res, nil + +} + +func DescribeRules(logger *log.Logger, param *request.DescribeRulesRequest, p util.Pageable) (*response.RuleList, error) { + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "is_del": 0, + } + if param.UserID != "" { + query["user_id"] = param.UserID + } + if param.UserName != "" { + query["user_name.like"] = "%" + param.UserName + "%" + } + if param.RuleID != "" { + query["rule_id"] = param.RuleID + } + if param.RuleName != "" { + query["rule_name.like"] = "%" + param.RuleName + "%" + } + if param.Status != 0 { + query["status"] = param.Status + } + count, err := monitorRuleDao.GetMonitorRulesCount(logger, query) + if err != nil { + logger.Warnf("GetSshkeyCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, err + } + entityList := []*monitorRuleDao.MonitorRules{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = monitorRuleDao.GetMultiMonitorRules(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = monitorRuleDao.GetMultiMonitorRules(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("DescribeRules.GetMultiMonitorRules sql error:", err.Error()) + return nil, err + } + items := []*response.Rule{} + for _, ruleEntity := range entityList { + item := RuleEntity2Rule(logger, ruleEntity, false) + items = append(items, item) + } + resp := &response.RuleList{ + Rules: items, + PageNumber: p.PageNumber, + PageSize: p.PageSize, + TotalCount: count, + } + + return resp, nil +} + +func EditRule(logger *log.Logger, param *request.EditRuleRequest) (bool, error) { + + ruleId := param.RuleId + entity, err := monitorRuleDao.GetMonitorRuleById(logger, ruleId) + if err != nil { + logger.Warnf("EditRule.GetMonitorRuleById error, ruleId:%s, error:%s", ruleId, err.Error()) + return false, err + } + + instanceIds := param.InstanceIds + + q := map[string]interface{}{ + "is_del": 0, + "instance_id.in": instanceIds, + } + instanceEntities, err := instanceDao.GetAllInstance(logger, q) + if err != nil { + logger.Warnf("EditRule.GetAllInstance error, instance_ids:%v, error:%s", instanceIds, err.Error()) + return false, err + } + if len(instanceEntities) < len(instanceIds) { + logger.Warnf("EditRule.GetAllInstance number lt, instance_ids:%v", instanceIds) + return false, errors.New("instanceIds param error") + } + + entity.Status = 1 + entity.RuleName = param.RuleName + entity.Dimension = param.Dimension + entity.Resource = param.Resource + entity.UpdatedTime = int(time.Now().Unix()) + entity.UserID = logger.GetPoint("userId").(string) + v, _ := json.Marshal(param.TriggerOption) + entity.TriggerOption = string(v) + v1, _ := json.Marshal(param.NoticeOption) + entity.NoticeOption = string(v1) + if err := monitorRuleDao.UpdateMonitorRules(logger, entity); err != nil { + logger.Warnf("EditRule.dao.UpdateMonitorRules error:%s", err.Error()) + return false, err + } else { + q := map[string]interface{}{ + "is_del": 0, + "rule_id": param.RuleId, + } + u := map[string]interface{}{ + "is_del": 1, + } + if err := rMonitorRulesInstanceDao.UpdateMultiRMonitorRulesInstance(logger, q, u); err != nil { + logger.Warnf("EditRule.UpdateMultiRMonitorRulesInstance error, rule_id:%s, error:%s", param.RuleId, err.Error()) + } + + rEntities := []*rMonitorRulesInstanceDao.RMonitorRulesInstance{} + for _, instanceEntity := range instanceEntities { + rEntity := &rMonitorRulesInstanceDao.RMonitorRulesInstance{ + RuleID: entity.RuleID, + RuleName: entity.RuleName, + InstanceID: instanceEntity.InstanceID, + InstanceName: instanceEntity.InstanceName, + Tags: param.DeviceTag, + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + } + rEntities = append(rEntities, rEntity) + } + if len(rEntities) > 0 { + if err := rMonitorRulesInstanceDao.AddMultiRMonitorRulesInstance(logger, rEntities); err != nil { + logger.Warnf("EditRule.AddMultiRMonitorRulesInstance error:%s", err.Error()) + return false, err + } + } + } + rule := RuleEntity2Rule(logger, entity, true) + if err := sendRuleToPronoea(logger, rule); err != nil { + logger.Warnf("EditRule.sendRuleToPronoea error, rule_id:%s, error:%s", param.RuleId, err.Error()) + return false, err + } + return true, nil + +} + +func EnableRule(logger *log.Logger, param *request.EnableRuleRequest) (bool, error) { + + ruleId := param.RuleId + entity, err := monitorRuleDao.GetMonitorRuleById(logger, ruleId) + if err != nil { + logger.Warnf("EnableRule.GetMonitorRuleById error, ruleId:%s, error:%s", ruleId, err.Error()) + return false, err + } + if entity.Status != 2 { + logger.Warnf("EnableRule.rule enablestatus now %d not allowed enable", entity.Status) + panic(constant.NOT_SUPPORTED) + } + entity.Status = 1 + if err := monitorRuleDao.UpdateMonitorRules(logger, entity); err != nil { + logger.Warnf("EnableRule.UpdateMonitorRules error, ruleId:%s, error:%s", ruleId, err.Error()) + return false, err + } + rule := RuleEntity2Rule(logger, entity, true) + if err := sendRuleToPronoea(logger, rule); err != nil { + logger.Warnf("EnableRule.sendRuleToPronoea error, rule_id:%s, error:%s", param.RuleId, err.Error()) + return false, err + } + return true, nil + +} + +func DisableRule(logger *log.Logger, param *request.DisableRuleRequest) (bool, error) { + + ruleId := param.RuleId + entity, err := monitorRuleDao.GetMonitorRuleById(logger, ruleId) + if err != nil { + logger.Warnf("DisableRule.GetMonitorRuleById error, ruleId:%s, error:%s", ruleId, err.Error()) + return false, err + } + if entity.Status == 2 { + logger.Warnf("DisableRule.rule enablestatus now %d not allowed enable", entity.Status) + panic(constant.NOT_SUPPORTED) + } + entity.Status = 2 + if err := monitorRuleDao.UpdateMonitorRules(logger, entity); err != nil { + logger.Warnf("DisableRule.UpdateMonitorRules error, ruleId:%s, error:%s", ruleId, err.Error()) + return false, err + } + if err := DelRuleToPronoea(logger, param.RuleId); err != nil { + logger.Warnf("DisableRule.DelRuleToPronoea error, rule_id:%s, error:%s", param.RuleId, err.Error()) + return false, err + } + return true, nil + +} + +func DeleteRule(logger *log.Logger, param *request.DeleteRuleRequest) (bool, error) { + + ruleId := param.RuleId + entity, err := monitorRuleDao.GetMonitorRuleById(logger, ruleId) + if err != nil { + logger.Warnf("DeleteRule.GetMonitorRuleById error, ruleId:%s, error:%s", ruleId, err.Error()) + return false, err + } + if entity.Status != 2 { + panic(constant.BuildInvalidArgumentWithArgs("禁用状态的规则才允许删除", "enabled rule not allow delete")) + } + + entity.IsDel = 1 + if err := monitorRuleDao.UpdateMonitorRules(logger, entity); err != nil { + logger.Warnf("DeleteRule.UpdateMonitorRules error, ruleId:%s, error:%s", ruleId, err.Error()) + return false, err + } + // if err := DelRuleToPronoea(logger, param.RuleId); err != nil { + // logger.Warnf("DeleteRule.DelRuleToPronoea error, rule_id:%s, error:%s", param.RuleId, err.Error()) + // return false, err + // } + return true, nil + +} + +func sendRuleToPronoea(logger *log.Logger, rule *response.Rule) error { + url := monitorRuleSendUrl + req := SendRuleToPronoeaRequest{ + Source: "bmpInBand", + Rule: *rule, + } + + logger.Infof("sendRuleToPronoea url:%s request:%s", url, util.InterfaceToJson(req)) + header := map[string]string{ + "Traceid": logger.GetPoint("logid").(string), + } + resp, err := util.DoHttpPost(logger, url, header, req) + if err != nil { + logger.Warnf("sendRuleToPronoea post error, rule_id:%s, error:%s", rule.RuleID, err.Error()) + return err + } + logger.Infof("sendRuleToPronoea resp:%s", string(resp)) + return nil + +} + +func DelRuleToPronoea(logger *log.Logger, ruleId string) error { + url := monitorRuleDelUrl + req := DeleteRuleToPronoeaRequest{ + RuleID: ruleId, + Source: "bmpInBand", + } + logger.Infof("DelRuleToPronoea url:%s, request:%s", url, util.InterfaceToJson(req)) + header := map[string]string{ + "Traceid": logger.GetPoint("logid").(string), + } + resp, err := util.DoHttpPost(logger, url, header, req) + if err != nil { + logger.Warnf("DelRuleToPronoea post error, rule_id:%s, error:%s", ruleId, err.Error()) + return err + } + logger.Infof("DelRuleToPronoea resp:%s", string(resp)) + return nil + +} diff --git a/bmp-openapi/logic/osLogic/osLogic.go b/bmp-openapi/logic/osLogic/osLogic.go new file mode 100644 index 0000000..65f1480 --- /dev/null +++ b/bmp-openapi/logic/osLogic/osLogic.go @@ -0,0 +1,145 @@ +package osLogic + +import ( + "fmt" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + osDao "coding.jd.com/aidc-bmp/bmp-openapi/dao/osDao" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + namespacePrefix "git.jd.com/cps-golang/ironic-common/ironic/common/NamespacePrefixs" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +func OsEntity2OS(o *osDao.Os, tz string) *responseTypes.Os { + return &responseTypes.Os{ + ID: o.ID, + OsID: o.OsID, + OsName: o.OsName, + OsType: o.OsType, + OsVersion: o.OsVersion, + + Architecture: o.Architecture, + Bits: o.Bits, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + } +} + +func GetByOsId(logger *log.Logger, osId string) (*responseTypes.Os, error) { + tz := logger.GetPoint("timezone").(string) + entity, err := osDao.GetOsByUuid(logger, osId) + if err != nil { + logger.Warn("GetOsByUuid sql error:", osId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + return OsEntity2OS(entity, tz), nil +} +func GetOsByUuid(logger *log.Logger, osid string) (o *osDao.Os, err error) { + entity, err := osDao.GetOsByUuid(logger, osid) + return entity, err +} + +func GetAndCheckById(logger *log.Logger, os_id string) (*responseTypes.Os, error) { + os, err := GetByOsId(logger, os_id) + if err != nil { + return nil, err + } + return os, nil + +} + +func CreateOS(logger *log.Logger, param *requestTypes.CreateOSRequest) (string, error) { + list, _ := osDao.GetAllOs(logger, map[string]interface{}{ + "os_name": param.OsName, + "is_del": baseLogic.IS_NOT_DEL, + }) + if len(list) != 0 { + logger.Warn("osName exist:", param.OsName) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("os名称 %s 已存在", param.OsName), fmt.Sprintf("osName %s exist", param.OsName))) + } + os_entity := &osDao.Os{ + OsName: param.OsName, + OsType: param.OsType, + Architecture: param.Architecture, + Bits: param.Bits, + OsVersion: param.OsVersion, + SysUser: param.SysUser, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + os_entity.OsID = commonUtil.GetRandString(namespacePrefix.IMAGE_ID_PREFIX, namespacePrefix.INSTANCE_ID_LENGTH, false, true, true) + if _, err := osDao.AddOs(logger, os_entity); err != nil { + logger.Warnf("CreateOs AddOs sql error, entity:%s, error:%s", util.ObjToJson(os_entity), err.Error()) + return "", err + } + return os_entity.OsID, nil +} + +func ModifyOS(logger *log.Logger, param *requestTypes.ModifyOSRequest, osId string) error { + + entity, err := osDao.GetOsByUuid(logger, osId) + if err != nil { + logger.Warn("GetOsByUuid sql error:", osId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + + entity.OsName = param.OsName + entity.OsType = param.OsType + + entity.Architecture = param.Architecture + entity.Bits = param.Bits + entity.OsVersion = param.OsVersion + entity.SysUser = param.SysUser + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + if err := osDao.UpdateOsById(logger, entity); err != nil { + logger.Warn("ModifyOS UpdateOsById sql error:", osId, err.Error()) + return err + } + return nil +} + +func DeleteOS(logger *log.Logger, osId string) error { + entity, err := osDao.GetOsByUuid(logger, osId) + if err != nil { + logger.Warn("GetOsByUuid sql error:", osId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + entity.IsDel = 1 + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + entity.DeletedTime = int(time.Now().Unix()) + if err := osDao.UpdateOsById(logger, entity); err != nil { + logger.Warn("DeleteOS UpdateOsById sql error:", osId, err.Error()) + return err + } + return nil +} + +func DescribeOSs(logger *log.Logger, param *requestTypes.QueryOssRequest) ([]*responseTypes.Os, error) { + + tz := logger.GetPoint("timezone").(string) + query := map[string]interface{}{ + "os_name": param.OsName, + "os_type": param.OsType, + "os_version": param.OsVersion, + "is_del": 0, + } + os_entity_list, err := osDao.GetAllOs(logger, query) //osDao.GetMultiOs(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 1000) + if err != nil { + logger.Warn("QueryByOsIds GetAllOs sql error:", err.Error()) + return nil, err + } + oss := []*responseTypes.Os{} + for _, entity := range os_entity_list { + oss = append(oss, OsEntity2OS(entity, tz)) + } + return oss, nil +} diff --git a/bmp-openapi/logic/projectLogic/projectLogic.go b/bmp-openapi/logic/projectLogic/projectLogic.go new file mode 100644 index 0000000..c9136d4 --- /dev/null +++ b/bmp-openapi/logic/projectLogic/projectLogic.go @@ -0,0 +1,364 @@ +package projectLogic + +import ( + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/projectDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/sharingProjectDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/instanceLogic" + + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + namespacePrefix "git.jd.com/cps-golang/ironic-common/ironic/common/NamespacePrefixs" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +func ProjectEntity2Project(logger *log.Logger, o *projectDao.Project, shareproject []*sharingProjectDao.SharingProject) *responseTypes.Project { + tz := logger.GetPoint("timezone").(string) + query := map[string]interface{}{ + "is_del": 0, + "project_id": o.ProjectID, + } + cnt, err := instanceLogic.GetInstanceCount(logger, query) + if err != nil { + logger.Warnf("instanceLogic.GetInstanceCount error:%s", err.Error()) + } + + shares := []responseTypes.ShareProject{} + + if len(shareproject) > 0 { + for _, v := range shareproject { + shares = append(shares, responseTypes.ShareProject{ + ProjectName: v.ProjectName, + ProjectID: v.ProjectID, + OwnerUserID: v.OwnerUserID, + OwnerUserName: v.OwnerUserName, + SharedUserID: v.SharedUserID, + SharedUserName: v.SharedUserName, + CreatedTime: util.TimestampToString(int64(v.CreatedTime), tz), + }) + } + + } + + return &responseTypes.Project{ + ID: o.ID, + ProjectName: o.ProjectName, + ProjectID: o.ProjectID, + InstanceCount: cnt, + ShareProjects: shares, + CreatedBy: o.CreatedBy, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + UpdatedBy: o.UpdatedBy, + UpdatedTime: util.TimestampToString(int64(o.UpdatedTime), tz), + } +} + +//只带owned标志位,不关心sharing具体内容 +func ProjectListEntity2Project(logger *log.Logger, o *projectDao.AllProject) *responseTypes.Project { + tz := logger.GetPoint("timezone").(string) + query := map[string]interface{}{ + "is_del": 0, + "project_id": o.ProjectID, + } + cnt, err := instanceLogic.GetInstanceCount(logger, query) + if err != nil { + logger.Warnf("instanceLogic.GetInstanceCount error:%s", err.Error()) + } + + shares := []responseTypes.ShareProject{} + + return &responseTypes.Project{ + ID: o.ID, + ProjectName: o.ProjectName, + ProjectID: o.ProjectID, + InstanceCount: cnt, + ShareProjects: shares, + Owned: o.Owned, + CreatedBy: o.CreatedBy, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + UpdatedBy: o.UpdatedBy, + UpdatedTime: util.TimestampToString(int64(o.UpdatedTime), tz), + } +} + +func GetProjectById(logger *log.Logger, ProjectId string) (*responseTypes.Project, error) { + entity, err := projectDao.GetProjectById(logger, ProjectId) + if err != nil { + logger.Warn("GetProjectByUuid sql error:", ProjectId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + shareEntity, err := sharingProjectDao.GetSharingsByProjectId(logger, ProjectId) + if err != nil { + logger.Warnf("GetProjectById.GetSharingsByProjectId error, project_id:%s, error:%s", ProjectId, err.Error()) + } + return ProjectEntity2Project(logger, entity, shareEntity), nil +} + +func CreateProject(logger *log.Logger, param *requestTypes.CreateProjectRequest, extraUserId string) (string, error) { + + var userId string + if extraUserId == "" { + userId = logger.GetPoint("userId").(string) + } else { + userId = extraUserId //兼容创建用户时创建默认项目,因为此时项目所属的userid不是当前登录用户的userid + } + + list, _ := projectDao.GetAllProject(logger, map[string]interface{}{ + "project_name": param.ProjectName, + "user_id": userId, + "is_del": 0, + }) + if len(list) != 0 { + logger.Warn("projectName exist:", param.ProjectName) + panic(constant.BuildInvalidArgumentWithArgs("项目名称已存在", "projectName exist")) + } + if param.IsDefault == 1 { + list, _ = projectDao.GetAllProject(logger, map[string]interface{}{ + "is_default": 1, + "user_id": userId, + "is_del": 0, + }) + if len(list) != 0 { + logger.Warn("默认项目 exist:", param.ProjectName) + panic(constant.BuildInvalidArgumentWithArgs("默认项目只能有一个", "defaultProject only exist one")) + } + } + ProjectEntity := &projectDao.Project{ + UserID: userId, + ProjectName: param.ProjectName, + IsDefault: param.IsDefault, + IsSystem: param.IsSystem, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + ProjectEntity.ProjectID = commonUtil.GetRandString("project-", namespacePrefix.INSTANCE_ID_LENGTH, false, true, true) + + if _, err := projectDao.AddProject(logger, ProjectEntity); err != nil { + logger.Warnf("CreateProject AddProject sql error, entity:%s, error:%s", util.ObjToJson(ProjectEntity), err.Error()) + return "", err + } + return ProjectEntity.ProjectID, nil +} + +func ModifyProject(logger *log.Logger, param *requestTypes.ModifyProjectRequest, ProjectId string) error { + userId := logger.GetPoint("userId").(string) + p, err := projectDao.GetProjectById(logger, ProjectId) + if err != nil { + logger.Warn("GetProjectByUuid sql error:", ProjectId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if p.UserID != userId { + panic(constant.PermissionDenyForObject) + } + + list, _ := projectDao.GetAllProject(logger, map[string]interface{}{ + "project_name": param.ProjectName, + "user_id": userId, + "is_del": 0, + }) + if len(list) != 0 { + logger.Warn("projectName exist:", param.ProjectName) + panic(constant.BuildInvalidArgumentWithArgs("项目名称已存在", "projectName exist")) + } + + p.ProjectName = param.ProjectName + p.UpdatedBy = logger.GetPoint("username").(string) + p.UpdatedTime = int(time.Now().Unix()) + if err := projectDao.UpdateProjectById(logger, p); err != nil { + logger.Warn("ModifyProject UpdateProjectById sql error:", ProjectId, err.Error()) + return err + } + return nil +} + +/* + 删除项目时,有如下要求: + 1,默认项目也可以删除。如果删除的是默认项目,则自动选一个最早的项目作为默认项目 + 2,每个用户至少保留一个项目。 + 3,项目下如果有资源则不可删除 +*/ + +func DeleteProject(logger *log.Logger, ProjectId string) error { + userId := logger.GetPoint("userId").(string) + query := map[string]interface{}{ + "user_id": userId, + "is_del": 0, + } + entities, err := projectDao.GetAllProject(logger, query) + if err != nil { + panic(constant.INTERNAL_ERROR) + } + idx := -1 + for i, entity := range entities { + if entity.ProjectID == ProjectId { + idx = i + } + } + if idx == -1 { + panic(constant.PermissionDenyForObject) + } + if len(entities) < 2 { + panic(constant.BuildCANCELLEDWithArgs("每个用户至少保留一个项目", "at least one project remained for user")) + } + + instanceQuery := map[string]interface{}{ + "project_id": ProjectId, + "is_del": 0, + } + instanceCnt, err := instanceDao.GetInstanceCount(logger, instanceQuery) + if err != nil { + panic(constant.INTERNAL_ERROR) + } + if instanceCnt > 0 { + panic(constant.BuildCANCELLEDWithArgs("项目下有资源不可删除", "project contains resource, please release resource first")) + } + + deleteEntity := entities[idx] + defaultEntity := entities[0] + if idx == 0 { + defaultEntity = entities[1] + } + + deleteEntity.IsDel = 1 + deleteEntity.UpdatedTime = int(time.Now().Unix()) + deleteEntity.DeletedTime = int(time.Now().Unix()) + if err := projectDao.UpdateProjectById(logger, deleteEntity); err != nil { + logger.Warn("DeleteProject1 UpdateProjectById sql error:", ProjectId, err.Error()) + return err + } + defaultEntity.IsDefault = 1 + defaultEntity.UpdatedTime = int(time.Now().Unix()) + defaultEntity.DeletedTime = int(time.Now().Unix()) + if err := projectDao.UpdateProjectById(logger, defaultEntity); err != nil { + logger.Warn("DeleteProject2 UpdateProjectById sql error:", ProjectId, err.Error()) + return err + } + + //删除项目时,此项目的共享关系都删除 + if err := sharingProjectDao.DeleteSharingProjectByProjectId(logger, ProjectId); err != nil { + logger.Warn("DeleteSharingProjectByProjectId sql error:", ProjectId, err.Error()) + return err + } + + userEntity, err := userDao.GetUserById(logger, userId) + if err != nil { + logger.Warn("DeleteProject GetUserById error:", userId, err.Error()) + return err + } + userEntity.DefaultProjectID = defaultEntity.ProjectID + if err := userDao.UpdateUserById(logger, userEntity); err != nil { + logger.Warn("DeleteProject UpdateUser's defaultProjectById error:", userId, ProjectId, err.Error()) + return err + } + + return nil +} + +func GetProjectList(logger *log.Logger, param requestTypes.QueryProjectsRequest, p util.Pageable) ([]*responseTypes.Project, int64, error) { + userId := logger.GetPoint("userId").(string) + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "user_id": userId, + "is_del": 0, + } + if param.ProjectName != "" { + query["project_name"] = param.ProjectName + } + count, err := projectDao.GetProjectAndSharedCount(logger, userId, param.Owned) + if err != nil { + logger.Warnf("GetProjectCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + var entityList []*projectDao.AllProject + if param.IsAll == baseLogic.IS_ALL { + entityList, err = projectDao.GetMultiProjectIncludeShare(logger, userId, 0, nil, nil, 0, 0) + } else { + entityList, err = projectDao.GetMultiProjectIncludeShare(logger, userId, 0, nil, nil, offset, limit) + } + if err != nil { + logger.Warnf("GetMultiProjectIncludeShare sql error, user_id:%s, error:%s", userId, err.Error()) + return nil, 0, err + } + Projects := []*responseTypes.Project{} + var defaultProject *responseTypes.Project + for _, entity := range entityList { + // shareEntity, err := sharingProjectDao.GetSharingsByProjectId(logger, entity.ProjectID) + if err != nil { + logger.Warnf("GetProjectList.GetSharingsByProjectId error, project_id:%s, error:%s", entity.ProjectID, err.Error()) + } + if entity.IsDefault == 1 { + defaultProject = ProjectListEntity2Project(logger, entity) + } else { + Projects = append(Projects, ProjectListEntity2Project(logger, entity)) + } + + } + if defaultProject == nil { + return Projects, count, nil + } + return append([]*responseTypes.Project{defaultProject}, Projects...), count, nil +} + +func CreateShareProject(logger *log.Logger, projectID string, param *requestTypes.ShareProjectRequest) error { + project, err := projectDao.GetProjectById(logger, projectID) + if project != nil { + logger.Warnf("CreateShareProject.GetProjectById error, project_id:%s, error:%s", projectID, err.Error()) + panic(constant.BuildCANCELLEDWithArgs("项目不存在", "project not found")) + } + owner, err := userDao.GetUserById(logger, param.OwnerID) + if owner != nil { + logger.Warnf("CreateShareProject.GetUserById error, owner_id:%s, error:%s", param.OwnerID, err.Error()) + panic(constant.BuildCANCELLEDWithArgs("用户不存在", "user not found")) + } + sharer, err := userDao.GetUserById(logger, param.SharerID) + if sharer != nil { + logger.Warnf("CreateShareProject.GetUserById error, sharer_id:%s, error:%s", param.OwnerID, err.Error()) + panic(constant.BuildCANCELLEDWithArgs("用户不存在", "user not found")) + } + + if project.UserID == param.SharerID { + panic(constant.BuildCANCELLEDWithArgs("项目不能分享给自己", "project can not shared to the project owner")) + } + + sp, _ := sharingProjectDao.GetOneSharingProject(logger, projectID, param.OwnerID, param.SharerID) + if sp != nil { + panic(constant.BuildCANCELLEDWithArgs("项目已被分享给相同用户", "project already shared to the user")) + } + sp = &sharingProjectDao.SharingProject{ + ProjectID: projectID, + OwnerUserID: param.OwnerID, + SharedUserID: param.SharerID, + OwnerUserName: owner.UserName, + SharedUserName: sharer.UserName, + } + _, err = sharingProjectDao.AddSharingProject(logger, sp) + if err != nil { + logger.Warnf("CreateShareProject.AddSharingProject error, project_id:%s, owner_id:%s, sharer_id:%s, error:%s", projectID, param.OwnerID, param.SharerID, err.Error()) + panic(constant.INTERNAL_ERROR) + } + + return nil +} + +func CancelShareProject(logger *log.Logger, projectID string, param *requestTypes.ShareProjectRequest) (err error) { + + sp, _ := sharingProjectDao.GetOneSharingProject(logger, projectID, param.OwnerID, param.SharerID) + if sp == nil { + panic(constant.BuildCANCELLEDWithArgs("共享项目不存在", "shared project not found")) + } + err = sharingProjectDao.DeleteOneSharingProject(logger, sp) + if err != nil { + logger.Warnf("CreateShareProject.DeleteSharingProject error, project_id:%s, owner_id:%s, sharer_id:%s, error:%s", projectID, param.OwnerID, param.SharerID, err.Error()) + panic(constant.INTERNAL_ERROR) + } + return nil +} diff --git a/bmp-openapi/logic/raidLogic/raidLogic.go b/bmp-openapi/logic/raidLogic/raidLogic.go new file mode 100644 index 0000000..03214db --- /dev/null +++ b/bmp-openapi/logic/raidLogic/raidLogic.go @@ -0,0 +1,203 @@ +package raidLogic + +import ( + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + + raidDao "coding.jd.com/aidc-bmp/bmp-openapi/dao/raidDao" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + namespacePrefix "git.jd.com/cps-golang/ironic-common/ironic/common/NamespacePrefixs" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +func DRaid2Raid(d *raidDao.DRaid) *responseTypes.Raid { + return &responseTypes.Raid{ + //RaidID: d.RaidId, + //Name: d.Name, + //DescriptionEn: d.DescriptionEn, + //DescriptionZh: d.DescriptionZh, + //DeviceType: d.DeviceType, + //VolumeType: d.VolumeType, + //VolumeDetail: d.VolumeDetail, + //SystemPartitionCount: d.SystemPartitionCount, + //AvailableValue: d.AvailableValue, + //DiskType: d.DiskType, + } +} + +func RaidEntity2Raid(d *raidDao.Raid) *responseTypes.Raid { + return &responseTypes.Raid{ + RaidID: d.RaidID, + Name: d.Name, + DescriptionEn: d.DescriptionEn, + DescriptionZh: d.DescriptionZh, + } +} + +func CreateRaid(logger *log.Logger, param *requestTypes.CreateRaidRequest) (string, error) { + + entity := &raidDao.Raid{ + Name: param.Name, + DescriptionEn: param.DescriptionEn, + DescriptionZh: param.DescriptionZh, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + entity.RaidID = commonUtil.GetRandString(namespacePrefix.RAID_ID_PREFIX, namespacePrefix.RAID_ID_LENGTH, false, true, true) + if _, err := raidDao.AddRaid(logger, entity); err != nil { + logger.Warnf("CreateRaid AddRaid sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) + return "", err + } + return entity.RaidID, nil +} + +//func CreateDeviceTypeRaid(logger *log.Logger, param *requestTypes.CreateDeviceTypeRaidRequest) error { +// entity := &rDeviceTypeRaidDao.RDeviceTypeRaid{ +// DeviceTypeID: param.DeviceType, +// RaidID: param.RaidID, +// VolumeDetail: param.VolumeDetail, +// VolumeType: param.VolumeType, +// AvailableValue: param.AvailableValue, +// SystemPartitionCount: param.SystemPartitionCount, +// DiskType: param.DiskType, +// CreatedBy: logger.GetPoint("username").(string), +// CreatedTime: int(time.Now().Unix()), +// UpdatedBy: logger.GetPoint("username").(string), +// UpdatedTime: int(time.Now().Unix()), +// } +// if _, err := rDeviceTypeRaidDao.AddRDeviceTypeRaid(logger, entity); err != nil { +// logger.Warnf("CreateDeviceTypeRaid AddRDeviceTypeRaid sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) +// return err +// } +// return nil +//} +// +//func DeleteDeviceTypeRaid(logger *log.Logger, param *requestTypes.DeleteDeviceTypeRaidRequest) error { +// +// query := map[string]interface{}{ +// "device_type": param.DeviceType, +// "raid_id": param.RaidId, +// "volume_type": param.VolumeType, +// } +// entity, err := rDeviceTypeRaidDao.GetOneRDeviceTypeRaid(logger, query) +// if err != nil { +// logger.Warn("DeleteDeviceTypeRaid_GetOneRDeviceTypeRaid sql error:", param.DeviceType, param.RaidId, param.VolumeType, err.Error()) +// return err +// } +// +// entity.IsDel = 1 +// entity.UpdatedBy = logger.GetPoint("username").(string) +// entity.UpdatedTime = int(time.Now().Unix()) +// entity.DeletedTime = int(time.Now().Unix()) +// +// if err := rDeviceTypeRaidDao.UpdateRDeviceTypeRaidById(logger, entity); err != nil { +// logger.Warnf("DeleteDeviceTypeRaid UpdateRDeviceTypeRaidById sql error, entity:%s, error:%s", util.ObjToJson(entity), err.Error()) +// return err +// } +// return nil +//} + +//func QueryByRequest(logger *log.Logger, param *requestTypes.QueryRaidsRequest) ([]*responseTypes.Raid, error) { +// +// d_raids, err := raidDao.GetAllRraidDevice(logger, param.RaidID, param.DeviceType, param.VolumeType) +// if err != nil { +// logger.Warn("raidDao.GetAllRraidDevice sql error:", param.RaidID, param.DeviceType, param.VolumeType, err.Error()) +// return nil, err +// } +// raids := []*responseTypes.Raid{} +// for _, raid := range d_raids { +// raids = append(raids, DRaid2Raid(raid)) +// } +// return raids, nil +//} + +func QueryRaidsAll(logger *log.Logger) ([]*responseTypes.Raid, error) { + + param := map[string]interface{}{ + "is_del": 0, + } + entities, err := raidDao.GetAllRaid(logger, param) + if err != nil { + logger.Warn("QueryRaidsAll GetAllRaid sql error:", err.Error()) + return nil, err + } + raids := []*responseTypes.Raid{} + for _, entity := range entities { + //rDeviceTypeRaid, err := rDeviceTypeRaidDao.GetOneRDeviceTypeRaid(logger, map[string]interface{}{"raid_id": entity.RaidID}) + //if err != nil { + // logger.Warnf("QueryRDeviceTypeRaid sql error, raid_id:%s:, error:%s", entity.RaidID, err.Error()) + // rDeviceTypeRaid = &rDeviceTypeRaidDao.RDeviceTypeRaid{} + //} + raids = append(raids, RaidEntity2Raid(entity)) + } + return raids, nil +} + +func GetByRaidId(logger *log.Logger, raidId string) (*responseTypes.Raid, error) { + entity, err := raidDao.GetRaidByUuid(logger, raidId) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + //rDeviceTypeRaid, err := rDeviceTypeRaidDao.GetOneRDeviceTypeRaid(logger, map[string]interface{}{"raid_id": entity.RaidID}) + //if err != nil { + // logger.Warnf("QueryRDeviceTypeRaid sql error, raid_id:%s, error:%s", entity.RaidID, err.Error()) + // rDeviceTypeRaid = &rDeviceTypeRaidDao.RDeviceTypeRaid{} + //} + return RaidEntity2Raid(entity), nil +} + +func GetRaidEntityByRaidId(logger *log.Logger, raidId string) (*raidDao.Raid, error) { + entity, err := raidDao.GetRaidByUuid(logger, raidId) + if err != nil { + logger.Warn("GetRaidByUuid sql error:", raidId, err.Error()) + return nil, err + } + return entity, nil +} + +func GetAndCheckByRaidId(logger *log.Logger, raidId string) (*responseTypes.Raid, error) { + raid, err := GetByRaidId(logger, raidId) + if err != nil { + return nil, err + } + return raid, nil +} + +func ModifyRaid(logger *log.Logger, param *requestTypes.ModifyRaidRequest, raidId string) error { + entity, err := raidDao.GetRaidByUuid(logger, raidId) //GetRaidEntityByRaidId(logger, raid_id, true) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + entity.Name = param.Name + entity.DescriptionEn = param.DescriptionEn + entity.DescriptionZh = param.DescriptionZh + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + if err := raidDao.UpdateRaidById(logger, entity); err != nil { + logger.Warn("ModifyRaid UpdateRaidById sql error:", raidId, err.Error()) + return err + } + return nil +} + +func DeleteRaid(logger *log.Logger, raidId string) error { + entity, err := raidDao.GetRaidByUuid(logger, raidId) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + entity.IsDel = 1 + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + entity.DeletedTime = int(time.Now().Unix()) + if err := raidDao.UpdateRaidById(logger, entity); err != nil { + logger.Warn("DeleteRaid UpdateRaidById sql error:", raidId, err.Error()) + return err + } + return nil +} diff --git a/bmp-openapi/logic/resourceLogic/resourceLogic.go b/bmp-openapi/logic/resourceLogic/resourceLogic.go new file mode 100644 index 0000000..2ac9d24 --- /dev/null +++ b/bmp-openapi/logic/resourceLogic/resourceLogic.go @@ -0,0 +1,56 @@ +package resourceLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/dao/deviceTypeDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/imageDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + "fmt" +) + +func DescribeResources(logger *log.Logger, param *requestTypes.QueryResourcesRequest) (int, error) { + query := map[string]interface{}{} + if param.Name != "" { + query["name"] = param.Name + list, err := deviceTypeDao.GetAllDeviceType(logger, query) + if err != nil { + logger.Warnf("GetAllDeviceType error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return 0, err + } + fmt.Println("查询到的数量", len(list)) + return len(list), err + } + if param.DeviceType != "" { + query["device_type"] = param.DeviceType + list, err := deviceTypeDao.GetAllDeviceType(logger, query) + if err != nil { + logger.Warnf("GetAllDeviceType error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return 0, err + } + fmt.Println("查询到的数量", len(list)) + return len(list), err + } + if param.ImageName != "" { + query["image_name"] = param.ImageName + list, err := imageDao.GetAllImage(logger, query) + if err != nil { + logger.Warnf("GetAllImage error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return 0, err + } + fmt.Println("查询到的数量", len(list)) + return len(list), err + } + if param.UserName != "" { + query["user_name"] = param.UserName + list, err := userDao.GetAllUser(logger, query) + if err != nil { + logger.Warnf("GetAllUser error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return 0, err + } + fmt.Println("查询到的数量", len(list)) + return len(list), err + } + return 0, nil +} diff --git a/bmp-openapi/logic/roleLogic/roleLogic.go b/bmp-openapi/logic/roleLogic/roleLogic.go new file mode 100644 index 0000000..00aca1c --- /dev/null +++ b/bmp-openapi/logic/roleLogic/roleLogic.go @@ -0,0 +1,183 @@ +package roleLogic + +import ( + "fmt" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/roleDao" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + namespacePrefix "git.jd.com/cps-golang/ironic-common/ironic/common/NamespacePrefixs" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +func RoleEntity2Role(logger *log.Logger, o *roleDao.Role) *responseTypes.Role { + tz := logger.GetPoint("timezone").(string) + userCount, _ := userDao.GetUserCount(logger, map[string]interface{}{ + "role_id": o.RoleID, + }) + roleName := o.RoleNameCn + if logger.GetPoint("language").(string) == baseLogic.EN_US { + roleName = o.RoleNameEn + } + permission := o.DescriptionCn + if logger.GetPoint("language").(string) == baseLogic.EN_US { + permission = o.DescriptionEn + } + return &responseTypes.Role{ + ID: o.ID, + RoleName: roleName, + Permission: permission, + RoleNameEn: o.RoleNameEn, + RoleNameCn: o.RoleNameCn, + RoleID: o.RoleID, + UserCount: int(userCount), + DescriptionEn: o.DescriptionEn, + DescriptionCn: o.DescriptionCn, + CreatedBy: o.CreatedBy, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + UpdatedBy: o.UpdatedBy, + UpdatedTime: util.TimestampToString(int64(o.UpdatedTime), tz), + } +} + +func GetRoleById(logger *log.Logger, RoleId string) (*responseTypes.Role, error) { + entity, err := roleDao.GetRoleById(logger, RoleId) + if err != nil { + logger.Warn("GetRoleByUuid sql error:", RoleId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + return RoleEntity2Role(logger, entity), nil +} + +func CurrentRole(logger *log.Logger) (*responseTypes.Role, error) { + + userId := logger.GetPoint("userId").(string) + u, err := userDao.GetUserById(logger, userId) + if err != nil { + logger.Warn("GurrentRole.GetUserById sql error:", userId, err.Error()) + panic(constant.INVALID_ARGUMENT) + } + + entity, err := roleDao.GetRoleById(logger, u.RoleID) + if err != nil { + logger.Warn("GurrentRole.GetRoleByUuid sql error:", u.RoleID, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + return RoleEntity2Role(logger, entity), nil +} + +func CreateRole(logger *log.Logger, param *requestTypes.CreateRoleRequest) (string, error) { + list, _ := roleDao.GetAllRole(logger, map[string]interface{}{ + "role_name_cn": param.RoleNameCn, + }) + if len(list) != 0 { + logger.Warn("roleNameCn exist:", param.RoleNameCn) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("角色中文名称 %s 已存在", param.RoleNameCn), fmt.Sprintf("roleNameCn %s exist", param.RoleNameCn))) + } + list, _ = roleDao.GetAllRole(logger, map[string]interface{}{ + "role_name_en": param.RoleNameCn, + }) + if len(list) != 0 { + logger.Warn("roleNameEn exist:", param.RoleNameEn) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("角色英文名称 %s 已存在", param.RoleNameEn), fmt.Sprintf("roleNameEn %s exist", param.RoleNameEn))) + } + roleEntity := &roleDao.Role{ + RoleNameEn: param.RoleNameEn, + RoleNameCn: param.RoleNameCn, + DescriptionEn: param.DescriptionEn, + DescriptionCn: param.DescriptionCn, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + roleEntity.RoleID = commonUtil.GetRandString("role-", namespacePrefix.INSTANCE_ID_LENGTH, false, true, true) + if _, err := roleDao.AddRole(logger, roleEntity); err != nil { + logger.Warnf("CreateRole AddRole sql error, entity:%s, error:%s", util.ObjToJson(roleEntity), err.Error()) + return "", err + } + return roleEntity.RoleID, nil +} + +func ModifyRole(logger *log.Logger, param *requestTypes.ModifyRoleRequest, roleId string) error { + _, err := roleDao.GetRoleById(logger, roleId) + if err != nil { + logger.Warn("GetRoleByUuid sql error:", roleId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + entity := &roleDao.Role{ + RoleID: roleId, + RoleNameEn: param.RoleNameEn, + RoleNameCn: param.RoleNameCn, + DescriptionEn: param.DescriptionEn, + DescriptionCn: param.DescriptionCn, + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + if err := roleDao.UpdateRoleById(logger, entity); err != nil { + logger.Warn("ModifyRole UpdateRoleById sql error:", roleId, err.Error()) + return err + } + return nil +} + +func DeleteRole(logger *log.Logger, roleId string) error { + entity, err := roleDao.GetRoleById(logger, roleId) + if err != nil { + logger.Warn("GetRoleByUuid sql error:", roleId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + userCount, err := userDao.GetUserCount(logger, map[string]interface{}{ + "role_id": roleId, + "is_del": baseLogic.IS_NOT_DEL, + }) + if userCount != 0 { + panic(constant.BuildInvalidArgumentWithArgs("角色下面含有用户,不能删除", "this role contains users,cannot delete")) + } + entity.IsDel = 1 + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + entity.DeletedTime = int(time.Now().Unix()) + if err := roleDao.UpdateRoleById(logger, entity); err != nil { + logger.Warn("DeleteRole UpdateRoleById sql error:", roleId, err.Error()) + return err + } + return nil +} + +func GetRoleList(logger *log.Logger, param requestTypes.QueryRolesRequest, p util.Pageable) ([]*responseTypes.Role, int64, error) { + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + //"role_name": param.RoleName, + //"role_id": param.RoleID, + //"default_project_id": param.DefaultProjectID, + "is_del": 0, + } + count, err := roleDao.GetRoleCount(logger, query) + if err != nil { + logger.Warnf("GetRoleCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*roleDao.Role{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = roleDao.GetMultiRole(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = roleDao.GetMultiRole(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("QueryByRoleIds GetAllRole sql error:", err.Error()) + return nil, 0, err + } + Roles := []*responseTypes.Role{} + for _, entity := range entityList { + Roles = append(Roles, RoleEntity2Role(logger, entity)) + } + return Roles, count, nil +} diff --git a/bmp-openapi/logic/sshkeyLogic/sshkeyLogic.go b/bmp-openapi/logic/sshkeyLogic/sshkeyLogic.go new file mode 100644 index 0000000..b1ee01f --- /dev/null +++ b/bmp-openapi/logic/sshkeyLogic/sshkeyLogic.go @@ -0,0 +1,213 @@ +package sshkeyLogic + +import ( + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/rInstanceSshkeyDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/sshkeyDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + namespacePrefix "git.jd.com/cps-golang/ironic-common/ironic/common/NamespacePrefixs" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +func SshkeyEntity2Sshkey(logger *log.Logger, o *sshkeyDao.Sshkey) *responseTypes.Sshkey { + tz := logger.GetPoint("timezone").(string) + return &responseTypes.Sshkey{ + Id: o.ID, + SshkeyId: o.SshkeyId, + UserId: o.UserId, + Name: o.Name, + FingerPrint: o.FingerPrint, + Key: o.Key, + CreatedBy: o.CreatedBy, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + UpdatedBy: o.UpdatedBy, + UpdatedTime: util.TimestampToString(int64(o.UpdatedTime), tz), + } +} + +func GetSshkeyById(logger *log.Logger, SshkeyId string) (*responseTypes.Sshkey, error) { + entity, err := sshkeyDao.GetSshkeyById(logger, SshkeyId) + if err != nil { + logger.Warn("GetSshkeyByUuid sql error:", SshkeyId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + return SshkeyEntity2Sshkey(logger, entity), nil +} + +func CreateSshkey(logger *log.Logger, param *requestTypes.CreateSshkeyRequest) (string, error) { + + userId := logger.GetPoint("userId").(string) + + v, _ := sshkeyDao.GetAllSshkey(logger, map[string]interface{}{ + "user_id": userId, + "is_del": 0, + }) + if len(v) >= 2 { + logger.Warn("two sshkey already exists", userId) + panic(constant.BuildCANCELLEDWithArgs("支持创建2个SSH密钥", "Only supports creating 2 keypairs")) + + } + + list, _ := sshkeyDao.GetAllSshkey(logger, map[string]interface{}{ + "name": param.Name, + "user_id": userId, + "is_del": 0, + }) + if len(list) != 0 { + logger.Warn("sshkey Name exist:", param.Name) + panic(constant.BuildCANCELLEDWithArgs("秘钥名称已存在", "sshkey name exist")) + + } + + finger_print, err := util.GetFingerprint(param.Key) + if err != nil { + logger.Warn("GetFingerprint error:", param.Key, err.Error()) + return "", err + } + + sshkeyEntity := &sshkeyDao.Sshkey{ + UserId: userId, + Name: param.Name, + Key: param.Key, + FingerPrint: finger_print, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + sshkeyEntity.SshkeyId = commonUtil.GetRandString("sshkey-", namespacePrefix.INSTANCE_ID_LENGTH, false, true, true) + if _, err := sshkeyDao.AddSshkey(logger, sshkeyEntity); err != nil { + logger.Warnf("CreateSshkey AddSshkey sql error, entity:%s, error:%s", util.ObjToJson(sshkeyEntity), err.Error()) + return "", err + } + return sshkeyEntity.SshkeyId, nil +} + +func ModifySshkey(logger *log.Logger, param *requestTypes.ModifySshkeyRequest, SshkeyId string) error { + userId := logger.GetPoint("userId").(string) + s, err := sshkeyDao.GetSshkeyById(logger, SshkeyId) + if err != nil { + logger.Warn("GetSshkeyByUuid sql error:", SshkeyId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if s.UserId != userId { + panic(constant.PermissionDenyForObject) + } + + list, _ := sshkeyDao.GetAllSshkey(logger, map[string]interface{}{ + "name": param.Name, + "user_id": userId, + "is_del": 0, + }) + if len(list) != 0 && list[0].SshkeyId != SshkeyId { + logger.Warn("sshkey Name exist:", param.Name) + panic(constant.BuildCANCELLEDWithArgs("秘钥名称已存在", "sshkey name exist")) + } + if param.Name != nil { + s.Name = *param.Name + } + s.UpdatedBy = logger.GetPoint("username").(string) + s.UpdatedTime = int(time.Now().Unix()) + if err := sshkeyDao.UpdateSshkeyById(logger, s); err != nil { + logger.Warn("ModifySshkey UpdateSshkeyById sql error:", SshkeyId, err.Error()) + return err + } + return nil +} + +func DeleteSshkey(logger *log.Logger, sshkeyId string) error { + + userId := logger.GetPoint("userId").(string) + entity, err := sshkeyDao.GetSshkeyById(logger, sshkeyId) + if err != nil { + logger.Warn("GetSshkeyByUuid sql error:", sshkeyId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if entity.UserId != userId { + panic(constant.PermissionDenyForObject) + } + + instanctIds := GetInstancesBySshkey(logger, sshkeyId) + if len(instanctIds) > 0 { + q := map[string]interface{}{ + "instance_id.in": instanctIds, + "sshkey_id": sshkeyId, + "is_del": 0, + } + u := map[string]interface{}{ + "is_del": 1, + } + if err := rInstanceSshkeyDao.UpdateMultirInstanceSshkey(logger, q, u); err != nil { + logger.Warnf("DeleteSshkey.UpdateMultirInstanceSshkey error, instanceIds:%s, sshkeyId:%s, error:%s", strings.Join(instanctIds, ","), sshkeyId, err.Error()) + return err + } + } + + entity.IsDel = 1 + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + entity.DeletedTime = int(time.Now().Unix()) + if err := sshkeyDao.UpdateSshkeyById(logger, entity); err != nil { + logger.Warn("DeleteSshkey UpdateSshkeyById sql error:", sshkeyId, err.Error()) + return err + } + return nil +} +func GetInstancesBySshkey(logger *log.Logger, sshkeyId string) []string { + entity, _ := rInstanceSshkeyDao.GetAllrInstanceSshkey(logger, map[string]interface{}{ + "sshkey_id": sshkeyId, + "is_del": 0, + }) + //if err != nil { + // logger.Warn("GetInstancesBySshkey sql error:", sshkeyId, err.Error()) + // return err + //} + if entity == nil { + return []string{} + } + ids := []string{} + for _, v := range entity { + ids = append(ids, v.InstanceID) + } + return ids +} +func GetSshkeyList(logger *log.Logger, param requestTypes.QuerySshkeysRequest, p util.Pageable) ([]*responseTypes.Sshkey, int64, error) { + userId := logger.GetPoint("userId").(string) + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "name": param.Name, + "user_id": userId, + //"Sshkey_id": param.SshkeyID, + //"default_project_id": param.DefaultProjectID, + "is_del": 0, + } + count, err := sshkeyDao.GetSshkeyCount(logger, query) + if err != nil { + logger.Warnf("GetSshkeyCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + entityList := []*sshkeyDao.Sshkey{} + if param.IsAll == baseLogic.IS_ALL { + entityList, err = sshkeyDao.GetMultiSshkey(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = sshkeyDao.GetMultiSshkey(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("QueryBySshkeyIds GetAllSshkey sql error:", err.Error()) + return nil, 0, err + } + sshkeys := []*responseTypes.Sshkey{} + for _, entity := range entityList { + sshkeys = append(sshkeys, SshkeyEntity2Sshkey(logger, entity)) + } + return sshkeys, count, nil +} diff --git a/bmp-openapi/logic/userLogic/userLogic.go b/bmp-openapi/logic/userLogic/userLogic.go new file mode 100644 index 0000000..bad9172 --- /dev/null +++ b/bmp-openapi/logic/userLogic/userLogic.go @@ -0,0 +1,400 @@ +package userLogic + +import ( + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/projectDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/roleDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/sharingProjectDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/projectLogic" + + userDao "coding.jd.com/aidc-bmp/bmp-openapi/dao/userDao" + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + namespacePrefix "git.jd.com/cps-golang/ironic-common/ironic/common/NamespacePrefixs" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +func userEntity2user(logger *log.Logger, o *userDao.User) *responseTypes.User { + + tz := logger.GetPoint("timezone").(string) + role, _ := roleDao.GetRoleById(logger, o.RoleID) + if role == nil { + role = &roleDao.Role{} + } + project, _ := projectDao.GetProjectById(logger, o.DefaultProjectID) + if project == nil { + project = &projectDao.Project{} + } + + roleName := role.RoleNameCn + if logger.GetPoint("language") == baseLogic.EN_US { + roleName = role.RoleNameEn + } + return &responseTypes.User{ + ID: o.ID, + UserName: o.UserName, + Password: o.Password, + UserID: o.UserID, + RoleID: o.RoleID, + RoleName: roleName, + PhonePrefix: o.PhonePrefix, + PhoneNumber: o.PhoneNumber, + DefaultProjectID: o.DefaultProjectID, + DefaultProjectName: project.ProjectName, + Timezone: o.Timezone, + Language: o.Language, + Email: o.Email, + Description: o.Description, + CreatedBy: o.CreatedBy, + CreatedTime: util.TimestampToString(int64(o.CreatedTime), tz), + UpdatedBy: o.UpdatedBy, + UpdatedTime: util.TimestampToString(int64(o.UpdatedTime), tz), + } +} + +func GetUserById(logger *log.Logger, userId string) (*responseTypes.User, error) { + entity, err := userDao.GetUserById(logger, userId) + if err != nil { + logger.Warn("GetuserByUuid sql error:", userId, err.Error()) + return nil, err + } + logger.Infof("GetUserById userid:%s, entity:%s", userId, util.InterfaceToJson(entity)) + return userEntity2user(logger, entity), nil +} + +func GetUserByName(logger *log.Logger, param *requestTypes.GetUserByNameRequest) (*responseTypes.User, error) { + entity, err := userDao.GetUserByName(logger, param.UserName) + if err != nil { + logger.Warn("GetuserByName sql error:", param.UserName, err.Error()) + return nil, err + } + return userEntity2user(logger, entity), nil +} + +func CreateUser(logger *log.Logger, param *requestTypes.CreateUserRequest) (string, error) { + list, _ := userDao.GetAllUser(logger, map[string]interface{}{ + "user_name": param.UserName, + "is_del": baseLogic.IS_NOT_DEL, + }) + if len(list) != 0 { + logger.Warn("user name exist:", param.UserName) + panic(constant.BuildInvalidArgumentWithArgs("用户名 "+param.UserName+" 已存在", "username "+param.UserName+" exist")) + } + if param.RoleID == baseLogic.ROLE_ADMIN_UUID { //如果是超级管理角色 + listRole, _ := userDao.GetAllUser(logger, map[string]interface{}{ + "role_id": baseLogic.ROLE_ADMIN_UUID, + "is_del": baseLogic.IS_NOT_DEL, + }) + if len(listRole) != 0 { + logger.Warn("roleID exist:", param.UserName) + panic(constant.BuildInvalidArgumentWithArgs("平台拥有者已存在,只能存在一个平台拥有着", "Owner exist")) + } + } + if _, err := roleDao.GetRoleById(logger, param.RoleID); err != nil { + chmsg := "角色Id不存在" + enmsg := "roleId not exist" + panic(constant.BuildNotFoundWithArgs(chmsg, enmsg)) + } + user_entity := &userDao.User{ + UserName: param.UserName, + RoleID: param.RoleID, + Email: param.Email, + PhonePrefix: param.PhonePrefix, + PhoneNumber: param.PhoneNumber, + Password: util.BcryptEncode(param.Password), + Description: param.Description, + Timezone: param.Timezone, + Language: param.Language, + CreatedBy: logger.GetPoint("username").(string), + CreatedTime: int(time.Now().Unix()), + UpdatedBy: logger.GetPoint("username").(string), + UpdatedTime: int(time.Now().Unix()), + } + user_entity.UserID = commonUtil.GetRandString("user-", namespacePrefix.INSTANCE_ID_LENGTH, false, true, true) + + pn := baseLogic.DEFAULTPROJECTNAME + if logger.GetPoint("language").(string) == baseLogic.EN_US { + pn = baseLogic.DEFAULTPROJECTNAME_EN + } + + projectId, err := projectLogic.CreateProject(logger, &requestTypes.CreateProjectRequest{ + ProjectName: pn, + IsDefault: 1, + IsSystem: 1, + }, user_entity.UserID) + if err != nil { + logger.Warnf("Createuser Add defaultProject sql error, entity:%s, error:%s", util.ObjToJson(user_entity), err.Error()) + return "", err + } + user_entity.DefaultProjectID = projectId + if _, err := userDao.Adduser(logger, user_entity); err != nil { + logger.Warnf("Createuser Adduser sql error, entity:%s, error:%s", util.ObjToJson(user_entity), err.Error()) + return "", err + } + return user_entity.UserID, nil +} + +func ModifyUser(logger *log.Logger, param *requestTypes.ModifyUserRequest, userId string) error { + + entity, err := userDao.GetUserById(logger, userId) + if err != nil { + logger.Warn("GetuserByUuid sql error:", userId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if param.Description != nil { + entity.Description = *param.Description + } + if param.PhonePrefix != nil { + entity.PhonePrefix = *param.PhonePrefix + } + if param.PhoneNumber != nil { + entity.PhoneNumber = *param.PhoneNumber + } + if param.Email != nil { + entity.Email = *param.Email + } + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + if err := userDao.UpdateUserById(logger, entity); err != nil { + logger.Warn("Modifyuser UpdateuserById sql error:", userId, err.Error()) + return err + } + return nil +} + +func ModifyLocalUser(logger *log.Logger, param *requestTypes.ModifyLocalUserRequest) error { + + userId := logger.GetPoint("userId").(string) + u, err := userDao.GetUserById(logger, userId) + if err != nil { + logger.Warn("GetuserByUuid sql error:", userId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if param.DefaultProjectID != nil { + u.DefaultProjectID = *param.DefaultProjectID + } + if param.Email != nil { + u.Email = *param.Email + } + if param.PhonePrefix != nil { + u.PhonePrefix = *param.PhonePrefix + } + if param.PhoneNumber != nil { + u.PhoneNumber = *param.PhoneNumber + } + if param.Language != nil { + u.Language = *param.Language + } + if param.Timezone != nil { + u.Timezone = *param.Timezone + } + + u.UpdatedBy = logger.GetPoint("username").(string) + u.UpdatedTime = int(time.Now().Unix()) + if err := userDao.UpdateUserById(logger, u); err != nil { + logger.Warn("Modifyuser UpdateuserById sql error:", userId, err.Error()) + return err + } + if param.DefaultProjectID != nil { + if err := projectDao.UpdateUserDefaultProject(logger, userId, *param.DefaultProjectID); err != nil { + logger.Warn("Modifyuser UpdateUserDefaultProject sql error:", userId, err.Error()) + return err + } + } + return nil +} + +func DeleteUser(logger *log.Logger, userId string) error { + entity, err := userDao.GetUserById(logger, userId) + if err != nil { + logger.Warn("GetuserByUuid sql error:", userId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if entity.RoleID == baseLogic.ROLE_ADMIN_UUID { + panic(constant.BuildInvalidArgumentWithArgs("平台拥有着不能被删除", "Can't delete Owner")) + } + + q := map[string]interface{}{ + "is_del": 0, + "user_id": userId, + } + instanceC, _ := instanceDao.GetInstanceCount(logger, q) + if instanceC > 0 { + logger.Warnf("user have instance, user_id:%s, count:%d", userId, instanceC) + panic(constant.BuildInvalidArgumentWithArgs("此用户内还有实例资源未被释放,请释放或转移给其它用户后才能删除用户", "There are resources in this user that have not been released. Please release or transfer to other users before deleting the user")) + } + + //删除项目和共享项目 + deleteUpdate := map[string]interface{}{ + "is_del": 1, + } + if err := projectDao.UpdateProjects(logger, q, deleteUpdate); err != nil { + logger.Warnf("delete project for user drop error, user_id:%s, err:%s", userId, err.Error()) + } + + q1 := map[string]interface{}{ + "is_del": 0, + "owner_user_id": userId, + } + if err := sharingProjectDao.UpdateShareProjects(logger, q1, deleteUpdate); err != nil { + logger.Warnf("delete share project for user drop error, user_id:%s, err:%s", userId, err.Error()) + } + + q2 := map[string]interface{}{ + "is_del": 0, + "shared_user_id": userId, + } + if err := sharingProjectDao.UpdateShareProjects(logger, q2, deleteUpdate); err != nil { + logger.Warnf("delete share project for user drop error, user_id:%s, err:%s", userId, err.Error()) + } + + // instanceList, err := instanceDao.GetAllInstance(logger, map[string]interface{}{ + // "user_id": userId, + // "is_del": baseLogic.IS_NOT_DEL, + // }) + // if len(instanceList) != 0 { + // logger.Warn("user have instances:", userId) + // panic(constant.BuildInvalidArgumentWithArgs("此用户内还有资源未被释放,请释放或转移给其它用户后才能删除用户", "There are resources in this user that have not been released. Please release or transfer to other users before deleting the user")) + // } + // deviceList, err := deviceDao.GetAllDevice(logger, map[string]interface{}{ + // "user_id": userId, + // "is_del": baseLogic.IS_NOT_DEL, + // }) + // if len(deviceList) != 0 { + // logger.Warn("user have devices:", userId) + // panic(constant.BuildInvalidArgumentWithArgs("此用户内还有资源未被释放,请释放或转移给其它用户后才能删除用户", "There are resources in this user that have not been released. Please release or transfer to other users before deleting the user")) + // } + entity.IsDel = 1 + entity.UpdatedBy = logger.GetPoint("username").(string) + entity.UpdatedTime = int(time.Now().Unix()) + entity.DeletedTime = int(time.Now().Unix()) + if err := userDao.UpdateUserById(logger, entity); err != nil { + logger.Warn("Deleteuser UpdateuserById sql error:", userId, err.Error()) + return err + } + + //删除项目和共享项目 + + return nil +} + +func GetUserList(logger *log.Logger, param *requestTypes.QueryUsersRequest, p util.Pageable) ([]*responseTypes.User, int64, error) { + offset, limit := p.Pageable2offset() + query := map[string]interface{}{ + "user_name.like": "%" + param.UserName + "%", + "default_project_id": param.DefaultProjectID, + "is_del": 0, + } + if param.RoleID != "" { + query["role_id.in"] = strings.Split(param.RoleID, ",") + } + count, err := userDao.GetUserCount(logger, query) + if err != nil { + logger.Warnf("GetUserCount dao error, query:%s, error:%s", util.ObjToJson(query), err.Error()) + return nil, 0, err + } + var entityList []*userDao.User + if param.IsAll == baseLogic.IS_ALL { + entityList, err = userDao.GetMultiUser(logger, query, []string{}, []string{"id"}, []string{"desc"}, 0, 0) + } else { + entityList, err = userDao.GetMultiUser(logger, query, []string{}, []string{"id"}, []string{"desc"}, offset, limit) + } + if err != nil { + logger.Warn("QueryByuserIds GetAlluser sql error:", err.Error()) + return nil, 0, err + } + users := []*responseTypes.User{} + pcu, err := projectDao.GetProjectCountGroupByUser(logger) + if err != nil { + logger.Warnf("GetProjectCountGroupByUser err:%s", err.Error()) + } + + spcu, err := sharingProjectDao.GetShareProjectCountGroupByUser(logger) + if err != nil { + logger.Warnf("GetShareProjectCountGroupByUser err:%s", err.Error()) + } + + icu, err := instanceDao.GetInstanceCountGroupByUser(logger) + if err != nil { + logger.Warnf("GetInstanceCountGroupByUser err:%s", err.Error()) + } + for _, entity := range entityList { + u := userEntity2user(logger, entity) + for _, vv := range pcu { + if vv.UserID == u.UserID { + u.ProjectCount = int(vv.Count) + break + } + } + for _, vv := range spcu { + if vv.UserID == u.UserID { + u.ProjectCount += int(vv.Count) + break + } + } + + for _, vv := range icu { + if vv.UserID == u.UserID { + u.InstanceCount = int(vv.Count) + break + } + } + users = append(users, u) + } + + return users, count, nil +} + +func VerifyUser(logger *log.Logger, req *requestTypes.VerifyUserRequest) bool { + entity, _ := userDao.GetAllUser(logger, map[string]interface{}{ + "user_name": req.UserName, + "is_del": baseLogic.IS_NOT_DEL, + }) + if len(entity) == 0 { //说明用户名不存在 + panic(constant.BuildInvalidArgumentWithArgs("用户名不存在", "userName not exist")) + } + + permit := false + for _, v := range entity { + if v.RoleID == req.RoleID || v.RoleID == "role-admin-uuid-01" { + permit = true + break + } + } + + if !permit { //无权限 + panic(constant.BuildInvalidArgumentWithArgs("用户权限不足", "permission denied")) + } + logger.Info("请求信息", util.ObjToJson(req), "数据库hash值", entity[0].Password) + res := util.BcryptVerify(req.Password, entity[0].Password) + if !res { + panic(constant.BuildInvalidArgumentWithArgs("密码错误", "password error")) + } else { + return true + } +} + +func ModifyUserPassword(logger *log.Logger, param *requestTypes.ModifyUserPasswordRequest) error { + userId := logger.GetPoint("userId").(string) + u, err := userDao.GetUserById(logger, userId) + if err != nil { + logger.Warn("GetuserByUuid sql error:", userId, err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(constant.NOT_FOUND.Messagech, constant.NOT_FOUND.MessageEn)) + } + if !util.BcryptVerify(param.OldPassword, u.Password) { + panic(constant.BuildInvalidArgumentWithArgs("旧密码输入错误", "oldPassword error")) + } + u.Password = util.BcryptEncode(param.Password) + if err := userDao.UpdateUserById(logger, u); err != nil { + logger.Warn("ModifyUserPassword UpdateuserById sql error:", userId, err.Error()) + return err + } + return nil +} diff --git a/bmp-openapi/main.go b/bmp-openapi/main.go new file mode 100644 index 0000000..7e82e68 --- /dev/null +++ b/bmp-openapi/main.go @@ -0,0 +1,165 @@ +package main + +import ( + "flag" + "fmt" + "os" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorDataLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorProxyLogic" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/monitorRuleLogic" + _ "coding.jd.com/aidc-bmp/bmp-openapi/routers" + rabbitMq "coding.jd.com/aidc-bmp/bmp-openapi/service/rabbit_mq" + redis "coding.jd.com/aidc-bmp/bmp-openapi/service/redis" + _ "coding.jd.com/aidc-bmp/bmp-openapi/swaggermodels" + "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + + "log" + + beego "github.com/beego/beego/v2/server/web" + _ "github.com/go-sql-driver/mysql" + + // schedulerCron "coding.jd.com/aidc-bmp/bmp-openapi/scheduler/cron" + + _ "coding.jd.com/aidc-bmp/bmp-openapi/constant" +) + +////// + +const ( + defaultConfigFile = "conf/bmp-openapi.ini" +) + +var ( + VERSION = "should be compiled with make." + BUILD_TIME = "should be compiled with make." +) + +var configFile = flag.String("c", defaultConfigFile, "specify config file") +var versionFlag = flag.Bool("v", false, "show version") + +func main() { + + time.LoadLocation("Asia/Shanghai") + flag.Parse() + + if *versionFlag { + fmt.Println("commit_id:", VERSION, "build_time:", BUILD_TIME) + os.Exit(0) + } + + log.Println("[ironic-api] start...") + + // initial Config From file + if err := beego.LoadAppConfig("ini", *configFile); err != nil { + fmt.Println(time.Now(), "LoadAppConfig Error:", err.Error()) + return + } + if err := initRedis(); err != nil { + fmt.Println(time.Now(), "initRedis Error: ", err.Error()) + // return + } + + initGormDB() + + if err := initRabbitMqTemplate(); err != nil { + fmt.Println(time.Now(), "initRabbitMqTemplate Error:", err.Error()) + // return + } + defer rabbitMq.DestroyTemplate() + + request.InitValidator() + + // if err := initIdcApiConfig(); err != nil { + // fmt.Println("initIdcApiConfig Error:", err.Error()) + // return + // } + + // if err := initSdnApiConfig(); err != nil { + // fmt.Println("initSdnApiConfig Error:", err.Error()) + // return + // } + + if err := monitorDataLogic.Init(); err != nil { + fmt.Println(time.Now(), "monitorDataLogic Init Error:", err.Error()) + + } + if err := monitorRuleLogic.Init(); err != nil { + fmt.Println(time.Now(), "monitorRuleLogic Init Error:", err.Error()) + + } + if err := monitorProxyLogic.Init(); err != nil { + fmt.Println(time.Now(), "monitorProxyLogic Init Error:", err.Error()) + + } + + // go schedulerCron.Run() + + beego.Run() +} + +func initRedis() error { + // initial redis + var namespace, host, port, password string + var dbNum int + namespace, _ = beego.AppConfig.String("bmp_redis_namespace") + host, _ = beego.AppConfig.String("bmp_redis_host") + port, _ = beego.AppConfig.String("bmp_redis_port") + password, _ = beego.AppConfig.String("bmp_redis_password") + dbNum = beego.AppConfig.DefaultInt("bmp_redis_db", 0) + addr := fmt.Sprintf("%s:%s", host, port) + return redis.InitRedis(namespace, addr, password, dbNum) +} + +func initGormDB() { + // initial mysql + host, _ := beego.AppConfig.String("bmp_db_host") + port, _ := beego.AppConfig.String("bmp_db_port") + user, _ := beego.AppConfig.String("bmp_db_user") + password, _ := beego.AppConfig.String("bmp_db_password") + name, _ := beego.AppConfig.String("bmp_db_name") + //root:admin@tcp(10.226.192.113:3306)/aidc_bmp?charset=utf8&parseTime=true&charset=utf8&loc=Asia%2FShanghai + sqlconn := user + ":" + password + "@tcp(" + host + ":" + port + ")/" + name + "?charset=utf8&parseTime=true&loc=Local" + dao.InitGormDb(sqlconn) +} + +func initRabbitMqTemplate() error { + host, _ := beego.AppConfig.String("bmp_mq_host") + port, _ := beego.AppConfig.String("bmp_mq_port") + user, _ := beego.AppConfig.String("bmp_mq_user") + password, _ := beego.AppConfig.String("bmp_mq_password") + vhost, _ := beego.AppConfig.String("bmp_mq_vhost") + mqUrl := "amqp://" + user + ":" + password + "@" + host + ":" + port + "/" + vhost + // exchange, _ := beego.AppConfig.String("rabbit.mq.ironic.exchange") + // receive_routing_key, _ := beego.AppConfig.String("rabbit.mq.ironic.receive_routing_key") + return rabbitMq.InitMqTemplate(mqUrl) +} + +// func initIdcApiConfig() error { +// host, _ := beego.AppConfig.String("idc.host") +// user, _ := beego.AppConfig.String("idc.user") +// token, _ := beego.AppConfig.String("idc.token") +// return idcApi.InitIdcApiConfig(host, user, token) +// } + +// func initSdnApiConfig() error { +// cn_east_1, _ := beego.AppConfig.String("sdn.configs.cn-east-1.ip") +// cn_east_jdr1, _ := beego.AppConfig.String("sdn.configs.cn-east-jdr1.ip") +// cn_north_1, _ := beego.AppConfig.String("sdn.configs.cn-north-1.ip") +// cn_east_tz1, _ := beego.AppConfig.String("sdn.configs.cn-east-tz1.ip") +// cn_east_jn1, _ := beego.AppConfig.String("sdn.configs.cn-east-jn1.ip") +// cn_east_11, _ := beego.AppConfig.String("sdn.configs.cn-east-11.ip") + +// c := map[string]string{ +// "cn-east-1": cn_east_1, +// "cn-east-jdr1": cn_east_jdr1, +// "cn-north-1": cn_north_1, +// "cn-east-tz1": cn_east_tz1, +// "cn-east-jn1": cn_east_jn1, +// "cn-east-11": cn_east_11, +// } +// return sdnApi.InitSdnApiConfig(c) + +// } diff --git a/bmp-openapi/routers/router.go b/bmp-openapi/routers/router.go new file mode 100644 index 0000000..664ac41 --- /dev/null +++ b/bmp-openapi/routers/router.go @@ -0,0 +1,352 @@ +// @APIVersion 1.0.0 +// @Title beego Test API +// @Description beego has a very cool tools to autogenerate documents for your API +// @Contact astaxie@gmail.com +// @TermsOfServiceUrl http://beego.me/ +// @License Apache 2.0 +// @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html +package routers + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/controllers" + + beego "github.com/beego/beego/v2/server/web" +) + +func init() { + + // beego.InsertFilter("/v1/pro/*", beego.BeforeRouter, license.CheckLicense) + + //subnetNS := beego.NewNamespace("/subnets", + // beego.NSRouter("/", &controllers.SubnetController{}, "get:QuerySubnets"), + // beego.NSRouter("/?:subnet_id", &controllers.SubnetController{}, "get:GetSubnet"), + // beego.NSRouter("/", &controllers.SubnetController{}, "post:CreateSubnet"), + // beego.NSRouter("/?:subnet_id", &controllers.SubnetController{}, "put:ModifySubnet"), + // beego.NSRouter("/?:subnet_id", &controllers.SubnetController{}, "delete:DeleteSubnet"), + //) + //beego.AddNamespace(subnetNS) + // + //wanSubnetNS := beego.NewNamespace("/wanSubnet", + // beego.NSRouter("/", &controllers.WanSubnetController{}, "post:CreateWanSubnet"), + //) + //beego.AddNamespace(wanSubnetNS) + + deviceNS := beego.NewNamespace("/v1/devices", + beego.NSRouter("/", &controllers.DeviceController{}, "get:DescribeDevices"), + beego.NSRouter("/", &controllers.DeviceController{}, "post:CreateDevice"), + beego.NSRouter("/", &controllers.DeviceController{}, "post:DescribeDevices"), + //设备关联机型 + beego.NSRouter("/deviceType/associate", &controllers.DeviceController{}, "put:DeviceAssociateDeviceType"), + beego.NSRouter("/?:device_id", &controllers.DeviceController{}, "put:ModifyDevice"), + beego.NSRouter("/mount", &controllers.DeviceController{}, "put:MountDevice"), + beego.NSRouter("/unmount", &controllers.DeviceController{}, "put:UnMountDevice"), + beego.NSRouter("/?:device_id", &controllers.DeviceController{}, "delete:DeleteDevice"), + beego.NSRouter("/stock", &controllers.DeviceController{}, "get:DescribeDeviceStock"), + beego.NSRouter("/?:device_id", &controllers.DeviceController{}, "get:DescribeDevice"), + beego.NSRouter("/?:device_id/remove", &controllers.DeviceController{}, "put:RemoveDevice"), + // 设备详情-磁盘 + beego.NSRouter("/?:device_id/disksDetail", &controllers.DeviceController{}, "get:DescribeDeviceDisks"), + // 关联设备磁盘 + beego.NSRouter("/disks/associateDisks", &controllers.DeviceController{}, "put:AssociateDeviceDisks"), + // 获取设备关联的磁盘信息 + beego.NSRouter("/disks/describeAssociateDisks", &controllers.DeviceController{}, "get:GetAssociatedDisks"), + ) + beego.AddNamespace(deviceNS) + + CommandNS := beego.NewNamespace("/commands", + beego.NSRouter("/", &controllers.CommandController{}, "get:Query"), + beego.NSRouter("/cancel", &controllers.CommandController{}, "put:CancelCommand"), + beego.NSRouter("/retryCommand", &controllers.CommandController{}, "put:RetryCommand"), + ) + beego.AddNamespace(CommandNS) + + DeviceTypeNS := beego.NewNamespace("/v1/deviceTypes", + beego.NSRouter("/", &controllers.DeviceTypeController{}, "post:CreateDeviceType"), + beego.NSRouter("/", &controllers.DeviceTypeController{}, "get:DescribeDeviceTypes"), + beego.NSRouter("/?:device_type_id", &controllers.DeviceTypeController{}, "get:DescribeDeviceType"), + beego.NSRouter("/?:device_type_id/describeVolumes", &controllers.DeviceTypeController{}, "get:DescribeVolumesByDeviceType"), + beego.NSRouter("/?:device_type_id", &controllers.DeviceTypeController{}, "put:ModifyDeviceType"), + beego.NSRouter("/?:device_type_id", &controllers.DeviceTypeController{}, "delete:DeleteDeviceType"), + beego.NSRouter("/associatedImage", &controllers.DeviceTypeController{}, "post:AssociatedImage"), + beego.NSRouter("/dissociatedImage", &controllers.DeviceTypeController{}, "delete:DissociatedImage"), + beego.NSRouter("/deviceTypeImage", &controllers.DeviceTypeController{}, "get:DescribeDeviceTypeImages"), + beego.NSRouter("/deviceTypeRaid", &controllers.DeviceTypeController{}, "get:DescribeDeviceTypeRaids"), + beego.NSRouter("/deviceTypeImagePartition", &controllers.DeviceTypeController{}, "get:DescribeDeviceTypeImagePartitions"), + ) + beego.AddNamespace(DeviceTypeNS) + + IdcNS := beego.NewNamespace("v1/idcs", + beego.NSRouter("/devices", &controllers.IdcController{}, "post:CreateDevicesFromIdc"), + //beego.NSRouter("/bm/deviceBatchImport", &controllers.IdcController{}, "post:DeviceBatchImport"), //ImportBms + + beego.NSRouter("/", &controllers.IdcController{}, "post:CreateIdc"), + beego.NSRouter("/", &controllers.IdcController{}, "get:DescribeIdcs"), + beego.NSRouter("/?:idc_id", &controllers.IdcController{}, "get:DescribeIdc"), + beego.NSRouter("/?:idc_id", &controllers.IdcController{}, "put:ModifyIdc"), + beego.NSRouter("/?:idc_id", &controllers.IdcController{}, "delete:DeleteIdc"), + ) + + beego.AddNamespace(IdcNS) + + OsNS := beego.NewNamespace("/v1/oss", + beego.NSRouter("/", &controllers.OsController{}, "post:CreateOS"), + beego.NSRouter("/", &controllers.OsController{}, "get:DescribeOSs"), + beego.NSRouter("/?:os_id", &controllers.OsController{}, "get:DescribeOS"), + beego.NSRouter("/?:os_id", &controllers.OsController{}, "put:ModifyOS"), + beego.NSRouter("/?:os_id", &controllers.OsController{}, "delete:DeleteOS"), + ) + beego.AddNamespace(OsNS) + + ImageNS := beego.NewNamespace("/v1/images", + beego.NSRouter("/", &controllers.ImageController{}, "post:CreateImage"), + beego.NSRouter("/", &controllers.ImageController{}, "get:DescribeImages"), + beego.NSRouter("/?:image_id", &controllers.ImageController{}, "get:DescribeImage"), + beego.NSRouter("/?:image_id", &controllers.ImageController{}, "put:ModifyImage"), + beego.NSRouter("/?:image_id", &controllers.ImageController{}, "delete:DeleteImage"), + beego.NSRouter("/imageDeviceTypes", &controllers.ImageController{}, "get:DescribeImageDeviceTypes"), + beego.NSRouter("/associatedDeviceType", &controllers.ImageController{}, "post:AssociatedDeviceType"), + beego.NSRouter("/dissociatedDeviceType", &controllers.ImageController{}, "delete:DissociatedDeviceType"), + ) + beego.AddNamespace(ImageNS) + + RabbitMq := beego.NewNamespace("/rabbitmq", + beego.NSRouter("/send", &controllers.RabbitMqController{}, "post:Send"), + beego.NSRouter("/receive", &controllers.RabbitMqController{}, "get:Receive"), + ) + beego.AddNamespace(RabbitMq) + + /*InterfaceNs := beego.NewNamespace("/interfaces", + beego.NSRouter("/", &controllers.InterfaceController{}, "post:CreateInterface"), + beego.NSRouter("/", &controllers.InterfaceController{}, "get:QueryInterfaces"), + beego.NSRouter("/", &controllers.InterfaceController{}, "delete:DeleteInterface"), + ) + beego.AddNamespace(InterfaceNs) + + SwitchNs := beego.NewNamespace("/switches", + beego.NSRouter("/", &controllers.JdSwitchController{}, "put:CreateSwitch"), + beego.NSRouter("/", &controllers.JdSwitchController{}, "post:UpdateSwitch"), + beego.NSRouter("/", &controllers.JdSwitchController{}, "get:QuerySwitches"), + ) + beego.AddNamespace(SwitchNs)*/ + + //KeypairNS := beego.NewNamespace("/keypairs", + // beego.NSRouter("/", &controllers.KeypairController{}, "post:CreateKeypair"), + // beego.NSRouter("/?:keypair_id", &controllers.KeypairController{}, "delete:DeleteKeypair"), + // beego.NSRouter("/", &controllers.KeypairController{}, "get:DescribeKeyPairs"), + // beego.NSRouter("/?:keypair_id", &controllers.KeypairController{}, "get:DescribeKeyPair"), + // beego.NSRouter("/getKeypairByname/?:keypair_name", &controllers.KeypairController{}, "get:DescribeKeyPairByName"), + //) + //beego.AddNamespace(KeypairNS) + + /*MailNS := beego.NewNamespace("/mail", + beego.NSRouter("/addReceiver", &controllers.MailReceiverController{}, "put:AddReceiver"), + beego.NSRouter("/removeReceiver", &controllers.MailReceiverController{}, "put:RemoveReceiver"), + beego.NSRouter("/listReceivers", &controllers.MailReceiverController{}, "get:QueryReceivers"), + ) + beego.AddNamespace(MailNS)*/ + + RaidNS := beego.NewNamespace("/v1/raids", + beego.NSRouter("/", &controllers.RaidController{}, "post:CreateRaid"), + beego.NSRouter("/deviceTypeRaid", &controllers.RaidController{}, "post:CreateDeviceTypeRaid"), + beego.NSRouter("/deviceTypeRaid", &controllers.RaidController{}, "delete:DeleteDeviceTypeRaid"), + beego.NSRouter("/", &controllers.RaidController{}, "get:DescribeRaids"), //QueryRaids + //beego.NSRouter("/queryRaidsAll", &controllers.RaidController{}, "get:QueryRaidsAll"), + beego.NSRouter("/?:raid_id", &controllers.RaidController{}, "get:DescribeRaid"), + beego.NSRouter("/?:raid_id", &controllers.RaidController{}, "put:ModifyRaid"), + beego.NSRouter("/?:raid_id", &controllers.RaidController{}, "delete:DeleteRaid"), + ) + beego.AddNamespace(RaidNS) + + InstanceNS := beego.NewNamespace("/v1/project/instances", + beego.NSRouter("/", &controllers.InstanceController{}, "post:CreateProjectInstance"), + beego.NSRouter("/", &controllers.InstanceController{}, "get:DescribeProjectInstances"), + beego.NSRouter("/?:instance_id", &controllers.InstanceController{}, "get:DescribeProjectInstance"), + beego.NSRouter("/?:instance_id", &controllers.InstanceController{}, "put:ModifyProjectInstance"), + beego.NSRouter("/?:instance_id", &controllers.InstanceController{}, "delete:DeleteProjectInstance"), + beego.NSRouter("/?:instance_id/lock", &controllers.InstanceController{}, "put:LockProjectInstance"), //锁定 + beego.NSRouter("/?:instance_id/unlock", &controllers.InstanceController{}, "put:UnLockProjectInstance"), //解锁定 + beego.NSRouter("/?:instance_id/start", &controllers.InstanceController{}, "put:StartProjectInstance"), //开机 + beego.NSRouter("/?:instance_id/stop", &controllers.InstanceController{}, "put:StopProjectInstance"), //关机 + beego.NSRouter("/?:instance_id/restart", &controllers.InstanceController{}, "put:RestartProjectInstance"), //重启 + beego.NSRouter("/?:instance_id/resetStatus", &controllers.InstanceController{}, "put:ResetInstanceStatus"), //重置状态 + //批量开机 + beego.NSRouter("/batch/:param(instances[:]{1}startInstances)", &controllers.InstanceController{}, "put:StartInstances"), + // //批量关机 + beego.NSRouter("/batch/:param(instances[:]{1}stopInstances)", &controllers.InstanceController{}, "put:StopInstances"), + // //批量重启 + beego.NSRouter("/batch/:param(instances[:]{1}restartInstances)", &controllers.InstanceController{}, "put:RestartInstances"), + // //批量编辑实例名称 + beego.NSRouter("/batch/:param(instances[:]{1}modifyInstances)", &controllers.InstanceController{}, "put:ModifyInstances"), + // //批量删除实例 + beego.NSRouter("/batch/:param(instances[:]{1}deleteInstances)", &controllers.InstanceController{}, "delete:DeleteInstances"), + // 重置密码 + beego.NSRouter("/?:instance_id/resetpasswd", &controllers.InstanceController{}, "put:ResetPasswd"), //重置密码 + // //批量重置密码 + beego.NSRouter("/batch/:param(instances[:]{1}resetPasswd)", &controllers.InstanceController{}, "put:ResetInstancesPasswd"), + // 实例重装 + beego.NSRouter("/?:instance_id/reinstallInstance", &controllers.InstanceController{}, "put:ReinstallInstance"), + ) + beego.AddNamespace(InstanceNS) + + //offline接口,给带内监控用的 + monitorNs := beego.NewNamespace("/v1/offline", + beego.NSRouter("/instance/queryBySn", &controllers.InstanceController{}, "get:QueryInstanceBySn"), + // beego.NSRouter("/license/timeout", &controllers.OfflineController{}, "get:LicenseTimeout"), + ) + + beego.AddNamespace(monitorNs) + + UserNS := beego.NewNamespace("/v1/users", + beego.NSRouter("/", &controllers.UserController{}, "post:CreateUser"), + beego.NSRouter("/verify", &controllers.UserController{}, "post:VerifyUser"), + beego.NSRouter("/", &controllers.UserController{}, "get:DescribeUsers"), + beego.NSRouter("/getUserByName", &controllers.UserController{}, "get:DescribeUserByName"), + beego.NSRouter("/?:user_id", &controllers.UserController{}, "get:DescribeUser"), + beego.NSRouter("/?:user_id", &controllers.UserController{}, "put:ModifyUser"), + beego.NSRouter("/?:user_id", &controllers.UserController{}, "delete:DeleteUser"), + ) + beego.AddNamespace(UserNS) + + // 控制台个人中心 + LocalUserNS := beego.NewNamespace("/v1/local/users", + beego.NSRouter("/", &controllers.UserController{}, "get:DescribeLocalUser"), + beego.NSRouter("/", &controllers.UserController{}, "put:ModifyLocalUser"), + beego.NSRouter("/password", &controllers.UserController{}, "put:ModifyLocalUserPassword"), + ) + beego.AddNamespace(LocalUserNS) + + RoleSN := beego.NewNamespace("/v1/roles", + beego.NSRouter("/", &controllers.RoleController{}, "post:CreateRole"), + beego.NSRouter("/", &controllers.RoleController{}, "get:DescribeRoles"), + beego.NSRouter("/?:role_id", &controllers.RoleController{}, "get:DescribeRole"), + beego.NSRouter("/roleInfo/current", &controllers.RoleController{}, "get:CurrentRole"), + beego.NSRouter("/?:role_id", &controllers.RoleController{}, "put:ModifyRole"), + beego.NSRouter("/?:role_id", &controllers.RoleController{}, "delete:DeleteRole"), + ) + beego.AddNamespace(RoleSN) + + ProjectSN := beego.NewNamespace("/v1/user/projects", + beego.NSRouter("/", &controllers.ProjectController{}, "post:CreateUserProject"), + beego.NSRouter("/", &controllers.ProjectController{}, "get:DescribeUserProjects"), + beego.NSRouter("/?:project_id/share", &controllers.ProjectController{}, "put:ShareUserProject"), + beego.NSRouter("/?:project_id/cancelShare", &controllers.ProjectController{}, "put:CancelShareUserProject"), + beego.NSRouter("/?:project_id", &controllers.ProjectController{}, "get:DescribeUserProject"), + beego.NSRouter("/?:project_id", &controllers.ProjectController{}, "put:ModifyUserProject"), + beego.NSRouter("/?:project_id", &controllers.ProjectController{}, "delete:DeleteUserProject"), + ) + beego.AddNamespace(ProjectSN) + SshkeySN := beego.NewNamespace("/v1/user/sshkeys", + beego.NSRouter("/", &controllers.SshkeyController{}, "post:CreateUserSshkey"), + beego.NSRouter("/", &controllers.SshkeyController{}, "get:DescribeUserSshKeys"), + beego.NSRouter("/?:sshkey_id", &controllers.SshkeyController{}, "get:DescribeUserSshKey"), + beego.NSRouter("/?:sshkey_id", &controllers.SshkeyController{}, "put:ModifyUserSshkey"), + beego.NSRouter("/?:sshkey_id", &controllers.SshkeyController{}, "delete:DeleteUserSshkey"), + beego.NSRouter("/instances/?:sshkey_id", &controllers.SshkeyController{}, "get:GetInstancesBySshkey"), + ) + beego.AddNamespace(SshkeySN) + ApikeySN := beego.NewNamespace("/v1/user/apikeys", + beego.NSRouter("/", &controllers.ApikeyController{}, "post:CreateUserApikey"), + beego.NSRouter("/", &controllers.ApikeyController{}, "get:DescribeUserAPIKeys"), + beego.NSRouter("/?:apikey_id", &controllers.ApikeyController{}, "get:DescribeUserAPIKey"), + beego.NSRouter("/?:apikey_id", &controllers.ApikeyController{}, "put:ModifyUserApikey"), + beego.NSRouter("/?:apikey_id", &controllers.ApikeyController{}, "delete:DeleteUserApikey"), + ) + beego.AddNamespace(ApikeySN) + resource := beego.NewNamespace("/v1/resources", + beego.NSRouter("/", &controllers.ResourceController{}, "get:DescribeResources"), + ) + beego.AddNamespace(resource) + + CollectNS := beego.NewNamespace("/v1/collect", + beego.NSRouter("/collectDeviceInfo", &controllers.DeviceController{}, "post:CollectDeviceInfo"), + ) + beego.AddNamespace(CollectNS) + + // license := beego.NewNamespace("/v1/license", + // beego.NSRouter("/requestToken", &controllers.LicenseController{}, "get:DescribeRequestToken"), + // beego.NSRouter("/content", &controllers.LicenseController{}, "get:DescribeLicenseContent"), + // beego.NSRouter("/upload", &controllers.LicenseController{}, "post:UploadLicense"), + // beego.NSRouter("/currentVersion", &controllers.LicenseController{}, "get:DescribeCurrentVersion"), + // ) + // beego.AddNamespace(license) + + messageNS := beego.NewNamespace("/v1/messages", + beego.NSRouter("/hasUnreadMessage", &controllers.MessageController{}, "get:HasUnreadMessage"), + beego.NSRouter("/", &controllers.MessageController{}, "get:GetMessageList"), + beego.NSRouter("/statistic", &controllers.MessageController{}, "get:GetMessageStatistic"), + beego.NSRouter("/doRead", &controllers.MessageController{}, "put:ReadMessage"), + beego.NSRouter("/delete", &controllers.MessageController{}, "delete:DeleteMessage"), + beego.NSRouter("/getMessageById", &controllers.MessageController{}, "get:GetMessageById"), + beego.NSRouter("/getMessageTypes", &controllers.MessageController{}, "get:GetMessageTypes"), + beego.NSRouter("/dialMail", &controllers.MessageController{}, "post:DialMail"), + beego.NSRouter("/saveIsPushMail", &controllers.MessageController{}, "post:SaveIsPushMail"), + beego.NSRouter("/mailDetail", &controllers.MessageController{}, "get:MailDetail"), + ) + beego.AddNamespace(messageNS) + + auditLogNS := beego.NewNamespace("/v1/auditLogs", + beego.NSRouter("/", &controllers.AuditLogsController{}, "get:DescribeAuditLogs"), + beego.NSRouter("/types", &controllers.AuditLogsController{}, "get:DescribeAuditLogTypes"), + ) + beego.AddNamespace(auditLogNS) + + //报警规则相关 + monitorRuleNs := + beego.NewNamespace("/v1/monitorRule", + //添加规则 + beego.NSRouter("/addRule", &controllers.MonitorRuleController{}, "post:AddRule"), + //规则详情 + beego.NSRouter("/describeRule", &controllers.MonitorRuleController{}, "get:DescribeRule"), + //规则列表 + beego.NSRouter("/describeRules", &controllers.MonitorRuleController{}, "get:DescribeRules"), + //编辑规则 + beego.NSRouter("/editRule", &controllers.MonitorRuleController{}, "put:EditRule"), + //启用规则 + beego.NSRouter("/enableRule", &controllers.MonitorRuleController{}, "put:EnableRule"), + //禁用规则 + beego.NSRouter("/disableRule", &controllers.MonitorRuleController{}, "put:DisableRule"), + //删除规则 + beego.NSRouter("/deleteRule", &controllers.MonitorRuleController{}, "delete:EditRule"), + ) + + beego.AddNamespace(monitorRuleNs) + + //监控报警相关 + monitorAlertNs := + beego.NewNamespace("/v1/monitorAlert", + //告警详情 + beego.NSRouter("/describeAlert", &controllers.MonitorAlertController{}, "get:DescribeAlert"), + //告警列表 + beego.NSRouter("/describeAlerts", &controllers.MonitorAlertController{}, "get:DescribeAlerts"), + //删除告警 + beego.NSRouter("/deleteAlert", &controllers.MonitorAlertController{}, "delete:DeleteAlert"), + ) + + beego.AddNamespace(monitorAlertNs) + + //带内监控-图表数据获取 + monitorDataNs := + beego.NewNamespace("/v1/monitorData", + beego.NSRouter("/", &controllers.MonitorDataController{}, "get:GetMonitorData"), + ) + + beego.AddNamespace(monitorDataNs) + + //带内监控-获取agent状态、获取tag列表 + monitorProxyNs := + beego.NewNamespace("/v1/monitorProxy", + beego.NSRouter("/desrcibeAgentStatus", &controllers.MonitorProxyController{}, "get:DesrcibeAgentStatus"), + beego.NSRouter("/desrcibeTags", &controllers.MonitorProxyController{}, "get:DesrcibeTags"), + ) + + beego.AddNamespace(monitorProxyNs) + + //内部测试用 + innerNs := + beego.NewNamespace("/v1/innerTest", + beego.NSRouter("/mockMultiAuditLogs", &controllers.AuditLogsController{}, "post:MockMultiAuditLogs"), + ) + + beego.AddNamespace(innerNs) + +} diff --git a/bmp-openapi/service/idc_api/idc_api.go b/bmp-openapi/service/idc_api/idc_api.go new file mode 100644 index 0000000..861c37b --- /dev/null +++ b/bmp-openapi/service/idc_api/idc_api.go @@ -0,0 +1,73 @@ +package idc_api + +import ( + "encoding/json" + "errors" + "fmt" + "time" + + "coding.jd.com/aidc-bmp/bmp-openapi/util" + log "coding.jd.com/aidc-bmp/bmp_log" + "git.jd.com/cps-golang/ironic-common/exception" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" + "gopkg.in/goyy/goyy.v0/util/crypto/hmac" +) + +//返回数据格式 https://cf.jd.com/pages/viewpage.action?pageId=103918804 +type IdcDevicesResp struct { + StatusCode int32 `json:"status_code"` + Data map[string]IDevice `json:"data"` +} + +type IDevice struct { + Sn string `json:"sn"` + IloIP string `json:"ilo_ip"` + Cabinet string `json:"cabinet"` + UPosition string `json:"u_position"` + Department string `json:"department"` + Model string `json:"model"` + Manufacturer string `json:"manufacturer"` + UpDown string `json:"up_down"` + Idc string `json:"idc"` +} + +var host, user, token string + +func InitIdcApiConfig(idcHost, idcUser, idcToken string) error { + if idcHost == "" || idcUser == "" || idcToken == "" { + return errors.New("host|user|token missing...") + } + host = idcHost + user = idcUser + token = idcToken + return nil +} + +func QueryDevices(logger *log.Logger, sns []string) map[string]IDevice { + + t := fmt.Sprint(time.Now().Unix()) + auth, _ := hmac.Md5Hex(fmt.Sprintf("%s%s%s", user, token, t), "key") + CMDB_GET_DEVICE_INFO_BY_SNS := fmt.Sprintf("http://%s/v1.0/search/device_info/sns?user=%s&auth=%s×tamp=%s", host, user, auth, t) + + header := map[string]string{ + "Host": host, + "Content-Type": "application/json", + "X-Jdcloud-Request-Id": logger.GetPoint("logid").(string), + } + resp, err := util.DoHttpPost(logger, CMDB_GET_DEVICE_INFO_BY_SNS, header, sns) + if err != nil { + logger.Warn("idc_api QueryDevices error:", sns, err.Error()) + panic(exception.Exception{httpStatus.INTERNAL_SERVER_ERROR, errorCode.INTERNAL, "queryDevices from idc fail"}) + } + logger.Point("idc_api_resp", string(resp)) + var res = IdcDevicesResp{} + if err = json.Unmarshal(resp, &res); err != nil { + logger.Warn("idc_api QueryDevices response parse error:", sns, err.Error()) + panic(exception.Exception{httpStatus.INTERNAL_SERVER_ERROR, errorCode.INTERNAL, "queryDevices from idc fail"}) + } + if res.StatusCode != 200 { + panic(exception.Exception{httpStatus.INTERNAL_SERVER_ERROR, errorCode.INTERNAL, "queryDevices from idc is empty"}) + } + return res.Data +} diff --git a/bmp-openapi/service/rabbit_mq/producer.go b/bmp-openapi/service/rabbit_mq/producer.go new file mode 100644 index 0000000..628d13b --- /dev/null +++ b/bmp-openapi/service/rabbit_mq/producer.go @@ -0,0 +1,30 @@ +package rabbit_mq + +import ( + "fmt" + + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + "github.com/streadway/amqp" +) + +func SendToApi2Scheduler(obj interface{}) error { + return doPublish(ironicChannel, IRONIC_EXCHANGE, API_TO_SCHEDULER_ROUTING_KEY, obj) +} + +func doPublish(c *amqp.Channel, exchangeName string, routingKey string, val interface{}) (err error) { + msg, err := commonUtil.Convert2String(val) + if err != nil { + return err + } + err = c.Publish( + exchangeName, // exchange + routingKey, // routing key + false, // mandatory + false, // immediate + amqp.Publishing{ + ContentType: "application/json", + Body: []byte(msg), + }) + fmt.Println(exchangeName, routingKey, msg) + return +} diff --git a/bmp-openapi/service/rabbit_mq/rabbit_mq.go b/bmp-openapi/service/rabbit_mq/rabbit_mq.go new file mode 100644 index 0000000..d36e690 --- /dev/null +++ b/bmp-openapi/service/rabbit_mq/rabbit_mq.go @@ -0,0 +1,212 @@ +package rabbit_mq + +import ( + "fmt" + "time" + + "github.com/streadway/amqp" +) + +const ( + //********************ironic******************** + IRONIC_EXCHANGE = "CPS_IRONIC_SCHEDULER" + IRONIC_TOPIC = "direct" + + API_TO_SCHEDULER_QUEUE_NAME = "CPS_IRONIC_API_TO_SCHEDULER" + API_TO_SCHEDULER_ROUTING_KEY = "CPS_IRONIC_INNER_ROUTING_KEY" + SCHEDULER_QUEUE_NAME = "CPS_IRONIC_SCHEDULER" + SCHEDULER_ROUTING_KEY = "CPS_IRONIC_SCHEDULER" + + //********************openapi******************** + OPENAPI_EXCHANGE = "CPS_OPENAPI_EXCHANGE" + OPENAPI_TOPIC = "direct" + + OPENAPI_CALLBACK_QUEUE_NAME = "CPS_OPENAPI_CALLBACK_QUEUE" + OPENAPI_CALLBACK_ROUTING_KEY = "CPS_OPENAPI_CALLBACK_ROUTING_KEY" + + IRONIC_4TOPIC_EXCHANGE = "BMP_SCHEDULER_TOPIC" +) + +var ( + openapiUrl string + ironicUrl string + ironicConn *amqp.Connection + ironicChannel *amqp.Channel + openapiConn *amqp.Connection + openapiChannel *amqp.Channel +) + +func DestroyTemplate() { + ironicChannel.Close() + ironicConn.Close() + //openapiChannel.Close() + //openapiConn.Close() +} + +//连接保活,断开时重连 +func keepAliveConn() { + + var ironicCloseChan chan *amqp.Error + var ironicNotifyClose chan *amqp.Error + + for { + + if ironicConn == nil || ironicConn.IsClosed() { //连接已断开,需要重连 + fmt.Printf(time.Now().String() + "ironic conn is closed\n") + //新建连接和信道 + if err := InitIronicMq(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitIronicMq error:%s\n", err.Error()) + goto END + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitIronicMq success\n") + } + } + + ironicCloseChan = make(chan *amqp.Error, 1) + //openapiCloseChan := make(chan *amqp.Error, 1) + ironicNotifyClose = ironicChannel.NotifyClose(ironicCloseChan) //一旦消费者的channel有错误,产生一个amqp.Error,channel监听并捕捉到这个错误 + //openapiNotifyClose := openapiChannel.NotifyClose(openapiCloseChan) + select { + case <-ironicNotifyClose: + fmt.Printf(time.Now().String() + "ironic channel error\n") + if ironicConn == nil || ironicConn.IsClosed() { //连接已断开,需要重连 + fmt.Printf(time.Now().String() + "ironic conn is closed\n") + time.Sleep(5 * time.Second) + //新建连接和信道 + if err := InitIronicMq(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitIronicMq error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitIronicMq success\n") + } + + } else { //连接还在,只是信道异常,需要获取新信道 + fmt.Printf(time.Now().String() + "ironic conn is open but channel is bad\n") + time.Sleep(5 * time.Second) + //获取新信道 + if err := InitIronicMqForNewChannel(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitIronicMqForNewChannel error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitIronicMqForNewChannel success\n") + } + } + /*case <-openapiNotifyClose: + + fmt.Printf(time.Now().String() + "openapi channel error\n") + if openapiConn == nil || openapiConn.IsClosed() { //连接已断开,需要重连 + fmt.Printf(time.Now().String() + "openapi conn is closed\n") + time.Sleep(5 * time.Second) + //新建连接和信道 + if err := InitOpenapiMq(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitOpenapiMq error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitOpenapiMq success\n") + } + + } else { //连接还在,只是信道异常,需要获取新信道 + fmt.Printf(time.Now().String() + "openapi conn is open but channel is bad\n") + time.Sleep(5 * time.Second) + //获取新信道 + if err := InitOpenapiMqForNewChannel(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitOpenapiMqForNewChannel error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitOpenapiMqForNewChannel success\n") + } + }*/ + } + END: + fmt.Printf(time.Now().String() + "keepAliveConn once done\n") + time.Sleep(10 * time.Second) + + } + +} + +//exchange receive_routing_key 用于ironicmq +func InitMqTemplate(ironic string) (err error) { + ironicUrl = ironic + if err := InitIronicMq(); err != nil { + fmt.Printf(time.Now().String()+" InitMqTemplate error:%s\n", err.Error()) + // return err + } + go keepAliveConn() + //******************************************* + return nil +} + +func InitIronicMq() error { + + var err error + ironicConn, err = amqp.Dial(ironicUrl) + if err != nil { + return err + } + ironicChannel, err = ironicConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(ironicChannel, IRONIC_EXCHANGE, IRONIC_TOPIC) + if err != nil { + return err + } + return nil +} + +//连接正常,信道异常时,获取新信道 +func InitIronicMqForNewChannel() error { + + var err error + ironicChannel, err = ironicConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(ironicChannel, IRONIC_EXCHANGE, IRONIC_TOPIC) + if err != nil { + return err + } + return nil +} + +func InitOpenapiMq() error { + + var err error + openapiConn, err = amqp.Dial(openapiUrl) + if err != nil { + return err + } + openapiChannel, err = openapiConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(openapiChannel, OPENAPI_EXCHANGE, OPENAPI_TOPIC) + if err != nil { + return err + } + return nil +} + +//连接正常,信道异常时,获取新信道 +func InitOpenapiMqForNewChannel() error { + + var err error + openapiChannel, err = openapiConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(openapiChannel, OPENAPI_EXCHANGE, OPENAPI_TOPIC) + if err != nil { + return err + } + return nil +} + +func exchangeDeclare(ch *amqp.Channel, exchange, topicType string) error { + return ch.ExchangeDeclare( + exchange, // name + topicType, // type + true, // durable + false, // auto-deleted + false, // internal + false, // no-wait + nil, // arguments + ) +} diff --git a/bmp-openapi/service/redis/redis.go b/bmp-openapi/service/redis/redis.go new file mode 100644 index 0000000..f966fbe --- /dev/null +++ b/bmp-openapi/service/redis/redis.go @@ -0,0 +1,261 @@ +package redis + +import ( + "sync" + "time" + + "github.com/go-redis/redis" +) + +var redisMonitorNamespace string + +var redisOnce sync.Once + +type redisUtil struct { + *redis.Client +} + +// RedisUtil singleton redis util +var RedisUtil *redisUtil + +// InitRedis initial redisUtil instance +func InitRedis(namespace, addr, passwd string, db int) error { + redisOnce.Do(func() { + if RedisUtil == nil { + + RedisUtil = &redisUtil{ + redis.NewClient(&redis.Options{ + Addr: addr, + Password: passwd, // no password set + DB: db, // use default DB + }), + } + + redisMonitorNamespace = namespace + + } + }) + return RedisUtil.Ping().Err() +} + +// SetObjectToRedisWithExpire set string object with a expiration +func SetObjectToRedisWithExpire(key, value string, sec int) error { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + err := RedisUtil.Set(fullKey, value, time.Second*time.Duration(sec)).Err() + if err != nil { + return err + } + + return nil +} + +// SetObjectToRedis set object to Redis +func SetObjectToRedis(key string, value string) error { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + err := RedisUtil.Set(fullKey, value, 0).Err() + if err != nil { + return err + } + + return nil +} + +// GetObjectFromRedis Get object from Redis +func GetObjectFromRedis(key string) (string, error) { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + ret, err := RedisUtil.Get(fullKey).Result() + if err != nil { + return "", err + } + + return ret, nil +} + +func DelObjectFromRedis(keys []string) error { + + if len(keys) <= 0 { + return nil + } + + var fullKeys []string + for _, v := range keys { + if v != "" { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = v + } else { + fullKey = redisMonitorNamespace + if v != "" { + fullKey = redisMonitorNamespace + ":" + v + } + } + fullKeys = append(fullKeys, fullKey) + } + } + + if len(fullKeys) > 0 { + err := RedisUtil.Del(fullKeys...).Err() + if err != nil { + return err + } + } + + return nil +} + +// HSetObjectToRedis hash set object to Redis +func HSetObjectToRedis(key, field, value string) error { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + err := RedisUtil.HSet(fullKey, field, value).Err() + if err != nil { + return err + } + + return nil +} + +// HGetObjectFromRedis hash get from redis +func HGetObjectFromRedis(key, field string) (string, error) { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + ret, err := RedisUtil.HGet(fullKey, field).Result() + if err != nil { + return "", err + } + return ret, nil +} + +func HDelObjectFromRedis(key string, fields []string) error { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + if len(fields) <= 0 { + return nil + } + + err := RedisUtil.HDel(fullKey, fields...).Err() + + if err != nil { + return err + } + return nil +} + +func SaddObjectToRedis(key string, members []interface{}) error { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + if len(members) <= 0 { + return nil + } + + err := RedisUtil.SAdd(fullKey, members...).Err() + + if err != nil { + return err + } + return nil +} + +func SremObjectFromRedis(key string, members []interface{}) error { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + if len(members) <= 0 { + return nil + } + + err := RedisUtil.SRem(fullKey, members...).Err() + + if err != nil { + return err + } + return nil +} + +func SmembersFromRedis(key string) ([]string, error) { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + members, err := RedisUtil.SMembers(fullKey).Result() + + if err != nil { + return nil, err + } + return members, nil +} diff --git a/bmp-openapi/swagger.json b/bmp-openapi/swagger.json new file mode 100644 index 0000000..039b831 --- /dev/null +++ b/bmp-openapi/swagger.json @@ -0,0 +1,16669 @@ +{ + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "schemes": [ + "http" + ], + "swagger": "2.0", + "info": { + "description": "the purpose of this application is to provide an application\nthat is using plain go code to define an API\n\nThis should demonstrate all the possible comment annotations\nthat are available to turn go code into a fully compliant swagger 2.0 spec", + "title": "CPS", + "termsOfService": "there are no TOS at this moment, use at your own risk we take no responsibility", + "contact": { + "email": "minping@jd.com" + }, + "license": { + "name": "MIT", + "url": "http://opensource.org/licenses/MIT" + }, + "version": "0.0.1" + }, + "host": "bmp-openapi.bmp.local", + "basePath": "/v1", + "paths": { + "/auditLogs": { + "get": { + "description": "DescribeAuditLogs 获取审计日志列表", + "tags": [ + "auditLog" + ], + "operationId": "describeAuditLogs", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Sn", + "description": "sn", + "name": "sn", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Operation", + "description": "操作名称", + "name": "operation", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserName", + "description": "操作人", + "name": "username", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Result", + "description": "result", + "name": "result", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "StartTime", + "description": "操作时间下限", + "name": "startTime", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "EndTime", + "description": "操作时间上限", + "name": "endTime", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示所有", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeAuditLogs" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/auditLogs/types": { + "get": { + "description": "DescribeAuditLogTypes 获取审计日志类型", + "tags": [ + "auditLog" + ], + "operationId": "describeAuditLogTypes", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeAuditLogTypes" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/collect/collectDeviceInfo": { + "post": { + "description": "CollectDeviceInfo 采集设备信息", + "tags": [ + "device" + ], + "operationId": "collectDeviceInfo", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CollectDeviceInfoRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/collectDeviceInfo" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/deviceTypes": { + "get": { + "description": "DescribeDeviceTypes 获取机型列表", + "tags": [ + "deviceType" + ], + "operationId": "describeDeviceTypes", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "description": "机型id", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceType", + "description": "机型规格", + "name": "deviceType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IdcID", + "description": "机房id", + "name": "idcId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Name", + "description": "机型名称", + "name": "name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceSeries", + "description": "机型类型", + "name": "deviceSeries", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDeviceTypes" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateDeviceType 添加机型", + "tags": [ + "deviceType" + ], + "operationId": "createDeviceType", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateDeviceTypeRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createDeviceType" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/deviceTypes/associatedImage": { + "post": { + "description": "AssociatedImage 机型绑定镜像", + "tags": [ + "deviceType" + ], + "operationId": "associatedImage", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/AssociateImageRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/associatedImage" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/deviceTypes/deviceTypeImage": { + "get": { + "description": "QueryDeviceTypeImage 根据机型获取镜像", + "tags": [ + "deviceType" + ], + "operationId": "describeDeviceTypeImages", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "description": "机型id", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ImageID", + "description": "镜像id", + "name": "imageId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Architecture", + "description": "体系架构", + "name": "architecture", + "in": "query" + }, + { + "type": "string", + "x-go-name": "OsType", + "description": "操作系统平台", + "name": "osType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ImageName", + "description": "镜像名称", + "name": "imageName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Version", + "description": "版本号", + "name": "version", + "in": "query" + }, + { + "type": "string", + "x-go-name": "OsID", + "description": "操作系统ID", + "name": "osId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Source", + "description": "镜像类型,预置,自定义", + "name": "source", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDeviceTypeImages" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/deviceTypes/deviceTypeImagePartition": { + "get": { + "description": "QueryDeviceTypeImagePartition 根据机型,镜像,获取分区", + "tags": [ + "deviceType" + ], + "operationId": "describeDeviceTypeImagePartitions", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "description": "机型id", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ImageID", + "description": "镜像id", + "name": "imageId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示所有,isAll=1显示所有", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDeviceTypeImagePartitions" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/deviceTypes/deviceTypeRaid": { + "get": { + "description": "DescribeDeviceTypeRaids 根据机型获取raid", + "tags": [ + "deviceType" + ], + "operationId": "describeDeviceTypeRaids", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "description": "机型id", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "VolumeType", + "description": "系统盘还是数据盘", + "name": "volumeType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "RaidID", + "description": "raidID", + "name": "raidId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示所有", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDeviceTypeRaids" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/deviceTypes/dissociatedImage": { + "delete": { + "description": "DissociatedImage 机型解绑镜像", + "tags": [ + "deviceType" + ], + "operationId": "dissociatedImage", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/DissociatedImageRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/dissociatedImage" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/deviceTypes/{device_type_id}": { + "get": { + "description": "DescribeDeviceType 获取机型详情", + "tags": [ + "deviceType" + ], + "operationId": "describeDeviceType", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "name": "device_type_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDeviceType" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyDeviceType 修改机型信息", + "tags": [ + "deviceType" + ], + "operationId": "modifyDeviceType", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "name": "device_type_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyDeviceTypeRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyDeviceType" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteDeviceType 删除机型", + "tags": [ + "deviceType" + ], + "operationId": "deleteDeviceType", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "name": "device_type_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteDeviceType" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/deviceTypes/{device_type_id}/describeVolumes": { + "get": { + "description": "DescribeVolumesByDeviceType 根据机型获取volumes", + "tags": [ + "deviceType" + ], + "operationId": "describeVolumesByDeviceType", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "name": "device_type_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeVolumesByDeviceType" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/devices": { + "get": { + "description": "DescribeDevices 获取设备列表", + "tags": [ + "device" + ], + "operationId": "describeDevices", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IDcID", + "description": "机房id", + "name": "idcId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Sn", + "description": "设备sn", + "name": "sn", + "in": "query" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "description": "实例id", + "name": "instanceId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "InstanceName", + "description": "实例名称", + "name": "instanceName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "description": "机型id", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ManageStatus", + "description": "设备管理状态", + "name": "manageStatus", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IloIP", + "description": "带外ip", + "name": "iloIp", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IPV4", + "description": "ipv4", + "name": "ipv4", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IPV6", + "description": "ipv6", + "name": "ipv6", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceSeries", + "description": "机型类型", + "name": "deviceSeries", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserID", + "description": "所属用户id", + "name": "userId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserName", + "description": "所属用户", + "name": "userName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部,1不分页", + "name": "isAll", + "in": "query" + }, + { + "type": "string", + "x-go-name": "CollectStatus", + "description": "\"1\"表示已采集,\"2\"表示未采集,\"3\"表示采集中,4表示采集失败", + "name": "collectStatus", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDevices" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateDevice 创建设备", + "tags": [ + "device" + ], + "operationId": "createDevice", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateDevicesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createDevice" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/devices/deviceType/associate": { + "put": { + "description": "AssociateDeviceType 设备绑定机型", + "tags": [ + "device" + ], + "operationId": "deviceAssociateDeviceType", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/DeviceAssociateDeviceTypeRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/deviceAssociateDeviceType" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/devices/disks/associateDisks": { + "put": { + "description": "AssociateDeviceDisks 设备关联磁盘", + "tags": [ + "device" + ], + "operationId": "associateDeviceDisks", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/AssociateDeviceDisksRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/associateDeviceDisks" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/devices/disks/describeAssociateDisks": { + "get": { + "description": "GetAssociatedDisks 获取设备已关联的磁盘", + "tags": [ + "device" + ], + "operationId": "getAssociatedDisks", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceID", + "description": "device uuid", + "name": "deviceId", + "in": "query", + "required": true + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "description": "devicetype uuid", + "name": "deviceTypeId", + "in": "query", + "required": true + }, + { + "type": "string", + "x-go-name": "VolumeID", + "description": "volume uuid", + "name": "volumeId", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/getAssociatedDisks" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/devices/mount": { + "put": { + "description": "MountDevice 设备上架", + "tags": [ + "device" + ], + "operationId": "mountDevice", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/MountDevicesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/mountDevice" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/devices/stock": { + "delete": { + "description": "DescribeDeviceStock 获取指定机型的设备库存", + "tags": [ + "device" + ], + "operationId": "describeDeviceStock", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "name": "deviceTypeId", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDeviceStock" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/devices/unmount": { + "put": { + "description": "UnMountDevice 设备下架", + "tags": [ + "device" + ], + "operationId": "unMountDevice", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/UnMountDevicesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/unMountDevice" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/devices/{device_id}": { + "get": { + "description": "DescribeDevice 获取设备详情", + "tags": [ + "device" + ], + "operationId": "describeDevice", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceID", + "name": "device_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDevice" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyDevice 修改设备信息", + "tags": [ + "device" + ], + "operationId": "modifyDevice", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceID", + "name": "device_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyDevicesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyDevice" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteDevice 删除设备", + "tags": [ + "device" + ], + "operationId": "deleteDevice", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceID", + "name": "device_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteDevice" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/devices/{device_id}/disksDetail": { + "get": { + "description": "DescribeDeviceDisks 设备详情-磁盘", + "tags": [ + "device" + ], + "operationId": "describeDeviceDisks", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceID", + "name": "device_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeDeviceDisks" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/devices/{device_id}/remove": { + "put": { + "description": "DeleteDevice 移除设备", + "tags": [ + "device" + ], + "operationId": "removeDevice", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "DeviceID", + "name": "device_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/removeDevice" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/idcs": { + "get": { + "description": "DescribeIdcs 获取idc列表", + "tags": [ + "idc" + ], + "operationId": "describeIdcs", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Name", + "description": "机房名称", + "name": "name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "NameEn", + "description": "机房英文名称", + "name": "nameEn", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Level", + "description": "机房等级", + "name": "level", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示所有", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeIdcs" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateIdc 创建idc(接口废弃,不对外开放)", + "tags": [ + "idc" + ], + "operationId": "createIdc", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateIdcRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createIdc" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/idcs/{idc_id}": { + "get": { + "description": "DescribeIdc 获取idc详情", + "tags": [ + "idc" + ], + "operationId": "describeIdc", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "IdcID", + "name": "idc_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeIdc" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyIdc 修改idc信息", + "tags": [ + "idc" + ], + "operationId": "modifyIdc", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "IdcID", + "name": "idc_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyIdcRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyIdc" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteIdc 删除idc", + "tags": [ + "idc" + ], + "operationId": "deleteIdc", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "IdcID", + "name": "idc_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteIdc" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/images": { + "get": { + "description": "DescribeImages 获取镜像列表", + "tags": [ + "image" + ], + "operationId": "describeImages", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ImageID", + "description": "镜像ID", + "name": "imageId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ImageName", + "description": "镜像名称", + "name": "imageName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "description": "设备类型id", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Version", + "description": "版本号", + "name": "version", + "in": "query" + }, + { + "type": "string", + "x-go-name": "OsID", + "description": "操作系统ID", + "name": "osId", + "in": "query" + }, + { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "ImageIDs", + "description": "镜像ID,数组,支持多个", + "name": "imageIds", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Source", + "description": "镜像类型,预置,自定义", + "name": "source", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Architecture", + "description": "体系架构", + "name": "architecture", + "in": "query" + }, + { + "type": "string", + "x-go-name": "OsType", + "description": "操作系统平台", + "name": "osType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeImages" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateImage 添加镜像", + "tags": [ + "image" + ], + "operationId": "createImage", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateImageRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createImage" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/images/associatedDeviceType": { + "post": { + "description": "AssociatedDeviceType 镜像绑定机型", + "tags": [ + "image" + ], + "operationId": "associatedDeviceType", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/AssociateDeviceTypeRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/associatedDeviceType" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/images/dissociatedDeviceType": { + "delete": { + "description": "DissociatedDeviceType 镜像解绑机型", + "tags": [ + "image" + ], + "operationId": "dissociatedDeviceType", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/DissociatedImageRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/dissociatedDeviceType" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/images/imageDeviceTypes": { + "get": { + "description": "DescribeImageDeviceTypes 查看镜像绑定的机型", + "tags": [ + "image" + ], + "operationId": "describeImageDeviceTypes", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ImageID", + "description": "镜像ID", + "name": "imageId", + "in": "query", + "required": true + }, + { + "type": "string", + "x-go-name": "Architecture", + "description": "体系架构", + "name": "architecture", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsBind", + "description": "镜像是否绑定了机型,0查询该镜像没有绑定的机型列表 1查询该镜像已经绑定了的机型列表", + "name": "isBind", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeImageDeviceTypes" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/images/{image_id}": { + "get": { + "description": "DescribeImage 获取镜像详情", + "tags": [ + "image" + ], + "operationId": "describeImage", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ImageID", + "name": "image_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeImage" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyImage 修改镜像(暂不启用)", + "tags": [ + "image" + ], + "operationId": "modifyImage", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ImageID", + "name": "image_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyImageRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyImage" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteImage 删除镜像", + "tags": [ + "image" + ], + "operationId": "deleteImage", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ImageID", + "name": "image_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteImage" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/license/content": { + "get": { + "description": "DescribeLicenseContent 获取授权详情", + "tags": [ + "license" + ], + "operationId": "describeLicenseContent", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeLicenseContent" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/license/requestToken": { + "get": { + "description": "DescribeRequestToken 获取请求码", + "tags": [ + "license" + ], + "operationId": "describeLicenseToken", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeLicenseToken" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/license/upload": { + "post": { + "description": "UploadLicense 上传授权", + "tags": [ + "license" + ], + "operationId": "uploadLicense", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateLicenseRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/uploadLicense" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/local/users": { + "get": { + "description": "DescribeLocalUser 控制台获取用户详情", + "tags": [ + "user" + ], + "operationId": "describeLocalUser", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeLocalUser" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyLocalUser 控制台修改除密码外的个人信息", + "tags": [ + "user" + ], + "operationId": "modifyLocalUser", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyLocalUserRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyLocalUser" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/local/users/password": { + "put": { + "description": "ModifyLocalUserPassword 控制台修改个人密码", + "tags": [ + "user" + ], + "operationId": "modifyLocalUserPassword", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyUserPasswordRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyLocalUserPassword" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages": { + "get": { + "description": "GetMessageList 获取message列表(分页)", + "tags": [ + "message" + ], + "operationId": "getMessageList", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部,取值为1时表示全部", + "name": "isAll", + "in": "query" + }, + { + "type": "string", + "x-go-name": "HasRead", + "description": "0:未读;1:已读;\"\"不传表示全部", + "name": "hasRead", + "in": "query" + }, + { + "type": "string", + "x-go-name": "MessageType", + "description": "消息类型", + "name": "messageType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "MessageSubType", + "description": "消息子类型", + "name": "messageSubType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Detail", + "description": "内容模糊搜索", + "name": "detail", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getMessageList" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages/delete": { + "delete": { + "description": "DeleteMessage 删除消息(可多条)", + "tags": [ + "message" + ], + "operationId": "deleteMessage", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/DeleteMessagesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteMessage" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages/dialMail": { + "post": { + "description": "DialMail 测试邮箱设置是否正确", + "tags": [ + "message" + ], + "operationId": "dialMail", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/MailDialRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/dialMail" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages/doRead": { + "put": { + "description": "ReadMessage 将消息设置为已读(可多条)", + "tags": [ + "message" + ], + "operationId": "readMessage", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ReadMessagesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/readMessage" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages/getMessageById": { + "get": { + "description": "GetMessageById 获取消息详情,包括上一条/下一条的messageid", + "tags": [ + "message" + ], + "operationId": "getMessageById", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "MessageID", + "name": "messageId", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/getMessageById" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages/getMessageTypes": { + "get": { + "description": "GetMessageTypes 获取消息类型/子类型", + "tags": [ + "message" + ], + "operationId": "getMessageTypes", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getMessageTypes" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages/hasUnreadMessage": { + "get": { + "description": "HasUnreadMessage 获取有没有未读消息", + "tags": [ + "message" + ], + "operationId": "hasUnreadMessage", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/hasUnreadMessage" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages/mailDetail": { + "get": { + "description": "MailDetail 获取邮箱设置", + "tags": [ + "message" + ], + "operationId": "mailDetail", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/mailDetail" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages/saveIsPushMail": { + "post": { + "description": "SaveIsPushMail 保存邮箱是否通知的设置", + "tags": [ + "message" + ], + "operationId": "saveIsPushMail", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/SaveIsPushMailRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/saveIsPushMail" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/messages/statistic": { + "get": { + "description": "GetMessageStatistic 获取message总数和未读数", + "tags": [ + "message" + ], + "operationId": "getMessageStatistic", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getMessageStatistic" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorAlert/deleteAlert": { + "delete": { + "description": "DeleteAlert 删除告警", + "tags": [ + "monitorAlert" + ], + "operationId": "deleteAlert", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/DeleteAlertRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteAlert" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorAlert/describeAlert": { + "get": { + "description": "DescribeAlert 告警详情", + "tags": [ + "monitorAlert" + ], + "operationId": "describeAlert", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "AlertID", + "description": "rule uuid", + "name": "alertId", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeAlert" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorAlert/describeAlerts": { + "get": { + "description": "DescribeAlerts 告警列表", + "tags": [ + "monitorAlert" + ], + "operationId": "describeAlerts", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部,取值为1时表示全部", + "name": "isAll", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserID", + "description": "user uuid", + "name": "userId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserName", + "description": "username", + "name": "userName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "RuleName", + "description": "规则名称", + "name": "ruleName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "RuleID", + "description": "规则uuid", + "name": "ruleId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ResourceID", + "description": "资源id,目前就是实例id", + "name": "resourceId", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "StartTime", + "description": "报警时间筛选stime", + "name": "startTime", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "EndTime", + "description": "报警时间筛选etime", + "name": "endTime", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeAlerts" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorData": { + "get": { + "description": "GetMonitorData 获取图表监控数据", + "tags": [ + "monitorData" + ], + "operationId": "getMonitorData", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "MetricName", + "description": "指标名称,支持多个,用逗号隔离开", + "name": "metricName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "description": "实例id", + "name": "instanceId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Device", + "description": "标签值", + "name": "device", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "StartTime", + "description": "开始时间戳", + "name": "startTime", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "EndTime", + "description": "结束时间戳", + "name": "endTime", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "TimeInterval", + "description": "间隔多久一个点 s为单位", + "name": "timeInterval", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "LastManyTime", + "description": "最近多少时间,小时为单位", + "name": "lastManyTime", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DownSampleType", + "description": "avg, min, max, sum", + "name": "downSampleType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserName", + "description": "以下为运营平台的", + "name": "userName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IdcID", + "description": "idc uuid", + "name": "idcID", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/getMonitorData" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorProxy/desrcibeAgentStatus": { + "get": { + "description": "DesrcibeAgentStatus 获取agent状态", + "tags": [ + "monitorProxy" + ], + "operationId": "desrcibeAgentStatus", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "description": "InstanceId,多个用逗号分隔", + "name": "instanceId", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/desrcibeAgentStatus" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorProxy/desrcibeTags": { + "get": { + "description": "DesrcibeAgentStatus 获取tag列表", + "tags": [ + "monitorProxy" + ], + "operationId": "desrcibeTags", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "description": "instanceId", + "name": "instanceId", + "in": "query", + "required": true + }, + { + "type": "string", + "x-go-name": "TagName", + "description": "tagName [disk mountpoint nic]", + "name": "tagName", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/desrcibeTags" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorRule/addRule": { + "post": { + "description": "AddRule 添加规则", + "tags": [ + "monitorRule" + ], + "operationId": "addRule", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/AddRuleRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/addRule" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorRule/deleteRule": { + "delete": { + "description": "DeleteRule 删除规则", + "tags": [ + "monitorRule" + ], + "operationId": "deleteRule", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/DeleteRuleRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteRule" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorRule/describeRule": { + "get": { + "description": "DescribeRule 规则详情", + "tags": [ + "monitorRule" + ], + "operationId": "describeRule", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "RuleID", + "description": "rule uuid", + "name": "ruleId", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeRule" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorRule/describeRules": { + "get": { + "description": "DescribeRules 规则列表", + "tags": [ + "monitorRule" + ], + "operationId": "describeRules", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部,取值为1时表示全部", + "name": "isAll", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserID", + "description": "user uuid", + "name": "userId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserName", + "description": "username", + "name": "userName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "RuleName", + "description": "规则名称", + "name": "ruleName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "RuleID", + "description": "规则uuid", + "name": "ruleId", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "Status", + "description": "1 正常,2 禁用,3 报警", + "name": "status", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeRules" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorRule/disableRule": { + "put": { + "description": "DisableRule 禁用规则", + "tags": [ + "monitorRule" + ], + "operationId": "disableRule", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/DisableRuleRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/disableRule" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorRule/editRule": { + "put": { + "description": "EditRule 编辑规则", + "tags": [ + "monitorRule" + ], + "operationId": "editRule", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/EditRuleRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/editRule" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/monitorRule/enableRule": { + "put": { + "description": "EnableRule 启用规则", + "tags": [ + "monitorRule" + ], + "operationId": "enableRule", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/EnableRuleRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/enableRule" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/oss": { + "get": { + "description": "DescribeOSs 获取os列表(暂不启用)", + "tags": [ + "os" + ], + "operationId": "describeOSs", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "OsName", + "description": "操作系统名称", + "name": "osName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "OsType", + "description": "操作系统平台", + "name": "osType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "OsVersion", + "description": "操作系统版本", + "name": "osVersion", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示所有", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeOSs" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateOS 添加操作系统(暂不启用)", + "tags": [ + "os" + ], + "operationId": "createOS", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateOSRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createOS" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/oss/{os_id}": { + "get": { + "description": "DescribeOS 获取os系统详情(暂不启用)", + "tags": [ + "os" + ], + "operationId": "describeOS", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "OsID", + "name": "os_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeOS" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyOS 修改os信息(暂不启用)", + "tags": [ + "os" + ], + "operationId": "modifyOS", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "OsID", + "name": "os_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyOSRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyOS" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteOS 删除os(暂不启用)", + "tags": [ + "os" + ], + "operationId": "deleteOS", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "OsID", + "name": "os_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteOS" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances": { + "get": { + "description": "DescribeProjectInstances 获取实例列表", + "tags": [ + "instance" + ], + "operationId": "describeProjectInstances", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "description": "实例ID", + "name": "instanceId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "InstanceName", + "description": "实例名称,模糊搜索", + "name": "instanceName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceTypeID", + "description": "设备类型ID", + "name": "deviceTypeId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Status", + "description": "运行状态", + "name": "status", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceID", + "description": "设备ID", + "name": "deviceId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Sn", + "description": "SN", + "name": "sn", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IdcID", + "description": "机房ID", + "name": "idcId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "description": "项目ID", + "name": "projectId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IloIP", + "description": "带外ip,精确搜索", + "name": "ilo_ip", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IPV4", + "description": "ipv4,精确搜索", + "name": "ipv4", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IPV6", + "description": "ipv6,精确搜索", + "name": "ipv6", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部,取值为1时表示全部", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeProjectInstances" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateProjectInstance 创建实例", + "tags": [ + "instance" + ], + "operationId": "createProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateInstanceRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/batch/instances:deleteInstances": { + "delete": { + "description": "DeleteInstances 批量删除实例", + "tags": [ + "instance" + ], + "operationId": "deleteInstances", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/DeleteInstancesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteInstances" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/batch/instances:modifyInstances": { + "put": { + "description": "ModifyInstances 批量修改实例名称", + "tags": [ + "instance" + ], + "operationId": "modifyInstances", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyInstancesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyInstances" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/batch/instances:resetPasswd": { + "put": { + "description": "ResetInstancesPasswd 批量重置密码", + "tags": [ + "instance" + ], + "operationId": "resetProjectInstancesPasswd", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ResetInstancesPasswdRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/resetProjectInstancesPasswd" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/batch/instances:restartInstances": { + "put": { + "description": "StartInstances 批量重启", + "tags": [ + "instance" + ], + "operationId": "restartInstances", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/RestartInstancesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/restartInstances" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/batch/instances:startInstances": { + "put": { + "description": "StartInstances 批量开机", + "tags": [ + "instance" + ], + "operationId": "startInstances", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/StartInstancesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/startInstances" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/batch/instances:stopInstances": { + "put": { + "description": "StartInstances 批量关机", + "tags": [ + "instance" + ], + "operationId": "stopInstances", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/StopInstancesRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/stopInstances" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}": { + "get": { + "description": "DescribeProjectInstance 获取实例详情", + "tags": [ + "instance" + ], + "operationId": "describeProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "description": "实例uuid", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyProjectInstance 修改实例信息", + "tags": [ + "instance" + ], + "operationId": "modifyProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyInstanceRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteProjectInstance 删除实例", + "tags": [ + "instance" + ], + "operationId": "deleteProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/lock": { + "put": { + "description": "LockProjectInstance 锁定实例", + "tags": [ + "instance" + ], + "operationId": "lockProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/lockProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/reinstallInstance": { + "put": { + "description": "ReinstallInstance 重装实例", + "tags": [ + "instance" + ], + "operationId": "reinstallProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ReinstallInstanceRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/reinstallProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/resetStatus": { + "put": { + "description": "ResetInstanceStatus 重置实例状态", + "tags": [ + "instance" + ], + "operationId": "resetInstanceStatus", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/resetInstanceStatus" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/resetpasswd": { + "put": { + "description": "ResetPasswd 重置密码", + "tags": [ + "instance" + ], + "operationId": "resetProjectInstancePasswd", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ResetInstancePasswdRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/resetProjectInstancePasswd" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/restart": { + "put": { + "description": "RestartProjectInstance 实例重启", + "tags": [ + "instance" + ], + "operationId": "restartProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/restartProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/start": { + "put": { + "description": "StartProjectInstance 实例开机", + "tags": [ + "instance" + ], + "operationId": "startProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/startProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/stop": { + "put": { + "description": "StopProjectInstance 实例关机", + "tags": [ + "instance" + ], + "operationId": "stopProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/stopProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/project/instances/{instance_id}/unlock": { + "put": { + "description": "UnLockProjectInstance 解锁实例", + "tags": [ + "instance" + ], + "operationId": "unLockProjectInstance", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "InstanceID", + "name": "instance_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/unLockProjectInstance" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/raids": { + "get": { + "description": "DescribeRaids 获取raid列表", + "tags": [ + "raid" + ], + "operationId": "describeRaids", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeRaids" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateRaid 创建raid(暂不启用)", + "tags": [ + "raid" + ], + "operationId": "createRaid", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateRaidRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createRaid" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/raids/deviceTypeRaid": { + "post": { + "description": "CreateDeviceTypeRaid ... 机型和raid关联(暂不启用)", + "tags": [ + "raid" + ], + "operationId": "createDeviceTypeRaid", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateDeviceTypeRaidRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createDeviceTypeRaid" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteDeviceTypeRaid ... 机型和raid解绑(暂不启用)", + "tags": [ + "raid" + ], + "operationId": "deleteDeviceTypeRaid", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/DeleteDeviceTypeRaidRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteDeviceTypeRaid" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/raids/{raid_id}": { + "get": { + "description": "DescribeRaid 获取raid详情", + "tags": [ + "raid" + ], + "operationId": "describeRaid", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "RaidID", + "name": "raid_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeRaid" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyRaid 修改raid信息(暂不启用)", + "tags": [ + "raid" + ], + "operationId": "modifyRaid", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "RaidID", + "name": "raid_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyRaidRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyRaid" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteRaid 删除raid(暂不启用)", + "tags": [ + "raid" + ], + "operationId": "deleteRaid", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "RaidID", + "name": "raid_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteRaid" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/resources": { + "get": { + "description": "DescribeResources 根据某个字段值精确查询对应的资源列表(如根据imageName查询镜像列表,根据idcName查询机房列表)", + "tags": [ + "resource" + ], + "operationId": "describeResources", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "Name", + "description": "机房名称\nIdcName string `json:\"idcName\"`\n机房英文名称\nIdcNameEn string `json:\"idcNameEn\"`*/\n机型名称", + "name": "name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DeviceType", + "description": "机型规格", + "name": "deviceType", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ImageName", + "description": "镜像名称", + "name": "imageName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserName", + "description": "用户名称", + "name": "userName", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeResources" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/roles": { + "get": { + "description": "DescribeRoles 获取角色列表", + "tags": [ + "role" + ], + "operationId": "describeRoles", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示所有", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeRoles" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateRole 创建角色(暂不启用)", + "tags": [ + "role" + ], + "operationId": "createRole", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateRoleRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createRole" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/roles/roleInfo/current": { + "get": { + "description": "CurrentRole 获取当前登录用户的角色", + "tags": [ + "role" + ], + "operationId": "currentRole", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + } + ], + "responses": { + "200": { + "$ref": "#/responses/currentRole" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/roles/{role_id}": { + "get": { + "description": "DescribeRole 获取角色详情", + "tags": [ + "role" + ], + "operationId": "describeRole", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "RoleID", + "name": "role_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeRole" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyRole 修改角色信息(暂不启用)", + "tags": [ + "role" + ], + "operationId": "modifyRole", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "RoleID", + "name": "role_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyRoleRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyRole" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteRole 删除角色(暂不启用)", + "tags": [ + "role" + ], + "operationId": "deleteRole", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "RoleID", + "name": "role_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteRole" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/apikeys": { + "get": { + "description": "DescribeUserAPIKeys 获取APIKey列表", + "tags": [ + "apiKey" + ], + "operationId": "describeUserAPIKeys", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Name", + "description": "秘钥对名称", + "name": "name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Type", + "description": "Token类型, [system/user]", + "name": "type", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否查询全部/导出", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUserAPIKeys" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateUserApikey 创建apikey", + "tags": [ + "apiKey" + ], + "operationId": "createUserApikey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateApikeyRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createUserApikey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/apikeys/{apikey_id}": { + "get": { + "description": "DescribeUserAPIKey 获取apikey详情", + "tags": [ + "apiKey" + ], + "operationId": "describeUserAPIKey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ApikeyID", + "name": "apikey_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUserAPIKey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyUserApikey 修改apikey(暂不启用)", + "tags": [ + "apiKey" + ], + "operationId": "modifyUserApikey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ApikeyID", + "name": "apikey_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyApikeyRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyUserApikey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteUserApikey 删除某个apikey", + "tags": [ + "apiKey" + ], + "operationId": "deleteUserApikey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ApikeyID", + "name": "apikey_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteUserApikey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/projects": { + "get": { + "description": "DescribeUserProjects 获取项目列表", + "tags": [ + "project" + ], + "operationId": "describeUserProjects", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "ProjectName", + "description": "项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-”", + "name": "projectName", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "Owned", + "name": "owned", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUserProjects" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateUserProject 创建项目", + "tags": [ + "project" + ], + "operationId": "createUserProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateProjectRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createUserProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/projects/{project_id}": { + "get": { + "description": "DescribeUserProject 获取项目详情", + "tags": [ + "project" + ], + "operationId": "describeUserProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUserProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyUserProject 修改项目信息", + "tags": [ + "project" + ], + "operationId": "modifyUserProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyProjectRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyUserProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteUserProject 删除项目", + "tags": [ + "project" + ], + "operationId": "deleteUserProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteUserProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/projects/{project_id}/cancelShare": { + "put": { + "description": "CancelShareUserProject 取消共享项目", + "tags": [ + "project" + ], + "operationId": "cancelShareUserProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ShareProjectRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/cancelShareUserProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/projects/{project_id}/share": { + "put": { + "description": "ShareUserProject 共享项目", + "tags": [ + "project" + ], + "operationId": "shareUserProject", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "ProjectID", + "name": "project_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ShareProjectRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/shareUserProject" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/sshkeys": { + "get": { + "description": "DescribeUserSshKeys 获取个人sshkey列表", + "tags": [ + "sshkey" + ], + "operationId": "describeUserSshKeys", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "Name", + "description": "秘钥名称", + "name": "name", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUserSshKeys" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateUserSshkey 创建个人sshkey", + "tags": [ + "sshkey" + ], + "operationId": "createUserSshkey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateSshkeyRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createUserSshkey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/sshkeys/instances/{sshkey_id}": { + "get": { + "description": "GetInstancesBySshkey 根据sshkey获取实例列表", + "tags": [ + "sshkey" + ], + "operationId": "getInstancesBySshkey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "SshkeyID", + "name": "sshkey_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/getInstancesBySshkey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/user/sshkeys/{sshkey_id}": { + "get": { + "description": "DescribeUserSshKey 获取sshkey详情", + "tags": [ + "sshkey" + ], + "operationId": "describeUserSshKey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "SshkeyID", + "name": "sshkey_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUserSshKey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyUserSshkey 修改sshkey", + "tags": [ + "sshkey" + ], + "operationId": "modifyUserSshkey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "SshkeyID", + "name": "sshkey_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifySshkeyRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyUserSshkey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteUserSshkey 删除sshkey", + "tags": [ + "sshkey" + ], + "operationId": "deleteUserSshkey", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "SshkeyID", + "name": "sshkey_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteUserSshkey" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/users": { + "get": { + "description": "DescribeUsers 获取用户列表", + "tags": [ + "user" + ], + "operationId": "describeUsers", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber", + "description": "页码", + "name": "pageNumber", + "in": "query" + }, + { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize", + "description": "每页数量", + "name": "pageSize", + "in": "query" + }, + { + "type": "string", + "x-go-name": "RoleID", + "description": "角色uuid", + "name": "roleId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "DefaultProjectID", + "description": "项目uuid", + "name": "defaultProjectId", + "in": "query" + }, + { + "type": "string", + "x-go-name": "UserName", + "description": "用户名", + "name": "userName", + "in": "query" + }, + { + "type": "string", + "x-go-name": "IsAll", + "description": "是否显示全部, isAll=1表示全部", + "name": "isAll", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUsers" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "post": { + "description": "CreateUser 创建用户", + "tags": [ + "user" + ], + "operationId": "createUser", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/CreateUserRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/createUser" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/users/getUserByName": { + "get": { + "description": "DescribeUserByName 根据用户名获取用户详情", + "tags": [ + "user" + ], + "operationId": "describeUserByName", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "UserName", + "description": "用户名,唯一", + "name": "userName", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUserByName" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/users/verify": { + "post": { + "description": "VerifyUser 鉴定用户", + "tags": [ + "user" + ], + "operationId": "verifyUser", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/VerifyUserRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/verifyUser" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + }, + "/users/{user_id}": { + "get": { + "description": "DescribeUser 获取用户详情", + "tags": [ + "user" + ], + "operationId": "describeUser", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "UserID", + "name": "user_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/describeUser" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "put": { + "description": "ModifyUser 修改用户信息", + "tags": [ + "user" + ], + "operationId": "modifyUser", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid, deprecated", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "UserID", + "name": "user_id", + "in": "path", + "required": true + }, + { + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/ModifyUserRequest" + } + } + ], + "responses": { + "200": { + "$ref": "#/responses/modifyUser" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + }, + "delete": { + "description": "DeleteUser 删除用户", + "tags": [ + "user" + ], + "operationId": "deleteUser", + "parameters": [ + { + "type": "string", + "x-go-name": "TraceID", + "description": "流量唯一id", + "name": "traceId", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "Authorization", + "description": "demo: curl -X GET -H \"Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu\" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token", + "name": "authorization", + "in": "header", + "required": true + }, + { + "type": "string", + "x-go-name": "BmpUserID", + "description": "用户uuid", + "name": "bmpUserId", + "in": "header" + }, + { + "type": "string", + "x-go-name": "BmpLanguage", + "description": "用户语言 [zh_CN, en_US]", + "name": "bmpLanguage", + "in": "header" + }, + { + "type": "string", + "x-go-name": "UserID", + "name": "user_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/deleteUser" + }, + "default": { + "$ref": "#/responses/ErrorResponse" + } + } + } + } + }, + "definitions": { + "AddRuleRequest": { + "type": "object", + "required": [ + "ruleName", + "dimension", + "resource", + "triggerOption", + "noticeOption", + "instanceIds" + ], + "properties": { + "deviceTag": { + "description": "盘符、挂载点、网口列表", + "type": "string", + "x-go-name": "DeviceTag" + }, + "dimension": { + "description": "维度 [instance、disk、mountpoint、nic]", + "type": "string", + "x-go-name": "Dimension" + }, + "instanceIds": { + "description": "实例id列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + }, + "noticeOption": { + "$ref": "#/definitions/RuleNotice" + }, + "resource": { + "description": "资源类型,目前只支持instance", + "type": "string", + "x-go-name": "Resource" + }, + "ruleName": { + "description": "规则名称", + "type": "string", + "x-go-name": "RuleName" + }, + "triggerOption": { + "description": "触发条件", + "type": "array", + "items": { + "$ref": "#/definitions/RuleTrigger" + }, + "x-go-name": "TriggerOption" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "AgentStatusItem": { + "type": "object", + "properties": { + "agent_version": { + "type": "string", + "x-go-name": "AgentVersion" + }, + "instance_id": { + "type": "string", + "x-go-name": "InstanceID" + }, + "sn": { + "type": "string", + "x-go-name": "SN" + }, + "status": { + "description": "1-\u003erunning 2-\u003estopped 0-\u003eunknown", + "type": "integer", + "format": "int64", + "x-go-name": "Status" + }, + "statusName": { + "description": "status 运行 停止 未知", + "type": "string", + "x-go-name": "StatusName" + }, + "timestamp": { + "type": "integer", + "format": "int64", + "x-go-name": "Timestamp" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "AgentStatusResponse": { + "type": "object", + "properties": { + "agentStatus": { + "type": "array", + "items": { + "$ref": "#/definitions/AgentStatusItem" + }, + "x-go-name": "AgentStatus" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Alert": { + "type": "object", + "properties": { + "alertId": { + "description": "alert uuid", + "type": "string", + "x-go-name": "AlertID" + }, + "alertLevel": { + "description": "1表示一般,2表示严重,3表示紧急", + "type": "integer", + "format": "int64", + "x-go-name": "AlertLevel" + }, + "alertLevelDescription": { + "description": "级别描述", + "type": "string", + "x-go-name": "AlertLevelDescription" + }, + "alertPeriod": { + "description": "告警持续时间(分钟为单位)", + "type": "integer", + "format": "int64", + "x-go-name": "AlertPeriod" + }, + "alertTime": { + "description": "告警时间戳", + "type": "integer", + "format": "int64", + "x-go-name": "AlertTime" + }, + "alertValue": { + "description": "报警值", + "type": "string", + "x-go-name": "AlertValue" + }, + "createdTime": { + "description": "创建时间戳", + "type": "integer", + "format": "int64", + "x-go-name": "CreatedTime" + }, + "instance": { + "$ref": "#/definitions/Instance" + }, + "resource": { + "description": "资源类型 [只支持instance一种]", + "type": "string", + "x-go-name": "Resource" + }, + "resourceId": { + "description": "资源id,目前就是实例id", + "type": "string", + "x-go-name": "ResourceID" + }, + "resourceName": { + "description": "资源名称,目前就是实例名称", + "type": "string", + "x-go-name": "ResourceName" + }, + "rule": { + "$ref": "#/definitions/Rule" + }, + "trigger": { + "description": "触发条件,接口需要翻译", + "type": "string", + "x-go-name": "Trigger" + }, + "triggerDescription": { + "description": "触发条件描述", + "type": "string", + "x-go-name": "TriggerDescription" + }, + "userId": { + "description": "通知对象 userid", + "type": "string", + "x-go-name": "UserID" + }, + "userName": { + "description": "通知对象 用户名", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "AlertList": { + "type": "object", + "properties": { + "instances": { + "description": "rules数组", + "type": "array", + "items": { + "$ref": "#/definitions/Alert" + }, + "x-go-name": "Alerts" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Apikey": { + "type": "object", + "required": [ + "apiKeyId", + "name", + "readOnly", + "token", + "type", + "userId" + ], + "properties": { + "apiKeyId": { + "description": "apikey uuid", + "type": "string", + "x-go-name": "ApikeyID" + }, + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "id": { + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "name": { + "description": "名称", + "type": "string", + "x-go-name": "Name" + }, + "readOnly": { + "description": "是否支持只读, [0/1], 1表示只读", + "type": "integer", + "format": "int8", + "x-go-name": "ReadOnly" + }, + "token": { + "description": "32位字符令牌,使用token来独立访问openapi", + "type": "string", + "x-go-name": "Token" + }, + "type": { + "description": "apikey的类型,[system/user]", + "type": "string", + "x-go-name": "Type" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "userId": { + "description": "所属用户uuid", + "type": "string", + "x-go-name": "UserID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ApikeyId": { + "type": "object", + "required": [ + "apikeyId" + ], + "properties": { + "apikeyId": { + "description": "apikey uuid", + "type": "string", + "x-go-name": "ApikeyId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ApikeyInfo": { + "type": "object", + "properties": { + "apikey": { + "$ref": "#/definitions/Apikey" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ApikeyList": { + "type": "object", + "properties": { + "apikeys": { + "type": "array", + "items": { + "$ref": "#/definitions/Apikey" + }, + "x-go-name": "Apikeys" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "AssociateDeviceDiskSpec": { + "type": "object", + "properties": { + "diskId": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "DiskIDs" + }, + "volumeId": { + "type": "string", + "x-go-name": "VolumeID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "AssociateDeviceDisksRequest": { + "type": "object", + "required": [ + "deviceId", + "deviceTypeId", + "volumes" + ], + "properties": { + "deviceId": { + "description": "device uuid", + "type": "string", + "x-go-name": "DeviceID" + }, + "deviceTypeId": { + "description": "设备类型id", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "volumes": { + "description": "volumeid和磁盘uuid列表", + "type": "array", + "items": { + "$ref": "#/definitions/AssociateDeviceDiskSpec" + }, + "x-go-name": "Volumes" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "AssociateDeviceTypeRequest": { + "type": "object", + "required": [ + "imageId", + "deviceTypeIds" + ], + "properties": { + "deviceTypeIds": { + "description": "设备类型id,数组,支持多个", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "DeviceTypeIDs" + }, + "imageId": { + "description": "镜像ID,", + "type": "string", + "x-go-name": "ImageID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "AssociateImageRequest": { + "type": "object", + "required": [ + "deviceTypeId", + "imageIds" + ], + "properties": { + "deviceTypeId": { + "description": "设备类型id", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "imageIds": { + "description": "镜像ID,数组,支持多个", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "ImageIDs" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "AuditLog": { + "type": "object", + "properties": { + "deviceId": { + "description": "device_id", + "type": "string", + "x-go-name": "DeviceID" + }, + "failReason": { + "description": "失败原因", + "type": "string", + "x-go-name": "FailReason" + }, + "finishTime": { + "description": "完成时间", + "type": "integer", + "format": "int64", + "x-go-name": "FinishTime" + }, + "id": { + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "instanceId": { + "description": "instance_id", + "type": "string", + "x-go-name": "InstanceID" + }, + "logid": { + "description": "日志uuid", + "type": "string", + "x-go-name": "LogID" + }, + "operateTime": { + "description": "操作时间", + "type": "integer", + "format": "int64", + "x-go-name": "OperateTime" + }, + "operation": { + "description": "操作", + "type": "string", + "x-go-name": "Operation" + }, + "operationName": { + "description": "操作名称", + "type": "string", + "x-go-name": "OperationName" + }, + "result": { + "description": "结果 success/fail", + "type": "string", + "x-go-name": "Result" + }, + "sn": { + "description": "sn", + "type": "string", + "x-go-name": "Sn" + }, + "userID": { + "description": "操作人", + "type": "string", + "x-go-name": "UserID" + }, + "userName": { + "description": "操作人", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "AuditLogList": { + "type": "object", + "properties": { + "auditLogs": { + "description": "机型列表", + "type": "array", + "items": { + "$ref": "#/definitions/AuditLog" + }, + "x-go-name": "AuditLogs" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "AuditLogsType": { + "type": "object", + "properties": { + "name": { + "description": "name,自动适配中英文", + "type": "string", + "x-go-name": "Name" + }, + "operation": { + "description": "数据库中存储的operation", + "type": "string", + "x-go-name": "Operation" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "CollectDeviceInfoRequest": { + "type": "object", + "required": [ + "collects" + ], + "properties": { + "collects": { + "description": "待采集项", + "type": "array", + "items": { + "$ref": "#/definitions/CollectItem" + }, + "x-go-name": "Collects" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CollectItem": { + "type": "object", + "required": [ + "sn" + ], + "properties": { + "allowOverride": { + "description": "可选参数。 传参:True, False 。True表示传入的raid_driver值将覆盖已适配机器的raid_driver", + "type": "boolean", + "x-go-name": "AllowOverride", + "x-nullable": true + }, + "sn": { + "description": "sn", + "type": "string", + "x-go-name": "Sn" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CommonResponse": { + "type": "object", + "properties": { + "success": { + "description": "操作是否成功 [true/false]", + "type": "boolean", + "x-go-name": "Success" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "CreateApikeyRequest": { + "type": "object", + "required": [ + "name", + "readOnly", + "type" + ], + "properties": { + "name": { + "description": "秘钥对名称", + "type": "string", + "x-go-name": "Name" + }, + "readOnly": { + "description": "是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法", + "type": "integer", + "format": "int8", + "x-go-name": "ReadOnly" + }, + "type": { + "description": "Token类型, [system/user]", + "type": "string", + "x-go-name": "Type" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateDeviceSpec": { + "type": "object", + "required": [ + "sn", + "cabinet", + "uPosition", + "iloIp", + "mac1", + "description", + "mask", + "gateway", + "privateIpv4" + ], + "properties": { + "cabinet": { + "description": "品牌", + "type": "string", + "x-go-name": "Cabinet" + }, + "description": { + "description": "MAC2(eth1)", + "type": "string", + "x-go-name": "Description" + }, + "gateway": { + "description": "eth1子网掩码\nMaskEth1 string `json:\"maskEth1\" validate:\"omitempty,min=1,max=128\"` // eth1子网掩码\n网关地址", + "type": "string", + "x-go-name": "Gateway" + }, + "iloIp": { + "description": "带外IP", + "type": "string", + "x-go-name": "IloIP" + }, + "iloPassword": { + "description": "带外密码", + "type": "string", + "x-go-name": "IloPassword" + }, + "iloUser": { + "description": "带外账号", + "type": "string", + "x-go-name": "IloUser" + }, + "instanceId": { + "type": "string", + "x-go-name": "InstanceID" + }, + "mac1": { + "description": "MAC1(eth0)", + "type": "string", + "x-go-name": "Mac1" + }, + "manageStatus": { + "description": "设备状态,默认已入库", + "type": "string", + "x-go-name": "ManageStatus" + }, + "mask": { + "description": "网口交换机IP\nSwitchIP string `json:\"switchIp\"` // 网口交换机IP\n子网掩码", + "type": "string", + "x-go-name": "Mask" + }, + "privateIpv4": { + "description": "内网IPV4", + "type": "string", + "x-go-name": "PrivateIPv4" + }, + "privateIpv6": { + "description": "eth1内网IPV4(非bond模式时传值)\nPrivateEth1IPv4 string `json:\"privateEth1Ipv4\" validate:\"omitempty,min=1,max=128\"` // eth1内网IPV4\n内网IPV6", + "type": "string", + "x-go-name": "PrivateIPv6" + }, + "sn": { + "description": "设备SN", + "type": "string", + "x-go-name": "Sn" + }, + "uPosition": { + "description": "所在U位", + "type": "string", + "x-go-name": "UPosition" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateDeviceTypeRaidRequest": { + "type": "object", + "properties": { + "DeviceTypeId": { + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "availableValue": { + "type": "integer", + "format": "int64", + "x-go-name": "AvailableValue" + }, + "deviceType": { + "type": "string", + "x-go-name": "DeviceType" + }, + "diskType": { + "type": "string", + "x-go-name": "DiskType" + }, + "raidId": { + "type": "string", + "x-go-name": "RaidID" + }, + "systemPartitionCount": { + "type": "integer", + "format": "int64", + "x-go-name": "SystemPartitionCount" + }, + "volumeDetail": { + "type": "string", + "x-go-name": "VolumeDetail" + }, + "volumeType": { + "type": "string", + "x-go-name": "VolumeType" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateDeviceTypeRequest": { + "type": "object", + "required": [ + "idcId", + "name", + "deviceType", + "deviceSeries", + "architecture", + "height", + "cpuAmount", + "cpuCores", + "cpuManufacturer", + "cpuModel", + "cpuFrequency", + "memType", + "memSize", + "memAmount", + "memFrequency", + "nicAmount", + "interfaceMode", + "nicRate", + "cpuSpec", + "memSpec", + "volumes" + ], + "properties": { + "architecture": { + "description": "体系架构,1-64", + "type": "string", + "x-go-name": "Architecture" + }, + "boot_mode": { + "description": "boot模式【UEFI Legacy/BIOS】支持多选,逗号分隔", + "type": "string", + "x-go-name": "BootMode" + }, + "cpuAmount": { + "description": "cpu数量1,10000", + "type": "integer", + "format": "int64", + "x-go-name": "CPUAmount" + }, + "cpuCores": { + "description": "单个cpu内核数1,10000", + "type": "integer", + "format": "int64", + "x-go-name": "CPUCores" + }, + "cpuFrequency": { + "description": "cpu频率(G)1-64", + "type": "string", + "x-go-name": "CPUFrequency" + }, + "cpuManufacturer": { + "description": "cpu厂商1-64", + "type": "string", + "x-go-name": "CPUManufacturer" + }, + "cpuModel": { + "description": "cpu处理器型号1-64", + "type": "string", + "x-go-name": "CPUModel" + }, + "cpuSpec": { + "description": "CPU 预置规格", + "type": "string", + "x-go-name": "CpuSpec" + }, + "description": { + "description": "描述0-256", + "type": "string", + "x-go-name": "Description" + }, + "deviceSeries": { + "description": "机型类型,如computer storage gpu other", + "type": "string", + "x-go-name": "DeviceSeries" + }, + "deviceType": { + "description": "机型规格1-64", + "type": "string", + "x-go-name": "DeviceType" + }, + "gpuAmount": { + "description": "gpu数量0-1000", + "type": "integer", + "format": "int64", + "x-go-name": "GpuAmount" + }, + "gpuManufacturer": { + "description": "gpu品牌0-64", + "type": "string", + "x-go-name": "GpuManufacturer" + }, + "gpuModel": { + "description": "gpu型号0-64", + "type": "string", + "x-go-name": "GpuModel" + }, + "height": { + "description": "【高度(U)】:显示机型高度 2,4", + "type": "integer", + "format": "int64", + "x-go-name": "Height" + }, + "idcId": { + "description": "机房id", + "type": "string", + "x-go-name": "IDcID" + }, + "interfaceMode": { + "description": "【网口模式】【网络设置】: bond,dual,single", + "type": "string", + "x-go-name": "InterfaceMode" + }, + "isNeedRaid": { + "description": "阵列卡是否需要配置 1 需要配置 2无需配置", + "type": "string", + "x-go-name": "IsNeedRaid" + }, + "memAmount": { + "description": "内存数量1-10000", + "type": "integer", + "format": "int64", + "x-go-name": "MemAmount" + }, + "memFrequency": { + "description": "内存主频(MHz)1-10000", + "type": "integer", + "format": "int64", + "x-go-name": "MemFrequency" + }, + "memSize": { + "description": "单个内存大小1,10000(GB)", + "type": "integer", + "format": "int64", + "x-go-name": "MemSize" + }, + "memSpec": { + "description": "内存 预置规格", + "type": "string", + "x-go-name": "MemSpec" + }, + "memType": { + "description": "内存接口(DDR DDR2 DDR3 DDR4 DDR5)", + "type": "string", + "x-go-name": "MemType" + }, + "name": { + "description": "机型名称1-64", + "type": "string", + "x-go-name": "Name" + }, + "nicAmount": { + "description": "网卡数量1-10000", + "type": "integer", + "format": "int64", + "x-go-name": "NicAmount" + }, + "nicRate": { + "description": "网卡传输速率(GE) 1-10000", + "type": "integer", + "format": "int64", + "x-go-name": "NicRate" + }, + "volumes": { + "description": "卷管理", + "type": "array", + "items": { + "$ref": "#/definitions/VolumeItem" + }, + "x-go-name": "Volumes" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateDevicesRequest": { + "type": "object", + "required": [ + "idcId", + "devices" + ], + "properties": { + "devices": { + "description": "机型uuid, 上传创建设备时不绑定机型,上架时才绑定机型 20240517 minping", + "type": "array", + "items": { + "$ref": "#/definitions/CreateDeviceSpec" + }, + "x-go-name": "Devices" + }, + "idcId": { + "description": "机房uuid", + "type": "string", + "x-go-name": "IDcID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateIdcRequest": { + "type": "object", + "required": [ + "name", + "nameEn", + "shortname", + "level" + ], + "properties": { + "address": { + "description": "机房地址 0-256", + "type": "string", + "x-go-name": "Address" + }, + "iloPassword": { + "description": "带外密码 0-64", + "type": "string", + "x-go-name": "IloPassword" + }, + "iloUser": { + "description": "带外用户名 0-64", + "type": "string", + "x-go-name": "IloUser" + }, + "level": { + "description": "机房等级 1-64", + "type": "string", + "x-go-name": "Level" + }, + "name": { + "description": "机房名称 1-64", + "type": "string", + "x-go-name": "Name" + }, + "nameEn": { + "description": "机房英文名称 1-64", + "type": "string", + "x-go-name": "NameEn" + }, + "shortname": { + "description": "机房缩写 1-64", + "type": "string", + "x-go-name": "Shortname" + }, + "switchPassword1": { + "description": "交换机密码1 0-64", + "type": "string", + "x-go-name": "SwitchPassword1" + }, + "switchPassword2": { + "description": "交换机密码2 0-64", + "type": "string", + "x-go-name": "SwitchPassword2" + }, + "switchUser1": { + "description": "交换机用户1 0-64", + "type": "string", + "x-go-name": "SwitchUser1" + }, + "switchUser2": { + "description": "交换机用户2 0-64", + "type": "string", + "x-go-name": "SwitchUser2" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateImageRequest": { + "type": "object", + "required": [ + "imageName", + "architecture", + "osType", + "Version", + "format", + "boot_mode", + "filename", + "url", + "hash" + ], + "properties": { + "Version": { + "description": "版本号", + "type": "string" + }, + "architecture": { + "description": "体系架构", + "type": "string", + "x-go-name": "Architecture" + }, + "boot_mode": { + "description": "引导模式【UEFI Legacy/BIOS】", + "type": "string", + "x-go-name": "BootMode" + }, + "dataPartition": { + "description": "数据分区信息", + "type": "string", + "x-go-name": "DataPartition" + }, + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description" + }, + "filename": { + "description": "镜像文件名称", + "type": "string", + "x-go-name": "Filename" + }, + "format": { + "description": "镜像文件类型", + "type": "string", + "x-go-name": "Format" + }, + "hash": { + "description": "文件hash值", + "type": "string", + "x-go-name": "Hash" + }, + "imageName": { + "description": "镜像名称", + "type": "string", + "x-go-name": "ImageName" + }, + "osType": { + "description": "操作系统平台", + "type": "string", + "x-go-name": "OsType" + }, + "source": { + "description": "镜像类型,预置,自定义", + "type": "string", + "x-go-name": "Source" + }, + "systemPartition": { + "description": "系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:50GiB,swap)", + "type": "string", + "x-go-name": "SystemPartition" + }, + "url": { + "description": "镜像上传地址", + "type": "string", + "x-go-name": "Url" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateInstanceRequest": { + "type": "object", + "required": [ + "projectId", + "idcId", + "deviceTypeId", + "imageId", + "systemVolumeRaidId", + "instanceName" + ], + "properties": { + "boot_mode": { + "type": "string", + "x-go-name": "BootMode" + }, + "count": { + "description": "创建数量", + "type": "integer", + "format": "int64", + "x-go-name": "Count" + }, + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description" + }, + "deviceTypeId": { + "description": "设备类型ID", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "hostname": { + "description": "主机名称", + "type": "string", + "x-go-name": "HostName" + }, + "idcId": { + "description": "机房ID", + "type": "string", + "x-go-name": "IdcID" + }, + "imageId": { + "description": "镜像ID", + "type": "string", + "x-go-name": "ImageID" + }, + "instanceName": { + "description": "实例名称", + "type": "string", + "x-go-name": "InstanceName" + }, + "password": { + "description": "密码", + "type": "string", + "x-go-name": "Password" + }, + "projectId": { + "description": "项目ID", + "type": "string", + "x-go-name": "ProjectID" + }, + "sshKeyId": { + "description": "秘钥ID", + "type": "string", + "x-go-name": "SshKeyID" + }, + "systemPartition": { + "description": "系统盘分区", + "type": "array", + "items": { + "$ref": "#/definitions/Partition" + }, + "x-go-name": "SystemPartition" + }, + "systemVolumeRaidId": { + "description": "系统盘RAID ID", + "type": "string", + "x-go-name": "SystemVolumeRaidID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateLicenseRequest": { + "type": "object", + "properties": { + "content": { + "type": "string", + "x-go-name": "Content" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateOSRequest": { + "type": "object", + "required": [ + "osName", + "osType", + "architecture", + "bits", + "osVersion" + ], + "properties": { + "architecture": { + "description": "体系架构", + "type": "string", + "x-go-name": "Architecture" + }, + "bits": { + "description": "位数", + "type": "integer", + "format": "int64", + "x-go-name": "Bits" + }, + "osName": { + "description": "操作系统名称", + "type": "string", + "x-go-name": "OsName" + }, + "osType": { + "description": "操作系统平台", + "type": "string", + "x-go-name": "OsType" + }, + "osVersion": { + "description": "操作系统版本", + "type": "string", + "x-go-name": "OsVersion" + }, + "sysUser": { + "description": "系统用户", + "type": "string", + "x-go-name": "SysUser" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateProjectRequest": { + "type": "object", + "required": [ + "projectName" + ], + "properties": { + "isDefault": { + "description": "是否作为该用户的默认项目, [0/1], 默认为0", + "type": "integer", + "format": "int8", + "x-go-name": "IsDefault" + }, + "isSystem": { + "description": "是否作为系统项目, [0/1], 默认为0", + "type": "integer", + "format": "int8", + "x-go-name": "IsSystem" + }, + "projectName": { + "description": "ProjectName 1~64字符,只支持数字、大小写字母、中英文下划线“_”及中划线“-”", + "type": "string", + "x-go-name": "ProjectName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateRaidRequest": { + "type": "object", + "required": [ + "name", + "descriptionEn", + "descriptionZh" + ], + "properties": { + "descriptionEn": { + "description": "raid描述(中文)", + "type": "string", + "x-go-name": "DescriptionEn" + }, + "descriptionZh": { + "description": "raid描述(英文)", + "type": "string", + "x-go-name": "DescriptionZh" + }, + "name": { + "description": "raid名称", + "type": "string", + "x-go-name": "Name" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateRoleRequest": { + "type": "object", + "required": [ + "roleNameEn", + "roleNameCn", + "descriptionEn", + "descriptionCn" + ], + "properties": { + "descriptionCn": { + "description": "角色描述中文名称", + "type": "string", + "x-go-name": "DescriptionCn" + }, + "descriptionEn": { + "description": "角色描述英文名称", + "type": "string", + "x-go-name": "DescriptionEn" + }, + "roleNameCn": { + "description": "角色中文名称", + "type": "string", + "x-go-name": "RoleNameCn" + }, + "roleNameEn": { + "description": "角色英文名称", + "type": "string", + "x-go-name": "RoleNameEn" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateSshkeyRequest": { + "type": "object", + "required": [ + "name", + "key" + ], + "properties": { + "key": { + "description": "公钥内容,格式:^ssh-rsa AAAAB3NzaC1yc2.*", + "type": "string", + "x-go-name": "Key" + }, + "name": { + "description": "秘钥名称", + "type": "string", + "x-go-name": "Name" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "CreateUserRequest": { + "type": "object", + "required": [ + "roleId", + "userName", + "password" + ], + "properties": { + "defaultProjectId": { + "description": "用户默认项目uuid", + "type": "string", + "x-go-name": "DefaultProjectID" + }, + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description" + }, + "email": { + "description": "邮箱", + "type": "string", + "x-go-name": "Email" + }, + "language": { + "description": "语言[en_US, zh_CN]", + "type": "string", + "x-go-name": "Language" + }, + "password": { + "description": "密码 明文 密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30}", + "type": "string", + "x-go-name": "Password" + }, + "phoneNumber": { + "description": "手机号", + "type": "string", + "x-go-name": "PhoneNumber" + }, + "phonePrefix": { + "description": "国家地区码,如86", + "type": "string", + "x-go-name": "PhonePrefix" + }, + "roleId": { + "description": "角色uuid", + "type": "string", + "x-go-name": "RoleID" + }, + "timezone": { + "description": "时区,Asia/Shanghai", + "type": "string", + "x-go-name": "Timezone" + }, + "userName": { + "description": "用户名,唯一, 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-”", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "DataEveryMetric": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/MonitorDataItem" + }, + "x-go-name": "Data" + }, + "query": { + "$ref": "#/definitions/MonitorDataQuery" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeleteAlertRequest": { + "type": "object", + "required": [ + "alertId" + ], + "properties": { + "alertId": { + "description": "告警id", + "type": "string", + "x-go-name": "AlertId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "DeleteDeviceTypeRaidRequest": { + "type": "object", + "properties": { + "deviceType": { + "type": "string", + "x-go-name": "DeviceType" + }, + "raidId": { + "type": "string", + "x-go-name": "RaidId" + }, + "volumeDetail": { + "type": "string", + "x-go-name": "VolumeDetail" + }, + "volumeType": { + "type": "string", + "x-go-name": "VolumeType" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "DeleteInstancesRequest": { + "description": "批量删除实例", + "type": "object", + "properties": { + "instance_ids": { + "description": "实例id列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIDs" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "DeleteMessagesRequest": { + "type": "object", + "required": [ + "messageIds" + ], + "properties": { + "messageIds": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "MessageIds" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "DeleteRuleRequest": { + "type": "object", + "required": [ + "ruleId" + ], + "properties": { + "ruleId": { + "description": "规则id", + "type": "string", + "x-go-name": "RuleId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "Device": { + "type": "object", + "required": [ + "idcId" + ], + "properties": { + "Enclosure2": { + "description": "系统盘2背板号", + "type": "string" + }, + "adapterId": { + "description": "adapter_id", + "type": "integer", + "format": "int64", + "x-go-name": "AdapterID" + }, + "architecture": { + "description": "体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64", + "type": "string", + "x-go-name": "Architecture" + }, + "brand": { + "description": "品牌", + "type": "string", + "x-go-name": "Brand" + }, + "cabinet": { + "description": "机柜编码", + "type": "string", + "x-go-name": "Cabinet" + }, + "collectFailReason": { + "type": "string", + "x-go-name": "CollectFailReason" + }, + "collectStatus": { + "description": "\"1\"表示采集成功,\"2\"表示未采集,3表示采集中,4表示采集失败", + "type": "string", + "x-go-name": "CollectStatus" + }, + "cpuAmount": { + "description": "cpu数量", + "type": "integer", + "format": "int64", + "x-go-name": "CPUAmount" + }, + "cpuCores": { + "description": "单个cpu内核数", + "type": "integer", + "format": "int64", + "x-go-name": "CPUCores" + }, + "cpuFrequency": { + "description": "cpu频率(G)", + "type": "string", + "x-go-name": "CPUFrequency" + }, + "cpuInfo": { + "description": "拼装信息", + "type": "string", + "x-go-name": "CpuInfo" + }, + "cpuManufacturer": { + "description": "cpu厂商", + "type": "string", + "x-go-name": "CPUManufacturer" + }, + "cpuModel": { + "description": "cpu处理器型号", + "type": "string", + "x-go-name": "CPUModel" + }, + "cpuRoads": { + "description": "单个cpu路数", + "type": "integer", + "format": "int8", + "x-go-name": "CPURoads" + }, + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "dataVolumeAmount": { + "description": "数据盘数量", + "type": "integer", + "format": "int64", + "x-go-name": "DataVolumeAmount" + }, + "dataVolumeInterfaceType": { + "description": "数据盘接口类型(SATA,SAS,NVME)", + "type": "string", + "x-go-name": "DataVolumeInterfaceType" + }, + "dataVolumeSize": { + "description": "数据盘单盘大小", + "type": "integer", + "format": "int64", + "x-go-name": "DataVolumeSize" + }, + "dataVolumeType": { + "description": "数据盘类型(SSD,HDD)", + "type": "string", + "x-go-name": "DataVolumeType" + }, + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description" + }, + "deviceId": { + "description": "设备uuid", + "type": "string", + "x-go-name": "DeviceID" + }, + "deviceSeries": { + "description": "计算型,存储型", + "type": "string", + "x-go-name": "DeviceSeries" + }, + "deviceSeriesName": { + "description": "计算型,存储型", + "type": "string", + "x-go-name": "DeviceSeriesName" + }, + "deviceType": { + "description": "型号,机型规格cps.normal", + "type": "string", + "x-go-name": "DeviceType" + }, + "deviceTypeId": { + "description": "机型uuid", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "deviceTypeName": { + "description": "机型名称", + "type": "string", + "x-go-name": "DeviceTypeName" + }, + "dvInfo": { + "type": "string", + "x-go-name": "DvInfo" + }, + "enclosure1": { + "description": "添加到disk表, 系统盘1背板号", + "type": "string", + "x-go-name": "Enclosure1" + }, + "eth1Mask": { + "description": "ETH1子网掩码", + "type": "string", + "x-go-name": "Eth1Mask" + }, + "gateway": { + "description": "网关地址", + "type": "string", + "x-go-name": "Gateway" + }, + "gpuAmount": { + "description": "gpu数量", + "type": "integer", + "format": "int64", + "x-go-name": "GpuAmount" + }, + "gpuInfo": { + "type": "string", + "x-go-name": "GpuInfo" + }, + "gpuManufacturer": { + "description": "gpu厂商", + "type": "string", + "x-go-name": "GpuManufacturer" + }, + "gpuModel": { + "description": "gpu处理器型号", + "type": "string", + "x-go-name": "GpuModel" + }, + "id": { + "description": "设备ID编号", + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "idcId": { + "description": "机房uuid", + "type": "string", + "x-go-name": "IdcID" + }, + "idcName": { + "description": "机房名称", + "type": "string", + "x-go-name": "IdcName" + }, + "idcNameEn": { + "description": "idcname", + "type": "string", + "x-go-name": "IDcNameEn" + }, + "iloIp": { + "description": "带外管理IP", + "type": "string", + "x-go-name": "IloIP" + }, + "iloPassword": { + "description": "带外账号密码", + "type": "string", + "x-go-name": "IloPassword" + }, + "iloUser": { + "description": "带外账号", + "type": "string", + "x-go-name": "IloUser" + }, + "imageName": { + "description": "实例镜像名称", + "type": "string", + "x-go-name": "ImageName" + }, + "instanceCreatedTime": { + "description": "实例创建时间", + "type": "string", + "x-go-name": "InstanceCreatedTime" + }, + "instanceDescription": { + "description": "实例描述", + "type": "string", + "x-go-name": "InstanceDescription" + }, + "instanceId": { + "description": "实例id", + "type": "string", + "x-go-name": "InstanceID" + }, + "instanceName": { + "description": "实例名称", + "type": "string", + "x-go-name": "InstanceName" + }, + "instanceReason": { + "description": "实例失败原因", + "type": "string", + "x-go-name": "InstanceReason" + }, + "instanceStatus": { + "description": "实例状态", + "type": "string", + "x-go-name": "InstanceStatus" + }, + "instanceStatusName": { + "description": "实例状态", + "type": "string", + "x-go-name": "InstanceStatusName" + }, + "interfaceMode": { + "description": "【网口模式】【网络设置】: bond单网口,dual双网口", + "type": "string", + "x-go-name": "InterfaceMode" + }, + "isNeedRaid": { + "type": "string", + "x-go-name": "IsNeedRaid" + }, + "locked": { + "description": "实例是否锁定 锁定locked 未锁定unlocked", + "type": "string", + "x-go-name": "Locked" + }, + "mac1": { + "description": "MAC1(eth0)", + "type": "string", + "x-go-name": "Mac1" + }, + "mac2": { + "description": "MAC2(eth2)", + "type": "string", + "x-go-name": "Mac2" + }, + "manageStatus": { + "description": "设备状态: 未装机,已装机", + "type": "string", + "x-go-name": "ManageStatus" + }, + "manageStatusName": { + "description": "设备状态: 未装机,已装机", + "type": "string", + "x-go-name": "ManageStatusName" + }, + "mask": { + "description": "子网掩码", + "type": "string", + "x-go-name": "Mask" + }, + "memAmount": { + "description": "内存数量", + "type": "integer", + "format": "int64", + "x-go-name": "MemAmount" + }, + "memFrequency": { + "description": "内存主频(MHz)", + "type": "integer", + "format": "int64", + "x-go-name": "MemFrequency" + }, + "memInfo": { + "type": "string", + "x-go-name": "MemInfo" + }, + "memSize": { + "description": "单个内存大小(GB)", + "type": "integer", + "format": "int64", + "x-go-name": "MemSize" + }, + "memType": { + "description": "内存接口(如DDR3,DDR4)", + "type": "string", + "x-go-name": "MemType" + }, + "model": { + "description": "型号", + "type": "string", + "x-go-name": "Model" + }, + "nicAmount": { + "description": "网卡数量", + "type": "integer", + "format": "int64", + "x-go-name": "NicAmount" + }, + "nicInfo": { + "type": "string", + "x-go-name": "NicInfo" + }, + "nicRate": { + "description": "网卡传输速率(GE)", + "type": "integer", + "format": "int64", + "x-go-name": "NicRate" + }, + "privateEth1Ipv4": { + "description": "eth1内网IPV4", + "type": "string", + "x-go-name": "PrivateEth1IPv4" + }, + "privateEth1Ipv6": { + "description": "eth1内网IPV6", + "type": "string", + "x-go-name": "PrivateEth1IPv6" + }, + "privateIpv4": { + "description": "内网IPV4", + "type": "string", + "x-go-name": "PrivateIPv4" + }, + "privateIpv6": { + "description": "内网IPV6", + "type": "string", + "x-go-name": "PrivateIPv6" + }, + "raidDriver": { + "description": "raid工具:(megacli64等)", + "type": "string", + "x-go-name": "RaidDriver" + }, + "reason": { + "description": "设备状态变更失败原因", + "type": "string", + "x-go-name": "Reason" + }, + "slot1": { + "description": "系统盘1槽位", + "type": "integer", + "format": "int64", + "x-go-name": "Slot1" + }, + "slot2": { + "description": "系统盘2槽位", + "type": "integer", + "format": "int64", + "x-go-name": "Slot2" + }, + "sn": { + "description": "设备SN", + "type": "string", + "x-go-name": "Sn" + }, + "svInfo": { + "type": "string", + "x-go-name": "SvInfo" + }, + "switchIp": { + "description": "网口交换机IP", + "type": "string", + "x-go-name": "SwitchIP" + }, + "switchIp1": { + "description": "交换机1ip", + "type": "string", + "x-go-name": "SwitchIP1" + }, + "switchIp2": { + "description": "交换机2ip", + "type": "string", + "x-go-name": "SwitchIP2" + }, + "switchPassword1": { + "description": "交换机1登录密码", + "type": "string", + "x-go-name": "SwitchPassword1" + }, + "switchPassword2": { + "description": "交换机2登录密码", + "type": "string", + "x-go-name": "SwitchPassword2" + }, + "switchPort1": { + "description": "交换机1port", + "type": "string", + "x-go-name": "SwitchPort1" + }, + "switchPort2": { + "description": "交换机2port", + "type": "string", + "x-go-name": "SwitchPort2" + }, + "switchUser1": { + "description": "交换机1登录账号,如果为空,取所在机房的值", + "type": "string", + "x-go-name": "SwitchUser1" + }, + "switchUser2": { + "description": "交换机2登录账号,如果为空,取所在机房的值", + "type": "string", + "x-go-name": "SwitchUser2" + }, + "systemVolumeAmount": { + "description": "系统盘数量", + "type": "integer", + "format": "int64", + "x-go-name": "SystemVolumeAmount" + }, + "systemVolumeInterfaceType": { + "description": "系统盘接口类型(SATA,SAS,NVME)", + "type": "string", + "x-go-name": "SystemVolumeInterfaceType" + }, + "systemVolumeSize": { + "description": "系统盘单盘大小", + "type": "integer", + "format": "int64", + "x-go-name": "SystemVolumeSize" + }, + "systemVolumeType": { + "description": "系统盘类型(SSD,HDD)", + "type": "string", + "x-go-name": "SystemVolumeType" + }, + "uPosition": { + "description": "U位", + "type": "string", + "x-go-name": "UPosition" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "userId": { + "description": "实例归属用户uuid", + "type": "string", + "x-go-name": "UserId" + }, + "userName": { + "description": "实例归属用户名称", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeviceAssociateDeviceTypeRequest": { + "type": "object", + "required": [ + "deviceTypeId", + "deviceId" + ], + "properties": { + "deviceId": { + "description": "设备ID", + "type": "string", + "x-go-name": "DeviceID" + }, + "deviceTypeId": { + "description": "设备类型id", + "type": "string", + "x-go-name": "DeviceTypeID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "DeviceDisks": { + "type": "object", + "properties": { + "disks": { + "type": "array", + "items": { + "$ref": "#/definitions/Disk" + }, + "x-go-name": "Disks" + }, + "panfu": { + "type": "array", + "items": { + "$ref": "#/definitions/Disk" + }, + "x-go-name": "Panfu" + }, + "volumes": { + "type": "array", + "items": { + "$ref": "#/definitions/VolumeIt" + }, + "x-go-name": "Volumes" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeviceInfo": { + "type": "object", + "properties": { + "device": { + "$ref": "#/definitions/Device" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeviceList": { + "type": "object", + "properties": { + "devices": { + "description": "设备列表", + "type": "array", + "items": { + "$ref": "#/definitions/Device" + }, + "x-go-name": "Devices" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeviceStock": { + "type": "object", + "properties": { + "stocks": { + "description": "库存量", + "type": "integer", + "format": "int64", + "x-go-name": "Stocks" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeviceType": { + "type": "object", + "properties": { + "architecture": { + "description": "体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64", + "type": "string", + "x-go-name": "Architecture" + }, + "boot_mode": { + "description": "boot模式", + "type": "string", + "x-go-name": "BootMode" + }, + "cpuAmount": { + "description": "cpu数量", + "type": "integer", + "format": "int64", + "x-go-name": "CPUAmount" + }, + "cpuCores": { + "description": "单个cpu内核数", + "type": "integer", + "format": "int64", + "x-go-name": "CPUCores" + }, + "cpuFrequency": { + "description": "cpu频率(G)", + "type": "string", + "x-go-name": "CPUFrequency" + }, + "cpuInfo": { + "description": "拼装信息", + "type": "string", + "x-go-name": "CpuInfo" + }, + "cpuManufacturer": { + "description": "cpu厂商", + "type": "string", + "x-go-name": "CPUManufacturer" + }, + "cpuModel": { + "description": "cpu处理器型号", + "type": "string", + "x-go-name": "CPUModel" + }, + "cpuSpec": { + "description": "CPU 规格,预置还是其它", + "type": "string", + "x-go-name": "CpuSpec" + }, + "createdBy": { + "description": "数据盘类型(SSD,HDD)\nDataVolumeType string `json:\"dataVolumeType\"`\n数据盘接口类型(SATA,SAS,NVME)\nDataVolumeInterfaceType string `json:\"dataVolumeInterfaceType\"`\n数据盘单盘大小\nDataVolumeSize int `json:\"dataVolumeSize\"`\n数据盘单位(GB,TB)\nDataVolumeUnit string `json:\"dataVolumeUnit\"`\n数据盘数量\nDataVolumeAmount int `json:\"dataVolumeAmount\"`\n创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description" + }, + "deviceCount": { + "type": "integer", + "format": "int64", + "x-go-name": "DeviceCount" + }, + "deviceSeries": { + "description": "机型类型,如计算型,存储型", + "type": "string", + "x-go-name": "DeviceSeries" + }, + "deviceSeriesName": { + "description": "机型类型,如计算型,存储型", + "type": "string", + "x-go-name": "DeviceSeriesName" + }, + "deviceType": { + "description": "机型规格, cps.c.normal", + "type": "string", + "x-go-name": "DeviceType" + }, + "deviceTypeId": { + "description": "机型uuid", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "dvInfo": { + "type": "string", + "x-go-name": "DvInfo" + }, + "gpuAmount": { + "description": "gpu数量", + "type": "integer", + "format": "int64", + "x-go-name": "GpuAmount" + }, + "gpuInfo": { + "type": "string", + "x-go-name": "GpuInfo" + }, + "gpuManufacturer": { + "description": "gpu厂商", + "type": "string", + "x-go-name": "GpuManufacturer" + }, + "gpuModel": { + "description": "gpu处理器型号", + "type": "string", + "x-go-name": "GpuModel" + }, + "height": { + "description": "显示机型高度", + "type": "integer", + "format": "int64", + "x-go-name": "Height" + }, + "id": { + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "idcId": { + "description": "机房uuid", + "type": "string", + "x-go-name": "IDcID" + }, + "idcName": { + "description": "机房名称", + "type": "string", + "x-go-name": "IDcName" + }, + "idcNameEn": { + "description": "机房名称", + "type": "string", + "x-go-name": "IDcNameEn" + }, + "instanceCount": { + "type": "integer", + "format": "int64", + "x-go-name": "InstanceCount" + }, + "instanceStatus": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceStatus" + }, + "interfaceMode": { + "description": "bond单网口,dual双网口", + "type": "string", + "x-go-name": "InterfaceMode" + }, + "isNeedRaid": { + "description": "阵列卡是否需要配置", + "type": "string", + "x-go-name": "IsNeedRaid" + }, + "memAmount": { + "description": "内存数量", + "type": "integer", + "format": "int64", + "x-go-name": "MemAmount" + }, + "memFrequency": { + "description": "内存主频(MHz)", + "type": "integer", + "format": "int64", + "x-go-name": "MemFrequency" + }, + "memInfo": { + "type": "string", + "x-go-name": "MemInfo" + }, + "memSize": { + "description": "单个内存大小(GB)", + "type": "integer", + "format": "int64", + "x-go-name": "MemSize" + }, + "memSpec": { + "description": "内存 规格,预置还是其它", + "type": "string", + "x-go-name": "MemSpec" + }, + "memType": { + "description": "内存接口(如DDR3,DDR4)", + "type": "string", + "x-go-name": "MemType" + }, + "name": { + "description": "机型名称,如计算效能型,标准计算型", + "type": "string", + "x-go-name": "Name" + }, + "nicAmount": { + "description": "网卡数量", + "type": "integer", + "format": "int64", + "x-go-name": "NicAmount" + }, + "nicInfo": { + "type": "string", + "x-go-name": "NicInfo" + }, + "nicRate": { + "description": "网卡传输速率(GE)", + "type": "integer", + "format": "int64", + "x-go-name": "NicRate" + }, + "raid": { + "description": "系统盘raid", + "type": "string", + "x-go-name": "Raid" + }, + "raidCan": { + "description": "系统盘类型(SSD,HDD)\nSystemVolumeType string `json:\"systemVolumeType\"`\n系统盘接口类型(SATA,SAS,NVME)\nSystemVolumeInterfaceType string `json:\"systemVolumeInterfaceType\"`\n系统盘单盘大小\nSystemVolumeSize int `json:\"systemVolumeSize\"`\n系统盘单位(GB,TB)\nSystemVolumeUnit string `json:\"systemVolumeUnit\"`\n系统盘数量\nSystemVolumeAmount int `json:\"systemVolumeAmount\"`*/\n是否做raid,[RAID/NORAID]", + "type": "string", + "x-go-name": "RaidCan" + }, + "stockAvailable": { + "description": "StockAvailable 可用库存", + "type": "integer", + "format": "int64", + "x-go-name": "StockAvailable" + }, + "svInfo": { + "type": "string", + "x-go-name": "SvInfo" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "volumes": { + "type": "array", + "items": { + "$ref": "#/definitions/Volume" + }, + "x-go-name": "Volumes" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeviceTypeId": { + "type": "object", + "required": [ + "deviceTypeId" + ], + "properties": { + "deviceTypeId": { + "description": "机型uuid", + "type": "string", + "x-go-name": "DeviceTypeId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeviceTypeInfo": { + "type": "object", + "properties": { + "deviceType": { + "$ref": "#/definitions/DeviceType" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DeviceTypeList": { + "type": "object", + "properties": { + "deviceTypes": { + "description": "机型列表", + "type": "array", + "items": { + "$ref": "#/definitions/DeviceType" + }, + "x-go-name": "DeviceTypes" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DisableRuleRequest": { + "type": "object", + "required": [ + "ruleId" + ], + "properties": { + "ruleId": { + "description": "规则id", + "type": "string", + "x-go-name": "RuleId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "Disk": { + "type": "object", + "properties": { + "adapterId": { + "type": "integer", + "format": "int64", + "x-go-name": "AdapterID" + }, + "createdBy": { + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "type": "integer", + "format": "int64", + "x-go-name": "CreatedTime" + }, + "deletedTime": { + "type": "integer", + "format": "int64", + "x-go-name": "DeletedTime" + }, + "deviceId": { + "type": "string", + "x-go-name": "DeviceID" + }, + "devicePath": { + "type": "string", + "x-go-name": "DevicePath" + }, + "diskId": { + "type": "string", + "x-go-name": "DiskId" + }, + "diskType": { + "description": "磁盘类型:system,data", + "type": "string", + "x-go-name": "DiskType" + }, + "enclosure": { + "type": "string", + "x-go-name": "Enclosure" + }, + "index": { + "type": "integer", + "format": "int64", + "x-go-name": "Index" + }, + "isDel": { + "type": "integer", + "format": "int8", + "x-go-name": "IsDel" + }, + "mediaType": { + "type": "string", + "x-go-name": "MediaType" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "pdType": { + "type": "string", + "x-go-name": "PdType" + }, + "selected": { + "description": "是否选中", + "type": "boolean", + "x-go-name": "Selected" + }, + "serialNumber": { + "type": "string", + "x-go-name": "SerialNumber" + }, + "size": { + "type": "string", + "x-go-name": "Size" + }, + "sizeUnit": { + "type": "string", + "x-go-name": "SizeUnit" + }, + "slot": { + "type": "integer", + "format": "int64", + "x-go-name": "Slot" + }, + "types": { + "description": "control/mvme/panfu", + "type": "string", + "x-go-name": "Types" + }, + "updatedBy": { + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "type": "integer", + "format": "int64", + "x-go-name": "UpdatedTime" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "DissociatedImageRequest": { + "type": "object", + "required": [ + "deviceTypeId", + "imageId" + ], + "properties": { + "deviceTypeId": { + "description": "设备类型id", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "imageId": { + "description": "镜像ID", + "type": "string", + "x-go-name": "ImageID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "EditRuleRequest": { + "type": "object", + "required": [ + "ruleId", + "ruleName", + "dimension", + "resource", + "triggerOption", + "noticeOption", + "instanceIds" + ], + "properties": { + "deviceTag": { + "description": "盘符、挂载点、网口列表", + "type": "string", + "x-go-name": "DeviceTag" + }, + "dimension": { + "description": "维度 [instance、disk、mountpoint、nic]", + "type": "string", + "x-go-name": "Dimension" + }, + "instanceIds": { + "description": "实例id列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + }, + "noticeOption": { + "$ref": "#/definitions/RuleNotice" + }, + "resource": { + "description": "资源类型,目前只支持instance", + "type": "string", + "x-go-name": "Resource" + }, + "ruleId": { + "description": "规则id", + "type": "string", + "x-go-name": "RuleId" + }, + "ruleName": { + "description": "规则名称", + "type": "string", + "x-go-name": "RuleName" + }, + "triggerOption": { + "description": "触发条件", + "type": "array", + "items": { + "$ref": "#/definitions/RuleTrigger" + }, + "x-go-name": "TriggerOption" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "EnableRuleRequest": { + "type": "object", + "required": [ + "ruleId" + ], + "properties": { + "ruleId": { + "description": "规则id", + "type": "string", + "x-go-name": "RuleId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ErrorResponse": { + "type": "object", + "properties": { + "code": { + "description": "错误码", + "type": "integer", + "format": "int64", + "x-go-name": "Code" + }, + "message": { + "description": "错误信息", + "type": "string", + "x-go-name": "Message" + }, + "status": { + "description": "错误状态", + "type": "string", + "x-go-name": "Status" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/controllers" + }, + "HasUnreadMessage": { + "type": "object", + "properties": { + "hasUnread": { + "type": "boolean", + "x-go-name": "HasUnread" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Idc": { + "type": "object", + "properties": { + "address": { + "description": "机房地址", + "type": "string", + "x-go-name": "Address" + }, + "createTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreateTime" + }, + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "id": { + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "idcId": { + "description": "机房uuid", + "type": "string", + "x-go-name": "IDcID" + }, + "iloPassword": { + "description": "机房公用带外管理password", + "type": "string", + "x-go-name": "IloPassword" + }, + "iloUser": { + "description": "机房公用带外管理user", + "type": "string", + "x-go-name": "IloUser" + }, + "level": { + "description": "机房等级", + "type": "string", + "x-go-name": "Level" + }, + "name": { + "description": "机房名称", + "type": "string", + "x-go-name": "Name" + }, + "nameEn": { + "description": "机房名称en", + "type": "string", + "x-go-name": "NameEn" + }, + "shortname": { + "description": "shortname", + "type": "string", + "x-go-name": "Shortname" + }, + "switchPassword1": { + "description": "交换机密码1", + "type": "string", + "x-go-name": "SwitchPassword1" + }, + "switchPassword2": { + "description": "交换机密码2", + "type": "string", + "x-go-name": "SwitchPassword2" + }, + "switchUser1": { + "description": "交换机用户名1", + "type": "string", + "x-go-name": "SwitchUser1" + }, + "switchUser2": { + "description": "交换机用户名2", + "type": "string", + "x-go-name": "SwitchUser2" + }, + "updateTime": { + "description": "修改时间", + "type": "string", + "x-go-name": "UpdateTime" + }, + "updatedBy": { + "description": "修改用户", + "type": "string", + "x-go-name": "UpdatedBy" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "IdcID": { + "type": "object", + "properties": { + "idcId": { + "description": "机房id", + "type": "string", + "x-go-name": "IdcID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "IdcInfo": { + "type": "object", + "properties": { + "idc": { + "$ref": "#/definitions/Idc" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "IdcList": { + "type": "object", + "properties": { + "idcs": { + "description": "机房列表", + "type": "array", + "items": { + "$ref": "#/definitions/Idc" + }, + "x-go-name": "Idcs" + }, + "pageNumber": { + "description": "页数", + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "description": "页大小", + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "description": "总条数", + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Image": { + "type": "object", + "properties": { + "architecture": { + "description": "架构:x86/x64/i386/", + "type": "string", + "x-go-name": "Architecture" + }, + "bootMode": { + "description": "boot模式", + "type": "string", + "x-go-name": "BootMode" + }, + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "dataPartition": { + "description": "数据分区信息", + "type": "string", + "x-go-name": "DataPartition" + }, + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description" + }, + "deviceTypeNum": { + "description": "绑定了机型数量", + "type": "integer", + "format": "int64", + "x-go-name": "DeviceTypeNum" + }, + "filename": { + "description": "镜像文件名称", + "type": "string", + "x-go-name": "Filename" + }, + "format": { + "description": "镜像格式(qcow2、tar)", + "type": "string", + "x-go-name": "Format" + }, + "hash": { + "description": "镜像校验码", + "type": "string", + "x-go-name": "Hash" + }, + "id": { + "type": "integer", + "format": "uint64", + "x-go-name": "ID" + }, + "imageId": { + "description": "镜像uuid", + "type": "string", + "x-go-name": "ImageID" + }, + "imageName": { + "description": "镜像名称", + "type": "string", + "x-go-name": "ImageName" + }, + "isBind": { + "description": "是否绑定了某个机型", + "type": "boolean", + "x-go-name": "IsBind" + }, + "osId": { + "description": "源os uuid", + "type": "string", + "x-go-name": "OsID" + }, + "osName": { + "description": "CentOS 7.2 64-bit", + "type": "string", + "x-go-name": "OsName" + }, + "osType": { + "description": "操作系统分类:linux/windows", + "type": "string", + "x-go-name": "OsType" + }, + "osVersion": { + "description": "操作系统版本", + "type": "string", + "x-go-name": "OsVersion" + }, + "source": { + "description": "镜像来源(common通用、customize定制、user_defined自定义)", + "type": "string", + "x-go-name": "Source" + }, + "sourceName": { + "description": "镜像来源(common通用、customize定制、user_defined自定义)", + "type": "string", + "x-go-name": "SourceName" + }, + "systemPartition": { + "description": "系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap)", + "type": "string", + "x-go-name": "SystemPartition" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "url": { + "description": "镜像源路径", + "type": "string", + "x-go-name": "URL" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ImageId": { + "type": "object", + "properties": { + "imageId": { + "description": "镜像uuid", + "type": "string", + "x-go-name": "ImageId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ImageInfo": { + "type": "object", + "properties": { + "image": { + "$ref": "#/definitions/Image" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ImageList": { + "type": "object", + "properties": { + "images": { + "description": "镜像实体列表", + "type": "array", + "items": { + "$ref": "#/definitions/Image" + }, + "x-go-name": "Images" + }, + "pageNumber": { + "description": "页数", + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "description": "页大小", + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "description": "总条数", + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Instance": { + "type": "object", + "properties": { + "DataVolumeRaidName": { + "description": "数据盘raid名称", + "type": "string" + }, + "cpuAmount": { + "description": "cpu数量", + "type": "integer", + "format": "int64", + "x-go-name": "CPUAmount" + }, + "cpuCores": { + "description": "单个cpu内核数", + "type": "integer", + "format": "int64", + "x-go-name": "CPUCores" + }, + "cpuFrequency": { + "description": "cpu频率(GHz)", + "type": "string", + "x-go-name": "CPUFrequency" + }, + "cpuManufacturer": { + "description": "cpu厂商", + "type": "string", + "x-go-name": "CPUManufacturer" + }, + "cpuModel": { + "description": "cpu处理器型号", + "type": "string", + "x-go-name": "CPUModel" + }, + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "dataVolumeAmount": { + "description": "数据盘数量", + "type": "integer", + "format": "int64", + "x-go-name": "DataVolumeAmount" + }, + "dataVolumeInterfaceType": { + "description": "数据盘接口类型(SATA,SAS,NVME)", + "type": "string", + "x-go-name": "DataVolumeInterfaceType" + }, + "dataVolumeRaidId": { + "description": "数据盘raidId", + "type": "string", + "x-go-name": "DataVolumeRaidID" + }, + "dataVolumeSize": { + "description": "数据盘单盘大小", + "type": "integer", + "format": "int64", + "x-go-name": "DataVolumeSize" + }, + "dataVolumeType": { + "description": "数据盘类型(SSD,HDD)", + "type": "string", + "x-go-name": "DataVolumeType" + }, + "dataVolumeUnit": { + "description": "系统盘单位", + "type": "string", + "x-go-name": "DataVolumeUnit" + }, + "description": { + "description": "实例描述", + "type": "string", + "x-go-name": "Description" + }, + "deviceId": { + "description": "设备uuid", + "type": "string", + "x-go-name": "DeviceID" + }, + "deviceSeries": { + "description": "机型类型,如computer", + "type": "string", + "x-go-name": "DeviceSeries" + }, + "deviceSeriesName": { + "description": "机型类型,如计算型,存储型", + "type": "string", + "x-go-name": "DeviceSeriesName" + }, + "deviceType": { + "description": "机型规格, cps.c.normal", + "type": "string", + "x-go-name": "DeviceType" + }, + "deviceTypeId": { + "description": "机型uuid", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "deviceTypeName": { + "description": "机型名称,如计算效能型,标准计算型", + "type": "string", + "x-go-name": "DeviceTypeName" + }, + "gpuAmount": { + "description": "gpu数量", + "type": "integer", + "format": "int64", + "x-go-name": "GpuAmount" + }, + "gpuManufacturer": { + "description": "gpu厂商", + "type": "string", + "x-go-name": "GpuManufacturer" + }, + "gpuModel": { + "description": "gpu处理器型号", + "type": "string", + "x-go-name": "GpuModel" + }, + "hostname": { + "description": "主机名", + "type": "string", + "x-go-name": "Hostname" + }, + "idcId": { + "description": "机房uuid", + "type": "string", + "x-go-name": "IDcID" + }, + "idcName": { + "description": "机房名称", + "type": "string", + "x-go-name": "IdcName" + }, + "iloIp": { + "description": "带外管理IP", + "type": "string", + "x-go-name": "IloIP" + }, + "imageId": { + "description": "镜像uuid", + "type": "string", + "x-go-name": "ImageID" + }, + "imageName": { + "description": "镜像名称", + "type": "string", + "x-go-name": "ImageName" + }, + "instanceId": { + "description": "实例uuid", + "type": "string", + "x-go-name": "InstanceID" + }, + "instanceName": { + "description": "实例名称", + "type": "string", + "x-go-name": "InstanceName" + }, + "interfaceMode": { + "description": "【网口模式】【网络设置】: bond单网口,dual双网口", + "type": "string", + "x-go-name": "InterfaceMode" + }, + "locked": { + "description": "是否锁定解锁锁定:locked,解锁unlocked", + "type": "string", + "x-go-name": "Locked" + }, + "lockedName": { + "description": "是否锁定解锁锁定:已解锁,已锁定", + "type": "string", + "x-go-name": "LockedName" + }, + "memAmount": { + "description": "内存数量", + "type": "integer", + "format": "int64", + "x-go-name": "MemAmount" + }, + "memFrequency": { + "description": "内存主频(MHz)", + "type": "integer", + "format": "int64", + "x-go-name": "MemFrequency" + }, + "memSize": { + "description": "单个内存大小(GB)", + "type": "integer", + "format": "int64", + "x-go-name": "MemSize" + }, + "memType": { + "description": "内存接口(如DDR3,DDR4)", + "type": "string", + "x-go-name": "MemType" + }, + "nicAmount": { + "description": "网卡数量", + "type": "integer", + "format": "int64", + "x-go-name": "NicAmount" + }, + "nicRate": { + "description": "网卡传输速率(GE)", + "type": "integer", + "format": "int64", + "x-go-name": "NicRate" + }, + "privateIpv4": { + "description": "内网IPV4", + "type": "string", + "x-go-name": "PrivateIPv4" + }, + "privateIpv6": { + "description": "内网IPV6", + "type": "string", + "x-go-name": "PrivateIPv6" + }, + "projectId": { + "description": "实例所属项目UUID", + "type": "string", + "x-go-name": "ProjectID" + }, + "raidCan": { + "description": "系统盘raid配置", + "type": "string", + "x-go-name": "RaidCan" + }, + "reason": { + "description": "实例错误状态时的错误原因", + "type": "string", + "x-go-name": "Reason" + }, + "sn": { + "description": "设备SN", + "type": "string", + "x-go-name": "Sn" + }, + "status": { + "description": "运行状态", + "type": "string", + "x-go-name": "Status" + }, + "statusName": { + "description": "运行状态中文名字", + "type": "string", + "x-go-name": "StatusName" + }, + "systemVolumeAmount": { + "description": "系统盘数量", + "type": "integer", + "format": "int64", + "x-go-name": "SystemVolumeAmount" + }, + "systemVolumeInterfaceType": { + "description": "系统盘接口类型(SATA,SAS,NVME)", + "type": "string", + "x-go-name": "SystemVolumeInterfaceType" + }, + "systemVolumeRaidId": { + "description": "系统盘raidId", + "type": "string", + "x-go-name": "SystemVolumeRaidID" + }, + "systemVolumeRaidName": { + "description": "系统盘raid名称", + "type": "string", + "x-go-name": "SystemVolumeRaidName" + }, + "systemVolumeSize": { + "description": "系统盘单盘大小", + "type": "integer", + "format": "int64", + "x-go-name": "SystemVolumeSize" + }, + "systemVolumeType": { + "description": "系统盘类型(SSD,HDD)", + "type": "string", + "x-go-name": "SystemVolumeType" + }, + "systemVolumeUnit": { + "description": "系统盘单位", + "type": "string", + "x-go-name": "SystemVolumeUnit" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "userId": { + "description": "实例所属用户UUID", + "type": "string", + "x-go-name": "UserID" + }, + "volumeRaid": { + "description": "实例的volume和raid信息", + "type": "array", + "items": { + "$ref": "#/definitions/InstanceVolumeRaid" + }, + "x-go-name": "InstanceVolumeRaids" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "InstanceIds": { + "type": "object", + "properties": { + "instanceIds": { + "description": "instanceId 列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "InstanceInfo": { + "type": "object", + "properties": { + "instance": { + "$ref": "#/definitions/Instance" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "InstanceList": { + "type": "object", + "properties": { + "instances": { + "description": "instance实体数组", + "type": "array", + "items": { + "$ref": "#/definitions/Instance" + }, + "x-go-name": "Instances" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "InstanceVolumeRaid": { + "type": "object", + "properties": { + "raid": { + "$ref": "#/definitions/Raid" + }, + "volume": { + "$ref": "#/definitions/Volume" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "InstancesSshkeyInfoResponse": { + "type": "object", + "properties": { + "instanceIds": { + "description": "实例Id列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "LicenseContent": { + "type": "object", + "properties": { + "end_time": { + "type": "integer", + "format": "int64", + "x-go-name": "EndTime" + }, + "hardwareinfo": { + "type": "string", + "x-go-name": "HardWare" + }, + "license_name": { + "type": "string", + "x-go-name": "LicenseName" + }, + "license_type": { + "type": "string", + "x-go-name": "LicenseType" + }, + "modelList": { + "type": "array", + "items": { + "$ref": "#/definitions/ModuleItem" + }, + "x-go-name": "ModelList" + }, + "models": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "Models" + }, + "nodes_num": { + "type": "integer", + "format": "int64", + "x-go-name": "NodesNum" + }, + "start_time": { + "type": "integer", + "format": "int64", + "x-go-name": "StartTime" + }, + "used_nodes_num": { + "type": "integer", + "format": "int64", + "x-go-name": "UsedNodesNum" + }, + "version": { + "type": "string", + "x-go-name": "Version" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "LicenseToken": { + "type": "object", + "properties": { + "msg": { + "type": "string", + "x-go-name": "Msg" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Mail": { + "type": "object", + "properties": { + "admin_addr": { + "description": "管理员邮箱", + "type": "string", + "x-go-name": "AdminAddr" + }, + "admin_pass": { + "description": "管理员邮箱密码", + "type": "string", + "x-go-name": "AdminPass" + }, + "is_pass": { + "description": "邮件功能是否验证过正常。1表示正常,其他表示异常", + "type": "string", + "x-go-name": "IsPass" + }, + "is_push": { + "description": "是否推送邮件告警,0不推送,1推送", + "type": "string", + "x-go-name": "IsPush" + }, + "server_addr": { + "description": "邮件服务器地址", + "type": "string", + "x-go-name": "ServerAddr" + }, + "server_port": { + "description": "邮件服务器端口", + "type": "string", + "x-go-name": "ServerPort" + }, + "to": { + "description": "收件人邮箱", + "type": "string", + "x-go-name": "To" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "MailDialRequest": { + "type": "object", + "required": [ + "server_addr", + "server_port", + "admin_addr", + "admin_pass" + ], + "properties": { + "admin_addr": { + "description": "管理员邮箱", + "type": "string", + "x-go-name": "AdminAddr" + }, + "admin_pass": { + "description": "管理员邮箱密码", + "type": "string", + "x-go-name": "AdminPass" + }, + "server_addr": { + "description": "邮件服务器地址", + "type": "string", + "x-go-name": "ServerAddr" + }, + "server_port": { + "description": "邮件服务器端口", + "type": "string", + "x-go-name": "ServerPort" + }, + "to": { + "description": "收件人邮箱地址", + "type": "string", + "x-go-name": "To" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "Message": { + "type": "object", + "properties": { + "alert_count": { + "description": "告警次数,始终为1,带外故障消息专属字段", + "type": "integer", + "format": "int64", + "x-go-name": "AlertCount" + }, + "alert_time": { + "description": "故障告警时间,带外故障消息专属字段", + "type": "integer", + "format": "int64", + "x-go-name": "AlertTime" + }, + "content": { + "description": "故障内容,带外故障消息专属字段", + "type": "string", + "x-go-name": "Content" + }, + "detail": { + "description": "详情, 带外监控日志的详情请用content", + "type": "string", + "x-go-name": "Detail" + }, + "device_id": { + "type": "string", + "x-go-name": "DeviceID" + }, + "fault_type": { + "description": "故障类型, 带外故障消息专属字段", + "type": "string", + "x-go-name": "FaultType" + }, + "finish_time": { + "description": "消息时间戳", + "type": "integer", + "format": "int64", + "x-go-name": "FinishTime" + }, + "has_read": { + "description": "0未读, 1已读", + "type": "integer", + "format": "int8", + "x-go-name": "HasRead" + }, + "idc_id": { + "description": "独一处的下划线,跟sdk一致", + "type": "string", + "x-go-name": "IDcID" + }, + "idc_name": { + "type": "string", + "x-go-name": "IDcName" + }, + "instance_id": { + "description": "实例id", + "type": "string", + "x-go-name": "InstanceID" + }, + "instance_name": { + "description": "实例name", + "type": "string", + "x-go-name": "InstanceName" + }, + "is_del": { + "description": "是否删除0未删除 1已删除", + "type": "integer", + "format": "int8", + "x-go-name": "IsDel" + }, + "license_end_time": { + "description": "结束时间, 许可证到期消息专属字段", + "type": "integer", + "format": "int64", + "x-go-name": "LienseEndTime" + }, + "license_name": { + "description": "版本名称, 许可证到期消息专属字段", + "type": "string", + "x-go-name": "LicenseName" + }, + "license_number": { + "description": "版本号, 许可证到期消息专属字段", + "type": "string", + "x-go-name": "LicenseNumber" + }, + "license_start_time": { + "description": "开始时间, 许可证到期消息专属字段", + "type": "integer", + "format": "int64", + "x-go-name": "LienseStartTime" + }, + "logid": { + "description": "系统原始日志id, 带外故障消息专属字段", + "type": "string", + "x-go-name": "LogID" + }, + "message_id": { + "description": "message uuid", + "type": "string", + "x-go-name": "MessageID" + }, + "message_sub_type": { + "description": "消息子类型", + "type": "string", + "x-go-name": "MessageSubType" + }, + "message_type": { + "description": "消息类型", + "type": "string", + "x-go-name": "MessageType" + }, + "project_id": { + "type": "string", + "x-go-name": "ProjectID" + }, + "project_name": { + "type": "string", + "x-go-name": "ProjectName" + }, + "resource_type": { + "description": "资源类型 实例/设备", + "type": "string", + "x-go-name": "ResourceType" + }, + "result": { + "description": "操作结果 fail/succ", + "type": "string", + "x-go-name": "Result" + }, + "rule_id": { + "description": "inbond rule uuid", + "type": "string", + "x-go-name": "RuleID" + }, + "rule_name": { + "description": "inbond rule name", + "type": "string", + "x-go-name": "RuleName" + }, + "sn": { + "description": "设备sn", + "type": "string", + "x-go-name": "SN" + }, + "user_id": { + "description": "user_id", + "type": "string", + "x-go-name": "UserID" + }, + "user_name": { + "description": "user_name", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "MessageList": { + "type": "object", + "properties": { + "messages": { + "type": "array", + "items": { + "$ref": "#/definitions/Message" + }, + "x-go-name": "Messages" + }, + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "MessageStatistic": { + "type": "object", + "properties": { + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + }, + "unreadCount": { + "type": "integer", + "format": "int64", + "x-go-name": "UnreadCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "MessageTypesResp": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "MessageWithNextPrev": { + "type": "object", + "properties": { + "message": { + "$ref": "#/definitions/Message" + }, + "nextMessageId": { + "type": "string", + "x-go-name": "NextMessageId" + }, + "prevMessageId": { + "type": "string", + "x-go-name": "PrevMessageId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ModifyApikeyRequest": { + "type": "object", + "required": [ + "name", + "readOnly" + ], + "properties": { + "name": { + "description": "秘钥对名称", + "type": "string", + "x-go-name": "Name" + }, + "readOnly": { + "description": "是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法", + "type": "integer", + "format": "int8", + "x-go-name": "ReadOnly" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyDeviceTypeRequest": { + "type": "object", + "properties": { + "architecture": { + "description": "体系架构,如i386/x86_64/ ARM64(aarch64),默认 x86_64", + "type": "string", + "x-go-name": "Architecture", + "x-nullable": true + }, + "boot_mode": { + "description": "boot模式【UEFI Legacy/BIOS】支持多选,逗号分隔", + "type": "string", + "x-go-name": "BootMode" + }, + "cpuAmount": { + "description": "cpu数量", + "type": "integer", + "format": "int64", + "x-go-name": "CPUAmount", + "x-nullable": true + }, + "cpuCores": { + "description": "单个cpu内核数", + "type": "integer", + "format": "int64", + "x-go-name": "CPUCores", + "x-nullable": true + }, + "cpuFrequency": { + "description": "cpu频率(G)", + "type": "string", + "x-go-name": "CPUFrequency", + "x-nullable": true + }, + "cpuManufacturer": { + "description": "cpu厂商", + "type": "string", + "x-go-name": "CPUManufacturer", + "x-nullable": true + }, + "cpuModel": { + "description": "cpu处理器型号", + "type": "string", + "x-go-name": "CPUModel", + "x-nullable": true + }, + "cpuSpec": { + "description": "CPU 预置规格", + "type": "string", + "x-go-name": "CpuSpec", + "x-nullable": true + }, + "dataVolumeAmount": { + "description": "数据盘数量", + "type": "integer", + "format": "int64", + "x-go-name": "DataVolumeAmount", + "x-nullable": true + }, + "dataVolumeInterfaceType": { + "description": "数据盘接口类型", + "type": "string", + "x-go-name": "DataVolumeInterfaceType", + "x-nullable": true + }, + "dataVolumeSize": { + "description": "数据盘单盘大小", + "type": "integer", + "format": "int64", + "x-go-name": "DataVolumeSize", + "x-nullable": true + }, + "dataVolumeType": { + "description": "数据盘类型", + "type": "string", + "x-go-name": "DataVolumeType", + "x-nullable": true + }, + "dataVolumeUnit": { + "description": "数据盘单盘大小单位", + "type": "string", + "x-go-name": "DataVolumeUnit", + "x-nullable": true + }, + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description", + "x-nullable": true + }, + "deviceSeries": { + "description": "机型类型,如计算型,存储型", + "type": "string", + "x-go-name": "DeviceSeries", + "x-nullable": true + }, + "deviceType": { + "description": "机型规格", + "type": "string", + "x-go-name": "DeviceType", + "x-nullable": true + }, + "gpuAmount": { + "description": "gpu数量", + "type": "integer", + "format": "int64", + "x-go-name": "GpuAmount", + "x-nullable": true + }, + "gpuManufacturer": { + "description": "gpu厂商", + "type": "string", + "x-go-name": "GpuManufacturer", + "x-nullable": true + }, + "gpuModel": { + "description": "gpu处理器型号", + "type": "string", + "x-go-name": "GpuModel", + "x-nullable": true + }, + "height": { + "description": "【高度(U)】:显示机型高度", + "type": "integer", + "format": "int64", + "x-go-name": "Height", + "x-nullable": true + }, + "idcId": { + "description": "机房id", + "type": "string", + "x-go-name": "IDcID", + "x-nullable": true + }, + "interfaceMode": { + "description": "【网口模式】【网络设置】: 单网口,双网口bond,single", + "type": "string", + "x-go-name": "InterfaceMode", + "x-nullable": true + }, + "isNeedRaid": { + "description": "阵列卡是否需要配置 1 需要配置 2无需配置", + "type": "string", + "x-go-name": "IsNeedRaid", + "x-nullable": true + }, + "memAmount": { + "description": "内存数量", + "type": "integer", + "format": "int64", + "x-go-name": "MemAmount", + "x-nullable": true + }, + "memFrequency": { + "description": "内存主频(MHz)", + "type": "integer", + "format": "int64", + "x-go-name": "MemFrequency", + "x-nullable": true + }, + "memSize": { + "description": "单个内存大小(GB)", + "type": "integer", + "format": "int64", + "x-go-name": "MemSize", + "x-nullable": true + }, + "memSpec": { + "description": "内存 预置规格", + "type": "string", + "x-go-name": "MemSpec", + "x-nullable": true + }, + "memType": { + "description": "内存接口(如DDR3,DDR4)", + "type": "string", + "x-go-name": "MemType", + "x-nullable": true + }, + "name": { + "description": "机型名称", + "type": "string", + "x-go-name": "Name", + "x-nullable": true + }, + "nicAmount": { + "description": "网卡数量", + "type": "integer", + "format": "int64", + "x-go-name": "NicAmount", + "x-nullable": true + }, + "nicRate": { + "description": "网卡传输速率(GE)", + "type": "integer", + "format": "int64", + "x-go-name": "NicRate", + "x-nullable": true + }, + "raidId": { + "description": "系统盘raid,支持多选,英文逗号分隔", + "type": "string", + "x-go-name": "RaidID", + "x-nullable": true + }, + "systemVolumeAmount": { + "description": "系统盘数量", + "type": "integer", + "format": "int64", + "x-go-name": "SystemVolumeAmount", + "x-nullable": true + }, + "systemVolumeInterfaceType": { + "description": "系统盘接口类型(SATA,SAS,NVME)", + "type": "string", + "x-go-name": "SystemVolumeInterfaceType", + "x-nullable": true + }, + "systemVolumeSize": { + "description": "系统盘单盘大小", + "type": "integer", + "format": "int64", + "x-go-name": "SystemVolumeSize", + "x-nullable": true + }, + "systemVolumeType": { + "description": "系统盘类型(SSD,HDD)", + "type": "string", + "x-go-name": "SystemVolumeType", + "x-nullable": true + }, + "systemVolumeUnit": { + "description": "系统盘单盘大小单位", + "type": "string", + "x-go-name": "SystemVolumeUnit", + "x-nullable": true + }, + "volumes": { + "description": "卷管理", + "type": "array", + "items": { + "$ref": "#/definitions/VolumeItem" + }, + "x-go-name": "Volumes", + "x-nullable": true + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyDevicesRequest": { + "type": "object", + "properties": { + "description": { + "description": "修改设备描述", + "type": "string", + "x-go-name": "Description", + "x-nullable": true + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyIdcRequest": { + "type": "object", + "properties": { + "address": { + "description": "机房地址 0-256", + "type": "string", + "x-go-name": "Address", + "x-nullable": true + }, + "iloPassword": { + "description": "带外密码 0-64", + "type": "string", + "x-go-name": "IloPassword", + "x-nullable": true + }, + "iloUser": { + "description": "带外用户名 0-64", + "type": "string", + "x-go-name": "IloUser", + "x-nullable": true + }, + "level": { + "description": "机房等级 1-64", + "type": "string", + "x-go-name": "Level", + "x-nullable": true + }, + "name": { + "description": "机房名称 1-64", + "type": "string", + "x-go-name": "Name", + "x-nullable": true + }, + "nameEn": { + "description": "机房英文名称 1-64", + "type": "string", + "x-go-name": "NameEn", + "x-nullable": true + }, + "shortname": { + "description": "机房缩写 1-64", + "type": "string", + "x-go-name": "Shortname", + "x-nullable": true + }, + "switchPassword1": { + "description": "交换机密码1 0-64", + "type": "string", + "x-go-name": "SwitchPassword1", + "x-nullable": true + }, + "switchPassword2": { + "description": "交换机2密码 0-64", + "type": "string", + "x-go-name": "SwitchPassword2", + "x-nullable": true + }, + "switchUser1": { + "description": "交换机用户1 0-64", + "type": "string", + "x-go-name": "SwitchUser1", + "x-nullable": true + }, + "switchUser2": { + "description": "交换机用户2 0-64", + "type": "string", + "x-go-name": "SwitchUser2", + "x-nullable": true + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyImageRequest": { + "type": "object", + "properties": { + "description": { + "description": "修改设备描述", + "type": "string", + "x-go-name": "Description", + "x-nullable": true + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyInstanceRequest": { + "type": "object", + "properties": { + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description", + "x-nullable": true + }, + "instanceName": { + "description": "实例名称", + "type": "string", + "x-go-name": "InstanceName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyInstancesRequest": { + "description": "批量修改实例名称", + "type": "object", + "properties": { + "instanceName": { + "description": "实例名称", + "type": "string", + "x-go-name": "InstanceName" + }, + "instance_ids": { + "description": "实例id列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIDs" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyLocalUserRequest": { + "type": "object", + "properties": { + "defaultProjectId": { + "description": "用户默认项目uuid", + "type": "string", + "x-go-name": "DefaultProjectID", + "x-nullable": true + }, + "email": { + "description": "邮箱", + "type": "string", + "x-go-name": "Email", + "x-nullable": true + }, + "language": { + "description": "语言[en_US, zh_CN]", + "type": "string", + "x-go-name": "Language", + "x-nullable": true + }, + "phoneNumber": { + "description": "手机号", + "type": "string", + "x-go-name": "PhoneNumber", + "x-nullable": true + }, + "phonePrefix": { + "description": "国家地区码,如86", + "type": "string", + "x-go-name": "PhonePrefix", + "x-nullable": true + }, + "timezone": { + "description": "时区 Asia/Shanghai", + "type": "string", + "x-go-name": "Timezone", + "x-nullable": true + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyOSRequest": { + "type": "object", + "properties": { + "architecture": { + "description": "体系架构", + "type": "string", + "x-go-name": "Architecture" + }, + "bits": { + "description": "位数", + "type": "integer", + "format": "int64", + "x-go-name": "Bits" + }, + "osName": { + "description": "操作系统名称", + "type": "string", + "x-go-name": "OsName" + }, + "osType": { + "description": "操作系统平台", + "type": "string", + "x-go-name": "OsType" + }, + "osVersion": { + "description": "操作系统版本", + "type": "string", + "x-go-name": "OsVersion" + }, + "sysUser": { + "description": "系统用户", + "type": "string", + "x-go-name": "SysUser" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyProjectRequest": { + "type": "object", + "required": [ + "projectName" + ], + "properties": { + "projectName": { + "description": "项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-”", + "type": "string", + "x-go-name": "ProjectName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyRaidRequest": { + "type": "object", + "required": [ + "name", + "descriptionEn", + "descriptionZh" + ], + "properties": { + "descriptionEn": { + "description": "raid描述(中文)", + "type": "string", + "x-go-name": "DescriptionEn" + }, + "descriptionZh": { + "description": "raid描述(英文)", + "type": "string", + "x-go-name": "DescriptionZh" + }, + "name": { + "description": "raid名称", + "type": "string", + "x-go-name": "Name" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyRoleRequest": { + "type": "object", + "properties": { + "descriptionCn": { + "description": "角色描述中文名称", + "type": "string", + "x-go-name": "DescriptionCn" + }, + "descriptionEn": { + "description": "角色描述英文名称", + "type": "string", + "x-go-name": "DescriptionEn" + }, + "roleNameCn": { + "description": "角色中文名称", + "type": "string", + "x-go-name": "RoleNameCn" + }, + "roleNameEn": { + "description": "角色英文名称", + "type": "string", + "x-go-name": "RoleNameEn" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifySshkeyRequest": { + "type": "object", + "properties": { + "name": { + "description": "秘钥名称", + "type": "string", + "x-go-name": "Name", + "x-nullable": true + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyUserPasswordRequest": { + "type": "object", + "required": [ + "oldPassword", + "password" + ], + "properties": { + "oldPassword": { + "description": "旧密码,明文", + "type": "string", + "x-go-name": "OldPassword" + }, + "password": { + "description": "新密码 明文,密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30}", + "type": "string", + "x-go-name": "Password" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModifyUserRequest": { + "type": "object", + "properties": { + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description", + "x-nullable": true + }, + "email": { + "description": "邮箱", + "type": "string", + "x-go-name": "Email", + "x-nullable": true + }, + "phoneNumber": { + "description": "手机号", + "type": "string", + "x-go-name": "PhoneNumber", + "x-nullable": true + }, + "phonePrefix": { + "description": "国家地区码,如86", + "type": "string", + "x-go-name": "PhonePrefix", + "x-nullable": true + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ModuleItem": { + "type": "object", + "properties": { + "description": { + "type": "string", + "x-go-name": "Description" + }, + "descriptionEn": { + "type": "string", + "x-go-name": "DescriptionEn" + }, + "effective": { + "type": "boolean", + "x-go-name": "Effective" + }, + "id": { + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "nameEn": { + "type": "string", + "x-go-name": "NameEn" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "MonitorDataItem": { + "type": "object", + "properties": { + "timestamp": { + "type": "integer", + "format": "int64", + "x-go-name": "Timestamp" + }, + "value": { + "type": "string", + "x-go-name": "Value" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "MonitorDataQuery": { + "type": "object", + "properties": { + "endTime": { + "type": "integer", + "format": "int64", + "x-go-name": "EndTime" + }, + "func": { + "description": "跟赛迪约定,转换单位放这里实现", + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int64" + }, + "x-go-name": "Func" + }, + "labels": { + "description": "metric都放这里了", + "type": "object", + "additionalProperties": { + "type": "string" + }, + "x-go-name": "Labels" + }, + "sampleMethod": { + "description": "MetricName string `json:\"metricName\"`\n[rate, increase]", + "type": "string", + "x-go-name": "SampleMethod" + }, + "startTime": { + "type": "integer", + "format": "int64", + "x-go-name": "StartTime" + }, + "step": { + "type": "integer", + "format": "int64", + "x-go-name": "Step" + }, + "tableName": { + "description": "[bmp_monitor_counter bmp_monitor_gauge]", + "type": "string", + "x-go-name": "TableName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "MountDevicesRequest": { + "type": "object", + "required": [ + "deviceId" + ], + "properties": { + "deviceId": { + "description": "设备uuid", + "type": "string", + "x-go-name": "DeviceID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "Os": { + "type": "object", + "properties": { + "architecture": { + "description": "架构:x86/x64/i386/", + "type": "string", + "x-go-name": "Architecture" + }, + "bits": { + "description": "指令宽度:64/32位", + "type": "integer", + "format": "int64", + "x-go-name": "Bits" + }, + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "deletedTime": { + "description": "删除时间", + "type": "string", + "x-go-name": "DeletedTime" + }, + "id": { + "description": "ID", + "type": "integer", + "format": "uint64", + "x-go-name": "ID" + }, + "isDel": { + "description": "是否删除0未删除 1已删除", + "type": "integer", + "format": "int8", + "x-go-name": "IsDel" + }, + "osId": { + "description": "操作系统uuid", + "type": "string", + "x-go-name": "OsID" + }, + "osName": { + "description": "操作系统名称", + "type": "string", + "x-go-name": "OsName" + }, + "osType": { + "description": "操作系统分类:linux/windows", + "type": "string", + "x-go-name": "OsType" + }, + "osVersion": { + "description": "操作系统版本", + "type": "string", + "x-go-name": "OsVersion" + }, + "sysUser": { + "description": "管理员账户", + "type": "string", + "x-go-name": "SysUser" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "OsId": { + "type": "object", + "properties": { + "osId": { + "description": "操作系统uuid", + "type": "string", + "x-go-name": "OsId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "OsInfo": { + "type": "object", + "properties": { + "os": { + "$ref": "#/definitions/Os" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "OsList": { + "type": "object", + "properties": { + "oss": { + "description": "操作系统列表", + "type": "array", + "items": { + "$ref": "#/definitions/Os" + }, + "x-go-name": "Oss" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Partition": { + "description": "镜像默认分区\n[{\"format\":\"swap\",\"point\":\"swap\",\"size\":10240},{\"format\":\"xfs\",\"point\":\"/\",\"size\":51200}]", + "type": "object", + "properties": { + "format": { + "description": "format,如[swap, xfs]", + "type": "string", + "x-go-name": "FsType" + }, + "point": { + "description": "point,如[swap, /, /var]", + "type": "string", + "x-go-name": "MountPoint" + }, + "size": { + "description": "分区大小, MB为单位", + "type": "integer", + "format": "int64", + "x-go-name": "Size" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Project": { + "type": "object", + "properties": { + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "instanceCount": { + "description": "项目下实例数量", + "type": "integer", + "format": "int64", + "x-go-name": "InstanceCount" + }, + "owned": { + "description": "此项目的共享标志位,1为拥有,2为共享", + "type": "integer", + "format": "int64", + "x-go-name": "Owned" + }, + "projectId": { + "description": "项目uuid", + "type": "string", + "x-go-name": "ProjectID" + }, + "projectName": { + "description": "项目名称", + "type": "string", + "x-go-name": "ProjectName" + }, + "shareProjects": { + "description": "共享", + "type": "array", + "items": { + "$ref": "#/definitions/ShareProject" + }, + "x-go-name": "ShareProjects" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ProjectId": { + "type": "object", + "properties": { + "projectId": { + "description": "项目uuid", + "type": "string", + "x-go-name": "ProjectId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ProjectInfo": { + "type": "object", + "properties": { + "project": { + "$ref": "#/definitions/Project" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ProjectList": { + "type": "object", + "properties": { + "pageNumber": { + "description": "页数", + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "description": "页大小", + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "projects": { + "description": "项目实体列表", + "type": "array", + "items": { + "$ref": "#/definitions/Project" + }, + "x-go-name": "Projects" + }, + "totalCount": { + "description": "总条数", + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "QueryDeviceTypeImagePartitionResponse": { + "type": "object", + "properties": { + "dataPartition": { + "description": "数据盘分区列表", + "type": "array", + "items": { + "$ref": "#/definitions/Partition" + }, + "x-go-name": "DataPartition" + }, + "systemPartition": { + "description": "系统盘分区列表", + "type": "array", + "items": { + "$ref": "#/definitions/Partition" + }, + "x-go-name": "SystemPartition" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "RDeviceTypeRaid": { + "type": "object", + "properties": { + "DiskInterfaceType": { + "description": "磁盘类型:SAS/SATA/SSD/NVME", + "type": "string" + }, + "availableValue": { + "description": "可用分区值,单位GB", + "type": "integer", + "format": "int64", + "x-go-name": "AvailableValue" + }, + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "deviceTypeId": { + "description": "设备类型id", + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "diskType": { + "description": "磁盘类型:SAS/SATA/SSD/NVME", + "type": "string", + "x-go-name": "DiskType" + }, + "raidId": { + "description": "RAID uuid", + "type": "string", + "x-go-name": "RaidID" + }, + "systemPartitionCount": { + "description": "系统盘noraid模式真实数量;此模式多块盘只能用一块", + "type": "integer", + "format": "int64", + "x-go-name": "SystemPartitionCount" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "volumeDetail": { + "description": "磁盘详细信息", + "type": "string", + "x-go-name": "VolumeDetail" + }, + "volumeType": { + "description": "磁盘类型 system/data", + "type": "string", + "x-go-name": "VolumeType" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Raid": { + "type": "object", + "properties": { + "descriptionEn": { + "description": "中文描述", + "type": "string", + "x-go-name": "DescriptionEn" + }, + "descriptionZh": { + "description": "description", + "type": "string", + "x-go-name": "DescriptionZh" + }, + "name": { + "description": "raid 名称", + "type": "string", + "x-go-name": "Name" + }, + "raidId": { + "description": "raid uuid", + "type": "string", + "x-go-name": "RaidID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "RaidId": { + "type": "object", + "properties": { + "raidId": { + "description": "raid uuid", + "type": "string", + "x-go-name": "RaidId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "RaidList": { + "type": "object", + "properties": { + "raids": { + "description": "raid实体列表", + "type": "array", + "items": { + "$ref": "#/definitions/Raid" + }, + "x-go-name": "Raids" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ReadMessagesRequest": { + "type": "object", + "required": [ + "messageIds" + ], + "properties": { + "messageIds": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "MessageIds" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ReinstallInstanceRequest": { + "type": "object", + "required": [ + "imageId", + "systemVolumeRaidId", + "instanceName", + "bootMode" + ], + "properties": { + "bootMode": { + "description": "引导模式 [UEFI Legacy/BIOS]", + "type": "string", + "x-go-name": "BootMode" + }, + "dataPartition": { + "description": "数据盘分区", + "type": "array", + "items": { + "$ref": "#/definitions/Partition" + }, + "x-go-name": "DataPartition" + }, + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description" + }, + "hostname": { + "description": "主机名称", + "type": "string", + "x-go-name": "HostName" + }, + "imageId": { + "description": "镜像ID", + "type": "string", + "x-go-name": "ImageID" + }, + "installBmpAgent": { + "description": "是否安装bmp-agent", + "type": "boolean", + "x-go-name": "InstallBmpAgent" + }, + "instanceName": { + "description": "实例名称", + "type": "string", + "x-go-name": "InstanceName" + }, + "password": { + "description": "密码", + "type": "string", + "x-go-name": "Password" + }, + "sshKeyId": { + "description": "秘钥ID,运营平台重装,密钥暂时不可用", + "type": "string", + "x-go-name": "SshKeyID" + }, + "systemPartition": { + "description": "系统盘分区", + "type": "array", + "items": { + "$ref": "#/definitions/Partition" + }, + "x-go-name": "SystemPartition" + }, + "systemVolumeRaidId": { + "description": "系统盘RAID ID", + "type": "string", + "x-go-name": "SystemVolumeRaidID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ResetInstancePasswdRequest": { + "description": "重置实例密码", + "type": "object", + "properties": { + "password": { + "description": "新密码", + "type": "string", + "x-go-name": "Password" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ResetInstancesPasswdRequest": { + "description": "批量重置实例密码", + "type": "object", + "properties": { + "instance_ids": { + "description": "实例id列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIDs" + }, + "password": { + "description": "新密码", + "type": "string", + "x-go-name": "Password" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "RestartInstancesRequest": { + "type": "object", + "properties": { + "instanceIds": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "Role": { + "type": "object", + "properties": { + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "descriptionCn": { + "description": "description", + "type": "string", + "x-go-name": "DescriptionCn" + }, + "descriptionEn": { + "description": "权限描述", + "type": "string", + "x-go-name": "DescriptionEn" + }, + "permission": { + "description": "权限", + "type": "string", + "x-go-name": "Permission" + }, + "roleId": { + "description": "角色uuid", + "type": "string", + "x-go-name": "RoleID" + }, + "roleName": { + "description": "角色名称", + "type": "string", + "x-go-name": "RoleName" + }, + "roleNameCn": { + "description": "角色名称,唯一", + "type": "string", + "x-go-name": "RoleNameCn" + }, + "roleNameEn": { + "description": "角色名称,唯一", + "type": "string", + "x-go-name": "RoleNameEn" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "userCount": { + "description": "用户数", + "type": "integer", + "format": "int64", + "x-go-name": "UserCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "RoleId": { + "type": "object", + "properties": { + "roleId": { + "description": "角色uuid", + "type": "string", + "x-go-name": "RoleId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "RoleInfo": { + "type": "object", + "properties": { + "role": { + "$ref": "#/definitions/Role" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "RoleList": { + "type": "object", + "properties": { + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "roles": { + "description": "角色实体列表", + "type": "array", + "items": { + "$ref": "#/definitions/Role" + }, + "x-go-name": "Roles" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "Rule": { + "type": "object", + "properties": { + "deviceTag": { + "description": "盘符、挂载点、网口列表", + "type": "string", + "x-go-name": "DeviceTag" + }, + "dimension": { + "description": "维度 [instance、disk、mountpoint、nic]", + "type": "string", + "x-go-name": "Dimension" + }, + "dimensionName": { + "description": "维度名称 [实例、盘符、挂载点、网卡]", + "type": "string", + "x-go-name": "DimensionName" + }, + "instanceCount": { + "description": "关联实例个数", + "type": "integer", + "format": "int64", + "x-go-name": "InstanceCount" + }, + "instanceIds": { + "description": "实例id列表", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + }, + "instances": { + "description": "实例详细信息", + "type": "array", + "items": { + "$ref": "#/definitions/Instance" + }, + "x-go-name": "Instances" + }, + "noticeOption": { + "$ref": "#/definitions/RuleNotice" + }, + "relatedResourceCount": { + "description": "此规则关联的资源数", + "type": "integer", + "format": "int64", + "x-go-name": "RelatedResourceCount" + }, + "resource": { + "description": "资源类型,目前只支持instance", + "type": "string", + "x-go-name": "Resource" + }, + "resourceName": { + "description": "资源类型名称 实例", + "type": "string", + "x-go-name": "ResourceName" + }, + "ruleId": { + "description": "规则uuid", + "type": "string", + "x-go-name": "RuleID" + }, + "ruleName": { + "description": "规则名称", + "type": "string", + "x-go-name": "RuleName" + }, + "status": { + "description": "规则状态[1-\u003e正常,2-\u003e已禁用,3-\u003e报警]", + "type": "integer", + "format": "int64", + "x-go-name": "Status" + }, + "statusName": { + "description": "规则状态名称", + "type": "string", + "x-go-name": "StatusName" + }, + "triggerDescription": { + "description": "触发条件描述", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "TriggerDescription" + }, + "triggerOption": { + "description": "触发条件", + "type": "array", + "items": { + "$ref": "#/definitions/RuleTrigger" + }, + "x-go-name": "TriggerOption" + }, + "userId": { + "description": "user_id", + "type": "string", + "x-go-name": "UserID" + }, + "userName": { + "description": "user_name", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "RuleList": { + "type": "object", + "properties": { + "pageNumber": { + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "rules": { + "description": "rules数组", + "type": "array", + "items": { + "$ref": "#/definitions/Rule" + }, + "x-go-name": "Rules" + }, + "totalCount": { + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "RuleNotice": { + "description": "通知策略", + "type": "object", + "required": [ + "noticePeriod", + "effectiveIntervalStart", + "effectiveIntervalEnd", + "noticeCondition", + "noticeWay", + "userId" + ], + "properties": { + "effectiveIntervalEnd": { + "description": "有效时段结束时间 [\"23:59:59\"]", + "type": "string", + "x-go-name": "EffectiveIntervalEnd" + }, + "effectiveIntervalStart": { + "description": "有效时段开始时间 [\"00:00:00\"]", + "type": "string", + "x-go-name": "EffectiveIntervalStart" + }, + "noticeCondition": { + "description": "通知条件,可多选 [1表示报警, 2表示恢复正常]", + "type": "array", + "items": { + "type": "integer", + "format": "int64" + }, + "x-go-name": "NoticeCondition" + }, + "noticePeriod": { + "description": "通知周期(分钟) [5 10 15 30 60 180 360 720 1440]", + "type": "integer", + "format": "int64", + "x-go-name": "NoticePeriod" + }, + "noticeWay": { + "description": "接收渠道,可多选 [1表示站内信, 2表示邮件]", + "type": "array", + "items": { + "type": "integer", + "format": "int64" + }, + "x-go-name": "NoticeWay" + }, + "userId": { + "description": "通知对象用户Id", + "type": "string", + "x-go-name": "UserID" + }, + "userName": { + "description": "通知对象用户", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "RuleTrigger": { + "description": "单个触发条件", + "type": "object", + "required": [ + "metric", + "period", + "calculation", + "operation", + "threshold", + "times", + "noticeLevel" + ], + "properties": { + "calculation": { + "description": "计算方式 [min max avg sum]", + "type": "string", + "x-go-name": "Calculation" + }, + "calculationUnit": { + "description": "计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出]", + "type": "string", + "x-go-name": "CalculationUnit" + }, + "description": { + "description": "对此rule的描述", + "type": "string", + "x-go-name": "Description" + }, + "metric": { + "description": "监控指标 cps.cpu.util", + "type": "string", + "x-go-name": "Metric" + }, + "metricName": { + "description": "监控指标名称 CPU使用率", + "type": "string", + "x-go-name": "MetricName" + }, + "noticeLevel": { + "description": "告警级别 [1表示一般,2表示严重,3表示紧急]", + "type": "integer", + "format": "int64", + "x-go-name": "NoticeLevel" + }, + "operation": { + "description": "比较方式 [\u003e \u003e= \u003c \u003c= == !=]或者[gt gte lt lte eq neq]", + "type": "string", + "x-go-name": "Operation" + }, + "period": { + "description": "周期 5(分钟)", + "type": "integer", + "format": "int64", + "x-go-name": "Period" + }, + "tableName": { + "description": "[bmp_monitor_counter, bmp_monitor_gauge]", + "type": "string", + "x-go-name": "TableName" + }, + "threshold": { + "description": "阈值", + "type": "number", + "format": "double", + "x-go-name": "Threshold" + }, + "times": { + "description": "持续周期数 [1, 2, 3, 5, 10, 15, 30, 60]", + "type": "integer", + "format": "int64", + "x-go-name": "Times" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "SaveIsPushMailRequest": { + "type": "object", + "properties": { + "is_push": { + "description": "是否推送邮件告警,0不推送,1推送", + "type": "string", + "x-go-name": "IsPush" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "ShareProject": { + "type": "object", + "properties": { + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "ownerUserId": { + "description": "项目拥有者用户id", + "type": "string", + "x-go-name": "OwnerUserID" + }, + "ownerUserName": { + "description": "项目拥有者用户名", + "type": "string", + "x-go-name": "OwnerUserName" + }, + "projectId": { + "description": "项目uuid", + "type": "string", + "x-go-name": "ProjectID" + }, + "projectName": { + "description": "项目名称", + "type": "string", + "x-go-name": "ProjectName" + }, + "shareProjects": { + "type": "array", + "items": { + "$ref": "#/definitions/ShareProject" + }, + "x-go-name": "ShareProjects" + }, + "sharedUserId": { + "description": "项目共享者用户id", + "type": "string", + "x-go-name": "SharedUserID" + }, + "sharedUserName": { + "description": "项目拥有者用户名", + "type": "string", + "x-go-name": "SharedUserName" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "ShareProjectRequest": { + "type": "object", + "required": [ + "ownerID", + "sharerID" + ], + "properties": { + "ownerID": { + "description": "from user_id", + "type": "string", + "x-go-name": "OwnerID" + }, + "sharerID": { + "description": "to user_id", + "type": "string", + "x-go-name": "SharerID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "Sshkey": { + "type": "object", + "properties": { + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "fingerPrint": { + "description": "公钥指纹", + "type": "string", + "x-go-name": "FingerPrint" + }, + "id": { + "description": "id", + "type": "integer", + "format": "int64", + "x-go-name": "Id" + }, + "key": { + "description": "公钥,格式:ssh-rsa AAA", + "type": "string", + "x-go-name": "Key" + }, + "name": { + "description": "秘钥名称", + "type": "string", + "x-go-name": "Name" + }, + "sshkeyId": { + "description": "秘钥uuid", + "type": "string", + "x-go-name": "SshkeyId" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "userId": { + "description": "所属用户uuid", + "type": "string", + "x-go-name": "UserId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "SshkeyId": { + "type": "object", + "properties": { + "sshkeyId": { + "description": "sshkey uuid", + "type": "string", + "x-go-name": "SshkeyId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "SshkeyInfo": { + "type": "object", + "properties": { + "sshkey": { + "$ref": "#/definitions/Sshkey" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "SshkeyList": { + "type": "object", + "properties": { + "pageNumber": { + "description": "页数", + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "description": "页大小", + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "sshkeys": { + "description": "sshkey实体列表", + "type": "array", + "items": { + "$ref": "#/definitions/Sshkey" + }, + "x-go-name": "Sshkeys" + }, + "totalCount": { + "description": "总条数", + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "StartInstancesRequest": { + "type": "object", + "properties": { + "instanceIds": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "StopInstancesRequest": { + "type": "object", + "properties": { + "instanceIds": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "InstanceIds" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "TagsResponse": { + "type": "object", + "properties": { + "tags": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "Tags" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "UnMountDevicesRequest": { + "type": "object", + "required": [ + "deviceId" + ], + "properties": { + "deviceId": { + "description": "设备uuid", + "type": "string", + "x-go-name": "DeviceID" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "User": { + "type": "object", + "properties": { + "createdBy": { + "description": "创建者", + "type": "string", + "x-go-name": "CreatedBy" + }, + "createdTime": { + "description": "创建时间", + "type": "string", + "x-go-name": "CreatedTime" + }, + "defaultProjectId": { + "description": "用户默认项目uuid", + "type": "string", + "x-go-name": "DefaultProjectID" + }, + "defaultProjectName": { + "description": "用户默认项目名称", + "type": "string", + "x-go-name": "DefaultProjectName" + }, + "description": { + "description": "描述", + "type": "string", + "x-go-name": "Description" + }, + "email": { + "description": "邮箱", + "type": "string", + "x-go-name": "Email" + }, + "id": { + "description": "用户id", + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "instanceCount": { + "description": "用户拥有的实例数量", + "type": "integer", + "format": "int64", + "x-go-name": "InstanceCount" + }, + "language": { + "description": "默认语言(en_US/zh_CN)", + "type": "string", + "x-go-name": "Language" + }, + "phoneNumber": { + "description": "手机号", + "type": "string", + "x-go-name": "PhoneNumber" + }, + "phonePrefix": { + "description": "国家地区码,如86", + "type": "string", + "x-go-name": "PhonePrefix" + }, + "projectCount": { + "description": "用户拥有的项目数量", + "type": "integer", + "format": "int64", + "x-go-name": "ProjectCount" + }, + "roleId": { + "description": "角色uuid", + "type": "string", + "x-go-name": "RoleID" + }, + "roleName": { + "description": "角色名称", + "type": "string", + "x-go-name": "RoleName" + }, + "timezone": { + "description": "时区", + "type": "string", + "x-go-name": "Timezone" + }, + "updatedBy": { + "description": "更新者", + "type": "string", + "x-go-name": "UpdatedBy" + }, + "updatedTime": { + "description": "更新时间", + "type": "string", + "x-go-name": "UpdatedTime" + }, + "userId": { + "description": "用户uuid", + "type": "string", + "x-go-name": "UserID" + }, + "userName": { + "description": "用户名,唯一", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "UserId": { + "type": "object", + "properties": { + "userId": { + "description": "用户uuid", + "type": "string", + "x-go-name": "UserId" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "UserInfo": { + "type": "object", + "properties": { + "user": { + "$ref": "#/definitions/User" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "UserList": { + "type": "object", + "properties": { + "pageNumber": { + "description": "页数", + "type": "integer", + "format": "int64", + "x-go-name": "PageNumber" + }, + "pageSize": { + "description": "页大小", + "type": "integer", + "format": "int64", + "x-go-name": "PageSize" + }, + "totalCount": { + "description": "总条数", + "type": "integer", + "format": "int64", + "x-go-name": "TotalCount" + }, + "users": { + "description": "user实体列表", + "type": "array", + "items": { + "$ref": "#/definitions/User" + }, + "x-go-name": "Users" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "VerifyUserRequest": { + "type": "object", + "required": [ + "userName", + "password", + "roleId" + ], + "properties": { + "password": { + "description": "密码", + "type": "string", + "x-go-name": "Password" + }, + "roleId": { + "description": "角色uuid", + "type": "string", + "x-go-name": "RoleID" + }, + "userName": { + "description": "用户名,唯一", + "type": "string", + "x-go-name": "UserName" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + }, + "Volume": { + "type": "object", + "properties": { + "diskType": { + "type": "string", + "x-go-name": "DiskType" + }, + "interfaceType": { + "type": "string", + "x-go-name": "InterfaceType" + }, + "raid": { + "type": "string", + "x-go-name": "Raid" + }, + "raidCan": { + "type": "string", + "x-go-name": "RaidCan" + }, + "raidId": { + "type": "string", + "x-go-name": "RaidId" + }, + "volumeAmount": { + "type": "integer", + "format": "int64", + "x-go-name": "VolumeAmount" + }, + "volumeId": { + "type": "string", + "x-go-name": "VolumeID" + }, + "volumeName": { + "type": "string", + "x-go-name": "VolumeName" + }, + "volumeSize": { + "type": "string", + "x-go-name": "VolumeSize" + }, + "volumeType": { + "type": "string", + "x-go-name": "VolumeType" + }, + "volumeUnit": { + "type": "string", + "x-go-name": "VolumeUnit" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "VolumeIt": { + "type": "object", + "properties": { + "diskType": { + "type": "string", + "x-go-name": "DiskType" + }, + "disks": { + "type": "array", + "items": { + "$ref": "#/definitions/Disk" + }, + "x-go-name": "Disks" + }, + "interfaceType": { + "type": "string", + "x-go-name": "InterfaceType" + }, + "raid": { + "type": "string", + "x-go-name": "Raid" + }, + "raidCan": { + "type": "string", + "x-go-name": "RaidCan" + }, + "raidId": { + "type": "string", + "x-go-name": "RaidId" + }, + "raids": { + "type": "array", + "items": { + "$ref": "#/definitions/Raid" + }, + "x-go-name": "Raids" + }, + "volumeAmount": { + "type": "integer", + "format": "int64", + "x-go-name": "VolumeAmount" + }, + "volumeId": { + "type": "string", + "x-go-name": "VolumeID" + }, + "volumeName": { + "type": "string", + "x-go-name": "VolumeName" + }, + "volumeSize": { + "type": "string", + "x-go-name": "VolumeSize" + }, + "volumeType": { + "type": "string", + "x-go-name": "VolumeType" + }, + "volumeUnit": { + "type": "string", + "x-go-name": "VolumeUnit" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + }, + "VolumeItem": { + "type": "object", + "properties": { + "deviceTypeId": { + "type": "string", + "x-go-name": "DeviceTypeID" + }, + "diskType": { + "type": "string", + "x-go-name": "DiskType" + }, + "interfaceType": { + "type": "string", + "x-go-name": "InterfaceType" + }, + "raid": { + "type": "string", + "x-go-name": "Raid" + }, + "raidCan": { + "type": "string", + "x-go-name": "RaidCan" + }, + "volumeAmount": { + "type": "integer", + "format": "int64", + "x-go-name": "VolumeAmount" + }, + "volumeName": { + "type": "string", + "x-go-name": "VolumeName" + }, + "volumeSize": { + "type": "string", + "x-go-name": "VolumeSize" + }, + "volumeType": { + "type": "string", + "x-go-name": "VolumeType" + }, + "volumeUnit": { + "type": "string", + "x-go-name": "VolumeUnit" + } + }, + "x-go-package": "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + } + }, + "responses": { + "ErrorResponse": { + "description": "unit err response for non 200", + "schema": { + "type": "object", + "required": [ + "error", + "requestId" + ], + "properties": { + "error": { + "$ref": "#/definitions/ErrorResponse" + }, + "requestId": { + "description": "流量ID", + "type": "string", + "x-go-name": "RequestId" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "addRule": { + "description": "A AddRuleResult is an response struct that is used to describe create rule result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "associateDeviceDisks": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "associatedDeviceType": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "associatedImage": { + "description": "A AssociatedImageResult is an response struct that is used to associated image result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "cancelShareUserProject": { + "description": "A CancelShareUserProjectResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "collectDeviceInfo": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createDevice": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createDeviceType": { + "description": "A CreateDeviceTypeResult is an response struct that is used to describe create deviceType result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/DeviceTypeId" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createDeviceTypeRaid": { + "description": "A CreateDeviceTypeRaidResult is an response struct that is used to describe create device type raid result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createIdc": { + "description": "A CreateIdcResult is an response struct that is used to describe create idc result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/IdcID" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createImage": { + "description": "A CreateImageResult is an response struct that is used to describe create image result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ImageId" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createOS": { + "description": "A CreateOsResult is an response struct that is used to describe create os result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/OsId" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createProjectInstance": { + "description": "A CreateProjectInstanceResult is an response struct that is used to describe create instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/InstanceIds" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createRaid": { + "description": "A CreateRaidResult is an response struct that is used to describe create raid result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/RaidId" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createRole": { + "description": "A CreateRoleResult is an response struct that is used to describe create role result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/RoleId" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createUser": { + "description": "A CreateInstancesResult is an response struct that is used to describe create instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/UserId" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createUserApikey": { + "description": "A CreateUserApikeyResult is an response struct that is used to describe create apikey result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ApikeyId" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createUserProject": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ProjectId" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "createUserSshkey": { + "description": "A CreateUserSshkeyResult is an response struct that is used to describe create sshkey result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/SshkeyId" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "currentRole": { + "description": "A CurrentRoleResult is an response struct that is used to describe role.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/RoleInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteAlert": { + "description": "A DeleteAlertResult is an response struct that is used to describe create alert result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteDevice": { + "description": "A DeleteDeviceResult is an response struct that is used to describe delete device result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteDeviceType": { + "description": "A DeleteDeviceTypeResult is an response struct that is used to delete device type.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteDeviceTypeRaid": { + "description": "A DeleteDeviceTypeRaidResult is an response struct that is used to describe delete device type raid result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteIdc": { + "description": "A DeleteIdcResult is an response struct that is used to delete idc.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteImage": { + "description": "A DeleteImageResult is an response struct that is used to delete image.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteInstances": { + "description": "A DeleteInstancesResult is an response struct that is used to describe modify instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteMessage": { + "description": "A DeleteMessageResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteOS": { + "description": "A DeleteOsResult is an response struct that is used to delete stop os result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteProjectInstance": { + "description": "A DeleteProjectInstanceResult is an response struct that is used to delete stop instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteRaid": { + "description": "A DeleteRaidResult is an response struct that is used to delete raid.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteRole": { + "description": "A DeleteRoleResult is an response struct that is used to delete role.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteRule": { + "description": "A DeleteRuleResult is an response struct that is used to describe create rule result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteUser": { + "description": "A GetUserResult is an response struct that is used to describe getuser.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteUserApikey": { + "description": "A DeleteUserApikeyResult is an response struct that is used to describe delete Apikey result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteUserProject": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deleteUserSshkey": { + "description": "A DeleteUserSshkeyResult is an response struct that is used to describe delete sshkey result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeAlert": { + "description": "A DescribeAlertResult is an response struct that is used to describe get Alert.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/Alert" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeAlerts": { + "description": "A DescribeAlertsResult is an response struct that is used to describe get Alert.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/AlertList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeAuditLogTypes": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "type": "array", + "items": { + "$ref": "#/definitions/AuditLogsType" + }, + "x-go-name": "Result" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeAuditLogs": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/AuditLogList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDevice": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/DeviceInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDeviceDisks": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/DeviceDisks" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDeviceStock": { + "description": "A GetDeviceStockResult is an response struct that is used to get device stock.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/DeviceStock" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDeviceType": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/DeviceTypeInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDeviceTypeImagePartitions": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/QueryDeviceTypeImagePartitionResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDeviceTypeImages": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ImageList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDeviceTypeRaids": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "type": "array", + "items": { + "$ref": "#/definitions/RDeviceTypeRaid" + }, + "x-go-name": "Result" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDeviceTypes": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/DeviceTypeList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeDevices": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/DeviceList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeIdc": { + "description": "A DescribeIdcResult is an response struct that is used to describe idc.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/IdcInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeIdcs": { + "description": "A DescribIdcsResult is an response struct that is used to describe idcs.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/IdcList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeImage": { + "description": "A DescribeImageResult is an response struct that is used to describe image.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ImageInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeImageDeviceTypes": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/DeviceTypeList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeImages": { + "description": "A DescribeImagesResult is an response struct that is used to describe images.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ImageList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeLicenseContent": { + "description": "A DescribeLicenseContentResult is an response struct that is used to describe getuser.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/LicenseContent" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeLicenseToken": { + "description": "A DescribeLocalUserResult is an response struct that is used to describe getuser.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/LicenseToken" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeLocalUser": { + "description": "A DescribeLocalUserResult is an response struct that is used to describe getuser.", + "schema": { + "type": "object", + "properties": { + "error": { + "$ref": "#/definitions/ErrorResponse" + }, + "result": { + "$ref": "#/definitions/UserInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeOS": { + "description": "A DescribeOsResult is an response struct that is used to describe os.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/OsInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeOSs": { + "description": "A DescribeOssResult is an response struct that is used to describe oss.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/OsList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeProjectInstance": { + "description": "A GetInstanceResult is an response struct that is used to describe instance.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/InstanceInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeProjectInstances": { + "description": "A DescribeProjectInstancesResult is an response struct that is used to get instance list.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/InstanceList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeRaid": { + "description": "A GetRaidResult is an response struct that is used to describe raid.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/Raid" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeRaids": { + "description": "QueryRaidsAllResult is an response struct that is used to query all raids.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/RaidList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeResources": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeRole": { + "description": "A GetRoleResult is an response struct that is used to describe role.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/RoleInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeRoles": { + "description": "A GetRoleListResult is an response struct that is used to describe get role list.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/RoleList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeRule": { + "description": "A DescribeRuleResult is an response struct that is used to describe get rule.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/Rule" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeRules": { + "description": "A DescribeRuleResult is an response struct that is used to describe get rule.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/RuleList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUser": { + "description": "", + "schema": { + "type": "object", + "properties": { + "error": { + "$ref": "#/definitions/ErrorResponse" + }, + "result": { + "$ref": "#/definitions/UserInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUserAPIKey": { + "description": "A DescribeUserAPIKeyResult is an response struct that is used to describe getapikey.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ApikeyInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUserAPIKeys": { + "description": "A DescribeUserAPIKeysResult is an response struct that is used to describe getapikeylist.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ApikeyList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUserByName": { + "description": "A GetUserByNameResult is an response struct that is used to describe user.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/UserInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUserProject": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ProjectInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUserProjects": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/ProjectList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUserSshKey": { + "description": "A DescribeUserSshKeyResult is an response struct that is used to describe sshkey.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/SshkeyInfo" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUserSshKeys": { + "description": "A DescribeUserSshKeysResult is an response struct that is used to describe get sshkey list.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/SshkeyList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeUsers": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/UserList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "describeVolumesByDeviceType": { + "description": "A DescribeVolumesByDeviceTypeResult is an response struct that is used to describe get sshkey list.", + "schema": { + "type": "object", + "properties": { + "result": { + "type": "array", + "items": { + "$ref": "#/definitions/VolumeIt" + }, + "x-go-name": "Result" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "desrcibeAgentStatus": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/AgentStatusResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "desrcibeTags": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/TagsResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "deviceAssociateDeviceType": { + "description": "A DeviceAssociateDeviceTypeResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "dialMail": { + "description": "A DialMailResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "disableRule": { + "description": "A DisableRuleResult is an response struct that is used to describe create rule result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "dissociatedDeviceType": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "dissociatedImage": { + "description": "A DissociatedImageResult is an response struct that is used to dissociated image result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "editRule": { + "description": "A EditRuleResult is an response struct that is used to describe create rule result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "enableRule": { + "description": "A EnableRuleResult is an response struct that is used to describe create rule result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "getAssociatedDisks": { + "description": "A GetAssociatedDisksResult is an response struct that is used to get instance list by sshkey.", + "schema": { + "type": "object", + "properties": { + "result": { + "type": "array", + "items": { + "$ref": "#/definitions/Disk" + }, + "x-go-name": "Result" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "getInstancesBySshkey": { + "description": "A GetInstancesBySshkeyResult is an response struct that is used to get instance list by sshkey.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/InstancesSshkeyInfoResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "getMessageById": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/MessageWithNextPrev" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "getMessageList": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/MessageList" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "getMessageStatistic": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/MessageStatistic" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "getMessageTypes": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/MessageTypesResp" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "getMonitorData": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "type": "array", + "items": { + "$ref": "#/definitions/DataEveryMetric" + }, + "x-go-name": "Result" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "hasUnreadMessage": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/HasUnreadMessage" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "lockProjectInstance": { + "description": "A LockProjectInstanceResult is an response struct that is used to describe lock instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "mailDetail": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/Mail" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyDevice": { + "description": "A ModifyDeviceResult is an response struct that is used to describe modify device result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyDeviceType": { + "description": "A ModifyDeviceTypeResult is an response struct that is used to modify device type.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyIdc": { + "description": "A ModifyIdcResult is an response struct that is used to modify idc.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyImage": { + "description": "A ModifyImageResult is an response struct that is used to modify image.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyInstances": { + "description": "A ModifyInstancesResult is an response struct that is used to describe modify instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyLocalUser": { + "description": "A ModifyLocalUserResult is an response struct that is used to describe getuser.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyLocalUserPassword": { + "description": "A ModifyLocalUserPasswordResult is an response struct that is used to describe getuser.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyOS": { + "description": "A ModifyOsResult is an response struct that is used to describe modify os.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyProjectInstance": { + "description": "A ModifyProjectInstanceResult is an response struct that is used to describe modify instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyRaid": { + "description": "A ModifyRaidResult is an response struct that is used to describe modify raid.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyRole": { + "description": "A ModifyRoleResult is an response struct that is used to describe modify role.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyUser": { + "description": "A GetUserResult is an response struct that is used to describe getuser.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyUserApikey": { + "description": "A ModifyUserApikeyResult is an response struct that is used to describe modifyApikey result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyUserProject": { + "description": "", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "modifyUserSshkey": { + "description": "A ModifyUserSshkeyResult is an response struct that is used to modify sshkey result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "mountDevice": { + "description": "A MountDeviceResult is an response struct that is used to describe mount device result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "readMessage": { + "description": "A ReadMessageResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "reinstallProjectInstance": { + "description": "A ReinstallProjectInstanceResult is an response struct that is used to describe reinstall instance.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "removeDevice": { + "description": "A RemoveDeviceResult is an response struct that is used to describe restart instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "resetInstanceStatus": { + "description": "A ResetInstanceStatusResult is an response struct that is used to describe restart instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "resetProjectInstancePasswd": { + "description": "A ResetProjectInstancePasswdResult is an response struct that is used to describe reset instance password.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "resetProjectInstancesPasswd": { + "description": "A ResetProjectInstancesPasswdResult is an response struct that is used to describe reset instance password.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "restartInstances": { + "description": "A RestartInstancesResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "restartProjectInstance": { + "description": "A RestartProjectInstanceResult is an response struct that is used to describe restart instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "saveIsPushMail": { + "description": "A SaveIsPushMailResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "shareUserProject": { + "description": "A ShareUserProjectResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "startInstances": { + "description": "A StartInstancesResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "startProjectInstance": { + "description": "A StartProjectInstanceResult is an response struct that is used to describe start instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "stopInstances": { + "description": "A StopInstancesResult is an response struct", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "stopProjectInstance": { + "description": "A StopProjectInstanceResult is an response struct that is used to describe stop instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "unLockProjectInstance": { + "description": "A UnLockProjectInstanceResult is an response struct that is used to describe unlock instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "unMountDevice": { + "description": "A UnMountDeviceResult is an response struct that is used to unmount device.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "uploadLicense": { + "description": "A UploadLicenseResult is an response struct that is used to describe modify instance result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + }, + "verifyUser": { + "description": "A VerifyUserResult is an response struct that is used to describe verify user result.", + "schema": { + "type": "object", + "properties": { + "result": { + "$ref": "#/definitions/CommonResponse" + } + } + }, + "headers": { + "traceId": { + "type": "string", + "description": "流量ID\nin: header" + } + } + } + }, + "securityDefinitions": { + "api_key": { + "type": "apiKey", + "name": "bmp-ak", + "in": "header" + } + }, + "security": [ + { + "api_key": [] + } + ], + "x-meta-array": [ + "value1", + "value2" + ], + "x-meta-array-obj": [ + { + "name": "obj", + "value": "field" + } + ], + "x-meta-value": "value" +} \ No newline at end of file diff --git a/bmp-openapi/swagger.yml b/bmp-openapi/swagger.yml new file mode 100644 index 0000000..ad711f9 --- /dev/null +++ b/bmp-openapi/swagger.yml @@ -0,0 +1,12281 @@ +basePath: /v1 +consumes: + - application/json + - application/xml +definitions: + AddRuleRequest: + properties: + deviceTag: + description: 盘符、挂载点、网口列表 + type: string + x-go-name: DeviceTag + dimension: + description: 维度 [instance、disk、mountpoint、nic] + type: string + x-go-name: Dimension + instanceIds: + description: 实例id列表 + items: + type: string + type: array + x-go-name: InstanceIds + noticeOption: + $ref: '#/definitions/RuleNotice' + resource: + description: 资源类型,目前只支持instance + type: string + x-go-name: Resource + ruleName: + description: 规则名称 + type: string + x-go-name: RuleName + triggerOption: + description: 触发条件 + items: + $ref: '#/definitions/RuleTrigger' + type: array + x-go-name: TriggerOption + required: + - ruleName + - dimension + - resource + - triggerOption + - noticeOption + - instanceIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + AgentStatusItem: + properties: + agent_version: + type: string + x-go-name: AgentVersion + instance_id: + type: string + x-go-name: InstanceID + sn: + type: string + x-go-name: SN + status: + description: 1->running 2->stopped 0->unknown + format: int64 + type: integer + x-go-name: Status + statusName: + description: status 运行 停止 未知 + type: string + x-go-name: StatusName + timestamp: + format: int64 + type: integer + x-go-name: Timestamp + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + AgentStatusResponse: + properties: + agentStatus: + items: + $ref: '#/definitions/AgentStatusItem' + type: array + x-go-name: AgentStatus + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Alert: + properties: + alertId: + description: alert uuid + type: string + x-go-name: AlertID + alertLevel: + description: 1表示一般,2表示严重,3表示紧急 + format: int64 + type: integer + x-go-name: AlertLevel + alertLevelDescription: + description: 级别描述 + type: string + x-go-name: AlertLevelDescription + alertPeriod: + description: 告警持续时间(分钟为单位) + format: int64 + type: integer + x-go-name: AlertPeriod + alertTime: + description: 告警时间戳 + format: int64 + type: integer + x-go-name: AlertTime + alertValue: + description: 报警值 + type: string + x-go-name: AlertValue + createdTime: + description: 创建时间戳 + format: int64 + type: integer + x-go-name: CreatedTime + instance: + $ref: '#/definitions/Instance' + resource: + description: 资源类型 [只支持instance一种] + type: string + x-go-name: Resource + resourceId: + description: 资源id,目前就是实例id + type: string + x-go-name: ResourceID + resourceName: + description: 资源名称,目前就是实例名称 + type: string + x-go-name: ResourceName + rule: + $ref: '#/definitions/Rule' + trigger: + description: 触发条件,接口需要翻译 + type: string + x-go-name: Trigger + triggerDescription: + description: 触发条件描述 + type: string + x-go-name: TriggerDescription + userId: + description: 通知对象 userid + type: string + x-go-name: UserID + userName: + description: 通知对象 用户名 + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + AlertList: + properties: + instances: + description: rules数组 + items: + $ref: '#/definitions/Alert' + type: array + x-go-name: Alerts + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Apikey: + properties: + apiKeyId: + description: apikey uuid + type: string + x-go-name: ApikeyID + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + id: + format: int64 + type: integer + x-go-name: ID + name: + description: 名称 + type: string + x-go-name: Name + readOnly: + description: 是否支持只读, [0/1], 1表示只读 + format: int8 + type: integer + x-go-name: ReadOnly + token: + description: 32位字符令牌,使用token来独立访问openapi + type: string + x-go-name: Token + type: + description: apikey的类型,[system/user] + type: string + x-go-name: Type + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + userId: + description: 所属用户uuid + type: string + x-go-name: UserID + required: + - apiKeyId + - name + - readOnly + - token + - type + - userId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ApikeyId: + properties: + apikeyId: + description: apikey uuid + type: string + x-go-name: ApikeyId + required: + - apikeyId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ApikeyInfo: + properties: + apikey: + $ref: '#/definitions/Apikey' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ApikeyList: + properties: + apikeys: + items: + $ref: '#/definitions/Apikey' + type: array + x-go-name: Apikeys + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + AssociateDeviceDiskSpec: + properties: + diskId: + items: + type: string + type: array + x-go-name: DiskIDs + volumeId: + type: string + x-go-name: VolumeID + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + AssociateDeviceDisksRequest: + properties: + deviceId: + description: device uuid + type: string + x-go-name: DeviceID + deviceTypeId: + description: 设备类型id + type: string + x-go-name: DeviceTypeID + volumes: + description: volumeid和磁盘uuid列表 + items: + $ref: '#/definitions/AssociateDeviceDiskSpec' + type: array + x-go-name: Volumes + required: + - deviceId + - deviceTypeId + - volumes + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + AssociateDeviceTypeRequest: + properties: + deviceTypeIds: + description: 设备类型id,数组,支持多个 + items: + type: string + type: array + x-go-name: DeviceTypeIDs + imageId: + description: 镜像ID, + type: string + x-go-name: ImageID + required: + - imageId + - deviceTypeIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + AssociateImageRequest: + properties: + deviceTypeId: + description: 设备类型id + type: string + x-go-name: DeviceTypeID + imageIds: + description: 镜像ID,数组,支持多个 + items: + type: string + type: array + x-go-name: ImageIDs + required: + - deviceTypeId + - imageIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + AuditLog: + properties: + deviceId: + description: device_id + type: string + x-go-name: DeviceID + failReason: + description: 失败原因 + type: string + x-go-name: FailReason + finishTime: + description: 完成时间 + format: int64 + type: integer + x-go-name: FinishTime + id: + format: int64 + type: integer + x-go-name: ID + instanceId: + description: instance_id + type: string + x-go-name: InstanceID + logid: + description: 日志uuid + type: string + x-go-name: LogID + operateTime: + description: 操作时间 + format: int64 + type: integer + x-go-name: OperateTime + operation: + description: 操作 + type: string + x-go-name: Operation + operationName: + description: 操作名称 + type: string + x-go-name: OperationName + result: + description: 结果 success/fail + type: string + x-go-name: Result + sn: + description: sn + type: string + x-go-name: Sn + userID: + description: 操作人 + type: string + x-go-name: UserID + userName: + description: 操作人 + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + AuditLogList: + properties: + auditLogs: + description: 机型列表 + items: + $ref: '#/definitions/AuditLog' + type: array + x-go-name: AuditLogs + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + AuditLogsType: + properties: + name: + description: name,自动适配中英文 + type: string + x-go-name: Name + operation: + description: 数据库中存储的operation + type: string + x-go-name: Operation + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + CollectDeviceInfoRequest: + properties: + collects: + description: 待采集项 + items: + $ref: '#/definitions/CollectItem' + type: array + x-go-name: Collects + required: + - collects + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CollectItem: + properties: + allowOverride: + description: 可选参数。 传参:True, False 。True表示传入的raid_driver值将覆盖已适配机器的raid_driver + type: boolean + x-go-name: AllowOverride + x-nullable: true + sn: + description: sn + type: string + x-go-name: Sn + required: + - sn + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CommonResponse: + properties: + success: + description: 操作是否成功 [true/false] + type: boolean + x-go-name: Success + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + CreateApikeyRequest: + properties: + name: + description: 秘钥对名称 + type: string + x-go-name: Name + readOnly: + description: 是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法 + format: int8 + type: integer + x-go-name: ReadOnly + type: + description: Token类型, [system/user] + type: string + x-go-name: Type + required: + - name + - readOnly + - type + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateDeviceSpec: + properties: + cabinet: + description: 品牌 + type: string + x-go-name: Cabinet + description: + description: MAC2(eth1) + type: string + x-go-name: Description + gateway: + description: |- + eth1子网掩码 + MaskEth1 string `json:"maskEth1" validate:"omitempty,min=1,max=128"` // eth1子网掩码 + 网关地址 + type: string + x-go-name: Gateway + iloIp: + description: 带外IP + type: string + x-go-name: IloIP + iloPassword: + description: 带外密码 + type: string + x-go-name: IloPassword + iloUser: + description: 带外账号 + type: string + x-go-name: IloUser + instanceId: + type: string + x-go-name: InstanceID + mac1: + description: MAC1(eth0) + type: string + x-go-name: Mac1 + manageStatus: + description: 设备状态,默认已入库 + type: string + x-go-name: ManageStatus + mask: + description: |- + 网口交换机IP + SwitchIP string `json:"switchIp"` // 网口交换机IP + 子网掩码 + type: string + x-go-name: Mask + privateIpv4: + description: 内网IPV4 + type: string + x-go-name: PrivateIPv4 + privateIpv6: + description: |- + eth1内网IPV4(非bond模式时传值) + PrivateEth1IPv4 string `json:"privateEth1Ipv4" validate:"omitempty,min=1,max=128"` // eth1内网IPV4 + 内网IPV6 + type: string + x-go-name: PrivateIPv6 + sn: + description: 设备SN + type: string + x-go-name: Sn + uPosition: + description: 所在U位 + type: string + x-go-name: UPosition + required: + - sn + - cabinet + - uPosition + - iloIp + - mac1 + - description + - mask + - gateway + - privateIpv4 + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateDeviceTypeRaidRequest: + properties: + DeviceTypeId: + type: string + x-go-name: DeviceTypeID + availableValue: + format: int64 + type: integer + x-go-name: AvailableValue + deviceType: + type: string + x-go-name: DeviceType + diskType: + type: string + x-go-name: DiskType + raidId: + type: string + x-go-name: RaidID + systemPartitionCount: + format: int64 + type: integer + x-go-name: SystemPartitionCount + volumeDetail: + type: string + x-go-name: VolumeDetail + volumeType: + type: string + x-go-name: VolumeType + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateDeviceTypeRequest: + properties: + architecture: + description: 体系架构,1-64 + type: string + x-go-name: Architecture + boot_mode: + description: boot模式【UEFI Legacy/BIOS】支持多选,逗号分隔 + type: string + x-go-name: BootMode + cpuAmount: + description: cpu数量1,10000 + format: int64 + type: integer + x-go-name: CPUAmount + cpuCores: + description: 单个cpu内核数1,10000 + format: int64 + type: integer + x-go-name: CPUCores + cpuFrequency: + description: cpu频率(G)1-64 + type: string + x-go-name: CPUFrequency + cpuManufacturer: + description: cpu厂商1-64 + type: string + x-go-name: CPUManufacturer + cpuModel: + description: cpu处理器型号1-64 + type: string + x-go-name: CPUModel + cpuSpec: + description: CPU 预置规格 + type: string + x-go-name: CpuSpec + description: + description: 描述0-256 + type: string + x-go-name: Description + deviceSeries: + description: 机型类型,如computer storage gpu other + type: string + x-go-name: DeviceSeries + deviceType: + description: 机型规格1-64 + type: string + x-go-name: DeviceType + gpuAmount: + description: gpu数量0-1000 + format: int64 + type: integer + x-go-name: GpuAmount + gpuManufacturer: + description: gpu品牌0-64 + type: string + x-go-name: GpuManufacturer + gpuModel: + description: gpu型号0-64 + type: string + x-go-name: GpuModel + height: + description: 【高度(U)】:显示机型高度 2,4 + format: int64 + type: integer + x-go-name: Height + idcId: + description: 机房id + type: string + x-go-name: IDcID + interfaceMode: + description: '【网口模式】【网络设置】: bond,dual,single' + type: string + x-go-name: InterfaceMode + isNeedRaid: + description: 阵列卡是否需要配置 1 需要配置 2无需配置 + type: string + x-go-name: IsNeedRaid + memAmount: + description: 内存数量1-10000 + format: int64 + type: integer + x-go-name: MemAmount + memFrequency: + description: 内存主频(MHz)1-10000 + format: int64 + type: integer + x-go-name: MemFrequency + memSize: + description: 单个内存大小1,10000(GB) + format: int64 + type: integer + x-go-name: MemSize + memSpec: + description: 内存 预置规格 + type: string + x-go-name: MemSpec + memType: + description: 内存接口(DDR DDR2 DDR3 DDR4 DDR5) + type: string + x-go-name: MemType + name: + description: 机型名称1-64 + type: string + x-go-name: Name + nicAmount: + description: 网卡数量1-10000 + format: int64 + type: integer + x-go-name: NicAmount + nicRate: + description: 网卡传输速率(GE) 1-10000 + format: int64 + type: integer + x-go-name: NicRate + volumes: + description: 卷管理 + items: + $ref: '#/definitions/VolumeItem' + type: array + x-go-name: Volumes + required: + - idcId + - name + - deviceType + - deviceSeries + - architecture + - height + - cpuAmount + - cpuCores + - cpuManufacturer + - cpuModel + - cpuFrequency + - memType + - memSize + - memAmount + - memFrequency + - nicAmount + - interfaceMode + - nicRate + - cpuSpec + - memSpec + - volumes + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateDevicesRequest: + properties: + devices: + description: 机型uuid, 上传创建设备时不绑定机型,上架时才绑定机型 20240517 minping + items: + $ref: '#/definitions/CreateDeviceSpec' + type: array + x-go-name: Devices + idcId: + description: 机房uuid + type: string + x-go-name: IDcID + required: + - idcId + - devices + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateIdcRequest: + properties: + address: + description: 机房地址 0-256 + type: string + x-go-name: Address + iloPassword: + description: 带外密码 0-64 + type: string + x-go-name: IloPassword + iloUser: + description: 带外用户名 0-64 + type: string + x-go-name: IloUser + level: + description: 机房等级 1-64 + type: string + x-go-name: Level + name: + description: 机房名称 1-64 + type: string + x-go-name: Name + nameEn: + description: 机房英文名称 1-64 + type: string + x-go-name: NameEn + shortname: + description: 机房缩写 1-64 + type: string + x-go-name: Shortname + switchPassword1: + description: 交换机密码1 0-64 + type: string + x-go-name: SwitchPassword1 + switchPassword2: + description: 交换机密码2 0-64 + type: string + x-go-name: SwitchPassword2 + switchUser1: + description: 交换机用户1 0-64 + type: string + x-go-name: SwitchUser1 + switchUser2: + description: 交换机用户2 0-64 + type: string + x-go-name: SwitchUser2 + required: + - name + - nameEn + - shortname + - level + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateImageRequest: + properties: + Version: + description: 版本号 + type: string + architecture: + description: 体系架构 + type: string + x-go-name: Architecture + boot_mode: + description: 引导模式【UEFI Legacy/BIOS】 + type: string + x-go-name: BootMode + dataPartition: + description: 数据分区信息 + type: string + x-go-name: DataPartition + description: + description: 描述 + type: string + x-go-name: Description + filename: + description: 镜像文件名称 + type: string + x-go-name: Filename + format: + description: 镜像文件类型 + type: string + x-go-name: Format + hash: + description: 文件hash值 + type: string + x-go-name: Hash + imageName: + description: 镜像名称 + type: string + x-go-name: ImageName + osType: + description: 操作系统平台 + type: string + x-go-name: OsType + source: + description: 镜像类型,预置,自定义 + type: string + x-go-name: Source + systemPartition: + description: 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:50GiB,swap) + type: string + x-go-name: SystemPartition + url: + description: 镜像上传地址 + type: string + x-go-name: Url + required: + - imageName + - architecture + - osType + - Version + - format + - boot_mode + - filename + - url + - hash + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateInstanceRequest: + properties: + boot_mode: + type: string + x-go-name: BootMode + count: + description: 创建数量 + format: int64 + type: integer + x-go-name: Count + description: + description: 描述 + type: string + x-go-name: Description + deviceTypeId: + description: 设备类型ID + type: string + x-go-name: DeviceTypeID + hostname: + description: 主机名称 + type: string + x-go-name: HostName + idcId: + description: 机房ID + type: string + x-go-name: IdcID + imageId: + description: 镜像ID + type: string + x-go-name: ImageID + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + password: + description: 密码 + type: string + x-go-name: Password + projectId: + description: 项目ID + type: string + x-go-name: ProjectID + sshKeyId: + description: 秘钥ID + type: string + x-go-name: SshKeyID + systemPartition: + description: 系统盘分区 + items: + $ref: '#/definitions/Partition' + type: array + x-go-name: SystemPartition + systemVolumeRaidId: + description: 系统盘RAID ID + type: string + x-go-name: SystemVolumeRaidID + required: + - projectId + - idcId + - deviceTypeId + - imageId + - systemVolumeRaidId + - instanceName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateLicenseRequest: + properties: + content: + type: string + x-go-name: Content + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateOSRequest: + properties: + architecture: + description: 体系架构 + type: string + x-go-name: Architecture + bits: + description: 位数 + format: int64 + type: integer + x-go-name: Bits + osName: + description: 操作系统名称 + type: string + x-go-name: OsName + osType: + description: 操作系统平台 + type: string + x-go-name: OsType + osVersion: + description: 操作系统版本 + type: string + x-go-name: OsVersion + sysUser: + description: 系统用户 + type: string + x-go-name: SysUser + required: + - osName + - osType + - architecture + - bits + - osVersion + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateProjectRequest: + properties: + isDefault: + description: 是否作为该用户的默认项目, [0/1], 默认为0 + format: int8 + type: integer + x-go-name: IsDefault + isSystem: + description: 是否作为系统项目, [0/1], 默认为0 + format: int8 + type: integer + x-go-name: IsSystem + projectName: + description: ProjectName 1~64字符,只支持数字、大小写字母、中英文下划线“_”及中划线“-” + type: string + x-go-name: ProjectName + required: + - projectName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateRaidRequest: + properties: + descriptionEn: + description: raid描述(中文) + type: string + x-go-name: DescriptionEn + descriptionZh: + description: raid描述(英文) + type: string + x-go-name: DescriptionZh + name: + description: raid名称 + type: string + x-go-name: Name + required: + - name + - descriptionEn + - descriptionZh + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateRoleRequest: + properties: + descriptionCn: + description: 角色描述中文名称 + type: string + x-go-name: DescriptionCn + descriptionEn: + description: 角色描述英文名称 + type: string + x-go-name: DescriptionEn + roleNameCn: + description: 角色中文名称 + type: string + x-go-name: RoleNameCn + roleNameEn: + description: 角色英文名称 + type: string + x-go-name: RoleNameEn + required: + - roleNameEn + - roleNameCn + - descriptionEn + - descriptionCn + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateSshkeyRequest: + properties: + key: + description: 公钥内容,格式:^ssh-rsa AAAAB3NzaC1yc2.* + type: string + x-go-name: Key + name: + description: 秘钥名称 + type: string + x-go-name: Name + required: + - name + - key + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + CreateUserRequest: + properties: + defaultProjectId: + description: 用户默认项目uuid + type: string + x-go-name: DefaultProjectID + description: + description: 描述 + type: string + x-go-name: Description + email: + description: 邮箱 + type: string + x-go-name: Email + language: + description: 语言[en_US, zh_CN] + type: string + x-go-name: Language + password: + description: 密码 明文 密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + type: string + x-go-name: Password + phoneNumber: + description: 手机号 + type: string + x-go-name: PhoneNumber + phonePrefix: + description: 国家地区码,如86 + type: string + x-go-name: PhonePrefix + roleId: + description: 角色uuid + type: string + x-go-name: RoleID + timezone: + description: 时区,Asia/Shanghai + type: string + x-go-name: Timezone + userName: + description: 用户名,唯一, 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + type: string + x-go-name: UserName + required: + - roleId + - userName + - password + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + DataEveryMetric: + properties: + data: + items: + $ref: '#/definitions/MonitorDataItem' + type: array + x-go-name: Data + query: + $ref: '#/definitions/MonitorDataQuery' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeleteAlertRequest: + properties: + alertId: + description: 告警id + type: string + x-go-name: AlertId + required: + - alertId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + DeleteDeviceTypeRaidRequest: + properties: + deviceType: + type: string + x-go-name: DeviceType + raidId: + type: string + x-go-name: RaidId + volumeDetail: + type: string + x-go-name: VolumeDetail + volumeType: + type: string + x-go-name: VolumeType + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + DeleteInstancesRequest: + description: 批量删除实例 + properties: + instance_ids: + description: 实例id列表 + items: + type: string + type: array + x-go-name: InstanceIDs + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + DeleteMessagesRequest: + properties: + messageIds: + items: + type: string + type: array + x-go-name: MessageIds + required: + - messageIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + DeleteRuleRequest: + properties: + ruleId: + description: 规则id + type: string + x-go-name: RuleId + required: + - ruleId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + Device: + properties: + Enclosure2: + description: 系统盘2背板号 + type: string + adapterId: + description: adapter_id + format: int64 + type: integer + x-go-name: AdapterID + architecture: + description: 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + type: string + x-go-name: Architecture + brand: + description: 品牌 + type: string + x-go-name: Brand + cabinet: + description: 机柜编码 + type: string + x-go-name: Cabinet + collectFailReason: + type: string + x-go-name: CollectFailReason + collectStatus: + description: '"1"表示采集成功,"2"表示未采集,3表示采集中,4表示采集失败' + type: string + x-go-name: CollectStatus + cpuAmount: + description: cpu数量 + format: int64 + type: integer + x-go-name: CPUAmount + cpuCores: + description: 单个cpu内核数 + format: int64 + type: integer + x-go-name: CPUCores + cpuFrequency: + description: cpu频率(G) + type: string + x-go-name: CPUFrequency + cpuInfo: + description: 拼装信息 + type: string + x-go-name: CpuInfo + cpuManufacturer: + description: cpu厂商 + type: string + x-go-name: CPUManufacturer + cpuModel: + description: cpu处理器型号 + type: string + x-go-name: CPUModel + cpuRoads: + description: 单个cpu路数 + format: int8 + type: integer + x-go-name: CPURoads + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + dataVolumeAmount: + description: 数据盘数量 + format: int64 + type: integer + x-go-name: DataVolumeAmount + dataVolumeInterfaceType: + description: 数据盘接口类型(SATA,SAS,NVME) + type: string + x-go-name: DataVolumeInterfaceType + dataVolumeSize: + description: 数据盘单盘大小 + format: int64 + type: integer + x-go-name: DataVolumeSize + dataVolumeType: + description: 数据盘类型(SSD,HDD) + type: string + x-go-name: DataVolumeType + description: + description: 描述 + type: string + x-go-name: Description + deviceId: + description: 设备uuid + type: string + x-go-name: DeviceID + deviceSeries: + description: 计算型,存储型 + type: string + x-go-name: DeviceSeries + deviceSeriesName: + description: 计算型,存储型 + type: string + x-go-name: DeviceSeriesName + deviceType: + description: 型号,机型规格cps.normal + type: string + x-go-name: DeviceType + deviceTypeId: + description: 机型uuid + type: string + x-go-name: DeviceTypeID + deviceTypeName: + description: 机型名称 + type: string + x-go-name: DeviceTypeName + dvInfo: + type: string + x-go-name: DvInfo + enclosure1: + description: 添加到disk表, 系统盘1背板号 + type: string + x-go-name: Enclosure1 + eth1Mask: + description: ETH1子网掩码 + type: string + x-go-name: Eth1Mask + gateway: + description: 网关地址 + type: string + x-go-name: Gateway + gpuAmount: + description: gpu数量 + format: int64 + type: integer + x-go-name: GpuAmount + gpuInfo: + type: string + x-go-name: GpuInfo + gpuManufacturer: + description: gpu厂商 + type: string + x-go-name: GpuManufacturer + gpuModel: + description: gpu处理器型号 + type: string + x-go-name: GpuModel + id: + description: 设备ID编号 + format: int64 + type: integer + x-go-name: ID + idcId: + description: 机房uuid + type: string + x-go-name: IdcID + idcName: + description: 机房名称 + type: string + x-go-name: IdcName + idcNameEn: + description: idcname + type: string + x-go-name: IDcNameEn + iloIp: + description: 带外管理IP + type: string + x-go-name: IloIP + iloPassword: + description: 带外账号密码 + type: string + x-go-name: IloPassword + iloUser: + description: 带外账号 + type: string + x-go-name: IloUser + imageName: + description: 实例镜像名称 + type: string + x-go-name: ImageName + instanceCreatedTime: + description: 实例创建时间 + type: string + x-go-name: InstanceCreatedTime + instanceDescription: + description: 实例描述 + type: string + x-go-name: InstanceDescription + instanceId: + description: 实例id + type: string + x-go-name: InstanceID + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + instanceReason: + description: 实例失败原因 + type: string + x-go-name: InstanceReason + instanceStatus: + description: 实例状态 + type: string + x-go-name: InstanceStatus + instanceStatusName: + description: 实例状态 + type: string + x-go-name: InstanceStatusName + interfaceMode: + description: '【网口模式】【网络设置】: bond单网口,dual双网口' + type: string + x-go-name: InterfaceMode + isNeedRaid: + type: string + x-go-name: IsNeedRaid + locked: + description: 实例是否锁定 锁定locked 未锁定unlocked + type: string + x-go-name: Locked + mac1: + description: MAC1(eth0) + type: string + x-go-name: Mac1 + mac2: + description: MAC2(eth2) + type: string + x-go-name: Mac2 + manageStatus: + description: '设备状态: 未装机,已装机' + type: string + x-go-name: ManageStatus + manageStatusName: + description: '设备状态: 未装机,已装机' + type: string + x-go-name: ManageStatusName + mask: + description: 子网掩码 + type: string + x-go-name: Mask + memAmount: + description: 内存数量 + format: int64 + type: integer + x-go-name: MemAmount + memFrequency: + description: 内存主频(MHz) + format: int64 + type: integer + x-go-name: MemFrequency + memInfo: + type: string + x-go-name: MemInfo + memSize: + description: 单个内存大小(GB) + format: int64 + type: integer + x-go-name: MemSize + memType: + description: 内存接口(如DDR3,DDR4) + type: string + x-go-name: MemType + model: + description: 型号 + type: string + x-go-name: Model + nicAmount: + description: 网卡数量 + format: int64 + type: integer + x-go-name: NicAmount + nicInfo: + type: string + x-go-name: NicInfo + nicRate: + description: 网卡传输速率(GE) + format: int64 + type: integer + x-go-name: NicRate + privateEth1Ipv4: + description: eth1内网IPV4 + type: string + x-go-name: PrivateEth1IPv4 + privateEth1Ipv6: + description: eth1内网IPV6 + type: string + x-go-name: PrivateEth1IPv6 + privateIpv4: + description: 内网IPV4 + type: string + x-go-name: PrivateIPv4 + privateIpv6: + description: 内网IPV6 + type: string + x-go-name: PrivateIPv6 + raidDriver: + description: raid工具:(megacli64等) + type: string + x-go-name: RaidDriver + reason: + description: 设备状态变更失败原因 + type: string + x-go-name: Reason + slot1: + description: 系统盘1槽位 + format: int64 + type: integer + x-go-name: Slot1 + slot2: + description: 系统盘2槽位 + format: int64 + type: integer + x-go-name: Slot2 + sn: + description: 设备SN + type: string + x-go-name: Sn + svInfo: + type: string + x-go-name: SvInfo + switchIp: + description: 网口交换机IP + type: string + x-go-name: SwitchIP + switchIp1: + description: 交换机1ip + type: string + x-go-name: SwitchIP1 + switchIp2: + description: 交换机2ip + type: string + x-go-name: SwitchIP2 + switchPassword1: + description: 交换机1登录密码 + type: string + x-go-name: SwitchPassword1 + switchPassword2: + description: 交换机2登录密码 + type: string + x-go-name: SwitchPassword2 + switchPort1: + description: 交换机1port + type: string + x-go-name: SwitchPort1 + switchPort2: + description: 交换机2port + type: string + x-go-name: SwitchPort2 + switchUser1: + description: 交换机1登录账号,如果为空,取所在机房的值 + type: string + x-go-name: SwitchUser1 + switchUser2: + description: 交换机2登录账号,如果为空,取所在机房的值 + type: string + x-go-name: SwitchUser2 + systemVolumeAmount: + description: 系统盘数量 + format: int64 + type: integer + x-go-name: SystemVolumeAmount + systemVolumeInterfaceType: + description: 系统盘接口类型(SATA,SAS,NVME) + type: string + x-go-name: SystemVolumeInterfaceType + systemVolumeSize: + description: 系统盘单盘大小 + format: int64 + type: integer + x-go-name: SystemVolumeSize + systemVolumeType: + description: 系统盘类型(SSD,HDD) + type: string + x-go-name: SystemVolumeType + uPosition: + description: U位 + type: string + x-go-name: UPosition + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + userId: + description: 实例归属用户uuid + type: string + x-go-name: UserId + userName: + description: 实例归属用户名称 + type: string + x-go-name: UserName + required: + - idcId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeviceAssociateDeviceTypeRequest: + properties: + deviceId: + description: 设备ID + type: string + x-go-name: DeviceID + deviceTypeId: + description: 设备类型id + type: string + x-go-name: DeviceTypeID + required: + - deviceTypeId + - deviceId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + DeviceDisks: + properties: + disks: + items: + $ref: '#/definitions/Disk' + type: array + x-go-name: Disks + panfu: + items: + $ref: '#/definitions/Disk' + type: array + x-go-name: Panfu + volumes: + items: + $ref: '#/definitions/VolumeIt' + type: array + x-go-name: Volumes + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeviceInfo: + properties: + device: + $ref: '#/definitions/Device' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeviceList: + properties: + devices: + description: 设备列表 + items: + $ref: '#/definitions/Device' + type: array + x-go-name: Devices + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeviceStock: + properties: + stocks: + description: 库存量 + format: int64 + type: integer + x-go-name: Stocks + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeviceType: + properties: + architecture: + description: 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + type: string + x-go-name: Architecture + boot_mode: + description: boot模式 + type: string + x-go-name: BootMode + cpuAmount: + description: cpu数量 + format: int64 + type: integer + x-go-name: CPUAmount + cpuCores: + description: 单个cpu内核数 + format: int64 + type: integer + x-go-name: CPUCores + cpuFrequency: + description: cpu频率(G) + type: string + x-go-name: CPUFrequency + cpuInfo: + description: 拼装信息 + type: string + x-go-name: CpuInfo + cpuManufacturer: + description: cpu厂商 + type: string + x-go-name: CPUManufacturer + cpuModel: + description: cpu处理器型号 + type: string + x-go-name: CPUModel + cpuSpec: + description: CPU 规格,预置还是其它 + type: string + x-go-name: CpuSpec + createdBy: + description: |- + 数据盘类型(SSD,HDD) + DataVolumeType string `json:"dataVolumeType"` + 数据盘接口类型(SATA,SAS,NVME) + DataVolumeInterfaceType string `json:"dataVolumeInterfaceType"` + 数据盘单盘大小 + DataVolumeSize int `json:"dataVolumeSize"` + 数据盘单位(GB,TB) + DataVolumeUnit string `json:"dataVolumeUnit"` + 数据盘数量 + DataVolumeAmount int `json:"dataVolumeAmount"` + 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + description: + description: 描述 + type: string + x-go-name: Description + deviceCount: + format: int64 + type: integer + x-go-name: DeviceCount + deviceSeries: + description: 机型类型,如计算型,存储型 + type: string + x-go-name: DeviceSeries + deviceSeriesName: + description: 机型类型,如计算型,存储型 + type: string + x-go-name: DeviceSeriesName + deviceType: + description: 机型规格, cps.c.normal + type: string + x-go-name: DeviceType + deviceTypeId: + description: 机型uuid + type: string + x-go-name: DeviceTypeID + dvInfo: + type: string + x-go-name: DvInfo + gpuAmount: + description: gpu数量 + format: int64 + type: integer + x-go-name: GpuAmount + gpuInfo: + type: string + x-go-name: GpuInfo + gpuManufacturer: + description: gpu厂商 + type: string + x-go-name: GpuManufacturer + gpuModel: + description: gpu处理器型号 + type: string + x-go-name: GpuModel + height: + description: 显示机型高度 + format: int64 + type: integer + x-go-name: Height + id: + format: int64 + type: integer + x-go-name: ID + idcId: + description: 机房uuid + type: string + x-go-name: IDcID + idcName: + description: 机房名称 + type: string + x-go-name: IDcName + idcNameEn: + description: 机房名称 + type: string + x-go-name: IDcNameEn + instanceCount: + format: int64 + type: integer + x-go-name: InstanceCount + instanceStatus: + items: + type: string + type: array + x-go-name: InstanceStatus + interfaceMode: + description: bond单网口,dual双网口 + type: string + x-go-name: InterfaceMode + isNeedRaid: + description: 阵列卡是否需要配置 + type: string + x-go-name: IsNeedRaid + memAmount: + description: 内存数量 + format: int64 + type: integer + x-go-name: MemAmount + memFrequency: + description: 内存主频(MHz) + format: int64 + type: integer + x-go-name: MemFrequency + memInfo: + type: string + x-go-name: MemInfo + memSize: + description: 单个内存大小(GB) + format: int64 + type: integer + x-go-name: MemSize + memSpec: + description: 内存 规格,预置还是其它 + type: string + x-go-name: MemSpec + memType: + description: 内存接口(如DDR3,DDR4) + type: string + x-go-name: MemType + name: + description: 机型名称,如计算效能型,标准计算型 + type: string + x-go-name: Name + nicAmount: + description: 网卡数量 + format: int64 + type: integer + x-go-name: NicAmount + nicInfo: + type: string + x-go-name: NicInfo + nicRate: + description: 网卡传输速率(GE) + format: int64 + type: integer + x-go-name: NicRate + raid: + description: 系统盘raid + type: string + x-go-name: Raid + raidCan: + description: |- + 系统盘类型(SSD,HDD) + SystemVolumeType string `json:"systemVolumeType"` + 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeInterfaceType string `json:"systemVolumeInterfaceType"` + 系统盘单盘大小 + SystemVolumeSize int `json:"systemVolumeSize"` + 系统盘单位(GB,TB) + SystemVolumeUnit string `json:"systemVolumeUnit"` + 系统盘数量 + SystemVolumeAmount int `json:"systemVolumeAmount"`*/ + 是否做raid,[RAID/NORAID] + type: string + x-go-name: RaidCan + stockAvailable: + description: StockAvailable 可用库存 + format: int64 + type: integer + x-go-name: StockAvailable + svInfo: + type: string + x-go-name: SvInfo + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + volumes: + items: + $ref: '#/definitions/Volume' + type: array + x-go-name: Volumes + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeviceTypeId: + properties: + deviceTypeId: + description: 机型uuid + type: string + x-go-name: DeviceTypeId + required: + - deviceTypeId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeviceTypeInfo: + properties: + deviceType: + $ref: '#/definitions/DeviceType' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DeviceTypeList: + properties: + deviceTypes: + description: 机型列表 + items: + $ref: '#/definitions/DeviceType' + type: array + x-go-name: DeviceTypes + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DisableRuleRequest: + properties: + ruleId: + description: 规则id + type: string + x-go-name: RuleId + required: + - ruleId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + Disk: + properties: + adapterId: + format: int64 + type: integer + x-go-name: AdapterID + createdBy: + type: string + x-go-name: CreatedBy + createdTime: + format: int64 + type: integer + x-go-name: CreatedTime + deletedTime: + format: int64 + type: integer + x-go-name: DeletedTime + deviceId: + type: string + x-go-name: DeviceID + devicePath: + type: string + x-go-name: DevicePath + diskId: + type: string + x-go-name: DiskId + diskType: + description: 磁盘类型:system,data + type: string + x-go-name: DiskType + enclosure: + type: string + x-go-name: Enclosure + index: + format: int64 + type: integer + x-go-name: Index + isDel: + format: int8 + type: integer + x-go-name: IsDel + mediaType: + type: string + x-go-name: MediaType + name: + type: string + x-go-name: Name + pdType: + type: string + x-go-name: PdType + selected: + description: 是否选中 + type: boolean + x-go-name: Selected + serialNumber: + type: string + x-go-name: SerialNumber + size: + type: string + x-go-name: Size + sizeUnit: + type: string + x-go-name: SizeUnit + slot: + format: int64 + type: integer + x-go-name: Slot + types: + description: control/mvme/panfu + type: string + x-go-name: Types + updatedBy: + type: string + x-go-name: UpdatedBy + updatedTime: + format: int64 + type: integer + x-go-name: UpdatedTime + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + DissociatedImageRequest: + properties: + deviceTypeId: + description: 设备类型id + type: string + x-go-name: DeviceTypeID + imageId: + description: 镜像ID + type: string + x-go-name: ImageID + required: + - deviceTypeId + - imageId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + EditRuleRequest: + properties: + deviceTag: + description: 盘符、挂载点、网口列表 + type: string + x-go-name: DeviceTag + dimension: + description: 维度 [instance、disk、mountpoint、nic] + type: string + x-go-name: Dimension + instanceIds: + description: 实例id列表 + items: + type: string + type: array + x-go-name: InstanceIds + noticeOption: + $ref: '#/definitions/RuleNotice' + resource: + description: 资源类型,目前只支持instance + type: string + x-go-name: Resource + ruleId: + description: 规则id + type: string + x-go-name: RuleId + ruleName: + description: 规则名称 + type: string + x-go-name: RuleName + triggerOption: + description: 触发条件 + items: + $ref: '#/definitions/RuleTrigger' + type: array + x-go-name: TriggerOption + required: + - ruleId + - ruleName + - dimension + - resource + - triggerOption + - noticeOption + - instanceIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + EnableRuleRequest: + properties: + ruleId: + description: 规则id + type: string + x-go-name: RuleId + required: + - ruleId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ErrorResponse: + properties: + code: + description: 错误码 + format: int64 + type: integer + x-go-name: Code + message: + description: 错误信息 + type: string + x-go-name: Message + status: + description: 错误状态 + type: string + x-go-name: Status + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/controllers + HasUnreadMessage: + properties: + hasUnread: + type: boolean + x-go-name: HasUnread + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Idc: + properties: + address: + description: 机房地址 + type: string + x-go-name: Address + createTime: + description: 创建时间 + type: string + x-go-name: CreateTime + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + id: + format: int64 + type: integer + x-go-name: ID + idcId: + description: 机房uuid + type: string + x-go-name: IDcID + iloPassword: + description: 机房公用带外管理password + type: string + x-go-name: IloPassword + iloUser: + description: 机房公用带外管理user + type: string + x-go-name: IloUser + level: + description: 机房等级 + type: string + x-go-name: Level + name: + description: 机房名称 + type: string + x-go-name: Name + nameEn: + description: 机房名称en + type: string + x-go-name: NameEn + shortname: + description: shortname + type: string + x-go-name: Shortname + switchPassword1: + description: 交换机密码1 + type: string + x-go-name: SwitchPassword1 + switchPassword2: + description: 交换机密码2 + type: string + x-go-name: SwitchPassword2 + switchUser1: + description: 交换机用户名1 + type: string + x-go-name: SwitchUser1 + switchUser2: + description: 交换机用户名2 + type: string + x-go-name: SwitchUser2 + updateTime: + description: 修改时间 + type: string + x-go-name: UpdateTime + updatedBy: + description: 修改用户 + type: string + x-go-name: UpdatedBy + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + IdcID: + properties: + idcId: + description: 机房id + type: string + x-go-name: IdcID + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + IdcInfo: + properties: + idc: + $ref: '#/definitions/Idc' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + IdcList: + properties: + idcs: + description: 机房列表 + items: + $ref: '#/definitions/Idc' + type: array + x-go-name: Idcs + pageNumber: + description: 页数 + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + description: 页大小 + format: int64 + type: integer + x-go-name: PageSize + totalCount: + description: 总条数 + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Image: + properties: + architecture: + description: 架构:x86/x64/i386/ + type: string + x-go-name: Architecture + bootMode: + description: boot模式 + type: string + x-go-name: BootMode + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + dataPartition: + description: 数据分区信息 + type: string + x-go-name: DataPartition + description: + description: 描述 + type: string + x-go-name: Description + deviceTypeNum: + description: 绑定了机型数量 + format: int64 + type: integer + x-go-name: DeviceTypeNum + filename: + description: 镜像文件名称 + type: string + x-go-name: Filename + format: + description: 镜像格式(qcow2、tar) + type: string + x-go-name: Format + hash: + description: 镜像校验码 + type: string + x-go-name: Hash + id: + format: uint64 + type: integer + x-go-name: ID + imageId: + description: 镜像uuid + type: string + x-go-name: ImageID + imageName: + description: 镜像名称 + type: string + x-go-name: ImageName + isBind: + description: 是否绑定了某个机型 + type: boolean + x-go-name: IsBind + osId: + description: 源os uuid + type: string + x-go-name: OsID + osName: + description: CentOS 7.2 64-bit + type: string + x-go-name: OsName + osType: + description: 操作系统分类:linux/windows + type: string + x-go-name: OsType + osVersion: + description: 操作系统版本 + type: string + x-go-name: OsVersion + source: + description: 镜像来源(common通用、customize定制、user_defined自定义) + type: string + x-go-name: Source + sourceName: + description: 镜像来源(common通用、customize定制、user_defined自定义) + type: string + x-go-name: SourceName + systemPartition: + description: 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + type: string + x-go-name: SystemPartition + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + url: + description: 镜像源路径 + type: string + x-go-name: URL + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ImageId: + properties: + imageId: + description: 镜像uuid + type: string + x-go-name: ImageId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ImageInfo: + properties: + image: + $ref: '#/definitions/Image' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ImageList: + properties: + images: + description: 镜像实体列表 + items: + $ref: '#/definitions/Image' + type: array + x-go-name: Images + pageNumber: + description: 页数 + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + description: 页大小 + format: int64 + type: integer + x-go-name: PageSize + totalCount: + description: 总条数 + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Instance: + properties: + DataVolumeRaidName: + description: 数据盘raid名称 + type: string + cpuAmount: + description: cpu数量 + format: int64 + type: integer + x-go-name: CPUAmount + cpuCores: + description: 单个cpu内核数 + format: int64 + type: integer + x-go-name: CPUCores + cpuFrequency: + description: cpu频率(GHz) + type: string + x-go-name: CPUFrequency + cpuManufacturer: + description: cpu厂商 + type: string + x-go-name: CPUManufacturer + cpuModel: + description: cpu处理器型号 + type: string + x-go-name: CPUModel + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + dataVolumeAmount: + description: 数据盘数量 + format: int64 + type: integer + x-go-name: DataVolumeAmount + dataVolumeInterfaceType: + description: 数据盘接口类型(SATA,SAS,NVME) + type: string + x-go-name: DataVolumeInterfaceType + dataVolumeRaidId: + description: 数据盘raidId + type: string + x-go-name: DataVolumeRaidID + dataVolumeSize: + description: 数据盘单盘大小 + format: int64 + type: integer + x-go-name: DataVolumeSize + dataVolumeType: + description: 数据盘类型(SSD,HDD) + type: string + x-go-name: DataVolumeType + dataVolumeUnit: + description: 系统盘单位 + type: string + x-go-name: DataVolumeUnit + description: + description: 实例描述 + type: string + x-go-name: Description + deviceId: + description: 设备uuid + type: string + x-go-name: DeviceID + deviceSeries: + description: 机型类型,如computer + type: string + x-go-name: DeviceSeries + deviceSeriesName: + description: 机型类型,如计算型,存储型 + type: string + x-go-name: DeviceSeriesName + deviceType: + description: 机型规格, cps.c.normal + type: string + x-go-name: DeviceType + deviceTypeId: + description: 机型uuid + type: string + x-go-name: DeviceTypeID + deviceTypeName: + description: 机型名称,如计算效能型,标准计算型 + type: string + x-go-name: DeviceTypeName + gpuAmount: + description: gpu数量 + format: int64 + type: integer + x-go-name: GpuAmount + gpuManufacturer: + description: gpu厂商 + type: string + x-go-name: GpuManufacturer + gpuModel: + description: gpu处理器型号 + type: string + x-go-name: GpuModel + hostname: + description: 主机名 + type: string + x-go-name: Hostname + idcId: + description: 机房uuid + type: string + x-go-name: IDcID + idcName: + description: 机房名称 + type: string + x-go-name: IdcName + iloIp: + description: 带外管理IP + type: string + x-go-name: IloIP + imageId: + description: 镜像uuid + type: string + x-go-name: ImageID + imageName: + description: 镜像名称 + type: string + x-go-name: ImageName + instanceId: + description: 实例uuid + type: string + x-go-name: InstanceID + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + interfaceMode: + description: '【网口模式】【网络设置】: bond单网口,dual双网口' + type: string + x-go-name: InterfaceMode + locked: + description: 是否锁定解锁锁定:locked,解锁unlocked + type: string + x-go-name: Locked + lockedName: + description: 是否锁定解锁锁定:已解锁,已锁定 + type: string + x-go-name: LockedName + memAmount: + description: 内存数量 + format: int64 + type: integer + x-go-name: MemAmount + memFrequency: + description: 内存主频(MHz) + format: int64 + type: integer + x-go-name: MemFrequency + memSize: + description: 单个内存大小(GB) + format: int64 + type: integer + x-go-name: MemSize + memType: + description: 内存接口(如DDR3,DDR4) + type: string + x-go-name: MemType + nicAmount: + description: 网卡数量 + format: int64 + type: integer + x-go-name: NicAmount + nicRate: + description: 网卡传输速率(GE) + format: int64 + type: integer + x-go-name: NicRate + privateIpv4: + description: 内网IPV4 + type: string + x-go-name: PrivateIPv4 + privateIpv6: + description: 内网IPV6 + type: string + x-go-name: PrivateIPv6 + projectId: + description: 实例所属项目UUID + type: string + x-go-name: ProjectID + raidCan: + description: 系统盘raid配置 + type: string + x-go-name: RaidCan + reason: + description: 实例错误状态时的错误原因 + type: string + x-go-name: Reason + sn: + description: 设备SN + type: string + x-go-name: Sn + status: + description: 运行状态 + type: string + x-go-name: Status + statusName: + description: 运行状态中文名字 + type: string + x-go-name: StatusName + systemVolumeAmount: + description: 系统盘数量 + format: int64 + type: integer + x-go-name: SystemVolumeAmount + systemVolumeInterfaceType: + description: 系统盘接口类型(SATA,SAS,NVME) + type: string + x-go-name: SystemVolumeInterfaceType + systemVolumeRaidId: + description: 系统盘raidId + type: string + x-go-name: SystemVolumeRaidID + systemVolumeRaidName: + description: 系统盘raid名称 + type: string + x-go-name: SystemVolumeRaidName + systemVolumeSize: + description: 系统盘单盘大小 + format: int64 + type: integer + x-go-name: SystemVolumeSize + systemVolumeType: + description: 系统盘类型(SSD,HDD) + type: string + x-go-name: SystemVolumeType + systemVolumeUnit: + description: 系统盘单位 + type: string + x-go-name: SystemVolumeUnit + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + userId: + description: 实例所属用户UUID + type: string + x-go-name: UserID + volumeRaid: + description: 实例的volume和raid信息 + items: + $ref: '#/definitions/InstanceVolumeRaid' + type: array + x-go-name: InstanceVolumeRaids + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + InstanceIds: + properties: + instanceIds: + description: instanceId 列表 + items: + type: string + type: array + x-go-name: InstanceIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + InstanceInfo: + properties: + instance: + $ref: '#/definitions/Instance' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + InstanceList: + properties: + instances: + description: instance实体数组 + items: + $ref: '#/definitions/Instance' + type: array + x-go-name: Instances + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + InstanceVolumeRaid: + properties: + raid: + $ref: '#/definitions/Raid' + volume: + $ref: '#/definitions/Volume' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + InstancesSshkeyInfoResponse: + properties: + instanceIds: + description: 实例Id列表 + items: + type: string + type: array + x-go-name: InstanceIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + LicenseContent: + properties: + end_time: + format: int64 + type: integer + x-go-name: EndTime + hardwareinfo: + type: string + x-go-name: HardWare + license_name: + type: string + x-go-name: LicenseName + license_type: + type: string + x-go-name: LicenseType + modelList: + items: + $ref: '#/definitions/ModuleItem' + type: array + x-go-name: ModelList + models: + items: + type: string + type: array + x-go-name: Models + nodes_num: + format: int64 + type: integer + x-go-name: NodesNum + start_time: + format: int64 + type: integer + x-go-name: StartTime + used_nodes_num: + format: int64 + type: integer + x-go-name: UsedNodesNum + version: + type: string + x-go-name: Version + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + LicenseToken: + properties: + msg: + type: string + x-go-name: Msg + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Mail: + properties: + admin_addr: + description: 管理员邮箱 + type: string + x-go-name: AdminAddr + admin_pass: + description: 管理员邮箱密码 + type: string + x-go-name: AdminPass + is_pass: + description: 邮件功能是否验证过正常。1表示正常,其他表示异常 + type: string + x-go-name: IsPass + is_push: + description: 是否推送邮件告警,0不推送,1推送 + type: string + x-go-name: IsPush + server_addr: + description: 邮件服务器地址 + type: string + x-go-name: ServerAddr + server_port: + description: 邮件服务器端口 + type: string + x-go-name: ServerPort + to: + description: 收件人邮箱 + type: string + x-go-name: To + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + MailDialRequest: + properties: + admin_addr: + description: 管理员邮箱 + type: string + x-go-name: AdminAddr + admin_pass: + description: 管理员邮箱密码 + type: string + x-go-name: AdminPass + server_addr: + description: 邮件服务器地址 + type: string + x-go-name: ServerAddr + server_port: + description: 邮件服务器端口 + type: string + x-go-name: ServerPort + to: + description: 收件人邮箱地址 + type: string + x-go-name: To + required: + - server_addr + - server_port + - admin_addr + - admin_pass + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + Message: + properties: + alert_count: + description: 告警次数,始终为1,带外故障消息专属字段 + format: int64 + type: integer + x-go-name: AlertCount + alert_time: + description: 故障告警时间,带外故障消息专属字段 + format: int64 + type: integer + x-go-name: AlertTime + content: + description: 故障内容,带外故障消息专属字段 + type: string + x-go-name: Content + detail: + description: 详情, 带外监控日志的详情请用content + type: string + x-go-name: Detail + device_id: + type: string + x-go-name: DeviceID + fault_type: + description: 故障类型, 带外故障消息专属字段 + type: string + x-go-name: FaultType + finish_time: + description: 消息时间戳 + format: int64 + type: integer + x-go-name: FinishTime + has_read: + description: 0未读, 1已读 + format: int8 + type: integer + x-go-name: HasRead + idc_id: + description: 独一处的下划线,跟sdk一致 + type: string + x-go-name: IDcID + idc_name: + type: string + x-go-name: IDcName + instance_id: + description: 实例id + type: string + x-go-name: InstanceID + instance_name: + description: 实例name + type: string + x-go-name: InstanceName + is_del: + description: 是否删除0未删除 1已删除 + format: int8 + type: integer + x-go-name: IsDel + license_end_time: + description: 结束时间, 许可证到期消息专属字段 + format: int64 + type: integer + x-go-name: LienseEndTime + license_name: + description: 版本名称, 许可证到期消息专属字段 + type: string + x-go-name: LicenseName + license_number: + description: 版本号, 许可证到期消息专属字段 + type: string + x-go-name: LicenseNumber + license_start_time: + description: 开始时间, 许可证到期消息专属字段 + format: int64 + type: integer + x-go-name: LienseStartTime + logid: + description: 系统原始日志id, 带外故障消息专属字段 + type: string + x-go-name: LogID + message_id: + description: message uuid + type: string + x-go-name: MessageID + message_sub_type: + description: 消息子类型 + type: string + x-go-name: MessageSubType + message_type: + description: 消息类型 + type: string + x-go-name: MessageType + project_id: + type: string + x-go-name: ProjectID + project_name: + type: string + x-go-name: ProjectName + resource_type: + description: 资源类型 实例/设备 + type: string + x-go-name: ResourceType + result: + description: 操作结果 fail/succ + type: string + x-go-name: Result + rule_id: + description: inbond rule uuid + type: string + x-go-name: RuleID + rule_name: + description: inbond rule name + type: string + x-go-name: RuleName + sn: + description: 设备sn + type: string + x-go-name: SN + user_id: + description: user_id + type: string + x-go-name: UserID + user_name: + description: user_name + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + MessageList: + properties: + messages: + items: + $ref: '#/definitions/Message' + type: array + x-go-name: Messages + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + MessageStatistic: + properties: + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + unreadCount: + format: int64 + type: integer + x-go-name: UnreadCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + MessageTypesResp: + additionalProperties: + items: + type: string + type: array + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + MessageWithNextPrev: + properties: + message: + $ref: '#/definitions/Message' + nextMessageId: + type: string + x-go-name: NextMessageId + prevMessageId: + type: string + x-go-name: PrevMessageId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ModifyApikeyRequest: + properties: + name: + description: 秘钥对名称 + type: string + x-go-name: Name + readOnly: + description: 是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法 + format: int8 + type: integer + x-go-name: ReadOnly + required: + - name + - readOnly + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyDeviceTypeRequest: + properties: + architecture: + description: 体系架构,如i386/x86_64/ ARM64(aarch64),默认 x86_64 + type: string + x-go-name: Architecture + x-nullable: true + boot_mode: + description: boot模式【UEFI Legacy/BIOS】支持多选,逗号分隔 + type: string + x-go-name: BootMode + cpuAmount: + description: cpu数量 + format: int64 + type: integer + x-go-name: CPUAmount + x-nullable: true + cpuCores: + description: 单个cpu内核数 + format: int64 + type: integer + x-go-name: CPUCores + x-nullable: true + cpuFrequency: + description: cpu频率(G) + type: string + x-go-name: CPUFrequency + x-nullable: true + cpuManufacturer: + description: cpu厂商 + type: string + x-go-name: CPUManufacturer + x-nullable: true + cpuModel: + description: cpu处理器型号 + type: string + x-go-name: CPUModel + x-nullable: true + cpuSpec: + description: CPU 预置规格 + type: string + x-go-name: CpuSpec + x-nullable: true + dataVolumeAmount: + description: 数据盘数量 + format: int64 + type: integer + x-go-name: DataVolumeAmount + x-nullable: true + dataVolumeInterfaceType: + description: 数据盘接口类型 + type: string + x-go-name: DataVolumeInterfaceType + x-nullable: true + dataVolumeSize: + description: 数据盘单盘大小 + format: int64 + type: integer + x-go-name: DataVolumeSize + x-nullable: true + dataVolumeType: + description: 数据盘类型 + type: string + x-go-name: DataVolumeType + x-nullable: true + dataVolumeUnit: + description: 数据盘单盘大小单位 + type: string + x-go-name: DataVolumeUnit + x-nullable: true + description: + description: 描述 + type: string + x-go-name: Description + x-nullable: true + deviceSeries: + description: 机型类型,如计算型,存储型 + type: string + x-go-name: DeviceSeries + x-nullable: true + deviceType: + description: 机型规格 + type: string + x-go-name: DeviceType + x-nullable: true + gpuAmount: + description: gpu数量 + format: int64 + type: integer + x-go-name: GpuAmount + x-nullable: true + gpuManufacturer: + description: gpu厂商 + type: string + x-go-name: GpuManufacturer + x-nullable: true + gpuModel: + description: gpu处理器型号 + type: string + x-go-name: GpuModel + x-nullable: true + height: + description: 【高度(U)】:显示机型高度 + format: int64 + type: integer + x-go-name: Height + x-nullable: true + idcId: + description: 机房id + type: string + x-go-name: IDcID + x-nullable: true + interfaceMode: + description: '【网口模式】【网络设置】: 单网口,双网口bond,single' + type: string + x-go-name: InterfaceMode + x-nullable: true + isNeedRaid: + description: 阵列卡是否需要配置 1 需要配置 2无需配置 + type: string + x-go-name: IsNeedRaid + x-nullable: true + memAmount: + description: 内存数量 + format: int64 + type: integer + x-go-name: MemAmount + x-nullable: true + memFrequency: + description: 内存主频(MHz) + format: int64 + type: integer + x-go-name: MemFrequency + x-nullable: true + memSize: + description: 单个内存大小(GB) + format: int64 + type: integer + x-go-name: MemSize + x-nullable: true + memSpec: + description: 内存 预置规格 + type: string + x-go-name: MemSpec + x-nullable: true + memType: + description: 内存接口(如DDR3,DDR4) + type: string + x-go-name: MemType + x-nullable: true + name: + description: 机型名称 + type: string + x-go-name: Name + x-nullable: true + nicAmount: + description: 网卡数量 + format: int64 + type: integer + x-go-name: NicAmount + x-nullable: true + nicRate: + description: 网卡传输速率(GE) + format: int64 + type: integer + x-go-name: NicRate + x-nullable: true + raidId: + description: 系统盘raid,支持多选,英文逗号分隔 + type: string + x-go-name: RaidID + x-nullable: true + systemVolumeAmount: + description: 系统盘数量 + format: int64 + type: integer + x-go-name: SystemVolumeAmount + x-nullable: true + systemVolumeInterfaceType: + description: 系统盘接口类型(SATA,SAS,NVME) + type: string + x-go-name: SystemVolumeInterfaceType + x-nullable: true + systemVolumeSize: + description: 系统盘单盘大小 + format: int64 + type: integer + x-go-name: SystemVolumeSize + x-nullable: true + systemVolumeType: + description: 系统盘类型(SSD,HDD) + type: string + x-go-name: SystemVolumeType + x-nullable: true + systemVolumeUnit: + description: 系统盘单盘大小单位 + type: string + x-go-name: SystemVolumeUnit + x-nullable: true + volumes: + description: 卷管理 + items: + $ref: '#/definitions/VolumeItem' + type: array + x-go-name: Volumes + x-nullable: true + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyDevicesRequest: + properties: + description: + description: 修改设备描述 + type: string + x-go-name: Description + x-nullable: true + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyIdcRequest: + properties: + address: + description: 机房地址 0-256 + type: string + x-go-name: Address + x-nullable: true + iloPassword: + description: 带外密码 0-64 + type: string + x-go-name: IloPassword + x-nullable: true + iloUser: + description: 带外用户名 0-64 + type: string + x-go-name: IloUser + x-nullable: true + level: + description: 机房等级 1-64 + type: string + x-go-name: Level + x-nullable: true + name: + description: 机房名称 1-64 + type: string + x-go-name: Name + x-nullable: true + nameEn: + description: 机房英文名称 1-64 + type: string + x-go-name: NameEn + x-nullable: true + shortname: + description: 机房缩写 1-64 + type: string + x-go-name: Shortname + x-nullable: true + switchPassword1: + description: 交换机密码1 0-64 + type: string + x-go-name: SwitchPassword1 + x-nullable: true + switchPassword2: + description: 交换机2密码 0-64 + type: string + x-go-name: SwitchPassword2 + x-nullable: true + switchUser1: + description: 交换机用户1 0-64 + type: string + x-go-name: SwitchUser1 + x-nullable: true + switchUser2: + description: 交换机用户2 0-64 + type: string + x-go-name: SwitchUser2 + x-nullable: true + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyImageRequest: + properties: + description: + description: 修改设备描述 + type: string + x-go-name: Description + x-nullable: true + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyInstanceRequest: + properties: + description: + description: 描述 + type: string + x-go-name: Description + x-nullable: true + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyInstancesRequest: + description: 批量修改实例名称 + properties: + instance_ids: + description: 实例id列表 + items: + type: string + type: array + x-go-name: InstanceIDs + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyLocalUserRequest: + properties: + defaultProjectId: + description: 用户默认项目uuid + type: string + x-go-name: DefaultProjectID + x-nullable: true + email: + description: 邮箱 + type: string + x-go-name: Email + x-nullable: true + language: + description: 语言[en_US, zh_CN] + type: string + x-go-name: Language + x-nullable: true + phoneNumber: + description: 手机号 + type: string + x-go-name: PhoneNumber + x-nullable: true + phonePrefix: + description: 国家地区码,如86 + type: string + x-go-name: PhonePrefix + x-nullable: true + timezone: + description: 时区 Asia/Shanghai + type: string + x-go-name: Timezone + x-nullable: true + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyOSRequest: + properties: + architecture: + description: 体系架构 + type: string + x-go-name: Architecture + bits: + description: 位数 + format: int64 + type: integer + x-go-name: Bits + osName: + description: 操作系统名称 + type: string + x-go-name: OsName + osType: + description: 操作系统平台 + type: string + x-go-name: OsType + osVersion: + description: 操作系统版本 + type: string + x-go-name: OsVersion + sysUser: + description: 系统用户 + type: string + x-go-name: SysUser + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyProjectRequest: + properties: + projectName: + description: 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + type: string + x-go-name: ProjectName + required: + - projectName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyRaidRequest: + properties: + descriptionEn: + description: raid描述(中文) + type: string + x-go-name: DescriptionEn + descriptionZh: + description: raid描述(英文) + type: string + x-go-name: DescriptionZh + name: + description: raid名称 + type: string + x-go-name: Name + required: + - name + - descriptionEn + - descriptionZh + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyRoleRequest: + properties: + descriptionCn: + description: 角色描述中文名称 + type: string + x-go-name: DescriptionCn + descriptionEn: + description: 角色描述英文名称 + type: string + x-go-name: DescriptionEn + roleNameCn: + description: 角色中文名称 + type: string + x-go-name: RoleNameCn + roleNameEn: + description: 角色英文名称 + type: string + x-go-name: RoleNameEn + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifySshkeyRequest: + properties: + name: + description: 秘钥名称 + type: string + x-go-name: Name + x-nullable: true + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyUserPasswordRequest: + properties: + oldPassword: + description: 旧密码,明文 + type: string + x-go-name: OldPassword + password: + description: 新密码 明文,密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + type: string + x-go-name: Password + required: + - oldPassword + - password + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModifyUserRequest: + properties: + description: + description: 描述 + type: string + x-go-name: Description + x-nullable: true + email: + description: 邮箱 + type: string + x-go-name: Email + x-nullable: true + phoneNumber: + description: 手机号 + type: string + x-go-name: PhoneNumber + x-nullable: true + phonePrefix: + description: 国家地区码,如86 + type: string + x-go-name: PhonePrefix + x-nullable: true + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ModuleItem: + properties: + description: + type: string + x-go-name: Description + descriptionEn: + type: string + x-go-name: DescriptionEn + effective: + type: boolean + x-go-name: Effective + id: + format: int64 + type: integer + x-go-name: ID + name: + type: string + x-go-name: Name + nameEn: + type: string + x-go-name: NameEn + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + MonitorDataItem: + properties: + timestamp: + format: int64 + type: integer + x-go-name: Timestamp + value: + type: string + x-go-name: Value + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + MonitorDataQuery: + properties: + endTime: + format: int64 + type: integer + x-go-name: EndTime + func: + additionalProperties: + format: int64 + type: integer + description: 跟赛迪约定,转换单位放这里实现 + type: object + x-go-name: Func + labels: + additionalProperties: + type: string + description: metric都放这里了 + type: object + x-go-name: Labels + sampleMethod: + description: |- + MetricName string `json:"metricName"` + [rate, increase] + type: string + x-go-name: SampleMethod + startTime: + format: int64 + type: integer + x-go-name: StartTime + step: + format: int64 + type: integer + x-go-name: Step + tableName: + description: '[bmp_monitor_counter bmp_monitor_gauge]' + type: string + x-go-name: TableName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + MountDevicesRequest: + properties: + deviceId: + description: 设备uuid + type: string + x-go-name: DeviceID + required: + - deviceId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + Os: + properties: + architecture: + description: 架构:x86/x64/i386/ + type: string + x-go-name: Architecture + bits: + description: 指令宽度:64/32位 + format: int64 + type: integer + x-go-name: Bits + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + deletedTime: + description: 删除时间 + type: string + x-go-name: DeletedTime + id: + description: ID + format: uint64 + type: integer + x-go-name: ID + isDel: + description: 是否删除0未删除 1已删除 + format: int8 + type: integer + x-go-name: IsDel + osId: + description: 操作系统uuid + type: string + x-go-name: OsID + osName: + description: 操作系统名称 + type: string + x-go-name: OsName + osType: + description: 操作系统分类:linux/windows + type: string + x-go-name: OsType + osVersion: + description: 操作系统版本 + type: string + x-go-name: OsVersion + sysUser: + description: 管理员账户 + type: string + x-go-name: SysUser + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + OsId: + properties: + osId: + description: 操作系统uuid + type: string + x-go-name: OsId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + OsInfo: + properties: + os: + $ref: '#/definitions/Os' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + OsList: + properties: + oss: + description: 操作系统列表 + items: + $ref: '#/definitions/Os' + type: array + x-go-name: Oss + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Partition: + description: |- + 镜像默认分区 + [{"format":"swap","point":"swap","size":10240},{"format":"xfs","point":"/","size":51200}] + properties: + format: + description: format,如[swap, xfs] + type: string + x-go-name: FsType + point: + description: point,如[swap, /, /var] + type: string + x-go-name: MountPoint + size: + description: 分区大小, MB为单位 + format: int64 + type: integer + x-go-name: Size + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Project: + properties: + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + instanceCount: + description: 项目下实例数量 + format: int64 + type: integer + x-go-name: InstanceCount + owned: + description: 此项目的共享标志位,1为拥有,2为共享 + format: int64 + type: integer + x-go-name: Owned + projectId: + description: 项目uuid + type: string + x-go-name: ProjectID + projectName: + description: 项目名称 + type: string + x-go-name: ProjectName + shareProjects: + description: 共享 + items: + $ref: '#/definitions/ShareProject' + type: array + x-go-name: ShareProjects + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ProjectId: + properties: + projectId: + description: 项目uuid + type: string + x-go-name: ProjectId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ProjectInfo: + properties: + project: + $ref: '#/definitions/Project' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ProjectList: + properties: + pageNumber: + description: 页数 + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + description: 页大小 + format: int64 + type: integer + x-go-name: PageSize + projects: + description: 项目实体列表 + items: + $ref: '#/definitions/Project' + type: array + x-go-name: Projects + totalCount: + description: 总条数 + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + QueryDeviceTypeImagePartitionResponse: + properties: + dataPartition: + description: 数据盘分区列表 + items: + $ref: '#/definitions/Partition' + type: array + x-go-name: DataPartition + systemPartition: + description: 系统盘分区列表 + items: + $ref: '#/definitions/Partition' + type: array + x-go-name: SystemPartition + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + RDeviceTypeRaid: + properties: + DiskInterfaceType: + description: 磁盘类型:SAS/SATA/SSD/NVME + type: string + availableValue: + description: 可用分区值,单位GB + format: int64 + type: integer + x-go-name: AvailableValue + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + deviceTypeId: + description: 设备类型id + type: string + x-go-name: DeviceTypeID + diskType: + description: 磁盘类型:SAS/SATA/SSD/NVME + type: string + x-go-name: DiskType + raidId: + description: RAID uuid + type: string + x-go-name: RaidID + systemPartitionCount: + description: 系统盘noraid模式真实数量;此模式多块盘只能用一块 + format: int64 + type: integer + x-go-name: SystemPartitionCount + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + volumeDetail: + description: 磁盘详细信息 + type: string + x-go-name: VolumeDetail + volumeType: + description: 磁盘类型 system/data + type: string + x-go-name: VolumeType + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Raid: + properties: + descriptionEn: + description: 中文描述 + type: string + x-go-name: DescriptionEn + descriptionZh: + description: description + type: string + x-go-name: DescriptionZh + name: + description: raid 名称 + type: string + x-go-name: Name + raidId: + description: raid uuid + type: string + x-go-name: RaidID + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + RaidId: + properties: + raidId: + description: raid uuid + type: string + x-go-name: RaidId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + RaidList: + properties: + raids: + description: raid实体列表 + items: + $ref: '#/definitions/Raid' + type: array + x-go-name: Raids + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ReadMessagesRequest: + properties: + messageIds: + items: + type: string + type: array + x-go-name: MessageIds + required: + - messageIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ReinstallInstanceRequest: + properties: + bootMode: + description: 引导模式 [UEFI Legacy/BIOS] + type: string + x-go-name: BootMode + dataPartition: + description: 数据盘分区 + items: + $ref: '#/definitions/Partition' + type: array + x-go-name: DataPartition + description: + description: 描述 + type: string + x-go-name: Description + hostname: + description: 主机名称 + type: string + x-go-name: HostName + imageId: + description: 镜像ID + type: string + x-go-name: ImageID + installBmpAgent: + description: 是否安装bmp-agent + type: boolean + x-go-name: InstallBmpAgent + instanceName: + description: 实例名称 + type: string + x-go-name: InstanceName + password: + description: 密码 + type: string + x-go-name: Password + sshKeyId: + description: 秘钥ID,运营平台重装,密钥暂时不可用 + type: string + x-go-name: SshKeyID + systemPartition: + description: 系统盘分区 + items: + $ref: '#/definitions/Partition' + type: array + x-go-name: SystemPartition + systemVolumeRaidId: + description: 系统盘RAID ID + type: string + x-go-name: SystemVolumeRaidID + required: + - imageId + - systemVolumeRaidId + - instanceName + - bootMode + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ResetInstancePasswdRequest: + description: 重置实例密码 + properties: + password: + description: 新密码 + type: string + x-go-name: Password + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ResetInstancesPasswdRequest: + description: 批量重置实例密码 + properties: + instance_ids: + description: 实例id列表 + items: + type: string + type: array + x-go-name: InstanceIDs + password: + description: 新密码 + type: string + x-go-name: Password + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + RestartInstancesRequest: + properties: + instanceIds: + items: + type: string + type: array + x-go-name: InstanceIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + Role: + properties: + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + descriptionCn: + description: description + type: string + x-go-name: DescriptionCn + descriptionEn: + description: 权限描述 + type: string + x-go-name: DescriptionEn + permission: + description: 权限 + type: string + x-go-name: Permission + roleId: + description: 角色uuid + type: string + x-go-name: RoleID + roleName: + description: 角色名称 + type: string + x-go-name: RoleName + roleNameCn: + description: 角色名称,唯一 + type: string + x-go-name: RoleNameCn + roleNameEn: + description: 角色名称,唯一 + type: string + x-go-name: RoleNameEn + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + userCount: + description: 用户数 + format: int64 + type: integer + x-go-name: UserCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + RoleId: + properties: + roleId: + description: 角色uuid + type: string + x-go-name: RoleId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + RoleInfo: + properties: + role: + $ref: '#/definitions/Role' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + RoleList: + properties: + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + roles: + description: 角色实体列表 + items: + $ref: '#/definitions/Role' + type: array + x-go-name: Roles + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + Rule: + properties: + deviceTag: + description: 盘符、挂载点、网口列表 + type: string + x-go-name: DeviceTag + dimension: + description: 维度 [instance、disk、mountpoint、nic] + type: string + x-go-name: Dimension + dimensionName: + description: 维度名称 [实例、盘符、挂载点、网卡] + type: string + x-go-name: DimensionName + instanceCount: + description: 关联实例个数 + format: int64 + type: integer + x-go-name: InstanceCount + instanceIds: + description: 实例id列表 + items: + type: string + type: array + x-go-name: InstanceIds + instances: + description: 实例详细信息 + items: + $ref: '#/definitions/Instance' + type: array + x-go-name: Instances + noticeOption: + $ref: '#/definitions/RuleNotice' + relatedResourceCount: + description: 此规则关联的资源数 + format: int64 + type: integer + x-go-name: RelatedResourceCount + resource: + description: 资源类型,目前只支持instance + type: string + x-go-name: Resource + resourceName: + description: 资源类型名称 实例 + type: string + x-go-name: ResourceName + ruleId: + description: 规则uuid + type: string + x-go-name: RuleID + ruleName: + description: 规则名称 + type: string + x-go-name: RuleName + status: + description: 规则状态[1->正常,2->已禁用,3->报警] + format: int64 + type: integer + x-go-name: Status + statusName: + description: 规则状态名称 + type: string + x-go-name: StatusName + triggerDescription: + description: 触发条件描述 + items: + type: string + type: array + x-go-name: TriggerDescription + triggerOption: + description: 触发条件 + items: + $ref: '#/definitions/RuleTrigger' + type: array + x-go-name: TriggerOption + userId: + description: user_id + type: string + x-go-name: UserID + userName: + description: user_name + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + RuleList: + properties: + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + rules: + description: rules数组 + items: + $ref: '#/definitions/Rule' + type: array + x-go-name: Rules + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + RuleNotice: + description: 通知策略 + properties: + effectiveIntervalEnd: + description: 有效时段结束时间 ["23:59:59"] + type: string + x-go-name: EffectiveIntervalEnd + effectiveIntervalStart: + description: 有效时段开始时间 ["00:00:00"] + type: string + x-go-name: EffectiveIntervalStart + noticeCondition: + description: 通知条件,可多选 [1表示报警, 2表示恢复正常] + items: + format: int64 + type: integer + type: array + x-go-name: NoticeCondition + noticePeriod: + description: 通知周期(分钟) [5 10 15 30 60 180 360 720 1440] + format: int64 + type: integer + x-go-name: NoticePeriod + noticeWay: + description: 接收渠道,可多选 [1表示站内信, 2表示邮件] + items: + format: int64 + type: integer + type: array + x-go-name: NoticeWay + userId: + description: 通知对象用户Id + type: string + x-go-name: UserID + userName: + description: 通知对象用户 + type: string + x-go-name: UserName + required: + - noticePeriod + - effectiveIntervalStart + - effectiveIntervalEnd + - noticeCondition + - noticeWay + - userId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + RuleTrigger: + description: 单个触发条件 + properties: + calculation: + description: 计算方式 [min max avg sum] + type: string + x-go-name: Calculation + calculationUnit: + description: 计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出] + type: string + x-go-name: CalculationUnit + description: + description: 对此rule的描述 + type: string + x-go-name: Description + metric: + description: 监控指标 cps.cpu.util + type: string + x-go-name: Metric + metricName: + description: 监控指标名称 CPU使用率 + type: string + x-go-name: MetricName + noticeLevel: + description: 告警级别 [1表示一般,2表示严重,3表示紧急] + format: int64 + type: integer + x-go-name: NoticeLevel + operation: + description: 比较方式 [> >= < <= == !=]或者[gt gte lt lte eq neq] + type: string + x-go-name: Operation + period: + description: 周期 5(分钟) + format: int64 + type: integer + x-go-name: Period + tableName: + description: '[bmp_monitor_counter, bmp_monitor_gauge]' + type: string + x-go-name: TableName + threshold: + description: 阈值 + format: double + type: number + x-go-name: Threshold + times: + description: 持续周期数 [1, 2, 3, 5, 10, 15, 30, 60] + format: int64 + type: integer + x-go-name: Times + required: + - metric + - period + - calculation + - operation + - threshold + - times + - noticeLevel + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + SaveIsPushMailRequest: + properties: + is_push: + description: 是否推送邮件告警,0不推送,1推送 + type: string + x-go-name: IsPush + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + ShareProject: + properties: + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + ownerUserId: + description: 项目拥有者用户id + type: string + x-go-name: OwnerUserID + ownerUserName: + description: 项目拥有者用户名 + type: string + x-go-name: OwnerUserName + projectId: + description: 项目uuid + type: string + x-go-name: ProjectID + projectName: + description: 项目名称 + type: string + x-go-name: ProjectName + shareProjects: + items: + $ref: '#/definitions/ShareProject' + type: array + x-go-name: ShareProjects + sharedUserId: + description: 项目共享者用户id + type: string + x-go-name: SharedUserID + sharedUserName: + description: 项目拥有者用户名 + type: string + x-go-name: SharedUserName + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + ShareProjectRequest: + properties: + ownerID: + description: from user_id + type: string + x-go-name: OwnerID + sharerID: + description: to user_id + type: string + x-go-name: SharerID + required: + - ownerID + - sharerID + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + Sshkey: + properties: + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + fingerPrint: + description: 公钥指纹 + type: string + x-go-name: FingerPrint + id: + description: id + format: int64 + type: integer + x-go-name: Id + key: + description: 公钥,格式:ssh-rsa AAA + type: string + x-go-name: Key + name: + description: 秘钥名称 + type: string + x-go-name: Name + sshkeyId: + description: 秘钥uuid + type: string + x-go-name: SshkeyId + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + userId: + description: 所属用户uuid + type: string + x-go-name: UserId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + SshkeyId: + properties: + sshkeyId: + description: sshkey uuid + type: string + x-go-name: SshkeyId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + SshkeyInfo: + properties: + sshkey: + $ref: '#/definitions/Sshkey' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + SshkeyList: + properties: + pageNumber: + description: 页数 + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + description: 页大小 + format: int64 + type: integer + x-go-name: PageSize + sshkeys: + description: sshkey实体列表 + items: + $ref: '#/definitions/Sshkey' + type: array + x-go-name: Sshkeys + totalCount: + description: 总条数 + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + StartInstancesRequest: + properties: + instanceIds: + items: + type: string + type: array + x-go-name: InstanceIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + StopInstancesRequest: + properties: + instanceIds: + items: + type: string + type: array + x-go-name: InstanceIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + TagsResponse: + properties: + tags: + items: + type: string + type: array + x-go-name: Tags + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + UnMountDevicesRequest: + properties: + deviceId: + description: 设备uuid + type: string + x-go-name: DeviceID + required: + - deviceId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + User: + properties: + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + defaultProjectId: + description: 用户默认项目uuid + type: string + x-go-name: DefaultProjectID + defaultProjectName: + description: 用户默认项目名称 + type: string + x-go-name: DefaultProjectName + description: + description: 描述 + type: string + x-go-name: Description + email: + description: 邮箱 + type: string + x-go-name: Email + id: + description: 用户id + format: int64 + type: integer + x-go-name: ID + instanceCount: + description: 用户拥有的实例数量 + format: int64 + type: integer + x-go-name: InstanceCount + language: + description: 默认语言(en_US/zh_CN) + type: string + x-go-name: Language + phoneNumber: + description: 手机号 + type: string + x-go-name: PhoneNumber + phonePrefix: + description: 国家地区码,如86 + type: string + x-go-name: PhonePrefix + projectCount: + description: 用户拥有的项目数量 + format: int64 + type: integer + x-go-name: ProjectCount + roleId: + description: 角色uuid + type: string + x-go-name: RoleID + roleName: + description: 角色名称 + type: string + x-go-name: RoleName + timezone: + description: 时区 + type: string + x-go-name: Timezone + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + userId: + description: 用户uuid + type: string + x-go-name: UserID + userName: + description: 用户名,唯一 + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + UserId: + properties: + userId: + description: 用户uuid + type: string + x-go-name: UserId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + UserInfo: + properties: + user: + $ref: '#/definitions/User' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + UserList: + properties: + pageNumber: + description: 页数 + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + description: 页大小 + format: int64 + type: integer + x-go-name: PageSize + totalCount: + description: 总条数 + format: int64 + type: integer + x-go-name: TotalCount + users: + description: user实体列表 + items: + $ref: '#/definitions/User' + type: array + x-go-name: Users + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + VerifyUserRequest: + properties: + password: + description: 密码 + type: string + x-go-name: Password + roleId: + description: 角色uuid + type: string + x-go-name: RoleID + userName: + description: 用户名,唯一 + type: string + x-go-name: UserName + required: + - userName + - password + - roleId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request + Volume: + properties: + diskType: + type: string + x-go-name: DiskType + interfaceType: + type: string + x-go-name: InterfaceType + raid: + type: string + x-go-name: Raid + raidCan: + type: string + x-go-name: RaidCan + raidId: + type: string + x-go-name: RaidId + volumeAmount: + format: int64 + type: integer + x-go-name: VolumeAmount + volumeId: + type: string + x-go-name: VolumeID + volumeName: + type: string + x-go-name: VolumeName + volumeSize: + type: string + x-go-name: VolumeSize + volumeType: + type: string + x-go-name: VolumeType + volumeUnit: + type: string + x-go-name: VolumeUnit + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + VolumeIt: + properties: + diskType: + type: string + x-go-name: DiskType + disks: + items: + $ref: '#/definitions/Disk' + type: array + x-go-name: Disks + interfaceType: + type: string + x-go-name: InterfaceType + raid: + type: string + x-go-name: Raid + raidCan: + type: string + x-go-name: RaidCan + raidId: + type: string + x-go-name: RaidId + raids: + items: + $ref: '#/definitions/Raid' + type: array + x-go-name: Raids + volumeAmount: + format: int64 + type: integer + x-go-name: VolumeAmount + volumeId: + type: string + x-go-name: VolumeID + volumeName: + type: string + x-go-name: VolumeName + volumeSize: + type: string + x-go-name: VolumeSize + volumeType: + type: string + x-go-name: VolumeType + volumeUnit: + type: string + x-go-name: VolumeUnit + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/response + VolumeItem: + properties: + deviceTypeId: + type: string + x-go-name: DeviceTypeID + diskType: + type: string + x-go-name: DiskType + interfaceType: + type: string + x-go-name: InterfaceType + raid: + type: string + x-go-name: Raid + raidCan: + type: string + x-go-name: RaidCan + volumeAmount: + format: int64 + type: integer + x-go-name: VolumeAmount + volumeName: + type: string + x-go-name: VolumeName + volumeSize: + type: string + x-go-name: VolumeSize + volumeType: + type: string + x-go-name: VolumeType + volumeUnit: + type: string + x-go-name: VolumeUnit + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi/types/request +host: bmp-openapi.bmp.local +info: + contact: + email: minping@jd.com + description: |- + the purpose of this application is to provide an application + that is using plain go code to define an API + + This should demonstrate all the possible comment annotations + that are available to turn go code into a fully compliant swagger 2.0 spec + license: + name: MIT + url: http://opensource.org/licenses/MIT + termsOfService: there are no TOS at this moment, use at your own risk we take no responsibility + title: CPS + version: 0.0.1 +paths: + /auditLogs: + get: + description: DescribeAuditLogs 获取审计日志列表 + operationId: describeAuditLogs + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: sn + in: query + name: sn + type: string + x-go-name: Sn + - description: 操作名称 + in: query + name: operation + type: string + x-go-name: Operation + - description: 操作人 + in: query + name: username + type: string + x-go-name: UserName + - description: result + in: query + name: result + type: string + x-go-name: Result + - description: 操作时间下限 + format: int64 + in: query + name: startTime + type: integer + x-go-name: StartTime + - description: 操作时间上限 + format: int64 + in: query + name: endTime + type: integer + x-go-name: EndTime + - description: 是否显示所有 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeAuditLogs' + default: + $ref: '#/responses/ErrorResponse' + tags: + - auditLog + /auditLogs/types: + get: + description: DescribeAuditLogTypes 获取审计日志类型 + operationId: describeAuditLogTypes + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/describeAuditLogTypes' + default: + $ref: '#/responses/ErrorResponse' + tags: + - auditLog + /collect/collectDeviceInfo: + post: + description: CollectDeviceInfo 采集设备信息 + operationId: collectDeviceInfo + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CollectDeviceInfoRequest' + responses: + "200": + $ref: '#/responses/collectDeviceInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /deviceTypes: + get: + description: DescribeDeviceTypes 获取机型列表 + operationId: describeDeviceTypes + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 机型id + in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - description: 机型规格 + in: query + name: deviceType + type: string + x-go-name: DeviceType + - description: 机房id + in: query + name: idcId + type: string + x-go-name: IdcID + - description: 机型名称 + in: query + name: name + type: string + x-go-name: Name + - description: 机型类型 + in: query + name: deviceSeries + type: string + x-go-name: DeviceSeries + - in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeDeviceTypes' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + post: + description: CreateDeviceType 添加机型 + operationId: createDeviceType + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateDeviceTypeRequest' + responses: + "200": + $ref: '#/responses/createDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/{device_type_id}: + delete: + description: DeleteDeviceType 删除机型 + operationId: deleteDeviceType + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: device_type_id + required: true + type: string + x-go-name: DeviceTypeID + responses: + "200": + $ref: '#/responses/deleteDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + get: + description: DescribeDeviceType 获取机型详情 + operationId: describeDeviceType + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: device_type_id + required: true + type: string + x-go-name: DeviceTypeID + responses: + "200": + $ref: '#/responses/describeDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + put: + description: ModifyDeviceType 修改机型信息 + operationId: modifyDeviceType + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: device_type_id + required: true + type: string + x-go-name: DeviceTypeID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyDeviceTypeRequest' + responses: + "200": + $ref: '#/responses/modifyDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/{device_type_id}/describeVolumes: + get: + description: DescribeVolumesByDeviceType 根据机型获取volumes + operationId: describeVolumesByDeviceType + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: device_type_id + required: true + type: string + x-go-name: DeviceTypeID + responses: + "200": + $ref: '#/responses/describeVolumesByDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/associatedImage: + post: + description: AssociatedImage 机型绑定镜像 + operationId: associatedImage + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/AssociateImageRequest' + responses: + "200": + $ref: '#/responses/associatedImage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/deviceTypeImage: + get: + description: QueryDeviceTypeImage 根据机型获取镜像 + operationId: describeDeviceTypeImages + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 机型id + in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - description: 镜像id + in: query + name: imageId + type: string + x-go-name: ImageID + - description: 体系架构 + in: query + name: architecture + type: string + x-go-name: Architecture + - description: 操作系统平台 + in: query + name: osType + type: string + x-go-name: OsType + - description: 镜像名称 + in: query + name: imageName + type: string + x-go-name: ImageName + - description: 版本号 + in: query + name: version + type: string + x-go-name: Version + - description: 操作系统ID + in: query + name: osId + type: string + x-go-name: OsID + - description: 镜像类型,预置,自定义 + in: query + name: source + type: string + x-go-name: Source + - description: 是否显示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeDeviceTypeImages' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/deviceTypeImagePartition: + get: + description: QueryDeviceTypeImagePartition 根据机型,镜像,获取分区 + operationId: describeDeviceTypeImagePartitions + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 机型id + in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - description: 镜像id + in: query + name: imageId + type: string + x-go-name: ImageID + - description: 是否显示所有,isAll=1显示所有 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeDeviceTypeImagePartitions' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/deviceTypeRaid: + get: + description: DescribeDeviceTypeRaids 根据机型获取raid + operationId: describeDeviceTypeRaids + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 机型id + in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - description: 系统盘还是数据盘 + in: query + name: volumeType + type: string + x-go-name: VolumeType + - description: raidID + in: query + name: raidId + type: string + x-go-name: RaidID + - description: 是否显示所有 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeDeviceTypeRaids' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/dissociatedImage: + delete: + description: DissociatedImage 机型解绑镜像 + operationId: dissociatedImage + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/DissociatedImageRequest' + responses: + "200": + $ref: '#/responses/dissociatedImage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /devices: + get: + description: DescribeDevices 获取设备列表 + operationId: describeDevices + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 机房id + in: query + name: idcId + type: string + x-go-name: IDcID + - description: 设备sn + in: query + name: sn + type: string + x-go-name: Sn + - description: 实例id + in: query + name: instanceId + type: string + x-go-name: InstanceID + - description: 实例名称 + in: query + name: instanceName + type: string + x-go-name: InstanceName + - description: 机型id + in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - description: 设备管理状态 + in: query + name: manageStatus + type: string + x-go-name: ManageStatus + - description: 带外ip + in: query + name: iloIp + type: string + x-go-name: IloIP + - description: ipv4 + in: query + name: ipv4 + type: string + x-go-name: IPV4 + - description: ipv6 + in: query + name: ipv6 + type: string + x-go-name: IPV6 + - description: 机型类型 + in: query + name: deviceSeries + type: string + x-go-name: DeviceSeries + - description: 所属用户id + in: query + name: userId + type: string + x-go-name: UserID + - description: 所属用户 + in: query + name: userName + type: string + x-go-name: UserName + - description: 是否显示全部,1不分页 + in: query + name: isAll + type: string + x-go-name: IsAll + - description: '"1"表示已采集,"2"表示未采集,"3"表示采集中,4表示采集失败' + in: query + name: collectStatus + type: string + x-go-name: CollectStatus + responses: + "200": + $ref: '#/responses/describeDevices' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + post: + description: CreateDevice 创建设备 + operationId: createDevice + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateDevicesRequest' + responses: + "200": + $ref: '#/responses/createDevice' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/{device_id}: + delete: + description: DeleteDevice 删除设备 + operationId: deleteDevice + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: device_id + required: true + type: string + x-go-name: DeviceID + responses: + "200": + $ref: '#/responses/deleteDevice' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + get: + description: DescribeDevice 获取设备详情 + operationId: describeDevice + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: device_id + required: true + type: string + x-go-name: DeviceID + responses: + "200": + $ref: '#/responses/describeDevice' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + put: + description: ModifyDevice 修改设备信息 + operationId: modifyDevice + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: device_id + required: true + type: string + x-go-name: DeviceID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyDevicesRequest' + responses: + "200": + $ref: '#/responses/modifyDevice' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/{device_id}/disksDetail: + get: + description: DescribeDeviceDisks 设备详情-磁盘 + operationId: describeDeviceDisks + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: device_id + required: true + type: string + x-go-name: DeviceID + responses: + "200": + $ref: '#/responses/describeDeviceDisks' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/{device_id}/remove: + put: + description: DeleteDevice 移除设备 + operationId: removeDevice + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: device_id + required: true + type: string + x-go-name: DeviceID + responses: + "200": + $ref: '#/responses/removeDevice' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/deviceType/associate: + put: + description: AssociateDeviceType 设备绑定机型 + operationId: deviceAssociateDeviceType + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/DeviceAssociateDeviceTypeRequest' + responses: + "200": + $ref: '#/responses/deviceAssociateDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/disks/associateDisks: + put: + description: AssociateDeviceDisks 设备关联磁盘 + operationId: associateDeviceDisks + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/AssociateDeviceDisksRequest' + responses: + "200": + $ref: '#/responses/associateDeviceDisks' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/disks/describeAssociateDisks: + get: + description: GetAssociatedDisks 获取设备已关联的磁盘 + operationId: getAssociatedDisks + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: device uuid + in: query + name: deviceId + required: true + type: string + x-go-name: DeviceID + - description: devicetype uuid + in: query + name: deviceTypeId + required: true + type: string + x-go-name: DeviceTypeID + - description: volume uuid + in: query + name: volumeId + required: true + type: string + x-go-name: VolumeID + responses: + "200": + $ref: '#/responses/getAssociatedDisks' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/mount: + put: + description: MountDevice 设备上架 + operationId: mountDevice + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/MountDevicesRequest' + responses: + "200": + $ref: '#/responses/mountDevice' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/stock: + delete: + description: DescribeDeviceStock 获取指定机型的设备库存 + operationId: describeDeviceStock + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + responses: + "200": + $ref: '#/responses/describeDeviceStock' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/unmount: + put: + description: UnMountDevice 设备下架 + operationId: unMountDevice + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/UnMountDevicesRequest' + responses: + "200": + $ref: '#/responses/unMountDevice' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /idcs: + get: + description: DescribeIdcs 获取idc列表 + operationId: describeIdcs + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 机房名称 + in: query + name: name + type: string + x-go-name: Name + - description: 机房英文名称 + in: query + name: nameEn + type: string + x-go-name: NameEn + - description: 机房等级 + in: query + name: level + type: string + x-go-name: Level + - description: 是否显示所有 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeIdcs' + default: + $ref: '#/responses/ErrorResponse' + tags: + - idc + post: + description: CreateIdc 创建idc(接口废弃,不对外开放) + operationId: createIdc + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateIdcRequest' + responses: + "200": + $ref: '#/responses/createIdc' + default: + $ref: '#/responses/ErrorResponse' + tags: + - idc + /idcs/{idc_id}: + delete: + description: DeleteIdc 删除idc + operationId: deleteIdc + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: idc_id + required: true + type: string + x-go-name: IdcID + responses: + "200": + $ref: '#/responses/deleteIdc' + default: + $ref: '#/responses/ErrorResponse' + tags: + - idc + get: + description: DescribeIdc 获取idc详情 + operationId: describeIdc + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: idc_id + required: true + type: string + x-go-name: IdcID + responses: + "200": + $ref: '#/responses/describeIdc' + default: + $ref: '#/responses/ErrorResponse' + tags: + - idc + put: + description: ModifyIdc 修改idc信息 + operationId: modifyIdc + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: idc_id + required: true + type: string + x-go-name: IdcID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyIdcRequest' + responses: + "200": + $ref: '#/responses/modifyIdc' + default: + $ref: '#/responses/ErrorResponse' + tags: + - idc + /images: + get: + description: DescribeImages 获取镜像列表 + operationId: describeImages + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 镜像ID + in: query + name: imageId + type: string + x-go-name: ImageID + - description: 镜像名称 + in: query + name: imageName + type: string + x-go-name: ImageName + - description: 设备类型id + in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - description: 版本号 + in: query + name: version + type: string + x-go-name: Version + - description: 操作系统ID + in: query + name: osId + type: string + x-go-name: OsID + - description: 镜像ID,数组,支持多个 + in: query + items: + type: string + name: imageIds + type: array + x-go-name: ImageIDs + - description: 镜像类型,预置,自定义 + in: query + name: source + type: string + x-go-name: Source + - description: 体系架构 + in: query + name: architecture + type: string + x-go-name: Architecture + - description: 操作系统平台 + in: query + name: osType + type: string + x-go-name: OsType + - description: 是否显示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeImages' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + post: + description: CreateImage 添加镜像 + operationId: createImage + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateImageRequest' + responses: + "200": + $ref: '#/responses/createImage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + /images/{image_id}: + delete: + description: DeleteImage 删除镜像 + operationId: deleteImage + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: image_id + required: true + type: string + x-go-name: ImageID + responses: + "200": + $ref: '#/responses/deleteImage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + get: + description: DescribeImage 获取镜像详情 + operationId: describeImage + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: image_id + required: true + type: string + x-go-name: ImageID + responses: + "200": + $ref: '#/responses/describeImage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + put: + description: ModifyImage 修改镜像(暂不启用) + operationId: modifyImage + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: image_id + required: true + type: string + x-go-name: ImageID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyImageRequest' + responses: + "200": + $ref: '#/responses/modifyImage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + /images/associatedDeviceType: + post: + description: AssociatedDeviceType 镜像绑定机型 + operationId: associatedDeviceType + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/AssociateDeviceTypeRequest' + responses: + "200": + $ref: '#/responses/associatedDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + /images/dissociatedDeviceType: + delete: + description: DissociatedDeviceType 镜像解绑机型 + operationId: dissociatedDeviceType + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/DissociatedImageRequest' + responses: + "200": + $ref: '#/responses/dissociatedDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + /images/imageDeviceTypes: + get: + description: DescribeImageDeviceTypes 查看镜像绑定的机型 + operationId: describeImageDeviceTypes + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 镜像ID + in: query + name: imageId + required: true + type: string + x-go-name: ImageID + - description: 体系架构 + in: query + name: architecture + type: string + x-go-name: Architecture + - description: 镜像是否绑定了机型,0查询该镜像没有绑定的机型列表 1查询该镜像已经绑定了的机型列表 + in: query + name: isBind + type: string + x-go-name: IsBind + - description: 是否显示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeImageDeviceTypes' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + /license/content: + get: + description: DescribeLicenseContent 获取授权详情 + operationId: describeLicenseContent + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/describeLicenseContent' + default: + $ref: '#/responses/ErrorResponse' + tags: + - license + /license/requestToken: + get: + description: DescribeRequestToken 获取请求码 + operationId: describeLicenseToken + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/describeLicenseToken' + default: + $ref: '#/responses/ErrorResponse' + tags: + - license + /license/upload: + post: + description: UploadLicense 上传授权 + operationId: uploadLicense + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateLicenseRequest' + responses: + "200": + $ref: '#/responses/uploadLicense' + default: + $ref: '#/responses/ErrorResponse' + tags: + - license + /local/users: + get: + description: DescribeLocalUser 控制台获取用户详情 + operationId: describeLocalUser + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/describeLocalUser' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + put: + description: ModifyLocalUser 控制台修改除密码外的个人信息 + operationId: modifyLocalUser + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyLocalUserRequest' + responses: + "200": + $ref: '#/responses/modifyLocalUser' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /local/users/password: + put: + description: ModifyLocalUserPassword 控制台修改个人密码 + operationId: modifyLocalUserPassword + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyUserPasswordRequest' + responses: + "200": + $ref: '#/responses/modifyLocalUserPassword' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /messages: + get: + description: GetMessageList 获取message列表(分页) + operationId: getMessageList + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 是否显示全部,取值为1时表示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + - description: 0:未读;1:已读;""不传表示全部 + in: query + name: hasRead + type: string + x-go-name: HasRead + - description: 消息类型 + in: query + name: messageType + type: string + x-go-name: MessageType + - description: 消息子类型 + in: query + name: messageSubType + type: string + x-go-name: MessageSubType + - description: 内容模糊搜索 + in: query + name: detail + type: string + x-go-name: Detail + responses: + "200": + $ref: '#/responses/getMessageList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/delete: + delete: + description: DeleteMessage 删除消息(可多条) + operationId: deleteMessage + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/DeleteMessagesRequest' + responses: + "200": + $ref: '#/responses/deleteMessage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/dialMail: + post: + description: DialMail 测试邮箱设置是否正确 + operationId: dialMail + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/MailDialRequest' + responses: + "200": + $ref: '#/responses/dialMail' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/doRead: + put: + description: ReadMessage 将消息设置为已读(可多条) + operationId: readMessage + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/ReadMessagesRequest' + responses: + "200": + $ref: '#/responses/readMessage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/getMessageById: + get: + description: GetMessageById 获取消息详情,包括上一条/下一条的messageid + operationId: getMessageById + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: query + name: messageId + required: true + type: string + x-go-name: MessageID + responses: + "200": + $ref: '#/responses/getMessageById' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/getMessageTypes: + get: + description: GetMessageTypes 获取消息类型/子类型 + operationId: getMessageTypes + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/getMessageTypes' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/hasUnreadMessage: + get: + description: HasUnreadMessage 获取有没有未读消息 + operationId: hasUnreadMessage + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/hasUnreadMessage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/mailDetail: + get: + description: MailDetail 获取邮箱设置 + operationId: mailDetail + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/mailDetail' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/saveIsPushMail: + post: + description: SaveIsPushMail 保存邮箱是否通知的设置 + operationId: saveIsPushMail + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/SaveIsPushMailRequest' + responses: + "200": + $ref: '#/responses/saveIsPushMail' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/statistic: + get: + description: GetMessageStatistic 获取message总数和未读数 + operationId: getMessageStatistic + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/getMessageStatistic' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /monitorAlert/deleteAlert: + delete: + description: DeleteAlert 删除告警 + operationId: deleteAlert + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/DeleteAlertRequest' + responses: + "200": + $ref: '#/responses/deleteAlert' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorAlert + /monitorAlert/describeAlert: + get: + description: DescribeAlert 告警详情 + operationId: describeAlert + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: rule uuid + in: query + name: alertId + required: true + type: string + x-go-name: AlertID + responses: + "200": + $ref: '#/responses/describeAlert' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorAlert + /monitorAlert/describeAlerts: + get: + description: DescribeAlerts 告警列表 + operationId: describeAlerts + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 是否显示全部,取值为1时表示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + - description: user uuid + in: query + name: userId + type: string + x-go-name: UserID + - description: username + in: query + name: userName + type: string + x-go-name: UserName + - description: 规则名称 + in: query + name: ruleName + type: string + x-go-name: RuleName + - description: 规则uuid + in: query + name: ruleId + type: string + x-go-name: RuleID + - description: 资源id,目前就是实例id + in: query + name: resourceId + type: string + x-go-name: ResourceID + - description: 报警时间筛选stime + format: int64 + in: query + name: startTime + type: integer + x-go-name: StartTime + - description: 报警时间筛选etime + format: int64 + in: query + name: endTime + type: integer + x-go-name: EndTime + responses: + "200": + $ref: '#/responses/describeAlerts' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorAlert + /monitorData: + get: + description: GetMonitorData 获取图表监控数据 + operationId: getMonitorData + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 指标名称,支持多个,用逗号隔离开 + in: query + name: metricName + type: string + x-go-name: MetricName + - description: 实例id + in: query + name: instanceId + type: string + x-go-name: InstanceID + - description: 标签值 + in: query + name: device + type: string + x-go-name: Device + - description: 开始时间戳 + format: int64 + in: query + name: startTime + type: integer + x-go-name: StartTime + - description: 结束时间戳 + format: int64 + in: query + name: endTime + type: integer + x-go-name: EndTime + - description: 间隔多久一个点 s为单位 + format: int64 + in: query + name: timeInterval + type: integer + x-go-name: TimeInterval + - description: 最近多少时间,小时为单位 + format: int64 + in: query + name: lastManyTime + type: integer + x-go-name: LastManyTime + - description: avg, min, max, sum + in: query + name: downSampleType + type: string + x-go-name: DownSampleType + - description: 以下为运营平台的 + in: query + name: userName + type: string + x-go-name: UserName + - description: idc uuid + in: query + name: idcID + type: string + x-go-name: IdcID + responses: + "200": + $ref: '#/responses/getMonitorData' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorData + /monitorProxy/desrcibeAgentStatus: + get: + description: DesrcibeAgentStatus 获取agent状态 + operationId: desrcibeAgentStatus + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: InstanceId,多个用逗号分隔 + in: query + name: instanceId + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/desrcibeAgentStatus' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorProxy + /monitorProxy/desrcibeTags: + get: + description: DesrcibeAgentStatus 获取tag列表 + operationId: desrcibeTags + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: instanceId + in: query + name: instanceId + required: true + type: string + x-go-name: InstanceID + - description: tagName [disk mountpoint nic] + in: query + name: tagName + required: true + type: string + x-go-name: TagName + responses: + "200": + $ref: '#/responses/desrcibeTags' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorProxy + /monitorRule/addRule: + post: + description: AddRule 添加规则 + operationId: addRule + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/AddRuleRequest' + responses: + "200": + $ref: '#/responses/addRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/deleteRule: + delete: + description: DeleteRule 删除规则 + operationId: deleteRule + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/DeleteRuleRequest' + responses: + "200": + $ref: '#/responses/deleteRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/describeRule: + get: + description: DescribeRule 规则详情 + operationId: describeRule + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: rule uuid + in: query + name: ruleId + required: true + type: string + x-go-name: RuleID + responses: + "200": + $ref: '#/responses/describeRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/describeRules: + get: + description: DescribeRules 规则列表 + operationId: describeRules + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 是否显示全部,取值为1时表示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + - description: user uuid + in: query + name: userId + type: string + x-go-name: UserID + - description: username + in: query + name: userName + type: string + x-go-name: UserName + - description: 规则名称 + in: query + name: ruleName + type: string + x-go-name: RuleName + - description: 规则uuid + in: query + name: ruleId + type: string + x-go-name: RuleID + - description: 1 正常,2 禁用,3 报警 + format: int64 + in: query + name: status + type: integer + x-go-name: Status + responses: + "200": + $ref: '#/responses/describeRules' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/disableRule: + put: + description: DisableRule 禁用规则 + operationId: disableRule + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/DisableRuleRequest' + responses: + "200": + $ref: '#/responses/disableRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/editRule: + put: + description: EditRule 编辑规则 + operationId: editRule + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/EditRuleRequest' + responses: + "200": + $ref: '#/responses/editRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /monitorRule/enableRule: + put: + description: EnableRule 启用规则 + operationId: enableRule + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/EnableRuleRequest' + responses: + "200": + $ref: '#/responses/enableRule' + default: + $ref: '#/responses/ErrorResponse' + tags: + - monitorRule + /oss: + get: + description: DescribeOSs 获取os列表(暂不启用) + operationId: describeOSs + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 操作系统名称 + in: query + name: osName + type: string + x-go-name: OsName + - description: 操作系统平台 + in: query + name: osType + type: string + x-go-name: OsType + - description: 操作系统版本 + in: query + name: osVersion + type: string + x-go-name: OsVersion + - description: 是否显示所有 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeOSs' + default: + $ref: '#/responses/ErrorResponse' + tags: + - os + post: + description: CreateOS 添加操作系统(暂不启用) + operationId: createOS + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateOSRequest' + responses: + "200": + $ref: '#/responses/createOS' + default: + $ref: '#/responses/ErrorResponse' + tags: + - os + /oss/{os_id}: + delete: + description: DeleteOS 删除os(暂不启用) + operationId: deleteOS + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: os_id + required: true + type: string + x-go-name: OsID + responses: + "200": + $ref: '#/responses/deleteOS' + default: + $ref: '#/responses/ErrorResponse' + tags: + - os + get: + description: DescribeOS 获取os系统详情(暂不启用) + operationId: describeOS + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: os_id + required: true + type: string + x-go-name: OsID + responses: + "200": + $ref: '#/responses/describeOS' + default: + $ref: '#/responses/ErrorResponse' + tags: + - os + put: + description: ModifyOS 修改os信息(暂不启用) + operationId: modifyOS + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: os_id + required: true + type: string + x-go-name: OsID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyOSRequest' + responses: + "200": + $ref: '#/responses/modifyOS' + default: + $ref: '#/responses/ErrorResponse' + tags: + - os + /project/instances: + get: + description: DescribeProjectInstances 获取实例列表 + operationId: describeProjectInstances + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 实例ID + in: query + name: instanceId + type: string + x-go-name: InstanceID + - description: 实例名称,模糊搜索 + in: query + name: instanceName + type: string + x-go-name: InstanceName + - description: 设备类型ID + in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - description: 运行状态 + in: query + name: status + type: string + x-go-name: Status + - description: 设备ID + in: query + name: deviceId + type: string + x-go-name: DeviceID + - description: SN + in: query + name: sn + type: string + x-go-name: Sn + - description: 机房ID + in: query + name: idcId + type: string + x-go-name: IdcID + - description: 项目ID + in: query + name: projectId + type: string + x-go-name: ProjectID + - description: 带外ip,精确搜索 + in: query + name: ilo_ip + type: string + x-go-name: IloIP + - description: ipv4,精确搜索 + in: query + name: ipv4 + type: string + x-go-name: IPV4 + - description: ipv6,精确搜索 + in: query + name: ipv6 + type: string + x-go-name: IPV6 + - description: 是否显示全部,取值为1时表示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeProjectInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + post: + description: CreateProjectInstance 创建实例 + operationId: createProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateInstanceRequest' + responses: + "200": + $ref: '#/responses/createProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}: + delete: + description: DeleteProjectInstance 删除实例 + operationId: deleteProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/deleteProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + get: + description: DescribeProjectInstance 获取实例详情 + operationId: describeProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 实例uuid + in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/describeProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + put: + description: ModifyProjectInstance 修改实例信息 + operationId: modifyProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyInstanceRequest' + responses: + "200": + $ref: '#/responses/modifyProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/lock: + put: + description: LockProjectInstance 锁定实例 + operationId: lockProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/lockProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/reinstallInstance: + put: + description: ReinstallInstance 重装实例 + operationId: reinstallProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + - in: body + name: Body + schema: + $ref: '#/definitions/ReinstallInstanceRequest' + responses: + "200": + $ref: '#/responses/reinstallProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/resetStatus: + put: + description: ResetInstanceStatus 重置实例状态 + operationId: resetInstanceStatus + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/resetInstanceStatus' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/resetpasswd: + put: + description: ResetPasswd 重置密码 + operationId: resetProjectInstancePasswd + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + - in: body + name: Body + schema: + $ref: '#/definitions/ResetInstancePasswdRequest' + responses: + "200": + $ref: '#/responses/resetProjectInstancePasswd' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/restart: + put: + description: RestartProjectInstance 实例重启 + operationId: restartProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/restartProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/start: + put: + description: StartProjectInstance 实例开机 + operationId: startProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/startProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/stop: + put: + description: StopProjectInstance 实例关机 + operationId: stopProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/stopProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/{instance_id}/unlock: + put: + description: UnLockProjectInstance 解锁实例 + operationId: unLockProjectInstance + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/unLockProjectInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/batch/instances:deleteInstances: + delete: + description: DeleteInstances 批量删除实例 + operationId: deleteInstances + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/DeleteInstancesRequest' + responses: + "200": + $ref: '#/responses/deleteInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/batch/instances:modifyInstances: + put: + description: ModifyInstances 批量修改实例名称 + operationId: modifyInstances + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyInstancesRequest' + responses: + "200": + $ref: '#/responses/modifyInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/batch/instances:resetPasswd: + put: + description: ResetInstancesPasswd 批量重置密码 + operationId: resetProjectInstancesPasswd + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/ResetInstancesPasswdRequest' + responses: + "200": + $ref: '#/responses/resetProjectInstancesPasswd' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/batch/instances:restartInstances: + put: + description: StartInstances 批量重启 + operationId: restartInstances + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/RestartInstancesRequest' + responses: + "200": + $ref: '#/responses/restartInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/batch/instances:startInstances: + put: + description: StartInstances 批量开机 + operationId: startInstances + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/StartInstancesRequest' + responses: + "200": + $ref: '#/responses/startInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /project/instances/batch/instances:stopInstances: + put: + description: StartInstances 批量关机 + operationId: stopInstances + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/StopInstancesRequest' + responses: + "200": + $ref: '#/responses/stopInstances' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /raids: + get: + description: DescribeRaids 获取raid列表 + operationId: describeRaids + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/describeRaids' + default: + $ref: '#/responses/ErrorResponse' + tags: + - raid + post: + description: CreateRaid 创建raid(暂不启用) + operationId: createRaid + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateRaidRequest' + responses: + "200": + $ref: '#/responses/createRaid' + default: + $ref: '#/responses/ErrorResponse' + tags: + - raid + /raids/{raid_id}: + delete: + description: DeleteRaid 删除raid(暂不启用) + operationId: deleteRaid + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: raid_id + required: true + type: string + x-go-name: RaidID + responses: + "200": + $ref: '#/responses/deleteRaid' + default: + $ref: '#/responses/ErrorResponse' + tags: + - raid + get: + description: DescribeRaid 获取raid详情 + operationId: describeRaid + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: raid_id + required: true + type: string + x-go-name: RaidID + responses: + "200": + $ref: '#/responses/describeRaid' + default: + $ref: '#/responses/ErrorResponse' + tags: + - raid + put: + description: ModifyRaid 修改raid信息(暂不启用) + operationId: modifyRaid + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: raid_id + required: true + type: string + x-go-name: RaidID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyRaidRequest' + responses: + "200": + $ref: '#/responses/modifyRaid' + default: + $ref: '#/responses/ErrorResponse' + tags: + - raid + /raids/deviceTypeRaid: + delete: + description: DeleteDeviceTypeRaid ... 机型和raid解绑(暂不启用) + operationId: deleteDeviceTypeRaid + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/DeleteDeviceTypeRaidRequest' + responses: + "200": + $ref: '#/responses/deleteDeviceTypeRaid' + default: + $ref: '#/responses/ErrorResponse' + tags: + - raid + post: + description: CreateDeviceTypeRaid ... 机型和raid关联(暂不启用) + operationId: createDeviceTypeRaid + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateDeviceTypeRaidRequest' + responses: + "200": + $ref: '#/responses/createDeviceTypeRaid' + default: + $ref: '#/responses/ErrorResponse' + tags: + - raid + /resources: + get: + description: DescribeResources 根据某个字段值精确查询对应的资源列表(如根据imageName查询镜像列表,根据idcName查询机房列表) + operationId: describeResources + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: |- + 机房名称 + IdcName string `json:"idcName"` + 机房英文名称 + IdcNameEn string `json:"idcNameEn"`*/ + 机型名称 + in: query + name: name + type: string + x-go-name: Name + - description: 机型规格 + in: query + name: deviceType + type: string + x-go-name: DeviceType + - description: 镜像名称 + in: query + name: imageName + type: string + x-go-name: ImageName + - description: 用户名称 + in: query + name: userName + type: string + x-go-name: UserName + responses: + "200": + $ref: '#/responses/describeResources' + default: + $ref: '#/responses/ErrorResponse' + tags: + - resource + /roles: + get: + description: DescribeRoles 获取角色列表 + operationId: describeRoles + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 是否显示所有 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeRoles' + default: + $ref: '#/responses/ErrorResponse' + tags: + - role + post: + description: CreateRole 创建角色(暂不启用) + operationId: createRole + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateRoleRequest' + responses: + "200": + $ref: '#/responses/createRole' + default: + $ref: '#/responses/ErrorResponse' + tags: + - role + /roles/{role_id}: + delete: + description: DeleteRole 删除角色(暂不启用) + operationId: deleteRole + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: role_id + required: true + type: string + x-go-name: RoleID + responses: + "200": + $ref: '#/responses/deleteRole' + default: + $ref: '#/responses/ErrorResponse' + tags: + - role + get: + description: DescribeRole 获取角色详情 + operationId: describeRole + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: role_id + required: true + type: string + x-go-name: RoleID + responses: + "200": + $ref: '#/responses/describeRole' + default: + $ref: '#/responses/ErrorResponse' + tags: + - role + put: + description: ModifyRole 修改角色信息(暂不启用) + operationId: modifyRole + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: role_id + required: true + type: string + x-go-name: RoleID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyRoleRequest' + responses: + "200": + $ref: '#/responses/modifyRole' + default: + $ref: '#/responses/ErrorResponse' + tags: + - role + /roles/roleInfo/current: + get: + description: CurrentRole 获取当前登录用户的角色 + operationId: currentRole + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + responses: + "200": + $ref: '#/responses/currentRole' + default: + $ref: '#/responses/ErrorResponse' + tags: + - role + /user/apikeys: + get: + description: DescribeUserAPIKeys 获取APIKey列表 + operationId: describeUserAPIKeys + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 秘钥对名称 + in: query + name: name + type: string + x-go-name: Name + - description: Token类型, [system/user] + in: query + name: type + type: string + x-go-name: Type + - description: 是否查询全部/导出 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeUserAPIKeys' + default: + $ref: '#/responses/ErrorResponse' + tags: + - apiKey + post: + description: CreateUserApikey 创建apikey + operationId: createUserApikey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateApikeyRequest' + responses: + "200": + $ref: '#/responses/createUserApikey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - apiKey + /user/apikeys/{apikey_id}: + delete: + description: DeleteUserApikey 删除某个apikey + operationId: deleteUserApikey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: apikey_id + required: true + type: string + x-go-name: ApikeyID + responses: + "200": + $ref: '#/responses/deleteUserApikey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - apiKey + get: + description: DescribeUserAPIKey 获取apikey详情 + operationId: describeUserAPIKey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: apikey_id + required: true + type: string + x-go-name: ApikeyID + responses: + "200": + $ref: '#/responses/describeUserAPIKey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - apiKey + put: + description: ModifyUserApikey 修改apikey(暂不启用) + operationId: modifyUserApikey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: apikey_id + required: true + type: string + x-go-name: ApikeyID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyApikeyRequest' + responses: + "200": + $ref: '#/responses/modifyUserApikey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - apiKey + /user/projects: + get: + description: DescribeUserProjects 获取项目列表 + operationId: describeUserProjects + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + in: query + name: projectName + type: string + x-go-name: ProjectName + - format: int64 + in: query + name: owned + type: integer + x-go-name: Owned + - in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeUserProjects' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + post: + description: CreateUserProject 创建项目 + operationId: createUserProject + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateProjectRequest' + responses: + "200": + $ref: '#/responses/createUserProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /user/projects/{project_id}: + delete: + description: DeleteUserProject 删除项目 + operationId: deleteUserProject + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + responses: + "200": + $ref: '#/responses/deleteUserProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + get: + description: DescribeUserProject 获取项目详情 + operationId: describeUserProject + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + responses: + "200": + $ref: '#/responses/describeUserProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + put: + description: ModifyUserProject 修改项目信息 + operationId: modifyUserProject + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyProjectRequest' + responses: + "200": + $ref: '#/responses/modifyUserProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /user/projects/{project_id}/cancelShare: + put: + description: CancelShareUserProject 取消共享项目 + operationId: cancelShareUserProject + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + - in: body + name: Body + schema: + $ref: '#/definitions/ShareProjectRequest' + responses: + "200": + $ref: '#/responses/cancelShareUserProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /user/projects/{project_id}/share: + put: + description: ShareUserProject 共享项目 + operationId: shareUserProject + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: project_id + required: true + type: string + x-go-name: ProjectID + - in: body + name: Body + schema: + $ref: '#/definitions/ShareProjectRequest' + responses: + "200": + $ref: '#/responses/shareUserProject' + default: + $ref: '#/responses/ErrorResponse' + tags: + - project + /user/sshkeys: + get: + description: DescribeUserSshKeys 获取个人sshkey列表 + operationId: describeUserSshKeys + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 秘钥名称 + in: query + name: name + type: string + x-go-name: Name + - description: 是否显示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeUserSshKeys' + default: + $ref: '#/responses/ErrorResponse' + tags: + - sshkey + post: + description: CreateUserSshkey 创建个人sshkey + operationId: createUserSshkey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateSshkeyRequest' + responses: + "200": + $ref: '#/responses/createUserSshkey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - sshkey + /user/sshkeys/{sshkey_id}: + delete: + description: DeleteUserSshkey 删除sshkey + operationId: deleteUserSshkey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: sshkey_id + required: true + type: string + x-go-name: SshkeyID + responses: + "200": + $ref: '#/responses/deleteUserSshkey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - sshkey + get: + description: DescribeUserSshKey 获取sshkey详情 + operationId: describeUserSshKey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: sshkey_id + required: true + type: string + x-go-name: SshkeyID + responses: + "200": + $ref: '#/responses/describeUserSshKey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - sshkey + put: + description: ModifyUserSshkey 修改sshkey + operationId: modifyUserSshkey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: sshkey_id + required: true + type: string + x-go-name: SshkeyID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifySshkeyRequest' + responses: + "200": + $ref: '#/responses/modifyUserSshkey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - sshkey + /user/sshkeys/instances/{sshkey_id}: + get: + description: GetInstancesBySshkey 根据sshkey获取实例列表 + operationId: getInstancesBySshkey + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: sshkey_id + required: true + type: string + x-go-name: SshkeyID + responses: + "200": + $ref: '#/responses/getInstancesBySshkey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - sshkey + /users: + get: + description: DescribeUsers 获取用户列表 + operationId: describeUsers + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 页码 + format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - description: 每页数量 + format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 角色uuid + in: query + name: roleId + type: string + x-go-name: RoleID + - description: 项目uuid + in: query + name: defaultProjectId + type: string + x-go-name: DefaultProjectID + - description: 用户名 + in: query + name: userName + type: string + x-go-name: UserName + - description: 是否显示全部, isAll=1表示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeUsers' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + post: + description: CreateUser 创建用户 + operationId: createUser + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/CreateUserRequest' + responses: + "200": + $ref: '#/responses/createUser' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /users/{user_id}: + delete: + description: DeleteUser 删除用户 + operationId: deleteUser + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: user_id + required: true + type: string + x-go-name: UserID + responses: + "200": + $ref: '#/responses/deleteUser' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + get: + description: DescribeUser 获取用户详情 + operationId: describeUser + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: user_id + required: true + type: string + x-go-name: UserID + responses: + "200": + $ref: '#/responses/describeUser' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + put: + description: ModifyUser 修改用户信息 + operationId: modifyUser + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: path + name: user_id + required: true + type: string + x-go-name: UserID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyUserRequest' + responses: + "200": + $ref: '#/responses/modifyUser' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /users/getUserByName: + get: + description: DescribeUserByName 根据用户名获取用户详情 + operationId: describeUserByName + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid, deprecated + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - description: 用户名,唯一 + in: query + name: userName + required: true + type: string + x-go-name: UserName + responses: + "200": + $ref: '#/responses/describeUserByName' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /users/verify: + post: + description: VerifyUser 鉴定用户 + operationId: verifyUser + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - description: 'demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token' + in: header + name: authorization + required: true + type: string + x-go-name: Authorization + - description: 用户uuid + in: header + name: bmpUserId + type: string + x-go-name: BmpUserID + - description: 用户语言 [zh_CN, en_US] + in: header + name: bmpLanguage + type: string + x-go-name: BmpLanguage + - in: body + name: Body + schema: + $ref: '#/definitions/VerifyUserRequest' + responses: + "200": + $ref: '#/responses/verifyUser' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user +produces: + - application/json + - application/xml +responses: + ErrorResponse: + description: unit err response for non 200 + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + error: + $ref: '#/definitions/ErrorResponse' + requestId: + description: 流量ID + type: string + x-go-name: RequestId + required: + - error + - requestId + type: object + addRule: + description: A AddRuleResult is an response struct that is used to describe create rule result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + associateDeviceDisks: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + associatedDeviceType: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + associatedImage: + description: A AssociatedImageResult is an response struct that is used to associated image result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + cancelShareUserProject: + description: A CancelShareUserProjectResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + collectDeviceInfo: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + createDevice: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + createDeviceType: + description: A CreateDeviceTypeResult is an response struct that is used to describe create deviceType result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/DeviceTypeId' + type: object + createDeviceTypeRaid: + description: A CreateDeviceTypeRaidResult is an response struct that is used to describe create device type raid result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + createIdc: + description: A CreateIdcResult is an response struct that is used to describe create idc result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/IdcID' + type: object + createImage: + description: A CreateImageResult is an response struct that is used to describe create image result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ImageId' + type: object + createOS: + description: A CreateOsResult is an response struct that is used to describe create os result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/OsId' + type: object + createProjectInstance: + description: A CreateProjectInstanceResult is an response struct that is used to describe create instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/InstanceIds' + type: object + createRaid: + description: A CreateRaidResult is an response struct that is used to describe create raid result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/RaidId' + type: object + createRole: + description: A CreateRoleResult is an response struct that is used to describe create role result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/RoleId' + type: object + createUser: + description: A CreateInstancesResult is an response struct that is used to describe create instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/UserId' + type: object + createUserApikey: + description: A CreateUserApikeyResult is an response struct that is used to describe create apikey result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ApikeyId' + type: object + createUserProject: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ProjectId' + type: object + createUserSshkey: + description: A CreateUserSshkeyResult is an response struct that is used to describe create sshkey result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/SshkeyId' + type: object + currentRole: + description: A CurrentRoleResult is an response struct that is used to describe role. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/RoleInfo' + type: object + deleteAlert: + description: A DeleteAlertResult is an response struct that is used to describe create alert result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteDevice: + description: A DeleteDeviceResult is an response struct that is used to describe delete device result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteDeviceType: + description: A DeleteDeviceTypeResult is an response struct that is used to delete device type. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteDeviceTypeRaid: + description: A DeleteDeviceTypeRaidResult is an response struct that is used to describe delete device type raid result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteIdc: + description: A DeleteIdcResult is an response struct that is used to delete idc. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteImage: + description: A DeleteImageResult is an response struct that is used to delete image. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteInstances: + description: A DeleteInstancesResult is an response struct that is used to describe modify instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteMessage: + description: A DeleteMessageResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteOS: + description: A DeleteOsResult is an response struct that is used to delete stop os result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteProjectInstance: + description: A DeleteProjectInstanceResult is an response struct that is used to delete stop instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteRaid: + description: A DeleteRaidResult is an response struct that is used to delete raid. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteRole: + description: A DeleteRoleResult is an response struct that is used to delete role. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteRule: + description: A DeleteRuleResult is an response struct that is used to describe create rule result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteUser: + description: A GetUserResult is an response struct that is used to describe getuser. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteUserApikey: + description: A DeleteUserApikeyResult is an response struct that is used to describe delete Apikey result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteUserProject: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteUserSshkey: + description: A DeleteUserSshkeyResult is an response struct that is used to describe delete sshkey result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + describeAlert: + description: A DescribeAlertResult is an response struct that is used to describe get Alert. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/Alert' + type: object + describeAlerts: + description: A DescribeAlertsResult is an response struct that is used to describe get Alert. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/AlertList' + type: object + describeAuditLogTypes: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + items: + $ref: '#/definitions/AuditLogsType' + type: array + x-go-name: Result + type: object + describeAuditLogs: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/AuditLogList' + type: object + describeDevice: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/DeviceInfo' + type: object + describeDeviceDisks: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/DeviceDisks' + type: object + describeDeviceStock: + description: A GetDeviceStockResult is an response struct that is used to get device stock. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/DeviceStock' + type: object + describeDeviceType: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/DeviceTypeInfo' + type: object + describeDeviceTypeImagePartitions: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/QueryDeviceTypeImagePartitionResponse' + type: object + describeDeviceTypeImages: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ImageList' + type: object + describeDeviceTypeRaids: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + items: + $ref: '#/definitions/RDeviceTypeRaid' + type: array + x-go-name: Result + type: object + describeDeviceTypes: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/DeviceTypeList' + type: object + describeDevices: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/DeviceList' + type: object + describeIdc: + description: A DescribeIdcResult is an response struct that is used to describe idc. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/IdcInfo' + type: object + describeIdcs: + description: A DescribIdcsResult is an response struct that is used to describe idcs. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/IdcList' + type: object + describeImage: + description: A DescribeImageResult is an response struct that is used to describe image. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ImageInfo' + type: object + describeImageDeviceTypes: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/DeviceTypeList' + type: object + describeImages: + description: A DescribeImagesResult is an response struct that is used to describe images. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ImageList' + type: object + describeLicenseContent: + description: A DescribeLicenseContentResult is an response struct that is used to describe getuser. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/LicenseContent' + type: object + describeLicenseToken: + description: A DescribeLocalUserResult is an response struct that is used to describe getuser. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/LicenseToken' + type: object + describeLocalUser: + description: A DescribeLocalUserResult is an response struct that is used to describe getuser. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + error: + $ref: '#/definitions/ErrorResponse' + result: + $ref: '#/definitions/UserInfo' + type: object + describeOS: + description: A DescribeOsResult is an response struct that is used to describe os. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/OsInfo' + type: object + describeOSs: + description: A DescribeOssResult is an response struct that is used to describe oss. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/OsList' + type: object + describeProjectInstance: + description: A GetInstanceResult is an response struct that is used to describe instance. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/InstanceInfo' + type: object + describeProjectInstances: + description: A DescribeProjectInstancesResult is an response struct that is used to get instance list. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/InstanceList' + type: object + describeRaid: + description: A GetRaidResult is an response struct that is used to describe raid. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/Raid' + type: object + describeRaids: + description: QueryRaidsAllResult is an response struct that is used to query all raids. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/RaidList' + type: object + describeResources: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + describeRole: + description: A GetRoleResult is an response struct that is used to describe role. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/RoleInfo' + type: object + describeRoles: + description: A GetRoleListResult is an response struct that is used to describe get role list. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/RoleList' + type: object + describeRule: + description: A DescribeRuleResult is an response struct that is used to describe get rule. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/Rule' + type: object + describeRules: + description: A DescribeRuleResult is an response struct that is used to describe get rule. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/RuleList' + type: object + describeUser: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + error: + $ref: '#/definitions/ErrorResponse' + result: + $ref: '#/definitions/UserInfo' + type: object + describeUserAPIKey: + description: A DescribeUserAPIKeyResult is an response struct that is used to describe getapikey. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ApikeyInfo' + type: object + describeUserAPIKeys: + description: A DescribeUserAPIKeysResult is an response struct that is used to describe getapikeylist. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ApikeyList' + type: object + describeUserByName: + description: A GetUserByNameResult is an response struct that is used to describe user. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/UserInfo' + type: object + describeUserProject: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ProjectInfo' + type: object + describeUserProjects: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/ProjectList' + type: object + describeUserSshKey: + description: A DescribeUserSshKeyResult is an response struct that is used to describe sshkey. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/SshkeyInfo' + type: object + describeUserSshKeys: + description: A DescribeUserSshKeysResult is an response struct that is used to describe get sshkey list. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/SshkeyList' + type: object + describeUsers: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/UserList' + type: object + describeVolumesByDeviceType: + description: A DescribeVolumesByDeviceTypeResult is an response struct that is used to describe get sshkey list. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + items: + $ref: '#/definitions/VolumeIt' + type: array + x-go-name: Result + type: object + desrcibeAgentStatus: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/AgentStatusResponse' + type: object + desrcibeTags: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/TagsResponse' + type: object + deviceAssociateDeviceType: + description: A DeviceAssociateDeviceTypeResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + dialMail: + description: A DialMailResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + disableRule: + description: A DisableRuleResult is an response struct that is used to describe create rule result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + dissociatedDeviceType: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + dissociatedImage: + description: A DissociatedImageResult is an response struct that is used to dissociated image result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + editRule: + description: A EditRuleResult is an response struct that is used to describe create rule result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + enableRule: + description: A EnableRuleResult is an response struct that is used to describe create rule result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + getAssociatedDisks: + description: A GetAssociatedDisksResult is an response struct that is used to get instance list by sshkey. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + items: + $ref: '#/definitions/Disk' + type: array + x-go-name: Result + type: object + getInstancesBySshkey: + description: A GetInstancesBySshkeyResult is an response struct that is used to get instance list by sshkey. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/InstancesSshkeyInfoResponse' + type: object + getMessageById: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/MessageWithNextPrev' + type: object + getMessageList: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/MessageList' + type: object + getMessageStatistic: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/MessageStatistic' + type: object + getMessageTypes: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/MessageTypesResp' + type: object + getMonitorData: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + items: + $ref: '#/definitions/DataEveryMetric' + type: array + x-go-name: Result + type: object + hasUnreadMessage: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/HasUnreadMessage' + type: object + lockProjectInstance: + description: A LockProjectInstanceResult is an response struct that is used to describe lock instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + mailDetail: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/Mail' + type: object + modifyDevice: + description: A ModifyDeviceResult is an response struct that is used to describe modify device result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyDeviceType: + description: A ModifyDeviceTypeResult is an response struct that is used to modify device type. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyIdc: + description: A ModifyIdcResult is an response struct that is used to modify idc. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyImage: + description: A ModifyImageResult is an response struct that is used to modify image. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyInstances: + description: A ModifyInstancesResult is an response struct that is used to describe modify instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyLocalUser: + description: A ModifyLocalUserResult is an response struct that is used to describe getuser. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyLocalUserPassword: + description: A ModifyLocalUserPasswordResult is an response struct that is used to describe getuser. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyOS: + description: A ModifyOsResult is an response struct that is used to describe modify os. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyProjectInstance: + description: A ModifyProjectInstanceResult is an response struct that is used to describe modify instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyRaid: + description: A ModifyRaidResult is an response struct that is used to describe modify raid. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyRole: + description: A ModifyRoleResult is an response struct that is used to describe modify role. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyUser: + description: A GetUserResult is an response struct that is used to describe getuser. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyUserApikey: + description: A ModifyUserApikeyResult is an response struct that is used to describe modifyApikey result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyUserProject: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyUserSshkey: + description: A ModifyUserSshkeyResult is an response struct that is used to modify sshkey result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + mountDevice: + description: A MountDeviceResult is an response struct that is used to describe mount device result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + readMessage: + description: A ReadMessageResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + reinstallProjectInstance: + description: A ReinstallProjectInstanceResult is an response struct that is used to describe reinstall instance. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + removeDevice: + description: A RemoveDeviceResult is an response struct that is used to describe restart instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + resetInstanceStatus: + description: A ResetInstanceStatusResult is an response struct that is used to describe restart instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + resetProjectInstancePasswd: + description: A ResetProjectInstancePasswdResult is an response struct that is used to describe reset instance password. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + resetProjectInstancesPasswd: + description: A ResetProjectInstancesPasswdResult is an response struct that is used to describe reset instance password. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + restartInstances: + description: A RestartInstancesResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + restartProjectInstance: + description: A RestartProjectInstanceResult is an response struct that is used to describe restart instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + saveIsPushMail: + description: A SaveIsPushMailResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + shareUserProject: + description: A ShareUserProjectResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + startInstances: + description: A StartInstancesResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + startProjectInstance: + description: A StartProjectInstanceResult is an response struct that is used to describe start instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + stopInstances: + description: A StopInstancesResult is an response struct + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + stopProjectInstance: + description: A StopProjectInstanceResult is an response struct that is used to describe stop instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + unLockProjectInstance: + description: A UnLockProjectInstanceResult is an response struct that is used to describe unlock instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + unMountDevice: + description: A UnMountDeviceResult is an response struct that is used to unmount device. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + uploadLicense: + description: A UploadLicenseResult is an response struct that is used to describe modify instance result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + verifyUser: + description: A VerifyUserResult is an response struct that is used to describe verify user result. + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object +schemes: + - http +security: + - api_key: [] +securityDefinitions: + api_key: + in: header + name: bmp-ak + type: apiKey +swagger: "2.0" +x-meta-array: + - value1 + - value2 +x-meta-array-obj: + - name: obj + value: field +x-meta-value: value diff --git a/bmp-openapi/swagger_gen.sh b/bmp-openapi/swagger_gen.sh new file mode 100644 index 0000000..3e4c65a --- /dev/null +++ b/bmp-openapi/swagger_gen.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +# install goswagger: https://goswagger.io/install.html#Installing%20from%20source + +swagger version +\rm ./swagger.yml | swagger generate spec -o ./swagger.yml +# swagger validate ./swagger.yml goswagger有缺陷,且报错无法提供有效信息,建议使用https://editor.swagger.io/来校验 +# validate 和 generate命令在0.25.0版本有panic,0.30.3版本已修复 +swagger validate swagger.yml +#\rm -rf ../bmp-openapi-sdk/client && \rm -rf ../bmp-openapi-sdk/models +swagger generate client -f swagger.yml --target=../bmp-openapi-sdk diff --git a/bmp-openapi/swagger_gen_from_yml.sh b/bmp-openapi/swagger_gen_from_yml.sh new file mode 100644 index 0000000..5cf4ff0 --- /dev/null +++ b/bmp-openapi/swagger_gen_from_yml.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +# install goswagger: https://goswagger.io/install.html#Installing%20from%20source + +swagger version +# swagger validate ./swagger.yml goswagger有缺陷,且报错无法提供有效信息,建议使用https://editor.swagger.io/来校验 +# validate 和 generate命令在0.25.0版本有panic,0.30.3版本已修复 +swagger validate swagger.yml +\rm -rf ../bmp-openapi-sdk/client && \rm -rf ../bmp-openapi-sdk/models +swagger generate client -f swagger.yml --target=../bmp-openapi-sdk diff --git a/bmp-openapi/swagger_gen_json.sh b/bmp-openapi/swagger_gen_json.sh new file mode 100644 index 0000000..526b128 --- /dev/null +++ b/bmp-openapi/swagger_gen_json.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +# install goswagger: https://goswagger.io/install.html#Installing%20from%20source + +swagger version +\rm ./swagger.json | swagger generate spec -o ./swagger.json +# swagger validate ./swagger.yml goswagger有缺陷,且报错无法提供有效信息,建议使用https://editor.swagger.io/来校验 +# validate 和 generate命令在0.25.0版本有panic,0.30.3版本已修复 +swagger validate swagger.json +#\rm -rf ../bmp-openapi-sdk/client && \rm -rf ../bmp-openapi-sdk/models +#swagger generate client -f swagger.yml --target=../bmp-openapi-sdk diff --git a/bmp-openapi/swaggermodels/AddRuleRequest.go b/bmp-openapi/swaggermodels/AddRuleRequest.go new file mode 100644 index 0000000..4ca2f82 --- /dev/null +++ b/bmp-openapi/swaggermodels/AddRuleRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters addRule +type AddRuleRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.AddRuleRequest +} diff --git a/bmp-openapi/swaggermodels/AddRuleResult.go b/bmp-openapi/swaggermodels/AddRuleResult.go new file mode 100644 index 0000000..8bd8547 --- /dev/null +++ b/bmp-openapi/swaggermodels/AddRuleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A AddRuleResult is an response struct that is used to describe create rule result. +// swagger:response addRule +type AddRuleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/AssociateDeviceDisksRequest.go b/bmp-openapi/swaggermodels/AssociateDeviceDisksRequest.go new file mode 100644 index 0000000..e0714cd --- /dev/null +++ b/bmp-openapi/swaggermodels/AssociateDeviceDisksRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters associateDeviceDisks +type AssociateDeviceDisksRequest struct { + WriteRequestHeader + + // in: body + Body requestTypes.AssociateDeviceDisksRequest +} diff --git a/bmp-openapi/swaggermodels/AssociateDeviceDisksResult.go b/bmp-openapi/swaggermodels/AssociateDeviceDisksResult.go new file mode 100644 index 0000000..c61d786 --- /dev/null +++ b/bmp-openapi/swaggermodels/AssociateDeviceDisksResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response associateDeviceDisks +type AssociateDeviceDisksResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/AssociatedDeviceTypeRequest.go b/bmp-openapi/swaggermodels/AssociatedDeviceTypeRequest.go new file mode 100644 index 0000000..b5800d6 --- /dev/null +++ b/bmp-openapi/swaggermodels/AssociatedDeviceTypeRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters associatedDeviceType +type AssociatedDeviceTypeRequest struct { + WriteRequestHeader + + // in: body + Body requestTypes.AssociateDeviceTypeRequest +} diff --git a/bmp-openapi/swaggermodels/AssociatedDeviceTypeResult.go b/bmp-openapi/swaggermodels/AssociatedDeviceTypeResult.go new file mode 100644 index 0000000..7be1bec --- /dev/null +++ b/bmp-openapi/swaggermodels/AssociatedDeviceTypeResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response associatedDeviceType +type AssociatedDeviceTypeResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/AssociatedImageRequest.go b/bmp-openapi/swaggermodels/AssociatedImageRequest.go new file mode 100644 index 0000000..93d5ef6 --- /dev/null +++ b/bmp-openapi/swaggermodels/AssociatedImageRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters associatedImage +type AssociatedImageRequest struct { + WriteRequestHeader + + // in: body + Body requestTypes.AssociateImageRequest +} diff --git a/bmp-openapi/swaggermodels/AssociatedImageResult.go b/bmp-openapi/swaggermodels/AssociatedImageResult.go new file mode 100644 index 0000000..6f82563 --- /dev/null +++ b/bmp-openapi/swaggermodels/AssociatedImageResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A AssociatedImageResult is an response struct that is used to associated image result. +// swagger:response associatedImage +type AssociatedImageResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/CancelShareUserProjectRequest.go b/bmp-openapi/swaggermodels/CancelShareUserProjectRequest.go new file mode 100644 index 0000000..b45ad87 --- /dev/null +++ b/bmp-openapi/swaggermodels/CancelShareUserProjectRequest.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters cancelShareUserProject +type CancelShareUserProjectRequest struct { + WriteRequestHeader + // in: path + ProjectID string `json:"project_id"` + // in: body + Body requestTypes.ShareProjectRequest +} diff --git a/bmp-openapi/swaggermodels/CancelShareUserProjectResult.go b/bmp-openapi/swaggermodels/CancelShareUserProjectResult.go new file mode 100644 index 0000000..b1e3770 --- /dev/null +++ b/bmp-openapi/swaggermodels/CancelShareUserProjectResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A CancelShareUserProjectResult is an response struct +// swagger:response cancelShareUserProject +type CancelShareUserProjectResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/CollectDeviceInfoRequest.go b/bmp-openapi/swaggermodels/CollectDeviceInfoRequest.go new file mode 100644 index 0000000..d640960 --- /dev/null +++ b/bmp-openapi/swaggermodels/CollectDeviceInfoRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters collectDeviceInfo +type CollectDeviceInfoRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CollectDeviceInfoRequest +} diff --git a/bmp-openapi/swaggermodels/CollectDeviceInfoResult.go b/bmp-openapi/swaggermodels/CollectDeviceInfoResult.go new file mode 100644 index 0000000..f8d24ec --- /dev/null +++ b/bmp-openapi/swaggermodels/CollectDeviceInfoResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response collectDeviceInfo +type CollectDeviceInfoResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/Common.go b/bmp-openapi/swaggermodels/Common.go new file mode 100644 index 0000000..31f8573 --- /dev/null +++ b/bmp-openapi/swaggermodels/Common.go @@ -0,0 +1,61 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/controllers" +) + +type ReadRequestHeader struct { + // 流量唯一id + // required: true + // in: header + TraceID string `json:"traceId"` + // demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + // required: true + // in: header + Authorization string `json:"authorization"` + // 用户uuid, deprecated + // in: header + BmpUserID string `json:"bmpUserId"` + // 用户语言 [zh_CN, en_US] + // in: header + BmpLanguage string `json:"bmpLanguage"` +} + +type WriteRequestHeader struct { + // 流量唯一id + // required: true + // in: header + TraceID string `json:"traceId"` + // demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + // required: true + // in: header + Authorization string `json:"authorization"` + // 用户uuid + // in: header + BmpUserID string `json:"bmpUserId"` + // 用户语言 [zh_CN, en_US] + // in: header + BmpLanguage string `json:"bmpLanguage"` +} + +// unit err response for non 200 +// swagger:response ErrorResponse +type ErrorResponse struct { + ResponseHeader + //In: body + Body struct { + // 错误信息 + // required: true + Err controllers.ErrorResponse `json:"error"` + // 流量ID + // required: true + RequestId string `json:"requestId"` + } +} + +// 返回body里面的公共字段 +type ResponseHeader struct { + // 流量ID + // in: header + TraceID string `json:"traceId"` +} diff --git a/bmp-openapi/swaggermodels/CreateDeviceRequest.go b/bmp-openapi/swaggermodels/CreateDeviceRequest.go new file mode 100644 index 0000000..c83431f --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateDeviceRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createDevice +type CreateDeviceRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateDevicesRequest +} diff --git a/bmp-openapi/swaggermodels/CreateDeviceResult.go b/bmp-openapi/swaggermodels/CreateDeviceResult.go new file mode 100644 index 0000000..18615dd --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateDeviceResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response createDevice +type CreateDeviceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/CreateDeviceTypeRaidRequest.go b/bmp-openapi/swaggermodels/CreateDeviceTypeRaidRequest.go new file mode 100644 index 0000000..393075a --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateDeviceTypeRaidRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createDeviceTypeRaid +type CreateDeviceTypeRaidRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateDeviceTypeRaidRequest +} diff --git a/bmp-openapi/swaggermodels/CreateDeviceTypeRaidResult.go b/bmp-openapi/swaggermodels/CreateDeviceTypeRaidResult.go new file mode 100644 index 0000000..bd306db --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateDeviceTypeRaidResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A CreateDeviceTypeRaidResult is an response struct that is used to describe create device type raid result. +// swagger:response createDeviceTypeRaid +type CreateDeviceTypeRaidResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/CreateDeviceTypeRequest.go b/bmp-openapi/swaggermodels/CreateDeviceTypeRequest.go new file mode 100644 index 0000000..db8a374 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateDeviceTypeRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createDeviceType +type CreateDeviceTypeRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateDeviceTypeRequest +} diff --git a/bmp-openapi/swaggermodels/CreateDeviceTypeResult.go b/bmp-openapi/swaggermodels/CreateDeviceTypeResult.go new file mode 100644 index 0000000..2bfc3d5 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateDeviceTypeResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A CreateDeviceTypeResult is an response struct that is used to describe create deviceType result. +// swagger:response createDeviceType +type CreateDeviceTypeResult struct { + ResponseHeader + // in: body + Body struct { + Result response.DeviceTypeId `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/CreateIdcRequest.go b/bmp-openapi/swaggermodels/CreateIdcRequest.go new file mode 100644 index 0000000..d6298d9 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateIdcRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createIdc +type CreateIdcRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateIdcRequest +} diff --git a/bmp-openapi/swaggermodels/CreateIdcResult.go b/bmp-openapi/swaggermodels/CreateIdcResult.go new file mode 100644 index 0000000..79539f3 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateIdcResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A CreateIdcResult is an response struct that is used to describe create idc result. +// swagger:response createIdc +type CreateIdcResult struct { + ResponseHeader + // in: body + Body struct { + Result response.IdcID `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/CreateImageRequest.go b/bmp-openapi/swaggermodels/CreateImageRequest.go new file mode 100644 index 0000000..f5df525 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateImageRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createImage +type CreateImageRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateImageRequest +} diff --git a/bmp-openapi/swaggermodels/CreateImageResult.go b/bmp-openapi/swaggermodels/CreateImageResult.go new file mode 100644 index 0000000..cad0a81 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateImageResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A CreateImageResult is an response struct that is used to describe create image result. +// swagger:response createImage +type CreateImageResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ImageId `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/CreateOsRequest.go b/bmp-openapi/swaggermodels/CreateOsRequest.go new file mode 100644 index 0000000..cc8dd92 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateOsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createOS +type CreateOsRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateOSRequest +} diff --git a/bmp-openapi/swaggermodels/CreateOsResult.go b/bmp-openapi/swaggermodels/CreateOsResult.go new file mode 100644 index 0000000..1f5dcb4 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateOsResult.go @@ -0,0 +1,13 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// A CreateOsResult is an response struct that is used to describe create os result. +// swagger:response createOS +type CreateOsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.OsId `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/CreateProjectInstanceRequest.go b/bmp-openapi/swaggermodels/CreateProjectInstanceRequest.go new file mode 100644 index 0000000..4689422 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateProjectInstanceRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createProjectInstance +type CreateProjectInstanceRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateInstanceRequest +} diff --git a/bmp-openapi/swaggermodels/CreateProjectInstanceResult.go b/bmp-openapi/swaggermodels/CreateProjectInstanceResult.go new file mode 100644 index 0000000..d8adc16 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A CreateProjectInstanceResult is an response struct that is used to describe create instance result. +// swagger:response createProjectInstance +type CreateProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.InstanceIds `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/CreateRaidRequest.go b/bmp-openapi/swaggermodels/CreateRaidRequest.go new file mode 100644 index 0000000..81a12f0 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateRaidRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createRaid +type CreateRaidRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateRaidRequest +} diff --git a/bmp-openapi/swaggermodels/CreateRaidResult.go b/bmp-openapi/swaggermodels/CreateRaidResult.go new file mode 100644 index 0000000..a5fbb70 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateRaidResult.go @@ -0,0 +1,13 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// A CreateRaidResult is an response struct that is used to describe create raid result. +// swagger:response createRaid +type CreateRaidResult struct { + ResponseHeader + // in: body + Body struct { + Result response.RaidId `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/CreateRoleRequest.go b/bmp-openapi/swaggermodels/CreateRoleRequest.go new file mode 100644 index 0000000..1787891 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateRoleRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createRole +type CreateRoleRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateRoleRequest +} diff --git a/bmp-openapi/swaggermodels/CreateRoleResult.go b/bmp-openapi/swaggermodels/CreateRoleResult.go new file mode 100644 index 0000000..7937cd2 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateRoleResult.go @@ -0,0 +1,13 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// A CreateRoleResult is an response struct that is used to describe create role result. +// swagger:response createRole +type CreateRoleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.RoleId `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/CreateUserApikeyRequest.go b/bmp-openapi/swaggermodels/CreateUserApikeyRequest.go new file mode 100644 index 0000000..3f6740c --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateUserApikeyRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createUserApikey +type CreateUserApikeyRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateApikeyRequest +} diff --git a/bmp-openapi/swaggermodels/CreateUserApikeyResult.go b/bmp-openapi/swaggermodels/CreateUserApikeyResult.go new file mode 100644 index 0000000..0c2ace6 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateUserApikeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A CreateUserApikeyResult is an response struct that is used to describe create apikey result. +// swagger:response createUserApikey +type CreateUserApikeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ApikeyId `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/CreateUserProjectRequest.go b/bmp-openapi/swaggermodels/CreateUserProjectRequest.go new file mode 100644 index 0000000..3af1e8d --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateUserProjectRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createUserProject +type CreateUserProjectRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateProjectRequest +} diff --git a/bmp-openapi/swaggermodels/CreateUserProjectResult.go b/bmp-openapi/swaggermodels/CreateUserProjectResult.go new file mode 100644 index 0000000..eb8a0b4 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateUserProjectResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// swagger:response createUserProject +type CreateUserProjectResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ProjectId `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/CreateUserRequest.go b/bmp-openapi/swaggermodels/CreateUserRequest.go new file mode 100644 index 0000000..a478a32 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateUserRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createUser +type CreateUserRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateUserRequest +} diff --git a/bmp-openapi/swaggermodels/CreateUserResult.go b/bmp-openapi/swaggermodels/CreateUserResult.go new file mode 100644 index 0000000..dfebe91 --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateUserResult.go @@ -0,0 +1,13 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// A CreateInstancesResult is an response struct that is used to describe create instance result. +// swagger:response createUser +type CreateUserResult struct { + ResponseHeader + // in: body + Body struct { + Result response.UserId `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/CreateUserSshkeyRequest.go b/bmp-openapi/swaggermodels/CreateUserSshkeyRequest.go new file mode 100644 index 0000000..208a99f --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateUserSshkeyRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters createUserSshkey +type CreateUserSshkeyRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.CreateSshkeyRequest +} diff --git a/bmp-openapi/swaggermodels/CreateUserSshkeyResult.go b/bmp-openapi/swaggermodels/CreateUserSshkeyResult.go new file mode 100644 index 0000000..c84557f --- /dev/null +++ b/bmp-openapi/swaggermodels/CreateUserSshkeyResult.go @@ -0,0 +1,13 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// A CreateUserSshkeyResult is an response struct that is used to describe create sshkey result. +// swagger:response createUserSshkey +type CreateUserSshkeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.SshkeyId `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/CurrentRoleRequest.go b/bmp-openapi/swaggermodels/CurrentRoleRequest.go new file mode 100644 index 0000000..349db0b --- /dev/null +++ b/bmp-openapi/swaggermodels/CurrentRoleRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters currentRole +type CurrentRoleRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi/swaggermodels/CurrentRoleResult.go b/bmp-openapi/swaggermodels/CurrentRoleResult.go new file mode 100644 index 0000000..23f3ea6 --- /dev/null +++ b/bmp-openapi/swaggermodels/CurrentRoleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A CurrentRoleResult is an response struct that is used to describe role. +// swagger:response currentRole +type CurrentRoleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.RoleInfo `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteAlertRequest.go b/bmp-openapi/swaggermodels/DeleteAlertRequest.go new file mode 100644 index 0000000..f72819c --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteAlertRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters deleteAlert +type DeleteAlertRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.DeleteAlertRequest +} diff --git a/bmp-openapi/swaggermodels/DeleteAlertResult.go b/bmp-openapi/swaggermodels/DeleteAlertResult.go new file mode 100644 index 0000000..1029c1f --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteAlertResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteAlertResult is an response struct that is used to describe create alert result. +// swagger:response deleteAlert +type DeleteAlertResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteDeviceRequest.go b/bmp-openapi/swaggermodels/DeleteDeviceRequest.go new file mode 100644 index 0000000..3780567 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteDeviceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteDevice +type DeleteDeviceRequest struct { + WriteRequestHeader + + // in: path + DeviceID string `json:"device_id"` +} diff --git a/bmp-openapi/swaggermodels/DeleteDeviceResult.go b/bmp-openapi/swaggermodels/DeleteDeviceResult.go new file mode 100644 index 0000000..149432b --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteDeviceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteDeviceResult is an response struct that is used to describe delete device result. +// swagger:response deleteDevice +type DeleteDeviceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteDeviceTypeRaidRequest.go b/bmp-openapi/swaggermodels/DeleteDeviceTypeRaidRequest.go new file mode 100644 index 0000000..acd280b --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteDeviceTypeRaidRequest.go @@ -0,0 +1,11 @@ +package swaggermodels + +import requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + +// swagger:parameters deleteDeviceTypeRaid +type DeleteDeviceTypeRaid struct { + WriteRequestHeader + + // in:body + Body requestTypes.DeleteDeviceTypeRaidRequest +} diff --git a/bmp-openapi/swaggermodels/DeleteDeviceTypeRaidResult.go b/bmp-openapi/swaggermodels/DeleteDeviceTypeRaidResult.go new file mode 100644 index 0000000..9ea51bf --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteDeviceTypeRaidResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteDeviceTypeRaidResult is an response struct that is used to describe delete device type raid result. +// swagger:response deleteDeviceTypeRaid +type DeleteDeviceTypeRaidResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteDeviceTypeRequest.go b/bmp-openapi/swaggermodels/DeleteDeviceTypeRequest.go new file mode 100644 index 0000000..f21f880 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteDeviceTypeRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteDeviceType +type DeleteDeviceTypeRequest struct { + WriteRequestHeader + + // in: path + DeviceTypeID string `json:"device_type_id"` +} diff --git a/bmp-openapi/swaggermodels/DeleteDeviceTypeResult.go b/bmp-openapi/swaggermodels/DeleteDeviceTypeResult.go new file mode 100644 index 0000000..4e6b121 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteDeviceTypeResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteDeviceTypeResult is an response struct that is used to delete device type. +// swagger:response deleteDeviceType +type DeleteDeviceTypeResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteIdcRequest.go b/bmp-openapi/swaggermodels/DeleteIdcRequest.go new file mode 100644 index 0000000..2176ff6 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteIdcRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteIdc +type DeleteIdcRequest struct { + WriteRequestHeader + + // in: path + IdcID string `json:"idc_id"` +} diff --git a/bmp-openapi/swaggermodels/DeleteIdcResult.go b/bmp-openapi/swaggermodels/DeleteIdcResult.go new file mode 100644 index 0000000..9bffe21 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteIdcResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteIdcResult is an response struct that is used to delete idc. +// swagger:response deleteIdc +type DeleteIdcResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteImageRequest.go b/bmp-openapi/swaggermodels/DeleteImageRequest.go new file mode 100644 index 0000000..c24aa9a --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteImageRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteImage +type DeleteImageRequest struct { + WriteRequestHeader + + // in: path + ImageID string `json:"image_id"` +} diff --git a/bmp-openapi/swaggermodels/DeleteImageResult.go b/bmp-openapi/swaggermodels/DeleteImageResult.go new file mode 100644 index 0000000..19ea135 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteImageResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteImageResult is an response struct that is used to delete image. +// swagger:response deleteImage +type DeleteImageResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteInstancesRequest.go b/bmp-openapi/swaggermodels/DeleteInstancesRequest.go new file mode 100644 index 0000000..58eac32 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteInstancesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters deleteInstances +type DeleteInstancesRequest struct { + ReadRequestHeader + + // in: body + Body requestTypes.DeleteInstancesRequest +} diff --git a/bmp-openapi/swaggermodels/DeleteInstancesResult.go b/bmp-openapi/swaggermodels/DeleteInstancesResult.go new file mode 100644 index 0000000..304a49a --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteInstancesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteInstancesResult is an response struct that is used to describe modify instance result. +// swagger:response deleteInstances +type DeleteInstancesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteMessageRequest.go b/bmp-openapi/swaggermodels/DeleteMessageRequest.go new file mode 100644 index 0000000..81d7bf9 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteMessageRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters deleteMessage +type DeleteMessageRequest struct { + WriteRequestHeader + + // in: body + Body requestTypes.DeleteMessagesRequest +} diff --git a/bmp-openapi/swaggermodels/DeleteMessageResult.go b/bmp-openapi/swaggermodels/DeleteMessageResult.go new file mode 100644 index 0000000..fde37dc --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteMessageResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteMessageResult is an response struct +// swagger:response deleteMessage +type DeleteMessageResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteOsRequest.go b/bmp-openapi/swaggermodels/DeleteOsRequest.go new file mode 100644 index 0000000..38c5a69 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteOsRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteOS +type DeleteOsRequest struct { + WriteRequestHeader + + // in: path + OsID string `json:"os_id"` +} diff --git a/bmp-openapi/swaggermodels/DeleteOsResult.go b/bmp-openapi/swaggermodels/DeleteOsResult.go new file mode 100644 index 0000000..ef5b26f --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteOsResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteOsResult is an response struct that is used to delete stop os result. +// swagger:response deleteOS +type DeleteOsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteProjectInstanceRequest.go b/bmp-openapi/swaggermodels/DeleteProjectInstanceRequest.go new file mode 100644 index 0000000..9b34ac5 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteProjectInstanceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteProjectInstance +type DeleteProjectInstanceRequest struct { + WriteRequestHeader + + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi/swaggermodels/DeleteProjectInstanceResult.go b/bmp-openapi/swaggermodels/DeleteProjectInstanceResult.go new file mode 100644 index 0000000..2abc940 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteProjectInstanceResult is an response struct that is used to delete stop instance result. +// swagger:response deleteProjectInstance +type DeleteProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteRaidRequest.go b/bmp-openapi/swaggermodels/DeleteRaidRequest.go new file mode 100644 index 0000000..0e49418 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteRaidRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteRaid +type DeleteRaidRequest struct { + WriteRequestHeader + + // in: path + RaidID string `json:"raid_id"` +} diff --git a/bmp-openapi/swaggermodels/DeleteRaidResult.go b/bmp-openapi/swaggermodels/DeleteRaidResult.go new file mode 100644 index 0000000..5fd8899 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteRaidResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteRaidResult is an response struct that is used to delete raid. +// swagger:response deleteRaid +type DeleteRaidResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteRoleRequest.go b/bmp-openapi/swaggermodels/DeleteRoleRequest.go new file mode 100644 index 0000000..e2b5367 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteRoleRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteRole +type DeleteRoleRequest struct { + WriteRequestHeader + + // in: path + RoleID string `json:"role_id"` +} diff --git a/bmp-openapi/swaggermodels/DeleteRoleResult.go b/bmp-openapi/swaggermodels/DeleteRoleResult.go new file mode 100644 index 0000000..5c22205 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteRoleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteRoleResult is an response struct that is used to delete role. +// swagger:response deleteRole +type DeleteRoleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteRuleRequest.go b/bmp-openapi/swaggermodels/DeleteRuleRequest.go new file mode 100644 index 0000000..c42df6d --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteRuleRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters deleteRule +type DeleteRuleRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.DeleteRuleRequest +} diff --git a/bmp-openapi/swaggermodels/DeleteRuleResult.go b/bmp-openapi/swaggermodels/DeleteRuleResult.go new file mode 100644 index 0000000..8175161 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteRuleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteRuleResult is an response struct that is used to describe create rule result. +// swagger:response deleteRule +type DeleteRuleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteUserApikeyRequest.go b/bmp-openapi/swaggermodels/DeleteUserApikeyRequest.go new file mode 100644 index 0000000..ded116b --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteUserApikeyRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteUserApikey +type DeleteUserApikeyRequest struct { + WriteRequestHeader + + // in: path + ApikeyID string `json:"apikey_id"` +} diff --git a/bmp-openapi/swaggermodels/DeleteUserApikeyResult.go b/bmp-openapi/swaggermodels/DeleteUserApikeyResult.go new file mode 100644 index 0000000..f36d2ba --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteUserApikeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteUserApikeyResult is an response struct that is used to describe delete Apikey result. +// swagger:response deleteUserApikey +type DeleteUserApikeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteUserProjectRequest.go b/bmp-openapi/swaggermodels/DeleteUserProjectRequest.go new file mode 100644 index 0000000..b3ded70 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteUserProjectRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteUserProject +type DeleteUserProjectRequest struct { + WriteRequestHeader + + // in: path + ProjectID string `json:"project_id"` +} diff --git a/bmp-openapi/swaggermodels/DeleteUserProjectResult.go b/bmp-openapi/swaggermodels/DeleteUserProjectResult.go new file mode 100644 index 0000000..17fe5b9 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteUserProjectResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response deleteUserProject +type DeleteUserProjectResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteUserRequest.go b/bmp-openapi/swaggermodels/DeleteUserRequest.go new file mode 100644 index 0000000..7436d5f --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteUserRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteUser +type DeleteUserRequest struct { + WriteRequestHeader + + // in: path + UserID string `json:"user_id"` +} diff --git a/bmp-openapi/swaggermodels/DeleteUserResult.go b/bmp-openapi/swaggermodels/DeleteUserResult.go new file mode 100644 index 0000000..695ed14 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteUserResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetUserResult is an response struct that is used to describe getuser. +// swagger:response deleteUser +type DeleteUserResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeleteUserSshkeyRequest.go b/bmp-openapi/swaggermodels/DeleteUserSshkeyRequest.go new file mode 100644 index 0000000..1d5fa9f --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteUserSshkeyRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters deleteUserSshkey +type DeleteUserSshkeyRequest struct { + WriteRequestHeader + + // in: path + SshkeyID string `json:"sshkey_id"` +} diff --git a/bmp-openapi/swaggermodels/DeleteUserSshkeyResult.go b/bmp-openapi/swaggermodels/DeleteUserSshkeyResult.go new file mode 100644 index 0000000..ce05045 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeleteUserSshkeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeleteUserSshkeyResult is an response struct that is used to describe delete sshkey result. +// swagger:response deleteUserSshkey +type DeleteUserSshkeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeAlertRequest.go b/bmp-openapi/swaggermodels/DescribeAlertRequest.go new file mode 100644 index 0000000..e2eb916 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeAlertRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeAlert +type DescribeAlertRequest struct { + ReadRequestHeader + + // in: query + requestTypes.DescribeAlertRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeAlertResult.go b/bmp-openapi/swaggermodels/DescribeAlertResult.go new file mode 100644 index 0000000..e6eaec0 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeAlertResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeAlertResult is an response struct that is used to describe get Alert. +// swagger:response describeAlert +type DescribeAlertResult struct { + ResponseHeader + // in: body + Body struct { + Result response.Alert `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeAlertsRequest.go b/bmp-openapi/swaggermodels/DescribeAlertsRequest.go new file mode 100644 index 0000000..3e9e4af --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeAlertsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeAlerts +type DescribeAlertsRequest struct { + ReadRequestHeader + + // in: query + requestTypes.DescribeAlertsRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeAlertsResult.go b/bmp-openapi/swaggermodels/DescribeAlertsResult.go new file mode 100644 index 0000000..33be981 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeAlertsResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeAlertsResult is an response struct that is used to describe get Alert. +// swagger:response describeAlerts +type DescribeAlertsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.AlertList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeAuditLogTypesRequest.go b/bmp-openapi/swaggermodels/DescribeAuditLogTypesRequest.go new file mode 100644 index 0000000..7d56f67 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeAuditLogTypesRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters describeAuditLogTypes +type DescribeAuditLogTypesRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi/swaggermodels/DescribeAuditLogTypesResult.go b/bmp-openapi/swaggermodels/DescribeAuditLogTypesResult.go new file mode 100644 index 0000000..29be235 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeAuditLogTypesResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeAuditLogTypes +type DescribeAuditLogTypesResult struct { + ResponseHeader + // in: body + Body struct { + Result []response.AuditLogsType `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeAuditLogsRequest.go b/bmp-openapi/swaggermodels/DescribeAuditLogsRequest.go new file mode 100644 index 0000000..c34f18d --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeAuditLogsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeAuditLogs +type DescribeAuditLogsRequest struct { + ReadRequestHeader + + // in: query + requestTypes.DescribeAuditLogsRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeAuditLogsResult.go b/bmp-openapi/swaggermodels/DescribeAuditLogsResult.go new file mode 100644 index 0000000..adced77 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeAuditLogsResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeAuditLogs +type DescribeAuditLogsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.AuditLogList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceDisksRequest.go b/bmp-openapi/swaggermodels/DescribeDeviceDisksRequest.go new file mode 100644 index 0000000..ca0cafb --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceDisksRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeDeviceDisks +type DescribeDeviceDisksRequest struct { + ReadRequestHeader + + // in: path + DeviceID string `json:"device_id"` +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceDisksResult.go b/bmp-openapi/swaggermodels/DescribeDeviceDisksResult.go new file mode 100644 index 0000000..6a64b9a --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceDisksResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeDeviceDisks +type DescribeDeviceDisksResult struct { + ResponseHeader + // in: body + Body struct { + Result response.DeviceDisks `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceRequest.go b/bmp-openapi/swaggermodels/DescribeDeviceRequest.go new file mode 100644 index 0000000..8adad9e --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeDevice +type DescribeDeviceRequest struct { + ReadRequestHeader + + // in: path + DeviceID string `json:"device_id"` +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceResult.go b/bmp-openapi/swaggermodels/DescribeDeviceResult.go new file mode 100644 index 0000000..cf319e1 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeDevice +type DescribeDeviceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.DeviceInfo `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceStockRequest.go b/bmp-openapi/swaggermodels/DescribeDeviceStockRequest.go new file mode 100644 index 0000000..b65a0e4 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceStockRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeDeviceStock +type DescribeDeviceStockRequest struct { + ReadRequestHeader + + // in: query + DeviceTypeID string `json:"deviceTypeId"` +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceStockResult.go b/bmp-openapi/swaggermodels/DescribeDeviceStockResult.go new file mode 100644 index 0000000..f632dfe --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceStockResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetDeviceStockResult is an response struct that is used to get device stock. +// swagger:response describeDeviceStock +type DescribeDeviceStockResult struct { + ResponseHeader + // in: body + Body struct { + Result response.DeviceStock `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceTypeImagePartitionsRequest.go b/bmp-openapi/swaggermodels/DescribeDeviceTypeImagePartitionsRequest.go new file mode 100644 index 0000000..ebd7fe8 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceTypeImagePartitionsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeDeviceTypeImagePartitions +type DescribeDeviceTypeImagePartitionsRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryDeviceTypeImagePartitionRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceTypeImagePartitionsResult.go b/bmp-openapi/swaggermodels/DescribeDeviceTypeImagePartitionsResult.go new file mode 100644 index 0000000..62a2ef2 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceTypeImagePartitionsResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeDeviceTypeImagePartitions +type DescribeDeviceTypeImagePartitionsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.QueryDeviceTypeImagePartitionResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceTypeImagesRequest.go b/bmp-openapi/swaggermodels/DescribeDeviceTypeImagesRequest.go new file mode 100644 index 0000000..979bfec --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceTypeImagesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeDeviceTypeImages +type DescribeDeviceTypeImagesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryDeviceTypeImageRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceTypeImagesResult.go b/bmp-openapi/swaggermodels/DescribeDeviceTypeImagesResult.go new file mode 100644 index 0000000..c11584a --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceTypeImagesResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeDeviceTypeImages +type DescribeDeviceTypeImagesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ImageList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceTypeRaidsRequest.go b/bmp-openapi/swaggermodels/DescribeDeviceTypeRaidsRequest.go new file mode 100644 index 0000000..fe36452 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceTypeRaidsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeDeviceTypeRaids +type DescribeDeviceTypeRaidsRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryDeviceTypeRaidRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceTypeRaidsResult.go b/bmp-openapi/swaggermodels/DescribeDeviceTypeRaidsResult.go new file mode 100644 index 0000000..1675d18 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceTypeRaidsResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeDeviceTypeRaids +type DescribeDeviceTypeRaidsResult struct { + ResponseHeader + // in: body + Body struct { + Result []*response.RDeviceTypeRaid `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceTypeRequest.go b/bmp-openapi/swaggermodels/DescribeDeviceTypeRequest.go new file mode 100644 index 0000000..f899cba --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceTypeRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeDeviceType +type DescribeDeviceTypeRequest struct { + ReadRequestHeader + + // in: path + DeviceTypeID string `json:"device_type_id"` +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceTypeResult.go b/bmp-openapi/swaggermodels/DescribeDeviceTypeResult.go new file mode 100644 index 0000000..96448e7 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceTypeResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeDeviceType +type DescribeDeviceTypeResult struct { + ResponseHeader + // in: body + Body struct { + Result response.DeviceTypeInfo `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceTypesRequest.go b/bmp-openapi/swaggermodels/DescribeDeviceTypesRequest.go new file mode 100644 index 0000000..00c50c0 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceTypesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeDeviceTypes +type DescribeDeviceTypesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryDeviceTypesRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeDeviceTypesResult.go b/bmp-openapi/swaggermodels/DescribeDeviceTypesResult.go new file mode 100644 index 0000000..7a7f1b1 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDeviceTypesResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeDeviceTypes +type DescribeDeviceTypesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.DeviceTypeList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeDevicesRequest.go b/bmp-openapi/swaggermodels/DescribeDevicesRequest.go new file mode 100644 index 0000000..1ded9a7 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDevicesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeDevices +type DescribeDevicesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryDevicesRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeDevicesResult.go b/bmp-openapi/swaggermodels/DescribeDevicesResult.go new file mode 100644 index 0000000..76700e6 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeDevicesResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeDevices +type DescribeDevicesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.DeviceList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeIdcRequest.go b/bmp-openapi/swaggermodels/DescribeIdcRequest.go new file mode 100644 index 0000000..9b4d158 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeIdcRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeIdc +type DescribeIdcRequest struct { + ReadRequestHeader + + // in: path + IdcID string `json:"idc_id"` +} diff --git a/bmp-openapi/swaggermodels/DescribeIdcResult.go b/bmp-openapi/swaggermodels/DescribeIdcResult.go new file mode 100644 index 0000000..88de6d4 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeIdcResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeIdcResult is an response struct that is used to describe idc. +// swagger:response describeIdc +type DescribeIdcResult struct { + ResponseHeader + // in: body + Body struct { + Result response.IdcInfo `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeIdcsRequest.go b/bmp-openapi/swaggermodels/DescribeIdcsRequest.go new file mode 100644 index 0000000..cc49dfa --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeIdcsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeIdcs +type DescribIdcsRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryIdcsRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeIdcsResult.go b/bmp-openapi/swaggermodels/DescribeIdcsResult.go new file mode 100644 index 0000000..fca09c2 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeIdcsResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribIdcsResult is an response struct that is used to describe idcs. +// swagger:response describeIdcs +type DescribIdcsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.IdcList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeImageDeviceTypesRequest.go b/bmp-openapi/swaggermodels/DescribeImageDeviceTypesRequest.go new file mode 100644 index 0000000..2ff4e7b --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeImageDeviceTypesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeImageDeviceTypes +type DescribeImageDeviceTypesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryImageDeviceTypesRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeImageDeviceTypesResult.go b/bmp-openapi/swaggermodels/DescribeImageDeviceTypesResult.go new file mode 100644 index 0000000..27dc379 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeImageDeviceTypesResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeImageDeviceTypes +type DescribeImageDeviceTypesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.DeviceTypeList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeImageRequest.go b/bmp-openapi/swaggermodels/DescribeImageRequest.go new file mode 100644 index 0000000..4a83942 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeImageRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeImage +type DescribeImageRequest struct { + ReadRequestHeader + + // in: path + ImageID string `json:"image_id"` +} diff --git a/bmp-openapi/swaggermodels/DescribeImageResult.go b/bmp-openapi/swaggermodels/DescribeImageResult.go new file mode 100644 index 0000000..9fa9d20 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeImageResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeImageResult is an response struct that is used to describe image. +// swagger:response describeImage +type DescribeImageResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ImageInfo `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeImagesRequest.go b/bmp-openapi/swaggermodels/DescribeImagesRequest.go new file mode 100644 index 0000000..0479001 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeImagesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeImages +type DescribeImagesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryImagesRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeImagesResult.go b/bmp-openapi/swaggermodels/DescribeImagesResult.go new file mode 100644 index 0000000..b99f619 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeImagesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeImagesResult is an response struct that is used to describe images. +// swagger:response describeImages +type DescribeImagesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ImageList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeLicenseContentResult.go b/bmp-openapi/swaggermodels/DescribeLicenseContentResult.go new file mode 100644 index 0000000..72e2ba3 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeLicenseContentResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeLicenseContentResult is an response struct that is used to describe getuser. +// swagger:response describeLicenseContent +type DescribeLicenseContentResult struct { + ResponseHeader + // in: body + Body struct { + Result response.LicenseContent `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeLicenseTokenRequest.go b/bmp-openapi/swaggermodels/DescribeLicenseTokenRequest.go new file mode 100644 index 0000000..e7d0137 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeLicenseTokenRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters describeLicenseToken +type DescribeLicenseTokenRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi/swaggermodels/DescribeLicenseTokenResult.go b/bmp-openapi/swaggermodels/DescribeLicenseTokenResult.go new file mode 100644 index 0000000..4066a0e --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeLicenseTokenResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeLocalUserResult is an response struct that is used to describe getuser. +// swagger:response describeLicenseToken +type DescribeLicenseTokenResult struct { + ResponseHeader + // in: body + Body struct { + Result response.LicenseToken `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeLocalUserResult.go b/bmp-openapi/swaggermodels/DescribeLocalUserResult.go new file mode 100644 index 0000000..a8d461b --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeLocalUserResult.go @@ -0,0 +1,17 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/controllers" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeLocalUserResult is an response struct that is used to describe getuser. +// swagger:response describeLocalUser +type DescribeLocalUserResult struct { + ResponseHeader + // in: body + Body struct { + Result response.UserInfo `json:"result"` + Err *controllers.ErrorResponse `json:"error"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeOsRequest.go b/bmp-openapi/swaggermodels/DescribeOsRequest.go new file mode 100644 index 0000000..0f41a68 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeOsRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeOS +type DescribeOsRequest struct { + ReadRequestHeader + + // in: path + OsID string `json:"os_id"` +} diff --git a/bmp-openapi/swaggermodels/DescribeOsResult.go b/bmp-openapi/swaggermodels/DescribeOsResult.go new file mode 100644 index 0000000..64d8575 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeOsResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeOsResult is an response struct that is used to describe os. +// swagger:response describeOS +type DescribeOsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.OsInfo `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeOssRequest.go b/bmp-openapi/swaggermodels/DescribeOssRequest.go new file mode 100644 index 0000000..199f8f3 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeOssRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeOSs +type DescribeOssRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryOssRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeOssResult.go b/bmp-openapi/swaggermodels/DescribeOssResult.go new file mode 100644 index 0000000..a3b2c7a --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeOssResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeOssResult is an response struct that is used to describe oss. +// swagger:response describeOSs +type DescribeOssResult struct { + ResponseHeader + // in: body + Body struct { + Result response.OsList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeProjectInstanceRequest.go b/bmp-openapi/swaggermodels/DescribeProjectInstanceRequest.go new file mode 100644 index 0000000..0beb2a4 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeProjectInstanceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeProjectInstance +type DescribeProjectInstanceRequest struct { + ReadRequestHeader + // 实例uuid + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi/swaggermodels/DescribeProjectInstanceResult.go b/bmp-openapi/swaggermodels/DescribeProjectInstanceResult.go new file mode 100644 index 0000000..aeb5c76 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetInstanceResult is an response struct that is used to describe instance. +// swagger:response describeProjectInstance +type GetInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.InstanceInfo `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeProjectInstancesRequest.go b/bmp-openapi/swaggermodels/DescribeProjectInstancesRequest.go new file mode 100644 index 0000000..96d4f89 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeProjectInstancesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeProjectInstances +type DescribeProjectInstancesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryInstancesRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeProjectInstancesResult.go b/bmp-openapi/swaggermodels/DescribeProjectInstancesResult.go new file mode 100644 index 0000000..3ebe075 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeProjectInstancesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeProjectInstancesResult is an response struct that is used to get instance list. +// swagger:response describeProjectInstances +type DescribeProjectInstancesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.InstanceList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeRaidRequest.go b/bmp-openapi/swaggermodels/DescribeRaidRequest.go new file mode 100644 index 0000000..3512857 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeRaidRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeRaid +type DescribeRaidRequest struct { + ReadRequestHeader + + // in: path + RaidID string `json:"raid_id"` +} diff --git a/bmp-openapi/swaggermodels/DescribeRaidResult.go b/bmp-openapi/swaggermodels/DescribeRaidResult.go new file mode 100644 index 0000000..9d756d5 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeRaidResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetRaidResult is an response struct that is used to describe raid. +// swagger:response describeRaid +type DescribeRaidResult struct { + ResponseHeader + // in: body + Body struct { + Result response.Raid `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeRaidsRequest.go b/bmp-openapi/swaggermodels/DescribeRaidsRequest.go new file mode 100644 index 0000000..fe85d01 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeRaidsRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters describeRaids +type DescribeRaidsRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi/swaggermodels/DescribeRaidsResult.go b/bmp-openapi/swaggermodels/DescribeRaidsResult.go new file mode 100644 index 0000000..e708b8b --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeRaidsResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// QueryRaidsAllResult is an response struct that is used to query all raids. +// swagger:response describeRaids +type DescribeRaidsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.RaidList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeResourcesRequest.go b/bmp-openapi/swaggermodels/DescribeResourcesRequest.go new file mode 100644 index 0000000..efc7cb5 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeResourcesRequest.go @@ -0,0 +1,11 @@ +package swaggermodels + +import requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" + +// swagger:parameters describeResources +type DescribeResourcesRequest struct { + ReadRequestHeader + + // in: path + requestTypes.QueryResourcesRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeResourcesResult.go b/bmp-openapi/swaggermodels/DescribeResourcesResult.go new file mode 100644 index 0000000..2c8e6ae --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeResourcesResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeResources +type DescribeResourcesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeRoleRequest.go b/bmp-openapi/swaggermodels/DescribeRoleRequest.go new file mode 100644 index 0000000..5e04b93 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeRoleRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeRole +type DescribeRoleRequest struct { + ReadRequestHeader + + // in: path + RoleID string `json:"role_id"` +} diff --git a/bmp-openapi/swaggermodels/DescribeRoleResult.go b/bmp-openapi/swaggermodels/DescribeRoleResult.go new file mode 100644 index 0000000..4273e52 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeRoleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetRoleResult is an response struct that is used to describe role. +// swagger:response describeRole +type DescribeRoleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.RoleInfo `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeRolesRequest.go b/bmp-openapi/swaggermodels/DescribeRolesRequest.go new file mode 100644 index 0000000..5a7c281 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeRolesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeRoles +type DescribeRolesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryRolesRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeRolesResult.go b/bmp-openapi/swaggermodels/DescribeRolesResult.go new file mode 100644 index 0000000..f47f334 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeRolesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetRoleListResult is an response struct that is used to describe get role list. +// swagger:response describeRoles +type DescribeRolesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.RoleList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeRuleRequest.go b/bmp-openapi/swaggermodels/DescribeRuleRequest.go new file mode 100644 index 0000000..9eda0e5 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeRuleRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeRule +type DescribeRuleRequest struct { + ReadRequestHeader + + // in: query + requestTypes.DescribeRuleRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeRuleResult.go b/bmp-openapi/swaggermodels/DescribeRuleResult.go new file mode 100644 index 0000000..d0685d3 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeRuleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeRuleResult is an response struct that is used to describe get rule. +// swagger:response describeRule +type DescribeRuleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.Rule `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeRulesRequest.go b/bmp-openapi/swaggermodels/DescribeRulesRequest.go new file mode 100644 index 0000000..1487520 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeRulesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeRules +type DescribeRulesRequest struct { + ReadRequestHeader + + // in: query + requestTypes.DescribeRulesRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeRulesResult.go b/bmp-openapi/swaggermodels/DescribeRulesResult.go new file mode 100644 index 0000000..3355909 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeRulesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeRuleResult is an response struct that is used to describe get rule. +// swagger:response describeRules +type DescribeRulesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.RuleList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeUserAPIKeyRequest.go b/bmp-openapi/swaggermodels/DescribeUserAPIKeyRequest.go new file mode 100644 index 0000000..e344412 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserAPIKeyRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeUserAPIKey +type DescribeUserAPIKeyRequest struct { + ReadRequestHeader + // required: true + // in: path + ApikeyID string `json:"apikey_id"` +} diff --git a/bmp-openapi/swaggermodels/DescribeUserAPIKeyResult.go b/bmp-openapi/swaggermodels/DescribeUserAPIKeyResult.go new file mode 100644 index 0000000..b998b93 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserAPIKeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeUserAPIKeyResult is an response struct that is used to describe getapikey. +// swagger:response describeUserAPIKey +type DescribeUserAPIKeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ApikeyInfo `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeUserAPIKeysRequest.go b/bmp-openapi/swaggermodels/DescribeUserAPIKeysRequest.go new file mode 100644 index 0000000..06ecd60 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserAPIKeysRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeUserAPIKeys +type DescribeUserAPIKeysRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryApikeysRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeUserAPIKeysResult.go b/bmp-openapi/swaggermodels/DescribeUserAPIKeysResult.go new file mode 100644 index 0000000..3f39d3a --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserAPIKeysResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeUserAPIKeysResult is an response struct that is used to describe getapikeylist. +// swagger:response describeUserAPIKeys +type DescribeUserAPIKeysResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ApikeyList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeUserByNameRequest.go b/bmp-openapi/swaggermodels/DescribeUserByNameRequest.go new file mode 100644 index 0000000..045e3dc --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserByNameRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeUserByName +type DescribeUserByNameRequest struct { + ReadRequestHeader + + // in: query + requestTypes.GetUserByNameRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeUserByNameResult.go b/bmp-openapi/swaggermodels/DescribeUserByNameResult.go new file mode 100644 index 0000000..5b12e3e --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserByNameResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetUserByNameResult is an response struct that is used to describe user. +// swagger:response describeUserByName +type DescribeUserByNameResult struct { + ResponseHeader + // in: body + Body struct { + Result response.UserInfo `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeUserProjectRequest.go b/bmp-openapi/swaggermodels/DescribeUserProjectRequest.go new file mode 100644 index 0000000..ff17e0d --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserProjectRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeUserProject +type DescribeUserProjectRequest struct { + ReadRequestHeader + + // in: path + ProjectID string `json:"project_id"` +} diff --git a/bmp-openapi/swaggermodels/DescribeUserProjectResult.go b/bmp-openapi/swaggermodels/DescribeUserProjectResult.go new file mode 100644 index 0000000..a35fbf3 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserProjectResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeUserProject +type DescribeUserProjectResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ProjectInfo `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeUserProjectsRequest.go b/bmp-openapi/swaggermodels/DescribeUserProjectsRequest.go new file mode 100644 index 0000000..6830897 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserProjectsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeUserProjects +type DescribeUserProjectsRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryProjectsRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeUserProjectsResult.go b/bmp-openapi/swaggermodels/DescribeUserProjectsResult.go new file mode 100644 index 0000000..fc08986 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserProjectsResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeUserProjects +type DescribeUserProjectsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.ProjectList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeUserRequest.go b/bmp-openapi/swaggermodels/DescribeUserRequest.go new file mode 100644 index 0000000..1ed7030 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeUser +type DescribeUserRequest struct { + ReadRequestHeader + + // in: path + UserID string `json:"user_id"` +} diff --git a/bmp-openapi/swaggermodels/DescribeUserResult.go b/bmp-openapi/swaggermodels/DescribeUserResult.go new file mode 100644 index 0000000..293b478 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserResult.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/controllers" + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeUser +type DescribeUserResult struct { + ResponseHeader + // in: body + Body struct { + Result response.UserInfo `json:"result"` + Err *controllers.ErrorResponse `json:"error"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeUserSshKeyRequest.go b/bmp-openapi/swaggermodels/DescribeUserSshKeyRequest.go new file mode 100644 index 0000000..3b56f94 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserSshKeyRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeUserSshKey +type DescribeUserSshKeyRequest struct { + ReadRequestHeader + + // in: path + SshkeyID string `json:"sshkey_id"` +} diff --git a/bmp-openapi/swaggermodels/DescribeUserSshKeyResult.go b/bmp-openapi/swaggermodels/DescribeUserSshKeyResult.go new file mode 100644 index 0000000..e349d2e --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserSshKeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeUserSshKeyResult is an response struct that is used to describe sshkey. +// swagger:response describeUserSshKey +type DescribeUserSshKeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.SshkeyInfo `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeUserSshKeysRequest.go b/bmp-openapi/swaggermodels/DescribeUserSshKeysRequest.go new file mode 100644 index 0000000..3b751e4 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserSshKeysRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeUserSshKeys +type DescribeUserSshKeysRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QuerySshkeysRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeUserSshKeysResult.go b/bmp-openapi/swaggermodels/DescribeUserSshKeysResult.go new file mode 100644 index 0000000..cc0df4e --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUserSshKeysResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeUserSshKeysResult is an response struct that is used to describe get sshkey list. +// swagger:response describeUserSshKeys +type DescribeUserSshKeysResult struct { + ResponseHeader + // in: body + Body struct { + Result response.SshkeyList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeUsersRequest.go b/bmp-openapi/swaggermodels/DescribeUsersRequest.go new file mode 100644 index 0000000..cb09b6f --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUsersRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters describeUsers +type DescribeUsersRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryUsersRequest +} diff --git a/bmp-openapi/swaggermodels/DescribeUsersResult.go b/bmp-openapi/swaggermodels/DescribeUsersResult.go new file mode 100644 index 0000000..62fa3e1 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeUsersResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response describeUsers +type DescribeUsersResult struct { + ResponseHeader + // in: body + Body struct { + Result response.UserList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DescribeVolumesByDeviceTypeRequest.go b/bmp-openapi/swaggermodels/DescribeVolumesByDeviceTypeRequest.go new file mode 100644 index 0000000..28cf80c --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeVolumesByDeviceTypeRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters describeVolumesByDeviceType +type DescribeVolumesByDeviceType struct { + ReadRequestHeader + + // in: path + DeviceTypeID string `json:"device_type_id"` +} diff --git a/bmp-openapi/swaggermodels/DescribeVolumesByDeviceTypeResult.go b/bmp-openapi/swaggermodels/DescribeVolumesByDeviceTypeResult.go new file mode 100644 index 0000000..087f604 --- /dev/null +++ b/bmp-openapi/swaggermodels/DescribeVolumesByDeviceTypeResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DescribeVolumesByDeviceTypeResult is an response struct that is used to describe get sshkey list. +// swagger:response describeVolumesByDeviceType +type DescribeVolumesByDeviceTypeResult struct { + ResponseHeader + // in: body + Body struct { + Result []*responseTypes.VolumeIt `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DesrcibeAgentStatusRequest.go b/bmp-openapi/swaggermodels/DesrcibeAgentStatusRequest.go new file mode 100644 index 0000000..2bf9749 --- /dev/null +++ b/bmp-openapi/swaggermodels/DesrcibeAgentStatusRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters desrcibeAgentStatus +type DesrcibeAgentStatusRequest struct { + ReadRequestHeader + + // in: query + requestTypes.DesrcibeAgentStatusRequest +} diff --git a/bmp-openapi/swaggermodels/DesrcibeAgentStatusResult.go b/bmp-openapi/swaggermodels/DesrcibeAgentStatusResult.go new file mode 100644 index 0000000..445b3a1 --- /dev/null +++ b/bmp-openapi/swaggermodels/DesrcibeAgentStatusResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response desrcibeAgentStatus +type DesrcibeAgentStatusResult struct { + ResponseHeader + // in: body + Body struct { + Result responseTypes.AgentStatusResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DesrcibeTagsRequest.go b/bmp-openapi/swaggermodels/DesrcibeTagsRequest.go new file mode 100644 index 0000000..ec0ca85 --- /dev/null +++ b/bmp-openapi/swaggermodels/DesrcibeTagsRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters desrcibeTags +type DesrcibeTagsRequest struct { + ReadRequestHeader + + // in: query + requestTypes.DesrcibeTagsRequest +} diff --git a/bmp-openapi/swaggermodels/DesrcibeTagsResult.go b/bmp-openapi/swaggermodels/DesrcibeTagsResult.go new file mode 100644 index 0000000..a849b89 --- /dev/null +++ b/bmp-openapi/swaggermodels/DesrcibeTagsResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response desrcibeTags +type DesrcibeTagsResult struct { + ResponseHeader + // in: body + Body struct { + Result responseTypes.TagsResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DeviceAssociateDeviceTypeRequest.go b/bmp-openapi/swaggermodels/DeviceAssociateDeviceTypeRequest.go new file mode 100644 index 0000000..71284e0 --- /dev/null +++ b/bmp-openapi/swaggermodels/DeviceAssociateDeviceTypeRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters deviceAssociateDeviceType +type DeviceAssociateDeviceTypeRequest struct { + WriteRequestHeader + + // in: body + Body requestTypes.DeviceAssociateDeviceTypeRequest +} diff --git a/bmp-openapi/swaggermodels/DeviceAssociateDeviceTypeResult.go b/bmp-openapi/swaggermodels/DeviceAssociateDeviceTypeResult.go new file mode 100644 index 0000000..2fbc63b --- /dev/null +++ b/bmp-openapi/swaggermodels/DeviceAssociateDeviceTypeResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DeviceAssociateDeviceTypeResult is an response struct +// swagger:response deviceAssociateDeviceType +type DeviceAssociateDeviceTypeResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DialMailRequest.go b/bmp-openapi/swaggermodels/DialMailRequest.go new file mode 100644 index 0000000..95a4bbd --- /dev/null +++ b/bmp-openapi/swaggermodels/DialMailRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters dialMail +type DialMailRequest struct { + WriteRequestHeader + + // in: body + Body requestTypes.MailDialRequest +} diff --git a/bmp-openapi/swaggermodels/DialMailResult.go b/bmp-openapi/swaggermodels/DialMailResult.go new file mode 100644 index 0000000..28dd8f1 --- /dev/null +++ b/bmp-openapi/swaggermodels/DialMailResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DialMailResult is an response struct +// swagger:response dialMail +type DialMailResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DisableRuleRequest.go b/bmp-openapi/swaggermodels/DisableRuleRequest.go new file mode 100644 index 0000000..6bd6c89 --- /dev/null +++ b/bmp-openapi/swaggermodels/DisableRuleRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters disableRule +type DisableRuleRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.DisableRuleRequest +} diff --git a/bmp-openapi/swaggermodels/DisableRuleResult.go b/bmp-openapi/swaggermodels/DisableRuleResult.go new file mode 100644 index 0000000..6686f8f --- /dev/null +++ b/bmp-openapi/swaggermodels/DisableRuleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DisableRuleResult is an response struct that is used to describe create rule result. +// swagger:response disableRule +type DisableRuleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DissociatedDeviceTypeRequest.go b/bmp-openapi/swaggermodels/DissociatedDeviceTypeRequest.go new file mode 100644 index 0000000..2bf9d2e --- /dev/null +++ b/bmp-openapi/swaggermodels/DissociatedDeviceTypeRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters dissociatedDeviceType +type DissociatedDeviceTypeRequest struct { + WriteRequestHeader + + // in: body + Body requestTypes.DissociatedImageRequest +} diff --git a/bmp-openapi/swaggermodels/DissociatedDeviceTypeResult.go b/bmp-openapi/swaggermodels/DissociatedDeviceTypeResult.go new file mode 100644 index 0000000..ab9fbc8 --- /dev/null +++ b/bmp-openapi/swaggermodels/DissociatedDeviceTypeResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response dissociatedDeviceType +type DissociatedDeviceTypeResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/DissociatedImageRequest.go b/bmp-openapi/swaggermodels/DissociatedImageRequest.go new file mode 100644 index 0000000..f304a3f --- /dev/null +++ b/bmp-openapi/swaggermodels/DissociatedImageRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters dissociatedImage +type DissociatedImageRequest struct { + WriteRequestHeader + + // in: body + Body requestTypes.DissociatedImageRequest +} diff --git a/bmp-openapi/swaggermodels/DissociatedImageResult.go b/bmp-openapi/swaggermodels/DissociatedImageResult.go new file mode 100644 index 0000000..421c6e9 --- /dev/null +++ b/bmp-openapi/swaggermodels/DissociatedImageResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A DissociatedImageResult is an response struct that is used to dissociated image result. +// swagger:response dissociatedImage +type DissociatedImageResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/EditRuleRequest.go b/bmp-openapi/swaggermodels/EditRuleRequest.go new file mode 100644 index 0000000..39611f1 --- /dev/null +++ b/bmp-openapi/swaggermodels/EditRuleRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters editRule +type EditRuleRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.EditRuleRequest +} diff --git a/bmp-openapi/swaggermodels/EditRuleResult.go b/bmp-openapi/swaggermodels/EditRuleResult.go new file mode 100644 index 0000000..3b0b23c --- /dev/null +++ b/bmp-openapi/swaggermodels/EditRuleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A EditRuleResult is an response struct that is used to describe create rule result. +// swagger:response editRule +type EditRuleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/EnableRuleRequest.go b/bmp-openapi/swaggermodels/EnableRuleRequest.go new file mode 100644 index 0000000..dc267df --- /dev/null +++ b/bmp-openapi/swaggermodels/EnableRuleRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters enableRule +type EnableRuleRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.EnableRuleRequest +} diff --git a/bmp-openapi/swaggermodels/EnableRuleResult.go b/bmp-openapi/swaggermodels/EnableRuleResult.go new file mode 100644 index 0000000..a7b2cbb --- /dev/null +++ b/bmp-openapi/swaggermodels/EnableRuleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A EnableRuleResult is an response struct that is used to describe create rule result. +// swagger:response enableRule +type EnableRuleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/GetAssociatedDisksRequest.go b/bmp-openapi/swaggermodels/GetAssociatedDisksRequest.go new file mode 100644 index 0000000..6c5c985 --- /dev/null +++ b/bmp-openapi/swaggermodels/GetAssociatedDisksRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters getAssociatedDisks +type GetAssociatedDisksRequest struct { + ReadRequestHeader + + // in: query + requestTypes.GetAssociatedDisksRequest +} diff --git a/bmp-openapi/swaggermodels/GetAssociatedDisksResult.go b/bmp-openapi/swaggermodels/GetAssociatedDisksResult.go new file mode 100644 index 0000000..f584d1f --- /dev/null +++ b/bmp-openapi/swaggermodels/GetAssociatedDisksResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetAssociatedDisksResult is an response struct that is used to get instance list by sshkey. +// swagger:response getAssociatedDisks +type GetAssociatedDisksResult struct { + ResponseHeader + // in: body + Body struct { + Result []*response.Disk `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/GetInstancesBySshkeyRequest.go b/bmp-openapi/swaggermodels/GetInstancesBySshkeyRequest.go new file mode 100644 index 0000000..83a98c0 --- /dev/null +++ b/bmp-openapi/swaggermodels/GetInstancesBySshkeyRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters getInstancesBySshkey +type GetInstancesBySshkey struct { + ReadRequestHeader + + // in: path + SshkeyID string `json:"sshkey_id"` +} diff --git a/bmp-openapi/swaggermodels/GetInstancesBySshkeyResult.go b/bmp-openapi/swaggermodels/GetInstancesBySshkeyResult.go new file mode 100644 index 0000000..2c8c154 --- /dev/null +++ b/bmp-openapi/swaggermodels/GetInstancesBySshkeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetInstancesBySshkeyResult is an response struct that is used to get instance list by sshkey. +// swagger:response getInstancesBySshkey +type GetInstancesBySshkeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.InstancesSshkeyInfoResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/GetMessageByIdRequest.go b/bmp-openapi/swaggermodels/GetMessageByIdRequest.go new file mode 100644 index 0000000..b053749 --- /dev/null +++ b/bmp-openapi/swaggermodels/GetMessageByIdRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters getMessageById +type GetMessageByIdRequest struct { + WriteRequestHeader + + // in: query + requestTypes.GetMessageByIdRequest +} diff --git a/bmp-openapi/swaggermodels/GetMessageByIdResult.go b/bmp-openapi/swaggermodels/GetMessageByIdResult.go new file mode 100644 index 0000000..8397377 --- /dev/null +++ b/bmp-openapi/swaggermodels/GetMessageByIdResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// swagger:response getMessageById +type GetMessageByIdResult struct { + ResponseHeader + // in: body + Body struct { + Result response.MessageWithNextPrev `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/GetMessageListRequest.go b/bmp-openapi/swaggermodels/GetMessageListRequest.go new file mode 100644 index 0000000..9b5dce3 --- /dev/null +++ b/bmp-openapi/swaggermodels/GetMessageListRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters getMessageList +type GetMessageListRequest struct { + ReadRequestHeader + + // in: query + requestTypes.QueryMessagesRequest +} diff --git a/bmp-openapi/swaggermodels/GetMessageListResult.go b/bmp-openapi/swaggermodels/GetMessageListResult.go new file mode 100644 index 0000000..d43b5cf --- /dev/null +++ b/bmp-openapi/swaggermodels/GetMessageListResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// swagger:response getMessageList +type GetMessageListResult struct { + ResponseHeader + // in: body + Body struct { + Result response.MessageList `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/GetMessageStatisticRequest.go b/bmp-openapi/swaggermodels/GetMessageStatisticRequest.go new file mode 100644 index 0000000..4d1cbcd --- /dev/null +++ b/bmp-openapi/swaggermodels/GetMessageStatisticRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters getMessageStatistic +type GetMessageStatisticRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi/swaggermodels/GetMessageStatisticResult.go b/bmp-openapi/swaggermodels/GetMessageStatisticResult.go new file mode 100644 index 0000000..4f65e6b --- /dev/null +++ b/bmp-openapi/swaggermodels/GetMessageStatisticResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// swagger:response getMessageStatistic +type GetMessageStatisticResult struct { + ResponseHeader + // in: body + Body struct { + Result response.MessageStatistic `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/GetMessageTypesRequest.go b/bmp-openapi/swaggermodels/GetMessageTypesRequest.go new file mode 100644 index 0000000..bfb50d2 --- /dev/null +++ b/bmp-openapi/swaggermodels/GetMessageTypesRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters getMessageTypes +type GetMessageTypesRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi/swaggermodels/GetMessageTypesResult.go b/bmp-openapi/swaggermodels/GetMessageTypesResult.go new file mode 100644 index 0000000..adc3404 --- /dev/null +++ b/bmp-openapi/swaggermodels/GetMessageTypesResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// swagger:response getMessageTypes +type GetMessageTypesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.MessageTypesResp `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/GetMonitorDataRequest.go b/bmp-openapi/swaggermodels/GetMonitorDataRequest.go new file mode 100644 index 0000000..84a40fa --- /dev/null +++ b/bmp-openapi/swaggermodels/GetMonitorDataRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters getMonitorData +type GetMonitorDataRequest struct { + ReadRequestHeader + + // in: query + requestTypes.GetMonitorDataRequest +} diff --git a/bmp-openapi/swaggermodels/GetMonitorDataResult.go b/bmp-openapi/swaggermodels/GetMonitorDataResult.go new file mode 100644 index 0000000..4947f8c --- /dev/null +++ b/bmp-openapi/swaggermodels/GetMonitorDataResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + responseTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response getMonitorData +type GetMonitorDataResult struct { + ResponseHeader + // in: body + Body struct { + Result []*responseTypes.DataEveryMetric `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/HasUnreadMessageRequest.go b/bmp-openapi/swaggermodels/HasUnreadMessageRequest.go new file mode 100644 index 0000000..6a215ba --- /dev/null +++ b/bmp-openapi/swaggermodels/HasUnreadMessageRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters hasUnreadMessage +type HasUnreadMessageRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi/swaggermodels/HasUnreadMessageResult.go b/bmp-openapi/swaggermodels/HasUnreadMessageResult.go new file mode 100644 index 0000000..b170e87 --- /dev/null +++ b/bmp-openapi/swaggermodels/HasUnreadMessageResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response hasUnreadMessage +type HasUnreadMessageResult struct { + ResponseHeader + // in: body + Body struct { + Result response.HasUnreadMessage `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/LockProjectInstanceRequest.go b/bmp-openapi/swaggermodels/LockProjectInstanceRequest.go new file mode 100644 index 0000000..552fe7c --- /dev/null +++ b/bmp-openapi/swaggermodels/LockProjectInstanceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters lockProjectInstance +type LockProjectInstanceRequest struct { + WriteRequestHeader + + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi/swaggermodels/LockProjectInstanceResult.go b/bmp-openapi/swaggermodels/LockProjectInstanceResult.go new file mode 100644 index 0000000..8c86466 --- /dev/null +++ b/bmp-openapi/swaggermodels/LockProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A LockProjectInstanceResult is an response struct that is used to describe lock instance result. +// swagger:response lockProjectInstance +type LockProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/MailDetailRequest.go b/bmp-openapi/swaggermodels/MailDetailRequest.go new file mode 100644 index 0000000..dd65f50 --- /dev/null +++ b/bmp-openapi/swaggermodels/MailDetailRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters mailDetail +type MailDetailRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi/swaggermodels/MailDetailResult.go b/bmp-openapi/swaggermodels/MailDetailResult.go new file mode 100644 index 0000000..61f5663 --- /dev/null +++ b/bmp-openapi/swaggermodels/MailDetailResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// swagger:response mailDetail +type MailDetailResult struct { + ResponseHeader + // in: body + Body struct { + Result response.Mail `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ModifyDeviceRequest.go b/bmp-openapi/swaggermodels/ModifyDeviceRequest.go new file mode 100644 index 0000000..714c476 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyDeviceRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyDevice +type ModifyDeviceRequest struct { + ReadRequestHeader + + // in: path + DeviceID string `json:"device_id"` + + // in: body + Body requestTypes.ModifyDevicesRequest +} diff --git a/bmp-openapi/swaggermodels/ModifyDeviceResult.go b/bmp-openapi/swaggermodels/ModifyDeviceResult.go new file mode 100644 index 0000000..e9de5af --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyDeviceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyDeviceResult is an response struct that is used to describe modify device result. +// swagger:response modifyDevice +type ModifyDeviceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ModifyDeviceTypeRequest.go b/bmp-openapi/swaggermodels/ModifyDeviceTypeRequest.go new file mode 100644 index 0000000..1435b32 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyDeviceTypeRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyDeviceType +type ModifyDeviceTypeRequest struct { + ReadRequestHeader + + // in: path + DeviceTypeID string `json:"device_type_id"` + + // in: body + Body requestTypes.ModifyDeviceTypeRequest +} diff --git a/bmp-openapi/swaggermodels/ModifyDeviceTypeResult.go b/bmp-openapi/swaggermodels/ModifyDeviceTypeResult.go new file mode 100644 index 0000000..e5460ce --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyDeviceTypeResult.go @@ -0,0 +1,17 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyDeviceTypeResult is an response struct that is used to modify device type. +// swagger:response modifyDeviceType +type ModifyDeviceTypeResult struct { + // in: header + ResponseHeader + + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ModifyIdcRequest.go b/bmp-openapi/swaggermodels/ModifyIdcRequest.go new file mode 100644 index 0000000..71b8a7b --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyIdcRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyIdc +type ModifyIdcRequest struct { + WriteRequestHeader + + // in: path + IdcID string `json:"idc_id"` + + // in: body + Body requestTypes.ModifyIdcRequest +} diff --git a/bmp-openapi/swaggermodels/ModifyIdcResult.go b/bmp-openapi/swaggermodels/ModifyIdcResult.go new file mode 100644 index 0000000..4f20bab --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyIdcResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyIdcResult is an response struct that is used to modify idc. +// swagger:response modifyIdc +type ModifyIdcResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ModifyImageRequest.go b/bmp-openapi/swaggermodels/ModifyImageRequest.go new file mode 100644 index 0000000..97cbd84 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyImageRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyImage +type ModifyImageRequest struct { + ReadRequestHeader + + // in: path + ImageID string `json:"image_id"` + + // in: body + Body requestTypes.ModifyImageRequest +} diff --git a/bmp-openapi/swaggermodels/ModifyImageResult.go b/bmp-openapi/swaggermodels/ModifyImageResult.go new file mode 100644 index 0000000..90ceda6 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyImageResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyImageResult is an response struct that is used to modify image. +// swagger:response modifyImage +type ModifyImageResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ModifyInstancesRequest.go b/bmp-openapi/swaggermodels/ModifyInstancesRequest.go new file mode 100644 index 0000000..a3e81ad --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyInstancesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyInstances +type ModifyInstancesRequest struct { + ReadRequestHeader + + // in: body + Body requestTypes.ModifyInstancesRequest +} diff --git a/bmp-openapi/swaggermodels/ModifyInstancesResult.go b/bmp-openapi/swaggermodels/ModifyInstancesResult.go new file mode 100644 index 0000000..865968d --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyInstancesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyInstancesResult is an response struct that is used to describe modify instance result. +// swagger:response modifyInstances +type ModifyInstancesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ModifyLocalUserPasswordRequest.go b/bmp-openapi/swaggermodels/ModifyLocalUserPasswordRequest.go new file mode 100644 index 0000000..32b1514 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyLocalUserPasswordRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyLocalUserPassword +type ModifyLocalUserPasswordRequest struct { + ReadRequestHeader + + // in: body + Body requestTypes.ModifyUserPasswordRequest +} diff --git a/bmp-openapi/swaggermodels/ModifyLocalUserPasswordResult.go b/bmp-openapi/swaggermodels/ModifyLocalUserPasswordResult.go new file mode 100644 index 0000000..a7286b3 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyLocalUserPasswordResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyLocalUserPasswordResult is an response struct that is used to describe getuser. +// swagger:response modifyLocalUserPassword +type ModifyLocalUserPasswordResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ModifyLocalUserRequest.go b/bmp-openapi/swaggermodels/ModifyLocalUserRequest.go new file mode 100644 index 0000000..f99b952 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyLocalUserRequest.go @@ -0,0 +1,12 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyLocalUser +type ModifyLocalUserRequest struct { + ReadRequestHeader + // in: body + Body requestTypes.ModifyLocalUserRequest +} diff --git a/bmp-openapi/swaggermodels/ModifyLocalUserResult.go b/bmp-openapi/swaggermodels/ModifyLocalUserResult.go new file mode 100644 index 0000000..34c8354 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyLocalUserResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyLocalUserResult is an response struct that is used to describe getuser. +// swagger:response modifyLocalUser +type ModifyLocalUserResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ModifyOsRequest.go b/bmp-openapi/swaggermodels/ModifyOsRequest.go new file mode 100644 index 0000000..09826d4 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyOsRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyOS +type ModifyOsRequest struct { + ReadRequestHeader + + // in: path + OsID string `json:"os_id"` + + // in: body + Body requestTypes.ModifyOSRequest +} diff --git a/bmp-openapi/swaggermodels/ModifyOsResult.go b/bmp-openapi/swaggermodels/ModifyOsResult.go new file mode 100644 index 0000000..5c4b0e5 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyOsResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyOsResult is an response struct that is used to describe modify os. +// swagger:response modifyOS +type ModifyOsResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ModifyProjectInstanceRequest.go b/bmp-openapi/swaggermodels/ModifyProjectInstanceRequest.go new file mode 100644 index 0000000..f5bf73f --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyProjectInstanceRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyProjectInstance +type ModifyProjectInstanceRequest struct { + ReadRequestHeader + + // in: path + InstanceID string `json:"instance_id"` + + // in: body + Body requestTypes.ModifyInstanceRequest +} diff --git a/bmp-openapi/swaggermodels/ModifyProjectInstanceResult.go b/bmp-openapi/swaggermodels/ModifyProjectInstanceResult.go new file mode 100644 index 0000000..270af3a --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyProjectInstanceResult is an response struct that is used to describe modify instance result. +// swagger:response modifyProjectInstance +type ModifyProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ModifyRaidRequest.go b/bmp-openapi/swaggermodels/ModifyRaidRequest.go new file mode 100644 index 0000000..9fbf8a2 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyRaidRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyRaid +type ModifyRaidRequest struct { + WriteRequestHeader + + // in: path + RaidID string `json:"raid_id"` + + // in: body + Body requestTypes.ModifyRaidRequest +} diff --git a/bmp-openapi/swaggermodels/ModifyRaidResult.go b/bmp-openapi/swaggermodels/ModifyRaidResult.go new file mode 100644 index 0000000..75d9d3d --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyRaidResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyRaidResult is an response struct that is used to describe modify raid. +// swagger:response modifyRaid +type ModifyRaidResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ModifyRoleRequest.go b/bmp-openapi/swaggermodels/ModifyRoleRequest.go new file mode 100644 index 0000000..10cf2b5 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyRoleRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyRole +type ModifyRoleRequest struct { + ReadRequestHeader + + // in: path + RoleID string `json:"role_id"` + + // in: body + Body requestTypes.ModifyRoleRequest +} diff --git a/bmp-openapi/swaggermodels/ModifyRoleResult.go b/bmp-openapi/swaggermodels/ModifyRoleResult.go new file mode 100644 index 0000000..53cc93d --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyRoleResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyRoleResult is an response struct that is used to describe modify role. +// swagger:response modifyRole +type ModifyRoleResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ModifyUserApikeyRequest.go b/bmp-openapi/swaggermodels/ModifyUserApikeyRequest.go new file mode 100644 index 0000000..037f72c --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyUserApikeyRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyUserApikey +type ModifyUserApikeyRequest struct { + ReadRequestHeader + + // in: path + ApikeyID string `json:"apikey_id"` + + // in: body + Body requestTypes.ModifyApikeyRequest +} diff --git a/bmp-openapi/swaggermodels/ModifyUserApikeyResult.go b/bmp-openapi/swaggermodels/ModifyUserApikeyResult.go new file mode 100644 index 0000000..8004193 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyUserApikeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyUserApikeyResult is an response struct that is used to describe modifyApikey result. +// swagger:response modifyUserApikey +type ModifyUserApikeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ModifyUserProjectRequest.go b/bmp-openapi/swaggermodels/ModifyUserProjectRequest.go new file mode 100644 index 0000000..5ec6aca --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyUserProjectRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyUserProject +type ModifyUserProjectRequest struct { + ReadRequestHeader + + // in: path + ProjectID string `json:"project_id"` + + // in: body + Body requestTypes.ModifyProjectRequest +} diff --git a/bmp-openapi/swaggermodels/ModifyUserProjectResult.go b/bmp-openapi/swaggermodels/ModifyUserProjectResult.go new file mode 100644 index 0000000..708d240 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyUserProjectResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// swagger:response modifyUserProject +type ModifyUserProjectResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ModifyUserRequest.go b/bmp-openapi/swaggermodels/ModifyUserRequest.go new file mode 100644 index 0000000..885448a --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyUserRequest.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyUser +type ModifyUserRequest struct { + ReadRequestHeader + + // in: path + UserID string `json:"user_id"` + // in: body + Body requestTypes.ModifyUserRequest +} diff --git a/bmp-openapi/swaggermodels/ModifyUserResult.go b/bmp-openapi/swaggermodels/ModifyUserResult.go new file mode 100644 index 0000000..4316a00 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyUserResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A GetUserResult is an response struct that is used to describe getuser. +// swagger:response modifyUser +type ModifyUserResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ModifyUserSshkeyRequest.go b/bmp-openapi/swaggermodels/ModifyUserSshkeyRequest.go new file mode 100644 index 0000000..2b77a37 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyUserSshkeyRequest.go @@ -0,0 +1,16 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters modifyUserSshkey +type ModifyUserSshkeyRequest struct { + WriteRequestHeader + + // in: path + SshkeyID string `json:"sshkey_id"` + + // in: body + Body requestTypes.ModifySshkeyRequest +} diff --git a/bmp-openapi/swaggermodels/ModifyUserSshkeyResult.go b/bmp-openapi/swaggermodels/ModifyUserSshkeyResult.go new file mode 100644 index 0000000..6fe8595 --- /dev/null +++ b/bmp-openapi/swaggermodels/ModifyUserSshkeyResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ModifyUserSshkeyResult is an response struct that is used to modify sshkey result. +// swagger:response modifyUserSshkey +type ModifyUserSshkeyResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/MountDeviceRequest.go b/bmp-openapi/swaggermodels/MountDeviceRequest.go new file mode 100644 index 0000000..9f19942 --- /dev/null +++ b/bmp-openapi/swaggermodels/MountDeviceRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters mountDevice +type MountDeviceRequest struct { + ReadRequestHeader + + // in: body + Body requestTypes.MountDevicesRequest +} diff --git a/bmp-openapi/swaggermodels/MountDeviceResult.go b/bmp-openapi/swaggermodels/MountDeviceResult.go new file mode 100644 index 0000000..21de592 --- /dev/null +++ b/bmp-openapi/swaggermodels/MountDeviceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A MountDeviceResult is an response struct that is used to describe mount device result. +// swagger:response mountDevice +type MountDeviceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ReStartInstancesResult.go b/bmp-openapi/swaggermodels/ReStartInstancesResult.go new file mode 100644 index 0000000..1c4a709 --- /dev/null +++ b/bmp-openapi/swaggermodels/ReStartInstancesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A RestartInstancesResult is an response struct +// swagger:response restartInstances +type RestartInstancesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ReadMessageRequest.go b/bmp-openapi/swaggermodels/ReadMessageRequest.go new file mode 100644 index 0000000..98d6927 --- /dev/null +++ b/bmp-openapi/swaggermodels/ReadMessageRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters readMessage +type ReadMessageRequest struct { + WriteRequestHeader + + // in: body + Body requestTypes.ReadMessagesRequest +} diff --git a/bmp-openapi/swaggermodels/ReadMessageResult.go b/bmp-openapi/swaggermodels/ReadMessageResult.go new file mode 100644 index 0000000..e6b5f7e --- /dev/null +++ b/bmp-openapi/swaggermodels/ReadMessageResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ReadMessageResult is an response struct +// swagger:response readMessage +type ReadMessageResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ReinstallProjectInstanceRequest.go b/bmp-openapi/swaggermodels/ReinstallProjectInstanceRequest.go new file mode 100644 index 0000000..99bae52 --- /dev/null +++ b/bmp-openapi/swaggermodels/ReinstallProjectInstanceRequest.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters reinstallProjectInstance +type ReinstallProjectInstanceRequest struct { + ReadRequestHeader + + // in: path + InstanceID string `json:"instance_id"` + // in: body + Body requestTypes.ReinstallInstanceRequest +} diff --git a/bmp-openapi/swaggermodels/ReinstallProjectInstanceResult.go b/bmp-openapi/swaggermodels/ReinstallProjectInstanceResult.go new file mode 100644 index 0000000..4a5fe1a --- /dev/null +++ b/bmp-openapi/swaggermodels/ReinstallProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ReinstallProjectInstanceResult is an response struct that is used to describe reinstall instance. +// swagger:response reinstallProjectInstance +type ReinstallProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/RemoveDeviceRequest.go b/bmp-openapi/swaggermodels/RemoveDeviceRequest.go new file mode 100644 index 0000000..265e351 --- /dev/null +++ b/bmp-openapi/swaggermodels/RemoveDeviceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters removeDevice +type RemoveDeviceRequest struct { + WriteRequestHeader + + // in: path + DeviceID string `json:"device_id"` +} diff --git a/bmp-openapi/swaggermodels/RemoveDeviceResult.go b/bmp-openapi/swaggermodels/RemoveDeviceResult.go new file mode 100644 index 0000000..2f06fb3 --- /dev/null +++ b/bmp-openapi/swaggermodels/RemoveDeviceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A RemoveDeviceResult is an response struct that is used to describe restart instance result. +// swagger:response removeDevice +type RemoveDeviceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ResetInstancePasswdRequest.go b/bmp-openapi/swaggermodels/ResetInstancePasswdRequest.go new file mode 100644 index 0000000..362ab08 --- /dev/null +++ b/bmp-openapi/swaggermodels/ResetInstancePasswdRequest.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters resetProjectInstancePasswd +type ResetInstancePasswdRequest struct { + ReadRequestHeader + + // in: path + InstanceID string `json:"instance_id"` + // in: body + Body requestTypes.ResetInstancePasswdRequest +} diff --git a/bmp-openapi/swaggermodels/ResetInstancePasswdResult.go b/bmp-openapi/swaggermodels/ResetInstancePasswdResult.go new file mode 100644 index 0000000..5422dd7 --- /dev/null +++ b/bmp-openapi/swaggermodels/ResetInstancePasswdResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ResetProjectInstancePasswdResult is an response struct that is used to describe reset instance password. +// swagger:response resetProjectInstancePasswd +type ResetProjectInstancePasswdResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ResetInstanceStatusRequest.go b/bmp-openapi/swaggermodels/ResetInstanceStatusRequest.go new file mode 100644 index 0000000..be85f4e --- /dev/null +++ b/bmp-openapi/swaggermodels/ResetInstanceStatusRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters resetInstanceStatus +type ResetInstanceStatusRequest struct { + WriteRequestHeader + + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi/swaggermodels/ResetInstanceStatusResult.go b/bmp-openapi/swaggermodels/ResetInstanceStatusResult.go new file mode 100644 index 0000000..03581d0 --- /dev/null +++ b/bmp-openapi/swaggermodels/ResetInstanceStatusResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ResetInstanceStatusResult is an response struct that is used to describe restart instance result. +// swagger:response resetInstanceStatus +type ResetInstanceStatusResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ResetInstancesPasswdRequest.go b/bmp-openapi/swaggermodels/ResetInstancesPasswdRequest.go new file mode 100644 index 0000000..f3aba53 --- /dev/null +++ b/bmp-openapi/swaggermodels/ResetInstancesPasswdRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters resetProjectInstancesPasswd +type ResetProjectInstancesPasswdRequest struct { + WriteRequestHeader + + // in: body + Body requestTypes.ResetInstancesPasswdRequest +} diff --git a/bmp-openapi/swaggermodels/ResetInstancesPasswdResult.go b/bmp-openapi/swaggermodels/ResetInstancesPasswdResult.go new file mode 100644 index 0000000..416fe91 --- /dev/null +++ b/bmp-openapi/swaggermodels/ResetInstancesPasswdResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ResetProjectInstancesPasswdResult is an response struct that is used to describe reset instance password. +// swagger:response resetProjectInstancesPasswd +type ResetProjectInstancesPasswdResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/RestartInstancesRequest.go b/bmp-openapi/swaggermodels/RestartInstancesRequest.go new file mode 100644 index 0000000..7b317af --- /dev/null +++ b/bmp-openapi/swaggermodels/RestartInstancesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters startInstances +type StartInstancesRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.StartInstancesRequest +} diff --git a/bmp-openapi/swaggermodels/RestartProjectInstanceRequest.go b/bmp-openapi/swaggermodels/RestartProjectInstanceRequest.go new file mode 100644 index 0000000..109d436 --- /dev/null +++ b/bmp-openapi/swaggermodels/RestartProjectInstanceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters restartProjectInstance +type RestartProjectInstanceRequest struct { + WriteRequestHeader + + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi/swaggermodels/RestartProjectInstanceResult.go b/bmp-openapi/swaggermodels/RestartProjectInstanceResult.go new file mode 100644 index 0000000..bf11a02 --- /dev/null +++ b/bmp-openapi/swaggermodels/RestartProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A RestartProjectInstanceResult is an response struct that is used to describe restart instance result. +// swagger:response restartProjectInstance +type RestartProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/SaveIsPushMailResult.go b/bmp-openapi/swaggermodels/SaveIsPushMailResult.go new file mode 100644 index 0000000..fd41429 --- /dev/null +++ b/bmp-openapi/swaggermodels/SaveIsPushMailResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A SaveIsPushMailResult is an response struct +// swagger:response saveIsPushMail +type SaveIsPushMailResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/ShareUserProjectRequest.go b/bmp-openapi/swaggermodels/ShareUserProjectRequest.go new file mode 100644 index 0000000..6389d71 --- /dev/null +++ b/bmp-openapi/swaggermodels/ShareUserProjectRequest.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters shareUserProject +type ShareUserProjectRequest struct { + WriteRequestHeader + // in: path + ProjectID string `json:"project_id"` + // in: body + Body requestTypes.ShareProjectRequest +} diff --git a/bmp-openapi/swaggermodels/ShareUserProjectResult.go b/bmp-openapi/swaggermodels/ShareUserProjectResult.go new file mode 100644 index 0000000..c79aa9e --- /dev/null +++ b/bmp-openapi/swaggermodels/ShareUserProjectResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A ShareUserProjectResult is an response struct +// swagger:response shareUserProject +type ShareUserProjectResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/StartInstancesRequest.go b/bmp-openapi/swaggermodels/StartInstancesRequest.go new file mode 100644 index 0000000..3d04b6a --- /dev/null +++ b/bmp-openapi/swaggermodels/StartInstancesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters restartInstances +type RestartInstancesRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.RestartInstancesRequest +} diff --git a/bmp-openapi/swaggermodels/StartInstancesResult.go b/bmp-openapi/swaggermodels/StartInstancesResult.go new file mode 100644 index 0000000..9871c92 --- /dev/null +++ b/bmp-openapi/swaggermodels/StartInstancesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A StartInstancesResult is an response struct +// swagger:response startInstances +type StartInstancesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/StartProjectInstanceRequest.go b/bmp-openapi/swaggermodels/StartProjectInstanceRequest.go new file mode 100644 index 0000000..23bfe78 --- /dev/null +++ b/bmp-openapi/swaggermodels/StartProjectInstanceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters startProjectInstance +type StartProjectInstanceRequest struct { + WriteRequestHeader + + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi/swaggermodels/StartProjectInstanceResult.go b/bmp-openapi/swaggermodels/StartProjectInstanceResult.go new file mode 100644 index 0000000..0c175ac --- /dev/null +++ b/bmp-openapi/swaggermodels/StartProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A StartProjectInstanceResult is an response struct that is used to describe start instance result. +// swagger:response startProjectInstance +type StartProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/StopInstancesRequest.go b/bmp-openapi/swaggermodels/StopInstancesRequest.go new file mode 100644 index 0000000..9ffc38b --- /dev/null +++ b/bmp-openapi/swaggermodels/StopInstancesRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters stopInstances +type StopInstancesRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.StopInstancesRequest +} diff --git a/bmp-openapi/swaggermodels/StopInstancesResult.go b/bmp-openapi/swaggermodels/StopInstancesResult.go new file mode 100644 index 0000000..a2a250d --- /dev/null +++ b/bmp-openapi/swaggermodels/StopInstancesResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A StopInstancesResult is an response struct +// swagger:response stopInstances +type StopInstancesResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/StopProjectInstanceRequest.go b/bmp-openapi/swaggermodels/StopProjectInstanceRequest.go new file mode 100644 index 0000000..8a583ab --- /dev/null +++ b/bmp-openapi/swaggermodels/StopProjectInstanceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters stopProjectInstance +type StopProjectInstanceRequest struct { + WriteRequestHeader + + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi/swaggermodels/StopProjectInstanceResult.go b/bmp-openapi/swaggermodels/StopProjectInstanceResult.go new file mode 100644 index 0000000..b4cb42e --- /dev/null +++ b/bmp-openapi/swaggermodels/StopProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A StopProjectInstanceResult is an response struct that is used to describe stop instance result. +// swagger:response stopProjectInstance +type StopProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/UnLockProjectInstanceRequest.go b/bmp-openapi/swaggermodels/UnLockProjectInstanceRequest.go new file mode 100644 index 0000000..9c05f2b --- /dev/null +++ b/bmp-openapi/swaggermodels/UnLockProjectInstanceRequest.go @@ -0,0 +1,9 @@ +package swaggermodels + +// swagger:parameters unLockProjectInstance +type UnLockProjectInstanceResultRequest struct { + WriteRequestHeader + + // in: path + InstanceID string `json:"instance_id"` +} diff --git a/bmp-openapi/swaggermodels/UnLockProjectInstanceResult.go b/bmp-openapi/swaggermodels/UnLockProjectInstanceResult.go new file mode 100644 index 0000000..702301a --- /dev/null +++ b/bmp-openapi/swaggermodels/UnLockProjectInstanceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A UnLockProjectInstanceResult is an response struct that is used to describe unlock instance result. +// swagger:response unLockProjectInstance +type UnLockProjectInstanceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/UnMountDeviceRequest.go b/bmp-openapi/swaggermodels/UnMountDeviceRequest.go new file mode 100644 index 0000000..bb507fb --- /dev/null +++ b/bmp-openapi/swaggermodels/UnMountDeviceRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters unMountDevice +type UnMountDeviceRequest struct { + ReadRequestHeader + + // in: body + Body requestTypes.UnMountDevicesRequest +} diff --git a/bmp-openapi/swaggermodels/UnMountDeviceResult.go b/bmp-openapi/swaggermodels/UnMountDeviceResult.go new file mode 100644 index 0000000..5020d57 --- /dev/null +++ b/bmp-openapi/swaggermodels/UnMountDeviceResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A UnMountDeviceResult is an response struct that is used to unmount device. +// swagger:response unMountDevice +type UnMountDeviceResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/UploadLicenseRequest.go b/bmp-openapi/swaggermodels/UploadLicenseRequest.go new file mode 100644 index 0000000..59d5148 --- /dev/null +++ b/bmp-openapi/swaggermodels/UploadLicenseRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters uploadLicense +type UploadLicenseRequest struct { + ReadRequestHeader + + // in: body + Body requestTypes.CreateLicenseRequest +} diff --git a/bmp-openapi/swaggermodels/UploadLicenseResult.go b/bmp-openapi/swaggermodels/UploadLicenseResult.go new file mode 100644 index 0000000..c809a67 --- /dev/null +++ b/bmp-openapi/swaggermodels/UploadLicenseResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/types/response" +) + +// A UploadLicenseResult is an response struct that is used to describe modify instance result. +// swagger:response uploadLicense +type UploadLicenseResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/VerifyUserRequest.go b/bmp-openapi/swaggermodels/VerifyUserRequest.go new file mode 100644 index 0000000..a5f14a5 --- /dev/null +++ b/bmp-openapi/swaggermodels/VerifyUserRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters verifyUser +type VerifyUserRequest struct { + WriteRequestHeader + + // in:body + Body requestTypes.VerifyUserRequest +} diff --git a/bmp-openapi/swaggermodels/VerifyUserResult.go b/bmp-openapi/swaggermodels/VerifyUserResult.go new file mode 100644 index 0000000..01776b5 --- /dev/null +++ b/bmp-openapi/swaggermodels/VerifyUserResult.go @@ -0,0 +1,13 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-openapi/types/response" + +// A VerifyUserResult is an response struct that is used to describe verify user result. +// swagger:response verifyUser +type VerifyUserResult struct { + ResponseHeader + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + } +} diff --git a/bmp-openapi/swaggermodels/describeLicenseContentRequest.go b/bmp-openapi/swaggermodels/describeLicenseContentRequest.go new file mode 100644 index 0000000..0166995 --- /dev/null +++ b/bmp-openapi/swaggermodels/describeLicenseContentRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters describeLicenseContent +type DescribeLicenseContentRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi/swaggermodels/describeLocalUserRequest.go b/bmp-openapi/swaggermodels/describeLocalUserRequest.go new file mode 100644 index 0000000..494117a --- /dev/null +++ b/bmp-openapi/swaggermodels/describeLocalUserRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters describeLocalUser +type DescribeLocalUserRequest struct { + ReadRequestHeader +} diff --git a/bmp-openapi/swaggermodels/saveIsPushMailRequest.go b/bmp-openapi/swaggermodels/saveIsPushMailRequest.go new file mode 100644 index 0000000..1604874 --- /dev/null +++ b/bmp-openapi/swaggermodels/saveIsPushMailRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-openapi/types/request" +) + +// swagger:parameters saveIsPushMail +type SaveIsPushMailRequest struct { + WriteRequestHeader + + // in: body + Body requestTypes.SaveIsPushMailRequest +} diff --git a/bmp-openapi/swaggermodels/swaggerinfo.go b/bmp-openapi/swaggermodels/swaggerinfo.go new file mode 100644 index 0000000..e7193fc --- /dev/null +++ b/bmp-openapi/swaggermodels/swaggerinfo.go @@ -0,0 +1,47 @@ +// Package classification CPS +// +// the purpose of this application is to provide an application +// that is using plain go code to define an API +// +// This should demonstrate all the possible comment annotations +// that are available to turn go code into a fully compliant swagger 2.0 spec +// +// Terms Of Service: +// +// there are no TOS at this moment, use at your own risk we take no responsibility +// +// Schemes: http +// Host: bmp-openapi.bmp.local +// BasePath: /v1 +// Version: 0.0.1 +// License: MIT http://opensource.org/licenses/MIT +// Contact: minping@jd.com +// +// Consumes: +// - application/json +// - application/xml +// +// Produces: +// - application/json +// - application/xml +// +// Security: +// - api_key: +// +// SecurityDefinitions: +// api_key: +// type: apiKey +// name: bmp-ak +// in: header +// +// Extensions: +// x-meta-value: value +// x-meta-array: +// - value1 +// - value2 +// x-meta-array-obj: +// - name: obj +// value: field +// +// swagger:meta +package swaggermodels diff --git a/bmp-openapi/types/request/ApikeyRequest.go b/bmp-openapi/types/request/ApikeyRequest.go new file mode 100644 index 0000000..4eed3b0 --- /dev/null +++ b/bmp-openapi/types/request/ApikeyRequest.go @@ -0,0 +1,81 @@ +package request + +import ( + "regexp" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateApikeyRequest struct { + // 秘钥对名称 + // required: true + Name string `json:"name" validate:"required"` + // 是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法 + // required: true + ReadOnly int8 `json:"readOnly" validate:"oneof=0 1"` + // Token类型, [system/user] + // required: true + Type string `json:"type" validate:"required,oneof=system user"` +} +type ModifyApikeyRequest struct { + // 秘钥对名称 + // required: true + Name string `json:"name" validate:"required"` // 秘钥对名称 + // 是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法 + // required: true + ReadOnly int8 `json:"readOnly" validate:"oneof=0 1"` +} +type QueryApikeysRequest struct { + Pageable + // 秘钥对名称 + Name string `json:"name"` + // Token类型, [system/user] + Type string `json:"type" validate:"omitempty,oneof=system user"` + // 是否查询全部/导出 + IsAll string `json:"isAll"` +} + +func (req *CreateApikeyRequest) Validate(logger *log.Logger) { + + validate(req, logger) + + if req.ReadOnly != 0 && req.ReadOnly != 1 { + panic(constant.BuildInvalidArgumentWithArgs("readonly范围不正确", "readonly param error")) + } + + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 + specialMatch := regexp.MustCompile("^[\u4e00-\u9fa5_a-zA-Z0-9_-]{1,64}$").MatchString + if !specialMatch(req.Name) { + panic(constant.BuildInvalidArgumentWithArgs("name格式不正确", "Name invalidate")) + } + +} + +func (req *ModifyApikeyRequest) Validate(logger *log.Logger) { + + validate(req, logger) + + if req.ReadOnly != 0 && req.ReadOnly != 1 { + panic(constant.BuildInvalidArgumentWithArgs("readonly范围不正确", "readonly param error")) + } + + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 + specialMatch := regexp.MustCompile("^[\u4e00-\u9fa5_a-zA-Z0-9_-]{1,64}$").MatchString + if !specialMatch(req.Name) { + panic(constant.BuildInvalidArgumentWithArgs("name格式不正确", "Name invalidate")) + } + +} +func (req *QueryApikeysRequest) Validate(logger *log.Logger) { + + validate(req, logger) + if req.Name != "" { + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 + specialMatch := regexp.MustCompile("^[\u4e00-\u9fa5_a-zA-Z0-9_-]{1,64}$").MatchString + if !specialMatch(req.Name) { + panic(constant.BuildInvalidArgumentWithArgs("name格式不正确", "Name invalidate")) + } + } + +} diff --git a/bmp-openapi/types/request/AuditLogsRequest.go b/bmp-openapi/types/request/AuditLogsRequest.go new file mode 100644 index 0000000..0bf5617 --- /dev/null +++ b/bmp-openapi/types/request/AuditLogsRequest.go @@ -0,0 +1,25 @@ +package request + +import log "coding.jd.com/aidc-bmp/bmp_log" + +type DescribeAuditLogsRequest struct { + // sn + Sn string `json:"sn" validate:"required"` + // 操作名称 + Operation string `json:"operation"` + // 操作人 + UserName string `json:"username"` + // result + Result string `json:"result"` + // 操作时间下限 + StartTime int `json:"startTime"` + // 操作时间上限 + EndTime int `json:"endTime"` + // 是否显示所有 + IsAll string `json:"isAll"` + Pageable +} + +func (req *DescribeAuditLogsRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi/types/request/BaseRequest.go b/bmp-openapi/types/request/BaseRequest.go new file mode 100644 index 0000000..f08acce --- /dev/null +++ b/bmp-openapi/types/request/BaseRequest.go @@ -0,0 +1,58 @@ +package request + +import ( + "fmt" + "reflect" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" + validator "github.com/go-playground/validator/v10" +) + +type Pageable struct { + // 页码 + PageNumber int64 `json:"pageNumber"` + // 每页数量 + PageSize int64 `json:"pageSize"` +} + +var va = validator.New() + +func InitValidator() { + va.RegisterTagNameFunc(func(fld reflect.StructField) string { + name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] + + // if name == "-" { + // return "" + // } + + return name + }) + + if err := va.RegisterValidation("required_in_ptr", ValidateRequiredInPtr); err != nil { + fmt.Println("required_in_ptr register error!!!") + } else { + fmt.Println("required_in_ptr register success!!!") + } +} + +func ValidateRequiredInPtr(fl validator.FieldLevel) bool { + + return true +} + +func validate(req interface{}, logger *log.Logger) { + if err := va.Struct(req); err != nil { + fmt.Println(err, err.Error()) + logger.Warn("Validate error:", err.Error()) + var e string + v, ok := err.(validator.ValidationErrors) + if !ok { + e = err.Error() + } else { + e = v[0].Field() + } + panic(constant.BuildInvalidArgumentWithArgs(e+" 非法", e+" invalid")) + } +} diff --git a/bmp-openapi/types/request/CollectDeviceInfoRequest.go b/bmp-openapi/types/request/CollectDeviceInfoRequest.go new file mode 100644 index 0000000..a2c8294 --- /dev/null +++ b/bmp-openapi/types/request/CollectDeviceInfoRequest.go @@ -0,0 +1,32 @@ +package request + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + + log "coding.jd.com/aidc-bmp/bmp_log" + validator "github.com/go-playground/validator/v10" +) + +type CollectDeviceInfoRequest struct { + // 待采集项 + // required: true + Collects []CollectItem `json:"collects" validate:"required"` +} + +type CollectItem struct { + // sn + // required: true + Sn string `json:"sn"` + // 可选参数。 传参:True, False 。True表示传入的raid_driver值将覆盖已适配机器的raid_driver + // Extensions: + // x-nullable: true + AllowOverride bool `json:"allowOverride"` +} + +func (c *CollectDeviceInfoRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("CollectDeviceInfoRequest Validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } + +} diff --git a/bmp-openapi/types/request/CommandsRequest.go b/bmp-openapi/types/request/CommandsRequest.go new file mode 100644 index 0000000..9cc0120 --- /dev/null +++ b/bmp-openapi/types/request/CommandsRequest.go @@ -0,0 +1,36 @@ +package request + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" + "github.com/go-playground/validator/v10" +) + +type CancelCommandsRequest struct { + Sn string `json:"sn"` +} +type RetryCommandRequest struct { + OffsetCommandId *int64 `json:"offset_command_id" validate:"required"` +} + +func (c *RetryCommandRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("RetryCommandRequest.Validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } +} + +type QueryCommandsRequest struct { + RequestId string + Sn string + InstanceId string + PageNumber int + PageSize int +} + +func (c *QueryCommandsRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("QueryCommandsRequest.Validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } +} diff --git a/bmp-openapi/types/request/DeviceExcelBean.go b/bmp-openapi/types/request/DeviceExcelBean.go new file mode 100644 index 0000000..a5871af --- /dev/null +++ b/bmp-openapi/types/request/DeviceExcelBean.go @@ -0,0 +1,18 @@ +package request + +type DeviceExcelBean struct { + Id int `xlsx:"0"` //序号 + Region string `xlsx:"1"` //region + Az string `xlsx:"2"` //az + Sn string `xlsx:"3"` //SN号 + SystemIp string `xlsx:"4"` //系统IP + IloIp string `xlsx:"5"` //管理IP + DeviceType string `xlsx:"6"` //型号 + Cabinet string `xlsx:"7"` //机柜 + UPosition string `xlsx:"8"` //U位 + Mac1 string `xlsx:"9"` //mac1 + Mac2 string `xlsx:"10"` //mac2 + SwitchIp string `xlsx:"11"` //switchIp +} + +var DeviceExcelColumn []string = []string{"序号", "region", "az", "SN号", "系统IP", "管理IP", "型号", "机柜", "U位", "Mac1", "Mac2", "switchIP"} diff --git a/bmp-openapi/types/request/DeviceRequest.go b/bmp-openapi/types/request/DeviceRequest.go new file mode 100644 index 0000000..f858ef2 --- /dev/null +++ b/bmp-openapi/types/request/DeviceRequest.go @@ -0,0 +1,251 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateDevicesRequest struct { + // 机房uuid + // required: true + IDcID string `json:"idcId" validate:"required"` // 机房uuid + // // 机型uuid, 上传创建设备时不绑定机型,上架时才绑定机型 20240517 minping + // // required: true + // DeviceTypeID string `json:"deviceTypeId" validate:"required"` // 设备类型uuid + // 设备信息 + // required: true + Devices []*CreateDeviceSpec `json:"devices" validate:"required"` +} + +func (req *CreateDevicesRequest) Validate(logger *log.Logger) { + //validate(req, logger) + //if err := validator.New().Struct(c); err != nil { + // logger.Warn("CreateDevicesRequest.Validate error:", err.Error()) + // panic(constant.INVALID_ARGUMENT) + //} + for _, v := range req.Devices { //符合属性需要单独调用 + v.Validate(logger) + } +} + +type CreateDeviceSpec struct { + InstanceID string `json:"instanceId"` // 实例id + // 设备SN + // required: true + Sn string `json:"sn" validate:"required,min=1,max=128"` // 设备SN + // 设备状态,默认已入库 + ManageStatus string `json:"manageStatus"` // 设备状态: 未装机,已装机 + // 品牌 + // required: true + // Brand string `json:"brand" validate:"required,min=1,max=128"` //品牌 + // 型号 + // required: true + // Model string `json:"model" validate:"required,min=1,max=128"` //型号 + // 机柜编码 + // required: true + Cabinet string `json:"cabinet" validate:"required,min=1,max=128"` // 机柜编码 + // 所在U位 + // required: true + UPosition string `json:"uPosition" validate:"required,min=1,max=128"` // U位 + // 带外IP + // required: true + IloIP string `json:"iloIp" validate:"required,min=1,max=128"` // 带外管理IP + // 带外账号 + IloUser string `json:"iloUser"` // 带外账号 + // 带外密码 + IloPassword string `json:"iloPassword"` // 带外账号密码 + // MAC1(eth0) + // required: true + Mac1 string `json:"mac1" validate:"required,min=1,max=128"` // MAC1(eth0) + // MAC2(eth1) + // required: true + // Mac2 string `json:"mac2" validate:"required,min=1,max=128"` // MAC2(eth1) + /* + // 交换机1ip + // required: true + SwitchIP1 string `json:"switchIp1" validate:"required,min=1,max=128"` // 交换机1ip + // 交换机1port + // required: true + SwitchPort1 string `json:"switchPort1" validate:"required,min=1,max=128"` // 交换机1port + // 交换机2ip + // required: true + SwitchIP2 string `json:"switchIp2" validate:"required,min=1,max=128"` // 交换机2ip + // 交换机2port + // required: true + SwitchPort2 string `json:"switchPort2" validate:"required,min=1,max=128"` // 交换机2port + // 交换机1登录账号 + SwitchUser1 string `json:"switchUser1"` // 交换机1登录账号,如果为空,取所在机房的值 + // 交换机1登录密码 + SwitchPassword1 string `json:"switchPassword1"` // 交换机1登录密码 + // 交换机2登录账号 + SwitchUser2 string `son:"switchUser2"` // 交换机2登录账号,如果为空,取所在机房的值 + // 交换机2登录密码 + SwitchPassword2 string `json:"switchPassword2"` // 交换机2登录密码 + */ + // 描述 + Description string `json:"description"` // 描述 + // 网口交换机IP + // SwitchIP string `json:"switchIp"` // 网口交换机IP + // 子网掩码 + // required: true + Mask string `json:"mask" validate:"required,min=1,max=128"` // 子网掩码 + // eth1子网掩码 + // MaskEth1 string `json:"maskEth1" validate:"omitempty,min=1,max=128"` // eth1子网掩码 + // 网关地址 + // required: true + Gateway string `json:"gateway" validate:"required,min=1,max=128"` // 网关地址 + // 内网IPV4 + // required: true + PrivateIPv4 string `json:"privateIpv4" validate:"required,min=1,max=128"` // 内网IPV4 + // eth1内网IPV4(非bond模式时传值) + // PrivateEth1IPv4 string `json:"privateEth1Ipv4" validate:"omitempty,min=1,max=128"` // eth1内网IPV4 + // 内网IPV6 + PrivateIPv6 string `json:"privateIpv6"` // 内网IPV6 + // eth1内网IPV6(非bond模式时传值) + // PrivateEth1IPv6 string `json:"privateEth1Ipv6"` // eth1内网IPV6 + // adapter_id + // required: true + // AdapterID *int `json:"adapterId" validate:"required,min=0,max=10000"` // adapter_id + // raid工具:(megacli128等) + // RaidDriver string `json:"raidDriver" validate:"max=64"` // raid工具:(megacli128等) + + /* remove minping 20240517 + // 系统盘1背板号 + // required: true + Enclosure1 string `json:"enclosure1" validate:"required,min=0,max=10000"` //系统盘1背板号 + // 系统盘1槽位 + // required: true + Slot1 *int `json:"slot1" validate:"required,min=0,max=10000"` //系统盘1槽位 + // 系统盘2背板号 + Enclosure2 string `json:"Enclosure2" validate:"max=64"` //系统盘2背板号 + // 系统盘2槽位 + Slot2 int `json:"slot2" validate:"max=10000"` //系统盘2槽位 + //以后还能还有数据盘,todo + */ +} + +func (req *CreateDeviceSpec) Validate(logger *log.Logger) { + validate(req, logger) +} + +type ModifyAllDevicesRequest struct { + InstanceID string `json:"instanceId"` // 实例id + ManageStatus string `json:"manageStatus"` + UserId string `json:"userId"` + UserName string `json:"userName"` +} +type ModifyDevicesRequest struct { + // 修改设备描述 + // Extensions: + // x-nullable: true + Description *string `json:"description" validate:"omitempty,max=256"` +} + +func (req *ModifyDevicesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type MountDevicesRequest struct { + // 设备uuid + // required: true + DeviceID string `json:"deviceId" validate:"required"` +} + +func (req *MountDevicesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type UnMountDevicesRequest struct { + // 设备uuid + // required: true + DeviceID string `json:"deviceId" validate:"required"` +} + +func (req *UnMountDevicesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryDevicesRequest struct { + Pageable + // 机房id + IDcID string `json:"idcId"` + // 设备sn + Sn string `json:"sn"` + // 实例id + InstanceID string `json:"instanceId"` + // 实例名称 + InstanceName string `json:"instanceName"` + // 机型id + DeviceTypeID string `json:"deviceTypeId"` + // 设备管理状态 + ManageStatus string `json:"manageStatus"` + // 带外ip + IloIP string `json:"iloIp"` + // ipv4 + IPV4 string `json:"ipv4"` + // ipv6 + IPV6 string `json:"ipv6"` + // 机型类型 + DeviceSeries string `json:"deviceSeries"` + // 所属用户id + UserID string `json:"userId"` + // 所属用户 + UserName string `json:"userName"` + // 是否显示全部,1不分页 + IsAll string `json:"isAll"` + // "1"表示已采集,"2"表示未采集,"3"表示采集中,4表示采集失败 + CollectStatus string `json:"collectStatus"` +} + +func (req *QueryDevicesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type AssociateDeviceDisksRequest struct { + // device uuid + // required: true + DeviceID string `json:"deviceId" validate:"required"` // device uuid + // 设备类型id + // required: true + DeviceTypeID string `json:"deviceTypeId" validate:"required"` + // volumeid和磁盘uuid列表 + // required: true + Volumes []*AssociateDeviceDiskSpec `json:"volumes" validate:"required"` +} + +type AssociateDeviceDiskSpec struct { + VolumeID string `json:"volumeId" validate:"required"` + DiskIDs []string `json:"diskId" validate:"required"` +} + +func (req *AssociateDeviceDisksRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type GetAssociatedDisksRequest struct { + // device uuid + // required: true + DeviceID string `json:"deviceId" validate:"required"` // device uuid + // devicetype uuid + // required: true + DeviceTypeID string `json:"deviceTypeId" validate:"required"` // devicetype uuid + // volume uuid + // required: true + VolumeID string `json:"volumeId" validate:"required"` +} + +func (req *GetAssociatedDisksRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DeviceAssociateDeviceTypeRequest struct { + // 设备类型id + // required: true + DeviceTypeID string `json:"deviceTypeId" validate:"required"` + // 设备ID + // required: true + DeviceID string `json:"deviceId" validate:"required"` +} + +func (req *DeviceAssociateDeviceTypeRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi/types/request/DeviceTypeRaidRequest.go b/bmp-openapi/types/request/DeviceTypeRaidRequest.go new file mode 100644 index 0000000..e48cfe9 --- /dev/null +++ b/bmp-openapi/types/request/DeviceTypeRaidRequest.go @@ -0,0 +1,39 @@ +package request + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" + "github.com/go-playground/validator/v10" +) + +type CreateDeviceTypeRaidRequest struct { + RaidID string `json:"raidId"` + DeviceType string `json:"deviceType"` + DeviceTypeID string `json:"DeviceTypeId"` + VolumeType string `json:"volumeType"` + VolumeDetail string `json:"volumeDetail"` + AvailableValue int `json:"availableValue"` + SystemPartitionCount int `json:"systemPartitionCount"` + DiskType string `json:"diskType"` +} + +func (c *CreateDeviceTypeRaidRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("CreateDeviceTypeRaidRequest.Validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } +} + +type DeleteDeviceTypeRaidRequest struct { + RaidId string `json:"raidId"` + DeviceType string `json:"deviceType"` + VolumeType string `json:"volumeType"` + VolumeDetail string `json:"volumeDetail"` +} + +func (c *DeleteDeviceTypeRaidRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("DeleteDeviceTypeRaidRequest.Validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } +} diff --git a/bmp-openapi/types/request/DeviceTypeRequest.go b/bmp-openapi/types/request/DeviceTypeRequest.go new file mode 100644 index 0000000..b989cf7 --- /dev/null +++ b/bmp-openapi/types/request/DeviceTypeRequest.go @@ -0,0 +1,479 @@ +package request + +import ( + "fmt" + "regexp" + "sort" + "strconv" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/raidDao" + "coding.jd.com/aidc-bmp/bmp-openapi/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateDeviceTypeRequest struct { + // 机房id + // required: true + IDcID string `json:"idcId"` + // 机型名称1-64 + // required: true + Name string `json:"name" validate:"required,min=1,max=64"` + // 机型规格1-64 + // required: true + DeviceType string `json:"deviceType" validate:"required,min=1,max=64"` + // 机型类型,如computer storage gpu other + // required: true + DeviceSeries string `json:"deviceSeries" validate:"required,oneof=computer storage gpu other"` + // 体系架构,1-64 + // required: true + Architecture string `json:"architecture" validate:"required,oneof=x86_64 ARM64(aarch64) i386 LoongArch"` + // 【高度(U)】:显示机型高度 2,4 + // required: true + Height int `json:"height" validate:"required,oneof=2 4"` + // 描述0-256 + Description string `json:"description" validate:"max=256"` + // cpu数量1,10000 + // required: true + CPUAmount int `json:"cpuAmount" validate:"required,min=1,max=10000"` + // 单个cpu内核数1,10000 + // required: true + CPUCores int `json:"cpuCores" validate:"required,min=1,max=10000"` + // cpu厂商1-64 + // required: true + CPUManufacturer string `json:"cpuManufacturer" validate:"required,min=1,max=64"` + // cpu处理器型号1-64 + // required: true + CPUModel string `json:"cpuModel" validate:"required,min=1,max=64"` + // cpu频率(G)1-64 + // required: true + CPUFrequency string `json:"cpuFrequency" validate:"required,min=1,max=64"` + // 内存接口(DDR DDR2 DDR3 DDR4 DDR5) + // required: true + MemType string `json:"memType" validate:"required,oneof=DDR DDR2 DDR3 DDR4 DDR5"` + // 单个内存大小1,10000(GB) + // required: true + MemSize int `json:"memSize" validate:"required,min=1,max=10000"` + // 内存数量1-10000 + // required: true + MemAmount int `json:"memAmount" validate:"required,min=1,max=10000"` + // 内存主频(MHz)1-10000 + // required: true + MemFrequency int `json:"memFrequency" validate:"required,min=1,max=10000"` + // 网卡数量1-10000 + // required: true + NicAmount int `json:"nicAmount" validate:"required,min=1,max=2"` + // 【网口模式】【网络设置】: bond,dual,single + // required: true + InterfaceMode string `json:"interfaceMode" validate:"required,oneof=bond dual single"` + // 网卡传输速率(GE) 1-10000 + // required: true + NicRate int `json:"nicRate" validate:"required,min=1,max=10000"` + // gpu数量0-1000 + GpuAmount int `json:"gpuAmount" validate:"min=0,max=1000"` + // gpu品牌0-64 + GpuManufacturer string `json:"gpuManufacturer" validate:"min=0,max=64"` + // gpu型号0-64 + GpuModel string `json:"gpuModel" validate:"min=0,max=64"` + // CPU 预置规格 + // required: true + CpuSpec string `json:"cpuSpec" validate:"required,oneof=common user_defined"` + // 内存 预置规格 + // required: true + MemSpec string `json:"memSpec" validate:"required,oneof=common user_defined"` + //boot模式【UEFI Legacy/BIOS】支持多选,逗号分隔 + BootMode string `json:"boot_mode" validate:"omitempty"` + // 卷管理 + // required: true + Volumes []VolumeItem `json:"volumes"` + // 阵列卡是否需要配置 1 需要配置 2无需配置 + IsNeedRaid string `json:"isNeedRaid" validate:"required,oneof=need_raid no_need_raid"` +} +type VolumeItem struct { + DeviceTypeID string `json:"deviceTypeId"` + VolumeName string `json:"volumeName"` + VolumeType string `json:"volumeType"` + DiskType string `json:"diskType"` + InterfaceType string `json:"interfaceType"` + VolumeSize string `json:"volumeSize"` + VolumeUnit string `json:"volumeUnit"` + VolumeAmount int `json:"volumeAmount"` + RaidCan string `json:"raidCan"` + Raid string `json:"raid"` +} + +func (param *CreateDeviceTypeRequest) Validate(logger *log.Logger) { + validate(param, logger) + if param.NicAmount == 1 && param.InterfaceMode == "bond" { + panic(constant.BuildInvalidArgumentWithArgs("nicAmount和interfaceMode参数错误", "nicAmount not match interfaceMode")) + } + if param.GpuManufacturer == "" { + if param.GpuModel != "" || param.GpuAmount != 0 { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.GpuModel == "" { + if param.GpuManufacturer != "" || param.GpuAmount != 0 { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.GpuAmount == 0 { + if param.GpuManufacturer != "" || param.GpuModel != "" { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.BootMode != "" { + items := strings.Split(param.BootMode, ",") + for _, v := range items { + b := strings.TrimSpace(v) + if b != "UEFI" && b != "Legacy/BIOS" { + panic(constant.BuildInvalidArgumentWithArgs("boot_mode 非法", "boot_mode invalid")) + } + } + } + ValidVolumes(logger, param.Volumes) //校验卷相关逻辑 +} +func ValidVolumes(logger *log.Logger, volumes []VolumeItem) { + //raidMap := map[string]response.Raid{} + //raidList,_ := raidLogic.QueryRaidsAll(logger) + //for _,v := range raidList{ + // raidMap[v.RaidID] = *v + //} + count := 0 + for _, v := range volumes { + specialMatch := regexp.MustCompile("^[a-zA-Z0-9_-]{1,64}$").MatchString + if !specialMatch(v.VolumeName) { + panic(constant.BuildInvalidArgumentWithArgs("卷名称:"+v.VolumeName+",不合法", "volumeName invalid")) + } + if v.VolumeType == baseLogic.VOLUME_TYPE_SYSTEM { + count++ + } + if v.RaidCan == baseLogic.RAID_CAN_NO_RAID { + if v.InterfaceType != "NVME" { + panic(constant.BuildInvalidArgumentWithArgs("RAID配置为NO RAID时,接口类型必须是NVME", "no raid,interfaceType must be NVME")) + } + if v.VolumeAmount != 1 { + logger.Warn("NVME只能有1块盘") + panic(constant.BuildInvalidArgumentWithArgs("仅支持1块盘", "Only support 1 disk")) + } + } + if v.RaidCan == baseLogic.RAID_CAN_SINGLE_RAID_EN { + if v.VolumeAmount != 1 { + logger.Warn("RAID配置为单盘RAID0时,只能有1块盘") + panic(constant.BuildInvalidArgumentWithArgs("仅支持1块盘", "Only support 1 disk")) + } + } + raidList := strings.Split(v.Raid, ",") + raidAmountMap := map[string]int{ + "RAID0": 2, + "RAID1": 2, + "RAID5": 3, + "RAID10": 4, + } + if len(raidList) == 1 { + raidInfo, _ := raidDao.GetRaidById(logger, v.Raid) + if raidInfo != nil { + if v.RaidCan == baseLogic.RAID_CAN_RAID { + if v.VolumeAmount < raidAmountMap[raidInfo.Name] { + logger.Warn(fmt.Sprintf("RAID配置为RAID,RAID模式是%s,最低%d块盘", raidInfo.Name, raidAmountMap[raidInfo.Name])) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("最少%d块盘,数量是所选RAID需要的最大盘数", raidAmountMap[raidInfo.Name]), fmt.Sprintf("At least %d disks", raidAmountMap[raidInfo.Name]))) + } + } + //其他模式todo + } + } else if len(raidList) > 1 { + amount := []int{0} + for _, raidId := range raidList { + raidInfo, _ := raidDao.GetRaidById(logger, raidId) + if raidInfo != nil { + amount = append(amount, raidAmountMap[raidInfo.Name]) + //其他模式todo + } + } + fmt.Println(amount) + sort.Ints(amount) + max := amount[len(amount)-1] + if v.VolumeAmount < max { + logger.Warn("多种raid模式,最低数量为这几种模式允许的最大值" + strconv.Itoa(max)) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("最少%d块盘,数量是所选RAID需要的最大盘数", max), fmt.Sprintf("At least %d disks", max))) + } + } + + } + if count != 1 { + panic(constant.BuildInvalidArgumentWithArgs("有且只有一个系统卷", "only one system volume")) + } + +} + +type ModifyDeviceTypeRequest struct { + // 机房id + // Extensions: + // x-nullable: true + IDcID *string `json:"idcId" validate:"omitempty,min=1,max=64"` + // 机型名称 + // Extensions: + // x-nullable: true + Name *string `json:"name" validate:"omitempty,min=1,max=64"` + // 机型规格 + // Extensions: + // x-nullable: true + DeviceType *string `json:"deviceType" validate:"omitempty,min=1,max=64"` + // 机型类型,如计算型,存储型 + // Extensions: + // x-nullable: true + DeviceSeries *string `json:"deviceSeries" validate:"omitempty,oneof=computer storage gpu other"` + // 体系架构,如i386/x86_64/ ARM64(aarch64),默认 x86_64 + // Extensions: + // x-nullable: true + Architecture *string `json:"architecture" validate:"omitempty,oneof=x86_64 'ARM64(aarch64)' i386 LoongArch"` + // 【高度(U)】:显示机型高度 + // Extensions: + // x-nullable: true + Height *int `json:"height" validate:"omitempty,oneof=2 4"` + // 描述 + // Extensions: + // x-nullable: true + Description *string `json:"description" validate:"omitempty,min=0,max=256"` + // cpu数量 + // Extensions: + // x-nullable: true + CPUAmount *int `json:"cpuAmount" validate:"omitempty,min=0,max=10000"` + // 单个cpu内核数 + // Extensions: + // x-nullable: true + CPUCores *int `json:"cpuCores" validate:"omitempty,min=0,max=10000"` + // cpu厂商 + // Extensions: + // x-nullable: true + CPUManufacturer *string `json:"cpuManufacturer" validate:"omitempty,min=1,max=64"` + // cpu处理器型号 + // Extensions: + // x-nullable: true + CPUModel *string `json:"cpuModel" validate:"omitempty,min=1,max=64"` + // cpu频率(G) + // Extensions: + // x-nullable: true + CPUFrequency *string `json:"cpuFrequency" validate:"omitempty,min=1,max=64"` + // 内存接口(如DDR3,DDR4) + // Extensions: + // x-nullable: true + MemType *string `json:"memType" validate:"omitempty,oneof=DDR DDR2 DDR3 DDR4 DDR5"` + // 单个内存大小(GB) + // Extensions: + // x-nullable: true + MemSize *int `json:"memSize" validate:"omitempty,min=0,max=10000"` + // 内存数量 + // Extensions: + // x-nullable: true + MemAmount *int `json:"memAmount" validate:"omitempty,min=0,max=10000"` + // 内存主频(MHz) + // Extensions: + // x-nullable: true + MemFrequency *int `json:"memFrequency" validate:"omitempty,min=0,max=10000"` + // 网卡数量 + // Extensions: + // x-nullable: true + NicAmount *int `json:"nicAmount" validate:"omitempty,min=0,max=2"` + // 【网口模式】【网络设置】: 单网口,双网口bond,single + // Extensions: + // x-nullable: true + InterfaceMode *string `json:"interfaceMode" validate:"omitempty,oneof=bond dual single"` + // 网卡传输速率(GE) + // Extensions: + // x-nullable: true + NicRate *int `json:"nicRate" validate:"omitempty,min=0,max=10000"` + // 系统盘类型(SSD,HDD) + // Extensions: + // x-nullable: true + SystemVolumeType *string `json:"systemVolumeType" validate:"omitempty,oneof=SSD HDD"` + // 系统盘接口类型(SATA,SAS,NVME) + // Extensions: + // x-nullable: true + SystemVolumeInterfaceType *string `json:"systemVolumeInterfaceType" validate:"omitempty,oneof=SATA SAS NVME"` + // 系统盘单盘大小 + // Extensions: + // x-nullable: true + SystemVolumeSize *int `json:"systemVolumeSize" validate:"omitempty,min=0,max=100000"` + // 系统盘单盘大小单位 + // Extensions: + // x-nullable: true + SystemVolumeUnit *string `json:"systemVolumeUnit" validate:"omitempty,oneof=GB TB"` + // 系统盘数量 + // Extensions: + // x-nullable: true + SystemVolumeAmount *int `json:"systemVolumeAmount" validate:"omitempty,min=1,max=2"` + // gpu数量 + // Extensions: + // x-nullable: true + GpuAmount *int `json:"gpuAmount" validate:"omitempty,min=0,max=10000"` + // gpu厂商 + // Extensions: + // x-nullable: true + GpuManufacturer *string `json:"gpuManufacturer" validate:"omitempty,min=0,max=64"` + // gpu处理器型号 + // Extensions: + // x-nullable: true + GpuModel *string `json:"gpuModel" validate:"omitempty,min=0,max=64"` + // 数据盘类型 + // Extensions: + // x-nullable: true + DataVolumeType *string `json:"dataVolumeType" validate:"omitempty,oneof='' SSD HDD"` + // 数据盘接口类型 + // Extensions: + // x-nullable: true + DataVolumeInterfaceType *string `json:"dataVolumeInterfaceType" validate:"omitempty,oneof='' SATA SAS NVME"` + // 数据盘单盘大小 + // Extensions: + // x-nullable: true + DataVolumeSize *int `json:"dataVolumeSize" validate:"omitempty,min=0,max=100000"` + // 数据盘单盘大小单位 + // Extensions: + // x-nullable: true + DataVolumeUnit *string `json:"dataVolumeUnit" validate:"omitempty,oneof='' GB TB"` + // 数据盘数量 + // Extensions: + // x-nullable: true + DataVolumeAmount *int `json:"dataVolumeAmount" validate:"omitempty,min=0,max=10000"` + // 系统盘raid,支持多选,英文逗号分隔 + // Extensions: + // x-nullable: true + RaidID *string `json:"raidId"` + // CPU 预置规格 + // Extensions: + // x-nullable: true + CpuSpec *string `json:"cpuSpec" validate:"omitempty,oneof=common user_defined"` + // 内存 预置规格 + // Extensions: + // x-nullable: true + MemSpec *string `json:"memSpec" validate:"omitempty,oneof=common user_defined"` + //boot模式【UEFI Legacy/BIOS】支持多选,逗号分隔 + BootMode string `json:"boot_mode" validate:"omitempty"` + // 卷管理 + // Extensions: + // x-nullable: true + Volumes []VolumeItem `json:"volumes"` + // 阵列卡是否需要配置 1 需要配置 2无需配置 + // Extensions: + // x-nullable: true + IsNeedRaid *string `json:"isNeedRaid" validate:"omitempty,oneof=need_raid no_need_raid"` +} + +func (param *ModifyDeviceTypeRequest) Validate(logger *log.Logger) { + validate(param, logger) + + if (param.NicAmount != nil && *param.NicAmount == 1) && (param.InterfaceMode != nil && *param.InterfaceMode == "bond") { + panic(constant.BuildInvalidArgumentWithArgs("nicAmount和interfaceMode参数错误", "nicAmount not match interfaceMode")) + } + + if param.GpuManufacturer != nil && *param.GpuManufacturer == "" { + if param.GpuModel != nil && *param.GpuModel != "" || param.GpuAmount != nil && *param.GpuAmount != 0 { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.GpuModel != nil && *param.GpuModel == "" { + if param.GpuManufacturer != nil && *param.GpuManufacturer != "" || param.GpuAmount != nil && *param.GpuAmount != 0 { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + if param.GpuAmount != nil && *param.GpuAmount == 0 { + if param.GpuManufacturer != nil && *param.GpuManufacturer != "" || param.GpuModel != nil && *param.GpuModel != "" { + panic(constant.BuildInvalidArgumentWithArgs("gpu不合法", "gpu invalidate")) + } + } + + if param.BootMode != "" { + items := strings.Split(param.BootMode, ",") + for _, v := range items { + b := strings.TrimSpace(v) + if b != "UEFI" && b != "Legacy/BIOS" { + panic(constant.BuildInvalidArgumentWithArgs("boot_mode 非法", "boot_mode invalid")) + } + } + } + ValidVolumes(logger, param.Volumes) //校验卷相关逻辑 +} + +type QueryDeviceTypesRequest struct { + // 机型id + DeviceTypeID string `json:"deviceTypeId"` + // 机型规格 + DeviceType string `json:"deviceType"` + // 机房id + IdcID string `json:"idcId"` + // 机型名称 + Name string `json:"name"` + // 机型类型 + DeviceSeries string `json:"deviceSeries"` + Pageable + IsAll string `json:"isAll"` +} + +func (req *QueryDeviceTypesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryDeviceTypeImageRequest struct { + // 机型id + DeviceTypeID string `json:"deviceTypeId"` + // 镜像id + ImageID string `json:"imageId"` + // 体系架构 + Architecture string `json:"architecture"` + // 操作系统平台 + OsType string `json:"osType"` + // 镜像名称 + ImageName string `json:"imageName"` + // 版本号 + Version string `json:"version"` + // 操作系统ID + OsID string `json:"osId"` + // 镜像类型,预置,自定义 + Source string `json:"source"` + Pageable + // 是否显示全部 + IsAll string `json:"isAll"` +} + +func (req *QueryDeviceTypeImageRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryDeviceTypeRaidRequest struct { + // 机型id + DeviceTypeID string `json:"deviceTypeId"` + // 系统盘还是数据盘 + VolumeType string `json:"volumeType"` + // raidID + RaidID string `json:"raidId"` + // 是否显示所有 + IsAll string `json:"isAll"` +} + +func (req *QueryDeviceTypeRaidRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryDeviceTypeImagePartitionRequest struct { + // 机型id + DeviceTypeID string `json:"deviceTypeId"` //validate:"required" + // 镜像id + ImageID string `json:"imageId"` //validate:"required" + // 是否显示所有,isAll=1显示所有 + IsAll string `json:"isAll"` +} + +func (req *QueryDeviceTypeImagePartitionRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DescribeVolumesByDeviceTypeRequest struct { + // 机型id + DeviceTypeID string `json:"deviceTypeId" validate:"required"` // +} + +func (req *DescribeVolumesByDeviceTypeRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi/types/request/DiskRequest.go b/bmp-openapi/types/request/DiskRequest.go new file mode 100644 index 0000000..6d4f0f6 --- /dev/null +++ b/bmp-openapi/types/request/DiskRequest.go @@ -0,0 +1,31 @@ +package request + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" + "github.com/go-playground/validator/v10" +) + +type CreateDiskRequest struct { + DeviceID string `gorm:"column:device_id" json:"deviceId"` // 设备uuid + Enclosure string `gorm:"column:enclosure" json:"enclosure"` // enclosure + Slot int `gorm:"column:slot" json:"slot"` // 卡槽槽位 + DiskType string `gorm:"column:disk_type" json:"diskType"` // 磁盘类型:system,data + Size string `gorm:"column:size" json:"size"` // 硬盘大小,不确定精度(非nvme盘) + SizeUnit string `gorm:"column:size_unit" json:"sizeUnit"` // 硬盘大小单位 MB GB TB ,1024进制 + PdType string `gorm:"column:pd_type" json:"pdType"` // 硬盘类型 + AdapterID string `gorm:"column:adapter_id" json:"adapterId"` // 适配ID + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + //DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + //IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (c *CreateDiskRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("CreateDiskRequest validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } +} diff --git a/bmp-openapi/types/request/IdcDevicesRequest.go b/bmp-openapi/types/request/IdcDevicesRequest.go new file mode 100644 index 0000000..215fcb5 --- /dev/null +++ b/bmp-openapi/types/request/IdcDevicesRequest.go @@ -0,0 +1,19 @@ +package request + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" + validator "github.com/go-playground/validator/v10" +) + +type CreateIdcDevicesRequest struct { + Sns []string `json:"sns" validate:"required"` + DeviceType string `json:"device_type"` +} + +func (c *CreateIdcDevicesRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("CreateIdcDevicesRequest.Validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } +} diff --git a/bmp-openapi/types/request/IdcRequest.go b/bmp-openapi/types/request/IdcRequest.go new file mode 100644 index 0000000..31e5f71 --- /dev/null +++ b/bmp-openapi/types/request/IdcRequest.go @@ -0,0 +1,161 @@ +package request + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" + "regexp" +) + +type CreateIdcRequest struct { + // 机房名称 1-64 + // required: true + Name string `json:"name" validate:"required,min=1,max=64"` + // 机房英文名称 1-64 + // required: true + NameEn string `json:"nameEn" validate:"required,min=1,max=64"` + // 机房缩写 1-64 + // required: true + Shortname string `json:"shortname" validate:"required,min=1,max=64"` + // 机房等级 1-64 + // required: true + Level string `json:"level" validate:"required,min=1,max=64"` + // 机房地址 0-256 + Address string `json:"address" validate:"max=256"` + // 带外用户名 0-64 + IloUser string `json:"iloUser" validate:"max=64"` + // 带外密码 0-64 + IloPassword string `json:"iloPassword" validate:"max=64"` + // 交换机用户1 0-64 + SwitchUser1 string `json:"switchUser1" validate:"max=64"` + // 交换机密码1 0-64 + SwitchPassword1 string `json:"switchPassword1" validate:"max=64"` + // 交换机用户2 0-64 + SwitchUser2 string `json:"switchUser2" validate:"max=64"` + // 交换机密码2 0-64 + SwitchPassword2 string `json:"switchPassword2" validate:"max=64"` +} + +func (req *CreateIdcRequest) Validate(logger *log.Logger) { + validate(req, logger) + specialMatch := regexp.MustCompile("^[a-zA-Z0-9_`{};:\"!~#$%@^&*()+-]+$").MatchString + if !specialMatch(req.NameEn) { + panic(constant.BuildInvalidArgumentWithArgs("机房英文名称不合法", "nameEn invalidate")) + } +} + +type ModifyIdcRequest struct { + // 机房名称 1-64 + // Extensions: + // x-nullable: true + Name *string `json:"name" validate:"omitempty,min=1,max=64"` + // 机房英文名称 1-64 + // Extensions: + // x-nullable: true + NameEn *string `json:"nameEn" validate:"omitempty,min=1,max=64"` + // 机房缩写 1-64 + // Extensions: + // x-nullable: true + Shortname *string `json:"shortname" validate:"omitempty,min=1,max=64"` + // 机房等级 1-64 + // Extensions: + // x-nullable: true + Level *string `json:"level" validate:"omitempty,min=1,max=64"` + // 机房地址 0-256 + // Extensions: + // x-nullable: true + Address *string `json:"address" validate:"omitempty,min=0,max=256"` + // 带外用户名 0-64 + // Extensions: + // x-nullable: true + IloUser *string `json:"iloUser" validate:"omitempty,min=0,max=64"` + // 带外密码 0-64 + // Extensions: + // x-nullable: true + IloPassword *string `json:"iloPassword" validate:"omitempty,min=0,max=64"` + // 交换机用户1 0-64 + // Extensions: + // x-nullable: true + SwitchUser1 *string `json:"switchUser1" validate:"omitempty,min=0,max=64"` + // 交换机密码1 0-64 + // Extensions: + // x-nullable: true + SwitchPassword1 *string `json:"switchPassword1" validate:"omitempty,min=0,max=64"` + // 交换机用户2 0-64 + // Extensions: + // x-nullable: true + SwitchUser2 *string `json:"switchUser2" validate:"omitempty,min=0,max=64"` + // 交换机2密码 0-64 + // Extensions: + // x-nullable: true + SwitchPassword2 *string `json:"switchPassword2" validate:"omitempty,min=0,max=64"` +} + +func (req *ModifyIdcRequest) Validate(logger *log.Logger) { + validate(req, logger) + specialMatch := regexp.MustCompile("^[a-zA-Z0-9_`{};:\"!~#$%@^&*()+-]+$").MatchString + if req.NameEn != nil && !specialMatch(*req.NameEn) { + panic(constant.BuildInvalidArgumentWithArgs("机房英文名称不合法", "nameEn invalidate")) + } + //对于必填项校验方法 + //if param.Name != nil && (len(*param.Name) < 1 || len(*param.Name) > 64) { + // panic(constant.BuildInvalidArgumentWithArgs("机房名称不合法", "idcName invalidate")) + //} + //fmt.Println(len(*param.NameEn)) + //if param.NameEn != nil && (len(*param.NameEn) < 1 || len(*param.NameEn) > 64) { + // panic(constant.BuildInvalidArgumentWithArgs("机房英文名称不合法", "idc nameEn invalidate")) + //} + //if param.Shortname != nil && (len(*param.Shortname) < 1 || len(*param.Shortname) > 64) { + // panic(constant.BuildInvalidArgumentWithArgs("机房名称缩写不合法", "idc shortName invalidate")) + //} + //if param.Level != nil && (len(*param.Level) < 1 || len(*param.Level) > 64) { + // panic(constant.BuildInvalidArgumentWithArgs("机房等级不合法", "idc level invalidate")) + //} + ////非必填校验方法 + //if param.Address != nil && len(*param.Address) > 256 { + // panic(constant.BuildInvalidArgumentWithArgs("地址长度不合法", "idc address invalidate")) + //} + //if param.IloUser != nil && len(*param.IloUser) > 64 { + // panic(constant.BuildInvalidArgumentWithArgs("带外用户名长度不合法", "IloUser invalidate")) + //} + //if param.IloPassword != nil && len(*param.IloPassword) > 64 { + // panic(constant.BuildInvalidArgumentWithArgs("带外密码长度不合法", "IloPassword invalidate")) + //} + //if param.SwitchUser1 != nil && len(*param.SwitchUser1) > 64 { + // panic(constant.BuildInvalidArgumentWithArgs("SwitchUser1 长度不合法", "SwitchUser1 invalidate")) + //} + //if param.SwitchPassword1 != nil && len(*param.SwitchPassword1) > 64 { + // panic(constant.BuildInvalidArgumentWithArgs("SwitchPassword1 长度不合法", "SwitchPassword1 invalidate")) + //} + //if param.SwitchUser2 != nil && len(*param.SwitchUser2) > 64 { + // panic(constant.BuildInvalidArgumentWithArgs("SwitchUser2 长度不合法", "SwitchUser2 invalidate")) + //} + //if param.SwitchPassword2 != nil && len(*param.SwitchPassword2) > 64 { + // panic(constant.BuildInvalidArgumentWithArgs("SwitchPassword2 长度不合法", "SwitchPassword2 invalidate")) + //} +} + +type QueryIdcsRequest struct { + // 机房名称 + Name string `json:"name"` + // 机房英文名称 + NameEn string `json:"nameEn"` + // 机房等级 + Level string `json:"level"` + Pageable + // 是否显示所有 + IsAll string `json:"isAll"` +} + +func (req *QueryIdcsRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryIdcRequest struct { + // 机房ID + // required: true + IDcID string `json:"idcId" validate:"required"` +} + +func (req *QueryIdcRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi/types/request/ImageRequest.go b/bmp-openapi/types/request/ImageRequest.go new file mode 100644 index 0000000..31ed20e --- /dev/null +++ b/bmp-openapi/types/request/ImageRequest.go @@ -0,0 +1,185 @@ +package request + +import ( + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateImageRequest struct { + // 镜像名称 + // required: true + ImageName string `json:"imageName" validate:"required,min=1,max=200"` + // 体系架构 + // required: true + Architecture string `json:"architecture" validate:"required,oneof=x86_64 ARM64(aarch64) i386"` + // 操作系统平台 + // required: true + OsType string `json:"osType" validate:"required"` + // 版本号 + // required: true + Version string `json:"Version" validate:"required"` + // 镜像文件类型 + // required: true + Format string `json:"format" validate:"required"` + // 引导模式【UEFI Legacy/BIOS】 + // required: true + BootMode string `json:"boot_mode" validate:"required"` + // 镜像文件名称 + // required: true + Filename string `json:"filename" validate:"required"` + // 镜像上传地址 + // required: true + Url string `json:"url" validate:"required"` + // 文件hash值 + // required: true + Hash string `json:"hash"` + // 镜像类型,预置,自定义 + Source string `json:"source" validate:"oneof=common user_defined"` + // 描述 + Description string `json:"description"` + // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:50GiB,swap) + SystemPartition string `json:"systemPartition"` + // 数据分区信息 + DataPartition string `json:"dataPartition"` +} + +func (req *CreateImageRequest) Validate(logger *log.Logger) { + validate(req, logger) + if req.BootMode != "" { + items := strings.Split(req.BootMode, ",") + for _, v := range items { + b := strings.TrimSpace(v) + if b != "UEFI" && b != "Legacy/BIOS" { + panic(constant.BuildInvalidArgumentWithArgs("boot_mode invalid", "boot_mode 非法")) + } + } + } +} + +//镜像默认分区 +//[{"format":"swap","point":"swap","size":10240},{"format":"xfs","point":"/","size":51200}] +type Partition struct { + FsType string `json:"format"` //format + MountPoint string `json:"point"` //point + Size int `json:"size"` +} + +type ModifyImageRequest struct { + // 修改设备描述 + // Extensions: + // x-nullable: true + Description *string `json:"description" validate:"omitempty,max=256"` +} + +//// 镜像名称 +//ImageName string `json:"imageName" validate:"min=1,max=200"` +//// 操作系统id +//OsID string `json:"osId" validate:"omitempty,max=256"` +//// 文件类型 +//Format string `json:"format" validate:"omitempty,max=256"` +//// 文件名称 +//Filename string `json:"filename" validate:"omitempty,max=256"` +//// 镜像上传地址 +//Url string `json:"url" validate:"omitempty,max=500"` +//// 文件hash值 +//Hash string `json:"hash" validate:"omitempty,max=256"` +//// 镜像类型,预置,自定义 +//Source string `json:"source" validate:"omitempty,oneof=common user_defined"` +//// 修改设备描述 +//// Extensions: +//// x-nullable: true +//Description *string `json:"description" validate:"omitempty,max=256"` +//// 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:50GiB,swap) +//SystemPartition string `json:"systemPartition" validate:"omitempty,max=256"` +//// 数据分区信息 +//DataPartition string `json:"dataPartition" validate:"omitempty,max=256"` + +func (req *ModifyImageRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryImagesRequest struct { + // 镜像ID + ImageID string `json:"imageId"` + // 镜像名称 + ImageName string `json:"imageName"` + // 设备类型id + DeviceTypeID string `json:"deviceTypeId"` + // 版本号 + Version string `json:"version"` + // 操作系统ID + OsID string `json:"osId"` + // 镜像ID,数组,支持多个 + ImageIDs []string `json:"imageIds"` + // 镜像类型,预置,自定义 + Source string `json:"source"` + // 体系架构 + Architecture string `json:"architecture"` + // 操作系统平台 + OsType string `json:"osType"` + Pageable + // 是否显示全部 + IsAll string `json:"isAll"` +} + +func (req *QueryImagesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type AssociateImageRequest struct { + // 设备类型id + // required: true + DeviceTypeID string `json:"deviceTypeId" validate:"required"` + // 镜像ID,数组,支持多个 + // required: true + ImageIDs []string `json:"imageIds" validate:"required"` +} + +func (req *AssociateImageRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DissociatedImageRequest struct { + // 设备类型id + // required: true + DeviceTypeID string `json:"deviceTypeId" validate:"required"` + // 镜像ID + // required: true + ImageID string `json:"imageId" validate:"required"` +} + +func (req *DissociatedImageRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type AssociateDeviceTypeRequest struct { + // 镜像ID, + // required: true + ImageID string `json:"imageId" validate:"required"` + // 设备类型id,数组,支持多个 + // required: true + DeviceTypeIDs []string `json:"deviceTypeIds" validate:"required"` +} + +func (req *AssociateDeviceTypeRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryImageDeviceTypesRequest struct { + // 镜像ID + // required: true + ImageID string `json:"imageId" validate:"required"` + // 体系架构 + Architecture string `json:"architecture"` + Pageable + //镜像是否绑定了机型,0查询该镜像没有绑定的机型列表 1查询该镜像已经绑定了的机型列表 + IsBind string `json:"isBind"` + // 是否显示全部 + IsAll string `json:"isAll"` +} + +func (req *QueryImageDeviceTypesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi/types/request/InstanceRequest.go b/bmp-openapi/types/request/InstanceRequest.go new file mode 100644 index 0000000..8f9fc2a --- /dev/null +++ b/bmp-openapi/types/request/InstanceRequest.go @@ -0,0 +1,392 @@ +package request + +import ( + "errors" + "fmt" + "regexp" + "strings" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + "coding.jd.com/aidc-bmp/bmp-openapi/util" + + log "coding.jd.com/aidc-bmp/bmp_log" + validation "git.jd.com/cps-golang/ironic-common/ironic/common/Validation" + "github.com/go-playground/validator/v10" +) + +type CreateInstanceRequest struct { + // 项目ID + // required: true + ProjectID string `json:"projectId" validate:"required"` + // 机房ID + // required: true + IdcID string `json:"idcId" validate:"required"` + // 设备类型ID + // required: true + DeviceTypeID string `json:"deviceTypeId" validate:"required"` + // 镜像ID + // required: true + ImageID string `json:"imageId" validate:"required"` + // 系统盘RAID ID + // required: true + SystemVolumeRaidID string `json:"systemVolumeRaidId" validate:"required"` + // 系统盘分区 + SystemPartition []Partition `json:"systemPartition"` + // 实例名称 + // required: true + InstanceName string `json:"instanceName" validate:"required"` + // 主机名称 + HostName string `json:"hostname"` + // 密码 + Password string `json:"password"` + // 秘钥ID + SshKeyID string `json:"sshKeyId"` + // 创建数量 + Count int `json:"count" validate:"gte=1"` + // 描述 + Description string `json:"description" validate:"omitempty,max=256"` + + BootMode string `json:"boot_mode" validate:"omitempty,oneof=uefi bios"` +} + +func (req *CreateInstanceRequest) Validate(logger *log.Logger) { + validate(req, logger) + //name条件:2-128 个字符,以大小写字母或中文开头,可包含数字、“.”、“_”、“:”或“-” + specialMatch := regexp.MustCompile("^[.:\u4e00-\u9fa5_a-zA-Z0-9_-]{2,128}$").MatchString + if !specialMatch(req.InstanceName) { + panic(constant.BuildInvalidArgumentWithArgs("instanceName格式不正确", "Name invalidate")) + } + + if req.HostName != "" { + //hostname条件:长度为 2-64 个字符,允许使用点号(.)分隔字符成多段,每段允许使 用大小写字母、数字或连字符(-),但不能连续使用点号(.)或连字符(-)。不能以点号(.)或连字符(-)开头或结尾 + specialMatch := regexp.MustCompile("^[.a-zA-Z0-9-]{2,64}$").MatchString + if !specialMatch(req.HostName) { + panic(constant.BuildInvalidArgumentWithArgs("hostName格式不正确", "hostName invalidate")) + } + if strings.HasPrefix(req.HostName, ".") || strings.HasPrefix(req.HostName, "-") || strings.HasSuffix(req.HostName, ".") || strings.HasSuffix(req.HostName, "-") || strings.Contains(req.HostName, "..") || strings.Contains(req.HostName, "--") { + panic(constant.BuildInvalidArgumentWithArgs("hostName格式不正确", "hostName invalidate")) + } + + } + + //if req.UserName != "" { + // specialMatch := regexp.MustCompile("^[a-zA-Z0-9_-]{1,64}$").MatchString + // if !specialMatch(req.UserName) { + // panic(constant.BuildInvalidArgumentWithArgs("userName格式不正确", "userName invalidate")) + // } + //} + + if req.Password != "" { + //密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + lowercaseMatch := regexp.MustCompile(`[a-z]`).MatchString + uppercaseMatch := regexp.MustCompile(`[A-Z]`).MatchString + digitMatch := regexp.MustCompile(`\d`).MatchString + //()`~!@#$%&*_-+=|{}[]:";'<>,.?/ + specialMatch := regexp.MustCompile("[()`~!@#$%&*\\_\\-+=|{}\\[\\]:\";'<>,.?/]").MatchString + total := 0 + if lowercaseMatch(req.Password) { + total += 1 + } + if uppercaseMatch(req.Password) { + total += 1 + } + if digitMatch(req.Password) { + total += 1 + } + if specialMatch(req.Password) { + total += 1 + } + + if total >= 3 && len(req.Password) >= 8 && len(req.Password) <= 30 { + //pass + } else { + panic(constant.BuildInvalidArgumentWithArgs("password格式不正确", "password invalidate")) + } + } + + if len(req.SystemPartition) > 0 { + fsTypes := []string{"swap", "xfs", "ext2", "ext3", "ext4"} + for _, v := range req.SystemPartition { + if !util.InArray(v.FsType, fsTypes) { + logger.Warnf("CreateInstanceRequest.SystemPartition.format invalid:%s", v.FsType) + panic(constant.BuildInvalidArgumentWithArgs("format格式不正确", "format invalidate")) + } + if !util.InArray(v.MountPoint, []string{"swap", "/boot", "/var", "/", "/export", "/data0", "/home"}) { + logger.Warnf("CreateInstanceRequest.SystemPartition.MountPoint invalid:%s", v.MountPoint) + panic(constant.BuildInvalidArgumentWithArgs("point格式不正确", "point invalidate")) + } + if v.Size <= 0 { + logger.Warnf("CreateInstanceRequest.SystemPartition.Size invalid:%s", v.MountPoint) + panic(constant.BuildInvalidArgumentWithArgs("size格式不正确", "size invalidate")) + } + } + } + +} + +type ModifyInstanceRequest struct { + // 实例名称 + InstanceName string `json:"instanceName"` + // 描述 + // Extensions: + // x-nullable: true + Description *string `json:"description" validate:"omitempty,max=256"` +} + +func (c *ModifyInstanceRequest) Validate(logger *log.Logger) { + validate(c, logger) + if c.InstanceName != "" { + //name条件:2-128 个字符,以大小写字母或中文开头,可包含数字、“.”、“_”、“:”或“-” + specialMatch := regexp.MustCompile("^[.:\u4e00-\u9fa5_a-zA-Z0-9_-]{2,128}$").MatchString + if !specialMatch(c.InstanceName) { + panic(constant.BuildInvalidArgumentWithArgs("instanceName格式不正确", "Name invalidate")) + } + } + +} + +// 批量修改实例名称 +type ModifyInstancesRequest struct { + // 实例名称 + InstanceName string `json:"instanceName" validate:"required"` + // 实例id列表 + InstanceIDs []string `json:"instance_ids" validate:"required"` +} + +func (c *ModifyInstancesRequest) Validate(logger *log.Logger) { + validate(c, logger) + if c.InstanceName != "" { + //name条件:2-128 个字符,以大小写字母或中文开头,可包含数字、“.”、“_”、“:”或“-” + specialMatch := regexp.MustCompile("^[.:\u4e00-\u9fa5_a-zA-Z0-9_-]{2,128}$").MatchString + if !specialMatch(c.InstanceName) { + panic(constant.BuildInvalidArgumentWithArgs("instanceName格式不正确", "Name invalidate")) + } + } + +} + +// 批量删除实例 +type DeleteInstancesRequest struct { + // 实例id列表 + InstanceIDs []string `json:"instance_ids" validate:"required"` +} + +func (c *DeleteInstancesRequest) Validate(logger *log.Logger) { + validate(c, logger) +} + +type QueryInstancesRequest struct { + Pageable + // 实例ID + InstanceID string `json:"instanceId"` + // 实例名称,模糊搜索 + InstanceName string `json:"instanceName"` + // 设备类型ID + DeviceTypeID string `json:"deviceTypeId"` + // 运行状态 + Status string `json:"status"` + // 设备ID + DeviceID string `json:"deviceId"` + // SN + Sn string `json:"sn"` + // 机房ID + IdcID string `json:"idcId"` + // 项目ID + ProjectID string `json:"projectId"` + // 带外ip,精确搜索 + IloIP string `json:"ilo_ip"` + // ipv4,精确搜索 + IPV4 string `json:"ipv4"` + // ipv6,精确搜索 + IPV6 string `json:"ipv6"` + // 是否显示全部,取值为1时表示全部 + IsAll string `json:"isAll"` +} + +func (req *QueryInstancesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type RetryInstallInstanceRequest struct { + Password string `json:"password"` + UserData string `json:"user_data"` + //AliasIps []AliasIP `json:"alias_ips"` +} +type RetryReinstallInstanceRequest struct { + KeepData *bool `json:"keep_data" validate:"required"` + Password string `json:"password"` + UserData string `json:"user_data"` +} + +func (c *RetryReinstallInstanceRequest) Validate(logger *log.Logger) { + validate(c, logger) +} + +type RetryStartInstanceRequest struct { + InstanceIds []string `json:"instance_ids" validate:"required"` +} + +func (c *RetryStartInstanceRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("RetryStartInstanceRequest.Validate error:", err.Error()) + panic(constant.INVALID_ARGUMENT) + } + for _, instance_id := range c.InstanceIds { + if match, _ := regexp.MatchString(validation.REGEX_ID, instance_id); !match { + logger.Warn("RetryStartInstanceRequest.InstanceIds inValid:", c.InstanceIds) + panic(constant.INVALID_ARGUMENT) + } + } +} + +type StartInstancesRequest struct { + InstanceIds []string `json:"instanceIds" validate:"required"` +} + +func (req *StartInstancesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type StopInstancesRequest struct { + InstanceIds []string `json:"instanceIds" validate:"required"` +} + +func (req *StopInstancesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type RestartInstancesRequest struct { + InstanceIds []string `json:"instanceIds" validate:"required"` +} + +func (req *RestartInstancesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +// 重置实例密码 +type ResetInstancePasswdRequest struct { + // 新密码 + Password string `json:"password" validate:"required"` +} + +func (req *ResetInstancePasswdRequest) Validate(logger *log.Logger) { + validate(req, logger) + + if req.Password != "" { + //密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + lowercaseMatch := regexp.MustCompile(`[a-z]`).MatchString + uppercaseMatch := regexp.MustCompile(`[A-Z]`).MatchString + digitMatch := regexp.MustCompile(`\d`).MatchString + //()`~!@#$%&*_-+=|{}[]:";'<>,.?/ + specialMatch := regexp.MustCompile("[()`~!@#$%&*\\_\\-+=|{}\\[\\]:\";'<>,.?/]").MatchString + total := 0 + if lowercaseMatch(req.Password) { + total += 1 + } + if uppercaseMatch(req.Password) { + total += 1 + } + if digitMatch(req.Password) { + total += 1 + } + if specialMatch(req.Password) { + total += 1 + } + + if total >= 3 && len(req.Password) >= 8 && len(req.Password) <= 30 { + //pass + } else { + panic(constant.BuildInvalidArgumentWithArgs("password格式不正确", "password invalidate")) + } + } +} + +// 批量重置实例密码 +type ResetInstancesPasswdRequest struct { + // 实例id列表 + InstanceIDs []string `json:"instance_ids" validate:"required"` + // 新密码 + Password string `json:"password" validate:"required"` +} + +func (req *ResetInstancesPasswdRequest) Validate(logger *log.Logger) { + validate(req, logger) + + if req.Password != "" { + //密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + lowercaseMatch := regexp.MustCompile(`[a-z]`).MatchString + uppercaseMatch := regexp.MustCompile(`[A-Z]`).MatchString + digitMatch := regexp.MustCompile(`\d`).MatchString + //()`~!@#$%&*_-+=|{}[]:";'<>,.?/ + specialMatch := regexp.MustCompile("[()`~!@#$%&*\\_\\-+=|{}\\[\\]:\";'<>,.?/]").MatchString + total := 0 + if lowercaseMatch(req.Password) { + total += 1 + } + if uppercaseMatch(req.Password) { + total += 1 + } + if digitMatch(req.Password) { + total += 1 + } + if specialMatch(req.Password) { + total += 1 + } + + if total >= 3 && len(req.Password) >= 8 && len(req.Password) <= 30 { + //pass + } else { + panic(constant.BuildInvalidArgumentWithArgs("password格式不正确", "password invalidate")) + } + } +} + +type ReinstallInstanceRequest struct { + // 镜像ID + // required: true + ImageID string `json:"imageId" validate:"required"` + // 系统盘RAID ID + // required: true + SystemVolumeRaidID string `json:"systemVolumeRaidId"` //panfu安装时,不传此字段 + // 系统盘分区 + SystemPartition []Partition `json:"systemPartition"` + // 数据盘分区 + DataPartition []Partition `json:"dataPartition"` + // 实例名称 + // required: true + InstanceName string `json:"instanceName" validate:"required"` + // 主机名称 + HostName string `json:"hostname"` + // 密码 + Password string `json:"password" validate:"required"` + // 秘钥ID,运营平台重装,密钥暂时不可用 + SshKeyID string `json:"sshKeyId"` + // 描述 + Description string `json:"description" validate:"omitempty,max=256"` + // 引导模式 [UEFI Legacy/BIOS] + // required: true + BootMode string `json:"bootMode"` + + //是否安装bmp-agent + InstallBmpAgent bool `json:"installBmpAgent"` +} + +func (req *ReinstallInstanceRequest) Validate(logger *log.Logger) error { + if err := validator.New().Struct(req); err != nil { + logger.Warn("ReinstallInstanceRequest.Validate error:", err.Error()) + return fmt.Errorf("parameter validate error:%s", err.Error()) + } + + if match, _ := regexp.MatchString(validation.REGEX_ID, req.ImageID); !match { + logger.Warn("ReinstallInstanceRequest.ImageId invalid:", req.ImageID) + return errors.New("parameter ImageId invalid") + } + + b := strings.TrimSpace(req.BootMode) + if b != "UEFI" && b != "Legacy/BIOS" { + panic(constant.BuildInvalidArgumentWithArgs("boot_mode invalid", "boot_mode 非法")) + } + + return nil + +} diff --git a/bmp-openapi/types/request/InstanceSshkeyRequest.go b/bmp-openapi/types/request/InstanceSshkeyRequest.go new file mode 100644 index 0000000..81ef33c --- /dev/null +++ b/bmp-openapi/types/request/InstanceSshkeyRequest.go @@ -0,0 +1,18 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type QueryInstancesSshkeyRequest struct { + // 实例Id + InstanceId string `json:"instanceId"` + // 秘钥Id + SshkeyId string `json:"sshkeyId"` + // 是否显示全部 + IsAll string `json:"isAll"` +} + +func (req *QueryInstancesSshkeyRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi/types/request/LicenseRequest.go b/bmp-openapi/types/request/LicenseRequest.go new file mode 100644 index 0000000..aab07f7 --- /dev/null +++ b/bmp-openapi/types/request/LicenseRequest.go @@ -0,0 +1,5 @@ +package request + +type CreateLicenseRequest struct { + Content string `json:"content"` +} diff --git a/bmp-openapi/types/request/MessageRequest.go b/bmp-openapi/types/request/MessageRequest.go new file mode 100644 index 0000000..45fe947 --- /dev/null +++ b/bmp-openapi/types/request/MessageRequest.go @@ -0,0 +1,110 @@ +package request + +import ( + "regexp" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type QueryMessagesRequest struct { + Pageable + // 是否显示全部,取值为1时表示全部 + IsAll string `json:"isAll"` + //0:未读;1:已读;""不传表示全部 + HasRead string `json:"hasRead"` + // 消息类型 + MessageType string `json:"messageType"` + // 消息子类型 + MessageSubType string `json:"messageSubType"` + // 内容模糊搜索 + Detail string `json:"detail"` +} + +func (req *QueryMessagesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type ReadMessagesRequest struct { + + // required: true + MessageIds []string `json:"messageIds" validate:"required"` +} + +func (req *ReadMessagesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DeleteMessagesRequest struct { + // required: true + MessageIds []string `json:"messageIds" validate:"required"` +} + +func (req *DeleteMessagesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type GetMessageByIdRequest struct { + // required: true + MessageID string `json:"messageId" validate:"required"` +} + +func (req *GetMessageByIdRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type MailDialRequest struct { + // 邮件服务器地址 + // required: true + ServerAddr string `json:"server_addr" validate:"required"` + // 邮件服务器端口 + // required: true + ServerPort string `json:"server_port" validate:"required"` + // 管理员邮箱 + // required: true + AdminAddr string `json:"admin_addr" validate:"required"` + // 管理员邮箱密码 + // required: true + AdminPass string `json:"admin_pass" validate:"required"` + // 收件人邮箱地址 + To string `json:"to"` +} + +func (req *MailDialRequest) Validate(logger *log.Logger) { + validate(req, logger) + pattern := `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*` //匹配电子邮箱 + reg := regexp.MustCompile(pattern) + if !reg.MatchString(req.AdminAddr) { + panic(constant.BuildInvalidArgumentWithArgs("admin_addr格式不正确", "admin_addr invalidate")) + } +} + +type MailSaveRequest struct { + // 邮件服务器地址 + // required: true + ServerAddr string `json:"server_addr" validate:"required"` + // 邮件服务器端口 + // required: true + ServerPort string `json:"server_port" validate:"required"` + // 管理员邮箱 + // required: true + AdminAddr string `json:"admin_addr" validate:"required"` + // 管理员邮箱密码 + // required: true + AdminPass string `json:"admin_pass" validate:"required"` + // 收件人邮箱地址 + To string `json:"to"` +} + +func (req *MailSaveRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type SaveIsPushMailRequest struct { + // 是否推送邮件告警,0不推送,1推送 + IsPush string `json:"is_push"` +} + +func (req *SaveIsPushMailRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi/types/request/MonitorAlertRequest.go b/bmp-openapi/types/request/MonitorAlertRequest.go new file mode 100644 index 0000000..5474c10 --- /dev/null +++ b/bmp-openapi/types/request/MonitorAlertRequest.go @@ -0,0 +1,82 @@ +package request + +import log "coding.jd.com/aidc-bmp/bmp_log" + +type AddAlertRequest struct { + Alerts []*AddAlertItem `json:"alerts"` +} + +type AddAlertItem struct { + //规则名称 + RuleName string `json:"ruleName" validate:"required"` + //规则ID + // required: true + RuleID string `json:"ruleId" validate:"required"` + //实例id + // required: true + InstanceID string `json:"instanceId" validate:"required"` + //触发条件 + // required: true + Trigger string `json:"trigger" validate:"required"` + //告警值 + // required: true + AlertValue string `json:"alertValue" validate:"required"` + //告警时间戳 + // required: true + AlertTimestamp int64 `json:"alertTimestamp" validate:"required"` + //告警持续时间 + // required: true + AlertPeriod int `json:"alertPeriod" validate:"required"` +} + +func (req *AddAlertRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} + +type DescribeAlertRequest struct { + // rule uuid + // required: true + AlertID string `json:"alertId" validate:"required"` +} + +func (req *DescribeAlertRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DescribeAlertsRequest struct { + Pageable + // 是否显示全部,取值为1时表示全部 + IsAll string `json:"isAll"` + //user uuid + UserID string `json:"userId"` + //username + UserName string `json:"userName"` + //规则名称 + RuleName string `json:"ruleName"` + //规则uuid + RuleID string `json:"ruleId"` + //资源id,目前就是实例id + ResourceID string `json:"resourceId"` + //报警时间筛选stime + StartTime int64 `json:"startTime"` + //报警时间筛选etime + EndTime int64 `json:"endTime"` +} + +func (req *DescribeAlertsRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DeleteAlertRequest struct { + //告警id + // required: true + AlertId string `json:"alertId" validate:"required"` +} + +func (req *DeleteAlertRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} diff --git a/bmp-openapi/types/request/MonitorDataRequest.go b/bmp-openapi/types/request/MonitorDataRequest.go new file mode 100644 index 0000000..a19843b --- /dev/null +++ b/bmp-openapi/types/request/MonitorDataRequest.go @@ -0,0 +1,38 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +/* +{"params":{"serviceCode":"cps-vpc","resourceId":"cps-2qtflhpvmuuw5tdodatv6ofxqcek","filters":[{"name":"metric","values":["cps.process.total"]}],"startTime":"2024-06-09T00:00:00","endTime":"2024-06-12T23:59:59","timeInterval":"1h", "downSampleType":"avg"}} +*/ +type GetMonitorDataRequest struct { + //指标名称,支持多个,用逗号隔离开 + MetricName string `json:"metricName" validate:"required"` + //实例id + InstanceID string `json:"instanceId" validate:"required"` + //标签值 + Device string `json:"device"` + //开始时间戳 + StartTime int64 `json:"startTime"` + //结束时间戳 + EndTime int64 `json:"endTime"` + // 间隔多久一个点 s为单位 + TimeInterval int `json:"timeInterval"` + //最近多少时间,小时为单位 + LastManyTime int `json:"lastManyTime"` + //avg, min, max, sum + DownSampleType string `json:"downSampleType"` + + //以下为运营平台的 + UserName string `json:"userName"` + //idc uuid + IdcID string `json:"idcID"` +} + +func (req *GetMonitorDataRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} diff --git a/bmp-openapi/types/request/MonitorProxyRequest.go b/bmp-openapi/types/request/MonitorProxyRequest.go new file mode 100644 index 0000000..6067594 --- /dev/null +++ b/bmp-openapi/types/request/MonitorProxyRequest.go @@ -0,0 +1,26 @@ +package request + +import log "coding.jd.com/aidc-bmp/bmp_log" + +type DesrcibeAgentStatusRequest struct { + // InstanceId,多个用逗号分隔 + // required: true + InstanceID string `json:"instanceId" validate:"required"` +} + +func (req *DesrcibeAgentStatusRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DesrcibeTagsRequest struct { + // instanceId + // required: true + InstanceID string `json:"instanceId" validate:"required"` + // tagName [disk mountpoint nic] + // required: true + TagName string `json:"tagName" validate:"required,oneof=disk mountpoint nic"` +} + +func (req *DesrcibeTagsRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi/types/request/MonitorRuleRequest.go b/bmp-openapi/types/request/MonitorRuleRequest.go new file mode 100644 index 0000000..1b59670 --- /dev/null +++ b/bmp-openapi/types/request/MonitorRuleRequest.go @@ -0,0 +1,181 @@ +package request + +import log "coding.jd.com/aidc-bmp/bmp_log" + +type AddRuleRequest struct { + //规则名称 + // required: true + RuleName string `json:"ruleName" validate:"required"` + //维度 [instance、disk、mountpoint、nic] + // required: true + Dimension string `json:"dimension" validate:"required,oneof=instance disk mountpoint nic"` + //资源类型,目前只支持instance + // required: true + Resource string `json:"resource" validate:"required,oneof=instance"` + //触发条件 + // required: true + TriggerOption []RuleTrigger `json:"triggerOption"` + //通知策略 + // required: true + NoticeOption RuleNotice `json:"noticeOption"` + //实例id列表 + // required: true + InstanceIds []string `json:"instanceIds" validate:"required"` + //盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag"` +} + +func (req *AddRuleRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} + +///`{"alertname":"bmpInBand_mr_4msjd0x9vhw7owwur22j4fi4piqc_minping-mock-instanceId_bmp.cpu.util_","calculation":"avg","calculationUnit":"%","instanceId":"minping-mock-instanceId","metric":"bmp.cpu.util","noticeLevel":"1","noticePeriodLabel":"NoticePeriod-180m","operation":"gt","period":"1","ruleId":"mr_4msjd0x9vhw7owwur22j4fi4piqc","threshold":"1","times":"1"}` + +//单个触发条件 +type RuleTrigger struct { + //监控指标 cps.cpu.util + // required: true + Metric string `json:"metric" validate:"required"` + //周期(分钟) [1, 2, 5, 15, 30, 60] + // required: true + Period int64 `json:"period" validate:"required,oneof=1 2 5 15 30 60"` + //计算方式 [min max avg sum] + // required: true + Calculation string `json:"calculation" validate:"required,oneof=min max avg sum"` + //计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出] + CalculationUnit string `json:"calculationUnit"` + //比较方式 [> >= < <= == !=]或者[gt gte lt lte eq neq] + // required: true + Operation string `json:"operation" validate:"required"` + //阈值 + // required: true + Threshold float64 `json:"threshold"` + //持续周期数 [1, 2, 3, 4, 5, 10, 15, 30, 60] + // required: true + Times int64 `json:"times" validate:"required,oneof=1 2 3 4 5 10 15 30 60"` + //告警级别 [1表示一般,2表示严重,3表示紧急] + // required: true + NoticeLevel int64 `json:"noticeLevel" validate:"required,oneof=1 2 3"` +} + +//通知策略 +type RuleNotice struct { + //通知周期(分钟) [5 10 15 30 60 180 360 720 1440] + // required: true + NoticePeriod int64 `json:"noticePeriod" validate:"required,oneof=5 10 15 30 60 180 360 720 1440"` + // 有效时段开始时间 ["00:00:00"] + // required: true + EffectiveIntervalStart string `json:"effectiveIntervalStart" validate:"required"` + // 有效时段结束时间 ["23:59:59"] + // required: true + EffectiveIntervalEnd string `json:"effectiveIntervalEnd" validate:"required"` + //通知条件,可多选 [1表示报警, 2表示恢复正常] + // required: true + NoticeCondition []int64 `json:"noticeCondition" validate:"required"` + //接收渠道,可多选 [1表示站内信, 2表示邮件] + // required: true + NoticeWay []int64 `json:"noticeWay" validate:"required"` + //通知对象 + // required: true + UserID string `json:"userId" validate:"required"` +} + +type DescribeRuleRequest struct { + // rule uuid + // required: true + RuleID string `json:"ruleId" validate:"required"` +} + +func (req *DescribeRuleRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type DescribeRulesRequest struct { + Pageable + // 是否显示全部,取值为1时表示全部 + IsAll string `json:"isAll"` + //user uuid + UserID string `json:"userId"` + //username + UserName string `json:"userName"` + //规则名称 + RuleName string `json:"ruleName"` + //规则uuid + RuleID string `json:"ruleId"` + //1 正常,2 禁用,3 报警 + Status int `json:"status"` +} + +func (req *DescribeRulesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type EditRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` + //规则名称 + // required: true + RuleName string `json:"ruleName" validate:"required"` + //维度 [instance、disk、mountpoint、nic] + // required: true + Dimension string `json:"dimension" validate:"required,oneof=instance disk mountpoint nic"` + //资源类型,目前只支持instance + // required: true + Resource string `json:"resource" validate:"required,oneof=instance"` + //触发条件 + // required: true + TriggerOption []RuleTrigger `json:"triggerOption"` + //通知策略 + // required: true + NoticeOption RuleNotice `json:"noticeOption"` + //实例id列表 + // required: true + InstanceIds []string `json:"instanceIds" validate:"required"` + //盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag"` +} + +func (req *EditRuleRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} + +type EnableRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` +} + +func (req *EnableRuleRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} + +type DisableRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` +} + +func (req *DisableRuleRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} + +type DeleteRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` +} + +func (req *DeleteRuleRequest) Validate(logger *log.Logger) { + + validate(req, logger) + +} diff --git a/bmp-openapi/types/request/OsRequest.go b/bmp-openapi/types/request/OsRequest.go new file mode 100644 index 0000000..26556d3 --- /dev/null +++ b/bmp-openapi/types/request/OsRequest.go @@ -0,0 +1,63 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateOSRequest struct { + // 操作系统名称 + // required: true + OsName string `json:"osName" validate:"required,min=1,max=200"` + // 操作系统平台 + // required: true + OsType string `json:"osType" validate:"required"` + // 体系架构 + // required: true + Architecture string `json:"architecture" validate:"required"` + // 位数 + // required: true + Bits int `json:"bits" validate:"required"` + // 操作系统版本 + // required: true + OsVersion string `json:"osVersion" validate:"required"` + // 系统用户 + SysUser string `json:"sysUser"` +} + +func (req *CreateOSRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type ModifyOSRequest struct { + // 操作系统名称 + OsName string `json:"osName"` + // 操作系统平台 + OsType string `json:"osType"` + // 体系架构 + Architecture string `json:"architecture"` + // 位数 + Bits int `json:"bits" ` + // 操作系统版本 + OsVersion string `json:"osVersion"` + // 系统用户 + SysUser string `json:"sysUser"` +} + +func (req *ModifyOSRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryOssRequest struct { + // 操作系统名称 + OsName string `json:"osName"` + // 操作系统平台 + OsType string `json:"osType"` + // 操作系统版本 + OsVersion string `json:"osVersion"` + // 是否显示所有 + IsAll string `json:"isAll"` +} + +func (req *QueryOssRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi/types/request/ProjectRequest.go b/bmp-openapi/types/request/ProjectRequest.go new file mode 100644 index 0000000..c775405 --- /dev/null +++ b/bmp-openapi/types/request/ProjectRequest.go @@ -0,0 +1,71 @@ +package request + +import ( + "regexp" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateProjectRequest struct { + // ProjectName 1~64字符,只支持数字、大小写字母、中英文下划线“_”及中划线“-” + // required: true + ProjectName string `json:"projectName" validate:"required"` //项目名称 + // 是否作为该用户的默认项目, [0/1], 默认为0 + IsDefault int8 `json:"isDefault" validate:"omitempty,oneof=0 1"` + // 是否作为系统项目, [0/1], 默认为0 + IsSystem int8 `json:"isSystem" validate:"omitempty,oneof=0 1"` +} + +func (req *CreateProjectRequest) Validate(logger *log.Logger) { + validate(req, logger) + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 + specialMatch := regexp.MustCompile("^[\u4e00-\u9fa5_a-zA-Z0-9_-]{1,64}$").MatchString + if !specialMatch(req.ProjectName) { + panic(constant.BuildInvalidArgumentWithArgs("projectName格式不正确", "Name invalidate")) + } + +} + +type ModifyProjectRequest struct { + // 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + // required: true + ProjectName string `json:"projectName" validate:"required"` +} + +func (req *ModifyProjectRequest) Validate(logger *log.Logger) { + validate(req, logger) + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 + specialMatch := regexp.MustCompile("^[\u4e00-\u9fa5_a-zA-Z0-9_-]{1,64}$").MatchString + if !specialMatch(req.ProjectName) { + panic(constant.BuildInvalidArgumentWithArgs("projectName格式不正确", "Name invalidate")) + } + +} + +type QueryProjectsRequest struct { + // 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + ProjectName string `json:"projectName"` + Owned int `json:"owned"` //0表示全部,1表示拥有者,2表示被共享者 + Pageable + IsAll string `json:"isAll"` +} + +func (req *QueryProjectsRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type ShareProjectRequest struct { + // from user_id + // required: true + OwnerID string `json:"ownerID" validate:"required"` + // to user_id + // required: true + SharerID string `json:"sharerID" validate:"required"` +} + +func (req *ShareProjectRequest) Validate(logger *log.Logger) { + validate(req, logger) + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 +} diff --git a/bmp-openapi/types/request/RaidRequest.go b/bmp-openapi/types/request/RaidRequest.go new file mode 100644 index 0000000..5fa1696 --- /dev/null +++ b/bmp-openapi/types/request/RaidRequest.go @@ -0,0 +1,37 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateRaidRequest struct { + // raid名称 + // required: true + Name string `json:"name" validate:"required,min=1,max=16"` + // raid描述(中文) + // required: true + DescriptionEn string `json:"descriptionEn" validate:"required"` + // raid描述(英文) + // required: true + DescriptionZh string `json:"descriptionZh" validate:"required"` +} + +func (req *CreateRaidRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type ModifyRaidRequest struct { + // raid名称 + // required: true + Name string `json:"name" validate:"required,min=1,max=16"` + // raid描述(中文) + // required: true + DescriptionEn string `json:"descriptionEn" validate:"required"` + // raid描述(英文) + // required: true + DescriptionZh string `json:"descriptionZh" validate:"required"` +} + +func (req *ModifyRaidRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi/types/request/ResourceRequest.go b/bmp-openapi/types/request/ResourceRequest.go new file mode 100644 index 0000000..7125f8e --- /dev/null +++ b/bmp-openapi/types/request/ResourceRequest.go @@ -0,0 +1,24 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type QueryResourcesRequest struct { + /*// 机房名称 + IdcName string `json:"idcName"` + // 机房英文名称 + IdcNameEn string `json:"idcNameEn"`*/ + // 机型名称 + Name string `json:"name"` + // 机型规格 + DeviceType string `json:"deviceType"` + // 镜像名称 + ImageName string `json:"imageName"` + // 用户名称 + UserName string `json:"userName"` +} + +func (req *QueryResourcesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi/types/request/RoleRequest.go b/bmp-openapi/types/request/RoleRequest.go new file mode 100644 index 0000000..1e21f06 --- /dev/null +++ b/bmp-openapi/types/request/RoleRequest.go @@ -0,0 +1,44 @@ +package request + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateRoleRequest struct { + // 角色英文名称 + // required: true + RoleNameEn string `json:"roleNameEn" validate:"required"` + // 角色中文名称 + // required: true + RoleNameCn string `json:"roleNameCn" validate:"required"` + // 角色描述英文名称 + // required: true + DescriptionEn string `json:"descriptionEn" validate:"required"` + // 角色描述中文名称 + // required: true + DescriptionCn string `json:"descriptionCn" validate:"required"` +} +type ModifyRoleRequest struct { + // 角色英文名称 + RoleNameEn string `json:"roleNameEn"` + // 角色中文名称 + RoleNameCn string `json:"roleNameCn"` + // 角色描述英文名称 + DescriptionEn string `json:"descriptionEn"` + // 角色描述中文名称 + DescriptionCn string `json:"descriptionCn"` +} + +func (req *CreateRoleRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type QueryRolesRequest struct { + Pageable + // 是否显示所有 + IsAll string `json:"isAll"` +} + +func (req *QueryRolesRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi/types/request/SshkeyRequest.go b/bmp-openapi/types/request/SshkeyRequest.go new file mode 100644 index 0000000..202c005 --- /dev/null +++ b/bmp-openapi/types/request/SshkeyRequest.go @@ -0,0 +1,61 @@ +package request + +import ( + "regexp" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + log "coding.jd.com/aidc-bmp/bmp_log" +) + +const REGEX_RSA_PUBLIC_KEY = "^ssh-rsa AAAAB3NzaC1yc2.*" + +type CreateSshkeyRequest struct { + // 秘钥名称 + // required: true + Name string `json:"name" validate:"required"` + // 公钥内容,格式:^ssh-rsa AAAAB3NzaC1yc2.* + // required: true + Key string `json:"key" validate:"required"` +} +type ModifySshkeyRequest struct { + // 秘钥名称 + // Extensions: + // x-nullable: true + Name *string `json:"name" validate:"omitempty,max=64"` +} + +func (req *CreateSshkeyRequest) Validate(logger *log.Logger) { + validate(req, logger) + //name条件:1~64 字符,只支持数字、大小写字母、英文下划线“_”及中划线 + specialMatch := regexp.MustCompile("^[a-zA-Z0-9_-]{1,64}$").MatchString + if !specialMatch(req.Name) { + panic(constant.BuildInvalidArgumentWithArgs("name格式不正确", "Name invalidate")) + } + if match, _ := regexp.MatchString(REGEX_RSA_PUBLIC_KEY, req.Key); !match { + logger.Warn("CreateKeypairRequest.PublicKey invalid", req.Key) + panic(constant.BuildInvalidArgumentWithArgs("公钥不合法", "publickey invalid")) + } + +} + +func (req *ModifySshkeyRequest) Validate(logger *log.Logger) { + validate(req, logger) + //name条件:1~64 字符,只支持数字、大小写字母、中英文下划线“_”及中划线 + specialMatch := regexp.MustCompile("^[a-zA-Z0-9_-]{1,64}$").MatchString + if req.Name != nil && !specialMatch(*req.Name) { + panic(constant.BuildInvalidArgumentWithArgs("name格式不正确", "Name invalidate")) + } + +} + +type QuerySshkeysRequest struct { + // 秘钥名称 + Name string `json:"name"` // 秘钥名称 + Pageable + // 是否显示全部 + IsAll string `json:"isAll"` +} + +func (req *QuerySshkeysRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi/types/request/UserRequest.go b/bmp-openapi/types/request/UserRequest.go new file mode 100644 index 0000000..3a356cf --- /dev/null +++ b/bmp-openapi/types/request/UserRequest.go @@ -0,0 +1,284 @@ +package request + +import ( + "fmt" + "regexp" + + "coding.jd.com/aidc-bmp/bmp-openapi/constant" + + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type CreateUserRequest struct { + + // 角色uuid + // required: true + RoleID string `json:"roleId"` + // 用户名,唯一, 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + // required: true + UserName string `json:"userName" validate:"required,min=1,max=64"` + // 邮箱 + Email string `json:"email" validate:"required,email"` + // 国家地区码,如86 + PhonePrefix string `json:"phonePrefix" validate:"required,min=1,max=64"` + // 手机号 + PhoneNumber string `json:"phoneNumber" validate:"required,min=1,max=64"` + // 用户默认项目uuid + DefaultProjectID string `json:"defaultProjectId"` + // 语言[en_US, zh_CN] + Language string `json:"language" validate:"omitempty,oneof=en_US zh_CN"` + // 时区,Asia/Shanghai + Timezone string `json:"timezone"` + // 密码 明文 密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + // required: true + Password string `json:"password"` + // 描述 + Description string `json:"description" validate:"max=256"` +} + +func (req *CreateUserRequest) Validate(logger *log.Logger) { + validate(req, logger) + //matched, err := regexp.MatchString(`^[a-zA-Z-_0-9]{1,32}$`, req.UserName) + //if err != nil { + // logger.Warn("CreateUserRequest.Validate error:", err.Error()) + // panic(constant.BuildInvalidArgumentWithArgs(err.Error(), err.Error())) + //} + //if !matched { + // logger.Warn("CreateUserRequest.Validate userName error") + // panic(constant.BuildInvalidArgumentWithArgs("用户名格式不正确", "userName invalidate")) + //} + + matchedPhone, err := regexp.MatchString(`^[0-9]+$`, req.PhoneNumber) + if err != nil { + logger.Warn("CreateUserRequest.Validate error:", err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(err.Error(), err.Error())) + } + if !matchedPhone { + logger.Warn("CreateUserRequest.Validate phoneNumber error") + panic(constant.BuildInvalidArgumentWithArgs("手机格式不正确", "phoneNumber invalidate")) + } + + if req.Timezone == "" { + req.Timezone = "Asia/Shanghai" + } + passwd := req.Password + //密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + lowercaseMatch := regexp.MustCompile(`[a-z]`).MatchString + uppercaseMatch := regexp.MustCompile(`[A-Z]`).MatchString + digitMatch := regexp.MustCompile(`\d`).MatchString + //()`~!@#$%&*_-+=|{}[]:";'<>,.?/ + specialMatch := regexp.MustCompile("[()`~!@#$%&*\\_\\-+=|{}\\[\\]:\";'<>,.?/]").MatchString + total := 0 + if lowercaseMatch(passwd) { + total += 1 + } + if uppercaseMatch(passwd) { + total += 1 + } + if digitMatch(passwd) { + total += 1 + } + if specialMatch(passwd) { + total += 1 + } + + if total >= 3 && len(passwd) >= 8 && len(passwd) <= 30 { + return + } + panic(constant.BuildInvalidArgumentWithArgs("密码格式不正确", "password invalidate")) +} + +type ModifyUserRequest struct { + // 邮箱 + // Extensions: + // x-nullable: true + Email *string `json:"email" validate:"omitempty,email"` + // 国家地区码,如86 + // Extensions: + // x-nullable: true + PhonePrefix *string `json:"phonePrefix" validate:"omitempty,min=1,max=64"` + // 手机号 + // Extensions: + // x-nullable: true + PhoneNumber *string `json:"phoneNumber" validate:"omitempty,min=1,max=64"` + // 描述 + // Extensions: + // x-nullable: true + Description *string `json:"description" validate:"omitempty,min=0,max=256"` +} + +func (req *ModifyUserRequest) Validate(logger *log.Logger) { + + validate(req, logger) + //matched, err := regexp.MatchString(`^[a-zA-Z-_0-9]{1,32}$`, req.UserName) + //if err != nil { + // logger.Warn("ModifyUserRequest.Validate error:", err.Error()) + // panic(constant.BuildInvalidArgumentWithArgs(err.Error(), err.Error())) + //} + //if !matched { + // logger.Warn("ModifyUserRequest.Validate userName error") + // panic(constant.BuildInvalidArgumentWithArgs("用户名格式不正确", "userName invalidate")) + //} + + if req.PhoneNumber != nil { + matchedPhone, err := regexp.MatchString(`^[0-9]+$`, *req.PhoneNumber) + if err != nil { + logger.Warn("ModifyUserRequest.Validate error:", err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(err.Error(), err.Error())) + } + if !matchedPhone { + logger.Warn("ModifyUserRequest.Validate phoneNumber error") + panic(constant.BuildInvalidArgumentWithArgs("手机格式不正确", "phoneNumber invalidate")) + } + } + +} + +type ModifyUserPasswordRequest struct { + // 旧密码,明文 + // required: true + OldPassword string `json:"oldPassword"` + // 新密码 明文,密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + // required: true + Password string `json:"password"` +} + +func (req *ModifyUserPasswordRequest) Validate(logger *log.Logger) { + + passwd := req.Password + //密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + lowercaseMatch := regexp.MustCompile(`[a-z]`).MatchString + uppercaseMatch := regexp.MustCompile(`[A-Z]`).MatchString + digitMatch := regexp.MustCompile(`\d`).MatchString + //()`~!@#$%&*_-+=|{}[]:";'<>,.?/ + specialMatch := regexp.MustCompile("[()`~!@#$%&*\\_\\-+=|{}\\[\\]:\";'<>,.?/]").MatchString + total := 0 + if lowercaseMatch(passwd) { + total += 1 + } + if uppercaseMatch(passwd) { + total += 1 + } + if digitMatch(passwd) { + total += 1 + } + if specialMatch(passwd) { + total += 1 + } + + if total >= 3 && len(passwd) >= 8 && len(passwd) <= 30 { + return + } + panic(constant.BuildInvalidArgumentWithArgs("密码格式不正确", "password invalidate")) + +} + +type ModifyLocalUserRequest struct { + // 邮箱 + // Extensions: + // x-nullable: true + Email *string `json:"email" validate:"omitempty,email"` + // 国家地区码,如86 + // Extensions: + // x-nullable: true + PhonePrefix *string `json:"phonePrefix" validate:"omitempty,min=0,max=64"` + // 手机号 + // Extensions: + // x-nullable: true + PhoneNumber *string `json:"phoneNumber" validate:"omitempty,min=0,max=64"` + // 用户默认项目uuid + // Extensions: + // x-nullable: true + DefaultProjectID *string `json:"defaultProjectId" validate:"omitempty,min=0,max=64"` + // 语言[en_US, zh_CN] + // Extensions: + // x-nullable: true + Language *string `json:"language" validate:"omitempty,oneof=en_US zh_CN"` // 语言(中文/English) + // 时区 Asia/Shanghai + // Extensions: + // x-nullable: true + Timezone *string `json:"timezone" validate:"omitempty,min=0,max=64"` +} + +func (req *ModifyLocalUserRequest) Validate(logger *log.Logger) { + + validate(req, logger) + if req.PhonePrefix != nil { + var phoneReg string + if *req.PhonePrefix == "086" { //中国大陆手机号 + phoneReg = `^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$` + } else if *req.PhonePrefix == "852" { //中国香港 + phoneReg = `^([5|6|9])\d{7}$` + } else if *req.PhonePrefix == "853" { //中国澳门 + phoneReg = `^6\d{7}$` + } else if *req.PhonePrefix == "886" { //中国台湾 + phoneReg = `^[0][9]\d{8}$` + } else { + phoneReg = `^[0-9]{1,}$` + } + + fmt.Println("dddd", *req.PhonePrefix) + if req.PhoneNumber != nil { + matchedPhone, err := regexp.MatchString(phoneReg, *req.PhoneNumber) + if err != nil { + logger.Warn("ModifyUserRequest.Validate error:", err.Error()) + panic(constant.BuildInvalidArgumentWithArgs(err.Error(), err.Error())) + } + if !matchedPhone { + logger.Warn("ModifyUserRequest.Validate phoneNumber error") + panic(constant.BuildInvalidArgumentWithArgs("手机格式不正确", "phoneNumber invalidate")) + } + } + } +} + +type GetUserByNameRequest struct { + + // 用户名,唯一 + // required: true + UserName string `json:"userName"` +} + +func (req *GetUserByNameRequest) Validate(logger *log.Logger) { + //matched, err := regexp.MatchString(`^[a-zA-Z-_0-9]{1,32}$`, req.UserName) + //if err != nil { + // logger.Warn("ModifyUserRequest.Validate error:", err.Error()) + // panic(constant.INVALID_ARGUMENT) + //} + //if !matched { + // logger.Warn("ModifyUserRequest.Validate projectName error") + // panic(constant.INVALID_ARGUMENT) + //} +} + +type QueryUsersRequest struct { + // 角色uuid + RoleID string `json:"roleId"` + // 项目uuid + DefaultProjectID string `json:"defaultProjectId"` + // 用户名 + UserName string `json:"userName"` + Pageable + // 是否显示全部, isAll=1表示全部 + IsAll string `json:"isAll"` +} + +func (req *QueryUsersRequest) Validate(logger *log.Logger) { + validate(req, logger) +} + +type VerifyUserRequest struct { + // 用户名,唯一 + // required: true + UserName string `json:"userName" validate:"required"` // + // 密码 + // required: true + Password string `json:"password" validate:"required"` // + // 角色uuid + // required: true + RoleID string `json:"roleId" validate:"required"` +} + +func (req *VerifyUserRequest) Validate(logger *log.Logger) { + validate(req, logger) +} diff --git a/bmp-openapi/types/response/ApiKey.go b/bmp-openapi/types/response/ApiKey.go new file mode 100644 index 0000000..be742f0 --- /dev/null +++ b/bmp-openapi/types/response/ApiKey.go @@ -0,0 +1,45 @@ +package response + +type Apikey struct { + ID int `json:"id"` + // apikey uuid + // required: true + ApikeyID string `json:"apiKeyId"` + // 名称 + // required: true + Name string `json:"name"` + // 是否支持只读, [0/1], 1表示只读 + // required: true + ReadOnly int8 `json:"readOnly"` + // 32位字符令牌,使用token来独立访问openapi + // required: true + Token string `json:"token"` + // apikey的类型,[system/user] + // required: true + Type string `json:"type"` + // 所属用户uuid + // required: true + UserID string `json:"userId"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` +} +type ApikeyList struct { + Apikeys []*Apikey `json:"apikeys"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type ApikeyInfo struct { + Apikey *Apikey `json:"apikey"` +} +type ApikeyId struct { + // apikey uuid + // required: true + ApikeyId string `json:"apikeyId"` +} diff --git a/bmp-openapi/types/response/AuditLogs.go b/bmp-openapi/types/response/AuditLogs.go new file mode 100644 index 0000000..d93f492 --- /dev/null +++ b/bmp-openapi/types/response/AuditLogs.go @@ -0,0 +1,61 @@ +package response + +import ( + "encoding/json" +) + +type AuditLog struct { + ID int `json:"id"` + // 日志uuid + LogID string `json:"logid"` + // 操作 + Operation string `json:"operation"` + // 操作名称 + OperationName string `json:"operationName"` + // 操作人 + UserName string `json:"userName"` + // 操作人 + UserID string `json:"userID"` + //sn + Sn string `json:"sn"` + //device_id + DeviceID string `json:"deviceId"` + //instance_id + InstanceID string `json:"instanceId"` + //结果 success/fail + Result string `json:"result"` + //失败原因 + FailReason string `json:"failReason"` // reason for fail + // 操作时间 + OperateTime int `json:"operateTime"` + // 完成时间 + FinishTime int `json:"finishTime"` +} + +type AuditLogList struct { + // 机型列表 + AuditLogs []*AuditLog `json:"auditLogs"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} + +func (d AuditLog) MarshalJSON() ([]byte, error) { + type Alias AuditLog + return json.Marshal(struct { + Alias + //CreateTime string `json:"create_time"` + //UpdateTime string `json:"update_time"` + }{ + Alias: Alias(d), + //CreateTime: d.CreateTime.Format("2006-01-02 15:04:05"), + //UpdateTime: d.UpdateTime.Format("2006-01-02 15:04:05"), + }) +} + +type AuditLogsType struct { + // 数据库中存储的operation + Operation string `json:"operation"` + // name,自动适配中英文 + Name string `json:"name"` +} diff --git a/bmp-openapi/types/response/CommonResponse.go b/bmp-openapi/types/response/CommonResponse.go new file mode 100644 index 0000000..070b2a1 --- /dev/null +++ b/bmp-openapi/types/response/CommonResponse.go @@ -0,0 +1,8 @@ +package response + +type CommonResponse struct { + // 操作是否成功 [true/false] + Success bool `json:"success"` +} +type CommonInfoResponse struct { +} diff --git a/bmp-openapi/types/response/Device.go b/bmp-openapi/types/response/Device.go new file mode 100644 index 0000000..7aff7dd --- /dev/null +++ b/bmp-openapi/types/response/Device.go @@ -0,0 +1,255 @@ +package response + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-openapi/dao/diskDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/raidDao" +) + +type Device struct { + // 机房uuid + // required: true + IdcID string `json:"idcId"` + //机型uuid + DeviceTypeID string `json:"deviceTypeId"` + // 设备ID编号 + ID int `json:"id"` + // 设备SN + Sn string `json:"sn"` + // 设备uuid + DeviceID string `json:"deviceId"` + // 实例id + InstanceID string `json:"instanceId"` + // 设备状态: 未装机,已装机 + ManageStatus string `json:"manageStatus"` + // 设备状态: 未装机,已装机 + ManageStatusName string `json:"manageStatusName"` + // 实例是否锁定 锁定locked 未锁定unlocked + Locked string `json:"locked"` + //品牌 + Brand string `json:"brand"` + //型号 + Model string `json:"model"` + // 设备状态变更失败原因 + Reason string `json:"reason"` + // 机柜编码 + Cabinet string `json:"cabinet"` + // U位 + UPosition string `json:"uPosition"` + // 带外管理IP + IloIP string `json:"iloIp"` + // 带外账号 + IloUser string `json:"iloUser"` + // 带外账号密码 + IloPassword string `json:"iloPassword"` + // MAC1(eth0) + Mac1 string `gorm:"column:mac1" json:"mac1"` + // MAC2(eth2) + Mac2 string `gorm:"column:mac2" json:"mac2"` + // 交换机1ip + SwitchIP1 string `gorm:"column:switch_ip1" json:"switchIp1"` + // 交换机1port + SwitchPort1 string `gorm:"column:switch_port1" json:"switchPort1"` + // 交换机2ip + SwitchIP2 string `gorm:"column:switch_ip2" json:"switchIp2"` + // 交换机2port + SwitchPort2 string `gorm:"column:switch_port2" json:"switchPort2"` + // 交换机1登录账号,如果为空,取所在机房的值 + SwitchUser1 string `json:"switchUser1"` + // 交换机1登录密码 + SwitchPassword1 string `json:"switchPassword1"` + // 交换机2登录账号,如果为空,取所在机房的值 + SwitchUser2 string `json:"switchUser2"` + // 交换机2登录密码 + SwitchPassword2 string `json:"switchPassword2"` + // 描述 + Description string `json:"description"` + // 网口交换机IP + SwitchIP string `json:"switchIp"` + // 子网掩码 + Mask string `json:"mask"` + // ETH1子网掩码 + Eth1Mask string `json:"eth1Mask"` + // 网关地址 + Gateway string `json:"gateway"` + // 内网IPV4 + PrivateIPv4 string `json:"privateIpv4"` + // 内网IPV6 + PrivateIPv6 string `json:"privateIpv6"` + // eth1内网IPV4 + PrivateEth1IPv4 string `json:"privateEth1Ipv4"` + // eth1内网IPV6 + PrivateEth1IPv6 string `json:"privateEth1Ipv6"` + // adapter_id + AdapterID int `json:"adapterId"` + // raid工具:(megacli64等) + RaidDriver string `json:"raidDriver"` + //添加到disk表, 系统盘1背板号 + Enclosure1 string `json:"enclosure1"` + //系统盘1槽位 + Slot1 int `json:"slot1"` + //系统盘2背板号 + Enclosure2 string `json:"Enclosure2"` + //系统盘2槽位 + Slot2 int `json:"slot2"` + //以后还能还有数据盘,todo + + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` + //DeletedTime int `json:"deletedTime"` // 删除时间戳 + //IsDel int8 `json:"isDel"` // 是否删除0未删除 1已删除 + + //以下是通过别的表查询出来的数据,用于返回给上层 + + //机房名称 + IdcName string `json:"idcName"` + //idcname + IDcNameEn string `json:"idcNameEn"` + //机型名称 + DeviceTypeName string `json:"deviceTypeName"` + + // 实例名称 + InstanceName string `json:"instanceName"` + // 实例镜像名称 + ImageName string `json:"imageName"` + // 实例状态 + InstanceStatus string `json:"instanceStatus"` + // 实例状态 + InstanceStatusName string `json:"instanceStatusName"` + // 实例失败原因 + InstanceReason string `json:"instanceReason"` + // 实例归属用户uuid + UserId string `json:"userId"` + // 实例归属用户名称 + UserName string `json:"userName"` + // 实例创建时间 + InstanceCreatedTime string `json:"instanceCreatedTime"` + // 实例描述 + InstanceDescription string `json:"instanceDescription"` + //机型配置 + + //型号,机型规格cps.normal + DeviceType string `json:"deviceType"` + //计算型,存储型 + DeviceSeries string `json:"deviceSeries"` + //计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName"` + // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Architecture string `json:"architecture"` + // cpu数量 + CPUAmount int `json:"cpuAmount"` + // 单个cpu内核数 + CPUCores int `json:"cpuCores"` + // 单个cpu路数 + CPURoads int8 `json:"cpuRoads"` + // cpu厂商 + CPUManufacturer string `json:"cpuManufacturer"` + // cpu处理器型号 + CPUModel string `json:"cpuModel"` + // cpu频率(G) + CPUFrequency string `json:"cpuFrequency"` + // 内存接口(如DDR3,DDR4) + MemType string `json:"memType"` + // 单个内存大小(GB) + MemSize int `json:"memSize"` + // 内存数量 + MemAmount int `json:"memAmount"` + // 内存主频(MHz) + MemFrequency int `json:"memFrequency"` + // 网卡数量 + NicAmount int `json:"nicAmount"` + // 网卡传输速率(GE) + NicRate int `json:"nicRate"` + // 【网口模式】【网络设置】: bond单网口,dual双网口 + InterfaceMode string `json:"interfaceMode"` + // 系统盘类型(SSD,HDD) + SystemVolumeType string `json:"systemVolumeType"` + // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeInterfaceType string `json:"systemVolumeInterfaceType"` + // 系统盘单盘大小 + SystemVolumeSize int `json:"systemVolumeSize"` + //SystemVolumeUnit string `json:"systemVolumeUnit"` // 系统盘单位(GB,TB) + + // 系统盘数量 + SystemVolumeAmount int `json:"systemVolumeAmount"` + // gpu数量 + GpuAmount int `json:"gpuAmount"` + // gpu厂商 + GpuManufacturer string `json:"gpuManufacturer"` + // gpu处理器型号 + GpuModel string `json:"gpuModel"` + // 数据盘类型(SSD,HDD) + DataVolumeType string `json:"dataVolumeType"` + // 数据盘接口类型(SATA,SAS,NVME) + DataVolumeInterfaceType string `json:"dataVolumeInterfaceType"` + // 数据盘单盘大小 + DataVolumeSize int `json:"dataVolumeSize"` + //DataVolumeUnit string `json:"dataVolumeUnit"` // 数据盘单位(GB,TB) + + // 数据盘数量 + DataVolumeAmount int `json:"dataVolumeAmount"` + + //拼装信息 + CpuInfo string `json:"cpuInfo"` + MemInfo string `json:"memInfo"` + SvInfo string `json:"svInfo"` + DvInfo string `json:"dvInfo"` + GpuInfo string `json:"gpuInfo"` + NicInfo string `json:"nicInfo"` + // "1"表示采集成功,"2"表示未采集,3表示采集中,4表示采集失败 + CollectStatus string `json:"collectStatus"` + CollectFailReason string `json:"collectFailReason"` + IsNeedRaid string `json:"isNeedRaid"` +} + +type DeviceList struct { + // 设备列表 + Devices []*Device `json:"devices"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type DeviceInfo struct { + // 设备 + Device *Device `json:"device"` +} +type DeviceIds struct { + // 设备id列表 + DeviceIds []string `json:"deviceIds"` +} +type DeviceStock struct { + // 库存量 + Stocks int `json:"stocks"` +} + +func (d Device) MarshalJSON() ([]byte, error) { + type Alias Device + return json.Marshal(struct { + Alias + //CreateTime string `json:"create_time"` + //UpdateTime string `json:"update_time"` + }{ + Alias: Alias(d), + //CreateTime: d.CreateTime.Format("2006-01-02 15:04:05"), + //UpdateTime: d.UpdateTime.Format("2006-01-02 15:04:05"), + }) +} + +type DeviceDisks struct { + Disks []*diskDao.Disk `json:"disks"` + Panfu []*diskDao.Disk `json:"panfu"` + Volumes []*VolumeIt `json:"volumes"` +} + +type VolumeIt struct { + Volume + Disks []*diskDao.Disk `json:"disks"` // disk uuid + Raids []*raidDao.Raid `json:"raids"` +} diff --git a/bmp-openapi/types/response/DeviceType.go b/bmp-openapi/types/response/DeviceType.go new file mode 100644 index 0000000..2a784fe --- /dev/null +++ b/bmp-openapi/types/response/DeviceType.go @@ -0,0 +1,158 @@ +package response + +import ( + "encoding/json" +) + +type DeviceType struct { + ID int `json:"id"` + // 机房uuid + IDcID string `json:"idcId"` + // 机房名称 + IDcName string `json:"idcName"` + // 机房名称 + IDcNameEn string `json:"idcNameEn"` + // 机型uuid + DeviceTypeID string `json:"deviceTypeId"` + // 机型名称,如计算效能型,标准计算型 + Name string `json:"name"` + // 机型规格, cps.c.normal + DeviceType string `json:"deviceType"` + // 机型类型,如计算型,存储型 + DeviceSeries string `json:"deviceSeries"` + // 机型类型,如计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName"` + // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Architecture string `json:"architecture"` + // 显示机型高度 + Height int `json:"height"` + // 描述 + Description string `json:"description"` + // cpu数量 + CPUAmount int `json:"cpuAmount"` + // 单个cpu内核数 + CPUCores int `json:"cpuCores"` + // cpu厂商 + CPUManufacturer string `json:"cpuManufacturer"` + // cpu处理器型号 + CPUModel string `json:"cpuModel"` + // cpu频率(G) + CPUFrequency string `json:"cpuFrequency"` + // 内存接口(如DDR3,DDR4) + MemType string `json:"memType"` + // 单个内存大小(GB) + MemSize int `json:"memSize"` + // 内存数量 + MemAmount int `json:"memAmount"` + // 内存主频(MHz) + MemFrequency int `json:"memFrequency"` + // 网卡数量 + NicAmount int `json:"nicAmount"` + // 网卡传输速率(GE) + NicRate int `json:"nicRate"` + // bond单网口,dual双网口 + InterfaceMode string `json:"interfaceMode"` + /*// 系统盘类型(SSD,HDD) + SystemVolumeType string `json:"systemVolumeType"` + // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeInterfaceType string `json:"systemVolumeInterfaceType"` + // 系统盘单盘大小 + SystemVolumeSize int `json:"systemVolumeSize"` + // 系统盘单位(GB,TB) + SystemVolumeUnit string `json:"systemVolumeUnit"` + // 系统盘数量 + SystemVolumeAmount int `json:"systemVolumeAmount"`*/ + // 是否做raid,[RAID/NORAID] + RaidCan string `json:"raidCan"` + // gpu数量 + GpuAmount int `json:"gpuAmount"` + // gpu厂商 + GpuManufacturer string `json:"gpuManufacturer"` + // gpu处理器型号 + GpuModel string `json:"gpuModel"` + //// 数据盘类型(SSD,HDD) + //DataVolumeType string `json:"dataVolumeType"` + //// 数据盘接口类型(SATA,SAS,NVME) + //DataVolumeInterfaceType string `json:"dataVolumeInterfaceType"` + //// 数据盘单盘大小 + //DataVolumeSize int `json:"dataVolumeSize"` + //// 数据盘单位(GB,TB) + //DataVolumeUnit string `json:"dataVolumeUnit"` + //// 数据盘数量 + //DataVolumeAmount int `json:"dataVolumeAmount"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` + // StockAvailable 可用库存 + StockAvailable int `json:"stockAvailable"` + //系统盘raid + Raid string `json:"raid"` + // CPU 规格,预置还是其它 + CpuSpec string `json:"cpuSpec"` + // 内存 规格,预置还是其它 + MemSpec string `json:"memSpec"` + + //拼装信息 + CpuInfo string `json:"cpuInfo"` + MemInfo string `json:"memInfo"` + SvInfo string `json:"svInfo"` + DvInfo string `json:"dvInfo"` + GpuInfo string `json:"gpuInfo"` + NicInfo string `json:"nicInfo"` + + InstanceCount int `json:"instanceCount"` + DeviceCount int `json:"deviceCount"` + InstanceStatus []string `json:"instanceStatus"` + //boot模式 + BootMode string `json:"boot_mode"` + Volumes []Volume `json:"volumes"` + //阵列卡是否需要配置 + IsNeedRaid string `json:"isNeedRaid"` +} +type Volume struct { + VolumeID string `json:"volumeId"` + VolumeName string `json:"volumeName"` + VolumeType string `json:"volumeType"` + DiskType string `json:"diskType"` + InterfaceType string `json:"interfaceType"` + VolumeSize string `json:"volumeSize"` + VolumeUnit string `json:"volumeUnit"` + VolumeAmount int `json:"volumeAmount"` + RaidCan string `json:"raidCan"` + Raid string `json:"raid"` + RaidId string `json:"raidId"` +} +type DeviceTypeList struct { + // 机型列表 + DeviceTypes []*DeviceType `json:"deviceTypes"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type DeviceTypeInfo struct { + // 机型信息 + DeviceType *DeviceType `json:"deviceType"` +} +type DeviceTypeId struct { + // 机型uuid + // required: true + DeviceTypeId string `json:"deviceTypeId"` +} + +func (d DeviceType) MarshalJSON() ([]byte, error) { + type Alias DeviceType + return json.Marshal(struct { + Alias + //CreateTime string `json:"create_time"` + //UpdateTime string `json:"update_time"` + }{ + Alias: Alias(d), + //CreateTime: d.CreateTime.Format("2006-01-02 15:04:05"), + //UpdateTime: d.UpdateTime.Format("2006-01-02 15:04:05"), + }) +} diff --git a/bmp-openapi/types/response/DeviceTypeImagePartitionResponse.go b/bmp-openapi/types/response/DeviceTypeImagePartitionResponse.go new file mode 100644 index 0000000..e102dcb --- /dev/null +++ b/bmp-openapi/types/response/DeviceTypeImagePartitionResponse.go @@ -0,0 +1,17 @@ +package response + +type QueryDeviceTypeImagePartitionResponse struct { + //系统盘分区列表 + SystemPartition []Partition `json:"systemPartition"` + //数据盘分区列表 + DataPartition []Partition `json:"dataPartition"` +} + +type Partition struct { + //format,如[swap, xfs] + FsType string `json:"format"` + //point,如[swap, /, /var] + MountPoint string `json:"point"` + // 分区大小, MB为单位 + Size int `json:"size"` +} diff --git a/bmp-openapi/types/response/Disk.go b/bmp-openapi/types/response/Disk.go new file mode 100644 index 0000000..12a75ef --- /dev/null +++ b/bmp-openapi/types/response/Disk.go @@ -0,0 +1,11 @@ +package response + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/dao/diskDao" +) + +type Disk struct { + diskDao.Disk + //是否选中 + Selected bool `json:"selected"` +} diff --git a/bmp-openapi/types/response/Idc.go b/bmp-openapi/types/response/Idc.go new file mode 100644 index 0000000..7f8fae2 --- /dev/null +++ b/bmp-openapi/types/response/Idc.go @@ -0,0 +1,68 @@ +package response + +type Idc struct { + ID int `json:"id"` + // 机房uuid + IDcID string `json:"idcId"` + // 机房名称 + Name string `json:"name"` + // 机房名称en + NameEn string `json:"nameEn"` + // shortname + Shortname string `json:"shortname"` + // 机房等级 + Level string `json:"level"` + // 机房地址 + Address string `json:"address"` + // 机房公用带外管理user + IloUser string `json:"iloUser"` + // 机房公用带外管理password + IloPassword string `json:"iloPassword"` + // 交换机用户名1 + SwitchUser1 string `json:"switchUser1"` + // 交换机密码1 + SwitchPassword1 string `json:"switchPassword1"` + // 交换机用户名2 + SwitchUser2 string `json:"switchUser2"` + // 交换机密码2 + SwitchPassword2 string `json:"switchPassword2"` + // 创建时间 + CreateTime string `json:"createTime"` + // 修改时间 + UpdateTime string `json:"updateTime"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 修改用户 + UpdatedBy string `json:"updatedBy"` +} +type IdcList struct { + // 机房列表 + Idcs []*Idc `json:"idcs"` + // 页数 + PageNumber int64 `json:"pageNumber"` + // 页大小 + PageSize int64 `json:"pageSize"` + // 总条数 + TotalCount int64 `json:"totalCount"` +} +type IdcInfo struct { + // 机房信息 + Idc *Idc `json:"idc"` +} +type IdcID struct { + // 机房id + IdcID string `json:"idcId"` +} + +//func (d Idc) MarshalJSON() ([]byte, error) { +// type Alias Idc +// return json.Marshal(struct { +// Alias +// CreateTime string `json:"createTime"` +// UpdateTime string `json:"updateTime"` +// }{ +// Alias: Alias(d), +// //CreateTime: time.Unix(d.CreateTime,0).Format("2006-01-02 15:04:05"), +// //UpdateTime: time.Unix(d.UpdateTime,0).Format("2006-01-02 15:04:05"), +// }) +//} diff --git a/bmp-openapi/types/response/Image.go b/bmp-openapi/types/response/Image.go new file mode 100644 index 0000000..e024c19 --- /dev/null +++ b/bmp-openapi/types/response/Image.go @@ -0,0 +1,69 @@ +package response + +type Image struct { + ID uint64 `json:"id"` // ID + // 镜像uuid + ImageID string `json:"imageId"` + // 镜像名称 + ImageName string `json:"imageName"` + // 源os uuid + OsID string `json:"osId"` + // 镜像格式(qcow2、tar) + Format string `json:"format"` + //boot模式 + BootMode string `json:"bootMode"` + // 镜像文件名称 + Filename string `json:"filename"` + // 镜像源路径 + URL string `json:"url"` + // 镜像校验码 + Hash string `json:"hash"` + // 镜像来源(common通用、customize定制、user_defined自定义) + Source string `json:"source"` + // 镜像来源(common通用、customize定制、user_defined自定义) + SourceName string `json:"sourceName"` + // 描述 + Description string `json:"description"` + // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + SystemPartition string `json:"systemPartition"` + // 数据分区信息 + DataPartition string `json:"dataPartition"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` + // 架构:x86/x64/i386/ + Architecture string `json:"architecture"` + //CentOS 7.2 64-bit + OsName string `json:"osName"` + // 操作系统分类:linux/windows + OsType string `json:"osType"` + // 操作系统版本 + OsVersion string `json:"osVersion"` + //绑定了机型数量 + DeviceTypeNum int `json:"deviceTypeNum"` + //是否绑定了某个机型 + IsBind bool `json:"isBind"` +} +type ImageList struct { + // 镜像实体列表 + Images []*Image `json:"images"` + // 页数 + PageNumber int64 `json:"pageNumber"` + // 页大小 + PageSize int64 `json:"pageSize"` + // 总条数 + TotalCount int64 `json:"totalCount"` +} +type ImageInfo struct { + // 镜像实体 + Image *Image `json:"image"` +} +type ImageId struct { + // 镜像uuid + ImageId string `json:"imageId"` +} diff --git a/bmp-openapi/types/response/Instance.go b/bmp-openapi/types/response/Instance.go new file mode 100644 index 0000000..41c73cf --- /dev/null +++ b/bmp-openapi/types/response/Instance.go @@ -0,0 +1,154 @@ +package response + +import ( + "coding.jd.com/aidc-bmp/bmp-openapi/dao/raidDao" + "coding.jd.com/aidc-bmp/bmp-openapi/dao/volumeDao" +) + +type Instance struct { + ID int `json:"-"` + // 实例uuid + InstanceID string `json:"instanceId"` // 实例ID(uuid) + // 机房uuid + IDcID string `json:"idcId"` + // 机房名称 + IdcName string `json:"idcName"` + // 实例所属项目UUID + ProjectID string `json:"projectId"` + // 实例所属用户UUID + UserID string `json:"userId"` + // 实例名称 + InstanceName string `json:"instanceName"` + // 设备uuid + DeviceID string `json:"deviceId"` + // 设备SN + Sn string `json:"sn"` + // 带外管理IP + IloIP string `json:"iloIp"` + // 内网IPV4 + PrivateIPv4 string `json:"privateIpv4"` + // 内网IPV6 + PrivateIPv6 string `json:"privateIpv6"` + // 机型uuid + DeviceTypeID string `json:"deviceTypeId"` + // 机型名称,如计算效能型,标准计算型 + DeviceTypeName string `json:"deviceTypeName"` + // 机型规格, cps.c.normal + DeviceType string `json:"deviceType"` + // 机型类型,如computer + DeviceSeries string `json:"deviceSeries"` + //机型类型,如计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName"` + // cpu数量 + CPUAmount int `json:"cpuAmount"` + // 单个cpu内核数 + CPUCores int `json:"cpuCores"` + // cpu厂商 + CPUManufacturer string `json:"cpuManufacturer"` + // cpu处理器型号 + CPUModel string `json:"cpuModel"` + // cpu频率(GHz) + CPUFrequency string `json:"cpuFrequency"` + // 内存接口(如DDR3,DDR4) + MemType string `json:"memType"` + // 单个内存大小(GB) + MemSize int `json:"memSize"` + // 内存数量 + MemAmount int `json:"memAmount"` + // 内存主频(MHz) + MemFrequency int `json:"memFrequency"` + // 网卡数量 + NicAmount int `json:"nicAmount"` + // 网卡传输速率(GE) + NicRate int `json:"nicRate"` + // 【网口模式】【网络设置】: bond单网口,dual双网口 + InterfaceMode string `json:"interfaceMode"` + // 系统盘类型(SSD,HDD) + SystemVolumeType string `json:"systemVolumeType"` + // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeInterfaceType string `json:"systemVolumeInterfaceType"` + // 系统盘单盘大小 + SystemVolumeSize int `json:"systemVolumeSize"` + // 系统盘数量 + SystemVolumeAmount int `json:"systemVolumeAmount"` + // 系统盘单位 + SystemVolumeUnit string `json:"systemVolumeUnit"` + // gpu数量 + GpuAmount int `json:"gpuAmount"` + // gpu厂商 + GpuManufacturer string `json:"gpuManufacturer"` + // gpu处理器型号 + GpuModel string `json:"gpuModel"` + // 数据盘类型(SSD,HDD) + DataVolumeType string `json:"dataVolumeType"` + // 数据盘接口类型(SATA,SAS,NVME) + DataVolumeInterfaceType string `json:"dataVolumeInterfaceType"` + // 数据盘单盘大小 + DataVolumeSize int `json:"dataVolumeSize"` + // 数据盘数量 + DataVolumeAmount int `json:"dataVolumeAmount"` + // 系统盘单位 + DataVolumeUnit string `json:"dataVolumeUnit"` + // 主机名 + Hostname string `json:"hostname"` + // 运行状态 + Status string `json:"status"` + // 实例错误状态时的错误原因 + Reason string `json:"reason"` + // 运行状态中文名字 + StatusName string `json:"statusName"` + // 镜像uuid + ImageID string `json:"imageId"` + // 镜像名称 + ImageName string `json:"imageName"` + // 系统盘raidId + SystemVolumeRaidID string `json:"systemVolumeRaidId"` + // 系统盘raid名称 + SystemVolumeRaidName string `json:"systemVolumeRaidName"` + //系统盘raid配置 + RaidCan string `json:"raidCan"` + // 是否锁定解锁锁定:locked,解锁unlocked + Locked string `json:"locked"` + // 是否锁定解锁锁定:已解锁,已锁定 + LockedName string `json:"lockedName"` + // 数据盘raidId + DataVolumeRaidID string `json:"dataVolumeRaidId"` + // 数据盘raid名称 + DataVolumeRaidName string `json:"DataVolumeRaidName"` + // 实例描述 + Description string `json:"description"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` + + //实例的volume和raid信息 + InstanceVolumeRaids []*InstanceVolumeRaid `json:"volumeRaid"` +} +type InstanceList struct { + // instance实体数组 + Instances []*Instance `json:"instances"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type InstanceInfo struct { + // instance实体 + Instance *Instance `json:"instance"` +} +type InstanceId struct { + InstanceId string `json:"instanceId"` +} +type InstanceIds struct { + // instanceId 列表 + InstanceIds []string `json:"instanceIds"` +} + +type InstanceVolumeRaid struct { + Volume *volumeDao.Volume `json:"volume"` + Raid *raidDao.Raid `json:"raid"` +} diff --git a/bmp-openapi/types/response/InstancePartitionResponse.go b/bmp-openapi/types/response/InstancePartitionResponse.go new file mode 100644 index 0000000..26456f8 --- /dev/null +++ b/bmp-openapi/types/response/InstancePartitionResponse.go @@ -0,0 +1,8 @@ +package response + +type QueryInstancePartitionResponse struct { + PartitionResult struct { + SystemPartition []Partition `json:"systemPartition"` + DataPartition []Partition `json:"dataPartition"` + } `json:"partition_result"` +} diff --git a/bmp-openapi/types/response/InstanceSshkey.go b/bmp-openapi/types/response/InstanceSshkey.go new file mode 100644 index 0000000..c0ec380 --- /dev/null +++ b/bmp-openapi/types/response/InstanceSshkey.go @@ -0,0 +1,17 @@ +package response + +type InstancesSshkeyResponse struct { + ID uint64 `json:"-"` // ID + InstanceID string `json:"instanceId"` // 实例ID + SSHkeyID string `json:"sshkeyId"` // sshkeyid + CreatedBy string `json:"createdBy"` // 创建者 + UpdatedBy string `json:"updatedBy"` // 更新者 + CreatedTime string `json:"createdTime"` // 创建时间 + UpdatedTime string `json:"updatedTime"` // 更新时间 +} + +type InstancesSshkeyInfoResponse struct { + // 实例Id列表 + InstanceIds []string `json:"instanceIds"` + //SshkeyIds []string `json:"sshkeyIds"` // 秘钥Id +} diff --git a/bmp-openapi/types/response/Interface.go b/bmp-openapi/types/response/Interface.go new file mode 100644 index 0000000..937a7de --- /dev/null +++ b/bmp-openapi/types/response/Interface.go @@ -0,0 +1,10 @@ +package response + +type Interface struct { + Sn string `json:"sn"` + InterfaceName string `json:"interface_name"` + InterfaceType string `json:"interface_type"` + Mac string `json:"mac"` + SwitchIp string `json:"switch_ip"` + SwitchPort string `json:"switch_port"` +} diff --git a/bmp-openapi/types/response/License.go b/bmp-openapi/types/response/License.go new file mode 100644 index 0000000..e5f3ad9 --- /dev/null +++ b/bmp-openapi/types/response/License.go @@ -0,0 +1,27 @@ +package response + +type LicenseToken struct { + Msg string `json:"msg"` +} + +type LicenseContent struct { + HardWare string `json:"hardwareinfo"` + StartTime int64 `json:"start_time"` + EndTime int64 `json:"end_time"` + Models []string `json:"models"` + NodesNum int `json:"nodes_num"` + UsedNodesNum int `json:"used_nodes_num"` + Version string `json:"version"` + LicenseType string `json:"license_type"` + LicenseName string `json:"license_name"` + ModelList []ModuleItem `json:"modelList"` +} + +type ModuleItem struct { + ID int `json:"id"` + Name string `json:"name"` + NameEn string `json:"nameEn"` + Description string `json:"description"` + DescriptionEn string `json:"descriptionEn"` + Effective bool `json:"effective"` +} diff --git a/bmp-openapi/types/response/Message.go b/bmp-openapi/types/response/Message.go new file mode 100644 index 0000000..c2432a1 --- /dev/null +++ b/bmp-openapi/types/response/Message.go @@ -0,0 +1,54 @@ +package response + +import "coding.jd.com/aidc-bmp/bmp-openapi/dao/messageDao" + +type Message struct { + messageDao.WebMessage + //独一处的下划线,跟sdk一致 + IDcID string `json:"idc_id"` + IDcName string `json:"idc_name"` + ProjectID string `json:"project_id"` + ProjectName string `json:"project_name"` + DeviceID string `json:"device_id"` +} + +type MessageList struct { + Messages []*Message `json:"messages"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} + +type MessageStatistic struct { + TotalCount int64 `json:"totalCount"` + UnreadCount int64 `json:"unreadCount"` +} + +type HasUnreadMessage struct { + HasUnread bool `json:"hasUnread"` +} + +type MessageWithNextPrev struct { + Message *Message `json:"message"` + NextMessageId string `json:"nextMessageId"` + PrevMessageId string `json:"prevMessageId"` +} + +type MessageTypesResp map[string][]string + +type Mail struct { + // 邮件服务器地址 + ServerAddr string `json:"server_addr"` + // 邮件服务器端口 + ServerPort string `json:"server_port"` + // 管理员邮箱 + AdminAddr string `json:"admin_addr"` + // 管理员邮箱密码 + AdminPass string `json:"admin_pass"` + // 是否推送邮件告警,0不推送,1推送 + IsPush string `json:"is_push"` + // 收件人邮箱 + To string `json:"to"` + // 邮件功能是否验证过正常。1表示正常,其他表示异常 + IsPass string `json:"is_pass"` +} diff --git a/bmp-openapi/types/response/MonitorAlertResponse.go b/bmp-openapi/types/response/MonitorAlertResponse.go new file mode 100644 index 0000000..f81cea6 --- /dev/null +++ b/bmp-openapi/types/response/MonitorAlertResponse.go @@ -0,0 +1,44 @@ +package response + +type AlertList struct { + // rules数组 + Alerts []*Alert `json:"instances"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} + +type Alert struct { + // alert uuid + AlertID string `json:"alertId"` + // 告警时间戳 + AlertTime int64 `json:"alertTime"` + // rule obj + Rule *Rule `json:"rule"` + //涉及到哪些实例 + Instance *Instance `json:"instance"` + // 资源类型 [只支持instance一种] + Resource string `json:"resource"` + // 资源id,目前就是实例id + ResourceID string `json:"resourceId"` + // 资源名称,目前就是实例名称 + ResourceName string `json:"resourceName"` + // 触发条件,接口需要翻译 + Trigger string `json:"trigger"` + //触发条件描述 + TriggerDescription string `json:"triggerDescription"` + // 报警值 + AlertValue string `json:"alertValue"` + // 1表示一般,2表示严重,3表示紧急 + AlertLevel int64 `json:"alertLevel"` + //级别描述 + AlertLevelDescription string `json:"alertLevelDescription"` + // 告警持续时间(分钟为单位) + AlertPeriod int64 `json:"alertPeriod"` + // 通知对象 userid + UserID string `json:"userId"` + // 通知对象 用户名 + UserName string `json:"userName"` + // 创建时间戳 + CreatedTime int64 `json:"createdTime"` +} diff --git a/bmp-openapi/types/response/MonitorDataResponse.go b/bmp-openapi/types/response/MonitorDataResponse.go new file mode 100644 index 0000000..a0e0bb7 --- /dev/null +++ b/bmp-openapi/types/response/MonitorDataResponse.go @@ -0,0 +1,26 @@ +package response + +type DataEveryMetric struct { + Query MonitorDataQuery `json:"query"` + Data []*MonitorDataItem `json:"data"` +} + +type MonitorDataQuery struct { + //[bmp_monitor_counter bmp_monitor_gauge] + TableName string `json:"tableName"` + // MetricName string `json:"metricName"` + //[rate, increase] + SampleMethod string `json:"sampleMethod"` + //metric都放这里了 + Labels map[string]string `json:"labels"` + StartTime int64 `json:"startTime"` + EndTime int64 `json:"endTime"` + Step int `json:"step"` + //跟赛迪约定,转换单位放这里实现 + Func map[string]int `json:"func"` +} + +type MonitorDataItem struct { + Timestamp int64 `json:"timestamp"` + Value string `json:"value"` +} diff --git a/bmp-openapi/types/response/MonitorProxyResponse.go b/bmp-openapi/types/response/MonitorProxyResponse.go new file mode 100644 index 0000000..57d229e --- /dev/null +++ b/bmp-openapi/types/response/MonitorProxyResponse.go @@ -0,0 +1,20 @@ +package response + +type AgentStatusResponse struct { + AgentStatus []AgentStatusItem `json:"agentStatus"` +} + +type AgentStatusItem struct { + InstanceID string `json:"instance_id"` + SN string `json:"sn"` + AgentVersion string `json:"agent_version"` + Timestamp int64 `json:"timestamp"` + // 1->running 2->stopped 0->unknown + Status int `json:"status"` + //status 运行 停止 未知 + StatusName string `json:"statusName"` +} + +type TagsResponse struct { + Tags []string `json:"tags"` +} diff --git a/bmp-openapi/types/response/MonitorRuleResponse.go b/bmp-openapi/types/response/MonitorRuleResponse.go new file mode 100644 index 0000000..0eab448 --- /dev/null +++ b/bmp-openapi/types/response/MonitorRuleResponse.go @@ -0,0 +1,92 @@ +package response + +type RuleList struct { + // rules数组 + Rules []*Rule `json:"rules"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} + +type Rule struct { + //规则uuid + RuleID string `json:"ruleId"` + //规则名称 + RuleName string `json:"ruleName"` + //维度 [instance、disk、mountpoint、nic] + Dimension string `json:"dimension"` + //维度名称 [实例、盘符、挂载点、网卡] + DimensionName string `json:"dimensionName"` + //资源类型,目前只支持instance + Resource string `json:"resource"` + //资源类型名称 实例 + ResourceName string `json:"resourceName"` + //触发条件 + TriggerOption []*RuleTrigger `json:"triggerOption"` + //触发条件描述 + TriggerDescription []string `json:"triggerDescription"` + //通知策略 + NoticeOption *RuleNotice `json:"noticeOption"` + //实例id列表 + InstanceIds []string `json:"instanceIds"` + // 关联实例个数 + InstanceCount int64 `json:"instanceCount"` + //实例详细信息 + Instances []*Instance `json:"instances"` + //盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag"` + //此规则关联的资源数 + RelatedResourceCount int64 `json:"relatedResourceCount"` + //规则状态[1->正常,2->已禁用,3->报警] + Status int64 `json:"status"` + //规则状态名称 + StatusName string `json:"statusName"` + // user_id + UserID string `json:"userId"` + // user_name + UserName string `json:"userName"` +} + +//单个触发条件 +type RuleTrigger struct { + // [bmp_monitor_counter, bmp_monitor_gauge] + TableName string `json:"tableName"` + //监控指标 cps.cpu.util + Metric string `json:"metric"` + //监控指标名称 CPU使用率 + MetricName string `json:"metricName"` + //周期 5(分钟) + Period int `json:"period"` + //计算方式 [min max avg sum] + Calculation string `json:"calculation"` + //计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出] + CalculationUnit string `json:"calculationUnit"` + //比较方式 [> >= < <= == !=]或者[gt gte lt lte eq neq] + Operation string `json:"operation"` + //阈值 + Threshold float64 `json:"threshold"` + //持续周期数 [1, 2, 3, 5, 10, 15, 30, 60] + Times int `json:"times"` + //告警级别 [1表示一般,2表示严重,3表示紧急] + NoticeLevel int `json:"noticeLevel"` + //对此rule的描述 + Description string `json:"description"` +} + +//通知策略 +type RuleNotice struct { + //通知周期(分钟) [5 10 15 30 60 180 360 720 1440] + NoticePeriod int `json:"noticePeriod"` + // 有效时段开始时间 ["00:00:00"] + EffectiveIntervalStart string `json:"effectiveIntervalStart"` + // 有效时段结束时间 ["23:59:59"] + EffectiveIntervalEnd string `json:"effectiveIntervalEnd"` + //通知条件,可多选 [1表示报警, 2表示恢复正常] + NoticeCondition []int `json:"noticeCondition"` + //接收渠道,可多选 [1表示站内信, 2表示邮件] + NoticeWay []int `json:"noticeWay"` + //通知对象用户Id + UserID string `json:"userId"` + //通知对象用户 + UserName string `json:"userName"` +} diff --git a/bmp-openapi/types/response/Os.go b/bmp-openapi/types/response/Os.go new file mode 100644 index 0000000..30d3ea5 --- /dev/null +++ b/bmp-openapi/types/response/Os.go @@ -0,0 +1,45 @@ +package response + +type Os struct { + // ID + ID uint64 `json:"id"` + // 操作系统uuid + OsID string `json:"osId"` + // 操作系统名称 + OsName string `json:"osName"` + // 操作系统分类:linux/windows + OsType string `json:"osType"` + // 架构:x86/x64/i386/ + Architecture string `json:"architecture"` + // 指令宽度:64/32位 + Bits int `json:"bits"` + // 操作系统版本 + OsVersion string `json:"osVersion"` + // 管理员账户 + SysUser string `json:"sysUser"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` + // 删除时间 + DeletedTime string `json:"deletedTime"` + // 是否删除0未删除 1已删除 + IsDel int8 `json:"isDel"` +} + +type OsList struct { + // 操作系统列表 + Oss []*Os `json:"oss"` +} +type OsInfo struct { + // 操作系统实体 + Os *Os `json:"os"` +} +type OsId struct { + // 操作系统uuid + OsId string `json:"osId"` +} diff --git a/bmp-openapi/types/response/Project.go b/bmp-openapi/types/response/Project.go new file mode 100644 index 0000000..b42963f --- /dev/null +++ b/bmp-openapi/types/response/Project.go @@ -0,0 +1,41 @@ +package response + +type Project struct { + ID int `json:"-"` + // 项目名称 + ProjectName string `json:"projectName"` + // 项目uuid + ProjectID string `json:"projectId"` + // 项目下实例数量 + InstanceCount int64 `json:"instanceCount"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` + // 共享 + ShareProjects []ShareProject `json:"shareProjects"` + // 此项目的共享标志位,1为拥有,2为共享 + Owned int `json:"owned"` +} +type ProjectList struct { + // 项目实体列表 + Projects []*Project `json:"projects"` + // 页数 + PageNumber int64 `json:"pageNumber"` + // 页大小 + PageSize int64 `json:"pageSize"` + // 总条数 + TotalCount int64 `json:"totalCount"` +} +type ProjectInfo struct { + // 项目实体 + Project *Project `json:"project"` +} +type ProjectId struct { + // 项目uuid + ProjectId string `json:"projectId"` +} diff --git a/bmp-openapi/types/response/RDeviceTypeRaid.go b/bmp-openapi/types/response/RDeviceTypeRaid.go new file mode 100644 index 0000000..0213dad --- /dev/null +++ b/bmp-openapi/types/response/RDeviceTypeRaid.go @@ -0,0 +1,38 @@ +package response + +type RDeviceTypeRaid struct { + ID uint64 `json:"-"` // ID + // RAID uuid + RaidID string `json:"raidId"` + // 设备类型id + DeviceTypeID string `json:"deviceTypeId"` + // 磁盘类型 system/data + VolumeType string `json:"volumeType"` + // 磁盘详细信息 + VolumeDetail string `json:"volumeDetail"` + // 可用分区值,单位GB + AvailableValue int `json:"availableValue"` + // 系统盘noraid模式真实数量;此模式多块盘只能用一块 + SystemPartitionCount int `json:"systemPartitionCount"` + // 磁盘类型:SAS/SATA/SSD/NVME + DiskType string `json:"diskType"` + // 磁盘类型:SAS/SATA/SSD/NVME + DiskInterfaceType string `json:"DiskInterfaceType"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` +} +type RDeviceTypeRaidList struct { + RDeviceTypeRaids []*RDeviceTypeRaid `json:"rDeviceTypeRaids"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type RDeviceTypeRaidInfo struct { + RDeviceTypeRaid *RDeviceTypeRaid `json:"rDeviceTypeRaid"` +} diff --git a/bmp-openapi/types/response/Raid.go b/bmp-openapi/types/response/Raid.go new file mode 100644 index 0000000..71e895b --- /dev/null +++ b/bmp-openapi/types/response/Raid.go @@ -0,0 +1,27 @@ +package response + +type Raid struct { + // raid uuid + RaidID string `json:"raidId"` + // raid 名称 + Name string `json:"name"` + //中文描述 + DescriptionEn string `json:"descriptionEn"` + // description + DescriptionZh string `json:"descriptionZh"` +} +type RaidList struct { + //raid实体列表 + Raids []*Raid `json:"raids"` + //PageNumber int64 `json:"pageNumber"` + //PageSize int64 `json:"pageSize"` + //TotalCount int64 `json:"totalCount"` +} +type RaidInfo struct { + //raid实体 + Raid *Raid `json:"raid"` +} +type RaidId struct { + //raid uuid + RaidId string `json:"raidId"` +} diff --git a/bmp-openapi/types/response/Role.go b/bmp-openapi/types/response/Role.go new file mode 100644 index 0000000..65286df --- /dev/null +++ b/bmp-openapi/types/response/Role.go @@ -0,0 +1,44 @@ +package response + +type Role struct { + ID int `json:"-"` + // 角色uuid + RoleID string `json:"roleId"` + // 角色名称,唯一 + RoleNameEn string `json:"roleNameEn"` + // 角色名称,唯一 + RoleNameCn string `json:"roleNameCn"` + // 权限描述 + DescriptionEn string `json:"descriptionEn"` + // description + DescriptionCn string `json:"descriptionCn"` + // 角色名称 + RoleName string `json:"roleName"` + // 权限 + Permission string `json:"permission"` + // 用户数 + UserCount int `json:"userCount"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` +} +type RoleList struct { + //角色实体列表 + Roles []*Role `json:"roles"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type RoleInfo struct { + //角色实体 + Role *Role `json:"role"` +} +type RoleId struct { + //角色uuid + RoleId string `json:"roleId"` +} diff --git a/bmp-openapi/types/response/ShareProject.go b/bmp-openapi/types/response/ShareProject.go new file mode 100644 index 0000000..3f86a61 --- /dev/null +++ b/bmp-openapi/types/response/ShareProject.go @@ -0,0 +1,25 @@ +package response + +type ShareProject struct { + ID int `json:"-"` + // 项目名称 + ProjectName string `json:"projectName"` + // 项目uuid + ProjectID string `json:"projectId"` + // 项目拥有者用户id + OwnerUserID string `json:"ownerUserId"` + // 项目共享者用户id + SharedUserID string `json:"sharedUserId"` + // 项目拥有者用户名 + OwnerUserName string `json:"ownerUserName"` + // 项目拥有者用户名 + SharedUserName string `json:"sharedUserName"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` + + ShareProjects []ShareProject `json:"shareProjects"` +} diff --git a/bmp-openapi/types/response/SshKey.go b/bmp-openapi/types/response/SshKey.go new file mode 100644 index 0000000..4d3c39f --- /dev/null +++ b/bmp-openapi/types/response/SshKey.go @@ -0,0 +1,42 @@ +package response + +type Sshkey struct { + // id + Id int64 `json:"id"` + // 秘钥uuid + SshkeyId string `json:"sshkeyId"` // 秘钥uuid + // 所属用户uuid + UserId string `json:"userId"` + // 秘钥名称 + Name string `json:"name"` + // 公钥,格式:ssh-rsa AAA + Key string `json:"key"` + // 公钥指纹 + FingerPrint string `json:"fingerPrint"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` +} +type SshkeyList struct { + // sshkey实体列表 + Sshkeys []*Sshkey `json:"sshkeys"` + // 页数 + PageNumber int64 `json:"pageNumber"` + // 页大小 + PageSize int64 `json:"pageSize"` + // 总条数 + TotalCount int64 `json:"totalCount"` +} +type SshkeyInfo struct { + // sshkey实体 + Sshkey *Sshkey `json:"sshkey"` +} +type SshkeyId struct { + // sshkey uuid + SshkeyId string `json:"sshkeyId"` +} diff --git a/bmp-openapi/types/response/User.go b/bmp-openapi/types/response/User.go new file mode 100644 index 0000000..c5abeef --- /dev/null +++ b/bmp-openapi/types/response/User.go @@ -0,0 +1,61 @@ +package response + +type User struct { + // 用户id + ID int `json:"id"` + // 用户uuid + UserID string `json:"userId"` + // 角色uuid + RoleID string `json:"roleId"` + // 角色名称 + RoleName string `json:"roleName"` + // 用户名,唯一 + UserName string `json:"userName"` + // 邮箱 + Email string `json:"email"` + // 国家地区码,如86 + PhonePrefix string `json:"phonePrefix"` + // 手机号 + PhoneNumber string `json:"phoneNumber"` + // 用户默认项目uuid + DefaultProjectID string `json:"defaultProjectId"` + // 用户默认项目名称 + DefaultProjectName string `json:"defaultProjectName"` + // 用户拥有的项目数量 + ProjectCount int `json:"projectCount"` + // 用户拥有的实例数量 + InstanceCount int `json:"instanceCount"` + // 默认语言(en_US/zh_CN) + Language string `json:"language"` + // 时区 + Timezone string `gorm:"column:timezone" json:"timezone"` + Password string `json:"-"` + // 描述 + Description string `json:"description"` + // 创建者 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` + // 更新者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` + // 创建时间 + CreatedTime string `gorm:"column:created_time" json:"createdTime"` + // 更新时间 + UpdatedTime string `gorm:"column:updated_time" json:"updatedTime"` +} +type UserList struct { + // user实体列表 + Users []*User `json:"users"` + // 页数 + PageNumber int64 `json:"pageNumber"` + // 页大小 + PageSize int64 `json:"pageSize"` + // 总条数 + TotalCount int64 `json:"totalCount"` +} +type UserInfo struct { + // 用户实体 + User *User `json:"user"` +} +type UserId struct { + // 用户uuid + UserId string `json:"userId"` +} diff --git a/bmp-openapi/types/response/command.go b/bmp-openapi/types/response/command.go new file mode 100644 index 0000000..bd34a80 --- /dev/null +++ b/bmp-openapi/types/response/command.go @@ -0,0 +1,42 @@ +package response + +import ( + "encoding/json" + "time" +) + +type Command struct { + Id int64 `json:"id"` + RequestId string `json:"request_id"` + Sn string `json:"sn"` + InstanceId string `json:"instance_id"` + Action string `json:"action"` + Type string `json:"type"` + Status string `json:"status"` + ParentCommandId int64 `json:"parent_command_id"` + ExecuteCount int `json:"execute_count"` + Result string `json:"result,omitempty"` + CreateTime time.Time `json:"create_time"` + UpdateTime time.Time `json:"update_time"` +} + +type QueryCommandsResult struct { + Commands []*Command `json:"commands"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} + +//解决time.Time类型序列化时默认格式为2018-12-25T19:43:35+08:00而不是2006-01-02 15:04:05的问题 +func (d Command) MarshalJSON() ([]byte, error) { + type Alias Command + return json.Marshal(struct { + Alias + CreateTime string `json:"create_time"` + UpdateTime string `json:"update_time"` + }{ + Alias: Alias(d), + CreateTime: d.CreateTime.Format("2006-01-02 15:04:05"), + UpdateTime: d.UpdateTime.Format("2006-01-02 15:04:05"), + }) +} diff --git a/bmp-openapi/util/array.go b/bmp-openapi/util/array.go new file mode 100644 index 0000000..db2ca59 --- /dev/null +++ b/bmp-openapi/util/array.go @@ -0,0 +1,119 @@ +package util + +import ( + "encoding/json" + "reflect" +) + +func GetValuesByField(objs []interface{}, field string) []string { + res := []string{} + for _, obj := range objs { + r := reflect.ValueOf(obj) + if reflect.TypeOf(obj).Kind() == reflect.Ptr { + r = reflect.Indirect(r) + } + f := r.FieldByName(field).String() + res = append(res, f) + } + return res +} + +func InArrayWithIndex(val interface{}, array interface{}) (exists bool, index int) { + exists = false + index = -1 + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + index = i + exists = true + return + } + } + } + return +} + +func InArray(val interface{}, array interface{}) (exists bool) { + exists = false + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + exists = true + return + } + } + } + return +} +func InArrayString(str string, arr []string) bool { + for _, v := range arr { + if v == str && str != "" { + return true + } + } + return false +} + +//求并集 +func UnionArray(slice1, slice2 []string) []string { + m := make(map[string]int) + for _, v := range slice1 { + m[v]++ + } + + for _, v := range slice2 { + times, _ := m[v] + if times == 0 { + slice1 = append(slice1, v) + } + } + return slice1 +} + +//求交集 +func IntersectArray(slice1, slice2 []string) []string { + m := make(map[string]int) + nn := make([]string, 0) + for _, v := range slice1 { + m[v]++ + } + + for _, v := range slice2 { + times, _ := m[v] + if times == 1 { + nn = append(nn, v) + } + } + return nn +} + +//求差集 slice1-并集 +func DifferenceArray(slice1, slice2 []string) []string { + m := make(map[string]int) + nn := make([]string, 0) + inter := IntersectArray(slice1, slice2) + for _, v := range inter { + m[v]++ + } + + for _, value := range slice1 { + times, _ := m[value] + if times == 0 { + nn = append(nn, value) + } + } + return nn +} + +func ObjToJson(obj interface{}) string { + dataType, err := json.Marshal(obj) + if err != nil { + return "" + } + dataString := string(dataType) + return dataString +} diff --git a/bmp-openapi/util/array_test.go b/bmp-openapi/util/array_test.go new file mode 100644 index 0000000..68dc442 --- /dev/null +++ b/bmp-openapi/util/array_test.go @@ -0,0 +1,14 @@ +package util + +import( + "testing" +) + +func TestInArray(t *testing.T){ + v := InArray("aaa", []string{"aaa", "bbb"}) + if !v{ + t.Fatal("not in array") + }else{ + t.Log("in array") + } +} diff --git a/bmp-openapi/util/bool.go b/bmp-openapi/util/bool.go new file mode 100644 index 0000000..39da658 --- /dev/null +++ b/bmp-openapi/util/bool.go @@ -0,0 +1,12 @@ +package util + +func Bool2Int8(b bool) int8 { + if b { + return 1 + } + return 0 +} + +func Int82Bool(i int8) bool { + return i > 0 +} diff --git a/bmp-openapi/util/common.go b/bmp-openapi/util/common.go new file mode 100644 index 0000000..3add6d4 --- /dev/null +++ b/bmp-openapi/util/common.go @@ -0,0 +1,196 @@ +package util + +import ( + "encoding/json" + "fmt" + "reflect" + "regexp" + "strconv" + "strings" + "time" + "unsafe" +) + +/** +map或者stuct转化为json字符串 +*/ +func ObjToJsonString(obj interface{}) string { + return MapToJson(InterfaceToMap(obj)) +} + +//任意类型转化成json,最常用 +func InterfaceToJson(obj interface{}) string { + dataType, err := json.Marshal(obj) + if err != nil { + return "" + } + dataString := string(dataType) + return dataString +} + +/** +Map对象转化为json string +*/ +func MapToJson(param map[string]interface{}) string { + dataType, _ := json.Marshal(param) + dataString := string(dataType) + return dataString +} +func InterfaceToMap(obj interface{}) map[string]interface{} { + + var data = make(map[string]interface{}) + if reflect.TypeOf(obj).Kind().String() == "map" { + d := obj.(map[string]interface{}) + for k, v := range d { + if vv := ReflectValue2string(reflect.ValueOf(v)); vv != "" { + data[k] = vv + } + } + } else if reflect.TypeOf(obj).Kind().String() == "struct" { + obj1 := reflect.TypeOf(obj) + obj2 := reflect.ValueOf(obj) + for i := 0; i < obj1.NumField(); i++ { + if vv := ReflectValue2string(obj2.Field(i)); vv != "" { + tagname := obj1.Field(i).Tag.Get("json") + if tagname != "" { + data[tagname] = vv + } else { + data[obj1.Field(i).Name] = vv + } + } + } + } else { + fmt.Printf("unknown obj, type is :%s, value is:%v\n", reflect.TypeOf(obj).String(), obj) + } + return data + +} + +//ReflectValue2string 默认值都设置为"",可能会误伤,后面改的方案:1,定义成wrapper类型,2,和上下游约定字段取值不要用默认值,比如int类型取值不要出现0,bool类型不要出现false +func ReflectValue2string(obj reflect.Value) string { + var v string + switch obj.Type().Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if vv := strconv.FormatInt(obj.Int(), 10); vv != "0" { //默认值问题 + v = vv + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + if vv := strconv.FormatUint(obj.Uint(), 10); vv != "0" { //默认值问题 + v = vv + } + case reflect.Float32, reflect.Float64: + if vv := fmt.Sprintf("%f", obj.Float()); vv != "0" { //默认值问题 + v = vv + } + case reflect.String: + v = obj.String() + case reflect.Bool: + if vv := strconv.FormatBool(obj.Bool()); vv != "false" { + v = vv + } + default: + v = "" + } + return v +} + +//将下划线转为驼峰 name_en => nameEn 一维,二维均可 +func DbToObj(obj map[string]interface{}) map[string]interface{} { + mapObj := make(map[string]interface{}) + for kk, vv := range obj { + if reflect.TypeOf(vv).Kind().String() == "slice" { + //fmt.Println(vv) + //sliceArr := []interface{} + for k1, v1 := range vv.([]interface{}) { + //fmt.Println(k1,v1) + mapObj1 := make(map[string]interface{}) + for k, v := range v1.(map[string]interface{}) { + sepStr := strings.Join(strings.Split(k, "_"), " ") + arr := strings.Split(strings.Title(sepStr), " ") + arr[0] = strings.ToLower(arr[0]) //hello World Haha + mapObj1[strings.Join(arr, "")] = v + } + vv.([]interface{})[k1] = mapObj1 + } + //fmt.Println(vv) + mapObj[kk] = vv + } else { + sepStr := strings.Join(strings.Split(kk, "_"), " ") + arr := strings.Split(strings.Title(sepStr), " ") + arr[0] = strings.ToLower(arr[0]) + mapObj[strings.Join(arr, "")] = vv + } + } + return mapObj +} + +//将一维map的驼峰 key转化为下划线 +func ObjToDb(param map[string]interface{}) map[string]interface{} { + //str := "userNameTom" //转为user_name_tom + //解析正则表达式,如果成功返回解释器 + reg := regexp.MustCompile(`[A-Z]`) + if reg == nil { //解释失败,返回nil + //fmt.Println("regexp err") + return nil + } + res := make(map[string]interface{}) + for key, value := range param { + //根据规则提取关键信息 + result := reg.FindAllStringSubmatch(key, -1) + for _, v := range result { + //fmt.Println(v) + key = strings.Replace(key, v[0], "_"+strings.ToLower(v[0]), 1) + } + res[key] = value + } + //fmt.Println("result1 = ", result,str) + return res +} + +func Int64ToInt(num int64) int { + int64_num := int64(num) + // 将 int64 转化为 int + int_num := *(*int)(unsafe.Pointer(&int64_num)) + return int_num +} +func StringToInt64(string string) int64 { + int64, err := strconv.ParseInt(string, 10, 64) + if err != nil { + fmt.Println("string to int64 error:", err.Error()) + return 0 + } + return int64 +} + +/** +时间戳根据timezone解析成时间字符串 +*/ +func TimestampToString(timestamp int64, timezone string) string { + if timestamp == 0 { + return "" + } + t := time.Unix(timestamp, 0) + local, err := time.LoadLocation(timezone) + if err != nil { + fmt.Println("timezone error:", timezone, err.Error()) + return "" + } + ts := t.In(local).String() + fmt.Println(timestamp, timezone, ts) + tsItems := strings.Split(ts, " ") + if len(tsItems) >= 2 { + ts = tsItems[0] + " " + tsItems[1] + } + return ts + //if timestamp == 0 { + // return "" + //} + //return time.Unix(timestamp, 0).UTC().Format(baseLogic.DATE_UTC_FORMAT) +} + +func Max(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/bmp-openapi/util/encrypt.go b/bmp-openapi/util/encrypt.go new file mode 100644 index 0000000..8f2e3bc --- /dev/null +++ b/bmp-openapi/util/encrypt.go @@ -0,0 +1,51 @@ +package util + +import ( + "crypto/md5" + "crypto/sha512" + "encoding/base64" + "encoding/hex" + "fmt" + + "golang.org/x/crypto/bcrypt" +) + +func BcryptEncode(pwd string) string { + // 第二个参数是进行哈希的次数,这里采用了默认值10,数字越大生成的密码速度越慢,成本越大。但是更安全 + // bcrypt每次生成的编码是不同的,较于md5更安全 + bytes, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost) + if err != nil { + fmt.Println("bcrypt error:", err.Error()) + return "" + } + return string(bytes) +} +func BcryptVerify(pwd, hash string) bool { + // CompareHashAndPassword 比较用户输入的明文和和数据库取出的的密码解析后是否匹配 + err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(pwd)) + return err == nil +} +func GetMd5(str string, salts ...string) string { + h := md5.New() + h.Write([]byte(str)) + if len(salts) == 0 { + return hex.EncodeToString(h.Sum(nil)) + } else { + for _, salt := range salts { + h.Write([]byte(salt)) + } + return hex.EncodeToString(h.Sum(nil)) + } +} + +func Base64Encrypt(str []byte) string { + return base64.StdEncoding.EncodeToString(str) +} + +func Base64Decrypt(data string) ([]byte, error) { + return base64.StdEncoding.DecodeString(data) +} + +func GetSha512(str string) string { + return fmt.Sprintf("%x", sha512.Sum512([]byte(str))) +} diff --git a/bmp-openapi/util/exec.go b/bmp-openapi/util/exec.go new file mode 100644 index 0000000..db6c262 --- /dev/null +++ b/bmp-openapi/util/exec.go @@ -0,0 +1,74 @@ +package util + +import ( + "errors" + "fmt" + "os/exec" + "regexp" + "strings" + "syscall" + + log "coding.jd.com/aidc-bmp/bmp_log" +) + +var ipmiToolPath = "/usr/sbin/ipmitool" + +// ExecCommand function to execute command +func ExecCommand(logger *log.Logger, cmdStr string, params ...string) (retStr string, ret int, err error) { + logger.Info("execCommand:", cmdStr+" "+strings.Join(params, " ")) + // check command injection + r := regexp.MustCompile(`[&\|;]+`) + if matched := r.MatchString(cmdStr); matched { + return "", -1, errors.New("command can not contain [&|;], ignore execute") + } + for _, param := range params { + if matched := r.MatchString(param); matched { + return "", -1, errors.New("params can not contain [&|;], ignore execute") + } + } + cmd := exec.Command(cmdStr, params...) + + // execute + //out, err := cmd.StdoutPipe() + //if err != nil { + // fmt.Println("StdoutPipe error: ", err.Error()) + // logger.Warn("StdoutPipe error: ", err.Error()) + // return "", 0, err + //} + //// fmt.Printf("stdout>%v\n", string(out)) + //defer out.Close() // 保证关闭输出流 + //for i := 1; i <= 4; i++ { + // if err := cmd.Start(); err != nil { // 运行命令 + // //log.Fatal(err) + // if i <= 3 { + // fmt.Println("exec Start error: ", err.Error(), i) + // logger.Warn("exec Start error: ", err.Error(), i) + // time.Sleep(time.Minute) + // continue + // } + // return "", 0, err + // } + //} + // + //bytes, _ := ioutil.ReadAll(out) + //for i := 1; i <= 4; i++ { + out, err := cmd.CombinedOutput() + if err != nil { + fmt.Println("CombinedOutput error, command:", cmdStr, params, "error:", err.Error(), "out:", string(out)) + logger.Warn("CombinedOutput error, command:", cmdStr, params, "error:", err.Error(), "out:", string(out)) + return string(out[:]), 0, err + } + //} + logger.Info("exec output: ", string(out[:])) + //return string(bytes) + // get exit code + ret = cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus() + if ret != 0 { + err = errors.New(strings.TrimSpace(string(out[:]))) + logger.Warn("exec WaitStatus error: ", err.Error()) + return "", 0, err + } + // fmt.Printf("cmd>%+v \n", cmd) + + return string(out[:]), ret, err +} diff --git a/bmp-openapi/util/http.go b/bmp-openapi/util/http.go new file mode 100644 index 0000000..d9e26eb --- /dev/null +++ b/bmp-openapi/util/http.go @@ -0,0 +1,61 @@ +package util + +import ( + "bytes" + "encoding/json" + "io/ioutil" + "net/http" + "reflect" + + "github.com/beego/beego/v2/server/web" + + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func DoHttpPost(logger *log.Logger, url string, header map[string]string, data interface{}) ([]byte, error) { + logPath, _ := web.AppConfig.String("log.path") + rpclogger := log.New(logPath + "/openapi-rpc.log") + + defer rpclogger.Flush() + defer rpclogger.TimeEnd("cost") + rpclogger.SetStableFields([]string{"url", "method", "cost", "header", "request", "response"}) + + rpclogger.Point("logid", logger.GetPoint("logid").(string)) + rpclogger.Point("url", url) + rpclogger.Point("method", "POST") + rpclogger.Point("header", header) + rpclogger.TimeStart("cost") + + var bytesData []byte + if reflect.TypeOf(data).Kind() == reflect.String { + bytesData = []byte(data.(string)) + } else { + var err error + bytesData, err = json.Marshal(data) + if err != nil { + return nil, err + } + } + rpclogger.Point("request", string(bytesData)) + reader := bytes.NewReader(bytesData) + request, err := http.NewRequest("POST", url, reader) + if err != nil { + return nil, err + } + defer request.Body.Close() + //务必带 X-Jdcloud-Request-Id + for k, v := range header { + request.Header.Set(k, v) + } + client := http.Client{} + resp, err := client.Do(request) + if err != nil { + return nil, err + } + respBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + rpclogger.Point("response", string(respBytes)) + return respBytes, nil +} diff --git a/bmp-openapi/util/ipv4.go b/bmp-openapi/util/ipv4.go new file mode 100644 index 0000000..f668a89 --- /dev/null +++ b/bmp-openapi/util/ipv4.go @@ -0,0 +1,200 @@ +package util + +import ( + "encoding/hex" + "fmt" + "net" + "strconv" + "strings" + + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +const ( + IP_NETWORK_SPLIT = "/" + IP_ADDRESS_REGEX = `^(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))$` + IP_WIDTH int32 = 32 + IP_MAX_VALUE int64 = 0xffffffff + IP_MIN_VALUE int64 = 0 +) + +func NetworkIp(cidr string) string { + _, ipNet, _ := net.ParseCIDR(cidr) + return ipNet.IP.String() +} + +// GetNetInfo 根据cidr获取网关和掩码信息 +func GetNetInfo(cidr string) (string, string) { + _, ipNet, _ := net.ParseCIDR(cidr) + mask := getIpMask(ipNet.Mask) + gateway := getDefaultGateway(ipNet.IP.String()) + return gateway, mask +} + +// getIpMask 获取ip掩码 +func getIpMask(mask net.IPMask) string { + val := make([]byte, len(mask)) + copy(val, mask) + s := make([]string, 0) + for _, value := range val { + s = append(s, strconv.Itoa(int(value))) + } + return strings.Join(s, ".") +} + +// getDefaultGateway 获取默认网关 +func getDefaultGateway(ip string) string { + ipArr := strings.Split(ip, ".") + if len(ipArr) > 3 { + lastNum, _ := strconv.Atoi(ipArr[3]) + return ipArr[0] + "." + ipArr[1] + "." + ipArr[2] + "." + strconv.Itoa(lastNum+1) + } else { + return "" + } +} +func Gateway(cidr string) string { + ip, _, err := net.ParseCIDR(cidr) + if err != nil { + panic(err.Error()) + } + IncrIP(ip) + return ip.String() +} + +func Mask(mask net.IPMask) string { + m, _ := hex.DecodeString(mask.String()) + return net.IP([]byte(m)).String() +} + +// IP地址自增 +func IncrIP(ip net.IP) { + for i := len(ip) - 1; i >= 0; i-- { + ip[i]++ + if ip[i] > 0 { + break + } + } +} + +// IP地址自减 +func DecrIP(ip net.IP) { + length := len(ip) + for i := length - 1; i >= 0; i-- { + ip[length-1]-- + if ip[length-1] < 0xFF { + break + } + for j := 1; j < length; j++ { + ip[length-j-1]-- + if ip[length-j-1] < 0xFF { + return + } + } + } +} + +// RandomMacAddress 生成随机mac地址 +func RandomMacAddress() string { + + uuid := commonUtil.GetRandString("", 12, false, false, true) + first_part := uuid[0:4] + first_part_num, _ := strconv.ParseInt("0x"+first_part, 16, 32) + first_hex_string := strconv.FormatInt(first_part_num&0xfeff, 16) + part := []string{fmt.Sprintf("%04x", first_hex_string), uuid[4:8], uuid[8:12]} + return strings.Join(part, "-") +} + +/* + * 列举一个CIDR段中的所有IP列表 + */ +func GetAllHostIPs(cidr string) []string { + //不过不包含掩码位,就当做32位IP对待 + if !strings.Contains(cidr, "/") { + return []string{cidr} + } + ip := strings.Split(cidr, "/")[0] + ipSegs := strings.Split(ip, ".") + maskLen, _ := strconv.Atoi(strings.Split(cidr, "/")[1]) + if maskLen <= 0 { + return []string{} + } + if maskLen == 32 { + return []string{ip} + } + seg1MinIp, seg1MaxIp := getIpSeg1Range(ipSegs[0], maskLen) + seg2MinIp, seg2MaxIp := getIpSeg2Range(ipSegs[1], maskLen) + seg3MinIp, seg3MaxIp := getIpSeg3Range(ipSegs[2], maskLen) + seg4MinIp, seg4MaxIp := getIpSeg4Range(ipSegs[3], maskLen) + + var ipList []string + for seg1Ip := seg1MinIp; seg1Ip <= seg1MaxIp; seg1Ip++ { + for seg2Ip := seg2MinIp; seg2Ip <= seg2MaxIp; seg2Ip++ { + for seg3Ip := seg3MinIp; seg3Ip <= seg3MaxIp; seg3Ip++ { + for seg4Ip := seg4MinIp; seg4Ip <= seg4MaxIp; seg4Ip++ { + oneIp := fmt.Sprintf("%d.%d.%d.%d", seg1Ip, seg2Ip, seg3Ip, seg4Ip) + ipList = append(ipList, oneIp) + } + } + } + } + return ipList +} + +/* + * 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)3部分的最小值和最大值 + */ +func getIpSeg1Range(ipSeg string, maskLen int) (int, int) { + //如果掩码位>16,此时说明掩码只会影响到seg2,seg3,seg4,seg1直接返回 + if maskLen > 8 { + segIp, _ := strconv.Atoi(ipSeg) + return segIp, segIp + } + ipSegNum, _ := strconv.Atoi(ipSeg) + return getIpSegRange(uint8(ipSegNum), uint8(8-maskLen)) +} + +/* +* 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)3部分的最小值和最大值 + */ +func getIpSeg2Range(ipSeg string, maskLen int) (int, int) { + //如果掩码位>16,此时说明掩码只会影响到seg3,seg4,seg2直接返回 + if maskLen > 16 { + segIp, _ := strconv.Atoi(ipSeg) + return segIp, segIp + } + ipSegNum, _ := strconv.Atoi(ipSeg) + return getIpSegRange(uint8(ipSegNum), uint8(16-maskLen)) +} + +/* +* 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)3部分的最小值和最大值 + */ +func getIpSeg3Range(ipSeg string, maskLen int) (int, int) { + //如果掩码位>24,此时说明掩码只会影响到seg4,seg3直接返回 + if maskLen > 24 { + segIp, _ := strconv.Atoi(ipSeg) + return segIp, segIp + } + ipSegNum, _ := strconv.Atoi(ipSeg) + return getIpSegRange(uint8(ipSegNum), uint8(24-maskLen)) +} + +/* + * 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)4部分的最小值和最大值 + */ +func getIpSeg4Range(ipSeg string, maskLen int) (int, int) { + ipSegNum, _ := strconv.Atoi(ipSeg) + segMinIp, segMaxIp := getIpSegRange(uint8(ipSegNum), uint8(32-maskLen)) + if segMinIp == 0 { + segMinIp = segMinIp + 1 //最后一段的IP不能是0,否则就会变为网段 + } + return segMinIp, segMaxIp +} + +func getIpSegRange(userSegIp, offset uint8) (int, int) { + var ipSegMax uint8 = 255 + netSegIp := ipSegMax << offset + segMinIp := netSegIp & userSegIp + segMaxIp := userSegIp&(255< target_len { //裁剪 + if ahead { //保留左边 + return string(r[:target_len]) + } else { //保留右边 + return string(r[len(r)-target_len:]) + } + + } else if len(r) < target_len { //填充 + pads := []rune{} + for i := 0; i < target_len-len(r); i++ { + pads = append(pads, padding_char) + } + if ahead { //左向填充 + return string(append(pads, r...)) + } else { //右向填充 + return string(append(r, pads...)) + } + } + return source + +} +func GetUuid(pre string) string { + rand.Seed(time.Now().UnixNano()) + str := "0123456789abcdefghijklmnopqrstuvwxyz" + bytes := []byte(str) + var result []byte + for i := 0; i < 28; i++ { + result = append(result, bytes[rand.Intn(len(bytes))]) + } + return pre + string(result) +} diff --git a/bmp-operation-api/.cmd b/bmp-operation-api/.cmd new file mode 100644 index 0000000..ced32d3 --- /dev/null +++ b/bmp-operation-api/.cmd @@ -0,0 +1 @@ +rm -rf vendor diff --git a/bmp-operation-api/.gitmodules b/bmp-operation-api/.gitmodules new file mode 100644 index 0000000..506f24c --- /dev/null +++ b/bmp-operation-api/.gitmodules @@ -0,0 +1,3 @@ +[submodule "bmp-deploy"] + path = bmp-deploy + url = git@coding.jd.com:aidc-bmp/bmp-deploy.git diff --git a/bmp-operation-api/Dockerfile b/bmp-operation-api/Dockerfile new file mode 100644 index 0000000..b22118a --- /dev/null +++ b/bmp-operation-api/Dockerfile @@ -0,0 +1,17 @@ +FROM centos:7.9.2009 + +MAINTAINER minping@jd.com +USER root +RUN groupadd -g 2001 ironic-console +RUN useradd -d /home/ironic-console -u 2001 -g 2001 ironic-console + +WORKDIR /home/ironic-console + +ADD ./ironic-console /home/ironic-console/ +RUN mkdir -p /home/ironic-console/conf +ADD ./conf/* /home/ironic-console/conf/ + +RUN chmod 755 /home/ironic-console/ironic-console +USER ironic-console +EXPOSE 9998 +CMD ./ironic-console \ No newline at end of file diff --git a/bmp-operation-api/Makefile b/bmp-operation-api/Makefile new file mode 100644 index 0000000..59677f8 --- /dev/null +++ b/bmp-operation-api/Makefile @@ -0,0 +1,10 @@ + +BUILD_TIME := $(shell date +%Y%m%d%H%M%S) +VERSION := $(shell git describe --tags --always) +COMMITID := $(shell git rev-parse ${VERSION} | cut -c 1-32) +APP_NAME := ironic-console-jdstack + +#GOARCH=amd64 GOOS=linux +ldflags ="-s -X main.VERSION=${COMMITID} -X main.BUILD_TIME=${BUILD_TIME}" +all: + GOARCH=amd64 GOOS=linux go build -ldflags ${ldflags} -o ${APP_NAME} main.go diff --git a/bmp-operation-api/README.md b/bmp-operation-api/README.md new file mode 100644 index 0000000..1103b48 --- /dev/null +++ b/bmp-operation-api/README.md @@ -0,0 +1,18 @@ +# bmp-operation-api + + +English | [简体中文](README.zh-CN.md) + +## Introduce + +The operation adaptation layer, Around the life cycle of an instance provides an interface for bmp-operation-web and requests bmp-openapi to obtain data. + +The location of bmp-operation-api in the entire bmp architecture is shown in:[bmp arch](../bmp-scheduler/README.md) + + + +## 2,Core Features + +- Serving the life cycle of devices. +- Provides an interface for bmp-operation-web. +- Request bmp-openapi to obtain data. \ No newline at end of file diff --git a/bmp-operation-api/README.zh-CN.md b/bmp-operation-api/README.zh-CN.md new file mode 100644 index 0000000..21d213b --- /dev/null +++ b/bmp-operation-api/README.zh-CN.md @@ -0,0 +1,19 @@ +# bmp-operation-api + +[English](README.md) | 简体中文 + + +## 介绍 + +运营平台适配层,围绕设备的生命周期,向上为bmp-operation-web提供接口,向下请求bmp-openapi获取数据。 + +bmp-operation-api在整个bmp架构中的位置见:[bmp架构图](../bmp-scheduler/README.zh-CN.md) + + + +## 2,核心功能 + +- 服务于设备的生命周期流转。 +- 向上为bmp-operation-web提供接口。 +- 向下请求bmp-openapi获取数据。 + diff --git a/bmp-operation-api/bmp-operation-api.Dockerfile b/bmp-operation-api/bmp-operation-api.Dockerfile new file mode 100644 index 0000000..ed3c101 --- /dev/null +++ b/bmp-operation-api/bmp-operation-api.Dockerfile @@ -0,0 +1,25 @@ +FROM quay.io/goswagger/swagger AS SDK +ENV GOPROXY https://goproxy.cn +WORKDIR /usr/src/bmp-openapi-tmp +COPY ./bmp-openapi . +RUN swagger generate spec -o ./swagger.yml +RUN swagger validate swagger.yml +RUN mkdir -p ../bmp-openapi-sdk +RUN cd ../bmp-openapi-sdk && go mod init coding.jd.com/aidc-bmp/bmp-openapi-sdk +RUN cd ../bmp-openapi-tmp +RUN swagger generate client -f swagger.yml --target=../bmp-openapi-sdk + +FROM golang:1.17-alpine AS builder +ENV GOPROXY https://goproxy.cn +WORKDIR /usr/src/bmp-operation-api +COPY ./bmp-operation-api . +COPY --from=SDK /usr/src/bmp-openapi-sdk ./bmp_vendor/bmp-openapi-sdk +RUN go mod tidy -compat=1.17 +RUN go mod vendor +RUN go build -o /tmp/bmp-operation-api . + +FROM alpine:3.16 +WORKDIR /home/bmp/bmp-operation-api +COPY --from=builder /tmp/bmp-operation-api . +COPY ./bmp-operation-api/conf ./conf +CMD ["./bmp-operation-api"] diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/api_key_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/api_key_client.go new file mode 100644 index 0000000..f786155 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/api_key_client.go @@ -0,0 +1,237 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new api key API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for api key API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateUserApikey(params *CreateUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserApikeyOK, error) + + DeleteUserApikey(params *DeleteUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserApikeyOK, error) + + DescribeUserAPIKey(params *DescribeUserAPIKeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserAPIKeyOK, error) + + DescribeUserAPIKeys(params *DescribeUserAPIKeysParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserAPIKeysOK, error) + + ModifyUserApikey(params *ModifyUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserApikeyOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateUserApikey CreateUserApikey 创建apikey +*/ +func (a *Client) CreateUserApikey(params *CreateUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserApikeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateUserApikeyParams() + } + op := &runtime.ClientOperation{ + ID: "createUserApikey", + Method: "POST", + PathPattern: "/user/apikeys", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateUserApikeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateUserApikeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateUserApikeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteUserApikey DeleteUserApikey 删除某个apikey +*/ +func (a *Client) DeleteUserApikey(params *DeleteUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserApikeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteUserApikeyParams() + } + op := &runtime.ClientOperation{ + ID: "deleteUserApikey", + Method: "DELETE", + PathPattern: "/user/apikeys/{apikey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteUserApikeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteUserApikeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteUserApikeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserAPIKey DescribeUserAPIKey 获取apikey详情 +*/ +func (a *Client) DescribeUserAPIKey(params *DescribeUserAPIKeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserAPIKeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserAPIKeyParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserAPIKey", + Method: "GET", + PathPattern: "/user/apikeys/{apikey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserAPIKeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserAPIKeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserAPIKeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserAPIKeys DescribeUserAPIKeys 获取APIKey列表 +*/ +func (a *Client) DescribeUserAPIKeys(params *DescribeUserAPIKeysParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserAPIKeysOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserAPIKeysParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserAPIKeys", + Method: "GET", + PathPattern: "/user/apikeys", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserAPIKeysReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserAPIKeysOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserAPIKeysDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyUserApikey ModifyUserApikey 修改apikey(暂不启用) +*/ +func (a *Client) ModifyUserApikey(params *ModifyUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserApikeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyUserApikeyParams() + } + op := &runtime.ClientOperation{ + ID: "modifyUserApikey", + Method: "PUT", + PathPattern: "/user/apikeys/{apikey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyUserApikeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyUserApikeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyUserApikeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/create_user_apikey_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/create_user_apikey_parameters.go new file mode 100644 index 0000000..0766e20 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/create_user_apikey_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateUserApikeyParams creates a new CreateUserApikeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateUserApikeyParams() *CreateUserApikeyParams { + return &CreateUserApikeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateUserApikeyParamsWithTimeout creates a new CreateUserApikeyParams object +// with the ability to set a timeout on a request. +func NewCreateUserApikeyParamsWithTimeout(timeout time.Duration) *CreateUserApikeyParams { + return &CreateUserApikeyParams{ + timeout: timeout, + } +} + +// NewCreateUserApikeyParamsWithContext creates a new CreateUserApikeyParams object +// with the ability to set a context for a request. +func NewCreateUserApikeyParamsWithContext(ctx context.Context) *CreateUserApikeyParams { + return &CreateUserApikeyParams{ + Context: ctx, + } +} + +// NewCreateUserApikeyParamsWithHTTPClient creates a new CreateUserApikeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateUserApikeyParamsWithHTTPClient(client *http.Client) *CreateUserApikeyParams { + return &CreateUserApikeyParams{ + HTTPClient: client, + } +} + +/* CreateUserApikeyParams contains all the parameters to send to the API endpoint + for the create user apikey operation. + + Typically these are written to a http.Request. +*/ +type CreateUserApikeyParams struct { + + // Body. + Body *models.CreateApikeyRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserApikeyParams) WithDefaults() *CreateUserApikeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserApikeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create user apikey params +func (o *CreateUserApikeyParams) WithTimeout(timeout time.Duration) *CreateUserApikeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create user apikey params +func (o *CreateUserApikeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create user apikey params +func (o *CreateUserApikeyParams) WithContext(ctx context.Context) *CreateUserApikeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create user apikey params +func (o *CreateUserApikeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create user apikey params +func (o *CreateUserApikeyParams) WithHTTPClient(client *http.Client) *CreateUserApikeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create user apikey params +func (o *CreateUserApikeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create user apikey params +func (o *CreateUserApikeyParams) WithBody(body *models.CreateApikeyRequest) *CreateUserApikeyParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create user apikey params +func (o *CreateUserApikeyParams) SetBody(body *models.CreateApikeyRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create user apikey params +func (o *CreateUserApikeyParams) WithAuthorization(authorization string) *CreateUserApikeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create user apikey params +func (o *CreateUserApikeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create user apikey params +func (o *CreateUserApikeyParams) WithBmpLanguage(bmpLanguage *string) *CreateUserApikeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create user apikey params +func (o *CreateUserApikeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create user apikey params +func (o *CreateUserApikeyParams) WithBmpUserID(bmpUserID *string) *CreateUserApikeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create user apikey params +func (o *CreateUserApikeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create user apikey params +func (o *CreateUserApikeyParams) WithTraceID(traceID string) *CreateUserApikeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create user apikey params +func (o *CreateUserApikeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateUserApikeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/create_user_apikey_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/create_user_apikey_responses.go new file mode 100644 index 0000000..1f90a8e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/create_user_apikey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateUserApikeyReader is a Reader for the CreateUserApikey structure. +type CreateUserApikeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateUserApikeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateUserApikeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateUserApikeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateUserApikeyOK creates a CreateUserApikeyOK with default headers values +func NewCreateUserApikeyOK() *CreateUserApikeyOK { + return &CreateUserApikeyOK{} +} + +/* CreateUserApikeyOK describes a response with status code 200, with default header values. + +A CreateUserApikeyResult is an response struct that is used to describe create apikey result. +*/ +type CreateUserApikeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserApikeyOKBody +} + +// IsSuccess returns true when this create user apikey o k response has a 2xx status code +func (o *CreateUserApikeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create user apikey o k response has a 3xx status code +func (o *CreateUserApikeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create user apikey o k response has a 4xx status code +func (o *CreateUserApikeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create user apikey o k response has a 5xx status code +func (o *CreateUserApikeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create user apikey o k response a status code equal to that given +func (o *CreateUserApikeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateUserApikeyOK) Error() string { + return fmt.Sprintf("[POST /user/apikeys][%d] createUserApikeyOK %+v", 200, o.Payload) +} + +func (o *CreateUserApikeyOK) String() string { + return fmt.Sprintf("[POST /user/apikeys][%d] createUserApikeyOK %+v", 200, o.Payload) +} + +func (o *CreateUserApikeyOK) GetPayload() *CreateUserApikeyOKBody { + return o.Payload +} + +func (o *CreateUserApikeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserApikeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateUserApikeyDefault creates a CreateUserApikeyDefault with default headers values +func NewCreateUserApikeyDefault(code int) *CreateUserApikeyDefault { + return &CreateUserApikeyDefault{ + _statusCode: code, + } +} + +/* CreateUserApikeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateUserApikeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserApikeyDefaultBody +} + +// Code gets the status code for the create user apikey default response +func (o *CreateUserApikeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create user apikey default response has a 2xx status code +func (o *CreateUserApikeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create user apikey default response has a 3xx status code +func (o *CreateUserApikeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create user apikey default response has a 4xx status code +func (o *CreateUserApikeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create user apikey default response has a 5xx status code +func (o *CreateUserApikeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create user apikey default response a status code equal to that given +func (o *CreateUserApikeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateUserApikeyDefault) Error() string { + return fmt.Sprintf("[POST /user/apikeys][%d] createUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserApikeyDefault) String() string { + return fmt.Sprintf("[POST /user/apikeys][%d] createUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserApikeyDefault) GetPayload() *CreateUserApikeyDefaultBody { + return o.Payload +} + +func (o *CreateUserApikeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserApikeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateUserApikeyDefaultBody create user apikey default body +swagger:model CreateUserApikeyDefaultBody +*/ +type CreateUserApikeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create user apikey default body +func (o *CreateUserApikeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserApikeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createUserApikey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateUserApikeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createUserApikey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user apikey default body based on the context it is used +func (o *CreateUserApikeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserApikeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserApikeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserApikeyDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateUserApikeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateUserApikeyOKBody create user apikey o k body +swagger:model CreateUserApikeyOKBody +*/ +type CreateUserApikeyOKBody struct { + + // result + Result *models.ApikeyID `json:"result,omitempty"` +} + +// Validate validates this create user apikey o k body +func (o *CreateUserApikeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserApikeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user apikey o k body based on the context it is used +func (o *CreateUserApikeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserApikeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserApikeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserApikeyOKBody) UnmarshalBinary(b []byte) error { + var res CreateUserApikeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/delete_user_apikey_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/delete_user_apikey_parameters.go new file mode 100644 index 0000000..3dd7d9b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/delete_user_apikey_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteUserApikeyParams creates a new DeleteUserApikeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteUserApikeyParams() *DeleteUserApikeyParams { + return &DeleteUserApikeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteUserApikeyParamsWithTimeout creates a new DeleteUserApikeyParams object +// with the ability to set a timeout on a request. +func NewDeleteUserApikeyParamsWithTimeout(timeout time.Duration) *DeleteUserApikeyParams { + return &DeleteUserApikeyParams{ + timeout: timeout, + } +} + +// NewDeleteUserApikeyParamsWithContext creates a new DeleteUserApikeyParams object +// with the ability to set a context for a request. +func NewDeleteUserApikeyParamsWithContext(ctx context.Context) *DeleteUserApikeyParams { + return &DeleteUserApikeyParams{ + Context: ctx, + } +} + +// NewDeleteUserApikeyParamsWithHTTPClient creates a new DeleteUserApikeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteUserApikeyParamsWithHTTPClient(client *http.Client) *DeleteUserApikeyParams { + return &DeleteUserApikeyParams{ + HTTPClient: client, + } +} + +/* DeleteUserApikeyParams contains all the parameters to send to the API endpoint + for the delete user apikey operation. + + Typically these are written to a http.Request. +*/ +type DeleteUserApikeyParams struct { + + // ApikeyID. + ApikeyID string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserApikeyParams) WithDefaults() *DeleteUserApikeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserApikeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete user apikey params +func (o *DeleteUserApikeyParams) WithTimeout(timeout time.Duration) *DeleteUserApikeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete user apikey params +func (o *DeleteUserApikeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete user apikey params +func (o *DeleteUserApikeyParams) WithContext(ctx context.Context) *DeleteUserApikeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete user apikey params +func (o *DeleteUserApikeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete user apikey params +func (o *DeleteUserApikeyParams) WithHTTPClient(client *http.Client) *DeleteUserApikeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete user apikey params +func (o *DeleteUserApikeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithApikeyID adds the apikeyID to the delete user apikey params +func (o *DeleteUserApikeyParams) WithApikeyID(apikeyID string) *DeleteUserApikeyParams { + o.SetApikeyID(apikeyID) + return o +} + +// SetApikeyID adds the apikeyId to the delete user apikey params +func (o *DeleteUserApikeyParams) SetApikeyID(apikeyID string) { + o.ApikeyID = apikeyID +} + +// WithAuthorization adds the authorization to the delete user apikey params +func (o *DeleteUserApikeyParams) WithAuthorization(authorization string) *DeleteUserApikeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete user apikey params +func (o *DeleteUserApikeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete user apikey params +func (o *DeleteUserApikeyParams) WithBmpLanguage(bmpLanguage *string) *DeleteUserApikeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete user apikey params +func (o *DeleteUserApikeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete user apikey params +func (o *DeleteUserApikeyParams) WithBmpUserID(bmpUserID *string) *DeleteUserApikeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete user apikey params +func (o *DeleteUserApikeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete user apikey params +func (o *DeleteUserApikeyParams) WithTraceID(traceID string) *DeleteUserApikeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete user apikey params +func (o *DeleteUserApikeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteUserApikeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param apikey_id + if err := r.SetPathParam("apikey_id", o.ApikeyID); err != nil { + return err + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/delete_user_apikey_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/delete_user_apikey_responses.go new file mode 100644 index 0000000..cd366f1 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/delete_user_apikey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteUserApikeyReader is a Reader for the DeleteUserApikey structure. +type DeleteUserApikeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteUserApikeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteUserApikeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteUserApikeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteUserApikeyOK creates a DeleteUserApikeyOK with default headers values +func NewDeleteUserApikeyOK() *DeleteUserApikeyOK { + return &DeleteUserApikeyOK{} +} + +/* DeleteUserApikeyOK describes a response with status code 200, with default header values. + +A DeleteUserApikeyResult is an response struct that is used to describe delete Apikey result. +*/ +type DeleteUserApikeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserApikeyOKBody +} + +// IsSuccess returns true when this delete user apikey o k response has a 2xx status code +func (o *DeleteUserApikeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete user apikey o k response has a 3xx status code +func (o *DeleteUserApikeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete user apikey o k response has a 4xx status code +func (o *DeleteUserApikeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete user apikey o k response has a 5xx status code +func (o *DeleteUserApikeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete user apikey o k response a status code equal to that given +func (o *DeleteUserApikeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteUserApikeyOK) Error() string { + return fmt.Sprintf("[DELETE /user/apikeys/{apikey_id}][%d] deleteUserApikeyOK %+v", 200, o.Payload) +} + +func (o *DeleteUserApikeyOK) String() string { + return fmt.Sprintf("[DELETE /user/apikeys/{apikey_id}][%d] deleteUserApikeyOK %+v", 200, o.Payload) +} + +func (o *DeleteUserApikeyOK) GetPayload() *DeleteUserApikeyOKBody { + return o.Payload +} + +func (o *DeleteUserApikeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserApikeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteUserApikeyDefault creates a DeleteUserApikeyDefault with default headers values +func NewDeleteUserApikeyDefault(code int) *DeleteUserApikeyDefault { + return &DeleteUserApikeyDefault{ + _statusCode: code, + } +} + +/* DeleteUserApikeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteUserApikeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserApikeyDefaultBody +} + +// Code gets the status code for the delete user apikey default response +func (o *DeleteUserApikeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete user apikey default response has a 2xx status code +func (o *DeleteUserApikeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete user apikey default response has a 3xx status code +func (o *DeleteUserApikeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete user apikey default response has a 4xx status code +func (o *DeleteUserApikeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete user apikey default response has a 5xx status code +func (o *DeleteUserApikeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete user apikey default response a status code equal to that given +func (o *DeleteUserApikeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteUserApikeyDefault) Error() string { + return fmt.Sprintf("[DELETE /user/apikeys/{apikey_id}][%d] deleteUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserApikeyDefault) String() string { + return fmt.Sprintf("[DELETE /user/apikeys/{apikey_id}][%d] deleteUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserApikeyDefault) GetPayload() *DeleteUserApikeyDefaultBody { + return o.Payload +} + +func (o *DeleteUserApikeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserApikeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteUserApikeyDefaultBody delete user apikey default body +swagger:model DeleteUserApikeyDefaultBody +*/ +type DeleteUserApikeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete user apikey default body +func (o *DeleteUserApikeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserApikeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserApikey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteUserApikeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserApikey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user apikey default body based on the context it is used +func (o *DeleteUserApikeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserApikeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserApikeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserApikeyDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteUserApikeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteUserApikeyOKBody delete user apikey o k body +swagger:model DeleteUserApikeyOKBody +*/ +type DeleteUserApikeyOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete user apikey o k body +func (o *DeleteUserApikeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserApikeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user apikey o k body based on the context it is used +func (o *DeleteUserApikeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserApikeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserApikeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserApikeyOKBody) UnmarshalBinary(b []byte) error { + var res DeleteUserApikeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_key_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_key_parameters.go new file mode 100644 index 0000000..0d39690 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_key_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeUserAPIKeyParams creates a new DescribeUserAPIKeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserAPIKeyParams() *DescribeUserAPIKeyParams { + return &DescribeUserAPIKeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserAPIKeyParamsWithTimeout creates a new DescribeUserAPIKeyParams object +// with the ability to set a timeout on a request. +func NewDescribeUserAPIKeyParamsWithTimeout(timeout time.Duration) *DescribeUserAPIKeyParams { + return &DescribeUserAPIKeyParams{ + timeout: timeout, + } +} + +// NewDescribeUserAPIKeyParamsWithContext creates a new DescribeUserAPIKeyParams object +// with the ability to set a context for a request. +func NewDescribeUserAPIKeyParamsWithContext(ctx context.Context) *DescribeUserAPIKeyParams { + return &DescribeUserAPIKeyParams{ + Context: ctx, + } +} + +// NewDescribeUserAPIKeyParamsWithHTTPClient creates a new DescribeUserAPIKeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserAPIKeyParamsWithHTTPClient(client *http.Client) *DescribeUserAPIKeyParams { + return &DescribeUserAPIKeyParams{ + HTTPClient: client, + } +} + +/* DescribeUserAPIKeyParams contains all the parameters to send to the API endpoint + for the describe user API key operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserAPIKeyParams struct { + + // ApikeyID. + ApikeyID string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user API key params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserAPIKeyParams) WithDefaults() *DescribeUserAPIKeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user API key params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserAPIKeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithTimeout(timeout time.Duration) *DescribeUserAPIKeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithContext(ctx context.Context) *DescribeUserAPIKeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithHTTPClient(client *http.Client) *DescribeUserAPIKeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithApikeyID adds the apikeyID to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithApikeyID(apikeyID string) *DescribeUserAPIKeyParams { + o.SetApikeyID(apikeyID) + return o +} + +// SetApikeyID adds the apikeyId to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetApikeyID(apikeyID string) { + o.ApikeyID = apikeyID +} + +// WithAuthorization adds the authorization to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithAuthorization(authorization string) *DescribeUserAPIKeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserAPIKeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithBmpUserID(bmpUserID *string) *DescribeUserAPIKeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithTraceID(traceID string) *DescribeUserAPIKeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserAPIKeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param apikey_id + if err := r.SetPathParam("apikey_id", o.ApikeyID); err != nil { + return err + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_key_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_key_responses.go new file mode 100644 index 0000000..57577a7 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_key_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserAPIKeyReader is a Reader for the DescribeUserAPIKey structure. +type DescribeUserAPIKeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserAPIKeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserAPIKeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserAPIKeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserAPIKeyOK creates a DescribeUserAPIKeyOK with default headers values +func NewDescribeUserAPIKeyOK() *DescribeUserAPIKeyOK { + return &DescribeUserAPIKeyOK{} +} + +/* DescribeUserAPIKeyOK describes a response with status code 200, with default header values. + +A DescribeUserAPIKeyResult is an response struct that is used to describe getapikey. +*/ +type DescribeUserAPIKeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserAPIKeyOKBody +} + +// IsSuccess returns true when this describe user Api key o k response has a 2xx status code +func (o *DescribeUserAPIKeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user Api key o k response has a 3xx status code +func (o *DescribeUserAPIKeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user Api key o k response has a 4xx status code +func (o *DescribeUserAPIKeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user Api key o k response has a 5xx status code +func (o *DescribeUserAPIKeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user Api key o k response a status code equal to that given +func (o *DescribeUserAPIKeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserAPIKeyOK) Error() string { + return fmt.Sprintf("[GET /user/apikeys/{apikey_id}][%d] describeUserApiKeyOK %+v", 200, o.Payload) +} + +func (o *DescribeUserAPIKeyOK) String() string { + return fmt.Sprintf("[GET /user/apikeys/{apikey_id}][%d] describeUserApiKeyOK %+v", 200, o.Payload) +} + +func (o *DescribeUserAPIKeyOK) GetPayload() *DescribeUserAPIKeyOKBody { + return o.Payload +} + +func (o *DescribeUserAPIKeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserAPIKeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserAPIKeyDefault creates a DescribeUserAPIKeyDefault with default headers values +func NewDescribeUserAPIKeyDefault(code int) *DescribeUserAPIKeyDefault { + return &DescribeUserAPIKeyDefault{ + _statusCode: code, + } +} + +/* DescribeUserAPIKeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserAPIKeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserAPIKeyDefaultBody +} + +// Code gets the status code for the describe user API key default response +func (o *DescribeUserAPIKeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user API key default response has a 2xx status code +func (o *DescribeUserAPIKeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user API key default response has a 3xx status code +func (o *DescribeUserAPIKeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user API key default response has a 4xx status code +func (o *DescribeUserAPIKeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user API key default response has a 5xx status code +func (o *DescribeUserAPIKeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user API key default response a status code equal to that given +func (o *DescribeUserAPIKeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserAPIKeyDefault) Error() string { + return fmt.Sprintf("[GET /user/apikeys/{apikey_id}][%d] describeUserAPIKey default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserAPIKeyDefault) String() string { + return fmt.Sprintf("[GET /user/apikeys/{apikey_id}][%d] describeUserAPIKey default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserAPIKeyDefault) GetPayload() *DescribeUserAPIKeyDefaultBody { + return o.Payload +} + +func (o *DescribeUserAPIKeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserAPIKeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserAPIKeyDefaultBody describe user API key default body +swagger:model DescribeUserAPIKeyDefaultBody +*/ +type DescribeUserAPIKeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user API key default body +func (o *DescribeUserAPIKeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserAPIKey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserAPIKeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserAPIKey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserAPIKey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserAPIKey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user API key default body based on the context it is used +func (o *DescribeUserAPIKeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserAPIKey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserAPIKey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserAPIKeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserAPIKeyDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserAPIKeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserAPIKeyOKBody describe user API key o k body +swagger:model DescribeUserAPIKeyOKBody +*/ +type DescribeUserAPIKeyOKBody struct { + + // result + Result *models.ApikeyInfo `json:"result,omitempty"` +} + +// Validate validates this describe user API key o k body +func (o *DescribeUserAPIKeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserApiKeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserApiKeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user API key o k body based on the context it is used +func (o *DescribeUserAPIKeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserApiKeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserApiKeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserAPIKeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserAPIKeyOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserAPIKeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_keys_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_keys_parameters.go new file mode 100644 index 0000000..4fecbc7 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_keys_parameters.go @@ -0,0 +1,396 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeUserAPIKeysParams creates a new DescribeUserAPIKeysParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserAPIKeysParams() *DescribeUserAPIKeysParams { + return &DescribeUserAPIKeysParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserAPIKeysParamsWithTimeout creates a new DescribeUserAPIKeysParams object +// with the ability to set a timeout on a request. +func NewDescribeUserAPIKeysParamsWithTimeout(timeout time.Duration) *DescribeUserAPIKeysParams { + return &DescribeUserAPIKeysParams{ + timeout: timeout, + } +} + +// NewDescribeUserAPIKeysParamsWithContext creates a new DescribeUserAPIKeysParams object +// with the ability to set a context for a request. +func NewDescribeUserAPIKeysParamsWithContext(ctx context.Context) *DescribeUserAPIKeysParams { + return &DescribeUserAPIKeysParams{ + Context: ctx, + } +} + +// NewDescribeUserAPIKeysParamsWithHTTPClient creates a new DescribeUserAPIKeysParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserAPIKeysParamsWithHTTPClient(client *http.Client) *DescribeUserAPIKeysParams { + return &DescribeUserAPIKeysParams{ + HTTPClient: client, + } +} + +/* DescribeUserAPIKeysParams contains all the parameters to send to the API endpoint + for the describe user API keys operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserAPIKeysParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否查询全部/导出 + */ + IsAll *string + + /* Name. + + 秘钥对名称 + */ + Name *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* Type. + + Token类型, [system/user] + */ + Type *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user API keys params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserAPIKeysParams) WithDefaults() *DescribeUserAPIKeysParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user API keys params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserAPIKeysParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithTimeout(timeout time.Duration) *DescribeUserAPIKeysParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithContext(ctx context.Context) *DescribeUserAPIKeysParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithHTTPClient(client *http.Client) *DescribeUserAPIKeysParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithAuthorization(authorization string) *DescribeUserAPIKeysParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserAPIKeysParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithBmpUserID(bmpUserID *string) *DescribeUserAPIKeysParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithIsAll(isAll *string) *DescribeUserAPIKeysParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithName adds the name to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithName(name *string) *DescribeUserAPIKeysParams { + o.SetName(name) + return o +} + +// SetName adds the name to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetName(name *string) { + o.Name = name +} + +// WithPageNumber adds the pageNumber to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithPageNumber(pageNumber *int64) *DescribeUserAPIKeysParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithPageSize(pageSize *int64) *DescribeUserAPIKeysParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithTraceID(traceID string) *DescribeUserAPIKeysParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithType adds the typeVar to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithType(typeVar *string) *DescribeUserAPIKeysParams { + o.SetType(typeVar) + return o +} + +// SetType adds the type to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetType(typeVar *string) { + o.Type = typeVar +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserAPIKeysParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.Type != nil { + + // query param type + var qrType string + + if o.Type != nil { + qrType = *o.Type + } + qType := qrType + if qType != "" { + + if err := r.SetQueryParam("type", qType); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_keys_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_keys_responses.go new file mode 100644 index 0000000..3f39901 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_keys_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserAPIKeysReader is a Reader for the DescribeUserAPIKeys structure. +type DescribeUserAPIKeysReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserAPIKeysReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserAPIKeysOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserAPIKeysDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserAPIKeysOK creates a DescribeUserAPIKeysOK with default headers values +func NewDescribeUserAPIKeysOK() *DescribeUserAPIKeysOK { + return &DescribeUserAPIKeysOK{} +} + +/* DescribeUserAPIKeysOK describes a response with status code 200, with default header values. + +A DescribeUserAPIKeysResult is an response struct that is used to describe getapikeylist. +*/ +type DescribeUserAPIKeysOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserAPIKeysOKBody +} + +// IsSuccess returns true when this describe user Api keys o k response has a 2xx status code +func (o *DescribeUserAPIKeysOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user Api keys o k response has a 3xx status code +func (o *DescribeUserAPIKeysOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user Api keys o k response has a 4xx status code +func (o *DescribeUserAPIKeysOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user Api keys o k response has a 5xx status code +func (o *DescribeUserAPIKeysOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user Api keys o k response a status code equal to that given +func (o *DescribeUserAPIKeysOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserAPIKeysOK) Error() string { + return fmt.Sprintf("[GET /user/apikeys][%d] describeUserApiKeysOK %+v", 200, o.Payload) +} + +func (o *DescribeUserAPIKeysOK) String() string { + return fmt.Sprintf("[GET /user/apikeys][%d] describeUserApiKeysOK %+v", 200, o.Payload) +} + +func (o *DescribeUserAPIKeysOK) GetPayload() *DescribeUserAPIKeysOKBody { + return o.Payload +} + +func (o *DescribeUserAPIKeysOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserAPIKeysOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserAPIKeysDefault creates a DescribeUserAPIKeysDefault with default headers values +func NewDescribeUserAPIKeysDefault(code int) *DescribeUserAPIKeysDefault { + return &DescribeUserAPIKeysDefault{ + _statusCode: code, + } +} + +/* DescribeUserAPIKeysDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserAPIKeysDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserAPIKeysDefaultBody +} + +// Code gets the status code for the describe user API keys default response +func (o *DescribeUserAPIKeysDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user API keys default response has a 2xx status code +func (o *DescribeUserAPIKeysDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user API keys default response has a 3xx status code +func (o *DescribeUserAPIKeysDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user API keys default response has a 4xx status code +func (o *DescribeUserAPIKeysDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user API keys default response has a 5xx status code +func (o *DescribeUserAPIKeysDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user API keys default response a status code equal to that given +func (o *DescribeUserAPIKeysDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserAPIKeysDefault) Error() string { + return fmt.Sprintf("[GET /user/apikeys][%d] describeUserAPIKeys default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserAPIKeysDefault) String() string { + return fmt.Sprintf("[GET /user/apikeys][%d] describeUserAPIKeys default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserAPIKeysDefault) GetPayload() *DescribeUserAPIKeysDefaultBody { + return o.Payload +} + +func (o *DescribeUserAPIKeysDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserAPIKeysDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserAPIKeysDefaultBody describe user API keys default body +swagger:model DescribeUserAPIKeysDefaultBody +*/ +type DescribeUserAPIKeysDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user API keys default body +func (o *DescribeUserAPIKeysDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeysDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserAPIKeys default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserAPIKeysDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserAPIKeys default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserAPIKeys default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserAPIKeys default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user API keys default body based on the context it is used +func (o *DescribeUserAPIKeysDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeysDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserAPIKeys default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserAPIKeys default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserAPIKeysDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserAPIKeysDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserAPIKeysDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserAPIKeysOKBody describe user API keys o k body +swagger:model DescribeUserAPIKeysOKBody +*/ +type DescribeUserAPIKeysOKBody struct { + + // result + Result *models.ApikeyList `json:"result,omitempty"` +} + +// Validate validates this describe user API keys o k body +func (o *DescribeUserAPIKeysOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeysOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserApiKeysOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserApiKeysOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user API keys o k body based on the context it is used +func (o *DescribeUserAPIKeysOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeysOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserApiKeysOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserApiKeysOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserAPIKeysOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserAPIKeysOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserAPIKeysOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/modify_user_apikey_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/modify_user_apikey_parameters.go new file mode 100644 index 0000000..b495f85 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/modify_user_apikey_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyUserApikeyParams creates a new ModifyUserApikeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyUserApikeyParams() *ModifyUserApikeyParams { + return &ModifyUserApikeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyUserApikeyParamsWithTimeout creates a new ModifyUserApikeyParams object +// with the ability to set a timeout on a request. +func NewModifyUserApikeyParamsWithTimeout(timeout time.Duration) *ModifyUserApikeyParams { + return &ModifyUserApikeyParams{ + timeout: timeout, + } +} + +// NewModifyUserApikeyParamsWithContext creates a new ModifyUserApikeyParams object +// with the ability to set a context for a request. +func NewModifyUserApikeyParamsWithContext(ctx context.Context) *ModifyUserApikeyParams { + return &ModifyUserApikeyParams{ + Context: ctx, + } +} + +// NewModifyUserApikeyParamsWithHTTPClient creates a new ModifyUserApikeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyUserApikeyParamsWithHTTPClient(client *http.Client) *ModifyUserApikeyParams { + return &ModifyUserApikeyParams{ + HTTPClient: client, + } +} + +/* ModifyUserApikeyParams contains all the parameters to send to the API endpoint + for the modify user apikey operation. + + Typically these are written to a http.Request. +*/ +type ModifyUserApikeyParams struct { + + // Body. + Body *models.ModifyApikeyRequest + + // ApikeyID. + ApikeyID string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserApikeyParams) WithDefaults() *ModifyUserApikeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserApikeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify user apikey params +func (o *ModifyUserApikeyParams) WithTimeout(timeout time.Duration) *ModifyUserApikeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify user apikey params +func (o *ModifyUserApikeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify user apikey params +func (o *ModifyUserApikeyParams) WithContext(ctx context.Context) *ModifyUserApikeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify user apikey params +func (o *ModifyUserApikeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify user apikey params +func (o *ModifyUserApikeyParams) WithHTTPClient(client *http.Client) *ModifyUserApikeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify user apikey params +func (o *ModifyUserApikeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify user apikey params +func (o *ModifyUserApikeyParams) WithBody(body *models.ModifyApikeyRequest) *ModifyUserApikeyParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify user apikey params +func (o *ModifyUserApikeyParams) SetBody(body *models.ModifyApikeyRequest) { + o.Body = body +} + +// WithApikeyID adds the apikeyID to the modify user apikey params +func (o *ModifyUserApikeyParams) WithApikeyID(apikeyID string) *ModifyUserApikeyParams { + o.SetApikeyID(apikeyID) + return o +} + +// SetApikeyID adds the apikeyId to the modify user apikey params +func (o *ModifyUserApikeyParams) SetApikeyID(apikeyID string) { + o.ApikeyID = apikeyID +} + +// WithAuthorization adds the authorization to the modify user apikey params +func (o *ModifyUserApikeyParams) WithAuthorization(authorization string) *ModifyUserApikeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify user apikey params +func (o *ModifyUserApikeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify user apikey params +func (o *ModifyUserApikeyParams) WithBmpLanguage(bmpLanguage *string) *ModifyUserApikeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify user apikey params +func (o *ModifyUserApikeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify user apikey params +func (o *ModifyUserApikeyParams) WithBmpUserID(bmpUserID *string) *ModifyUserApikeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify user apikey params +func (o *ModifyUserApikeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the modify user apikey params +func (o *ModifyUserApikeyParams) WithTraceID(traceID string) *ModifyUserApikeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify user apikey params +func (o *ModifyUserApikeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyUserApikeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // path param apikey_id + if err := r.SetPathParam("apikey_id", o.ApikeyID); err != nil { + return err + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/modify_user_apikey_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/modify_user_apikey_responses.go new file mode 100644 index 0000000..cbdadcb --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/api_key/modify_user_apikey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyUserApikeyReader is a Reader for the ModifyUserApikey structure. +type ModifyUserApikeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyUserApikeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyUserApikeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyUserApikeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyUserApikeyOK creates a ModifyUserApikeyOK with default headers values +func NewModifyUserApikeyOK() *ModifyUserApikeyOK { + return &ModifyUserApikeyOK{} +} + +/* ModifyUserApikeyOK describes a response with status code 200, with default header values. + +A ModifyUserApikeyResult is an response struct that is used to describe modifyApikey result. +*/ +type ModifyUserApikeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserApikeyOKBody +} + +// IsSuccess returns true when this modify user apikey o k response has a 2xx status code +func (o *ModifyUserApikeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify user apikey o k response has a 3xx status code +func (o *ModifyUserApikeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify user apikey o k response has a 4xx status code +func (o *ModifyUserApikeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify user apikey o k response has a 5xx status code +func (o *ModifyUserApikeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify user apikey o k response a status code equal to that given +func (o *ModifyUserApikeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyUserApikeyOK) Error() string { + return fmt.Sprintf("[PUT /user/apikeys/{apikey_id}][%d] modifyUserApikeyOK %+v", 200, o.Payload) +} + +func (o *ModifyUserApikeyOK) String() string { + return fmt.Sprintf("[PUT /user/apikeys/{apikey_id}][%d] modifyUserApikeyOK %+v", 200, o.Payload) +} + +func (o *ModifyUserApikeyOK) GetPayload() *ModifyUserApikeyOKBody { + return o.Payload +} + +func (o *ModifyUserApikeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserApikeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyUserApikeyDefault creates a ModifyUserApikeyDefault with default headers values +func NewModifyUserApikeyDefault(code int) *ModifyUserApikeyDefault { + return &ModifyUserApikeyDefault{ + _statusCode: code, + } +} + +/* ModifyUserApikeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyUserApikeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserApikeyDefaultBody +} + +// Code gets the status code for the modify user apikey default response +func (o *ModifyUserApikeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify user apikey default response has a 2xx status code +func (o *ModifyUserApikeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify user apikey default response has a 3xx status code +func (o *ModifyUserApikeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify user apikey default response has a 4xx status code +func (o *ModifyUserApikeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify user apikey default response has a 5xx status code +func (o *ModifyUserApikeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify user apikey default response a status code equal to that given +func (o *ModifyUserApikeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyUserApikeyDefault) Error() string { + return fmt.Sprintf("[PUT /user/apikeys/{apikey_id}][%d] modifyUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserApikeyDefault) String() string { + return fmt.Sprintf("[PUT /user/apikeys/{apikey_id}][%d] modifyUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserApikeyDefault) GetPayload() *ModifyUserApikeyDefaultBody { + return o.Payload +} + +func (o *ModifyUserApikeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserApikeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyUserApikeyDefaultBody modify user apikey default body +swagger:model ModifyUserApikeyDefaultBody +*/ +type ModifyUserApikeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify user apikey default body +func (o *ModifyUserApikeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserApikeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserApikey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyUserApikeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserApikey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user apikey default body based on the context it is used +func (o *ModifyUserApikeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserApikeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserApikeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserApikeyDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyUserApikeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyUserApikeyOKBody modify user apikey o k body +swagger:model ModifyUserApikeyOKBody +*/ +type ModifyUserApikeyOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify user apikey o k body +func (o *ModifyUserApikeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserApikeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user apikey o k body based on the context it is used +func (o *ModifyUserApikeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserApikeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserApikeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserApikeyOKBody) UnmarshalBinary(b []byte) error { + var res ModifyUserApikeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/audit_log/audit_log_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/audit_log/audit_log_client.go new file mode 100644 index 0000000..38e1c67 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/audit_log/audit_log_client.go @@ -0,0 +1,117 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package audit_log + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new audit log API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for audit log API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DescribeAuditLogTypes(params *DescribeAuditLogTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAuditLogTypesOK, error) + + DescribeAuditLogs(params *DescribeAuditLogsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAuditLogsOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DescribeAuditLogTypes DescribeAuditLogTypes 获取审计日志类型 +*/ +func (a *Client) DescribeAuditLogTypes(params *DescribeAuditLogTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAuditLogTypesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeAuditLogTypesParams() + } + op := &runtime.ClientOperation{ + ID: "describeAuditLogTypes", + Method: "GET", + PathPattern: "/auditLogs/types", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeAuditLogTypesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeAuditLogTypesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeAuditLogTypesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeAuditLogs DescribeAuditLogs 获取审计日志列表 +*/ +func (a *Client) DescribeAuditLogs(params *DescribeAuditLogsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAuditLogsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeAuditLogsParams() + } + op := &runtime.ClientOperation{ + ID: "describeAuditLogs", + Method: "GET", + PathPattern: "/auditLogs", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeAuditLogsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeAuditLogsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeAuditLogsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/audit_log/describe_audit_log_types_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/audit_log/describe_audit_log_types_parameters.go new file mode 100644 index 0000000..b7dcb80 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/audit_log/describe_audit_log_types_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package audit_log + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeAuditLogTypesParams creates a new DescribeAuditLogTypesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeAuditLogTypesParams() *DescribeAuditLogTypesParams { + return &DescribeAuditLogTypesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeAuditLogTypesParamsWithTimeout creates a new DescribeAuditLogTypesParams object +// with the ability to set a timeout on a request. +func NewDescribeAuditLogTypesParamsWithTimeout(timeout time.Duration) *DescribeAuditLogTypesParams { + return &DescribeAuditLogTypesParams{ + timeout: timeout, + } +} + +// NewDescribeAuditLogTypesParamsWithContext creates a new DescribeAuditLogTypesParams object +// with the ability to set a context for a request. +func NewDescribeAuditLogTypesParamsWithContext(ctx context.Context) *DescribeAuditLogTypesParams { + return &DescribeAuditLogTypesParams{ + Context: ctx, + } +} + +// NewDescribeAuditLogTypesParamsWithHTTPClient creates a new DescribeAuditLogTypesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeAuditLogTypesParamsWithHTTPClient(client *http.Client) *DescribeAuditLogTypesParams { + return &DescribeAuditLogTypesParams{ + HTTPClient: client, + } +} + +/* DescribeAuditLogTypesParams contains all the parameters to send to the API endpoint + for the describe audit log types operation. + + Typically these are written to a http.Request. +*/ +type DescribeAuditLogTypesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe audit log types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAuditLogTypesParams) WithDefaults() *DescribeAuditLogTypesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe audit log types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAuditLogTypesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe audit log types params +func (o *DescribeAuditLogTypesParams) WithTimeout(timeout time.Duration) *DescribeAuditLogTypesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe audit log types params +func (o *DescribeAuditLogTypesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe audit log types params +func (o *DescribeAuditLogTypesParams) WithContext(ctx context.Context) *DescribeAuditLogTypesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe audit log types params +func (o *DescribeAuditLogTypesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe audit log types params +func (o *DescribeAuditLogTypesParams) WithHTTPClient(client *http.Client) *DescribeAuditLogTypesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe audit log types params +func (o *DescribeAuditLogTypesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe audit log types params +func (o *DescribeAuditLogTypesParams) WithAuthorization(authorization string) *DescribeAuditLogTypesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe audit log types params +func (o *DescribeAuditLogTypesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe audit log types params +func (o *DescribeAuditLogTypesParams) WithBmpLanguage(bmpLanguage *string) *DescribeAuditLogTypesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe audit log types params +func (o *DescribeAuditLogTypesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe audit log types params +func (o *DescribeAuditLogTypesParams) WithBmpUserID(bmpUserID *string) *DescribeAuditLogTypesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe audit log types params +func (o *DescribeAuditLogTypesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe audit log types params +func (o *DescribeAuditLogTypesParams) WithTraceID(traceID string) *DescribeAuditLogTypesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe audit log types params +func (o *DescribeAuditLogTypesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeAuditLogTypesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/audit_log/describe_audit_log_types_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/audit_log/describe_audit_log_types_responses.go new file mode 100644 index 0000000..88c999c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/audit_log/describe_audit_log_types_responses.go @@ -0,0 +1,415 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package audit_log + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeAuditLogTypesReader is a Reader for the DescribeAuditLogTypes structure. +type DescribeAuditLogTypesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeAuditLogTypesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeAuditLogTypesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeAuditLogTypesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeAuditLogTypesOK creates a DescribeAuditLogTypesOK with default headers values +func NewDescribeAuditLogTypesOK() *DescribeAuditLogTypesOK { + return &DescribeAuditLogTypesOK{} +} + +/* DescribeAuditLogTypesOK describes a response with status code 200, with default header values. + +DescribeAuditLogTypesOK describe audit log types o k +*/ +type DescribeAuditLogTypesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAuditLogTypesOKBody +} + +// IsSuccess returns true when this describe audit log types o k response has a 2xx status code +func (o *DescribeAuditLogTypesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe audit log types o k response has a 3xx status code +func (o *DescribeAuditLogTypesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe audit log types o k response has a 4xx status code +func (o *DescribeAuditLogTypesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe audit log types o k response has a 5xx status code +func (o *DescribeAuditLogTypesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe audit log types o k response a status code equal to that given +func (o *DescribeAuditLogTypesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeAuditLogTypesOK) Error() string { + return fmt.Sprintf("[GET /auditLogs/types][%d] describeAuditLogTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeAuditLogTypesOK) String() string { + return fmt.Sprintf("[GET /auditLogs/types][%d] describeAuditLogTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeAuditLogTypesOK) GetPayload() *DescribeAuditLogTypesOKBody { + return o.Payload +} + +func (o *DescribeAuditLogTypesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAuditLogTypesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeAuditLogTypesDefault creates a DescribeAuditLogTypesDefault with default headers values +func NewDescribeAuditLogTypesDefault(code int) *DescribeAuditLogTypesDefault { + return &DescribeAuditLogTypesDefault{ + _statusCode: code, + } +} + +/* DescribeAuditLogTypesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeAuditLogTypesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAuditLogTypesDefaultBody +} + +// Code gets the status code for the describe audit log types default response +func (o *DescribeAuditLogTypesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe audit log types default response has a 2xx status code +func (o *DescribeAuditLogTypesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe audit log types default response has a 3xx status code +func (o *DescribeAuditLogTypesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe audit log types default response has a 4xx status code +func (o *DescribeAuditLogTypesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe audit log types default response has a 5xx status code +func (o *DescribeAuditLogTypesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe audit log types default response a status code equal to that given +func (o *DescribeAuditLogTypesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeAuditLogTypesDefault) Error() string { + return fmt.Sprintf("[GET /auditLogs/types][%d] describeAuditLogTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAuditLogTypesDefault) String() string { + return fmt.Sprintf("[GET /auditLogs/types][%d] describeAuditLogTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAuditLogTypesDefault) GetPayload() *DescribeAuditLogTypesDefaultBody { + return o.Payload +} + +func (o *DescribeAuditLogTypesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAuditLogTypesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeAuditLogTypesDefaultBody describe audit log types default body +swagger:model DescribeAuditLogTypesDefaultBody +*/ +type DescribeAuditLogTypesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe audit log types default body +func (o *DescribeAuditLogTypesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogTypesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeAuditLogTypes default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeAuditLogTypesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeAuditLogTypes default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe audit log types default body based on the context it is used +func (o *DescribeAuditLogTypesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogTypesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAuditLogTypesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAuditLogTypesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeAuditLogTypesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeAuditLogTypesOKBody describe audit log types o k body +swagger:model DescribeAuditLogTypesOKBody +*/ +type DescribeAuditLogTypesOKBody struct { + + // result + Result []*models.AuditLogsType `json:"result"` +} + +// Validate validates this describe audit log types o k body +func (o *DescribeAuditLogTypesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogTypesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + for i := 0; i < len(o.Result); i++ { + if swag.IsZero(o.Result[i]) { // not required + continue + } + + if o.Result[i] != nil { + if err := o.Result[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogTypesOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogTypesOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this describe audit log types o k body based on the context it is used +func (o *DescribeAuditLogTypesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogTypesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Result); i++ { + + if o.Result[i] != nil { + if err := o.Result[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogTypesOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogTypesOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAuditLogTypesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAuditLogTypesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeAuditLogTypesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/audit_log/describe_audit_logs_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/audit_log/describe_audit_logs_parameters.go new file mode 100644 index 0000000..56b8189 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/audit_log/describe_audit_logs_parameters.go @@ -0,0 +1,536 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package audit_log + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeAuditLogsParams creates a new DescribeAuditLogsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeAuditLogsParams() *DescribeAuditLogsParams { + return &DescribeAuditLogsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeAuditLogsParamsWithTimeout creates a new DescribeAuditLogsParams object +// with the ability to set a timeout on a request. +func NewDescribeAuditLogsParamsWithTimeout(timeout time.Duration) *DescribeAuditLogsParams { + return &DescribeAuditLogsParams{ + timeout: timeout, + } +} + +// NewDescribeAuditLogsParamsWithContext creates a new DescribeAuditLogsParams object +// with the ability to set a context for a request. +func NewDescribeAuditLogsParamsWithContext(ctx context.Context) *DescribeAuditLogsParams { + return &DescribeAuditLogsParams{ + Context: ctx, + } +} + +// NewDescribeAuditLogsParamsWithHTTPClient creates a new DescribeAuditLogsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeAuditLogsParamsWithHTTPClient(client *http.Client) *DescribeAuditLogsParams { + return &DescribeAuditLogsParams{ + HTTPClient: client, + } +} + +/* DescribeAuditLogsParams contains all the parameters to send to the API endpoint + for the describe audit logs operation. + + Typically these are written to a http.Request. +*/ +type DescribeAuditLogsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* EndTime. + + 操作时间上限 + + Format: int64 + */ + EndTime *int64 + + /* IsAll. + + 是否显示所有 + */ + IsAll *string + + /* Operation. + + 操作名称 + */ + Operation *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* Result. + + result + */ + Result *string + + /* Sn. + + sn + */ + Sn *string + + /* StartTime. + + 操作时间下限 + + Format: int64 + */ + StartTime *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* Username. + + 操作人 + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe audit logs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAuditLogsParams) WithDefaults() *DescribeAuditLogsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe audit logs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAuditLogsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe audit logs params +func (o *DescribeAuditLogsParams) WithTimeout(timeout time.Duration) *DescribeAuditLogsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe audit logs params +func (o *DescribeAuditLogsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe audit logs params +func (o *DescribeAuditLogsParams) WithContext(ctx context.Context) *DescribeAuditLogsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe audit logs params +func (o *DescribeAuditLogsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe audit logs params +func (o *DescribeAuditLogsParams) WithHTTPClient(client *http.Client) *DescribeAuditLogsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe audit logs params +func (o *DescribeAuditLogsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe audit logs params +func (o *DescribeAuditLogsParams) WithAuthorization(authorization string) *DescribeAuditLogsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe audit logs params +func (o *DescribeAuditLogsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe audit logs params +func (o *DescribeAuditLogsParams) WithBmpLanguage(bmpLanguage *string) *DescribeAuditLogsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe audit logs params +func (o *DescribeAuditLogsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe audit logs params +func (o *DescribeAuditLogsParams) WithBmpUserID(bmpUserID *string) *DescribeAuditLogsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe audit logs params +func (o *DescribeAuditLogsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithEndTime adds the endTime to the describe audit logs params +func (o *DescribeAuditLogsParams) WithEndTime(endTime *int64) *DescribeAuditLogsParams { + o.SetEndTime(endTime) + return o +} + +// SetEndTime adds the endTime to the describe audit logs params +func (o *DescribeAuditLogsParams) SetEndTime(endTime *int64) { + o.EndTime = endTime +} + +// WithIsAll adds the isAll to the describe audit logs params +func (o *DescribeAuditLogsParams) WithIsAll(isAll *string) *DescribeAuditLogsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe audit logs params +func (o *DescribeAuditLogsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithOperation adds the operation to the describe audit logs params +func (o *DescribeAuditLogsParams) WithOperation(operation *string) *DescribeAuditLogsParams { + o.SetOperation(operation) + return o +} + +// SetOperation adds the operation to the describe audit logs params +func (o *DescribeAuditLogsParams) SetOperation(operation *string) { + o.Operation = operation +} + +// WithPageNumber adds the pageNumber to the describe audit logs params +func (o *DescribeAuditLogsParams) WithPageNumber(pageNumber *int64) *DescribeAuditLogsParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe audit logs params +func (o *DescribeAuditLogsParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe audit logs params +func (o *DescribeAuditLogsParams) WithPageSize(pageSize *int64) *DescribeAuditLogsParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe audit logs params +func (o *DescribeAuditLogsParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithResult adds the result to the describe audit logs params +func (o *DescribeAuditLogsParams) WithResult(result *string) *DescribeAuditLogsParams { + o.SetResult(result) + return o +} + +// SetResult adds the result to the describe audit logs params +func (o *DescribeAuditLogsParams) SetResult(result *string) { + o.Result = result +} + +// WithSn adds the sn to the describe audit logs params +func (o *DescribeAuditLogsParams) WithSn(sn *string) *DescribeAuditLogsParams { + o.SetSn(sn) + return o +} + +// SetSn adds the sn to the describe audit logs params +func (o *DescribeAuditLogsParams) SetSn(sn *string) { + o.Sn = sn +} + +// WithStartTime adds the startTime to the describe audit logs params +func (o *DescribeAuditLogsParams) WithStartTime(startTime *int64) *DescribeAuditLogsParams { + o.SetStartTime(startTime) + return o +} + +// SetStartTime adds the startTime to the describe audit logs params +func (o *DescribeAuditLogsParams) SetStartTime(startTime *int64) { + o.StartTime = startTime +} + +// WithTraceID adds the traceID to the describe audit logs params +func (o *DescribeAuditLogsParams) WithTraceID(traceID string) *DescribeAuditLogsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe audit logs params +func (o *DescribeAuditLogsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserName adds the username to the describe audit logs params +func (o *DescribeAuditLogsParams) WithUserName(username *string) *DescribeAuditLogsParams { + o.SetUserName(username) + return o +} + +// SetUserName adds the username to the describe audit logs params +func (o *DescribeAuditLogsParams) SetUserName(username *string) { + o.UserName = username +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeAuditLogsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.EndTime != nil { + + // query param endTime + var qrEndTime int64 + + if o.EndTime != nil { + qrEndTime = *o.EndTime + } + qEndTime := swag.FormatInt64(qrEndTime) + if qEndTime != "" { + + if err := r.SetQueryParam("endTime", qEndTime); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Operation != nil { + + // query param operation + var qrOperation string + + if o.Operation != nil { + qrOperation = *o.Operation + } + qOperation := qrOperation + if qOperation != "" { + + if err := r.SetQueryParam("operation", qOperation); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.Result != nil { + + // query param result + var qrResult string + + if o.Result != nil { + qrResult = *o.Result + } + qResult := qrResult + if qResult != "" { + + if err := r.SetQueryParam("result", qResult); err != nil { + return err + } + } + } + + if o.Sn != nil { + + // query param sn + var qrSn string + + if o.Sn != nil { + qrSn = *o.Sn + } + qSn := qrSn + if qSn != "" { + + if err := r.SetQueryParam("sn", qSn); err != nil { + return err + } + } + } + + if o.StartTime != nil { + + // query param startTime + var qrStartTime int64 + + if o.StartTime != nil { + qrStartTime = *o.StartTime + } + qStartTime := swag.FormatInt64(qrStartTime) + if qStartTime != "" { + + if err := r.SetQueryParam("startTime", qStartTime); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserName != nil { + + // query param username + var qrUsername string + + if o.UserName != nil { + qrUsername = *o.UserName + } + qUsername := qrUsername + if qUsername != "" { + + if err := r.SetQueryParam("username", qUsername); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/audit_log/describe_audit_logs_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/audit_log/describe_audit_logs_responses.go new file mode 100644 index 0000000..363249e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/audit_log/describe_audit_logs_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package audit_log + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeAuditLogsReader is a Reader for the DescribeAuditLogs structure. +type DescribeAuditLogsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeAuditLogsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeAuditLogsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeAuditLogsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeAuditLogsOK creates a DescribeAuditLogsOK with default headers values +func NewDescribeAuditLogsOK() *DescribeAuditLogsOK { + return &DescribeAuditLogsOK{} +} + +/* DescribeAuditLogsOK describes a response with status code 200, with default header values. + +DescribeAuditLogsOK describe audit logs o k +*/ +type DescribeAuditLogsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAuditLogsOKBody +} + +// IsSuccess returns true when this describe audit logs o k response has a 2xx status code +func (o *DescribeAuditLogsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe audit logs o k response has a 3xx status code +func (o *DescribeAuditLogsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe audit logs o k response has a 4xx status code +func (o *DescribeAuditLogsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe audit logs o k response has a 5xx status code +func (o *DescribeAuditLogsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe audit logs o k response a status code equal to that given +func (o *DescribeAuditLogsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeAuditLogsOK) Error() string { + return fmt.Sprintf("[GET /auditLogs][%d] describeAuditLogsOK %+v", 200, o.Payload) +} + +func (o *DescribeAuditLogsOK) String() string { + return fmt.Sprintf("[GET /auditLogs][%d] describeAuditLogsOK %+v", 200, o.Payload) +} + +func (o *DescribeAuditLogsOK) GetPayload() *DescribeAuditLogsOKBody { + return o.Payload +} + +func (o *DescribeAuditLogsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAuditLogsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeAuditLogsDefault creates a DescribeAuditLogsDefault with default headers values +func NewDescribeAuditLogsDefault(code int) *DescribeAuditLogsDefault { + return &DescribeAuditLogsDefault{ + _statusCode: code, + } +} + +/* DescribeAuditLogsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeAuditLogsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAuditLogsDefaultBody +} + +// Code gets the status code for the describe audit logs default response +func (o *DescribeAuditLogsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe audit logs default response has a 2xx status code +func (o *DescribeAuditLogsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe audit logs default response has a 3xx status code +func (o *DescribeAuditLogsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe audit logs default response has a 4xx status code +func (o *DescribeAuditLogsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe audit logs default response has a 5xx status code +func (o *DescribeAuditLogsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe audit logs default response a status code equal to that given +func (o *DescribeAuditLogsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeAuditLogsDefault) Error() string { + return fmt.Sprintf("[GET /auditLogs][%d] describeAuditLogs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAuditLogsDefault) String() string { + return fmt.Sprintf("[GET /auditLogs][%d] describeAuditLogs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAuditLogsDefault) GetPayload() *DescribeAuditLogsDefaultBody { + return o.Payload +} + +func (o *DescribeAuditLogsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAuditLogsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeAuditLogsDefaultBody describe audit logs default body +swagger:model DescribeAuditLogsDefaultBody +*/ +type DescribeAuditLogsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe audit logs default body +func (o *DescribeAuditLogsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeAuditLogs default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeAuditLogsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeAuditLogs default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogs default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe audit logs default body based on the context it is used +func (o *DescribeAuditLogsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogs default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAuditLogsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAuditLogsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeAuditLogsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeAuditLogsOKBody describe audit logs o k body +swagger:model DescribeAuditLogsOKBody +*/ +type DescribeAuditLogsOKBody struct { + + // result + Result *models.AuditLogList `json:"result,omitempty"` +} + +// Validate validates this describe audit logs o k body +func (o *DescribeAuditLogsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe audit logs o k body based on the context it is used +func (o *DescribeAuditLogsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAuditLogsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAuditLogsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAuditLogsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAuditLogsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAuditLogsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeAuditLogsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/c_p_s_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/c_p_s_client.go new file mode 100644 index 0000000..4b476bb --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/c_p_s_client.go @@ -0,0 +1,207 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package client + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/api_key" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/audit_log" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/device" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/device_type" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/idc" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/image" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/instance" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/license" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/message" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/monitor_alert" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/monitor_data" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/monitor_proxy" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/monitor_rule" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/os" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/project" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/raid" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/resource" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/role" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/sshkey" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/user" +) + +// Default c p s HTTP client. +var Default = NewHTTPClient(nil) + +const ( + // DefaultHost is the default Host + // found in Meta (info) section of spec file + DefaultHost string = "bmp-openapi.bmp.local" + // DefaultBasePath is the default BasePath + // found in Meta (info) section of spec file + DefaultBasePath string = "/v1" +) + +// DefaultSchemes are the default schemes found in Meta (info) section of spec file +var DefaultSchemes = []string{"http"} + +// NewHTTPClient creates a new c p s HTTP client. +func NewHTTPClient(formats strfmt.Registry) *CPS { + return NewHTTPClientWithConfig(formats, nil) +} + +// NewHTTPClientWithConfig creates a new c p s HTTP client, +// using a customizable transport config. +func NewHTTPClientWithConfig(formats strfmt.Registry, cfg *TransportConfig) *CPS { + // ensure nullable parameters have default + if cfg == nil { + cfg = DefaultTransportConfig() + } + + // create transport and client + transport := httptransport.New(cfg.Host, cfg.BasePath, cfg.Schemes) + return New(transport, formats) +} + +// New creates a new c p s client +func New(transport runtime.ClientTransport, formats strfmt.Registry) *CPS { + // ensure nullable parameters have default + if formats == nil { + formats = strfmt.Default + } + + cli := new(CPS) + cli.Transport = transport + cli.APIKey = api_key.New(transport, formats) + cli.AuditLog = audit_log.New(transport, formats) + cli.Device = device.New(transport, formats) + cli.DeviceType = device_type.New(transport, formats) + cli.Idc = idc.New(transport, formats) + cli.Image = image.New(transport, formats) + cli.Instance = instance.New(transport, formats) + cli.License = license.New(transport, formats) + cli.Message = message.New(transport, formats) + cli.MonitorAlert = monitor_alert.New(transport, formats) + cli.MonitorData = monitor_data.New(transport, formats) + cli.MonitorProxy = monitor_proxy.New(transport, formats) + cli.MonitorRule = monitor_rule.New(transport, formats) + cli.Os = os.New(transport, formats) + cli.Project = project.New(transport, formats) + cli.Raid = raid.New(transport, formats) + cli.Resource = resource.New(transport, formats) + cli.Role = role.New(transport, formats) + cli.Sshkey = sshkey.New(transport, formats) + cli.User = user.New(transport, formats) + return cli +} + +// DefaultTransportConfig creates a TransportConfig with the +// default settings taken from the meta section of the spec file. +func DefaultTransportConfig() *TransportConfig { + return &TransportConfig{ + Host: DefaultHost, + BasePath: DefaultBasePath, + Schemes: DefaultSchemes, + } +} + +// TransportConfig contains the transport related info, +// found in the meta section of the spec file. +type TransportConfig struct { + Host string + BasePath string + Schemes []string +} + +// WithHost overrides the default host, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithHost(host string) *TransportConfig { + cfg.Host = host + return cfg +} + +// WithBasePath overrides the default basePath, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithBasePath(basePath string) *TransportConfig { + cfg.BasePath = basePath + return cfg +} + +// WithSchemes overrides the default schemes, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithSchemes(schemes []string) *TransportConfig { + cfg.Schemes = schemes + return cfg +} + +// CPS is a client for c p s +type CPS struct { + APIKey api_key.ClientService + + AuditLog audit_log.ClientService + + Device device.ClientService + + DeviceType device_type.ClientService + + Idc idc.ClientService + + Image image.ClientService + + Instance instance.ClientService + + License license.ClientService + + Message message.ClientService + + MonitorAlert monitor_alert.ClientService + + MonitorData monitor_data.ClientService + + MonitorProxy monitor_proxy.ClientService + + MonitorRule monitor_rule.ClientService + + Os os.ClientService + + Project project.ClientService + + Raid raid.ClientService + + Resource resource.ClientService + + Role role.ClientService + + Sshkey sshkey.ClientService + + User user.ClientService + + Transport runtime.ClientTransport +} + +// SetTransport changes the transport on the client and all its subresources +func (c *CPS) SetTransport(transport runtime.ClientTransport) { + c.Transport = transport + c.APIKey.SetTransport(transport) + c.AuditLog.SetTransport(transport) + c.Device.SetTransport(transport) + c.DeviceType.SetTransport(transport) + c.Idc.SetTransport(transport) + c.Image.SetTransport(transport) + c.Instance.SetTransport(transport) + c.License.SetTransport(transport) + c.Message.SetTransport(transport) + c.MonitorAlert.SetTransport(transport) + c.MonitorData.SetTransport(transport) + c.MonitorProxy.SetTransport(transport) + c.MonitorRule.SetTransport(transport) + c.Os.SetTransport(transport) + c.Project.SetTransport(transport) + c.Raid.SetTransport(transport) + c.Resource.SetTransport(transport) + c.Role.SetTransport(transport) + c.Sshkey.SetTransport(transport) + c.User.SetTransport(transport) +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/associate_device_disks_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/associate_device_disks_parameters.go new file mode 100644 index 0000000..c7db68b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/associate_device_disks_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewAssociateDeviceDisksParams creates a new AssociateDeviceDisksParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewAssociateDeviceDisksParams() *AssociateDeviceDisksParams { + return &AssociateDeviceDisksParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewAssociateDeviceDisksParamsWithTimeout creates a new AssociateDeviceDisksParams object +// with the ability to set a timeout on a request. +func NewAssociateDeviceDisksParamsWithTimeout(timeout time.Duration) *AssociateDeviceDisksParams { + return &AssociateDeviceDisksParams{ + timeout: timeout, + } +} + +// NewAssociateDeviceDisksParamsWithContext creates a new AssociateDeviceDisksParams object +// with the ability to set a context for a request. +func NewAssociateDeviceDisksParamsWithContext(ctx context.Context) *AssociateDeviceDisksParams { + return &AssociateDeviceDisksParams{ + Context: ctx, + } +} + +// NewAssociateDeviceDisksParamsWithHTTPClient creates a new AssociateDeviceDisksParams object +// with the ability to set a custom HTTPClient for a request. +func NewAssociateDeviceDisksParamsWithHTTPClient(client *http.Client) *AssociateDeviceDisksParams { + return &AssociateDeviceDisksParams{ + HTTPClient: client, + } +} + +/* AssociateDeviceDisksParams contains all the parameters to send to the API endpoint + for the associate device disks operation. + + Typically these are written to a http.Request. +*/ +type AssociateDeviceDisksParams struct { + + // Body. + Body *models.AssociateDeviceDisksRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the associate device disks params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AssociateDeviceDisksParams) WithDefaults() *AssociateDeviceDisksParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the associate device disks params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AssociateDeviceDisksParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the associate device disks params +func (o *AssociateDeviceDisksParams) WithTimeout(timeout time.Duration) *AssociateDeviceDisksParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the associate device disks params +func (o *AssociateDeviceDisksParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the associate device disks params +func (o *AssociateDeviceDisksParams) WithContext(ctx context.Context) *AssociateDeviceDisksParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the associate device disks params +func (o *AssociateDeviceDisksParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the associate device disks params +func (o *AssociateDeviceDisksParams) WithHTTPClient(client *http.Client) *AssociateDeviceDisksParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the associate device disks params +func (o *AssociateDeviceDisksParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the associate device disks params +func (o *AssociateDeviceDisksParams) WithBody(body *models.AssociateDeviceDisksRequest) *AssociateDeviceDisksParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the associate device disks params +func (o *AssociateDeviceDisksParams) SetBody(body *models.AssociateDeviceDisksRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the associate device disks params +func (o *AssociateDeviceDisksParams) WithAuthorization(authorization string) *AssociateDeviceDisksParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the associate device disks params +func (o *AssociateDeviceDisksParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the associate device disks params +func (o *AssociateDeviceDisksParams) WithBmpLanguage(bmpLanguage *string) *AssociateDeviceDisksParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the associate device disks params +func (o *AssociateDeviceDisksParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the associate device disks params +func (o *AssociateDeviceDisksParams) WithBmpUserID(bmpUserID *string) *AssociateDeviceDisksParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the associate device disks params +func (o *AssociateDeviceDisksParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the associate device disks params +func (o *AssociateDeviceDisksParams) WithTraceID(traceID string) *AssociateDeviceDisksParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the associate device disks params +func (o *AssociateDeviceDisksParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *AssociateDeviceDisksParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/associate_device_disks_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/associate_device_disks_responses.go new file mode 100644 index 0000000..3fa9194 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/associate_device_disks_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// AssociateDeviceDisksReader is a Reader for the AssociateDeviceDisks structure. +type AssociateDeviceDisksReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *AssociateDeviceDisksReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewAssociateDeviceDisksOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewAssociateDeviceDisksDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewAssociateDeviceDisksOK creates a AssociateDeviceDisksOK with default headers values +func NewAssociateDeviceDisksOK() *AssociateDeviceDisksOK { + return &AssociateDeviceDisksOK{} +} + +/* AssociateDeviceDisksOK describes a response with status code 200, with default header values. + +AssociateDeviceDisksOK associate device disks o k +*/ +type AssociateDeviceDisksOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *AssociateDeviceDisksOKBody +} + +// IsSuccess returns true when this associate device disks o k response has a 2xx status code +func (o *AssociateDeviceDisksOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this associate device disks o k response has a 3xx status code +func (o *AssociateDeviceDisksOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this associate device disks o k response has a 4xx status code +func (o *AssociateDeviceDisksOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this associate device disks o k response has a 5xx status code +func (o *AssociateDeviceDisksOK) IsServerError() bool { + return false +} + +// IsCode returns true when this associate device disks o k response a status code equal to that given +func (o *AssociateDeviceDisksOK) IsCode(code int) bool { + return code == 200 +} + +func (o *AssociateDeviceDisksOK) Error() string { + return fmt.Sprintf("[PUT /devices/disks/associateDisks][%d] associateDeviceDisksOK %+v", 200, o.Payload) +} + +func (o *AssociateDeviceDisksOK) String() string { + return fmt.Sprintf("[PUT /devices/disks/associateDisks][%d] associateDeviceDisksOK %+v", 200, o.Payload) +} + +func (o *AssociateDeviceDisksOK) GetPayload() *AssociateDeviceDisksOKBody { + return o.Payload +} + +func (o *AssociateDeviceDisksOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AssociateDeviceDisksOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAssociateDeviceDisksDefault creates a AssociateDeviceDisksDefault with default headers values +func NewAssociateDeviceDisksDefault(code int) *AssociateDeviceDisksDefault { + return &AssociateDeviceDisksDefault{ + _statusCode: code, + } +} + +/* AssociateDeviceDisksDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type AssociateDeviceDisksDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *AssociateDeviceDisksDefaultBody +} + +// Code gets the status code for the associate device disks default response +func (o *AssociateDeviceDisksDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this associate device disks default response has a 2xx status code +func (o *AssociateDeviceDisksDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this associate device disks default response has a 3xx status code +func (o *AssociateDeviceDisksDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this associate device disks default response has a 4xx status code +func (o *AssociateDeviceDisksDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this associate device disks default response has a 5xx status code +func (o *AssociateDeviceDisksDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this associate device disks default response a status code equal to that given +func (o *AssociateDeviceDisksDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *AssociateDeviceDisksDefault) Error() string { + return fmt.Sprintf("[PUT /devices/disks/associateDisks][%d] associateDeviceDisks default %+v", o._statusCode, o.Payload) +} + +func (o *AssociateDeviceDisksDefault) String() string { + return fmt.Sprintf("[PUT /devices/disks/associateDisks][%d] associateDeviceDisks default %+v", o._statusCode, o.Payload) +} + +func (o *AssociateDeviceDisksDefault) GetPayload() *AssociateDeviceDisksDefaultBody { + return o.Payload +} + +func (o *AssociateDeviceDisksDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AssociateDeviceDisksDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*AssociateDeviceDisksDefaultBody associate device disks default body +swagger:model AssociateDeviceDisksDefaultBody +*/ +type AssociateDeviceDisksDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this associate device disks default body +func (o *AssociateDeviceDisksDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociateDeviceDisksDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("associateDeviceDisks default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *AssociateDeviceDisksDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("associateDeviceDisks default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associateDeviceDisks default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associateDeviceDisks default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this associate device disks default body based on the context it is used +func (o *AssociateDeviceDisksDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociateDeviceDisksDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associateDeviceDisks default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associateDeviceDisks default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AssociateDeviceDisksDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AssociateDeviceDisksDefaultBody) UnmarshalBinary(b []byte) error { + var res AssociateDeviceDisksDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*AssociateDeviceDisksOKBody associate device disks o k body +swagger:model AssociateDeviceDisksOKBody +*/ +type AssociateDeviceDisksOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this associate device disks o k body +func (o *AssociateDeviceDisksOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociateDeviceDisksOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associateDeviceDisksOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associateDeviceDisksOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this associate device disks o k body based on the context it is used +func (o *AssociateDeviceDisksOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociateDeviceDisksOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associateDeviceDisksOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associateDeviceDisksOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AssociateDeviceDisksOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AssociateDeviceDisksOKBody) UnmarshalBinary(b []byte) error { + var res AssociateDeviceDisksOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/collect_device_info_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/collect_device_info_parameters.go new file mode 100644 index 0000000..e31906e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/collect_device_info_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCollectDeviceInfoParams creates a new CollectDeviceInfoParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCollectDeviceInfoParams() *CollectDeviceInfoParams { + return &CollectDeviceInfoParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCollectDeviceInfoParamsWithTimeout creates a new CollectDeviceInfoParams object +// with the ability to set a timeout on a request. +func NewCollectDeviceInfoParamsWithTimeout(timeout time.Duration) *CollectDeviceInfoParams { + return &CollectDeviceInfoParams{ + timeout: timeout, + } +} + +// NewCollectDeviceInfoParamsWithContext creates a new CollectDeviceInfoParams object +// with the ability to set a context for a request. +func NewCollectDeviceInfoParamsWithContext(ctx context.Context) *CollectDeviceInfoParams { + return &CollectDeviceInfoParams{ + Context: ctx, + } +} + +// NewCollectDeviceInfoParamsWithHTTPClient creates a new CollectDeviceInfoParams object +// with the ability to set a custom HTTPClient for a request. +func NewCollectDeviceInfoParamsWithHTTPClient(client *http.Client) *CollectDeviceInfoParams { + return &CollectDeviceInfoParams{ + HTTPClient: client, + } +} + +/* CollectDeviceInfoParams contains all the parameters to send to the API endpoint + for the collect device info operation. + + Typically these are written to a http.Request. +*/ +type CollectDeviceInfoParams struct { + + // Body. + Body *models.CollectDeviceInfoRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the collect device info params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CollectDeviceInfoParams) WithDefaults() *CollectDeviceInfoParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the collect device info params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CollectDeviceInfoParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the collect device info params +func (o *CollectDeviceInfoParams) WithTimeout(timeout time.Duration) *CollectDeviceInfoParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the collect device info params +func (o *CollectDeviceInfoParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the collect device info params +func (o *CollectDeviceInfoParams) WithContext(ctx context.Context) *CollectDeviceInfoParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the collect device info params +func (o *CollectDeviceInfoParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the collect device info params +func (o *CollectDeviceInfoParams) WithHTTPClient(client *http.Client) *CollectDeviceInfoParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the collect device info params +func (o *CollectDeviceInfoParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the collect device info params +func (o *CollectDeviceInfoParams) WithBody(body *models.CollectDeviceInfoRequest) *CollectDeviceInfoParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the collect device info params +func (o *CollectDeviceInfoParams) SetBody(body *models.CollectDeviceInfoRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the collect device info params +func (o *CollectDeviceInfoParams) WithAuthorization(authorization string) *CollectDeviceInfoParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the collect device info params +func (o *CollectDeviceInfoParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the collect device info params +func (o *CollectDeviceInfoParams) WithBmpLanguage(bmpLanguage *string) *CollectDeviceInfoParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the collect device info params +func (o *CollectDeviceInfoParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the collect device info params +func (o *CollectDeviceInfoParams) WithBmpUserID(bmpUserID *string) *CollectDeviceInfoParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the collect device info params +func (o *CollectDeviceInfoParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the collect device info params +func (o *CollectDeviceInfoParams) WithTraceID(traceID string) *CollectDeviceInfoParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the collect device info params +func (o *CollectDeviceInfoParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CollectDeviceInfoParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/collect_device_info_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/collect_device_info_responses.go new file mode 100644 index 0000000..6362ead --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/collect_device_info_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CollectDeviceInfoReader is a Reader for the CollectDeviceInfo structure. +type CollectDeviceInfoReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CollectDeviceInfoReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCollectDeviceInfoOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCollectDeviceInfoDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCollectDeviceInfoOK creates a CollectDeviceInfoOK with default headers values +func NewCollectDeviceInfoOK() *CollectDeviceInfoOK { + return &CollectDeviceInfoOK{} +} + +/* CollectDeviceInfoOK describes a response with status code 200, with default header values. + +CollectDeviceInfoOK collect device info o k +*/ +type CollectDeviceInfoOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CollectDeviceInfoOKBody +} + +// IsSuccess returns true when this collect device info o k response has a 2xx status code +func (o *CollectDeviceInfoOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this collect device info o k response has a 3xx status code +func (o *CollectDeviceInfoOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this collect device info o k response has a 4xx status code +func (o *CollectDeviceInfoOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this collect device info o k response has a 5xx status code +func (o *CollectDeviceInfoOK) IsServerError() bool { + return false +} + +// IsCode returns true when this collect device info o k response a status code equal to that given +func (o *CollectDeviceInfoOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CollectDeviceInfoOK) Error() string { + return fmt.Sprintf("[POST /collect/collectDeviceInfo][%d] collectDeviceInfoOK %+v", 200, o.Payload) +} + +func (o *CollectDeviceInfoOK) String() string { + return fmt.Sprintf("[POST /collect/collectDeviceInfo][%d] collectDeviceInfoOK %+v", 200, o.Payload) +} + +func (o *CollectDeviceInfoOK) GetPayload() *CollectDeviceInfoOKBody { + return o.Payload +} + +func (o *CollectDeviceInfoOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CollectDeviceInfoOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCollectDeviceInfoDefault creates a CollectDeviceInfoDefault with default headers values +func NewCollectDeviceInfoDefault(code int) *CollectDeviceInfoDefault { + return &CollectDeviceInfoDefault{ + _statusCode: code, + } +} + +/* CollectDeviceInfoDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CollectDeviceInfoDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CollectDeviceInfoDefaultBody +} + +// Code gets the status code for the collect device info default response +func (o *CollectDeviceInfoDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this collect device info default response has a 2xx status code +func (o *CollectDeviceInfoDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this collect device info default response has a 3xx status code +func (o *CollectDeviceInfoDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this collect device info default response has a 4xx status code +func (o *CollectDeviceInfoDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this collect device info default response has a 5xx status code +func (o *CollectDeviceInfoDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this collect device info default response a status code equal to that given +func (o *CollectDeviceInfoDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CollectDeviceInfoDefault) Error() string { + return fmt.Sprintf("[POST /collect/collectDeviceInfo][%d] collectDeviceInfo default %+v", o._statusCode, o.Payload) +} + +func (o *CollectDeviceInfoDefault) String() string { + return fmt.Sprintf("[POST /collect/collectDeviceInfo][%d] collectDeviceInfo default %+v", o._statusCode, o.Payload) +} + +func (o *CollectDeviceInfoDefault) GetPayload() *CollectDeviceInfoDefaultBody { + return o.Payload +} + +func (o *CollectDeviceInfoDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CollectDeviceInfoDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CollectDeviceInfoDefaultBody collect device info default body +swagger:model CollectDeviceInfoDefaultBody +*/ +type CollectDeviceInfoDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this collect device info default body +func (o *CollectDeviceInfoDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CollectDeviceInfoDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("collectDeviceInfo default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CollectDeviceInfoDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("collectDeviceInfo default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("collectDeviceInfo default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("collectDeviceInfo default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this collect device info default body based on the context it is used +func (o *CollectDeviceInfoDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CollectDeviceInfoDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("collectDeviceInfo default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("collectDeviceInfo default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CollectDeviceInfoDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CollectDeviceInfoDefaultBody) UnmarshalBinary(b []byte) error { + var res CollectDeviceInfoDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CollectDeviceInfoOKBody collect device info o k body +swagger:model CollectDeviceInfoOKBody +*/ +type CollectDeviceInfoOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this collect device info o k body +func (o *CollectDeviceInfoOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CollectDeviceInfoOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("collectDeviceInfoOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("collectDeviceInfoOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this collect device info o k body based on the context it is used +func (o *CollectDeviceInfoOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CollectDeviceInfoOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("collectDeviceInfoOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("collectDeviceInfoOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CollectDeviceInfoOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CollectDeviceInfoOKBody) UnmarshalBinary(b []byte) error { + var res CollectDeviceInfoOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/create_device_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/create_device_parameters.go new file mode 100644 index 0000000..293324b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/create_device_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateDeviceParams creates a new CreateDeviceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateDeviceParams() *CreateDeviceParams { + return &CreateDeviceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateDeviceParamsWithTimeout creates a new CreateDeviceParams object +// with the ability to set a timeout on a request. +func NewCreateDeviceParamsWithTimeout(timeout time.Duration) *CreateDeviceParams { + return &CreateDeviceParams{ + timeout: timeout, + } +} + +// NewCreateDeviceParamsWithContext creates a new CreateDeviceParams object +// with the ability to set a context for a request. +func NewCreateDeviceParamsWithContext(ctx context.Context) *CreateDeviceParams { + return &CreateDeviceParams{ + Context: ctx, + } +} + +// NewCreateDeviceParamsWithHTTPClient creates a new CreateDeviceParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateDeviceParamsWithHTTPClient(client *http.Client) *CreateDeviceParams { + return &CreateDeviceParams{ + HTTPClient: client, + } +} + +/* CreateDeviceParams contains all the parameters to send to the API endpoint + for the create device operation. + + Typically these are written to a http.Request. +*/ +type CreateDeviceParams struct { + + // Body. + Body *models.CreateDevicesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateDeviceParams) WithDefaults() *CreateDeviceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateDeviceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create device params +func (o *CreateDeviceParams) WithTimeout(timeout time.Duration) *CreateDeviceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create device params +func (o *CreateDeviceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create device params +func (o *CreateDeviceParams) WithContext(ctx context.Context) *CreateDeviceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create device params +func (o *CreateDeviceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create device params +func (o *CreateDeviceParams) WithHTTPClient(client *http.Client) *CreateDeviceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create device params +func (o *CreateDeviceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create device params +func (o *CreateDeviceParams) WithBody(body *models.CreateDevicesRequest) *CreateDeviceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create device params +func (o *CreateDeviceParams) SetBody(body *models.CreateDevicesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create device params +func (o *CreateDeviceParams) WithAuthorization(authorization string) *CreateDeviceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create device params +func (o *CreateDeviceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create device params +func (o *CreateDeviceParams) WithBmpLanguage(bmpLanguage *string) *CreateDeviceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create device params +func (o *CreateDeviceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create device params +func (o *CreateDeviceParams) WithBmpUserID(bmpUserID *string) *CreateDeviceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create device params +func (o *CreateDeviceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create device params +func (o *CreateDeviceParams) WithTraceID(traceID string) *CreateDeviceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create device params +func (o *CreateDeviceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/create_device_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/create_device_responses.go new file mode 100644 index 0000000..dced3c9 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/create_device_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateDeviceReader is a Reader for the CreateDevice structure. +type CreateDeviceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateDeviceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateDeviceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateDeviceOK creates a CreateDeviceOK with default headers values +func NewCreateDeviceOK() *CreateDeviceOK { + return &CreateDeviceOK{} +} + +/* CreateDeviceOK describes a response with status code 200, with default header values. + +CreateDeviceOK create device o k +*/ +type CreateDeviceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateDeviceOKBody +} + +// IsSuccess returns true when this create device o k response has a 2xx status code +func (o *CreateDeviceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create device o k response has a 3xx status code +func (o *CreateDeviceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create device o k response has a 4xx status code +func (o *CreateDeviceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create device o k response has a 5xx status code +func (o *CreateDeviceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create device o k response a status code equal to that given +func (o *CreateDeviceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateDeviceOK) Error() string { + return fmt.Sprintf("[POST /devices][%d] createDeviceOK %+v", 200, o.Payload) +} + +func (o *CreateDeviceOK) String() string { + return fmt.Sprintf("[POST /devices][%d] createDeviceOK %+v", 200, o.Payload) +} + +func (o *CreateDeviceOK) GetPayload() *CreateDeviceOKBody { + return o.Payload +} + +func (o *CreateDeviceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateDeviceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateDeviceDefault creates a CreateDeviceDefault with default headers values +func NewCreateDeviceDefault(code int) *CreateDeviceDefault { + return &CreateDeviceDefault{ + _statusCode: code, + } +} + +/* CreateDeviceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateDeviceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateDeviceDefaultBody +} + +// Code gets the status code for the create device default response +func (o *CreateDeviceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create device default response has a 2xx status code +func (o *CreateDeviceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create device default response has a 3xx status code +func (o *CreateDeviceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create device default response has a 4xx status code +func (o *CreateDeviceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create device default response has a 5xx status code +func (o *CreateDeviceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create device default response a status code equal to that given +func (o *CreateDeviceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateDeviceDefault) Error() string { + return fmt.Sprintf("[POST /devices][%d] createDevice default %+v", o._statusCode, o.Payload) +} + +func (o *CreateDeviceDefault) String() string { + return fmt.Sprintf("[POST /devices][%d] createDevice default %+v", o._statusCode, o.Payload) +} + +func (o *CreateDeviceDefault) GetPayload() *CreateDeviceDefaultBody { + return o.Payload +} + +func (o *CreateDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateDeviceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateDeviceDefaultBody create device default body +swagger:model CreateDeviceDefaultBody +*/ +type CreateDeviceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create device default body +func (o *CreateDeviceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createDevice default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateDeviceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createDevice default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create device default body based on the context it is used +func (o *CreateDeviceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateDeviceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateDeviceDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateDeviceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateDeviceOKBody create device o k body +swagger:model CreateDeviceOKBody +*/ +type CreateDeviceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this create device o k body +func (o *CreateDeviceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create device o k body based on the context it is used +func (o *CreateDeviceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateDeviceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateDeviceOKBody) UnmarshalBinary(b []byte) error { + var res CreateDeviceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/delete_device_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/delete_device_parameters.go new file mode 100644 index 0000000..9736479 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/delete_device_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteDeviceParams creates a new DeleteDeviceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteDeviceParams() *DeleteDeviceParams { + return &DeleteDeviceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteDeviceParamsWithTimeout creates a new DeleteDeviceParams object +// with the ability to set a timeout on a request. +func NewDeleteDeviceParamsWithTimeout(timeout time.Duration) *DeleteDeviceParams { + return &DeleteDeviceParams{ + timeout: timeout, + } +} + +// NewDeleteDeviceParamsWithContext creates a new DeleteDeviceParams object +// with the ability to set a context for a request. +func NewDeleteDeviceParamsWithContext(ctx context.Context) *DeleteDeviceParams { + return &DeleteDeviceParams{ + Context: ctx, + } +} + +// NewDeleteDeviceParamsWithHTTPClient creates a new DeleteDeviceParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteDeviceParamsWithHTTPClient(client *http.Client) *DeleteDeviceParams { + return &DeleteDeviceParams{ + HTTPClient: client, + } +} + +/* DeleteDeviceParams contains all the parameters to send to the API endpoint + for the delete device operation. + + Typically these are written to a http.Request. +*/ +type DeleteDeviceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // DeviceID. + DeviceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteDeviceParams) WithDefaults() *DeleteDeviceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteDeviceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete device params +func (o *DeleteDeviceParams) WithTimeout(timeout time.Duration) *DeleteDeviceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete device params +func (o *DeleteDeviceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete device params +func (o *DeleteDeviceParams) WithContext(ctx context.Context) *DeleteDeviceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete device params +func (o *DeleteDeviceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete device params +func (o *DeleteDeviceParams) WithHTTPClient(client *http.Client) *DeleteDeviceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete device params +func (o *DeleteDeviceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete device params +func (o *DeleteDeviceParams) WithAuthorization(authorization string) *DeleteDeviceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete device params +func (o *DeleteDeviceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete device params +func (o *DeleteDeviceParams) WithBmpLanguage(bmpLanguage *string) *DeleteDeviceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete device params +func (o *DeleteDeviceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete device params +func (o *DeleteDeviceParams) WithBmpUserID(bmpUserID *string) *DeleteDeviceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete device params +func (o *DeleteDeviceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceID adds the deviceID to the delete device params +func (o *DeleteDeviceParams) WithDeviceID(deviceID string) *DeleteDeviceParams { + o.SetDeviceID(deviceID) + return o +} + +// SetDeviceID adds the deviceId to the delete device params +func (o *DeleteDeviceParams) SetDeviceID(deviceID string) { + o.DeviceID = deviceID +} + +// WithTraceID adds the traceID to the delete device params +func (o *DeleteDeviceParams) WithTraceID(traceID string) *DeleteDeviceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete device params +func (o *DeleteDeviceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_id + if err := r.SetPathParam("device_id", o.DeviceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/delete_device_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/delete_device_responses.go new file mode 100644 index 0000000..084a18d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/delete_device_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteDeviceReader is a Reader for the DeleteDevice structure. +type DeleteDeviceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteDeviceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteDeviceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteDeviceOK creates a DeleteDeviceOK with default headers values +func NewDeleteDeviceOK() *DeleteDeviceOK { + return &DeleteDeviceOK{} +} + +/* DeleteDeviceOK describes a response with status code 200, with default header values. + +A DeleteDeviceResult is an response struct that is used to describe delete device result. +*/ +type DeleteDeviceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteDeviceOKBody +} + +// IsSuccess returns true when this delete device o k response has a 2xx status code +func (o *DeleteDeviceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete device o k response has a 3xx status code +func (o *DeleteDeviceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete device o k response has a 4xx status code +func (o *DeleteDeviceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete device o k response has a 5xx status code +func (o *DeleteDeviceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete device o k response a status code equal to that given +func (o *DeleteDeviceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteDeviceOK) Error() string { + return fmt.Sprintf("[DELETE /devices/{device_id}][%d] deleteDeviceOK %+v", 200, o.Payload) +} + +func (o *DeleteDeviceOK) String() string { + return fmt.Sprintf("[DELETE /devices/{device_id}][%d] deleteDeviceOK %+v", 200, o.Payload) +} + +func (o *DeleteDeviceOK) GetPayload() *DeleteDeviceOKBody { + return o.Payload +} + +func (o *DeleteDeviceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteDeviceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteDeviceDefault creates a DeleteDeviceDefault with default headers values +func NewDeleteDeviceDefault(code int) *DeleteDeviceDefault { + return &DeleteDeviceDefault{ + _statusCode: code, + } +} + +/* DeleteDeviceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteDeviceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteDeviceDefaultBody +} + +// Code gets the status code for the delete device default response +func (o *DeleteDeviceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete device default response has a 2xx status code +func (o *DeleteDeviceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete device default response has a 3xx status code +func (o *DeleteDeviceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete device default response has a 4xx status code +func (o *DeleteDeviceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete device default response has a 5xx status code +func (o *DeleteDeviceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete device default response a status code equal to that given +func (o *DeleteDeviceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteDeviceDefault) Error() string { + return fmt.Sprintf("[DELETE /devices/{device_id}][%d] deleteDevice default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteDeviceDefault) String() string { + return fmt.Sprintf("[DELETE /devices/{device_id}][%d] deleteDevice default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteDeviceDefault) GetPayload() *DeleteDeviceDefaultBody { + return o.Payload +} + +func (o *DeleteDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteDeviceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteDeviceDefaultBody delete device default body +swagger:model DeleteDeviceDefaultBody +*/ +type DeleteDeviceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete device default body +func (o *DeleteDeviceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteDevice default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteDeviceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteDevice default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete device default body based on the context it is used +func (o *DeleteDeviceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteDeviceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteDeviceDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteDeviceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteDeviceOKBody delete device o k body +swagger:model DeleteDeviceOKBody +*/ +type DeleteDeviceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete device o k body +func (o *DeleteDeviceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete device o k body based on the context it is used +func (o *DeleteDeviceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteDeviceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteDeviceOKBody) UnmarshalBinary(b []byte) error { + var res DeleteDeviceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_disks_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_disks_parameters.go new file mode 100644 index 0000000..0de12ba --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_disks_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeDeviceDisksParams creates a new DescribeDeviceDisksParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceDisksParams() *DescribeDeviceDisksParams { + return &DescribeDeviceDisksParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceDisksParamsWithTimeout creates a new DescribeDeviceDisksParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceDisksParamsWithTimeout(timeout time.Duration) *DescribeDeviceDisksParams { + return &DescribeDeviceDisksParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceDisksParamsWithContext creates a new DescribeDeviceDisksParams object +// with the ability to set a context for a request. +func NewDescribeDeviceDisksParamsWithContext(ctx context.Context) *DescribeDeviceDisksParams { + return &DescribeDeviceDisksParams{ + Context: ctx, + } +} + +// NewDescribeDeviceDisksParamsWithHTTPClient creates a new DescribeDeviceDisksParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceDisksParamsWithHTTPClient(client *http.Client) *DescribeDeviceDisksParams { + return &DescribeDeviceDisksParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceDisksParams contains all the parameters to send to the API endpoint + for the describe device disks operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceDisksParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // DeviceID. + DeviceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device disks params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceDisksParams) WithDefaults() *DescribeDeviceDisksParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device disks params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceDisksParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device disks params +func (o *DescribeDeviceDisksParams) WithTimeout(timeout time.Duration) *DescribeDeviceDisksParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device disks params +func (o *DescribeDeviceDisksParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device disks params +func (o *DescribeDeviceDisksParams) WithContext(ctx context.Context) *DescribeDeviceDisksParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device disks params +func (o *DescribeDeviceDisksParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device disks params +func (o *DescribeDeviceDisksParams) WithHTTPClient(client *http.Client) *DescribeDeviceDisksParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device disks params +func (o *DescribeDeviceDisksParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device disks params +func (o *DescribeDeviceDisksParams) WithAuthorization(authorization string) *DescribeDeviceDisksParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device disks params +func (o *DescribeDeviceDisksParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device disks params +func (o *DescribeDeviceDisksParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceDisksParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device disks params +func (o *DescribeDeviceDisksParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device disks params +func (o *DescribeDeviceDisksParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceDisksParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device disks params +func (o *DescribeDeviceDisksParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceID adds the deviceID to the describe device disks params +func (o *DescribeDeviceDisksParams) WithDeviceID(deviceID string) *DescribeDeviceDisksParams { + o.SetDeviceID(deviceID) + return o +} + +// SetDeviceID adds the deviceId to the describe device disks params +func (o *DescribeDeviceDisksParams) SetDeviceID(deviceID string) { + o.DeviceID = deviceID +} + +// WithTraceID adds the traceID to the describe device disks params +func (o *DescribeDeviceDisksParams) WithTraceID(traceID string) *DescribeDeviceDisksParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device disks params +func (o *DescribeDeviceDisksParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceDisksParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_id + if err := r.SetPathParam("device_id", o.DeviceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_disks_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_disks_responses.go new file mode 100644 index 0000000..ce00ae9 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_disks_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDeviceDisksReader is a Reader for the DescribeDeviceDisks structure. +type DescribeDeviceDisksReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceDisksReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceDisksOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceDisksDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceDisksOK creates a DescribeDeviceDisksOK with default headers values +func NewDescribeDeviceDisksOK() *DescribeDeviceDisksOK { + return &DescribeDeviceDisksOK{} +} + +/* DescribeDeviceDisksOK describes a response with status code 200, with default header values. + +DescribeDeviceDisksOK describe device disks o k +*/ +type DescribeDeviceDisksOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceDisksOKBody +} + +// IsSuccess returns true when this describe device disks o k response has a 2xx status code +func (o *DescribeDeviceDisksOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device disks o k response has a 3xx status code +func (o *DescribeDeviceDisksOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device disks o k response has a 4xx status code +func (o *DescribeDeviceDisksOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device disks o k response has a 5xx status code +func (o *DescribeDeviceDisksOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device disks o k response a status code equal to that given +func (o *DescribeDeviceDisksOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceDisksOK) Error() string { + return fmt.Sprintf("[GET /devices/{device_id}/disksDetail][%d] describeDeviceDisksOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceDisksOK) String() string { + return fmt.Sprintf("[GET /devices/{device_id}/disksDetail][%d] describeDeviceDisksOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceDisksOK) GetPayload() *DescribeDeviceDisksOKBody { + return o.Payload +} + +func (o *DescribeDeviceDisksOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceDisksOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceDisksDefault creates a DescribeDeviceDisksDefault with default headers values +func NewDescribeDeviceDisksDefault(code int) *DescribeDeviceDisksDefault { + return &DescribeDeviceDisksDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceDisksDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceDisksDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceDisksDefaultBody +} + +// Code gets the status code for the describe device disks default response +func (o *DescribeDeviceDisksDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device disks default response has a 2xx status code +func (o *DescribeDeviceDisksDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device disks default response has a 3xx status code +func (o *DescribeDeviceDisksDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device disks default response has a 4xx status code +func (o *DescribeDeviceDisksDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device disks default response has a 5xx status code +func (o *DescribeDeviceDisksDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device disks default response a status code equal to that given +func (o *DescribeDeviceDisksDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceDisksDefault) Error() string { + return fmt.Sprintf("[GET /devices/{device_id}/disksDetail][%d] describeDeviceDisks default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceDisksDefault) String() string { + return fmt.Sprintf("[GET /devices/{device_id}/disksDetail][%d] describeDeviceDisks default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceDisksDefault) GetPayload() *DescribeDeviceDisksDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceDisksDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceDisksDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceDisksDefaultBody describe device disks default body +swagger:model DescribeDeviceDisksDefaultBody +*/ +type DescribeDeviceDisksDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device disks default body +func (o *DescribeDeviceDisksDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceDisksDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceDisks default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceDisksDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceDisks default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceDisks default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceDisks default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device disks default body based on the context it is used +func (o *DescribeDeviceDisksDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceDisksDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceDisks default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceDisks default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceDisksDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceDisksDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceDisksDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceDisksOKBody describe device disks o k body +swagger:model DescribeDeviceDisksOKBody +*/ +type DescribeDeviceDisksOKBody struct { + + // result + Result *models.DeviceDisks `json:"result,omitempty"` +} + +// Validate validates this describe device disks o k body +func (o *DescribeDeviceDisksOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceDisksOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceDisksOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceDisksOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device disks o k body based on the context it is used +func (o *DescribeDeviceDisksOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceDisksOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceDisksOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceDisksOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceDisksOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceDisksOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceDisksOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_parameters.go new file mode 100644 index 0000000..7c7e31e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeDeviceParams creates a new DescribeDeviceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceParams() *DescribeDeviceParams { + return &DescribeDeviceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceParamsWithTimeout creates a new DescribeDeviceParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceParamsWithTimeout(timeout time.Duration) *DescribeDeviceParams { + return &DescribeDeviceParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceParamsWithContext creates a new DescribeDeviceParams object +// with the ability to set a context for a request. +func NewDescribeDeviceParamsWithContext(ctx context.Context) *DescribeDeviceParams { + return &DescribeDeviceParams{ + Context: ctx, + } +} + +// NewDescribeDeviceParamsWithHTTPClient creates a new DescribeDeviceParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceParamsWithHTTPClient(client *http.Client) *DescribeDeviceParams { + return &DescribeDeviceParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceParams contains all the parameters to send to the API endpoint + for the describe device operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // DeviceID. + DeviceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceParams) WithDefaults() *DescribeDeviceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device params +func (o *DescribeDeviceParams) WithTimeout(timeout time.Duration) *DescribeDeviceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device params +func (o *DescribeDeviceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device params +func (o *DescribeDeviceParams) WithContext(ctx context.Context) *DescribeDeviceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device params +func (o *DescribeDeviceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device params +func (o *DescribeDeviceParams) WithHTTPClient(client *http.Client) *DescribeDeviceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device params +func (o *DescribeDeviceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device params +func (o *DescribeDeviceParams) WithAuthorization(authorization string) *DescribeDeviceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device params +func (o *DescribeDeviceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device params +func (o *DescribeDeviceParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device params +func (o *DescribeDeviceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device params +func (o *DescribeDeviceParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device params +func (o *DescribeDeviceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceID adds the deviceID to the describe device params +func (o *DescribeDeviceParams) WithDeviceID(deviceID string) *DescribeDeviceParams { + o.SetDeviceID(deviceID) + return o +} + +// SetDeviceID adds the deviceId to the describe device params +func (o *DescribeDeviceParams) SetDeviceID(deviceID string) { + o.DeviceID = deviceID +} + +// WithTraceID adds the traceID to the describe device params +func (o *DescribeDeviceParams) WithTraceID(traceID string) *DescribeDeviceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device params +func (o *DescribeDeviceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_id + if err := r.SetPathParam("device_id", o.DeviceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_responses.go new file mode 100644 index 0000000..d28bf8d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDeviceReader is a Reader for the DescribeDevice structure. +type DescribeDeviceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceOK creates a DescribeDeviceOK with default headers values +func NewDescribeDeviceOK() *DescribeDeviceOK { + return &DescribeDeviceOK{} +} + +/* DescribeDeviceOK describes a response with status code 200, with default header values. + +DescribeDeviceOK describe device o k +*/ +type DescribeDeviceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceOKBody +} + +// IsSuccess returns true when this describe device o k response has a 2xx status code +func (o *DescribeDeviceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device o k response has a 3xx status code +func (o *DescribeDeviceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device o k response has a 4xx status code +func (o *DescribeDeviceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device o k response has a 5xx status code +func (o *DescribeDeviceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device o k response a status code equal to that given +func (o *DescribeDeviceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceOK) Error() string { + return fmt.Sprintf("[GET /devices/{device_id}][%d] describeDeviceOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceOK) String() string { + return fmt.Sprintf("[GET /devices/{device_id}][%d] describeDeviceOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceOK) GetPayload() *DescribeDeviceOKBody { + return o.Payload +} + +func (o *DescribeDeviceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceDefault creates a DescribeDeviceDefault with default headers values +func NewDescribeDeviceDefault(code int) *DescribeDeviceDefault { + return &DescribeDeviceDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceDefaultBody +} + +// Code gets the status code for the describe device default response +func (o *DescribeDeviceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device default response has a 2xx status code +func (o *DescribeDeviceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device default response has a 3xx status code +func (o *DescribeDeviceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device default response has a 4xx status code +func (o *DescribeDeviceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device default response has a 5xx status code +func (o *DescribeDeviceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device default response a status code equal to that given +func (o *DescribeDeviceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceDefault) Error() string { + return fmt.Sprintf("[GET /devices/{device_id}][%d] describeDevice default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceDefault) String() string { + return fmt.Sprintf("[GET /devices/{device_id}][%d] describeDevice default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceDefault) GetPayload() *DescribeDeviceDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceDefaultBody describe device default body +swagger:model DescribeDeviceDefaultBody +*/ +type DescribeDeviceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device default body +func (o *DescribeDeviceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDevice default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDevice default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device default body based on the context it is used +func (o *DescribeDeviceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceOKBody describe device o k body +swagger:model DescribeDeviceOKBody +*/ +type DescribeDeviceOKBody struct { + + // result + Result *models.DeviceInfo `json:"result,omitempty"` +} + +// Validate validates this describe device o k body +func (o *DescribeDeviceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device o k body based on the context it is used +func (o *DescribeDeviceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_stock_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_stock_parameters.go new file mode 100644 index 0000000..66c5c8f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_stock_parameters.go @@ -0,0 +1,252 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeDeviceStockParams creates a new DescribeDeviceStockParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceStockParams() *DescribeDeviceStockParams { + return &DescribeDeviceStockParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceStockParamsWithTimeout creates a new DescribeDeviceStockParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceStockParamsWithTimeout(timeout time.Duration) *DescribeDeviceStockParams { + return &DescribeDeviceStockParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceStockParamsWithContext creates a new DescribeDeviceStockParams object +// with the ability to set a context for a request. +func NewDescribeDeviceStockParamsWithContext(ctx context.Context) *DescribeDeviceStockParams { + return &DescribeDeviceStockParams{ + Context: ctx, + } +} + +// NewDescribeDeviceStockParamsWithHTTPClient creates a new DescribeDeviceStockParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceStockParamsWithHTTPClient(client *http.Client) *DescribeDeviceStockParams { + return &DescribeDeviceStockParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceStockParams contains all the parameters to send to the API endpoint + for the describe device stock operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceStockParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // DeviceTypeID. + DeviceTypeID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device stock params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceStockParams) WithDefaults() *DescribeDeviceStockParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device stock params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceStockParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device stock params +func (o *DescribeDeviceStockParams) WithTimeout(timeout time.Duration) *DescribeDeviceStockParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device stock params +func (o *DescribeDeviceStockParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device stock params +func (o *DescribeDeviceStockParams) WithContext(ctx context.Context) *DescribeDeviceStockParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device stock params +func (o *DescribeDeviceStockParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device stock params +func (o *DescribeDeviceStockParams) WithHTTPClient(client *http.Client) *DescribeDeviceStockParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device stock params +func (o *DescribeDeviceStockParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device stock params +func (o *DescribeDeviceStockParams) WithAuthorization(authorization string) *DescribeDeviceStockParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device stock params +func (o *DescribeDeviceStockParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device stock params +func (o *DescribeDeviceStockParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceStockParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device stock params +func (o *DescribeDeviceStockParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device stock params +func (o *DescribeDeviceStockParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceStockParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device stock params +func (o *DescribeDeviceStockParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device stock params +func (o *DescribeDeviceStockParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDeviceStockParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device stock params +func (o *DescribeDeviceStockParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithTraceID adds the traceID to the describe device stock params +func (o *DescribeDeviceStockParams) WithTraceID(traceID string) *DescribeDeviceStockParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device stock params +func (o *DescribeDeviceStockParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceStockParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_stock_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_stock_responses.go new file mode 100644 index 0000000..74d726b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_stock_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDeviceStockReader is a Reader for the DescribeDeviceStock structure. +type DescribeDeviceStockReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceStockReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceStockOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceStockDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceStockOK creates a DescribeDeviceStockOK with default headers values +func NewDescribeDeviceStockOK() *DescribeDeviceStockOK { + return &DescribeDeviceStockOK{} +} + +/* DescribeDeviceStockOK describes a response with status code 200, with default header values. + +A GetDeviceStockResult is an response struct that is used to get device stock. +*/ +type DescribeDeviceStockOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceStockOKBody +} + +// IsSuccess returns true when this describe device stock o k response has a 2xx status code +func (o *DescribeDeviceStockOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device stock o k response has a 3xx status code +func (o *DescribeDeviceStockOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device stock o k response has a 4xx status code +func (o *DescribeDeviceStockOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device stock o k response has a 5xx status code +func (o *DescribeDeviceStockOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device stock o k response a status code equal to that given +func (o *DescribeDeviceStockOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceStockOK) Error() string { + return fmt.Sprintf("[DELETE /devices/stock][%d] describeDeviceStockOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceStockOK) String() string { + return fmt.Sprintf("[DELETE /devices/stock][%d] describeDeviceStockOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceStockOK) GetPayload() *DescribeDeviceStockOKBody { + return o.Payload +} + +func (o *DescribeDeviceStockOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceStockOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceStockDefault creates a DescribeDeviceStockDefault with default headers values +func NewDescribeDeviceStockDefault(code int) *DescribeDeviceStockDefault { + return &DescribeDeviceStockDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceStockDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceStockDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceStockDefaultBody +} + +// Code gets the status code for the describe device stock default response +func (o *DescribeDeviceStockDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device stock default response has a 2xx status code +func (o *DescribeDeviceStockDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device stock default response has a 3xx status code +func (o *DescribeDeviceStockDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device stock default response has a 4xx status code +func (o *DescribeDeviceStockDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device stock default response has a 5xx status code +func (o *DescribeDeviceStockDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device stock default response a status code equal to that given +func (o *DescribeDeviceStockDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceStockDefault) Error() string { + return fmt.Sprintf("[DELETE /devices/stock][%d] describeDeviceStock default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceStockDefault) String() string { + return fmt.Sprintf("[DELETE /devices/stock][%d] describeDeviceStock default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceStockDefault) GetPayload() *DescribeDeviceStockDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceStockDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceStockDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceStockDefaultBody describe device stock default body +swagger:model DescribeDeviceStockDefaultBody +*/ +type DescribeDeviceStockDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device stock default body +func (o *DescribeDeviceStockDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceStockDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceStock default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceStockDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceStock default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceStock default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceStock default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device stock default body based on the context it is used +func (o *DescribeDeviceStockDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceStockDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceStock default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceStock default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceStockDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceStockDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceStockDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceStockOKBody describe device stock o k body +swagger:model DescribeDeviceStockOKBody +*/ +type DescribeDeviceStockOKBody struct { + + // result + Result *models.DeviceStock `json:"result,omitempty"` +} + +// Validate validates this describe device stock o k body +func (o *DescribeDeviceStockOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceStockOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceStockOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceStockOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device stock o k body based on the context it is used +func (o *DescribeDeviceStockOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceStockOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceStockOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceStockOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceStockOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceStockOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceStockOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_devices_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_devices_parameters.go new file mode 100644 index 0000000..bc2ab2c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_devices_parameters.go @@ -0,0 +1,770 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeDevicesParams creates a new DescribeDevicesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDevicesParams() *DescribeDevicesParams { + return &DescribeDevicesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDevicesParamsWithTimeout creates a new DescribeDevicesParams object +// with the ability to set a timeout on a request. +func NewDescribeDevicesParamsWithTimeout(timeout time.Duration) *DescribeDevicesParams { + return &DescribeDevicesParams{ + timeout: timeout, + } +} + +// NewDescribeDevicesParamsWithContext creates a new DescribeDevicesParams object +// with the ability to set a context for a request. +func NewDescribeDevicesParamsWithContext(ctx context.Context) *DescribeDevicesParams { + return &DescribeDevicesParams{ + Context: ctx, + } +} + +// NewDescribeDevicesParamsWithHTTPClient creates a new DescribeDevicesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDevicesParamsWithHTTPClient(client *http.Client) *DescribeDevicesParams { + return &DescribeDevicesParams{ + HTTPClient: client, + } +} + +/* DescribeDevicesParams contains all the parameters to send to the API endpoint + for the describe devices operation. + + Typically these are written to a http.Request. +*/ +type DescribeDevicesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* CollectStatus. + + "1"表示已采集,"2"表示未采集,"3"表示采集中,4表示采集失败 + */ + CollectStatus *string + + /* DeviceSeries. + + 机型类型 + */ + DeviceSeries *string + + /* DeviceTypeID. + + 机型id + */ + DeviceTypeID *string + + /* IdcID. + + 机房id + */ + IDcID *string + + /* IloIP. + + 带外ip + */ + IloIP *string + + /* InstanceID. + + 实例id + */ + InstanceID *string + + /* InstanceName. + + 实例名称 + */ + InstanceName *string + + /* IPV4. + + ipv4 + */ + IPV4 *string + + /* IPV6. + + ipv6 + */ + IPV6 *string + + /* IsAll. + + 是否显示全部,1不分页 + */ + IsAll *string + + /* ManageStatus. + + 设备管理状态 + */ + ManageStatus *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* Sn. + + 设备sn + */ + Sn *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserID. + + 所属用户id + */ + UserID *string + + /* UserName. + + 所属用户 + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe devices params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDevicesParams) WithDefaults() *DescribeDevicesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe devices params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDevicesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe devices params +func (o *DescribeDevicesParams) WithTimeout(timeout time.Duration) *DescribeDevicesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe devices params +func (o *DescribeDevicesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe devices params +func (o *DescribeDevicesParams) WithContext(ctx context.Context) *DescribeDevicesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe devices params +func (o *DescribeDevicesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe devices params +func (o *DescribeDevicesParams) WithHTTPClient(client *http.Client) *DescribeDevicesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe devices params +func (o *DescribeDevicesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe devices params +func (o *DescribeDevicesParams) WithAuthorization(authorization string) *DescribeDevicesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe devices params +func (o *DescribeDevicesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe devices params +func (o *DescribeDevicesParams) WithBmpLanguage(bmpLanguage *string) *DescribeDevicesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe devices params +func (o *DescribeDevicesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe devices params +func (o *DescribeDevicesParams) WithBmpUserID(bmpUserID *string) *DescribeDevicesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe devices params +func (o *DescribeDevicesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithCollectStatus adds the collectStatus to the describe devices params +func (o *DescribeDevicesParams) WithCollectStatus(collectStatus *string) *DescribeDevicesParams { + o.SetCollectStatus(collectStatus) + return o +} + +// SetCollectStatus adds the collectStatus to the describe devices params +func (o *DescribeDevicesParams) SetCollectStatus(collectStatus *string) { + o.CollectStatus = collectStatus +} + +// WithDeviceSeries adds the deviceSeries to the describe devices params +func (o *DescribeDevicesParams) WithDeviceSeries(deviceSeries *string) *DescribeDevicesParams { + o.SetDeviceSeries(deviceSeries) + return o +} + +// SetDeviceSeries adds the deviceSeries to the describe devices params +func (o *DescribeDevicesParams) SetDeviceSeries(deviceSeries *string) { + o.DeviceSeries = deviceSeries +} + +// WithDeviceTypeID adds the deviceTypeID to the describe devices params +func (o *DescribeDevicesParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDevicesParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe devices params +func (o *DescribeDevicesParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithIDcID adds the idcID to the describe devices params +func (o *DescribeDevicesParams) WithIDcID(idcID *string) *DescribeDevicesParams { + o.SetIDcID(idcID) + return o +} + +// SetIDcID adds the idcId to the describe devices params +func (o *DescribeDevicesParams) SetIDcID(idcID *string) { + o.IDcID = idcID +} + +// WithIloIP adds the iloIP to the describe devices params +func (o *DescribeDevicesParams) WithIloIP(iloIP *string) *DescribeDevicesParams { + o.SetIloIP(iloIP) + return o +} + +// SetIloIP adds the iloIp to the describe devices params +func (o *DescribeDevicesParams) SetIloIP(iloIP *string) { + o.IloIP = iloIP +} + +// WithInstanceID adds the instanceID to the describe devices params +func (o *DescribeDevicesParams) WithInstanceID(instanceID *string) *DescribeDevicesParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the describe devices params +func (o *DescribeDevicesParams) SetInstanceID(instanceID *string) { + o.InstanceID = instanceID +} + +// WithInstanceName adds the instanceName to the describe devices params +func (o *DescribeDevicesParams) WithInstanceName(instanceName *string) *DescribeDevicesParams { + o.SetInstanceName(instanceName) + return o +} + +// SetInstanceName adds the instanceName to the describe devices params +func (o *DescribeDevicesParams) SetInstanceName(instanceName *string) { + o.InstanceName = instanceName +} + +// WithIPV4 adds the iPV4 to the describe devices params +func (o *DescribeDevicesParams) WithIPV4(iPV4 *string) *DescribeDevicesParams { + o.SetIPV4(iPV4) + return o +} + +// SetIPV4 adds the ipv4 to the describe devices params +func (o *DescribeDevicesParams) SetIPV4(iPV4 *string) { + o.IPV4 = iPV4 +} + +// WithIPV6 adds the iPV6 to the describe devices params +func (o *DescribeDevicesParams) WithIPV6(iPV6 *string) *DescribeDevicesParams { + o.SetIPV6(iPV6) + return o +} + +// SetIPV6 adds the ipv6 to the describe devices params +func (o *DescribeDevicesParams) SetIPV6(iPV6 *string) { + o.IPV6 = iPV6 +} + +// WithIsAll adds the isAll to the describe devices params +func (o *DescribeDevicesParams) WithIsAll(isAll *string) *DescribeDevicesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe devices params +func (o *DescribeDevicesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithManageStatus adds the manageStatus to the describe devices params +func (o *DescribeDevicesParams) WithManageStatus(manageStatus *string) *DescribeDevicesParams { + o.SetManageStatus(manageStatus) + return o +} + +// SetManageStatus adds the manageStatus to the describe devices params +func (o *DescribeDevicesParams) SetManageStatus(manageStatus *string) { + o.ManageStatus = manageStatus +} + +// WithPageNumber adds the pageNumber to the describe devices params +func (o *DescribeDevicesParams) WithPageNumber(pageNumber *int64) *DescribeDevicesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe devices params +func (o *DescribeDevicesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe devices params +func (o *DescribeDevicesParams) WithPageSize(pageSize *int64) *DescribeDevicesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe devices params +func (o *DescribeDevicesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithSn adds the sn to the describe devices params +func (o *DescribeDevicesParams) WithSn(sn *string) *DescribeDevicesParams { + o.SetSn(sn) + return o +} + +// SetSn adds the sn to the describe devices params +func (o *DescribeDevicesParams) SetSn(sn *string) { + o.Sn = sn +} + +// WithTraceID adds the traceID to the describe devices params +func (o *DescribeDevicesParams) WithTraceID(traceID string) *DescribeDevicesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe devices params +func (o *DescribeDevicesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserID adds the userID to the describe devices params +func (o *DescribeDevicesParams) WithUserID(userID *string) *DescribeDevicesParams { + o.SetUserID(userID) + return o +} + +// SetUserID adds the userId to the describe devices params +func (o *DescribeDevicesParams) SetUserID(userID *string) { + o.UserID = userID +} + +// WithUserName adds the userName to the describe devices params +func (o *DescribeDevicesParams) WithUserName(userName *string) *DescribeDevicesParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe devices params +func (o *DescribeDevicesParams) SetUserName(userName *string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDevicesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.CollectStatus != nil { + + // query param collectStatus + var qrCollectStatus string + + if o.CollectStatus != nil { + qrCollectStatus = *o.CollectStatus + } + qCollectStatus := qrCollectStatus + if qCollectStatus != "" { + + if err := r.SetQueryParam("collectStatus", qCollectStatus); err != nil { + return err + } + } + } + + if o.DeviceSeries != nil { + + // query param deviceSeries + var qrDeviceSeries string + + if o.DeviceSeries != nil { + qrDeviceSeries = *o.DeviceSeries + } + qDeviceSeries := qrDeviceSeries + if qDeviceSeries != "" { + + if err := r.SetQueryParam("deviceSeries", qDeviceSeries); err != nil { + return err + } + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.IDcID != nil { + + // query param idcId + var qrIdcID string + + if o.IDcID != nil { + qrIdcID = *o.IDcID + } + qIdcID := qrIdcID + if qIdcID != "" { + + if err := r.SetQueryParam("idcId", qIdcID); err != nil { + return err + } + } + } + + if o.IloIP != nil { + + // query param iloIp + var qrIloIP string + + if o.IloIP != nil { + qrIloIP = *o.IloIP + } + qIloIP := qrIloIP + if qIloIP != "" { + + if err := r.SetQueryParam("iloIp", qIloIP); err != nil { + return err + } + } + } + + if o.InstanceID != nil { + + // query param instanceId + var qrInstanceID string + + if o.InstanceID != nil { + qrInstanceID = *o.InstanceID + } + qInstanceID := qrInstanceID + if qInstanceID != "" { + + if err := r.SetQueryParam("instanceId", qInstanceID); err != nil { + return err + } + } + } + + if o.InstanceName != nil { + + // query param instanceName + var qrInstanceName string + + if o.InstanceName != nil { + qrInstanceName = *o.InstanceName + } + qInstanceName := qrInstanceName + if qInstanceName != "" { + + if err := r.SetQueryParam("instanceName", qInstanceName); err != nil { + return err + } + } + } + + if o.IPV4 != nil { + + // query param ipv4 + var qrIPV4 string + + if o.IPV4 != nil { + qrIPV4 = *o.IPV4 + } + qIPV4 := qrIPV4 + if qIPV4 != "" { + + if err := r.SetQueryParam("ipv4", qIPV4); err != nil { + return err + } + } + } + + if o.IPV6 != nil { + + // query param ipv6 + var qrIPV6 string + + if o.IPV6 != nil { + qrIPV6 = *o.IPV6 + } + qIPV6 := qrIPV6 + if qIPV6 != "" { + + if err := r.SetQueryParam("ipv6", qIPV6); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.ManageStatus != nil { + + // query param manageStatus + var qrManageStatus string + + if o.ManageStatus != nil { + qrManageStatus = *o.ManageStatus + } + qManageStatus := qrManageStatus + if qManageStatus != "" { + + if err := r.SetQueryParam("manageStatus", qManageStatus); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.Sn != nil { + + // query param sn + var qrSn string + + if o.Sn != nil { + qrSn = *o.Sn + } + qSn := qrSn + if qSn != "" { + + if err := r.SetQueryParam("sn", qSn); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserID != nil { + + // query param userId + var qrUserID string + + if o.UserID != nil { + qrUserID = *o.UserID + } + qUserID := qrUserID + if qUserID != "" { + + if err := r.SetQueryParam("userId", qUserID); err != nil { + return err + } + } + } + + if o.UserName != nil { + + // query param userName + var qrUserName string + + if o.UserName != nil { + qrUserName = *o.UserName + } + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_devices_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_devices_responses.go new file mode 100644 index 0000000..0c42cca --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/describe_devices_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDevicesReader is a Reader for the DescribeDevices structure. +type DescribeDevicesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDevicesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDevicesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDevicesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDevicesOK creates a DescribeDevicesOK with default headers values +func NewDescribeDevicesOK() *DescribeDevicesOK { + return &DescribeDevicesOK{} +} + +/* DescribeDevicesOK describes a response with status code 200, with default header values. + +DescribeDevicesOK describe devices o k +*/ +type DescribeDevicesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDevicesOKBody +} + +// IsSuccess returns true when this describe devices o k response has a 2xx status code +func (o *DescribeDevicesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe devices o k response has a 3xx status code +func (o *DescribeDevicesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe devices o k response has a 4xx status code +func (o *DescribeDevicesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe devices o k response has a 5xx status code +func (o *DescribeDevicesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe devices o k response a status code equal to that given +func (o *DescribeDevicesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDevicesOK) Error() string { + return fmt.Sprintf("[GET /devices][%d] describeDevicesOK %+v", 200, o.Payload) +} + +func (o *DescribeDevicesOK) String() string { + return fmt.Sprintf("[GET /devices][%d] describeDevicesOK %+v", 200, o.Payload) +} + +func (o *DescribeDevicesOK) GetPayload() *DescribeDevicesOKBody { + return o.Payload +} + +func (o *DescribeDevicesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDevicesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDevicesDefault creates a DescribeDevicesDefault with default headers values +func NewDescribeDevicesDefault(code int) *DescribeDevicesDefault { + return &DescribeDevicesDefault{ + _statusCode: code, + } +} + +/* DescribeDevicesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDevicesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDevicesDefaultBody +} + +// Code gets the status code for the describe devices default response +func (o *DescribeDevicesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe devices default response has a 2xx status code +func (o *DescribeDevicesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe devices default response has a 3xx status code +func (o *DescribeDevicesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe devices default response has a 4xx status code +func (o *DescribeDevicesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe devices default response has a 5xx status code +func (o *DescribeDevicesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe devices default response a status code equal to that given +func (o *DescribeDevicesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDevicesDefault) Error() string { + return fmt.Sprintf("[GET /devices][%d] describeDevices default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDevicesDefault) String() string { + return fmt.Sprintf("[GET /devices][%d] describeDevices default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDevicesDefault) GetPayload() *DescribeDevicesDefaultBody { + return o.Payload +} + +func (o *DescribeDevicesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDevicesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDevicesDefaultBody describe devices default body +swagger:model DescribeDevicesDefaultBody +*/ +type DescribeDevicesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe devices default body +func (o *DescribeDevicesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDevicesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDevices default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDevicesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDevices default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevices default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevices default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe devices default body based on the context it is used +func (o *DescribeDevicesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDevicesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevices default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevices default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDevicesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDevicesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDevicesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDevicesOKBody describe devices o k body +swagger:model DescribeDevicesOKBody +*/ +type DescribeDevicesOKBody struct { + + // result + Result *models.DeviceList `json:"result,omitempty"` +} + +// Validate validates this describe devices o k body +func (o *DescribeDevicesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDevicesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevicesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevicesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe devices o k body based on the context it is used +func (o *DescribeDevicesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDevicesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevicesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevicesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDevicesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDevicesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDevicesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/device_associate_device_type_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/device_associate_device_type_parameters.go new file mode 100644 index 0000000..4cba2fb --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/device_associate_device_type_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewDeviceAssociateDeviceTypeParams creates a new DeviceAssociateDeviceTypeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeviceAssociateDeviceTypeParams() *DeviceAssociateDeviceTypeParams { + return &DeviceAssociateDeviceTypeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeviceAssociateDeviceTypeParamsWithTimeout creates a new DeviceAssociateDeviceTypeParams object +// with the ability to set a timeout on a request. +func NewDeviceAssociateDeviceTypeParamsWithTimeout(timeout time.Duration) *DeviceAssociateDeviceTypeParams { + return &DeviceAssociateDeviceTypeParams{ + timeout: timeout, + } +} + +// NewDeviceAssociateDeviceTypeParamsWithContext creates a new DeviceAssociateDeviceTypeParams object +// with the ability to set a context for a request. +func NewDeviceAssociateDeviceTypeParamsWithContext(ctx context.Context) *DeviceAssociateDeviceTypeParams { + return &DeviceAssociateDeviceTypeParams{ + Context: ctx, + } +} + +// NewDeviceAssociateDeviceTypeParamsWithHTTPClient creates a new DeviceAssociateDeviceTypeParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeviceAssociateDeviceTypeParamsWithHTTPClient(client *http.Client) *DeviceAssociateDeviceTypeParams { + return &DeviceAssociateDeviceTypeParams{ + HTTPClient: client, + } +} + +/* DeviceAssociateDeviceTypeParams contains all the parameters to send to the API endpoint + for the device associate device type operation. + + Typically these are written to a http.Request. +*/ +type DeviceAssociateDeviceTypeParams struct { + + // Body. + Body *models.DeviceAssociateDeviceTypeRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the device associate device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeviceAssociateDeviceTypeParams) WithDefaults() *DeviceAssociateDeviceTypeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the device associate device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeviceAssociateDeviceTypeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) WithTimeout(timeout time.Duration) *DeviceAssociateDeviceTypeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) WithContext(ctx context.Context) *DeviceAssociateDeviceTypeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) WithHTTPClient(client *http.Client) *DeviceAssociateDeviceTypeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) WithBody(body *models.DeviceAssociateDeviceTypeRequest) *DeviceAssociateDeviceTypeParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) SetBody(body *models.DeviceAssociateDeviceTypeRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) WithAuthorization(authorization string) *DeviceAssociateDeviceTypeParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) WithBmpLanguage(bmpLanguage *string) *DeviceAssociateDeviceTypeParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) WithBmpUserID(bmpUserID *string) *DeviceAssociateDeviceTypeParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) WithTraceID(traceID string) *DeviceAssociateDeviceTypeParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the device associate device type params +func (o *DeviceAssociateDeviceTypeParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeviceAssociateDeviceTypeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/device_associate_device_type_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/device_associate_device_type_responses.go new file mode 100644 index 0000000..e1f91e3 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/device_associate_device_type_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeviceAssociateDeviceTypeReader is a Reader for the DeviceAssociateDeviceType structure. +type DeviceAssociateDeviceTypeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeviceAssociateDeviceTypeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeviceAssociateDeviceTypeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeviceAssociateDeviceTypeDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeviceAssociateDeviceTypeOK creates a DeviceAssociateDeviceTypeOK with default headers values +func NewDeviceAssociateDeviceTypeOK() *DeviceAssociateDeviceTypeOK { + return &DeviceAssociateDeviceTypeOK{} +} + +/* DeviceAssociateDeviceTypeOK describes a response with status code 200, with default header values. + +A DeviceAssociateDeviceTypeResult is an response struct +*/ +type DeviceAssociateDeviceTypeOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeviceAssociateDeviceTypeOKBody +} + +// IsSuccess returns true when this device associate device type o k response has a 2xx status code +func (o *DeviceAssociateDeviceTypeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this device associate device type o k response has a 3xx status code +func (o *DeviceAssociateDeviceTypeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this device associate device type o k response has a 4xx status code +func (o *DeviceAssociateDeviceTypeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this device associate device type o k response has a 5xx status code +func (o *DeviceAssociateDeviceTypeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this device associate device type o k response a status code equal to that given +func (o *DeviceAssociateDeviceTypeOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeviceAssociateDeviceTypeOK) Error() string { + return fmt.Sprintf("[PUT /devices/deviceType/associate][%d] deviceAssociateDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DeviceAssociateDeviceTypeOK) String() string { + return fmt.Sprintf("[PUT /devices/deviceType/associate][%d] deviceAssociateDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DeviceAssociateDeviceTypeOK) GetPayload() *DeviceAssociateDeviceTypeOKBody { + return o.Payload +} + +func (o *DeviceAssociateDeviceTypeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeviceAssociateDeviceTypeOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeviceAssociateDeviceTypeDefault creates a DeviceAssociateDeviceTypeDefault with default headers values +func NewDeviceAssociateDeviceTypeDefault(code int) *DeviceAssociateDeviceTypeDefault { + return &DeviceAssociateDeviceTypeDefault{ + _statusCode: code, + } +} + +/* DeviceAssociateDeviceTypeDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeviceAssociateDeviceTypeDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeviceAssociateDeviceTypeDefaultBody +} + +// Code gets the status code for the device associate device type default response +func (o *DeviceAssociateDeviceTypeDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this device associate device type default response has a 2xx status code +func (o *DeviceAssociateDeviceTypeDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this device associate device type default response has a 3xx status code +func (o *DeviceAssociateDeviceTypeDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this device associate device type default response has a 4xx status code +func (o *DeviceAssociateDeviceTypeDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this device associate device type default response has a 5xx status code +func (o *DeviceAssociateDeviceTypeDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this device associate device type default response a status code equal to that given +func (o *DeviceAssociateDeviceTypeDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeviceAssociateDeviceTypeDefault) Error() string { + return fmt.Sprintf("[PUT /devices/deviceType/associate][%d] deviceAssociateDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DeviceAssociateDeviceTypeDefault) String() string { + return fmt.Sprintf("[PUT /devices/deviceType/associate][%d] deviceAssociateDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DeviceAssociateDeviceTypeDefault) GetPayload() *DeviceAssociateDeviceTypeDefaultBody { + return o.Payload +} + +func (o *DeviceAssociateDeviceTypeDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeviceAssociateDeviceTypeDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeviceAssociateDeviceTypeDefaultBody device associate device type default body +swagger:model DeviceAssociateDeviceTypeDefaultBody +*/ +type DeviceAssociateDeviceTypeDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this device associate device type default body +func (o *DeviceAssociateDeviceTypeDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeviceAssociateDeviceTypeDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deviceAssociateDeviceType default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeviceAssociateDeviceTypeDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deviceAssociateDeviceType default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceAssociateDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceAssociateDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this device associate device type default body based on the context it is used +func (o *DeviceAssociateDeviceTypeDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeviceAssociateDeviceTypeDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceAssociateDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceAssociateDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeviceAssociateDeviceTypeDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeviceAssociateDeviceTypeDefaultBody) UnmarshalBinary(b []byte) error { + var res DeviceAssociateDeviceTypeDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeviceAssociateDeviceTypeOKBody device associate device type o k body +swagger:model DeviceAssociateDeviceTypeOKBody +*/ +type DeviceAssociateDeviceTypeOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this device associate device type o k body +func (o *DeviceAssociateDeviceTypeOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeviceAssociateDeviceTypeOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceAssociateDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceAssociateDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this device associate device type o k body based on the context it is used +func (o *DeviceAssociateDeviceTypeOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeviceAssociateDeviceTypeOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceAssociateDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceAssociateDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeviceAssociateDeviceTypeOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeviceAssociateDeviceTypeOKBody) UnmarshalBinary(b []byte) error { + var res DeviceAssociateDeviceTypeOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/device_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/device_client.go new file mode 100644 index 0000000..f17d8b0 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/device_client.go @@ -0,0 +1,597 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new device API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for device API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + AssociateDeviceDisks(params *AssociateDeviceDisksParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AssociateDeviceDisksOK, error) + + CollectDeviceInfo(params *CollectDeviceInfoParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CollectDeviceInfoOK, error) + + CreateDevice(params *CreateDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateDeviceOK, error) + + DeleteDevice(params *DeleteDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteDeviceOK, error) + + DescribeDevice(params *DescribeDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceOK, error) + + DescribeDeviceDisks(params *DescribeDeviceDisksParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceDisksOK, error) + + DescribeDeviceStock(params *DescribeDeviceStockParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceStockOK, error) + + DescribeDevices(params *DescribeDevicesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDevicesOK, error) + + DeviceAssociateDeviceType(params *DeviceAssociateDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeviceAssociateDeviceTypeOK, error) + + GetAssociatedDisks(params *GetAssociatedDisksParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetAssociatedDisksOK, error) + + ModifyDevice(params *ModifyDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyDeviceOK, error) + + MountDevice(params *MountDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*MountDeviceOK, error) + + RemoveDevice(params *RemoveDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RemoveDeviceOK, error) + + UnMountDevice(params *UnMountDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UnMountDeviceOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + AssociateDeviceDisks AssociateDeviceDisks 设备关联磁盘 +*/ +func (a *Client) AssociateDeviceDisks(params *AssociateDeviceDisksParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AssociateDeviceDisksOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewAssociateDeviceDisksParams() + } + op := &runtime.ClientOperation{ + ID: "associateDeviceDisks", + Method: "PUT", + PathPattern: "/devices/disks/associateDisks", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &AssociateDeviceDisksReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*AssociateDeviceDisksOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*AssociateDeviceDisksDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + CollectDeviceInfo CollectDeviceInfo 采集设备信息 +*/ +func (a *Client) CollectDeviceInfo(params *CollectDeviceInfoParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CollectDeviceInfoOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCollectDeviceInfoParams() + } + op := &runtime.ClientOperation{ + ID: "collectDeviceInfo", + Method: "POST", + PathPattern: "/collect/collectDeviceInfo", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CollectDeviceInfoReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CollectDeviceInfoOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CollectDeviceInfoDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + CreateDevice CreateDevice 创建设备 +*/ +func (a *Client) CreateDevice(params *CreateDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateDeviceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateDeviceParams() + } + op := &runtime.ClientOperation{ + ID: "createDevice", + Method: "POST", + PathPattern: "/devices", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateDeviceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateDeviceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateDeviceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteDevice DeleteDevice 删除设备 +*/ +func (a *Client) DeleteDevice(params *DeleteDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteDeviceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteDeviceParams() + } + op := &runtime.ClientOperation{ + ID: "deleteDevice", + Method: "DELETE", + PathPattern: "/devices/{device_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteDeviceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteDeviceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteDeviceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDevice DescribeDevice 获取设备详情 +*/ +func (a *Client) DescribeDevice(params *DescribeDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceParams() + } + op := &runtime.ClientOperation{ + ID: "describeDevice", + Method: "GET", + PathPattern: "/devices/{device_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceDisks DescribeDeviceDisks 设备详情-磁盘 +*/ +func (a *Client) DescribeDeviceDisks(params *DescribeDeviceDisksParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceDisksOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceDisksParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceDisks", + Method: "GET", + PathPattern: "/devices/{device_id}/disksDetail", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceDisksReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceDisksOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceDisksDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceStock DescribeDeviceStock 获取指定机型的设备库存 +*/ +func (a *Client) DescribeDeviceStock(params *DescribeDeviceStockParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceStockOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceStockParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceStock", + Method: "DELETE", + PathPattern: "/devices/stock", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceStockReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceStockOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceStockDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDevices DescribeDevices 获取设备列表 +*/ +func (a *Client) DescribeDevices(params *DescribeDevicesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDevicesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDevicesParams() + } + op := &runtime.ClientOperation{ + ID: "describeDevices", + Method: "GET", + PathPattern: "/devices", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDevicesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDevicesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDevicesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeviceAssociateDeviceType AssociateDeviceType 设备绑定机型 +*/ +func (a *Client) DeviceAssociateDeviceType(params *DeviceAssociateDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeviceAssociateDeviceTypeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeviceAssociateDeviceTypeParams() + } + op := &runtime.ClientOperation{ + ID: "deviceAssociateDeviceType", + Method: "PUT", + PathPattern: "/devices/deviceType/associate", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeviceAssociateDeviceTypeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeviceAssociateDeviceTypeOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeviceAssociateDeviceTypeDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + GetAssociatedDisks GetAssociatedDisks 获取设备已关联的磁盘 +*/ +func (a *Client) GetAssociatedDisks(params *GetAssociatedDisksParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetAssociatedDisksOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetAssociatedDisksParams() + } + op := &runtime.ClientOperation{ + ID: "getAssociatedDisks", + Method: "GET", + PathPattern: "/devices/disks/describeAssociateDisks", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetAssociatedDisksReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetAssociatedDisksOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetAssociatedDisksDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyDevice ModifyDevice 修改设备信息 +*/ +func (a *Client) ModifyDevice(params *ModifyDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyDeviceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyDeviceParams() + } + op := &runtime.ClientOperation{ + ID: "modifyDevice", + Method: "PUT", + PathPattern: "/devices/{device_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyDeviceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyDeviceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyDeviceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + MountDevice MountDevice 设备上架 +*/ +func (a *Client) MountDevice(params *MountDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*MountDeviceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewMountDeviceParams() + } + op := &runtime.ClientOperation{ + ID: "mountDevice", + Method: "PUT", + PathPattern: "/devices/mount", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &MountDeviceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*MountDeviceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*MountDeviceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + RemoveDevice DeleteDevice 移除设备 +*/ +func (a *Client) RemoveDevice(params *RemoveDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RemoveDeviceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewRemoveDeviceParams() + } + op := &runtime.ClientOperation{ + ID: "removeDevice", + Method: "PUT", + PathPattern: "/devices/{device_id}/remove", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &RemoveDeviceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*RemoveDeviceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*RemoveDeviceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + UnMountDevice UnMountDevice 设备下架 +*/ +func (a *Client) UnMountDevice(params *UnMountDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UnMountDeviceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewUnMountDeviceParams() + } + op := &runtime.ClientOperation{ + ID: "unMountDevice", + Method: "PUT", + PathPattern: "/devices/unmount", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UnMountDeviceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*UnMountDeviceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*UnMountDeviceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/get_associated_disks_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/get_associated_disks_parameters.go new file mode 100644 index 0000000..d1190a6 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/get_associated_disks_parameters.go @@ -0,0 +1,302 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetAssociatedDisksParams creates a new GetAssociatedDisksParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetAssociatedDisksParams() *GetAssociatedDisksParams { + return &GetAssociatedDisksParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetAssociatedDisksParamsWithTimeout creates a new GetAssociatedDisksParams object +// with the ability to set a timeout on a request. +func NewGetAssociatedDisksParamsWithTimeout(timeout time.Duration) *GetAssociatedDisksParams { + return &GetAssociatedDisksParams{ + timeout: timeout, + } +} + +// NewGetAssociatedDisksParamsWithContext creates a new GetAssociatedDisksParams object +// with the ability to set a context for a request. +func NewGetAssociatedDisksParamsWithContext(ctx context.Context) *GetAssociatedDisksParams { + return &GetAssociatedDisksParams{ + Context: ctx, + } +} + +// NewGetAssociatedDisksParamsWithHTTPClient creates a new GetAssociatedDisksParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetAssociatedDisksParamsWithHTTPClient(client *http.Client) *GetAssociatedDisksParams { + return &GetAssociatedDisksParams{ + HTTPClient: client, + } +} + +/* GetAssociatedDisksParams contains all the parameters to send to the API endpoint + for the get associated disks operation. + + Typically these are written to a http.Request. +*/ +type GetAssociatedDisksParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceID. + + device uuid + */ + DeviceID string + + /* DeviceTypeID. + + devicetype uuid + */ + DeviceTypeID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* VolumeID. + + volume uuid + */ + VolumeID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get associated disks params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetAssociatedDisksParams) WithDefaults() *GetAssociatedDisksParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get associated disks params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetAssociatedDisksParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get associated disks params +func (o *GetAssociatedDisksParams) WithTimeout(timeout time.Duration) *GetAssociatedDisksParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get associated disks params +func (o *GetAssociatedDisksParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get associated disks params +func (o *GetAssociatedDisksParams) WithContext(ctx context.Context) *GetAssociatedDisksParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get associated disks params +func (o *GetAssociatedDisksParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get associated disks params +func (o *GetAssociatedDisksParams) WithHTTPClient(client *http.Client) *GetAssociatedDisksParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get associated disks params +func (o *GetAssociatedDisksParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the get associated disks params +func (o *GetAssociatedDisksParams) WithAuthorization(authorization string) *GetAssociatedDisksParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the get associated disks params +func (o *GetAssociatedDisksParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the get associated disks params +func (o *GetAssociatedDisksParams) WithBmpLanguage(bmpLanguage *string) *GetAssociatedDisksParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the get associated disks params +func (o *GetAssociatedDisksParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the get associated disks params +func (o *GetAssociatedDisksParams) WithBmpUserID(bmpUserID *string) *GetAssociatedDisksParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the get associated disks params +func (o *GetAssociatedDisksParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceID adds the deviceID to the get associated disks params +func (o *GetAssociatedDisksParams) WithDeviceID(deviceID string) *GetAssociatedDisksParams { + o.SetDeviceID(deviceID) + return o +} + +// SetDeviceID adds the deviceId to the get associated disks params +func (o *GetAssociatedDisksParams) SetDeviceID(deviceID string) { + o.DeviceID = deviceID +} + +// WithDeviceTypeID adds the deviceTypeID to the get associated disks params +func (o *GetAssociatedDisksParams) WithDeviceTypeID(deviceTypeID string) *GetAssociatedDisksParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the get associated disks params +func (o *GetAssociatedDisksParams) SetDeviceTypeID(deviceTypeID string) { + o.DeviceTypeID = deviceTypeID +} + +// WithTraceID adds the traceID to the get associated disks params +func (o *GetAssociatedDisksParams) WithTraceID(traceID string) *GetAssociatedDisksParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the get associated disks params +func (o *GetAssociatedDisksParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithVolumeID adds the volumeID to the get associated disks params +func (o *GetAssociatedDisksParams) WithVolumeID(volumeID string) *GetAssociatedDisksParams { + o.SetVolumeID(volumeID) + return o +} + +// SetVolumeID adds the volumeId to the get associated disks params +func (o *GetAssociatedDisksParams) SetVolumeID(volumeID string) { + o.VolumeID = volumeID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetAssociatedDisksParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // query param deviceId + qrDeviceID := o.DeviceID + qDeviceID := qrDeviceID + if qDeviceID != "" { + + if err := r.SetQueryParam("deviceId", qDeviceID); err != nil { + return err + } + } + + // query param deviceTypeId + qrDeviceTypeID := o.DeviceTypeID + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + // query param volumeId + qrVolumeID := o.VolumeID + qVolumeID := qrVolumeID + if qVolumeID != "" { + + if err := r.SetQueryParam("volumeId", qVolumeID); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/get_associated_disks_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/get_associated_disks_responses.go new file mode 100644 index 0000000..85f6c26 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/get_associated_disks_responses.go @@ -0,0 +1,415 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// GetAssociatedDisksReader is a Reader for the GetAssociatedDisks structure. +type GetAssociatedDisksReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetAssociatedDisksReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetAssociatedDisksOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetAssociatedDisksDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetAssociatedDisksOK creates a GetAssociatedDisksOK with default headers values +func NewGetAssociatedDisksOK() *GetAssociatedDisksOK { + return &GetAssociatedDisksOK{} +} + +/* GetAssociatedDisksOK describes a response with status code 200, with default header values. + +A GetAssociatedDisksResult is an response struct that is used to get instance list by sshkey. +*/ +type GetAssociatedDisksOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetAssociatedDisksOKBody +} + +// IsSuccess returns true when this get associated disks o k response has a 2xx status code +func (o *GetAssociatedDisksOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get associated disks o k response has a 3xx status code +func (o *GetAssociatedDisksOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get associated disks o k response has a 4xx status code +func (o *GetAssociatedDisksOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get associated disks o k response has a 5xx status code +func (o *GetAssociatedDisksOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get associated disks o k response a status code equal to that given +func (o *GetAssociatedDisksOK) IsCode(code int) bool { + return code == 200 +} + +func (o *GetAssociatedDisksOK) Error() string { + return fmt.Sprintf("[GET /devices/disks/describeAssociateDisks][%d] getAssociatedDisksOK %+v", 200, o.Payload) +} + +func (o *GetAssociatedDisksOK) String() string { + return fmt.Sprintf("[GET /devices/disks/describeAssociateDisks][%d] getAssociatedDisksOK %+v", 200, o.Payload) +} + +func (o *GetAssociatedDisksOK) GetPayload() *GetAssociatedDisksOKBody { + return o.Payload +} + +func (o *GetAssociatedDisksOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetAssociatedDisksOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetAssociatedDisksDefault creates a GetAssociatedDisksDefault with default headers values +func NewGetAssociatedDisksDefault(code int) *GetAssociatedDisksDefault { + return &GetAssociatedDisksDefault{ + _statusCode: code, + } +} + +/* GetAssociatedDisksDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type GetAssociatedDisksDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetAssociatedDisksDefaultBody +} + +// Code gets the status code for the get associated disks default response +func (o *GetAssociatedDisksDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this get associated disks default response has a 2xx status code +func (o *GetAssociatedDisksDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get associated disks default response has a 3xx status code +func (o *GetAssociatedDisksDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get associated disks default response has a 4xx status code +func (o *GetAssociatedDisksDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get associated disks default response has a 5xx status code +func (o *GetAssociatedDisksDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get associated disks default response a status code equal to that given +func (o *GetAssociatedDisksDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *GetAssociatedDisksDefault) Error() string { + return fmt.Sprintf("[GET /devices/disks/describeAssociateDisks][%d] getAssociatedDisks default %+v", o._statusCode, o.Payload) +} + +func (o *GetAssociatedDisksDefault) String() string { + return fmt.Sprintf("[GET /devices/disks/describeAssociateDisks][%d] getAssociatedDisks default %+v", o._statusCode, o.Payload) +} + +func (o *GetAssociatedDisksDefault) GetPayload() *GetAssociatedDisksDefaultBody { + return o.Payload +} + +func (o *GetAssociatedDisksDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetAssociatedDisksDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*GetAssociatedDisksDefaultBody get associated disks default body +swagger:model GetAssociatedDisksDefaultBody +*/ +type GetAssociatedDisksDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this get associated disks default body +func (o *GetAssociatedDisksDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetAssociatedDisksDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("getAssociatedDisks default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *GetAssociatedDisksDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("getAssociatedDisks default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getAssociatedDisks default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getAssociatedDisks default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get associated disks default body based on the context it is used +func (o *GetAssociatedDisksDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetAssociatedDisksDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getAssociatedDisks default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getAssociatedDisks default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetAssociatedDisksDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetAssociatedDisksDefaultBody) UnmarshalBinary(b []byte) error { + var res GetAssociatedDisksDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*GetAssociatedDisksOKBody get associated disks o k body +swagger:model GetAssociatedDisksOKBody +*/ +type GetAssociatedDisksOKBody struct { + + // result + Result []*models.Disk `json:"result"` +} + +// Validate validates this get associated disks o k body +func (o *GetAssociatedDisksOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetAssociatedDisksOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + for i := 0; i < len(o.Result); i++ { + if swag.IsZero(o.Result[i]) { // not required + continue + } + + if o.Result[i] != nil { + if err := o.Result[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getAssociatedDisksOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getAssociatedDisksOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get associated disks o k body based on the context it is used +func (o *GetAssociatedDisksOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetAssociatedDisksOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Result); i++ { + + if o.Result[i] != nil { + if err := o.Result[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getAssociatedDisksOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getAssociatedDisksOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetAssociatedDisksOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetAssociatedDisksOKBody) UnmarshalBinary(b []byte) error { + var res GetAssociatedDisksOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/modify_device_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/modify_device_parameters.go new file mode 100644 index 0000000..c169994 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/modify_device_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyDeviceParams creates a new ModifyDeviceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyDeviceParams() *ModifyDeviceParams { + return &ModifyDeviceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyDeviceParamsWithTimeout creates a new ModifyDeviceParams object +// with the ability to set a timeout on a request. +func NewModifyDeviceParamsWithTimeout(timeout time.Duration) *ModifyDeviceParams { + return &ModifyDeviceParams{ + timeout: timeout, + } +} + +// NewModifyDeviceParamsWithContext creates a new ModifyDeviceParams object +// with the ability to set a context for a request. +func NewModifyDeviceParamsWithContext(ctx context.Context) *ModifyDeviceParams { + return &ModifyDeviceParams{ + Context: ctx, + } +} + +// NewModifyDeviceParamsWithHTTPClient creates a new ModifyDeviceParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyDeviceParamsWithHTTPClient(client *http.Client) *ModifyDeviceParams { + return &ModifyDeviceParams{ + HTTPClient: client, + } +} + +/* ModifyDeviceParams contains all the parameters to send to the API endpoint + for the modify device operation. + + Typically these are written to a http.Request. +*/ +type ModifyDeviceParams struct { + + // Body. + Body *models.ModifyDevicesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // DeviceID. + DeviceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyDeviceParams) WithDefaults() *ModifyDeviceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyDeviceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify device params +func (o *ModifyDeviceParams) WithTimeout(timeout time.Duration) *ModifyDeviceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify device params +func (o *ModifyDeviceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify device params +func (o *ModifyDeviceParams) WithContext(ctx context.Context) *ModifyDeviceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify device params +func (o *ModifyDeviceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify device params +func (o *ModifyDeviceParams) WithHTTPClient(client *http.Client) *ModifyDeviceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify device params +func (o *ModifyDeviceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify device params +func (o *ModifyDeviceParams) WithBody(body *models.ModifyDevicesRequest) *ModifyDeviceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify device params +func (o *ModifyDeviceParams) SetBody(body *models.ModifyDevicesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify device params +func (o *ModifyDeviceParams) WithAuthorization(authorization string) *ModifyDeviceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify device params +func (o *ModifyDeviceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify device params +func (o *ModifyDeviceParams) WithBmpLanguage(bmpLanguage *string) *ModifyDeviceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify device params +func (o *ModifyDeviceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify device params +func (o *ModifyDeviceParams) WithBmpUserID(bmpUserID *string) *ModifyDeviceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify device params +func (o *ModifyDeviceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceID adds the deviceID to the modify device params +func (o *ModifyDeviceParams) WithDeviceID(deviceID string) *ModifyDeviceParams { + o.SetDeviceID(deviceID) + return o +} + +// SetDeviceID adds the deviceId to the modify device params +func (o *ModifyDeviceParams) SetDeviceID(deviceID string) { + o.DeviceID = deviceID +} + +// WithTraceID adds the traceID to the modify device params +func (o *ModifyDeviceParams) WithTraceID(traceID string) *ModifyDeviceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify device params +func (o *ModifyDeviceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_id + if err := r.SetPathParam("device_id", o.DeviceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/modify_device_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/modify_device_responses.go new file mode 100644 index 0000000..7225eed --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/modify_device_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyDeviceReader is a Reader for the ModifyDevice structure. +type ModifyDeviceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyDeviceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyDeviceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyDeviceOK creates a ModifyDeviceOK with default headers values +func NewModifyDeviceOK() *ModifyDeviceOK { + return &ModifyDeviceOK{} +} + +/* ModifyDeviceOK describes a response with status code 200, with default header values. + +A ModifyDeviceResult is an response struct that is used to describe modify device result. +*/ +type ModifyDeviceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyDeviceOKBody +} + +// IsSuccess returns true when this modify device o k response has a 2xx status code +func (o *ModifyDeviceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify device o k response has a 3xx status code +func (o *ModifyDeviceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify device o k response has a 4xx status code +func (o *ModifyDeviceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify device o k response has a 5xx status code +func (o *ModifyDeviceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify device o k response a status code equal to that given +func (o *ModifyDeviceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyDeviceOK) Error() string { + return fmt.Sprintf("[PUT /devices/{device_id}][%d] modifyDeviceOK %+v", 200, o.Payload) +} + +func (o *ModifyDeviceOK) String() string { + return fmt.Sprintf("[PUT /devices/{device_id}][%d] modifyDeviceOK %+v", 200, o.Payload) +} + +func (o *ModifyDeviceOK) GetPayload() *ModifyDeviceOKBody { + return o.Payload +} + +func (o *ModifyDeviceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyDeviceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyDeviceDefault creates a ModifyDeviceDefault with default headers values +func NewModifyDeviceDefault(code int) *ModifyDeviceDefault { + return &ModifyDeviceDefault{ + _statusCode: code, + } +} + +/* ModifyDeviceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyDeviceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyDeviceDefaultBody +} + +// Code gets the status code for the modify device default response +func (o *ModifyDeviceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify device default response has a 2xx status code +func (o *ModifyDeviceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify device default response has a 3xx status code +func (o *ModifyDeviceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify device default response has a 4xx status code +func (o *ModifyDeviceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify device default response has a 5xx status code +func (o *ModifyDeviceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify device default response a status code equal to that given +func (o *ModifyDeviceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyDeviceDefault) Error() string { + return fmt.Sprintf("[PUT /devices/{device_id}][%d] modifyDevice default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyDeviceDefault) String() string { + return fmt.Sprintf("[PUT /devices/{device_id}][%d] modifyDevice default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyDeviceDefault) GetPayload() *ModifyDeviceDefaultBody { + return o.Payload +} + +func (o *ModifyDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyDeviceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyDeviceDefaultBody modify device default body +swagger:model ModifyDeviceDefaultBody +*/ +type ModifyDeviceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify device default body +func (o *ModifyDeviceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyDevice default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyDeviceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyDevice default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify device default body based on the context it is used +func (o *ModifyDeviceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyDeviceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyDeviceDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyDeviceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyDeviceOKBody modify device o k body +swagger:model ModifyDeviceOKBody +*/ +type ModifyDeviceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify device o k body +func (o *ModifyDeviceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify device o k body based on the context it is used +func (o *ModifyDeviceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyDeviceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyDeviceOKBody) UnmarshalBinary(b []byte) error { + var res ModifyDeviceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/mount_device_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/mount_device_parameters.go new file mode 100644 index 0000000..dbe2352 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/mount_device_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewMountDeviceParams creates a new MountDeviceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewMountDeviceParams() *MountDeviceParams { + return &MountDeviceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewMountDeviceParamsWithTimeout creates a new MountDeviceParams object +// with the ability to set a timeout on a request. +func NewMountDeviceParamsWithTimeout(timeout time.Duration) *MountDeviceParams { + return &MountDeviceParams{ + timeout: timeout, + } +} + +// NewMountDeviceParamsWithContext creates a new MountDeviceParams object +// with the ability to set a context for a request. +func NewMountDeviceParamsWithContext(ctx context.Context) *MountDeviceParams { + return &MountDeviceParams{ + Context: ctx, + } +} + +// NewMountDeviceParamsWithHTTPClient creates a new MountDeviceParams object +// with the ability to set a custom HTTPClient for a request. +func NewMountDeviceParamsWithHTTPClient(client *http.Client) *MountDeviceParams { + return &MountDeviceParams{ + HTTPClient: client, + } +} + +/* MountDeviceParams contains all the parameters to send to the API endpoint + for the mount device operation. + + Typically these are written to a http.Request. +*/ +type MountDeviceParams struct { + + // Body. + Body *models.MountDevicesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the mount device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *MountDeviceParams) WithDefaults() *MountDeviceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the mount device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *MountDeviceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the mount device params +func (o *MountDeviceParams) WithTimeout(timeout time.Duration) *MountDeviceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the mount device params +func (o *MountDeviceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the mount device params +func (o *MountDeviceParams) WithContext(ctx context.Context) *MountDeviceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the mount device params +func (o *MountDeviceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the mount device params +func (o *MountDeviceParams) WithHTTPClient(client *http.Client) *MountDeviceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the mount device params +func (o *MountDeviceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the mount device params +func (o *MountDeviceParams) WithBody(body *models.MountDevicesRequest) *MountDeviceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the mount device params +func (o *MountDeviceParams) SetBody(body *models.MountDevicesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the mount device params +func (o *MountDeviceParams) WithAuthorization(authorization string) *MountDeviceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the mount device params +func (o *MountDeviceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the mount device params +func (o *MountDeviceParams) WithBmpLanguage(bmpLanguage *string) *MountDeviceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the mount device params +func (o *MountDeviceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the mount device params +func (o *MountDeviceParams) WithBmpUserID(bmpUserID *string) *MountDeviceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the mount device params +func (o *MountDeviceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the mount device params +func (o *MountDeviceParams) WithTraceID(traceID string) *MountDeviceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the mount device params +func (o *MountDeviceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *MountDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/mount_device_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/mount_device_responses.go new file mode 100644 index 0000000..53ce48a --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/mount_device_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// MountDeviceReader is a Reader for the MountDevice structure. +type MountDeviceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *MountDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewMountDeviceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewMountDeviceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewMountDeviceOK creates a MountDeviceOK with default headers values +func NewMountDeviceOK() *MountDeviceOK { + return &MountDeviceOK{} +} + +/* MountDeviceOK describes a response with status code 200, with default header values. + +A MountDeviceResult is an response struct that is used to describe mount device result. +*/ +type MountDeviceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *MountDeviceOKBody +} + +// IsSuccess returns true when this mount device o k response has a 2xx status code +func (o *MountDeviceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this mount device o k response has a 3xx status code +func (o *MountDeviceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this mount device o k response has a 4xx status code +func (o *MountDeviceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this mount device o k response has a 5xx status code +func (o *MountDeviceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this mount device o k response a status code equal to that given +func (o *MountDeviceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *MountDeviceOK) Error() string { + return fmt.Sprintf("[PUT /devices/mount][%d] mountDeviceOK %+v", 200, o.Payload) +} + +func (o *MountDeviceOK) String() string { + return fmt.Sprintf("[PUT /devices/mount][%d] mountDeviceOK %+v", 200, o.Payload) +} + +func (o *MountDeviceOK) GetPayload() *MountDeviceOKBody { + return o.Payload +} + +func (o *MountDeviceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(MountDeviceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewMountDeviceDefault creates a MountDeviceDefault with default headers values +func NewMountDeviceDefault(code int) *MountDeviceDefault { + return &MountDeviceDefault{ + _statusCode: code, + } +} + +/* MountDeviceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type MountDeviceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *MountDeviceDefaultBody +} + +// Code gets the status code for the mount device default response +func (o *MountDeviceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this mount device default response has a 2xx status code +func (o *MountDeviceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this mount device default response has a 3xx status code +func (o *MountDeviceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this mount device default response has a 4xx status code +func (o *MountDeviceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this mount device default response has a 5xx status code +func (o *MountDeviceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this mount device default response a status code equal to that given +func (o *MountDeviceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *MountDeviceDefault) Error() string { + return fmt.Sprintf("[PUT /devices/mount][%d] mountDevice default %+v", o._statusCode, o.Payload) +} + +func (o *MountDeviceDefault) String() string { + return fmt.Sprintf("[PUT /devices/mount][%d] mountDevice default %+v", o._statusCode, o.Payload) +} + +func (o *MountDeviceDefault) GetPayload() *MountDeviceDefaultBody { + return o.Payload +} + +func (o *MountDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(MountDeviceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*MountDeviceDefaultBody mount device default body +swagger:model MountDeviceDefaultBody +*/ +type MountDeviceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this mount device default body +func (o *MountDeviceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MountDeviceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("mountDevice default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *MountDeviceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("mountDevice default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("mountDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("mountDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this mount device default body based on the context it is used +func (o *MountDeviceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MountDeviceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("mountDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("mountDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *MountDeviceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *MountDeviceDefaultBody) UnmarshalBinary(b []byte) error { + var res MountDeviceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*MountDeviceOKBody mount device o k body +swagger:model MountDeviceOKBody +*/ +type MountDeviceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this mount device o k body +func (o *MountDeviceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MountDeviceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("mountDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("mountDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this mount device o k body based on the context it is used +func (o *MountDeviceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MountDeviceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("mountDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("mountDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *MountDeviceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *MountDeviceOKBody) UnmarshalBinary(b []byte) error { + var res MountDeviceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/remove_device_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/remove_device_parameters.go new file mode 100644 index 0000000..740ce5a --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/remove_device_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewRemoveDeviceParams creates a new RemoveDeviceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewRemoveDeviceParams() *RemoveDeviceParams { + return &RemoveDeviceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewRemoveDeviceParamsWithTimeout creates a new RemoveDeviceParams object +// with the ability to set a timeout on a request. +func NewRemoveDeviceParamsWithTimeout(timeout time.Duration) *RemoveDeviceParams { + return &RemoveDeviceParams{ + timeout: timeout, + } +} + +// NewRemoveDeviceParamsWithContext creates a new RemoveDeviceParams object +// with the ability to set a context for a request. +func NewRemoveDeviceParamsWithContext(ctx context.Context) *RemoveDeviceParams { + return &RemoveDeviceParams{ + Context: ctx, + } +} + +// NewRemoveDeviceParamsWithHTTPClient creates a new RemoveDeviceParams object +// with the ability to set a custom HTTPClient for a request. +func NewRemoveDeviceParamsWithHTTPClient(client *http.Client) *RemoveDeviceParams { + return &RemoveDeviceParams{ + HTTPClient: client, + } +} + +/* RemoveDeviceParams contains all the parameters to send to the API endpoint + for the remove device operation. + + Typically these are written to a http.Request. +*/ +type RemoveDeviceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // DeviceID. + DeviceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the remove device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RemoveDeviceParams) WithDefaults() *RemoveDeviceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the remove device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RemoveDeviceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the remove device params +func (o *RemoveDeviceParams) WithTimeout(timeout time.Duration) *RemoveDeviceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the remove device params +func (o *RemoveDeviceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the remove device params +func (o *RemoveDeviceParams) WithContext(ctx context.Context) *RemoveDeviceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the remove device params +func (o *RemoveDeviceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the remove device params +func (o *RemoveDeviceParams) WithHTTPClient(client *http.Client) *RemoveDeviceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the remove device params +func (o *RemoveDeviceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the remove device params +func (o *RemoveDeviceParams) WithAuthorization(authorization string) *RemoveDeviceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the remove device params +func (o *RemoveDeviceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the remove device params +func (o *RemoveDeviceParams) WithBmpLanguage(bmpLanguage *string) *RemoveDeviceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the remove device params +func (o *RemoveDeviceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the remove device params +func (o *RemoveDeviceParams) WithBmpUserID(bmpUserID *string) *RemoveDeviceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the remove device params +func (o *RemoveDeviceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceID adds the deviceID to the remove device params +func (o *RemoveDeviceParams) WithDeviceID(deviceID string) *RemoveDeviceParams { + o.SetDeviceID(deviceID) + return o +} + +// SetDeviceID adds the deviceId to the remove device params +func (o *RemoveDeviceParams) SetDeviceID(deviceID string) { + o.DeviceID = deviceID +} + +// WithTraceID adds the traceID to the remove device params +func (o *RemoveDeviceParams) WithTraceID(traceID string) *RemoveDeviceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the remove device params +func (o *RemoveDeviceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *RemoveDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_id + if err := r.SetPathParam("device_id", o.DeviceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/remove_device_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/remove_device_responses.go new file mode 100644 index 0000000..7cd1b42 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/remove_device_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// RemoveDeviceReader is a Reader for the RemoveDevice structure. +type RemoveDeviceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *RemoveDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewRemoveDeviceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewRemoveDeviceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewRemoveDeviceOK creates a RemoveDeviceOK with default headers values +func NewRemoveDeviceOK() *RemoveDeviceOK { + return &RemoveDeviceOK{} +} + +/* RemoveDeviceOK describes a response with status code 200, with default header values. + +A RemoveDeviceResult is an response struct that is used to describe restart instance result. +*/ +type RemoveDeviceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *RemoveDeviceOKBody +} + +// IsSuccess returns true when this remove device o k response has a 2xx status code +func (o *RemoveDeviceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this remove device o k response has a 3xx status code +func (o *RemoveDeviceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this remove device o k response has a 4xx status code +func (o *RemoveDeviceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this remove device o k response has a 5xx status code +func (o *RemoveDeviceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this remove device o k response a status code equal to that given +func (o *RemoveDeviceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *RemoveDeviceOK) Error() string { + return fmt.Sprintf("[PUT /devices/{device_id}/remove][%d] removeDeviceOK %+v", 200, o.Payload) +} + +func (o *RemoveDeviceOK) String() string { + return fmt.Sprintf("[PUT /devices/{device_id}/remove][%d] removeDeviceOK %+v", 200, o.Payload) +} + +func (o *RemoveDeviceOK) GetPayload() *RemoveDeviceOKBody { + return o.Payload +} + +func (o *RemoveDeviceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RemoveDeviceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewRemoveDeviceDefault creates a RemoveDeviceDefault with default headers values +func NewRemoveDeviceDefault(code int) *RemoveDeviceDefault { + return &RemoveDeviceDefault{ + _statusCode: code, + } +} + +/* RemoveDeviceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type RemoveDeviceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *RemoveDeviceDefaultBody +} + +// Code gets the status code for the remove device default response +func (o *RemoveDeviceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this remove device default response has a 2xx status code +func (o *RemoveDeviceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this remove device default response has a 3xx status code +func (o *RemoveDeviceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this remove device default response has a 4xx status code +func (o *RemoveDeviceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this remove device default response has a 5xx status code +func (o *RemoveDeviceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this remove device default response a status code equal to that given +func (o *RemoveDeviceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *RemoveDeviceDefault) Error() string { + return fmt.Sprintf("[PUT /devices/{device_id}/remove][%d] removeDevice default %+v", o._statusCode, o.Payload) +} + +func (o *RemoveDeviceDefault) String() string { + return fmt.Sprintf("[PUT /devices/{device_id}/remove][%d] removeDevice default %+v", o._statusCode, o.Payload) +} + +func (o *RemoveDeviceDefault) GetPayload() *RemoveDeviceDefaultBody { + return o.Payload +} + +func (o *RemoveDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RemoveDeviceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*RemoveDeviceDefaultBody remove device default body +swagger:model RemoveDeviceDefaultBody +*/ +type RemoveDeviceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this remove device default body +func (o *RemoveDeviceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RemoveDeviceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("removeDevice default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *RemoveDeviceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("removeDevice default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("removeDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("removeDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this remove device default body based on the context it is used +func (o *RemoveDeviceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RemoveDeviceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("removeDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("removeDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RemoveDeviceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RemoveDeviceDefaultBody) UnmarshalBinary(b []byte) error { + var res RemoveDeviceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*RemoveDeviceOKBody remove device o k body +swagger:model RemoveDeviceOKBody +*/ +type RemoveDeviceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this remove device o k body +func (o *RemoveDeviceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RemoveDeviceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("removeDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("removeDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this remove device o k body based on the context it is used +func (o *RemoveDeviceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RemoveDeviceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("removeDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("removeDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RemoveDeviceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RemoveDeviceOKBody) UnmarshalBinary(b []byte) error { + var res RemoveDeviceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/un_mount_device_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/un_mount_device_parameters.go new file mode 100644 index 0000000..05e0aa5 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/un_mount_device_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewUnMountDeviceParams creates a new UnMountDeviceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewUnMountDeviceParams() *UnMountDeviceParams { + return &UnMountDeviceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUnMountDeviceParamsWithTimeout creates a new UnMountDeviceParams object +// with the ability to set a timeout on a request. +func NewUnMountDeviceParamsWithTimeout(timeout time.Duration) *UnMountDeviceParams { + return &UnMountDeviceParams{ + timeout: timeout, + } +} + +// NewUnMountDeviceParamsWithContext creates a new UnMountDeviceParams object +// with the ability to set a context for a request. +func NewUnMountDeviceParamsWithContext(ctx context.Context) *UnMountDeviceParams { + return &UnMountDeviceParams{ + Context: ctx, + } +} + +// NewUnMountDeviceParamsWithHTTPClient creates a new UnMountDeviceParams object +// with the ability to set a custom HTTPClient for a request. +func NewUnMountDeviceParamsWithHTTPClient(client *http.Client) *UnMountDeviceParams { + return &UnMountDeviceParams{ + HTTPClient: client, + } +} + +/* UnMountDeviceParams contains all the parameters to send to the API endpoint + for the un mount device operation. + + Typically these are written to a http.Request. +*/ +type UnMountDeviceParams struct { + + // Body. + Body *models.UnMountDevicesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the un mount device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UnMountDeviceParams) WithDefaults() *UnMountDeviceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the un mount device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UnMountDeviceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the un mount device params +func (o *UnMountDeviceParams) WithTimeout(timeout time.Duration) *UnMountDeviceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the un mount device params +func (o *UnMountDeviceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the un mount device params +func (o *UnMountDeviceParams) WithContext(ctx context.Context) *UnMountDeviceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the un mount device params +func (o *UnMountDeviceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the un mount device params +func (o *UnMountDeviceParams) WithHTTPClient(client *http.Client) *UnMountDeviceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the un mount device params +func (o *UnMountDeviceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the un mount device params +func (o *UnMountDeviceParams) WithBody(body *models.UnMountDevicesRequest) *UnMountDeviceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the un mount device params +func (o *UnMountDeviceParams) SetBody(body *models.UnMountDevicesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the un mount device params +func (o *UnMountDeviceParams) WithAuthorization(authorization string) *UnMountDeviceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the un mount device params +func (o *UnMountDeviceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the un mount device params +func (o *UnMountDeviceParams) WithBmpLanguage(bmpLanguage *string) *UnMountDeviceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the un mount device params +func (o *UnMountDeviceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the un mount device params +func (o *UnMountDeviceParams) WithBmpUserID(bmpUserID *string) *UnMountDeviceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the un mount device params +func (o *UnMountDeviceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the un mount device params +func (o *UnMountDeviceParams) WithTraceID(traceID string) *UnMountDeviceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the un mount device params +func (o *UnMountDeviceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *UnMountDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/un_mount_device_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/un_mount_device_responses.go new file mode 100644 index 0000000..cd725bd --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device/un_mount_device_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// UnMountDeviceReader is a Reader for the UnMountDevice structure. +type UnMountDeviceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UnMountDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUnMountDeviceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewUnMountDeviceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewUnMountDeviceOK creates a UnMountDeviceOK with default headers values +func NewUnMountDeviceOK() *UnMountDeviceOK { + return &UnMountDeviceOK{} +} + +/* UnMountDeviceOK describes a response with status code 200, with default header values. + +A UnMountDeviceResult is an response struct that is used to unmount device. +*/ +type UnMountDeviceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *UnMountDeviceOKBody +} + +// IsSuccess returns true when this un mount device o k response has a 2xx status code +func (o *UnMountDeviceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this un mount device o k response has a 3xx status code +func (o *UnMountDeviceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this un mount device o k response has a 4xx status code +func (o *UnMountDeviceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this un mount device o k response has a 5xx status code +func (o *UnMountDeviceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this un mount device o k response a status code equal to that given +func (o *UnMountDeviceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *UnMountDeviceOK) Error() string { + return fmt.Sprintf("[PUT /devices/unmount][%d] unMountDeviceOK %+v", 200, o.Payload) +} + +func (o *UnMountDeviceOK) String() string { + return fmt.Sprintf("[PUT /devices/unmount][%d] unMountDeviceOK %+v", 200, o.Payload) +} + +func (o *UnMountDeviceOK) GetPayload() *UnMountDeviceOKBody { + return o.Payload +} + +func (o *UnMountDeviceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(UnMountDeviceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUnMountDeviceDefault creates a UnMountDeviceDefault with default headers values +func NewUnMountDeviceDefault(code int) *UnMountDeviceDefault { + return &UnMountDeviceDefault{ + _statusCode: code, + } +} + +/* UnMountDeviceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type UnMountDeviceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *UnMountDeviceDefaultBody +} + +// Code gets the status code for the un mount device default response +func (o *UnMountDeviceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this un mount device default response has a 2xx status code +func (o *UnMountDeviceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this un mount device default response has a 3xx status code +func (o *UnMountDeviceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this un mount device default response has a 4xx status code +func (o *UnMountDeviceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this un mount device default response has a 5xx status code +func (o *UnMountDeviceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this un mount device default response a status code equal to that given +func (o *UnMountDeviceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *UnMountDeviceDefault) Error() string { + return fmt.Sprintf("[PUT /devices/unmount][%d] unMountDevice default %+v", o._statusCode, o.Payload) +} + +func (o *UnMountDeviceDefault) String() string { + return fmt.Sprintf("[PUT /devices/unmount][%d] unMountDevice default %+v", o._statusCode, o.Payload) +} + +func (o *UnMountDeviceDefault) GetPayload() *UnMountDeviceDefaultBody { + return o.Payload +} + +func (o *UnMountDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(UnMountDeviceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*UnMountDeviceDefaultBody un mount device default body +swagger:model UnMountDeviceDefaultBody +*/ +type UnMountDeviceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this un mount device default body +func (o *UnMountDeviceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnMountDeviceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("unMountDevice default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *UnMountDeviceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("unMountDevice default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unMountDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unMountDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this un mount device default body based on the context it is used +func (o *UnMountDeviceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnMountDeviceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unMountDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unMountDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *UnMountDeviceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *UnMountDeviceDefaultBody) UnmarshalBinary(b []byte) error { + var res UnMountDeviceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*UnMountDeviceOKBody un mount device o k body +swagger:model UnMountDeviceOKBody +*/ +type UnMountDeviceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this un mount device o k body +func (o *UnMountDeviceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnMountDeviceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unMountDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unMountDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this un mount device o k body based on the context it is used +func (o *UnMountDeviceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnMountDeviceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unMountDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unMountDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *UnMountDeviceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *UnMountDeviceOKBody) UnmarshalBinary(b []byte) error { + var res UnMountDeviceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/associated_image_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/associated_image_parameters.go new file mode 100644 index 0000000..593b7bc --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/associated_image_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewAssociatedImageParams creates a new AssociatedImageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewAssociatedImageParams() *AssociatedImageParams { + return &AssociatedImageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewAssociatedImageParamsWithTimeout creates a new AssociatedImageParams object +// with the ability to set a timeout on a request. +func NewAssociatedImageParamsWithTimeout(timeout time.Duration) *AssociatedImageParams { + return &AssociatedImageParams{ + timeout: timeout, + } +} + +// NewAssociatedImageParamsWithContext creates a new AssociatedImageParams object +// with the ability to set a context for a request. +func NewAssociatedImageParamsWithContext(ctx context.Context) *AssociatedImageParams { + return &AssociatedImageParams{ + Context: ctx, + } +} + +// NewAssociatedImageParamsWithHTTPClient creates a new AssociatedImageParams object +// with the ability to set a custom HTTPClient for a request. +func NewAssociatedImageParamsWithHTTPClient(client *http.Client) *AssociatedImageParams { + return &AssociatedImageParams{ + HTTPClient: client, + } +} + +/* AssociatedImageParams contains all the parameters to send to the API endpoint + for the associated image operation. + + Typically these are written to a http.Request. +*/ +type AssociatedImageParams struct { + + // Body. + Body *models.AssociateImageRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the associated image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AssociatedImageParams) WithDefaults() *AssociatedImageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the associated image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AssociatedImageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the associated image params +func (o *AssociatedImageParams) WithTimeout(timeout time.Duration) *AssociatedImageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the associated image params +func (o *AssociatedImageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the associated image params +func (o *AssociatedImageParams) WithContext(ctx context.Context) *AssociatedImageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the associated image params +func (o *AssociatedImageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the associated image params +func (o *AssociatedImageParams) WithHTTPClient(client *http.Client) *AssociatedImageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the associated image params +func (o *AssociatedImageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the associated image params +func (o *AssociatedImageParams) WithBody(body *models.AssociateImageRequest) *AssociatedImageParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the associated image params +func (o *AssociatedImageParams) SetBody(body *models.AssociateImageRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the associated image params +func (o *AssociatedImageParams) WithAuthorization(authorization string) *AssociatedImageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the associated image params +func (o *AssociatedImageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the associated image params +func (o *AssociatedImageParams) WithBmpLanguage(bmpLanguage *string) *AssociatedImageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the associated image params +func (o *AssociatedImageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the associated image params +func (o *AssociatedImageParams) WithBmpUserID(bmpUserID *string) *AssociatedImageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the associated image params +func (o *AssociatedImageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the associated image params +func (o *AssociatedImageParams) WithTraceID(traceID string) *AssociatedImageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the associated image params +func (o *AssociatedImageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *AssociatedImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/associated_image_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/associated_image_responses.go new file mode 100644 index 0000000..a45b302 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/associated_image_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// AssociatedImageReader is a Reader for the AssociatedImage structure. +type AssociatedImageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *AssociatedImageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewAssociatedImageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewAssociatedImageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewAssociatedImageOK creates a AssociatedImageOK with default headers values +func NewAssociatedImageOK() *AssociatedImageOK { + return &AssociatedImageOK{} +} + +/* AssociatedImageOK describes a response with status code 200, with default header values. + +A AssociatedImageResult is an response struct that is used to associated image result. +*/ +type AssociatedImageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *AssociatedImageOKBody +} + +// IsSuccess returns true when this associated image o k response has a 2xx status code +func (o *AssociatedImageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this associated image o k response has a 3xx status code +func (o *AssociatedImageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this associated image o k response has a 4xx status code +func (o *AssociatedImageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this associated image o k response has a 5xx status code +func (o *AssociatedImageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this associated image o k response a status code equal to that given +func (o *AssociatedImageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *AssociatedImageOK) Error() string { + return fmt.Sprintf("[POST /deviceTypes/associatedImage][%d] associatedImageOK %+v", 200, o.Payload) +} + +func (o *AssociatedImageOK) String() string { + return fmt.Sprintf("[POST /deviceTypes/associatedImage][%d] associatedImageOK %+v", 200, o.Payload) +} + +func (o *AssociatedImageOK) GetPayload() *AssociatedImageOKBody { + return o.Payload +} + +func (o *AssociatedImageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AssociatedImageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAssociatedImageDefault creates a AssociatedImageDefault with default headers values +func NewAssociatedImageDefault(code int) *AssociatedImageDefault { + return &AssociatedImageDefault{ + _statusCode: code, + } +} + +/* AssociatedImageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type AssociatedImageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *AssociatedImageDefaultBody +} + +// Code gets the status code for the associated image default response +func (o *AssociatedImageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this associated image default response has a 2xx status code +func (o *AssociatedImageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this associated image default response has a 3xx status code +func (o *AssociatedImageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this associated image default response has a 4xx status code +func (o *AssociatedImageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this associated image default response has a 5xx status code +func (o *AssociatedImageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this associated image default response a status code equal to that given +func (o *AssociatedImageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *AssociatedImageDefault) Error() string { + return fmt.Sprintf("[POST /deviceTypes/associatedImage][%d] associatedImage default %+v", o._statusCode, o.Payload) +} + +func (o *AssociatedImageDefault) String() string { + return fmt.Sprintf("[POST /deviceTypes/associatedImage][%d] associatedImage default %+v", o._statusCode, o.Payload) +} + +func (o *AssociatedImageDefault) GetPayload() *AssociatedImageDefaultBody { + return o.Payload +} + +func (o *AssociatedImageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AssociatedImageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*AssociatedImageDefaultBody associated image default body +swagger:model AssociatedImageDefaultBody +*/ +type AssociatedImageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this associated image default body +func (o *AssociatedImageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedImageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("associatedImage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *AssociatedImageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("associatedImage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this associated image default body based on the context it is used +func (o *AssociatedImageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedImageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AssociatedImageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AssociatedImageDefaultBody) UnmarshalBinary(b []byte) error { + var res AssociatedImageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*AssociatedImageOKBody associated image o k body +swagger:model AssociatedImageOKBody +*/ +type AssociatedImageOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this associated image o k body +func (o *AssociatedImageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedImageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this associated image o k body based on the context it is used +func (o *AssociatedImageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedImageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AssociatedImageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AssociatedImageOKBody) UnmarshalBinary(b []byte) error { + var res AssociatedImageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/create_device_type_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/create_device_type_parameters.go new file mode 100644 index 0000000..9a9577e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/create_device_type_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateDeviceTypeParams creates a new CreateDeviceTypeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateDeviceTypeParams() *CreateDeviceTypeParams { + return &CreateDeviceTypeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateDeviceTypeParamsWithTimeout creates a new CreateDeviceTypeParams object +// with the ability to set a timeout on a request. +func NewCreateDeviceTypeParamsWithTimeout(timeout time.Duration) *CreateDeviceTypeParams { + return &CreateDeviceTypeParams{ + timeout: timeout, + } +} + +// NewCreateDeviceTypeParamsWithContext creates a new CreateDeviceTypeParams object +// with the ability to set a context for a request. +func NewCreateDeviceTypeParamsWithContext(ctx context.Context) *CreateDeviceTypeParams { + return &CreateDeviceTypeParams{ + Context: ctx, + } +} + +// NewCreateDeviceTypeParamsWithHTTPClient creates a new CreateDeviceTypeParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateDeviceTypeParamsWithHTTPClient(client *http.Client) *CreateDeviceTypeParams { + return &CreateDeviceTypeParams{ + HTTPClient: client, + } +} + +/* CreateDeviceTypeParams contains all the parameters to send to the API endpoint + for the create device type operation. + + Typically these are written to a http.Request. +*/ +type CreateDeviceTypeParams struct { + + // Body. + Body *models.CreateDeviceTypeRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateDeviceTypeParams) WithDefaults() *CreateDeviceTypeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateDeviceTypeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create device type params +func (o *CreateDeviceTypeParams) WithTimeout(timeout time.Duration) *CreateDeviceTypeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create device type params +func (o *CreateDeviceTypeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create device type params +func (o *CreateDeviceTypeParams) WithContext(ctx context.Context) *CreateDeviceTypeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create device type params +func (o *CreateDeviceTypeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create device type params +func (o *CreateDeviceTypeParams) WithHTTPClient(client *http.Client) *CreateDeviceTypeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create device type params +func (o *CreateDeviceTypeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create device type params +func (o *CreateDeviceTypeParams) WithBody(body *models.CreateDeviceTypeRequest) *CreateDeviceTypeParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create device type params +func (o *CreateDeviceTypeParams) SetBody(body *models.CreateDeviceTypeRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create device type params +func (o *CreateDeviceTypeParams) WithAuthorization(authorization string) *CreateDeviceTypeParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create device type params +func (o *CreateDeviceTypeParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create device type params +func (o *CreateDeviceTypeParams) WithBmpLanguage(bmpLanguage *string) *CreateDeviceTypeParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create device type params +func (o *CreateDeviceTypeParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create device type params +func (o *CreateDeviceTypeParams) WithBmpUserID(bmpUserID *string) *CreateDeviceTypeParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create device type params +func (o *CreateDeviceTypeParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create device type params +func (o *CreateDeviceTypeParams) WithTraceID(traceID string) *CreateDeviceTypeParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create device type params +func (o *CreateDeviceTypeParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateDeviceTypeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/create_device_type_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/create_device_type_responses.go new file mode 100644 index 0000000..7c5b69e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/create_device_type_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateDeviceTypeReader is a Reader for the CreateDeviceType structure. +type CreateDeviceTypeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateDeviceTypeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateDeviceTypeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateDeviceTypeDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateDeviceTypeOK creates a CreateDeviceTypeOK with default headers values +func NewCreateDeviceTypeOK() *CreateDeviceTypeOK { + return &CreateDeviceTypeOK{} +} + +/* CreateDeviceTypeOK describes a response with status code 200, with default header values. + +A CreateDeviceTypeResult is an response struct that is used to describe create deviceType result. +*/ +type CreateDeviceTypeOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateDeviceTypeOKBody +} + +// IsSuccess returns true when this create device type o k response has a 2xx status code +func (o *CreateDeviceTypeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create device type o k response has a 3xx status code +func (o *CreateDeviceTypeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create device type o k response has a 4xx status code +func (o *CreateDeviceTypeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create device type o k response has a 5xx status code +func (o *CreateDeviceTypeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create device type o k response a status code equal to that given +func (o *CreateDeviceTypeOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateDeviceTypeOK) Error() string { + return fmt.Sprintf("[POST /deviceTypes][%d] createDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *CreateDeviceTypeOK) String() string { + return fmt.Sprintf("[POST /deviceTypes][%d] createDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *CreateDeviceTypeOK) GetPayload() *CreateDeviceTypeOKBody { + return o.Payload +} + +func (o *CreateDeviceTypeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateDeviceTypeOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateDeviceTypeDefault creates a CreateDeviceTypeDefault with default headers values +func NewCreateDeviceTypeDefault(code int) *CreateDeviceTypeDefault { + return &CreateDeviceTypeDefault{ + _statusCode: code, + } +} + +/* CreateDeviceTypeDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateDeviceTypeDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateDeviceTypeDefaultBody +} + +// Code gets the status code for the create device type default response +func (o *CreateDeviceTypeDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create device type default response has a 2xx status code +func (o *CreateDeviceTypeDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create device type default response has a 3xx status code +func (o *CreateDeviceTypeDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create device type default response has a 4xx status code +func (o *CreateDeviceTypeDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create device type default response has a 5xx status code +func (o *CreateDeviceTypeDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create device type default response a status code equal to that given +func (o *CreateDeviceTypeDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateDeviceTypeDefault) Error() string { + return fmt.Sprintf("[POST /deviceTypes][%d] createDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *CreateDeviceTypeDefault) String() string { + return fmt.Sprintf("[POST /deviceTypes][%d] createDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *CreateDeviceTypeDefault) GetPayload() *CreateDeviceTypeDefaultBody { + return o.Payload +} + +func (o *CreateDeviceTypeDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateDeviceTypeDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateDeviceTypeDefaultBody create device type default body +swagger:model CreateDeviceTypeDefaultBody +*/ +type CreateDeviceTypeDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create device type default body +func (o *CreateDeviceTypeDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createDeviceType default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateDeviceTypeDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createDeviceType default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create device type default body based on the context it is used +func (o *CreateDeviceTypeDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateDeviceTypeDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateDeviceTypeDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateDeviceTypeDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateDeviceTypeOKBody create device type o k body +swagger:model CreateDeviceTypeOKBody +*/ +type CreateDeviceTypeOKBody struct { + + // result + Result *models.DeviceTypeID `json:"result,omitempty"` +} + +// Validate validates this create device type o k body +func (o *CreateDeviceTypeOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create device type o k body based on the context it is used +func (o *CreateDeviceTypeOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateDeviceTypeOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateDeviceTypeOKBody) UnmarshalBinary(b []byte) error { + var res CreateDeviceTypeOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/delete_device_type_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/delete_device_type_parameters.go new file mode 100644 index 0000000..6ef3fdf --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/delete_device_type_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteDeviceTypeParams creates a new DeleteDeviceTypeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteDeviceTypeParams() *DeleteDeviceTypeParams { + return &DeleteDeviceTypeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteDeviceTypeParamsWithTimeout creates a new DeleteDeviceTypeParams object +// with the ability to set a timeout on a request. +func NewDeleteDeviceTypeParamsWithTimeout(timeout time.Duration) *DeleteDeviceTypeParams { + return &DeleteDeviceTypeParams{ + timeout: timeout, + } +} + +// NewDeleteDeviceTypeParamsWithContext creates a new DeleteDeviceTypeParams object +// with the ability to set a context for a request. +func NewDeleteDeviceTypeParamsWithContext(ctx context.Context) *DeleteDeviceTypeParams { + return &DeleteDeviceTypeParams{ + Context: ctx, + } +} + +// NewDeleteDeviceTypeParamsWithHTTPClient creates a new DeleteDeviceTypeParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteDeviceTypeParamsWithHTTPClient(client *http.Client) *DeleteDeviceTypeParams { + return &DeleteDeviceTypeParams{ + HTTPClient: client, + } +} + +/* DeleteDeviceTypeParams contains all the parameters to send to the API endpoint + for the delete device type operation. + + Typically these are written to a http.Request. +*/ +type DeleteDeviceTypeParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // DeviceTypeID. + DeviceTypeID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteDeviceTypeParams) WithDefaults() *DeleteDeviceTypeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteDeviceTypeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete device type params +func (o *DeleteDeviceTypeParams) WithTimeout(timeout time.Duration) *DeleteDeviceTypeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete device type params +func (o *DeleteDeviceTypeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete device type params +func (o *DeleteDeviceTypeParams) WithContext(ctx context.Context) *DeleteDeviceTypeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete device type params +func (o *DeleteDeviceTypeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete device type params +func (o *DeleteDeviceTypeParams) WithHTTPClient(client *http.Client) *DeleteDeviceTypeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete device type params +func (o *DeleteDeviceTypeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete device type params +func (o *DeleteDeviceTypeParams) WithAuthorization(authorization string) *DeleteDeviceTypeParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete device type params +func (o *DeleteDeviceTypeParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete device type params +func (o *DeleteDeviceTypeParams) WithBmpLanguage(bmpLanguage *string) *DeleteDeviceTypeParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete device type params +func (o *DeleteDeviceTypeParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete device type params +func (o *DeleteDeviceTypeParams) WithBmpUserID(bmpUserID *string) *DeleteDeviceTypeParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete device type params +func (o *DeleteDeviceTypeParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the delete device type params +func (o *DeleteDeviceTypeParams) WithDeviceTypeID(deviceTypeID string) *DeleteDeviceTypeParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the delete device type params +func (o *DeleteDeviceTypeParams) SetDeviceTypeID(deviceTypeID string) { + o.DeviceTypeID = deviceTypeID +} + +// WithTraceID adds the traceID to the delete device type params +func (o *DeleteDeviceTypeParams) WithTraceID(traceID string) *DeleteDeviceTypeParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete device type params +func (o *DeleteDeviceTypeParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteDeviceTypeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_type_id + if err := r.SetPathParam("device_type_id", o.DeviceTypeID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/delete_device_type_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/delete_device_type_responses.go new file mode 100644 index 0000000..686d347 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/delete_device_type_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteDeviceTypeReader is a Reader for the DeleteDeviceType structure. +type DeleteDeviceTypeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteDeviceTypeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteDeviceTypeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteDeviceTypeDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteDeviceTypeOK creates a DeleteDeviceTypeOK with default headers values +func NewDeleteDeviceTypeOK() *DeleteDeviceTypeOK { + return &DeleteDeviceTypeOK{} +} + +/* DeleteDeviceTypeOK describes a response with status code 200, with default header values. + +A DeleteDeviceTypeResult is an response struct that is used to delete device type. +*/ +type DeleteDeviceTypeOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteDeviceTypeOKBody +} + +// IsSuccess returns true when this delete device type o k response has a 2xx status code +func (o *DeleteDeviceTypeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete device type o k response has a 3xx status code +func (o *DeleteDeviceTypeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete device type o k response has a 4xx status code +func (o *DeleteDeviceTypeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete device type o k response has a 5xx status code +func (o *DeleteDeviceTypeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete device type o k response a status code equal to that given +func (o *DeleteDeviceTypeOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteDeviceTypeOK) Error() string { + return fmt.Sprintf("[DELETE /deviceTypes/{device_type_id}][%d] deleteDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DeleteDeviceTypeOK) String() string { + return fmt.Sprintf("[DELETE /deviceTypes/{device_type_id}][%d] deleteDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DeleteDeviceTypeOK) GetPayload() *DeleteDeviceTypeOKBody { + return o.Payload +} + +func (o *DeleteDeviceTypeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteDeviceTypeOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteDeviceTypeDefault creates a DeleteDeviceTypeDefault with default headers values +func NewDeleteDeviceTypeDefault(code int) *DeleteDeviceTypeDefault { + return &DeleteDeviceTypeDefault{ + _statusCode: code, + } +} + +/* DeleteDeviceTypeDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteDeviceTypeDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteDeviceTypeDefaultBody +} + +// Code gets the status code for the delete device type default response +func (o *DeleteDeviceTypeDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete device type default response has a 2xx status code +func (o *DeleteDeviceTypeDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete device type default response has a 3xx status code +func (o *DeleteDeviceTypeDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete device type default response has a 4xx status code +func (o *DeleteDeviceTypeDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete device type default response has a 5xx status code +func (o *DeleteDeviceTypeDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete device type default response a status code equal to that given +func (o *DeleteDeviceTypeDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteDeviceTypeDefault) Error() string { + return fmt.Sprintf("[DELETE /deviceTypes/{device_type_id}][%d] deleteDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteDeviceTypeDefault) String() string { + return fmt.Sprintf("[DELETE /deviceTypes/{device_type_id}][%d] deleteDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteDeviceTypeDefault) GetPayload() *DeleteDeviceTypeDefaultBody { + return o.Payload +} + +func (o *DeleteDeviceTypeDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteDeviceTypeDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteDeviceTypeDefaultBody delete device type default body +swagger:model DeleteDeviceTypeDefaultBody +*/ +type DeleteDeviceTypeDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete device type default body +func (o *DeleteDeviceTypeDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteDeviceType default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteDeviceTypeDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteDeviceType default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete device type default body based on the context it is used +func (o *DeleteDeviceTypeDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteDeviceTypeDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteDeviceTypeDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteDeviceTypeDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteDeviceTypeOKBody delete device type o k body +swagger:model DeleteDeviceTypeOKBody +*/ +type DeleteDeviceTypeOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete device type o k body +func (o *DeleteDeviceTypeOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete device type o k body based on the context it is used +func (o *DeleteDeviceTypeOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteDeviceTypeOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteDeviceTypeOKBody) UnmarshalBinary(b []byte) error { + var res DeleteDeviceTypeOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_image_partitions_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_image_partitions_parameters.go new file mode 100644 index 0000000..93af2e4 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_image_partitions_parameters.go @@ -0,0 +1,323 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeDeviceTypeImagePartitionsParams creates a new DescribeDeviceTypeImagePartitionsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceTypeImagePartitionsParams() *DescribeDeviceTypeImagePartitionsParams { + return &DescribeDeviceTypeImagePartitionsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceTypeImagePartitionsParamsWithTimeout creates a new DescribeDeviceTypeImagePartitionsParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceTypeImagePartitionsParamsWithTimeout(timeout time.Duration) *DescribeDeviceTypeImagePartitionsParams { + return &DescribeDeviceTypeImagePartitionsParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceTypeImagePartitionsParamsWithContext creates a new DescribeDeviceTypeImagePartitionsParams object +// with the ability to set a context for a request. +func NewDescribeDeviceTypeImagePartitionsParamsWithContext(ctx context.Context) *DescribeDeviceTypeImagePartitionsParams { + return &DescribeDeviceTypeImagePartitionsParams{ + Context: ctx, + } +} + +// NewDescribeDeviceTypeImagePartitionsParamsWithHTTPClient creates a new DescribeDeviceTypeImagePartitionsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceTypeImagePartitionsParamsWithHTTPClient(client *http.Client) *DescribeDeviceTypeImagePartitionsParams { + return &DescribeDeviceTypeImagePartitionsParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceTypeImagePartitionsParams contains all the parameters to send to the API endpoint + for the describe device type image partitions operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceTypeImagePartitionsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceTypeID. + + 机型id + */ + DeviceTypeID *string + + /* ImageID. + + 镜像id + */ + ImageID *string + + /* IsAll. + + 是否显示所有,isAll=1显示所有 + */ + IsAll *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device type image partitions params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeImagePartitionsParams) WithDefaults() *DescribeDeviceTypeImagePartitionsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device type image partitions params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeImagePartitionsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithTimeout(timeout time.Duration) *DescribeDeviceTypeImagePartitionsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithContext(ctx context.Context) *DescribeDeviceTypeImagePartitionsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithHTTPClient(client *http.Client) *DescribeDeviceTypeImagePartitionsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithAuthorization(authorization string) *DescribeDeviceTypeImagePartitionsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceTypeImagePartitionsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceTypeImagePartitionsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDeviceTypeImagePartitionsParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithImageID adds the imageID to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithImageID(imageID *string) *DescribeDeviceTypeImagePartitionsParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetImageID(imageID *string) { + o.ImageID = imageID +} + +// WithIsAll adds the isAll to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithIsAll(isAll *string) *DescribeDeviceTypeImagePartitionsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithTraceID adds the traceID to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithTraceID(traceID string) *DescribeDeviceTypeImagePartitionsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceTypeImagePartitionsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.ImageID != nil { + + // query param imageId + var qrImageID string + + if o.ImageID != nil { + qrImageID = *o.ImageID + } + qImageID := qrImageID + if qImageID != "" { + + if err := r.SetQueryParam("imageId", qImageID); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_image_partitions_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_image_partitions_responses.go new file mode 100644 index 0000000..1666161 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_image_partitions_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDeviceTypeImagePartitionsReader is a Reader for the DescribeDeviceTypeImagePartitions structure. +type DescribeDeviceTypeImagePartitionsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceTypeImagePartitionsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceTypeImagePartitionsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceTypeImagePartitionsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceTypeImagePartitionsOK creates a DescribeDeviceTypeImagePartitionsOK with default headers values +func NewDescribeDeviceTypeImagePartitionsOK() *DescribeDeviceTypeImagePartitionsOK { + return &DescribeDeviceTypeImagePartitionsOK{} +} + +/* DescribeDeviceTypeImagePartitionsOK describes a response with status code 200, with default header values. + +DescribeDeviceTypeImagePartitionsOK describe device type image partitions o k +*/ +type DescribeDeviceTypeImagePartitionsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeImagePartitionsOKBody +} + +// IsSuccess returns true when this describe device type image partitions o k response has a 2xx status code +func (o *DescribeDeviceTypeImagePartitionsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device type image partitions o k response has a 3xx status code +func (o *DescribeDeviceTypeImagePartitionsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device type image partitions o k response has a 4xx status code +func (o *DescribeDeviceTypeImagePartitionsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device type image partitions o k response has a 5xx status code +func (o *DescribeDeviceTypeImagePartitionsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device type image partitions o k response a status code equal to that given +func (o *DescribeDeviceTypeImagePartitionsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceTypeImagePartitionsOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImagePartition][%d] describeDeviceTypeImagePartitionsOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeImagePartitionsOK) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImagePartition][%d] describeDeviceTypeImagePartitionsOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeImagePartitionsOK) GetPayload() *DescribeDeviceTypeImagePartitionsOKBody { + return o.Payload +} + +func (o *DescribeDeviceTypeImagePartitionsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeImagePartitionsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceTypeImagePartitionsDefault creates a DescribeDeviceTypeImagePartitionsDefault with default headers values +func NewDescribeDeviceTypeImagePartitionsDefault(code int) *DescribeDeviceTypeImagePartitionsDefault { + return &DescribeDeviceTypeImagePartitionsDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceTypeImagePartitionsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceTypeImagePartitionsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeImagePartitionsDefaultBody +} + +// Code gets the status code for the describe device type image partitions default response +func (o *DescribeDeviceTypeImagePartitionsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device type image partitions default response has a 2xx status code +func (o *DescribeDeviceTypeImagePartitionsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device type image partitions default response has a 3xx status code +func (o *DescribeDeviceTypeImagePartitionsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device type image partitions default response has a 4xx status code +func (o *DescribeDeviceTypeImagePartitionsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device type image partitions default response has a 5xx status code +func (o *DescribeDeviceTypeImagePartitionsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device type image partitions default response a status code equal to that given +func (o *DescribeDeviceTypeImagePartitionsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceTypeImagePartitionsDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImagePartition][%d] describeDeviceTypeImagePartitions default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeImagePartitionsDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImagePartition][%d] describeDeviceTypeImagePartitions default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeImagePartitionsDefault) GetPayload() *DescribeDeviceTypeImagePartitionsDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceTypeImagePartitionsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeImagePartitionsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceTypeImagePartitionsDefaultBody describe device type image partitions default body +swagger:model DescribeDeviceTypeImagePartitionsDefaultBody +*/ +type DescribeDeviceTypeImagePartitionsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device type image partitions default body +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeImagePartitions default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeImagePartitions default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagePartitions default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagePartitions default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type image partitions default body based on the context it is used +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagePartitions default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagePartitions default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeImagePartitionsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceTypeImagePartitionsOKBody describe device type image partitions o k body +swagger:model DescribeDeviceTypeImagePartitionsOKBody +*/ +type DescribeDeviceTypeImagePartitionsOKBody struct { + + // result + Result *models.QueryDeviceTypeImagePartitionResponse `json:"result,omitempty"` +} + +// Validate validates this describe device type image partitions o k body +func (o *DescribeDeviceTypeImagePartitionsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagePartitionsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagePartitionsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagePartitionsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type image partitions o k body based on the context it is used +func (o *DescribeDeviceTypeImagePartitionsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagePartitionsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagePartitionsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagePartitionsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeImagePartitionsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeImagePartitionsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeImagePartitionsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_images_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_images_parameters.go new file mode 100644 index 0000000..18a2d74 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_images_parameters.go @@ -0,0 +1,600 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeDeviceTypeImagesParams creates a new DescribeDeviceTypeImagesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceTypeImagesParams() *DescribeDeviceTypeImagesParams { + return &DescribeDeviceTypeImagesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceTypeImagesParamsWithTimeout creates a new DescribeDeviceTypeImagesParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceTypeImagesParamsWithTimeout(timeout time.Duration) *DescribeDeviceTypeImagesParams { + return &DescribeDeviceTypeImagesParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceTypeImagesParamsWithContext creates a new DescribeDeviceTypeImagesParams object +// with the ability to set a context for a request. +func NewDescribeDeviceTypeImagesParamsWithContext(ctx context.Context) *DescribeDeviceTypeImagesParams { + return &DescribeDeviceTypeImagesParams{ + Context: ctx, + } +} + +// NewDescribeDeviceTypeImagesParamsWithHTTPClient creates a new DescribeDeviceTypeImagesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceTypeImagesParamsWithHTTPClient(client *http.Client) *DescribeDeviceTypeImagesParams { + return &DescribeDeviceTypeImagesParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceTypeImagesParams contains all the parameters to send to the API endpoint + for the describe device type images operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceTypeImagesParams struct { + + /* Architecture. + + 体系架构 + */ + Architecture *string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceTypeID. + + 机型id + */ + DeviceTypeID *string + + /* ImageID. + + 镜像id + */ + ImageID *string + + /* ImageName. + + 镜像名称 + */ + ImageName *string + + /* IsAll. + + 是否显示全部 + */ + IsAll *string + + /* OsID. + + 操作系统ID + */ + OsID *string + + /* OsType. + + 操作系统平台 + */ + OsType *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* Source. + + 镜像类型,预置,自定义 + */ + Source *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* Version. + + 版本号 + */ + Version *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device type images params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeImagesParams) WithDefaults() *DescribeDeviceTypeImagesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device type images params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeImagesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithTimeout(timeout time.Duration) *DescribeDeviceTypeImagesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithContext(ctx context.Context) *DescribeDeviceTypeImagesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithHTTPClient(client *http.Client) *DescribeDeviceTypeImagesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithArchitecture adds the architecture to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithArchitecture(architecture *string) *DescribeDeviceTypeImagesParams { + o.SetArchitecture(architecture) + return o +} + +// SetArchitecture adds the architecture to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetArchitecture(architecture *string) { + o.Architecture = architecture +} + +// WithAuthorization adds the authorization to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithAuthorization(authorization string) *DescribeDeviceTypeImagesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceTypeImagesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceTypeImagesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDeviceTypeImagesParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithImageID adds the imageID to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithImageID(imageID *string) *DescribeDeviceTypeImagesParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetImageID(imageID *string) { + o.ImageID = imageID +} + +// WithImageName adds the imageName to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithImageName(imageName *string) *DescribeDeviceTypeImagesParams { + o.SetImageName(imageName) + return o +} + +// SetImageName adds the imageName to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetImageName(imageName *string) { + o.ImageName = imageName +} + +// WithIsAll adds the isAll to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithIsAll(isAll *string) *DescribeDeviceTypeImagesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithOsID adds the osID to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithOsID(osID *string) *DescribeDeviceTypeImagesParams { + o.SetOsID(osID) + return o +} + +// SetOsID adds the osId to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetOsID(osID *string) { + o.OsID = osID +} + +// WithOsType adds the osType to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithOsType(osType *string) *DescribeDeviceTypeImagesParams { + o.SetOsType(osType) + return o +} + +// SetOsType adds the osType to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetOsType(osType *string) { + o.OsType = osType +} + +// WithPageNumber adds the pageNumber to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithPageNumber(pageNumber *int64) *DescribeDeviceTypeImagesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithPageSize(pageSize *int64) *DescribeDeviceTypeImagesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithSource adds the source to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithSource(source *string) *DescribeDeviceTypeImagesParams { + o.SetSource(source) + return o +} + +// SetSource adds the source to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetSource(source *string) { + o.Source = source +} + +// WithTraceID adds the traceID to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithTraceID(traceID string) *DescribeDeviceTypeImagesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithVersion adds the version to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithVersion(version *string) *DescribeDeviceTypeImagesParams { + o.SetVersion(version) + return o +} + +// SetVersion adds the version to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetVersion(version *string) { + o.Version = version +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceTypeImagesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Architecture != nil { + + // query param architecture + var qrArchitecture string + + if o.Architecture != nil { + qrArchitecture = *o.Architecture + } + qArchitecture := qrArchitecture + if qArchitecture != "" { + + if err := r.SetQueryParam("architecture", qArchitecture); err != nil { + return err + } + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.ImageID != nil { + + // query param imageId + var qrImageID string + + if o.ImageID != nil { + qrImageID = *o.ImageID + } + qImageID := qrImageID + if qImageID != "" { + + if err := r.SetQueryParam("imageId", qImageID); err != nil { + return err + } + } + } + + if o.ImageName != nil { + + // query param imageName + var qrImageName string + + if o.ImageName != nil { + qrImageName = *o.ImageName + } + qImageName := qrImageName + if qImageName != "" { + + if err := r.SetQueryParam("imageName", qImageName); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.OsID != nil { + + // query param osId + var qrOsID string + + if o.OsID != nil { + qrOsID = *o.OsID + } + qOsID := qrOsID + if qOsID != "" { + + if err := r.SetQueryParam("osId", qOsID); err != nil { + return err + } + } + } + + if o.OsType != nil { + + // query param osType + var qrOsType string + + if o.OsType != nil { + qrOsType = *o.OsType + } + qOsType := qrOsType + if qOsType != "" { + + if err := r.SetQueryParam("osType", qOsType); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.Source != nil { + + // query param source + var qrSource string + + if o.Source != nil { + qrSource = *o.Source + } + qSource := qrSource + if qSource != "" { + + if err := r.SetQueryParam("source", qSource); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.Version != nil { + + // query param version + var qrVersion string + + if o.Version != nil { + qrVersion = *o.Version + } + qVersion := qrVersion + if qVersion != "" { + + if err := r.SetQueryParam("version", qVersion); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_images_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_images_responses.go new file mode 100644 index 0000000..e12580b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_images_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDeviceTypeImagesReader is a Reader for the DescribeDeviceTypeImages structure. +type DescribeDeviceTypeImagesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceTypeImagesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceTypeImagesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceTypeImagesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceTypeImagesOK creates a DescribeDeviceTypeImagesOK with default headers values +func NewDescribeDeviceTypeImagesOK() *DescribeDeviceTypeImagesOK { + return &DescribeDeviceTypeImagesOK{} +} + +/* DescribeDeviceTypeImagesOK describes a response with status code 200, with default header values. + +DescribeDeviceTypeImagesOK describe device type images o k +*/ +type DescribeDeviceTypeImagesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeImagesOKBody +} + +// IsSuccess returns true when this describe device type images o k response has a 2xx status code +func (o *DescribeDeviceTypeImagesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device type images o k response has a 3xx status code +func (o *DescribeDeviceTypeImagesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device type images o k response has a 4xx status code +func (o *DescribeDeviceTypeImagesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device type images o k response has a 5xx status code +func (o *DescribeDeviceTypeImagesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device type images o k response a status code equal to that given +func (o *DescribeDeviceTypeImagesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceTypeImagesOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImage][%d] describeDeviceTypeImagesOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeImagesOK) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImage][%d] describeDeviceTypeImagesOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeImagesOK) GetPayload() *DescribeDeviceTypeImagesOKBody { + return o.Payload +} + +func (o *DescribeDeviceTypeImagesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeImagesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceTypeImagesDefault creates a DescribeDeviceTypeImagesDefault with default headers values +func NewDescribeDeviceTypeImagesDefault(code int) *DescribeDeviceTypeImagesDefault { + return &DescribeDeviceTypeImagesDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceTypeImagesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceTypeImagesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeImagesDefaultBody +} + +// Code gets the status code for the describe device type images default response +func (o *DescribeDeviceTypeImagesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device type images default response has a 2xx status code +func (o *DescribeDeviceTypeImagesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device type images default response has a 3xx status code +func (o *DescribeDeviceTypeImagesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device type images default response has a 4xx status code +func (o *DescribeDeviceTypeImagesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device type images default response has a 5xx status code +func (o *DescribeDeviceTypeImagesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device type images default response a status code equal to that given +func (o *DescribeDeviceTypeImagesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceTypeImagesDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImage][%d] describeDeviceTypeImages default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeImagesDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImage][%d] describeDeviceTypeImages default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeImagesDefault) GetPayload() *DescribeDeviceTypeImagesDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceTypeImagesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeImagesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceTypeImagesDefaultBody describe device type images default body +swagger:model DescribeDeviceTypeImagesDefaultBody +*/ +type DescribeDeviceTypeImagesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device type images default body +func (o *DescribeDeviceTypeImagesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeImages default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceTypeImagesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeImages default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImages default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImages default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type images default body based on the context it is used +func (o *DescribeDeviceTypeImagesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImages default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImages default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeImagesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeImagesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeImagesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceTypeImagesOKBody describe device type images o k body +swagger:model DescribeDeviceTypeImagesOKBody +*/ +type DescribeDeviceTypeImagesOKBody struct { + + // result + Result *models.ImageList `json:"result,omitempty"` +} + +// Validate validates this describe device type images o k body +func (o *DescribeDeviceTypeImagesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type images o k body based on the context it is used +func (o *DescribeDeviceTypeImagesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeImagesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeImagesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeImagesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_parameters.go new file mode 100644 index 0000000..fb352df --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeDeviceTypeParams creates a new DescribeDeviceTypeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceTypeParams() *DescribeDeviceTypeParams { + return &DescribeDeviceTypeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceTypeParamsWithTimeout creates a new DescribeDeviceTypeParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceTypeParamsWithTimeout(timeout time.Duration) *DescribeDeviceTypeParams { + return &DescribeDeviceTypeParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceTypeParamsWithContext creates a new DescribeDeviceTypeParams object +// with the ability to set a context for a request. +func NewDescribeDeviceTypeParamsWithContext(ctx context.Context) *DescribeDeviceTypeParams { + return &DescribeDeviceTypeParams{ + Context: ctx, + } +} + +// NewDescribeDeviceTypeParamsWithHTTPClient creates a new DescribeDeviceTypeParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceTypeParamsWithHTTPClient(client *http.Client) *DescribeDeviceTypeParams { + return &DescribeDeviceTypeParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceTypeParams contains all the parameters to send to the API endpoint + for the describe device type operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceTypeParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // DeviceTypeID. + DeviceTypeID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeParams) WithDefaults() *DescribeDeviceTypeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device type params +func (o *DescribeDeviceTypeParams) WithTimeout(timeout time.Duration) *DescribeDeviceTypeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device type params +func (o *DescribeDeviceTypeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device type params +func (o *DescribeDeviceTypeParams) WithContext(ctx context.Context) *DescribeDeviceTypeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device type params +func (o *DescribeDeviceTypeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device type params +func (o *DescribeDeviceTypeParams) WithHTTPClient(client *http.Client) *DescribeDeviceTypeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device type params +func (o *DescribeDeviceTypeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device type params +func (o *DescribeDeviceTypeParams) WithAuthorization(authorization string) *DescribeDeviceTypeParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device type params +func (o *DescribeDeviceTypeParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device type params +func (o *DescribeDeviceTypeParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceTypeParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device type params +func (o *DescribeDeviceTypeParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device type params +func (o *DescribeDeviceTypeParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceTypeParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device type params +func (o *DescribeDeviceTypeParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device type params +func (o *DescribeDeviceTypeParams) WithDeviceTypeID(deviceTypeID string) *DescribeDeviceTypeParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device type params +func (o *DescribeDeviceTypeParams) SetDeviceTypeID(deviceTypeID string) { + o.DeviceTypeID = deviceTypeID +} + +// WithTraceID adds the traceID to the describe device type params +func (o *DescribeDeviceTypeParams) WithTraceID(traceID string) *DescribeDeviceTypeParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device type params +func (o *DescribeDeviceTypeParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceTypeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_type_id + if err := r.SetPathParam("device_type_id", o.DeviceTypeID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_raids_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_raids_parameters.go new file mode 100644 index 0000000..b140917 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_raids_parameters.go @@ -0,0 +1,357 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeDeviceTypeRaidsParams creates a new DescribeDeviceTypeRaidsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceTypeRaidsParams() *DescribeDeviceTypeRaidsParams { + return &DescribeDeviceTypeRaidsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceTypeRaidsParamsWithTimeout creates a new DescribeDeviceTypeRaidsParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceTypeRaidsParamsWithTimeout(timeout time.Duration) *DescribeDeviceTypeRaidsParams { + return &DescribeDeviceTypeRaidsParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceTypeRaidsParamsWithContext creates a new DescribeDeviceTypeRaidsParams object +// with the ability to set a context for a request. +func NewDescribeDeviceTypeRaidsParamsWithContext(ctx context.Context) *DescribeDeviceTypeRaidsParams { + return &DescribeDeviceTypeRaidsParams{ + Context: ctx, + } +} + +// NewDescribeDeviceTypeRaidsParamsWithHTTPClient creates a new DescribeDeviceTypeRaidsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceTypeRaidsParamsWithHTTPClient(client *http.Client) *DescribeDeviceTypeRaidsParams { + return &DescribeDeviceTypeRaidsParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceTypeRaidsParams contains all the parameters to send to the API endpoint + for the describe device type raids operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceTypeRaidsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceTypeID. + + 机型id + */ + DeviceTypeID *string + + /* IsAll. + + 是否显示所有 + */ + IsAll *string + + /* RaidID. + + raidID + */ + RaidID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* VolumeType. + + 系统盘还是数据盘 + */ + VolumeType *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device type raids params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeRaidsParams) WithDefaults() *DescribeDeviceTypeRaidsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device type raids params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeRaidsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithTimeout(timeout time.Duration) *DescribeDeviceTypeRaidsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithContext(ctx context.Context) *DescribeDeviceTypeRaidsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithHTTPClient(client *http.Client) *DescribeDeviceTypeRaidsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithAuthorization(authorization string) *DescribeDeviceTypeRaidsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceTypeRaidsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceTypeRaidsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDeviceTypeRaidsParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithIsAll adds the isAll to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithIsAll(isAll *string) *DescribeDeviceTypeRaidsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithRaidID adds the raidID to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithRaidID(raidID *string) *DescribeDeviceTypeRaidsParams { + o.SetRaidID(raidID) + return o +} + +// SetRaidID adds the raidId to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetRaidID(raidID *string) { + o.RaidID = raidID +} + +// WithTraceID adds the traceID to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithTraceID(traceID string) *DescribeDeviceTypeRaidsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithVolumeType adds the volumeType to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithVolumeType(volumeType *string) *DescribeDeviceTypeRaidsParams { + o.SetVolumeType(volumeType) + return o +} + +// SetVolumeType adds the volumeType to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetVolumeType(volumeType *string) { + o.VolumeType = volumeType +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceTypeRaidsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.RaidID != nil { + + // query param raidId + var qrRaidID string + + if o.RaidID != nil { + qrRaidID = *o.RaidID + } + qRaidID := qrRaidID + if qRaidID != "" { + + if err := r.SetQueryParam("raidId", qRaidID); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.VolumeType != nil { + + // query param volumeType + var qrVolumeType string + + if o.VolumeType != nil { + qrVolumeType = *o.VolumeType + } + qVolumeType := qrVolumeType + if qVolumeType != "" { + + if err := r.SetQueryParam("volumeType", qVolumeType); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_raids_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_raids_responses.go new file mode 100644 index 0000000..04deb0c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_raids_responses.go @@ -0,0 +1,415 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDeviceTypeRaidsReader is a Reader for the DescribeDeviceTypeRaids structure. +type DescribeDeviceTypeRaidsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceTypeRaidsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceTypeRaidsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceTypeRaidsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceTypeRaidsOK creates a DescribeDeviceTypeRaidsOK with default headers values +func NewDescribeDeviceTypeRaidsOK() *DescribeDeviceTypeRaidsOK { + return &DescribeDeviceTypeRaidsOK{} +} + +/* DescribeDeviceTypeRaidsOK describes a response with status code 200, with default header values. + +DescribeDeviceTypeRaidsOK describe device type raids o k +*/ +type DescribeDeviceTypeRaidsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeRaidsOKBody +} + +// IsSuccess returns true when this describe device type raids o k response has a 2xx status code +func (o *DescribeDeviceTypeRaidsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device type raids o k response has a 3xx status code +func (o *DescribeDeviceTypeRaidsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device type raids o k response has a 4xx status code +func (o *DescribeDeviceTypeRaidsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device type raids o k response has a 5xx status code +func (o *DescribeDeviceTypeRaidsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device type raids o k response a status code equal to that given +func (o *DescribeDeviceTypeRaidsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceTypeRaidsOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeRaid][%d] describeDeviceTypeRaidsOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeRaidsOK) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeRaid][%d] describeDeviceTypeRaidsOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeRaidsOK) GetPayload() *DescribeDeviceTypeRaidsOKBody { + return o.Payload +} + +func (o *DescribeDeviceTypeRaidsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeRaidsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceTypeRaidsDefault creates a DescribeDeviceTypeRaidsDefault with default headers values +func NewDescribeDeviceTypeRaidsDefault(code int) *DescribeDeviceTypeRaidsDefault { + return &DescribeDeviceTypeRaidsDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceTypeRaidsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceTypeRaidsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeRaidsDefaultBody +} + +// Code gets the status code for the describe device type raids default response +func (o *DescribeDeviceTypeRaidsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device type raids default response has a 2xx status code +func (o *DescribeDeviceTypeRaidsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device type raids default response has a 3xx status code +func (o *DescribeDeviceTypeRaidsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device type raids default response has a 4xx status code +func (o *DescribeDeviceTypeRaidsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device type raids default response has a 5xx status code +func (o *DescribeDeviceTypeRaidsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device type raids default response a status code equal to that given +func (o *DescribeDeviceTypeRaidsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceTypeRaidsDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeRaid][%d] describeDeviceTypeRaids default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeRaidsDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeRaid][%d] describeDeviceTypeRaids default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeRaidsDefault) GetPayload() *DescribeDeviceTypeRaidsDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceTypeRaidsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeRaidsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceTypeRaidsDefaultBody describe device type raids default body +swagger:model DescribeDeviceTypeRaidsDefaultBody +*/ +type DescribeDeviceTypeRaidsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device type raids default body +func (o *DescribeDeviceTypeRaidsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeRaidsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeRaids default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceTypeRaidsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeRaids default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeRaids default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeRaids default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type raids default body based on the context it is used +func (o *DescribeDeviceTypeRaidsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeRaidsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeRaids default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeRaids default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeRaidsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeRaidsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeRaidsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceTypeRaidsOKBody describe device type raids o k body +swagger:model DescribeDeviceTypeRaidsOKBody +*/ +type DescribeDeviceTypeRaidsOKBody struct { + + // result + Result []*models.RDeviceTypeRaid `json:"result"` +} + +// Validate validates this describe device type raids o k body +func (o *DescribeDeviceTypeRaidsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeRaidsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + for i := 0; i < len(o.Result); i++ { + if swag.IsZero(o.Result[i]) { // not required + continue + } + + if o.Result[i] != nil { + if err := o.Result[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeRaidsOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeRaidsOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this describe device type raids o k body based on the context it is used +func (o *DescribeDeviceTypeRaidsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeRaidsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Result); i++ { + + if o.Result[i] != nil { + if err := o.Result[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeRaidsOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeRaidsOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeRaidsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeRaidsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeRaidsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_responses.go new file mode 100644 index 0000000..1f10de5 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDeviceTypeReader is a Reader for the DescribeDeviceType structure. +type DescribeDeviceTypeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceTypeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceTypeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceTypeDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceTypeOK creates a DescribeDeviceTypeOK with default headers values +func NewDescribeDeviceTypeOK() *DescribeDeviceTypeOK { + return &DescribeDeviceTypeOK{} +} + +/* DescribeDeviceTypeOK describes a response with status code 200, with default header values. + +DescribeDeviceTypeOK describe device type o k +*/ +type DescribeDeviceTypeOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeOKBody +} + +// IsSuccess returns true when this describe device type o k response has a 2xx status code +func (o *DescribeDeviceTypeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device type o k response has a 3xx status code +func (o *DescribeDeviceTypeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device type o k response has a 4xx status code +func (o *DescribeDeviceTypeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device type o k response has a 5xx status code +func (o *DescribeDeviceTypeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device type o k response a status code equal to that given +func (o *DescribeDeviceTypeOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceTypeOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}][%d] describeDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeOK) String() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}][%d] describeDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeOK) GetPayload() *DescribeDeviceTypeOKBody { + return o.Payload +} + +func (o *DescribeDeviceTypeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceTypeDefault creates a DescribeDeviceTypeDefault with default headers values +func NewDescribeDeviceTypeDefault(code int) *DescribeDeviceTypeDefault { + return &DescribeDeviceTypeDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceTypeDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceTypeDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeDefaultBody +} + +// Code gets the status code for the describe device type default response +func (o *DescribeDeviceTypeDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device type default response has a 2xx status code +func (o *DescribeDeviceTypeDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device type default response has a 3xx status code +func (o *DescribeDeviceTypeDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device type default response has a 4xx status code +func (o *DescribeDeviceTypeDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device type default response has a 5xx status code +func (o *DescribeDeviceTypeDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device type default response a status code equal to that given +func (o *DescribeDeviceTypeDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceTypeDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}][%d] describeDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}][%d] describeDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeDefault) GetPayload() *DescribeDeviceTypeDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceTypeDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceTypeDefaultBody describe device type default body +swagger:model DescribeDeviceTypeDefaultBody +*/ +type DescribeDeviceTypeDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device type default body +func (o *DescribeDeviceTypeDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceType default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceTypeDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceType default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type default body based on the context it is used +func (o *DescribeDeviceTypeDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceTypeOKBody describe device type o k body +swagger:model DescribeDeviceTypeOKBody +*/ +type DescribeDeviceTypeOKBody struct { + + // result + Result *models.DeviceTypeInfo `json:"result,omitempty"` +} + +// Validate validates this describe device type o k body +func (o *DescribeDeviceTypeOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type o k body based on the context it is used +func (o *DescribeDeviceTypeOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_types_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_types_parameters.go new file mode 100644 index 0000000..515c3d8 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_types_parameters.go @@ -0,0 +1,495 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeDeviceTypesParams creates a new DescribeDeviceTypesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceTypesParams() *DescribeDeviceTypesParams { + return &DescribeDeviceTypesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceTypesParamsWithTimeout creates a new DescribeDeviceTypesParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceTypesParamsWithTimeout(timeout time.Duration) *DescribeDeviceTypesParams { + return &DescribeDeviceTypesParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceTypesParamsWithContext creates a new DescribeDeviceTypesParams object +// with the ability to set a context for a request. +func NewDescribeDeviceTypesParamsWithContext(ctx context.Context) *DescribeDeviceTypesParams { + return &DescribeDeviceTypesParams{ + Context: ctx, + } +} + +// NewDescribeDeviceTypesParamsWithHTTPClient creates a new DescribeDeviceTypesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceTypesParamsWithHTTPClient(client *http.Client) *DescribeDeviceTypesParams { + return &DescribeDeviceTypesParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceTypesParams contains all the parameters to send to the API endpoint + for the describe device types operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceTypesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceSeries. + + 机型类型 + */ + DeviceSeries *string + + /* DeviceType. + + 机型规格 + */ + DeviceType *string + + /* DeviceTypeID. + + 机型id + */ + DeviceTypeID *string + + /* IdcID. + + 机房id + */ + IdcID *string + + // IsAll. + IsAll *string + + /* Name. + + 机型名称 + */ + Name *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypesParams) WithDefaults() *DescribeDeviceTypesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device types params +func (o *DescribeDeviceTypesParams) WithTimeout(timeout time.Duration) *DescribeDeviceTypesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device types params +func (o *DescribeDeviceTypesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device types params +func (o *DescribeDeviceTypesParams) WithContext(ctx context.Context) *DescribeDeviceTypesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device types params +func (o *DescribeDeviceTypesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device types params +func (o *DescribeDeviceTypesParams) WithHTTPClient(client *http.Client) *DescribeDeviceTypesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device types params +func (o *DescribeDeviceTypesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device types params +func (o *DescribeDeviceTypesParams) WithAuthorization(authorization string) *DescribeDeviceTypesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device types params +func (o *DescribeDeviceTypesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device types params +func (o *DescribeDeviceTypesParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceTypesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device types params +func (o *DescribeDeviceTypesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device types params +func (o *DescribeDeviceTypesParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceTypesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device types params +func (o *DescribeDeviceTypesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceSeries adds the deviceSeries to the describe device types params +func (o *DescribeDeviceTypesParams) WithDeviceSeries(deviceSeries *string) *DescribeDeviceTypesParams { + o.SetDeviceSeries(deviceSeries) + return o +} + +// SetDeviceSeries adds the deviceSeries to the describe device types params +func (o *DescribeDeviceTypesParams) SetDeviceSeries(deviceSeries *string) { + o.DeviceSeries = deviceSeries +} + +// WithDeviceType adds the deviceType to the describe device types params +func (o *DescribeDeviceTypesParams) WithDeviceType(deviceType *string) *DescribeDeviceTypesParams { + o.SetDeviceType(deviceType) + return o +} + +// SetDeviceType adds the deviceType to the describe device types params +func (o *DescribeDeviceTypesParams) SetDeviceType(deviceType *string) { + o.DeviceType = deviceType +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device types params +func (o *DescribeDeviceTypesParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDeviceTypesParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device types params +func (o *DescribeDeviceTypesParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithIdcID adds the idcID to the describe device types params +func (o *DescribeDeviceTypesParams) WithIdcID(idcID *string) *DescribeDeviceTypesParams { + o.SetIdcID(idcID) + return o +} + +// SetIdcID adds the idcId to the describe device types params +func (o *DescribeDeviceTypesParams) SetIdcID(idcID *string) { + o.IdcID = idcID +} + +// WithIsAll adds the isAll to the describe device types params +func (o *DescribeDeviceTypesParams) WithIsAll(isAll *string) *DescribeDeviceTypesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe device types params +func (o *DescribeDeviceTypesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithName adds the name to the describe device types params +func (o *DescribeDeviceTypesParams) WithName(name *string) *DescribeDeviceTypesParams { + o.SetName(name) + return o +} + +// SetName adds the name to the describe device types params +func (o *DescribeDeviceTypesParams) SetName(name *string) { + o.Name = name +} + +// WithPageNumber adds the pageNumber to the describe device types params +func (o *DescribeDeviceTypesParams) WithPageNumber(pageNumber *int64) *DescribeDeviceTypesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe device types params +func (o *DescribeDeviceTypesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe device types params +func (o *DescribeDeviceTypesParams) WithPageSize(pageSize *int64) *DescribeDeviceTypesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe device types params +func (o *DescribeDeviceTypesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe device types params +func (o *DescribeDeviceTypesParams) WithTraceID(traceID string) *DescribeDeviceTypesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device types params +func (o *DescribeDeviceTypesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceTypesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceSeries != nil { + + // query param deviceSeries + var qrDeviceSeries string + + if o.DeviceSeries != nil { + qrDeviceSeries = *o.DeviceSeries + } + qDeviceSeries := qrDeviceSeries + if qDeviceSeries != "" { + + if err := r.SetQueryParam("deviceSeries", qDeviceSeries); err != nil { + return err + } + } + } + + if o.DeviceType != nil { + + // query param deviceType + var qrDeviceType string + + if o.DeviceType != nil { + qrDeviceType = *o.DeviceType + } + qDeviceType := qrDeviceType + if qDeviceType != "" { + + if err := r.SetQueryParam("deviceType", qDeviceType); err != nil { + return err + } + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.IdcID != nil { + + // query param idcId + var qrIdcID string + + if o.IdcID != nil { + qrIdcID = *o.IdcID + } + qIdcID := qrIdcID + if qIdcID != "" { + + if err := r.SetQueryParam("idcId", qIdcID); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_types_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_types_responses.go new file mode 100644 index 0000000..cc37ea3 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_types_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDeviceTypesReader is a Reader for the DescribeDeviceTypes structure. +type DescribeDeviceTypesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceTypesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceTypesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceTypesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceTypesOK creates a DescribeDeviceTypesOK with default headers values +func NewDescribeDeviceTypesOK() *DescribeDeviceTypesOK { + return &DescribeDeviceTypesOK{} +} + +/* DescribeDeviceTypesOK describes a response with status code 200, with default header values. + +DescribeDeviceTypesOK describe device types o k +*/ +type DescribeDeviceTypesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypesOKBody +} + +// IsSuccess returns true when this describe device types o k response has a 2xx status code +func (o *DescribeDeviceTypesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device types o k response has a 3xx status code +func (o *DescribeDeviceTypesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device types o k response has a 4xx status code +func (o *DescribeDeviceTypesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device types o k response has a 5xx status code +func (o *DescribeDeviceTypesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device types o k response a status code equal to that given +func (o *DescribeDeviceTypesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceTypesOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes][%d] describeDeviceTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypesOK) String() string { + return fmt.Sprintf("[GET /deviceTypes][%d] describeDeviceTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypesOK) GetPayload() *DescribeDeviceTypesOKBody { + return o.Payload +} + +func (o *DescribeDeviceTypesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceTypesDefault creates a DescribeDeviceTypesDefault with default headers values +func NewDescribeDeviceTypesDefault(code int) *DescribeDeviceTypesDefault { + return &DescribeDeviceTypesDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceTypesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceTypesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypesDefaultBody +} + +// Code gets the status code for the describe device types default response +func (o *DescribeDeviceTypesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device types default response has a 2xx status code +func (o *DescribeDeviceTypesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device types default response has a 3xx status code +func (o *DescribeDeviceTypesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device types default response has a 4xx status code +func (o *DescribeDeviceTypesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device types default response has a 5xx status code +func (o *DescribeDeviceTypesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device types default response a status code equal to that given +func (o *DescribeDeviceTypesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceTypesDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes][%d] describeDeviceTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypesDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes][%d] describeDeviceTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypesDefault) GetPayload() *DescribeDeviceTypesDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceTypesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceTypesDefaultBody describe device types default body +swagger:model DescribeDeviceTypesDefaultBody +*/ +type DescribeDeviceTypesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device types default body +func (o *DescribeDeviceTypesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypes default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceTypesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypes default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device types default body based on the context it is used +func (o *DescribeDeviceTypesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceTypesOKBody describe device types o k body +swagger:model DescribeDeviceTypesOKBody +*/ +type DescribeDeviceTypesOKBody struct { + + // result + Result *models.DeviceTypeList `json:"result,omitempty"` +} + +// Validate validates this describe device types o k body +func (o *DescribeDeviceTypesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device types o k body based on the context it is used +func (o *DescribeDeviceTypesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_volumes_by_device_type_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_volumes_by_device_type_parameters.go new file mode 100644 index 0000000..70cec8c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_volumes_by_device_type_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeVolumesByDeviceTypeParams creates a new DescribeVolumesByDeviceTypeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeVolumesByDeviceTypeParams() *DescribeVolumesByDeviceTypeParams { + return &DescribeVolumesByDeviceTypeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeVolumesByDeviceTypeParamsWithTimeout creates a new DescribeVolumesByDeviceTypeParams object +// with the ability to set a timeout on a request. +func NewDescribeVolumesByDeviceTypeParamsWithTimeout(timeout time.Duration) *DescribeVolumesByDeviceTypeParams { + return &DescribeVolumesByDeviceTypeParams{ + timeout: timeout, + } +} + +// NewDescribeVolumesByDeviceTypeParamsWithContext creates a new DescribeVolumesByDeviceTypeParams object +// with the ability to set a context for a request. +func NewDescribeVolumesByDeviceTypeParamsWithContext(ctx context.Context) *DescribeVolumesByDeviceTypeParams { + return &DescribeVolumesByDeviceTypeParams{ + Context: ctx, + } +} + +// NewDescribeVolumesByDeviceTypeParamsWithHTTPClient creates a new DescribeVolumesByDeviceTypeParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeVolumesByDeviceTypeParamsWithHTTPClient(client *http.Client) *DescribeVolumesByDeviceTypeParams { + return &DescribeVolumesByDeviceTypeParams{ + HTTPClient: client, + } +} + +/* DescribeVolumesByDeviceTypeParams contains all the parameters to send to the API endpoint + for the describe volumes by device type operation. + + Typically these are written to a http.Request. +*/ +type DescribeVolumesByDeviceTypeParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // DeviceTypeID. + DeviceTypeID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe volumes by device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeVolumesByDeviceTypeParams) WithDefaults() *DescribeVolumesByDeviceTypeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe volumes by device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeVolumesByDeviceTypeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) WithTimeout(timeout time.Duration) *DescribeVolumesByDeviceTypeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) WithContext(ctx context.Context) *DescribeVolumesByDeviceTypeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) WithHTTPClient(client *http.Client) *DescribeVolumesByDeviceTypeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) WithAuthorization(authorization string) *DescribeVolumesByDeviceTypeParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) WithBmpLanguage(bmpLanguage *string) *DescribeVolumesByDeviceTypeParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) WithBmpUserID(bmpUserID *string) *DescribeVolumesByDeviceTypeParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) WithDeviceTypeID(deviceTypeID string) *DescribeVolumesByDeviceTypeParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) SetDeviceTypeID(deviceTypeID string) { + o.DeviceTypeID = deviceTypeID +} + +// WithTraceID adds the traceID to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) WithTraceID(traceID string) *DescribeVolumesByDeviceTypeParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe volumes by device type params +func (o *DescribeVolumesByDeviceTypeParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeVolumesByDeviceTypeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_type_id + if err := r.SetPathParam("device_type_id", o.DeviceTypeID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_volumes_by_device_type_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_volumes_by_device_type_responses.go new file mode 100644 index 0000000..e8ebd05 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_volumes_by_device_type_responses.go @@ -0,0 +1,415 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeVolumesByDeviceTypeReader is a Reader for the DescribeVolumesByDeviceType structure. +type DescribeVolumesByDeviceTypeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeVolumesByDeviceTypeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeVolumesByDeviceTypeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeVolumesByDeviceTypeDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeVolumesByDeviceTypeOK creates a DescribeVolumesByDeviceTypeOK with default headers values +func NewDescribeVolumesByDeviceTypeOK() *DescribeVolumesByDeviceTypeOK { + return &DescribeVolumesByDeviceTypeOK{} +} + +/* DescribeVolumesByDeviceTypeOK describes a response with status code 200, with default header values. + +A DescribeVolumesByDeviceTypeResult is an response struct that is used to describe get sshkey list. +*/ +type DescribeVolumesByDeviceTypeOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeVolumesByDeviceTypeOKBody +} + +// IsSuccess returns true when this describe volumes by device type o k response has a 2xx status code +func (o *DescribeVolumesByDeviceTypeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe volumes by device type o k response has a 3xx status code +func (o *DescribeVolumesByDeviceTypeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe volumes by device type o k response has a 4xx status code +func (o *DescribeVolumesByDeviceTypeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe volumes by device type o k response has a 5xx status code +func (o *DescribeVolumesByDeviceTypeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe volumes by device type o k response a status code equal to that given +func (o *DescribeVolumesByDeviceTypeOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeVolumesByDeviceTypeOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}/describeVolumes][%d] describeVolumesByDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DescribeVolumesByDeviceTypeOK) String() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}/describeVolumes][%d] describeVolumesByDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DescribeVolumesByDeviceTypeOK) GetPayload() *DescribeVolumesByDeviceTypeOKBody { + return o.Payload +} + +func (o *DescribeVolumesByDeviceTypeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeVolumesByDeviceTypeOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeVolumesByDeviceTypeDefault creates a DescribeVolumesByDeviceTypeDefault with default headers values +func NewDescribeVolumesByDeviceTypeDefault(code int) *DescribeVolumesByDeviceTypeDefault { + return &DescribeVolumesByDeviceTypeDefault{ + _statusCode: code, + } +} + +/* DescribeVolumesByDeviceTypeDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeVolumesByDeviceTypeDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeVolumesByDeviceTypeDefaultBody +} + +// Code gets the status code for the describe volumes by device type default response +func (o *DescribeVolumesByDeviceTypeDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe volumes by device type default response has a 2xx status code +func (o *DescribeVolumesByDeviceTypeDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe volumes by device type default response has a 3xx status code +func (o *DescribeVolumesByDeviceTypeDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe volumes by device type default response has a 4xx status code +func (o *DescribeVolumesByDeviceTypeDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe volumes by device type default response has a 5xx status code +func (o *DescribeVolumesByDeviceTypeDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe volumes by device type default response a status code equal to that given +func (o *DescribeVolumesByDeviceTypeDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeVolumesByDeviceTypeDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}/describeVolumes][%d] describeVolumesByDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeVolumesByDeviceTypeDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}/describeVolumes][%d] describeVolumesByDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeVolumesByDeviceTypeDefault) GetPayload() *DescribeVolumesByDeviceTypeDefaultBody { + return o.Payload +} + +func (o *DescribeVolumesByDeviceTypeDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeVolumesByDeviceTypeDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeVolumesByDeviceTypeDefaultBody describe volumes by device type default body +swagger:model DescribeVolumesByDeviceTypeDefaultBody +*/ +type DescribeVolumesByDeviceTypeDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe volumes by device type default body +func (o *DescribeVolumesByDeviceTypeDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeVolumesByDeviceTypeDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeVolumesByDeviceType default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeVolumesByDeviceTypeDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeVolumesByDeviceType default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeVolumesByDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeVolumesByDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe volumes by device type default body based on the context it is used +func (o *DescribeVolumesByDeviceTypeDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeVolumesByDeviceTypeDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeVolumesByDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeVolumesByDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeVolumesByDeviceTypeDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeVolumesByDeviceTypeDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeVolumesByDeviceTypeDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeVolumesByDeviceTypeOKBody describe volumes by device type o k body +swagger:model DescribeVolumesByDeviceTypeOKBody +*/ +type DescribeVolumesByDeviceTypeOKBody struct { + + // result + Result []*models.VolumeIt `json:"result"` +} + +// Validate validates this describe volumes by device type o k body +func (o *DescribeVolumesByDeviceTypeOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeVolumesByDeviceTypeOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + for i := 0; i < len(o.Result); i++ { + if swag.IsZero(o.Result[i]) { // not required + continue + } + + if o.Result[i] != nil { + if err := o.Result[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeVolumesByDeviceTypeOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeVolumesByDeviceTypeOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this describe volumes by device type o k body based on the context it is used +func (o *DescribeVolumesByDeviceTypeOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeVolumesByDeviceTypeOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Result); i++ { + + if o.Result[i] != nil { + if err := o.Result[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeVolumesByDeviceTypeOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeVolumesByDeviceTypeOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeVolumesByDeviceTypeOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeVolumesByDeviceTypeOKBody) UnmarshalBinary(b []byte) error { + var res DescribeVolumesByDeviceTypeOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/device_type_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/device_type_client.go new file mode 100644 index 0000000..e0e4604 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/device_type_client.go @@ -0,0 +1,477 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new device type API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for device type API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + AssociatedImage(params *AssociatedImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AssociatedImageOK, error) + + CreateDeviceType(params *CreateDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateDeviceTypeOK, error) + + DeleteDeviceType(params *DeleteDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteDeviceTypeOK, error) + + DescribeDeviceType(params *DescribeDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeOK, error) + + DescribeDeviceTypeImagePartitions(params *DescribeDeviceTypeImagePartitionsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeImagePartitionsOK, error) + + DescribeDeviceTypeImages(params *DescribeDeviceTypeImagesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeImagesOK, error) + + DescribeDeviceTypeRaids(params *DescribeDeviceTypeRaidsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeRaidsOK, error) + + DescribeDeviceTypes(params *DescribeDeviceTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypesOK, error) + + DescribeVolumesByDeviceType(params *DescribeVolumesByDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeVolumesByDeviceTypeOK, error) + + DissociatedImage(params *DissociatedImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DissociatedImageOK, error) + + ModifyDeviceType(params *ModifyDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyDeviceTypeOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + AssociatedImage AssociatedImage 机型绑定镜像 +*/ +func (a *Client) AssociatedImage(params *AssociatedImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AssociatedImageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewAssociatedImageParams() + } + op := &runtime.ClientOperation{ + ID: "associatedImage", + Method: "POST", + PathPattern: "/deviceTypes/associatedImage", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &AssociatedImageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*AssociatedImageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*AssociatedImageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + CreateDeviceType CreateDeviceType 添加机型 +*/ +func (a *Client) CreateDeviceType(params *CreateDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateDeviceTypeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateDeviceTypeParams() + } + op := &runtime.ClientOperation{ + ID: "createDeviceType", + Method: "POST", + PathPattern: "/deviceTypes", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateDeviceTypeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateDeviceTypeOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateDeviceTypeDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteDeviceType DeleteDeviceType 删除机型 +*/ +func (a *Client) DeleteDeviceType(params *DeleteDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteDeviceTypeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteDeviceTypeParams() + } + op := &runtime.ClientOperation{ + ID: "deleteDeviceType", + Method: "DELETE", + PathPattern: "/deviceTypes/{device_type_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteDeviceTypeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteDeviceTypeOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteDeviceTypeDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceType DescribeDeviceType 获取机型详情 +*/ +func (a *Client) DescribeDeviceType(params *DescribeDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceTypeParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceType", + Method: "GET", + PathPattern: "/deviceTypes/{device_type_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceTypeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceTypeOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceTypeDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceTypeImagePartitions QueryDeviceTypeImagePartition 根据机型,镜像,获取分区 +*/ +func (a *Client) DescribeDeviceTypeImagePartitions(params *DescribeDeviceTypeImagePartitionsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeImagePartitionsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceTypeImagePartitionsParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceTypeImagePartitions", + Method: "GET", + PathPattern: "/deviceTypes/deviceTypeImagePartition", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceTypeImagePartitionsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceTypeImagePartitionsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceTypeImagePartitionsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceTypeImages QueryDeviceTypeImage 根据机型获取镜像 +*/ +func (a *Client) DescribeDeviceTypeImages(params *DescribeDeviceTypeImagesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeImagesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceTypeImagesParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceTypeImages", + Method: "GET", + PathPattern: "/deviceTypes/deviceTypeImage", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceTypeImagesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceTypeImagesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceTypeImagesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceTypeRaids DescribeDeviceTypeRaids 根据机型获取raid +*/ +func (a *Client) DescribeDeviceTypeRaids(params *DescribeDeviceTypeRaidsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeRaidsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceTypeRaidsParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceTypeRaids", + Method: "GET", + PathPattern: "/deviceTypes/deviceTypeRaid", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceTypeRaidsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceTypeRaidsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceTypeRaidsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceTypes DescribeDeviceTypes 获取机型列表 +*/ +func (a *Client) DescribeDeviceTypes(params *DescribeDeviceTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceTypesParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceTypes", + Method: "GET", + PathPattern: "/deviceTypes", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceTypesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceTypesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceTypesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeVolumesByDeviceType DescribeVolumesByDeviceType 根据机型获取volumes +*/ +func (a *Client) DescribeVolumesByDeviceType(params *DescribeVolumesByDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeVolumesByDeviceTypeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeVolumesByDeviceTypeParams() + } + op := &runtime.ClientOperation{ + ID: "describeVolumesByDeviceType", + Method: "GET", + PathPattern: "/deviceTypes/{device_type_id}/describeVolumes", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeVolumesByDeviceTypeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeVolumesByDeviceTypeOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeVolumesByDeviceTypeDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DissociatedImage DissociatedImage 机型解绑镜像 +*/ +func (a *Client) DissociatedImage(params *DissociatedImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DissociatedImageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDissociatedImageParams() + } + op := &runtime.ClientOperation{ + ID: "dissociatedImage", + Method: "DELETE", + PathPattern: "/deviceTypes/dissociatedImage", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DissociatedImageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DissociatedImageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DissociatedImageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyDeviceType ModifyDeviceType 修改机型信息 +*/ +func (a *Client) ModifyDeviceType(params *ModifyDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyDeviceTypeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyDeviceTypeParams() + } + op := &runtime.ClientOperation{ + ID: "modifyDeviceType", + Method: "PUT", + PathPattern: "/deviceTypes/{device_type_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyDeviceTypeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyDeviceTypeOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyDeviceTypeDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/dissociated_image_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/dissociated_image_parameters.go new file mode 100644 index 0000000..1cf4d75 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/dissociated_image_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewDissociatedImageParams creates a new DissociatedImageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDissociatedImageParams() *DissociatedImageParams { + return &DissociatedImageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDissociatedImageParamsWithTimeout creates a new DissociatedImageParams object +// with the ability to set a timeout on a request. +func NewDissociatedImageParamsWithTimeout(timeout time.Duration) *DissociatedImageParams { + return &DissociatedImageParams{ + timeout: timeout, + } +} + +// NewDissociatedImageParamsWithContext creates a new DissociatedImageParams object +// with the ability to set a context for a request. +func NewDissociatedImageParamsWithContext(ctx context.Context) *DissociatedImageParams { + return &DissociatedImageParams{ + Context: ctx, + } +} + +// NewDissociatedImageParamsWithHTTPClient creates a new DissociatedImageParams object +// with the ability to set a custom HTTPClient for a request. +func NewDissociatedImageParamsWithHTTPClient(client *http.Client) *DissociatedImageParams { + return &DissociatedImageParams{ + HTTPClient: client, + } +} + +/* DissociatedImageParams contains all the parameters to send to the API endpoint + for the dissociated image operation. + + Typically these are written to a http.Request. +*/ +type DissociatedImageParams struct { + + // Body. + Body *models.DissociatedImageRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the dissociated image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DissociatedImageParams) WithDefaults() *DissociatedImageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the dissociated image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DissociatedImageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the dissociated image params +func (o *DissociatedImageParams) WithTimeout(timeout time.Duration) *DissociatedImageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the dissociated image params +func (o *DissociatedImageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the dissociated image params +func (o *DissociatedImageParams) WithContext(ctx context.Context) *DissociatedImageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the dissociated image params +func (o *DissociatedImageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the dissociated image params +func (o *DissociatedImageParams) WithHTTPClient(client *http.Client) *DissociatedImageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the dissociated image params +func (o *DissociatedImageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the dissociated image params +func (o *DissociatedImageParams) WithBody(body *models.DissociatedImageRequest) *DissociatedImageParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the dissociated image params +func (o *DissociatedImageParams) SetBody(body *models.DissociatedImageRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the dissociated image params +func (o *DissociatedImageParams) WithAuthorization(authorization string) *DissociatedImageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the dissociated image params +func (o *DissociatedImageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the dissociated image params +func (o *DissociatedImageParams) WithBmpLanguage(bmpLanguage *string) *DissociatedImageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the dissociated image params +func (o *DissociatedImageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the dissociated image params +func (o *DissociatedImageParams) WithBmpUserID(bmpUserID *string) *DissociatedImageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the dissociated image params +func (o *DissociatedImageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the dissociated image params +func (o *DissociatedImageParams) WithTraceID(traceID string) *DissociatedImageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the dissociated image params +func (o *DissociatedImageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DissociatedImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/dissociated_image_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/dissociated_image_responses.go new file mode 100644 index 0000000..09cb2e2 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/dissociated_image_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DissociatedImageReader is a Reader for the DissociatedImage structure. +type DissociatedImageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DissociatedImageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDissociatedImageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDissociatedImageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDissociatedImageOK creates a DissociatedImageOK with default headers values +func NewDissociatedImageOK() *DissociatedImageOK { + return &DissociatedImageOK{} +} + +/* DissociatedImageOK describes a response with status code 200, with default header values. + +A DissociatedImageResult is an response struct that is used to dissociated image result. +*/ +type DissociatedImageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DissociatedImageOKBody +} + +// IsSuccess returns true when this dissociated image o k response has a 2xx status code +func (o *DissociatedImageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this dissociated image o k response has a 3xx status code +func (o *DissociatedImageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this dissociated image o k response has a 4xx status code +func (o *DissociatedImageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this dissociated image o k response has a 5xx status code +func (o *DissociatedImageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this dissociated image o k response a status code equal to that given +func (o *DissociatedImageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DissociatedImageOK) Error() string { + return fmt.Sprintf("[DELETE /deviceTypes/dissociatedImage][%d] dissociatedImageOK %+v", 200, o.Payload) +} + +func (o *DissociatedImageOK) String() string { + return fmt.Sprintf("[DELETE /deviceTypes/dissociatedImage][%d] dissociatedImageOK %+v", 200, o.Payload) +} + +func (o *DissociatedImageOK) GetPayload() *DissociatedImageOKBody { + return o.Payload +} + +func (o *DissociatedImageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DissociatedImageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDissociatedImageDefault creates a DissociatedImageDefault with default headers values +func NewDissociatedImageDefault(code int) *DissociatedImageDefault { + return &DissociatedImageDefault{ + _statusCode: code, + } +} + +/* DissociatedImageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DissociatedImageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DissociatedImageDefaultBody +} + +// Code gets the status code for the dissociated image default response +func (o *DissociatedImageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this dissociated image default response has a 2xx status code +func (o *DissociatedImageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this dissociated image default response has a 3xx status code +func (o *DissociatedImageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this dissociated image default response has a 4xx status code +func (o *DissociatedImageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this dissociated image default response has a 5xx status code +func (o *DissociatedImageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this dissociated image default response a status code equal to that given +func (o *DissociatedImageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DissociatedImageDefault) Error() string { + return fmt.Sprintf("[DELETE /deviceTypes/dissociatedImage][%d] dissociatedImage default %+v", o._statusCode, o.Payload) +} + +func (o *DissociatedImageDefault) String() string { + return fmt.Sprintf("[DELETE /deviceTypes/dissociatedImage][%d] dissociatedImage default %+v", o._statusCode, o.Payload) +} + +func (o *DissociatedImageDefault) GetPayload() *DissociatedImageDefaultBody { + return o.Payload +} + +func (o *DissociatedImageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DissociatedImageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DissociatedImageDefaultBody dissociated image default body +swagger:model DissociatedImageDefaultBody +*/ +type DissociatedImageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this dissociated image default body +func (o *DissociatedImageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedImageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("dissociatedImage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DissociatedImageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("dissociatedImage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this dissociated image default body based on the context it is used +func (o *DissociatedImageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedImageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DissociatedImageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DissociatedImageDefaultBody) UnmarshalBinary(b []byte) error { + var res DissociatedImageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DissociatedImageOKBody dissociated image o k body +swagger:model DissociatedImageOKBody +*/ +type DissociatedImageOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this dissociated image o k body +func (o *DissociatedImageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedImageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this dissociated image o k body based on the context it is used +func (o *DissociatedImageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedImageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DissociatedImageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DissociatedImageOKBody) UnmarshalBinary(b []byte) error { + var res DissociatedImageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/modify_device_type_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/modify_device_type_parameters.go new file mode 100644 index 0000000..1e67b29 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/modify_device_type_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyDeviceTypeParams creates a new ModifyDeviceTypeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyDeviceTypeParams() *ModifyDeviceTypeParams { + return &ModifyDeviceTypeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyDeviceTypeParamsWithTimeout creates a new ModifyDeviceTypeParams object +// with the ability to set a timeout on a request. +func NewModifyDeviceTypeParamsWithTimeout(timeout time.Duration) *ModifyDeviceTypeParams { + return &ModifyDeviceTypeParams{ + timeout: timeout, + } +} + +// NewModifyDeviceTypeParamsWithContext creates a new ModifyDeviceTypeParams object +// with the ability to set a context for a request. +func NewModifyDeviceTypeParamsWithContext(ctx context.Context) *ModifyDeviceTypeParams { + return &ModifyDeviceTypeParams{ + Context: ctx, + } +} + +// NewModifyDeviceTypeParamsWithHTTPClient creates a new ModifyDeviceTypeParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyDeviceTypeParamsWithHTTPClient(client *http.Client) *ModifyDeviceTypeParams { + return &ModifyDeviceTypeParams{ + HTTPClient: client, + } +} + +/* ModifyDeviceTypeParams contains all the parameters to send to the API endpoint + for the modify device type operation. + + Typically these are written to a http.Request. +*/ +type ModifyDeviceTypeParams struct { + + // Body. + Body *models.ModifyDeviceTypeRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // DeviceTypeID. + DeviceTypeID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyDeviceTypeParams) WithDefaults() *ModifyDeviceTypeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyDeviceTypeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify device type params +func (o *ModifyDeviceTypeParams) WithTimeout(timeout time.Duration) *ModifyDeviceTypeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify device type params +func (o *ModifyDeviceTypeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify device type params +func (o *ModifyDeviceTypeParams) WithContext(ctx context.Context) *ModifyDeviceTypeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify device type params +func (o *ModifyDeviceTypeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify device type params +func (o *ModifyDeviceTypeParams) WithHTTPClient(client *http.Client) *ModifyDeviceTypeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify device type params +func (o *ModifyDeviceTypeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify device type params +func (o *ModifyDeviceTypeParams) WithBody(body *models.ModifyDeviceTypeRequest) *ModifyDeviceTypeParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify device type params +func (o *ModifyDeviceTypeParams) SetBody(body *models.ModifyDeviceTypeRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify device type params +func (o *ModifyDeviceTypeParams) WithAuthorization(authorization string) *ModifyDeviceTypeParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify device type params +func (o *ModifyDeviceTypeParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify device type params +func (o *ModifyDeviceTypeParams) WithBmpLanguage(bmpLanguage *string) *ModifyDeviceTypeParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify device type params +func (o *ModifyDeviceTypeParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify device type params +func (o *ModifyDeviceTypeParams) WithBmpUserID(bmpUserID *string) *ModifyDeviceTypeParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify device type params +func (o *ModifyDeviceTypeParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the modify device type params +func (o *ModifyDeviceTypeParams) WithDeviceTypeID(deviceTypeID string) *ModifyDeviceTypeParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the modify device type params +func (o *ModifyDeviceTypeParams) SetDeviceTypeID(deviceTypeID string) { + o.DeviceTypeID = deviceTypeID +} + +// WithTraceID adds the traceID to the modify device type params +func (o *ModifyDeviceTypeParams) WithTraceID(traceID string) *ModifyDeviceTypeParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify device type params +func (o *ModifyDeviceTypeParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyDeviceTypeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_type_id + if err := r.SetPathParam("device_type_id", o.DeviceTypeID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/modify_device_type_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/modify_device_type_responses.go new file mode 100644 index 0000000..339a323 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/device_type/modify_device_type_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyDeviceTypeReader is a Reader for the ModifyDeviceType structure. +type ModifyDeviceTypeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyDeviceTypeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyDeviceTypeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyDeviceTypeDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyDeviceTypeOK creates a ModifyDeviceTypeOK with default headers values +func NewModifyDeviceTypeOK() *ModifyDeviceTypeOK { + return &ModifyDeviceTypeOK{} +} + +/* ModifyDeviceTypeOK describes a response with status code 200, with default header values. + +A ModifyDeviceTypeResult is an response struct that is used to modify device type. +*/ +type ModifyDeviceTypeOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyDeviceTypeOKBody +} + +// IsSuccess returns true when this modify device type o k response has a 2xx status code +func (o *ModifyDeviceTypeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify device type o k response has a 3xx status code +func (o *ModifyDeviceTypeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify device type o k response has a 4xx status code +func (o *ModifyDeviceTypeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify device type o k response has a 5xx status code +func (o *ModifyDeviceTypeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify device type o k response a status code equal to that given +func (o *ModifyDeviceTypeOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyDeviceTypeOK) Error() string { + return fmt.Sprintf("[PUT /deviceTypes/{device_type_id}][%d] modifyDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *ModifyDeviceTypeOK) String() string { + return fmt.Sprintf("[PUT /deviceTypes/{device_type_id}][%d] modifyDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *ModifyDeviceTypeOK) GetPayload() *ModifyDeviceTypeOKBody { + return o.Payload +} + +func (o *ModifyDeviceTypeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyDeviceTypeOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyDeviceTypeDefault creates a ModifyDeviceTypeDefault with default headers values +func NewModifyDeviceTypeDefault(code int) *ModifyDeviceTypeDefault { + return &ModifyDeviceTypeDefault{ + _statusCode: code, + } +} + +/* ModifyDeviceTypeDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyDeviceTypeDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyDeviceTypeDefaultBody +} + +// Code gets the status code for the modify device type default response +func (o *ModifyDeviceTypeDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify device type default response has a 2xx status code +func (o *ModifyDeviceTypeDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify device type default response has a 3xx status code +func (o *ModifyDeviceTypeDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify device type default response has a 4xx status code +func (o *ModifyDeviceTypeDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify device type default response has a 5xx status code +func (o *ModifyDeviceTypeDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify device type default response a status code equal to that given +func (o *ModifyDeviceTypeDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyDeviceTypeDefault) Error() string { + return fmt.Sprintf("[PUT /deviceTypes/{device_type_id}][%d] modifyDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyDeviceTypeDefault) String() string { + return fmt.Sprintf("[PUT /deviceTypes/{device_type_id}][%d] modifyDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyDeviceTypeDefault) GetPayload() *ModifyDeviceTypeDefaultBody { + return o.Payload +} + +func (o *ModifyDeviceTypeDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyDeviceTypeDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyDeviceTypeDefaultBody modify device type default body +swagger:model ModifyDeviceTypeDefaultBody +*/ +type ModifyDeviceTypeDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify device type default body +func (o *ModifyDeviceTypeDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceTypeDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyDeviceType default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyDeviceTypeDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyDeviceType default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify device type default body based on the context it is used +func (o *ModifyDeviceTypeDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceTypeDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyDeviceTypeDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyDeviceTypeDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyDeviceTypeDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyDeviceTypeOKBody modify device type o k body +swagger:model ModifyDeviceTypeOKBody +*/ +type ModifyDeviceTypeOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify device type o k body +func (o *ModifyDeviceTypeOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceTypeOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify device type o k body based on the context it is used +func (o *ModifyDeviceTypeOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceTypeOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyDeviceTypeOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyDeviceTypeOKBody) UnmarshalBinary(b []byte) error { + var res ModifyDeviceTypeOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/create_idc_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/create_idc_parameters.go new file mode 100644 index 0000000..ae9f244 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/create_idc_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateIdcParams creates a new CreateIdcParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateIdcParams() *CreateIdcParams { + return &CreateIdcParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateIdcParamsWithTimeout creates a new CreateIdcParams object +// with the ability to set a timeout on a request. +func NewCreateIdcParamsWithTimeout(timeout time.Duration) *CreateIdcParams { + return &CreateIdcParams{ + timeout: timeout, + } +} + +// NewCreateIdcParamsWithContext creates a new CreateIdcParams object +// with the ability to set a context for a request. +func NewCreateIdcParamsWithContext(ctx context.Context) *CreateIdcParams { + return &CreateIdcParams{ + Context: ctx, + } +} + +// NewCreateIdcParamsWithHTTPClient creates a new CreateIdcParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateIdcParamsWithHTTPClient(client *http.Client) *CreateIdcParams { + return &CreateIdcParams{ + HTTPClient: client, + } +} + +/* CreateIdcParams contains all the parameters to send to the API endpoint + for the create idc operation. + + Typically these are written to a http.Request. +*/ +type CreateIdcParams struct { + + // Body. + Body *models.CreateIdcRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateIdcParams) WithDefaults() *CreateIdcParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateIdcParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create idc params +func (o *CreateIdcParams) WithTimeout(timeout time.Duration) *CreateIdcParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create idc params +func (o *CreateIdcParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create idc params +func (o *CreateIdcParams) WithContext(ctx context.Context) *CreateIdcParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create idc params +func (o *CreateIdcParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create idc params +func (o *CreateIdcParams) WithHTTPClient(client *http.Client) *CreateIdcParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create idc params +func (o *CreateIdcParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create idc params +func (o *CreateIdcParams) WithBody(body *models.CreateIdcRequest) *CreateIdcParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create idc params +func (o *CreateIdcParams) SetBody(body *models.CreateIdcRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create idc params +func (o *CreateIdcParams) WithAuthorization(authorization string) *CreateIdcParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create idc params +func (o *CreateIdcParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create idc params +func (o *CreateIdcParams) WithBmpLanguage(bmpLanguage *string) *CreateIdcParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create idc params +func (o *CreateIdcParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create idc params +func (o *CreateIdcParams) WithBmpUserID(bmpUserID *string) *CreateIdcParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create idc params +func (o *CreateIdcParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create idc params +func (o *CreateIdcParams) WithTraceID(traceID string) *CreateIdcParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create idc params +func (o *CreateIdcParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateIdcParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/create_idc_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/create_idc_responses.go new file mode 100644 index 0000000..c2a1d74 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/create_idc_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateIdcReader is a Reader for the CreateIdc structure. +type CreateIdcReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateIdcReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateIdcOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateIdcDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateIdcOK creates a CreateIdcOK with default headers values +func NewCreateIdcOK() *CreateIdcOK { + return &CreateIdcOK{} +} + +/* CreateIdcOK describes a response with status code 200, with default header values. + +A CreateIdcResult is an response struct that is used to describe create idc result. +*/ +type CreateIdcOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateIdcOKBody +} + +// IsSuccess returns true when this create idc o k response has a 2xx status code +func (o *CreateIdcOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create idc o k response has a 3xx status code +func (o *CreateIdcOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create idc o k response has a 4xx status code +func (o *CreateIdcOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create idc o k response has a 5xx status code +func (o *CreateIdcOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create idc o k response a status code equal to that given +func (o *CreateIdcOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateIdcOK) Error() string { + return fmt.Sprintf("[POST /idcs][%d] createIdcOK %+v", 200, o.Payload) +} + +func (o *CreateIdcOK) String() string { + return fmt.Sprintf("[POST /idcs][%d] createIdcOK %+v", 200, o.Payload) +} + +func (o *CreateIdcOK) GetPayload() *CreateIdcOKBody { + return o.Payload +} + +func (o *CreateIdcOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateIdcOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateIdcDefault creates a CreateIdcDefault with default headers values +func NewCreateIdcDefault(code int) *CreateIdcDefault { + return &CreateIdcDefault{ + _statusCode: code, + } +} + +/* CreateIdcDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateIdcDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateIdcDefaultBody +} + +// Code gets the status code for the create idc default response +func (o *CreateIdcDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create idc default response has a 2xx status code +func (o *CreateIdcDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create idc default response has a 3xx status code +func (o *CreateIdcDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create idc default response has a 4xx status code +func (o *CreateIdcDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create idc default response has a 5xx status code +func (o *CreateIdcDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create idc default response a status code equal to that given +func (o *CreateIdcDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateIdcDefault) Error() string { + return fmt.Sprintf("[POST /idcs][%d] createIdc default %+v", o._statusCode, o.Payload) +} + +func (o *CreateIdcDefault) String() string { + return fmt.Sprintf("[POST /idcs][%d] createIdc default %+v", o._statusCode, o.Payload) +} + +func (o *CreateIdcDefault) GetPayload() *CreateIdcDefaultBody { + return o.Payload +} + +func (o *CreateIdcDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateIdcDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateIdcDefaultBody create idc default body +swagger:model CreateIdcDefaultBody +*/ +type CreateIdcDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create idc default body +func (o *CreateIdcDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateIdcDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createIdc default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateIdcDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createIdc default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create idc default body based on the context it is used +func (o *CreateIdcDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateIdcDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateIdcDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateIdcDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateIdcDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateIdcOKBody create idc o k body +swagger:model CreateIdcOKBody +*/ +type CreateIdcOKBody struct { + + // result + Result *models.IdcID `json:"result,omitempty"` +} + +// Validate validates this create idc o k body +func (o *CreateIdcOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateIdcOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create idc o k body based on the context it is used +func (o *CreateIdcOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateIdcOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateIdcOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateIdcOKBody) UnmarshalBinary(b []byte) error { + var res CreateIdcOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/delete_idc_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/delete_idc_parameters.go new file mode 100644 index 0000000..4222fab --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/delete_idc_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteIdcParams creates a new DeleteIdcParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteIdcParams() *DeleteIdcParams { + return &DeleteIdcParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteIdcParamsWithTimeout creates a new DeleteIdcParams object +// with the ability to set a timeout on a request. +func NewDeleteIdcParamsWithTimeout(timeout time.Duration) *DeleteIdcParams { + return &DeleteIdcParams{ + timeout: timeout, + } +} + +// NewDeleteIdcParamsWithContext creates a new DeleteIdcParams object +// with the ability to set a context for a request. +func NewDeleteIdcParamsWithContext(ctx context.Context) *DeleteIdcParams { + return &DeleteIdcParams{ + Context: ctx, + } +} + +// NewDeleteIdcParamsWithHTTPClient creates a new DeleteIdcParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteIdcParamsWithHTTPClient(client *http.Client) *DeleteIdcParams { + return &DeleteIdcParams{ + HTTPClient: client, + } +} + +/* DeleteIdcParams contains all the parameters to send to the API endpoint + for the delete idc operation. + + Typically these are written to a http.Request. +*/ +type DeleteIdcParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // IdcID. + IdcID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteIdcParams) WithDefaults() *DeleteIdcParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteIdcParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete idc params +func (o *DeleteIdcParams) WithTimeout(timeout time.Duration) *DeleteIdcParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete idc params +func (o *DeleteIdcParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete idc params +func (o *DeleteIdcParams) WithContext(ctx context.Context) *DeleteIdcParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete idc params +func (o *DeleteIdcParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete idc params +func (o *DeleteIdcParams) WithHTTPClient(client *http.Client) *DeleteIdcParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete idc params +func (o *DeleteIdcParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete idc params +func (o *DeleteIdcParams) WithAuthorization(authorization string) *DeleteIdcParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete idc params +func (o *DeleteIdcParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete idc params +func (o *DeleteIdcParams) WithBmpLanguage(bmpLanguage *string) *DeleteIdcParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete idc params +func (o *DeleteIdcParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete idc params +func (o *DeleteIdcParams) WithBmpUserID(bmpUserID *string) *DeleteIdcParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete idc params +func (o *DeleteIdcParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIdcID adds the idcID to the delete idc params +func (o *DeleteIdcParams) WithIdcID(idcID string) *DeleteIdcParams { + o.SetIdcID(idcID) + return o +} + +// SetIdcID adds the idcId to the delete idc params +func (o *DeleteIdcParams) SetIdcID(idcID string) { + o.IdcID = idcID +} + +// WithTraceID adds the traceID to the delete idc params +func (o *DeleteIdcParams) WithTraceID(traceID string) *DeleteIdcParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete idc params +func (o *DeleteIdcParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteIdcParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param idc_id + if err := r.SetPathParam("idc_id", o.IdcID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/delete_idc_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/delete_idc_responses.go new file mode 100644 index 0000000..5aff303 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/delete_idc_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteIdcReader is a Reader for the DeleteIdc structure. +type DeleteIdcReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteIdcReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteIdcOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteIdcDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteIdcOK creates a DeleteIdcOK with default headers values +func NewDeleteIdcOK() *DeleteIdcOK { + return &DeleteIdcOK{} +} + +/* DeleteIdcOK describes a response with status code 200, with default header values. + +A DeleteIdcResult is an response struct that is used to delete idc. +*/ +type DeleteIdcOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteIdcOKBody +} + +// IsSuccess returns true when this delete idc o k response has a 2xx status code +func (o *DeleteIdcOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete idc o k response has a 3xx status code +func (o *DeleteIdcOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete idc o k response has a 4xx status code +func (o *DeleteIdcOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete idc o k response has a 5xx status code +func (o *DeleteIdcOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete idc o k response a status code equal to that given +func (o *DeleteIdcOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteIdcOK) Error() string { + return fmt.Sprintf("[DELETE /idcs/{idc_id}][%d] deleteIdcOK %+v", 200, o.Payload) +} + +func (o *DeleteIdcOK) String() string { + return fmt.Sprintf("[DELETE /idcs/{idc_id}][%d] deleteIdcOK %+v", 200, o.Payload) +} + +func (o *DeleteIdcOK) GetPayload() *DeleteIdcOKBody { + return o.Payload +} + +func (o *DeleteIdcOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteIdcOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteIdcDefault creates a DeleteIdcDefault with default headers values +func NewDeleteIdcDefault(code int) *DeleteIdcDefault { + return &DeleteIdcDefault{ + _statusCode: code, + } +} + +/* DeleteIdcDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteIdcDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteIdcDefaultBody +} + +// Code gets the status code for the delete idc default response +func (o *DeleteIdcDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete idc default response has a 2xx status code +func (o *DeleteIdcDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete idc default response has a 3xx status code +func (o *DeleteIdcDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete idc default response has a 4xx status code +func (o *DeleteIdcDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete idc default response has a 5xx status code +func (o *DeleteIdcDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete idc default response a status code equal to that given +func (o *DeleteIdcDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteIdcDefault) Error() string { + return fmt.Sprintf("[DELETE /idcs/{idc_id}][%d] deleteIdc default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteIdcDefault) String() string { + return fmt.Sprintf("[DELETE /idcs/{idc_id}][%d] deleteIdc default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteIdcDefault) GetPayload() *DeleteIdcDefaultBody { + return o.Payload +} + +func (o *DeleteIdcDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteIdcDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteIdcDefaultBody delete idc default body +swagger:model DeleteIdcDefaultBody +*/ +type DeleteIdcDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete idc default body +func (o *DeleteIdcDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteIdcDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteIdc default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteIdcDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteIdc default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete idc default body based on the context it is used +func (o *DeleteIdcDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteIdcDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteIdcDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteIdcDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteIdcDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteIdcOKBody delete idc o k body +swagger:model DeleteIdcOKBody +*/ +type DeleteIdcOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete idc o k body +func (o *DeleteIdcOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteIdcOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete idc o k body based on the context it is used +func (o *DeleteIdcOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteIdcOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteIdcOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteIdcOKBody) UnmarshalBinary(b []byte) error { + var res DeleteIdcOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idc_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idc_parameters.go new file mode 100644 index 0000000..8a6fc34 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idc_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeIdcParams creates a new DescribeIdcParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeIdcParams() *DescribeIdcParams { + return &DescribeIdcParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeIdcParamsWithTimeout creates a new DescribeIdcParams object +// with the ability to set a timeout on a request. +func NewDescribeIdcParamsWithTimeout(timeout time.Duration) *DescribeIdcParams { + return &DescribeIdcParams{ + timeout: timeout, + } +} + +// NewDescribeIdcParamsWithContext creates a new DescribeIdcParams object +// with the ability to set a context for a request. +func NewDescribeIdcParamsWithContext(ctx context.Context) *DescribeIdcParams { + return &DescribeIdcParams{ + Context: ctx, + } +} + +// NewDescribeIdcParamsWithHTTPClient creates a new DescribeIdcParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeIdcParamsWithHTTPClient(client *http.Client) *DescribeIdcParams { + return &DescribeIdcParams{ + HTTPClient: client, + } +} + +/* DescribeIdcParams contains all the parameters to send to the API endpoint + for the describe idc operation. + + Typically these are written to a http.Request. +*/ +type DescribeIdcParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // IdcID. + IdcID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeIdcParams) WithDefaults() *DescribeIdcParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeIdcParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe idc params +func (o *DescribeIdcParams) WithTimeout(timeout time.Duration) *DescribeIdcParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe idc params +func (o *DescribeIdcParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe idc params +func (o *DescribeIdcParams) WithContext(ctx context.Context) *DescribeIdcParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe idc params +func (o *DescribeIdcParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe idc params +func (o *DescribeIdcParams) WithHTTPClient(client *http.Client) *DescribeIdcParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe idc params +func (o *DescribeIdcParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe idc params +func (o *DescribeIdcParams) WithAuthorization(authorization string) *DescribeIdcParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe idc params +func (o *DescribeIdcParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe idc params +func (o *DescribeIdcParams) WithBmpLanguage(bmpLanguage *string) *DescribeIdcParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe idc params +func (o *DescribeIdcParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe idc params +func (o *DescribeIdcParams) WithBmpUserID(bmpUserID *string) *DescribeIdcParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe idc params +func (o *DescribeIdcParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIdcID adds the idcID to the describe idc params +func (o *DescribeIdcParams) WithIdcID(idcID string) *DescribeIdcParams { + o.SetIdcID(idcID) + return o +} + +// SetIdcID adds the idcId to the describe idc params +func (o *DescribeIdcParams) SetIdcID(idcID string) { + o.IdcID = idcID +} + +// WithTraceID adds the traceID to the describe idc params +func (o *DescribeIdcParams) WithTraceID(traceID string) *DescribeIdcParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe idc params +func (o *DescribeIdcParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeIdcParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param idc_id + if err := r.SetPathParam("idc_id", o.IdcID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idc_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idc_responses.go new file mode 100644 index 0000000..f0383d9 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idc_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeIdcReader is a Reader for the DescribeIdc structure. +type DescribeIdcReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeIdcReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeIdcOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeIdcDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeIdcOK creates a DescribeIdcOK with default headers values +func NewDescribeIdcOK() *DescribeIdcOK { + return &DescribeIdcOK{} +} + +/* DescribeIdcOK describes a response with status code 200, with default header values. + +A DescribeIdcResult is an response struct that is used to describe idc. +*/ +type DescribeIdcOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeIdcOKBody +} + +// IsSuccess returns true when this describe idc o k response has a 2xx status code +func (o *DescribeIdcOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe idc o k response has a 3xx status code +func (o *DescribeIdcOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe idc o k response has a 4xx status code +func (o *DescribeIdcOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe idc o k response has a 5xx status code +func (o *DescribeIdcOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe idc o k response a status code equal to that given +func (o *DescribeIdcOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeIdcOK) Error() string { + return fmt.Sprintf("[GET /idcs/{idc_id}][%d] describeIdcOK %+v", 200, o.Payload) +} + +func (o *DescribeIdcOK) String() string { + return fmt.Sprintf("[GET /idcs/{idc_id}][%d] describeIdcOK %+v", 200, o.Payload) +} + +func (o *DescribeIdcOK) GetPayload() *DescribeIdcOKBody { + return o.Payload +} + +func (o *DescribeIdcOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeIdcOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeIdcDefault creates a DescribeIdcDefault with default headers values +func NewDescribeIdcDefault(code int) *DescribeIdcDefault { + return &DescribeIdcDefault{ + _statusCode: code, + } +} + +/* DescribeIdcDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeIdcDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeIdcDefaultBody +} + +// Code gets the status code for the describe idc default response +func (o *DescribeIdcDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe idc default response has a 2xx status code +func (o *DescribeIdcDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe idc default response has a 3xx status code +func (o *DescribeIdcDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe idc default response has a 4xx status code +func (o *DescribeIdcDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe idc default response has a 5xx status code +func (o *DescribeIdcDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe idc default response a status code equal to that given +func (o *DescribeIdcDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeIdcDefault) Error() string { + return fmt.Sprintf("[GET /idcs/{idc_id}][%d] describeIdc default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeIdcDefault) String() string { + return fmt.Sprintf("[GET /idcs/{idc_id}][%d] describeIdc default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeIdcDefault) GetPayload() *DescribeIdcDefaultBody { + return o.Payload +} + +func (o *DescribeIdcDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeIdcDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeIdcDefaultBody describe idc default body +swagger:model DescribeIdcDefaultBody +*/ +type DescribeIdcDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe idc default body +func (o *DescribeIdcDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeIdc default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeIdcDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeIdc default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe idc default body based on the context it is used +func (o *DescribeIdcDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeIdcDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeIdcDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeIdcDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeIdcOKBody describe idc o k body +swagger:model DescribeIdcOKBody +*/ +type DescribeIdcOKBody struct { + + // result + Result *models.IdcInfo `json:"result,omitempty"` +} + +// Validate validates this describe idc o k body +func (o *DescribeIdcOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe idc o k body based on the context it is used +func (o *DescribeIdcOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeIdcOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeIdcOKBody) UnmarshalBinary(b []byte) error { + var res DescribeIdcOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idcs_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idcs_parameters.go new file mode 100644 index 0000000..b70ce2a --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idcs_parameters.go @@ -0,0 +1,430 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeIdcsParams creates a new DescribeIdcsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeIdcsParams() *DescribeIdcsParams { + return &DescribeIdcsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeIdcsParamsWithTimeout creates a new DescribeIdcsParams object +// with the ability to set a timeout on a request. +func NewDescribeIdcsParamsWithTimeout(timeout time.Duration) *DescribeIdcsParams { + return &DescribeIdcsParams{ + timeout: timeout, + } +} + +// NewDescribeIdcsParamsWithContext creates a new DescribeIdcsParams object +// with the ability to set a context for a request. +func NewDescribeIdcsParamsWithContext(ctx context.Context) *DescribeIdcsParams { + return &DescribeIdcsParams{ + Context: ctx, + } +} + +// NewDescribeIdcsParamsWithHTTPClient creates a new DescribeIdcsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeIdcsParamsWithHTTPClient(client *http.Client) *DescribeIdcsParams { + return &DescribeIdcsParams{ + HTTPClient: client, + } +} + +/* DescribeIdcsParams contains all the parameters to send to the API endpoint + for the describe idcs operation. + + Typically these are written to a http.Request. +*/ +type DescribeIdcsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否显示所有 + */ + IsAll *string + + /* Level. + + 机房等级 + */ + Level *string + + /* Name. + + 机房名称 + */ + Name *string + + /* NameEn. + + 机房英文名称 + */ + NameEn *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe idcs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeIdcsParams) WithDefaults() *DescribeIdcsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe idcs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeIdcsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe idcs params +func (o *DescribeIdcsParams) WithTimeout(timeout time.Duration) *DescribeIdcsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe idcs params +func (o *DescribeIdcsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe idcs params +func (o *DescribeIdcsParams) WithContext(ctx context.Context) *DescribeIdcsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe idcs params +func (o *DescribeIdcsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe idcs params +func (o *DescribeIdcsParams) WithHTTPClient(client *http.Client) *DescribeIdcsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe idcs params +func (o *DescribeIdcsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe idcs params +func (o *DescribeIdcsParams) WithAuthorization(authorization string) *DescribeIdcsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe idcs params +func (o *DescribeIdcsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe idcs params +func (o *DescribeIdcsParams) WithBmpLanguage(bmpLanguage *string) *DescribeIdcsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe idcs params +func (o *DescribeIdcsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe idcs params +func (o *DescribeIdcsParams) WithBmpUserID(bmpUserID *string) *DescribeIdcsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe idcs params +func (o *DescribeIdcsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe idcs params +func (o *DescribeIdcsParams) WithIsAll(isAll *string) *DescribeIdcsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe idcs params +func (o *DescribeIdcsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithLevel adds the level to the describe idcs params +func (o *DescribeIdcsParams) WithLevel(level *string) *DescribeIdcsParams { + o.SetLevel(level) + return o +} + +// SetLevel adds the level to the describe idcs params +func (o *DescribeIdcsParams) SetLevel(level *string) { + o.Level = level +} + +// WithName adds the name to the describe idcs params +func (o *DescribeIdcsParams) WithName(name *string) *DescribeIdcsParams { + o.SetName(name) + return o +} + +// SetName adds the name to the describe idcs params +func (o *DescribeIdcsParams) SetName(name *string) { + o.Name = name +} + +// WithNameEn adds the nameEn to the describe idcs params +func (o *DescribeIdcsParams) WithNameEn(nameEn *string) *DescribeIdcsParams { + o.SetNameEn(nameEn) + return o +} + +// SetNameEn adds the nameEn to the describe idcs params +func (o *DescribeIdcsParams) SetNameEn(nameEn *string) { + o.NameEn = nameEn +} + +// WithPageNumber adds the pageNumber to the describe idcs params +func (o *DescribeIdcsParams) WithPageNumber(pageNumber *int64) *DescribeIdcsParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe idcs params +func (o *DescribeIdcsParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe idcs params +func (o *DescribeIdcsParams) WithPageSize(pageSize *int64) *DescribeIdcsParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe idcs params +func (o *DescribeIdcsParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe idcs params +func (o *DescribeIdcsParams) WithTraceID(traceID string) *DescribeIdcsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe idcs params +func (o *DescribeIdcsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeIdcsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Level != nil { + + // query param level + var qrLevel string + + if o.Level != nil { + qrLevel = *o.Level + } + qLevel := qrLevel + if qLevel != "" { + + if err := r.SetQueryParam("level", qLevel); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.NameEn != nil { + + // query param nameEn + var qrNameEn string + + if o.NameEn != nil { + qrNameEn = *o.NameEn + } + qNameEn := qrNameEn + if qNameEn != "" { + + if err := r.SetQueryParam("nameEn", qNameEn); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idcs_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idcs_responses.go new file mode 100644 index 0000000..2f5ba8a --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idcs_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeIdcsReader is a Reader for the DescribeIdcs structure. +type DescribeIdcsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeIdcsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeIdcsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeIdcsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeIdcsOK creates a DescribeIdcsOK with default headers values +func NewDescribeIdcsOK() *DescribeIdcsOK { + return &DescribeIdcsOK{} +} + +/* DescribeIdcsOK describes a response with status code 200, with default header values. + +A DescribIdcsResult is an response struct that is used to describe idcs. +*/ +type DescribeIdcsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeIdcsOKBody +} + +// IsSuccess returns true when this describe idcs o k response has a 2xx status code +func (o *DescribeIdcsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe idcs o k response has a 3xx status code +func (o *DescribeIdcsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe idcs o k response has a 4xx status code +func (o *DescribeIdcsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe idcs o k response has a 5xx status code +func (o *DescribeIdcsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe idcs o k response a status code equal to that given +func (o *DescribeIdcsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeIdcsOK) Error() string { + return fmt.Sprintf("[GET /idcs][%d] describeIdcsOK %+v", 200, o.Payload) +} + +func (o *DescribeIdcsOK) String() string { + return fmt.Sprintf("[GET /idcs][%d] describeIdcsOK %+v", 200, o.Payload) +} + +func (o *DescribeIdcsOK) GetPayload() *DescribeIdcsOKBody { + return o.Payload +} + +func (o *DescribeIdcsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeIdcsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeIdcsDefault creates a DescribeIdcsDefault with default headers values +func NewDescribeIdcsDefault(code int) *DescribeIdcsDefault { + return &DescribeIdcsDefault{ + _statusCode: code, + } +} + +/* DescribeIdcsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeIdcsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeIdcsDefaultBody +} + +// Code gets the status code for the describe idcs default response +func (o *DescribeIdcsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe idcs default response has a 2xx status code +func (o *DescribeIdcsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe idcs default response has a 3xx status code +func (o *DescribeIdcsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe idcs default response has a 4xx status code +func (o *DescribeIdcsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe idcs default response has a 5xx status code +func (o *DescribeIdcsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe idcs default response a status code equal to that given +func (o *DescribeIdcsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeIdcsDefault) Error() string { + return fmt.Sprintf("[GET /idcs][%d] describeIdcs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeIdcsDefault) String() string { + return fmt.Sprintf("[GET /idcs][%d] describeIdcs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeIdcsDefault) GetPayload() *DescribeIdcsDefaultBody { + return o.Payload +} + +func (o *DescribeIdcsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeIdcsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeIdcsDefaultBody describe idcs default body +swagger:model DescribeIdcsDefaultBody +*/ +type DescribeIdcsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe idcs default body +func (o *DescribeIdcsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeIdcs default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeIdcsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeIdcs default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcs default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe idcs default body based on the context it is used +func (o *DescribeIdcsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcs default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeIdcsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeIdcsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeIdcsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeIdcsOKBody describe idcs o k body +swagger:model DescribeIdcsOKBody +*/ +type DescribeIdcsOKBody struct { + + // result + Result *models.IdcList `json:"result,omitempty"` +} + +// Validate validates this describe idcs o k body +func (o *DescribeIdcsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe idcs o k body based on the context it is used +func (o *DescribeIdcsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeIdcsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeIdcsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeIdcsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/idc_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/idc_client.go new file mode 100644 index 0000000..81b2591 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/idc_client.go @@ -0,0 +1,237 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new idc API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for idc API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateIdc(params *CreateIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateIdcOK, error) + + DeleteIdc(params *DeleteIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteIdcOK, error) + + DescribeIdc(params *DescribeIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeIdcOK, error) + + DescribeIdcs(params *DescribeIdcsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeIdcsOK, error) + + ModifyIdc(params *ModifyIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyIdcOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateIdc CreateIdc 创建idc(接口废弃,不对外开放) +*/ +func (a *Client) CreateIdc(params *CreateIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateIdcOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateIdcParams() + } + op := &runtime.ClientOperation{ + ID: "createIdc", + Method: "POST", + PathPattern: "/idcs", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateIdcReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateIdcOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateIdcDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteIdc DeleteIdc 删除idc +*/ +func (a *Client) DeleteIdc(params *DeleteIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteIdcOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteIdcParams() + } + op := &runtime.ClientOperation{ + ID: "deleteIdc", + Method: "DELETE", + PathPattern: "/idcs/{idc_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteIdcReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteIdcOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteIdcDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeIdc DescribeIdc 获取idc详情 +*/ +func (a *Client) DescribeIdc(params *DescribeIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeIdcOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeIdcParams() + } + op := &runtime.ClientOperation{ + ID: "describeIdc", + Method: "GET", + PathPattern: "/idcs/{idc_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeIdcReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeIdcOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeIdcDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeIdcs DescribeIdcs 获取idc列表 +*/ +func (a *Client) DescribeIdcs(params *DescribeIdcsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeIdcsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeIdcsParams() + } + op := &runtime.ClientOperation{ + ID: "describeIdcs", + Method: "GET", + PathPattern: "/idcs", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeIdcsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeIdcsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeIdcsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyIdc ModifyIdc 修改idc信息 +*/ +func (a *Client) ModifyIdc(params *ModifyIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyIdcOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyIdcParams() + } + op := &runtime.ClientOperation{ + ID: "modifyIdc", + Method: "PUT", + PathPattern: "/idcs/{idc_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyIdcReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyIdcOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyIdcDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/modify_idc_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/modify_idc_parameters.go new file mode 100644 index 0000000..41e22dc --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/modify_idc_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyIdcParams creates a new ModifyIdcParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyIdcParams() *ModifyIdcParams { + return &ModifyIdcParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyIdcParamsWithTimeout creates a new ModifyIdcParams object +// with the ability to set a timeout on a request. +func NewModifyIdcParamsWithTimeout(timeout time.Duration) *ModifyIdcParams { + return &ModifyIdcParams{ + timeout: timeout, + } +} + +// NewModifyIdcParamsWithContext creates a new ModifyIdcParams object +// with the ability to set a context for a request. +func NewModifyIdcParamsWithContext(ctx context.Context) *ModifyIdcParams { + return &ModifyIdcParams{ + Context: ctx, + } +} + +// NewModifyIdcParamsWithHTTPClient creates a new ModifyIdcParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyIdcParamsWithHTTPClient(client *http.Client) *ModifyIdcParams { + return &ModifyIdcParams{ + HTTPClient: client, + } +} + +/* ModifyIdcParams contains all the parameters to send to the API endpoint + for the modify idc operation. + + Typically these are written to a http.Request. +*/ +type ModifyIdcParams struct { + + // Body. + Body *models.ModifyIdcRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // IdcID. + IdcID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyIdcParams) WithDefaults() *ModifyIdcParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyIdcParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify idc params +func (o *ModifyIdcParams) WithTimeout(timeout time.Duration) *ModifyIdcParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify idc params +func (o *ModifyIdcParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify idc params +func (o *ModifyIdcParams) WithContext(ctx context.Context) *ModifyIdcParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify idc params +func (o *ModifyIdcParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify idc params +func (o *ModifyIdcParams) WithHTTPClient(client *http.Client) *ModifyIdcParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify idc params +func (o *ModifyIdcParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify idc params +func (o *ModifyIdcParams) WithBody(body *models.ModifyIdcRequest) *ModifyIdcParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify idc params +func (o *ModifyIdcParams) SetBody(body *models.ModifyIdcRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify idc params +func (o *ModifyIdcParams) WithAuthorization(authorization string) *ModifyIdcParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify idc params +func (o *ModifyIdcParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify idc params +func (o *ModifyIdcParams) WithBmpLanguage(bmpLanguage *string) *ModifyIdcParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify idc params +func (o *ModifyIdcParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify idc params +func (o *ModifyIdcParams) WithBmpUserID(bmpUserID *string) *ModifyIdcParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify idc params +func (o *ModifyIdcParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIdcID adds the idcID to the modify idc params +func (o *ModifyIdcParams) WithIdcID(idcID string) *ModifyIdcParams { + o.SetIdcID(idcID) + return o +} + +// SetIdcID adds the idcId to the modify idc params +func (o *ModifyIdcParams) SetIdcID(idcID string) { + o.IdcID = idcID +} + +// WithTraceID adds the traceID to the modify idc params +func (o *ModifyIdcParams) WithTraceID(traceID string) *ModifyIdcParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify idc params +func (o *ModifyIdcParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyIdcParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param idc_id + if err := r.SetPathParam("idc_id", o.IdcID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/modify_idc_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/modify_idc_responses.go new file mode 100644 index 0000000..fe29766 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/idc/modify_idc_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyIdcReader is a Reader for the ModifyIdc structure. +type ModifyIdcReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyIdcReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyIdcOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyIdcDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyIdcOK creates a ModifyIdcOK with default headers values +func NewModifyIdcOK() *ModifyIdcOK { + return &ModifyIdcOK{} +} + +/* ModifyIdcOK describes a response with status code 200, with default header values. + +A ModifyIdcResult is an response struct that is used to modify idc. +*/ +type ModifyIdcOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyIdcOKBody +} + +// IsSuccess returns true when this modify idc o k response has a 2xx status code +func (o *ModifyIdcOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify idc o k response has a 3xx status code +func (o *ModifyIdcOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify idc o k response has a 4xx status code +func (o *ModifyIdcOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify idc o k response has a 5xx status code +func (o *ModifyIdcOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify idc o k response a status code equal to that given +func (o *ModifyIdcOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyIdcOK) Error() string { + return fmt.Sprintf("[PUT /idcs/{idc_id}][%d] modifyIdcOK %+v", 200, o.Payload) +} + +func (o *ModifyIdcOK) String() string { + return fmt.Sprintf("[PUT /idcs/{idc_id}][%d] modifyIdcOK %+v", 200, o.Payload) +} + +func (o *ModifyIdcOK) GetPayload() *ModifyIdcOKBody { + return o.Payload +} + +func (o *ModifyIdcOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyIdcOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyIdcDefault creates a ModifyIdcDefault with default headers values +func NewModifyIdcDefault(code int) *ModifyIdcDefault { + return &ModifyIdcDefault{ + _statusCode: code, + } +} + +/* ModifyIdcDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyIdcDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyIdcDefaultBody +} + +// Code gets the status code for the modify idc default response +func (o *ModifyIdcDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify idc default response has a 2xx status code +func (o *ModifyIdcDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify idc default response has a 3xx status code +func (o *ModifyIdcDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify idc default response has a 4xx status code +func (o *ModifyIdcDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify idc default response has a 5xx status code +func (o *ModifyIdcDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify idc default response a status code equal to that given +func (o *ModifyIdcDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyIdcDefault) Error() string { + return fmt.Sprintf("[PUT /idcs/{idc_id}][%d] modifyIdc default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyIdcDefault) String() string { + return fmt.Sprintf("[PUT /idcs/{idc_id}][%d] modifyIdc default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyIdcDefault) GetPayload() *ModifyIdcDefaultBody { + return o.Payload +} + +func (o *ModifyIdcDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyIdcDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyIdcDefaultBody modify idc default body +swagger:model ModifyIdcDefaultBody +*/ +type ModifyIdcDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify idc default body +func (o *ModifyIdcDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyIdcDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyIdc default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyIdcDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyIdc default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify idc default body based on the context it is used +func (o *ModifyIdcDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyIdcDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyIdcDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyIdcDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyIdcDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyIdcOKBody modify idc o k body +swagger:model ModifyIdcOKBody +*/ +type ModifyIdcOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify idc o k body +func (o *ModifyIdcOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyIdcOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify idc o k body based on the context it is used +func (o *ModifyIdcOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyIdcOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyIdcOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyIdcOKBody) UnmarshalBinary(b []byte) error { + var res ModifyIdcOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/associated_device_type_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/associated_device_type_parameters.go new file mode 100644 index 0000000..a331625 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/associated_device_type_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewAssociatedDeviceTypeParams creates a new AssociatedDeviceTypeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewAssociatedDeviceTypeParams() *AssociatedDeviceTypeParams { + return &AssociatedDeviceTypeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewAssociatedDeviceTypeParamsWithTimeout creates a new AssociatedDeviceTypeParams object +// with the ability to set a timeout on a request. +func NewAssociatedDeviceTypeParamsWithTimeout(timeout time.Duration) *AssociatedDeviceTypeParams { + return &AssociatedDeviceTypeParams{ + timeout: timeout, + } +} + +// NewAssociatedDeviceTypeParamsWithContext creates a new AssociatedDeviceTypeParams object +// with the ability to set a context for a request. +func NewAssociatedDeviceTypeParamsWithContext(ctx context.Context) *AssociatedDeviceTypeParams { + return &AssociatedDeviceTypeParams{ + Context: ctx, + } +} + +// NewAssociatedDeviceTypeParamsWithHTTPClient creates a new AssociatedDeviceTypeParams object +// with the ability to set a custom HTTPClient for a request. +func NewAssociatedDeviceTypeParamsWithHTTPClient(client *http.Client) *AssociatedDeviceTypeParams { + return &AssociatedDeviceTypeParams{ + HTTPClient: client, + } +} + +/* AssociatedDeviceTypeParams contains all the parameters to send to the API endpoint + for the associated device type operation. + + Typically these are written to a http.Request. +*/ +type AssociatedDeviceTypeParams struct { + + // Body. + Body *models.AssociateDeviceTypeRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the associated device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AssociatedDeviceTypeParams) WithDefaults() *AssociatedDeviceTypeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the associated device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AssociatedDeviceTypeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the associated device type params +func (o *AssociatedDeviceTypeParams) WithTimeout(timeout time.Duration) *AssociatedDeviceTypeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the associated device type params +func (o *AssociatedDeviceTypeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the associated device type params +func (o *AssociatedDeviceTypeParams) WithContext(ctx context.Context) *AssociatedDeviceTypeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the associated device type params +func (o *AssociatedDeviceTypeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the associated device type params +func (o *AssociatedDeviceTypeParams) WithHTTPClient(client *http.Client) *AssociatedDeviceTypeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the associated device type params +func (o *AssociatedDeviceTypeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the associated device type params +func (o *AssociatedDeviceTypeParams) WithBody(body *models.AssociateDeviceTypeRequest) *AssociatedDeviceTypeParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the associated device type params +func (o *AssociatedDeviceTypeParams) SetBody(body *models.AssociateDeviceTypeRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the associated device type params +func (o *AssociatedDeviceTypeParams) WithAuthorization(authorization string) *AssociatedDeviceTypeParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the associated device type params +func (o *AssociatedDeviceTypeParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the associated device type params +func (o *AssociatedDeviceTypeParams) WithBmpLanguage(bmpLanguage *string) *AssociatedDeviceTypeParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the associated device type params +func (o *AssociatedDeviceTypeParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the associated device type params +func (o *AssociatedDeviceTypeParams) WithBmpUserID(bmpUserID *string) *AssociatedDeviceTypeParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the associated device type params +func (o *AssociatedDeviceTypeParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the associated device type params +func (o *AssociatedDeviceTypeParams) WithTraceID(traceID string) *AssociatedDeviceTypeParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the associated device type params +func (o *AssociatedDeviceTypeParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *AssociatedDeviceTypeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/associated_device_type_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/associated_device_type_responses.go new file mode 100644 index 0000000..3857d1f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/associated_device_type_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// AssociatedDeviceTypeReader is a Reader for the AssociatedDeviceType structure. +type AssociatedDeviceTypeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *AssociatedDeviceTypeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewAssociatedDeviceTypeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewAssociatedDeviceTypeDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewAssociatedDeviceTypeOK creates a AssociatedDeviceTypeOK with default headers values +func NewAssociatedDeviceTypeOK() *AssociatedDeviceTypeOK { + return &AssociatedDeviceTypeOK{} +} + +/* AssociatedDeviceTypeOK describes a response with status code 200, with default header values. + +AssociatedDeviceTypeOK associated device type o k +*/ +type AssociatedDeviceTypeOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *AssociatedDeviceTypeOKBody +} + +// IsSuccess returns true when this associated device type o k response has a 2xx status code +func (o *AssociatedDeviceTypeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this associated device type o k response has a 3xx status code +func (o *AssociatedDeviceTypeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this associated device type o k response has a 4xx status code +func (o *AssociatedDeviceTypeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this associated device type o k response has a 5xx status code +func (o *AssociatedDeviceTypeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this associated device type o k response a status code equal to that given +func (o *AssociatedDeviceTypeOK) IsCode(code int) bool { + return code == 200 +} + +func (o *AssociatedDeviceTypeOK) Error() string { + return fmt.Sprintf("[POST /images/associatedDeviceType][%d] associatedDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *AssociatedDeviceTypeOK) String() string { + return fmt.Sprintf("[POST /images/associatedDeviceType][%d] associatedDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *AssociatedDeviceTypeOK) GetPayload() *AssociatedDeviceTypeOKBody { + return o.Payload +} + +func (o *AssociatedDeviceTypeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AssociatedDeviceTypeOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAssociatedDeviceTypeDefault creates a AssociatedDeviceTypeDefault with default headers values +func NewAssociatedDeviceTypeDefault(code int) *AssociatedDeviceTypeDefault { + return &AssociatedDeviceTypeDefault{ + _statusCode: code, + } +} + +/* AssociatedDeviceTypeDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type AssociatedDeviceTypeDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *AssociatedDeviceTypeDefaultBody +} + +// Code gets the status code for the associated device type default response +func (o *AssociatedDeviceTypeDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this associated device type default response has a 2xx status code +func (o *AssociatedDeviceTypeDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this associated device type default response has a 3xx status code +func (o *AssociatedDeviceTypeDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this associated device type default response has a 4xx status code +func (o *AssociatedDeviceTypeDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this associated device type default response has a 5xx status code +func (o *AssociatedDeviceTypeDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this associated device type default response a status code equal to that given +func (o *AssociatedDeviceTypeDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *AssociatedDeviceTypeDefault) Error() string { + return fmt.Sprintf("[POST /images/associatedDeviceType][%d] associatedDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *AssociatedDeviceTypeDefault) String() string { + return fmt.Sprintf("[POST /images/associatedDeviceType][%d] associatedDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *AssociatedDeviceTypeDefault) GetPayload() *AssociatedDeviceTypeDefaultBody { + return o.Payload +} + +func (o *AssociatedDeviceTypeDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AssociatedDeviceTypeDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*AssociatedDeviceTypeDefaultBody associated device type default body +swagger:model AssociatedDeviceTypeDefaultBody +*/ +type AssociatedDeviceTypeDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this associated device type default body +func (o *AssociatedDeviceTypeDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedDeviceTypeDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("associatedDeviceType default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *AssociatedDeviceTypeDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("associatedDeviceType default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this associated device type default body based on the context it is used +func (o *AssociatedDeviceTypeDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedDeviceTypeDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AssociatedDeviceTypeDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AssociatedDeviceTypeDefaultBody) UnmarshalBinary(b []byte) error { + var res AssociatedDeviceTypeDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*AssociatedDeviceTypeOKBody associated device type o k body +swagger:model AssociatedDeviceTypeOKBody +*/ +type AssociatedDeviceTypeOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this associated device type o k body +func (o *AssociatedDeviceTypeOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedDeviceTypeOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this associated device type o k body based on the context it is used +func (o *AssociatedDeviceTypeOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedDeviceTypeOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AssociatedDeviceTypeOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AssociatedDeviceTypeOKBody) UnmarshalBinary(b []byte) error { + var res AssociatedDeviceTypeOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/create_image_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/create_image_parameters.go new file mode 100644 index 0000000..9bc6e9f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/create_image_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateImageParams creates a new CreateImageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateImageParams() *CreateImageParams { + return &CreateImageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateImageParamsWithTimeout creates a new CreateImageParams object +// with the ability to set a timeout on a request. +func NewCreateImageParamsWithTimeout(timeout time.Duration) *CreateImageParams { + return &CreateImageParams{ + timeout: timeout, + } +} + +// NewCreateImageParamsWithContext creates a new CreateImageParams object +// with the ability to set a context for a request. +func NewCreateImageParamsWithContext(ctx context.Context) *CreateImageParams { + return &CreateImageParams{ + Context: ctx, + } +} + +// NewCreateImageParamsWithHTTPClient creates a new CreateImageParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateImageParamsWithHTTPClient(client *http.Client) *CreateImageParams { + return &CreateImageParams{ + HTTPClient: client, + } +} + +/* CreateImageParams contains all the parameters to send to the API endpoint + for the create image operation. + + Typically these are written to a http.Request. +*/ +type CreateImageParams struct { + + // Body. + Body *models.CreateImageRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateImageParams) WithDefaults() *CreateImageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateImageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create image params +func (o *CreateImageParams) WithTimeout(timeout time.Duration) *CreateImageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create image params +func (o *CreateImageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create image params +func (o *CreateImageParams) WithContext(ctx context.Context) *CreateImageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create image params +func (o *CreateImageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create image params +func (o *CreateImageParams) WithHTTPClient(client *http.Client) *CreateImageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create image params +func (o *CreateImageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create image params +func (o *CreateImageParams) WithBody(body *models.CreateImageRequest) *CreateImageParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create image params +func (o *CreateImageParams) SetBody(body *models.CreateImageRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create image params +func (o *CreateImageParams) WithAuthorization(authorization string) *CreateImageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create image params +func (o *CreateImageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create image params +func (o *CreateImageParams) WithBmpLanguage(bmpLanguage *string) *CreateImageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create image params +func (o *CreateImageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create image params +func (o *CreateImageParams) WithBmpUserID(bmpUserID *string) *CreateImageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create image params +func (o *CreateImageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create image params +func (o *CreateImageParams) WithTraceID(traceID string) *CreateImageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create image params +func (o *CreateImageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/create_image_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/create_image_responses.go new file mode 100644 index 0000000..9db3776 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/create_image_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateImageReader is a Reader for the CreateImage structure. +type CreateImageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateImageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateImageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateImageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateImageOK creates a CreateImageOK with default headers values +func NewCreateImageOK() *CreateImageOK { + return &CreateImageOK{} +} + +/* CreateImageOK describes a response with status code 200, with default header values. + +A CreateImageResult is an response struct that is used to describe create image result. +*/ +type CreateImageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateImageOKBody +} + +// IsSuccess returns true when this create image o k response has a 2xx status code +func (o *CreateImageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create image o k response has a 3xx status code +func (o *CreateImageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create image o k response has a 4xx status code +func (o *CreateImageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create image o k response has a 5xx status code +func (o *CreateImageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create image o k response a status code equal to that given +func (o *CreateImageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateImageOK) Error() string { + return fmt.Sprintf("[POST /images][%d] createImageOK %+v", 200, o.Payload) +} + +func (o *CreateImageOK) String() string { + return fmt.Sprintf("[POST /images][%d] createImageOK %+v", 200, o.Payload) +} + +func (o *CreateImageOK) GetPayload() *CreateImageOKBody { + return o.Payload +} + +func (o *CreateImageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateImageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateImageDefault creates a CreateImageDefault with default headers values +func NewCreateImageDefault(code int) *CreateImageDefault { + return &CreateImageDefault{ + _statusCode: code, + } +} + +/* CreateImageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateImageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateImageDefaultBody +} + +// Code gets the status code for the create image default response +func (o *CreateImageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create image default response has a 2xx status code +func (o *CreateImageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create image default response has a 3xx status code +func (o *CreateImageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create image default response has a 4xx status code +func (o *CreateImageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create image default response has a 5xx status code +func (o *CreateImageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create image default response a status code equal to that given +func (o *CreateImageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateImageDefault) Error() string { + return fmt.Sprintf("[POST /images][%d] createImage default %+v", o._statusCode, o.Payload) +} + +func (o *CreateImageDefault) String() string { + return fmt.Sprintf("[POST /images][%d] createImage default %+v", o._statusCode, o.Payload) +} + +func (o *CreateImageDefault) GetPayload() *CreateImageDefaultBody { + return o.Payload +} + +func (o *CreateImageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateImageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateImageDefaultBody create image default body +swagger:model CreateImageDefaultBody +*/ +type CreateImageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create image default body +func (o *CreateImageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateImageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createImage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateImageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createImage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create image default body based on the context it is used +func (o *CreateImageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateImageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateImageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateImageDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateImageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateImageOKBody create image o k body +swagger:model CreateImageOKBody +*/ +type CreateImageOKBody struct { + + // result + Result *models.ImageID `json:"result,omitempty"` +} + +// Validate validates this create image o k body +func (o *CreateImageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateImageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create image o k body based on the context it is used +func (o *CreateImageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateImageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateImageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateImageOKBody) UnmarshalBinary(b []byte) error { + var res CreateImageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/delete_image_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/delete_image_parameters.go new file mode 100644 index 0000000..4de11c2 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/delete_image_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteImageParams creates a new DeleteImageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteImageParams() *DeleteImageParams { + return &DeleteImageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteImageParamsWithTimeout creates a new DeleteImageParams object +// with the ability to set a timeout on a request. +func NewDeleteImageParamsWithTimeout(timeout time.Duration) *DeleteImageParams { + return &DeleteImageParams{ + timeout: timeout, + } +} + +// NewDeleteImageParamsWithContext creates a new DeleteImageParams object +// with the ability to set a context for a request. +func NewDeleteImageParamsWithContext(ctx context.Context) *DeleteImageParams { + return &DeleteImageParams{ + Context: ctx, + } +} + +// NewDeleteImageParamsWithHTTPClient creates a new DeleteImageParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteImageParamsWithHTTPClient(client *http.Client) *DeleteImageParams { + return &DeleteImageParams{ + HTTPClient: client, + } +} + +/* DeleteImageParams contains all the parameters to send to the API endpoint + for the delete image operation. + + Typically these are written to a http.Request. +*/ +type DeleteImageParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // ImageID. + ImageID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteImageParams) WithDefaults() *DeleteImageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteImageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete image params +func (o *DeleteImageParams) WithTimeout(timeout time.Duration) *DeleteImageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete image params +func (o *DeleteImageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete image params +func (o *DeleteImageParams) WithContext(ctx context.Context) *DeleteImageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete image params +func (o *DeleteImageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete image params +func (o *DeleteImageParams) WithHTTPClient(client *http.Client) *DeleteImageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete image params +func (o *DeleteImageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete image params +func (o *DeleteImageParams) WithAuthorization(authorization string) *DeleteImageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete image params +func (o *DeleteImageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete image params +func (o *DeleteImageParams) WithBmpLanguage(bmpLanguage *string) *DeleteImageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete image params +func (o *DeleteImageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete image params +func (o *DeleteImageParams) WithBmpUserID(bmpUserID *string) *DeleteImageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete image params +func (o *DeleteImageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithImageID adds the imageID to the delete image params +func (o *DeleteImageParams) WithImageID(imageID string) *DeleteImageParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the delete image params +func (o *DeleteImageParams) SetImageID(imageID string) { + o.ImageID = imageID +} + +// WithTraceID adds the traceID to the delete image params +func (o *DeleteImageParams) WithTraceID(traceID string) *DeleteImageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete image params +func (o *DeleteImageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param image_id + if err := r.SetPathParam("image_id", o.ImageID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/delete_image_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/delete_image_responses.go new file mode 100644 index 0000000..66ce257 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/delete_image_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteImageReader is a Reader for the DeleteImage structure. +type DeleteImageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteImageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteImageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteImageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteImageOK creates a DeleteImageOK with default headers values +func NewDeleteImageOK() *DeleteImageOK { + return &DeleteImageOK{} +} + +/* DeleteImageOK describes a response with status code 200, with default header values. + +A DeleteImageResult is an response struct that is used to delete image. +*/ +type DeleteImageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteImageOKBody +} + +// IsSuccess returns true when this delete image o k response has a 2xx status code +func (o *DeleteImageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete image o k response has a 3xx status code +func (o *DeleteImageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete image o k response has a 4xx status code +func (o *DeleteImageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete image o k response has a 5xx status code +func (o *DeleteImageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete image o k response a status code equal to that given +func (o *DeleteImageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteImageOK) Error() string { + return fmt.Sprintf("[DELETE /images/{image_id}][%d] deleteImageOK %+v", 200, o.Payload) +} + +func (o *DeleteImageOK) String() string { + return fmt.Sprintf("[DELETE /images/{image_id}][%d] deleteImageOK %+v", 200, o.Payload) +} + +func (o *DeleteImageOK) GetPayload() *DeleteImageOKBody { + return o.Payload +} + +func (o *DeleteImageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteImageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteImageDefault creates a DeleteImageDefault with default headers values +func NewDeleteImageDefault(code int) *DeleteImageDefault { + return &DeleteImageDefault{ + _statusCode: code, + } +} + +/* DeleteImageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteImageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteImageDefaultBody +} + +// Code gets the status code for the delete image default response +func (o *DeleteImageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete image default response has a 2xx status code +func (o *DeleteImageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete image default response has a 3xx status code +func (o *DeleteImageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete image default response has a 4xx status code +func (o *DeleteImageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete image default response has a 5xx status code +func (o *DeleteImageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete image default response a status code equal to that given +func (o *DeleteImageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteImageDefault) Error() string { + return fmt.Sprintf("[DELETE /images/{image_id}][%d] deleteImage default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteImageDefault) String() string { + return fmt.Sprintf("[DELETE /images/{image_id}][%d] deleteImage default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteImageDefault) GetPayload() *DeleteImageDefaultBody { + return o.Payload +} + +func (o *DeleteImageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteImageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteImageDefaultBody delete image default body +swagger:model DeleteImageDefaultBody +*/ +type DeleteImageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete image default body +func (o *DeleteImageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteImageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteImage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteImageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteImage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete image default body based on the context it is used +func (o *DeleteImageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteImageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteImageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteImageDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteImageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteImageOKBody delete image o k body +swagger:model DeleteImageOKBody +*/ +type DeleteImageOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete image o k body +func (o *DeleteImageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteImageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete image o k body based on the context it is used +func (o *DeleteImageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteImageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteImageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteImageOKBody) UnmarshalBinary(b []byte) error { + var res DeleteImageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_device_types_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_device_types_parameters.go new file mode 100644 index 0000000..00dad00 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_device_types_parameters.go @@ -0,0 +1,423 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeImageDeviceTypesParams creates a new DescribeImageDeviceTypesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeImageDeviceTypesParams() *DescribeImageDeviceTypesParams { + return &DescribeImageDeviceTypesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeImageDeviceTypesParamsWithTimeout creates a new DescribeImageDeviceTypesParams object +// with the ability to set a timeout on a request. +func NewDescribeImageDeviceTypesParamsWithTimeout(timeout time.Duration) *DescribeImageDeviceTypesParams { + return &DescribeImageDeviceTypesParams{ + timeout: timeout, + } +} + +// NewDescribeImageDeviceTypesParamsWithContext creates a new DescribeImageDeviceTypesParams object +// with the ability to set a context for a request. +func NewDescribeImageDeviceTypesParamsWithContext(ctx context.Context) *DescribeImageDeviceTypesParams { + return &DescribeImageDeviceTypesParams{ + Context: ctx, + } +} + +// NewDescribeImageDeviceTypesParamsWithHTTPClient creates a new DescribeImageDeviceTypesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeImageDeviceTypesParamsWithHTTPClient(client *http.Client) *DescribeImageDeviceTypesParams { + return &DescribeImageDeviceTypesParams{ + HTTPClient: client, + } +} + +/* DescribeImageDeviceTypesParams contains all the parameters to send to the API endpoint + for the describe image device types operation. + + Typically these are written to a http.Request. +*/ +type DescribeImageDeviceTypesParams struct { + + /* Architecture. + + 体系架构 + */ + Architecture *string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* ImageID. + + 镜像ID + */ + ImageID string + + /* IsAll. + + 是否显示全部 + */ + IsAll *string + + /* IsBind. + + 镜像是否绑定了机型,0查询该镜像没有绑定的机型列表 1查询该镜像已经绑定了的机型列表 + */ + IsBind *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe image device types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImageDeviceTypesParams) WithDefaults() *DescribeImageDeviceTypesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe image device types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImageDeviceTypesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithTimeout(timeout time.Duration) *DescribeImageDeviceTypesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithContext(ctx context.Context) *DescribeImageDeviceTypesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithHTTPClient(client *http.Client) *DescribeImageDeviceTypesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithArchitecture adds the architecture to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithArchitecture(architecture *string) *DescribeImageDeviceTypesParams { + o.SetArchitecture(architecture) + return o +} + +// SetArchitecture adds the architecture to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetArchitecture(architecture *string) { + o.Architecture = architecture +} + +// WithAuthorization adds the authorization to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithAuthorization(authorization string) *DescribeImageDeviceTypesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithBmpLanguage(bmpLanguage *string) *DescribeImageDeviceTypesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithBmpUserID(bmpUserID *string) *DescribeImageDeviceTypesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithImageID adds the imageID to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithImageID(imageID string) *DescribeImageDeviceTypesParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetImageID(imageID string) { + o.ImageID = imageID +} + +// WithIsAll adds the isAll to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithIsAll(isAll *string) *DescribeImageDeviceTypesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithIsBind adds the isBind to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithIsBind(isBind *string) *DescribeImageDeviceTypesParams { + o.SetIsBind(isBind) + return o +} + +// SetIsBind adds the isBind to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetIsBind(isBind *string) { + o.IsBind = isBind +} + +// WithPageNumber adds the pageNumber to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithPageNumber(pageNumber *int64) *DescribeImageDeviceTypesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithPageSize(pageSize *int64) *DescribeImageDeviceTypesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithTraceID(traceID string) *DescribeImageDeviceTypesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeImageDeviceTypesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Architecture != nil { + + // query param architecture + var qrArchitecture string + + if o.Architecture != nil { + qrArchitecture = *o.Architecture + } + qArchitecture := qrArchitecture + if qArchitecture != "" { + + if err := r.SetQueryParam("architecture", qArchitecture); err != nil { + return err + } + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // query param imageId + qrImageID := o.ImageID + qImageID := qrImageID + if qImageID != "" { + + if err := r.SetQueryParam("imageId", qImageID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.IsBind != nil { + + // query param isBind + var qrIsBind string + + if o.IsBind != nil { + qrIsBind = *o.IsBind + } + qIsBind := qrIsBind + if qIsBind != "" { + + if err := r.SetQueryParam("isBind", qIsBind); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_device_types_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_device_types_responses.go new file mode 100644 index 0000000..0261ecc --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_device_types_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeImageDeviceTypesReader is a Reader for the DescribeImageDeviceTypes structure. +type DescribeImageDeviceTypesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeImageDeviceTypesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeImageDeviceTypesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeImageDeviceTypesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeImageDeviceTypesOK creates a DescribeImageDeviceTypesOK with default headers values +func NewDescribeImageDeviceTypesOK() *DescribeImageDeviceTypesOK { + return &DescribeImageDeviceTypesOK{} +} + +/* DescribeImageDeviceTypesOK describes a response with status code 200, with default header values. + +DescribeImageDeviceTypesOK describe image device types o k +*/ +type DescribeImageDeviceTypesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImageDeviceTypesOKBody +} + +// IsSuccess returns true when this describe image device types o k response has a 2xx status code +func (o *DescribeImageDeviceTypesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe image device types o k response has a 3xx status code +func (o *DescribeImageDeviceTypesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe image device types o k response has a 4xx status code +func (o *DescribeImageDeviceTypesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe image device types o k response has a 5xx status code +func (o *DescribeImageDeviceTypesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe image device types o k response a status code equal to that given +func (o *DescribeImageDeviceTypesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeImageDeviceTypesOK) Error() string { + return fmt.Sprintf("[GET /images/imageDeviceTypes][%d] describeImageDeviceTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeImageDeviceTypesOK) String() string { + return fmt.Sprintf("[GET /images/imageDeviceTypes][%d] describeImageDeviceTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeImageDeviceTypesOK) GetPayload() *DescribeImageDeviceTypesOKBody { + return o.Payload +} + +func (o *DescribeImageDeviceTypesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImageDeviceTypesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeImageDeviceTypesDefault creates a DescribeImageDeviceTypesDefault with default headers values +func NewDescribeImageDeviceTypesDefault(code int) *DescribeImageDeviceTypesDefault { + return &DescribeImageDeviceTypesDefault{ + _statusCode: code, + } +} + +/* DescribeImageDeviceTypesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeImageDeviceTypesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImageDeviceTypesDefaultBody +} + +// Code gets the status code for the describe image device types default response +func (o *DescribeImageDeviceTypesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe image device types default response has a 2xx status code +func (o *DescribeImageDeviceTypesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe image device types default response has a 3xx status code +func (o *DescribeImageDeviceTypesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe image device types default response has a 4xx status code +func (o *DescribeImageDeviceTypesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe image device types default response has a 5xx status code +func (o *DescribeImageDeviceTypesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe image device types default response a status code equal to that given +func (o *DescribeImageDeviceTypesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeImageDeviceTypesDefault) Error() string { + return fmt.Sprintf("[GET /images/imageDeviceTypes][%d] describeImageDeviceTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImageDeviceTypesDefault) String() string { + return fmt.Sprintf("[GET /images/imageDeviceTypes][%d] describeImageDeviceTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImageDeviceTypesDefault) GetPayload() *DescribeImageDeviceTypesDefaultBody { + return o.Payload +} + +func (o *DescribeImageDeviceTypesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImageDeviceTypesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeImageDeviceTypesDefaultBody describe image device types default body +swagger:model DescribeImageDeviceTypesDefaultBody +*/ +type DescribeImageDeviceTypesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe image device types default body +func (o *DescribeImageDeviceTypesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDeviceTypesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeImageDeviceTypes default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeImageDeviceTypesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeImageDeviceTypes default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageDeviceTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageDeviceTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe image device types default body based on the context it is used +func (o *DescribeImageDeviceTypesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDeviceTypesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageDeviceTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageDeviceTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImageDeviceTypesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImageDeviceTypesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeImageDeviceTypesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeImageDeviceTypesOKBody describe image device types o k body +swagger:model DescribeImageDeviceTypesOKBody +*/ +type DescribeImageDeviceTypesOKBody struct { + + // result + Result *models.DeviceTypeList `json:"result,omitempty"` +} + +// Validate validates this describe image device types o k body +func (o *DescribeImageDeviceTypesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDeviceTypesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageDeviceTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageDeviceTypesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe image device types o k body based on the context it is used +func (o *DescribeImageDeviceTypesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDeviceTypesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageDeviceTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageDeviceTypesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImageDeviceTypesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImageDeviceTypesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeImageDeviceTypesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_parameters.go new file mode 100644 index 0000000..7057d4b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeImageParams creates a new DescribeImageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeImageParams() *DescribeImageParams { + return &DescribeImageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeImageParamsWithTimeout creates a new DescribeImageParams object +// with the ability to set a timeout on a request. +func NewDescribeImageParamsWithTimeout(timeout time.Duration) *DescribeImageParams { + return &DescribeImageParams{ + timeout: timeout, + } +} + +// NewDescribeImageParamsWithContext creates a new DescribeImageParams object +// with the ability to set a context for a request. +func NewDescribeImageParamsWithContext(ctx context.Context) *DescribeImageParams { + return &DescribeImageParams{ + Context: ctx, + } +} + +// NewDescribeImageParamsWithHTTPClient creates a new DescribeImageParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeImageParamsWithHTTPClient(client *http.Client) *DescribeImageParams { + return &DescribeImageParams{ + HTTPClient: client, + } +} + +/* DescribeImageParams contains all the parameters to send to the API endpoint + for the describe image operation. + + Typically these are written to a http.Request. +*/ +type DescribeImageParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // ImageID. + ImageID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImageParams) WithDefaults() *DescribeImageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe image params +func (o *DescribeImageParams) WithTimeout(timeout time.Duration) *DescribeImageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe image params +func (o *DescribeImageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe image params +func (o *DescribeImageParams) WithContext(ctx context.Context) *DescribeImageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe image params +func (o *DescribeImageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe image params +func (o *DescribeImageParams) WithHTTPClient(client *http.Client) *DescribeImageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe image params +func (o *DescribeImageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe image params +func (o *DescribeImageParams) WithAuthorization(authorization string) *DescribeImageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe image params +func (o *DescribeImageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe image params +func (o *DescribeImageParams) WithBmpLanguage(bmpLanguage *string) *DescribeImageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe image params +func (o *DescribeImageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe image params +func (o *DescribeImageParams) WithBmpUserID(bmpUserID *string) *DescribeImageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe image params +func (o *DescribeImageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithImageID adds the imageID to the describe image params +func (o *DescribeImageParams) WithImageID(imageID string) *DescribeImageParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the describe image params +func (o *DescribeImageParams) SetImageID(imageID string) { + o.ImageID = imageID +} + +// WithTraceID adds the traceID to the describe image params +func (o *DescribeImageParams) WithTraceID(traceID string) *DescribeImageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe image params +func (o *DescribeImageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param image_id + if err := r.SetPathParam("image_id", o.ImageID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_responses.go new file mode 100644 index 0000000..feb0907 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeImageReader is a Reader for the DescribeImage structure. +type DescribeImageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeImageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeImageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeImageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeImageOK creates a DescribeImageOK with default headers values +func NewDescribeImageOK() *DescribeImageOK { + return &DescribeImageOK{} +} + +/* DescribeImageOK describes a response with status code 200, with default header values. + +A DescribeImageResult is an response struct that is used to describe image. +*/ +type DescribeImageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImageOKBody +} + +// IsSuccess returns true when this describe image o k response has a 2xx status code +func (o *DescribeImageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe image o k response has a 3xx status code +func (o *DescribeImageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe image o k response has a 4xx status code +func (o *DescribeImageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe image o k response has a 5xx status code +func (o *DescribeImageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe image o k response a status code equal to that given +func (o *DescribeImageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeImageOK) Error() string { + return fmt.Sprintf("[GET /images/{image_id}][%d] describeImageOK %+v", 200, o.Payload) +} + +func (o *DescribeImageOK) String() string { + return fmt.Sprintf("[GET /images/{image_id}][%d] describeImageOK %+v", 200, o.Payload) +} + +func (o *DescribeImageOK) GetPayload() *DescribeImageOKBody { + return o.Payload +} + +func (o *DescribeImageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeImageDefault creates a DescribeImageDefault with default headers values +func NewDescribeImageDefault(code int) *DescribeImageDefault { + return &DescribeImageDefault{ + _statusCode: code, + } +} + +/* DescribeImageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeImageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImageDefaultBody +} + +// Code gets the status code for the describe image default response +func (o *DescribeImageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe image default response has a 2xx status code +func (o *DescribeImageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe image default response has a 3xx status code +func (o *DescribeImageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe image default response has a 4xx status code +func (o *DescribeImageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe image default response has a 5xx status code +func (o *DescribeImageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe image default response a status code equal to that given +func (o *DescribeImageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeImageDefault) Error() string { + return fmt.Sprintf("[GET /images/{image_id}][%d] describeImage default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImageDefault) String() string { + return fmt.Sprintf("[GET /images/{image_id}][%d] describeImage default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImageDefault) GetPayload() *DescribeImageDefaultBody { + return o.Payload +} + +func (o *DescribeImageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeImageDefaultBody describe image default body +swagger:model DescribeImageDefaultBody +*/ +type DescribeImageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe image default body +func (o *DescribeImageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeImage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeImageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeImage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe image default body based on the context it is used +func (o *DescribeImageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImageDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeImageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeImageOKBody describe image o k body +swagger:model DescribeImageOKBody +*/ +type DescribeImageOKBody struct { + + // result + Result *models.ImageInfo `json:"result,omitempty"` +} + +// Validate validates this describe image o k body +func (o *DescribeImageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe image o k body based on the context it is used +func (o *DescribeImageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImageOKBody) UnmarshalBinary(b []byte) error { + var res DescribeImageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_images_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_images_parameters.go new file mode 100644 index 0000000..7e11911 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_images_parameters.go @@ -0,0 +1,645 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeImagesParams creates a new DescribeImagesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeImagesParams() *DescribeImagesParams { + return &DescribeImagesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeImagesParamsWithTimeout creates a new DescribeImagesParams object +// with the ability to set a timeout on a request. +func NewDescribeImagesParamsWithTimeout(timeout time.Duration) *DescribeImagesParams { + return &DescribeImagesParams{ + timeout: timeout, + } +} + +// NewDescribeImagesParamsWithContext creates a new DescribeImagesParams object +// with the ability to set a context for a request. +func NewDescribeImagesParamsWithContext(ctx context.Context) *DescribeImagesParams { + return &DescribeImagesParams{ + Context: ctx, + } +} + +// NewDescribeImagesParamsWithHTTPClient creates a new DescribeImagesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeImagesParamsWithHTTPClient(client *http.Client) *DescribeImagesParams { + return &DescribeImagesParams{ + HTTPClient: client, + } +} + +/* DescribeImagesParams contains all the parameters to send to the API endpoint + for the describe images operation. + + Typically these are written to a http.Request. +*/ +type DescribeImagesParams struct { + + /* Architecture. + + 体系架构 + */ + Architecture *string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceTypeID. + + 设备类型id + */ + DeviceTypeID *string + + /* ImageID. + + 镜像ID + */ + ImageID *string + + /* ImageIds. + + 镜像ID,数组,支持多个 + */ + ImageIDs []string + + /* ImageName. + + 镜像名称 + */ + ImageName *string + + /* IsAll. + + 是否显示全部 + */ + IsAll *string + + /* OsID. + + 操作系统ID + */ + OsID *string + + /* OsType. + + 操作系统平台 + */ + OsType *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* Source. + + 镜像类型,预置,自定义 + */ + Source *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* Version. + + 版本号 + */ + Version *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe images params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImagesParams) WithDefaults() *DescribeImagesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe images params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImagesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe images params +func (o *DescribeImagesParams) WithTimeout(timeout time.Duration) *DescribeImagesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe images params +func (o *DescribeImagesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe images params +func (o *DescribeImagesParams) WithContext(ctx context.Context) *DescribeImagesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe images params +func (o *DescribeImagesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe images params +func (o *DescribeImagesParams) WithHTTPClient(client *http.Client) *DescribeImagesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe images params +func (o *DescribeImagesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithArchitecture adds the architecture to the describe images params +func (o *DescribeImagesParams) WithArchitecture(architecture *string) *DescribeImagesParams { + o.SetArchitecture(architecture) + return o +} + +// SetArchitecture adds the architecture to the describe images params +func (o *DescribeImagesParams) SetArchitecture(architecture *string) { + o.Architecture = architecture +} + +// WithAuthorization adds the authorization to the describe images params +func (o *DescribeImagesParams) WithAuthorization(authorization string) *DescribeImagesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe images params +func (o *DescribeImagesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe images params +func (o *DescribeImagesParams) WithBmpLanguage(bmpLanguage *string) *DescribeImagesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe images params +func (o *DescribeImagesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe images params +func (o *DescribeImagesParams) WithBmpUserID(bmpUserID *string) *DescribeImagesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe images params +func (o *DescribeImagesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe images params +func (o *DescribeImagesParams) WithDeviceTypeID(deviceTypeID *string) *DescribeImagesParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe images params +func (o *DescribeImagesParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithImageID adds the imageID to the describe images params +func (o *DescribeImagesParams) WithImageID(imageID *string) *DescribeImagesParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the describe images params +func (o *DescribeImagesParams) SetImageID(imageID *string) { + o.ImageID = imageID +} + +// WithImageIDs adds the imageIds to the describe images params +func (o *DescribeImagesParams) WithImageIDs(imageIds []string) *DescribeImagesParams { + o.SetImageIDs(imageIds) + return o +} + +// SetImageIDs adds the imageIds to the describe images params +func (o *DescribeImagesParams) SetImageIDs(imageIds []string) { + o.ImageIDs = imageIds +} + +// WithImageName adds the imageName to the describe images params +func (o *DescribeImagesParams) WithImageName(imageName *string) *DescribeImagesParams { + o.SetImageName(imageName) + return o +} + +// SetImageName adds the imageName to the describe images params +func (o *DescribeImagesParams) SetImageName(imageName *string) { + o.ImageName = imageName +} + +// WithIsAll adds the isAll to the describe images params +func (o *DescribeImagesParams) WithIsAll(isAll *string) *DescribeImagesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe images params +func (o *DescribeImagesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithOsID adds the osID to the describe images params +func (o *DescribeImagesParams) WithOsID(osID *string) *DescribeImagesParams { + o.SetOsID(osID) + return o +} + +// SetOsID adds the osId to the describe images params +func (o *DescribeImagesParams) SetOsID(osID *string) { + o.OsID = osID +} + +// WithOsType adds the osType to the describe images params +func (o *DescribeImagesParams) WithOsType(osType *string) *DescribeImagesParams { + o.SetOsType(osType) + return o +} + +// SetOsType adds the osType to the describe images params +func (o *DescribeImagesParams) SetOsType(osType *string) { + o.OsType = osType +} + +// WithPageNumber adds the pageNumber to the describe images params +func (o *DescribeImagesParams) WithPageNumber(pageNumber *int64) *DescribeImagesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe images params +func (o *DescribeImagesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe images params +func (o *DescribeImagesParams) WithPageSize(pageSize *int64) *DescribeImagesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe images params +func (o *DescribeImagesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithSource adds the source to the describe images params +func (o *DescribeImagesParams) WithSource(source *string) *DescribeImagesParams { + o.SetSource(source) + return o +} + +// SetSource adds the source to the describe images params +func (o *DescribeImagesParams) SetSource(source *string) { + o.Source = source +} + +// WithTraceID adds the traceID to the describe images params +func (o *DescribeImagesParams) WithTraceID(traceID string) *DescribeImagesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe images params +func (o *DescribeImagesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithVersion adds the version to the describe images params +func (o *DescribeImagesParams) WithVersion(version *string) *DescribeImagesParams { + o.SetVersion(version) + return o +} + +// SetVersion adds the version to the describe images params +func (o *DescribeImagesParams) SetVersion(version *string) { + o.Version = version +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeImagesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Architecture != nil { + + // query param architecture + var qrArchitecture string + + if o.Architecture != nil { + qrArchitecture = *o.Architecture + } + qArchitecture := qrArchitecture + if qArchitecture != "" { + + if err := r.SetQueryParam("architecture", qArchitecture); err != nil { + return err + } + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.ImageID != nil { + + // query param imageId + var qrImageID string + + if o.ImageID != nil { + qrImageID = *o.ImageID + } + qImageID := qrImageID + if qImageID != "" { + + if err := r.SetQueryParam("imageId", qImageID); err != nil { + return err + } + } + } + + if o.ImageIDs != nil { + + // binding items for imageIds + joinedImageIds := o.bindParamImageIds(reg) + + // query array param imageIds + if err := r.SetQueryParam("imageIds", joinedImageIds...); err != nil { + return err + } + } + + if o.ImageName != nil { + + // query param imageName + var qrImageName string + + if o.ImageName != nil { + qrImageName = *o.ImageName + } + qImageName := qrImageName + if qImageName != "" { + + if err := r.SetQueryParam("imageName", qImageName); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.OsID != nil { + + // query param osId + var qrOsID string + + if o.OsID != nil { + qrOsID = *o.OsID + } + qOsID := qrOsID + if qOsID != "" { + + if err := r.SetQueryParam("osId", qOsID); err != nil { + return err + } + } + } + + if o.OsType != nil { + + // query param osType + var qrOsType string + + if o.OsType != nil { + qrOsType = *o.OsType + } + qOsType := qrOsType + if qOsType != "" { + + if err := r.SetQueryParam("osType", qOsType); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.Source != nil { + + // query param source + var qrSource string + + if o.Source != nil { + qrSource = *o.Source + } + qSource := qrSource + if qSource != "" { + + if err := r.SetQueryParam("source", qSource); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.Version != nil { + + // query param version + var qrVersion string + + if o.Version != nil { + qrVersion = *o.Version + } + qVersion := qrVersion + if qVersion != "" { + + if err := r.SetQueryParam("version", qVersion); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindParamDescribeImages binds the parameter imageIds +func (o *DescribeImagesParams) bindParamImageIds(formats strfmt.Registry) []string { + imageIdsIR := o.ImageIDs + + var imageIdsIC []string + for _, imageIdsIIR := range imageIdsIR { // explode []string + + imageIdsIIV := imageIdsIIR // string as string + imageIdsIC = append(imageIdsIC, imageIdsIIV) + } + + // items.CollectionFormat: "" + imageIdsIS := swag.JoinByFormat(imageIdsIC, "") + + return imageIdsIS +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_images_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_images_responses.go new file mode 100644 index 0000000..0adb8dd --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/describe_images_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeImagesReader is a Reader for the DescribeImages structure. +type DescribeImagesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeImagesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeImagesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeImagesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeImagesOK creates a DescribeImagesOK with default headers values +func NewDescribeImagesOK() *DescribeImagesOK { + return &DescribeImagesOK{} +} + +/* DescribeImagesOK describes a response with status code 200, with default header values. + +A DescribeImagesResult is an response struct that is used to describe images. +*/ +type DescribeImagesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImagesOKBody +} + +// IsSuccess returns true when this describe images o k response has a 2xx status code +func (o *DescribeImagesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe images o k response has a 3xx status code +func (o *DescribeImagesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe images o k response has a 4xx status code +func (o *DescribeImagesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe images o k response has a 5xx status code +func (o *DescribeImagesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe images o k response a status code equal to that given +func (o *DescribeImagesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeImagesOK) Error() string { + return fmt.Sprintf("[GET /images][%d] describeImagesOK %+v", 200, o.Payload) +} + +func (o *DescribeImagesOK) String() string { + return fmt.Sprintf("[GET /images][%d] describeImagesOK %+v", 200, o.Payload) +} + +func (o *DescribeImagesOK) GetPayload() *DescribeImagesOKBody { + return o.Payload +} + +func (o *DescribeImagesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImagesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeImagesDefault creates a DescribeImagesDefault with default headers values +func NewDescribeImagesDefault(code int) *DescribeImagesDefault { + return &DescribeImagesDefault{ + _statusCode: code, + } +} + +/* DescribeImagesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeImagesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImagesDefaultBody +} + +// Code gets the status code for the describe images default response +func (o *DescribeImagesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe images default response has a 2xx status code +func (o *DescribeImagesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe images default response has a 3xx status code +func (o *DescribeImagesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe images default response has a 4xx status code +func (o *DescribeImagesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe images default response has a 5xx status code +func (o *DescribeImagesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe images default response a status code equal to that given +func (o *DescribeImagesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeImagesDefault) Error() string { + return fmt.Sprintf("[GET /images][%d] describeImages default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImagesDefault) String() string { + return fmt.Sprintf("[GET /images][%d] describeImages default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImagesDefault) GetPayload() *DescribeImagesDefaultBody { + return o.Payload +} + +func (o *DescribeImagesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImagesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeImagesDefaultBody describe images default body +swagger:model DescribeImagesDefaultBody +*/ +type DescribeImagesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe images default body +func (o *DescribeImagesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImagesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeImages default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeImagesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeImages default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImages default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImages default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe images default body based on the context it is used +func (o *DescribeImagesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImagesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImages default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImages default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImagesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImagesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeImagesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeImagesOKBody describe images o k body +swagger:model DescribeImagesOKBody +*/ +type DescribeImagesOKBody struct { + + // result + Result *models.ImageList `json:"result,omitempty"` +} + +// Validate validates this describe images o k body +func (o *DescribeImagesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImagesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImagesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImagesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe images o k body based on the context it is used +func (o *DescribeImagesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImagesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImagesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImagesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImagesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImagesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeImagesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/dissociated_device_type_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/dissociated_device_type_parameters.go new file mode 100644 index 0000000..0df631a --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/dissociated_device_type_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewDissociatedDeviceTypeParams creates a new DissociatedDeviceTypeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDissociatedDeviceTypeParams() *DissociatedDeviceTypeParams { + return &DissociatedDeviceTypeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDissociatedDeviceTypeParamsWithTimeout creates a new DissociatedDeviceTypeParams object +// with the ability to set a timeout on a request. +func NewDissociatedDeviceTypeParamsWithTimeout(timeout time.Duration) *DissociatedDeviceTypeParams { + return &DissociatedDeviceTypeParams{ + timeout: timeout, + } +} + +// NewDissociatedDeviceTypeParamsWithContext creates a new DissociatedDeviceTypeParams object +// with the ability to set a context for a request. +func NewDissociatedDeviceTypeParamsWithContext(ctx context.Context) *DissociatedDeviceTypeParams { + return &DissociatedDeviceTypeParams{ + Context: ctx, + } +} + +// NewDissociatedDeviceTypeParamsWithHTTPClient creates a new DissociatedDeviceTypeParams object +// with the ability to set a custom HTTPClient for a request. +func NewDissociatedDeviceTypeParamsWithHTTPClient(client *http.Client) *DissociatedDeviceTypeParams { + return &DissociatedDeviceTypeParams{ + HTTPClient: client, + } +} + +/* DissociatedDeviceTypeParams contains all the parameters to send to the API endpoint + for the dissociated device type operation. + + Typically these are written to a http.Request. +*/ +type DissociatedDeviceTypeParams struct { + + // Body. + Body *models.DissociatedImageRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the dissociated device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DissociatedDeviceTypeParams) WithDefaults() *DissociatedDeviceTypeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the dissociated device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DissociatedDeviceTypeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithTimeout(timeout time.Duration) *DissociatedDeviceTypeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithContext(ctx context.Context) *DissociatedDeviceTypeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithHTTPClient(client *http.Client) *DissociatedDeviceTypeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithBody(body *models.DissociatedImageRequest) *DissociatedDeviceTypeParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetBody(body *models.DissociatedImageRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithAuthorization(authorization string) *DissociatedDeviceTypeParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithBmpLanguage(bmpLanguage *string) *DissociatedDeviceTypeParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithBmpUserID(bmpUserID *string) *DissociatedDeviceTypeParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithTraceID(traceID string) *DissociatedDeviceTypeParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DissociatedDeviceTypeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/dissociated_device_type_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/dissociated_device_type_responses.go new file mode 100644 index 0000000..4a2b3c2 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/dissociated_device_type_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DissociatedDeviceTypeReader is a Reader for the DissociatedDeviceType structure. +type DissociatedDeviceTypeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DissociatedDeviceTypeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDissociatedDeviceTypeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDissociatedDeviceTypeDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDissociatedDeviceTypeOK creates a DissociatedDeviceTypeOK with default headers values +func NewDissociatedDeviceTypeOK() *DissociatedDeviceTypeOK { + return &DissociatedDeviceTypeOK{} +} + +/* DissociatedDeviceTypeOK describes a response with status code 200, with default header values. + +DissociatedDeviceTypeOK dissociated device type o k +*/ +type DissociatedDeviceTypeOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DissociatedDeviceTypeOKBody +} + +// IsSuccess returns true when this dissociated device type o k response has a 2xx status code +func (o *DissociatedDeviceTypeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this dissociated device type o k response has a 3xx status code +func (o *DissociatedDeviceTypeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this dissociated device type o k response has a 4xx status code +func (o *DissociatedDeviceTypeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this dissociated device type o k response has a 5xx status code +func (o *DissociatedDeviceTypeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this dissociated device type o k response a status code equal to that given +func (o *DissociatedDeviceTypeOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DissociatedDeviceTypeOK) Error() string { + return fmt.Sprintf("[DELETE /images/dissociatedDeviceType][%d] dissociatedDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DissociatedDeviceTypeOK) String() string { + return fmt.Sprintf("[DELETE /images/dissociatedDeviceType][%d] dissociatedDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DissociatedDeviceTypeOK) GetPayload() *DissociatedDeviceTypeOKBody { + return o.Payload +} + +func (o *DissociatedDeviceTypeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DissociatedDeviceTypeOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDissociatedDeviceTypeDefault creates a DissociatedDeviceTypeDefault with default headers values +func NewDissociatedDeviceTypeDefault(code int) *DissociatedDeviceTypeDefault { + return &DissociatedDeviceTypeDefault{ + _statusCode: code, + } +} + +/* DissociatedDeviceTypeDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DissociatedDeviceTypeDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DissociatedDeviceTypeDefaultBody +} + +// Code gets the status code for the dissociated device type default response +func (o *DissociatedDeviceTypeDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this dissociated device type default response has a 2xx status code +func (o *DissociatedDeviceTypeDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this dissociated device type default response has a 3xx status code +func (o *DissociatedDeviceTypeDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this dissociated device type default response has a 4xx status code +func (o *DissociatedDeviceTypeDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this dissociated device type default response has a 5xx status code +func (o *DissociatedDeviceTypeDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this dissociated device type default response a status code equal to that given +func (o *DissociatedDeviceTypeDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DissociatedDeviceTypeDefault) Error() string { + return fmt.Sprintf("[DELETE /images/dissociatedDeviceType][%d] dissociatedDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DissociatedDeviceTypeDefault) String() string { + return fmt.Sprintf("[DELETE /images/dissociatedDeviceType][%d] dissociatedDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DissociatedDeviceTypeDefault) GetPayload() *DissociatedDeviceTypeDefaultBody { + return o.Payload +} + +func (o *DissociatedDeviceTypeDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DissociatedDeviceTypeDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DissociatedDeviceTypeDefaultBody dissociated device type default body +swagger:model DissociatedDeviceTypeDefaultBody +*/ +type DissociatedDeviceTypeDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this dissociated device type default body +func (o *DissociatedDeviceTypeDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedDeviceTypeDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("dissociatedDeviceType default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DissociatedDeviceTypeDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("dissociatedDeviceType default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this dissociated device type default body based on the context it is used +func (o *DissociatedDeviceTypeDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedDeviceTypeDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DissociatedDeviceTypeDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DissociatedDeviceTypeDefaultBody) UnmarshalBinary(b []byte) error { + var res DissociatedDeviceTypeDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DissociatedDeviceTypeOKBody dissociated device type o k body +swagger:model DissociatedDeviceTypeOKBody +*/ +type DissociatedDeviceTypeOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this dissociated device type o k body +func (o *DissociatedDeviceTypeOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedDeviceTypeOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this dissociated device type o k body based on the context it is used +func (o *DissociatedDeviceTypeOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedDeviceTypeOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DissociatedDeviceTypeOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DissociatedDeviceTypeOKBody) UnmarshalBinary(b []byte) error { + var res DissociatedDeviceTypeOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/image_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/image_client.go new file mode 100644 index 0000000..52ae2ae --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/image_client.go @@ -0,0 +1,357 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new image API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for image API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + AssociatedDeviceType(params *AssociatedDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AssociatedDeviceTypeOK, error) + + CreateImage(params *CreateImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateImageOK, error) + + DeleteImage(params *DeleteImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteImageOK, error) + + DescribeImage(params *DescribeImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImageOK, error) + + DescribeImageDeviceTypes(params *DescribeImageDeviceTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImageDeviceTypesOK, error) + + DescribeImages(params *DescribeImagesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImagesOK, error) + + DissociatedDeviceType(params *DissociatedDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DissociatedDeviceTypeOK, error) + + ModifyImage(params *ModifyImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyImageOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + AssociatedDeviceType AssociatedDeviceType 镜像绑定机型 +*/ +func (a *Client) AssociatedDeviceType(params *AssociatedDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AssociatedDeviceTypeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewAssociatedDeviceTypeParams() + } + op := &runtime.ClientOperation{ + ID: "associatedDeviceType", + Method: "POST", + PathPattern: "/images/associatedDeviceType", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &AssociatedDeviceTypeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*AssociatedDeviceTypeOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*AssociatedDeviceTypeDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + CreateImage CreateImage 添加镜像 +*/ +func (a *Client) CreateImage(params *CreateImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateImageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateImageParams() + } + op := &runtime.ClientOperation{ + ID: "createImage", + Method: "POST", + PathPattern: "/images", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateImageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateImageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateImageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteImage DeleteImage 删除镜像 +*/ +func (a *Client) DeleteImage(params *DeleteImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteImageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteImageParams() + } + op := &runtime.ClientOperation{ + ID: "deleteImage", + Method: "DELETE", + PathPattern: "/images/{image_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteImageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteImageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteImageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeImage DescribeImage 获取镜像详情 +*/ +func (a *Client) DescribeImage(params *DescribeImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeImageParams() + } + op := &runtime.ClientOperation{ + ID: "describeImage", + Method: "GET", + PathPattern: "/images/{image_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeImageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeImageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeImageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeImageDeviceTypes DescribeImageDeviceTypes 查看镜像绑定的机型 +*/ +func (a *Client) DescribeImageDeviceTypes(params *DescribeImageDeviceTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImageDeviceTypesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeImageDeviceTypesParams() + } + op := &runtime.ClientOperation{ + ID: "describeImageDeviceTypes", + Method: "GET", + PathPattern: "/images/imageDeviceTypes", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeImageDeviceTypesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeImageDeviceTypesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeImageDeviceTypesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeImages DescribeImages 获取镜像列表 +*/ +func (a *Client) DescribeImages(params *DescribeImagesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImagesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeImagesParams() + } + op := &runtime.ClientOperation{ + ID: "describeImages", + Method: "GET", + PathPattern: "/images", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeImagesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeImagesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeImagesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DissociatedDeviceType DissociatedDeviceType 镜像解绑机型 +*/ +func (a *Client) DissociatedDeviceType(params *DissociatedDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DissociatedDeviceTypeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDissociatedDeviceTypeParams() + } + op := &runtime.ClientOperation{ + ID: "dissociatedDeviceType", + Method: "DELETE", + PathPattern: "/images/dissociatedDeviceType", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DissociatedDeviceTypeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DissociatedDeviceTypeOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DissociatedDeviceTypeDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyImage ModifyImage 修改镜像(暂不启用) +*/ +func (a *Client) ModifyImage(params *ModifyImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyImageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyImageParams() + } + op := &runtime.ClientOperation{ + ID: "modifyImage", + Method: "PUT", + PathPattern: "/images/{image_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyImageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyImageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyImageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/modify_image_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/modify_image_parameters.go new file mode 100644 index 0000000..b2159e5 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/modify_image_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyImageParams creates a new ModifyImageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyImageParams() *ModifyImageParams { + return &ModifyImageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyImageParamsWithTimeout creates a new ModifyImageParams object +// with the ability to set a timeout on a request. +func NewModifyImageParamsWithTimeout(timeout time.Duration) *ModifyImageParams { + return &ModifyImageParams{ + timeout: timeout, + } +} + +// NewModifyImageParamsWithContext creates a new ModifyImageParams object +// with the ability to set a context for a request. +func NewModifyImageParamsWithContext(ctx context.Context) *ModifyImageParams { + return &ModifyImageParams{ + Context: ctx, + } +} + +// NewModifyImageParamsWithHTTPClient creates a new ModifyImageParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyImageParamsWithHTTPClient(client *http.Client) *ModifyImageParams { + return &ModifyImageParams{ + HTTPClient: client, + } +} + +/* ModifyImageParams contains all the parameters to send to the API endpoint + for the modify image operation. + + Typically these are written to a http.Request. +*/ +type ModifyImageParams struct { + + // Body. + Body *models.ModifyImageRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // ImageID. + ImageID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyImageParams) WithDefaults() *ModifyImageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyImageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify image params +func (o *ModifyImageParams) WithTimeout(timeout time.Duration) *ModifyImageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify image params +func (o *ModifyImageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify image params +func (o *ModifyImageParams) WithContext(ctx context.Context) *ModifyImageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify image params +func (o *ModifyImageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify image params +func (o *ModifyImageParams) WithHTTPClient(client *http.Client) *ModifyImageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify image params +func (o *ModifyImageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify image params +func (o *ModifyImageParams) WithBody(body *models.ModifyImageRequest) *ModifyImageParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify image params +func (o *ModifyImageParams) SetBody(body *models.ModifyImageRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify image params +func (o *ModifyImageParams) WithAuthorization(authorization string) *ModifyImageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify image params +func (o *ModifyImageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify image params +func (o *ModifyImageParams) WithBmpLanguage(bmpLanguage *string) *ModifyImageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify image params +func (o *ModifyImageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify image params +func (o *ModifyImageParams) WithBmpUserID(bmpUserID *string) *ModifyImageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify image params +func (o *ModifyImageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithImageID adds the imageID to the modify image params +func (o *ModifyImageParams) WithImageID(imageID string) *ModifyImageParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the modify image params +func (o *ModifyImageParams) SetImageID(imageID string) { + o.ImageID = imageID +} + +// WithTraceID adds the traceID to the modify image params +func (o *ModifyImageParams) WithTraceID(traceID string) *ModifyImageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify image params +func (o *ModifyImageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param image_id + if err := r.SetPathParam("image_id", o.ImageID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/modify_image_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/modify_image_responses.go new file mode 100644 index 0000000..f31e33a --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/image/modify_image_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyImageReader is a Reader for the ModifyImage structure. +type ModifyImageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyImageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyImageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyImageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyImageOK creates a ModifyImageOK with default headers values +func NewModifyImageOK() *ModifyImageOK { + return &ModifyImageOK{} +} + +/* ModifyImageOK describes a response with status code 200, with default header values. + +A ModifyImageResult is an response struct that is used to modify image. +*/ +type ModifyImageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyImageOKBody +} + +// IsSuccess returns true when this modify image o k response has a 2xx status code +func (o *ModifyImageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify image o k response has a 3xx status code +func (o *ModifyImageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify image o k response has a 4xx status code +func (o *ModifyImageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify image o k response has a 5xx status code +func (o *ModifyImageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify image o k response a status code equal to that given +func (o *ModifyImageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyImageOK) Error() string { + return fmt.Sprintf("[PUT /images/{image_id}][%d] modifyImageOK %+v", 200, o.Payload) +} + +func (o *ModifyImageOK) String() string { + return fmt.Sprintf("[PUT /images/{image_id}][%d] modifyImageOK %+v", 200, o.Payload) +} + +func (o *ModifyImageOK) GetPayload() *ModifyImageOKBody { + return o.Payload +} + +func (o *ModifyImageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyImageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyImageDefault creates a ModifyImageDefault with default headers values +func NewModifyImageDefault(code int) *ModifyImageDefault { + return &ModifyImageDefault{ + _statusCode: code, + } +} + +/* ModifyImageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyImageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyImageDefaultBody +} + +// Code gets the status code for the modify image default response +func (o *ModifyImageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify image default response has a 2xx status code +func (o *ModifyImageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify image default response has a 3xx status code +func (o *ModifyImageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify image default response has a 4xx status code +func (o *ModifyImageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify image default response has a 5xx status code +func (o *ModifyImageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify image default response a status code equal to that given +func (o *ModifyImageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyImageDefault) Error() string { + return fmt.Sprintf("[PUT /images/{image_id}][%d] modifyImage default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyImageDefault) String() string { + return fmt.Sprintf("[PUT /images/{image_id}][%d] modifyImage default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyImageDefault) GetPayload() *ModifyImageDefaultBody { + return o.Payload +} + +func (o *ModifyImageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyImageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyImageDefaultBody modify image default body +swagger:model ModifyImageDefaultBody +*/ +type ModifyImageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify image default body +func (o *ModifyImageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyImageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyImage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyImageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyImage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify image default body based on the context it is used +func (o *ModifyImageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyImageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyImageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyImageDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyImageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyImageOKBody modify image o k body +swagger:model ModifyImageOKBody +*/ +type ModifyImageOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify image o k body +func (o *ModifyImageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyImageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify image o k body based on the context it is used +func (o *ModifyImageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyImageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyImageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyImageOKBody) UnmarshalBinary(b []byte) error { + var res ModifyImageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/create_project_instance_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/create_project_instance_parameters.go new file mode 100644 index 0000000..4e370ba --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/create_project_instance_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateProjectInstanceParams creates a new CreateProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateProjectInstanceParams() *CreateProjectInstanceParams { + return &CreateProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateProjectInstanceParamsWithTimeout creates a new CreateProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewCreateProjectInstanceParamsWithTimeout(timeout time.Duration) *CreateProjectInstanceParams { + return &CreateProjectInstanceParams{ + timeout: timeout, + } +} + +// NewCreateProjectInstanceParamsWithContext creates a new CreateProjectInstanceParams object +// with the ability to set a context for a request. +func NewCreateProjectInstanceParamsWithContext(ctx context.Context) *CreateProjectInstanceParams { + return &CreateProjectInstanceParams{ + Context: ctx, + } +} + +// NewCreateProjectInstanceParamsWithHTTPClient creates a new CreateProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateProjectInstanceParamsWithHTTPClient(client *http.Client) *CreateProjectInstanceParams { + return &CreateProjectInstanceParams{ + HTTPClient: client, + } +} + +/* CreateProjectInstanceParams contains all the parameters to send to the API endpoint + for the create project instance operation. + + Typically these are written to a http.Request. +*/ +type CreateProjectInstanceParams struct { + + // Body. + Body *models.CreateInstanceRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateProjectInstanceParams) WithDefaults() *CreateProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create project instance params +func (o *CreateProjectInstanceParams) WithTimeout(timeout time.Duration) *CreateProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create project instance params +func (o *CreateProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create project instance params +func (o *CreateProjectInstanceParams) WithContext(ctx context.Context) *CreateProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create project instance params +func (o *CreateProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create project instance params +func (o *CreateProjectInstanceParams) WithHTTPClient(client *http.Client) *CreateProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create project instance params +func (o *CreateProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create project instance params +func (o *CreateProjectInstanceParams) WithBody(body *models.CreateInstanceRequest) *CreateProjectInstanceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create project instance params +func (o *CreateProjectInstanceParams) SetBody(body *models.CreateInstanceRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create project instance params +func (o *CreateProjectInstanceParams) WithAuthorization(authorization string) *CreateProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create project instance params +func (o *CreateProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create project instance params +func (o *CreateProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *CreateProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create project instance params +func (o *CreateProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create project instance params +func (o *CreateProjectInstanceParams) WithBmpUserID(bmpUserID *string) *CreateProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create project instance params +func (o *CreateProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create project instance params +func (o *CreateProjectInstanceParams) WithTraceID(traceID string) *CreateProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create project instance params +func (o *CreateProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/create_project_instance_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/create_project_instance_responses.go new file mode 100644 index 0000000..8a32dc6 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/create_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateProjectInstanceReader is a Reader for the CreateProjectInstance structure. +type CreateProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateProjectInstanceOK creates a CreateProjectInstanceOK with default headers values +func NewCreateProjectInstanceOK() *CreateProjectInstanceOK { + return &CreateProjectInstanceOK{} +} + +/* CreateProjectInstanceOK describes a response with status code 200, with default header values. + +A CreateProjectInstanceResult is an response struct that is used to describe create instance result. +*/ +type CreateProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateProjectInstanceOKBody +} + +// IsSuccess returns true when this create project instance o k response has a 2xx status code +func (o *CreateProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create project instance o k response has a 3xx status code +func (o *CreateProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create project instance o k response has a 4xx status code +func (o *CreateProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create project instance o k response has a 5xx status code +func (o *CreateProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create project instance o k response a status code equal to that given +func (o *CreateProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateProjectInstanceOK) Error() string { + return fmt.Sprintf("[POST /project/instances][%d] createProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *CreateProjectInstanceOK) String() string { + return fmt.Sprintf("[POST /project/instances][%d] createProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *CreateProjectInstanceOK) GetPayload() *CreateProjectInstanceOKBody { + return o.Payload +} + +func (o *CreateProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateProjectInstanceDefault creates a CreateProjectInstanceDefault with default headers values +func NewCreateProjectInstanceDefault(code int) *CreateProjectInstanceDefault { + return &CreateProjectInstanceDefault{ + _statusCode: code, + } +} + +/* CreateProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateProjectInstanceDefaultBody +} + +// Code gets the status code for the create project instance default response +func (o *CreateProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create project instance default response has a 2xx status code +func (o *CreateProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create project instance default response has a 3xx status code +func (o *CreateProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create project instance default response has a 4xx status code +func (o *CreateProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create project instance default response has a 5xx status code +func (o *CreateProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create project instance default response a status code equal to that given +func (o *CreateProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateProjectInstanceDefault) Error() string { + return fmt.Sprintf("[POST /project/instances][%d] createProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *CreateProjectInstanceDefault) String() string { + return fmt.Sprintf("[POST /project/instances][%d] createProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *CreateProjectInstanceDefault) GetPayload() *CreateProjectInstanceDefaultBody { + return o.Payload +} + +func (o *CreateProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateProjectInstanceDefaultBody create project instance default body +swagger:model CreateProjectInstanceDefaultBody +*/ +type CreateProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create project instance default body +func (o *CreateProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create project instance default body based on the context it is used +func (o *CreateProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateProjectInstanceOKBody create project instance o k body +swagger:model CreateProjectInstanceOKBody +*/ +type CreateProjectInstanceOKBody struct { + + // result + Result *models.InstanceIds `json:"result,omitempty"` +} + +// Validate validates this create project instance o k body +func (o *CreateProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create project instance o k body based on the context it is used +func (o *CreateProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res CreateProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/delete_instances_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/delete_instances_parameters.go new file mode 100644 index 0000000..09a6304 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/delete_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewDeleteInstancesParams creates a new DeleteInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteInstancesParams() *DeleteInstancesParams { + return &DeleteInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteInstancesParamsWithTimeout creates a new DeleteInstancesParams object +// with the ability to set a timeout on a request. +func NewDeleteInstancesParamsWithTimeout(timeout time.Duration) *DeleteInstancesParams { + return &DeleteInstancesParams{ + timeout: timeout, + } +} + +// NewDeleteInstancesParamsWithContext creates a new DeleteInstancesParams object +// with the ability to set a context for a request. +func NewDeleteInstancesParamsWithContext(ctx context.Context) *DeleteInstancesParams { + return &DeleteInstancesParams{ + Context: ctx, + } +} + +// NewDeleteInstancesParamsWithHTTPClient creates a new DeleteInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteInstancesParamsWithHTTPClient(client *http.Client) *DeleteInstancesParams { + return &DeleteInstancesParams{ + HTTPClient: client, + } +} + +/* DeleteInstancesParams contains all the parameters to send to the API endpoint + for the delete instances operation. + + Typically these are written to a http.Request. +*/ +type DeleteInstancesParams struct { + + // Body. + Body *models.DeleteInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteInstancesParams) WithDefaults() *DeleteInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete instances params +func (o *DeleteInstancesParams) WithTimeout(timeout time.Duration) *DeleteInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete instances params +func (o *DeleteInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete instances params +func (o *DeleteInstancesParams) WithContext(ctx context.Context) *DeleteInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete instances params +func (o *DeleteInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete instances params +func (o *DeleteInstancesParams) WithHTTPClient(client *http.Client) *DeleteInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete instances params +func (o *DeleteInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the delete instances params +func (o *DeleteInstancesParams) WithBody(body *models.DeleteInstancesRequest) *DeleteInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the delete instances params +func (o *DeleteInstancesParams) SetBody(body *models.DeleteInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the delete instances params +func (o *DeleteInstancesParams) WithAuthorization(authorization string) *DeleteInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete instances params +func (o *DeleteInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete instances params +func (o *DeleteInstancesParams) WithBmpLanguage(bmpLanguage *string) *DeleteInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete instances params +func (o *DeleteInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete instances params +func (o *DeleteInstancesParams) WithBmpUserID(bmpUserID *string) *DeleteInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete instances params +func (o *DeleteInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete instances params +func (o *DeleteInstancesParams) WithTraceID(traceID string) *DeleteInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete instances params +func (o *DeleteInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/delete_instances_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/delete_instances_responses.go new file mode 100644 index 0000000..05388da --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/delete_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteInstancesReader is a Reader for the DeleteInstances structure. +type DeleteInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteInstancesOK creates a DeleteInstancesOK with default headers values +func NewDeleteInstancesOK() *DeleteInstancesOK { + return &DeleteInstancesOK{} +} + +/* DeleteInstancesOK describes a response with status code 200, with default header values. + +A DeleteInstancesResult is an response struct that is used to describe modify instance result. +*/ +type DeleteInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteInstancesOKBody +} + +// IsSuccess returns true when this delete instances o k response has a 2xx status code +func (o *DeleteInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete instances o k response has a 3xx status code +func (o *DeleteInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete instances o k response has a 4xx status code +func (o *DeleteInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete instances o k response has a 5xx status code +func (o *DeleteInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete instances o k response a status code equal to that given +func (o *DeleteInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteInstancesOK) Error() string { + return fmt.Sprintf("[DELETE /project/instances/batch/instances:deleteInstances][%d] deleteInstancesOK %+v", 200, o.Payload) +} + +func (o *DeleteInstancesOK) String() string { + return fmt.Sprintf("[DELETE /project/instances/batch/instances:deleteInstances][%d] deleteInstancesOK %+v", 200, o.Payload) +} + +func (o *DeleteInstancesOK) GetPayload() *DeleteInstancesOKBody { + return o.Payload +} + +func (o *DeleteInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteInstancesDefault creates a DeleteInstancesDefault with default headers values +func NewDeleteInstancesDefault(code int) *DeleteInstancesDefault { + return &DeleteInstancesDefault{ + _statusCode: code, + } +} + +/* DeleteInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteInstancesDefaultBody +} + +// Code gets the status code for the delete instances default response +func (o *DeleteInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete instances default response has a 2xx status code +func (o *DeleteInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete instances default response has a 3xx status code +func (o *DeleteInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete instances default response has a 4xx status code +func (o *DeleteInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete instances default response has a 5xx status code +func (o *DeleteInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete instances default response a status code equal to that given +func (o *DeleteInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteInstancesDefault) Error() string { + return fmt.Sprintf("[DELETE /project/instances/batch/instances:deleteInstances][%d] deleteInstances default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteInstancesDefault) String() string { + return fmt.Sprintf("[DELETE /project/instances/batch/instances:deleteInstances][%d] deleteInstances default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteInstancesDefault) GetPayload() *DeleteInstancesDefaultBody { + return o.Payload +} + +func (o *DeleteInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteInstancesDefaultBody delete instances default body +swagger:model DeleteInstancesDefaultBody +*/ +type DeleteInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete instances default body +func (o *DeleteInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete instances default body based on the context it is used +func (o *DeleteInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteInstancesOKBody delete instances o k body +swagger:model DeleteInstancesOKBody +*/ +type DeleteInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete instances o k body +func (o *DeleteInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete instances o k body based on the context it is used +func (o *DeleteInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteInstancesOKBody) UnmarshalBinary(b []byte) error { + var res DeleteInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/delete_project_instance_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/delete_project_instance_parameters.go new file mode 100644 index 0000000..0ed6624 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/delete_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteProjectInstanceParams creates a new DeleteProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteProjectInstanceParams() *DeleteProjectInstanceParams { + return &DeleteProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteProjectInstanceParamsWithTimeout creates a new DeleteProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewDeleteProjectInstanceParamsWithTimeout(timeout time.Duration) *DeleteProjectInstanceParams { + return &DeleteProjectInstanceParams{ + timeout: timeout, + } +} + +// NewDeleteProjectInstanceParamsWithContext creates a new DeleteProjectInstanceParams object +// with the ability to set a context for a request. +func NewDeleteProjectInstanceParamsWithContext(ctx context.Context) *DeleteProjectInstanceParams { + return &DeleteProjectInstanceParams{ + Context: ctx, + } +} + +// NewDeleteProjectInstanceParamsWithHTTPClient creates a new DeleteProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteProjectInstanceParamsWithHTTPClient(client *http.Client) *DeleteProjectInstanceParams { + return &DeleteProjectInstanceParams{ + HTTPClient: client, + } +} + +/* DeleteProjectInstanceParams contains all the parameters to send to the API endpoint + for the delete project instance operation. + + Typically these are written to a http.Request. +*/ +type DeleteProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteProjectInstanceParams) WithDefaults() *DeleteProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete project instance params +func (o *DeleteProjectInstanceParams) WithTimeout(timeout time.Duration) *DeleteProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete project instance params +func (o *DeleteProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete project instance params +func (o *DeleteProjectInstanceParams) WithContext(ctx context.Context) *DeleteProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete project instance params +func (o *DeleteProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete project instance params +func (o *DeleteProjectInstanceParams) WithHTTPClient(client *http.Client) *DeleteProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete project instance params +func (o *DeleteProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete project instance params +func (o *DeleteProjectInstanceParams) WithAuthorization(authorization string) *DeleteProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete project instance params +func (o *DeleteProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete project instance params +func (o *DeleteProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *DeleteProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete project instance params +func (o *DeleteProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete project instance params +func (o *DeleteProjectInstanceParams) WithBmpUserID(bmpUserID *string) *DeleteProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete project instance params +func (o *DeleteProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the delete project instance params +func (o *DeleteProjectInstanceParams) WithInstanceID(instanceID string) *DeleteProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the delete project instance params +func (o *DeleteProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the delete project instance params +func (o *DeleteProjectInstanceParams) WithTraceID(traceID string) *DeleteProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete project instance params +func (o *DeleteProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/delete_project_instance_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/delete_project_instance_responses.go new file mode 100644 index 0000000..ea5f636 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/delete_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteProjectInstanceReader is a Reader for the DeleteProjectInstance structure. +type DeleteProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteProjectInstanceOK creates a DeleteProjectInstanceOK with default headers values +func NewDeleteProjectInstanceOK() *DeleteProjectInstanceOK { + return &DeleteProjectInstanceOK{} +} + +/* DeleteProjectInstanceOK describes a response with status code 200, with default header values. + +A DeleteProjectInstanceResult is an response struct that is used to delete stop instance result. +*/ +type DeleteProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteProjectInstanceOKBody +} + +// IsSuccess returns true when this delete project instance o k response has a 2xx status code +func (o *DeleteProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete project instance o k response has a 3xx status code +func (o *DeleteProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete project instance o k response has a 4xx status code +func (o *DeleteProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete project instance o k response has a 5xx status code +func (o *DeleteProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete project instance o k response a status code equal to that given +func (o *DeleteProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteProjectInstanceOK) Error() string { + return fmt.Sprintf("[DELETE /project/instances/{instance_id}][%d] deleteProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *DeleteProjectInstanceOK) String() string { + return fmt.Sprintf("[DELETE /project/instances/{instance_id}][%d] deleteProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *DeleteProjectInstanceOK) GetPayload() *DeleteProjectInstanceOKBody { + return o.Payload +} + +func (o *DeleteProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteProjectInstanceDefault creates a DeleteProjectInstanceDefault with default headers values +func NewDeleteProjectInstanceDefault(code int) *DeleteProjectInstanceDefault { + return &DeleteProjectInstanceDefault{ + _statusCode: code, + } +} + +/* DeleteProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteProjectInstanceDefaultBody +} + +// Code gets the status code for the delete project instance default response +func (o *DeleteProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete project instance default response has a 2xx status code +func (o *DeleteProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete project instance default response has a 3xx status code +func (o *DeleteProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete project instance default response has a 4xx status code +func (o *DeleteProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete project instance default response has a 5xx status code +func (o *DeleteProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete project instance default response a status code equal to that given +func (o *DeleteProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteProjectInstanceDefault) Error() string { + return fmt.Sprintf("[DELETE /project/instances/{instance_id}][%d] deleteProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteProjectInstanceDefault) String() string { + return fmt.Sprintf("[DELETE /project/instances/{instance_id}][%d] deleteProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteProjectInstanceDefault) GetPayload() *DeleteProjectInstanceDefaultBody { + return o.Payload +} + +func (o *DeleteProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteProjectInstanceDefaultBody delete project instance default body +swagger:model DeleteProjectInstanceDefaultBody +*/ +type DeleteProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete project instance default body +func (o *DeleteProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete project instance default body based on the context it is used +func (o *DeleteProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteProjectInstanceOKBody delete project instance o k body +swagger:model DeleteProjectInstanceOKBody +*/ +type DeleteProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete project instance o k body +func (o *DeleteProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete project instance o k body based on the context it is used +func (o *DeleteProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res DeleteProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instance_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instance_parameters.go new file mode 100644 index 0000000..f7def69 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instance_parameters.go @@ -0,0 +1,243 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeProjectInstanceParams creates a new DescribeProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeProjectInstanceParams() *DescribeProjectInstanceParams { + return &DescribeProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeProjectInstanceParamsWithTimeout creates a new DescribeProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewDescribeProjectInstanceParamsWithTimeout(timeout time.Duration) *DescribeProjectInstanceParams { + return &DescribeProjectInstanceParams{ + timeout: timeout, + } +} + +// NewDescribeProjectInstanceParamsWithContext creates a new DescribeProjectInstanceParams object +// with the ability to set a context for a request. +func NewDescribeProjectInstanceParamsWithContext(ctx context.Context) *DescribeProjectInstanceParams { + return &DescribeProjectInstanceParams{ + Context: ctx, + } +} + +// NewDescribeProjectInstanceParamsWithHTTPClient creates a new DescribeProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeProjectInstanceParamsWithHTTPClient(client *http.Client) *DescribeProjectInstanceParams { + return &DescribeProjectInstanceParams{ + HTTPClient: client, + } +} + +/* DescribeProjectInstanceParams contains all the parameters to send to the API endpoint + for the describe project instance operation. + + Typically these are written to a http.Request. +*/ +type DescribeProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* InstanceID. + + 实例uuid + */ + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeProjectInstanceParams) WithDefaults() *DescribeProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe project instance params +func (o *DescribeProjectInstanceParams) WithTimeout(timeout time.Duration) *DescribeProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe project instance params +func (o *DescribeProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe project instance params +func (o *DescribeProjectInstanceParams) WithContext(ctx context.Context) *DescribeProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe project instance params +func (o *DescribeProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe project instance params +func (o *DescribeProjectInstanceParams) WithHTTPClient(client *http.Client) *DescribeProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe project instance params +func (o *DescribeProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe project instance params +func (o *DescribeProjectInstanceParams) WithAuthorization(authorization string) *DescribeProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe project instance params +func (o *DescribeProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe project instance params +func (o *DescribeProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *DescribeProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe project instance params +func (o *DescribeProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe project instance params +func (o *DescribeProjectInstanceParams) WithBmpUserID(bmpUserID *string) *DescribeProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe project instance params +func (o *DescribeProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the describe project instance params +func (o *DescribeProjectInstanceParams) WithInstanceID(instanceID string) *DescribeProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the describe project instance params +func (o *DescribeProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the describe project instance params +func (o *DescribeProjectInstanceParams) WithTraceID(traceID string) *DescribeProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe project instance params +func (o *DescribeProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instance_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instance_responses.go new file mode 100644 index 0000000..128b26a --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeProjectInstanceReader is a Reader for the DescribeProjectInstance structure. +type DescribeProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeProjectInstanceOK creates a DescribeProjectInstanceOK with default headers values +func NewDescribeProjectInstanceOK() *DescribeProjectInstanceOK { + return &DescribeProjectInstanceOK{} +} + +/* DescribeProjectInstanceOK describes a response with status code 200, with default header values. + +A GetInstanceResult is an response struct that is used to describe instance. +*/ +type DescribeProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeProjectInstanceOKBody +} + +// IsSuccess returns true when this describe project instance o k response has a 2xx status code +func (o *DescribeProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe project instance o k response has a 3xx status code +func (o *DescribeProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe project instance o k response has a 4xx status code +func (o *DescribeProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe project instance o k response has a 5xx status code +func (o *DescribeProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe project instance o k response a status code equal to that given +func (o *DescribeProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeProjectInstanceOK) Error() string { + return fmt.Sprintf("[GET /project/instances/{instance_id}][%d] describeProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *DescribeProjectInstanceOK) String() string { + return fmt.Sprintf("[GET /project/instances/{instance_id}][%d] describeProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *DescribeProjectInstanceOK) GetPayload() *DescribeProjectInstanceOKBody { + return o.Payload +} + +func (o *DescribeProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeProjectInstanceDefault creates a DescribeProjectInstanceDefault with default headers values +func NewDescribeProjectInstanceDefault(code int) *DescribeProjectInstanceDefault { + return &DescribeProjectInstanceDefault{ + _statusCode: code, + } +} + +/* DescribeProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeProjectInstanceDefaultBody +} + +// Code gets the status code for the describe project instance default response +func (o *DescribeProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe project instance default response has a 2xx status code +func (o *DescribeProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe project instance default response has a 3xx status code +func (o *DescribeProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe project instance default response has a 4xx status code +func (o *DescribeProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe project instance default response has a 5xx status code +func (o *DescribeProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe project instance default response a status code equal to that given +func (o *DescribeProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeProjectInstanceDefault) Error() string { + return fmt.Sprintf("[GET /project/instances/{instance_id}][%d] describeProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeProjectInstanceDefault) String() string { + return fmt.Sprintf("[GET /project/instances/{instance_id}][%d] describeProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeProjectInstanceDefault) GetPayload() *DescribeProjectInstanceDefaultBody { + return o.Payload +} + +func (o *DescribeProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeProjectInstanceDefaultBody describe project instance default body +swagger:model DescribeProjectInstanceDefaultBody +*/ +type DescribeProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe project instance default body +func (o *DescribeProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe project instance default body based on the context it is used +func (o *DescribeProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeProjectInstanceOKBody describe project instance o k body +swagger:model DescribeProjectInstanceOKBody +*/ +type DescribeProjectInstanceOKBody struct { + + // result + Result *models.InstanceInfo `json:"result,omitempty"` +} + +// Validate validates this describe project instance o k body +func (o *DescribeProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe project instance o k body based on the context it is used +func (o *DescribeProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res DescribeProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instances_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instances_parameters.go new file mode 100644 index 0000000..cf169d0 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instances_parameters.go @@ -0,0 +1,702 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeProjectInstancesParams creates a new DescribeProjectInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeProjectInstancesParams() *DescribeProjectInstancesParams { + return &DescribeProjectInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeProjectInstancesParamsWithTimeout creates a new DescribeProjectInstancesParams object +// with the ability to set a timeout on a request. +func NewDescribeProjectInstancesParamsWithTimeout(timeout time.Duration) *DescribeProjectInstancesParams { + return &DescribeProjectInstancesParams{ + timeout: timeout, + } +} + +// NewDescribeProjectInstancesParamsWithContext creates a new DescribeProjectInstancesParams object +// with the ability to set a context for a request. +func NewDescribeProjectInstancesParamsWithContext(ctx context.Context) *DescribeProjectInstancesParams { + return &DescribeProjectInstancesParams{ + Context: ctx, + } +} + +// NewDescribeProjectInstancesParamsWithHTTPClient creates a new DescribeProjectInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeProjectInstancesParamsWithHTTPClient(client *http.Client) *DescribeProjectInstancesParams { + return &DescribeProjectInstancesParams{ + HTTPClient: client, + } +} + +/* DescribeProjectInstancesParams contains all the parameters to send to the API endpoint + for the describe project instances operation. + + Typically these are written to a http.Request. +*/ +type DescribeProjectInstancesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceID. + + 设备ID + */ + DeviceID *string + + /* DeviceTypeID. + + 设备类型ID + */ + DeviceTypeID *string + + /* IdcID. + + 机房ID + */ + IdcID *string + + /* IloIP. + + 带外ip,精确搜索 + */ + IloIP *string + + /* InstanceID. + + 实例ID + */ + InstanceID *string + + /* InstanceName. + + 实例名称,模糊搜索 + */ + InstanceName *string + + /* IPV4. + + ipv4,精确搜索 + */ + IPV4 *string + + /* IPV6. + + ipv6,精确搜索 + */ + IPV6 *string + + /* IsAll. + + 是否显示全部,取值为1时表示全部 + */ + IsAll *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* ProjectID. + + 项目ID + */ + ProjectID *string + + /* Sn. + + SN + */ + Sn *string + + /* Status. + + 运行状态 + */ + Status *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe project instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeProjectInstancesParams) WithDefaults() *DescribeProjectInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe project instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeProjectInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe project instances params +func (o *DescribeProjectInstancesParams) WithTimeout(timeout time.Duration) *DescribeProjectInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe project instances params +func (o *DescribeProjectInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe project instances params +func (o *DescribeProjectInstancesParams) WithContext(ctx context.Context) *DescribeProjectInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe project instances params +func (o *DescribeProjectInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe project instances params +func (o *DescribeProjectInstancesParams) WithHTTPClient(client *http.Client) *DescribeProjectInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe project instances params +func (o *DescribeProjectInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe project instances params +func (o *DescribeProjectInstancesParams) WithAuthorization(authorization string) *DescribeProjectInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe project instances params +func (o *DescribeProjectInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe project instances params +func (o *DescribeProjectInstancesParams) WithBmpLanguage(bmpLanguage *string) *DescribeProjectInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe project instances params +func (o *DescribeProjectInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithBmpUserID(bmpUserID *string) *DescribeProjectInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceID adds the deviceID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithDeviceID(deviceID *string) *DescribeProjectInstancesParams { + o.SetDeviceID(deviceID) + return o +} + +// SetDeviceID adds the deviceId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetDeviceID(deviceID *string) { + o.DeviceID = deviceID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithDeviceTypeID(deviceTypeID *string) *DescribeProjectInstancesParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithIdcID adds the idcID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIdcID(idcID *string) *DescribeProjectInstancesParams { + o.SetIdcID(idcID) + return o +} + +// SetIdcID adds the idcId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIdcID(idcID *string) { + o.IdcID = idcID +} + +// WithIloIP adds the iloIP to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIloIP(iloIP *string) *DescribeProjectInstancesParams { + o.SetIloIP(iloIP) + return o +} + +// SetIloIP adds the iloIp to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIloIP(iloIP *string) { + o.IloIP = iloIP +} + +// WithInstanceID adds the instanceID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithInstanceID(instanceID *string) *DescribeProjectInstancesParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetInstanceID(instanceID *string) { + o.InstanceID = instanceID +} + +// WithInstanceName adds the instanceName to the describe project instances params +func (o *DescribeProjectInstancesParams) WithInstanceName(instanceName *string) *DescribeProjectInstancesParams { + o.SetInstanceName(instanceName) + return o +} + +// SetInstanceName adds the instanceName to the describe project instances params +func (o *DescribeProjectInstancesParams) SetInstanceName(instanceName *string) { + o.InstanceName = instanceName +} + +// WithIPV4 adds the iPV4 to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIPV4(iPV4 *string) *DescribeProjectInstancesParams { + o.SetIPV4(iPV4) + return o +} + +// SetIPV4 adds the ipv4 to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIPV4(iPV4 *string) { + o.IPV4 = iPV4 +} + +// WithIPV6 adds the iPV6 to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIPV6(iPV6 *string) *DescribeProjectInstancesParams { + o.SetIPV6(iPV6) + return o +} + +// SetIPV6 adds the ipv6 to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIPV6(iPV6 *string) { + o.IPV6 = iPV6 +} + +// WithIsAll adds the isAll to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIsAll(isAll *string) *DescribeProjectInstancesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithPageNumber adds the pageNumber to the describe project instances params +func (o *DescribeProjectInstancesParams) WithPageNumber(pageNumber *int64) *DescribeProjectInstancesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe project instances params +func (o *DescribeProjectInstancesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe project instances params +func (o *DescribeProjectInstancesParams) WithPageSize(pageSize *int64) *DescribeProjectInstancesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe project instances params +func (o *DescribeProjectInstancesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithProjectID adds the projectID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithProjectID(projectID *string) *DescribeProjectInstancesParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetProjectID(projectID *string) { + o.ProjectID = projectID +} + +// WithSn adds the sn to the describe project instances params +func (o *DescribeProjectInstancesParams) WithSn(sn *string) *DescribeProjectInstancesParams { + o.SetSn(sn) + return o +} + +// SetSn adds the sn to the describe project instances params +func (o *DescribeProjectInstancesParams) SetSn(sn *string) { + o.Sn = sn +} + +// WithStatus adds the status to the describe project instances params +func (o *DescribeProjectInstancesParams) WithStatus(status *string) *DescribeProjectInstancesParams { + o.SetStatus(status) + return o +} + +// SetStatus adds the status to the describe project instances params +func (o *DescribeProjectInstancesParams) SetStatus(status *string) { + o.Status = status +} + +// WithTraceID adds the traceID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithTraceID(traceID string) *DescribeProjectInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeProjectInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceID != nil { + + // query param deviceId + var qrDeviceID string + + if o.DeviceID != nil { + qrDeviceID = *o.DeviceID + } + qDeviceID := qrDeviceID + if qDeviceID != "" { + + if err := r.SetQueryParam("deviceId", qDeviceID); err != nil { + return err + } + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.IdcID != nil { + + // query param idcId + var qrIdcID string + + if o.IdcID != nil { + qrIdcID = *o.IdcID + } + qIdcID := qrIdcID + if qIdcID != "" { + + if err := r.SetQueryParam("idcId", qIdcID); err != nil { + return err + } + } + } + + if o.IloIP != nil { + + // query param ilo_ip + var qrIloIP string + + if o.IloIP != nil { + qrIloIP = *o.IloIP + } + qIloIP := qrIloIP + if qIloIP != "" { + + if err := r.SetQueryParam("ilo_ip", qIloIP); err != nil { + return err + } + } + } + + if o.InstanceID != nil { + + // query param instanceId + var qrInstanceID string + + if o.InstanceID != nil { + qrInstanceID = *o.InstanceID + } + qInstanceID := qrInstanceID + if qInstanceID != "" { + + if err := r.SetQueryParam("instanceId", qInstanceID); err != nil { + return err + } + } + } + + if o.InstanceName != nil { + + // query param instanceName + var qrInstanceName string + + if o.InstanceName != nil { + qrInstanceName = *o.InstanceName + } + qInstanceName := qrInstanceName + if qInstanceName != "" { + + if err := r.SetQueryParam("instanceName", qInstanceName); err != nil { + return err + } + } + } + + if o.IPV4 != nil { + + // query param ipv4 + var qrIPV4 string + + if o.IPV4 != nil { + qrIPV4 = *o.IPV4 + } + qIPV4 := qrIPV4 + if qIPV4 != "" { + + if err := r.SetQueryParam("ipv4", qIPV4); err != nil { + return err + } + } + } + + if o.IPV6 != nil { + + // query param ipv6 + var qrIPV6 string + + if o.IPV6 != nil { + qrIPV6 = *o.IPV6 + } + qIPV6 := qrIPV6 + if qIPV6 != "" { + + if err := r.SetQueryParam("ipv6", qIPV6); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.ProjectID != nil { + + // query param projectId + var qrProjectID string + + if o.ProjectID != nil { + qrProjectID = *o.ProjectID + } + qProjectID := qrProjectID + if qProjectID != "" { + + if err := r.SetQueryParam("projectId", qProjectID); err != nil { + return err + } + } + } + + if o.Sn != nil { + + // query param sn + var qrSn string + + if o.Sn != nil { + qrSn = *o.Sn + } + qSn := qrSn + if qSn != "" { + + if err := r.SetQueryParam("sn", qSn); err != nil { + return err + } + } + } + + if o.Status != nil { + + // query param status + var qrStatus string + + if o.Status != nil { + qrStatus = *o.Status + } + qStatus := qrStatus + if qStatus != "" { + + if err := r.SetQueryParam("status", qStatus); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instances_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instances_responses.go new file mode 100644 index 0000000..172005e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeProjectInstancesReader is a Reader for the DescribeProjectInstances structure. +type DescribeProjectInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeProjectInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeProjectInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeProjectInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeProjectInstancesOK creates a DescribeProjectInstancesOK with default headers values +func NewDescribeProjectInstancesOK() *DescribeProjectInstancesOK { + return &DescribeProjectInstancesOK{} +} + +/* DescribeProjectInstancesOK describes a response with status code 200, with default header values. + +A DescribeProjectInstancesResult is an response struct that is used to get instance list. +*/ +type DescribeProjectInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeProjectInstancesOKBody +} + +// IsSuccess returns true when this describe project instances o k response has a 2xx status code +func (o *DescribeProjectInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe project instances o k response has a 3xx status code +func (o *DescribeProjectInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe project instances o k response has a 4xx status code +func (o *DescribeProjectInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe project instances o k response has a 5xx status code +func (o *DescribeProjectInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe project instances o k response a status code equal to that given +func (o *DescribeProjectInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeProjectInstancesOK) Error() string { + return fmt.Sprintf("[GET /project/instances][%d] describeProjectInstancesOK %+v", 200, o.Payload) +} + +func (o *DescribeProjectInstancesOK) String() string { + return fmt.Sprintf("[GET /project/instances][%d] describeProjectInstancesOK %+v", 200, o.Payload) +} + +func (o *DescribeProjectInstancesOK) GetPayload() *DescribeProjectInstancesOKBody { + return o.Payload +} + +func (o *DescribeProjectInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeProjectInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeProjectInstancesDefault creates a DescribeProjectInstancesDefault with default headers values +func NewDescribeProjectInstancesDefault(code int) *DescribeProjectInstancesDefault { + return &DescribeProjectInstancesDefault{ + _statusCode: code, + } +} + +/* DescribeProjectInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeProjectInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeProjectInstancesDefaultBody +} + +// Code gets the status code for the describe project instances default response +func (o *DescribeProjectInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe project instances default response has a 2xx status code +func (o *DescribeProjectInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe project instances default response has a 3xx status code +func (o *DescribeProjectInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe project instances default response has a 4xx status code +func (o *DescribeProjectInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe project instances default response has a 5xx status code +func (o *DescribeProjectInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe project instances default response a status code equal to that given +func (o *DescribeProjectInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeProjectInstancesDefault) Error() string { + return fmt.Sprintf("[GET /project/instances][%d] describeProjectInstances default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeProjectInstancesDefault) String() string { + return fmt.Sprintf("[GET /project/instances][%d] describeProjectInstances default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeProjectInstancesDefault) GetPayload() *DescribeProjectInstancesDefaultBody { + return o.Payload +} + +func (o *DescribeProjectInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeProjectInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeProjectInstancesDefaultBody describe project instances default body +swagger:model DescribeProjectInstancesDefaultBody +*/ +type DescribeProjectInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe project instances default body +func (o *DescribeProjectInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeProjectInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeProjectInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeProjectInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe project instances default body based on the context it is used +func (o *DescribeProjectInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeProjectInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeProjectInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeProjectInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeProjectInstancesOKBody describe project instances o k body +swagger:model DescribeProjectInstancesOKBody +*/ +type DescribeProjectInstancesOKBody struct { + + // result + Result *models.InstanceList `json:"result,omitempty"` +} + +// Validate validates this describe project instances o k body +func (o *DescribeProjectInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe project instances o k body based on the context it is used +func (o *DescribeProjectInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeProjectInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeProjectInstancesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeProjectInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/instance_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/instance_client.go new file mode 100644 index 0000000..5ebe75e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/instance_client.go @@ -0,0 +1,797 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new instance API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for instance API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateProjectInstance(params *CreateProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateProjectInstanceOK, error) + + DeleteInstances(params *DeleteInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteInstancesOK, error) + + DeleteProjectInstance(params *DeleteProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteProjectInstanceOK, error) + + DescribeProjectInstance(params *DescribeProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeProjectInstanceOK, error) + + DescribeProjectInstances(params *DescribeProjectInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeProjectInstancesOK, error) + + LockProjectInstance(params *LockProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*LockProjectInstanceOK, error) + + ModifyInstances(params *ModifyInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyInstancesOK, error) + + ModifyProjectInstance(params *ModifyProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyProjectInstanceOK, error) + + ReinstallProjectInstance(params *ReinstallProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ReinstallProjectInstanceOK, error) + + ResetInstanceStatus(params *ResetInstanceStatusParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetInstanceStatusOK, error) + + ResetProjectInstancePasswd(params *ResetProjectInstancePasswdParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetProjectInstancePasswdOK, error) + + ResetProjectInstancesPasswd(params *ResetProjectInstancesPasswdParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetProjectInstancesPasswdOK, error) + + RestartInstances(params *RestartInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RestartInstancesOK, error) + + RestartProjectInstance(params *RestartProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RestartProjectInstanceOK, error) + + StartInstances(params *StartInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StartInstancesOK, error) + + StartProjectInstance(params *StartProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StartProjectInstanceOK, error) + + StopInstances(params *StopInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StopInstancesOK, error) + + StopProjectInstance(params *StopProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StopProjectInstanceOK, error) + + UnLockProjectInstance(params *UnLockProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UnLockProjectInstanceOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateProjectInstance CreateProjectInstance 创建实例 +*/ +func (a *Client) CreateProjectInstance(params *CreateProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "createProjectInstance", + Method: "POST", + PathPattern: "/project/instances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteInstances DeleteInstances 批量删除实例 +*/ +func (a *Client) DeleteInstances(params *DeleteInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "deleteInstances", + Method: "DELETE", + PathPattern: "/project/instances/batch/instances:deleteInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteProjectInstance DeleteProjectInstance 删除实例 +*/ +func (a *Client) DeleteProjectInstance(params *DeleteProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "deleteProjectInstance", + Method: "DELETE", + PathPattern: "/project/instances/{instance_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeProjectInstance DescribeProjectInstance 获取实例详情 +*/ +func (a *Client) DescribeProjectInstance(params *DescribeProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "describeProjectInstance", + Method: "GET", + PathPattern: "/project/instances/{instance_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeProjectInstances DescribeProjectInstances 获取实例列表 +*/ +func (a *Client) DescribeProjectInstances(params *DescribeProjectInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeProjectInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeProjectInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "describeProjectInstances", + Method: "GET", + PathPattern: "/project/instances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeProjectInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeProjectInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeProjectInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + LockProjectInstance LockProjectInstance 锁定实例 +*/ +func (a *Client) LockProjectInstance(params *LockProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*LockProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewLockProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "lockProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/lock", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &LockProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*LockProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*LockProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyInstances ModifyInstances 批量修改实例名称 +*/ +func (a *Client) ModifyInstances(params *ModifyInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "modifyInstances", + Method: "PUT", + PathPattern: "/project/instances/batch/instances:modifyInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyProjectInstance ModifyProjectInstance 修改实例信息 +*/ +func (a *Client) ModifyProjectInstance(params *ModifyProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "modifyProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ReinstallProjectInstance ReinstallInstance 重装实例 +*/ +func (a *Client) ReinstallProjectInstance(params *ReinstallProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ReinstallProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewReinstallProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "reinstallProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/reinstallInstance", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ReinstallProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ReinstallProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ReinstallProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ResetInstanceStatus ResetInstanceStatus 重置实例状态 +*/ +func (a *Client) ResetInstanceStatus(params *ResetInstanceStatusParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetInstanceStatusOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewResetInstanceStatusParams() + } + op := &runtime.ClientOperation{ + ID: "resetInstanceStatus", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/resetStatus", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ResetInstanceStatusReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ResetInstanceStatusOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ResetInstanceStatusDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ResetProjectInstancePasswd ResetPasswd 重置密码 +*/ +func (a *Client) ResetProjectInstancePasswd(params *ResetProjectInstancePasswdParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetProjectInstancePasswdOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewResetProjectInstancePasswdParams() + } + op := &runtime.ClientOperation{ + ID: "resetProjectInstancePasswd", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/resetpasswd", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ResetProjectInstancePasswdReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ResetProjectInstancePasswdOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ResetProjectInstancePasswdDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ResetProjectInstancesPasswd ResetInstancesPasswd 批量重置密码 +*/ +func (a *Client) ResetProjectInstancesPasswd(params *ResetProjectInstancesPasswdParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetProjectInstancesPasswdOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewResetProjectInstancesPasswdParams() + } + op := &runtime.ClientOperation{ + ID: "resetProjectInstancesPasswd", + Method: "PUT", + PathPattern: "/project/instances/batch/instances:resetPasswd", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ResetProjectInstancesPasswdReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ResetProjectInstancesPasswdOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ResetProjectInstancesPasswdDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + RestartInstances StartInstances 批量重启 +*/ +func (a *Client) RestartInstances(params *RestartInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RestartInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewRestartInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "restartInstances", + Method: "PUT", + PathPattern: "/project/instances/batch/instances:restartInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &RestartInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*RestartInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*RestartInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + RestartProjectInstance RestartProjectInstance 实例重启 +*/ +func (a *Client) RestartProjectInstance(params *RestartProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RestartProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewRestartProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "restartProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/restart", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &RestartProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*RestartProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*RestartProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + StartInstances StartInstances 批量开机 +*/ +func (a *Client) StartInstances(params *StartInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StartInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewStartInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "startInstances", + Method: "PUT", + PathPattern: "/project/instances/batch/instances:startInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &StartInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*StartInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*StartInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + StartProjectInstance StartProjectInstance 实例开机 +*/ +func (a *Client) StartProjectInstance(params *StartProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StartProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewStartProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "startProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/start", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &StartProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*StartProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*StartProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + StopInstances StartInstances 批量关机 +*/ +func (a *Client) StopInstances(params *StopInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StopInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewStopInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "stopInstances", + Method: "PUT", + PathPattern: "/project/instances/batch/instances:stopInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &StopInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*StopInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*StopInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + StopProjectInstance StopProjectInstance 实例关机 +*/ +func (a *Client) StopProjectInstance(params *StopProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StopProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewStopProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "stopProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/stop", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &StopProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*StopProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*StopProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + UnLockProjectInstance UnLockProjectInstance 解锁实例 +*/ +func (a *Client) UnLockProjectInstance(params *UnLockProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UnLockProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewUnLockProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "unLockProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/unlock", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UnLockProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*UnLockProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*UnLockProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/lock_project_instance_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/lock_project_instance_parameters.go new file mode 100644 index 0000000..8758de3 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/lock_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewLockProjectInstanceParams creates a new LockProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewLockProjectInstanceParams() *LockProjectInstanceParams { + return &LockProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewLockProjectInstanceParamsWithTimeout creates a new LockProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewLockProjectInstanceParamsWithTimeout(timeout time.Duration) *LockProjectInstanceParams { + return &LockProjectInstanceParams{ + timeout: timeout, + } +} + +// NewLockProjectInstanceParamsWithContext creates a new LockProjectInstanceParams object +// with the ability to set a context for a request. +func NewLockProjectInstanceParamsWithContext(ctx context.Context) *LockProjectInstanceParams { + return &LockProjectInstanceParams{ + Context: ctx, + } +} + +// NewLockProjectInstanceParamsWithHTTPClient creates a new LockProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewLockProjectInstanceParamsWithHTTPClient(client *http.Client) *LockProjectInstanceParams { + return &LockProjectInstanceParams{ + HTTPClient: client, + } +} + +/* LockProjectInstanceParams contains all the parameters to send to the API endpoint + for the lock project instance operation. + + Typically these are written to a http.Request. +*/ +type LockProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the lock project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *LockProjectInstanceParams) WithDefaults() *LockProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the lock project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *LockProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the lock project instance params +func (o *LockProjectInstanceParams) WithTimeout(timeout time.Duration) *LockProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the lock project instance params +func (o *LockProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the lock project instance params +func (o *LockProjectInstanceParams) WithContext(ctx context.Context) *LockProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the lock project instance params +func (o *LockProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the lock project instance params +func (o *LockProjectInstanceParams) WithHTTPClient(client *http.Client) *LockProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the lock project instance params +func (o *LockProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the lock project instance params +func (o *LockProjectInstanceParams) WithAuthorization(authorization string) *LockProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the lock project instance params +func (o *LockProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the lock project instance params +func (o *LockProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *LockProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the lock project instance params +func (o *LockProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the lock project instance params +func (o *LockProjectInstanceParams) WithBmpUserID(bmpUserID *string) *LockProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the lock project instance params +func (o *LockProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the lock project instance params +func (o *LockProjectInstanceParams) WithInstanceID(instanceID string) *LockProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the lock project instance params +func (o *LockProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the lock project instance params +func (o *LockProjectInstanceParams) WithTraceID(traceID string) *LockProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the lock project instance params +func (o *LockProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *LockProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/lock_project_instance_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/lock_project_instance_responses.go new file mode 100644 index 0000000..a8e125f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/lock_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// LockProjectInstanceReader is a Reader for the LockProjectInstance structure. +type LockProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *LockProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewLockProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewLockProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewLockProjectInstanceOK creates a LockProjectInstanceOK with default headers values +func NewLockProjectInstanceOK() *LockProjectInstanceOK { + return &LockProjectInstanceOK{} +} + +/* LockProjectInstanceOK describes a response with status code 200, with default header values. + +A LockProjectInstanceResult is an response struct that is used to describe lock instance result. +*/ +type LockProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *LockProjectInstanceOKBody +} + +// IsSuccess returns true when this lock project instance o k response has a 2xx status code +func (o *LockProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this lock project instance o k response has a 3xx status code +func (o *LockProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this lock project instance o k response has a 4xx status code +func (o *LockProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this lock project instance o k response has a 5xx status code +func (o *LockProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this lock project instance o k response a status code equal to that given +func (o *LockProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *LockProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/lock][%d] lockProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *LockProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/lock][%d] lockProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *LockProjectInstanceOK) GetPayload() *LockProjectInstanceOKBody { + return o.Payload +} + +func (o *LockProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(LockProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewLockProjectInstanceDefault creates a LockProjectInstanceDefault with default headers values +func NewLockProjectInstanceDefault(code int) *LockProjectInstanceDefault { + return &LockProjectInstanceDefault{ + _statusCode: code, + } +} + +/* LockProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type LockProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *LockProjectInstanceDefaultBody +} + +// Code gets the status code for the lock project instance default response +func (o *LockProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this lock project instance default response has a 2xx status code +func (o *LockProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this lock project instance default response has a 3xx status code +func (o *LockProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this lock project instance default response has a 4xx status code +func (o *LockProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this lock project instance default response has a 5xx status code +func (o *LockProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this lock project instance default response a status code equal to that given +func (o *LockProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *LockProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/lock][%d] lockProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *LockProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/lock][%d] lockProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *LockProjectInstanceDefault) GetPayload() *LockProjectInstanceDefaultBody { + return o.Payload +} + +func (o *LockProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(LockProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*LockProjectInstanceDefaultBody lock project instance default body +swagger:model LockProjectInstanceDefaultBody +*/ +type LockProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this lock project instance default body +func (o *LockProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *LockProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("lockProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *LockProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("lockProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("lockProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("lockProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this lock project instance default body based on the context it is used +func (o *LockProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *LockProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("lockProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("lockProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *LockProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *LockProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res LockProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*LockProjectInstanceOKBody lock project instance o k body +swagger:model LockProjectInstanceOKBody +*/ +type LockProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this lock project instance o k body +func (o *LockProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *LockProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("lockProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("lockProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this lock project instance o k body based on the context it is used +func (o *LockProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *LockProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("lockProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("lockProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *LockProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *LockProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res LockProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/modify_instances_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/modify_instances_parameters.go new file mode 100644 index 0000000..8354293 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/modify_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyInstancesParams creates a new ModifyInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyInstancesParams() *ModifyInstancesParams { + return &ModifyInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyInstancesParamsWithTimeout creates a new ModifyInstancesParams object +// with the ability to set a timeout on a request. +func NewModifyInstancesParamsWithTimeout(timeout time.Duration) *ModifyInstancesParams { + return &ModifyInstancesParams{ + timeout: timeout, + } +} + +// NewModifyInstancesParamsWithContext creates a new ModifyInstancesParams object +// with the ability to set a context for a request. +func NewModifyInstancesParamsWithContext(ctx context.Context) *ModifyInstancesParams { + return &ModifyInstancesParams{ + Context: ctx, + } +} + +// NewModifyInstancesParamsWithHTTPClient creates a new ModifyInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyInstancesParamsWithHTTPClient(client *http.Client) *ModifyInstancesParams { + return &ModifyInstancesParams{ + HTTPClient: client, + } +} + +/* ModifyInstancesParams contains all the parameters to send to the API endpoint + for the modify instances operation. + + Typically these are written to a http.Request. +*/ +type ModifyInstancesParams struct { + + // Body. + Body *models.ModifyInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyInstancesParams) WithDefaults() *ModifyInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify instances params +func (o *ModifyInstancesParams) WithTimeout(timeout time.Duration) *ModifyInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify instances params +func (o *ModifyInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify instances params +func (o *ModifyInstancesParams) WithContext(ctx context.Context) *ModifyInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify instances params +func (o *ModifyInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify instances params +func (o *ModifyInstancesParams) WithHTTPClient(client *http.Client) *ModifyInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify instances params +func (o *ModifyInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify instances params +func (o *ModifyInstancesParams) WithBody(body *models.ModifyInstancesRequest) *ModifyInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify instances params +func (o *ModifyInstancesParams) SetBody(body *models.ModifyInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify instances params +func (o *ModifyInstancesParams) WithAuthorization(authorization string) *ModifyInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify instances params +func (o *ModifyInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify instances params +func (o *ModifyInstancesParams) WithBmpLanguage(bmpLanguage *string) *ModifyInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify instances params +func (o *ModifyInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify instances params +func (o *ModifyInstancesParams) WithBmpUserID(bmpUserID *string) *ModifyInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify instances params +func (o *ModifyInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the modify instances params +func (o *ModifyInstancesParams) WithTraceID(traceID string) *ModifyInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify instances params +func (o *ModifyInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/modify_instances_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/modify_instances_responses.go new file mode 100644 index 0000000..9b8eec6 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/modify_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyInstancesReader is a Reader for the ModifyInstances structure. +type ModifyInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyInstancesOK creates a ModifyInstancesOK with default headers values +func NewModifyInstancesOK() *ModifyInstancesOK { + return &ModifyInstancesOK{} +} + +/* ModifyInstancesOK describes a response with status code 200, with default header values. + +A ModifyInstancesResult is an response struct that is used to describe modify instance result. +*/ +type ModifyInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyInstancesOKBody +} + +// IsSuccess returns true when this modify instances o k response has a 2xx status code +func (o *ModifyInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify instances o k response has a 3xx status code +func (o *ModifyInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify instances o k response has a 4xx status code +func (o *ModifyInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify instances o k response has a 5xx status code +func (o *ModifyInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify instances o k response a status code equal to that given +func (o *ModifyInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyInstancesOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:modifyInstances][%d] modifyInstancesOK %+v", 200, o.Payload) +} + +func (o *ModifyInstancesOK) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:modifyInstances][%d] modifyInstancesOK %+v", 200, o.Payload) +} + +func (o *ModifyInstancesOK) GetPayload() *ModifyInstancesOKBody { + return o.Payload +} + +func (o *ModifyInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyInstancesDefault creates a ModifyInstancesDefault with default headers values +func NewModifyInstancesDefault(code int) *ModifyInstancesDefault { + return &ModifyInstancesDefault{ + _statusCode: code, + } +} + +/* ModifyInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyInstancesDefaultBody +} + +// Code gets the status code for the modify instances default response +func (o *ModifyInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify instances default response has a 2xx status code +func (o *ModifyInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify instances default response has a 3xx status code +func (o *ModifyInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify instances default response has a 4xx status code +func (o *ModifyInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify instances default response has a 5xx status code +func (o *ModifyInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify instances default response a status code equal to that given +func (o *ModifyInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyInstancesDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:modifyInstances][%d] modifyInstances default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyInstancesDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:modifyInstances][%d] modifyInstances default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyInstancesDefault) GetPayload() *ModifyInstancesDefaultBody { + return o.Payload +} + +func (o *ModifyInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyInstancesDefaultBody modify instances default body +swagger:model ModifyInstancesDefaultBody +*/ +type ModifyInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify instances default body +func (o *ModifyInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify instances default body based on the context it is used +func (o *ModifyInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyInstancesOKBody modify instances o k body +swagger:model ModifyInstancesOKBody +*/ +type ModifyInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify instances o k body +func (o *ModifyInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify instances o k body based on the context it is used +func (o *ModifyInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyInstancesOKBody) UnmarshalBinary(b []byte) error { + var res ModifyInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/modify_project_instance_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/modify_project_instance_parameters.go new file mode 100644 index 0000000..8608e78 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/modify_project_instance_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyProjectInstanceParams creates a new ModifyProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyProjectInstanceParams() *ModifyProjectInstanceParams { + return &ModifyProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyProjectInstanceParamsWithTimeout creates a new ModifyProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewModifyProjectInstanceParamsWithTimeout(timeout time.Duration) *ModifyProjectInstanceParams { + return &ModifyProjectInstanceParams{ + timeout: timeout, + } +} + +// NewModifyProjectInstanceParamsWithContext creates a new ModifyProjectInstanceParams object +// with the ability to set a context for a request. +func NewModifyProjectInstanceParamsWithContext(ctx context.Context) *ModifyProjectInstanceParams { + return &ModifyProjectInstanceParams{ + Context: ctx, + } +} + +// NewModifyProjectInstanceParamsWithHTTPClient creates a new ModifyProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyProjectInstanceParamsWithHTTPClient(client *http.Client) *ModifyProjectInstanceParams { + return &ModifyProjectInstanceParams{ + HTTPClient: client, + } +} + +/* ModifyProjectInstanceParams contains all the parameters to send to the API endpoint + for the modify project instance operation. + + Typically these are written to a http.Request. +*/ +type ModifyProjectInstanceParams struct { + + // Body. + Body *models.ModifyInstanceRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyProjectInstanceParams) WithDefaults() *ModifyProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify project instance params +func (o *ModifyProjectInstanceParams) WithTimeout(timeout time.Duration) *ModifyProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify project instance params +func (o *ModifyProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify project instance params +func (o *ModifyProjectInstanceParams) WithContext(ctx context.Context) *ModifyProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify project instance params +func (o *ModifyProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify project instance params +func (o *ModifyProjectInstanceParams) WithHTTPClient(client *http.Client) *ModifyProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify project instance params +func (o *ModifyProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify project instance params +func (o *ModifyProjectInstanceParams) WithBody(body *models.ModifyInstanceRequest) *ModifyProjectInstanceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify project instance params +func (o *ModifyProjectInstanceParams) SetBody(body *models.ModifyInstanceRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify project instance params +func (o *ModifyProjectInstanceParams) WithAuthorization(authorization string) *ModifyProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify project instance params +func (o *ModifyProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify project instance params +func (o *ModifyProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *ModifyProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify project instance params +func (o *ModifyProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify project instance params +func (o *ModifyProjectInstanceParams) WithBmpUserID(bmpUserID *string) *ModifyProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify project instance params +func (o *ModifyProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the modify project instance params +func (o *ModifyProjectInstanceParams) WithInstanceID(instanceID string) *ModifyProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the modify project instance params +func (o *ModifyProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the modify project instance params +func (o *ModifyProjectInstanceParams) WithTraceID(traceID string) *ModifyProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify project instance params +func (o *ModifyProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/modify_project_instance_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/modify_project_instance_responses.go new file mode 100644 index 0000000..e22862e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/modify_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyProjectInstanceReader is a Reader for the ModifyProjectInstance structure. +type ModifyProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyProjectInstanceOK creates a ModifyProjectInstanceOK with default headers values +func NewModifyProjectInstanceOK() *ModifyProjectInstanceOK { + return &ModifyProjectInstanceOK{} +} + +/* ModifyProjectInstanceOK describes a response with status code 200, with default header values. + +A ModifyProjectInstanceResult is an response struct that is used to describe modify instance result. +*/ +type ModifyProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyProjectInstanceOKBody +} + +// IsSuccess returns true when this modify project instance o k response has a 2xx status code +func (o *ModifyProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify project instance o k response has a 3xx status code +func (o *ModifyProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify project instance o k response has a 4xx status code +func (o *ModifyProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify project instance o k response has a 5xx status code +func (o *ModifyProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify project instance o k response a status code equal to that given +func (o *ModifyProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}][%d] modifyProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *ModifyProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}][%d] modifyProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *ModifyProjectInstanceOK) GetPayload() *ModifyProjectInstanceOKBody { + return o.Payload +} + +func (o *ModifyProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyProjectInstanceDefault creates a ModifyProjectInstanceDefault with default headers values +func NewModifyProjectInstanceDefault(code int) *ModifyProjectInstanceDefault { + return &ModifyProjectInstanceDefault{ + _statusCode: code, + } +} + +/* ModifyProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyProjectInstanceDefaultBody +} + +// Code gets the status code for the modify project instance default response +func (o *ModifyProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify project instance default response has a 2xx status code +func (o *ModifyProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify project instance default response has a 3xx status code +func (o *ModifyProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify project instance default response has a 4xx status code +func (o *ModifyProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify project instance default response has a 5xx status code +func (o *ModifyProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify project instance default response a status code equal to that given +func (o *ModifyProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}][%d] modifyProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}][%d] modifyProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyProjectInstanceDefault) GetPayload() *ModifyProjectInstanceDefaultBody { + return o.Payload +} + +func (o *ModifyProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyProjectInstanceDefaultBody modify project instance default body +swagger:model ModifyProjectInstanceDefaultBody +*/ +type ModifyProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify project instance default body +func (o *ModifyProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify project instance default body based on the context it is used +func (o *ModifyProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyProjectInstanceOKBody modify project instance o k body +swagger:model ModifyProjectInstanceOKBody +*/ +type ModifyProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify project instance o k body +func (o *ModifyProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify project instance o k body based on the context it is used +func (o *ModifyProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res ModifyProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reinstall_project_instance_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reinstall_project_instance_parameters.go new file mode 100644 index 0000000..fe4605d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reinstall_project_instance_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewReinstallProjectInstanceParams creates a new ReinstallProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewReinstallProjectInstanceParams() *ReinstallProjectInstanceParams { + return &ReinstallProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewReinstallProjectInstanceParamsWithTimeout creates a new ReinstallProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewReinstallProjectInstanceParamsWithTimeout(timeout time.Duration) *ReinstallProjectInstanceParams { + return &ReinstallProjectInstanceParams{ + timeout: timeout, + } +} + +// NewReinstallProjectInstanceParamsWithContext creates a new ReinstallProjectInstanceParams object +// with the ability to set a context for a request. +func NewReinstallProjectInstanceParamsWithContext(ctx context.Context) *ReinstallProjectInstanceParams { + return &ReinstallProjectInstanceParams{ + Context: ctx, + } +} + +// NewReinstallProjectInstanceParamsWithHTTPClient creates a new ReinstallProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewReinstallProjectInstanceParamsWithHTTPClient(client *http.Client) *ReinstallProjectInstanceParams { + return &ReinstallProjectInstanceParams{ + HTTPClient: client, + } +} + +/* ReinstallProjectInstanceParams contains all the parameters to send to the API endpoint + for the reinstall project instance operation. + + Typically these are written to a http.Request. +*/ +type ReinstallProjectInstanceParams struct { + + // Body. + Body *models.ReinstallInstanceRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the reinstall project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ReinstallProjectInstanceParams) WithDefaults() *ReinstallProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the reinstall project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ReinstallProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithTimeout(timeout time.Duration) *ReinstallProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithContext(ctx context.Context) *ReinstallProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithHTTPClient(client *http.Client) *ReinstallProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithBody(body *models.ReinstallInstanceRequest) *ReinstallProjectInstanceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetBody(body *models.ReinstallInstanceRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithAuthorization(authorization string) *ReinstallProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *ReinstallProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithBmpUserID(bmpUserID *string) *ReinstallProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithInstanceID(instanceID string) *ReinstallProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithTraceID(traceID string) *ReinstallProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ReinstallProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reinstall_project_instance_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reinstall_project_instance_responses.go new file mode 100644 index 0000000..7786a73 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reinstall_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ReinstallProjectInstanceReader is a Reader for the ReinstallProjectInstance structure. +type ReinstallProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ReinstallProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewReinstallProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewReinstallProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewReinstallProjectInstanceOK creates a ReinstallProjectInstanceOK with default headers values +func NewReinstallProjectInstanceOK() *ReinstallProjectInstanceOK { + return &ReinstallProjectInstanceOK{} +} + +/* ReinstallProjectInstanceOK describes a response with status code 200, with default header values. + +A ReinstallProjectInstanceResult is an response struct that is used to describe reinstall instance. +*/ +type ReinstallProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ReinstallProjectInstanceOKBody +} + +// IsSuccess returns true when this reinstall project instance o k response has a 2xx status code +func (o *ReinstallProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this reinstall project instance o k response has a 3xx status code +func (o *ReinstallProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this reinstall project instance o k response has a 4xx status code +func (o *ReinstallProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this reinstall project instance o k response has a 5xx status code +func (o *ReinstallProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this reinstall project instance o k response a status code equal to that given +func (o *ReinstallProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ReinstallProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/reinstallInstance][%d] reinstallProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *ReinstallProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/reinstallInstance][%d] reinstallProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *ReinstallProjectInstanceOK) GetPayload() *ReinstallProjectInstanceOKBody { + return o.Payload +} + +func (o *ReinstallProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ReinstallProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewReinstallProjectInstanceDefault creates a ReinstallProjectInstanceDefault with default headers values +func NewReinstallProjectInstanceDefault(code int) *ReinstallProjectInstanceDefault { + return &ReinstallProjectInstanceDefault{ + _statusCode: code, + } +} + +/* ReinstallProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ReinstallProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ReinstallProjectInstanceDefaultBody +} + +// Code gets the status code for the reinstall project instance default response +func (o *ReinstallProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this reinstall project instance default response has a 2xx status code +func (o *ReinstallProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this reinstall project instance default response has a 3xx status code +func (o *ReinstallProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this reinstall project instance default response has a 4xx status code +func (o *ReinstallProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this reinstall project instance default response has a 5xx status code +func (o *ReinstallProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this reinstall project instance default response a status code equal to that given +func (o *ReinstallProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ReinstallProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/reinstallInstance][%d] reinstallProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *ReinstallProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/reinstallInstance][%d] reinstallProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *ReinstallProjectInstanceDefault) GetPayload() *ReinstallProjectInstanceDefaultBody { + return o.Payload +} + +func (o *ReinstallProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ReinstallProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ReinstallProjectInstanceDefaultBody reinstall project instance default body +swagger:model ReinstallProjectInstanceDefaultBody +*/ +type ReinstallProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this reinstall project instance default body +func (o *ReinstallProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReinstallProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("reinstallProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ReinstallProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("reinstallProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("reinstallProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("reinstallProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reinstall project instance default body based on the context it is used +func (o *ReinstallProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReinstallProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("reinstallProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("reinstallProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ReinstallProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ReinstallProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res ReinstallProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ReinstallProjectInstanceOKBody reinstall project instance o k body +swagger:model ReinstallProjectInstanceOKBody +*/ +type ReinstallProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this reinstall project instance o k body +func (o *ReinstallProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReinstallProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("reinstallProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("reinstallProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reinstall project instance o k body based on the context it is used +func (o *ReinstallProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReinstallProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("reinstallProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("reinstallProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ReinstallProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ReinstallProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res ReinstallProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_instance_status_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_instance_status_parameters.go new file mode 100644 index 0000000..853f1fe --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_instance_status_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewResetInstanceStatusParams creates a new ResetInstanceStatusParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewResetInstanceStatusParams() *ResetInstanceStatusParams { + return &ResetInstanceStatusParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewResetInstanceStatusParamsWithTimeout creates a new ResetInstanceStatusParams object +// with the ability to set a timeout on a request. +func NewResetInstanceStatusParamsWithTimeout(timeout time.Duration) *ResetInstanceStatusParams { + return &ResetInstanceStatusParams{ + timeout: timeout, + } +} + +// NewResetInstanceStatusParamsWithContext creates a new ResetInstanceStatusParams object +// with the ability to set a context for a request. +func NewResetInstanceStatusParamsWithContext(ctx context.Context) *ResetInstanceStatusParams { + return &ResetInstanceStatusParams{ + Context: ctx, + } +} + +// NewResetInstanceStatusParamsWithHTTPClient creates a new ResetInstanceStatusParams object +// with the ability to set a custom HTTPClient for a request. +func NewResetInstanceStatusParamsWithHTTPClient(client *http.Client) *ResetInstanceStatusParams { + return &ResetInstanceStatusParams{ + HTTPClient: client, + } +} + +/* ResetInstanceStatusParams contains all the parameters to send to the API endpoint + for the reset instance status operation. + + Typically these are written to a http.Request. +*/ +type ResetInstanceStatusParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the reset instance status params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetInstanceStatusParams) WithDefaults() *ResetInstanceStatusParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the reset instance status params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetInstanceStatusParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the reset instance status params +func (o *ResetInstanceStatusParams) WithTimeout(timeout time.Duration) *ResetInstanceStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the reset instance status params +func (o *ResetInstanceStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the reset instance status params +func (o *ResetInstanceStatusParams) WithContext(ctx context.Context) *ResetInstanceStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the reset instance status params +func (o *ResetInstanceStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the reset instance status params +func (o *ResetInstanceStatusParams) WithHTTPClient(client *http.Client) *ResetInstanceStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the reset instance status params +func (o *ResetInstanceStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the reset instance status params +func (o *ResetInstanceStatusParams) WithAuthorization(authorization string) *ResetInstanceStatusParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the reset instance status params +func (o *ResetInstanceStatusParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the reset instance status params +func (o *ResetInstanceStatusParams) WithBmpLanguage(bmpLanguage *string) *ResetInstanceStatusParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the reset instance status params +func (o *ResetInstanceStatusParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the reset instance status params +func (o *ResetInstanceStatusParams) WithBmpUserID(bmpUserID *string) *ResetInstanceStatusParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the reset instance status params +func (o *ResetInstanceStatusParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the reset instance status params +func (o *ResetInstanceStatusParams) WithInstanceID(instanceID string) *ResetInstanceStatusParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the reset instance status params +func (o *ResetInstanceStatusParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the reset instance status params +func (o *ResetInstanceStatusParams) WithTraceID(traceID string) *ResetInstanceStatusParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the reset instance status params +func (o *ResetInstanceStatusParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ResetInstanceStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_instance_status_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_instance_status_responses.go new file mode 100644 index 0000000..5da5276 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_instance_status_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ResetInstanceStatusReader is a Reader for the ResetInstanceStatus structure. +type ResetInstanceStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ResetInstanceStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewResetInstanceStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewResetInstanceStatusDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewResetInstanceStatusOK creates a ResetInstanceStatusOK with default headers values +func NewResetInstanceStatusOK() *ResetInstanceStatusOK { + return &ResetInstanceStatusOK{} +} + +/* ResetInstanceStatusOK describes a response with status code 200, with default header values. + +A ResetInstanceStatusResult is an response struct that is used to describe restart instance result. +*/ +type ResetInstanceStatusOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetInstanceStatusOKBody +} + +// IsSuccess returns true when this reset instance status o k response has a 2xx status code +func (o *ResetInstanceStatusOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this reset instance status o k response has a 3xx status code +func (o *ResetInstanceStatusOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this reset instance status o k response has a 4xx status code +func (o *ResetInstanceStatusOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this reset instance status o k response has a 5xx status code +func (o *ResetInstanceStatusOK) IsServerError() bool { + return false +} + +// IsCode returns true when this reset instance status o k response a status code equal to that given +func (o *ResetInstanceStatusOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ResetInstanceStatusOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetStatus][%d] resetInstanceStatusOK %+v", 200, o.Payload) +} + +func (o *ResetInstanceStatusOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetStatus][%d] resetInstanceStatusOK %+v", 200, o.Payload) +} + +func (o *ResetInstanceStatusOK) GetPayload() *ResetInstanceStatusOKBody { + return o.Payload +} + +func (o *ResetInstanceStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetInstanceStatusOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewResetInstanceStatusDefault creates a ResetInstanceStatusDefault with default headers values +func NewResetInstanceStatusDefault(code int) *ResetInstanceStatusDefault { + return &ResetInstanceStatusDefault{ + _statusCode: code, + } +} + +/* ResetInstanceStatusDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ResetInstanceStatusDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetInstanceStatusDefaultBody +} + +// Code gets the status code for the reset instance status default response +func (o *ResetInstanceStatusDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this reset instance status default response has a 2xx status code +func (o *ResetInstanceStatusDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this reset instance status default response has a 3xx status code +func (o *ResetInstanceStatusDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this reset instance status default response has a 4xx status code +func (o *ResetInstanceStatusDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this reset instance status default response has a 5xx status code +func (o *ResetInstanceStatusDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this reset instance status default response a status code equal to that given +func (o *ResetInstanceStatusDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ResetInstanceStatusDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetStatus][%d] resetInstanceStatus default %+v", o._statusCode, o.Payload) +} + +func (o *ResetInstanceStatusDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetStatus][%d] resetInstanceStatus default %+v", o._statusCode, o.Payload) +} + +func (o *ResetInstanceStatusDefault) GetPayload() *ResetInstanceStatusDefaultBody { + return o.Payload +} + +func (o *ResetInstanceStatusDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetInstanceStatusDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ResetInstanceStatusDefaultBody reset instance status default body +swagger:model ResetInstanceStatusDefaultBody +*/ +type ResetInstanceStatusDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this reset instance status default body +func (o *ResetInstanceStatusDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetInstanceStatusDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("resetInstanceStatus default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ResetInstanceStatusDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("resetInstanceStatus default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetInstanceStatus default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetInstanceStatus default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset instance status default body based on the context it is used +func (o *ResetInstanceStatusDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetInstanceStatusDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetInstanceStatus default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetInstanceStatus default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetInstanceStatusDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetInstanceStatusDefaultBody) UnmarshalBinary(b []byte) error { + var res ResetInstanceStatusDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ResetInstanceStatusOKBody reset instance status o k body +swagger:model ResetInstanceStatusOKBody +*/ +type ResetInstanceStatusOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this reset instance status o k body +func (o *ResetInstanceStatusOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetInstanceStatusOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetInstanceStatusOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetInstanceStatusOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset instance status o k body based on the context it is used +func (o *ResetInstanceStatusOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetInstanceStatusOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetInstanceStatusOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetInstanceStatusOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetInstanceStatusOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetInstanceStatusOKBody) UnmarshalBinary(b []byte) error { + var res ResetInstanceStatusOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instance_passwd_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instance_passwd_parameters.go new file mode 100644 index 0000000..e7c5925 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instance_passwd_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewResetProjectInstancePasswdParams creates a new ResetProjectInstancePasswdParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewResetProjectInstancePasswdParams() *ResetProjectInstancePasswdParams { + return &ResetProjectInstancePasswdParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewResetProjectInstancePasswdParamsWithTimeout creates a new ResetProjectInstancePasswdParams object +// with the ability to set a timeout on a request. +func NewResetProjectInstancePasswdParamsWithTimeout(timeout time.Duration) *ResetProjectInstancePasswdParams { + return &ResetProjectInstancePasswdParams{ + timeout: timeout, + } +} + +// NewResetProjectInstancePasswdParamsWithContext creates a new ResetProjectInstancePasswdParams object +// with the ability to set a context for a request. +func NewResetProjectInstancePasswdParamsWithContext(ctx context.Context) *ResetProjectInstancePasswdParams { + return &ResetProjectInstancePasswdParams{ + Context: ctx, + } +} + +// NewResetProjectInstancePasswdParamsWithHTTPClient creates a new ResetProjectInstancePasswdParams object +// with the ability to set a custom HTTPClient for a request. +func NewResetProjectInstancePasswdParamsWithHTTPClient(client *http.Client) *ResetProjectInstancePasswdParams { + return &ResetProjectInstancePasswdParams{ + HTTPClient: client, + } +} + +/* ResetProjectInstancePasswdParams contains all the parameters to send to the API endpoint + for the reset project instance passwd operation. + + Typically these are written to a http.Request. +*/ +type ResetProjectInstancePasswdParams struct { + + // Body. + Body *models.ResetInstancePasswdRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the reset project instance passwd params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetProjectInstancePasswdParams) WithDefaults() *ResetProjectInstancePasswdParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the reset project instance passwd params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetProjectInstancePasswdParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithTimeout(timeout time.Duration) *ResetProjectInstancePasswdParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithContext(ctx context.Context) *ResetProjectInstancePasswdParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithHTTPClient(client *http.Client) *ResetProjectInstancePasswdParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithBody(body *models.ResetInstancePasswdRequest) *ResetProjectInstancePasswdParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetBody(body *models.ResetInstancePasswdRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithAuthorization(authorization string) *ResetProjectInstancePasswdParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithBmpLanguage(bmpLanguage *string) *ResetProjectInstancePasswdParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithBmpUserID(bmpUserID *string) *ResetProjectInstancePasswdParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithInstanceID(instanceID string) *ResetProjectInstancePasswdParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithTraceID(traceID string) *ResetProjectInstancePasswdParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ResetProjectInstancePasswdParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instance_passwd_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instance_passwd_responses.go new file mode 100644 index 0000000..e998a94 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instance_passwd_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ResetProjectInstancePasswdReader is a Reader for the ResetProjectInstancePasswd structure. +type ResetProjectInstancePasswdReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ResetProjectInstancePasswdReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewResetProjectInstancePasswdOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewResetProjectInstancePasswdDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewResetProjectInstancePasswdOK creates a ResetProjectInstancePasswdOK with default headers values +func NewResetProjectInstancePasswdOK() *ResetProjectInstancePasswdOK { + return &ResetProjectInstancePasswdOK{} +} + +/* ResetProjectInstancePasswdOK describes a response with status code 200, with default header values. + +A ResetProjectInstancePasswdResult is an response struct that is used to describe reset instance password. +*/ +type ResetProjectInstancePasswdOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetProjectInstancePasswdOKBody +} + +// IsSuccess returns true when this reset project instance passwd o k response has a 2xx status code +func (o *ResetProjectInstancePasswdOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this reset project instance passwd o k response has a 3xx status code +func (o *ResetProjectInstancePasswdOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this reset project instance passwd o k response has a 4xx status code +func (o *ResetProjectInstancePasswdOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this reset project instance passwd o k response has a 5xx status code +func (o *ResetProjectInstancePasswdOK) IsServerError() bool { + return false +} + +// IsCode returns true when this reset project instance passwd o k response a status code equal to that given +func (o *ResetProjectInstancePasswdOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ResetProjectInstancePasswdOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetpasswd][%d] resetProjectInstancePasswdOK %+v", 200, o.Payload) +} + +func (o *ResetProjectInstancePasswdOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetpasswd][%d] resetProjectInstancePasswdOK %+v", 200, o.Payload) +} + +func (o *ResetProjectInstancePasswdOK) GetPayload() *ResetProjectInstancePasswdOKBody { + return o.Payload +} + +func (o *ResetProjectInstancePasswdOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetProjectInstancePasswdOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewResetProjectInstancePasswdDefault creates a ResetProjectInstancePasswdDefault with default headers values +func NewResetProjectInstancePasswdDefault(code int) *ResetProjectInstancePasswdDefault { + return &ResetProjectInstancePasswdDefault{ + _statusCode: code, + } +} + +/* ResetProjectInstancePasswdDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ResetProjectInstancePasswdDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetProjectInstancePasswdDefaultBody +} + +// Code gets the status code for the reset project instance passwd default response +func (o *ResetProjectInstancePasswdDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this reset project instance passwd default response has a 2xx status code +func (o *ResetProjectInstancePasswdDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this reset project instance passwd default response has a 3xx status code +func (o *ResetProjectInstancePasswdDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this reset project instance passwd default response has a 4xx status code +func (o *ResetProjectInstancePasswdDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this reset project instance passwd default response has a 5xx status code +func (o *ResetProjectInstancePasswdDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this reset project instance passwd default response a status code equal to that given +func (o *ResetProjectInstancePasswdDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ResetProjectInstancePasswdDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetpasswd][%d] resetProjectInstancePasswd default %+v", o._statusCode, o.Payload) +} + +func (o *ResetProjectInstancePasswdDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetpasswd][%d] resetProjectInstancePasswd default %+v", o._statusCode, o.Payload) +} + +func (o *ResetProjectInstancePasswdDefault) GetPayload() *ResetProjectInstancePasswdDefaultBody { + return o.Payload +} + +func (o *ResetProjectInstancePasswdDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetProjectInstancePasswdDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ResetProjectInstancePasswdDefaultBody reset project instance passwd default body +swagger:model ResetProjectInstancePasswdDefaultBody +*/ +type ResetProjectInstancePasswdDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this reset project instance passwd default body +func (o *ResetProjectInstancePasswdDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancePasswdDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("resetProjectInstancePasswd default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ResetProjectInstancePasswdDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("resetProjectInstancePasswd default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancePasswd default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancePasswd default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset project instance passwd default body based on the context it is used +func (o *ResetProjectInstancePasswdDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancePasswdDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancePasswd default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancePasswd default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetProjectInstancePasswdDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetProjectInstancePasswdDefaultBody) UnmarshalBinary(b []byte) error { + var res ResetProjectInstancePasswdDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ResetProjectInstancePasswdOKBody reset project instance passwd o k body +swagger:model ResetProjectInstancePasswdOKBody +*/ +type ResetProjectInstancePasswdOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this reset project instance passwd o k body +func (o *ResetProjectInstancePasswdOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancePasswdOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancePasswdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancePasswdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset project instance passwd o k body based on the context it is used +func (o *ResetProjectInstancePasswdOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancePasswdOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancePasswdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancePasswdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetProjectInstancePasswdOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetProjectInstancePasswdOKBody) UnmarshalBinary(b []byte) error { + var res ResetProjectInstancePasswdOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instances_passwd_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instances_passwd_parameters.go new file mode 100644 index 0000000..7de3615 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instances_passwd_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewResetProjectInstancesPasswdParams creates a new ResetProjectInstancesPasswdParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewResetProjectInstancesPasswdParams() *ResetProjectInstancesPasswdParams { + return &ResetProjectInstancesPasswdParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewResetProjectInstancesPasswdParamsWithTimeout creates a new ResetProjectInstancesPasswdParams object +// with the ability to set a timeout on a request. +func NewResetProjectInstancesPasswdParamsWithTimeout(timeout time.Duration) *ResetProjectInstancesPasswdParams { + return &ResetProjectInstancesPasswdParams{ + timeout: timeout, + } +} + +// NewResetProjectInstancesPasswdParamsWithContext creates a new ResetProjectInstancesPasswdParams object +// with the ability to set a context for a request. +func NewResetProjectInstancesPasswdParamsWithContext(ctx context.Context) *ResetProjectInstancesPasswdParams { + return &ResetProjectInstancesPasswdParams{ + Context: ctx, + } +} + +// NewResetProjectInstancesPasswdParamsWithHTTPClient creates a new ResetProjectInstancesPasswdParams object +// with the ability to set a custom HTTPClient for a request. +func NewResetProjectInstancesPasswdParamsWithHTTPClient(client *http.Client) *ResetProjectInstancesPasswdParams { + return &ResetProjectInstancesPasswdParams{ + HTTPClient: client, + } +} + +/* ResetProjectInstancesPasswdParams contains all the parameters to send to the API endpoint + for the reset project instances passwd operation. + + Typically these are written to a http.Request. +*/ +type ResetProjectInstancesPasswdParams struct { + + // Body. + Body *models.ResetInstancesPasswdRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the reset project instances passwd params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetProjectInstancesPasswdParams) WithDefaults() *ResetProjectInstancesPasswdParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the reset project instances passwd params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetProjectInstancesPasswdParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithTimeout(timeout time.Duration) *ResetProjectInstancesPasswdParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithContext(ctx context.Context) *ResetProjectInstancesPasswdParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithHTTPClient(client *http.Client) *ResetProjectInstancesPasswdParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithBody(body *models.ResetInstancesPasswdRequest) *ResetProjectInstancesPasswdParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetBody(body *models.ResetInstancesPasswdRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithAuthorization(authorization string) *ResetProjectInstancesPasswdParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithBmpLanguage(bmpLanguage *string) *ResetProjectInstancesPasswdParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithBmpUserID(bmpUserID *string) *ResetProjectInstancesPasswdParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithTraceID(traceID string) *ResetProjectInstancesPasswdParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ResetProjectInstancesPasswdParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instances_passwd_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instances_passwd_responses.go new file mode 100644 index 0000000..dedb483 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instances_passwd_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ResetProjectInstancesPasswdReader is a Reader for the ResetProjectInstancesPasswd structure. +type ResetProjectInstancesPasswdReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ResetProjectInstancesPasswdReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewResetProjectInstancesPasswdOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewResetProjectInstancesPasswdDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewResetProjectInstancesPasswdOK creates a ResetProjectInstancesPasswdOK with default headers values +func NewResetProjectInstancesPasswdOK() *ResetProjectInstancesPasswdOK { + return &ResetProjectInstancesPasswdOK{} +} + +/* ResetProjectInstancesPasswdOK describes a response with status code 200, with default header values. + +A ResetProjectInstancesPasswdResult is an response struct that is used to describe reset instance password. +*/ +type ResetProjectInstancesPasswdOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetProjectInstancesPasswdOKBody +} + +// IsSuccess returns true when this reset project instances passwd o k response has a 2xx status code +func (o *ResetProjectInstancesPasswdOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this reset project instances passwd o k response has a 3xx status code +func (o *ResetProjectInstancesPasswdOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this reset project instances passwd o k response has a 4xx status code +func (o *ResetProjectInstancesPasswdOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this reset project instances passwd o k response has a 5xx status code +func (o *ResetProjectInstancesPasswdOK) IsServerError() bool { + return false +} + +// IsCode returns true when this reset project instances passwd o k response a status code equal to that given +func (o *ResetProjectInstancesPasswdOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ResetProjectInstancesPasswdOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:resetPasswd][%d] resetProjectInstancesPasswdOK %+v", 200, o.Payload) +} + +func (o *ResetProjectInstancesPasswdOK) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:resetPasswd][%d] resetProjectInstancesPasswdOK %+v", 200, o.Payload) +} + +func (o *ResetProjectInstancesPasswdOK) GetPayload() *ResetProjectInstancesPasswdOKBody { + return o.Payload +} + +func (o *ResetProjectInstancesPasswdOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetProjectInstancesPasswdOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewResetProjectInstancesPasswdDefault creates a ResetProjectInstancesPasswdDefault with default headers values +func NewResetProjectInstancesPasswdDefault(code int) *ResetProjectInstancesPasswdDefault { + return &ResetProjectInstancesPasswdDefault{ + _statusCode: code, + } +} + +/* ResetProjectInstancesPasswdDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ResetProjectInstancesPasswdDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetProjectInstancesPasswdDefaultBody +} + +// Code gets the status code for the reset project instances passwd default response +func (o *ResetProjectInstancesPasswdDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this reset project instances passwd default response has a 2xx status code +func (o *ResetProjectInstancesPasswdDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this reset project instances passwd default response has a 3xx status code +func (o *ResetProjectInstancesPasswdDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this reset project instances passwd default response has a 4xx status code +func (o *ResetProjectInstancesPasswdDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this reset project instances passwd default response has a 5xx status code +func (o *ResetProjectInstancesPasswdDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this reset project instances passwd default response a status code equal to that given +func (o *ResetProjectInstancesPasswdDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ResetProjectInstancesPasswdDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:resetPasswd][%d] resetProjectInstancesPasswd default %+v", o._statusCode, o.Payload) +} + +func (o *ResetProjectInstancesPasswdDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:resetPasswd][%d] resetProjectInstancesPasswd default %+v", o._statusCode, o.Payload) +} + +func (o *ResetProjectInstancesPasswdDefault) GetPayload() *ResetProjectInstancesPasswdDefaultBody { + return o.Payload +} + +func (o *ResetProjectInstancesPasswdDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetProjectInstancesPasswdDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ResetProjectInstancesPasswdDefaultBody reset project instances passwd default body +swagger:model ResetProjectInstancesPasswdDefaultBody +*/ +type ResetProjectInstancesPasswdDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this reset project instances passwd default body +func (o *ResetProjectInstancesPasswdDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancesPasswdDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("resetProjectInstancesPasswd default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ResetProjectInstancesPasswdDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("resetProjectInstancesPasswd default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancesPasswd default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancesPasswd default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset project instances passwd default body based on the context it is used +func (o *ResetProjectInstancesPasswdDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancesPasswdDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancesPasswd default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancesPasswd default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetProjectInstancesPasswdDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetProjectInstancesPasswdDefaultBody) UnmarshalBinary(b []byte) error { + var res ResetProjectInstancesPasswdDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ResetProjectInstancesPasswdOKBody reset project instances passwd o k body +swagger:model ResetProjectInstancesPasswdOKBody +*/ +type ResetProjectInstancesPasswdOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this reset project instances passwd o k body +func (o *ResetProjectInstancesPasswdOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancesPasswdOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancesPasswdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancesPasswdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset project instances passwd o k body based on the context it is used +func (o *ResetProjectInstancesPasswdOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancesPasswdOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancesPasswdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancesPasswdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetProjectInstancesPasswdOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetProjectInstancesPasswdOKBody) UnmarshalBinary(b []byte) error { + var res ResetProjectInstancesPasswdOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/restart_instances_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/restart_instances_parameters.go new file mode 100644 index 0000000..d308c6a --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/restart_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewRestartInstancesParams creates a new RestartInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewRestartInstancesParams() *RestartInstancesParams { + return &RestartInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewRestartInstancesParamsWithTimeout creates a new RestartInstancesParams object +// with the ability to set a timeout on a request. +func NewRestartInstancesParamsWithTimeout(timeout time.Duration) *RestartInstancesParams { + return &RestartInstancesParams{ + timeout: timeout, + } +} + +// NewRestartInstancesParamsWithContext creates a new RestartInstancesParams object +// with the ability to set a context for a request. +func NewRestartInstancesParamsWithContext(ctx context.Context) *RestartInstancesParams { + return &RestartInstancesParams{ + Context: ctx, + } +} + +// NewRestartInstancesParamsWithHTTPClient creates a new RestartInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewRestartInstancesParamsWithHTTPClient(client *http.Client) *RestartInstancesParams { + return &RestartInstancesParams{ + HTTPClient: client, + } +} + +/* RestartInstancesParams contains all the parameters to send to the API endpoint + for the restart instances operation. + + Typically these are written to a http.Request. +*/ +type RestartInstancesParams struct { + + // Body. + Body *models.RestartInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the restart instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RestartInstancesParams) WithDefaults() *RestartInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the restart instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RestartInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the restart instances params +func (o *RestartInstancesParams) WithTimeout(timeout time.Duration) *RestartInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the restart instances params +func (o *RestartInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the restart instances params +func (o *RestartInstancesParams) WithContext(ctx context.Context) *RestartInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the restart instances params +func (o *RestartInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the restart instances params +func (o *RestartInstancesParams) WithHTTPClient(client *http.Client) *RestartInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the restart instances params +func (o *RestartInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the restart instances params +func (o *RestartInstancesParams) WithBody(body *models.RestartInstancesRequest) *RestartInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the restart instances params +func (o *RestartInstancesParams) SetBody(body *models.RestartInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the restart instances params +func (o *RestartInstancesParams) WithAuthorization(authorization string) *RestartInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the restart instances params +func (o *RestartInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the restart instances params +func (o *RestartInstancesParams) WithBmpLanguage(bmpLanguage *string) *RestartInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the restart instances params +func (o *RestartInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the restart instances params +func (o *RestartInstancesParams) WithBmpUserID(bmpUserID *string) *RestartInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the restart instances params +func (o *RestartInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the restart instances params +func (o *RestartInstancesParams) WithTraceID(traceID string) *RestartInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the restart instances params +func (o *RestartInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *RestartInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/restart_instances_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/restart_instances_responses.go new file mode 100644 index 0000000..674d6a5 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/restart_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// RestartInstancesReader is a Reader for the RestartInstances structure. +type RestartInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *RestartInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewRestartInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewRestartInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewRestartInstancesOK creates a RestartInstancesOK with default headers values +func NewRestartInstancesOK() *RestartInstancesOK { + return &RestartInstancesOK{} +} + +/* RestartInstancesOK describes a response with status code 200, with default header values. + +A RestartInstancesResult is an response struct +*/ +type RestartInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *RestartInstancesOKBody +} + +// IsSuccess returns true when this restart instances o k response has a 2xx status code +func (o *RestartInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this restart instances o k response has a 3xx status code +func (o *RestartInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this restart instances o k response has a 4xx status code +func (o *RestartInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this restart instances o k response has a 5xx status code +func (o *RestartInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this restart instances o k response a status code equal to that given +func (o *RestartInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *RestartInstancesOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:restartInstances][%d] restartInstancesOK %+v", 200, o.Payload) +} + +func (o *RestartInstancesOK) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:restartInstances][%d] restartInstancesOK %+v", 200, o.Payload) +} + +func (o *RestartInstancesOK) GetPayload() *RestartInstancesOKBody { + return o.Payload +} + +func (o *RestartInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RestartInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewRestartInstancesDefault creates a RestartInstancesDefault with default headers values +func NewRestartInstancesDefault(code int) *RestartInstancesDefault { + return &RestartInstancesDefault{ + _statusCode: code, + } +} + +/* RestartInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type RestartInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *RestartInstancesDefaultBody +} + +// Code gets the status code for the restart instances default response +func (o *RestartInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this restart instances default response has a 2xx status code +func (o *RestartInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this restart instances default response has a 3xx status code +func (o *RestartInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this restart instances default response has a 4xx status code +func (o *RestartInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this restart instances default response has a 5xx status code +func (o *RestartInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this restart instances default response a status code equal to that given +func (o *RestartInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *RestartInstancesDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:restartInstances][%d] restartInstances default %+v", o._statusCode, o.Payload) +} + +func (o *RestartInstancesDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:restartInstances][%d] restartInstances default %+v", o._statusCode, o.Payload) +} + +func (o *RestartInstancesDefault) GetPayload() *RestartInstancesDefaultBody { + return o.Payload +} + +func (o *RestartInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RestartInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*RestartInstancesDefaultBody restart instances default body +swagger:model RestartInstancesDefaultBody +*/ +type RestartInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this restart instances default body +func (o *RestartInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("restartInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *RestartInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("restartInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this restart instances default body based on the context it is used +func (o *RestartInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RestartInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RestartInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res RestartInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*RestartInstancesOKBody restart instances o k body +swagger:model RestartInstancesOKBody +*/ +type RestartInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this restart instances o k body +func (o *RestartInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this restart instances o k body based on the context it is used +func (o *RestartInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RestartInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RestartInstancesOKBody) UnmarshalBinary(b []byte) error { + var res RestartInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/restart_project_instance_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/restart_project_instance_parameters.go new file mode 100644 index 0000000..d1b78b2 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/restart_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewRestartProjectInstanceParams creates a new RestartProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewRestartProjectInstanceParams() *RestartProjectInstanceParams { + return &RestartProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewRestartProjectInstanceParamsWithTimeout creates a new RestartProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewRestartProjectInstanceParamsWithTimeout(timeout time.Duration) *RestartProjectInstanceParams { + return &RestartProjectInstanceParams{ + timeout: timeout, + } +} + +// NewRestartProjectInstanceParamsWithContext creates a new RestartProjectInstanceParams object +// with the ability to set a context for a request. +func NewRestartProjectInstanceParamsWithContext(ctx context.Context) *RestartProjectInstanceParams { + return &RestartProjectInstanceParams{ + Context: ctx, + } +} + +// NewRestartProjectInstanceParamsWithHTTPClient creates a new RestartProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewRestartProjectInstanceParamsWithHTTPClient(client *http.Client) *RestartProjectInstanceParams { + return &RestartProjectInstanceParams{ + HTTPClient: client, + } +} + +/* RestartProjectInstanceParams contains all the parameters to send to the API endpoint + for the restart project instance operation. + + Typically these are written to a http.Request. +*/ +type RestartProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the restart project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RestartProjectInstanceParams) WithDefaults() *RestartProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the restart project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RestartProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the restart project instance params +func (o *RestartProjectInstanceParams) WithTimeout(timeout time.Duration) *RestartProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the restart project instance params +func (o *RestartProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the restart project instance params +func (o *RestartProjectInstanceParams) WithContext(ctx context.Context) *RestartProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the restart project instance params +func (o *RestartProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the restart project instance params +func (o *RestartProjectInstanceParams) WithHTTPClient(client *http.Client) *RestartProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the restart project instance params +func (o *RestartProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the restart project instance params +func (o *RestartProjectInstanceParams) WithAuthorization(authorization string) *RestartProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the restart project instance params +func (o *RestartProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the restart project instance params +func (o *RestartProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *RestartProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the restart project instance params +func (o *RestartProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the restart project instance params +func (o *RestartProjectInstanceParams) WithBmpUserID(bmpUserID *string) *RestartProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the restart project instance params +func (o *RestartProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the restart project instance params +func (o *RestartProjectInstanceParams) WithInstanceID(instanceID string) *RestartProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the restart project instance params +func (o *RestartProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the restart project instance params +func (o *RestartProjectInstanceParams) WithTraceID(traceID string) *RestartProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the restart project instance params +func (o *RestartProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *RestartProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/restart_project_instance_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/restart_project_instance_responses.go new file mode 100644 index 0000000..2a76a9d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/restart_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// RestartProjectInstanceReader is a Reader for the RestartProjectInstance structure. +type RestartProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *RestartProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewRestartProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewRestartProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewRestartProjectInstanceOK creates a RestartProjectInstanceOK with default headers values +func NewRestartProjectInstanceOK() *RestartProjectInstanceOK { + return &RestartProjectInstanceOK{} +} + +/* RestartProjectInstanceOK describes a response with status code 200, with default header values. + +A RestartProjectInstanceResult is an response struct that is used to describe restart instance result. +*/ +type RestartProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *RestartProjectInstanceOKBody +} + +// IsSuccess returns true when this restart project instance o k response has a 2xx status code +func (o *RestartProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this restart project instance o k response has a 3xx status code +func (o *RestartProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this restart project instance o k response has a 4xx status code +func (o *RestartProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this restart project instance o k response has a 5xx status code +func (o *RestartProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this restart project instance o k response a status code equal to that given +func (o *RestartProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *RestartProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/restart][%d] restartProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *RestartProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/restart][%d] restartProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *RestartProjectInstanceOK) GetPayload() *RestartProjectInstanceOKBody { + return o.Payload +} + +func (o *RestartProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RestartProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewRestartProjectInstanceDefault creates a RestartProjectInstanceDefault with default headers values +func NewRestartProjectInstanceDefault(code int) *RestartProjectInstanceDefault { + return &RestartProjectInstanceDefault{ + _statusCode: code, + } +} + +/* RestartProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type RestartProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *RestartProjectInstanceDefaultBody +} + +// Code gets the status code for the restart project instance default response +func (o *RestartProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this restart project instance default response has a 2xx status code +func (o *RestartProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this restart project instance default response has a 3xx status code +func (o *RestartProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this restart project instance default response has a 4xx status code +func (o *RestartProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this restart project instance default response has a 5xx status code +func (o *RestartProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this restart project instance default response a status code equal to that given +func (o *RestartProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *RestartProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/restart][%d] restartProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *RestartProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/restart][%d] restartProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *RestartProjectInstanceDefault) GetPayload() *RestartProjectInstanceDefaultBody { + return o.Payload +} + +func (o *RestartProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RestartProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*RestartProjectInstanceDefaultBody restart project instance default body +swagger:model RestartProjectInstanceDefaultBody +*/ +type RestartProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this restart project instance default body +func (o *RestartProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("restartProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *RestartProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("restartProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this restart project instance default body based on the context it is used +func (o *RestartProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RestartProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RestartProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res RestartProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*RestartProjectInstanceOKBody restart project instance o k body +swagger:model RestartProjectInstanceOKBody +*/ +type RestartProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this restart project instance o k body +func (o *RestartProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this restart project instance o k body based on the context it is used +func (o *RestartProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RestartProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RestartProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res RestartProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/start_instances_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/start_instances_parameters.go new file mode 100644 index 0000000..a6ff851 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/start_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewStartInstancesParams creates a new StartInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewStartInstancesParams() *StartInstancesParams { + return &StartInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewStartInstancesParamsWithTimeout creates a new StartInstancesParams object +// with the ability to set a timeout on a request. +func NewStartInstancesParamsWithTimeout(timeout time.Duration) *StartInstancesParams { + return &StartInstancesParams{ + timeout: timeout, + } +} + +// NewStartInstancesParamsWithContext creates a new StartInstancesParams object +// with the ability to set a context for a request. +func NewStartInstancesParamsWithContext(ctx context.Context) *StartInstancesParams { + return &StartInstancesParams{ + Context: ctx, + } +} + +// NewStartInstancesParamsWithHTTPClient creates a new StartInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewStartInstancesParamsWithHTTPClient(client *http.Client) *StartInstancesParams { + return &StartInstancesParams{ + HTTPClient: client, + } +} + +/* StartInstancesParams contains all the parameters to send to the API endpoint + for the start instances operation. + + Typically these are written to a http.Request. +*/ +type StartInstancesParams struct { + + // Body. + Body *models.StartInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the start instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StartInstancesParams) WithDefaults() *StartInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the start instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StartInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the start instances params +func (o *StartInstancesParams) WithTimeout(timeout time.Duration) *StartInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the start instances params +func (o *StartInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the start instances params +func (o *StartInstancesParams) WithContext(ctx context.Context) *StartInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the start instances params +func (o *StartInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the start instances params +func (o *StartInstancesParams) WithHTTPClient(client *http.Client) *StartInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the start instances params +func (o *StartInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the start instances params +func (o *StartInstancesParams) WithBody(body *models.StartInstancesRequest) *StartInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the start instances params +func (o *StartInstancesParams) SetBody(body *models.StartInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the start instances params +func (o *StartInstancesParams) WithAuthorization(authorization string) *StartInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the start instances params +func (o *StartInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the start instances params +func (o *StartInstancesParams) WithBmpLanguage(bmpLanguage *string) *StartInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the start instances params +func (o *StartInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the start instances params +func (o *StartInstancesParams) WithBmpUserID(bmpUserID *string) *StartInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the start instances params +func (o *StartInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the start instances params +func (o *StartInstancesParams) WithTraceID(traceID string) *StartInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the start instances params +func (o *StartInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *StartInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/start_instances_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/start_instances_responses.go new file mode 100644 index 0000000..643764c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/start_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// StartInstancesReader is a Reader for the StartInstances structure. +type StartInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *StartInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewStartInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewStartInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewStartInstancesOK creates a StartInstancesOK with default headers values +func NewStartInstancesOK() *StartInstancesOK { + return &StartInstancesOK{} +} + +/* StartInstancesOK describes a response with status code 200, with default header values. + +A StartInstancesResult is an response struct +*/ +type StartInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *StartInstancesOKBody +} + +// IsSuccess returns true when this start instances o k response has a 2xx status code +func (o *StartInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this start instances o k response has a 3xx status code +func (o *StartInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this start instances o k response has a 4xx status code +func (o *StartInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this start instances o k response has a 5xx status code +func (o *StartInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this start instances o k response a status code equal to that given +func (o *StartInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *StartInstancesOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:startInstances][%d] startInstancesOK %+v", 200, o.Payload) +} + +func (o *StartInstancesOK) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:startInstances][%d] startInstancesOK %+v", 200, o.Payload) +} + +func (o *StartInstancesOK) GetPayload() *StartInstancesOKBody { + return o.Payload +} + +func (o *StartInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StartInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewStartInstancesDefault creates a StartInstancesDefault with default headers values +func NewStartInstancesDefault(code int) *StartInstancesDefault { + return &StartInstancesDefault{ + _statusCode: code, + } +} + +/* StartInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type StartInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *StartInstancesDefaultBody +} + +// Code gets the status code for the start instances default response +func (o *StartInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this start instances default response has a 2xx status code +func (o *StartInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this start instances default response has a 3xx status code +func (o *StartInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this start instances default response has a 4xx status code +func (o *StartInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this start instances default response has a 5xx status code +func (o *StartInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this start instances default response a status code equal to that given +func (o *StartInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *StartInstancesDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:startInstances][%d] startInstances default %+v", o._statusCode, o.Payload) +} + +func (o *StartInstancesDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:startInstances][%d] startInstances default %+v", o._statusCode, o.Payload) +} + +func (o *StartInstancesDefault) GetPayload() *StartInstancesDefaultBody { + return o.Payload +} + +func (o *StartInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StartInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*StartInstancesDefaultBody start instances default body +swagger:model StartInstancesDefaultBody +*/ +type StartInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this start instances default body +func (o *StartInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("startInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *StartInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("startInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this start instances default body based on the context it is used +func (o *StartInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StartInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StartInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res StartInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*StartInstancesOKBody start instances o k body +swagger:model StartInstancesOKBody +*/ +type StartInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this start instances o k body +func (o *StartInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this start instances o k body based on the context it is used +func (o *StartInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StartInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StartInstancesOKBody) UnmarshalBinary(b []byte) error { + var res StartInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/start_project_instance_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/start_project_instance_parameters.go new file mode 100644 index 0000000..9014aa5 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/start_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewStartProjectInstanceParams creates a new StartProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewStartProjectInstanceParams() *StartProjectInstanceParams { + return &StartProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewStartProjectInstanceParamsWithTimeout creates a new StartProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewStartProjectInstanceParamsWithTimeout(timeout time.Duration) *StartProjectInstanceParams { + return &StartProjectInstanceParams{ + timeout: timeout, + } +} + +// NewStartProjectInstanceParamsWithContext creates a new StartProjectInstanceParams object +// with the ability to set a context for a request. +func NewStartProjectInstanceParamsWithContext(ctx context.Context) *StartProjectInstanceParams { + return &StartProjectInstanceParams{ + Context: ctx, + } +} + +// NewStartProjectInstanceParamsWithHTTPClient creates a new StartProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewStartProjectInstanceParamsWithHTTPClient(client *http.Client) *StartProjectInstanceParams { + return &StartProjectInstanceParams{ + HTTPClient: client, + } +} + +/* StartProjectInstanceParams contains all the parameters to send to the API endpoint + for the start project instance operation. + + Typically these are written to a http.Request. +*/ +type StartProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the start project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StartProjectInstanceParams) WithDefaults() *StartProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the start project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StartProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the start project instance params +func (o *StartProjectInstanceParams) WithTimeout(timeout time.Duration) *StartProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the start project instance params +func (o *StartProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the start project instance params +func (o *StartProjectInstanceParams) WithContext(ctx context.Context) *StartProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the start project instance params +func (o *StartProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the start project instance params +func (o *StartProjectInstanceParams) WithHTTPClient(client *http.Client) *StartProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the start project instance params +func (o *StartProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the start project instance params +func (o *StartProjectInstanceParams) WithAuthorization(authorization string) *StartProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the start project instance params +func (o *StartProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the start project instance params +func (o *StartProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *StartProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the start project instance params +func (o *StartProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the start project instance params +func (o *StartProjectInstanceParams) WithBmpUserID(bmpUserID *string) *StartProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the start project instance params +func (o *StartProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the start project instance params +func (o *StartProjectInstanceParams) WithInstanceID(instanceID string) *StartProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the start project instance params +func (o *StartProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the start project instance params +func (o *StartProjectInstanceParams) WithTraceID(traceID string) *StartProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the start project instance params +func (o *StartProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *StartProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/start_project_instance_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/start_project_instance_responses.go new file mode 100644 index 0000000..5d6f102 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/start_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// StartProjectInstanceReader is a Reader for the StartProjectInstance structure. +type StartProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *StartProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewStartProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewStartProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewStartProjectInstanceOK creates a StartProjectInstanceOK with default headers values +func NewStartProjectInstanceOK() *StartProjectInstanceOK { + return &StartProjectInstanceOK{} +} + +/* StartProjectInstanceOK describes a response with status code 200, with default header values. + +A StartProjectInstanceResult is an response struct that is used to describe start instance result. +*/ +type StartProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *StartProjectInstanceOKBody +} + +// IsSuccess returns true when this start project instance o k response has a 2xx status code +func (o *StartProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this start project instance o k response has a 3xx status code +func (o *StartProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this start project instance o k response has a 4xx status code +func (o *StartProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this start project instance o k response has a 5xx status code +func (o *StartProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this start project instance o k response a status code equal to that given +func (o *StartProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *StartProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/start][%d] startProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *StartProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/start][%d] startProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *StartProjectInstanceOK) GetPayload() *StartProjectInstanceOKBody { + return o.Payload +} + +func (o *StartProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StartProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewStartProjectInstanceDefault creates a StartProjectInstanceDefault with default headers values +func NewStartProjectInstanceDefault(code int) *StartProjectInstanceDefault { + return &StartProjectInstanceDefault{ + _statusCode: code, + } +} + +/* StartProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type StartProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *StartProjectInstanceDefaultBody +} + +// Code gets the status code for the start project instance default response +func (o *StartProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this start project instance default response has a 2xx status code +func (o *StartProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this start project instance default response has a 3xx status code +func (o *StartProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this start project instance default response has a 4xx status code +func (o *StartProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this start project instance default response has a 5xx status code +func (o *StartProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this start project instance default response a status code equal to that given +func (o *StartProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *StartProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/start][%d] startProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *StartProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/start][%d] startProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *StartProjectInstanceDefault) GetPayload() *StartProjectInstanceDefaultBody { + return o.Payload +} + +func (o *StartProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StartProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*StartProjectInstanceDefaultBody start project instance default body +swagger:model StartProjectInstanceDefaultBody +*/ +type StartProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this start project instance default body +func (o *StartProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("startProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *StartProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("startProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this start project instance default body based on the context it is used +func (o *StartProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StartProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StartProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res StartProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*StartProjectInstanceOKBody start project instance o k body +swagger:model StartProjectInstanceOKBody +*/ +type StartProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this start project instance o k body +func (o *StartProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this start project instance o k body based on the context it is used +func (o *StartProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StartProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StartProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res StartProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/stop_instances_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/stop_instances_parameters.go new file mode 100644 index 0000000..c76e3d5 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/stop_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewStopInstancesParams creates a new StopInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewStopInstancesParams() *StopInstancesParams { + return &StopInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewStopInstancesParamsWithTimeout creates a new StopInstancesParams object +// with the ability to set a timeout on a request. +func NewStopInstancesParamsWithTimeout(timeout time.Duration) *StopInstancesParams { + return &StopInstancesParams{ + timeout: timeout, + } +} + +// NewStopInstancesParamsWithContext creates a new StopInstancesParams object +// with the ability to set a context for a request. +func NewStopInstancesParamsWithContext(ctx context.Context) *StopInstancesParams { + return &StopInstancesParams{ + Context: ctx, + } +} + +// NewStopInstancesParamsWithHTTPClient creates a new StopInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewStopInstancesParamsWithHTTPClient(client *http.Client) *StopInstancesParams { + return &StopInstancesParams{ + HTTPClient: client, + } +} + +/* StopInstancesParams contains all the parameters to send to the API endpoint + for the stop instances operation. + + Typically these are written to a http.Request. +*/ +type StopInstancesParams struct { + + // Body. + Body *models.StopInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the stop instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StopInstancesParams) WithDefaults() *StopInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the stop instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StopInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the stop instances params +func (o *StopInstancesParams) WithTimeout(timeout time.Duration) *StopInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the stop instances params +func (o *StopInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the stop instances params +func (o *StopInstancesParams) WithContext(ctx context.Context) *StopInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the stop instances params +func (o *StopInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the stop instances params +func (o *StopInstancesParams) WithHTTPClient(client *http.Client) *StopInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the stop instances params +func (o *StopInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the stop instances params +func (o *StopInstancesParams) WithBody(body *models.StopInstancesRequest) *StopInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the stop instances params +func (o *StopInstancesParams) SetBody(body *models.StopInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the stop instances params +func (o *StopInstancesParams) WithAuthorization(authorization string) *StopInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the stop instances params +func (o *StopInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the stop instances params +func (o *StopInstancesParams) WithBmpLanguage(bmpLanguage *string) *StopInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the stop instances params +func (o *StopInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the stop instances params +func (o *StopInstancesParams) WithBmpUserID(bmpUserID *string) *StopInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the stop instances params +func (o *StopInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the stop instances params +func (o *StopInstancesParams) WithTraceID(traceID string) *StopInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the stop instances params +func (o *StopInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *StopInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/stop_instances_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/stop_instances_responses.go new file mode 100644 index 0000000..d9bee91 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/stop_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// StopInstancesReader is a Reader for the StopInstances structure. +type StopInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *StopInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewStopInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewStopInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewStopInstancesOK creates a StopInstancesOK with default headers values +func NewStopInstancesOK() *StopInstancesOK { + return &StopInstancesOK{} +} + +/* StopInstancesOK describes a response with status code 200, with default header values. + +A StopInstancesResult is an response struct +*/ +type StopInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *StopInstancesOKBody +} + +// IsSuccess returns true when this stop instances o k response has a 2xx status code +func (o *StopInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this stop instances o k response has a 3xx status code +func (o *StopInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this stop instances o k response has a 4xx status code +func (o *StopInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this stop instances o k response has a 5xx status code +func (o *StopInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this stop instances o k response a status code equal to that given +func (o *StopInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *StopInstancesOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:stopInstances][%d] stopInstancesOK %+v", 200, o.Payload) +} + +func (o *StopInstancesOK) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:stopInstances][%d] stopInstancesOK %+v", 200, o.Payload) +} + +func (o *StopInstancesOK) GetPayload() *StopInstancesOKBody { + return o.Payload +} + +func (o *StopInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StopInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewStopInstancesDefault creates a StopInstancesDefault with default headers values +func NewStopInstancesDefault(code int) *StopInstancesDefault { + return &StopInstancesDefault{ + _statusCode: code, + } +} + +/* StopInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type StopInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *StopInstancesDefaultBody +} + +// Code gets the status code for the stop instances default response +func (o *StopInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this stop instances default response has a 2xx status code +func (o *StopInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this stop instances default response has a 3xx status code +func (o *StopInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this stop instances default response has a 4xx status code +func (o *StopInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this stop instances default response has a 5xx status code +func (o *StopInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this stop instances default response a status code equal to that given +func (o *StopInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *StopInstancesDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:stopInstances][%d] stopInstances default %+v", o._statusCode, o.Payload) +} + +func (o *StopInstancesDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:stopInstances][%d] stopInstances default %+v", o._statusCode, o.Payload) +} + +func (o *StopInstancesDefault) GetPayload() *StopInstancesDefaultBody { + return o.Payload +} + +func (o *StopInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StopInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*StopInstancesDefaultBody stop instances default body +swagger:model StopInstancesDefaultBody +*/ +type StopInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this stop instances default body +func (o *StopInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("stopInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *StopInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("stopInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this stop instances default body based on the context it is used +func (o *StopInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StopInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StopInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res StopInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*StopInstancesOKBody stop instances o k body +swagger:model StopInstancesOKBody +*/ +type StopInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this stop instances o k body +func (o *StopInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this stop instances o k body based on the context it is used +func (o *StopInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StopInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StopInstancesOKBody) UnmarshalBinary(b []byte) error { + var res StopInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/stop_project_instance_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/stop_project_instance_parameters.go new file mode 100644 index 0000000..f9a48c8 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/stop_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewStopProjectInstanceParams creates a new StopProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewStopProjectInstanceParams() *StopProjectInstanceParams { + return &StopProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewStopProjectInstanceParamsWithTimeout creates a new StopProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewStopProjectInstanceParamsWithTimeout(timeout time.Duration) *StopProjectInstanceParams { + return &StopProjectInstanceParams{ + timeout: timeout, + } +} + +// NewStopProjectInstanceParamsWithContext creates a new StopProjectInstanceParams object +// with the ability to set a context for a request. +func NewStopProjectInstanceParamsWithContext(ctx context.Context) *StopProjectInstanceParams { + return &StopProjectInstanceParams{ + Context: ctx, + } +} + +// NewStopProjectInstanceParamsWithHTTPClient creates a new StopProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewStopProjectInstanceParamsWithHTTPClient(client *http.Client) *StopProjectInstanceParams { + return &StopProjectInstanceParams{ + HTTPClient: client, + } +} + +/* StopProjectInstanceParams contains all the parameters to send to the API endpoint + for the stop project instance operation. + + Typically these are written to a http.Request. +*/ +type StopProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the stop project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StopProjectInstanceParams) WithDefaults() *StopProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the stop project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StopProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the stop project instance params +func (o *StopProjectInstanceParams) WithTimeout(timeout time.Duration) *StopProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the stop project instance params +func (o *StopProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the stop project instance params +func (o *StopProjectInstanceParams) WithContext(ctx context.Context) *StopProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the stop project instance params +func (o *StopProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the stop project instance params +func (o *StopProjectInstanceParams) WithHTTPClient(client *http.Client) *StopProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the stop project instance params +func (o *StopProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the stop project instance params +func (o *StopProjectInstanceParams) WithAuthorization(authorization string) *StopProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the stop project instance params +func (o *StopProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the stop project instance params +func (o *StopProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *StopProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the stop project instance params +func (o *StopProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the stop project instance params +func (o *StopProjectInstanceParams) WithBmpUserID(bmpUserID *string) *StopProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the stop project instance params +func (o *StopProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the stop project instance params +func (o *StopProjectInstanceParams) WithInstanceID(instanceID string) *StopProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the stop project instance params +func (o *StopProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the stop project instance params +func (o *StopProjectInstanceParams) WithTraceID(traceID string) *StopProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the stop project instance params +func (o *StopProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *StopProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/stop_project_instance_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/stop_project_instance_responses.go new file mode 100644 index 0000000..245abb7 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/stop_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// StopProjectInstanceReader is a Reader for the StopProjectInstance structure. +type StopProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *StopProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewStopProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewStopProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewStopProjectInstanceOK creates a StopProjectInstanceOK with default headers values +func NewStopProjectInstanceOK() *StopProjectInstanceOK { + return &StopProjectInstanceOK{} +} + +/* StopProjectInstanceOK describes a response with status code 200, with default header values. + +A StopProjectInstanceResult is an response struct that is used to describe stop instance result. +*/ +type StopProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *StopProjectInstanceOKBody +} + +// IsSuccess returns true when this stop project instance o k response has a 2xx status code +func (o *StopProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this stop project instance o k response has a 3xx status code +func (o *StopProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this stop project instance o k response has a 4xx status code +func (o *StopProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this stop project instance o k response has a 5xx status code +func (o *StopProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this stop project instance o k response a status code equal to that given +func (o *StopProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *StopProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/stop][%d] stopProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *StopProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/stop][%d] stopProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *StopProjectInstanceOK) GetPayload() *StopProjectInstanceOKBody { + return o.Payload +} + +func (o *StopProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StopProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewStopProjectInstanceDefault creates a StopProjectInstanceDefault with default headers values +func NewStopProjectInstanceDefault(code int) *StopProjectInstanceDefault { + return &StopProjectInstanceDefault{ + _statusCode: code, + } +} + +/* StopProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type StopProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *StopProjectInstanceDefaultBody +} + +// Code gets the status code for the stop project instance default response +func (o *StopProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this stop project instance default response has a 2xx status code +func (o *StopProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this stop project instance default response has a 3xx status code +func (o *StopProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this stop project instance default response has a 4xx status code +func (o *StopProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this stop project instance default response has a 5xx status code +func (o *StopProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this stop project instance default response a status code equal to that given +func (o *StopProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *StopProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/stop][%d] stopProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *StopProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/stop][%d] stopProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *StopProjectInstanceDefault) GetPayload() *StopProjectInstanceDefaultBody { + return o.Payload +} + +func (o *StopProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StopProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*StopProjectInstanceDefaultBody stop project instance default body +swagger:model StopProjectInstanceDefaultBody +*/ +type StopProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this stop project instance default body +func (o *StopProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("stopProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *StopProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("stopProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this stop project instance default body based on the context it is used +func (o *StopProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StopProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StopProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res StopProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*StopProjectInstanceOKBody stop project instance o k body +swagger:model StopProjectInstanceOKBody +*/ +type StopProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this stop project instance o k body +func (o *StopProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this stop project instance o k body based on the context it is used +func (o *StopProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StopProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StopProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res StopProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/un_lock_project_instance_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/un_lock_project_instance_parameters.go new file mode 100644 index 0000000..c23507f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/un_lock_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewUnLockProjectInstanceParams creates a new UnLockProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewUnLockProjectInstanceParams() *UnLockProjectInstanceParams { + return &UnLockProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUnLockProjectInstanceParamsWithTimeout creates a new UnLockProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewUnLockProjectInstanceParamsWithTimeout(timeout time.Duration) *UnLockProjectInstanceParams { + return &UnLockProjectInstanceParams{ + timeout: timeout, + } +} + +// NewUnLockProjectInstanceParamsWithContext creates a new UnLockProjectInstanceParams object +// with the ability to set a context for a request. +func NewUnLockProjectInstanceParamsWithContext(ctx context.Context) *UnLockProjectInstanceParams { + return &UnLockProjectInstanceParams{ + Context: ctx, + } +} + +// NewUnLockProjectInstanceParamsWithHTTPClient creates a new UnLockProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewUnLockProjectInstanceParamsWithHTTPClient(client *http.Client) *UnLockProjectInstanceParams { + return &UnLockProjectInstanceParams{ + HTTPClient: client, + } +} + +/* UnLockProjectInstanceParams contains all the parameters to send to the API endpoint + for the un lock project instance operation. + + Typically these are written to a http.Request. +*/ +type UnLockProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the un lock project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UnLockProjectInstanceParams) WithDefaults() *UnLockProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the un lock project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UnLockProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithTimeout(timeout time.Duration) *UnLockProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithContext(ctx context.Context) *UnLockProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithHTTPClient(client *http.Client) *UnLockProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithAuthorization(authorization string) *UnLockProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *UnLockProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithBmpUserID(bmpUserID *string) *UnLockProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithInstanceID(instanceID string) *UnLockProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithTraceID(traceID string) *UnLockProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *UnLockProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/un_lock_project_instance_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/un_lock_project_instance_responses.go new file mode 100644 index 0000000..1c615e7 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/instance/un_lock_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// UnLockProjectInstanceReader is a Reader for the UnLockProjectInstance structure. +type UnLockProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UnLockProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUnLockProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewUnLockProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewUnLockProjectInstanceOK creates a UnLockProjectInstanceOK with default headers values +func NewUnLockProjectInstanceOK() *UnLockProjectInstanceOK { + return &UnLockProjectInstanceOK{} +} + +/* UnLockProjectInstanceOK describes a response with status code 200, with default header values. + +A UnLockProjectInstanceResult is an response struct that is used to describe unlock instance result. +*/ +type UnLockProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *UnLockProjectInstanceOKBody +} + +// IsSuccess returns true when this un lock project instance o k response has a 2xx status code +func (o *UnLockProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this un lock project instance o k response has a 3xx status code +func (o *UnLockProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this un lock project instance o k response has a 4xx status code +func (o *UnLockProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this un lock project instance o k response has a 5xx status code +func (o *UnLockProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this un lock project instance o k response a status code equal to that given +func (o *UnLockProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *UnLockProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/unlock][%d] unLockProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *UnLockProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/unlock][%d] unLockProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *UnLockProjectInstanceOK) GetPayload() *UnLockProjectInstanceOKBody { + return o.Payload +} + +func (o *UnLockProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(UnLockProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUnLockProjectInstanceDefault creates a UnLockProjectInstanceDefault with default headers values +func NewUnLockProjectInstanceDefault(code int) *UnLockProjectInstanceDefault { + return &UnLockProjectInstanceDefault{ + _statusCode: code, + } +} + +/* UnLockProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type UnLockProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *UnLockProjectInstanceDefaultBody +} + +// Code gets the status code for the un lock project instance default response +func (o *UnLockProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this un lock project instance default response has a 2xx status code +func (o *UnLockProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this un lock project instance default response has a 3xx status code +func (o *UnLockProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this un lock project instance default response has a 4xx status code +func (o *UnLockProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this un lock project instance default response has a 5xx status code +func (o *UnLockProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this un lock project instance default response a status code equal to that given +func (o *UnLockProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *UnLockProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/unlock][%d] unLockProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *UnLockProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/unlock][%d] unLockProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *UnLockProjectInstanceDefault) GetPayload() *UnLockProjectInstanceDefaultBody { + return o.Payload +} + +func (o *UnLockProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(UnLockProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*UnLockProjectInstanceDefaultBody un lock project instance default body +swagger:model UnLockProjectInstanceDefaultBody +*/ +type UnLockProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this un lock project instance default body +func (o *UnLockProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnLockProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("unLockProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *UnLockProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("unLockProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unLockProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unLockProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this un lock project instance default body based on the context it is used +func (o *UnLockProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnLockProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unLockProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unLockProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *UnLockProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *UnLockProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res UnLockProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*UnLockProjectInstanceOKBody un lock project instance o k body +swagger:model UnLockProjectInstanceOKBody +*/ +type UnLockProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this un lock project instance o k body +func (o *UnLockProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnLockProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unLockProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unLockProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this un lock project instance o k body based on the context it is used +func (o *UnLockProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnLockProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unLockProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unLockProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *UnLockProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *UnLockProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res UnLockProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_content_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_content_parameters.go new file mode 100644 index 0000000..aa6caae --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_content_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeLicenseContentParams creates a new DescribeLicenseContentParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeLicenseContentParams() *DescribeLicenseContentParams { + return &DescribeLicenseContentParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeLicenseContentParamsWithTimeout creates a new DescribeLicenseContentParams object +// with the ability to set a timeout on a request. +func NewDescribeLicenseContentParamsWithTimeout(timeout time.Duration) *DescribeLicenseContentParams { + return &DescribeLicenseContentParams{ + timeout: timeout, + } +} + +// NewDescribeLicenseContentParamsWithContext creates a new DescribeLicenseContentParams object +// with the ability to set a context for a request. +func NewDescribeLicenseContentParamsWithContext(ctx context.Context) *DescribeLicenseContentParams { + return &DescribeLicenseContentParams{ + Context: ctx, + } +} + +// NewDescribeLicenseContentParamsWithHTTPClient creates a new DescribeLicenseContentParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeLicenseContentParamsWithHTTPClient(client *http.Client) *DescribeLicenseContentParams { + return &DescribeLicenseContentParams{ + HTTPClient: client, + } +} + +/* DescribeLicenseContentParams contains all the parameters to send to the API endpoint + for the describe license content operation. + + Typically these are written to a http.Request. +*/ +type DescribeLicenseContentParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe license content params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLicenseContentParams) WithDefaults() *DescribeLicenseContentParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe license content params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLicenseContentParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe license content params +func (o *DescribeLicenseContentParams) WithTimeout(timeout time.Duration) *DescribeLicenseContentParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe license content params +func (o *DescribeLicenseContentParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe license content params +func (o *DescribeLicenseContentParams) WithContext(ctx context.Context) *DescribeLicenseContentParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe license content params +func (o *DescribeLicenseContentParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe license content params +func (o *DescribeLicenseContentParams) WithHTTPClient(client *http.Client) *DescribeLicenseContentParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe license content params +func (o *DescribeLicenseContentParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe license content params +func (o *DescribeLicenseContentParams) WithAuthorization(authorization string) *DescribeLicenseContentParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe license content params +func (o *DescribeLicenseContentParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe license content params +func (o *DescribeLicenseContentParams) WithBmpLanguage(bmpLanguage *string) *DescribeLicenseContentParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe license content params +func (o *DescribeLicenseContentParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe license content params +func (o *DescribeLicenseContentParams) WithBmpUserID(bmpUserID *string) *DescribeLicenseContentParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe license content params +func (o *DescribeLicenseContentParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe license content params +func (o *DescribeLicenseContentParams) WithTraceID(traceID string) *DescribeLicenseContentParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe license content params +func (o *DescribeLicenseContentParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeLicenseContentParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_content_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_content_responses.go new file mode 100644 index 0000000..eaa8bea --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_content_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeLicenseContentReader is a Reader for the DescribeLicenseContent structure. +type DescribeLicenseContentReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeLicenseContentReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeLicenseContentOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeLicenseContentDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeLicenseContentOK creates a DescribeLicenseContentOK with default headers values +func NewDescribeLicenseContentOK() *DescribeLicenseContentOK { + return &DescribeLicenseContentOK{} +} + +/* DescribeLicenseContentOK describes a response with status code 200, with default header values. + +A DescribeLicenseContentResult is an response struct that is used to describe getuser. +*/ +type DescribeLicenseContentOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLicenseContentOKBody +} + +// IsSuccess returns true when this describe license content o k response has a 2xx status code +func (o *DescribeLicenseContentOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe license content o k response has a 3xx status code +func (o *DescribeLicenseContentOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe license content o k response has a 4xx status code +func (o *DescribeLicenseContentOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe license content o k response has a 5xx status code +func (o *DescribeLicenseContentOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe license content o k response a status code equal to that given +func (o *DescribeLicenseContentOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeLicenseContentOK) Error() string { + return fmt.Sprintf("[GET /license/content][%d] describeLicenseContentOK %+v", 200, o.Payload) +} + +func (o *DescribeLicenseContentOK) String() string { + return fmt.Sprintf("[GET /license/content][%d] describeLicenseContentOK %+v", 200, o.Payload) +} + +func (o *DescribeLicenseContentOK) GetPayload() *DescribeLicenseContentOKBody { + return o.Payload +} + +func (o *DescribeLicenseContentOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLicenseContentOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeLicenseContentDefault creates a DescribeLicenseContentDefault with default headers values +func NewDescribeLicenseContentDefault(code int) *DescribeLicenseContentDefault { + return &DescribeLicenseContentDefault{ + _statusCode: code, + } +} + +/* DescribeLicenseContentDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeLicenseContentDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLicenseContentDefaultBody +} + +// Code gets the status code for the describe license content default response +func (o *DescribeLicenseContentDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe license content default response has a 2xx status code +func (o *DescribeLicenseContentDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe license content default response has a 3xx status code +func (o *DescribeLicenseContentDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe license content default response has a 4xx status code +func (o *DescribeLicenseContentDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe license content default response has a 5xx status code +func (o *DescribeLicenseContentDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe license content default response a status code equal to that given +func (o *DescribeLicenseContentDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeLicenseContentDefault) Error() string { + return fmt.Sprintf("[GET /license/content][%d] describeLicenseContent default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLicenseContentDefault) String() string { + return fmt.Sprintf("[GET /license/content][%d] describeLicenseContent default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLicenseContentDefault) GetPayload() *DescribeLicenseContentDefaultBody { + return o.Payload +} + +func (o *DescribeLicenseContentDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLicenseContentDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeLicenseContentDefaultBody describe license content default body +swagger:model DescribeLicenseContentDefaultBody +*/ +type DescribeLicenseContentDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe license content default body +func (o *DescribeLicenseContentDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseContentDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeLicenseContent default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeLicenseContentDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeLicenseContent default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseContent default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseContent default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe license content default body based on the context it is used +func (o *DescribeLicenseContentDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseContentDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseContent default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseContent default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLicenseContentDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLicenseContentDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeLicenseContentDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeLicenseContentOKBody describe license content o k body +swagger:model DescribeLicenseContentOKBody +*/ +type DescribeLicenseContentOKBody struct { + + // result + Result *models.LicenseContent `json:"result,omitempty"` +} + +// Validate validates this describe license content o k body +func (o *DescribeLicenseContentOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseContentOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseContentOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseContentOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe license content o k body based on the context it is used +func (o *DescribeLicenseContentOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseContentOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseContentOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseContentOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLicenseContentOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLicenseContentOKBody) UnmarshalBinary(b []byte) error { + var res DescribeLicenseContentOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_token_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_token_parameters.go new file mode 100644 index 0000000..36295cf --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_token_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeLicenseTokenParams creates a new DescribeLicenseTokenParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeLicenseTokenParams() *DescribeLicenseTokenParams { + return &DescribeLicenseTokenParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeLicenseTokenParamsWithTimeout creates a new DescribeLicenseTokenParams object +// with the ability to set a timeout on a request. +func NewDescribeLicenseTokenParamsWithTimeout(timeout time.Duration) *DescribeLicenseTokenParams { + return &DescribeLicenseTokenParams{ + timeout: timeout, + } +} + +// NewDescribeLicenseTokenParamsWithContext creates a new DescribeLicenseTokenParams object +// with the ability to set a context for a request. +func NewDescribeLicenseTokenParamsWithContext(ctx context.Context) *DescribeLicenseTokenParams { + return &DescribeLicenseTokenParams{ + Context: ctx, + } +} + +// NewDescribeLicenseTokenParamsWithHTTPClient creates a new DescribeLicenseTokenParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeLicenseTokenParamsWithHTTPClient(client *http.Client) *DescribeLicenseTokenParams { + return &DescribeLicenseTokenParams{ + HTTPClient: client, + } +} + +/* DescribeLicenseTokenParams contains all the parameters to send to the API endpoint + for the describe license token operation. + + Typically these are written to a http.Request. +*/ +type DescribeLicenseTokenParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe license token params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLicenseTokenParams) WithDefaults() *DescribeLicenseTokenParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe license token params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLicenseTokenParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe license token params +func (o *DescribeLicenseTokenParams) WithTimeout(timeout time.Duration) *DescribeLicenseTokenParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe license token params +func (o *DescribeLicenseTokenParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe license token params +func (o *DescribeLicenseTokenParams) WithContext(ctx context.Context) *DescribeLicenseTokenParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe license token params +func (o *DescribeLicenseTokenParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe license token params +func (o *DescribeLicenseTokenParams) WithHTTPClient(client *http.Client) *DescribeLicenseTokenParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe license token params +func (o *DescribeLicenseTokenParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe license token params +func (o *DescribeLicenseTokenParams) WithAuthorization(authorization string) *DescribeLicenseTokenParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe license token params +func (o *DescribeLicenseTokenParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe license token params +func (o *DescribeLicenseTokenParams) WithBmpLanguage(bmpLanguage *string) *DescribeLicenseTokenParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe license token params +func (o *DescribeLicenseTokenParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe license token params +func (o *DescribeLicenseTokenParams) WithBmpUserID(bmpUserID *string) *DescribeLicenseTokenParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe license token params +func (o *DescribeLicenseTokenParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe license token params +func (o *DescribeLicenseTokenParams) WithTraceID(traceID string) *DescribeLicenseTokenParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe license token params +func (o *DescribeLicenseTokenParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeLicenseTokenParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_token_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_token_responses.go new file mode 100644 index 0000000..f840018 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_token_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeLicenseTokenReader is a Reader for the DescribeLicenseToken structure. +type DescribeLicenseTokenReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeLicenseTokenReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeLicenseTokenOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeLicenseTokenDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeLicenseTokenOK creates a DescribeLicenseTokenOK with default headers values +func NewDescribeLicenseTokenOK() *DescribeLicenseTokenOK { + return &DescribeLicenseTokenOK{} +} + +/* DescribeLicenseTokenOK describes a response with status code 200, with default header values. + +A DescribeLocalUserResult is an response struct that is used to describe getuser. +*/ +type DescribeLicenseTokenOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLicenseTokenOKBody +} + +// IsSuccess returns true when this describe license token o k response has a 2xx status code +func (o *DescribeLicenseTokenOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe license token o k response has a 3xx status code +func (o *DescribeLicenseTokenOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe license token o k response has a 4xx status code +func (o *DescribeLicenseTokenOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe license token o k response has a 5xx status code +func (o *DescribeLicenseTokenOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe license token o k response a status code equal to that given +func (o *DescribeLicenseTokenOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeLicenseTokenOK) Error() string { + return fmt.Sprintf("[GET /license/requestToken][%d] describeLicenseTokenOK %+v", 200, o.Payload) +} + +func (o *DescribeLicenseTokenOK) String() string { + return fmt.Sprintf("[GET /license/requestToken][%d] describeLicenseTokenOK %+v", 200, o.Payload) +} + +func (o *DescribeLicenseTokenOK) GetPayload() *DescribeLicenseTokenOKBody { + return o.Payload +} + +func (o *DescribeLicenseTokenOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLicenseTokenOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeLicenseTokenDefault creates a DescribeLicenseTokenDefault with default headers values +func NewDescribeLicenseTokenDefault(code int) *DescribeLicenseTokenDefault { + return &DescribeLicenseTokenDefault{ + _statusCode: code, + } +} + +/* DescribeLicenseTokenDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeLicenseTokenDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLicenseTokenDefaultBody +} + +// Code gets the status code for the describe license token default response +func (o *DescribeLicenseTokenDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe license token default response has a 2xx status code +func (o *DescribeLicenseTokenDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe license token default response has a 3xx status code +func (o *DescribeLicenseTokenDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe license token default response has a 4xx status code +func (o *DescribeLicenseTokenDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe license token default response has a 5xx status code +func (o *DescribeLicenseTokenDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe license token default response a status code equal to that given +func (o *DescribeLicenseTokenDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeLicenseTokenDefault) Error() string { + return fmt.Sprintf("[GET /license/requestToken][%d] describeLicenseToken default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLicenseTokenDefault) String() string { + return fmt.Sprintf("[GET /license/requestToken][%d] describeLicenseToken default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLicenseTokenDefault) GetPayload() *DescribeLicenseTokenDefaultBody { + return o.Payload +} + +func (o *DescribeLicenseTokenDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLicenseTokenDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeLicenseTokenDefaultBody describe license token default body +swagger:model DescribeLicenseTokenDefaultBody +*/ +type DescribeLicenseTokenDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe license token default body +func (o *DescribeLicenseTokenDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseTokenDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeLicenseToken default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeLicenseTokenDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeLicenseToken default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseToken default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseToken default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe license token default body based on the context it is used +func (o *DescribeLicenseTokenDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseTokenDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseToken default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseToken default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLicenseTokenDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLicenseTokenDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeLicenseTokenDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeLicenseTokenOKBody describe license token o k body +swagger:model DescribeLicenseTokenOKBody +*/ +type DescribeLicenseTokenOKBody struct { + + // result + Result *models.LicenseToken `json:"result,omitempty"` +} + +// Validate validates this describe license token o k body +func (o *DescribeLicenseTokenOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseTokenOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseTokenOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseTokenOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe license token o k body based on the context it is used +func (o *DescribeLicenseTokenOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseTokenOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseTokenOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseTokenOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLicenseTokenOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLicenseTokenOKBody) UnmarshalBinary(b []byte) error { + var res DescribeLicenseTokenOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/license_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/license_client.go new file mode 100644 index 0000000..12231a8 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/license_client.go @@ -0,0 +1,157 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new license API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for license API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DescribeLicenseContent(params *DescribeLicenseContentParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLicenseContentOK, error) + + DescribeLicenseToken(params *DescribeLicenseTokenParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLicenseTokenOK, error) + + UploadLicense(params *UploadLicenseParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UploadLicenseOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DescribeLicenseContent DescribeLicenseContent 获取授权详情 +*/ +func (a *Client) DescribeLicenseContent(params *DescribeLicenseContentParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLicenseContentOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeLicenseContentParams() + } + op := &runtime.ClientOperation{ + ID: "describeLicenseContent", + Method: "GET", + PathPattern: "/license/content", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeLicenseContentReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeLicenseContentOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeLicenseContentDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeLicenseToken DescribeRequestToken 获取请求码 +*/ +func (a *Client) DescribeLicenseToken(params *DescribeLicenseTokenParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLicenseTokenOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeLicenseTokenParams() + } + op := &runtime.ClientOperation{ + ID: "describeLicenseToken", + Method: "GET", + PathPattern: "/license/requestToken", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeLicenseTokenReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeLicenseTokenOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeLicenseTokenDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + UploadLicense UploadLicense 上传授权 +*/ +func (a *Client) UploadLicense(params *UploadLicenseParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UploadLicenseOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewUploadLicenseParams() + } + op := &runtime.ClientOperation{ + ID: "uploadLicense", + Method: "POST", + PathPattern: "/license/upload", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UploadLicenseReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*UploadLicenseOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*UploadLicenseDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/upload_license_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/upload_license_parameters.go new file mode 100644 index 0000000..6435a40 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/upload_license_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewUploadLicenseParams creates a new UploadLicenseParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewUploadLicenseParams() *UploadLicenseParams { + return &UploadLicenseParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUploadLicenseParamsWithTimeout creates a new UploadLicenseParams object +// with the ability to set a timeout on a request. +func NewUploadLicenseParamsWithTimeout(timeout time.Duration) *UploadLicenseParams { + return &UploadLicenseParams{ + timeout: timeout, + } +} + +// NewUploadLicenseParamsWithContext creates a new UploadLicenseParams object +// with the ability to set a context for a request. +func NewUploadLicenseParamsWithContext(ctx context.Context) *UploadLicenseParams { + return &UploadLicenseParams{ + Context: ctx, + } +} + +// NewUploadLicenseParamsWithHTTPClient creates a new UploadLicenseParams object +// with the ability to set a custom HTTPClient for a request. +func NewUploadLicenseParamsWithHTTPClient(client *http.Client) *UploadLicenseParams { + return &UploadLicenseParams{ + HTTPClient: client, + } +} + +/* UploadLicenseParams contains all the parameters to send to the API endpoint + for the upload license operation. + + Typically these are written to a http.Request. +*/ +type UploadLicenseParams struct { + + // Body. + Body *models.CreateLicenseRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the upload license params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UploadLicenseParams) WithDefaults() *UploadLicenseParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the upload license params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UploadLicenseParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the upload license params +func (o *UploadLicenseParams) WithTimeout(timeout time.Duration) *UploadLicenseParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the upload license params +func (o *UploadLicenseParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the upload license params +func (o *UploadLicenseParams) WithContext(ctx context.Context) *UploadLicenseParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the upload license params +func (o *UploadLicenseParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the upload license params +func (o *UploadLicenseParams) WithHTTPClient(client *http.Client) *UploadLicenseParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the upload license params +func (o *UploadLicenseParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the upload license params +func (o *UploadLicenseParams) WithBody(body *models.CreateLicenseRequest) *UploadLicenseParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the upload license params +func (o *UploadLicenseParams) SetBody(body *models.CreateLicenseRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the upload license params +func (o *UploadLicenseParams) WithAuthorization(authorization string) *UploadLicenseParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the upload license params +func (o *UploadLicenseParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the upload license params +func (o *UploadLicenseParams) WithBmpLanguage(bmpLanguage *string) *UploadLicenseParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the upload license params +func (o *UploadLicenseParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the upload license params +func (o *UploadLicenseParams) WithBmpUserID(bmpUserID *string) *UploadLicenseParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the upload license params +func (o *UploadLicenseParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the upload license params +func (o *UploadLicenseParams) WithTraceID(traceID string) *UploadLicenseParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the upload license params +func (o *UploadLicenseParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *UploadLicenseParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/upload_license_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/upload_license_responses.go new file mode 100644 index 0000000..7e8828a --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/license/upload_license_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// UploadLicenseReader is a Reader for the UploadLicense structure. +type UploadLicenseReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UploadLicenseReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUploadLicenseOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewUploadLicenseDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewUploadLicenseOK creates a UploadLicenseOK with default headers values +func NewUploadLicenseOK() *UploadLicenseOK { + return &UploadLicenseOK{} +} + +/* UploadLicenseOK describes a response with status code 200, with default header values. + +A UploadLicenseResult is an response struct that is used to describe modify instance result. +*/ +type UploadLicenseOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *UploadLicenseOKBody +} + +// IsSuccess returns true when this upload license o k response has a 2xx status code +func (o *UploadLicenseOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this upload license o k response has a 3xx status code +func (o *UploadLicenseOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this upload license o k response has a 4xx status code +func (o *UploadLicenseOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this upload license o k response has a 5xx status code +func (o *UploadLicenseOK) IsServerError() bool { + return false +} + +// IsCode returns true when this upload license o k response a status code equal to that given +func (o *UploadLicenseOK) IsCode(code int) bool { + return code == 200 +} + +func (o *UploadLicenseOK) Error() string { + return fmt.Sprintf("[POST /license/upload][%d] uploadLicenseOK %+v", 200, o.Payload) +} + +func (o *UploadLicenseOK) String() string { + return fmt.Sprintf("[POST /license/upload][%d] uploadLicenseOK %+v", 200, o.Payload) +} + +func (o *UploadLicenseOK) GetPayload() *UploadLicenseOKBody { + return o.Payload +} + +func (o *UploadLicenseOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(UploadLicenseOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUploadLicenseDefault creates a UploadLicenseDefault with default headers values +func NewUploadLicenseDefault(code int) *UploadLicenseDefault { + return &UploadLicenseDefault{ + _statusCode: code, + } +} + +/* UploadLicenseDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type UploadLicenseDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *UploadLicenseDefaultBody +} + +// Code gets the status code for the upload license default response +func (o *UploadLicenseDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this upload license default response has a 2xx status code +func (o *UploadLicenseDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this upload license default response has a 3xx status code +func (o *UploadLicenseDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this upload license default response has a 4xx status code +func (o *UploadLicenseDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this upload license default response has a 5xx status code +func (o *UploadLicenseDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this upload license default response a status code equal to that given +func (o *UploadLicenseDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *UploadLicenseDefault) Error() string { + return fmt.Sprintf("[POST /license/upload][%d] uploadLicense default %+v", o._statusCode, o.Payload) +} + +func (o *UploadLicenseDefault) String() string { + return fmt.Sprintf("[POST /license/upload][%d] uploadLicense default %+v", o._statusCode, o.Payload) +} + +func (o *UploadLicenseDefault) GetPayload() *UploadLicenseDefaultBody { + return o.Payload +} + +func (o *UploadLicenseDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(UploadLicenseDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*UploadLicenseDefaultBody upload license default body +swagger:model UploadLicenseDefaultBody +*/ +type UploadLicenseDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this upload license default body +func (o *UploadLicenseDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UploadLicenseDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("uploadLicense default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *UploadLicenseDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("uploadLicense default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("uploadLicense default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("uploadLicense default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this upload license default body based on the context it is used +func (o *UploadLicenseDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UploadLicenseDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("uploadLicense default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("uploadLicense default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *UploadLicenseDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *UploadLicenseDefaultBody) UnmarshalBinary(b []byte) error { + var res UploadLicenseDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*UploadLicenseOKBody upload license o k body +swagger:model UploadLicenseOKBody +*/ +type UploadLicenseOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this upload license o k body +func (o *UploadLicenseOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UploadLicenseOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("uploadLicenseOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("uploadLicenseOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this upload license o k body based on the context it is used +func (o *UploadLicenseOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UploadLicenseOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("uploadLicenseOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("uploadLicenseOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *UploadLicenseOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *UploadLicenseOKBody) UnmarshalBinary(b []byte) error { + var res UploadLicenseOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/delete_message_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/delete_message_parameters.go new file mode 100644 index 0000000..eccf608 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/delete_message_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewDeleteMessageParams creates a new DeleteMessageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteMessageParams() *DeleteMessageParams { + return &DeleteMessageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteMessageParamsWithTimeout creates a new DeleteMessageParams object +// with the ability to set a timeout on a request. +func NewDeleteMessageParamsWithTimeout(timeout time.Duration) *DeleteMessageParams { + return &DeleteMessageParams{ + timeout: timeout, + } +} + +// NewDeleteMessageParamsWithContext creates a new DeleteMessageParams object +// with the ability to set a context for a request. +func NewDeleteMessageParamsWithContext(ctx context.Context) *DeleteMessageParams { + return &DeleteMessageParams{ + Context: ctx, + } +} + +// NewDeleteMessageParamsWithHTTPClient creates a new DeleteMessageParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteMessageParamsWithHTTPClient(client *http.Client) *DeleteMessageParams { + return &DeleteMessageParams{ + HTTPClient: client, + } +} + +/* DeleteMessageParams contains all the parameters to send to the API endpoint + for the delete message operation. + + Typically these are written to a http.Request. +*/ +type DeleteMessageParams struct { + + // Body. + Body *models.DeleteMessagesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete message params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteMessageParams) WithDefaults() *DeleteMessageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete message params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteMessageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete message params +func (o *DeleteMessageParams) WithTimeout(timeout time.Duration) *DeleteMessageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete message params +func (o *DeleteMessageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete message params +func (o *DeleteMessageParams) WithContext(ctx context.Context) *DeleteMessageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete message params +func (o *DeleteMessageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete message params +func (o *DeleteMessageParams) WithHTTPClient(client *http.Client) *DeleteMessageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete message params +func (o *DeleteMessageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the delete message params +func (o *DeleteMessageParams) WithBody(body *models.DeleteMessagesRequest) *DeleteMessageParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the delete message params +func (o *DeleteMessageParams) SetBody(body *models.DeleteMessagesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the delete message params +func (o *DeleteMessageParams) WithAuthorization(authorization string) *DeleteMessageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete message params +func (o *DeleteMessageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete message params +func (o *DeleteMessageParams) WithBmpLanguage(bmpLanguage *string) *DeleteMessageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete message params +func (o *DeleteMessageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete message params +func (o *DeleteMessageParams) WithBmpUserID(bmpUserID *string) *DeleteMessageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete message params +func (o *DeleteMessageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete message params +func (o *DeleteMessageParams) WithTraceID(traceID string) *DeleteMessageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete message params +func (o *DeleteMessageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteMessageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/delete_message_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/delete_message_responses.go new file mode 100644 index 0000000..440c993 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/delete_message_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteMessageReader is a Reader for the DeleteMessage structure. +type DeleteMessageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteMessageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteMessageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteMessageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteMessageOK creates a DeleteMessageOK with default headers values +func NewDeleteMessageOK() *DeleteMessageOK { + return &DeleteMessageOK{} +} + +/* DeleteMessageOK describes a response with status code 200, with default header values. + +A DeleteMessageResult is an response struct +*/ +type DeleteMessageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteMessageOKBody +} + +// IsSuccess returns true when this delete message o k response has a 2xx status code +func (o *DeleteMessageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete message o k response has a 3xx status code +func (o *DeleteMessageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete message o k response has a 4xx status code +func (o *DeleteMessageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete message o k response has a 5xx status code +func (o *DeleteMessageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete message o k response a status code equal to that given +func (o *DeleteMessageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteMessageOK) Error() string { + return fmt.Sprintf("[DELETE /messages/delete][%d] deleteMessageOK %+v", 200, o.Payload) +} + +func (o *DeleteMessageOK) String() string { + return fmt.Sprintf("[DELETE /messages/delete][%d] deleteMessageOK %+v", 200, o.Payload) +} + +func (o *DeleteMessageOK) GetPayload() *DeleteMessageOKBody { + return o.Payload +} + +func (o *DeleteMessageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteMessageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteMessageDefault creates a DeleteMessageDefault with default headers values +func NewDeleteMessageDefault(code int) *DeleteMessageDefault { + return &DeleteMessageDefault{ + _statusCode: code, + } +} + +/* DeleteMessageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteMessageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteMessageDefaultBody +} + +// Code gets the status code for the delete message default response +func (o *DeleteMessageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete message default response has a 2xx status code +func (o *DeleteMessageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete message default response has a 3xx status code +func (o *DeleteMessageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete message default response has a 4xx status code +func (o *DeleteMessageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete message default response has a 5xx status code +func (o *DeleteMessageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete message default response a status code equal to that given +func (o *DeleteMessageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteMessageDefault) Error() string { + return fmt.Sprintf("[DELETE /messages/delete][%d] deleteMessage default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteMessageDefault) String() string { + return fmt.Sprintf("[DELETE /messages/delete][%d] deleteMessage default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteMessageDefault) GetPayload() *DeleteMessageDefaultBody { + return o.Payload +} + +func (o *DeleteMessageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteMessageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteMessageDefaultBody delete message default body +swagger:model DeleteMessageDefaultBody +*/ +type DeleteMessageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete message default body +func (o *DeleteMessageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteMessageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteMessage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteMessageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteMessage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteMessage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteMessage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete message default body based on the context it is used +func (o *DeleteMessageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteMessageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteMessage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteMessage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteMessageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteMessageDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteMessageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteMessageOKBody delete message o k body +swagger:model DeleteMessageOKBody +*/ +type DeleteMessageOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete message o k body +func (o *DeleteMessageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteMessageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteMessageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteMessageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete message o k body based on the context it is used +func (o *DeleteMessageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteMessageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteMessageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteMessageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteMessageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteMessageOKBody) UnmarshalBinary(b []byte) error { + var res DeleteMessageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/dial_mail_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/dial_mail_parameters.go new file mode 100644 index 0000000..8508d4d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/dial_mail_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewDialMailParams creates a new DialMailParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDialMailParams() *DialMailParams { + return &DialMailParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDialMailParamsWithTimeout creates a new DialMailParams object +// with the ability to set a timeout on a request. +func NewDialMailParamsWithTimeout(timeout time.Duration) *DialMailParams { + return &DialMailParams{ + timeout: timeout, + } +} + +// NewDialMailParamsWithContext creates a new DialMailParams object +// with the ability to set a context for a request. +func NewDialMailParamsWithContext(ctx context.Context) *DialMailParams { + return &DialMailParams{ + Context: ctx, + } +} + +// NewDialMailParamsWithHTTPClient creates a new DialMailParams object +// with the ability to set a custom HTTPClient for a request. +func NewDialMailParamsWithHTTPClient(client *http.Client) *DialMailParams { + return &DialMailParams{ + HTTPClient: client, + } +} + +/* DialMailParams contains all the parameters to send to the API endpoint + for the dial mail operation. + + Typically these are written to a http.Request. +*/ +type DialMailParams struct { + + // Body. + Body *models.MailDialRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the dial mail params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DialMailParams) WithDefaults() *DialMailParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the dial mail params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DialMailParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the dial mail params +func (o *DialMailParams) WithTimeout(timeout time.Duration) *DialMailParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the dial mail params +func (o *DialMailParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the dial mail params +func (o *DialMailParams) WithContext(ctx context.Context) *DialMailParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the dial mail params +func (o *DialMailParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the dial mail params +func (o *DialMailParams) WithHTTPClient(client *http.Client) *DialMailParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the dial mail params +func (o *DialMailParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the dial mail params +func (o *DialMailParams) WithBody(body *models.MailDialRequest) *DialMailParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the dial mail params +func (o *DialMailParams) SetBody(body *models.MailDialRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the dial mail params +func (o *DialMailParams) WithAuthorization(authorization string) *DialMailParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the dial mail params +func (o *DialMailParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the dial mail params +func (o *DialMailParams) WithBmpLanguage(bmpLanguage *string) *DialMailParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the dial mail params +func (o *DialMailParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the dial mail params +func (o *DialMailParams) WithBmpUserID(bmpUserID *string) *DialMailParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the dial mail params +func (o *DialMailParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the dial mail params +func (o *DialMailParams) WithTraceID(traceID string) *DialMailParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the dial mail params +func (o *DialMailParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DialMailParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/dial_mail_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/dial_mail_responses.go new file mode 100644 index 0000000..ea6d851 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/dial_mail_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DialMailReader is a Reader for the DialMail structure. +type DialMailReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DialMailReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDialMailOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDialMailDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDialMailOK creates a DialMailOK with default headers values +func NewDialMailOK() *DialMailOK { + return &DialMailOK{} +} + +/* DialMailOK describes a response with status code 200, with default header values. + +A DialMailResult is an response struct +*/ +type DialMailOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DialMailOKBody +} + +// IsSuccess returns true when this dial mail o k response has a 2xx status code +func (o *DialMailOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this dial mail o k response has a 3xx status code +func (o *DialMailOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this dial mail o k response has a 4xx status code +func (o *DialMailOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this dial mail o k response has a 5xx status code +func (o *DialMailOK) IsServerError() bool { + return false +} + +// IsCode returns true when this dial mail o k response a status code equal to that given +func (o *DialMailOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DialMailOK) Error() string { + return fmt.Sprintf("[POST /messages/dialMail][%d] dialMailOK %+v", 200, o.Payload) +} + +func (o *DialMailOK) String() string { + return fmt.Sprintf("[POST /messages/dialMail][%d] dialMailOK %+v", 200, o.Payload) +} + +func (o *DialMailOK) GetPayload() *DialMailOKBody { + return o.Payload +} + +func (o *DialMailOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DialMailOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDialMailDefault creates a DialMailDefault with default headers values +func NewDialMailDefault(code int) *DialMailDefault { + return &DialMailDefault{ + _statusCode: code, + } +} + +/* DialMailDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DialMailDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DialMailDefaultBody +} + +// Code gets the status code for the dial mail default response +func (o *DialMailDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this dial mail default response has a 2xx status code +func (o *DialMailDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this dial mail default response has a 3xx status code +func (o *DialMailDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this dial mail default response has a 4xx status code +func (o *DialMailDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this dial mail default response has a 5xx status code +func (o *DialMailDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this dial mail default response a status code equal to that given +func (o *DialMailDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DialMailDefault) Error() string { + return fmt.Sprintf("[POST /messages/dialMail][%d] dialMail default %+v", o._statusCode, o.Payload) +} + +func (o *DialMailDefault) String() string { + return fmt.Sprintf("[POST /messages/dialMail][%d] dialMail default %+v", o._statusCode, o.Payload) +} + +func (o *DialMailDefault) GetPayload() *DialMailDefaultBody { + return o.Payload +} + +func (o *DialMailDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DialMailDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DialMailDefaultBody dial mail default body +swagger:model DialMailDefaultBody +*/ +type DialMailDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this dial mail default body +func (o *DialMailDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DialMailDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("dialMail default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DialMailDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("dialMail default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dialMail default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dialMail default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this dial mail default body based on the context it is used +func (o *DialMailDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DialMailDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dialMail default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dialMail default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DialMailDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DialMailDefaultBody) UnmarshalBinary(b []byte) error { + var res DialMailDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DialMailOKBody dial mail o k body +swagger:model DialMailOKBody +*/ +type DialMailOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this dial mail o k body +func (o *DialMailOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DialMailOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dialMailOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dialMailOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this dial mail o k body based on the context it is used +func (o *DialMailOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DialMailOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dialMailOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dialMailOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DialMailOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DialMailOKBody) UnmarshalBinary(b []byte) error { + var res DialMailOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_by_id_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_by_id_parameters.go new file mode 100644 index 0000000..8d75f8c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_by_id_parameters.go @@ -0,0 +1,245 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetMessageByIDParams creates a new GetMessageByIDParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetMessageByIDParams() *GetMessageByIDParams { + return &GetMessageByIDParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetMessageByIDParamsWithTimeout creates a new GetMessageByIDParams object +// with the ability to set a timeout on a request. +func NewGetMessageByIDParamsWithTimeout(timeout time.Duration) *GetMessageByIDParams { + return &GetMessageByIDParams{ + timeout: timeout, + } +} + +// NewGetMessageByIDParamsWithContext creates a new GetMessageByIDParams object +// with the ability to set a context for a request. +func NewGetMessageByIDParamsWithContext(ctx context.Context) *GetMessageByIDParams { + return &GetMessageByIDParams{ + Context: ctx, + } +} + +// NewGetMessageByIDParamsWithHTTPClient creates a new GetMessageByIDParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetMessageByIDParamsWithHTTPClient(client *http.Client) *GetMessageByIDParams { + return &GetMessageByIDParams{ + HTTPClient: client, + } +} + +/* GetMessageByIDParams contains all the parameters to send to the API endpoint + for the get message by Id operation. + + Typically these are written to a http.Request. +*/ +type GetMessageByIDParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // MessageID. + MessageID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get message by Id params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageByIDParams) WithDefaults() *GetMessageByIDParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get message by Id params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageByIDParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get message by Id params +func (o *GetMessageByIDParams) WithTimeout(timeout time.Duration) *GetMessageByIDParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get message by Id params +func (o *GetMessageByIDParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get message by Id params +func (o *GetMessageByIDParams) WithContext(ctx context.Context) *GetMessageByIDParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get message by Id params +func (o *GetMessageByIDParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get message by Id params +func (o *GetMessageByIDParams) WithHTTPClient(client *http.Client) *GetMessageByIDParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get message by Id params +func (o *GetMessageByIDParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the get message by Id params +func (o *GetMessageByIDParams) WithAuthorization(authorization string) *GetMessageByIDParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the get message by Id params +func (o *GetMessageByIDParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the get message by Id params +func (o *GetMessageByIDParams) WithBmpLanguage(bmpLanguage *string) *GetMessageByIDParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the get message by Id params +func (o *GetMessageByIDParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the get message by Id params +func (o *GetMessageByIDParams) WithBmpUserID(bmpUserID *string) *GetMessageByIDParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the get message by Id params +func (o *GetMessageByIDParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithMessageID adds the messageID to the get message by Id params +func (o *GetMessageByIDParams) WithMessageID(messageID string) *GetMessageByIDParams { + o.SetMessageID(messageID) + return o +} + +// SetMessageID adds the messageId to the get message by Id params +func (o *GetMessageByIDParams) SetMessageID(messageID string) { + o.MessageID = messageID +} + +// WithTraceID adds the traceID to the get message by Id params +func (o *GetMessageByIDParams) WithTraceID(traceID string) *GetMessageByIDParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the get message by Id params +func (o *GetMessageByIDParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetMessageByIDParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // query param messageId + qrMessageID := o.MessageID + qMessageID := qrMessageID + if qMessageID != "" { + + if err := r.SetQueryParam("messageId", qMessageID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_by_id_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_by_id_responses.go new file mode 100644 index 0000000..4dd1453 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_by_id_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// GetMessageByIDReader is a Reader for the GetMessageByID structure. +type GetMessageByIDReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetMessageByIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetMessageByIDOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetMessageByIDDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetMessageByIDOK creates a GetMessageByIDOK with default headers values +func NewGetMessageByIDOK() *GetMessageByIDOK { + return &GetMessageByIDOK{} +} + +/* GetMessageByIDOK describes a response with status code 200, with default header values. + +GetMessageByIDOK get message by Id o k +*/ +type GetMessageByIDOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageByIDOKBody +} + +// IsSuccess returns true when this get message by Id o k response has a 2xx status code +func (o *GetMessageByIDOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get message by Id o k response has a 3xx status code +func (o *GetMessageByIDOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get message by Id o k response has a 4xx status code +func (o *GetMessageByIDOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get message by Id o k response has a 5xx status code +func (o *GetMessageByIDOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get message by Id o k response a status code equal to that given +func (o *GetMessageByIDOK) IsCode(code int) bool { + return code == 200 +} + +func (o *GetMessageByIDOK) Error() string { + return fmt.Sprintf("[GET /messages/getMessageById][%d] getMessageByIdOK %+v", 200, o.Payload) +} + +func (o *GetMessageByIDOK) String() string { + return fmt.Sprintf("[GET /messages/getMessageById][%d] getMessageByIdOK %+v", 200, o.Payload) +} + +func (o *GetMessageByIDOK) GetPayload() *GetMessageByIDOKBody { + return o.Payload +} + +func (o *GetMessageByIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageByIDOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetMessageByIDDefault creates a GetMessageByIDDefault with default headers values +func NewGetMessageByIDDefault(code int) *GetMessageByIDDefault { + return &GetMessageByIDDefault{ + _statusCode: code, + } +} + +/* GetMessageByIDDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type GetMessageByIDDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageByIDDefaultBody +} + +// Code gets the status code for the get message by Id default response +func (o *GetMessageByIDDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this get message by Id default response has a 2xx status code +func (o *GetMessageByIDDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get message by Id default response has a 3xx status code +func (o *GetMessageByIDDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get message by Id default response has a 4xx status code +func (o *GetMessageByIDDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get message by Id default response has a 5xx status code +func (o *GetMessageByIDDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get message by Id default response a status code equal to that given +func (o *GetMessageByIDDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *GetMessageByIDDefault) Error() string { + return fmt.Sprintf("[GET /messages/getMessageById][%d] getMessageById default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageByIDDefault) String() string { + return fmt.Sprintf("[GET /messages/getMessageById][%d] getMessageById default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageByIDDefault) GetPayload() *GetMessageByIDDefaultBody { + return o.Payload +} + +func (o *GetMessageByIDDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageByIDDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*GetMessageByIDDefaultBody get message by ID default body +swagger:model GetMessageByIDDefaultBody +*/ +type GetMessageByIDDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this get message by ID default body +func (o *GetMessageByIDDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageByIDDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("getMessageById default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *GetMessageByIDDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("getMessageById default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageById default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageById default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message by ID default body based on the context it is used +func (o *GetMessageByIDDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageByIDDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageById default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageById default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageByIDDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageByIDDefaultBody) UnmarshalBinary(b []byte) error { + var res GetMessageByIDDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*GetMessageByIDOKBody get message by ID o k body +swagger:model GetMessageByIDOKBody +*/ +type GetMessageByIDOKBody struct { + + // result + Result *models.MessageWithNextPrev `json:"result,omitempty"` +} + +// Validate validates this get message by ID o k body +func (o *GetMessageByIDOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageByIDOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageByIdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageByIdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message by ID o k body based on the context it is used +func (o *GetMessageByIDOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageByIDOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageByIdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageByIdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageByIDOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageByIDOKBody) UnmarshalBinary(b []byte) error { + var res GetMessageByIDOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_list_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_list_parameters.go new file mode 100644 index 0000000..e513e14 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_list_parameters.go @@ -0,0 +1,464 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetMessageListParams creates a new GetMessageListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetMessageListParams() *GetMessageListParams { + return &GetMessageListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetMessageListParamsWithTimeout creates a new GetMessageListParams object +// with the ability to set a timeout on a request. +func NewGetMessageListParamsWithTimeout(timeout time.Duration) *GetMessageListParams { + return &GetMessageListParams{ + timeout: timeout, + } +} + +// NewGetMessageListParamsWithContext creates a new GetMessageListParams object +// with the ability to set a context for a request. +func NewGetMessageListParamsWithContext(ctx context.Context) *GetMessageListParams { + return &GetMessageListParams{ + Context: ctx, + } +} + +// NewGetMessageListParamsWithHTTPClient creates a new GetMessageListParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetMessageListParamsWithHTTPClient(client *http.Client) *GetMessageListParams { + return &GetMessageListParams{ + HTTPClient: client, + } +} + +/* GetMessageListParams contains all the parameters to send to the API endpoint + for the get message list operation. + + Typically these are written to a http.Request. +*/ +type GetMessageListParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* Detail. + + 内容模糊搜索 + */ + Detail *string + + /* HasRead. + + 0:未读;1:已读;""不传表示全部 + */ + HasRead *string + + /* IsAll. + + 是否显示全部,取值为1时表示全部 + */ + IsAll *string + + /* MessageSubType. + + 消息子类型 + */ + MessageSubType *string + + /* MessageType. + + 消息类型 + */ + MessageType *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get message list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageListParams) WithDefaults() *GetMessageListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get message list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get message list params +func (o *GetMessageListParams) WithTimeout(timeout time.Duration) *GetMessageListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get message list params +func (o *GetMessageListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get message list params +func (o *GetMessageListParams) WithContext(ctx context.Context) *GetMessageListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get message list params +func (o *GetMessageListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get message list params +func (o *GetMessageListParams) WithHTTPClient(client *http.Client) *GetMessageListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get message list params +func (o *GetMessageListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the get message list params +func (o *GetMessageListParams) WithAuthorization(authorization string) *GetMessageListParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the get message list params +func (o *GetMessageListParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the get message list params +func (o *GetMessageListParams) WithBmpLanguage(bmpLanguage *string) *GetMessageListParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the get message list params +func (o *GetMessageListParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the get message list params +func (o *GetMessageListParams) WithBmpUserID(bmpUserID *string) *GetMessageListParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the get message list params +func (o *GetMessageListParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDetail adds the detail to the get message list params +func (o *GetMessageListParams) WithDetail(detail *string) *GetMessageListParams { + o.SetDetail(detail) + return o +} + +// SetDetail adds the detail to the get message list params +func (o *GetMessageListParams) SetDetail(detail *string) { + o.Detail = detail +} + +// WithHasRead adds the hasRead to the get message list params +func (o *GetMessageListParams) WithHasRead(hasRead *string) *GetMessageListParams { + o.SetHasRead(hasRead) + return o +} + +// SetHasRead adds the hasRead to the get message list params +func (o *GetMessageListParams) SetHasRead(hasRead *string) { + o.HasRead = hasRead +} + +// WithIsAll adds the isAll to the get message list params +func (o *GetMessageListParams) WithIsAll(isAll *string) *GetMessageListParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the get message list params +func (o *GetMessageListParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithMessageSubType adds the messageSubType to the get message list params +func (o *GetMessageListParams) WithMessageSubType(messageSubType *string) *GetMessageListParams { + o.SetMessageSubType(messageSubType) + return o +} + +// SetMessageSubType adds the messageSubType to the get message list params +func (o *GetMessageListParams) SetMessageSubType(messageSubType *string) { + o.MessageSubType = messageSubType +} + +// WithMessageType adds the messageType to the get message list params +func (o *GetMessageListParams) WithMessageType(messageType *string) *GetMessageListParams { + o.SetMessageType(messageType) + return o +} + +// SetMessageType adds the messageType to the get message list params +func (o *GetMessageListParams) SetMessageType(messageType *string) { + o.MessageType = messageType +} + +// WithPageNumber adds the pageNumber to the get message list params +func (o *GetMessageListParams) WithPageNumber(pageNumber *int64) *GetMessageListParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the get message list params +func (o *GetMessageListParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the get message list params +func (o *GetMessageListParams) WithPageSize(pageSize *int64) *GetMessageListParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the get message list params +func (o *GetMessageListParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the get message list params +func (o *GetMessageListParams) WithTraceID(traceID string) *GetMessageListParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the get message list params +func (o *GetMessageListParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetMessageListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.Detail != nil { + + // query param detail + var qrDetail string + + if o.Detail != nil { + qrDetail = *o.Detail + } + qDetail := qrDetail + if qDetail != "" { + + if err := r.SetQueryParam("detail", qDetail); err != nil { + return err + } + } + } + + if o.HasRead != nil { + + // query param hasRead + var qrHasRead string + + if o.HasRead != nil { + qrHasRead = *o.HasRead + } + qHasRead := qrHasRead + if qHasRead != "" { + + if err := r.SetQueryParam("hasRead", qHasRead); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.MessageSubType != nil { + + // query param messageSubType + var qrMessageSubType string + + if o.MessageSubType != nil { + qrMessageSubType = *o.MessageSubType + } + qMessageSubType := qrMessageSubType + if qMessageSubType != "" { + + if err := r.SetQueryParam("messageSubType", qMessageSubType); err != nil { + return err + } + } + } + + if o.MessageType != nil { + + // query param messageType + var qrMessageType string + + if o.MessageType != nil { + qrMessageType = *o.MessageType + } + qMessageType := qrMessageType + if qMessageType != "" { + + if err := r.SetQueryParam("messageType", qMessageType); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_list_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_list_responses.go new file mode 100644 index 0000000..c181f2c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_list_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// GetMessageListReader is a Reader for the GetMessageList structure. +type GetMessageListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetMessageListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetMessageListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetMessageListDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetMessageListOK creates a GetMessageListOK with default headers values +func NewGetMessageListOK() *GetMessageListOK { + return &GetMessageListOK{} +} + +/* GetMessageListOK describes a response with status code 200, with default header values. + +GetMessageListOK get message list o k +*/ +type GetMessageListOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageListOKBody +} + +// IsSuccess returns true when this get message list o k response has a 2xx status code +func (o *GetMessageListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get message list o k response has a 3xx status code +func (o *GetMessageListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get message list o k response has a 4xx status code +func (o *GetMessageListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get message list o k response has a 5xx status code +func (o *GetMessageListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get message list o k response a status code equal to that given +func (o *GetMessageListOK) IsCode(code int) bool { + return code == 200 +} + +func (o *GetMessageListOK) Error() string { + return fmt.Sprintf("[GET /messages][%d] getMessageListOK %+v", 200, o.Payload) +} + +func (o *GetMessageListOK) String() string { + return fmt.Sprintf("[GET /messages][%d] getMessageListOK %+v", 200, o.Payload) +} + +func (o *GetMessageListOK) GetPayload() *GetMessageListOKBody { + return o.Payload +} + +func (o *GetMessageListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageListOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetMessageListDefault creates a GetMessageListDefault with default headers values +func NewGetMessageListDefault(code int) *GetMessageListDefault { + return &GetMessageListDefault{ + _statusCode: code, + } +} + +/* GetMessageListDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type GetMessageListDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageListDefaultBody +} + +// Code gets the status code for the get message list default response +func (o *GetMessageListDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this get message list default response has a 2xx status code +func (o *GetMessageListDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get message list default response has a 3xx status code +func (o *GetMessageListDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get message list default response has a 4xx status code +func (o *GetMessageListDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get message list default response has a 5xx status code +func (o *GetMessageListDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get message list default response a status code equal to that given +func (o *GetMessageListDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *GetMessageListDefault) Error() string { + return fmt.Sprintf("[GET /messages][%d] getMessageList default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageListDefault) String() string { + return fmt.Sprintf("[GET /messages][%d] getMessageList default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageListDefault) GetPayload() *GetMessageListDefaultBody { + return o.Payload +} + +func (o *GetMessageListDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageListDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*GetMessageListDefaultBody get message list default body +swagger:model GetMessageListDefaultBody +*/ +type GetMessageListDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this get message list default body +func (o *GetMessageListDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageListDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("getMessageList default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *GetMessageListDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("getMessageList default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageList default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageList default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message list default body based on the context it is used +func (o *GetMessageListDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageListDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageList default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageList default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageListDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageListDefaultBody) UnmarshalBinary(b []byte) error { + var res GetMessageListDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*GetMessageListOKBody get message list o k body +swagger:model GetMessageListOKBody +*/ +type GetMessageListOKBody struct { + + // result + Result *models.MessageList `json:"result,omitempty"` +} + +// Validate validates this get message list o k body +func (o *GetMessageListOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageListOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageListOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageListOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message list o k body based on the context it is used +func (o *GetMessageListOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageListOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageListOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageListOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageListOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageListOKBody) UnmarshalBinary(b []byte) error { + var res GetMessageListOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_statistic_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_statistic_parameters.go new file mode 100644 index 0000000..8775faf --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_statistic_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetMessageStatisticParams creates a new GetMessageStatisticParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetMessageStatisticParams() *GetMessageStatisticParams { + return &GetMessageStatisticParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetMessageStatisticParamsWithTimeout creates a new GetMessageStatisticParams object +// with the ability to set a timeout on a request. +func NewGetMessageStatisticParamsWithTimeout(timeout time.Duration) *GetMessageStatisticParams { + return &GetMessageStatisticParams{ + timeout: timeout, + } +} + +// NewGetMessageStatisticParamsWithContext creates a new GetMessageStatisticParams object +// with the ability to set a context for a request. +func NewGetMessageStatisticParamsWithContext(ctx context.Context) *GetMessageStatisticParams { + return &GetMessageStatisticParams{ + Context: ctx, + } +} + +// NewGetMessageStatisticParamsWithHTTPClient creates a new GetMessageStatisticParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetMessageStatisticParamsWithHTTPClient(client *http.Client) *GetMessageStatisticParams { + return &GetMessageStatisticParams{ + HTTPClient: client, + } +} + +/* GetMessageStatisticParams contains all the parameters to send to the API endpoint + for the get message statistic operation. + + Typically these are written to a http.Request. +*/ +type GetMessageStatisticParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get message statistic params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageStatisticParams) WithDefaults() *GetMessageStatisticParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get message statistic params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageStatisticParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get message statistic params +func (o *GetMessageStatisticParams) WithTimeout(timeout time.Duration) *GetMessageStatisticParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get message statistic params +func (o *GetMessageStatisticParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get message statistic params +func (o *GetMessageStatisticParams) WithContext(ctx context.Context) *GetMessageStatisticParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get message statistic params +func (o *GetMessageStatisticParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get message statistic params +func (o *GetMessageStatisticParams) WithHTTPClient(client *http.Client) *GetMessageStatisticParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get message statistic params +func (o *GetMessageStatisticParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the get message statistic params +func (o *GetMessageStatisticParams) WithAuthorization(authorization string) *GetMessageStatisticParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the get message statistic params +func (o *GetMessageStatisticParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the get message statistic params +func (o *GetMessageStatisticParams) WithBmpLanguage(bmpLanguage *string) *GetMessageStatisticParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the get message statistic params +func (o *GetMessageStatisticParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the get message statistic params +func (o *GetMessageStatisticParams) WithBmpUserID(bmpUserID *string) *GetMessageStatisticParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the get message statistic params +func (o *GetMessageStatisticParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the get message statistic params +func (o *GetMessageStatisticParams) WithTraceID(traceID string) *GetMessageStatisticParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the get message statistic params +func (o *GetMessageStatisticParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetMessageStatisticParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_statistic_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_statistic_responses.go new file mode 100644 index 0000000..3244f29 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_statistic_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// GetMessageStatisticReader is a Reader for the GetMessageStatistic structure. +type GetMessageStatisticReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetMessageStatisticReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetMessageStatisticOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetMessageStatisticDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetMessageStatisticOK creates a GetMessageStatisticOK with default headers values +func NewGetMessageStatisticOK() *GetMessageStatisticOK { + return &GetMessageStatisticOK{} +} + +/* GetMessageStatisticOK describes a response with status code 200, with default header values. + +GetMessageStatisticOK get message statistic o k +*/ +type GetMessageStatisticOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageStatisticOKBody +} + +// IsSuccess returns true when this get message statistic o k response has a 2xx status code +func (o *GetMessageStatisticOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get message statistic o k response has a 3xx status code +func (o *GetMessageStatisticOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get message statistic o k response has a 4xx status code +func (o *GetMessageStatisticOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get message statistic o k response has a 5xx status code +func (o *GetMessageStatisticOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get message statistic o k response a status code equal to that given +func (o *GetMessageStatisticOK) IsCode(code int) bool { + return code == 200 +} + +func (o *GetMessageStatisticOK) Error() string { + return fmt.Sprintf("[GET /messages/statistic][%d] getMessageStatisticOK %+v", 200, o.Payload) +} + +func (o *GetMessageStatisticOK) String() string { + return fmt.Sprintf("[GET /messages/statistic][%d] getMessageStatisticOK %+v", 200, o.Payload) +} + +func (o *GetMessageStatisticOK) GetPayload() *GetMessageStatisticOKBody { + return o.Payload +} + +func (o *GetMessageStatisticOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageStatisticOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetMessageStatisticDefault creates a GetMessageStatisticDefault with default headers values +func NewGetMessageStatisticDefault(code int) *GetMessageStatisticDefault { + return &GetMessageStatisticDefault{ + _statusCode: code, + } +} + +/* GetMessageStatisticDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type GetMessageStatisticDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageStatisticDefaultBody +} + +// Code gets the status code for the get message statistic default response +func (o *GetMessageStatisticDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this get message statistic default response has a 2xx status code +func (o *GetMessageStatisticDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get message statistic default response has a 3xx status code +func (o *GetMessageStatisticDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get message statistic default response has a 4xx status code +func (o *GetMessageStatisticDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get message statistic default response has a 5xx status code +func (o *GetMessageStatisticDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get message statistic default response a status code equal to that given +func (o *GetMessageStatisticDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *GetMessageStatisticDefault) Error() string { + return fmt.Sprintf("[GET /messages/statistic][%d] getMessageStatistic default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageStatisticDefault) String() string { + return fmt.Sprintf("[GET /messages/statistic][%d] getMessageStatistic default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageStatisticDefault) GetPayload() *GetMessageStatisticDefaultBody { + return o.Payload +} + +func (o *GetMessageStatisticDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageStatisticDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*GetMessageStatisticDefaultBody get message statistic default body +swagger:model GetMessageStatisticDefaultBody +*/ +type GetMessageStatisticDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this get message statistic default body +func (o *GetMessageStatisticDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageStatisticDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("getMessageStatistic default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *GetMessageStatisticDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("getMessageStatistic default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageStatistic default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageStatistic default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message statistic default body based on the context it is used +func (o *GetMessageStatisticDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageStatisticDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageStatistic default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageStatistic default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageStatisticDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageStatisticDefaultBody) UnmarshalBinary(b []byte) error { + var res GetMessageStatisticDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*GetMessageStatisticOKBody get message statistic o k body +swagger:model GetMessageStatisticOKBody +*/ +type GetMessageStatisticOKBody struct { + + // result + Result *models.MessageStatistic `json:"result,omitempty"` +} + +// Validate validates this get message statistic o k body +func (o *GetMessageStatisticOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageStatisticOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageStatisticOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageStatisticOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message statistic o k body based on the context it is used +func (o *GetMessageStatisticOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageStatisticOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageStatisticOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageStatisticOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageStatisticOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageStatisticOKBody) UnmarshalBinary(b []byte) error { + var res GetMessageStatisticOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_types_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_types_parameters.go new file mode 100644 index 0000000..47c011c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_types_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetMessageTypesParams creates a new GetMessageTypesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetMessageTypesParams() *GetMessageTypesParams { + return &GetMessageTypesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetMessageTypesParamsWithTimeout creates a new GetMessageTypesParams object +// with the ability to set a timeout on a request. +func NewGetMessageTypesParamsWithTimeout(timeout time.Duration) *GetMessageTypesParams { + return &GetMessageTypesParams{ + timeout: timeout, + } +} + +// NewGetMessageTypesParamsWithContext creates a new GetMessageTypesParams object +// with the ability to set a context for a request. +func NewGetMessageTypesParamsWithContext(ctx context.Context) *GetMessageTypesParams { + return &GetMessageTypesParams{ + Context: ctx, + } +} + +// NewGetMessageTypesParamsWithHTTPClient creates a new GetMessageTypesParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetMessageTypesParamsWithHTTPClient(client *http.Client) *GetMessageTypesParams { + return &GetMessageTypesParams{ + HTTPClient: client, + } +} + +/* GetMessageTypesParams contains all the parameters to send to the API endpoint + for the get message types operation. + + Typically these are written to a http.Request. +*/ +type GetMessageTypesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get message types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageTypesParams) WithDefaults() *GetMessageTypesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get message types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMessageTypesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get message types params +func (o *GetMessageTypesParams) WithTimeout(timeout time.Duration) *GetMessageTypesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get message types params +func (o *GetMessageTypesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get message types params +func (o *GetMessageTypesParams) WithContext(ctx context.Context) *GetMessageTypesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get message types params +func (o *GetMessageTypesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get message types params +func (o *GetMessageTypesParams) WithHTTPClient(client *http.Client) *GetMessageTypesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get message types params +func (o *GetMessageTypesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the get message types params +func (o *GetMessageTypesParams) WithAuthorization(authorization string) *GetMessageTypesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the get message types params +func (o *GetMessageTypesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the get message types params +func (o *GetMessageTypesParams) WithBmpLanguage(bmpLanguage *string) *GetMessageTypesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the get message types params +func (o *GetMessageTypesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the get message types params +func (o *GetMessageTypesParams) WithBmpUserID(bmpUserID *string) *GetMessageTypesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the get message types params +func (o *GetMessageTypesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the get message types params +func (o *GetMessageTypesParams) WithTraceID(traceID string) *GetMessageTypesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the get message types params +func (o *GetMessageTypesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetMessageTypesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_types_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_types_responses.go new file mode 100644 index 0000000..ccc9451 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/get_message_types_responses.go @@ -0,0 +1,401 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// GetMessageTypesReader is a Reader for the GetMessageTypes structure. +type GetMessageTypesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetMessageTypesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetMessageTypesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetMessageTypesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetMessageTypesOK creates a GetMessageTypesOK with default headers values +func NewGetMessageTypesOK() *GetMessageTypesOK { + return &GetMessageTypesOK{} +} + +/* GetMessageTypesOK describes a response with status code 200, with default header values. + +GetMessageTypesOK get message types o k +*/ +type GetMessageTypesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageTypesOKBody +} + +// IsSuccess returns true when this get message types o k response has a 2xx status code +func (o *GetMessageTypesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get message types o k response has a 3xx status code +func (o *GetMessageTypesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get message types o k response has a 4xx status code +func (o *GetMessageTypesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get message types o k response has a 5xx status code +func (o *GetMessageTypesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get message types o k response a status code equal to that given +func (o *GetMessageTypesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *GetMessageTypesOK) Error() string { + return fmt.Sprintf("[GET /messages/getMessageTypes][%d] getMessageTypesOK %+v", 200, o.Payload) +} + +func (o *GetMessageTypesOK) String() string { + return fmt.Sprintf("[GET /messages/getMessageTypes][%d] getMessageTypesOK %+v", 200, o.Payload) +} + +func (o *GetMessageTypesOK) GetPayload() *GetMessageTypesOKBody { + return o.Payload +} + +func (o *GetMessageTypesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageTypesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetMessageTypesDefault creates a GetMessageTypesDefault with default headers values +func NewGetMessageTypesDefault(code int) *GetMessageTypesDefault { + return &GetMessageTypesDefault{ + _statusCode: code, + } +} + +/* GetMessageTypesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type GetMessageTypesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMessageTypesDefaultBody +} + +// Code gets the status code for the get message types default response +func (o *GetMessageTypesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this get message types default response has a 2xx status code +func (o *GetMessageTypesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get message types default response has a 3xx status code +func (o *GetMessageTypesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get message types default response has a 4xx status code +func (o *GetMessageTypesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get message types default response has a 5xx status code +func (o *GetMessageTypesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get message types default response a status code equal to that given +func (o *GetMessageTypesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *GetMessageTypesDefault) Error() string { + return fmt.Sprintf("[GET /messages/getMessageTypes][%d] getMessageTypes default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageTypesDefault) String() string { + return fmt.Sprintf("[GET /messages/getMessageTypes][%d] getMessageTypes default %+v", o._statusCode, o.Payload) +} + +func (o *GetMessageTypesDefault) GetPayload() *GetMessageTypesDefaultBody { + return o.Payload +} + +func (o *GetMessageTypesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMessageTypesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*GetMessageTypesDefaultBody get message types default body +swagger:model GetMessageTypesDefaultBody +*/ +type GetMessageTypesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this get message types default body +func (o *GetMessageTypesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageTypesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("getMessageTypes default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *GetMessageTypesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("getMessageTypes default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message types default body based on the context it is used +func (o *GetMessageTypesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageTypesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageTypesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageTypesDefaultBody) UnmarshalBinary(b []byte) error { + var res GetMessageTypesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*GetMessageTypesOKBody get message types o k body +swagger:model GetMessageTypesOKBody +*/ +type GetMessageTypesOKBody struct { + + // result + Result models.MessageTypesResp `json:"result,omitempty"` +} + +// Validate validates this get message types o k body +func (o *GetMessageTypesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageTypesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageTypesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get message types o k body based on the context it is used +func (o *GetMessageTypesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMessageTypesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMessageTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMessageTypesOK" + "." + "result") + } + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMessageTypesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMessageTypesOKBody) UnmarshalBinary(b []byte) error { + var res GetMessageTypesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/has_unread_message_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/has_unread_message_parameters.go new file mode 100644 index 0000000..574dec2 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/has_unread_message_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewHasUnreadMessageParams creates a new HasUnreadMessageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewHasUnreadMessageParams() *HasUnreadMessageParams { + return &HasUnreadMessageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewHasUnreadMessageParamsWithTimeout creates a new HasUnreadMessageParams object +// with the ability to set a timeout on a request. +func NewHasUnreadMessageParamsWithTimeout(timeout time.Duration) *HasUnreadMessageParams { + return &HasUnreadMessageParams{ + timeout: timeout, + } +} + +// NewHasUnreadMessageParamsWithContext creates a new HasUnreadMessageParams object +// with the ability to set a context for a request. +func NewHasUnreadMessageParamsWithContext(ctx context.Context) *HasUnreadMessageParams { + return &HasUnreadMessageParams{ + Context: ctx, + } +} + +// NewHasUnreadMessageParamsWithHTTPClient creates a new HasUnreadMessageParams object +// with the ability to set a custom HTTPClient for a request. +func NewHasUnreadMessageParamsWithHTTPClient(client *http.Client) *HasUnreadMessageParams { + return &HasUnreadMessageParams{ + HTTPClient: client, + } +} + +/* HasUnreadMessageParams contains all the parameters to send to the API endpoint + for the has unread message operation. + + Typically these are written to a http.Request. +*/ +type HasUnreadMessageParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the has unread message params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *HasUnreadMessageParams) WithDefaults() *HasUnreadMessageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the has unread message params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *HasUnreadMessageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the has unread message params +func (o *HasUnreadMessageParams) WithTimeout(timeout time.Duration) *HasUnreadMessageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the has unread message params +func (o *HasUnreadMessageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the has unread message params +func (o *HasUnreadMessageParams) WithContext(ctx context.Context) *HasUnreadMessageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the has unread message params +func (o *HasUnreadMessageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the has unread message params +func (o *HasUnreadMessageParams) WithHTTPClient(client *http.Client) *HasUnreadMessageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the has unread message params +func (o *HasUnreadMessageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the has unread message params +func (o *HasUnreadMessageParams) WithAuthorization(authorization string) *HasUnreadMessageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the has unread message params +func (o *HasUnreadMessageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the has unread message params +func (o *HasUnreadMessageParams) WithBmpLanguage(bmpLanguage *string) *HasUnreadMessageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the has unread message params +func (o *HasUnreadMessageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the has unread message params +func (o *HasUnreadMessageParams) WithBmpUserID(bmpUserID *string) *HasUnreadMessageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the has unread message params +func (o *HasUnreadMessageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the has unread message params +func (o *HasUnreadMessageParams) WithTraceID(traceID string) *HasUnreadMessageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the has unread message params +func (o *HasUnreadMessageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *HasUnreadMessageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/has_unread_message_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/has_unread_message_responses.go new file mode 100644 index 0000000..f2d87df --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/has_unread_message_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// HasUnreadMessageReader is a Reader for the HasUnreadMessage structure. +type HasUnreadMessageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *HasUnreadMessageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewHasUnreadMessageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewHasUnreadMessageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewHasUnreadMessageOK creates a HasUnreadMessageOK with default headers values +func NewHasUnreadMessageOK() *HasUnreadMessageOK { + return &HasUnreadMessageOK{} +} + +/* HasUnreadMessageOK describes a response with status code 200, with default header values. + +HasUnreadMessageOK has unread message o k +*/ +type HasUnreadMessageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *HasUnreadMessageOKBody +} + +// IsSuccess returns true when this has unread message o k response has a 2xx status code +func (o *HasUnreadMessageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this has unread message o k response has a 3xx status code +func (o *HasUnreadMessageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this has unread message o k response has a 4xx status code +func (o *HasUnreadMessageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this has unread message o k response has a 5xx status code +func (o *HasUnreadMessageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this has unread message o k response a status code equal to that given +func (o *HasUnreadMessageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *HasUnreadMessageOK) Error() string { + return fmt.Sprintf("[GET /messages/hasUnreadMessage][%d] hasUnreadMessageOK %+v", 200, o.Payload) +} + +func (o *HasUnreadMessageOK) String() string { + return fmt.Sprintf("[GET /messages/hasUnreadMessage][%d] hasUnreadMessageOK %+v", 200, o.Payload) +} + +func (o *HasUnreadMessageOK) GetPayload() *HasUnreadMessageOKBody { + return o.Payload +} + +func (o *HasUnreadMessageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(HasUnreadMessageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewHasUnreadMessageDefault creates a HasUnreadMessageDefault with default headers values +func NewHasUnreadMessageDefault(code int) *HasUnreadMessageDefault { + return &HasUnreadMessageDefault{ + _statusCode: code, + } +} + +/* HasUnreadMessageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type HasUnreadMessageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *HasUnreadMessageDefaultBody +} + +// Code gets the status code for the has unread message default response +func (o *HasUnreadMessageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this has unread message default response has a 2xx status code +func (o *HasUnreadMessageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this has unread message default response has a 3xx status code +func (o *HasUnreadMessageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this has unread message default response has a 4xx status code +func (o *HasUnreadMessageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this has unread message default response has a 5xx status code +func (o *HasUnreadMessageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this has unread message default response a status code equal to that given +func (o *HasUnreadMessageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *HasUnreadMessageDefault) Error() string { + return fmt.Sprintf("[GET /messages/hasUnreadMessage][%d] hasUnreadMessage default %+v", o._statusCode, o.Payload) +} + +func (o *HasUnreadMessageDefault) String() string { + return fmt.Sprintf("[GET /messages/hasUnreadMessage][%d] hasUnreadMessage default %+v", o._statusCode, o.Payload) +} + +func (o *HasUnreadMessageDefault) GetPayload() *HasUnreadMessageDefaultBody { + return o.Payload +} + +func (o *HasUnreadMessageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(HasUnreadMessageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*HasUnreadMessageDefaultBody has unread message default body +swagger:model HasUnreadMessageDefaultBody +*/ +type HasUnreadMessageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this has unread message default body +func (o *HasUnreadMessageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *HasUnreadMessageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("hasUnreadMessage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *HasUnreadMessageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("hasUnreadMessage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("hasUnreadMessage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("hasUnreadMessage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this has unread message default body based on the context it is used +func (o *HasUnreadMessageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *HasUnreadMessageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("hasUnreadMessage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("hasUnreadMessage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *HasUnreadMessageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *HasUnreadMessageDefaultBody) UnmarshalBinary(b []byte) error { + var res HasUnreadMessageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*HasUnreadMessageOKBody has unread message o k body +swagger:model HasUnreadMessageOKBody +*/ +type HasUnreadMessageOKBody struct { + + // result + Result *models.HasUnreadMessage `json:"result,omitempty"` +} + +// Validate validates this has unread message o k body +func (o *HasUnreadMessageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *HasUnreadMessageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("hasUnreadMessageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("hasUnreadMessageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this has unread message o k body based on the context it is used +func (o *HasUnreadMessageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *HasUnreadMessageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("hasUnreadMessageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("hasUnreadMessageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *HasUnreadMessageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *HasUnreadMessageOKBody) UnmarshalBinary(b []byte) error { + var res HasUnreadMessageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/mail_detail_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/mail_detail_parameters.go new file mode 100644 index 0000000..0e3232b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/mail_detail_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewMailDetailParams creates a new MailDetailParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewMailDetailParams() *MailDetailParams { + return &MailDetailParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewMailDetailParamsWithTimeout creates a new MailDetailParams object +// with the ability to set a timeout on a request. +func NewMailDetailParamsWithTimeout(timeout time.Duration) *MailDetailParams { + return &MailDetailParams{ + timeout: timeout, + } +} + +// NewMailDetailParamsWithContext creates a new MailDetailParams object +// with the ability to set a context for a request. +func NewMailDetailParamsWithContext(ctx context.Context) *MailDetailParams { + return &MailDetailParams{ + Context: ctx, + } +} + +// NewMailDetailParamsWithHTTPClient creates a new MailDetailParams object +// with the ability to set a custom HTTPClient for a request. +func NewMailDetailParamsWithHTTPClient(client *http.Client) *MailDetailParams { + return &MailDetailParams{ + HTTPClient: client, + } +} + +/* MailDetailParams contains all the parameters to send to the API endpoint + for the mail detail operation. + + Typically these are written to a http.Request. +*/ +type MailDetailParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the mail detail params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *MailDetailParams) WithDefaults() *MailDetailParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the mail detail params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *MailDetailParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the mail detail params +func (o *MailDetailParams) WithTimeout(timeout time.Duration) *MailDetailParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the mail detail params +func (o *MailDetailParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the mail detail params +func (o *MailDetailParams) WithContext(ctx context.Context) *MailDetailParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the mail detail params +func (o *MailDetailParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the mail detail params +func (o *MailDetailParams) WithHTTPClient(client *http.Client) *MailDetailParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the mail detail params +func (o *MailDetailParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the mail detail params +func (o *MailDetailParams) WithAuthorization(authorization string) *MailDetailParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the mail detail params +func (o *MailDetailParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the mail detail params +func (o *MailDetailParams) WithBmpLanguage(bmpLanguage *string) *MailDetailParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the mail detail params +func (o *MailDetailParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the mail detail params +func (o *MailDetailParams) WithBmpUserID(bmpUserID *string) *MailDetailParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the mail detail params +func (o *MailDetailParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the mail detail params +func (o *MailDetailParams) WithTraceID(traceID string) *MailDetailParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the mail detail params +func (o *MailDetailParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *MailDetailParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/mail_detail_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/mail_detail_responses.go new file mode 100644 index 0000000..9508e49 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/mail_detail_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// MailDetailReader is a Reader for the MailDetail structure. +type MailDetailReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *MailDetailReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewMailDetailOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewMailDetailDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewMailDetailOK creates a MailDetailOK with default headers values +func NewMailDetailOK() *MailDetailOK { + return &MailDetailOK{} +} + +/* MailDetailOK describes a response with status code 200, with default header values. + +MailDetailOK mail detail o k +*/ +type MailDetailOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *MailDetailOKBody +} + +// IsSuccess returns true when this mail detail o k response has a 2xx status code +func (o *MailDetailOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this mail detail o k response has a 3xx status code +func (o *MailDetailOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this mail detail o k response has a 4xx status code +func (o *MailDetailOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this mail detail o k response has a 5xx status code +func (o *MailDetailOK) IsServerError() bool { + return false +} + +// IsCode returns true when this mail detail o k response a status code equal to that given +func (o *MailDetailOK) IsCode(code int) bool { + return code == 200 +} + +func (o *MailDetailOK) Error() string { + return fmt.Sprintf("[GET /messages/mailDetail][%d] mailDetailOK %+v", 200, o.Payload) +} + +func (o *MailDetailOK) String() string { + return fmt.Sprintf("[GET /messages/mailDetail][%d] mailDetailOK %+v", 200, o.Payload) +} + +func (o *MailDetailOK) GetPayload() *MailDetailOKBody { + return o.Payload +} + +func (o *MailDetailOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(MailDetailOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewMailDetailDefault creates a MailDetailDefault with default headers values +func NewMailDetailDefault(code int) *MailDetailDefault { + return &MailDetailDefault{ + _statusCode: code, + } +} + +/* MailDetailDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type MailDetailDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *MailDetailDefaultBody +} + +// Code gets the status code for the mail detail default response +func (o *MailDetailDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this mail detail default response has a 2xx status code +func (o *MailDetailDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this mail detail default response has a 3xx status code +func (o *MailDetailDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this mail detail default response has a 4xx status code +func (o *MailDetailDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this mail detail default response has a 5xx status code +func (o *MailDetailDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this mail detail default response a status code equal to that given +func (o *MailDetailDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *MailDetailDefault) Error() string { + return fmt.Sprintf("[GET /messages/mailDetail][%d] mailDetail default %+v", o._statusCode, o.Payload) +} + +func (o *MailDetailDefault) String() string { + return fmt.Sprintf("[GET /messages/mailDetail][%d] mailDetail default %+v", o._statusCode, o.Payload) +} + +func (o *MailDetailDefault) GetPayload() *MailDetailDefaultBody { + return o.Payload +} + +func (o *MailDetailDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(MailDetailDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*MailDetailDefaultBody mail detail default body +swagger:model MailDetailDefaultBody +*/ +type MailDetailDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this mail detail default body +func (o *MailDetailDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MailDetailDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("mailDetail default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *MailDetailDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("mailDetail default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("mailDetail default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("mailDetail default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this mail detail default body based on the context it is used +func (o *MailDetailDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MailDetailDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("mailDetail default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("mailDetail default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *MailDetailDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *MailDetailDefaultBody) UnmarshalBinary(b []byte) error { + var res MailDetailDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*MailDetailOKBody mail detail o k body +swagger:model MailDetailOKBody +*/ +type MailDetailOKBody struct { + + // result + Result *models.Mail `json:"result,omitempty"` +} + +// Validate validates this mail detail o k body +func (o *MailDetailOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MailDetailOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("mailDetailOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("mailDetailOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this mail detail o k body based on the context it is used +func (o *MailDetailOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MailDetailOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("mailDetailOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("mailDetailOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *MailDetailOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *MailDetailOKBody) UnmarshalBinary(b []byte) error { + var res MailDetailOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/message_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/message_client.go new file mode 100644 index 0000000..f932ac2 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/message_client.go @@ -0,0 +1,437 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new message API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for message API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DeleteMessage(params *DeleteMessageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteMessageOK, error) + + DialMail(params *DialMailParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DialMailOK, error) + + GetMessageByID(params *GetMessageByIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageByIDOK, error) + + GetMessageList(params *GetMessageListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageListOK, error) + + GetMessageStatistic(params *GetMessageStatisticParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageStatisticOK, error) + + GetMessageTypes(params *GetMessageTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageTypesOK, error) + + HasUnreadMessage(params *HasUnreadMessageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*HasUnreadMessageOK, error) + + MailDetail(params *MailDetailParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*MailDetailOK, error) + + ReadMessage(params *ReadMessageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ReadMessageOK, error) + + SaveIsPushMail(params *SaveIsPushMailParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*SaveIsPushMailOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DeleteMessage DeleteMessage 删除消息(可多条) +*/ +func (a *Client) DeleteMessage(params *DeleteMessageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteMessageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteMessageParams() + } + op := &runtime.ClientOperation{ + ID: "deleteMessage", + Method: "DELETE", + PathPattern: "/messages/delete", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteMessageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteMessageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteMessageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DialMail DialMail 测试邮箱设置是否正确 +*/ +func (a *Client) DialMail(params *DialMailParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DialMailOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDialMailParams() + } + op := &runtime.ClientOperation{ + ID: "dialMail", + Method: "POST", + PathPattern: "/messages/dialMail", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DialMailReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DialMailOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DialMailDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + GetMessageByID GetMessageById 获取消息详情,包括上一条/下一条的messageid +*/ +func (a *Client) GetMessageByID(params *GetMessageByIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageByIDOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetMessageByIDParams() + } + op := &runtime.ClientOperation{ + ID: "getMessageById", + Method: "GET", + PathPattern: "/messages/getMessageById", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetMessageByIDReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetMessageByIDOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetMessageByIDDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + GetMessageList GetMessageList 获取message列表(分页) +*/ +func (a *Client) GetMessageList(params *GetMessageListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetMessageListParams() + } + op := &runtime.ClientOperation{ + ID: "getMessageList", + Method: "GET", + PathPattern: "/messages", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetMessageListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetMessageListOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetMessageListDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + GetMessageStatistic GetMessageStatistic 获取message总数和未读数 +*/ +func (a *Client) GetMessageStatistic(params *GetMessageStatisticParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageStatisticOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetMessageStatisticParams() + } + op := &runtime.ClientOperation{ + ID: "getMessageStatistic", + Method: "GET", + PathPattern: "/messages/statistic", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetMessageStatisticReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetMessageStatisticOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetMessageStatisticDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + GetMessageTypes GetMessageTypes 获取消息类型/子类型 +*/ +func (a *Client) GetMessageTypes(params *GetMessageTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMessageTypesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetMessageTypesParams() + } + op := &runtime.ClientOperation{ + ID: "getMessageTypes", + Method: "GET", + PathPattern: "/messages/getMessageTypes", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetMessageTypesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetMessageTypesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetMessageTypesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + HasUnreadMessage HasUnreadMessage 获取有没有未读消息 +*/ +func (a *Client) HasUnreadMessage(params *HasUnreadMessageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*HasUnreadMessageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewHasUnreadMessageParams() + } + op := &runtime.ClientOperation{ + ID: "hasUnreadMessage", + Method: "GET", + PathPattern: "/messages/hasUnreadMessage", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &HasUnreadMessageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*HasUnreadMessageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*HasUnreadMessageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + MailDetail MailDetail 获取邮箱设置 +*/ +func (a *Client) MailDetail(params *MailDetailParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*MailDetailOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewMailDetailParams() + } + op := &runtime.ClientOperation{ + ID: "mailDetail", + Method: "GET", + PathPattern: "/messages/mailDetail", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &MailDetailReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*MailDetailOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*MailDetailDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ReadMessage ReadMessage 将消息设置为已读(可多条) +*/ +func (a *Client) ReadMessage(params *ReadMessageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ReadMessageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewReadMessageParams() + } + op := &runtime.ClientOperation{ + ID: "readMessage", + Method: "PUT", + PathPattern: "/messages/doRead", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ReadMessageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ReadMessageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ReadMessageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + SaveIsPushMail SaveIsPushMail 保存邮箱是否通知的设置 +*/ +func (a *Client) SaveIsPushMail(params *SaveIsPushMailParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*SaveIsPushMailOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewSaveIsPushMailParams() + } + op := &runtime.ClientOperation{ + ID: "saveIsPushMail", + Method: "POST", + PathPattern: "/messages/saveIsPushMail", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &SaveIsPushMailReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*SaveIsPushMailOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*SaveIsPushMailDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/read_message_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/read_message_parameters.go new file mode 100644 index 0000000..50aa9d9 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/read_message_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewReadMessageParams creates a new ReadMessageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewReadMessageParams() *ReadMessageParams { + return &ReadMessageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewReadMessageParamsWithTimeout creates a new ReadMessageParams object +// with the ability to set a timeout on a request. +func NewReadMessageParamsWithTimeout(timeout time.Duration) *ReadMessageParams { + return &ReadMessageParams{ + timeout: timeout, + } +} + +// NewReadMessageParamsWithContext creates a new ReadMessageParams object +// with the ability to set a context for a request. +func NewReadMessageParamsWithContext(ctx context.Context) *ReadMessageParams { + return &ReadMessageParams{ + Context: ctx, + } +} + +// NewReadMessageParamsWithHTTPClient creates a new ReadMessageParams object +// with the ability to set a custom HTTPClient for a request. +func NewReadMessageParamsWithHTTPClient(client *http.Client) *ReadMessageParams { + return &ReadMessageParams{ + HTTPClient: client, + } +} + +/* ReadMessageParams contains all the parameters to send to the API endpoint + for the read message operation. + + Typically these are written to a http.Request. +*/ +type ReadMessageParams struct { + + // Body. + Body *models.ReadMessagesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the read message params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ReadMessageParams) WithDefaults() *ReadMessageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the read message params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ReadMessageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the read message params +func (o *ReadMessageParams) WithTimeout(timeout time.Duration) *ReadMessageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the read message params +func (o *ReadMessageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the read message params +func (o *ReadMessageParams) WithContext(ctx context.Context) *ReadMessageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the read message params +func (o *ReadMessageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the read message params +func (o *ReadMessageParams) WithHTTPClient(client *http.Client) *ReadMessageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the read message params +func (o *ReadMessageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the read message params +func (o *ReadMessageParams) WithBody(body *models.ReadMessagesRequest) *ReadMessageParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the read message params +func (o *ReadMessageParams) SetBody(body *models.ReadMessagesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the read message params +func (o *ReadMessageParams) WithAuthorization(authorization string) *ReadMessageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the read message params +func (o *ReadMessageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the read message params +func (o *ReadMessageParams) WithBmpLanguage(bmpLanguage *string) *ReadMessageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the read message params +func (o *ReadMessageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the read message params +func (o *ReadMessageParams) WithBmpUserID(bmpUserID *string) *ReadMessageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the read message params +func (o *ReadMessageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the read message params +func (o *ReadMessageParams) WithTraceID(traceID string) *ReadMessageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the read message params +func (o *ReadMessageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ReadMessageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/read_message_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/read_message_responses.go new file mode 100644 index 0000000..fa170e5 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/read_message_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ReadMessageReader is a Reader for the ReadMessage structure. +type ReadMessageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ReadMessageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewReadMessageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewReadMessageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewReadMessageOK creates a ReadMessageOK with default headers values +func NewReadMessageOK() *ReadMessageOK { + return &ReadMessageOK{} +} + +/* ReadMessageOK describes a response with status code 200, with default header values. + +A ReadMessageResult is an response struct +*/ +type ReadMessageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ReadMessageOKBody +} + +// IsSuccess returns true when this read message o k response has a 2xx status code +func (o *ReadMessageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this read message o k response has a 3xx status code +func (o *ReadMessageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this read message o k response has a 4xx status code +func (o *ReadMessageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this read message o k response has a 5xx status code +func (o *ReadMessageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this read message o k response a status code equal to that given +func (o *ReadMessageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ReadMessageOK) Error() string { + return fmt.Sprintf("[PUT /messages/doRead][%d] readMessageOK %+v", 200, o.Payload) +} + +func (o *ReadMessageOK) String() string { + return fmt.Sprintf("[PUT /messages/doRead][%d] readMessageOK %+v", 200, o.Payload) +} + +func (o *ReadMessageOK) GetPayload() *ReadMessageOKBody { + return o.Payload +} + +func (o *ReadMessageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ReadMessageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewReadMessageDefault creates a ReadMessageDefault with default headers values +func NewReadMessageDefault(code int) *ReadMessageDefault { + return &ReadMessageDefault{ + _statusCode: code, + } +} + +/* ReadMessageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ReadMessageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ReadMessageDefaultBody +} + +// Code gets the status code for the read message default response +func (o *ReadMessageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this read message default response has a 2xx status code +func (o *ReadMessageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this read message default response has a 3xx status code +func (o *ReadMessageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this read message default response has a 4xx status code +func (o *ReadMessageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this read message default response has a 5xx status code +func (o *ReadMessageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this read message default response a status code equal to that given +func (o *ReadMessageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ReadMessageDefault) Error() string { + return fmt.Sprintf("[PUT /messages/doRead][%d] readMessage default %+v", o._statusCode, o.Payload) +} + +func (o *ReadMessageDefault) String() string { + return fmt.Sprintf("[PUT /messages/doRead][%d] readMessage default %+v", o._statusCode, o.Payload) +} + +func (o *ReadMessageDefault) GetPayload() *ReadMessageDefaultBody { + return o.Payload +} + +func (o *ReadMessageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ReadMessageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ReadMessageDefaultBody read message default body +swagger:model ReadMessageDefaultBody +*/ +type ReadMessageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this read message default body +func (o *ReadMessageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReadMessageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("readMessage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ReadMessageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("readMessage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("readMessage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("readMessage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this read message default body based on the context it is used +func (o *ReadMessageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReadMessageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("readMessage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("readMessage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ReadMessageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ReadMessageDefaultBody) UnmarshalBinary(b []byte) error { + var res ReadMessageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ReadMessageOKBody read message o k body +swagger:model ReadMessageOKBody +*/ +type ReadMessageOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this read message o k body +func (o *ReadMessageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReadMessageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("readMessageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("readMessageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this read message o k body based on the context it is used +func (o *ReadMessageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReadMessageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("readMessageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("readMessageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ReadMessageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ReadMessageOKBody) UnmarshalBinary(b []byte) error { + var res ReadMessageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/save_is_push_mail_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/save_is_push_mail_parameters.go new file mode 100644 index 0000000..f544951 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/save_is_push_mail_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewSaveIsPushMailParams creates a new SaveIsPushMailParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewSaveIsPushMailParams() *SaveIsPushMailParams { + return &SaveIsPushMailParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewSaveIsPushMailParamsWithTimeout creates a new SaveIsPushMailParams object +// with the ability to set a timeout on a request. +func NewSaveIsPushMailParamsWithTimeout(timeout time.Duration) *SaveIsPushMailParams { + return &SaveIsPushMailParams{ + timeout: timeout, + } +} + +// NewSaveIsPushMailParamsWithContext creates a new SaveIsPushMailParams object +// with the ability to set a context for a request. +func NewSaveIsPushMailParamsWithContext(ctx context.Context) *SaveIsPushMailParams { + return &SaveIsPushMailParams{ + Context: ctx, + } +} + +// NewSaveIsPushMailParamsWithHTTPClient creates a new SaveIsPushMailParams object +// with the ability to set a custom HTTPClient for a request. +func NewSaveIsPushMailParamsWithHTTPClient(client *http.Client) *SaveIsPushMailParams { + return &SaveIsPushMailParams{ + HTTPClient: client, + } +} + +/* SaveIsPushMailParams contains all the parameters to send to the API endpoint + for the save is push mail operation. + + Typically these are written to a http.Request. +*/ +type SaveIsPushMailParams struct { + + // Body. + Body *models.SaveIsPushMailRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the save is push mail params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *SaveIsPushMailParams) WithDefaults() *SaveIsPushMailParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the save is push mail params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *SaveIsPushMailParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the save is push mail params +func (o *SaveIsPushMailParams) WithTimeout(timeout time.Duration) *SaveIsPushMailParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the save is push mail params +func (o *SaveIsPushMailParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the save is push mail params +func (o *SaveIsPushMailParams) WithContext(ctx context.Context) *SaveIsPushMailParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the save is push mail params +func (o *SaveIsPushMailParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the save is push mail params +func (o *SaveIsPushMailParams) WithHTTPClient(client *http.Client) *SaveIsPushMailParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the save is push mail params +func (o *SaveIsPushMailParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the save is push mail params +func (o *SaveIsPushMailParams) WithBody(body *models.SaveIsPushMailRequest) *SaveIsPushMailParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the save is push mail params +func (o *SaveIsPushMailParams) SetBody(body *models.SaveIsPushMailRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the save is push mail params +func (o *SaveIsPushMailParams) WithAuthorization(authorization string) *SaveIsPushMailParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the save is push mail params +func (o *SaveIsPushMailParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the save is push mail params +func (o *SaveIsPushMailParams) WithBmpLanguage(bmpLanguage *string) *SaveIsPushMailParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the save is push mail params +func (o *SaveIsPushMailParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the save is push mail params +func (o *SaveIsPushMailParams) WithBmpUserID(bmpUserID *string) *SaveIsPushMailParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the save is push mail params +func (o *SaveIsPushMailParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the save is push mail params +func (o *SaveIsPushMailParams) WithTraceID(traceID string) *SaveIsPushMailParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the save is push mail params +func (o *SaveIsPushMailParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *SaveIsPushMailParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/save_is_push_mail_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/save_is_push_mail_responses.go new file mode 100644 index 0000000..048eb5b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/message/save_is_push_mail_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package message + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// SaveIsPushMailReader is a Reader for the SaveIsPushMail structure. +type SaveIsPushMailReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *SaveIsPushMailReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewSaveIsPushMailOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewSaveIsPushMailDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewSaveIsPushMailOK creates a SaveIsPushMailOK with default headers values +func NewSaveIsPushMailOK() *SaveIsPushMailOK { + return &SaveIsPushMailOK{} +} + +/* SaveIsPushMailOK describes a response with status code 200, with default header values. + +A SaveIsPushMailResult is an response struct +*/ +type SaveIsPushMailOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *SaveIsPushMailOKBody +} + +// IsSuccess returns true when this save is push mail o k response has a 2xx status code +func (o *SaveIsPushMailOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this save is push mail o k response has a 3xx status code +func (o *SaveIsPushMailOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this save is push mail o k response has a 4xx status code +func (o *SaveIsPushMailOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this save is push mail o k response has a 5xx status code +func (o *SaveIsPushMailOK) IsServerError() bool { + return false +} + +// IsCode returns true when this save is push mail o k response a status code equal to that given +func (o *SaveIsPushMailOK) IsCode(code int) bool { + return code == 200 +} + +func (o *SaveIsPushMailOK) Error() string { + return fmt.Sprintf("[POST /messages/saveIsPushMail][%d] saveIsPushMailOK %+v", 200, o.Payload) +} + +func (o *SaveIsPushMailOK) String() string { + return fmt.Sprintf("[POST /messages/saveIsPushMail][%d] saveIsPushMailOK %+v", 200, o.Payload) +} + +func (o *SaveIsPushMailOK) GetPayload() *SaveIsPushMailOKBody { + return o.Payload +} + +func (o *SaveIsPushMailOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(SaveIsPushMailOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewSaveIsPushMailDefault creates a SaveIsPushMailDefault with default headers values +func NewSaveIsPushMailDefault(code int) *SaveIsPushMailDefault { + return &SaveIsPushMailDefault{ + _statusCode: code, + } +} + +/* SaveIsPushMailDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type SaveIsPushMailDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *SaveIsPushMailDefaultBody +} + +// Code gets the status code for the save is push mail default response +func (o *SaveIsPushMailDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this save is push mail default response has a 2xx status code +func (o *SaveIsPushMailDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this save is push mail default response has a 3xx status code +func (o *SaveIsPushMailDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this save is push mail default response has a 4xx status code +func (o *SaveIsPushMailDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this save is push mail default response has a 5xx status code +func (o *SaveIsPushMailDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this save is push mail default response a status code equal to that given +func (o *SaveIsPushMailDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *SaveIsPushMailDefault) Error() string { + return fmt.Sprintf("[POST /messages/saveIsPushMail][%d] saveIsPushMail default %+v", o._statusCode, o.Payload) +} + +func (o *SaveIsPushMailDefault) String() string { + return fmt.Sprintf("[POST /messages/saveIsPushMail][%d] saveIsPushMail default %+v", o._statusCode, o.Payload) +} + +func (o *SaveIsPushMailDefault) GetPayload() *SaveIsPushMailDefaultBody { + return o.Payload +} + +func (o *SaveIsPushMailDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(SaveIsPushMailDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*SaveIsPushMailDefaultBody save is push mail default body +swagger:model SaveIsPushMailDefaultBody +*/ +type SaveIsPushMailDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this save is push mail default body +func (o *SaveIsPushMailDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *SaveIsPushMailDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("saveIsPushMail default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *SaveIsPushMailDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("saveIsPushMail default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("saveIsPushMail default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("saveIsPushMail default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this save is push mail default body based on the context it is used +func (o *SaveIsPushMailDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *SaveIsPushMailDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("saveIsPushMail default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("saveIsPushMail default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *SaveIsPushMailDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *SaveIsPushMailDefaultBody) UnmarshalBinary(b []byte) error { + var res SaveIsPushMailDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*SaveIsPushMailOKBody save is push mail o k body +swagger:model SaveIsPushMailOKBody +*/ +type SaveIsPushMailOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this save is push mail o k body +func (o *SaveIsPushMailOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *SaveIsPushMailOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("saveIsPushMailOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("saveIsPushMailOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this save is push mail o k body based on the context it is used +func (o *SaveIsPushMailOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *SaveIsPushMailOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("saveIsPushMailOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("saveIsPushMailOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *SaveIsPushMailOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *SaveIsPushMailOKBody) UnmarshalBinary(b []byte) error { + var res SaveIsPushMailOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/delete_alert_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/delete_alert_parameters.go new file mode 100644 index 0000000..406c2bc --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/delete_alert_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewDeleteAlertParams creates a new DeleteAlertParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteAlertParams() *DeleteAlertParams { + return &DeleteAlertParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteAlertParamsWithTimeout creates a new DeleteAlertParams object +// with the ability to set a timeout on a request. +func NewDeleteAlertParamsWithTimeout(timeout time.Duration) *DeleteAlertParams { + return &DeleteAlertParams{ + timeout: timeout, + } +} + +// NewDeleteAlertParamsWithContext creates a new DeleteAlertParams object +// with the ability to set a context for a request. +func NewDeleteAlertParamsWithContext(ctx context.Context) *DeleteAlertParams { + return &DeleteAlertParams{ + Context: ctx, + } +} + +// NewDeleteAlertParamsWithHTTPClient creates a new DeleteAlertParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteAlertParamsWithHTTPClient(client *http.Client) *DeleteAlertParams { + return &DeleteAlertParams{ + HTTPClient: client, + } +} + +/* DeleteAlertParams contains all the parameters to send to the API endpoint + for the delete alert operation. + + Typically these are written to a http.Request. +*/ +type DeleteAlertParams struct { + + // Body. + Body *models.DeleteAlertRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete alert params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteAlertParams) WithDefaults() *DeleteAlertParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete alert params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteAlertParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete alert params +func (o *DeleteAlertParams) WithTimeout(timeout time.Duration) *DeleteAlertParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete alert params +func (o *DeleteAlertParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete alert params +func (o *DeleteAlertParams) WithContext(ctx context.Context) *DeleteAlertParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete alert params +func (o *DeleteAlertParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete alert params +func (o *DeleteAlertParams) WithHTTPClient(client *http.Client) *DeleteAlertParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete alert params +func (o *DeleteAlertParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the delete alert params +func (o *DeleteAlertParams) WithBody(body *models.DeleteAlertRequest) *DeleteAlertParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the delete alert params +func (o *DeleteAlertParams) SetBody(body *models.DeleteAlertRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the delete alert params +func (o *DeleteAlertParams) WithAuthorization(authorization string) *DeleteAlertParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete alert params +func (o *DeleteAlertParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete alert params +func (o *DeleteAlertParams) WithBmpLanguage(bmpLanguage *string) *DeleteAlertParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete alert params +func (o *DeleteAlertParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete alert params +func (o *DeleteAlertParams) WithBmpUserID(bmpUserID *string) *DeleteAlertParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete alert params +func (o *DeleteAlertParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete alert params +func (o *DeleteAlertParams) WithTraceID(traceID string) *DeleteAlertParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete alert params +func (o *DeleteAlertParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteAlertParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/delete_alert_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/delete_alert_responses.go new file mode 100644 index 0000000..90407b1 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/delete_alert_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteAlertReader is a Reader for the DeleteAlert structure. +type DeleteAlertReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteAlertReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteAlertOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteAlertDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteAlertOK creates a DeleteAlertOK with default headers values +func NewDeleteAlertOK() *DeleteAlertOK { + return &DeleteAlertOK{} +} + +/* DeleteAlertOK describes a response with status code 200, with default header values. + +A DeleteAlertResult is an response struct that is used to describe create alert result. +*/ +type DeleteAlertOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteAlertOKBody +} + +// IsSuccess returns true when this delete alert o k response has a 2xx status code +func (o *DeleteAlertOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete alert o k response has a 3xx status code +func (o *DeleteAlertOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete alert o k response has a 4xx status code +func (o *DeleteAlertOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete alert o k response has a 5xx status code +func (o *DeleteAlertOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete alert o k response a status code equal to that given +func (o *DeleteAlertOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteAlertOK) Error() string { + return fmt.Sprintf("[DELETE /monitorAlert/deleteAlert][%d] deleteAlertOK %+v", 200, o.Payload) +} + +func (o *DeleteAlertOK) String() string { + return fmt.Sprintf("[DELETE /monitorAlert/deleteAlert][%d] deleteAlertOK %+v", 200, o.Payload) +} + +func (o *DeleteAlertOK) GetPayload() *DeleteAlertOKBody { + return o.Payload +} + +func (o *DeleteAlertOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteAlertOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteAlertDefault creates a DeleteAlertDefault with default headers values +func NewDeleteAlertDefault(code int) *DeleteAlertDefault { + return &DeleteAlertDefault{ + _statusCode: code, + } +} + +/* DeleteAlertDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteAlertDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteAlertDefaultBody +} + +// Code gets the status code for the delete alert default response +func (o *DeleteAlertDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete alert default response has a 2xx status code +func (o *DeleteAlertDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete alert default response has a 3xx status code +func (o *DeleteAlertDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete alert default response has a 4xx status code +func (o *DeleteAlertDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete alert default response has a 5xx status code +func (o *DeleteAlertDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete alert default response a status code equal to that given +func (o *DeleteAlertDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteAlertDefault) Error() string { + return fmt.Sprintf("[DELETE /monitorAlert/deleteAlert][%d] deleteAlert default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteAlertDefault) String() string { + return fmt.Sprintf("[DELETE /monitorAlert/deleteAlert][%d] deleteAlert default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteAlertDefault) GetPayload() *DeleteAlertDefaultBody { + return o.Payload +} + +func (o *DeleteAlertDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteAlertDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteAlertDefaultBody delete alert default body +swagger:model DeleteAlertDefaultBody +*/ +type DeleteAlertDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete alert default body +func (o *DeleteAlertDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteAlertDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteAlert default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteAlertDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteAlert default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteAlert default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteAlert default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete alert default body based on the context it is used +func (o *DeleteAlertDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteAlertDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteAlert default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteAlert default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteAlertDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteAlertDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteAlertDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteAlertOKBody delete alert o k body +swagger:model DeleteAlertOKBody +*/ +type DeleteAlertOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete alert o k body +func (o *DeleteAlertOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteAlertOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteAlertOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteAlertOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete alert o k body based on the context it is used +func (o *DeleteAlertOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteAlertOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteAlertOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteAlertOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteAlertOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteAlertOKBody) UnmarshalBinary(b []byte) error { + var res DeleteAlertOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/describe_alert_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/describe_alert_parameters.go new file mode 100644 index 0000000..7e32513 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/describe_alert_parameters.go @@ -0,0 +1,248 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeAlertParams creates a new DescribeAlertParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeAlertParams() *DescribeAlertParams { + return &DescribeAlertParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeAlertParamsWithTimeout creates a new DescribeAlertParams object +// with the ability to set a timeout on a request. +func NewDescribeAlertParamsWithTimeout(timeout time.Duration) *DescribeAlertParams { + return &DescribeAlertParams{ + timeout: timeout, + } +} + +// NewDescribeAlertParamsWithContext creates a new DescribeAlertParams object +// with the ability to set a context for a request. +func NewDescribeAlertParamsWithContext(ctx context.Context) *DescribeAlertParams { + return &DescribeAlertParams{ + Context: ctx, + } +} + +// NewDescribeAlertParamsWithHTTPClient creates a new DescribeAlertParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeAlertParamsWithHTTPClient(client *http.Client) *DescribeAlertParams { + return &DescribeAlertParams{ + HTTPClient: client, + } +} + +/* DescribeAlertParams contains all the parameters to send to the API endpoint + for the describe alert operation. + + Typically these are written to a http.Request. +*/ +type DescribeAlertParams struct { + + /* AlertID. + + rule uuid + */ + AlertID string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe alert params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAlertParams) WithDefaults() *DescribeAlertParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe alert params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAlertParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe alert params +func (o *DescribeAlertParams) WithTimeout(timeout time.Duration) *DescribeAlertParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe alert params +func (o *DescribeAlertParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe alert params +func (o *DescribeAlertParams) WithContext(ctx context.Context) *DescribeAlertParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe alert params +func (o *DescribeAlertParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe alert params +func (o *DescribeAlertParams) WithHTTPClient(client *http.Client) *DescribeAlertParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe alert params +func (o *DescribeAlertParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAlertID adds the alertID to the describe alert params +func (o *DescribeAlertParams) WithAlertID(alertID string) *DescribeAlertParams { + o.SetAlertID(alertID) + return o +} + +// SetAlertID adds the alertId to the describe alert params +func (o *DescribeAlertParams) SetAlertID(alertID string) { + o.AlertID = alertID +} + +// WithAuthorization adds the authorization to the describe alert params +func (o *DescribeAlertParams) WithAuthorization(authorization string) *DescribeAlertParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe alert params +func (o *DescribeAlertParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe alert params +func (o *DescribeAlertParams) WithBmpLanguage(bmpLanguage *string) *DescribeAlertParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe alert params +func (o *DescribeAlertParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe alert params +func (o *DescribeAlertParams) WithBmpUserID(bmpUserID *string) *DescribeAlertParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe alert params +func (o *DescribeAlertParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe alert params +func (o *DescribeAlertParams) WithTraceID(traceID string) *DescribeAlertParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe alert params +func (o *DescribeAlertParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeAlertParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // query param alertId + qrAlertID := o.AlertID + qAlertID := qrAlertID + if qAlertID != "" { + + if err := r.SetQueryParam("alertId", qAlertID); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/describe_alert_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/describe_alert_responses.go new file mode 100644 index 0000000..beb1bdb --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/describe_alert_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeAlertReader is a Reader for the DescribeAlert structure. +type DescribeAlertReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeAlertReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeAlertOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeAlertDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeAlertOK creates a DescribeAlertOK with default headers values +func NewDescribeAlertOK() *DescribeAlertOK { + return &DescribeAlertOK{} +} + +/* DescribeAlertOK describes a response with status code 200, with default header values. + +A DescribeAlertResult is an response struct that is used to describe get Alert. +*/ +type DescribeAlertOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAlertOKBody +} + +// IsSuccess returns true when this describe alert o k response has a 2xx status code +func (o *DescribeAlertOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe alert o k response has a 3xx status code +func (o *DescribeAlertOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe alert o k response has a 4xx status code +func (o *DescribeAlertOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe alert o k response has a 5xx status code +func (o *DescribeAlertOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe alert o k response a status code equal to that given +func (o *DescribeAlertOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeAlertOK) Error() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlert][%d] describeAlertOK %+v", 200, o.Payload) +} + +func (o *DescribeAlertOK) String() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlert][%d] describeAlertOK %+v", 200, o.Payload) +} + +func (o *DescribeAlertOK) GetPayload() *DescribeAlertOKBody { + return o.Payload +} + +func (o *DescribeAlertOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAlertOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeAlertDefault creates a DescribeAlertDefault with default headers values +func NewDescribeAlertDefault(code int) *DescribeAlertDefault { + return &DescribeAlertDefault{ + _statusCode: code, + } +} + +/* DescribeAlertDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeAlertDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAlertDefaultBody +} + +// Code gets the status code for the describe alert default response +func (o *DescribeAlertDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe alert default response has a 2xx status code +func (o *DescribeAlertDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe alert default response has a 3xx status code +func (o *DescribeAlertDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe alert default response has a 4xx status code +func (o *DescribeAlertDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe alert default response has a 5xx status code +func (o *DescribeAlertDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe alert default response a status code equal to that given +func (o *DescribeAlertDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeAlertDefault) Error() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlert][%d] describeAlert default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAlertDefault) String() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlert][%d] describeAlert default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAlertDefault) GetPayload() *DescribeAlertDefaultBody { + return o.Payload +} + +func (o *DescribeAlertDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAlertDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeAlertDefaultBody describe alert default body +swagger:model DescribeAlertDefaultBody +*/ +type DescribeAlertDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe alert default body +func (o *DescribeAlertDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeAlert default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeAlertDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeAlert default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlert default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlert default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe alert default body based on the context it is used +func (o *DescribeAlertDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlert default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlert default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAlertDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAlertDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeAlertDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeAlertOKBody describe alert o k body +swagger:model DescribeAlertOKBody +*/ +type DescribeAlertOKBody struct { + + // result + Result *models.Alert `json:"result,omitempty"` +} + +// Validate validates this describe alert o k body +func (o *DescribeAlertOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlertOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlertOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe alert o k body based on the context it is used +func (o *DescribeAlertOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlertOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlertOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAlertOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAlertOKBody) UnmarshalBinary(b []byte) error { + var res DescribeAlertOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/describe_alerts_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/describe_alerts_parameters.go new file mode 100644 index 0000000..7576c24 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/describe_alerts_parameters.go @@ -0,0 +1,570 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeAlertsParams creates a new DescribeAlertsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeAlertsParams() *DescribeAlertsParams { + return &DescribeAlertsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeAlertsParamsWithTimeout creates a new DescribeAlertsParams object +// with the ability to set a timeout on a request. +func NewDescribeAlertsParamsWithTimeout(timeout time.Duration) *DescribeAlertsParams { + return &DescribeAlertsParams{ + timeout: timeout, + } +} + +// NewDescribeAlertsParamsWithContext creates a new DescribeAlertsParams object +// with the ability to set a context for a request. +func NewDescribeAlertsParamsWithContext(ctx context.Context) *DescribeAlertsParams { + return &DescribeAlertsParams{ + Context: ctx, + } +} + +// NewDescribeAlertsParamsWithHTTPClient creates a new DescribeAlertsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeAlertsParamsWithHTTPClient(client *http.Client) *DescribeAlertsParams { + return &DescribeAlertsParams{ + HTTPClient: client, + } +} + +/* DescribeAlertsParams contains all the parameters to send to the API endpoint + for the describe alerts operation. + + Typically these are written to a http.Request. +*/ +type DescribeAlertsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* EndTime. + + 报警时间筛选etime + + Format: int64 + */ + EndTime *int64 + + /* IsAll. + + 是否显示全部,取值为1时表示全部 + */ + IsAll *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* ResourceID. + + 资源id,目前就是实例id + */ + ResourceID *string + + /* RuleID. + + 规则uuid + */ + RuleID *string + + /* RuleName. + + 规则名称 + */ + RuleName *string + + /* StartTime. + + 报警时间筛选stime + + Format: int64 + */ + StartTime *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserID. + + user uuid + */ + UserID *string + + /* UserName. + + username + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe alerts params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAlertsParams) WithDefaults() *DescribeAlertsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe alerts params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeAlertsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe alerts params +func (o *DescribeAlertsParams) WithTimeout(timeout time.Duration) *DescribeAlertsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe alerts params +func (o *DescribeAlertsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe alerts params +func (o *DescribeAlertsParams) WithContext(ctx context.Context) *DescribeAlertsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe alerts params +func (o *DescribeAlertsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe alerts params +func (o *DescribeAlertsParams) WithHTTPClient(client *http.Client) *DescribeAlertsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe alerts params +func (o *DescribeAlertsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe alerts params +func (o *DescribeAlertsParams) WithAuthorization(authorization string) *DescribeAlertsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe alerts params +func (o *DescribeAlertsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe alerts params +func (o *DescribeAlertsParams) WithBmpLanguage(bmpLanguage *string) *DescribeAlertsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe alerts params +func (o *DescribeAlertsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe alerts params +func (o *DescribeAlertsParams) WithBmpUserID(bmpUserID *string) *DescribeAlertsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe alerts params +func (o *DescribeAlertsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithEndTime adds the endTime to the describe alerts params +func (o *DescribeAlertsParams) WithEndTime(endTime *int64) *DescribeAlertsParams { + o.SetEndTime(endTime) + return o +} + +// SetEndTime adds the endTime to the describe alerts params +func (o *DescribeAlertsParams) SetEndTime(endTime *int64) { + o.EndTime = endTime +} + +// WithIsAll adds the isAll to the describe alerts params +func (o *DescribeAlertsParams) WithIsAll(isAll *string) *DescribeAlertsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe alerts params +func (o *DescribeAlertsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithPageNumber adds the pageNumber to the describe alerts params +func (o *DescribeAlertsParams) WithPageNumber(pageNumber *int64) *DescribeAlertsParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe alerts params +func (o *DescribeAlertsParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe alerts params +func (o *DescribeAlertsParams) WithPageSize(pageSize *int64) *DescribeAlertsParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe alerts params +func (o *DescribeAlertsParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithResourceID adds the resourceID to the describe alerts params +func (o *DescribeAlertsParams) WithResourceID(resourceID *string) *DescribeAlertsParams { + o.SetResourceID(resourceID) + return o +} + +// SetResourceID adds the resourceId to the describe alerts params +func (o *DescribeAlertsParams) SetResourceID(resourceID *string) { + o.ResourceID = resourceID +} + +// WithRuleID adds the ruleID to the describe alerts params +func (o *DescribeAlertsParams) WithRuleID(ruleID *string) *DescribeAlertsParams { + o.SetRuleID(ruleID) + return o +} + +// SetRuleID adds the ruleId to the describe alerts params +func (o *DescribeAlertsParams) SetRuleID(ruleID *string) { + o.RuleID = ruleID +} + +// WithRuleName adds the ruleName to the describe alerts params +func (o *DescribeAlertsParams) WithRuleName(ruleName *string) *DescribeAlertsParams { + o.SetRuleName(ruleName) + return o +} + +// SetRuleName adds the ruleName to the describe alerts params +func (o *DescribeAlertsParams) SetRuleName(ruleName *string) { + o.RuleName = ruleName +} + +// WithStartTime adds the startTime to the describe alerts params +func (o *DescribeAlertsParams) WithStartTime(startTime *int64) *DescribeAlertsParams { + o.SetStartTime(startTime) + return o +} + +// SetStartTime adds the startTime to the describe alerts params +func (o *DescribeAlertsParams) SetStartTime(startTime *int64) { + o.StartTime = startTime +} + +// WithTraceID adds the traceID to the describe alerts params +func (o *DescribeAlertsParams) WithTraceID(traceID string) *DescribeAlertsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe alerts params +func (o *DescribeAlertsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserID adds the userID to the describe alerts params +func (o *DescribeAlertsParams) WithUserID(userID *string) *DescribeAlertsParams { + o.SetUserID(userID) + return o +} + +// SetUserID adds the userId to the describe alerts params +func (o *DescribeAlertsParams) SetUserID(userID *string) { + o.UserID = userID +} + +// WithUserName adds the userName to the describe alerts params +func (o *DescribeAlertsParams) WithUserName(userName *string) *DescribeAlertsParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe alerts params +func (o *DescribeAlertsParams) SetUserName(userName *string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeAlertsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.EndTime != nil { + + // query param endTime + var qrEndTime int64 + + if o.EndTime != nil { + qrEndTime = *o.EndTime + } + qEndTime := swag.FormatInt64(qrEndTime) + if qEndTime != "" { + + if err := r.SetQueryParam("endTime", qEndTime); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.ResourceID != nil { + + // query param resourceId + var qrResourceID string + + if o.ResourceID != nil { + qrResourceID = *o.ResourceID + } + qResourceID := qrResourceID + if qResourceID != "" { + + if err := r.SetQueryParam("resourceId", qResourceID); err != nil { + return err + } + } + } + + if o.RuleID != nil { + + // query param ruleId + var qrRuleID string + + if o.RuleID != nil { + qrRuleID = *o.RuleID + } + qRuleID := qrRuleID + if qRuleID != "" { + + if err := r.SetQueryParam("ruleId", qRuleID); err != nil { + return err + } + } + } + + if o.RuleName != nil { + + // query param ruleName + var qrRuleName string + + if o.RuleName != nil { + qrRuleName = *o.RuleName + } + qRuleName := qrRuleName + if qRuleName != "" { + + if err := r.SetQueryParam("ruleName", qRuleName); err != nil { + return err + } + } + } + + if o.StartTime != nil { + + // query param startTime + var qrStartTime int64 + + if o.StartTime != nil { + qrStartTime = *o.StartTime + } + qStartTime := swag.FormatInt64(qrStartTime) + if qStartTime != "" { + + if err := r.SetQueryParam("startTime", qStartTime); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserID != nil { + + // query param userId + var qrUserID string + + if o.UserID != nil { + qrUserID = *o.UserID + } + qUserID := qrUserID + if qUserID != "" { + + if err := r.SetQueryParam("userId", qUserID); err != nil { + return err + } + } + } + + if o.UserName != nil { + + // query param userName + var qrUserName string + + if o.UserName != nil { + qrUserName = *o.UserName + } + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/describe_alerts_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/describe_alerts_responses.go new file mode 100644 index 0000000..10a0252 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/describe_alerts_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeAlertsReader is a Reader for the DescribeAlerts structure. +type DescribeAlertsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeAlertsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeAlertsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeAlertsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeAlertsOK creates a DescribeAlertsOK with default headers values +func NewDescribeAlertsOK() *DescribeAlertsOK { + return &DescribeAlertsOK{} +} + +/* DescribeAlertsOK describes a response with status code 200, with default header values. + +A DescribeAlertsResult is an response struct that is used to describe get Alert. +*/ +type DescribeAlertsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAlertsOKBody +} + +// IsSuccess returns true when this describe alerts o k response has a 2xx status code +func (o *DescribeAlertsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe alerts o k response has a 3xx status code +func (o *DescribeAlertsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe alerts o k response has a 4xx status code +func (o *DescribeAlertsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe alerts o k response has a 5xx status code +func (o *DescribeAlertsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe alerts o k response a status code equal to that given +func (o *DescribeAlertsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeAlertsOK) Error() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlerts][%d] describeAlertsOK %+v", 200, o.Payload) +} + +func (o *DescribeAlertsOK) String() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlerts][%d] describeAlertsOK %+v", 200, o.Payload) +} + +func (o *DescribeAlertsOK) GetPayload() *DescribeAlertsOKBody { + return o.Payload +} + +func (o *DescribeAlertsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAlertsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeAlertsDefault creates a DescribeAlertsDefault with default headers values +func NewDescribeAlertsDefault(code int) *DescribeAlertsDefault { + return &DescribeAlertsDefault{ + _statusCode: code, + } +} + +/* DescribeAlertsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeAlertsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeAlertsDefaultBody +} + +// Code gets the status code for the describe alerts default response +func (o *DescribeAlertsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe alerts default response has a 2xx status code +func (o *DescribeAlertsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe alerts default response has a 3xx status code +func (o *DescribeAlertsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe alerts default response has a 4xx status code +func (o *DescribeAlertsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe alerts default response has a 5xx status code +func (o *DescribeAlertsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe alerts default response a status code equal to that given +func (o *DescribeAlertsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeAlertsDefault) Error() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlerts][%d] describeAlerts default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAlertsDefault) String() string { + return fmt.Sprintf("[GET /monitorAlert/describeAlerts][%d] describeAlerts default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeAlertsDefault) GetPayload() *DescribeAlertsDefaultBody { + return o.Payload +} + +func (o *DescribeAlertsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeAlertsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeAlertsDefaultBody describe alerts default body +swagger:model DescribeAlertsDefaultBody +*/ +type DescribeAlertsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe alerts default body +func (o *DescribeAlertsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeAlerts default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeAlertsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeAlerts default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlerts default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlerts default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe alerts default body based on the context it is used +func (o *DescribeAlertsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlerts default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlerts default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAlertsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAlertsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeAlertsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeAlertsOKBody describe alerts o k body +swagger:model DescribeAlertsOKBody +*/ +type DescribeAlertsOKBody struct { + + // result + Result *models.AlertList `json:"result,omitempty"` +} + +// Validate validates this describe alerts o k body +func (o *DescribeAlertsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlertsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlertsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe alerts o k body based on the context it is used +func (o *DescribeAlertsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeAlertsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeAlertsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeAlertsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeAlertsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeAlertsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeAlertsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/monitor_alert_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/monitor_alert_client.go new file mode 100644 index 0000000..bb2e797 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_alert/monitor_alert_client.go @@ -0,0 +1,157 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_alert + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new monitor alert API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for monitor alert API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DeleteAlert(params *DeleteAlertParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteAlertOK, error) + + DescribeAlert(params *DescribeAlertParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAlertOK, error) + + DescribeAlerts(params *DescribeAlertsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAlertsOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DeleteAlert DeleteAlert 删除告警 +*/ +func (a *Client) DeleteAlert(params *DeleteAlertParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteAlertOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteAlertParams() + } + op := &runtime.ClientOperation{ + ID: "deleteAlert", + Method: "DELETE", + PathPattern: "/monitorAlert/deleteAlert", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteAlertReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteAlertOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteAlertDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeAlert DescribeAlert 告警详情 +*/ +func (a *Client) DescribeAlert(params *DescribeAlertParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAlertOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeAlertParams() + } + op := &runtime.ClientOperation{ + ID: "describeAlert", + Method: "GET", + PathPattern: "/monitorAlert/describeAlert", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeAlertReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeAlertOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeAlertDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeAlerts DescribeAlerts 告警列表 +*/ +func (a *Client) DescribeAlerts(params *DescribeAlertsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeAlertsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeAlertsParams() + } + op := &runtime.ClientOperation{ + ID: "describeAlerts", + Method: "GET", + PathPattern: "/monitorAlert/describeAlerts", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeAlertsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeAlertsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeAlertsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_data/get_monitor_data_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_data/get_monitor_data_parameters.go new file mode 100644 index 0000000..ae0cabc --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_data/get_monitor_data_parameters.go @@ -0,0 +1,570 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_data + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetMonitorDataParams creates a new GetMonitorDataParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetMonitorDataParams() *GetMonitorDataParams { + return &GetMonitorDataParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetMonitorDataParamsWithTimeout creates a new GetMonitorDataParams object +// with the ability to set a timeout on a request. +func NewGetMonitorDataParamsWithTimeout(timeout time.Duration) *GetMonitorDataParams { + return &GetMonitorDataParams{ + timeout: timeout, + } +} + +// NewGetMonitorDataParamsWithContext creates a new GetMonitorDataParams object +// with the ability to set a context for a request. +func NewGetMonitorDataParamsWithContext(ctx context.Context) *GetMonitorDataParams { + return &GetMonitorDataParams{ + Context: ctx, + } +} + +// NewGetMonitorDataParamsWithHTTPClient creates a new GetMonitorDataParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetMonitorDataParamsWithHTTPClient(client *http.Client) *GetMonitorDataParams { + return &GetMonitorDataParams{ + HTTPClient: client, + } +} + +/* GetMonitorDataParams contains all the parameters to send to the API endpoint + for the get monitor data operation. + + Typically these are written to a http.Request. +*/ +type GetMonitorDataParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* Device. + + 标签值 + */ + Device *string + + /* DownSampleType. + + avg, min, max, sum + */ + DownSampleType *string + + /* EndTime. + + 结束时间戳 + + Format: int64 + */ + EndTime *int64 + + /* IdcID. + + idc uuid + */ + IdcID *string + + /* InstanceID. + + 实例id + */ + InstanceID *string + + /* LastManyTime. + + 最近多少时间,小时为单位 + + Format: int64 + */ + LastManyTime *int64 + + /* MetricName. + + 指标名称,支持多个,用逗号隔离开 + */ + MetricName *string + + /* StartTime. + + 开始时间戳 + + Format: int64 + */ + StartTime *int64 + + /* TimeInterval. + + 间隔多久一个点 s为单位 + + Format: int64 + */ + TimeInterval *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserName. + + 以下为运营平台的 + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get monitor data params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMonitorDataParams) WithDefaults() *GetMonitorDataParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get monitor data params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMonitorDataParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get monitor data params +func (o *GetMonitorDataParams) WithTimeout(timeout time.Duration) *GetMonitorDataParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get monitor data params +func (o *GetMonitorDataParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get monitor data params +func (o *GetMonitorDataParams) WithContext(ctx context.Context) *GetMonitorDataParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get monitor data params +func (o *GetMonitorDataParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get monitor data params +func (o *GetMonitorDataParams) WithHTTPClient(client *http.Client) *GetMonitorDataParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get monitor data params +func (o *GetMonitorDataParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the get monitor data params +func (o *GetMonitorDataParams) WithAuthorization(authorization string) *GetMonitorDataParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the get monitor data params +func (o *GetMonitorDataParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the get monitor data params +func (o *GetMonitorDataParams) WithBmpLanguage(bmpLanguage *string) *GetMonitorDataParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the get monitor data params +func (o *GetMonitorDataParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the get monitor data params +func (o *GetMonitorDataParams) WithBmpUserID(bmpUserID *string) *GetMonitorDataParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the get monitor data params +func (o *GetMonitorDataParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDevice adds the device to the get monitor data params +func (o *GetMonitorDataParams) WithDevice(device *string) *GetMonitorDataParams { + o.SetDevice(device) + return o +} + +// SetDevice adds the device to the get monitor data params +func (o *GetMonitorDataParams) SetDevice(device *string) { + o.Device = device +} + +// WithDownSampleType adds the downSampleType to the get monitor data params +func (o *GetMonitorDataParams) WithDownSampleType(downSampleType *string) *GetMonitorDataParams { + o.SetDownSampleType(downSampleType) + return o +} + +// SetDownSampleType adds the downSampleType to the get monitor data params +func (o *GetMonitorDataParams) SetDownSampleType(downSampleType *string) { + o.DownSampleType = downSampleType +} + +// WithEndTime adds the endTime to the get monitor data params +func (o *GetMonitorDataParams) WithEndTime(endTime *int64) *GetMonitorDataParams { + o.SetEndTime(endTime) + return o +} + +// SetEndTime adds the endTime to the get monitor data params +func (o *GetMonitorDataParams) SetEndTime(endTime *int64) { + o.EndTime = endTime +} + +// WithIdcID adds the idcID to the get monitor data params +func (o *GetMonitorDataParams) WithIdcID(idcID *string) *GetMonitorDataParams { + o.SetIdcID(idcID) + return o +} + +// SetIdcID adds the idcId to the get monitor data params +func (o *GetMonitorDataParams) SetIdcID(idcID *string) { + o.IdcID = idcID +} + +// WithInstanceID adds the instanceID to the get monitor data params +func (o *GetMonitorDataParams) WithInstanceID(instanceID *string) *GetMonitorDataParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the get monitor data params +func (o *GetMonitorDataParams) SetInstanceID(instanceID *string) { + o.InstanceID = instanceID +} + +// WithLastManyTime adds the lastManyTime to the get monitor data params +func (o *GetMonitorDataParams) WithLastManyTime(lastManyTime *int64) *GetMonitorDataParams { + o.SetLastManyTime(lastManyTime) + return o +} + +// SetLastManyTime adds the lastManyTime to the get monitor data params +func (o *GetMonitorDataParams) SetLastManyTime(lastManyTime *int64) { + o.LastManyTime = lastManyTime +} + +// WithMetricName adds the metricName to the get monitor data params +func (o *GetMonitorDataParams) WithMetricName(metricName *string) *GetMonitorDataParams { + o.SetMetricName(metricName) + return o +} + +// SetMetricName adds the metricName to the get monitor data params +func (o *GetMonitorDataParams) SetMetricName(metricName *string) { + o.MetricName = metricName +} + +// WithStartTime adds the startTime to the get monitor data params +func (o *GetMonitorDataParams) WithStartTime(startTime *int64) *GetMonitorDataParams { + o.SetStartTime(startTime) + return o +} + +// SetStartTime adds the startTime to the get monitor data params +func (o *GetMonitorDataParams) SetStartTime(startTime *int64) { + o.StartTime = startTime +} + +// WithTimeInterval adds the timeInterval to the get monitor data params +func (o *GetMonitorDataParams) WithTimeInterval(timeInterval *int64) *GetMonitorDataParams { + o.SetTimeInterval(timeInterval) + return o +} + +// SetTimeInterval adds the timeInterval to the get monitor data params +func (o *GetMonitorDataParams) SetTimeInterval(timeInterval *int64) { + o.TimeInterval = timeInterval +} + +// WithTraceID adds the traceID to the get monitor data params +func (o *GetMonitorDataParams) WithTraceID(traceID string) *GetMonitorDataParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the get monitor data params +func (o *GetMonitorDataParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserName adds the userName to the get monitor data params +func (o *GetMonitorDataParams) WithUserName(userName *string) *GetMonitorDataParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the get monitor data params +func (o *GetMonitorDataParams) SetUserName(userName *string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *GetMonitorDataParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.Device != nil { + + // query param device + var qrDevice string + + if o.Device != nil { + qrDevice = *o.Device + } + qDevice := qrDevice + if qDevice != "" { + + if err := r.SetQueryParam("device", qDevice); err != nil { + return err + } + } + } + + if o.DownSampleType != nil { + + // query param downSampleType + var qrDownSampleType string + + if o.DownSampleType != nil { + qrDownSampleType = *o.DownSampleType + } + qDownSampleType := qrDownSampleType + if qDownSampleType != "" { + + if err := r.SetQueryParam("downSampleType", qDownSampleType); err != nil { + return err + } + } + } + + if o.EndTime != nil { + + // query param endTime + var qrEndTime int64 + + if o.EndTime != nil { + qrEndTime = *o.EndTime + } + qEndTime := swag.FormatInt64(qrEndTime) + if qEndTime != "" { + + if err := r.SetQueryParam("endTime", qEndTime); err != nil { + return err + } + } + } + + if o.IdcID != nil { + + // query param idcID + var qrIdcID string + + if o.IdcID != nil { + qrIdcID = *o.IdcID + } + qIdcID := qrIdcID + if qIdcID != "" { + + if err := r.SetQueryParam("idcID", qIdcID); err != nil { + return err + } + } + } + + if o.InstanceID != nil { + + // query param instanceId + var qrInstanceID string + + if o.InstanceID != nil { + qrInstanceID = *o.InstanceID + } + qInstanceID := qrInstanceID + if qInstanceID != "" { + + if err := r.SetQueryParam("instanceId", qInstanceID); err != nil { + return err + } + } + } + + if o.LastManyTime != nil { + + // query param lastManyTime + var qrLastManyTime int64 + + if o.LastManyTime != nil { + qrLastManyTime = *o.LastManyTime + } + qLastManyTime := swag.FormatInt64(qrLastManyTime) + if qLastManyTime != "" { + + if err := r.SetQueryParam("lastManyTime", qLastManyTime); err != nil { + return err + } + } + } + + if o.MetricName != nil { + + // query param metricName + var qrMetricName string + + if o.MetricName != nil { + qrMetricName = *o.MetricName + } + qMetricName := qrMetricName + if qMetricName != "" { + + if err := r.SetQueryParam("metricName", qMetricName); err != nil { + return err + } + } + } + + if o.StartTime != nil { + + // query param startTime + var qrStartTime int64 + + if o.StartTime != nil { + qrStartTime = *o.StartTime + } + qStartTime := swag.FormatInt64(qrStartTime) + if qStartTime != "" { + + if err := r.SetQueryParam("startTime", qStartTime); err != nil { + return err + } + } + } + + if o.TimeInterval != nil { + + // query param timeInterval + var qrTimeInterval int64 + + if o.TimeInterval != nil { + qrTimeInterval = *o.TimeInterval + } + qTimeInterval := swag.FormatInt64(qrTimeInterval) + if qTimeInterval != "" { + + if err := r.SetQueryParam("timeInterval", qTimeInterval); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserName != nil { + + // query param userName + var qrUserName string + + if o.UserName != nil { + qrUserName = *o.UserName + } + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_data/get_monitor_data_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_data/get_monitor_data_responses.go new file mode 100644 index 0000000..6fb1dc8 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_data/get_monitor_data_responses.go @@ -0,0 +1,415 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_data + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// GetMonitorDataReader is a Reader for the GetMonitorData structure. +type GetMonitorDataReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetMonitorDataReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetMonitorDataOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetMonitorDataDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetMonitorDataOK creates a GetMonitorDataOK with default headers values +func NewGetMonitorDataOK() *GetMonitorDataOK { + return &GetMonitorDataOK{} +} + +/* GetMonitorDataOK describes a response with status code 200, with default header values. + +GetMonitorDataOK get monitor data o k +*/ +type GetMonitorDataOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMonitorDataOKBody +} + +// IsSuccess returns true when this get monitor data o k response has a 2xx status code +func (o *GetMonitorDataOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get monitor data o k response has a 3xx status code +func (o *GetMonitorDataOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get monitor data o k response has a 4xx status code +func (o *GetMonitorDataOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get monitor data o k response has a 5xx status code +func (o *GetMonitorDataOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get monitor data o k response a status code equal to that given +func (o *GetMonitorDataOK) IsCode(code int) bool { + return code == 200 +} + +func (o *GetMonitorDataOK) Error() string { + return fmt.Sprintf("[GET /monitorData][%d] getMonitorDataOK %+v", 200, o.Payload) +} + +func (o *GetMonitorDataOK) String() string { + return fmt.Sprintf("[GET /monitorData][%d] getMonitorDataOK %+v", 200, o.Payload) +} + +func (o *GetMonitorDataOK) GetPayload() *GetMonitorDataOKBody { + return o.Payload +} + +func (o *GetMonitorDataOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMonitorDataOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetMonitorDataDefault creates a GetMonitorDataDefault with default headers values +func NewGetMonitorDataDefault(code int) *GetMonitorDataDefault { + return &GetMonitorDataDefault{ + _statusCode: code, + } +} + +/* GetMonitorDataDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type GetMonitorDataDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetMonitorDataDefaultBody +} + +// Code gets the status code for the get monitor data default response +func (o *GetMonitorDataDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this get monitor data default response has a 2xx status code +func (o *GetMonitorDataDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get monitor data default response has a 3xx status code +func (o *GetMonitorDataDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get monitor data default response has a 4xx status code +func (o *GetMonitorDataDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get monitor data default response has a 5xx status code +func (o *GetMonitorDataDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get monitor data default response a status code equal to that given +func (o *GetMonitorDataDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *GetMonitorDataDefault) Error() string { + return fmt.Sprintf("[GET /monitorData][%d] getMonitorData default %+v", o._statusCode, o.Payload) +} + +func (o *GetMonitorDataDefault) String() string { + return fmt.Sprintf("[GET /monitorData][%d] getMonitorData default %+v", o._statusCode, o.Payload) +} + +func (o *GetMonitorDataDefault) GetPayload() *GetMonitorDataDefaultBody { + return o.Payload +} + +func (o *GetMonitorDataDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetMonitorDataDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*GetMonitorDataDefaultBody get monitor data default body +swagger:model GetMonitorDataDefaultBody +*/ +type GetMonitorDataDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this get monitor data default body +func (o *GetMonitorDataDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMonitorDataDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("getMonitorData default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *GetMonitorDataDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("getMonitorData default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMonitorData default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMonitorData default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get monitor data default body based on the context it is used +func (o *GetMonitorDataDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMonitorDataDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMonitorData default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMonitorData default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMonitorDataDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMonitorDataDefaultBody) UnmarshalBinary(b []byte) error { + var res GetMonitorDataDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*GetMonitorDataOKBody get monitor data o k body +swagger:model GetMonitorDataOKBody +*/ +type GetMonitorDataOKBody struct { + + // result + Result []*models.DataEveryMetric `json:"result"` +} + +// Validate validates this get monitor data o k body +func (o *GetMonitorDataOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMonitorDataOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + for i := 0; i < len(o.Result); i++ { + if swag.IsZero(o.Result[i]) { // not required + continue + } + + if o.Result[i] != nil { + if err := o.Result[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMonitorDataOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMonitorDataOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get monitor data o k body based on the context it is used +func (o *GetMonitorDataOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetMonitorDataOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Result); i++ { + + if o.Result[i] != nil { + if err := o.Result[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getMonitorDataOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getMonitorDataOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetMonitorDataOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetMonitorDataOKBody) UnmarshalBinary(b []byte) error { + var res GetMonitorDataOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_data/monitor_data_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_data/monitor_data_client.go new file mode 100644 index 0000000..6925f61 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_data/monitor_data_client.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_data + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new monitor data API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for monitor data API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + GetMonitorData(params *GetMonitorDataParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMonitorDataOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + GetMonitorData GetMonitorData 获取图表监控数据 +*/ +func (a *Client) GetMonitorData(params *GetMonitorDataParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMonitorDataOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetMonitorDataParams() + } + op := &runtime.ClientOperation{ + ID: "getMonitorData", + Method: "GET", + PathPattern: "/monitorData", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetMonitorDataReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetMonitorDataOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetMonitorDataDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_proxy/desrcibe_agent_status_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_proxy/desrcibe_agent_status_parameters.go new file mode 100644 index 0000000..45c1e12 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_proxy/desrcibe_agent_status_parameters.go @@ -0,0 +1,248 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_proxy + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDesrcibeAgentStatusParams creates a new DesrcibeAgentStatusParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDesrcibeAgentStatusParams() *DesrcibeAgentStatusParams { + return &DesrcibeAgentStatusParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDesrcibeAgentStatusParamsWithTimeout creates a new DesrcibeAgentStatusParams object +// with the ability to set a timeout on a request. +func NewDesrcibeAgentStatusParamsWithTimeout(timeout time.Duration) *DesrcibeAgentStatusParams { + return &DesrcibeAgentStatusParams{ + timeout: timeout, + } +} + +// NewDesrcibeAgentStatusParamsWithContext creates a new DesrcibeAgentStatusParams object +// with the ability to set a context for a request. +func NewDesrcibeAgentStatusParamsWithContext(ctx context.Context) *DesrcibeAgentStatusParams { + return &DesrcibeAgentStatusParams{ + Context: ctx, + } +} + +// NewDesrcibeAgentStatusParamsWithHTTPClient creates a new DesrcibeAgentStatusParams object +// with the ability to set a custom HTTPClient for a request. +func NewDesrcibeAgentStatusParamsWithHTTPClient(client *http.Client) *DesrcibeAgentStatusParams { + return &DesrcibeAgentStatusParams{ + HTTPClient: client, + } +} + +/* DesrcibeAgentStatusParams contains all the parameters to send to the API endpoint + for the desrcibe agent status operation. + + Typically these are written to a http.Request. +*/ +type DesrcibeAgentStatusParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* InstanceID. + + InstanceId,多个用逗号分隔 + */ + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the desrcibe agent status params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DesrcibeAgentStatusParams) WithDefaults() *DesrcibeAgentStatusParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the desrcibe agent status params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DesrcibeAgentStatusParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithTimeout(timeout time.Duration) *DesrcibeAgentStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithContext(ctx context.Context) *DesrcibeAgentStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithHTTPClient(client *http.Client) *DesrcibeAgentStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithAuthorization(authorization string) *DesrcibeAgentStatusParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithBmpLanguage(bmpLanguage *string) *DesrcibeAgentStatusParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithBmpUserID(bmpUserID *string) *DesrcibeAgentStatusParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithInstanceID(instanceID string) *DesrcibeAgentStatusParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) WithTraceID(traceID string) *DesrcibeAgentStatusParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the desrcibe agent status params +func (o *DesrcibeAgentStatusParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DesrcibeAgentStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // query param instanceId + qrInstanceID := o.InstanceID + qInstanceID := qrInstanceID + if qInstanceID != "" { + + if err := r.SetQueryParam("instanceId", qInstanceID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_proxy/desrcibe_agent_status_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_proxy/desrcibe_agent_status_responses.go new file mode 100644 index 0000000..bc82205 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_proxy/desrcibe_agent_status_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_proxy + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DesrcibeAgentStatusReader is a Reader for the DesrcibeAgentStatus structure. +type DesrcibeAgentStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DesrcibeAgentStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDesrcibeAgentStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDesrcibeAgentStatusDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDesrcibeAgentStatusOK creates a DesrcibeAgentStatusOK with default headers values +func NewDesrcibeAgentStatusOK() *DesrcibeAgentStatusOK { + return &DesrcibeAgentStatusOK{} +} + +/* DesrcibeAgentStatusOK describes a response with status code 200, with default header values. + +DesrcibeAgentStatusOK desrcibe agent status o k +*/ +type DesrcibeAgentStatusOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DesrcibeAgentStatusOKBody +} + +// IsSuccess returns true when this desrcibe agent status o k response has a 2xx status code +func (o *DesrcibeAgentStatusOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this desrcibe agent status o k response has a 3xx status code +func (o *DesrcibeAgentStatusOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this desrcibe agent status o k response has a 4xx status code +func (o *DesrcibeAgentStatusOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this desrcibe agent status o k response has a 5xx status code +func (o *DesrcibeAgentStatusOK) IsServerError() bool { + return false +} + +// IsCode returns true when this desrcibe agent status o k response a status code equal to that given +func (o *DesrcibeAgentStatusOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DesrcibeAgentStatusOK) Error() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeAgentStatus][%d] desrcibeAgentStatusOK %+v", 200, o.Payload) +} + +func (o *DesrcibeAgentStatusOK) String() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeAgentStatus][%d] desrcibeAgentStatusOK %+v", 200, o.Payload) +} + +func (o *DesrcibeAgentStatusOK) GetPayload() *DesrcibeAgentStatusOKBody { + return o.Payload +} + +func (o *DesrcibeAgentStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DesrcibeAgentStatusOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDesrcibeAgentStatusDefault creates a DesrcibeAgentStatusDefault with default headers values +func NewDesrcibeAgentStatusDefault(code int) *DesrcibeAgentStatusDefault { + return &DesrcibeAgentStatusDefault{ + _statusCode: code, + } +} + +/* DesrcibeAgentStatusDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DesrcibeAgentStatusDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DesrcibeAgentStatusDefaultBody +} + +// Code gets the status code for the desrcibe agent status default response +func (o *DesrcibeAgentStatusDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this desrcibe agent status default response has a 2xx status code +func (o *DesrcibeAgentStatusDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this desrcibe agent status default response has a 3xx status code +func (o *DesrcibeAgentStatusDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this desrcibe agent status default response has a 4xx status code +func (o *DesrcibeAgentStatusDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this desrcibe agent status default response has a 5xx status code +func (o *DesrcibeAgentStatusDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this desrcibe agent status default response a status code equal to that given +func (o *DesrcibeAgentStatusDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DesrcibeAgentStatusDefault) Error() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeAgentStatus][%d] desrcibeAgentStatus default %+v", o._statusCode, o.Payload) +} + +func (o *DesrcibeAgentStatusDefault) String() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeAgentStatus][%d] desrcibeAgentStatus default %+v", o._statusCode, o.Payload) +} + +func (o *DesrcibeAgentStatusDefault) GetPayload() *DesrcibeAgentStatusDefaultBody { + return o.Payload +} + +func (o *DesrcibeAgentStatusDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DesrcibeAgentStatusDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DesrcibeAgentStatusDefaultBody desrcibe agent status default body +swagger:model DesrcibeAgentStatusDefaultBody +*/ +type DesrcibeAgentStatusDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this desrcibe agent status default body +func (o *DesrcibeAgentStatusDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeAgentStatusDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("desrcibeAgentStatus default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DesrcibeAgentStatusDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("desrcibeAgentStatus default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeAgentStatus default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeAgentStatus default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this desrcibe agent status default body based on the context it is used +func (o *DesrcibeAgentStatusDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeAgentStatusDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeAgentStatus default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeAgentStatus default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DesrcibeAgentStatusDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DesrcibeAgentStatusDefaultBody) UnmarshalBinary(b []byte) error { + var res DesrcibeAgentStatusDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DesrcibeAgentStatusOKBody desrcibe agent status o k body +swagger:model DesrcibeAgentStatusOKBody +*/ +type DesrcibeAgentStatusOKBody struct { + + // result + Result *models.AgentStatusResponse `json:"result,omitempty"` +} + +// Validate validates this desrcibe agent status o k body +func (o *DesrcibeAgentStatusOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeAgentStatusOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeAgentStatusOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeAgentStatusOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this desrcibe agent status o k body based on the context it is used +func (o *DesrcibeAgentStatusOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeAgentStatusOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeAgentStatusOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeAgentStatusOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DesrcibeAgentStatusOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DesrcibeAgentStatusOKBody) UnmarshalBinary(b []byte) error { + var res DesrcibeAgentStatusOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_proxy/desrcibe_tags_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_proxy/desrcibe_tags_parameters.go new file mode 100644 index 0000000..e270152 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_proxy/desrcibe_tags_parameters.go @@ -0,0 +1,275 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_proxy + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDesrcibeTagsParams creates a new DesrcibeTagsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDesrcibeTagsParams() *DesrcibeTagsParams { + return &DesrcibeTagsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDesrcibeTagsParamsWithTimeout creates a new DesrcibeTagsParams object +// with the ability to set a timeout on a request. +func NewDesrcibeTagsParamsWithTimeout(timeout time.Duration) *DesrcibeTagsParams { + return &DesrcibeTagsParams{ + timeout: timeout, + } +} + +// NewDesrcibeTagsParamsWithContext creates a new DesrcibeTagsParams object +// with the ability to set a context for a request. +func NewDesrcibeTagsParamsWithContext(ctx context.Context) *DesrcibeTagsParams { + return &DesrcibeTagsParams{ + Context: ctx, + } +} + +// NewDesrcibeTagsParamsWithHTTPClient creates a new DesrcibeTagsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDesrcibeTagsParamsWithHTTPClient(client *http.Client) *DesrcibeTagsParams { + return &DesrcibeTagsParams{ + HTTPClient: client, + } +} + +/* DesrcibeTagsParams contains all the parameters to send to the API endpoint + for the desrcibe tags operation. + + Typically these are written to a http.Request. +*/ +type DesrcibeTagsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* InstanceID. + + instanceId + */ + InstanceID string + + /* TagName. + + tagName [disk mountpoint nic] + */ + TagName string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the desrcibe tags params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DesrcibeTagsParams) WithDefaults() *DesrcibeTagsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the desrcibe tags params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DesrcibeTagsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the desrcibe tags params +func (o *DesrcibeTagsParams) WithTimeout(timeout time.Duration) *DesrcibeTagsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the desrcibe tags params +func (o *DesrcibeTagsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the desrcibe tags params +func (o *DesrcibeTagsParams) WithContext(ctx context.Context) *DesrcibeTagsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the desrcibe tags params +func (o *DesrcibeTagsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the desrcibe tags params +func (o *DesrcibeTagsParams) WithHTTPClient(client *http.Client) *DesrcibeTagsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the desrcibe tags params +func (o *DesrcibeTagsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the desrcibe tags params +func (o *DesrcibeTagsParams) WithAuthorization(authorization string) *DesrcibeTagsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the desrcibe tags params +func (o *DesrcibeTagsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the desrcibe tags params +func (o *DesrcibeTagsParams) WithBmpLanguage(bmpLanguage *string) *DesrcibeTagsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the desrcibe tags params +func (o *DesrcibeTagsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the desrcibe tags params +func (o *DesrcibeTagsParams) WithBmpUserID(bmpUserID *string) *DesrcibeTagsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the desrcibe tags params +func (o *DesrcibeTagsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the desrcibe tags params +func (o *DesrcibeTagsParams) WithInstanceID(instanceID string) *DesrcibeTagsParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the desrcibe tags params +func (o *DesrcibeTagsParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTagName adds the tagName to the desrcibe tags params +func (o *DesrcibeTagsParams) WithTagName(tagName string) *DesrcibeTagsParams { + o.SetTagName(tagName) + return o +} + +// SetTagName adds the tagName to the desrcibe tags params +func (o *DesrcibeTagsParams) SetTagName(tagName string) { + o.TagName = tagName +} + +// WithTraceID adds the traceID to the desrcibe tags params +func (o *DesrcibeTagsParams) WithTraceID(traceID string) *DesrcibeTagsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the desrcibe tags params +func (o *DesrcibeTagsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DesrcibeTagsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // query param instanceId + qrInstanceID := o.InstanceID + qInstanceID := qrInstanceID + if qInstanceID != "" { + + if err := r.SetQueryParam("instanceId", qInstanceID); err != nil { + return err + } + } + + // query param tagName + qrTagName := o.TagName + qTagName := qrTagName + if qTagName != "" { + + if err := r.SetQueryParam("tagName", qTagName); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_proxy/desrcibe_tags_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_proxy/desrcibe_tags_responses.go new file mode 100644 index 0000000..3bbea2c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_proxy/desrcibe_tags_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_proxy + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DesrcibeTagsReader is a Reader for the DesrcibeTags structure. +type DesrcibeTagsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DesrcibeTagsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDesrcibeTagsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDesrcibeTagsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDesrcibeTagsOK creates a DesrcibeTagsOK with default headers values +func NewDesrcibeTagsOK() *DesrcibeTagsOK { + return &DesrcibeTagsOK{} +} + +/* DesrcibeTagsOK describes a response with status code 200, with default header values. + +DesrcibeTagsOK desrcibe tags o k +*/ +type DesrcibeTagsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DesrcibeTagsOKBody +} + +// IsSuccess returns true when this desrcibe tags o k response has a 2xx status code +func (o *DesrcibeTagsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this desrcibe tags o k response has a 3xx status code +func (o *DesrcibeTagsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this desrcibe tags o k response has a 4xx status code +func (o *DesrcibeTagsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this desrcibe tags o k response has a 5xx status code +func (o *DesrcibeTagsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this desrcibe tags o k response a status code equal to that given +func (o *DesrcibeTagsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DesrcibeTagsOK) Error() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeTags][%d] desrcibeTagsOK %+v", 200, o.Payload) +} + +func (o *DesrcibeTagsOK) String() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeTags][%d] desrcibeTagsOK %+v", 200, o.Payload) +} + +func (o *DesrcibeTagsOK) GetPayload() *DesrcibeTagsOKBody { + return o.Payload +} + +func (o *DesrcibeTagsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DesrcibeTagsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDesrcibeTagsDefault creates a DesrcibeTagsDefault with default headers values +func NewDesrcibeTagsDefault(code int) *DesrcibeTagsDefault { + return &DesrcibeTagsDefault{ + _statusCode: code, + } +} + +/* DesrcibeTagsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DesrcibeTagsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DesrcibeTagsDefaultBody +} + +// Code gets the status code for the desrcibe tags default response +func (o *DesrcibeTagsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this desrcibe tags default response has a 2xx status code +func (o *DesrcibeTagsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this desrcibe tags default response has a 3xx status code +func (o *DesrcibeTagsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this desrcibe tags default response has a 4xx status code +func (o *DesrcibeTagsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this desrcibe tags default response has a 5xx status code +func (o *DesrcibeTagsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this desrcibe tags default response a status code equal to that given +func (o *DesrcibeTagsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DesrcibeTagsDefault) Error() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeTags][%d] desrcibeTags default %+v", o._statusCode, o.Payload) +} + +func (o *DesrcibeTagsDefault) String() string { + return fmt.Sprintf("[GET /monitorProxy/desrcibeTags][%d] desrcibeTags default %+v", o._statusCode, o.Payload) +} + +func (o *DesrcibeTagsDefault) GetPayload() *DesrcibeTagsDefaultBody { + return o.Payload +} + +func (o *DesrcibeTagsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DesrcibeTagsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DesrcibeTagsDefaultBody desrcibe tags default body +swagger:model DesrcibeTagsDefaultBody +*/ +type DesrcibeTagsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this desrcibe tags default body +func (o *DesrcibeTagsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeTagsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("desrcibeTags default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DesrcibeTagsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("desrcibeTags default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeTags default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeTags default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this desrcibe tags default body based on the context it is used +func (o *DesrcibeTagsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeTagsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeTags default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeTags default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DesrcibeTagsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DesrcibeTagsDefaultBody) UnmarshalBinary(b []byte) error { + var res DesrcibeTagsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DesrcibeTagsOKBody desrcibe tags o k body +swagger:model DesrcibeTagsOKBody +*/ +type DesrcibeTagsOKBody struct { + + // result + Result *models.TagsResponse `json:"result,omitempty"` +} + +// Validate validates this desrcibe tags o k body +func (o *DesrcibeTagsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeTagsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeTagsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeTagsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this desrcibe tags o k body based on the context it is used +func (o *DesrcibeTagsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DesrcibeTagsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("desrcibeTagsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("desrcibeTagsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DesrcibeTagsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DesrcibeTagsOKBody) UnmarshalBinary(b []byte) error { + var res DesrcibeTagsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_proxy/monitor_proxy_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_proxy/monitor_proxy_client.go new file mode 100644 index 0000000..548eb1f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_proxy/monitor_proxy_client.go @@ -0,0 +1,117 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_proxy + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new monitor proxy API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for monitor proxy API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DesrcibeAgentStatus(params *DesrcibeAgentStatusParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DesrcibeAgentStatusOK, error) + + DesrcibeTags(params *DesrcibeTagsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DesrcibeTagsOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DesrcibeAgentStatus DesrcibeAgentStatus 获取agent状态 +*/ +func (a *Client) DesrcibeAgentStatus(params *DesrcibeAgentStatusParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DesrcibeAgentStatusOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDesrcibeAgentStatusParams() + } + op := &runtime.ClientOperation{ + ID: "desrcibeAgentStatus", + Method: "GET", + PathPattern: "/monitorProxy/desrcibeAgentStatus", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DesrcibeAgentStatusReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DesrcibeAgentStatusOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DesrcibeAgentStatusDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DesrcibeTags DesrcibeAgentStatus 获取tag列表 +*/ +func (a *Client) DesrcibeTags(params *DesrcibeTagsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DesrcibeTagsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDesrcibeTagsParams() + } + op := &runtime.ClientOperation{ + ID: "desrcibeTags", + Method: "GET", + PathPattern: "/monitorProxy/desrcibeTags", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DesrcibeTagsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DesrcibeTagsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DesrcibeTagsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/add_rule_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/add_rule_parameters.go new file mode 100644 index 0000000..fcfbfc5 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/add_rule_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewAddRuleParams creates a new AddRuleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewAddRuleParams() *AddRuleParams { + return &AddRuleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewAddRuleParamsWithTimeout creates a new AddRuleParams object +// with the ability to set a timeout on a request. +func NewAddRuleParamsWithTimeout(timeout time.Duration) *AddRuleParams { + return &AddRuleParams{ + timeout: timeout, + } +} + +// NewAddRuleParamsWithContext creates a new AddRuleParams object +// with the ability to set a context for a request. +func NewAddRuleParamsWithContext(ctx context.Context) *AddRuleParams { + return &AddRuleParams{ + Context: ctx, + } +} + +// NewAddRuleParamsWithHTTPClient creates a new AddRuleParams object +// with the ability to set a custom HTTPClient for a request. +func NewAddRuleParamsWithHTTPClient(client *http.Client) *AddRuleParams { + return &AddRuleParams{ + HTTPClient: client, + } +} + +/* AddRuleParams contains all the parameters to send to the API endpoint + for the add rule operation. + + Typically these are written to a http.Request. +*/ +type AddRuleParams struct { + + // Body. + Body *models.AddRuleRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the add rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AddRuleParams) WithDefaults() *AddRuleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the add rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AddRuleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the add rule params +func (o *AddRuleParams) WithTimeout(timeout time.Duration) *AddRuleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the add rule params +func (o *AddRuleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the add rule params +func (o *AddRuleParams) WithContext(ctx context.Context) *AddRuleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the add rule params +func (o *AddRuleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the add rule params +func (o *AddRuleParams) WithHTTPClient(client *http.Client) *AddRuleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the add rule params +func (o *AddRuleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the add rule params +func (o *AddRuleParams) WithBody(body *models.AddRuleRequest) *AddRuleParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the add rule params +func (o *AddRuleParams) SetBody(body *models.AddRuleRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the add rule params +func (o *AddRuleParams) WithAuthorization(authorization string) *AddRuleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the add rule params +func (o *AddRuleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the add rule params +func (o *AddRuleParams) WithBmpLanguage(bmpLanguage *string) *AddRuleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the add rule params +func (o *AddRuleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the add rule params +func (o *AddRuleParams) WithBmpUserID(bmpUserID *string) *AddRuleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the add rule params +func (o *AddRuleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the add rule params +func (o *AddRuleParams) WithTraceID(traceID string) *AddRuleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the add rule params +func (o *AddRuleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *AddRuleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/add_rule_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/add_rule_responses.go new file mode 100644 index 0000000..b6cc49d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/add_rule_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// AddRuleReader is a Reader for the AddRule structure. +type AddRuleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *AddRuleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewAddRuleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewAddRuleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewAddRuleOK creates a AddRuleOK with default headers values +func NewAddRuleOK() *AddRuleOK { + return &AddRuleOK{} +} + +/* AddRuleOK describes a response with status code 200, with default header values. + +A AddRuleResult is an response struct that is used to describe create rule result. +*/ +type AddRuleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *AddRuleOKBody +} + +// IsSuccess returns true when this add rule o k response has a 2xx status code +func (o *AddRuleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this add rule o k response has a 3xx status code +func (o *AddRuleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this add rule o k response has a 4xx status code +func (o *AddRuleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this add rule o k response has a 5xx status code +func (o *AddRuleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this add rule o k response a status code equal to that given +func (o *AddRuleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *AddRuleOK) Error() string { + return fmt.Sprintf("[POST /monitorRule/addRule][%d] addRuleOK %+v", 200, o.Payload) +} + +func (o *AddRuleOK) String() string { + return fmt.Sprintf("[POST /monitorRule/addRule][%d] addRuleOK %+v", 200, o.Payload) +} + +func (o *AddRuleOK) GetPayload() *AddRuleOKBody { + return o.Payload +} + +func (o *AddRuleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AddRuleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAddRuleDefault creates a AddRuleDefault with default headers values +func NewAddRuleDefault(code int) *AddRuleDefault { + return &AddRuleDefault{ + _statusCode: code, + } +} + +/* AddRuleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type AddRuleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *AddRuleDefaultBody +} + +// Code gets the status code for the add rule default response +func (o *AddRuleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this add rule default response has a 2xx status code +func (o *AddRuleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this add rule default response has a 3xx status code +func (o *AddRuleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this add rule default response has a 4xx status code +func (o *AddRuleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this add rule default response has a 5xx status code +func (o *AddRuleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this add rule default response a status code equal to that given +func (o *AddRuleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *AddRuleDefault) Error() string { + return fmt.Sprintf("[POST /monitorRule/addRule][%d] addRule default %+v", o._statusCode, o.Payload) +} + +func (o *AddRuleDefault) String() string { + return fmt.Sprintf("[POST /monitorRule/addRule][%d] addRule default %+v", o._statusCode, o.Payload) +} + +func (o *AddRuleDefault) GetPayload() *AddRuleDefaultBody { + return o.Payload +} + +func (o *AddRuleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AddRuleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*AddRuleDefaultBody add rule default body +swagger:model AddRuleDefaultBody +*/ +type AddRuleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this add rule default body +func (o *AddRuleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AddRuleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("addRule default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *AddRuleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("addRule default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("addRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("addRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this add rule default body based on the context it is used +func (o *AddRuleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AddRuleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("addRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("addRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AddRuleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AddRuleDefaultBody) UnmarshalBinary(b []byte) error { + var res AddRuleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*AddRuleOKBody add rule o k body +swagger:model AddRuleOKBody +*/ +type AddRuleOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this add rule o k body +func (o *AddRuleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AddRuleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("addRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("addRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this add rule o k body based on the context it is used +func (o *AddRuleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AddRuleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("addRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("addRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AddRuleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AddRuleOKBody) UnmarshalBinary(b []byte) error { + var res AddRuleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/delete_rule_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/delete_rule_parameters.go new file mode 100644 index 0000000..f5de280 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/delete_rule_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewDeleteRuleParams creates a new DeleteRuleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteRuleParams() *DeleteRuleParams { + return &DeleteRuleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteRuleParamsWithTimeout creates a new DeleteRuleParams object +// with the ability to set a timeout on a request. +func NewDeleteRuleParamsWithTimeout(timeout time.Duration) *DeleteRuleParams { + return &DeleteRuleParams{ + timeout: timeout, + } +} + +// NewDeleteRuleParamsWithContext creates a new DeleteRuleParams object +// with the ability to set a context for a request. +func NewDeleteRuleParamsWithContext(ctx context.Context) *DeleteRuleParams { + return &DeleteRuleParams{ + Context: ctx, + } +} + +// NewDeleteRuleParamsWithHTTPClient creates a new DeleteRuleParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteRuleParamsWithHTTPClient(client *http.Client) *DeleteRuleParams { + return &DeleteRuleParams{ + HTTPClient: client, + } +} + +/* DeleteRuleParams contains all the parameters to send to the API endpoint + for the delete rule operation. + + Typically these are written to a http.Request. +*/ +type DeleteRuleParams struct { + + // Body. + Body *models.DeleteRuleRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteRuleParams) WithDefaults() *DeleteRuleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteRuleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete rule params +func (o *DeleteRuleParams) WithTimeout(timeout time.Duration) *DeleteRuleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete rule params +func (o *DeleteRuleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete rule params +func (o *DeleteRuleParams) WithContext(ctx context.Context) *DeleteRuleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete rule params +func (o *DeleteRuleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete rule params +func (o *DeleteRuleParams) WithHTTPClient(client *http.Client) *DeleteRuleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete rule params +func (o *DeleteRuleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the delete rule params +func (o *DeleteRuleParams) WithBody(body *models.DeleteRuleRequest) *DeleteRuleParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the delete rule params +func (o *DeleteRuleParams) SetBody(body *models.DeleteRuleRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the delete rule params +func (o *DeleteRuleParams) WithAuthorization(authorization string) *DeleteRuleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete rule params +func (o *DeleteRuleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete rule params +func (o *DeleteRuleParams) WithBmpLanguage(bmpLanguage *string) *DeleteRuleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete rule params +func (o *DeleteRuleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete rule params +func (o *DeleteRuleParams) WithBmpUserID(bmpUserID *string) *DeleteRuleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete rule params +func (o *DeleteRuleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete rule params +func (o *DeleteRuleParams) WithTraceID(traceID string) *DeleteRuleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete rule params +func (o *DeleteRuleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteRuleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/delete_rule_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/delete_rule_responses.go new file mode 100644 index 0000000..411e0d1 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/delete_rule_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteRuleReader is a Reader for the DeleteRule structure. +type DeleteRuleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteRuleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteRuleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteRuleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteRuleOK creates a DeleteRuleOK with default headers values +func NewDeleteRuleOK() *DeleteRuleOK { + return &DeleteRuleOK{} +} + +/* DeleteRuleOK describes a response with status code 200, with default header values. + +A DeleteRuleResult is an response struct that is used to describe create rule result. +*/ +type DeleteRuleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteRuleOKBody +} + +// IsSuccess returns true when this delete rule o k response has a 2xx status code +func (o *DeleteRuleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete rule o k response has a 3xx status code +func (o *DeleteRuleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete rule o k response has a 4xx status code +func (o *DeleteRuleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete rule o k response has a 5xx status code +func (o *DeleteRuleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete rule o k response a status code equal to that given +func (o *DeleteRuleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteRuleOK) Error() string { + return fmt.Sprintf("[DELETE /monitorRule/deleteRule][%d] deleteRuleOK %+v", 200, o.Payload) +} + +func (o *DeleteRuleOK) String() string { + return fmt.Sprintf("[DELETE /monitorRule/deleteRule][%d] deleteRuleOK %+v", 200, o.Payload) +} + +func (o *DeleteRuleOK) GetPayload() *DeleteRuleOKBody { + return o.Payload +} + +func (o *DeleteRuleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteRuleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteRuleDefault creates a DeleteRuleDefault with default headers values +func NewDeleteRuleDefault(code int) *DeleteRuleDefault { + return &DeleteRuleDefault{ + _statusCode: code, + } +} + +/* DeleteRuleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteRuleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteRuleDefaultBody +} + +// Code gets the status code for the delete rule default response +func (o *DeleteRuleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete rule default response has a 2xx status code +func (o *DeleteRuleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete rule default response has a 3xx status code +func (o *DeleteRuleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete rule default response has a 4xx status code +func (o *DeleteRuleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete rule default response has a 5xx status code +func (o *DeleteRuleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete rule default response a status code equal to that given +func (o *DeleteRuleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteRuleDefault) Error() string { + return fmt.Sprintf("[DELETE /monitorRule/deleteRule][%d] deleteRule default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteRuleDefault) String() string { + return fmt.Sprintf("[DELETE /monitorRule/deleteRule][%d] deleteRule default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteRuleDefault) GetPayload() *DeleteRuleDefaultBody { + return o.Payload +} + +func (o *DeleteRuleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteRuleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteRuleDefaultBody delete rule default body +swagger:model DeleteRuleDefaultBody +*/ +type DeleteRuleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete rule default body +func (o *DeleteRuleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRuleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteRule default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteRuleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteRule default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete rule default body based on the context it is used +func (o *DeleteRuleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRuleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteRuleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteRuleDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteRuleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteRuleOKBody delete rule o k body +swagger:model DeleteRuleOKBody +*/ +type DeleteRuleOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete rule o k body +func (o *DeleteRuleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRuleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete rule o k body based on the context it is used +func (o *DeleteRuleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRuleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteRuleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteRuleOKBody) UnmarshalBinary(b []byte) error { + var res DeleteRuleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/describe_rule_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/describe_rule_parameters.go new file mode 100644 index 0000000..b568b57 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/describe_rule_parameters.go @@ -0,0 +1,248 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeRuleParams creates a new DescribeRuleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeRuleParams() *DescribeRuleParams { + return &DescribeRuleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeRuleParamsWithTimeout creates a new DescribeRuleParams object +// with the ability to set a timeout on a request. +func NewDescribeRuleParamsWithTimeout(timeout time.Duration) *DescribeRuleParams { + return &DescribeRuleParams{ + timeout: timeout, + } +} + +// NewDescribeRuleParamsWithContext creates a new DescribeRuleParams object +// with the ability to set a context for a request. +func NewDescribeRuleParamsWithContext(ctx context.Context) *DescribeRuleParams { + return &DescribeRuleParams{ + Context: ctx, + } +} + +// NewDescribeRuleParamsWithHTTPClient creates a new DescribeRuleParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeRuleParamsWithHTTPClient(client *http.Client) *DescribeRuleParams { + return &DescribeRuleParams{ + HTTPClient: client, + } +} + +/* DescribeRuleParams contains all the parameters to send to the API endpoint + for the describe rule operation. + + Typically these are written to a http.Request. +*/ +type DescribeRuleParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* RuleID. + + rule uuid + */ + RuleID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRuleParams) WithDefaults() *DescribeRuleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRuleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe rule params +func (o *DescribeRuleParams) WithTimeout(timeout time.Duration) *DescribeRuleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe rule params +func (o *DescribeRuleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe rule params +func (o *DescribeRuleParams) WithContext(ctx context.Context) *DescribeRuleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe rule params +func (o *DescribeRuleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe rule params +func (o *DescribeRuleParams) WithHTTPClient(client *http.Client) *DescribeRuleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe rule params +func (o *DescribeRuleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe rule params +func (o *DescribeRuleParams) WithAuthorization(authorization string) *DescribeRuleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe rule params +func (o *DescribeRuleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe rule params +func (o *DescribeRuleParams) WithBmpLanguage(bmpLanguage *string) *DescribeRuleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe rule params +func (o *DescribeRuleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe rule params +func (o *DescribeRuleParams) WithBmpUserID(bmpUserID *string) *DescribeRuleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe rule params +func (o *DescribeRuleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithRuleID adds the ruleID to the describe rule params +func (o *DescribeRuleParams) WithRuleID(ruleID string) *DescribeRuleParams { + o.SetRuleID(ruleID) + return o +} + +// SetRuleID adds the ruleId to the describe rule params +func (o *DescribeRuleParams) SetRuleID(ruleID string) { + o.RuleID = ruleID +} + +// WithTraceID adds the traceID to the describe rule params +func (o *DescribeRuleParams) WithTraceID(traceID string) *DescribeRuleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe rule params +func (o *DescribeRuleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeRuleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // query param ruleId + qrRuleID := o.RuleID + qRuleID := qrRuleID + if qRuleID != "" { + + if err := r.SetQueryParam("ruleId", qRuleID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/describe_rule_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/describe_rule_responses.go new file mode 100644 index 0000000..d82521e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/describe_rule_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeRuleReader is a Reader for the DescribeRule structure. +type DescribeRuleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeRuleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeRuleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeRuleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeRuleOK creates a DescribeRuleOK with default headers values +func NewDescribeRuleOK() *DescribeRuleOK { + return &DescribeRuleOK{} +} + +/* DescribeRuleOK describes a response with status code 200, with default header values. + +A DescribeRuleResult is an response struct that is used to describe get rule. +*/ +type DescribeRuleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRuleOKBody +} + +// IsSuccess returns true when this describe rule o k response has a 2xx status code +func (o *DescribeRuleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe rule o k response has a 3xx status code +func (o *DescribeRuleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe rule o k response has a 4xx status code +func (o *DescribeRuleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe rule o k response has a 5xx status code +func (o *DescribeRuleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe rule o k response a status code equal to that given +func (o *DescribeRuleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeRuleOK) Error() string { + return fmt.Sprintf("[GET /monitorRule/describeRule][%d] describeRuleOK %+v", 200, o.Payload) +} + +func (o *DescribeRuleOK) String() string { + return fmt.Sprintf("[GET /monitorRule/describeRule][%d] describeRuleOK %+v", 200, o.Payload) +} + +func (o *DescribeRuleOK) GetPayload() *DescribeRuleOKBody { + return o.Payload +} + +func (o *DescribeRuleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRuleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeRuleDefault creates a DescribeRuleDefault with default headers values +func NewDescribeRuleDefault(code int) *DescribeRuleDefault { + return &DescribeRuleDefault{ + _statusCode: code, + } +} + +/* DescribeRuleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeRuleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRuleDefaultBody +} + +// Code gets the status code for the describe rule default response +func (o *DescribeRuleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe rule default response has a 2xx status code +func (o *DescribeRuleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe rule default response has a 3xx status code +func (o *DescribeRuleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe rule default response has a 4xx status code +func (o *DescribeRuleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe rule default response has a 5xx status code +func (o *DescribeRuleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe rule default response a status code equal to that given +func (o *DescribeRuleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeRuleDefault) Error() string { + return fmt.Sprintf("[GET /monitorRule/describeRule][%d] describeRule default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRuleDefault) String() string { + return fmt.Sprintf("[GET /monitorRule/describeRule][%d] describeRule default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRuleDefault) GetPayload() *DescribeRuleDefaultBody { + return o.Payload +} + +func (o *DescribeRuleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRuleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeRuleDefaultBody describe rule default body +swagger:model DescribeRuleDefaultBody +*/ +type DescribeRuleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe rule default body +func (o *DescribeRuleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRuleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeRule default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeRuleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeRule default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe rule default body based on the context it is used +func (o *DescribeRuleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRuleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRuleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRuleDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeRuleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeRuleOKBody describe rule o k body +swagger:model DescribeRuleOKBody +*/ +type DescribeRuleOKBody struct { + + // result + Result *models.Rule `json:"result,omitempty"` +} + +// Validate validates this describe rule o k body +func (o *DescribeRuleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRuleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe rule o k body based on the context it is used +func (o *DescribeRuleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRuleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRuleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRuleOKBody) UnmarshalBinary(b []byte) error { + var res DescribeRuleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/describe_rules_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/describe_rules_parameters.go new file mode 100644 index 0000000..ad349a0 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/describe_rules_parameters.go @@ -0,0 +1,500 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeRulesParams creates a new DescribeRulesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeRulesParams() *DescribeRulesParams { + return &DescribeRulesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeRulesParamsWithTimeout creates a new DescribeRulesParams object +// with the ability to set a timeout on a request. +func NewDescribeRulesParamsWithTimeout(timeout time.Duration) *DescribeRulesParams { + return &DescribeRulesParams{ + timeout: timeout, + } +} + +// NewDescribeRulesParamsWithContext creates a new DescribeRulesParams object +// with the ability to set a context for a request. +func NewDescribeRulesParamsWithContext(ctx context.Context) *DescribeRulesParams { + return &DescribeRulesParams{ + Context: ctx, + } +} + +// NewDescribeRulesParamsWithHTTPClient creates a new DescribeRulesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeRulesParamsWithHTTPClient(client *http.Client) *DescribeRulesParams { + return &DescribeRulesParams{ + HTTPClient: client, + } +} + +/* DescribeRulesParams contains all the parameters to send to the API endpoint + for the describe rules operation. + + Typically these are written to a http.Request. +*/ +type DescribeRulesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否显示全部,取值为1时表示全部 + */ + IsAll *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* RuleID. + + 规则uuid + */ + RuleID *string + + /* RuleName. + + 规则名称 + */ + RuleName *string + + /* Status. + + 1 正常,2 禁用,3 报警 + + Format: int64 + */ + Status *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserID. + + user uuid + */ + UserID *string + + /* UserName. + + username + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe rules params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRulesParams) WithDefaults() *DescribeRulesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe rules params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRulesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe rules params +func (o *DescribeRulesParams) WithTimeout(timeout time.Duration) *DescribeRulesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe rules params +func (o *DescribeRulesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe rules params +func (o *DescribeRulesParams) WithContext(ctx context.Context) *DescribeRulesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe rules params +func (o *DescribeRulesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe rules params +func (o *DescribeRulesParams) WithHTTPClient(client *http.Client) *DescribeRulesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe rules params +func (o *DescribeRulesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe rules params +func (o *DescribeRulesParams) WithAuthorization(authorization string) *DescribeRulesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe rules params +func (o *DescribeRulesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe rules params +func (o *DescribeRulesParams) WithBmpLanguage(bmpLanguage *string) *DescribeRulesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe rules params +func (o *DescribeRulesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe rules params +func (o *DescribeRulesParams) WithBmpUserID(bmpUserID *string) *DescribeRulesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe rules params +func (o *DescribeRulesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe rules params +func (o *DescribeRulesParams) WithIsAll(isAll *string) *DescribeRulesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe rules params +func (o *DescribeRulesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithPageNumber adds the pageNumber to the describe rules params +func (o *DescribeRulesParams) WithPageNumber(pageNumber *int64) *DescribeRulesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe rules params +func (o *DescribeRulesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe rules params +func (o *DescribeRulesParams) WithPageSize(pageSize *int64) *DescribeRulesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe rules params +func (o *DescribeRulesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithRuleID adds the ruleID to the describe rules params +func (o *DescribeRulesParams) WithRuleID(ruleID *string) *DescribeRulesParams { + o.SetRuleID(ruleID) + return o +} + +// SetRuleID adds the ruleId to the describe rules params +func (o *DescribeRulesParams) SetRuleID(ruleID *string) { + o.RuleID = ruleID +} + +// WithRuleName adds the ruleName to the describe rules params +func (o *DescribeRulesParams) WithRuleName(ruleName *string) *DescribeRulesParams { + o.SetRuleName(ruleName) + return o +} + +// SetRuleName adds the ruleName to the describe rules params +func (o *DescribeRulesParams) SetRuleName(ruleName *string) { + o.RuleName = ruleName +} + +// WithStatus adds the status to the describe rules params +func (o *DescribeRulesParams) WithStatus(status *int64) *DescribeRulesParams { + o.SetStatus(status) + return o +} + +// SetStatus adds the status to the describe rules params +func (o *DescribeRulesParams) SetStatus(status *int64) { + o.Status = status +} + +// WithTraceID adds the traceID to the describe rules params +func (o *DescribeRulesParams) WithTraceID(traceID string) *DescribeRulesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe rules params +func (o *DescribeRulesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserID adds the userID to the describe rules params +func (o *DescribeRulesParams) WithUserID(userID *string) *DescribeRulesParams { + o.SetUserID(userID) + return o +} + +// SetUserID adds the userId to the describe rules params +func (o *DescribeRulesParams) SetUserID(userID *string) { + o.UserID = userID +} + +// WithUserName adds the userName to the describe rules params +func (o *DescribeRulesParams) WithUserName(userName *string) *DescribeRulesParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe rules params +func (o *DescribeRulesParams) SetUserName(userName *string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeRulesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.RuleID != nil { + + // query param ruleId + var qrRuleID string + + if o.RuleID != nil { + qrRuleID = *o.RuleID + } + qRuleID := qrRuleID + if qRuleID != "" { + + if err := r.SetQueryParam("ruleId", qRuleID); err != nil { + return err + } + } + } + + if o.RuleName != nil { + + // query param ruleName + var qrRuleName string + + if o.RuleName != nil { + qrRuleName = *o.RuleName + } + qRuleName := qrRuleName + if qRuleName != "" { + + if err := r.SetQueryParam("ruleName", qRuleName); err != nil { + return err + } + } + } + + if o.Status != nil { + + // query param status + var qrStatus int64 + + if o.Status != nil { + qrStatus = *o.Status + } + qStatus := swag.FormatInt64(qrStatus) + if qStatus != "" { + + if err := r.SetQueryParam("status", qStatus); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserID != nil { + + // query param userId + var qrUserID string + + if o.UserID != nil { + qrUserID = *o.UserID + } + qUserID := qrUserID + if qUserID != "" { + + if err := r.SetQueryParam("userId", qUserID); err != nil { + return err + } + } + } + + if o.UserName != nil { + + // query param userName + var qrUserName string + + if o.UserName != nil { + qrUserName = *o.UserName + } + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/describe_rules_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/describe_rules_responses.go new file mode 100644 index 0000000..0f59b05 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/describe_rules_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeRulesReader is a Reader for the DescribeRules structure. +type DescribeRulesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeRulesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeRulesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeRulesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeRulesOK creates a DescribeRulesOK with default headers values +func NewDescribeRulesOK() *DescribeRulesOK { + return &DescribeRulesOK{} +} + +/* DescribeRulesOK describes a response with status code 200, with default header values. + +A DescribeRuleResult is an response struct that is used to describe get rule. +*/ +type DescribeRulesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRulesOKBody +} + +// IsSuccess returns true when this describe rules o k response has a 2xx status code +func (o *DescribeRulesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe rules o k response has a 3xx status code +func (o *DescribeRulesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe rules o k response has a 4xx status code +func (o *DescribeRulesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe rules o k response has a 5xx status code +func (o *DescribeRulesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe rules o k response a status code equal to that given +func (o *DescribeRulesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeRulesOK) Error() string { + return fmt.Sprintf("[GET /monitorRule/describeRules][%d] describeRulesOK %+v", 200, o.Payload) +} + +func (o *DescribeRulesOK) String() string { + return fmt.Sprintf("[GET /monitorRule/describeRules][%d] describeRulesOK %+v", 200, o.Payload) +} + +func (o *DescribeRulesOK) GetPayload() *DescribeRulesOKBody { + return o.Payload +} + +func (o *DescribeRulesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRulesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeRulesDefault creates a DescribeRulesDefault with default headers values +func NewDescribeRulesDefault(code int) *DescribeRulesDefault { + return &DescribeRulesDefault{ + _statusCode: code, + } +} + +/* DescribeRulesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeRulesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRulesDefaultBody +} + +// Code gets the status code for the describe rules default response +func (o *DescribeRulesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe rules default response has a 2xx status code +func (o *DescribeRulesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe rules default response has a 3xx status code +func (o *DescribeRulesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe rules default response has a 4xx status code +func (o *DescribeRulesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe rules default response has a 5xx status code +func (o *DescribeRulesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe rules default response a status code equal to that given +func (o *DescribeRulesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeRulesDefault) Error() string { + return fmt.Sprintf("[GET /monitorRule/describeRules][%d] describeRules default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRulesDefault) String() string { + return fmt.Sprintf("[GET /monitorRule/describeRules][%d] describeRules default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRulesDefault) GetPayload() *DescribeRulesDefaultBody { + return o.Payload +} + +func (o *DescribeRulesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRulesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeRulesDefaultBody describe rules default body +swagger:model DescribeRulesDefaultBody +*/ +type DescribeRulesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe rules default body +func (o *DescribeRulesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRulesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeRules default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeRulesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeRules default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRules default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRules default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe rules default body based on the context it is used +func (o *DescribeRulesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRulesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRules default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRules default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRulesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRulesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeRulesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeRulesOKBody describe rules o k body +swagger:model DescribeRulesOKBody +*/ +type DescribeRulesOKBody struct { + + // result + Result *models.RuleList `json:"result,omitempty"` +} + +// Validate validates this describe rules o k body +func (o *DescribeRulesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRulesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRulesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRulesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe rules o k body based on the context it is used +func (o *DescribeRulesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRulesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRulesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRulesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRulesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRulesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeRulesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/disable_rule_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/disable_rule_parameters.go new file mode 100644 index 0000000..49db569 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/disable_rule_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewDisableRuleParams creates a new DisableRuleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDisableRuleParams() *DisableRuleParams { + return &DisableRuleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDisableRuleParamsWithTimeout creates a new DisableRuleParams object +// with the ability to set a timeout on a request. +func NewDisableRuleParamsWithTimeout(timeout time.Duration) *DisableRuleParams { + return &DisableRuleParams{ + timeout: timeout, + } +} + +// NewDisableRuleParamsWithContext creates a new DisableRuleParams object +// with the ability to set a context for a request. +func NewDisableRuleParamsWithContext(ctx context.Context) *DisableRuleParams { + return &DisableRuleParams{ + Context: ctx, + } +} + +// NewDisableRuleParamsWithHTTPClient creates a new DisableRuleParams object +// with the ability to set a custom HTTPClient for a request. +func NewDisableRuleParamsWithHTTPClient(client *http.Client) *DisableRuleParams { + return &DisableRuleParams{ + HTTPClient: client, + } +} + +/* DisableRuleParams contains all the parameters to send to the API endpoint + for the disable rule operation. + + Typically these are written to a http.Request. +*/ +type DisableRuleParams struct { + + // Body. + Body *models.DisableRuleRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the disable rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DisableRuleParams) WithDefaults() *DisableRuleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the disable rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DisableRuleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the disable rule params +func (o *DisableRuleParams) WithTimeout(timeout time.Duration) *DisableRuleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the disable rule params +func (o *DisableRuleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the disable rule params +func (o *DisableRuleParams) WithContext(ctx context.Context) *DisableRuleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the disable rule params +func (o *DisableRuleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the disable rule params +func (o *DisableRuleParams) WithHTTPClient(client *http.Client) *DisableRuleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the disable rule params +func (o *DisableRuleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the disable rule params +func (o *DisableRuleParams) WithBody(body *models.DisableRuleRequest) *DisableRuleParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the disable rule params +func (o *DisableRuleParams) SetBody(body *models.DisableRuleRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the disable rule params +func (o *DisableRuleParams) WithAuthorization(authorization string) *DisableRuleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the disable rule params +func (o *DisableRuleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the disable rule params +func (o *DisableRuleParams) WithBmpLanguage(bmpLanguage *string) *DisableRuleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the disable rule params +func (o *DisableRuleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the disable rule params +func (o *DisableRuleParams) WithBmpUserID(bmpUserID *string) *DisableRuleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the disable rule params +func (o *DisableRuleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the disable rule params +func (o *DisableRuleParams) WithTraceID(traceID string) *DisableRuleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the disable rule params +func (o *DisableRuleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DisableRuleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/disable_rule_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/disable_rule_responses.go new file mode 100644 index 0000000..4f2b738 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/disable_rule_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DisableRuleReader is a Reader for the DisableRule structure. +type DisableRuleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DisableRuleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDisableRuleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDisableRuleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDisableRuleOK creates a DisableRuleOK with default headers values +func NewDisableRuleOK() *DisableRuleOK { + return &DisableRuleOK{} +} + +/* DisableRuleOK describes a response with status code 200, with default header values. + +A DisableRuleResult is an response struct that is used to describe create rule result. +*/ +type DisableRuleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DisableRuleOKBody +} + +// IsSuccess returns true when this disable rule o k response has a 2xx status code +func (o *DisableRuleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this disable rule o k response has a 3xx status code +func (o *DisableRuleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this disable rule o k response has a 4xx status code +func (o *DisableRuleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this disable rule o k response has a 5xx status code +func (o *DisableRuleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this disable rule o k response a status code equal to that given +func (o *DisableRuleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DisableRuleOK) Error() string { + return fmt.Sprintf("[PUT /monitorRule/disableRule][%d] disableRuleOK %+v", 200, o.Payload) +} + +func (o *DisableRuleOK) String() string { + return fmt.Sprintf("[PUT /monitorRule/disableRule][%d] disableRuleOK %+v", 200, o.Payload) +} + +func (o *DisableRuleOK) GetPayload() *DisableRuleOKBody { + return o.Payload +} + +func (o *DisableRuleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DisableRuleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDisableRuleDefault creates a DisableRuleDefault with default headers values +func NewDisableRuleDefault(code int) *DisableRuleDefault { + return &DisableRuleDefault{ + _statusCode: code, + } +} + +/* DisableRuleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DisableRuleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DisableRuleDefaultBody +} + +// Code gets the status code for the disable rule default response +func (o *DisableRuleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this disable rule default response has a 2xx status code +func (o *DisableRuleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this disable rule default response has a 3xx status code +func (o *DisableRuleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this disable rule default response has a 4xx status code +func (o *DisableRuleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this disable rule default response has a 5xx status code +func (o *DisableRuleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this disable rule default response a status code equal to that given +func (o *DisableRuleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DisableRuleDefault) Error() string { + return fmt.Sprintf("[PUT /monitorRule/disableRule][%d] disableRule default %+v", o._statusCode, o.Payload) +} + +func (o *DisableRuleDefault) String() string { + return fmt.Sprintf("[PUT /monitorRule/disableRule][%d] disableRule default %+v", o._statusCode, o.Payload) +} + +func (o *DisableRuleDefault) GetPayload() *DisableRuleDefaultBody { + return o.Payload +} + +func (o *DisableRuleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DisableRuleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DisableRuleDefaultBody disable rule default body +swagger:model DisableRuleDefaultBody +*/ +type DisableRuleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this disable rule default body +func (o *DisableRuleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DisableRuleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("disableRule default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DisableRuleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("disableRule default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("disableRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("disableRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this disable rule default body based on the context it is used +func (o *DisableRuleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DisableRuleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("disableRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("disableRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DisableRuleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DisableRuleDefaultBody) UnmarshalBinary(b []byte) error { + var res DisableRuleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DisableRuleOKBody disable rule o k body +swagger:model DisableRuleOKBody +*/ +type DisableRuleOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this disable rule o k body +func (o *DisableRuleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DisableRuleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("disableRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("disableRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this disable rule o k body based on the context it is used +func (o *DisableRuleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DisableRuleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("disableRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("disableRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DisableRuleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DisableRuleOKBody) UnmarshalBinary(b []byte) error { + var res DisableRuleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/edit_rule_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/edit_rule_parameters.go new file mode 100644 index 0000000..54ccaf2 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/edit_rule_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewEditRuleParams creates a new EditRuleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewEditRuleParams() *EditRuleParams { + return &EditRuleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewEditRuleParamsWithTimeout creates a new EditRuleParams object +// with the ability to set a timeout on a request. +func NewEditRuleParamsWithTimeout(timeout time.Duration) *EditRuleParams { + return &EditRuleParams{ + timeout: timeout, + } +} + +// NewEditRuleParamsWithContext creates a new EditRuleParams object +// with the ability to set a context for a request. +func NewEditRuleParamsWithContext(ctx context.Context) *EditRuleParams { + return &EditRuleParams{ + Context: ctx, + } +} + +// NewEditRuleParamsWithHTTPClient creates a new EditRuleParams object +// with the ability to set a custom HTTPClient for a request. +func NewEditRuleParamsWithHTTPClient(client *http.Client) *EditRuleParams { + return &EditRuleParams{ + HTTPClient: client, + } +} + +/* EditRuleParams contains all the parameters to send to the API endpoint + for the edit rule operation. + + Typically these are written to a http.Request. +*/ +type EditRuleParams struct { + + // Body. + Body *models.EditRuleRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the edit rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *EditRuleParams) WithDefaults() *EditRuleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the edit rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *EditRuleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the edit rule params +func (o *EditRuleParams) WithTimeout(timeout time.Duration) *EditRuleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the edit rule params +func (o *EditRuleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the edit rule params +func (o *EditRuleParams) WithContext(ctx context.Context) *EditRuleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the edit rule params +func (o *EditRuleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the edit rule params +func (o *EditRuleParams) WithHTTPClient(client *http.Client) *EditRuleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the edit rule params +func (o *EditRuleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the edit rule params +func (o *EditRuleParams) WithBody(body *models.EditRuleRequest) *EditRuleParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the edit rule params +func (o *EditRuleParams) SetBody(body *models.EditRuleRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the edit rule params +func (o *EditRuleParams) WithAuthorization(authorization string) *EditRuleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the edit rule params +func (o *EditRuleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the edit rule params +func (o *EditRuleParams) WithBmpLanguage(bmpLanguage *string) *EditRuleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the edit rule params +func (o *EditRuleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the edit rule params +func (o *EditRuleParams) WithBmpUserID(bmpUserID *string) *EditRuleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the edit rule params +func (o *EditRuleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the edit rule params +func (o *EditRuleParams) WithTraceID(traceID string) *EditRuleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the edit rule params +func (o *EditRuleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *EditRuleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/edit_rule_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/edit_rule_responses.go new file mode 100644 index 0000000..2527f70 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/edit_rule_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// EditRuleReader is a Reader for the EditRule structure. +type EditRuleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *EditRuleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewEditRuleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewEditRuleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewEditRuleOK creates a EditRuleOK with default headers values +func NewEditRuleOK() *EditRuleOK { + return &EditRuleOK{} +} + +/* EditRuleOK describes a response with status code 200, with default header values. + +A EditRuleResult is an response struct that is used to describe create rule result. +*/ +type EditRuleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *EditRuleOKBody +} + +// IsSuccess returns true when this edit rule o k response has a 2xx status code +func (o *EditRuleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this edit rule o k response has a 3xx status code +func (o *EditRuleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this edit rule o k response has a 4xx status code +func (o *EditRuleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this edit rule o k response has a 5xx status code +func (o *EditRuleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this edit rule o k response a status code equal to that given +func (o *EditRuleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *EditRuleOK) Error() string { + return fmt.Sprintf("[PUT /monitorRule/editRule][%d] editRuleOK %+v", 200, o.Payload) +} + +func (o *EditRuleOK) String() string { + return fmt.Sprintf("[PUT /monitorRule/editRule][%d] editRuleOK %+v", 200, o.Payload) +} + +func (o *EditRuleOK) GetPayload() *EditRuleOKBody { + return o.Payload +} + +func (o *EditRuleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(EditRuleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewEditRuleDefault creates a EditRuleDefault with default headers values +func NewEditRuleDefault(code int) *EditRuleDefault { + return &EditRuleDefault{ + _statusCode: code, + } +} + +/* EditRuleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type EditRuleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *EditRuleDefaultBody +} + +// Code gets the status code for the edit rule default response +func (o *EditRuleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this edit rule default response has a 2xx status code +func (o *EditRuleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this edit rule default response has a 3xx status code +func (o *EditRuleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this edit rule default response has a 4xx status code +func (o *EditRuleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this edit rule default response has a 5xx status code +func (o *EditRuleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this edit rule default response a status code equal to that given +func (o *EditRuleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *EditRuleDefault) Error() string { + return fmt.Sprintf("[PUT /monitorRule/editRule][%d] editRule default %+v", o._statusCode, o.Payload) +} + +func (o *EditRuleDefault) String() string { + return fmt.Sprintf("[PUT /monitorRule/editRule][%d] editRule default %+v", o._statusCode, o.Payload) +} + +func (o *EditRuleDefault) GetPayload() *EditRuleDefaultBody { + return o.Payload +} + +func (o *EditRuleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(EditRuleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*EditRuleDefaultBody edit rule default body +swagger:model EditRuleDefaultBody +*/ +type EditRuleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this edit rule default body +func (o *EditRuleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EditRuleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("editRule default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *EditRuleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("editRule default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("editRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("editRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this edit rule default body based on the context it is used +func (o *EditRuleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EditRuleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("editRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("editRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *EditRuleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *EditRuleDefaultBody) UnmarshalBinary(b []byte) error { + var res EditRuleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*EditRuleOKBody edit rule o k body +swagger:model EditRuleOKBody +*/ +type EditRuleOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this edit rule o k body +func (o *EditRuleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EditRuleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("editRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("editRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this edit rule o k body based on the context it is used +func (o *EditRuleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EditRuleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("editRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("editRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *EditRuleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *EditRuleOKBody) UnmarshalBinary(b []byte) error { + var res EditRuleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/enable_rule_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/enable_rule_parameters.go new file mode 100644 index 0000000..afbd98b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/enable_rule_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewEnableRuleParams creates a new EnableRuleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewEnableRuleParams() *EnableRuleParams { + return &EnableRuleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewEnableRuleParamsWithTimeout creates a new EnableRuleParams object +// with the ability to set a timeout on a request. +func NewEnableRuleParamsWithTimeout(timeout time.Duration) *EnableRuleParams { + return &EnableRuleParams{ + timeout: timeout, + } +} + +// NewEnableRuleParamsWithContext creates a new EnableRuleParams object +// with the ability to set a context for a request. +func NewEnableRuleParamsWithContext(ctx context.Context) *EnableRuleParams { + return &EnableRuleParams{ + Context: ctx, + } +} + +// NewEnableRuleParamsWithHTTPClient creates a new EnableRuleParams object +// with the ability to set a custom HTTPClient for a request. +func NewEnableRuleParamsWithHTTPClient(client *http.Client) *EnableRuleParams { + return &EnableRuleParams{ + HTTPClient: client, + } +} + +/* EnableRuleParams contains all the parameters to send to the API endpoint + for the enable rule operation. + + Typically these are written to a http.Request. +*/ +type EnableRuleParams struct { + + // Body. + Body *models.EnableRuleRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the enable rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *EnableRuleParams) WithDefaults() *EnableRuleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the enable rule params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *EnableRuleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the enable rule params +func (o *EnableRuleParams) WithTimeout(timeout time.Duration) *EnableRuleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the enable rule params +func (o *EnableRuleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the enable rule params +func (o *EnableRuleParams) WithContext(ctx context.Context) *EnableRuleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the enable rule params +func (o *EnableRuleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the enable rule params +func (o *EnableRuleParams) WithHTTPClient(client *http.Client) *EnableRuleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the enable rule params +func (o *EnableRuleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the enable rule params +func (o *EnableRuleParams) WithBody(body *models.EnableRuleRequest) *EnableRuleParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the enable rule params +func (o *EnableRuleParams) SetBody(body *models.EnableRuleRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the enable rule params +func (o *EnableRuleParams) WithAuthorization(authorization string) *EnableRuleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the enable rule params +func (o *EnableRuleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the enable rule params +func (o *EnableRuleParams) WithBmpLanguage(bmpLanguage *string) *EnableRuleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the enable rule params +func (o *EnableRuleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the enable rule params +func (o *EnableRuleParams) WithBmpUserID(bmpUserID *string) *EnableRuleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the enable rule params +func (o *EnableRuleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the enable rule params +func (o *EnableRuleParams) WithTraceID(traceID string) *EnableRuleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the enable rule params +func (o *EnableRuleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *EnableRuleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/enable_rule_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/enable_rule_responses.go new file mode 100644 index 0000000..8fba8e6 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/enable_rule_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// EnableRuleReader is a Reader for the EnableRule structure. +type EnableRuleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *EnableRuleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewEnableRuleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewEnableRuleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewEnableRuleOK creates a EnableRuleOK with default headers values +func NewEnableRuleOK() *EnableRuleOK { + return &EnableRuleOK{} +} + +/* EnableRuleOK describes a response with status code 200, with default header values. + +A EnableRuleResult is an response struct that is used to describe create rule result. +*/ +type EnableRuleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *EnableRuleOKBody +} + +// IsSuccess returns true when this enable rule o k response has a 2xx status code +func (o *EnableRuleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this enable rule o k response has a 3xx status code +func (o *EnableRuleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this enable rule o k response has a 4xx status code +func (o *EnableRuleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this enable rule o k response has a 5xx status code +func (o *EnableRuleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this enable rule o k response a status code equal to that given +func (o *EnableRuleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *EnableRuleOK) Error() string { + return fmt.Sprintf("[PUT /monitorRule/enableRule][%d] enableRuleOK %+v", 200, o.Payload) +} + +func (o *EnableRuleOK) String() string { + return fmt.Sprintf("[PUT /monitorRule/enableRule][%d] enableRuleOK %+v", 200, o.Payload) +} + +func (o *EnableRuleOK) GetPayload() *EnableRuleOKBody { + return o.Payload +} + +func (o *EnableRuleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(EnableRuleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewEnableRuleDefault creates a EnableRuleDefault with default headers values +func NewEnableRuleDefault(code int) *EnableRuleDefault { + return &EnableRuleDefault{ + _statusCode: code, + } +} + +/* EnableRuleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type EnableRuleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *EnableRuleDefaultBody +} + +// Code gets the status code for the enable rule default response +func (o *EnableRuleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this enable rule default response has a 2xx status code +func (o *EnableRuleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this enable rule default response has a 3xx status code +func (o *EnableRuleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this enable rule default response has a 4xx status code +func (o *EnableRuleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this enable rule default response has a 5xx status code +func (o *EnableRuleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this enable rule default response a status code equal to that given +func (o *EnableRuleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *EnableRuleDefault) Error() string { + return fmt.Sprintf("[PUT /monitorRule/enableRule][%d] enableRule default %+v", o._statusCode, o.Payload) +} + +func (o *EnableRuleDefault) String() string { + return fmt.Sprintf("[PUT /monitorRule/enableRule][%d] enableRule default %+v", o._statusCode, o.Payload) +} + +func (o *EnableRuleDefault) GetPayload() *EnableRuleDefaultBody { + return o.Payload +} + +func (o *EnableRuleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(EnableRuleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*EnableRuleDefaultBody enable rule default body +swagger:model EnableRuleDefaultBody +*/ +type EnableRuleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this enable rule default body +func (o *EnableRuleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EnableRuleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("enableRule default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *EnableRuleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("enableRule default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("enableRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("enableRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this enable rule default body based on the context it is used +func (o *EnableRuleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EnableRuleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("enableRule default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("enableRule default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *EnableRuleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *EnableRuleDefaultBody) UnmarshalBinary(b []byte) error { + var res EnableRuleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*EnableRuleOKBody enable rule o k body +swagger:model EnableRuleOKBody +*/ +type EnableRuleOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this enable rule o k body +func (o *EnableRuleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EnableRuleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("enableRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("enableRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this enable rule o k body based on the context it is used +func (o *EnableRuleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *EnableRuleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("enableRuleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("enableRuleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *EnableRuleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *EnableRuleOKBody) UnmarshalBinary(b []byte) error { + var res EnableRuleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/monitor_rule_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/monitor_rule_client.go new file mode 100644 index 0000000..286c404 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/monitor_rule/monitor_rule_client.go @@ -0,0 +1,317 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package monitor_rule + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new monitor rule API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for monitor rule API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + AddRule(params *AddRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AddRuleOK, error) + + DeleteRule(params *DeleteRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteRuleOK, error) + + DescribeRule(params *DescribeRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRuleOK, error) + + DescribeRules(params *DescribeRulesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRulesOK, error) + + DisableRule(params *DisableRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DisableRuleOK, error) + + EditRule(params *EditRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*EditRuleOK, error) + + EnableRule(params *EnableRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*EnableRuleOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + AddRule AddRule 添加规则 +*/ +func (a *Client) AddRule(params *AddRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AddRuleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewAddRuleParams() + } + op := &runtime.ClientOperation{ + ID: "addRule", + Method: "POST", + PathPattern: "/monitorRule/addRule", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &AddRuleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*AddRuleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*AddRuleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteRule DeleteRule 删除规则 +*/ +func (a *Client) DeleteRule(params *DeleteRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteRuleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteRuleParams() + } + op := &runtime.ClientOperation{ + ID: "deleteRule", + Method: "DELETE", + PathPattern: "/monitorRule/deleteRule", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteRuleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteRuleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteRuleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeRule DescribeRule 规则详情 +*/ +func (a *Client) DescribeRule(params *DescribeRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRuleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeRuleParams() + } + op := &runtime.ClientOperation{ + ID: "describeRule", + Method: "GET", + PathPattern: "/monitorRule/describeRule", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeRuleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeRuleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeRuleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeRules DescribeRules 规则列表 +*/ +func (a *Client) DescribeRules(params *DescribeRulesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRulesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeRulesParams() + } + op := &runtime.ClientOperation{ + ID: "describeRules", + Method: "GET", + PathPattern: "/monitorRule/describeRules", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeRulesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeRulesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeRulesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DisableRule DisableRule 禁用规则 +*/ +func (a *Client) DisableRule(params *DisableRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DisableRuleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDisableRuleParams() + } + op := &runtime.ClientOperation{ + ID: "disableRule", + Method: "PUT", + PathPattern: "/monitorRule/disableRule", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DisableRuleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DisableRuleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DisableRuleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + EditRule EditRule 编辑规则 +*/ +func (a *Client) EditRule(params *EditRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*EditRuleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewEditRuleParams() + } + op := &runtime.ClientOperation{ + ID: "editRule", + Method: "PUT", + PathPattern: "/monitorRule/editRule", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &EditRuleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*EditRuleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*EditRuleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + EnableRule EnableRule 启用规则 +*/ +func (a *Client) EnableRule(params *EnableRuleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*EnableRuleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewEnableRuleParams() + } + op := &runtime.ClientOperation{ + ID: "enableRule", + Method: "PUT", + PathPattern: "/monitorRule/enableRule", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &EnableRuleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*EnableRuleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*EnableRuleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/create_o_s_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/create_o_s_parameters.go new file mode 100644 index 0000000..1357863 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/create_o_s_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateOSParams creates a new CreateOSParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateOSParams() *CreateOSParams { + return &CreateOSParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateOSParamsWithTimeout creates a new CreateOSParams object +// with the ability to set a timeout on a request. +func NewCreateOSParamsWithTimeout(timeout time.Duration) *CreateOSParams { + return &CreateOSParams{ + timeout: timeout, + } +} + +// NewCreateOSParamsWithContext creates a new CreateOSParams object +// with the ability to set a context for a request. +func NewCreateOSParamsWithContext(ctx context.Context) *CreateOSParams { + return &CreateOSParams{ + Context: ctx, + } +} + +// NewCreateOSParamsWithHTTPClient creates a new CreateOSParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateOSParamsWithHTTPClient(client *http.Client) *CreateOSParams { + return &CreateOSParams{ + HTTPClient: client, + } +} + +/* CreateOSParams contains all the parameters to send to the API endpoint + for the create o s operation. + + Typically these are written to a http.Request. +*/ +type CreateOSParams struct { + + // Body. + Body *models.CreateOSRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateOSParams) WithDefaults() *CreateOSParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateOSParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create o s params +func (o *CreateOSParams) WithTimeout(timeout time.Duration) *CreateOSParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create o s params +func (o *CreateOSParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create o s params +func (o *CreateOSParams) WithContext(ctx context.Context) *CreateOSParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create o s params +func (o *CreateOSParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create o s params +func (o *CreateOSParams) WithHTTPClient(client *http.Client) *CreateOSParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create o s params +func (o *CreateOSParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create o s params +func (o *CreateOSParams) WithBody(body *models.CreateOSRequest) *CreateOSParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create o s params +func (o *CreateOSParams) SetBody(body *models.CreateOSRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create o s params +func (o *CreateOSParams) WithAuthorization(authorization string) *CreateOSParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create o s params +func (o *CreateOSParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create o s params +func (o *CreateOSParams) WithBmpLanguage(bmpLanguage *string) *CreateOSParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create o s params +func (o *CreateOSParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create o s params +func (o *CreateOSParams) WithBmpUserID(bmpUserID *string) *CreateOSParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create o s params +func (o *CreateOSParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create o s params +func (o *CreateOSParams) WithTraceID(traceID string) *CreateOSParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create o s params +func (o *CreateOSParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateOSParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/create_o_s_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/create_o_s_responses.go new file mode 100644 index 0000000..3db1968 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/create_o_s_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateOSReader is a Reader for the CreateOS structure. +type CreateOSReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateOSReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateOSOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateOSDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateOSOK creates a CreateOSOK with default headers values +func NewCreateOSOK() *CreateOSOK { + return &CreateOSOK{} +} + +/* CreateOSOK describes a response with status code 200, with default header values. + +A CreateOsResult is an response struct that is used to describe create os result. +*/ +type CreateOSOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateOSOKBody +} + +// IsSuccess returns true when this create o s o k response has a 2xx status code +func (o *CreateOSOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create o s o k response has a 3xx status code +func (o *CreateOSOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create o s o k response has a 4xx status code +func (o *CreateOSOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create o s o k response has a 5xx status code +func (o *CreateOSOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create o s o k response a status code equal to that given +func (o *CreateOSOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateOSOK) Error() string { + return fmt.Sprintf("[POST /oss][%d] createOSOK %+v", 200, o.Payload) +} + +func (o *CreateOSOK) String() string { + return fmt.Sprintf("[POST /oss][%d] createOSOK %+v", 200, o.Payload) +} + +func (o *CreateOSOK) GetPayload() *CreateOSOKBody { + return o.Payload +} + +func (o *CreateOSOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateOSOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateOSDefault creates a CreateOSDefault with default headers values +func NewCreateOSDefault(code int) *CreateOSDefault { + return &CreateOSDefault{ + _statusCode: code, + } +} + +/* CreateOSDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateOSDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateOSDefaultBody +} + +// Code gets the status code for the create o s default response +func (o *CreateOSDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create o s default response has a 2xx status code +func (o *CreateOSDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create o s default response has a 3xx status code +func (o *CreateOSDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create o s default response has a 4xx status code +func (o *CreateOSDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create o s default response has a 5xx status code +func (o *CreateOSDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create o s default response a status code equal to that given +func (o *CreateOSDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateOSDefault) Error() string { + return fmt.Sprintf("[POST /oss][%d] createOS default %+v", o._statusCode, o.Payload) +} + +func (o *CreateOSDefault) String() string { + return fmt.Sprintf("[POST /oss][%d] createOS default %+v", o._statusCode, o.Payload) +} + +func (o *CreateOSDefault) GetPayload() *CreateOSDefaultBody { + return o.Payload +} + +func (o *CreateOSDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateOSDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateOSDefaultBody create o s default body +swagger:model CreateOSDefaultBody +*/ +type CreateOSDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create o s default body +func (o *CreateOSDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateOSDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createOS default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateOSDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createOS default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create o s default body based on the context it is used +func (o *CreateOSDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateOSDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateOSDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateOSDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateOSDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateOSOKBody create o s o k body +swagger:model CreateOSOKBody +*/ +type CreateOSOKBody struct { + + // result + Result *models.OsID `json:"result,omitempty"` +} + +// Validate validates this create o s o k body +func (o *CreateOSOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateOSOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create o s o k body based on the context it is used +func (o *CreateOSOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateOSOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateOSOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateOSOKBody) UnmarshalBinary(b []byte) error { + var res CreateOSOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/delete_o_s_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/delete_o_s_parameters.go new file mode 100644 index 0000000..c80c5fd --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/delete_o_s_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteOSParams creates a new DeleteOSParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteOSParams() *DeleteOSParams { + return &DeleteOSParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteOSParamsWithTimeout creates a new DeleteOSParams object +// with the ability to set a timeout on a request. +func NewDeleteOSParamsWithTimeout(timeout time.Duration) *DeleteOSParams { + return &DeleteOSParams{ + timeout: timeout, + } +} + +// NewDeleteOSParamsWithContext creates a new DeleteOSParams object +// with the ability to set a context for a request. +func NewDeleteOSParamsWithContext(ctx context.Context) *DeleteOSParams { + return &DeleteOSParams{ + Context: ctx, + } +} + +// NewDeleteOSParamsWithHTTPClient creates a new DeleteOSParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteOSParamsWithHTTPClient(client *http.Client) *DeleteOSParams { + return &DeleteOSParams{ + HTTPClient: client, + } +} + +/* DeleteOSParams contains all the parameters to send to the API endpoint + for the delete o s operation. + + Typically these are written to a http.Request. +*/ +type DeleteOSParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // OsID. + OsID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteOSParams) WithDefaults() *DeleteOSParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteOSParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete o s params +func (o *DeleteOSParams) WithTimeout(timeout time.Duration) *DeleteOSParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete o s params +func (o *DeleteOSParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete o s params +func (o *DeleteOSParams) WithContext(ctx context.Context) *DeleteOSParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete o s params +func (o *DeleteOSParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete o s params +func (o *DeleteOSParams) WithHTTPClient(client *http.Client) *DeleteOSParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete o s params +func (o *DeleteOSParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete o s params +func (o *DeleteOSParams) WithAuthorization(authorization string) *DeleteOSParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete o s params +func (o *DeleteOSParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete o s params +func (o *DeleteOSParams) WithBmpLanguage(bmpLanguage *string) *DeleteOSParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete o s params +func (o *DeleteOSParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete o s params +func (o *DeleteOSParams) WithBmpUserID(bmpUserID *string) *DeleteOSParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete o s params +func (o *DeleteOSParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithOsID adds the osID to the delete o s params +func (o *DeleteOSParams) WithOsID(osID string) *DeleteOSParams { + o.SetOsID(osID) + return o +} + +// SetOsID adds the osId to the delete o s params +func (o *DeleteOSParams) SetOsID(osID string) { + o.OsID = osID +} + +// WithTraceID adds the traceID to the delete o s params +func (o *DeleteOSParams) WithTraceID(traceID string) *DeleteOSParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete o s params +func (o *DeleteOSParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteOSParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param os_id + if err := r.SetPathParam("os_id", o.OsID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/delete_o_s_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/delete_o_s_responses.go new file mode 100644 index 0000000..e397536 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/delete_o_s_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteOSReader is a Reader for the DeleteOS structure. +type DeleteOSReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteOSReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteOSOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteOSDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteOSOK creates a DeleteOSOK with default headers values +func NewDeleteOSOK() *DeleteOSOK { + return &DeleteOSOK{} +} + +/* DeleteOSOK describes a response with status code 200, with default header values. + +A DeleteOsResult is an response struct that is used to delete stop os result. +*/ +type DeleteOSOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteOSOKBody +} + +// IsSuccess returns true when this delete o s o k response has a 2xx status code +func (o *DeleteOSOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete o s o k response has a 3xx status code +func (o *DeleteOSOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete o s o k response has a 4xx status code +func (o *DeleteOSOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete o s o k response has a 5xx status code +func (o *DeleteOSOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete o s o k response a status code equal to that given +func (o *DeleteOSOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteOSOK) Error() string { + return fmt.Sprintf("[DELETE /oss/{os_id}][%d] deleteOSOK %+v", 200, o.Payload) +} + +func (o *DeleteOSOK) String() string { + return fmt.Sprintf("[DELETE /oss/{os_id}][%d] deleteOSOK %+v", 200, o.Payload) +} + +func (o *DeleteOSOK) GetPayload() *DeleteOSOKBody { + return o.Payload +} + +func (o *DeleteOSOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteOSOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteOSDefault creates a DeleteOSDefault with default headers values +func NewDeleteOSDefault(code int) *DeleteOSDefault { + return &DeleteOSDefault{ + _statusCode: code, + } +} + +/* DeleteOSDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteOSDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteOSDefaultBody +} + +// Code gets the status code for the delete o s default response +func (o *DeleteOSDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete o s default response has a 2xx status code +func (o *DeleteOSDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete o s default response has a 3xx status code +func (o *DeleteOSDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete o s default response has a 4xx status code +func (o *DeleteOSDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete o s default response has a 5xx status code +func (o *DeleteOSDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete o s default response a status code equal to that given +func (o *DeleteOSDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteOSDefault) Error() string { + return fmt.Sprintf("[DELETE /oss/{os_id}][%d] deleteOS default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteOSDefault) String() string { + return fmt.Sprintf("[DELETE /oss/{os_id}][%d] deleteOS default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteOSDefault) GetPayload() *DeleteOSDefaultBody { + return o.Payload +} + +func (o *DeleteOSDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteOSDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteOSDefaultBody delete o s default body +swagger:model DeleteOSDefaultBody +*/ +type DeleteOSDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete o s default body +func (o *DeleteOSDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteOSDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteOS default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteOSDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteOS default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete o s default body based on the context it is used +func (o *DeleteOSDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteOSDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteOSDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteOSDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteOSDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteOSOKBody delete o s o k body +swagger:model DeleteOSOKBody +*/ +type DeleteOSOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete o s o k body +func (o *DeleteOSOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteOSOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete o s o k body based on the context it is used +func (o *DeleteOSOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteOSOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteOSOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteOSOKBody) UnmarshalBinary(b []byte) error { + var res DeleteOSOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_s_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_s_parameters.go new file mode 100644 index 0000000..df2f89f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_s_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeOSParams creates a new DescribeOSParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeOSParams() *DescribeOSParams { + return &DescribeOSParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeOSParamsWithTimeout creates a new DescribeOSParams object +// with the ability to set a timeout on a request. +func NewDescribeOSParamsWithTimeout(timeout time.Duration) *DescribeOSParams { + return &DescribeOSParams{ + timeout: timeout, + } +} + +// NewDescribeOSParamsWithContext creates a new DescribeOSParams object +// with the ability to set a context for a request. +func NewDescribeOSParamsWithContext(ctx context.Context) *DescribeOSParams { + return &DescribeOSParams{ + Context: ctx, + } +} + +// NewDescribeOSParamsWithHTTPClient creates a new DescribeOSParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeOSParamsWithHTTPClient(client *http.Client) *DescribeOSParams { + return &DescribeOSParams{ + HTTPClient: client, + } +} + +/* DescribeOSParams contains all the parameters to send to the API endpoint + for the describe o s operation. + + Typically these are written to a http.Request. +*/ +type DescribeOSParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // OsID. + OsID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeOSParams) WithDefaults() *DescribeOSParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeOSParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe o s params +func (o *DescribeOSParams) WithTimeout(timeout time.Duration) *DescribeOSParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe o s params +func (o *DescribeOSParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe o s params +func (o *DescribeOSParams) WithContext(ctx context.Context) *DescribeOSParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe o s params +func (o *DescribeOSParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe o s params +func (o *DescribeOSParams) WithHTTPClient(client *http.Client) *DescribeOSParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe o s params +func (o *DescribeOSParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe o s params +func (o *DescribeOSParams) WithAuthorization(authorization string) *DescribeOSParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe o s params +func (o *DescribeOSParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe o s params +func (o *DescribeOSParams) WithBmpLanguage(bmpLanguage *string) *DescribeOSParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe o s params +func (o *DescribeOSParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe o s params +func (o *DescribeOSParams) WithBmpUserID(bmpUserID *string) *DescribeOSParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe o s params +func (o *DescribeOSParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithOsID adds the osID to the describe o s params +func (o *DescribeOSParams) WithOsID(osID string) *DescribeOSParams { + o.SetOsID(osID) + return o +} + +// SetOsID adds the osId to the describe o s params +func (o *DescribeOSParams) SetOsID(osID string) { + o.OsID = osID +} + +// WithTraceID adds the traceID to the describe o s params +func (o *DescribeOSParams) WithTraceID(traceID string) *DescribeOSParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe o s params +func (o *DescribeOSParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeOSParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param os_id + if err := r.SetPathParam("os_id", o.OsID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_s_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_s_responses.go new file mode 100644 index 0000000..370a646 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_s_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeOSReader is a Reader for the DescribeOS structure. +type DescribeOSReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeOSReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeOSOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeOSDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeOSOK creates a DescribeOSOK with default headers values +func NewDescribeOSOK() *DescribeOSOK { + return &DescribeOSOK{} +} + +/* DescribeOSOK describes a response with status code 200, with default header values. + +A DescribeOsResult is an response struct that is used to describe os. +*/ +type DescribeOSOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeOSOKBody +} + +// IsSuccess returns true when this describe o s o k response has a 2xx status code +func (o *DescribeOSOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe o s o k response has a 3xx status code +func (o *DescribeOSOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe o s o k response has a 4xx status code +func (o *DescribeOSOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe o s o k response has a 5xx status code +func (o *DescribeOSOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe o s o k response a status code equal to that given +func (o *DescribeOSOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeOSOK) Error() string { + return fmt.Sprintf("[GET /oss/{os_id}][%d] describeOSOK %+v", 200, o.Payload) +} + +func (o *DescribeOSOK) String() string { + return fmt.Sprintf("[GET /oss/{os_id}][%d] describeOSOK %+v", 200, o.Payload) +} + +func (o *DescribeOSOK) GetPayload() *DescribeOSOKBody { + return o.Payload +} + +func (o *DescribeOSOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeOSOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeOSDefault creates a DescribeOSDefault with default headers values +func NewDescribeOSDefault(code int) *DescribeOSDefault { + return &DescribeOSDefault{ + _statusCode: code, + } +} + +/* DescribeOSDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeOSDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeOSDefaultBody +} + +// Code gets the status code for the describe o s default response +func (o *DescribeOSDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe o s default response has a 2xx status code +func (o *DescribeOSDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe o s default response has a 3xx status code +func (o *DescribeOSDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe o s default response has a 4xx status code +func (o *DescribeOSDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe o s default response has a 5xx status code +func (o *DescribeOSDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe o s default response a status code equal to that given +func (o *DescribeOSDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeOSDefault) Error() string { + return fmt.Sprintf("[GET /oss/{os_id}][%d] describeOS default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeOSDefault) String() string { + return fmt.Sprintf("[GET /oss/{os_id}][%d] describeOS default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeOSDefault) GetPayload() *DescribeOSDefaultBody { + return o.Payload +} + +func (o *DescribeOSDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeOSDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeOSDefaultBody describe o s default body +swagger:model DescribeOSDefaultBody +*/ +type DescribeOSDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe o s default body +func (o *DescribeOSDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeOS default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeOSDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeOS default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe o s default body based on the context it is used +func (o *DescribeOSDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeOSDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeOSDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeOSDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeOSOKBody describe o s o k body +swagger:model DescribeOSOKBody +*/ +type DescribeOSOKBody struct { + + // result + Result *models.OsInfo `json:"result,omitempty"` +} + +// Validate validates this describe o s o k body +func (o *DescribeOSOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe o s o k body based on the context it is used +func (o *DescribeOSOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeOSOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeOSOKBody) UnmarshalBinary(b []byte) error { + var res DescribeOSOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_ss_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_ss_parameters.go new file mode 100644 index 0000000..d009e8d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_ss_parameters.go @@ -0,0 +1,357 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeOSsParams creates a new DescribeOSsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeOSsParams() *DescribeOSsParams { + return &DescribeOSsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeOSsParamsWithTimeout creates a new DescribeOSsParams object +// with the ability to set a timeout on a request. +func NewDescribeOSsParamsWithTimeout(timeout time.Duration) *DescribeOSsParams { + return &DescribeOSsParams{ + timeout: timeout, + } +} + +// NewDescribeOSsParamsWithContext creates a new DescribeOSsParams object +// with the ability to set a context for a request. +func NewDescribeOSsParamsWithContext(ctx context.Context) *DescribeOSsParams { + return &DescribeOSsParams{ + Context: ctx, + } +} + +// NewDescribeOSsParamsWithHTTPClient creates a new DescribeOSsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeOSsParamsWithHTTPClient(client *http.Client) *DescribeOSsParams { + return &DescribeOSsParams{ + HTTPClient: client, + } +} + +/* DescribeOSsParams contains all the parameters to send to the API endpoint + for the describe o ss operation. + + Typically these are written to a http.Request. +*/ +type DescribeOSsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否显示所有 + */ + IsAll *string + + /* OsName. + + 操作系统名称 + */ + OsName *string + + /* OsType. + + 操作系统平台 + */ + OsType *string + + /* OsVersion. + + 操作系统版本 + */ + OsVersion *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe o ss params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeOSsParams) WithDefaults() *DescribeOSsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe o ss params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeOSsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe o ss params +func (o *DescribeOSsParams) WithTimeout(timeout time.Duration) *DescribeOSsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe o ss params +func (o *DescribeOSsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe o ss params +func (o *DescribeOSsParams) WithContext(ctx context.Context) *DescribeOSsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe o ss params +func (o *DescribeOSsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe o ss params +func (o *DescribeOSsParams) WithHTTPClient(client *http.Client) *DescribeOSsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe o ss params +func (o *DescribeOSsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe o ss params +func (o *DescribeOSsParams) WithAuthorization(authorization string) *DescribeOSsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe o ss params +func (o *DescribeOSsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe o ss params +func (o *DescribeOSsParams) WithBmpLanguage(bmpLanguage *string) *DescribeOSsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe o ss params +func (o *DescribeOSsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe o ss params +func (o *DescribeOSsParams) WithBmpUserID(bmpUserID *string) *DescribeOSsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe o ss params +func (o *DescribeOSsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe o ss params +func (o *DescribeOSsParams) WithIsAll(isAll *string) *DescribeOSsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe o ss params +func (o *DescribeOSsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithOsName adds the osName to the describe o ss params +func (o *DescribeOSsParams) WithOsName(osName *string) *DescribeOSsParams { + o.SetOsName(osName) + return o +} + +// SetOsName adds the osName to the describe o ss params +func (o *DescribeOSsParams) SetOsName(osName *string) { + o.OsName = osName +} + +// WithOsType adds the osType to the describe o ss params +func (o *DescribeOSsParams) WithOsType(osType *string) *DescribeOSsParams { + o.SetOsType(osType) + return o +} + +// SetOsType adds the osType to the describe o ss params +func (o *DescribeOSsParams) SetOsType(osType *string) { + o.OsType = osType +} + +// WithOsVersion adds the osVersion to the describe o ss params +func (o *DescribeOSsParams) WithOsVersion(osVersion *string) *DescribeOSsParams { + o.SetOsVersion(osVersion) + return o +} + +// SetOsVersion adds the osVersion to the describe o ss params +func (o *DescribeOSsParams) SetOsVersion(osVersion *string) { + o.OsVersion = osVersion +} + +// WithTraceID adds the traceID to the describe o ss params +func (o *DescribeOSsParams) WithTraceID(traceID string) *DescribeOSsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe o ss params +func (o *DescribeOSsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeOSsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.OsName != nil { + + // query param osName + var qrOsName string + + if o.OsName != nil { + qrOsName = *o.OsName + } + qOsName := qrOsName + if qOsName != "" { + + if err := r.SetQueryParam("osName", qOsName); err != nil { + return err + } + } + } + + if o.OsType != nil { + + // query param osType + var qrOsType string + + if o.OsType != nil { + qrOsType = *o.OsType + } + qOsType := qrOsType + if qOsType != "" { + + if err := r.SetQueryParam("osType", qOsType); err != nil { + return err + } + } + } + + if o.OsVersion != nil { + + // query param osVersion + var qrOsVersion string + + if o.OsVersion != nil { + qrOsVersion = *o.OsVersion + } + qOsVersion := qrOsVersion + if qOsVersion != "" { + + if err := r.SetQueryParam("osVersion", qOsVersion); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_ss_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_ss_responses.go new file mode 100644 index 0000000..ac6e43b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_ss_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeOSsReader is a Reader for the DescribeOSs structure. +type DescribeOSsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeOSsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeOSsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeOSsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeOSsOK creates a DescribeOSsOK with default headers values +func NewDescribeOSsOK() *DescribeOSsOK { + return &DescribeOSsOK{} +} + +/* DescribeOSsOK describes a response with status code 200, with default header values. + +A DescribeOssResult is an response struct that is used to describe oss. +*/ +type DescribeOSsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeOSsOKBody +} + +// IsSuccess returns true when this describe o ss o k response has a 2xx status code +func (o *DescribeOSsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe o ss o k response has a 3xx status code +func (o *DescribeOSsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe o ss o k response has a 4xx status code +func (o *DescribeOSsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe o ss o k response has a 5xx status code +func (o *DescribeOSsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe o ss o k response a status code equal to that given +func (o *DescribeOSsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeOSsOK) Error() string { + return fmt.Sprintf("[GET /oss][%d] describeOSsOK %+v", 200, o.Payload) +} + +func (o *DescribeOSsOK) String() string { + return fmt.Sprintf("[GET /oss][%d] describeOSsOK %+v", 200, o.Payload) +} + +func (o *DescribeOSsOK) GetPayload() *DescribeOSsOKBody { + return o.Payload +} + +func (o *DescribeOSsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeOSsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeOSsDefault creates a DescribeOSsDefault with default headers values +func NewDescribeOSsDefault(code int) *DescribeOSsDefault { + return &DescribeOSsDefault{ + _statusCode: code, + } +} + +/* DescribeOSsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeOSsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeOSsDefaultBody +} + +// Code gets the status code for the describe o ss default response +func (o *DescribeOSsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe o ss default response has a 2xx status code +func (o *DescribeOSsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe o ss default response has a 3xx status code +func (o *DescribeOSsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe o ss default response has a 4xx status code +func (o *DescribeOSsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe o ss default response has a 5xx status code +func (o *DescribeOSsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe o ss default response a status code equal to that given +func (o *DescribeOSsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeOSsDefault) Error() string { + return fmt.Sprintf("[GET /oss][%d] describeOSs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeOSsDefault) String() string { + return fmt.Sprintf("[GET /oss][%d] describeOSs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeOSsDefault) GetPayload() *DescribeOSsDefaultBody { + return o.Payload +} + +func (o *DescribeOSsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeOSsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeOSsDefaultBody describe o ss default body +swagger:model DescribeOSsDefaultBody +*/ +type DescribeOSsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe o ss default body +func (o *DescribeOSsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeOSs default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeOSsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeOSs default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSs default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe o ss default body based on the context it is used +func (o *DescribeOSsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSs default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeOSsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeOSsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeOSsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeOSsOKBody describe o ss o k body +swagger:model DescribeOSsOKBody +*/ +type DescribeOSsOKBody struct { + + // result + Result *models.OsList `json:"result,omitempty"` +} + +// Validate validates this describe o ss o k body +func (o *DescribeOSsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe o ss o k body based on the context it is used +func (o *DescribeOSsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeOSsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeOSsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeOSsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/modify_o_s_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/modify_o_s_parameters.go new file mode 100644 index 0000000..74a1a82 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/modify_o_s_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyOSParams creates a new ModifyOSParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyOSParams() *ModifyOSParams { + return &ModifyOSParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyOSParamsWithTimeout creates a new ModifyOSParams object +// with the ability to set a timeout on a request. +func NewModifyOSParamsWithTimeout(timeout time.Duration) *ModifyOSParams { + return &ModifyOSParams{ + timeout: timeout, + } +} + +// NewModifyOSParamsWithContext creates a new ModifyOSParams object +// with the ability to set a context for a request. +func NewModifyOSParamsWithContext(ctx context.Context) *ModifyOSParams { + return &ModifyOSParams{ + Context: ctx, + } +} + +// NewModifyOSParamsWithHTTPClient creates a new ModifyOSParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyOSParamsWithHTTPClient(client *http.Client) *ModifyOSParams { + return &ModifyOSParams{ + HTTPClient: client, + } +} + +/* ModifyOSParams contains all the parameters to send to the API endpoint + for the modify o s operation. + + Typically these are written to a http.Request. +*/ +type ModifyOSParams struct { + + // Body. + Body *models.ModifyOSRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // OsID. + OsID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyOSParams) WithDefaults() *ModifyOSParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyOSParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify o s params +func (o *ModifyOSParams) WithTimeout(timeout time.Duration) *ModifyOSParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify o s params +func (o *ModifyOSParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify o s params +func (o *ModifyOSParams) WithContext(ctx context.Context) *ModifyOSParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify o s params +func (o *ModifyOSParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify o s params +func (o *ModifyOSParams) WithHTTPClient(client *http.Client) *ModifyOSParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify o s params +func (o *ModifyOSParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify o s params +func (o *ModifyOSParams) WithBody(body *models.ModifyOSRequest) *ModifyOSParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify o s params +func (o *ModifyOSParams) SetBody(body *models.ModifyOSRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify o s params +func (o *ModifyOSParams) WithAuthorization(authorization string) *ModifyOSParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify o s params +func (o *ModifyOSParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify o s params +func (o *ModifyOSParams) WithBmpLanguage(bmpLanguage *string) *ModifyOSParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify o s params +func (o *ModifyOSParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify o s params +func (o *ModifyOSParams) WithBmpUserID(bmpUserID *string) *ModifyOSParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify o s params +func (o *ModifyOSParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithOsID adds the osID to the modify o s params +func (o *ModifyOSParams) WithOsID(osID string) *ModifyOSParams { + o.SetOsID(osID) + return o +} + +// SetOsID adds the osId to the modify o s params +func (o *ModifyOSParams) SetOsID(osID string) { + o.OsID = osID +} + +// WithTraceID adds the traceID to the modify o s params +func (o *ModifyOSParams) WithTraceID(traceID string) *ModifyOSParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify o s params +func (o *ModifyOSParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyOSParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param os_id + if err := r.SetPathParam("os_id", o.OsID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/modify_o_s_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/modify_o_s_responses.go new file mode 100644 index 0000000..7c0f605 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/modify_o_s_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyOSReader is a Reader for the ModifyOS structure. +type ModifyOSReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyOSReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyOSOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyOSDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyOSOK creates a ModifyOSOK with default headers values +func NewModifyOSOK() *ModifyOSOK { + return &ModifyOSOK{} +} + +/* ModifyOSOK describes a response with status code 200, with default header values. + +A ModifyOsResult is an response struct that is used to describe modify os. +*/ +type ModifyOSOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyOSOKBody +} + +// IsSuccess returns true when this modify o s o k response has a 2xx status code +func (o *ModifyOSOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify o s o k response has a 3xx status code +func (o *ModifyOSOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify o s o k response has a 4xx status code +func (o *ModifyOSOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify o s o k response has a 5xx status code +func (o *ModifyOSOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify o s o k response a status code equal to that given +func (o *ModifyOSOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyOSOK) Error() string { + return fmt.Sprintf("[PUT /oss/{os_id}][%d] modifyOSOK %+v", 200, o.Payload) +} + +func (o *ModifyOSOK) String() string { + return fmt.Sprintf("[PUT /oss/{os_id}][%d] modifyOSOK %+v", 200, o.Payload) +} + +func (o *ModifyOSOK) GetPayload() *ModifyOSOKBody { + return o.Payload +} + +func (o *ModifyOSOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyOSOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyOSDefault creates a ModifyOSDefault with default headers values +func NewModifyOSDefault(code int) *ModifyOSDefault { + return &ModifyOSDefault{ + _statusCode: code, + } +} + +/* ModifyOSDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyOSDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyOSDefaultBody +} + +// Code gets the status code for the modify o s default response +func (o *ModifyOSDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify o s default response has a 2xx status code +func (o *ModifyOSDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify o s default response has a 3xx status code +func (o *ModifyOSDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify o s default response has a 4xx status code +func (o *ModifyOSDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify o s default response has a 5xx status code +func (o *ModifyOSDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify o s default response a status code equal to that given +func (o *ModifyOSDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyOSDefault) Error() string { + return fmt.Sprintf("[PUT /oss/{os_id}][%d] modifyOS default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyOSDefault) String() string { + return fmt.Sprintf("[PUT /oss/{os_id}][%d] modifyOS default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyOSDefault) GetPayload() *ModifyOSDefaultBody { + return o.Payload +} + +func (o *ModifyOSDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyOSDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyOSDefaultBody modify o s default body +swagger:model ModifyOSDefaultBody +*/ +type ModifyOSDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify o s default body +func (o *ModifyOSDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyOSDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyOS default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyOSDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyOS default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify o s default body based on the context it is used +func (o *ModifyOSDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyOSDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyOSDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyOSDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyOSDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyOSOKBody modify o s o k body +swagger:model ModifyOSOKBody +*/ +type ModifyOSOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify o s o k body +func (o *ModifyOSOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyOSOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify o s o k body based on the context it is used +func (o *ModifyOSOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyOSOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyOSOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyOSOKBody) UnmarshalBinary(b []byte) error { + var res ModifyOSOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/os_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/os_client.go new file mode 100644 index 0000000..8b6692f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/os/os_client.go @@ -0,0 +1,237 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new os API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for os API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateOS(params *CreateOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateOSOK, error) + + DeleteOS(params *DeleteOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteOSOK, error) + + DescribeOS(params *DescribeOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeOSOK, error) + + DescribeOSs(params *DescribeOSsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeOSsOK, error) + + ModifyOS(params *ModifyOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyOSOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateOS CreateOS 添加操作系统(暂不启用) +*/ +func (a *Client) CreateOS(params *CreateOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateOSOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateOSParams() + } + op := &runtime.ClientOperation{ + ID: "createOS", + Method: "POST", + PathPattern: "/oss", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateOSReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateOSOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateOSDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteOS DeleteOS 删除os(暂不启用) +*/ +func (a *Client) DeleteOS(params *DeleteOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteOSOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteOSParams() + } + op := &runtime.ClientOperation{ + ID: "deleteOS", + Method: "DELETE", + PathPattern: "/oss/{os_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteOSReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteOSOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteOSDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeOS DescribeOS 获取os系统详情(暂不启用) +*/ +func (a *Client) DescribeOS(params *DescribeOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeOSOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeOSParams() + } + op := &runtime.ClientOperation{ + ID: "describeOS", + Method: "GET", + PathPattern: "/oss/{os_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeOSReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeOSOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeOSDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeOSs DescribeOSs 获取os列表(暂不启用) +*/ +func (a *Client) DescribeOSs(params *DescribeOSsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeOSsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeOSsParams() + } + op := &runtime.ClientOperation{ + ID: "describeOSs", + Method: "GET", + PathPattern: "/oss", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeOSsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeOSsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeOSsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyOS ModifyOS 修改os信息(暂不启用) +*/ +func (a *Client) ModifyOS(params *ModifyOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyOSOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyOSParams() + } + op := &runtime.ClientOperation{ + ID: "modifyOS", + Method: "PUT", + PathPattern: "/oss/{os_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyOSReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyOSOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyOSDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/cancel_share_user_project_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/cancel_share_user_project_parameters.go new file mode 100644 index 0000000..1729c0c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/cancel_share_user_project_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCancelShareUserProjectParams creates a new CancelShareUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCancelShareUserProjectParams() *CancelShareUserProjectParams { + return &CancelShareUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCancelShareUserProjectParamsWithTimeout creates a new CancelShareUserProjectParams object +// with the ability to set a timeout on a request. +func NewCancelShareUserProjectParamsWithTimeout(timeout time.Duration) *CancelShareUserProjectParams { + return &CancelShareUserProjectParams{ + timeout: timeout, + } +} + +// NewCancelShareUserProjectParamsWithContext creates a new CancelShareUserProjectParams object +// with the ability to set a context for a request. +func NewCancelShareUserProjectParamsWithContext(ctx context.Context) *CancelShareUserProjectParams { + return &CancelShareUserProjectParams{ + Context: ctx, + } +} + +// NewCancelShareUserProjectParamsWithHTTPClient creates a new CancelShareUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewCancelShareUserProjectParamsWithHTTPClient(client *http.Client) *CancelShareUserProjectParams { + return &CancelShareUserProjectParams{ + HTTPClient: client, + } +} + +/* CancelShareUserProjectParams contains all the parameters to send to the API endpoint + for the cancel share user project operation. + + Typically these are written to a http.Request. +*/ +type CancelShareUserProjectParams struct { + + // Body. + Body *models.ShareProjectRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the cancel share user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CancelShareUserProjectParams) WithDefaults() *CancelShareUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the cancel share user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CancelShareUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the cancel share user project params +func (o *CancelShareUserProjectParams) WithTimeout(timeout time.Duration) *CancelShareUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the cancel share user project params +func (o *CancelShareUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the cancel share user project params +func (o *CancelShareUserProjectParams) WithContext(ctx context.Context) *CancelShareUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the cancel share user project params +func (o *CancelShareUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the cancel share user project params +func (o *CancelShareUserProjectParams) WithHTTPClient(client *http.Client) *CancelShareUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the cancel share user project params +func (o *CancelShareUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the cancel share user project params +func (o *CancelShareUserProjectParams) WithBody(body *models.ShareProjectRequest) *CancelShareUserProjectParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the cancel share user project params +func (o *CancelShareUserProjectParams) SetBody(body *models.ShareProjectRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the cancel share user project params +func (o *CancelShareUserProjectParams) WithAuthorization(authorization string) *CancelShareUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the cancel share user project params +func (o *CancelShareUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the cancel share user project params +func (o *CancelShareUserProjectParams) WithBmpLanguage(bmpLanguage *string) *CancelShareUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the cancel share user project params +func (o *CancelShareUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the cancel share user project params +func (o *CancelShareUserProjectParams) WithBmpUserID(bmpUserID *string) *CancelShareUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the cancel share user project params +func (o *CancelShareUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the cancel share user project params +func (o *CancelShareUserProjectParams) WithProjectID(projectID string) *CancelShareUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the cancel share user project params +func (o *CancelShareUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the cancel share user project params +func (o *CancelShareUserProjectParams) WithTraceID(traceID string) *CancelShareUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the cancel share user project params +func (o *CancelShareUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CancelShareUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/cancel_share_user_project_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/cancel_share_user_project_responses.go new file mode 100644 index 0000000..4fc3307 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/cancel_share_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CancelShareUserProjectReader is a Reader for the CancelShareUserProject structure. +type CancelShareUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CancelShareUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCancelShareUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCancelShareUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCancelShareUserProjectOK creates a CancelShareUserProjectOK with default headers values +func NewCancelShareUserProjectOK() *CancelShareUserProjectOK { + return &CancelShareUserProjectOK{} +} + +/* CancelShareUserProjectOK describes a response with status code 200, with default header values. + +A CancelShareUserProjectResult is an response struct +*/ +type CancelShareUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CancelShareUserProjectOKBody +} + +// IsSuccess returns true when this cancel share user project o k response has a 2xx status code +func (o *CancelShareUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this cancel share user project o k response has a 3xx status code +func (o *CancelShareUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this cancel share user project o k response has a 4xx status code +func (o *CancelShareUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this cancel share user project o k response has a 5xx status code +func (o *CancelShareUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this cancel share user project o k response a status code equal to that given +func (o *CancelShareUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CancelShareUserProjectOK) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/cancelShare][%d] cancelShareUserProjectOK %+v", 200, o.Payload) +} + +func (o *CancelShareUserProjectOK) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/cancelShare][%d] cancelShareUserProjectOK %+v", 200, o.Payload) +} + +func (o *CancelShareUserProjectOK) GetPayload() *CancelShareUserProjectOKBody { + return o.Payload +} + +func (o *CancelShareUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CancelShareUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCancelShareUserProjectDefault creates a CancelShareUserProjectDefault with default headers values +func NewCancelShareUserProjectDefault(code int) *CancelShareUserProjectDefault { + return &CancelShareUserProjectDefault{ + _statusCode: code, + } +} + +/* CancelShareUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CancelShareUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CancelShareUserProjectDefaultBody +} + +// Code gets the status code for the cancel share user project default response +func (o *CancelShareUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this cancel share user project default response has a 2xx status code +func (o *CancelShareUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this cancel share user project default response has a 3xx status code +func (o *CancelShareUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this cancel share user project default response has a 4xx status code +func (o *CancelShareUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this cancel share user project default response has a 5xx status code +func (o *CancelShareUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this cancel share user project default response a status code equal to that given +func (o *CancelShareUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CancelShareUserProjectDefault) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/cancelShare][%d] cancelShareUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *CancelShareUserProjectDefault) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/cancelShare][%d] cancelShareUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *CancelShareUserProjectDefault) GetPayload() *CancelShareUserProjectDefaultBody { + return o.Payload +} + +func (o *CancelShareUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CancelShareUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CancelShareUserProjectDefaultBody cancel share user project default body +swagger:model CancelShareUserProjectDefaultBody +*/ +type CancelShareUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this cancel share user project default body +func (o *CancelShareUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CancelShareUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("cancelShareUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CancelShareUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("cancelShareUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cancelShareUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cancelShareUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this cancel share user project default body based on the context it is used +func (o *CancelShareUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CancelShareUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cancelShareUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cancelShareUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CancelShareUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CancelShareUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res CancelShareUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CancelShareUserProjectOKBody cancel share user project o k body +swagger:model CancelShareUserProjectOKBody +*/ +type CancelShareUserProjectOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this cancel share user project o k body +func (o *CancelShareUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CancelShareUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cancelShareUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cancelShareUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this cancel share user project o k body based on the context it is used +func (o *CancelShareUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CancelShareUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cancelShareUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cancelShareUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CancelShareUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CancelShareUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res CancelShareUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/create_user_project_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/create_user_project_parameters.go new file mode 100644 index 0000000..62ddaec --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/create_user_project_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateUserProjectParams creates a new CreateUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateUserProjectParams() *CreateUserProjectParams { + return &CreateUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateUserProjectParamsWithTimeout creates a new CreateUserProjectParams object +// with the ability to set a timeout on a request. +func NewCreateUserProjectParamsWithTimeout(timeout time.Duration) *CreateUserProjectParams { + return &CreateUserProjectParams{ + timeout: timeout, + } +} + +// NewCreateUserProjectParamsWithContext creates a new CreateUserProjectParams object +// with the ability to set a context for a request. +func NewCreateUserProjectParamsWithContext(ctx context.Context) *CreateUserProjectParams { + return &CreateUserProjectParams{ + Context: ctx, + } +} + +// NewCreateUserProjectParamsWithHTTPClient creates a new CreateUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateUserProjectParamsWithHTTPClient(client *http.Client) *CreateUserProjectParams { + return &CreateUserProjectParams{ + HTTPClient: client, + } +} + +/* CreateUserProjectParams contains all the parameters to send to the API endpoint + for the create user project operation. + + Typically these are written to a http.Request. +*/ +type CreateUserProjectParams struct { + + // Body. + Body *models.CreateProjectRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserProjectParams) WithDefaults() *CreateUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create user project params +func (o *CreateUserProjectParams) WithTimeout(timeout time.Duration) *CreateUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create user project params +func (o *CreateUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create user project params +func (o *CreateUserProjectParams) WithContext(ctx context.Context) *CreateUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create user project params +func (o *CreateUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create user project params +func (o *CreateUserProjectParams) WithHTTPClient(client *http.Client) *CreateUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create user project params +func (o *CreateUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create user project params +func (o *CreateUserProjectParams) WithBody(body *models.CreateProjectRequest) *CreateUserProjectParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create user project params +func (o *CreateUserProjectParams) SetBody(body *models.CreateProjectRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create user project params +func (o *CreateUserProjectParams) WithAuthorization(authorization string) *CreateUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create user project params +func (o *CreateUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create user project params +func (o *CreateUserProjectParams) WithBmpLanguage(bmpLanguage *string) *CreateUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create user project params +func (o *CreateUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create user project params +func (o *CreateUserProjectParams) WithBmpUserID(bmpUserID *string) *CreateUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create user project params +func (o *CreateUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create user project params +func (o *CreateUserProjectParams) WithTraceID(traceID string) *CreateUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create user project params +func (o *CreateUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/create_user_project_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/create_user_project_responses.go new file mode 100644 index 0000000..5c10d67 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/create_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateUserProjectReader is a Reader for the CreateUserProject structure. +type CreateUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateUserProjectOK creates a CreateUserProjectOK with default headers values +func NewCreateUserProjectOK() *CreateUserProjectOK { + return &CreateUserProjectOK{} +} + +/* CreateUserProjectOK describes a response with status code 200, with default header values. + +CreateUserProjectOK create user project o k +*/ +type CreateUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserProjectOKBody +} + +// IsSuccess returns true when this create user project o k response has a 2xx status code +func (o *CreateUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create user project o k response has a 3xx status code +func (o *CreateUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create user project o k response has a 4xx status code +func (o *CreateUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create user project o k response has a 5xx status code +func (o *CreateUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create user project o k response a status code equal to that given +func (o *CreateUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateUserProjectOK) Error() string { + return fmt.Sprintf("[POST /user/projects][%d] createUserProjectOK %+v", 200, o.Payload) +} + +func (o *CreateUserProjectOK) String() string { + return fmt.Sprintf("[POST /user/projects][%d] createUserProjectOK %+v", 200, o.Payload) +} + +func (o *CreateUserProjectOK) GetPayload() *CreateUserProjectOKBody { + return o.Payload +} + +func (o *CreateUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateUserProjectDefault creates a CreateUserProjectDefault with default headers values +func NewCreateUserProjectDefault(code int) *CreateUserProjectDefault { + return &CreateUserProjectDefault{ + _statusCode: code, + } +} + +/* CreateUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserProjectDefaultBody +} + +// Code gets the status code for the create user project default response +func (o *CreateUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create user project default response has a 2xx status code +func (o *CreateUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create user project default response has a 3xx status code +func (o *CreateUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create user project default response has a 4xx status code +func (o *CreateUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create user project default response has a 5xx status code +func (o *CreateUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create user project default response a status code equal to that given +func (o *CreateUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateUserProjectDefault) Error() string { + return fmt.Sprintf("[POST /user/projects][%d] createUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserProjectDefault) String() string { + return fmt.Sprintf("[POST /user/projects][%d] createUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserProjectDefault) GetPayload() *CreateUserProjectDefaultBody { + return o.Payload +} + +func (o *CreateUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateUserProjectDefaultBody create user project default body +swagger:model CreateUserProjectDefaultBody +*/ +type CreateUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create user project default body +func (o *CreateUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user project default body based on the context it is used +func (o *CreateUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateUserProjectOKBody create user project o k body +swagger:model CreateUserProjectOKBody +*/ +type CreateUserProjectOKBody struct { + + // result + Result *models.ProjectID `json:"result,omitempty"` +} + +// Validate validates this create user project o k body +func (o *CreateUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user project o k body based on the context it is used +func (o *CreateUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res CreateUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/delete_user_project_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/delete_user_project_parameters.go new file mode 100644 index 0000000..161bf7f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/delete_user_project_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteUserProjectParams creates a new DeleteUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteUserProjectParams() *DeleteUserProjectParams { + return &DeleteUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteUserProjectParamsWithTimeout creates a new DeleteUserProjectParams object +// with the ability to set a timeout on a request. +func NewDeleteUserProjectParamsWithTimeout(timeout time.Duration) *DeleteUserProjectParams { + return &DeleteUserProjectParams{ + timeout: timeout, + } +} + +// NewDeleteUserProjectParamsWithContext creates a new DeleteUserProjectParams object +// with the ability to set a context for a request. +func NewDeleteUserProjectParamsWithContext(ctx context.Context) *DeleteUserProjectParams { + return &DeleteUserProjectParams{ + Context: ctx, + } +} + +// NewDeleteUserProjectParamsWithHTTPClient creates a new DeleteUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteUserProjectParamsWithHTTPClient(client *http.Client) *DeleteUserProjectParams { + return &DeleteUserProjectParams{ + HTTPClient: client, + } +} + +/* DeleteUserProjectParams contains all the parameters to send to the API endpoint + for the delete user project operation. + + Typically these are written to a http.Request. +*/ +type DeleteUserProjectParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserProjectParams) WithDefaults() *DeleteUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete user project params +func (o *DeleteUserProjectParams) WithTimeout(timeout time.Duration) *DeleteUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete user project params +func (o *DeleteUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete user project params +func (o *DeleteUserProjectParams) WithContext(ctx context.Context) *DeleteUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete user project params +func (o *DeleteUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete user project params +func (o *DeleteUserProjectParams) WithHTTPClient(client *http.Client) *DeleteUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete user project params +func (o *DeleteUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete user project params +func (o *DeleteUserProjectParams) WithAuthorization(authorization string) *DeleteUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete user project params +func (o *DeleteUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete user project params +func (o *DeleteUserProjectParams) WithBmpLanguage(bmpLanguage *string) *DeleteUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete user project params +func (o *DeleteUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete user project params +func (o *DeleteUserProjectParams) WithBmpUserID(bmpUserID *string) *DeleteUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete user project params +func (o *DeleteUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the delete user project params +func (o *DeleteUserProjectParams) WithProjectID(projectID string) *DeleteUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the delete user project params +func (o *DeleteUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the delete user project params +func (o *DeleteUserProjectParams) WithTraceID(traceID string) *DeleteUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete user project params +func (o *DeleteUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/delete_user_project_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/delete_user_project_responses.go new file mode 100644 index 0000000..1813aed --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/delete_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteUserProjectReader is a Reader for the DeleteUserProject structure. +type DeleteUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteUserProjectOK creates a DeleteUserProjectOK with default headers values +func NewDeleteUserProjectOK() *DeleteUserProjectOK { + return &DeleteUserProjectOK{} +} + +/* DeleteUserProjectOK describes a response with status code 200, with default header values. + +DeleteUserProjectOK delete user project o k +*/ +type DeleteUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserProjectOKBody +} + +// IsSuccess returns true when this delete user project o k response has a 2xx status code +func (o *DeleteUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete user project o k response has a 3xx status code +func (o *DeleteUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete user project o k response has a 4xx status code +func (o *DeleteUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete user project o k response has a 5xx status code +func (o *DeleteUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete user project o k response a status code equal to that given +func (o *DeleteUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteUserProjectOK) Error() string { + return fmt.Sprintf("[DELETE /user/projects/{project_id}][%d] deleteUserProjectOK %+v", 200, o.Payload) +} + +func (o *DeleteUserProjectOK) String() string { + return fmt.Sprintf("[DELETE /user/projects/{project_id}][%d] deleteUserProjectOK %+v", 200, o.Payload) +} + +func (o *DeleteUserProjectOK) GetPayload() *DeleteUserProjectOKBody { + return o.Payload +} + +func (o *DeleteUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteUserProjectDefault creates a DeleteUserProjectDefault with default headers values +func NewDeleteUserProjectDefault(code int) *DeleteUserProjectDefault { + return &DeleteUserProjectDefault{ + _statusCode: code, + } +} + +/* DeleteUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserProjectDefaultBody +} + +// Code gets the status code for the delete user project default response +func (o *DeleteUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete user project default response has a 2xx status code +func (o *DeleteUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete user project default response has a 3xx status code +func (o *DeleteUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete user project default response has a 4xx status code +func (o *DeleteUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete user project default response has a 5xx status code +func (o *DeleteUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete user project default response a status code equal to that given +func (o *DeleteUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteUserProjectDefault) Error() string { + return fmt.Sprintf("[DELETE /user/projects/{project_id}][%d] deleteUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserProjectDefault) String() string { + return fmt.Sprintf("[DELETE /user/projects/{project_id}][%d] deleteUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserProjectDefault) GetPayload() *DeleteUserProjectDefaultBody { + return o.Payload +} + +func (o *DeleteUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteUserProjectDefaultBody delete user project default body +swagger:model DeleteUserProjectDefaultBody +*/ +type DeleteUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete user project default body +func (o *DeleteUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user project default body based on the context it is used +func (o *DeleteUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteUserProjectOKBody delete user project o k body +swagger:model DeleteUserProjectOKBody +*/ +type DeleteUserProjectOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete user project o k body +func (o *DeleteUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user project o k body based on the context it is used +func (o *DeleteUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res DeleteUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_project_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_project_parameters.go new file mode 100644 index 0000000..3610ef7 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_project_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeUserProjectParams creates a new DescribeUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserProjectParams() *DescribeUserProjectParams { + return &DescribeUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserProjectParamsWithTimeout creates a new DescribeUserProjectParams object +// with the ability to set a timeout on a request. +func NewDescribeUserProjectParamsWithTimeout(timeout time.Duration) *DescribeUserProjectParams { + return &DescribeUserProjectParams{ + timeout: timeout, + } +} + +// NewDescribeUserProjectParamsWithContext creates a new DescribeUserProjectParams object +// with the ability to set a context for a request. +func NewDescribeUserProjectParamsWithContext(ctx context.Context) *DescribeUserProjectParams { + return &DescribeUserProjectParams{ + Context: ctx, + } +} + +// NewDescribeUserProjectParamsWithHTTPClient creates a new DescribeUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserProjectParamsWithHTTPClient(client *http.Client) *DescribeUserProjectParams { + return &DescribeUserProjectParams{ + HTTPClient: client, + } +} + +/* DescribeUserProjectParams contains all the parameters to send to the API endpoint + for the describe user project operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserProjectParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserProjectParams) WithDefaults() *DescribeUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user project params +func (o *DescribeUserProjectParams) WithTimeout(timeout time.Duration) *DescribeUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user project params +func (o *DescribeUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user project params +func (o *DescribeUserProjectParams) WithContext(ctx context.Context) *DescribeUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user project params +func (o *DescribeUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user project params +func (o *DescribeUserProjectParams) WithHTTPClient(client *http.Client) *DescribeUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user project params +func (o *DescribeUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user project params +func (o *DescribeUserProjectParams) WithAuthorization(authorization string) *DescribeUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user project params +func (o *DescribeUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user project params +func (o *DescribeUserProjectParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user project params +func (o *DescribeUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user project params +func (o *DescribeUserProjectParams) WithBmpUserID(bmpUserID *string) *DescribeUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user project params +func (o *DescribeUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the describe user project params +func (o *DescribeUserProjectParams) WithProjectID(projectID string) *DescribeUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the describe user project params +func (o *DescribeUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the describe user project params +func (o *DescribeUserProjectParams) WithTraceID(traceID string) *DescribeUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user project params +func (o *DescribeUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_project_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_project_responses.go new file mode 100644 index 0000000..48e1fa5 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserProjectReader is a Reader for the DescribeUserProject structure. +type DescribeUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserProjectOK creates a DescribeUserProjectOK with default headers values +func NewDescribeUserProjectOK() *DescribeUserProjectOK { + return &DescribeUserProjectOK{} +} + +/* DescribeUserProjectOK describes a response with status code 200, with default header values. + +DescribeUserProjectOK describe user project o k +*/ +type DescribeUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserProjectOKBody +} + +// IsSuccess returns true when this describe user project o k response has a 2xx status code +func (o *DescribeUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user project o k response has a 3xx status code +func (o *DescribeUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user project o k response has a 4xx status code +func (o *DescribeUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user project o k response has a 5xx status code +func (o *DescribeUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user project o k response a status code equal to that given +func (o *DescribeUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserProjectOK) Error() string { + return fmt.Sprintf("[GET /user/projects/{project_id}][%d] describeUserProjectOK %+v", 200, o.Payload) +} + +func (o *DescribeUserProjectOK) String() string { + return fmt.Sprintf("[GET /user/projects/{project_id}][%d] describeUserProjectOK %+v", 200, o.Payload) +} + +func (o *DescribeUserProjectOK) GetPayload() *DescribeUserProjectOKBody { + return o.Payload +} + +func (o *DescribeUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserProjectDefault creates a DescribeUserProjectDefault with default headers values +func NewDescribeUserProjectDefault(code int) *DescribeUserProjectDefault { + return &DescribeUserProjectDefault{ + _statusCode: code, + } +} + +/* DescribeUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserProjectDefaultBody +} + +// Code gets the status code for the describe user project default response +func (o *DescribeUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user project default response has a 2xx status code +func (o *DescribeUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user project default response has a 3xx status code +func (o *DescribeUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user project default response has a 4xx status code +func (o *DescribeUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user project default response has a 5xx status code +func (o *DescribeUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user project default response a status code equal to that given +func (o *DescribeUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserProjectDefault) Error() string { + return fmt.Sprintf("[GET /user/projects/{project_id}][%d] describeUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserProjectDefault) String() string { + return fmt.Sprintf("[GET /user/projects/{project_id}][%d] describeUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserProjectDefault) GetPayload() *DescribeUserProjectDefaultBody { + return o.Payload +} + +func (o *DescribeUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserProjectDefaultBody describe user project default body +swagger:model DescribeUserProjectDefaultBody +*/ +type DescribeUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user project default body +func (o *DescribeUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user project default body based on the context it is used +func (o *DescribeUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserProjectOKBody describe user project o k body +swagger:model DescribeUserProjectOKBody +*/ +type DescribeUserProjectOKBody struct { + + // result + Result *models.ProjectInfo `json:"result,omitempty"` +} + +// Validate validates this describe user project o k body +func (o *DescribeUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user project o k body based on the context it is used +func (o *DescribeUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_projects_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_projects_parameters.go new file mode 100644 index 0000000..1a25ce1 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_projects_parameters.go @@ -0,0 +1,392 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeUserProjectsParams creates a new DescribeUserProjectsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserProjectsParams() *DescribeUserProjectsParams { + return &DescribeUserProjectsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserProjectsParamsWithTimeout creates a new DescribeUserProjectsParams object +// with the ability to set a timeout on a request. +func NewDescribeUserProjectsParamsWithTimeout(timeout time.Duration) *DescribeUserProjectsParams { + return &DescribeUserProjectsParams{ + timeout: timeout, + } +} + +// NewDescribeUserProjectsParamsWithContext creates a new DescribeUserProjectsParams object +// with the ability to set a context for a request. +func NewDescribeUserProjectsParamsWithContext(ctx context.Context) *DescribeUserProjectsParams { + return &DescribeUserProjectsParams{ + Context: ctx, + } +} + +// NewDescribeUserProjectsParamsWithHTTPClient creates a new DescribeUserProjectsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserProjectsParamsWithHTTPClient(client *http.Client) *DescribeUserProjectsParams { + return &DescribeUserProjectsParams{ + HTTPClient: client, + } +} + +/* DescribeUserProjectsParams contains all the parameters to send to the API endpoint + for the describe user projects operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserProjectsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // IsAll. + IsAll *string + + // Owned. + // + // Format: int64 + Owned *int64 + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* ProjectName. + + 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + */ + ProjectName *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user projects params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserProjectsParams) WithDefaults() *DescribeUserProjectsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user projects params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserProjectsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user projects params +func (o *DescribeUserProjectsParams) WithTimeout(timeout time.Duration) *DescribeUserProjectsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user projects params +func (o *DescribeUserProjectsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user projects params +func (o *DescribeUserProjectsParams) WithContext(ctx context.Context) *DescribeUserProjectsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user projects params +func (o *DescribeUserProjectsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user projects params +func (o *DescribeUserProjectsParams) WithHTTPClient(client *http.Client) *DescribeUserProjectsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user projects params +func (o *DescribeUserProjectsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user projects params +func (o *DescribeUserProjectsParams) WithAuthorization(authorization string) *DescribeUserProjectsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user projects params +func (o *DescribeUserProjectsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user projects params +func (o *DescribeUserProjectsParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserProjectsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user projects params +func (o *DescribeUserProjectsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user projects params +func (o *DescribeUserProjectsParams) WithBmpUserID(bmpUserID *string) *DescribeUserProjectsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user projects params +func (o *DescribeUserProjectsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe user projects params +func (o *DescribeUserProjectsParams) WithIsAll(isAll *string) *DescribeUserProjectsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe user projects params +func (o *DescribeUserProjectsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithOwned adds the owned to the describe user projects params +func (o *DescribeUserProjectsParams) WithOwned(owned *int64) *DescribeUserProjectsParams { + o.SetOwned(owned) + return o +} + +// SetOwned adds the owned to the describe user projects params +func (o *DescribeUserProjectsParams) SetOwned(owned *int64) { + o.Owned = owned +} + +// WithPageNumber adds the pageNumber to the describe user projects params +func (o *DescribeUserProjectsParams) WithPageNumber(pageNumber *int64) *DescribeUserProjectsParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe user projects params +func (o *DescribeUserProjectsParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe user projects params +func (o *DescribeUserProjectsParams) WithPageSize(pageSize *int64) *DescribeUserProjectsParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe user projects params +func (o *DescribeUserProjectsParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithProjectName adds the projectName to the describe user projects params +func (o *DescribeUserProjectsParams) WithProjectName(projectName *string) *DescribeUserProjectsParams { + o.SetProjectName(projectName) + return o +} + +// SetProjectName adds the projectName to the describe user projects params +func (o *DescribeUserProjectsParams) SetProjectName(projectName *string) { + o.ProjectName = projectName +} + +// WithTraceID adds the traceID to the describe user projects params +func (o *DescribeUserProjectsParams) WithTraceID(traceID string) *DescribeUserProjectsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user projects params +func (o *DescribeUserProjectsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserProjectsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Owned != nil { + + // query param owned + var qrOwned int64 + + if o.Owned != nil { + qrOwned = *o.Owned + } + qOwned := swag.FormatInt64(qrOwned) + if qOwned != "" { + + if err := r.SetQueryParam("owned", qOwned); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.ProjectName != nil { + + // query param projectName + var qrProjectName string + + if o.ProjectName != nil { + qrProjectName = *o.ProjectName + } + qProjectName := qrProjectName + if qProjectName != "" { + + if err := r.SetQueryParam("projectName", qProjectName); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_projects_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_projects_responses.go new file mode 100644 index 0000000..82f3fb5 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_projects_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserProjectsReader is a Reader for the DescribeUserProjects structure. +type DescribeUserProjectsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserProjectsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserProjectsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserProjectsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserProjectsOK creates a DescribeUserProjectsOK with default headers values +func NewDescribeUserProjectsOK() *DescribeUserProjectsOK { + return &DescribeUserProjectsOK{} +} + +/* DescribeUserProjectsOK describes a response with status code 200, with default header values. + +DescribeUserProjectsOK describe user projects o k +*/ +type DescribeUserProjectsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserProjectsOKBody +} + +// IsSuccess returns true when this describe user projects o k response has a 2xx status code +func (o *DescribeUserProjectsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user projects o k response has a 3xx status code +func (o *DescribeUserProjectsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user projects o k response has a 4xx status code +func (o *DescribeUserProjectsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user projects o k response has a 5xx status code +func (o *DescribeUserProjectsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user projects o k response a status code equal to that given +func (o *DescribeUserProjectsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserProjectsOK) Error() string { + return fmt.Sprintf("[GET /user/projects][%d] describeUserProjectsOK %+v", 200, o.Payload) +} + +func (o *DescribeUserProjectsOK) String() string { + return fmt.Sprintf("[GET /user/projects][%d] describeUserProjectsOK %+v", 200, o.Payload) +} + +func (o *DescribeUserProjectsOK) GetPayload() *DescribeUserProjectsOKBody { + return o.Payload +} + +func (o *DescribeUserProjectsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserProjectsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserProjectsDefault creates a DescribeUserProjectsDefault with default headers values +func NewDescribeUserProjectsDefault(code int) *DescribeUserProjectsDefault { + return &DescribeUserProjectsDefault{ + _statusCode: code, + } +} + +/* DescribeUserProjectsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserProjectsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserProjectsDefaultBody +} + +// Code gets the status code for the describe user projects default response +func (o *DescribeUserProjectsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user projects default response has a 2xx status code +func (o *DescribeUserProjectsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user projects default response has a 3xx status code +func (o *DescribeUserProjectsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user projects default response has a 4xx status code +func (o *DescribeUserProjectsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user projects default response has a 5xx status code +func (o *DescribeUserProjectsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user projects default response a status code equal to that given +func (o *DescribeUserProjectsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserProjectsDefault) Error() string { + return fmt.Sprintf("[GET /user/projects][%d] describeUserProjects default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserProjectsDefault) String() string { + return fmt.Sprintf("[GET /user/projects][%d] describeUserProjects default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserProjectsDefault) GetPayload() *DescribeUserProjectsDefaultBody { + return o.Payload +} + +func (o *DescribeUserProjectsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserProjectsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserProjectsDefaultBody describe user projects default body +swagger:model DescribeUserProjectsDefaultBody +*/ +type DescribeUserProjectsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user projects default body +func (o *DescribeUserProjectsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserProjects default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserProjectsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserProjects default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjects default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjects default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user projects default body based on the context it is used +func (o *DescribeUserProjectsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjects default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjects default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserProjectsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserProjectsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserProjectsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserProjectsOKBody describe user projects o k body +swagger:model DescribeUserProjectsOKBody +*/ +type DescribeUserProjectsOKBody struct { + + // result + Result *models.ProjectList `json:"result,omitempty"` +} + +// Validate validates this describe user projects o k body +func (o *DescribeUserProjectsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjectsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjectsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user projects o k body based on the context it is used +func (o *DescribeUserProjectsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjectsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjectsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserProjectsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserProjectsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserProjectsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/modify_user_project_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/modify_user_project_parameters.go new file mode 100644 index 0000000..cfe9859 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/modify_user_project_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyUserProjectParams creates a new ModifyUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyUserProjectParams() *ModifyUserProjectParams { + return &ModifyUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyUserProjectParamsWithTimeout creates a new ModifyUserProjectParams object +// with the ability to set a timeout on a request. +func NewModifyUserProjectParamsWithTimeout(timeout time.Duration) *ModifyUserProjectParams { + return &ModifyUserProjectParams{ + timeout: timeout, + } +} + +// NewModifyUserProjectParamsWithContext creates a new ModifyUserProjectParams object +// with the ability to set a context for a request. +func NewModifyUserProjectParamsWithContext(ctx context.Context) *ModifyUserProjectParams { + return &ModifyUserProjectParams{ + Context: ctx, + } +} + +// NewModifyUserProjectParamsWithHTTPClient creates a new ModifyUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyUserProjectParamsWithHTTPClient(client *http.Client) *ModifyUserProjectParams { + return &ModifyUserProjectParams{ + HTTPClient: client, + } +} + +/* ModifyUserProjectParams contains all the parameters to send to the API endpoint + for the modify user project operation. + + Typically these are written to a http.Request. +*/ +type ModifyUserProjectParams struct { + + // Body. + Body *models.ModifyProjectRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserProjectParams) WithDefaults() *ModifyUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify user project params +func (o *ModifyUserProjectParams) WithTimeout(timeout time.Duration) *ModifyUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify user project params +func (o *ModifyUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify user project params +func (o *ModifyUserProjectParams) WithContext(ctx context.Context) *ModifyUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify user project params +func (o *ModifyUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify user project params +func (o *ModifyUserProjectParams) WithHTTPClient(client *http.Client) *ModifyUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify user project params +func (o *ModifyUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify user project params +func (o *ModifyUserProjectParams) WithBody(body *models.ModifyProjectRequest) *ModifyUserProjectParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify user project params +func (o *ModifyUserProjectParams) SetBody(body *models.ModifyProjectRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify user project params +func (o *ModifyUserProjectParams) WithAuthorization(authorization string) *ModifyUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify user project params +func (o *ModifyUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify user project params +func (o *ModifyUserProjectParams) WithBmpLanguage(bmpLanguage *string) *ModifyUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify user project params +func (o *ModifyUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify user project params +func (o *ModifyUserProjectParams) WithBmpUserID(bmpUserID *string) *ModifyUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify user project params +func (o *ModifyUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the modify user project params +func (o *ModifyUserProjectParams) WithProjectID(projectID string) *ModifyUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the modify user project params +func (o *ModifyUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the modify user project params +func (o *ModifyUserProjectParams) WithTraceID(traceID string) *ModifyUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify user project params +func (o *ModifyUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/modify_user_project_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/modify_user_project_responses.go new file mode 100644 index 0000000..8f83a32 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/modify_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyUserProjectReader is a Reader for the ModifyUserProject structure. +type ModifyUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyUserProjectOK creates a ModifyUserProjectOK with default headers values +func NewModifyUserProjectOK() *ModifyUserProjectOK { + return &ModifyUserProjectOK{} +} + +/* ModifyUserProjectOK describes a response with status code 200, with default header values. + +ModifyUserProjectOK modify user project o k +*/ +type ModifyUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserProjectOKBody +} + +// IsSuccess returns true when this modify user project o k response has a 2xx status code +func (o *ModifyUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify user project o k response has a 3xx status code +func (o *ModifyUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify user project o k response has a 4xx status code +func (o *ModifyUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify user project o k response has a 5xx status code +func (o *ModifyUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify user project o k response a status code equal to that given +func (o *ModifyUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyUserProjectOK) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}][%d] modifyUserProjectOK %+v", 200, o.Payload) +} + +func (o *ModifyUserProjectOK) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}][%d] modifyUserProjectOK %+v", 200, o.Payload) +} + +func (o *ModifyUserProjectOK) GetPayload() *ModifyUserProjectOKBody { + return o.Payload +} + +func (o *ModifyUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyUserProjectDefault creates a ModifyUserProjectDefault with default headers values +func NewModifyUserProjectDefault(code int) *ModifyUserProjectDefault { + return &ModifyUserProjectDefault{ + _statusCode: code, + } +} + +/* ModifyUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserProjectDefaultBody +} + +// Code gets the status code for the modify user project default response +func (o *ModifyUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify user project default response has a 2xx status code +func (o *ModifyUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify user project default response has a 3xx status code +func (o *ModifyUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify user project default response has a 4xx status code +func (o *ModifyUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify user project default response has a 5xx status code +func (o *ModifyUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify user project default response a status code equal to that given +func (o *ModifyUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyUserProjectDefault) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}][%d] modifyUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserProjectDefault) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}][%d] modifyUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserProjectDefault) GetPayload() *ModifyUserProjectDefaultBody { + return o.Payload +} + +func (o *ModifyUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyUserProjectDefaultBody modify user project default body +swagger:model ModifyUserProjectDefaultBody +*/ +type ModifyUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify user project default body +func (o *ModifyUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user project default body based on the context it is used +func (o *ModifyUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyUserProjectOKBody modify user project o k body +swagger:model ModifyUserProjectOKBody +*/ +type ModifyUserProjectOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify user project o k body +func (o *ModifyUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user project o k body based on the context it is used +func (o *ModifyUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res ModifyUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/project_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/project_client.go new file mode 100644 index 0000000..c886e48 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/project_client.go @@ -0,0 +1,317 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new project API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for project API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CancelShareUserProject(params *CancelShareUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CancelShareUserProjectOK, error) + + CreateUserProject(params *CreateUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserProjectOK, error) + + DeleteUserProject(params *DeleteUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserProjectOK, error) + + DescribeUserProject(params *DescribeUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserProjectOK, error) + + DescribeUserProjects(params *DescribeUserProjectsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserProjectsOK, error) + + ModifyUserProject(params *ModifyUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserProjectOK, error) + + ShareUserProject(params *ShareUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ShareUserProjectOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CancelShareUserProject CancelShareUserProject 取消共享项目 +*/ +func (a *Client) CancelShareUserProject(params *CancelShareUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CancelShareUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCancelShareUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "cancelShareUserProject", + Method: "PUT", + PathPattern: "/user/projects/{project_id}/cancelShare", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CancelShareUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CancelShareUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CancelShareUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + CreateUserProject CreateUserProject 创建项目 +*/ +func (a *Client) CreateUserProject(params *CreateUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "createUserProject", + Method: "POST", + PathPattern: "/user/projects", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteUserProject DeleteUserProject 删除项目 +*/ +func (a *Client) DeleteUserProject(params *DeleteUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "deleteUserProject", + Method: "DELETE", + PathPattern: "/user/projects/{project_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserProject DescribeUserProject 获取项目详情 +*/ +func (a *Client) DescribeUserProject(params *DescribeUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserProject", + Method: "GET", + PathPattern: "/user/projects/{project_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserProjects DescribeUserProjects 获取项目列表 +*/ +func (a *Client) DescribeUserProjects(params *DescribeUserProjectsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserProjectsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserProjectsParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserProjects", + Method: "GET", + PathPattern: "/user/projects", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserProjectsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserProjectsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserProjectsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyUserProject ModifyUserProject 修改项目信息 +*/ +func (a *Client) ModifyUserProject(params *ModifyUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "modifyUserProject", + Method: "PUT", + PathPattern: "/user/projects/{project_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ShareUserProject ShareUserProject 共享项目 +*/ +func (a *Client) ShareUserProject(params *ShareUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ShareUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewShareUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "shareUserProject", + Method: "PUT", + PathPattern: "/user/projects/{project_id}/share", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ShareUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ShareUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ShareUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/share_user_project_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/share_user_project_parameters.go new file mode 100644 index 0000000..f831800 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/share_user_project_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewShareUserProjectParams creates a new ShareUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewShareUserProjectParams() *ShareUserProjectParams { + return &ShareUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewShareUserProjectParamsWithTimeout creates a new ShareUserProjectParams object +// with the ability to set a timeout on a request. +func NewShareUserProjectParamsWithTimeout(timeout time.Duration) *ShareUserProjectParams { + return &ShareUserProjectParams{ + timeout: timeout, + } +} + +// NewShareUserProjectParamsWithContext creates a new ShareUserProjectParams object +// with the ability to set a context for a request. +func NewShareUserProjectParamsWithContext(ctx context.Context) *ShareUserProjectParams { + return &ShareUserProjectParams{ + Context: ctx, + } +} + +// NewShareUserProjectParamsWithHTTPClient creates a new ShareUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewShareUserProjectParamsWithHTTPClient(client *http.Client) *ShareUserProjectParams { + return &ShareUserProjectParams{ + HTTPClient: client, + } +} + +/* ShareUserProjectParams contains all the parameters to send to the API endpoint + for the share user project operation. + + Typically these are written to a http.Request. +*/ +type ShareUserProjectParams struct { + + // Body. + Body *models.ShareProjectRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the share user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ShareUserProjectParams) WithDefaults() *ShareUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the share user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ShareUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the share user project params +func (o *ShareUserProjectParams) WithTimeout(timeout time.Duration) *ShareUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the share user project params +func (o *ShareUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the share user project params +func (o *ShareUserProjectParams) WithContext(ctx context.Context) *ShareUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the share user project params +func (o *ShareUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the share user project params +func (o *ShareUserProjectParams) WithHTTPClient(client *http.Client) *ShareUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the share user project params +func (o *ShareUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the share user project params +func (o *ShareUserProjectParams) WithBody(body *models.ShareProjectRequest) *ShareUserProjectParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the share user project params +func (o *ShareUserProjectParams) SetBody(body *models.ShareProjectRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the share user project params +func (o *ShareUserProjectParams) WithAuthorization(authorization string) *ShareUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the share user project params +func (o *ShareUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the share user project params +func (o *ShareUserProjectParams) WithBmpLanguage(bmpLanguage *string) *ShareUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the share user project params +func (o *ShareUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the share user project params +func (o *ShareUserProjectParams) WithBmpUserID(bmpUserID *string) *ShareUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the share user project params +func (o *ShareUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the share user project params +func (o *ShareUserProjectParams) WithProjectID(projectID string) *ShareUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the share user project params +func (o *ShareUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the share user project params +func (o *ShareUserProjectParams) WithTraceID(traceID string) *ShareUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the share user project params +func (o *ShareUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ShareUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/share_user_project_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/share_user_project_responses.go new file mode 100644 index 0000000..1ff7c2b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/project/share_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ShareUserProjectReader is a Reader for the ShareUserProject structure. +type ShareUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ShareUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewShareUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewShareUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewShareUserProjectOK creates a ShareUserProjectOK with default headers values +func NewShareUserProjectOK() *ShareUserProjectOK { + return &ShareUserProjectOK{} +} + +/* ShareUserProjectOK describes a response with status code 200, with default header values. + +A ShareUserProjectResult is an response struct +*/ +type ShareUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ShareUserProjectOKBody +} + +// IsSuccess returns true when this share user project o k response has a 2xx status code +func (o *ShareUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this share user project o k response has a 3xx status code +func (o *ShareUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this share user project o k response has a 4xx status code +func (o *ShareUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this share user project o k response has a 5xx status code +func (o *ShareUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this share user project o k response a status code equal to that given +func (o *ShareUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ShareUserProjectOK) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/share][%d] shareUserProjectOK %+v", 200, o.Payload) +} + +func (o *ShareUserProjectOK) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/share][%d] shareUserProjectOK %+v", 200, o.Payload) +} + +func (o *ShareUserProjectOK) GetPayload() *ShareUserProjectOKBody { + return o.Payload +} + +func (o *ShareUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ShareUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewShareUserProjectDefault creates a ShareUserProjectDefault with default headers values +func NewShareUserProjectDefault(code int) *ShareUserProjectDefault { + return &ShareUserProjectDefault{ + _statusCode: code, + } +} + +/* ShareUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ShareUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ShareUserProjectDefaultBody +} + +// Code gets the status code for the share user project default response +func (o *ShareUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this share user project default response has a 2xx status code +func (o *ShareUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this share user project default response has a 3xx status code +func (o *ShareUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this share user project default response has a 4xx status code +func (o *ShareUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this share user project default response has a 5xx status code +func (o *ShareUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this share user project default response a status code equal to that given +func (o *ShareUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ShareUserProjectDefault) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/share][%d] shareUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *ShareUserProjectDefault) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/share][%d] shareUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *ShareUserProjectDefault) GetPayload() *ShareUserProjectDefaultBody { + return o.Payload +} + +func (o *ShareUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ShareUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ShareUserProjectDefaultBody share user project default body +swagger:model ShareUserProjectDefaultBody +*/ +type ShareUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this share user project default body +func (o *ShareUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ShareUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("shareUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ShareUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("shareUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this share user project default body based on the context it is used +func (o *ShareUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ShareUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ShareUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ShareUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res ShareUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ShareUserProjectOKBody share user project o k body +swagger:model ShareUserProjectOKBody +*/ +type ShareUserProjectOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this share user project o k body +func (o *ShareUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ShareUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this share user project o k body based on the context it is used +func (o *ShareUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ShareUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ShareUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ShareUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res ShareUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/create_device_type_raid_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/create_device_type_raid_parameters.go new file mode 100644 index 0000000..cda10a7 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/create_device_type_raid_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateDeviceTypeRaidParams creates a new CreateDeviceTypeRaidParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateDeviceTypeRaidParams() *CreateDeviceTypeRaidParams { + return &CreateDeviceTypeRaidParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateDeviceTypeRaidParamsWithTimeout creates a new CreateDeviceTypeRaidParams object +// with the ability to set a timeout on a request. +func NewCreateDeviceTypeRaidParamsWithTimeout(timeout time.Duration) *CreateDeviceTypeRaidParams { + return &CreateDeviceTypeRaidParams{ + timeout: timeout, + } +} + +// NewCreateDeviceTypeRaidParamsWithContext creates a new CreateDeviceTypeRaidParams object +// with the ability to set a context for a request. +func NewCreateDeviceTypeRaidParamsWithContext(ctx context.Context) *CreateDeviceTypeRaidParams { + return &CreateDeviceTypeRaidParams{ + Context: ctx, + } +} + +// NewCreateDeviceTypeRaidParamsWithHTTPClient creates a new CreateDeviceTypeRaidParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateDeviceTypeRaidParamsWithHTTPClient(client *http.Client) *CreateDeviceTypeRaidParams { + return &CreateDeviceTypeRaidParams{ + HTTPClient: client, + } +} + +/* CreateDeviceTypeRaidParams contains all the parameters to send to the API endpoint + for the create device type raid operation. + + Typically these are written to a http.Request. +*/ +type CreateDeviceTypeRaidParams struct { + + // Body. + Body *models.CreateDeviceTypeRaidRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create device type raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateDeviceTypeRaidParams) WithDefaults() *CreateDeviceTypeRaidParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create device type raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateDeviceTypeRaidParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithTimeout(timeout time.Duration) *CreateDeviceTypeRaidParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithContext(ctx context.Context) *CreateDeviceTypeRaidParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithHTTPClient(client *http.Client) *CreateDeviceTypeRaidParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithBody(body *models.CreateDeviceTypeRaidRequest) *CreateDeviceTypeRaidParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetBody(body *models.CreateDeviceTypeRaidRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithAuthorization(authorization string) *CreateDeviceTypeRaidParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithBmpLanguage(bmpLanguage *string) *CreateDeviceTypeRaidParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithBmpUserID(bmpUserID *string) *CreateDeviceTypeRaidParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithTraceID(traceID string) *CreateDeviceTypeRaidParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateDeviceTypeRaidParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/create_device_type_raid_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/create_device_type_raid_responses.go new file mode 100644 index 0000000..c1c691e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/create_device_type_raid_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateDeviceTypeRaidReader is a Reader for the CreateDeviceTypeRaid structure. +type CreateDeviceTypeRaidReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateDeviceTypeRaidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateDeviceTypeRaidOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateDeviceTypeRaidDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateDeviceTypeRaidOK creates a CreateDeviceTypeRaidOK with default headers values +func NewCreateDeviceTypeRaidOK() *CreateDeviceTypeRaidOK { + return &CreateDeviceTypeRaidOK{} +} + +/* CreateDeviceTypeRaidOK describes a response with status code 200, with default header values. + +A CreateDeviceTypeRaidResult is an response struct that is used to describe create device type raid result. +*/ +type CreateDeviceTypeRaidOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateDeviceTypeRaidOKBody +} + +// IsSuccess returns true when this create device type raid o k response has a 2xx status code +func (o *CreateDeviceTypeRaidOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create device type raid o k response has a 3xx status code +func (o *CreateDeviceTypeRaidOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create device type raid o k response has a 4xx status code +func (o *CreateDeviceTypeRaidOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create device type raid o k response has a 5xx status code +func (o *CreateDeviceTypeRaidOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create device type raid o k response a status code equal to that given +func (o *CreateDeviceTypeRaidOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateDeviceTypeRaidOK) Error() string { + return fmt.Sprintf("[POST /raids/deviceTypeRaid][%d] createDeviceTypeRaidOK %+v", 200, o.Payload) +} + +func (o *CreateDeviceTypeRaidOK) String() string { + return fmt.Sprintf("[POST /raids/deviceTypeRaid][%d] createDeviceTypeRaidOK %+v", 200, o.Payload) +} + +func (o *CreateDeviceTypeRaidOK) GetPayload() *CreateDeviceTypeRaidOKBody { + return o.Payload +} + +func (o *CreateDeviceTypeRaidOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateDeviceTypeRaidOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateDeviceTypeRaidDefault creates a CreateDeviceTypeRaidDefault with default headers values +func NewCreateDeviceTypeRaidDefault(code int) *CreateDeviceTypeRaidDefault { + return &CreateDeviceTypeRaidDefault{ + _statusCode: code, + } +} + +/* CreateDeviceTypeRaidDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateDeviceTypeRaidDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateDeviceTypeRaidDefaultBody +} + +// Code gets the status code for the create device type raid default response +func (o *CreateDeviceTypeRaidDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create device type raid default response has a 2xx status code +func (o *CreateDeviceTypeRaidDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create device type raid default response has a 3xx status code +func (o *CreateDeviceTypeRaidDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create device type raid default response has a 4xx status code +func (o *CreateDeviceTypeRaidDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create device type raid default response has a 5xx status code +func (o *CreateDeviceTypeRaidDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create device type raid default response a status code equal to that given +func (o *CreateDeviceTypeRaidDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateDeviceTypeRaidDefault) Error() string { + return fmt.Sprintf("[POST /raids/deviceTypeRaid][%d] createDeviceTypeRaid default %+v", o._statusCode, o.Payload) +} + +func (o *CreateDeviceTypeRaidDefault) String() string { + return fmt.Sprintf("[POST /raids/deviceTypeRaid][%d] createDeviceTypeRaid default %+v", o._statusCode, o.Payload) +} + +func (o *CreateDeviceTypeRaidDefault) GetPayload() *CreateDeviceTypeRaidDefaultBody { + return o.Payload +} + +func (o *CreateDeviceTypeRaidDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateDeviceTypeRaidDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateDeviceTypeRaidDefaultBody create device type raid default body +swagger:model CreateDeviceTypeRaidDefaultBody +*/ +type CreateDeviceTypeRaidDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create device type raid default body +func (o *CreateDeviceTypeRaidDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeRaidDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createDeviceTypeRaid default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateDeviceTypeRaidDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createDeviceTypeRaid default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceTypeRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceTypeRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create device type raid default body based on the context it is used +func (o *CreateDeviceTypeRaidDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeRaidDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceTypeRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceTypeRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateDeviceTypeRaidDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateDeviceTypeRaidDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateDeviceTypeRaidDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateDeviceTypeRaidOKBody create device type raid o k body +swagger:model CreateDeviceTypeRaidOKBody +*/ +type CreateDeviceTypeRaidOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this create device type raid o k body +func (o *CreateDeviceTypeRaidOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeRaidOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceTypeRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceTypeRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create device type raid o k body based on the context it is used +func (o *CreateDeviceTypeRaidOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeRaidOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceTypeRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceTypeRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateDeviceTypeRaidOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateDeviceTypeRaidOKBody) UnmarshalBinary(b []byte) error { + var res CreateDeviceTypeRaidOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/create_raid_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/create_raid_parameters.go new file mode 100644 index 0000000..3af01df --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/create_raid_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateRaidParams creates a new CreateRaidParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateRaidParams() *CreateRaidParams { + return &CreateRaidParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateRaidParamsWithTimeout creates a new CreateRaidParams object +// with the ability to set a timeout on a request. +func NewCreateRaidParamsWithTimeout(timeout time.Duration) *CreateRaidParams { + return &CreateRaidParams{ + timeout: timeout, + } +} + +// NewCreateRaidParamsWithContext creates a new CreateRaidParams object +// with the ability to set a context for a request. +func NewCreateRaidParamsWithContext(ctx context.Context) *CreateRaidParams { + return &CreateRaidParams{ + Context: ctx, + } +} + +// NewCreateRaidParamsWithHTTPClient creates a new CreateRaidParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateRaidParamsWithHTTPClient(client *http.Client) *CreateRaidParams { + return &CreateRaidParams{ + HTTPClient: client, + } +} + +/* CreateRaidParams contains all the parameters to send to the API endpoint + for the create raid operation. + + Typically these are written to a http.Request. +*/ +type CreateRaidParams struct { + + // Body. + Body *models.CreateRaidRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateRaidParams) WithDefaults() *CreateRaidParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateRaidParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create raid params +func (o *CreateRaidParams) WithTimeout(timeout time.Duration) *CreateRaidParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create raid params +func (o *CreateRaidParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create raid params +func (o *CreateRaidParams) WithContext(ctx context.Context) *CreateRaidParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create raid params +func (o *CreateRaidParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create raid params +func (o *CreateRaidParams) WithHTTPClient(client *http.Client) *CreateRaidParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create raid params +func (o *CreateRaidParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create raid params +func (o *CreateRaidParams) WithBody(body *models.CreateRaidRequest) *CreateRaidParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create raid params +func (o *CreateRaidParams) SetBody(body *models.CreateRaidRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create raid params +func (o *CreateRaidParams) WithAuthorization(authorization string) *CreateRaidParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create raid params +func (o *CreateRaidParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create raid params +func (o *CreateRaidParams) WithBmpLanguage(bmpLanguage *string) *CreateRaidParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create raid params +func (o *CreateRaidParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create raid params +func (o *CreateRaidParams) WithBmpUserID(bmpUserID *string) *CreateRaidParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create raid params +func (o *CreateRaidParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create raid params +func (o *CreateRaidParams) WithTraceID(traceID string) *CreateRaidParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create raid params +func (o *CreateRaidParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateRaidParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/create_raid_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/create_raid_responses.go new file mode 100644 index 0000000..7e4b5cd --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/create_raid_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateRaidReader is a Reader for the CreateRaid structure. +type CreateRaidReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateRaidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateRaidOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateRaidDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateRaidOK creates a CreateRaidOK with default headers values +func NewCreateRaidOK() *CreateRaidOK { + return &CreateRaidOK{} +} + +/* CreateRaidOK describes a response with status code 200, with default header values. + +A CreateRaidResult is an response struct that is used to describe create raid result. +*/ +type CreateRaidOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateRaidOKBody +} + +// IsSuccess returns true when this create raid o k response has a 2xx status code +func (o *CreateRaidOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create raid o k response has a 3xx status code +func (o *CreateRaidOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create raid o k response has a 4xx status code +func (o *CreateRaidOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create raid o k response has a 5xx status code +func (o *CreateRaidOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create raid o k response a status code equal to that given +func (o *CreateRaidOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateRaidOK) Error() string { + return fmt.Sprintf("[POST /raids][%d] createRaidOK %+v", 200, o.Payload) +} + +func (o *CreateRaidOK) String() string { + return fmt.Sprintf("[POST /raids][%d] createRaidOK %+v", 200, o.Payload) +} + +func (o *CreateRaidOK) GetPayload() *CreateRaidOKBody { + return o.Payload +} + +func (o *CreateRaidOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateRaidOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateRaidDefault creates a CreateRaidDefault with default headers values +func NewCreateRaidDefault(code int) *CreateRaidDefault { + return &CreateRaidDefault{ + _statusCode: code, + } +} + +/* CreateRaidDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateRaidDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateRaidDefaultBody +} + +// Code gets the status code for the create raid default response +func (o *CreateRaidDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create raid default response has a 2xx status code +func (o *CreateRaidDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create raid default response has a 3xx status code +func (o *CreateRaidDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create raid default response has a 4xx status code +func (o *CreateRaidDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create raid default response has a 5xx status code +func (o *CreateRaidDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create raid default response a status code equal to that given +func (o *CreateRaidDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateRaidDefault) Error() string { + return fmt.Sprintf("[POST /raids][%d] createRaid default %+v", o._statusCode, o.Payload) +} + +func (o *CreateRaidDefault) String() string { + return fmt.Sprintf("[POST /raids][%d] createRaid default %+v", o._statusCode, o.Payload) +} + +func (o *CreateRaidDefault) GetPayload() *CreateRaidDefaultBody { + return o.Payload +} + +func (o *CreateRaidDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateRaidDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateRaidDefaultBody create raid default body +swagger:model CreateRaidDefaultBody +*/ +type CreateRaidDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create raid default body +func (o *CreateRaidDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRaidDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createRaid default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateRaidDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createRaid default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create raid default body based on the context it is used +func (o *CreateRaidDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRaidDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateRaidDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateRaidDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateRaidDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateRaidOKBody create raid o k body +swagger:model CreateRaidOKBody +*/ +type CreateRaidOKBody struct { + + // result + Result *models.RaidID `json:"result,omitempty"` +} + +// Validate validates this create raid o k body +func (o *CreateRaidOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRaidOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create raid o k body based on the context it is used +func (o *CreateRaidOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRaidOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateRaidOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateRaidOKBody) UnmarshalBinary(b []byte) error { + var res CreateRaidOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/delete_device_type_raid_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/delete_device_type_raid_parameters.go new file mode 100644 index 0000000..f14b807 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/delete_device_type_raid_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewDeleteDeviceTypeRaidParams creates a new DeleteDeviceTypeRaidParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteDeviceTypeRaidParams() *DeleteDeviceTypeRaidParams { + return &DeleteDeviceTypeRaidParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteDeviceTypeRaidParamsWithTimeout creates a new DeleteDeviceTypeRaidParams object +// with the ability to set a timeout on a request. +func NewDeleteDeviceTypeRaidParamsWithTimeout(timeout time.Duration) *DeleteDeviceTypeRaidParams { + return &DeleteDeviceTypeRaidParams{ + timeout: timeout, + } +} + +// NewDeleteDeviceTypeRaidParamsWithContext creates a new DeleteDeviceTypeRaidParams object +// with the ability to set a context for a request. +func NewDeleteDeviceTypeRaidParamsWithContext(ctx context.Context) *DeleteDeviceTypeRaidParams { + return &DeleteDeviceTypeRaidParams{ + Context: ctx, + } +} + +// NewDeleteDeviceTypeRaidParamsWithHTTPClient creates a new DeleteDeviceTypeRaidParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteDeviceTypeRaidParamsWithHTTPClient(client *http.Client) *DeleteDeviceTypeRaidParams { + return &DeleteDeviceTypeRaidParams{ + HTTPClient: client, + } +} + +/* DeleteDeviceTypeRaidParams contains all the parameters to send to the API endpoint + for the delete device type raid operation. + + Typically these are written to a http.Request. +*/ +type DeleteDeviceTypeRaidParams struct { + + // Body. + Body *models.DeleteDeviceTypeRaidRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete device type raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteDeviceTypeRaidParams) WithDefaults() *DeleteDeviceTypeRaidParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete device type raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteDeviceTypeRaidParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithTimeout(timeout time.Duration) *DeleteDeviceTypeRaidParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithContext(ctx context.Context) *DeleteDeviceTypeRaidParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithHTTPClient(client *http.Client) *DeleteDeviceTypeRaidParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithBody(body *models.DeleteDeviceTypeRaidRequest) *DeleteDeviceTypeRaidParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetBody(body *models.DeleteDeviceTypeRaidRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithAuthorization(authorization string) *DeleteDeviceTypeRaidParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithBmpLanguage(bmpLanguage *string) *DeleteDeviceTypeRaidParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithBmpUserID(bmpUserID *string) *DeleteDeviceTypeRaidParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithTraceID(traceID string) *DeleteDeviceTypeRaidParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteDeviceTypeRaidParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/delete_device_type_raid_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/delete_device_type_raid_responses.go new file mode 100644 index 0000000..63d897c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/delete_device_type_raid_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteDeviceTypeRaidReader is a Reader for the DeleteDeviceTypeRaid structure. +type DeleteDeviceTypeRaidReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteDeviceTypeRaidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteDeviceTypeRaidOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteDeviceTypeRaidDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteDeviceTypeRaidOK creates a DeleteDeviceTypeRaidOK with default headers values +func NewDeleteDeviceTypeRaidOK() *DeleteDeviceTypeRaidOK { + return &DeleteDeviceTypeRaidOK{} +} + +/* DeleteDeviceTypeRaidOK describes a response with status code 200, with default header values. + +A DeleteDeviceTypeRaidResult is an response struct that is used to describe delete device type raid result. +*/ +type DeleteDeviceTypeRaidOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteDeviceTypeRaidOKBody +} + +// IsSuccess returns true when this delete device type raid o k response has a 2xx status code +func (o *DeleteDeviceTypeRaidOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete device type raid o k response has a 3xx status code +func (o *DeleteDeviceTypeRaidOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete device type raid o k response has a 4xx status code +func (o *DeleteDeviceTypeRaidOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete device type raid o k response has a 5xx status code +func (o *DeleteDeviceTypeRaidOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete device type raid o k response a status code equal to that given +func (o *DeleteDeviceTypeRaidOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteDeviceTypeRaidOK) Error() string { + return fmt.Sprintf("[DELETE /raids/deviceTypeRaid][%d] deleteDeviceTypeRaidOK %+v", 200, o.Payload) +} + +func (o *DeleteDeviceTypeRaidOK) String() string { + return fmt.Sprintf("[DELETE /raids/deviceTypeRaid][%d] deleteDeviceTypeRaidOK %+v", 200, o.Payload) +} + +func (o *DeleteDeviceTypeRaidOK) GetPayload() *DeleteDeviceTypeRaidOKBody { + return o.Payload +} + +func (o *DeleteDeviceTypeRaidOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteDeviceTypeRaidOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteDeviceTypeRaidDefault creates a DeleteDeviceTypeRaidDefault with default headers values +func NewDeleteDeviceTypeRaidDefault(code int) *DeleteDeviceTypeRaidDefault { + return &DeleteDeviceTypeRaidDefault{ + _statusCode: code, + } +} + +/* DeleteDeviceTypeRaidDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteDeviceTypeRaidDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteDeviceTypeRaidDefaultBody +} + +// Code gets the status code for the delete device type raid default response +func (o *DeleteDeviceTypeRaidDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete device type raid default response has a 2xx status code +func (o *DeleteDeviceTypeRaidDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete device type raid default response has a 3xx status code +func (o *DeleteDeviceTypeRaidDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete device type raid default response has a 4xx status code +func (o *DeleteDeviceTypeRaidDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete device type raid default response has a 5xx status code +func (o *DeleteDeviceTypeRaidDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete device type raid default response a status code equal to that given +func (o *DeleteDeviceTypeRaidDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteDeviceTypeRaidDefault) Error() string { + return fmt.Sprintf("[DELETE /raids/deviceTypeRaid][%d] deleteDeviceTypeRaid default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteDeviceTypeRaidDefault) String() string { + return fmt.Sprintf("[DELETE /raids/deviceTypeRaid][%d] deleteDeviceTypeRaid default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteDeviceTypeRaidDefault) GetPayload() *DeleteDeviceTypeRaidDefaultBody { + return o.Payload +} + +func (o *DeleteDeviceTypeRaidDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteDeviceTypeRaidDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteDeviceTypeRaidDefaultBody delete device type raid default body +swagger:model DeleteDeviceTypeRaidDefaultBody +*/ +type DeleteDeviceTypeRaidDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete device type raid default body +func (o *DeleteDeviceTypeRaidDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeRaidDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteDeviceTypeRaid default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteDeviceTypeRaidDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteDeviceTypeRaid default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceTypeRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceTypeRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete device type raid default body based on the context it is used +func (o *DeleteDeviceTypeRaidDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeRaidDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceTypeRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceTypeRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteDeviceTypeRaidDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteDeviceTypeRaidDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteDeviceTypeRaidDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteDeviceTypeRaidOKBody delete device type raid o k body +swagger:model DeleteDeviceTypeRaidOKBody +*/ +type DeleteDeviceTypeRaidOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete device type raid o k body +func (o *DeleteDeviceTypeRaidOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeRaidOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceTypeRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceTypeRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete device type raid o k body based on the context it is used +func (o *DeleteDeviceTypeRaidOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeRaidOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceTypeRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceTypeRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteDeviceTypeRaidOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteDeviceTypeRaidOKBody) UnmarshalBinary(b []byte) error { + var res DeleteDeviceTypeRaidOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/delete_raid_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/delete_raid_parameters.go new file mode 100644 index 0000000..4264cce --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/delete_raid_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteRaidParams creates a new DeleteRaidParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteRaidParams() *DeleteRaidParams { + return &DeleteRaidParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteRaidParamsWithTimeout creates a new DeleteRaidParams object +// with the ability to set a timeout on a request. +func NewDeleteRaidParamsWithTimeout(timeout time.Duration) *DeleteRaidParams { + return &DeleteRaidParams{ + timeout: timeout, + } +} + +// NewDeleteRaidParamsWithContext creates a new DeleteRaidParams object +// with the ability to set a context for a request. +func NewDeleteRaidParamsWithContext(ctx context.Context) *DeleteRaidParams { + return &DeleteRaidParams{ + Context: ctx, + } +} + +// NewDeleteRaidParamsWithHTTPClient creates a new DeleteRaidParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteRaidParamsWithHTTPClient(client *http.Client) *DeleteRaidParams { + return &DeleteRaidParams{ + HTTPClient: client, + } +} + +/* DeleteRaidParams contains all the parameters to send to the API endpoint + for the delete raid operation. + + Typically these are written to a http.Request. +*/ +type DeleteRaidParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // RaidID. + RaidID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteRaidParams) WithDefaults() *DeleteRaidParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteRaidParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete raid params +func (o *DeleteRaidParams) WithTimeout(timeout time.Duration) *DeleteRaidParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete raid params +func (o *DeleteRaidParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete raid params +func (o *DeleteRaidParams) WithContext(ctx context.Context) *DeleteRaidParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete raid params +func (o *DeleteRaidParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete raid params +func (o *DeleteRaidParams) WithHTTPClient(client *http.Client) *DeleteRaidParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete raid params +func (o *DeleteRaidParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete raid params +func (o *DeleteRaidParams) WithAuthorization(authorization string) *DeleteRaidParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete raid params +func (o *DeleteRaidParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete raid params +func (o *DeleteRaidParams) WithBmpLanguage(bmpLanguage *string) *DeleteRaidParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete raid params +func (o *DeleteRaidParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete raid params +func (o *DeleteRaidParams) WithBmpUserID(bmpUserID *string) *DeleteRaidParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete raid params +func (o *DeleteRaidParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithRaidID adds the raidID to the delete raid params +func (o *DeleteRaidParams) WithRaidID(raidID string) *DeleteRaidParams { + o.SetRaidID(raidID) + return o +} + +// SetRaidID adds the raidId to the delete raid params +func (o *DeleteRaidParams) SetRaidID(raidID string) { + o.RaidID = raidID +} + +// WithTraceID adds the traceID to the delete raid params +func (o *DeleteRaidParams) WithTraceID(traceID string) *DeleteRaidParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete raid params +func (o *DeleteRaidParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteRaidParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param raid_id + if err := r.SetPathParam("raid_id", o.RaidID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/delete_raid_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/delete_raid_responses.go new file mode 100644 index 0000000..553b72a --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/delete_raid_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteRaidReader is a Reader for the DeleteRaid structure. +type DeleteRaidReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteRaidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteRaidOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteRaidDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteRaidOK creates a DeleteRaidOK with default headers values +func NewDeleteRaidOK() *DeleteRaidOK { + return &DeleteRaidOK{} +} + +/* DeleteRaidOK describes a response with status code 200, with default header values. + +A DeleteRaidResult is an response struct that is used to delete raid. +*/ +type DeleteRaidOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteRaidOKBody +} + +// IsSuccess returns true when this delete raid o k response has a 2xx status code +func (o *DeleteRaidOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete raid o k response has a 3xx status code +func (o *DeleteRaidOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete raid o k response has a 4xx status code +func (o *DeleteRaidOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete raid o k response has a 5xx status code +func (o *DeleteRaidOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete raid o k response a status code equal to that given +func (o *DeleteRaidOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteRaidOK) Error() string { + return fmt.Sprintf("[DELETE /raids/{raid_id}][%d] deleteRaidOK %+v", 200, o.Payload) +} + +func (o *DeleteRaidOK) String() string { + return fmt.Sprintf("[DELETE /raids/{raid_id}][%d] deleteRaidOK %+v", 200, o.Payload) +} + +func (o *DeleteRaidOK) GetPayload() *DeleteRaidOKBody { + return o.Payload +} + +func (o *DeleteRaidOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteRaidOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteRaidDefault creates a DeleteRaidDefault with default headers values +func NewDeleteRaidDefault(code int) *DeleteRaidDefault { + return &DeleteRaidDefault{ + _statusCode: code, + } +} + +/* DeleteRaidDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteRaidDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteRaidDefaultBody +} + +// Code gets the status code for the delete raid default response +func (o *DeleteRaidDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete raid default response has a 2xx status code +func (o *DeleteRaidDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete raid default response has a 3xx status code +func (o *DeleteRaidDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete raid default response has a 4xx status code +func (o *DeleteRaidDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete raid default response has a 5xx status code +func (o *DeleteRaidDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete raid default response a status code equal to that given +func (o *DeleteRaidDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteRaidDefault) Error() string { + return fmt.Sprintf("[DELETE /raids/{raid_id}][%d] deleteRaid default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteRaidDefault) String() string { + return fmt.Sprintf("[DELETE /raids/{raid_id}][%d] deleteRaid default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteRaidDefault) GetPayload() *DeleteRaidDefaultBody { + return o.Payload +} + +func (o *DeleteRaidDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteRaidDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteRaidDefaultBody delete raid default body +swagger:model DeleteRaidDefaultBody +*/ +type DeleteRaidDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete raid default body +func (o *DeleteRaidDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRaidDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteRaid default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteRaidDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteRaid default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete raid default body based on the context it is used +func (o *DeleteRaidDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRaidDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteRaidDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteRaidDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteRaidDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteRaidOKBody delete raid o k body +swagger:model DeleteRaidOKBody +*/ +type DeleteRaidOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete raid o k body +func (o *DeleteRaidOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRaidOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete raid o k body based on the context it is used +func (o *DeleteRaidOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRaidOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteRaidOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteRaidOKBody) UnmarshalBinary(b []byte) error { + var res DeleteRaidOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raid_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raid_parameters.go new file mode 100644 index 0000000..adc6c1b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raid_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeRaidParams creates a new DescribeRaidParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeRaidParams() *DescribeRaidParams { + return &DescribeRaidParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeRaidParamsWithTimeout creates a new DescribeRaidParams object +// with the ability to set a timeout on a request. +func NewDescribeRaidParamsWithTimeout(timeout time.Duration) *DescribeRaidParams { + return &DescribeRaidParams{ + timeout: timeout, + } +} + +// NewDescribeRaidParamsWithContext creates a new DescribeRaidParams object +// with the ability to set a context for a request. +func NewDescribeRaidParamsWithContext(ctx context.Context) *DescribeRaidParams { + return &DescribeRaidParams{ + Context: ctx, + } +} + +// NewDescribeRaidParamsWithHTTPClient creates a new DescribeRaidParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeRaidParamsWithHTTPClient(client *http.Client) *DescribeRaidParams { + return &DescribeRaidParams{ + HTTPClient: client, + } +} + +/* DescribeRaidParams contains all the parameters to send to the API endpoint + for the describe raid operation. + + Typically these are written to a http.Request. +*/ +type DescribeRaidParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // RaidID. + RaidID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRaidParams) WithDefaults() *DescribeRaidParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRaidParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe raid params +func (o *DescribeRaidParams) WithTimeout(timeout time.Duration) *DescribeRaidParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe raid params +func (o *DescribeRaidParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe raid params +func (o *DescribeRaidParams) WithContext(ctx context.Context) *DescribeRaidParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe raid params +func (o *DescribeRaidParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe raid params +func (o *DescribeRaidParams) WithHTTPClient(client *http.Client) *DescribeRaidParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe raid params +func (o *DescribeRaidParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe raid params +func (o *DescribeRaidParams) WithAuthorization(authorization string) *DescribeRaidParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe raid params +func (o *DescribeRaidParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe raid params +func (o *DescribeRaidParams) WithBmpLanguage(bmpLanguage *string) *DescribeRaidParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe raid params +func (o *DescribeRaidParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe raid params +func (o *DescribeRaidParams) WithBmpUserID(bmpUserID *string) *DescribeRaidParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe raid params +func (o *DescribeRaidParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithRaidID adds the raidID to the describe raid params +func (o *DescribeRaidParams) WithRaidID(raidID string) *DescribeRaidParams { + o.SetRaidID(raidID) + return o +} + +// SetRaidID adds the raidId to the describe raid params +func (o *DescribeRaidParams) SetRaidID(raidID string) { + o.RaidID = raidID +} + +// WithTraceID adds the traceID to the describe raid params +func (o *DescribeRaidParams) WithTraceID(traceID string) *DescribeRaidParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe raid params +func (o *DescribeRaidParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeRaidParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param raid_id + if err := r.SetPathParam("raid_id", o.RaidID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raid_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raid_responses.go new file mode 100644 index 0000000..d256d8d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raid_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeRaidReader is a Reader for the DescribeRaid structure. +type DescribeRaidReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeRaidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeRaidOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeRaidDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeRaidOK creates a DescribeRaidOK with default headers values +func NewDescribeRaidOK() *DescribeRaidOK { + return &DescribeRaidOK{} +} + +/* DescribeRaidOK describes a response with status code 200, with default header values. + +A GetRaidResult is an response struct that is used to describe raid. +*/ +type DescribeRaidOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRaidOKBody +} + +// IsSuccess returns true when this describe raid o k response has a 2xx status code +func (o *DescribeRaidOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe raid o k response has a 3xx status code +func (o *DescribeRaidOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe raid o k response has a 4xx status code +func (o *DescribeRaidOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe raid o k response has a 5xx status code +func (o *DescribeRaidOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe raid o k response a status code equal to that given +func (o *DescribeRaidOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeRaidOK) Error() string { + return fmt.Sprintf("[GET /raids/{raid_id}][%d] describeRaidOK %+v", 200, o.Payload) +} + +func (o *DescribeRaidOK) String() string { + return fmt.Sprintf("[GET /raids/{raid_id}][%d] describeRaidOK %+v", 200, o.Payload) +} + +func (o *DescribeRaidOK) GetPayload() *DescribeRaidOKBody { + return o.Payload +} + +func (o *DescribeRaidOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRaidOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeRaidDefault creates a DescribeRaidDefault with default headers values +func NewDescribeRaidDefault(code int) *DescribeRaidDefault { + return &DescribeRaidDefault{ + _statusCode: code, + } +} + +/* DescribeRaidDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeRaidDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRaidDefaultBody +} + +// Code gets the status code for the describe raid default response +func (o *DescribeRaidDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe raid default response has a 2xx status code +func (o *DescribeRaidDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe raid default response has a 3xx status code +func (o *DescribeRaidDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe raid default response has a 4xx status code +func (o *DescribeRaidDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe raid default response has a 5xx status code +func (o *DescribeRaidDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe raid default response a status code equal to that given +func (o *DescribeRaidDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeRaidDefault) Error() string { + return fmt.Sprintf("[GET /raids/{raid_id}][%d] describeRaid default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRaidDefault) String() string { + return fmt.Sprintf("[GET /raids/{raid_id}][%d] describeRaid default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRaidDefault) GetPayload() *DescribeRaidDefaultBody { + return o.Payload +} + +func (o *DescribeRaidDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRaidDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeRaidDefaultBody describe raid default body +swagger:model DescribeRaidDefaultBody +*/ +type DescribeRaidDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe raid default body +func (o *DescribeRaidDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeRaid default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeRaidDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeRaid default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe raid default body based on the context it is used +func (o *DescribeRaidDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRaidDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRaidDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeRaidDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeRaidOKBody describe raid o k body +swagger:model DescribeRaidOKBody +*/ +type DescribeRaidOKBody struct { + + // result + Result *models.Raid `json:"result,omitempty"` +} + +// Validate validates this describe raid o k body +func (o *DescribeRaidOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe raid o k body based on the context it is used +func (o *DescribeRaidOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRaidOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRaidOKBody) UnmarshalBinary(b []byte) error { + var res DescribeRaidOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raids_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raids_parameters.go new file mode 100644 index 0000000..c9da3d1 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raids_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeRaidsParams creates a new DescribeRaidsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeRaidsParams() *DescribeRaidsParams { + return &DescribeRaidsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeRaidsParamsWithTimeout creates a new DescribeRaidsParams object +// with the ability to set a timeout on a request. +func NewDescribeRaidsParamsWithTimeout(timeout time.Duration) *DescribeRaidsParams { + return &DescribeRaidsParams{ + timeout: timeout, + } +} + +// NewDescribeRaidsParamsWithContext creates a new DescribeRaidsParams object +// with the ability to set a context for a request. +func NewDescribeRaidsParamsWithContext(ctx context.Context) *DescribeRaidsParams { + return &DescribeRaidsParams{ + Context: ctx, + } +} + +// NewDescribeRaidsParamsWithHTTPClient creates a new DescribeRaidsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeRaidsParamsWithHTTPClient(client *http.Client) *DescribeRaidsParams { + return &DescribeRaidsParams{ + HTTPClient: client, + } +} + +/* DescribeRaidsParams contains all the parameters to send to the API endpoint + for the describe raids operation. + + Typically these are written to a http.Request. +*/ +type DescribeRaidsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe raids params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRaidsParams) WithDefaults() *DescribeRaidsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe raids params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRaidsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe raids params +func (o *DescribeRaidsParams) WithTimeout(timeout time.Duration) *DescribeRaidsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe raids params +func (o *DescribeRaidsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe raids params +func (o *DescribeRaidsParams) WithContext(ctx context.Context) *DescribeRaidsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe raids params +func (o *DescribeRaidsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe raids params +func (o *DescribeRaidsParams) WithHTTPClient(client *http.Client) *DescribeRaidsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe raids params +func (o *DescribeRaidsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe raids params +func (o *DescribeRaidsParams) WithAuthorization(authorization string) *DescribeRaidsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe raids params +func (o *DescribeRaidsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe raids params +func (o *DescribeRaidsParams) WithBmpLanguage(bmpLanguage *string) *DescribeRaidsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe raids params +func (o *DescribeRaidsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe raids params +func (o *DescribeRaidsParams) WithBmpUserID(bmpUserID *string) *DescribeRaidsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe raids params +func (o *DescribeRaidsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe raids params +func (o *DescribeRaidsParams) WithTraceID(traceID string) *DescribeRaidsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe raids params +func (o *DescribeRaidsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeRaidsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raids_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raids_responses.go new file mode 100644 index 0000000..27ce6f8 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raids_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeRaidsReader is a Reader for the DescribeRaids structure. +type DescribeRaidsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeRaidsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeRaidsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeRaidsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeRaidsOK creates a DescribeRaidsOK with default headers values +func NewDescribeRaidsOK() *DescribeRaidsOK { + return &DescribeRaidsOK{} +} + +/* DescribeRaidsOK describes a response with status code 200, with default header values. + +QueryRaidsAllResult is an response struct that is used to query all raids. +*/ +type DescribeRaidsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRaidsOKBody +} + +// IsSuccess returns true when this describe raids o k response has a 2xx status code +func (o *DescribeRaidsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe raids o k response has a 3xx status code +func (o *DescribeRaidsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe raids o k response has a 4xx status code +func (o *DescribeRaidsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe raids o k response has a 5xx status code +func (o *DescribeRaidsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe raids o k response a status code equal to that given +func (o *DescribeRaidsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeRaidsOK) Error() string { + return fmt.Sprintf("[GET /raids][%d] describeRaidsOK %+v", 200, o.Payload) +} + +func (o *DescribeRaidsOK) String() string { + return fmt.Sprintf("[GET /raids][%d] describeRaidsOK %+v", 200, o.Payload) +} + +func (o *DescribeRaidsOK) GetPayload() *DescribeRaidsOKBody { + return o.Payload +} + +func (o *DescribeRaidsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRaidsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeRaidsDefault creates a DescribeRaidsDefault with default headers values +func NewDescribeRaidsDefault(code int) *DescribeRaidsDefault { + return &DescribeRaidsDefault{ + _statusCode: code, + } +} + +/* DescribeRaidsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeRaidsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRaidsDefaultBody +} + +// Code gets the status code for the describe raids default response +func (o *DescribeRaidsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe raids default response has a 2xx status code +func (o *DescribeRaidsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe raids default response has a 3xx status code +func (o *DescribeRaidsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe raids default response has a 4xx status code +func (o *DescribeRaidsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe raids default response has a 5xx status code +func (o *DescribeRaidsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe raids default response a status code equal to that given +func (o *DescribeRaidsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeRaidsDefault) Error() string { + return fmt.Sprintf("[GET /raids][%d] describeRaids default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRaidsDefault) String() string { + return fmt.Sprintf("[GET /raids][%d] describeRaids default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRaidsDefault) GetPayload() *DescribeRaidsDefaultBody { + return o.Payload +} + +func (o *DescribeRaidsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRaidsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeRaidsDefaultBody describe raids default body +swagger:model DescribeRaidsDefaultBody +*/ +type DescribeRaidsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe raids default body +func (o *DescribeRaidsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeRaids default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeRaidsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeRaids default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaids default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaids default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe raids default body based on the context it is used +func (o *DescribeRaidsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaids default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaids default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRaidsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRaidsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeRaidsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeRaidsOKBody describe raids o k body +swagger:model DescribeRaidsOKBody +*/ +type DescribeRaidsOKBody struct { + + // result + Result *models.RaidList `json:"result,omitempty"` +} + +// Validate validates this describe raids o k body +func (o *DescribeRaidsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaidsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaidsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe raids o k body based on the context it is used +func (o *DescribeRaidsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaidsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaidsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRaidsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRaidsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeRaidsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/modify_raid_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/modify_raid_parameters.go new file mode 100644 index 0000000..cc283b9 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/modify_raid_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyRaidParams creates a new ModifyRaidParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyRaidParams() *ModifyRaidParams { + return &ModifyRaidParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyRaidParamsWithTimeout creates a new ModifyRaidParams object +// with the ability to set a timeout on a request. +func NewModifyRaidParamsWithTimeout(timeout time.Duration) *ModifyRaidParams { + return &ModifyRaidParams{ + timeout: timeout, + } +} + +// NewModifyRaidParamsWithContext creates a new ModifyRaidParams object +// with the ability to set a context for a request. +func NewModifyRaidParamsWithContext(ctx context.Context) *ModifyRaidParams { + return &ModifyRaidParams{ + Context: ctx, + } +} + +// NewModifyRaidParamsWithHTTPClient creates a new ModifyRaidParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyRaidParamsWithHTTPClient(client *http.Client) *ModifyRaidParams { + return &ModifyRaidParams{ + HTTPClient: client, + } +} + +/* ModifyRaidParams contains all the parameters to send to the API endpoint + for the modify raid operation. + + Typically these are written to a http.Request. +*/ +type ModifyRaidParams struct { + + // Body. + Body *models.ModifyRaidRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // RaidID. + RaidID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyRaidParams) WithDefaults() *ModifyRaidParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyRaidParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify raid params +func (o *ModifyRaidParams) WithTimeout(timeout time.Duration) *ModifyRaidParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify raid params +func (o *ModifyRaidParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify raid params +func (o *ModifyRaidParams) WithContext(ctx context.Context) *ModifyRaidParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify raid params +func (o *ModifyRaidParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify raid params +func (o *ModifyRaidParams) WithHTTPClient(client *http.Client) *ModifyRaidParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify raid params +func (o *ModifyRaidParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify raid params +func (o *ModifyRaidParams) WithBody(body *models.ModifyRaidRequest) *ModifyRaidParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify raid params +func (o *ModifyRaidParams) SetBody(body *models.ModifyRaidRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify raid params +func (o *ModifyRaidParams) WithAuthorization(authorization string) *ModifyRaidParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify raid params +func (o *ModifyRaidParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify raid params +func (o *ModifyRaidParams) WithBmpLanguage(bmpLanguage *string) *ModifyRaidParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify raid params +func (o *ModifyRaidParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify raid params +func (o *ModifyRaidParams) WithBmpUserID(bmpUserID *string) *ModifyRaidParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify raid params +func (o *ModifyRaidParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithRaidID adds the raidID to the modify raid params +func (o *ModifyRaidParams) WithRaidID(raidID string) *ModifyRaidParams { + o.SetRaidID(raidID) + return o +} + +// SetRaidID adds the raidId to the modify raid params +func (o *ModifyRaidParams) SetRaidID(raidID string) { + o.RaidID = raidID +} + +// WithTraceID adds the traceID to the modify raid params +func (o *ModifyRaidParams) WithTraceID(traceID string) *ModifyRaidParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify raid params +func (o *ModifyRaidParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyRaidParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param raid_id + if err := r.SetPathParam("raid_id", o.RaidID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/modify_raid_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/modify_raid_responses.go new file mode 100644 index 0000000..12bbeac --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/modify_raid_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyRaidReader is a Reader for the ModifyRaid structure. +type ModifyRaidReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyRaidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyRaidOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyRaidDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyRaidOK creates a ModifyRaidOK with default headers values +func NewModifyRaidOK() *ModifyRaidOK { + return &ModifyRaidOK{} +} + +/* ModifyRaidOK describes a response with status code 200, with default header values. + +A ModifyRaidResult is an response struct that is used to describe modify raid. +*/ +type ModifyRaidOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyRaidOKBody +} + +// IsSuccess returns true when this modify raid o k response has a 2xx status code +func (o *ModifyRaidOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify raid o k response has a 3xx status code +func (o *ModifyRaidOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify raid o k response has a 4xx status code +func (o *ModifyRaidOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify raid o k response has a 5xx status code +func (o *ModifyRaidOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify raid o k response a status code equal to that given +func (o *ModifyRaidOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyRaidOK) Error() string { + return fmt.Sprintf("[PUT /raids/{raid_id}][%d] modifyRaidOK %+v", 200, o.Payload) +} + +func (o *ModifyRaidOK) String() string { + return fmt.Sprintf("[PUT /raids/{raid_id}][%d] modifyRaidOK %+v", 200, o.Payload) +} + +func (o *ModifyRaidOK) GetPayload() *ModifyRaidOKBody { + return o.Payload +} + +func (o *ModifyRaidOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyRaidOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyRaidDefault creates a ModifyRaidDefault with default headers values +func NewModifyRaidDefault(code int) *ModifyRaidDefault { + return &ModifyRaidDefault{ + _statusCode: code, + } +} + +/* ModifyRaidDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyRaidDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyRaidDefaultBody +} + +// Code gets the status code for the modify raid default response +func (o *ModifyRaidDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify raid default response has a 2xx status code +func (o *ModifyRaidDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify raid default response has a 3xx status code +func (o *ModifyRaidDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify raid default response has a 4xx status code +func (o *ModifyRaidDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify raid default response has a 5xx status code +func (o *ModifyRaidDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify raid default response a status code equal to that given +func (o *ModifyRaidDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyRaidDefault) Error() string { + return fmt.Sprintf("[PUT /raids/{raid_id}][%d] modifyRaid default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyRaidDefault) String() string { + return fmt.Sprintf("[PUT /raids/{raid_id}][%d] modifyRaid default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyRaidDefault) GetPayload() *ModifyRaidDefaultBody { + return o.Payload +} + +func (o *ModifyRaidDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyRaidDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyRaidDefaultBody modify raid default body +swagger:model ModifyRaidDefaultBody +*/ +type ModifyRaidDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify raid default body +func (o *ModifyRaidDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRaidDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyRaid default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyRaidDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyRaid default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify raid default body based on the context it is used +func (o *ModifyRaidDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRaidDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyRaidDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyRaidDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyRaidDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyRaidOKBody modify raid o k body +swagger:model ModifyRaidOKBody +*/ +type ModifyRaidOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify raid o k body +func (o *ModifyRaidOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRaidOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify raid o k body based on the context it is used +func (o *ModifyRaidOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRaidOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyRaidOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyRaidOKBody) UnmarshalBinary(b []byte) error { + var res ModifyRaidOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/raid_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/raid_client.go new file mode 100644 index 0000000..1baf54d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/raid/raid_client.go @@ -0,0 +1,317 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new raid API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for raid API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateDeviceTypeRaid(params *CreateDeviceTypeRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateDeviceTypeRaidOK, error) + + CreateRaid(params *CreateRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateRaidOK, error) + + DeleteDeviceTypeRaid(params *DeleteDeviceTypeRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteDeviceTypeRaidOK, error) + + DeleteRaid(params *DeleteRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteRaidOK, error) + + DescribeRaid(params *DescribeRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRaidOK, error) + + DescribeRaids(params *DescribeRaidsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRaidsOK, error) + + ModifyRaid(params *ModifyRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyRaidOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateDeviceTypeRaid CreateDeviceTypeRaid ... 机型和raid关联(暂不启用) +*/ +func (a *Client) CreateDeviceTypeRaid(params *CreateDeviceTypeRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateDeviceTypeRaidOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateDeviceTypeRaidParams() + } + op := &runtime.ClientOperation{ + ID: "createDeviceTypeRaid", + Method: "POST", + PathPattern: "/raids/deviceTypeRaid", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateDeviceTypeRaidReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateDeviceTypeRaidOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateDeviceTypeRaidDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + CreateRaid CreateRaid 创建raid(暂不启用) +*/ +func (a *Client) CreateRaid(params *CreateRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateRaidOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateRaidParams() + } + op := &runtime.ClientOperation{ + ID: "createRaid", + Method: "POST", + PathPattern: "/raids", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateRaidReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateRaidOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateRaidDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteDeviceTypeRaid DeleteDeviceTypeRaid ... 机型和raid解绑(暂不启用) +*/ +func (a *Client) DeleteDeviceTypeRaid(params *DeleteDeviceTypeRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteDeviceTypeRaidOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteDeviceTypeRaidParams() + } + op := &runtime.ClientOperation{ + ID: "deleteDeviceTypeRaid", + Method: "DELETE", + PathPattern: "/raids/deviceTypeRaid", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteDeviceTypeRaidReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteDeviceTypeRaidOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteDeviceTypeRaidDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteRaid DeleteRaid 删除raid(暂不启用) +*/ +func (a *Client) DeleteRaid(params *DeleteRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteRaidOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteRaidParams() + } + op := &runtime.ClientOperation{ + ID: "deleteRaid", + Method: "DELETE", + PathPattern: "/raids/{raid_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteRaidReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteRaidOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteRaidDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeRaid DescribeRaid 获取raid详情 +*/ +func (a *Client) DescribeRaid(params *DescribeRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRaidOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeRaidParams() + } + op := &runtime.ClientOperation{ + ID: "describeRaid", + Method: "GET", + PathPattern: "/raids/{raid_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeRaidReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeRaidOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeRaidDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeRaids DescribeRaids 获取raid列表 +*/ +func (a *Client) DescribeRaids(params *DescribeRaidsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRaidsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeRaidsParams() + } + op := &runtime.ClientOperation{ + ID: "describeRaids", + Method: "GET", + PathPattern: "/raids", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeRaidsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeRaidsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeRaidsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyRaid ModifyRaid 修改raid信息(暂不启用) +*/ +func (a *Client) ModifyRaid(params *ModifyRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyRaidOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyRaidParams() + } + op := &runtime.ClientOperation{ + ID: "modifyRaid", + Method: "PUT", + PathPattern: "/raids/{raid_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyRaidReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyRaidOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyRaidDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/resource/describe_resources_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/resource/describe_resources_parameters.go new file mode 100644 index 0000000..ea3d17d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/resource/describe_resources_parameters.go @@ -0,0 +1,361 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package resource + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeResourcesParams creates a new DescribeResourcesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeResourcesParams() *DescribeResourcesParams { + return &DescribeResourcesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeResourcesParamsWithTimeout creates a new DescribeResourcesParams object +// with the ability to set a timeout on a request. +func NewDescribeResourcesParamsWithTimeout(timeout time.Duration) *DescribeResourcesParams { + return &DescribeResourcesParams{ + timeout: timeout, + } +} + +// NewDescribeResourcesParamsWithContext creates a new DescribeResourcesParams object +// with the ability to set a context for a request. +func NewDescribeResourcesParamsWithContext(ctx context.Context) *DescribeResourcesParams { + return &DescribeResourcesParams{ + Context: ctx, + } +} + +// NewDescribeResourcesParamsWithHTTPClient creates a new DescribeResourcesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeResourcesParamsWithHTTPClient(client *http.Client) *DescribeResourcesParams { + return &DescribeResourcesParams{ + HTTPClient: client, + } +} + +/* DescribeResourcesParams contains all the parameters to send to the API endpoint + for the describe resources operation. + + Typically these are written to a http.Request. +*/ +type DescribeResourcesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceType. + + 机型规格 + */ + DeviceType *string + + /* ImageName. + + 镜像名称 + */ + ImageName *string + + /* Name. + + 机房名称 + IdcName string `json:"idcName"` + 机房英文名称 + IdcNameEn string `json:"idcNameEn"`[*]/ + 机型名称 + */ + Name *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserName. + + 用户名称 + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe resources params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeResourcesParams) WithDefaults() *DescribeResourcesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe resources params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeResourcesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe resources params +func (o *DescribeResourcesParams) WithTimeout(timeout time.Duration) *DescribeResourcesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe resources params +func (o *DescribeResourcesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe resources params +func (o *DescribeResourcesParams) WithContext(ctx context.Context) *DescribeResourcesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe resources params +func (o *DescribeResourcesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe resources params +func (o *DescribeResourcesParams) WithHTTPClient(client *http.Client) *DescribeResourcesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe resources params +func (o *DescribeResourcesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe resources params +func (o *DescribeResourcesParams) WithAuthorization(authorization string) *DescribeResourcesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe resources params +func (o *DescribeResourcesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe resources params +func (o *DescribeResourcesParams) WithBmpLanguage(bmpLanguage *string) *DescribeResourcesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe resources params +func (o *DescribeResourcesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe resources params +func (o *DescribeResourcesParams) WithBmpUserID(bmpUserID *string) *DescribeResourcesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe resources params +func (o *DescribeResourcesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceType adds the deviceType to the describe resources params +func (o *DescribeResourcesParams) WithDeviceType(deviceType *string) *DescribeResourcesParams { + o.SetDeviceType(deviceType) + return o +} + +// SetDeviceType adds the deviceType to the describe resources params +func (o *DescribeResourcesParams) SetDeviceType(deviceType *string) { + o.DeviceType = deviceType +} + +// WithImageName adds the imageName to the describe resources params +func (o *DescribeResourcesParams) WithImageName(imageName *string) *DescribeResourcesParams { + o.SetImageName(imageName) + return o +} + +// SetImageName adds the imageName to the describe resources params +func (o *DescribeResourcesParams) SetImageName(imageName *string) { + o.ImageName = imageName +} + +// WithName adds the name to the describe resources params +func (o *DescribeResourcesParams) WithName(name *string) *DescribeResourcesParams { + o.SetName(name) + return o +} + +// SetName adds the name to the describe resources params +func (o *DescribeResourcesParams) SetName(name *string) { + o.Name = name +} + +// WithTraceID adds the traceID to the describe resources params +func (o *DescribeResourcesParams) WithTraceID(traceID string) *DescribeResourcesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe resources params +func (o *DescribeResourcesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserName adds the userName to the describe resources params +func (o *DescribeResourcesParams) WithUserName(userName *string) *DescribeResourcesParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe resources params +func (o *DescribeResourcesParams) SetUserName(userName *string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeResourcesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceType != nil { + + // query param deviceType + var qrDeviceType string + + if o.DeviceType != nil { + qrDeviceType = *o.DeviceType + } + qDeviceType := qrDeviceType + if qDeviceType != "" { + + if err := r.SetQueryParam("deviceType", qDeviceType); err != nil { + return err + } + } + } + + if o.ImageName != nil { + + // query param imageName + var qrImageName string + + if o.ImageName != nil { + qrImageName = *o.ImageName + } + qImageName := qrImageName + if qImageName != "" { + + if err := r.SetQueryParam("imageName", qImageName); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserName != nil { + + // query param userName + var qrUserName string + + if o.UserName != nil { + qrUserName = *o.UserName + } + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/resource/describe_resources_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/resource/describe_resources_responses.go new file mode 100644 index 0000000..a2a1879 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/resource/describe_resources_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package resource + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeResourcesReader is a Reader for the DescribeResources structure. +type DescribeResourcesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeResourcesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeResourcesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeResourcesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeResourcesOK creates a DescribeResourcesOK with default headers values +func NewDescribeResourcesOK() *DescribeResourcesOK { + return &DescribeResourcesOK{} +} + +/* DescribeResourcesOK describes a response with status code 200, with default header values. + +DescribeResourcesOK describe resources o k +*/ +type DescribeResourcesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeResourcesOKBody +} + +// IsSuccess returns true when this describe resources o k response has a 2xx status code +func (o *DescribeResourcesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe resources o k response has a 3xx status code +func (o *DescribeResourcesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe resources o k response has a 4xx status code +func (o *DescribeResourcesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe resources o k response has a 5xx status code +func (o *DescribeResourcesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe resources o k response a status code equal to that given +func (o *DescribeResourcesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeResourcesOK) Error() string { + return fmt.Sprintf("[GET /resources][%d] describeResourcesOK %+v", 200, o.Payload) +} + +func (o *DescribeResourcesOK) String() string { + return fmt.Sprintf("[GET /resources][%d] describeResourcesOK %+v", 200, o.Payload) +} + +func (o *DescribeResourcesOK) GetPayload() *DescribeResourcesOKBody { + return o.Payload +} + +func (o *DescribeResourcesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeResourcesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeResourcesDefault creates a DescribeResourcesDefault with default headers values +func NewDescribeResourcesDefault(code int) *DescribeResourcesDefault { + return &DescribeResourcesDefault{ + _statusCode: code, + } +} + +/* DescribeResourcesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeResourcesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeResourcesDefaultBody +} + +// Code gets the status code for the describe resources default response +func (o *DescribeResourcesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe resources default response has a 2xx status code +func (o *DescribeResourcesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe resources default response has a 3xx status code +func (o *DescribeResourcesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe resources default response has a 4xx status code +func (o *DescribeResourcesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe resources default response has a 5xx status code +func (o *DescribeResourcesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe resources default response a status code equal to that given +func (o *DescribeResourcesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeResourcesDefault) Error() string { + return fmt.Sprintf("[GET /resources][%d] describeResources default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeResourcesDefault) String() string { + return fmt.Sprintf("[GET /resources][%d] describeResources default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeResourcesDefault) GetPayload() *DescribeResourcesDefaultBody { + return o.Payload +} + +func (o *DescribeResourcesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeResourcesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeResourcesDefaultBody describe resources default body +swagger:model DescribeResourcesDefaultBody +*/ +type DescribeResourcesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe resources default body +func (o *DescribeResourcesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeResourcesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeResources default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeResourcesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeResources default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeResources default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeResources default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe resources default body based on the context it is used +func (o *DescribeResourcesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeResourcesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeResources default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeResources default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeResourcesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeResourcesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeResourcesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeResourcesOKBody describe resources o k body +swagger:model DescribeResourcesOKBody +*/ +type DescribeResourcesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this describe resources o k body +func (o *DescribeResourcesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeResourcesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeResourcesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeResourcesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe resources o k body based on the context it is used +func (o *DescribeResourcesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeResourcesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeResourcesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeResourcesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeResourcesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeResourcesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeResourcesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/resource/resource_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/resource/resource_client.go new file mode 100644 index 0000000..4bc504f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/resource/resource_client.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package resource + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new resource API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for resource API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DescribeResources(params *DescribeResourcesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeResourcesOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DescribeResources DescribeResources 根据某个字段值精确查询对应的资源列表(如根据imageName查询镜像列表,根据idcName查询机房列表) +*/ +func (a *Client) DescribeResources(params *DescribeResourcesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeResourcesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeResourcesParams() + } + op := &runtime.ClientOperation{ + ID: "describeResources", + Method: "GET", + PathPattern: "/resources", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeResourcesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeResourcesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeResourcesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/create_role_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/create_role_parameters.go new file mode 100644 index 0000000..352050c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/create_role_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateRoleParams creates a new CreateRoleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateRoleParams() *CreateRoleParams { + return &CreateRoleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateRoleParamsWithTimeout creates a new CreateRoleParams object +// with the ability to set a timeout on a request. +func NewCreateRoleParamsWithTimeout(timeout time.Duration) *CreateRoleParams { + return &CreateRoleParams{ + timeout: timeout, + } +} + +// NewCreateRoleParamsWithContext creates a new CreateRoleParams object +// with the ability to set a context for a request. +func NewCreateRoleParamsWithContext(ctx context.Context) *CreateRoleParams { + return &CreateRoleParams{ + Context: ctx, + } +} + +// NewCreateRoleParamsWithHTTPClient creates a new CreateRoleParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateRoleParamsWithHTTPClient(client *http.Client) *CreateRoleParams { + return &CreateRoleParams{ + HTTPClient: client, + } +} + +/* CreateRoleParams contains all the parameters to send to the API endpoint + for the create role operation. + + Typically these are written to a http.Request. +*/ +type CreateRoleParams struct { + + // Body. + Body *models.CreateRoleRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateRoleParams) WithDefaults() *CreateRoleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateRoleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create role params +func (o *CreateRoleParams) WithTimeout(timeout time.Duration) *CreateRoleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create role params +func (o *CreateRoleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create role params +func (o *CreateRoleParams) WithContext(ctx context.Context) *CreateRoleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create role params +func (o *CreateRoleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create role params +func (o *CreateRoleParams) WithHTTPClient(client *http.Client) *CreateRoleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create role params +func (o *CreateRoleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create role params +func (o *CreateRoleParams) WithBody(body *models.CreateRoleRequest) *CreateRoleParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create role params +func (o *CreateRoleParams) SetBody(body *models.CreateRoleRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create role params +func (o *CreateRoleParams) WithAuthorization(authorization string) *CreateRoleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create role params +func (o *CreateRoleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create role params +func (o *CreateRoleParams) WithBmpLanguage(bmpLanguage *string) *CreateRoleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create role params +func (o *CreateRoleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create role params +func (o *CreateRoleParams) WithBmpUserID(bmpUserID *string) *CreateRoleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create role params +func (o *CreateRoleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create role params +func (o *CreateRoleParams) WithTraceID(traceID string) *CreateRoleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create role params +func (o *CreateRoleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateRoleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/create_role_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/create_role_responses.go new file mode 100644 index 0000000..521928d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/create_role_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateRoleReader is a Reader for the CreateRole structure. +type CreateRoleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateRoleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateRoleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateRoleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateRoleOK creates a CreateRoleOK with default headers values +func NewCreateRoleOK() *CreateRoleOK { + return &CreateRoleOK{} +} + +/* CreateRoleOK describes a response with status code 200, with default header values. + +A CreateRoleResult is an response struct that is used to describe create role result. +*/ +type CreateRoleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateRoleOKBody +} + +// IsSuccess returns true when this create role o k response has a 2xx status code +func (o *CreateRoleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create role o k response has a 3xx status code +func (o *CreateRoleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create role o k response has a 4xx status code +func (o *CreateRoleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create role o k response has a 5xx status code +func (o *CreateRoleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create role o k response a status code equal to that given +func (o *CreateRoleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateRoleOK) Error() string { + return fmt.Sprintf("[POST /roles][%d] createRoleOK %+v", 200, o.Payload) +} + +func (o *CreateRoleOK) String() string { + return fmt.Sprintf("[POST /roles][%d] createRoleOK %+v", 200, o.Payload) +} + +func (o *CreateRoleOK) GetPayload() *CreateRoleOKBody { + return o.Payload +} + +func (o *CreateRoleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateRoleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateRoleDefault creates a CreateRoleDefault with default headers values +func NewCreateRoleDefault(code int) *CreateRoleDefault { + return &CreateRoleDefault{ + _statusCode: code, + } +} + +/* CreateRoleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateRoleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateRoleDefaultBody +} + +// Code gets the status code for the create role default response +func (o *CreateRoleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create role default response has a 2xx status code +func (o *CreateRoleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create role default response has a 3xx status code +func (o *CreateRoleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create role default response has a 4xx status code +func (o *CreateRoleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create role default response has a 5xx status code +func (o *CreateRoleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create role default response a status code equal to that given +func (o *CreateRoleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateRoleDefault) Error() string { + return fmt.Sprintf("[POST /roles][%d] createRole default %+v", o._statusCode, o.Payload) +} + +func (o *CreateRoleDefault) String() string { + return fmt.Sprintf("[POST /roles][%d] createRole default %+v", o._statusCode, o.Payload) +} + +func (o *CreateRoleDefault) GetPayload() *CreateRoleDefaultBody { + return o.Payload +} + +func (o *CreateRoleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateRoleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateRoleDefaultBody create role default body +swagger:model CreateRoleDefaultBody +*/ +type CreateRoleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create role default body +func (o *CreateRoleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRoleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createRole default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateRoleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createRole default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create role default body based on the context it is used +func (o *CreateRoleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRoleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateRoleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateRoleDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateRoleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateRoleOKBody create role o k body +swagger:model CreateRoleOKBody +*/ +type CreateRoleOKBody struct { + + // result + Result *models.RoleID `json:"result,omitempty"` +} + +// Validate validates this create role o k body +func (o *CreateRoleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRoleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create role o k body based on the context it is used +func (o *CreateRoleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRoleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateRoleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateRoleOKBody) UnmarshalBinary(b []byte) error { + var res CreateRoleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/current_role_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/current_role_parameters.go new file mode 100644 index 0000000..e39198b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/current_role_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewCurrentRoleParams creates a new CurrentRoleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCurrentRoleParams() *CurrentRoleParams { + return &CurrentRoleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCurrentRoleParamsWithTimeout creates a new CurrentRoleParams object +// with the ability to set a timeout on a request. +func NewCurrentRoleParamsWithTimeout(timeout time.Duration) *CurrentRoleParams { + return &CurrentRoleParams{ + timeout: timeout, + } +} + +// NewCurrentRoleParamsWithContext creates a new CurrentRoleParams object +// with the ability to set a context for a request. +func NewCurrentRoleParamsWithContext(ctx context.Context) *CurrentRoleParams { + return &CurrentRoleParams{ + Context: ctx, + } +} + +// NewCurrentRoleParamsWithHTTPClient creates a new CurrentRoleParams object +// with the ability to set a custom HTTPClient for a request. +func NewCurrentRoleParamsWithHTTPClient(client *http.Client) *CurrentRoleParams { + return &CurrentRoleParams{ + HTTPClient: client, + } +} + +/* CurrentRoleParams contains all the parameters to send to the API endpoint + for the current role operation. + + Typically these are written to a http.Request. +*/ +type CurrentRoleParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the current role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CurrentRoleParams) WithDefaults() *CurrentRoleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the current role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CurrentRoleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the current role params +func (o *CurrentRoleParams) WithTimeout(timeout time.Duration) *CurrentRoleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the current role params +func (o *CurrentRoleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the current role params +func (o *CurrentRoleParams) WithContext(ctx context.Context) *CurrentRoleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the current role params +func (o *CurrentRoleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the current role params +func (o *CurrentRoleParams) WithHTTPClient(client *http.Client) *CurrentRoleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the current role params +func (o *CurrentRoleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the current role params +func (o *CurrentRoleParams) WithAuthorization(authorization string) *CurrentRoleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the current role params +func (o *CurrentRoleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the current role params +func (o *CurrentRoleParams) WithBmpLanguage(bmpLanguage *string) *CurrentRoleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the current role params +func (o *CurrentRoleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the current role params +func (o *CurrentRoleParams) WithBmpUserID(bmpUserID *string) *CurrentRoleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the current role params +func (o *CurrentRoleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the current role params +func (o *CurrentRoleParams) WithTraceID(traceID string) *CurrentRoleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the current role params +func (o *CurrentRoleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CurrentRoleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/current_role_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/current_role_responses.go new file mode 100644 index 0000000..f9a3938 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/current_role_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CurrentRoleReader is a Reader for the CurrentRole structure. +type CurrentRoleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CurrentRoleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCurrentRoleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCurrentRoleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCurrentRoleOK creates a CurrentRoleOK with default headers values +func NewCurrentRoleOK() *CurrentRoleOK { + return &CurrentRoleOK{} +} + +/* CurrentRoleOK describes a response with status code 200, with default header values. + +A CurrentRoleResult is an response struct that is used to describe role. +*/ +type CurrentRoleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CurrentRoleOKBody +} + +// IsSuccess returns true when this current role o k response has a 2xx status code +func (o *CurrentRoleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this current role o k response has a 3xx status code +func (o *CurrentRoleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this current role o k response has a 4xx status code +func (o *CurrentRoleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this current role o k response has a 5xx status code +func (o *CurrentRoleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this current role o k response a status code equal to that given +func (o *CurrentRoleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CurrentRoleOK) Error() string { + return fmt.Sprintf("[GET /roles/roleInfo/current][%d] currentRoleOK %+v", 200, o.Payload) +} + +func (o *CurrentRoleOK) String() string { + return fmt.Sprintf("[GET /roles/roleInfo/current][%d] currentRoleOK %+v", 200, o.Payload) +} + +func (o *CurrentRoleOK) GetPayload() *CurrentRoleOKBody { + return o.Payload +} + +func (o *CurrentRoleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CurrentRoleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCurrentRoleDefault creates a CurrentRoleDefault with default headers values +func NewCurrentRoleDefault(code int) *CurrentRoleDefault { + return &CurrentRoleDefault{ + _statusCode: code, + } +} + +/* CurrentRoleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CurrentRoleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CurrentRoleDefaultBody +} + +// Code gets the status code for the current role default response +func (o *CurrentRoleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this current role default response has a 2xx status code +func (o *CurrentRoleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this current role default response has a 3xx status code +func (o *CurrentRoleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this current role default response has a 4xx status code +func (o *CurrentRoleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this current role default response has a 5xx status code +func (o *CurrentRoleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this current role default response a status code equal to that given +func (o *CurrentRoleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CurrentRoleDefault) Error() string { + return fmt.Sprintf("[GET /roles/roleInfo/current][%d] currentRole default %+v", o._statusCode, o.Payload) +} + +func (o *CurrentRoleDefault) String() string { + return fmt.Sprintf("[GET /roles/roleInfo/current][%d] currentRole default %+v", o._statusCode, o.Payload) +} + +func (o *CurrentRoleDefault) GetPayload() *CurrentRoleDefaultBody { + return o.Payload +} + +func (o *CurrentRoleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CurrentRoleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CurrentRoleDefaultBody current role default body +swagger:model CurrentRoleDefaultBody +*/ +type CurrentRoleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this current role default body +func (o *CurrentRoleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CurrentRoleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("currentRole default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CurrentRoleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("currentRole default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("currentRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("currentRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this current role default body based on the context it is used +func (o *CurrentRoleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CurrentRoleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("currentRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("currentRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CurrentRoleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CurrentRoleDefaultBody) UnmarshalBinary(b []byte) error { + var res CurrentRoleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CurrentRoleOKBody current role o k body +swagger:model CurrentRoleOKBody +*/ +type CurrentRoleOKBody struct { + + // result + Result *models.RoleInfo `json:"result,omitempty"` +} + +// Validate validates this current role o k body +func (o *CurrentRoleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CurrentRoleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("currentRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("currentRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this current role o k body based on the context it is used +func (o *CurrentRoleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CurrentRoleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("currentRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("currentRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CurrentRoleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CurrentRoleOKBody) UnmarshalBinary(b []byte) error { + var res CurrentRoleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/delete_role_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/delete_role_parameters.go new file mode 100644 index 0000000..a4ef43c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/delete_role_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteRoleParams creates a new DeleteRoleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteRoleParams() *DeleteRoleParams { + return &DeleteRoleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteRoleParamsWithTimeout creates a new DeleteRoleParams object +// with the ability to set a timeout on a request. +func NewDeleteRoleParamsWithTimeout(timeout time.Duration) *DeleteRoleParams { + return &DeleteRoleParams{ + timeout: timeout, + } +} + +// NewDeleteRoleParamsWithContext creates a new DeleteRoleParams object +// with the ability to set a context for a request. +func NewDeleteRoleParamsWithContext(ctx context.Context) *DeleteRoleParams { + return &DeleteRoleParams{ + Context: ctx, + } +} + +// NewDeleteRoleParamsWithHTTPClient creates a new DeleteRoleParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteRoleParamsWithHTTPClient(client *http.Client) *DeleteRoleParams { + return &DeleteRoleParams{ + HTTPClient: client, + } +} + +/* DeleteRoleParams contains all the parameters to send to the API endpoint + for the delete role operation. + + Typically these are written to a http.Request. +*/ +type DeleteRoleParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // RoleID. + RoleID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteRoleParams) WithDefaults() *DeleteRoleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteRoleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete role params +func (o *DeleteRoleParams) WithTimeout(timeout time.Duration) *DeleteRoleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete role params +func (o *DeleteRoleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete role params +func (o *DeleteRoleParams) WithContext(ctx context.Context) *DeleteRoleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete role params +func (o *DeleteRoleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete role params +func (o *DeleteRoleParams) WithHTTPClient(client *http.Client) *DeleteRoleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete role params +func (o *DeleteRoleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete role params +func (o *DeleteRoleParams) WithAuthorization(authorization string) *DeleteRoleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete role params +func (o *DeleteRoleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete role params +func (o *DeleteRoleParams) WithBmpLanguage(bmpLanguage *string) *DeleteRoleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete role params +func (o *DeleteRoleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete role params +func (o *DeleteRoleParams) WithBmpUserID(bmpUserID *string) *DeleteRoleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete role params +func (o *DeleteRoleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithRoleID adds the roleID to the delete role params +func (o *DeleteRoleParams) WithRoleID(roleID string) *DeleteRoleParams { + o.SetRoleID(roleID) + return o +} + +// SetRoleID adds the roleId to the delete role params +func (o *DeleteRoleParams) SetRoleID(roleID string) { + o.RoleID = roleID +} + +// WithTraceID adds the traceID to the delete role params +func (o *DeleteRoleParams) WithTraceID(traceID string) *DeleteRoleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete role params +func (o *DeleteRoleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteRoleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param role_id + if err := r.SetPathParam("role_id", o.RoleID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/delete_role_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/delete_role_responses.go new file mode 100644 index 0000000..4d9be49 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/delete_role_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteRoleReader is a Reader for the DeleteRole structure. +type DeleteRoleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteRoleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteRoleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteRoleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteRoleOK creates a DeleteRoleOK with default headers values +func NewDeleteRoleOK() *DeleteRoleOK { + return &DeleteRoleOK{} +} + +/* DeleteRoleOK describes a response with status code 200, with default header values. + +A DeleteRoleResult is an response struct that is used to delete role. +*/ +type DeleteRoleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteRoleOKBody +} + +// IsSuccess returns true when this delete role o k response has a 2xx status code +func (o *DeleteRoleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete role o k response has a 3xx status code +func (o *DeleteRoleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete role o k response has a 4xx status code +func (o *DeleteRoleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete role o k response has a 5xx status code +func (o *DeleteRoleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete role o k response a status code equal to that given +func (o *DeleteRoleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteRoleOK) Error() string { + return fmt.Sprintf("[DELETE /roles/{role_id}][%d] deleteRoleOK %+v", 200, o.Payload) +} + +func (o *DeleteRoleOK) String() string { + return fmt.Sprintf("[DELETE /roles/{role_id}][%d] deleteRoleOK %+v", 200, o.Payload) +} + +func (o *DeleteRoleOK) GetPayload() *DeleteRoleOKBody { + return o.Payload +} + +func (o *DeleteRoleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteRoleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteRoleDefault creates a DeleteRoleDefault with default headers values +func NewDeleteRoleDefault(code int) *DeleteRoleDefault { + return &DeleteRoleDefault{ + _statusCode: code, + } +} + +/* DeleteRoleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteRoleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteRoleDefaultBody +} + +// Code gets the status code for the delete role default response +func (o *DeleteRoleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete role default response has a 2xx status code +func (o *DeleteRoleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete role default response has a 3xx status code +func (o *DeleteRoleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete role default response has a 4xx status code +func (o *DeleteRoleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete role default response has a 5xx status code +func (o *DeleteRoleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete role default response a status code equal to that given +func (o *DeleteRoleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteRoleDefault) Error() string { + return fmt.Sprintf("[DELETE /roles/{role_id}][%d] deleteRole default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteRoleDefault) String() string { + return fmt.Sprintf("[DELETE /roles/{role_id}][%d] deleteRole default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteRoleDefault) GetPayload() *DeleteRoleDefaultBody { + return o.Payload +} + +func (o *DeleteRoleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteRoleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteRoleDefaultBody delete role default body +swagger:model DeleteRoleDefaultBody +*/ +type DeleteRoleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete role default body +func (o *DeleteRoleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRoleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteRole default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteRoleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteRole default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete role default body based on the context it is used +func (o *DeleteRoleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRoleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteRoleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteRoleDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteRoleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteRoleOKBody delete role o k body +swagger:model DeleteRoleOKBody +*/ +type DeleteRoleOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete role o k body +func (o *DeleteRoleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRoleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete role o k body based on the context it is used +func (o *DeleteRoleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRoleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteRoleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteRoleOKBody) UnmarshalBinary(b []byte) error { + var res DeleteRoleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/describe_role_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/describe_role_parameters.go new file mode 100644 index 0000000..5cda2db --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/describe_role_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeRoleParams creates a new DescribeRoleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeRoleParams() *DescribeRoleParams { + return &DescribeRoleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeRoleParamsWithTimeout creates a new DescribeRoleParams object +// with the ability to set a timeout on a request. +func NewDescribeRoleParamsWithTimeout(timeout time.Duration) *DescribeRoleParams { + return &DescribeRoleParams{ + timeout: timeout, + } +} + +// NewDescribeRoleParamsWithContext creates a new DescribeRoleParams object +// with the ability to set a context for a request. +func NewDescribeRoleParamsWithContext(ctx context.Context) *DescribeRoleParams { + return &DescribeRoleParams{ + Context: ctx, + } +} + +// NewDescribeRoleParamsWithHTTPClient creates a new DescribeRoleParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeRoleParamsWithHTTPClient(client *http.Client) *DescribeRoleParams { + return &DescribeRoleParams{ + HTTPClient: client, + } +} + +/* DescribeRoleParams contains all the parameters to send to the API endpoint + for the describe role operation. + + Typically these are written to a http.Request. +*/ +type DescribeRoleParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // RoleID. + RoleID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRoleParams) WithDefaults() *DescribeRoleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRoleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe role params +func (o *DescribeRoleParams) WithTimeout(timeout time.Duration) *DescribeRoleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe role params +func (o *DescribeRoleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe role params +func (o *DescribeRoleParams) WithContext(ctx context.Context) *DescribeRoleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe role params +func (o *DescribeRoleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe role params +func (o *DescribeRoleParams) WithHTTPClient(client *http.Client) *DescribeRoleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe role params +func (o *DescribeRoleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe role params +func (o *DescribeRoleParams) WithAuthorization(authorization string) *DescribeRoleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe role params +func (o *DescribeRoleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe role params +func (o *DescribeRoleParams) WithBmpLanguage(bmpLanguage *string) *DescribeRoleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe role params +func (o *DescribeRoleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe role params +func (o *DescribeRoleParams) WithBmpUserID(bmpUserID *string) *DescribeRoleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe role params +func (o *DescribeRoleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithRoleID adds the roleID to the describe role params +func (o *DescribeRoleParams) WithRoleID(roleID string) *DescribeRoleParams { + o.SetRoleID(roleID) + return o +} + +// SetRoleID adds the roleId to the describe role params +func (o *DescribeRoleParams) SetRoleID(roleID string) { + o.RoleID = roleID +} + +// WithTraceID adds the traceID to the describe role params +func (o *DescribeRoleParams) WithTraceID(traceID string) *DescribeRoleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe role params +func (o *DescribeRoleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeRoleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param role_id + if err := r.SetPathParam("role_id", o.RoleID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/describe_role_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/describe_role_responses.go new file mode 100644 index 0000000..0ac2096 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/describe_role_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeRoleReader is a Reader for the DescribeRole structure. +type DescribeRoleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeRoleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeRoleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeRoleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeRoleOK creates a DescribeRoleOK with default headers values +func NewDescribeRoleOK() *DescribeRoleOK { + return &DescribeRoleOK{} +} + +/* DescribeRoleOK describes a response with status code 200, with default header values. + +A GetRoleResult is an response struct that is used to describe role. +*/ +type DescribeRoleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRoleOKBody +} + +// IsSuccess returns true when this describe role o k response has a 2xx status code +func (o *DescribeRoleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe role o k response has a 3xx status code +func (o *DescribeRoleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe role o k response has a 4xx status code +func (o *DescribeRoleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe role o k response has a 5xx status code +func (o *DescribeRoleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe role o k response a status code equal to that given +func (o *DescribeRoleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeRoleOK) Error() string { + return fmt.Sprintf("[GET /roles/{role_id}][%d] describeRoleOK %+v", 200, o.Payload) +} + +func (o *DescribeRoleOK) String() string { + return fmt.Sprintf("[GET /roles/{role_id}][%d] describeRoleOK %+v", 200, o.Payload) +} + +func (o *DescribeRoleOK) GetPayload() *DescribeRoleOKBody { + return o.Payload +} + +func (o *DescribeRoleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRoleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeRoleDefault creates a DescribeRoleDefault with default headers values +func NewDescribeRoleDefault(code int) *DescribeRoleDefault { + return &DescribeRoleDefault{ + _statusCode: code, + } +} + +/* DescribeRoleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeRoleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRoleDefaultBody +} + +// Code gets the status code for the describe role default response +func (o *DescribeRoleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe role default response has a 2xx status code +func (o *DescribeRoleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe role default response has a 3xx status code +func (o *DescribeRoleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe role default response has a 4xx status code +func (o *DescribeRoleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe role default response has a 5xx status code +func (o *DescribeRoleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe role default response a status code equal to that given +func (o *DescribeRoleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeRoleDefault) Error() string { + return fmt.Sprintf("[GET /roles/{role_id}][%d] describeRole default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRoleDefault) String() string { + return fmt.Sprintf("[GET /roles/{role_id}][%d] describeRole default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRoleDefault) GetPayload() *DescribeRoleDefaultBody { + return o.Payload +} + +func (o *DescribeRoleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRoleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeRoleDefaultBody describe role default body +swagger:model DescribeRoleDefaultBody +*/ +type DescribeRoleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe role default body +func (o *DescribeRoleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRoleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeRole default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeRoleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeRole default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe role default body based on the context it is used +func (o *DescribeRoleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRoleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRoleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRoleDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeRoleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeRoleOKBody describe role o k body +swagger:model DescribeRoleOKBody +*/ +type DescribeRoleOKBody struct { + + // result + Result *models.RoleInfo `json:"result,omitempty"` +} + +// Validate validates this describe role o k body +func (o *DescribeRoleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRoleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe role o k body based on the context it is used +func (o *DescribeRoleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRoleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRoleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRoleOKBody) UnmarshalBinary(b []byte) error { + var res DescribeRoleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/describe_roles_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/describe_roles_parameters.go new file mode 100644 index 0000000..d8b50db --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/describe_roles_parameters.go @@ -0,0 +1,328 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeRolesParams creates a new DescribeRolesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeRolesParams() *DescribeRolesParams { + return &DescribeRolesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeRolesParamsWithTimeout creates a new DescribeRolesParams object +// with the ability to set a timeout on a request. +func NewDescribeRolesParamsWithTimeout(timeout time.Duration) *DescribeRolesParams { + return &DescribeRolesParams{ + timeout: timeout, + } +} + +// NewDescribeRolesParamsWithContext creates a new DescribeRolesParams object +// with the ability to set a context for a request. +func NewDescribeRolesParamsWithContext(ctx context.Context) *DescribeRolesParams { + return &DescribeRolesParams{ + Context: ctx, + } +} + +// NewDescribeRolesParamsWithHTTPClient creates a new DescribeRolesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeRolesParamsWithHTTPClient(client *http.Client) *DescribeRolesParams { + return &DescribeRolesParams{ + HTTPClient: client, + } +} + +/* DescribeRolesParams contains all the parameters to send to the API endpoint + for the describe roles operation. + + Typically these are written to a http.Request. +*/ +type DescribeRolesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否显示所有 + */ + IsAll *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe roles params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRolesParams) WithDefaults() *DescribeRolesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe roles params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRolesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe roles params +func (o *DescribeRolesParams) WithTimeout(timeout time.Duration) *DescribeRolesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe roles params +func (o *DescribeRolesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe roles params +func (o *DescribeRolesParams) WithContext(ctx context.Context) *DescribeRolesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe roles params +func (o *DescribeRolesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe roles params +func (o *DescribeRolesParams) WithHTTPClient(client *http.Client) *DescribeRolesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe roles params +func (o *DescribeRolesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe roles params +func (o *DescribeRolesParams) WithAuthorization(authorization string) *DescribeRolesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe roles params +func (o *DescribeRolesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe roles params +func (o *DescribeRolesParams) WithBmpLanguage(bmpLanguage *string) *DescribeRolesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe roles params +func (o *DescribeRolesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe roles params +func (o *DescribeRolesParams) WithBmpUserID(bmpUserID *string) *DescribeRolesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe roles params +func (o *DescribeRolesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe roles params +func (o *DescribeRolesParams) WithIsAll(isAll *string) *DescribeRolesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe roles params +func (o *DescribeRolesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithPageNumber adds the pageNumber to the describe roles params +func (o *DescribeRolesParams) WithPageNumber(pageNumber *int64) *DescribeRolesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe roles params +func (o *DescribeRolesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe roles params +func (o *DescribeRolesParams) WithPageSize(pageSize *int64) *DescribeRolesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe roles params +func (o *DescribeRolesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe roles params +func (o *DescribeRolesParams) WithTraceID(traceID string) *DescribeRolesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe roles params +func (o *DescribeRolesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeRolesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/describe_roles_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/describe_roles_responses.go new file mode 100644 index 0000000..c4d6d29 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/describe_roles_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeRolesReader is a Reader for the DescribeRoles structure. +type DescribeRolesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeRolesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeRolesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeRolesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeRolesOK creates a DescribeRolesOK with default headers values +func NewDescribeRolesOK() *DescribeRolesOK { + return &DescribeRolesOK{} +} + +/* DescribeRolesOK describes a response with status code 200, with default header values. + +A GetRoleListResult is an response struct that is used to describe get role list. +*/ +type DescribeRolesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRolesOKBody +} + +// IsSuccess returns true when this describe roles o k response has a 2xx status code +func (o *DescribeRolesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe roles o k response has a 3xx status code +func (o *DescribeRolesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe roles o k response has a 4xx status code +func (o *DescribeRolesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe roles o k response has a 5xx status code +func (o *DescribeRolesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe roles o k response a status code equal to that given +func (o *DescribeRolesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeRolesOK) Error() string { + return fmt.Sprintf("[GET /roles][%d] describeRolesOK %+v", 200, o.Payload) +} + +func (o *DescribeRolesOK) String() string { + return fmt.Sprintf("[GET /roles][%d] describeRolesOK %+v", 200, o.Payload) +} + +func (o *DescribeRolesOK) GetPayload() *DescribeRolesOKBody { + return o.Payload +} + +func (o *DescribeRolesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRolesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeRolesDefault creates a DescribeRolesDefault with default headers values +func NewDescribeRolesDefault(code int) *DescribeRolesDefault { + return &DescribeRolesDefault{ + _statusCode: code, + } +} + +/* DescribeRolesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeRolesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRolesDefaultBody +} + +// Code gets the status code for the describe roles default response +func (o *DescribeRolesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe roles default response has a 2xx status code +func (o *DescribeRolesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe roles default response has a 3xx status code +func (o *DescribeRolesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe roles default response has a 4xx status code +func (o *DescribeRolesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe roles default response has a 5xx status code +func (o *DescribeRolesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe roles default response a status code equal to that given +func (o *DescribeRolesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeRolesDefault) Error() string { + return fmt.Sprintf("[GET /roles][%d] describeRoles default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRolesDefault) String() string { + return fmt.Sprintf("[GET /roles][%d] describeRoles default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRolesDefault) GetPayload() *DescribeRolesDefaultBody { + return o.Payload +} + +func (o *DescribeRolesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRolesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeRolesDefaultBody describe roles default body +swagger:model DescribeRolesDefaultBody +*/ +type DescribeRolesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe roles default body +func (o *DescribeRolesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRolesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeRoles default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeRolesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeRoles default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRoles default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRoles default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe roles default body based on the context it is used +func (o *DescribeRolesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRolesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRoles default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRoles default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRolesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRolesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeRolesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeRolesOKBody describe roles o k body +swagger:model DescribeRolesOKBody +*/ +type DescribeRolesOKBody struct { + + // result + Result *models.RoleList `json:"result,omitempty"` +} + +// Validate validates this describe roles o k body +func (o *DescribeRolesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRolesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRolesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRolesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe roles o k body based on the context it is used +func (o *DescribeRolesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRolesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRolesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRolesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRolesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRolesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeRolesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/modify_role_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/modify_role_parameters.go new file mode 100644 index 0000000..5973443 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/modify_role_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyRoleParams creates a new ModifyRoleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyRoleParams() *ModifyRoleParams { + return &ModifyRoleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyRoleParamsWithTimeout creates a new ModifyRoleParams object +// with the ability to set a timeout on a request. +func NewModifyRoleParamsWithTimeout(timeout time.Duration) *ModifyRoleParams { + return &ModifyRoleParams{ + timeout: timeout, + } +} + +// NewModifyRoleParamsWithContext creates a new ModifyRoleParams object +// with the ability to set a context for a request. +func NewModifyRoleParamsWithContext(ctx context.Context) *ModifyRoleParams { + return &ModifyRoleParams{ + Context: ctx, + } +} + +// NewModifyRoleParamsWithHTTPClient creates a new ModifyRoleParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyRoleParamsWithHTTPClient(client *http.Client) *ModifyRoleParams { + return &ModifyRoleParams{ + HTTPClient: client, + } +} + +/* ModifyRoleParams contains all the parameters to send to the API endpoint + for the modify role operation. + + Typically these are written to a http.Request. +*/ +type ModifyRoleParams struct { + + // Body. + Body *models.ModifyRoleRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // RoleID. + RoleID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyRoleParams) WithDefaults() *ModifyRoleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyRoleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify role params +func (o *ModifyRoleParams) WithTimeout(timeout time.Duration) *ModifyRoleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify role params +func (o *ModifyRoleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify role params +func (o *ModifyRoleParams) WithContext(ctx context.Context) *ModifyRoleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify role params +func (o *ModifyRoleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify role params +func (o *ModifyRoleParams) WithHTTPClient(client *http.Client) *ModifyRoleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify role params +func (o *ModifyRoleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify role params +func (o *ModifyRoleParams) WithBody(body *models.ModifyRoleRequest) *ModifyRoleParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify role params +func (o *ModifyRoleParams) SetBody(body *models.ModifyRoleRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify role params +func (o *ModifyRoleParams) WithAuthorization(authorization string) *ModifyRoleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify role params +func (o *ModifyRoleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify role params +func (o *ModifyRoleParams) WithBmpLanguage(bmpLanguage *string) *ModifyRoleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify role params +func (o *ModifyRoleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify role params +func (o *ModifyRoleParams) WithBmpUserID(bmpUserID *string) *ModifyRoleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify role params +func (o *ModifyRoleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithRoleID adds the roleID to the modify role params +func (o *ModifyRoleParams) WithRoleID(roleID string) *ModifyRoleParams { + o.SetRoleID(roleID) + return o +} + +// SetRoleID adds the roleId to the modify role params +func (o *ModifyRoleParams) SetRoleID(roleID string) { + o.RoleID = roleID +} + +// WithTraceID adds the traceID to the modify role params +func (o *ModifyRoleParams) WithTraceID(traceID string) *ModifyRoleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify role params +func (o *ModifyRoleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyRoleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param role_id + if err := r.SetPathParam("role_id", o.RoleID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/modify_role_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/modify_role_responses.go new file mode 100644 index 0000000..4893a88 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/modify_role_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyRoleReader is a Reader for the ModifyRole structure. +type ModifyRoleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyRoleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyRoleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyRoleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyRoleOK creates a ModifyRoleOK with default headers values +func NewModifyRoleOK() *ModifyRoleOK { + return &ModifyRoleOK{} +} + +/* ModifyRoleOK describes a response with status code 200, with default header values. + +A ModifyRoleResult is an response struct that is used to describe modify role. +*/ +type ModifyRoleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyRoleOKBody +} + +// IsSuccess returns true when this modify role o k response has a 2xx status code +func (o *ModifyRoleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify role o k response has a 3xx status code +func (o *ModifyRoleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify role o k response has a 4xx status code +func (o *ModifyRoleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify role o k response has a 5xx status code +func (o *ModifyRoleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify role o k response a status code equal to that given +func (o *ModifyRoleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyRoleOK) Error() string { + return fmt.Sprintf("[PUT /roles/{role_id}][%d] modifyRoleOK %+v", 200, o.Payload) +} + +func (o *ModifyRoleOK) String() string { + return fmt.Sprintf("[PUT /roles/{role_id}][%d] modifyRoleOK %+v", 200, o.Payload) +} + +func (o *ModifyRoleOK) GetPayload() *ModifyRoleOKBody { + return o.Payload +} + +func (o *ModifyRoleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyRoleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyRoleDefault creates a ModifyRoleDefault with default headers values +func NewModifyRoleDefault(code int) *ModifyRoleDefault { + return &ModifyRoleDefault{ + _statusCode: code, + } +} + +/* ModifyRoleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyRoleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyRoleDefaultBody +} + +// Code gets the status code for the modify role default response +func (o *ModifyRoleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify role default response has a 2xx status code +func (o *ModifyRoleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify role default response has a 3xx status code +func (o *ModifyRoleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify role default response has a 4xx status code +func (o *ModifyRoleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify role default response has a 5xx status code +func (o *ModifyRoleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify role default response a status code equal to that given +func (o *ModifyRoleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyRoleDefault) Error() string { + return fmt.Sprintf("[PUT /roles/{role_id}][%d] modifyRole default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyRoleDefault) String() string { + return fmt.Sprintf("[PUT /roles/{role_id}][%d] modifyRole default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyRoleDefault) GetPayload() *ModifyRoleDefaultBody { + return o.Payload +} + +func (o *ModifyRoleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyRoleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyRoleDefaultBody modify role default body +swagger:model ModifyRoleDefaultBody +*/ +type ModifyRoleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify role default body +func (o *ModifyRoleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRoleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyRole default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyRoleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyRole default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify role default body based on the context it is used +func (o *ModifyRoleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRoleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyRoleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyRoleDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyRoleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyRoleOKBody modify role o k body +swagger:model ModifyRoleOKBody +*/ +type ModifyRoleOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify role o k body +func (o *ModifyRoleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRoleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify role o k body based on the context it is used +func (o *ModifyRoleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRoleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyRoleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyRoleOKBody) UnmarshalBinary(b []byte) error { + var res ModifyRoleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/role_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/role_client.go new file mode 100644 index 0000000..8f729cb --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/role/role_client.go @@ -0,0 +1,277 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new role API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for role API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateRole(params *CreateRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateRoleOK, error) + + CurrentRole(params *CurrentRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CurrentRoleOK, error) + + DeleteRole(params *DeleteRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteRoleOK, error) + + DescribeRole(params *DescribeRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRoleOK, error) + + DescribeRoles(params *DescribeRolesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRolesOK, error) + + ModifyRole(params *ModifyRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyRoleOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateRole CreateRole 创建角色(暂不启用) +*/ +func (a *Client) CreateRole(params *CreateRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateRoleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateRoleParams() + } + op := &runtime.ClientOperation{ + ID: "createRole", + Method: "POST", + PathPattern: "/roles", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateRoleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateRoleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateRoleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + CurrentRole CurrentRole 获取当前登录用户的角色 +*/ +func (a *Client) CurrentRole(params *CurrentRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CurrentRoleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCurrentRoleParams() + } + op := &runtime.ClientOperation{ + ID: "currentRole", + Method: "GET", + PathPattern: "/roles/roleInfo/current", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CurrentRoleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CurrentRoleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CurrentRoleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteRole DeleteRole 删除角色(暂不启用) +*/ +func (a *Client) DeleteRole(params *DeleteRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteRoleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteRoleParams() + } + op := &runtime.ClientOperation{ + ID: "deleteRole", + Method: "DELETE", + PathPattern: "/roles/{role_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteRoleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteRoleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteRoleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeRole DescribeRole 获取角色详情 +*/ +func (a *Client) DescribeRole(params *DescribeRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRoleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeRoleParams() + } + op := &runtime.ClientOperation{ + ID: "describeRole", + Method: "GET", + PathPattern: "/roles/{role_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeRoleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeRoleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeRoleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeRoles DescribeRoles 获取角色列表 +*/ +func (a *Client) DescribeRoles(params *DescribeRolesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRolesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeRolesParams() + } + op := &runtime.ClientOperation{ + ID: "describeRoles", + Method: "GET", + PathPattern: "/roles", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeRolesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeRolesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeRolesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyRole ModifyRole 修改角色信息(暂不启用) +*/ +func (a *Client) ModifyRole(params *ModifyRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyRoleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyRoleParams() + } + op := &runtime.ClientOperation{ + ID: "modifyRole", + Method: "PUT", + PathPattern: "/roles/{role_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyRoleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyRoleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyRoleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/create_user_sshkey_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/create_user_sshkey_parameters.go new file mode 100644 index 0000000..1216d68 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/create_user_sshkey_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateUserSshkeyParams creates a new CreateUserSshkeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateUserSshkeyParams() *CreateUserSshkeyParams { + return &CreateUserSshkeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateUserSshkeyParamsWithTimeout creates a new CreateUserSshkeyParams object +// with the ability to set a timeout on a request. +func NewCreateUserSshkeyParamsWithTimeout(timeout time.Duration) *CreateUserSshkeyParams { + return &CreateUserSshkeyParams{ + timeout: timeout, + } +} + +// NewCreateUserSshkeyParamsWithContext creates a new CreateUserSshkeyParams object +// with the ability to set a context for a request. +func NewCreateUserSshkeyParamsWithContext(ctx context.Context) *CreateUserSshkeyParams { + return &CreateUserSshkeyParams{ + Context: ctx, + } +} + +// NewCreateUserSshkeyParamsWithHTTPClient creates a new CreateUserSshkeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateUserSshkeyParamsWithHTTPClient(client *http.Client) *CreateUserSshkeyParams { + return &CreateUserSshkeyParams{ + HTTPClient: client, + } +} + +/* CreateUserSshkeyParams contains all the parameters to send to the API endpoint + for the create user sshkey operation. + + Typically these are written to a http.Request. +*/ +type CreateUserSshkeyParams struct { + + // Body. + Body *models.CreateSshkeyRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserSshkeyParams) WithDefaults() *CreateUserSshkeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserSshkeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create user sshkey params +func (o *CreateUserSshkeyParams) WithTimeout(timeout time.Duration) *CreateUserSshkeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create user sshkey params +func (o *CreateUserSshkeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create user sshkey params +func (o *CreateUserSshkeyParams) WithContext(ctx context.Context) *CreateUserSshkeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create user sshkey params +func (o *CreateUserSshkeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create user sshkey params +func (o *CreateUserSshkeyParams) WithHTTPClient(client *http.Client) *CreateUserSshkeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create user sshkey params +func (o *CreateUserSshkeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create user sshkey params +func (o *CreateUserSshkeyParams) WithBody(body *models.CreateSshkeyRequest) *CreateUserSshkeyParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create user sshkey params +func (o *CreateUserSshkeyParams) SetBody(body *models.CreateSshkeyRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create user sshkey params +func (o *CreateUserSshkeyParams) WithAuthorization(authorization string) *CreateUserSshkeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create user sshkey params +func (o *CreateUserSshkeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create user sshkey params +func (o *CreateUserSshkeyParams) WithBmpLanguage(bmpLanguage *string) *CreateUserSshkeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create user sshkey params +func (o *CreateUserSshkeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create user sshkey params +func (o *CreateUserSshkeyParams) WithBmpUserID(bmpUserID *string) *CreateUserSshkeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create user sshkey params +func (o *CreateUserSshkeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create user sshkey params +func (o *CreateUserSshkeyParams) WithTraceID(traceID string) *CreateUserSshkeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create user sshkey params +func (o *CreateUserSshkeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateUserSshkeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/create_user_sshkey_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/create_user_sshkey_responses.go new file mode 100644 index 0000000..1d5e6cb --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/create_user_sshkey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateUserSshkeyReader is a Reader for the CreateUserSshkey structure. +type CreateUserSshkeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateUserSshkeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateUserSshkeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateUserSshkeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateUserSshkeyOK creates a CreateUserSshkeyOK with default headers values +func NewCreateUserSshkeyOK() *CreateUserSshkeyOK { + return &CreateUserSshkeyOK{} +} + +/* CreateUserSshkeyOK describes a response with status code 200, with default header values. + +A CreateUserSshkeyResult is an response struct that is used to describe create sshkey result. +*/ +type CreateUserSshkeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserSshkeyOKBody +} + +// IsSuccess returns true when this create user sshkey o k response has a 2xx status code +func (o *CreateUserSshkeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create user sshkey o k response has a 3xx status code +func (o *CreateUserSshkeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create user sshkey o k response has a 4xx status code +func (o *CreateUserSshkeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create user sshkey o k response has a 5xx status code +func (o *CreateUserSshkeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create user sshkey o k response a status code equal to that given +func (o *CreateUserSshkeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateUserSshkeyOK) Error() string { + return fmt.Sprintf("[POST /user/sshkeys][%d] createUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *CreateUserSshkeyOK) String() string { + return fmt.Sprintf("[POST /user/sshkeys][%d] createUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *CreateUserSshkeyOK) GetPayload() *CreateUserSshkeyOKBody { + return o.Payload +} + +func (o *CreateUserSshkeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserSshkeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateUserSshkeyDefault creates a CreateUserSshkeyDefault with default headers values +func NewCreateUserSshkeyDefault(code int) *CreateUserSshkeyDefault { + return &CreateUserSshkeyDefault{ + _statusCode: code, + } +} + +/* CreateUserSshkeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateUserSshkeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserSshkeyDefaultBody +} + +// Code gets the status code for the create user sshkey default response +func (o *CreateUserSshkeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create user sshkey default response has a 2xx status code +func (o *CreateUserSshkeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create user sshkey default response has a 3xx status code +func (o *CreateUserSshkeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create user sshkey default response has a 4xx status code +func (o *CreateUserSshkeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create user sshkey default response has a 5xx status code +func (o *CreateUserSshkeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create user sshkey default response a status code equal to that given +func (o *CreateUserSshkeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateUserSshkeyDefault) Error() string { + return fmt.Sprintf("[POST /user/sshkeys][%d] createUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserSshkeyDefault) String() string { + return fmt.Sprintf("[POST /user/sshkeys][%d] createUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserSshkeyDefault) GetPayload() *CreateUserSshkeyDefaultBody { + return o.Payload +} + +func (o *CreateUserSshkeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserSshkeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateUserSshkeyDefaultBody create user sshkey default body +swagger:model CreateUserSshkeyDefaultBody +*/ +type CreateUserSshkeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create user sshkey default body +func (o *CreateUserSshkeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserSshkeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createUserSshkey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateUserSshkeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createUserSshkey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user sshkey default body based on the context it is used +func (o *CreateUserSshkeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserSshkeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserSshkeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserSshkeyDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateUserSshkeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateUserSshkeyOKBody create user sshkey o k body +swagger:model CreateUserSshkeyOKBody +*/ +type CreateUserSshkeyOKBody struct { + + // result + Result *models.SshkeyID `json:"result,omitempty"` +} + +// Validate validates this create user sshkey o k body +func (o *CreateUserSshkeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserSshkeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user sshkey o k body based on the context it is used +func (o *CreateUserSshkeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserSshkeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserSshkeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserSshkeyOKBody) UnmarshalBinary(b []byte) error { + var res CreateUserSshkeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/delete_user_sshkey_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/delete_user_sshkey_parameters.go new file mode 100644 index 0000000..9fdcc89 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/delete_user_sshkey_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteUserSshkeyParams creates a new DeleteUserSshkeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteUserSshkeyParams() *DeleteUserSshkeyParams { + return &DeleteUserSshkeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteUserSshkeyParamsWithTimeout creates a new DeleteUserSshkeyParams object +// with the ability to set a timeout on a request. +func NewDeleteUserSshkeyParamsWithTimeout(timeout time.Duration) *DeleteUserSshkeyParams { + return &DeleteUserSshkeyParams{ + timeout: timeout, + } +} + +// NewDeleteUserSshkeyParamsWithContext creates a new DeleteUserSshkeyParams object +// with the ability to set a context for a request. +func NewDeleteUserSshkeyParamsWithContext(ctx context.Context) *DeleteUserSshkeyParams { + return &DeleteUserSshkeyParams{ + Context: ctx, + } +} + +// NewDeleteUserSshkeyParamsWithHTTPClient creates a new DeleteUserSshkeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteUserSshkeyParamsWithHTTPClient(client *http.Client) *DeleteUserSshkeyParams { + return &DeleteUserSshkeyParams{ + HTTPClient: client, + } +} + +/* DeleteUserSshkeyParams contains all the parameters to send to the API endpoint + for the delete user sshkey operation. + + Typically these are written to a http.Request. +*/ +type DeleteUserSshkeyParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // SshkeyID. + SshkeyID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserSshkeyParams) WithDefaults() *DeleteUserSshkeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserSshkeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithTimeout(timeout time.Duration) *DeleteUserSshkeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithContext(ctx context.Context) *DeleteUserSshkeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithHTTPClient(client *http.Client) *DeleteUserSshkeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithAuthorization(authorization string) *DeleteUserSshkeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithBmpLanguage(bmpLanguage *string) *DeleteUserSshkeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithBmpUserID(bmpUserID *string) *DeleteUserSshkeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithSshkeyID adds the sshkeyID to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithSshkeyID(sshkeyID string) *DeleteUserSshkeyParams { + o.SetSshkeyID(sshkeyID) + return o +} + +// SetSshkeyID adds the sshkeyId to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetSshkeyID(sshkeyID string) { + o.SshkeyID = sshkeyID +} + +// WithTraceID adds the traceID to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithTraceID(traceID string) *DeleteUserSshkeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteUserSshkeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param sshkey_id + if err := r.SetPathParam("sshkey_id", o.SshkeyID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/delete_user_sshkey_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/delete_user_sshkey_responses.go new file mode 100644 index 0000000..461caf2 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/delete_user_sshkey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteUserSshkeyReader is a Reader for the DeleteUserSshkey structure. +type DeleteUserSshkeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteUserSshkeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteUserSshkeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteUserSshkeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteUserSshkeyOK creates a DeleteUserSshkeyOK with default headers values +func NewDeleteUserSshkeyOK() *DeleteUserSshkeyOK { + return &DeleteUserSshkeyOK{} +} + +/* DeleteUserSshkeyOK describes a response with status code 200, with default header values. + +A DeleteUserSshkeyResult is an response struct that is used to describe delete sshkey result. +*/ +type DeleteUserSshkeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserSshkeyOKBody +} + +// IsSuccess returns true when this delete user sshkey o k response has a 2xx status code +func (o *DeleteUserSshkeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete user sshkey o k response has a 3xx status code +func (o *DeleteUserSshkeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete user sshkey o k response has a 4xx status code +func (o *DeleteUserSshkeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete user sshkey o k response has a 5xx status code +func (o *DeleteUserSshkeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete user sshkey o k response a status code equal to that given +func (o *DeleteUserSshkeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteUserSshkeyOK) Error() string { + return fmt.Sprintf("[DELETE /user/sshkeys/{sshkey_id}][%d] deleteUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *DeleteUserSshkeyOK) String() string { + return fmt.Sprintf("[DELETE /user/sshkeys/{sshkey_id}][%d] deleteUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *DeleteUserSshkeyOK) GetPayload() *DeleteUserSshkeyOKBody { + return o.Payload +} + +func (o *DeleteUserSshkeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserSshkeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteUserSshkeyDefault creates a DeleteUserSshkeyDefault with default headers values +func NewDeleteUserSshkeyDefault(code int) *DeleteUserSshkeyDefault { + return &DeleteUserSshkeyDefault{ + _statusCode: code, + } +} + +/* DeleteUserSshkeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteUserSshkeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserSshkeyDefaultBody +} + +// Code gets the status code for the delete user sshkey default response +func (o *DeleteUserSshkeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete user sshkey default response has a 2xx status code +func (o *DeleteUserSshkeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete user sshkey default response has a 3xx status code +func (o *DeleteUserSshkeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete user sshkey default response has a 4xx status code +func (o *DeleteUserSshkeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete user sshkey default response has a 5xx status code +func (o *DeleteUserSshkeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete user sshkey default response a status code equal to that given +func (o *DeleteUserSshkeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteUserSshkeyDefault) Error() string { + return fmt.Sprintf("[DELETE /user/sshkeys/{sshkey_id}][%d] deleteUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserSshkeyDefault) String() string { + return fmt.Sprintf("[DELETE /user/sshkeys/{sshkey_id}][%d] deleteUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserSshkeyDefault) GetPayload() *DeleteUserSshkeyDefaultBody { + return o.Payload +} + +func (o *DeleteUserSshkeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserSshkeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteUserSshkeyDefaultBody delete user sshkey default body +swagger:model DeleteUserSshkeyDefaultBody +*/ +type DeleteUserSshkeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete user sshkey default body +func (o *DeleteUserSshkeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserSshkeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserSshkey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteUserSshkeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserSshkey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user sshkey default body based on the context it is used +func (o *DeleteUserSshkeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserSshkeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserSshkeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserSshkeyDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteUserSshkeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteUserSshkeyOKBody delete user sshkey o k body +swagger:model DeleteUserSshkeyOKBody +*/ +type DeleteUserSshkeyOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete user sshkey o k body +func (o *DeleteUserSshkeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserSshkeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user sshkey o k body based on the context it is used +func (o *DeleteUserSshkeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserSshkeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserSshkeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserSshkeyOKBody) UnmarshalBinary(b []byte) error { + var res DeleteUserSshkeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_key_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_key_parameters.go new file mode 100644 index 0000000..0039fc8 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_key_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeUserSSHKeyParams creates a new DescribeUserSSHKeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserSSHKeyParams() *DescribeUserSSHKeyParams { + return &DescribeUserSSHKeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserSSHKeyParamsWithTimeout creates a new DescribeUserSSHKeyParams object +// with the ability to set a timeout on a request. +func NewDescribeUserSSHKeyParamsWithTimeout(timeout time.Duration) *DescribeUserSSHKeyParams { + return &DescribeUserSSHKeyParams{ + timeout: timeout, + } +} + +// NewDescribeUserSSHKeyParamsWithContext creates a new DescribeUserSSHKeyParams object +// with the ability to set a context for a request. +func NewDescribeUserSSHKeyParamsWithContext(ctx context.Context) *DescribeUserSSHKeyParams { + return &DescribeUserSSHKeyParams{ + Context: ctx, + } +} + +// NewDescribeUserSSHKeyParamsWithHTTPClient creates a new DescribeUserSSHKeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserSSHKeyParamsWithHTTPClient(client *http.Client) *DescribeUserSSHKeyParams { + return &DescribeUserSSHKeyParams{ + HTTPClient: client, + } +} + +/* DescribeUserSSHKeyParams contains all the parameters to send to the API endpoint + for the describe user Ssh key operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserSSHKeyParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // SshkeyID. + SshkeyID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user Ssh key params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserSSHKeyParams) WithDefaults() *DescribeUserSSHKeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user Ssh key params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserSSHKeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithTimeout(timeout time.Duration) *DescribeUserSSHKeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithContext(ctx context.Context) *DescribeUserSSHKeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithHTTPClient(client *http.Client) *DescribeUserSSHKeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithAuthorization(authorization string) *DescribeUserSSHKeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserSSHKeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithBmpUserID(bmpUserID *string) *DescribeUserSSHKeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithSshkeyID adds the sshkeyID to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithSshkeyID(sshkeyID string) *DescribeUserSSHKeyParams { + o.SetSshkeyID(sshkeyID) + return o +} + +// SetSshkeyID adds the sshkeyId to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetSshkeyID(sshkeyID string) { + o.SshkeyID = sshkeyID +} + +// WithTraceID adds the traceID to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithTraceID(traceID string) *DescribeUserSSHKeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserSSHKeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param sshkey_id + if err := r.SetPathParam("sshkey_id", o.SshkeyID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_key_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_key_responses.go new file mode 100644 index 0000000..572eba8 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_key_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserSSHKeyReader is a Reader for the DescribeUserSSHKey structure. +type DescribeUserSSHKeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserSSHKeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserSSHKeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserSSHKeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserSSHKeyOK creates a DescribeUserSSHKeyOK with default headers values +func NewDescribeUserSSHKeyOK() *DescribeUserSSHKeyOK { + return &DescribeUserSSHKeyOK{} +} + +/* DescribeUserSSHKeyOK describes a response with status code 200, with default header values. + +A DescribeUserSshKeyResult is an response struct that is used to describe sshkey. +*/ +type DescribeUserSSHKeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserSSHKeyOKBody +} + +// IsSuccess returns true when this describe user Ssh key o k response has a 2xx status code +func (o *DescribeUserSSHKeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user Ssh key o k response has a 3xx status code +func (o *DescribeUserSSHKeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user Ssh key o k response has a 4xx status code +func (o *DescribeUserSSHKeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user Ssh key o k response has a 5xx status code +func (o *DescribeUserSSHKeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user Ssh key o k response a status code equal to that given +func (o *DescribeUserSSHKeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserSSHKeyOK) Error() string { + return fmt.Sprintf("[GET /user/sshkeys/{sshkey_id}][%d] describeUserSshKeyOK %+v", 200, o.Payload) +} + +func (o *DescribeUserSSHKeyOK) String() string { + return fmt.Sprintf("[GET /user/sshkeys/{sshkey_id}][%d] describeUserSshKeyOK %+v", 200, o.Payload) +} + +func (o *DescribeUserSSHKeyOK) GetPayload() *DescribeUserSSHKeyOKBody { + return o.Payload +} + +func (o *DescribeUserSSHKeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserSSHKeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserSSHKeyDefault creates a DescribeUserSSHKeyDefault with default headers values +func NewDescribeUserSSHKeyDefault(code int) *DescribeUserSSHKeyDefault { + return &DescribeUserSSHKeyDefault{ + _statusCode: code, + } +} + +/* DescribeUserSSHKeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserSSHKeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserSSHKeyDefaultBody +} + +// Code gets the status code for the describe user Ssh key default response +func (o *DescribeUserSSHKeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user Ssh key default response has a 2xx status code +func (o *DescribeUserSSHKeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user Ssh key default response has a 3xx status code +func (o *DescribeUserSSHKeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user Ssh key default response has a 4xx status code +func (o *DescribeUserSSHKeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user Ssh key default response has a 5xx status code +func (o *DescribeUserSSHKeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user Ssh key default response a status code equal to that given +func (o *DescribeUserSSHKeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserSSHKeyDefault) Error() string { + return fmt.Sprintf("[GET /user/sshkeys/{sshkey_id}][%d] describeUserSshKey default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserSSHKeyDefault) String() string { + return fmt.Sprintf("[GET /user/sshkeys/{sshkey_id}][%d] describeUserSshKey default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserSSHKeyDefault) GetPayload() *DescribeUserSSHKeyDefaultBody { + return o.Payload +} + +func (o *DescribeUserSSHKeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserSSHKeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserSSHKeyDefaultBody describe user SSH key default body +swagger:model DescribeUserSSHKeyDefaultBody +*/ +type DescribeUserSSHKeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user SSH key default body +func (o *DescribeUserSSHKeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserSshKey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserSSHKeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserSshKey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user SSH key default body based on the context it is used +func (o *DescribeUserSSHKeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserSSHKeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserSSHKeyDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserSSHKeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserSSHKeyOKBody describe user SSH key o k body +swagger:model DescribeUserSSHKeyOKBody +*/ +type DescribeUserSSHKeyOKBody struct { + + // result + Result *models.SshkeyInfo `json:"result,omitempty"` +} + +// Validate validates this describe user SSH key o k body +func (o *DescribeUserSSHKeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user SSH key o k body based on the context it is used +func (o *DescribeUserSSHKeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserSSHKeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserSSHKeyOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserSSHKeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_keys_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_keys_parameters.go new file mode 100644 index 0000000..78cbf1f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_keys_parameters.go @@ -0,0 +1,362 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeUserSSHKeysParams creates a new DescribeUserSSHKeysParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserSSHKeysParams() *DescribeUserSSHKeysParams { + return &DescribeUserSSHKeysParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserSSHKeysParamsWithTimeout creates a new DescribeUserSSHKeysParams object +// with the ability to set a timeout on a request. +func NewDescribeUserSSHKeysParamsWithTimeout(timeout time.Duration) *DescribeUserSSHKeysParams { + return &DescribeUserSSHKeysParams{ + timeout: timeout, + } +} + +// NewDescribeUserSSHKeysParamsWithContext creates a new DescribeUserSSHKeysParams object +// with the ability to set a context for a request. +func NewDescribeUserSSHKeysParamsWithContext(ctx context.Context) *DescribeUserSSHKeysParams { + return &DescribeUserSSHKeysParams{ + Context: ctx, + } +} + +// NewDescribeUserSSHKeysParamsWithHTTPClient creates a new DescribeUserSSHKeysParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserSSHKeysParamsWithHTTPClient(client *http.Client) *DescribeUserSSHKeysParams { + return &DescribeUserSSHKeysParams{ + HTTPClient: client, + } +} + +/* DescribeUserSSHKeysParams contains all the parameters to send to the API endpoint + for the describe user Ssh keys operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserSSHKeysParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否显示全部 + */ + IsAll *string + + /* Name. + + 秘钥名称 + */ + Name *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user Ssh keys params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserSSHKeysParams) WithDefaults() *DescribeUserSSHKeysParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user Ssh keys params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserSSHKeysParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithTimeout(timeout time.Duration) *DescribeUserSSHKeysParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithContext(ctx context.Context) *DescribeUserSSHKeysParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithHTTPClient(client *http.Client) *DescribeUserSSHKeysParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithAuthorization(authorization string) *DescribeUserSSHKeysParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserSSHKeysParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithBmpUserID(bmpUserID *string) *DescribeUserSSHKeysParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithIsAll(isAll *string) *DescribeUserSSHKeysParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithName adds the name to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithName(name *string) *DescribeUserSSHKeysParams { + o.SetName(name) + return o +} + +// SetName adds the name to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetName(name *string) { + o.Name = name +} + +// WithPageNumber adds the pageNumber to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithPageNumber(pageNumber *int64) *DescribeUserSSHKeysParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithPageSize(pageSize *int64) *DescribeUserSSHKeysParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithTraceID(traceID string) *DescribeUserSSHKeysParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserSSHKeysParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_keys_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_keys_responses.go new file mode 100644 index 0000000..db54423 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_keys_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserSSHKeysReader is a Reader for the DescribeUserSSHKeys structure. +type DescribeUserSSHKeysReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserSSHKeysReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserSSHKeysOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserSSHKeysDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserSSHKeysOK creates a DescribeUserSSHKeysOK with default headers values +func NewDescribeUserSSHKeysOK() *DescribeUserSSHKeysOK { + return &DescribeUserSSHKeysOK{} +} + +/* DescribeUserSSHKeysOK describes a response with status code 200, with default header values. + +A DescribeUserSshKeysResult is an response struct that is used to describe get sshkey list. +*/ +type DescribeUserSSHKeysOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserSSHKeysOKBody +} + +// IsSuccess returns true when this describe user Ssh keys o k response has a 2xx status code +func (o *DescribeUserSSHKeysOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user Ssh keys o k response has a 3xx status code +func (o *DescribeUserSSHKeysOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user Ssh keys o k response has a 4xx status code +func (o *DescribeUserSSHKeysOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user Ssh keys o k response has a 5xx status code +func (o *DescribeUserSSHKeysOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user Ssh keys o k response a status code equal to that given +func (o *DescribeUserSSHKeysOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserSSHKeysOK) Error() string { + return fmt.Sprintf("[GET /user/sshkeys][%d] describeUserSshKeysOK %+v", 200, o.Payload) +} + +func (o *DescribeUserSSHKeysOK) String() string { + return fmt.Sprintf("[GET /user/sshkeys][%d] describeUserSshKeysOK %+v", 200, o.Payload) +} + +func (o *DescribeUserSSHKeysOK) GetPayload() *DescribeUserSSHKeysOKBody { + return o.Payload +} + +func (o *DescribeUserSSHKeysOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserSSHKeysOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserSSHKeysDefault creates a DescribeUserSSHKeysDefault with default headers values +func NewDescribeUserSSHKeysDefault(code int) *DescribeUserSSHKeysDefault { + return &DescribeUserSSHKeysDefault{ + _statusCode: code, + } +} + +/* DescribeUserSSHKeysDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserSSHKeysDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserSSHKeysDefaultBody +} + +// Code gets the status code for the describe user Ssh keys default response +func (o *DescribeUserSSHKeysDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user Ssh keys default response has a 2xx status code +func (o *DescribeUserSSHKeysDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user Ssh keys default response has a 3xx status code +func (o *DescribeUserSSHKeysDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user Ssh keys default response has a 4xx status code +func (o *DescribeUserSSHKeysDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user Ssh keys default response has a 5xx status code +func (o *DescribeUserSSHKeysDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user Ssh keys default response a status code equal to that given +func (o *DescribeUserSSHKeysDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserSSHKeysDefault) Error() string { + return fmt.Sprintf("[GET /user/sshkeys][%d] describeUserSshKeys default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserSSHKeysDefault) String() string { + return fmt.Sprintf("[GET /user/sshkeys][%d] describeUserSshKeys default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserSSHKeysDefault) GetPayload() *DescribeUserSSHKeysDefaultBody { + return o.Payload +} + +func (o *DescribeUserSSHKeysDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserSSHKeysDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserSSHKeysDefaultBody describe user SSH keys default body +swagger:model DescribeUserSSHKeysDefaultBody +*/ +type DescribeUserSSHKeysDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user SSH keys default body +func (o *DescribeUserSSHKeysDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeysDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserSshKeys default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserSSHKeysDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserSshKeys default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeys default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeys default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user SSH keys default body based on the context it is used +func (o *DescribeUserSSHKeysDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeysDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeys default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeys default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserSSHKeysDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserSSHKeysDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserSSHKeysDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserSSHKeysOKBody describe user SSH keys o k body +swagger:model DescribeUserSSHKeysOKBody +*/ +type DescribeUserSSHKeysOKBody struct { + + // result + Result *models.SshkeyList `json:"result,omitempty"` +} + +// Validate validates this describe user SSH keys o k body +func (o *DescribeUserSSHKeysOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeysOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeysOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeysOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user SSH keys o k body based on the context it is used +func (o *DescribeUserSSHKeysOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeysOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeysOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeysOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserSSHKeysOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserSSHKeysOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserSSHKeysOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/get_instances_by_sshkey_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/get_instances_by_sshkey_parameters.go new file mode 100644 index 0000000..d12c7d1 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/get_instances_by_sshkey_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetInstancesBySshkeyParams creates a new GetInstancesBySshkeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetInstancesBySshkeyParams() *GetInstancesBySshkeyParams { + return &GetInstancesBySshkeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetInstancesBySshkeyParamsWithTimeout creates a new GetInstancesBySshkeyParams object +// with the ability to set a timeout on a request. +func NewGetInstancesBySshkeyParamsWithTimeout(timeout time.Duration) *GetInstancesBySshkeyParams { + return &GetInstancesBySshkeyParams{ + timeout: timeout, + } +} + +// NewGetInstancesBySshkeyParamsWithContext creates a new GetInstancesBySshkeyParams object +// with the ability to set a context for a request. +func NewGetInstancesBySshkeyParamsWithContext(ctx context.Context) *GetInstancesBySshkeyParams { + return &GetInstancesBySshkeyParams{ + Context: ctx, + } +} + +// NewGetInstancesBySshkeyParamsWithHTTPClient creates a new GetInstancesBySshkeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetInstancesBySshkeyParamsWithHTTPClient(client *http.Client) *GetInstancesBySshkeyParams { + return &GetInstancesBySshkeyParams{ + HTTPClient: client, + } +} + +/* GetInstancesBySshkeyParams contains all the parameters to send to the API endpoint + for the get instances by sshkey operation. + + Typically these are written to a http.Request. +*/ +type GetInstancesBySshkeyParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // SshkeyID. + SshkeyID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get instances by sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetInstancesBySshkeyParams) WithDefaults() *GetInstancesBySshkeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get instances by sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetInstancesBySshkeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithTimeout(timeout time.Duration) *GetInstancesBySshkeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithContext(ctx context.Context) *GetInstancesBySshkeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithHTTPClient(client *http.Client) *GetInstancesBySshkeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithAuthorization(authorization string) *GetInstancesBySshkeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithBmpLanguage(bmpLanguage *string) *GetInstancesBySshkeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithBmpUserID(bmpUserID *string) *GetInstancesBySshkeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithSshkeyID adds the sshkeyID to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithSshkeyID(sshkeyID string) *GetInstancesBySshkeyParams { + o.SetSshkeyID(sshkeyID) + return o +} + +// SetSshkeyID adds the sshkeyId to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetSshkeyID(sshkeyID string) { + o.SshkeyID = sshkeyID +} + +// WithTraceID adds the traceID to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithTraceID(traceID string) *GetInstancesBySshkeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetInstancesBySshkeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param sshkey_id + if err := r.SetPathParam("sshkey_id", o.SshkeyID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/get_instances_by_sshkey_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/get_instances_by_sshkey_responses.go new file mode 100644 index 0000000..b7c4f1b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/get_instances_by_sshkey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// GetInstancesBySshkeyReader is a Reader for the GetInstancesBySshkey structure. +type GetInstancesBySshkeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetInstancesBySshkeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetInstancesBySshkeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetInstancesBySshkeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetInstancesBySshkeyOK creates a GetInstancesBySshkeyOK with default headers values +func NewGetInstancesBySshkeyOK() *GetInstancesBySshkeyOK { + return &GetInstancesBySshkeyOK{} +} + +/* GetInstancesBySshkeyOK describes a response with status code 200, with default header values. + +A GetInstancesBySshkeyResult is an response struct that is used to get instance list by sshkey. +*/ +type GetInstancesBySshkeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetInstancesBySshkeyOKBody +} + +// IsSuccess returns true when this get instances by sshkey o k response has a 2xx status code +func (o *GetInstancesBySshkeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get instances by sshkey o k response has a 3xx status code +func (o *GetInstancesBySshkeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get instances by sshkey o k response has a 4xx status code +func (o *GetInstancesBySshkeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get instances by sshkey o k response has a 5xx status code +func (o *GetInstancesBySshkeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get instances by sshkey o k response a status code equal to that given +func (o *GetInstancesBySshkeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *GetInstancesBySshkeyOK) Error() string { + return fmt.Sprintf("[GET /user/sshkeys/instances/{sshkey_id}][%d] getInstancesBySshkeyOK %+v", 200, o.Payload) +} + +func (o *GetInstancesBySshkeyOK) String() string { + return fmt.Sprintf("[GET /user/sshkeys/instances/{sshkey_id}][%d] getInstancesBySshkeyOK %+v", 200, o.Payload) +} + +func (o *GetInstancesBySshkeyOK) GetPayload() *GetInstancesBySshkeyOKBody { + return o.Payload +} + +func (o *GetInstancesBySshkeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetInstancesBySshkeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetInstancesBySshkeyDefault creates a GetInstancesBySshkeyDefault with default headers values +func NewGetInstancesBySshkeyDefault(code int) *GetInstancesBySshkeyDefault { + return &GetInstancesBySshkeyDefault{ + _statusCode: code, + } +} + +/* GetInstancesBySshkeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type GetInstancesBySshkeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetInstancesBySshkeyDefaultBody +} + +// Code gets the status code for the get instances by sshkey default response +func (o *GetInstancesBySshkeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this get instances by sshkey default response has a 2xx status code +func (o *GetInstancesBySshkeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get instances by sshkey default response has a 3xx status code +func (o *GetInstancesBySshkeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get instances by sshkey default response has a 4xx status code +func (o *GetInstancesBySshkeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get instances by sshkey default response has a 5xx status code +func (o *GetInstancesBySshkeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get instances by sshkey default response a status code equal to that given +func (o *GetInstancesBySshkeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *GetInstancesBySshkeyDefault) Error() string { + return fmt.Sprintf("[GET /user/sshkeys/instances/{sshkey_id}][%d] getInstancesBySshkey default %+v", o._statusCode, o.Payload) +} + +func (o *GetInstancesBySshkeyDefault) String() string { + return fmt.Sprintf("[GET /user/sshkeys/instances/{sshkey_id}][%d] getInstancesBySshkey default %+v", o._statusCode, o.Payload) +} + +func (o *GetInstancesBySshkeyDefault) GetPayload() *GetInstancesBySshkeyDefaultBody { + return o.Payload +} + +func (o *GetInstancesBySshkeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetInstancesBySshkeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*GetInstancesBySshkeyDefaultBody get instances by sshkey default body +swagger:model GetInstancesBySshkeyDefaultBody +*/ +type GetInstancesBySshkeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this get instances by sshkey default body +func (o *GetInstancesBySshkeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetInstancesBySshkeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("getInstancesBySshkey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *GetInstancesBySshkeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("getInstancesBySshkey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getInstancesBySshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getInstancesBySshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get instances by sshkey default body based on the context it is used +func (o *GetInstancesBySshkeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetInstancesBySshkeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getInstancesBySshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getInstancesBySshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetInstancesBySshkeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetInstancesBySshkeyDefaultBody) UnmarshalBinary(b []byte) error { + var res GetInstancesBySshkeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*GetInstancesBySshkeyOKBody get instances by sshkey o k body +swagger:model GetInstancesBySshkeyOKBody +*/ +type GetInstancesBySshkeyOKBody struct { + + // result + Result *models.InstancesSshkeyInfoResponse `json:"result,omitempty"` +} + +// Validate validates this get instances by sshkey o k body +func (o *GetInstancesBySshkeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetInstancesBySshkeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getInstancesBySshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getInstancesBySshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get instances by sshkey o k body based on the context it is used +func (o *GetInstancesBySshkeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetInstancesBySshkeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getInstancesBySshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getInstancesBySshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetInstancesBySshkeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetInstancesBySshkeyOKBody) UnmarshalBinary(b []byte) error { + var res GetInstancesBySshkeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/modify_user_sshkey_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/modify_user_sshkey_parameters.go new file mode 100644 index 0000000..43464ce --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/modify_user_sshkey_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyUserSshkeyParams creates a new ModifyUserSshkeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyUserSshkeyParams() *ModifyUserSshkeyParams { + return &ModifyUserSshkeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyUserSshkeyParamsWithTimeout creates a new ModifyUserSshkeyParams object +// with the ability to set a timeout on a request. +func NewModifyUserSshkeyParamsWithTimeout(timeout time.Duration) *ModifyUserSshkeyParams { + return &ModifyUserSshkeyParams{ + timeout: timeout, + } +} + +// NewModifyUserSshkeyParamsWithContext creates a new ModifyUserSshkeyParams object +// with the ability to set a context for a request. +func NewModifyUserSshkeyParamsWithContext(ctx context.Context) *ModifyUserSshkeyParams { + return &ModifyUserSshkeyParams{ + Context: ctx, + } +} + +// NewModifyUserSshkeyParamsWithHTTPClient creates a new ModifyUserSshkeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyUserSshkeyParamsWithHTTPClient(client *http.Client) *ModifyUserSshkeyParams { + return &ModifyUserSshkeyParams{ + HTTPClient: client, + } +} + +/* ModifyUserSshkeyParams contains all the parameters to send to the API endpoint + for the modify user sshkey operation. + + Typically these are written to a http.Request. +*/ +type ModifyUserSshkeyParams struct { + + // Body. + Body *models.ModifySshkeyRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // SshkeyID. + SshkeyID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserSshkeyParams) WithDefaults() *ModifyUserSshkeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserSshkeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithTimeout(timeout time.Duration) *ModifyUserSshkeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithContext(ctx context.Context) *ModifyUserSshkeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithHTTPClient(client *http.Client) *ModifyUserSshkeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithBody(body *models.ModifySshkeyRequest) *ModifyUserSshkeyParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetBody(body *models.ModifySshkeyRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithAuthorization(authorization string) *ModifyUserSshkeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithBmpLanguage(bmpLanguage *string) *ModifyUserSshkeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithBmpUserID(bmpUserID *string) *ModifyUserSshkeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithSshkeyID adds the sshkeyID to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithSshkeyID(sshkeyID string) *ModifyUserSshkeyParams { + o.SetSshkeyID(sshkeyID) + return o +} + +// SetSshkeyID adds the sshkeyId to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetSshkeyID(sshkeyID string) { + o.SshkeyID = sshkeyID +} + +// WithTraceID adds the traceID to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithTraceID(traceID string) *ModifyUserSshkeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyUserSshkeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param sshkey_id + if err := r.SetPathParam("sshkey_id", o.SshkeyID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/modify_user_sshkey_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/modify_user_sshkey_responses.go new file mode 100644 index 0000000..8037709 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/modify_user_sshkey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyUserSshkeyReader is a Reader for the ModifyUserSshkey structure. +type ModifyUserSshkeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyUserSshkeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyUserSshkeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyUserSshkeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyUserSshkeyOK creates a ModifyUserSshkeyOK with default headers values +func NewModifyUserSshkeyOK() *ModifyUserSshkeyOK { + return &ModifyUserSshkeyOK{} +} + +/* ModifyUserSshkeyOK describes a response with status code 200, with default header values. + +A ModifyUserSshkeyResult is an response struct that is used to modify sshkey result. +*/ +type ModifyUserSshkeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserSshkeyOKBody +} + +// IsSuccess returns true when this modify user sshkey o k response has a 2xx status code +func (o *ModifyUserSshkeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify user sshkey o k response has a 3xx status code +func (o *ModifyUserSshkeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify user sshkey o k response has a 4xx status code +func (o *ModifyUserSshkeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify user sshkey o k response has a 5xx status code +func (o *ModifyUserSshkeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify user sshkey o k response a status code equal to that given +func (o *ModifyUserSshkeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyUserSshkeyOK) Error() string { + return fmt.Sprintf("[PUT /user/sshkeys/{sshkey_id}][%d] modifyUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *ModifyUserSshkeyOK) String() string { + return fmt.Sprintf("[PUT /user/sshkeys/{sshkey_id}][%d] modifyUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *ModifyUserSshkeyOK) GetPayload() *ModifyUserSshkeyOKBody { + return o.Payload +} + +func (o *ModifyUserSshkeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserSshkeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyUserSshkeyDefault creates a ModifyUserSshkeyDefault with default headers values +func NewModifyUserSshkeyDefault(code int) *ModifyUserSshkeyDefault { + return &ModifyUserSshkeyDefault{ + _statusCode: code, + } +} + +/* ModifyUserSshkeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyUserSshkeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserSshkeyDefaultBody +} + +// Code gets the status code for the modify user sshkey default response +func (o *ModifyUserSshkeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify user sshkey default response has a 2xx status code +func (o *ModifyUserSshkeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify user sshkey default response has a 3xx status code +func (o *ModifyUserSshkeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify user sshkey default response has a 4xx status code +func (o *ModifyUserSshkeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify user sshkey default response has a 5xx status code +func (o *ModifyUserSshkeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify user sshkey default response a status code equal to that given +func (o *ModifyUserSshkeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyUserSshkeyDefault) Error() string { + return fmt.Sprintf("[PUT /user/sshkeys/{sshkey_id}][%d] modifyUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserSshkeyDefault) String() string { + return fmt.Sprintf("[PUT /user/sshkeys/{sshkey_id}][%d] modifyUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserSshkeyDefault) GetPayload() *ModifyUserSshkeyDefaultBody { + return o.Payload +} + +func (o *ModifyUserSshkeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserSshkeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyUserSshkeyDefaultBody modify user sshkey default body +swagger:model ModifyUserSshkeyDefaultBody +*/ +type ModifyUserSshkeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify user sshkey default body +func (o *ModifyUserSshkeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserSshkeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserSshkey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyUserSshkeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserSshkey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user sshkey default body based on the context it is used +func (o *ModifyUserSshkeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserSshkeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserSshkeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserSshkeyDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyUserSshkeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyUserSshkeyOKBody modify user sshkey o k body +swagger:model ModifyUserSshkeyOKBody +*/ +type ModifyUserSshkeyOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify user sshkey o k body +func (o *ModifyUserSshkeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserSshkeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user sshkey o k body based on the context it is used +func (o *ModifyUserSshkeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserSshkeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserSshkeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserSshkeyOKBody) UnmarshalBinary(b []byte) error { + var res ModifyUserSshkeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/sshkey_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/sshkey_client.go new file mode 100644 index 0000000..16c7309 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/sshkey/sshkey_client.go @@ -0,0 +1,277 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new sshkey API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for sshkey API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateUserSshkey(params *CreateUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserSshkeyOK, error) + + DeleteUserSshkey(params *DeleteUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserSshkeyOK, error) + + DescribeUserSSHKey(params *DescribeUserSSHKeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserSSHKeyOK, error) + + DescribeUserSSHKeys(params *DescribeUserSSHKeysParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserSSHKeysOK, error) + + GetInstancesBySshkey(params *GetInstancesBySshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetInstancesBySshkeyOK, error) + + ModifyUserSshkey(params *ModifyUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserSshkeyOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateUserSshkey CreateUserSshkey 创建个人sshkey +*/ +func (a *Client) CreateUserSshkey(params *CreateUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserSshkeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateUserSshkeyParams() + } + op := &runtime.ClientOperation{ + ID: "createUserSshkey", + Method: "POST", + PathPattern: "/user/sshkeys", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateUserSshkeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateUserSshkeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateUserSshkeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteUserSshkey DeleteUserSshkey 删除sshkey +*/ +func (a *Client) DeleteUserSshkey(params *DeleteUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserSshkeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteUserSshkeyParams() + } + op := &runtime.ClientOperation{ + ID: "deleteUserSshkey", + Method: "DELETE", + PathPattern: "/user/sshkeys/{sshkey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteUserSshkeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteUserSshkeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteUserSshkeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserSSHKey DescribeUserSshKey 获取sshkey详情 +*/ +func (a *Client) DescribeUserSSHKey(params *DescribeUserSSHKeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserSSHKeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserSSHKeyParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserSshKey", + Method: "GET", + PathPattern: "/user/sshkeys/{sshkey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserSSHKeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserSSHKeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserSSHKeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserSSHKeys DescribeUserSshKeys 获取个人sshkey列表 +*/ +func (a *Client) DescribeUserSSHKeys(params *DescribeUserSSHKeysParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserSSHKeysOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserSSHKeysParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserSshKeys", + Method: "GET", + PathPattern: "/user/sshkeys", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserSSHKeysReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserSSHKeysOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserSSHKeysDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + GetInstancesBySshkey GetInstancesBySshkey 根据sshkey获取实例列表 +*/ +func (a *Client) GetInstancesBySshkey(params *GetInstancesBySshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetInstancesBySshkeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetInstancesBySshkeyParams() + } + op := &runtime.ClientOperation{ + ID: "getInstancesBySshkey", + Method: "GET", + PathPattern: "/user/sshkeys/instances/{sshkey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetInstancesBySshkeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetInstancesBySshkeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetInstancesBySshkeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyUserSshkey ModifyUserSshkey 修改sshkey +*/ +func (a *Client) ModifyUserSshkey(params *ModifyUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserSshkeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyUserSshkeyParams() + } + op := &runtime.ClientOperation{ + ID: "modifyUserSshkey", + Method: "PUT", + PathPattern: "/user/sshkeys/{sshkey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyUserSshkeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyUserSshkeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyUserSshkeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/create_user_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/create_user_parameters.go new file mode 100644 index 0000000..a600f31 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/create_user_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateUserParams creates a new CreateUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateUserParams() *CreateUserParams { + return &CreateUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateUserParamsWithTimeout creates a new CreateUserParams object +// with the ability to set a timeout on a request. +func NewCreateUserParamsWithTimeout(timeout time.Duration) *CreateUserParams { + return &CreateUserParams{ + timeout: timeout, + } +} + +// NewCreateUserParamsWithContext creates a new CreateUserParams object +// with the ability to set a context for a request. +func NewCreateUserParamsWithContext(ctx context.Context) *CreateUserParams { + return &CreateUserParams{ + Context: ctx, + } +} + +// NewCreateUserParamsWithHTTPClient creates a new CreateUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateUserParamsWithHTTPClient(client *http.Client) *CreateUserParams { + return &CreateUserParams{ + HTTPClient: client, + } +} + +/* CreateUserParams contains all the parameters to send to the API endpoint + for the create user operation. + + Typically these are written to a http.Request. +*/ +type CreateUserParams struct { + + // Body. + Body *models.CreateUserRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserParams) WithDefaults() *CreateUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create user params +func (o *CreateUserParams) WithTimeout(timeout time.Duration) *CreateUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create user params +func (o *CreateUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create user params +func (o *CreateUserParams) WithContext(ctx context.Context) *CreateUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create user params +func (o *CreateUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create user params +func (o *CreateUserParams) WithHTTPClient(client *http.Client) *CreateUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create user params +func (o *CreateUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create user params +func (o *CreateUserParams) WithBody(body *models.CreateUserRequest) *CreateUserParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create user params +func (o *CreateUserParams) SetBody(body *models.CreateUserRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create user params +func (o *CreateUserParams) WithAuthorization(authorization string) *CreateUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create user params +func (o *CreateUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create user params +func (o *CreateUserParams) WithBmpLanguage(bmpLanguage *string) *CreateUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create user params +func (o *CreateUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create user params +func (o *CreateUserParams) WithBmpUserID(bmpUserID *string) *CreateUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create user params +func (o *CreateUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create user params +func (o *CreateUserParams) WithTraceID(traceID string) *CreateUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create user params +func (o *CreateUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/create_user_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/create_user_responses.go new file mode 100644 index 0000000..de54876 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/create_user_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateUserReader is a Reader for the CreateUser structure. +type CreateUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateUserOK creates a CreateUserOK with default headers values +func NewCreateUserOK() *CreateUserOK { + return &CreateUserOK{} +} + +/* CreateUserOK describes a response with status code 200, with default header values. + +A CreateInstancesResult is an response struct that is used to describe create instance result. +*/ +type CreateUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserOKBody +} + +// IsSuccess returns true when this create user o k response has a 2xx status code +func (o *CreateUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create user o k response has a 3xx status code +func (o *CreateUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create user o k response has a 4xx status code +func (o *CreateUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create user o k response has a 5xx status code +func (o *CreateUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create user o k response a status code equal to that given +func (o *CreateUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateUserOK) Error() string { + return fmt.Sprintf("[POST /users][%d] createUserOK %+v", 200, o.Payload) +} + +func (o *CreateUserOK) String() string { + return fmt.Sprintf("[POST /users][%d] createUserOK %+v", 200, o.Payload) +} + +func (o *CreateUserOK) GetPayload() *CreateUserOKBody { + return o.Payload +} + +func (o *CreateUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateUserDefault creates a CreateUserDefault with default headers values +func NewCreateUserDefault(code int) *CreateUserDefault { + return &CreateUserDefault{ + _statusCode: code, + } +} + +/* CreateUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserDefaultBody +} + +// Code gets the status code for the create user default response +func (o *CreateUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create user default response has a 2xx status code +func (o *CreateUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create user default response has a 3xx status code +func (o *CreateUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create user default response has a 4xx status code +func (o *CreateUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create user default response has a 5xx status code +func (o *CreateUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create user default response a status code equal to that given +func (o *CreateUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateUserDefault) Error() string { + return fmt.Sprintf("[POST /users][%d] createUser default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserDefault) String() string { + return fmt.Sprintf("[POST /users][%d] createUser default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserDefault) GetPayload() *CreateUserDefaultBody { + return o.Payload +} + +func (o *CreateUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateUserDefaultBody create user default body +swagger:model CreateUserDefaultBody +*/ +type CreateUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create user default body +func (o *CreateUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user default body based on the context it is used +func (o *CreateUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateUserOKBody create user o k body +swagger:model CreateUserOKBody +*/ +type CreateUserOKBody struct { + + // result + Result *models.UserID `json:"result,omitempty"` +} + +// Validate validates this create user o k body +func (o *CreateUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user o k body based on the context it is used +func (o *CreateUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserOKBody) UnmarshalBinary(b []byte) error { + var res CreateUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/delete_user_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/delete_user_parameters.go new file mode 100644 index 0000000..3a1399c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/delete_user_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteUserParams creates a new DeleteUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteUserParams() *DeleteUserParams { + return &DeleteUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteUserParamsWithTimeout creates a new DeleteUserParams object +// with the ability to set a timeout on a request. +func NewDeleteUserParamsWithTimeout(timeout time.Duration) *DeleteUserParams { + return &DeleteUserParams{ + timeout: timeout, + } +} + +// NewDeleteUserParamsWithContext creates a new DeleteUserParams object +// with the ability to set a context for a request. +func NewDeleteUserParamsWithContext(ctx context.Context) *DeleteUserParams { + return &DeleteUserParams{ + Context: ctx, + } +} + +// NewDeleteUserParamsWithHTTPClient creates a new DeleteUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteUserParamsWithHTTPClient(client *http.Client) *DeleteUserParams { + return &DeleteUserParams{ + HTTPClient: client, + } +} + +/* DeleteUserParams contains all the parameters to send to the API endpoint + for the delete user operation. + + Typically these are written to a http.Request. +*/ +type DeleteUserParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + // UserID. + UserID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserParams) WithDefaults() *DeleteUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete user params +func (o *DeleteUserParams) WithTimeout(timeout time.Duration) *DeleteUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete user params +func (o *DeleteUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete user params +func (o *DeleteUserParams) WithContext(ctx context.Context) *DeleteUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete user params +func (o *DeleteUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete user params +func (o *DeleteUserParams) WithHTTPClient(client *http.Client) *DeleteUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete user params +func (o *DeleteUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete user params +func (o *DeleteUserParams) WithAuthorization(authorization string) *DeleteUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete user params +func (o *DeleteUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete user params +func (o *DeleteUserParams) WithBmpLanguage(bmpLanguage *string) *DeleteUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete user params +func (o *DeleteUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete user params +func (o *DeleteUserParams) WithBmpUserID(bmpUserID *string) *DeleteUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete user params +func (o *DeleteUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete user params +func (o *DeleteUserParams) WithTraceID(traceID string) *DeleteUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete user params +func (o *DeleteUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserID adds the userID to the delete user params +func (o *DeleteUserParams) WithUserID(userID string) *DeleteUserParams { + o.SetUserID(userID) + return o +} + +// SetUserID adds the userId to the delete user params +func (o *DeleteUserParams) SetUserID(userID string) { + o.UserID = userID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + // path param user_id + if err := r.SetPathParam("user_id", o.UserID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/delete_user_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/delete_user_responses.go new file mode 100644 index 0000000..f0d119d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/delete_user_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteUserReader is a Reader for the DeleteUser structure. +type DeleteUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteUserOK creates a DeleteUserOK with default headers values +func NewDeleteUserOK() *DeleteUserOK { + return &DeleteUserOK{} +} + +/* DeleteUserOK describes a response with status code 200, with default header values. + +A GetUserResult is an response struct that is used to describe getuser. +*/ +type DeleteUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserOKBody +} + +// IsSuccess returns true when this delete user o k response has a 2xx status code +func (o *DeleteUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete user o k response has a 3xx status code +func (o *DeleteUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete user o k response has a 4xx status code +func (o *DeleteUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete user o k response has a 5xx status code +func (o *DeleteUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete user o k response a status code equal to that given +func (o *DeleteUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteUserOK) Error() string { + return fmt.Sprintf("[DELETE /users/{user_id}][%d] deleteUserOK %+v", 200, o.Payload) +} + +func (o *DeleteUserOK) String() string { + return fmt.Sprintf("[DELETE /users/{user_id}][%d] deleteUserOK %+v", 200, o.Payload) +} + +func (o *DeleteUserOK) GetPayload() *DeleteUserOKBody { + return o.Payload +} + +func (o *DeleteUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteUserDefault creates a DeleteUserDefault with default headers values +func NewDeleteUserDefault(code int) *DeleteUserDefault { + return &DeleteUserDefault{ + _statusCode: code, + } +} + +/* DeleteUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserDefaultBody +} + +// Code gets the status code for the delete user default response +func (o *DeleteUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete user default response has a 2xx status code +func (o *DeleteUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete user default response has a 3xx status code +func (o *DeleteUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete user default response has a 4xx status code +func (o *DeleteUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete user default response has a 5xx status code +func (o *DeleteUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete user default response a status code equal to that given +func (o *DeleteUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteUserDefault) Error() string { + return fmt.Sprintf("[DELETE /users/{user_id}][%d] deleteUser default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserDefault) String() string { + return fmt.Sprintf("[DELETE /users/{user_id}][%d] deleteUser default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserDefault) GetPayload() *DeleteUserDefaultBody { + return o.Payload +} + +func (o *DeleteUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteUserDefaultBody delete user default body +swagger:model DeleteUserDefaultBody +*/ +type DeleteUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete user default body +func (o *DeleteUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user default body based on the context it is used +func (o *DeleteUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteUserOKBody delete user o k body +swagger:model DeleteUserOKBody +*/ +type DeleteUserOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete user o k body +func (o *DeleteUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user o k body based on the context it is used +func (o *DeleteUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserOKBody) UnmarshalBinary(b []byte) error { + var res DeleteUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_local_user_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_local_user_parameters.go new file mode 100644 index 0000000..737566e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_local_user_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeLocalUserParams creates a new DescribeLocalUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeLocalUserParams() *DescribeLocalUserParams { + return &DescribeLocalUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeLocalUserParamsWithTimeout creates a new DescribeLocalUserParams object +// with the ability to set a timeout on a request. +func NewDescribeLocalUserParamsWithTimeout(timeout time.Duration) *DescribeLocalUserParams { + return &DescribeLocalUserParams{ + timeout: timeout, + } +} + +// NewDescribeLocalUserParamsWithContext creates a new DescribeLocalUserParams object +// with the ability to set a context for a request. +func NewDescribeLocalUserParamsWithContext(ctx context.Context) *DescribeLocalUserParams { + return &DescribeLocalUserParams{ + Context: ctx, + } +} + +// NewDescribeLocalUserParamsWithHTTPClient creates a new DescribeLocalUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeLocalUserParamsWithHTTPClient(client *http.Client) *DescribeLocalUserParams { + return &DescribeLocalUserParams{ + HTTPClient: client, + } +} + +/* DescribeLocalUserParams contains all the parameters to send to the API endpoint + for the describe local user operation. + + Typically these are written to a http.Request. +*/ +type DescribeLocalUserParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe local user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLocalUserParams) WithDefaults() *DescribeLocalUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe local user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLocalUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe local user params +func (o *DescribeLocalUserParams) WithTimeout(timeout time.Duration) *DescribeLocalUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe local user params +func (o *DescribeLocalUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe local user params +func (o *DescribeLocalUserParams) WithContext(ctx context.Context) *DescribeLocalUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe local user params +func (o *DescribeLocalUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe local user params +func (o *DescribeLocalUserParams) WithHTTPClient(client *http.Client) *DescribeLocalUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe local user params +func (o *DescribeLocalUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe local user params +func (o *DescribeLocalUserParams) WithAuthorization(authorization string) *DescribeLocalUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe local user params +func (o *DescribeLocalUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe local user params +func (o *DescribeLocalUserParams) WithBmpLanguage(bmpLanguage *string) *DescribeLocalUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe local user params +func (o *DescribeLocalUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe local user params +func (o *DescribeLocalUserParams) WithBmpUserID(bmpUserID *string) *DescribeLocalUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe local user params +func (o *DescribeLocalUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe local user params +func (o *DescribeLocalUserParams) WithTraceID(traceID string) *DescribeLocalUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe local user params +func (o *DescribeLocalUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeLocalUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_local_user_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_local_user_responses.go new file mode 100644 index 0000000..8f3b50d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_local_user_responses.go @@ -0,0 +1,449 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeLocalUserReader is a Reader for the DescribeLocalUser structure. +type DescribeLocalUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeLocalUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeLocalUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeLocalUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeLocalUserOK creates a DescribeLocalUserOK with default headers values +func NewDescribeLocalUserOK() *DescribeLocalUserOK { + return &DescribeLocalUserOK{} +} + +/* DescribeLocalUserOK describes a response with status code 200, with default header values. + +A DescribeLocalUserResult is an response struct that is used to describe getuser. +*/ +type DescribeLocalUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLocalUserOKBody +} + +// IsSuccess returns true when this describe local user o k response has a 2xx status code +func (o *DescribeLocalUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe local user o k response has a 3xx status code +func (o *DescribeLocalUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe local user o k response has a 4xx status code +func (o *DescribeLocalUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe local user o k response has a 5xx status code +func (o *DescribeLocalUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe local user o k response a status code equal to that given +func (o *DescribeLocalUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeLocalUserOK) Error() string { + return fmt.Sprintf("[GET /local/users][%d] describeLocalUserOK %+v", 200, o.Payload) +} + +func (o *DescribeLocalUserOK) String() string { + return fmt.Sprintf("[GET /local/users][%d] describeLocalUserOK %+v", 200, o.Payload) +} + +func (o *DescribeLocalUserOK) GetPayload() *DescribeLocalUserOKBody { + return o.Payload +} + +func (o *DescribeLocalUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLocalUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeLocalUserDefault creates a DescribeLocalUserDefault with default headers values +func NewDescribeLocalUserDefault(code int) *DescribeLocalUserDefault { + return &DescribeLocalUserDefault{ + _statusCode: code, + } +} + +/* DescribeLocalUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeLocalUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLocalUserDefaultBody +} + +// Code gets the status code for the describe local user default response +func (o *DescribeLocalUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe local user default response has a 2xx status code +func (o *DescribeLocalUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe local user default response has a 3xx status code +func (o *DescribeLocalUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe local user default response has a 4xx status code +func (o *DescribeLocalUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe local user default response has a 5xx status code +func (o *DescribeLocalUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe local user default response a status code equal to that given +func (o *DescribeLocalUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeLocalUserDefault) Error() string { + return fmt.Sprintf("[GET /local/users][%d] describeLocalUser default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLocalUserDefault) String() string { + return fmt.Sprintf("[GET /local/users][%d] describeLocalUser default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLocalUserDefault) GetPayload() *DescribeLocalUserDefaultBody { + return o.Payload +} + +func (o *DescribeLocalUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLocalUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeLocalUserDefaultBody describe local user default body +swagger:model DescribeLocalUserDefaultBody +*/ +type DescribeLocalUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe local user default body +func (o *DescribeLocalUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLocalUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeLocalUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeLocalUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeLocalUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe local user default body based on the context it is used +func (o *DescribeLocalUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLocalUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLocalUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLocalUserDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeLocalUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeLocalUserOKBody describe local user o k body +swagger:model DescribeLocalUserOKBody +*/ +type DescribeLocalUserOKBody struct { + + // error + Error *models.ErrorResponse `json:"error,omitempty"` + + // result + Result *models.UserInfo `json:"result,omitempty"` +} + +// Validate validates this describe local user o k body +func (o *DescribeLocalUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLocalUserOKBody) validateError(formats strfmt.Registry) error { + if swag.IsZero(o.Error) { // not required + return nil + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUserOK" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUserOK" + "." + "error") + } + return err + } + } + + return nil +} + +func (o *DescribeLocalUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe local user o k body based on the context it is used +func (o *DescribeLocalUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLocalUserOKBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUserOK" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUserOK" + "." + "error") + } + return err + } + } + + return nil +} + +func (o *DescribeLocalUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLocalUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLocalUserOKBody) UnmarshalBinary(b []byte) error { + var res DescribeLocalUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_by_name_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_by_name_parameters.go new file mode 100644 index 0000000..488d83c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_by_name_parameters.go @@ -0,0 +1,248 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeUserByNameParams creates a new DescribeUserByNameParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserByNameParams() *DescribeUserByNameParams { + return &DescribeUserByNameParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserByNameParamsWithTimeout creates a new DescribeUserByNameParams object +// with the ability to set a timeout on a request. +func NewDescribeUserByNameParamsWithTimeout(timeout time.Duration) *DescribeUserByNameParams { + return &DescribeUserByNameParams{ + timeout: timeout, + } +} + +// NewDescribeUserByNameParamsWithContext creates a new DescribeUserByNameParams object +// with the ability to set a context for a request. +func NewDescribeUserByNameParamsWithContext(ctx context.Context) *DescribeUserByNameParams { + return &DescribeUserByNameParams{ + Context: ctx, + } +} + +// NewDescribeUserByNameParamsWithHTTPClient creates a new DescribeUserByNameParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserByNameParamsWithHTTPClient(client *http.Client) *DescribeUserByNameParams { + return &DescribeUserByNameParams{ + HTTPClient: client, + } +} + +/* DescribeUserByNameParams contains all the parameters to send to the API endpoint + for the describe user by name operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserByNameParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserName. + + 用户名,唯一 + */ + UserName string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user by name params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserByNameParams) WithDefaults() *DescribeUserByNameParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user by name params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserByNameParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user by name params +func (o *DescribeUserByNameParams) WithTimeout(timeout time.Duration) *DescribeUserByNameParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user by name params +func (o *DescribeUserByNameParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user by name params +func (o *DescribeUserByNameParams) WithContext(ctx context.Context) *DescribeUserByNameParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user by name params +func (o *DescribeUserByNameParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user by name params +func (o *DescribeUserByNameParams) WithHTTPClient(client *http.Client) *DescribeUserByNameParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user by name params +func (o *DescribeUserByNameParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user by name params +func (o *DescribeUserByNameParams) WithAuthorization(authorization string) *DescribeUserByNameParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user by name params +func (o *DescribeUserByNameParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user by name params +func (o *DescribeUserByNameParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserByNameParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user by name params +func (o *DescribeUserByNameParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user by name params +func (o *DescribeUserByNameParams) WithBmpUserID(bmpUserID *string) *DescribeUserByNameParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user by name params +func (o *DescribeUserByNameParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe user by name params +func (o *DescribeUserByNameParams) WithTraceID(traceID string) *DescribeUserByNameParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user by name params +func (o *DescribeUserByNameParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserName adds the userName to the describe user by name params +func (o *DescribeUserByNameParams) WithUserName(userName string) *DescribeUserByNameParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe user by name params +func (o *DescribeUserByNameParams) SetUserName(userName string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserByNameParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + // query param userName + qrUserName := o.UserName + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_by_name_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_by_name_responses.go new file mode 100644 index 0000000..73ba314 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_by_name_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserByNameReader is a Reader for the DescribeUserByName structure. +type DescribeUserByNameReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserByNameReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserByNameOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserByNameDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserByNameOK creates a DescribeUserByNameOK with default headers values +func NewDescribeUserByNameOK() *DescribeUserByNameOK { + return &DescribeUserByNameOK{} +} + +/* DescribeUserByNameOK describes a response with status code 200, with default header values. + +A GetUserByNameResult is an response struct that is used to describe user. +*/ +type DescribeUserByNameOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserByNameOKBody +} + +// IsSuccess returns true when this describe user by name o k response has a 2xx status code +func (o *DescribeUserByNameOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user by name o k response has a 3xx status code +func (o *DescribeUserByNameOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user by name o k response has a 4xx status code +func (o *DescribeUserByNameOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user by name o k response has a 5xx status code +func (o *DescribeUserByNameOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user by name o k response a status code equal to that given +func (o *DescribeUserByNameOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserByNameOK) Error() string { + return fmt.Sprintf("[GET /users/getUserByName][%d] describeUserByNameOK %+v", 200, o.Payload) +} + +func (o *DescribeUserByNameOK) String() string { + return fmt.Sprintf("[GET /users/getUserByName][%d] describeUserByNameOK %+v", 200, o.Payload) +} + +func (o *DescribeUserByNameOK) GetPayload() *DescribeUserByNameOKBody { + return o.Payload +} + +func (o *DescribeUserByNameOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserByNameOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserByNameDefault creates a DescribeUserByNameDefault with default headers values +func NewDescribeUserByNameDefault(code int) *DescribeUserByNameDefault { + return &DescribeUserByNameDefault{ + _statusCode: code, + } +} + +/* DescribeUserByNameDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserByNameDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserByNameDefaultBody +} + +// Code gets the status code for the describe user by name default response +func (o *DescribeUserByNameDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user by name default response has a 2xx status code +func (o *DescribeUserByNameDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user by name default response has a 3xx status code +func (o *DescribeUserByNameDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user by name default response has a 4xx status code +func (o *DescribeUserByNameDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user by name default response has a 5xx status code +func (o *DescribeUserByNameDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user by name default response a status code equal to that given +func (o *DescribeUserByNameDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserByNameDefault) Error() string { + return fmt.Sprintf("[GET /users/getUserByName][%d] describeUserByName default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserByNameDefault) String() string { + return fmt.Sprintf("[GET /users/getUserByName][%d] describeUserByName default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserByNameDefault) GetPayload() *DescribeUserByNameDefaultBody { + return o.Payload +} + +func (o *DescribeUserByNameDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserByNameDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserByNameDefaultBody describe user by name default body +swagger:model DescribeUserByNameDefaultBody +*/ +type DescribeUserByNameDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user by name default body +func (o *DescribeUserByNameDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserByNameDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserByName default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserByNameDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserByName default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserByName default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserByName default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user by name default body based on the context it is used +func (o *DescribeUserByNameDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserByNameDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserByName default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserByName default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserByNameDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserByNameDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserByNameDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserByNameOKBody describe user by name o k body +swagger:model DescribeUserByNameOKBody +*/ +type DescribeUserByNameOKBody struct { + + // result + Result *models.UserInfo `json:"result,omitempty"` +} + +// Validate validates this describe user by name o k body +func (o *DescribeUserByNameOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserByNameOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserByNameOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserByNameOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user by name o k body based on the context it is used +func (o *DescribeUserByNameOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserByNameOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserByNameOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserByNameOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserByNameOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserByNameOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserByNameOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_parameters.go new file mode 100644 index 0000000..8b874fd --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeUserParams creates a new DescribeUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserParams() *DescribeUserParams { + return &DescribeUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserParamsWithTimeout creates a new DescribeUserParams object +// with the ability to set a timeout on a request. +func NewDescribeUserParamsWithTimeout(timeout time.Duration) *DescribeUserParams { + return &DescribeUserParams{ + timeout: timeout, + } +} + +// NewDescribeUserParamsWithContext creates a new DescribeUserParams object +// with the ability to set a context for a request. +func NewDescribeUserParamsWithContext(ctx context.Context) *DescribeUserParams { + return &DescribeUserParams{ + Context: ctx, + } +} + +// NewDescribeUserParamsWithHTTPClient creates a new DescribeUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserParamsWithHTTPClient(client *http.Client) *DescribeUserParams { + return &DescribeUserParams{ + HTTPClient: client, + } +} + +/* DescribeUserParams contains all the parameters to send to the API endpoint + for the describe user operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + // UserID. + UserID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserParams) WithDefaults() *DescribeUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user params +func (o *DescribeUserParams) WithTimeout(timeout time.Duration) *DescribeUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user params +func (o *DescribeUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user params +func (o *DescribeUserParams) WithContext(ctx context.Context) *DescribeUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user params +func (o *DescribeUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user params +func (o *DescribeUserParams) WithHTTPClient(client *http.Client) *DescribeUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user params +func (o *DescribeUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user params +func (o *DescribeUserParams) WithAuthorization(authorization string) *DescribeUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user params +func (o *DescribeUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user params +func (o *DescribeUserParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user params +func (o *DescribeUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user params +func (o *DescribeUserParams) WithBmpUserID(bmpUserID *string) *DescribeUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user params +func (o *DescribeUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe user params +func (o *DescribeUserParams) WithTraceID(traceID string) *DescribeUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user params +func (o *DescribeUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserID adds the userID to the describe user params +func (o *DescribeUserParams) WithUserID(userID string) *DescribeUserParams { + o.SetUserID(userID) + return o +} + +// SetUserID adds the userId to the describe user params +func (o *DescribeUserParams) SetUserID(userID string) { + o.UserID = userID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + // path param user_id + if err := r.SetPathParam("user_id", o.UserID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_responses.go new file mode 100644 index 0000000..f39a4d4 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_responses.go @@ -0,0 +1,449 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserReader is a Reader for the DescribeUser structure. +type DescribeUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserOK creates a DescribeUserOK with default headers values +func NewDescribeUserOK() *DescribeUserOK { + return &DescribeUserOK{} +} + +/* DescribeUserOK describes a response with status code 200, with default header values. + +DescribeUserOK describe user o k +*/ +type DescribeUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserOKBody +} + +// IsSuccess returns true when this describe user o k response has a 2xx status code +func (o *DescribeUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user o k response has a 3xx status code +func (o *DescribeUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user o k response has a 4xx status code +func (o *DescribeUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user o k response has a 5xx status code +func (o *DescribeUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user o k response a status code equal to that given +func (o *DescribeUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserOK) Error() string { + return fmt.Sprintf("[GET /users/{user_id}][%d] describeUserOK %+v", 200, o.Payload) +} + +func (o *DescribeUserOK) String() string { + return fmt.Sprintf("[GET /users/{user_id}][%d] describeUserOK %+v", 200, o.Payload) +} + +func (o *DescribeUserOK) GetPayload() *DescribeUserOKBody { + return o.Payload +} + +func (o *DescribeUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserDefault creates a DescribeUserDefault with default headers values +func NewDescribeUserDefault(code int) *DescribeUserDefault { + return &DescribeUserDefault{ + _statusCode: code, + } +} + +/* DescribeUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserDefaultBody +} + +// Code gets the status code for the describe user default response +func (o *DescribeUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user default response has a 2xx status code +func (o *DescribeUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user default response has a 3xx status code +func (o *DescribeUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user default response has a 4xx status code +func (o *DescribeUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user default response has a 5xx status code +func (o *DescribeUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user default response a status code equal to that given +func (o *DescribeUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserDefault) Error() string { + return fmt.Sprintf("[GET /users/{user_id}][%d] describeUser default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserDefault) String() string { + return fmt.Sprintf("[GET /users/{user_id}][%d] describeUser default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserDefault) GetPayload() *DescribeUserDefaultBody { + return o.Payload +} + +func (o *DescribeUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserDefaultBody describe user default body +swagger:model DescribeUserDefaultBody +*/ +type DescribeUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user default body +func (o *DescribeUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user default body based on the context it is used +func (o *DescribeUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserOKBody describe user o k body +swagger:model DescribeUserOKBody +*/ +type DescribeUserOKBody struct { + + // error + Error *models.ErrorResponse `json:"error,omitempty"` + + // result + Result *models.UserInfo `json:"result,omitempty"` +} + +// Validate validates this describe user o k body +func (o *DescribeUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserOKBody) validateError(formats strfmt.Registry) error { + if swag.IsZero(o.Error) { // not required + return nil + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserOK" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserOK" + "." + "error") + } + return err + } + } + + return nil +} + +func (o *DescribeUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user o k body based on the context it is used +func (o *DescribeUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserOKBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserOK" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserOK" + "." + "error") + } + return err + } + } + + return nil +} + +func (o *DescribeUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_users_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_users_parameters.go new file mode 100644 index 0000000..6bc90a4 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_users_parameters.go @@ -0,0 +1,430 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeUsersParams creates a new DescribeUsersParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUsersParams() *DescribeUsersParams { + return &DescribeUsersParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUsersParamsWithTimeout creates a new DescribeUsersParams object +// with the ability to set a timeout on a request. +func NewDescribeUsersParamsWithTimeout(timeout time.Duration) *DescribeUsersParams { + return &DescribeUsersParams{ + timeout: timeout, + } +} + +// NewDescribeUsersParamsWithContext creates a new DescribeUsersParams object +// with the ability to set a context for a request. +func NewDescribeUsersParamsWithContext(ctx context.Context) *DescribeUsersParams { + return &DescribeUsersParams{ + Context: ctx, + } +} + +// NewDescribeUsersParamsWithHTTPClient creates a new DescribeUsersParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUsersParamsWithHTTPClient(client *http.Client) *DescribeUsersParams { + return &DescribeUsersParams{ + HTTPClient: client, + } +} + +/* DescribeUsersParams contains all the parameters to send to the API endpoint + for the describe users operation. + + Typically these are written to a http.Request. +*/ +type DescribeUsersParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DefaultProjectID. + + 项目uuid + */ + DefaultProjectID *string + + /* IsAll. + + 是否显示全部, isAll=1表示全部 + */ + IsAll *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* RoleID. + + 角色uuid + */ + RoleID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserName. + + 用户名 + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe users params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUsersParams) WithDefaults() *DescribeUsersParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe users params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUsersParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe users params +func (o *DescribeUsersParams) WithTimeout(timeout time.Duration) *DescribeUsersParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe users params +func (o *DescribeUsersParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe users params +func (o *DescribeUsersParams) WithContext(ctx context.Context) *DescribeUsersParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe users params +func (o *DescribeUsersParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe users params +func (o *DescribeUsersParams) WithHTTPClient(client *http.Client) *DescribeUsersParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe users params +func (o *DescribeUsersParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe users params +func (o *DescribeUsersParams) WithAuthorization(authorization string) *DescribeUsersParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe users params +func (o *DescribeUsersParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe users params +func (o *DescribeUsersParams) WithBmpLanguage(bmpLanguage *string) *DescribeUsersParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe users params +func (o *DescribeUsersParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe users params +func (o *DescribeUsersParams) WithBmpUserID(bmpUserID *string) *DescribeUsersParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe users params +func (o *DescribeUsersParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDefaultProjectID adds the defaultProjectID to the describe users params +func (o *DescribeUsersParams) WithDefaultProjectID(defaultProjectID *string) *DescribeUsersParams { + o.SetDefaultProjectID(defaultProjectID) + return o +} + +// SetDefaultProjectID adds the defaultProjectId to the describe users params +func (o *DescribeUsersParams) SetDefaultProjectID(defaultProjectID *string) { + o.DefaultProjectID = defaultProjectID +} + +// WithIsAll adds the isAll to the describe users params +func (o *DescribeUsersParams) WithIsAll(isAll *string) *DescribeUsersParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe users params +func (o *DescribeUsersParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithPageNumber adds the pageNumber to the describe users params +func (o *DescribeUsersParams) WithPageNumber(pageNumber *int64) *DescribeUsersParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe users params +func (o *DescribeUsersParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe users params +func (o *DescribeUsersParams) WithPageSize(pageSize *int64) *DescribeUsersParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe users params +func (o *DescribeUsersParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithRoleID adds the roleID to the describe users params +func (o *DescribeUsersParams) WithRoleID(roleID *string) *DescribeUsersParams { + o.SetRoleID(roleID) + return o +} + +// SetRoleID adds the roleId to the describe users params +func (o *DescribeUsersParams) SetRoleID(roleID *string) { + o.RoleID = roleID +} + +// WithTraceID adds the traceID to the describe users params +func (o *DescribeUsersParams) WithTraceID(traceID string) *DescribeUsersParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe users params +func (o *DescribeUsersParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserName adds the userName to the describe users params +func (o *DescribeUsersParams) WithUserName(userName *string) *DescribeUsersParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe users params +func (o *DescribeUsersParams) SetUserName(userName *string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUsersParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DefaultProjectID != nil { + + // query param defaultProjectId + var qrDefaultProjectID string + + if o.DefaultProjectID != nil { + qrDefaultProjectID = *o.DefaultProjectID + } + qDefaultProjectID := qrDefaultProjectID + if qDefaultProjectID != "" { + + if err := r.SetQueryParam("defaultProjectId", qDefaultProjectID); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.RoleID != nil { + + // query param roleId + var qrRoleID string + + if o.RoleID != nil { + qrRoleID = *o.RoleID + } + qRoleID := qrRoleID + if qRoleID != "" { + + if err := r.SetQueryParam("roleId", qRoleID); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserName != nil { + + // query param userName + var qrUserName string + + if o.UserName != nil { + qrUserName = *o.UserName + } + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_users_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_users_responses.go new file mode 100644 index 0000000..61001ee --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/describe_users_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUsersReader is a Reader for the DescribeUsers structure. +type DescribeUsersReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUsersReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUsersOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUsersDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUsersOK creates a DescribeUsersOK with default headers values +func NewDescribeUsersOK() *DescribeUsersOK { + return &DescribeUsersOK{} +} + +/* DescribeUsersOK describes a response with status code 200, with default header values. + +DescribeUsersOK describe users o k +*/ +type DescribeUsersOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUsersOKBody +} + +// IsSuccess returns true when this describe users o k response has a 2xx status code +func (o *DescribeUsersOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe users o k response has a 3xx status code +func (o *DescribeUsersOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe users o k response has a 4xx status code +func (o *DescribeUsersOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe users o k response has a 5xx status code +func (o *DescribeUsersOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe users o k response a status code equal to that given +func (o *DescribeUsersOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUsersOK) Error() string { + return fmt.Sprintf("[GET /users][%d] describeUsersOK %+v", 200, o.Payload) +} + +func (o *DescribeUsersOK) String() string { + return fmt.Sprintf("[GET /users][%d] describeUsersOK %+v", 200, o.Payload) +} + +func (o *DescribeUsersOK) GetPayload() *DescribeUsersOKBody { + return o.Payload +} + +func (o *DescribeUsersOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUsersOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUsersDefault creates a DescribeUsersDefault with default headers values +func NewDescribeUsersDefault(code int) *DescribeUsersDefault { + return &DescribeUsersDefault{ + _statusCode: code, + } +} + +/* DescribeUsersDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUsersDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUsersDefaultBody +} + +// Code gets the status code for the describe users default response +func (o *DescribeUsersDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe users default response has a 2xx status code +func (o *DescribeUsersDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe users default response has a 3xx status code +func (o *DescribeUsersDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe users default response has a 4xx status code +func (o *DescribeUsersDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe users default response has a 5xx status code +func (o *DescribeUsersDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe users default response a status code equal to that given +func (o *DescribeUsersDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUsersDefault) Error() string { + return fmt.Sprintf("[GET /users][%d] describeUsers default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUsersDefault) String() string { + return fmt.Sprintf("[GET /users][%d] describeUsers default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUsersDefault) GetPayload() *DescribeUsersDefaultBody { + return o.Payload +} + +func (o *DescribeUsersDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUsersDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUsersDefaultBody describe users default body +swagger:model DescribeUsersDefaultBody +*/ +type DescribeUsersDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe users default body +func (o *DescribeUsersDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUsersDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUsers default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUsersDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUsers default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUsers default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUsers default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe users default body based on the context it is used +func (o *DescribeUsersDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUsersDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUsers default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUsers default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUsersDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUsersDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUsersDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUsersOKBody describe users o k body +swagger:model DescribeUsersOKBody +*/ +type DescribeUsersOKBody struct { + + // result + Result *models.UserList `json:"result,omitempty"` +} + +// Validate validates this describe users o k body +func (o *DescribeUsersOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUsersOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUsersOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUsersOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe users o k body based on the context it is used +func (o *DescribeUsersOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUsersOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUsersOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUsersOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUsersOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUsersOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUsersOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_parameters.go new file mode 100644 index 0000000..4ec0580 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyLocalUserParams creates a new ModifyLocalUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyLocalUserParams() *ModifyLocalUserParams { + return &ModifyLocalUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyLocalUserParamsWithTimeout creates a new ModifyLocalUserParams object +// with the ability to set a timeout on a request. +func NewModifyLocalUserParamsWithTimeout(timeout time.Duration) *ModifyLocalUserParams { + return &ModifyLocalUserParams{ + timeout: timeout, + } +} + +// NewModifyLocalUserParamsWithContext creates a new ModifyLocalUserParams object +// with the ability to set a context for a request. +func NewModifyLocalUserParamsWithContext(ctx context.Context) *ModifyLocalUserParams { + return &ModifyLocalUserParams{ + Context: ctx, + } +} + +// NewModifyLocalUserParamsWithHTTPClient creates a new ModifyLocalUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyLocalUserParamsWithHTTPClient(client *http.Client) *ModifyLocalUserParams { + return &ModifyLocalUserParams{ + HTTPClient: client, + } +} + +/* ModifyLocalUserParams contains all the parameters to send to the API endpoint + for the modify local user operation. + + Typically these are written to a http.Request. +*/ +type ModifyLocalUserParams struct { + + // Body. + Body *models.ModifyLocalUserRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify local user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyLocalUserParams) WithDefaults() *ModifyLocalUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify local user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyLocalUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify local user params +func (o *ModifyLocalUserParams) WithTimeout(timeout time.Duration) *ModifyLocalUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify local user params +func (o *ModifyLocalUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify local user params +func (o *ModifyLocalUserParams) WithContext(ctx context.Context) *ModifyLocalUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify local user params +func (o *ModifyLocalUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify local user params +func (o *ModifyLocalUserParams) WithHTTPClient(client *http.Client) *ModifyLocalUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify local user params +func (o *ModifyLocalUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify local user params +func (o *ModifyLocalUserParams) WithBody(body *models.ModifyLocalUserRequest) *ModifyLocalUserParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify local user params +func (o *ModifyLocalUserParams) SetBody(body *models.ModifyLocalUserRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify local user params +func (o *ModifyLocalUserParams) WithAuthorization(authorization string) *ModifyLocalUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify local user params +func (o *ModifyLocalUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify local user params +func (o *ModifyLocalUserParams) WithBmpLanguage(bmpLanguage *string) *ModifyLocalUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify local user params +func (o *ModifyLocalUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify local user params +func (o *ModifyLocalUserParams) WithBmpUserID(bmpUserID *string) *ModifyLocalUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify local user params +func (o *ModifyLocalUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the modify local user params +func (o *ModifyLocalUserParams) WithTraceID(traceID string) *ModifyLocalUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify local user params +func (o *ModifyLocalUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyLocalUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_password_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_password_parameters.go new file mode 100644 index 0000000..79c4b96 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_password_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyLocalUserPasswordParams creates a new ModifyLocalUserPasswordParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyLocalUserPasswordParams() *ModifyLocalUserPasswordParams { + return &ModifyLocalUserPasswordParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyLocalUserPasswordParamsWithTimeout creates a new ModifyLocalUserPasswordParams object +// with the ability to set a timeout on a request. +func NewModifyLocalUserPasswordParamsWithTimeout(timeout time.Duration) *ModifyLocalUserPasswordParams { + return &ModifyLocalUserPasswordParams{ + timeout: timeout, + } +} + +// NewModifyLocalUserPasswordParamsWithContext creates a new ModifyLocalUserPasswordParams object +// with the ability to set a context for a request. +func NewModifyLocalUserPasswordParamsWithContext(ctx context.Context) *ModifyLocalUserPasswordParams { + return &ModifyLocalUserPasswordParams{ + Context: ctx, + } +} + +// NewModifyLocalUserPasswordParamsWithHTTPClient creates a new ModifyLocalUserPasswordParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyLocalUserPasswordParamsWithHTTPClient(client *http.Client) *ModifyLocalUserPasswordParams { + return &ModifyLocalUserPasswordParams{ + HTTPClient: client, + } +} + +/* ModifyLocalUserPasswordParams contains all the parameters to send to the API endpoint + for the modify local user password operation. + + Typically these are written to a http.Request. +*/ +type ModifyLocalUserPasswordParams struct { + + // Body. + Body *models.ModifyUserPasswordRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify local user password params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyLocalUserPasswordParams) WithDefaults() *ModifyLocalUserPasswordParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify local user password params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyLocalUserPasswordParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithTimeout(timeout time.Duration) *ModifyLocalUserPasswordParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithContext(ctx context.Context) *ModifyLocalUserPasswordParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithHTTPClient(client *http.Client) *ModifyLocalUserPasswordParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithBody(body *models.ModifyUserPasswordRequest) *ModifyLocalUserPasswordParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetBody(body *models.ModifyUserPasswordRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithAuthorization(authorization string) *ModifyLocalUserPasswordParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithBmpLanguage(bmpLanguage *string) *ModifyLocalUserPasswordParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithBmpUserID(bmpUserID *string) *ModifyLocalUserPasswordParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithTraceID(traceID string) *ModifyLocalUserPasswordParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyLocalUserPasswordParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_password_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_password_responses.go new file mode 100644 index 0000000..17acafd --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_password_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyLocalUserPasswordReader is a Reader for the ModifyLocalUserPassword structure. +type ModifyLocalUserPasswordReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyLocalUserPasswordReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyLocalUserPasswordOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyLocalUserPasswordDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyLocalUserPasswordOK creates a ModifyLocalUserPasswordOK with default headers values +func NewModifyLocalUserPasswordOK() *ModifyLocalUserPasswordOK { + return &ModifyLocalUserPasswordOK{} +} + +/* ModifyLocalUserPasswordOK describes a response with status code 200, with default header values. + +A ModifyLocalUserPasswordResult is an response struct that is used to describe getuser. +*/ +type ModifyLocalUserPasswordOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyLocalUserPasswordOKBody +} + +// IsSuccess returns true when this modify local user password o k response has a 2xx status code +func (o *ModifyLocalUserPasswordOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify local user password o k response has a 3xx status code +func (o *ModifyLocalUserPasswordOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify local user password o k response has a 4xx status code +func (o *ModifyLocalUserPasswordOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify local user password o k response has a 5xx status code +func (o *ModifyLocalUserPasswordOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify local user password o k response a status code equal to that given +func (o *ModifyLocalUserPasswordOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyLocalUserPasswordOK) Error() string { + return fmt.Sprintf("[PUT /local/users/password][%d] modifyLocalUserPasswordOK %+v", 200, o.Payload) +} + +func (o *ModifyLocalUserPasswordOK) String() string { + return fmt.Sprintf("[PUT /local/users/password][%d] modifyLocalUserPasswordOK %+v", 200, o.Payload) +} + +func (o *ModifyLocalUserPasswordOK) GetPayload() *ModifyLocalUserPasswordOKBody { + return o.Payload +} + +func (o *ModifyLocalUserPasswordOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyLocalUserPasswordOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyLocalUserPasswordDefault creates a ModifyLocalUserPasswordDefault with default headers values +func NewModifyLocalUserPasswordDefault(code int) *ModifyLocalUserPasswordDefault { + return &ModifyLocalUserPasswordDefault{ + _statusCode: code, + } +} + +/* ModifyLocalUserPasswordDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyLocalUserPasswordDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyLocalUserPasswordDefaultBody +} + +// Code gets the status code for the modify local user password default response +func (o *ModifyLocalUserPasswordDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify local user password default response has a 2xx status code +func (o *ModifyLocalUserPasswordDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify local user password default response has a 3xx status code +func (o *ModifyLocalUserPasswordDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify local user password default response has a 4xx status code +func (o *ModifyLocalUserPasswordDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify local user password default response has a 5xx status code +func (o *ModifyLocalUserPasswordDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify local user password default response a status code equal to that given +func (o *ModifyLocalUserPasswordDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyLocalUserPasswordDefault) Error() string { + return fmt.Sprintf("[PUT /local/users/password][%d] modifyLocalUserPassword default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyLocalUserPasswordDefault) String() string { + return fmt.Sprintf("[PUT /local/users/password][%d] modifyLocalUserPassword default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyLocalUserPasswordDefault) GetPayload() *ModifyLocalUserPasswordDefaultBody { + return o.Payload +} + +func (o *ModifyLocalUserPasswordDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyLocalUserPasswordDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyLocalUserPasswordDefaultBody modify local user password default body +swagger:model ModifyLocalUserPasswordDefaultBody +*/ +type ModifyLocalUserPasswordDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify local user password default body +func (o *ModifyLocalUserPasswordDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserPasswordDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyLocalUserPassword default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyLocalUserPasswordDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyLocalUserPassword default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserPassword default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserPassword default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify local user password default body based on the context it is used +func (o *ModifyLocalUserPasswordDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserPasswordDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserPassword default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserPassword default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyLocalUserPasswordDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyLocalUserPasswordDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyLocalUserPasswordDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyLocalUserPasswordOKBody modify local user password o k body +swagger:model ModifyLocalUserPasswordOKBody +*/ +type ModifyLocalUserPasswordOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify local user password o k body +func (o *ModifyLocalUserPasswordOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserPasswordOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserPasswordOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserPasswordOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify local user password o k body based on the context it is used +func (o *ModifyLocalUserPasswordOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserPasswordOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserPasswordOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserPasswordOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyLocalUserPasswordOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyLocalUserPasswordOKBody) UnmarshalBinary(b []byte) error { + var res ModifyLocalUserPasswordOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_responses.go new file mode 100644 index 0000000..912ea09 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyLocalUserReader is a Reader for the ModifyLocalUser structure. +type ModifyLocalUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyLocalUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyLocalUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyLocalUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyLocalUserOK creates a ModifyLocalUserOK with default headers values +func NewModifyLocalUserOK() *ModifyLocalUserOK { + return &ModifyLocalUserOK{} +} + +/* ModifyLocalUserOK describes a response with status code 200, with default header values. + +A ModifyLocalUserResult is an response struct that is used to describe getuser. +*/ +type ModifyLocalUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyLocalUserOKBody +} + +// IsSuccess returns true when this modify local user o k response has a 2xx status code +func (o *ModifyLocalUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify local user o k response has a 3xx status code +func (o *ModifyLocalUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify local user o k response has a 4xx status code +func (o *ModifyLocalUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify local user o k response has a 5xx status code +func (o *ModifyLocalUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify local user o k response a status code equal to that given +func (o *ModifyLocalUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyLocalUserOK) Error() string { + return fmt.Sprintf("[PUT /local/users][%d] modifyLocalUserOK %+v", 200, o.Payload) +} + +func (o *ModifyLocalUserOK) String() string { + return fmt.Sprintf("[PUT /local/users][%d] modifyLocalUserOK %+v", 200, o.Payload) +} + +func (o *ModifyLocalUserOK) GetPayload() *ModifyLocalUserOKBody { + return o.Payload +} + +func (o *ModifyLocalUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyLocalUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyLocalUserDefault creates a ModifyLocalUserDefault with default headers values +func NewModifyLocalUserDefault(code int) *ModifyLocalUserDefault { + return &ModifyLocalUserDefault{ + _statusCode: code, + } +} + +/* ModifyLocalUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyLocalUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyLocalUserDefaultBody +} + +// Code gets the status code for the modify local user default response +func (o *ModifyLocalUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify local user default response has a 2xx status code +func (o *ModifyLocalUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify local user default response has a 3xx status code +func (o *ModifyLocalUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify local user default response has a 4xx status code +func (o *ModifyLocalUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify local user default response has a 5xx status code +func (o *ModifyLocalUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify local user default response a status code equal to that given +func (o *ModifyLocalUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyLocalUserDefault) Error() string { + return fmt.Sprintf("[PUT /local/users][%d] modifyLocalUser default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyLocalUserDefault) String() string { + return fmt.Sprintf("[PUT /local/users][%d] modifyLocalUser default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyLocalUserDefault) GetPayload() *ModifyLocalUserDefaultBody { + return o.Payload +} + +func (o *ModifyLocalUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyLocalUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyLocalUserDefaultBody modify local user default body +swagger:model ModifyLocalUserDefaultBody +*/ +type ModifyLocalUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify local user default body +func (o *ModifyLocalUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyLocalUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyLocalUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyLocalUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify local user default body based on the context it is used +func (o *ModifyLocalUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyLocalUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyLocalUserDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyLocalUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyLocalUserOKBody modify local user o k body +swagger:model ModifyLocalUserOKBody +*/ +type ModifyLocalUserOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify local user o k body +func (o *ModifyLocalUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify local user o k body based on the context it is used +func (o *ModifyLocalUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyLocalUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyLocalUserOKBody) UnmarshalBinary(b []byte) error { + var res ModifyLocalUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_user_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_user_parameters.go new file mode 100644 index 0000000..4b888d3 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_user_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyUserParams creates a new ModifyUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyUserParams() *ModifyUserParams { + return &ModifyUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyUserParamsWithTimeout creates a new ModifyUserParams object +// with the ability to set a timeout on a request. +func NewModifyUserParamsWithTimeout(timeout time.Duration) *ModifyUserParams { + return &ModifyUserParams{ + timeout: timeout, + } +} + +// NewModifyUserParamsWithContext creates a new ModifyUserParams object +// with the ability to set a context for a request. +func NewModifyUserParamsWithContext(ctx context.Context) *ModifyUserParams { + return &ModifyUserParams{ + Context: ctx, + } +} + +// NewModifyUserParamsWithHTTPClient creates a new ModifyUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyUserParamsWithHTTPClient(client *http.Client) *ModifyUserParams { + return &ModifyUserParams{ + HTTPClient: client, + } +} + +/* ModifyUserParams contains all the parameters to send to the API endpoint + for the modify user operation. + + Typically these are written to a http.Request. +*/ +type ModifyUserParams struct { + + // Body. + Body *models.ModifyUserRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + // UserID. + UserID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserParams) WithDefaults() *ModifyUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify user params +func (o *ModifyUserParams) WithTimeout(timeout time.Duration) *ModifyUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify user params +func (o *ModifyUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify user params +func (o *ModifyUserParams) WithContext(ctx context.Context) *ModifyUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify user params +func (o *ModifyUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify user params +func (o *ModifyUserParams) WithHTTPClient(client *http.Client) *ModifyUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify user params +func (o *ModifyUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify user params +func (o *ModifyUserParams) WithBody(body *models.ModifyUserRequest) *ModifyUserParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify user params +func (o *ModifyUserParams) SetBody(body *models.ModifyUserRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify user params +func (o *ModifyUserParams) WithAuthorization(authorization string) *ModifyUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify user params +func (o *ModifyUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify user params +func (o *ModifyUserParams) WithBmpLanguage(bmpLanguage *string) *ModifyUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify user params +func (o *ModifyUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify user params +func (o *ModifyUserParams) WithBmpUserID(bmpUserID *string) *ModifyUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify user params +func (o *ModifyUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the modify user params +func (o *ModifyUserParams) WithTraceID(traceID string) *ModifyUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify user params +func (o *ModifyUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserID adds the userID to the modify user params +func (o *ModifyUserParams) WithUserID(userID string) *ModifyUserParams { + o.SetUserID(userID) + return o +} + +// SetUserID adds the userId to the modify user params +func (o *ModifyUserParams) SetUserID(userID string) { + o.UserID = userID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + // path param user_id + if err := r.SetPathParam("user_id", o.UserID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_user_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_user_responses.go new file mode 100644 index 0000000..a34d90e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/modify_user_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyUserReader is a Reader for the ModifyUser structure. +type ModifyUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyUserOK creates a ModifyUserOK with default headers values +func NewModifyUserOK() *ModifyUserOK { + return &ModifyUserOK{} +} + +/* ModifyUserOK describes a response with status code 200, with default header values. + +A GetUserResult is an response struct that is used to describe getuser. +*/ +type ModifyUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserOKBody +} + +// IsSuccess returns true when this modify user o k response has a 2xx status code +func (o *ModifyUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify user o k response has a 3xx status code +func (o *ModifyUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify user o k response has a 4xx status code +func (o *ModifyUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify user o k response has a 5xx status code +func (o *ModifyUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify user o k response a status code equal to that given +func (o *ModifyUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyUserOK) Error() string { + return fmt.Sprintf("[PUT /users/{user_id}][%d] modifyUserOK %+v", 200, o.Payload) +} + +func (o *ModifyUserOK) String() string { + return fmt.Sprintf("[PUT /users/{user_id}][%d] modifyUserOK %+v", 200, o.Payload) +} + +func (o *ModifyUserOK) GetPayload() *ModifyUserOKBody { + return o.Payload +} + +func (o *ModifyUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyUserDefault creates a ModifyUserDefault with default headers values +func NewModifyUserDefault(code int) *ModifyUserDefault { + return &ModifyUserDefault{ + _statusCode: code, + } +} + +/* ModifyUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserDefaultBody +} + +// Code gets the status code for the modify user default response +func (o *ModifyUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify user default response has a 2xx status code +func (o *ModifyUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify user default response has a 3xx status code +func (o *ModifyUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify user default response has a 4xx status code +func (o *ModifyUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify user default response has a 5xx status code +func (o *ModifyUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify user default response a status code equal to that given +func (o *ModifyUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyUserDefault) Error() string { + return fmt.Sprintf("[PUT /users/{user_id}][%d] modifyUser default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserDefault) String() string { + return fmt.Sprintf("[PUT /users/{user_id}][%d] modifyUser default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserDefault) GetPayload() *ModifyUserDefaultBody { + return o.Payload +} + +func (o *ModifyUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyUserDefaultBody modify user default body +swagger:model ModifyUserDefaultBody +*/ +type ModifyUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify user default body +func (o *ModifyUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user default body based on the context it is used +func (o *ModifyUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyUserOKBody modify user o k body +swagger:model ModifyUserOKBody +*/ +type ModifyUserOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify user o k body +func (o *ModifyUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user o k body based on the context it is used +func (o *ModifyUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserOKBody) UnmarshalBinary(b []byte) error { + var res ModifyUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/user_client.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/user_client.go new file mode 100644 index 0000000..6a1bae7 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/user_client.go @@ -0,0 +1,437 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new user API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for user API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateUser(params *CreateUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserOK, error) + + DeleteUser(params *DeleteUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserOK, error) + + DescribeLocalUser(params *DescribeLocalUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLocalUserOK, error) + + DescribeUser(params *DescribeUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserOK, error) + + DescribeUserByName(params *DescribeUserByNameParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserByNameOK, error) + + DescribeUsers(params *DescribeUsersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUsersOK, error) + + ModifyLocalUser(params *ModifyLocalUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyLocalUserOK, error) + + ModifyLocalUserPassword(params *ModifyLocalUserPasswordParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyLocalUserPasswordOK, error) + + ModifyUser(params *ModifyUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserOK, error) + + VerifyUser(params *VerifyUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*VerifyUserOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateUser CreateUser 创建用户 +*/ +func (a *Client) CreateUser(params *CreateUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateUserParams() + } + op := &runtime.ClientOperation{ + ID: "createUser", + Method: "POST", + PathPattern: "/users", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteUser DeleteUser 删除用户 +*/ +func (a *Client) DeleteUser(params *DeleteUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteUserParams() + } + op := &runtime.ClientOperation{ + ID: "deleteUser", + Method: "DELETE", + PathPattern: "/users/{user_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeLocalUser DescribeLocalUser 控制台获取用户详情 +*/ +func (a *Client) DescribeLocalUser(params *DescribeLocalUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLocalUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeLocalUserParams() + } + op := &runtime.ClientOperation{ + ID: "describeLocalUser", + Method: "GET", + PathPattern: "/local/users", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeLocalUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeLocalUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeLocalUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUser DescribeUser 获取用户详情 +*/ +func (a *Client) DescribeUser(params *DescribeUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserParams() + } + op := &runtime.ClientOperation{ + ID: "describeUser", + Method: "GET", + PathPattern: "/users/{user_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserByName DescribeUserByName 根据用户名获取用户详情 +*/ +func (a *Client) DescribeUserByName(params *DescribeUserByNameParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserByNameOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserByNameParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserByName", + Method: "GET", + PathPattern: "/users/getUserByName", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserByNameReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserByNameOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserByNameDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUsers DescribeUsers 获取用户列表 +*/ +func (a *Client) DescribeUsers(params *DescribeUsersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUsersOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUsersParams() + } + op := &runtime.ClientOperation{ + ID: "describeUsers", + Method: "GET", + PathPattern: "/users", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUsersReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUsersOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUsersDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyLocalUser ModifyLocalUser 控制台修改除密码外的个人信息 +*/ +func (a *Client) ModifyLocalUser(params *ModifyLocalUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyLocalUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyLocalUserParams() + } + op := &runtime.ClientOperation{ + ID: "modifyLocalUser", + Method: "PUT", + PathPattern: "/local/users", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyLocalUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyLocalUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyLocalUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyLocalUserPassword ModifyLocalUserPassword 控制台修改个人密码 +*/ +func (a *Client) ModifyLocalUserPassword(params *ModifyLocalUserPasswordParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyLocalUserPasswordOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyLocalUserPasswordParams() + } + op := &runtime.ClientOperation{ + ID: "modifyLocalUserPassword", + Method: "PUT", + PathPattern: "/local/users/password", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyLocalUserPasswordReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyLocalUserPasswordOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyLocalUserPasswordDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyUser ModifyUser 修改用户信息 +*/ +func (a *Client) ModifyUser(params *ModifyUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyUserParams() + } + op := &runtime.ClientOperation{ + ID: "modifyUser", + Method: "PUT", + PathPattern: "/users/{user_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + VerifyUser VerifyUser 鉴定用户 +*/ +func (a *Client) VerifyUser(params *VerifyUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*VerifyUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewVerifyUserParams() + } + op := &runtime.ClientOperation{ + ID: "verifyUser", + Method: "POST", + PathPattern: "/users/verify", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &VerifyUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*VerifyUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*VerifyUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/verify_user_parameters.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/verify_user_parameters.go new file mode 100644 index 0000000..bf260ee --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/verify_user_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewVerifyUserParams creates a new VerifyUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewVerifyUserParams() *VerifyUserParams { + return &VerifyUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewVerifyUserParamsWithTimeout creates a new VerifyUserParams object +// with the ability to set a timeout on a request. +func NewVerifyUserParamsWithTimeout(timeout time.Duration) *VerifyUserParams { + return &VerifyUserParams{ + timeout: timeout, + } +} + +// NewVerifyUserParamsWithContext creates a new VerifyUserParams object +// with the ability to set a context for a request. +func NewVerifyUserParamsWithContext(ctx context.Context) *VerifyUserParams { + return &VerifyUserParams{ + Context: ctx, + } +} + +// NewVerifyUserParamsWithHTTPClient creates a new VerifyUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewVerifyUserParamsWithHTTPClient(client *http.Client) *VerifyUserParams { + return &VerifyUserParams{ + HTTPClient: client, + } +} + +/* VerifyUserParams contains all the parameters to send to the API endpoint + for the verify user operation. + + Typically these are written to a http.Request. +*/ +type VerifyUserParams struct { + + // Body. + Body *models.VerifyUserRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the verify user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *VerifyUserParams) WithDefaults() *VerifyUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the verify user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *VerifyUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the verify user params +func (o *VerifyUserParams) WithTimeout(timeout time.Duration) *VerifyUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the verify user params +func (o *VerifyUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the verify user params +func (o *VerifyUserParams) WithContext(ctx context.Context) *VerifyUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the verify user params +func (o *VerifyUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the verify user params +func (o *VerifyUserParams) WithHTTPClient(client *http.Client) *VerifyUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the verify user params +func (o *VerifyUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the verify user params +func (o *VerifyUserParams) WithBody(body *models.VerifyUserRequest) *VerifyUserParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the verify user params +func (o *VerifyUserParams) SetBody(body *models.VerifyUserRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the verify user params +func (o *VerifyUserParams) WithAuthorization(authorization string) *VerifyUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the verify user params +func (o *VerifyUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the verify user params +func (o *VerifyUserParams) WithBmpLanguage(bmpLanguage *string) *VerifyUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the verify user params +func (o *VerifyUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the verify user params +func (o *VerifyUserParams) WithBmpUserID(bmpUserID *string) *VerifyUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the verify user params +func (o *VerifyUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the verify user params +func (o *VerifyUserParams) WithTraceID(traceID string) *VerifyUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the verify user params +func (o *VerifyUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *VerifyUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/verify_user_responses.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/verify_user_responses.go new file mode 100644 index 0000000..220fb78 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/client/user/verify_user_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// VerifyUserReader is a Reader for the VerifyUser structure. +type VerifyUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *VerifyUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewVerifyUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewVerifyUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewVerifyUserOK creates a VerifyUserOK with default headers values +func NewVerifyUserOK() *VerifyUserOK { + return &VerifyUserOK{} +} + +/* VerifyUserOK describes a response with status code 200, with default header values. + +A VerifyUserResult is an response struct that is used to describe verify user result. +*/ +type VerifyUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *VerifyUserOKBody +} + +// IsSuccess returns true when this verify user o k response has a 2xx status code +func (o *VerifyUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this verify user o k response has a 3xx status code +func (o *VerifyUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this verify user o k response has a 4xx status code +func (o *VerifyUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this verify user o k response has a 5xx status code +func (o *VerifyUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this verify user o k response a status code equal to that given +func (o *VerifyUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *VerifyUserOK) Error() string { + return fmt.Sprintf("[POST /users/verify][%d] verifyUserOK %+v", 200, o.Payload) +} + +func (o *VerifyUserOK) String() string { + return fmt.Sprintf("[POST /users/verify][%d] verifyUserOK %+v", 200, o.Payload) +} + +func (o *VerifyUserOK) GetPayload() *VerifyUserOKBody { + return o.Payload +} + +func (o *VerifyUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(VerifyUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewVerifyUserDefault creates a VerifyUserDefault with default headers values +func NewVerifyUserDefault(code int) *VerifyUserDefault { + return &VerifyUserDefault{ + _statusCode: code, + } +} + +/* VerifyUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type VerifyUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *VerifyUserDefaultBody +} + +// Code gets the status code for the verify user default response +func (o *VerifyUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this verify user default response has a 2xx status code +func (o *VerifyUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this verify user default response has a 3xx status code +func (o *VerifyUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this verify user default response has a 4xx status code +func (o *VerifyUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this verify user default response has a 5xx status code +func (o *VerifyUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this verify user default response a status code equal to that given +func (o *VerifyUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *VerifyUserDefault) Error() string { + return fmt.Sprintf("[POST /users/verify][%d] verifyUser default %+v", o._statusCode, o.Payload) +} + +func (o *VerifyUserDefault) String() string { + return fmt.Sprintf("[POST /users/verify][%d] verifyUser default %+v", o._statusCode, o.Payload) +} + +func (o *VerifyUserDefault) GetPayload() *VerifyUserDefaultBody { + return o.Payload +} + +func (o *VerifyUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(VerifyUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*VerifyUserDefaultBody verify user default body +swagger:model VerifyUserDefaultBody +*/ +type VerifyUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this verify user default body +func (o *VerifyUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *VerifyUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("verifyUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *VerifyUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("verifyUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("verifyUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("verifyUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this verify user default body based on the context it is used +func (o *VerifyUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *VerifyUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("verifyUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("verifyUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *VerifyUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *VerifyUserDefaultBody) UnmarshalBinary(b []byte) error { + var res VerifyUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*VerifyUserOKBody verify user o k body +swagger:model VerifyUserOKBody +*/ +type VerifyUserOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this verify user o k body +func (o *VerifyUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *VerifyUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("verifyUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("verifyUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this verify user o k body based on the context it is used +func (o *VerifyUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *VerifyUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("verifyUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("verifyUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *VerifyUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *VerifyUserOKBody) UnmarshalBinary(b []byte) error { + var res VerifyUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/go.mod b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/go.mod new file mode 100644 index 0000000..2b82f4f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/go.mod @@ -0,0 +1,3 @@ +module coding.jd.com/aidc-bmp/bmp-openapi-sdk + +go 1.17 diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/add_rule_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/add_rule_request.go new file mode 100644 index 0000000..aefb2c8 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/add_rule_request.go @@ -0,0 +1,238 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// AddRuleRequest add rule request +// +// swagger:model AddRuleRequest +type AddRuleRequest struct { + + // 盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag,omitempty"` + + // 维度 [instance、disk、mountpoint、nic] + // Required: true + Dimension *string `json:"dimension"` + + // 实例id列表 + // Required: true + InstanceIds []string `json:"instanceIds"` + + // 资源类型,目前只支持instance + // Required: true + Resource *string `json:"resource"` + + // 规则名称 + // Required: true + RuleName *string `json:"ruleName"` + + // 触发条件 + // Required: true + TriggerOption []*RuleTrigger `json:"triggerOption"` + + // notice option + // Required: true + NoticeOption *RuleNotice `json:"noticeOption"` +} + +// Validate validates this add rule request +func (m *AddRuleRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDimension(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInstanceIds(formats); err != nil { + res = append(res, err) + } + + if err := m.validateResource(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRuleName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTriggerOption(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNoticeOption(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AddRuleRequest) validateDimension(formats strfmt.Registry) error { + + if err := validate.Required("dimension", "body", m.Dimension); err != nil { + return err + } + + return nil +} + +func (m *AddRuleRequest) validateInstanceIds(formats strfmt.Registry) error { + + if err := validate.Required("instanceIds", "body", m.InstanceIds); err != nil { + return err + } + + return nil +} + +func (m *AddRuleRequest) validateResource(formats strfmt.Registry) error { + + if err := validate.Required("resource", "body", m.Resource); err != nil { + return err + } + + return nil +} + +func (m *AddRuleRequest) validateRuleName(formats strfmt.Registry) error { + + if err := validate.Required("ruleName", "body", m.RuleName); err != nil { + return err + } + + return nil +} + +func (m *AddRuleRequest) validateTriggerOption(formats strfmt.Registry) error { + + if err := validate.Required("triggerOption", "body", m.TriggerOption); err != nil { + return err + } + + for i := 0; i < len(m.TriggerOption); i++ { + if swag.IsZero(m.TriggerOption[i]) { // not required + continue + } + + if m.TriggerOption[i] != nil { + if err := m.TriggerOption[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *AddRuleRequest) validateNoticeOption(formats strfmt.Registry) error { + + if err := validate.Required("noticeOption", "body", m.NoticeOption); err != nil { + return err + } + + if m.NoticeOption != nil { + if err := m.NoticeOption.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("noticeOption") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("noticeOption") + } + return err + } + } + + return nil +} + +// ContextValidate validate this add rule request based on the context it is used +func (m *AddRuleRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateTriggerOption(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateNoticeOption(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AddRuleRequest) contextValidateTriggerOption(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.TriggerOption); i++ { + + if m.TriggerOption[i] != nil { + if err := m.TriggerOption[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *AddRuleRequest) contextValidateNoticeOption(ctx context.Context, formats strfmt.Registry) error { + + if m.NoticeOption != nil { + if err := m.NoticeOption.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("noticeOption") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("noticeOption") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *AddRuleRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AddRuleRequest) UnmarshalBinary(b []byte) error { + var res AddRuleRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/agent_status_item.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/agent_status_item.go new file mode 100644 index 0000000..2aa421b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/agent_status_item.go @@ -0,0 +1,65 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// AgentStatusItem agent status item +// +// swagger:model AgentStatusItem +type AgentStatusItem struct { + + // agent version + AgentVersion string `json:"agent_version,omitempty"` + + // instance ID + InstanceID string `json:"instance_id,omitempty"` + + // s n + SN string `json:"sn,omitempty"` + + // 1->running 2->stopped 0->unknown + Status int64 `json:"status,omitempty"` + + // status 运行 停止 未知 + StatusName string `json:"statusName,omitempty"` + + // timestamp + Timestamp int64 `json:"timestamp,omitempty"` +} + +// Validate validates this agent status item +func (m *AgentStatusItem) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this agent status item based on context it is used +func (m *AgentStatusItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *AgentStatusItem) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AgentStatusItem) UnmarshalBinary(b []byte) error { + var res AgentStatusItem + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/agent_status_response.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/agent_status_response.go new file mode 100644 index 0000000..1e9bfb3 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/agent_status_response.go @@ -0,0 +1,116 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// AgentStatusResponse agent status response +// +// swagger:model AgentStatusResponse +type AgentStatusResponse struct { + + // agent status + AgentStatus []*AgentStatusItem `json:"agentStatus"` +} + +// Validate validates this agent status response +func (m *AgentStatusResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAgentStatus(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AgentStatusResponse) validateAgentStatus(formats strfmt.Registry) error { + if swag.IsZero(m.AgentStatus) { // not required + return nil + } + + for i := 0; i < len(m.AgentStatus); i++ { + if swag.IsZero(m.AgentStatus[i]) { // not required + continue + } + + if m.AgentStatus[i] != nil { + if err := m.AgentStatus[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("agentStatus" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("agentStatus" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this agent status response based on the context it is used +func (m *AgentStatusResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateAgentStatus(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AgentStatusResponse) contextValidateAgentStatus(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.AgentStatus); i++ { + + if m.AgentStatus[i] != nil { + if err := m.AgentStatus[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("agentStatus" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("agentStatus" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *AgentStatusResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AgentStatusResponse) UnmarshalBinary(b []byte) error { + var res AgentStatusResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/alert.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/alert.go new file mode 100644 index 0000000..fac0eb7 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/alert.go @@ -0,0 +1,192 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Alert alert +// +// swagger:model Alert +type Alert struct { + + // alert uuid + AlertID string `json:"alertId,omitempty"` + + // 1表示一般,2表示严重,3表示紧急 + AlertLevel int64 `json:"alertLevel,omitempty"` + + // 级别描述 + AlertLevelDescription string `json:"alertLevelDescription,omitempty"` + + // 告警持续时间(分钟为单位) + AlertPeriod int64 `json:"alertPeriod,omitempty"` + + // 告警时间戳 + AlertTime int64 `json:"alertTime,omitempty"` + + // 报警值 + AlertValue string `json:"alertValue,omitempty"` + + // 创建时间戳 + CreatedTime int64 `json:"createdTime,omitempty"` + + // 资源类型 [只支持instance一种] + Resource string `json:"resource,omitempty"` + + // 资源id,目前就是实例id + ResourceID string `json:"resourceId,omitempty"` + + // 资源名称,目前就是实例名称 + ResourceName string `json:"resourceName,omitempty"` + + // 触发条件,接口需要翻译 + Trigger string `json:"trigger,omitempty"` + + // 触发条件描述 + TriggerDescription string `json:"triggerDescription,omitempty"` + + // 通知对象 userid + UserID string `json:"userId,omitempty"` + + // 通知对象 用户名 + UserName string `json:"userName,omitempty"` + + // instance + Instance *Instance `json:"instance,omitempty"` + + // rule + Rule *Rule `json:"rule,omitempty"` +} + +// Validate validates this alert +func (m *Alert) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstance(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRule(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Alert) validateInstance(formats strfmt.Registry) error { + if swag.IsZero(m.Instance) { // not required + return nil + } + + if m.Instance != nil { + if err := m.Instance.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instance") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instance") + } + return err + } + } + + return nil +} + +func (m *Alert) validateRule(formats strfmt.Registry) error { + if swag.IsZero(m.Rule) { // not required + return nil + } + + if m.Rule != nil { + if err := m.Rule.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("rule") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("rule") + } + return err + } + } + + return nil +} + +// ContextValidate validate this alert based on the context it is used +func (m *Alert) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateInstance(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateRule(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Alert) contextValidateInstance(ctx context.Context, formats strfmt.Registry) error { + + if m.Instance != nil { + if err := m.Instance.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instance") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instance") + } + return err + } + } + + return nil +} + +func (m *Alert) contextValidateRule(ctx context.Context, formats strfmt.Registry) error { + + if m.Rule != nil { + if err := m.Rule.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("rule") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("rule") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Alert) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Alert) UnmarshalBinary(b []byte) error { + var res Alert + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/alert_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/alert_list.go new file mode 100644 index 0000000..1d844d3 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/alert_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// AlertList alert list +// +// swagger:model AlertList +type AlertList struct { + + // rules数组 + Alerts []*Alert `json:"instances"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this alert list +func (m *AlertList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAlerts(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AlertList) validateAlerts(formats strfmt.Registry) error { + if swag.IsZero(m.Alerts) { // not required + return nil + } + + for i := 0; i < len(m.Alerts); i++ { + if swag.IsZero(m.Alerts[i]) { // not required + continue + } + + if m.Alerts[i] != nil { + if err := m.Alerts[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this alert list based on the context it is used +func (m *AlertList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateAlerts(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AlertList) contextValidateAlerts(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Alerts); i++ { + + if m.Alerts[i] != nil { + if err := m.Alerts[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *AlertList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AlertList) UnmarshalBinary(b []byte) error { + var res AlertList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/apikey.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/apikey.go new file mode 100644 index 0000000..415fe37 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/apikey.go @@ -0,0 +1,171 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Apikey apikey +// +// swagger:model Apikey +type Apikey struct { + + // apikey uuid + // Required: true + ApikeyID *string `json:"apiKeyId"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // ID + ID int64 `json:"id,omitempty"` + + // 名称 + // Required: true + Name *string `json:"name"` + + // 是否支持只读, [0/1], 1表示只读 + // Required: true + ReadOnly *int8 `json:"readOnly"` + + // 32位字符令牌,使用token来独立访问openapi + // Required: true + Token *string `json:"token"` + + // apikey的类型,[system/user] + // Required: true + Type *string `json:"type"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 所属用户uuid + // Required: true + UserID *string `json:"userId"` +} + +// Validate validates this apikey +func (m *Apikey) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateApikeyID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateReadOnly(formats); err != nil { + res = append(res, err) + } + + if err := m.validateToken(formats); err != nil { + res = append(res, err) + } + + if err := m.validateType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Apikey) validateApikeyID(formats strfmt.Registry) error { + + if err := validate.Required("apiKeyId", "body", m.ApikeyID); err != nil { + return err + } + + return nil +} + +func (m *Apikey) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +func (m *Apikey) validateReadOnly(formats strfmt.Registry) error { + + if err := validate.Required("readOnly", "body", m.ReadOnly); err != nil { + return err + } + + return nil +} + +func (m *Apikey) validateToken(formats strfmt.Registry) error { + + if err := validate.Required("token", "body", m.Token); err != nil { + return err + } + + return nil +} + +func (m *Apikey) validateType(formats strfmt.Registry) error { + + if err := validate.Required("type", "body", m.Type); err != nil { + return err + } + + return nil +} + +func (m *Apikey) validateUserID(formats strfmt.Registry) error { + + if err := validate.Required("userId", "body", m.UserID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this apikey based on context it is used +func (m *Apikey) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Apikey) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Apikey) UnmarshalBinary(b []byte) error { + var res Apikey + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/apikey_id.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/apikey_id.go new file mode 100644 index 0000000..6097b8a --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/apikey_id.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ApikeyID apikey Id +// +// swagger:model ApikeyId +type ApikeyID struct { + + // apikey uuid + // Required: true + ApikeyID *string `json:"apikeyId"` +} + +// Validate validates this apikey Id +func (m *ApikeyID) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateApikeyID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ApikeyID) validateApikeyID(formats strfmt.Registry) error { + + if err := validate.Required("apikeyId", "body", m.ApikeyID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this apikey Id based on context it is used +func (m *ApikeyID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ApikeyID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ApikeyID) UnmarshalBinary(b []byte) error { + var res ApikeyID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/apikey_info.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/apikey_info.go new file mode 100644 index 0000000..652fa8c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/apikey_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ApikeyInfo apikey info +// +// swagger:model ApikeyInfo +type ApikeyInfo struct { + + // apikey + Apikey *Apikey `json:"apikey,omitempty"` +} + +// Validate validates this apikey info +func (m *ApikeyInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateApikey(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ApikeyInfo) validateApikey(formats strfmt.Registry) error { + if swag.IsZero(m.Apikey) { // not required + return nil + } + + if m.Apikey != nil { + if err := m.Apikey.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("apikey") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("apikey") + } + return err + } + } + + return nil +} + +// ContextValidate validate this apikey info based on the context it is used +func (m *ApikeyInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateApikey(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ApikeyInfo) contextValidateApikey(ctx context.Context, formats strfmt.Registry) error { + + if m.Apikey != nil { + if err := m.Apikey.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("apikey") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("apikey") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ApikeyInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ApikeyInfo) UnmarshalBinary(b []byte) error { + var res ApikeyInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/apikey_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/apikey_list.go new file mode 100644 index 0000000..6cceae9 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/apikey_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ApikeyList apikey list +// +// swagger:model ApikeyList +type ApikeyList struct { + + // apikeys + Apikeys []*Apikey `json:"apikeys"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this apikey list +func (m *ApikeyList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateApikeys(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ApikeyList) validateApikeys(formats strfmt.Registry) error { + if swag.IsZero(m.Apikeys) { // not required + return nil + } + + for i := 0; i < len(m.Apikeys); i++ { + if swag.IsZero(m.Apikeys[i]) { // not required + continue + } + + if m.Apikeys[i] != nil { + if err := m.Apikeys[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("apikeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("apikeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this apikey list based on the context it is used +func (m *ApikeyList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateApikeys(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ApikeyList) contextValidateApikeys(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Apikeys); i++ { + + if m.Apikeys[i] != nil { + if err := m.Apikeys[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("apikeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("apikeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ApikeyList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ApikeyList) UnmarshalBinary(b []byte) error { + var res ApikeyList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/associate_device_disk_spec.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/associate_device_disk_spec.go new file mode 100644 index 0000000..0cb8b7e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/associate_device_disk_spec.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// AssociateDeviceDiskSpec associate device disk spec +// +// swagger:model AssociateDeviceDiskSpec +type AssociateDeviceDiskSpec struct { + + // disk i ds + DiskIDs []string `json:"diskId"` + + // volume ID + VolumeID string `json:"volumeId,omitempty"` +} + +// Validate validates this associate device disk spec +func (m *AssociateDeviceDiskSpec) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this associate device disk spec based on context it is used +func (m *AssociateDeviceDiskSpec) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *AssociateDeviceDiskSpec) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AssociateDeviceDiskSpec) UnmarshalBinary(b []byte) error { + var res AssociateDeviceDiskSpec + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/associate_device_disks_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/associate_device_disks_request.go new file mode 100644 index 0000000..a0d05c0 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/associate_device_disks_request.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// AssociateDeviceDisksRequest associate device disks request +// +// swagger:model AssociateDeviceDisksRequest +type AssociateDeviceDisksRequest struct { + + // device uuid + // Required: true + DeviceID *string `json:"deviceId"` + + // 设备类型id + // Required: true + DeviceTypeID *string `json:"deviceTypeId"` + + // volumeid和磁盘uuid列表 + // Required: true + Volumes []*AssociateDeviceDiskSpec `json:"volumes"` +} + +// Validate validates this associate device disks request +func (m *AssociateDeviceDisksRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDeviceTypeID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVolumes(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AssociateDeviceDisksRequest) validateDeviceID(formats strfmt.Registry) error { + + if err := validate.Required("deviceId", "body", m.DeviceID); err != nil { + return err + } + + return nil +} + +func (m *AssociateDeviceDisksRequest) validateDeviceTypeID(formats strfmt.Registry) error { + + if err := validate.Required("deviceTypeId", "body", m.DeviceTypeID); err != nil { + return err + } + + return nil +} + +func (m *AssociateDeviceDisksRequest) validateVolumes(formats strfmt.Registry) error { + + if err := validate.Required("volumes", "body", m.Volumes); err != nil { + return err + } + + for i := 0; i < len(m.Volumes); i++ { + if swag.IsZero(m.Volumes[i]) { // not required + continue + } + + if m.Volumes[i] != nil { + if err := m.Volumes[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this associate device disks request based on the context it is used +func (m *AssociateDeviceDisksRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateVolumes(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AssociateDeviceDisksRequest) contextValidateVolumes(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Volumes); i++ { + + if m.Volumes[i] != nil { + if err := m.Volumes[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *AssociateDeviceDisksRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AssociateDeviceDisksRequest) UnmarshalBinary(b []byte) error { + var res AssociateDeviceDisksRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/associate_device_type_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/associate_device_type_request.go new file mode 100644 index 0000000..5e22584 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/associate_device_type_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// AssociateDeviceTypeRequest associate device type request +// +// swagger:model AssociateDeviceTypeRequest +type AssociateDeviceTypeRequest struct { + + // 设备类型id,数组,支持多个 + // Required: true + DeviceTypeIDs []string `json:"deviceTypeIds"` + + // 镜像ID, + // Required: true + ImageID *string `json:"imageId"` +} + +// Validate validates this associate device type request +func (m *AssociateDeviceTypeRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceTypeIDs(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImageID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AssociateDeviceTypeRequest) validateDeviceTypeIDs(formats strfmt.Registry) error { + + if err := validate.Required("deviceTypeIds", "body", m.DeviceTypeIDs); err != nil { + return err + } + + return nil +} + +func (m *AssociateDeviceTypeRequest) validateImageID(formats strfmt.Registry) error { + + if err := validate.Required("imageId", "body", m.ImageID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this associate device type request based on context it is used +func (m *AssociateDeviceTypeRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *AssociateDeviceTypeRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AssociateDeviceTypeRequest) UnmarshalBinary(b []byte) error { + var res AssociateDeviceTypeRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/associate_image_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/associate_image_request.go new file mode 100644 index 0000000..6da7b09 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/associate_image_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// AssociateImageRequest associate image request +// +// swagger:model AssociateImageRequest +type AssociateImageRequest struct { + + // 设备类型id + // Required: true + DeviceTypeID *string `json:"deviceTypeId"` + + // 镜像ID,数组,支持多个 + // Required: true + ImageIDs []string `json:"imageIds"` +} + +// Validate validates this associate image request +func (m *AssociateImageRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceTypeID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImageIDs(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AssociateImageRequest) validateDeviceTypeID(formats strfmt.Registry) error { + + if err := validate.Required("deviceTypeId", "body", m.DeviceTypeID); err != nil { + return err + } + + return nil +} + +func (m *AssociateImageRequest) validateImageIDs(formats strfmt.Registry) error { + + if err := validate.Required("imageIds", "body", m.ImageIDs); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this associate image request based on context it is used +func (m *AssociateImageRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *AssociateImageRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AssociateImageRequest) UnmarshalBinary(b []byte) error { + var res AssociateImageRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/audit_log.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/audit_log.go new file mode 100644 index 0000000..ae6098d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/audit_log.go @@ -0,0 +1,86 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// AuditLog audit log +// +// swagger:model AuditLog +type AuditLog struct { + + // device_id + DeviceID string `json:"deviceId,omitempty"` + + // 失败原因 + FailReason string `json:"failReason,omitempty"` + + // 完成时间 + FinishTime int64 `json:"finishTime,omitempty"` + + // ID + ID int64 `json:"id,omitempty"` + + // instance_id + InstanceID string `json:"instanceId,omitempty"` + + // 日志uuid + LogID string `json:"logid,omitempty"` + + // 操作时间 + OperateTime int64 `json:"operateTime,omitempty"` + + // 操作 + Operation string `json:"operation,omitempty"` + + // 操作名称 + OperationName string `json:"operationName,omitempty"` + + // 结果 success/fail + Result string `json:"result,omitempty"` + + // sn + Sn string `json:"sn,omitempty"` + + // 操作人 + UserID string `json:"userID,omitempty"` + + // 操作人 + UserName string `json:"userName,omitempty"` +} + +// Validate validates this audit log +func (m *AuditLog) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this audit log based on context it is used +func (m *AuditLog) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *AuditLog) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AuditLog) UnmarshalBinary(b []byte) error { + var res AuditLog + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/audit_log_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/audit_log_list.go new file mode 100644 index 0000000..510813d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/audit_log_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// AuditLogList audit log list +// +// swagger:model AuditLogList +type AuditLogList struct { + + // 机型列表 + AuditLogs []*AuditLog `json:"auditLogs"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this audit log list +func (m *AuditLogList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAuditLogs(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AuditLogList) validateAuditLogs(formats strfmt.Registry) error { + if swag.IsZero(m.AuditLogs) { // not required + return nil + } + + for i := 0; i < len(m.AuditLogs); i++ { + if swag.IsZero(m.AuditLogs[i]) { // not required + continue + } + + if m.AuditLogs[i] != nil { + if err := m.AuditLogs[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("auditLogs" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("auditLogs" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this audit log list based on the context it is used +func (m *AuditLogList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateAuditLogs(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AuditLogList) contextValidateAuditLogs(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.AuditLogs); i++ { + + if m.AuditLogs[i] != nil { + if err := m.AuditLogs[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("auditLogs" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("auditLogs" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *AuditLogList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AuditLogList) UnmarshalBinary(b []byte) error { + var res AuditLogList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/audit_logs_type.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/audit_logs_type.go new file mode 100644 index 0000000..34decc2 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/audit_logs_type.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// AuditLogsType audit logs type +// +// swagger:model AuditLogsType +type AuditLogsType struct { + + // name,自动适配中英文 + Name string `json:"name,omitempty"` + + // 数据库中存储的operation + Operation string `json:"operation,omitempty"` +} + +// Validate validates this audit logs type +func (m *AuditLogsType) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this audit logs type based on context it is used +func (m *AuditLogsType) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *AuditLogsType) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AuditLogsType) UnmarshalBinary(b []byte) error { + var res AuditLogsType + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/collect_device_info_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/collect_device_info_request.go new file mode 100644 index 0000000..38888b4 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/collect_device_info_request.go @@ -0,0 +1,119 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CollectDeviceInfoRequest collect device info request +// +// swagger:model CollectDeviceInfoRequest +type CollectDeviceInfoRequest struct { + + // 待采集项 + // Required: true + Collects []*CollectItem `json:"collects"` +} + +// Validate validates this collect device info request +func (m *CollectDeviceInfoRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCollects(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CollectDeviceInfoRequest) validateCollects(formats strfmt.Registry) error { + + if err := validate.Required("collects", "body", m.Collects); err != nil { + return err + } + + for i := 0; i < len(m.Collects); i++ { + if swag.IsZero(m.Collects[i]) { // not required + continue + } + + if m.Collects[i] != nil { + if err := m.Collects[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("collects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("collects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this collect device info request based on the context it is used +func (m *CollectDeviceInfoRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateCollects(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CollectDeviceInfoRequest) contextValidateCollects(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Collects); i++ { + + if m.Collects[i] != nil { + if err := m.Collects[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("collects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("collects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CollectDeviceInfoRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CollectDeviceInfoRequest) UnmarshalBinary(b []byte) error { + var res CollectDeviceInfoRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/collect_item.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/collect_item.go new file mode 100644 index 0000000..508c085 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/collect_item.go @@ -0,0 +1,74 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CollectItem collect item +// +// swagger:model CollectItem +type CollectItem struct { + + // 可选参数。 传参:True, False 。True表示传入的raid_driver值将覆盖已适配机器的raid_driver + AllowOverride *bool `json:"allowOverride,omitempty"` + + // sn + // Required: true + Sn *string `json:"sn"` +} + +// Validate validates this collect item +func (m *CollectItem) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSn(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CollectItem) validateSn(formats strfmt.Registry) error { + + if err := validate.Required("sn", "body", m.Sn); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this collect item based on context it is used +func (m *CollectItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CollectItem) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CollectItem) UnmarshalBinary(b []byte) error { + var res CollectItem + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/common_response.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/common_response.go new file mode 100644 index 0000000..f3957c5 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/common_response.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonResponse common response +// +// swagger:model CommonResponse +type CommonResponse struct { + + // 操作是否成功 [true/false] + Success bool `json:"success,omitempty"` +} + +// Validate validates this common response +func (m *CommonResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common response based on context it is used +func (m *CommonResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonResponse) UnmarshalBinary(b []byte) error { + var res CommonResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_apikey_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_apikey_request.go new file mode 100644 index 0000000..7462b07 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_apikey_request.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateApikeyRequest create apikey request +// +// swagger:model CreateApikeyRequest +type CreateApikeyRequest struct { + + // 秘钥对名称 + // Required: true + Name *string `json:"name"` + + // 是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法 + // Required: true + ReadOnly *int8 `json:"readOnly"` + + // Token类型, [system/user] + // Required: true + Type *string `json:"type"` +} + +// Validate validates this create apikey request +func (m *CreateApikeyRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateReadOnly(formats); err != nil { + res = append(res, err) + } + + if err := m.validateType(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateApikeyRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +func (m *CreateApikeyRequest) validateReadOnly(formats strfmt.Registry) error { + + if err := validate.Required("readOnly", "body", m.ReadOnly); err != nil { + return err + } + + return nil +} + +func (m *CreateApikeyRequest) validateType(formats strfmt.Registry) error { + + if err := validate.Required("type", "body", m.Type); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create apikey request based on context it is used +func (m *CreateApikeyRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateApikeyRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateApikeyRequest) UnmarshalBinary(b []byte) error { + var res CreateApikeyRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_device_spec.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_device_spec.go new file mode 100644 index 0000000..a92e09f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_device_spec.go @@ -0,0 +1,228 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateDeviceSpec create device spec +// +// swagger:model CreateDeviceSpec +type CreateDeviceSpec struct { + + // 品牌 + // Required: true + Cabinet *string `json:"cabinet"` + + // MAC2(eth1) + // Required: true + Description *string `json:"description"` + + // eth1子网掩码 + // MaskEth1 string `json:"maskEth1" validate:"omitempty,min=1,max=128"` // eth1子网掩码 + // 网关地址 + // Required: true + Gateway *string `json:"gateway"` + + // 带外IP + // Required: true + IloIP *string `json:"iloIp"` + + // 带外密码 + IloPassword string `json:"iloPassword,omitempty"` + + // 带外账号 + IloUser string `json:"iloUser,omitempty"` + + // instance ID + InstanceID string `json:"instanceId,omitempty"` + + // MAC1(eth0) + // Required: true + Mac1 *string `json:"mac1"` + + // 设备状态,默认已入库 + ManageStatus string `json:"manageStatus,omitempty"` + + // 网口交换机IP + // SwitchIP string `json:"switchIp"` // 网口交换机IP + // 子网掩码 + // Required: true + Mask *string `json:"mask"` + + // 内网IPV4 + // Required: true + PrivateIPV4 *string `json:"privateIpv4"` + + // eth1内网IPV4(非bond模式时传值) + // PrivateEth1IPv4 string `json:"privateEth1Ipv4" validate:"omitempty,min=1,max=128"` // eth1内网IPV4 + // 内网IPV6 + PrivateIPV6 string `json:"privateIpv6,omitempty"` + + // 设备SN + // Required: true + Sn *string `json:"sn"` + + // 所在U位 + // Required: true + UPosition *string `json:"uPosition"` +} + +// Validate validates this create device spec +func (m *CreateDeviceSpec) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCabinet(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDescription(formats); err != nil { + res = append(res, err) + } + + if err := m.validateGateway(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIloIP(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMac1(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMask(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePrivateIPV4(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSn(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUPosition(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateDeviceSpec) validateCabinet(formats strfmt.Registry) error { + + if err := validate.Required("cabinet", "body", m.Cabinet); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateDescription(formats strfmt.Registry) error { + + if err := validate.Required("description", "body", m.Description); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateGateway(formats strfmt.Registry) error { + + if err := validate.Required("gateway", "body", m.Gateway); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateIloIP(formats strfmt.Registry) error { + + if err := validate.Required("iloIp", "body", m.IloIP); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateMac1(formats strfmt.Registry) error { + + if err := validate.Required("mac1", "body", m.Mac1); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateMask(formats strfmt.Registry) error { + + if err := validate.Required("mask", "body", m.Mask); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validatePrivateIPV4(formats strfmt.Registry) error { + + if err := validate.Required("privateIpv4", "body", m.PrivateIPV4); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateSn(formats strfmt.Registry) error { + + if err := validate.Required("sn", "body", m.Sn); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateUPosition(formats strfmt.Registry) error { + + if err := validate.Required("uPosition", "body", m.UPosition); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create device spec based on context it is used +func (m *CreateDeviceSpec) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateDeviceSpec) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateDeviceSpec) UnmarshalBinary(b []byte) error { + var res CreateDeviceSpec + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_device_type_raid_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_device_type_raid_request.go new file mode 100644 index 0000000..b43eb95 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_device_type_raid_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CreateDeviceTypeRaidRequest create device type raid request +// +// swagger:model CreateDeviceTypeRaidRequest +type CreateDeviceTypeRaidRequest struct { + + // available value + AvailableValue int64 `json:"availableValue,omitempty"` + + // device type + DeviceType string `json:"deviceType,omitempty"` + + // device type ID + DeviceTypeID string `json:"DeviceTypeId,omitempty"` + + // disk type + DiskType string `json:"diskType,omitempty"` + + // raid ID + RaidID string `json:"raidId,omitempty"` + + // system partition count + SystemPartitionCount int64 `json:"systemPartitionCount,omitempty"` + + // volume detail + VolumeDetail string `json:"volumeDetail,omitempty"` + + // volume type + VolumeType string `json:"volumeType,omitempty"` +} + +// Validate validates this create device type raid request +func (m *CreateDeviceTypeRaidRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this create device type raid request based on context it is used +func (m *CreateDeviceTypeRaidRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateDeviceTypeRaidRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateDeviceTypeRaidRequest) UnmarshalBinary(b []byte) error { + var res CreateDeviceTypeRaidRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_device_type_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_device_type_request.go new file mode 100644 index 0000000..bba69ff --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_device_type_request.go @@ -0,0 +1,477 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateDeviceTypeRequest create device type request +// +// swagger:model CreateDeviceTypeRequest +type CreateDeviceTypeRequest struct { + + // 体系架构,1-64 + // Required: true + Architecture *string `json:"architecture"` + + // boot模式【UEFI Legacy/BIOS】支持多选,逗号分隔 + BootMode string `json:"boot_mode,omitempty"` + + // cpu数量1,10000 + // Required: true + CPUAmount *int64 `json:"cpuAmount"` + + // 单个cpu内核数1,10000 + // Required: true + CPUCores *int64 `json:"cpuCores"` + + // cpu频率(G)1-64 + // Required: true + CPUFrequency *string `json:"cpuFrequency"` + + // cpu厂商1-64 + // Required: true + CPUManufacturer *string `json:"cpuManufacturer"` + + // cpu处理器型号1-64 + // Required: true + CPUModel *string `json:"cpuModel"` + + // CPU 预置规格 + // Required: true + CPUSpec *string `json:"cpuSpec"` + + // 描述0-256 + Description string `json:"description,omitempty"` + + // 机型类型,如computer storage gpu other + // Required: true + DeviceSeries *string `json:"deviceSeries"` + + // 机型规格1-64 + // Required: true + DeviceType *string `json:"deviceType"` + + // gpu数量0-1000 + GpuAmount int64 `json:"gpuAmount,omitempty"` + + // gpu品牌0-64 + GpuManufacturer string `json:"gpuManufacturer,omitempty"` + + // gpu型号0-64 + GpuModel string `json:"gpuModel,omitempty"` + + // 【高度(U)】:显示机型高度 2,4 + // Required: true + Height *int64 `json:"height"` + + // 机房id + // Required: true + IDcID *string `json:"idcId"` + + // 【网口模式】【网络设置】: bond,dual,single + // Required: true + InterfaceMode *string `json:"interfaceMode"` + + // 阵列卡是否需要配置 1 需要配置 2无需配置 + IsNeedRaid string `json:"isNeedRaid,omitempty"` + + // 内存数量1-10000 + // Required: true + MemAmount *int64 `json:"memAmount"` + + // 内存主频(MHz)1-10000 + // Required: true + MemFrequency *int64 `json:"memFrequency"` + + // 单个内存大小1,10000(GB) + // Required: true + MemSize *int64 `json:"memSize"` + + // 内存 预置规格 + // Required: true + MemSpec *string `json:"memSpec"` + + // 内存接口(DDR DDR2 DDR3 DDR4 DDR5) + // Required: true + MemType *string `json:"memType"` + + // 机型名称1-64 + // Required: true + Name *string `json:"name"` + + // 网卡数量1-10000 + // Required: true + NicAmount *int64 `json:"nicAmount"` + + // 网卡传输速率(GE) 1-10000 + // Required: true + NicRate *int64 `json:"nicRate"` + + // 卷管理 + // Required: true + Volumes []*VolumeItem `json:"volumes"` +} + +// Validate validates this create device type request +func (m *CreateDeviceTypeRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateArchitecture(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCPUAmount(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCPUCores(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCPUFrequency(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCPUManufacturer(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCPUModel(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCPUSpec(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDeviceSeries(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDeviceType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateHeight(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIDcID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInterfaceMode(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMemAmount(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMemFrequency(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMemSize(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMemSpec(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMemType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNicAmount(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNicRate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVolumes(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateDeviceTypeRequest) validateArchitecture(formats strfmt.Registry) error { + + if err := validate.Required("architecture", "body", m.Architecture); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateCPUAmount(formats strfmt.Registry) error { + + if err := validate.Required("cpuAmount", "body", m.CPUAmount); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateCPUCores(formats strfmt.Registry) error { + + if err := validate.Required("cpuCores", "body", m.CPUCores); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateCPUFrequency(formats strfmt.Registry) error { + + if err := validate.Required("cpuFrequency", "body", m.CPUFrequency); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateCPUManufacturer(formats strfmt.Registry) error { + + if err := validate.Required("cpuManufacturer", "body", m.CPUManufacturer); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateCPUModel(formats strfmt.Registry) error { + + if err := validate.Required("cpuModel", "body", m.CPUModel); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateCPUSpec(formats strfmt.Registry) error { + + if err := validate.Required("cpuSpec", "body", m.CPUSpec); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateDeviceSeries(formats strfmt.Registry) error { + + if err := validate.Required("deviceSeries", "body", m.DeviceSeries); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateDeviceType(formats strfmt.Registry) error { + + if err := validate.Required("deviceType", "body", m.DeviceType); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateHeight(formats strfmt.Registry) error { + + if err := validate.Required("height", "body", m.Height); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateIDcID(formats strfmt.Registry) error { + + if err := validate.Required("idcId", "body", m.IDcID); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateInterfaceMode(formats strfmt.Registry) error { + + if err := validate.Required("interfaceMode", "body", m.InterfaceMode); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateMemAmount(formats strfmt.Registry) error { + + if err := validate.Required("memAmount", "body", m.MemAmount); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateMemFrequency(formats strfmt.Registry) error { + + if err := validate.Required("memFrequency", "body", m.MemFrequency); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateMemSize(formats strfmt.Registry) error { + + if err := validate.Required("memSize", "body", m.MemSize); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateMemSpec(formats strfmt.Registry) error { + + if err := validate.Required("memSpec", "body", m.MemSpec); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateMemType(formats strfmt.Registry) error { + + if err := validate.Required("memType", "body", m.MemType); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateNicAmount(formats strfmt.Registry) error { + + if err := validate.Required("nicAmount", "body", m.NicAmount); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateNicRate(formats strfmt.Registry) error { + + if err := validate.Required("nicRate", "body", m.NicRate); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateVolumes(formats strfmt.Registry) error { + + if err := validate.Required("volumes", "body", m.Volumes); err != nil { + return err + } + + for i := 0; i < len(m.Volumes); i++ { + if swag.IsZero(m.Volumes[i]) { // not required + continue + } + + if m.Volumes[i] != nil { + if err := m.Volumes[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this create device type request based on the context it is used +func (m *CreateDeviceTypeRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateVolumes(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateDeviceTypeRequest) contextValidateVolumes(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Volumes); i++ { + + if m.Volumes[i] != nil { + if err := m.Volumes[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CreateDeviceTypeRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateDeviceTypeRequest) UnmarshalBinary(b []byte) error { + var res CreateDeviceTypeRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_devices_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_devices_request.go new file mode 100644 index 0000000..96bf80f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_devices_request.go @@ -0,0 +1,136 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateDevicesRequest create devices request +// +// swagger:model CreateDevicesRequest +type CreateDevicesRequest struct { + + // 机型uuid, 上传创建设备时不绑定机型,上架时才绑定机型 20240517 minping + // Required: true + Devices []*CreateDeviceSpec `json:"devices"` + + // 机房uuid + // Required: true + IDcID *string `json:"idcId"` +} + +// Validate validates this create devices request +func (m *CreateDevicesRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDevices(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIDcID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateDevicesRequest) validateDevices(formats strfmt.Registry) error { + + if err := validate.Required("devices", "body", m.Devices); err != nil { + return err + } + + for i := 0; i < len(m.Devices); i++ { + if swag.IsZero(m.Devices[i]) { // not required + continue + } + + if m.Devices[i] != nil { + if err := m.Devices[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("devices" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("devices" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CreateDevicesRequest) validateIDcID(formats strfmt.Registry) error { + + if err := validate.Required("idcId", "body", m.IDcID); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this create devices request based on the context it is used +func (m *CreateDevicesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDevices(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateDevicesRequest) contextValidateDevices(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Devices); i++ { + + if m.Devices[i] != nil { + if err := m.Devices[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("devices" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("devices" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CreateDevicesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateDevicesRequest) UnmarshalBinary(b []byte) error { + var res CreateDevicesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_idc_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_idc_request.go new file mode 100644 index 0000000..4c26cfb --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_idc_request.go @@ -0,0 +1,143 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateIdcRequest create idc request +// +// swagger:model CreateIdcRequest +type CreateIdcRequest struct { + + // 机房地址 0-256 + Address string `json:"address,omitempty"` + + // 带外密码 0-64 + IloPassword string `json:"iloPassword,omitempty"` + + // 带外用户名 0-64 + IloUser string `json:"iloUser,omitempty"` + + // 机房等级 1-64 + // Required: true + Level *string `json:"level"` + + // 机房名称 1-64 + // Required: true + Name *string `json:"name"` + + // 机房英文名称 1-64 + // Required: true + NameEn *string `json:"nameEn"` + + // 机房缩写 1-64 + // Required: true + Shortname *string `json:"shortname"` + + // 交换机密码1 0-64 + SwitchPassword1 string `json:"switchPassword1,omitempty"` + + // 交换机密码2 0-64 + SwitchPassword2 string `json:"switchPassword2,omitempty"` + + // 交换机用户1 0-64 + SwitchUser1 string `json:"switchUser1,omitempty"` + + // 交换机用户2 0-64 + SwitchUser2 string `json:"switchUser2,omitempty"` +} + +// Validate validates this create idc request +func (m *CreateIdcRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateLevel(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNameEn(formats); err != nil { + res = append(res, err) + } + + if err := m.validateShortname(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateIdcRequest) validateLevel(formats strfmt.Registry) error { + + if err := validate.Required("level", "body", m.Level); err != nil { + return err + } + + return nil +} + +func (m *CreateIdcRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +func (m *CreateIdcRequest) validateNameEn(formats strfmt.Registry) error { + + if err := validate.Required("nameEn", "body", m.NameEn); err != nil { + return err + } + + return nil +} + +func (m *CreateIdcRequest) validateShortname(formats strfmt.Registry) error { + + if err := validate.Required("shortname", "body", m.Shortname); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create idc request based on context it is used +func (m *CreateIdcRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateIdcRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateIdcRequest) UnmarshalBinary(b []byte) error { + var res CreateIdcRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_image_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_image_request.go new file mode 100644 index 0000000..c812a61 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_image_request.go @@ -0,0 +1,219 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateImageRequest create image request +// +// swagger:model CreateImageRequest +type CreateImageRequest struct { + + // 体系架构 + // Required: true + Architecture *string `json:"architecture"` + + // 引导模式【UEFI Legacy/BIOS】 + // Required: true + BootMode *string `json:"boot_mode"` + + // 数据分区信息 + DataPartition string `json:"dataPartition,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 镜像文件名称 + // Required: true + Filename *string `json:"filename"` + + // 镜像文件类型 + // Required: true + Format *string `json:"format"` + + // 文件hash值 + // Required: true + Hash *string `json:"hash"` + + // 镜像名称 + // Required: true + ImageName *string `json:"imageName"` + + // 操作系统平台 + // Required: true + OsType *string `json:"osType"` + + // 镜像类型,预置,自定义 + Source string `json:"source,omitempty"` + + // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:50GiB,swap) + SystemPartition string `json:"systemPartition,omitempty"` + + // 镜像上传地址 + // Required: true + URL *string `json:"url"` + + // 版本号 + // Required: true + Version *string `json:"Version"` +} + +// Validate validates this create image request +func (m *CreateImageRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateArchitecture(formats); err != nil { + res = append(res, err) + } + + if err := m.validateBootMode(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFilename(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFormat(formats); err != nil { + res = append(res, err) + } + + if err := m.validateHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImageName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOsType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateURL(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateImageRequest) validateArchitecture(formats strfmt.Registry) error { + + if err := validate.Required("architecture", "body", m.Architecture); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateBootMode(formats strfmt.Registry) error { + + if err := validate.Required("boot_mode", "body", m.BootMode); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateFilename(formats strfmt.Registry) error { + + if err := validate.Required("filename", "body", m.Filename); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateFormat(formats strfmt.Registry) error { + + if err := validate.Required("format", "body", m.Format); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateHash(formats strfmt.Registry) error { + + if err := validate.Required("hash", "body", m.Hash); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateImageName(formats strfmt.Registry) error { + + if err := validate.Required("imageName", "body", m.ImageName); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateOsType(formats strfmt.Registry) error { + + if err := validate.Required("osType", "body", m.OsType); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateURL(formats strfmt.Registry) error { + + if err := validate.Required("url", "body", m.URL); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateVersion(formats strfmt.Registry) error { + + if err := validate.Required("Version", "body", m.Version); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create image request based on context it is used +func (m *CreateImageRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateImageRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateImageRequest) UnmarshalBinary(b []byte) error { + var res CreateImageRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_instance_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_instance_request.go new file mode 100644 index 0000000..4782366 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_instance_request.go @@ -0,0 +1,237 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateInstanceRequest create instance request +// +// swagger:model CreateInstanceRequest +type CreateInstanceRequest struct { + + // boot mode + BootMode string `json:"boot_mode,omitempty"` + + // 创建数量 + Count int64 `json:"count,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 设备类型ID + // Required: true + DeviceTypeID *string `json:"deviceTypeId"` + + // 主机名称 + HostName string `json:"hostname,omitempty"` + + // 机房ID + // Required: true + IdcID *string `json:"idcId"` + + // 镜像ID + // Required: true + ImageID *string `json:"imageId"` + + // 实例名称 + // Required: true + InstanceName *string `json:"instanceName"` + + // 密码 + Password string `json:"password,omitempty"` + + // 项目ID + // Required: true + ProjectID *string `json:"projectId"` + + // 秘钥ID + SSHKeyID string `json:"sshKeyId,omitempty"` + + // 系统盘分区 + SystemPartition []*Partition `json:"systemPartition"` + + // 系统盘RAID ID + // Required: true + SystemVolumeRaidID *string `json:"systemVolumeRaidId"` +} + +// Validate validates this create instance request +func (m *CreateInstanceRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceTypeID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIdcID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImageID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInstanceName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProjectID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemPartition(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemVolumeRaidID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateInstanceRequest) validateDeviceTypeID(formats strfmt.Registry) error { + + if err := validate.Required("deviceTypeId", "body", m.DeviceTypeID); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateIdcID(formats strfmt.Registry) error { + + if err := validate.Required("idcId", "body", m.IdcID); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateImageID(formats strfmt.Registry) error { + + if err := validate.Required("imageId", "body", m.ImageID); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateInstanceName(formats strfmt.Registry) error { + + if err := validate.Required("instanceName", "body", m.InstanceName); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateProjectID(formats strfmt.Registry) error { + + if err := validate.Required("projectId", "body", m.ProjectID); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateSystemPartition(formats strfmt.Registry) error { + if swag.IsZero(m.SystemPartition) { // not required + return nil + } + + for i := 0; i < len(m.SystemPartition); i++ { + if swag.IsZero(m.SystemPartition[i]) { // not required + continue + } + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CreateInstanceRequest) validateSystemVolumeRaidID(formats strfmt.Registry) error { + + if err := validate.Required("systemVolumeRaidId", "body", m.SystemVolumeRaidID); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this create instance request based on the context it is used +func (m *CreateInstanceRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSystemPartition(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateInstanceRequest) contextValidateSystemPartition(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.SystemPartition); i++ { + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CreateInstanceRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateInstanceRequest) UnmarshalBinary(b []byte) error { + var res CreateInstanceRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_license_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_license_request.go new file mode 100644 index 0000000..840a879 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_license_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CreateLicenseRequest create license request +// +// swagger:model CreateLicenseRequest +type CreateLicenseRequest struct { + + // content + Content string `json:"content,omitempty"` +} + +// Validate validates this create license request +func (m *CreateLicenseRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this create license request based on context it is used +func (m *CreateLicenseRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateLicenseRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateLicenseRequest) UnmarshalBinary(b []byte) error { + var res CreateLicenseRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_o_s_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_o_s_request.go new file mode 100644 index 0000000..537575b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_o_s_request.go @@ -0,0 +1,142 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateOSRequest create o s request +// +// swagger:model CreateOSRequest +type CreateOSRequest struct { + + // 体系架构 + // Required: true + Architecture *string `json:"architecture"` + + // 位数 + // Required: true + Bits *int64 `json:"bits"` + + // 操作系统名称 + // Required: true + OsName *string `json:"osName"` + + // 操作系统平台 + // Required: true + OsType *string `json:"osType"` + + // 操作系统版本 + // Required: true + OsVersion *string `json:"osVersion"` + + // 系统用户 + SysUser string `json:"sysUser,omitempty"` +} + +// Validate validates this create o s request +func (m *CreateOSRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateArchitecture(formats); err != nil { + res = append(res, err) + } + + if err := m.validateBits(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOsName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOsType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOsVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateOSRequest) validateArchitecture(formats strfmt.Registry) error { + + if err := validate.Required("architecture", "body", m.Architecture); err != nil { + return err + } + + return nil +} + +func (m *CreateOSRequest) validateBits(formats strfmt.Registry) error { + + if err := validate.Required("bits", "body", m.Bits); err != nil { + return err + } + + return nil +} + +func (m *CreateOSRequest) validateOsName(formats strfmt.Registry) error { + + if err := validate.Required("osName", "body", m.OsName); err != nil { + return err + } + + return nil +} + +func (m *CreateOSRequest) validateOsType(formats strfmt.Registry) error { + + if err := validate.Required("osType", "body", m.OsType); err != nil { + return err + } + + return nil +} + +func (m *CreateOSRequest) validateOsVersion(formats strfmt.Registry) error { + + if err := validate.Required("osVersion", "body", m.OsVersion); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create o s request based on context it is used +func (m *CreateOSRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateOSRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateOSRequest) UnmarshalBinary(b []byte) error { + var res CreateOSRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_project_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_project_request.go new file mode 100644 index 0000000..017df2d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_project_request.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateProjectRequest create project request +// +// swagger:model CreateProjectRequest +type CreateProjectRequest struct { + + // 是否作为该用户的默认项目, [0/1], 默认为0 + IsDefault int8 `json:"isDefault,omitempty"` + + // 是否作为系统项目, [0/1], 默认为0 + IsSystem int8 `json:"isSystem,omitempty"` + + // ProjectName 1~64字符,只支持数字、大小写字母、中英文下划线“_”及中划线“-” + // Required: true + ProjectName *string `json:"projectName"` +} + +// Validate validates this create project request +func (m *CreateProjectRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateProjectName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateProjectRequest) validateProjectName(formats strfmt.Registry) error { + + if err := validate.Required("projectName", "body", m.ProjectName); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create project request based on context it is used +func (m *CreateProjectRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateProjectRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateProjectRequest) UnmarshalBinary(b []byte) error { + var res CreateProjectRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_raid_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_raid_request.go new file mode 100644 index 0000000..c52c5dc --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_raid_request.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateRaidRequest create raid request +// +// swagger:model CreateRaidRequest +type CreateRaidRequest struct { + + // raid描述(中文) + // Required: true + DescriptionEn *string `json:"descriptionEn"` + + // raid描述(英文) + // Required: true + DescriptionZh *string `json:"descriptionZh"` + + // raid名称 + // Required: true + Name *string `json:"name"` +} + +// Validate validates this create raid request +func (m *CreateRaidRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDescriptionEn(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDescriptionZh(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateRaidRequest) validateDescriptionEn(formats strfmt.Registry) error { + + if err := validate.Required("descriptionEn", "body", m.DescriptionEn); err != nil { + return err + } + + return nil +} + +func (m *CreateRaidRequest) validateDescriptionZh(formats strfmt.Registry) error { + + if err := validate.Required("descriptionZh", "body", m.DescriptionZh); err != nil { + return err + } + + return nil +} + +func (m *CreateRaidRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create raid request based on context it is used +func (m *CreateRaidRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateRaidRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateRaidRequest) UnmarshalBinary(b []byte) error { + var res CreateRaidRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_role_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_role_request.go new file mode 100644 index 0000000..744a9b3 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_role_request.go @@ -0,0 +1,122 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateRoleRequest create role request +// +// swagger:model CreateRoleRequest +type CreateRoleRequest struct { + + // 角色描述中文名称 + // Required: true + DescriptionCn *string `json:"descriptionCn"` + + // 角色描述英文名称 + // Required: true + DescriptionEn *string `json:"descriptionEn"` + + // 角色中文名称 + // Required: true + RoleNameCn *string `json:"roleNameCn"` + + // 角色英文名称 + // Required: true + RoleNameEn *string `json:"roleNameEn"` +} + +// Validate validates this create role request +func (m *CreateRoleRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDescriptionCn(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDescriptionEn(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRoleNameCn(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRoleNameEn(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateRoleRequest) validateDescriptionCn(formats strfmt.Registry) error { + + if err := validate.Required("descriptionCn", "body", m.DescriptionCn); err != nil { + return err + } + + return nil +} + +func (m *CreateRoleRequest) validateDescriptionEn(formats strfmt.Registry) error { + + if err := validate.Required("descriptionEn", "body", m.DescriptionEn); err != nil { + return err + } + + return nil +} + +func (m *CreateRoleRequest) validateRoleNameCn(formats strfmt.Registry) error { + + if err := validate.Required("roleNameCn", "body", m.RoleNameCn); err != nil { + return err + } + + return nil +} + +func (m *CreateRoleRequest) validateRoleNameEn(formats strfmt.Registry) error { + + if err := validate.Required("roleNameEn", "body", m.RoleNameEn); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create role request based on context it is used +func (m *CreateRoleRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateRoleRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateRoleRequest) UnmarshalBinary(b []byte) error { + var res CreateRoleRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_sshkey_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_sshkey_request.go new file mode 100644 index 0000000..8afaff3 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_sshkey_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateSshkeyRequest create sshkey request +// +// swagger:model CreateSshkeyRequest +type CreateSshkeyRequest struct { + + // 公钥内容,格式:^ssh-rsa AAAAB3NzaC1yc2.* + // Required: true + Key *string `json:"key"` + + // 秘钥名称 + // Required: true + Name *string `json:"name"` +} + +// Validate validates this create sshkey request +func (m *CreateSshkeyRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateKey(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateSshkeyRequest) validateKey(formats strfmt.Registry) error { + + if err := validate.Required("key", "body", m.Key); err != nil { + return err + } + + return nil +} + +func (m *CreateSshkeyRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create sshkey request based on context it is used +func (m *CreateSshkeyRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateSshkeyRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateSshkeyRequest) UnmarshalBinary(b []byte) error { + var res CreateSshkeyRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_user_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_user_request.go new file mode 100644 index 0000000..c0d97f4 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/create_user_request.go @@ -0,0 +1,126 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateUserRequest create user request +// +// swagger:model CreateUserRequest +type CreateUserRequest struct { + + // 用户默认项目uuid + DefaultProjectID string `json:"defaultProjectId,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 邮箱 + Email string `json:"email,omitempty"` + + // 语言[en_US, zh_CN] + Language string `json:"language,omitempty"` + + // 密码 明文 密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + // Required: true + Password *string `json:"password"` + + // 手机号 + PhoneNumber string `json:"phoneNumber,omitempty"` + + // 国家地区码,如86 + PhonePrefix string `json:"phonePrefix,omitempty"` + + // 角色uuid + // Required: true + RoleID *string `json:"roleId"` + + // 时区,Asia/Shanghai + Timezone string `json:"timezone,omitempty"` + + // 用户名,唯一, 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + // Required: true + UserName *string `json:"userName"` +} + +// Validate validates this create user request +func (m *CreateUserRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validatePassword(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRoleID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateUserRequest) validatePassword(formats strfmt.Registry) error { + + if err := validate.Required("password", "body", m.Password); err != nil { + return err + } + + return nil +} + +func (m *CreateUserRequest) validateRoleID(formats strfmt.Registry) error { + + if err := validate.Required("roleId", "body", m.RoleID); err != nil { + return err + } + + return nil +} + +func (m *CreateUserRequest) validateUserName(formats strfmt.Registry) error { + + if err := validate.Required("userName", "body", m.UserName); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create user request based on context it is used +func (m *CreateUserRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateUserRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateUserRequest) UnmarshalBinary(b []byte) error { + var res CreateUserRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/data_every_metric.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/data_every_metric.go new file mode 100644 index 0000000..62fc3c2 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/data_every_metric.go @@ -0,0 +1,162 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DataEveryMetric data every metric +// +// swagger:model DataEveryMetric +type DataEveryMetric struct { + + // data + Data []*MonitorDataItem `json:"data"` + + // query + Query *MonitorDataQuery `json:"query,omitempty"` +} + +// Validate validates this data every metric +func (m *DataEveryMetric) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateData(formats); err != nil { + res = append(res, err) + } + + if err := m.validateQuery(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DataEveryMetric) validateData(formats strfmt.Registry) error { + if swag.IsZero(m.Data) { // not required + return nil + } + + for i := 0; i < len(m.Data); i++ { + if swag.IsZero(m.Data[i]) { // not required + continue + } + + if m.Data[i] != nil { + if err := m.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *DataEveryMetric) validateQuery(formats strfmt.Registry) error { + if swag.IsZero(m.Query) { // not required + return nil + } + + if m.Query != nil { + if err := m.Query.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("query") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("query") + } + return err + } + } + + return nil +} + +// ContextValidate validate this data every metric based on the context it is used +func (m *DataEveryMetric) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateQuery(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DataEveryMetric) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Data); i++ { + + if m.Data[i] != nil { + if err := m.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *DataEveryMetric) contextValidateQuery(ctx context.Context, formats strfmt.Registry) error { + + if m.Query != nil { + if err := m.Query.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("query") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("query") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DataEveryMetric) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DataEveryMetric) UnmarshalBinary(b []byte) error { + var res DataEveryMetric + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/delete_alert_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/delete_alert_request.go new file mode 100644 index 0000000..00089d3 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/delete_alert_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DeleteAlertRequest delete alert request +// +// swagger:model DeleteAlertRequest +type DeleteAlertRequest struct { + + // 告警id + // Required: true + AlertID *string `json:"alertId"` +} + +// Validate validates this delete alert request +func (m *DeleteAlertRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAlertID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeleteAlertRequest) validateAlertID(formats strfmt.Registry) error { + + if err := validate.Required("alertId", "body", m.AlertID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this delete alert request based on context it is used +func (m *DeleteAlertRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeleteAlertRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeleteAlertRequest) UnmarshalBinary(b []byte) error { + var res DeleteAlertRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/delete_device_type_raid_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/delete_device_type_raid_request.go new file mode 100644 index 0000000..f5ca7fc --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/delete_device_type_raid_request.go @@ -0,0 +1,59 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeleteDeviceTypeRaidRequest delete device type raid request +// +// swagger:model DeleteDeviceTypeRaidRequest +type DeleteDeviceTypeRaidRequest struct { + + // device type + DeviceType string `json:"deviceType,omitempty"` + + // raid Id + RaidID string `json:"raidId,omitempty"` + + // volume detail + VolumeDetail string `json:"volumeDetail,omitempty"` + + // volume type + VolumeType string `json:"volumeType,omitempty"` +} + +// Validate validates this delete device type raid request +func (m *DeleteDeviceTypeRaidRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this delete device type raid request based on context it is used +func (m *DeleteDeviceTypeRaidRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeleteDeviceTypeRaidRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeleteDeviceTypeRaidRequest) UnmarshalBinary(b []byte) error { + var res DeleteDeviceTypeRaidRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/delete_instances_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/delete_instances_request.go new file mode 100644 index 0000000..c95504b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/delete_instances_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeleteInstancesRequest 批量删除实例 +// +// swagger:model DeleteInstancesRequest +type DeleteInstancesRequest struct { + + // 实例id列表 + InstanceIDs []string `json:"instance_ids"` +} + +// Validate validates this delete instances request +func (m *DeleteInstancesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this delete instances request based on context it is used +func (m *DeleteInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeleteInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeleteInstancesRequest) UnmarshalBinary(b []byte) error { + var res DeleteInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/delete_messages_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/delete_messages_request.go new file mode 100644 index 0000000..2e44060 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/delete_messages_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DeleteMessagesRequest delete messages request +// +// swagger:model DeleteMessagesRequest +type DeleteMessagesRequest struct { + + // message ids + // Required: true + MessageIds []string `json:"messageIds"` +} + +// Validate validates this delete messages request +func (m *DeleteMessagesRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateMessageIds(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeleteMessagesRequest) validateMessageIds(formats strfmt.Registry) error { + + if err := validate.Required("messageIds", "body", m.MessageIds); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this delete messages request based on context it is used +func (m *DeleteMessagesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeleteMessagesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeleteMessagesRequest) UnmarshalBinary(b []byte) error { + var res DeleteMessagesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/delete_rule_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/delete_rule_request.go new file mode 100644 index 0000000..3080e96 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/delete_rule_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DeleteRuleRequest delete rule request +// +// swagger:model DeleteRuleRequest +type DeleteRuleRequest struct { + + // 规则id + // Required: true + RuleID *string `json:"ruleId"` +} + +// Validate validates this delete rule request +func (m *DeleteRuleRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRuleID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeleteRuleRequest) validateRuleID(formats strfmt.Registry) error { + + if err := validate.Required("ruleId", "body", m.RuleID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this delete rule request based on context it is used +func (m *DeleteRuleRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeleteRuleRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeleteRuleRequest) UnmarshalBinary(b []byte) error { + var res DeleteRuleRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device.go new file mode 100644 index 0000000..d217348 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device.go @@ -0,0 +1,353 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Device device +// +// swagger:model Device +type Device struct { + + // adapter_id + AdapterID int64 `json:"adapterId,omitempty"` + + // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Architecture string `json:"architecture,omitempty"` + + // 品牌 + Brand string `json:"brand,omitempty"` + + // cpu数量 + CPUAmount int64 `json:"cpuAmount,omitempty"` + + // 单个cpu内核数 + CPUCores int64 `json:"cpuCores,omitempty"` + + // cpu频率(G) + CPUFrequency string `json:"cpuFrequency,omitempty"` + + // cpu厂商 + CPUManufacturer string `json:"cpuManufacturer,omitempty"` + + // cpu处理器型号 + CPUModel string `json:"cpuModel,omitempty"` + + // 单个cpu路数 + CPURoads int8 `json:"cpuRoads,omitempty"` + + // 机柜编码 + Cabinet string `json:"cabinet,omitempty"` + + // collect fail reason + CollectFailReason string `json:"collectFailReason,omitempty"` + + // "1"表示采集成功,"2"表示未采集,3表示采集中,4表示采集失败 + CollectStatus string `json:"collectStatus,omitempty"` + + // 拼装信息 + CPUInfo string `json:"cpuInfo,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 数据盘数量 + DataVolumeAmount int64 `json:"dataVolumeAmount,omitempty"` + + // 数据盘接口类型(SATA,SAS,NVME) + DataVolumeInterfaceType string `json:"dataVolumeInterfaceType,omitempty"` + + // 数据盘单盘大小 + DataVolumeSize int64 `json:"dataVolumeSize,omitempty"` + + // 数据盘类型(SSD,HDD) + DataVolumeType string `json:"dataVolumeType,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 设备uuid + DeviceID string `json:"deviceId,omitempty"` + + // 计算型,存储型 + DeviceSeries string `json:"deviceSeries,omitempty"` + + // 计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName,omitempty"` + + // 型号,机型规格cps.normal + DeviceType string `json:"deviceType,omitempty"` + + // 机型uuid + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // 机型名称 + DeviceTypeName string `json:"deviceTypeName,omitempty"` + + // dv info + DvInfo string `json:"dvInfo,omitempty"` + + // 添加到disk表, 系统盘1背板号 + Enclosure1 string `json:"enclosure1,omitempty"` + + // 系统盘2背板号 + Enclosure2 string `json:"Enclosure2,omitempty"` + + // ETH1子网掩码 + Eth1Mask string `json:"eth1Mask,omitempty"` + + // 网关地址 + Gateway string `json:"gateway,omitempty"` + + // gpu数量 + GpuAmount int64 `json:"gpuAmount,omitempty"` + + // gpu info + GpuInfo string `json:"gpuInfo,omitempty"` + + // gpu厂商 + GpuManufacturer string `json:"gpuManufacturer,omitempty"` + + // gpu处理器型号 + GpuModel string `json:"gpuModel,omitempty"` + + // 设备ID编号 + ID int64 `json:"id,omitempty"` + + // idcname + IDcNameEn string `json:"idcNameEn,omitempty"` + + // 机房uuid + // Required: true + IdcID *string `json:"idcId"` + + // 机房名称 + IdcName string `json:"idcName,omitempty"` + + // 带外管理IP + IloIP string `json:"iloIp,omitempty"` + + // 带外账号密码 + IloPassword string `json:"iloPassword,omitempty"` + + // 带外账号 + IloUser string `json:"iloUser,omitempty"` + + // 实例镜像名称 + ImageName string `json:"imageName,omitempty"` + + // 实例创建时间 + InstanceCreatedTime string `json:"instanceCreatedTime,omitempty"` + + // 实例描述 + InstanceDescription string `json:"instanceDescription,omitempty"` + + // 实例id + InstanceID string `json:"instanceId,omitempty"` + + // 实例名称 + InstanceName string `json:"instanceName,omitempty"` + + // 实例失败原因 + InstanceReason string `json:"instanceReason,omitempty"` + + // 实例状态 + InstanceStatus string `json:"instanceStatus,omitempty"` + + // 实例状态 + InstanceStatusName string `json:"instanceStatusName,omitempty"` + + // 【网口模式】【网络设置】: bond单网口,dual双网口 + InterfaceMode string `json:"interfaceMode,omitempty"` + + // is need raid + IsNeedRaid string `json:"isNeedRaid,omitempty"` + + // 实例是否锁定 锁定locked 未锁定unlocked + Locked string `json:"locked,omitempty"` + + // MAC1(eth0) + Mac1 string `json:"mac1,omitempty"` + + // MAC2(eth2) + Mac2 string `json:"mac2,omitempty"` + + // 设备状态: 未装机,已装机 + ManageStatus string `json:"manageStatus,omitempty"` + + // 设备状态: 未装机,已装机 + ManageStatusName string `json:"manageStatusName,omitempty"` + + // 子网掩码 + Mask string `json:"mask,omitempty"` + + // 内存数量 + MemAmount int64 `json:"memAmount,omitempty"` + + // 内存主频(MHz) + MemFrequency int64 `json:"memFrequency,omitempty"` + + // mem info + MemInfo string `json:"memInfo,omitempty"` + + // 单个内存大小(GB) + MemSize int64 `json:"memSize,omitempty"` + + // 内存接口(如DDR3,DDR4) + MemType string `json:"memType,omitempty"` + + // 型号 + Model string `json:"model,omitempty"` + + // 网卡数量 + NicAmount int64 `json:"nicAmount,omitempty"` + + // nic info + NicInfo string `json:"nicInfo,omitempty"` + + // 网卡传输速率(GE) + NicRate int64 `json:"nicRate,omitempty"` + + // eth1内网IPV4 + PrivateEth1IPV4 string `json:"privateEth1Ipv4,omitempty"` + + // eth1内网IPV6 + PrivateEth1IPV6 string `json:"privateEth1Ipv6,omitempty"` + + // 内网IPV4 + PrivateIPV4 string `json:"privateIpv4,omitempty"` + + // 内网IPV6 + PrivateIPV6 string `json:"privateIpv6,omitempty"` + + // raid工具:(megacli64等) + RaidDriver string `json:"raidDriver,omitempty"` + + // 设备状态变更失败原因 + Reason string `json:"reason,omitempty"` + + // 系统盘1槽位 + Slot1 int64 `json:"slot1,omitempty"` + + // 系统盘2槽位 + Slot2 int64 `json:"slot2,omitempty"` + + // 设备SN + Sn string `json:"sn,omitempty"` + + // sv info + SvInfo string `json:"svInfo,omitempty"` + + // 网口交换机IP + SwitchIP string `json:"switchIp,omitempty"` + + // 交换机1ip + SwitchIP1 string `json:"switchIp1,omitempty"` + + // 交换机2ip + SwitchIP2 string `json:"switchIp2,omitempty"` + + // 交换机1登录密码 + SwitchPassword1 string `json:"switchPassword1,omitempty"` + + // 交换机2登录密码 + SwitchPassword2 string `json:"switchPassword2,omitempty"` + + // 交换机1port + SwitchPort1 string `json:"switchPort1,omitempty"` + + // 交换机2port + SwitchPort2 string `json:"switchPort2,omitempty"` + + // 交换机1登录账号,如果为空,取所在机房的值 + SwitchUser1 string `json:"switchUser1,omitempty"` + + // 交换机2登录账号,如果为空,取所在机房的值 + SwitchUser2 string `json:"switchUser2,omitempty"` + + // 系统盘数量 + SystemVolumeAmount int64 `json:"systemVolumeAmount,omitempty"` + + // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeInterfaceType string `json:"systemVolumeInterfaceType,omitempty"` + + // 系统盘单盘大小 + SystemVolumeSize int64 `json:"systemVolumeSize,omitempty"` + + // 系统盘类型(SSD,HDD) + SystemVolumeType string `json:"systemVolumeType,omitempty"` + + // U位 + UPosition string `json:"uPosition,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 实例归属用户uuid + UserID string `json:"userId,omitempty"` + + // 实例归属用户名称 + UserName string `json:"userName,omitempty"` +} + +// Validate validates this device +func (m *Device) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateIdcID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Device) validateIdcID(formats strfmt.Registry) error { + + if err := validate.Required("idcId", "body", m.IdcID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this device based on context it is used +func (m *Device) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Device) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Device) UnmarshalBinary(b []byte) error { + var res Device + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_associate_device_type_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_associate_device_type_request.go new file mode 100644 index 0000000..e9831fe --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_associate_device_type_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DeviceAssociateDeviceTypeRequest device associate device type request +// +// swagger:model DeviceAssociateDeviceTypeRequest +type DeviceAssociateDeviceTypeRequest struct { + + // 设备ID + // Required: true + DeviceID *string `json:"deviceId"` + + // 设备类型id + // Required: true + DeviceTypeID *string `json:"deviceTypeId"` +} + +// Validate validates this device associate device type request +func (m *DeviceAssociateDeviceTypeRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDeviceTypeID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceAssociateDeviceTypeRequest) validateDeviceID(formats strfmt.Registry) error { + + if err := validate.Required("deviceId", "body", m.DeviceID); err != nil { + return err + } + + return nil +} + +func (m *DeviceAssociateDeviceTypeRequest) validateDeviceTypeID(formats strfmt.Registry) error { + + if err := validate.Required("deviceTypeId", "body", m.DeviceTypeID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this device associate device type request based on context it is used +func (m *DeviceAssociateDeviceTypeRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceAssociateDeviceTypeRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceAssociateDeviceTypeRequest) UnmarshalBinary(b []byte) error { + var res DeviceAssociateDeviceTypeRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_disks.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_disks.go new file mode 100644 index 0000000..a855c05 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_disks.go @@ -0,0 +1,230 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceDisks device disks +// +// swagger:model DeviceDisks +type DeviceDisks struct { + + // disks + Disks []*Disk `json:"disks"` + + // panfu + Panfu []*Disk `json:"panfu"` + + // volumes + Volumes []*VolumeIt `json:"volumes"` +} + +// Validate validates this device disks +func (m *DeviceDisks) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDisks(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePanfu(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVolumes(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceDisks) validateDisks(formats strfmt.Registry) error { + if swag.IsZero(m.Disks) { // not required + return nil + } + + for i := 0; i < len(m.Disks); i++ { + if swag.IsZero(m.Disks[i]) { // not required + continue + } + + if m.Disks[i] != nil { + if err := m.Disks[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("disks" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("disks" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *DeviceDisks) validatePanfu(formats strfmt.Registry) error { + if swag.IsZero(m.Panfu) { // not required + return nil + } + + for i := 0; i < len(m.Panfu); i++ { + if swag.IsZero(m.Panfu[i]) { // not required + continue + } + + if m.Panfu[i] != nil { + if err := m.Panfu[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("panfu" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("panfu" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *DeviceDisks) validateVolumes(formats strfmt.Registry) error { + if swag.IsZero(m.Volumes) { // not required + return nil + } + + for i := 0; i < len(m.Volumes); i++ { + if swag.IsZero(m.Volumes[i]) { // not required + continue + } + + if m.Volumes[i] != nil { + if err := m.Volumes[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this device disks based on the context it is used +func (m *DeviceDisks) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDisks(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidatePanfu(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateVolumes(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceDisks) contextValidateDisks(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Disks); i++ { + + if m.Disks[i] != nil { + if err := m.Disks[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("disks" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("disks" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *DeviceDisks) contextValidatePanfu(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Panfu); i++ { + + if m.Panfu[i] != nil { + if err := m.Panfu[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("panfu" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("panfu" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *DeviceDisks) contextValidateVolumes(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Volumes); i++ { + + if m.Volumes[i] != nil { + if err := m.Volumes[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceDisks) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceDisks) UnmarshalBinary(b []byte) error { + var res DeviceDisks + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_info.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_info.go new file mode 100644 index 0000000..a70a4e4 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceInfo device info +// +// swagger:model DeviceInfo +type DeviceInfo struct { + + // device + Device *Device `json:"device,omitempty"` +} + +// Validate validates this device info +func (m *DeviceInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDevice(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceInfo) validateDevice(formats strfmt.Registry) error { + if swag.IsZero(m.Device) { // not required + return nil + } + + if m.Device != nil { + if err := m.Device.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("device") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("device") + } + return err + } + } + + return nil +} + +// ContextValidate validate this device info based on the context it is used +func (m *DeviceInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDevice(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceInfo) contextValidateDevice(ctx context.Context, formats strfmt.Registry) error { + + if m.Device != nil { + if err := m.Device.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("device") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("device") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceInfo) UnmarshalBinary(b []byte) error { + var res DeviceInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_list.go new file mode 100644 index 0000000..0f58c64 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceList device list +// +// swagger:model DeviceList +type DeviceList struct { + + // 设备列表 + Devices []*Device `json:"devices"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this device list +func (m *DeviceList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDevices(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceList) validateDevices(formats strfmt.Registry) error { + if swag.IsZero(m.Devices) { // not required + return nil + } + + for i := 0; i < len(m.Devices); i++ { + if swag.IsZero(m.Devices[i]) { // not required + continue + } + + if m.Devices[i] != nil { + if err := m.Devices[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("devices" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("devices" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this device list based on the context it is used +func (m *DeviceList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDevices(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceList) contextValidateDevices(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Devices); i++ { + + if m.Devices[i] != nil { + if err := m.Devices[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("devices" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("devices" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceList) UnmarshalBinary(b []byte) error { + var res DeviceList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_stock.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_stock.go new file mode 100644 index 0000000..5ad0cb9 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_stock.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceStock device stock +// +// swagger:model DeviceStock +type DeviceStock struct { + + // 库存量 + Stocks int64 `json:"stocks,omitempty"` +} + +// Validate validates this device stock +func (m *DeviceStock) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this device stock based on context it is used +func (m *DeviceStock) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceStock) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceStock) UnmarshalBinary(b []byte) error { + var res DeviceStock + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_type.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_type.go new file mode 100644 index 0000000..b00da40 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_type.go @@ -0,0 +1,277 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceType device type +// +// swagger:model DeviceType +type DeviceType struct { + + // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Architecture string `json:"architecture,omitempty"` + + // boot模式 + BootMode string `json:"boot_mode,omitempty"` + + // cpu数量 + CPUAmount int64 `json:"cpuAmount,omitempty"` + + // 单个cpu内核数 + CPUCores int64 `json:"cpuCores,omitempty"` + + // cpu频率(G) + CPUFrequency string `json:"cpuFrequency,omitempty"` + + // cpu厂商 + CPUManufacturer string `json:"cpuManufacturer,omitempty"` + + // cpu处理器型号 + CPUModel string `json:"cpuModel,omitempty"` + + // 拼装信息 + CPUInfo string `json:"cpuInfo,omitempty"` + + // CPU 规格,预置还是其它 + CPUSpec string `json:"cpuSpec,omitempty"` + + // 数据盘类型(SSD,HDD) + // DataVolumeType string `json:"dataVolumeType"` + // 数据盘接口类型(SATA,SAS,NVME) + // DataVolumeInterfaceType string `json:"dataVolumeInterfaceType"` + // 数据盘单盘大小 + // DataVolumeSize int `json:"dataVolumeSize"` + // 数据盘单位(GB,TB) + // DataVolumeUnit string `json:"dataVolumeUnit"` + // 数据盘数量 + // DataVolumeAmount int `json:"dataVolumeAmount"` + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // device count + DeviceCount int64 `json:"deviceCount,omitempty"` + + // 机型类型,如计算型,存储型 + DeviceSeries string `json:"deviceSeries,omitempty"` + + // 机型类型,如计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName,omitempty"` + + // 机型规格, cps.c.normal + DeviceType string `json:"deviceType,omitempty"` + + // 机型uuid + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // dv info + DvInfo string `json:"dvInfo,omitempty"` + + // gpu数量 + GpuAmount int64 `json:"gpuAmount,omitempty"` + + // gpu info + GpuInfo string `json:"gpuInfo,omitempty"` + + // gpu厂商 + GpuManufacturer string `json:"gpuManufacturer,omitempty"` + + // gpu处理器型号 + GpuModel string `json:"gpuModel,omitempty"` + + // 显示机型高度 + Height int64 `json:"height,omitempty"` + + // ID + ID int64 `json:"id,omitempty"` + + // 机房uuid + IDcID string `json:"idcId,omitempty"` + + // 机房名称 + IDcName string `json:"idcName,omitempty"` + + // 机房名称 + IDcNameEn string `json:"idcNameEn,omitempty"` + + // instance count + InstanceCount int64 `json:"instanceCount,omitempty"` + + // instance status + InstanceStatus []string `json:"instanceStatus"` + + // bond单网口,dual双网口 + InterfaceMode string `json:"interfaceMode,omitempty"` + + // 阵列卡是否需要配置 + IsNeedRaid string `json:"isNeedRaid,omitempty"` + + // 内存数量 + MemAmount int64 `json:"memAmount,omitempty"` + + // 内存主频(MHz) + MemFrequency int64 `json:"memFrequency,omitempty"` + + // mem info + MemInfo string `json:"memInfo,omitempty"` + + // 单个内存大小(GB) + MemSize int64 `json:"memSize,omitempty"` + + // 内存 规格,预置还是其它 + MemSpec string `json:"memSpec,omitempty"` + + // 内存接口(如DDR3,DDR4) + MemType string `json:"memType,omitempty"` + + // 机型名称,如计算效能型,标准计算型 + Name string `json:"name,omitempty"` + + // 网卡数量 + NicAmount int64 `json:"nicAmount,omitempty"` + + // nic info + NicInfo string `json:"nicInfo,omitempty"` + + // 网卡传输速率(GE) + NicRate int64 `json:"nicRate,omitempty"` + + // 系统盘raid + Raid string `json:"raid,omitempty"` + + // 系统盘类型(SSD,HDD) + // SystemVolumeType string `json:"systemVolumeType"` + // 系统盘接口类型(SATA,SAS,NVME) + // SystemVolumeInterfaceType string `json:"systemVolumeInterfaceType"` + // 系统盘单盘大小 + // SystemVolumeSize int `json:"systemVolumeSize"` + // 系统盘单位(GB,TB) + // SystemVolumeUnit string `json:"systemVolumeUnit"` + // 系统盘数量 + // SystemVolumeAmount int `json:"systemVolumeAmount"`*/ + // 是否做raid,[RAID/NORAID] + RaidCan string `json:"raidCan,omitempty"` + + // StockAvailable 可用库存 + StockAvailable int64 `json:"stockAvailable,omitempty"` + + // sv info + SvInfo string `json:"svInfo,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // volumes + Volumes []*Volume `json:"volumes"` +} + +// Validate validates this device type +func (m *DeviceType) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateVolumes(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceType) validateVolumes(formats strfmt.Registry) error { + if swag.IsZero(m.Volumes) { // not required + return nil + } + + for i := 0; i < len(m.Volumes); i++ { + if swag.IsZero(m.Volumes[i]) { // not required + continue + } + + if m.Volumes[i] != nil { + if err := m.Volumes[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this device type based on the context it is used +func (m *DeviceType) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateVolumes(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceType) contextValidateVolumes(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Volumes); i++ { + + if m.Volumes[i] != nil { + if err := m.Volumes[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceType) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceType) UnmarshalBinary(b []byte) error { + var res DeviceType + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_type_id.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_type_id.go new file mode 100644 index 0000000..05dee3c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_type_id.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DeviceTypeID device type Id +// +// swagger:model DeviceTypeId +type DeviceTypeID struct { + + // 机型uuid + // Required: true + DeviceTypeID *string `json:"deviceTypeId"` +} + +// Validate validates this device type Id +func (m *DeviceTypeID) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceTypeID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceTypeID) validateDeviceTypeID(formats strfmt.Registry) error { + + if err := validate.Required("deviceTypeId", "body", m.DeviceTypeID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this device type Id based on context it is used +func (m *DeviceTypeID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceTypeID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceTypeID) UnmarshalBinary(b []byte) error { + var res DeviceTypeID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_type_info.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_type_info.go new file mode 100644 index 0000000..382e25c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_type_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceTypeInfo device type info +// +// swagger:model DeviceTypeInfo +type DeviceTypeInfo struct { + + // device type + DeviceType *DeviceType `json:"deviceType,omitempty"` +} + +// Validate validates this device type info +func (m *DeviceTypeInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceType(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceTypeInfo) validateDeviceType(formats strfmt.Registry) error { + if swag.IsZero(m.DeviceType) { // not required + return nil + } + + if m.DeviceType != nil { + if err := m.DeviceType.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceType") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceType") + } + return err + } + } + + return nil +} + +// ContextValidate validate this device type info based on the context it is used +func (m *DeviceTypeInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDeviceType(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceTypeInfo) contextValidateDeviceType(ctx context.Context, formats strfmt.Registry) error { + + if m.DeviceType != nil { + if err := m.DeviceType.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceType") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceType") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceTypeInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceTypeInfo) UnmarshalBinary(b []byte) error { + var res DeviceTypeInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_type_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_type_list.go new file mode 100644 index 0000000..8959ae5 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/device_type_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceTypeList device type list +// +// swagger:model DeviceTypeList +type DeviceTypeList struct { + + // 机型列表 + DeviceTypes []*DeviceType `json:"deviceTypes"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this device type list +func (m *DeviceTypeList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceTypes(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceTypeList) validateDeviceTypes(formats strfmt.Registry) error { + if swag.IsZero(m.DeviceTypes) { // not required + return nil + } + + for i := 0; i < len(m.DeviceTypes); i++ { + if swag.IsZero(m.DeviceTypes[i]) { // not required + continue + } + + if m.DeviceTypes[i] != nil { + if err := m.DeviceTypes[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceTypes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceTypes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this device type list based on the context it is used +func (m *DeviceTypeList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDeviceTypes(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceTypeList) contextValidateDeviceTypes(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.DeviceTypes); i++ { + + if m.DeviceTypes[i] != nil { + if err := m.DeviceTypes[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceTypes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceTypes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceTypeList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceTypeList) UnmarshalBinary(b []byte) error { + var res DeviceTypeList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/disable_rule_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/disable_rule_request.go new file mode 100644 index 0000000..ce8ec67 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/disable_rule_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DisableRuleRequest disable rule request +// +// swagger:model DisableRuleRequest +type DisableRuleRequest struct { + + // 规则id + // Required: true + RuleID *string `json:"ruleId"` +} + +// Validate validates this disable rule request +func (m *DisableRuleRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRuleID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DisableRuleRequest) validateRuleID(formats strfmt.Registry) error { + + if err := validate.Required("ruleId", "body", m.RuleID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this disable rule request based on context it is used +func (m *DisableRuleRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DisableRuleRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DisableRuleRequest) UnmarshalBinary(b []byte) error { + var res DisableRuleRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/disk.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/disk.go new file mode 100644 index 0000000..cdd713e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/disk.go @@ -0,0 +1,113 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Disk disk +// +// swagger:model Disk +type Disk struct { + + // adapter ID + AdapterID int64 `json:"adapterId,omitempty"` + + // created by + CreatedBy string `json:"createdBy,omitempty"` + + // created time + CreatedTime int64 `json:"createdTime,omitempty"` + + // deleted time + DeletedTime int64 `json:"deletedTime,omitempty"` + + // device ID + DeviceID string `json:"deviceId,omitempty"` + + // device path + DevicePath string `json:"devicePath,omitempty"` + + // disk Id + DiskID string `json:"diskId,omitempty"` + + // 磁盘类型:system,data + DiskType string `json:"diskType,omitempty"` + + // enclosure + Enclosure string `json:"enclosure,omitempty"` + + // index + Index int64 `json:"index,omitempty"` + + // is del + IsDel int8 `json:"isDel,omitempty"` + + // media type + MediaType string `json:"mediaType,omitempty"` + + // name + Name string `json:"name,omitempty"` + + // pd type + PdType string `json:"pdType,omitempty"` + + // 是否选中 + Selected bool `json:"selected,omitempty"` + + // serial number + SerialNumber string `json:"serialNumber,omitempty"` + + // size + Size string `json:"size,omitempty"` + + // size unit + SizeUnit string `json:"sizeUnit,omitempty"` + + // slot + Slot int64 `json:"slot,omitempty"` + + // control/mvme/panfu + Types string `json:"types,omitempty"` + + // updated by + UpdatedBy string `json:"updatedBy,omitempty"` + + // updated time + UpdatedTime int64 `json:"updatedTime,omitempty"` +} + +// Validate validates this disk +func (m *Disk) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this disk based on context it is used +func (m *Disk) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Disk) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Disk) UnmarshalBinary(b []byte) error { + var res Disk + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/dissociated_image_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/dissociated_image_request.go new file mode 100644 index 0000000..c3a2d59 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/dissociated_image_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DissociatedImageRequest dissociated image request +// +// swagger:model DissociatedImageRequest +type DissociatedImageRequest struct { + + // 设备类型id + // Required: true + DeviceTypeID *string `json:"deviceTypeId"` + + // 镜像ID + // Required: true + ImageID *string `json:"imageId"` +} + +// Validate validates this dissociated image request +func (m *DissociatedImageRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceTypeID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImageID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DissociatedImageRequest) validateDeviceTypeID(formats strfmt.Registry) error { + + if err := validate.Required("deviceTypeId", "body", m.DeviceTypeID); err != nil { + return err + } + + return nil +} + +func (m *DissociatedImageRequest) validateImageID(formats strfmt.Registry) error { + + if err := validate.Required("imageId", "body", m.ImageID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this dissociated image request based on context it is used +func (m *DissociatedImageRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DissociatedImageRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DissociatedImageRequest) UnmarshalBinary(b []byte) error { + var res DissociatedImageRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/edit_rule_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/edit_rule_request.go new file mode 100644 index 0000000..30887f9 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/edit_rule_request.go @@ -0,0 +1,255 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// EditRuleRequest edit rule request +// +// swagger:model EditRuleRequest +type EditRuleRequest struct { + + // 盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag,omitempty"` + + // 维度 [instance、disk、mountpoint、nic] + // Required: true + Dimension *string `json:"dimension"` + + // 实例id列表 + // Required: true + InstanceIds []string `json:"instanceIds"` + + // 资源类型,目前只支持instance + // Required: true + Resource *string `json:"resource"` + + // 规则id + // Required: true + RuleID *string `json:"ruleId"` + + // 规则名称 + // Required: true + RuleName *string `json:"ruleName"` + + // 触发条件 + // Required: true + TriggerOption []*RuleTrigger `json:"triggerOption"` + + // notice option + // Required: true + NoticeOption *RuleNotice `json:"noticeOption"` +} + +// Validate validates this edit rule request +func (m *EditRuleRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDimension(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInstanceIds(formats); err != nil { + res = append(res, err) + } + + if err := m.validateResource(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRuleID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRuleName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTriggerOption(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNoticeOption(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *EditRuleRequest) validateDimension(formats strfmt.Registry) error { + + if err := validate.Required("dimension", "body", m.Dimension); err != nil { + return err + } + + return nil +} + +func (m *EditRuleRequest) validateInstanceIds(formats strfmt.Registry) error { + + if err := validate.Required("instanceIds", "body", m.InstanceIds); err != nil { + return err + } + + return nil +} + +func (m *EditRuleRequest) validateResource(formats strfmt.Registry) error { + + if err := validate.Required("resource", "body", m.Resource); err != nil { + return err + } + + return nil +} + +func (m *EditRuleRequest) validateRuleID(formats strfmt.Registry) error { + + if err := validate.Required("ruleId", "body", m.RuleID); err != nil { + return err + } + + return nil +} + +func (m *EditRuleRequest) validateRuleName(formats strfmt.Registry) error { + + if err := validate.Required("ruleName", "body", m.RuleName); err != nil { + return err + } + + return nil +} + +func (m *EditRuleRequest) validateTriggerOption(formats strfmt.Registry) error { + + if err := validate.Required("triggerOption", "body", m.TriggerOption); err != nil { + return err + } + + for i := 0; i < len(m.TriggerOption); i++ { + if swag.IsZero(m.TriggerOption[i]) { // not required + continue + } + + if m.TriggerOption[i] != nil { + if err := m.TriggerOption[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *EditRuleRequest) validateNoticeOption(formats strfmt.Registry) error { + + if err := validate.Required("noticeOption", "body", m.NoticeOption); err != nil { + return err + } + + if m.NoticeOption != nil { + if err := m.NoticeOption.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("noticeOption") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("noticeOption") + } + return err + } + } + + return nil +} + +// ContextValidate validate this edit rule request based on the context it is used +func (m *EditRuleRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateTriggerOption(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateNoticeOption(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *EditRuleRequest) contextValidateTriggerOption(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.TriggerOption); i++ { + + if m.TriggerOption[i] != nil { + if err := m.TriggerOption[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *EditRuleRequest) contextValidateNoticeOption(ctx context.Context, formats strfmt.Registry) error { + + if m.NoticeOption != nil { + if err := m.NoticeOption.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("noticeOption") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("noticeOption") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *EditRuleRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *EditRuleRequest) UnmarshalBinary(b []byte) error { + var res EditRuleRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/enable_rule_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/enable_rule_request.go new file mode 100644 index 0000000..e00eba4 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/enable_rule_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// EnableRuleRequest enable rule request +// +// swagger:model EnableRuleRequest +type EnableRuleRequest struct { + + // 规则id + // Required: true + RuleID *string `json:"ruleId"` +} + +// Validate validates this enable rule request +func (m *EnableRuleRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRuleID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *EnableRuleRequest) validateRuleID(formats strfmt.Registry) error { + + if err := validate.Required("ruleId", "body", m.RuleID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this enable rule request based on context it is used +func (m *EnableRuleRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *EnableRuleRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *EnableRuleRequest) UnmarshalBinary(b []byte) error { + var res EnableRuleRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/error_response.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/error_response.go new file mode 100644 index 0000000..e39f94b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/error_response.go @@ -0,0 +1,56 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ErrorResponse error response +// +// swagger:model ErrorResponse +type ErrorResponse struct { + + // 错误码 + Code int64 `json:"code,omitempty"` + + // 错误信息 + Message string `json:"message,omitempty"` + + // 错误状态 + Status string `json:"status,omitempty"` +} + +// Validate validates this error response +func (m *ErrorResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this error response based on context it is used +func (m *ErrorResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ErrorResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ErrorResponse) UnmarshalBinary(b []byte) error { + var res ErrorResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/has_unread_message.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/has_unread_message.go new file mode 100644 index 0000000..c3a5dce --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/has_unread_message.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HasUnreadMessage has unread message +// +// swagger:model HasUnreadMessage +type HasUnreadMessage struct { + + // has unread + HasUnread bool `json:"hasUnread,omitempty"` +} + +// Validate validates this has unread message +func (m *HasUnreadMessage) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this has unread message based on context it is used +func (m *HasUnreadMessage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HasUnreadMessage) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HasUnreadMessage) UnmarshalBinary(b []byte) error { + var res HasUnreadMessage + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/idc.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/idc.go new file mode 100644 index 0000000..bbe18a9 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/idc.go @@ -0,0 +1,98 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Idc idc +// +// swagger:model Idc +type Idc struct { + + // 机房地址 + Address string `json:"address,omitempty"` + + // 创建时间 + CreateTime string `json:"createTime,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // ID + ID int64 `json:"id,omitempty"` + + // 机房uuid + IDcID string `json:"idcId,omitempty"` + + // 机房公用带外管理password + IloPassword string `json:"iloPassword,omitempty"` + + // 机房公用带外管理user + IloUser string `json:"iloUser,omitempty"` + + // 机房等级 + Level string `json:"level,omitempty"` + + // 机房名称 + Name string `json:"name,omitempty"` + + // 机房名称en + NameEn string `json:"nameEn,omitempty"` + + // shortname + Shortname string `json:"shortname,omitempty"` + + // 交换机密码1 + SwitchPassword1 string `json:"switchPassword1,omitempty"` + + // 交换机密码2 + SwitchPassword2 string `json:"switchPassword2,omitempty"` + + // 交换机用户名1 + SwitchUser1 string `json:"switchUser1,omitempty"` + + // 交换机用户名2 + SwitchUser2 string `json:"switchUser2,omitempty"` + + // 修改时间 + UpdateTime string `json:"updateTime,omitempty"` + + // 修改用户 + UpdatedBy string `json:"updatedBy,omitempty"` +} + +// Validate validates this idc +func (m *Idc) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this idc based on context it is used +func (m *Idc) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Idc) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Idc) UnmarshalBinary(b []byte) error { + var res Idc + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/idc_id.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/idc_id.go new file mode 100644 index 0000000..3e7f724 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/idc_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// IdcID idc ID +// +// swagger:model IdcID +type IdcID struct { + + // 机房id + IdcID string `json:"idcId,omitempty"` +} + +// Validate validates this idc ID +func (m *IdcID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this idc ID based on context it is used +func (m *IdcID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *IdcID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *IdcID) UnmarshalBinary(b []byte) error { + var res IdcID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/idc_info.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/idc_info.go new file mode 100644 index 0000000..8ca49a0 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/idc_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// IdcInfo idc info +// +// swagger:model IdcInfo +type IdcInfo struct { + + // idc + Idc *Idc `json:"idc,omitempty"` +} + +// Validate validates this idc info +func (m *IdcInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateIdc(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *IdcInfo) validateIdc(formats strfmt.Registry) error { + if swag.IsZero(m.Idc) { // not required + return nil + } + + if m.Idc != nil { + if err := m.Idc.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("idc") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("idc") + } + return err + } + } + + return nil +} + +// ContextValidate validate this idc info based on the context it is used +func (m *IdcInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateIdc(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *IdcInfo) contextValidateIdc(ctx context.Context, formats strfmt.Registry) error { + + if m.Idc != nil { + if err := m.Idc.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("idc") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("idc") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *IdcInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *IdcInfo) UnmarshalBinary(b []byte) error { + var res IdcInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/idc_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/idc_list.go new file mode 100644 index 0000000..3cb1fe4 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/idc_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// IdcList idc list +// +// swagger:model IdcList +type IdcList struct { + + // 机房列表 + Idcs []*Idc `json:"idcs"` + + // 页数 + PageNumber int64 `json:"pageNumber,omitempty"` + + // 页大小 + PageSize int64 `json:"pageSize,omitempty"` + + // 总条数 + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this idc list +func (m *IdcList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateIdcs(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *IdcList) validateIdcs(formats strfmt.Registry) error { + if swag.IsZero(m.Idcs) { // not required + return nil + } + + for i := 0; i < len(m.Idcs); i++ { + if swag.IsZero(m.Idcs[i]) { // not required + continue + } + + if m.Idcs[i] != nil { + if err := m.Idcs[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("idcs" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("idcs" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this idc list based on the context it is used +func (m *IdcList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateIdcs(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *IdcList) contextValidateIdcs(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Idcs); i++ { + + if m.Idcs[i] != nil { + if err := m.Idcs[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("idcs" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("idcs" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *IdcList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *IdcList) UnmarshalBinary(b []byte) error { + var res IdcList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/image.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/image.go new file mode 100644 index 0000000..fee3c1f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/image.go @@ -0,0 +1,119 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Image image +// +// swagger:model Image +type Image struct { + + // 架构:x86/x64/i386/ + Architecture string `json:"architecture,omitempty"` + + // boot模式 + BootMode string `json:"bootMode,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 数据分区信息 + DataPartition string `json:"dataPartition,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 绑定了机型数量 + DeviceTypeNum int64 `json:"deviceTypeNum,omitempty"` + + // 镜像文件名称 + Filename string `json:"filename,omitempty"` + + // 镜像格式(qcow2、tar) + Format string `json:"format,omitempty"` + + // 镜像校验码 + Hash string `json:"hash,omitempty"` + + // ID + ID uint64 `json:"id,omitempty"` + + // 镜像uuid + ImageID string `json:"imageId,omitempty"` + + // 镜像名称 + ImageName string `json:"imageName,omitempty"` + + // 是否绑定了某个机型 + IsBind bool `json:"isBind,omitempty"` + + // 源os uuid + OsID string `json:"osId,omitempty"` + + // CentOS 7.2 64-bit + OsName string `json:"osName,omitempty"` + + // 操作系统分类:linux/windows + OsType string `json:"osType,omitempty"` + + // 操作系统版本 + OsVersion string `json:"osVersion,omitempty"` + + // 镜像来源(common通用、customize定制、user_defined自定义) + Source string `json:"source,omitempty"` + + // 镜像来源(common通用、customize定制、user_defined自定义) + SourceName string `json:"sourceName,omitempty"` + + // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + SystemPartition string `json:"systemPartition,omitempty"` + + // 镜像源路径 + URL string `json:"url,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` +} + +// Validate validates this image +func (m *Image) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this image based on context it is used +func (m *Image) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Image) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Image) UnmarshalBinary(b []byte) error { + var res Image + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/image_id.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/image_id.go new file mode 100644 index 0000000..0d8e965 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/image_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ImageID image Id +// +// swagger:model ImageId +type ImageID struct { + + // 镜像uuid + ImageID string `json:"imageId,omitempty"` +} + +// Validate validates this image Id +func (m *ImageID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this image Id based on context it is used +func (m *ImageID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ImageID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ImageID) UnmarshalBinary(b []byte) error { + var res ImageID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/image_info.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/image_info.go new file mode 100644 index 0000000..7064fb8 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/image_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ImageInfo image info +// +// swagger:model ImageInfo +type ImageInfo struct { + + // image + Image *Image `json:"image,omitempty"` +} + +// Validate validates this image info +func (m *ImageInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateImage(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ImageInfo) validateImage(formats strfmt.Registry) error { + if swag.IsZero(m.Image) { // not required + return nil + } + + if m.Image != nil { + if err := m.Image.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("image") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("image") + } + return err + } + } + + return nil +} + +// ContextValidate validate this image info based on the context it is used +func (m *ImageInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateImage(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ImageInfo) contextValidateImage(ctx context.Context, formats strfmt.Registry) error { + + if m.Image != nil { + if err := m.Image.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("image") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("image") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ImageInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ImageInfo) UnmarshalBinary(b []byte) error { + var res ImageInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/image_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/image_list.go new file mode 100644 index 0000000..61ce37d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/image_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ImageList image list +// +// swagger:model ImageList +type ImageList struct { + + // 镜像实体列表 + Images []*Image `json:"images"` + + // 页数 + PageNumber int64 `json:"pageNumber,omitempty"` + + // 页大小 + PageSize int64 `json:"pageSize,omitempty"` + + // 总条数 + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this image list +func (m *ImageList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateImages(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ImageList) validateImages(formats strfmt.Registry) error { + if swag.IsZero(m.Images) { // not required + return nil + } + + for i := 0; i < len(m.Images); i++ { + if swag.IsZero(m.Images[i]) { // not required + continue + } + + if m.Images[i] != nil { + if err := m.Images[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("images" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("images" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this image list based on the context it is used +func (m *ImageList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateImages(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ImageList) contextValidateImages(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Images); i++ { + + if m.Images[i] != nil { + if err := m.Images[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("images" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("images" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ImageList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ImageList) UnmarshalBinary(b []byte) error { + var res ImageList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instance.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instance.go new file mode 100644 index 0000000..291e97c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instance.go @@ -0,0 +1,293 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Instance instance +// +// swagger:model Instance +type Instance struct { + + // cpu数量 + CPUAmount int64 `json:"cpuAmount,omitempty"` + + // 单个cpu内核数 + CPUCores int64 `json:"cpuCores,omitempty"` + + // cpu频率(GHz) + CPUFrequency string `json:"cpuFrequency,omitempty"` + + // cpu厂商 + CPUManufacturer string `json:"cpuManufacturer,omitempty"` + + // cpu处理器型号 + CPUModel string `json:"cpuModel,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 数据盘数量 + DataVolumeAmount int64 `json:"dataVolumeAmount,omitempty"` + + // 数据盘接口类型(SATA,SAS,NVME) + DataVolumeInterfaceType string `json:"dataVolumeInterfaceType,omitempty"` + + // 数据盘raidId + DataVolumeRaidID string `json:"dataVolumeRaidId,omitempty"` + + // 数据盘raid名称 + DataVolumeRaidName string `json:"DataVolumeRaidName,omitempty"` + + // 数据盘单盘大小 + DataVolumeSize int64 `json:"dataVolumeSize,omitempty"` + + // 数据盘类型(SSD,HDD) + DataVolumeType string `json:"dataVolumeType,omitempty"` + + // 系统盘单位 + DataVolumeUnit string `json:"dataVolumeUnit,omitempty"` + + // 实例描述 + Description string `json:"description,omitempty"` + + // 设备uuid + DeviceID string `json:"deviceId,omitempty"` + + // 机型类型,如computer + DeviceSeries string `json:"deviceSeries,omitempty"` + + // 机型类型,如计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName,omitempty"` + + // 机型规格, cps.c.normal + DeviceType string `json:"deviceType,omitempty"` + + // 机型uuid + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // 机型名称,如计算效能型,标准计算型 + DeviceTypeName string `json:"deviceTypeName,omitempty"` + + // gpu数量 + GpuAmount int64 `json:"gpuAmount,omitempty"` + + // gpu厂商 + GpuManufacturer string `json:"gpuManufacturer,omitempty"` + + // gpu处理器型号 + GpuModel string `json:"gpuModel,omitempty"` + + // 主机名 + Hostname string `json:"hostname,omitempty"` + + // 机房uuid + IDcID string `json:"idcId,omitempty"` + + // 机房名称 + IdcName string `json:"idcName,omitempty"` + + // 带外管理IP + IloIP string `json:"iloIp,omitempty"` + + // 镜像uuid + ImageID string `json:"imageId,omitempty"` + + // 镜像名称 + ImageName string `json:"imageName,omitempty"` + + // 实例uuid + InstanceID string `json:"instanceId,omitempty"` + + // 实例名称 + InstanceName string `json:"instanceName,omitempty"` + + // 实例的volume和raid信息 + InstanceVolumeRaids []*InstanceVolumeRaid `json:"volumeRaid"` + + // 【网口模式】【网络设置】: bond单网口,dual双网口 + InterfaceMode string `json:"interfaceMode,omitempty"` + + // 是否锁定解锁锁定:locked,解锁unlocked + Locked string `json:"locked,omitempty"` + + // 是否锁定解锁锁定:已解锁,已锁定 + LockedName string `json:"lockedName,omitempty"` + + // 内存数量 + MemAmount int64 `json:"memAmount,omitempty"` + + // 内存主频(MHz) + MemFrequency int64 `json:"memFrequency,omitempty"` + + // 单个内存大小(GB) + MemSize int64 `json:"memSize,omitempty"` + + // 内存接口(如DDR3,DDR4) + MemType string `json:"memType,omitempty"` + + // 网卡数量 + NicAmount int64 `json:"nicAmount,omitempty"` + + // 网卡传输速率(GE) + NicRate int64 `json:"nicRate,omitempty"` + + // 内网IPV4 + PrivateIPV4 string `json:"privateIpv4,omitempty"` + + // 内网IPV6 + PrivateIPV6 string `json:"privateIpv6,omitempty"` + + // 实例所属项目UUID + ProjectID string `json:"projectId,omitempty"` + + // 系统盘raid配置 + RaidCan string `json:"raidCan,omitempty"` + + // 实例错误状态时的错误原因 + Reason string `json:"reason,omitempty"` + + // 设备SN + Sn string `json:"sn,omitempty"` + + // 运行状态 + Status string `json:"status,omitempty"` + + // 运行状态中文名字 + StatusName string `json:"statusName,omitempty"` + + // 系统盘数量 + SystemVolumeAmount int64 `json:"systemVolumeAmount,omitempty"` + + // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeInterfaceType string `json:"systemVolumeInterfaceType,omitempty"` + + // 系统盘raidId + SystemVolumeRaidID string `json:"systemVolumeRaidId,omitempty"` + + // 系统盘raid名称 + SystemVolumeRaidName string `json:"systemVolumeRaidName,omitempty"` + + // 系统盘单盘大小 + SystemVolumeSize int64 `json:"systemVolumeSize,omitempty"` + + // 系统盘类型(SSD,HDD) + SystemVolumeType string `json:"systemVolumeType,omitempty"` + + // 系统盘单位 + SystemVolumeUnit string `json:"systemVolumeUnit,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 实例所属用户UUID + UserID string `json:"userId,omitempty"` +} + +// Validate validates this instance +func (m *Instance) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstanceVolumeRaids(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Instance) validateInstanceVolumeRaids(formats strfmt.Registry) error { + if swag.IsZero(m.InstanceVolumeRaids) { // not required + return nil + } + + for i := 0; i < len(m.InstanceVolumeRaids); i++ { + if swag.IsZero(m.InstanceVolumeRaids[i]) { // not required + continue + } + + if m.InstanceVolumeRaids[i] != nil { + if err := m.InstanceVolumeRaids[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumeRaid" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumeRaid" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this instance based on the context it is used +func (m *Instance) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateInstanceVolumeRaids(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Instance) contextValidateInstanceVolumeRaids(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.InstanceVolumeRaids); i++ { + + if m.InstanceVolumeRaids[i] != nil { + if err := m.InstanceVolumeRaids[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumeRaid" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumeRaid" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Instance) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Instance) UnmarshalBinary(b []byte) error { + var res Instance + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instance_ids.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instance_ids.go new file mode 100644 index 0000000..1120ae1 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instance_ids.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstanceIds instance ids +// +// swagger:model InstanceIds +type InstanceIds struct { + + // instanceId 列表 + InstanceIds []string `json:"instanceIds"` +} + +// Validate validates this instance ids +func (m *InstanceIds) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this instance ids based on context it is used +func (m *InstanceIds) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *InstanceIds) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstanceIds) UnmarshalBinary(b []byte) error { + var res InstanceIds + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instance_info.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instance_info.go new file mode 100644 index 0000000..abf1a71 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instance_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstanceInfo instance info +// +// swagger:model InstanceInfo +type InstanceInfo struct { + + // instance + Instance *Instance `json:"instance,omitempty"` +} + +// Validate validates this instance info +func (m *InstanceInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstance(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceInfo) validateInstance(formats strfmt.Registry) error { + if swag.IsZero(m.Instance) { // not required + return nil + } + + if m.Instance != nil { + if err := m.Instance.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instance") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instance") + } + return err + } + } + + return nil +} + +// ContextValidate validate this instance info based on the context it is used +func (m *InstanceInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateInstance(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceInfo) contextValidateInstance(ctx context.Context, formats strfmt.Registry) error { + + if m.Instance != nil { + if err := m.Instance.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instance") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instance") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *InstanceInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstanceInfo) UnmarshalBinary(b []byte) error { + var res InstanceInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instance_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instance_list.go new file mode 100644 index 0000000..1cdd579 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instance_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstanceList instance list +// +// swagger:model InstanceList +type InstanceList struct { + + // instance实体数组 + Instances []*Instance `json:"instances"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this instance list +func (m *InstanceList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstances(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceList) validateInstances(formats strfmt.Registry) error { + if swag.IsZero(m.Instances) { // not required + return nil + } + + for i := 0; i < len(m.Instances); i++ { + if swag.IsZero(m.Instances[i]) { // not required + continue + } + + if m.Instances[i] != nil { + if err := m.Instances[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this instance list based on the context it is used +func (m *InstanceList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateInstances(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceList) contextValidateInstances(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Instances); i++ { + + if m.Instances[i] != nil { + if err := m.Instances[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *InstanceList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstanceList) UnmarshalBinary(b []byte) error { + var res InstanceList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instance_volume_raid.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instance_volume_raid.go new file mode 100644 index 0000000..885b029 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instance_volume_raid.go @@ -0,0 +1,150 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstanceVolumeRaid instance volume raid +// +// swagger:model InstanceVolumeRaid +type InstanceVolumeRaid struct { + + // raid + Raid *Raid `json:"raid,omitempty"` + + // volume + Volume *Volume `json:"volume,omitempty"` +} + +// Validate validates this instance volume raid +func (m *InstanceVolumeRaid) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRaid(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVolume(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceVolumeRaid) validateRaid(formats strfmt.Registry) error { + if swag.IsZero(m.Raid) { // not required + return nil + } + + if m.Raid != nil { + if err := m.Raid.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("raid") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("raid") + } + return err + } + } + + return nil +} + +func (m *InstanceVolumeRaid) validateVolume(formats strfmt.Registry) error { + if swag.IsZero(m.Volume) { // not required + return nil + } + + if m.Volume != nil { + if err := m.Volume.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volume") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volume") + } + return err + } + } + + return nil +} + +// ContextValidate validate this instance volume raid based on the context it is used +func (m *InstanceVolumeRaid) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateRaid(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateVolume(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceVolumeRaid) contextValidateRaid(ctx context.Context, formats strfmt.Registry) error { + + if m.Raid != nil { + if err := m.Raid.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("raid") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("raid") + } + return err + } + } + + return nil +} + +func (m *InstanceVolumeRaid) contextValidateVolume(ctx context.Context, formats strfmt.Registry) error { + + if m.Volume != nil { + if err := m.Volume.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volume") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volume") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *InstanceVolumeRaid) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstanceVolumeRaid) UnmarshalBinary(b []byte) error { + var res InstanceVolumeRaid + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instances_sshkey_info_response.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instances_sshkey_info_response.go new file mode 100644 index 0000000..e0acfb3 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/instances_sshkey_info_response.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstancesSshkeyInfoResponse instances sshkey info response +// +// swagger:model InstancesSshkeyInfoResponse +type InstancesSshkeyInfoResponse struct { + + // 实例Id列表 + InstanceIds []string `json:"instanceIds"` +} + +// Validate validates this instances sshkey info response +func (m *InstancesSshkeyInfoResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this instances sshkey info response based on context it is used +func (m *InstancesSshkeyInfoResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *InstancesSshkeyInfoResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstancesSshkeyInfoResponse) UnmarshalBinary(b []byte) error { + var res InstancesSshkeyInfoResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/license_content.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/license_content.go new file mode 100644 index 0000000..3abcc96 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/license_content.go @@ -0,0 +1,143 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// LicenseContent license content +// +// swagger:model LicenseContent +type LicenseContent struct { + + // end time + EndTime int64 `json:"end_time,omitempty"` + + // hard ware + HardWare string `json:"hardwareinfo,omitempty"` + + // license name + LicenseName string `json:"license_name,omitempty"` + + // license type + LicenseType string `json:"license_type,omitempty"` + + // model list + ModelList []*ModuleItem `json:"modelList"` + + // models + Models []string `json:"models"` + + // nodes num + NodesNum int64 `json:"nodes_num,omitempty"` + + // start time + StartTime int64 `json:"start_time,omitempty"` + + // used nodes num + UsedNodesNum int64 `json:"used_nodes_num,omitempty"` + + // version + Version string `json:"version,omitempty"` +} + +// Validate validates this license content +func (m *LicenseContent) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateModelList(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *LicenseContent) validateModelList(formats strfmt.Registry) error { + if swag.IsZero(m.ModelList) { // not required + return nil + } + + for i := 0; i < len(m.ModelList); i++ { + if swag.IsZero(m.ModelList[i]) { // not required + continue + } + + if m.ModelList[i] != nil { + if err := m.ModelList[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modelList" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modelList" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this license content based on the context it is used +func (m *LicenseContent) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateModelList(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *LicenseContent) contextValidateModelList(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.ModelList); i++ { + + if m.ModelList[i] != nil { + if err := m.ModelList[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modelList" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modelList" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *LicenseContent) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *LicenseContent) UnmarshalBinary(b []byte) error { + var res LicenseContent + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/license_token.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/license_token.go new file mode 100644 index 0000000..f28c85f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/license_token.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// LicenseToken license token +// +// swagger:model LicenseToken +type LicenseToken struct { + + // msg + Msg string `json:"msg,omitempty"` +} + +// Validate validates this license token +func (m *LicenseToken) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this license token based on context it is used +func (m *LicenseToken) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *LicenseToken) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *LicenseToken) UnmarshalBinary(b []byte) error { + var res LicenseToken + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/mail.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/mail.go new file mode 100644 index 0000000..08549a4 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/mail.go @@ -0,0 +1,68 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Mail mail +// +// swagger:model Mail +type Mail struct { + + // 管理员邮箱 + AdminAddr string `json:"admin_addr,omitempty"` + + // 管理员邮箱密码 + AdminPass string `json:"admin_pass,omitempty"` + + // 邮件功能是否验证过正常。1表示正常,其他表示异常 + IsPass string `json:"is_pass,omitempty"` + + // 是否推送邮件告警,0不推送,1推送 + IsPush string `json:"is_push,omitempty"` + + // 邮件服务器地址 + ServerAddr string `json:"server_addr,omitempty"` + + // 邮件服务器端口 + ServerPort string `json:"server_port,omitempty"` + + // 收件人邮箱 + To string `json:"to,omitempty"` +} + +// Validate validates this mail +func (m *Mail) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this mail based on context it is used +func (m *Mail) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Mail) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Mail) UnmarshalBinary(b []byte) error { + var res Mail + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/mail_dial_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/mail_dial_request.go new file mode 100644 index 0000000..a970bfc --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/mail_dial_request.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// MailDialRequest mail dial request +// +// swagger:model MailDialRequest +type MailDialRequest struct { + + // 管理员邮箱 + // Required: true + AdminAddr *string `json:"admin_addr"` + + // 管理员邮箱密码 + // Required: true + AdminPass *string `json:"admin_pass"` + + // 邮件服务器地址 + // Required: true + ServerAddr *string `json:"server_addr"` + + // 邮件服务器端口 + // Required: true + ServerPort *string `json:"server_port"` + + // 收件人邮箱地址 + To string `json:"to,omitempty"` +} + +// Validate validates this mail dial request +func (m *MailDialRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAdminAddr(formats); err != nil { + res = append(res, err) + } + + if err := m.validateAdminPass(formats); err != nil { + res = append(res, err) + } + + if err := m.validateServerAddr(formats); err != nil { + res = append(res, err) + } + + if err := m.validateServerPort(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MailDialRequest) validateAdminAddr(formats strfmt.Registry) error { + + if err := validate.Required("admin_addr", "body", m.AdminAddr); err != nil { + return err + } + + return nil +} + +func (m *MailDialRequest) validateAdminPass(formats strfmt.Registry) error { + + if err := validate.Required("admin_pass", "body", m.AdminPass); err != nil { + return err + } + + return nil +} + +func (m *MailDialRequest) validateServerAddr(formats strfmt.Registry) error { + + if err := validate.Required("server_addr", "body", m.ServerAddr); err != nil { + return err + } + + return nil +} + +func (m *MailDialRequest) validateServerPort(formats strfmt.Registry) error { + + if err := validate.Required("server_port", "body", m.ServerPort); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this mail dial request based on context it is used +func (m *MailDialRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *MailDialRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MailDialRequest) UnmarshalBinary(b []byte) error { + var res MailDialRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/message.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/message.go new file mode 100644 index 0000000..2f2fabb --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/message.go @@ -0,0 +1,137 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Message message +// +// swagger:model Message +type Message struct { + + // 告警次数,始终为1,带外故障消息专属字段 + AlertCount int64 `json:"alert_count,omitempty"` + + // 故障告警时间,带外故障消息专属字段 + AlertTime int64 `json:"alert_time,omitempty"` + + // 故障内容,带外故障消息专属字段 + Content string `json:"content,omitempty"` + + // 详情, 带外监控日志的详情请用content + Detail string `json:"detail,omitempty"` + + // device ID + DeviceID string `json:"device_id,omitempty"` + + // 故障类型, 带外故障消息专属字段 + FaultType string `json:"fault_type,omitempty"` + + // 消息时间戳 + FinishTime int64 `json:"finish_time,omitempty"` + + // 0未读, 1已读 + HasRead int8 `json:"has_read,omitempty"` + + // 独一处的下划线,跟sdk一致 + IDcID string `json:"idc_id,omitempty"` + + // i dc name + IDcName string `json:"idc_name,omitempty"` + + // 实例id + InstanceID string `json:"instance_id,omitempty"` + + // 实例name + InstanceName string `json:"instance_name,omitempty"` + + // 是否删除0未删除 1已删除 + IsDel int8 `json:"is_del,omitempty"` + + // 版本名称, 许可证到期消息专属字段 + LicenseName string `json:"license_name,omitempty"` + + // 版本号, 许可证到期消息专属字段 + LicenseNumber string `json:"license_number,omitempty"` + + // 结束时间, 许可证到期消息专属字段 + LienseEndTime int64 `json:"license_end_time,omitempty"` + + // 开始时间, 许可证到期消息专属字段 + LienseStartTime int64 `json:"license_start_time,omitempty"` + + // 系统原始日志id, 带外故障消息专属字段 + LogID string `json:"logid,omitempty"` + + // message uuid + MessageID string `json:"message_id,omitempty"` + + // 消息子类型 + MessageSubType string `json:"message_sub_type,omitempty"` + + // 消息类型 + MessageType string `json:"message_type,omitempty"` + + // project ID + ProjectID string `json:"project_id,omitempty"` + + // project name + ProjectName string `json:"project_name,omitempty"` + + // 资源类型 实例/设备 + ResourceType string `json:"resource_type,omitempty"` + + // 操作结果 fail/succ + Result string `json:"result,omitempty"` + + // inbond rule uuid + RuleID string `json:"rule_id,omitempty"` + + // inbond rule name + RuleName string `json:"rule_name,omitempty"` + + // 设备sn + SN string `json:"sn,omitempty"` + + // user_id + UserID string `json:"user_id,omitempty"` + + // user_name + UserName string `json:"user_name,omitempty"` +} + +// Validate validates this message +func (m *Message) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this message based on context it is used +func (m *Message) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Message) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Message) UnmarshalBinary(b []byte) error { + var res Message + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/message_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/message_list.go new file mode 100644 index 0000000..655c2b1 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/message_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// MessageList message list +// +// swagger:model MessageList +type MessageList struct { + + // messages + Messages []*Message `json:"messages"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this message list +func (m *MessageList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateMessages(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MessageList) validateMessages(formats strfmt.Registry) error { + if swag.IsZero(m.Messages) { // not required + return nil + } + + for i := 0; i < len(m.Messages); i++ { + if swag.IsZero(m.Messages[i]) { // not required + continue + } + + if m.Messages[i] != nil { + if err := m.Messages[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("messages" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("messages" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this message list based on the context it is used +func (m *MessageList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateMessages(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MessageList) contextValidateMessages(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Messages); i++ { + + if m.Messages[i] != nil { + if err := m.Messages[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("messages" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("messages" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *MessageList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MessageList) UnmarshalBinary(b []byte) error { + var res MessageList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/message_statistic.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/message_statistic.go new file mode 100644 index 0000000..89a5a76 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/message_statistic.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// MessageStatistic message statistic +// +// swagger:model MessageStatistic +type MessageStatistic struct { + + // total count + TotalCount int64 `json:"totalCount,omitempty"` + + // unread count + UnreadCount int64 `json:"unreadCount,omitempty"` +} + +// Validate validates this message statistic +func (m *MessageStatistic) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this message statistic based on context it is used +func (m *MessageStatistic) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *MessageStatistic) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MessageStatistic) UnmarshalBinary(b []byte) error { + var res MessageStatistic + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/message_types_resp.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/message_types_resp.go new file mode 100644 index 0000000..0a51420 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/message_types_resp.go @@ -0,0 +1,27 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" +) + +// MessageTypesResp message types resp +// +// swagger:model MessageTypesResp +type MessageTypesResp map[string][]string + +// Validate validates this message types resp +func (m MessageTypesResp) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this message types resp based on context it is used +func (m MessageTypesResp) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/message_with_next_prev.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/message_with_next_prev.go new file mode 100644 index 0000000..ccf69b1 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/message_with_next_prev.go @@ -0,0 +1,110 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// MessageWithNextPrev message with next prev +// +// swagger:model MessageWithNextPrev +type MessageWithNextPrev struct { + + // next message Id + NextMessageID string `json:"nextMessageId,omitempty"` + + // prev message Id + PrevMessageID string `json:"prevMessageId,omitempty"` + + // message + Message *Message `json:"message,omitempty"` +} + +// Validate validates this message with next prev +func (m *MessageWithNextPrev) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateMessage(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MessageWithNextPrev) validateMessage(formats strfmt.Registry) error { + if swag.IsZero(m.Message) { // not required + return nil + } + + if m.Message != nil { + if err := m.Message.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("message") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("message") + } + return err + } + } + + return nil +} + +// ContextValidate validate this message with next prev based on the context it is used +func (m *MessageWithNextPrev) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateMessage(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MessageWithNextPrev) contextValidateMessage(ctx context.Context, formats strfmt.Registry) error { + + if m.Message != nil { + if err := m.Message.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("message") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("message") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *MessageWithNextPrev) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MessageWithNextPrev) UnmarshalBinary(b []byte) error { + var res MessageWithNextPrev + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_apikey_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_apikey_request.go new file mode 100644 index 0000000..8a852b2 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_apikey_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ModifyApikeyRequest modify apikey request +// +// swagger:model ModifyApikeyRequest +type ModifyApikeyRequest struct { + + // 秘钥对名称 + // Required: true + Name *string `json:"name"` + + // 是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法 + // Required: true + ReadOnly *int8 `json:"readOnly"` +} + +// Validate validates this modify apikey request +func (m *ModifyApikeyRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateReadOnly(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ModifyApikeyRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +func (m *ModifyApikeyRequest) validateReadOnly(formats strfmt.Registry) error { + + if err := validate.Required("readOnly", "body", m.ReadOnly); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this modify apikey request based on context it is used +func (m *ModifyApikeyRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyApikeyRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyApikeyRequest) UnmarshalBinary(b []byte) error { + var res ModifyApikeyRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_device_type_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_device_type_request.go new file mode 100644 index 0000000..a5988c5 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_device_type_request.go @@ -0,0 +1,227 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyDeviceTypeRequest modify device type request +// +// swagger:model ModifyDeviceTypeRequest +type ModifyDeviceTypeRequest struct { + + // 体系架构,如i386/x86_64/ ARM64(aarch64),默认 x86_64 + Architecture *string `json:"architecture,omitempty"` + + // boot模式【UEFI Legacy/BIOS】支持多选,逗号分隔 + BootMode string `json:"boot_mode,omitempty"` + + // cpu数量 + CPUAmount *int64 `json:"cpuAmount,omitempty"` + + // 单个cpu内核数 + CPUCores *int64 `json:"cpuCores,omitempty"` + + // cpu频率(G) + CPUFrequency *string `json:"cpuFrequency,omitempty"` + + // cpu厂商 + CPUManufacturer *string `json:"cpuManufacturer,omitempty"` + + // cpu处理器型号 + CPUModel *string `json:"cpuModel,omitempty"` + + // CPU 预置规格 + CPUSpec *string `json:"cpuSpec,omitempty"` + + // 数据盘数量 + DataVolumeAmount *int64 `json:"dataVolumeAmount,omitempty"` + + // 数据盘接口类型 + DataVolumeInterfaceType *string `json:"dataVolumeInterfaceType,omitempty"` + + // 数据盘单盘大小 + DataVolumeSize *int64 `json:"dataVolumeSize,omitempty"` + + // 数据盘类型 + DataVolumeType *string `json:"dataVolumeType,omitempty"` + + // 数据盘单盘大小单位 + DataVolumeUnit *string `json:"dataVolumeUnit,omitempty"` + + // 描述 + Description *string `json:"description,omitempty"` + + // 机型类型,如计算型,存储型 + DeviceSeries *string `json:"deviceSeries,omitempty"` + + // 机型规格 + DeviceType *string `json:"deviceType,omitempty"` + + // gpu数量 + GpuAmount *int64 `json:"gpuAmount,omitempty"` + + // gpu厂商 + GpuManufacturer *string `json:"gpuManufacturer,omitempty"` + + // gpu处理器型号 + GpuModel *string `json:"gpuModel,omitempty"` + + // 【高度(U)】:显示机型高度 + Height *int64 `json:"height,omitempty"` + + // 机房id + IDcID *string `json:"idcId,omitempty"` + + // 【网口模式】【网络设置】: 单网口,双网口bond,single + InterfaceMode *string `json:"interfaceMode,omitempty"` + + // 阵列卡是否需要配置 1 需要配置 2无需配置 + IsNeedRaid *string `json:"isNeedRaid,omitempty"` + + // 内存数量 + MemAmount *int64 `json:"memAmount,omitempty"` + + // 内存主频(MHz) + MemFrequency *int64 `json:"memFrequency,omitempty"` + + // 单个内存大小(GB) + MemSize *int64 `json:"memSize,omitempty"` + + // 内存 预置规格 + MemSpec *string `json:"memSpec,omitempty"` + + // 内存接口(如DDR3,DDR4) + MemType *string `json:"memType,omitempty"` + + // 机型名称 + Name *string `json:"name,omitempty"` + + // 网卡数量 + NicAmount *int64 `json:"nicAmount,omitempty"` + + // 网卡传输速率(GE) + NicRate *int64 `json:"nicRate,omitempty"` + + // 系统盘raid,支持多选,英文逗号分隔 + RaidID *string `json:"raidId,omitempty"` + + // 系统盘数量 + SystemVolumeAmount *int64 `json:"systemVolumeAmount,omitempty"` + + // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeInterfaceType *string `json:"systemVolumeInterfaceType,omitempty"` + + // 系统盘单盘大小 + SystemVolumeSize *int64 `json:"systemVolumeSize,omitempty"` + + // 系统盘类型(SSD,HDD) + SystemVolumeType *string `json:"systemVolumeType,omitempty"` + + // 系统盘单盘大小单位 + SystemVolumeUnit *string `json:"systemVolumeUnit,omitempty"` + + // 卷管理 + Volumes []*VolumeItem `json:"volumes"` +} + +// Validate validates this modify device type request +func (m *ModifyDeviceTypeRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateVolumes(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ModifyDeviceTypeRequest) validateVolumes(formats strfmt.Registry) error { + if swag.IsZero(m.Volumes) { // not required + return nil + } + + for i := 0; i < len(m.Volumes); i++ { + if swag.IsZero(m.Volumes[i]) { // not required + continue + } + + if m.Volumes[i] != nil { + if err := m.Volumes[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this modify device type request based on the context it is used +func (m *ModifyDeviceTypeRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateVolumes(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ModifyDeviceTypeRequest) contextValidateVolumes(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Volumes); i++ { + + if m.Volumes[i] != nil { + if err := m.Volumes[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("volumes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("volumes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyDeviceTypeRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyDeviceTypeRequest) UnmarshalBinary(b []byte) error { + var res ModifyDeviceTypeRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_devices_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_devices_request.go new file mode 100644 index 0000000..ca01a4b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_devices_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyDevicesRequest modify devices request +// +// swagger:model ModifyDevicesRequest +type ModifyDevicesRequest struct { + + // 修改设备描述 + Description *string `json:"description,omitempty"` +} + +// Validate validates this modify devices request +func (m *ModifyDevicesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify devices request based on context it is used +func (m *ModifyDevicesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyDevicesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyDevicesRequest) UnmarshalBinary(b []byte) error { + var res ModifyDevicesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_idc_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_idc_request.go new file mode 100644 index 0000000..b490bdd --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_idc_request.go @@ -0,0 +1,80 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyIdcRequest modify idc request +// +// swagger:model ModifyIdcRequest +type ModifyIdcRequest struct { + + // 机房地址 0-256 + Address *string `json:"address,omitempty"` + + // 带外密码 0-64 + IloPassword *string `json:"iloPassword,omitempty"` + + // 带外用户名 0-64 + IloUser *string `json:"iloUser,omitempty"` + + // 机房等级 1-64 + Level *string `json:"level,omitempty"` + + // 机房名称 1-64 + Name *string `json:"name,omitempty"` + + // 机房英文名称 1-64 + NameEn *string `json:"nameEn,omitempty"` + + // 机房缩写 1-64 + Shortname *string `json:"shortname,omitempty"` + + // 交换机密码1 0-64 + SwitchPassword1 *string `json:"switchPassword1,omitempty"` + + // 交换机2密码 0-64 + SwitchPassword2 *string `json:"switchPassword2,omitempty"` + + // 交换机用户1 0-64 + SwitchUser1 *string `json:"switchUser1,omitempty"` + + // 交换机用户2 0-64 + SwitchUser2 *string `json:"switchUser2,omitempty"` +} + +// Validate validates this modify idc request +func (m *ModifyIdcRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify idc request based on context it is used +func (m *ModifyIdcRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyIdcRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyIdcRequest) UnmarshalBinary(b []byte) error { + var res ModifyIdcRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_image_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_image_request.go new file mode 100644 index 0000000..aa0c05a --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_image_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyImageRequest modify image request +// +// swagger:model ModifyImageRequest +type ModifyImageRequest struct { + + // 修改设备描述 + Description *string `json:"description,omitempty"` +} + +// Validate validates this modify image request +func (m *ModifyImageRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify image request based on context it is used +func (m *ModifyImageRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyImageRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyImageRequest) UnmarshalBinary(b []byte) error { + var res ModifyImageRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_instance_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_instance_request.go new file mode 100644 index 0000000..6cf9850 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_instance_request.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyInstanceRequest modify instance request +// +// swagger:model ModifyInstanceRequest +type ModifyInstanceRequest struct { + + // 描述 + Description *string `json:"description,omitempty"` + + // 实例名称 + InstanceName string `json:"instanceName,omitempty"` +} + +// Validate validates this modify instance request +func (m *ModifyInstanceRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify instance request based on context it is used +func (m *ModifyInstanceRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyInstanceRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyInstanceRequest) UnmarshalBinary(b []byte) error { + var res ModifyInstanceRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_instances_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_instances_request.go new file mode 100644 index 0000000..93be971 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_instances_request.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyInstancesRequest 批量修改实例名称 +// +// swagger:model ModifyInstancesRequest +type ModifyInstancesRequest struct { + + // 实例id列表 + InstanceIDs []string `json:"instance_ids"` + + // 实例名称 + InstanceName string `json:"instanceName,omitempty"` +} + +// Validate validates this modify instances request +func (m *ModifyInstancesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify instances request based on context it is used +func (m *ModifyInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyInstancesRequest) UnmarshalBinary(b []byte) error { + var res ModifyInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_local_user_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_local_user_request.go new file mode 100644 index 0000000..f08328d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_local_user_request.go @@ -0,0 +1,65 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyLocalUserRequest modify local user request +// +// swagger:model ModifyLocalUserRequest +type ModifyLocalUserRequest struct { + + // 用户默认项目uuid + DefaultProjectID *string `json:"defaultProjectId,omitempty"` + + // 邮箱 + Email *string `json:"email,omitempty"` + + // 语言[en_US, zh_CN] + Language *string `json:"language,omitempty"` + + // 手机号 + PhoneNumber *string `json:"phoneNumber,omitempty"` + + // 国家地区码,如86 + PhonePrefix *string `json:"phonePrefix,omitempty"` + + // 时区 Asia/Shanghai + Timezone *string `json:"timezone,omitempty"` +} + +// Validate validates this modify local user request +func (m *ModifyLocalUserRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify local user request based on context it is used +func (m *ModifyLocalUserRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyLocalUserRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyLocalUserRequest) UnmarshalBinary(b []byte) error { + var res ModifyLocalUserRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_o_s_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_o_s_request.go new file mode 100644 index 0000000..be8740c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_o_s_request.go @@ -0,0 +1,65 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyOSRequest modify o s request +// +// swagger:model ModifyOSRequest +type ModifyOSRequest struct { + + // 体系架构 + Architecture string `json:"architecture,omitempty"` + + // 位数 + Bits int64 `json:"bits,omitempty"` + + // 操作系统名称 + OsName string `json:"osName,omitempty"` + + // 操作系统平台 + OsType string `json:"osType,omitempty"` + + // 操作系统版本 + OsVersion string `json:"osVersion,omitempty"` + + // 系统用户 + SysUser string `json:"sysUser,omitempty"` +} + +// Validate validates this modify o s request +func (m *ModifyOSRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify o s request based on context it is used +func (m *ModifyOSRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyOSRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyOSRequest) UnmarshalBinary(b []byte) error { + var res ModifyOSRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_project_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_project_request.go new file mode 100644 index 0000000..1e030ef --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_project_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ModifyProjectRequest modify project request +// +// swagger:model ModifyProjectRequest +type ModifyProjectRequest struct { + + // 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + // Required: true + ProjectName *string `json:"projectName"` +} + +// Validate validates this modify project request +func (m *ModifyProjectRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateProjectName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ModifyProjectRequest) validateProjectName(formats strfmt.Registry) error { + + if err := validate.Required("projectName", "body", m.ProjectName); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this modify project request based on context it is used +func (m *ModifyProjectRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyProjectRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyProjectRequest) UnmarshalBinary(b []byte) error { + var res ModifyProjectRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_raid_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_raid_request.go new file mode 100644 index 0000000..443468e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_raid_request.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ModifyRaidRequest modify raid request +// +// swagger:model ModifyRaidRequest +type ModifyRaidRequest struct { + + // raid描述(中文) + // Required: true + DescriptionEn *string `json:"descriptionEn"` + + // raid描述(英文) + // Required: true + DescriptionZh *string `json:"descriptionZh"` + + // raid名称 + // Required: true + Name *string `json:"name"` +} + +// Validate validates this modify raid request +func (m *ModifyRaidRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDescriptionEn(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDescriptionZh(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ModifyRaidRequest) validateDescriptionEn(formats strfmt.Registry) error { + + if err := validate.Required("descriptionEn", "body", m.DescriptionEn); err != nil { + return err + } + + return nil +} + +func (m *ModifyRaidRequest) validateDescriptionZh(formats strfmt.Registry) error { + + if err := validate.Required("descriptionZh", "body", m.DescriptionZh); err != nil { + return err + } + + return nil +} + +func (m *ModifyRaidRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this modify raid request based on context it is used +func (m *ModifyRaidRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyRaidRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyRaidRequest) UnmarshalBinary(b []byte) error { + var res ModifyRaidRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_role_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_role_request.go new file mode 100644 index 0000000..3fcc3e8 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_role_request.go @@ -0,0 +1,59 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyRoleRequest modify role request +// +// swagger:model ModifyRoleRequest +type ModifyRoleRequest struct { + + // 角色描述中文名称 + DescriptionCn string `json:"descriptionCn,omitempty"` + + // 角色描述英文名称 + DescriptionEn string `json:"descriptionEn,omitempty"` + + // 角色中文名称 + RoleNameCn string `json:"roleNameCn,omitempty"` + + // 角色英文名称 + RoleNameEn string `json:"roleNameEn,omitempty"` +} + +// Validate validates this modify role request +func (m *ModifyRoleRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify role request based on context it is used +func (m *ModifyRoleRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyRoleRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyRoleRequest) UnmarshalBinary(b []byte) error { + var res ModifyRoleRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_sshkey_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_sshkey_request.go new file mode 100644 index 0000000..5e17a3a --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_sshkey_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifySshkeyRequest modify sshkey request +// +// swagger:model ModifySshkeyRequest +type ModifySshkeyRequest struct { + + // 秘钥名称 + Name *string `json:"name,omitempty"` +} + +// Validate validates this modify sshkey request +func (m *ModifySshkeyRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify sshkey request based on context it is used +func (m *ModifySshkeyRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifySshkeyRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifySshkeyRequest) UnmarshalBinary(b []byte) error { + var res ModifySshkeyRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_user_password_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_user_password_request.go new file mode 100644 index 0000000..51fa312 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_user_password_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ModifyUserPasswordRequest modify user password request +// +// swagger:model ModifyUserPasswordRequest +type ModifyUserPasswordRequest struct { + + // 旧密码,明文 + // Required: true + OldPassword *string `json:"oldPassword"` + + // 新密码 明文,密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + // Required: true + Password *string `json:"password"` +} + +// Validate validates this modify user password request +func (m *ModifyUserPasswordRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateOldPassword(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePassword(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ModifyUserPasswordRequest) validateOldPassword(formats strfmt.Registry) error { + + if err := validate.Required("oldPassword", "body", m.OldPassword); err != nil { + return err + } + + return nil +} + +func (m *ModifyUserPasswordRequest) validatePassword(formats strfmt.Registry) error { + + if err := validate.Required("password", "body", m.Password); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this modify user password request based on context it is used +func (m *ModifyUserPasswordRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyUserPasswordRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyUserPasswordRequest) UnmarshalBinary(b []byte) error { + var res ModifyUserPasswordRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_user_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_user_request.go new file mode 100644 index 0000000..ea68964 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/modify_user_request.go @@ -0,0 +1,59 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyUserRequest modify user request +// +// swagger:model ModifyUserRequest +type ModifyUserRequest struct { + + // 描述 + Description *string `json:"description,omitempty"` + + // 邮箱 + Email *string `json:"email,omitempty"` + + // 手机号 + PhoneNumber *string `json:"phoneNumber,omitempty"` + + // 国家地区码,如86 + PhonePrefix *string `json:"phonePrefix,omitempty"` +} + +// Validate validates this modify user request +func (m *ModifyUserRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify user request based on context it is used +func (m *ModifyUserRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyUserRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyUserRequest) UnmarshalBinary(b []byte) error { + var res ModifyUserRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/module_item.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/module_item.go new file mode 100644 index 0000000..7d101be --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/module_item.go @@ -0,0 +1,65 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModuleItem module item +// +// swagger:model ModuleItem +type ModuleItem struct { + + // description + Description string `json:"description,omitempty"` + + // description en + DescriptionEn string `json:"descriptionEn,omitempty"` + + // effective + Effective bool `json:"effective,omitempty"` + + // ID + ID int64 `json:"id,omitempty"` + + // name + Name string `json:"name,omitempty"` + + // name en + NameEn string `json:"nameEn,omitempty"` +} + +// Validate validates this module item +func (m *ModuleItem) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this module item based on context it is used +func (m *ModuleItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModuleItem) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModuleItem) UnmarshalBinary(b []byte) error { + var res ModuleItem + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/monitor_data_item.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/monitor_data_item.go new file mode 100644 index 0000000..d3fc90e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/monitor_data_item.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// MonitorDataItem monitor data item +// +// swagger:model MonitorDataItem +type MonitorDataItem struct { + + // timestamp + Timestamp int64 `json:"timestamp,omitempty"` + + // value + Value string `json:"value,omitempty"` +} + +// Validate validates this monitor data item +func (m *MonitorDataItem) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this monitor data item based on context it is used +func (m *MonitorDataItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *MonitorDataItem) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MonitorDataItem) UnmarshalBinary(b []byte) error { + var res MonitorDataItem + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/monitor_data_query.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/monitor_data_query.go new file mode 100644 index 0000000..f119ed8 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/monitor_data_query.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// MonitorDataQuery monitor data query +// +// swagger:model MonitorDataQuery +type MonitorDataQuery struct { + + // end time + EndTime int64 `json:"endTime,omitempty"` + + // 跟赛迪约定,转换单位放这里实现 + Func map[string]int64 `json:"func,omitempty"` + + // metric都放这里了 + Labels map[string]string `json:"labels,omitempty"` + + // MetricName string `json:"metricName"` + // [rate, increase] + SampleMethod string `json:"sampleMethod,omitempty"` + + // start time + StartTime int64 `json:"startTime,omitempty"` + + // step + Step int64 `json:"step,omitempty"` + + // [bmp_monitor_counter bmp_monitor_gauge] + TableName string `json:"tableName,omitempty"` +} + +// Validate validates this monitor data query +func (m *MonitorDataQuery) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this monitor data query based on context it is used +func (m *MonitorDataQuery) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *MonitorDataQuery) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MonitorDataQuery) UnmarshalBinary(b []byte) error { + var res MonitorDataQuery + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/mount_devices_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/mount_devices_request.go new file mode 100644 index 0000000..88f5334 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/mount_devices_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// MountDevicesRequest mount devices request +// +// swagger:model MountDevicesRequest +type MountDevicesRequest struct { + + // 设备uuid + // Required: true + DeviceID *string `json:"deviceId"` +} + +// Validate validates this mount devices request +func (m *MountDevicesRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MountDevicesRequest) validateDeviceID(formats strfmt.Registry) error { + + if err := validate.Required("deviceId", "body", m.DeviceID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this mount devices request based on context it is used +func (m *MountDevicesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *MountDevicesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MountDevicesRequest) UnmarshalBinary(b []byte) error { + var res MountDevicesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/os.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/os.go new file mode 100644 index 0000000..f563370 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/os.go @@ -0,0 +1,89 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Os os +// +// swagger:model Os +type Os struct { + + // 架构:x86/x64/i386/ + Architecture string `json:"architecture,omitempty"` + + // 指令宽度:64/32位 + Bits int64 `json:"bits,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 删除时间 + DeletedTime string `json:"deletedTime,omitempty"` + + // ID + ID uint64 `json:"id,omitempty"` + + // 是否删除0未删除 1已删除 + IsDel int8 `json:"isDel,omitempty"` + + // 操作系统uuid + OsID string `json:"osId,omitempty"` + + // 操作系统名称 + OsName string `json:"osName,omitempty"` + + // 操作系统分类:linux/windows + OsType string `json:"osType,omitempty"` + + // 操作系统版本 + OsVersion string `json:"osVersion,omitempty"` + + // 管理员账户 + SysUser string `json:"sysUser,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` +} + +// Validate validates this os +func (m *Os) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this os based on context it is used +func (m *Os) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Os) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Os) UnmarshalBinary(b []byte) error { + var res Os + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/os_id.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/os_id.go new file mode 100644 index 0000000..427468c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/os_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// OsID os Id +// +// swagger:model OsId +type OsID struct { + + // 操作系统uuid + OsID string `json:"osId,omitempty"` +} + +// Validate validates this os Id +func (m *OsID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this os Id based on context it is used +func (m *OsID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *OsID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *OsID) UnmarshalBinary(b []byte) error { + var res OsID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/os_info.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/os_info.go new file mode 100644 index 0000000..3042eb8 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/os_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// OsInfo os info +// +// swagger:model OsInfo +type OsInfo struct { + + // os + Os *Os `json:"os,omitempty"` +} + +// Validate validates this os info +func (m *OsInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateOs(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *OsInfo) validateOs(formats strfmt.Registry) error { + if swag.IsZero(m.Os) { // not required + return nil + } + + if m.Os != nil { + if err := m.Os.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("os") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("os") + } + return err + } + } + + return nil +} + +// ContextValidate validate this os info based on the context it is used +func (m *OsInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateOs(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *OsInfo) contextValidateOs(ctx context.Context, formats strfmt.Registry) error { + + if m.Os != nil { + if err := m.Os.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("os") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("os") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *OsInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *OsInfo) UnmarshalBinary(b []byte) error { + var res OsInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/os_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/os_list.go new file mode 100644 index 0000000..522f28d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/os_list.go @@ -0,0 +1,116 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// OsList os list +// +// swagger:model OsList +type OsList struct { + + // 操作系统列表 + Oss []*Os `json:"oss"` +} + +// Validate validates this os list +func (m *OsList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateOss(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *OsList) validateOss(formats strfmt.Registry) error { + if swag.IsZero(m.Oss) { // not required + return nil + } + + for i := 0; i < len(m.Oss); i++ { + if swag.IsZero(m.Oss[i]) { // not required + continue + } + + if m.Oss[i] != nil { + if err := m.Oss[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("oss" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("oss" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this os list based on the context it is used +func (m *OsList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateOss(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *OsList) contextValidateOss(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Oss); i++ { + + if m.Oss[i] != nil { + if err := m.Oss[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("oss" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("oss" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *OsList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *OsList) UnmarshalBinary(b []byte) error { + var res OsList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/partition.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/partition.go new file mode 100644 index 0000000..b0047e8 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/partition.go @@ -0,0 +1,57 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Partition 镜像默认分区 +// [{"format":"swap","point":"swap","size":10240},{"format":"xfs","point":"/","size":51200}] +// +// swagger:model Partition +type Partition struct { + + // format,如[swap, xfs] + FsType string `json:"format,omitempty"` + + // point,如[swap, /, /var] + MountPoint string `json:"point,omitempty"` + + // 分区大小, MB为单位 + Size int64 `json:"size,omitempty"` +} + +// Validate validates this partition +func (m *Partition) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this partition based on context it is used +func (m *Partition) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Partition) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Partition) UnmarshalBinary(b []byte) error { + var res Partition + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/project.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/project.go new file mode 100644 index 0000000..af6dd43 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/project.go @@ -0,0 +1,140 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Project project +// +// swagger:model Project +type Project struct { + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 项目下实例数量 + InstanceCount int64 `json:"instanceCount,omitempty"` + + // 此项目的共享标志位,1为拥有,2为共享 + Owned int64 `json:"owned,omitempty"` + + // 项目uuid + ProjectID string `json:"projectId,omitempty"` + + // 项目名称 + ProjectName string `json:"projectName,omitempty"` + + // 共享 + ShareProjects []*ShareProject `json:"shareProjects"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` +} + +// Validate validates this project +func (m *Project) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateShareProjects(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Project) validateShareProjects(formats strfmt.Registry) error { + if swag.IsZero(m.ShareProjects) { // not required + return nil + } + + for i := 0; i < len(m.ShareProjects); i++ { + if swag.IsZero(m.ShareProjects[i]) { // not required + continue + } + + if m.ShareProjects[i] != nil { + if err := m.ShareProjects[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this project based on the context it is used +func (m *Project) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateShareProjects(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Project) contextValidateShareProjects(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.ShareProjects); i++ { + + if m.ShareProjects[i] != nil { + if err := m.ShareProjects[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Project) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Project) UnmarshalBinary(b []byte) error { + var res Project + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/project_id.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/project_id.go new file mode 100644 index 0000000..3c4cef9 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/project_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ProjectID project Id +// +// swagger:model ProjectId +type ProjectID struct { + + // 项目uuid + ProjectID string `json:"projectId,omitempty"` +} + +// Validate validates this project Id +func (m *ProjectID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this project Id based on context it is used +func (m *ProjectID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ProjectID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ProjectID) UnmarshalBinary(b []byte) error { + var res ProjectID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/project_info.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/project_info.go new file mode 100644 index 0000000..8a6287d --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/project_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ProjectInfo project info +// +// swagger:model ProjectInfo +type ProjectInfo struct { + + // project + Project *Project `json:"project,omitempty"` +} + +// Validate validates this project info +func (m *ProjectInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateProject(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ProjectInfo) validateProject(formats strfmt.Registry) error { + if swag.IsZero(m.Project) { // not required + return nil + } + + if m.Project != nil { + if err := m.Project.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("project") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("project") + } + return err + } + } + + return nil +} + +// ContextValidate validate this project info based on the context it is used +func (m *ProjectInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateProject(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ProjectInfo) contextValidateProject(ctx context.Context, formats strfmt.Registry) error { + + if m.Project != nil { + if err := m.Project.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("project") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("project") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ProjectInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ProjectInfo) UnmarshalBinary(b []byte) error { + var res ProjectInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/project_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/project_list.go new file mode 100644 index 0000000..a9e6867 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/project_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ProjectList project list +// +// swagger:model ProjectList +type ProjectList struct { + + // 页数 + PageNumber int64 `json:"pageNumber,omitempty"` + + // 页大小 + PageSize int64 `json:"pageSize,omitempty"` + + // 项目实体列表 + Projects []*Project `json:"projects"` + + // 总条数 + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this project list +func (m *ProjectList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateProjects(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ProjectList) validateProjects(formats strfmt.Registry) error { + if swag.IsZero(m.Projects) { // not required + return nil + } + + for i := 0; i < len(m.Projects); i++ { + if swag.IsZero(m.Projects[i]) { // not required + continue + } + + if m.Projects[i] != nil { + if err := m.Projects[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("projects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("projects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this project list based on the context it is used +func (m *ProjectList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateProjects(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ProjectList) contextValidateProjects(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Projects); i++ { + + if m.Projects[i] != nil { + if err := m.Projects[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("projects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("projects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ProjectList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ProjectList) UnmarshalBinary(b []byte) error { + var res ProjectList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/query_device_type_image_partition_response.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/query_device_type_image_partition_response.go new file mode 100644 index 0000000..01b3e25 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/query_device_type_image_partition_response.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// QueryDeviceTypeImagePartitionResponse query device type image partition response +// +// swagger:model QueryDeviceTypeImagePartitionResponse +type QueryDeviceTypeImagePartitionResponse struct { + + // 数据盘分区列表 + DataPartition []*Partition `json:"dataPartition"` + + // 系统盘分区列表 + SystemPartition []*Partition `json:"systemPartition"` +} + +// Validate validates this query device type image partition response +func (m *QueryDeviceTypeImagePartitionResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDataPartition(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemPartition(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *QueryDeviceTypeImagePartitionResponse) validateDataPartition(formats strfmt.Registry) error { + if swag.IsZero(m.DataPartition) { // not required + return nil + } + + for i := 0; i < len(m.DataPartition); i++ { + if swag.IsZero(m.DataPartition[i]) { // not required + continue + } + + if m.DataPartition[i] != nil { + if err := m.DataPartition[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *QueryDeviceTypeImagePartitionResponse) validateSystemPartition(formats strfmt.Registry) error { + if swag.IsZero(m.SystemPartition) { // not required + return nil + } + + for i := 0; i < len(m.SystemPartition); i++ { + if swag.IsZero(m.SystemPartition[i]) { // not required + continue + } + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this query device type image partition response based on the context it is used +func (m *QueryDeviceTypeImagePartitionResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDataPartition(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateSystemPartition(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *QueryDeviceTypeImagePartitionResponse) contextValidateDataPartition(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.DataPartition); i++ { + + if m.DataPartition[i] != nil { + if err := m.DataPartition[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *QueryDeviceTypeImagePartitionResponse) contextValidateSystemPartition(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.SystemPartition); i++ { + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *QueryDeviceTypeImagePartitionResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *QueryDeviceTypeImagePartitionResponse) UnmarshalBinary(b []byte) error { + var res QueryDeviceTypeImagePartitionResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/r_device_type_raid.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/r_device_type_raid.go new file mode 100644 index 0000000..fae862e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/r_device_type_raid.go @@ -0,0 +1,83 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RDeviceTypeRaid r device type raid +// +// swagger:model RDeviceTypeRaid +type RDeviceTypeRaid struct { + + // 可用分区值,单位GB + AvailableValue int64 `json:"availableValue,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 设备类型id + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // 磁盘类型:SAS/SATA/SSD/NVME + DiskInterfaceType string `json:"DiskInterfaceType,omitempty"` + + // 磁盘类型:SAS/SATA/SSD/NVME + DiskType string `json:"diskType,omitempty"` + + // RAID uuid + RaidID string `json:"raidId,omitempty"` + + // 系统盘noraid模式真实数量;此模式多块盘只能用一块 + SystemPartitionCount int64 `json:"systemPartitionCount,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 磁盘详细信息 + VolumeDetail string `json:"volumeDetail,omitempty"` + + // 磁盘类型 system/data + VolumeType string `json:"volumeType,omitempty"` +} + +// Validate validates this r device type raid +func (m *RDeviceTypeRaid) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this r device type raid based on context it is used +func (m *RDeviceTypeRaid) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RDeviceTypeRaid) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RDeviceTypeRaid) UnmarshalBinary(b []byte) error { + var res RDeviceTypeRaid + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/raid.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/raid.go new file mode 100644 index 0000000..7ebc7e4 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/raid.go @@ -0,0 +1,59 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Raid raid +// +// swagger:model Raid +type Raid struct { + + // 中文描述 + DescriptionEn string `json:"descriptionEn,omitempty"` + + // description + DescriptionZh string `json:"descriptionZh,omitempty"` + + // raid 名称 + Name string `json:"name,omitempty"` + + // raid uuid + RaidID string `json:"raidId,omitempty"` +} + +// Validate validates this raid +func (m *Raid) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this raid based on context it is used +func (m *Raid) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Raid) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Raid) UnmarshalBinary(b []byte) error { + var res Raid + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/raid_id.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/raid_id.go new file mode 100644 index 0000000..7883f4f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/raid_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RaidID raid Id +// +// swagger:model RaidId +type RaidID struct { + + // raid uuid + RaidID string `json:"raidId,omitempty"` +} + +// Validate validates this raid Id +func (m *RaidID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this raid Id based on context it is used +func (m *RaidID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RaidID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RaidID) UnmarshalBinary(b []byte) error { + var res RaidID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/raid_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/raid_list.go new file mode 100644 index 0000000..36ff208 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/raid_list.go @@ -0,0 +1,116 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RaidList raid list +// +// swagger:model RaidList +type RaidList struct { + + // raid实体列表 + Raids []*Raid `json:"raids"` +} + +// Validate validates this raid list +func (m *RaidList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRaids(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RaidList) validateRaids(formats strfmt.Registry) error { + if swag.IsZero(m.Raids) { // not required + return nil + } + + for i := 0; i < len(m.Raids); i++ { + if swag.IsZero(m.Raids[i]) { // not required + continue + } + + if m.Raids[i] != nil { + if err := m.Raids[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("raids" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("raids" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this raid list based on the context it is used +func (m *RaidList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateRaids(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RaidList) contextValidateRaids(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Raids); i++ { + + if m.Raids[i] != nil { + if err := m.Raids[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("raids" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("raids" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *RaidList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RaidList) UnmarshalBinary(b []byte) error { + var res RaidList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/read_messages_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/read_messages_request.go new file mode 100644 index 0000000..d133997 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/read_messages_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ReadMessagesRequest read messages request +// +// swagger:model ReadMessagesRequest +type ReadMessagesRequest struct { + + // message ids + // Required: true + MessageIds []string `json:"messageIds"` +} + +// Validate validates this read messages request +func (m *ReadMessagesRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateMessageIds(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ReadMessagesRequest) validateMessageIds(formats strfmt.Registry) error { + + if err := validate.Required("messageIds", "body", m.MessageIds); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this read messages request based on context it is used +func (m *ReadMessagesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ReadMessagesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ReadMessagesRequest) UnmarshalBinary(b []byte) error { + var res ReadMessagesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/reinstall_instance_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/reinstall_instance_request.go new file mode 100644 index 0000000..2ec09fd --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/reinstall_instance_request.go @@ -0,0 +1,257 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ReinstallInstanceRequest reinstall instance request +// +// swagger:model ReinstallInstanceRequest +type ReinstallInstanceRequest struct { + + // 引导模式 [UEFI Legacy/BIOS] + // Required: true + BootMode *string `json:"bootMode"` + + // 数据盘分区 + DataPartition []*Partition `json:"dataPartition"` + + // 描述 + Description string `json:"description,omitempty"` + + // 主机名称 + HostName string `json:"hostname,omitempty"` + + // 镜像ID + // Required: true + ImageID *string `json:"imageId"` + + // 是否安装bmp-agent + InstallBmpAgent bool `json:"installBmpAgent,omitempty"` + + // 实例名称 + // Required: true + InstanceName *string `json:"instanceName"` + + // 密码 + Password string `json:"password,omitempty"` + + // 秘钥ID,运营平台重装,密钥暂时不可用 + SSHKeyID string `json:"sshKeyId,omitempty"` + + // 系统盘分区 + SystemPartition []*Partition `json:"systemPartition"` + + // 系统盘RAID ID + // Required: true + SystemVolumeRaidID *string `json:"systemVolumeRaidId"` +} + +// Validate validates this reinstall instance request +func (m *ReinstallInstanceRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateBootMode(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDataPartition(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImageID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInstanceName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemPartition(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemVolumeRaidID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ReinstallInstanceRequest) validateBootMode(formats strfmt.Registry) error { + + if err := validate.Required("bootMode", "body", m.BootMode); err != nil { + return err + } + + return nil +} + +func (m *ReinstallInstanceRequest) validateDataPartition(formats strfmt.Registry) error { + if swag.IsZero(m.DataPartition) { // not required + return nil + } + + for i := 0; i < len(m.DataPartition); i++ { + if swag.IsZero(m.DataPartition[i]) { // not required + continue + } + + if m.DataPartition[i] != nil { + if err := m.DataPartition[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *ReinstallInstanceRequest) validateImageID(formats strfmt.Registry) error { + + if err := validate.Required("imageId", "body", m.ImageID); err != nil { + return err + } + + return nil +} + +func (m *ReinstallInstanceRequest) validateInstanceName(formats strfmt.Registry) error { + + if err := validate.Required("instanceName", "body", m.InstanceName); err != nil { + return err + } + + return nil +} + +func (m *ReinstallInstanceRequest) validateSystemPartition(formats strfmt.Registry) error { + if swag.IsZero(m.SystemPartition) { // not required + return nil + } + + for i := 0; i < len(m.SystemPartition); i++ { + if swag.IsZero(m.SystemPartition[i]) { // not required + continue + } + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *ReinstallInstanceRequest) validateSystemVolumeRaidID(formats strfmt.Registry) error { + + if err := validate.Required("systemVolumeRaidId", "body", m.SystemVolumeRaidID); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this reinstall instance request based on the context it is used +func (m *ReinstallInstanceRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDataPartition(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateSystemPartition(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ReinstallInstanceRequest) contextValidateDataPartition(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.DataPartition); i++ { + + if m.DataPartition[i] != nil { + if err := m.DataPartition[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *ReinstallInstanceRequest) contextValidateSystemPartition(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.SystemPartition); i++ { + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ReinstallInstanceRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ReinstallInstanceRequest) UnmarshalBinary(b []byte) error { + var res ReinstallInstanceRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/reset_instance_passwd_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/reset_instance_passwd_request.go new file mode 100644 index 0000000..0a735f2 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/reset_instance_passwd_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ResetInstancePasswdRequest 重置实例密码 +// +// swagger:model ResetInstancePasswdRequest +type ResetInstancePasswdRequest struct { + + // 新密码 + Password string `json:"password,omitempty"` +} + +// Validate validates this reset instance passwd request +func (m *ResetInstancePasswdRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this reset instance passwd request based on context it is used +func (m *ResetInstancePasswdRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ResetInstancePasswdRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ResetInstancePasswdRequest) UnmarshalBinary(b []byte) error { + var res ResetInstancePasswdRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/reset_instances_passwd_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/reset_instances_passwd_request.go new file mode 100644 index 0000000..fef10ab --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/reset_instances_passwd_request.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ResetInstancesPasswdRequest 批量重置实例密码 +// +// swagger:model ResetInstancesPasswdRequest +type ResetInstancesPasswdRequest struct { + + // 实例id列表 + InstanceIDs []string `json:"instance_ids"` + + // 新密码 + Password string `json:"password,omitempty"` +} + +// Validate validates this reset instances passwd request +func (m *ResetInstancesPasswdRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this reset instances passwd request based on context it is used +func (m *ResetInstancesPasswdRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ResetInstancesPasswdRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ResetInstancesPasswdRequest) UnmarshalBinary(b []byte) error { + var res ResetInstancesPasswdRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/restart_instances_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/restart_instances_request.go new file mode 100644 index 0000000..d26b5a8 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/restart_instances_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RestartInstancesRequest restart instances request +// +// swagger:model RestartInstancesRequest +type RestartInstancesRequest struct { + + // instance ids + InstanceIds []string `json:"instanceIds"` +} + +// Validate validates this restart instances request +func (m *RestartInstancesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this restart instances request based on context it is used +func (m *RestartInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RestartInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RestartInstancesRequest) UnmarshalBinary(b []byte) error { + var res RestartInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/role.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/role.go new file mode 100644 index 0000000..9881844 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/role.go @@ -0,0 +1,83 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Role role +// +// swagger:model Role +type Role struct { + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // description + DescriptionCn string `json:"descriptionCn,omitempty"` + + // 权限描述 + DescriptionEn string `json:"descriptionEn,omitempty"` + + // 权限 + Permission string `json:"permission,omitempty"` + + // 角色uuid + RoleID string `json:"roleId,omitempty"` + + // 角色名称 + RoleName string `json:"roleName,omitempty"` + + // 角色名称,唯一 + RoleNameCn string `json:"roleNameCn,omitempty"` + + // 角色名称,唯一 + RoleNameEn string `json:"roleNameEn,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 用户数 + UserCount int64 `json:"userCount,omitempty"` +} + +// Validate validates this role +func (m *Role) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this role based on context it is used +func (m *Role) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Role) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Role) UnmarshalBinary(b []byte) error { + var res Role + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/role_id.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/role_id.go new file mode 100644 index 0000000..a696dc6 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/role_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RoleID role Id +// +// swagger:model RoleId +type RoleID struct { + + // 角色uuid + RoleID string `json:"roleId,omitempty"` +} + +// Validate validates this role Id +func (m *RoleID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this role Id based on context it is used +func (m *RoleID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RoleID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RoleID) UnmarshalBinary(b []byte) error { + var res RoleID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/role_info.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/role_info.go new file mode 100644 index 0000000..bf39a63 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/role_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RoleInfo role info +// +// swagger:model RoleInfo +type RoleInfo struct { + + // role + Role *Role `json:"role,omitempty"` +} + +// Validate validates this role info +func (m *RoleInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRole(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RoleInfo) validateRole(formats strfmt.Registry) error { + if swag.IsZero(m.Role) { // not required + return nil + } + + if m.Role != nil { + if err := m.Role.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("role") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("role") + } + return err + } + } + + return nil +} + +// ContextValidate validate this role info based on the context it is used +func (m *RoleInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateRole(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RoleInfo) contextValidateRole(ctx context.Context, formats strfmt.Registry) error { + + if m.Role != nil { + if err := m.Role.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("role") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("role") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *RoleInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RoleInfo) UnmarshalBinary(b []byte) error { + var res RoleInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/role_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/role_list.go new file mode 100644 index 0000000..25876cb --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/role_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RoleList role list +// +// swagger:model RoleList +type RoleList struct { + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // 角色实体列表 + Roles []*Role `json:"roles"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this role list +func (m *RoleList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRoles(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RoleList) validateRoles(formats strfmt.Registry) error { + if swag.IsZero(m.Roles) { // not required + return nil + } + + for i := 0; i < len(m.Roles); i++ { + if swag.IsZero(m.Roles[i]) { // not required + continue + } + + if m.Roles[i] != nil { + if err := m.Roles[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("roles" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("roles" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this role list based on the context it is used +func (m *RoleList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateRoles(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RoleList) contextValidateRoles(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Roles); i++ { + + if m.Roles[i] != nil { + if err := m.Roles[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("roles" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("roles" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *RoleList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RoleList) UnmarshalBinary(b []byte) error { + var res RoleList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/rule.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/rule.go new file mode 100644 index 0000000..27fad1b --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/rule.go @@ -0,0 +1,264 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Rule rule +// +// swagger:model Rule +type Rule struct { + + // 盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag,omitempty"` + + // 维度 [instance、disk、mountpoint、nic] + Dimension string `json:"dimension,omitempty"` + + // 维度名称 [实例、盘符、挂载点、网卡] + DimensionName string `json:"dimensionName,omitempty"` + + // 关联实例个数 + InstanceCount int64 `json:"instanceCount,omitempty"` + + // 实例id列表 + InstanceIds []string `json:"instanceIds"` + + // 实例详细信息 + Instances []*Instance `json:"instances"` + + // 此规则关联的资源数 + RelatedResourceCount int64 `json:"relatedResourceCount,omitempty"` + + // 资源类型,目前只支持instance + Resource string `json:"resource,omitempty"` + + // 资源类型名称 实例 + ResourceName string `json:"resourceName,omitempty"` + + // 规则uuid + RuleID string `json:"ruleId,omitempty"` + + // 规则名称 + RuleName string `json:"ruleName,omitempty"` + + // 规则状态[1->正常,2->已禁用,3->报警] + Status int64 `json:"status,omitempty"` + + // 规则状态名称 + StatusName string `json:"statusName,omitempty"` + + // 触发条件描述 + TriggerDescription []string `json:"triggerDescription"` + + // 触发条件 + TriggerOption []*RuleTrigger `json:"triggerOption"` + + // user_id + UserID string `json:"userId,omitempty"` + + // user_name + UserName string `json:"userName,omitempty"` + + // notice option + NoticeOption *RuleNotice `json:"noticeOption,omitempty"` +} + +// Validate validates this rule +func (m *Rule) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstances(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTriggerOption(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNoticeOption(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Rule) validateInstances(formats strfmt.Registry) error { + if swag.IsZero(m.Instances) { // not required + return nil + } + + for i := 0; i < len(m.Instances); i++ { + if swag.IsZero(m.Instances[i]) { // not required + continue + } + + if m.Instances[i] != nil { + if err := m.Instances[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *Rule) validateTriggerOption(formats strfmt.Registry) error { + if swag.IsZero(m.TriggerOption) { // not required + return nil + } + + for i := 0; i < len(m.TriggerOption); i++ { + if swag.IsZero(m.TriggerOption[i]) { // not required + continue + } + + if m.TriggerOption[i] != nil { + if err := m.TriggerOption[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *Rule) validateNoticeOption(formats strfmt.Registry) error { + if swag.IsZero(m.NoticeOption) { // not required + return nil + } + + if m.NoticeOption != nil { + if err := m.NoticeOption.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("noticeOption") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("noticeOption") + } + return err + } + } + + return nil +} + +// ContextValidate validate this rule based on the context it is used +func (m *Rule) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateInstances(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateTriggerOption(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateNoticeOption(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Rule) contextValidateInstances(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Instances); i++ { + + if m.Instances[i] != nil { + if err := m.Instances[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *Rule) contextValidateTriggerOption(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.TriggerOption); i++ { + + if m.TriggerOption[i] != nil { + if err := m.TriggerOption[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("triggerOption" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *Rule) contextValidateNoticeOption(ctx context.Context, formats strfmt.Registry) error { + + if m.NoticeOption != nil { + if err := m.NoticeOption.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("noticeOption") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("noticeOption") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Rule) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Rule) UnmarshalBinary(b []byte) error { + var res Rule + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/rule_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/rule_list.go new file mode 100644 index 0000000..3744ca7 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/rule_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RuleList rule list +// +// swagger:model RuleList +type RuleList struct { + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // rules数组 + Rules []*Rule `json:"rules"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this rule list +func (m *RuleList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRules(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RuleList) validateRules(formats strfmt.Registry) error { + if swag.IsZero(m.Rules) { // not required + return nil + } + + for i := 0; i < len(m.Rules); i++ { + if swag.IsZero(m.Rules[i]) { // not required + continue + } + + if m.Rules[i] != nil { + if err := m.Rules[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("rules" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("rules" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this rule list based on the context it is used +func (m *RuleList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateRules(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RuleList) contextValidateRules(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Rules); i++ { + + if m.Rules[i] != nil { + if err := m.Rules[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("rules" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("rules" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *RuleList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RuleList) UnmarshalBinary(b []byte) error { + var res RuleList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/rule_notice.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/rule_notice.go new file mode 100644 index 0000000..43c7ea4 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/rule_notice.go @@ -0,0 +1,159 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// RuleNotice 通知策略 +// +// swagger:model RuleNotice +type RuleNotice struct { + + // 有效时段结束时间 ["23:59:59"] + // Required: true + EffectiveIntervalEnd *string `json:"effectiveIntervalEnd"` + + // 有效时段开始时间 ["00:00:00"] + // Required: true + EffectiveIntervalStart *string `json:"effectiveIntervalStart"` + + // 通知条件,可多选 [1表示报警, 2表示恢复正常] + // Required: true + NoticeCondition []int64 `json:"noticeCondition"` + + // 通知周期(分钟) [5 10 15 30 60 180 360 720 1440] + // Required: true + NoticePeriod *int64 `json:"noticePeriod"` + + // 接收渠道,可多选 [1表示站内信, 2表示邮件] + // Required: true + NoticeWay []int64 `json:"noticeWay"` + + // 通知对象用户Id + // Required: true + UserID *string `json:"userId"` + + // 通知对象用户 + UserName string `json:"userName,omitempty"` +} + +// Validate validates this rule notice +func (m *RuleNotice) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateEffectiveIntervalEnd(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEffectiveIntervalStart(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNoticeCondition(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNoticePeriod(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNoticeWay(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RuleNotice) validateEffectiveIntervalEnd(formats strfmt.Registry) error { + + if err := validate.Required("effectiveIntervalEnd", "body", m.EffectiveIntervalEnd); err != nil { + return err + } + + return nil +} + +func (m *RuleNotice) validateEffectiveIntervalStart(formats strfmt.Registry) error { + + if err := validate.Required("effectiveIntervalStart", "body", m.EffectiveIntervalStart); err != nil { + return err + } + + return nil +} + +func (m *RuleNotice) validateNoticeCondition(formats strfmt.Registry) error { + + if err := validate.Required("noticeCondition", "body", m.NoticeCondition); err != nil { + return err + } + + return nil +} + +func (m *RuleNotice) validateNoticePeriod(formats strfmt.Registry) error { + + if err := validate.Required("noticePeriod", "body", m.NoticePeriod); err != nil { + return err + } + + return nil +} + +func (m *RuleNotice) validateNoticeWay(formats strfmt.Registry) error { + + if err := validate.Required("noticeWay", "body", m.NoticeWay); err != nil { + return err + } + + return nil +} + +func (m *RuleNotice) validateUserID(formats strfmt.Registry) error { + + if err := validate.Required("userId", "body", m.UserID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this rule notice based on context it is used +func (m *RuleNotice) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RuleNotice) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RuleNotice) UnmarshalBinary(b []byte) error { + var res RuleNotice + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/rule_trigger.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/rule_trigger.go new file mode 100644 index 0000000..e7f3f9e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/rule_trigger.go @@ -0,0 +1,185 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// RuleTrigger 单个触发条件 +// +// swagger:model RuleTrigger +type RuleTrigger struct { + + // 计算方式 [min max avg sum] + // Required: true + Calculation *string `json:"calculation"` + + // 计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出] + CalculationUnit string `json:"calculationUnit,omitempty"` + + // 对此rule的描述 + Description string `json:"description,omitempty"` + + // 监控指标 cps.cpu.util + // Required: true + Metric *string `json:"metric"` + + // 监控指标名称 CPU使用率 + MetricName string `json:"metricName,omitempty"` + + // 告警级别 [1表示一般,2表示严重,3表示紧急] + // Required: true + NoticeLevel *int64 `json:"noticeLevel"` + + // 比较方式 [> >= < <= == !=]或者[gt gte lt lte eq neq] + // Required: true + Operation *string `json:"operation"` + + // 周期 5(分钟) + // Required: true + Period *int64 `json:"period"` + + // [bmp_monitor_counter, bmp_monitor_gauge] + TableName string `json:"tableName,omitempty"` + + // 阈值 + // Required: true + Threshold *float64 `json:"threshold"` + + // 持续周期数 [1, 2, 3, 5, 10, 15, 30, 60] + // Required: true + Times *int64 `json:"times"` +} + +// Validate validates this rule trigger +func (m *RuleTrigger) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCalculation(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMetric(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNoticeLevel(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOperation(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePeriod(formats); err != nil { + res = append(res, err) + } + + if err := m.validateThreshold(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTimes(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RuleTrigger) validateCalculation(formats strfmt.Registry) error { + + if err := validate.Required("calculation", "body", m.Calculation); err != nil { + return err + } + + return nil +} + +func (m *RuleTrigger) validateMetric(formats strfmt.Registry) error { + + if err := validate.Required("metric", "body", m.Metric); err != nil { + return err + } + + return nil +} + +func (m *RuleTrigger) validateNoticeLevel(formats strfmt.Registry) error { + + if err := validate.Required("noticeLevel", "body", m.NoticeLevel); err != nil { + return err + } + + return nil +} + +func (m *RuleTrigger) validateOperation(formats strfmt.Registry) error { + + if err := validate.Required("operation", "body", m.Operation); err != nil { + return err + } + + return nil +} + +func (m *RuleTrigger) validatePeriod(formats strfmt.Registry) error { + + if err := validate.Required("period", "body", m.Period); err != nil { + return err + } + + return nil +} + +func (m *RuleTrigger) validateThreshold(formats strfmt.Registry) error { + + if err := validate.Required("threshold", "body", m.Threshold); err != nil { + return err + } + + return nil +} + +func (m *RuleTrigger) validateTimes(formats strfmt.Registry) error { + + if err := validate.Required("times", "body", m.Times); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this rule trigger based on context it is used +func (m *RuleTrigger) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RuleTrigger) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RuleTrigger) UnmarshalBinary(b []byte) error { + var res RuleTrigger + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/save_is_push_mail_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/save_is_push_mail_request.go new file mode 100644 index 0000000..0919806 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/save_is_push_mail_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// SaveIsPushMailRequest save is push mail request +// +// swagger:model SaveIsPushMailRequest +type SaveIsPushMailRequest struct { + + // 是否推送邮件告警,0不推送,1推送 + IsPush string `json:"is_push,omitempty"` +} + +// Validate validates this save is push mail request +func (m *SaveIsPushMailRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this save is push mail request based on context it is used +func (m *SaveIsPushMailRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SaveIsPushMailRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SaveIsPushMailRequest) UnmarshalBinary(b []byte) error { + var res SaveIsPushMailRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/share_project.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/share_project.go new file mode 100644 index 0000000..d31ebb0 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/share_project.go @@ -0,0 +1,143 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ShareProject share project +// +// swagger:model ShareProject +type ShareProject struct { + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 项目拥有者用户id + OwnerUserID string `json:"ownerUserId,omitempty"` + + // 项目拥有者用户名 + OwnerUserName string `json:"ownerUserName,omitempty"` + + // 项目uuid + ProjectID string `json:"projectId,omitempty"` + + // 项目名称 + ProjectName string `json:"projectName,omitempty"` + + // share projects + ShareProjects []*ShareProject `json:"shareProjects"` + + // 项目共享者用户id + SharedUserID string `json:"sharedUserId,omitempty"` + + // 项目拥有者用户名 + SharedUserName string `json:"sharedUserName,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` +} + +// Validate validates this share project +func (m *ShareProject) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateShareProjects(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ShareProject) validateShareProjects(formats strfmt.Registry) error { + if swag.IsZero(m.ShareProjects) { // not required + return nil + } + + for i := 0; i < len(m.ShareProjects); i++ { + if swag.IsZero(m.ShareProjects[i]) { // not required + continue + } + + if m.ShareProjects[i] != nil { + if err := m.ShareProjects[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this share project based on the context it is used +func (m *ShareProject) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateShareProjects(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ShareProject) contextValidateShareProjects(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.ShareProjects); i++ { + + if m.ShareProjects[i] != nil { + if err := m.ShareProjects[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ShareProject) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ShareProject) UnmarshalBinary(b []byte) error { + var res ShareProject + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/share_project_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/share_project_request.go new file mode 100644 index 0000000..f98de44 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/share_project_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ShareProjectRequest share project request +// +// swagger:model ShareProjectRequest +type ShareProjectRequest struct { + + // from user_id + // Required: true + OwnerID *string `json:"ownerID"` + + // to user_id + // Required: true + SharerID *string `json:"sharerID"` +} + +// Validate validates this share project request +func (m *ShareProjectRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateOwnerID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSharerID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ShareProjectRequest) validateOwnerID(formats strfmt.Registry) error { + + if err := validate.Required("ownerID", "body", m.OwnerID); err != nil { + return err + } + + return nil +} + +func (m *ShareProjectRequest) validateSharerID(formats strfmt.Registry) error { + + if err := validate.Required("sharerID", "body", m.SharerID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this share project request based on context it is used +func (m *ShareProjectRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ShareProjectRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ShareProjectRequest) UnmarshalBinary(b []byte) error { + var res ShareProjectRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/sshkey.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/sshkey.go new file mode 100644 index 0000000..5a0fae4 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/sshkey.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Sshkey sshkey +// +// swagger:model Sshkey +type Sshkey struct { + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 公钥指纹 + FingerPrint string `json:"fingerPrint,omitempty"` + + // id + ID int64 `json:"id,omitempty"` + + // 公钥,格式:ssh-rsa AAA + Key string `json:"key,omitempty"` + + // 秘钥名称 + Name string `json:"name,omitempty"` + + // 秘钥uuid + SshkeyID string `json:"sshkeyId,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 所属用户uuid + UserID string `json:"userId,omitempty"` +} + +// Validate validates this sshkey +func (m *Sshkey) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this sshkey based on context it is used +func (m *Sshkey) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Sshkey) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Sshkey) UnmarshalBinary(b []byte) error { + var res Sshkey + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/sshkey_id.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/sshkey_id.go new file mode 100644 index 0000000..c14abe6 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/sshkey_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// SshkeyID sshkey Id +// +// swagger:model SshkeyId +type SshkeyID struct { + + // sshkey uuid + SshkeyID string `json:"sshkeyId,omitempty"` +} + +// Validate validates this sshkey Id +func (m *SshkeyID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this sshkey Id based on context it is used +func (m *SshkeyID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SshkeyID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SshkeyID) UnmarshalBinary(b []byte) error { + var res SshkeyID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/sshkey_info.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/sshkey_info.go new file mode 100644 index 0000000..60eb531 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/sshkey_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// SshkeyInfo sshkey info +// +// swagger:model SshkeyInfo +type SshkeyInfo struct { + + // sshkey + Sshkey *Sshkey `json:"sshkey,omitempty"` +} + +// Validate validates this sshkey info +func (m *SshkeyInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSshkey(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SshkeyInfo) validateSshkey(formats strfmt.Registry) error { + if swag.IsZero(m.Sshkey) { // not required + return nil + } + + if m.Sshkey != nil { + if err := m.Sshkey.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sshkey") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sshkey") + } + return err + } + } + + return nil +} + +// ContextValidate validate this sshkey info based on the context it is used +func (m *SshkeyInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSshkey(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SshkeyInfo) contextValidateSshkey(ctx context.Context, formats strfmt.Registry) error { + + if m.Sshkey != nil { + if err := m.Sshkey.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sshkey") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sshkey") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SshkeyInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SshkeyInfo) UnmarshalBinary(b []byte) error { + var res SshkeyInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/sshkey_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/sshkey_list.go new file mode 100644 index 0000000..af8e27f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/sshkey_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// SshkeyList sshkey list +// +// swagger:model SshkeyList +type SshkeyList struct { + + // 页数 + PageNumber int64 `json:"pageNumber,omitempty"` + + // 页大小 + PageSize int64 `json:"pageSize,omitempty"` + + // sshkey实体列表 + Sshkeys []*Sshkey `json:"sshkeys"` + + // 总条数 + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this sshkey list +func (m *SshkeyList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSshkeys(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SshkeyList) validateSshkeys(formats strfmt.Registry) error { + if swag.IsZero(m.Sshkeys) { // not required + return nil + } + + for i := 0; i < len(m.Sshkeys); i++ { + if swag.IsZero(m.Sshkeys[i]) { // not required + continue + } + + if m.Sshkeys[i] != nil { + if err := m.Sshkeys[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sshkeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sshkeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this sshkey list based on the context it is used +func (m *SshkeyList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSshkeys(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SshkeyList) contextValidateSshkeys(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Sshkeys); i++ { + + if m.Sshkeys[i] != nil { + if err := m.Sshkeys[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sshkeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sshkeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SshkeyList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SshkeyList) UnmarshalBinary(b []byte) error { + var res SshkeyList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/start_instances_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/start_instances_request.go new file mode 100644 index 0000000..cb20838 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/start_instances_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// StartInstancesRequest start instances request +// +// swagger:model StartInstancesRequest +type StartInstancesRequest struct { + + // instance ids + InstanceIds []string `json:"instanceIds"` +} + +// Validate validates this start instances request +func (m *StartInstancesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this start instances request based on context it is used +func (m *StartInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *StartInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *StartInstancesRequest) UnmarshalBinary(b []byte) error { + var res StartInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/stop_instances_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/stop_instances_request.go new file mode 100644 index 0000000..ae9f8d3 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/stop_instances_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// StopInstancesRequest stop instances request +// +// swagger:model StopInstancesRequest +type StopInstancesRequest struct { + + // instance ids + InstanceIds []string `json:"instanceIds"` +} + +// Validate validates this stop instances request +func (m *StopInstancesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this stop instances request based on context it is used +func (m *StopInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *StopInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *StopInstancesRequest) UnmarshalBinary(b []byte) error { + var res StopInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/tags_response.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/tags_response.go new file mode 100644 index 0000000..45fe4aa --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/tags_response.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// TagsResponse tags response +// +// swagger:model TagsResponse +type TagsResponse struct { + + // tags + Tags []string `json:"tags"` +} + +// Validate validates this tags response +func (m *TagsResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this tags response based on context it is used +func (m *TagsResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *TagsResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *TagsResponse) UnmarshalBinary(b []byte) error { + var res TagsResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/un_mount_devices_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/un_mount_devices_request.go new file mode 100644 index 0000000..292ef2a --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/un_mount_devices_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// UnMountDevicesRequest un mount devices request +// +// swagger:model UnMountDevicesRequest +type UnMountDevicesRequest struct { + + // 设备uuid + // Required: true + DeviceID *string `json:"deviceId"` +} + +// Validate validates this un mount devices request +func (m *UnMountDevicesRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UnMountDevicesRequest) validateDeviceID(formats strfmt.Registry) error { + + if err := validate.Required("deviceId", "body", m.DeviceID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this un mount devices request based on context it is used +func (m *UnMountDevicesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *UnMountDevicesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UnMountDevicesRequest) UnmarshalBinary(b []byte) error { + var res UnMountDevicesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/user.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/user.go new file mode 100644 index 0000000..9273de3 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/user.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// User user +// +// swagger:model User +type User struct { + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 用户默认项目uuid + DefaultProjectID string `json:"defaultProjectId,omitempty"` + + // 用户默认项目名称 + DefaultProjectName string `json:"defaultProjectName,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 邮箱 + Email string `json:"email,omitempty"` + + // 用户id + ID int64 `json:"id,omitempty"` + + // 用户拥有的实例数量 + InstanceCount int64 `json:"instanceCount,omitempty"` + + // 默认语言(en_US/zh_CN) + Language string `json:"language,omitempty"` + + // 手机号 + PhoneNumber string `json:"phoneNumber,omitempty"` + + // 国家地区码,如86 + PhonePrefix string `json:"phonePrefix,omitempty"` + + // 用户拥有的项目数量 + ProjectCount int64 `json:"projectCount,omitempty"` + + // 角色uuid + RoleID string `json:"roleId,omitempty"` + + // 角色名称 + RoleName string `json:"roleName,omitempty"` + + // 时区 + Timezone string `json:"timezone,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 用户uuid + UserID string `json:"userId,omitempty"` + + // 用户名,唯一 + UserName string `json:"userName,omitempty"` +} + +// Validate validates this user +func (m *User) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this user based on context it is used +func (m *User) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *User) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *User) UnmarshalBinary(b []byte) error { + var res User + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/user_id.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/user_id.go new file mode 100644 index 0000000..c107f76 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/user_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// UserID user Id +// +// swagger:model UserId +type UserID struct { + + // 用户uuid + UserID string `json:"userId,omitempty"` +} + +// Validate validates this user Id +func (m *UserID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this user Id based on context it is used +func (m *UserID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *UserID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UserID) UnmarshalBinary(b []byte) error { + var res UserID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/user_info.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/user_info.go new file mode 100644 index 0000000..81d4111 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/user_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// UserInfo user info +// +// swagger:model UserInfo +type UserInfo struct { + + // user + User *User `json:"user,omitempty"` +} + +// Validate validates this user info +func (m *UserInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateUser(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UserInfo) validateUser(formats strfmt.Registry) error { + if swag.IsZero(m.User) { // not required + return nil + } + + if m.User != nil { + if err := m.User.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("user") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("user") + } + return err + } + } + + return nil +} + +// ContextValidate validate this user info based on the context it is used +func (m *UserInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateUser(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UserInfo) contextValidateUser(ctx context.Context, formats strfmt.Registry) error { + + if m.User != nil { + if err := m.User.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("user") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("user") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *UserInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UserInfo) UnmarshalBinary(b []byte) error { + var res UserInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/user_list.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/user_list.go new file mode 100644 index 0000000..b072faa --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/user_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// UserList user list +// +// swagger:model UserList +type UserList struct { + + // 页数 + PageNumber int64 `json:"pageNumber,omitempty"` + + // 页大小 + PageSize int64 `json:"pageSize,omitempty"` + + // 总条数 + TotalCount int64 `json:"totalCount,omitempty"` + + // user实体列表 + Users []*User `json:"users"` +} + +// Validate validates this user list +func (m *UserList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateUsers(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UserList) validateUsers(formats strfmt.Registry) error { + if swag.IsZero(m.Users) { // not required + return nil + } + + for i := 0; i < len(m.Users); i++ { + if swag.IsZero(m.Users[i]) { // not required + continue + } + + if m.Users[i] != nil { + if err := m.Users[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("users" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("users" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this user list based on the context it is used +func (m *UserList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateUsers(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UserList) contextValidateUsers(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Users); i++ { + + if m.Users[i] != nil { + if err := m.Users[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("users" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("users" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *UserList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UserList) UnmarshalBinary(b []byte) error { + var res UserList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/verify_user_request.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/verify_user_request.go new file mode 100644 index 0000000..e902b1c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/verify_user_request.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// VerifyUserRequest verify user request +// +// swagger:model VerifyUserRequest +type VerifyUserRequest struct { + + // 密码 + // Required: true + Password *string `json:"password"` + + // 角色uuid + // Required: true + RoleID *string `json:"roleId"` + + // 用户名,唯一 + // Required: true + UserName *string `json:"userName"` +} + +// Validate validates this verify user request +func (m *VerifyUserRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validatePassword(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRoleID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *VerifyUserRequest) validatePassword(formats strfmt.Registry) error { + + if err := validate.Required("password", "body", m.Password); err != nil { + return err + } + + return nil +} + +func (m *VerifyUserRequest) validateRoleID(formats strfmt.Registry) error { + + if err := validate.Required("roleId", "body", m.RoleID); err != nil { + return err + } + + return nil +} + +func (m *VerifyUserRequest) validateUserName(formats strfmt.Registry) error { + + if err := validate.Required("userName", "body", m.UserName); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this verify user request based on context it is used +func (m *VerifyUserRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *VerifyUserRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *VerifyUserRequest) UnmarshalBinary(b []byte) error { + var res VerifyUserRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/volume.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/volume.go new file mode 100644 index 0000000..f0b8f9e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/volume.go @@ -0,0 +1,80 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Volume volume +// +// swagger:model Volume +type Volume struct { + + // disk type + DiskType string `json:"diskType,omitempty"` + + // interface type + InterfaceType string `json:"interfaceType,omitempty"` + + // raid + Raid string `json:"raid,omitempty"` + + // raid can + RaidCan string `json:"raidCan,omitempty"` + + // raid Id + RaidID string `json:"raidId,omitempty"` + + // volume amount + VolumeAmount int64 `json:"volumeAmount,omitempty"` + + // volume ID + VolumeID string `json:"volumeId,omitempty"` + + // volume name + VolumeName string `json:"volumeName,omitempty"` + + // volume size + VolumeSize string `json:"volumeSize,omitempty"` + + // volume type + VolumeType string `json:"volumeType,omitempty"` + + // volume unit + VolumeUnit string `json:"volumeUnit,omitempty"` +} + +// Validate validates this volume +func (m *Volume) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this volume based on context it is used +func (m *Volume) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Volume) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Volume) UnmarshalBinary(b []byte) error { + var res Volume + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/volume_it.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/volume_it.go new file mode 100644 index 0000000..22969e5 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/volume_it.go @@ -0,0 +1,206 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// VolumeIt volume it +// +// swagger:model VolumeIt +type VolumeIt struct { + + // disk type + DiskType string `json:"diskType,omitempty"` + + // disks + Disks []*Disk `json:"disks"` + + // interface type + InterfaceType string `json:"interfaceType,omitempty"` + + // raid + Raid string `json:"raid,omitempty"` + + // raid can + RaidCan string `json:"raidCan,omitempty"` + + // raid Id + RaidID string `json:"raidId,omitempty"` + + // raids + Raids []*Raid `json:"raids"` + + // volume amount + VolumeAmount int64 `json:"volumeAmount,omitempty"` + + // volume ID + VolumeID string `json:"volumeId,omitempty"` + + // volume name + VolumeName string `json:"volumeName,omitempty"` + + // volume size + VolumeSize string `json:"volumeSize,omitempty"` + + // volume type + VolumeType string `json:"volumeType,omitempty"` + + // volume unit + VolumeUnit string `json:"volumeUnit,omitempty"` +} + +// Validate validates this volume it +func (m *VolumeIt) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDisks(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRaids(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *VolumeIt) validateDisks(formats strfmt.Registry) error { + if swag.IsZero(m.Disks) { // not required + return nil + } + + for i := 0; i < len(m.Disks); i++ { + if swag.IsZero(m.Disks[i]) { // not required + continue + } + + if m.Disks[i] != nil { + if err := m.Disks[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("disks" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("disks" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *VolumeIt) validateRaids(formats strfmt.Registry) error { + if swag.IsZero(m.Raids) { // not required + return nil + } + + for i := 0; i < len(m.Raids); i++ { + if swag.IsZero(m.Raids[i]) { // not required + continue + } + + if m.Raids[i] != nil { + if err := m.Raids[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("raids" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("raids" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this volume it based on the context it is used +func (m *VolumeIt) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDisks(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateRaids(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *VolumeIt) contextValidateDisks(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Disks); i++ { + + if m.Disks[i] != nil { + if err := m.Disks[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("disks" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("disks" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *VolumeIt) contextValidateRaids(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Raids); i++ { + + if m.Raids[i] != nil { + if err := m.Raids[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("raids" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("raids" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *VolumeIt) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *VolumeIt) UnmarshalBinary(b []byte) error { + var res VolumeIt + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/volume_item.go b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/volume_item.go new file mode 100644 index 0000000..b231e17 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/bmp-openapi-sdk/models/volume_item.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// VolumeItem volume item +// +// swagger:model VolumeItem +type VolumeItem struct { + + // device type ID + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // disk type + DiskType string `json:"diskType,omitempty"` + + // interface type + InterfaceType string `json:"interfaceType,omitempty"` + + // raid + Raid string `json:"raid,omitempty"` + + // raid can + RaidCan string `json:"raidCan,omitempty"` + + // volume amount + VolumeAmount int64 `json:"volumeAmount,omitempty"` + + // volume name + VolumeName string `json:"volumeName,omitempty"` + + // volume size + VolumeSize string `json:"volumeSize,omitempty"` + + // volume type + VolumeType string `json:"volumeType,omitempty"` + + // volume unit + VolumeUnit string `json:"volumeUnit,omitempty"` +} + +// Validate validates this volume item +func (m *VolumeItem) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this volume item based on context it is used +func (m *VolumeItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *VolumeItem) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *VolumeItem) UnmarshalBinary(b []byte) error { + var res VolumeItem + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/bmp-operation-api/bmp_vendor/ironic-common/exception/exception.go b/bmp-operation-api/bmp_vendor/ironic-common/exception/exception.go new file mode 100644 index 0000000..daf985f --- /dev/null +++ b/bmp-operation-api/bmp_vendor/ironic-common/exception/exception.go @@ -0,0 +1,24 @@ +package exception + +import ( + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +type Exception struct { + Status int `json:"code"` + ErrorCode string `json:"status"` + Msg string `json:"message"` +} + +var CommonParamValid = Exception{ + Status: httpStatus.BAD_REQUEST, + ErrorCode: errorCode.INVALID_ARGUMENT, + Msg: "param invalid", +} + +var InternalError = Exception{ + Status: httpStatus.INTERNAL_SERVER_ERROR, + ErrorCode: errorCode.INTERNAL, + Msg: "内部错误", +} diff --git a/bmp-operation-api/bmp_vendor/ironic-common/go.mod b/bmp-operation-api/bmp_vendor/ironic-common/go.mod new file mode 100644 index 0000000..5364f89 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/ironic-common/go.mod @@ -0,0 +1,3 @@ +module git.jd.com/cps-golang/ironic-common + +go 1.17 diff --git a/bmp-operation-api/bmp_vendor/ironic-common/ironic/common/ErrorCode/ErrorCode.go b/bmp-operation-api/bmp_vendor/ironic-common/ironic/common/ErrorCode/ErrorCode.go new file mode 100644 index 0000000..68743e6 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/ironic-common/ironic/common/ErrorCode/ErrorCode.go @@ -0,0 +1,134 @@ +package ErrorCode + +const ( + // 此操作需要的预置条件不满足 400 + FAILED_PRECONDITION = "FAILED_PRECONDITION" + + // 参数错误 400 + INVALID_ARGUMENT = "INVALID_ARGUMENT" + + // 缺少参数 400 + MISSING_ARGUMENT = "MISSING_ARGUMENT" + + // 参数类型不匹配400 + MISMATCH_ARGUMENT_TYPE = "MISMATCH_ARGUMENT_TYPE" + + // 无效的action 400 + INVALID_ACTION = "INVALID_ACTION" + + // 参数超出范围 400 + OUT_OF_RANGE = "OUT_OF_RANGE" + + // 缺少Multipart 400 + MISSING_MULTIPART = "MISSING_MULTIPART" + + // 缺少header信息 400 + MISSING_HEADER = "MISSING_HEADER" + + // pathVariable参数错误 400 + INVALID_PATHVARIABLE = "INVALID_PATHVARIABLE" + + // 验证失败 401 + UNAUTHENTICATED = "UNAUTHENTICATED" + + // 用户未激活 402 + USER_NOT_ACTIVE = "USER_NOT_ACTIVE" + + // 没有权限 403 + HTTP_FORBIDDEN = "HTTP_FORBIDDEN" + + // 找不到对象 404 + NOT_FOUND = "NOT_FOUND" + + // 操作终止 409 + ABORTED = "ABORTED" + + // 对象已存在 409 + ALREADY_EXISTS = "ALREADY_EXISTS" + + // 媒体类型不支持 415 + UNSUPPORTED_MEDIA_TYPE = "UNSUPPORTED_MEDIA_TYPE" + + // 不支持的请求方法 405 + UNSUPPORTED_HTTP_REQUEST_METHOD = "UNSUPPORTED_HTTP_REQUEST_METHOD" + + // 配额不足 429 + QUOTA_EXCEEDED = "QUOTA_EXCEEDED" + + // 库存不足429 + STOCK_SHORTAGE = "STOCK_SHORTAGE" + + // 未知错误 500 + UNKNOWN = "UNKNOWN" + + // 内部错误 500 + INTERNAL = "INTERNAL" + + // 服务不可用 503 + UNAVAILABLE = "UNAVAILABLE" + + // 会话网关 Timeout 504 + SESSION_GATEWAY_TIMEOUT = "SESSION_GATEWAY_TIMEOUT" + + // 参数错误 + PARAMETER_ERROR = "PARAMETER_ERROR" + + //com.jcloud.cps.ironic.common.ErrorCode + UNSUPPORTED_OPERATION = "UNSUPPORTED_OPERATION" + + // 子网没有可用的内网IP可以分配 400 + EXHAUSTED_SUBNET = "EXHAUSTED_SUBNET" + + EXHAUSTED_PUBLIC_IP = "EXHAUSTED_PUBLIC_IP" + + UNSUPPORTED_RAID_TYPE = "UNSUPPORTED_RAID_TYPE" + + CHANGE_ARE_NOT_ALLOWED = "CHANGE_ARE_NOT_ALLOWED" + + // 权限校验失败 + NO_PERMISSION = "NO_PERMISSION" + + // 资源被占用 + RESOURCE_IN_USE = "RESOURCE_IN_USE" + + // 内网IP超出范围 + PRIVATE_IP_NOT_IN_SUBNET = "PRIVATE_IP_NOT_IN_SUBNET" + + // EIP已经绑定 + EIP_ALREADY_ASSOCIATE = "EIP_ALREADY_ASSOCIATE" + + // EIP未绑定 + EIP_HAS_NOT_ASSOCIATE = "EIP_HAS_NOT_ASSOCIATE" + + // 子网未开通IPv6 + SUBNET_HAS_NOT_ASSIGN_IPV6 = "SUBNET_HAS_NOT_ASSIGN_IPV6" + + // IPV6已经被分配 + IPV6_ALREADY_ASSIGN = "IPV6_ALREADY_ASSIGN" + + // 实例已经绑定EIP + INSTANCE_ALREADY_ASSOCIATE_EIP = "INSTANCE_ALREADY_ASSOCIATE_EIP" + + // 实例还没有绑定EIP + INSTANCE_HAS_NOT_ASSOCIATE_EIP = "INSTANCE_HAS_NOT_ASSOCIATE_EIP" + + // 实例已经绑定IPV6 + INSTANCE_ALREADY_ASSOCIATE_IPV6 = "INSTANCE_ALREADY_ASSOCIATE_IPV6" + + // 基础网路不支持EIP + UNSUPPORTED_EIP_IN_BASIC_NETWORK = "UNSUPPORTED_EIP_IN_BASIC_NETWORK" + + // VPC网络不支持调整带宽 + UNSUPPORTED_MODIFY_BANDWIDTH_IN_VPC_NETWORK = "UNSUPPORTED_MODIFY_BANDWIDTH_IN_VPC_NETWORK" + + // 不支持批量指定内网IP + UNSUPPORTED_BATCH_SPECIFYING_PRIVATE_IP = "UNSUPPORTED_BATCH_SPECIFYING_PRIVATE_IP" + + // 不支持批量指定别名IP + UNSUPPORTED_BATCH_SPECIFYING_ALIAS_IP = "UNSUPPORTED_BATCH_SPECIFYING_ALIAS_IP" + + // 密钥对正在被实例使用 + KEYPAIR_IS_USING_BY_INSTANCE = "KEYPAIR_IS_USING_BY_INSTANCE" + + ARGUMENT_ERROR = "ARGUMENT_ERROR" +) diff --git a/bmp-operation-api/bmp_vendor/ironic-common/ironic/common/Validation/Validation.go b/bmp-operation-api/bmp_vendor/ironic-common/ironic/common/Validation/Validation.go new file mode 100644 index 0000000..9c6f3dc --- /dev/null +++ b/bmp-operation-api/bmp_vendor/ironic-common/ironic/common/Validation/Validation.go @@ -0,0 +1,16 @@ +package Validation + +const ( + REGEX_ID string = `^[a-zA-Z0-9-_]{2,36}$` + REGEX_RAID_VOLUME_TYPE string = `^system$|^data$` + REGEX_NETWORK_TYPE string = `^basic$|^vpc$|^retail$` + INTERFACE_MODE string = `^bond$|^dual$` + REGEX_IP_ADDRESS string = `(^127\.0\.0\.1)|(^192\.168)|(^10\.)|(^172\.1[6-9])|(^172\.2[0-9])|(^172\.3[0-1])` + REGEX_CIDR string = `(10|11|172|192)\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,3})` + REGEX_PASSWORD string = "^(?=.*[a-z])(?=.*[A-Z])(?=.*[\\d\\* \\(\\)`~!@#\\$%&_\\-+=\\|\\{\\}\\[\\]:\";\\'<>,.\\?\\/\\)])[a-zA-Z\\d\\* \\(\\)`~!@#\\$%&_\\-+=\\|\\{\\}\\[\\]:\";\\'<>,.\\?\\/\\)]{8,30}$" + REGEX_DEVICE_STATUS string = "^putawaying$|^creating$|^starting$|^running$|^stopping$|^stopped$|^restarting$|^error$|^upgrading$|^reinstalling$|^destroying$|^resetting_password$" + REGEX_RSA_PUBLIC_KEY string = "^ssh-rsa AAAAB3NzaC1yc2.*" + REGEX_MAIL_TYPE string = "^api_error$|^command_warning$" + REGEX_EMAIL string = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}" + REGEX_SOURCE_TYPE string = "^common$|^customize$|^user_defined$" +) diff --git a/bmp-operation-api/bmp_vendor/ironic-common/ironic/enums/HttpStatus/HttpStatus.go b/bmp-operation-api/bmp_vendor/ironic-common/ironic/enums/HttpStatus/HttpStatus.go new file mode 100644 index 0000000..243c37c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/ironic-common/ironic/enums/HttpStatus/HttpStatus.go @@ -0,0 +1,66 @@ +package HttpStatus + +// refer https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpStatus.html +const ( + ACCEPTED = 202 //Accepted. + ALREADY_REPORTED = 208 //Already Reported. + BAD_GATEWAY = 502 //Bad Gateway. + BAD_REQUEST = 400 //Bad Request. + BANDWIDTH_LIMIT_EXCEEDED = 509 //Bandwidth Limit Exceeded + CHECKPOINT = 103 //Checkpoint. + CONFLICT = 409 //Conflict. + CONTINUE = 100 //Continue. + CREATED = 201 //Created. + EXPECTATION_FAILED = 417 //Expectation Failed. + FAILED_DEPENDENCY = 424 //Failed Dependency. + FORBIDDEN = 403 //Forbidden. + FOUND = 302 //Found. + GATEWAY_TIMEOUT = 504 //Gateway Timeout. + GONE = 410 //Gone. + HTTP_VERSION_NOT_SUPPORTED = 505 //HTTP Version Not Supported. + I_AM_A_TEAPOT = 418 //I'm a teapot. + IM_USED = 226 //IM Used. + INSUFFICIENT_STORAGE = 507 //Insufficient Storage + INTERNAL_SERVER_ERROR = 500 //Internal Server Error. + LENGTH_REQUIRED = 411 //Length Required. + LOCKED = 423 //Locked. + LOOP_DETECTED = 508 //Loop Detected + METHOD_NOT_ALLOWED = 405 //Method Not Allowed. + MOVED_PERMANENTLY = 301 //Moved Permanently. = MOVE//D_TEMPORARILY Deprecated in favor of FOUND which will be returned from HttpStatusvalueOf(302). + MULTI_STATUS = 207 //Multi-Status. + MULTIPLE_CHOICES = 300 //Multiple Choices. + NETWORK_AUTHENTICATION_REQUIRED = 511 //Network Authentication Required. + NO_CONTENT = 204 //No Content. + NON_AUTHORITATIVE_INFORMATION = 203 //Non-Authoritative Information. + NOT_ACCEPTABLE = 406 //Not Acceptable. + NOT_EXTENDED = 510 //Not Extended + NOT_FOUND = 404 //Not Found. + NOT_IMPLEMENTED = 501 //Not Implemented. + NOT_MODIFIED = 304 //Not Modified. + OK = 200 //OK. + PARTIAL_CONTENT = 206 //Partial Content. + PAYLOAD_TOO_LARGE = 413 //Payload Too Large. + PAYMENT_REQUIRED = 402 //Payment Required. + PERMANENT_REDIRECT = 308 //Permanent Redirect. + PRECONDITION_FAILED = 412 //Precondition failed. + PRECONDITION_REQUIRED = 428 //Precondition Required. + PROCESSING = 102 //Processing. + PROXY_AUTHENTICATION_REQUIRED = 407 //Proxy Authentication Required. + REQUEST_HEADER_FIELDS_TOO_LARGE = 431 //Request Header Fields Too Large. + REQUEST_TIMEOUT = 408 //Request Timeout. + REQUESTED_RANGE_NOT_SATISFIABLE = 416 //Requested Range Not Satisfiable. + RESET_CONTENT = 205 //Reset Content. + SEE_OTHER = 303 //See Other. + SERVICE_UNAVAILABLE = 503 //Service Unavailable. + SWITCHING_PROTOCOLS = 101 //Switching Protocols. + TEMPORARY_REDIRECT = 307 //Temporary Redirect. + TOO_EARLY = 425 //Too Early. + TOO_MANY_REQUESTS = 429 //Too Many Requests. + UNAUTHORIZED = 401 //Unauthorized. + UNAVAILABLE_FOR_LEGAL_REASONS = 451 //Unavailable For Legal Reasons. + UNPROCESSABLE_ENTITY = 422 //Unprocessable Entity. + UNSUPPORTED_MEDIA_TYPE = 415 //Unsupported Media Type. + UPGRADE_REQUIRED = 426 //Upgrade Required. + URI_TOO_LONG = 414 //URI Too Long USE_PROXY Deprecated due to security concerns regarding in-band configuration of a proxy + VARIANT_ALSO_NEGOTIATES = 506 //Variant Also Negotiates +) diff --git a/bmp-operation-api/bmp_vendor/ironic-common/ironic/util/util.go b/bmp-operation-api/bmp_vendor/ironic-common/ironic/util/util.go new file mode 100644 index 0000000..5aca77e --- /dev/null +++ b/bmp-operation-api/bmp_vendor/ironic-common/ironic/util/util.go @@ -0,0 +1,77 @@ +package util + +import ( + "encoding/json" + "errors" + "fmt" + "math/rand" + "reflect" + "strconv" + "time" +) + +//GetRandString 借鉴RandomStringUtils.random包生成随机字符串 +// length 随机字符串的长度(不包括前缀) +// uletter 随机字符串是否包含大写字母字符 +// dletter 随机字符串是否包含小写字母字符 +// number 随机字符串是否包含数字字符 +func GetRandString(prefix string, length int32, uletter, dletter, number bool) string { + rand.Seed(time.Now().UnixNano()) + uletters := []rune("ABCDEFGHIGKLMNOPQRSTUVWXYZ") + dletters := []rune("abcdefghijklmnopqrstuvwxyz") + numbers := []rune("0123456789") + source := []rune{} + if uletter { + source = append(source, uletters...) + } + if dletter { + source = append(source, dletters...) + } + if number { + source = append(source, numbers...) + } + if len(source) == 0 { + return "atLeastContainsLetterOrNumber" + } + b := make([]rune, length) + for i := range b { + b[i] = source[rand.Intn(len(source))] + } + return prefix + string(b) +} + +// 跟现有环境一致,格式:aafc4d1b-f696-4ec2-924f-6fd012aa8345 +func GenerateRandUuid() string { + s := GetRandString("", 32, false, true, true) + runes := []rune(s) + return string(runes[0:8]) + "-" + string(runes[8:12]) + "-" + string(runes[12:16]) + "-" + string(runes[16:20]) + "-" + string(runes[20:32]) +} + +func Convert2String(val interface{}) (msg string, err error) { + + if val == nil{ + return "", nil + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool: + msg = strconv.FormatBool(val.(bool)) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + msg = fmt.Sprintf("%v", val) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + msg = fmt.Sprintf("%v", val) + case reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + msg = fmt.Sprintf("%v", val) + case reflect.String: + msg = val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + s, err := json.Marshal(val) + if err == nil { + msg = string(s) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + err = errors.New(fmt.Sprintf("type %s not support convert to string", reflect.TypeOf(val).String())) + default: + err = errors.New(fmt.Sprintf("type %s not support convert to string", reflect.TypeOf(val).String())) + } + return +} diff --git a/bmp-operation-api/bmp_vendor/log/.cmd b/bmp-operation-api/bmp_vendor/log/.cmd new file mode 100644 index 0000000..5c2f328 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/log/.cmd @@ -0,0 +1 @@ +rm test.log.FATAL test.log.INFO test.log.WARN diff --git a/bmp-operation-api/bmp_vendor/log/README.md b/bmp-operation-api/bmp_vendor/log/README.md new file mode 100644 index 0000000..f39a094 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/log/README.md @@ -0,0 +1,6 @@ +精简日志库,用于打点统计,监控,告警等场景 +- WARN,FATAL等等级的日志即时打印落盘 + - 一个流量可以打印多条WARN,FATAL日志 +- INFO,DEBUG等级的日志,一个流量只落一条日志 + - 支持字段顺序自定义,便于正则匹配做监控等场景 + - 支持自定义代码段耗时打印,便于后续性能统计分析 diff --git a/bmp-operation-api/bmp_vendor/log/go.mod b/bmp-operation-api/bmp_vendor/log/go.mod new file mode 100644 index 0000000..83d5129 --- /dev/null +++ b/bmp-operation-api/bmp_vendor/log/go.mod @@ -0,0 +1,3 @@ +module git.jd.com/cps-golang/log + +go 1.17 diff --git a/bmp-operation-api/bmp_vendor/log/log.go b/bmp-operation-api/bmp_vendor/log/log.go new file mode 100644 index 0000000..6e5b79c --- /dev/null +++ b/bmp-operation-api/bmp_vendor/log/log.go @@ -0,0 +1,249 @@ +package cps_log + +import ( + "encoding/json" + "fmt" + "io" + "log" + "os" + "reflect" + "strings" + "time" +) + +// Level type +type Level uint32 + +const ( + // TraceLevel level. Designates finer-grained informational events than the Debug. + TraceLevel Level = iota + // DebugLevel level. Usually only enabled when debugging. Very verbose logging. + DebugLevel + // InfoLevel level. General operational entries about what's going on inside the + // application. + InfoLevel + // WarnLevel level. Non-critical entries that deserve eyes. + WarnLevel + // ErrorLevel level. Logs. Used for errors that should definitely be noted. + // Commonly used for hooks to send errors to an error tracking service. + ErrorLevel + // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the + // logging level is set to Panic. + FatalLevel + // PanicLevel level, highest level of severity. Logs and then calls panic with the + // message passed to Debug, Info, ... + PanicLevel +) + +var globalDefinedKeys = []string{"time", "logid", "self_t", "all_t"} + +type Logger struct { + data map[string]interface{} + level Level + fileName string + definedKeys []string +} + +func New(filename string) *Logger { + if filename == "" { + log.Fatal("filename must be provided !!!") + return nil + } + l := &Logger{ + data: make(map[string]interface{}), + fileName: filename, + } + l.definedKeys = append([]string{}, globalDefinedKeys...) + l.data["time"] = time.Now().Format("2006-01-02T15:04:05") + return l +} + +func NewLoggerWithConfig(filename string, level Level, definedKeys []string) *Logger { + l := New(filename) + l.SetLevel(level) + l.SetStableFields(definedKeys) + return l +} + +func (l *Logger) SetLevel(level Level) { + l.level = level +} + +//SetStableFields 需要固定每条日志的字段时,通过此接口设置,global在前,userdefined在后 +func (l *Logger) SetStableFields(fields []string) { + l.definedKeys = append(l.definedKeys, fields...) +} + +func (l *Logger) Point(key string, val interface{}) { + l.data[key] = val +} + +func (l *Logger) GetPoint(key string) interface{} { + return l.data[key] +} + +func (l *Logger) TimeStart(key string) { + if _, ok := l.data[key]; ok { + log.Print(fmt.Sprintf("point %s TimeStart more than once, check !!!", key)) + } + l.data[key] = time.Now() + +} + +func (l *Logger) TimeEnd(key string) { + if t, ok := l.data[key]; ok { + v := time.Now().Sub(t.(time.Time)).Milliseconds() + l.data[key] = fmt.Sprintf("%f", float64(v)/1000.0) + } else { + log.Print(fmt.Sprintf("missing call TimeStart before TimeEnd when point %s, check it!!!", key)) + } + +} + +func (l *Logger) PushPoint(key string, val interface{}) { + if _, ok := l.data[key]; !ok { + l.data[key] = []interface{}{} + } + d := l.data[key].([]interface{}) + d = append(d, val) +} + +func (l *Logger) Info(v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Infof(format string, v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warn(v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warnf(format string, v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatal(v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatalf(format string, v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Flush() { + if l.level > DebugLevel { + return + } + var beforeStr, afterStr string + for _, key := range l.definedKeys { + if val, ok := l.data[key]; ok { + if key == "time" { + beforeStr = val.(string) + continue + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + beforeStr = beforeStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + beforeStr = beforeStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + beforeStr = beforeStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Printf("val for %s unknown type!!!", key)) + + } + } + } + for key, val := range l.data { + if exist, _ := inArray(key, l.definedKeys); !exist { + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + afterStr = afterStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + afterStr = afterStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + afterStr = afterStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Sprintf("val for %s unknown type!!!", key)) + } + } + } + + line := strings.TrimSpace(beforeStr) + " " + strings.TrimSpace(afterStr) + "\r\n" + filename := fmt.Sprintf("%s.DEBUG", l.fileName) + WriteFile(filename, line) +} + +func WriteFile(filename, line string) { + TimeStamp := time.Now() + str := filename + "." + TimeStamp.Format("2006-01-02") + logf, err := os.OpenFile(str, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + if err != nil { + log.Fatal("open filename error:", err.Error()) + } + defer logf.Close() + if _, err := io.WriteString(logf, line); err != nil { + log.Fatal("write line error:", err.Error()) + } +} + +func inArray(val interface{}, array interface{}) (exists bool, index int) { + exists = false + index = -1 + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + index = i + exists = true + return + } + } + } + return +} diff --git a/bmp-operation-api/build.sh b/bmp-operation-api/build.sh new file mode 100644 index 0000000..c076ae2 --- /dev/null +++ b/bmp-operation-api/build.sh @@ -0,0 +1,124 @@ +#!/bin/bash +############################################################################### +#编译脚本的原理是将编译结果放到output目录中,这个样例模版提供一个产生 +#一个最基本golang运行程序包的编译脚本,对于特殊的需求请酌情考虑 +# +#1、该脚本支持参数化,参数将传入build_package函数(内容为最终执行的编译命令) +# ,用$1,$2....表示,第1,2...个参数 +#2、部署需要启动程序,所以需要提供control文件放在当前目录中,用于启动和 +# 监控程序状态 + +###############用户修改部分################ +readonly PROJECT_NAME="ironic-jdstack" #项目名称,相对于$GOPATH/src文件夹所在的目录,可选项 +readonly PACKAGE_DIR_NAME=main.go #main文件相对于src文件夹所在的目录,可选项 +readonly PACKAGE_BIN_NAME=ironic-jdstack #定义产出的运行程序名,必填项 +readonly CONF_DIR_NAME="conf" #定义配置文件目录,此路径为相对路径,可选项 +readonly OTHERS_DIR_NAME="" #定义其它文件目录,多个目录以空格区分,此路径为相对路径,可选项 +#最终的抽包路径为$OUTPUT +########################################### + +if [[ "${PACKAGE_BIN_NAME}" == "" ]];then + echo "Please set "PACKAGE_BIN_NAME" value" + exit 1 +fi + +function set_work_dir +{ + readonly OUTPUT=$(pwd)/output + readonly WORKSPACE_DIR=$(pwd) +} + +#清理编译构建目录操作 +function clean_before_build +{ + cd ${WORKSPACE_DIR} + rm -rf bin pkg + rm -rf ${OUTPUT} +} + +#初始化编译环境 +function prepare_package() +{ + if [ ! -z "$PROJECT_NAME" ];then + mkdir -p src/$PROJECT_NAME + copy_files=`ls |grep -vw 'src'` + cp -rf $copy_files src/$PROJECT_NAME/ + fi +} + +#实际的编译命令 +#这个函数中可使用$1,$2...获取第1,2...个参数 +function build_package() +{ + cd ${WORKSPACE_DIR} + # export GOPATH=$(pwd) + go clean + echo $(pwd) + echo $(ls) + go build -v -gcflags="-N -l" -o ${PACKAGE_BIN_NAME} ${PACKAGE_DIR_NAME} || return 1 +} + +#建立最终发布的目录 +function build_dir +{ + mkdir -p ${OUTPUT}/bin || return 1 +} + +function dir_not_empty() +{ + if [[ ! -d $1 ]];then + return 1 + fi + if [[ $(ls $1|wc -l) -eq 0 ]];then + return 1 + fi + return 0 +} + +#拷贝编译结果到发布的目录 +function copy_result +{ + cd ${WORKSPACE_DIR} + cp -r ${PACKAGE_BIN_NAME} ${OUTPUT}/bin/ || return 1 + cp -r ./control ${OUTPUT}/bin || return 1 + dir_not_empty ${WORKSPACE_DIR}/${CONF_DIR_NAME} && mkdir -p ${OUTPUT}/${CONF_DIR_NAME} + cp -rf ./${CONF_DIR_NAME}/* ${OUTPUT}/${CONF_DIR_NAME}/ + test -z "$OTHERS_DIR_NAME" || cp -rf $OTHERS_DIR_NAME ${OUTPUT}/ + return 0 +} + +#执行 +function main() +{ + cd $(dirname $0) + set_work_dir + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Cleaning...' + clean_before_build || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Clean completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'preparng...' + prepare_package || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'prepare completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Building...' + build_package $@ || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Build completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Making dir...' + build_dir || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Make completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy result to publish dir...' + copy_result || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy completed' + echo + + exit 0 +} + +main $@ diff --git a/bmp-operation-api/conf/app.conf b/bmp-operation-api/conf/app.conf new file mode 100644 index 0000000..e69de29 diff --git a/bmp-operation-api/conf/bmp-operation-test.ini b/bmp-operation-api/conf/bmp-operation-test.ini new file mode 100644 index 0000000..44b0a8d --- /dev/null +++ b/bmp-operation-api/conf/bmp-operation-test.ini @@ -0,0 +1,9 @@ +[test] +# redis +bmp_redis_host=${BMP_REDIS_HOST||10.226.192.72} +bmp_redis_port=${BMP_REDIS_PORT||16379} +bmp_redis_password=${BMP_REDIS_PASSWORD||LpK9Jq12Zf} + + +openapi_host=${BMP_OPENAPI_HOST||127.0.0.1} +openapi_port=${BMP_OPENAPI_PORT||8801} diff --git a/bmp-operation-api/conf/bmp-operation.ini b/bmp-operation-api/conf/bmp-operation.ini new file mode 100644 index 0000000..e5c5081 --- /dev/null +++ b/bmp-operation-api/conf/bmp-operation.ini @@ -0,0 +1,30 @@ +appname = bmp-ironic-operation +runmode = "${IRONIC_OPERATION_RUNMODE||test}" +autorender = false +copyrequestbody = true +EnableDocs = true +httpport = 8799 +# 打开session +sessionon = true +# 设置session id的名字 +sessionname = bmp_ironic_operation +# 设置session存储引擎 +sessionlife = 43200 + +bmp_redis_host=${BMP_REDIS_HOST} +bmp_redis_port=${BMP_REDIS_PORT} +bmp_redis_password=${BMP_REDIS_PASSWORD} + +openapi_host=${BMP_OPENAPI_HOST} +openapi_port=${BMP_OPENAPI_PORT} +openapi_token="Ym1wLW9wZXJhdGlvbi1hcGk=" + +image.url="{host}/" +# log +log.level=DEBUG +log.max.history=10 +log.path=/var/log/bmp/bmp-operation-api +# upload file path(image,device) +upload.path=./data +# 本地调试的话,把下面的注释打开,读取本地配置文件 +;include "bmp-operation-test.ini" diff --git a/bmp-operation-api/constant/constant.go b/bmp-operation-api/constant/constant.go new file mode 100644 index 0000000..c626a03 --- /dev/null +++ b/bmp-operation-api/constant/constant.go @@ -0,0 +1,147 @@ +package constant + +import "fmt" + +var ( + OK RespMsg + INVALID_ARGUMENT RespMsg + INVALID_ARGUMENT_WITH_ARGS RespMsg + NO_LOGIN_PIN RespMsg + AUTH_NOT_LOGIN RespMsg + AUTH_BASIC_AUTH_ERROR RespMsg + INVALID_ARGUMENT_OUT_OF_RANGE RespMsg + RATE_LIMIT RespMsg + INTERNAL_ERROR RespMsg + NOT_FOUND RespMsg + NOT_FOUND_WITH_ARGS RespMsg + CANCELLED RespMsg + CANCELLEDWithArgs RespMsg + PermissionDenyForObject RespMsg + NOT_SUPPORTED RespMsg + + LANGUAGE_EN = "en_US" + LANGUAGE_ZH = "zh_CN" +) + +type RespMsg struct { + Code int `json:"code"` + MessageEn string `json:"message_en"` + Messagech string `json:"message_ch"` + Status string `json:"status"` +} + +func init() { + OK = RespMsg{ + 200, + "OK", + "成功", + "OK", + } + INVALID_ARGUMENT = RespMsg{ + 400, + "Parameters error", + "参数错误", + "INVALID_ARGUMENT", + } + INVALID_ARGUMENT_WITH_ARGS = RespMsg{ + 400, + "%s", + "%s", + "INVALID_ARGUMENT", + } + AUTH_NOT_LOGIN = RespMsg{ + 400, + "Login Please", + "请先登录", + "AUTH_NOT_LOGIN", + } + AUTH_BASIC_AUTH_ERROR = RespMsg{ + 401, + "Unauthorized", + "认证失败或者权限错误", + "AUTH_ERROR_OR_PERMISSION_DENIED", + } + RATE_LIMIT = RespMsg{ + 429, + "Requests are too frequent", + "请求过于频繁", + "RATE_LIMIT", + } + INTERNAL_ERROR = RespMsg{ + 500, + "Internal error", + "内部错误", + "INTERNAL", + } + NOT_FOUND = RespMsg{ + 404, + "Not found", + "找不到对象", + "NOT_FOUND", + } + NOT_FOUND_WITH_ARGS = RespMsg{ + 404, + "%s Not found", + "%s 找不到对象", + "NOT_FOUND", + } + CANCELLED = RespMsg{ + 400, + "Operation cancelled", + "取消操作", + "CANCELLED", + } + NOT_SUPPORTED = RespMsg{ + 400, + "Operation not allowed", + "不支持此操作", + "NOT ALLOWEDS", + } + CANCELLEDWithArgs = RespMsg{ + 400, + "%s", + "%s", + "CANCELLED", + } + PermissionDenyForObject = RespMsg{ + 401, + "permission denied", + "无操作权限", + "PERMISSION DENIED", + } +} + +func BuildNotFoundWithArgs(c, e string) RespMsg { + return RespMsg{ + 404, + fmt.Sprintf("%s Not found", e), + fmt.Sprintf("%s 找不到对象", c), + "NOT_FOUND", + } +} +func BuildCANCELLEDWithArgs(c, e string) RespMsg { + return RespMsg{ + 400, + e, + c, + "CANCEL", + } +} + +func BuildInvalidArgumentWithArgs(c, e string) RespMsg { + return RespMsg{ + 400, + e, + c, + "INVALID_ARGUMENT", + } +} + +func BuildAuthTokenAuthError(c, e string) RespMsg { + return RespMsg{ + 401, + e, + c, + "AUTH_TOKEN_AUTH_ERROR", + } +} diff --git a/bmp-operation-api/control b/bmp-operation-api/control new file mode 100644 index 0000000..5396811 --- /dev/null +++ b/bmp-operation-api/control @@ -0,0 +1,125 @@ +#!/bin/bash +set -x +cd "$(dirname $0)"/.. +BASE_DIR=`pwd` +if [ -f default_env.sh ];then + source default_env.sh +fi + +PROC_NAME=ironic-jdstack # 进程名 一般就是二进制的名字java类程序一般就是java +PROC_PORT=8503 # 程序占用的端口,建议写,程序不占用端口的话只用ps来判断进程是否启动,机器上有同名程序是可能有问题 +WAIT_TIME=60 # 执行START_COMMAND后到程序能完全启动listen端口需要花的时间 + +USER=nginx +app_dir=/home/$USER/$PROC_NAME +mkdir -p $app_dir/log + +START_COMMAND="$app_dir/bin/ironic-jdstack -c $app_dir/conf/ironic-console.ini" #在output目录下启动你程序的命令 + +help(){ + echo "${0} " + exit 1 +} + +checkhealth(){ + if [[ -n "$PROC_PORT" ]] ; then + PORT_PROC=$(/usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d |awk '{print $NF}' |grep -oP '".*"' |sed "s/\"//g" |uniq) + if [ X"$PORT_PROC" = X"$PROC_NAME" ] ; then + echo "1 running" + return 0 + fi + echo "1 not running" + return 1 + else + ps -eo comm,pid |grep -P "^$PROC_NAME" + if [ "$?" = 0 ] ; then + echo "2 running" + return 0 + fi + echo "2 not running" + return 1 + fi +} + + +start(){ + checkhealth + if [ $? = 0 ]; then + echo "[WARN] $PROC_NAME is aleady running!" + return 0 + fi + + [ -d "$app_dir" ] && cd $app_dir && rm -rf `ls ${app_dir} | grep -v log` + cp -r $BASE_DIR/* ${app_dir}/ + chown -R $USER:$USER ${app_dir} + su $USER -c "nohup $START_COMMAND > ${app_dir}/log/cps-ironic-api.log 2>&1 &" + + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ $? = 0 ]; then + echo "Start $PROC_NAME success" + return 0 + fi + done + echo "[ERROR] Start $PROC_NAME failed" + return 1 +} + +stop(){ + if [[ -n "$PROC_PORT" ]] ; then + PROC_ID=$( /usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d | awk '{print $NF}' | grep -oP ',.*,' | grep -oP "\d+" | uniq ) + else + PROC_ID=$(ps -eo comm,pid | grep "^$PROC_NAME" |awk '{print $2}') + fi + + if [[ -z "$PROC_ID" ]] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + + checkhealth + if [ "$?" != "0" ] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + kill $PROC_ID + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + done + + kill -9 $PROC_ID + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + + echo "[ERROR] Stop $PROC_NAME failed" + return 1 +} + +case "${1}" in + start) + start + ;; + stop) + stop + ;; + status|health|checkhealth) + checkhealth + ;; + restart) + stop && start + ;; + *) + help + ;; +esac + diff --git a/bmp-operation-api/controllers/ApikeyController.go b/bmp-operation-api/controllers/ApikeyController.go new file mode 100644 index 0000000..9ad7a89 --- /dev/null +++ b/bmp-operation-api/controllers/ApikeyController.go @@ -0,0 +1,86 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/ApikeyLogic" + + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + response "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type ApikeyController struct { + BaseController +} + +// swagger:route PUT /apikey keypair createApikey +// CreateAPIkey 创建apikey +// Responses: +// 200: createApikey +// default: ErrorResponse + +func (c *ApikeyController) CreateApikey() { + req := &sdkModels.CreateApikeyRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("CreateAPIkey parse pAPIkeyt body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + // req.Validate(c.logPoints) + uuid, err := ApikeyLogic.CreateApikey(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.ApikeyId{ + ApikeyId: uuid, + } +} + +// swagger:route GET /apikey keypair getApikeyList +// GetApikeyList 获取apikey列表 +// Responses: +// 200: getApikeyList +// default: ErrorResponse + +func (c *ApikeyController) GetApikeyList() { + defer c.CatchException() + + req := requestTypes.GetApikeyListRequest{ + PagingRequest: requestTypes.PagingRequest{ + PageNumber: c.getPageNumber(), + PageSize: c.getPageSize(), + }, + } + + // req.Validate(c.logPoints) + res, err := ApikeyLogic.GetApikeyList(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res + +} + +// swagger:route DELETE /apikey/{apikey_id} keypair deleteApikey +// DeleteApikey 删除apikey +// Responses: +// 200: deleteApikey +// default: ErrorResponse + +func (c *ApikeyController) DeleteApikey() { + defer c.CatchException() + apikeyId := c.Ctx.Input.Param(":apikey_id") + if err := ApikeyLogic.DeleteApikey(c.logPoints, apikeyId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} diff --git a/bmp-operation-api/controllers/BaseController.go b/bmp-operation-api/controllers/BaseController.go new file mode 100644 index 0000000..3117d25 --- /dev/null +++ b/bmp-operation-api/controllers/BaseController.go @@ -0,0 +1,392 @@ +package controllers + +import ( + "encoding/json" + "fmt" + "reflect" + "strconv" + "strings" + "time" + + baseLogic "coding.jd.com/aidc-bmp/bmp-operation-api/logic/BaseLogic" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" + + UserLoigc "coding.jd.com/aidc-bmp/bmp-operation-api/logic/UserLogic" + + util "coding.jd.com/aidc-bmp/bmp-operation-api/util" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + log "git.jd.com/cps-golang/log" + "github.com/beego/beego/v2/server/web" + + beego "github.com/beego/beego/v2/server/web" +) + +var sessionName string + +func Init() { + sessionName, _ = beego.AppConfig.String("sessionname") +} + +var noQueryResponse = map[string]interface{}{ + "success": true, +} + +type ErrorResponse struct { + Code int `json:"code"` + Message string `json:"message"` + Status string `json:"status"` +} + +type Response struct { + Result interface{} `json:"result,omitempty"` + Error *ErrorResponse `json:"error,omitempty"` + RequestId string `json:"requestId"` +} + +// SubnetController operations for Subnet +type BaseController struct { + web.Controller + logPoints *log.Logger + Res Response + pageable util.Pageable +} + +func (b *BaseController) SetErrorResponse(httpCode int, errmsg, errno string) { + + b.Ctx.Output.Status = httpCode + b.Res.Error = &ErrorResponse{ + Code: httpCode, + Message: errmsg, + Status: errno, + } +} + +func (b *BaseController) Prepare() { + web.ReadFromRequest(&b.Controller) + logPath, _ := beego.AppConfig.String("log.path") + b.logPoints = log.New(logPath + "/bmp-operation.log") + b.logPoints.SetStableFields([]string{"method", "uri", "header", "request", "response"}) + b.logPoints.Point("uri", b.Ctx.Request.RequestURI) + b.logPoints.Point("method", b.Ctx.Request.Method) + b.logPoints.Point("header", b.Ctx.Request.Header) + b.logPoints.Point("request", string(b.Ctx.Input.RequestBody)) + b.logPoints.TimeStart("all_t") + b.logPoints.TimeStart("self_t") + requestID := b.GetRequestID() + + b.logPoints.Point("logid", requestID) + b.logPoints.Point("language", b.GetLanguage()) + b.Ctx.Output.Header("X-Jdcloud-Request-Id", requestID) + b.Res = Response{} + b.pageable = util.Pageable{ + PageNumber: b.getPageNumber(), + PageSize: b.getPageSize(), + } + + if !strings.HasPrefix(b.Ctx.Input.URI(), "/login") && !strings.HasPrefix(b.Ctx.Input.URI(), "/logout") { + jdc := b.Ctx.GetCookie(sessionName) + fmt.Println(time.Now().String(), "prepare func get cookie:", jdc, sessionName) + b.logPoints.Info(time.Now().Local().String(), "prepare func get cookie:", jdc, sessionName) + if jdc == "" { + b.logPoints.Warn("no session_id in cookie, the sessionName is: %s, cookies are: %v", sessionName, b.Ctx.Request.Cookies()) + b.Ctx.ResponseWriter.WriteHeader(402) + fmt.Fprintln(b.Ctx.ResponseWriter, "user not login") + return + } + //err := b.SetSession(jdc, "admin") + //fmt.Println(err) + userName := b.GetSession(jdc) + fmt.Println(time.Now().String(), "prepare func get session.username:", sessionName, jdc, userName) + b.logPoints.Info(time.Now().Local().String(), "prepare func get session.username:", sessionName, jdc, userName) + if userName == nil { + b.logPoints.Warnf("sessionname %s session_id %s not found or timeout, relogin please...", sessionName, jdc) + b.Ctx.ResponseWriter.WriteHeader(402) + fmt.Fprintln(b.Ctx.ResponseWriter, "user not login") + return + } else { + b.Ctx.Output.Header("X-Jdcloud-Username", userName.(string)) + b.logPoints.Point("username", userName.(string)) + user, err := UserLoigc.GetUserByName(b.logPoints, userName.(string)) + if err != nil { + fmt.Println("prepare.UserLoigc.GetUserByName error:", err.Error()) + b.logPoints.Warnf("prepare.UserLoigc.GetUserByName error, username:%s, error:%s", userName.(string), err.Error()) + b.Ctx.ResponseWriter.WriteHeader(402) + fmt.Fprintln(b.Ctx.ResponseWriter, "user not login") + return + } + fmt.Println("prepare.userid:", user.UserID) + b.logPoints.Point("userId", user.UserID) + if user.Timezone == "" { + user.Timezone = "Asia/Shanghai" + } + b.logPoints.Point("timezone", user.Timezone) + // b.Ctx.Output.Header("X-Jdcloud-UserID", user.UserID) + b.logPoints.Infof("get session success, session_id: %s, userid: %s", jdc, userName) + } + } + //b.logPoints.Point("userId", "user-tl84cfjq3m3f83fszhf9j3mqst3m") + //b.logPoints.Point("username", "zcl") + //fmt.Println("[DEBUG MINPING]req url:", b.Ctx.Request.URL) + //fmt.Println("[DEBUG MINPING]req method", b.Ctx.Request.Method) + //fmt.Println("[DEBUG MINPING]req header", b.Ctx.Request.Header) + //fmt.Println("[DEBUG MINPING]req body:", string(b.Ctx.Input.RequestBody)) + +} + +func (b *BaseController) Finish() { + + //上述情况为正确情况 + b.Res.RequestId = b.GetRequestID() + b.Data["json"] = b.Res + b.ServeJSON() + + b.logPoints.TimeEnd("self_t") + b.logPoints.TimeEnd("all_t") + b.logPoints.Point("response", b.Data["json"]) + b.logPoints.Flush() + + v, _ := json.Marshal(b.Data["json"]) + fmt.Println("[DEBUG MINPING]resp body:", string(v)) + +} + +func (b *BaseController) GetString(key string) string { + return b.Controller.GetString(key, "") +} + +func (b *BaseController) GetInt(key string) (int, error) { + return b.Controller.GetInt(key, 0) +} + +//业务代码可以直接panic终止运行,后面放开 +func (b *BaseController) CatchException() { + // if r := recover(); r != nil { + // // t := make([]byte, 1<<16) + // // runtime.Stack(t, true) + // t, _ := json.Marshal(r) + // b.logPoints.Warn(string(t)) + // if reflect.TypeOf(r).String() == "exception.Exception" { + // b.Res["result"] = r + // } else { //非预期panic输出统一化 + // b.Res["result"] = exception.InternalError + // } + // } + if r := recover(); r != nil { + t, _ := json.Marshal(r) + b.logPoints.Warn(string(t)) + //b.Res["result"] = int(reflect.ValueOf(r).Field(0).Int()) + //if reflect.ValueOf(r).Field(1).String() == "" { //重要返回,如果errno不写,那么默认的errno和msg在这里设置 + // b.Res["error"] = 40000 + // b.Res["m"] = reflect.ValueOf(r).Field(2).String() + // return + //} + //errno, err := strconv.Atoi(reflect.ValueOf(r).Field(1).String()) //如果errno不写 + //if err != nil { //字符串转整形失败 + // b.Res["errno"] = 40001 + // b.Res["errmsg"] = reflect.ValueOf(r).Field(2).String() + // return + //} + var ( + code int + chMessage string + enMessage string + status string + ) + if reflect.ValueOf(r).Field(0).Int() == 0 { + code = httpStatus.BAD_REQUEST //默认httpcode 400 + } else { + code = int(reflect.ValueOf(r).Field(0).Int()) + } + //en_message + if reflect.ValueOf(r).Field(1).String() == "" { + enMessage = errorCode.INVALID_ARGUMENT //参数错误 + } else { + enMessage = reflect.ValueOf(r).Field(1).String() + } + + //ch_message + if reflect.ValueOf(r).Field(2).String() == "" { + chMessage = errorCode.INVALID_ARGUMENT //参数错误 + } else { + chMessage = reflect.ValueOf(r).Field(2).String() + } + + //status + if reflect.ValueOf(r).Field(3).String() == "" { + status = errorCode.INVALID_ARGUMENT //参数错误 + } else { + status = reflect.ValueOf(r).Field(3).String() //具体的报错信息err.error() + } + fmt.Println("recover info:", code, chMessage, enMessage, status) + if b.logPoints.GetPoint("language").(string) == baseLogic.EN_US { + b.SetErrorResponse(code, enMessage, status) + } else { + b.SetErrorResponse(code, chMessage, status) + } + + } +} + +func (b *BaseController) GetRequestID() string { + if b.Ctx.Request.Header["X-Jdcloud-Request-Id"] != nil { + return b.Ctx.Request.Header["X-Jdcloud-Request-Id"][0] + } + //生成随机字符串logid + logid := commonUtil.GenerateRandUuid() + b.Ctx.Request.Header["X-Jdcloud-Request-Id"] = []string{logid} + return logid +} + +func (b *BaseController) GetErp() string { + if b.Ctx.Request.Header["X-Jdcloud-Erp"] != nil { + return b.Ctx.Request.Header["X-Jdcloud-Erp"][0] + } + return "" +} + +func (b *BaseController) GetJDCookie() string { + if b.Ctx.Request.Header["X-Jdcloud-Cookie"] != nil { + return b.Ctx.Request.Header["X-Jdcloud-Host"][0] + } + return "" +} + +func (b *BaseController) GetJDHost() string { + if b.Ctx.Request.Header["X-Jdcloud-Host"] != nil { + return b.Ctx.Request.Header["X-Jdcloud-Host"][0] + } + return "" +} + +// v1/validation success res: {"requestId":"0wzsgfzm-veo8-rjbm-nf53-0gqparr6b9di","error":null,"result":{"loginInfo":{"type":1,"pin":"4cb497f05ae7455c9272","adminPin":null,"credentialInfo":null,"loginUrl":"","loginName":"zyTest"}}} + +// failed res:{"requestId":"bygqoepg-k3n1-k8rc-4l52-iho1nr3brmtp","error":null,"result":{"loginInfo":{"type":0,"pin":null,"adminPin":null,"credentialInfo":null,"loginUrl":"http://login-stag.jdcloud.com","loginName":null}}} + +type LoginstateValidationRes struct { + RequestId string `json:"requestId"` + // Error string `json:"error"` + Result struct { + LoginInfo LoginInfo `json:"loginInfo"` + } `json:"result"` +} + +type LoginInfo struct { + Type int `json:"type"` //0表示未登录,1表示主账号登录,2表示子账号登录,3表示角色登录 + Pin string `json:"pin"` + AdminPin string `json:"adminPin"` + CredentialInfo *CredentialInfo `json:"credentialInfo"` + LoginUrl string `json:"loginUrl"` + LoginName string `json:"loginName"` +} + +type CredentialInfo struct { + AccessKey string `json:"accessKey"` + SecretKey string `json:"secretKey"` + SessionToken string `json:"sessionToken"` + Expiration string `json:"expiration"` //类型是data还是string?返回结果此字段都没有数据,先定义成string + RolePin string `json:"rolePin"` +} + +func (b *BaseController) GetLanguage() string { + fmt.Println("语言header", b.Ctx.Request.Header["X-Jdcloud-Language"]) + fmt.Println("语言cookie", b.Ctx.GetCookie("X-Jdcloud-Language"), b.Ctx.GetCookie("path_url")) + return b.Ctx.GetCookie("X-Jdcloud-Language") + //if len(b.Ctx.Request.Header["X-Jdcloud-Language"]) == 0 { + // if b.Ctx.GetCookie("X-Jdcloud-Language") == "" { + // return "" + // } else { + // return b.Ctx.GetCookie("X-Jdcloud-Language") + // } + //} + //return b.Ctx.Request.Header["X-Jdcloud-Language"][0] +} + +func (b *BaseController) GetHost() string { + return b.Ctx.Request.Host +} + +func (b *BaseController) GetFields() (fields []string) { + // fields: col1,col2,entity.col3 + if v := b.GetString("fields"); v != "" { + fields = strings.Split(v, ",") + } + return +} + +func (b *BaseController) GetSortBy() (sortby []string) { + // sortby: col1,col2 + if v := b.GetString("sortby"); v != "" { + sortby = strings.Split(v, ",") + } + return +} + +func (b *BaseController) GetOrder() (order []string) { + // order: desc,asc + if v := b.GetString("order"); v != "" { + order = strings.Split(v, ",") + } + return +} + +// GetOffset 默认返回0 +func (b *BaseController) GetOffset() int64 { + if o := b.GetString("pageNumber"); o != "" { + if v, err := strconv.ParseInt(o, 10, 64); err == nil { + //第2页 每页10条 offset=10 + //第1页, 每页10条,offset=0 + if v > 0 { + return (v - 1) * b.GetLimit() + } + } + } + return 0 +} + +// GetOffset 默认返回10 +func (b *BaseController) GetLimit() int64 { + if l := b.GetString("pageSize"); l != "" { + if v, err := strconv.ParseInt(l, 10, 64); err == nil { + return v + } + } + return 20 +} + +func (b *BaseController) getPageNumber() int64 { + if l := b.GetString("pageNumber"); l != "" { + if v, err := strconv.Atoi(l); err == nil { + return int64(v) + } + } + return 1 +} + +func (b *BaseController) getPageSize() int64 { + if l := b.GetString("pageSize"); l != "" { + if v, err := strconv.Atoi(l); err == nil { + return int64(v) + } + } + if strings.HasPrefix(b.Ctx.Request.RequestURI, "/devices") { + return 10 + } + if strings.HasPrefix(b.Ctx.Request.RequestURI, "/instances") { + return 10 + } + if strings.HasPrefix(b.Ctx.Request.RequestURI, "/subnets") { + return 10 + } + return 20 +} + +func restfulResponseException(code int, status string, msg string) map[string]interface{} { + return map[string]interface{}{ + "error": map[string]interface{}{ + "code": code, + "status": status, + "message": msg, + }, + } +} diff --git a/bmp-operation-api/controllers/CustomController.go b/bmp-operation-api/controllers/CustomController.go new file mode 100644 index 0000000..2af6886 --- /dev/null +++ b/bmp-operation-api/controllers/CustomController.go @@ -0,0 +1,118 @@ +package controllers + +import ( + "encoding/json" + "strconv" + "strings" + + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/CustomInfoLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + "git.jd.com/cps-golang/ironic-common/exception" +) + +// CustomController operations for custom info +type CustomController struct { + BaseController +} + +// FilterList ... +// swagger:route GET /filterList custom filterList +// FilterList 设置自定义信息 +// Responses: +// 200: filterList +// default: ErrorResponse +func (c *CustomController) FilterList() { + defer c.CatchException() + language := c.logPoints.GetPoint("language").(string) + core := "物理核," + if language == BaseLogic.EN_US { + core = "cores," + } + architecture := response.ArchitectureList{ + Arm: "ARM64(aarch64)", + I386: "i386", + X86_64: "x86_64", + LoongArch: "LoongArch™", + } + + bootMode := []string{ + "UEFI", + "Legacy/BIOS", + } + + res := response.FilterList{ + Architecture: architecture, + BootMode: bootMode, + } + + cpu := response.CPU{} + for k, v := range BaseLogic.Cpulist { + cpu.Value = k + 1 + arr := strings.Split(v, ",") + cpu.Label = arr[0] + " " + arr[1] + "(" + arr[2] + "*" + arr[3] + core + arr[4] + "GHz)" + cpu.Info.CPUManufacturer = arr[0] + cpu.Info.CPUModel = arr[1] + cpu.Info.CPUAmount = s2i(arr[2]) + cpu.Info.CPUCores = s2i(arr[3]) + cpu.Info.CPUFrequency = arr[4] + res.CPU = append(res.CPU, cpu) + } + + mem := response.Mem{} + for k, v := range BaseLogic.Memlist { + mem.Value = k + 1 + arr := strings.Split(v, " ") + mem.Label = arr[0] + "GB(" + arr[1] + "GB*" + arr[2] + ")" + arr[3] + " " + arr[4] + "MHz" + mem.Info.MemType = arr[3] + mem.Info.MemFrequency = s2i(arr[4]) + mem.Info.MemSize = s2i(arr[1]) + mem.Info.MemAmount = s2i(arr[2]) + res.Mem = append(res.Mem, mem) + } + + res.RaidRules = CustomInfoLogic.GetRaidconf(c.logPoints) + + c.Res.Result = res +} +func s2i(s string) int { + i, _ := strconv.Atoi(s) + return i +} + +// SetCustomInfo ... +// swagger:route POST /custom/setCustomInfo custom setCustomInfo +// SetCustomInfo 设置自定义信息 +// Responses: +// 200: setCustomInfo +// default: ErrorResponse + +func (c *CustomController) SetCustomInfo() { + defer c.CatchException() + req := &requestTypes.SetCustomInfoRequest{} + // req.Validate() + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + panic(exception.Exception{Msg: err.Error()}) + } + res := CustomInfoLogic.SetCustomInfo(c.logPoints, *req) + c.Res.Result = res +} + +// GetCustomInfo ... +// swagger:route GET /custom/getCustomInfo custom getCustomInfo +// GetCustomInfo 获取自定义信息 +// Responses: +// 200: getCustomInfo +// default: ErrorResponse + +func (c *CustomController) GetCustomInfo() { + defer c.CatchException() + req := &requestTypes.QueryCustomInfoRequest{ + PageKey: c.GetString("pageKey"), + Reload: c.GetString("reload"), + } + // req.Validate() + res := CustomInfoLogic.GetCustomInfo(c.logPoints, *req) + c.Res.Result = res +} diff --git a/bmp-operation-api/controllers/DeviceController.go b/bmp-operation-api/controllers/DeviceController.go new file mode 100644 index 0000000..6a4c6b1 --- /dev/null +++ b/bmp-operation-api/controllers/DeviceController.go @@ -0,0 +1,356 @@ +package controllers + +import ( + // "encoding/json" + + "encoding/json" + "os" + + baseLogic "coding.jd.com/aidc-bmp/bmp-operation-api/logic/BaseLogic" + + DeviceLogic "coding.jd.com/aidc-bmp/bmp-operation-api/logic/DeviceLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +type DeviceController struct { + BaseController +} + +func (c *DeviceController) UploadDevices() { + defer c.CatchException() + file, header, err := c.GetFile("deviceFile") + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + defer file.Close() + req := &requestTypes.UploadDeviceRequest{ + DeviceFile: file, + } + res, err := DeviceLogic.UploadDevices(c.logPoints, req, header, c.GetRequestID()) //返回byte数组 + if err != nil { + errmsg := "文件不合法" + if c.logPoints.GetPoint("language") == baseLogic.EN_US { + errmsg = "file invalidate" + } + c.logPoints.Warn("上传文件出错", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, errmsg, errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route POST /devices device createDevices +// Responses: +// 200: createDevices +// default: ErrorResponse +func (c *DeviceController) CreateDevices() { + defer c.CatchException() + req := &requestTypes.CreateDeviceRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("createImage unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + res, err := DeviceLogic.CreateDevices(c.logPoints, req) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route POST /devices device createDevices +// Responses: +// 200: createDevices +// default: ErrorResponse +func (c *DeviceController) CollectDevice() { + defer c.CatchException() + req := &requestTypes.CollectDevice{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("CollectDevice unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + res, err := DeviceLogic.CollectDevice(c.logPoints, req) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// QueryDevices【设备管理】【设备列表】 +// swagger:route GET /devices/queryDevices device queryDevices +// QueryDevices【设备管理】【设备列表】 +// Responses: +// 200: queryDevices +// default: ErrorResponse + +func (c *DeviceController) QueryDevices() { + defer c.CatchException() + page := requestTypes.PagingRequest{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.QueryDeviceListRequest{ + Sn: c.GetString("sn"), + DeviceTypeID: c.GetString("deviceTypeId"), + DeviceSeries: c.GetString("deviceSeries"), + ManageStatus: c.GetString("manageStatus"), + IloIP: c.GetString("iloIp"), + InstanceID: c.GetString("instanceId"), + InstanceName: c.GetString("instanceName"), + UserID: c.GetString("userId"), + UserName: c.GetString("userName"), + Show: c.GetString("show"), + IsAll: c.GetString("isAll"), + CollectStatus: c.GetString("collectStatus"), + PagingRequest: page, + } + result, err := DeviceLogic.GetDeviceList(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + + if c.GetString("exportType") != "" { + fileName, downloadFileName, err := DeviceLogic.ExportDeviceExcel(c.logPoints, result.Devices) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, "导出设备列表excel错误 "+err.Error(), errorCode.INTERNAL) + return + } + //c.Ctx.Input.SetData("download", "yes") + c.Ctx.Output.Download(fileName, downloadFileName) + if err := os.Remove(fileName); err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, "删除上传文件失败"+err.Error(), errorCode.INTERNAL) + return + } + return + } + c.Res.Result = result +} + +// GetDevice【设备管理】【设备详情】 +// swagger:route GET /devices/queryDevice/{device_id} device getDevice +// GetDevice【设备管理】【设备详情】 +// Responses: +// 200: getDevice +// default: ErrorResponse + +func (c *DeviceController) GetDevice() { + defer c.CatchException() + deviceId := c.Ctx.Input.Param(":device_id") + req := &requestTypes.QueryDeviceInfoRequest{ + DeviceID: deviceId, + Show: c.GetString("show"), + } + result, err := DeviceLogic.GetDeviceInfo(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// UnPutaway【设备管理】【设备下架】支持多sn,英文逗号分隔 +// swagger:route PUT /devices/unPutaway device unPutaway +// UnPutaway【设备管理】【设备下架】支持多sn,英文逗号分隔 +// Responses: +// 200: unPutaway +// default: ErrorResponse + +func (c *DeviceController) UnPutaway() { + defer c.CatchException() + + req := &requestTypes.UnPutawayDeviceRequest{} + // req.Validate() + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("deviceController.UnPutaway.unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + + result, err := DeviceLogic.UnPutawayDevice(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), err.Error()) + return + } + c.Res.Result = result +} + +// Putaway【设备管理】【设备上架】支持多sn,英文逗号分隔 +// swagger:route PUT /devices/putaway device putaway +// Putaway【设备管理】【设备上架】支持多sn,英文逗号分隔 +// Responses: +// 200: putaway +// default: ErrorResponse + +func (c *DeviceController) Putaway() { + defer c.CatchException() + req := &requestTypes.PutawayDeviceRequest{} + // req.Validate() + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("deviceController.Putaway.unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + result, err := DeviceLogic.PutawayDevice(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), err.Error()) + return + } + c.Res.Result = result +} + +// Modify【设备管理】【设备修改】支持描述信息修改 +// swagger:route PUT /devices/{device_id} device modify +// Modify【设备管理】【设备修改】支持描述信息修改 +// Responses: +// 200: modify +// default: ErrorResponse + +func (c *DeviceController) ModifyDevice() { + defer c.CatchException() + req := &requestTypes.ModifyDeviceRequest{} + // req.Validate() + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("deviceController.modify.unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + result, err := DeviceLogic.ModifyDevice(c.logPoints, req, c.Ctx.Input.Param(":device_id")) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), err.Error()) + return + } + c.Res.Result = result +} + +// DeleteDevice【设备管理】【删除设备】 +// swagger:route DELETE /devices/{device_id} device deleteDevice +// DeleteDevice【设备管理】【删除设备】 +// Responses: +// 200: deleteDevice +// default: ErrorResponse + +func (c *DeviceController) DeleteDevice() { + defer c.CatchException() + deviceId := c.Ctx.Input.Param(":device_id") + req := &requestTypes.DeleteDeviceRequest{ + DeviceId: deviceId, + } + result, err := DeviceLogic.DeleteDevice(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// swagger:route PUT /devices/{device_id}/remove device removeDevice +// RemoveDevice【设备管理】【移除设备】 +// Responses: +// 200: removeDevice +// default: ErrorResponse + +func (c *DeviceController) RemoveDevice() { + defer c.CatchException() + deviceId := c.Ctx.Input.Param(":device_id") + result, err := DeviceLogic.RemoveDevice(c.logPoints, deviceId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// GetDeviceDiskDetail 设备详情-磁盘 +func (c *DeviceController) GetDeviceDiskDetail() { + defer c.CatchException() + deviceId := c.Ctx.Input.Param(":device_id") + req := &requestTypes.QueryDeviceDisksRequest{ + DeviceID: deviceId, + } + result, err := DeviceLogic.GetDeviceDiskDetail(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// swagger:route PUT /devices/disks/associateDisks device associateDeviceDisks +// +// AssociateDeviceDisks 设备关联磁盘 +// +// Responses: +// 200: associateDeviceDisks +// default: ErrorResponse + +func (c *DeviceController) AssociateDeviceDisks() { + defer c.CatchException() + req := &requestTypes.AssociateDeviceDisksRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("AssociateDeviceDisks parse post body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := DeviceLogic.AssociateDeviceDisks(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + c.Res.Result = res +} + +// swagger:route GET /devices/disks/describeAssociateDisks device getAssociatedDisks +// +// GetAssociatedDisks 获取设备已关联的磁盘 +// +// Responses: +// 200: getAssociatedDisks +// default: ErrorResponse +func (c *DeviceController) GetAssociatedDisks() { + defer c.CatchException() + req := &requestTypes.GetAssociatedDisksRequest{ + DeviceID: c.GetString("deviceId"), + VolumeID: c.GetString("volumeId"), + DeviceTypeID: c.GetString("deviceTypeId"), + } + res, err := DeviceLogic.GetAssociatedDisks(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + c.Res.Result = res +} + +// AssociateDeviceType ... +// swagger:route PUT /devices/associateDeviceType device deviceAssociateDeviceType +// +// AssociateDeviceType 设备绑定机型 +// +// Responses: +// 200: deviceAssociateDeviceType +// default: ErrorResponse + +func (c *DeviceController) DeviceAssociateDeviceType() { + defer c.CatchException() + req := &requestTypes.DeviceAssociateDeviceTypeRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("AssociateDeviceType parse post body err:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := DeviceLogic.DeviceAssociateDeviceType(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-operation-api/controllers/DeviceTypeController.go b/bmp-operation-api/controllers/DeviceTypeController.go new file mode 100644 index 0000000..b75d740 --- /dev/null +++ b/bmp-operation-api/controllers/DeviceTypeController.go @@ -0,0 +1,267 @@ +package controllers + +import ( + "encoding/json" + "os" + + DeviceTypeLogic "coding.jd.com/aidc-bmp/bmp-operation-api/logic/DeviceTypeLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +type DeviceTypeController struct { + BaseController +} + +// CreateDeviceType【机型管理】【添加机型】 +// swagger:route PUT /deviceTypes deviceType createDeviceType +// CreateDeviceType【机型管理】【添加机型】 +// Responses: +// 200: createDeviceType +// default: ErrorResponse + +func (c *DeviceTypeController) CreateDeviceType() { + defer c.CatchException() + req := &requestTypes.CreateDeviceTypeRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + result, err := DeviceTypeLogic.AddDeviceType(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// QueryDeviceTypes【机型管理】【机型列表】 +// swagger:route GET /deviceTypes deviceType queryDeviceTypes +// QueryDeviceTypes【机型管理】【机型列表】 +// Responses: +// 200: queryDeviceTypes +// default: ErrorResponse + +func (c *DeviceTypeController) QueryDeviceTypes() { + defer c.CatchException() + page := requestTypes.PagingRequest{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.QueryDeviceTypesRequest{ + DeviceTypeID: c.GetString("deviceTypeId"), + DeviceType: c.GetString("deviceType"), + IdcID: c.GetString("idcId"), + Name: c.GetString("name"), + DeviceSeries: c.GetString("deviceSeries"), + IsAll: c.GetString("isAll"), + PagingRequest: page, + } + result, err := DeviceTypeLogic.GetDeviceTypeList(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + + if c.GetString("exportType") != "" { + fileName, downloadFileName, err := DeviceTypeLogic.ExportDeviceTypeExcel(c.logPoints, result.DeviceTypes) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, "导出设备列表excel错误"+err.Error(), errorCode.INTERNAL) + return + } + //c.Ctx.Input.SetData("download", "yes") + c.Ctx.Output.Download(fileName, downloadFileName) + if err := os.Remove(fileName); err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, "删除上传文件失败"+err.Error(), errorCode.INTERNAL) + return + } + return + } + c.Res.Result = result +} + +// QueryDeviceType【机型管理】【机型详情信息】 +// swagger:route GET /deviceTypes/queryDeviceType/{device_type_id} deviceType queryDeviceType +// QueryDeviceType【机型管理】【机型详情信息】 +// Responses: +// 200: queryDeviceType +// default: ErrorResponse + +func (c *DeviceTypeController) QueryDeviceType() { + defer c.CatchException() + deviceTypeId := c.Ctx.Input.Param(":device_type_id") + req := &requestTypes.QueryDeviceTypeRequest{ + DeviceTypeID: deviceTypeId, + } + result, err := DeviceTypeLogic.GetDeviceTypeInfo(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// QueryDeviceTypeImages【机型管理】【机型详情信息】【关联镜像列表】此接口无分页参数 +// swagger:route GET /deviceTypes/deviceTypeImage deviceType queryDeviceTypeImages +// QueryDeviceTypeImages【机型管理】【机型详情信息】【关联镜像列表】此接口无分页参数 +// Responses: +// 200: queryDeviceTypeImages +// default: ErrorResponse + +func (c *DeviceTypeController) QueryDeviceTypeImages() { + defer c.CatchException() + req := &requestTypes.QueryDeviceTypeImagePageRequest{ + DeviceTypeID: c.GetString("deviceTypeId"), + ImageID: c.GetString("imageId"), + Architecture: c.GetString("architecture"), + OsType: c.GetString("osType"), + + ImageName: c.GetString("imageName"), + Version: c.GetString("version"), + OsID: c.GetString("osId"), + //ImageIDs: strings.Split(c.GetString("imageIds"), ","), + Source: c.GetString("source"), + IsAll: c.GetString("isAll"), + } + result, err := DeviceTypeLogic.GetDeviceTypeImageList(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// AssociateDeviceTypeImage【机型管理】【机型详情信息】【关联镜像列表】【添加镜像】 +// swagger:route POST /deviceTypes/associatedImage deviceType associateDeviceTypeImage +// AssociateDeviceTypeImage【机型管理】【机型详情信息】【关联镜像列表】【添加镜像】 +// Responses: +// 200: associateDeviceTypeImage +// default: ErrorResponse + +func (c *DeviceTypeController) AssociateDeviceTypeImage() { + defer c.CatchException() + req := &requestTypes.AssociateDeviceTypeImageRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("AssociateDeviceTypeImage parse request body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + result, err := DeviceTypeLogic.AssociateDeviceTypeImage(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// DisassociateDeviceTypeImage【机型管理】【机型详情信息】【关联镜像列表】【删除镜像】 +// swagger:route POST /deviceTypes/dissociatedImage deviceType disassociateDeviceTypeImage +// DisassociateDeviceTypeImage【机型管理】【机型详情信息】【关联镜像列表】【删除镜像】 +// Responses: +// 200: disassociateDeviceTypeImage +// default: ErrorResponse + +func (c *DeviceTypeController) DisassociateDeviceTypeImage() { + defer c.CatchException() + req := &requestTypes.DisassociateDeviceTypeImageRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DisassociateDeviceTypeImage parse request body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + result, err := DeviceTypeLogic.DisassociateDeviceTypeImage(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// ModifyDeviceType【机型管理】【编辑机型】 +// swagger:route PUT /deviceTypes/{device_type_id} deviceType modifyDeviceType +// ModifyDeviceType【机型管理】【编辑机型】 +// Responses: +// 200: modifyDeviceType +// default: ErrorResponse + +func (c *DeviceTypeController) ModifyDeviceType() { + defer c.CatchException() + deviceTypeId := c.Ctx.Input.Param(":device_type_id") + req := &requestTypes.ModifyDeviceTypeRequest{ + DeviceTypeID: deviceTypeId, + } + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + result, err := DeviceTypeLogic.ModifyDeviceTypeInfo(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// DeleteDeviceType【机型管理】【删除机型】 +// swagger:route DELETE /deviceTypes/{device_type_id} deviceType deleteDeviceType +// DeleteDeviceType【机型管理】【删除机型】 +// Responses: +// 200: deleteDeviceType +// default: ErrorResponse + +func (c *DeviceTypeController) DeleteDeviceType() { + defer c.CatchException() + deviceTypeId := c.Ctx.Input.Param(":device_type_id") + req := &requestTypes.DeleteDeviceTypeRequest{ + DeviceTypeID: deviceTypeId, + } + result, err := DeviceTypeLogic.DeleteDeviceTypeInfo(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// swagger:route GET /deviceType/getAvailableDeviceTypes deviceType getAvailableDeviceTypes +// GetAvailableDeviceTypes 获取该机房内可用机型列表 +// Responses: +// 200: getAvailableDeviceTypes +// default: ErrorResponse + +func (c *DeviceTypeController) GetAvailableDeviceTypes() { + defer c.CatchException() + req := requestTypes.GetAvailableDeviceTypesRequest{ + IdcID: c.GetString("idc_id"), + } + + // req.Validate(c.logPoints) + res, err := DeviceTypeLogic.GetAvailableDeviceTypes(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = res + +} + +// swagger:route GET /deviceTypes/{device_type_id}/describeVolumes deviceType describeVolumesByDeviceType +// +// DescribeVolumesByDeviceType 根据机型获取volumes +// +// Responses: +// 200: describeVolumesByDeviceType +// default: ErrorResponse + +func (c *DeviceTypeController) DescribeVolumesByDeviceType() { + deviceTypeId := c.Ctx.Input.Param(":device_type_id") + + res, err := DeviceTypeLogic.DescribeVolumesByDeviceType(c.logPoints, deviceTypeId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-operation-api/controllers/IdcContorller.go b/bmp-operation-api/controllers/IdcContorller.go new file mode 100644 index 0000000..6d4b00e --- /dev/null +++ b/bmp-operation-api/controllers/IdcContorller.go @@ -0,0 +1,175 @@ +package controllers + +import ( + "encoding/json" + "fmt" + "os" + + IdcLogic "coding.jd.com/aidc-bmp/bmp-operation-api/logic/IdcLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +type IdcController struct { + BaseController +} + +// GetIdcList【机房管理】【机房列表】 +// swagger:route GET /idc idc getIdcList +// GetIdcList【机房管理】【机房列表】 +// Responses: +// 200: getIdcList +// default: ErrorResponse + +func (c *IdcController) GetIdcList() { + + fmt.Println("IdcController.GetIdcList traffic...") + // defer c.CatchException() + page := requestTypes.PagingRequest{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.QueryIdcListRequest{ + Name: c.GetString("name"), + Level: c.GetString("level"), + IsAll: c.GetString("isAll"), + Show: c.GetString("show"), + PagingRequest: page, + } + result, err := IdcLogic.GetIdcList(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + if c.GetString("exportType") != "" { + fileName, downloadFileName, err := IdcLogic.ExportIdc(c.logPoints, result.Idcs) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, "导出excel错误"+err.Error(), errorCode.INTERNAL) + return + } + c.Ctx.Output.Download(fileName, downloadFileName) + if err := os.Remove(fileName); err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, "删除上传文件失败"+err.Error(), errorCode.INTERNAL) + return + } + return + + } + c.Res.Result = result +} + +// GetIdcInfo【机房管理】【机房详情】 +// swagger:route GET /idc/{idc_id} idc getIdcInfo +// GetIdcInfo【机房管理】【机房详情】 +// Responses: +// 200: getIdcInfo +// default: ErrorResponse + +func (c *IdcController) GetIdcInfo() { + defer c.CatchException() + idcID := c.Ctx.Input.Param(":idc_id") + req := &requestTypes.QueryIdcRequest{ + IdcID: idcID, + Show: c.GetString("show"), + } + result, err := IdcLogic.GetIdcInfo(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + + c.Res.Result = result +} + +// DeleteIdc【机房管理】【删除机房】 +// swagger:route DELETE /idc/{idc_id} idc deleteIdc +// DeleteIdc【机房管理】【删除机房】 +// Responses: +// 200: deleteIdc +// default: ErrorResponse + +func (c *IdcController) DeleteIdc() { + defer c.CatchException() + idcId := c.Ctx.Input.Param(":idc_id") + req := &requestTypes.DeleteIdcRequest{ + IdcID: idcId, + } + result, err := IdcLogic.DeleteIdc(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// CreateIdc【机房管理】【添加机房】 +// swagger:route PUT /idc idc createIdc +// CreateIdc【机房管理】【添加机房】 +// Responses: +// 200: createIdc +// default: ErrorResponse + +func (c *IdcController) CreateIdc() { + defer c.CatchException() + req := &requestTypes.CreateIdcRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + result, err := IdcLogic.CreateIdc(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// ModifyIdcInfo【机房管理】【编辑机房】 +// swagger:route POST /idc/{idc_id} idc modifyIdcInfo +// ModifyIdcInfo【机房管理】【编辑机房】 +// Responses: +// 200: modifyIdcInfo +// default: ErrorResponse + +func (c *IdcController) ModifyIdcInfo() { + defer c.CatchException() + idcId := c.Ctx.Input.Param(":idc_id") + req := &requestTypes.ModifyIdcRequest{ + IdcID: idcId, + } + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + result, err := IdcLogic.ModifyIdcInfo(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// VerifyUser【机房管理】【验证用户名密码】 +// swagger:route POST /idc/user/validate idc verifyUser +// VerifyUser【机房管理】【验证用户名密码】 +// Responses: +// 200: verifyUser +// default: ErrorResponse + +func (c *IdcController) VerifyUser() { + defer c.CatchException() + req := &requestTypes.VerifyUserRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + result, err := IdcLogic.VerifyUser(c.logPoints, req) + if err != nil || !result.Success { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} diff --git a/bmp-operation-api/controllers/ImageController.go b/bmp-operation-api/controllers/ImageController.go new file mode 100644 index 0000000..a570bbe --- /dev/null +++ b/bmp-operation-api/controllers/ImageController.go @@ -0,0 +1,295 @@ +package controllers + +import ( + "encoding/json" + "fmt" + "os" + "regexp" + "strings" + + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + + imageLogic "coding.jd.com/aidc-bmp/bmp-operation-api/logic/ImageLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + validation "git.jd.com/cps-golang/ironic-common/ironic/common/Validation" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type ImageController struct { + BaseController +} + +func (c *ImageController) UploadImage() { + defer c.CatchException() + file, header, err := c.GetFile("imageFile") + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + defer file.Close() + req := &requestTypes.UploadImageRequest{ + ImageFile: file, + } + res, err := imageLogic.UploadImage(c.logPoints, req, header, c.GetRequestID()) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route POST /images image createImage +// +// Responses: +// 200: createImage +// default: ErrorResponse +func (c *ImageController) CreateImage() { + defer c.CatchException() + req := &requestTypes.CreateImageRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("createImage unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + res, err := imageLogic.CreateImage(c.logPoints, req) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// DescribeImages ... +// swagger:route GET /images image describeImages +// +// Responses: +// 200: describeImages +// default: ErrorResponse + +func (c *ImageController) DescribeImages() { + defer c.CatchException() + req := &requestTypes.QueryImagesRequest{ + ImageID: c.GetString("imageId"), + DeviceTypeID: c.GetString("deviceTypeId"), + ImageName: c.GetString("imageName"), + Version: c.GetString("version"), + OsID: c.GetString("osId"), + ImageIDs: strings.Split(c.GetString("imageIds"), ","), + Source: c.GetString("source"), + PageNumber: c.getPageNumber(), + PageSize: c.getPageSize(), + IsAll: c.GetString("isAll"), + Architecture: c.GetString("architecture"), + OsType: c.GetString("osType"), + } + //req.Validate(c.logPoints) + + res, err := imageLogic.DescribeImages(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + fmt.Println(res.Images) + if c.GetString("exportType") != "" { + fileName, downloadFileName, err := imageLogic.ExportImage(c.logPoints, res.Images) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, "导出excel错误 "+err.Error(), errorCode.INTERNAL) + return + } + //c.Ctx.Input.SetData("download", "yes") + c.Ctx.Output.Download(fileName, downloadFileName) + if err := os.Remove(fileName); err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, "删除上传文件失败"+err.Error(), errorCode.INTERNAL) + return + } + return + } + /*if res.Images == nil { + res.Images = make([]&response.Image, 0) + }*/ + c.Res.Result = res +} + +// DescribeImage ... +// swagger:route GET /images/{image_id} image describeImage +// +// Responses: +// 200: describeImage +// default: ErrorResponse + +func (c *ImageController) DescribeImage() { + defer c.CatchException() + imageId := c.Ctx.Input.Param(":image_id") + if match, err := regexp.MatchString(validation.REGEX_ID, imageId); !match { + if err != nil { + c.logPoints.Warn("DeleteImage regexp match source error:", err.Error()) + } + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := imageLogic.DescribeImage(c.logPoints, imageId) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = res +} + +// ModifyImage ... +// swagger:route PUT /images/{image_id} image modifyImage +// +// Responses: +// 200: modifyImage +// default: ErrorResponse + +func (c *ImageController) ModifyImage() { + defer c.CatchException() + imageId := c.Ctx.Input.Param(":image_id") + if match, err := regexp.MatchString(validation.REGEX_ID, imageId); !match { + if err != nil { + c.logPoints.Warn("DeleteImage regexp match source error:", err.Error()) + } + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + req := &requestTypes.ModifyImageRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("createImage unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + res, err := imageLogic.ModifyImage(c.logPoints, req, imageId) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = res +} + +// DeleteImage ... +// swagger:route DELETE /images/{image_id} image deleteImage +// +// Responses: +// 200: deleteImage +// default: ErrorResponse + +func (c *ImageController) DeleteImage() { + defer c.CatchException() + imageId := c.Ctx.Input.Param(":image_id") + if match, err := regexp.MatchString(validation.REGEX_ID, imageId); !match { + if err != nil { + c.logPoints.Warn("DeleteImage regexp match source error:", err.Error()) + } + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := imageLogic.DeleteImage(c.logPoints, imageId) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = res +} + +// DescribeImageDeviceTypes ... +// swagger:route DELETE /images/imageDeviceTypes image describeImageDeviceTypes +// +// Responses: +// 200: describeImageDeviceTypes +// default: ErrorResponse + +func (c *ImageController) DescribeImageDeviceTypes() { + defer c.CatchException() + req := &requestTypes.QueryImageDeviceTypesRequest{ + ImageID: c.GetString("imageId"), + Architecture: c.GetString("architecture"), + IsAll: c.GetString("isAll"), + PageNumber: c.getPageNumber(), + PageSize: c.getPageSize(), + IsBind: c.GetString("isBind"), + } + result, err := imageLogic.DescribeImageDeviceTypes(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// swagger:route POST /images/associatedDeviceType image associatedDeviceType +// +// AssociatedDeviceType 镜像绑定机型 +// +// Responses: +// 200: associatedDeviceType +// default: ErrorResponse + +func (c *ImageController) AssociatedDeviceType() { + defer c.CatchException() + req := &requestTypes.AssociateImageDeviceTypeRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("AssociateDeviceType parse post body err:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := imageLogic.AssociatedDeviceType(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route DELETE /deviceTypes/dissociatedDeviceType deviceType dissociatedDeviceType +// +// DissociatedDeviceType 镜像解绑机型 +// +// Responses: +// 200: dissociatedDeviceType +// default: ErrorResponse + +func (c *ImageController) DissociatedDeviceType() { + defer c.CatchException() + req := &requestTypes.DisassociateDeviceTypeImageRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DissociatedImage parse post body err:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + //res, err := deviceTypeLogic.DisassociateDeviceTypeImage(c.logPoints, req) //直接调用机型解绑镜像接口 + res, err := imageLogic.DissociatedDeviceType(c.logPoints, req) //直接调用镜像解绑机型接口,不要调用机型解绑镜像,虽然接口参数一样,但是镜像解绑机型接口还要判断机型的实例是否有创建中的 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route GET /image/queryImagesByDeviceType image queryImagesByDeviceType +// QueryImagesByDeviceType 根据机型获取绑定的镜像列表 +// Responses: +// 200: queryImagesByDeviceType +// default: ErrorResponse + +func (c *ImageController) QueryImagesByDeviceType() { + defer c.CatchException() + + req := requestTypes.QueryImagesByDeviceTypeRequest{ + IdcID: c.GetString("idc_id"), + DeviceTypeID: c.GetString("deviceTypeId"), + } + // req.Validate(c.logPoints) + res, err := imageLogic.QueryImagesByDeviceType(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = res + +} diff --git a/bmp-operation-api/controllers/InstanceController.go b/bmp-operation-api/controllers/InstanceController.go new file mode 100644 index 0000000..5c6905e --- /dev/null +++ b/bmp-operation-api/controllers/InstanceController.go @@ -0,0 +1,354 @@ +package controllers + +import ( + // "encoding/json" + + "encoding/json" + + InstanceLogic "coding.jd.com/aidc-bmp/bmp-operation-api/logic/InstanceLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + response "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +type InstanceController struct { + BaseController +} + +// StartInstance【设备管理】【开机】 +// swagger:route POST /instances/start/{instance_id} instance startInstance +// StartInstance【设备管理】【开机】 +// Responses: +// 200: startInstance +// default: ErrorResponse + +func (c *InstanceController) StartInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + req := &requestTypes.StartInstanceRequest{ + InstanceID: instanceId, + } + result, err := InstanceLogic.StartInstance(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// RestartInstance【设备管理】【重启】 +// swagger:route POST /instances/restart/{instance_id} instance restartInstance +// RestartInstance【设备管理】【重启】 +// Responses: +// 200: restartInstance +// default: ErrorResponse + +func (c *InstanceController) RestartInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + req := &requestTypes.RestartInstanceRequest{ + InstanceID: instanceId, + } + result, err := InstanceLogic.RestartInstance(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// StopInstance【设备管理】【关机】 +// swagger:route POST /instances/stop/{instance_id} instance stopInstance +// StopInstance【设备管理】【关机】 +// Responses: +// 200: stopInstance +// default: ErrorResponse + +func (c *InstanceController) StopInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + req := &requestTypes.StopInstanceRequest{ + InstanceID: instanceId, + } + result, err := InstanceLogic.StopInstance(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// swagger:route POST /instances/resetStatus/{instance_id} instance resetInstanceStatus +// ResetInstanceStatus【设备管理】【重置实例状态】 +// Responses: +// 200: resetInstanceStatus +// default: ErrorResponse +func (c *InstanceController) ResetInstanceStatus() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + + result, err := InstanceLogic.ResetInstanceStatus(c.logPoints, instanceId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// swagger:route DELETE /instances/{instance_id} instance deleteInstance +// DeleteInstance【设备管理】【回收实例】 +// Responses: +// 200: deleteInstance +// default: ErrorResponse +func (c *InstanceController) DeleteInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + + result, err := InstanceLogic.DeleteInstance(c.logPoints, instanceId) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// swagger:route POST /instances/lock/{instance_id} instance lockInstance +// LockInstance 锁定实例 +// Responses: +// 200: lockInstance +// default: ErrorResponse + +func (c *InstanceController) LockInstance() { + defer c.CatchException() + + instanceId := c.Ctx.Input.Param(":instance_id") + + res, err := InstanceLogic.LockInstance(c.logPoints, instanceId) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instances/unlock/{instance_id} instance unlockInstance +// UnlockInstance 解锁实例 +// Responses: +// 200: unlockInstance +// default: ErrorResponse + +func (c *InstanceController) UnlockInstance() { + defer c.CatchException() + instanceId := c.Ctx.Input.Param(":instance_id") + // req.Validate() + res, err := InstanceLogic.UnLockInstance(c.logPoints, instanceId) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// StartInstances 批量开机 +func (c *InstanceController) StartInstances() { + defer c.CatchException() + req := &requestTypes.StartInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("StartInstances unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + // req.Validate() + res, err := InstanceLogic.StartInstances(c.logPoints, req.InstanceIDs) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// StartInstances 批量关机 +func (c *InstanceController) StopInstances() { + defer c.CatchException() + req := &requestTypes.StartInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("StopInstances unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + // req.Validate() + res, err := InstanceLogic.StopInstances(c.logPoints, req.InstanceIDs) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// StartInstances 批量重启 +func (c *InstanceController) RestartInstances() { + defer c.CatchException() + req := &requestTypes.StartInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("RestartInstances unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + // req.Validate() + res, err := InstanceLogic.RestartInstances(c.logPoints, req.InstanceIDs) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// ModifyInstances 批量编辑实例名称 +func (c *InstanceController) ModifyInstances() { + defer c.CatchException() + req := &requestTypes.ModifyInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("ModifyInstancesRequest unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + // req.Validate() + res, err := InstanceLogic.ModifyInstances(c.logPoints, req.InstanceIDs, req.InstanceName) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// StartInstances 批量删除实例 +func (c *InstanceController) DeleteInstances() { + defer c.CatchException() + req := &requestTypes.StartInstancesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warnf("DeleteInstances unmarshal error:%s", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + // req.Validate() + res, err := InstanceLogic.DeleteInstances(c.logPoints, req.InstanceIDs) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instance/resetPasswd instance resetPasswd +// resetPasswd 重置密码 +// Responses: +// 200: resetPasswd +// default: ErrorResponse + +func (c *InstanceController) ResetPasswd() { + defer c.CatchException() + + req := &requestTypes.ResetPasswdRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + // req.Validate() + res, err := InstanceLogic.ResetInstancePassword(c.logPoints, req.InstanceId, req.Password) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instances/batchResetPasswd instance resetInstancesPasswd +// resetInstancesPasswd 批量重置密码 +// Responses: +// 200: resetInstancesPasswd +// default: ErrorResponse + +func (c *InstanceController) ResetInstancesPasswd() { + defer c.CatchException() + + req := &requestTypes.ResetInstancesPasswdRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + // req.Validate() + res, err := InstanceLogic.ResetInstancesPassword(c.logPoints, req.InstanceIds, req.Password) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route POST /instances/reinstallInstance instance reinstallInstance +// ReinstallInstance 重装实例 +// Responses: +// 200: reinstallInstance +// default: ErrorResponse + +func (c *InstanceController) ReinstallInstance() { + defer c.CatchException() + + req := &requestTypes.ReinstallInstanceRequest{} + + //fmt.Println(req, req.Hostname) + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + // req.Validate() + res, err := InstanceLogic.ReinstallInstance(c.logPoints, *req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } else { + c.Res.Result = response.CommonResponse{ + Success: res, + } + return + } +} + +// swagger:route GET /instances/{instance_id} instance getInstanceInfo +// GetInstanceInfo 查看实例详情 +// Responses: +// 200: getInstanceInfo +// default: ErrorResponse + +func (c *InstanceController) GetInstanceInfo() { + defer c.CatchException() + param := requestTypes.QueryInstanceRequest{ + InstanceId: c.Ctx.Input.Param(":instance_id"), + } + res, err := InstanceLogic.DescribeInstance(c.logPoints, param) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-operation-api/controllers/KeypairController.go b/bmp-operation-api/controllers/KeypairController.go new file mode 100644 index 0000000..74f939e --- /dev/null +++ b/bmp-operation-api/controllers/KeypairController.go @@ -0,0 +1,40 @@ +package controllers + +import ( + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" + + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/KeypairLoigc" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" +) + +// DeviceController operations for Device +type KeypairController struct { + BaseController +} + +// swagger:route GET /keypair keypair getKeypairList +// GetKeypairList 获取keypair列表 +// Responses: +// 200: getKeypairList +// default: ErrorResponse + +func (c *KeypairController) GetKeypairList() { + defer c.CatchException() + pg := requestTypes.PagingRequest{ + PageNumber: c.pageable.PageNumber, + PageSize: c.pageable.PageSize, + } + req := &requestTypes.QueryKeypairsRequest{ + PagingRequest: pg, + Name: c.GetString("name"), + KeypairIds: c.GetStrings("keypairId"), + } + + res, err := KeypairLoigc.DescribeKeypairs(c.logPoints, *req) //返回byte数组 + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-operation-api/controllers/MessageController.go b/bmp-operation-api/controllers/MessageController.go new file mode 100644 index 0000000..b42fe46 --- /dev/null +++ b/bmp-operation-api/controllers/MessageController.go @@ -0,0 +1,253 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/messageLogic" + util "coding.jd.com/aidc-bmp/bmp-operation-api/util" + + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type MessageController struct { + BaseController +} + +// HasUnreadMessage ... +// swagger:route GET /messages/hasUnreadMessage message hasUnreadMessage +// +// HasUnreadMessage 获取有没有未读消息 +// +// Responses: +// 200: hasUnreadMessage +// default: ErrorResponse + +func (c *MessageController) HasUnreadMessage() { + defer c.CatchException() + + res, err := messageLogic.HasUnreadMessage(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.HasUnreadMessage{ + HasUnread: res, + } +} + +// GetMessageList ... +// swagger:route GET /messages message getMessageList +// +// GetMessageList 获取message列表(分页) +// +// Responses: +// 200: getMessageList +// default: ErrorResponse +func (c *MessageController) GetMessageList() { + defer c.CatchException() + + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + + req := &requestTypes.QueryMessagesRequest{ + IsAll: c.GetString("isAll"), + HasRead: c.GetString("hasRead"), + MessageType: c.GetString("messageType"), + MessageSubType: c.GetString("messageSubType"), + Detail: c.GetString("detail"), + ExportType: c.GetString("exportType"), + } + + res, err := messageLogic.GetPageMessages(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if c.GetString("exportType") != "" { + fileName, downloadFileName := messageLogic.ExportMessage(c.logPoints, res.Messages) + //c.Ctx.Input.SetData("download", "yes") + c.Ctx.Output.Download(fileName, downloadFileName) + return + } else { + c.Res.Result = res + } +} + +// GetMessageStatistic ... +// swagger:route GET /messages/statistic message getMessageStatistic +// +// GetMessageStatistic 获取message总数和未读数 +// +// Responses: +// 200: getMessageStatistic +// default: ErrorResponse +func (c *MessageController) GetMessageStatistic() { + defer c.CatchException() + + total, unread, err := messageLogic.GetMessageStatistic(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = response.MessageStatistic{ + + TotalCount: total, + UnreadCount: unread, + } +} + +// ReadMessage ... +// swagger:route PUT /messages/doRead message readMessage +// +// ReadMessage 将消息设置为已读(可多条) +// +// Responses: +// 200: readMessage +// default: ErrorResponse +func (c *MessageController) ReadMessage() { + defer c.CatchException() + + req := &requestTypes.ReadMessagesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ReadMessage parse ReadMessagesRequest body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := messageLogic.ReadMessages(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// GetMessageById ... +// swagger:route GET /messages/getMessageById message getMessageById +// +// GetMessageById 获取消息详情,包括上一条/下一条的messageid +// +// Responses: +// 200: getMessageById +// default: ErrorResponse + +func (c *MessageController) GetMessageById() { + defer c.CatchException() + + req := &requestTypes.GetMessageByIdRequest{ + MessageId: c.GetString("messageId"), + } + msg, nextMsgId, prevMsgId, err := messageLogic.GetMessageById(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.MessageWithNextPrev{ + Message: msg, + NextMessageId: nextMsgId, + PrevMessageId: prevMsgId, + } +} + +// GetMessageTypes ... +// swagger:route GET /messages/getMessageTypes message getMessageTypes +// +// GetMessageTypes 获取消息类型/子类型 +// +// Responses: +// 200: getMessageTypes +// default: ErrorResponse + +func (c *MessageController) GetMessageTypes() { + defer c.CatchException() + + res, err := messageLogic.GetMessageTypes(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +func (c *MessageController) DeleteMessage() { + defer c.CatchException() + + req := &requestTypes.DeleteMessagesRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ReadMessage parse ReadMessagesRequest body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := messageLogic.DeleteMessages(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// DialMail ... +// swagger:route POST /messages/dialMail message dialMail +// +// DialMail 测试邮箱设置是否正确 +// +// Responses: +// 200: dialMail +// default: ErrorResponse +func (c *MessageController) DialMail() { + defer c.CatchException() + + req := &requestTypes.MailDialRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("MailDial parse MailDialRequest body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := messageLogic.DialMail(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +func (c *MessageController) SaveIsPushMail() { + defer c.CatchException() + + req := &requestTypes.SaveIsPushMailRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("SaveIsPushMail parse MailSaveIsPushRequest body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := messageLogic.SaveIsPushMail(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +func (c *MessageController) DescribeMail() { + defer c.CatchException() + + res, err := messageLogic.DescribeMail(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-operation-api/controllers/OsController.go b/bmp-operation-api/controllers/OsController.go new file mode 100644 index 0000000..8d03b35 --- /dev/null +++ b/bmp-operation-api/controllers/OsController.go @@ -0,0 +1,52 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/OsLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type OsController struct { + BaseController +} + +// DescribeOSs ... +// swagger:route GET /oss os describeOSs +// +// Responses: +// 200: describeOSs +// default: ErrorResponse + +func (c *OsController) DescribeOSs() { + defer c.CatchException() + req := &requestTypes.QueryOssRequest{ + OsName: c.GetString("osName"), + Architecture: c.GetString("architecture"), + OsType: c.GetString("osType"), + Platform: c.GetString("platform"), + OsVersion: c.GetString("osVersion"), + IsAll: c.GetString("isAll"), + } + + res, err := OsLogic.DescribeOSs(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + if res.Oss == nil { + res.Oss = make([]*response.Os, 0) + } + c.Res.Result = res +} +func (c *OsController) DescribeOSsFilter() { + defer c.CatchException() + res := BaseLogic.OssFilter + if c.logPoints.GetPoint("language") == BaseLogic.EN_US { + res = BaseLogic.OssFilterEn + } + c.Res.Result = res +} diff --git a/bmp-operation-api/controllers/PartitionController.go b/bmp-operation-api/controllers/PartitionController.go new file mode 100644 index 0000000..e023b37 --- /dev/null +++ b/bmp-operation-api/controllers/PartitionController.go @@ -0,0 +1,36 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/PartitionLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// PartitionController operations for partition +type PartitionController struct { + BaseController +} + +// swagger:route GET /partition/queryDefaultSystemPartitions keypair queryDefaultSystemPartitions +// QueryDefaultSystemPartitions 根据机型和镜像查系统盘默认分区列表 +// Responses: +// 200: queryDefaultSystemPartitions +// default: ErrorResponse + +func (c *PartitionController) QueryDefaultSystemPartitions() { + defer c.CatchException() + + req := requestTypes.QueryDefaultSystemPartitionRequest{ + ImageID: c.GetString("imageId"), + DeviceTypeID: c.GetString("deviceTypeId"), + } + + res, err := PartitionLogic.QueryDefaultSystemPartitions(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.PARAMETER_ERROR) + return + } + c.Res.Result = res + +} diff --git a/bmp-operation-api/controllers/RaidController.go b/bmp-operation-api/controllers/RaidController.go new file mode 100644 index 0000000..f74d700 --- /dev/null +++ b/bmp-operation-api/controllers/RaidController.go @@ -0,0 +1,77 @@ +package controllers + +import ( + RaidLogic "coding.jd.com/aidc-bmp/bmp-operation-api/logic/RaidLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type RaidController struct { + BaseController +} + +// QueryRaidsAll ... +// swagger:route GET /raids raid queryRaidsAll +// +// Responses: +// 200: queryRaidsAll +// default: ErrorResponse + +func (c *RaidController) QueryRaidsAll() { + defer c.CatchException() + res, err := RaidLogic.QueryRaidsAll(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + if res.Raids == nil { + res.Raids = make([]*response.Raid, 0) + } + c.Res.Result = res +} + +// swagger:route GET /raid/queryRaidsByDeviceTypeIDAndVolumeType raid queryRaidsByDeviceTypeIDAndVolumeType +// QueryRaidsByDeviceTypeIDAndVolumeType 根据机型查询系统盘/数据盘可用raid列表 +// Responses: +// 200: queryRaidsByDeviceTypeIDAndVolumeType +// default: ErrorResponse + +func (c *RaidController) QueryRaidsByDeviceTypeIDAndVolumeType() { + defer c.CatchException() + + req := requestTypes.QueryRaidsRequest{ + DeviceTypeID: c.GetString("deviceTypeId"), + VolumeType: c.GetString("volumeType"), + } + + raids, err := RaidLogic.QueryRaids(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.PARAMETER_ERROR) + return + } + + /*dt, _ := DeviceTypeLogic.GetDeviceTypeInfo(c.logPoints, &requestTypes.QueryDeviceTypeRequest{DeviceTypeID: req.DeviceTypeID}) + if req.VolumeType == "system" { + for idx, raid := range raids { + if raid.RaidName == "NORAID" { //产品坚持认为,两块盘的noraid要叫单盘RAID0 + if dt.SystemVolumeAmount == 2 && dt.RaidCan == "RAID" { + raids[idx].RaidName = "单盘RAID0" + if c.logPoints.GetPoint("language").(string) == BaseLogic.EN_US { + raids[idx].RaidName = "RAID0-stripping" + } + } else if dt.RaidCan == "NORAID" { + raids[idx].RaidName = "未配置RAID" + if c.logPoints.GetPoint("language").(string) == BaseLogic.EN_US { + raids[idx].RaidName = "RAID is not configured" + } + } + + } + } + }*/ + c.Res.Result = raids + return +} diff --git a/bmp-operation-api/controllers/RoleController.go b/bmp-operation-api/controllers/RoleController.go new file mode 100644 index 0000000..542624f --- /dev/null +++ b/bmp-operation-api/controllers/RoleController.go @@ -0,0 +1,57 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/RoleLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// DeviceTypeController operations for Device +type RoleController struct { + BaseController +} + +// DescribeOSs ... +// swagger:route GET /oss os describeOSs +// +// Responses: +// 200: describeOSs +// default: ErrorResponse + +func (c *RoleController) DescribeRoles() { + defer c.CatchException() + req := &requestTypes.DescribeRolesRequest{ + IsAll: c.GetString("isAll"), + } + res, err := RoleLogic.DescribeRoles(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + if res.Roles == nil { + res.Roles = make([]*response.Role, 0) + } + c.Res.Result = res +} + +// swagger:route GET /roles/roleInfo/current role currentRole +// +// CurrentRole 获取当前登录用户的角色 +// Responses: +// 200: currentRole +// default: ErrorResponse + +func (c *RoleController) CurrentRole() { + defer c.CatchException() + + res, err := RoleLogic.CurrentRole(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.RoleInfo{ + Role: res, + } +} diff --git a/bmp-operation-api/controllers/TimezoneController.go b/bmp-operation-api/controllers/TimezoneController.go new file mode 100644 index 0000000..14846de --- /dev/null +++ b/bmp-operation-api/controllers/TimezoneController.go @@ -0,0 +1,25 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/TimezoneLogic" + responseTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" +) + +type TimezoneController struct { + BaseController +} + +// swagger:route GET /user/timezones user getTimezoneList +// GetTimezoneList 获取时区列表 +// Responses: +// 200: getTimezoneList +// default: ErrorResponse + +func (c *TimezoneController) GetTimezoneList() { + + res := TimezoneLogic.GetTimeZoneList(c.logPoints) + c.Res.Result = responseTypes.GetTimezoneListResponse{ + TimeZones: res, + } + +} diff --git a/bmp-operation-api/controllers/UserController.go b/bmp-operation-api/controllers/UserController.go new file mode 100644 index 0000000..8d4bcf2 --- /dev/null +++ b/bmp-operation-api/controllers/UserController.go @@ -0,0 +1,306 @@ +package controllers + +import ( + "encoding/json" + "fmt" + "os" + + UserLoigc "coding.jd.com/aidc-bmp/bmp-operation-api/logic/UserLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + "git.jd.com/cps-golang/ironic-common/exception" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +type UserController struct { + BaseController +} + +// Login 登录 +// swagger:route POST /login user login +// Login 登录 +// Responses: +// 200: login +// default: ErrorResponse + +func (c *UserController) Login() { + + // defer c.CatchException() + req := &requestTypes.LoginRequest{} + // req.Validate() + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + panic(exception.Exception{Msg: err.Error()}) + } + + _, err := UserLoigc.VerifyUser(c.logPoints, req.Username, req.Password) + + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + + jdc := c.Ctx.GetCookie(sessionName) + if err := c.SetSession(jdc, req.Username); err != nil { + c.logPoints.Warnf("SetSession error, session_id:%s, username:%s, error:%s", jdc, req.Username, err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, errorCode.HTTP_FORBIDDEN, err.Error()) + return + } + c.Ctx.Output.Header("X-Jdcloud-Username", req.Username) + c.logPoints.Infof("SetSession success, session_id:%s, username:%s:", jdc, req.Username) + c.Res.Result = noQueryResponse +} + +// Logout 登出 +// swagger:route POST /logout user logout +// Logout 登出 +// Responses: +// 200: logout +// default: ErrorResponse + +func (c *UserController) Logout() { + //username := c.GetString("username") + + // fmt.Println("所有cookie:", c.Ctx.Request.Cookies()) + jdc := c.Ctx.GetCookie(sessionName) + username := c.GetSession(jdc) + + if err := c.DelSession(jdc); err != nil { + c.logPoints.Warnf("del session error, session_id:%s, username:%s, error:%s", jdc, username, err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, errorCode.HTTP_FORBIDDEN, err.Error()) + return + } + c.logPoints.Infof("del session success, session_id:%s, username:%s", jdc, username) + c.Res.Result = noQueryResponse +} + +// GetUserList 获取用户列表 +// swagger:route GET /users user getUserList +// GetUserList 获取用户列表 +// Responses: +// 200: getUserList +// default: ErrorResponse + +func (c *UserController) GetUserList() { + defer c.CatchException() + p := requestTypes.PagingRequest{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.QueryUsersRequest{ + UserName: c.GetString("userName"), + RoleID: c.GetString("roleId"), + ProjectID: c.GetString("projectId"), + IsAll: c.GetString("isAll"), + PagingRequest: p, + } + result, err := UserLoigc.GetUserList(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + + if c.GetString("exportType") != "" { + fileName, downloadFileName, err := UserLoigc.ExportUserExcel(c.logPoints, result.Users) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, "导出设备列表excel错误 "+err.Error(), errorCode.INTERNAL) + return + } + //c.Ctx.Input.SetData("download", "yes") + c.Ctx.Output.Download(fileName, downloadFileName) + if err := os.Remove(fileName); err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, "删除上传文件失败"+err.Error(), errorCode.INTERNAL) + return + } + return + } + c.Res.Result = result +} + +// AddUser 【用户管理】【添加用户】 +// swagger:route PUT /users user addUser +// AddUser 【用户管理】【添加用户】 +// Responses: +// 200: addUser +// default: ErrorResponse + +func (c *UserController) AddUser() { + defer c.CatchException() + + req := &requestTypes.AddUserRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + result, err := UserLoigc.AddUser(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// GetUserInfo 【用户管理】【用户详情】 +// swagger:route GET /users/{user_id} user getUserInfo +// GetUserInfo 【用户管理】【用户详情】 +// Responses: +// 200: getUserInfo +// default: ErrorResponse + +func (c *UserController) GetUserInfo() { + defer c.CatchException() + userId := c.Ctx.Input.Param(":user_id") + req := &requestTypes.QueryUserInfoRequest{ + UserID: userId, + } + result := UserLoigc.GetUserInfo(c.logPoints, req) + c.Res.Result = result +} + +// ModifyUserInfo 【用户管理】【编辑用户信息】 +// swagger:route POST /users/{user_id} user modifyUserInfo +// ModifyUserInfo 【用户管理】【编辑用户信息】 +// Responses: +// 200: modifyUserInfo +// default: ErrorResponse + +func (c *UserController) ModifyUserInfo() { + defer c.CatchException() + userId := c.Ctx.Input.Param(":user_id") + req := &requestTypes.ModifyUserInfoRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("ModifyUser parse pUsert body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if err := UserLoigc.ModifyUserInfo(c.logPoints, req, userId); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// DeleteUserInfo 【用户管理】【删除用户】 +// swagger:route DELETE /users/{user_id} user deleteUserInfo +// DeleteUserInfo 【用户管理】【删除用户】 +// Responses: +// 200: deleteUserInfo +// default: ErrorResponse + +func (c *UserController) DeleteUserInfo() { + defer c.CatchException() + userId := c.Ctx.Input.Param(":user_id") + req := &requestTypes.DeleteUserInfoRequest{ + UserID: userId, + } + if err := UserLoigc.DeleteUserInfo(c.logPoints, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: true, + } +} + +// VerifyLoginUser【验证用户名密码】 +// swagger:route POST /users/login/validate user verifyLoginUser +// VerifyLoginUser【验证用户名密码】 +// Responses: +// 200: verifyLoginUser +// default: ErrorResponse + +func (c *UserController) VerifyLoginUser() { + defer c.CatchException() + req := &requestTypes.VerifyUserRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + + result, err := UserLoigc.VerifyUser(c.logPoints, req.Username, req.Password) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.ABORTED) + return + } + c.Res.Result = result +} + +// swagger:route GET /user/local user getLocalUserInfo +//GetUserInfo 获取当前用户详情 +// Responses: +// 200: getLocalUserInfo +// default: ErrorResponse + +func (c *UserController) GetLocalUserInfo() { + defer c.CatchException() + result, err := UserLoigc.GetLocalUserInfo(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.HTTP_FORBIDDEN) + return + } + c.Res.Result = result +} + +// swagger:route PUT /user/local/password user updateLocalPassword +// UpdatePassword 修改当前登录用户密码 +// Responses: +// 200: updateLocalPassword +// default: ErrorResponse + +func (c *UserController) UpdateLocalPassword() { + req := &requestTypes.UpdateLocalPasswordRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + userId := c.logPoints.GetPoint("userId").(string) + res, err := UserLoigc.ModifyLocalUserPassword(c.logPoints, userId, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.HTTP_FORBIDDEN) + return + } + //修改完成后登出 + if res { + jdc := c.Ctx.GetCookie(sessionName) + username := c.GetSession(jdc) + + if err := c.DelSession(jdc); err != nil { + c.logPoints.Warnf("UpdatePassword del session error, session_id:%s, username:%s, error:%s", jdc, username, err.Error()) + } else { + c.Ctx.ResponseWriter.WriteHeader(402) + fmt.Fprintln(c.Ctx.ResponseWriter, "请重新登录") + return + } + } + c.Res.Result = response.CommonResponse{ + Success: res, + } + +} + +// swagger:route PUT /user/local user updateLocalUserInfo +// UpdateLocalUserInfo 修改个人信息(除密码) +// Responses: +// 200: updateLocalUserInfo +// default: ErrorResponse + +func (c *UserController) UpdateLocalUserInfo() { + userId := c.logPoints.GetPoint("userId").(string) + req := &requestTypes.ModifyLocalUserInfoRequest{} + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := UserLoigc.ModifyLocalUserInfo(c.logPoints, userId, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.HTTP_FORBIDDEN) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } + +} diff --git a/bmp-operation-api/controllers/WebSocketController.go b/bmp-operation-api/controllers/WebSocketController.go new file mode 100644 index 0000000..bcdd652 --- /dev/null +++ b/bmp-operation-api/controllers/WebSocketController.go @@ -0,0 +1,104 @@ +package controllers + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "time" + + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/WebsocketLogic" + response "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + "github.com/gorilla/websocket" +) + +// WebSocketController operations for Msg +type WebSocketController struct { + BaseController +} + +func (wsc *WebSocketController) Send() { + userId := wsc.logPoints.GetPoint("userId").(string) + err := WebsocketLogic.SendMsg2Client(wsc.logPoints, []string{userId}, WebsocketLogic.NofifyMessage{ + Type: "test", + SubType: "sendTestSocketmsg", + Message: "test text", + }) + success := true + if err != nil { + success = false + } + + wsc.Res.Result = response.CommonResponse{ + Success: success, + } + +} + +func (wsc *WebSocketController) Get() { + fmt.Println("aaaa") + var upgrader = websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 1024, + // 解决跨域问题 + CheckOrigin: func(r *http.Request) bool { + return true + }, + } + + ws, err := upgrader.Upgrade(wsc.Ctx.ResponseWriter, wsc.Ctx.Request, nil) + if err != nil { + log.Fatal(err) + } + + ConnId := wsc.logPoints.GetPoint("logid").(string) + c := &WebsocketLogic.Client{ + ID: ConnId, // 连接id + // UserId: wsc.logPoints.GetPoint("userId").(string), + UserId: "minping-mock", + HeartbeatTime: time.Now().Unix(), + Socket: ws, + } + + // defer ws.Close() + WebsocketLogic.RegisterChan <- c + + defer func() { + WebsocketLogic.UnregisterChan <- c + }() + for { + // 读取消息 + _, body, err := c.Socket.ReadMessage() + if err != nil { + wsc.logPoints.Warnf("c.Socket.ReadMessage error:%s", err.Error()) + break + } + fmt.Println("receive msg:", string(body)) + + msg := WebsocketLogic.ReceiveMessage{} + err = json.Unmarshal(body, &msg) + if err != nil { + wsc.logPoints.Warnf("unmarshal error:%s", err.Error()) + continue + } + + if msg.Type == WebsocketLogic.MessageTypeHeartbeatFromClient { // 维持心跳消息 + // 刷新连接时间 + c.HeartbeatTime = time.Now().Unix() + + // 回复心跳 + replyMsg := WebsocketLogic.NofifyMessage{ + Type: WebsocketLogic.MessageTypeHeartbeatFromServer, + } + err = c.Socket.WriteJSON(replyMsg) + if err != nil { + fmt.Println("c.Socket.WriteJSON error:", err.Error()) + wsc.logPoints.Warnf("c.Socket.WriteJSON error:%s", err.Error()) + } + // + } else { + //目前nothing + } + } + +} diff --git a/bmp-operation-api/controllers/auditLogsController.go b/bmp-operation-api/controllers/auditLogsController.go new file mode 100644 index 0000000..c0f93a2 --- /dev/null +++ b/bmp-operation-api/controllers/auditLogsController.go @@ -0,0 +1,67 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/AuditLogLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// AuditLogsController operations for auditlog +type AuditLogsController struct { + BaseController +} + +// swagger:route GET /auditLogs auditLog describeAuditLogs +// DescribeAuditLogs 获取审计日志列表 +// Responses: +// 200: describeAuditLogs +// default: ErrorResponse + +func (c *AuditLogsController) DescribeAuditLogs() { + defer c.CatchException() + + p := requestTypes.PagingRequest{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + req := &requestTypes.DescribeAuditLogsRequest{ + PagingRequest: p, + Sn: c.GetString("sn"), + Operation: c.GetString("operation"), + Result: c.GetString("result"), + UserName: c.GetString("userName"), + IsAll: c.GetString("isAll"), + } + st, _ := c.GetInt64("startTime") + et, _ := c.GetInt64("endTime") + req.StartTime = st + req.EndTime = et + + //device_types, err := deviceTypeLogic.QueryByRequest(c.logPoints, req) + res, err := AuditLogLogic.QueryAuditLogs(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if c.GetString("exportType") != "" { + fileName, downloadFileName := AuditLogLogic.ExportAuditLogs(c.logPoints, res.AuditLogs) + //c.Ctx.Input.SetData("download", "yes") + c.Ctx.Output.Download(fileName, downloadFileName) + return + } else { + c.Res.Result = res + } + +} + +func (c *AuditLogsController) DescribeAuditLogTypes() { + + //device_types, err := deviceTypeLogic.QueryByRequest(c.logPoints, req) + res, err := AuditLogLogic.DescribeAuditLogsTypes(c.logPoints) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-operation-api/controllers/monitorAlertController.go b/bmp-operation-api/controllers/monitorAlertController.go new file mode 100644 index 0000000..e362f1a --- /dev/null +++ b/bmp-operation-api/controllers/monitorAlertController.go @@ -0,0 +1,107 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/monitorAlertLogic" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + response "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + util "coding.jd.com/aidc-bmp/bmp-operation-api/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorAlertController 告警规则 +type MonitorAlertController struct { + BaseController +} + +// swagger:route GET /monitorAlert/describeAlert monitorAlert describeAlert +// +// DescribeAlert 告警详情 +// +// Responses: +// 200: describeAlert +// default: ErrorResponse +func (c *MonitorAlertController) DescribeAlert() { + defer c.CatchException() + req := request.DescribeAlertRequest{ + AlertID: c.GetString("AlertId"), + } + res, err := monitorAlertLogic.DescribeAlert(c.logPoints, req.AlertID) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route GET /monitorAlert/describeAlerts monitorAlert describeAlerts +// +// DescribeAlerts 告警列表 +// +// Responses: +// 200: describeAlerts +// default: ErrorResponse +func (c *MonitorAlertController) DescribeAlerts() { + defer c.CatchException() + + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + stime, _ := c.GetInt64("startTime") + etime, _ := c.GetInt64("endTime") + + req := &request.DescribeAlertsRequest{ + IsAll: c.GetString("isAll"), + UserName: c.GetString("userName"), + UserID: c.GetString("userId"), + RuleName: c.GetString("ruleName"), + RuleID: c.GetString("ruleId"), + ResourceID: c.GetString("resourceId"), + StartTime: stime, + EndTime: etime, + } + + res, err := monitorAlertLogic.DescribeAlerts(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if c.GetString("exportType") != "" { + fileName, downloadFileName := monitorAlertLogic.ExportAlerts(c.logPoints, res.Alerts) + //c.Ctx.Input.SetData("download", "yes") + c.Ctx.Output.Download(fileName, downloadFileName) + return + } else { + c.Res.Result = res + } +} + +// swagger:route DELETE /monitorAlert/deleteAlert monitorAlert deleteAlert +// +// DeleteAlert 删除告警 +// +// Responses: +// 200: deleteAlert +// default: ErrorResponse +func (c *MonitorAlertController) DeleteAlert() { + defer c.CatchException() + c.logPoints.Infof("EnableAlert body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.DeleteAlertRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DeleteAlert parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := monitorAlertLogic.DeleteAlert(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} diff --git a/bmp-operation-api/controllers/monitorDataController.go b/bmp-operation-api/controllers/monitorDataController.go new file mode 100644 index 0000000..66834d2 --- /dev/null +++ b/bmp-operation-api/controllers/monitorDataController.go @@ -0,0 +1,49 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/monitorDataLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorDataController 读取监控数据 +type MonitorDataController struct { + BaseController +} + +// swagger:route GET /monitorData monitorData getMonitorData +// +// GetMonitorData 获取图表监控数据 +// +// Responses: +// 200: getMonitorData +// default: ErrorResponse +func (c *MonitorDataController) GetMonitorData() { + + stime, _ := c.GetInt64("startTime") + etime, _ := c.GetInt64("endTime") + ti, _ := c.GetInt64("timeInterval") + lastManyTime, _ := c.GetInt64("lastManyTime") + req := requestTypes.GetMonitorDataRequest{ + MetricName: c.GetString("metricName"), + InstanceID: c.GetString("instanceId"), + Device: c.GetString("device"), + StartTime: stime, + EndTime: etime, + TimeInterval: ti, + LastManyTime: lastManyTime, + DownSampleType: c.GetString("downSampleType"), + + UserName: c.GetString("userName"), + IdcID: c.GetString("idcID"), + } + + res, err := monitorDataLogic.GetMonitorData(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res + +} diff --git a/bmp-operation-api/controllers/monitorProxyController.go b/bmp-operation-api/controllers/monitorProxyController.go new file mode 100644 index 0000000..a81eea2 --- /dev/null +++ b/bmp-operation-api/controllers/monitorProxyController.go @@ -0,0 +1,53 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/monitorProxyLogic" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorProxyController 从monitorproxy服务读取数据,包括agent状态,tag列表等 +type MonitorProxyController struct { + BaseController +} + +// swagger:route GET /monitorProxy/desrcibeAgentStatus monitorProxy desrcibeAgentStatus +// +// DesrcibeAgentStatus 获取agent状态 +// +// Responses: +// 200: desrcibeAgentStatus +// default: ErrorResponse +func (c *MonitorProxyController) DesrcibeAgentStatus() { + req := &request.DesrcibeAgentStatusRequest{ + InstanceId: c.GetString("instanceId"), + } + res, err := monitorProxyLogic.DescribeAgentStatus(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res + +} + +// swagger:route GET /monitorProxy/desrcibeTags monitorProxy desrcibeTags +// +// DesrcibeAgentStatus 获取tag列表 +// +// Responses: +// 200: desrcibeTags +// default: ErrorResponse +func (c *MonitorProxyController) DesrcibeTags() { + req := &request.DesrcibeTagsRequest{ + InstanceID: c.GetString("instanceId"), + TagName: c.GetString("tagName"), + } + res, err := monitorProxyLogic.DescribeDeviceTags(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} diff --git a/bmp-operation-api/controllers/monitorRuleController.go b/bmp-operation-api/controllers/monitorRuleController.go new file mode 100644 index 0000000..f001b41 --- /dev/null +++ b/bmp-operation-api/controllers/monitorRuleController.go @@ -0,0 +1,212 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/monitorRuleLogic" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +// MonitorRuleController 告警规则 +type MonitorRuleController struct { + BaseController +} + +// swagger:route POST /monitorRule/addRule monitorRule addRule +// +// AddRule 添加规则 +// +// Responses: +// 200: addRule +// default: ErrorResponse +func (c *MonitorRuleController) AddRule() { + defer c.CatchException() + c.logPoints.Infof("AddRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.AddRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("AddRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := monitorRuleLogic.AddRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route GET /monitorRule/describeRule monitorRule describeRule +// +// DescribeRule 规则详情 +// +// Responses: +// 200: describeRule +// default: ErrorResponse +func (c *MonitorRuleController) DescribeRule() { + defer c.CatchException() + req := request.DescribeRuleRequest{ + RuleID: c.GetString("ruleId"), + } + res, err := monitorRuleLogic.DescribeRule(c.logPoints, req.RuleID) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = res +} + +// swagger:route GET /monitorRule/describeRules monitorRule describeRules +// +// DescribeRules 规则列表 +// +// Responses: +// 200: describeRules +// default: ErrorResponse +func (c *MonitorRuleController) DescribeRules() { + defer c.CatchException() + + p := util.Pageable{ + PageSize: c.getPageSize(), + PageNumber: c.getPageNumber(), + } + s, _ := c.GetInt("status") + + req := &request.DescribeRulesRequest{ + IsAll: c.GetString("isAll"), + UserName: c.GetString("userName"), + UserId: c.GetString("userId"), + RuleName: c.GetString("ruleName"), + RuleId: c.GetString("ruleId"), + Status: s, + } + + res, err := monitorRuleLogic.DescribeRules(c.logPoints, req, p) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + if c.GetString("exportType") != "" { + fileName, downloadFileName := monitorRuleLogic.ExportRules(c.logPoints, res.Rules) + //c.Ctx.Input.SetData("download", "yes") + c.Ctx.Output.Download(fileName, downloadFileName) + return + } else { + c.Res.Result = res + } +} + +// swagger:route PUT /monitorRule/editRule monitorRule editRule +// +// EditRule 编辑规则 +// +// Responses: +// 200: editRule +// default: ErrorResponse +func (c *MonitorRuleController) EditRule() { + defer c.CatchException() + c.logPoints.Infof("EditRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.EditRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("EditRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := monitorRuleLogic.EditRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route PUT /monitorRule/enableRule monitorRule enableRule +// +// EnableRule 启用规则 +// +// Responses: +// 200: enableRule +// default: ErrorResponse +func (c *MonitorRuleController) EnableRule() { + defer c.CatchException() + c.logPoints.Infof("EnableRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.EnableRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("EnableRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := monitorRuleLogic.EnableRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route PUT /monitorRule/disableRule monitorRule disableRule +// +// DisableRule 禁用规则 +// +// Responses: +// 200: disableRule +// default: ErrorResponse +func (c *MonitorRuleController) DisableRule() { + defer c.CatchException() + c.logPoints.Infof("DisableRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.DisableRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DisableRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := monitorRuleLogic.DisableRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} + +// swagger:route DELETE /monitorRule/deleteRule monitorRule deleteRule +// +// DeleteRule 删除规则 +// +// Responses: +// 200: deleteRule +// default: ErrorResponse +func (c *MonitorRuleController) DeleteRule() { + defer c.CatchException() + c.logPoints.Infof("EnableRule body:%s", string(c.Ctx.Input.RequestBody)) + req := &request.DeleteRuleRequest{} + + if err := json.Unmarshal(c.Ctx.Input.RequestBody, req); err != nil { + c.logPoints.Warn("DeleteRule parse body error:", err.Error()) + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + res, err := monitorRuleLogic.DeleteRule(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.BAD_REQUEST, err.Error(), errorCode.INVALID_ARGUMENT) + return + } + c.Res.Result = response.CommonResponse{ + Success: res, + } +} diff --git a/bmp-operation-api/controllers/resourceController.go b/bmp-operation-api/controllers/resourceController.go new file mode 100644 index 0000000..a918641 --- /dev/null +++ b/bmp-operation-api/controllers/resourceController.go @@ -0,0 +1,38 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/resourceLogic" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + errorCode "git.jd.com/cps-golang/ironic-common/ironic/common/ErrorCode" + httpStatus "git.jd.com/cps-golang/ironic-common/ironic/enums/HttpStatus" +) + +type ResourceController struct { + BaseController +} + +// swagger:route GET /resources resource describeResources +// +// DescribeResources 根据某个字段值精确查询对应的资源列表(如根据imageName查询镜像列表,根据idcName查询机房列表) +// +// Responses: +// 200: describeResources +// default: ErrorResponse +func (c *ResourceController) DescribeResources() { + defer c.CatchException() + req := &requestTypes.QueryResourcesRequest{ + Name: c.GetString("name"), + DeviceType: c.GetString("deviceType"), + ImageName: c.GetString("imageName"), + UserName: c.GetString("userName"), + } + isExist, err := resourceLogic.DescribeResources(c.logPoints, req) + if err != nil { + c.SetErrorResponse(httpStatus.INTERNAL_SERVER_ERROR, err.Error(), errorCode.INTERNAL) + return + } + c.Res.Result = response.CommonResponse{ + Success: isExist, + } +} diff --git a/bmp-operation-api/dao/AdminDao/AdminDao.go b/bmp-operation-api/dao/AdminDao/AdminDao.go new file mode 100644 index 0000000..47538b1 --- /dev/null +++ b/bmp-operation-api/dao/AdminDao/AdminDao.go @@ -0,0 +1,69 @@ +package AdminDao + +import ( + "time" + + log "git.jd.com/cps-golang/log" + + "coding.jd.com/aidc-bmp/bmp-operation-api/dao" +) + +type CpsUser struct { + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + Username string `gorm:"unique;column:username;type:varchar(32);not null" json:"username"` + Password string `gorm:"column:password;type:varchar(64)" json:"password"` + Fullname string `gorm:"column:fullname;type:varchar(64)" json:"fullname"` + Email string `gorm:"column:email;type:varchar(128)" json:"email"` + Mobile string `gorm:"column:mobile;type:varchar(32)" json:"mobile"` + ErpID string `gorm:"column:erp_id;type:varchar(32)" json:"erp_id"` + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` +} + +func (t *CpsUser) TableName() string { + return "cps_user" +} + +// AddImage insert a new Image into database and returns +// last inserted Id on success. +func AddUser(logger *log.Logger, m *CpsUser) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetImageById retrieves Image by Id. Returns error if +// Id doesn't exist +func GetUserById(logger *log.Logger, id int64) (v *CpsUser, err error) { + v = &CpsUser{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + return +} + +func GetUserByName(logger *log.Logger, username string) (v *CpsUser, err error) { + v = &CpsUser{} + err = dao.Where(logger, dao.IronicRdb, "username = ? and is_del = 0", username).Take(v).Error + return +} + +// GetMultiImage retrieves all Image matches certain condition. Returns empty list if +// no records exist + +func GetAllUser(logger *log.Logger, query map[string]interface{}) (ml []*CpsUser, err error) { + + var db = dao.Model(logger, dao.IronicRdb, CpsUser{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// UpdateImage updates Image by Id and returns error if +// the record to be updated doesn't exist +func UpdateUserById(logger *log.Logger, m *CpsUser) (err error) { + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, CpsUser{}).Where("id = ?", m.ID).Updates(m).Error +} diff --git a/bmp-operation-api/dao/baseDao.go b/bmp-operation-api/dao/baseDao.go new file mode 100644 index 0000000..8c09fd4 --- /dev/null +++ b/bmp-operation-api/dao/baseDao.go @@ -0,0 +1,121 @@ +package dao + +import ( + "fmt" + "strings" + + clog "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +var ( + IronicRdb *gorm.DB + IronicWdb *gorm.DB +) + +type gLogger struct { + traceid string +} + +func (g *gLogger) Print(values ...interface{}) { + var ( + level = values[0] + // source = values[1] + ) + logger := clog.New("./log/ironic-console.log") + defer logger.Flush() + logger.SetStableFields([]string{"sql", "args", "cost"}) + logger.Point("logid", g.traceid) + + if level == "sql" { + logger.Point("sql", values[3]) + logger.Point("args", values[4]) + logger.Point("cost", fmt.Sprint(values[2])) + } else { + logger.Point("trace", values) + } +} + +func InitGormDb(conn string) error { + var err error + IronicRdb, err = gorm.Open("mysql", conn) + if err != nil { + return err + } + IronicRdb.LogMode(true) + IronicRdb.DB().SetMaxOpenConns(100) + IronicRdb.DB().SetMaxIdleConns(20) + + IronicWdb, err = gorm.Open("mysql", conn) + if err != nil { + return err + } + IronicWdb.LogMode(true) + IronicWdb.DB().SetMaxOpenConns(100) + IronicWdb.DB().SetMaxIdleConns(20) + + return nil +} + +func GetGormTx(logger *clog.Logger) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := IronicWdb.New() + db.SetLogger(gl) + return db +} + +type NullType byte + +const ( + _ NullType = iota + // IsNull the same as `is null` + IsNull + // IsNotNull the same as `is not null` + IsNotNull +) + +// sql build where +func WhereBuild(g *gorm.DB, query map[string]interface{}) (*gorm.DB, error) { + + for k, v := range query { + ks := strings.Split(k, ".") + if len(ks) > 2 { + fmt.Println(fmt.Errorf("Error in query condition: %s. ", k)) + return g, fmt.Errorf("Error in query condition: %s. ", k) + } + switch len(ks) { + case 1: + g = g.Where(fmt.Sprintf("%s = ?", k), v) + break + case 2: + k = ks[0] + switch ks[1] { + case "=": + g = g.Where(fmt.Sprintf("%s = ?", k), v) + break + case ">", "gt": + g = g.Where(fmt.Sprintf("%s > ?", k), v) + case ">=", "gte": + g = g.Where(fmt.Sprintf("%s >= ?", k), v) + break + case "<", "lt": + g = g.Where(fmt.Sprintf("%s < ?", k), v) + break + case "<=", "lte": + g = g.Where(fmt.Sprintf("%s <= ?", k), v) + break + case "!=", "<>": + g = g.Where(fmt.Sprintf("%s <> ?", k), v) + break + case "in": + g = g.Where(fmt.Sprintf("%s IN (?)", k), v) + break + case "like": + g = g.Where(fmt.Sprintf("%s LIKE ?", k), v) + break + } + break + } + } + return g, nil +} diff --git a/bmp-operation-api/dao/createDao.go b/bmp-operation-api/dao/createDao.go new file mode 100644 index 0000000..944c2f8 --- /dev/null +++ b/bmp-operation-api/dao/createDao.go @@ -0,0 +1,36 @@ +package dao + +import ( + clog "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +// 插入单条记录,v2版本才支持插入多条记录? +//eg. db.Create(logger, rdb, u) +func Create(logger *clog.Logger, gdb *gorm.DB, out interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Create(out) +} + +//插入并获取刚插入数据的自增Id +//eg. db.CreateAndGetId(logger, rdb, u) +func CreateAndGetId(logger *clog.Logger, gdb *gorm.DB, out interface{}) (int64, error) { + // 事务约束,否则并发下可能获取到的是错误的id + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + tx := db.Begin() + if err := tx.Create(out).Error; err != nil { + tx.Rollback() + return 0, err + } + var id []int64 + if err := tx.Raw("select LAST_INSERT_ID() as id").Pluck("id", &id).Error; err != nil { + tx.Rollback() + return 0, err + } + tx.Commit() + return id[0], nil +} diff --git a/bmp-operation-api/dao/deleteDao.go b/bmp-operation-api/dao/deleteDao.go new file mode 100644 index 0000000..43e5850 --- /dev/null +++ b/bmp-operation-api/dao/deleteDao.go @@ -0,0 +1,21 @@ +package dao + +import ( + clog "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +//删除记录 +//eg1.根据模型删除 +/* +food := Food{} +dao.Where(logger, rdb, "id = ?", 2).Take(&food).Delete(&food) +*/ +//eg2.根据Where条件删除数据 +// dao.Where(logger, rdb, "type = ?", 5).Delete(&Food{})//注意这里Delete函数需要传递一个空的模型变量指针 +func Delete(logger *clog.Logger, gdb *gorm.DB, value interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Delete(value, where...) +} diff --git a/bmp-operation-api/dao/queryDao.go b/bmp-operation-api/dao/queryDao.go new file mode 100644 index 0000000..29c4c7a --- /dev/null +++ b/bmp-operation-api/dao/queryDao.go @@ -0,0 +1,129 @@ +package dao + +import ( + clog "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +// SELECT * FROM `foods` LIMIT 1 +//eg. db.Take(logger, rdb, &food) +func Take(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Take(out, where...) +} + +// SELECT * FROM `foods` ORDER BY `foods`.`id` ASC LIMIT 1 +//eg. db.First(logger, rdb, &food) +func First(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.First(out, where...) +} + +// SELECT * FROM `foods` ORDER BY `foods`.`id` DESC LIMIT 1 +//eg. db.Last(logger, rdb, &food) +func Last(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Last(out, where...) +} + +// SELECT * FROM `foods` 可单可复 +//eg. db.Find(logger, rdb, &foods) +func Find(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Find(out, where...) +} + +// // 查询一列值 +//eg. Model(Food{}).Pluck("title", &titles) +// func Pluck(logger *clog.Logger, model interface{}, column string, target interface{}) error { +// //等价于:SELECT title FROM `foods` 提取了title字段,保存到titles变量 +// //这里Model函数是为了绑定一个模型实例,可以从里面提取表名。 +// gl := &gLogger{traceid: logger.GetPoint("logid").(string)} +// db := gdb.New() +// db.SetLogger(gl) +// return gdb.Model(model).Pluck("title", target).Error +// } + +// 设置where条件 +//eg. dao.Where(logger, rdb, "id = ?", 10).Take(&food) +//eg. dao.Where(logger, rdb, "id in (?)", []int{1,2,5,6}).Take(&food) +//eg. dao.Where(logger, rdb, "create_time >= ? and create_time <= ?", "2018-11-06 00:00:00", "2018-11-06 23:59:59").Find(&foods) +//eg. dao.Where(logger, rdb, "title like ?", "%可乐%").Find(&foods) +func Where(logger *clog.Logger, gdb *gorm.DB, query interface{}, args ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Where(query, args...) +} + +// 指定返回的字段 +//eg. dao.Select(logger, rdb, "id,title").Where("id = ?", 1).Take(&food) +//eg. dao.Model(logger, rdb, Food{}).Select("count(*) as total").Pluck("total", &total) +func Select(logger *clog.Logger, gdb *gorm.DB, query interface{}, args ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Select(query, args...) +} + +// 指定绑定的模型,一般和Pluck一起使用 +//eg. dao.Model(logger, rdb, Food{}).Select("count(*) as total").Pluck("total", &total) +func Model(logger *clog.Logger, gdb *gorm.DB, value interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Model(value) +} + +// 指定order +//eg. dao.Order(logger, rdb, "create_time desc").Limit(10).Offset(0).Find(&foods) +//eg. dao.Where(logger, rdb, "create_time >= ?", "2018-11-06 00:00:00").Order("create_time desc").Find(&foods) +func Order(logger *clog.Logger, gdb *gorm.DB, value interface{}, reorder ...bool) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Order(value, reorder...) +} + +// limit +//eg. dao.Order(logger, rdb, "create_time desc").Limit(10).Offset(0).Find(&foods) +//eg. dao.Limit(logger, rdb, 10).Offset(0).Find(&foods) +func Limit(logger *clog.Logger, gdb *gorm.DB, limit interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Limit(limit) +} + +// Offset +//eg. dao.Order(logger, rdb, "create_time desc").Limit(10).Offset(0).Find(&foods) +//eg. dao.Offset(logger, rdb, 10).Find(&foods) +func Offset(logger *clog.Logger, gdb *gorm.DB, limit interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Offset(limit) +} + +//eg. dao.Model(logger, rdb, Food{}).Count(&total) +// COUNT + +//eg. dao.Model(logger, rdb, Food{}).Select("type, count(*) as total").Group("type").Having("total > 0").Scan(&results) +//group by,必须要搭配select一起使用 + +//Raw +//eg. dao.Raw(logger, rdb, sql, "2018-11-06 00:00:00").Scan(&results) +func Raw(logger *clog.Logger, gdb *gorm.DB, sql string, values ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Raw(sql, values...) +} diff --git a/bmp-operation-api/dao/updateDao.go b/bmp-operation-api/dao/updateDao.go new file mode 100644 index 0000000..f5adcba --- /dev/null +++ b/bmp-operation-api/dao/updateDao.go @@ -0,0 +1,53 @@ +package dao + +import ( + clog "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +//更新 根据主键id,更新所有模型字段值。查询->set->save +//eg. dao.Save(logger, rdb, &food) +func Save(logger *clog.Logger, gdb *gorm.DB, value interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Save(value) +} + +//更新单个字段值 +//eg1.更新一条记录(根据主键) dao.Model(logger, rdb, &food).Update("price", 25) +//eg2.更新所有记录 dao.Model(logger, rdb, Food{}).Update("price", 25) +//eg3.根据自定义条件更新记录 dao.Model(logger, rdb, Food{}).Where("create_time > ?", "2018-11-06 20:00:00").Update("price", 25) +func Update(logger *clog.Logger, gdb *gorm.DB, attrs ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Update(attrs...) +} + +//更新多个字段值 +/* +updataFood := Food{ + Stock:120, + Title:"柠檬雪碧", + //Age:0 +} +*/ +//eg1. 通过结构体变量设置更新字段 dao.Model(logger, rdb, &food).Updates(&updataFood) 问题是:这样只会更新updataFood中字段为非默认值的字段,比如updataFood定义时就算加上了Age:0,这个字段也不会被更新成目标0 +//eg2. 根据自定义条件更新记录 dao.Model(logger, rdb, Food{}).Where("price > ?", 10).Updates(&updataFood) 问题同上 +//eg3. 想更新所有字段值,包括零值,就是不想忽略掉空值字段时,使用map类型替代上面的结构体变量 +/* +data := make(map[string]interface{}) +data["stock"] = 0 //零值字段 +data["price"] = 35 +dao.Model(logger, rdb, Food{}).Where("id = ?", 2).Updates(data) +*/ +func Updates(logger *clog.Logger, gdb *gorm.DB, values interface{}, ignoreProtectedAttrs ...bool) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Updates(values, ignoreProtectedAttrs...) +} + +//更新表达式 +//eg. db.Model(&food).Update("stock", gorm.Expr("stock + 1")) 等价于UPDATE `foods` SET `stock` = stock + 1 WHERE `foods`.`id` = '2' diff --git a/bmp-operation-api/docs/.cmd b/bmp-operation-api/docs/.cmd new file mode 100644 index 0000000..21418e6 --- /dev/null +++ b/bmp-operation-api/docs/.cmd @@ -0,0 +1 @@ +rm -rf resources diff --git a/bmp-operation-api/enums/charge_mode.go b/bmp-operation-api/enums/charge_mode.go new file mode 100644 index 0000000..e770402 --- /dev/null +++ b/bmp-operation-api/enums/charge_mode.go @@ -0,0 +1,29 @@ +package enums + +var ChargeMode map[int]string = map[int]string{ //创建订单sdk时候的map + 1: "CONFIG", //按配置 postpaid_by_duration + 2: "FLOW", //用量 postpaid_by_usage + 3: "MONTHLY", //包年包月 prepaid_by_duration + 4: "ONCE", //一次性付费 once +} +var ChargeModeZh map[string]string = map[string]string{ //导出时候用到的。跟前端保持一直 + //"MONTHLY": "包年包月", + //"CONFIG": "按配置", + "prepaid_by_duration": "包年包月", + "postpaid_by_duration": "按配置", +} + +var ChargeModeEn map[string]string = map[string]string{ //导出时候用到的。跟前端保持一直 + //"MONTHLY": "包年包月", + //"CONFIG": "按配置", + "prepaid_by_duration": "Pay By Month", + "postpaid_by_duration": "Pay By Configuration", +} + +//创建实例sdk的map +var ChargeModeInstance map[int]string = map[int]string{ + 1: "postpaid_by_duration", //按配置 postpaid_by_duration + 2: "postpaid_by_usage", //用量 postpaid_by_usage + 3: "prepaid_by_duration", //包年包月 prepaid_by_duration + 4: "once", //一次性付费 once +} diff --git a/bmp-operation-api/enums/charge_unit.go b/bmp-operation-api/enums/charge_unit.go new file mode 100644 index 0000000..f86232f --- /dev/null +++ b/bmp-operation-api/enums/charge_unit.go @@ -0,0 +1,14 @@ +package enums + +var ChargeUnit map[int]string = map[int]string{ + 1: "HOUR", //hour + 2: "DAY", //day + 3: "MONTH", //month + 4: "YEAR", //year +} +var ChargeUnitInstance map[int]string = map[int]string{ + 1: "hour", //hour + 2: "day", //day + 3: "month", //month + 4: "year", //year +} diff --git a/bmp-operation-api/enums/item_type.go b/bmp-operation-api/enums/item_type.go new file mode 100644 index 0000000..9ad7b5f --- /dev/null +++ b/bmp-operation-api/enums/item_type.go @@ -0,0 +1,6 @@ +package enums + +var ItemType map[int]string = map[int]string{ + 1: "COMMON_ITEM", //普通商品 + 2: "ACTIVITY_ITEM", //活动商品 +} diff --git a/bmp-operation-api/enums/network_operatior.go b/bmp-operation-api/enums/network_operatior.go new file mode 100644 index 0000000..b5e6972 --- /dev/null +++ b/bmp-operation-api/enums/network_operatior.go @@ -0,0 +1,8 @@ +package enums + +var NetworkOperator map[int]string = map[int]string{ + 0: "NULL", + 1: "NON_BGP", //non-BGP + 2: "BGP", //BGP + 3: "UN", //联通 +} diff --git a/bmp-operation-api/enums/order_type.go b/bmp-operation-api/enums/order_type.go new file mode 100644 index 0000000..d682a3f --- /dev/null +++ b/bmp-operation-api/enums/order_type.go @@ -0,0 +1,7 @@ +package enums + +var OrderType map[int]string = map[int]string{ + 1: "NEW", //新购 + 2: "RENEW", //续费 + 3: "RESIZE_FORMULA", //配置变更 +} diff --git a/bmp-operation-api/enums/site_type.go b/bmp-operation-api/enums/site_type.go new file mode 100644 index 0000000..0014dec --- /dev/null +++ b/bmp-operation-api/enums/site_type.go @@ -0,0 +1,7 @@ +package enums + +var SiteType map[int]string = map[int]string{ + 0: "MAIN_SITE", //主站 - 现在的国内站 + 1: "INTERNATIONAL_SITE", //美国站 - 现在的国际站 + 10: "SUQIAN_DEDICATED_CLOUD", //宿迁专有云 +} diff --git a/bmp-operation-api/errors/code.go b/bmp-operation-api/errors/code.go new file mode 100644 index 0000000..046cf23 --- /dev/null +++ b/bmp-operation-api/errors/code.go @@ -0,0 +1,107 @@ +package errors + +const ( + API_OK = 10000 + API_ARGUMENTS_ERROR = 20040 + API_NO_ARGUMENTS = 20041 + API_DB_ERROR = 20050 + API_UNKOWN_ERROR = 20051 + API_INTERNAL_ERROR = 20052 + API_CALL_SERVICE_ERROR = 20053 + API_RESOURCE_NOT_FOUND = 20060 + API_RESOURCE_HAS_EXISTED = 20061 + API_RESOURCE_OCCUPIED = 20062 + API_RESOURCE_OUT_OF_RANGE = 20063 + API_RESOURCE_NOT_MATCH = 20064 + API_LOGIN_ERROR = 20065 + API_UPLOAD_FILE_ERROR = 20066 + API_RESOURCE_UNAVAILABLE = 20067 +) + +type codeMsg struct { + HttpCode int + Message string +} + +var CodeMap = make(map[int]*codeMsg) + +func init() { + CodeMap = map[int]*codeMsg{ + API_OK: { + 200, + "OK", + }, + API_ARGUMENTS_ERROR: { + 400, + "参数错误", + }, + API_NO_ARGUMENTS: { + 400, + "参数缺失", + }, + API_DB_ERROR: { + 500, + "数据库错误", + }, + API_UNKOWN_ERROR: { + 500, + "未知错误", + }, + API_INTERNAL_ERROR: { + 500, + "内部错误", + }, + API_CALL_SERVICE_ERROR: { + 500, + "调用外部服务错误", + }, + API_RESOURCE_NOT_FOUND: { + 400, + "资源未找到", + }, + API_RESOURCE_HAS_EXISTED: { + 400, + "资源已存在", + }, + API_RESOURCE_OCCUPIED: { + 400, + "资源已被占用", + }, + API_RESOURCE_OUT_OF_RANGE: { + 400, + "资源数量超出限制", + }, + API_RESOURCE_NOT_MATCH: { + 400, + "资源不匹配", + }, + API_LOGIN_ERROR: { + 401, + "请先进行单点登录", + }, + API_UPLOAD_FILE_ERROR: { + 400, + "上传文件有误", + }, + API_RESOURCE_UNAVAILABLE: { + 400, + "资源不可用", + }, + } +} + +func GetCodeMsg(errCode int) string { + if msg, ok := CodeMap[errCode]; ok { + return msg.Message + } else { + return CodeMap[API_UNKOWN_ERROR].Message + } +} + +func GetHttpCode(errCode int) int { + if msg, ok := CodeMap[errCode]; ok { + return msg.HttpCode + } else { + return CodeMap[API_UNKOWN_ERROR].HttpCode + } +} diff --git a/bmp-operation-api/errors/errors.go b/bmp-operation-api/errors/errors.go new file mode 100644 index 0000000..0269e41 --- /dev/null +++ b/bmp-operation-api/errors/errors.go @@ -0,0 +1,49 @@ +package errors + +import "fmt" + +type Error interface { + error + GetErrorCode() int + GetMessage() string + GetOriginError() error +} + +type CommonError struct { + errorCode int + message string + originError error +} + +func NewCommonError(errorCode int, message string, originErr error) Error { + return &CommonError{ + errorCode: errorCode, + message: message, + originError: originErr, + } +} + +func (e *CommonError) Error() string { + var msg string + if e.GetMessage() == "" { + msg = fmt.Sprintf("%s", GetCodeMsg(e.GetErrorCode())) + } else { + msg = fmt.Sprintf("%s:%s", GetCodeMsg(e.GetErrorCode()), e.GetMessage()) + } + if e.GetOriginError() != nil { + return msg + " caused by: " + e.GetOriginError().Error() + } + return msg +} + +func (e *CommonError) GetErrorCode() int { + return e.errorCode +} + +func (e *CommonError) GetOriginError() error { + return e.originError +} + +func (e *CommonError) GetMessage() string { + return e.message +} diff --git a/bmp-operation-api/go.mod b/bmp-operation-api/go.mod new file mode 100644 index 0000000..cc3d74e --- /dev/null +++ b/bmp-operation-api/go.mod @@ -0,0 +1,79 @@ +module coding.jd.com/aidc-bmp/bmp-operation-api + +go 1.17 + +require github.com/beego/beego/v2 v2.0.1 + +require ( + coding.jd.com/aidc-bmp/bmp-openapi-sdk v0.0.0-00010101000000-000000000000 + github.com/gorilla/websocket v1.5.1 +) + +require ( + github.com/PuerkitoBio/purell v1.1.1 // indirect + github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect + github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.1.1 // indirect + github.com/go-openapi/analysis v0.21.2 // indirect + github.com/go-openapi/errors v0.20.3 // indirect + github.com/go-openapi/jsonpointer v0.19.5 // indirect + github.com/go-openapi/jsonreference v0.19.6 // indirect + github.com/go-openapi/loads v0.21.1 // indirect + github.com/go-openapi/spec v0.20.4 // indirect + github.com/go-openapi/swag v0.22.3 // indirect + github.com/go-openapi/validate v0.21.0 // indirect + github.com/go-playground/locales v0.13.0 // indirect + github.com/go-playground/universal-translator v0.17.0 // indirect + github.com/go-redis/redis/v7 v7.4.0 // indirect + github.com/golang/protobuf v1.4.2 // indirect + github.com/hashicorp/golang-lru v0.5.4 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/leodido/go-urn v1.2.0 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect + github.com/mitchellh/mapstructure v1.4.3 // indirect + github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect + github.com/oklog/ulid v1.3.1 // indirect + github.com/opentracing/opentracing-go v1.2.0 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/prometheus/client_golang v1.7.0 // indirect + github.com/prometheus/client_model v0.2.0 // indirect + github.com/prometheus/common v0.10.0 // indirect + github.com/prometheus/procfs v0.1.3 // indirect + github.com/richardlehane/mscfb v1.0.3 // indirect + github.com/richardlehane/msoleps v1.0.1 // indirect + github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect + github.com/xuri/efp v0.0.0-20210322160811-ab561f5b45e3 // indirect + go.mongodb.org/mongo-driver v1.10.0 // indirect + golang.org/x/mod v0.8.0 // indirect + golang.org/x/net v0.17.0 // indirect + golang.org/x/sys v0.13.0 // indirect + golang.org/x/text v0.13.0 // indirect + golang.org/x/tools v0.6.0 // indirect + google.golang.org/protobuf v1.23.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) + +require ( + git.jd.com/cps-golang/ironic-common v0.0.0-00010101000000-000000000000 + git.jd.com/cps-golang/log v0.0.0-00010101000000-000000000000 + github.com/go-openapi/runtime v0.24.2 + github.com/go-openapi/strfmt v0.21.3 + github.com/go-playground/validator/v10 v10.4.1 + github.com/go-redis/redis v6.14.2+incompatible + github.com/go-sql-driver/mysql v1.5.0 + github.com/gofrs/uuid v4.2.0+incompatible + github.com/google/go-cmp v0.5.5 // indirect + github.com/jinzhu/gorm v1.9.16 + github.com/xuri/excelize/v2 v2.5.0 + golang.org/x/crypto v0.14.0 +) + +replace git.jd.com/cps-golang/log => ./bmp_vendor/log + +replace git.jd.com/cps-golang/ironic-common => ./bmp_vendor/ironic-common + +replace coding.jd.com/aidc-bmp/bmp-openapi-sdk => ./bmp_vendor/bmp-openapi-sdk diff --git a/bmp-operation-api/go.sum b/bmp-operation-api/go.sum new file mode 100644 index 0000000..3c0a055 --- /dev/null +++ b/bmp-operation-api/go.sum @@ -0,0 +1,488 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc= +github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= +github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= +github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk= +github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y= +github.com/asaskevich/govalidator v0.0.0-20200907205600-7a23bdc65eef/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d h1:Byv0BzEl3/e6D5CLfI0j/7hiIEtvGVFPCZ7Ei2oq8iQ= +github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/beego/beego/v2 v2.0.1 h1:07a7Z0Ok5vbqyqh+q53sDPl9LdhKh0ZDy3gbyGrhFnE= +github.com/beego/beego/v2 v2.0.1/go.mod h1:8zyHi1FnWO1mZLwTn62aKRIZF/aIKvkCBB2JYs+eqQI= +github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ= +github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60= +github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= +github.com/coreos/etcd v3.3.25+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U= +github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= +github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd h1:83Wprp6ROGeiHFAP8WJdI2RoxALQYgdllERc3N5N2DM= +github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= +github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= +github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk= +github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y= +github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-openapi/analysis v0.21.2 h1:hXFrOYFHUAMQdu6zwAiKKJHJQ8kqZs1ux/ru1P1wLJU= +github.com/go-openapi/analysis v0.21.2/go.mod h1:HZwRk4RRisyG8vx2Oe6aqeSQcoxRp47Xkp3+K6q+LdY= +github.com/go-openapi/errors v0.19.8/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= +github.com/go-openapi/errors v0.19.9/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= +github.com/go-openapi/errors v0.20.2/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= +github.com/go-openapi/errors v0.20.3 h1:rz6kiC84sqNQoqrtulzaL/VERgkoCyB6WdEkc2ujzUc= +github.com/go-openapi/errors v0.20.3/go.mod h1:Z3FlZ4I8jEGxjUK+bugx3on2mIAk4txuAOhlsB1FSgk= +github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= +github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs= +github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= +github.com/go-openapi/loads v0.21.1 h1:Wb3nVZpdEzDTcly8S4HMkey6fjARRzb7iEaySimlDW0= +github.com/go-openapi/loads v0.21.1/go.mod h1:/DtAMXXneXFjbQMGEtbamCZb+4x7eGwkvZCvBmwUG+g= +github.com/go-openapi/runtime v0.24.2 h1:yX9HMGQbz32M87ECaAhGpJjBmErO3QLcgdZj9BzGx7c= +github.com/go-openapi/runtime v0.24.2/go.mod h1:AKurw9fNre+h3ELZfk6ILsfvPN+bvvlaU/M9q/r9hpk= +github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M= +github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= +github.com/go-openapi/strfmt v0.21.0/go.mod h1:ZRQ409bWMj+SOgXofQAGTIo2Ebu72Gs+WaRADcS5iNg= +github.com/go-openapi/strfmt v0.21.1/go.mod h1:I/XVKeLc5+MM5oPNN7P6urMOpuLXEcNrCX/rPGuWb0k= +github.com/go-openapi/strfmt v0.21.2/go.mod h1:I/XVKeLc5+MM5oPNN7P6urMOpuLXEcNrCX/rPGuWb0k= +github.com/go-openapi/strfmt v0.21.3 h1:xwhj5X6CjXEZZHMWy1zKJxvW9AfHC9pkyUjLvHtKG7o= +github.com/go-openapi/strfmt v0.21.3/go.mod h1:k+RzNO0Da+k3FrrynSNN8F7n/peCmQQqbbXjtDfvmGg= +github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= +github.com/go-openapi/swag v0.21.1/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= +github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g= +github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= +github.com/go-openapi/validate v0.21.0 h1:+Wqk39yKOhfpLqNLEC0/eViCkzM5FVXVqrvt526+wcI= +github.com/go-openapi/validate v0.21.0/go.mod h1:rjnrwK57VJ7A8xqfpAOEKRH8yQSGUriMu5/zuPSQ1hg= +github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= +github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= +github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= +github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= +github.com/go-redis/redis v6.14.2+incompatible h1:UE9pLhzmWf+xHNmZsoccjXosPicuiNaInPgym8nzfg0= +github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis/v7 v7.4.0 h1:7obg6wUoj05T0EpY0o8B59S9w5yeMWql7sw2kwNW1x4= +github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= +github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4= +github.com/gobuffalo/attrs v0.0.0-20190224210810-a9411de4debd/go.mod h1:4duuawTqi2wkkpB4ePgWMaai6/Kc6WEz83bhFwpHzj0= +github.com/gobuffalo/depgen v0.0.0-20190329151759-d478694a28d3/go.mod h1:3STtPUQYuzV0gBVOY3vy6CfMm/ljR4pABfrTeHNLHUY= +github.com/gobuffalo/depgen v0.1.0/go.mod h1:+ifsuy7fhi15RWncXQQKjWS9JPkdah5sZvtHc2RXGlg= +github.com/gobuffalo/envy v1.6.15/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI= +github.com/gobuffalo/envy v1.7.0/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI= +github.com/gobuffalo/flect v0.1.0/go.mod h1:d2ehjJqGOH/Kjqcoz+F7jHTBbmDb38yXA598Hb50EGs= +github.com/gobuffalo/flect v0.1.1/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI= +github.com/gobuffalo/flect v0.1.3/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI= +github.com/gobuffalo/genny v0.0.0-20190329151137-27723ad26ef9/go.mod h1:rWs4Z12d1Zbf19rlsn0nurr75KqhYp52EAGGxTbBhNk= +github.com/gobuffalo/genny v0.0.0-20190403191548-3ca520ef0d9e/go.mod h1:80lIj3kVJWwOrXWWMRzzdhW3DsrdjILVil/SFKBzF28= +github.com/gobuffalo/genny v0.1.0/go.mod h1:XidbUqzak3lHdS//TPu2OgiFB+51Ur5f7CSnXZ/JDvo= +github.com/gobuffalo/genny v0.1.1/go.mod h1:5TExbEyY48pfunL4QSXxlDOmdsD44RRq4mVZ0Ex28Xk= +github.com/gobuffalo/gitgen v0.0.0-20190315122116-cc086187d211/go.mod h1:vEHJk/E9DmhejeLeNt7UVvlSGv3ziL+djtTr3yyzcOw= +github.com/gobuffalo/gogen v0.0.0-20190315121717-8f38393713f5/go.mod h1:V9QVDIxsgKNZs6L2IYiGR8datgMhB577vzTDqypH360= +github.com/gobuffalo/gogen v0.1.0/go.mod h1:8NTelM5qd8RZ15VjQTFkAW6qOMx5wBbW4dSCS3BY8gg= +github.com/gobuffalo/gogen v0.1.1/go.mod h1:y8iBtmHmGc4qa3urIyo1shvOD8JftTtfcKi+71xfDNE= +github.com/gobuffalo/logger v0.0.0-20190315122211-86e12af44bc2/go.mod h1:QdxcLw541hSGtBnhUc4gaNIXRjiDppFGaDqzbrBd3v8= +github.com/gobuffalo/mapi v1.0.1/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc= +github.com/gobuffalo/mapi v1.0.2/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc= +github.com/gobuffalo/packd v0.0.0-20190315124812-a385830c7fc0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4= +github.com/gobuffalo/packd v0.1.0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4= +github.com/gobuffalo/packr/v2 v2.0.9/go.mod h1:emmyGweYTm6Kdper+iywB6YK5YzuKchGtJQZ0Odn4pQ= +github.com/gobuffalo/packr/v2 v2.2.0/go.mod h1:CaAwI0GPIAv+5wKLtv8Afwl+Cm78K/I/VCm/3ptBN+0= +github.com/gobuffalo/syncx v0.0.0-20190224160051-33c29581e754/go.mod h1:HhnNqWY95UYwwW3uSASeV7vtgYkT2t16hJgV3AEPUpw= +github.com/gofrs/uuid v4.2.0+incompatible h1:yyYWMnhkhrKwwr8gAOcOCYxOOscHgDS9yZgBrnJfGa0= +github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY= +github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o= +github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.0.1 h1:HjfetcXq097iXP0uoPCdnM4Efp5/9MsM0/M+XOTeR3M= +github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/karrick/godirwalk v1.8.0/go.mod h1:H5KPZjojv4lE+QYImBI8xVtrBRgYrIVsaRPx4tDPEn4= +github.com/karrick/godirwalk v1.10.3/go.mod h1:RoGL9dQei4vP9ilrpETWE8CLOZ1kiN0LhBygSwrAsHA= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDuKuq+uX4v1fulaMbA/7ZLLhjc85h7chZGBCQ= +github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= +github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.1.1 h1:sJZmqHoEaY7f+NPP8pgLB/WxulyR3fewgCM2qaSlBb4= +github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/markbates/oncer v0.0.0-20181203154359-bf2de49a0be2/go.mod h1:Ld9puTsIW75CHf65OeIOkyKbteujpZVXDpWK6YGZbxE= +github.com/markbates/safe v1.0.1/go.mod h1:nAqgmRi7cY2nqMc92/bSEeQA+R4OheNU2T1kNSCBdG0= +github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus= +github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U= +github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/mapstructure v1.4.3 h1:OVowDSCllw/YjdLkam3/sm7wEtOy59d8ndGgCcyj8cs= +github.com/mitchellh/mapstructure v1.4.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= +github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= +github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.0 h1:Iw5WCbBcaAAd0fpRb1c9r5YCylv4XDoCSigm1zLevwU= +github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.7.0/go.mod h1:vwGMzjaWMwyfHwgIBhI2YUM4fB6nL6lVAvS1LBMMhTE= +github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= +github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.7.0 h1:wCi7urQOGBsYcQROHqpUUX4ct84xp40t9R9JX0FuA/U= +github.com/prometheus/client_golang v1.7.0/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.10.0 h1:RyRA7RzGXQZiW+tGMr7sxa85G1z0yOpM1qq5c8lNawc= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.1.3 h1:F0+tqvhOksq22sc6iCHF5WGlWjdwj92p0udFh1VFBS8= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/richardlehane/mscfb v1.0.3 h1:rD8TBkYWkObWO0oLDFCbwMeZ4KoalxQy+QgniCj3nKI= +github.com/richardlehane/mscfb v1.0.3/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk= +github.com/richardlehane/msoleps v1.0.1 h1:RfrALnSNXzmXLbGct/P2b4xkFz4e8Gmj/0Vj9M9xC1o= +github.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg= +github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= +github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= +github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s= +github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= +github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= +github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= +github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs= +github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g= +github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM= +github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8= +github.com/xuri/efp v0.0.0-20210322160811-ab561f5b45e3 h1:EpI0bqf/eX9SdZDwlMmahKM+CDBgNbsXMhsN28XrM8o= +github.com/xuri/efp v0.0.0-20210322160811-ab561f5b45e3/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI= +github.com/xuri/excelize/v2 v2.5.0 h1:nDDVfX0qaDuGjAvb+5zTd0Bxxoqa1Ffv9B4kiE23PTM= +github.com/xuri/excelize/v2 v2.5.0/go.mod h1:rSu0C3papjzxQA3sdK8cU544TebhrPUoTOaGPIh0Q1A= +github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= +go.etcd.io/etcd v3.3.25+incompatible/go.mod h1:yaeTdrJi5lOmYerz05bd8+V7KubZs8YSFZfzsF9A6aI= +go.mongodb.org/mongo-driver v1.7.3/go.mod h1:NqaYOwnXWr5Pm7AOpO5QFxKJ503nbMse/R79oO62zWg= +go.mongodb.org/mongo-driver v1.7.5/go.mod h1:VXEWRZ6URJIkUq2SCAyapmhH0ZLRBP+FT4xhp5Zvxng= +go.mongodb.org/mongo-driver v1.8.3/go.mod h1:0sQWfOeY63QTntERDJJ/0SuKK0T1uVSgKCuAROlKEPY= +go.mongodb.org/mongo-driver v1.10.0 h1:UtV6N5k14upNp4LTduX0QCufG124fSu25Wz9tu94GLg= +go.mongodb.org/mongo-driver v1.10.0/go.mod h1:wsihk0Kdgv8Kqu1Anit4sfK+22vSFbUrAVEYRhCXrA8= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190422162423-af44ce270edf/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= +golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb h1:fqpd0EBDzlHRCjiphRR5Zo/RSWWQlWv34418dnEixWk= +golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= +golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= +golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190412183630-56d357773e84/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190419153524-e8e3143a4f4a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190531175056-4c3a928424d2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.13.0 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190329151228-23e29df326fe/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190416151739-9c9e1878f421/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190420181800-aa740d480789/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200605160147-a5ece683394c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.5/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= diff --git a/bmp-operation-api/log/.cmd b/bmp-operation-api/log/.cmd new file mode 100644 index 0000000..8a80e60 --- /dev/null +++ b/bmp-operation-api/log/.cmd @@ -0,0 +1 @@ +rm ironic-console.log.DEBUG.2022110315.time ironic-console.log.DEBUG.2022110914.time ironic-console.log.DEBUG.2022-11-18 ironic-console.log.INFO.2022110315.time ironic-console.log.INFO.2022110914.time ironic-console.log.INFO.2022-11-18 ironic-console.log.WARN.2022110315.time ironic-console.log.WARN.2022-11-18 diff --git a/bmp-operation-api/log/console.log b/bmp-operation-api/log/console.log new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/bmp-operation-api/log/console.log @@ -0,0 +1 @@ + diff --git a/bmp-operation-api/logic/ApikeyLogic/ApikeyLogic.go b/bmp-operation-api/logic/ApikeyLogic/ApikeyLogic.go new file mode 100644 index 0000000..ff429fc --- /dev/null +++ b/bmp-operation-api/logic/ApikeyLogic/ApikeyLogic.go @@ -0,0 +1,88 @@ +package ApikeyLogic + +import ( + "errors" + + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + + sdkApikeyParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/api_key" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" +) + +func CreateApikey(logger *log.Logger, param *sdkModels.CreateApikeyRequest) (string, error) { + + logid := logger.GetPoint("logid").(string) + + req := sdkApikeyParameters.NewCreateUserApikeyParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithBody(param) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("CreateApikey openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.APIKey.CreateUserApikey(req, nil) + logger.Info("CreateApikey openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("CreateApikey openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return "", err + } + return "", errors.New(respErr.Message) + } + return *responseApi.Payload.Result.ApikeyID, nil + +} + +func DeleteApikey(logger *log.Logger, apikeyId string) error { + logid := logger.GetPoint("logid").(string) + req := sdkApikeyParameters.NewDeleteUserApikeyParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithApikeyID(apikeyId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("DeleteApikey openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.APIKey.DeleteUserApikey(req, nil) + logger.Info("DeleteApikey openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DeleteApikey openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return err + } + return errors.New(respErr.Message) + } + return nil +} + +func GetApikeyList(logger *log.Logger, param requestTypes.GetApikeyListRequest) (*sdkModels.ApikeyList, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkApikeyParameters.NewDescribeUserAPIKeysParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithPageNumber(¶m.PageNumber) + req.WithPageSize(¶m.PageSize) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("GetApikeyList openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.APIKey.DescribeUserAPIKeys(req, nil) + logger.Info("GetApikeyList openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("GetApikeyList openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + return responseApi.Payload.Result, nil + +} diff --git a/bmp-operation-api/logic/AuditLogLogic/AuditLogLogic.go b/bmp-operation-api/logic/AuditLogLogic/AuditLogLogic.go new file mode 100644 index 0000000..91ba823 --- /dev/null +++ b/bmp-operation-api/logic/AuditLogLogic/AuditLogLogic.go @@ -0,0 +1,154 @@ +package AuditLogLogic + +import ( + "errors" + "math/rand" + "strconv" + "time" + + sdkAuditLogParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/audit_log" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/excel" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + "git.jd.com/cps-golang/ironic-common/exception" + + log "git.jd.com/cps-golang/log" +) + +func QueryAuditLogs(logger *log.Logger, param *requestTypes.DescribeAuditLogsRequest) (*response.AuditLogsList, error) { + // language := logger.GetPoint("language").(string) + logid := logger.GetPoint("logid").(string) + request := sdkAuditLogParameters.NewDescribeAuditLogsParams() + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithSn(¶m.Sn) + + request.WithPageNumber(¶m.PageNumber) + request.WithPageSize(¶m.PageSize) + if param.Operation != "" { + request.WithOperation(¶m.Operation) + } + if param.Result != "" { + request.WithResult(¶m.Result) + } + if param.UserName != "" { + request.WithUserName(¶m.UserName) + } + if param.StartTime != 0 { + request.WithStartTime(¶m.StartTime) + } + if param.EndTime != 0 { + request.WithEndTime(¶m.EndTime) + } + + if param.ExportType != "" || param.IsAll == "1" { + isAll := "1" + request.IsAll = &isAll + } + + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + logger.Info("DescribeAuditLogs openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.AuditLog.DescribeAuditLogs(request, nil) + logger.Info("DescribeAuditLogs openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeAuditLogs openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + resp := &response.AuditLogsList{ + AuditLogs: responseApi.Payload.Result.AuditLogs, + PageNumber: responseApi.Payload.Result.PageNumber, + PageSize: responseApi.Payload.Result.PageSize, + TotalCount: responseApi.Payload.Result.TotalCount, + } + + return resp, nil + +} + +var resultMapEn map[string]string = map[string]string{ + "success": "Operation Success", + "fail": "Operation Fail", + "doing": "Doing", +} + +var resultMapZh map[string]string = map[string]string{ + "success": "操作成功", + "fail": "操作失败", + "doing": "操作中", +} + +func ExportAuditLogs(logger *log.Logger, result []*models.AuditLog) (fileName, downLoadFileName string) { + + language := logger.GetPoint("language").(string) + + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + + for _, data := range result { + var result string = resultMapZh[data.Result] + if language == "en_US" { + result = resultMapEn[data.Result] + } + sheetData = append(sheetData, []string{ + data.LogID, + data.OperationName, + data.UserName, + time.Unix(data.OperateTime, 0).Format("2006-01-02 15:04:05"), + result, + data.FailReason, + }) + } + exportHeader := BaseLogic.ExportAuditLogsHeader + if language == "en_US" { + exportHeader = BaseLogic.ExportAuditLogsHeaderEn + } + if err := e.SetSheetData("Sheet1", exportHeader, sheetData); err != nil { + panic(exception.Exception{Msg: "新建excel失败", Status: BaseLogic.ERROR_CODE}) + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + downloadFileName := "auditlogs_list_" + time.Now().Format(BaseLogic.FormatDate) + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" //生成100000到100000+900000之间的随机数,左闭右开 + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Info("保存excel到本地失败" + err.Error()) + panic(exception.Exception{Msg: "保存excel到本地失败", Status: BaseLogic.ERROR_CODE}) + } + return fileName, downloadFileName +} + +func DescribeAuditLogsTypes(logger *log.Logger) ([]*models.AuditLogsType, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkAuditLogParameters.NewDescribeAuditLogTypesParams() + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + logger.Info("DescribeAuditLogTypes openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.AuditLog.DescribeAuditLogTypes(request, nil) + logger.Info("DescribeAuditLogTypes openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeAuditLogTypes openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + return responseApi.Payload.Result, nil +} diff --git a/bmp-operation-api/logic/BaseLogic/BaseLogic.go b/bmp-operation-api/logic/BaseLogic/BaseLogic.go new file mode 100644 index 0000000..37e5539 --- /dev/null +++ b/bmp-operation-api/logic/BaseLogic/BaseLogic.go @@ -0,0 +1,1023 @@ +package BaseLogic + +const ( + SUCCESS_CODE_OPENAPI = 0 //openapi返回的code,成功返回0,如果不是0,说明有错误,需要抛出错误信息 + ERROR_CODE = 400 + EOPEN_CODE = 500 + ERROR_REDIS_CODE = 401 + ERROR_MYSQL_CODE = 402 + + LOCAL_FILE_PATH = "./log/batch/" + UPLOAD_FILE_FORMAT_ERROR = "20201" + UPLOAD_FILE_SIZE_ERROR = "20202" + UPLOAD_FILE_BASE64 = "20203" + UPLOAD_FILE_NOT_BASE64 = "20204" + + //uc的调用路径配置 + + USERCENTER_GET_PRIVILEGENEW = "/usercenter/getPrivilegeNew" + ORDER_SUBMITRENEW = "/operate/submitRenew" + //以下错误码返给前端特定的错误提示,并且支持国际化 + ERROR_NO = 400001 //通用返回错误码 + ERROR_NO_INSTANCE_NOT_FOUND = "400002" + ERROR_NO_STRING_TO_STRING = 400003 + + COMMON = "common" //内置镜像 + USER_DEFINED = "user_defined" //自定义 + + EN_US = "en_US" + CN_ZH = "zh_CN" +) + +var ( + code int + chMessage string + enMessage string + status string +) +var ( + FileError = map[string]string{ + UPLOAD_FILE_FORMAT_ERROR: "uploadFileFormatError", + UPLOAD_FILE_SIZE_ERROR: "uploadFileSizeError", + UPLOAD_FILE_BASE64: "uploadFileBase64", + UPLOAD_FILE_NOT_BASE64: "uploadFileNotBase64", + } + FormatTime = "2006-01-02 15:04:05" + FormatDate = "2006-01-02" + MountPoints = map[string]map[string][]string{ + "points": map[string][]string{ + "data": []string{"/var", "/export", "/data0"}, + "system": []string{"/", "/boot", "swap", "/var", "/export", "/data0"}, + }, + } + OSFileSystemFormats = map[string][]string{ + "formats": []string{"XFS", "EXT3", "EXT4", "SWAP"}, + } + Cpulist = []string{ + "Intel,E5-2620V4,2,8,2.1", + "Intel,E5-2650V4,2,12,2.2", + "Intel,E5-2683V4,2,16,2.1", + "Intel,Silver 4116,2,12,2.1", + "Intel,Silver 4210,2,10,2.2", + "Intel,Gold 5218,2,16,2.3", + "Intel,Gold 6146,2,12,3.2", + + "Intel,Gold 6148,2,20,2.4", + "Intel,GOLD 6267,2,24,2.6", + "Intel,Platinum 8338,2,32,2.6", + "AMD,EPYC-7H12,2,64,2.6", + "AMD,EPYC-7642,2,48,2.3", + + "Ampere®,Altra® Q80-30,2,80,3.0", + "Kunpeng,920-7260,2,64,2.60", + } + Memlist = []string{ + "128 16 8 DDR3 1600", + "192 16 12 DDR4 2400", + "256 32 8 DDR4 2666", + "384 32 12 DDR4 2933", + "512 32 16 DDR4 2933", + "768 64 12 DDR4 3200", + "1024 64 16 DDR4 3200", + } + + HeaderList = map[string]map[string]map[string]map[string]bool{ + //镜像自定义列表 + "imageList": { + "customInfo": { + "imageName": { + "selected": true, //默认选中 + "required": true, //true代表灰色按钮,直接就是选中,不可更改选中状态,默认就是选中 + }, + "imageId": { + "selected": true, //默认选中 + "required": false, //true代表灰色按钮,直接就是选中,不可更改选中状态,默认就是选中 + }, + "source": { //内置镜像 + "selected": true, + "required": false, + }, + "architecture": { //体系架构 + "selected": true, + "required": false, + }, + "osType": { + "selected": true, + "required": false, + }, + "osVersion": { + "selected": true, + "required": false, + }, + "systemPartition": { + "required": false, + "selected": true, + }, + "description": { + "selected": true, + "required": false, + }, + "deviceTypeNum": { + "selected": true, + "required": false, + }, + "createdTime": { + "selected": true, + "required": false, + }, + "operate": { + "selected": true, + "required": true, + }, + "bootMode": { + "required": false, + "selected": true, + }, + "format": { + "required": false, + "selected": true, + }, + }, + }, + //设备列自定义表头 + "deviceList": { + "customInfo": { + "sn": { + "selected": true, + "required": true, + }, + "deviceTypeName": { // 机型 + "selected": true, + "required": false, + }, + "architecture": { // 体系架构 + "selected": true, + "required": false, + }, + "description": { // 描述 + "selected": true, + "required": false, + }, + "deviceSeries": { // 机型类型 + "selected": true, + "required": false, + }, + + "manageStatusName": { // 管理状态 + "selected": true, + "required": false, + }, + "idcName": { //机房名称 + "selected": true, + "required": false, + }, + "cabinet": { // 机柜编码 + "selected": true, + "required": false, + }, + "uPosition": { // 所在U位 + "selected": true, + "required": false, + }, + "brand": { // 品牌 + "selected": true, + "required": false, + }, + + "model": { // 型号 + "selected": true, + "required": false, + }, + "imageName": { // 实例镜像 + "selected": true, + "required": false, + }, + "instanceName": { // 实例名称 + "selected": true, + "required": false, + }, + "instanceId": { // 实例ID + "selected": true, + "required": false, + }, + "instanceStatus": { // 实例状态 + "selected": true, + "required": false, + }, + "instanceLockedStatus": { // 实例锁定状态 + "selected": true, + "required": false, + }, + + "instanceOwer": { // 实例属主 + "selected": true, + "required": false, + }, + "cpuInfo": { // CPU 英特尔 I7 (10*8 物理核, 2.5GHz) + "selected": true, + "required": false, + }, + "memInfo": { // 内存 256GB DDR4 2933MHz + "selected": true, + "required": false, + }, + "svInfo": { // 系统盘 2880GB (240GB SAS SSD*12,RAID1) + "selected": true, + "required": false, + }, + "dvInfo": { // 数据盘 10GB (1GB SATA SSD*10,RAID1) + "selected": true, + "required": false, + }, + + "gpuInfo": { // GPU INVIDA I8*10 + "selected": true, + "required": false, + }, + "switchIp1": { // 网口1交换机IP + "selected": true, + "required": false, + }, + "switchIp2": { // 网口2交换机IP + "selected": true, + "required": false, + }, + "switchPort1": { // 网口1(eth0)上联端口 + "selected": true, + "required": false, + }, + "switchPort2": { // 网口2(eth1)上联端口 + "selected": true, + "required": false, + }, + + "nicInfo": { // 网络设置 单网卡 or 双网口 + "selected": true, + "required": false, + }, + "iloIp": { // 带外IP + "selected": true, + "required": false, + }, + "privateIpv4": { // 内网IPv4 + "selected": true, + "required": false, + }, + "privateEth1Ipv4": { // eth1内网IPv4 + "selected": true, + "required": false, + }, + "privateIpv6": { // 内网IPv6 + "selected": true, + "required": false, + }, + "privateEth1Ipv6": { // eth1内网IPv6 + "selected": true, + "required": false, + }, + "createdTime": { // 创建时间 + "selected": true, + "required": false, + }, + "operate": { + "selected": true, + "required": true, + }, + "collectStatus": { + "selected": true, + "required": false, + }, + }, + }, + //设备类型列表自定义表头 + "deviceTypeList": { + "customInfo": { + "name": { + "selected": true, + "required": true, + }, + "deviceSeries": { + "selected": true, + "required": false, + }, + "idcName": { + "selected": true, + "required": false, + }, + "idcRegion": { + "selected": true, + "required": false, + }, + "architecture": { + "selected": true, + "required": false, + }, + "deviceType": { + "selected": true, + "required": false, + }, + + "image": { + "selected": true, + "required": false, + }, + "cpu": { + "selected": true, + "required": false, + }, + "memory": { + "selected": true, + "required": false, + }, + "systemVolume": { + "selected": true, + "required": false, + }, + "systemVolumeRaid": { + "selected": true, + "required": false, + }, + "raidCan": { + "selected": true, + "required": false, + }, + "dataVolume": { + "selected": true, + "required": false, + }, + "nicInfo": { + "selected": true, + "required": false, + }, + "nic": { + "selected": true, + "required": false, + }, + "gpu": { + "selected": true, + "required": false, + }, + + "remark": { + "selected": true, + "required": false, + }, + "operate": { + "selected": true, + "required": true, + }, + "deviceCount": { + "selected": true, + "required": false, + }, + "bootMode": { + "required": false, + "selected": true, + }, + }, + }, + //机房列表自定义表头 + "idcList": { + "customInfo": { + "address": { + "selected": true, + "required": false, + }, + + "level": { + "selected": true, + "required": false, + }, + "name": { + "selected": true, + "required": true, + }, + "nameEn": { + "selected": true, + "required": false, + }, + + "updateTime": { + "selected": true, + "required": false, + }, + "createTime": { + "selected": true, + "required": false, + }, + + "createdBy": { + "selected": true, + "required": false, + }, + "updatedBy": { + "selected": true, + "required": false, + }, + "operate": { + "selected": true, + "required": true, + }, + }, + }, + // 用户列表自定义表头 + "userList": { + "customInfo": { + "userName": { + "selected": true, + "required": true, + }, + "userId": { + "selected": true, + "required": false, + }, + "roleName": { + "selected": true, + "required": false, + }, + "phone": { + "selected": true, + "required": false, + }, + "email": { + "selected": true, + "required": false, + }, + "remark": { + "selected": true, + "required": false, + }, + "createTime": { + "selected": true, + "required": false, + }, + "projectCount": { + "selected": true, + "required": false, + }, + "operate": { + "selected": true, + "required": true, + }, + }, + }, + // 角色列表自定义表头 + "roleList": { + "customInfo": { + "roleName": { + "selected": true, + "required": true, + }, + "userName": { + "selected": true, + "required": false, + }, + "permission": { + "selected": true, + "required": false, + }, + "operate": { + "selected": true, + "required": true, + }, + }, + }, + //消息自定义表头 + "messageList": { + "customInfo": { + "detail": { + "selected": true, + "required": true, + }, + "finish_time": { // + "selected": true, + "required": false, + }, + "message_type": { // + "selected": true, + "required": false, + }, + "message_sub_type": { // + "selected": true, + "required": false, + }, + }, + }, + "auditLogsList": { + "customInfo": { + "logid": { + "selected": true, + "required": true, + }, + "operationName": { // + "selected": true, + "required": true, + }, + "userName": { // + "selected": true, + "required": false, + }, + "operateTime": { // + "selected": true, + "required": false, + }, + "result": { // + "selected": true, + "required": false, + }, + "failReason": { // + "selected": true, + "required": false, + }, + }, + }, + "monitorRulesList": { + "customInfo": { + "ruleName": { + "selected": true, + "required": false, + }, + "ruleId": { // + "selected": true, + "required": false, + }, + "resourceName": { // + "selected": true, + "required": false, + }, + "instanceCount": { // + "selected": true, + "required": false, + }, + "triggerDescription": { // + "selected": true, + "required": false, + }, + "statusName": { // + "selected": true, + "required": false, + }, + "operate": { + "required": true, + "selected": true, + }, + "userName": { + "required": true, + "selected": true, + }, + }, + }, + "monitorAlertsList": { + "customInfo": { + "alertTime": { + "selected": true, + "required": true, + }, + "resourceName": { // + "selected": true, + "required": false, + }, + "triggerDescription": { // + "selected": true, + "required": false, + }, + "alertValue": { // + "selected": true, + "required": false, + }, + "alertLevelDescription": { // + "selected": true, + "required": false, + }, + "alertPeriod": { // + "selected": true, + "required": false, + }, + "userName": { // + "selected": true, + "required": false, + }, + }, + }, + } + ExportImageHeader = []string{ + "镜像名称", + "镜像ID", + "镜像类型", + "体系架构", + "操作系统平台", + "操作系统版本", + "镜像格式", + "引导模式", + "系统盘分区", + "镜像描述", + "已关联机型数", + "创建时间", + } + ExportImageHeaderEn = []string{ + "Image Name", + "Image ID", + "Image Type", + "Architecture", + "OS Platform", + "OS Version", + "Image Format", + "Boot Mode", + "System Volume Partition", + "Image Desp", + "Associated ITs", + "Created Time", + } + + NetworkType = map[string]string{ + "basic": "基础网络", + "vpc": "私有网络", + "retail": "定制网络", + } + + NetworkTypeEn = map[string]string{ + "basic": "basic", + "vpc": "vpc", + "retail": "retail", + } + + InterfaceMode = map[string]string{ + "single": "单网口", + "bond": "单网口bond", + "dual": "双网口", + } + InterfaceModeEn = map[string]string{ + "single": "Single Network Interface", + "bond": "Single Network Interface bond", + "dual": "Double Network Interfaces", + } + InstanceStatus = map[string]string{ + "creating": "创建中", + "starting": "开机中", + "running": "运行", + "stopping": "关机中", + "stopped": "关机", + "restarting": "重启中", + "resetting_password": "重置密码中", + "destroying": "销毁中", + "destroyed": "已销毁", + "error": "错误", + "upgrading": "调整配置中", + "reinstalling": "重装系统中", + } + + InstanceStatusEn = map[string]string{ + "creating": "Creating", + "starting": "Starting up", + "running": "running", + "stopping": "Shutting Down", + "stopped": "Shut Down", + "restarting": "Rebooting", + "resetting_password": "Resetting password", + "destroying": "Destroying", + "destroyed": "destroyed", + "error": "Error", + "upgrading": "Upgrading", + "reinstalling": "Reinstalling System", + } + + FilterInstanceStatus = map[string]string{ //给前端用的实例列表的fiter筛选接口用 + "running": "运行", + "stopped": "关机", + "error": "错误", + } + + FilterInstanceStatusEn = map[string]string{ //给前端用的实例列表的fiter筛选接口用 + "running": "running", + "stopped": "stopped", + "error": "error", + } + Instance = map[string]map[string]string{ + ERROR_NO_INSTANCE_NOT_FOUND: map[string]string{ + "cn": "资源实例未找到", + "en": "instance not found", + }, + //todo + } + InstanceLockedName = map[string]string{ //给前端用的设备列表的实力锁定状态 + "locked": "已锁定", + "unlocked": "已解锁", + } + + InstanceLockedNameEn = map[string]string{ + "locked": "locked", + "unlocked": "unlocked", + } + + ExportDeviceHeader = []string{ + "SN", + "机型名称", + "机型类型", + "管理状态", + "机房名称", + "机柜编码", + "所在U位", + "品牌", + "型号", + "体系架构", + "镜像", + + "实例名称", + "实例ID", + "实例状态", + "实例锁定状态", + "实例属主", + "CPU", + "内存", + "系统盘", + "数据盘", + "GPU", + "网口1交换机IP", + + "网口2交换机IP", + "网口1(eth0)上联端口", + "网口2(eth1)上联端口", + "网络设置", + "带外IP", + "内网IPv4(eth0)", + "内网IPv4(eth1)", + "内网IPv6(eth0)", + "内网IPv6(eth1)", + "创建时间", + "备注", + } + ExportDeviceHeaderEn = []string{ + "SN", + "Type Name", + "Instance Type", + "Management Status", + "Name", + "Cabinet ID", + "Unit Location", + "Brand", + "Model", + "Architecture", + "Image", + + "Instance Name", + "Instance ID", + "Instance Status", + "Locked Status", + "Instance Owner", + "CPU", + "Memory", + "System Volume", + "Data Volume", + "GPU", + "Uplink SW IP(Port #1)", + + "Uplink SW IP(Port #2)", + "Uplink SW Port #1", + "Uplink SW Port #2", + "NIC settings", + "OOB IP", + "Private IPv4(eth0)", + "Private IPv4(eth1)", + "Private IPv6(eth0)", + "Private IPv6(eth1)", + "Created Time", + "Remark", + } + + ExportDeviceTypeHeader = []string{ + "机型名称", + "机型类型", + "机房名称", + "机房英文名称", + "体系架构", + "引导模式", + "机型规格", + + "镜像", + "设备", + "CPU", + "内存", + //"系统盘", + //"RAID配置", + //"系统盘RAID", + // + //"数据盘", + //"数据盘 RAID", + "网卡", + "网络设置", + "GPU", + + "描述", + } + + ExportDeviceTypeHeaderEn = []string{ + "Type Name", + "Instance Type", + "Name", // TODO 机房名称:显示所属的机房 + "English Name", // TODO 机房编码: cn-north-1 + "Architecture", + "BootMode", + "Instance Spec (IS)", + + "Image", + "Devices", + "CPU", + "Memory", + "System Volume", + "RAID Config", + "System Volume RAID Type", + "Data Volume", + //"Data Volume Raid Type", + "NIC", + "NIC settings", + "GPU", + + "Description", + } + + ExportIdcHeader = []string{ + "机房名称", + "机房英文名称", + "机房等级", + "机房地址", + "创建时间", + "创建人", + "更新时间", + "更新人", + } + + ExportIdcHeaderEn = []string{ + "Name", + "English name", + "Level", + "Address", + "Created Time", + "Creator", + "Update time", + "Updater", + } + + ExportUserHeader = []string{ + "用户名", + "用户ID", + "角色", + "手机", + "邮箱", + "描述", + "创建时间", + } + ExportUserHeaderEn = []string{ + "User Name", + "User ID", + "Role", + "Mobile Phone", + "Email", + "Description", + "Create Time", + } + + ExportMessageHeader = []string{ + "消息内容", + "接收时间", + "消息类型", + "消息子类型", + } + + ExportMessageHeaderEn = []string{ + "message content", + "time", + "message type", + "message subtype", + } + + ExportAuditLogsHeader = []string{ + "LogID", + "操作名称", + "操作人", + "操作时间", + "操作反馈", + "错误码", + } + + ExportAuditLogsHeaderEn = []string{ + "LogID", + "Operation Name", + "Operator", + "Operation Time", + "Operation Feedback", + "Fault Info", + } + + OssFilter = map[string]interface{}{ + "architecture": map[string]interface{}{ + "i386": map[string]interface{}{ + "osType": map[string]interface{}{ + "其它": "", + }, + }, + "x86_64": map[string]interface{}{ + "osType": map[string]interface{}{ + "CentOS": []string{"7.1", "7.2", "7.4", "7.5", "7.6", "7.8", "7.9", "8.0", "8.2"}, + "Ubuntu": []string{"14.04", "16.04", "18.04", "20.04"}, + "Windows": []string{"2012", "2016", "2019", "2022"}, + "Debian": []string{"10.9"}, + "OpenEuler": []string{"20.03"}, + "其它": "", + }, + }, + "ARM64(aarch64)": map[string]interface{}{ + "osType": map[string]interface{}{ + "CentOS": []string{"8.2"}, + "OpenEuler": []string{"20.03"}, + "其它": "", + }, + }, + "LoongArch™": map[string]interface{}{ + "osType": map[string]interface{}{ + "loongnix-server": []string{"8.4"}, + }, + }, + "format": []string{ + "tar", + "qcow2", + }, + "bootMode": []string{ + "UEFI", + "Legacy/BIOS", + }, + }, + } + OssFilterEn = map[string]interface{}{ + "architecture": map[string]interface{}{ + "i386": map[string]interface{}{ + "osType": map[string]interface{}{ + "Other": "", + }, + }, + "x86_64": map[string]interface{}{ + "osType": map[string]interface{}{ + "CentOS": []string{"6.6", "7.1", "7.2", "7.4", "7.5", "7.6", "7.8", "7.9", "8.0", "8.2"}, + "Ubuntu": []string{"14.04", "16.04", "18.04", "20.04"}, + "Windows": []string{"2012", "2016", "2019", "2022"}, + "Debian": []string{"10.9"}, + "OpenEuler": []string{"20.03"}, + "Other": "", + }, + }, + "ARM64(aarch64)": map[string]interface{}{ + "osType": map[string]interface{}{ + "CentOS": []string{"8.2"}, + "OpenEuler": []string{"20.03"}, + "Other": "", + }, + }, + "LoongArch™": map[string]interface{}{ + "osType": map[string]interface{}{ + "loongnix-server": []string{"8.4"}, + }, + }, + }, + } + ExportRulesHeader = []string{ + "用户名", + "规则名称", + "规则ID", + "资源类型", + "实例关联数量", + "触发条件", + "状态", + } + + ExportRulesHeaderEn = []string{ + "User Name", + "Rule Name", + "Rule ID", + "Resource Type", + "Instance associated number", + "Triggering conditions", + "Status", + } + ExportAlertsHeader = []string{ + "用户名", + "报警时间", + "资源类型", + "报警资源ID", + "触发条件", + "报警值", + "报警级别", + "持续时间", + "通知对象", + } + + ExportAlertsHeaderEn = []string{ + "User Name", + "Alarm time", + "Resource Type", + "Alarm Resources ID", + "Trigger Conditions", + "Alarm Value", + "Alarm Level", + "Duration", + "Notification Object", + } +) diff --git a/bmp-operation-api/logic/CustomInfoLogic/CustomInfoLogic.go b/bmp-operation-api/logic/CustomInfoLogic/CustomInfoLogic.go new file mode 100644 index 0000000..22733cb --- /dev/null +++ b/bmp-operation-api/logic/CustomInfoLogic/CustomInfoLogic.go @@ -0,0 +1,86 @@ +package CustomInfoLogic + +import ( + "strings" + + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/RaidLogic" + rdsUtil "coding.jd.com/aidc-bmp/bmp-operation-api/services/redis" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + + //"coding.jd.com/bmp/ironic-console-jdstack/thirdpart/redis" + "encoding/json" + + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + "git.jd.com/cps-golang/ironic-common/exception" + log "git.jd.com/cps-golang/log" + "github.com/go-redis/redis" +) + +func SetCustomInfo(logger *log.Logger, param requestTypes.SetCustomInfoRequest) *response.CommonResponse { + userId := logger.GetPoint("userId").(string) + redisValue := make(map[string]map[string]map[string]bool, 0) + redisValue["customInfo"] = param.PageValue + err := rdsUtil.RedisCli.Set("custom_info_operation_"+userId+":"+param.PageKey, util.InterfaceToJson(redisValue), 0).Err() + if err != nil { + panic(exception.Exception{Msg: "redis set " + param.PageKey + " error", Status: BaseLogic.ERROR_CODE}) + } + res := response.CommonResponse{ + Success: true, + } + return &res +} +func GetCustomInfo(logger *log.Logger, param requestTypes.QueryCustomInfoRequest) *map[string]map[string]map[string]bool { + userId := logger.GetPoint("userId").(string) + if param.Reload == "true" { + rdsUtil.RedisCli.Del("custom_info_operation_" + userId + ":" + param.PageKey) + } + result, err := rdsUtil.RedisCli.Get("custom_info_operation_" + userId + ":" + param.PageKey).Result() + if err == redis.Nil { //如果key不存在,取默认值 + result = util.InterfaceToJson(BaseLogic.HeaderList[param.PageKey]) + //panic(exception.Exception{Msg: "redis name " + param.PageKey + " does not exist", Status: BaseLogic.ERROR_CODE}) + } else if err != nil { + panic(exception.Exception{Msg: "get redis name " + param.PageKey + " failed", Status: BaseLogic.ERROR_CODE}) + } + obj := make(map[string]map[string]map[string]bool, 0) //responseWeb.GetCustomInfoResponse{} + err = json.Unmarshal([]byte(result), &obj) + return &obj +} + +func GetRaidconf(logger *log.Logger) map[int]map[string]map[string]string { + raids, _ := RaidLogic.QueryRaidsAll(logger) + m := map[string]string{} + for _, raid := range raids.Raids { + m[strings.ToUpper(raid.Name)] = raid.RaidID + } + r := map[int]map[string]map[string]string{} + if logger.GetPoint("language").(string) == BaseLogic.EN_US { + //r[2]["RAID"] = map[string]string{"RAID0": m["RAID0"], "RAID1": m["RAID1"], "RAID0-stripping": m["NO RAID"]} + r = map[int]map[string]map[string]string{ + 1: map[string]map[string]string{ + "NO RAID": map[string]string{"NO RAID": m["NO RAID"]}, + }, + 2: map[string]map[string]string{ + "RAID": map[string]string{"RAID0": m["RAID0"], "RAID1": m["RAID1"], "RAID5": m["RAID5"], "RAID10": m["RAID10"]}, + }, + 3: map[string]map[string]string{ + "RAID0-stripping": map[string]string{"RAID0": m["RAID0"]}, + }, + } + } else { + r = map[int]map[string]map[string]string{ + 1: map[string]map[string]string{ + "NO RAID": map[string]string{"NO RAID": m["NO RAID"]}, + }, + 2: map[string]map[string]string{ + //"NO RAID": map[string]string{"NO RAID": m["NO RAID"]}, + "RAID": map[string]string{"RAID0": m["RAID0"], "RAID1": m["RAID1"], "RAID5": m["RAID5"], "RAID10": m["RAID10"]}, + }, + 3: map[string]map[string]string{ + "单盘RAID0": map[string]string{"RAID0": m["RAID0"]}, + }, + } + } + return r +} diff --git a/bmp-operation-api/logic/DeviceLogic/DeviceLogic.go b/bmp-operation-api/logic/DeviceLogic/DeviceLogic.go new file mode 100644 index 0000000..c3f0059 --- /dev/null +++ b/bmp-operation-api/logic/DeviceLogic/DeviceLogic.go @@ -0,0 +1,986 @@ +package DeviceLogic + +import ( + "errors" + "fmt" + "math/rand" + "mime/multipart" + "net" + "os" + "path" + "regexp" + "strconv" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-operation-api/constant" + + sdkDeviceParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/device" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + beego "github.com/beego/beego/v2/server/web" + + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/excel" + sdk "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" +) + +// 【设备管理】【设备列表】 +func GetDeviceList(logger *log.Logger, param *requestTypes.QueryDeviceListRequest) (*response.DevicePage, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceParameters.NewDescribeDevicesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithDeviceTypeID(¶m.DeviceTypeID) + req.WithDeviceSeries(¶m.DeviceSeries) + req.WithIloIP(¶m.IloIP) + req.WithInstanceID(¶m.InstanceID) + req.WithInstanceName(¶m.InstanceName) + req.WithManageStatus(¶m.ManageStatus) + req.WithCollectStatus(¶m.CollectStatus) + req.WithSn(¶m.Sn) + req.WithUserID(¶m.UserID) + req.WithUserName(¶m.UserName) + req.WithPageNumber(¶m.PageNumber) + req.WithPageSize(¶m.PageSize) + req.WithIsAll(¶m.IsAll) + logger.Info("DescribeDevices openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Device.DescribeDevices(req, nil) + logger.Info("DescribeDevices openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil { + logger.Info("DescribeDevices openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + resp := response.DevicePage{} + obj := response.Device{} + if len(client.Payload.Result.Devices) == 0 { + resp.Devices = make([]response.Device, 0) + return &resp, nil + } + + for _, v := range client.Payload.Result.Devices { + obj = buildEntity(logger, v, param.Show) + resp.Devices = append(resp.Devices, obj) + } + resp.PageNumber = client.Payload.Result.PageNumber + resp.PageSize = client.Payload.Result.PageSize + resp.TotalCount = client.Payload.Result.TotalCount + return &resp, nil +} + +// 导出Excel文件 +func ExportDeviceExcel(logger *log.Logger, result []response.Device) (string, string, error) { + language := logger.GetPoint("language").(string) + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + for _, data := range result { + + //dt, err := DeviceTypeLogic.GetDeviceTypeInfo(logger, &requestTypes.QueryDeviceTypeRequest{ + // DeviceTypeID: data.DeviceTypeID, + //}) + //if err != nil { + // logger.Warn("deviceType err:", err.Error()) + // return "", "", err + //} + + nic_ := BaseLogic.InterfaceMode[data.InterfaceMode] //"单网口" + if language == BaseLogic.EN_US { + nic_ = BaseLogic.InterfaceModeEn[data.InterfaceMode] + } + sheetData = append(sheetData, []string{ + data.Sn, // SN + data.DeviceTypeName, // 机型名称 + data.DeviceSeriesName, //机型类型 + data.ManageStatusName, // 管理状态,包含:已入库 已上架 已创建 上架中 下架中; + data.IdcName, // 机房名称 + data.Cabinet, // 机柜编码 + data.UPosition, // 所在U位 + data.Brand, // 品牌 + data.Model, // 型号 + data.Architecture, // 体系架构 + data.ImageName, // 实例镜像 + + data.InstanceName, // 实例名称 + data.InstanceID, // 实例ID + data.InstanceStatusName, // 实例状态 + data.Locked, // 实例锁定状态 + data.UserName, // 实例属主 + data.CpuInfo, // CPU + + data.MemInfo, // 内存:显示总容量 + data.SvInfo, // 系统盘 + data.DvInfo, // 数据盘 + data.GpuInfo, // GPU + data.SwitchIP1, // 网口1交换机IP + + data.SwitchIP2, // 网口2交换机IP + data.SwitchPort1, // 网口1(eth0)上联端口 + data.SwitchPort2, // 网口2(eth1)上联端口 + nic_, // 网络设置 + data.IloIP, // 带外IP + data.PrivateIPv4, // 内网IPv4 + data.PrivateEth1IPV4, + data.PrivateIPv6, // 内网IPv6 + data.PrivateEth1IPV6, + data.CreatedTime, // 创建时间 + data.Description, // 设备描述 + }) + } + exportExcelHeader := BaseLogic.ExportDeviceHeader + if language == BaseLogic.EN_US { + exportExcelHeader = BaseLogic.ExportDeviceHeaderEn + } + if err := e.SetSheetData("Sheet1", exportExcelHeader, sheetData); err != nil { + logger.Warn("create excel error:", err.Error()) + return "", "", err + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + // 生成100000到100000+900000之间的随机数,左闭右开 + downloadFileName := "device_list_" + time.Now().Format(BaseLogic.FormatDate) + "_" + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Warn("保存excel到本地失败" + err.Error()) + return "", "", err + } + return fileName, downloadFileName, nil +} + +// 【设备管理】【设备详情】 +func GetDeviceInfo(logger *log.Logger, param *requestTypes.QueryDeviceInfoRequest) (*response.Device, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceParameters.NewDescribeDeviceParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithTraceID(logid) + req.WithDeviceID(param.DeviceID) + logger.Info("DescribeDevice openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Device.DescribeDevice(req, nil) + logger.Info("DescribeDevice openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil { + logger.Info("DescribeDevice openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + if client.Payload.Result == nil { + return nil, errors.New("device not found") + } + + obj := buildEntity(logger, client.Payload.Result.Device, param.Show) + return &obj, nil +} + +// 【设备管理】【设备磁盘详情】 +func GetDeviceDiskDetail(logger *log.Logger, param *requestTypes.QueryDeviceDisksRequest) (*models.DeviceDisks, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceParameters.NewDescribeDeviceDisksParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithTraceID(logid) + req.WithDeviceID(param.DeviceID) + logger.Info("DescribeDeviceDisks openapi sdk req:", util.InterfaceToJson(req)) + res, err := sdk.SdkClient.Device.DescribeDeviceDisks(req, nil) + logger.Info("DescribeDeviceDisks openapi sdk resp:", util.InterfaceToJson(res)) + if err != nil { + logger.Warn("DescribeDeviceDisks openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + if res.Payload.Result == nil { + return nil, errors.New("device not found") + } + + return res.Payload.Result, nil +} + +// 列表和详情共用方法 +func buildEntity(logger *log.Logger, v *sdkModels.Device, show string) response.Device { + //dt, err := DeviceTypeLogic.GetDeviceTypeInfo(logger, &requestTypes.QueryDeviceTypeRequest{ + // DeviceTypeID: v.DeviceTypeID, + //}) + //if err != nil { + // logger.Warn("deviceType err:", err.Error()) + // return response.Device{} + //} + + interfaceModeName := BaseLogic.InterfaceMode[v.InterfaceMode] //"单网口" + if logger.GetPoint("language").(string) == BaseLogic.EN_US { + interfaceModeName = BaseLogic.InterfaceModeEn[v.InterfaceMode] + } + lockedName := BaseLogic.InstanceLockedName[v.Locked] //"单网口" + if logger.GetPoint("language").(string) == BaseLogic.EN_US { + lockedName = BaseLogic.InstanceLockedNameEn[v.Locked] + } + + obj := response.Device{} + obj.CpuInfo = v.CPUInfo + obj.MemInfo = v.MemInfo + obj.SvInfo = v.SvInfo + obj.DvInfo = v.DvInfo + obj.GpuInfo = v.GpuInfo + obj.NicInfo = v.NicInfo + obj.InterfaceModeName = interfaceModeName + obj.LockedName = lockedName + + obj.AdapterID = int(v.AdapterID) + obj.Architecture = v.Architecture + obj.Brand = v.Brand + obj.Model = v.Model + obj.CPUAmount = v.CPUAmount + obj.CPUCores = v.CPUCores + + obj.CPUFrequency = v.CPUFrequency + obj.CPUManufacturer = v.CPUManufacturer + obj.CPUModel = v.CPUModel + obj.CPURoads = v.CPURoads + obj.Reason = v.Reason + obj.Cabinet = v.Cabinet + + obj.DataVolumeAmount = v.DataVolumeAmount + obj.DataVolumeInterfaceType = v.DataVolumeInterfaceType + obj.DataVolumeSize = int(v.DataVolumeSize) + obj.DataVolumeType = v.DataVolumeType + obj.Description = v.Description + + obj.DeviceID = v.DeviceID + obj.DeviceSeries = v.DeviceSeries + obj.DeviceSeriesName = v.DeviceSeriesName + obj.DeviceType = v.DeviceType + obj.DeviceTypeID = v.DeviceTypeID + obj.DeviceTypeName = v.DeviceTypeName + + obj.Enclosure1 = v.Enclosure1 + obj.Enclosure2 = v.Enclosure2 + obj.Gateway = v.Gateway + obj.GpuAmount = v.GpuAmount + obj.GpuManufacturer = v.GpuManufacturer + + obj.GpuModel = v.GpuModel + obj.ID = int(v.ID) + obj.IdcID = *v.IdcID + obj.IdcName = v.IdcName + obj.IdcNameEn = v.IDcNameEn + obj.IloIP = v.IloIP + + obj.IloUser = v.IloUser + obj.ImageName = v.ImageName + obj.InstanceCreatedTime = util.UtcToTime(v.InstanceCreatedTime) + obj.InstanceDescription = v.InstanceDescription + + obj.InstanceID = v.InstanceID + obj.InstanceName = v.InstanceName + obj.UserID = v.UserID + obj.UserName = v.UserName + obj.InstanceStatus = v.InstanceStatus + obj.InstanceStatusName = v.InstanceStatusName + obj.InstanceReason = v.InstanceReason + obj.InterfaceMode = v.InterfaceMode + obj.Locked = v.Locked + + obj.Mac1 = v.Mac1 + obj.Mac2 = v.Mac2 + // in=已入库|putway=已上架|unputway=已下架|created=已创建|putawaying=上架中|unputwaying=下架中 + obj.ManageStatus = v.ManageStatus // 英文展示 + obj.ManageStatusName = v.ManageStatusName // 中文展示 + obj.Mask = v.Mask + obj.MemAmount = int(v.MemAmount) + + obj.MemFrequency = int(v.MemFrequency) + obj.MemSize = int(v.MemSize) + obj.MemType = v.MemType + obj.NicAmount = v.NicAmount + obj.NicRate = int(v.NicRate) + + obj.PrivateIPv4 = v.PrivateIPV4 + obj.PrivateIPv6 = v.PrivateIPV6 + obj.Eth1Mask = v.Eth1Mask + obj.PrivateEth1IPV4 = v.PrivateEth1IPV4 + obj.PrivateEth1IPV6 = v.PrivateEth1IPV6 + obj.RaidDriver = v.RaidDriver + obj.Slot1 = int(v.Slot1) + obj.Slot2 = int(v.Slot2) + + obj.Sn = v.Sn + obj.SwitchIP = v.SwitchIP + obj.SwitchIP1 = v.SwitchIP1 + obj.SwitchIP2 = v.SwitchIP2 + + obj.SwitchPort1 = v.SwitchPort1 + obj.SwitchPort2 = v.SwitchPort2 + obj.SwitchUser1 = v.SwitchUser1 + obj.SwitchUser2 = v.SwitchUser2 + + obj.SystemVolumeAmount = v.SystemVolumeAmount + obj.SystemVolumeInterfaceType = v.SystemVolumeInterfaceType + obj.SystemVolumeSize = int(v.SystemVolumeSize) + obj.SystemVolumeType = v.SystemVolumeType + obj.UPosition = v.UPosition + + obj.CreatedBy = v.CreatedBy + obj.CreatedTime = util.UtcToTime(v.CreatedTime) + obj.UpdatedBy = v.UpdatedBy + obj.UpdatedBy = util.UtcToTime(v.UpdatedTime) + if show == "iloPassword" { + obj.IloPassword = v.IloPassword + obj.SwitchPassword1 = "" + obj.SwitchPassword2 = "" + } + if show == "switchPassword1" { + obj.IloPassword = "" + obj.SwitchPassword1 = v.SwitchPassword1 + obj.SwitchPassword2 = "" + } + if show == "switchPassword2" { + obj.IloPassword = "" + obj.SwitchPassword1 = "" + obj.SwitchPassword2 = v.SwitchPassword2 + } + obj.CollectStatus = v.CollectStatus + obj.CollectFailReason = v.CollectFailReason + obj.IsNeedRaid = v.IsNeedRaid + return obj +} + +// 【设备管理】【设备下架】支持多sn,英文逗号分隔 +func UnPutawayDevice(logger *log.Logger, param *requestTypes.UnPutawayDeviceRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceParameters.NewUnMountDeviceParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithTraceID(logid) + + //array := []string{} + //if len(param.Sns) != 0 { + // array = strings.Split(param.Sns, ",") + //} + body := sdkModels.UnMountDevicesRequest{ + DeviceID: ¶m.DeviceID, + } + req.WithBody(&body) + logger.Info("UnMountDevice openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Device.UnMountDevice(req, nil) + logger.Info("UnMountDevice openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil { + logger.Info("UnMountDevice openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +// 【设备管理】【设备上架】支持多sn,英文逗号分隔 +func PutawayDevice(logger *log.Logger, param *requestTypes.PutawayDeviceRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceParameters.NewMountDeviceParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + //array := []string{} + //if len(param.Sns) != 0 { + // array = strings.Split(param.Sns, ",") + //} + body := sdkModels.MountDevicesRequest{ + DeviceID: ¶m.DeviceID, + } + req.WithBody(&body) + logger.Info("MountDevice openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Device.MountDevice(req, nil) + logger.Info("MountDevice openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil { + logger.Info("MountDevice openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +// 【设备管理】【设备修改】 +func ModifyDevice(logger *log.Logger, param *requestTypes.ModifyDeviceRequest, deviceId string) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceParameters.NewModifyDeviceParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.DeviceID = deviceId + body := sdkModels.ModifyDevicesRequest{ + Description: param.Description, + } + req.WithBody(&body) + logger.Info("ModifyDevice openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Device.ModifyDevice(req, nil) + logger.Info("ModifyDevice openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil { + logger.Info("MountDevice openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +// 【设备管理】【删除设备】 +func DeleteDevice(logger *log.Logger, param *requestTypes.DeleteDeviceRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceParameters.NewDeleteDeviceParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithDeviceID(param.DeviceId) + logger.Info("DeleteDevice openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Device.DeleteDevice(req, nil) + logger.Info("DeleteDevice openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil { + logger.Info("DeleteDevice openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +// 【设备管理】【移除设备】 +func RemoveDevice(logger *log.Logger, deviceId string) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceParameters.NewRemoveDeviceParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithDeviceID(deviceId) + logger.Info("RemoveDevice openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Device.RemoveDevice(req, nil) + logger.Info("RemoveDevice openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil { + logger.Info("RemoveDevice openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +func UploadDevices(logger *log.Logger, param *requestTypes.UploadDeviceRequest, header *multipart.FileHeader, requestId string) ([]*response.UploadDevice, error) { + arr := strings.Split(header.Filename, ".") + suffix := strings.ToLower(arr[len(arr)-1]) + //language := logger.GetPoint("language").(string) + if suffix != "xlsx" { //util.InArray(suffix, AvailableSuffix) { + logger.Warn("file format not support:", suffix) + panic(constant.BuildInvalidArgumentWithArgs("文件类型不符合,必须是xlsx类型", "file must be xlsx")) + } + dir, err := util.GetBaseDir() + if err != nil { + logger.Warn("获取当前根目录失败" + err.Error()) + return nil, err + } + //prefix := util.GenUuid() + uploadPath, _ := beego.AppConfig.String("upload.path") + util.CreateDirIfNotExist(uploadPath) //如果目录不存在,创建一个目录 + localFileName := path.Join(dir, uploadPath, requestId+"_"+header.Filename) //prefix+"-"+header.Filename + fmt.Println(localFileName) + if err = util.SaveToLocal(localFileName, param.DeviceFile); err != nil { + logger.Warn("保存excel到本地失败" + err.Error()) + return nil, err + } + f, err := excel.LoadExcel(localFileName) + if err != nil { + return nil, err + } + defer DelUploadExcel(localFileName) + list, err := f.GetSheetData() + if err != nil { + return nil, err + } + logger.Infof("UploadExcel.GetSheetData:%s", util.InterfaceToJson(list)) + devices := []*response.UploadDevice{} + + sns := []string{} + iloIps := []string{} + ipv6s := []string{} + if len(list) > 10002 { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("单次上传不能超过10000条"), fmt.Sprintf("exceed 10000"))) + } + fmt.Println("the excel parse content=======:", list) + for k, v := range list { + if k >= 2 { + // if len(v) == 25 { + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("AdapterId 不能为空"), fmt.Sprintf("AdapterId empty"))) + // } + // if len(v) == 26 { + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("Enclosure1 不能为空"), fmt.Sprintf("Enclosure1 empty"))) + // } + // if len(v) == 27 { + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("Slot1 不能为空"), fmt.Sprintf("Slot1 empty"))) + // } + // if len(v) < 28 { //slot1v[24] + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("有必填项没有写,请检查"), fmt.Sprintf("empty invalidate,please check"))) + // } + specialMatch := regexp.MustCompile("^.{1,128}$").MatchString //[一-龥_a-zA-Z0-9_-] + if !specialMatch(v[0]) { //sn + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("Sn %s 不合法", v[0]), fmt.Sprintf("Sn %s invalidate", v[0]))) + } + if !specialMatch(v[1]) { //Cabinet机柜 + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("Cabinet %s 不合法", v[1]), fmt.Sprintf("Cabinet %s invalidate", v[1]))) + } + if !specialMatch(v[2]) { //U位 + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("UPosition %s 不合法", v[2]), fmt.Sprintf("UPosition %s invalidate", v[2]))) + } + // if !specialMatch(v[3]) { + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("Brand %s 不合法", v[3]), fmt.Sprintf("Brand %s invalidate", v[3]))) + // } + // if !specialMatch(v[4]) { + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("Model %s 不合法", v[4]), fmt.Sprintf("Model %s invalidate", v[4]))) + // } + if _, err := net.ParseMAC(v[3]); err != nil { //mac1(eth0) + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("mac1(eth0) %s 不合法", v[3]), fmt.Sprintf("mac1(eth0) %s invalidate", v[3]))) + } + // if _, err := net.ParseMAC(v[6]); err != nil { + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("Mac2 %s 不合法", v[6]), fmt.Sprintf("Mac2 %s invalidate", v[6]))) + // } + // specialMatch = regexp.MustCompile("^[a-zA-Z/0-9_-]{1,128}$").MatchString + // if !specialMatch(v[9]) { + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("switchport1 %s 不合法", v[9]), fmt.Sprintf("switchport1 %s invalidate", v[9]))) + // } + // specialMatch = regexp.MustCompile("^[a-zA-Z/0-9_-]{1,128}$").MatchString + // if !specialMatch(v[10]) { + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("switchport2 %s 不合法", v[10]), fmt.Sprintf("switchport2 %s invalidate", v[10]))) + // } + if net.ParseIP(v[4]) == nil { //mask + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("mask %s 不合法", v[4]), fmt.Sprintf("mask %s invalidate", v[4]))) + } + + if net.ParseIP(v[5]) == nil { //eth0 private ipv4 + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("ipv4(eth0) %s 不合法", v[5]), fmt.Sprintf("eth0 PrivateIPv4 %s invalidate", v[5]))) + } + if v[6] != "" { //eth0 ipv6 + if strings.Contains(v[6], "/") { //2403:1EC0:8549:60C0::1/64 + arr := strings.Split(v[6], "/") + ipv6 := arr[0] + mask := arr[1] + maskCount, err := strconv.Atoi(mask) + if err != nil { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("eth0 ipv6 %s 不合法", v[6]), fmt.Sprintf("eth0 ipv6 %s invalidate", v[6]))) + } + if !strings.Contains(ipv6, ":") { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("eth0 ipv6 %s 不合法", v[6]), fmt.Sprintf("eth0 ipv6 %s invalidate", v[6]))) + } + if net.ParseIP(ipv6) == nil || (maskCount < 0 || maskCount > 128) { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("eth0 ipv6 %s 不合法", v[6]), fmt.Sprintf("eth0 ipv6 %s invalidate", v[6]))) + } + } else { + ipv6 := v[6] + if !strings.Contains(ipv6, ":") { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("eth0 ipv6 %s 不合法", v[6]), fmt.Sprintf("eth0 ipv6 %s invalidate", v[6]))) + } + if net.ParseIP(ipv6) == nil { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("eth0 ipv6 %s 不合法", v[6]), fmt.Sprintf("eth0 ipv6 %s invalidate", v[6]))) + } + } + } + if net.ParseIP(v[7]) == nil { //gateway + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("Gateway %s 不合法", v[7]), fmt.Sprintf("Gateway %s invalidate", v[7]))) + } + + if net.ParseIP(v[8]) == nil { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("IloIP %s 不合法", v[8]), fmt.Sprintf("IloIP %s invalidate", v[8]))) + } + + specialMatch = regexp.MustCompile("^.{1,128}$").MatchString + if !specialMatch(v[9]) && v[9] != "" { //IloUser + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("IloUser %s 不合法", v[9]), fmt.Sprintf("IloUser %s invalidate", v[9]))) + } + if !specialMatch(v[10]) && v[10] != "" { //IloPassword + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("IloPassword %s 不合法", v[10]), fmt.Sprintf("IloPassword %s invalidate", v[10]))) + } + + if util.InArrayString(v[0], sns) { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("文件中sn %s 重复", v[0]), fmt.Sprintf("file sn %s repeat", v[0]))) + } + sns = append(sns, v[0]) + if util.InArrayString(v[8], iloIps) { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("文件中带外IP %s 重复", v[8]), fmt.Sprintf("file iloIp %s repeat", v[8]))) + } + iloIps = append(iloIps, v[8]) + //res, err := rdsUtil.RedisCli.SAdd("sns", v[0]).Result() + //if res == 0 { //没有设置成功,说明有元素存在了 + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("文件中sn %s 重复", v[0]), fmt.Sprintf("file sn %s repeat", v[0]))) + //} + //fmt.Println("err", res, err, rdsUtil.RedisCli.SMembers("b")) + + if v[6] != "" { //eth0 ipv6 + if util.InArrayString(v[6], ipv6s) { + panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("文件中eth0 IPV6 %s 重复", v[6]), fmt.Sprintf("file eth0 IPV6 %s repeat", v[6]))) + } + ipv6s = append(ipv6s, v[6]) + } + + // if v[25] == "" { //adapterid + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("AdapterId %s 不能为空", v[25]), fmt.Sprintf("AdapterId %s empty", v[25]))) + // } + // if v[26] == "" { //enslouser1 + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("Enclosure1 %s 不能为空", v[26]), fmt.Sprintf("Enclosure1 %s empty", v[26]))) + // } + // if v[27] == "" { //slot1 + // panic(constant.BuildInvalidArgumentWithArgs(fmt.Sprintf("Slot1 %s 不能为空", v[27]), fmt.Sprintf("Slot1 %s empty", v[27]))) + // } + // adapterId, _ := strconv.Atoi(v[25]) + // slot1, _ := strconv.Atoi(v[27]) + device := &response.UploadDevice{ + Sn: v[0], + Cabinet: v[1], + UPosition: v[2], + // Brand: v[3], + // Model: v[4], + + Mac1: strings.ToLower(v[3]), //mac地址转小写 + // Mac2: strings.ToLower(v[6]), + // SwitchIP1: v[7], + // SwitchIP2: v[8], + // SwitchPort1: v[9], + // SwitchPort2: v[10], + + Mask: v[4], + // MaskEth1: v[12], + Gateway: v[7], + IloIP: v[8], + IloUser: v[9], + IloPassword: v[10], + + // SwitchUser1: v[17], + // SwitchPassword1: v[18], + // SwitchUser2: v[19], + // SwitchPassword2: v[20], + PrivateIPv4: v[5], + // PrivateEth1IPv4: v[22], + PrivateIPv6: v[6], + // PrivateEth1IPv6: v[24], + + // AdapterID: adapterId, + // Enclosure1: v[26], + // Slot1: slot1, + } + // if len(v) == 30 { //如果30,说明槽位2都有数据(不能只出现slot2或者enclouser2一个,要么都出现,要么都不出现) + // device.Enclosure2 = v[28] + // slot2, _ := strconv.Atoi(v[29]) + // device.Slot2 = slot2 + // } + + devices = append(devices, device) + } + } + return devices, nil +} +func DelUploadExcel(localFileName string) error { + if err := os.Remove(localFileName); err != nil { + return err + } + return nil +} +func CreateDevices(logger *log.Logger, param *requestTypes.CreateDeviceRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceParameters.NewCreateDeviceParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithTimeout(time.Minute * 10) //超时时间设置 + devices := []*sdkModels.CreateDeviceSpec{} + for _, v := range param.Devices { + // adapterId := int64(v.AdapterID) + // slot1 := int64(v.Slot1) + deviceSpec := &sdkModels.CreateDeviceSpec{ + Sn: &v.Sn, + Cabinet: &v.Cabinet, + UPosition: &v.UPosition, + // Brand: &v.Brand, + // Model: &v.Model, + + Mac1: &v.Mac1, + // Mac2: &v.Mac2, + // SwitchIP1: &v.SwitchIP1, + // SwitchIP2: &v.SwitchIP2, + // SwitchPort1: &v.SwitchPort1, + // SwitchPort2: &v.SwitchPort2, + + Mask: &v.Mask, + // MaskEth1: v.MaskEth1, + Gateway: &v.Gateway, + IloIP: &v.IloIP, + IloUser: v.IloUser, + IloPassword: v.IloPassword, + + // SwitchUser1: v.SwitchUser1, + // SwitchPassword1: v.SwitchPassword1, + // SwitchUser2: v.SwitchUser2, + // SwitchPassword2: v.SwitchPassword2, + PrivateIPV4: &v.PrivateIPv4, + // PrivateEth1IPV4: v.PrivateEth1IPv4, + PrivateIPV6: v.PrivateIPv6, + // PrivateEth1IPV6: v.PrivateEth1IPv6, + + // RaidDriver: "megacli64", //写死 + // AdapterID: &adapterId, + // Enclosure1: &v.Enclosure1, + // Slot1: &slot1, + // Enclosure2: v.Enclosure2, + // Slot2: int64(v.Slot2), + } + devices = append(devices, deviceSpec) + } + //return response.DeviceIds{}, err + body := sdkModels.CreateDevicesRequest{ + IDcID: ¶m.IdcId, + // DeviceTypeID: ¶m.DeviceTypeId, + Devices: devices, + } + req.WithBody(&body) + logger.Info("openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Device.CreateDevice(req, nil) + logger.Info(":", util.InterfaceToJson(client)) + if err != nil { + logger.Info("CreateDevices openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + if client == nil || client.Payload == nil || client.Payload.Result == nil { + return nil, errors.New("create device failed") + } + return &response.CommonResponse{ + Success: client.Payload.Result.Success, + }, nil +} + +func CollectDevice(logger *log.Logger, param *requestTypes.CollectDevice) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceParameters.NewCollectDeviceInfoParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithTimeout(time.Minute * 10) //超时时间设置 + c := []*sdkModels.CollectItem{ + &sdkModels.CollectItem{ + Sn: ¶m.Sn, + AllowOverride: ¶m.AllowOverride, + }, + } + body := sdkModels.CollectDeviceInfoRequest{ + Collects: c, + } + req.WithBody(&body) + logger.Info("openapi CollectDeviceInfo req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Device.CollectDeviceInfo(req, nil) + logger.Info("openapi CollectDeviceInfo resp:", util.InterfaceToJson(client)) + if err != nil { + logger.Info("openapi CollectDeviceInfo openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + if client == nil || client.Payload == nil || client.Payload.Result == nil { + return nil, errors.New("openapi CollectDeviceInfo failed") + } + return &response.CommonResponse{ + Success: client.Payload.Result.Success, + }, nil + +} + +// 设备关联磁盘 +func AssociateDeviceDisks(logger *log.Logger, param *requestTypes.AssociateDeviceDisksRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceParameters.NewAssociateDeviceDisksParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithTraceID(logid) + + //array := []string{} + //if len(param.Sns) != 0 { + // array = strings.Split(param.Sns, ",") + //} + volumes := []*sdkModels.AssociateDeviceDiskSpec{} + for _, v := range param.Volumes { + item := &sdkModels.AssociateDeviceDiskSpec{ + DiskIDs: v.DiskIDs, + VolumeID: v.VolumeID, + } + volumes = append(volumes, item) + } + body := sdkModels.AssociateDeviceDisksRequest{ + DeviceID: ¶m.DeviceID, + DeviceTypeID: ¶m.DeviceTypeID, + Volumes: volumes, + } + req.WithBody(&body) + logger.Info("AssociateDeviceDisks openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Device.AssociateDeviceDisks(req, nil) + logger.Info("AssociateDeviceDisks openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil { + logger.Info("AssociateDeviceDisks openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +func GetAssociatedDisks(logger *log.Logger, param *requestTypes.GetAssociatedDisksRequest) ([]*models.Disk, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceParameters.NewGetAssociatedDisksParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithTraceID(logid) + req.WithDeviceID(param.DeviceID) + req.WithVolumeID(param.VolumeID) + req.WithDeviceTypeID(param.DeviceTypeID) + logger.Info("GetAssociatedDisks openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Device.GetAssociatedDisks(req, nil) + logger.Info("GetAssociatedDisks openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil { + logger.Info("GetAssociatedDisks openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + if client.Payload.Result == nil { + return nil, errors.New("disks not found") + } + + return client.Payload.Result, nil +} + +// 设备关联机型 +func DeviceAssociateDeviceType(logger *log.Logger, param *requestTypes.DeviceAssociateDeviceTypeRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceParameters.NewDeviceAssociateDeviceTypeParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithTraceID(logid) + + body := sdkModels.DeviceAssociateDeviceTypeRequest{ + DeviceID: ¶m.DeviceID, + DeviceTypeID: ¶m.DeviceTypeID, + } + req.WithBody(&body) + logger.Info("DeviceAssociateDeviceType openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Device.DeviceAssociateDeviceType(req, nil) + logger.Info("DeviceAssociateDeviceType openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil { + logger.Info("DeviceAssociateDeviceType openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} diff --git a/bmp-operation-api/logic/DeviceTypeLogic/DeviceTypeLogic.go b/bmp-operation-api/logic/DeviceTypeLogic/DeviceTypeLogic.go new file mode 100644 index 0000000..2e3102f --- /dev/null +++ b/bmp-operation-api/logic/DeviceTypeLogic/DeviceTypeLogic.go @@ -0,0 +1,949 @@ +package DeviceTypeLogic + +import ( + "errors" + "fmt" + "math/rand" + "strconv" + "strings" + "time" + + sdkDeviceTypeParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/device_type" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/BaseLogic" + raidLogic "coding.jd.com/aidc-bmp/bmp-operation-api/logic/RaidLogic" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/excel" + sdk "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" +) + +// 【机型管理】【添加机型】 +func AddDeviceType(logger *log.Logger, param *requestTypes.CreateDeviceTypeRequest) (*response.CreateDeviceTypeResult, error) { + logid := logger.GetPoint("logid").(string) + + req := sdkDeviceTypeParameters.NewCreateDeviceTypeParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + //systemVolumeSize := int64(param.SystemVolumeSize) + //if param.SystemVolumeUnit == "TB" { + // systemVolumeSize = int64(param.SystemVolumeSize * 1000) + //} + //dataVolumeSize := int64(param.DataVolumeSize) + //if param.DataVolumeUnit == "TB" { + // dataVolumeSize = int64(param.DataVolumeSize * 1000) + //} + //volumeItem := sdkModels.CreateDeviceTypeRequestVolumesItems0{ + // DeviceTypeID: + //} + body := sdkModels.CreateDeviceTypeRequest{ + Architecture: ¶m.Architecture, + CPUAmount: ¶m.CPUAmount, + CPUCores: ¶m.CPUCores, + CPUFrequency: ¶m.CPUFrequency, + CPUManufacturer: ¶m.CPUManufacturer, + CPUModel: ¶m.CPUModel, + + Description: param.Description, + DeviceSeries: ¶m.DeviceSeries, + DeviceType: ¶m.DeviceType, + GpuAmount: param.GpuAmount, + GpuManufacturer: param.GpuManufacturer, + GpuModel: param.GpuModel, + Height: GetInt64(param.Height), + IDcID: ¶m.IDcID, + InterfaceMode: ¶m.InterfaceMode, + MemAmount: GetInt64(param.MemAmount), + MemFrequency: GetInt64(param.MemFrequency), + MemSize: GetInt64(param.MemSize), + MemType: ¶m.MemType, + Name: ¶m.Name, + NicAmount: ¶m.NicAmount, + NicRate: GetInt64(param.NicRate), + + CPUSpec: ¶m.CpuSpec, + MemSpec: ¶m.MemSpec, + BootMode: param.BootMode, + Volumes: param.Volumes, + IsNeedRaid: param.IsNeedRaid, + } + req.WithBody(&body) + logger.Info("CreateDeviceType openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.DeviceType.CreateDeviceType(req, nil) + logger.Info("CreateDeviceType openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil { + logger.Info("AddDeviceType openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + if client == nil || client.Payload == nil || client.Payload.Result == nil { + return nil, errors.New("add device info failed") + } + + res := &response.CreateDeviceTypeResult{ + DeviceTypeId: *client.Payload.Result.DeviceTypeID, + } + + return res, nil +} +func GetInt64(number int) *int64 { + num := int64(number) + return &num +} +func f2i(f float64) int { + i, _ := strconv.Atoi(fmt.Sprintf("%1.0f", f)) + return i +} +func GetInt8(number int8) *int8 { + return &number +} + +// 【机型管理】【机型列表】 +func GetDeviceTypeList(logger *log.Logger, param *requestTypes.QueryDeviceTypesRequest) (*response.DeviceTypePage, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceTypeParameters.NewDescribeDeviceTypesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithDeviceSeries(¶m.DeviceSeries) + req.WithDeviceType(¶m.DeviceType) + req.WithDeviceTypeID(¶m.DeviceTypeID) + req.WithIdcID(¶m.IdcID) + req.WithIsAll(¶m.IsAll) + req.WithName(¶m.Name) + req.WithPageNumber(¶m.PageNumber) + req.WithPageSize(¶m.PageSize) + logger.Info("DescribeDeviceTypes openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.DeviceType.DescribeDeviceTypes(req, nil) + logger.Info("DescribeDeviceTypes openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil || client.Payload == nil { + logger.Info("DescribeDeviceTypeList openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + resp := response.DeviceTypePage{} + obj := response.DeviceType{} + if len(client.Payload.Result.DeviceTypes) == 0 { + resp.DeviceTypes = make([]response.DeviceType, 0) + return &resp, nil + } + + raidMap := make(map[string]response.Raid) // 请求一次,避免循环请求 + raid, raidsErr := raidLogic.QueryRaidsAll(logger) + if raidsErr == nil && len(raid.Raids) != 0 { + for _, v := range raid.Raids { + raidMap[v.RaidID] = *v + } + } + + for _, v := range client.Payload.Result.DeviceTypes { + //idc, err := idcLogic.GetIdcInfo(logger, idcReq) + //if err == nil { + // idcName = idc.Name + // //idcRegion = idc.NameEn + //} + imageCount := "" + imagesReq := &requestTypes.QueryDeviceTypeImagePageRequest{ + DeviceTypeID: v.DeviceTypeID, + } + images, imagesErr := GetDeviceTypeImageList(logger, imagesReq) + if imagesErr == nil { + imageCount = strconv.Itoa(len(images.DeviceTypeImages)) + } + + obj = buildEntity(logger, v) + obj.ImageCount = imageCount + //array := []string{} // 拆分查询 + //if len(v.Raid) != 0 { + // array = strings.Split(v.Raid, ",") + //} + //if len(array) != 0 { + // raid := "" + // for _, str := range array { + // raid = raid + raidMap[str].Name + "," // RAID0,RAID1 + // } + // obj.Raid = raid[0 : len(raid)-1] + //} + + resp.DeviceTypes = append(resp.DeviceTypes, obj) + } + resp.PageNumber = client.Payload.Result.PageNumber + resp.PageSize = client.Payload.Result.PageSize + resp.TotalCount = client.Payload.Result.TotalCount + return &resp, nil +} + +// 导出Excel文件 +func ExportDeviceTypeExcel(logger *log.Logger, result []response.DeviceType) (string, string, error) { + language := logger.GetPoint("language").(string) + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + for _, v := range result { + + //obj := response.DeviceType{} + //raidMap := make(map[string]response.Raid) // 请求一次,避免循环请求 + //raid, raidsErr := raidLogic.QueryRaidsAll(logger) + //if raidsErr == nil && len(raid.Raids) != 0 { + // for _, v := range raid.Raids { + // raidMap[v.RaidID] = *v + // } + //} + //array := []string{} // 拆分查询 + //if len(v.Raid) != 0 { + // array = strings.Split(v.Raid, ",") + //} + //if len(array) != 0 { + // raid_ := "" + // for _, str := range array { + // raid_ = raid_ + raidMap[str].Name + "," // RAID0,RAID1 + // } + // obj.Raid = raid_[0 : len(raid_)-1] + //} + + //fmt.Println("1", v.Raid, "2", obj.Raid) + //os.Exit(1) + //cpu_ := v.v.CPUManufacturer + " " + v.CPUModel + "(" + strconv.Itoa(int(v.CPUAmount)) + "*" + strconv.Itoa(int(v.CPUCores)) + " 物理核, " + v.CPUFrequency + "GHz)" + //mem_ := strconv.Itoa(int(v.MemAmount)*int(v.MemSize)) + "GB " + v.MemType + " " + strconv.Itoa(int(v.MemFrequency)) + "MHz" + //// 系统盘:显示总容量 (单块容量 接口类型 类型*数量 RAID 模式) + //// 240GB 240GB SATA SSD*2 RAID1 + //sv_ := strconv.Itoa(int(v.SystemVolumeAmount)*int(v.SystemVolumeSize)) + "GB(" + strconv.Itoa(int(v.SystemVolumeSize)) + "GB " + v.SystemVolumeInterfaceType + " " + v.SystemVolumeType + "*" + strconv.Itoa(int(v.SystemVolumeAmount)) + "," + v.Raid + ")" + //if v.SystemVolumeUnit == "TB" { + // sv_ = strconv.FormatFloat(float64(v.SystemVolumeAmount)*float64(v.SystemVolumeSize), 'f', 2, 64) + "TB(" + strconv.FormatFloat(float64(v.SystemVolumeSize), 'f', 2, 64) + "TB " + v.SystemVolumeInterfaceType + " " + v.SystemVolumeType + "*" + strconv.Itoa(int(v.SystemVolumeAmount)) + "," + v.Raid + ")" + //} + //// 数据盘:显示总容量 (单块容量 接口类型 类型*数量 RAID 模式) + //dv_ := strconv.Itoa(int(v.DataVolumeAmount)*int(v.DataVolumeSize)) + "GB(" + strconv.Itoa(int(v.DataVolumeSize)) + "GB " + v.DataVolumeInterfaceType + " " + v.DataVolumeType + "*" + strconv.Itoa(int(v.DataVolumeAmount)) + "," + v.Raid + ")" + //if v.DataVolumeUnit == "TB" { + // dv_ = strconv.FormatFloat(float64(v.DataVolumeAmount)*float64(v.DataVolumeSize), 'f', 2, 64) + "TB(" + strconv.FormatFloat(float64(v.DataVolumeSize), 'f', 2, 64) + "TB " + v.DataVolumeInterfaceType + " " + v.DataVolumeType + "*" + strconv.Itoa(int(v.DataVolumeAmount)) + "," + v.Raid + ")" + //} + //if v.DataVolumeAmount == 0 { + // dv_ = "" + //} + //// 显示品牌 显卡型号 个数,例 NVIDIA P40 * 4 + //gpu_ := v.GpuManufacturer + " " + v.GpuModel + "*" + strconv.Itoa(int(v.GpuAmount)) + //if v.GpuAmount == 0 { + // gpu_ = "" + //} + //nicInfo := strconv.Itoa(int(v.NicAmount)) + "*" + strconv.Itoa(int(v.NicRate)) + "GE" + + nic_ := BaseLogic.InterfaceMode[v.InterfaceMode] + if language == BaseLogic.EN_US { + nic_ = BaseLogic.InterfaceModeEn[v.InterfaceMode] + } + + imageCount := "" + imagesReq := &requestTypes.QueryDeviceTypeImagePageRequest{ + DeviceTypeID: v.DeviceTypeID, + } + images, imagesErr := GetDeviceTypeImageList(logger, imagesReq) + if imagesErr == nil { + imageCount = strconv.Itoa(len(images.DeviceTypeImages)) + } + + deviceCount := "--" + if v.DeviceCount > 0 { + deviceCount = strconv.Itoa(v.DeviceCount) + } + + sheetData = append(sheetData, []string{ + v.Name, + v.DeviceSeriesName, // 机型类型:显示所属的机型类型 + v.IdcName, // 机房名称:显示所属的机房 + v.IdcNameEn, // 机房英文名称: cn-north-1 + v.Architecture, // 体系架构:显示机型的体系架构 + v.BootMode, + v.DeviceType, // 机型规格 + + imageCount, // 暂时默认0 支持镜像数量 + deviceCount, + v.CpuInfo, // CPU + v.MemInfo, // 内存 + //v.SvInfo, // 系统盘 + //v.RaidCan, + //v.Raid, // 系统盘RAID + //v.DvInfo, // 数据盘 + //"RAID1", // TODO 缺少此字段 数据盘 RAID + v.NicInfo, // 网卡 + nic_, // 网络设置 + v.GpuInfo, // GPU + + v.Description, // 描述:显示针对机型的描述 + + }) + } + exportExcelHeader := BaseLogic.ExportDeviceTypeHeader + if language == BaseLogic.EN_US { + exportExcelHeader = BaseLogic.ExportDeviceTypeHeaderEn + } + if err := e.SetSheetData("Sheet1", exportExcelHeader, sheetData); err != nil { + logger.Warn("create excel error:", err.Error()) + return "", "", err + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + // 生成100000到100000+900000之间的随机数,左闭右开 + downloadFileName := "device_type_list_" + time.Now().Format(BaseLogic.FormatDate) + "_" + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Warn("保存excel到本地失败" + err.Error()) + return "", "", err + } + return fileName, downloadFileName, nil +} + +// 【机型管理】【机型详情信息】 +func GetDeviceTypeInfo(logger *log.Logger, param *requestTypes.QueryDeviceTypeRequest) (*response.DeviceType, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceTypeParameters.NewDescribeDeviceTypeParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithDeviceTypeID(param.DeviceTypeID) + logger.Info("DescribeDeviceType openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.DeviceType.DescribeDeviceType(req, nil) + logger.Info("DescribeDeviceType openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil || client.Payload == nil { + logger.Info("DescribeDeviceTypeInfo openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + if client.Payload.Result == nil { + return nil, errors.New("device type not found") + } + imageCount := "" + imagesReq := &requestTypes.QueryDeviceTypeImagePageRequest{ + DeviceTypeID: param.DeviceTypeID, + } + images, imagesErr := GetDeviceTypeImageList(logger, imagesReq) + if imagesErr == nil { + imageCount = strconv.Itoa(len(images.DeviceTypeImages)) + } + obj := buildEntity(logger, client.Payload.Result.DeviceType) + obj.ImageCount = imageCount + return &obj, nil +} +func buildEntity(logger *log.Logger, v *sdkModels.DeviceType) response.DeviceType { + language := logger.GetPoint("language").(string) + interfaceModeName := BaseLogic.InterfaceMode[v.InterfaceMode] + if language == BaseLogic.EN_US { + interfaceModeName = BaseLogic.InterfaceModeEn[v.InterfaceMode] + } + obj := response.DeviceType{} + /*raidMap := make(map[string]response.Raid) // 请求一次,避免循环请求 + raid, raidsErr := raidLogic.QueryRaidsAll(logger) + if raidsErr == nil && len(raid.Raids) != 0 { + for _, v := range raid.Raids { + raidMap[v.RaidID] = *v + } + } + array := []string{} // 拆分查询 + if len(v.Raid) != 0 { + array = strings.Split(v.Raid, ",") + } + if len(array) != 0 { + raid_ := "" + for _, str := range array { + _name := raidMap[str].Name + if strings.ToUpper(_name) == "NORAID" && v.SystemVolumeAmount == 2 && v.RaidCan == "RAID" { + if language == BaseLogic.EN_US { + _name = "RAID0-stripping" + } else { + _name = "单盘RAID0" + } + } + if v.RaidCan == "NORAID" { //配合前端展示 + _name = "--" + } + raid_ = raid_ + _name + "," // RAID0,RAID1 + + } + obj.Raid = raid_[0 : len(raid_)-1] + } + obj.RaidCan = v.RaidCan*/ + // + //cpu_ := v.CPUManufacturer + " " + v.CPUModel + "(" + strconv.Itoa(int(v.CPUAmount)) + "*" + strconv.Itoa(int(v.CPUCores)) + "物理核," + v.CPUFrequency + "GHz)" + //if language == BaseLogic.EN_US { + // cpu_ = v.CPUManufacturer + " " + v.CPUModel + "(" + strconv.Itoa(int(v.CPUAmount)) + "*" + strconv.Itoa(int(v.CPUCores)) + "cores," + v.CPUFrequency + "GHz)" + //} + //mem_ := strconv.Itoa(int(v.MemAmount)*int(v.MemSize)) + "GB(" + strconv.Itoa(int(v.MemSize)) + "GB*" + strconv.Itoa(int(v.MemAmount)) + ")" + v.MemType + " " + strconv.Itoa(int(v.MemFrequency)) + "MHz" + //// 系统盘:显示总容量 (单块容量 接口类型 类型*数量 RAID 模式) + //// 240GB 240GB SATA SSD*2 RAID1 + //sv_ := strconv.Itoa(int(v.SystemVolumeAmount)*int(v.SystemVolumeSize)) + "GB(" + strconv.Itoa(int(v.SystemVolumeSize)) + "GB " + v.SystemVolumeInterfaceType + " " + v.SystemVolumeType + "*" + strconv.Itoa(int(v.SystemVolumeAmount)) + "," + obj.Raid + ")" + //if v.SystemVolumeUnit == "TB" { + // sv_ = Trim(strconv.FormatFloat(float64(v.SystemVolumeAmount)*float64(v.SystemVolumeSize)/1000, 'f', 2, 64)) + "TB(" + Trim(strconv.FormatFloat(float64(v.SystemVolumeSize)/1000, 'f', 2, 64)) + "TB " + v.SystemVolumeInterfaceType + " " + v.SystemVolumeType + "*" + strconv.Itoa(int(v.SystemVolumeAmount)) + "," + obj.Raid + ")" + //} + //// 数据盘:显示总容量 (单块容量 接口类型 类型*数量 RAID 模式) + //dv_ := strconv.Itoa(int(v.DataVolumeAmount)*int(v.DataVolumeSize)) + "GB(" + strconv.Itoa(int(v.DataVolumeSize)) + "GB " + v.DataVolumeInterfaceType + " " + v.DataVolumeType + "*" + strconv.Itoa(int(v.DataVolumeAmount)) + "," + obj.Raid + ")" + //if v.DataVolumeUnit == "TB" { + // dv_ = Trim(strconv.FormatFloat(float64(v.DataVolumeAmount)*float64(v.DataVolumeSize)/1000, 'f', 2, 64)) + "TB(" + Trim(strconv.FormatFloat(float64(v.DataVolumeSize)/1000, 'f', 2, 64)) + "TB " + v.DataVolumeInterfaceType + " " + v.DataVolumeType + "*" + strconv.Itoa(int(v.DataVolumeAmount)) + "," + obj.Raid + ")" + //} + //if v.DataVolumeAmount == 0 { + // dv_ = "" + //} + //// 显示品牌 显卡型号 个数,例 NVIDIA P40 * 4 + //gpu_ := v.GpuManufacturer + " " + v.GpuModel + "*" + strconv.Itoa(int(v.GpuAmount)) + //if v.GpuAmount == 0 { + // gpu_ = "" + //} + //nicInfo := strconv.Itoa(int(v.NicAmount)) + "*" + strconv.Itoa(int(v.NicRate)) + "GE" + // + //nic_ := BaseLogic.InterfaceMode[v.InterfaceMode] + //if language == BaseLogic.EN_US { + // nic_ = BaseLogic.InterfaceModeEn[v.InterfaceMode] + //} + + //obj.CpuInfo = cpu_ + //obj.MemInfo = mem_ + //obj.SvInfo = sv_ + //obj.DvInfo = dv_ + //obj.GpuInfo = gpu_ + //obj.NicInfo = nicInfo + //obj.Nic = nic_ + obj.CpuInfo = v.CPUInfo + obj.MemInfo = v.MemInfo + obj.SvInfo = v.SvInfo + obj.DvInfo = v.DvInfo + obj.GpuInfo = v.GpuInfo + obj.NicInfo = v.NicInfo + + obj.IDcID = v.IDcID + obj.IdcName = v.IDcName + obj.IdcNameEn = v.IDcNameEn + obj.DeviceTypeID = v.DeviceTypeID + obj.Name = v.Name + obj.DeviceType = v.DeviceType + obj.DeviceSeries = v.DeviceSeries + + obj.DeviceSeriesName = v.DeviceSeriesName + obj.Architecture = v.Architecture + obj.Height = int(v.Height) + obj.Description = v.Description + obj.CPUAmount = v.CPUAmount + + obj.CPUCores = v.CPUCores + obj.CPUManufacturer = v.CPUManufacturer + obj.CPUModel = v.CPUModel + obj.CPUFrequency = v.CPUFrequency + obj.MemSize = int(v.MemSize) + + obj.MemAmount = int(v.MemAmount) + obj.MemType = v.MemType + obj.MemFrequency = int(v.MemFrequency) + obj.NicAmount = v.NicAmount + obj.NicRate = int(v.NicRate) + obj.InterfaceMode = v.InterfaceMode + obj.InterfaceModeName = interfaceModeName + + obj.GpuAmount = v.GpuAmount + + obj.GpuManufacturer = v.GpuManufacturer + obj.GpuModel = v.GpuModel + + obj.CreatedBy = v.CreatedBy + obj.CreatedTime = util.UtcToTime(v.CreatedTime) + obj.UpdatedBy = v.UpdatedBy + obj.UpdatedBy = util.UtcToTime(v.UpdatedTime) + + obj.CPUSpec = v.CPUSpec + obj.MemSpec = v.MemSpec + obj.InstanceCount = int(v.InstanceCount) + obj.DeviceCount = int(v.DeviceCount) + obj.BootMode = v.BootMode + volumes := []response.Volume{} + + if v.Volumes != nil { + volumeResp := response.Volume{} + for _, value := range v.Volumes { + volumeResp.VolumeID = value.VolumeID + volumeResp.VolumeAmount = value.VolumeAmount + volumeResp.VolumeName = value.VolumeName + volumeResp.VolumeUnit = value.VolumeUnit + volumeResp.VolumeSize = value.VolumeSize + + volumeResp.VolumeType = value.VolumeType + volumeResp.RaidCan = value.RaidCan + volumeResp.Raid = value.Raid + volumeResp.RaidID = value.RaidID + volumeResp.InterfaceType = value.InterfaceType + volumeResp.DiskType = value.DiskType + volumes = append(volumes, volumeResp) + } + } + obj.Volumes = volumes + obj.IsNeedRaid = v.IsNeedRaid + return obj +} + +// 【机型管理】【机型详情信息】【关联镜像列表】 +func GetDeviceTypeImageList(logger *log.Logger, param *requestTypes.QueryDeviceTypeImagePageRequest) (*response.DeviceTypeImageList, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceTypeParameters.NewDescribeDeviceTypeImagesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithDeviceTypeID(¶m.DeviceTypeID) + req.WithImageID(¶m.ImageID) + req.WithArchitecture(¶m.Architecture) + req.WithOsType(¶m.OsType) + req.WithSource(¶m.Source) + req.WithVersion(¶m.Version) + req.WithImageName(¶m.ImageName) + + logger.Info("DescribeDeviceTypeImages openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.DeviceType.DescribeDeviceTypeImages(req, nil) + fmt.Println("cli", client) + logger.Info("DescribeDeviceTypeImages openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil { + logger.Info("DescribeDeviceTypeImages openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + resp := response.DeviceTypeImageList{} + if len(client.Payload.Result.Images) == 0 { + resp.DeviceTypeImages = make([]response.DeviceTypeImage, 0) + return &resp, nil + } + obj := response.DeviceTypeImage{} + for _, v := range client.Payload.Result.Images { + obj.ID = v.ID + obj.ImageID = v.ImageID + obj.ImageName = v.ImageName + obj.OsID = v.OsID + obj.Format = v.Format + + obj.Filename = v.Filename + obj.URL = v.URL + obj.Hash = v.Hash + obj.Source = v.Source + obj.SourceName = v.SourceName + obj.Description = v.Description + + obj.SystemPartition = v.SystemPartition + obj.DataPartition = v.DataPartition + obj.OsType = v.OsType + obj.OsVersion = v.OsVersion + obj.DeviceTypeNum = int(v.DeviceTypeNum) + + obj.Architecture = v.Architecture + //obj.PreImage = "预置镜像" + obj.IsBind = v.IsBind + obj.CreatedBy = v.CreatedBy + obj.CreatedTime = util.UtcToTime(v.CreatedTime) + obj.UpdatedBy = v.UpdatedBy + obj.UpdatedBy = util.UtcToTime(v.UpdatedTime) + + resp.DeviceTypeImages = append(resp.DeviceTypeImages, obj) + } + resp.PageNumber = client.Payload.Result.PageNumber + resp.PageSize = client.Payload.Result.PageSize + resp.TotalCount = client.Payload.Result.TotalCount + return &resp, nil +} + +// 【机型管理】【机型详情信息】【关联镜像列表】【添加镜像】 +func AssociateDeviceTypeImage(logger *log.Logger, param *requestTypes.AssociateDeviceTypeImageRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceTypeParameters.NewAssociatedImageParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + array := []string{} + if len(param.ImageIds) != 0 { + array = strings.Split(param.ImageIds, ",") + } + body := sdkModels.AssociateImageRequest{ + DeviceTypeID: ¶m.DeviceTypeID, + ImageIDs: array, + } + req.WithBody(&body) + logger.Info("AssociatedImage openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.DeviceType.AssociatedImage(req, nil) + logger.Info("AssociatedImage openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil || client.Payload == nil { + logger.Info("AssociateDeviceTypeImage openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +// 【机型管理】【机型详情信息】【关联镜像列表】【删除镜像】 +func DisassociateDeviceTypeImage(logger *log.Logger, param *requestTypes.DisassociateDeviceTypeImageRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceTypeParameters.NewDissociatedImageParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + body := sdkModels.DissociatedImageRequest{ + DeviceTypeID: ¶m.DeviceTypeID, + ImageID: ¶m.ImageId, + } + req.WithBody(&body) + logger.Info("DissociatedImage openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.DeviceType.DissociatedImage(req, nil) + logger.Info("DissociatedImage openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil || client.Payload == nil { + logger.Info("DisassociateDeviceTypeImage openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +// 【机型管理】【编辑机型】 +func ModifyDeviceTypeInfo(logger *log.Logger, param *requestTypes.ModifyDeviceTypeRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceTypeParameters.NewModifyDeviceTypeParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithDeviceTypeID(param.DeviceTypeID) + + body := sdkModels.ModifyDeviceTypeRequest{ + Architecture: param.Architecture, + CPUAmount: param.CPUAmount, + CPUCores: param.CPUCores, + CPUFrequency: param.CPUFrequency, + CPUManufacturer: param.CPUManufacturer, + CPUModel: param.CPUModel, + //DataVolumeAmount: param.DataVolumeAmount, + //DataVolumeInterfaceType: param.DataVolumeInterfaceType, + // + //DataVolumeType: param.DataVolumeType, + //DataVolumeUnit: param.DataVolumeUnit, + Description: param.Description, + DeviceSeries: param.DeviceSeries, + DeviceType: param.DeviceType, + GpuAmount: param.GpuAmount, + GpuManufacturer: param.GpuManufacturer, + GpuModel: param.GpuModel, + Height: param.Height, + IDcID: param.IDcID, + InterfaceMode: param.InterfaceMode, + MemAmount: param.MemAmount, + MemFrequency: param.MemFrequency, + MemSize: param.MemSize, + MemType: param.MemType, + Name: param.Name, + NicAmount: param.NicAmount, + NicRate: param.NicRate, + RaidID: param.RaidID, + CPUSpec: param.CpuSpec, + MemSpec: param.MemSpec, + //SystemVolumeAmount: param.SystemVolumeAmount, + //SystemVolumeInterfaceType: param.SystemVolumeInterfaceType, + // + //SystemVolumeType: param.SystemVolumeType, + //SystemVolumeUnit: param.SystemVolumeUnit, + BootMode: param.BootMode, + Volumes: param.Volumes, + IsNeedRaid: param.IsNeedRaid, + } + //if param.SystemVolumeSize != nil && param.SystemVolumeUnit != nil { + // systemVolumeSize := int64(*param.SystemVolumeSize) + // if *param.SystemVolumeUnit == "TB" { + // systemVolumeSize = int64(*param.SystemVolumeSize * 1000) + // } + // body.SystemVolumeSize = &systemVolumeSize + // + //} + //if param.RaidCan != "" { + // body.RaidCan = ¶m.RaidCan + //} + + //if param.DataVolumeSize != nil && param.DataVolumeUnit != nil { + // dataVolumeSize := int64(*param.DataVolumeSize) + // if *param.DataVolumeUnit == "TB" { + // dataVolumeSize = int64(*param.DataVolumeSize * 1000) + // } + // body.DataVolumeSize = &dataVolumeSize + // + //} + + req.WithBody(&body) + logger.Info("ModifyDeviceType openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.DeviceType.ModifyDeviceType(req, nil) + logger.Info("ModifyDeviceType openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil { + logger.Info("ModifyDeviceTypeInfo openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + if client == nil || client.Payload == nil || client.Payload.Result == nil { + return nil, errors.New("modify device info failed") + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +// 【机型管理】【删除】 +func DeleteDeviceTypeInfo(logger *log.Logger, param *requestTypes.DeleteDeviceTypeRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkDeviceTypeParameters.NewDeleteDeviceTypeParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithDeviceTypeID(param.DeviceTypeID) + logger.Info("DeleteDeviceType openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.DeviceType.DeleteDeviceType(req, nil) + logger.Info("DeleteDeviceType openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil || client.Payload == nil { + logger.Info("DeleteDeviceTypeInfo openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + if client.Payload.Result == nil { + return nil, errors.New("device type not found") + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} +func Trim(str string) string { + s := strings.TrimRight(str, "0") + s = strings.TrimRight(s, ".") + return s +} + +func GetAvailableDeviceTypes(logger *log.Logger, param requestTypes.GetAvailableDeviceTypesRequest) (*response.AvailableDeviceType, error) { + + logid := logger.GetPoint("logid").(string) + userId := logger.GetPoint("userId").(string) + req := sdkDeviceTypeParameters.NewDescribeDeviceTypesParams() + req.WithTraceID(logid) + req.WithIdcID(¶m.IdcID) + req.WithBmpUserID(&userId) + isAll := "1" + req.WithIsAll(&isAll) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("QueryDeviceTypes openapi request:", util.InterfaceToJson(req)) + responseApi, err := sdk.SdkClient.DeviceType.DescribeDeviceTypes(req, nil) + logger.Info("QueryDeviceTypes openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("QueryDeviceTypes openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + deviceTypes := responseApi.Payload.Result.DeviceTypes + res := map[string][]response.DeviceTypeReinstall{} + for _, v := range deviceTypes { + if _, ok := res[v.DeviceSeries]; !ok { + res[v.DeviceSeries] = []response.DeviceTypeReinstall{sdkDeviceType2DeviceType(logger, v)} + } else { + res[v.DeviceSeries] = append(res[v.DeviceSeries], sdkDeviceType2DeviceType(logger, v)) + } + } + obj := &response.AvailableDeviceType{} + if len(res["computer"]) != 0 { + obj.Computer = res["computer"] + } + if len(res["storage"]) != 0 { + obj.Storage = res["storage"] + } + if len(res["gpu"]) != 0 { + obj.Gpu = res["gpu"] + } + if len(res["other"]) != 0 { + obj.Other = res["other"] + } + fmt.Println(obj) + return obj, nil + +} + +func sdkDeviceType2DeviceType(logger *log.Logger, v *sdkModels.DeviceType) response.DeviceTypeReinstall { + language := logger.GetPoint("language").(string) + + /* + CPU:2* 24物理核,2.6GHz + + 内存:384GB,2933MHz + + 数据盘:2* 480 SSD + + 系统盘:2* 2TB NVME + + 网卡:2* 25GE + + GPU:4* NVIDIA T4 + */ + //var cputpl string = "%d*%d 物理核,%s" // + //var memtpl string = "%d*%d, %d MHZ" + //var systemtpl string = "%d*%d %s" + //var datatpl string = "%d*%d %s" + //var nictpl string = "%d*%d GE" + //var gputpl string = "%d*%s %s" + //if language == constants.LANGUAGE_EN { + // cputpl = "%d*%d cores,%s" + //} + + //raidMap := make(map[string]responseTypes.Raid) // 请求一次,避免循环请求 + + //raid, _ := raidLogic.QueryRaids(logger, requestTypes.QueryRaidsRequest{ + // DeviceTypeID: v.DeviceTypeID, + //}) + //raidStr := "" + //for _, value := range raid { + // raidStr += value.RaidName + "," + //} + //raidStr = strings.Trim(raidStr, ",") + cpu_ := strconv.Itoa(int(v.CPUAmount)) + "*" + strconv.Itoa(int(v.CPUCores)) + "物理核," + v.CPUFrequency + "GHz" + if language == BaseLogic.EN_US { + cpu_ = strconv.Itoa(int(v.CPUAmount)) + "*" + strconv.Itoa(int(v.CPUCores)) + "cores," + v.CPUFrequency + "GHz" + } + mem_ := strconv.Itoa(int(v.MemAmount)*int(v.MemSize)) + "GB " + v.MemType + " " + strconv.Itoa(int(v.MemFrequency)) + "MHz" + // 系统盘:显示总容量 (单块容量 接口类型 类型*数量 RAID 模式) + // 240GB 240GB SATA SSD*2 RAID1 + //sv_ := strconv.Itoa(int(v.SystemVolumeAmount)*int(v.SystemVolumeSize)) + "GB (" + strconv.Itoa(int(v.SystemVolumeSize)) + "GB " + v.SystemVolumeInterfaceType + " " + v.SystemVolumeType + "*" + strconv.Itoa(int(v.SystemVolumeAmount)) + "," + raidStr + ")" + //if v.SystemVolumeUnit == "TB" { + // sv_ = strconv.FormatFloat(float64(v.SystemVolumeAmount)*float64(v.SystemVolumeSize)/1000, 'f', 2, 64) + "TB (" + strconv.FormatFloat(float64(v.SystemVolumeSize)/1000, 'f', 2, 64) + "TB " + v.SystemVolumeInterfaceType + " " + v.SystemVolumeType + "*" + strconv.Itoa(int(v.SystemVolumeAmount)) + "," + raidStr + ")" + //} + //// 数据盘:显示总容量 (单块容量 接口类型 类型*数量 RAID 模式) + //dv_ := strconv.Itoa(int(v.DataVolumeAmount)*int(v.DataVolumeSize)) + "GB (" + strconv.Itoa(int(v.DataVolumeSize)) + "GB " + v.DataVolumeInterfaceType + " " + v.DataVolumeType + "*" + strconv.Itoa(int(v.DataVolumeAmount)) + "," + raidStr + ")" + //if v.DataVolumeUnit == "TB" { + // dv_ = strconv.FormatFloat(float64(v.DataVolumeAmount)*float64(v.DataVolumeSize)/1000, 'f', 2, 64) + "TB (" + strconv.FormatFloat(float64(v.DataVolumeSize)/1000, 'f', 2, 64) + "TB " + v.DataVolumeInterfaceType + " " + v.DataVolumeType + "*" + strconv.Itoa(int(v.DataVolumeAmount)) + "," + raidStr + ")" + //} + //if v.DataVolumeAmount == 0 { + // dv_ = "" + //} + + /*sv_ := strconv.Itoa(int(v.SystemVolumeSize)) + "GB " + v.SystemVolumeInterfaceType + " " + v.SystemVolumeType + "*" + strconv.Itoa(int(v.SystemVolumeAmount)) + if v.SystemVolumeUnit == "TB" { + sv_ = Trim(strconv.FormatFloat(float64(v.SystemVolumeSize)/1000, 'f', 2, 64)) + "TB " + v.SystemVolumeInterfaceType + " " + v.SystemVolumeType + "*" + strconv.Itoa(int(v.SystemVolumeAmount)) + } + // 数据盘:显示总容量 (单块容量 接口类型 类型*数量 RAID 模式) + dv_ := strconv.Itoa(int(v.DataVolumeSize)) + "GB " + v.DataVolumeInterfaceType + " " + v.DataVolumeType + "*" + strconv.Itoa(int(v.DataVolumeAmount)) + if v.DataVolumeUnit == "TB" { + dv_ = Trim(strconv.FormatFloat(float64(v.DataVolumeSize)/1000, 'f', 2, 64)) + "TB " + v.DataVolumeInterfaceType + " " + v.DataVolumeType + "*" + strconv.Itoa(int(v.DataVolumeAmount)) + } + if v.DataVolumeAmount == 0 { + dv_ = "" + }*/ + + // 显示品牌 显卡型号 个数,例 NVIDIA P40 * 4 + gpu_ := v.GpuManufacturer + " " + v.GpuModel + "*" + strconv.Itoa(int(v.GpuAmount)) + if v.GpuAmount == 0 { + gpu_ = "" + } + nicInfo := strconv.Itoa(int(v.NicAmount)) + "*" + strconv.Itoa(int(v.NicRate)) + "GE" + + return response.DeviceTypeReinstall{ + Name: v.Name, + DeviceTypeId: v.DeviceTypeID, + //Cpu: fmt.Sprintf(cputpl, v.CPUAmount, v.CPUCores, v.CPUFrequency), + //Mem: fmt.Sprintf(memtpl, v.MemAmount, v.MemSize, v.MemFrequency), + //System: fmt.Sprintf(systemtpl, v.SystemVolumeAmount, v.SystemVolumeSize, v.SystemVolumeType), + //Data: fmt.Sprintf(datatpl, v.DataVolumeAmount, v.DataVolumeSize, v.DataVolumeType), + //Nic: fmt.Sprintf(nictpl, v.NicAmount, v.NicRate), + //Gpu: fmt.Sprintf(gputpl, v.GpuAmount, v.GpuManufacturer, v.GpuModel), + Cpu: cpu_, + Mem: mem_, + /*System: sv_, + Data: dv_,*/ + Nic: nicInfo, + Gpu: gpu_, + AvailableStock: v.StockAvailable, + DeviceSeries: v.DeviceSeries, + DeviceSeriesName: v.DeviceSeriesName, + BootMode: v.BootMode, + } +} + +func DescribeVolumesByDeviceType(logger *log.Logger, deviceTypeId string) ([]*sdkModels.VolumeIt, error) { + + logid := logger.GetPoint("logid").(string) + userId := logger.GetPoint("userId").(string) + req := sdkDeviceTypeParameters.NewDescribeVolumesByDeviceTypeParams() + req.WithTraceID(logid) + req.WithBmpUserID(&userId) + req.WithDeviceTypeID(deviceTypeId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("DescribeVolumesByDeviceType openapi request:", util.InterfaceToJson(req)) + responseApi, err := sdk.SdkClient.DeviceType.DescribeVolumesByDeviceType(req, nil) + logger.Info("DescribeVolumesByDeviceType openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeVolumesByDeviceType openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + return responseApi.Payload.Result, nil + +} diff --git a/bmp-operation-api/logic/IdcLogic/IdcLogic.go b/bmp-operation-api/logic/IdcLogic/IdcLogic.go new file mode 100644 index 0000000..f775a66 --- /dev/null +++ b/bmp-operation-api/logic/IdcLogic/IdcLogic.go @@ -0,0 +1,364 @@ +package IdcLogic + +import ( + "errors" + "strconv" + + "math/rand" + "time" + + sdkIdcParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/idc" + sdkUserParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/user" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/excel" + sdk "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" +) + +// 【设备管理】【设备列表】 +func GetIdcList(logger *log.Logger, param *requestTypes.QueryIdcListRequest) (*response.IdcPage, error) { + logid := logger.GetPoint("logid").(string) + userId := logger.GetPoint("userId").(string) + req := sdkIdcParameters.NewDescribeIdcsParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + req.WithBmpUserID(&userId) + req.WithLevel(¶m.Level) + req.WithName(¶m.Name) + req.WithIsAll(¶m.IsAll) + req.WithPageNumber(¶m.PageNumber) + req.WithPageSize(¶m.PageSize) + + logger.Info("DescribeIdcs openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Idc.DescribeIdcs(req, nil) + logger.Info("DescribeIdcs openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warnf("unknown error in Idc.GetIdcList:", err.Error()) + return nil, errors.New("unknown error") //未知错误不暴露给用户 + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warnf("Idc.GetIdcList error:", respErr.Message) + return nil, errors.New(respErr.Message) + } + + resp := response.IdcPage{} + obj := response.Idc{} + if len(client.Payload.Result.Idcs) == 0 { + resp.Idcs = make([]response.Idc, 0) + return &resp, nil + } + + for _, v := range client.Payload.Result.Idcs { + obj = buildEntity(v, param.Show) + resp.Idcs = append(resp.Idcs, obj) + } + + resp.PageNumber = client.Payload.Result.PageNumber + resp.PageSize = client.Payload.Result.PageSize + resp.TotalCount = client.Payload.Result.TotalCount + return &resp, nil +} + +func ExportIdc(logger *log.Logger, result []response.Idc) (string, string, error) { + language := logger.GetPoint("language").(string) + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + for _, data := range result { + sheetData = append(sheetData, []string{ + //strconv.FormatInt(data.CabinetNum, 10), + data.Name, + data.NameEn, + data.Level, + data.Address, + data.CreateTime, + data.CreatedBy, + data.UpdateTime, + data.UpdatedBy, + }) + } + exportIdcHeader := BaseLogic.ExportIdcHeader + if language == BaseLogic.EN_US { + exportIdcHeader = BaseLogic.ExportIdcHeaderEn + } + if err := e.SetSheetData("Sheet1", exportIdcHeader, sheetData); err != nil { + logger.Warn("create excel error:", err.Error()) + return "", "", err + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + downloadFileName := "idc_list_" + time.Now().Format(BaseLogic.FormatDate) + "_" + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" //生成100000到100000+900000之间的随机数,左闭右开 + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Warn("保存excel到本地失败" + err.Error()) + return "", "", err + } + return fileName, downloadFileName, nil +} + +// 【设备管理】【设备详情】 +func GetIdcInfo(logger *log.Logger, param *requestTypes.QueryIdcRequest) (*response.Idc, error) { + logid := logger.GetPoint("logid").(string) + req := sdkIdcParameters.NewDescribeIdcParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithIdcID(param.IdcID) + logger.Info("DescribeIdc openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Idc.DescribeIdc(req, nil) + logger.Info("DescribeIdc openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warnf("unknown error in Idc.GetIdcInfo:", err.Error()) + return nil, errors.New("unknown error") //未知错误不暴露给用户 + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warnf("Idc.GetIdcInfo error:", respErr.Message) + return nil, errors.New(respErr.Message) + } + if client.Payload.Result == nil || client.Payload.Result.Idc == nil { + return nil, errors.New("idc not found") + } + + obj := buildEntity(client.Payload.Result.Idc, param.Show) + return &obj, nil +} + +// 列表和详情共用方法 +func buildEntity(v *sdkModels.Idc, show string) response.Idc { + obj := response.Idc{} + + obj.Address = v.Address + obj.ID = v.ID + obj.IDcID = v.IDcID + obj.IloUser = v.IloUser + obj.Level = v.Level + obj.Name = v.Name + obj.NameEn = v.NameEn + obj.Shortname = v.Shortname + obj.SwitchUser1 = v.SwitchUser1 + obj.SwitchUser2 = v.SwitchUser2 + obj.CreateTime = util.UtcToTime(v.CreateTime) + obj.CreatedBy = v.CreatedBy + obj.UpdateTime = util.UtcToTime(v.UpdateTime) + obj.UpdatedBy = v.UpdatedBy + + if show == "iloPassword" { + obj.IloPassword = v.IloPassword + obj.SwitchPassword1 = "" + obj.SwitchPassword2 = "" + } + if show == "switchPassword1" { + obj.IloPassword = "" + obj.SwitchPassword1 = v.SwitchPassword1 + obj.SwitchPassword2 = "" + } + if show == "switchPassword2" { + obj.IloPassword = "" + obj.SwitchPassword1 = "" + obj.SwitchPassword2 = v.SwitchPassword2 + } + if show == "iloPassword,switchPassword1,switchPassword2" { + obj.IloPassword = v.IloPassword + obj.SwitchPassword1 = v.SwitchPassword1 + obj.SwitchPassword2 = v.SwitchPassword2 + } + return obj +} + +// 【设备管理】【删除设备】 +func DeleteIdc(logger *log.Logger, param *requestTypes.DeleteIdcRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkIdcParameters.NewDeleteIdcParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithIdcID(param.IdcID) + logger.Info("DeleteIdc openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Idc.DeleteIdc(req, nil) + logger.Info("DeleteIdc openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warnf("unknown error in Idc.DeleteIdc:", err.Error()) + return nil, errors.New("unknown error") //未知错误不暴露给用户 + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warnf("Idc.DeleteIdc error:", respErr.Message) + return nil, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +// 【机型管理】【添加机型】 +func CreateIdc(logger *log.Logger, param *requestTypes.CreateIdcRequest) (*response.CreateIdcResult, error) { + logid := logger.GetPoint("logid").(string) + req := sdkIdcParameters.NewCreateIdcParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + body := sdkModels.CreateIdcRequest{ + Address: param.Address, + NameEn: ¶m.NameEn, + IloPassword: param.IloPassword, + IloUser: param.IloUser, + Level: ¶m.Level, + Name: ¶m.Name, + Shortname: ¶m.Shortname, + SwitchPassword1: param.SwitchPassword1, + SwitchPassword2: param.SwitchPassword2, + SwitchUser1: param.SwitchUser1, + SwitchUser2: param.SwitchUser2, + } + req.WithBody(&body) + logger.Info("CreateIdc openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Idc.CreateIdc(req, nil) + logger.Info("CreateIdc openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warnf("unknown error in Idc.CreateIdc:", err.Error()) + return nil, errors.New("unknown error") //未知错误不暴露给用户 + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warnf("Idc.CreateIdc error:", respErr.Message) + return nil, errors.New(respErr.Message) + } + if client == nil || client.Payload == nil || client.Payload.Result == nil { + return nil, errors.New("add idc info failed") + } + + res := &response.CreateIdcResult{ + IdcId: client.Payload.Result.IdcID, + } + + return res, nil +} + +// 【机型管理】【编辑机型】 +func ModifyIdcInfo(logger *log.Logger, param *requestTypes.ModifyIdcRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkIdcParameters.NewModifyIdcParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithIdcID(param.IdcID) + body := sdkModels.ModifyIdcRequest{ + Address: param.Address, + // CabinetNum: int64(param.CabinetNum), + IloPassword: param.IloPassword, + IloUser: param.IloUser, + Level: param.Level, + Name: param.Name, + NameEn: param.NameEn, + Shortname: param.Shortname, + SwitchPassword1: param.SwitchPassword1, + SwitchPassword2: param.SwitchPassword2, + SwitchUser1: param.SwitchUser1, + SwitchUser2: param.SwitchUser2, + } + req.WithBody(&body) + logger.Info("ModifyIdc openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Idc.ModifyIdc(req, nil) + logger.Info("ModifyIdc openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warnf("unknown error in Idc.ModifyIdc:", err.Error()) + return nil, errors.New("unknown error") //未知错误不暴露给用户 + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warnf("Idc.ModifyIdc error:", respErr.Message) + return nil, errors.New(respErr.Message) + } + if client == nil || client.Payload == nil || client.Payload.Result == nil { + return nil, errors.New("modify idc info failed") + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +// 【机型管理】【安全验证】 +func VerifyUser(logger *log.Logger, param *requestTypes.VerifyUserRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewVerifyUserParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + body := sdkModels.VerifyUserRequest{ + Password: ¶m.Password, + UserName: ¶m.Username, + } + req.WithBody(&body) + logger.Info("VerifyUser openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.User.VerifyUser(req, nil) + logger.Info("VerifyUser openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warnf("unknown error in Idc.VerifyUser:", err.Error()) + return nil, errors.New("unknown error") //未知错误不暴露给用户 + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warnf("Idc.VerifyUser error:", respErr.Message) + return nil, errors.New(respErr.Message) + } + if client == nil || client.Payload == nil || client.Payload.Result == nil { + return nil, errors.New("VerifyUser failed") + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} diff --git a/bmp-operation-api/logic/ImageLogic/ImageLogic.go b/bmp-operation-api/logic/ImageLogic/ImageLogic.go new file mode 100644 index 0000000..ea263e5 --- /dev/null +++ b/bmp-operation-api/logic/ImageLogic/ImageLogic.go @@ -0,0 +1,552 @@ +package ImageLoigc + +import ( + "encoding/json" + "errors" + "fmt" + "math/rand" + "mime/multipart" + "os" + "path" + "strconv" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-operation-api/constant" + + sdkDeviceTypeParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/device_type" + sdkParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/image" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/excel" + sdk "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" + beego "github.com/beego/beego/v2/server/web" +) + +// 【用户管理】【用户列表】 +func DescribeImages(logger *log.Logger, param *requestTypes.QueryImagesRequest) (*response.ImageList, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkParameters.NewDescribeImagesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithImageName(¶m.ImageName) + req.WithDeviceTypeID(¶m.DeviceTypeID) + req.WithIsAll(¶m.IsAll) + req.WithPageSize(¶m.PageSize) + req.WithPageNumber(¶m.PageNumber) + req.WithArchitecture(¶m.Architecture) + req.WithOsType(¶m.OsType) + req.WithSource(¶m.Source) + req.WithImageID(¶m.ImageID) + logger.Info("DescribeImages openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Image.DescribeImages(req, nil) + logger.Info("DescribeImages openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + resp := &response.ImageList{} + if len(client.Payload.Result.Images) == 0 { + resp.Images = make([]response.Image, 0) + return resp, nil + } + for _, v := range client.Payload.Result.Images { + obj := response.Image{} //不能放在外层!!! + obj.ID = v.ID + obj.ImageID = v.ImageID + obj.ImageName = v.ImageName + obj.OsID = v.OsID + obj.Format = v.Format + obj.BootMode = v.BootMode + obj.Filename = v.Filename + obj.URL = v.URL + obj.Hash = v.Hash + obj.Description = v.Description + obj.Source = v.Source + obj.SystemPartition = v.SystemPartition + obj.OsVersion = v.OsVersion + obj.OsType = v.OsType + obj.CreatedBy = v.CreatedBy + obj.CreatedTime = util.UtcToTime(v.CreatedTime) + obj.UpdatedBy = v.UpdatedBy + obj.UpdatedTime = util.UtcToTime(v.UpdatedTime) + obj.Architecture = v.Architecture + obj.SourceName = v.SourceName + obj.IsBind = v.IsBind + obj.DeviceTypeNum = int(v.DeviceTypeNum) + resp.Images = append(resp.Images, obj) + } + resp.PageNumber = client.Payload.Result.PageNumber + resp.PageSize = client.Payload.Result.PageSize + resp.TotalCount = client.Payload.Result.TotalCount + return resp, nil +} + +// 【用户管理】【用户列表】 +func DescribeImage(logger *log.Logger, imageId string) (*response.Image, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkParameters.NewDescribeImageParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithImageID(imageId) + logger.Info("DescribeImage openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Image.DescribeImage(req, nil) + logger.Info("DescribeImage openapi sdk resp:", util.InterfaceToJson(client)) + fmt.Println("sss", err) + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + v := client.Payload.Result.Image + obj := &response.Image{} //不能放在外层!!! + obj.ID = v.ID + obj.ImageID = v.ImageID + obj.ImageName = v.ImageName + obj.OsID = v.OsID + obj.Format = v.Format + obj.BootMode = v.BootMode + obj.Filename = v.Filename + obj.URL = v.URL + obj.Hash = v.Hash + obj.Description = v.Description + obj.Source = v.Source + obj.SystemPartition = v.SystemPartition + obj.OsVersion = v.OsVersion + obj.OsType = v.OsType + obj.CreatedBy = v.CreatedBy + obj.CreatedTime = util.UtcToTime(v.CreatedTime) + obj.UpdatedBy = v.UpdatedBy + obj.UpdatedTime = util.UtcToTime(v.UpdatedTime) + obj.Architecture = v.Architecture + obj.SourceName = v.SourceName + obj.IsBind = v.IsBind + obj.DeviceTypeNum = int(v.DeviceTypeNum) + + return obj, nil +} +func ExportImage(logger *log.Logger, result []response.Image) (string, string, error) { + language := logger.GetPoint("language").(string) + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + for _, data := range result { + if data.SystemPartition != "" { + partition := []response.Partition{} + if err := json.Unmarshal([]byte(data.SystemPartition), &partition); err != nil { + panic(constant.BuildInvalidArgumentWithArgs("系统分区解析json错误", err.Error())) + } + systemPartition := "" + for _, v := range partition { + systemPartition = systemPartition + v.MountPoint + ":" + strconv.Itoa(v.Size/1024) + "GiB," + v.FsType + ";" + } + data.SystemPartition = systemPartition + } + + sheetData = append(sheetData, []string{ + data.ImageName, + data.ImageID, + data.SourceName, + data.Architecture, + data.OsType, + data.OsVersion, + data.Format, + data.BootMode, + data.SystemPartition, + data.Description, + strconv.Itoa(data.DeviceTypeNum), + data.CreatedTime, + }) + } + exportImageHeader := BaseLogic.ExportImageHeader + if language == BaseLogic.EN_US { + exportImageHeader = BaseLogic.ExportImageHeaderEn + } + if err := e.SetSheetData("Sheet1", exportImageHeader, sheetData); err != nil { + logger.Warn("create excel error:", err.Error()) + return "", "", err + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + downloadFileName := "image_list_" + time.Now().Format(BaseLogic.FormatDate) + "_" + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" //生成100000到100000+900000之间的随机数,左闭右开 + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Warn("保存excel到本地失败" + err.Error()) + return "", "", err + } + return fileName, downloadFileName, nil +} + +//【镜像管理】【修改镜像描述】 +func ModifyImage(logger *log.Logger, param *requestTypes.ModifyImageRequest, imageId string) (*response.CommonResponse, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkParameters.NewModifyImageParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithTraceID(logid) + req.WithImageID(imageId) + + body := sdkModels.ModifyImageRequest{ + Description: param.Description, + } + req.WithBody(&body) + + c, err := sdk.SdkClient.Image.ModifyImage(req, nil) + if err != nil { + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warnf("unknown error in ModifyImage:%s", err.Error()) + return nil, errors.New("unknown error") //未知错误不暴露给用户 + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warnf("ModifyImage error:%s", respErr.Message) + return nil, errors.New(respErr.Message) + } + } + + return &response.CommonResponse{ + Success: c.Payload.Result.Success, + }, nil +} + +// 【镜像管理】【删除镜像】 +func DeleteImage(logger *log.Logger, imageId string) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + userId := logger.GetPoint("userId").(string) + reqInfo := sdkParameters.NewDescribeImagesParams() + reqInfo.WithImageID(&imageId) + reqInfo.WithBmpUserID(&userId) + logger.Info("DescribeImages openapi sdk req:", util.InterfaceToJson(reqInfo)) + clientInfo, errInfo := sdk.SdkClient.Image.DescribeImages(reqInfo, nil) + logger.Info("DescribeImages openapi sdk resp:", util.InterfaceToJson(clientInfo)) + if errInfo != nil { + if errInfo != nil { + respErr, b := util.GetOpenapiError(errInfo) + if !b { + logger.Warnf("unknown error in CreateImage:", errInfo.Error()) + return nil, errors.New("unknown error") //未知错误不暴露给用户 + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warnf("DeleteImage error:", respErr.Message) + return nil, errors.New(respErr.Message) + } + } + + req := sdkParameters.NewDeleteImageParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + req.WithBmpUserID(&userId) + req.WithImageID(imageId) + logger.Info("DeleteImage openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Image.DeleteImage(req, nil) + logger.Info("DeleteImage openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil { + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warnf("unknown error in CreateImage:", err.Error()) + return nil, errors.New("unknown error") //未知错误不暴露给用户 + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warnf("DeleteImage error:", respErr.Message) + return nil, errors.New(respErr.Message) + } + } + res := &response.CommonResponse{} + if client.Payload.Result.Success { + arr := strings.Split(clientInfo.Payload.Result.Images[0].URL, "/") + if len(arr) >= 2 { + fileName := arr[len(arr)-1] + uploadPath, _ := beego.AppConfig.String("upload.path") + if err := os.Remove(uploadPath + "/" + fileName); err != nil { + return nil, nil //即便删除文件失败,也不报错 errors.New("删除上传的镜像文件失败") + } + } + res.Success = true + } else { + res.Success = false + } + return res, nil +} +func UploadImage(logger *log.Logger, param *requestTypes.UploadImageRequest, header *multipart.FileHeader, requestId string) (*response.ImageUpload, error) { + //fmt.Println("文件大小", header.Size, util.GetMd5("qq123"), util.GetMd5("./log/test.txt"), util.Md5sum("./log/test.txt")) + //os.Exit(1) + //if header.Size > 16*1024 { //16K + // logger.Warn("file large exceed, size:", header.Size) + // return "", errors.New("文件大小超出范围") + //} + arr := strings.Split(header.Filename, ".") + //suffix := strings.ToLower(arr[len(arr)-1]) + suffix := strings.ToLower(arr[len(arr)-2]) + "." + strings.ToLower(arr[len(arr)-1]) + fmt.Println(suffix) + //AvailableSuffix := []string{"qcow2", "xz"} + if suffix != "tar.xz" && strings.ToLower(arr[len(arr)-1]) != "qcow2" { //util.InArray(suffix, AvailableSuffix) { + logger.Warn("file format not support:", suffix) + return nil, errors.New("文件类型不符合,必须是tar.xz或者qcow2类型") + } else { + if strings.ToLower(arr[len(arr)-1]) == "qcow2" { + suffix = "qcow2" + } else { + suffix = "tar" + } + } + dir, err := util.GetBaseDir() + if err != nil { + logger.Warn("获取当前根目录失败" + err.Error()) + return nil, err + } + uploadPath, _ := beego.AppConfig.String("upload.path") + util.CreateDirIfNotExist(uploadPath) //如果目录不存在,创建一个目录 + localFileName := path.Join(dir, uploadPath, requestId+"_"+header.Filename) //prefix+"-"+header.Filename + if err = util.SaveToLocal(localFileName, param.ImageFile); err != nil { + logger.Warn("保存excel到本地失败" + err.Error()) + return nil, err + } + imageUrl, _ := beego.AppConfig.String("image.url") + res := &response.ImageUpload{ + Format: suffix, + FileName: header.Filename, + Url: imageUrl + requestId + "_" + header.Filename, + Hash: util.Md5sum(localFileName), + } + return res, nil +} + +// 【镜像管理】【上传镜像】 +func CreateImage(logger *log.Logger, param *requestTypes.CreateImageRequest) (response.ImageId, error) { + logid := logger.GetPoint("logid").(string) + req := sdkParameters.NewCreateImageParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := sdkModels.CreateImageRequest{ + ImageName: ¶m.ImageName, + Architecture: ¶m.Architecture, + OsType: ¶m.OsType, + Version: ¶m.Version, + Format: ¶m.Format, + BootMode: ¶m.BootMode, + Filename: ¶m.FileName, + URL: ¶m.Url, + Hash: ¶m.Hash, + Source: BaseLogic.USER_DEFINED, //用户上传的,默认是自定义镜像 + Description: param.Description, + SystemPartition: param.SystemPartition, + DataPartition: param.DataPartition, + } + req.WithBody(&body) + logger.Info("CreateImage openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Image.CreateImage(req, nil) + logger.Info("CreateImage openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warnf("unknown error in CreateImage:", err.Error()) + return response.ImageId{}, errors.New("unknown error") //未知错误不暴露给用户 + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warnf("CreateImage error:", respErr.Message) + return response.ImageId{}, errors.New(respErr.Message) + } + if client == nil || client.Payload == nil || client.Payload.Result == nil { + return response.ImageId{}, errors.New("create image failed") + } + return response.ImageId{ + ImageId: client.Payload.Result.ImageID, + }, nil +} + +func DescribeImageDeviceTypes(logger *log.Logger, param *requestTypes.QueryImageDeviceTypesRequest) (*response.DeviceTypePage, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkParameters.NewDescribeImageDeviceTypesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithIsAll(¶m.IsAll) + req.WithPageSize(¶m.PageSize) + req.WithPageNumber(¶m.PageNumber) + req.WithArchitecture(¶m.Architecture) + req.WithImageID(param.ImageID) + req.WithIsBind(¶m.IsBind) + logger.Info("DescribeImageDeviceTypes openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Image.DescribeImageDeviceTypes(req, nil) + logger.Info("DescribeImageDeviceTypes openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + resp := &response.DeviceTypePage{} + if len(client.Payload.Result.DeviceTypes) == 0 { + resp.DeviceTypes = make([]response.DeviceType, 0) + return resp, nil + } + for _, v := range client.Payload.Result.DeviceTypes { + obj := response.DeviceType{} //不能放在外层!!! + obj.DeviceTypeID = v.DeviceTypeID + obj.Name = v.Name + obj.IDcID = v.IDcID + obj.IdcName = v.IDcName + obj.IdcNameEn = v.IDcNameEn + obj.DeviceType = v.DeviceType + obj.Architecture = v.Architecture + obj.BootMode = v.BootMode + obj.DeviceSeries = v.DeviceSeries + obj.DeviceSeriesName = v.DeviceSeriesName + obj.Description = v.Description + + obj.CreatedBy = v.CreatedBy + obj.CreatedTime = util.UtcToTime(v.CreatedTime) + obj.UpdatedBy = v.UpdatedBy + obj.UpdatedTime = util.UtcToTime(v.UpdatedTime) + obj.Architecture = v.Architecture + + obj.InstanceStatus = v.InstanceStatus + + resp.DeviceTypes = append(resp.DeviceTypes, obj) + } + resp.PageNumber = client.Payload.Result.PageNumber + resp.PageSize = client.Payload.Result.PageSize + resp.TotalCount = client.Payload.Result.TotalCount + return resp, nil +} +func AssociatedDeviceType(logger *log.Logger, param *requestTypes.AssociateImageDeviceTypeRequest) (bool, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkParameters.NewAssociatedDeviceTypeParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + array := []string{} + if len(param.DeviceTypeIDs) != 0 { + array = strings.Split(param.DeviceTypeIDs, ",") + } + body := sdkModels.AssociateDeviceTypeRequest{ + ImageID: ¶m.ImageId, + DeviceTypeIDs: array, + } + req.WithBody(&body) + logger.Info("AssociatedDeviceType openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Image.AssociatedDeviceType(req, nil) + logger.Info("AssociatedDeviceType openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + return client.Payload.Result.Success, err +} + +func DissociatedDeviceType(logger *log.Logger, param *requestTypes.DisassociateDeviceTypeImageRequest) (bool, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkParameters.NewDissociatedDeviceTypeParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + body := sdkModels.DissociatedImageRequest{ + DeviceTypeID: ¶m.DeviceTypeID, + ImageID: ¶m.ImageId, + } + req.WithBody(&body) + logger.Info("DissociatedDeviceType openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Image.DissociatedDeviceType(req, nil) + logger.Info("DissociatedDeviceType openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + return client.Payload.Result.Success, err +} + +func QueryImagesByDeviceType(logger *log.Logger, param requestTypes.QueryImagesByDeviceTypeRequest) (map[string][]*sdkModels.Image, error) { + + logid := logger.GetPoint("logid").(string) + userId := logger.GetPoint("userId").(string) + req := sdkDeviceTypeParameters.NewDescribeDeviceTypeImagesParams() + req.WithTraceID(logid) + req.WithBmpUserID(&userId) + req.WithDeviceTypeID(¶m.DeviceTypeID) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + // req.WithIdcID(¶m.IdcID) + logger.Info("DescribeImages openapi request:", util.InterfaceToJson(req)) + responseApi, err := sdk.SdkClient.DeviceType.DescribeDeviceTypeImages(req, nil) + logger.Info("DescribeImages openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeImages openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + res := map[string][]*sdkModels.Image{} + images := responseApi.Payload.Result.Images + for _, v := range images { + if _, ok := res[v.OsType]; !ok { + res[v.OsType] = []*sdkModels.Image{v} + } else { + res[v.OsType] = append(res[v.OsType], v) + } + } + return res, nil +} diff --git a/bmp-operation-api/logic/InstanceLogic/InstanceLogic.go b/bmp-operation-api/logic/InstanceLogic/InstanceLogic.go new file mode 100644 index 0000000..8b58fa7 --- /dev/null +++ b/bmp-operation-api/logic/InstanceLogic/InstanceLogic.go @@ -0,0 +1,647 @@ +package InstanceLogic + +import ( + // "errors" + + "errors" + "fmt" + "strconv" + "strings" + + sdkInstanceParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/instance" + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + sdk "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" +) + +// 【设备管理】【开机】 +func StartInstance(logger *log.Logger, param *requestTypes.StartInstanceRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkInstanceParameters.NewStartProjectInstanceParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithInstanceID(param.InstanceID) + logger.Info("StartProjectInstance openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Instance.StartProjectInstance(req, nil) + logger.Info("StartProjectInstance openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +// 【设备管理】【重启】 +func RestartInstance(logger *log.Logger, param *requestTypes.RestartInstanceRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkInstanceParameters.NewRestartProjectInstanceParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithInstanceID(param.InstanceID) + logger.Info("RestartProjectInstance openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Instance.RestartProjectInstance(req, nil) + logger.Info("RestartProjectInstance openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +// 【设备管理】【关机】 +func StopInstance(logger *log.Logger, param *requestTypes.StopInstanceRequest) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkInstanceParameters.NewStopProjectInstanceParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithInstanceID(param.InstanceID) + logger.Info("StopProjectInstance openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Instance.StopProjectInstance(req, nil) + logger.Info("StopProjectInstance openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +// 【设备管理 +func ResetInstanceStatus(logger *log.Logger, instanceId string) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkInstanceParameters.NewResetInstanceStatusParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithInstanceID(instanceId) + logger.Info("ResetInstanceStatus openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Instance.ResetInstanceStatus(req, nil) + logger.Info("ResetInstanceStatus openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +// 【设备管理】【关机】 +func DeleteInstance(logger *log.Logger, instanceId string) (*response.CommonResponse, error) { + logid := logger.GetPoint("logid").(string) + req := sdkInstanceParameters.NewDeleteProjectInstanceParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithInstanceID(instanceId) + logger.Info("DeleteProjectInstance openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Instance.DeleteProjectInstance(req, nil) + logger.Info("DeleteProjectInstance openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +func LockInstance(logger *log.Logger, instanceId string) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewLockProjectInstanceParams() + request.WithInstanceID(instanceId) + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("lockinstance openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.LockProjectInstance(request, nil) + logger.Info("lockinstance openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("lockinstance openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + return responseApi.Payload.Result.Success, nil +} + +func UnLockInstance(logger *log.Logger, instanceId string) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewUnLockProjectInstanceParams() + request.WithInstanceID(instanceId) + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("unlockinstance openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.UnLockProjectInstance(request, nil) + logger.Info("unlockinstance openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("lockinstance openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + return responseApi.Payload.Result.Success, nil +} + +// 【设备管理】【批量开机】 +func StartInstances(logger *log.Logger, instanceIDs []string) (bool, error) { + logid := logger.GetPoint("logid").(string) + req := sdkInstanceParameters.NewStartInstancesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := sdkModels.StartInstancesRequest{ + InstanceIds: instanceIDs, + } + req.WithBody(&body) + + logger.Info("StartInstances StartInstances openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Instance.StartInstances(req, nil) + logger.Info("StartInstances StartInstances openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return true, nil +} + +// 【设备管理】【批量关机】 +func StopInstances(logger *log.Logger, instanceIDs []string) (bool, error) { + logid := logger.GetPoint("logid").(string) + req := sdkInstanceParameters.NewStopInstancesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := sdkModels.StopInstancesRequest{ + InstanceIds: instanceIDs, + } + req.WithBody(&body) + + logger.Info("StopInstances openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Instance.StopInstances(req, nil) + logger.Info("StopInstances openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return true, nil +} + +// 【设备管理】【批量重启】 +func RestartInstances(logger *log.Logger, instanceIDs []string) (bool, error) { + logid := logger.GetPoint("logid").(string) + req := sdkInstanceParameters.NewRestartInstancesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := sdkModels.RestartInstancesRequest{ + InstanceIds: instanceIDs, + } + req.WithBody(&body) + + logger.Info("RestartInstances openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Instance.RestartInstances(req, nil) + logger.Info("RestartInstances openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return true, nil +} + +// 【设备管理】【批量编辑实例名称】 +func ModifyInstances(logger *log.Logger, instanceIDs []string, instanceName string) (bool, error) { + logid := logger.GetPoint("logid").(string) + req := sdkInstanceParameters.NewModifyInstancesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := sdkModels.ModifyInstancesRequest{ + InstanceIDs: instanceIDs, + InstanceName: instanceName, + } + req.WithBody(&body) + + logger.Info("ModifyInstances openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Instance.ModifyInstances(req, nil) + logger.Info("ModifyInstances openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return true, nil +} + +// 【设备管理】【批量删除】 +func DeleteInstances(logger *log.Logger, instanceIDs []string) (bool, error) { + logid := logger.GetPoint("logid").(string) + req := sdkInstanceParameters.NewDeleteInstancesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := sdkModels.DeleteInstancesRequest{ + InstanceIDs: instanceIDs, + } + req.WithBody(&body) + + logger.Info("DeleteInstances openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Instance.DeleteInstances(req, nil) + logger.Info("DeleteInstances openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return true, nil +} + +func ResetInstancePassword(logger *log.Logger, instanceId string, password string) (bool, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewResetProjectInstancePasswdParams() + request.WithInstanceID(instanceId) + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + body := sdkModels.ResetInstancePasswdRequest{ + Password: password, + } + request.WithBody(&body) + + logger.Info("ResetProjectInstancePasswd openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.ResetProjectInstancePasswd(request, nil) + logger.Info("ResetProjectInstancePasswd openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("ResetProjectInstancePasswd openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + return responseApi.Payload.Result.Success, nil +} + +func ResetInstancesPassword(logger *log.Logger, instanceIds []string, password string) (bool, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewResetProjectInstancesPasswdParams() + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + body := sdkModels.ResetInstancesPasswdRequest{ + Password: password, + InstanceIDs: instanceIds, + } + request.WithBody(&body) + + logger.Info("ResetProjectInstancesPasswd openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.ResetProjectInstancesPasswd(request, nil) + logger.Info("ResetProjectInstancesPasswd openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("ResetProjectInstancesPasswd openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + return responseApi.Payload.Result.Success, nil +} + +//ReinstallInstance sdk重装 +func ReinstallInstance(logger *log.Logger, param requestTypes.ReinstallInstanceRequest) (bool, error) { + + logid := logger.GetPoint("logid").(string) + + req := sdkInstanceParameters.NewReinstallProjectInstanceParams() + req.WithTraceID(logid) + req.WithBody(¶m.ReinstallInstanceRequest) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithInstanceID(param.InstanceId) + logger.Info("ReinstallProjectInstance openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Instance.ReinstallProjectInstance(req, nil) + logger.Info("ReinstallProjectInstance openapi response:", util.InterfaceToJson(responseApi)) + fmt.Println("ReinstallProjectInstance openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("ReinstallProjectInstance openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil +} + +func DescribeInstance(logger *log.Logger, param requestTypes.QueryInstanceRequest) (*response.InstanceInfo, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkInstanceParameters.NewDescribeProjectInstanceParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + request.WithInstanceID(param.InstanceId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("DescribeProjectInstance openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Instance.DescribeProjectInstance(request, nil) + logger.Info("DescribeProjectInstance openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeProjectInstance openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + obj := response.Instance{} + v := responseApi.Payload.Result.Instance + + obj = SdkInstance2RespInstance(logger, *v) + + return &response.InstanceInfo{ + Instance: obj, + }, nil +} + +func SdkInstance2RespInstance(logger *log.Logger, v sdkModels.Instance) response.Instance { + /* + CPU:Intel E5-2650V4(2*12物理核,2.2GHz) + 内存:256GB DDR4 + 系统盘:300GB (2*300GB SAS, RAID1) + 数据盘:72TB (12*6TB SATA, NO RAID) + 网卡:2*25GE + GPU:P40*4 + */ + //cputpl := "%s %s (%d*%d物理核, %sGHz)" + //memtpl := "%dGB %s %dGHZ" + //systemtpl := "%dGB(%dGB %s %s*%d,%s)" + //datatpl := "%dGB(%dGB %s %s*%d,%s)" + //nictpl := "%d*%dGE" + //gputpl := "%s %s*%d" + language := logger.GetPoint("language").(string) + //if language == constants.LANGUAGE_EN { + // cputpl = "%s %s (%d*%dcores, %sGHz)" + //} + + //raidMap := make(map[string]response.DeviceTypeRaid) // 请求一次,避免循环请求 + + // raid, _ := raidLogic.QueryRaid(logger, v.SystemVolumeRaidID) + // raidStr := "" + // if raid != nil { + // raidStr = raid.Name + // } + + cpu_ := strconv.Itoa(int(v.CPUAmount)) + "*" + strconv.Itoa(int(v.CPUCores)) + "物理核," + v.CPUFrequency + "GHz" + if language == BaseLogic.EN_US { + cpu_ = strconv.Itoa(int(v.CPUAmount)) + "*" + strconv.Itoa(int(v.CPUCores)) + "cores," + v.CPUFrequency + "GHz" + } + mem_ := strconv.Itoa(int(v.MemAmount)*int(v.MemSize)) + "GB(" + strconv.Itoa(int(v.MemSize)) + "GB*" + strconv.Itoa(int(v.MemAmount)) + ")" + v.MemType + " " + strconv.Itoa(int(v.MemFrequency)) + "MHz" + //系统盘:显示总容量 (单块容量 接口类型 类型*数量 RAID 模式) + //240GB 240GB SATA SSD*2 RAID1 + _svcap := int(v.SystemVolumeAmount) * int(v.SystemVolumeSize) + if strings.ToUpper(v.SystemVolumeRaidName) == "RAID1" { + _svcap = _svcap / 2 + } + sv_, systemVolumeType := GetSystemDiskDetailByRaid(logger, v.InstanceVolumeRaids) + // 显示品牌 显卡型号 个数,例 NVIDIA P40 * 4 + gpu_ := v.GpuManufacturer + " " + v.GpuModel + "*" + strconv.Itoa(int(v.GpuAmount)) + if v.GpuAmount == 0 { + gpu_ = "" + } + nicInfo := strconv.Itoa(int(v.NicAmount)) + "*" + strconv.Itoa(int(v.NicRate)) + "GE" + v.SystemVolumeType = systemVolumeType + return response.Instance{ + Instance: v, + CpuInfo: cpu_, + MemInfo: mem_, + SystemInfo: sv_, + NicInfo: nicInfo, + GpuInfo: gpu_, + } +} + +func Trim(str string) string { + s := strings.TrimRight(str, "0") + s = strings.TrimRight(s, ".") + return s +} + +func GetSystemDiskDetailByRaid(logger *log.Logger, ivr []*sdkModels.InstanceVolumeRaid) (string, string) { + + volumeDetail := "" + + systemVolumeType := "" + + for _, vr := range ivr { + if vr.Volume.VolumeType == "system" { + + v := vr.Volume + systemVolumeType = v.DiskType + + // avaliableValue := .0 + all := 0.0 + volumeSize, _ := strconv.ParseFloat(v.VolumeSize, 64) + size := volumeSize + all = volumeSize * float64(v.VolumeAmount) + if vr.Raid != nil { + if util.InArray(vr.Raid.Name, []string{"RAID1", "RAID10"}) { + all = all / 2 + } else if util.InArray(vr.Raid.Name, []string{"RAID51H"}) { + all = volumeSize * float64(v.VolumeAmount-2) + } else if util.InArray(vr.Raid.Name, []string{"RAID5"}) { + all = volumeSize * float64(v.VolumeAmount-1) + } + + } + var allStr, sizeStr string + if v.VolumeUnit == "TB" { //保留两位小数 + allStr = strconv.FormatFloat(all, 'f', 2, 64) + sizeStr = strconv.FormatFloat(size, 'f', 2, 64) + } else { //不保留小数 + allStr = strconv.Itoa(int(all)) + sizeStr = strconv.Itoa(int(size)) + + } + + volumeDetail = allStr + v.VolumeUnit + "(" + + (strconv.Itoa(int(v.VolumeAmount)) + "*" + sizeStr + v.VolumeUnit) + " " + v.InterfaceType + ")" + + } else { + continue + } + } + + //NVME另外算法 TODO + return volumeDetail, systemVolumeType + +} diff --git a/bmp-operation-api/logic/KeypairLoigc/KeypairLoigc.go b/bmp-operation-api/logic/KeypairLoigc/KeypairLoigc.go new file mode 100644 index 0000000..9014d0c --- /dev/null +++ b/bmp-operation-api/logic/KeypairLoigc/KeypairLoigc.go @@ -0,0 +1,92 @@ +package KeypairLoigc + +import ( + "errors" + + "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + + sdkSshkeyParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/sshkey" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" +) + +func DescribeKeypairs(logger *log.Logger, param requestTypes.QueryKeypairsRequest) (*response.KeyPairsResponse, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkSshkeyParameters.NewDescribeUserSSHKeysParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + if param.Name != "" { + req.WithName(¶m.Name) + } + pageNumber := param.PageNumber + pageSize := param.PageSize + if pageNumber != 0 { + req.WithPageNumber(&pageNumber) + } + if pageSize != 0 { + req.WithPageSize(&pageSize) + } + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("describekeypairs openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.Sshkey.DescribeUserSSHKeys(req, nil) + logger.Info("describekeypairs openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("describekeypairs openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + resp := response.KeyPairsResponse{} + resp.PagingResponse.PageNumber = responseApi.Payload.Result.PageNumber + resp.PagingResponse.PageSize = responseApi.Payload.Result.PageSize + resp.PagingResponse.TotalCount = responseApi.Payload.Result.TotalCount + + obj := response.KeyPair{} + for _, v := range responseApi.Payload.Result.Sshkeys { + + obj.Name = v.Name + obj.KeypairId = v.SshkeyID + + req := sdkSshkeyParameters.NewGetInstancesBySshkeyParams() + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithSshkeyID(v.SshkeyID) + req.WithBmpLanguage(&language) + logger.Info("getInstancesBySshkey openapi request:", util.InterfaceToJson(req)) + respInstance, _ := openApi.SdkClient.Sshkey.GetInstancesBySshkey(req, nil) + logger.Info("getInstancesBySshkey openapi response:", util.InterfaceToJson(respInstance)) + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warn("getInstancesBySshkey openapi error:", err.Error()) + } + logger.Warn("getInstancesBySshkey openapi error:", respErr.Message) + } + obj.IsCheckDelete = "yes" + if len(respInstance.Payload.Result.InstanceIds) != 0 { + // for _, value := range respInstance.Result.Instances { + // if value.Status == "creating" || value.Status == "reinstalling" { + // logger.Info("list keypair "+v.KeypairId+" is using by instance:", value.InstanceId) + // obj.IsCheckDelete = "no" + // break + // } + // } + obj.IsCheckDelete = "no" + } + obj.FingerPrint = v.FingerPrint + obj.CreatedTime = v.CreatedTime + obj.UpdatedTime = v.UpdatedTime + resp.Keypairs = append(resp.Keypairs, obj) + + } + + return &resp, nil +} diff --git a/bmp-operation-api/logic/OsLogic/OsLogic.go b/bmp-operation-api/logic/OsLogic/OsLogic.go new file mode 100644 index 0000000..e93ebe4 --- /dev/null +++ b/bmp-operation-api/logic/OsLogic/OsLogic.go @@ -0,0 +1,62 @@ +package OsLogic + +import ( + "errors" + + sdkParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/os" + sdk "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" +) + +// 【raid列表】 +func DescribeOSs(logger *log.Logger, param *requestTypes.QueryOssRequest) (*response.OsList, error) { + userId := logger.GetPoint("userId").(string) + logid := logger.GetPoint("logid").(string) + req := sdkParameters.NewDescribeOSsParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + req.WithBmpUserID(&userId) + req.WithOsType(¶m.OsType) + req.WithOsName(¶m.OsName) + req.WithOsVersion(¶m.OsVersion) + //req.WithPlatform(¶m.Platform) + req.WithIsAll(¶m.IsAll) + logger.Info("DescribeOSs openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Os.DescribeOSs(req, nil) + logger.Info("DescribeOSs openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + //if len(result.Payload.Result.Oss) == 0 { + // return nil, errors.New("Oss not found") + //} + resp := response.OsList{} + + for _, v := range client.Payload.Result.Oss { + obj := response.Os{} + obj.ID = v.ID + obj.OsID = v.OsID + obj.OsName = v.OsName + obj.OsType = v.OsType + obj.OsVersion = v.OsVersion + obj.Architecture = v.Architecture + obj.Bits = int(v.Bits) + obj.SysUser = v.SysUser + obj.CreatedTime = util.UtcToTime(v.CreatedTime) + obj.UpdatedTime = util.UtcToTime(v.UpdatedTime) + obj.CreatedBy = v.CreatedBy + obj.UpdatedBy = v.UpdatedBy + resp.Oss = append(resp.Oss, &obj) + } + return &resp, nil +} diff --git a/bmp-operation-api/logic/PartitionLogic/PartitionLogic.go b/bmp-operation-api/logic/PartitionLogic/PartitionLogic.go new file mode 100644 index 0000000..1a6cc6b --- /dev/null +++ b/bmp-operation-api/logic/PartitionLogic/PartitionLogic.go @@ -0,0 +1,40 @@ +package PartitionLogic + +import ( + "errors" + + "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" + + sdkDeviceTypeParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/device_type" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +func QueryDefaultSystemPartitions(logger *log.Logger, param requestTypes.QueryDefaultSystemPartitionRequest) ([]*sdkModels.Partition, error) { + + // language := logger.GetPoint("language").(string) + logid := logger.GetPoint("logid").(string) + request := sdkDeviceTypeParameters.NewDescribeDeviceTypeImagePartitionsParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + request.WithImageID(¶m.ImageID) + request.WithDeviceTypeID(¶m.DeviceTypeID) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("QueryDeviceTypeImagePartition openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.DeviceType.DescribeDeviceTypeImagePartitions(request, nil) + logger.Info("QueryDeviceTypeImagePartition openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("QueryDeviceTypeImagePartition openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + return responseApi.Payload.Result.SystemPartition, nil + +} diff --git a/bmp-operation-api/logic/RaidLogic/RaidLogic.go b/bmp-operation-api/logic/RaidLogic/RaidLogic.go new file mode 100644 index 0000000..27e2e5a --- /dev/null +++ b/bmp-operation-api/logic/RaidLogic/RaidLogic.go @@ -0,0 +1,114 @@ +package RaidLogic + +import ( + "errors" + + sdkParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/raid" + sdk "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + responseTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" + + sdkDeviceTypeParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/device_type" + sdkRaidParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/raid" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// 【raid列表】 +func QueryRaidsAll(logger *log.Logger) (*response.RaidList, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkParameters.NewDescribeRaidsParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + logger.Info("DescribeRaids openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Raid.DescribeRaids(req, nil) + logger.Info("DescribeRaids openapi sdk resp:", util.InterfaceToJson(client)) + + resp := response.RaidList{} + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + for _, v := range client.Payload.Result.Raids { + obj := &response.Raid{} + obj.RaidID = v.RaidID + obj.Name = v.Name + + obj.DescriptionZh = v.DescriptionZh + obj.DescriptionEn = v.DescriptionEn + + //obj.AvailableValue = int(v.AvailableValue) + + resp.Raids = append(resp.Raids, obj) + } + return &resp, nil +} + +func QueryRaids(logger *log.Logger, param requestTypes.QueryRaidsRequest) ([]responseTypes.DeviceTypeRaid, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkDeviceTypeParameters.NewDescribeDeviceTypeRaidsParams() + request.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithDeviceTypeID(¶m.DeviceTypeID) + request.WithVolumeType(¶m.VolumeType) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + //request.SetOsType(param.ImageType) + logger.Info("DescribeDeviceTypeRaids openapi request:", util.InterfaceToJson(request)) + responseApi, err := sdk.SdkClient.DeviceType.DescribeDeviceTypeRaids(request, nil) + logger.Info("DescribeDeviceTypeRaids openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeDeviceTypeRaids openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + res := []responseTypes.DeviceTypeRaid{} + + rdeviceTypeRaids := responseApi.Payload.Result + for _, v := range rdeviceTypeRaids { + request := sdkRaidParameters.NewDescribeRaidParams() + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + request.WithRaidID(v.RaidID) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + responseApi, err := sdk.SdkClient.Raid.DescribeRaid(request, nil) + if err != nil { + logger.Info("DescribeRaid openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + res = append(res, SdkRDeviceTypeRaid2Raid(v, responseApi.Payload.Result.Name)) + + } + return res, nil +} + +func SdkRDeviceTypeRaid2Raid(v *sdkModels.RDeviceTypeRaid, raidName string) responseTypes.DeviceTypeRaid { + res := responseTypes.DeviceTypeRaid{ + RDeviceTypeRaid: *v, + RaidName: raidName, + } + + return res +} diff --git a/bmp-operation-api/logic/RoleLogic/RoleLogic.go b/bmp-operation-api/logic/RoleLogic/RoleLogic.go new file mode 100644 index 0000000..0220a13 --- /dev/null +++ b/bmp-operation-api/logic/RoleLogic/RoleLogic.go @@ -0,0 +1,96 @@ +package RoleLogic + +import ( + "errors" + + sdkParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/role" + sdk "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" +) + +// 【raid列表】 +func DescribeRoles(logger *log.Logger, param *requestTypes.DescribeRolesRequest) (*response.RoleList, error) { + userId := logger.GetPoint("userId").(string) + logid := logger.GetPoint("logid").(string) + req := sdkParameters.NewDescribeRolesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + req.WithBmpUserID(&userId) + req.WithIsAll(¶m.IsAll) + logger.Info("DescribeRoles openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Role.DescribeRoles(req, nil) + logger.Info("DescribeRoles openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + logger.Info("openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + //if len(result.Payload.Result.Oss) == 0 { + // return nil, errors.New("Oss not found") + //} + resp := response.RoleList{} + + for _, v := range client.Payload.Result.Roles { + obj := response.Role{} + + obj.RoleID = v.RoleID + obj.DescriptionEn = v.DescriptionEn + obj.DescriptionCn = v.DescriptionCn + obj.RoleNameEn = v.RoleNameEn + obj.RoleNameCn = v.RoleNameCn + obj.RoleName = v.RoleName + obj.Permission = v.Permission + obj.UserCount = int(v.UserCount) + obj.CreatedTime = util.UtcToTime(v.CreatedTime) + obj.UpdatedTime = util.UtcToTime(v.UpdatedTime) + obj.CreatedBy = v.CreatedBy + obj.UpdatedBy = v.UpdatedBy + resp.Roles = append(resp.Roles, &obj) + } + resp.PageNumber = client.Payload.Result.PageNumber + resp.PageSize = client.Payload.Result.PageSize + resp.TotalCount = client.Payload.Result.TotalCount + return &resp, nil +} + +func CurrentRole(logger *log.Logger) (*response.Role, error) { + userId := logger.GetPoint("userId").(string) + logid := logger.GetPoint("logid").(string) + req := sdkParameters.NewCurrentRoleParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + req.WithBmpUserID(&userId) + logger.Info("CurrentRole openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Role.CurrentRole(req, nil) + logger.Info("CurrentRole openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil || client.Payload == nil { + return nil, err + } + o := client.Payload.Result.Role + + r := &response.Role{ + RoleName: o.RoleName, + Permission: o.Permission, + RoleNameEn: o.RoleNameEn, + RoleNameCn: o.RoleNameCn, + RoleID: o.RoleID, + DescriptionEn: o.DescriptionEn, + DescriptionCn: o.DescriptionCn, + CreatedBy: o.CreatedBy, + CreatedTime: o.CreatedTime, + UpdatedBy: o.UpdatedBy, + UpdatedTime: o.UpdatedTime, + } + + return r, nil +} diff --git a/bmp-operation-api/logic/TimezoneLogic/TimezoneLogic.go b/bmp-operation-api/logic/TimezoneLogic/TimezoneLogic.go new file mode 100644 index 0000000..82cf8cc --- /dev/null +++ b/bmp-operation-api/logic/TimezoneLogic/TimezoneLogic.go @@ -0,0 +1,245 @@ +package TimezoneLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-operation-api/constant" + responseTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + log "git.jd.com/cps-golang/log" +) + +var TimeZoneDictZh responseTypes.OrderedJsonDict = responseTypes.OrderedJsonDict{ + M: map[string]string{ + "Pacific/Pago_Pago": "(GMT-11:00)帕果帕果", + "US/Hawaii": "(GMT-10:00)夏威夷时间", + "US/Pacific": "(GMT-08:00)太平洋时间", + "America/Tijuana": "(GMT-08:00)太平洋时间-提华纳", + "US/Mountain": "(GMT-07:00)山区时间", + "US/Arizona": "(GMT-07:00)山区时间-亚利桑那州", + "America/Chihuahua": "(GMT-07:00)山区时间-奇瓦瓦,马萨特兰", + "US/Central": "(GMT-07:00)中部时间", + "America/Mexico_City": "(GMT-06:00)中部时间-墨西哥城", + "America/Regina": "(GMT-06:00)中部时间-里贾纳", + "America/Guatemala": "(GMT-06:00)中部时间-里贾纳", + "America/Bogota": "(GMT-05:00)波哥大", + "US/Eastern": "(GMT-05:00)东部时间", + "America/Lima": "(GMT-05:00)利马", + "America/Caracas": "(GMT-04:30)加拉加斯", + "America/Halifax": "(GMT-04:00)大西洋时间-哈利法克斯", + "America/Guyana": "(GMT-04:00)圭亚那", + "America/La_Paz": "(GMT-04:00)拉巴斯", + "America/Buenos_Aires": "(GMT-03:00)布宜诺斯艾利斯", + "America/Godthab": "(GMT-03:00)戈特霍布", + "America/Montevideo": "(GMT-03:00)蒙得维的亚", + "Canada/Newfoundland": "(GMT-03:30)纽芬兰时间-圣约翰", + "America/Santiago": "(GMT-03:00)圣地亚哥", + "America/Sao_Paulo": "(GMT-02:00)圣保罗", + "Atlantic/South_Georgia": "(GMT-02:00)南乔治亚州", + "Atlantic/Azores": "(GMT-01:00)亚速尔群岛", + "Atlantic/Cape_Verde": "(GMT-01:00)佛得角", + "Africa/Casablanca": "(GMT+00:00)卡萨布兰卡", + "Europe/Dublin": "(GMT+00:00)都柏林", + "Europe/Lisbon": "(GMT+00:00)里斯本", + "Europe/London": "(GMT+00:00)伦敦", + "Africa/Monrovia": "(GMT+00:00)蒙罗维亚", + "Africa/Algiers": "(GMT+01:00)阿尔及尔", + "Europe/Amsterdam": "(GMT+01:00)阿姆斯特丹", + "Europe/Berlin": "(GMT+01:00)柏林", + "Europe/Brussels": "(GMT+01:00)布鲁塞尔", + "Europe/Budapest": "(GMT+01:00)布达佩斯", + "Europe/Belgrade": "(GMT+01:00)中欧时间-贝尔格莱德", + "Europe/Prague": "(GMT+01:00)中欧时间-布拉格", + "Europe/Copenhagen": "(GMT+01:00)哥本哈根", + "Europe/Madrid": "(GMT+01:00)马德里", + "Europe/Paris": "(GMT+01:00)巴黎", + "Europe/Rome": "(GMT+01:00)罗马", + "Europe/Stockholm": "(GMT+01:00)斯德哥尔摩", + "Europe/Vienna": "(GMT+01:00)维也纳", + "Europe/Warsaw": "(GMT+01:00)华沙", + "Europe/Athens": "(GMT+02:00)雅典", + "Europe/Bucharest": "(GMT+02:00)布加勒斯特", + "Africa/Cairo": "(GMT+02:00)开罗", + "Europe/Helsinki": "(GMT+02:00)赫尔辛基", + "Asia/Jerusalem": "(GMT+02:00)耶路撒冷", + "Africa/Johannesburg": "(GMT+02:00)约翰内斯堡", + "Europe/Kiev": "(GMT+02:00)基辅", + "Europe/Kaliningrad": "(GMT+02:00)莫斯科-加里宁格勒", + "Europe/Riga": "(GMT+02:00)里加", + "Europe/Sofia": "(GMT+02:00)索非亚", + "Europe/Tallinn": "(GMT+02:00)塔林", + "Europe/Vilnius": "(GMT+02:00)维尔纽斯", + "Asia/Baghdad": "(GMT+03:00)巴格达", + "Asia/Istanbul": "(GMT+03:00)伊斯坦布尔", + "Europe/Minsk": "(GMT+03:00)明斯克", + "Asia/Riyadh": "(GMT+03:00)利雅得", + "Europe/Moscow": "(GMT+03:00)莫斯科-莫斯科", + "Asia/Tehran": "(GMT+03:30)德黑兰", + "Asia/Baku": "(GMT+04:00)巴库", + "Europe/Samara": "(GMT+04:00)莫斯科-萨马拉", + "Asia/Tbilisi": "(GMT+04:00)第比利斯", + "Asia/Yerevan": "(GMT+04:00)埃里温", + "Asia/Kabul": "(GMT+04:30)喀布尔", + "Asia/Karachi": "(GMT+05:00)卡拉奇", + "Asia/Yekaterinburg": "(GMT+05:00)莫斯科-叶卡捷琳堡", + "Asia/Tashkent": "(GMT+05:00)塔什干", + "Asia/Colombo": "(GMT+05:30)科伦坡", + "Asia/Almaty": "(GMT+06:00)阿拉木图", + "Asia/Dhaka": "(GMT+06:00)达卡", + "Asia/Rangoon": "(GMT+06:30)仰光", + "Asia/Bangkok": "(GMT+07:00)曼谷", + "Asia/Jakarta": "(GMT+07:00)雅加达", + "Asia/Krasnoyarsk": "(GMT+07:00)莫斯科-克拉斯诺亚尔斯克", + "Asia/Shanghai": "(GMT+08:00)中国时间-北京", + "Hongkong": "(GMT+08:00)香港", + "Asia/Kuala_Lumpur": "(GMT+08:00)吉隆坡", + "Asia/Irkutsk": "(GMT+08:00)莫斯科-伊尔库茨克", + "Asia/Singapore": "(GMT+08:00)新加坡", + "Asia/Taipei": "(GMT+08:00)台北", + "Asia/Ulaanbaatar": "(GMT+08:00)乌兰巴托", + "Australia/Perth": "(GMT+08:00)西部时间-珀斯", + "Asia/Yakutsk": "(GMT+09:00)莫斯科-雅库茨克", + "Asia/Seoul": "(GMT+09:00)首尔", + "Asia/Tokyo": "(GMT+09:00)东京", + "Australia/Darwin": "(GMT+09:30)中部时间-达尔文", + "Australia/Brisbane": "(GMT+10:00)东部时间-布里斯班", + "Pacific/Guam": "(GMT+10:00)关岛", + "Asia/Magadan": "(GMT+10:00)莫斯科-马加丹", + "Asia/Sakhalin": "(GMT+10:00)莫斯科-南萨哈林斯克", + "Pacific/Port_Moresby": "(GMT+10:00)莫尔兹比港", + "Australia/Adelaide": "(GMT+10:30)中部时间-阿德莱德", + "Australia/Hobart": "(GMT+11:00)东部时间-霍巴特", + "Australia/Melbourne": "(GMT+11:00)东部时间-悉尼墨尔本", + "Pacific/Guadalcanal": "(GMT+11:00)Guadalcanal", + "Pacific/Noumea": "(GMT+11:00)努美阿", + "Pacific/Majuro": "(GMT+12:00)马朱罗", + "Asia/Kamchatka": "(GMT+12:00)莫斯科-堪察加彼得罗巴甫洛夫斯克", + "Pacific/Auckland": "(GMT+13:00)奥克兰", + "Pacific/Fakaofo": "(GMT+13:00)法考福", + "Pacific/Fiji": "(GMT+13:00)斐济", + "Pacific/Tongatapu": "(GMT+13:00)汤加塔布群岛", + "Pacific/Apia": "(GMT+14:00)阿皮亚", + }, + Keys: []string{"Pacific/Pago_Pago", "US/Hawaii", "US/Pacific", "America/Tijuana", "US/Mountain", "US/Arizona", "America/Chihuahua", "US/Central", "America/Mexico_City", "America/Regina", "America/Guatemala", "America/Bogota", "US/Eastern", "America/Lima", "America/Caracas", "America/Halifax", "America/Guyana", "America/La_Paz", "America/Buenos_Aires", "America/Godthab", "America/Montevideo", "Canada/Newfoundland", "America/Santiago", "America/Sao_Paulo", "Atlantic/South_Georgia", "Atlantic/Azores", "Atlantic/Cape_Verde", "Africa/Casablanca", "Europe/Dublin", "Europe/Lisbon", "Europe/London", "Africa/Monrovia", "Africa/Algiers", "Europe/Amsterdam", "Europe/Berlin", "Europe/Brussels", "Europe/Budapest", "Europe/Belgrade", "Europe/Prague", "Europe/Copenhagen", "Europe/Madrid", "Europe/Paris", "Europe/Rome", "Europe/Stockholm", "Europe/Vienna", "Europe/Warsaw", "Europe/Athens", "Europe/Bucharest", "Africa/Cairo", "Europe/Helsinki", "Asia/Jerusalem", "Africa/Johannesburg", "Europe/Kiev", "Europe/Kaliningrad", "Europe/Riga", "Europe/Sofia", "Europe/Tallinn", "Europe/Vilnius", "Asia/Baghdad", "Asia/Istanbul", "Europe/Minsk", "Asia/Riyadh", "Europe/Moscow", "Asia/Tehran", "Asia/Baku", "Europe/Samara", "Asia/Tbilisi", "Asia/Yerevan", "Asia/Kabul", "Asia/Karachi", "Asia/Yekaterinburg", "Asia/Tashkent", "Asia/Colombo", "Asia/Almaty", "Asia/Dhaka", "Asia/Rangoon", "Asia/Bangkok", "Asia/Jakarta", "Asia/Krasnoyarsk", "Asia/Shanghai", "Hongkong", "Asia/Kuala_Lumpur", "Asia/Irkutsk", "Asia/Singapore", "Asia/Taipei", "Asia/Ulaanbaatar", "Australia/Perth", "Asia/Yakutsk", "Asia/Seoul", "Asia/Tokyo", "Australia/Darwin", "Australia/Brisbane", "Pacific/Guam", "Asia/Magadan", "Asia/Sakhalin", "Pacific/Port_Moresby", "Australia/Adelaide", "Australia/Hobart", "Australia/Melbourne", "Pacific/Guadalcanal", "Pacific/Noumea", "Pacific/Majuro", "Asia/Kamchatka", "Pacific/Auckland", "Pacific/Fakaofo", "Pacific/Fiji", "Pacific/Tongatapu", "Pacific/Apia"}, +} + +var TimeZoneDictEn responseTypes.OrderedJsonDict = responseTypes.OrderedJsonDict{ + M: map[string]string{ + "Pacific/Pago_Pago": "(GMT-11:00) Pago Pago", + "US/Hawaii": "(GMT-10:00) Hawaii Time", + "US/Pacific": "(GMT-08:00) Pacific Time", + "America/Tijuana": "(GMT-08:00) Pacific Time - Tijuana", + "US/Mountain": "(GMT-07:00) Mountain Time", + "US/Arizona": "(GMT-07:00) Mountain Time - Arizona", + "America/Chihuahua": "(GMT-07:00) Mountain Time - Chihuahua, Mazatlan", + "US/Central": "(GMT-06:00) Central Time", + "America/Mexico_City": "(GMT-06:00) Central Time - Mexico City", + "America/Regina": "(GMT-06:00) Central Time - Regina", + "America/Guatemala": "(GMT-06:00) Guatemala", + "America/Bogota": "(GMT-05:00) Bogota", + "US/Eastern": "(GMT-05:00) Eastern Time", + "America/Lima": "(GMT-05:00) Lima", + "America/Caracas": "(GMT-04:30) Caracas", + "America/Halifax": "(GMT-04:00) Atlantic Time - Halifax", + "America/Guyana": "(GMT-04:00) Guyana", + "America/La_Paz": "(GMT-04:00) La Paz", + "America/Buenos_Aires": "(GMT-03:00) Buenos Aires", + "America/Godthab": "(GMT-03:00) Godthab", + "America/Montevideo": "(GMT-03:00) Montevideo", + "Canada/Newfoundland": "(GMT-03:30) Newfoundland Time - St. Johns", + "America/Santiago": "(GMT-03:00) Santiago", + "America/Sao_Paulo": "(GMT-02:00) Sao Paulo", + "Atlantic/South_Georgia": "(GMT-02:00) South Georgia", + "Atlantic/Azores": "(GMT-01:00) Azores", + "Atlantic/Cape_Verde": "(GMT-01:00) Cape Verde", + "Africa/Casablanca": "(GMT+00:00) Casablanca", + "Europe/Dublin": "(GMT+00:00) Dublin", + "Europe/Lisbon": "(GMT+00:00) Lisbon", + "Europe/London": "(GMT+00:00) London", + "Africa/Monrovia": "(GMT+00:00) Monrovia", + "Africa/Algiers": "(GMT+01:00) Algiers", + "Europe/Amsterdam": "(GMT+01:00) Amsterdam", + "Europe/Berlin": "(GMT+01:00) Berlin", + "Europe/Brussels": "(GMT+01:00) Brussels", + "Europe/Budapest": "(GMT+01:00) Budapest", + "Europe/Belgrade": "(GMT+01:00) Central European Time - Belgrade", + "Europe/Prague": "(GMT+01:00) Central European Time - Prague", + "Europe/Copenhagen": "(GMT+01:00) Copenhagen", + "Europe/Madrid": "(GMT+01:00) Madrid", + "Europe/Paris": "(GMT+01:00) Paris", + "Europe/Rome": "(GMT+01:00) Rome", + "Europe/Stockholm": "(GMT+01:00) Stockholm", + "Europe/Vienna": "(GMT+01:00) Vienna", + "Europe/Warsaw": "(GMT+01:00) Warsaw", + "Europe/Athens": "(GMT+02:00) Athens", + "Europe/Bucharest": "(GMT+02:00) Bucharest", + "Africa/Cairo": "(GMT+02:00) Cairo", + "Europe/Helsinki": "(GMT+02:00) Helsinki", + "Asia/Jerusalem": "(GMT+02:00) Jerusalem", + "Africa/Johannesburg": "(GMT+02:00) Johannesburg", + "Europe/Kiev": "(GMT+02:00) Kiev", + "Europe/Kaliningrad": "(GMT+02:00) Moscow-01 - Kaliningrad", + "Europe/Riga": "(GMT+02:00) Riga", + "Europe/Sofia": "(GMT+02:00) Sofia", + "Europe/Tallinn": "(GMT+02:00) Tallinn", + "Europe/Vilnius": "(GMT+02:00) Vilnius", + "Asia/Baghdad": "(GMT+03:00) Baghdad", + "Asia/Istanbul": "(GMT+03:00) Istanbul", + "Europe/Minsk": "(GMT+03:00) Minsk", + "Asia/Riyadh": "(GMT+03:00) Riyadh", + "Europe/Moscow": "(GMT+03:00) Moscow+00 - Moscow", + "Asia/Tehran": "(GMT+03:30) Tehran", + "Asia/Baku": "(GMT+04:00) Baku", + "Europe/Samara": "(GMT+04:00) Moscow+01 - Samara", + "Asia/Tbilisi": "(GMT+04:00) Tbilisi", + "Asia/Yerevan": "(GMT+04:00) Yerevan", + "Asia/Kabul": "(GMT+04:30) Kabul", + "Asia/Karachi": "(GMT+05:00) Karachi", + "Asia/Yekaterinburg": "(GMT+05:00) Moscow+02 - Yekaterinburg", + "Asia/Tashkent": "(GMT+05:00) Tashkent", + "Asia/Colombo": "(GMT+05:30) Colombo", + "Asia/Almaty": "(GMT+06:00) Almaty", + "Asia/Dhaka": "(GMT+06:00) Dhaka", + "Asia/Rangoon": "(GMT+06:30) Rangoon", + "Asia/Bangkok": "(GMT+07:00) Bangkok", + "Asia/Jakarta": "(GMT+07:00) Jakarta", + "Asia/Krasnoyarsk": "(GMT+07:00) Moscow+04 - Krasnoyarsk", + "Asia/Shanghai": "(GMT+08:00) China Time - Beijing", + "Hongkong": "(GMT+08:00) Hong Kong", + "Asia/Kuala_Lumpur": "(GMT+08:00) Kuala Lumpur", + "Asia/Irkutsk": "(GMT+08:00) Moscow+05 - Irkutsk", + "Asia/Singapore": "(GMT+08:00) Singapore", + "Asia/Taipei": "(GMT+08:00) Taipei", + "Asia/Ulaanbaatar": "(GMT+08:00) Ulaanbaatar", + "Australia/Perth": "(GMT+08:00) Western Time - Perth", + "Asia/Yakutsk": "(GMT+09:00) Moscow+06 - Yakutsk", + "Asia/Seoul": "(GMT+09:00) Seoul", + "Asia/Tokyo": "(GMT+09:00) Tokyo", + "Australia/Darwin": "(GMT+09:30) Central Time - Darwin", + "Australia/Brisbane": "(GMT+10:00) Eastern Time - Brisbane", + "Pacific/Guam": "(GMT+10:00) Guam", + "Asia/Magadan": "(GMT+10:00) Moscow+07 - Magadan", + "Asia/Sakhalin": "(GMT+10:00) Moscow+07 - Yuzhno-Sakhalinsk", + "Pacific/Port_Moresby": "(GMT+10:00) Port Moresby", + "Australia/Adelaide": "(GMT+10:30) Central Time - Adelaide", + "Australia/Hobart": "(GMT+11:00) Eastern Time - Hobart", + "Australia/Melbourne": "(GMT+11:00) Eastern Time - Melbourne, Sydney", + "Pacific/Guadalcanal": "(GMT+11:00) Guadalcanal", + "Pacific/Noumea": "(GMT+11:00) Noumea", + "Pacific/Majuro": "(GMT+12:00) Majuro", + "Asia/Kamchatka": "(GMT+12:00) Moscow+09 - Petropavlovsk-Kamchatskiy", + "Pacific/Auckland": "(GMT+13:00) Auckland", + "Pacific/Fakaofo": "(GMT+13:00) Fakaofo", + "Pacific/Fiji": "(GMT+13:00) Fiji", + "Pacific/Tongatapu": "(GMT+13:00) Tongatapu", + "Pacific/Apia": "(GMT+14:00) Apia", + }, + Keys: []string{"Pacific/Pago_Pago", "US/Hawaii", "US/Pacific", "America/Tijuana", "US/Mountain", "US/Arizona", "America/Chihuahua", "US/Central", "America/Mexico_City", "America/Regina", "America/Guatemala", "America/Bogota", "US/Eastern", "America/Lima", "America/Caracas", "America/Halifax", "America/Guyana", "America/La_Paz", "America/Buenos_Aires", "America/Godthab", "America/Montevideo", "Canada/Newfoundland", "America/Santiago", "America/Sao_Paulo", "Atlantic/South_Georgia", "Atlantic/Azores", "Atlantic/Cape_Verde", "Africa/Casablanca", "Europe/Dublin", "Europe/Lisbon", "Europe/London", "Africa/Monrovia", "Africa/Algiers", "Europe/Amsterdam", "Europe/Berlin", "Europe/Brussels", "Europe/Budapest", "Europe/Belgrade", "Europe/Prague", "Europe/Copenhagen", "Europe/Madrid", "Europe/Paris", "Europe/Rome", "Europe/Stockholm", "Europe/Vienna", "Europe/Warsaw", "Europe/Athens", "Europe/Bucharest", "Africa/Cairo", "Europe/Helsinki", "Asia/Jerusalem", "Africa/Johannesburg", "Europe/Kiev", "Europe/Kaliningrad", "Europe/Riga", "Europe/Sofia", "Europe/Tallinn", "Europe/Vilnius", "Asia/Baghdad", "Asia/Istanbul", "Europe/Minsk", "Asia/Riyadh", "Europe/Moscow", "Asia/Tehran", "Asia/Baku", "Europe/Samara", "Asia/Tbilisi", "Asia/Yerevan", "Asia/Kabul", "Asia/Karachi", "Asia/Yekaterinburg", "Asia/Tashkent", "Asia/Colombo", "Asia/Almaty", "Asia/Dhaka", "Asia/Rangoon", "Asia/Bangkok", "Asia/Jakarta", "Asia/Krasnoyarsk", "Asia/Shanghai", "Hongkong", "Asia/Kuala_Lumpur", "Asia/Irkutsk", "Asia/Singapore", "Asia/Taipei", "Asia/Ulaanbaatar", "Australia/Perth", "Asia/Yakutsk", "Asia/Seoul", "Asia/Tokyo", "Australia/Darwin", "Australia/Brisbane", "Pacific/Guam", "Asia/Magadan", "Asia/Sakhalin", "Pacific/Port_Moresby", "Australia/Adelaide", "Australia/Hobart", "Australia/Melbourne", "Pacific/Guadalcanal", "Pacific/Noumea", "Pacific/Majuro", "Asia/Kamchatka", "Pacific/Auckland", "Pacific/Fakaofo", "Pacific/Fiji", "Pacific/Tongatapu", "Pacific/Apia"}, +} + +func GetTimeZoneList(logger *log.Logger) responseTypes.OrderedJsonDict { + + language := logger.GetPoint("language").(string) + if language == constant.LANGUAGE_EN { + return TimeZoneDictEn + } else { + return TimeZoneDictZh + } +} diff --git a/bmp-operation-api/logic/UserLogic/UserLogic.go b/bmp-operation-api/logic/UserLogic/UserLogic.go new file mode 100644 index 0000000..8ad4cd3 --- /dev/null +++ b/bmp-operation-api/logic/UserLogic/UserLogic.go @@ -0,0 +1,517 @@ +package UserLoigc + +import ( + "encoding/base64" + "errors" + "fmt" + "math/rand" + "strconv" + "time" + + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/BaseLogic" + + sdkUserParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/user" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/excel" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + sdk "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" +) + +const OPERATION_ROLE_ID = "role-operator-uuid-01" + +// 【用户管理】【用户列表】 +func GetUserList(logger *log.Logger, param *requestTypes.QueryUsersRequest) (*response.UserPage, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewDescribeUsersParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithDefaultProjectID(¶m.ProjectID) + req.WithUserName(¶m.UserName) + req.WithRoleID(¶m.RoleID) + req.WithIsAll(¶m.IsAll) + req.WithPageSize(¶m.PageSize) + req.WithPageNumber(¶m.PageNumber) + logger.Info("DescribeUsers openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.User.DescribeUsers(req, nil) + logger.Info("DescribeUsers openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warn("unknown error in User.GetUserList:", err.Error()) + return nil, errors.New("unknown error") //未知错误不暴露给用户 + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warn("User.GetUserList error:", respErr.Message) + return nil, errors.New(respErr.Message) + } + resp := response.UserPage{} + obj := response.User{} + if len(client.Payload.Result.Users) == 0 { + resp.Users = make([]response.User, 0) + return &resp, nil + } + for _, v := range client.Payload.Result.Users { + obj.ID = v.ID + obj.UserID = v.UserID + obj.UserName = v.UserName + obj.Email = v.Email + // obj.Timezone = time.Time(v.Timezone) + obj.Language = v.Language + obj.DefaultProjectID = v.DefaultProjectID + obj.DefaultProjectName = v.DefaultProjectName + obj.ProjectCount = int(v.ProjectCount) + obj.InstanceCount = int(v.InstanceCount) + obj.Description = v.Description + obj.PhoneNumber = v.PhoneNumber + obj.PhonePrefix = v.PhonePrefix + obj.RoleID = v.RoleID + obj.RoleName = v.RoleName + obj.RoleName = v.RoleName + obj.CreatedBy = v.CreatedBy + obj.CreatedTime = util.UtcToTime(v.CreatedTime) + obj.UpdatedBy = v.UpdatedBy + obj.UpdatedBy = util.UtcToTime(v.UpdatedTime) + + resp.Users = append(resp.Users, obj) + } + resp.PageNumber = client.Payload.Result.PageNumber + resp.PageSize = client.Payload.Result.PageSize + resp.TotalCount = client.Payload.Result.TotalCount + return &resp, nil +} + +// 导出Excel文件 +func ExportUserExcel(logger *log.Logger, result []response.User) (string, string, error) { + language := logger.GetPoint("language").(string) + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + for _, data := range result { + sheetData = append(sheetData, []string{ + data.UserName, + data.UserID, + data.RoleName, + data.PhoneNumber, + data.Email, + data.Description, + data.CreatedTime, + }) + } + exportExcelHeader := BaseLogic.ExportUserHeader + if language == BaseLogic.EN_US { + exportExcelHeader = BaseLogic.ExportUserHeaderEn + } + if err := e.SetSheetData("Sheet1", exportExcelHeader, sheetData); err != nil { + logger.Warn("create excel error:", err.Error()) + return "", "", err + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + // 生成100000到100000+900000之间的随机数,左闭右开 + downloadFileName := "device_list_" + time.Now().Format(BaseLogic.FormatDate) + "_" + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Warn("保存excel到本地失败" + err.Error()) + return "", "", err + } + return fileName, downloadFileName, nil +} + +// 【用户管理】【添加用户】 +func AddUser(logger *log.Logger, param *requestTypes.AddUserRequest) (*response.UserAdd, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewCreateUserParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := sdkModels.CreateUserRequest{ + RoleID: ¶m.RoleID, + UserName: ¶m.UserName, + Email: param.Email, + PhonePrefix: param.PhonePrefix, + PhoneNumber: param.PhoneNumber, + Language: param.Language, + Password: ¶m.Password, + Description: param.Description, + } + req.WithBody(&body) + logger.Info("CreateUser openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.User.CreateUser(req, nil) + logger.Info("CreateUser openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warn("unknown error in User.CreateUser:", err.Error()) + return nil, errors.New("unknown error") //未知错误不暴露给用户 + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warn("User.CreateUser error:", respErr.Message) + return nil, errors.New(respErr.Message) + } + return &response.UserAdd{ + UserID: client.Payload.Result.UserID, + }, nil +} + +// 【用户管理】【用户详情】 +func GetUserInfo(logger *log.Logger, param *requestTypes.QueryUserInfoRequest) *response.User { + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewDescribeUserParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithUserID(param.UserID) + logger.Info("DescribeUser openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.User.DescribeUser(req, nil) + logger.Info("DescribeUser openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warn("unknown error in User.DescribeUser:", err.Error()) + return nil + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warn("User.DescribeUser error:", respErr.Message) + return nil + } + + var v = client.Payload.Result.User + obj := response.User{} + obj.ID = v.ID + obj.UserID = v.UserID + obj.UserName = v.UserName + obj.Email = v.Email + // obj.Timezone = time.Time(v.Timezone) + obj.Language = v.Language + obj.DefaultProjectID = v.DefaultProjectID + obj.DefaultProjectName = v.DefaultProjectName + obj.Description = v.Description + obj.PhoneNumber = v.PhoneNumber + obj.PhonePrefix = v.PhonePrefix + obj.RoleID = v.RoleID + obj.RoleName = v.RoleName + obj.CreatedBy = v.CreatedBy + obj.CreatedTime = v.CreatedTime + obj.UpdatedBy = v.UpdatedBy + obj.UpdatedBy = v.UpdatedTime + return &obj +} + +func GetUserByName(logger *log.Logger, username string) (*sdkModels.User, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewDescribeUserByNameParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + // userId := logger.GetPoint("userId").(string) + // req.WithBmpUserID(&userId) + req.WithUserName(username) + + logger.Info("DescribeUserByName openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.User.DescribeUserByName(req, nil) + logger.Info("DescribeUserByName openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil { + fmt.Println("GetUserByName resp.err:", err.Error()) + } + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + fmt.Println("unknown error in User.GetUserByName:", err.Error()) + logger.Warn("unknown error in User.GetUserByName:", err.Error()) + return nil, errors.New("unknown error") //未知错误不暴露给用户 + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warn("User.GetUserByName error:", respErr.Message) + return nil, errors.New(respErr.Message) + } + return client.Payload.Result.User, nil + +} + +// 【用户管理】【编辑用户信息】 +func ModifyUserInfo(logger *log.Logger, param *requestTypes.ModifyUserInfoRequest, userIdModify string) error { + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewModifyUserParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithUserID(userIdModify) + + body := sdkModels.ModifyUserRequest{ + //RoleID: param.RoleID, + //UserName: param.UserName, + Email: param.Email, + PhonePrefix: param.PhonePrefix, + PhoneNumber: param.PhoneNumber, + //Language: param.Language, + //Password: param.Password, + Description: param.Description, + } + req.WithBody(&body) + logger.Info("ModifyUser openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.User.ModifyUser(req, nil) + logger.Info("ModifyUser openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warn("unknown error in User.ModifyUser:", err.Error()) + return err + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warn("User.ModifyUser error:", respErr.Message) + return errors.New(respErr.Message) + } + return nil +} + +// 【用户管理】【删除用户】 +func DeleteUserInfo(logger *log.Logger, param *requestTypes.DeleteUserInfoRequest) error { + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewDeleteUserParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + req.WithUserID(param.UserID) + logger.Info("DeleteUser openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.User.DeleteUser(req, nil) + logger.Info("DeleteUser openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warn("unknown error in User.VerifyUser:", err.Error()) + return err + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warn("User.VerifyUser error:", respErr.Message) + return errors.New(respErr.Message) + } + return nil + +} + +func VerifyUser(logger *log.Logger, username, password string) (*response.CommonResponse, error) { + + fmt.Println("[DEBUG] ORIGIN PASSWORD IS:", password) + //前端传过来的是加密并base64过的 + pv, err := base64.StdEncoding.DecodeString(password) + if err != nil { + return nil, errors.New("parse password error:" + err.Error()) + } + pv, err = util.AesDecrypt(pv) + if err != nil { + return nil, errors.New("password aes decode error:" + err.Error()) + } + password = string(pv) + fmt.Println("[DEBUG] PARSED PASSWORD IS:", password) + + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewVerifyUserParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + roleId := OPERATION_ROLE_ID + body := &sdkModels.VerifyUserRequest{ + UserName: &username, + Password: &password, + RoleID: &roleId, + } + req.WithBody(body) + + logger.Info("VerifyUser openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.User.VerifyUser(req, nil) + logger.Info("VerifyUser openapi sdk resp:", util.InterfaceToJson(client)) + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warn("unknown error in User.VerifyUser:", err.Error()) + return nil, errors.New("unknown error") //未知错误不暴露给用户 + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warn("User.VerifyUser error:", respErr.Message) + return nil, errors.New(respErr.Message) + } + if client == nil || client.Payload == nil || client.Payload.Result == nil { + return nil, errors.New("VerifyUser failed") + } + + res := &response.CommonResponse{} + if client.Payload.Result.Success { + res.Success = true + } else { + res.Success = false + } + return res, nil +} + +// 【用户管理】【用户详情】 +func GetLocalUserInfo(logger *log.Logger) (*response.LocalUser, error) { + userId := logger.GetPoint("userId").(string) + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewDescribeLocalUserParams() + req.WithTraceID(logid) + req.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + responseApi, err := openApi.SdkClient.User.DescribeLocalUser(req, nil) + if err != nil { + logger.Info("DescribeLocalUser openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + var v = responseApi.Payload.Result.User + obj := response.LocalUser{} + obj.ID = int64(v.ID) + obj.UserID = v.UserID + obj.UserName = v.UserName + obj.Email = v.Email + obj.Timezone = v.Timezone + obj.Language = v.Language + obj.DefaultProjectID = v.DefaultProjectID + obj.DefaultProjectName = v.DefaultProjectName + obj.Description = v.Description + obj.PhoneNumber = v.PhoneNumber + obj.PhonePrefix = v.PhonePrefix + obj.RoleID = v.RoleID + obj.RoleName = v.RoleName + obj.CreatedBy = v.CreatedBy + obj.CreatedTime = v.CreatedTime + obj.UpdatedBy = v.UpdatedBy + obj.UpdatedBy = v.UpdatedTime + obj.LicenseExist = true + obj.LicenseModels = []string{"带内监控管理", "带外监控管理"} + + return &obj, nil +} + +// 【用户管理】【修改密码】 +func ModifyLocalUserPassword(logger *log.Logger, userID string, param *requestTypes.UpdateLocalPasswordRequest) (bool, error) { + + fmt.Println("[DEBUG] ORIGIN OLD PASSWORD IS:", param.OldPassword) + //前端传过来的是加密并base64过的 + pv, err := base64.StdEncoding.DecodeString(param.OldPassword) + if err != nil { + return false, errors.New("parse old password error:" + err.Error()) + } + pv, err = util.AesDecrypt(pv) + if err != nil { + return false, errors.New("old password aes decode error:" + err.Error()) + } + param.OldPassword = string(pv) + fmt.Println("[DEBUG] PARSED OLD PASSWORD IS:", param.OldPassword) + //// + fmt.Println("[DEBUG] ORIGIN PASSWORD IS:", param.Password) + //前端传过来的是加密并base64过的 + pv, err = base64.StdEncoding.DecodeString(param.Password) + if err != nil { + return false, errors.New("parse password error:" + err.Error()) + } + pv, err = util.AesDecrypt(pv) + if err != nil { + return false, errors.New("password aes decode error:" + err.Error()) + } + param.Password = string(pv) + fmt.Println("[DEBUG] PARSED PASSWORD IS:", param.Password) + + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewModifyLocalUserPasswordParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + + body := sdkModels.ModifyUserPasswordRequest{ + Password: ¶m.Password, + OldPassword: ¶m.OldPassword, + } + req.WithBody(&body) + + res, err := openApi.SdkClient.User.ModifyLocalUserPassword(req, nil) + if err != nil { + logger.Info("ModifyLocalUserPassword openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return res.Payload.Result.Success, nil +} + +// 【用户管理】【编辑用户信息】 +func ModifyLocalUserInfo(logger *log.Logger, userID string, param *requestTypes.ModifyLocalUserInfoRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + req := sdkUserParameters.NewModifyLocalUserParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + + body := sdkModels.ModifyLocalUserRequest{ + DefaultProjectID: param.DefaultProjectID, + //Description: param.Description, + Email: param.Email, + Language: param.Language, + PhonePrefix: param.PhonePrefix, + PhoneNumber: param.PhoneNumber, + Timezone: param.Timezone, + } + req.WithBody(&body) + + res, err := openApi.SdkClient.User.ModifyLocalUser(req, nil) + if err != nil { + logger.Info("ModifyLocalUserPassword openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return res.Payload.Result.Success, nil +} diff --git a/bmp-operation-api/logic/WebsocketLogic/WebsocketLogic.go b/bmp-operation-api/logic/WebsocketLogic/WebsocketLogic.go new file mode 100644 index 0000000..29019d1 --- /dev/null +++ b/bmp-operation-api/logic/WebsocketLogic/WebsocketLogic.go @@ -0,0 +1,258 @@ +package WebsocketLogic + +import ( + "fmt" + "sync" + "time" + + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" + "github.com/gorilla/websocket" +) + +const ( + MessageTypeHeartbeatFromClient = "heartbeat" // 心跳 + MessageTypeHeartbeatFromServer = "ok" // 心跳回复成功 + MessageTypeRegisterFromClient = "register" // 注册 + MessageTypeRegisterSuccFromServer = "register ok" // 注册成功 + MessageTypeRegisterFailFromServer = "register err" // 注册失败 + MessageTypeNewNofifyFromServer = "nofifyfromserver" + + HeartbeatCheckTime = 5 // 心跳检测几秒检测一次 + HeartbeatTime = 300 // 心跳距离上一次的最大时间 + + ChanBufferRegister = 100 // 注册chan缓冲 + ChanBufferUnregister = 100 // 注销chan大小 +) + +// ReceiveMessage 客户端请求的报文格式(心跳or业务消息) +type ReceiveMessage struct { + Type string `json:"type"` + Message string `json:"message"` +} + +// NofifyMessage 回复给客户端的报文格式(心跳回复or业务消息) +type NofifyMessage struct { + Type string `json:"type"` + SubType string `json:"subType"` + Message string `json:"message"` + MetaData string `json:"metaData"` // 元数据 +} + +// var Nofify = make(chan NofifyMessage) + +// 客户端连接信息 +type Client struct { + ID string // 连接ID + UserId string // 账号id, 一个账号可能有多个连接 + Socket *websocket.Conn // socket连接 + HeartbeatTime int64 // 前一次心跳时间 +} + +// 客户端管理 +type ClientManager struct { + Clients map[string]*Client // 保存连接 + Accounts map[string][]string // 账号和连接关系,map的key是账号id即:AccountId,这里主要考虑到一个账号多个连接 + mu *sync.Mutex +} + +// 定义一个管理Manager +var Manager = ClientManager{ + Clients: make(map[string]*Client), // 参与连接的用户,出于性能的考虑,需要设置最大连接数 + Accounts: make(map[string][]string), // 账号和连接关系 + mu: new(sync.Mutex), +} + +var ( + RegisterChan = make(chan *Client, ChanBufferRegister) // 注册 + UnregisterChan = make(chan *Client, ChanBufferUnregister) // 注销 +) + +//有新消息,在这里通知到客户端 +func init() { + + /* + go dealRegister() + go dealHeartbeat() + + go MSendInterval() + */ + + // for { + // msg := <-Nofify + + // logPath, _ := beego.AppConfig.String("log.path") + // logger := log.New(logPath + "/bmp-msg-notify.log") + // logger.SetStableFields([]string{"time", "type", "subtype", "message"}) + // //没有requestid,临时生成 + // logger.Point("logid", util.GenerateRandUuid()) + // logger.Point("time", time.Now().String()) + // logger.Point("type", msg.Type) + // logger.Point("subtype", msg.SubType) + // logger.Point("message", msg.Message) + + // // for _, client := range Manager.Clients { + // // err := client.Socket.WriteJSON(msg) + // // if err != nil { + // // logger.Warnf("client.WriteJSON error: %v", err) + // // client.Socket.Close() + // // delete(Manager.Clients, client) + // // } + // // } + // logger.Flush() + // } +} + +// 注册注销 +func dealRegister() { + for { + select { + case conn := <-RegisterChan: // 新注册,新连接 + // 加入连接,进行管理 + connBind(conn) + + // 回复消息 + content := NofifyMessage{ + Type: "register", + SubType: "register", + Message: "register success", + } + _ = conn.Socket.WriteJSON(content) + + case conn := <-UnregisterChan: // 注销,或者没有心跳 + fmt.Println("UnregisterChan come...") + // 删除Client + connUnBind(conn) + } + } +} + +// 新加连接 +func connBind(c *Client) { + Manager.mu.Lock() + defer Manager.mu.Unlock() + + // 加入到连接 + Manager.Clients[c.ID] = c + + // 加入到绑定 + if _, ok := Manager.Accounts[c.UserId]; ok { // 该账号已经有绑定,就追加一个绑定 + Manager.Accounts[c.UserId] = append(Manager.Accounts[c.UserId], c.ID) + } else { // 没有就新增一个账号的绑定切片 + Manager.Accounts[c.UserId] = []string{c.ID} + } +} + +// 删除连接并关闭 +func connUnBind(c *Client) { + Manager.mu.Lock() + defer Manager.mu.Unlock() + + defer c.Socket.Close() + + // 取消连接 + delete(Manager.Clients, c.ID) + + // 取消绑定 + if len(Manager.Accounts[c.UserId]) > 0 { + for k, clientId := range Manager.Accounts[c.UserId] { + if clientId == c.ID { // 找到绑定客户端Id + Manager.Accounts[c.UserId] = append(Manager.Accounts[c.UserId][:k], Manager.Accounts[c.UserId][k+1:]...) + } + if len(Manager.Accounts[c.UserId]) == 0 { + delete(Manager.Accounts, c.UserId) + } + } + } +} + +// 维持心跳 +func dealHeartbeat() { + for { + // 获取所有的Clients + Manager.mu.Lock() + // clients := make([]*Client, len(Manager.Clients)) + clients := []*Client{} + for _, c := range Manager.Clients { + clients = append(clients, c) + } + Manager.mu.Unlock() + fmt.Println(time.Now().String(), "debug... clients is:", clients) + fmt.Println(time.Now().String(), "debug... Manager.Clients is:", Manager.Clients) + fmt.Println(time.Now().String(), "debug... Manager.Accounts is:", Manager.Accounts) + for _, c := range clients { + // fmt.Println("debug... c is:", c) + if time.Now().Unix()-c.HeartbeatTime > HeartbeatTime { + connUnBind(c) + } + } + + time.Sleep(time.Second * HeartbeatCheckTime) + } +} + +// 有新消息时,业务侧通过这个func发送消息到客户端 +func SendMsg2Client(logger *log.Logger, userIds []string, message NofifyMessage) error { + + for _, userId := range userIds { + // 获取连接id + clients := GetClient(userId) + // 发送消息 + for _, c := range clients { + err := c.Socket.WriteJSON(message) + if err != nil { + logger.Infof("SendMsg2Client failed, userId:%s, message:%s, error:%s", userId, util.ObjToJsonString(message), err.Error()) + connUnBind(c) + } else { + logger.Infof("SendMsg2Client success, userId:%s, message:%s", userId, util.ObjToJsonString(message)) + } + } + } + + return nil +} + +// 根据账号获取连接 +func GetClient(userId string) []*Client { + clients := make([]*Client, 0) + + Manager.mu.Lock() + defer Manager.mu.Unlock() + + if len(Manager.Accounts[userId]) > 0 { + for _, clientId := range Manager.Accounts[userId] { + if c, ok := Manager.Clients[clientId]; ok { + clients = append(clients, c) + } + } + } + + return clients +} + +func MSendInterval() { + + message := NofifyMessage{ + Type: "test", + SubType: "send_interval", + Message: "hello socket", + } + for { + for _, c := range Manager.Clients { + if c == nil { + fmt.Println("socket client is nil ...., check it") + continue + } + err := c.Socket.WriteJSON(message) + if err != nil { + fmt.Printf(time.Now().String(), "SendMsg2Client failed, message:%s, error:%s\n", util.ObjToJsonString(message), err.Error()) + connUnBind(c) + } else { + fmt.Printf(time.Now().String(), "SendMsg2Client success, userId:%s, message:%s\n", util.ObjToJsonString(message)) + } + + } + time.Sleep(20 * time.Second) + } + +} diff --git a/bmp-operation-api/logic/messageLogic/messageLogic.go b/bmp-operation-api/logic/messageLogic/messageLogic.go new file mode 100644 index 0000000..a95e65d --- /dev/null +++ b/bmp-operation-api/logic/messageLogic/messageLogic.go @@ -0,0 +1,352 @@ +package messageLogic + +import ( + // "coding.jd.com/aidc-bmp/bmp-openapi/dao/messageDao" + "errors" + "math/rand" + "strconv" + "time" + + sdkMessageParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/message" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + "coding.jd.com/aidc-bmp/bmp-operation-api/constant" + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/excel" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + + // "coding.jd.com/aidc-bmp/bmp-openapi/util" + "git.jd.com/cps-golang/ironic-common/exception" + log "git.jd.com/cps-golang/log" +) + +func HasUnreadMessage(logger *log.Logger) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewHasUnreadMessageParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("HasUnreadMessage openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.HasUnreadMessage(request, nil) + logger.Info("HasUnreadMessage openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("HasUnreadMessage openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.HasUnread, nil +} + +func GetPageMessages(logger *log.Logger, param *requestTypes.QueryMessagesRequest, p util.Pageable) (*response.MessageList, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewGetMessageListParams() + userId := logger.GetPoint("userId").(string) + request.WithPageNumber(&p.PageNumber) + request.WithPageSize(&p.PageSize) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + if param.HasRead != "" { + request.WithHasRead(¶m.HasRead) + } + if param.IsAll != "" || param.ExportType != "" { + request.WithIsAll(¶m.IsAll) + } + if param.MessageType != "" { + request.WithMessageType(¶m.MessageType) + } + if param.MessageSubType != "" { + request.WithMessageSubType(¶m.MessageSubType) + } + if param.Detail != "" { + request.WithDetail(¶m.Detail) + } + + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("GetMessageList openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.GetMessageList(request, nil) + logger.Info("GetMessageList openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("GetMessageList openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + resp := response.MessageList{} + resp.PageNumber = responseApi.Payload.Result.PageNumber + resp.PageSize = responseApi.Payload.Result.PageSize + resp.TotalCount = responseApi.Payload.Result.TotalCount + resp.Messages = responseApi.Payload.Result.Messages + + return &resp, nil + +} + +func GetMessageStatistic(logger *log.Logger) (int64, int64, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewGetMessageStatisticParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("GetMessageStatistic openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.GetMessageStatistic(request, nil) + logger.Info("GetMessageStatistic openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("GetMessageStatistic openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return 0, 0, err + } + return 0, 0, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.TotalCount, responseApi.Payload.Result.UnreadCount, nil + +} + +func ReadMessages(logger *log.Logger, param *requestTypes.ReadMessagesRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewReadMessageParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + body := sdkModels.ReadMessagesRequest{ + MessageIds: param.MessageIds, + } + request.WithBody(&body) + + logger.Info("ReadMessage openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.ReadMessage(request, nil) + logger.Info("ReadMessage openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("ReadMessage openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil +} + +func GetMessageById(logger *log.Logger, param *requestTypes.GetMessageByIdRequest) (*sdkModels.Message, string, string, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewGetMessageByIDParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + request.WithMessageID(param.MessageId) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("GetMessageByID openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.GetMessageByID(request, nil) + logger.Info("GetMessageByID openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("GetMessageByID openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, "", "", err + } + return nil, "", "", errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Message, responseApi.Payload.Result.NextMessageID, responseApi.Payload.Result.PrevMessageID, nil + +} + +func GetMessageTypes(logger *log.Logger) (*sdkModels.MessageTypesResp, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewGetMessageTypesParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("GetMessageTypes openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.GetMessageTypes(request, nil) + logger.Info("GetMessageTypes openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("GetMessageTypes openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return &responseApi.Payload.Result, nil + +} + +func DeleteMessages(logger *log.Logger, param *requestTypes.DeleteMessagesRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewDeleteMessageParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + body := sdkModels.DeleteMessagesRequest{ + MessageIds: param.MessageIds, + } + request.WithBody(&body) + + logger.Info("DeleteMessage openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.DeleteMessage(request, nil) + logger.Info("DeleteMessage openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DeleteMessage openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil +} + +func ExportMessage(logger *log.Logger, result []*models.Message) (fileName, downLoadFileName string) { + + language := logger.GetPoint("language").(string) + tz := logger.GetPoint("timezone").(string) + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + + for _, data := range result { + + if language == BaseLogic.EN_US { + + } + + sheetData = append(sheetData, []string{ + data.Detail, + util.TimestampToString(int64(data.FinishTime), tz), + data.MessageType, + data.MessageSubType, + }) + } + exportMessageHeader := BaseLogic.ExportMessageHeader + if language == "en_US" { + exportMessageHeader = BaseLogic.ExportMessageHeaderEn + } + if err := e.SetSheetData("Sheet1", exportMessageHeader, sheetData); err != nil { + panic(exception.Exception{Msg: "新建excel失败", Status: BaseLogic.ERROR_CODE}) + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + downloadFileName := "message_list_" + time.Now().Format(BaseLogic.FormatDate) + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" //生成100000到100000+900000之间的随机数,左闭右开 + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Info("保存excel到本地失败" + err.Error()) + panic(exception.Exception{Msg: "保存excel到本地失败", Status: BaseLogic.ERROR_CODE}) + } + return fileName, downloadFileName +} + +func DialMail(logger *log.Logger, param *requestTypes.MailDialRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewDialMailParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + body := sdkModels.MailDialRequest{ + ServerAddr: ¶m.ServerAddr, + ServerPort: ¶m.ServerPort, + AdminAddr: ¶m.AdminAddr, + AdminPass: ¶m.AdminPass, + To: param.To, + } + request.WithBody(&body) + + logger.Info("DialMail openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.DialMail(request, nil) + logger.Info("DialMail openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Warnf("DialMail openapi error:%s", err.Error()) + panic(constant.BuildInvalidArgumentWithArgs("邮箱配置信息有误,请重新输入", "mail config error, please re input")) + } + + return responseApi.Payload.Result.Success, nil +} + +func DescribeMail(logger *log.Logger) (*sdkModels.Mail, error) { + + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewMailDetailParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + logger.Info("MailDetail openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.MailDetail(request, nil) + logger.Info("MailDetail openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("MailDetail openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result, nil + +} + +func SaveIsPushMail(logger *log.Logger, param *requestTypes.SaveIsPushMailRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + request := sdkMessageParameters.NewSaveIsPushMailParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + + body := sdkModels.SaveIsPushMailRequest{ + IsPush: param.IsPush, + } + request.WithBody(&body) + + logger.Info("SaveIsPushMail openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.Message.SaveIsPushMail(request, nil) + logger.Info("SaveIsPushMail openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("SaveIsPushMail openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil +} diff --git a/bmp-operation-api/logic/monitorAlertLogic/monitorAlertLogic.go b/bmp-operation-api/logic/monitorAlertLogic/monitorAlertLogic.go new file mode 100644 index 0000000..63bbb76 --- /dev/null +++ b/bmp-operation-api/logic/monitorAlertLogic/monitorAlertLogic.go @@ -0,0 +1,151 @@ +package monitorAlertLogic + +import ( + "errors" + "fmt" + "math/rand" + "strconv" + "time" + + sdkmonitorAlertParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/monitor_alert" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/excel" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + "git.jd.com/cps-golang/ironic-common/exception" + log "git.jd.com/cps-golang/log" +) + +func DescribeAlert(logger *log.Logger, AlertId string) (*sdkModels.Alert, error) { + logid := logger.GetPoint("logid").(string) + request := sdkmonitorAlertParameters.NewDescribeAlertParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + request.WithAlertID(AlertId) + logger.Info("DescribeAlert openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.MonitorAlert.DescribeAlert(request, nil) + logger.Info("DescribeAlert openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeAlert openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result, nil + +} + +func DescribeAlerts(logger *log.Logger, param *request.DescribeAlertsRequest, p util.Pageable) (*sdkModels.AlertList, error) { + logid := logger.GetPoint("logid").(string) + request := sdkmonitorAlertParameters.NewDescribeAlertsParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + request.WithIsAll(¶m.IsAll) + request.WithPageNumber(&p.PageNumber) + request.WithPageSize(&p.PageSize) + request.WithUserID(¶m.UserID) + request.WithUserName(¶m.UserName) + request.WithRuleID(¶m.RuleID) + request.WithRuleName(¶m.RuleName) + request.WithStartTime(¶m.StartTime) + request.WithEndTime(¶m.EndTime) + request.WithResourceID(¶m.ResourceID) + + logger.Info("DescribeAlerts openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.MonitorAlert.DescribeAlerts(request, nil) + logger.Info("DescribeAlerts openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeAlerts openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result, nil +} + +func ExportAlerts(logger *log.Logger, result []*sdkModels.Alert) (fileName, downLoadFileName string) { + + language := logger.GetPoint("language").(string) + tz := logger.GetPoint("timezone").(string) + + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + for _, data := range result { + alertPeriod := fmt.Sprintf("%d分钟", data.AlertPeriod) + if language == "en_US" { + alertPeriod = fmt.Sprintf("%dmin", data.AlertPeriod) + } + sheetData = append(sheetData, []string{ + data.UserName, + util.TimestampToString(int64(data.AlertTime), tz), + data.Resource, + data.ResourceID, + data.TriggerDescription, + data.AlertValue, + data.AlertLevelDescription, + alertPeriod, + data.UserName, + }) + } + exportAlertHeader := BaseLogic.ExportAlertsHeader + if language == "en_US" { + exportAlertHeader = BaseLogic.ExportAlertsHeaderEn + } + if err := e.SetSheetData("Sheet1", exportAlertHeader, sheetData); err != nil { + panic(exception.Exception{Msg: "新建excel失败", Status: BaseLogic.ERROR_CODE}) + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + downloadFileName := "alert_list_" + time.Now().Format(BaseLogic.FormatDate) + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" //生成100000到100000+900000之间的随机数,左闭右开 + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Info("保存excel到本地失败" + err.Error()) + panic(exception.Exception{Msg: "保存excel到本地失败", Status: BaseLogic.ERROR_CODE}) + } + return fileName, downloadFileName +} + +func DeleteAlert(logger *log.Logger, param *request.DeleteAlertRequest) (bool, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkmonitorAlertParameters.NewDeleteAlertParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := &sdkModels.DeleteAlertRequest{ + AlertID: ¶m.AlertId, + } + req.WithBody(body) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("DeleteAlert openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.MonitorAlert.DeleteAlert(req, nil) + logger.Info("DeleteAlert openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DeleteAlert openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil + +} diff --git a/bmp-operation-api/logic/monitorDataLogic/monitorDataLogic.go b/bmp-operation-api/logic/monitorDataLogic/monitorDataLogic.go new file mode 100644 index 0000000..c2ab247 --- /dev/null +++ b/bmp-operation-api/logic/monitorDataLogic/monitorDataLogic.go @@ -0,0 +1,45 @@ +package monitorDataLogic + +import ( + "errors" + + sdkmonitorDataParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/monitor_data" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" +) + +func GetMonitorData(logger *log.Logger, param request.GetMonitorDataRequest) ([]*sdkModels.DataEveryMetric, error) { + logid := logger.GetPoint("logid").(string) + request := sdkmonitorDataParameters.NewGetMonitorDataParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + request.WithMetricName(¶m.MetricName) + request.WithInstanceID(¶m.InstanceID) + request.WithDevice(¶m.Device) + request.WithStartTime(¶m.StartTime) + request.WithEndTime(¶m.EndTime) + request.WithTimeInterval(¶m.TimeInterval) + request.WithDownSampleType(¶m.DownSampleType) + request.WithLastManyTime(¶m.LastManyTime) + request.WithUserName(¶m.UserName) + request.WithIdcID(¶m.IdcID) + logger.Info("GetMonitorData openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.MonitorData.GetMonitorData(request, nil) + logger.Info("GetMonitorData openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("GetMonitorData openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result, nil +} diff --git a/bmp-operation-api/logic/monitorProxyLogic/monitorProxyLogic.go b/bmp-operation-api/logic/monitorProxyLogic/monitorProxyLogic.go new file mode 100644 index 0000000..428189b --- /dev/null +++ b/bmp-operation-api/logic/monitorProxyLogic/monitorProxyLogic.go @@ -0,0 +1,65 @@ +package monitorProxyLogic + +import ( + "errors" + + sdkmonitorProxyParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/monitor_proxy" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" +) + +func DescribeAgentStatus(logger *log.Logger, param *request.DesrcibeAgentStatusRequest) (*sdkModels.AgentStatusResponse, error) { + logid := logger.GetPoint("logid").(string) + request := sdkmonitorProxyParameters.NewDesrcibeAgentStatusParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + request.WithInstanceID(param.InstanceId) + + logger.Info("DesrcibeAgentStatus openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.MonitorProxy.DesrcibeAgentStatus(request, nil) + logger.Info("DesrcibeAgentStatus openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DesrcibeAgentStatus openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result, nil + +} + +func DescribeDeviceTags(logger *log.Logger, param *request.DesrcibeTagsRequest) (response.TagsResponse, error) { + logid := logger.GetPoint("logid").(string) + request := sdkmonitorProxyParameters.NewDesrcibeTagsParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + request.WithInstanceID(param.InstanceID) + request.WithTagName(param.TagName) + + logger.Info("DesrcibeTags openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.MonitorProxy.DesrcibeTags(request, nil) + logger.Info("DesrcibeTags openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DesrcibeTags openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Tags, nil +} diff --git a/bmp-operation-api/logic/monitorRuleLogic/monitorRuleLogic.go b/bmp-operation-api/logic/monitorRuleLogic/monitorRuleLogic.go new file mode 100644 index 0000000..50617af --- /dev/null +++ b/bmp-operation-api/logic/monitorRuleLogic/monitorRuleLogic.go @@ -0,0 +1,319 @@ +package monitorRuleLogic + +import ( + "errors" + "fmt" + "math/rand" + "strconv" + "strings" + "time" + + sdkmonitorRuleParameters "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/monitor_rule" + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + "coding.jd.com/aidc-bmp/bmp-operation-api/logic/BaseLogic" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/excel" + "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + "git.jd.com/cps-golang/ironic-common/exception" + log "git.jd.com/cps-golang/log" +) + +func AddRule(logger *log.Logger, param *request.AddRuleRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + req := sdkmonitorRuleParameters.NewAddRuleParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + trOption := []*sdkModels.RuleTrigger{} + for _, v := range param.TriggerOption { + item := &sdkModels.RuleTrigger{ + Calculation: &v.Calculation, + CalculationUnit: v.CalculationUnit, + Metric: &v.Metric, + NoticeLevel: &v.NoticeLevel, + Operation: &v.Operation, + Period: &v.Period, + Threshold: &v.Threshold, + Times: &v.Times, + } + trOption = append(trOption, item) + } + notifyOption := &sdkModels.RuleNotice{ + EffectiveIntervalEnd: ¶m.NoticeOption.EffectiveIntervalEnd, + EffectiveIntervalStart: ¶m.NoticeOption.EffectiveIntervalStart, + NoticeCondition: param.NoticeOption.NoticeCondition, + NoticePeriod: ¶m.NoticeOption.NoticePeriod, + NoticeWay: param.NoticeOption.NoticeWay, + UserID: ¶m.NoticeOption.UserID, + } + body := &sdkModels.AddRuleRequest{ + DeviceTag: param.DeviceTag, + Dimension: ¶m.Dimension, + InstanceIds: param.InstanceIds, + Resource: ¶m.Resource, + RuleName: ¶m.RuleName, + TriggerOption: trOption, + NoticeOption: notifyOption, + } + req.WithBody(body) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("AddRule openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.MonitorRule.AddRule(req, nil) + logger.Info("AddRule openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("AddRule openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil + +} + +func DescribeRule(logger *log.Logger, ruleId string) (*sdkModels.Rule, error) { + logid := logger.GetPoint("logid").(string) + request := sdkmonitorRuleParameters.NewDescribeRuleParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + request.WithRuleID(ruleId) + logger.Info("DescribeRule openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.MonitorRule.DescribeRule(request, nil) + logger.Info("DescribeRule openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeRule openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result, nil + +} + +func DescribeRules(logger *log.Logger, param *request.DescribeRulesRequest, p util.Pageable) (*sdkModels.RuleList, error) { + logid := logger.GetPoint("logid").(string) + request := sdkmonitorRuleParameters.NewDescribeRulesParams() + userId := logger.GetPoint("userId").(string) + request.WithBmpUserID(&userId) + request.WithTraceID(logid) + language := logger.GetPoint("language").(string) + request.WithBmpLanguage(&language) + request.WithIsAll(¶m.IsAll) + request.WithPageNumber(&p.PageNumber) + request.WithPageSize(&p.PageSize) + request.WithUserID(¶m.UserId) + request.WithUserName(¶m.UserName) + request.WithRuleID(¶m.RuleId) + request.WithRuleName(¶m.RuleName) + status := int64(param.Status) + request.WithStatus(&status) + + logger.Info("DescribeRules openapi request:", util.InterfaceToJson(request)) + responseApi, err := openApi.SdkClient.MonitorRule.DescribeRules(request, nil) + logger.Info("DescribeRules openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DescribeRules openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return nil, err + } + return nil, errors.New(respErr.Message) + } + + return responseApi.Payload.Result, nil +} + +func ExportRules(logger *log.Logger, result []*sdkModels.Rule) (fileName, downLoadFileName string) { + + language := logger.GetPoint("language").(string) + + e := excel.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + for _, data := range result { + + sheetData = append(sheetData, []string{ + data.UserName, + data.RuleName, + data.RuleID, + data.ResourceName, + fmt.Sprintf("%d", len(data.InstanceIds)), + strings.Join(data.TriggerDescription, ";"), + data.StatusName, + }) + } + exportRuleHeader := BaseLogic.ExportRulesHeader + if language == "en_US" { + exportRuleHeader = BaseLogic.ExportRulesHeaderEn + } + if err := e.SetSheetData("Sheet1", exportRuleHeader, sheetData); err != nil { + panic(exception.Exception{Msg: "新建excel失败", Status: BaseLogic.ERROR_CODE}) + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + downloadFileName := "rule_list_" + time.Now().Format(BaseLogic.FormatDate) + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" //生成100000到100000+900000之间的随机数,左闭右开 + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Info("保存excel到本地失败" + err.Error()) + panic(exception.Exception{Msg: "保存excel到本地失败", Status: BaseLogic.ERROR_CODE}) + } + return fileName, downloadFileName +} + +func EditRule(logger *log.Logger, param *request.EditRuleRequest) (bool, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkmonitorRuleParameters.NewEditRuleParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + trOption := []*sdkModels.RuleTrigger{} + for _, v := range param.TriggerOption { + item := &sdkModels.RuleTrigger{ + Calculation: &v.Calculation, + CalculationUnit: v.CalculationUnit, + Metric: &v.Metric, + NoticeLevel: &v.NoticeLevel, + Operation: &v.Operation, + Period: &v.Period, + Threshold: &v.Threshold, + Times: &v.Times, + } + trOption = append(trOption, item) + } + notifyOption := &sdkModels.RuleNotice{ + EffectiveIntervalEnd: ¶m.NoticeOption.EffectiveIntervalEnd, + EffectiveIntervalStart: ¶m.NoticeOption.EffectiveIntervalStart, + NoticeCondition: param.NoticeOption.NoticeCondition, + NoticePeriod: ¶m.NoticeOption.NoticePeriod, + NoticeWay: param.NoticeOption.NoticeWay, + UserID: ¶m.NoticeOption.UserID, + } + body := &sdkModels.EditRuleRequest{ + DeviceTag: param.DeviceTag, + Dimension: ¶m.Dimension, + InstanceIds: param.InstanceIds, + Resource: ¶m.Resource, + RuleID: ¶m.RuleId, + RuleName: ¶m.RuleName, + TriggerOption: trOption, + NoticeOption: notifyOption, + } + req.WithBody(body) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("EditRule openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.MonitorRule.EditRule(req, nil) + logger.Info("EditRule openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("EditRule openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil + +} + +func EnableRule(logger *log.Logger, param *request.EnableRuleRequest) (bool, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkmonitorRuleParameters.NewEnableRuleParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := &sdkModels.EnableRuleRequest{ + RuleID: ¶m.RuleId, + } + req.WithBody(body) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("EnableRule openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.MonitorRule.EnableRule(req, nil) + logger.Info("EnableRule openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("EnableRule openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil + +} + +func DisableRule(logger *log.Logger, param *request.DisableRuleRequest) (bool, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkmonitorRuleParameters.NewDisableRuleParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := &sdkModels.DisableRuleRequest{ + RuleID: ¶m.RuleId, + } + req.WithBody(body) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("DisableRule openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.MonitorRule.DisableRule(req, nil) + logger.Info("DisableRule openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DisableRule openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil + +} + +func DeleteRule(logger *log.Logger, param *request.DeleteRuleRequest) (bool, error) { + + logid := logger.GetPoint("logid").(string) + req := sdkmonitorRuleParameters.NewDeleteRuleParams() + req.WithTraceID(logid) + userId := logger.GetPoint("userId").(string) + req.WithBmpUserID(&userId) + + body := &sdkModels.DeleteRuleRequest{ + RuleID: ¶m.RuleId, + } + req.WithBody(body) + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + logger.Info("DeleteRule openapi request:", util.InterfaceToJson(req)) + responseApi, err := openApi.SdkClient.MonitorRule.DeleteRule(req, nil) + logger.Info("DeleteRule openapi response:", util.InterfaceToJson(responseApi)) + if err != nil { + logger.Info("DeleteRule openapi error:", err.Error()) + respErr, b := util.GetOpenapiError(err) + if !b { + return false, err + } + return false, errors.New(respErr.Message) + } + + return responseApi.Payload.Result.Success, nil + +} diff --git a/bmp-operation-api/logic/resourceLogic/resourceLogic.go b/bmp-operation-api/logic/resourceLogic/resourceLogic.go new file mode 100644 index 0000000..584bdf7 --- /dev/null +++ b/bmp-operation-api/logic/resourceLogic/resourceLogic.go @@ -0,0 +1,44 @@ +package resourceLogic + +import ( + "errors" + + sdkClient "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/resource" + sdk "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + log "git.jd.com/cps-golang/log" +) + +// 【设备管理】【设备列表】 +func DescribeResources(logger *log.Logger, param *requestTypes.QueryResourcesRequest) (bool, error) { + logid := logger.GetPoint("logid").(string) + userId := logger.GetPoint("userId").(string) + req := sdkClient.NewDescribeResourcesParams() + language := logger.GetPoint("language").(string) + req.WithBmpLanguage(&language) + req.WithTraceID(logid) + req.WithBmpUserID(&userId) + req.WithImageName(¶m.ImageName) + req.WithName(¶m.Name) + req.WithDeviceType(¶m.DeviceType) + req.WithUserName(¶m.UserName) + + logger.Info("DescribeResources openapi sdk req:", util.InterfaceToJson(req)) + client, err := sdk.SdkClient.Resource.DescribeResources(req, nil) + logger.Info("DescribeResources openapi sdk resp:", util.InterfaceToJson(client)) + + if err != nil { + respErr, b := util.GetOpenapiError(err) + if !b { + logger.Warnf("unknown error:", err.Error()) + return true, errors.New("unknown error") //未知错误不暴露给用户 + } + // respErr.Code + // respErr.Status + // respErr.Message + logger.Warnf("openapi error:", respErr.Message) + return true, errors.New(respErr.Message) + } + return client.Payload.Result.Success, nil +} diff --git a/bmp-operation-api/main b/bmp-operation-api/main new file mode 100755 index 0000000..0489843 Binary files /dev/null and b/bmp-operation-api/main differ diff --git a/bmp-operation-api/main.go b/bmp-operation-api/main.go new file mode 100644 index 0000000..d081d25 --- /dev/null +++ b/bmp-operation-api/main.go @@ -0,0 +1,83 @@ +package main + +import ( + "flag" + "fmt" + "log" + "os" + "time" + + "coding.jd.com/aidc-bmp/bmp-operation-api/controllers" + redisUtil "coding.jd.com/aidc-bmp/bmp-operation-api/services/redis" + sessionUtil "coding.jd.com/aidc-bmp/bmp-operation-api/services/session" + "github.com/beego/beego/v2/core/logs" + + _ "coding.jd.com/aidc-bmp/bmp-operation-api/routers" + + "coding.jd.com/aidc-bmp/bmp-operation-api/services/openApi" + _ "coding.jd.com/aidc-bmp/bmp-operation-api/swaggermodels" + beego "github.com/beego/beego/v2/server/web" + _ "github.com/beego/beego/v2/server/web/session/redis" + _ "github.com/go-sql-driver/mysql" +) + + +const ( + defaultConfigFile = "conf/bmp-operation.ini" +) + +var ( + VERSION = "should be compiled with make." + BUILD_TIME = "should be compiled with make." +) + +var configFile = flag.String("c", defaultConfigFile, "specify config file") +var versionFlag = flag.Bool("v", false, "show version") + +func main() { + + time.LoadLocation("Asia/Shanghai") + flag.Parse() + + if *versionFlag { + fmt.Println("commit_id:", VERSION, "build_time:", BUILD_TIME) + os.Exit(0) + } + + log.Println("[bmp-operation] start...") + // logs.SetLogger(logs.Adapteroperation) + logs.SetLevel(logs.LevelTrace) + logs.EnableFuncCallDepth(true) + logs.SetLogFuncCallDepth(3) + logs.Info("============== Start========") + + // initial Config From file + if err := beego.LoadAppConfig("ini", *configFile); err != nil { + fmt.Println("LoadAppConfig Error:", err.Error()) + return + } + //if err := initGormDB(); err != nil { + // fmt.Println("initGormDB() Error:", err.Error()) + // return + //} + + //kafka, 创建实例付费成功接收msg + // kafkaOrderHost, _ := beego.AppConfig.String("kafka.order.bootstrap-server") + // kafkaOrderTopic, _ := beego.AppConfig.String("kafka.order.topic.order_produce") + // go kafka.Consume(kafkaOrderHost, kafkaOrderTopic) + + // TODO 监听付款成功的kafka消息,然后请求innerCreateInstance + controllers.Init() + openApi.Init() + redisUtil.Init() + sessionUtil.Init() + + beego.BConfig.MaxUploadSize = 1 << 35 //32G + beego.Run() +} + +// func initGormDB() error { +// // initial mysql +// sqlconn, _ := beego.AppConfig.String("jdbc.url") //mysql +// return dao.InitGormDb(sqlconn) +// } diff --git a/bmp-operation-api/routers/router.go b/bmp-operation-api/routers/router.go new file mode 100644 index 0000000..0b45b8d --- /dev/null +++ b/bmp-operation-api/routers/router.go @@ -0,0 +1,305 @@ +// @APIVersion 1.0.0 +// @Title beego Test API +// @Description beego has a very cool tools to autogenerate documents for your API +// @Contact astaxie@gmail.com +// @TermsOfServiceUrl http://beego.me/ +// @License Apache 2.0 +// @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html +package routers + +import ( + "coding.jd.com/aidc-bmp/bmp-operation-api/controllers" + beego "github.com/beego/beego/v2/server/web" +) + +func init() { + + beego.Router("/ws/msg", &controllers.WebSocketController{}) + beego.Router("/ws/innerSendmsg", &controllers.WebSocketController{}, "post:Send") + + beego.Router("/login", &controllers.UserController{}, "post:Login") + beego.Router("/logout", &controllers.UserController{}, "post:Logout") + + // 后面用户角色校验时需要放开 + // beego.InsertFilter("/*", beego.BeforeRouter, controllers.Authentication) + // beego.InsertFilter("/api/*", beego.BeforeRouter, controllers.Authentication) + + // beego.InsertFilter("/*", beego.BeforeRouter, filter.FilterPin) + + //----------------------------- operation api ---------------------------------------- + beego.Router("/filterList", &controllers.CustomController{}, "get:FilterList") + customer := beego.NewNamespace("/custom", + beego.NSRouter("/setCustomInfo", &controllers.CustomController{}, "post:SetCustomInfo"), //暂时没用到,前端自己存 + beego.NSRouter("/getCustomInfo", &controllers.CustomController{}, "get:GetCustomInfo"), + ) + beego.AddNamespace(customer) + UserNS := beego.NewNamespace("/users", + beego.NSRouter("/", &controllers.UserController{}, "put:AddUser"), + beego.NSRouter("/", &controllers.UserController{}, "get:GetUserList"), + beego.NSRouter("/?:user_id", &controllers.UserController{}, "get:GetUserInfo"), + beego.NSRouter("/?:user_id", &controllers.UserController{}, "post:ModifyUserInfo"), + beego.NSRouter("/?:user_id", &controllers.UserController{}, "delete:DeleteUserInfo"), + beego.NSRouter("/login/validate", &controllers.UserController{}, "post:VerifyLoginUser"), + ) + beego.AddNamespace(UserNS) + + //【设备管理】 + deviceNS := beego.NewNamespace("/devices", + beego.NSRouter("/queryDevices", &controllers.DeviceController{}, "get:QueryDevices"), + beego.NSRouter("/queryDevice/?:device_id", &controllers.DeviceController{}, "get:GetDevice"), + + beego.NSRouter("/unPutaway", &controllers.DeviceController{}, "put:UnPutaway"), + beego.NSRouter("/putaway", &controllers.DeviceController{}, "put:Putaway"), + //设备关联机型 + beego.NSRouter("/deviceType/associate", &controllers.DeviceController{}, "put:DeviceAssociateDeviceType"), + beego.NSRouter("/?:device_id", &controllers.DeviceController{}, "delete:DeleteDevice"), + beego.NSRouter("/?:device_id", &controllers.DeviceController{}, "put:ModifyDevice"), + + beego.NSRouter("/upload", &controllers.DeviceController{}, "post:UploadDevices"), + beego.NSRouter("/collect", &controllers.DeviceController{}, "post:CollectDevice"), + beego.NSRouter("/", &controllers.DeviceController{}, "post:CreateDevices"), + beego.NSRouter("/?:device_id/remove", &controllers.DeviceController{}, "put:RemoveDevice"), + //设备详情-磁盘 + beego.NSRouter("/?:device_id/disksDetail", &controllers.DeviceController{}, "get:GetDeviceDiskDetail"), + //获取设备关联的磁盘信息 + beego.NSRouter("/disks/describeAssociateDisks", &controllers.DeviceController{}, "get:GetAssociatedDisks"), + //设备关联磁盘 + beego.NSRouter("/disks/associateDisks", &controllers.DeviceController{}, "put:AssociateDeviceDisks"), + ) + beego.AddNamespace(deviceNS) + + // 【机型管理】 + DeviceTypeNS := beego.NewNamespace("/deviceTypes", + beego.NSRouter("/", &controllers.DeviceTypeController{}, "put:CreateDeviceType"), + beego.NSRouter("/", &controllers.DeviceTypeController{}, "get:QueryDeviceTypes"), + beego.NSRouter("/queryDeviceType/?:device_type_id", &controllers.DeviceTypeController{}, "get:QueryDeviceType"), + beego.NSRouter("/deviceTypeImage", &controllers.DeviceTypeController{}, "get:QueryDeviceTypeImages"), + beego.NSRouter("/associatedImage", &controllers.DeviceTypeController{}, "post:AssociateDeviceTypeImage"), + beego.NSRouter("/dissociatedImage", &controllers.DeviceTypeController{}, "post:DisassociateDeviceTypeImage"), + beego.NSRouter("/?:device_type_id", &controllers.DeviceTypeController{}, "put:ModifyDeviceType"), + beego.NSRouter("/?:device_type_id", &controllers.DeviceTypeController{}, "delete:DeleteDeviceType"), + beego.NSRouter("/?:device_type_id/describeVolumes", &controllers.DeviceTypeController{}, "get:DescribeVolumesByDeviceType"), + //以下是重装使用的接口 + beego.NSRouter("/getAvailableDeviceTypes", &controllers.DeviceTypeController{}, "get:GetAvailableDeviceTypes"), //td + ) + beego.AddNamespace(DeviceTypeNS) + + OsNS := beego.NewNamespace("/oss", + beego.NSRouter("/", &controllers.OsController{}, "get:DescribeOSs"), + beego.NSRouter("/filter", &controllers.OsController{}, "get:DescribeOSsFilter"), + ) + beego.AddNamespace(OsNS) + RoleNS := beego.NewNamespace("/roles", + beego.NSRouter("/", &controllers.RoleController{}, "get:DescribeRoles"), + beego.NSRouter("/roleInfo/current", &controllers.RoleController{}, "get:CurrentRole"), + ) + beego.AddNamespace(RoleNS) + + ImageNS := beego.NewNamespace("/images", + beego.NSRouter("/", &controllers.ImageController{}, "post:CreateImage"), + beego.NSRouter("/", &controllers.ImageController{}, "get:DescribeImages"), + beego.NSRouter("/?:image_id", &controllers.ImageController{}, "get:DescribeImage"), + beego.NSRouter("/?:image_id", &controllers.ImageController{}, "put:ModifyImage"), + beego.NSRouter("/?:image_id", &controllers.ImageController{}, "delete:DeleteImage"), + beego.NSRouter("/upload", &controllers.ImageController{}, "post:UploadImage"), + beego.NSRouter("/imageDeviceTypes", &controllers.ImageController{}, "get:DescribeImageDeviceTypes"), + beego.NSRouter("/associatedDeviceType", &controllers.ImageController{}, "post:AssociatedDeviceType"), + beego.NSRouter("/dissociatedDeviceType", &controllers.ImageController{}, "delete:DissociatedDeviceType"), + + beego.NSRouter("/queryImagesByDeviceType", &controllers.ImageController{}, "get:QueryImagesByDeviceType"), + ) + beego.AddNamespace(ImageNS) + + RaidNS := beego.NewNamespace("/raids", + // beego.NSRouter("/", &controllers.RaidController{}, "post:CreateRaid"), + // beego.NSRouter("/deviceTypeRaid", &controllers.RaidController{}, "post:CreateDeviceTypeRaid"), + // beego.NSRouter("/deviceTypeRaid", &controllers.RaidController{}, "delete:DeleteDeviceTypeRaid"), + // beego.NSRouter("/", &controllers.RaidController{}, "get:QueryRaidsAll"), //QueryRaids + beego.NSRouter("/", &controllers.RaidController{}, "get:QueryRaidsAll"), + // beego.NSRouter("/?:raid_id", &controllers.RaidController{}, "get:GetRaid"), + // beego.NSRouter("/?:raid_id", &controllers.RaidController{}, "put:ModifyRaid"), + // beego.NSRouter("/?:raid_id", &controllers.RaidController{}, "delete:DeleteRaid"), + beego.NSRouter("/queryRaidsByDeviceTypeIDAndVolumeType", &controllers.RaidController{}, "get:QueryRaidsByDeviceTypeIDAndVolumeType"), + ) + beego.AddNamespace(RaidNS) + + InstanceNS := beego.NewNamespace("/instances", + // beego.NSRouter("/", &controllers.InstanceController{}, "post:CreateInstance"), + // beego.NSRouter("/", &controllers.InstanceController{}, "get:GetInstanceList"), + beego.NSRouter("/?:instance_id", &controllers.InstanceController{}, "get:GetInstanceInfo"), + // beego.NSRouter("/?:instance_id", &controllers.InstanceController{}, "put:ModifyInstance"), + // beego.NSRouter("/?:instance_id", &controllers.InstanceController{}, "delete:DeleteInstance"), + // beego.NSRouter("/lock/?:instance_id", &controllers.InstanceController{}, "put:LockInstance"), //锁定 + // beego.NSRouter("/unlock/?:instance_id", &controllers.InstanceController{}, "put:UnLockInstance"), //解锁定 + beego.NSRouter("/start/?:instance_id", &controllers.InstanceController{}, "post:StartInstance"), //开机 + beego.NSRouter("/restart/?:instance_id", &controllers.InstanceController{}, "post:RestartInstance"), //重启 + beego.NSRouter("/stop/?:instance_id", &controllers.InstanceController{}, "post:StopInstance"), //关机 + beego.NSRouter("/resetStatus/?:instance_id", &controllers.InstanceController{}, "post:ResetInstanceStatus"), //重置实例状态 + beego.NSRouter("/?:instance_id", &controllers.InstanceController{}, "delete:DeleteInstance"), //回收实例 + beego.NSRouter("/lock/?:instance_id", &controllers.InstanceController{}, "post:LockInstance"), + beego.NSRouter("/unlock/?:instance_id", &controllers.InstanceController{}, "post:UnlockInstance"), + beego.NSRouter("/startInstances", &controllers.InstanceController{}, "post:StartInstances"), //批量开机 + beego.NSRouter("/stopInstances", &controllers.InstanceController{}, "post:StopInstances"), //批量关机 + beego.NSRouter("/restartInstances", &controllers.InstanceController{}, "post:RestartInstances"), //批量重启 + beego.NSRouter("/modifyInstances", &controllers.InstanceController{}, "post:ModifyInstances"), //批量编辑实例名称 + beego.NSRouter("/deleteInstances", &controllers.InstanceController{}, "delete:DeleteInstances"), //批量删除 + beego.NSRouter("/resetPasswd", &controllers.InstanceController{}, "post:ResetPasswd"), + beego.NSRouter("/batchResetPasswd", &controllers.InstanceController{}, "post:ResetInstancesPasswd"), + beego.NSRouter("/reinstallInstance", &controllers.InstanceController{}, "post:ReinstallInstance"), //重装实例 + ) + beego.AddNamespace(InstanceNS) + + // + //monitorNs := beego.NewNamespace("/offline") //beego.NSRouter("/instance/queryBySn", &controllers.InstanceController{}, "get:QueryBySn"), + // + //beego.AddNamespace(monitorNs) + + //RoleSN := beego.NewNamespace("/roles", + // beego.NSRouter("/", &controllers.RoleController{}, "post:CreateRole"), + // beego.NSRouter("/", &controllers.RoleController{}, "get:GetRoleList"), + // beego.NSRouter("/?:role_id", &controllers.RoleController{}, "get:GetRole"), + // beego.NSRouter("/?:role_id", &controllers.RoleController{}, "put:ModifyRole"), + // beego.NSRouter("/?:role_id", &controllers.RoleController{}, "delete:DeleteRole"), + //) + //beego.AddNamespace(RoleSN) + // + //ProjectSN := beego.NewNamespace("/projects", + // beego.NSRouter("/", &controllers.ProjectController{}, "post:CreateProject"), + // beego.NSRouter("/", &controllers.ProjectController{}, "get:GetProjectList"), + // beego.NSRouter("/?:project_id", &controllers.ProjectController{}, "get:GetProject"), + // beego.NSRouter("/?:project_id", &controllers.ProjectController{}, "put:ModifyProject"), + // beego.NSRouter("/?:project_id", &controllers.ProjectController{}, "delete:DeleteProject"), + //) + //beego.AddNamespace(ProjectSN) + //SshkeySN := beego.NewNamespace("/sshkeys", + // beego.NSRouter("/", &controllers.SshkeyController{}, "post:CreateSshkey"), + // beego.NSRouter("/", &controllers.SshkeyController{}, "get:GetSshkeyList"), + // beego.NSRouter("/?:sshkey_id", &controllers.SshkeyController{}, "get:GetSshkey"), + // beego.NSRouter("/?:sshkey_id", &controllers.SshkeyController{}, "put:ModifySshkey"), + // beego.NSRouter("/?:sshkey_id", &controllers.SshkeyController{}, "delete:DeleteSshkey"), + // beego.NSRouter("/instances/?:sshkey_id", &controllers.SshkeyController{}, "get:GetInstancesBySshkey"), + //) + //beego.AddNamespace(SshkeySN) + //ApikeySN := beego.NewNamespace("/apikeys", + // beego.NSRouter("/", &controllers.ApikeyController{}, "post:CreateApikey"), + // beego.NSRouter("/", &controllers.ApikeyController{}, "get:GetApikeyList"), + // beego.NSRouter("/?:apikey_id", &controllers.ApikeyController{}, "get:GetApikey"), + // beego.NSRouter("/?:apikey_id", &controllers.ApikeyController{}, "put:ModifyApikey"), + // beego.NSRouter("/?:apikey_id", &controllers.ApikeyController{}, "delete:DeleteApikey"), + //) + //beego.AddNamespace(ApikeySN) + + keypairNS := beego.NewNamespace("/keypair", + beego.NSRouter("/", &controllers.KeypairController{}, "get:GetKeypairList"), + ) + beego.AddNamespace(keypairNS) + + IdcNS := beego.NewNamespace("/idc", + beego.NSRouter("/", &controllers.IdcController{}, "put:CreateIdc"), + beego.NSRouter("/", &controllers.IdcController{}, "get:GetIdcList"), + beego.NSRouter("/?:idc_id", &controllers.IdcController{}, "get:GetIdcInfo"), + beego.NSRouter("/?:idc_id", &controllers.IdcController{}, "delete:DeleteIdc"), + beego.NSRouter("/?:idc_id", &controllers.IdcController{}, "put:ModifyIdcInfo"), + beego.NSRouter("/VerifyUser", &controllers.IdcController{}, "post:VerifyUser"), + ) + beego.AddNamespace(IdcNS) + + userNS := beego.NewNamespace("/user/local", + beego.NSRouter("/", &controllers.UserController{}, "get:GetLocalUserInfo"), //td + beego.NSRouter("/password", &controllers.UserController{}, "put:UpdateLocalPassword"), //td + beego.NSRouter("/", &controllers.UserController{}, "put:UpdateLocalUserInfo"), //td + beego.NSRouter("/timezones", &controllers.TimezoneController{}, "get:GetTimezoneList"), + ) + beego.AddNamespace(userNS) + + apikeyNS := beego.NewNamespace("/apikey", + beego.NSRouter("/", &controllers.ApikeyController{}, "put:CreateApikey"), //td + beego.NSRouter("/", &controllers.ApikeyController{}, "get:GetApikeyList"), + beego.NSRouter("/?:apikey_id", &controllers.ApikeyController{}, "delete:DeleteApikey"), + ) + beego.AddNamespace(apikeyNS) + + resource := beego.NewNamespace("/resources", + beego.NSRouter("/", &controllers.ResourceController{}, "get:DescribeResources"), + ) + beego.AddNamespace(resource) + + partitionNS := beego.NewNamespace("/partition", + beego.NSRouter("/queryDefaultSystemPartitions", &controllers.PartitionController{}, "get:QueryDefaultSystemPartitions"), //td + ) + beego.AddNamespace(partitionNS) + + messageNS := beego.NewNamespace("/messages", + beego.NSRouter("/hasUnreadMessage", &controllers.MessageController{}, "get:HasUnreadMessage"), + beego.NSRouter("/", &controllers.MessageController{}, "get:GetMessageList"), + beego.NSRouter("/statistic", &controllers.MessageController{}, "get:GetMessageStatistic"), + beego.NSRouter("/doRead", &controllers.MessageController{}, "put:ReadMessage"), + beego.NSRouter("/delete", &controllers.MessageController{}, "delete:DeleteMessage"), + beego.NSRouter("/getMessageById", &controllers.MessageController{}, "get:GetMessageById"), + beego.NSRouter("/getMessageTypes", &controllers.MessageController{}, "get:GetMessageTypes"), + beego.NSRouter("/dialMail", &controllers.MessageController{}, "post:DialMail"), + beego.NSRouter("/saveIsPushMail", &controllers.MessageController{}, "post:SaveIsPushMail"), + beego.NSRouter("/describeMail", &controllers.MessageController{}, "get:DescribeMail"), + ) + beego.AddNamespace(messageNS) + + auditLogNS := beego.NewNamespace("/auditLogs", + beego.NSRouter("/", &controllers.AuditLogsController{}, "get:DescribeAuditLogs"), + beego.NSRouter("/types", &controllers.AuditLogsController{}, "get:DescribeAuditLogTypes"), + ) + beego.AddNamespace(auditLogNS) + + //报警规则相关 + monitorRuleNs := + beego.NewNamespace("/monitorRule", + //添加规则 + beego.NSRouter("/addRule", &controllers.MonitorRuleController{}, "post:AddRule"), + //规则详情 + beego.NSRouter("/describeRule", &controllers.MonitorRuleController{}, "get:DescribeRule"), + //规则列表 + beego.NSRouter("/describeRules", &controllers.MonitorRuleController{}, "get:DescribeRules"), + //编辑规则 + beego.NSRouter("/editRule", &controllers.MonitorRuleController{}, "put:EditRule"), + //启用规则 + beego.NSRouter("/enableRule", &controllers.MonitorRuleController{}, "put:EnableRule"), + //禁用规则 + beego.NSRouter("/disableRule", &controllers.MonitorRuleController{}, "put:DisableRule"), + //删除规则 + beego.NSRouter("/deleteRule", &controllers.MonitorRuleController{}, "delete:EditRule"), + ) + + beego.AddNamespace(monitorRuleNs) + + //监控报警相关 + monitorAlertNs := + beego.NewNamespace("/monitorAlert", + //告警详情 + beego.NSRouter("/describeAlert", &controllers.MonitorAlertController{}, "get:DescribeAlert"), + //告警列表 + beego.NSRouter("/describeAlerts", &controllers.MonitorAlertController{}, "get:DescribeAlerts"), + //删除告警 + beego.NSRouter("/deleteAlert", &controllers.MonitorAlertController{}, "delete:DeleteAlert"), + ) + + beego.AddNamespace(monitorAlertNs) + + //带内监控-图表数据获取 + monitorDataNs := + beego.NewNamespace("/monitorData", + beego.NSRouter("/", &controllers.MonitorDataController{}, "get:GetMonitorData"), + ) + + beego.AddNamespace(monitorDataNs) + + //带内监控-获取agent状态、获取tag列表 + monitorProxyNs := + beego.NewNamespace("/monitorProxy", + beego.NSRouter("/desrcibeAgentStatus", &controllers.MonitorProxyController{}, "get:DesrcibeAgentStatus"), + beego.NSRouter("/desrcibeTags", &controllers.MonitorProxyController{}, "get:DesrcibeTags"), + ) + + beego.AddNamespace(monitorProxyNs) + +} + +//TODO queryRaidsByDeviceTypeIDAndVolumeType queryDefaultSystemPartitions 未完成 diff --git a/bmp-operation-api/services/excel/excel.go b/bmp-operation-api/services/excel/excel.go new file mode 100644 index 0000000..dc0d198 --- /dev/null +++ b/bmp-operation-api/services/excel/excel.go @@ -0,0 +1,146 @@ +package excel + +import ( + beego "github.com/beego/beego/v2/server/web" + "os" + "path/filepath" + "strconv" + + "coding.jd.com/aidc-bmp/bmp-operation-api/util" + "github.com/xuri/excelize/v2" +) + +type IExcel interface { + GetSheetData() ([][]string, error) + SetSheetData(string, []string, [][]string) error + SetNewSheet(string) int + SaveFile(string) (string, error) + SetSheetHeader(string, []string) error + SetSheetDataRandom(string, string, [][]string, int) error +} + +type Excel struct { + File *excelize.File +} + +func NewExcelInstance() *Excel { + return &Excel{ + File: excelize.NewFile(), + } +} + +func LoadExcel(fileName string) (*Excel, error) { + f, err := excelize.OpenFile(fileName) + if err != nil { + return nil, err + } + return &Excel{ + File: f, + }, nil +} + +func (e *Excel) GetSheetData() ([][]string, error) { + index := e.File.GetActiveSheetIndex() + name := e.File.GetSheetName(index) + return e.File.GetRows(name) +} + +func (e *Excel) SetNewSheet(sheetName string) int { + return e.File.NewSheet(sheetName) +} + +func (e *Excel) SetSheetHeader(sheetName string, sheetHeaders []string) error { + colNum, rowNum := 1, 1 + for _, header := range sheetHeaders { + //从第一列开始获取每列第一个元素位置 + axis, err := excelize.ColumnNumberToName(colNum) + if err != nil { + return err + } + axis = axis + strconv.Itoa(rowNum) + if err = e.File.SetCellValue(sheetName, axis, header); err != nil { + return err + } + colNum++ + } + return nil +} + +func (e *Excel) SetSheetDataRandom(requestId, sheetName string, sheetData [][]string, rowNum int) error { + for _, row := range sheetData { + colNum := 1 + for _, value := range row { + axis, err := excelize.ColumnNumberToName(colNum) + if err != nil { + return err + } + axis = axis + strconv.Itoa(rowNum) + if err := e.File.SetCellValue(sheetName, axis, value); err != nil { + return err + } + colNum++ + } + rowNum++ + } + return nil +} + +func (e *Excel) SetSheetData(sheetName string, sheetHeaders []string, sheetData [][]string) error { + if err := e.SetSheetHeader(sheetName, sheetHeaders); err != nil { + return err + } + rowNum := 2 + for _, row := range sheetData { + colNum := 1 + for _, value := range row { + axis, err := excelize.ColumnNumberToName(colNum) + if err != nil { + return err + } + axis = axis + strconv.Itoa(rowNum) + if err := e.File.SetCellValue(sheetName, axis, value); err != nil { + return err + } + colNum++ + } + rowNum++ + } + return nil +} + +func (e *Excel) SaveFile(fileName string) (string, error) { + basePath, err := os.Executable() + if err != nil { + return "", err + } + res, err := filepath.EvalSymlinks(filepath.Dir(basePath)) + if err != nil { + return "", err + } + excelPath, _ := beego.AppConfig.String("upload.path") + CreateDirIfNotExist(excelPath + "/") + fileName = filepath.Join(res, excelPath+"/", util.GenUuid()+fileName) + return fileName, e.File.SaveAs(fileName) +} + +/** +判断文件是否存在 +*/ +func CreateDirIfNotExist(fileAddr string) bool { + s, err := os.Stat(fileAddr) + if err != nil { + return CreateDir(fileAddr) + } + return s.IsDir() +} + +/** +创建文件夹 +*/ +func CreateDir(dirName string) bool { + err := os.Mkdir(dirName, 0777) + if err != nil { + return false + } + return true +} diff --git a/bmp-operation-api/services/openApi/openApi.go b/bmp-operation-api/services/openApi/openApi.go new file mode 100644 index 0000000..53928b2 --- /dev/null +++ b/bmp-operation-api/services/openApi/openApi.go @@ -0,0 +1,37 @@ +package openApi + +import ( + "fmt" + + sdk "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client" + beego "github.com/beego/beego/v2/server/web" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +var ( + SdkClient *sdk.CPS +) + +func Init() { + + host, _ := beego.AppConfig.String("openapi_host") + port, _ := beego.AppConfig.String("openapi_port") + host = fmt.Sprintf("%s:%s", host, port) + fmt.Println("openapi host:", host) + + token, _ := beego.AppConfig.String("openapi_token") + /* + cfg := sdk.TransportConfig{ + Host: host, + BasePath: "/v1", + Schemes: []string{"http"}, + } + SdkClient = sdk.NewHTTPClientWithConfig(nil, &cfg) + */ + + r := httptransport.New(host, "/v1", []string{"http"}) + r.SetDebug(true) + r.DefaultAuthentication = httptransport.BearerToken(token) + SdkClient = sdk.New(r, strfmt.Default) +} diff --git a/bmp-operation-api/services/redis/redis.go b/bmp-operation-api/services/redis/redis.go new file mode 100644 index 0000000..e46dd9f --- /dev/null +++ b/bmp-operation-api/services/redis/redis.go @@ -0,0 +1,35 @@ +package redis + +import ( + "fmt" + + beego "github.com/beego/beego/v2/server/web" + "github.com/go-redis/redis" +) + +var RedisCli *redis.Client + +// InitRedis initial redisUtil instance +func Init() error { + var host, port, password string + var dbNum int + //namespace, _ = beego.AppConfig.String("bmp_redis_namespace") + host, _ = beego.AppConfig.String("bmp_redis_host") + port, _ = beego.AppConfig.String("bmp_redis_port") + password, _ = beego.AppConfig.String("bmp_redis_password") + dbNum = beego.AppConfig.DefaultInt("bmp_redis_db", 0) + //addr := fmt.Sprintf("%s:%s", host, port) + //return redisInit.InitRedis(namespace, addr, password, dbNum) + + RedisCli = redis.NewClient(&redis.Options{ + Addr: host + ":" + port, + Password: password, // no password set + DB: dbNum, // use default DB + }) + _, err := RedisCli.Ping().Result() + if err != nil { + fmt.Println("redis connect error:", RedisCli, err) + return err + } + return nil +} diff --git a/bmp-operation-api/services/session/session.go b/bmp-operation-api/services/session/session.go new file mode 100644 index 0000000..100afeb --- /dev/null +++ b/bmp-operation-api/services/session/session.go @@ -0,0 +1,28 @@ +package session + +import ( + "fmt" + + beego "github.com/beego/beego/v2/server/web" +) + +func Init() error { + + cookieName, _ := beego.AppConfig.String("sessionname") + sessionLife, _ := beego.AppConfig.Int64("sessionlife") + + redisHost, _ := beego.AppConfig.String("bmp_redis_host") + redisPort, _ := beego.AppConfig.Int("bmp_redis_port") + redisPassword, _ := beego.AppConfig.String("bmp_redis_password") + redisProvider := fmt.Sprintf("%s:%d,10,%s", redisHost, redisPort, redisPassword) + fmt.Println("session.redis.provicer:", redisProvider) + + beego.BConfig.WebConfig.Session.SessionOn = true + beego.BConfig.WebConfig.Session.SessionName = cookieName + //beego.BConfig.WebConfig.Session.SessionCookieLifeTime = sessionLife + beego.BConfig.WebConfig.Session.SessionGCMaxLifetime = sessionLife + beego.BConfig.WebConfig.Session.SessionProvider = "redis" + beego.BConfig.WebConfig.Session.SessionProviderConfig = redisProvider + + return nil +} diff --git a/bmp-operation-api/swagger.yml b/bmp-operation-api/swagger.yml new file mode 100644 index 0000000..9be8ed6 --- /dev/null +++ b/bmp-operation-api/swagger.yml @@ -0,0 +1,4488 @@ +basePath: / +consumes: + - application/json +definitions: + AddUserRequest: + description: 【用户管理】【添加用户】 + properties: + description: + type: string + x-go-name: Description + email: + type: string + x-go-name: Email + language: + type: string + x-go-name: Language + password: + type: string + x-go-name: Password + phoneNumber: + type: string + x-go-name: PhoneNumber + phonePrefix: + type: string + x-go-name: PhonePrefix + roleId: + description: BaseRequest + type: string + x-go-name: RoleID + userName: + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + AssociateDeviceTypeImageRequest: + properties: + deviceTypeId: + type: string + x-go-name: DeviceTypeID + imageIds: + type: string + x-go-name: ImageIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + CommonResponse: + description: 新增加或者删除返给前端的true或者false + properties: + success: + type: boolean + x-go-name: Success + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + CreateDeviceRequest: + properties: + deviceTypeId: + type: string + x-go-name: DeviceTypeId + devices: + items: + $ref: '#/definitions/UploadDevice' + type: array + x-go-name: Devices + idcId: + type: string + x-go-name: IdcId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + CreateDeviceTypeRequest: + description: 机型管理 模块请求字段 + properties: + architecture: + type: string + x-go-name: Architecture + bootMode: + description: boot模式[UEFI Legacy/BIOS]支持多选,逗号分隔 + type: string + x-go-name: BootMode + cpuAmount: + format: int64 + type: integer + x-go-name: CPUAmount + cpuCores: + format: int64 + type: integer + x-go-name: CPUCores + cpuFrequency: + type: string + x-go-name: CPUFrequency + cpuManufacturer: + type: string + x-go-name: CPUManufacturer + cpuModel: + type: string + x-go-name: CPUModel + cpuSpec: + description: CPU 预置规格 + type: string + x-go-name: CpuSpec + createdBy: + type: string + x-go-name: CreatedBy + createdTime: + format: int64 + type: integer + x-go-name: CreatedTime + dataVolumeAmount: + format: int64 + type: integer + x-go-name: DataVolumeAmount + dataVolumeInterfaceType: + type: string + x-go-name: DataVolumeInterfaceType + dataVolumeSize: + format: double + type: number + x-go-name: DataVolumeSize + dataVolumeType: + type: string + x-go-name: DataVolumeType + dataVolumeUnit: + type: string + x-go-name: DataVolumeUnit + description: + type: string + x-go-name: Description + deviceSeries: + type: string + x-go-name: DeviceSeries + deviceType: + type: string + x-go-name: DeviceType + gpuAmount: + format: int64 + type: integer + x-go-name: GpuAmount + gpuManufacturer: + type: string + x-go-name: GpuManufacturer + gpuModel: + type: string + x-go-name: GpuModel + height: + format: int64 + type: integer + x-go-name: Height + idcId: + description: ID int `gorm:"primaryKey;column:id" json:"-"` // 主键 + type: string + x-go-name: IDcID + interfaceMode: + type: string + x-go-name: InterfaceMode + memAmount: + format: int64 + type: integer + x-go-name: MemAmount + memFrequency: + format: int64 + type: integer + x-go-name: MemFrequency + memSize: + format: int64 + type: integer + x-go-name: MemSize + memSpec: + description: 内存 预置规格 + type: string + x-go-name: MemSpec + memType: + type: string + x-go-name: MemType + name: + description: DeviceTypeID string `json:"deviceTypeId"` // 设备类型uuid + type: string + x-go-name: Name + nicAmount: + format: int64 + type: integer + x-go-name: NicAmount + nicRate: + format: int64 + type: integer + x-go-name: NicRate + raidCan: + description: 是否做raid,[RAID/NO RAID] + type: string + x-go-name: RaidCan + raidId: + type: string + x-go-name: RaidID + systemVolumeAmount: + format: int64 + type: integer + x-go-name: SystemVolumeAmount + systemVolumeInterfaceType: + type: string + x-go-name: SystemVolumeInterfaceType + systemVolumeSize: + format: double + type: number + x-go-name: SystemVolumeSize + systemVolumeType: + type: string + x-go-name: SystemVolumeType + systemVolumeUnit: + type: string + x-go-name: SystemVolumeUnit + updatedBy: + type: string + x-go-name: UpdatedBy + updatedTime: + format: int64 + type: integer + x-go-name: UpdatedTime + required: + - cpuSpec + - memSpec + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + CreateDeviceTypeResult: + properties: + deviceTypeId: + type: string + x-go-name: DeviceTypeId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + CreateIdcRequest: + description: 机房管理 模块请求字段 + properties: + address: + type: string + x-go-name: Address + iloPassword: + description: ilo password + type: string + x-go-name: IloPassword + iloUser: + description: ilo user + type: string + x-go-name: IloUser + level: + description: level + type: string + x-go-name: Level + name: + description: name + type: string + x-go-name: Name + nameEn: + description: nameEn + type: string + x-go-name: NameEn + shortname: + description: shortname + type: string + x-go-name: Shortname + switchPassword1: + description: switch password1 + type: string + x-go-name: SwitchPassword1 + switchPassword2: + description: switch password2 + type: string + x-go-name: SwitchPassword2 + switchUser1: + description: switch user1 + type: string + x-go-name: SwitchUser1 + switchUser2: + description: switch user2 + type: string + x-go-name: SwitchUser2 + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + CreateIdcResult: + properties: + idcId: + type: string + x-go-name: IdcId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + CreateImageRequest: + properties: + architecture: + type: string + x-go-name: Architecture + bootMode: + description: boot模式[UEFI Legacy/BIOS]支持多选,逗号分隔 + type: string + x-go-name: BootMode + dataPartition: + type: string + x-go-name: DataPartition + description: + type: string + x-go-name: Description + fileName: + type: string + x-go-name: FileName + format: + description: |- + OsID string `json:"osId" validate:"required"` + ImageFile multipart.File `json:"imageFile"` + type: string + x-go-name: Format + hash: + type: string + x-go-name: Hash + imageName: + type: string + x-go-name: ImageName + osType: + type: string + x-go-name: OsType + systemPartition: + type: string + x-go-name: SystemPartition + url: + type: string + x-go-name: Url + version: + type: string + x-go-name: Version + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + Device: + properties: + adapterId: + format: int64 + type: integer + x-go-name: AdapterID + architecture: + type: string + x-go-name: Architecture + brand: + description: 硬件配置 + type: string + x-go-name: Brand + cabinet: + type: string + x-go-name: Cabinet + cpuAmount: + format: int64 + type: integer + x-go-name: CPUAmount + cpuCores: + format: int64 + type: integer + x-go-name: CPUCores + cpuFrequency: + type: string + x-go-name: CPUFrequency + cpuInfo: + description: 额外拼接的字段,省去前端工作 + type: string + x-go-name: CpuInfo + cpuManufacturer: + type: string + x-go-name: CPUManufacturer + cpuModel: + type: string + x-go-name: CPUModel + cpuRoads: + format: int8 + type: integer + x-go-name: CPURoads + createdBy: + type: string + x-go-name: CreatedBy + createdTime: + type: string + x-go-name: CreatedTime + dataVolumeAmount: + description: DataVolumeUnit string `json:"dataVolumeUnit"` // 数据盘单位(GB,TB) + format: int64 + type: integer + x-go-name: DataVolumeAmount + dataVolumeInterfaceType: + type: string + x-go-name: DataVolumeInterfaceType + dataVolumeSize: + format: int64 + type: integer + x-go-name: DataVolumeSize + dataVolumeType: + type: string + x-go-name: DataVolumeType + description: + type: string + x-go-name: Description + deviceId: + type: string + x-go-name: DeviceID + deviceSeries: + type: string + x-go-name: DeviceSeries + deviceSeriesName: + type: string + x-go-name: DeviceSeriesName + deviceType: + type: string + x-go-name: DeviceType + deviceTypeId: + type: string + x-go-name: DeviceTypeID + deviceTypeName: + type: string + x-go-name: DeviceTypeName + dvInfo: + type: string + x-go-name: DvInfo + enclosure1: + description: 添加到disk表 + type: string + x-go-name: Enclosure1 + enclosure2: + type: string + x-go-name: Enclosure2 + eth1Mask: + type: string + x-go-name: Eth1Mask + gateway: + type: string + x-go-name: Gateway + gpuAmount: + format: int64 + type: integer + x-go-name: GpuAmount + gpuInfo: + type: string + x-go-name: GpuInfo + gpuManufacturer: + type: string + x-go-name: GpuManufacturer + gpuModel: + type: string + x-go-name: GpuModel + id: + format: int64 + type: integer + x-go-name: ID + idcId: + type: string + x-go-name: IdcID + idcName: + description: 以下是通过别的表查询出来的数据,用于返回给上层 + type: string + x-go-name: IdcName + idcNameEn: + type: string + x-go-name: IdcNameEn + iloIp: + type: string + x-go-name: IloIP + iloPassword: + type: string + x-go-name: IloPassword + iloUser: + type: string + x-go-name: IloUser + imageName: + type: string + x-go-name: ImageName + instanceCreatedTime: + type: string + x-go-name: InstanceCreatedTime + instanceDescription: + type: string + x-go-name: InstanceDescription + instanceId: + type: string + x-go-name: InstanceID + instanceName: + description: 实例信息 + type: string + x-go-name: InstanceName + instanceReason: + description: 实例失败原因 + type: string + x-go-name: InstanceReason + instanceStatus: + type: string + x-go-name: InstanceStatus + instanceStatusName: + type: string + x-go-name: InstanceStatusName + interfaceMode: + type: string + x-go-name: InterfaceMode + interfaceModeName: + type: string + x-go-name: InterfaceModeName + locked: + description: 实例是否锁定 锁定locked 未锁定unlocked + type: string + x-go-name: Locked + lockedname: + type: string + x-go-name: LockedName + mac1: + type: string + x-go-name: Mac1 + mac2: + type: string + x-go-name: Mac2 + manageStatus: + type: string + x-go-name: ManageStatus + manageStatusName: + type: string + x-go-name: ManageStatusName + mask: + type: string + x-go-name: Mask + memAmount: + format: int64 + type: integer + x-go-name: MemAmount + memFrequency: + format: int64 + type: integer + x-go-name: MemFrequency + memInfo: + type: string + x-go-name: MemInfo + memSize: + format: int64 + type: integer + x-go-name: MemSize + memType: + type: string + x-go-name: MemType + model: + type: string + x-go-name: Model + nicAmount: + format: int64 + type: integer + x-go-name: NicAmount + nicInfo: + type: string + x-go-name: NicInfo + nicRate: + format: int64 + type: integer + x-go-name: NicRate + privateEth1Ipv4: + type: string + x-go-name: PrivateEth1IPV4 + privateEth1Ipv6: + type: string + x-go-name: PrivateEth1IPV6 + privateIpv4: + type: string + x-go-name: PrivateIPv4 + privateIpv6: + type: string + x-go-name: PrivateIPv6 + raidDriver: + type: string + x-go-name: RaidDriver + reason: + type: string + x-go-name: Reason + slot1: + format: int64 + type: integer + x-go-name: Slot1 + slot2: + format: int64 + type: integer + x-go-name: Slot2 + sn: + type: string + x-go-name: Sn + svInfo: + type: string + x-go-name: SvInfo + switchIp: + type: string + x-go-name: SwitchIP + switchIp1: + type: string + x-go-name: SwitchIP1 + switchIp2: + type: string + x-go-name: SwitchIP2 + switchPassword1: + type: string + x-go-name: SwitchPassword1 + switchPassword2: + type: string + x-go-name: SwitchPassword2 + switchPort1: + type: string + x-go-name: SwitchPort1 + switchPort2: + type: string + x-go-name: SwitchPort2 + switchUser1: + type: string + x-go-name: SwitchUser1 + switchUser2: + type: string + x-go-name: SwitchUser2 + systemVolumeAmount: + description: SystemVolumeUnit string `json:"systemVolumeUnit"` // 系统盘单位(GB,TB) + format: int64 + type: integer + x-go-name: SystemVolumeAmount + systemVolumeInterfaceType: + type: string + x-go-name: SystemVolumeInterfaceType + systemVolumeSize: + format: int64 + type: integer + x-go-name: SystemVolumeSize + systemVolumeType: + type: string + x-go-name: SystemVolumeType + uPosition: + type: string + x-go-name: UPosition + updatedBy: + type: string + x-go-name: UpdatedBy + updatedTime: + type: string + x-go-name: UpdatedTime + userId: + type: string + x-go-name: UserID + userName: + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + DeviceIds: + properties: + deviceIds: + items: + type: string + type: array + x-go-name: DeviceIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + DevicePage: + properties: + devices: + items: + $ref: '#/definitions/Device' + type: array + x-go-name: Devices + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + DeviceType: + properties: + architecture: + type: string + x-go-name: Architecture + bootMode: + description: boot模式 + type: string + x-go-name: BootMode + cpuAmount: + format: int64 + type: integer + x-go-name: CPUAmount + cpuCores: + format: int64 + type: integer + x-go-name: CPUCores + cpuFrequency: + type: string + x-go-name: CPUFrequency + cpuInfo: + description: 额外拼接的字段,省去前端工作 + type: string + x-go-name: CpuInfo + cpuManufacturer: + type: string + x-go-name: CPUManufacturer + cpuModel: + type: string + x-go-name: CPUModel + cpuSpec: + type: string + x-go-name: CPUSpec + createdBy: + type: string + x-go-name: CreatedBy + createdTime: + type: string + x-go-name: CreatedTime + dataVolumeAmount: + format: int64 + type: integer + x-go-name: DataVolumeAmount + dataVolumeInterfaceType: + type: string + x-go-name: DataVolumeInterfaceType + dataVolumeSize: + format: double + type: number + x-go-name: DataVolumeSize + dataVolumeType: + type: string + x-go-name: DataVolumeType + dataVolumeUnit: + type: string + x-go-name: DataVolumeUnit + description: + type: string + x-go-name: Description + deviceCount: + format: int64 + type: integer + x-go-name: DeviceCount + deviceSeries: + type: string + x-go-name: DeviceSeries + deviceSeriesName: + type: string + x-go-name: DeviceSeriesName + deviceType: + type: string + x-go-name: DeviceType + deviceTypeId: + type: string + x-go-name: DeviceTypeID + dvInfo: + type: string + x-go-name: DvInfo + gpuAmount: + format: int64 + type: integer + x-go-name: GpuAmount + gpuInfo: + type: string + x-go-name: GpuInfo + gpuManufacturer: + type: string + x-go-name: GpuManufacturer + gpuModel: + type: string + x-go-name: GpuModel + height: + format: int64 + type: integer + x-go-name: Height + id: + format: int64 + type: integer + x-go-name: ID + idcId: + type: string + x-go-name: IDcID + idcName: + type: string + x-go-name: IdcName + idcNameEn: + type: string + x-go-name: IdcNameEn + imageCount: + type: string + x-go-name: ImageCount + instanceCount: + format: int64 + type: integer + x-go-name: InstanceCount + instanceStatus: + items: + type: string + type: array + x-go-name: InstanceStatus + interfaceMode: + type: string + x-go-name: InterfaceMode + interfaceModeName: + type: string + x-go-name: InterfaceModeName + memAmount: + format: int64 + type: integer + x-go-name: MemAmount + memFrequency: + format: int64 + type: integer + x-go-name: MemFrequency + memInfo: + type: string + x-go-name: MemInfo + memSize: + format: int64 + type: integer + x-go-name: MemSize + memSpec: + type: string + x-go-name: MemSpec + memType: + type: string + x-go-name: MemType + name: + type: string + x-go-name: Name + nic: + type: string + x-go-name: Nic + nicAmount: + format: int64 + type: integer + x-go-name: NicAmount + nicInfo: + type: string + x-go-name: NicInfo + nicRate: + format: int64 + type: integer + x-go-name: NicRate + raid: + description: |- + DeletedTime int `json:"deletedTime"` // 删除时间 + IsDel int8 `son:"isDel"` // 是否删除0未删除 1已删除 + type: string + x-go-name: Raid + raidCan: + description: 是否做raid,[RAID/NO RAID] + type: string + x-go-name: RaidCan + svInfo: + type: string + x-go-name: SvInfo + systemVolumeAmount: + format: int64 + type: integer + x-go-name: SystemVolumeAmount + systemVolumeInterfaceType: + type: string + x-go-name: SystemVolumeInterfaceType + systemVolumeSize: + format: double + type: number + x-go-name: SystemVolumeSize + systemVolumeType: + type: string + x-go-name: SystemVolumeType + systemVolumeUnit: + type: string + x-go-name: SystemVolumeUnit + updatedBy: + type: string + x-go-name: UpdatedBy + updatedTime: + type: string + x-go-name: UpdatedTime + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + DeviceTypeImage: + properties: + architecture: + description: 架构:x86/x64/i386/ + type: string + x-go-name: Architecture + createdBy: + description: 创建者 + type: string + x-go-name: CreatedBy + createdTime: + description: 创建时间 + type: string + x-go-name: CreatedTime + dataPartition: + description: 数据分区信息 + type: string + x-go-name: DataPartition + description: + description: 描述 + type: string + x-go-name: Description + deviceTypeNum: + description: 绑定了机型数量 + format: int64 + type: integer + x-go-name: DeviceTypeNum + filename: + description: 镜像文件名称 + type: string + x-go-name: Filename + format: + description: 镜像格式(qcow2、tar) + type: string + x-go-name: Format + hash: + description: 镜像校验码 + type: string + x-go-name: Hash + id: + format: uint64 + type: integer + x-go-name: ID + imageId: + description: 镜像uuid + type: string + x-go-name: ImageID + imageName: + description: 镜像名称 + type: string + x-go-name: ImageName + isBind: + description: 是否绑定了某个机型 + type: boolean + x-go-name: IsBind + osId: + description: 源os uuid + type: string + x-go-name: OsID + osName: + description: CentOS 7.2 64-bit + type: string + x-go-name: OsName + osType: + description: 操作系统分类:linux/windows + type: string + x-go-name: OsType + osVersion: + description: 操作系统版本 + type: string + x-go-name: OsVersion + source: + description: 镜像来源(common通用、customize定制、user_defined自定义) + type: string + x-go-name: Source + sourceName: + description: 镜像来源(common通用、customize定制、user_defined自定义) + type: string + x-go-name: SourceName + systemPartition: + description: 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + type: string + x-go-name: SystemPartition + updatedBy: + description: 更新者 + type: string + x-go-name: UpdatedBy + updatedTime: + description: 更新时间 + type: string + x-go-name: UpdatedTime + url: + description: 镜像源路径 + type: string + x-go-name: URL + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + DeviceTypeImageList: + properties: + deviceTypes: + items: + $ref: '#/definitions/DeviceTypeImage' + type: array + x-go-name: DeviceTypeImages + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + DeviceTypePage: + properties: + deviceTypes: + items: + $ref: '#/definitions/DeviceType' + type: array + x-go-name: DeviceTypes + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + DisassociateDeviceTypeImageRequest: + properties: + deviceTypeId: + type: string + x-go-name: DeviceTypeID + imageId: + type: string + x-go-name: ImageId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + ErrorResponse: + properties: + code: + format: int64 + type: integer + x-go-name: Code + message: + type: string + x-go-name: Message + status: + type: string + x-go-name: Status + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/controllers + File: + allOf: + - properties: + Close: + type: string + type: object + - type: object + - type: object + - type: object + - properties: + Close: + type: string + type: object + - type: object + - type: object + - type: object + description: |- + Its contents may be either stored in memory or on disk. + If stored on disk, the File's underlying concrete type will be an *os.File. + title: File is an interface to access the file part of a multipart message. + type: object + x-go-package: mime/multipart + GetMessageByIdRequest: + properties: + messageId: + type: string + x-go-name: MessageId + required: + - messageId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + HasUnreadMessage: + properties: + hasUnread: + type: boolean + x-go-name: HasUnread + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + Idc: + properties: + address: + description: address + type: string + x-go-name: Address + createTime: + description: create time + type: string + x-go-name: CreateTime + createdBy: + description: created by + type: string + x-go-name: CreatedBy + id: + description: ID + format: int64 + type: integer + x-go-name: ID + idcId: + description: i dc ID + type: string + x-go-name: IDcID + iloPassword: + description: ilo password + type: string + x-go-name: IloPassword + iloUser: + description: ilo user + type: string + x-go-name: IloUser + level: + description: level + type: string + x-go-name: Level + name: + description: name + type: string + x-go-name: Name + nameEn: + description: name en + type: string + x-go-name: NameEn + shortname: + description: shortname + type: string + x-go-name: Shortname + switchPassword1: + description: switch password1 + type: string + x-go-name: SwitchPassword1 + switchPassword2: + description: switch password2 + type: string + x-go-name: SwitchPassword2 + switchUser1: + description: switch user1 + type: string + x-go-name: SwitchUser1 + switchUser2: + description: switch user2 + type: string + x-go-name: SwitchUser2 + updateTime: + description: update time + type: string + x-go-name: UpdateTime + updatedBy: + description: updated by + type: string + x-go-name: UpdatedBy + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + IdcPage: + properties: + idcs: + items: + $ref: '#/definitions/Idc' + type: array + x-go-name: Idcs + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + Image: + properties: + architecture: + description: |- + DeletedTime int `json:"deletedTime"` // 删除时间戳 + IsDel int8 `json:"isDel"` // 是否删除0未删除 1已删除 + Platform string `json:"platform"` // suse/centos/ubuntu + type: string + x-go-name: Architecture + bootMode: + description: boot模式 + type: string + x-go-name: BootMode + createdBy: + type: string + x-go-name: CreatedBy + createdTime: + type: string + x-go-name: CreatedTime + dataPartition: + type: string + x-go-name: DataPartition + description: + type: string + x-go-name: Description + deviceTypeNum: + format: int64 + type: integer + x-go-name: DeviceTypeNum + filename: + type: string + x-go-name: Filename + format: + type: string + x-go-name: Format + hash: + type: string + x-go-name: Hash + imageId: + type: string + x-go-name: ImageID + imageName: + type: string + x-go-name: ImageName + isBind: + type: boolean + x-go-name: IsBind + osId: + type: string + x-go-name: OsID + osType: + type: string + x-go-name: OsType + osVersion: + type: string + x-go-name: OsVersion + source: + type: string + x-go-name: Source + sourceName: + type: string + x-go-name: SourceName + systemPartition: + type: string + x-go-name: SystemPartition + updatedBy: + type: string + x-go-name: UpdatedBy + updatedTime: + type: string + x-go-name: UpdatedTime + url: + type: string + x-go-name: URL + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + ImageId: + properties: + imageId: + type: string + x-go-name: ImageId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + ImageList: + properties: + images: + items: + $ref: '#/definitions/Image' + type: array + x-go-name: Images + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + ImageUpload: + properties: + fileName: + type: string + x-go-name: FileName + format: + type: string + x-go-name: Format + hash: + type: string + x-go-name: Hash + url: + type: string + x-go-name: Url + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + LoginRequest: + properties: + password: + type: string + x-go-name: Password + username: + type: string + x-go-name: Username + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + MessageList: + properties: + apikeys: + items: + $ref: '#/definitions/WebMessage' + type: array + x-go-name: Messages + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + MessageStatistic: + properties: + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + unreadCount: + format: int64 + type: integer + x-go-name: UnreadCount + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + MessageWithNextPrev: + properties: + apikeys: + $ref: '#/definitions/WebMessage' + nextMessageId: + type: string + x-go-name: NextMessageId + prevMessageId: + type: string + x-go-name: PrevMessageId + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + ModifyDeviceTypeRequest: + description: 【机型管理】【编辑机型】 + properties: + architecture: + type: string + x-go-name: Architecture + bootMode: + description: boot模式[UEFI Legacy/BIOS]支持多选,逗号分隔 + type: string + x-go-name: BootMode + cpuAmount: + format: int64 + type: integer + x-go-name: CPUAmount + cpuCores: + format: int64 + type: integer + x-go-name: CPUCores + cpuFrequency: + type: string + x-go-name: CPUFrequency + cpuManufacturer: + type: string + x-go-name: CPUManufacturer + cpuModel: + type: string + x-go-name: CPUModel + cpuSpec: + description: CPU 预置规格 + type: string + x-go-name: CpuSpec + createdBy: + type: string + x-go-name: CreatedBy + createdTime: + format: int64 + type: integer + x-go-name: CreatedTime + dataVolumeAmount: + format: int64 + type: integer + x-go-name: DataVolumeAmount + dataVolumeInterfaceType: + type: string + x-go-name: DataVolumeInterfaceType + dataVolumeSize: + format: double + type: number + x-go-name: DataVolumeSize + dataVolumeType: + type: string + x-go-name: DataVolumeType + dataVolumeUnit: + type: string + x-go-name: DataVolumeUnit + description: + type: string + x-go-name: Description + deviceSeries: + type: string + x-go-name: DeviceSeries + deviceType: + type: string + x-go-name: DeviceType + deviceTypeId: + type: string + x-go-name: DeviceTypeID + gpuAmount: + format: int64 + type: integer + x-go-name: GpuAmount + gpuManufacturer: + type: string + x-go-name: GpuManufacturer + gpuModel: + type: string + x-go-name: GpuModel + height: + format: int64 + type: integer + x-go-name: Height + idcId: + description: ID int `gorm:"primaryKey;column:id" json:"-"` // 主键 + type: string + x-go-name: IDcID + interfaceMode: + type: string + x-go-name: InterfaceMode + memAmount: + format: int64 + type: integer + x-go-name: MemAmount + memFrequency: + format: int64 + type: integer + x-go-name: MemFrequency + memSize: + format: int64 + type: integer + x-go-name: MemSize + memSpec: + description: 内存 预置规格 + type: string + x-go-name: MemSpec + memType: + type: string + x-go-name: MemType + name: + type: string + x-go-name: Name + nicAmount: + format: int64 + type: integer + x-go-name: NicAmount + nicRate: + format: int64 + type: integer + x-go-name: NicRate + raidCan: + description: 是否做raid,[RAID/NO RAID] + type: string + x-go-name: RaidCan + raidId: + type: string + x-go-name: RaidID + systemVolumeAmount: + format: int64 + type: integer + x-go-name: SystemVolumeAmount + systemVolumeInterfaceType: + type: string + x-go-name: SystemVolumeInterfaceType + systemVolumeSize: + format: double + type: number + x-go-name: SystemVolumeSize + systemVolumeType: + type: string + x-go-name: SystemVolumeType + systemVolumeUnit: + type: string + x-go-name: SystemVolumeUnit + updatedBy: + type: string + x-go-name: UpdatedBy + updatedTime: + format: int64 + type: integer + x-go-name: UpdatedTime + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + ModifyIdcRequest: + description: 【机房管理】【编辑机房】 + properties: + address: + description: address + type: string + x-go-name: Address + idcId: + description: ID int `gorm:"primaryKey;column:id" json:"-"` // 主键 + type: string + x-go-name: IdcID + iloPassword: + description: ilo password + type: string + x-go-name: IloPassword + iloUser: + description: ilo user + type: string + x-go-name: IloUser + level: + description: level + type: string + x-go-name: Level + name: + description: name + type: string + x-go-name: Name + nameEn: + description: name en + type: string + x-go-name: NameEn + shortname: + description: shortname + type: string + x-go-name: Shortname + switchPassword1: + description: switch password1 + type: string + x-go-name: SwitchPassword1 + switchPassword2: + description: switch password2 + type: string + x-go-name: SwitchPassword2 + switchUser1: + description: switch user1 + type: string + x-go-name: SwitchUser1 + switchUser2: + description: switch user2 + type: string + x-go-name: SwitchUser2 + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + ModifyUserInfoRequest: + description: 【用户管理】【编辑用户信息】 + properties: + defaultProjectId: + type: string + x-go-name: DefaultProjectID + description: + type: string + x-go-name: Description + email: + type: string + x-go-name: Email + language: + type: string + x-go-name: Language + password: + description: Timezone time.Time `gorm:"column:timezone" json:"timezone"` // UTC或者本时区时间 + type: string + x-go-name: Password + phoneNumber: + type: string + x-go-name: PhoneNumber + phonePrefix: + type: string + x-go-name: PhonePrefix + roleId: + description: UserID string `json:"userId"` + type: string + x-go-name: RoleID + userName: + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + Os: + properties: + architecture: + type: string + x-go-name: Architecture + bits: + format: int64 + type: integer + x-go-name: Bits + createdBy: + type: string + x-go-name: CreatedBy + createdTime: + type: string + x-go-name: CreatedTime + deletedTime: + type: string + x-go-name: DeletedTime + id: + format: uint64 + type: integer + x-go-name: ID + isDel: + format: int8 + type: integer + x-go-name: IsDel + osId: + type: string + x-go-name: OsID + osName: + type: string + x-go-name: OsName + osType: + type: string + x-go-name: OsType + osVersion: + type: string + x-go-name: OsVersion + sysUser: + type: string + x-go-name: SysUser + updatedBy: + type: string + x-go-name: UpdatedBy + updatedTime: + type: string + x-go-name: UpdatedTime + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + OsList: + properties: + oss: + items: + $ref: '#/definitions/Os' + type: array + x-go-name: Oss + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + PutawayDeviceRequest: + description: 【设备管理】【设备上架】支持多sn + properties: + deviceId: + type: string + x-go-name: DeviceID + sns: + type: string + x-go-name: Sns + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + Raid: + properties: + availableValue: + format: int64 + type: integer + x-go-name: AvailableValue + descriptionEn: + type: string + x-go-name: DescriptionEn + descriptionZh: + type: string + x-go-name: DescriptionZh + deviceTypeId: + type: string + x-go-name: DeviceTypeId + diskType: + type: string + x-go-name: DiskType + name: + type: string + x-go-name: Name + raidId: + type: string + x-go-name: RaidID + systemPartitionCount: + format: int64 + type: integer + x-go-name: SystemPartitionCount + volumeDetail: + type: string + x-go-name: VolumeDetail + volumeType: + type: string + x-go-name: VolumeType + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + RaidList: + properties: + raids: + items: + $ref: '#/definitions/Raid' + type: array + x-go-name: Raids + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + ReadMessagesRequest: + properties: + messageIds: + items: + type: string + type: array + x-go-name: MessageIds + required: + - messageIds + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + ResetInstancesPasswdRequest: + properties: + az: + type: string + x-go-name: Az + instanceIds: + items: + type: string + type: array + x-go-name: InstanceIds + password: + type: string + x-go-name: Password + pin: + type: string + x-go-name: Pin + region: + type: string + x-go-name: Region + tenant: + type: string + x-go-name: Tenant + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + ResetPasswdRequest: + properties: + az: + type: string + x-go-name: Az + instanceId: + type: string + x-go-name: InstanceId + password: + type: string + x-go-name: Password + pin: + type: string + x-go-name: Pin + region: + type: string + x-go-name: Region + tenant: + type: string + x-go-name: Tenant + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + SetCustomInfoRequest: + properties: + pageKey: + type: string + x-go-name: PageKey + pageValue: + additionalProperties: + additionalProperties: + type: boolean + type: object + type: object + x-go-name: PageValue + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + UnPutawayDeviceRequest: + description: 【设备管理】【设备下架】支持多sn + properties: + deviceId: + type: string + x-go-name: DeviceID + sns: + type: string + x-go-name: Sns + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + UploadDevice: + description: 上传设备返回 + properties: + SwitchUser2: + type: string + adapterId: + format: int64 + type: integer + x-go-name: AdapterID + brand: + type: string + x-go-name: Brand + cabinet: + type: string + x-go-name: Cabinet + enclosure1: + type: string + x-go-name: Enclosure1 + enclosure2: + type: string + x-go-name: Enclosure2 + gateway: + type: string + x-go-name: Gateway + iloIp: + type: string + x-go-name: IloIP + iloPassword: + type: string + x-go-name: IloPassword + iloUser: + type: string + x-go-name: IloUser + mac1: + type: string + x-go-name: Mac1 + mac2: + type: string + x-go-name: Mac2 + mask: + description: SwitchIP string `json:"switchIp"` // 网口交换机IP + type: string + x-go-name: Mask + maskEth1: + type: string + x-go-name: MaskEth1 + model: + type: string + x-go-name: Model + privateEth1Ipv4: + type: string + x-go-name: PrivateEth1IPv4 + privateEth1Ipv6: + type: string + x-go-name: PrivateEth1IPv6 + privateIpv4: + type: string + x-go-name: PrivateIPv4 + privateIpv6: + type: string + x-go-name: PrivateIPv6 + slot1: + format: int64 + type: integer + x-go-name: Slot1 + slot2: + format: int64 + type: integer + x-go-name: Slot2 + sn: + description: 额外拼接的字段,省去前端工作 + type: string + x-go-name: Sn + switchIp1: + type: string + x-go-name: SwitchIP1 + switchIp2: + type: string + x-go-name: SwitchIP2 + switchPassword1: + type: string + x-go-name: SwitchPassword1 + switchPassword2: + type: string + x-go-name: SwitchPassword2 + switchPort1: + type: string + x-go-name: SwitchPort1 + switchPort2: + type: string + x-go-name: SwitchPort2 + switchUser1: + type: string + x-go-name: SwitchUser1 + uPosition: + type: string + x-go-name: UPosition + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + UploadDeviceRequest: + properties: + deviceFile: + $ref: '#/definitions/File' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + UploadImageRequest: + properties: + imageFile: + $ref: '#/definitions/File' + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + User: + properties: + DefaultProjectName: + type: string + createdBy: + type: string + x-go-name: CreatedBy + createdTime: + type: string + x-go-name: CreatedTime + defaultProjectId: + type: string + x-go-name: DefaultProjectID + description: + type: string + x-go-name: Description + email: + type: string + x-go-name: Email + id: + format: int64 + type: integer + x-go-name: ID + instanceCount: + format: int64 + type: integer + x-go-name: InstanceCount + language: + type: string + x-go-name: Language + password: + type: string + x-go-name: Password + phoneNumber: + type: string + x-go-name: PhoneNumber + phonePrefix: + type: string + x-go-name: PhonePrefix + projectCount: + format: int64 + type: integer + x-go-name: ProjectCount + roleId: + type: string + x-go-name: RoleID + roleName: + type: string + x-go-name: RoleName + timezone: + format: date-time + type: string + x-go-name: Timezone + updatedBy: + type: string + x-go-name: UpdatedBy + updatedTime: + type: string + x-go-name: UpdatedTime + userId: + type: string + x-go-name: UserID + userName: + type: string + x-go-name: UserName + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + UserAdd: + properties: + userId: + type: string + x-go-name: UserID + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + UserPage: + properties: + pageNumber: + format: int64 + type: integer + x-go-name: PageNumber + pageSize: + format: int64 + type: integer + x-go-name: PageSize + totalCount: + format: int64 + type: integer + x-go-name: TotalCount + users: + items: + $ref: '#/definitions/User' + type: array + x-go-name: Users + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/response + VerifyUserRequest: + properties: + password: + type: string + x-go-name: Password + username: + type: string + x-go-name: Username + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-operation-api/types/request + WebMessage: + description: WebMessage WebMessage message + properties: + alert_count: + description: alert count + format: int64 + type: integer + x-go-name: AlertCount + alert_time: + description: alert time + format: int64 + type: integer + x-go-name: AlertTime + content: + description: content + type: string + x-go-name: Content + detail: + description: detail + type: string + x-go-name: Detail + fault_type: + description: 以下为带外故障消息专属字段 + type: string + x-go-name: FaultType + finish_time: + description: finish time + format: int64 + type: integer + x-go-name: FinishTime + has_read: + description: has read + format: int8 + type: integer + x-go-name: HasRead + instance_id: + description: instance ID + type: string + x-go-name: InstanceID + is_del: + description: is del + format: int8 + type: integer + x-go-name: IsDel + license_end_time: + description: liense end time + format: int64 + type: integer + x-go-name: LienseEndTime + license_name: + description: 以下为许可证到期消息专属字段 + type: string + x-go-name: LicenseName + license_number: + description: license number + type: string + x-go-name: LicenseNumber + license_start_time: + description: liense start time + format: int64 + type: integer + x-go-name: LienseStartTime + logid: + description: log ID + type: string + x-go-name: LogID + message_id: + description: message ID + type: string + x-go-name: MessageID + message_sub_type: + description: message sub type + type: string + x-go-name: MessageSubType + message_type: + description: message type + type: string + x-go-name: MessageType + resource_type: + description: resource type + type: string + x-go-name: ResourceType + result: + description: result + type: string + x-go-name: Result + sn: + description: s n + type: string + x-go-name: SN + user_id: + description: user ID + type: string + x-go-name: UserID + type: object + x-go-package: coding.jd.com/aidc-bmp/bmp-openapi-sdk/models +host: bmp-operation-api.local +info: + contact: + email: minping@jd.com + description: |- + the purpose of this application is to provide an application + that is using plain go code to define an API + + This should demonstrate all the possible comment annotations + that are available to turn go code into a fully compliant swagger 2.0 spec + license: + name: MIT + url: http://opensource.org/licenses/MIT + termsOfService: there are no TOS at this moment, use at your own risk we take no responsibility + title: bmp-operation-api + version: 0.0.1 +paths: + /apikey: + get: + description: GetApikeyList 获取apikey列表 + operationId: getApikeyList + responses: + "200": + $ref: '#/responses/getApikeyList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - keypair + put: + description: CreateAPIkey 创建apikey + operationId: createApikey + responses: + "200": + $ref: '#/responses/createApikey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - keypair + /apikey/{apikey_id}: + delete: + description: DeleteApikey 删除apikey + operationId: deleteApikey + responses: + "200": + $ref: '#/responses/deleteApikey' + default: + $ref: '#/responses/ErrorResponse' + tags: + - keypair + /custom/getCustomInfo: + get: + description: GetCustomInfo 获取自定义信息 + operationId: getCustomInfo + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: query + name: pageKey + type: string + x-go-name: PageKey + - in: query + name: reload + type: string + x-go-name: Reload + responses: + "200": + $ref: '#/responses/getCustomInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - custom + /custom/setCustomInfo: + post: + description: SetCustomInfo 设置自定义信息 + operationId: setCustomInfo + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/SetCustomInfoRequest' + responses: + "200": + $ref: '#/responses/setCustomInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - custom + /deviceType/getAvailableDeviceTypes: + get: + description: GetAvailableDeviceTypes 获取该机房内可用机型列表 + operationId: getAvailableDeviceTypes + responses: + "200": + $ref: '#/responses/getAvailableDeviceTypes' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes: + get: + description: QueryDeviceTypes【机型管理】【机型列表】 + operationId: queryDeviceTypes + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - in: query + name: deviceType + type: string + x-go-name: DeviceType + - in: query + name: idcId + type: string + x-go-name: IdcID + - in: query + name: name + type: string + x-go-name: Name + - in: query + name: deviceSeries + type: string + x-go-name: DeviceSeries + - in: query + name: isAll + type: string + x-go-name: IsAll + - description: 非空表示导出 + in: query + name: exportType + type: string + x-go-name: ExportType + responses: + "200": + $ref: '#/responses/queryDeviceTypes' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + put: + description: CreateDeviceType【机型管理】【添加机型】 + operationId: createDeviceType + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/CreateDeviceTypeRequest' + responses: + "200": + $ref: '#/responses/createDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/{device_type_id}: + delete: + description: DeleteDeviceType【机型管理】【删除机型】 + operationId: deleteDeviceType + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: device_type_id + required: true + type: string + x-go-name: DeviceTypeID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyDeviceTypeRequest' + responses: + "200": + $ref: '#/responses/deleteDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + put: + description: ModifyDeviceType【机型管理】【编辑机型】 + operationId: modifyDeviceType + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: device_type_id + required: true + type: string + x-go-name: DeviceTypeID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyDeviceTypeRequest' + responses: + "200": + $ref: '#/responses/modifyDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/associatedImage: + post: + description: AssociateDeviceTypeImage【机型管理】【机型详情信息】【关联镜像列表】【添加镜像】 + operationId: associateDeviceTypeImage + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/AssociateDeviceTypeImageRequest' + responses: + "200": + $ref: '#/responses/associateDeviceTypeImage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/deviceTypeImage: + get: + description: QueryDeviceTypeImages【机型管理】【机型详情信息】【关联镜像列表】此接口无分页参数 + operationId: queryDeviceTypeImages + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 机型id + in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - description: 镜像id + in: query + name: imageId + type: string + x-go-name: ImageID + - description: 体系架构 + in: query + name: architecture + type: string + x-go-name: Architecture + - description: 操作系统平台 + in: query + name: osType + type: string + x-go-name: OsType + - description: 镜像名称 + in: query + name: imageName + type: string + x-go-name: ImageName + - description: 版本号 + in: query + name: version + type: string + x-go-name: Version + - description: 操作系统ID + in: query + name: osId + type: string + x-go-name: OsID + - description: 镜像类型,预置,自定义 + in: query + name: source + type: string + x-go-name: Source + - description: 是否显示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/queryDeviceTypeImages' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/dissociatedDeviceType: + delete: + description: DissociatedDeviceType 镜像解绑机型 + operationId: dissociatedDeviceType + responses: + "200": + $ref: '#/responses/dissociatedDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/dissociatedImage: + post: + description: DisassociateDeviceTypeImage【机型管理】【机型详情信息】【关联镜像列表】【删除镜像】 + operationId: disassociateDeviceTypeImage + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/DisassociateDeviceTypeImageRequest' + responses: + "200": + $ref: '#/responses/disassociateDeviceTypeImage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /deviceTypes/queryDeviceType/{device_type_id}: + get: + description: QueryDeviceType【机型管理】【机型详情信息】 + operationId: queryDeviceType + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: device_type_id + required: true + type: string + x-go-name: DeviceTypeID + responses: + "200": + $ref: '#/responses/queryDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - deviceType + /devices: + post: + operationId: createDevices + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/CreateDeviceRequest' + responses: + "200": + $ref: '#/responses/createDevices' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/{device_id}: + delete: + description: DeleteDevice【设备管理】【删除设备】 + operationId: deleteDevice + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: device_id + required: true + type: string + x-go-name: DeviceID + responses: + "200": + $ref: '#/responses/deleteDevice' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + put: + description: Modify【设备管理】【设备修改】支持描述信息修改 + operationId: modify + responses: + "200": + $ref: '#/responses/modify' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/{device_id}/remove: + put: + description: RemoveDevice【设备管理】【移除设备】 + operationId: removeDevice + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: device_id + required: true + type: string + x-go-name: DeviceID + responses: + "200": + $ref: '#/responses/removeDevice' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/putaway: + put: + description: Putaway【设备管理】【设备上架】支持多sn,英文逗号分隔 + operationId: putaway + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/PutawayDeviceRequest' + responses: + "200": + $ref: '#/responses/putaway' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/queryDevice/{device_id}: + get: + description: GetDevice【设备管理】【设备详情】 + operationId: getDevice + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: device_id + required: true + type: string + x-go-name: DeviceID + responses: + "200": + $ref: '#/responses/getDevice' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/queryDevices: + get: + description: QueryDevices【设备管理】【设备列表】 + operationId: queryDevices + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - in: query + name: sn + type: string + x-go-name: Sn + - in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - in: query + name: deviceSeries + type: string + x-go-name: DeviceSeries + - in: query + name: manageStatus + type: string + x-go-name: ManageStatus + - in: query + name: iloIp + type: string + x-go-name: IloIP + - in: query + name: instanceId + type: string + x-go-name: InstanceID + - in: query + name: instanceName + type: string + x-go-name: InstanceName + - in: query + name: userId + type: string + x-go-name: UserID + - in: query + name: userName + type: string + x-go-name: UserName + - in: query + name: show + type: string + x-go-name: Show + - in: query + name: isAll + type: string + x-go-name: IsAll + - description: ExportType 非空表示要导出 + in: query + name: exportType + type: string + x-go-name: ExportType + responses: + "200": + $ref: '#/responses/queryDevices' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /devices/unPutaway: + put: + description: UnPutaway【设备管理】【设备下架】支持多sn,英文逗号分隔 + operationId: unPutaway + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/UnPutawayDeviceRequest' + responses: + "200": + $ref: '#/responses/unPutaway' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /filterList: + get: + description: FilterList 设置自定义信息 + operationId: filterList + responses: + "200": + $ref: '#/responses/filterList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - custom + /idc: + get: + description: GetIdcList【机房管理】【机房列表】 + operationId: getIdcList + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - in: query + name: name + type: string + x-go-name: Name + - in: query + name: level + type: string + x-go-name: Level + - in: query + name: isAll + type: string + x-go-name: IsAll + - in: query + name: show + type: string + x-go-name: Show + - description: 非空表示导出 + in: query + name: exportType + type: string + x-go-name: ExportType + responses: + "200": + $ref: '#/responses/getIdcList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - idc + put: + description: CreateIdc【机房管理】【添加机房】 + operationId: createIdc + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/CreateIdcRequest' + responses: + "200": + $ref: '#/responses/createIdc' + default: + $ref: '#/responses/ErrorResponse' + tags: + - idc + /idc/{idc_id}: + delete: + description: DeleteIdc【机房管理】【删除机房】 + operationId: deleteIdc + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: idc_id + required: true + type: string + x-go-name: IdcID + responses: + "200": + $ref: '#/responses/deleteIdc' + default: + $ref: '#/responses/ErrorResponse' + tags: + - idc + get: + description: GetIdcInfo【机房管理】【机房详情】 + operationId: getIdcInfo + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: idc_id + required: true + type: string + x-go-name: IdcID + responses: + "200": + $ref: '#/responses/getIdcInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - idc + post: + description: ModifyIdcInfo【机房管理】【编辑机房】 + operationId: modifyIdcInfo + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: idc_id + required: true + type: string + x-go-name: IdcID + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyIdcRequest' + responses: + "200": + $ref: '#/responses/modifyIdcInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - idc + /idc/user/validate: + post: + description: VerifyUser【机房管理】【验证用户名密码】 + operationId: verifyUser + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/VerifyUserRequest' + responses: + "200": + $ref: '#/responses/verifyUser' + default: + $ref: '#/responses/ErrorResponse' + tags: + - idc + /image/queryImagesByDeviceType: + get: + description: QueryImagesByDeviceType 根据机型获取绑定的镜像列表 + operationId: queryImagesByDeviceType + responses: + "200": + $ref: '#/responses/queryImagesByDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + /images: + get: + operationId: describeImages + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: query + name: imageId + type: string + x-go-name: ImageID + - in: query + name: imageName + type: string + x-go-name: ImageName + - in: query + name: deviceTypeId + type: string + x-go-name: DeviceTypeID + - in: query + name: version + type: string + x-go-name: Version + - in: query + name: osId + type: string + x-go-name: OsID + - in: query + items: + type: string + name: imageIds + type: array + x-go-name: ImageIDs + - in: query + name: source + type: string + x-go-name: Source + - format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - in: query + name: isAll + type: string + x-go-name: IsAll + - in: query + name: exportType + type: string + x-go-name: ExportType + - in: query + name: architecture + type: string + x-go-name: Architecture + - in: query + name: osType + type: string + x-go-name: OsType + responses: + "200": + $ref: '#/responses/describeImages' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + post: + operationId: createImage + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/CreateImageRequest' + responses: + "200": + $ref: '#/responses/createImage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + /images/{image_id}: + delete: + operationId: deleteImage + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: image_id + required: true + type: string + x-go-name: ImageID + responses: + "200": + $ref: '#/responses/deleteImage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + get: + operationId: describeImage + responses: + "200": + $ref: '#/responses/describeImage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + put: + operationId: modifyImage + responses: + "200": + $ref: '#/responses/modifyImage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + /images/associatedDeviceType: + post: + description: AssociatedDeviceType 镜像绑定机型 + operationId: associatedDeviceType + responses: + "200": + $ref: '#/responses/associatedDeviceType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + /images/imageDeviceTypes: + delete: + operationId: describeImageDeviceTypes + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - description: 镜像ID + in: query + name: imageId + required: true + type: string + x-go-name: ImageID + - description: 体系架构 + in: query + name: architecture + type: string + x-go-name: Architecture + - format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 镜像是否绑定了机型,0查询该镜像没有绑定的机型列表 1查询该镜像已经绑定了的机型列表 + in: query + name: isBind + type: string + x-go-name: IsBind + - description: 是否显示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeImageDeviceTypes' + default: + $ref: '#/responses/ErrorResponse' + tags: + - image + /instance/resetPasswd: + post: + description: resetPasswd 重置密码 + operationId: resetPasswd + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/ResetPasswdRequest' + responses: + "200": + $ref: '#/responses/resetPasswd' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instances/{instance_id}: + delete: + description: DeleteInstance【设备管理】【回收实例】 + operationId: deleteInstance + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/deleteInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + get: + description: GetInstanceInfo 查看实例详情 + operationId: getInstanceInfo + responses: + "200": + $ref: '#/responses/getInstanceInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instances/batchResetPasswd: + post: + description: resetInstancesPasswd 批量重置密码 + operationId: resetInstancesPasswd + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/ResetInstancesPasswdRequest' + responses: + "200": + $ref: '#/responses/resetInstancesPasswd' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instances/lock/{instance_id}: + post: + description: LockInstance 锁定实例 + operationId: lockInstance + responses: + "200": + $ref: '#/responses/lockInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instances/reinstallInstance: + post: + description: ReinstallInstance 重装实例 + operationId: reinstallInstance + responses: + "200": + $ref: '#/responses/reinstallInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instances/resetStatus/{instance_id}: + post: + description: ResetInstanceStatus【设备管理】【重置实例状态】 + operationId: resetInstanceStatus + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/resetInstanceStatus' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instances/restart/{instance_id}: + post: + description: RestartInstance【设备管理】【重启】 + operationId: restartInstance + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/restartInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instances/start/{instance_id}: + post: + description: StartInstance【设备管理】【开机】 + operationId: startInstance + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/startInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instances/stop/{instance_id}: + post: + description: StopInstance【设备管理】【关机】 + operationId: stopInstance + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: instance_id + required: true + type: string + x-go-name: InstanceID + responses: + "200": + $ref: '#/responses/stopInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /instances/unlock/{instance_id}: + post: + description: UnlockInstance 解锁实例 + operationId: unlockInstance + responses: + "200": + $ref: '#/responses/unlockInstance' + default: + $ref: '#/responses/ErrorResponse' + tags: + - instance + /keypair: + get: + description: GetKeypairList 获取keypair列表 + operationId: getKeypairList + responses: + "200": + $ref: '#/responses/getKeypairList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - keypair + /login: + post: + description: Login 登录 + operationId: login + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/LoginRequest' + responses: + "200": + $ref: '#/responses/login' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /logout: + post: + description: Logout 登出 + operationId: logout + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + responses: + "200": + $ref: '#/responses/logout' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /messages: + get: + description: GetMessageList 获取message列表(分页) + operationId: getMessageList + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - description: 是否显示全部,取值为1时表示全部 + in: query + name: isAll + type: string + x-go-name: IsAll + - description: 0:未读;1:已读;""不传表示全部 + in: query + name: hasRead + type: string + x-go-name: HasRead + - in: query + name: messageType + type: string + x-go-name: MessageType + - in: query + name: messageSubType + type: string + x-go-name: MessageSubType + responses: + "200": + $ref: '#/responses/getMessageList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/doRead: + put: + description: ReadMessage 将消息设置为已读(可多条) + operationId: readMessage + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/ReadMessagesRequest' + responses: + "200": + $ref: '#/responses/readMessage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/getMessageById: + get: + description: GetMessageById 获取消息详情,包括上一条/下一条的messageid + operationId: getMessageById + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/GetMessageByIdRequest' + responses: + "200": + $ref: '#/responses/getMessageById' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/getMessageTypes: + get: + description: GetMessageTypes 获取消息类型/子类型 + operationId: getMessageTypes + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + responses: + "200": + $ref: '#/responses/getMessageTypes' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/hasUnreadMessage: + get: + description: HasUnreadMessage 获取有没有未读消息 + operationId: hasUnreadMessage + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + responses: + "200": + $ref: '#/responses/hasUnreadMessage' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /messages/statistic: + get: + description: GetMessageStatistic 获取message总数和未读数 + operationId: getMessageStatistic + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + responses: + "200": + $ref: '#/responses/getMessageStatistic' + default: + $ref: '#/responses/ErrorResponse' + tags: + - message + /oss: + get: + operationId: describeOSs + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: query + name: osName + type: string + x-go-name: OsName + - in: query + name: architecture + type: string + x-go-name: Architecture + - in: query + name: osType + type: string + x-go-name: OsType + - in: query + name: platform + type: string + x-go-name: Platform + - in: query + name: osVersion + type: string + x-go-name: OsVersion + - in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/describeOSs' + default: + $ref: '#/responses/ErrorResponse' + tags: + - os + /partition/queryDefaultSystemPartitions: + get: + description: QueryDefaultSystemPartitions 根据机型和镜像查系统盘默认分区列表 + operationId: queryDefaultSystemPartitions + responses: + "200": + $ref: '#/responses/queryDefaultSystemPartitions' + default: + $ref: '#/responses/ErrorResponse' + tags: + - keypair + /raid/queryRaidsByDeviceTypeIDAndVolumeType: + get: + description: QueryRaidsByDeviceTypeIDAndVolumeType 根据机型查询系统盘/数据盘可用raid列表 + operationId: queryRaidsByDeviceTypeIDAndVolumeType + responses: + "200": + $ref: '#/responses/queryRaidsByDeviceTypeIDAndVolumeType' + default: + $ref: '#/responses/ErrorResponse' + tags: + - raid + /raids: + get: + operationId: queryRaidsAll + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + responses: + "200": + $ref: '#/responses/queryRaidsAll' + default: + $ref: '#/responses/ErrorResponse' + tags: + - raid + /resources: + get: + description: DescribeResources 根据某个字段值精确查询对应的资源列表(如根据imageName查询镜像列表,根据idcName查询机房列表) + operationId: describeResources + responses: + "200": + $ref: '#/responses/describeResources' + default: + $ref: '#/responses/ErrorResponse' + tags: + - resource + /roles/roleInfo/current: + get: + description: CurrentRole 获取当前登录用户的角色 + operationId: currentRole + responses: + "200": + $ref: '#/responses/currentRole' + default: + $ref: '#/responses/ErrorResponse' + tags: + - role + /user/local: + get: + description: GetUserInfo 获取当前用户详情 + operationId: getLocalUserInfo + responses: + "200": + $ref: '#/responses/getLocalUserInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + put: + description: UpdateLocalUserInfo 修改个人信息(除密码) + operationId: updateLocalUserInfo + responses: + "200": + $ref: '#/responses/updateLocalUserInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /user/local/password: + put: + description: UpdatePassword 修改当前登录用户密码 + operationId: updateLocalPassword + responses: + "200": + $ref: '#/responses/updateLocalPassword' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /user/timezones: + get: + description: GetTimezoneList 获取时区列表 + operationId: getTimezoneList + responses: + "200": + $ref: '#/responses/getTimezoneList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /users: + get: + description: GetUserList 获取用户列表 + operationId: getUserList + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - format: int64 + in: query + name: pageNumber + type: integer + x-go-name: PageNumber + - format: int64 + in: query + name: pageSize + type: integer + x-go-name: PageSize + - in: query + name: roleId + type: string + x-go-name: RoleID + - in: query + name: defaultProjectId + type: string + x-go-name: ProjectID + - in: query + name: userName + type: string + x-go-name: UserName + - in: query + name: isAll + type: string + x-go-name: IsAll + responses: + "200": + $ref: '#/responses/getUserList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + put: + description: AddUser 【用户管理】【添加用户】 + operationId: addUser + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/AddUserRequest' + responses: + "200": + $ref: '#/responses/addUser' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /users/{user_id}: + delete: + description: DeleteUserInfo 【用户管理】【删除用户】 + operationId: deleteUserInfo + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: user_id + required: true + type: string + x-go-name: UserId + responses: + "200": + $ref: '#/responses/deleteUserInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + get: + description: GetUserInfo 【用户管理】【用户详情】 + operationId: getUserInfo + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: user_id + required: true + type: string + x-go-name: UserId + responses: + "200": + $ref: '#/responses/getUserInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + post: + description: ModifyUserInfo 【用户管理】【编辑用户信息】 + operationId: modifyUserInfo + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: path + name: user_id + required: true + type: string + x-go-name: UserId + - in: body + name: Body + schema: + $ref: '#/definitions/ModifyUserInfoRequest' + responses: + "200": + $ref: '#/responses/modifyUserInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user + /users/login/validate: + post: + description: VerifyLoginUser【验证用户名密码】 + operationId: verifyLoginUser + parameters: + - in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: header + name: cookie + type: string + x-go-name: Cookie + - in: body + name: Body + schema: + $ref: '#/definitions/LoginRequest' + responses: + "200": + $ref: '#/responses/verifyLoginUser' + default: + $ref: '#/responses/ErrorResponse' + tags: + - user +produces: + - application/json +responses: + ErrorResponse: + description: unit err response for non 200 + headers: + traceId: + description: 'in: header' + type: string + schema: + properties: + error: + $ref: '#/definitions/ErrorResponse' + requestId: + type: string + x-go-name: RequestId + type: object + addUser: + description: AddUserResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/UserAdd' + type: object + associateDeviceTypeImage: + description: AssociateDeviceTypeImageResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + createDeviceType: + description: CreateDeviceTypeResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CreateDeviceTypeResult' + type: object + createDevices: + description: "" + headers: + traceId: + description: 'in: header' + type: string + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/DeviceIds' + type: object + createIdc: + description: CreateIdcResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CreateIdcResult' + type: object + createImage: + description: CreateImageResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/ImageId' + type: object + deleteDevice: + description: DeleteDeviceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteDeviceType: + description: DeleteDeviceTypeResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteIdc: + description: DeleteIdcResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteImage: + description: DeleteImageResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteInstance: + description: DeleteInstanceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + deleteUserInfo: + description: DeleteUserInfoResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + describeImageDeviceTypes: + description: DescribeImageDeviceTypesResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/DeviceTypePage' + type: object + describeImages: + description: DescribeImagesResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/ImageList' + type: object + describeOSs: + description: DescribeOSsResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/OsList' + type: object + disassociateDeviceTypeImage: + description: DisassociateDeviceTypeImageResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + getCustomInfo: + description: GetCustomInfoResponse is an response struct + headers: + traceId: + description: 'in: header' + type: string + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + getDevice: + description: GetDeviceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/Device' + type: object + getIdcInfo: + description: GetIdcInfoResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/Idc' + type: object + getIdcList: + description: GetIdcListResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/IdcPage' + type: object + getMessageById: + description: "" + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/MessageWithNextPrev' + type: object + getMessageList: + description: "" + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/MessageList' + type: object + getMessageStatistic: + description: "" + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/MessageStatistic' + type: object + getMessageTypes: + description: "" + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + additionalProperties: + items: + type: string + type: array + type: object + x-go-name: Result + type: object + getUserInfo: + description: GetUserInfoResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/User' + type: object + getUserList: + description: GetUserListResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/UserPage' + type: object + hasUnreadMessage: + description: "" + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/HasUnreadMessage' + type: object + login: + description: LoginResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + logout: + description: LogoutResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyDeviceType: + description: ModifyDeviceTypeResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyIdcInfo: + description: ModifyIdcInfoResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + modifyUserInfo: + description: ModifyUserInfoResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + putaway: + description: PutawayResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + queryDeviceType: + description: QueryDeviceTypeResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/DeviceType' + type: object + queryDeviceTypeImages: + description: QueryDeviceTypeImagesResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/DeviceTypeImageList' + type: object + queryDeviceTypes: + description: QueryDeviceTypesResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/DeviceTypePage' + type: object + queryDevices: + description: QueryDevicesResponse is an response struct + headers: + traceId: + description: 'in: header' + type: string + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/DevicePage' + type: object + queryRaidsAll: + description: QueryRaidsAllResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/RaidList' + type: object + readMessage: + description: A ReadMessageResult is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + removeDevice: + description: RemoveDeviceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + resetInstanceStatus: + description: ResetInstanceStatus is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + resetInstancesPasswd: + description: ResetInstancesPasswdResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + resetPasswd: + description: ResetPasswdResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + restartInstance: + description: RestartInstanceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + setCustomInfo: + description: SetCustomInfoResponse is an response struct + headers: + traceId: + description: 'in: header' + type: string + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + startInstance: + description: StartInstanceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + stopInstance: + description: StopInstanceResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + unPutaway: + description: UnPutawayResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + uploadDevices: + description: "" + headers: + traceId: + description: 'in: header' + type: string + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/UploadDevice' + type: object + uploadImage: + description: "" + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/ImageUpload' + type: object + verifyLoginUser: + description: VerifyLoginUserResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object + verifyUser: + description: VerifyUserResponse is an response struct + schema: + properties: + requestId: + type: string + x-go-name: RequestId + result: + $ref: '#/definitions/CommonResponse' + type: object +schemes: + - http +swagger: "2.0" diff --git a/bmp-operation-api/swagger_gen.sh b/bmp-operation-api/swagger_gen.sh new file mode 100644 index 0000000..cbe08ed --- /dev/null +++ b/bmp-operation-api/swagger_gen.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +# install goswagger: https://goswagger.io/install.html#Installing%20from%20source + +swagger version +\rm ./swagger.yml | swagger generate spec -o ./swagger.yml +# swagger validate ./swagger.yml goswagger有缺陷,且报错无法提供有效信息,建议使用https://editor.swagger.io/来校验 +# validate 和 generate命令在0.25.0版本有panic,0.30.3版本已修复 +swagger validate swagger.yml diff --git a/bmp-operation-api/swaggermodels/CommonHeader.go b/bmp-operation-api/swaggermodels/CommonHeader.go new file mode 100644 index 0000000..248f255 --- /dev/null +++ b/bmp-operation-api/swaggermodels/CommonHeader.go @@ -0,0 +1,23 @@ +package swaggermodels + +type ReadHeader struct { + // required: true + // in: header + TraceID string `json:"traceId"` //同APIKey + // in: header + Cookie string `json:"cookie"` +} + +type WriteHeader struct { + // required: true + // in: header + TraceID string `json:"traceId"` + // in: header + Cookie string `json:"cookie"` +} + +// 返回body里面的公共字段 +type ResponseHeader struct { + // in: header + TraceID string `json:"traceId"` +} diff --git a/bmp-operation-api/swaggermodels/Custom.go b/bmp-operation-api/swaggermodels/Custom.go new file mode 100644 index 0000000..0c63be8 --- /dev/null +++ b/bmp-operation-api/swaggermodels/Custom.go @@ -0,0 +1,42 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" +) + +// swagger:parameters setCustomInfo +type SetCustomInfoRequest struct { + WriteHeader + // in:body + Body requestTypes.SetCustomInfoRequest +} + +// SetCustomInfoResponse is an response struct +// swagger:response setCustomInfo +type SetCustomInfoResponse struct { + ResponseHeader + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters getCustomInfo +type GetCustomInfoRequest struct { + ReadHeader + // in: query + requestTypes.QueryCustomInfoRequest +} + +// GetCustomInfoResponse is an response struct +// swagger:response getCustomInfo +type GetCustomInfoResponse struct { + ResponseHeader + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} diff --git a/bmp-operation-api/swaggermodels/Device.go b/bmp-operation-api/swaggermodels/Device.go new file mode 100644 index 0000000..e6c8ff7 --- /dev/null +++ b/bmp-operation-api/swaggermodels/Device.go @@ -0,0 +1,143 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" +) + +// swagger:parameters uploadDevices +type UploadDevicesRequest struct { + WriteHeader + // in: body + Body requestTypes.UploadDeviceRequest +} + +// swagger:response uploadDevices +type UploadDevicesResponse struct { + ResponseHeader + // in: body + Body struct { + Result responseTypes.UploadDevice `json:"result"` + CommonRespBody + } +} + +// swagger:parameters createDevices +type CreateDevicesRequest struct { + WriteHeader + // in: body + Body requestTypes.CreateDeviceRequest +} + +// swagger:response createDevices +type CreateDevicesResponse struct { + ResponseHeader + // in: body + Body struct { + Result responseTypes.DeviceIds `json:"result"` + CommonRespBody + } +} + +// swagger:parameters queryDevices +type QueryDevicesRequest struct { + ReadHeader + // in: query + requestTypes.QueryDeviceListRequest +} + +// QueryDevicesResponse is an response struct +// swagger:response queryDevices +type QueryDevicesResponse struct { + ResponseHeader + // in: body + Body struct { + Result responseTypes.DevicePage `json:"result"` + CommonRespBody + } +} + +// swagger:parameters getDevice +type GetDeviceRequest struct { + ReadHeader + // in: path + DeviceID string `json:"device_id"` +} + +// GetDeviceResponse is an response struct +// swagger:response getDevice +type GetDeviceResponse struct { + // in: body + Body struct { + Result responseTypes.Device `json:"result"` + CommonRespBody + } +} + +// swagger:parameters unPutaway +type UnPutawayRequest struct { + WriteHeader + // in:body + Body requestTypes.UnPutawayDeviceRequest +} + +// UnPutawayResponse is an response struct +// swagger:response unPutaway +type UnPutawayResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters putaway +type PutawayRequest struct { + WriteHeader + // in:body + Body requestTypes.PutawayDeviceRequest +} + +// PutawayResponse is an response struct +// swagger:response putaway +type PutawayResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters deleteDevice +type DeleteDeviceRequest struct { + WriteHeader + // in: path + DeviceID string `json:"device_id"` +} + +// DeleteDeviceResponse is an response struct +// swagger:response deleteDevice +type DeleteDeviceResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters removeDevice +type RemoveDeviceRequest struct { + WriteHeader + // in: path + DeviceID string `json:"device_id"` +} + +// RemoveDeviceResponse is an response struct +// swagger:response removeDevice +type RemoveDeviceResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} diff --git a/bmp-operation-api/swaggermodels/DeviceType.go b/bmp-operation-api/swaggermodels/DeviceType.go new file mode 100644 index 0000000..e130279 --- /dev/null +++ b/bmp-operation-api/swaggermodels/DeviceType.go @@ -0,0 +1,146 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" +) + +// swagger:parameters createDeviceType +type CreateDeviceTypeRequest struct { + WriteHeader + // in:body + Body requestTypes.CreateDeviceTypeRequest +} + +// CreateDeviceTypeResponse is an response struct +// swagger:response createDeviceType +type CreateDeviceTypeResponse struct { + // in: body + Body struct { + Result responseTypes.CreateDeviceTypeResult `json:"result"` + CommonRespBody + } +} + +// swagger:parameters queryDeviceTypes +type QueryDeviceTypesRequest struct { + WriteHeader + // in: query + requestTypes.QueryDeviceTypesRequest +} + +// QueryDeviceTypesResponse is an response struct +// swagger:response queryDeviceTypes +type QueryDeviceTypesResponse struct { + // in: body + Body struct { + Result responseTypes.DeviceTypePage `json:"result"` + CommonRespBody + } +} + +// swagger:parameters queryDeviceType +type QueryDeviceTypeRequest struct { + ReadHeader + // in: path + DeviceTypeID string `json:"device_type_id"` +} + +// QueryDeviceTypeResponse is an response struct +// swagger:response queryDeviceType +type QueryDeviceTypeResponse struct { + // in: body + Body struct { + Result responseTypes.DeviceType `json:"result"` + CommonRespBody + } +} + +// swagger:parameters queryDeviceTypeImages +type QueryDeviceTypeImagesRequest struct { + ReadHeader + // in: query + requestTypes.QueryDeviceTypeImagePageRequest +} + +// QueryDeviceTypeImagesResponse is an response struct +// swagger:response queryDeviceTypeImages +type QueryDeviceTypeImagesResponse struct { + // in: body + Body struct { + Result responseTypes.DeviceTypeImageList `json:"result"` + CommonRespBody + } +} + +// swagger:parameters associateDeviceTypeImage +type AssociateDeviceTypeImageRequest struct { + WriteHeader + // in: body + Body requestTypes.AssociateDeviceTypeImageRequest +} + +// AssociateDeviceTypeImageResponse is an response struct +// swagger:response associateDeviceTypeImage +type AssociateDeviceTypeImageResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters disassociateDeviceTypeImage +type DisassociateDeviceTypeImageRequest struct { + WriteHeader + // in: body + Body requestTypes.DisassociateDeviceTypeImageRequest +} + +// DisassociateDeviceTypeImageResponse is an response struct +// swagger:response disassociateDeviceTypeImage +type DisassociateDeviceTypeImageResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters modifyDeviceType +type ModifyDeviceTypeRequest struct { + WriteHeader + // in: path + DeviceTypeID string `json:"device_type_id"` + // in: body + Body requestTypes.ModifyDeviceTypeRequest +} + +// ModifyDeviceTypeResponse is an response struct +// swagger:response modifyDeviceType +type ModifyDeviceTypeResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters deleteDeviceType +type DeleteDeviceTypeRequest struct { + WriteHeader + // in: path + DeviceTypeID string `json:"device_type_id"` + // in: body + Body requestTypes.ModifyDeviceTypeRequest +} + +// DeleteDeviceTypeResponse is an response struct +// swagger:response deleteDeviceType +type DeleteDeviceTypeResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} diff --git a/bmp-operation-api/swaggermodels/GetMessageByIdRequest.go b/bmp-operation-api/swaggermodels/GetMessageByIdRequest.go new file mode 100644 index 0000000..fed0efa --- /dev/null +++ b/bmp-operation-api/swaggermodels/GetMessageByIdRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" +) + +// swagger:parameters getMessageById +type GetMessageByIdRequest struct { + ReadHeader + + // in: query + requestTypes.GetMessageByIdRequest +} diff --git a/bmp-operation-api/swaggermodels/GetMessageByIdResult.go b/bmp-operation-api/swaggermodels/GetMessageByIdResult.go new file mode 100644 index 0000000..45452d2 --- /dev/null +++ b/bmp-operation-api/swaggermodels/GetMessageByIdResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + +// swagger:response getMessageById +type GetMessageByIdResult struct { + // in: body + Body struct { + Result response.MessageWithNextPrev `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-operation-api/swaggermodels/GetMessageListRequest.go b/bmp-operation-api/swaggermodels/GetMessageListRequest.go new file mode 100644 index 0000000..51579d1 --- /dev/null +++ b/bmp-operation-api/swaggermodels/GetMessageListRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" +) + +// swagger:parameters getMessageList +type GetMessageListRequest struct { + ReadHeader + + // in: query + requestTypes.QueryMessagesRequest +} diff --git a/bmp-operation-api/swaggermodels/GetMessageListResult.go b/bmp-operation-api/swaggermodels/GetMessageListResult.go new file mode 100644 index 0000000..2208195 --- /dev/null +++ b/bmp-operation-api/swaggermodels/GetMessageListResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + +// swagger:response getMessageList +type GetMessageListResult struct { + // in: body + Body struct { + Result response.MessageList `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-operation-api/swaggermodels/GetMessageStatisticRequest.go b/bmp-operation-api/swaggermodels/GetMessageStatisticRequest.go new file mode 100644 index 0000000..9ae4eca --- /dev/null +++ b/bmp-operation-api/swaggermodels/GetMessageStatisticRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters getMessageStatistic +type GetMessageStatisticRequest struct { + ReadHeader +} diff --git a/bmp-operation-api/swaggermodels/GetMessageStatisticResult.go b/bmp-operation-api/swaggermodels/GetMessageStatisticResult.go new file mode 100644 index 0000000..27dbe53 --- /dev/null +++ b/bmp-operation-api/swaggermodels/GetMessageStatisticResult.go @@ -0,0 +1,12 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" + +// swagger:response getMessageStatistic +type GetMessageStatisticResult struct { + // in: body + Body struct { + Result response.MessageStatistic `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-operation-api/swaggermodels/GetMessageTypesRequest.go b/bmp-operation-api/swaggermodels/GetMessageTypesRequest.go new file mode 100644 index 0000000..2c22a6c --- /dev/null +++ b/bmp-operation-api/swaggermodels/GetMessageTypesRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters getMessageTypes +type GetMessageTypesRequest struct { + ReadHeader +} diff --git a/bmp-operation-api/swaggermodels/GetMessageTypesResult.go b/bmp-operation-api/swaggermodels/GetMessageTypesResult.go new file mode 100644 index 0000000..ea735c9 --- /dev/null +++ b/bmp-operation-api/swaggermodels/GetMessageTypesResult.go @@ -0,0 +1,10 @@ +package swaggermodels + +// swagger:response getMessageTypes +type GetMessageTypesResult struct { + // in: body + Body struct { + Result map[string][]string `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-operation-api/swaggermodels/HasUnreadMessageRequest.go b/bmp-operation-api/swaggermodels/HasUnreadMessageRequest.go new file mode 100644 index 0000000..2114316 --- /dev/null +++ b/bmp-operation-api/swaggermodels/HasUnreadMessageRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters hasUnreadMessage +type HasUnreadMessageRequest struct { + ReadHeader +} diff --git a/bmp-operation-api/swaggermodels/HasUnreadMessageResult.go b/bmp-operation-api/swaggermodels/HasUnreadMessageResult.go new file mode 100644 index 0000000..4de1b72 --- /dev/null +++ b/bmp-operation-api/swaggermodels/HasUnreadMessageResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" +) + +// swagger:response hasUnreadMessage +type HasUnreadMessageResult struct { + // in: body + Body struct { + Result response.HasUnreadMessage `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-operation-api/swaggermodels/Idc.go b/bmp-operation-api/swaggermodels/Idc.go new file mode 100644 index 0000000..c985ecb --- /dev/null +++ b/bmp-operation-api/swaggermodels/Idc.go @@ -0,0 +1,110 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" +) + +// swagger:parameters getIdcList +type GetIdcListRequest struct { + ReadHeader + // in: query + requestTypes.QueryIdcListRequest +} + +// GetIdcListResponse is an response struct +// swagger:response getIdcList +type GetIdcListResponse struct { + // in: body + Body struct { + Result responseTypes.IdcPage `json:"result"` + CommonRespBody + } +} + +// swagger:parameters getIdcInfo +type GetIdcInfoRequest struct { + ReadHeader + // in: path + IdcID string `json:"idc_id"` +} + +// GetIdcInfoResponse is an response struct +// swagger:response getIdcInfo +type GetIdcInfoResponse struct { + // in: body + Body struct { + Result responseTypes.Idc `json:"result"` + CommonRespBody + } +} + +// swagger:parameters deleteIdc +type DeleteIdcRequest struct { + WriteHeader + // in: path + IdcID string `json:"idc_id"` +} + +// DeleteIdcResponse is an response struct +// swagger:response deleteIdc +type DeleteIdcResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters createIdc +type CreateIdcRequest struct { + WriteHeader + // in: body + Body requestTypes.CreateIdcRequest +} + +// CreateIdcResponse is an response struct +// swagger:response createIdc +type CreateIdcResponse struct { + // in: body + Body struct { + Result responseTypes.CreateIdcResult `json:"result"` + CommonRespBody + } +} + +// swagger:parameters modifyIdcInfo +type ModifyIdcInfoRequest struct { + WriteHeader + // in: path + IdcID string `json:"idc_id"` + // in: body + Body requestTypes.ModifyIdcRequest +} + +// ModifyIdcInfoResponse is an response struct +// swagger:response modifyIdcInfo +type ModifyIdcInfoResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters verifyUser +type VerifyUserRequest struct { + WriteHeader + // in: body + Body requestTypes.VerifyUserRequest +} + +// VerifyUserResponse is an response struct +// swagger:response verifyUser +type VerifyUserResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} diff --git a/bmp-operation-api/swaggermodels/Image.go b/bmp-operation-api/swaggermodels/Image.go new file mode 100644 index 0000000..c15cbd6 --- /dev/null +++ b/bmp-operation-api/swaggermodels/Image.go @@ -0,0 +1,91 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" +) + +// swagger:parameters uploadImage +type UploadImageRequest struct { + WriteHeader + // in:body + Body requestTypes.UploadImageRequest +} + +// swagger:response uploadImage +type UploadImageResponse struct { + // in: body + Body struct { + Result responseTypes.ImageUpload `json:"result"` + CommonRespBody + } +} + +// swagger:parameters createImage +type CreateImageRequest struct { + WriteHeader + // in:body + Body requestTypes.CreateImageRequest +} + +// CreateImageResponse is an response struct +// swagger:response createImage +type CreateImageResponse struct { + // in: body + Body struct { + Result responseTypes.ImageId `json:"result"` + CommonRespBody + } +} + +// swagger:parameters describeImages +type DescribeImagesRequest struct { + ReadHeader + // in: query + requestTypes.QueryImagesRequest +} + +// DescribeImagesResponse is an response struct +// swagger:response describeImages +type DescribeImagesResponse struct { + // in: body + Body struct { + Result responseTypes.ImageList `json:"result"` + CommonRespBody + } +} + +// swagger:parameters deleteImage +type DeleteImageRequest struct { + WriteHeader + + // in: path + ImageID string `json:"image_id"` +} + +// DeleteImageResponse is an response struct +// swagger:response deleteImage +type DeleteImageResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters describeImageDeviceTypes +type DescribeImageDeviceTypesRequest struct { + ReadHeader + // in: query + requestTypes.QueryImageDeviceTypesRequest +} + +// DescribeImageDeviceTypesResponse is an response struct +// swagger:response describeImageDeviceTypes +type DescribeImageDeviceTypesResponse struct { + // in: body + Body struct { + Result responseTypes.DeviceTypePage `json:"result"` + CommonRespBody + } +} diff --git a/bmp-operation-api/swaggermodels/Instance.go b/bmp-operation-api/swaggermodels/Instance.go new file mode 100644 index 0000000..0f48f97 --- /dev/null +++ b/bmp-operation-api/swaggermodels/Instance.go @@ -0,0 +1,127 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" +) + +// swagger:parameters startInstance +type StartInstanceRequest struct { + WriteHeader + // in: path + InstanceID string `json:"instance_id"` +} + +// StartInstanceResponse is an response struct +// swagger:response startInstance +type StartInstanceResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters restartInstance +type RestartInstanceRequest struct { + WriteHeader + // in: path + InstanceID string `json:"instance_id"` +} + +// RestartInstanceResponse is an response struct +// swagger:response restartInstance +type RestartInstanceResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters stopInstance +type StopInstanceRequest struct { + WriteHeader + // in: path + InstanceID string `json:"instance_id"` +} + +// StopInstanceResponse is an response struct +// swagger:response stopInstance +type StopInstanceResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters resetInstanceStatus +type ResetInstanceStatusRequest struct { + WriteHeader + // in: path + InstanceID string `json:"instance_id"` +} + +// ResetInstanceStatus is an response struct +// swagger:response resetInstanceStatus +type ResetInstanceStatusResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters deleteInstance +type DeleteInstanceRequest struct { + WriteHeader + // in: path + InstanceID string `json:"instance_id"` +} + +// DeleteInstanceResponse is an response struct +// swagger:response deleteInstance +type DeleteInstanceResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters resetPasswd +type ResetPasswdRequest struct { + WriteHeader + + // in:body + Body requestTypes.ResetPasswdRequest +} + +// ResetPasswdResponse is an response struct +// swagger:response resetPasswd +type ResetPasswdResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} + +// swagger:parameters resetInstancesPasswd +type ResetInstancesPasswdRequest struct { + WriteHeader + + // in:body + Body requestTypes.ResetInstancesPasswdRequest +} + +// ResetInstancesPasswdResponse is an response struct +// swagger:response resetInstancesPasswd +type ResetInstancesPasswdResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-operation-api/swaggermodels/ReadMessageRequest.go b/bmp-operation-api/swaggermodels/ReadMessageRequest.go new file mode 100644 index 0000000..ee057cb --- /dev/null +++ b/bmp-operation-api/swaggermodels/ReadMessageRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" +) + +// swagger:parameters readMessage +type ReadMessageRequest struct { + WriteHeader + + // in: body + Body requestTypes.ReadMessagesRequest +} diff --git a/bmp-operation-api/swaggermodels/ReadMessageResult.go b/bmp-operation-api/swaggermodels/ReadMessageResult.go new file mode 100644 index 0000000..4bd4ad9 --- /dev/null +++ b/bmp-operation-api/swaggermodels/ReadMessageResult.go @@ -0,0 +1,15 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" +) + +// A ReadMessageResult is an response struct +// swagger:response readMessage +type ReadMessageResult struct { + // in: body + Body struct { + Result response.CommonResponse `json:"result"` + RequestId string `json:"requestId"` + } +} diff --git a/bmp-operation-api/swaggermodels/User.go b/bmp-operation-api/swaggermodels/User.go new file mode 100644 index 0000000..cdb11ae --- /dev/null +++ b/bmp-operation-api/swaggermodels/User.go @@ -0,0 +1,142 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" +) + +// swagger:parameters login +type LoginRequest struct { + WriteHeader + // in:body + Body requestTypes.LoginRequest +} + +// LoginResponse is an response struct +// swagger:response login +type LoginResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters logout +type LogoutRequest struct { + WriteHeader +} + +// LogoutResponse is an response struct +// swagger:response logout +type LogoutResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters getUserList +type GetUserListRequest struct { + ReadHeader + // in: query + requestTypes.QueryUsersRequest +} + +// GetUserListResponse is an response struct +// swagger:response getUserList +type GetUserListResponse struct { + // in: body + Body struct { + Result responseTypes.UserPage `json:"result"` + CommonRespBody + } +} + +// swagger:parameters addUser +type AddUserRequest struct { + WriteHeader + // in: body + Body requestTypes.AddUserRequest +} + +// AddUserResponse is an response struct +// swagger:response addUser +type AddUserResponse struct { + // in: body + Body struct { + Result responseTypes.UserAdd `json:"result"` + CommonRespBody + } +} + +// swagger:parameters getUserInfo +type GetUserInfoRequest struct { + WriteHeader + // in: path + UserId string `json:"user_id"` +} + +// GetUserInfoResponse is an response struct +// swagger:response getUserInfo +type GetUserInfoResponse struct { + // in: body + Body struct { + Result responseTypes.User `json:"result"` + CommonRespBody + } +} + +// swagger:parameters modifyUserInfo +type ModifyUserInfoRequest struct { + WriteHeader + // in: path + UserId string `json:"user_id"` + // in: body + Body requestTypes.ModifyUserInfoRequest +} + +// ModifyUserInfoResponse is an response struct +// swagger:response modifyUserInfo +type ModifyUserInfoResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters deleteUserInfo +type DeleteUserInfoRequest struct { + WriteHeader + // in: path + UserId string `json:"user_id"` +} + +// DeleteUserInfoResponse is an response struct +// swagger:response deleteUserInfo +type DeleteUserInfoResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} + +// swagger:parameters verifyLoginUser +type VerifyLoginUserRequest struct { + ReadHeader + // in:body + Body requestTypes.LoginRequest +} + +// VerifyLoginUserResponse is an response struct +// swagger:response verifyLoginUser +type VerifyLoginUserResponse struct { + // in: body + Body struct { + Result responseTypes.CommonResponse `json:"result"` + CommonRespBody + } +} diff --git a/bmp-operation-api/swaggermodels/common.go b/bmp-operation-api/swaggermodels/common.go new file mode 100644 index 0000000..e8f3ce1 --- /dev/null +++ b/bmp-operation-api/swaggermodels/common.go @@ -0,0 +1,18 @@ +package swaggermodels + +import "coding.jd.com/aidc-bmp/bmp-operation-api/controllers" + +// unit err response for non 200 +// swagger:response ErrorResponse +type ErrorResponse struct { + ResponseHeader + //In: body + Body struct { + Err controllers.ErrorResponse `json:"error"` + RequestId string `json:"requestId"` + } +} + +type CommonRespBody struct { + RequestId string `json:"requestId"` +} diff --git a/bmp-operation-api/swaggermodels/os.go b/bmp-operation-api/swaggermodels/os.go new file mode 100644 index 0000000..06cb6ae --- /dev/null +++ b/bmp-operation-api/swaggermodels/os.go @@ -0,0 +1,23 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/request" + responseTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" +) + +// swagger:parameters describeOSs +type DescribeOSsRequest struct { + ReadHeader + // in: query + requestTypes.QueryOssRequest +} + +// DescribeOSsResponse is an response struct +// swagger:response describeOSs +type DescribeOSsResponse struct { + // in: body + Body struct { + Result responseTypes.OsList `json:"result"` + CommonRespBody + } +} diff --git a/bmp-operation-api/swaggermodels/raid.go b/bmp-operation-api/swaggermodels/raid.go new file mode 100644 index 0000000..f7dccbe --- /dev/null +++ b/bmp-operation-api/swaggermodels/raid.go @@ -0,0 +1,20 @@ +package swaggermodels + +import ( + responseTypes "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" +) + +// swagger:parameters queryRaidsAll +type QueryRaidsAllRequest struct { + ReadHeader +} + +// QueryRaidsAllResponse is an response struct +// swagger:response queryRaidsAll +type QueryRaidsAllResponse struct { + // in: body + Body struct { + Result responseTypes.RaidList `json:"result"` + CommonRespBody + } +} diff --git a/bmp-operation-api/swaggermodels/swaggerinfo.go b/bmp-operation-api/swaggermodels/swaggerinfo.go new file mode 100644 index 0000000..70e2920 --- /dev/null +++ b/bmp-operation-api/swaggermodels/swaggerinfo.go @@ -0,0 +1,28 @@ +// Package classification bmp-operation-api +// +// the purpose of this application is to provide an application +// that is using plain go code to define an API +// +// This should demonstrate all the possible comment annotations +// that are available to turn go code into a fully compliant swagger 2.0 spec +// +// Terms Of Service: +// +// there are no TOS at this moment, use at your own risk we take no responsibility +// +// Schemes: http +// Host: bmp-operation-api.local +// BasePath: / +// Version: 0.0.1 +// License: MIT http://opensource.org/licenses/MIT +// Contact: minping@jd.com +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// +// swagger:meta +package swaggermodels diff --git a/bmp-operation-api/test_script/curl.sh b/bmp-operation-api/test_script/curl.sh new file mode 100644 index 0000000..e99fc1c --- /dev/null +++ b/bmp-operation-api/test_script/curl.sh @@ -0,0 +1,57 @@ +#!/bin/bash + +curl -X PUT -H 'Authorization: JDCLOUD2-HMAC-SHA256 Credential=DD1B0BFA7BAA5DAED057ACF4817AF55B/20220424/cn-north-1/cps/jdcloud2_request, SignedHeaders=content-type;host;x-jdcloud-date;x-jdcloud-language;x-jdcloud-nonce;x-jdcloud-order-key;x-jdcloud-pin;x-jdcloud-profile, Signature=7fabd922cd7ed21259dd5aaa6a9598b71b5f3c26981df2130d7a4692331e31d6' -H 'Content-Type: application/json' -H 'User-Agent: JdcloudSdkGo/1.1.6 cps/2.5.5' -H 'X-Jdcloud-Date: 20220424T061849Z' -H 'X-Jdcloud-Language: cn' -H 'X-Jdcloud-Nonce: 288135bc-ba8b-4fc4-899a-1468bdc23331' -H 'X-Jdcloud-Order-Key: ghpmaezb-pz10-vodh-8x1g-bzu854815zfk' -H 'X-Jdcloud-Pin: MWMxODczMWZhYjdmNDkwNzg4MjM=' -H 'X-Jdcloud-Request-Id: ghpmaezb-pz10-vodh-8x1g-111111111111' -d '{ + "clientToken": null, + "instanceSpec": { + "aliasIps": null, + "az": "cn-north-1a", + "bandwidth": null, + "bandwidthPackageId": null, + "charge": { + "autoRenew": false, + "buyScenario": null, + "chargeDuration": null, + "chargeMode": "postpaid_by_duration", + "chargeUnit": null + }, + "cidr": null, + "count": 1, + "dataDiskPartitions": null, + "dataRaidTypeId": "r-l6pounvfife0njlinhk6ztf2xyio", + "description": null, + "deviceType": "cps.s.normal", + "enableInternet": "no", + "enableIpv6": null, + "extensionAliasIps": null, + "extensionBandwidth": null, + "extensionBandwidthPackageId": null, + "extensionEnableInternet": null, + "extensionEnableIpv6": null, + "extensionInternetChargeMode": null, + "extensionIpv6Address": null, + "extensionIpv6AliasIps": null, + "extensionLineType": null, + "extensionPrivateIp": null, + "extensionSubnetId": null, + "hostname": null, + "imageType": "standard", + "interfaceMode": "bond", + "internetChargeMode": null, + "ipv6Address": null, + "ipv6AliasIps": null, + "keypairId": null, + "keypairIdSos": null, + "lineType": null, + "name": "cccc", + "networkType": "retail", + "osTypeId": "i-v2xudi13m1yrdg3aencxya21bcaa", + "password": "JDyun123", + "privateIp": null, + "resourceTags": null, + "subnetId": null, + "sysRaidTypeId": "r-wtzluqacgzzxgunnabdkpnpjew3d", + "systemDiskPartitions": null, + "userData": null + }, + "regionId": "cn-north-1" +}' 'http://10.226.148.63:8000/v1/regions/cn-north-1/instances' diff --git a/bmp-operation-api/test_script/curl_api.sh b/bmp-operation-api/test_script/curl_api.sh new file mode 100644 index 0000000..c1ea819 --- /dev/null +++ b/bmp-operation-api/test_script/curl_api.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +curl -X PUT -H 'X-Jdcloud-Pin: 1c18731fab7f49078823' -d '{"clientToken":null,"instanceSpec":{"aliasIps":null,"az":"cn-north-1a","bandwidth":null,"bandwidthPackageId":null,"charge":{"autoRenew":false,"buyScenario":null,"chargeDuration":null,"chargeMode":"postpaid_by_duration","chargeUnit":"month"},"cidr":null,"count":1,"dataDiskPartitions":null,"dataRaidTypeId":"r-l6pounvfife0njlinhk6ztf2xyio","description":null,"deviceType":"cps.s.normal","enableInternet":"no","enableIpv6":null,"extensionAliasIps":null,"extensionBandwidth":null,"extensionBandwidthPackageId":null,"extensionEnableInternet":null,"extensionEnableIpv6":null,"extensionInternetChargeMode":null,"extensionIpv6Address":null,"extensionIpv6AliasIps":null,"extensionLineType":null,"extensionPrivateIp":null,"extensionSubnetId":null,"hostname":null,"imageType":"standard","interfaceMode":"bond","internetChargeMode":null,"ipv6Address":null,"ipv6AliasIps":null,"keypairId":null,"keypairIdSos":null,"lineType":null,"name":"minping_test","networkType":"retail","osTypeId":"i-v2xudi13m1yrdg3aencxya21bcaa","password":"JDyun123","privateIp":null,"resourceTags":null,"subnetId":null,"sysRaidTypeId":"r-wtzluqacgzzxgunnabdkpnpjew3d","systemDiskPartitions":null,"userData":null},"regionId":"cn-north-1"}' 'http://127.0.0.1:8799/v1/regions/cn-north-1/instances' diff --git a/bmp-operation-api/types/request/ApikeyRequest.go b/bmp-operation-api/types/request/ApikeyRequest.go new file mode 100644 index 0000000..ba4eb9b --- /dev/null +++ b/bmp-operation-api/types/request/ApikeyRequest.go @@ -0,0 +1,5 @@ +package request + +type GetApikeyListRequest struct { + PagingRequest +} diff --git a/bmp-operation-api/types/request/AuditLogsRequest.go b/bmp-operation-api/types/request/AuditLogsRequest.go new file mode 100644 index 0000000..1b89115 --- /dev/null +++ b/bmp-operation-api/types/request/AuditLogsRequest.go @@ -0,0 +1,20 @@ +package request + +type DescribeAuditLogsRequest struct { + PagingRequest + // instance_id + Sn string `json:"sn" validate:"required"` + // 操作名称 + Operation string `json:"operation"` + // 操作人 + UserName string `json:"userName"` + // result + Result string `json:"result"` + // 操作时间下限 + StartTime int64 `json:"startTime"` + // 操作时间上限 + EndTime int64 `json:"endTime"` + // 是否显示所有 + IsAll string `json:"isAll"` + ExportType string `json:"exportType"` // v2.27.2 0:导出全部实力;1:导出选中实例;2:导出搜索结果 +} diff --git a/bmp-operation-api/types/request/BaseRequest.go b/bmp-operation-api/types/request/BaseRequest.go new file mode 100644 index 0000000..03089e2 --- /dev/null +++ b/bmp-operation-api/types/request/BaseRequest.go @@ -0,0 +1,30 @@ +package request + +import ( + "errors" + "fmt" + "git.jd.com/cps-golang/ironic-common/exception" + + "github.com/beego/beego/v2/core/validation" +) + +type IRequest interface { + Validate(request IRequest) error +} + +type BaseRequest struct{} + +func (r *BaseRequest) Validate(request IRequest) error { + valid := validation.Validation{} + ok, err := valid.Valid(request) + fmt.Println("校验结果", ok, err) + if err != nil { + panic(exception.Exception{Msg: err.Error()}) + return err + } + if !ok { + fmt.Println("返回的err是", errors.New(valid.Errors[0].Key+" "+valid.Errors[0].Error())) + panic(exception.Exception{Msg: errors.New(valid.Errors[0].Key + " " + valid.Errors[0].Error()).Error()}) + } + return nil +} diff --git a/bmp-operation-api/types/request/CustomInfoRequest.go b/bmp-operation-api/types/request/CustomInfoRequest.go new file mode 100644 index 0000000..652b22f --- /dev/null +++ b/bmp-operation-api/types/request/CustomInfoRequest.go @@ -0,0 +1,13 @@ +package request + +type QueryCustomInfoRequest struct { + PageKey string `json:"pageKey"` + Reload string `json:"reload"` +} +type SetCustomInfoRequest struct { + PageKey string `json:"pageKey"` + PageValue map[string]map[string]bool `json:"pageValue"` +} +type QueryPrivilegeNewRequest struct { + Pin string `json:"pin"` +} diff --git a/bmp-operation-api/types/request/DeviceRequest.go b/bmp-operation-api/types/request/DeviceRequest.go new file mode 100644 index 0000000..a6b2cce --- /dev/null +++ b/bmp-operation-api/types/request/DeviceRequest.go @@ -0,0 +1,119 @@ +package request + +import ( + "mime/multipart" + + "coding.jd.com/aidc-bmp/bmp-operation-api/types/response" +) + +type CreateDeviceRequest struct { + IdcId string `json:"idcId" validate:"required"` + // DeviceTypeId string `json:"deviceTypeId" validate:"required"` + Devices []*response.UploadDevice `json:"devices" validate:"required"` +} +type UploadDeviceRequest struct { + DeviceFile multipart.File `json:"deviceFile"` +} + +// 【设备管理】【设备列表】 +type QueryDeviceListRequest struct { + BaseRequest + PagingRequest + + Sn string `json:"sn"` + DeviceTypeID string `json:"deviceTypeId"` + DeviceSeries string `json:"deviceSeries"` + ManageStatus string `json:"manageStatus"` + IloIP string `json:"iloIp"` + InstanceID string `json:"instanceId"` + InstanceName string `json:"instanceName"` + UserID string `json:"userId"` + UserName string `json:"userName"` + Show string `json:"show"` + IsAll string `json:"isAll"` + // ExportType 非空表示要导出 + ExportType string `json:"exportType"` + // "1"表示采集成功,"2"表示未采集, "3"表示采集中,4表示采集失败,不传表示全部 + CollectStatus string `json:"collectStatus"` +} + +// 【设备管理】【设备详情】 +type QueryDeviceInfoRequest struct { + Show string `json:"show"` + DeviceID string `json:"deviceId"` +} + +// 【设备管理】【设备磁盘详情】 +type QueryDeviceDisksRequest struct { + DeviceID string `json:"deviceId"` +} + +// 【设备管理】【设备下架】支持多sn +type UnPutawayDeviceRequest struct { + Sns string `json:"sns"` + DeviceID string `json:"deviceId"` +} + +// 【设备管理】【设备上架】支持多sn +type PutawayDeviceRequest struct { + Sns string `json:"sns"` + DeviceID string `json:"deviceId"` +} + +// 【设备管理】【删除设备】 +type ModifyDeviceRequest struct { + Description *string `json:"description"` +} + +// 【设备管理】【删除设备】 +type DeleteDeviceRequest struct { + DeviceId string `json:"deviceId"` +} + +type CollectDevice struct { + // sn + // required: true + Sn string `json:"sn"` + // 可选参数。 传参:True, False 。True表示传入的raid_driver值将覆盖已适配机器的raid_driver + // Extensions: + // x-nullable: true + AllowOverride bool `json:"allowOverride"` +} + +type AssociateDeviceDisksRequest struct { + // device uuid + // required: true + DeviceID string `json:"deviceId" validate:"required"` // device uuid + // devicetype uuid + // required: true + DeviceTypeID string `json:"deviceTypeId" validate:"required"` // devicetype uuid + // volumeid和磁盘uuid列表 + // required: true + Volumes []*AssociateDeviceDiskSpec `json:"volumes" validate:"required"` +} + +type AssociateDeviceDiskSpec struct { + VolumeID string `json:"volumeId" validate:"required"` + DiskIDs []string `json:"diskId" validate:"required"` +} + +type GetAssociatedDisksRequest struct { + // device uuid + // required: true + DeviceID string `json:"deviceId" validate:"required"` // device uuid + // devicetype uuid + // required: true + DeviceTypeID string `json:"deviceTypeId" validate:"required"` // devicetype uuid + // volume uuid + // required: true + VolumeID string `json:"volumeId" validate:"required"` +} + +type DeviceAssociateDeviceTypeRequest struct { + // 设备类型id + // required: true + DeviceTypeID string `json:"deviceTypeId" validate:"required"` + // 设备ID + // required: true + DeviceID string `json:"deviceId" validate:"required"` +} diff --git a/bmp-operation-api/types/request/DeviceTypeImageRequest.go b/bmp-operation-api/types/request/DeviceTypeImageRequest.go new file mode 100644 index 0000000..163aca8 --- /dev/null +++ b/bmp-operation-api/types/request/DeviceTypeImageRequest.go @@ -0,0 +1,36 @@ +package request + +type QueryDeviceTypeImagePageRequest struct { + BaseRequest + PagingRequest + // 机型id + DeviceTypeID string `json:"deviceTypeId"` + // 镜像id + ImageID string `json:"imageId"` + // 体系架构 + Architecture string `json:"architecture"` + // 操作系统平台 + OsType string `json:"osType"` + // 镜像名称 + ImageName string `json:"imageName"` + // 版本号 + Version string `json:"version"` + // 操作系统ID + OsID string `json:"osId"` + // 镜像类型,预置,自定义 + Source string `json:"source"` + // 是否显示全部 + IsAll string `json:"isAll"` +} + +type AssociateDeviceTypeImageRequest struct { + BaseRequest + DeviceTypeID string `json:"deviceTypeId"` + ImageIds string `json:"imageIds"` // 逗号分隔 +} + +type DisassociateDeviceTypeImageRequest struct { + BaseRequest + DeviceTypeID string `json:"deviceTypeId"` + ImageId string `json:"imageId"` +} diff --git a/bmp-operation-api/types/request/DeviceTypeRequest.go b/bmp-operation-api/types/request/DeviceTypeRequest.go new file mode 100644 index 0000000..c008a85 --- /dev/null +++ b/bmp-operation-api/types/request/DeviceTypeRequest.go @@ -0,0 +1,143 @@ +package request + +import sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + +// 机型管理 模块请求字段 +type CreateDeviceTypeRequest struct { + //ID int `gorm:"primaryKey;column:id" json:"-"` // 主键 + IDcID string `json:"idcId"` + //DeviceTypeID string `json:"deviceTypeId"` // 设备类型uuid + Name string `json:"name"` // 机型名称,如计算效能型,标准计算型 + DeviceType string `json:"deviceType"` // 机型规格, cps.c.normal + DeviceSeries string `json:"deviceSeries"` // 机型类型,如计算型,存储型 + Architecture string `json:"architecture"` // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Height int `json:"height"` // 【高度(U)】:显示机型高度 + Description string `json:"description"` // 描述 + CPUAmount int64 `json:"cpuAmount"` // cpu数量 + CPUCores int64 `json:"cpuCores"` // 单个cpu内核数 + CPUManufacturer string `json:"cpuManufacturer"` // cpu厂商 + CPUModel string `json:"cpuModel"` // cpu处理器型号 + CPUFrequency string `json:"cpuFrequency"` // cpu频率(G) + MemType string `json:"memType"` // 内存接口(如DDR3,DDR4) + MemSize int `json:"memSize"` // 单个内存大小(GB) + MemAmount int `json:"memAmount"` // 内存数量 + MemFrequency int `json:"memFrequency"` // 内存主频(MHz) + NicAmount int64 `json:"nicAmount"` // 网卡数量 + NicRate int `json:"nicRate"` // 网卡传输速率(GE) + InterfaceMode string `json:"interfaceMode"` // 【网口模式】【网络设置】: bond单网口,dual双网口 + SystemVolumeType string `json:"systemVolumeType"` // 系统盘类型(SSD,HDD) + SystemVolumeInterfaceType string `json:"systemVolumeInterfaceType"` // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeSize float64 `json:"systemVolumeSize"` // 系统盘单盘大小 + SystemVolumeUnit string `json:"systemVolumeUnit"` // 系统盘单盘大小单位 + SystemVolumeAmount int64 `json:"systemVolumeAmount"` // 系统盘数量 + // 是否做raid,[RAID/NO RAID] + RaidCan string `json:"raidCan"` + GpuAmount int64 `json:"gpuAmount"` // gpu数量 + GpuManufacturer string `json:"gpuManufacturer"` // gpu厂商 + GpuModel string `json:"gpuModel"` // gpu处理器型号 + DataVolumeType string `json:"dataVolumeType"` // 数据盘类型(SSD,HDD) + DataVolumeInterfaceType string `json:"dataVolumeInterfaceType"` // 数据盘接口类型(SATA,SAS,NVME) + DataVolumeSize float64 `json:"dataVolumeSize"` // 数据盘单盘大小 + DataVolumeUnit string `json:"dataVolumeUnit"` + DataVolumeAmount int64 `json:"dataVolumeAmount"` // 数据盘数量 + CreatedBy string `json:"createdBy"` // 创建者 + UpdatedBy string `json:"updatedBy"` // 更新者 + CreatedTime int `json:"createdTime"` // 创建时间 + UpdatedTime int `json:"updatedTime"` // 更新时间 + RaidID string `json:"raidId"` //系统盘raid,支持多选 + // CPU 预置规格 + // required: true + CpuSpec string `json:"cpuSpec" validate:"required,oneof=common user_defined"` + // 内存 预置规格 + // required: true + MemSpec string `json:"memSpec" validate:"required,oneof=common user_defined"` + + //boot模式[UEFI Legacy/BIOS]支持多选,逗号分隔 + BootMode string `json:"bootMode" validate:"omitempty"` + + Volumes []*sdkModels.VolumeItem `json:"volumes"` + IsNeedRaid string `json:"isNeedRaid"` +} + +// 【机型管理】【编辑机型】 +type ModifyDeviceTypeRequest struct { + //ID int `gorm:"primaryKey;column:id" json:"-"` // 主键 + IDcID *string `json:"idcId"` + DeviceTypeID string `json:"deviceTypeId"` // 设备类型uuid + Name *string `json:"name"` // 机型名称,如计算效能型,标准计算型 + DeviceType *string `json:"deviceType"` // 机型规格, cps.c.normal + DeviceSeries *string `json:"deviceSeries"` // 机型类型,如计算型,存储型 + Architecture *string `json:"architecture"` // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Height *int64 `json:"height"` // 【高度(U)】:显示机型高度 + Description *string `json:"description"` // 描述 + CPUAmount *int64 `json:"cpuAmount"` // cpu数量 + CPUCores *int64 `json:"cpuCores"` // 单个cpu内核数 + + CPUManufacturer *string `json:"cpuManufacturer"` // cpu厂商 + CPUModel *string `json:"cpuModel"` // cpu处理器型号 + CPUFrequency *string `json:"cpuFrequency"` // cpu频率(G) + MemType *string `json:"memType"` // 内存接口(如DDR3,DDR4) + MemSize *int64 `json:"memSize"` // 单个内存大小(GB) + MemAmount *int64 `json:"memAmount"` // 内存数量 + MemFrequency *int64 `json:"memFrequency"` // 内存主频(MHz) + NicAmount *int64 `json:"nicAmount"` // 网卡数量 + NicRate *int64 `json:"nicRate"` // 网卡传输速率(GE) + InterfaceMode *string `json:"interfaceMode"` // 【网口模式】【网络设置】: bond单网口,dual双网口 + SystemVolumeType *string `json:"systemVolumeType"` // 系统盘类型(SSD,HDD) + SystemVolumeInterfaceType *string `json:"systemVolumeInterfaceType"` // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeSize *float64 `json:"systemVolumeSize"` // 系统盘单盘大小 + SystemVolumeUnit *string `json:"systemVolumeUnit"` // 系统盘单位(GB,TB) + SystemVolumeAmount *int64 `json:"systemVolumeAmount"` // 系统盘数量 + // 是否做raid,[RAID/NO RAID] + //RaidCan string `json:"raidCan"` + GpuAmount *int64 `json:"gpuAmount"` // gpu数量 + GpuManufacturer *string `json:"gpuManufacturer"` // gpu厂商 + GpuModel *string `json:"gpuModel"` // gpu处理器型号 + DataVolumeType *string `json:"dataVolumeType"` // 数据盘类型(SSD,HDD) + DataVolumeInterfaceType *string `json:"dataVolumeInterfaceType"` // 数据盘接口类型(SATA,SAS,NVME) + DataVolumeSize *float64 `json:"dataVolumeSize"` // 数据盘单盘大小 + DataVolumeUnit *string `json:"dataVolumeUnit"` // 数据盘单位(GB,TB) + DataVolumeAmount *int64 `json:"dataVolumeAmount"` // 数据盘数量 + CreatedBy *string `json:"createdBy"` // 创建者 + UpdatedBy *string `json:"updatedBy"` // 更新者 + CreatedTime *int `json:"createdTime"` // 创建时间 + UpdatedTime *int `json:"updatedTime"` // 更新时间 + + RaidID *string `json:"raidId"` //系统盘raid,支持多选 + // CPU 预置规格 + CpuSpec *string `json:"cpuSpec" validate:"omitempty,oneof=common user_defined"` + // 内存 预置规格 + MemSpec *string `json:"memSpec" validate:"omitempty,oneof=common user_defined"` + //boot模式[UEFI Legacy/BIOS]支持多选,逗号分隔 + BootMode string `json:"bootMode" validate:"omitempty"` + Volumes []*sdkModels.VolumeItem `json:"volumes"` + IsNeedRaid *string `json:"isNeedRaid"` +} + +// 【机型管理】【机型列表】 +type QueryDeviceTypesRequest struct { + BaseRequest + PagingRequest + DeviceTypeID string `json:"deviceTypeId"` + DeviceType string `json:"deviceType"` // 机型规格, cps.c.normal + IdcID string `json:"idcId"` + Name string `json:"name"` // 机型名称,如计算效能型,标准计算型 + DeviceSeries string `json:"deviceSeries"` // 机型类型,如计算型,存储型 + IsAll string `json:"isAll"` + // 非空表示导出 + ExportType string `json:"exportType"` +} + +// 【机型管理】【机型详情信息】 +type QueryDeviceTypeRequest struct { + DeviceTypeID string `json:"deviceTypeID"` +} + +// 【机型管理】【删除】 +type DeleteDeviceTypeRequest struct { + DeviceTypeID string `json:"deviceTypeID"` +} + +type GetAvailableDeviceTypesRequest struct { + IdcID string `json:"idc_id"` +} diff --git a/bmp-operation-api/types/request/HeaderRequest.go b/bmp-operation-api/types/request/HeaderRequest.go new file mode 100644 index 0000000..af041c5 --- /dev/null +++ b/bmp-operation-api/types/request/HeaderRequest.go @@ -0,0 +1,8 @@ +package request + +type HeaderRequest struct { + Region string `json:"region"` // 必填 + Az string `json:"az"` + Pin string `json:"pin"` + Tenant string `json:"tenant"` +} diff --git a/bmp-operation-api/types/request/IdcRequest.go b/bmp-operation-api/types/request/IdcRequest.go new file mode 100644 index 0000000..da3c940 --- /dev/null +++ b/bmp-operation-api/types/request/IdcRequest.go @@ -0,0 +1,77 @@ +package request + +// 机房管理 模块请求字段 +type CreateIdcRequest struct { + Address string `json:"address"` + // ilo password + IloPassword string `json:"iloPassword"` + // ilo user + IloUser string `json:"iloUser"` + // level + Level string `json:"level"` + // name + Name string `json:"name"` + // nameEn + NameEn string `json:"nameEn"` + // shortname + Shortname string `json:"shortname"` + // switch password1 + SwitchPassword1 string `json:"switchPassword1"` + // switch password2 + SwitchPassword2 string `json:"switchPassword2"` + // switch user1 + SwitchUser1 string `json:"switchUser1"` + // switch user2 + SwitchUser2 string `json:"switchUser2"` +} + +// 【机房管理】【编辑机房】 +type ModifyIdcRequest struct { + //ID int `gorm:"primaryKey;column:id" json:"-"` // 主键 + IdcID string `json:"idcId"` + // address + Address *string `json:"address"` + // ilo password + IloPassword *string `json:"iloPassword"` + // ilo user + IloUser *string `json:"iloUser"` + // level + Level *string `json:"level"` + // name + Name *string `json:"name"` + // name en + NameEn *string `json:"nameEn"` + // shortname + Shortname *string `json:"shortname"` + // switch password1 + SwitchPassword1 *string `json:"switchPassword1"` + // switch password2 + SwitchPassword2 *string `json:"switchPassword2"` + // switch user1 + SwitchUser1 *string `json:"switchUser1"` + // switch user2 + SwitchUser2 *string `json:"switchUser2"` +} + +// 【机房管理】【机房列表】 +type QueryIdcListRequest struct { + BaseRequest + PagingRequest + Name string `json:"name"` + Level string `json:"level"` + IsAll string `json:"isAll"` + Show string `json:"show"` + // 非空表示导出 + ExportType string `json:"exportType"` +} + +// 【机房管理】【机房详情信息】 +type QueryIdcRequest struct { + Show string `json:"show"` + IdcID string `json:"idcId"` +} + +// 【机房管理】【删除】 +type DeleteIdcRequest struct { + IdcID string `json:"idcId"` +} diff --git a/bmp-operation-api/types/request/ImageRequest.go b/bmp-operation-api/types/request/ImageRequest.go new file mode 100644 index 0000000..dac75e1 --- /dev/null +++ b/bmp-operation-api/types/request/ImageRequest.go @@ -0,0 +1,158 @@ +package request + +import ( + "mime/multipart" +) + +type CreateImageRequest struct { + ImageName string `json:"imageName" validate:"required,min=1,max=200"` + Architecture string `json:"architecture" validate:"required"` + OsType string `json:"osType" validate:"required"` + Version string `json:"version" validate:"required"` + //OsID string `json:"osId" validate:"required"` + //ImageFile multipart.File `json:"imageFile"` + Format string `json:"format"` + //boot模式[UEFI Legacy/BIOS]支持多选,逗号分隔 + BootMode string `json:"bootMode" validate:"omitempty"` + FileName string `json:"fileName"` + Url string `json:"url"` + Hash string `json:"hash"` + Description string `json:"description"` // 描述 + SystemPartition string `json:"systemPartition"` // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + DataPartition string `json:"dataPartition"` // 数据分区信息 +} +type UploadImageRequest struct { + ImageFile multipart.File `json:"imageFile"` +} + +//Format string `json:"format" validate:"required"` +//Filename string `json:"filename" validate:"required"` +//Url string `json:"url" validate:"required"` +//Hash string `json:"hash"` +//Source string `json:"source"` +//镜像默认分区 +//[{"format":"swap","point":"swap","size":10240},{"format":"xfs","point":"/","size":51200}] +type Partition struct { + FsType string `json:"format"` //format + MountPoint string `json:"point"` //point + Size int `json:"size"` +} + +//func (c *CreateImageRequest) Validate(logger *log.Logger) { +// if err := validator.New().Struct(c); err != nil { +// logger.Warn("CreateImageRequest validate error:", err.Error()) +// panic(exception.CommonParamValid) +// } +//} + +type ModifyImageRequest struct { + Description *string `json:"description"` // 描述 +} + +//func (req *ModifyImageRequest) Validate(logger *log.Logger) { +// if err := validator.New().Struct(req); err != nil { +// logger.Warn("ModifyImageRequest.Validate error:", err.Error()) +// panic(exception.CommonParamValid) +// } +// if match, _ := regexp.MatchString(validation.REGEX_ID, req.OsID); !match { +// logger.Warn("ModifyImageRequest.OsId invalid:", req.OsID) +// panic(exception.CommonParamValid) +// } +// if match, _ := regexp.MatchString(validation.REGEX_SOURCE_TYPE, req.Source); !match { +// logger.Warn("ModifyImageRequest.Source invalid:", req.Source) +// panic(exception.CommonParamValid) +// } +// +//} + +type QueryImagesRequest struct { + ImageID string `json:"imageId"` + ImageName string `json:"imageName"` + DeviceTypeID string `json:"deviceTypeId"` + Version string `json:"version"` + OsID string `json:"osId"` + ImageIDs []string `json:"imageIds"` + Source string `json:"source"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + IsAll string `json:"isAll"` + ExportType string `json:"exportType"` + Architecture string `json:"architecture"` + OsType string `json:"osType"` +} + +//func (req *QueryImagesRequest) Validate(logger *log.Logger) { +// if err := validator.New().Struct(req); err != nil { +// logger.Warn("QueryImagesRequest validate error:", err.Error()) +// panic(exception.CommonParamValid) +// } +// +// //if req.Source != "" { +// // if match, _ := regexp.MatchString(validation.REGEX_SOURCE_TYPE, req.Source); !match { +// // logger.Warn("QueryImagesRequest Source invalid") +// // panic(exception.CommonParamValid) +// // } +// //} +// +//} + +type AssociateImageRequest struct { + //DeviceTypeImages []DeviceTypeImagePair `json:"device_type_images"` + DeviceTypeID string `json:"deviceTypeId"` + ImageIDs []string `json:"imageIds"` +} + +type DeviceTypeImagePair struct { + DeviceType string `json:"device_type"` + ImageId string `json:"image_id"` +} + +//func (c *AssociateImageRequest) Validate(logger *log.Logger) { +// if err := validator.New().Struct(c); err != nil { +// logger.Warn("AssociateImageRequest.Validate error:", err.Error()) +// panic(exception.CommonParamValid) +// } +//} + +type DissociatedImageRequest struct { + DeviceTypeID string `json:"deviceTypeId"` + ImageID string `json:"ImageId"` +} + +//func (req *DissociatedImageRequest) Validate(logger *log.Logger) { +// if err := validator.New().Struct(req); err != nil { +// logger.Warn("DissociatedImageRequest.Validate error:", err.Error()) +// panic(exception.CommonParamValid) +// } +//} +type QueryImageDeviceTypesRequest struct { + // 镜像ID + // required: true + ImageID string `json:"imageId" validate:"required"` + // 体系架构 + Architecture string `json:"architecture"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + //镜像是否绑定了机型,0查询该镜像没有绑定的机型列表 1查询该镜像已经绑定了的机型列表 + IsBind string `json:"isBind"` + // 是否显示全部 + IsAll string `json:"isAll"` +} + +//镜像绑定机型 +type AssociateImageDeviceTypeRequest struct { + BaseRequest + ImageId string `json:"ImageId"` + DeviceTypeIDs string `json:"deviceTypeIds"` // 逗号分隔 +} + +type QueryImagesByDeviceTypeRequest struct { + // Pin string `json:"pin"` + IdcID string `json:"idc_id"` + DeviceTypeID string `json:"deviceTypeId"` + // OsType string `json:"os_type"` + // OsVersion string `json:"os_version"` + // OsID string `json:"os_id"` + // Source string `json:"source"` + // ImageIds []string `json:"image_ids"` +} diff --git a/bmp-operation-api/types/request/InstanceRequest.go b/bmp-operation-api/types/request/InstanceRequest.go new file mode 100644 index 0000000..f59aba3 --- /dev/null +++ b/bmp-operation-api/types/request/InstanceRequest.go @@ -0,0 +1,63 @@ +package request + +import ( + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// type InstanceRequest struct { +// PageNumber string `json:"pageNumber"` +// PageSize string `json:"pageSize"` +// CabinetNo string `json:"cabinetNo"` +// Erp string `json:"erp"` +// Host string `json:"host"` +// } + +type StartInstanceRequest struct { + InstanceID string `json:"instanceId"` +} + +type RestartInstanceRequest struct { + InstanceID string `json:"instanceId"` +} + +type StopInstanceRequest struct { + InstanceID string `json:"instanceId"` +} + +// func (c *InstanceRequest) Validate() { +// if err := validator.New().Struct(c); err != nil { +// panic(exception.CommonParamValid) +// } +// } + +type StartInstancesRequest struct { + InstanceIDs []string `json:"instanceIds"` +} + +type ModifyInstancesRequest struct { + InstanceIDs []string `json:"instanceIds"` + InstanceName string `json:"instanceName"` +} + +type ResetPasswdRequest struct { + HeaderRequest + InstanceId string `json:"instanceId" valid:"Required"` + Password string `json:"password"` +} + +type ResetInstancesPasswdRequest struct { + HeaderRequest + InstanceIds []string `json:"instanceIds" valid:"Required"` + Password string `json:"password"` +} + +type ReinstallInstanceRequest struct { + HeaderRequest + InstanceId string `json:"instanceId" valid:"Required"` + sdkModels.ReinstallInstanceRequest +} + +type QueryInstanceRequest struct { + HeaderRequest + InstanceId string `json:"instanceId" valid:"Required"` +} diff --git a/bmp-operation-api/types/request/KeypairRequest.go b/bmp-operation-api/types/request/KeypairRequest.go new file mode 100644 index 0000000..1280a36 --- /dev/null +++ b/bmp-operation-api/types/request/KeypairRequest.go @@ -0,0 +1,9 @@ +package request + +type QueryKeypairsRequest struct { + PagingRequest + + Name string `json:"name"` + + KeypairIds []string `json:"keypairId"` +} diff --git a/bmp-operation-api/types/request/MessageRequest.go b/bmp-operation-api/types/request/MessageRequest.go new file mode 100644 index 0000000..f7f493f --- /dev/null +++ b/bmp-operation-api/types/request/MessageRequest.go @@ -0,0 +1,73 @@ +package request + +type QueryMessagesRequest struct { + PagingRequest + // 0:导出全部实力;1:导出选中实例;2:导出搜索结果 + ExportType string `json:"exportType"` + // 是否显示全部,取值为1时表示全部 + IsAll string `json:"isAll"` + //0:未读;1:已读;""不传表示全部 + HasRead string `json:"hasRead"` + // 消息类型 + MessageType string `json:"messageType"` + // 消息子类型 + MessageSubType string `json:"messageSubType"` + // 内容模糊搜索 + Detail string `json:"detail"` +} + +type ReadMessagesRequest struct { + + // required: true + MessageIds []string `json:"messageIds" validate:"required"` +} +type DeleteMessagesRequest struct { + + // required: true + MessageIds []string `json:"messageIds" validate:"required"` +} + +type GetMessageByIdRequest struct { + // required: true + MessageId string `json:"messageId" validate:"required"` +} + +type MailDialRequest struct { + // 邮件服务器地址 + // required: true + ServerAddr string `json:"server_addr" validate:"required"` + // 邮件服务器端口 + // required: true + ServerPort string `json:"server_port" validate:"required"` + // 管理员邮箱 + // required: true + AdminAddr string `json:"admin_addr" validate:"required"` + // 管理员邮箱密码 + // required: true + AdminPass string `json:"admin_pass" validate:"required"` + //收件人邮箱 + To string `json:"to"` +} + +type MailSaveRequest struct { + // 邮件服务器地址 + // required: true + ServerAddr string `json:"server_addr" validate:"required"` + // 邮件服务器端口 + // required: true + ServerPort string `json:"server_port" validate:"required"` + // 管理员邮箱 + // required: true + AdminAddr string `json:"admin_addr" validate:"required"` + // 管理员邮箱密码 + // required: true + AdminPass string `json:"admin_pass" validate:"required"` + //收件人邮箱 + To string `json:"to"` +} + +type SaveIsPushMailRequest struct { + // 是否打开推送,"0","1" + // required: true + IsPush string `json:"is_push" validate:"required"` +} diff --git a/bmp-operation-api/types/request/MonitorAlertRequest.go b/bmp-operation-api/types/request/MonitorAlertRequest.go new file mode 100644 index 0000000..5ba68eb --- /dev/null +++ b/bmp-operation-api/types/request/MonitorAlertRequest.go @@ -0,0 +1,58 @@ +package request + +type AddAlertRequest struct { + //规则名称 + RuleName string `json:"ruleName" validate:"required"` + //规则ID + // required: true + RuleID string `json:"ruleId" validate:"required"` + //实例id + // required: true + InstanceID string `json:"instanceId" validate:"required"` + //触发条件 + // required: true + Trigger string `json:"trigger" validate:"required"` + //告警值 + // required: true + AlertValue string `json:"alertValue" validate:"required"` + //告警时间戳 + // required: true + AlertTimestamp int64 `json:"alertTimestamp" validate:"required"` + //告警持续时间 + // required: true + AlertPeriod int `json:"alertPeriod" validate:"required"` +} + +type DescribeAlertRequest struct { + // rule uuid + // required: true + AlertID string `json:"alertId" validate:"required"` +} + +type DescribeAlertsRequest struct { + PagingRequest + ExportType string `json:"exportType"` + + // 是否显示全部,取值为1时表示全部 + IsAll string `json:"isAll"` + //user uuid + UserID string `json:"userId"` + //username + UserName string `json:"userName"` + //规则名称 + RuleName string `json:"ruleName"` + //规则uuid + RuleID string `json:"ruleId"` + //资源id,目前就是实例id + ResourceID string `json:"resourceId"` + //报警时间筛选stime + StartTime int64 `json:"startTime"` + //报警时间筛选etime + EndTime int64 `json:"endTime"` +} + +type DeleteAlertRequest struct { + //告警id + // required: true + AlertId string `json:"alertId" validate:"required"` +} diff --git a/bmp-operation-api/types/request/MonitorDataRequest.go b/bmp-operation-api/types/request/MonitorDataRequest.go new file mode 100644 index 0000000..eba0f20 --- /dev/null +++ b/bmp-operation-api/types/request/MonitorDataRequest.go @@ -0,0 +1,21 @@ +package request + +/* +{"params":{"serviceCode":"cps-vpc","resourceId":"cps-2qtflhpvmuuw5tdodatv6ofxqcek","filters":[{"name":"metric","values":["cps.process.total"]}],"startTime":"2024-06-09T00:00:00","endTime":"2024-06-12T23:59:59","timeInterval":"1h", "downSampleType":"avg"}} +*/ +type GetMonitorDataRequest struct { + MetricName string `json:"metricName" validate:"required"` + InstanceID string `json:"instanceId" validate:"required"` + Device string `json:"device"` + StartTime int64 `json:"startTime"` + EndTime int64 `json:"endTime"` + //最近多少时间,小时为单位 + LastManyTime int64 `json:"lastManyTime"` + TimeInterval int64 `json:"timeInterval"` //s为单位 + DownSampleType string `json:"downSampleType"` //好像不支持 + + //以下为运营平台的 + UserName string `json:"userName"` + //idc uuid + IdcID string `json:"idcID"` +} diff --git a/bmp-operation-api/types/request/MonitorProxyRequest.go b/bmp-operation-api/types/request/MonitorProxyRequest.go new file mode 100644 index 0000000..cead90d --- /dev/null +++ b/bmp-operation-api/types/request/MonitorProxyRequest.go @@ -0,0 +1,16 @@ +package request + +type DesrcibeAgentStatusRequest struct { + // InstanceId,多个用逗号分隔 + // required: true + InstanceId string `json:"instanceId" validate:"required"` +} + +type DesrcibeTagsRequest struct { + // instanceId + // required: true + InstanceID string `json:"instanceId" validate:"required"` + // tagName [disk mountpoint nic] + // required: true + TagName string `json:"tagName" validate:"required,oneof=disk mountpoint nic"` +} diff --git a/bmp-operation-api/types/request/MonitorRuleRequest.go b/bmp-operation-api/types/request/MonitorRuleRequest.go new file mode 100644 index 0000000..8de7ea9 --- /dev/null +++ b/bmp-operation-api/types/request/MonitorRuleRequest.go @@ -0,0 +1,140 @@ +package request + +type AddRuleRequest struct { + //规则名称 + // required: true + RuleName string `json:"ruleName" validate:"required"` + //维度 [instance、disk、mountpoint、nic] + // required: true + Dimension string `json:"dimension" validate:"required,oneof=instance disk mountpoint nic"` + //资源类型,目前只支持instance + // required: true + Resource string `json:"resource" validate:"required,oneof=instance"` + //触发条件 + // required: true + TriggerOption []RuleTrigger `json:"triggerOption"` + //通知策略 + // required: true + NoticeOption RuleNotice `json:"noticeOption"` + //实例id列表 + // required: true + InstanceIds []string `json:"instanceIds" validate:"required"` + //盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag"` +} + +//单个触发条件 +type RuleTrigger struct { + //监控指标 cps.cpu.util + // required: true + Metric string `json:"metric" validate:"required"` + //周期(分钟) [1, 2, 5, 15, 30, 60] + // required: true + Period int64 `json:"period" validate:"required,oneof=1 2 5 15 30 60"` + //计算方式 [min max avg sum] + // required: true + Calculation string `json:"calculation" validate:"required,oneof=min max avg sum"` + //计算结果单位 [对于使用量,有Bytes,KB,MB,GB,TB,对于使用率,是%,对于连接个数,是count,对于网络包量,是pps,Kpps,Mpps,Gpps,Tpps,对于网络速率,是bps,Kbps,Mbps,Gbps,Tbps 对于负载,没有单位。。。。。。产品需详细列出] + // required: true + CalculationUnit string `json:"calculationUnit"` + //比较方式 [> >= < <= == !=]或者[gt gte lt lte eq neq] + // required: true + Operation string `json:"operation" validate:"required"` + //阈值 + // required: true + Threshold float64 `json:"threshold"` + //持续周期数 [1, 2, 3, 4, 5, 10, 15, 30, 60] + // required: true + Times int64 `json:"times" validate:"required,oneof=1 2 3 4 5 10 15 30 60"` + //告警级别 [1表示一般,2表示严重,3表示紧急] + // required: true + NoticeLevel int64 `json:"noticeLevel" validate:"required,oneof=1 2 3"` +} + +//通知策略 +type RuleNotice struct { + //通知周期(分钟) [5 10 15 30 60 180 360 720 1440] + // required: true + NoticePeriod int64 `json:"noticePeriod" validate:"required,oneof=5 10 15 30 60 180 360 720 1440"` + // 有效时段开始时间 ["00:00:00"] + // required: true + EffectiveIntervalStart string `json:"effectiveIntervalStart" validate:"required"` + // 有效时段结束时间 ["23:59:59"] + // required: true + EffectiveIntervalEnd string `json:"effectiveIntervalEnd" validate:"required"` + //通知条件,可多选 [1表示报警, 2表示恢复正常] + // required: true + NoticeCondition []int64 `json:"noticeCondition" validate:"required"` + //接收渠道,可多选 [1表示站内信, 2表示邮件] + // required: true + NoticeWay []int64 `json:"noticeWay" validate:"required"` + //通知对象 + // required: true + UserID string `json:"userId" validate:"required"` +} + +type DescribeRuleRequest struct { + // rule uuid + // required: true + RuleID string `json:"ruleId" validate:"required"` +} + +type DescribeRulesRequest struct { + PagingRequest + ExportType string `json:"exportType"` + // 是否显示全部,取值为1时表示全部 + IsAll string `json:"isAll"` + //user uuid + UserId string `json:"userId"` + //username + UserName string `json:"userName"` + //规则名称 + RuleName string `json:"ruleName"` + //规则uuid + RuleId string `json:"ruleId"` + Status int `json:"status"` +} + +type EditRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` + //规则名称 + // required: true + RuleName string `json:"ruleName" validate:"required"` + //维度 [instance、disk、mountpoint、nic] + // required: true + Dimension string `json:"dimension" validate:"required,oneof=instance disk mountpoint nic"` + //资源类型,目前只支持instance + // required: true + Resource string `json:"resource" validate:"required,oneof=instance"` + //触发条件 + // required: true + TriggerOption []RuleTrigger `json:"triggerOption"` + //通知策略 + // required: true + NoticeOption RuleNotice `json:"noticeOption"` + //实例id列表 + // required: true + InstanceIds []string `json:"instanceIds" validate:"required"` + //盘符、挂载点、网口列表 + DeviceTag string `json:"deviceTag"` +} + +type EnableRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` +} + +type DisableRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` +} + +type DeleteRuleRequest struct { + //规则id + // required: true + RuleId string `json:"ruleId" validate:"required"` +} diff --git a/bmp-operation-api/types/request/OsRequest.go b/bmp-operation-api/types/request/OsRequest.go new file mode 100644 index 0000000..c13c91d --- /dev/null +++ b/bmp-operation-api/types/request/OsRequest.go @@ -0,0 +1,63 @@ +package request + +import ( + "git.jd.com/cps-golang/ironic-common/exception" + log "git.jd.com/cps-golang/log" + "github.com/go-playground/validator/v10" +) + +type CreateOSRequest struct { + OsName string `json:"osName" validate:"required,min=1,max=200"` + OsType string `json:"osType" validate:"required"` + + Architecture string `json:"architecture" validate:"required"` + Bits int `json:"bits" validate:"required"` + OsVersion string `json:"osVersion" validate:"required"` + SysUser string `json:"sysUser"` +} + +func (req *CreateOSRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(req); err != nil { + logger.Warn("CreateOSRequest.Validate error:", err.Error()) + panic(exception.CommonParamValid) + } +} + +type ModifyOSRequest struct { + OsName string `json:"osName" ` + OsType string `json:"osType" ` + + Architecture string `json:"architecture"` + Bits int `json:"bits" ` + OsVersion string `json:"osVersion"` + SysUser string `json:"sysUser"` +} + +func (c *ModifyOSRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(c); err != nil { + logger.Warn("ModifyOSRequest.Validate error:", err.Error()) + panic(exception.CommonParamValid) + } +} + +type QueryOssRequest struct { + OsName string `json:"osName"` // 操作系统名称 + Architecture string `json:"architecture"` //体系架构 + OsType string `json:"osType"` // 操作系统分类:linux/windows + Platform string `json:"platform"` // suse/centos/ubuntu + OsVersion string `json:"osVersion"` // 操作系统版本 + IsAll string `json:"isAll"` +} + +func (req *QueryOssRequest) Validate(logger *log.Logger) { + if err := validator.New().Struct(req); err != nil { + logger.Warn("QueryOssRequest.Validate error:", err.Error()) + panic(exception.CommonParamValid) + } + //for _, v := range req.Ids { + // if match, _ := regexp.MatchString(validation.REGEX_ID, v); !match { + // logger.Warn("QueryOssRequest.Ids invalid:", req.Ids) + // panic(exception.CommonParamValid) + // } + //} +} diff --git a/bmp-operation-api/types/request/PagingRequest.go b/bmp-operation-api/types/request/PagingRequest.go new file mode 100644 index 0000000..39d87f3 --- /dev/null +++ b/bmp-operation-api/types/request/PagingRequest.go @@ -0,0 +1,6 @@ +package request + +type PagingRequest struct { + PageNumber int64 `json:"pageNumber" validate:"gte=1"` + PageSize int64 `json:"pageSize" validate:"lte=1000,gte=1"` +} diff --git a/bmp-operation-api/types/request/ParseFileRequest.go b/bmp-operation-api/types/request/ParseFileRequest.go new file mode 100644 index 0000000..0fc2dbf --- /dev/null +++ b/bmp-operation-api/types/request/ParseFileRequest.go @@ -0,0 +1,10 @@ +package request + +import "mime/multipart" + +type ParseFileRequest struct { + BaseRequest + Region string `json:"region" valid:"Required"` + Base64 bool `json:"base64" valid:"Required"` + UserDataFile multipart.File `json:"userDataFile" valid:"Required"` +} diff --git a/bmp-operation-api/types/request/PartitionRequest.go b/bmp-operation-api/types/request/PartitionRequest.go new file mode 100644 index 0000000..25fbaad --- /dev/null +++ b/bmp-operation-api/types/request/PartitionRequest.go @@ -0,0 +1,6 @@ +package request + +type QueryDefaultSystemPartitionRequest struct { + ImageID string `json:"imageId" validate:"required"` + DeviceTypeID string `json:"deviceTypeId" validate:"required"` +} diff --git a/bmp-operation-api/types/request/RaidRequest.go b/bmp-operation-api/types/request/RaidRequest.go new file mode 100644 index 0000000..5cc2beb --- /dev/null +++ b/bmp-operation-api/types/request/RaidRequest.go @@ -0,0 +1,6 @@ +package request + +type QueryRaidsRequest struct { + DeviceTypeID string `json:"deviceTypeId" validate:"required"` + VolumeType string `json:"volumeType" validate:"required"` +} diff --git a/bmp-operation-api/types/request/ResourceRequest.go b/bmp-operation-api/types/request/ResourceRequest.go new file mode 100644 index 0000000..ff9a229 --- /dev/null +++ b/bmp-operation-api/types/request/ResourceRequest.go @@ -0,0 +1,16 @@ +package request + +type QueryResourcesRequest struct { + /*// 机房名称 + IdcName string `json:"idcName"` + // 机房英文名称 + IdcNameEn string `json:"idcNameEn"`*/ + // 机型名称 + Name string `json:"name"` + // 机型规格 + DeviceType string `json:"deviceType"` + // 镜像名称 + ImageName string `json:"imageName"` + // 用户名称 + UserName string `json:"userName"` +} diff --git a/bmp-operation-api/types/request/ResourceTagRequest.go b/bmp-operation-api/types/request/ResourceTagRequest.go new file mode 100644 index 0000000..9c98775 --- /dev/null +++ b/bmp-operation-api/types/request/ResourceTagRequest.go @@ -0,0 +1,22 @@ +package request + +import ( + "git.jd.com/cps-golang/ironic-common/exception" + validator "github.com/go-playground/validator/v10" +) + +type ResourceTagRequest struct { + Region string `json:"region"` + Params struct { + ResourceVo struct { + ResourceIds []string `json:"resourceIds"` + ServiceCodes []string `json:"serviceCodes"` + } `json:"resourceVo"` + } `json:"params"` +} + +func (c *ResourceTagRequest) Validate() { + if err := validator.New().Struct(c); err != nil { + panic(exception.CommonParamValid) + } +} diff --git a/bmp-operation-api/types/request/RoleRequest.go b/bmp-operation-api/types/request/RoleRequest.go new file mode 100644 index 0000000..e0ac513 --- /dev/null +++ b/bmp-operation-api/types/request/RoleRequest.go @@ -0,0 +1,5 @@ +package request + +type DescribeRolesRequest struct { + IsAll string `json:"isAll"` +} diff --git a/bmp-operation-api/types/request/UserRequest.go b/bmp-operation-api/types/request/UserRequest.go new file mode 100644 index 0000000..2a25a44 --- /dev/null +++ b/bmp-operation-api/types/request/UserRequest.go @@ -0,0 +1,74 @@ +package request + +// 【用户管理】【用户列表】 +type QueryUsersRequest struct { + BaseRequest + PagingRequest + RoleID string `json:"roleId"` + ProjectID string `json:"defaultProjectId"` + UserName string `json:"userName"` + IsAll string `json:"isAll"` +} + +// 【用户管理】【添加用户】 +type AddUserRequest struct { + // BaseRequest + RoleID string `json:"roleId"` // 角色uuid + UserName string `json:"userName"` // 用户名,唯一 + Email string `json:"email"` // 邮箱 + PhonePrefix string `json:"phonePrefix"` // 国家地区码,如86 + PhoneNumber string `json:"phoneNumber"` // 手机号 + Language string `json:"language"` // 语言(中文/English) + Password string `json:"password"` // 密码,sha256非对称加密后存储 + Description string `json:"description"` // 描述 +} + +type QueryUserInfoRequest struct { + UserID string `json:"userId"` // 用户uuid +} + +// 【用户管理】【编辑用户信息】 +type ModifyUserInfoRequest struct { + //UserID string `json:"userId"` + RoleID *string `json:"roleId"` // 角色uuid + UserName *string `json:"userName"` // 用户名,唯一 + Email *string `json:"email"` // 邮箱 + PhonePrefix *string `json:"phonePrefix"` // 国家地区码,如86 + PhoneNumber *string `json:"phoneNumber"` // 手机号 + DefaultProjectID string `json:"defaultProjectId"` // 所属项目uuid + Language *string `json:"language"` // 语言(中文/English) + //Timezone time.Time `gorm:"column:timezone" json:"timezone"` // UTC或者本时区时间 + Password *string `json:"password"` // 密码,sha256非对称加密后存储 + Description *string `json:"description"` // 描述 +} + +type DeleteUserInfoRequest struct { + UserID string `json:"userId"` // 用户uuid +} + +type LoginRequest struct { + Username string `json:"username"` + Password string `json:"password"` +} + +type VerifyUserRequest struct { + Username string `json:"username"` + Password string `json:"password"` +} + +type UpdateLocalPasswordRequest struct { + OldPassword string `json:"oldPassword"` // + Password string `json:"password"` // 密码 +} + +// 【用户管理】【编辑用户信息】 +type ModifyLocalUserInfoRequest struct { + UserName *string `json:"userName"` // 用户名,唯一 + Email *string `json:"email"` // 邮箱 + PhonePrefix *string `json:"phonePrefix"` // 国家地区码,如86 + PhoneNumber *string `json:"phoneNumber"` // 手机号 + DefaultProjectID *string `json:"defaultProjectId"` // 所属项目uuid + Language *string `json:"language"` // 语言(中文/English) + Timezone *string `json:"timezone"` // UTC或者本时区时间 + Description *string `json:"description"` // 描述 +} diff --git a/bmp-operation-api/types/response/ApiKey.go b/bmp-operation-api/types/response/ApiKey.go new file mode 100644 index 0000000..66d44bf --- /dev/null +++ b/bmp-operation-api/types/response/ApiKey.go @@ -0,0 +1,27 @@ +package response + +type Apikey struct { + ID int `json:"id"` + ApikeyID string `json:"apiKeyId"` // 秘钥uuid + Name string `json:"name"` // 秘钥名称 + ReadOnly int8 `json:"readOnly"` //是否支持只读,read_only =1 的时候说明这个key是只读key,不能访问写方法。 + Token string `json:"token"` // 32位字符令牌 + Type string `json:"type"` // Token类型system/user + UserID string `json:"userId"` // 所属用户 + CreatedBy string `json:"createdBy"` // 创建者 + UpdatedBy string `json:"updatedBy"` // 更新者 + CreatedTime string `json:"createdTime"` // 创建时间戳 + UpdatedTime string `json:"updatedTime"` // 更新时间戳 +} +type ApikeyList struct { + Apikeys []*Apikey `json:"apikeys"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type ApikeyInfo struct { + Apikey *Apikey `json:"apikey"` +} +type ApikeyId struct { + ApikeyId string `json:"apikeyId"` +} diff --git a/bmp-operation-api/types/response/AuditLogs.go b/bmp-operation-api/types/response/AuditLogs.go new file mode 100644 index 0000000..e5d0982 --- /dev/null +++ b/bmp-operation-api/types/response/AuditLogs.go @@ -0,0 +1,10 @@ +package response + +import sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + +type AuditLogsList struct { + AuditLogs []*sdkModels.AuditLog `json:"messages"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} diff --git a/bmp-operation-api/types/response/CommonResponse.go b/bmp-operation-api/types/response/CommonResponse.go new file mode 100644 index 0000000..b1e8d06 --- /dev/null +++ b/bmp-operation-api/types/response/CommonResponse.go @@ -0,0 +1,40 @@ +package response + +//新增加或者删除返给前端的true或者false +type CommonResponse struct { + Success bool `json:"success"` +} +type FilterList struct { + Architecture ArchitectureList `json:"architecture"` + CPU []CPU `json:"cpuSpec"` + Mem []Mem `json:"memSpec"` + RaidRules map[int]map[string]map[string]string `json:"raidRules"` + BootMode []string `json:"bootMode"` //新增bootmode配置@minping,国梁 +} +type ArchitectureList struct { + X86_64 string `json:"x86_64"` + Arm string `json:"ARM64(aarch64)"` + I386 string `json:"i386"` + LoongArch string `json:"LoongArch™"` +} +type CPU struct { + Value int `json:"value"` + Label string `json:"label"` + Info struct { + CPUManufacturer string `json:"cpuManufacturer"` + CPUCores int `json:"cpuCores"` + CPUModel string `json:"cpuModel"` + CPUAmount int `json:"cpuAmount"` + CPUFrequency string `json:"cpuFrequency"` + } `json:"info"` +} +type Mem struct { + Value int `json:"value"` + Label string `json:"label"` + Info struct { + MemType string `json:"memType"` + MemSize int `json:"memSize"` + MemAmount int `json:"memAmount"` + MemFrequency int `json:"memFrequency"` + } `json:"info"` +} diff --git a/bmp-operation-api/types/response/DeviceResponse.go b/bmp-operation-api/types/response/DeviceResponse.go new file mode 100644 index 0000000..7123975 --- /dev/null +++ b/bmp-operation-api/types/response/DeviceResponse.go @@ -0,0 +1,188 @@ +package response + +// import "encoding/json" + +type Device struct { + + // 额外拼接的字段,省去前端工作 + CpuInfo string `json:"cpuInfo"` + MemInfo string `json:"memInfo"` // 内存信息拼接 + SvInfo string `json:"svInfo"` // 系统盘信息拼接 + DvInfo string `json:"dvInfo"` // 数据盘信息拼接 + GpuInfo string `json:"gpuInfo"` + NicInfo string `json:"nicInfo"` // 单网卡 or 双网口 + + IdcID string `json:"idcId"` + DeviceTypeID string `json:"deviceTypeId"` + ID int `json:"id"` // 设备ID编号 + Sn string `json:"sn"` // 设备SN + DeviceID string `json:"deviceId"` // 设备uuid + InstanceID string `json:"instanceId"` // 实例id + ManageStatus string `json:"manageStatus"` // 设备状态: 未装机,已装机 + ManageStatusName string `json:"manageStatusName"` // 设备状态: 未装机,已装机 + Reason string `json:"reason"` // 设备状态变更失败原因 + Cabinet string `json:"cabinet"` // 机柜编码 + UPosition string `json:"uPosition"` // U位 + IloIP string `json:"iloIp"` // 带外管理IP + IloUser string `json:"iloUser"` // 带外账号 + IloPassword string `json:"iloPassword"` // 带外账号密码 + + Mac1 string `json:"mac1"` // MAC1(eth0) + Mac2 string `json:"mac2"` // MAC2(eth2) + SwitchIP1 string `json:"switchIp1"` // 交换机1ip + SwitchPort1 string `json:"switchPort1"` // 交换机1port + SwitchIP2 string `json:"switchIp2"` // 交换机2ip + SwitchPort2 string `json:"switchPort2"` // 交换机2port + + SwitchUser1 string `json:"switchUser1"` // 交换机1登录账号,如果为空,取所在机房的值 + SwitchPassword1 string `json:"switchPassword1"` // 交换机1登录密码 + SwitchUser2 string `json:"switchUser2"` // 交换机2登录账号,如果为空,取所在机房的值 + SwitchPassword2 string `json:"switchPassword2"` // 交换机2登录密码 + Description string `json:"description"` // 描述 + SwitchIP string `json:"switchIp"` // 网口交换机IP + Mask string `json:"mask"` // 子网掩码 + Eth1Mask string `json:"eth1Mask"` // eth1子网掩码 + Gateway string `json:"gateway"` // 网关地址 + PrivateIPv4 string `json:"privateIpv4"` // 内网IPV4 + PrivateEth1IPV4 string `json:"privateEth1Ipv4"` // ETH1内网IPV4 + PrivateIPv6 string `json:"privateIpv6"` // 内网IPV6 + PrivateEth1IPV6 string `json:"privateEth1Ipv6"` // ETH1内网IPV4 + AdapterID int `json:"adapterId"` // adapter_id + RaidDriver string `json:"raidDriver"` // raid工具:(megacli64等) + + //添加到disk表 + Enclosure1 string `json:"enclosure1"` //系统盘1背板号 + Slot1 int `json:"slot1"` //系统盘1槽位 + Enclosure2 string `json:"enclosure2"` //系统盘2背板号 + Slot2 int `json:"slot2"` //系统盘2槽位 + //以后还能还有数据盘,todo + + CreatedBy string `json:"createdBy"` // 创建者 + UpdatedBy string `json:"updatedBy"` // 更新者 + CreatedTime string `json:"createdTime"` // 创建时间戳 + UpdatedTime string `json:"updatedTime"` // 更新时间戳 + //DeletedTime int `json:"deletedTime"` // 删除时间戳 + //IsDel int8 `json:"isDel"` // 是否删除0未删除 1已删除 + + //以下是通过别的表查询出来的数据,用于返回给上层 + IdcName string `json:"idcName"` + IdcNameEn string `json:"idcNameEn"` + DeviceTypeName string `json:"deviceTypeName"` + + //实例信息 + InstanceName string `json:"instanceName"` + ImageName string `json:"imageName"` + InstanceStatus string `json:"instanceStatus"` + InstanceStatusName string `json:"instanceStatusName"` + // 实例失败原因 + InstanceReason string `json:"instanceReason"` + UserID string `json:"userId"` + UserName string `json:"userName"` + InstanceCreatedTime string `json:"instanceCreatedTime"` + InstanceDescription string `json:"instanceDescription"` + // 实例是否锁定 锁定locked 未锁定unlocked + Locked string `json:"locked"` + LockedName string `json:"lockedname"` + //硬件配置 + Brand string `json:"brand"` //品牌 + Model string `json:"model"` //型号 + DeviceType string `json:"deviceType"` //型号,机型规格cps.normal + DeviceSeries string `json:"deviceSeries"` //计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName"` //计算型,存储型 + Architecture string `json:"architecture"` // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + CPUAmount int64 `json:"cpuAmount"` // cpu数量 + CPUCores int64 `json:"cpuCores"` // 单个cpu内核数 + CPURoads int8 `json:"cpuRoads"` // 单个cpu路数 + CPUManufacturer string `json:"cpuManufacturer"` // cpu厂商 + CPUModel string `json:"cpuModel"` // cpu处理器型号 + CPUFrequency string `json:"cpuFrequency"` // cpu频率(G) + MemType string `json:"memType"` // 内存接口(如DDR3,DDR4) + MemSize int `json:"memSize"` // 单个内存大小(GB) + MemAmount int `json:"memAmount"` // 内存数量 + MemFrequency int `json:"memFrequency"` // 内存主频(MHz) + NicAmount int64 `json:"nicAmount"` // 网卡数量 + NicRate int `json:"nicRate"` // 网卡传输速率(GE) + InterfaceMode string `json:"interfaceMode"` // 【网口模式】【网络设置】: bond单网口,dual双网口 + InterfaceModeName string `json:"interfaceModeName"` + SystemVolumeType string `json:"systemVolumeType"` // 系统盘类型(SSD,HDD) + SystemVolumeInterfaceType string `json:"systemVolumeInterfaceType"` // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeSize int `json:"systemVolumeSize"` // 系统盘单盘大小 + //SystemVolumeUnit string `json:"systemVolumeUnit"` // 系统盘单位(GB,TB) + SystemVolumeAmount int64 `json:"systemVolumeAmount"` // 系统盘数量 + GpuAmount int64 `json:"gpuAmount"` // gpu数量 + GpuManufacturer string `json:"gpuManufacturer"` // gpu厂商 + GpuModel string `json:"gpuModel"` // gpu处理器型号 + DataVolumeType string `json:"dataVolumeType"` // 数据盘类型(SSD,HDD) + DataVolumeInterfaceType string `json:"dataVolumeInterfaceType"` // 数据盘接口类型(SATA,SAS,NVME) + DataVolumeSize int `json:"dataVolumeSize"` // 数据盘单盘大小 + //DataVolumeUnit string `json:"dataVolumeUnit"` // 数据盘单位(GB,TB) + DataVolumeAmount int64 `json:"dataVolumeAmount"` // 数据盘数量 + // "1"表示已采集,"2"表示未采集,3表示采集中,4表示采集失败 + CollectStatus string `json:"collectStatus"` + CollectFailReason string `json:"collectFailReason"` + IsNeedRaid string `json:"isNeedRaid"` +} + +// 上传设备返回 +type UploadDevice struct { + + // 额外拼接的字段,省去前端工作 + Sn string `json:"sn"` // 设备SN + Cabinet string `json:"cabinet"` // 机柜编码 + UPosition string `json:"uPosition"` // U位 + // Brand string `json:"brand"` //品牌 + // Model string `json:"model"` //型号 + IloIP string `json:"iloIp"` // 带外管理IP + IloUser string `json:"iloUser"` // 带外账号 + IloPassword string `json:"iloPassword"` // 带外账号密码 + + Mac1 string `gorm:"column:mac1" json:"mac1"` // MAC1(eth0) + // Mac2 string `gorm:"column:mac2" json:"mac2"` // MAC2(eth2) + /* + SwitchIP1 string `gorm:"column:switch_ip1" json:"switchIp1"` // 交换机1ip + SwitchPort1 string `gorm:"column:switch_port1" json:"switchPort1"` // 交换机1port + SwitchIP2 string `gorm:"column:switch_ip2" json:"switchIp2"` // 交换机2ip + SwitchPort2 string `gorm:"column:switch_port2" json:"switchPort2"` // 交换机2port + + SwitchUser1 string `json:"switchUser1"` // 交换机1登录账号,如果为空,取所在机房的值 + SwitchPassword1 string `json:"switchPassword1"` // 交换机1登录密码 + SwitchUser2 string `son:"switchUser2"` // 交换机2登录账号,如果为空,取所在机房的值 + SwitchPassword2 string `json:"switchPassword2"` // 交换机2登录密码 + */ + //SwitchIP string `json:"switchIp"` // 网口交换机IP + Mask string `json:"mask"` // 子网掩码 + // MaskEth1 string `json:"maskEth1"` // eth1子网掩码 + Gateway string `json:"gateway"` // 网关地址 + PrivateIPv4 string `json:"privateIpv4"` // 内网IPV4 + // PrivateEth1IPv4 string `json:"privateEth1Ipv4"` // Eth1内网IPV4 + PrivateIPv6 string `json:"privateIpv6"` // 内网IPV6 + // PrivateEth1IPv6 string `json:"privateEth1Ipv6"` // 内网eth1IPV6 + // AdapterID int `json:"adapterId"` // adapter_id + //RaidDriver string `json:"raidDriver"` // raid工具:(megacli64等) + /* + Enclosure1 string `json:"enclosure1"` //系统盘1背板号 + Slot1 int `json:"slot1"` //系统盘1槽位 + Enclosure2 string `json:"enclosure2"` //系统盘2背板号 + Slot2 int `json:"slot2"` //系统盘2槽位 + */ + +} +type DevicePage struct { + Devices []Device `json:"devices"` + PagingResponse +} +type DeviceList struct { + Devices []*Device `json:"devices"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type DeviceInfo struct { + Device *Device `json:"device"` +} +type DeviceIds struct { + DeviceIds []string `json:"deviceIds"` +} +type DeviceStock struct { + Stocks int `json:"stocks"` +} diff --git a/bmp-operation-api/types/response/DeviceTypeImageResponse.go b/bmp-operation-api/types/response/DeviceTypeImageResponse.go new file mode 100644 index 0000000..5a6ce6e --- /dev/null +++ b/bmp-operation-api/types/response/DeviceTypeImageResponse.go @@ -0,0 +1,56 @@ +package response + +type DeviceTypeImageList struct { + DeviceTypeImages []DeviceTypeImage `json:"deviceTypes"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} + +type DeviceTypeImage struct { + ID uint64 `json:"id"` // ID + // 镜像uuid + ImageID string `json:"imageId"` + // 镜像名称 + ImageName string `json:"imageName"` + // 源os uuid + OsID string `json:"osId"` + // 镜像格式(qcow2、tar) + Format string `json:"format"` + // 镜像文件名称 + Filename string `json:"filename"` + // 镜像源路径 + URL string `json:"url"` + // 镜像校验码 + Hash string `json:"hash"` + // 镜像来源(common通用、customize定制、user_defined自定义) + Source string `json:"source"` + // 镜像来源(common通用、customize定制、user_defined自定义) + SourceName string `json:"sourceName"` + // 描述 + Description string `json:"description"` + // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + SystemPartition string `json:"systemPartition"` + // 数据分区信息 + DataPartition string `json:"dataPartition"` + // 创建者 + CreatedBy string `json:"createdBy"` + // 更新者 + UpdatedBy string `json:"updatedBy"` + // 创建时间 + CreatedTime string `json:"createdTime"` + // 更新时间 + UpdatedTime string `json:"updatedTime"` + // 架构:x86/x64/i386/ + Architecture string `json:"architecture"` + //CentOS 7.2 64-bit + OsName string `json:"osName"` + // 操作系统分类:linux/windows + OsType string `json:"osType"` + // 操作系统版本 + OsVersion string `json:"osVersion"` + //绑定了机型数量 + DeviceTypeNum int `json:"deviceTypeNum"` + //是否绑定了某个机型 + IsBind bool `json:"isBind"` +} diff --git a/bmp-operation-api/types/response/DeviceTypeResponse.go b/bmp-operation-api/types/response/DeviceTypeResponse.go new file mode 100644 index 0000000..94a9314 --- /dev/null +++ b/bmp-operation-api/types/response/DeviceTypeResponse.go @@ -0,0 +1,154 @@ +package response + +import ( + "encoding/json" +) + +type DeviceType struct { + // 额外拼接的字段,省去前端工作 + CpuInfo string `json:"cpuInfo"` + MemInfo string `json:"memInfo"` // 内存信息拼接 + SvInfo string `json:"svInfo"` // 系统盘信息拼接 + DvInfo string `json:"dvInfo"` // 数据盘信息拼接 + GpuInfo string `json:"gpuInfo"` + NicInfo string `json:"nicInfo"` // 2*10GE + Nic string `json:"nic"` // 单网卡 or 双网口 + ImageCount string `json:"imageCount"` + + ID int `json:"id"` + IDcID string `json:"idcId"` + IdcName string `json:"idcName"` + IdcNameEn string `json:"idcNameEn"` + DeviceTypeID string `json:"deviceTypeId"` // 设备类型uuid + Name string `json:"name"` // 机型名称,如计算效能型,标准计算型 + DeviceType string `json:"deviceType"` // 机型规格, cps.c.normal + DeviceSeries string `json:"deviceSeries"` // 机型类型,如计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName"` // 机型类型,如计算型,存储型 + Architecture string `json:"architecture"` // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Height int `json:"height"` // 【高度(U)】:显示机型高度 + Description string `json:"description"` // 描述 + CPUAmount int64 `json:"cpuAmount"` // cpu数量 + CPUCores int64 `json:"cpuCores"` // 单个cpu内核数 + + CPUManufacturer string `json:"cpuManufacturer"` // cpu厂商 + CPUModel string `json:"cpuModel"` // cpu处理器型号 + CPUFrequency string `json:"cpuFrequency"` // cpu频率(G) + MemType string `json:"memType"` // 内存接口(如DDR3,DDR4) + MemSize int `json:"memSize"` // 单个内存大小(GB) + MemAmount int `json:"memAmount"` // 内存数量 + MemFrequency int `json:"memFrequency"` // 内存主频(MHz) + NicAmount int64 `json:"nicAmount"` // 网卡数量 + NicRate int `json:"nicRate"` // 网卡传输速率(GE) + InterfaceMode string `json:"interfaceMode"` // 【网口模式】【网络设置】: bond单网口,dual双网口 + InterfaceModeName string `json:"interfaceModeName"` // 【网口模式】【网络设置】: bond单网口,dual双网口 + + // 是否做raid,[RAID/NO RAID] + RaidCan string `json:"raidCan"` + GpuAmount int64 `json:"gpuAmount"` // gpu数量 + GpuManufacturer string `json:"gpuManufacturer"` // gpu厂商 + GpuModel string `json:"gpuModel"` // gpu处理器型号 + + CreatedBy string `json:"createdBy"` // 创建者 + UpdatedBy string `json:"updatedBy"` // 更新者 + CreatedTime string `json:"createdTime"` // 创建时间 + UpdatedTime string `json:"updatedTime"` // 更新时间 + //DeletedTime int `json:"deletedTime"` // 删除时间 + //IsDel int8 `son:"isDel"` // 是否删除0未删除 1已删除 + //Raid string `json:"raid"` //系统盘raid + + CPUSpec string `json:"cpuSpec"` // gpu处理器型号 + MemSpec string `json:"memSpec"` // gpu处理器型号 + + InstanceCount int `json:"instanceCount"` + DeviceCount int `json:"deviceCount"` + InstanceStatus []string `json:"instanceStatus"` + //boot模式 + BootMode string `json:"bootMode"` + //Volumes []*sdkModels.Volume `json:"volumes"` + Volumes []Volume `json:"volumes"` + IsNeedRaid string `json:"isNeedRaid"` +} +type Volume struct { + + // disk type + DiskType string `json:"diskType"` + + // interface type + InterfaceType string `json:"interfaceType"` + + // raid + Raid string `json:"raid"` + + // raid can + RaidCan string `json:"raidCan"` + + // raid Id + RaidID string `json:"raidId"` + + // volume amount + VolumeAmount int64 `json:"volumeAmount"` + + // volume ID + VolumeID string `json:"volumeId"` + + // volume name + VolumeName string `json:"volumeName"` + + // volume size + VolumeSize string `json:"volumeSize"` + + // volume type + VolumeType string `json:"volumeType"` + + // volume unit + VolumeUnit string `json:"volumeUnit"` +} +type DeviceTypePage struct { + DeviceTypes []DeviceType `json:"deviceTypes"` + PagingResponse +} + +type DeviceTypeInfo struct { + DeviceType *DeviceType `json:"deviceType"` +} + +type CreateDeviceTypeResult struct { + DeviceTypeId string `json:"deviceTypeId"` +} + +func (d DeviceType) MarshalJSON() ([]byte, error) { + type Alias DeviceType + return json.Marshal(struct { + Alias + //CreateTime string `json:"create_time"` + //UpdateTime string `json:"update_time"` + }{ + Alias: Alias(d), + //CreateTime: d.CreateTime.Format("2006-01-02 15:04:05"), + //UpdateTime: d.UpdateTime.Format("2006-01-02 15:04:05"), + }) +} + +type AvailableDeviceType struct { + Computer []DeviceTypeReinstall `json:"computer,omitempty"` + Storage []DeviceTypeReinstall `json:"storage,omitempty"` + Gpu []DeviceTypeReinstall `json:"gpu,omitempty"` + Other []DeviceTypeReinstall `json:"other,omitempty"` +} + +type DeviceTypeReinstall struct { + Name string `json:"name"` + DeviceTypeId string `json:"deviceTypeId"` + Cpu string `json:"cpu"` + Mem string `json:"mem"` + System string `json:"system"` + Data string `json:"data"` + Nic string `json:"nic"` + Gpu string `json:"gpu"` + // IsStockAvailable 是否有库存 + AvailableStock int64 `json:"availableStock"` + DeviceSeries string `json:"deviceSeries"` + DeviceSeriesName string `json:"deviceSeriesName"` + //boot模式 + BootMode string `json:"boot_mode"` +} diff --git a/bmp-operation-api/types/response/FilterResponse.go b/bmp-operation-api/types/response/FilterResponse.go new file mode 100644 index 0000000..4bbfbab --- /dev/null +++ b/bmp-operation-api/types/response/FilterResponse.go @@ -0,0 +1,8 @@ +package response + +type FilterResponse struct { + Azs map[string]string `json:"azs"` + DeviceTypes map[string]string `json:"deviceTypes"` + InterfaceModes map[string]string `json:"interfaceModes"` + Status map[string]string `json:"status"` +} diff --git a/bmp-operation-api/types/response/IdcResponse.go b/bmp-operation-api/types/response/IdcResponse.go new file mode 100644 index 0000000..cd262cf --- /dev/null +++ b/bmp-operation-api/types/response/IdcResponse.go @@ -0,0 +1,82 @@ +package response + +import "encoding/json" + +type Idc struct { + // address + Address string `json:"address"` + + // create time + CreateTime string `json:"createTime"` + + // created by + CreatedBy string `json:"createdBy"` + + // ID + ID int64 `json:"id"` + + // i dc ID + IDcID string `json:"idcId"` + + // ilo password + IloPassword string `json:"iloPassword"` + + // ilo user + IloUser string `json:"iloUser"` + + // level + Level string `json:"level"` + + // name + Name string `json:"name"` + + // name en + NameEn string `json:"nameEn"` + + // shortname + Shortname string `json:"shortname"` + + // switch password1 + SwitchPassword1 string `json:"switchPassword1"` + + // switch password2 + SwitchPassword2 string `json:"switchPassword2"` + + // switch user1 + SwitchUser1 string `json:"switchUser1"` + + // switch user2 + SwitchUser2 string `json:"switchUser2"` + + // update time + UpdateTime string `json:"updateTime"` + + // updated by + UpdatedBy string `json:"updatedBy"` +} + +type IdcPage struct { + Idcs []Idc `json:"idcs"` + PagingResponse +} + +type IdcInfo struct { + Idc *Idc `json:"idc"` +} + +type CreateIdcResult struct { + IdcId string `json:"idcId"` +} + +func (d Idc) MarshalJSON() ([]byte, error) { + type Alias Idc + return json.Marshal(struct { + Alias + //CreateTime string `json:"create_time"` + //UpdateTime string `json:"update_time"` + }{ + Alias: Alias(d), + //CreateTime: d.CreateTime.Format("2006-01-02 15:04:05"), + //UpdateTime: d.UpdateTime.Format("2006-01-02 15:04:05"), + }) +} diff --git a/bmp-operation-api/types/response/Image.go b/bmp-operation-api/types/response/Image.go new file mode 100644 index 0000000..115b313 --- /dev/null +++ b/bmp-operation-api/types/response/Image.go @@ -0,0 +1,58 @@ +package response + +type Image struct { + ID uint64 `json:"-"` // ID + ImageID string `json:"imageId"` // 镜像uuid + ImageName string `json:"imageName"` // 镜像名称 + OsID string `json:"osId"` // OSID + Format string `json:"format"` // 镜像格式(qcow2、tar) + //boot模式 + BootMode string `json:"bootMode"` + Filename string `json:"filename"` // 镜像文件名称 + URL string `json:"url"` // 镜像源路径 + Hash string `json:"hash"` // 镜像校验码 + Source string `json:"source"` // 镜像来源(common通用、customize定制、user_defined自定义) + SourceName string `json:"sourceName"` // 镜像来源(common通用、customize定制、user_defined自定义) + Description string `json:"description"` // 描述 + SystemPartition string `json:"systemPartition"` // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + DataPartition string `json:"dataPartition"` // 数据分区信息 + CreatedBy string `json:"createdBy"` // 创建者 + UpdatedBy string `json:"updatedBy"` // 更新者 + CreatedTime string `json:"createdTime"` // 创建时间戳 + UpdatedTime string `json:"updatedTime"` // 更新时间戳 + //DeletedTime int `json:"deletedTime"` // 删除时间戳 + //IsDel int8 `json:"isDel"` // 是否删除0未删除 1已删除 + //Platform string `json:"platform"` // suse/centos/ubuntu + Architecture string `json:"architecture"` // 架构:x86/x64/i386/ + OsType string `json:"osType"` // 操作系统分类:linux/windows + OsVersion string `json:"osVersion"` // 操作系统版本 + DeviceTypeNum int `json:"deviceTypeNum"` + IsBind bool `json:"isBind"` + //Os OS `json:"os"` +} +type ImageList struct { + Images []Image `json:"images"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type ImageInfo struct { + Image *Image `json:"image"` +} +type ImageId struct { + ImageId string `json:"imageId"` +} +type ImageUpload struct { + Format string `json:"format"` + FileName string `json:"fileName"` + Url string `json:"url"` + Hash string `json:"hash"` +} +type Partition struct { + //format,如[swap, xfs] + FsType string `json:"format"` + //point,如[swap, /, /var] + MountPoint string `json:"point"` + // 分区大小, MB为单位 + Size int `json:"size"` +} diff --git a/bmp-operation-api/types/response/Instance.go b/bmp-operation-api/types/response/Instance.go new file mode 100644 index 0000000..afb4a5b --- /dev/null +++ b/bmp-operation-api/types/response/Instance.go @@ -0,0 +1,30 @@ +package response + +import ( + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +type InstancesResponse struct { + PagingResponse + Instances []Instance `json:"instances"` +} + +//详情使用 +type InstanceInfo struct { + Instance Instance `json:"instance"` +} + +type CreateInstanceResponse struct { + InstanceIDs []string `json:"instanceIds"` +} + +//列表 +type Instance struct { + sdkModels.Instance + CpuInfo string `json:"cpuInfo"` + MemInfo string `json:"memInfo"` + SystemInfo string `json:"systemInfo"` + DataInfo string `json:"dataInfo"` + NicInfo string `json:"nicInfo"` + GpuInfo string `json:"gpuInfo"` +} diff --git a/bmp-operation-api/types/response/KeypairResponse.go b/bmp-operation-api/types/response/KeypairResponse.go new file mode 100644 index 0000000..c94c902 --- /dev/null +++ b/bmp-operation-api/types/response/KeypairResponse.go @@ -0,0 +1,18 @@ +package response + +type KeyPairsResponse struct { + PagingResponse + Keypairs []KeyPair `json:"keypairs"` +} + +//给列表用的 +type KeyPair struct { + KeypairId string `json:"keypairId"` + Name string `json:"name"` + IsCheckDelete string `json:"isCheckDelete"` + PublicKey string `json:"publicKey"` + PrivateKey string `json:"privateKey"` + FingerPrint string `json:"fingerPrint"` + CreatedTime string `json:"createdTime"` + UpdatedTime string `json:"updatedTime"` +} diff --git a/bmp-operation-api/types/response/Message.go b/bmp-operation-api/types/response/Message.go new file mode 100644 index 0000000..79330cb --- /dev/null +++ b/bmp-operation-api/types/response/Message.go @@ -0,0 +1,25 @@ +package response + +import sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + +type MessageList struct { + Messages []*sdkModels.Message `json:"messages"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} + +type MessageStatistic struct { + TotalCount int64 `json:"totalCount"` + UnreadCount int64 `json:"unreadCount"` +} + +type HasUnreadMessage struct { + HasUnread bool `json:"hasUnread"` +} + +type MessageWithNextPrev struct { + Message *sdkModels.Message `json:"message"` + NextMessageId string `json:"nextMessageId"` + PrevMessageId string `json:"prevMessageId"` +} diff --git a/bmp-operation-api/types/response/Os.go b/bmp-operation-api/types/response/Os.go new file mode 100644 index 0000000..f996256 --- /dev/null +++ b/bmp-operation-api/types/response/Os.go @@ -0,0 +1,32 @@ +package response + +type Os struct { + ID uint64 `json:"id"` // ID + OsID string `json:"osId"` // 操作系统uuid + OsName string `json:"osName"` // 操作系统名称 + OsType string `json:"osType"` // 操作系统分类:linux/windows + + Architecture string `json:"architecture"` // 架构:x86/x64/i386/ + Bits int `json:"bits"` // 指令宽度:64/32位 + OsVersion string `json:"osVersion"` // 操作系统版本 + SysUser string `json:"sysUser"` // 管理员账户 + CreatedBy string `json:"createdBy"` // 创建者 + UpdatedBy string `json:"updatedBy"` // 更新者 + CreatedTime string `json:"createdTime"` // 创建时间戳 + UpdatedTime string `json:"updatedTime"` // 更新时间戳 + DeletedTime string `json:"deletedTime"` // 删除时间戳 + IsDel int8 `json:"isDel"` // 是否删除0未删除 1已删除 +} + +type OsList struct { + Oss []*Os `json:"oss"` + //PageNumber int64 `json:"pageNumber"` + //PageSize int64 `json:"pageSize"` + //TotalCount int64 `json:"totalCount"` +} +type OsInfo struct { + Os *Os `json:"os"` +} +type OsId struct { + OsId string `json:"osId"` +} diff --git a/bmp-operation-api/types/response/PagingResponse.go b/bmp-operation-api/types/response/PagingResponse.go new file mode 100644 index 0000000..00ff93c --- /dev/null +++ b/bmp-operation-api/types/response/PagingResponse.go @@ -0,0 +1,9 @@ +package response + +type PagingResponse struct { + PageNumber int64 `json:"pageNumber"` + + PageSize int64 `json:"pageSize"` + + TotalCount int64 `json:"totalCount"` +} diff --git a/bmp-operation-api/types/response/Raid.go b/bmp-operation-api/types/response/Raid.go new file mode 100644 index 0000000..5df4787 --- /dev/null +++ b/bmp-operation-api/types/response/Raid.go @@ -0,0 +1,35 @@ +package response + +import ( + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +type Raid struct { + RaidID string `json:"raidId"` + Name string `json:"name"` + //DeviceTypeId string `json:"deviceTypeId"` //设备类型 + //VolumeType string `json:"volumeType"` //磁盘类型 + //VolumeDetail string `json:"volumeDetail"` //磁盘详细信息 + DescriptionEn string `json:"descriptionEn"` + DescriptionZh string `json:"descriptionZh"` + //SystemPartitionCount int `json:"systemPartitionCount"` + //AvailableValue int `json:"availableValue"` // 可用分区值,单位GB + //DiskType string `json:"diskType"` // 磁盘类型:SAS/SATA/SSD/NVME +} +type RaidList struct { + Raids []*Raid `json:"raids"` + //PageNumber int64 `json:"pageNumber"` + //PageSize int64 `json:"pageSize"` + //TotalCount int64 `json:"totalCount"` +} +type RaidInfo struct { + Raid *Raid `json:"raid"` +} +type RaidId struct { + RaidId string `json:"raidId"` +} + +type DeviceTypeRaid struct { + sdkModels.RDeviceTypeRaid + RaidName string `json:"raidName"` +} diff --git a/bmp-operation-api/types/response/RegionsResponse.go b/bmp-operation-api/types/response/RegionsResponse.go new file mode 100644 index 0000000..68bf3dd --- /dev/null +++ b/bmp-operation-api/types/response/RegionsResponse.go @@ -0,0 +1,16 @@ +package response + +type RegionsResponse struct { + Regions []Region `json:"regions"` +} +type Region struct { + Region string `json:"region"` + RegionName string `json:"regionName"` + EnableIpv6 string `json:"enableIpv6"` + Azs []Az `json:"azs"` +} +type Az struct { + Region string `json:"region"` + Az string `json:"az"` + AzName string `json:"azName"` +} diff --git a/bmp-operation-api/types/response/RoleResponse.go b/bmp-operation-api/types/response/RoleResponse.go new file mode 100644 index 0000000..fd48c42 --- /dev/null +++ b/bmp-operation-api/types/response/RoleResponse.go @@ -0,0 +1,29 @@ +package response + +type Role struct { + ID int `json:"-"` + RoleID string `json:"roleId"` // 角色uuid + RoleNameEn string `json:"roleNameEn"` // 角色名称,唯一 + RoleNameCn string `json:"roleNameCn"` // 角色名称,唯一 + DescriptionEn string `json:"descriptionEn"` // 权限描述 + DescriptionCn string `json:"descriptionCn"` // 权限描述 + RoleName string `json:"roleName"` + Permission string `json:"permission"` + UserCount int `json:"userCount"` + CreatedBy string `json:"createdBy"` // 创建者 + UpdatedBy string `json:"updatedBy"` // 更新者 + CreatedTime string `json:"createdTime"` // 创建时间戳 + UpdatedTime string `json:"updatedTime"` // 更新时间戳 +} +type RoleList struct { + Roles []*Role `json:"roles"` + PageNumber int64 `json:"pageNumber"` + PageSize int64 `json:"pageSize"` + TotalCount int64 `json:"totalCount"` +} +type RoleInfo struct { + Role *Role `json:"role"` +} +type RoleId struct { + RoleId string `json:"roleId"` +} diff --git a/bmp-operation-api/types/response/TagsResponse.go b/bmp-operation-api/types/response/TagsResponse.go new file mode 100644 index 0000000..dc1084e --- /dev/null +++ b/bmp-operation-api/types/response/TagsResponse.go @@ -0,0 +1,3 @@ +package response + +type TagsResponse []string diff --git a/bmp-operation-api/types/response/TimezoneResponse.go b/bmp-operation-api/types/response/TimezoneResponse.go new file mode 100644 index 0000000..b313775 --- /dev/null +++ b/bmp-operation-api/types/response/TimezoneResponse.go @@ -0,0 +1,31 @@ +package response + +import "bytes" + +type GetTimezoneListResponse struct { + TimeZones OrderedJsonDict `json:"timezones"` +} + +type OrderedJsonDict struct { + M map[string]string + Keys []string +} + +func (o OrderedJsonDict) MarshalJSON() ([]byte, error) { + buf := &bytes.Buffer{} + buf.WriteByte('{') + for i, k := range o.Keys { + if i != 0 { + buf.WriteByte(',') + } + buf.WriteByte('"') + buf.WriteString(k) + buf.WriteByte('"') + buf.WriteByte(':') + buf.WriteByte('"') + buf.Write([]byte(o.M[k])) + buf.WriteByte('"') + } + buf.WriteByte('}') + return buf.Bytes(), nil +} diff --git a/bmp-operation-api/types/response/UserResponse.go b/bmp-operation-api/types/response/UserResponse.go new file mode 100644 index 0000000..a6809fb --- /dev/null +++ b/bmp-operation-api/types/response/UserResponse.go @@ -0,0 +1,62 @@ +package response + +import "time" + +type UserPage struct { + Users []User `json:"users"` + PagingResponse +} + +type User struct { + ID int64 `json:"id"` + UserID string `json:"userId"` // 用户uuid + RoleID string `json:"roleId"` // 角色uuid + RoleName string `json:"roleName"` // 角色名称 + UserName string `json:"userName"` // 用户名,唯一 + Email string `json:"email"` // 邮箱 + PhonePrefix string `json:"phonePrefix"` // 国家地区码,如86 + PhoneNumber string `json:"phoneNumber"` // 手机号 + DefaultProjectID string `json:"defaultProjectId"` // 所属项目uuid + DefaultProjectName string `json:"DefaultProjectName"` // 默认所属项目名称 + ProjectCount int `json:"projectCount"` //用户拥有的项目数 + InstanceCount int `json:"instanceCount"` //用户拥有的实例数 + Language string `json:"language"` // 语言(中文/English) + Timezone time.Time `gorm:"column:timezone" json:"timezone"` // UTC或者本时区时间 + Password string `json:"password"` // 密码,sha256非对称加密后存储 + Description string `json:"description"` // 描述 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime string `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime string `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + //DeletedTime string `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + //IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +type UserAdd struct { + UserID string `json:"userId"` // 用户uuid +} + +type LocalUser struct { + ID int64 `json:"id"` + UserID string `json:"userId"` // 用户uuid + RoleID string `json:"roleId"` // 角色uuid + RoleName string `json:"roleName"` // 角色名称 + UserName string `json:"userName"` // 用户名,唯一 + Email string `json:"email"` // 邮箱 + PhonePrefix string `json:"phonePrefix"` // 国家地区码,如86 + PhoneNumber string `json:"phoneNumber"` // 手机号 + DefaultProjectID string `json:"defaultProjectId"` // 所属项目uuid + DefaultProjectName string `json:"DefaultProjectName"` // 默认所属项目名称 + Language string `json:"language"` // 语言(中文/English) + Timezone string `gorm:"column:timezone" json:"timezone"` // UTC或者本时区时间 + Password string `json:"password"` // 密码,sha256非对称加密后存储 + Description string `json:"description"` // 描述 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime string `gorm:"column:createdTime" json:"createdTime"` // 创建时间戳 + UpdatedTime string `gorm:"column:updatedTime" json:"updatedTime"` // 更新时间戳 + //DeletedTime string `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + //IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 + LicenseExist bool `json:"licenseExist"` //系统是否做过授权 + LicenseModels []string `json:"licenseModels"` //授权过的模块 +} diff --git a/bmp-operation-api/types/types.go b/bmp-operation-api/types/types.go new file mode 100644 index 0000000..22187b6 --- /dev/null +++ b/bmp-operation-api/types/types.go @@ -0,0 +1,28 @@ +package types + +import "time" + +const TimeFormat = "2006-01-02 15:04:05" + +type LocalTime time.Time + +func (t *LocalTime) UnmarshalJSON(data []byte) (err error) { + // 空值不进行解析 + if len(data) == 2 { + *t = LocalTime(time.Time{}) + return + } + + // 指定解析的格式 + now, err := time.Parse(`"`+TimeFormat+`"`, string(data)) + *t = LocalTime(now) + return +} + +func (t LocalTime) MarshalJSON() ([]byte, error) { + b := make([]byte, 0, len(TimeFormat)+2) + b = append(b, '"') + b = time.Time(t).AppendFormat(b, TimeFormat) + b = append(b, '"') + return b, nil +} diff --git a/bmp-operation-api/util/array.go b/bmp-operation-api/util/array.go new file mode 100644 index 0000000..5c7a5e0 --- /dev/null +++ b/bmp-operation-api/util/array.go @@ -0,0 +1,109 @@ +package util + +import ( + "reflect" +) + +func GetValuesByField(objs []interface{}, field string) []string { + res := []string{} + for _, obj := range objs { + r := reflect.ValueOf(obj) + if reflect.TypeOf(obj).Kind() == reflect.Ptr { + r = reflect.Indirect(r) + } + f := r.FieldByName(field).String() + res = append(res, f) + } + return res +} + +func InArrayWithIndex(val interface{}, array interface{}) (exists bool, index int) { + exists = false + index = -1 + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + index = i + exists = true + return + } + } + } + return +} + +func InArray(val interface{}, array interface{}) (exists bool) { + exists = false + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + exists = true + return + } + } + } + return +} +func InArrayString(str string, arr []string) bool { + for _, v := range arr { + if v == str && str != "" { + return true + } + } + return false +} + +//求并集 +func UnionArray(slice1, slice2 []string) []string { + m := make(map[string]int) + for _, v := range slice1 { + m[v]++ + } + + for _, v := range slice2 { + times, _ := m[v] + if times == 0 { + slice1 = append(slice1, v) + } + } + return slice1 +} + +//求交集 +func IntersectArray(slice1, slice2 []string) []string { + m := make(map[string]int) + nn := make([]string, 0) + for _, v := range slice1 { + m[v]++ + } + + for _, v := range slice2 { + times, _ := m[v] + if times == 1 { + nn = append(nn, v) + } + } + return nn +} + +//求差集 slice1-并集 +func DifferenceArray(slice1, slice2 []string) []string { + m := make(map[string]int) + nn := make([]string, 0) + inter := IntersectArray(slice1, slice2) + for _, v := range inter { + m[v]++ + } + + for _, value := range slice1 { + times, _ := m[value] + if times == 0 { + nn = append(nn, value) + } + } + return nn +} diff --git a/bmp-operation-api/util/array_test.go b/bmp-operation-api/util/array_test.go new file mode 100644 index 0000000..68dc442 --- /dev/null +++ b/bmp-operation-api/util/array_test.go @@ -0,0 +1,14 @@ +package util + +import( + "testing" +) + +func TestInArray(t *testing.T){ + v := InArray("aaa", []string{"aaa", "bbb"}) + if !v{ + t.Fatal("not in array") + }else{ + t.Log("in array") + } +} diff --git a/bmp-operation-api/util/bool.go b/bmp-operation-api/util/bool.go new file mode 100644 index 0000000..39da658 --- /dev/null +++ b/bmp-operation-api/util/bool.go @@ -0,0 +1,12 @@ +package util + +func Bool2Int8(b bool) int8 { + if b { + return 1 + } + return 0 +} + +func Int82Bool(i int8) bool { + return i > 0 +} diff --git a/bmp-operation-api/util/common.go b/bmp-operation-api/util/common.go new file mode 100644 index 0000000..1848d45 --- /dev/null +++ b/bmp-operation-api/util/common.go @@ -0,0 +1,262 @@ +package util + +import ( + "encoding/json" + "fmt" + "math/rand" + "os" + "reflect" + "regexp" + "strconv" + "strings" + "time" + "unsafe" + + "github.com/gofrs/uuid" +) + +const FormatTime = "2006-01-02 15:04:05" + +func GenUuid() string { + return uuid.Must(uuid.NewV4()).String() +} + +/** +map或者stuct转化为json字符串 +*/ +func ObjToJsonString(obj interface{}) string { + return MapToJson(InterfaceToMap(obj)) +} + +//任意类型转化成json,最常用 +func InterfaceToJson(obj interface{}) string { + dataType, err := json.Marshal(obj) + if err != nil { + return "" + } + dataString := string(dataType) + return dataString +} + +/** +Map对象转化为json string +*/ +func MapToJson(param map[string]interface{}) string { + dataType, _ := json.Marshal(param) + dataString := string(dataType) + return dataString +} +func InterfaceToMap(obj interface{}) map[string]interface{} { + + var data = make(map[string]interface{}) + if reflect.TypeOf(obj).Kind().String() == "map" { + d := obj.(map[string]interface{}) + for k, v := range d { + if vv := ReflectValue2string(reflect.ValueOf(v)); vv != "" { + data[k] = vv + } + } + } else if reflect.TypeOf(obj).Kind().String() == "struct" { + obj1 := reflect.TypeOf(obj) + obj2 := reflect.ValueOf(obj) + for i := 0; i < obj1.NumField(); i++ { + if vv := ReflectValue2string(obj2.Field(i)); vv != "" { + tagname := obj1.Field(i).Tag.Get("json") + if tagname != "" { + data[tagname] = vv + } else { + data[obj1.Field(i).Name] = vv + } + } + } + } else { + fmt.Printf("unknown obj, type is :%s, value is:%v\n", reflect.TypeOf(obj).String(), obj) + } + return data + +} + +//ReflectValue2string 默认值都设置为"",可能会误伤,后面改的方案:1,定义成wrapper类型,2,和上下游约定字段取值不要用默认值,比如int类型取值不要出现0,bool类型不要出现false +func ReflectValue2string(obj reflect.Value) string { + var v string + switch obj.Type().Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if vv := strconv.FormatInt(obj.Int(), 10); vv != "0" { //默认值问题 + v = vv + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + if vv := strconv.FormatUint(obj.Uint(), 10); vv != "0" { //默认值问题 + v = vv + } + case reflect.Float32, reflect.Float64: + if vv := fmt.Sprintf("%f", obj.Float()); vv != "0" { //默认值问题 + v = vv + } + case reflect.String: + v = obj.String() + case reflect.Bool: + if vv := strconv.FormatBool(obj.Bool()); vv != "false" { + v = vv + } + default: + v = "" + } + return v +} + +//将下划线转为驼峰 name_en => nameEn 一维,二维均可 +func DbToObj(obj map[string]interface{}) map[string]interface{} { + mapObj := make(map[string]interface{}) + for kk, vv := range obj { + if reflect.TypeOf(vv).Kind().String() == "slice" { + //fmt.Println(vv) + //sliceArr := []interface{} + for k1, v1 := range vv.([]interface{}) { + //fmt.Println(k1,v1) + mapObj1 := make(map[string]interface{}) + for k, v := range v1.(map[string]interface{}) { + sepStr := strings.Join(strings.Split(k, "_"), " ") + arr := strings.Split(strings.Title(sepStr), " ") + arr[0] = strings.ToLower(arr[0]) //hello World Haha + mapObj1[strings.Join(arr, "")] = v + } + vv.([]interface{})[k1] = mapObj1 + } + //fmt.Println(vv) + mapObj[kk] = vv + } else { + sepStr := strings.Join(strings.Split(kk, "_"), " ") + arr := strings.Split(strings.Title(sepStr), " ") + arr[0] = strings.ToLower(arr[0]) + mapObj[strings.Join(arr, "")] = vv + } + } + return mapObj +} + +//将一维map的驼峰 key转化为下划线 +func ObjToDb(param map[string]interface{}) map[string]interface{} { + //str := "userNameTom" //转为user_name_tom + //解析正则表达式,如果成功返回解释器 + reg := regexp.MustCompile(`[A-Z]`) + if reg == nil { //解释失败,返回nil + //fmt.Println("regexp err") + return nil + } + res := make(map[string]interface{}) + for key, value := range param { + //根据规则提取关键信息 + result := reg.FindAllStringSubmatch(key, -1) + for _, v := range result { + //fmt.Println(v) + key = strings.Replace(key, v[0], "_"+strings.ToLower(v[0]), 1) + } + res[key] = value + } + //fmt.Println("result1 = ", result,str) + return res +} + +func Int64ToInt(num int64) int { + int64_num := int64(num) + // 将 int64 转化为 int + int_num := *(*int)(unsafe.Pointer(&int64_num)) + return int_num +} +func UtcToTime(utc string) string { //2022-02-18T06:01:32Z 这个时间转为东八区 为2022-02-18 14:01:32 + return utc + if utc == "" { + return "" + } + if !strings.Contains(utc, "T") { + return utc + } + ctime, _ := time.ParseInLocation("2006-01-02T15:04:05Z", utc, time.UTC) //如果utc是带有TZ的,说明是UTC时间,先转成UTC时间 + return ctime.Local().Format(FormatTime) +} + +//生成8-30位随机密码 +func GenerateRandPassWord() string { + a := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"} + b := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"} + d := "0123456789()`~!@#$%&*_-+=|{}[]:\";'<>,.?/" + c := strings.Split(d, "") + rand.Seed(time.Now().UnixNano()) + x := rand.Intn(len(a)) //生成0-数组长度之间的随机整数 + y := rand.Intn(len(b)) //生成0-数组长度之间的随机整数 + z := rand.Intn(len(c)) //生成0-数组长度之间的随机整数 + //fmt.Println(c) + s := make([]string, 0) + s = append(s, a[x]) + s = append(s, b[y]) + s = append(s, c[z]) + //以上生成了3个固定长度的字符串,这是必须要有的3个 + var arr = append(append(a, b...), c...) + + for i := 1; i <= 5; i++ { + rand := rand.Intn(len(arr)) //生成0-数组长度之间的随机整数 + s = append(s, arr[rand]) + } + //以上组成了至少8位的一个随机字符,下面生成9-30之间的随机长度的字符串 + length := rand.Intn(23) //生成0-22之间的数,前闭区间,后开区间,跟前面的8位拼接,组成8-30之间的随机数 + if length != 0 { + for i := 1; i <= length; i++ { + rand := rand.Intn(len(arr)) //生成0-数组长度之间的随机整数 + s = append(s, arr[rand]) + } + } + str := "" //下面将最终的数组打乱,生成新的字符串 + for i := 0; i < len(s); i++ { + rand := rand.Intn(len(s)) + str += s[rand] + } + return str +} + +/** +判断文件是否存在 +*/ +func CreateDirIfNotExist(fileAddr string) bool { + s, err := os.Stat(fileAddr) + if err != nil { + return CreateDir(fileAddr) + } + return s.IsDir() +} + +/** +创建文件夹 +*/ +func CreateDir(dirName string) bool { + err := os.Mkdir(dirName, 0777) + if err != nil { + return false + } + return true +} + +/** +时间戳根据timezone解析成时间字符串 +*/ +func TimestampToString(timestamp int64, timezone string) string { + if timestamp == 0 { + return "" + } + t := time.Unix(timestamp, 0) + local, err := time.LoadLocation(timezone) + if err != nil { + fmt.Println("timezone error:", timezone, err.Error()) + return "" + } + ts := t.In(local).String() + fmt.Println(timestamp, timezone, ts) + tsItems := strings.Split(ts, " ") + if len(tsItems) >= 2 { + ts = tsItems[0] + " " + tsItems[1] + } + return ts + //if timestamp == 0 { + // return "" + //} + //return time.Unix(timestamp, 0).UTC().Format(baseLogic.DATE_UTC_FORMAT) +} diff --git a/bmp-operation-api/util/coverage.out b/bmp-operation-api/util/coverage.out new file mode 100644 index 0000000..a333b69 --- /dev/null +++ b/bmp-operation-api/util/coverage.out @@ -0,0 +1,155 @@ +mode: set +git.jd.com/cps-golang/ironic-api/util/ipv4.go:43.58,45.21 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:48.2,50.62 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:64.2,64.43 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:45.21,47.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:50.62,52.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:52.8,55.17 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:58.3,58.30 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:55.17,57.4 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:58.30,60.4 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:60.9,60.38 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:60.38,62.4 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:67.75,68.70 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:71.2,80.8 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:68.70,70.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:83.42,85.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:87.40,90.26 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:93.2,93.16 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:90.26,92.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:96.40,98.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:100.40,102.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:104.48,107.30 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:111.2,111.12 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:107.30,110.3 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:114.50,117.28 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:121.2,121.18 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:117.28,120.3 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:124.53,126.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:128.49,130.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:132.53,134.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:136.76,137.18 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:140.2,141.29 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:144.2,148.28 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:156.2,156.21 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:137.18,139.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:141.29,143.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:148.28,149.35 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:152.3,154.50 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:149.35,151.4 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:160.32,165.2 4 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:167.44,170.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:172.43,174.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:176.40,179.2 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:181.41,184.2 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:186.43,187.20 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:190.2,191.18 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:194.2,195.19 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:202.2,202.27 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:187.20,189.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:191.18,193.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:195.19,196.25 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:199.3,200.25 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:196.25,197.9 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:206.44,207.21 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:210.2,211.18 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:214.2,215.19 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:222.2,222.16 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:207.21,209.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:211.18,213.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:215.19,216.25 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:219.3,220.25 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:216.25,217.9 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:225.55,227.40 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:235.2,235.24 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:228.22,229.37 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:230.21,231.22 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:232.10,233.36 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:238.48,240.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:242.41,245.22 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:248.2,249.29 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:257.2,257.77 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:245.22,246.102 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:249.29,250.59 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:250.59,251.103 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:252.9,254.4 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:30.61,54.2 14 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:57.30,60.2 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:63.57,64.16 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:64.16,66.44 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:72.52,76.2 3 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:79.50,95.16 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:98.2,111.3 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:95.16,97.3 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:115.36,132.16 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:137.2,152.16 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:156.2,158.12 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:165.2,166.11 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:132.16,134.3 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:152.16,154.3 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:158.12,159.23 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:159.23,163.4 1 0 +git.jd.com/cps-golang/ironic-api/util/page.go:9.65,11.23 2 0 +git.jd.com/cps-golang/ironic-api/util/page.go:16.2,16.22 1 0 +git.jd.com/cps-golang/ironic-api/util/page.go:11.23,13.3 1 0 +git.jd.com/cps-golang/ironic-api/util/page.go:13.8,15.3 1 0 +git.jd.com/cps-golang/ironic-api/util/page.go:19.59,26.2 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:16.69,18.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:21.2,21.41 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:18.16,20.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:25.55,30.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:32.61,34.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:37.2,40.9 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:34.16,36.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:44.58,46.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:49.2,49.49 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:46.16,48.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:52.47,55.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:59.2,60.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:65.2,65.57 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:55.16,57.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:60.16,62.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:68.56,70.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:74.2,74.42 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:70.16,72.3 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:7.66,9.27 2 0 +git.jd.com/cps-golang/ironic-api/util/array.go:17.2,17.12 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:9.27,11.48 2 0 +git.jd.com/cps-golang/ironic-api/util/array.go:14.3,15.23 2 0 +git.jd.com/cps-golang/ironic-api/util/array.go:11.48,13.4 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:20.84,23.38 3 0 +git.jd.com/cps-golang/ironic-api/util/array.go:34.2,34.8 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:24.21,26.32 2 0 +git.jd.com/cps-golang/ironic-api/util/array.go:26.32,27.62 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:27.62,31.5 3 0 +git.jd.com/cps-golang/ironic-api/util/array.go:37.64,39.38 2 1 +git.jd.com/cps-golang/ironic-api/util/array.go:49.2,49.8 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:40.21,42.32 2 1 +git.jd.com/cps-golang/ironic-api/util/array.go:42.32,43.62 1 1 +git.jd.com/cps-golang/ironic-api/util/array.go:43.62,46.5 2 1 +git.jd.com/cps-golang/ironic-api/util/bool.go:3.29,4.7 1 0 +git.jd.com/cps-golang/ironic-api/util/bool.go:7.2,7.10 1 0 +git.jd.com/cps-golang/ironic-api/util/bool.go:4.7,6.3 1 0 +git.jd.com/cps-golang/ironic-api/util/bool.go:10.29,12.2 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:10.89,13.16 2 0 +git.jd.com/cps-golang/ironic-api/util/http.go:16.2,18.16 3 0 +git.jd.com/cps-golang/ironic-api/util/http.go:21.2,23.27 2 0 +git.jd.com/cps-golang/ironic-api/util/http.go:26.2,28.16 3 0 +git.jd.com/cps-golang/ironic-api/util/http.go:31.2,32.16 2 0 +git.jd.com/cps-golang/ironic-api/util/http.go:35.2,35.23 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:13.16,15.3 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:18.16,20.3 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:23.27,25.3 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:28.16,30.3 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:32.16,34.3 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:4.83,6.25 2 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:24.2,24.15 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:6.25,7.12 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:7.12,9.4 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:9.9,11.4 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:13.8,13.32 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:13.32,15.42 2 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:18.3,18.12 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:15.42,17.4 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:18.12,20.4 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:20.9,22.4 1 0 diff --git a/bmp-operation-api/util/encrypt.go b/bmp-operation-api/util/encrypt.go new file mode 100644 index 0000000..96c2314 --- /dev/null +++ b/bmp-operation-api/util/encrypt.go @@ -0,0 +1,109 @@ +package util + +import ( + "bufio" + "bytes" + "crypto/aes" + "crypto/cipher" + "crypto/md5" + "crypto/sha512" + "encoding/base64" + "encoding/hex" + "fmt" + "io" + "os" + "time" +) + +const ( + AES_KEY = "ABCDEFGHIJKLMNOP" + AES_IV = "0123456789ABCDEF" +) + +func GetMd5(str string, salts ...string) string { + h := md5.New() + h.Write([]byte(str)) + if len(salts) == 0 { + return hex.EncodeToString(h.Sum(nil)) + } else { + for _, salt := range salts { + h.Write([]byte(salt)) + } + return hex.EncodeToString(h.Sum(nil)) + } +} + +func Base64Encrypt(str []byte) string { + return base64.StdEncoding.EncodeToString(str) +} + +func Base64Decrypt(data string) ([]byte, error) { + return base64.StdEncoding.DecodeString(data) +} + +func GetSha512(str string) string { + return fmt.Sprintf("%x", sha512.Sum512([]byte(str))) +} + +//linux下面的MD5sum方法实现,注意,linux下面的文件最后会有一个默认的换行符,用这个命令去掉换行写入文件 echo -n "qq123" > test.txt 然后 md5sum test.txt +func Md5sum(file string) string { + f, err := os.Open(file) + if err != nil { + return "" + } + defer f.Close() + r := bufio.NewReader(f) + + h := md5.New() + + _, err = io.Copy(h, r) + if err != nil { + return "" + } + return fmt.Sprintf("%x", h.Sum(nil)) +} + +func AesEncrypt(data []byte) ([]byte, error) { + aesBlockEncrypt, err := aes.NewCipher([]byte(AES_KEY)) + if err != nil { + println(err.Error()) + return nil, err + } + + content := PKCS7Padding2(data, aesBlockEncrypt.BlockSize()) + cipherBytes := make([]byte, len(content)) + aesEncrypt := cipher.NewCBCEncrypter(aesBlockEncrypt, []byte(AES_IV)) + aesEncrypt.CryptBlocks(cipherBytes, content) + return cipherBytes, nil +} + +func AesDecrypt(src []byte) (data []byte, err error) { + decrypted := make([]byte, len(src)) + var aesBlockDecrypt cipher.Block + aesBlockDecrypt, err = aes.NewCipher([]byte(AES_KEY)) + if err != nil { + println(err.Error()) + return nil, err + } + aesDecrypt := cipher.NewCBCDecrypter(aesBlockDecrypt, []byte(AES_IV)) + aesDecrypt.CryptBlocks(decrypted, src) + return PKCS7UnPadding2(decrypted), nil +} + +//PKCS7Padding 使用PKCS7进行填充 +func PKCS7Padding2(ciphertext []byte, blockSize int) []byte { + padding := blockSize - len(ciphertext)%blockSize + padText := bytes.Repeat([]byte{byte(padding)}, padding) + return append(ciphertext, padText...) +} + +//PKCS7UnPadding 解PKCS7填充 +func PKCS7UnPadding2(origData []byte) []byte { + length := len(origData) + unPadding := int(origData[length-1]) + if length < unPadding { + fmt.Println(time.Now().String(), "PKCS7UnPadding error") + return nil + } + return origData[:(length - unPadding)] +} diff --git a/bmp-operation-api/util/error.go b/bmp-operation-api/util/error.go new file mode 100644 index 0000000..fdfde4b --- /dev/null +++ b/bmp-operation-api/util/error.go @@ -0,0 +1,53 @@ +package util + +import ( + "reflect" + + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + apiRuntime "github.com/go-openapi/runtime" +) + +/* +sdk的原因,写了此GetOpenapiError用来解析openapi的返回err。err如果已知,为具体类型(比如GetUserListDefault)或者APIError类型(多了一层),如果未知解析失败,第二个参数为false + +type GetUserListDefault struct { + _statusCode int + TraceID string + Payload *GetUserListDefaultBody + } + + type GetUserListDefaultBody struct { + + // error + Error *models.ErrorResponse `json:"error,omitempty"` +} + +APIError{ + OperationName: opName, + Response: interface{}(GetUserListDefault), + Code: code, +} + +*/ + +func GetOpenapiError(err error) (*sdkModels.ErrorResponse, bool) { + + var v interface{} + e, ok := err.(*apiRuntime.APIError) + if ok { + v = e.Response + } else { + v = err + } + if reflect.ValueOf(v).MethodByName("GetPayload").IsValid() { + val := reflect.ValueOf(v).MethodByName("GetPayload").Call([]reflect.Value{}) + if reflect.Indirect(val[0]).FieldByName("Error").IsValid() { + err1, ok := reflect.Indirect(val[0]).FieldByName("Error").Interface().(*sdkModels.ErrorResponse) + if ok { + return err1, true + } + } + } + return nil, false + +} diff --git a/bmp-operation-api/util/file.go b/bmp-operation-api/util/file.go new file mode 100644 index 0000000..da4d5cf --- /dev/null +++ b/bmp-operation-api/util/file.go @@ -0,0 +1,51 @@ +package util + +import ( + "bufio" + "io" + "io/ioutil" + "mime/multipart" + "os" + "path/filepath" +) + +//GetBaseDir 获取项目根目录 +func GetBaseDir() (string, error) { + basePath, err := os.Executable() + if err != nil { + return "", err + } + res, err := filepath.EvalSymlinks(filepath.Dir(basePath)) + if err != nil { + return "", err + } + + return res, nil +} + +func SaveToLocal(localFileName string, uploadFile multipart.File) error { + f, err := os.OpenFile(localFileName, os.O_WRONLY|os.O_CREATE, 0666) //|os.O_APPEND + if err != nil { + return err + } + defer f.Close() + buf := bufio.NewWriter(f) + if _, err = io.Copy(f, uploadFile); err != nil { + return err + } + //将文件指针指回文件开头则可重新读取文件 + if _, err = uploadFile.Seek(0, io.SeekStart); err != nil { + return err + } + if err = buf.Flush(); err != nil { + return err + } + return nil +} +func ReadFileContent(filePth string) ([]byte, error) { + f, err := os.Open(filePth) + if err != nil { + return nil, err + } + return ioutil.ReadAll(f) +} diff --git a/bmp-operation-api/util/http.go b/bmp-operation-api/util/http.go new file mode 100644 index 0000000..db54977 --- /dev/null +++ b/bmp-operation-api/util/http.go @@ -0,0 +1,229 @@ +package util + +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "net" + "net/http" + "reflect" + "strings" + "time" + + log "git.jd.com/cps-golang/log" +) + +/* +func DoHttpGet(logger *log.Logger, url string, header map[string]string, data interface{}) ([]byte, error) { + + rpclogger := log.New("./logs/ironic-console-rpc.log") + defer rpclogger.Flush() + defer rpclogger.TimeEnd("cost") + rpclogger.SetStableFields([]string{"url", "method", "cost", "header", "request", "status", "statusCode", "response"}) + + rpclogger.Point("logid", logger.GetPoint("logid")) + rpclogger.Point("url", url) + rpclogger.Point("method", "GET") + rpclogger.Point("header", header) + rpclogger.TimeStart("cost") + + var bytesData []byte + if reflect.TypeOf(data).Kind() == reflect.String { + bytesData = []byte(data.(string)) + } else { + var err error + bytesData, err = json.Marshal(data) + if err != nil { + return nil, err + } + } + rpclogger.Point("request", string(bytesData)) + reader := bytes.NewReader(bytesData) + + request, err := http.NewRequest("GET", url, reader) + if err != nil { + return nil, err + } + q := request.URL.Query() + + param := InterfaceToMap(data) + fmt.Println(data, param) + for key, value := range param { + q.Add(key, value) + } + request.URL.RawQuery = q.Encode() + fmt.Println("get请求的最终url:", request.URL.String()) + defer request.Body.Close() + //务必带 X-Jdcloud-Requestid + for k, v := range header { + //fmt.Println(k,v) + request.Header.Set(k, v) + } + //if header["host"] != "" { + request.Host = header["Host"] + //} + client := http.Client{} + resp, err := client.Do(request) + if err != nil { + return nil, err + } + rpclogger.Point("status", resp.Status) + rpclogger.Point("statusCode", resp.StatusCode) + respBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + fmt.Println("状态码:", resp.Status, resp.StatusCode) + rpclogger.Point("response", string(respBytes)) + return respBytes, nil +} + +func DoHttpPost(logger *log.Logger, url string, header map[string]string, data interface{}) ([]byte, error) { + + rpclogger := log.New("./logs/ironic-console-rpc.log") + defer rpclogger.Flush() + defer rpclogger.TimeEnd("cost") + rpclogger.SetStableFields([]string{"url", "method", "cost", "header", "request", "status", "statusCode", "response"}) + + rpclogger.Point("logid", logger.GetPoint("logid").(string)) + rpclogger.Point("url", url) + rpclogger.Point("method", "POST") + rpclogger.Point("header", header) + rpclogger.TimeStart("cost") + + var bytesData []byte + if reflect.TypeOf(data).Kind() == reflect.String { + bytesData = []byte(data.(string)) + } else { + var err error + bytesData, err = json.Marshal(data) + if err != nil { + return nil, err + } + } + rpclogger.Point("request", string(bytesData)) + reader := bytes.NewReader(bytesData) + request, err := http.NewRequest("POST", url, reader) + if err != nil { + return nil, err + } + defer request.Body.Close() + //务必带 X-Jdcloud-Request-Id + for k, v := range header { + request.Header.Set(k, v) + } + client := http.Client{} + resp, err := client.Do(request) + if err != nil { + return nil, err + } + fmt.Println("状态码:", resp.Status, resp.StatusCode) + rpclogger.Point("status", resp.Status) + rpclogger.Point("statusCode", resp.StatusCode) + //if resp.StatusCode != 200 { + // fmt.Println("ironic-api接口异常") + // return nil,err + //} + respBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + rpclogger.Point("response", string(respBytes)) + return respBytes, nil +} +*/ +func DoHttp(logger *log.Logger, url string, header map[string]string, data interface{}, method string) ([]byte, error) { + + rpclogger := log.New("./log/ironic-console-rpc.log") + defer rpclogger.Flush() + defer rpclogger.TimeEnd("cost") + rpclogger.SetStableFields([]string{"url", "method", "cost", "header", "request", "status", "statusCode", "response"}) + + rpclogger.Point("logid", logger.GetPoint("logid")) + rpclogger.Point("url", url) + rpclogger.Point("method", method) + rpclogger.Point("header", header) + rpclogger.TimeStart("cost") + + var bytesData []byte + if data != nil { + fmt.Println("当前参数类型", reflect.TypeOf(data).Kind()) + if reflect.TypeOf(data).Kind() == reflect.String { + bytesData = []byte(data.(string)) + } else { + var err error + bytesData, err = json.Marshal(data) + if err != nil { + return nil, err + } + } + } + + // byteHeader, _ := json.Marshal(header) + // fmt.Println("请求header", string(byteHeader)) + fmt.Println("ironicapi请求url", url) + fmt.Println("ironicapi请求method", method) + fmt.Println("ironicapi请求body", string(bytesData)) + rpclogger.Point("request", string(bytesData)) + reader := bytes.NewReader(bytesData) + + request, err := http.NewRequest(method, url, reader) + if err != nil { + return nil, err + } + if method == "GET" && data != nil { + param := InterfaceToMap(data) + q := request.URL.Query() + for key, value := range param { + q.Add(key, value.(string)) + } + request.URL.RawQuery = q.Encode() + } + fmt.Println("ironicapi请求url:", request.URL.String()) + defer request.Body.Close() + //务必带 X-Jdcloud-Request-Id + for k, v := range header { + //fmt.Println(k,v) + request.Header.Set(k, v) + } + + fmt.Println("dohttp request header:", request.Header) + + // request.Header.Set("x-jdcloud-erp", "ZXJw") + if header["Host"] != "" { + request.Host = header["Host"] + } + client := http.Client{} + resp, err := client.Do(request) + if err != nil { + return nil, err + } + rpclogger.Point("status", resp.Status) + rpclogger.Point("statusCode", resp.StatusCode) + respBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + // fmt.Println("状态码:", resp.Status, resp.StatusCode) + fmt.Println("ironicapi响应:", string(respBytes)) + rpclogger.Point("response", string(respBytes)) + return respBytes, nil +} + +func CheckIpPort(ipPort string) error { + ipPort = strings.TrimLeft(ipPort, "http://") + ipPort = strings.TrimLeft(ipPort, "https://") + conn, err := net.DialTimeout("tcp", ipPort, 3*time.Second) + if err != nil { + return err + } else { + if conn != nil { + conn.Close() + return nil + } else { + return fmt.Errorf("%s dial failed", ipPort) + } + } +} diff --git a/bmp-operation-api/util/ipv4.go b/bmp-operation-api/util/ipv4.go new file mode 100644 index 0000000..b188cb5 --- /dev/null +++ b/bmp-operation-api/util/ipv4.go @@ -0,0 +1,166 @@ +package util + +import ( + "encoding/hex" + "fmt" + "net" + "strconv" + "strings" + + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +const ( + IP_NETWORK_SPLIT = "/" + IP_ADDRESS_REGEX = `^(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))$` + IP_WIDTH int32 = 32 + IP_MAX_VALUE int64 = 0xffffffff + IP_MIN_VALUE int64 = 0 +) + +func Gateway(cidr string) string { + ip, _, err := net.ParseCIDR(cidr) + if err != nil { + panic(err.Error()) + } + IncrIP(ip) + return ip.String() +} + +func Mask(mask net.IPMask) string { + m, _ := hex.DecodeString(mask.String()) + return net.IP([]byte(m)).String() +} + +// IP地址自增 +func IncrIP(ip net.IP) { + for i := len(ip) - 1; i >= 0; i-- { + ip[i]++ + if ip[i] > 0 { + break + } + } +} + +// IP地址自减 +func DecrIP(ip net.IP) { + length := len(ip) + for i := length - 1; i >= 0; i-- { + ip[length-1]-- + if ip[length-1] < 0xFF { + break + } + for j := 1; j < length; j++ { + ip[length-j-1]-- + if ip[length-j-1] < 0xFF { + return + } + } + } +} + +// RandomMacAddress 生成随机mac地址 +func RandomMacAddress() string { + + uuid := commonUtil.GetRandString("", 12, false, false, true) + first_part := uuid[0:4] + first_part_num, _ := strconv.ParseInt("0x"+first_part, 16, 32) + first_hex_string := strconv.FormatInt(first_part_num&0xfeff, 16) + part := []string{fmt.Sprintf("%04x", first_hex_string), uuid[4:8], uuid[8:12]} + return strings.Join(part, "-") +} + +/* + * 列举一个CIDR段中的所有IP列表 + */ +func GetAllHostIPs(cidr string) []string { + //不过不包含掩码位,就当做32位IP对待 + if !strings.Contains(cidr, "/") { + return []string{cidr} + } + ip := strings.Split(cidr, "/")[0] + ipSegs := strings.Split(ip, ".") + maskLen, _ := strconv.Atoi(strings.Split(cidr, "/")[1]) + if maskLen <= 0 { + return []string{} + } + if maskLen == 32 { + return []string{ip} + } + seg1MinIp, seg1MaxIp := getIpSeg1Range(ipSegs[0], maskLen) + seg2MinIp, seg2MaxIp := getIpSeg2Range(ipSegs[1], maskLen) + seg3MinIp, seg3MaxIp := getIpSeg3Range(ipSegs[2], maskLen) + seg4MinIp, seg4MaxIp := getIpSeg4Range(ipSegs[3], maskLen) + + var ipList []string + for seg1Ip := seg1MinIp; seg1Ip <= seg1MaxIp; seg1Ip++ { + for seg2Ip := seg2MinIp; seg2Ip <= seg2MaxIp; seg2Ip++ { + for seg3Ip := seg3MinIp; seg3Ip <= seg3MaxIp; seg3Ip++ { + for seg4Ip := seg4MinIp; seg4Ip <= seg4MaxIp; seg4Ip++ { + oneIp := fmt.Sprintf("%d.%d.%d.%d", seg1Ip, seg2Ip, seg3Ip, seg4Ip) + ipList = append(ipList, oneIp) + } + } + } + } + return ipList +} + +/* + * 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)3部分的最小值和最大值 + */ +func getIpSeg1Range(ipSeg string, maskLen int) (int, int) { + //如果掩码位>16,此时说明掩码只会影响到seg2,seg3,seg4,seg1直接返回 + if maskLen > 8 { + segIp, _ := strconv.Atoi(ipSeg) + return segIp, segIp + } + ipSegNum, _ := strconv.Atoi(ipSeg) + return getIpSegRange(uint8(ipSegNum), uint8(8-maskLen)) +} + +/* +* 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)3部分的最小值和最大值 + */ +func getIpSeg2Range(ipSeg string, maskLen int) (int, int) { + //如果掩码位>16,此时说明掩码只会影响到seg3,seg4,seg2直接返回 + if maskLen > 16 { + segIp, _ := strconv.Atoi(ipSeg) + return segIp, segIp + } + ipSegNum, _ := strconv.Atoi(ipSeg) + return getIpSegRange(uint8(ipSegNum), uint8(16-maskLen)) +} + +/* +* 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)3部分的最小值和最大值 + */ +func getIpSeg3Range(ipSeg string, maskLen int) (int, int) { + //如果掩码位>24,此时说明掩码只会影响到seg4,seg3直接返回 + if maskLen > 24 { + segIp, _ := strconv.Atoi(ipSeg) + return segIp, segIp + } + ipSegNum, _ := strconv.Atoi(ipSeg) + return getIpSegRange(uint8(ipSegNum), uint8(24-maskLen)) +} + +/* + * 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)4部分的最小值和最大值 + */ +func getIpSeg4Range(ipSeg string, maskLen int) (int, int) { + ipSegNum, _ := strconv.Atoi(ipSeg) + segMinIp, segMaxIp := getIpSegRange(uint8(ipSegNum), uint8(32-maskLen)) + if segMinIp == 0 { + segMinIp = segMinIp + 1 //最后一段的IP不能是0,否则就会变为网段 + } + return segMinIp, segMaxIp +} + +func getIpSegRange(userSegIp, offset uint8) (int, int) { + var ipSegMax uint8 = 255 + netSegIp := ipSegMax << offset + segMinIp := netSegIp & userSegIp + segMaxIp := userSegIp&(255< target_len { //裁剪 + if ahead { //保留左边 + return string(r[:target_len]) + } else { //保留右边 + return string(r[len(r)-target_len:]) + } + + } else if len(r) < target_len { //填充 + pads := []rune{} + for i := 0; i < target_len-len(r); i++ { + pads = append(pads, padding_char) + } + if ahead { //左向填充 + return string(append(pads, r...)) + } else { //右向填充 + return string(append(r, pads...)) + } + } + return source + +} + +func String2int8(v string) int8 { + i, err := strconv.ParseInt(v, 10, 32) + if err != nil { + panic(fmt.Sprintf("String2int8 error:%s", err.Error())) + } + return int8(i) +} + +func String2int(v string) int { + i, err := strconv.ParseInt(v, 10, 32) + if err != nil { + panic(fmt.Sprintf("String2int8 error:%s", err.Error())) + } + return int(i) +} + +func String2Bool(v string) bool { + if strings.ToLower(v) == "true" { + return true + } + return false +} diff --git a/bmp-operation-api/util/time.go b/bmp-operation-api/util/time.go new file mode 100644 index 0000000..679f809 --- /dev/null +++ b/bmp-operation-api/util/time.go @@ -0,0 +1,104 @@ +package util + +import ( + "time" +) + +//ParseTimeToDate 解析time格式为date格式 +func ParseTimeToDate(str, timeLayout, dateLayout string) (time.Time, error) { + var res time.Time + + t, err := time.Parse(timeLayout, str) + if err != nil { + return res, err + } + res, err = time.Parse(dateLayout, t.Format(dateLayout)) + if err != nil { + return res, err + } + return res, nil +} + +//GetFirstDayOfMonth 获取某个月份第一天 +func GetFirstDayOfMonth(month, monthLayout string) (time.Time, error) { + var res time.Time + + t, err := time.Parse(monthLayout, month) + if err != nil { + return res, err + } + return t.AddDate(0, 0, -t.Day()+1), nil +} + +//GetLastDayOfMonth 获取某个月份最后一天 +func GetLastDayOfMonth(month, monthLayout string) (time.Time, error) { + var res time.Time + + t, err := time.Parse(monthLayout, month) + if err != nil { + return res, err + } + return t.AddDate(0, 1, -t.Day()), nil +} + +//GetDateSubDays 获取某两个时间的差值 +func GetDateSubDays(dateStart, dateEnd time.Time) int { + return int(dateEnd.Sub(dateStart).Hours()/24) + 1 +} + +//GetMonthDays 获取某个月份总天数 +func GetMonthDays(month, monthLayout string) (int, error) { + dateStart, err := GetFirstDayOfMonth(month, monthLayout) + if err != nil { + return 0, err + } + dateEnd, err := GetLastDayOfMonth(month, monthLayout) + if err != nil { + return 0, err + } + + return GetDateSubDays(dateStart, dateEnd), nil +} + +//GetMonthCount 获取某两个月份之间的个数,包含这2个月份 +//ex: 2021-07和2021-09之间包含3个月 +func GetMonthCount(startMonth, endMonth, monthLayout string) (int, error) { + startMonthTime, err := time.Parse(monthLayout, startMonth) + if err != nil { + return 0, err + } + endMonthTime, err := time.Parse(monthLayout, endMonth) + if err != nil { + return 0, err + } + + startYear := startMonthTime.Year() + endYear := endMonthTime.Year() + startM := int(startMonthTime.Month()) + endM := int(endMonthTime.Month()) + yearInterval := endYear - startYear + + if endM <= startM { + yearInterval-- + } + + monthInterval := (endM + 12 - startM) % 12 + return yearInterval*12 + monthInterval + 1, nil +} + +//GetMonthSub 获取某两个月份之间的月份,包含这2个月份 +func GetMonthSub(startMonth, endMonth, monthLayout string) ([]string, error) { + months, err := GetMonthCount(startMonth, endMonth, monthLayout) + if err != nil { + return nil, err + } + startMonthTime, err := time.Parse(monthLayout, startMonth) + if err != nil { + return nil, err + } + monthArr := make([]string, 0) + for i := 0; i < months; i++ { + monthArr = append(monthArr, startMonthTime.AddDate(0, i, 0).Format(monthLayout)) + } + return monthArr, nil +} diff --git a/bmp-operation-web/.env b/bmp-operation-web/.env new file mode 100644 index 0000000..55b5d36 --- /dev/null +++ b/bmp-operation-web/.env @@ -0,0 +1,2 @@ +NODE_ENV="development" +VUE_APP_ENV="dev" \ No newline at end of file diff --git a/bmp-operation-web/.env.dev b/bmp-operation-web/.env.dev new file mode 100644 index 0000000..685b073 --- /dev/null +++ b/bmp-operation-web/.env.dev @@ -0,0 +1,2 @@ +NODE_ENV="production" +VUE_APP_ENV="dev" \ No newline at end of file diff --git a/bmp-operation-web/.env.pre b/bmp-operation-web/.env.pre new file mode 100644 index 0000000..8a522ef --- /dev/null +++ b/bmp-operation-web/.env.pre @@ -0,0 +1,2 @@ +NODE_ENV="production" +VUE_APP_ENV="pre" \ No newline at end of file diff --git a/bmp-operation-web/.eslintrc.js b/bmp-operation-web/.eslintrc.js new file mode 100644 index 0000000..1491481 --- /dev/null +++ b/bmp-operation-web/.eslintrc.js @@ -0,0 +1,50 @@ +module.exports = { + root: true, + env: { + 'node': true + }, + // eslint关闭 + rules: { + 'no-unused-vars': 'off', + 'linebreak-style': ['error', 'windows'], + 'no-console': 'off', // 禁用console + 'no-debugger': 'off', // 禁用debugger + 'space-before-function-paren': 'off', // 强制在function的左括号之前使用一致的空格 + 'no-underscore-dangle': 'off', // 禁止标识符中有悬空下划线 + 'no-param-reassign': 'off', // 禁止对函数参数再赋值 + 'func-names': 'off', // 禁止命名的 function 表达式 + 'no-bitwise': 'off', // 禁止使用按位操作符 + 'prefer-rest-params': 'off', // 建议使用剩余参数代替 arguments + 'no-trailing-spaces': 'off', // 禁用行尾空格 + 'comma-dangle': 'off', // 禁止使用拖尾逗号 + 'quote-props': 'off', // 要求对象字面量属性名称使用引号 + 'consistent-return': 'off', // 要求return语句要么总是指定返回的值,要么不指定 + 'no-plusplus': 'off', // 禁用一元操作符++和-- + 'prefer-spread': 'warn', // 要求使用扩展运算符而非.apply() + 'semi': 'warn', // 要求使用分号代替ASI + 'indent': ['warn', 'tab'], // 强制使用一致的缩进 + 'no-tabs': 'warn', // 禁用tab风格字符 + 'no-unused-vars': 'warn', // 禁止出现未使用过的变量 + 'quotes': 'warn', // 强制使用一致的反勾号、双引号或单引号 + 'no-void': 'off', // 禁止使用void操作符 + 'no-nested-ternary': 'off', // 禁止使用嵌套的三元表达式 + 'import/no-unresolved': 'off', + 'no-return-assign': 'warn', // 禁止在return语句中使用赋值语句 + 'linebreak-style': 'off', // 强制使用一致的换行符风格 + 'prefer-destructuring': 'off', // 优先使用数组和对象解构 + 'no-restricted-syntax': 'warn', // 禁止使用特定的语法 + 'arrow-parens': 'off', // 要求箭头函数的参数使用圆括号 + 'import/extensions': 'off', + 'import/named': 'off', + 'import/no-deprecated': 'off', + 'import/no-extraneous-dependencies': 'off', + 'fecs-no-require': 'off', + 'fecs-valid-jsdoc': 'off' + }, + parserOptions: { + 'parser': 'babel-eslint' + }, + extends: [ + 'plugin:@typescript-eslint/no-unused-vars' + ] +}; diff --git a/bmp-operation-web/.gitignore b/bmp-operation-web/.gitignore new file mode 100644 index 0000000..837579e --- /dev/null +++ b/bmp-operation-web/.gitignore @@ -0,0 +1,23 @@ +.DS_Store +node_modules +/dist +package-lock.json + +# local env files +.env.local +.env.*.local + +# Log files +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* + +# Editor directories and files +.idea +.vscode +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/bmp-operation-web/.gitmodules b/bmp-operation-web/.gitmodules new file mode 100644 index 0000000..506f24c --- /dev/null +++ b/bmp-operation-web/.gitmodules @@ -0,0 +1,3 @@ +[submodule "bmp-deploy"] + path = bmp-deploy + url = git@coding.jd.com:aidc-bmp/bmp-deploy.git diff --git a/bmp-operation-web/README.md b/bmp-operation-web/README.md new file mode 100644 index 0000000..db83eef --- /dev/null +++ b/bmp-operation-web/README.md @@ -0,0 +1,38 @@ +# bmp privatization operation platform project + +English | [简体中文](README.zh-CN.md) + +## Introduction +* This project is built based on @vue/cli 4 (vue3 + ts + pinia) + +## Introduction to directory and file functions +* The config directory stores webpack related configurations +* The public directory is created by @vue/cli by default and stores some static resources that do not need to be packaged by webpack +* public/robots.txt- is a plain text file that can declare the parts of the website that you do not want to be accessed by search engines, or specify that search engines only include specified content +* The src directory stores project development files +* App.vue root component +* The api directory stores interface-related configurations and calling methods based on routing +* The utils directory stores public methods and regular expressions +* The components directory stores common components for pages +* The lib directory stores third-party class libraries and plug-in references other than the vue family bucket, currently including element-plus, filters, vue-i18n, mitt, and pinia references +* The reuqest directory stores axios secondary encapsulation +* The router directory stores routing configuration files +* The store directory stores the state management library pinia +* main.ts project entry ts +* assets public resource association: pictures, styles, fonts +* views directory stores page components divided by routes +* .env file configures global environment variables +* .eslintrsc file configures eslint detection code related rules +* .gitignore file specifies ignore rules +* shims-vue.d.ts This file is an adaptation definition file for typescript +* package.json configuration file +* tsconfig.json ts file configuration +* babel.config.js configures babel to parse and convert js code related rules and parse es6 optional chain syntax +* jest.config.js jest unit test related +* tsconfig.json ts configuration related +* vue.config.js configures webpack and cross-domain related +* node version-dependency-recommendation 10.16.0, startup-recommendation-16.19.0 +* or npm i —-legacy-peer-deps to avoid dependency version issues, npm run dev[Use this command to specify the node version as 16.19.0, no need to switch] + +## Local development +* npm run dev, the interface uses the test environment interface, for the specific URL, see the proxy configuration in dev.server.js \ No newline at end of file diff --git a/bmp-operation-web/README.zh-CN.md b/bmp-operation-web/README.zh-CN.md new file mode 100644 index 0000000..c11bdf1 --- /dev/null +++ b/bmp-operation-web/README.zh-CN.md @@ -0,0 +1,38 @@ +# bmp私有化运营平台项目 + +[English](README.md) | 简体中文 + +## 简介 +* 本工程基于@vue/cli 4搭建而成(vue3 + ts + pinia) + +## 目录及文件功能简介 +* config目录存放webpack相关配置 +* public目录由@vue/cli默认创建生成,存放一些不需要经过webpack打包处理的静态资源 +* public/robots.txt-是一个纯文本文件,可以声明该网站中不想被搜索引擎访问的部分,或者指定搜索引擎只收录指定的内容 +* src目录存放项目开发文件 +* App.vue根组件 +* api目录存放根据路由划分接口相关配置及调用方法 +* utils目录存放公共方法、正则表达式 +* components目录存放页面通用组件 +* lib目录存放除vue全家桶以外的第三方类库及插件引用,当前包含element-plus、filters、vue-i18n、mitt、pinia的引用 +* reuqest目录存放axios二次封装 +* router目录存放路由配置文件 +* store目录存放状态管理库pinia +* main.ts工程入口ts +* assets公共资源关联:图片、样式、字体 +* views目录存储根据路由划分的页面组件 +* .env文件配置全局环境变量 +* .eslintrsc文件配置eslint检测代码相关规则 +* .gitignore文件 指定忽略规则 +* shims-vue.d.ts 该文件是为了 typescript 做的适配定义文件 +* package.json 配置文件 +* tsconfig.json ts文件的一些配置 +* babel.config.js配置babel解析转换js代码相关规则、解析es6可选链式语法 +* jest.config.js jest单元测试相关 +* tsconfig.json ts配置相关 +* vue.config.js配置webpack、跨域相关 +* node版本-依赖-建议10.16.0,启动-建议-16.19.0 +* 或者npm i —-legacy-peer-deps 避免各依赖版本问题,npm run dev[用这个命令node版本指定为16.19.0即可,不用切换] + +## 本地开发 +* npm run dev, 接口走测试环境的接口,具体url见dev.server.js中的代理配置 \ No newline at end of file diff --git a/bmp-operation-web/babel.config.js b/bmp-operation-web/babel.config.js new file mode 100644 index 0000000..ecedfee --- /dev/null +++ b/bmp-operation-web/babel.config.js @@ -0,0 +1,9 @@ +module.exports = { + presets: [ + '@vue/cli-plugin-babel/preset' + ], + plugins: [ + // 解析es6可选链式语法 + ['@babel/plugin-proposal-optional-chaining'] + ] +} diff --git a/bmp-operation-web/bmp-operation-web.Dockerfile b/bmp-operation-web/bmp-operation-web.Dockerfile new file mode 100644 index 0000000..d001d64 --- /dev/null +++ b/bmp-operation-web/bmp-operation-web.Dockerfile @@ -0,0 +1,10 @@ +FROM node:16.19-alpine3.16 AS builder +WORKDIR /usr/src/bmp-operation-web +RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories \ + && apk add python3 make gcc g++ +COPY . . +RUN npm config set registry https://registry.npmmirror.com && npm install --legacy-peer-deps && npm run build-pre + +FROM nginx:1.22-alpine +WORKDIR /home/bmp/bmp-operation-web +COPY --from=builder /usr/src/bmp-operation-web/dist . diff --git a/bmp-operation-web/config/devServer.js b/bmp-operation-web/config/devServer.js new file mode 100644 index 0000000..8c5741d --- /dev/null +++ b/bmp-operation-web/config/devServer.js @@ -0,0 +1,37 @@ +module.exports = { + devServer: { + overlay: { // 让浏览器 overlay 同时显示警告和错误 + warnings: true, + errors: true + }, + open: true, // 是否直接打开浏览器 + host: 'localhost', // 本地服务器 + port: 8089, // 端口号 + hotOnly: true, // 热更新,在某些模块不支持热更新的情况下,在控制台输出热更新失败 + proxy: { // 跨域 + '/operation-web': { + target: 'http://bmp-operation.bmp.local', + // ws: true, + changeOrigin: true // 是否需要跨域 + }, + '/template-upload': { + target: 'http://bmp-operation.bmp.local', + changeOrigin: true, // 是否需要跨域 + // ws: true, + pathRewrite: { + '^/template-upload': '' + } + }, + '/oob-alert': { + target: 'http://bmp-oob-alert.bmp.local', + changeOrigin: true, // 是否需要跨域 + pathRewrite: { + '^/oob-alert': '' + } + } + }, + sockHost: 'localhost', + disableHostCheck: true, // 禁止主机检查 + progress: false + } +}; diff --git a/bmp-operation-web/config/devTool.js b/bmp-operation-web/config/devTool.js new file mode 100644 index 0000000..8024b6d --- /dev/null +++ b/bmp-operation-web/config/devTool.js @@ -0,0 +1,6 @@ +const env = process.env.VUE_APP_ENV; + +module.exports = (config) => { + config.devtool = env === 'dev' ? 'source-map' : 'cheap-module-souce-map'; + return config; +}; \ No newline at end of file diff --git a/bmp-operation-web/config/noParse.js b/bmp-operation-web/config/noParse.js new file mode 100644 index 0000000..48df4f0 --- /dev/null +++ b/bmp-operation-web/config/noParse.js @@ -0,0 +1,5 @@ +module.exports = (config) => { + // 减少不必要的解析,让 Webpack 忽略对部分没采用模块化的文件的递归解析处理,这样做的好处是能提高构建性能 + config.module.noParse = '/^(vue|vue-router|vue-i18n)$/'; + return config +}; diff --git a/bmp-operation-web/config/plugin.js b/bmp-operation-web/config/plugin.js new file mode 100644 index 0000000..de060a0 --- /dev/null +++ b/bmp-operation-web/config/plugin.js @@ -0,0 +1,17 @@ +const components = require('unplugin-vue-components/webpack'); +const autoImport = require('unplugin-auto-import/webpack'); + +module.exports = config => { + config.plugins.push( + components({ + dirs: ['./src/components'], + extensions: ['vue'], + dts: './src/components.d.ts' + }), + autoImport({ + imports: ['vue'], + dts: './src/auto-imports.d.ts' + }) + ); + return config; +}; diff --git a/bmp-operation-web/config/runtimeChunk.js b/bmp-operation-web/config/runtimeChunk.js new file mode 100644 index 0000000..8bb2e65 --- /dev/null +++ b/bmp-operation-web/config/runtimeChunk.js @@ -0,0 +1,5 @@ +// 避免文件的频繁变更导致浏览器缓存失效,更好的利用缓存。提升用户体验 +module.exports = (config) => { + config.optimization.runtimeChunk = true; + return config; +}; diff --git a/bmp-operation-web/config/setAlias.js b/bmp-operation-web/config/setAlias.js new file mode 100644 index 0000000..77eb811 --- /dev/null +++ b/bmp-operation-web/config/setAlias.js @@ -0,0 +1,24 @@ +const path = require('path'); +const resolve = (dir) => path.join(__dirname, '..', dir); + +// 设置alias别名、配置简化路径 +module.exports = config => { + config.resolve.alias + .set('@', resolve('src')) + .set('api', resolve('src/api')) + .set('@utils', resolve('src/utils/')) + .set('assets', resolve('src/assets')) + .set('utils', resolve('src/utils')) + .set('mock', resolve('src/mock')) + .set('staticData', resolve('src/staticData')) + .set('components', resolve('src/components')) + .set('hooks', resolve('src/hooks')) + .set('lib', resolve('src/lib')) + .set('plugin', resolve('src/plugin')) + .set('request', resolve('src/request')) + .set('router', resolve('src/router')) + .set('store', resolve('src/store')) + .set('views', resolve('src/views')) + .set('vue-i18n', 'vue-i18n/dist/vue-i18n.cjs.js') // 解决控制台警告 + return config; +}; diff --git a/bmp-operation-web/config/setOutPut.js b/bmp-operation-web/config/setOutPut.js new file mode 100644 index 0000000..32c357a --- /dev/null +++ b/bmp-operation-web/config/setOutPut.js @@ -0,0 +1,5 @@ +module.exports = (config) => { + config.output.filename = '[name].[hash].js'; + config.output.chunkFilename = '[name].[hash].js'; + return config; +} \ No newline at end of file diff --git a/bmp-operation-web/config/speedMeasure.js b/bmp-operation-web/config/speedMeasure.js new file mode 100644 index 0000000..37fb9d8 --- /dev/null +++ b/bmp-operation-web/config/speedMeasure.js @@ -0,0 +1,9 @@ +// 这个插件可以看到启动时候的耗时模块,方便后续做优化使用 +const SpeedMeasurePlugin = require('speed-measure-webpack-plugin'); + +module.exports = (config) => { + config.plugins.push( + new SpeedMeasurePlugin() + ); + return config; +} diff --git a/bmp-operation-web/config/terserPlugin.js b/bmp-operation-web/config/terserPlugin.js new file mode 100644 index 0000000..3ec26a9 --- /dev/null +++ b/bmp-operation-web/config/terserPlugin.js @@ -0,0 +1,19 @@ +// 移除console +const TerserPlugin = require('terser-webpack-plugin'); +module.exports = () => { + if (['prod', 'pre'].includes(process.env.VUE_APP_ENV)) { + new TerserPlugin({ + parallel: true, + terserOptions: { + ecma: undefined, + warnings: false, + parse: {}, + compress: { + drop_console: true, + drop_debugger: false, + pure_funcs: ['console.log'], // 移除console + }, + } + }) + } +} diff --git a/bmp-operation-web/jest.config.js b/bmp-operation-web/jest.config.js new file mode 100644 index 0000000..8c3c689 --- /dev/null +++ b/bmp-operation-web/jest.config.js @@ -0,0 +1,7 @@ +module.exports = { + // ts编译之后,在进行一个babel编译 + 'preset': '@vue/cli-plugin-unit-jest/presets/typescript-and-babel', + 'transform': { + '^.+\\.vue$': 'vue-jest' + } +}; \ No newline at end of file diff --git a/bmp-operation-web/package.json b/bmp-operation-web/package.json new file mode 100644 index 0000000..8a0f3af --- /dev/null +++ b/bmp-operation-web/package.json @@ -0,0 +1,60 @@ +{ + "name": "bmp-operation-web", + "version": "1.0.0", + "private": true, + "scripts": { + "dev": "vue-cli-service serve", + "start": "npm run dev", + "build": "vue-cli-service build --report", + "build-pre": "vue-cli-service build --mode pre", + "build-test": "vue-cli-service build --mode test", + "build-prod": "vue-cli-service build --mode prod", + "test": "vue-cli-service test:unit" + }, + "dependencies": { + "@element-plus/icons": "0.0.11", + "axios": "^0.25.0", + "browserslist": "^4.23.2", + "caniuse-lite": "^1.0.30001643", + "core-js": "3.6.5", + "crypto-js": "^4.1.1", + "default-passive-events": "^2.0.0", + "element-plus": "2.0.0", + "mitt": "3.0.0", + "mockjs": "^1.1.0", + "pinia": "2.0.21", + "pinia-plugin-persist": "1.0.0", + "pinyin-pro": "^3.19.6", + "polyfill-object.fromentries": "1.0.1", + "vue": "3.2.25", + "vue-cookies": "1.8.1", + "vue-i18n": "9.1.10", + "vue-router": "4.0.3" + }, + "devDependencies": { + "@babel/plugin-proposal-optional-chaining": "7.18.9", + "@types/jest": "^24.0.19", + "@vue/cli-plugin-babel": "~4.5.15", + "@vue/cli-plugin-pwa": "~4.5.15", + "@vue/cli-plugin-router": "~4.5.15", + "@vue/cli-plugin-typescript": "~4.5.15", + "@vue/cli-plugin-unit-jest": "~4.5.15", + "@vue/cli-service": "~4.5.15", + "@vue/test-utils": "^2.0.0-0", + "babel-eslint": "10.1.0", + "echarts": "^5.5.0", + "sass": "1.26.5", + "sass-loader": "^8.0.2", + "speed-measure-webpack-plugin": "^1.5.0", + "terser-webpack-plugin": "^5.3.6", + "typescript": "4.4.4", + "unplugin-auto-import": "^0.16.7", + "unplugin-vue-components": "^0.23.0", + "vue-jest": "^5.0.0-0" + }, + "browserslist": [ + "> 1%", + "last 2 versions", + "not dead" + ] +} diff --git a/bmp-operation-web/public/img/icons/android-chrome-192x192.png b/bmp-operation-web/public/img/icons/android-chrome-192x192.png new file mode 100644 index 0000000..b02aa64 Binary files /dev/null and b/bmp-operation-web/public/img/icons/android-chrome-192x192.png differ diff --git a/bmp-operation-web/public/index.html b/bmp-operation-web/public/index.html new file mode 100644 index 0000000..029e490 --- /dev/null +++ b/bmp-operation-web/public/index.html @@ -0,0 +1,16 @@ + + + + + + + + bmp-operation-web + + + +
+ + + + diff --git a/bmp-operation-web/public/robots.txt b/bmp-operation-web/public/robots.txt new file mode 100644 index 0000000..9c502b1 --- /dev/null +++ b/bmp-operation-web/public/robots.txt @@ -0,0 +1,3 @@ +User-agent: * +Disallow: /index.html +Disallow: /? diff --git a/bmp-operation-web/src/App.vue b/bmp-operation-web/src/App.vue new file mode 100644 index 0000000..fe1ce7d --- /dev/null +++ b/bmp-operation-web/src/App.vue @@ -0,0 +1,9 @@ + + diff --git a/bmp-operation-web/src/api/device/config.ts b/bmp-operation-web/src/api/device/config.ts new file mode 100644 index 0000000..9225b08 --- /dev/null +++ b/bmp-operation-web/src/api/device/config.ts @@ -0,0 +1,55 @@ +/** + * @file + * @author +*/ +import {methodsTotal} from 'utils/index.ts'; +import {TotalUrlPathType} from './typeManagement'; // url地址类 + +const defaultUrl1: string = '/devices'; +const defaultUrl2: string = '/instances'; +const defaultUrl3: string = '/v1/oobAlert/'; +const defaultUrl4: string = '/auditLogs'; + +// url地址集合 +const urlPath: TotalUrlPathType = { + devicesListUrl: `${defaultUrl1}/queryDevices`, // 设备列表 + deviceTemplateUrl: '/data/device_import.xlsx', // 设备模板下载 + devicesUpUrl: `${defaultUrl1}/putaway`, // 设备上架 + devicesDownUrl: `${defaultUrl1}/unPutaway`, // 设备下架 + devicesRemoveUrl: `${defaultUrl1}/`, // 设备移除 + instanceRecoveryUrl: `${defaultUrl2}/`, // 回收实例 + resetInstanceUrl: `${defaultUrl2}/resetStatus/`, // 重置实例 + devicesEditUrl: `${defaultUrl1}/`, // 设备编辑 + devicesDeleteUrl: `${defaultUrl1}/`, // 设备删除 + devicesStartUrl: `${defaultUrl2}/start/`, // 设备开机 + devicesResetPasswordUrl: `${defaultUrl2}/resetPasswd`, // 重置密码 + devicesBatchStartUrl: `${defaultUrl2}/startInstances`, // 设备批量开机 + devicesStopUrl: `${defaultUrl2}/stop/`, // 设备关机 + devicesBatchStopUrl: `${defaultUrl2}/stopInstances`, // 设备批量关机 + devicesRestartUrl: `${defaultUrl2}/restart/`, // 设备重启 + devicesBatchRestartUrl: `${defaultUrl2}/restartInstances`, // 设备批量重启 + deviceBatchResetPasswordUrl: `${defaultUrl2}/batchResetPasswd`, // 批量重置密码 + lockUrl: `${defaultUrl2}/lock/`, // 锁定 + unlockUrl: `${defaultUrl2}/unlock/`, // 解锁 + resetSystemUrl: `${defaultUrl2}/reinstallInstance`, // 重装系统 + devicesDetailUrl: `${defaultUrl1}/queryDevice/`, // 设备详情 + devicesCollectUrl: `${defaultUrl1}/collect`, // 设备采集 + instanceDetailUrl: `${defaultUrl2}/`, // 实例详情 + importDevicesUrl: defaultUrl1, // 导入设备 + batchEditInstanceNameUrl: `${defaultUrl2}/modifyInstances`, // 批量编辑实例名称 + batchRecoveryInstanceUrl: `${defaultUrl2}/deleteInstances`, // 批量回收实例 + deviceStatusUrl: methodsTotal.humpSplit(`${defaultUrl3}device/status`), // 获取设备带外总体状态 + consolelogsUrl: methodsTotal.humpSplit(`${defaultUrl3}consolelogs`), // 设备详情-硬件监控-报警日志列表接口 + disksDetailUrl: `${defaultUrl1}/`, // 磁盘详情 + describeAssociateDisksUrl: `${defaultUrl1}/disks/describeAssociateDisks`, // 获取设备关联磁盘信息 + associateDisksUrl: `${defaultUrl1}/disks/associateDisks`, // 关联设备磁盘 + describeVolumesUrl: `/deviceTypes/`, // 根据机型获取卷列表信息 + associateUrl: `${defaultUrl1}/deviceType/associate`, // 设备关联机型 + auditLogsUrl: defaultUrl4, // 设备详情-操作日志 + auditLogsTypesUrl: `${defaultUrl4}/types`, // 获取操作日志类型的接口 + monitorDataUrl: '/monitorData', // 监控图表 + desrcibeTagsUrl: '/monitorProxy/desrcibeTags', // 监控tag + desrcibeAgentStatusUrl: '/monitorProxy/desrcibeAgentStatus', // 监控Agent章台 +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/device/request.ts b/bmp-operation-web/src/api/device/request.ts new file mode 100644 index 0000000..278d5e0 --- /dev/null +++ b/bmp-operation-web/src/api/device/request.ts @@ -0,0 +1,356 @@ +/** + * @file + * @author +*/ + +import urlPath from './config'; +import request from 'request/index.ts'; +import {AxiosPromise} from 'axios'; +import {ParamDataType, RequestType} from './typeManagement'; +import store from 'store/index.ts'; +const {get, put, deleteReq, post} = request; + +type ProgressEventType = { lengthComputable: boolean; loaded: number; total: number; } + +const reqProgress = (progressEvent: ProgressEventType) => { + if (progressEvent.lengthComputable) { + const percentComplete = (progressEvent.loaded / progressEvent.total) * 100; + store.progressInfo.progressNum = Number(percentComplete.toFixed(2)); + } +} + +/** + * 设备列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function devicesListAPI(params: ParamDataType['DevicesListType']): ReturnType { + return get(urlPath.devicesListUrl, params, {isBusinessProcessing: false, islongReq: true}); +}; + +/** + * 设备模板接口 + * @param {Object} params 请求需要的参数 +*/ +export function deviceTemplateAPI(params: ParamDataType['DeviceTemplateType']): ReturnType { + return get(urlPath.deviceTemplateUrl, params, {baseURL: '/template-upload', timeout: 1000 * 120, isBusinessProcessing: false, responseType: 'blob', islongReq: true}); +}; + +/** + * 设备列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +export function devicesListExportAPI(params: ParamDataType['DevicesListExportType']): ReturnType { + return get(urlPath.devicesListUrl, params, {timeout: 1000 * 120, isBusinessProcessing: false, responseType: 'blob', islongReq: true}); +}; + +/** + * 设备详情-硬件监控-报警日志列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function consolelogsAPI(params: ParamDataType['ConsolelogsType']): ReturnType { + return get(urlPath.consolelogsUrl, params, {baseURL: '/oob-alert', isBusinessProcessing: false}); +}; + +/** + * 设备详情-硬件监控-报警日志列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +export function consolelogsExportAPI(params: ParamDataType['ConsolelogsType']): ReturnType { + return get(urlPath.consolelogsUrl, params, {baseURL: '/oob-alert', timeout: 1000 * 120, isBusinessProcessing: false, responseType: 'blob', islongReq: true}); +}; + +/** + * 设备上架接口 + * @param {Object} data 请求需要的参数 +*/ +export function devicesUpAPI(data: ParamDataType['DeviceUpType']): ReturnType { + return put(urlPath.devicesUpUrl, data, true); +}; + +/** + * 设备采集接口 + * @param {Object} data 请求需要的参数 +*/ +export function devicesCollectAPI(data: {sn: string; allowOverride: boolean}): ReturnType { + return post(urlPath.devicesCollectUrl, data, true); +}; + +/** + * 设备下架接口 + * @param {Object} data 请求需要的参数 +*/ +export function devicesDownAPI(data: ParamDataType['DeviceDownType']): ReturnType { + return put(urlPath.devicesDownUrl, data, true); +}; + +/** + * 设备移除接口 + * @param {Object} data 请求需要的参数 +*/ +export function devicesRemoveAPI(data: ParamDataType['DevicesRemoveType']): ReturnType { + return put(urlPath.devicesRemoveUrl + data.deviceId + '/remove', data, true); +}; + +/** + * 回收实例接口 + * @param {Object} data 请求需要的参数 +*/ +export function instanceRecoveryAPI(data: ParamDataType['InstanceRecoveryType']): ReturnType { + return deleteReq(urlPath.instanceRecoveryUrl + data.instanceId, data, true); +}; + +/** + * 重置实例接口 + * @param {Object} data 请求需要的参数 +*/ +export function resetInstanceAPI(data: ParamDataType['ResetInstanceType']): ReturnType { + return post(urlPath.resetInstanceUrl + data.instanceId, data, true); +}; + +/** + * 设备描述编辑接口 + * @param {Object} data 请求需要的参数 +*/ +export function devicesEditAPI(data: ParamDataType['DevicesEditType']): ReturnType { + return put(urlPath.devicesEditUrl + data.id, data, true); +}; + +/** + * 设备删除接口 + * @param {Object} data 请求需要的参数 +*/ +export function devicesDeleteAPI(data: ParamDataType['DeviceDeleteType']): ReturnType { + return deleteReq(urlPath.devicesDeleteUrl + data.deviceId, data, true); +}; + +/** + * 设备开机接口 + * @param {Object} data 请求需要的参数 +*/ +export function devicesStartAPI(data: ParamDataType['DevicesStartType']): ReturnType { + return post(urlPath.devicesStartUrl + data.instanceId, data, true); +}; + +/** + * 设备重置密码接口 + * @param {Object} data 请求需要的参数 +*/ +export function devicesResetPasswordAPI(data: ParamDataType['DevicesResetPasswordType']): ReturnType { + return post(urlPath.devicesResetPasswordUrl, data, true); +}; + + +/** + * 设备批量开机接口 + * @param {Object} data 请求需要的参数 +*/ +export function devicesBatchStartAPI(data: ParamDataType['DevicesStartType']): ReturnType { + return post(urlPath.devicesBatchStartUrl, data, true); +}; + +/** + * 设备关机接口 + * @param {Object} data 请求需要的参数 +*/ +export function devicesStopAPI(data: ParamDataType['DevicesStopType']): ReturnType { + return post(urlPath.devicesStopUrl + data.instanceId, data, true); +}; + +/** + * 设备批量关机接口 + * @param {Object} data 请求需要的参数 +*/ +export function devicesBatchStopAPI(data: ParamDataType['DevicesStopType']): ReturnType { + return post(urlPath.devicesBatchStopUrl, data, true); +}; + +/** + * 设备重启接口 + * @param {Object} data 请求需要的参数 +*/ +export function devicesRestartAPI(data: ParamDataType['DevicesRestartType']): ReturnType { + return post(urlPath.devicesRestartUrl + data.instanceId, {}, true); +}; + +/** + * 设备批量重启接口 + * @param {Object} data 请求需要的参数 +*/ +export function devicesBatchRestartAPI(data: ParamDataType['DevicesRestartType']): ReturnType { + return post(urlPath.devicesBatchRestartUrl, data, true); +}; + +/** + * 设备批量重置密码接口 + * @param {Object} data 请求需要的参数 +*/ +export function deviceBatchResetPasswordAPI(data: ParamDataType['BatchResetPasswordType']): ReturnType { + return post(urlPath.deviceBatchResetPasswordUrl, data, true); +}; + +/** + * 锁定接口 + * @param {Object} data 请求需要的参数 +*/ +export function lockAPI(data: ParamDataType['LockType']): ReturnType { + return post(urlPath.lockUrl + data.instanceId, data, true); +}; + +/** + * 解锁接口 + * @param {Object} data 请求需要的参数 +*/ +export function unlockAPI(data: ParamDataType['UnlockType']): ReturnType { + return post(urlPath.unlockUrl + data.instanceId, data, true); +}; + +/** + * 重装系统接口 + * @param {Object} data 请求需要的参数 +*/ +export function resetSystemAPI(data: ParamDataType['ResetSystemType']): ReturnType { + return post(urlPath.resetSystemUrl, data, true); +}; + +/** + * 设备详情接口 + * @param {Object} params 请求需要的参数 +*/ +export function devicesDetailAPI(params: ParamDataType['DevicesDetailType']): ReturnType { + return get(urlPath.devicesDetailUrl + params.deviceId, params, {isBusinessProcessing: false}); +}; + +/** + * 实例详情接口 + * @param {Object} params 请求需要的参数 +*/ +export function instanceDetailAPI(params: ParamDataType['InstanceDetailType']): ReturnType { + return get(urlPath.instanceDetailUrl + params.instanceId, params, {isBusinessProcessing: false}); +}; + +/** + * 导入设备接口 + * @param {Object} data 请求需要的参数 +*/ +export function importDevicesAPI(data: ParamDataType['ImportDevicesType']): ReturnType { + return post(urlPath.importDevicesUrl, data, true, {timeout: 1000 * 180, islongReq: true}); +}; + +/** + * 批量编辑实例名称接口 + * @param {Object} data 请求需要的参数 +*/ +export function BatchEditInstanceNameAPI(data: ParamDataType['BatchEditInstanceNameType']): ReturnType { + return post(urlPath.batchEditInstanceNameUrl, data, false); +}; + +/** + * 批量回收实例接口 + * @param {Object} data 请求需要的参数 +*/ +export function BatchRecoveryInstanceAPI(data: ParamDataType['BatchRecoveryInstanceType']): ReturnType { + return deleteReq(urlPath.batchRecoveryInstanceUrl, data, true); +}; + +/** + * 获取设备带外总体状态接口 + * @param {Object} params 请求需要的参数 +*/ +export function deviceStatusAPI(params: ParamDataType['deviceStatusType']): AxiosPromise { + return get(urlPath.deviceStatusUrl, params, {isBusinessProcessing: false, baseURL: '/oob-alert'}); +}; + +/** + * 设备详情-磁盘信息接口 + * @param {Object} params 请求需要的参数 +*/ +export function disksDetailAPI(params: {deviceId: string}): ReturnType { + return get(urlPath.disksDetailUrl + params.deviceId + '/disksDetail', {}, {isBusinessProcessing: false}); +}; + +/** + * 获取设备关联的磁盘信息 + * @param {Object} params 请求需要的参数 +*/ +export function describeAssociateDisksAPI(params: Parameters): ReturnType { + return get(urlPath.describeAssociateDisksUrl, params, {isBusinessProcessing: true}); +}; + +/** + * 关联设备磁盘 + * @param {Object} data 请求需要的参数 +*/ +export function associateDisksAPI(data: Parameters): ReturnType { + return put(urlPath.associateDisksUrl, data, true); +}; + +/** + * 根据机型获取卷列表信息 + * @param {Object} params 请求需要的参数 +*/ +export function describeVolumesAPI(params: {deviceTypeId: string}): ReturnType { + return get(urlPath.describeVolumesUrl + params.deviceTypeId + '/describeVolumes', {}, {isBusinessProcessing: true}); +}; + +/** + * 设备关联机型 + * @param {Object} data 请求需要的参数 +*/ +export function associateAPI(data: {deviceTypeId: string}): ReturnType { + return put(urlPath.associateUrl, data, true); +}; + +/** + * 设备详情-操作日志 + * @param {Object} params 请求需要的参数 +*/ +export function auditLogsAPI(params: Parameters): ReturnType { + return get(urlPath.auditLogsUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 设备详情-获取操作日志类型的接口 + * @param {Object} params 请求需要的参数 +*/ +export function auditLogsTypesAPI(params: Parameters): ReturnType { + return get(urlPath.auditLogsTypesUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 设备详情-操作日志-导出 + * @param {Object} params 请求需要的参数 +*/ +export function auditLogsExportAPI(params: Parameters): ReturnType { + const otherParams = { + isBusinessProcessing: false, + timeout: 1000 * 120, + responseType: 'blob', + islongReq: true, + onDownloadProgress: (progressEvent: ProgressEventType) => reqProgress(progressEvent) + }; + return get(urlPath.auditLogsUrl, params, {...otherParams}); +}; + +/** + * 设备详情-监控图表 + * @param {Object} params 请求需要的参数 +*/ +export function monitorDataAPI(params: Parameters): ReturnType { + return get(urlPath.monitorDataUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 设备详情-监控tags + * @param {Object} params 请求需要的参数 +*/ +export function desrcibeTagsAPI(params: Parameters): ReturnType { + return get(urlPath.desrcibeTagsUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 设备详情-监控agent状态 + * @param {Object} params 请求需要的参数 +*/ +export function desrcibeAgentStatusAPI(params: Parameters): ReturnType { + return get(urlPath.desrcibeAgentStatusUrl, params, {isBusinessProcessing: false}); +}; diff --git a/bmp-operation-web/src/api/device/typeManagement.ts b/bmp-operation-web/src/api/device/typeManagement.ts new file mode 100644 index 0000000..abf55dd --- /dev/null +++ b/bmp-operation-web/src/api/device/typeManagement.ts @@ -0,0 +1,103 @@ +type AddReadonly = {readonly [P in keyof T]: T[P]}; + +type UrlPathType = { + devicesListUrl: string; // 设备列表 + deviceTemplateUrl: string; // 设备模板 + devicesUpUrl: string; // 设备上架 + devicesDownUrl: string; // 设备下架 + devicesRemoveUrl: string; // 设备移除 + instanceRecoveryUrl: string; // 回收实例 + resetInstanceUrl: string; // 重置实例 + devicesEditUrl: string; // 设备编辑 + devicesDeleteUrl: string; // 设备删除 + devicesStartUrl: string; // 设备开机 + devicesResetPasswordUrl: string; // 设备重置密码 + devicesBatchStartUrl: string; // 设备批量开机 + devicesStopUrl: string; // 设备关机 + devicesBatchStopUrl: string; // 设备批量关机 + devicesRestartUrl: string; // 设备重启 + devicesBatchRestartUrl: string; // 设备批量重启 + deviceBatchResetPasswordUrl: string; // 设备批量重置密码 + lockUrl: string; // 锁定 + unlockUrl: string; // 解锁 + resetSystemUrl: string; // 重装系统 + devicesDetailUrl: string; // 设备详情 + devicesCollectUrl: string; // 设备采集 + instanceDetailUrl: string; // 实例详情 + importDevicesUrl: string; // 导入设备 + batchEditInstanceNameUrl: string; // 批量编辑实例名称 + batchRecoveryInstanceUrl: string; // 批量回收实例 + deviceStatusUrl: string; // 获取设备带外总体状态 + consolelogsUrl: string; // 设备详情-硬件监控-报警日志列表接口 + disksDetailUrl: string; // 磁盘详情 + describeAssociateDisksUrl: string; // 获取设备关联磁盘信息 + associateDisksUrl: string; // 关联设备磁盘 + describeVolumesUrl: string; // 根据机型获取卷列表信息 + associateUrl: string; // 设备关联机型 + auditLogsUrl: string; // 设备详情-操作日志 + auditLogsTypesUrl: string; // 获取操作日志类型的接口 + monitorDataUrl: string; // 监控图表 + desrcibeTagsUrl: string; // 监控tags + desrcibeAgentStatusUrl: string; // 监控agent状态 +}; + +// url地址类型 +type TotalUrlPathType = AddReadonly; + +// idc-机房列表类 +type ListType = { + pageNumber: number; + pageSize: number; + isAll: boolean | number; + exportType: string; +}; + +type DeviceOperateType = { + deviceId: string; + sns: string; +}; + +// 接口参数类型 +interface ParamDataType { + DeleteImageType: Required<{deviceTypeId: string}> | Partial<{imageId: string;}>; + DeleteModelType: Required<{id: string;}>; + DevicesListType: Partial & Partial<{sn: string; deviceTypeId: string; manageStatus: string; iloIp: string; instanceOwer: string;}>; + DevicesListExportType: Partial & Partial<{sn: string; deviceTypeId: string; manageStatus: string; iloIp: string; instanceOwer: string;}>; + ConsolelogsType: ListType & {sn: string}; + DeviceUpType: Required; + DeviceDownType: Required; + DevicesRemoveType: Required<{deviceId: string}>; + InstanceRecoveryType: Required<{instanceId: string;}>; + ResetInstanceType: Required<{instanceId: string;}>; + DevicesEditType: {id?: string; description: string;}; + DeviceDeleteType: Required<{deviceId: string;}>; + DevicesStartType: Required<{instanceId: string;}>; + DevicesResetPasswordType: Required<{instanceId: string; idcId: string; password: string;}>; + DevicesStopType: Required<{instanceId: string;}>; + DevicesRestartType: Required; + BatchResetPasswordType: {instanceIds: string[]; password: string;}; + LockType: {instanceId: string;}; + UnlockType: {instanceId: string;}; + DevicesDetailType: {deviceId?: string; show: string}; + InstanceDetailType: {instanceId: string}; + ResetSystemType: any; + DeviceTemplateType: {}; + ImportDevicesType: {idcId: string; deviceTypeId: string}; + BatchEditInstanceNameType: any; + BatchRecoveryInstanceType: any; + deviceStatusType: {pageNumber: number; pageSize: number; idcId: string; sn: string;}; +}; + +interface RequestType { + CurrencyType: { + isBusinessProcessing: boolean; + url: string; + methods: string; + }; +}; + +export { + TotalUrlPathType, + ParamDataType, + RequestType +}; diff --git a/bmp-operation-web/src/api/idc/config.ts b/bmp-operation-web/src/api/idc/config.ts new file mode 100644 index 0000000..a009939 --- /dev/null +++ b/bmp-operation-web/src/api/idc/config.ts @@ -0,0 +1,17 @@ +/** + * @file + * @author +*/ + +import {TotalUrlPathType} from './typeManagement'; // url地址类 + +const dafaultUrl: string = '/idc'; + +// url地址集合 +const urlPath: TotalUrlPathType = { + idcListUrl: dafaultUrl, // 机房列表 + idcDetailUrl: dafaultUrl + '/', // 机房详情 + editIdcUrl: dafaultUrl + '/', // 编辑机房 +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/idc/request.ts b/bmp-operation-web/src/api/idc/request.ts new file mode 100644 index 0000000..b941fd1 --- /dev/null +++ b/bmp-operation-web/src/api/idc/request.ts @@ -0,0 +1,77 @@ +/** + * @file + * @author +*/ + +import urlPath from './config'; +import store from 'store/index.ts'; +import request from 'request/index.ts'; +import {ParamDataType} from './typeManagement'; +const {get, put} = request; + +type ProgressEventType = { lengthComputable: boolean; loaded: number; total: number; } + +const reqProgress = (progressEvent: ProgressEventType) => { + // if (progressEvent.lengthComputable) { + // const percentComplete = (progressEvent.loaded / progressEvent.total) * 100; + // let val:number = 0; + // if (Number(percentComplete.toFixed(2)) >= 100) { + // val = 100; + // } + // else { + // val = Number(percentComplete.toFixed(2)); + // } + // store.progressInfo.progressNum = val; + // } + if (progressEvent.lengthComputable) { + const percentComplete = (progressEvent.loaded / progressEvent.total) * 100; + store.progressInfo.progressNum = Math.min(100, Number(percentComplete.toFixed(2))); + } +} +/** + * 机房列表接口 + * @param {Object} params 请求需要的参数 +*/ +const idcListAPI = (params: ParamDataType['IdcListType']): ReturnType => { + return get(urlPath.idcListUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 机房列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +const idcListExportAPI = (params: ParamDataType['idcListExportType']): ReturnType => { + const otherParams = { + isBusinessProcessing: false, + timeout: 1000 * 120, + responseType: 'blob', + islongReq: true, + onDownloadProgress: (progressEvent: ProgressEventType) => reqProgress(progressEvent) + }; + return get(urlPath.idcListUrl, params, {...otherParams}); +}; + +/** + * 机房详情接口 + * @param {Object} params 请求需要的参数 +*/ +const idcDetailAPI = (params: ParamDataType['IdcDetailType']): ReturnType => { + return get(urlPath.idcDetailUrl + params.idcid, params, {isBusinessProcessing: false}); +}; + +/** + * 编辑机房接口 + * @param {Object} data 请求需要的参数 +*/ +const editIdcAPI = (data: ParamDataType['EditIdcType']): ReturnType => { + return put(urlPath.editIdcUrl + data.idcId, data, true); +}; + +const idcApiCount = { + idcListAPI, + idcListExportAPI, + idcDetailAPI, + editIdcAPI +}; + +export default idcApiCount; diff --git a/bmp-operation-web/src/api/idc/typeManagement.ts b/bmp-operation-web/src/api/idc/typeManagement.ts new file mode 100644 index 0000000..353803c --- /dev/null +++ b/bmp-operation-web/src/api/idc/typeManagement.ts @@ -0,0 +1,55 @@ +type AddReadonly = {readonly [P in keyof T]: T[P]}; + +type UrlPathType = { + idcListUrl: string; // 机房列表 + idcDetailUrl: string; // 机房详情 + editIdcUrl: string; // 编辑机房 +}; + +// url地址类型 +type TotalUrlPathType = AddReadonly; + +// idc-机房列表类 +type ListType = { + pageNumber: number; + pageSize: number; + isAll: boolean | number; + exportType: string; +}; + +// 编辑机房类 +type EditIdcType = { + idcId: string; + address: string; + iloPassword: string; + iloUser: string; + level: string; + name: string; + switchPassword1: string + switchPassword2: string + switchUser1: string + switchUser2: string + nameEn: string; +}; + +// 接口参数类型 +interface ParamDataType { + IdcListType: Partial & Required<{name: string; level: string}>; + idcListExportType: Omit; + IdcDetailType: Partial<{idcid?: string; show: string;}> + EditIdcType: Required; +}; + +interface RequestType { + CurrencyType: { + isBusinessProcessing: boolean; + url: string; + methods: string; + } +}; + +export { + TotalUrlPathType, + ParamDataType, + RequestType +}; diff --git a/bmp-operation-web/src/api/image/config.ts b/bmp-operation-web/src/api/image/config.ts new file mode 100644 index 0000000..1c13da6 --- /dev/null +++ b/bmp-operation-web/src/api/image/config.ts @@ -0,0 +1,23 @@ +/** + * @file + * @author +*/ + +import {TotalUrlPathType} from './typeManagement'; // url地址类 + +const defaultUrl: string = '/images'; + +// url地址集合 +const urlPath: TotalUrlPathType = { + imagesUrl: defaultUrl, // 镜像列表 + imagesDetailUrl: `${defaultUrl}/`, // 镜像详情 + imageDeviceTypesUrl: `${defaultUrl}/imageDeviceTypes`, // 镜像详情-机型列表、添加机型列表 + imageAddModelUrl: `${defaultUrl}/associatedDeviceType`, // 镜像详情-机型列表、添加机型 + deleteImageModelUrl: `${defaultUrl}/dissociatedDeviceType`, // 镜像详情-删除关联机型 + imageEditUrl: `${defaultUrl}/`, // 镜像编辑 + imagesDeleteUrl: `${defaultUrl}/`, // 删除镜像 + importImageUrl: defaultUrl, // 导入镜像 + imageOssUrl: '/oss/filter' // 镜像oss数据 +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/image/request.ts b/bmp-operation-web/src/api/image/request.ts new file mode 100644 index 0000000..c2cb345 --- /dev/null +++ b/bmp-operation-web/src/api/image/request.ts @@ -0,0 +1,88 @@ +/** + * @file + * @author +*/ +import urlPath from './config'; +import request from 'request/index.ts'; +import {ParamDataType} from './typeManagement'; +const {get, post, put, deleteReq} = request; + +/** + * 镜像列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function imagesAPI(params: ParamDataType['ImagesType']) { + return get(urlPath.imagesUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 镜像列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +export function imagesExportAPI(params: ParamDataType['ImagesType']) { + return get(urlPath.imagesUrl, params, {isBusinessProcessing: false, timeout: 1000 * 120, responseType: 'blob', islongReq: true}); +}; + +/** + * 镜像详情接口 + * @param {Object} params 请求需要的参数 +*/ +export function imagesDetailAPI(params: ParamDataType['ImagesType']) { + return get(urlPath.imagesDetailUrl + params.imageId, params, {isBusinessProcessing: false}); +}; + +/** + * 镜像详情-机型列表-添加机型列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function imageDeviceTypesAPI(params: ParamDataType['ImagesModelType']) { + return get(urlPath.imageDeviceTypesUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 镜像详情-描述编辑接口 + * @param {Object} data 请求需要的参数 +*/ +export function imageEditAPI(data: ParamDataType['ImageEditType']) { + return put(urlPath.imageEditUrl + data.imageId, data, true); +}; + +/** + * 镜像详情-添加机型接口 + * @param {Object} data 请求需要的参数 +*/ +export function imageAddModelAPI(data: ParamDataType['ImageAddModelType']) { + return post(urlPath.imageAddModelUrl, data, true); +}; + +/** + * 镜像详情-移除关联机型接口 + * @param {Object} data 请求需要的参数 +*/ +export function deleteImageModelAPI(data: ParamDataType['DeleteImageModelType']) { + return deleteReq(urlPath.deleteImageModelUrl, data, true); +}; + +/** + * 镜像删除接口 + * @param {Object} data 请求需要的参数 +*/ +export function imagesDeleteAPI(data: ParamDataType['ImagesDeleteType']) { + return deleteReq(urlPath.imagesDeleteUrl + data.imageId, data, true); +}; + +/** + * 导入镜像接口 + * @param {Object} data 请求需要的参数 +*/ +export function importImageAPI(data: ParamDataType['ImportImageType']) { + return post(urlPath.importImageUrl, data, true, {timeout: 1000 * 120, islongReq: true}); +}; + +/** + * 镜像-oss接口 + * @param {Object} params 请求需要的参数 +*/ +export function imageOssAPI(params: ParamDataType['ImageOssType']) { + return get(urlPath.imageOssUrl, params, {isBusinessProcessing: false}); +}; diff --git a/bmp-operation-web/src/api/image/typeManagement.ts b/bmp-operation-web/src/api/image/typeManagement.ts new file mode 100644 index 0000000..4afe34e --- /dev/null +++ b/bmp-operation-web/src/api/image/typeManagement.ts @@ -0,0 +1,76 @@ +type AddReadonly = {readonly [P in keyof T]: T[P]}; + +type UrlPathType = { + imagesUrl: string; // 镜像列表 + imagesDetailUrl: string; // 镜像详情 + imageDeviceTypesUrl: string; // 镜像详情-机型列表-添加机型列表 + imageAddModelUrl: string; // 镜像详情-机型列表-添加机型 + deleteImageModelUrl: string; // 镜像详情-机型列表-移除关联机型 + imageEditUrl: string; // 镜像详情-编辑描述 + imagesDeleteUrl: string; // 删除镜像 + importImageUrl: string; // 导入镜像 + imageOssUrl: string; // 镜像oss数据 +}; + +// url地址类型 +type TotalUrlPathType = AddReadonly; + +// idc-机房列表类 +type ListType = { + pageNumber: number; + pageSize: number; + isAll: boolean | number; + exportType: string; +}; + +type SysPartitionType = { + format: string; + point: string; + size: number; +}; + +interface ImportImage { + imageFile: unknown; + imageName: string; + architecture: string; + description: string; + systemPartition: SysPartitionType[]; + osType: string; + osVersion: string; +}; + +// 接口参数类型 +interface ParamDataType { + ImagesType: Partial & Partial<{imageId: string; imageName: string; deviceTypeId: string; osId: string;}>; + ImagesModelType: { + imageId: string; + architecture: string; + isBind: string; + }; + ImageAddModelType: { + imageId: string; + deviceTypeIds: string; + }; + ImageEditType: {imageId: string; description: string;}; + DeleteImageModelType: { + imageId: string; + deviceTypeId: string; + }; + ImagesDeleteType: Required<{imageId: string;}>; + ImportImageType: ImportImage; + ImageOssType: {}; +}; + +interface RequestType { + CurrencyType: { + isBusinessProcessing: boolean; + url: string; + methods: string; + } +}; + +export { + TotalUrlPathType, + ParamDataType, + RequestType +}; diff --git a/bmp-operation-web/src/api/inBandMonitoring/allAlarmRules/config.ts b/bmp-operation-web/src/api/inBandMonitoring/allAlarmRules/config.ts new file mode 100644 index 0000000..c45f790 --- /dev/null +++ b/bmp-operation-web/src/api/inBandMonitoring/allAlarmRules/config.ts @@ -0,0 +1,17 @@ +/** + * @file + * @author +*/ + +import {TotalUrlPathType} from './typeManagement'; // url地址类 + +const dafaultUrl: string = '/monitorRule/describeRules'; + +// url地址集合 +const urlPath: TotalUrlPathType = { + describeRulesUrl: dafaultUrl, // 全部报价规则列表 + describeRulesExportUrl: dafaultUrl, // 全部报价规则列表导出 + describeRulesDetailUrl: '/monitorRule/describeRule' // 全部报警规则详情 +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/inBandMonitoring/allAlarmRules/request.ts b/bmp-operation-web/src/api/inBandMonitoring/allAlarmRules/request.ts new file mode 100644 index 0000000..6c00b1f --- /dev/null +++ b/bmp-operation-web/src/api/inBandMonitoring/allAlarmRules/request.ts @@ -0,0 +1,44 @@ +/** + * @file + * @author +*/ + +import urlPath from './config'; +import request from 'request/index.ts'; +const {get} = request; + +/** + * 全部报警规则列表接口 + * @param {Object} params 请求需要的参数 +*/ +const describeRulesAPI = (params: Parameters): ReturnType => { + return get(urlPath.describeRulesUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 全部报警规则列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +const describeRulesExportAPI = (params: Parameters): ReturnType => { + const otherParams = { + isBusinessProcessing: false, + timeout: 1000 * 120, + responseType: 'blob', + islongReq: true + }; + return get(urlPath.describeRulesExportUrl, params, {...otherParams}); +}; + +/** + * 全部报警规则详情接口 + * @param {Object} params 请求需要的参数 +*/ +const describeRulesDetailAPI = (params: Parameters): ReturnType => { + return get(urlPath.describeRulesDetailUrl, params, {isBusinessProcessing: false}); +}; + +export { + describeRulesAPI, + describeRulesExportAPI, + describeRulesDetailAPI +}; diff --git a/bmp-operation-web/src/api/inBandMonitoring/allAlarmRules/typeManagement.ts b/bmp-operation-web/src/api/inBandMonitoring/allAlarmRules/typeManagement.ts new file mode 100644 index 0000000..96d0a89 --- /dev/null +++ b/bmp-operation-web/src/api/inBandMonitoring/allAlarmRules/typeManagement.ts @@ -0,0 +1,39 @@ +type AddReadonly = {readonly [P in keyof T]: T[P]}; + +type UrlPathType = { + describeRulesUrl: string; // 全部报警规则列表 + describeRulesExportUrl: string; // 全部报警规则导出 + describeRulesDetailUrl: string; // 全部报警规则详情 +}; + +// url地址类型 +type TotalUrlPathType = AddReadonly; + +// idc-机房列表类 +type ListType = { + pageNumber: number; + pageSize: number; + isAll: boolean | number; + exportType: string; +}; + + +// 接口参数类型 +interface ParamDataType { + IdcListType: Partial & Required<{name: string; level: string}>; + idcListExportType: Omit; +}; + +interface RequestType { + CurrencyType: { + isBusinessProcessing: boolean; + url: string; + methods: string; + } +}; + +export { + TotalUrlPathType, + ParamDataType, + RequestType +}; diff --git a/bmp-operation-web/src/api/inBandMonitoring/historyAlarmInfo/config.ts b/bmp-operation-web/src/api/inBandMonitoring/historyAlarmInfo/config.ts new file mode 100644 index 0000000..d4c6c12 --- /dev/null +++ b/bmp-operation-web/src/api/inBandMonitoring/historyAlarmInfo/config.ts @@ -0,0 +1,16 @@ +/** + * @file + * @author +*/ + +import {TotalUrlPathType} from './typeManagement'; // url地址类 + +const dafaultUrl: string = '/monitorAlert/describeAlerts'; + +// url地址集合 +const urlPath: TotalUrlPathType = { + describeAlertsUrl: dafaultUrl, // 报警历史列表 + describeAlertsExportUrl: dafaultUrl // 报警历史列表导出 +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/inBandMonitoring/historyAlarmInfo/request.ts b/bmp-operation-web/src/api/inBandMonitoring/historyAlarmInfo/request.ts new file mode 100644 index 0000000..4db8198 --- /dev/null +++ b/bmp-operation-web/src/api/inBandMonitoring/historyAlarmInfo/request.ts @@ -0,0 +1,35 @@ +/** + * @file + * @author +*/ + +import urlPath from './config'; +import request from 'request/index.ts'; +const {get} = request; + +/** + * 报警历史列表接口 + * @param {Object} params 请求需要的参数 +*/ +const describeAlertsAPI = (params: Parameters): ReturnType => { + return get(urlPath.describeAlertsUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 报警历史列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +const describeAlertsExportAPI = (params: Parameters): ReturnType => { + const otherParams = { + isBusinessProcessing: false, + timeout: 1000 * 120, + responseType: 'blob', + islongReq: true + }; + return get(urlPath.describeAlertsExportUrl, params, {...otherParams}); +}; + +export { + describeAlertsAPI, + describeAlertsExportAPI +}; diff --git a/bmp-operation-web/src/api/inBandMonitoring/historyAlarmInfo/typeManagement.ts b/bmp-operation-web/src/api/inBandMonitoring/historyAlarmInfo/typeManagement.ts new file mode 100644 index 0000000..23108a6 --- /dev/null +++ b/bmp-operation-web/src/api/inBandMonitoring/historyAlarmInfo/typeManagement.ts @@ -0,0 +1,38 @@ +type AddReadonly = {readonly [P in keyof T]: T[P]}; + +type UrlPathType = { + describeAlertsUrl: string; // 报警历史列表 + describeAlertsExportUrl: string; // 报警历史导出 +}; + +// url地址类型 +type TotalUrlPathType = AddReadonly; + +// idc-机房列表类 +type ListType = { + pageNumber: number; + pageSize: number; + isAll: boolean | number; + exportType: string; +}; + + +// 接口参数类型 +interface ParamDataType { + IdcListType: Partial & Required<{name: string; level: string}>; + idcListExportType: Omit; +}; + +interface RequestType { + CurrencyType: { + isBusinessProcessing: boolean; + url: string; + methods: string; + } +}; + +export { + TotalUrlPathType, + ParamDataType, + RequestType +}; diff --git a/bmp-operation-web/src/api/inBandMonitoring/resourceMonitor/config.ts b/bmp-operation-web/src/api/inBandMonitoring/resourceMonitor/config.ts new file mode 100644 index 0000000..5e160b1 --- /dev/null +++ b/bmp-operation-web/src/api/inBandMonitoring/resourceMonitor/config.ts @@ -0,0 +1,14 @@ +/** + * @file + * @author +*/ + +import {TotalUrlPathType} from './typeManagement'; // url地址类 + + +// url地址集合 +const urlPath: TotalUrlPathType = { + monitorDataUrl: '/monitorData' // 监控图表 +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/inBandMonitoring/resourceMonitor/request.ts b/bmp-operation-web/src/api/inBandMonitoring/resourceMonitor/request.ts new file mode 100644 index 0000000..497c9e1 --- /dev/null +++ b/bmp-operation-web/src/api/inBandMonitoring/resourceMonitor/request.ts @@ -0,0 +1,17 @@ +/** + * @file + * @author +*/ + +import urlPath from './config'; +import request from 'request/index.ts'; +const {get} = request; + + +/** + * 带内监控-监控图表 + * @param {Object} params 请求需要的参数 +*/ +export function monitorDataAPI(params: Parameters): ReturnType { + return get(urlPath.monitorDataUrl, params, {isBusinessProcessing: false}); +}; diff --git a/bmp-operation-web/src/api/inBandMonitoring/resourceMonitor/typeManagement.ts b/bmp-operation-web/src/api/inBandMonitoring/resourceMonitor/typeManagement.ts new file mode 100644 index 0000000..f426c98 --- /dev/null +++ b/bmp-operation-web/src/api/inBandMonitoring/resourceMonitor/typeManagement.ts @@ -0,0 +1,12 @@ +type AddReadonly = {readonly [P in keyof T]: T[P]}; + +type UrlPathType = { + monitorDataUrl: string; // 监控图表 +}; + +// url地址类型 +type TotalUrlPathType = AddReadonly; + +export { + TotalUrlPathType +}; diff --git a/bmp-operation-web/src/api/login/config.ts b/bmp-operation-web/src/api/login/config.ts new file mode 100644 index 0000000..c456a8b --- /dev/null +++ b/bmp-operation-web/src/api/login/config.ts @@ -0,0 +1,15 @@ +/** + * @file + * @author +*/ + +import {TotalUrlPathType} from './typeManagement'; // url地址类 + +// url地址集合 +const urlPath: TotalUrlPathType = { + loginUrl: '/login', // 登录 + userPurviewUrl: '/roles/roleInfo/current', // 用户权限 + loginOutUrl: '/logout' // 退出登录 +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/login/request.ts b/bmp-operation-web/src/api/login/request.ts new file mode 100644 index 0000000..b6a3445 --- /dev/null +++ b/bmp-operation-web/src/api/login/request.ts @@ -0,0 +1,41 @@ +/** + * @file + * @author +*/ + +import urlPath from './config'; +import request from 'request/index.ts'; +import {ParamDataType} from './typeManagement'; +const {get, post} = request; + +/** + * 登录接口 + * @param {Object} data 请求需要的参数 +*/ +const loginAPI = (data: ParamDataType['LoginType']): ReturnType => { + return post(urlPath.loginUrl, data, false); +}; + +/** + * 用户权限接口 + * @param {Object} params 请求需要的参数 +*/ +const userPurviewAPI = (params: ParamDataType['UserPurviewType']): ReturnType => { + return get(urlPath.userPurviewUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 退出登录接口 + * @param {Object} data 请求需要的参数 +*/ +const loginOutAPI = (data: ParamDataType['LoginOutType']): ReturnType => { + return post(urlPath.loginOutUrl, data, false); +}; + +const loginUserApiCount = { + loginAPI, + loginOutAPI, + userPurviewAPI +}; + +export default loginUserApiCount; diff --git a/bmp-operation-web/src/api/login/typeManagement.ts b/bmp-operation-web/src/api/login/typeManagement.ts new file mode 100644 index 0000000..8a0b0d0 --- /dev/null +++ b/bmp-operation-web/src/api/login/typeManagement.ts @@ -0,0 +1,36 @@ +type AddReadonly = {readonly [P in keyof T]: T[P]}; + +type UrlPathType = { + loginUrl: string; // 登录 + userPurviewUrl: string; // 用户权限 + loginOutUrl: string; // 退出登录 +}; + +// url地址类型 +type TotalUrlPathType = AddReadonly; + +type UserInfo = { + username: string; + password: string; +}; + +// 接口参数类型 +interface ParamDataType { + LoginType: Required; + UserPurviewType: {}; + LoginOutType: {}; +}; + +interface RequestType { + CurrencyType: { + isBusinessProcessing: boolean; + url: string; + methods: string; + }; +}; + +export { + TotalUrlPathType, + ParamDataType, + RequestType +}; diff --git a/bmp-operation-web/src/api/message/config.ts b/bmp-operation-web/src/api/message/config.ts new file mode 100644 index 0000000..adae882 --- /dev/null +++ b/bmp-operation-web/src/api/message/config.ts @@ -0,0 +1,24 @@ +/** + * @file + * @author +*/ + +const dafaultUrl: string = '/messages'; +// const defaultUrl2: string = '/v1'; + +// url地址集合 +const urlPath = { + messageListUrl: dafaultUrl, // 消息列表 + statisticUrl: `${dafaultUrl}/statistic`, // 获取message总数和未读数 + messageTypesUrl: `${dafaultUrl}/getMessageTypes`, // 获取消息类型、子类型 + hasUnreadMessageUrl: `${dafaultUrl}/hasUnreadMessage`, // 获取有没有未读消息 + messageByIdUrl: `${dafaultUrl}/getMessageById`, // 获取消息详情 + doReadUrl: `${dafaultUrl}/doRead`, // 消息标为已读 + deleteUrl: `${dafaultUrl}/delete`, // 删除消息 + describeMailUrl: `${dafaultUrl}/describeMail`, // 读消息设置 + dialMailUrl: `${dafaultUrl}/dialMail`, // 消息设置-测试邮箱信息接口 + saveMailUrl: `${dafaultUrl}/saveMail`, // 消息设置-保存接口 + savelsPushMailUrl: `${dafaultUrl}/saveIsPushMail`, // 是否关联邮箱推送 +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/message/request.ts b/bmp-operation-web/src/api/message/request.ts new file mode 100644 index 0000000..d73b1b0 --- /dev/null +++ b/bmp-operation-web/src/api/message/request.ts @@ -0,0 +1,139 @@ +/** + * @file + * @author +*/ + +import urlPath from './config'; +import request from 'request/index.ts'; +import store from 'store/index.ts'; + +const {get, deleteReq, post, put} = request; +const reqProgress = (progressEvent: any) => { + // if (progressEvent.lengthComputable) { + // const percentComplete = (progressEvent.loaded / progressEvent.total) * 100; + // let val:number = 0; + // if (Number(percentComplete.toFixed(2)) >= 100) { + // val = 100; + // } + // else { + // val = Number(percentComplete.toFixed(2)); + // } + // store.progressInfo.progressNum = val; + // } + if (progressEvent.lengthComputable) { + const percentComplete = (progressEvent.loaded / progressEvent.total) * 100; + store.progressInfo.progressNum = Math.min(100, Number(percentComplete.toFixed(2))); + } +} +/** + * 消息列表接口 + * @param {Object} params 请求需要的参数 +*/ +const messageListAPI = (params: Parameters): ReturnType => { + return get(urlPath.messageListUrl, params, {isBusinessProcessing: false, islongReq: true}); +}; + +/** + * 消息列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +const messageExportAPI = (params: Parameters): ReturnType => { + return get(urlPath.messageListUrl, params, {isBusinessProcessing: false, timeout: 1000 * 120, responseType: 'blob', islongReq: true, onDownloadProgress: (progressEvent: any) => reqProgress(progressEvent)}); +}; + +/** + * 消息列表总数和未读数接口 + * @param {Object} params 请求需要的参数 +*/ +const messagesStatisticAPI = (params: {}): ReturnType => { + return get(urlPath.statisticUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 获取消息类型、子类型接口 + * @param {Object} params 请求需要的参数 +*/ +const messageTypesAPI = (params: {}): ReturnType => { + return get(urlPath.messageTypesUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 获取有没有未读消息 + * @param {Object} params 请求需要的参数 +*/ +const hasUnreadMessageAPI = (params: {}): ReturnType => { + return get(urlPath.hasUnreadMessageUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 获取消息详情id + * @param {Object} params 请求需要的参数 +*/ +const messageByIdAPI = (params: {messageId: string}): ReturnType => { + return get(urlPath.messageByIdUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 消息标为已读 + * @param {Object} data 请求需要的参数 +*/ +const doReadAPI = (data: {messageIds: [string]}): ReturnType => { + return put(urlPath.doReadUrl, data, false); +}; + +/** + * 删除消息接口 + * @param {Object} data 请求需要的参数 +*/ +const deleteAPI = (data: Parameters): ReturnType => { + return deleteReq(urlPath.deleteUrl, data, true); +}; + +/** + * 读消息设置 + * @param {Object} params 请求需要的参数 +*/ +const describeMailAPI = (params: {}): ReturnType => { + return get(urlPath.describeMailUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 消息设置-校验邮箱信息 + * @param {Object} data 请求需要的参数 +*/ +const dialMailAPI = (data: {server_addr: string; server_port: string; admin_addr: string; admin_pass: string; to: string;}) => { + return post(urlPath.dialMailUrl, data, true, {timeout: 1000 * 30}); +}; + +/** + * 消息设置-保存消息设置 + * @param {Object} data 请求需要的参数 +*/ +const saveMailAPI = (data: Parameters): ReturnType => { + return post(urlPath.saveMailUrl, data, true); +}; + +/** + * 消息设置-是否关联邮箱推送 + * @param {Object} data 请求需要的参数 +*/ +const savelsPushMailAPI = (data: {is_push: string;}) => { + return post(urlPath.savelsPushMailUrl, data, true); +}; + +const messageApiCount = { + messageListAPI, + messageExportAPI, + messagesStatisticAPI, + messageTypesAPI, + hasUnreadMessageAPI, + messageByIdAPI, + doReadAPI, + deleteAPI, + describeMailAPI, + dialMailAPI, + saveMailAPI, + savelsPushMailAPI +}; + +export default messageApiCount; diff --git a/bmp-operation-web/src/api/message/typeManagement.ts b/bmp-operation-web/src/api/message/typeManagement.ts new file mode 100644 index 0000000..e69de29 diff --git a/bmp-operation-web/src/api/model/config.ts b/bmp-operation-web/src/api/model/config.ts new file mode 100644 index 0000000..7d0e3a6 --- /dev/null +++ b/bmp-operation-web/src/api/model/config.ts @@ -0,0 +1,24 @@ +/** + * @file + * @author +*/ + +import {TotalUrlPathType} from './typeManagement'; // url地址类 + +const defaultUrl: string = '/deviceTypes'; + +// url地址集合 +const urlPath: TotalUrlPathType = { + modelListUrl: defaultUrl, // 机型列表 + modelDetailUrl: `${defaultUrl}/queryDeviceType/`, // 机型详情 + relationImageListUrl: `${defaultUrl}/deviceTypeImage`, // 机型详情-关联镜像列表 + addImageUrl: `${defaultUrl}/associatedImage`, // 机型详情-添加镜像 + addModelUrl: defaultUrl, // 添加机型 + editModelUrl: `${defaultUrl}/`, // 编辑机型 + deleteImageUrl: `${defaultUrl}/dissociatedImage`, // 删除关联镜像 + deleteModelUrl: `${defaultUrl}/`, // 删除机型 + getRaidsUrl: '/raids', // 获取raid + filterListUrl: '/filterList', // 筛选list +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/model/request.ts b/bmp-operation-web/src/api/model/request.ts new file mode 100644 index 0000000..cb59f89 --- /dev/null +++ b/bmp-operation-web/src/api/model/request.ts @@ -0,0 +1,112 @@ +/** + * @file + * @author +*/ +import urlPath from './config'; +import request from 'request/index.ts'; +import {ParamDataType} from './typeManagement'; +const {get, post, put, deleteReq} = request; + +/** + * 机型列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function modelListAPI(params: ParamDataType['ModeListType']): ReturnType { + return get(urlPath.modelListUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 机型列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +export function modelListExportAPI(params: ParamDataType['ModelListExportType']): ReturnType { + return get(urlPath.modelListUrl, params, {isBusinessProcessing: false, timeout: 1000 * 120, responseType: 'blob', islongReq: true}); +}; + +/** + * 机型详情接口 + * @param {Object} params 请求需要的参数 +*/ +export function modelDetailAPI(params: ParamDataType['ModelDetailType']): ReturnType { + return get(urlPath.modelDetailUrl + params.id, params, {isBusinessProcessing: false}); +}; + +/** + * 关联镜像列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function relationImageListAPI(params: ParamDataType['RelationImageListType']): ReturnType { + return get(urlPath.relationImageListUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 添加镜像接口 + * @param {Object} data 请求需要的参数 +*/ +export function addImageAPI(data: ParamDataType['AddImageType']): ReturnType { + return post(urlPath.addImageUrl, data, true); +}; + +/** + * 添加机型接口 + * @param {Object} data 请求需要的参数 +*/ +export function addModelAPI(data: ParamDataType['ModelCurrencyType']): ReturnType { + return put(urlPath.addModelUrl, data, true); +}; + +/** + * 编辑机型接口 + * @param {Object} data 请求需要的参数 +*/ +export function editModelAPI(data: ParamDataType['ModelCurrencyType']): ReturnType { + return put(urlPath.editModelUrl + data.deviceTypeId, data, true); +}; + +/** + * 删除关联镜像接口 + * @param {Object} data 请求需要的参数 +*/ +export function deleteImageAPI(data: ParamDataType['DeleteImageType']): ReturnType { + return post(urlPath.deleteImageUrl, data, true); +}; + +/** + * 删除机型接口 + * @param {Object} data 请求需要的参数 +*/ +export function deleteModelAPI(data: ParamDataType['DeleteModelType']): ReturnType { + return deleteReq(urlPath.deleteModelUrl + data.id, data, true); +}; + +/** + * raid接口 + * @param {Object} params 请求需要的参数 +*/ +export function raidsAPI(params: ParamDataType['RaidsType']): ReturnType { + return get(urlPath.getRaidsUrl, params, {isBusinessProcessing: true}); +}; + +/** + * filter接口 + * @param {Object} params 请求需要的参数 +*/ +export function getFilterListAPI(params: ParamDataType['FilterListType']): ReturnType { + return get(urlPath.filterListUrl, params, {isBusinessProcessing: false}); +}; + +const modelApiCount = { + modelListAPI, + modelListExportAPI, + modelDetailAPI, + relationImageListAPI, + addImageAPI, + addModelAPI, + editModelAPI, + deleteImageAPI, + deleteModelAPI, + raidsAPI, + getFilterListAPI +}; + +export default modelApiCount; diff --git a/bmp-operation-web/src/api/model/typeManagement.ts b/bmp-operation-web/src/api/model/typeManagement.ts new file mode 100644 index 0000000..c58e16b --- /dev/null +++ b/bmp-operation-web/src/api/model/typeManagement.ts @@ -0,0 +1,94 @@ +type AddReadonly = {readonly [P in keyof T]: T[P]}; + +type UrlPathType = { + modelListUrl: string; // 机型列表 + modelDetailUrl: string; // 机型详情 + relationImageListUrl: string; // 机型详情-关联镜像列表 + addImageUrl: string; // 机型详情-添加镜像 + addModelUrl: string; // 添加机型 + editModelUrl: string; // 编辑机型 + deleteImageUrl: string; // 删除关联镜像 + deleteModelUrl: string; // 删除机型 + getRaidsUrl: string; // raid + filterListUrl: string; // filter List +}; + +// url地址类型 +type TotalUrlPathType = AddReadonly; + +// idc-机房列表类 +type ListType = { + pageNumber: number; + pageSize: number; + isAll: boolean | number; + exportType: string; +}; + +type ModelRequiredType = { + deviceTypeId: string; + name: string; + deviceType: string; + deviceSeries: string; + architecture: string; + height: string; + nicAmount: string | number; + nicRate: string; + interfaceMode: string; + systemVolumeType: string; + systemVolumeInterfaceType: string; + systemVolumeSize: string | number; + systemVolumeUnit: string; + systemVolumeAmount: string | number; + gpuAmount: string | number; + gpuManufacturer: string; + gpuModel: string; + dataVolumeType: string; + dataVolumeInterfaceType: string; + dataVolumeSize: string | number; + dataVolumeUnit: string; + dataVolumeAmount: string | number; + raidId: string; +}; + +type ModelPartialType = { + id: string; + idcId: string; + description: string; + cpuManufacturer: string; + cpuModel: string; + cpuAmount: string | number; + cpuCores: string | number; + cpuFrequency: string | number; + memType: string; + memSize: string; + memAmount: string | number; + memFrequency: string; +}; + +// 接口参数类型 +interface ParamDataType { + ModeListType: Partial & Partial<{idcId: string; deviceSeries: string;}>; + ModelListExportType: Partial & Partial<{idcId: string; deviceSeries: string;}>; + ModelDetailType: Required<{id: string;}>; + RelationImageListType: Required<{deviceTypeId: string}> | Partial<{imageId: string;}>; + AddImageType: Required; + ModelCurrencyType: Required & Partial; + DeleteImageType: Required; + DeleteModelType: Required; + RaidsType: {}; + FilterListType: {}; +}; + +interface RequestType { + CurrencyType: { + isBusinessProcessing: boolean; + url: string; + methods: string; + } +}; + +export { + TotalUrlPathType, + ParamDataType, + RequestType +}; diff --git a/bmp-operation-web/src/api/public/config.ts b/bmp-operation-web/src/api/public/config.ts new file mode 100644 index 0000000..47c7fde --- /dev/null +++ b/bmp-operation-web/src/api/public/config.ts @@ -0,0 +1,25 @@ +/** + * @file + * @author +*/ + +import {methodsTotal} from 'utils/index.ts'; +import {TotalUrlPathType} from './typeManagement'; // url地址类 + +// url地址集合 +const urlPath: TotalUrlPathType = { + resourcesUrl: '/resources', // 精确查询 + securityVerificationUrl: '/users/login/validate', // 安全验证 + customListUrl: '/custom/getCustomInfo', // 自定义列表 + setCustomListUrl: '/custom/setCustomInfo', // 设置自定义列表 + surveillanceCustomListUrl: methodsTotal.humpSplit('/v1/oobAlert/custom/getCustomInfo'), // 监控自定义列表 + surveillanceSetCustomListUrl: methodsTotal.humpSplit('/v1/oobAlert/custom/setCustomInfo'), // 监控设置自定义列表 + getOssUrl: '/oss', // oss数据 + queryImagesUrl: '/images/queryImagesByDeviceType', // images类型 + systemRaidsUrl: '/raids/queryRaidsByDeviceTypeIDAndVolumeType', // raids + querySystemPartitionUrl: '/partition/queryDefaultSystemPartitions', // 系统盘分区 + keyInfoUrl: '/keypair', // 密钥 + localUrl: '/user/local ', // 权限列表 +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/public/request.ts b/bmp-operation-web/src/api/public/request.ts new file mode 100644 index 0000000..aed247d --- /dev/null +++ b/bmp-operation-web/src/api/public/request.ts @@ -0,0 +1,106 @@ +/** + * @file + * @author +*/ + +import urlPath from './config'; +import request from 'request/index.ts'; +import {ParamDataType} from './typeManagement'; +const {get, post} = request; + +/** + * 精确查询 + * @param {Object} params 请求需要的参数 +*/ +export function resourcesAPI(params: ParamDataType['ResourcesType']): ReturnType { + return get(urlPath.resourcesUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 安全验证接口 + * @param {Object} data 请求需要的参数 +*/ +export function securityVerificationAPI(data: ParamDataType['SecurityVerificationType']): ReturnType { + return post(urlPath.securityVerificationUrl, data, false); +}; + +/** + * 自定义列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function customListAPI(params: ParamDataType['CustomListType']): ReturnType { + return get(urlPath.customListUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 设置自定义列表接口 + * @param {Object} data 请求需要的参数 +*/ +export function setCustomListAPI(data: ParamDataType['SetCustomListType']): ReturnType { + return post(urlPath.setCustomListUrl, data, true); +}; + +/** + * 监控自定义列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function surveillanceCustomListAPI(params: ParamDataType['CustomListType']): ReturnType { + return get(urlPath.surveillanceCustomListUrl, params, {baseURL: '/oob-alert', isBusinessProcessing: false}); +}; + +/** + * 监控设置自定义列表接口 + * @param {Object} data 请求需要的参数 +*/ +export function surveillanceSetCustomListAPI(data: ParamDataType['SetCustomListType']): ReturnType { + return post(urlPath.surveillanceSetCustomListUrl, data, true, {baseURL: '/oob-alert'}); +}; + + +/** + * oss接口 + * @param {Object} params 请求需要的参数 +*/ +export function getOssAPI(params: ParamDataType['OssTyoe']): ReturnType { + return get(urlPath.getOssUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 镜像类型接口 + * @param {Object} params 请求需要的参数 +*/ +export function queryImagesAPI(params: ParamDataType['QueryImagesType']): ReturnType { + return get(urlPath.queryImagesUrl, params, {isBusinessProcessing: true}); +}; + +/** + * raids接口 + * @param {Object} params 请求需要的参数 +*/ +export function systemRaidsAPI(params: ParamDataType['SystemRaidsType']): ReturnType { + return get(urlPath.systemRaidsUrl, params, {isBusinessProcessing: true}); +}; + +/** + * 系统盘分区接口 + * @param {Object} params 请求需要的参数 +*/ +export function querySystemPartitionAPI(params: ParamDataType['SystemPartitionType']): ReturnType { + return get(urlPath.querySystemPartitionUrl, params, {isBusinessProcessing: true}); +}; + +/** + * 密钥信息接口 + * @param {Object} params 请求需要的参数 +*/ +export function keyInfoAPI(params: ParamDataType['KeyInfoType']): ReturnType { + return get(urlPath.keyInfoUrl, params, {isBusinessProcessing: true}); +}; + +/** + * 权限列表 + * @param {Object} params 请求需要的参数 +*/ +export function localAPI(params: Parameters): ReturnType { + return get(urlPath.localUrl, params, {isBusinessProcessing: false}); +}; diff --git a/bmp-operation-web/src/api/public/typeManagement.ts b/bmp-operation-web/src/api/public/typeManagement.ts new file mode 100644 index 0000000..305a63a --- /dev/null +++ b/bmp-operation-web/src/api/public/typeManagement.ts @@ -0,0 +1,71 @@ +type SetType = T extends {} ? any : T; + +type AddReadonly = {readonly [P in keyof T]: T[P]}; + +type UrlPathType = { + resourcesUrl: string; // 精确查询 + securityVerificationUrl: string; // 安全验证 + customListUrl: string; // 自定义列表 + setCustomListUrl: string; // 设置自定义列表 + surveillanceCustomListUrl: string; // 监控自定义列表 + surveillanceSetCustomListUrl: string; // 监控设置自定义列表 + getOssUrl: string; // oss数据 + queryImagesUrl: string; // 镜像类型 + systemRaidsUrl: string; // raids + querySystemPartitionUrl: string; // 系统盘分区 + keyInfoUrl: string; // 密钥信息 + localUrl: string; // 权限列表 +}; + +type UserInfo = { + username: string; + password: string; +}; + +// url地址类型 +type TotalUrlPathType = AddReadonly; + +// oss数据类 +type OssDataType = { + osName: string; + osType: string; + platform: string; + osVersion: string; + isAll: string | number; +}; + +// 接口参数类型 +interface ParamDataType { + ResourcesType: Partial<{ + name: string; + userName: string; + imageName: string; + deviceType: string; + }>; + SecurityVerificationType: Required; + SetCustomListType: Required<{pageKey: string; pageValue: SetType<{}>;}>; + CustomListType: Omit; + OssTyoe: Partial; + QueryImagesType: {idcId: string; deviceTypeId: string;}; + SystemRaidsType: {deviceTypeId: string; volumeType: string;}; + SystemPartitionType: {deviceTypeId: string; imageId: string;}; + KeyInfoType: {isAll: string;}; +}; + +// 请求类型 +interface ReqType { + CurrencyType: { + isBusinessProcessing: boolean; + url: string; + methods: string; + } +}; + +// 请求类型 +type RequestType = Required; + +export { + RequestType, + ParamDataType, + TotalUrlPathType +}; diff --git a/bmp-operation-web/src/api/role/config.ts b/bmp-operation-web/src/api/role/config.ts new file mode 100644 index 0000000..a544767 --- /dev/null +++ b/bmp-operation-web/src/api/role/config.ts @@ -0,0 +1,13 @@ +/** + * @file + * @author +*/ + +import {TotalUrlPathType} from './typeManagement'; // url地址类 + +// url地址集合 +const urlPath: TotalUrlPathType = { + roleListUrl: '/roles' // 角色列表 +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/role/request.ts b/bmp-operation-web/src/api/role/request.ts new file mode 100644 index 0000000..be18898 --- /dev/null +++ b/bmp-operation-web/src/api/role/request.ts @@ -0,0 +1,23 @@ +/** + * @file + * @author +*/ + +import urlPath from './config'; +import request from 'request/index.ts'; +import {ParamDataType} from './typeManagement'; +const {get} = request; + +/** + * 角色列表接口 + * @param {Object} params 请求需要的参数 +*/ +const roleListAPI = (params: ParamDataType['roleListType']): ReturnType => { + return get(urlPath.roleListUrl, params, {isBusinessProcessing: true}); +}; + +const roleApiCount = { + roleListAPI +}; + +export default roleApiCount; diff --git a/bmp-operation-web/src/api/role/typeManagement.ts b/bmp-operation-web/src/api/role/typeManagement.ts new file mode 100644 index 0000000..6b7a245 --- /dev/null +++ b/bmp-operation-web/src/api/role/typeManagement.ts @@ -0,0 +1,46 @@ +type AddReadonly = {readonly [P in keyof T]: T[P]}; + +type UrlPathType = { + roleListUrl: string; // 角色列表 +}; + +// url地址类型 +type TotalUrlPathType = AddReadonly; + +/** + * idc-机房列表类 +*/ +type ListType = { + pageNumber: number; + pageSize: number; + isAll: boolean | number; + exportType: string; +}; + +/** + * 接口参数类型 +*/ +interface ParamDataType { + roleListType: ListType; +}; + +/** + * 请求类型 +*/ +interface ReqType { + CurrencyType: { + isBusinessProcessing: boolean; + url: string; + methods: string; + params: ParamDataType['roleListType']; + } +}; + +// 请求类型 +type RequestType = Required; + +export { + RequestType, + ParamDataType, + TotalUrlPathType +}; diff --git a/bmp-operation-web/src/api/surveillance/faultLog/config.ts b/bmp-operation-web/src/api/surveillance/faultLog/config.ts new file mode 100644 index 0000000..bf4f699 --- /dev/null +++ b/bmp-operation-web/src/api/surveillance/faultLog/config.ts @@ -0,0 +1,18 @@ +/** + * @file + * @author +*/ + +import {methodsTotal} from 'utils/index.ts'; +import {TotalUrlPathType} from './typeManagement'; // url地址类 + +const defaultUrl: string = methodsTotal.humpSplit('/v1/oobAlert/logs'); + +// url地址集合 +const urlPath: TotalUrlPathType = { + faultLogUrl: defaultUrl, // 故障报警日志 + faultLogExportUrl: defaultUrl, // 故障报警日志导出 + faultLogDealUrl: `${defaultUrl}/deal`, // 故障报警日志处理 +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/surveillance/faultLog/request.ts b/bmp-operation-web/src/api/surveillance/faultLog/request.ts new file mode 100644 index 0000000..3286c29 --- /dev/null +++ b/bmp-operation-web/src/api/surveillance/faultLog/request.ts @@ -0,0 +1,43 @@ +/** + * @file + * @author +*/ + +import urlPath from './config'; +import request from 'request/index.ts'; +import {ParamDataType} from './typeManagement'; +const {get, post} = request; + +/** + * 规则报警日志列表接口 + * @param {Object} params 请求需要的参数 +*/ +const faultLogAPI = (params: ParamDataType['faultLogListType']): ReturnType => { + return get(urlPath.faultLogUrl, params, {baseURL: '/oob-alert', isBusinessProcessing: false, timeout: 1000 * 20, islongReq: true}); +}; + +/** + * 故障报警日志列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +const faultLogExportAPI = (params: ParamDataType['faultLogExportType']): ReturnType => { + return get(urlPath.faultLogExportUrl, params, {baseURL: '/oob-alert', isBusinessProcessing: false, responseType: 'blob', timeout: 1000 * 120, islongReq: true}); +}; + + +/** + * 故障报警日志处理接口 + * @param {Object} data 请求需要的参数 +*/ +const faultLogDealAPI = (data: ParamDataType['faultLogDealType']): ReturnType => { + return post(urlPath.faultLogDealUrl, data, false, {baseURL: '/oob-alert'}); +}; + + +const faultLogApiCount = { + faultLogAPI, + faultLogExportAPI, + faultLogDealAPI +}; + +export default faultLogApiCount; diff --git a/bmp-operation-web/src/api/surveillance/faultLog/typeManagement.ts b/bmp-operation-web/src/api/surveillance/faultLog/typeManagement.ts new file mode 100644 index 0000000..f27c7e6 --- /dev/null +++ b/bmp-operation-web/src/api/surveillance/faultLog/typeManagement.ts @@ -0,0 +1,49 @@ +type AddReadonly = {readonly [P in keyof T]: T[P]}; + +type UrlPathType = { + faultLogUrl: string; // 故障报警日志 + faultLogExportUrl: string; // 故障报警日志导出 + faultLogDealUrl: string; // 故障报警日志处理 +}; + +// url地址类型 +type TotalUrlPathType = AddReadonly; + +/** + * idc-机房列表类 +*/ +type ListType = { + pageNumber: number; + pageSize: number; + isAll: boolean | number; + exportType: string; +}; + +/** + * 接口参数类型 +*/ +interface ParamDataType { + faultLogListType: ListType; + faultLogExportType: Omit; + faultLogDealType: {logid: number}; +}; + +/** + * 请求类型 +*/ +interface ReqType { + CurrencyType: { + isBusinessProcessing: boolean; + url: string; + methods: string; + } +}; + +// 请求类型 +type RequestType = Required; + +export { + RequestType, + ParamDataType, + TotalUrlPathType +}; diff --git a/bmp-operation-web/src/api/surveillance/faultRule/config.ts b/bmp-operation-web/src/api/surveillance/faultRule/config.ts new file mode 100644 index 0000000..4372af7 --- /dev/null +++ b/bmp-operation-web/src/api/surveillance/faultRule/config.ts @@ -0,0 +1,22 @@ +/** + * @file + * @author +*/ + +import {methodsTotal} from 'utils/index.ts'; +import {TotalUrlPathType} from './typeManagement'; // url地址类 + +const defaultPath: string = methodsTotal.humpSplit('/v1/oobAlert/rules'); + +// url地址集合 +const urlPath: TotalUrlPathType = { + faultRulesUrl: defaultPath, // 故障报警规则 + faultRulesExportUrl: defaultPath, // 故障报警规则导出 + faultPushUrl: `${defaultPath}/${methodsTotal.humpSplit('changePush')}`, // 故障推送push + faultUseUrl: `${defaultPath}/${methodsTotal.humpSplit('changeUse')}`, // 故障启用禁用 + faultResetUrl: `${defaultPath}/reset`, // 恢复默认设置 + faultLevelUrl: `${defaultPath}/${methodsTotal.humpSplit('alertLevelList')}`, // 故障等级列表 + faultSpecUrl: `${defaultPath}/${methodsTotal.humpSplit('alertSpecList')}`, // 故障配件列表 +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/surveillance/faultRule/request.ts b/bmp-operation-web/src/api/surveillance/faultRule/request.ts new file mode 100644 index 0000000..d348de4 --- /dev/null +++ b/bmp-operation-web/src/api/surveillance/faultRule/request.ts @@ -0,0 +1,65 @@ +/** + * @file + * @author +*/ + +import urlPath from './config'; +import request from 'request/index.ts'; +import {ParamDataType} from './typeManagement'; +const {get, post} = request; + +/** + * 故障报警规则列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function faultRulesAPI(params: ParamDataType['faultRulesListType']): ReturnType { + return get(urlPath.faultRulesUrl, params, {baseURL: '/oob-alert', isBusinessProcessing: false}); +}; + +/** + * 故障报警规则列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +export function faultRulesExportAPI(params: ParamDataType['faultRulesLisExportType']): ReturnType { + return get(urlPath.faultRulesExportUrl, params, {baseURL: '/oob-alert', isBusinessProcessing: false, responseType: 'blob', timeout: 1000 * 120, islongReq: true}); +}; + +/** + * 故障推送push接口 + * @param {Object} data 请求需要的参数 +*/ +export function faultPushAPI(data: ParamDataType['faultPushType']): ReturnType { + return post(urlPath.faultPushUrl, data, true, {baseURL: '/oob-alert'}); +}; + +/** + * 故障启用、禁用接口 + * @param {Object} data 请求需要的参数 +*/ +export function faultUseAPI(data: ParamDataType['faultUseType']): ReturnType { + return post(urlPath.faultUseUrl, data, true, {baseURL: '/oob-alert'}); +}; + +/** + * 恢复默认设置接口 + * @param {Object} data 请求需要的参数 +*/ +export function faultResetAPI(data: ParamDataType['faultResetType']): ReturnType { + return post(urlPath.faultResetUrl, data, true, {baseURL: '/oob-alert'}); +}; + +/** + * 故障等级列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function faultLevelAPI(params: ParamDataType['faultLevelType']): ReturnType { + return get(urlPath.faultLevelUrl, params, {baseURL: '/oob-alert', isBusinessProcessing: false}); +}; + +/** + * 故障配件列表接口 + * @param {Object} params 请求需要的参数 +*/ +export function faultSpecAPI(params: ParamDataType['faultSpecType']): ReturnType { + return get(urlPath.faultSpecUrl, params, {baseURL: '/oob-alert', isBusinessProcessing: false}); +}; diff --git a/bmp-operation-web/src/api/surveillance/faultRule/typeManagement.ts b/bmp-operation-web/src/api/surveillance/faultRule/typeManagement.ts new file mode 100644 index 0000000..a0416d8 --- /dev/null +++ b/bmp-operation-web/src/api/surveillance/faultRule/typeManagement.ts @@ -0,0 +1,57 @@ +type AddReadonly = {readonly [P in keyof T]: T[P]}; + +type UrlPathType = { + faultRulesUrl: string; // 故障报警规则 + faultRulesExportUrl: string; // 故障报警规则导出 + faultPushUrl: string; // 故障推送 + faultUseUrl: string; // 故障启用 + faultResetUrl: string; // 恢复默认设置 + faultLevelUrl: string; // 故障等级 + faultSpecUrl: string; // 规则配件 +}; + +// url地址类型 +type TotalUrlPathType = AddReadonly; + +/** + * idc-机房列表类 +*/ +type ListType = { + pageNumber: number; + pageSize: number; + isAll: boolean | number; + exportType: string; +}; + +/** + * 接口参数类型 +*/ +interface ParamDataType { + faultRulesListType: ListType; + faultPushType: {role_id: string; push_status: number;} + faultUseType: {role_idd: string; use_status: number;} + faultRulesLisExportType: Omit; + faultResetType: {role_ids: string;}; + faultLevelType: {}; + faultSpecType: {}; +}; + +/** + * 请求类型 +*/ +interface ReqType { + CurrencyType: { + isBusinessProcessing: boolean; + url: string; + methods: string; + } +}; + +// 请求类型 +type RequestType = Required; + +export { + RequestType, + ParamDataType, + TotalUrlPathType +}; diff --git a/bmp-operation-web/src/api/surveillance/hardwareStatus/config.ts b/bmp-operation-web/src/api/surveillance/hardwareStatus/config.ts new file mode 100644 index 0000000..5d9bdad --- /dev/null +++ b/bmp-operation-web/src/api/surveillance/hardwareStatus/config.ts @@ -0,0 +1,17 @@ +/** + * @file + * @author +*/ + +import {methodsTotal} from 'utils/index.ts'; +import {TotalUrlPathType} from './typeManagement'; // url地址类 + +const defaultUrl: string = methodsTotal.humpSplit('/v1/oobAlert/device/status'); + +// url地址集合 +const urlPath: TotalUrlPathType = { + hardwareStatusUrl: defaultUrl, // 硬件报警状态列表 + hardwareStatusExportUrl: defaultUrl // 硬件报警状态列表导出 +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/surveillance/hardwareStatus/request.ts b/bmp-operation-web/src/api/surveillance/hardwareStatus/request.ts new file mode 100644 index 0000000..6115fe5 --- /dev/null +++ b/bmp-operation-web/src/api/surveillance/hardwareStatus/request.ts @@ -0,0 +1,33 @@ +/** + * @file + * @author +*/ + +import urlPath from './config'; +import request from 'request/index.ts'; +import {ParamDataType} from './typeManagement'; +const {get} = request; + +/** + * 硬件报警状态列表接口 + * @param {Object} params 请求需要的参数 +*/ +const hardwareStatusAPI = (params: ParamDataType['hardwareStatusType']): ReturnType => { + return get(urlPath.hardwareStatusUrl, params, {baseURL: '/oob-alert', isBusinessProcessing: false}); +}; + +/** + * 硬件报警状态导出列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +const hardwareStatusExportAPI = (params: ParamDataType['hardwareStatusExportType']) => { + return get(urlPath.hardwareStatusExportUrl, params, {baseURL: '/oob-alert', timeout: 1000 * 120, isBusinessProcessing: false, responseType: 'blob', islongReq: true}); +}; + + +const hardwareStatusApiCount = { + hardwareStatusAPI, + hardwareStatusExportAPI +}; + +export default hardwareStatusApiCount; diff --git a/bmp-operation-web/src/api/surveillance/hardwareStatus/typeManagement.ts b/bmp-operation-web/src/api/surveillance/hardwareStatus/typeManagement.ts new file mode 100644 index 0000000..63517f2 --- /dev/null +++ b/bmp-operation-web/src/api/surveillance/hardwareStatus/typeManagement.ts @@ -0,0 +1,45 @@ +type AddReadonly = {readonly [P in keyof T]: T[P]}; + +type UrlPathType = { + hardwareStatusUrl: string; // 硬件报警状态 + hardwareStatusExportUrl: string; // 硬件报警状态导出 +}; + +// url地址类型 +type TotalUrlPathType = AddReadonly; + +type ListType = { + pageNumber: number; + pageSize: number; + isAll: boolean | number; + exportType: string; +}; + + +/** + * 接口参数类型 +*/ +interface ParamDataType { + hardwareStatusType: ListType; + hardwareStatusExportType: Omit; +}; + +/** + * 请求类型 +*/ +interface ReqType { + CurrencyType: { + isBusinessProcessing: boolean; + url: string; + methods: string; + } +}; + +// 请求类型 +type RequestType = Required; + +export { + RequestType, + ParamDataType, + TotalUrlPathType +}; diff --git a/bmp-operation-web/src/api/user/config.ts b/bmp-operation-web/src/api/user/config.ts new file mode 100644 index 0000000..fba8775 --- /dev/null +++ b/bmp-operation-web/src/api/user/config.ts @@ -0,0 +1,18 @@ +/** + * @file + * @author +*/ + +import {TotalUrlPathType} from './typeManagement'; // url地址类 + +const defaultPath: string = '/users'; + +// url地址集合 +const urlPath: TotalUrlPathType = { + userListUrl: defaultPath, // 用户列表 + addUserUrl: defaultPath, // 添加用户 + editUserUrl: `${defaultPath}/`, // 编辑用户 + deleteUserUrl: `${defaultPath}/`, // 删除用户 +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/user/request.ts b/bmp-operation-web/src/api/user/request.ts new file mode 100644 index 0000000..4fba2ae --- /dev/null +++ b/bmp-operation-web/src/api/user/request.ts @@ -0,0 +1,59 @@ +/** + * @file + * @author +*/ + +import urlPath from './config'; +import request from 'request/index.ts'; +import {ParamDataType} from './typeManagement'; +const {get, post, put, deleteReq} = request; + +/** + * 用户列表接口 + * @param {Object} params 请求需要的参数 +*/ +const userListAPI = (params: ParamDataType['UserListType']): ReturnType => { + return get(urlPath.userListUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 用户列表导出接口 + * @param {Object} params 请求需要的参数 +*/ +const userListExportAPI = (params: ParamDataType['UserListExportType']): ReturnType => { + return get(urlPath.userListUrl, params, {isBusinessProcessing: false, timeout: 1000 * 120, responseType: 'blob', islongReq: true}); +}; + +/** + * 添加用户接口 + * @param {Object} data 请求需要的参数 +*/ +const addUserAPI = (data: ParamDataType['AddUserType']): ReturnType => { + return put(urlPath.addUserUrl, data, true); +}; + +/** + * 编辑用户接口 + * @param {Object} data 请求需要的参数 +*/ +const editUserAPI = (data: ParamDataType['EditUserType']): ReturnType => { + return post(urlPath.editUserUrl + data.userId, data, true); +}; + +/** + * 删除用户接口 + * @param {Object} data 请求需要的参数 +*/ +const deleteUserAPI = (data: ParamDataType['DeleteUserType']): ReturnType => { + return deleteReq(urlPath.deleteUserUrl + data.userId, data, true); +}; + +const userApiCount = { + addUserAPI, + userListAPI, + editUserAPI, + deleteUserAPI, + userListExportAPI +}; + +export default userApiCount; diff --git a/bmp-operation-web/src/api/user/typeManagement.ts b/bmp-operation-web/src/api/user/typeManagement.ts new file mode 100644 index 0000000..3ebd4ef --- /dev/null +++ b/bmp-operation-web/src/api/user/typeManagement.ts @@ -0,0 +1,67 @@ +type AddReadonly = {readonly [P in keyof T]: T[P]}; + +type UrlPathType = { + userListUrl: string; // 用户列表 + addUserUrl: string; // 添加用户 + editUserUrl: string; // 编辑用户 + deleteUserUrl: string; // 删除用户 +}; + +// url地址类型 +type TotalUrlPathType = AddReadonly; + +/** + * idc-机房列表类 +*/ +type ListType = { + pageNumber: number; + pageSize: number; + isAll: boolean | number; + exportType: string; +}; + +/** + * 操作用户类 +*/ +type OperateUserType = { + description: string; + email: string; + language: string; + phoneNumber: string; + phonePrefix: string; + roleId: string; + userName: string; + userId: string; + defaultProjectId: string; +}; + +/** + * 接口参数类型 +*/ +interface ParamDataType { + UserListType: Partial & Partial<{roleId: string; defaultProjectId: string; userName: string;}>; + UserListExportType: Omit; + AddUserType: Omit; + EditUserType: Required; + DeleteUserType: Required<{userId: string;}>; +}; + +/** + * 请求类型 +*/ +interface ReqType { + CurrencyType: { + isBusinessProcessing: boolean; + url: string; + methods: string; + } +}; + +// 请求类型 +type RequestType = Required; + +export { + RequestType, + ParamDataType, + TotalUrlPathType +}; diff --git a/bmp-operation-web/src/api/userCenter/config.ts b/bmp-operation-web/src/api/userCenter/config.ts new file mode 100644 index 0000000..15dee85 --- /dev/null +++ b/bmp-operation-web/src/api/userCenter/config.ts @@ -0,0 +1,21 @@ +/** + * @file + * @author +*/ +import {TotalUrlPathType} from './typeManagement'; // url地址类 + +const defaultUrl1: string = '/user/'; +const defaultUrl2: string = '/apikey'; + +// url地址集合 +const urlPath: TotalUrlPathType = { + timeOneUrl: `${defaultUrl1}local/timezones`, // 时区 + userInfoUrl: `${defaultUrl1}local`, // 用户信息 + setUserInfoUrl: `${defaultUrl1}local`, // 修改用户信息 + deleteApiKeyUrl: `${defaultUrl2}/`, // 删除apikey + createApiKeyUrl: defaultUrl2, // 创建apikey + getApiKeyUrl: defaultUrl2, // 获取apikey + revisePasswordUrl: `${defaultUrl1}local/password` // 修改密码 +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/userCenter/license/config.ts b/bmp-operation-web/src/api/userCenter/license/config.ts new file mode 100644 index 0000000..58f5ac7 --- /dev/null +++ b/bmp-operation-web/src/api/userCenter/license/config.ts @@ -0,0 +1,16 @@ +/** + * @file + * @author +*/ + +import {TotalUrlPathType} from './typeManagement'; // url地址类 + +const defaultUrl: string = '/license/'; + +// url地址集合 +const urlPath: TotalUrlPathType = { + licenseUrl: `${defaultUrl}content`, // 授权证内容 + downloadTokenUrl: `${defaultUrl}downloadToken` +}; + +export default urlPath; diff --git a/bmp-operation-web/src/api/userCenter/license/request.ts b/bmp-operation-web/src/api/userCenter/license/request.ts new file mode 100644 index 0000000..39c8be7 --- /dev/null +++ b/bmp-operation-web/src/api/userCenter/license/request.ts @@ -0,0 +1,31 @@ +/** + * @file + * @author +*/ + +import urlPath from './config'; +import request from 'request/index.ts'; +const {get} = request; + +/** + * 授权证内容接口 + * @param {Object} params 请求需要的参数 +*/ +const licenseAPI = (params: {}): ReturnType => { + return get(urlPath.licenseUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 请求码下载接口 + * @param {Object} params 请求需要的参数 +*/ +const downloadTokenAPI = (params: {}): ReturnType => { + return get(urlPath.downloadTokenUrl, params, {timeout: 1000 * 120, isBusinessProcessing: false, responseType: 'blob', islongReq: true}); +}; + +const licenseApiCount = { + licenseAPI, + downloadTokenAPI +}; + +export default licenseApiCount; diff --git a/bmp-operation-web/src/api/userCenter/license/typeManagement.ts b/bmp-operation-web/src/api/userCenter/license/typeManagement.ts new file mode 100644 index 0000000..6073c8d --- /dev/null +++ b/bmp-operation-web/src/api/userCenter/license/typeManagement.ts @@ -0,0 +1,8 @@ +interface TotalUrlPathType { + licenseUrl: string; + downloadTokenUrl: string; +} + +export { + TotalUrlPathType +}; \ No newline at end of file diff --git a/bmp-operation-web/src/api/userCenter/request.ts b/bmp-operation-web/src/api/userCenter/request.ts new file mode 100644 index 0000000..b115f94 --- /dev/null +++ b/bmp-operation-web/src/api/userCenter/request.ts @@ -0,0 +1,65 @@ +/** + * @file + * @author +*/ + +import urlPath from './config'; +import request from 'request/index.ts'; +import {ParamDataType} from './typeManagement'; +const {get, put, deleteReq} = request; + +/** + * 时区 + * @param {Object} params 请求需要的参数 +*/ +export function timeOneAPI(params: ParamDataType['TimeOneType']): ReturnType { + return get(urlPath.timeOneUrl, params, {isBusinessProcessing: true}); +}; + +/** + * 用户信息 + * @param {Object} params 请求需要的参数 +*/ +export function userInfoAPI(params: ParamDataType['UserInfoType']): ReturnType { + return get(urlPath.userInfoUrl, params, {isBusinessProcessing: false}); +}; + +/** + * 修改用户信息 + * @param {Object} data 请求需要的参数 +*/ +export function setUserInfoAPI(data: ParamDataType['UserInfoType']): ReturnType { + return put(urlPath.setUserInfoUrl, data, false); +}; + +/** + * 获取apikey + * @param {Object} params 请求需要的参数 +*/ +export function getApiKeyAPI(params: ParamDataType['GetApiKeyType']): ReturnType { + return get(urlPath.getApiKeyUrl, params, {isBusinessProcessing: true}); +}; + +/** + * 创建apikey + * @param {Object} data 请求需要的参数 +*/ +export function createApiKeyAPI(data: ParamDataType['CreateApiKeyType']): ReturnType { + return put(urlPath.createApiKeyUrl, data, true); +}; + +/** + * 删除apikey + * @param {Object} data 请求需要的参数 +*/ +export function deleteApiKeyAPI(data: ParamDataType['DeleteApiKeyType']): ReturnType { + return deleteReq(urlPath.deleteApiKeyUrl + data.apiKey, data, true); +}; + +/** + * 修改密码 + * @param {Object} data 请求需要的参数 +*/ +export function revisePasswordAPI(data: ParamDataType['RevisePasswordType']): ReturnType { + return put(urlPath.revisePasswordUrl, data, false); +}; diff --git a/bmp-operation-web/src/api/userCenter/typeManagement.ts b/bmp-operation-web/src/api/userCenter/typeManagement.ts new file mode 100644 index 0000000..defde93 --- /dev/null +++ b/bmp-operation-web/src/api/userCenter/typeManagement.ts @@ -0,0 +1,66 @@ +type AddReadonly = {readonly [P in keyof T]: T[P]}; + +type UrlPathType = { + timeOneUrl: string; // 时区 + userInfoUrl: string; // 用户信息 + setUserInfoUrl: string; // 修改用户信息 + deleteApiKeyUrl: string; // 删除apikey + createApiKeyUrl: string; // 创建apikey + getApiKeyUrl: string; // 获取apikey + revisePasswordUrl: string; // 修改密码 +}; + +// url地址类型 +type TotalUrlPathType = AddReadonly; + + +/** + * 接口参数类型 +*/ +interface ParamDataType { + TimeOneType: {}; + UserInfoType: {}; + GetApiKeyType: { + isAll: string; + }; + CreateApiKeyType: { + name: string; + readOnly: number; + type: string; + }; + DeleteApiKeyType: { + apiKey: string; + }; + SetUserInfoType: { + email: string; + phoneNumber: string; + language: string; + timezone: string; + userName: string; + phonePrefix: string; + }; + RevisePasswordType: { + oldPassword: string; + password: string; + }; +}; + +/** + * 请求类型 +*/ +interface ReqType { + CurrencyType: { + isBusinessProcessing: boolean; + url: string; + methods: string; + } +}; + +// 请求类型 +type RequestType = Required; + +export { + RequestType, + ParamDataType, + TotalUrlPathType +}; diff --git a/bmp-operation-web/src/assets/css/batchOperatePagination.scss b/bmp-operation-web/src/assets/css/batchOperatePagination.scss new file mode 100644 index 0000000..f105fac --- /dev/null +++ b/bmp-operation-web/src/assets/css/batchOperatePagination.scss @@ -0,0 +1,52 @@ +.check-all { + position: absolute; + left: 46.6px; + top: 14.5px; +} + +.batch-operate { + position: absolute; + left: 90px; + top: 50%; + transform: translateY(-50%); + + &-device-list { + border: .53px solid $border2; + margin-left: 20px; + border-radius: 5px; + padding: 3px 9px; + @include display-align(center); + @include set-cursor(pointer); + @include size-weight-color($fontSize, $fontSmallWeight, $color6); + + .text-color { + color: $color12; + } + + &:hover { + color: $color12; + border-color: $border4; + } + + &:hover .arrow-bottom-img { + background-image: url('~@/assets/img/listImg/arrow-bottom.png'); + @include position-repeat(0); + } + + .arrow-bottom-img { + background-image: url('~@/assets/img/uiImg/table-arrow-bottom.png'); + @include position-repeat(0); + } + + &:hover .arrow-bottom-img, + .arrow-bottom-img { + @include set-width-height(16px); + background-size: backgoundSize(auto); + } + } + + button { + padding: 5px 12px; + border-radius: 5px; + } +} diff --git a/bmp-operation-web/src/assets/css/clear.scss b/bmp-operation-web/src/assets/css/clear.scss new file mode 100644 index 0000000..a98ccf4 --- /dev/null +++ b/bmp-operation-web/src/assets/css/clear.scss @@ -0,0 +1,157 @@ +* { + margin: 0; + padding: 0; +} + +li { + list-style: none; +} + +img { + vertical-align: top; + border: none; +} + +body { + font-family: "Microsoft YaHei"; + font-size: 14px; + color: #333; +} + +html, body { + height: 100%; + width: 100%; +} + +h1, +h2, +h3, +h4, +h5, +h6 { + font-size: 100%; + font-weight: normal; +} + +address, +cite, +dfn, +em, +var { + font-style: normal; +} + +/* 将斜体扶正 */ +code, +kbd, +pre, +samp { + font-family: courier new, courier, monospace; +} + +/* 统一等宽字体 */ +small { + font-size: 12px; +} + +/* 小于 12px 的中文很难阅读, 让 small 正常化 */ + +/** 重置列表元素 **/ +ul, +ol { + list-style: none; +} + +/** 重置文本格式元素 **/ +a { + text-decoration: none; + + &:hover { + text-decoration: none !important; + } +} + +a:hover { + text-decoration: underline; +} + +sup { + vertical-align: text-top; +} + +/* 重置, 减少对行高的影响 */ + +sub { + vertical-align: text-bottom; +} + +/** 重置表单元素 **/ +legend { + color: #000; +} + +fieldset, +img { + border: 0; +} + +button, +input, +select, +textarea { + font-size: 100%; +} + +input { + &::placeholder { + font-size: 12px; + } +} +/* 使得表单元素在 ie 下能继承字体大小 */ + +/* 重置 HTML5 元素 */ +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +menu, +nav, +section, +summary, +time, +mark, +audio, +video { + display: block; + margin: 0; + padding: 0; +} + +mark { + background: #ff0; +} + +/* 设置placeholder的默认样式 */ +:-moz-placeholder { + color: #ddd; + opacity: 1; +} + +::-moz-placeholder { + color: #ddd; + opacity: 1; +} + +input:-ms-input-placeholder { + color: #ddd; + opacity: 1; +} + +input::-webkit-input-placeholder { + color: #ddd; + opacity: 1; +} diff --git a/bmp-operation-web/src/assets/css/communal.scss b/bmp-operation-web/src/assets/css/communal.scss new file mode 100644 index 0000000..2d00b02 --- /dev/null +++ b/bmp-operation-web/src/assets/css/communal.scss @@ -0,0 +1,190 @@ +/** 存放一些公共的样式 **/ +$color1: #108ee9; +$color2: #e0e0e0; +$color3: #fff; +$color4: #e8f4fd; +$color5: #000; +$color6: #666; +$color7: #999; +$color8: #aaa; +$color9: #43b561; +$color10: #9254de; +$color11: #d48806; +$color12: #0f8fe9; +$color13: #f56c6c; +$color14: #ff4d4f; +$color15: #c0c4cc; +$color16: #f04134; +$defaultColor: #333; +$border: #f0f0f0; +$border2: #979797; +$border3: #108ee9; +$border4: #0f8fe9; +$border5: #c7c7c7; +$border6: #0f81d4; +$border7: #999; +$border8: #fff; +$border9: #f56c6c; +$border10: #bcbcbc; +$border11: #d48806; +$border12: #9254de; +$border13: #ff4d4f; +$border14: #43b561; +$border15: #dcdfe6; +$border16: #e8f4fd; +$border17: #333; +$border18: #e9e9e9; +$border19: #666; +$border20: #d2d2d2; +$whiteBackground: #fff; +$background1: #108ee9; +$background2: #0f81d4; +$background3: #f7f7f7; +$background4: #d7eeff; +$background5: #eee; +$background6: #dfdfdf; +$background7: rgba(255, 255, 255, .8); +$background8: #0f8fe9; +$background9: #999; +$background10: #ededed; +$background11: rgba(212, 217, 221, .6); +$background12: rgba(247, 247, 247, .6); +$background13: rgb(249, 237, 239); +$background14: #e8f4fd; +$background15: #f5f5f5; +$background16: #979797; +$background17: #f9ecee; +$transparent: transparent; +$fontSize: 12px; +$fontSize2: 14px; +$fontSize3: 19px; +$borderRadius: 14px; +$fontLargeWeight2: 700; +$fontLargeWeight: 600; +$fontSmallWeight: 400; +$percentageWidth: 100%; +$percentageHeight: 100%; +$boxShadow: 0 1px 3px 0 rgba(0, 0, 0, .30); +$backdropFilter: blur(100px); + +@mixin set-cursor($val) { + cursor: $val; +} + +%resize-none { + resize: none; +} + +%pointer-events { + pointer-events: none; +} + +%justify-center { + justify-content: center; +} + +%justify-start { + justify-content: flex-start !important; +} + +%display-flex-column { + display: flex; + flex-direction: column; +} + +%displafy-flex-wrap { + display: flex; + flex-wrap: wrap; +} + +@mixin display-justify($val) { + display: flex; + justify-content: $val; +} + +@mixin display-align($val) { + display: flex !important; + align-items: $val !important; +} + +@mixin position-repeat($key) { + @if $key == 0 { + background-position: center center; + background-repeat: no-repeat; + } + // 后续可以自由发挥 +} + +@mixin text-align($val) { + text-align: $val; +} + +%header-info { + width: 100%; + height: 60px; + background: $whiteBackground; + box-shadow: 0 2px 4px 0 rgba(210, 210, 210, .50); + border-radius: 10px 10px 0 0; + @include display-align(center); + position: absolute; + z-index: 9; +} + +@mixin set-width-height($val) { + width: $val; + height: $val; +} + +%white-flw-over { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +@mixin break-wrap($val) { + /** 允许长的内容可以自动换行:长单词内部进行换行 */ + word-wrap: break-word; + /** word-break属性用于指定非CJK(中日韩)脚本的断行规则,规定了自动换行的处理方法 break-all: 允许在单词内换行 */ + word-break: $val; +} + +%more-two-ellipsis { + display: -webkit-box; + text-overflow: ellipsis; + overflow: hidden; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; +} + +%def-c-f-style { + color: $defaultColor; + font-size: $fontSize; +} +@mixin size-weight-color($size, $weight, $colors) { + font-size: $size; + font-weight: $weight; + color: $colors; +} + +@mixin active-style($size) { + font-size: $size; + @include set-cursor(pointer); + color: $color1; +} + +@function backgoundSize($val) { + @if $val == auto { + @return 100% auto; + } + @else if $val == cover { + @return cover; + } + @else { + @return contain; + } +} + +%no-btn-opt { + justify-content: flex-end; + margin-top: 7px; +} \ No newline at end of file diff --git a/bmp-operation-web/src/assets/css/detail.scss b/bmp-operation-web/src/assets/css/detail.scss new file mode 100644 index 0000000..a265c39 --- /dev/null +++ b/bmp-operation-web/src/assets/css/detail.scss @@ -0,0 +1,258 @@ +$height: 28px; + +.operate-management-detail { + + .custom-tip-count { + font-size: 12px; + text-align: center; + margin-bottom: 30px; + } + + .operate-management { + &-count { + border-radius: 10px; + margin-bottom: 22px; + padding: 0; + + .info-header { + @include display-align(center); + margin-bottom: 18px; + } + + .info-line { + width: 2px; + height: $fontSize2; + background: $background1; + margin-right: $fontSize; + } + + .info-title { + @include size-weight-color($fontSize2, $fontLargeWeight, $color1); + } + + .info-content { + @include size-weight-color($fontSize, $fontLargeWeight, $defaultColor); + margin-right: 0px !important; + + .info-name, + label { + line-height: 17px; + } + + .set-text-wrap { + @include break-wrap(break-all); + } + } + + .default-password { + @include set-cursor(auto); + color: $defaultColor; + } + + .login-password { + color: $border3; + @include set-cursor(pointer); + @extend %justify-center; + @include display-align(center); + height: 18px; + + .set-size-small { + margin-top: 0px; + font-size: $fontSize; + } + + .set-size { + font-size: 15px; + margin-top: 3px; + // margin-left: 20px; + } + + &-img { + margin-left: 10px; + @include set-width-height(16px); + } + } + } + } + + &-info { + @extend %display-flex-column; + padding: 0 29px; + margin-bottom: 22px; + margin-top: 83px; + + .split-line { + width: $percentageWidth; + height: 1px; + background: $background3; + margin-top: 51px; + } + + .info-header { + @include display-align(center); + } + + .idc-administration { + margin: 42px 0 13px; + } + + .info-line { + width: 2px; + height: 14px; + background: $background1; + margin-right: 12px; + } + + .info-title { + @include size-weight-color($fontSize2, $fontLargeWeight, $defaultColor); + } + + .info-content { + background: $background3; + border-radius: 10px; + margin-top: 13px; + padding: 26px 0 6px 22px; + margin-left: 0 !important; + margin-right: 0 !important; + + label { + @include size-weight-color($fontSize, $fontLargeWeight, $defaultColor); + line-height: 17px; + } + + .el-form-item--default { + margin-bottom: 20px; + } + + .info-name { + line-height: 17px; + @include size-weight-color($fontSize, $fontSmallWeight, $defaultColor); + } + } + } + + .en-model-info, + .zh-model-info { + margin-top: 78px; + padding: 0 32px; + + .el-tabs__active-bar { + background: $color1; + } + + .el-tabs__item { + padding: 0 25px; + @include size-weight-color($fontSize2, $fontSmallWeight, $defaultColor); + + &:hover { + color: $color1; + } + } + + .el-tabs__item.is-active { + @include size-weight-color($fontSize2, $fontSmallWeight, $color1); + } + + .el-tabs__nav-wrap { + &::after { + height: 1px !important; + background: $border; + } + } + } + + &-image-info { + padding: 0 32px; + + button { + margin-top: 18px; + margin-bottom: 8px; + } + + .el-table__body tr:hover > td{ + background-color: $background3 !important; + } + } +} + +.no-table-img-url { + padding: 5px 0 26px; + margin-bottom: 22px; + border-radius: 10px; + margin-left: 4px; + + .btn { + border-radius: 15px; + margin-bottom: 20px; + } + + .el-table__empty-block { + background: $whiteBackground; + } + + .info-header { + @include display-align(center); + margin-bottom: 18px; + } + + .info-line { + width: 2px; + height: 14px; + background: $background1; + margin-right: 12px; + } + + .info-title { + @include size-weight-color($fontSize2, $fontLargeWeight, $color1); + } +} + +.model-detail-basic { + .operate-management-count { + padding: 16px 31px 6px; + background: $background3; + margin-bottom: 22px; + } +} + +.device-detail { + .operate-management-count { + padding: 10px 31px 6px; + } +} + +/* 设备详情 - 机型详情*/ +.model-detail-basic, +.device-detail { + + &-content { + @extend %display-flex-column; + padding: 12px 29px 0; + background: $whiteBackground; + border-bottom-right-radius: 10px; + border-bottom-left-radius: 10px; + min-height: 755px; + } + + .info-header { + margin-bottom: 22px; + } + + .operate-management-count { + background: $background3; + margin-bottom: 22px; + } + + .el-form-item--default { + margin-bottom: 22px; + } + + .el-form-item__label { + @include size-weight-color($fontSize, $fontLargeWeight, $defaultColor); + } + + .info-name { + @include size-weight-color($fontSize, $fontSmallWeight, $defaultColor); + @include display-align(center); + } +} diff --git a/bmp-operation-web/src/assets/css/deviceOperate.scss b/bmp-operation-web/src/assets/css/deviceOperate.scss new file mode 100644 index 0000000..a77b1a1 --- /dev/null +++ b/bmp-operation-web/src/assets/css/deviceOperate.scss @@ -0,0 +1,38 @@ +%img-count { + @include set-width-height(32px); + transform: scale(.5); + margin-left: 10px; + margin-top: 1px; +} + +%plugin-warnning-tip { + @include text-align(center); + border-radius: 2px; + background: rgb(249, 237, 239); + margin-top: 15px; + @include display-align(flex-start); +} + +%warnning-tip { + @extend %plugin-warnning-tip; + @extend %justify-center; + + img { + @extend %img-count; + } + + span { + @include size-weight-color($fontSize, $fontSmallWeight, $defaultColor); + padding-right: 30px; + margin-top: 8px; + } +} + +%tip-title { + margin: 15px 0; + @include size-weight-color($fontSize, $fontSmallWeight, $defaultColor); + + span { + color: $color1; + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/assets/css/index.scss b/bmp-operation-web/src/assets/css/index.scss new file mode 100644 index 0000000..e5eaba5 --- /dev/null +++ b/bmp-operation-web/src/assets/css/index.scss @@ -0,0 +1,204 @@ +.content, +#app { + height: 100%; + + .common-img { + @include set-width-height(16px); + } + + .copy-img { + cursor: pointer; + } + + .single-line-omission { + @extend %white-flw-over; + max-width: 260px; + } + + .default-style { + color: $defaultColor; + } + + .currency-style { + @include set-cursor(pointer); + color: $color1; + } + + .currency-style-right { + margin-right: 10px; + } + + .disabled-currency-style { + @include set-cursor(no-drop); + color: $color7; + } + + .default-unify { + border-radius: 15px; + height: 30px; + @include display-align(center); + @extend %justify-center; + position: relative; + } + + .set-status-create-en, + .set-status-create { + color: $color9; + border: 1px solid $border14; + } + + .en-def-status { + padding: 0 15px; + min-width: 125px; + } + + .def-management-status { + width: 100px; + } + + .def-status { + padding: 0 12px; + min-width: 75px; + } + + .set-status-default-en, + .set-status-default { + color: $color7; + border: 1px solid $border7; + } + + .set-empty { + color: $defaultColor; + } + + .set-status-warehousing-en, + .set-status-warehousing { + color: $color11; + border: 1px solid $border11; + } + + .set-status-on-down-en, + .set-status-on-down { + color: $color10; + border: 1px solid $border12; + } + + .set-status-error-en, + .set-status-error { + color: $color14; + border: 1px solid $border13; + } + + .more-text-ellipsis { + @extend %more-two-ellipsis; + } + + .radio-button-text-ellipsis { + .el-radio-button__inner { + max-width: 150px; + @extend %white-flw-over; + } + } + + .search-filter-tip { + @include size-weight-color($fontSize, $fontSmallWeight, $defaultColor); + padding-right: 30px; + margin-bottom: 10px; + + .go-back-list { + @include size-weight-color($fontSize, $fontSmallWeight, $color12); + @include set-cursor(pointer); + } + } +} + +.set-tooltip-width { + width: auto !important; + max-width: 360px !important; +} + +.warning-tip { + @include set-width-height(16px); + @include set-cursor(pointer); + position: absolute; + right: -26px; +} + +.warning-tips { + @include set-width-height(16px); + @include set-cursor(pointer); + margin-left: 10px; +} + +.set-wrap { + @include break-wrap(break-all); +} + +.set-word { + @include break-wrap(keep-all); +} + +.el-table-filter { + inset: 14px -20px auto auto !important; + + &__list { + &-item { + font-size: $fontSize !important; + + &:hover { + background: $background3 !important; + color: $color1 !important; + } + } + + &-item.is-active { + background: $background1 !important; + + &:hover { + color: $color3 !important; + } + } + } +} + +.edit-icon { + @include set-width-height(16px); + @include set-cursor(pointer); + margin-left: 10px; +} + +.drop-down-operate-content { + padding: 5px 25px; + width: 100%; + font-size: $fontSize; + @include text-align(center); + + &:hover, + &:active { + background: $background3; + color: $color1; + } +} + +.drop-down-disabled { + padding: 5px 25px; + width: 100%; + @include text-align(center); + @include size-weight-color($fontSize, $fontSmallWeight, $color7); + + &:hover { + background: $whiteBackground; + @include set-cursor(no-drop); + color: $color7; + } +} + +.no-drop-disabled { + @include set-cursor(no-drop); + @include size-weight-color($fontSize, $fontSmallWeight, $color7); + + &:hover { + @include set-cursor(no-drop); + color: $color7; + } +} diff --git a/bmp-operation-web/src/assets/css/listSearch.scss b/bmp-operation-web/src/assets/css/listSearch.scss new file mode 100644 index 0000000..b6953e7 --- /dev/null +++ b/bmp-operation-web/src/assets/css/listSearch.scss @@ -0,0 +1,143 @@ +%public-search-style { + @extend %displafy-flex-wrap; + + .el-form-item__label { + font-weight: $fontLargeWeight; + // @extend %display-flex-align; + @include display-align(center); + margin-right: 5px; + } + + .custom-width { + margin-right: 48px; + + .el-input__inner { + height: 30px; + } + } + + .custom-width1 { + width: 158px; + } +} + +:deep(.operate-management-content) { + + .custom-tip-count { + font-size: $fontSize; + @include text-align(center); + margin-bottom: 30px; + } + + .copy-email-info { + color: $color1; + @include set-cursor(pointer); + } + + .operate-management-content-operate { + margin-bottom: 0 !important; + } + + .search-tip-operate { + @include display-justify(space-between); + height: 17px; + margin-bottom: 16px; + } + + .search-tip-operate2 { + @include display-justify(space-between); + } + + .operate-log-form { + @extend %public-search-style; + } + + .in-band-monitoring { + margin-top: 0; + } + + .public-form, + .fault-form { + margin-top: 22px; + } + + .set-ipt-error { + .el-form-item__error { + margin-top: 5px; + } + } + + .in-band-monitoring, + .public-form, + .fault-form { + // @extend %displafy-flex-wrap; + padding: 0 30px; + @extend %public-search-style; + + // .el-form-item__label { + // font-weight: $fontLargeWeight; + // // @extend %display-flex-align; + // @include display-align(center); + // margin-right: 5px; + // } + + // .custom-width { + // margin-right: 48px; + + // .el-input__inner { + // height: 30px; + // } + // } + + .custom-width4 { + height: 30px; + } + + .custom-width5 { + width: 132px; + } + + // .custom-width1 { + // width: 158px; + // } + + .custom-width3 { + width: 118px; + } + + .custom-width7 { + width: 220px; + } + + .custom-width2 { + width: 248px; + } + + .custom-width6 { + width: 330px; + } + + button { + min-width: 70px; + height: 30px; + border-radius: 4px; + } + + .el-button+.el-button { + margin-left: 21px; + } + } + .restore-default-set { + margin: 4px 0 16px 30px; + + button { + min-width: 112px; + } + } + + .search-tip-operate { + .search-filter-tip { + margin-left: 30px; + } + } +} diff --git a/bmp-operation-web/src/assets/css/modelForm.scss b/bmp-operation-web/src/assets/css/modelForm.scss new file mode 100644 index 0000000..493f450 --- /dev/null +++ b/bmp-operation-web/src/assets/css/modelForm.scss @@ -0,0 +1,113 @@ +%error-tip { + position: absolute; + color: $color13; + text-align: left; + left: 0; + padding-top: 35px; + top: 0; + line-height: 1.4; + font-size: $fontSize; + z-index: -1; +} + +%word-css { + align-items: flex-start; + word-wrap: break-word; + word-break: keep-all; +} + +%template-tip-css { + font-size: $fontSize; + color: $defaultColor; + font-weight: $fontLargeWeight; + margin-bottom: 15px; +} + +%volume-manager { + // @extend %display-flex-start; + @include display-align(flex-start); + margin-bottom: 0 !important; + + label { + line-height: 4; + + &::before { + content: "*"; + color: var(--el-color-danger); + margin-right: 4px; + } + } +} + +.model-operate { + .volume-manager-table { + + .el-form-item__content { + @extend %justify-center; + } + + .ipt-height { + margin-top: 20px; + margin-bottom: 45px !important; + + .el-form-item__content { + position: relative; + margin-bottom: 10px; + + .el-form-item__error { + text-align: left; + line-height: 1.2; + top: 100%; + padding-top: 7px; + } + } + } + + .ipt-default { + .el-form-item__content { + .el-input-number { + margin-bottom: 0px; + + .el-input { + margin-bottom: 0; + } + } + + .el-input { + margin-bottom: 0px; + } + } + } + } + + &-rule-form { + + .flex-checkbox { + // @extend %display-flex-align; + @include display-align(center); + + .el-checkbox { + width: auto; + margin-bottom: 0; + align-items: center !important; + } + } + + .is-loading { + position: absolute; + top: 8px; + right: 0; + transform: translateY(-50%); + animation: custom-loading .7s linear ease-in-out; + } + + @keyframes custom-loading { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(100deg); + } + } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/assets/img/diaLogImg/tooltiip.png b/bmp-operation-web/src/assets/img/diaLogImg/tooltiip.png new file mode 100644 index 0000000..2472ee4 Binary files /dev/null and b/bmp-operation-web/src/assets/img/diaLogImg/tooltiip.png differ diff --git a/bmp-operation-web/src/assets/img/diaLogImg/warning-tip.png b/bmp-operation-web/src/assets/img/diaLogImg/warning-tip.png new file mode 100644 index 0000000..292842b Binary files /dev/null and b/bmp-operation-web/src/assets/img/diaLogImg/warning-tip.png differ diff --git a/bmp-operation-web/src/assets/img/listImg/arrow-bottom.png b/bmp-operation-web/src/assets/img/listImg/arrow-bottom.png new file mode 100644 index 0000000..5e4ad03 Binary files /dev/null and b/bmp-operation-web/src/assets/img/listImg/arrow-bottom.png differ diff --git a/bmp-operation-web/src/assets/img/listImg/default-export.png b/bmp-operation-web/src/assets/img/listImg/default-export.png new file mode 100644 index 0000000..870b73f Binary files /dev/null and b/bmp-operation-web/src/assets/img/listImg/default-export.png differ diff --git a/bmp-operation-web/src/assets/img/listImg/default-refresh.png b/bmp-operation-web/src/assets/img/listImg/default-refresh.png new file mode 100644 index 0000000..a86c73c Binary files /dev/null and b/bmp-operation-web/src/assets/img/listImg/default-refresh.png differ diff --git a/bmp-operation-web/src/assets/img/listImg/default-set-up.png b/bmp-operation-web/src/assets/img/listImg/default-set-up.png new file mode 100644 index 0000000..22452cf Binary files /dev/null and b/bmp-operation-web/src/assets/img/listImg/default-set-up.png differ diff --git a/bmp-operation-web/src/assets/img/listImg/export.png b/bmp-operation-web/src/assets/img/listImg/export.png new file mode 100644 index 0000000..1e676b7 Binary files /dev/null and b/bmp-operation-web/src/assets/img/listImg/export.png differ diff --git a/bmp-operation-web/src/assets/img/listImg/refresh.png b/bmp-operation-web/src/assets/img/listImg/refresh.png new file mode 100644 index 0000000..85bb2d2 Binary files /dev/null and b/bmp-operation-web/src/assets/img/listImg/refresh.png differ diff --git a/bmp-operation-web/src/assets/img/listImg/set-up.png b/bmp-operation-web/src/assets/img/listImg/set-up.png new file mode 100644 index 0000000..481b2de Binary files /dev/null and b/bmp-operation-web/src/assets/img/listImg/set-up.png differ diff --git a/bmp-operation-web/src/assets/img/loginImg/clear.png b/bmp-operation-web/src/assets/img/loginImg/clear.png new file mode 100644 index 0000000..7323cf1 Binary files /dev/null and b/bmp-operation-web/src/assets/img/loginImg/clear.png differ diff --git a/bmp-operation-web/src/assets/img/loginImg/close-eye.png b/bmp-operation-web/src/assets/img/loginImg/close-eye.png new file mode 100644 index 0000000..1652324 Binary files /dev/null and b/bmp-operation-web/src/assets/img/loginImg/close-eye.png differ diff --git a/bmp-operation-web/src/assets/img/loginImg/login-out.png b/bmp-operation-web/src/assets/img/loginImg/login-out.png new file mode 100644 index 0000000..cfd6a04 Binary files /dev/null and b/bmp-operation-web/src/assets/img/loginImg/login-out.png differ diff --git a/bmp-operation-web/src/assets/img/loginImg/open-eye.png b/bmp-operation-web/src/assets/img/loginImg/open-eye.png new file mode 100644 index 0000000..511354a Binary files /dev/null and b/bmp-operation-web/src/assets/img/loginImg/open-eye.png differ diff --git a/bmp-operation-web/src/assets/img/loginImg/user-login.png b/bmp-operation-web/src/assets/img/loginImg/user-login.png new file mode 100644 index 0000000..6189fe4 Binary files /dev/null and b/bmp-operation-web/src/assets/img/loginImg/user-login.png differ diff --git a/bmp-operation-web/src/assets/img/loginImg/user.png b/bmp-operation-web/src/assets/img/loginImg/user.png new file mode 100644 index 0000000..33f7eb9 Binary files /dev/null and b/bmp-operation-web/src/assets/img/loginImg/user.png differ diff --git a/bmp-operation-web/src/assets/img/message/message.png b/bmp-operation-web/src/assets/img/message/message.png new file mode 100644 index 0000000..e60358d Binary files /dev/null and b/bmp-operation-web/src/assets/img/message/message.png differ diff --git a/bmp-operation-web/src/assets/img/message/no-message-light.png b/bmp-operation-web/src/assets/img/message/no-message-light.png new file mode 100644 index 0000000..d8b4270 Binary files /dev/null and b/bmp-operation-web/src/assets/img/message/no-message-light.png differ diff --git a/bmp-operation-web/src/assets/img/message/no-message.png b/bmp-operation-web/src/assets/img/message/no-message.png new file mode 100644 index 0000000..481ba03 Binary files /dev/null and b/bmp-operation-web/src/assets/img/message/no-message.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/active-card.png b/bmp-operation-web/src/assets/img/navigationBarImg/active-card.png new file mode 100644 index 0000000..62d9e44 Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/active-card.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/active-in-band-monitoring.png b/bmp-operation-web/src/assets/img/navigationBarImg/active-in-band-monitoring.png new file mode 100644 index 0000000..bce30db Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/active-in-band-monitoring.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/computer-room-x.png b/bmp-operation-web/src/assets/img/navigationBarImg/computer-room-x.png new file mode 100644 index 0000000..c27c941 Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/computer-room-x.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/computer-room.png b/bmp-operation-web/src/assets/img/navigationBarImg/computer-room.png new file mode 100644 index 0000000..ab3d56e Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/computer-room.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/default-card.png b/bmp-operation-web/src/assets/img/navigationBarImg/default-card.png new file mode 100644 index 0000000..6bdc368 Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/default-card.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/default-device.png b/bmp-operation-web/src/assets/img/navigationBarImg/default-device.png new file mode 100644 index 0000000..f445ed9 Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/default-device.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/default-image.png b/bmp-operation-web/src/assets/img/navigationBarImg/default-image.png new file mode 100644 index 0000000..fcf1b7f Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/default-image.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/default-in-band-monitoring.png b/bmp-operation-web/src/assets/img/navigationBarImg/default-in-band-monitoring.png new file mode 100644 index 0000000..20eed61 Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/default-in-band-monitoring.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/default-model.png b/bmp-operation-web/src/assets/img/navigationBarImg/default-model.png new file mode 100644 index 0000000..a51372c Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/default-model.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/default-role.png b/bmp-operation-web/src/assets/img/navigationBarImg/default-role.png new file mode 100644 index 0000000..d2fc5aa Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/default-role.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/default-surveillance-manage-backups.png b/bmp-operation-web/src/assets/img/navigationBarImg/default-surveillance-manage-backups.png new file mode 100644 index 0000000..c37c45a Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/default-surveillance-manage-backups.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/default-user.png b/bmp-operation-web/src/assets/img/navigationBarImg/default-user.png new file mode 100644 index 0000000..864520d Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/default-user.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/device.png b/bmp-operation-web/src/assets/img/navigationBarImg/device.png new file mode 100644 index 0000000..46723e4 Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/device.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/image-manage.png b/bmp-operation-web/src/assets/img/navigationBarImg/image-manage.png new file mode 100644 index 0000000..5108c2e Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/image-manage.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/model.png b/bmp-operation-web/src/assets/img/navigationBarImg/model.png new file mode 100644 index 0000000..2af503a Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/model.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/password.png b/bmp-operation-web/src/assets/img/navigationBarImg/password.png new file mode 100644 index 0000000..2153133 Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/password.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/role.png b/bmp-operation-web/src/assets/img/navigationBarImg/role.png new file mode 100644 index 0000000..0671510 Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/role.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/shrink-expand.png b/bmp-operation-web/src/assets/img/navigationBarImg/shrink-expand.png new file mode 100644 index 0000000..f3c15bf Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/shrink-expand.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/surveillance-manage-backups.png b/bmp-operation-web/src/assets/img/navigationBarImg/surveillance-manage-backups.png new file mode 100644 index 0000000..6e8b37d Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/surveillance-manage-backups.png differ diff --git a/bmp-operation-web/src/assets/img/navigationBarImg/user.png b/bmp-operation-web/src/assets/img/navigationBarImg/user.png new file mode 100644 index 0000000..39dd379 Binary files /dev/null and b/bmp-operation-web/src/assets/img/navigationBarImg/user.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/add-default.png b/bmp-operation-web/src/assets/img/uiImg/add-default.png new file mode 100644 index 0000000..813ebb4 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/add-default.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/add-hover-active.png b/bmp-operation-web/src/assets/img/uiImg/add-hover-active.png new file mode 100644 index 0000000..6776349 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/add-hover-active.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/api-key.png b/bmp-operation-web/src/assets/img/uiImg/api-key.png new file mode 100644 index 0000000..2c3f063 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/api-key.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/arrow-bottom.png b/bmp-operation-web/src/assets/img/uiImg/arrow-bottom.png new file mode 100644 index 0000000..c7ceb57 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/arrow-bottom.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/arrow-left.png b/bmp-operation-web/src/assets/img/uiImg/arrow-left.png new file mode 100644 index 0000000..cf5366b Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/arrow-left.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/big-size.png b/bmp-operation-web/src/assets/img/uiImg/big-size.png new file mode 100644 index 0000000..e82467c Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/big-size.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/bottom.png b/bmp-operation-web/src/assets/img/uiImg/bottom.png new file mode 100644 index 0000000..dc73adb Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/bottom.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/centos.png b/bmp-operation-web/src/assets/img/uiImg/centos.png new file mode 100644 index 0000000..5039870 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/centos.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/clear.png b/bmp-operation-web/src/assets/img/uiImg/clear.png new file mode 100644 index 0000000..0d1afde Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/clear.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/copy.png b/bmp-operation-web/src/assets/img/uiImg/copy.png new file mode 100644 index 0000000..506a329 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/copy.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/debian.png b/bmp-operation-web/src/assets/img/uiImg/debian.png new file mode 100644 index 0000000..e142ffc Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/debian.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/desc-edit.png b/bmp-operation-web/src/assets/img/uiImg/desc-edit.png new file mode 100644 index 0000000..cd76e31 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/desc-edit.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/generic-version.png b/bmp-operation-web/src/assets/img/uiImg/generic-version.png new file mode 100644 index 0000000..2bc4b05 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/generic-version.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/green.png b/bmp-operation-web/src/assets/img/uiImg/green.png new file mode 100644 index 0000000..5a8cdd5 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/green.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/hover-arrow-left.png b/bmp-operation-web/src/assets/img/uiImg/hover-arrow-left.png new file mode 100644 index 0000000..b7f099c Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/hover-arrow-left.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/lock.png b/bmp-operation-web/src/assets/img/uiImg/lock.png new file mode 100644 index 0000000..797b408 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/lock.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/openeuler.png b/bmp-operation-web/src/assets/img/uiImg/openeuler.png new file mode 100644 index 0000000..1e9e4cd Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/openeuler.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/opt-doing.png b/bmp-operation-web/src/assets/img/uiImg/opt-doing.png new file mode 100644 index 0000000..c0ec39b Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/opt-doing.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/opt-fail.png b/bmp-operation-web/src/assets/img/uiImg/opt-fail.png new file mode 100644 index 0000000..702ca13 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/opt-fail.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/opt-success.png b/bmp-operation-web/src/assets/img/uiImg/opt-success.png new file mode 100644 index 0000000..1cb825a Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/opt-success.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/overlay-active.png b/bmp-operation-web/src/assets/img/uiImg/overlay-active.png new file mode 100644 index 0000000..56f5956 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/overlay-active.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/overlay.png b/bmp-operation-web/src/assets/img/uiImg/overlay.png new file mode 100644 index 0000000..5a4aa0e Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/overlay.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/re-collect.png b/bmp-operation-web/src/assets/img/uiImg/re-collect.png new file mode 100644 index 0000000..d285bde Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/re-collect.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/red.png b/bmp-operation-web/src/assets/img/uiImg/red.png new file mode 100644 index 0000000..fa6c579 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/red.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/reduce-default.png b/bmp-operation-web/src/assets/img/uiImg/reduce-default.png new file mode 100644 index 0000000..d21dfcb Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/reduce-default.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/reduce-grey.png b/bmp-operation-web/src/assets/img/uiImg/reduce-grey.png new file mode 100644 index 0000000..e8ec8fc Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/reduce-grey.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/reduce-hover.png b/bmp-operation-web/src/assets/img/uiImg/reduce-hover.png new file mode 100644 index 0000000..90b487b Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/reduce-hover.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/search-icon.png b/bmp-operation-web/src/assets/img/uiImg/search-icon.png new file mode 100644 index 0000000..bc33098 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/search-icon.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/table-arrow-bottom.png b/bmp-operation-web/src/assets/img/uiImg/table-arrow-bottom.png new file mode 100644 index 0000000..58254d6 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/table-arrow-bottom.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/tip.png b/bmp-operation-web/src/assets/img/uiImg/tip.png new file mode 100644 index 0000000..6738e6f Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/tip.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/tooltip.png b/bmp-operation-web/src/assets/img/uiImg/tooltip.png new file mode 100644 index 0000000..4206b21 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/tooltip.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/ubantu.png b/bmp-operation-web/src/assets/img/uiImg/ubantu.png new file mode 100644 index 0000000..1c4651c Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/ubantu.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/user-center-active.png b/bmp-operation-web/src/assets/img/uiImg/user-center-active.png new file mode 100644 index 0000000..faecef4 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/user-center-active.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/user-center.png b/bmp-operation-web/src/assets/img/uiImg/user-center.png new file mode 100644 index 0000000..31b150c Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/user-center.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/white-clear.png b/bmp-operation-web/src/assets/img/uiImg/white-clear.png new file mode 100644 index 0000000..b207729 Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/white-clear.png differ diff --git a/bmp-operation-web/src/assets/img/uiImg/windows.png b/bmp-operation-web/src/assets/img/uiImg/windows.png new file mode 100644 index 0000000..e7e8bcc Binary files /dev/null and b/bmp-operation-web/src/assets/img/uiImg/windows.png differ diff --git a/bmp-operation-web/src/auto-imports.d.ts b/bmp-operation-web/src/auto-imports.d.ts new file mode 100644 index 0000000..65b02fd --- /dev/null +++ b/bmp-operation-web/src/auto-imports.d.ts @@ -0,0 +1,71 @@ +/* eslint-disable */ +/* prettier-ignore */ +// @ts-nocheck +// noinspection JSUnusedGlobalSymbols +// Generated by unplugin-auto-import +export {} +declare global { + const EffectScope: typeof import('vue')['EffectScope'] + const computed: typeof import('vue')['computed'] + const createApp: typeof import('vue')['createApp'] + const customRef: typeof import('vue')['customRef'] + const defineAsyncComponent: typeof import('vue')['defineAsyncComponent'] + const defineComponent: typeof import('vue')['defineComponent'] + const effectScope: typeof import('vue')['effectScope'] + const getCurrentInstance: typeof import('vue')['getCurrentInstance'] + const getCurrentScope: typeof import('vue')['getCurrentScope'] + const h: typeof import('vue')['h'] + const inject: typeof import('vue')['inject'] + const isProxy: typeof import('vue')['isProxy'] + const isReactive: typeof import('vue')['isReactive'] + const isReadonly: typeof import('vue')['isReadonly'] + const isRef: typeof import('vue')['isRef'] + const markRaw: typeof import('vue')['markRaw'] + const nextTick: typeof import('vue')['nextTick'] + const onActivated: typeof import('vue')['onActivated'] + const onBeforeMount: typeof import('vue')['onBeforeMount'] + const onBeforeRouteLeave: typeof import('vue-router')['onBeforeRouteLeave'] + const onBeforeRouteUpdate: typeof import('vue-router')['onBeforeRouteUpdate'] + const onBeforeUnmount: typeof import('vue')['onBeforeUnmount'] + const onBeforeUpdate: typeof import('vue')['onBeforeUpdate'] + const onDeactivated: typeof import('vue')['onDeactivated'] + const onErrorCaptured: typeof import('vue')['onErrorCaptured'] + const onMounted: typeof import('vue')['onMounted'] + const onRenderTracked: typeof import('vue')['onRenderTracked'] + const onRenderTriggered: typeof import('vue')['onRenderTriggered'] + const onScopeDispose: typeof import('vue')['onScopeDispose'] + const onServerPrefetch: typeof import('vue')['onServerPrefetch'] + const onUnmounted: typeof import('vue')['onUnmounted'] + const onUpdated: typeof import('vue')['onUpdated'] + const provide: typeof import('vue')['provide'] + const reactive: typeof import('vue')['reactive'] + const readonly: typeof import('vue')['readonly'] + const ref: typeof import('vue')['ref'] + const resolveComponent: typeof import('vue')['resolveComponent'] + const shallowReactive: typeof import('vue')['shallowReactive'] + const shallowReadonly: typeof import('vue')['shallowReadonly'] + const shallowRef: typeof import('vue')['shallowRef'] + const toRaw: typeof import('vue')['toRaw'] + const toRef: typeof import('vue')['toRef'] + const toRefs: typeof import('vue')['toRefs'] + const toValue: typeof import('vue')['toValue'] + const triggerRef: typeof import('vue')['triggerRef'] + const unref: typeof import('vue')['unref'] + const useAttrs: typeof import('vue')['useAttrs'] + const useCssModule: typeof import('vue')['useCssModule'] + const useCssVars: typeof import('vue')['useCssVars'] + const useLink: typeof import('vue-router')['useLink'] + const useRoute: typeof import('vue-router')['useRoute'] + const useRouter: typeof import('vue-router')['useRouter'] + const useSlots: typeof import('vue')['useSlots'] + const watch: typeof import('vue')['watch'] + const watchEffect: typeof import('vue')['watchEffect'] + const watchPostEffect: typeof import('vue')['watchPostEffect'] + const watchSyncEffect: typeof import('vue')['watchSyncEffect'] +} +// for type re-export +declare global { + // @ts-ignore + export type { Component, ComponentPublicInstance, ComputedRef, ExtractDefaultPropTypes, ExtractPropTypes, ExtractPublicPropTypes, InjectionKey, PropType, Ref, VNode, WritableComputedRef } from 'vue' + import('vue') +} diff --git a/bmp-operation-web/src/components.d.ts b/bmp-operation-web/src/components.d.ts new file mode 100644 index 0000000..888ac29 --- /dev/null +++ b/bmp-operation-web/src/components.d.ts @@ -0,0 +1,85 @@ +// generated by unplugin-vue-components +// We suggest you to commit this file into source control +// Read more: https://github.com/vuejs/core/pull/3399 +import '@vue/runtime-core' + +export {} + +declare module '@vue/runtime-core' { + export interface GlobalComponents { + AddUser: typeof import('./components/UserOperates/AddUser/AddUser.vue')['default'] + AlarmHistory: typeof import('./components/InBandMonitoringManagement/AllAlarmRules/AlarmHistory.vue')['default'] + AssociatedModels: typeof import('./components/DeviceOperations/AssociatedModels/AssociatedModels.vue')['default'] + BatchEditInstanceName: typeof import('./components/DeviceOperations/BatchOperate/BatchEditInstanceName/BatchEditInstanceName.vue')['default'] + BatchOpenCloseRestart: typeof import('./components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/BatchOpenCloseRestart.vue')['default'] + BatchOpenCloseRestartTable: typeof import('./components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/table/batchOpenCloseRestartTable.vue')['default'] + BatchRecoveryInstance: typeof import('./components/DeviceOperations/BatchOperate/BatchRecoveryInstance/BatchRecoveryInstance.vue')['default'] + BatchResetPassword: typeof import('./components/DeviceOperations/BatchOperate/BatchResetPassword/BatchResetPassword.vue')['default'] + BtnOperate: typeof import('./components/Public/BtnOperate/BtnOperate.vue')['default'] + ClearRaidConfirm: typeof import('./components/DeviceOperations/ResetCollect/ClearRaidConfirm.vue')['default'] + CollectInfoConfirm: typeof import('./components/DeviceOperations/ResetCollect/CollectInfoConfirm.vue')['default'] + CreateApiKey: typeof import('./components/UserCenter/CreateApiKey/CreateApiKey.vue')['default'] + CustomDiaLog: typeof import('./components/CustomDiaLog/CustomDiaLog.vue')['default'] + CustomFilter: typeof import('./components/Public/CustomFilter/CustomFilter.vue')['default'] + CustomList: typeof import('./components/Public/CustomList/CustomList.vue')['default'] + DefaultSet: typeof import('./components/Surveillance/FaultRules/DefaultSet/DefaultSet.vue')['default'] + DeleteApiKey: typeof import('./components/UserCenter/DeleteApiKey/DeleteApiKey.vue')['default'] + DeleteImage: typeof import('./components/DeleteImage/DeleteImage.vue')['default'] + DeleteMessage: typeof import('./components/MessageInfo/DeleteMessage/DeleteMessage.vue')['default'] + DeleteModel: typeof import('./components/ModelOperates/DeleteModel/DeleteModel.vue')['default'] + DeleteUser: typeof import('./components/UserOperates/DeleteUser/DeleteUser.vue')['default'] + DetailHeader: typeof import('./components/Public/DetailHeader/DetailHeader.vue')['default'] + DeviceResetPasswordForm: typeof import('./components/DeviceOperations/ResetPassword/ruleForm/DeviceResetPasswordForm.vue')['default'] + DeviceResetPasswordTable: typeof import('./components/DeviceOperations/ResetPassword/table/DeviceResetPasswordTable.vue')['default'] + EditIdc: typeof import('./components/IdcOperates/EditIdc/EditIdc.vue')['default'] + EditIdcForm: typeof import('./components/IdcOperates/EditIdc/formSubmit/EditIdcForm.vue')['default'] + EditingUser: typeof import('./components/UserOperates/EditingUser/EditingUser.vue')['default'] + EditInstanceNameForm: typeof import('./components/DeviceOperations/BatchOperate/BatchEditInstanceName/formTable/EditInstanceNameForm.vue')['default'] + EditInstanceNameTable: typeof import('./components/DeviceOperations/BatchOperate/BatchEditInstanceName/formTable/EditInstanceNameTable.vue')['default'] + EditNotes: typeof import('./components/DeviceOperations/EditNotes/EditNotes.vue')['default'] + EmailPush: typeof import('./components/MessageInfo/MessageSet/EmailPush/EmailPush.vue')['default'] + EnableStatus: typeof import('./components/Surveillance/FaultRules/EnableStatus/EnableStatus.vue')['default'] + Export: typeof import('./components/Public/Export/Export.vue')['default'] + FaultHandlingConfirm: typeof import('./components/Surveillance/FaultLog/FaultHandlingConfirm/FaultHandlingConfirm.vue')['default'] + FaultPush: typeof import('./components/Surveillance/FaultRules/FaultPush/FaultPush.vue')['default'] + FormRules: typeof import('./components/DeviceOperations/AssociatedModels/formRules.vue')['default'] + HeaderInfo: typeof import('./components/Public/HeaderInfo/HeaderInfo.vue')['default'] + I18nSwitch: typeof import('./components/NavigationHeader/i18nSwitch/i18nSwitch.vue')['default'] + ImageAdd: typeof import('./components/ModelOperates/ImageAdd/ImageAdd.vue')['default'] + ImageAddModel: typeof import('./components/ImageOperates/ImageModel/ImageAddModel.vue')['default'] + ImageDesc: typeof import('./components/ImageOperates/ImageDesc/ImageDesc.vue')['default'] + ImageDeviceTypesList: typeof import('./components/ImageOperates/ImageModel/table/ImageDeviceTypesList.vue')['default'] + ImageModelName: typeof import('./components/ImageOperates/ImageModel/imageName/ImageModelName.vue')['default'] + ImageModelPagination: typeof import('./components/ImageOperates/ImageModel/pagination/ImageModelPagination.vue')['default'] + ImportDevice: typeof import('./components/DeviceOperations/ImportDevice/ImportDevice.vue')['default'] + ImportImage: typeof import('./components/ImageOperates/ImportImage/ImportImage.vue')['default'] + Lock: typeof import('./components/DeviceOperations/Lock/Lock.vue')['default'] + LoginOut: typeof import('./components/LoginOut/LoginOut.vue')['default'] + ModelImageAddName: typeof import('./components/ModelOperates/ImageAdd/modelName/ModelImageAddName.vue')['default'] + ModelImageAddPagination: typeof import('./components/ModelOperates/ImageAdd/pagination/ModelImageAddPagination.vue')['default'] + ModelImageAddReset: typeof import('./components/ModelOperates/ImageAdd/resetOperate/ModelImageAddReset.vue')['default'] + ModelImageListTable: typeof import('./components/ModelOperates/ImageAdd/table/ModelImageListTable.vue')['default'] + NavigationHeader: typeof import('./components/NavigationHeader/NavigationHeader.vue')['default'] + NoDataTip: typeof import('./components/Public/NoDataTip/NoDataTip.vue')['default'] + OpenShutDownRestart: typeof import('./components/DeviceOperations/OpenShutDownRestart/OpenShutDownRestart.vue')['default'] + RefreshCustomExport: typeof import('./components/Public/RefreshCustomExport/RefreshCustomExport.vue')['default'] + RemoveModel: typeof import('./components/ImageOperates/RemoveModel/RemoveModel.vue')['default'] + RemoveRecovery: typeof import('./components/DeviceOperations/ReomveRecovery/RemoveRecovery.vue')['default'] + RemoveRecoveryTable: typeof import('./components/DeviceOperations/ReomveRecovery/table/RemoveRecoveryTable.vue')['default'] + ResetInstance: typeof import('./components/DeviceOperations/ResetInstance/ResetInstance.vue')['default'] + ResetPassword: typeof import('./components/DeviceOperations/ResetPassword/ResetPassword.vue')['default'] + ResetSystem: typeof import('./components/DeviceOperations/ResetSystem/ResetSystem.vue')['default'] + ResetSystemFormSubmit: typeof import('./components/DeviceOperations/ResetSystem/FormSubmit/ResetSystemFormSubmit.vue')['default'] + ResetSystemInstanceInfo: typeof import('./components/DeviceOperations/ResetSystem/InstanceInfo/ResetSystemInstanceInfo.vue')['default'] + ResetSystemKeyTable: typeof import('./components/DeviceOperations/ResetSystem/KeyTable/ResetSystemKeyTable.vue')['default'] + RouterLink: typeof import('vue-router')['RouterLink'] + RouterView: typeof import('vue-router')['RouterView'] + RulesAlarmHistoryPagination: typeof import('./components/InBandMonitoringManagement/AllAlarmRules/pagination/rulesAlarmHistoryPagination.vue')['default'] + Search: typeof import('./components/Public/Search/Search.vue')['default'] + SecondaryConfirmation: typeof import('./components/DeviceOperations/ResetSystem/SecondaryConfirmation.vue')['default'] + SecurityVerification: typeof import('./components/Public/SecurityVerification/SecurityVerification.vue')['default'] + SelectOperate: typeof import('./components/NavigationHeader/selectOperate/selectOperate.vue')['default'] + UpDownFrame: typeof import('./components/DeviceOperations/UpDownFrame/UpDownFrame.vue')['default'] + UpDownFrameTable: typeof import('./components/DeviceOperations/UpDownFrame/table/UpDownFrameTable.vue')['default'] + } +} diff --git a/bmp-operation-web/src/components/CustomDiaLog/CustomDiaLog.vue b/bmp-operation-web/src/components/CustomDiaLog/CustomDiaLog.vue new file mode 100644 index 0000000..1ac3fee --- /dev/null +++ b/bmp-operation-web/src/components/CustomDiaLog/CustomDiaLog.vue @@ -0,0 +1,160 @@ + + + + diff --git a/bmp-operation-web/src/components/CustomDiaLog/customDiaLog.scss b/bmp-operation-web/src/components/CustomDiaLog/customDiaLog.scss new file mode 100644 index 0000000..3ef9a92 --- /dev/null +++ b/bmp-operation-web/src/components/CustomDiaLog/customDiaLog.scss @@ -0,0 +1,70 @@ +.custom-dialog { + &-header { + height: $percentageHeight; + @include display-align(center); + @include display-justify(space-between); + + .title { + @include display-align(center); + @include size-weight-color($fontSize2, $fontLargeWeight, $color1); + + img { + margin-right: 10px; + } + } + + .close-button { + // width: 23px; + // height: 23px; + @include set-width-height(23px); + position: absolute; + right: -12px; + top: -13px; + background: $whiteBackground; + + &:hover, + &:active, + &:focus { + background: $whiteBackground; + border-color: $border8; + color: $color1; + } + + .el-icon { + margin-left: 1px; + } + } + } + + &-footer { + &-cancel-btn { + border: 0; + } + + &-cancel-btn, + &-confirm-btn { + width: 100px; + height: 30px; + border-radius: 4px; + font-size: $fontSize; + font-weight: $fontSmallWeight; + } + } +} + +.set-height { + .el-overlay-dialog .el-dialog--center { + height: 366px !important; + + .el-table__body-wrapper { + height: 130px; + } + .currency-count-table .el-table { + margin-bottom: 0; + + .el-loading-mask { + height: 160px; + } + } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/components/DeleteImage/DeleteImage.vue b/bmp-operation-web/src/components/DeleteImage/DeleteImage.vue new file mode 100644 index 0000000..7743c5d --- /dev/null +++ b/bmp-operation-web/src/components/DeleteImage/DeleteImage.vue @@ -0,0 +1,93 @@ + + + + diff --git a/bmp-operation-web/src/components/DeleteImage/deleteImage.scss b/bmp-operation-web/src/components/DeleteImage/deleteImage.scss new file mode 100644 index 0000000..65fcbe0 --- /dev/null +++ b/bmp-operation-web/src/components/DeleteImage/deleteImage.scss @@ -0,0 +1,24 @@ +.delete-image { + .el-dialog { + &--center { + --el-dialog-width: 526px; + height: 298px;; + } + + &__footer { + width: 481px; + } + } + + &-count { + @include display-align(center); + @extend %justify-center; + margin-top: 80.5px; + + &-title { + @include display-align(center); + @include text-align(center); + @include size-weight-color($fontSize2, $fontSmallWeight, $defaultColor); + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/AssociatedModels/AssociatedModels.vue b/bmp-operation-web/src/components/DeviceOperations/AssociatedModels/AssociatedModels.vue new file mode 100644 index 0000000..5f69c72 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/AssociatedModels/AssociatedModels.vue @@ -0,0 +1,201 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/AssociatedModels/formRules.vue b/bmp-operation-web/src/components/DeviceOperations/AssociatedModels/formRules.vue new file mode 100644 index 0000000..98ebabc --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/AssociatedModels/formRules.vue @@ -0,0 +1,79 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/AssociatedModels/index.scss b/bmp-operation-web/src/components/DeviceOperations/AssociatedModels/index.scss new file mode 100644 index 0000000..e0d3b58 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/AssociatedModels/index.scss @@ -0,0 +1,147 @@ +.associated-models { + .el-dialog { + &--center { + --el-dialog-width: 1046px; + height: 530px;; + margin: auto; + } + + .el-loading-mask { + top: 42px; + } + + &__body { + padding: 0; + position: absolute; + min-height: calc(100% - 33px); + left: 50%; + transform: translateX(-50%); + overflow: hidden; + width: 1046px; + + .currency-count { + @extend %display-flex-column; + height: calc(91%); + position: absolute; + margin: 0; + overflow: hidden; + width: 1000px; + z-index: 1; + padding: 0 22.5px; + + &-table { + .el-table { + margin-bottom: 100px; + + .el-table__empty-block { + background: $background3; + } + } + } + + } + + .el-table__body { + padding-bottom: 0 !important; + + .el-table-fixed-column--right, + .el-table-fixed-column--left { + background-color: $background15; + } + } + + .error-tip { + input { + border-color: $border9; + + &::placeholder { + color: $color13; + } + } + } + + .def-tip { + input { + border-color: $border15; + + &::placeholder { + color: $color15; + } + } + } + + .def-select, + .multiple-choice { + margin: 10px; + + input { + width: 360px !important; + } + } + } + + &__footer { + width: 1101px; + } + } + + .add-new-model { + margin-left: 20px; + + span { + font-size: $fontSize; + color: $color1; + @include set-cursor(pointer); + } + } + + .set-empty { + margin-bottom: 30px !important; + + .el-form-item__error { + padding-top: 8px; + } + } + // table为空 + .currency-count-table { + + .el-table__header-wrapper { + margin-bottom: 5px; + } + + .el-table__body-wrapper { + max-height: 240px; + overflow-y: auto; + } + + .el-table__inner-wrapper tr:first-child th { + &:first-child { + border-left: none; + } + + &:last-child { + border-color: $border16; + } + } + + .el-table__row { + background-color: $background3; + + &:hover { + td { + background-color: $background10 !important; + } + } + } + } + + &-count { + @extend %display-flex-column; + margin-top: 20.5px; + + &-title { + @include text-align(center); + @include size-weight-color($fontSize2, $fontSmallWeight, $defaultColor); + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/AssociatedModels/utils/associatedModelsOpt.ts b/bmp-operation-web/src/components/DeviceOperations/AssociatedModels/utils/associatedModelsOpt.ts new file mode 100644 index 0000000..56e3356 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/AssociatedModels/utils/associatedModelsOpt.ts @@ -0,0 +1,135 @@ +/** + * @file + * @author +*/ + +// RuleFormRefType, +// import {SuccessType} from '@utils/publicType'; +import {msgTip} from 'utils/index.ts'; +import {language} from 'utils/publicClass.ts'; +import {AxiosError} from 'axios'; +import {associateDisksAPI} from 'api/device/request.ts'; +// associateAPI +class AssociatedModelsOpt { + errorFlag: Ref = ref(false); + // loading加载态 + isLoading: Ref = ref(false); + upFormOpt; + emitValue; + deviceId: string; + + constructor(upFormOpt: any, emitValue: any, deviceId: string) { + this.upFormOpt = upFormOpt; + this.emitValue = emitValue; + this.deviceId = deviceId; + } + + /** + * 确定按钮弹窗 + */ + determineClick: () => Promise = async () => { + this.errorFlag.value = true; + await this.upFormOpt.formRef.value!.validate((valid: boolean) => { + if (valid) { + this.associateDisks(); + } + }) + }; + + associateDisks = async () => { + const res = this.upFormOpt.reactiveArr.tableData.map((item: any) => { + // if (['RAID0-stripping', 'NO RAID'].includes(item.raidCan)) { + // item.newDisks = deepCopy([item.disks]); + // // this.reactiveArr.uniquenessData[index] = [...this.reactiveArr.uniquenessData[index], ...item.newDisks]; + // } + return { + ...item, + disks: this.upFormOpt.reactiveArr.selectObj[item.volumeId] + } + }) + this.upFormOpt.reactiveArr.tableData = res; + const status = res.some((item: {disks: string[]}) => !item.disks.length); + if (status) { + for (const key of this.upFormOpt.reactiveArr.tableData) { + key.disksDataFlag = !key.disks.length ? true : false; + } + return; + } + this.isLoading.value = true; + const valData = this.upFormOpt.reactiveArr.tableData.map((item: {volumeId: string; disks: string[]}) => { + return { + volumeId: item.volumeId, + diskId: typeof item.disks === 'string' ? [item.disks] : item.disks + } + }); + try { + const res = await associateDisksAPI({ + deviceTypeId: this.upFormOpt.deviceTypeId.value, + deviceId: this.deviceId, + volumes: valData + }); + if (res?.data?.result?.success) { + msgTip.success(language.t('operate.success')) + this.emitValue('determine-click') + // this.associate(); + return; + } + this.isLoading.value = false; + } + catch (e) { + const err = e as AxiosError; + err.message && msgTip.error(err.message); + } + finally { + this.isLoading.value = false; + this.cancelClick(); + } + // const newReq = this.upFormOpt.reactiveArr.tableData.map((item: {volumeId: string; disks: string[]}) => { + // return associateDisksAPI({ + // deviceTypeId: this.upFormOpt.deviceTypeId.value, + // deviceId: this.deviceId, + // volumes: [ + // { + // volumeId: item.volumeId, + // diskId: item.disks + // } + // ] + // }) + // }) + // Promise.all(newReq).then((res: any) => { + // if (res?.length) { + // this.associate(); + // } + // }) + // .catch(() => { + // this.isLoading.value = false; + // }) + } + + // associate = () => { + // associateAPI({ + // deviceTypeId: this.upFormOpt.deviceTypeId.value, + // deviceId: this.deviceId + // }) + // .then(({data}: {data: SuccessType}) => { + // if (data?.result?.success) { + // msgTip.success(language.t('operate.success')) + // this.emitValue('determine-click') + // } + // }) + // .finally(() => { + // this.isLoading.value = false; + // this.cancelClick(); + // }) + // } + + /** + * defineEmits API 来替代 emits,子传父,事件回传 + */ + cancelClick = (): void => { + // 回传父组件当前页码,可以处理相关操作 + this.emitValue('dia-log-close', false); + }; +}; + +export default AssociatedModelsOpt; diff --git a/bmp-operation-web/src/components/DeviceOperations/AssociatedModels/utils/upForm.ts b/bmp-operation-web/src/components/DeviceOperations/AssociatedModels/utils/upForm.ts new file mode 100644 index 0000000..fd5d42e --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/AssociatedModels/utils/upForm.ts @@ -0,0 +1,171 @@ +/** + * @file + * @author +*/ + +// uiLocale, locationItem, +import {CurrentInstance, language} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; +import {RuleFormRefType} from '@utils/publicType'; +// import {ElForm} from 'element-plus'; +import {describeVolumesAPI, describeAssociateDisksAPI} from 'api/device/request.ts'; +import {modelDetailAPI} from 'api/model/request.ts'; +import {AxiosError} from 'axios'; +import {msgTip} from 'utils/index.ts'; +import {CurrencyType} from '@utils/publicType'; + +class UpFormOpt { + instanceProxy = new CurrentInstance().proxy; + ruleForm = reactive({ + model: '' + }); + arrayCard: Ref = ref(''); + isTableLoading: Ref = ref(false); + formRef: Ref = ref() + reactiveArr: { + selectObj: any; + modelData: {text: string; filterParams: string; value: number}[]; + tableData: CurrencyType[]; + disksData: {name: string; size: string; sizeUnit: string; diskId: string; select: boolean;}[][]; + } = reactive<{ + selectObj: any; + modelData: {text: string; filterParams: string; value: number}[]; + tableData: CurrencyType[]; + disksData: {name: string; size: string; sizeUnit: string; diskId: string; select: boolean;}[][]; + }>({ + selectObj: {}, + modelData: [], + tableData: [], + disksData: [], + }); + rules = reactive({ + model: [ + { + required: true, + trigger: 'change', + message: language.t('associatedModel.content.placeholder') + } + ] + }); + deviceTypeId: Ref = ref(''); + deviceId: Ref = ref(''); + + constructor(props: {deviceId: string}) { + this.deviceId.value = props.deviceId; + store.ossDataInfo().getModelListRes().then((data: {text: string; filterParams: string; value: number}[]) => { + this.reactiveArr.modelData = data; + }) + } + + modelChange = (val: string) => { + this.isTableLoading.value = true; + this.deviceTypeId.value = val; + this.getModelDetail(val); + }; + + getModelDetail = async (val: string) => { + try { + const res = await modelDetailAPI({ + id: val + }); + if (res?.data?.result && Object.keys(res.data.result)?.length) { + this.arrayCard.value = res.data.result.isNeedRaid; + this.getDescribeVolumes(val); + } + } + catch(e) { + const err = e as AxiosError; + err?.message && msgTip.error(err.message); + } + } + + setRaid = (arr: any) => { + return arr?.map((item: {name: string}) => item.name).join(',') + } + + getDescribeVolumes = (val: string) => { + this.reactiveArr.selectObj = {}; + describeVolumesAPI({ + deviceTypeId: val + }) + .then(({data}: {data: {result: T[]}}) => { + if (data?.result?.length) { + data.result.forEach((t) => { + this.reactiveArr.selectObj[t.volumeId] = []; + }) + const newData = data.result.map((item) => { + return { + ...item, + disksDataFlag: false + } + }); + this.reactiveArr.tableData = newData; + const ids = data.result.map(item => item.volumeId); + this.describeAssociateDisks(ids, val); + return; + } + return Promise.reject(); + }) + .catch(() => { + this.reactiveArr.tableData = []; + }) + .finally(() => { + this.isTableLoading.value = false; + }) + } + + describeAssociateDisks = (ids: string[], val: string) => { + const newReq = ids.map((item: string) => { + return describeAssociateDisksAPI({ + deviceId: this.deviceId.value, + volumeId: item, + deviceTypeId: val + }) + }); + Promise.all(newReq).then((res: any[]) => { + if (res?.length) { + const data = res.map((t: any) => t.data).map((g: any) => g.result); + this.reactiveArr.disksData = data; + } + }) + .catch(() => { + this.reactiveArr.disksData = []; + }) + } + + setDiskLabel = (item: {name: string; size: string; sizeUnit: string;}) => { + return `${item.name}: ${item.size}${item.sizeUnit}`; + } + + jumpPage = () => { + const path: string = this.instanceProxy!.$defInfo.routerPath('modelList') as unknown as string; + window.open(path, '_blank') + } + + getFormRef = (forEl: {value: RuleFormRefType}) => { + this.formRef.value = forEl.value; + } + + setRaidCan = (item: string) => { + return item === 'RAID0-stripping' ? language.t('modelForm.raid') : item; + } + + getAllSelectDisks = (item: string) => { + return Object.keys(this.reactiveArr.selectObj).reduce((pre: string[], cur: string) => { + const c = item == cur ? [] : this.reactiveArr.selectObj[cur]; + return pre.concat(c); + }, []) + } + + // 下拉勾选 + disksDataChange = (item: {volumeId: string; disksDataFlag: boolean; select: boolean}) => { + item.disksDataFlag = this.reactiveArr.selectObj[item.volumeId]?.length ? false : true; + } + + setDiskInterfaceType = (item: string) => { + return item === 'notLimited' ? language.t('modelForm.unrestricted') : item; + } + +}; + +export default UpFormOpt; diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/BatchEditInstanceName.vue b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/BatchEditInstanceName.vue new file mode 100644 index 0000000..6de382c --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/BatchEditInstanceName.vue @@ -0,0 +1,139 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/batchEditInstanceName.scss b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/batchEditInstanceName.scss new file mode 100644 index 0000000..6983470 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/batchEditInstanceName.scss @@ -0,0 +1,88 @@ +@import 'assets/css/deviceOperate.scss'; + +.batch-edit-instance-name { + .el-dialog { + &--center { + --el-dialog-width: 676px; + height: 490px; + + .el-table { + &__header-wrapper { + margin-bottom: 5px; + } + + &__row { + background-color: $background3; + &:hover { + td { + background-color: $background10 !important; + } + } + } + } + + // table为空 + .el-table__inner-wrapper tr:first-child th { + &:first-child { + border-left: none; + } + + &:last-child { + border-color: $border16; + } + } + + .el-table__row { + background-color: $background3; + + &:hover { + td { + background-color: $background10 !important; + } + } + } + } + + &__body { + padding: 0; + } + + &__footer { + width: 631px; + } + } + + &-content { + .warnning-tip { + @extend %warnning-tip; + } + + .tip-title { + @extend %tip-title; + } + } + + .instance-name-ruleform { + margin-top: 15px; + + input { + width: 450px; + } + + .ipt-tip { + width: 453px; + line-height: 1.5; + margin-top: 6px; + @include size-weight-color($fontSize, $fontSmallWeight, $defaultColor); + } + + .error-tip { + @include size-weight-color($fontSize, $fontSmallWeight, $color13); + } + + .el-form-item__label { + @include display-align(flex-start); + margin-top: 5px; + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/formTable/EditInstanceNameForm.vue b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/formTable/EditInstanceNameForm.vue new file mode 100644 index 0000000..9711f4a --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/formTable/EditInstanceNameForm.vue @@ -0,0 +1,38 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/formTable/EditInstanceNameTable.vue b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/formTable/EditInstanceNameTable.vue new file mode 100644 index 0000000..00c76b9 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/formTable/EditInstanceNameTable.vue @@ -0,0 +1,116 @@ + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/formTable/ruleForm.ts b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/formTable/ruleForm.ts new file mode 100644 index 0000000..1183524 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/formTable/ruleForm.ts @@ -0,0 +1,18 @@ +class FormRulesOpt { + ruleForm: {instanceName: string} = reactive<{instanceName: string}>({ + instanceName: '' + }); + ruleFormRef: Ref = ref(); + + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: any}): void => { + this.ruleFormRef.value = formEl.value; + }; + +}; + +export default FormRulesOpt; diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/formTable/rulesCheck.ts b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/formTable/rulesCheck.ts new file mode 100644 index 0000000..0dd3b0c --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchEditInstanceName/formTable/rulesCheck.ts @@ -0,0 +1,59 @@ +import {language} from 'utils/publicClass.ts'; +import RegularContent from 'utils/regular.ts'; + +class RulesCheck { + iptTipVal: Ref = ref(language.t('batchOperate.instanceName.iptTip.text')); + errorFlag: Ref = ref(false); + rules: any = reactive({ + instanceName: [ + { + required: true, + trigger: 'blur', + validator: '' + } + ] + }); + + constructor() { + this.rules.instanceName[0].validator = this.instanceNameCheck; + } + + instanceNameCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + + const nameCheck = [ + [ + (value: string) => !value?.length, + () => { + this.errorFlag.value = true; + this.iptTipVal.value = language.t('batchOperate.instanceName.iptTip.empty') + callback(new Error()); + } + ], + [ + (value: string) => (!RegularContent.instanceNameReg.test(value)), + ()=> { + this.errorFlag.value = true; + this.iptTipVal.value = language.t('batchOperate.instanceName.iptTip.text'); + callback(new Error()); + } + ], + [ + (value: string) => value, + () => { + this.iptTipVal.value = language.t('batchOperate.instanceName.iptTip.text'); + this.errorFlag.value = false; + callback(); + } + ] + ] + + for (const key of nameCheck) { + if (key[0](value)) { + key[1](value) + break; + } + } + }; +}; + +export default RulesCheck; diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/BatchOpenCloseRestart.vue b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/BatchOpenCloseRestart.vue new file mode 100644 index 0000000..7eca1ea --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/BatchOpenCloseRestart.vue @@ -0,0 +1,51 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/batchOpenCloseRestart.scss b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/batchOpenCloseRestart.scss new file mode 100644 index 0000000..997c82b --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/batchOpenCloseRestart.scss @@ -0,0 +1,48 @@ +@import 'assets/css/deviceOperate.scss'; + +.open-close-restart { + .el-dialog { + &--center { + --el-dialog-width: 676px; + height: 355px; + + .el-table { + &__header-wrapper { + margin-bottom: 5px; + } + + &__row { + background-color: $background3; + + &:hover { + td { + background-color: $background10 !important; + } + } + } + } + + // table为空 + .el-table__inner-wrapper tr:first-child th { + &:first-child { + border-left: none; + } + + &:last-child { + border-color: $border16; + } + } + } + + &__footer { + width: 631px; + } + } + + &-content { + + .tip-title { + @extend %tip-title; + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/table/batchOpenCloseRestartTable.vue b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/table/batchOpenCloseRestartTable.vue new file mode 100644 index 0000000..0a1c579 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/table/batchOpenCloseRestartTable.vue @@ -0,0 +1,113 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/utils/batchOpenCloseRestart.ts b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/utils/batchOpenCloseRestart.ts new file mode 100644 index 0000000..b2991ff --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/utils/batchOpenCloseRestart.ts @@ -0,0 +1,62 @@ +import {msgTip} from 'utils/index.ts'; +import {language} from 'utils/publicClass.ts'; +import {SuccessType, CurrencyType} from '@utils/publicType'; +import {devicesBatchStopAPI, devicesBatchStartAPI, devicesBatchRestartAPI} from 'api/device/request.ts'; + +class BatchOpenCloseRestart { + // loading加载态 + isLoading: Ref = ref(false); + props: { + types: string; + selectArr: CurrencyType[]; + }; + emitValue: any; + + constructor (props: {types: string; selectArr: CurrencyType[];}, emitValue: any) { + this.props = props; + this.emitValue = emitValue; + }; + + /** + * 确定按钮弹窗 + */ + determineClick: () => Promise = async () => { + this.isLoading.value = true; + await this.requestOpenDownRestart(); + }; + + requestOpenDownRestart = () => { + const requestApi = new Map([ + ['open', devicesBatchStartAPI], + ['close', devicesBatchStopAPI], + ['restart', devicesBatchRestartAPI] + ]); + return this.getDevicesOperate(requestApi.get(this.props.types)); + }; + + getDevicesOperate = (requestUrl: (arg0: {instanceIds: string[]}) => Promise<{data: SuccessType}>) => { + requestUrl( + { + instanceIds: this.props.selectArr.map((item: CurrencyType) => item.instanceId) + } + ) + .then(({data} : {data: SuccessType}) => { + data?.result?.success && msgTip.success(language.t('operate.success')); + }) + .finally(() => { + this.isLoading.value = false; + this.cancelClick(); + this.emitValue('determine-click'); + }) + }; + + /** + * 取消按钮点击操作 + */ + cancelClick = (): void => { + // 回传父组件当前页码,可以处理相关操作 + this.emitValue('dia-log-close', false); + }; +}; + +export default BatchOpenCloseRestart; diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/utils/setTip.ts b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/utils/setTip.ts new file mode 100644 index 0000000..62c1bea --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchOpenCloseRestart/utils/setTip.ts @@ -0,0 +1,38 @@ +import {CurrencyType} from '@utils/publicType'; +import {language} from 'utils/publicClass.ts'; + +class SetTip { + + titleTip = (types: string) => { + const titleTip: CurrencyType = { + 'open': language.t('batchOperate.openCloseRestart.open'), + 'close': language.t('batchOperate.openCloseRestart.close'), + 'restart': language.t('batchOperate.openCloseRestart.restart') + }; + return titleTip[types]; + }; + + /** + * 开/关/重启操作返回对应的提示文案 + * @return {string} xxx 返回对应的提示信息 + */ + tooltipLeft = (types: string) => { + const tooltipInfo: CurrencyType = { + 'open': language.t('batchOperate.openCloseRestart.open1'), + 'close': language.t('batchOperate.openCloseRestart.close1'), + 'restart': language.t('batchOperate.openCloseRestart.restart1') + }; + return tooltipInfo[types]; + }; + + tooltipRight = (types: string) => { + const tooltipInfo: CurrencyType = { + 'open': language.t('batchOperate.openCloseRestart.open2'), + 'close': language.t('batchOperate.openCloseRestart.close2'), + 'restart': language.t('batchOperate.openCloseRestart.restart2') + }; + return tooltipInfo[types]; + }; +}; + +export default SetTip; diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchRecoveryInstance/BatchRecoveryInstance.vue b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchRecoveryInstance/BatchRecoveryInstance.vue new file mode 100644 index 0000000..be97821 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchRecoveryInstance/BatchRecoveryInstance.vue @@ -0,0 +1,194 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchRecoveryInstance/batchRecoveryInstance.scss b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchRecoveryInstance/batchRecoveryInstance.scss new file mode 100644 index 0000000..c3462b4 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchRecoveryInstance/batchRecoveryInstance.scss @@ -0,0 +1,65 @@ +@import 'assets/css/deviceOperate.scss'; + +.batch-recovery-instance { + .el-dialog { + &--center { + --el-dialog-width: 676px; + height: 402px; + + .el-table { + &__header-wrapper { + margin-bottom: 5px; + } + + &__row { + background-color: $background3; + + &:hover { + td { + background-color: $background10 !important; + } + } + } + } + + .el-table__inner-wrapper tr:first-child th { + &:first-child { + border-left: none; + } + + &:last-child { + border-color: $border16; + } + } + + .el-table__row { + background-color: $background3; + + &:hover { + td { + background-color: $background10 !important; + } + } + } + } + + &__body { + padding: 0; + } + + &__footer { + width: 631px; + } + } + + &-content { + + .warnning-tip { + @extend %warnning-tip; + } + + .tip-title { + @extend %tip-title; + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchResetPassword/BatchResetPassword.vue b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchResetPassword/BatchResetPassword.vue new file mode 100644 index 0000000..9440c63 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchResetPassword/BatchResetPassword.vue @@ -0,0 +1,206 @@ + + + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchResetPassword/batchResetPassword.scss b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchResetPassword/batchResetPassword.scss new file mode 100644 index 0000000..b9f799d --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchResetPassword/batchResetPassword.scss @@ -0,0 +1,146 @@ +@import 'assets/css/deviceOperate.scss'; + +.batch-reset-password { + .el-dialog { + &--center { + --el-dialog-width: 676px; + // height: 530px; + padding-bottom: 80px; + + .el-table { + &__header-wrapper { + margin-bottom: 5px; + } + + &__row { + background-color: $background3; + + &:hover { + td { + background-color: $background10 !important; + } + } + } + } + + // table为空 + .currency-count-table { + .el-table__inner-wrapper tr:first-child th { + &:first-child { + border-left: none; + } + + &:last-child { + border-color: $border16; + } + } + + .el-table__row { + background-color: $background3; + &:hover { + td { + background-color: $background10 !important; + } + } + } + } + } + + &__body { + padding: 0; + } + + &__footer { + width: 631px; + } + } + + &-content { + + // table为空 + .currency-count-table { + .img-empty { + .el-table__body { + padding-bottom: 0 !important; + } + .el-table__empty-block { + background: $whiteBackground; + + .el-table__empty-text { + color: $defaultColor; + } + } + } + } + + .tip-title { + @extend %tip-title; + } + + .warnning-tip { + @extend %plugin-warnning-tip; + + img { + @extend %img-count; + } + + .tip-count { + font-size: $fontSize; + padding: 10px 0; + + .reset-system-tip { + @include text-align(left); + line-height: 1.5; + padding: 0 10px 0 0; + } + } + } + } + + // 表单 + .rule-form { + margin-top: 15px; + + input { + width: 450px; + } + + .ipt-tip { + width: 453px; + line-height: 1.5; + margin-top: 6px; + @include size-weight-color($fontSize, $fontSmallWeight, $defaultColor); + } + + // 间隔 + .set-empty { + margin-bottom: 45px; + + .el-form-item__error { + padding-top: 8px; + @include break-wrap(break-all); + } + } + + // 自定义表单error文案颜色 + .error-color-tip { + color: $color13; + } + + // 常态表单error文案颜色 + .password-tip { + color: $color7; + } + + // 表单error文案、自定义表单error文案公共样式 + .error-color-tip, + .password-tip { + font-size: $fontSize; + font-weight: $fontSmallWeight; + @include display-align(center); + margin-top: 8px; + @include break-wrap(break-all); + line-height: 1.5; + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchResetPassword/utils/batchResetPasswordOpt.ts b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchResetPassword/utils/batchResetPasswordOpt.ts new file mode 100644 index 0000000..5293d42 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchResetPassword/utils/batchResetPasswordOpt.ts @@ -0,0 +1,70 @@ +import {deviceBatchResetPasswordAPI} from 'api/device/request.ts'; +import {msgTip} from 'utils/index.ts'; +import {language} from 'utils/publicClass.ts'; + +class BatchResetPasswordOpt { + // loading加载态 + isLoading: Ref = ref(false); + formRulesOperate: any; + emitValue: any; + checkArr: any; + + constructor(formRulesOperate: any, checkArr: any, emitValue: any) { + this.checkArr = checkArr; + this.emitValue = emitValue; + this.formRulesOperate = formRulesOperate; + document.onkeyup = (event: {keyCode: number;}) => { + event.keyCode === 13 && this.determineClick(); + }; + onUnmounted(() => document.onkeyup = (() => {return})); + }; + + /** + * 确定按钮弹窗 + */ + determineClick: () => Promise = async () => { + // 判断输入项是否符合条件 + await nextTick(() => { + this.formRulesOperate.ruleFormRef.value!.validate((valid: boolean) => { + // 输入符合条件后才可以继续后续操作 + if (valid) { + this.isLoading.value = true; + this.#requestBatchResetPssword(); + } + }); + }); + }; + + /** + * 请求接口,成功后把事件回传,关闭弹窗 + */ + #requestBatchResetPssword = (): string | void => { + const {ruleForm} = this.formRulesOperate; + deviceBatchResetPasswordAPI( + { + instanceIds: this.checkArr.map((item: {instanceId: string}) => item.instanceId), + password: ruleForm.newPassword + } + ) + .then(({data}: {data: {result: {success: boolean}}}) => { + if (data?.result?.success) { + msgTip.success(language.t('operate.success')); + } + }) + .finally(() => { + this.emitValue('determine-click'); + this.cancelClick(); + this.isLoading.value = false; + }) + }; + + /** + * 取消按钮点击操作 + */ + cancelClick = (): void => { + // 回传父组件当前页码,可以处理相关操作 + this.emitValue('dia-log-close', false); + }; +}; + +export default BatchResetPasswordOpt; diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchResetPassword/utils/formRules.ts b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchResetPassword/utils/formRules.ts new file mode 100644 index 0000000..a605bb9 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchResetPassword/utils/formRules.ts @@ -0,0 +1,48 @@ +import {RuleFormRefType} from '@utils/publicType'; + +class FormRulesOperate { + // 表单ref + ruleFormRef: Ref = ref(); + ruleForm: any = reactive({ + newPassword: '', + confirmPassword: '' + }); + rules = { + newPassword: [ // 邮箱 + { + required: true, + trigger: 'blur', + validator: '' + } + ], + confirmPassword: [ + { + required: true, + trigger: 'blur', + validator: '' + } + ], + }; + rulesCheck: any; + + + constructor (rulesCheck: any) { + this.rulesCheck = rulesCheck; + this.rules.newPassword[0].validator = rulesCheck.newPasswordCheck; + this.rules.confirmPassword[0].validator = rulesCheck.confirmPasswordCheck; + }; + + // setData = (item: any) => { + // // this.reactiveArr.tableData.push(item); + // }; + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: RuleFormRefType}): void => { + this.ruleFormRef.value = formEl.value; + }; +}; + +export default FormRulesOperate; diff --git a/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchResetPassword/utils/rulesCheck.ts b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchResetPassword/utils/rulesCheck.ts new file mode 100644 index 0000000..8e91229 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/BatchOperate/BatchResetPassword/utils/rulesCheck.ts @@ -0,0 +1,76 @@ +import RegularContent from 'utils/regular.ts'; +import {language} from 'utils/publicClass.ts'; + +class RulesCheck { + confirmPasswordFlag: Ref = ref(false); + errorTip: Ref = ref(language.t('batchOperate.resetPassword.ipt.errorTip.newPassword')); + colorStatus: Ref = ref(false); + newPassword: Ref = ref(''); + newPasswordCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + this.newPassword.value = value; + this.colorStatus.value = true; + const passwordArr = [ + [ + (value: string) => !value?.length, + () => { + this.errorTip.value = language.t('batchOperate.resetPassword.ipt.emptyTip.newPassword'); + callback(new Error()); + } + ], + [ + (value: string) => (!RegularContent.passwordReg.test(value)), + () => { + this.errorTip.value = language.t('batchOperate.resetPassword.ipt.errorTip.newPassword'); + callback(new Error()); + } + ], + [ + (value: string) => value, + () => { + this.errorTip.value = language.t('batchOperate.resetPassword.ipt.errorTip.newPassword'); + this.colorStatus.value = false; + callback(); + } + ] + ]; + for (const key of passwordArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + confirmPasswordCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + this.confirmPasswordFlag.value = true; + const confirmPasswordArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t('batchOperate.resetPassword.ipt.emptyTip.confirmPassword'))) + ], + [ + (value: string) => (!RegularContent.passwordReg.test(value)), + () => callback(new Error(language.t('batchOperate.resetPassword.ipt.errorTip.newPassword'))) + ], + [ + (value: string) => (value !== this.newPassword.value), + () => callback(new Error(language.t('batchOperate.resetPassword.ipt.errorTip.confirmPassword'))) + ], + [ + (value: string) => value, + () => { + this.confirmPasswordFlag.value = false; + callback(); + } + ] + ]; + for (const key of confirmPasswordArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; +}; + +export default RulesCheck; \ No newline at end of file diff --git a/bmp-operation-web/src/components/DeviceOperations/EditNotes/EditNotes.vue b/bmp-operation-web/src/components/DeviceOperations/EditNotes/EditNotes.vue new file mode 100644 index 0000000..6b5b6f8 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/EditNotes/EditNotes.vue @@ -0,0 +1,104 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/EditNotes/editNotes.scss b/bmp-operation-web/src/components/DeviceOperations/EditNotes/editNotes.scss new file mode 100644 index 0000000..a3f81f6 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/EditNotes/editNotes.scss @@ -0,0 +1,34 @@ +.edit-notes { + .el-dialog { + &--center { + --el-dialog-width: 526px; + height: 298px; + } + + &__footer { + width: 481px; + } + } + + &-count { + @extend %display-flex-column; + @include display-align(flex-start); + + p { + margin: 19.5px 0 8px; + font-size: $fontSize; + } + + textarea { + width: 480px; + height: 117px; + border-radius: 4px; + font-size: $fontSize; + @extend %resize-none; + + &::placeholder { + font-size: $fontSize; + } + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/ImportDevice/ImportDevice.vue b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/ImportDevice.vue new file mode 100644 index 0000000..4ee39a1 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/ImportDevice.vue @@ -0,0 +1,193 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/ImportDevice/importDevice.scss b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/importDevice.scss new file mode 100644 index 0000000..6789614 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/importDevice.scss @@ -0,0 +1,227 @@ +.import-device { + .el-dialog { + &--center { + --el-dialog-width: 707px; + height: 491px; + } + + &__body { + padding: 0; + + } + + &__footer { + width: 662px; + } + } + + &-ruleForm { + margin-top: 13px; + + .set-empty { + margin-bottom: 32px !important; + + .el-form-item__error { + margin-top: 6px !important; + } + } + + .el-form-item__error { + margin-top: 1px !important; + } + + .set-computer-room, + .set-model-name { + input { + width: 230px; + } + } + + .set-model-name, + .set-computer-room, + &-computer-room, + &-model-name { + .el-form-item__label { + margin-right: 30px; + } + + } + + .set-device-info { + .el-form-item__content { + a.el-upload-list__item-name { + width: 455px; + } + } + } + + .add-new-model { + margin-top: -12px; + margin-bottom: 20px; + } + + .error-add-new-model { + margin-bottom: 20px; + margin-top: -6px; + } + + .add-new-model, + .error-add-new-model { + font-size: $fontSize; + font-weight: $fontSmallWeight; + + span { + &:first-child { + @include set-cursor(text); + color: $color6; + } + + &:last-child { + @include set-cursor(pointer); + color: $color12; + } + } + } + + .operate-refresh { + @include display-align(center); + margin-left: 20px; + @include set-cursor(pointer); + + .refresh-rotate, + .refresh-img { + @include set-width-height(16px); + font-size: $fontSize; + background-image: url('~@/assets/img/listImg/refresh.png'); + @include position-repeat(0); + background-size: backgoundSize(auto); + margin-right: 5px; + } + + .refresh-rotate { + animation: rotation .8s linear infinite; + @include set-cursor(no-drop); + } + + @keyframes rotation { + 0% { + transform: rotate(0deg); + } + + 100% { + transform: rotate(360deg); + } + } + + &:hover { + color: $color1; + } + } + + &-device-info { + .el-form-item__content { + a.el-upload-list__item-name { + width: 465px; + } + } + } + + .set-device-info, + &-device-info { + .el-form-item__content { + margin-left: 30px; + @include display-align(flex-start); + @extend %display-flex-column; + + a.el-upload-list__item-name { + border-radius: 4px; + height: 30px; + @include display-align(center); + border: .63px solid $border2; + margin-right: 0; + text-decoration: none; + @include set-cursor(pointer); + @include size-weight-color($fontSize, $fontLargeWeight, $defaultColor); + + &:hover { + background: $whiteBackground; + } + } + + .el-upload-list__item-status-label { + top: 5px; + } + + .el-upload-list__item .el-icon--close { + top: 9px !important; + } + } + + .error-tip { + margin-bottom: -15px; + @include size-weight-color($fontSize, $fontSmallWeight, $color13); + } + + .template-down-load { + margin-left: 20px; + position: absolute; + left: 100px; + @include set-cursor(pointer); + @include size-weight-color($fontSize, $fontSmallWeight, $color12); + } + } + + .upload-tip { + @extend %display-flex-column; + margin-top: 22px; + @include size-weight-color($fontSize, $fontSmallWeight, $color6); + + p { + @include display-align(center); + margin-bottom: 10px; + line-height: 1.5; + + &:last-child { + margin-bottom: 0 !important; + } + } + } + + .el-form-item__label { + position: relative; + font-weight: $fontLargeWeight; + } + + .el-form-item__error { + margin-top: 5px; + } + + .el-input--default, + .el-form-item__content { + @include display-align(flex-start); + } + + .el-form-item__label, + .el-input__inner { + @include display-align(flex-start); + } + + .el-form-item--default { + margin-bottom: 20px; + + &:last-child { + margin-bottom: 0 !important; + } + } + + input { + width: 213px; + height: 30px; + border-radius: 4px; + + &:focus { + border-color: $border3; + } + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/ImportDevice/typeManagement.ts b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/typeManagement.ts new file mode 100644 index 0000000..611f3e7 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/typeManagement.ts @@ -0,0 +1,23 @@ +import {CurrencyType, RuleFormRefType, VerifyRulesType} from '@utils/publicType'; + +type RuleFormRefType2 = Omit; +// 'modelName' | +type key = 'idcName' | 'deviceInfo'; + +type RulesType = { + [k in key]: VerifyRulesType[]; +}; + +interface RuleFormType { + fileParams: CurrencyType; + idcName: string; + // modelName: string; + deviceInfo: CurrencyType[]; +}; + +export { + RulesType, + RuleFormType, + // RuleFormRefType, + RuleFormRefType2 +}; diff --git a/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/down.ts b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/down.ts new file mode 100644 index 0000000..062fe73 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/down.ts @@ -0,0 +1,14 @@ +const downLoad = () => { + + const templateDownLoad = () => { + const agreement: string = window.location.protocol; + const url: string = `${agreement}//${window.location.host}/data/device_import.xlsx`; + window.open(url, '_self'); + }; + + return { + templateDownLoad + }; +}; + +export default downLoad; diff --git a/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/formRules.ts b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/formRules.ts new file mode 100644 index 0000000..f6f7c15 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/formRules.ts @@ -0,0 +1,59 @@ +import {RuleFormType, RuleFormRefType2, RulesType} from '../typeManagement' +import {language} from 'utils/publicClass.ts'; + +interface DataType { + ruleFormRef: Ref; + ruleForm: RuleFormType; + rules: RulesType; +}; + +const formRules = () => { + const data: DataType = { + // 表单ref + ruleFormRef: ref(), + ruleForm: reactive({ + fileParams: {}, + idcName: '', // 机房名称 + // modelName: '', // 机型名称 + deviceInfo: [] // 设备信息 + }), + // 表单提交规则 + rules: reactive({ + idcName: [ // 机房名称 + { + required: true, + message: language.t('importDevice.errTip.computerRoomName'), + trigger: 'change' + } + ], + // modelName: [ // 机型名称 + // { + // required: true, + // message: language.t('importDevice.errTip.modelName'), + // trigger: 'change' + // } + // ], + deviceInfo: [ // 设备信息 + { + required: true, + trigger: 'change' + } + ] + }) + }; + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + const getFormRef = (formEl: {value: RuleFormRefType2}): void => { + data.ruleFormRef.value = formEl.value; + }; + + return { + ...data, + getFormRef + }; +}; + +export default formRules; diff --git a/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/idcList.ts b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/idcList.ts new file mode 100644 index 0000000..6f177c6 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/idcList.ts @@ -0,0 +1,76 @@ +import HeightStatus from './utils'; +import {AxiosError} from 'axios'; +import {CurrencyType} from '@utils/publicType'; +import {filterData, msgTip} from 'utils/index.ts'; +import {locationItem, CurrentInstance} from 'utils/publicClass.ts'; + +class IdcList extends HeightStatus { + idcListLoading: Ref = ref(true); + reactiveArr: { + idcName: string; + idcData: CurrencyType[]; + } = reactive<{ + idcName: string; + idcData: CurrencyType[]; + }>({ + idcName: '', + idcData: [] // 机房名称 + }); + proxy = new CurrentInstance().proxy; + + constructor (formRulesOperate: any, fn: any) { + super(formRulesOperate); + this.getIdcList(); + this.watchIdcName(formRulesOperate, fn); + }; + + getIdcList = async () => { + try { + const idcApi = await this.proxy.$idcApi.idcListAPI({isAll: '1'}); + if (idcApi?.data?.result?.idcs?.length) { + const newIdcsData = filterData((idcApi.data.result.idcs), 'name').map((item: CurrencyType) => { + return { + ...item, + newIdcName: this.#setName(locationItem.getLocationItem, item) + } + }); + this.reactiveArr.idcData = newIdcsData; + return; + } + throw new Error(''); + } + catch (e) { + const err = e as AxiosError; + this.reactiveArr.idcData = []; + err.message && msgTip.error(err.message); + } + finally { + this.idcListLoading.value = false; + } + }; + + #setName = (name: string, item: CurrencyType) => { + const keyName: Map = new Map([ + ['zh_CN', item.name], + ['en_US', item.nameEn] + ]); + return keyName.get(name); + }; + + watchIdcName = (formRulesOperate: any, fn: any) => { + watch(() => formRulesOperate.ruleForm.idcName, (newValue: string) => { + if (newValue) { + this.reactiveArr.idcName = newValue; + if (formRulesOperate.ruleForm.modelName) { + formRulesOperate.ruleForm.modelName = ''; + this.hasClick.value = true; + } + fn(); + // modelList.modelNameLoading.value = true; + // modelList.getModelList(); + } + }) + }; +}; + +export default IdcList; diff --git a/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/importDevice.ts b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/importDevice.ts new file mode 100644 index 0000000..a2ee8f3 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/importDevice.ts @@ -0,0 +1,94 @@ +import {msgTip} from 'utils/index.ts'; +import {importDevicesAPI} from 'api/device/request.ts'; +import {language} from 'utils/publicClass.ts'; +import router from 'router/index.ts'; +// import {removeLong} from 'request/index.ts'; +import {removeLong} from 'request/RemoveLongReq/remove.ts'; + +const importDevice = (formRules: any, upLoadOperate: any, heightStatus: any, emitValue: any) => { + // loading 加载态 + const isLoading: Ref = ref(false); + + onMounted(() => { + document.onkeyup = (event: {keyCode: number;}) => { + event.keyCode === 13 && determineClick(); + }; + }); + + /** + * 确定按钮弹窗 + */ + const determineClick = async (): Promise => { + // 判断输入项是否符合条件 + await nextTick(() => { + formRules.ruleFormRef.value!.validate((valid: boolean) => { + // 输入符合条件后才可以继续后续操作 + if (valid) { + if (formRules.ruleForm.fileParams?.result?.length) { + isLoading.value = true; + upLoadOperate.hasError.value = false; + requestImportDevice(); + } + } + else if (!formRules.ruleForm.deviceInfo.length) { + upLoadOperate.hasError.value = true; + heightStatus.hasClick.value = true; + } + else { + if (!valid) return; + msgTip.warning(language.t('importDevice.errTip.upload')); + upLoadOperate.hasError.value = false; + heightStatus.hasClick.value = true; + } + }); + }); + }; + + /** + * 请求导入设备接口,成功后把事件回传,关闭弹窗 + */ + const requestImportDevice = (): void => { + importDevicesAPI( + { + idcId: formRules.ruleForm.idcName, + deviceTypeId: formRules.ruleForm.modelName, + devices: formRules.ruleForm.fileParams.result + } + ) + .then(({data} : {data: {result: {success: boolean}}}) => { + if (data?.result?.success) { + msgTip.success(language.t('operate.success')); + emitValue('determine-click'); + cancelClick(); + return; + } + }) + .finally(() => { + isLoading.value = false; + }); + }; + + /** + * 取消按钮点击操作 + */ + const cancelClick = (): void => { + // 回传父组件当前页码,可以处理相关操作 + emitValue('dia-log-close', false); + // 清空输入内容、异常提示状态 + formRules.ruleFormRef.value!.resetFields(); + upLoadOperate.uploads.value!.abort(); + upLoadOperate.uploads.value!.clearFiles(); + if (formRules.ruleForm.fileParams?.result?.length) { + removeLong(router.currentRoute.value.name); + // removeLong(router.currentRoute.value.name); + } + }; + + return { + isLoading, + determineClick, + cancelClick + }; +}; + +export default importDevice; diff --git a/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/modelList.ts b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/modelList.ts new file mode 100644 index 0000000..f810857 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/modelList.ts @@ -0,0 +1,71 @@ +import HeightStatus from './utils'; +import {CurrencyType} from '@utils/publicType'; +import {CurrentInstance} from 'utils/publicClass'; +import {modelListAPI} from 'api/model/request.ts'; +import {msgTip} from 'utils/index.ts'; + +class ModelList extends HeightStatus { + hasRotate: Ref = ref(false); + modelNameLoading: Ref = ref(false); + reactiveArr: { + modelData: CurrencyType[]; + } = reactive<{ + modelData: CurrencyType[]; + }>({ + modelData: [] // 机型名称 + }); + idcList: any; + formRulesOperate: any; + heightStatus: any; + instanceProxy = new CurrentInstance().proxy; + + constructor(idcList: any, formRulesOperate: any, heightStatus: any) { + super(formRulesOperate); + this.formRulesOperate = formRulesOperate; + this.idcList = idcList; + this.heightStatus = heightStatus; + }; + + getModelList = () => { + modelListAPI( + { + isAll: '1', + idcId: this.idcList.reactiveArr.idcName + } + ) + .then(({data} : {data: {result: {deviceTypes: CurrencyType[];}}}) => { + if (data?.result?.deviceTypes?.length) { + this.reactiveArr.modelData = data.result.deviceTypes; + return; + } + this.reactiveArr.modelData = []; + }) + .catch(({message} : {message: string}) => { + this.idcList.reactiveArr.idcData.length && msgTip.error(message); + this.reactiveArr.modelData = []; + }) + .finally(() => { + this.modelNameLoading.value = false; + this.hasRotate.value = false; + }); + }; + + jumpPage = () => { + const path: string = this.instanceProxy!.$defInfo.routerPath('modelList') as unknown as string; + window.open(path, '_blank') + }; + + resetData = () => { + if (!this.formRulesOperate.ruleForm.idcName.length) return; + if (this.hasRotate.value) return; + this.formRulesOperate.ruleForm.modelName = ''; + this.reactiveArr.modelData = []; + this.hasRotate.value = true; + this.formRulesOperate.ruleFormRef.value!.validate((valid: boolean) => { + if (!valid) this.heightStatus.hasClick.value = true; + }) + this.getModelList(); + }; +}; + +export default ModelList; diff --git a/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/upLoad.ts b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/upLoad.ts new file mode 100644 index 0000000..0a8d1cd --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/upLoad.ts @@ -0,0 +1,77 @@ +import {CurrencyType, UpLoadsType} from '@utils/publicType'; +import {msgTip} from 'utils/index.ts'; +import {language, CurrentInstance} from 'utils/publicClass.ts'; + +class UpLoadOperate { + // 上传 + uploads: Ref = ref(); + // 是否显示异常提示-默认false + hasError: Ref = ref(false); + formRulesOperate: any; + instanceProxy = new CurrentInstance().proxy; + + constructor (formRulesOperate: any) { + this.formRulesOperate = formRulesOperate; + }; + + /** + * 上传的event事件 + */ + uploadEvent = (refs: {value: UpLoadsType}): void => { + this.uploads.value = refs.value; + + }; + + handleChange = (_: unknown, data: Array) => { + this.formRulesOperate.ruleForm.deviceInfo = data; + this.uploads.value!.submit(); + }; + + /** + * 上传成功的返回 + */ + uploadSuccess = (data: CurrencyType): void => { + this.formRulesOperate.ruleForm.fileParams = data; + this.hasError.value = false; + }; + + /** + * 点击删除上传信息时触发 + */ + removeChange = (): boolean => { + this.formRulesOperate.ruleForm.deviceInfo = []; + return this.hasError.value = false; + }; + + progressChange = (info: {percent: number | {toFixed(arg0: number): number;}}) => { + this.hasError.value = false; + info.percent = Number(info.percent.toFixed(2)); + }; + /** + * 仅限上传一次,第二次上次替换第一次的值时-触发 + * @param {Object} files 上传的文件 + */ + handleExceed = (files: CurrencyType[]): void => { + this.uploads?.value!.clearFiles(); + const file: CurrencyType = files[0]; + this.uploads.value!.handleStart(file); + this.hasError.value = false; + }; + + /** + * 上传失败的返回 + * @param {Object} error 失败信息 + */ + errorChange = (error: Error & string): void => { + const status = JSON.parse(JSON.stringify(error)).status; + if (status === 402) { + const path: string = this.instanceProxy!.$defInfo.routerPath('login') as unknown as string; + window.open(path, '_self'); + return; + } + const errorInfo = JSON.parse(error.message); + msgTip.error(errorInfo?.error?.message??language.t('importDevice.errTip.error')); + }; +}; + +export default UpLoadOperate; diff --git a/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/utils.ts b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/utils.ts new file mode 100644 index 0000000..0d943cc --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ImportDevice/utils/utils.ts @@ -0,0 +1,13 @@ +class HeightStatus { + hasClick: Ref = ref(false); + + constructor(formRulesOperate: any) { + watch(() => formRulesOperate.ruleForm.modelName, (newValue) => { + if (newValue) { + this.hasClick.value = false; + } + }) + }; +}; + +export default HeightStatus; diff --git a/bmp-operation-web/src/components/DeviceOperations/Lock/Lock.vue b/bmp-operation-web/src/components/DeviceOperations/Lock/Lock.vue new file mode 100644 index 0000000..b6f0c1d --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/Lock/Lock.vue @@ -0,0 +1,125 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/Lock/lock.scss b/bmp-operation-web/src/components/DeviceOperations/Lock/lock.scss new file mode 100644 index 0000000..2037433 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/Lock/lock.scss @@ -0,0 +1,45 @@ +.lock-instance { + .el-dialog { + &--center { + --el-dialog-width: 520px; + height: 292px; + } + + &__body { + + .currency-count { + @extend %display-flex-column; + + .lock-count { + padding: 9px 15px; + border-radius: 2px; + background: $background17; + margin-top: 20px; + @include display-align(flex-start); + @extend %justify-center ; + margin-bottom: -30px; + + &-icon { + @include set-width-height(16px); + margin-right: 20px; + } + + &-tip { + font-size: $fontSize; + } + } + + &-title { + margin-top: 80px; + padding-bottom: 131px; + @include text-align(center); + @include size-weight-color($fontSize2, $fontSmallWeight, $defaultColor); + } + } + } + + &__footer { + width: 475px; + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/OpenShutDownRestart/OpenShutDownRestart.vue b/bmp-operation-web/src/components/DeviceOperations/OpenShutDownRestart/OpenShutDownRestart.vue new file mode 100644 index 0000000..95ab23a --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/OpenShutDownRestart/OpenShutDownRestart.vue @@ -0,0 +1,128 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/OpenShutDownRestart/openShutDownRestart.scss b/bmp-operation-web/src/components/DeviceOperations/OpenShutDownRestart/openShutDownRestart.scss new file mode 100644 index 0000000..3d89b5c --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/OpenShutDownRestart/openShutDownRestart.scss @@ -0,0 +1,28 @@ +.open-shut-down-restart { + .el-dialog { + &--center { + --el-dialog-width: 526px; + height: 298px; + } + + &__footer { + width: 481px; + } + } + + &-count { + @include display-align(center); + @extend %justify-center; + margin-top: 80px; + @include size-weight-color($fontSize2, $fontSmallWeight, $defaultColor); + + &-title { + color: $defaultColor; + } + + &-info { + font-weight: $fontLargeWeight; + margin-right: 5px; + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/RemoveRecovery.vue b/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/RemoveRecovery.vue new file mode 100644 index 0000000..adc373b --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/RemoveRecovery.vue @@ -0,0 +1,63 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/removeRecovery.scss b/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/removeRecovery.scss new file mode 100644 index 0000000..56ff0c6 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/removeRecovery.scss @@ -0,0 +1,102 @@ +.remove-recovery{ + &-checkbox { + @include display-align(center); + margin-top: 10px; + } + + .el-dialog { + &--center { + --el-dialog-width: 646px; + height: 500px; + } + + &__body { + padding: 0; + + .el-table__row { + background: $background12; + } + + .currency-count { + @extend %display-flex-column; + + .el-checkbox__inner { + @include set-width-height(12px); + + &::after { + left: 3px; + height: 5px; + } + } + .header-title { + margin: 19.5px 0 20px; + @include size-weight-color($fontSize, $fontLargeWeight, $defaultColor); + } + + &-title { + width: 580px; + padding-right: 20px; + @include text-align(center); + border-radius: 2px; + background: $background13; + margin: 19.5px 0 .5px; + @include display-align(flex-start); + @include size-weight-color($fontSize, $fontSmallWeight, $defaultColor); + + .icon { + @include text-align(left); + margin-top: 6px; + color: $color16; + font-size: 19px; + margin-left: 5px; + } + + .text-count { + color: $color16; + @include text-align(left); + padding: 10px 8px; + } + + img { + @include set-width-height(32px); + transform: scale(.5); + margin-right: -2px + } + } + + .text-tip { + color: $defaultColor; + } + + &-table { + .el-table__header-wrapper { + margin-bottom: 5px; + } + + .el-table__inner-wrapper tr:first-child th { + &:first-child { + border-left: none; + } + + &:last-child { + border-color: $border16; + } + } + + .el-table__row { + background-color: $background3; + &:hover { + td { + background-color: $background10 !important; + } + } + } + } + } + } + + &__footer { + width: 601px; + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/table/RemoveRecoveryTable.vue b/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/table/RemoveRecoveryTable.vue new file mode 100644 index 0000000..b5e08a4 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/table/RemoveRecoveryTable.vue @@ -0,0 +1,142 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/utils/removeRecovery.ts b/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/utils/removeRecovery.ts new file mode 100644 index 0000000..c6a0ee9 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/utils/removeRecovery.ts @@ -0,0 +1,87 @@ +import {msgTip} from 'utils/index.ts'; +import {language} from 'utils/publicClass.ts'; +import {TableDataType, ParamsType} from './type'; +import {SuccessType} from '@utils/publicType'; +import {devicesRemoveAPI, instanceRecoveryAPI} from 'api/device/request.ts'; + +class RemoveRecovery { + // loading加载态 + isLoading: Ref = ref(false); + // 使用mitt传值 + instanceMitt: any = getCurrentInstance(); + // 表格数据 + tableData: TableDataType[] = reactive([]); + checkboxStatus: Ref = ref(false); + props: {title: string} = {title: ''}; + emitValue: any; + + constructor(props: {title: string}, emitValue: any) { + this.props = props; + this.emitValue = emitValue; + // 监听mitt-remove-recovery-table,获取表格数据 + this.instanceMitt?.proxy?.$Bus?.on('device-table', this.getTableFn); + }; + + /** + * 确定按钮弹窗 + */ + determineClick: () => Promise = async () => { + this.isLoading.value = true; + await this.#getRequestApi(); + }; + + #getRequestApi = () => { + const requestData = new Map([ + ['remove', devicesRemoveAPI], + ['recovery', instanceRecoveryAPI] + ]); + return this.#requestRemoveRecovery(requestData.get(this.props.title), this.props.title) + }; + + /** + * @param {Function} requestUrl url请求地址 + */ + #requestRemoveRecovery = (requestUrl: (arg0: ParamsType) => Promise<{data: SuccessType}>, type: string) => { + requestUrl( + { + ...this.#setParams(type) + } + ) + .then(({data} : {data: SuccessType}) => { + if (data?.result?.success) { + msgTip.success(language.t('operate.success')); + } + }).finally(() => { + this.isLoading.value = false; + this.cancelClick(); + this.emitValue('determine-click', type); + }); + }; + + #setParams = (type: string) => { + const params = new Map([ + ['remove', {deviceId: this.tableData[0].deviceId}], + ['recovery', {instanceId: this.tableData[0].instanceId}] + ]); + return params.get(type); + }; + + /** + * 取消按钮点击操作 + */ + cancelClick = () => { + // 回传父组件当前页码,可以处理相关操作 + this.emitValue('dia-log-close', false); + this.instanceMitt.proxy.$Bus.off('device-table', this.getTableFn); + }; + + /** + * 获取表格数据函数 + * @param {Object} item 表格数据 + */ + getTableFn: unknown = ({list}: {list: TableDataType;}) => { + this.tableData.push(list); + }; +}; + +export default RemoveRecovery; diff --git a/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/utils/setInfo.ts b/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/utils/setInfo.ts new file mode 100644 index 0000000..a1a623c --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/utils/setInfo.ts @@ -0,0 +1,42 @@ +import {language} from 'utils/publicClass.ts'; +import {CurrencyType} from '@utils/publicType'; + +class SetInfo { + title = (title: string) => { + const titleData: CurrencyType = { + 'remove': language.t('removeRecovery.header.remove'), + 'recovery': language.t('removeRecovery.header.recovery') + }; + return titleData[title]; + }; + + /** + * header头部标题 + * @return {string} xxx 对应标题的内容 + */ + headerTitle = (title: string) => { + const headerTitle: CurrencyType = { + 'remove': language.t('removeRecovery.tooltip.remove'), + 'recovery': language.t('removeRecovery.tooltip.recovery') + }; + return headerTitle[title]; + }; + + tooltipCount = (title: string) => { + const tip: CurrencyType = { + 'remove': language.t('removeRecovery.operateTip.remove'), + 'recovery': language.t('removeRecovery.operateTip.recovery') + }; + return tip[title]; + }; + + sureTip = (title: string) => { + const tip: CurrencyType = { + 'remove': language.t('removeRecovery.checkbox.remove'), + 'recovery': language.t('removeRecovery.checkbox.recovery') + }; + return tip[title]; + }; +} + +export default SetInfo; diff --git a/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/utils/type.ts b/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/utils/type.ts new file mode 100644 index 0000000..9daa270 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ReomveRecovery/utils/type.ts @@ -0,0 +1,19 @@ +// 表格类 +interface TableDataType { + sn: string; + instanceName: string; + instanceId: string; + userName: string; + privateIpv4: string; + deviceId: string; +}; + +type ParamsType = { + deviceId?: string; + instanceId?: string; +}; + +export { + TableDataType, + ParamsType +} diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetCollect/ClearRaidConfirm.vue b/bmp-operation-web/src/components/DeviceOperations/ResetCollect/ClearRaidConfirm.vue new file mode 100644 index 0000000..20808c5 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetCollect/ClearRaidConfirm.vue @@ -0,0 +1,82 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetCollect/CollectInfoConfirm.vue b/bmp-operation-web/src/components/DeviceOperations/ResetCollect/CollectInfoConfirm.vue new file mode 100644 index 0000000..ea0caf7 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetCollect/CollectInfoConfirm.vue @@ -0,0 +1,96 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetCollect/clearRaidConfirm.scss b/bmp-operation-web/src/components/DeviceOperations/ResetCollect/clearRaidConfirm.scss new file mode 100644 index 0000000..d101f47 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetCollect/clearRaidConfirm.scss @@ -0,0 +1,80 @@ +.clear-info-confirm{ + + &-checkbox { + @include display-align(center); + margin-top: 10px; + } + + .el-dialog { + &--center { + --el-dialog-width: 696px; + height: 300px; + } + + &__body { + padding: 0; + + .el-table__row { + background: $background12; + } + + .currency-count { + @extend %display-flex-column; + + .header-title { + // width: 600px; + font-size: $fontSize; + font-weight: $fontLargeWeight; + color: $defaultColor; + margin: 19.5px 0 20px; + } + + &-title { + // width: 580px; + padding-right: 20px; + // min-height: 34px; + text-align: center; + border-radius: 2px; + background: $background13; + color: $defaultColor; + font-size: $fontSize; + font-weight: $fontSmallWeight; + // line-height: 34px; + margin: 19.5px 0 .5px; + @include display-align(flex-start); + // @extend %display-flex-start; + + .icon { + text-align: left; + margin-top: 6px; + color: $color16; + font-size: $fontSize3; + margin-left: 5px; + } + + .text-count { + color: $color16; + text-align: left; + padding: 10px 8px; + font-size: $fontSize; + } + + img { + width: 32px; + height: 32px; + transform: scale(.5); + margin-right: -2px + } + } + + .text-tip { + color: $defaultColor; + } + } + } + + &__footer { + width: 651px; + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetCollect/index.scss b/bmp-operation-web/src/components/DeviceOperations/ResetCollect/index.scss new file mode 100644 index 0000000..5f93492 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetCollect/index.scss @@ -0,0 +1,43 @@ +.collect-info-confirm{ + + &-checkbox { + // @extend %display-flex-align; + @include display-align(center); + margin-top: 10px; + + .el-checkbox__inner { + border-radius: 0; + } + } + + .el-dialog { + &--center { + --el-dialog-width: 646px; + padding-bottom: 50px; + height: 300px; + } + + &__body { + padding: 0; + + .currency-count { + margin-top: 20px; + } + + .el-table__row { + background: $background12; + } + + .text-count { + color: $color16; + text-align: left; + padding: 10px 10px 10px 0; + font-size: $fontSize; + } + } + + &__footer { + width: 601px; + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetInstance/ResetInstance.vue b/bmp-operation-web/src/components/DeviceOperations/ResetInstance/ResetInstance.vue new file mode 100644 index 0000000..7108ae3 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetInstance/ResetInstance.vue @@ -0,0 +1,104 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetInstance/resetInstance.scss b/bmp-operation-web/src/components/DeviceOperations/ResetInstance/resetInstance.scss new file mode 100644 index 0000000..d214884 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetInstance/resetInstance.scss @@ -0,0 +1,45 @@ +.reset-instance { + .el-dialog { + &--center { + --el-dialog-width: 528px; + height: 298px; + } + + &__footer { + width: 482px; + } + } + + .tip-count { + padding: 10px 8px; + // width: 540px; + background: rgba(254, 249, 237, 1); + color: $defaultColor; + display: flex; + font-size: $fontSize; + // font-weight: $fontLargeWeight; + margin: 20px 0 35px; + + .tip-img { + // @extend %width-height; + @include set-width-height(16px); + margin-right: 10px; + } + } + + &-count { + // @extend %display-flex-align; + @include display-align(center); + @extend %justify-center; + font-size: $fontSize2; + color: $defaultColor; + + &-info { + margin-right: 5px; + + span { + font-weight: $fontLargeWeight; + } + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetPassword/ResetPassword.vue b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/ResetPassword.vue new file mode 100644 index 0000000..fbae2f8 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/ResetPassword.vue @@ -0,0 +1,59 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetPassword/resetPassword.scss b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/resetPassword.scss new file mode 100644 index 0000000..c9d3200 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/resetPassword.scss @@ -0,0 +1,136 @@ +@import 'assets/css/deviceOperate.scss'; + +.reset-password { + .el-dialog { + &--center { + --el-dialog-width: 676px; + height: 530px; + + .el-table { + &__header-wrapper { + margin-bottom: 5px; + } + + &__row { + background-color: $background3; + &:hover { + td { + background-color: $background10 !important; + } + } + } + } + } + + &__body { + padding: 0; + } + + &__footer { + width: 631px; + } + } + + &-content { + + // table为空 + .currency-count-table { + .el-table__inner-wrapper tr:first-child th { + &:first-child { + border-left: none; + } + + &:last-child { + border-color: $border16; + } + } + } + + .warnning-tip { + // text-align: center; + // border-radius: 2px; + // background: rgb(249, 237, 239); + // display: flex; + // align-items: flex-start; + // margin-top: 15px; + // justify-content: center; + @extend %warnning-tip; + + // img { + // width: 32px; + // height: 32px; + // transform: scale(.5); + // margin-left: 10px; + // margin-top: 1px; + // } + + // span { + // font-size: $fontSize; + // color: $defaultColor; + // padding-right: 30px; + // font-weight: $fontSmallWeight; + // margin-top: 8px; + // } + } + + .tip-title { + @extend %tip-title; + // font-size: $fontSize; + // color: $defaultColor; + // margin: 15px 0; + + // span { + // color: $color1; + // } + } + } + + // 表单 + .rule-form { + margin-top: 15px; + + input { + width: 450px; + } + + .ipt-tip { + font-size: $fontSize; + color: $defaultColor; + width: 453px; + line-height: 1.5; + margin-top: 6px; + } + + // 间隔 + .set-empty { + margin-bottom: 45px; + + .el-form-item__error { + padding-top: 8px; + @include break-wrap(break-all); + } + } + + // 自定义表单error文案颜色 + .error-color-tip { + color: $color13; + } + + // 常态表单error文案颜色 + .password-tip { + color: $color7; + } + + // 表单error文案、自定义表单error文案公共样式 + .error-color-tip, + .password-tip { + font-size: $fontSize; + font-weight: $fontSmallWeight; + // @extend %display-flex-align; + @include display-align(center); + margin-top: 8px; + @include break-wrap(break-all); + line-height: 1.5; + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetPassword/ruleForm/DeviceResetPasswordForm.vue b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/ruleForm/DeviceResetPasswordForm.vue new file mode 100644 index 0000000..38a9f4c --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/ruleForm/DeviceResetPasswordForm.vue @@ -0,0 +1,61 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetPassword/table/DeviceResetPasswordTable.vue b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/table/DeviceResetPasswordTable.vue new file mode 100644 index 0000000..15c3f9b --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/table/DeviceResetPasswordTable.vue @@ -0,0 +1,114 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetPassword/utils/formRules.ts b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/utils/formRules.ts new file mode 100644 index 0000000..757338a --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/utils/formRules.ts @@ -0,0 +1,27 @@ +import {RuleFormRefType} from '@utils/publicType'; + +class FormRulesOperate { + reactiveArr: any = reactive({ + tableData: [] + }); + // 表单ref + ruleFormRef: Ref = ref(); + ruleForm: any = reactive({ + newPassword: '', + confirmPassword: '' + }); + + setData = (item: any) => { + this.reactiveArr.tableData.push(item); + }; + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: RuleFormRefType}): void => { + this.ruleFormRef.value = formEl.value; + }; +}; + +export default FormRulesOperate; diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetPassword/utils/propsOperate.ts b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/utils/propsOperate.ts new file mode 100644 index 0000000..8c16562 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/utils/propsOperate.ts @@ -0,0 +1,18 @@ +import {CurrentInstance} from 'utils/publicClass.ts'; + +const propsOperate = (fn: any) => { + const instanceMitt: any = new CurrentInstance(); + + const getTableFn = (item: any) => { + fn(item); + }; + + // 监听mitt-device-table,获取表格数据 + instanceMitt?.proxy?.$Bus?.on('reset-password', getTableFn); + + onUnmounted(() => { + instanceMitt?.proxy?.$Bus?.off('reset-password', getTableFn); + }) +} + +export default propsOperate; diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetPassword/utils/resetPassword.ts b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/utils/resetPassword.ts new file mode 100644 index 0000000..b3d529d --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/utils/resetPassword.ts @@ -0,0 +1,69 @@ +import {devicesResetPasswordAPI} from 'api/device/request.ts'; +import {msgTip} from 'utils/index.ts'; +import {language} from 'utils/publicClass.ts'; + +class ResetPassword { + // loading加载态 + isLoading: Ref = ref(false); + formRulesOperate: any; + emitValue: any; + + constructor(formRulesOperate: any, emitValue: any) { + this.emitValue = emitValue; + this.formRulesOperate = formRulesOperate; + document.onkeyup = (event: {keyCode: number;}) => { + event.keyCode === 13 && this.determineClick(); + }; + onUnmounted(() => document.onkeyup = (() => {return})); + }; + + /** + * 确定按钮弹窗 + */ + determineClick: () => Promise = async () => { + // 判断输入项是否符合条件 + await nextTick(() => { + this.formRulesOperate.ruleFormRef.value!.validate((valid: boolean) => { + // 输入符合条件后才可以继续后续操作 + if (valid) { + this.isLoading.value = true; + this.#requestResetPssword(); + } + }); + }); + }; + + /** + * 请求接口,成功后把事件回传,关闭弹窗 + */ + #requestResetPssword = () => { + const {reactiveArr, ruleForm} = this.formRulesOperate; + devicesResetPasswordAPI( + { + instanceId: reactiveArr.tableData[0].instanceId, + idcId: reactiveArr.tableData[0].idcId, + password: ruleForm.newPassword + } + ) + .then(({data}: any) => { + if (data?.result?.success) { + msgTip.success(language.t('operate.success')); + } + }) + .finally(() => { + this.emitValue('determine-click'); + this.cancelClick(); + this.isLoading.value = false; + }) + }; + + /** + * 取消按钮点击操作 + */ + cancelClick = (): void => { + // 回传父组件当前页码,可以处理相关操作 + this.emitValue('dia-log-close', false); + }; +}; + +export default ResetPassword; diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetPassword/utils/rulesCheck.ts b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/utils/rulesCheck.ts new file mode 100644 index 0000000..4b9126a --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetPassword/utils/rulesCheck.ts @@ -0,0 +1,94 @@ +import RegularContent from 'utils/regular.ts'; +import {language} from 'utils/publicClass.ts'; + +class RulesCheck { + confirmPasswordFlag: Ref = ref(false); + errorTip: Ref = ref(language.t('resetPassword.ipt.errorTip.newPassword')); + colorStatus: Ref = ref(false); + newPassword: Ref = ref(''); + + newPasswordCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + this.newPassword.value = value; + this.colorStatus.value = true; + const passwordArr = [ + [ + (value: string) => !value?.length, + () => { + this.errorTip.value = language.t('resetPassword.ipt.emptyTip.newPassword'); + callback(new Error()); + } + ], + [ + (value: string) => (!RegularContent.passwordReg.test(value)), + () => { + this.errorTip.value = language.t('resetPassword.ipt.errorTip.newPassword'); + callback(new Error()); + } + ], + [ + (value: string) => value, + () => { + this.errorTip.value = language.t('resetPassword.ipt.errorTip.newPassword'); + this.colorStatus.value = false; + callback(); + } + ] + ]; + for (const key of passwordArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + confirmPasswordCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + this.confirmPasswordFlag.value = true; + const confirmPasswordArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t('resetPassword.ipt.emptyTip.confirmPassword'))) + ], + [ + (value: string) => (!RegularContent.passwordReg.test(value)), + () => callback(new Error(language.t('resetPassword.ipt.errorTip.newPassword'))) + ], + [ + (value: string) => (value !== this.newPassword.value), + () => callback(new Error(language.t('resetPassword.ipt.errorTip.confirmPassword'))) + ], + [ + (value: string) => value, + () => { + this.confirmPasswordFlag.value = false; + callback(); + } + ] + ]; + for (const key of confirmPasswordArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + rules = { + newPassword: [ // 邮箱 + { + required: true, + trigger: 'blur', + validator: this.newPasswordCheck + } + ], + confirmPassword: [ + { + required: true, + trigger: 'blur', + validator: this.confirmPasswordCheck + } + ] + }; +}; + +export default RulesCheck; \ No newline at end of file diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetSystem/FormSubmit/ResetSystemFormSubmit.vue b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/FormSubmit/ResetSystemFormSubmit.vue new file mode 100644 index 0000000..000023f --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/FormSubmit/ResetSystemFormSubmit.vue @@ -0,0 +1,349 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetSystem/FormSubmit/submitIpt.ts b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/FormSubmit/submitIpt.ts new file mode 100644 index 0000000..db769af --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/FormSubmit/submitIpt.ts @@ -0,0 +1,310 @@ +/** + * @file + * @author +*/ + +// keyInfoAPI,systemRaidsAPI +import {queryImagesAPI} from 'api/public/request.ts'; +import {instanceDetailAPI} from 'api/device/request.ts'; +import {language, CurrentInstance} from 'utils/publicClass.ts'; +import {CurrencyType, RuleFormRefType, StatusParamsType, SystemPartitionType} from '@utils/publicType'; +import store from 'store/index.ts'; +import * as allType from '../type'; + +class RuleOperate { + rules: allType.RuleType = { + hostName: [ + { + required: false, + trigger: 'blur', + validator: '' + } + ], + password: [ // 邮箱 + { + required: true, + trigger: 'blur', + validator: '' + } + ], + confirmPassword: [ + { + required: true, + trigger: 'blur', + validator: '' + } + ], + }; + rulesCheck: allType.RulesCheckType; + + constructor (rulesCheck: allType.RulesCheckType) { + this.rulesCheck = rulesCheck; + this.rules.hostName[0].validator = rulesCheck.hostNameCheck; + this.rules.password[0].validator = rulesCheck.passwordCheck; + this.rules.confirmPassword[0].validator = rulesCheck.confirmPasswordCheck; + } +}; + +class DataOperate extends RuleOperate { + isLoading: Ref = ref(true); + selectStatus: Ref = ref(false); + showRemaining: Ref = ref(false); + currIndex: Ref = ref(0); + selectCurrIndex: Ref = ref(0); + systemCurrIndex: Ref = ref(0); + bootModeCurrIndex: Ref = ref(0); + reactiveArr: allType.ReactiveArrType = reactive({ + tableData: [], + centOSData: [], + imageTypekeyData: [ + { + name: '--', + initName: '--' + } + ], + systemDiskData: [ + { + raidId: '--', + raidName: '--', + volumeDetail: '--', + diskType: '--' + } + ], + keyPariData: [], + systemPartitionData: [ + { + format: '--', + size: 0, + point: '--' + } + ], + bootModeData: ['--'] + }); +} + +class FormRulesOperate extends DataOperate { + // 表单ref + ruleFormRef: Ref = ref(); + ruleForm: allType.RuleFormType = reactive({ + instanceName: '', + instanceId: '', + imageType: '', + bootMode: '', + systemVolumeRaidId: '', + hostName: '', + setType: 'customPassword', + password: '', + confirmPassword: '', + sshKeyId: '', + imageId: '', + systemPartition: [], + userName: '', + installBmpAgent: true + }); + proxy = new CurrentInstance().proxy; + + setData = (item: allType.ItemType, query: Pick) => { + const {instanceName, instanceId} = item; + this.ruleForm.instanceName = instanceName; + this.ruleForm.instanceId = instanceId; + this.reactiveArr.tableData.push({ + ...item, + showTooltip: false + }) + this.#getSystemRaids(); + this.#getImages(query) + }; + + + #getImages = (query: Pick) => { + queryImagesAPI( + query + ) + .then(({data}: {data: {result: {[x: string]: {systemPartition: allType.ReactiveArrType['systemPartitionData']} & allType.DropDownItemType[]}}}) => { + if (data?.result && Object.values(data.result).length) { + const val: allType.ReactiveArrType['imageTypekeyData'] = Object.keys(data.result).map((item: string, index: number) => { + return { + name: item, + initName: index === this.currIndex.value ? data.result[item][index].imageName : language.t('resetSystem.placeholder.select'), + childrenData: data.result[item], + img: this.setImg(item) + } + }); + this.reactiveArr.imageTypekeyData = val; + this.ruleForm.imageType = data.result[val[0].name][0].imageName; + this.ruleForm.imageId = data.result[val[0].name][0].imageId; + this.showRemaining.value = !(this.reactiveArr.imageTypekeyData.length > 2); + this.reactiveArr.bootModeData = data.result[val[0].name][0].bootMode.split(','); + this.ruleForm.bootMode = (this.reactiveArr.bootModeData as never)[0]; + const systemPartitionData = JSON.parse((data.result[val[0].name])[0].systemPartition as string)?? this.reactiveArr.systemPartitionData; + this.reactiveArr.systemPartitionData = this.#setSystemPartitionData(systemPartitionData); + this.ruleForm.systemPartition = systemPartitionData; + this.ruleForm.userName = this.#setUserName(data.result[val[0].name] as unknown as string); + // this.#getSystemRaids(query); + } + }) + }; + + #setSystemPartitionData = (val: SystemPartitionType[]) => { + const newData = val?.map((item: SystemPartitionType) => { + return { + ...item, + size: store.sysPartitionInfo.setSizeNoUnit(item.size) + } + }); + return newData; + }; + + setImg = (type: string) => { + const {$defInfo} = this.proxy; + const imgUrl = new Map([ + ['CentOS', $defInfo.imagePath('centos')], + ['Ubuntu', $defInfo.imagePath('ubantu')], + ['Debian', $defInfo.imagePath('debian')], + ['OpenEuler', $defInfo.imagePath('openEuler')], + ['Windows', $defInfo.imagePath('windows')] + ]); + return imgUrl.get(type)?? $defInfo.imagePath('genericVersion'); + }; + + #getSystemRaids = () => { + instanceDetailAPI( + { + instanceId: this.ruleForm.instanceId + } + ) + .then(({data}: {data: {result: {instance: CurrencyType}}}) => { + if (data?.result?.instance?.idcName?.length) { + const {systemVolumeRaidId, systemVolumeRaidName, systemInfo, systemVolumeType} = data.result.instance; + this.ruleForm.systemVolumeRaidId = systemVolumeRaidId?? ''; + this.reactiveArr.systemDiskData[0].raidName = systemVolumeRaidName?? ''; + const newVal = systemInfo.split(')')[0]; + this.reactiveArr.systemDiskData[0].volumeDetail = newVal + ' | ' + this.reactiveArr.systemDiskData[0].raidName + ')'; + this.reactiveArr.systemDiskData[0].diskType = systemVolumeType; + this.reactiveArr.systemDiskData[0].raidId = systemVolumeRaidId; + // 暂时先注释 + // this.#getKeyInfo(); + return; + } + }) + } + + // #getSystemRaids = (query: Omit) => { + // systemRaidsAPI( + // { + // deviceTypeId: query.deviceTypeId, + // volumeType: 'system' + // } + // ) + // .then(({data}: {data: {result: {raidId: string}[]}}) => { + // if (data?.result?.length) { + // this.ruleForm.systemVolumeRaidId = data.result[0].raidId; + // this.reactiveArr.systemDiskData = data.result; + // // 暂时先注释 + // // this.#getKeyInfo(); + // return; + // } + // }) + // }; + + // #getKeyInfo = () => { + // keyInfoAPI( + // { + // isAll: '1' + // } + // ) + // .then(({data}: {data: {result: {keypairs: CurrencyType[]}}}) => { + // if (data?.result?.keypairs?.length) { + // this.reactiveArr.keyPariData = data.result.keypairs; + // return; + // } + // }) + // .finally(() => this.isLoading.value = false) + // }; + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: RuleFormRefType}): void => { + this.ruleFormRef.value = formEl.value; + }; + + visibleChange: StatusParamsType <(val: boolean) => boolean> = (val: boolean): boolean => { + return this.selectStatus.value = val; + }; + + visibleClick = (item: allType.DropDwomType, index: number) => { + this.currIndex.value = index; + this.ruleForm.userName = this.#setUserName(item.name); + if (item.initName === language.t('resetSystem.placeholder.select')) { + this.#setRuleForm(item.childrenData[0]); + this.reactiveArr.imageTypekeyData.forEach((t) => { + if (t.name === item.name) { + t.initName = t.childrenData![0].imageName; + } + }); + return; + }; + const val = item.childrenData.find((ite: {imageName: string;}) => ite.imageName === item.initName); + this.#setRuleForm(val!); + }; + + #setUserName = (name: string) => { + const newUserName = new Map([ + ['Windows', 'administrator'] + ]); + return newUserName.get(name)?? 'root'; + }; + + activeClick = () => { + this.showRemaining.value = !this.showRemaining.value; + const height: allType.HeightType = document.querySelector('.custom-image') as HTMLDivElement; + if (this.showRemaining.value) { + height.style.maxHeight = height.scrollHeight + 'px'; + return; + } + height.style.maxHeight = '155px'; + }; + + systemDiskClick = (item: {raidId: string}, index: number) => { + this.ruleForm.systemVolumeRaidId = item.raidId; + this.systemCurrIndex.value = index; + }; + + radioChange = (item: string, index: number) => { + this.bootModeCurrIndex.value = index; + this.ruleForm.bootMode = item; + }; + + dropdownItemChange = (item: allType.ChildrenDataType, index: number) => { + this.reactiveArr.imageTypekeyData[index].initName = item.imageName; + this.#setRuleForm(item!); + }; + + #setRuleForm = (itemData: allType.ChildrenDataType) => { + this.ruleForm.imageId = itemData!.imageId; + this.ruleForm.imageType = itemData!.imageName; + this.reactiveArr.bootModeData = itemData!.bootMode.split(','); + this.ruleForm.bootMode = (this.reactiveArr.bootModeData as never)[0]; + const systemPartitionData = (itemData?.systemPartition && JSON.parse(itemData.systemPartition))?? [{ + format: '--', + size: 0, + point: '--' + }]; + this.ruleForm.systemPartition = systemPartitionData; + this.reactiveArr.systemPartitionData = this.#setSystemPartitionData(systemPartitionData); + }; + + setPasswordChange = () => { + this.ruleForm.password = ''; + this.ruleForm.confirmPassword = ''; + this.ruleForm.sshKeyId = ''; + this.rulesCheck.confirmPasswordFlag.value = false; + this.rulesCheck.colorStatus.value = false; + this.rulesCheck.hasKeyFlag.value = false; + this.rulesCheck.errorTip.value = language.t('resetSystem.regCheckTip.password'); + }; +}; + +export default FormRulesOperate; diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetSystem/InstanceInfo/ResetSystemInstanceInfo.vue b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/InstanceInfo/ResetSystemInstanceInfo.vue new file mode 100644 index 0000000..531b961 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/InstanceInfo/ResetSystemInstanceInfo.vue @@ -0,0 +1,138 @@ + + diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetSystem/KeyTable/ResetSystemKeyTable.vue b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/KeyTable/ResetSystemKeyTable.vue new file mode 100644 index 0000000..d3a3da1 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/KeyTable/ResetSystemKeyTable.vue @@ -0,0 +1,94 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetSystem/KeyTable/tableOperate.ts b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/KeyTable/tableOperate.ts new file mode 100644 index 0000000..682d750 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/KeyTable/tableOperate.ts @@ -0,0 +1,57 @@ +import {ChooseItemType} from '../type'; +import {CurrencyType, CurrencyType3} from '@utils/publicType'; +import {RuleFormType, RulesCheckType} from '../type'; + +const tableOperate = (ruleForm: RuleFormType, rulesCheck: RulesCheckType) => { + let tableRef: { + [x: string]: unknown; + value?: { + toggleRowSelection(arg1: CurrencyType, arg2: undefined): void; + clearFilter(): unknown; + clearSelection(): void; + } + } = { + value: { + clearFilter(): void{}, + toggleRowSelection(): void{}, + clearSelection(): void{} + } + }; + + /** + * 获取表格ref + * @param {Object} tableEl 表格信息 + */ + const getTableRef = (tableEl: CurrencyType3): void => { + tableRef = tableEl; + }; + + const cellClick = (row: CurrencyType) => { + toggleSelection([row]); + }; + + const toggleSelection = (rows?: CurrencyType[]) => { + if (rows) { + rows.forEach((row: CurrencyType) => { + tableRef.value?.toggleRowSelection(row, undefined); + }); + return; + } + tableRef.value?.clearSelection() + }; + + const handleSelectionChange = (val: ChooseItemType[]) => { + const id: string[] = val.map((item: ChooseItemType) => item.keypairId); + ruleForm.sshKeyId = id.join(','); + rulesCheck.hasKeyFlag.value = !(val.length) + }; + + return { + tableRef, + getTableRef, + cellClick, + handleSelectionChange + }; +}; + +export default tableOperate; diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetSystem/ResetSystem.vue b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/ResetSystem.vue new file mode 100644 index 0000000..4d1be86 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/ResetSystem.vue @@ -0,0 +1,69 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetSystem/SecondaryConfirmation.vue b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/SecondaryConfirmation.vue new file mode 100644 index 0000000..fff9abc --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/SecondaryConfirmation.vue @@ -0,0 +1,60 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetSystem/resetSystem.scss b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/resetSystem.scss new file mode 100644 index 0000000..e46a7b3 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/resetSystem.scss @@ -0,0 +1,496 @@ +@import 'assets/css/deviceOperate.scss'; + +.reset-system { + .el-dialog { + &--center { + --el-dialog-width: 906px; + // height: 598px; + background: $whiteBackground; + padding-bottom: 100px; + } + + &__body { + // padding: 0; + height: 508px; + // margin: auto; + overflow-y: auto; + // overflow-x: hidden; + // padding-bottom: 100px !important; + } + + &__footer { + width: 844px; + } + } + + .input-select { + width: 240px; + } + + .install-bmp-agent { + .el-checkbox__inner { + border-radius: 0; + } + + img { + margin-left: 10px; + } + } + + &-content { + // height: 290px; + + .warnning-tip { + text-align: center; + border-radius: 2px; + background: rgb(249, 237, 239); + // @extend %display-flex-start; + @include display-align(flex-start); + margin-top: 15px; + + img { + @extend %img-count; + margin-top: 2px !important; + } + + .tip-count { + font-size: $fontSize; + padding: 10px 0; + + .reset-system-tip { + text-align: left; + line-height: 24px; + padding: 0 10px 0 0; + } + } + } + + // 实例信息 + .instance-count { + .title { + font-size: $fontSize; + color: $defaultColor; + font-weight: $fontLargeWeight; + margin: 20.5px 0 16px; + } + + .el-table__inner-wrapper tr:first-child th:first-child { + border-left: 0; + } + } + + .currency-count-table { + .img-empty { + .el-table__empty-block { + background: $whiteBackground; + + .el-table__empty-text { + color: $defaultColor; + } + } + } + } + + .reset-system-information { + margin-top: 30px; + + .el-form-item--default { + margin-bottom: 30px; + } + + &-count { + width: 240px; + height: 60px; + // @extend %display-flex-align; + @include display-align(center); + border: 1px solid $border2; + border-radius: 5px; + margin-top: 8px; + @include set-cursor(pointer); + + &:hover { + border-color: $border3 !important; + } + // margin-right: 30px; + + .img { + width: 35px; + height: 35px; + margin-left: 11px; + } + + .info { + @extend %display-flex-column; + line-height: 1.3; + margin-left: 5px; + + span { + color: $defaultColor; + + &:first-child { + font-size: $fontSize2; + } + + &:last-child { + font-size: $fontSize; + } + } + } + + .custom-icon { + position: absolute; + right: 13px; + bottom: 16px; + @include set-cursor(pointer); + transition: all .3s; + } + + .rotate180 { + transform: rotate(180deg); + } + + .rotate0 { + transform: rotate(0deg); + } + } + + + .custom-yes-icon { + position: absolute; + right: 0; + bottom: 0; + } + + .triangle { + width: 0; + right: 0; + bottom: 0; + height: 0; + border-bottom: 15px solid $border3; + border-top: 15px solid transparent; + border-left: 15px solid transparent; + position: absolute; + border-bottom-right-radius: 4px !important; + } + + .rule-form { + + label { + font-weight: $fontLargeWeight; + @include break-wrap(break-all); + + &::before { + display: none; + } + } + + .custom-image { + overflow: hidden; + max-height: 155px; + transition: max-height .3s; + + .el-form-item__content { + .el-dropdown { + margin-right: 30px; + margin-bottom: 8px; + } + } + + // 展开收起按钮 + .active-bottom { + width: 29px; + height: 29px; + border-radius: 50%; + border: 1px solid $border7; + position: absolute; + right: 86px; + // @extend %display-flex-align; + @include display-align(center); + top: 0; + margin-top: 100px; + @extend %justify-center; + + &:hover { + border-color: $border3; + background-color: $background1; + @include set-cursor(pointer); + + .el-icon { + color: #fff; + } + } + } + + // 下拉展开收起 + .icon-rotate180, + .icon-rotate0 { + transition: transform .3s; + } + + .icon-rotate180 { + transform: rotate(180deg); + } + + .icon-rotate0 { + transform: rotate(0); + } + } + + // 系统盘 + .custom-system-disk { + position: relative; + z-index: 10; + background: $whiteBackground; + + .system-disk { + // width: 150px; + min-width: 110px; + position: relative; + z-index: 10; + height: 78px; + margin-right: 30px; + @include set-cursor(pointer); + margin-bottom: 16px; + + &:hover { + .system-disk-header { + color: $color12; + border-color: $border4 !important; + background-color: $whiteBackground; + } + + .system-disk-count { + border-color: $border4 !important; + } + } + + .volume-detail { + padding: 0 5px; + } + + &-header { + border: 1px solid $border2; + border-radius: 5px 5px 0 0; + font-size: $fontSize; + color: $defaultColor; + text-align: center; + font-weight: $fontLargeWeight; + height: 23px; + // @extend %display-flex-align; + @include display-align(center); + @extend %justify-center; + } + + &-count { + border: 1px solid $border2; + border-top: 0; + padding-top: 5px; + height: 47px; + font-size: $fontSize; + color: $defaultColor; + text-align: center; + font-weight: $fontSmallWeight; + border-radius: 0 0 5px 5px; + + p { + line-height: 1.7; + } + } + } + } + + .custom-label { + label { + line-height: 1.5; + } + } + + // 系统盘分区 + .system-partition { + // min-width: 68px; + min-width: 71px; + height: 84px; + border: 1px solid $border2; + border-radius: 5px; + position: relative; + margin-right: 30px; + margin-bottom: 16px; + + &-header { + font-size: $fontSize; + font-weight: $fontLargeWeight; + margin-left: 8px; + } + + &-line { + height: 1px; + background: $background16; + position: absolute; + top: 32px; + width: calc(100% - 16px); + left: 50%; + transform: translateX(-50%); + } + + &-num, + &-unit { + font-size: $fontSize; + text-align: center; + line-height: 1; + } + + &-num { + margin-top: 13px; + padding: 0 10px; + margin-bottom: 5px; + } + + %w-h-p-triangle { + width: 0; + height: 0; + position: absolute; + } + + &-triangle { + @extend %w-h-p-triangle; + right: 0; + top: 0; + border-top: 30px solid $border2; + border-bottom: 30px solid $transparent; + border-left: 30px solid $transparent; + + } + + &-triangle2 { + @extend %w-h-p-triangle; + right: -1.5px; + top: -1px; + border-top: 31.5px solid $border8; + border-bottom: 31.5px solid $transparent; + border-left: 31.5px solid $transparent; + } + } + + // 引导模式 + .boot-mode { + // margin-bottom: 20px; + .custom-radio-btn { + border: 0.62px solid $border2; + &:hover { + // color: #fff; + border-color: $border3; + color: $color1; + // background: #108ee9; + } + } + + .custom-radio-btn-active { + border: 0.62px solid $border3; + background: $background1; + color: $color3; + } + + .custom-radio-btn, + .custom-radio-btn-active { + @include set-cursor(pointer); + width: 99px; + height: 30px; + border-radius: 4px; + margin-right: 21px; + font-size: $fontSize; + // @extend %display-flex-align; + @include display-align(center); + @extend %justify-center ; + } + } + + // 间隔 + .set-empty { + margin-bottom: 45px; + } + + // 自定义input宽高度 + .custom-ipt { + width: 340px; + height: 30px; + } + + // 表单校验异常 + .el-form-item__error { + line-height: 1.5; + padding-top: 6px; + @include break-wrap(break-all); + } + + // 设置密码-radio切换 + .set-password { + .el-radio__label { + color: $color6; + } + } + + // 自定义密码 + .custom-password { + .el-form-item__content { + @extend %display-flex-column; + // @extend %display-flex-start; + @include display-align(flex-start); + } + } + + // 自定义表单error文案颜色 + .error-color-tip { + color: $color13; + } + + // 常态表单error文案颜色 + .password-tip { + color: $color7; + } + + // 表单error文案、自定义表单error文案公共样式 + .error-color-tip, + .password-tip { + font-size: $fontSize; + font-weight: $fontSmallWeight; + // @extend %display-flex-align; + @include display-align(center); + margin-top: 12px; + @include break-wrap(break-all); + line-height: 1.5; + } + } + } + } +} + +// drop-down-下拉item +.custom-card-select { + .el-dropdown-menu__item { + width: 240px; + height: 36px; + // @extend %display-flex-align; + @include display-align(center); + font-size: $fontSize; + @extend %justify-center; + + &:focus { + background: $background3 !important; + color: $color1; + } + } + + .drop-down-item-active, + .custom-drop-down-item { + width: $percentageWidth; + height: $percentageHeight; + // @extend %display-flex-align; + @include display-align(center); + @extend %justify-center; + } + + .drop-down-item-active { + background: $background3; + color: $color1; + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetSystem/secondaryConfirmation.scss b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/secondaryConfirmation.scss new file mode 100644 index 0000000..0e62b16 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/secondaryConfirmation.scss @@ -0,0 +1,70 @@ +@import '@/assets/css/deviceOperate'; + +.secondary-confirmation { + .el-dialog { + &--center { + --el-dialog-width: 716px; + // height: 402px; + padding-bottom: 60px; + } + + &__body { + padding: 0; + } + + &__footer { + width: 671px; + } + } + + &-content { + // height: 290px; + + .warnning-tip { + @extend %warnning-tip; + // min-width: 380px; + // height: 52px; + // text-align: center; + // border-radius: 2px; + // background: rgb(249, 237, 239); + // display: flex; + // align-items: flex-start; + // justify-content: center; + // margin-top: 15px; + // // margin-bottom: 44.5px; + // // padding-bottom: 10px; + + // img { + // width: 32px; + // height: 32px; + // transform: scale(.5); + // margin-left: 10px; + // margin-top: 2px; + // } + + .tip-count { + font-size: 12px; + padding: 10px 0; + + .reset-system-tip { + text-align: left; + line-height: 24px; + padding: 0 10px 0 0; + } + } + } + + .tip-title { + padding: 0 25px; + font-size: $fontSize2; + color: $defaultColor; + margin: 15px 0; + // @extend %display-flex-align; + @include display-align(center); + @extend %justify-center; + // justify-content: center; + text-align: center; + height: 160px; + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetSystem/type.ts b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/type.ts new file mode 100644 index 0000000..1d0bbd0 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/type.ts @@ -0,0 +1,110 @@ +import {CurrencyType, SystemPartitionType, VerifyRulesType} from '@utils/publicType'; +interface ItemType { + instanceName: string; + instanceId: string; + showTooltip: boolean; +}; + + +interface DropDownItemType { + systemPartition: SystemPartitionType[] | string; + imageName: string; + imageId: string; + bootMode: { + split: (arg0: string) => CurrencyType[]; + }; +}; + +interface QueryType { + deviceTypeId: string; + idcId?: string; + volumeType?: string; + imageId?: string; +}; + +interface ReactiveArrType { + tableData: ItemType[] | {push(arg0: ItemType): void}; + centOSData: CurrencyType[]; + imageTypekeyData: { + name: string; + initName: string; + img?: string; + childrenData?: { imageName: string; }[] + }[]; + systemDiskData: CurrencyType[]; + keyPariData: CurrencyType[]; + systemPartitionData: SystemPartitionType[]; + bootModeData: string | string[] | DropDownItemType['bootMode'] | CurrencyType[]; +}; + +type key = 'instanceName' | 'instanceId' | 'imageType' | 'bootMode' | 'systemVolumeRaidId' | 'hostName' | 'setType' | 'password' | 'confirmPassword' | 'sshKeyId' | 'imageId' | 'userName'; + + +type RuleFormType = { + [k in key]: string; +} & { + systemPartition: SystemPartitionType[]; +} & {installBmpAgent: boolean;}; + +interface RuleType { + hostName: VerifyRulesType[]; + password: VerifyRulesType[]; + confirmPassword: VerifyRulesType[]; +}; + +interface RulesCheckType { + confirmPasswordFlag: {value: boolean}; + colorStatus: {value: boolean}; + hasKeyFlag: {value: boolean}; + errorTip: {value: string}; + hostNameCheck: unknown; + passwordCheck: unknown; + confirmPasswordCheck: unknown; +}; + +interface ChildrenDataType { + [x: string]: string; + imageId:string; + imageName: string; +}; + +type DropDwomType = { + initName: string; + childrenData: ChildrenDataType[]; + name: string; + imageName: string; + bootMode: { + split: (arg0: string) => CurrencyType[]; + }; +}; + +type FormRulesOptType = { + ruleFormRef: { + value: { + validate(arg0: (valid: boolean) => void): void + }; + }; + ruleForm: { + setType: string; + sshKeyId: string; + }; +}; + +type HeightType = {style: {maxHeight: string;}; scrollHeight: number;}; + +interface ChooseItemType {keypairId: string;}; + +export { + RuleType, + ItemType, + QueryType, + HeightType, + RuleFormType, + DropDwomType, + ChooseItemType, + RulesCheckType, + ReactiveArrType, + ChildrenDataType, + FormRulesOptType, + DropDownItemType +} diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetSystem/utils/propsOperate.ts b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/utils/propsOperate.ts new file mode 100644 index 0000000..b7641bf --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/utils/propsOperate.ts @@ -0,0 +1,26 @@ + +import {CurrentInstance} from 'utils/publicClass.ts'; +import {QueryType} from '../type'; + +const propsOperate = (fn: Function) => { + const instanceMitt = new CurrentInstance(); + const query: Pick = { + idcId: '', + deviceTypeId: '', + }; + + const getTableFn = (item: QueryType) => { + query.deviceTypeId = item.deviceTypeId; + query.idcId = item.idcId; + fn(item, query); + }; + + // 监听mitt-device-table,获取表格数据 + instanceMitt?.proxy?.$Bus?.on('reset-system', getTableFn); + + onUnmounted(() => { + instanceMitt?.proxy?.$Bus?.off('reset-system', getTableFn); + }) +} + +export default propsOperate; diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetSystem/utils/resetSystem.ts b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/utils/resetSystem.ts new file mode 100644 index 0000000..34adfa5 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/utils/resetSystem.ts @@ -0,0 +1,60 @@ +import {msgTip} from 'utils/index.ts'; +import {language} from 'utils/publicClass.ts'; +import {resetSystemAPI} from 'api/device/request.ts'; +import {SuccessType} from '@utils/publicType'; +import {FormRulesOptType, RulesCheckType} from '../type'; + +const resetSystemOpt = (formRulesOpt: FormRulesOptType, rulesCheck: RulesCheckType, emitValue: Function) => { + const isLoading: Ref = ref(false); + + /** + * 确定按钮弹窗 + */ + const sureClick = async () => { + await nextTick(() => { + formRulesOpt.ruleFormRef.value!.validate((valid: boolean) => { + // 输入符合条件后才可以继续后续操作 + if (valid) { + rulesCheck.hasKeyFlag.value = (formRulesOpt.ruleForm.setType === 'sshKey' && !formRulesOpt.ruleForm.sshKeyId); + if (rulesCheck.hasKeyFlag.value) return; + isLoading.value = true; + requestResetSystem(); + } + }); + }); + }; + + const requestResetSystem = () => { + resetSystemAPI( + { + ...formRulesOpt.ruleForm + } + ) + .then(({data}: {data: SuccessType}) => { + if (data?.result?.success) { + msgTip.success(language.t('operate.success')); + } + }) + .finally(() => { + isLoading.value = false; + cancelClick(); + emitValue('determine-click'); + }) + }; + + /** + * 取消按钮点击操作 + */ + const cancelClick = (): void => { + // 回传父组件当前页码,可以处理相关操作 + emitValue('dia-log-close', false); + }; + + return { + isLoading, + sureClick, + cancelClick + } +}; + +export default resetSystemOpt; diff --git a/bmp-operation-web/src/components/DeviceOperations/ResetSystem/utils/rulesCheck.ts b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/utils/rulesCheck.ts new file mode 100644 index 0000000..b6acf1a --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/ResetSystem/utils/rulesCheck.ts @@ -0,0 +1,95 @@ +import {CurrencyType3} from '@utils/publicType'; +import RegularContent from 'utils/regular.ts'; +import {language} from 'utils/publicClass.ts'; + +class RulesCheck { + hostNameFlag: Ref = ref(false); + confirmPasswordFlag: Ref = ref(false); + errorTip: Ref = ref(language.t('resetSystem.regCheckTip.password')); + colorStatus: Ref = ref(false); + newPassword: Ref = ref(''); + hasKeyFlag: Ref = ref(false); + + hostNameCheck = (_: CurrencyType3, value: string, callback: (arg0?: Error | string) => void) => { + this.hostNameFlag.value = true; + if (!value?.length) { + this.hostNameFlag.value = false; + callback(); + } + else if (!RegularContent.hostNameReg.test(value)) { + callback(new Error(language.t('resetSystem.regCheckTip.hostName'))); + } + else { + this.hostNameFlag.value = false; + callback(); + } + }; + + passwordCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + this.newPassword.value = value; + this.colorStatus.value = true; + const newPasswordArr = [ + [ + (value: string) => !value?.length, + () => { + this.errorTip.value = language.t('resetSystem.emptyCheck.password'); + callback(new Error()); + } + ], + [ + (value: string) => (!RegularContent.passwordReg.test(value)), + () => { + this.errorTip.value = language.t('resetSystem.regCheckTip.password'); + callback(new Error()); + } + ], + [ + (value: string) => value, + () => { + this.errorTip.value = language.t('resetSystem.regCheckTip.password'); + this.colorStatus.value = false; + callback(); + } + ] + ]; + for (const key of newPasswordArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + confirmPasswordCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + this.confirmPasswordFlag.value = true; + const confirmPasswordArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t('resetSystem.emptyCheck.confirmPassword'))) + ], + [ + (value: string) => (!RegularContent.passwordReg.test(value)), + () => callback(new Error(language.t('resetSystem.regCheckTip.password'))) + ], + [ + (value: string) => (value !== this.newPassword.value), + () => callback(new Error(language.t('resetSystem.regCheckTip.password2'))) + ], + [ + (value: string) => value, + () => { + this.confirmPasswordFlag.value = false; + callback(); + } + ] + ]; + for (const key of confirmPasswordArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; +}; + +export default RulesCheck; diff --git a/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/UpDownFrame.vue b/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/UpDownFrame.vue new file mode 100644 index 0000000..3c734e5 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/UpDownFrame.vue @@ -0,0 +1,311 @@ + + + + diff --git a/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/table/UpDownFrameTable.vue b/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/table/UpDownFrameTable.vue new file mode 100644 index 0000000..85f20eb --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/table/UpDownFrameTable.vue @@ -0,0 +1,100 @@ + + diff --git a/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/upDownFrame.scss b/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/upDownFrame.scss new file mode 100644 index 0000000..aedf0b3 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/upDownFrame.scss @@ -0,0 +1,266 @@ +.default-dia-log { + .el-dialog { + &--center { + // --el-dialog-width: 1046px; + // height: 566px; + --el-dialog-width: 646px; + height: 366px; + } + + + &__footer { + // width: 1001px; + width: 601px; + } + } +} + +%step-icon { + color: $color3; + font-size: $fontSize; + font-weight: $fontSmallWeight; + border: 0; +} + +%step-title { + color: $color6; + font-size: $fontSize; +} + +@mixin setSmallWeight { + font-weight: $fontSmallWeight; +} + +@mixin setLargeWeight { + font-weight: $fontLargeWeight; +} + +.set-dia-log { + + .el-dialog { + &--center { + --el-dialog-width: 646px; + // --el-dialog-width: 1046px; + // height: 566px; + height: 366px; + // background: #fff; + } + + + &__footer { + // width: 1001px; + width: 601px; + } + } +} + +.up-down-frame { + + .el-loading-mask { + top: 42px; + } + + .add-new-model { + font-size: $fontSize; + color: $color1; + cursor: pointer; + margin-left: 10px; + } + + .el-steps--horizontal { + margin: 20px; + transform: scale(.9); + } + + .set-empty { + margin-bottom: 30px; + + .el-form-item__error { + padding-top: 8px; + } + } + + .first-step2 { + .el-step__title.is-finish { + @extend %step-title; + @include setLargeWeight; + } + + .el-step__icon.is-text { + background: $background1; + color: $whiteBackground; + border: 0; + } + } + + .last-step2 { + .el-step__icon.is-text { + background: $background9; + @extend %step-icon; + } + + .el-step__title.is-process { + @include setSmallWeight; + @extend %step-title; + } + } + + .el-step__icon.is-text { + width: 29px; + height: 29px; + } + + .last-step1 { + .el-step__icon.is-text { + background: $background1; + @extend %step-icon; + } + + .el-step__title.is-success { + @include setLargeWeight; + @extend %step-title; + } + } + + .first-step1 { + + .el-step__title.is-success { + @include setSmallWeight; + @extend %step-title; + } + + .el-step__icon.is-text { + background: $background14; + border: 1px solid $border3; + + .el-icon { + color: $color1; + transform: scale(1.2); + } + } + } + + .el-step__line { + left: 60% !important; + height: 1px; + right: 0; + width: 80%; + + &-inner { + display: none; + } + } + + .el-dialog { + + .el-table__row { + background: $background12; + } + + .def-select, + .multiple-choice { + margin: 10px; + + input { + width: 360px !important; + } + } + + .error-tip { + input { + border-color: $border9; + + &::placeholder { + color: $color13; + } + } + } + + .def-tip { + input { + border-color: $border15; + + &::placeholder { + color: $color15; + } + } + } + + &__body { + padding: 0; + + .el-table__body { + padding-bottom: 0 !important; + + .el-table-fixed-column--right, + .el-table-fixed-column--left { + background-color: $background15; + } + } + + .currency-count { + @extend %display-flex-column; + + .header-title { + font-size: $fontSize; + font-weight: $fontLargeWeight; + color: $defaultColor; + margin: 19.5px 0 20px; + } + + &-title { + width: 580px; + padding-right: 20px; + min-height: 34px; + text-align: center; + border-radius: 2px; + background: $background13; + color: $defaultColor; + font-size: $fontSize; + font-weight: $fontSmallWeight; + line-height: 34px; + margin: 19.5px 0 .5px; + + img { + width: 32px; + height: 32px; + transform: scale(.5); + margin-right: -2px + } + } + } + + // table为空 + .currency-count-table { + + .el-table__header-wrapper { + margin-bottom: 5px; + } + .el-table__inner-wrapper tr:first-child th { + &:first-child { + border-left: none; + } + + &:last-child { + border-color: $border16; + } + } + + .el-table__body-wrapper { + max-height: 240px; + overflow-y: auto; + } + + .el-table__row { + background-color: $background3; + + &:hover { + td { + background-color: $background10 !important; + } + } + } + } + } + } +} diff --git a/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/utils/setInfo.ts b/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/utils/setInfo.ts new file mode 100644 index 0000000..ecd2504 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/utils/setInfo.ts @@ -0,0 +1,41 @@ +import {language} from 'utils/publicClass.ts'; + +class SetInfo { + + titleComputed = (title: string) => { + const titleData: {[x: string]: string} = { + 'up': language.t('upDownFrame.titleTip.up'), + 'down': language.t('upDownFrame.titleTip.down'), + 'delete': language.t('upDownFrame.titleTip.delete') + }; + return titleData[title]; + }; + + /** + * 主体内容 + * @return {string} xxx 对应的主体内容 + */ + countTitle = (title: string) => { + const countTitle: {[x: string]: string | null} = { + 'up': null, + 'down': language.t('upDownFrame.countTitleTip.down'), + 'delete': language.t('upDownFrame.countTitleTip.delete') + }; + return countTitle[title]; + }; + + /** + * header头部标题 + * @return {string} xxx 对应标题的内容 + */ + headerTitle = (title: string) => { + const headerTitle: {[x: string]: string} = { + 'up': language.t('upDownFrame.headerTitleTip.up'), + 'down': language.t('upDownFrame.headerTitleTip.down'), + 'delete': language.t('upDownFrame.headerTitleTip.delete') + }; + return headerTitle[title]; + }; +}; + +export default SetInfo; diff --git a/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/utils/type.ts b/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/utils/type.ts new file mode 100644 index 0000000..3cbb9bd --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/utils/type.ts @@ -0,0 +1,24 @@ +interface TableDataType { + sn: string; + cabinet: string; + uPosition: string; + deviceTypeId: string; + iloIp: string; + privateIpv4: string; +}; + +type ParamsType = { + deviceId: string; + sns?: string; +}; + +interface PropsType { + deviceId: string; + title: string; +} + +export { + TableDataType, + ParamsType, + PropsType +}; diff --git a/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/utils/upDownDeleteOpt.ts b/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/utils/upDownDeleteOpt.ts new file mode 100644 index 0000000..3e8c2d3 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/utils/upDownDeleteOpt.ts @@ -0,0 +1,212 @@ +import {msgTip} from 'utils/index.ts'; +import {SuccessType} from '@utils/publicType'; +import {PropsType, ParamsType, TableDataType} from './type'; +import {language, CurrentInstance} from 'utils/publicClass.ts'; +import {devicesUpAPI, devicesDownAPI, devicesDeleteAPI, associateDisksAPI, associateAPI} from 'api/device/request.ts'; +import {AxiosError} from 'axios'; + +let s: HTMLElement | null; + +class UpDownDel { + nextLoading: Ref = ref(false); + errorFlag: Ref = ref(false); + instanceMitt = new CurrentInstance().instanceMitt; + // loading加载态 + isLoading: Ref = ref(false); + // 表格数据 + upDownFrameTable: TableDataType[] = reactive([]); + props: PropsType = {title: '', deviceId: ''}; + emitValue: any; + active: Ref = ref(1); + setUpTitle: Ref = ref(language.t('upDownFrame.btn.next')); + setTitle: Ref = ref(language.t('upDownFrame.btn.cancel')); + upFormOpt; + + constructor(props: PropsType, emitValue: any, upFormOpt: any) { + this.props = props; + this.emitValue = emitValue; + this.upFormOpt = upFormOpt; + // 监听mitt-device-table,获取表格数据 + this.instanceMitt?.proxy?.$Bus?.on('device-table', this.getTableFn); + watch((this.active), (newValue) => { + s = document.querySelector('.up-down-frame .default-step .el-step__icon.is-text') + if (newValue > 1) { + nextTick(() => s!.innerHTML = '2'); + return; + } + s!.innerHTML = ''; + }) + }; + + preClick = () => { + if (this.setTitle.value === language.t('upDownFrame.btn.cancel')) { + this.cancelClick(); + } + else { + this.active.value = 1; + this.setUpTitle.value = language.t('upDownFrame.btn.next'); + this.setTitle.value = language.t('upDownFrame.btn.sure'); + } + } + + nextClick = () => { + if (this.active.value === 1) { + this.errorFlag.value = true; + this.upFormOpt.formRef.value.validate((valid: boolean) => { + if (valid) { + this.associateDisks(); + + } + }) + } + else { + // 调用 + this.determineClick() + } + } + + associateDisks = async () => { + const status = this.upFormOpt.reactiveArr.tableData.some((item: {disks: string[]}) => !item.disks.length); + if (status) { + for (const key of this.upFormOpt.reactiveArr.tableData) { + key.disksDataFlag = !key.disks.length ? true : false; + } + return; + } + this.nextLoading.value = true; + const valData = this.upFormOpt.reactiveArr.tableData.map((item: {volumeId: string; disks: string[]}) => { + return { + volumeId: item.volumeId, + diskId: typeof item.disks === 'string' ? [item.disks] : item.disks + } + }); + try { + const res = await associateDisksAPI({ + deviceTypeId: this.upFormOpt.deviceTypeId.value, + deviceId: this.props.deviceId, + volumes: valData + }); + if (res?.data?.result?.success) { + this.associate(); + return; + } + this.nextLoading.value = false; + } + catch (e) { + this.nextLoading.value = false; + const err = e as AxiosError; + err.message && msgTip.error(err.message); + } + // const newReq = this.upFormOpt.reactiveArr.tableData.map((item: {volumeId: string; disks: string[]}) => { + // return associateDisksAPI({ + // deviceTypeId: this.upFormOpt.deviceTypeId.value, + // deviceId: this.props.deviceId, + // volumes: [ + // { + // volumeId: item.volumeId, + // diskId: item.disks + // } + // ] + // }) + // }); + // Promise.all([newReq]) + // .then((res) => { + // if (res?.length) { + // this.associate(); + // } + // }) + // .catch(() => { + // this.nextLoading.value = false; + // }) + } + + associate = () => { + associateAPI({ + deviceTypeId: this.upFormOpt.deviceTypeId.value, + deviceId: this.props.deviceId + }) + .then(({data}: any) => { + if (data?.result?.success) { + this.active.value = 2; + this.setUpTitle.value = language.t('upDownFrame.btn.sure'); + this.setTitle.value = language.t('upDownFrame.btn.pre'); + this.errorFlag.value = false; + } + }) + .finally(() => { + this.nextLoading.value = false; + }) + } + + /** + * 确定按钮弹窗 + */ + determineClick: () => Promise = async () => { + this.isLoading.value = true; + await this.requestUpDownFrame(); + }; + + /** + * 请求上架下架删除接口,成功后把事件回传,关闭弹窗 + */ + requestUpDownFrame = () => { + const requestUrl = new Map([ + ['up', devicesUpAPI], + ['down', devicesDownAPI], + ['delete', devicesDeleteAPI] + ]); + return this.#getDevicesOperate(requestUrl.get(this.props.title), this.props.title)!; + }; + + /** + * 设备操作-上架、下架、删除 + * @param {Function} requestUrl url请求地址 + * @param {string} type 设备操作状态-上架、下架、删除 + */ + #getDevicesOperate = (requestUrl: (arg0: ParamsType) => Promise<{data: SuccessType}>, type: string) => { + const params: ParamsType = this.#setParams(type); + requestUrl( + { + ...params + } + ) + .then(({data}: {data: SuccessType}) => { + if (data?.result?.success) { + msgTip.success(language.t('operate.success')); + } + }) + .finally(() => { + this.isLoading.value = false; + this.cancelClick(); + this.emitValue('determine-click', type); + }) + }; + + #setParams = (type: string) => { + const param = {deviceId: this.props.deviceId}; + const newParams = new Map([ + ['delete', param] + ]); + return newParams.get(type)?? {...param, sns: this.upDownFrameTable.map((item) => item.sn).join(',')}; + }; + + /** + * 取消按钮点击操作 + */ + cancelClick = (): void => { + // 回传父组件当前页码,可以处理相关操作 + this.emitValue('dia-log-close', false); + // 取消device-table mitt事件,第一个参数-事件名,第二个参数,需要取消的函数 + this.instanceMitt.proxy.$Bus.off('device-table', this.getTableFn); + }; + + /** + * 获取表格数据函数 + * @param {Object} list 表格数据 + */ + getTableFn: unknown = ({list}: {list: TableDataType}) => { + this.upDownFrameTable.push(list); + }; +}; + +export default UpDownDel; diff --git a/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/utils/upForm.ts b/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/utils/upForm.ts new file mode 100644 index 0000000..2df9141 --- /dev/null +++ b/bmp-operation-web/src/components/DeviceOperations/UpDownFrame/utils/upForm.ts @@ -0,0 +1,192 @@ +/** + * @file + * @author +*/ + +// uiLocale, locationItem, +import {CurrentInstance, language} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; +import {RuleFormRefType} from '@utils/publicType'; +// import {ElForm} from 'element-plus'; +import {msgTip, deepCopy} from 'utils/index.ts'; +import {describeVolumesAPI, describeAssociateDisksAPI} from 'api/device/request.ts'; +import {modelDetailAPI} from 'api/model/request.ts'; +import {AxiosError} from 'axios'; + +class UpFormOpt { + isTableLoading: Ref = ref(false); + instanceProxy = new CurrentInstance().proxy; + ruleForm = reactive({ + modelName: '' + }) + arrayCard: Ref = ref(''); + formRef: Ref = ref() + reactiveArr: { + modelData: {text: string; filterParams: string; value: number;}[]; + tableData: any + disksData: {name: string; size: string; sizeUnit: string; diskId: string; select: boolean;}[][]; + uniquenessData: string[][]; + } = reactive<{ + modelData: {text: string; filterParams: string; value: number;}[]; + tableData: any + disksData: {name: string; size: string; sizeUnit: string; diskId: string; select: boolean;}[][]; + uniquenessData: string[][]; + }>({ + modelData: store.ossDataInfo().deviceTypeId, + tableData: [], + disksData: [], + uniquenessData: [] + }); + rules = reactive({ + modelName: [ + { + required: true, + trigger: 'change', + message: '请选择机型' + } + ], + }); + deviceId: Ref = ref(''); + deviceTypeId: Ref = ref(''); + + constructor(props: {deviceId: string}) { + this.deviceId.value = props.deviceId; + } + + modelChange = (val: string) => { + this.isTableLoading.value = true; + this.deviceTypeId.value = val; + this.getModelDetail(val); + }; + + getModelDetail = async (val: string) => { + try { + const res = await modelDetailAPI({ + id: val + }); + if (res?.data?.result && Object.keys(res.data.result)?.length) { + this.arrayCard.value = res.data.result.isNeedRaid; + this.getDescribeVolumes(val); + } + } + catch(e) { + const err = e as AxiosError; + msgTip.error(err.message); + } + } + + getDescribeVolumes = (val: string) => { + describeVolumesAPI({ + deviceTypeId: val + }) + .then(({data}: any) => { + if (data?.result?.length) { + this.reactiveArr.tableData = data.result.map((item: {disksDataFlag: boolean}) => { + return { + ...item, + disksDataFlag: false + } + }); + const ids = this.reactiveArr.tableData.map((item: {volumeId: string}) => item.volumeId); + this.describeAssociateDisks(ids, val); + return; + } + this.reactiveArr.tableData = []; + }) + .finally(() => { + this.isTableLoading.value = false; + }) + } + + setRaid = (arr: any) => { + return arr?.map((item: {name: string}) => item.name).join(',') + } + + describeAssociateDisks = (ids: string[], val: string) => { + const newReq = ids.map((item: string) => { + return describeAssociateDisksAPI({ + deviceId: this.deviceId.value, + volumeId: item, + deviceTypeId: val + }) + }); + Promise.all(newReq).then((res: any[]) => { + this.reactiveArr.uniquenessData = []; + if (res?.length) { + const data = res.map((t: any) => t.data).map((g: any) => g.result); + this.reactiveArr.disksData = data; + for (let i = 1; i <= this.reactiveArr.disksData.length; i++) { + this.reactiveArr.uniquenessData.push([]); + } + } + }) + .catch(() => { + this.reactiveArr.disksData = []; + }) + } + + setDiskLabel = (item: {name: string; size: string; sizeUnit: string;}) => { + return `${item.name}: ${item.size}${item.sizeUnit}`; + } + + setRaidCan = (item: string) => { + return item === 'RAID0-stripping' ? language.t('modelForm.raid') : item; + } + + jumpPage = () => { + const path: string = this.instanceProxy!.$defInfo.routerPath('modelList') as unknown as string; + window.open(path, '_blank') + } + + getFormRef = (forEl: {value: RuleFormRefType}) => { + this.formRef.value = forEl.value; + } + + setDiskInterfaceType = (item: string) => { + return item === 'notLimited' ? language.t('modelForm.unrestricted') : item; + } + + // disksDataChange = (item: {disks: string[]; disksDataFlag: boolean}) => { + // item.disksDataFlag = item.disks.length ? false : true; + // } + + disksDataChange = (item: {newDisks: string; raidCan: string; disks: string[]; disksDataFlag: boolean; select: boolean}, index: number) => { + item.disksDataFlag = item.disks.length ? false : true; + this.reactiveArr.uniquenessData[index] = []; + if (['RAID0-stripping', 'NO RAID'].includes(item.raidCan)) { + item.newDisks = deepCopy([item.disks]); + this.reactiveArr.uniquenessData[index] = [...this.reactiveArr.uniquenessData[index], ...item.newDisks]; + } + else { + this.reactiveArr.uniquenessData[index] = [...this.reactiveArr.uniquenessData[index], ...item.disks]; + } + for (let i = this.reactiveArr.disksData.length; i >= 0; i--) { + if (this.reactiveArr.disksData[i] !== void 0) { + this.reactiveArr.disksData[i].forEach((t) => { + i --; + if (this.reactiveArr?.uniquenessData[i]?.includes(t.diskId)) { + t.select = true; + } + else { + t.select = false; + } + i ++; + }) + } + } + + for (let i = 0; i < this.reactiveArr.disksData.length; i++) { + if (this.reactiveArr.disksData[i] !== void 0) { + this.reactiveArr.disksData[i].forEach((t) => { + i ++; + if (this.reactiveArr?.uniquenessData[i]?.includes(t.diskId)) { + t.select = true; + } + i --; + }) + } + } + } +} + +export default UpFormOpt; diff --git a/bmp-operation-web/src/components/IdcOperates/EditIdc/EditIdc.vue b/bmp-operation-web/src/components/IdcOperates/EditIdc/EditIdc.vue new file mode 100644 index 0000000..debcc90 --- /dev/null +++ b/bmp-operation-web/src/components/IdcOperates/EditIdc/EditIdc.vue @@ -0,0 +1,62 @@ + + + + diff --git a/bmp-operation-web/src/components/IdcOperates/EditIdc/editIdc.scss b/bmp-operation-web/src/components/IdcOperates/EditIdc/editIdc.scss new file mode 100644 index 0000000..3b6cb48 --- /dev/null +++ b/bmp-operation-web/src/components/IdcOperates/EditIdc/editIdc.scss @@ -0,0 +1,100 @@ +.edit-idc { + .el-dialog { + &--center { + --el-dialog-width: 696px; + height: 491px; + } + + &__body { + height: 358px; + overflow-y: auto; + overflow-x: hidden; + } + + &__footer { + width: 651px; + } + } + + &-rule-form { + margin-top: 20px; + + .set-empty { + margin-bottom: 32px !important; + + .el-form-item__error { + margin-top: 6px !important; + } + } + + .set-en { + .el-form-item__label { + margin-right: 10px; + } + } + + .el-form-item--default { + margin-bottom: 20px; + @include display-align(center); + + .el-form-item__label { + position: relative; + @include display-align(flex-start); + font-weight: $fontLargeWeight; + line-height: 1.5; + @include break-wrap(break-all); + } + + .el-form-item__error { + margin-top: 1px; + } + } + + .set-public-style, + .set-address { + .el-form-item__label { + margin-left: 10px; + } + } + + .set-address, + &-address { + + .el-textarea__inner { + padding: 5px 10px; + } + + textarea { + min-height: 78px; + font-size: $fontSize; + @extend %resize-none; + + &::placeholder { + font-size: $fontSize; + } + } + } + + &-address { + .el-form-item__label { + width: 105px !important; + margin-top: -32px; + margin-left: 10px; + } + } + + .set-width { + .el-form-item__label { + width: 105px !important; + margin-left: 10px; + } + } + + .el-textarea, + input { + width: 460px; + border-radius: 4px; + outline: 0; + } + } +} diff --git a/bmp-operation-web/src/components/IdcOperates/EditIdc/formSubmit/EditIdcForm.vue b/bmp-operation-web/src/components/IdcOperates/EditIdc/formSubmit/EditIdcForm.vue new file mode 100644 index 0000000..3cb8685 --- /dev/null +++ b/bmp-operation-web/src/components/IdcOperates/EditIdc/formSubmit/EditIdcForm.vue @@ -0,0 +1,199 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/IdcOperates/EditIdc/typeManagement.ts b/bmp-operation-web/src/components/IdcOperates/EditIdc/typeManagement.ts new file mode 100644 index 0000000..78ca6f1 --- /dev/null +++ b/bmp-operation-web/src/components/IdcOperates/EditIdc/typeManagement.ts @@ -0,0 +1,44 @@ +import {RuleFormRefType, VerifyRulesType} from '@utils/publicType'; + +/** + * 表单-输入项ts类型 +*/ +interface FormType { + value: string; + idcId: string; + name: string; + shortname: string; + nameEn: string; + level?: string; + customGrade?: string; + address: string; + iloUser: string; + iloPassword: string; + switchUser1: string; + switchPassword1: string; + switchUser2: string; + switchPassword2: string; +}; + +/** + * 表单-规则ts类型 +*/ +interface RulesType { + name: VerifyRulesType[]; + nameEn: VerifyRulesType[]; + level: VerifyRulesType[]; + customGrade: VerifyRulesType[]; + address: VerifyRulesType[]; + iloUser: VerifyRulesType[]; + iloPassword: VerifyRulesType[]; + switchUser1: VerifyRulesType[]; + switchPassword1: VerifyRulesType[]; + switchUser2: VerifyRulesType[]; + switchPassword2: VerifyRulesType[]; +}; + +export { + FormType, + RulesType, + RuleFormRefType +}; diff --git a/bmp-operation-web/src/components/IdcOperates/EditIdc/utils/editIdc.ts b/bmp-operation-web/src/components/IdcOperates/EditIdc/utils/editIdc.ts new file mode 100644 index 0000000..7489e9d --- /dev/null +++ b/bmp-operation-web/src/components/IdcOperates/EditIdc/utils/editIdc.ts @@ -0,0 +1,78 @@ +import {msgTip} from 'utils/index.ts'; +import {FormType} from '../typeManagement'; +import {CurrencyType5} from '@utils/publicType'; +import {language, CurrentInstance} from 'utils/publicClass.ts'; +import IdcStaticData from 'staticData/idc/index.ts'; // 机房等级数据 + +/** + * 编辑机房操作 +*/ +class EditIdcOperate { + // loading加载态 + isLoading: Ref = ref(false); + // 机房等级 + machineRoomGrade: CurrencyType5[] = IdcStaticData.machineRoomGradeData; + formRuleOperate: any; + emitValue: any; + instanceProxy = new CurrentInstance().proxy; + + constructor (formRuleOperate: any, emitValue: any) { + this.emitValue = emitValue; + this.formRuleOperate = formRuleOperate; + document.onkeyup = (event: {keyCode: number;}) => { + event.keyCode === 13 && this.determineClick(); + }; + onUnmounted(() => document.onkeyup = (() => {return})); + }; + + /** + * 确定按钮弹窗 + */ + determineClick = async (): Promise => { + // 判断输入项是否符合条件 + await nextTick(() => { + this.formRuleOperate.validate('customGrade', this.formRuleOperate.customGradeFlag) + this.formRuleOperate.ruleFormRef.value!.validate((valid: boolean) => { + // 输入符合条件后才可以继续后续操作 + if (valid) { + this.isLoading.value = true; + this.#requestVerificationInterface(); + } + }); + }); + }; + + /** + * 请求编辑机房验证接口,成功后把事件回传,关闭弹窗 + */ + #requestVerificationInterface = async () => { + try { + const {level, customGrade}: FormType = this.formRuleOperate.ruleForm; + const newLevel = IdcStaticData.otherData.includes(level!) ? customGrade : level; + const editApi = await this.instanceProxy.$idcApi.editIdcAPI({...this.formRuleOperate.ruleForm, level: newLevel}) + const status = (editApi?.data?.result?.success)?? false; + status && this.#dealWithResponse(); + } + finally { + this.isLoading.value = false; + } + }; + + #dealWithResponse = () => { + msgTip.success(language.t('operate.success')); + this.cancelClick(); + this.emitValue('determine-click'); + }; + + /** + * 取消按钮点击操作 + */ + cancelClick = () => { + // 清空输入内容、异常提示状态 + this.formRuleOperate.ruleFormRef.value!.resetFields(); + // 回传父组件当前页码,可以处理相关操作 + this.emitValue('dia-log-close', false); + }; +}; + +export default EditIdcOperate; diff --git a/bmp-operation-web/src/components/IdcOperates/EditIdc/utils/formRules.ts b/bmp-operation-web/src/components/IdcOperates/EditIdc/utils/formRules.ts new file mode 100644 index 0000000..1e6b362 --- /dev/null +++ b/bmp-operation-web/src/components/IdcOperates/EditIdc/utils/formRules.ts @@ -0,0 +1,142 @@ +import {language} from 'utils/publicClass.ts'; +import {FormType, RulesType, RuleFormRefType} from '../typeManagement'; + +interface DataType { + value: FormType; + idcNameFlag: Ref; + nameEnFlag: Ref; + customGradeFlag: Ref; + iloUserFlag: Ref; + iloPasswordFlag: Ref; + switchUser1Flag: Ref; + switchPassword1Flag: Ref; + switchUser2Flag: Ref; + switchPassword2Flag: Ref; + ruleFormRef: Ref; + ruleForm: FormType; + rules: RulesType; +}; + +const formRule = (props: any, rulesCheck: any) => { + const data: DataType = { + // props参数对象 + value: props?.itemData?.value??props?.itemData, + idcNameFlag: ref(false), + nameEnFlag: ref(false), + customGradeFlag: ref(false), + iloUserFlag: ref(false), + iloPasswordFlag: ref(false), + switchUser1Flag: ref(false), + switchPassword1Flag: ref(false), + switchUser2Flag: ref(false), + switchPassword2Flag: ref(false), + // 表单ref + ruleFormRef: ref(), + // 表单-输入项ts类型 + ruleForm: reactive( + { + ...props?.itemData?.value??props?.itemData, + customGrade: '' + } + ), + // 表单-规则 + rules: reactive({ + name: [ // 机房名称 + { + required: true, + trigger: 'blur', + validator: rulesCheck.computerRoomNameCheck + } + ], + nameEn: [ // 机房英文名称 + { + required: true, + trigger: 'blur', + validator: rulesCheck.computerRoomCodeCheck + } + ], + level: [ // 机房等级 + { + required: true, + trigger: 'change' + } + ], + customGrade: [ // 自定义机房等级 + { + required: true, + trigger: 'blur', + validator: rulesCheck.computerRoomGradeCheck + } + ], + address: [ // 机房地址 + { + required: false, + message: language.t('editIdc.errTip.computerRoomAddressEmpty'), + trigger: 'blur' + } + ], + iloUser: [ // 带外登录账号 + { + required: false, + trigger: 'blur', + validator: rulesCheck.iloUserCheck + } + ], + iloPassword: [ // 带外登录密码 + { + required: false, + trigger: 'blur', + validator: rulesCheck.iloPasswordCheck + } + ], + switchUser1: [ // 交换机1登录账号 + { + required: false, + trigger: 'blur', + validator: rulesCheck.switchUser1Check + } + ], + switchPassword1: [ // 交换机1登录密码 + { + required: false, + trigger: 'blur', + validator: rulesCheck.switchPassword1Check + } + ], + switchUser2: [ // 交换机2登录账号 + { + required: false, + trigger: 'blur', + validator: rulesCheck.switchUser2Check + } + ], + switchPassword2: [ // 交换机2登录密码 + { + required: false, + trigger: 'blur', + validator: rulesCheck.switchPassword2Check + } + ] + }) + }; + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + const getFormRef = (formEl: {value: RuleFormRefType}): void => { + data.ruleFormRef.value = formEl.value; + }; + + const validate = (type1: string, type2: {value: boolean}) => { + data.ruleFormRef.value!.validateField([type1] as never, (valid: string) => !valid ? type2.value = false : type2.value = true); + }; + + return { + ...data, + getFormRef, + validate + }; +}; + +export default formRule; diff --git a/bmp-operation-web/src/components/IdcOperates/EditIdc/utils/idcDetail.ts b/bmp-operation-web/src/components/IdcOperates/EditIdc/utils/idcDetail.ts new file mode 100644 index 0000000..4041254 --- /dev/null +++ b/bmp-operation-web/src/components/IdcOperates/EditIdc/utils/idcDetail.ts @@ -0,0 +1,33 @@ +import {AxiosError} from 'axios'; +import {msgTip} from 'utils/index.ts'; +import {CurrentInstance} from 'utils/publicClass.ts'; + +class IdcDetail { + instanceProxy = new CurrentInstance().proxy; + + constructor (props: any, formRuleOperate: any) { + this.getIdcDetail(props, formRuleOperate); + }; + + getIdcDetail = async (props: any, formRuleOperate: any) => { + try { + const params = { + idcid: props.itemData?.value?.idcId??props.itemData?.idcId, + show: 'iloPassword,switchPassword1,switchPassword2' + }; + const detailApi = await this.instanceProxy.$idcApi.idcDetailAPI(params); + if (detailApi.data?.result && Object.keys(detailApi.data?.result).length) { + const {iloPassword, switchPassword1, switchPassword2} = detailApi.data.result; + formRuleOperate.ruleForm.iloPassword = iloPassword; + formRuleOperate.ruleForm.switchPassword1 = switchPassword1; + formRuleOperate.ruleForm.switchPassword2 = switchPassword2; + } + } + catch (e) { + const err = e as AxiosError; + msgTip.error(err.message); + } + } +}; + +export default IdcDetail; diff --git a/bmp-operation-web/src/components/IdcOperates/EditIdc/utils/ruleVerification.ts b/bmp-operation-web/src/components/IdcOperates/EditIdc/utils/ruleVerification.ts new file mode 100644 index 0000000..dcb480d --- /dev/null +++ b/bmp-operation-web/src/components/IdcOperates/EditIdc/utils/ruleVerification.ts @@ -0,0 +1,155 @@ +import {language} from 'utils/publicClass.ts'; +import {CurrencyType3} from '@utils/publicType'; + +const rulesVerification = () => { + + /** + * 机房名称的校验 + * @param {Object} _ 对应规则的标识 + * @param {string} value 输入框输入的值 + * @param {Function} callback 回调函数,异常/正常时的返回 + */ + const computerRoomNameCheck = ( _: CurrencyType3, value: string, callback: (arg0?: Error | string) => void) => { + currencyCheck(value, language.t('editIdc.errTip.computerRoomNameEmpty'), language.t('editIdc.errTip.currency'), callback); + }; + + /** + * 机房英文名称的校验 + * @param {Object} _ 对应规则的标识 + * @param {string} value 输入框输入的值 + * @param {Function} callback 回调函数,异常/正常时的返回 + */ + const computerRoomCodeCheck = ( _: CurrencyType3, value: string, callback: (arg0?: Error | string) => void) => { + currencyCheck(value, language.t('editIdc.errTip.computerRoomCodeEmpty'), language.t('editIdc.errTip.currency'), callback); + }; + + /** + * 自定义机房等级校验 + * @param {Object} _ 对应规则的标识 + * @param {string} value 输入框输入的值 + * @param {Function} callback 回调函数,异常/正常时的返回 + */ + const computerRoomGradeCheck = ( _: CurrencyType3, value: string, callback: (arg0?: Error | string) => void) => { + currencyCheck(value, language.t('editIdc.errTip.customComputerRoomGrade'), language.t('editIdc.errTip.currency'), callback); + }; + + /** + * 通用校验 + * @param {string} value 输入项/select选择项 + * @param {string} emptyTip 为空提示 + * @param {string} errTip 输入有误提示 + * @param {Function} callback 回调函数,异常/正常时的返回 + */ + const currencyCheck = (value: string, emptyTip: string, errTip: string, callback: (arg0?: Error | string) => void) => { + const check = [ + [ + (value: string) => !value?.length, + () => callback(new Error(emptyTip)) + ], + [ + (value: string) => value.length > 64, + () => callback(new Error(errTip)) + ], + [ + (value: string) => value, + () => callback() + ] + ]; + for (const key of check) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + /** + * 带外登录账号校验 + * @param {Object} _ 对应规则的标识 + * @param {string} value 输入框输入的值 + * @param {Function} callback 回调函数,异常/正常时的返回 + */ + const iloUserCheck = ( _: CurrencyType3, value: string, callback: (arg0?: Error | string) => void) => { + currencyCheck2(value, language.t('editIdc.errTip.currencyPassword'), callback); + }; + + /** + * 带外登录密码校验 + * @param {Object} _ 对应规则的标识 + * @param {string} value 输入框输入的值 + * @param {Function} callback 回调函数,异常/正常时的返回 + */ + const iloPasswordCheck = ( _: CurrencyType3, value: string, callback: (arg0?: Error | string) => void) => { + currencyCheck2(value, language.t('editIdc.errTip.currencyPassword'), callback); + }; + + /** + * 交换机1登录账号校验 + * @param {Object} _ 对应规则的标识 + * @param {string} value 输入框输入的值 + * @param {Function} callback 回调函数,异常/正常时的返回 + */ + const switchUser1Check = ( _: CurrencyType3, value: string, callback: (arg0?: Error | string) => void) => { + currencyCheck2(value, language.t('editIdc.errTip.currencyPassword'), callback); + }; + + /** + * 交换机1登录密码校验 + * @param {Object} _ 对应规则的标识 + * @param {string} value 输入框输入的值 + * @param {Function} callback 回调函数,异常/正常时的返回 + */ + const switchPassword1Check = ( _: CurrencyType3, value: string, callback: (arg0?: Error | string) => void) => { + currencyCheck2(value, language.t('editIdc.errTip.currencyPassword'), callback); + }; + + /** + * 交换机2登录账号校验 + * @param {Object} _ 对应规则的标识 + * @param {string} value 输入框输入的值 + * @param {Function} callback 回调函数,异常/正常时的返回 + */ + const switchUser2Check = ( _: CurrencyType3, value: string, callback: (arg0?: Error | string) => void) => { + currencyCheck2(value, language.t('editIdc.errTip.currencyPassword'), callback); + }; + + /** + * 交换机2登录密码校验 + * @param {Object} _ 对应规则的标识 + * @param {string} value 输入框输入的值 + * @param {Function} callback 回调函数,异常/正常时的返回 + */ + const switchPassword2Check = ( _: CurrencyType3, value: string, callback: (arg0?: Error | string) => void) => { + currencyCheck2(value, language.t('editIdc.errTip.currencyPassword'), callback); + }; + + /** + * 通用校验 + * @param {string} value 输入项 + * @param {string} errTip 输入有误提示 + * @param {Function} callback 回调函数,异常/正常时的返回 + */ + const currencyCheck2 = (value: string, errTip: string, callback: (arg0?: Error | string) => void) => { + if (value.length > 128) { + callback(new Error(errTip)); + } + else { + // 正常情况 + callback(); + } + }; + + return { + computerRoomNameCheck, + computerRoomCodeCheck, + computerRoomGradeCheck, + iloUserCheck, + iloPasswordCheck, + switchUser1Check, + switchPassword1Check, + switchUser2Check, + switchPassword2Check + }; +}; + +export default rulesVerification; diff --git a/bmp-operation-web/src/components/IdcOperates/EditIdc/utils/setLevel.ts b/bmp-operation-web/src/components/IdcOperates/EditIdc/utils/setLevel.ts new file mode 100644 index 0000000..58708ca --- /dev/null +++ b/bmp-operation-web/src/components/IdcOperates/EditIdc/utils/setLevel.ts @@ -0,0 +1,20 @@ +import {FormType} from '../typeManagement'; +import IdcStaticData from 'staticData/idc/index.ts'; + +class SetLevel { + constructor (props: any, formRuleOperate: any, editIdcOperate: any) { + this.init(props, formRuleOperate, editIdcOperate); + }; + + init = (props: any, formRuleOperate: any, editIdcOperate: any) => { + const level: string | undefined = formRuleOperate.ruleForm!.level; + if (IdcStaticData.levelData.includes(level!)) { + (formRuleOperate.ruleForm.level as string | FormType) = props.itemData?.value?.level??props.itemData?.level; + return; + } + formRuleOperate.ruleForm.customGrade = formRuleOperate.ruleForm.level; + formRuleOperate.ruleForm.level = editIdcOperate.machineRoomGrade[4].label; + } +}; + +export default SetLevel; diff --git a/bmp-operation-web/src/components/ImageOperates/ImageDesc/ImageDesc.vue b/bmp-operation-web/src/components/ImageOperates/ImageDesc/ImageDesc.vue new file mode 100644 index 0000000..0e4cac5 --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImageDesc/ImageDesc.vue @@ -0,0 +1,115 @@ + + + + diff --git a/bmp-operation-web/src/components/ImageOperates/ImageDesc/imageDesc.scss b/bmp-operation-web/src/components/ImageOperates/ImageDesc/imageDesc.scss new file mode 100644 index 0000000..f4f1650 --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImageDesc/imageDesc.scss @@ -0,0 +1,37 @@ +@import '@/assets/css/communal'; + +.image-desc { + .el-dialog { + &--center { + --el-dialog-width: 526px; + height: 298px; + } + + &__footer { + width: 481px; + } + } + + &-count { + display: flex; + flex-direction: column; + align-items: flex-start; + + p { + margin: 19.5px 0 8px; + font-size: 12px; + } + + textarea { + width: 480px; + height: 117px; + border-radius: 4px; + font-size: 12px; + resize: none; + + &::placeholder { + font-size: 12px; + } + } + } +} diff --git a/bmp-operation-web/src/components/ImageOperates/ImageModel/ImageAddModel.vue b/bmp-operation-web/src/components/ImageOperates/ImageModel/ImageAddModel.vue new file mode 100644 index 0000000..22816f8 --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImageModel/ImageAddModel.vue @@ -0,0 +1,63 @@ + + + + diff --git a/bmp-operation-web/src/components/ImageOperates/ImageModel/all.ts b/bmp-operation-web/src/components/ImageOperates/ImageModel/all.ts new file mode 100644 index 0000000..9f13e04 --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImageModel/all.ts @@ -0,0 +1,9 @@ +import paginationOperate from './pagination/pagination'; +import ImageDeviceTypes from './table/imageDeviceTypes'; +import addModelOperate from './table/addModel'; + +export { + paginationOperate, + ImageDeviceTypes, + addModelOperate +}; diff --git a/bmp-operation-web/src/components/ImageOperates/ImageModel/imageAddModel.scss b/bmp-operation-web/src/components/ImageOperates/ImageModel/imageAddModel.scss new file mode 100644 index 0000000..453dd2d --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImageModel/imageAddModel.scss @@ -0,0 +1,95 @@ +@import '@/assets/css/communal'; + +.image-model-add { + .el-dialog { + &--center { + width: 860px; + box-shadow: $boxShadow; + border-radius: 10px; + padding: 0 22.5px; + // background: $background7; + height: 520px; + // width: 726px; + // height: 520px; + margin: auto; + background: $whiteBackground; + } + + &__body { + padding: 0; + position: absolute; + min-height: calc(100% - 33px); + left: 50%; + transform: translateX(-50%); + overflow: hidden; + width: 860px; + // width: 720px; + // width: 680.5px; + + .currency-count { + display: flex; + flex-direction: column; + height: calc(91%); + position: absolute; + margin: 0; + // overflow: auto; + overflow: hidden; + width: 815px; + z-index: 1; + padding: 0 22.5px; + + &-table { + .el-table { + margin-bottom: 100px; + } + } + + .check-all { + position: absolute; + left: 10px; + top: 6px; + } + + &-name-title { + font-size: $fontSize; + font-weight: $fontLargeWeight; + color: $defaultColor; + margin: 20px 0 0px; + } + + &-title { + font-size: $fontSize; + font-weight: $fontLargeWeight; + color: $defaultColor; + margin: 6px 0 16px; + } + } + } + + &__footer { + width: 95%; + } + + .currency-count-table { + .img-empty { + .el-table__empty-block { + background: #fff; + + .el-table__empty-text { + color: #333; + } + } + } + .footer-count { + position: fixed; + bottom: 70px !important; + line-height: 55px; + bottom: 0; + background: $whiteBackground; + z-index: 9; + margin-bottom: 10px; + left: 0; + } + } + } +} diff --git a/bmp-operation-web/src/components/ImageOperates/ImageModel/imageName/ImageModelName.vue b/bmp-operation-web/src/components/ImageOperates/ImageModel/imageName/ImageModelName.vue new file mode 100644 index 0000000..773745e --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImageModel/imageName/ImageModelName.vue @@ -0,0 +1,29 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/ImageOperates/ImageModel/pagination/ImageModelPagination.vue b/bmp-operation-web/src/components/ImageOperates/ImageModel/pagination/ImageModelPagination.vue new file mode 100644 index 0000000..a5193de --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImageModel/pagination/ImageModelPagination.vue @@ -0,0 +1,34 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/ImageOperates/ImageModel/pagination/pagination.ts b/bmp-operation-web/src/components/ImageOperates/ImageModel/pagination/pagination.ts new file mode 100644 index 0000000..99b6742 --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImageModel/pagination/pagination.ts @@ -0,0 +1,44 @@ +interface DataType { + pageSize: Ref; + pageNumber: Ref; + total: Ref; +}; + +const paginationOperate = (fn: any) => { + const data: DataType = { + pageSize: ref(20), + pageNumber: ref(1), + total: ref(0) + }; + + watch(() => [ + data.pageSize.value, + data.pageNumber.value + ], (_: any[]): void => { + fn(); + }); + + /** + * 分页操作 + * @param {number} count 每页展示条数、页数 + * @param {string} type size、num类型 + */ + const paginationChange = (count: number, type: string) => { + switch (type) { + case 'num': + data.pageNumber.value = count; + break; + case 'size': + data.pageSize.value = count; + data.pageNumber.value = 1; + break; + }; + }; + + return { + ...data, + paginationChange + }; +}; + +export default paginationOperate; diff --git a/bmp-operation-web/src/components/ImageOperates/ImageModel/table/ImageDeviceTypesList.vue b/bmp-operation-web/src/components/ImageOperates/ImageModel/table/ImageDeviceTypesList.vue new file mode 100644 index 0000000..545d6ca --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImageModel/table/ImageDeviceTypesList.vue @@ -0,0 +1,219 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/ImageOperates/ImageModel/table/addModel.ts b/bmp-operation-web/src/components/ImageOperates/ImageModel/table/addModel.ts new file mode 100644 index 0000000..024afed --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImageModel/table/addModel.ts @@ -0,0 +1,52 @@ +import {msgTip} from 'utils/index.ts'; // 深拷贝数据 +import {imageAddModelAPI} from 'api/image/request.ts'; // 添加机型接口 +import {language} from 'utils/publicClass.ts'; + +const addModelOperate = (imageDeviceTypes: any, props: any, emitValue: any) => { + // loading加载态 + const isLoading: Ref = ref(false); + + /** + * 请求机型验证接口,成功后把事件回传,关闭弹窗 + */ + const determineClick = (): void => { + const paramsData = imageDeviceTypes.reactiveArr.arr.filter((item: {isBind: boolean;}) => !item.isBind); + isLoading.value = true; + imageAddModelAPI( + { + imageId: props.imageId, + deviceTypeIds: paramsData.map((item: {deviceTypeId: string;}) => item.deviceTypeId).join(',') + } + ) + .then(({data} : {data: {result: {success: boolean;}}}) => { + if (data?.result?.success) { + msgTip.success(language.t('operate.success')); + emitValue('determine-click'); + cancelClick(); + } + }) + .finally(() => { + isLoading.value = false; + }) + .catch(() => { + emitValue('determine-click'); + cancelClick(); + }) + }; + + /** + * 取消按钮点击操作 + */ + const cancelClick = (): void => { + // 回传父组件当前页码,可以处理相关操作 + emitValue('dia-log-close', false); + }; + + return { + isLoading, + determineClick, + cancelClick + }; +}; + +export default addModelOperate; diff --git a/bmp-operation-web/src/components/ImageOperates/ImageModel/table/imageDeviceTypes.ts b/bmp-operation-web/src/components/ImageOperates/ImageModel/table/imageDeviceTypes.ts new file mode 100644 index 0000000..2e620d3 --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImageModel/table/imageDeviceTypes.ts @@ -0,0 +1,200 @@ +import {ElTable} from 'element-plus'; +import {languageSwitch} from 'utils/index.ts'; +import {imageDeviceTypesAPI} from 'api/image/request.ts'; // 添加机型接口 +// import publicIndexStore from 'store/index.ts'; // 公共store +import {CurrencyType} from '@utils/publicType'; +import ImageStaticData from 'staticData/image/index.ts'; + +interface ParamsType { + pageNumber: number; + pageSize: number; + imageId: string; + architecture: string; + hasCheckbox: string; +}; + +class ImageDeviceTypes { + locale = languageSwitch(); + // 表单ref + tableRef = ref>() + // table-loading加载态 + tableLoading: Ref = ref(true); + // filter-空值参数 + reactiveArr: any = reactive({ + selection: [], + tableData: [], + arr: [], + idList: [] + }); + btnDisabled: Ref = ref(0); + customPagination: any; + props: any; + + constructor (customPagination: any, props: any) { + this.customPagination = customPagination; + this.props = props; + this.processingParameters(); + watch(() => this.reactiveArr.arr, (newValue) => { + this.btnDisabled.value = newValue.filter((item: {hasCheckbox: boolean;}) => !item.hasCheckbox).length + }, {deep: true}) + }; + + /** + * 获取表格ref + * @param {Object} tableEl 表格信息 + */ + getTableRef = async (tableEl: any): Promise => { + await nextTick(() => { + this.tableRef = tableEl; + }); + }; + + processingParameters = () => { + let params: ParamsType = { + pageNumber: this.customPagination.pageNumber.value, + pageSize: this.customPagination.pageSize.value, + imageId: this.props.imageId, + architecture: this.props.architecture, + hasCheckbox: '0' + }; + this.imageDeviceTypes(params); + }; + + imageDeviceTypes = (params: any) => { + this.tableLoading.value = true; + imageDeviceTypesAPI( + { + ...params + } + ) + .then(({data}: {data: any}) => { + if (data?.result?.deviceTypes?.length) { + const newDeviceTypes = data.result.deviceTypes.map((item: {hasCheckbox: boolean; deviceTypeId: string;}, index: number) => { + item.hasCheckbox = this.reactiveArr?.arr?.filter((ite: {deviceTypeId: string;}) => ite.deviceTypeId === item.deviceTypeId)[0]??false; + ImageStaticData.imageModelAddTipData.forEach((t: any) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }) + return item; + }); + this.reactiveArr.tableData = newDeviceTypes; + this.customPagination.total.value = data.result.totalCount; + nextTick(() => { + for (const key of this.reactiveArr.tableData) { + this.tableRef?.value?.toggleRowSelection(key, key.hasCheckbox); + } + }); + return; + } + return Promise.reject(''); + }) + .catch(() => { + this.reactiveArr.tableData = []; + this.customPagination.total.value = 0; + }) + .finally(() => { + this.tableLoading.value = false; + }); + }; + + + // 多选框回显 + getRowKeys = (row: {deviceTypeId: string;}) => { + if (row.deviceTypeId) return row.deviceTypeId; + }; + + selectAllChange = (rows: CurrencyType[]) => { + const newRows = rows.filter((item) => !item.hasCheckbox); + if (newRows.length > 0) { // 全选 + for(let i = 0; i < newRows.length; i++) { + // 未添加的才插入,否则数据会冗余 + if (!this.reactiveArr.arr.some((s: {deviceTypeId: string;}) => s.deviceTypeId === newRows[i].deviceTypeId)) { + this.reactiveArr.arr.push(newRows[i]); + } + } + } + else { // 取消全选 + for (let i = 0; i< this.reactiveArr.tableData.length; i++) { + for (let j = 0; j< this.reactiveArr.idList.length; j++){ + // 移除当前页idList的数据 + if (this.reactiveArr.idList[j].deviceTypeId === this.reactiveArr.tableData[i].deviceTypeId) { + this.reactiveArr.idList.splice(j, 1); + } + } + for(let k = 0; k < this.reactiveArr.arr.length; k++){ + // 移除当前页idList的数据 + if (this.reactiveArr.arr[k].deviceTypeId === this.reactiveArr.tableData[i].deviceTypeId) { + this.reactiveArr.arr.splice(k, 1); + } + } + } + } + }; + + rowClick = (row: any, _: any, event: any) => { + this.tableRef.value!.toggleRowSelection(row, event); + this.selectChange(this.reactiveArr.selection, row); + }; + + /** + * 单选 + */ + selectChange = (rows: CurrencyType[], row: CurrencyType) => { + const newRows: boolean | number = rows.filter((item) => !item.hasCheckbox).length && rows.indexOf(row) !== -1; + if (newRows) { + this.reactiveArr.arr.push(row); + } + else { + for(let i = 0; i < this.reactiveArr.idList.length; i++) { + if(this.reactiveArr.idList[i].deviceTypeId === row.deviceTypeId){ + this.reactiveArr.idList.splice(i,1); + } + } + for(let i = 0; i < this.reactiveArr.arr.length; i++){ + if(this.reactiveArr.arr[i].deviceTypeId === row.deviceTypeId){ + this.reactiveArr.arr.splice(i,1); + } + } + } + }; + + /** + * 当选择项发生变化时会触发该事件 + */ + handleSelectionChange = (val: CurrencyType[]) => { + this.reactiveArr.selection = val.filter((item) => !item.hasCheckbox); + }; + + // checkAll = (event: Event) => { + // const filterData = this.reactiveArr.tableData.filter((item: {hasCheckbox: boolean}) => !item.hasCheckbox); + // filterData.map(item => { + // // toggleRowSelection接收两个参数,第一个是被勾选的数据,第二个是选中状态(注:需要注册 ref 来引用) + // if (event) { + // for(let i = 0; i < filterData.length; i++) { + // // 未添加的才插入,否则数据会冗余 + // if (!this.reactiveArr.arr.some((s: {imageId: string;}) => s.imageId === filterData[i].imageId)) { + // this.reactiveArr.arr.push(filterData[i]); + // } + // } + // } + // else { + // for (let i = 0; i< this.reactiveArr.tableData.length; i++) { + // for (let j = 0; j< this.reactiveArr.idList.length; j++){ + // // 移除当前页idList的数据 + // if (this.reactiveArr.idList[j].imageId === this.reactiveArr.tableData[i].imageId) { + // this.reactiveArr.idList.splice(j, 1); + // } + // } + // for(let k = 0; k < this.reactiveArr.arr.length; k++){ + // // 移除当前页idList的数据 + // if (this.reactiveArr.arr[k].imageId === this.reactiveArr.tableData[i].imageId) { + // this.reactiveArr.arr.splice(k, 1); + // } + // } + // } + // } + // this.tableRef?.value.toggleRowSelection(item, event); + // }); + // }; +}; + +export default ImageDeviceTypes; diff --git a/bmp-operation-web/src/components/ImageOperates/ImageModel/typeManagement.ts b/bmp-operation-web/src/components/ImageOperates/ImageModel/typeManagement.ts new file mode 100644 index 0000000..e26512d --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImageModel/typeManagement.ts @@ -0,0 +1,14 @@ +/** + * params参数 +*/ +interface ParamsType { + pageSize: number; + pageNumber: number; + deviceTypeId: string; + osType?: string; + architecture?: string; +}; + +export { + ParamsType +}; diff --git a/bmp-operation-web/src/components/ImageOperates/ImportImage/ImportImage.vue b/bmp-operation-web/src/components/ImageOperates/ImportImage/ImportImage.vue new file mode 100644 index 0000000..e932018 --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImportImage/ImportImage.vue @@ -0,0 +1,327 @@ + + + + diff --git a/bmp-operation-web/src/components/ImageOperates/ImportImage/importImage.scss b/bmp-operation-web/src/components/ImageOperates/ImportImage/importImage.scss new file mode 100644 index 0000000..eda18f7 --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImportImage/importImage.scss @@ -0,0 +1,243 @@ + +@import '@/assets/css/communal'; + +.import-image { + .el-dialog { + &--center { + --el-dialog-width: 646px; + height: 630px;; + } + + &__body { + height: 515px; + overflow-y: auto; + overflow-x: hidden; + } + + &__footer { + width: 601px; + } + } + + &-ruleForm { + margin-top: 11px; + + .multiple-choice { + input { + width: 470px !important; + } + + + .el-select__tags { + .el-tag.el-tag--info.is-hit { + + .el-tag__content { + font-size: $fontSize; + + .el-select__tags-text { + width: auto !important; + justify-content: flex-start; + // max-width: px !important; + } + } + } + } + + } + + .import-image-name { + .is-loading { + position: absolute; + right: 10px; + top: 7px; + z-index: 9; + animation: loading .7s linear ease-in-out; + } + + @keyframes loading { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(100deg); + } + } + } + .set-empty { + margin-bottom: 32px !important; + .el-form-item__error { + margin-top: 6px !important; + } + } + + .set-default { + // margin-bottom: 16px !important; + } + + .set-empty-chooseimage { + margin-bottom: 52px !important; + } + + .el-form-item__label { + line-height: 1.5; + display: flex; + align-items: center; + position: relative; + font-weight: $fontLargeWeight; + } + + .el-form-item__error { + margin-top: 1.5px !important; + } + + &-desc { + .el-form-item__label { + align-items: flex-start; + margin-top: 8px; + width: 100px !important; + margin-left: 10px; + } + } + + .sys-partition { + .el-form-item__label { + width: 122px !important; + display: flex; + align-items: flex-start; + margin-right: -15px; + } + + .el-form-item__content { + height: 20px; + line-height: 20px; + margin-left: 4px; + } + } + + &-choose-image { + .el-form-item__content { + display: flex; + justify-content: flex-start !important; + + .upload-demo { + .el-upload-list { + position: absolute !important; + } + } + + a.el-upload-list__item-name { + border-radius: 4px; + width: 465px; + border: .63px solid #979797; + height: 30px; + display: flex; + align-items: center; + font-size: $fontSize; + font-weight: $fontLargeWeight; + margin-bottom: 20px; + margin-right: 0; + color: $defaultColor; + text-decoration: none; + cursor: pointer; + + &:hover { + background: $whiteBackground; + } + } + + .el-upload-list__item-status-label { + top: 5px; + } + + .el-upload-list__item .el-icon--close { + top: 9px !important; + } + } + + .error-tip { + color: $color13; + font-size: $fontSize; + // margin-bottom: 20px; + position: absolute; + } + } + + .el-form-item__label, + .el-input__inner { + font-size: $fontSize; + color: $defaultColor; + } + + .el-form-item--default { + margin-bottom: 20px; + } + + input { + width: 470px; + height: 30px; + border-radius: 4px; + } + + textarea { + width: 470px; + height: 78px; + padding: 5px 8px; + margin-top: 7px; + font-size: $fontSize; + resize: none; + // margin-left: 10px; + + &::placeholder { + font-size: $fontSize; + } + } + + .el-textarea .el-input__count { + right: 30px !important; + } + + .input-select-count { + float: left; + + .el-form-item__content { + display: flex; + justify-content: flex-start; + } + + .input-select { + margin-left: 33px; + + .el-input__inner { + width: 130px; + height: 30px; + border-radius: 4px; + color: $defaultColor; + font-weight: $fontLargeWeight; + } + } + } + + + .input-phone-count { + display: flex; + + .el-form-item__content { + display: flex; + justify-content: flex-start; + } + + .el-input--default, + .el-input__inner { + width: 162px; + height: 30px; + } + } + + input { + &:focus { + border-color: $border3; + } + } + } +} + diff --git a/bmp-operation-web/src/components/ImageOperates/ImportImage/typeManagement.ts b/bmp-operation-web/src/components/ImageOperates/ImportImage/typeManagement.ts new file mode 100644 index 0000000..3a1ac73 --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImportImage/typeManagement.ts @@ -0,0 +1,58 @@ +import {CurrencyType, RuleFormRefType, VerifyRulesType, SystemPartitionType} from '@utils/publicType'; + + + + +type RuleFormRefType2 = Omit; +interface ReactiveArrType { + defaultBootMode: string[]; + fileParams: {result?: CurrencyType[]}; + architectureData: CurrencyType[]; + totalData: CurrencyType; + architecture: CurrencyType[]; + osType: CurrencyType[]; + osVersion: CurrencyType[]; + bootModeData: string[]; + imageFormatData: string[]; +}; + +/** + * 表单类 +*/ +interface RuleFormType { + imageName: string; + architecture: string | number; + osType: string; + customVersion: string; + imageFormat: string; + bootMode: CurrencyType[] | null; + customOperatePlatform?: string; + version: string; + systemPartition: SystemPartitionType[]; + description: string; + imageFile?: CurrencyType[]; +}; + +/** + * 规则类 +*/ +interface RulesType { + imageName: VerifyRulesType[]; + architecture: VerifyRulesType[]; + osType: VerifyRulesType[]; + customOperatePlatform: VerifyRulesType[]; + customVersion: VerifyRulesType[]; + version: VerifyRulesType[]; + imageFormat: VerifyRulesType[]; + bootMode: VerifyRulesType[]; + systemPartition: VerifyRulesType[]; + imageFile?: VerifyRulesType[]; +}; + + +export { + RulesType, + RuleFormType, + ReactiveArrType, + RuleFormRefType2 +}; diff --git a/bmp-operation-web/src/components/ImageOperates/ImportImage/utils/chooseImage.ts b/bmp-operation-web/src/components/ImageOperates/ImportImage/utils/chooseImage.ts new file mode 100644 index 0000000..553cc8e --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImportImage/utils/chooseImage.ts @@ -0,0 +1,90 @@ +import {msgTip} from 'utils/index.ts'; +import {language, CurrentInstance} from 'utils/publicClass'; +import {UpLoadsType, CurrencyType} from '@utils/publicType'; + +class ChooseImage { + chooseImageFlag: Ref = ref(false); + + // 是否显示异常提示-默认false + hasError: Ref = ref(false); + // 上传 + uploads: Ref = ref(); + formRulesOperate: any; + fn: any + instanceProxy = new CurrentInstance().proxy; + + constructor (formRulesOperate: any, fn: any) { + this.formRulesOperate = formRulesOperate; + this.fn = fn; + }; + + /** + * 上传的event事件 + */ + uploadEvent = (refs: {value: UpLoadsType}): void => { + this.uploads.value = refs.value; + }; + + /** + * 仅限上传一次,第二次上次替换第一次的值时-触发 + * @param {Object} files 上传的文件 + */ + handleExceed = (files: CurrencyType[]): void => { + this.uploads.value!.clearFiles(); + const file: CurrencyType = files[0]; + this.uploads.value!.handleStart(file); + this.hasError.value = false; + this.chooseImageFlag.value = false; + }; + + handleChange = (_: unknown, data: Array) => { + this.formRulesOperate.ruleForm.imageFile = data; + this.uploads.value!.submit(); + this.chooseImageFlag.value = false; + }; + + /** + * 点击删除上传信息时触发 + */ + removeChange = (): void => { + // this.hasError.value = true; + this.formRulesOperate.ruleForm.imageFile = []; + this.chooseImageFlag.value = false; + }; + + /** + * 上传成功的返回 + */ + uploadSuccess = (result: CurrencyType): void => { + this.fn(result); + // importImage.reactiveArr.fileParams = result; + this.hasError.value = false; + this.chooseImageFlag.value = false; + }; + + /** + * 上传失败的返回 + * @param {Object} error 失败信息 + * @param {Object} uploadFile 上传的文件 + * @param {Object} uploadFiles 上传的文件信息 + */ + errorChange = (error: Error & string): void => { + const status = JSON.parse(JSON.stringify(error)).status; + if (status === 402) { + const path: string = this.instanceProxy!.$defInfo.routerPath('login') as unknown as string; + window.open(path, '_self'); + return; + } + const errorInfo: {error: {message: string;}} = JSON.parse(error.message); + msgTip.error(errorInfo?.error?.message??language.t('importImage.errTip.error')); + this.chooseImageFlag.value = false; + }; + + progressChange = (info: {percent: number | {toFixed(arg0: number): number;}}) => { + this.hasError.value = false; + this.chooseImageFlag.value = false; + info.percent = Number(info.percent.toFixed(2)); + }; +}; + +export default ChooseImage; diff --git a/bmp-operation-web/src/components/ImageOperates/ImportImage/utils/formRules.ts b/bmp-operation-web/src/components/ImageOperates/ImportImage/utils/formRules.ts new file mode 100644 index 0000000..d720c91 --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImportImage/utils/formRules.ts @@ -0,0 +1,53 @@ +import {RuleFormType, RuleFormRefType2} from '../typeManagement'; + +interface DataType { + ruleFormRef: Ref; + ruleForm: RuleFormType; +} + +const formRules = () => { + const data: DataType = { + // 表单ref + ruleFormRef: ref(), + // 表单提交项 + ruleForm: reactive({ + imageFile: [], // 选择镜像 + imageName: '', // 镜像名称 + architecture: '', // 体系架构 + osType: '', // 操作系统平台 + customOperatePlatform: '', // 自定义操作系统平台 + customVersion: '', // 自定义操作版本 + imageFormat: '', // 镜像格式 + bootMode: null, // 引导模式 + version: '', // 操作系统版本 + systemPartition: [ + { + format: "xfs", + point: "/", + size: 51200 + }, + { + format: "swap", + point: "swap", + size: 10240 + } + ], // 系统盘分区模块 + description: '' // 镜像描述 + }) + }; + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + const getFormRef = (formEl: {value: RuleFormRefType2}): void => { + data.ruleFormRef.value = formEl.value; + }; + + return { + ...data, + getFormRef + }; +}; + +export default formRules; diff --git a/bmp-operation-web/src/components/ImageOperates/ImportImage/utils/importImage.ts b/bmp-operation-web/src/components/ImageOperates/ImportImage/utils/importImage.ts new file mode 100644 index 0000000..0830c86 --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImportImage/utils/importImage.ts @@ -0,0 +1,196 @@ +import {ReactiveArrType} from '../typeManagement'; +import {imageOssAPI} from 'api/image/request.ts'; +import {importImageAPI} from 'api/image/request.ts'; +import {CurrencyType, CurrencyType5} from '@utils/publicType'; +import {msgTip} from 'utils/index.ts'; +import MethodsTotal from 'utils/index.ts'; +import ImageStaticData from 'staticData/image/index.ts'; +import {language} from 'utils/publicClass.ts'; + +class ImportImageOperate { + hasClick: Ref = ref(false); + imageFormatClick: Ref = ref(false); + sysDefault: Ref = ref(''); + hasBootModeFlag: Ref = ref(false); + // loading 加载态 + isLoading: Ref = ref(false); + init: number = 1; + // 复杂数据类型 + reactiveArr: ReactiveArrType = reactive({ + defaultBootMode: [], + fileParams: {}, + architectureData: [], + totalData: {}, + architecture: [], // 体系架构 + osType: [], // 操作系统平台 + osVersion: [], // 操作系统版本 + bootModeData: [], + imageFormatData: [] + }); + formRulesOperate: any; + rulesVerification: any; + chooseImageOperate: any; + emitValue: any; + + constructor (formRulesOperate: any, rulesVerification: any, chooseImageOperate: any, emitValue: any) { + this.#getImageOss(); + this.formRulesOperate = formRulesOperate; + this.rulesVerification = rulesVerification; + this.chooseImageOperate = chooseImageOperate; + this.emitValue = emitValue; + }; + + #getImageOss = () => { + imageOssAPI({}) + .then(({data} : {data: {result: {architecture: CurrencyType;}}}) => { + if (data?.result?.architecture) { + this.reactiveArr.totalData = data.result.architecture; + this.reactiveArr.defaultBootMode = (this.reactiveArr.totalData.bootMode as unknown as string[]); + this.reactiveArr.imageFormatData = (this.reactiveArr.totalData.format as unknown as string[]); + this.#processData('architecture', data.result.architecture, Object.keys); + if (this.init === 1) { + this.init ++; + this.#setInitData(); + } + } + }); + }; + + #setInitData = () => { + const osType = (this.reactiveArr.totalData['x86_64'][`${['osType']}` as keyof typeof this.reactiveArr.totalData['x86_64']] as never); + this.reactiveArr.architectureData = osType; + this.formRulesOperate.ruleForm.architecture = 'x86_64'; + this.formRulesOperate.ruleForm.osType = Object.keys(osType)[0]; + this.formRulesOperate.ruleForm.version = osType['CentOS'][0]; + this.#processData('osType', osType, Object.keys); + this.#processData('osVersion', osType['CentOS'], Object.values); + }; + + imageFormatChange = () => { + this.reactiveArr.bootModeData = this.reactiveArr.defaultBootMode; + if (this.hasBootModeFlag.value) { + this.hasBootModeFlag.value = false; + } + } + + bootModeChange = (val: string | string[]) => { + this.rulesVerification.rules.bootMode[0].trigger = 'change'; + this.hasBootModeFlag.value = !(val?.length); + }; + + architectureChange = (architecture: string & number) => { + this.hasClick.value = true; + this.formRulesOperate.ruleForm.osType = ''; + this.formRulesOperate.ruleForm.version = ''; + const osType = (this.reactiveArr.totalData[architecture][`${['osType']}` as keyof typeof this.reactiveArr.totalData['architecture']] as never); + this.reactiveArr.architectureData = osType; + this.#processData('osType', osType, Object.keys); + }; + + osTypeChange = (osType: number & string) => { + this.hasClick.value = true; + this.formRulesOperate.ruleForm.version = ''; + const newData = this.reactiveArr.architectureData[osType]; + this.#processData('osVersion', newData, Object.values); + }; + + #processData = (type: string, newData: string | CurrencyType, obj: Function) => { + (this.reactiveArr[`${type}` as keyof typeof this.reactiveArr] as string) = obj(newData).map((item: string, index: number): CurrencyType5 => { + return { + value: index + 1, + label: item + } + }); + }; + + /** + * 确定按钮弹窗 + */ + determineClick = async (): Promise => { + this.isLoading.value = true; + // 判断输入项是否符合条件 + await nextTick(() => { + this.formRulesOperate.ruleFormRef.value!.validate(async (valid: boolean) => { + // 输入符合条件后才可以继续后续操作 + if (valid && this.reactiveArr?.fileParams?.result) { + this.#requestImportImage(await this.#setParams()); + return; + } + this.isLoading.value = false; + this.hasClick.value = true; + this.imageFormatClick.value = true; + this.hasBootModeFlag.value = !this.formRulesOperate.ruleForm.bootMode?.length + this.rulesVerification.customOSVersion.value = true; + this.#fileErrorStatus(valid); + }); + }); + }; + + #setParams = async () => { + const params: CurrencyType = MethodsTotal.deepCopy(this.formRulesOperate.ruleForm); + params.systemPartition = JSON.stringify(params.systemPartition); + if (ImageStaticData.otherSystemData.includes(params.osType)) { + // params.systemPartition = ''; + if (!['Windows'].includes(params.osType)) { + params.osType = params.customOperatePlatform + params.version = params.customVersion; + } + } + else { + // params.systemPartition = JSON.stringify(params.systemPartition); + } + return params; + }; + + #fileErrorStatus = (valid: boolean) => { + if (!this.formRulesOperate.ruleForm.imageFile?.length) { + this.chooseImageOperate.hasError.value = true; + this.chooseImageOperate.chooseImageFlag.value = true; + return; + } + if (!valid) return; + this.chooseImageOperate.hasError.value = false; + msgTip.warning(language.t('importImage.errTip.upload')); + }; + + /** + * 请求导入镜像接口,成功后把事件回传,关闭弹窗 + */ + #requestImportImage = (params: CurrencyType): void => { + let bootMode = params.imageFormat === 'tar' ? (params.bootMode as any).join(',') : params.bootMode; + params.bootMode = bootMode; + importImageAPI({ + ...params, + ...this.reactiveArr.fileParams.result + }) + .then(({data} : {data: {result: {imageId: string;}}}) => { + if (data?.result?.imageId) { + msgTip.success(language.t('operate.success')); + this.emitValue('determine-click'); + this.cancelClick(); + } + }) + .finally(() => { + this.isLoading.value = false; + }); + }; + + /** + * 取消按钮点击操作 + */ + cancelClick = (): void => { + // 关闭蒙层 + this.diaLogClose(); + }; + + /** + * defineEmits API 来替代 emits,子传父,事件回传 + */ + diaLogClose = (): void => { + this.chooseImageOperate.uploads.value!.abort(); + this.chooseImageOperate.uploads.value!.clearFiles(); + this.emitValue('dia-log-close', false); + }; +}; + +export default ImportImageOperate; diff --git a/bmp-operation-web/src/components/ImageOperates/ImportImage/utils/rulesVerification.ts b/bmp-operation-web/src/components/ImageOperates/ImportImage/utils/rulesVerification.ts new file mode 100644 index 0000000..507bb7e --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/ImportImage/utils/rulesVerification.ts @@ -0,0 +1,221 @@ +// import {CurrencyType1} from '@utils/publicType'; +import {language} from 'utils/publicClass.ts'; +import {resourcesAPI} from 'api/public/request.ts'; +import {RulesType} from '../typeManagement'; + +class RulesVerification { + isShowLoading: Ref = ref(false); + imageNameFlag: Ref = ref(false); + customOSType: Ref = ref(false); + customOSVersion: Ref = ref(false); + // 表单提交规则 + rules: RulesType = reactive ({ + imageName: [ // 镜像名称 + { + required: true, + trigger: 'blur', + validator: '' + } + ], + architecture: [ // 体系架构 + { + required: true, + trigger: 'change', + message: language.t('importImage.emptyTip.architecture') + } + ], + osType: [ // 操作系统平台 + { + required: true, + trigger: 'change', + message: language.t('importImage.emptyTip.operateSysPlatform') + } + ], + customOperatePlatform: [ // 自定义操作系统平台 + { + required: true, + trigger: 'blur', + validator: '' + } + ], + customVersion: [ + { + required: true, + trigger: 'blur', + validator: '' + } + ], + imageFormat: [ + { + required: true, + trigger: 'change', + message: language.t('importImage.emptyTip.imageFormat') + } + ], + bootMode: [ + { + required: true, + trigger: 'blur', + validator: '' + // message: language.t('importImage.emptyTip.bootMode') + } + ], + version: [ // 操作系统版本 + { + required: true, + trigger: 'change', + message: language.t('importImage.emptyTip.operateSysVersion') + } + ], + systemPartition: [ // 系统盘分区模板 + { + required: true + } + ], + imageFile: [ // 选择镜像 + { + required: true, + trigger: 'change' + } + ] + }); + fn: any; + + constructor(fn: any) { + this.fn = fn; + this.rules.imageName[0].validator = this.imageNameChcek; + this.rules.customOperatePlatform[0].validator = this.customOperatePlatformCheck; + this.rules.customVersion[0].validator = this.customVersionCheck; + this.rules.bootMode[0].validator = this.bootModeCheck; + } + + /** + * 镜像名称校验 + * @param {Object} _ 对应规则的标识 + * @param {string} value 输入框输入的值 + * @param {Function} callback 回调函数,异常/正常时的返回 + */ + imageNameChcek: unknown = (_: unknown, value: string, callback: (arg0?: Error | string) => void) => { + const imageNameArr = [ + [ + (value: string) => !value?.length, + () => { + this.imageNameFlag.value = true; + callback(new Error(language.t('importImage.emptyTip.imageName'))); + } + ], + [ + (value: string) => (value.length > 64), + () => { + this.imageNameFlag.value = true; + callback(new Error(language.t('importImage.errTip.imageName'))); + } + ], + [ + (value: string) => value, + () => { + this.isShowLoading.value = true; + resourcesAPI( + { + imageName: value + } + ) + .then(({data}: {data: {result: {success: boolean}}}) => { + if (data?.result?.success) { + this.imageNameFlag.value = true; + callback(new Error(language.t('importImage.errTip.imageRepeat'))); + return; + } + // importImageOperate.repeatData = images.map((item) => item.imageName); + return Promise.reject(); + }) + .catch(() => { + this.imageNameFlag.value = false; + callback(); + // importImageOperate.repeatData = []; + }) + .finally(() => { + this.isShowLoading.value = false; + }); + } + ] + ]; + for (const key of imageNameArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + customOperatePlatformCheck: unknown = (_: unknown, value: string, callback: (arg0?: Error | string) => void) => { + this.customOSType.value = true; + const cusotmPlatFormArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t('importImage.emptyTip.customOperatePlatform'))) + ], + [ + (value: string) => value, + () => { + this.customOSType.value = false; + callback(); + } + ] + ]; + for (const key of cusotmPlatFormArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + customVersionCheck: unknown = (_: unknown, value: string, callback: (arg0?: Error | string) => void) => { + this.customOSVersion.value = true; + const customVersionArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t('importImage.emptyTip.customVersion'))) + ], + [ + (value: string) => value, + () => { + this.customOSVersion.value = false; + callback(); + } + ] + ]; + for (const key of customVersionArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + bootModeCheck: unknown = (_: unknown, value: string, callback: (arg0?: Error | string) => void) => { + this.fn(true); + const customVersionArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t('importImage.emptyTip.bootMode'))) + ], + [ + (value: string) => value, + () => { + this.fn(false); + callback(); + } + ] + ]; + for (const key of customVersionArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; +}; + +export default RulesVerification; diff --git a/bmp-operation-web/src/components/ImageOperates/RemoveModel/RemoveModel.vue b/bmp-operation-web/src/components/ImageOperates/RemoveModel/RemoveModel.vue new file mode 100644 index 0000000..0eb88c3 --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/RemoveModel/RemoveModel.vue @@ -0,0 +1,106 @@ + + + + diff --git a/bmp-operation-web/src/components/ImageOperates/RemoveModel/removeModel.scss b/bmp-operation-web/src/components/ImageOperates/RemoveModel/removeModel.scss new file mode 100644 index 0000000..aef46d3 --- /dev/null +++ b/bmp-operation-web/src/components/ImageOperates/RemoveModel/removeModel.scss @@ -0,0 +1,56 @@ +@import '@/assets/css/communal'; + +.remove-model { + .el-dialog { + &--center { + --el-dialog-width: 526px; + } + + &__footer { + width: 481px; + } + } + + &-count { + display: flex; + align-items: center; + justify-content: center; + margin-top: 28.5px; + flex-direction: column; + + &-tip { + padding: 9px 18px; + border-radius: 2px; + background: #f9ecee; + // margin-top: 20px; + display: flex; + align-items: flex-start; + justify-content: center; + + img { + width: 16px; + height: 16px; + margin-right: 8px; + } + + span { + font-size: $fontSize; + color: $defaultColor; + } + } + + &-title { + width: 420px; + font-size: 14px; + font-weight: $fontSmallWeight; + color: $defaultColor; + text-align: center; + margin-top: 45px; + padding-bottom: 127.5px; + + span { + font-weight: $fontLargeWeight; + } + } + } +} diff --git a/bmp-operation-web/src/components/InBandMonitoringManagement/AllAlarmRules/AlarmHistory.vue b/bmp-operation-web/src/components/InBandMonitoringManagement/AllAlarmRules/AlarmHistory.vue new file mode 100644 index 0000000..203017d --- /dev/null +++ b/bmp-operation-web/src/components/InBandMonitoringManagement/AllAlarmRules/AlarmHistory.vue @@ -0,0 +1,299 @@ + + + + diff --git a/bmp-operation-web/src/components/InBandMonitoringManagement/AllAlarmRules/index.scss b/bmp-operation-web/src/components/InBandMonitoringManagement/AllAlarmRules/index.scss new file mode 100644 index 0000000..e524eee --- /dev/null +++ b/bmp-operation-web/src/components/InBandMonitoringManagement/AllAlarmRules/index.scss @@ -0,0 +1,121 @@ +.alarm-history-count { + .el-dialog { + &--center { + width: 860px; + box-shadow: $boxShadow; + border-radius: 10px; + padding: 0 22.5px; + // background: $background7; + height: 520px; + // width: 726px; + // height: 520px; + margin: auto; + background: $whiteBackground; + } + + &__body { + padding: 0; + position: absolute; + min-height: calc(100% - 33px); + left: 50%; + transform: translateX(-50%); + overflow: hidden; + width: 860px; + // width: 720px; + // width: 680.5px; + + .currency-count { + display: flex; + flex-direction: column; + height: calc(91%); + position: absolute; + margin: 0; + // overflow: auto; + overflow: hidden; + width: 815px; + z-index: 1; + padding: 0 22.5px; + + .el-table__body { + margin-bottom: 30px; + + } + + .el-range-input { + font-size: $fontSize; + } + + .reduce-search-opt { + margin: 20px 0 10px; + } + + .search-opt { + margin: 20px 0; + } + + .reduce-search-opt, + .search-opt { + display: flex; + align-items: center; + + button { + margin-left: 30px; + } + } + + // &-table { + // .el-table { + // margin-bottom: 100px; + // } + // } + + .check-all { + position: absolute; + left: 10px; + top: 6px; + } + + &-name-title { + font-size: $fontSize; + font-weight: $fontLargeWeight; + color: $defaultColor; + margin: 20px 0 0px; + } + + &-title { + font-size: $fontSize; + font-weight: $fontLargeWeight; + color: $defaultColor; + margin: 6px 0 16px; + } + } + } + + &__footer { + width: 95%; + display: none; + } + + .currency-count-table { + .img-empty { + .el-table__empty-block { + background: #fff; + + .el-table__empty-text { + color: #333; + } + } + } + .footer-count { + position: fixed; + bottom: 20px !important; + line-height: 55px; + bottom: 0; + background: $whiteBackground; + z-index: 9; + margin-bottom: 10px; + left: 0; + } + } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/components/InBandMonitoringManagement/AllAlarmRules/pagination/pagination.ts b/bmp-operation-web/src/components/InBandMonitoringManagement/AllAlarmRules/pagination/pagination.ts new file mode 100644 index 0000000..99b6742 --- /dev/null +++ b/bmp-operation-web/src/components/InBandMonitoringManagement/AllAlarmRules/pagination/pagination.ts @@ -0,0 +1,44 @@ +interface DataType { + pageSize: Ref; + pageNumber: Ref; + total: Ref; +}; + +const paginationOperate = (fn: any) => { + const data: DataType = { + pageSize: ref(20), + pageNumber: ref(1), + total: ref(0) + }; + + watch(() => [ + data.pageSize.value, + data.pageNumber.value + ], (_: any[]): void => { + fn(); + }); + + /** + * 分页操作 + * @param {number} count 每页展示条数、页数 + * @param {string} type size、num类型 + */ + const paginationChange = (count: number, type: string) => { + switch (type) { + case 'num': + data.pageNumber.value = count; + break; + case 'size': + data.pageSize.value = count; + data.pageNumber.value = 1; + break; + }; + }; + + return { + ...data, + paginationChange + }; +}; + +export default paginationOperate; diff --git a/bmp-operation-web/src/components/InBandMonitoringManagement/AllAlarmRules/pagination/rulesAlarmHistoryPagination.vue b/bmp-operation-web/src/components/InBandMonitoringManagement/AllAlarmRules/pagination/rulesAlarmHistoryPagination.vue new file mode 100644 index 0000000..6a26271 --- /dev/null +++ b/bmp-operation-web/src/components/InBandMonitoringManagement/AllAlarmRules/pagination/rulesAlarmHistoryPagination.vue @@ -0,0 +1,27 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/LoginOut/LoginOut.vue b/bmp-operation-web/src/components/LoginOut/LoginOut.vue new file mode 100644 index 0000000..d4ae533 --- /dev/null +++ b/bmp-operation-web/src/components/LoginOut/LoginOut.vue @@ -0,0 +1,102 @@ + + + + diff --git a/bmp-operation-web/src/components/LoginOut/loginOut.scss b/bmp-operation-web/src/components/LoginOut/loginOut.scss new file mode 100644 index 0000000..9d7e937 --- /dev/null +++ b/bmp-operation-web/src/components/LoginOut/loginOut.scss @@ -0,0 +1,21 @@ +.login-out { + .el-dialog { + &--center { + width: 526px; + height: 298px; + } + + &__footer { + width: 481px; + } + } + .currency-count { + @extend %display-flex-column; + + .header-title { + @include size-weight-color($fontSize2, $fontLargeWeight, $defaultColor); + margin-top: 80.5px; + @include text-align(center); + } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/components/MessageInfo/DeleteMessage/DeleteMessage.vue b/bmp-operation-web/src/components/MessageInfo/DeleteMessage/DeleteMessage.vue new file mode 100644 index 0000000..29e2d5f --- /dev/null +++ b/bmp-operation-web/src/components/MessageInfo/DeleteMessage/DeleteMessage.vue @@ -0,0 +1,92 @@ + + + + diff --git a/bmp-operation-web/src/components/MessageInfo/DeleteMessage/deleteMessage.scss b/bmp-operation-web/src/components/MessageInfo/DeleteMessage/deleteMessage.scss new file mode 100644 index 0000000..e64581c --- /dev/null +++ b/bmp-operation-web/src/components/MessageInfo/DeleteMessage/deleteMessage.scss @@ -0,0 +1,27 @@ +.delete-message { + .el-dialog { + &--center { + --el-dialog-width: 576px; + height: 298px; + } + + &__body { + padding: 0; + + .delete-message-count { + height: 190px; + @include display-align(center); + @extend %justify-center; + + &-title { + @include size-weight-color($fontSize2, $fontSize2, $defaultColor); + @include text-align(center); + } + } + } + + &__footer { + width: 531px; + } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/components/MessageInfo/MessageSet/EmailPush/EmailPush.vue b/bmp-operation-web/src/components/MessageInfo/MessageSet/EmailPush/EmailPush.vue new file mode 100644 index 0000000..d08f853 --- /dev/null +++ b/bmp-operation-web/src/components/MessageInfo/MessageSet/EmailPush/EmailPush.vue @@ -0,0 +1,110 @@ + + + + diff --git a/bmp-operation-web/src/components/MessageInfo/MessageSet/EmailPush/index.scss b/bmp-operation-web/src/components/MessageInfo/MessageSet/EmailPush/index.scss new file mode 100644 index 0000000..8aead0a --- /dev/null +++ b/bmp-operation-web/src/components/MessageInfo/MessageSet/EmailPush/index.scss @@ -0,0 +1,29 @@ +.email-push-count { + .el-dialog { + &--center { + --el-dialog-width: 530px; + height: 292px; + } + + &__body { + + .currency-count { + display: flex; + flex-direction: column; + + &-title { + font-size: $fontSize2; + font-weight: $fontSmallWeight; + color: $defaultColor; + text-align: center; + margin-top: 80px; + padding-bottom: 131px; + } + } + } + + &__footer { + width: 485px; + } + } +} diff --git a/bmp-operation-web/src/components/ModelOperates/DeleteModel/DeleteModel.vue b/bmp-operation-web/src/components/ModelOperates/DeleteModel/DeleteModel.vue new file mode 100644 index 0000000..eb695a9 --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/DeleteModel/DeleteModel.vue @@ -0,0 +1,109 @@ + + + + diff --git a/bmp-operation-web/src/components/ModelOperates/DeleteModel/deleteModel.scss b/bmp-operation-web/src/components/ModelOperates/DeleteModel/deleteModel.scss new file mode 100644 index 0000000..39bf4b1 --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/DeleteModel/deleteModel.scss @@ -0,0 +1,62 @@ +@import 'assets/css/deviceOperate.scss'; + +.delete-model { + .el-dialog { + &--center { + --el-dialog-width: 526px; + // height: 298px; + padding-bottom: 65px; + } + + &__body { + padding: 0; + + .delete-model-count { + // @extend %display-flex-align; + @include display-align(center); + @extend %justify-center; + margin-top: 20px; + @extend %display-flex-column; + + &-tip { + width: 480px; + // height: 52px; + text-align: center; + border-radius: 2px; + background: rgb(249, 237, 239); + @include display-align(flex-start); + // @extend %display-flex-start; + // margin-bottom: 44.5px; + padding-bottom: 10px; + + img { + @extend %img-count; + } + + span { + font-size: $fontSize; + color: $defaultColor; + padding-right: 30px; + font-weight: $fontSmallWeight; + margin-top: 8px; + } + } + + &-title { + font-size: $fontSize2; + font-weight: $fontSmallWeight; + color: $defaultColor; + height: 130px; + // @extend %display-flex-align; + @include display-align(center); + @extend %justify-center ; + text-align: center; + } + } + } + + &__footer { + width: 481px; + } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/components/ModelOperates/ImageAdd/ImageAdd.vue b/bmp-operation-web/src/components/ModelOperates/ImageAdd/ImageAdd.vue new file mode 100644 index 0000000..42e8e88 --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/ImageAdd/ImageAdd.vue @@ -0,0 +1,78 @@ + + + + diff --git a/bmp-operation-web/src/components/ModelOperates/ImageAdd/addImage.scss b/bmp-operation-web/src/components/ModelOperates/ImageAdd/addImage.scss new file mode 100644 index 0000000..9395695 --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/ImageAdd/addImage.scss @@ -0,0 +1,91 @@ +@import '@/assets/css/communal'; + +.model-image-add { + .el-dialog { + &--center { + width: 890px; + box-shadow: $boxShadow; + border-radius: 10px; + padding: 0 22.5px; + height: 520px; + margin: auto; + background: $whiteBackground; + } + + &__body { + position: absolute; + min-height: calc(100% - 33px); + left: 50%; + transform: translateX(-50%); + overflow: hidden; + width: 890px; + + .currency-count { + display: flex; + flex-direction: column; + height: calc(91%); + position: absolute; + margin: 0; + overflow: hidden; + // overflow: auto; + width: 845px; + z-index: 1; + padding: 0 22.5px; + + &-table { + .el-table { + margin-bottom: 100px; + } + } + + .check-all { + position: absolute; + left: 10px; + top: 6px; + } + + &-name-title { + font-size: $fontSize; + font-weight: $fontLargeWeight; + color: $defaultColor; + margin: 20px 0 0px; + } + + &-title { + font-size: $fontSize; + font-weight: $fontLargeWeight; + color: $defaultColor; + margin: 6px 0 16px; + } + + } + } + + &__footer { + width: 95%; + } + + .currency-count-table { + .img-empty { + .el-table__empty-block { + background: #fff; + + .el-table__empty-text { + color: #333; + } + } + } + + .footer-count { + position: fixed; + bottom: 70px !important; + line-height: 55px; + bottom: 0; + background: $whiteBackground; + z-index: 9; + margin-bottom: 10px; + left: 0; + } + } + } +} diff --git a/bmp-operation-web/src/components/ModelOperates/ImageAdd/all.ts b/bmp-operation-web/src/components/ModelOperates/ImageAdd/all.ts new file mode 100644 index 0000000..874962c --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/ImageAdd/all.ts @@ -0,0 +1,13 @@ +import paginationOperate from './pagination/pagination'; +import resetOperate from './resetOperate/reset'; +import ImageList from './table/imageList'; +import FilterOperate from './table/tableFilter'; +import addImageOperate from './table/addImage'; + +export { + ImageList, + resetOperate, + FilterOperate, + addImageOperate, + paginationOperate +}; diff --git a/bmp-operation-web/src/components/ModelOperates/ImageAdd/modelName/ModelImageAddName.vue b/bmp-operation-web/src/components/ModelOperates/ImageAdd/modelName/ModelImageAddName.vue new file mode 100644 index 0000000..a0b7261 --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/ImageAdd/modelName/ModelImageAddName.vue @@ -0,0 +1,31 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/ModelOperates/ImageAdd/pagination/ModelImageAddPagination.vue b/bmp-operation-web/src/components/ModelOperates/ImageAdd/pagination/ModelImageAddPagination.vue new file mode 100644 index 0000000..1d6a764 --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/ImageAdd/pagination/ModelImageAddPagination.vue @@ -0,0 +1,33 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/ModelOperates/ImageAdd/pagination/pagination.ts b/bmp-operation-web/src/components/ModelOperates/ImageAdd/pagination/pagination.ts new file mode 100644 index 0000000..99b6742 --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/ImageAdd/pagination/pagination.ts @@ -0,0 +1,44 @@ +interface DataType { + pageSize: Ref; + pageNumber: Ref; + total: Ref; +}; + +const paginationOperate = (fn: any) => { + const data: DataType = { + pageSize: ref(20), + pageNumber: ref(1), + total: ref(0) + }; + + watch(() => [ + data.pageSize.value, + data.pageNumber.value + ], (_: any[]): void => { + fn(); + }); + + /** + * 分页操作 + * @param {number} count 每页展示条数、页数 + * @param {string} type size、num类型 + */ + const paginationChange = (count: number, type: string) => { + switch (type) { + case 'num': + data.pageNumber.value = count; + break; + case 'size': + data.pageSize.value = count; + data.pageNumber.value = 1; + break; + }; + }; + + return { + ...data, + paginationChange + }; +}; + +export default paginationOperate; diff --git a/bmp-operation-web/src/components/ModelOperates/ImageAdd/resetOperate/ModelImageAddReset.vue b/bmp-operation-web/src/components/ModelOperates/ImageAdd/resetOperate/ModelImageAddReset.vue new file mode 100644 index 0000000..119e8cb --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/ImageAdd/resetOperate/ModelImageAddReset.vue @@ -0,0 +1,31 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/ModelOperates/ImageAdd/resetOperate/reset.ts b/bmp-operation-web/src/components/ModelOperates/ImageAdd/resetOperate/reset.ts new file mode 100644 index 0000000..3ed748b --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/ImageAdd/resetOperate/reset.ts @@ -0,0 +1,14 @@ +const resetOperate = (imageList: any, filterOperate: any) => { + + const reset = () => { + imageList.tableRef?.value?.clearFilter(); + filterOperate.reactiveArr.filterParams = {source: '', osType: ''}; + imageList.init(); + }; + + return { + reset + } +}; + +export default resetOperate; diff --git a/bmp-operation-web/src/components/ModelOperates/ImageAdd/table/ModelImageListTable.vue b/bmp-operation-web/src/components/ModelOperates/ImageAdd/table/ModelImageListTable.vue new file mode 100644 index 0000000..3a61332 --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/ImageAdd/table/ModelImageListTable.vue @@ -0,0 +1,199 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/ModelOperates/ImageAdd/table/addImage.ts b/bmp-operation-web/src/components/ModelOperates/ImageAdd/table/addImage.ts new file mode 100644 index 0000000..4894355 --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/ImageAdd/table/addImage.ts @@ -0,0 +1,57 @@ +import {msgTip} from 'utils/index.ts'; +import {addImageAPI} from 'api/model/request.ts'; +import {language} from 'utils/publicClass.ts'; + +const addImageOperate = (imageList: any, props: any, emitValue: any) => { + // loading加载态 + const isLoading: Ref = ref(false); + + // 确定按钮弹窗 + const determineClick = (): void => { + isLoading.value = true; + requestAddImage(); + }; + + /** + * 请求镜像验证接口,成功后把事件回传,关闭弹窗 + */ + const requestAddImage = (): void => { + const paramsData = imageList.reactiveArr.arr.filter((item: {isBind: boolean;}) => !item.isBind); + addImageAPI( + { + deviceTypeId: props.deviceTypeId, + imageIds: paramsData.map((item: {imageId: string;}) => item.imageId).join(',') + } + ) + .then(({data} : {data: {result: {success: boolean;}}}) => { + if (data?.result?.success) { + msgTip.success(language.t('operate.success')); + emitValue('determine-click'); + cancelClick(); + } + }) + .finally(() => { + isLoading.value = false; + }) + .catch(() => { + emitValue('determine-click'); + cancelClick(); + }) + }; + + /** + * 取消按钮点击操作 + */ + const cancelClick = (): void => { + // 回传父组件当前页码,可以处理相关操作 + emitValue('dia-log-close', false); + }; + + return { + isLoading, + cancelClick, + determineClick + }; +}; + +export default addImageOperate; diff --git a/bmp-operation-web/src/components/ModelOperates/ImageAdd/table/filterStyle.ts b/bmp-operation-web/src/components/ModelOperates/ImageAdd/table/filterStyle.ts new file mode 100644 index 0000000..e01f042 --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/ImageAdd/table/filterStyle.ts @@ -0,0 +1,130 @@ +class FilterStyleOperate { + classNameData = [ + { + name: 'def-type-status3', + // name: 'def-sources-status', + type: 'sources' + }, + { + name: 'def-type-status4', + // name: 'def-os-types-status', + type: 'osTypes' + } + ]; + filterStatus: any = reactive({ + source: false, + osType: false + }) + + constructor (props: any) { + onMounted(() => { + nextTick(() => { + this.customFilter(props); + }) + this.watchSearchTip(props); + this.watchFilter(props); + }) + }; + + watchSearchTip = (props: any) => { + watch(() => + props.imageList.searchTip, (newValue) => { + if (!newValue.value) { + for (let index in this.filterStatus) { + this.filterStatus[index] = false; + } + } + else { + this.setFilterStatus(props.filterOperate.reactiveArr.filterParams); + } + }, { + deep: true + }); + }; + + watchFilter = (props: any) => { + watch(() => props.filterOperate.reactiveArr.filterParams, (newValue) => { + this.setFilterStatus(newValue); + }, {deep: true}) + }; + + setFilterStatus = (params: any) => { + this.classNameData.forEach((item) => { + if (['', undefined].includes(params[item.type])) { + this.filterStatus[item.type] = false; + return; + } + this.filterStatus[item.type] = true; + }) + }; + + customFilter = (props: any) => { + let filterName: HTMLElement | null; + let filterOpt: HTMLElement | null; + this.classNameData.forEach((item) => { + filterName = document.querySelector(`.${item.name} > .cell`); + filterOpt = document.querySelector(`.${item.name} > .cell > .el-table__column-filter-trigger`) + filterName?.addEventListener('click', () => { + // this.filterStatus[item.type] = false; + for (let index in this.filterStatus) { + this.filterStatus[index] = false; + } + }) + filterOpt?.addEventListener('click', () => { + if (!props.imageList.searchTip.value) { + const clickStatus: any = { + 'sources': () => this.filterStatus['osTypes'] = false, + 'osTypes': () => this.filterStatus['sources'] = false + }; + clickStatus[item.type](); + } + this.filterStatus[item.type] = !this.filterStatus[item.type]; + }); + const filterOtherRegion = document.querySelectorAll('.el-table-filter'); + filterOtherRegion.forEach((_, index) => { + filterOtherRegion[index]?.addEventListener('click', (event) => { + event.stopPropagation(); + for (let index in this.filterStatus) { + for (const key of this.classNameData) { + if (key.type === index && props.filterOperate?.reactiveArr?.filterParams[key.type]?.length) { + this.filterStatus[index] = true; + } + } + } + }) + }) + let newType = []; + document.addEventListener('click', () => { + newType = []; + newType.push(item.type); + newType.forEach((ite) => { + this.filterDispose(ite, props); + }) + }) + }) + }; + + filterDispose = (type: string, props: any) => { + const filterVal = props.filterOperate.reactiveArr.filterParams; + if (props.imageList.searchTip.value) { + for (let key in filterVal) { + if (key === type) { + this.filterStatus[key] = true; + } + else { + if (this.filterStatus[type] && Object.keys(filterVal).length > 1) { + this.filterStatus[type] = !this.filterStatus[type]; + } + else { + this.filterStatus[type] = false; + } + } + } + } + else { + this.filterStatus[type] = false; + } + } +}; + +export default FilterStyleOperate; diff --git a/bmp-operation-web/src/components/ModelOperates/ImageAdd/table/imageList.ts b/bmp-operation-web/src/components/ModelOperates/ImageAdd/table/imageList.ts new file mode 100644 index 0000000..7476130 --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/ImageAdd/table/imageList.ts @@ -0,0 +1,205 @@ +import {languageSwitch} from 'utils/index.ts'; +import {ParamsType} from '../typeManagement'; // ts类 +// import publicIndexStore from 'store/index.ts'; // 公共store +import store from 'store/index.ts'; +import {CurrencyType} from '@utils/publicType'; +import ModelStaticData from 'staticData/model/index.ts'; + +class ImageList { + // ui库-语言 + locale = languageSwitch(); + imagesInfo = store.imagesInfo; + filterEmptyInfo = store.filterEmpty; + systemPartitionInfo = store.sysPartitionInfo; + searchTip: Ref = ref(false); + // table-loading加载态 + tableLoading: Ref = ref(true); + reactiveArr: any = reactive({ + selection: [], + tableData: [], + idList: [], + arr: [] + }); + filter: any = {}; + // 表单ref + tableRef: Ref = ref(); + btnDisabled: Ref = ref(0); + customPagination: any; + props: any; + + constructor (customPagination: any, props: any) { + this.customPagination = customPagination; + this.props = props; + this.init(); + watch(() => this.reactiveArr.arr, (newValue) => { + this.btnDisabled.value = newValue.filter((item: {hasCheckbox: boolean;}) => !item.hasCheckbox).length + }, {deep: true}) + }; + + /** + * 获取表格ref + * @param {Object} tableEl 表格信息 + */ + getTableRef = async (tableEl: any): Promise => { + await nextTick(() => { + this.tableRef = tableEl; + }) + }; + + init = (): void => { + this.tableLoading.value = true; + this.processingParameters(this.filter); + }; + + setFilterData = (filter: any) => { + this.filter = filter; + this.init(); + }; + + processingParameters = (filter: any) => { + const params: ParamsType = { + pageNumber: this.customPagination.pageNumber.value, + pageSize: this.customPagination.pageSize.value, + deviceTypeId: this.props.deviceTypeId, + architecture: this.props.architecture, + ...filter.filterParams + }; + this.filterEmptyInfo.deleteEmtpyData(params); + this.getImageList(params); + }; + + // checkAll = (event: Event) => { + // const filterData = this.reactiveArr.tableData.filter((item: {hasCheckbox: boolean}) => !item.hasCheckbox); + // filterData.map(item => { + // // toggleRowSelection接收两个参数,第一个是被勾选的数据,第二个是选中状态(注:需要注册 ref 来引用) + // if (event) { + // for(let i = 0; i < filterData.length; i++) { + // // 未添加的才插入,否则数据会冗余 + // if (!this.reactiveArr.arr.some((s: {imageId: string;}) => s.imageId === filterData[i].imageId)) { + // this.reactiveArr.arr.push(filterData[i]); + // } + // } + // } + // else { + // for (let i = 0; i< this.reactiveArr.tableData.length; i++) { + // for (let j = 0; j< this.reactiveArr.idList.length; j++){ + // // 移除当前页idList的数据 + // if (this.reactiveArr.idList[j].imageId === this.reactiveArr.tableData[i].imageId) { + // this.reactiveArr.idList.splice(j, 1); + // } + // } + // for(let k = 0; k < this.reactiveArr.arr.length; k++){ + // // 移除当前页idList的数据 + // if (this.reactiveArr.arr[k].imageId === this.reactiveArr.tableData[i].imageId) { + // this.reactiveArr.arr.splice(k, 1); + // } + // } + // } + // } + // this.tableRef?.value.toggleRowSelection(item, event); + // }); + // }; + rowClick = (row: any, _: any, event: any) => { + this.tableRef?.value.toggleRowSelection(row, event); + this.selectChange(this.reactiveArr.selection, row); + }; + + getImageList = (params: ParamsType) => { + this.imagesInfo.getImage(params, this.reactiveArr).then((result: {images: CurrencyType[], totalCount: number;}) => { + const {images, totalCount} : {images: CurrencyType[], totalCount: number} = result; + this.reactiveArr.tableData = images.map((item, index: number) => { + item.hasCheckbox = this.reactiveArr?.arr?.filter((ite: {imageId: string;}) => ite.imageId === item.imageId)[0]??false; + ModelStaticData.modelDetailTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }) + const systemPartition = JSON.parse((item?.systemPartition?.length ? item?.systemPartition : '[]')); + return { + ...item, + newSystemPartition: systemPartition + } + }); + this.customPagination.total.value = totalCount; + nextTick(() => { + for (const key of this.reactiveArr.tableData) { + this.tableRef?.value?.toggleRowSelection(key, key.hasCheckbox); + } + }); + }) + .catch(() => { + this.reactiveArr.tableData = []; + this.customPagination.total.value = 0; + }) + .finally(() => { + const params = this.filter; + const val = params?.filterParams && Object.values(params?.filterParams).some((item) => item !== ''); + this.searchTip.value = val; + this.tableLoading.value = false; + }); + }; + + // 多选框回显 + getRowKeys = (row: {imageId: string;}) => { + if (row.imageId) return row.imageId; + }; + + /** + * 单选 + */ + selectChange = (rows: CurrencyType[], row: CurrencyType) => { + const newRows: boolean | number = rows.filter((item: any) => !item.hasCheckbox).length && rows.indexOf(row) !== -1; + if (newRows) { + this.reactiveArr.arr.push(row); + } + else { + for(let i = 0; i < this.reactiveArr.idList.length; i++) { + if(this.reactiveArr.idList[i].imageId === row.imageId){ + this.reactiveArr.idList.splice(i,1); + } + } + for(let i = 0; i < this.reactiveArr.arr.length; i++){ + if(this.reactiveArr.arr[i].imageId === row.imageId){ + this.reactiveArr.arr.splice(i,1); + } + } + } + }; + + /** + * 当选择项发生变化时会触发该事件 + */ + handleSelectionChange = (val: CurrencyType[]) => { + this.reactiveArr.selection = val.filter((item) => !item.hasCheckbox); + // this.selectChange(this.reactiveArr.selection, this.test); + + }; + + selectAllChange = (rows: CurrencyType[]) => { + const newRows = rows.filter((item) => !item.hasCheckbox); + if (newRows.length > 0) { // 全选 + for(let i = 0; i < newRows.length; i++) { + // 未添加的才插入,否则数据会冗余 + if (!this.reactiveArr.arr.some((s: {imageId: string;}) => s.imageId === newRows[i].imageId)) { + this.reactiveArr.arr.push(newRows[i]); + } + } + } + else { // 取消全选 + for (let i = 0; i < this.reactiveArr.tableData.length; i++) { + for (let j = 0; j< this.reactiveArr.idList.length; j++){ + // 移除当前页idList的数据 + if (this.reactiveArr.idList[j].imageId === this.reactiveArr.tableData[i].imageId) { + this.reactiveArr.idList.splice(j, 1); + } + } + for(let k = 0; k < this.reactiveArr.arr.length; k++){ + // 移除当前页idList的数据 + if (this.reactiveArr.arr[k].imageId === this.reactiveArr.tableData[i].imageId) { + this.reactiveArr.arr.splice(k, 1); + } + } + } + } + }; +}; + +export default ImageList; diff --git a/bmp-operation-web/src/components/ModelOperates/ImageAdd/table/tableFilter.ts b/bmp-operation-web/src/components/ModelOperates/ImageAdd/table/tableFilter.ts new file mode 100644 index 0000000..168fa0f --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/ImageAdd/table/tableFilter.ts @@ -0,0 +1,67 @@ +import store from 'store/index.ts'; + +class FilterOperate { + filterEmptyInfo = store.filterEmpty; + reactiveArr: any = reactive({ + filterParams: { + source: '', + osType: '' + } + }); + ossStore: { + getOssData(): void; + osType: any; + source: any; + } = store.ossDataInfo(); + pagination: any; + imageList: any; + + constructor (pagination: any, imageList: any) { + this.pagination = pagination; + this.imageList = imageList; + this.ossStore?.getOssData(); + }; + + /** + * 筛选事件 + */ + filterOsType = (): boolean => { + // value: number, row: {osType: {[x: string]: string}} + // return row.osType === this.ossStore?.osType[value - 1]?.text; + return true; + }; + + /** + * 镜像类型筛选 + * @param {number} value 当前选中的value值 + * @param {Object} row 当前点击的这一项 + * @param {string} sourceName sourceName + * @return {string} row.sourceName 赋值 + */ + imageTypeFilter = (): boolean => { + // value: number, row: {sourceName: string;} + return true; + // return row.sourceName === this.ossStore?.source[value - 1]?.text; + }; + + /** + * 筛选搜索 + */ + filterChange = (filter: {[x: string]: string;}): void => { + const filterParams: {source: string; osType: string;} = { + source: 'source', + osType: 'osType' + }; + this.filterEmptyInfo.filterParams(filter, this.ossStore, this.reactiveArr, filterParams) + .then((res: any) => { + this.reactiveArr.filterParams = res.filterParams; + if (this.pagination.pageNumber.value > 1) { + this.pagination.pageNumber.value = 1; + return; + } + this.imageList.setFilterData(res); + }); + }; +}; + +export default FilterOperate; diff --git a/bmp-operation-web/src/components/ModelOperates/ImageAdd/typeManagement.ts b/bmp-operation-web/src/components/ModelOperates/ImageAdd/typeManagement.ts new file mode 100644 index 0000000..e26512d --- /dev/null +++ b/bmp-operation-web/src/components/ModelOperates/ImageAdd/typeManagement.ts @@ -0,0 +1,14 @@ +/** + * params参数 +*/ +interface ParamsType { + pageSize: number; + pageNumber: number; + deviceTypeId: string; + osType?: string; + architecture?: string; +}; + +export { + ParamsType +}; diff --git a/bmp-operation-web/src/components/NavigationHeader/NavigationHeader.vue b/bmp-operation-web/src/components/NavigationHeader/NavigationHeader.vue new file mode 100644 index 0000000..1e7c49b --- /dev/null +++ b/bmp-operation-web/src/components/NavigationHeader/NavigationHeader.vue @@ -0,0 +1,44 @@ + + + diff --git a/bmp-operation-web/src/components/NavigationHeader/i18nSwitch/i18nSwitch.vue b/bmp-operation-web/src/components/NavigationHeader/i18nSwitch/i18nSwitch.vue new file mode 100644 index 0000000..f27a3a3 --- /dev/null +++ b/bmp-operation-web/src/components/NavigationHeader/i18nSwitch/i18nSwitch.vue @@ -0,0 +1,31 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/NavigationHeader/navigationHeader.scss b/bmp-operation-web/src/components/NavigationHeader/navigationHeader.scss new file mode 100644 index 0000000..8a85b45 --- /dev/null +++ b/bmp-operation-web/src/components/NavigationHeader/navigationHeader.scss @@ -0,0 +1,117 @@ +.operate-header { + height: 57px; + background: $whiteBackground; + box-shadow: 0 0 5px 0 rgba(153, 153, 153, .50); + @include display-align(center); + @include display-justify(space-between); + position: fixed; + width: $percentageWidth; + top: 0; + z-index: 10; + + &-info { + @include display-align(center); + height: $percentageHeight; + margin-left: 34px; + @include set-cursor(pointer); + + &-icon, + &-img { + @include set-width-height(32px); + margin-right: 13px; + } + } + + &-title { + font-size: 18px; + color: $defaultColor; + font-weight: $fontLargeWeight; + } + + &-information { + @include display-align(center); + margin-right: 38px; + + img { + @include set-width-height(16px); + margin-right: 24px; + cursor: pointer; + } + } + + .header-language-change { + @include display-align(center); + @include set-cursor(pointer); + + :deep(span) { + margin-right: 15px; + } + } + + :deep(.header-disabled) { + font-size: $fontSize; + color: $color7; + font-weight: $fontSmallWeight; + + &:hover { + color: $defaultColor; + font-weight: $fontLargeWeight; + } + } + + :deep(.header-optional) { + @extend %def-c-f-style; + font-weight: $fontLargeWeight; + } + + &-login-info { + margin-left: 5px; + @include display-align(center); + padding: 12px 0; + @include set-cursor(pointer); + + :deep(.el-dropdown) { + .el-dropdown--default { + @include display-align(center); + + .route { + transform: rotate(180deg); + } + + .default-route { + transform: rotate(0); + } + + .route, + .default-route { + transition: all .1s; + } + } + } + + :deep(.user-header-img) { + @include set-width-height(36px); + margin-right: 14px; + border-radius: 50%; + } + + :deep(.user-header-name) { + font-size: $fontSize2; + font-weight: $fontSmallWeight; + + span { + &:first-child { + color: $defaultColor; + margin-right: 6px; + } + &:last-child { + color: $color1; + } + } + } + + :deep(.user-header-icon) { + margin-left: 9px; + } + } +} diff --git a/bmp-operation-web/src/components/NavigationHeader/select.ts b/bmp-operation-web/src/components/NavigationHeader/select.ts new file mode 100644 index 0000000..4deb87d --- /dev/null +++ b/bmp-operation-web/src/components/NavigationHeader/select.ts @@ -0,0 +1,118 @@ +/** + * @file + * @author +*/ + +import {useI18n} from 'vue-i18n'; // 国际化 +import {Router, useRouter} from 'vue-router'; +import {locationItem, CurrentInstance} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; + +class NavBarHeader { + email: Ref = ref(''); + router: Router = useRouter(); + locale: Ref = ref(useI18n().locale.value); + // 退出登录弹窗状态 + loginOutDiaLog: Ref = ref(false); + // 登录用户名 + loginUserName: Ref = ref(''); + instanceProxy = new CurrentInstance().proxy; + hasNoRead: Ref = ref(false); + + // 构造器 + constructor () { + this.#setInfo(); + this.watchRouter(); + this.#getHasNoRead(); + }; + + /** + * 监听路由变化 + */ + watchRouter = () => { + + /** + * 监听路由path + * @param {string} newValue 每次更新的路由的值 + */ + watch(() => this.router.currentRoute.value.path, (newValue: string) => { + if (newValue) { + this.#setInfo(); + this.#getHasNoRead(); + } + }, {deep: true}); + }; + + #getHasNoRead = async () => { + const res = await this.instanceProxy.$messageApi.hasUnreadMessageAPI({}); + this.hasNoRead.value = res?.data?.result?.hasUnread; + } + + #setInfo = async () => { + store.userPurviewInfo().promiseUserInfo() + .then((res: {email: string; userName: string;}) => { + if (res?.email?.length) { + this.email.value = res.email; + this.loginUserName.value = res.userName; + return; + } + return Promise.reject(); + }) + .catch(() => { + const email: string = localStorage?.getItem('email')?? ''; + const userName: string = localStorage?.getItem('userName')?? ''; + this.email.value = email ? window.atob(email) : ''; + this.loginUserName.value = userName ? window.atob(userName) : ''; + }) + }; + + /** + * 改变语言类型 + * @param {string} lang 语言类型 + */ + changeLang = (lang: string): void => { + this.locale.value = lang; + // if (lang === locationItem.cookie.get('X-Jdcloud-Language')) return; + // setUserInfoAPI( + // { + // language: this.locale.value + // } + // ) + // .then(({data} : {data: any}) => { + // if (data?.result && Object.keys(data.result)?.length) { + locationItem.cookie.set('X-Jdcloud-Language', this.locale.value); + location.reload(); + }; + + /** + * 退出登录 + * @return {boolean} xxx 返回对应的弹窗状态 + */ + loginOut = (): boolean => { + return this.loginOutDiaLog.value = !this.loginOutDiaLog.value; + }; + + /** + * 退出登录取消操作 + * @param {boolean} type 弹窗状态 + * @return {boolean} xxx 返回对应的弹窗状态 + */ + loginOutCancel = (type: boolean): boolean => { + return this.loginOutDiaLog.value = type; + }; + + userClick = (type: string) => { + this.router.push(this.instanceProxy!.$defInfo.routerPath(type)); + }; + + messageListClick = () => { + this.router.push(this.instanceProxy!.$defInfo.routerPath('myMessage')); + } + + jumpDefaultList = () => { + const path: string = this.instanceProxy!.$defInfo.routerPath('idcList'); + this.router.push(path); + }; +}; + +export default NavBarHeader; diff --git a/bmp-operation-web/src/components/NavigationHeader/selectOperate/selectOperate.scss b/bmp-operation-web/src/components/NavigationHeader/selectOperate/selectOperate.scss new file mode 100644 index 0000000..9d4f861 --- /dev/null +++ b/bmp-operation-web/src/components/NavigationHeader/selectOperate/selectOperate.scss @@ -0,0 +1,70 @@ +/* 右侧下拉样式 */ +.user { + + .line { + border-top: 1px solid $border18; + } + + &-img { + @include set-width-height(40px); + margin: 8px auto 0; + @include set-cursor(text); + } + + &-count { + @extend %display-flex-column; + @include display-align(center); + width: 175px; + + &:hover { + background: $transparent !important; + } + } + + &-name { + margin-bottom: -2px !important; + } + + &-email, + &-name { + @extend %def-c-f-style; + font-weight: $fontSmallWeight; + margin: 0px 0 4px; + @include text-align(center); + @include set-cursor(text); + width: 155px; + @extend %white-flw-over; + } + + + &-center { + @extend %def-c-f-style; + min-height: 38px; + @include display-align(center); + width: 175px; + @extend %justify-center; + + &:hover { + background: $background3; + color: $color1; + } + } + + .login-out { + width: 175px; + font-size: $fontSize; + min-height: 38px; + @include display-align(center); + @extend %justify-center; + font-weight: $fontLargeWeight; + border-bottom-left-radius: 5px; + border-bottom-right-radius: 5px; + background: $background1; + color: $color3; + + &:active { + background: $background2; + color: $color3; + } + } +} diff --git a/bmp-operation-web/src/components/NavigationHeader/selectOperate/selectOperate.vue b/bmp-operation-web/src/components/NavigationHeader/selectOperate/selectOperate.vue new file mode 100644 index 0000000..3da8955 --- /dev/null +++ b/bmp-operation-web/src/components/NavigationHeader/selectOperate/selectOperate.vue @@ -0,0 +1,129 @@ + + + diff --git a/bmp-operation-web/src/components/Public/BtnOperate/BtnOperate.vue b/bmp-operation-web/src/components/Public/BtnOperate/BtnOperate.vue new file mode 100644 index 0000000..c7ecb9e --- /dev/null +++ b/bmp-operation-web/src/components/Public/BtnOperate/BtnOperate.vue @@ -0,0 +1,55 @@ + + + + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/Public/CustomFilter/CustomFilter.vue b/bmp-operation-web/src/components/Public/CustomFilter/CustomFilter.vue new file mode 100644 index 0000000..1dd217c --- /dev/null +++ b/bmp-operation-web/src/components/Public/CustomFilter/CustomFilter.vue @@ -0,0 +1,214 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/Public/CustomFilter/customFilter.ts b/bmp-operation-web/src/components/Public/CustomFilter/customFilter.ts new file mode 100644 index 0000000..e69de29 diff --git a/bmp-operation-web/src/components/Public/CustomFilter/index.scss b/bmp-operation-web/src/components/Public/CustomFilter/index.scss new file mode 100644 index 0000000..4ed731f --- /dev/null +++ b/bmp-operation-web/src/components/Public/CustomFilter/index.scss @@ -0,0 +1,83 @@ +.custom-table-filter-a { + z-index: 10; + position: absolute; + margin: 0; + max-height: 265px; + width: 160px; + + .custom-table-filter-b { + background: $whiteBackground; + border-radius: 5px; + overflow-y: auto; + position: absolute; + box-shadow: $boxShadow; + + .filter-scroll-count { + overflow-y: auto; + max-height: 205px; + } + + .custom-filter-count { + padding: 2px 10px; + cursor: pointer; + + &:hover { + background: $background3; + + .text-tip { + color: $color1; + } + } + } + + .el-input { + background: $whiteBackground; + } + + :deep(.el-input__inner) { + border-radius: 0; + border-top: 0; + border-right: 0; + border-left: 0; + } + + .custom-footer-btn { + position: sticky; + bottom: 0; + background: $whiteBackground; + z-index: 10; + border-top: .5px solid #C4C4C4; + height: 27px; + display: flex; + align-items: center; + justify-content: space-around; + + span { + font-size: 12px; + + &:last-child { + cursor: pointer; + + &:hover { + color: $color1; + } + } + } + + .disabled-select { + color: #999; + opacity: .99; + cursor: no-drop; + } + + .select-opt { + color: #333; + cursor: pointer; + + &:hover { + color: #108ee9; + } + } + } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/components/Public/CustomList/CustomList.vue b/bmp-operation-web/src/components/Public/CustomList/CustomList.vue new file mode 100644 index 0000000..bf31ffa --- /dev/null +++ b/bmp-operation-web/src/components/Public/CustomList/CustomList.vue @@ -0,0 +1,181 @@ + + + + diff --git a/bmp-operation-web/src/components/Public/CustomList/customList.scss b/bmp-operation-web/src/components/Public/CustomList/customList.scss new file mode 100644 index 0000000..6d1010b --- /dev/null +++ b/bmp-operation-web/src/components/Public/CustomList/customList.scss @@ -0,0 +1,30 @@ +@import '@/assets/css/communal'; + +.custom-list { + .el-dialog { + &--center { + --el-dialog-width: 446px; + } + + &__footer { + width: 401px; + } + } + + &-count { + padding-bottom: 89px; + + &-title { + font-size: $fontSize; + color: $defaultColor; + font-weight: $fontLargeWeight; + margin: 19.5px 0 16px; + } + } + + .unify-checkbox { + display: flex; + flex-wrap: wrap; + // width: $percentageWidth; + } +} diff --git a/bmp-operation-web/src/components/Public/CustomList/type.ts b/bmp-operation-web/src/components/Public/CustomList/type.ts new file mode 100644 index 0000000..f4c4442 --- /dev/null +++ b/bmp-operation-web/src/components/Public/CustomList/type.ts @@ -0,0 +1,15 @@ +import {PublicType6, CurrencyStatusType, CurrencyStatusType2} from '@utils/publicType'; + +// 需要显示的列表信息类 +type CheckListArrType = Partial & Required & Required<{showTooltip: boolean;}>; + +// 自定义信息类 +type HasCustomInfoType = {[x: number]: CurrencyStatusType}; + +type ParamsType = {pageKey?: string; pageValue: HasCustomInfoType}; + +export { + ParamsType, + CheckListArrType, + HasCustomInfoType +}; diff --git a/bmp-operation-web/src/components/Public/DetailHeader/DetailHeader.vue b/bmp-operation-web/src/components/Public/DetailHeader/DetailHeader.vue new file mode 100644 index 0000000..fe6f7be --- /dev/null +++ b/bmp-operation-web/src/components/Public/DetailHeader/DetailHeader.vue @@ -0,0 +1,86 @@ + + + + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/Public/DetailHeader/detailHeader.scss b/bmp-operation-web/src/components/Public/DetailHeader/detailHeader.scss new file mode 100644 index 0000000..00f342e --- /dev/null +++ b/bmp-operation-web/src/components/Public/DetailHeader/detailHeader.scss @@ -0,0 +1,168 @@ +$height: 28px; +.operate-management-detail { + overflow-x: auto; + overflow-y: auto; + + &-header { + @extend %header-info; + + &-count { + @include display-align(center); + @include display-justify(space-between); + width: $percentageWidth; + } + + &-left { + // @extend %display-flex-align; + @include display-align(center); + + .detail-arrow-left { + // @extend %display-flex-align; + @include display-align(center); + height: 40px; + @include set-cursor(pointer); + + &:hover .header-arrow-left, + .header-arrow-left { + margin: 0 15px 0 29px; + // @extend %width-height; + @include set-width-height(16px); + background-size: 100% auto !important; + } + + &:hover { + .header-arrow-left { + background: url('~@/assets/img/uiImg/hover-arrow-left.png') no-repeat center center; + } + } + + .header-arrow-left { + background: url('~@/assets/img/uiImg/arrow-left.png') no-repeat center center; + } + } + + .header-list-title { + font-size: $fontSize2; + color: $defaultColor; + line-height: 20px; + font-weight: $fontLargeWeight; + } + + .header-left-icon { + margin: 0 17px 0 $fontSize2; + } + + .header-title { + font-size: $fontSize2; + color: $defaultColor; + font-weight: $fontLargeWeight; + } + + .header-status { + margin-left: 42px; + font-size: $fontSize2; + } + } + + .hover-select { + border-color: $color1 !important; + } + + .hover-select, + .header-select { + margin-right: 30px; + padding: 0 1px; + height: 26px; + border: 1px solid $color6; + border-radius: $borderRadius; + + .input-select-count { + width: $percentageWidth; + height: $percentageHeight; + @include display-align(center); + + .select-trigger { + height: $height; + display: flex; + } + + input { + border: 0; + width: $percentageWidth; + height: $percentageHeight; + font-size: $fontSize; + border-radius: $borderRadius; + font-weight: $fontSmallWeight; + color: $color1; + padding-right: 0; + padding-left: 17px; + } + + .el-input__icon { + color: $color5; + font-size: $fontSize; + } + } + .el-dropdown--default { + .drop-down-operate { + @include set-cursor(pointer); + position: relative; + font-size: $fontSize; + @include display-align(center); + + &-count { + @include display-align(center); + @extend %justify-center; + height: 26px; + + span { + padding: 8px 1px 8px 14px; + margin-right: 5px; + @extend %white-flw-over; + } + + .arrow-bottom-img { + @include set-width-height(16px); + background: url('~@/assets/img/uiImg/arrow-bottom.png') no-repeat center center; + background-size: backgoundSize(auto); + // 100% auto; + margin-right: 7px; + } + + .arrow-img { + // @extend %width-height; + @include set-width-height(16px); + background: url('~@/assets/img/uiImg/bottom.png') no-repeat center center; + background-size: backgoundSize(auto); + // 100% auto; + margin-right: 7px; + } + } + } + } + + &:hover { + border-color: $color1; + .el-dropdown--default { + .drop-down-operate { + &-count { + + span { + color: $color1 !important; + } + + .arrow-bottom-img { + // @extend %width-height; + @include set-width-height(16px); + background: url('~@/assets/img/uiImg/bottom.png') no-repeat center center; + background-size: backgoundSize(auto); + // 100% auto; + margin-right: 7px; + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/components/Public/Export/Export.vue b/bmp-operation-web/src/components/Public/Export/Export.vue new file mode 100644 index 0000000..af80a4d --- /dev/null +++ b/bmp-operation-web/src/components/Public/Export/Export.vue @@ -0,0 +1,138 @@ + + + + diff --git a/bmp-operation-web/src/components/Public/Export/export.scss b/bmp-operation-web/src/components/Public/Export/export.scss new file mode 100644 index 0000000..60171a9 --- /dev/null +++ b/bmp-operation-web/src/components/Public/Export/export.scss @@ -0,0 +1,54 @@ +.export-data { + .el-dialog { + &--center { + --el-dialog-width: 446px; + height: 252px; + } + + &__body { + height: calc(100% - 116px); + } + + &__footer { + width: 401px; + } + } + + .export-content, + .radio-style1 { + @extend %display-flex-column; + height: 100%; + position: relative; + + .export-flex { + display: flex; + } + + .el-progress { + width: 100%; + position: absolute; + bottom: 15px; + } + + .export-scope { + margin-top: 19.5px; + margin-right: 23px; + @include size-weight-color($fontSize, $fontLargeWeight, $defaultColor); + } + + .el-radio { + height: 16px; + margin-bottom: 16px; + + &:last-child { + margin-right: 30px; + } + + &-group { + @extend %display-flex-column; + margin-top: 19.5px; + @include display-align(flex-start); + } + } + } +} diff --git a/bmp-operation-web/src/components/Public/HeaderInfo/HeaderInfo.vue b/bmp-operation-web/src/components/Public/HeaderInfo/HeaderInfo.vue new file mode 100644 index 0000000..d7b049a --- /dev/null +++ b/bmp-operation-web/src/components/Public/HeaderInfo/HeaderInfo.vue @@ -0,0 +1,79 @@ + + + + + diff --git a/bmp-operation-web/src/components/Public/HeaderInfo/headerInfo.scss b/bmp-operation-web/src/components/Public/HeaderInfo/headerInfo.scss new file mode 100644 index 0000000..19b0da0 --- /dev/null +++ b/bmp-operation-web/src/components/Public/HeaderInfo/headerInfo.scss @@ -0,0 +1,14 @@ +.header-count { + @extend %header-info; + + &-img { + margin: 0 15px 0 33px; + @include set-width-height(16px); + } + + &-title { + font-size: $fontSize2; + color: $defaultColor; + font-weight: 600; + } +} diff --git a/bmp-operation-web/src/components/Public/NoDataTip/NoDataTip.vue b/bmp-operation-web/src/components/Public/NoDataTip/NoDataTip.vue new file mode 100644 index 0000000..d91329a --- /dev/null +++ b/bmp-operation-web/src/components/Public/NoDataTip/NoDataTip.vue @@ -0,0 +1,58 @@ + + + + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/Public/RefreshCustomExport/RefreshCustomExport.vue b/bmp-operation-web/src/components/Public/RefreshCustomExport/RefreshCustomExport.vue new file mode 100644 index 0000000..8dbd5e9 --- /dev/null +++ b/bmp-operation-web/src/components/Public/RefreshCustomExport/RefreshCustomExport.vue @@ -0,0 +1,122 @@ + + + + + diff --git a/bmp-operation-web/src/components/Public/RefreshCustomExport/index.scss b/bmp-operation-web/src/components/Public/RefreshCustomExport/index.scss new file mode 100644 index 0000000..9410147 --- /dev/null +++ b/bmp-operation-web/src/components/Public/RefreshCustomExport/index.scss @@ -0,0 +1,67 @@ +%operate { + @include display-align(center); + margin-right: 20px; +} + +%operate-img { + @include set-width-height(16px); + background-size: backgoundSize(auto) !important; + @include position-repeat(0); + margin-right: 5px; +} + +@mixin set-background-img($key) { + @if $key == 0 { + background-image: url('~@/assets/img/listImg/default-refresh.png'); + } + @else if $key == 1 { + background-image: url('~@/assets/img/listImg/default-set-up.png'); + } + @else { + background-image: url('~@/assets/img/listImg/default-export.png'); + } +} + +@mixin background-img-hover($key) { + @if $key == 0 { + &:hover { + .default-img-style { + background-image: url('~@/assets/img/listImg/refresh.png'); + } + } + } + @else if $key == 1 { + &:hover { + .default-img-style { + background-image: url('~@/assets/img/listImg/set-up.png'); + } + } + } + @else { + &:hover { + .default-img-style { + background-image: url('~@/assets/img/listImg/export.png'); + } + } + } +} + +%public-operate-style { + .default-img-style { + @extend %operate-img; + } + + .default-text-size { + font-size: $fontSize; + } +} + +@mixin operate-count($key) { + @extend %operate; + @extend %public-operate-style; + + .default-img-style { + @include set-background-img($key); + } + @include background-img-hover($key); +} \ No newline at end of file diff --git a/bmp-operation-web/src/components/Public/RefreshCustomExport/refreshCustomExport.scss b/bmp-operation-web/src/components/Public/RefreshCustomExport/refreshCustomExport.scss new file mode 100644 index 0000000..0134a10 --- /dev/null +++ b/bmp-operation-web/src/components/Public/RefreshCustomExport/refreshCustomExport.scss @@ -0,0 +1,56 @@ +@import './index.scss'; + +.operate-management { + width: $percentageWidth; + + &-content { + @extend %display-flex-column; + position: relative; + margin-top: 61px; + + &-operate2 { + width: 100%; + + &-right { + @extend %displafy-flex-wrap; + margin-top: 22px; + } + } + + .set-flex-end { + @extend %no-btn-opt; + } + + &-operate2, + &-operate { + padding: 0 30px; + @include display-align(center); + @extend %displafy-flex-wrap; + @include display-justify(space-between); + + &-right { + display: flex; + } + + @for $i from 0 through 2 { + $key: $i; + .list-data-operate#{$key} { + @include set-cursor(pointer); + @include operate-count($key); + + &:hover { + color: $color1; + } + } + } + + @for $i from 0 through 2 { + $key: $i; + .disabled-list-data-operate#{$key} { + @extend %pointer-events; + @include operate-count($key); + } + } + } + } +} diff --git a/bmp-operation-web/src/components/Public/Search/Search.vue b/bmp-operation-web/src/components/Public/Search/Search.vue new file mode 100644 index 0000000..bb631b3 --- /dev/null +++ b/bmp-operation-web/src/components/Public/Search/Search.vue @@ -0,0 +1,54 @@ + + + + + \ No newline at end of file diff --git a/bmp-operation-web/src/components/Public/SecurityVerification/SecurityVerification.vue b/bmp-operation-web/src/components/Public/SecurityVerification/SecurityVerification.vue new file mode 100644 index 0000000..352bf5a --- /dev/null +++ b/bmp-operation-web/src/components/Public/SecurityVerification/SecurityVerification.vue @@ -0,0 +1,198 @@ + + + + diff --git a/bmp-operation-web/src/components/Public/SecurityVerification/securityVerification.scss b/bmp-operation-web/src/components/Public/SecurityVerification/securityVerification.scss new file mode 100644 index 0000000..8d25478 --- /dev/null +++ b/bmp-operation-web/src/components/Public/SecurityVerification/securityVerification.scss @@ -0,0 +1,60 @@ +.security-verification { + + .el-dialog { + &--center { + --el-dialog-width: 526px; + height: 298px; + + .title { + + .common-img { + position: absolute; + left: 17.5px; + object-fit: contain; + } + + span { + margin-left: 27px; + } + } + } + + &__footer { + width: 481px; + } + } + + &-ruleForm { + margin-top: 50.5px; + + .el-form-item__label { + margin-left: 106px; + font-weight: $fontLargeWeight; + + &::before { + display: none; + } + } + + .el-form-item__error { + margin-top: 5px; + } + + .el-form-item__label, + .el-input__inner { + // 不要用全局样式 + --el-form-label-font-size: 12px; + --el-text-color-regular: #333; + } + + input { + width: 204px; + height: 30px; + --el-input-bg-color: transparent; + + &::placeholder { + font-size: $fontSize; + } + } + } +} diff --git a/bmp-operation-web/src/components/Public/SecurityVerification/typeManagement.ts b/bmp-operation-web/src/components/Public/SecurityVerification/typeManagement.ts new file mode 100644 index 0000000..41e6d10 --- /dev/null +++ b/bmp-operation-web/src/components/Public/SecurityVerification/typeManagement.ts @@ -0,0 +1,22 @@ +import {RuleFormRefType, VerifyRulesType} from '@utils/publicType'; + +type RuleFormRefType2 = Omit; + +/** + * 表单输入类型 +*/ +type RuleFormType = {username: string; password: string;}; + +/** + * 规则类型 +*/ +interface RulesType { + username: VerifyRulesType[]; + password: VerifyRulesType[]; +}; + +export { + RulesType, + RuleFormType, + RuleFormRefType2 +}; diff --git a/bmp-operation-web/src/components/Surveillance/FaultLog/FaultHandlingConfirm/FaultHandlingConfirm.vue b/bmp-operation-web/src/components/Surveillance/FaultLog/FaultHandlingConfirm/FaultHandlingConfirm.vue new file mode 100644 index 0000000..b2c03df --- /dev/null +++ b/bmp-operation-web/src/components/Surveillance/FaultLog/FaultHandlingConfirm/FaultHandlingConfirm.vue @@ -0,0 +1,298 @@ + + + + diff --git a/bmp-operation-web/src/components/Surveillance/FaultLog/FaultHandlingConfirm/faultHandlingConfirm.scss b/bmp-operation-web/src/components/Surveillance/FaultLog/FaultHandlingConfirm/faultHandlingConfirm.scss new file mode 100644 index 0000000..cd492bd --- /dev/null +++ b/bmp-operation-web/src/components/Surveillance/FaultLog/FaultHandlingConfirm/faultHandlingConfirm.scss @@ -0,0 +1,91 @@ +@import 'assets/css/deviceOperate.scss'; + +.fault-handling-confirm { + .el-dialog { + &--center { + --el-dialog-width: 786px; + height: 402px; + + .el-table { + &__header-wrapper { + margin-bottom: 5px; + } + + &__row { + background-color: $background3; + + &:hover { + td { + background-color: $background10 !important; + } + } + } + } + } + + &__body { + padding: 0; + } + + &__footer { + width: 741px; + } + } + + &-content { + + // table为空 + .currency-count-table { + .img-empty { + .el-table__body { + padding-bottom: 0 !important; + } + .el-table__empty-block { + background: $whiteBackground; + + .el-table__empty-text { + color: $defaultColor; + } + } + } + } + + .warnning-tip { + @extend %warnning-tip; + // text-align: center; + // border-radius: 2px; + // background: rgb(249, 237, 239); + // display: flex; + // align-items: flex-start; + // justify-content: center; + // margin-top: 15px; + + // img { + // width: 32px; + // height: 32px; + // transform: scale(.5); + // margin-left: 10px; + // margin-top: 1px; + // } + + // span { + // font-size: $fontSize; + // color: $defaultColor; + // padding-right: 30px; + // font-weight: $fontSmallWeight; + // margin-top: 8px; + // } + } + + .tip-title { + @extend %tip-title; + // font-size: $fontSize; + // color: $defaultColor; + // margin: 15px 0; + + // span { + // color: $color1; + // } + } + } +} diff --git a/bmp-operation-web/src/components/Surveillance/FaultRules/DefaultSet/DefaultSet.vue b/bmp-operation-web/src/components/Surveillance/FaultRules/DefaultSet/DefaultSet.vue new file mode 100644 index 0000000..6a381c9 --- /dev/null +++ b/bmp-operation-web/src/components/Surveillance/FaultRules/DefaultSet/DefaultSet.vue @@ -0,0 +1,259 @@ + + + + diff --git a/bmp-operation-web/src/components/Surveillance/FaultRules/DefaultSet/defaultSet.scss b/bmp-operation-web/src/components/Surveillance/FaultRules/DefaultSet/defaultSet.scss new file mode 100644 index 0000000..c906077 --- /dev/null +++ b/bmp-operation-web/src/components/Surveillance/FaultRules/DefaultSet/defaultSet.scss @@ -0,0 +1,103 @@ +@import 'assets/css/deviceOperate.scss'; + +.default-set { + .el-dialog { + &--center { + --el-dialog-width: 676px; + height: 402px; + + .el-table { + &__header-wrapper { + margin-bottom: 5px; + } + + &__row { + background-color: $background3; + &:hover { + td { + background-color: $background10 !important; + } + } + } + } + } + + &__body { + padding: 0; + } + + &__footer { + width: 631px; + } + } + + &-content { + + // table为空 + .currency-count-table { + .img-empty { + .el-table__body { + padding-bottom: 0 !important; + } + .el-table__empty-block { + background: $whiteBackground; + + .el-table__empty-text { + color: $defaultColor; + } + } + } + + .el-table__inner-wrapper tr:first-child th { + &:first-child { + border-left: none; + } + + &:last-child { + border-color: $border16; + } + } + } + + .warnning-tip { + @extend %warnning-tip; + // text-align: center; + // border-radius: 2px; + // background: rgb(249, 237, 239); + // display: flex; + // align-items: flex-start; + // justify-content: center; + // margin-top: 15px; + + // img { + // width: 32px; + // height: 32px; + // transform: scale(.5); + // margin-left: 10px; + // margin-top: 1px; + // } + + // span { + // font-size: $fontSize; + // color: $defaultColor; + // padding-right: 30px; + // font-weight: $fontSmallWeight; + // margin: 8px 0; + // } + span { + margin: 8px; + } + } + + .tip-title { + @extend %tip-title; + // font-size: $fontSize; + // color: $defaultColor; + // margin: 15px 0; + + // span { + // color: $color1; + // } + } + } +} diff --git a/bmp-operation-web/src/components/Surveillance/FaultRules/EnableStatus/EnableStatus.vue b/bmp-operation-web/src/components/Surveillance/FaultRules/EnableStatus/EnableStatus.vue new file mode 100644 index 0000000..3ac93b3 --- /dev/null +++ b/bmp-operation-web/src/components/Surveillance/FaultRules/EnableStatus/EnableStatus.vue @@ -0,0 +1,136 @@ + + + + diff --git a/bmp-operation-web/src/components/Surveillance/FaultRules/EnableStatus/enableStatus.scss b/bmp-operation-web/src/components/Surveillance/FaultRules/EnableStatus/enableStatus.scss new file mode 100644 index 0000000..7d02af8 --- /dev/null +++ b/bmp-operation-web/src/components/Surveillance/FaultRules/EnableStatus/enableStatus.scss @@ -0,0 +1,35 @@ +@import '@/assets/css/communal'; + +.enable-status { + .el-dialog { + &--center { + --el-dialog-width: 526px; + height: 302px; + } + + &__body { + padding: 0; + } + + &__footer { + width: 481px; + } + } + + &-content { + + .tip-title { + font-size: 14px; + color: $defaultColor; + display: flex; + align-items: center; + text-align: center; + justify-content: center; + height: 190px; + + span { + color: $color1; + } + } + } +} diff --git a/bmp-operation-web/src/components/Surveillance/FaultRules/FaultPush/FaultPush.vue b/bmp-operation-web/src/components/Surveillance/FaultRules/FaultPush/FaultPush.vue new file mode 100644 index 0000000..ff80554 --- /dev/null +++ b/bmp-operation-web/src/components/Surveillance/FaultRules/FaultPush/FaultPush.vue @@ -0,0 +1,97 @@ + + + + diff --git a/bmp-operation-web/src/components/Surveillance/FaultRules/FaultPush/faultPush.scss b/bmp-operation-web/src/components/Surveillance/FaultRules/FaultPush/faultPush.scss new file mode 100644 index 0000000..d8e6eb3 --- /dev/null +++ b/bmp-operation-web/src/components/Surveillance/FaultRules/FaultPush/faultPush.scss @@ -0,0 +1,31 @@ +@import '@/assets/css/communal'; + +.fault-push { + .el-dialog { + &--center { + --el-dialog-width: 526px; + height: 302px; + } + + &__body { + padding: 0; + } + + &__footer { + width: 481px; + } + } + + &-content { + + .tip-title { + font-size: 14px; + color: $defaultColor; + display: flex; + align-items: center; + text-align: center; + justify-content: center; + height: 190px; + } + } +} diff --git a/bmp-operation-web/src/components/UserCenter/CreateApiKey/CreateApiKey.vue b/bmp-operation-web/src/components/UserCenter/CreateApiKey/CreateApiKey.vue new file mode 100644 index 0000000..7dcba10 --- /dev/null +++ b/bmp-operation-web/src/components/UserCenter/CreateApiKey/CreateApiKey.vue @@ -0,0 +1,109 @@ + + + + diff --git a/bmp-operation-web/src/components/UserCenter/CreateApiKey/createApiKey.scss b/bmp-operation-web/src/components/UserCenter/CreateApiKey/createApiKey.scss new file mode 100644 index 0000000..55d30ca --- /dev/null +++ b/bmp-operation-web/src/components/UserCenter/CreateApiKey/createApiKey.scss @@ -0,0 +1,68 @@ +@import '@/assets/css/communal'; + +.create-api-key { + .el-dialog { + &--center { + --el-dialog-width: 540px; + height: 292px; + } + + &__footer { + width: 495px; + } + } + + .create-apicontent { + display: flex; + + .create-apiscope { + font-size: $fontSize; + font-weight: $fontLargeWeight; + margin-top: 19.5px; + color: $defaultColor; + + } + + .el-form-item__label { + font-size: $fontSize; + color: $defaultColor; + font-weight: 500; + + &::before { + display: none; + } + } + + .api-key-name { + margin-top: 19.5px; + } + + input { + width: 204px; + height: 30px; + border-radius: 4px; + font-size: $fontSize; + } + + .el-form-item__content { + margin-left: 10px; + } + + .read-only { + margin-bottom: 10px; + } + .name-tip { + font-size: $fontSize; + color: $color7; + } + .error-tip { + color: #f56c6c; + font-size: $fontSize; + } + + .set-error-tip { + line-height: 1.5; + margin-top: 5px; + } + } +} diff --git a/bmp-operation-web/src/components/UserCenter/CreateApiKey/utils/createApiKey.ts b/bmp-operation-web/src/components/UserCenter/CreateApiKey/utils/createApiKey.ts new file mode 100644 index 0000000..e93c3da --- /dev/null +++ b/bmp-operation-web/src/components/UserCenter/CreateApiKey/utils/createApiKey.ts @@ -0,0 +1,139 @@ +import {createApiKeyAPI} from 'api/userCenter/request.ts'; +import {language} from 'utils/publicClass.ts'; +import {msgTip} from 'utils/index.ts'; + +const createApiKey = (formRules: any, emitValue: any) => { + const isLoading: Ref = ref(false); + + onUnmounted(() => { + document.onkeyup = () => {return;} + }); + + document.onkeyup = (event: {keyCode: number;}) => { + event.keyCode === 13 && determineClick(); + }; + + /** + * 请求创建密钥接口,成功后把事件回传,关闭弹窗 + */ + const determineClick = async () => { + isLoading.value = true; + // 判断输入项是否符合条件 + await nextTick(() => { + formRules.ruleFormRef.value!.validate((valid: boolean) => { + // 输入符合条件后才可以继续后续操作 + if (valid) { + createApiKey(); + } + else { + isLoading.value = false; + } + }); + }); + }; + + const createApiKey = () => { + createApiKeyAPI( + { + ...formRules.ruleForm + } + ) + .then(({data} : {data: {result: {apikeyId: string}}}) => { + if (data?.result?.apikeyId?.length) { + msgTip.success(language.t('operate.success')); + cancelClick(); + emitValue('determine-click'); + return; + } + }) + .finally(() => { + isLoading.value = false; + }) + .catch(() => { + cancelClick(); + emitValue('determine-click'); + }); + }; + + /** + * 取消按钮点击操作 + */ + const cancelClick = (): void => { + // 回传父组件当前页码,可以处理相关操作 + emitValue('dia-log-close', false); + }; + + return { + isLoading, + determineClick, + cancelClick + }; +}; + +export default createApiKey; + +/** + * 创建密钥 +*/ +// class CreateApiKey { +// isLoading: Ref = ref(false) + +// constructor () { +// onUnmounted(() => { +// document.onkeyup = () => {return;} +// }) +// document.onkeyup = (event: {keyCode: number;}) => { +// event.keyCode === 13 && this.determineClick(); +// }; +// }; + +// /** +// * 请求创建密钥接口,成功后把事件回传,关闭弹窗 +// */ +// determineClick = async () => { +// this.isLoading.value = true; +// // 判断输入项是否符合条件 +// await nextTick(() => { +// formRulesOperate.ruleFormRef.value!.validate((valid: boolean) => { +// // 输入符合条件后才可以继续后续操作 +// if (valid) { +// this.createApiKey(); +// } +// else { +// this.isLoading.value = false; +// } +// }); +// }); +// }; + +// createApiKey = () => { +// createApiKeyAPI( +// { +// ...formRulesOperate.ruleForm +// } +// ) +// .then(({data} : {data: {result: {apikeyId: string}}}) => { +// if (data?.result?.apikeyId?.length) { +// msgTip.success(language.t('operate.success')); +// this.cancelClick(); +// emitValue('determine-click'); +// return; +// } +// }) +// .finally(() => { +// this.isLoading.value = false; +// }) +// .catch(() => { +// this.cancelClick(); +// emitValue('determine-click'); +// }); +// }; + +// /** +// * 取消按钮点击操作 +// */ +// cancelClick = (): void => { +// // 回传父组件当前页码,可以处理相关操作 +// emitValue('dia-log-close', false); +// }; +// }; \ No newline at end of file diff --git a/bmp-operation-web/src/components/UserCenter/CreateApiKey/utils/formRules.ts b/bmp-operation-web/src/components/UserCenter/CreateApiKey/utils/formRules.ts new file mode 100644 index 0000000..2813bab --- /dev/null +++ b/bmp-operation-web/src/components/UserCenter/CreateApiKey/utils/formRules.ts @@ -0,0 +1,50 @@ +import {RuleFormRefType, CurrencyType5} from '@utils/publicType'; +import {language} from 'utils/publicClass'; + +interface DataType { + ruleFormRef: Ref; + ruleForm: { + name: string; + readOnly: number; + type: string; + }; + reactiveArr: { + readOnlyData: CurrencyType5[]; + }; +}; + +const formRules = () => { + const data: DataType = { + // ref 操作 + ruleFormRef: ref(), + // 表单输入项 + ruleForm: reactive({ + name: '', + readOnly: 0, + type: 'user' + }), + reactiveArr: reactive({ + readOnlyData: [ + { + value: 0, + label: language.t('createKey.select.title') + } + ] + }) + }; + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + const getFormRef = (formEl: {value: RuleFormRefType}): void => { + data.ruleFormRef.value = formEl.value; + }; + + return { + ...data, + getFormRef + }; +}; + +export default formRules; diff --git a/bmp-operation-web/src/components/UserCenter/CreateApiKey/utils/regExp.ts b/bmp-operation-web/src/components/UserCenter/CreateApiKey/utils/regExp.ts new file mode 100644 index 0000000..38312a5 --- /dev/null +++ b/bmp-operation-web/src/components/UserCenter/CreateApiKey/utils/regExp.ts @@ -0,0 +1,92 @@ +import RegularContent from 'utils/regular.ts'; +import {language} from 'utils/publicClass.ts'; +import {VerifyRulesType} from '@utils/publicType'; + +interface DataType { + keyNameTip: Ref; + hasErrorStatus: Ref; + rules: { + name: VerifyRulesType[]; + readOnly: VerifyRulesType[]; + }; +}; + +const regExpCheck = (props: any) => { + const data: DataType = { + keyNameTip: ref(language.t('createKey.errorTip.keyName')), + hasErrorStatus: ref(false), + + rules: reactive({ + name: [ + { + required: true, + trigger: 'blur', + validator: '' + } + ], + readOnly: [ + { + required: true, + trigger: 'change', + message: language.t('createKey.empty.permissions') + } + ] + }) + }; + + /** + * 密钥名称正则校验 + * @param {Object} _ 占位符 + * @param {string} value 输入项 + * @param {Function} callback 回调函数,返回对应状态 + */ + const keyNameCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + data.hasErrorStatus.value = true; + const keyNameArr = [ + [ + (value: string) => !value?.length, + () => { + data.keyNameTip.value = language.t('createKey.empty.keyName'); + callback(new Error()); + } + ], + [ + (value: string) => (!RegularContent.nameReg.test(value)), + () => { + data.keyNameTip.value = language.t('createKey.errorTip.keyName'); + callback(new Error()); + } + ], + [ + (value: string) => (props.keyNameData.includes(value)), + () => { + data.keyNameTip.value = language.t('createKey.errorTip.repeat'); + callback(new Error()); + } + ], + [ + (value: string) => value, + () => { + data.hasErrorStatus.value = false; + data.keyNameTip.value = language.t('createKey.errorTip.keyName'); + callback(); + } + ] + ]; + for (const key of keyNameArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + data.rules.name[0].validator = keyNameCheck; + + return { + ...data, + keyNameCheck + }; +}; + +export default regExpCheck; diff --git a/bmp-operation-web/src/components/UserCenter/DeleteApiKey/DeleteApiKey.vue b/bmp-operation-web/src/components/UserCenter/DeleteApiKey/DeleteApiKey.vue new file mode 100644 index 0000000..7e44681 --- /dev/null +++ b/bmp-operation-web/src/components/UserCenter/DeleteApiKey/DeleteApiKey.vue @@ -0,0 +1,92 @@ + + + + diff --git a/bmp-operation-web/src/components/UserCenter/DeleteApiKey/deleteApiKey.scss b/bmp-operation-web/src/components/UserCenter/DeleteApiKey/deleteApiKey.scss new file mode 100644 index 0000000..d42975f --- /dev/null +++ b/bmp-operation-web/src/components/UserCenter/DeleteApiKey/deleteApiKey.scss @@ -0,0 +1,44 @@ +@import '@/assets/css/communal'; + +.delete-api-key { + .el-dialog { + &--center { + --el-dialog-width: 520px; + height: 292px; + } + + &__body { + padding: 0; + + .delete-keycontent { + margin: 80.5px auto; + width: 420px; + text-align: center; + + .delete-keyscope { + font-size: $fontSize2; + color: $defaultColor; + } + + .el-radio { + height: 16px; + margin-bottom: 16px; + + &:last-child { + margin-right: 30px; + } + + &-group { + display: flex; + flex-direction: column; + margin-top: 19.5px; + } + } + } + } + + &__footer { + width: 475px; + } + } +} diff --git a/bmp-operation-web/src/components/UserOperates/AddUser/AddUser.vue b/bmp-operation-web/src/components/UserOperates/AddUser/AddUser.vue new file mode 100644 index 0000000..b03aaa9 --- /dev/null +++ b/bmp-operation-web/src/components/UserOperates/AddUser/AddUser.vue @@ -0,0 +1,223 @@ + + + + diff --git a/bmp-operation-web/src/components/UserOperates/AddUser/addUser.scss b/bmp-operation-web/src/components/UserOperates/AddUser/addUser.scss new file mode 100644 index 0000000..f44c447 --- /dev/null +++ b/bmp-operation-web/src/components/UserOperates/AddUser/addUser.scss @@ -0,0 +1,370 @@ +@import '@/assets/css/communal'; + +.add-user { + .el-dialog { + &--center { + --el-dialog-width: 646px; + height: 545px; + } + + &__footer { + width: 601px; + } + } + + &-ruleForm { + margin-top: 11px; + + .el-radio__label { + font-size: 12px; + } + + .el-form-item__error { + margin-top: 2px; + } + + .el-form-item__label { + margin-right: 5px; + position: relative; + font-weight: $fontLargeWeight; + line-height: 1.5; + display: flex; + align-items: center; + } + + &-role { + + .el-form-item__label { + width: 70px !important; + margin-left: 10px; + } + + &-img { + width: 32px; + height: 32px; + transform: scale(.5); + margin-left: 6px; + margin-top: -15px; + cursor: pointer; + } + + .el-form-item__content { + font-size: 121px; + color: $defaultColor; + font-weight: $fontLargeWeight; + + .el-radio { + margin-right: 24px; + } + + .is-checked { + .el-radio__inner { + width: 7px; + height: 7px; + position: absolute; + left: 50%; + top: 50%; + transform: translate(-50%, -50%); + display: inherit !important; + + &::after { + display: none; + } + } + } + + .el-radio__input { + width: 12px; + height: 12px; + border: 0.62px solid $border2; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + + .el-radio__inner { + display: none; + } + } + } + } + + &-desc { + .el-form-item__label { + width: 70px !important; + margin-left: 10px; + display: flex; + align-items: flex-start; + margin-top: 5px; + } + } + + .el-input--default, + .el-form-item__content { + display: flex; + } + + .user-count { + position: absolute; + + .user-mailbox { + font-size: 12px; + color: $defaultColor; + font-weight: $fontSmallWeight; + } + } + + .set-empty { + margin-bottom: 32px !important; + .el-form-item__error { + margin-top: 6px !important; + } + } + + .set-empty-email { + .el-form-item__error { + margin-top: 6px !important; + } + } + + .user-password { + margin-bottom: 16px; + .el-form-item__error { + margin-top: 5px; + } + } + + .height-user-password { + margin-bottom: 47px !important; + .el-form-item__error { + margin-top: 5px; + line-height: 1.4; + } + } + + .height-user-password, + .user-password { + .el-form-item__label { + align-items: flex-start; + } + } + + .el-form-item__label, + .el-input__inner { + font-size: $fontSize; + color: $defaultColor; + } + + .el-form-item--default { + margin-bottom: 16px; + + &:last-child { + margin-bottom: 0; + } + } + + input { + width: 515px; + height: 30px; + color: $defaultColor; + border-radius: 4px; + + &:focus { + border-color: $border3; + } + } + + textarea { + width: 515px; + height: 78px; + padding: 5px 8px; + margin-top: 7px; + font-size: $fontSize; + resize: none; + + &::placeholder { + font-size: $fontSize; + } + } + + .set-select-count { + .input-select { + .el-input__inner { + width: 165px; + } + } + } + + .input-select-count { + .input-select { + .el-input__inner { + width: 140px; + } + } + } + + .set-select-count, + .input-select-count { + float: left; + + .input-select { + .el-input__inner { + height: 30px; + border-radius: 4px; + color: $defaultColor; + font-weight: 500; + } + } + } + + .set-ipt-phone { + .el-input--default, + .el-input__inner { + width: 205px; + } + } + + .input-phone-count { + .el-input--default, + .el-input__inner { + width: 162px; + } + } + + .set-ipt-phone, + .input-phone-count { + display: flex; + + .el-form-item__content { + margin-left: 14px !important; + } + + .el-input--default, + .el-input__inner { + height: 30px; + } + } + } + + .set-add-user-ipt { + .add-user-ipt-user-img, + .add-user-ipt-open-eye, + .add-user-ipt-close-eye { + left: 0px !important; + } + + .el-form-item__error { + margin-left: 0px !important; + } + } + + &-ipt { + &-user-img, + &-open-eye, + &-close-eye { + left: 5px; + } + } + + .set-add-user-ipt, + &-ipt { + width: 535px; + height: 30px; + display: flex; + align-items: center; + + input { + padding-left: 35px; + height: 30px; + border-radius: 4px; + + &:focus { + border-color: $border3; + } + } + + &-open-eye, + &-close-eye { + cursor: pointer; + } + + &-user-img, + &-open-eye, + &-close-eye { + width: 32px; + height: 32px; + transform: scale(.5); + position: absolute; + z-index: 9; + } + + &-clear { + width: 32px; + height: 32px; + transform: scale(.5); + position: absolute; + right: 8px; + cursor: pointer; + } + } + + .user-name-c { + margin-bottom: 0; + position: relative; + + .is-loading { + position: absolute; + right: 10px; + top: 7px; + animation: loading .7s linear ease-in-out; + } + + @keyframes loading { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(100deg); + } + } + + .el-form-item__label { + align-items: flex-start; + margin-top: 5px; + } + } + + .tooltip-img { + width: 32px; + height: 32px; + transform: scale(.5); + margin-left: 6px; + margin-top: -15px; + cursor: pointer; + } + + .default-tip, + .custom-tip { + font-size: 12px; + height: 20px; + margin-bottom: 13px; + margin-top: 5px; + line-height: 20px; + } + .default-tip { + font-size: 12px; + height: 20px; + margin-bottom: 13px; + margin-top: 5px; + // margin: 3px 0; + line-height: 20px; + } + + .default-tip { + color: #999; + } + + .custom-tip { + color: #f56c6c; + } +} diff --git a/bmp-operation-web/src/components/UserOperates/AddUser/typeManagement.ts b/bmp-operation-web/src/components/UserOperates/AddUser/typeManagement.ts new file mode 100644 index 0000000..4ac8ff0 --- /dev/null +++ b/bmp-operation-web/src/components/UserOperates/AddUser/typeManagement.ts @@ -0,0 +1,36 @@ +import {VerifyRulesType} from '@utils/publicType'; + +/** + * 规则类-信息 +*/ +interface RuleInfoType { + userName: VerifyRulesType[]; + password: VerifyRulesType[]; + phoneNumber: VerifyRulesType[]; + email: VerifyRulesType[]; +}; + +/** + * 表单类信息 +*/ +interface RuleFormType { + userName: string; // 用户名 + password: string; // 密码 + roleId: string; + description: string; // 描述 + phonePrefix: string; // 手机号类型 + phoneNumber: string; // 手机号 + email: string; // 邮箱 +}; + +interface AddUserFormRulesType { + ruleForm: RuleFormType; + phoneFlag: boolean; + validate(arg0: string, arg1: boolean): Function; +}; + +export { + RuleInfoType, + RuleFormType, + AddUserFormRulesType +}; diff --git a/bmp-operation-web/src/components/UserOperates/AddUser/utils/addUser.ts b/bmp-operation-web/src/components/UserOperates/AddUser/utils/addUser.ts new file mode 100644 index 0000000..a8fba78 --- /dev/null +++ b/bmp-operation-web/src/components/UserOperates/AddUser/utils/addUser.ts @@ -0,0 +1,80 @@ +import {deepCopy} from 'utils/index.ts'; +import {RuleFormRefType} from '@utils/publicType'; +import {AddUserFormRulesType} from '../typeManagement'; +import {language, locationItem, CurrentInstance} from 'utils/publicClass.ts'; +import UserStaticData from 'staticData/user/index.ts'; + +interface RefType extends AddUserFormRulesType { + ruleFormRef: Ref; +}; + +class AddUserOperate { + // loading态 + isLoading: Ref = ref(false); + formRulesOperate: RefType; + emitValue: (arg0: string, arg1?: boolean) => () => {}; + msgTip: {success(arg0: string): void}; + proxy = new CurrentInstance().proxy; + + constructor (formRulesOperate: RefType, emitValue: (arg0: string, arg1?: boolean) => () => {}, msgTip: {success(arg0: string): void}) { + this.formRulesOperate = formRulesOperate; + this.emitValue = emitValue; + this.msgTip = msgTip; + document.onkeyup = (event: {keyCode: number;}) => { + event.keyCode === 13 && this.determineClick(); + }; + }; + + /** + * 确定按钮弹窗 + */ + determineClick: () => Promise = async () => { + this.isLoading.value = true; + // 判断输入项是否符合条件 + await nextTick(() => { + this.formRulesOperate.validate('phoneNumber', this.formRulesOperate.phoneFlag); + this.formRulesOperate.ruleFormRef.value!.validate((valid: boolean) => { + // 输入符合条件后才可以继续后续操作 + if (valid) { + this.requestAddUser(); + } + else { + this.isLoading.value = false; + } + }); + }); + }; + + /** + * 请求添加用户验证接口,成功后把事件回传,关闭弹窗 + */ + requestAddUser = async () => { + let item = deepCopy(this.formRulesOperate.ruleForm as any); + const type = UserStaticData.phoneType.find((item: any) => item.name === this.formRulesOperate.ruleForm.phonePrefix).type; + item.phonePrefix = type; + try { + const addUserApi = await this.proxy.$userApi.addUserAPI({...item, language: locationItem.getLocationItem}); + if (addUserApi?.data?.result?.userId?.length) { + this.cancelClick(); + this.msgTip.success(language.t('operate.success')); + this.emitValue('determine-click'); + } + } + finally { + this.isLoading.value = false; + sessionStorage?.removeItem('roleId'); + } + }; + + /** + * 取消按钮点击操作 + */ + cancelClick = (): void => { + // 清空输入内容、异常提示状态 + this.formRulesOperate.ruleFormRef.value!.resetFields(); + // 回传父组件当前页码,可以处理相关操作 + this.emitValue('dia-log-close', false); + }; +}; + +export default AddUserOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/components/UserOperates/AddUser/utils/formRules.ts b/bmp-operation-web/src/components/UserOperates/AddUser/utils/formRules.ts new file mode 100644 index 0000000..a37cf78 --- /dev/null +++ b/bmp-operation-web/src/components/UserOperates/AddUser/utils/formRules.ts @@ -0,0 +1,100 @@ +import {RuleFormRefType} from '@utils/publicType'; +import {RuleFormType, RuleInfoType} from '../typeManagement'; +import {decrypt} from 'utils/index.ts'; +import {language, UserCheck, CurrentInstance} from 'utils/publicClass.ts'; + +class FormRulesOperate { + emailFlag: Ref = ref(false); + phoneFlag: Ref = ref(false); + // 表单ref + ruleFormRef: Ref = ref(); + ruleForm: RuleFormType = reactive({ + userName: '', // 用户名 + password: '', // 密码 + roleId: '', // 角色选择 + description: '', // 描述 + phonePrefix: language.t('addUser.phoneData.China'), // 手机号类型 + phoneNumber: '', // 手机号 + email: '' // 邮箱 + }); + // 规则 + rules: RuleInfoType = reactive({ + userName: [ // 用户名 + { + required: true, + trigger: 'blur', + // validator: regExpCheck.userNameCheck + } + ], + password: [ // 密码 + { + required: true, + trigger: 'blur', + // validator: regExpCheck.passwordCheck + } + ], + phoneNumber: [ // 手机号 + { + required: true, + trigger: 'blur', + validator: new UserCheck(this.ruleForm.phonePrefix, 'addUser').phoneChcek + } + ], + email: [ // 邮箱 + { + required: true, + trigger: 'blur', + validator: new UserCheck('', 'addUser').emailChcek + } + ] + }); + // 密码是否明文显示,密码类型 + passwordType: Ref = ref('password'); + instanceProxy = new CurrentInstance().proxy; + + constructor (status: boolean, regExpCheck: {userNameCheck: unknown; passwordCheck: unknown;}) { + const userPurview: string = this.instanceProxy.$defInfo.purview('user'); + const adminPurview: string = this.instanceProxy.$defInfo.purview('admin'); + const roleId = sessionStorage?.getItem('roleId')??''; + const encryptDecrypt: string[] = this.instanceProxy.$defInfo.encryptDecrypt(1); + this.ruleForm.roleId = roleId ? decrypt(roleId, encryptDecrypt[0], encryptDecrypt[1]) : status ? userPurview : adminPurview; // 角色选择 + this.rules.userName[0].validator = regExpCheck.userNameCheck; + this.rules.password[0].validator = regExpCheck.passwordCheck; + watch(() => this.ruleForm.phonePrefix, (newValue: string) => { + this.ruleForm.phonePrefix = newValue; + this.ruleForm.phoneNumber = ''; + this.rules.phoneNumber[0].validator = new UserCheck(this.ruleForm.phonePrefix).phoneChcek; + }, {deep: true}); + }; + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: RuleFormRefType}): void => { + this.ruleFormRef.value = formEl.value; + }; + + /** + * 清空输入项 + * @param {string} inputValue 输入项内容 + */ + clearInput = (inputValue: string): void => { + (this.ruleForm[`${inputValue}` as keyof typeof this.ruleForm] as string) = ''; + }; + + /** + * 清空输入项 + * @param {string} status 密码类型 + * @return {string} passwordType.value 密码类型 + */ + passwordStatusChange = (status: string): string => { + return this.passwordType.value = status; + }; + + validate = (type1: string, type2: {value: boolean}) => { + this.ruleFormRef.value!.validateField(([type1] as never), (valid: string) => !valid ? type2.value = false : type2.value = true); + }; +}; + +export default FormRulesOperate; diff --git a/bmp-operation-web/src/components/UserOperates/AddUser/utils/regExpCheck.ts b/bmp-operation-web/src/components/UserOperates/AddUser/utils/regExpCheck.ts new file mode 100644 index 0000000..f312279 --- /dev/null +++ b/bmp-operation-web/src/components/UserOperates/AddUser/utils/regExpCheck.ts @@ -0,0 +1,115 @@ +import {language} from 'utils/publicClass.ts'; +import RegularContent from 'utils/regular.ts'; +import {resourcesAPI} from 'api/public/request.ts'; + +class RegExpCheck { + userNameTip: Ref = ref(''); + heightFlag: Ref = ref(false); + passwordFlag: Ref = ref(false); + isShowLoading: Ref = ref(false); + + /** + * 用户名正则校验 + * @param {Object} _ 占位符 + * @param {string} value 输入项 + * @param {Function} callback 回调函数,返回对应状态 + */ + userNameCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + const userNameArr = [ + [ + (value: string) => !value?.length, + () => { + this.userNameTip.value = language.t('addUser.emptyTip.userName'); + callback(new Error()); + } + ], + [ + (value: string) => (!RegularContent.name1Reg.test(value)), + () => { + this.userNameTip.value = language.t('addUser.errorTip.userName'); + callback(new Error()); + } + ], + [ + (value: string) => value, + () => { + this.userNameTip.value = ''; + this.isShowLoading.value = true; + this.getData(value).then(() => { + this.userNameTip.value = language.t('addUser.errorTip.repeatUserName'); + callback(new Error()); + }) + .catch(() => { + this.userNameTip.value = ''; + callback(); + }) + .finally(() => { + this.isShowLoading.value = false; + }); + } + ] + ]; + for (const key of userNameArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + getData = (userName: string): Promise => { + return resourcesAPI({userName}) + .then(({data} : {data: {result: {success: boolean}}}) => { + if (data?.result?.success) { + return Promise.resolve(); + } + return Promise.reject(); + }) + .catch(() => { + return Promise.reject(); + }); + }; + + /** + * 密码正则校验 + * @param {Object} _ 占位符 + * @param {string} value 输入项 + * @param {Function} callback 回调函数,返回对应状态 + */ + passwordCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + const passwordArr = [ + [ + (value: string) => !value?.length, + () => { + this.heightFlag.value = false; + this.passwordFlag.value = true; + callback(new Error(language.t('addUser.emptyTip.password'))); + } + ], + [ + (value: string) => (!RegularContent.passwordReg.test(value)), + () => { + this.heightFlag.value = true; + this.passwordFlag.value = false; + callback(new Error(language.t('addUser.errorTip.password'))); + } + ], + [ + (value: string) => value, + () => { + this.heightFlag.value = false; + this.passwordFlag.value = false; + callback(); + } + ] + ]; + for (const key of passwordArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; +}; + +export default RegExpCheck; diff --git a/bmp-operation-web/src/components/UserOperates/DeleteUser/DeleteUser.vue b/bmp-operation-web/src/components/UserOperates/DeleteUser/DeleteUser.vue new file mode 100644 index 0000000..1762284 --- /dev/null +++ b/bmp-operation-web/src/components/UserOperates/DeleteUser/DeleteUser.vue @@ -0,0 +1,173 @@ + + + + diff --git a/bmp-operation-web/src/components/UserOperates/DeleteUser/deleteUser.scss b/bmp-operation-web/src/components/UserOperates/DeleteUser/deleteUser.scss new file mode 100644 index 0000000..59b7124 --- /dev/null +++ b/bmp-operation-web/src/components/UserOperates/DeleteUser/deleteUser.scss @@ -0,0 +1,67 @@ + + +@import '@/assets/css/communal'; + +.delete-user { + .el-dialog { + &--center { + --el-dialog-width: 646px; + height: 366px;; + } + + &__body { + padding: 0; + + .currency-count { + display: flex; + flex-direction: column; + + &-title { + font-size: $fontSize; + font-weight: $fontLargeWeight; + color: $defaultColor; + margin: 19.5px 0 20px; + } + + &-table { + + .el-table__body-wrapper { + .el-table__body { + width: 100% !important; + } + .el-table__body tr:hover > td{ + background-color: $background10 !important; + } + + table { + .el-table__row { + background: $background3; + } + } + } + + .el-table__header-wrapper { + margin-bottom: 5px; + + table { + width: 100% !important; + } + } + + .el-table__cell { + border-left: 0 !important; + // border: 0 !important; + + &:last-child { + border-right: 0; + } + } + } + } + } + + &__footer { + width: 601px; + } + } +} diff --git a/bmp-operation-web/src/components/UserOperates/DeleteUser/type.ts b/bmp-operation-web/src/components/UserOperates/DeleteUser/type.ts new file mode 100644 index 0000000..d9a518d --- /dev/null +++ b/bmp-operation-web/src/components/UserOperates/DeleteUser/type.ts @@ -0,0 +1,14 @@ + +type key = 'userName' | 'roleName' | 'phoneNumber' | 'userId' | 'email'; + +/** + * 表格数据类 +*/ +type ListDataType = { + [k in key]: string; +}; + + +export { + ListDataType +}; diff --git a/bmp-operation-web/src/components/UserOperates/EditingUser/EditingUser.vue b/bmp-operation-web/src/components/UserOperates/EditingUser/EditingUser.vue new file mode 100644 index 0000000..9cdf439 --- /dev/null +++ b/bmp-operation-web/src/components/UserOperates/EditingUser/EditingUser.vue @@ -0,0 +1,161 @@ + + + + diff --git a/bmp-operation-web/src/components/UserOperates/EditingUser/editingUser.scss b/bmp-operation-web/src/components/UserOperates/EditingUser/editingUser.scss new file mode 100644 index 0000000..4edda07 --- /dev/null +++ b/bmp-operation-web/src/components/UserOperates/EditingUser/editingUser.scss @@ -0,0 +1,161 @@ +@import '@/assets/css/communal'; + +.editing-user { + .el-dialog { + &--center { + --el-dialog-width: 648px; + padding: 0 22.5px; + + margin: auto; + } + + &__body { + margin-bottom: 229px; + } + + &__footer { + width: 601px; + } + } + + &-ruleForm { + margin-top: 11px; + + .set-empty { + margin-bottom: 32px !important; + .el-form-item__error { + margin-top: 6px !important; + } + } + + .el-form-item__label { + position: relative; + font-weight: $fontLargeWeight; + } + + .el-form-item__error { + margin-top: 2px; + } + + .set-email, + .user-counts { + position: absolute; + + .user-mailbox { + font-size: $fontSize; + color: $defaultColor; + font-weight: $fontSmallWeight; + width: 507px; + } + } + + .user-names, + .user-roles { + font-size: $fontSize; + color: $defaultColor; + font-weight: $fontSmallWeight; + } + + .el-form-item__label, + .el-input__inner { + font-size: $fontSize; + color: $defaultColor; + } + + .el-form-item--default { + margin-bottom: 20px; + + &:last-child { + margin-bottom: 0; + } + } + + &-desc { + + .el-form-item__label { + width: 70px !important; + margin-left: 10px; + } + } + + input { + width: 515px; + height: 30px; + border-radius: 4px; + } + + textarea { + width: 505px; + height: 78px; + padding: 5px 8px; + margin-top: 7px; + font-size: $fontSize; + resize: none; + + &::placeholder { + font-size: $fontSize; + } + } + + .el-textarea .el-input__count { + right: 33px; + } + + .set-select-count { + .input-select { + .el-input__inner { + width: 165px; + } + } + } + + .input-select-count { + .input-select { + .el-input__inner { + width: 130px; + } + } + } + + .set-select-count, + .input-select-count { + float: left; + + .input-select { + .el-input__inner { + height: 30px; + border-radius: 4px; + color: $defaultColor; + font-weight: 500; + } + } + } + + .set-ipt-phone { + .el-input--default, + .el-input__inner { + width: 205px; + } + } + + .input-phone-count { + .el-input--default, + .el-input__inner { + width: 162px; + } + } + + .set-ipt-phone, + .input-phone-count { + display: flex; + .el-form-item__content { + margin-left: 14px !important; + } + + .el-input--default, + .el-input__inner { + height: 30px; + } + } + } +} diff --git a/bmp-operation-web/src/components/UserOperates/EditingUser/typeManagement.ts b/bmp-operation-web/src/components/UserOperates/EditingUser/typeManagement.ts new file mode 100644 index 0000000..2d9afc0 --- /dev/null +++ b/bmp-operation-web/src/components/UserOperates/EditingUser/typeManagement.ts @@ -0,0 +1,31 @@ +import {VerifyRulesType} from '@utils/publicType'; + +/** + * 规则类-信息 +*/ +interface RuleInfoType { + description: VerifyRulesType[]; + phoneNumber: VerifyRulesType[]; + email: VerifyRulesType[]; +}; + +/** + * 表单类 +*/ +interface RuleFormType { + type: string; + userName: string; + roleName: string; + defaultProjectId: string; + description: string; + phoneNumber: string; + phonePrefix: string; + email: string; + userId: string; + roleId?: string; +}; + +export { + RuleInfoType, + RuleFormType +}; diff --git a/bmp-operation-web/src/components/UserOperates/EditingUser/utils/editUser.ts b/bmp-operation-web/src/components/UserOperates/EditingUser/utils/editUser.ts new file mode 100644 index 0000000..c490298 --- /dev/null +++ b/bmp-operation-web/src/components/UserOperates/EditingUser/utils/editUser.ts @@ -0,0 +1,84 @@ +import {CurrencyType} from '@utils/publicType'; +import {deepCopy, msgTip, methodsTotal} from 'utils/index.ts'; +import {language, locationItem, CurrentInstance} from 'utils/publicClass.ts'; + +const editUserOperate = (formRules: any, emitValue: any) => { + // loading态 + const isLoading: Ref = ref(false); + const proxy = new CurrentInstance().proxy; + + onMounted(() => { + document.onkeyup = (event: {keyCode: number;}) => { + event.keyCode === 13 && determineClick(); + }; + onUnmounted(() => { + document.onkeyup = () => {return;} + }); + }); + + /** + * 确定按钮弹窗 + */ + const determineClick = async (): Promise => { + // 判断输入项是否符合条件 + await nextTick(() => { + formRules.ruleFormRef.value!.validate((valid: boolean) => { + // 输入符合条件后才可以继续后续操作 + if (valid) { + isLoading.value = true; + requestEditUser(); + } + else { + if (!formRules.ruleForm.phoneNumber) { + formRules.phoneFlag.value = true; + } + } + }); + }); + }; + + /** + * 请求编辑用户验证接口,成功后把事件回传,关闭弹窗 + */ + const requestEditUser = async () => { + const copyRuleForm = deepCopy(formRules.ruleForm as never); + copyRuleForm.phonePrefix = formRules.ruleForm.type; + try { + const editApi = await proxy.$userApi.editUserAPI({...copyRuleForm, language: locationItem.getLocationItem}); + const status: boolean = (editApi?.data?.result?.success)?? false; + status && dealWithResponse(copyRuleForm); + } + finally { + dealWithFinally(); + } + }; + + const dealWithResponse = (copyRuleForm: CurrencyType) => { + methodsTotal.sendMsg('update-user-info', {...copyRuleForm}); + msgTip.success(language.t('operate.success')); + }; + + const dealWithFinally = () => { + isLoading.value = false; + emitValue('determine-click'); + cancelClick(); + }; + + /** + * 取消按钮点击操作 + */ + const cancelClick = (): void => { + // 清空输入内容、异常提示状态 + formRules.ruleFormRef.value!.resetFields(); + // 回传父组件当前页码,可以处理相关操作 + emitValue('dia-log-close', false); + }; + + return { + isLoading, + determineClick, + cancelClick + } +}; + +export default editUserOperate; diff --git a/bmp-operation-web/src/components/UserOperates/EditingUser/utils/formRules.ts b/bmp-operation-web/src/components/UserOperates/EditingUser/utils/formRules.ts new file mode 100644 index 0000000..e09bd33 --- /dev/null +++ b/bmp-operation-web/src/components/UserOperates/EditingUser/utils/formRules.ts @@ -0,0 +1,98 @@ +import {RuleFormRefType} from '@utils/publicType'; +import {language, UserCheck} from 'utils/publicClass.ts'; // cookie、国际化、用户验证 +import {RuleFormType, RuleInfoType} from '../typeManagement'; +import UserStaticData from 'staticData/user/index.ts'; // 手机号类型数据 + +interface DataType { + phoneFlag: Ref; + emailFlag: Ref; + ruleFormRef: Ref; + ruleForm: RuleFormType; + rules: RuleInfoType; +}; + +const formRulesOperate = (props: any) => { + const data: DataType = { + phoneFlag: ref(false), + emailFlag: ref(false), + // 表单ref + ruleFormRef: ref(), + // 表单项 + ruleForm: reactive({ + ...props.listData, + type: '' + }), + // 规则 + rules: reactive({ + description: [ // 描述 + { + required: false, + message: language.t('editUser.emptyTip.desc'), + trigger: 'blur' + } + ], + phoneNumber: [ // 手机号 + { + required: true, + trigger: 'blur', + validator: {} + } + ], + email: [ // 邮箱 + { + required: true, + trigger: 'blur', + validator: new UserCheck().emailChcek + } + ] + }) + }; + + onMounted(() => { + nextTick(() => { + data.rules.phoneNumber[0].validator = new UserCheck(data.ruleForm.phonePrefix).phoneChcek; + }) + if (props.prefix === '1') { + data.ruleForm.phonePrefix = language.t('editUser.phoneData.USA'); + data.ruleForm.type = '1'; + } + else { + for(const key of UserStaticData.phoneType) { + if (key.type === props.prefix) { + data.ruleForm.phonePrefix = key.name; + const value = UserStaticData.cellPhoneType.find((item: {label: string}) => item.label === data.ruleForm.phonePrefix); + data.ruleForm.type = value.text; + } + } + } + }); + + const selectChange = (newValue: string) => { + data.ruleForm.phonePrefix = newValue; + data.ruleForm.phoneNumber = ''; + const value = UserStaticData.cellPhoneType.find((item: {label: string}) => item.label === newValue); + data.ruleForm.type = value.text; + data.rules.phoneNumber[0].validator = new UserCheck(data.ruleForm.phonePrefix).phoneChcek; + }; + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + const getFormRef = (formEl: {value: RuleFormRefType}): void => { + data.ruleFormRef.value = formEl.value; + }; + + const validate = (type1: never | string, type2: {value: boolean}) => { + data.ruleFormRef.value!.validateField(([type1] as never), (valid: string) => !valid ? type2.value = false : type2.value = true); + }; + + return { + ...data, + getFormRef, + validate, + selectChange + }; +}; + +export default formRulesOperate; diff --git a/bmp-operation-web/src/hooks/custom/custom.vue b/bmp-operation-web/src/hooks/custom/custom.vue new file mode 100644 index 0000000..35cad67 --- /dev/null +++ b/bmp-operation-web/src/hooks/custom/custom.vue @@ -0,0 +1,21 @@ + + diff --git a/bmp-operation-web/src/hooks/custom/useCustom.ts b/bmp-operation-web/src/hooks/custom/useCustom.ts new file mode 100644 index 0000000..63c4888 --- /dev/null +++ b/bmp-operation-web/src/hooks/custom/useCustom.ts @@ -0,0 +1,37 @@ +/** + * @file + * @author +*/ + +import {methodsTotal} from 'utils/index.ts'; +import {CustomOperate} from 'utils/publicClass.ts'; +import AllStaticData from 'staticData/staticData.ts'; // 自定义列表信息 自定义列表数据 + +const {idcInfo, modelInfo, imageInfo, deviceInfo, messageInfo, roleInfo, userInfo, hardwareInfo, faultLogInfo, faultRulesInfo, auditLogsInfo, allAlarmRulesInfo} = AllStaticData.allCustomListInfo; +const {idcList, modelList, imageList, deviceList, messageList, roleList, userList, hardwareList, faultLogList, faultRulesList, auditLogsList, allAlarmRulesList} = AllStaticData.allCustomList; + +const useCustom = (type: string) => { + const infoList = new Map([ + ['idcList', [idcInfo, idcList]], + ['deviceTypeList', [modelInfo, modelList]], + ['imageList', [imageInfo, imageList]], + ['deviceList', [deviceInfo, deviceList]], + ['roleList', [roleInfo, roleList]], + ['userList', [userInfo, userList]], + [methodsTotal.humpConversion('deviceStatusList'), [hardwareInfo, hardwareList]], + [methodsTotal.humpConversion('alertLogList'), [faultLogInfo, faultLogList]], + [methodsTotal.humpConversion('alertRuleList'), [faultRulesInfo, faultRulesList]], + [methodsTotal.lineConverting('messageList'), [messageInfo, messageList]], + ['auditLogsList', [auditLogsInfo, auditLogsList]], + ['monitorRulesList', [allAlarmRulesInfo, allAlarmRulesList]] + ]); + + // @ts-ignore + const info = new CustomOperate(type, infoList.get(type)[0], infoList.get(type)[1]); + + return { + info + } +} + +export default useCustom; \ No newline at end of file diff --git a/bmp-operation-web/src/hooks/pagination/paginationSelect.vue b/bmp-operation-web/src/hooks/pagination/paginationSelect.vue new file mode 100644 index 0000000..7c47366 --- /dev/null +++ b/bmp-operation-web/src/hooks/pagination/paginationSelect.vue @@ -0,0 +1,32 @@ + + + diff --git a/bmp-operation-web/src/hooks/pagination/usePagination.ts b/bmp-operation-web/src/hooks/pagination/usePagination.ts new file mode 100644 index 0000000..bac1b16 --- /dev/null +++ b/bmp-operation-web/src/hooks/pagination/usePagination.ts @@ -0,0 +1,16 @@ +import {paginationOperate} from 'utils/publicClass.ts'; + + +const usePagination = (list: T, clear: K) => { + watch(() => [ + paginationOperate.pageSize.value, + paginationOperate.pageNumber.value + ], (_: boolean[]): void => { + clear?.clearSelection(); + if (paginationOperate.routerChange.value) return; + paginationOperate.total.value = 0; + list(); + }); +} + +export default usePagination; \ No newline at end of file diff --git a/bmp-operation-web/src/lib/default/defInfo.ts b/bmp-operation-web/src/lib/default/defInfo.ts new file mode 100644 index 0000000..352154f --- /dev/null +++ b/bmp-operation-web/src/lib/default/defInfo.ts @@ -0,0 +1,123 @@ +/** + * @file + * @author +*/ + +import {AppType} from '../filters/filter'; + +const defInfo = (app: AppType) => app.config.globalProperties.$defInfo = { + purview(value: string = '') { + const purviewInfo: Map = new Map([ + ['admin', 'role-admin-uuid-01'], + ['operator', 'role-operator-uuid-01'], + ['user', 'role-user-uuid-01'] + ]); + return purviewInfo.get(value); + }, + + routerPath(value: string) { + const url: Map = new Map([ + ['login', '/Login/login'], + ['idcList', '/IdcManagement/idcList'], + ['idcDetail', '/IdcManagement/idcDetail'], + ['modelList', '/ModelManagement/modelList'], + ['modelDetail', '/ModelManagement/modelDetail'], + ['addModel', '/ModelManagement/modelAdd'], + ['editModel', '/ModelManagement/modelEdit'], + ['addModelTemplate', '/ModelManagement/addModelTemplate'], + ['imageList', '/ImageManagement/imageList'], + ['imageDetail', '/ImageManagement/imageDetail'], + ['deviceList', '/DeviceManagement/deviceList'], + ['deviceDetail', '/DeviceManagement/deviceDetail'], + ['hardwareStatus', '/MonitorManagement/hardwareStatus'], + ['faultLog', '/MonitorManagement/faultLog'], + ['faultRules', '/MonitorManagement/faultRules'], + ['resourceMonitor', '/InBandMonitoringManagement/resourceMonitor'], + ['historyAlarmInfo', '/InBandMonitoringManagement/historyAlarmInfo'], + ['alarmRulesList', '/InBandMonitoringManagement/allAlarmRulesList'], + ['alarmRulesDetail', '/InBandMonitoringManagement/allAlarmRulesDetail'], + ['role', '/RoleManagement/roleList'], + ['user', '/UserManagement/userList'], + ['myMessage', '/MessageNotification/myMessage'], + ['myMessageDetail', '/MessageNotification/messageDetail'], + ['myMessageSettings', '/MessageNotification/messageSettings'], + ['myProfile', '/PersonalCenter/myProfile'], + ['securitySettings', '/PersonalCenter/securitySettings'], + ['apiKey', '/PersonalCenter/apiKeyApi'] + ]); + return url.get(value); + }, + + imagePath(value: string) { + const imgUrl: Map = new Map([ + ['loginOut', require('@/assets/img/loginImg/login-out.png')], + ['imageManage', require('@/assets/img/navigationBarImg/image-manage.png')], + ['descEdit', require('@/assets/img/uiImg/desc-edit.png')], + ['warningTip', require('@/assets/img/diaLogImg/warning-tip.png')], + ['device', require('@/assets/img/navigationBarImg/device.png')], + ['lock', require('@/assets/img/uiImg/lock.png')], + ['tip', require('@/assets/img/uiImg/tip.png')], + ['centos', require('@/assets/img/uiImg/centos.png')], + ['ubantu', require('@/assets/img/uiImg/ubantu.png')], + ['debian', require('@/assets/img/uiImg/debian.png')], + ['openEuler', require('@/assets/img/uiImg/openeuler.png')], + ['windows', require('@/assets/img/uiImg/windows.png')], + ['genericVersion', require('@/assets/img/uiImg/generic-version.png')], + ['idcManage', require('@/assets/img/navigationBarImg/computer-room.png')], + ['model', require('@/assets/img/navigationBarImg/model.png')], + ['toolTip', require('@/assets/img/diaLogImg/tooltiip.png')], + ['loginUser', require('@/assets/img/loginImg/user.png')], + ['setUp', require('@/assets/img/listImg/set-up.png')], + ['export', require('@/assets/img/listImg/export.png')], + ['idcManageDef', require('@/assets/img/navigationBarImg/computer-room-x.png')], + ['modelDefault', require('@/assets/img/navigationBarImg/default-model.png')], + ['imageDefault', require('@/assets/img/navigationBarImg/default-image.png')], + ['deviceDefault', require('@/assets/img/navigationBarImg/default-device.png')], + ['surveillanceDef', require('@/assets/img/navigationBarImg/default-surveillance-manage-backups.png')], + ['defaultInBandMonitoringDef', require('@/assets/img/navigationBarImg/default-in-band-monitoring.png')], + ['defaultInBandMonitoringActive', require('@/assets/img/navigationBarImg/active-in-band-monitoring.png')], + ['defaultCard', require('@/assets/img/navigationBarImg/default-card.png')], + ['activeCard', require('@/assets/img/navigationBarImg/active-card.png')], + ['roleDefault', require('@/assets/img/navigationBarImg/default-role.png')], + ['userDefault', require('@/assets/img/navigationBarImg/default-user.png')], + ['userCenter', require('@/assets/img/uiImg/user-center.png')], + ['usercCenterActive', require('@/assets/img/uiImg/user-center-active.png')], + ['password', require('@/assets/img/navigationBarImg/password.png')], + ['surveillance', require('@/assets/img/navigationBarImg/surveillance-manage-backups.png')], + ['searchIcon', require('@/assets/img/uiImg/search-icon.png')], + ['clear', require('@/assets/img/uiImg/clear.png')], + ['apiKey', require('@/assets/img/uiImg/api-key.png')], + ['user', require('@/assets/img/navigationBarImg/user.png')], + ['openEye', require('@/assets/img/loginImg/open-eye.png')], + ['closeEye', require('@/assets/img/loginImg/close-eye.png')], + ['loginClear', require('@/assets/img/loginImg/clear.png')], + ['role', require('@/assets/img/navigationBarImg/role.png')], + ['uiTooltip', require('@/assets/img/uiImg/tooltip.png')], + ['arrowBottom', require('@/assets/img/listImg/arrow-bottom.png')], + ['defArrowBottom', require('@/assets/img/uiImg/table-arrow-bottom.png')], + ['userLogin', require('@/assets/img/loginImg/user-login.png')], + ['shrinkExpand', require('@/assets/img/navigationBarImg/shrink-expand.png')], + ['greenIcon', require('@/assets/img/uiImg/green.png')], + ['redIcon', require('@/assets/img/uiImg/red.png')], + ['overlayAactive', require('@/assets/img/uiImg/overlay-active.png')], + ['overlay', require('@/assets/img/uiImg/overlay.png')], + ['messageDef', require('@/assets/img/message/no-message.png')], + ['messageTip', require('@/assets/img/message/message.png')], + ['messageLight', require('@/assets/img/message/no-message-light.png')], + ['collect', require('@/assets/img/uiImg/re-collect.png')], + ['optSuccess', require('@/assets/img/uiImg/opt-success.png')], + ['optFail', require('@/assets/img/uiImg/opt-fail.png')], + ['optDoing', require('@/assets/img/uiImg/opt-doing.png')] + ]); + return imgUrl.get(value); + }, + + encryptDecrypt(num: number) { + const info: Map = new Map([ + [1, ['QAZPLMUNYRTVCBFG', '02835485DRFDHTYG']] + ]); + return info.get(num); + } +}; + +export default defInfo; \ No newline at end of file diff --git a/bmp-operation-web/src/lib/element/index.ts b/bmp-operation-web/src/lib/element/index.ts new file mode 100644 index 0000000..2ec96e6 --- /dev/null +++ b/bmp-operation-web/src/lib/element/index.ts @@ -0,0 +1,4 @@ +import ElementPlus from 'element-plus'; +import 'element-plus/dist/index.css'; + +export default ElementPlus; diff --git a/bmp-operation-web/src/lib/filters/filter.ts b/bmp-operation-web/src/lib/filters/filter.ts new file mode 100644 index 0000000..83d5add --- /dev/null +++ b/bmp-operation-web/src/lib/filters/filter.ts @@ -0,0 +1,80 @@ +type FiltersType = { + withClon(value: string): string; + withClonZh(value: string): string; + emptyFilter(value?: string | null | undefined): string; + paginationEllipsis(value: string): string; + defaultPassword(val: string): string; + defaultWidth(val: number): string | number; +}; + +type DefType = { + purview(value: string): void; + routerPath(value: string): void; + imagePath(value: string): void; + encryptDecrypt(num: number): string[] | undefined; +}; + +interface AppType { + config: { + globalProperties: { + $filter: FiltersType; + $defInfo: DefType; + }; + }; +}; + +/** + * ComponentCustomProperties用于扩充组件实例类型以支持自定义全局属性,否则会报警告。 +*/ +declare module 'vue' { + export interface ComponentCustomProperties { + $filter: FiltersType; + $defInfo: DefType; + } +} + +const filter = (app: AppType) => app.config.globalProperties.$filter = { + withClon(value: string): string { + return value + ':'; + }, + + withClonZh(value: string): string { + return value + ':'; + }, + + emptyFilter(value?: string | null | undefined): string { + switch (value) { + case '': + case undefined: + case 'undefined': + case null: + return '--'; + default: + return value; + } + }, + + paginationEllipsis(value: string): string { + return value + '...'; + }, + + defaultPassword(val: string): string { + if (val) { + return val; + } + return '********'; + }, + + defaultWidth(val: number): number | string { + if (val) { + return val; + } + return 'auto'; + } +}; + +export { + AppType +} + +export default filter; \ No newline at end of file diff --git a/bmp-operation-web/src/lib/i18n/en-US.ts b/bmp-operation-web/src/lib/i18n/en-US.ts new file mode 100644 index 0000000..a656ba0 --- /dev/null +++ b/bmp-operation-web/src/lib/i18n/en-US.ts @@ -0,0 +1,2581 @@ +const en: {[x: string]: {[x: string]: unknown}} = { + size: { + num: 'Optimize all remaining', + all: 'All' + }, + operate: { + success: 'Operate Success', + fail: 'Fail', + doing: 'Doing', + copy: 'Copy Success', + refresh: 'Refresh', + setUp: 'Settings', + name: 'Actions', + export: 'Export', + btn: { + cancel: 'Cancel', + sure: 'Confirm' + }, + tip: { + default: 'Please select resource', + } + }, + searchTip: { + title1: 'Find {0} resource matching the search and filter criteria, ', + title2: 'Find {0} resource matching the search and filter criteria, please change the search keywords or ', + title3: 'please go back to the list' + }, + monitorEcharts: { + tabs: { + h1: '1h', + h6: '6h', + h12: '12h', + d1: '1d', + d3: '3d', + d7: '7d', + d14: '14d' + }, + datePicker: { + startDate: 'Start Date', + endDate: 'End Date' + }, + radio: { + instance: 'Instance', + disk: 'Disk', + diskPartition: 'Disk Partition', + netWorkInterface: 'Network Interface' + }, + diskTip: 'Linux OS reports by DeviceName, and Windows OS reports by DriveLetter', + diskPartitionTip: 'Linux OS reports by MountPoint, and Windows OS reports by DriveLetter', + echartsCount: { + period: 'Period', + aggregationMethod: 'Aggregation Method', + cpuUnit: 'CPU Usage(%)', + cpu: 'CPU Usage', + memUnit: 'Memory Usage(%)', + mem: 'Memory Usage', + memUsageUnit: 'Memory Used(GB)', + memUsage: 'Memory Used', + diskUsageUnit: 'Disk Used(GB)', + diskUsage: 'Disk Used', + diskUsageRateUnit: 'Disk Usage(%)', + diskUsageRate: 'Disk Usage', + diskReadWriteTrafficUnit: 'Disk Read/Write Traffic (Bps)', + diskReadWriteTraffic: 'Disk Read/Write Traffic', + diskReadTraffic: 'Disk Read Traffic ', + diskWriteTraffic: 'Disk Write Traffic ', + diskReadWriteIOPSUnit: 'Disk Read/Write IOPS(次/秒)', + diskReadWriteIOPS: 'Disk Read/Write IOPS', + diskReadIOPS: 'Disk Read IOPS', + diskWriteIOPS: 'Disk Write IOPS', + netWorkBpsUnit: 'Network Ingress/Egress Traffic (bps)', + netWorkBps: 'Network Ingress/Egress Traffic ', + netWorkIn: 'Network Ingress Traffic', + netWorkOut: 'Network Egress Traffic', + netWorkPackagesNumUnit: 'Network Ingress/Egress Packets(个/秒)', + netWorkPackagesNumber: 'Network Ingress/Egress Packets', + netWorkInPackageNum: 'Network Ingress Packets', + netWorkOutPackageNum: 'Network Egress Packets', + averageLoad1MinUnit: 'Load Average 1min', + averageLoad1Min: 'Load Average 1min', + averageLoad5MinUnit: 'Load Average 5min', + averageLoad5Min: 'Load Average 5min', + averageLoad15MinUnit: 'Load Average 15min', + averageLoad15Min: 'Load Average 15min', + totalTCPConnectionsUnit: 'Total TCP Connections(个)', + totalTCPConnections: 'Total TCP Connections', + normalTCPConnectionsUnit: 'Established TCP Connections(个)', + normalTCPConnections: 'Established TCP Connections', + totalNumberOfProcessesUnit: 'Total Process Count(个)', + totalNumberOfProcesses: 'Total Process Count' + } + }, + messageDelete: { + header: { + messageDelete: 'Delete Message' + }, + tips: 'Once deleted, the message cannot be recovered. Are you sure you want to delete it?' + }, + myMessage: { + day90: 'Reminder 90 days before', + day30: 'Reminder 30 days before', + day15: 'Reminder 15 days before', + expired: 'License expired reminder', + header: { + myMessage: 'Message List', + title: '(Total {0},', + title2: 'of which are unread)', + }, + radioGroup: { + all: 'All', + read: 'Read', + noRead: 'Unread' + }, + search: { + title: 'Message Content', + placeholder: 'Please enter the message content' + }, + table: { + expired: 'Expired', + tip15: '', + tip30: '', + tip90: '', + systemMessages: 'system', + faultMessages: 'oob-monitor', + operationMessages: 'operation', + inbondAlert: 'inbond-alert', + remind: 'Remind', + failureNotification: 'Failure Notification', + alarmTips: 'Alarm Reminder' + }, + label: { + messageContent: 'Message Content', + finishTime: 'Receiving Time', + messageType: 'Message Type', + messageSubType: 'Message Sub Type' + }, + footer: { + tips: 'Please select message', + delete: 'Delete', + read: 'Mark as read' + } + }, + customFilter: { + placeholder: 'Please Enter', + btn: { + confirm: 'Confirm', + reset: 'Reset' + } + }, + messageDetail: { + header: { + title2: 'Message Detail', + renewImmediately: 'Renew now' + }, + label: { + optContent: 'Operation Content', + optPeople: 'Operator', + optTime: 'Operation Time', + versionName: 'Version Name', + version: 'Version', + startTime: 'Start Time', + licenseEndTime: 'Expiration Time', + licenseStatus: 'License Status', + faultType: 'Fault Type', + faultDesc: 'Fault Description', + faultAlarmTime: 'Fault alarm time', + alarmNum: 'Number of alarms', + }, + optTips: { + title: 'The following are the details of the operation content:', + label: { + instanceName: 'Instance Name', + instanceId: 'Instance Id' + }, + instance: 'Examples of', + current: 'Current' + }, + footer: { + pre: 'Previous', + next: 'Next' + }, + failureNotification: 'Failure Notification', + alarmTips: 'Alarm Reminder', + remind: 'Remind', + tip0: 'Hello {0} user! ', + tip: 'Hello {0} user!Operation failed. Please try again or contact the administrator for assistance.', + tip1: '', + tip11: 'has expired, ', + tip2: ' You can continue to use the cloud platform functions normally after renewal.', + tip3: '', + tip4: 'Here is an overview of the operation:', + tip5: '', + tip6: 'The following are the fault details:', + tip7: '【Monitoring Alarm】', + day90: '', + day30: '', + day15: '', + expired: '', + systemMessages: 'system', + faultMessages: 'oob-monitor', + operationMessages: 'operation', + inbondAlert: 'inbond-alert', + status: { + effective: 'Effective', + expired: 'Expired', + } + }, + messageSettings: { + header: { + messageSettings: 'Message Settings' + }, + label: { + emailPush: 'Associated email push', + ipAddress: 'Mail Server', + port: 'Mail Server Port', + emailAddress: 'Email Address', + emailPassword: 'Email Password', + testEmail: 'Test email receiving address' + }, + placeholder: { + ipAddress: 'Please enter the SMTP server address for your email', + port: 'Please enter the email server port', + emailAddress: 'Please enter the email address that needs to be configured', + emailPassword: 'Please enter your email password', + testEmail: 'Please enter the test email receiving email address' + }, + empty: { + ipAddress: 'The mail server cannot be empty', + port: 'The email server port cannot be empty', + emailAddress: 'Email address cannot be empty', + emailPassword: 'Email password cannot be empty', + testEmail: 'Test email receiving email cannot be empty' + }, + errorTip: { + port: 'Only numbers can be entered, range 1-65535', + emailAddress: 'Please enter the correct email address', + emailPassword: 'Please enter the correct email password', + testEmail: 'Please enter the correct email address' + }, + tips: { + pushTip: 'Enable email push, allowing users to receive email messages while receiving messages within the site;
' + 'Turn off email push, users can only receive internal messages and cannot receive email messages.', + checkTip: 'Used to verify whether the email configuration information is normal.
Click the [Save and Verify] button below to send a test email to check
whether the specified mailbox can receive the email notification.
There will be a certain delay in the email receiving process, please wait patiently.' + }, + footer: { + success: 'Verified', + save: 'Save and verify', + checkInfo: 'Verify email information' + } + }, + emailPush: { + start: { + title: 'Enable email push', + content: 'Please confirm to enable email push. Once enabled, users will receive email reminders synchronously when receiving internal messages.' + }, + close: { + title: 'Turn off email push', + content: 'Please confirm to turn off email push. After turning it off, users can accept internal messages and will not be able to receive email reminders.' + } + }, + userInfo: { + emptyTip: { + userName: 'Username input cannot be empty', + password: 'Password input cannot be empty', + cellPhone: 'Mobile phone number cannot be empty', + email: 'Email input cannot be empty' + }, + errorTip: { + number: 'Only numbers can be entered', + userName: '1-64 characters, only numbers, letters, underscore “_” and hyphen “-” are supported', + password: "Password: 8-30 characters, and simultaneously including three types (Capital letters, lowercase letters, numbers or special characters ()`~!{'@'}#{'$'}%&*_-+={'|'}{'{'}{'}'}[]:<>,.?/)", + repeatUserName: 'Duplicated Username', + cellPhone: 'Please enter the correct mobile phone number', + email: 'Please enter the correct email address', + HongKong: 'Please enter the correct mobile phone number in HongKong, China', + MacaMacao: 'Please enter the correct mobile phone number in Macau, China', + Taiwan: 'Please enter the correct mobile phone number in Taiwan, China' + } + }, + login: { + header: { + title: 'BMP-Operating Support Playtform STD', + title2: 'BMP-Operating Support Playtform Pro' + }, + formSubmit: { + title: 'Welcome Back', + placeholder: { + userName: 'Username', + passWord: 'Password' + }, + toolTip: 'UserName does not exist password error', + login: 'Login' + } + }, + loginOut: { + title: 'Log out', + tip: 'Confirm to login out', + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + navigationHeader: { + title: 'BMP-Operating Support Playtform STD', + title2: 'BMP-Operating Support Playtform Pro', + myProfile: 'My Profile', + securitySettings: 'Security Settings', + apiKey: 'Personal API Keys', + loginOut: 'Login Out' + }, + navigationBar: { + list: { + computerRoomManagement: 'Data Center (DC)', + modelManagement: 'Instance Type (IT)', + imageManagement: 'Image', + deviceManagement: 'Device', + roleManagement: 'Role', + userManagement: 'User', + inBandMonitoringManagement: 'In-band monitoring management', + surveillanceManagement: 'Out-of-band monitoring and management', + messageCenter: 'Messages Center', + userCenter: 'Personal Center' + }, + children: { + hardwareAlarmStatus: 'Hardware Device Status', + resourceEcharts: 'Resource monitoring graph', + historyAlarmInfo: 'Historical alarm information', + allAlarmRules: 'All alarm rules', + faultAlarmLog: 'Alarm Log', + faultAlarmRules: 'Alarm Rules', + myMessages: 'My Messages', + messageSet: 'Message Settings' + } + }, + export: { + title: 'Custom Export', + content: { + scope: 'Export Scope:', + all: 'Export All', + Selected: 'Export Selected instance', + search: 'Export Search result' + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + idcList: { + header: { + idcList: 'Idc List', + operate: { + refresh: 'Refresh', + setUp: 'Settings', + export: 'Export' + } + }, + content: { + name: 'Name', + englishCode: 'English Name', + grade: 'Level', + address: 'Address', + createTime: 'Created Time', + createPeople: 'Creator', + updateTime: 'Update Time', + updatePeople: 'Updater', + operate: { + name: 'Actions', + edit: 'Edit' + } + } + }, + idcDetail: { + header: { + title: 'Idc List', + title2: 'Idc Detail', + operate: { + name: 'Actions', + edit: 'Edit' + } + }, + basicInfo: { + title: 'Account Basics', + label: { + name: 'Name', + englishCode: 'English Name', + grade: 'Level', + address: 'Address', + total: 'Cabinet Total', + createTime: 'Created Time', + createPeople: 'Creator', + updateTime: 'Update Time', + updatePeople: 'Updater' + } + }, + allAdministration: { + title: 'General Settings', + name: 'Name', + loginAccount: 'OOB IPMI', + loginUserName: 'Login Name', + loginPassWord: 'Login Password', + switchboardOneNum: 'Ethernet switch #1', + switchboardTwoNum: 'Ethernet switch #2', + } + }, + securityVerification: { + header: { + verification: 'Security Check' + }, + label: { + userName: 'Username', + passWord: 'Password' + }, + placeholder: { + userName: 'Username', + passWord: 'Password' + }, + empty: 'Password input cannot be empty', + errTip: { + userName: 'Username does not exist or password is wrong', + passWord: 'Username does not exist or password is wrong', + currencyPassword: 'Please enter 6-64 characters' + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + editIdc: { + header: { + name: 'Edit Data center (DC)' + }, + iptInfo: { + other: 'Other' + }, + label: { + computerRoomName: 'Name', + computerRoomCode: 'English Name', + computerRoomGrade: 'Level', + computerRoomAddress: 'Address', + outsideLoginAccountNum: 'OOB IPMI Username', + outsideLoginPsd: 'OOB IPMI Password', + switchboardOneNum: 'Ethernet switch #1 login Username', + switchboardOnePsd: 'Ethernet switch #1 login Password', + switchboardTwoNum: 'Ethernet switch #2 login Username', + switchboardTwoPsd: 'Ethernet switch #2 login Password' + }, + placeholder: { + computerRoomName: 'please enter the Data center (DC) name', + computerRoomCode: 'please enter the Data center (DC) English name', + computerRoomGrade: 'please choose the Data center (DC) level', + customComputerRoomGrade: 'please enter the customized Data center (DC) level', + computerRoomAddress: 'please enter the Data center (DC) address', + outsideLoginAccountNum: 'please enter the OOB IPMI Username', + outsideLoginPsd: 'please enter the OOB IPMI Password', + switchboardOneNum: 'please enter the Ethernet switch #1 login Username', + switchboardOnePsd: 'please enter the Ethernet switch #1 login Password', + switchboardTwoNum: 'please enter the Ethernet switch #2 login Username', + switchboardTwoPsd: 'please enter the Ethernet switch #2 login Password' + }, + errTip: { + currency: 'Please enter 1-64 characters', + currencyPassword: 'Please enter 1-128 characters', + computerRoomNameEmpty: 'Data center (DC) name cannot be empty', + computerRoomCodeEmpty: 'Data center (DC) English name cannot be empty', + customComputerRoomGrade: 'Customized Data center (DC) level cannot be empty', + computerRoomAddressEmpty: 'Data center (DC) address cannot be empty', + outsideLoginAccountNumEmpty: 'OOB IPMI Username cannot be empty', + outsideLoginPsdEmpty: 'OOB IPMI Password cannot be empty', + switchboardOneNumEmpty: 'Ethernet Switch #1 login Username cannot be empty', + switchboardOnePsdEmpty: 'Ethernet Switch #1 login Password cannot be empty', + switchboardTwoNumEmpty: 'Ethernet Switch #2 login Username cannot be empty', + switchboardTwoPsdEmpty: 'Ethernet switch #2 login Password cannot be empty' + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + customList: { + header: { + name: 'Edit Columns' + }, + text: { + tip: 'Please select the Colume items to display' + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + modelList: { + header: { + modelList: 'Instance Type', + label: { + modelName: 'Type Name', + modelSpecifications: 'Instance Spec (IS)' + }, + placeholder: { + modelName: 'Please enter the type name to search', + modelSpecifications: 'Please enter the type Specifications to search' + }, + operate: { + addModel: 'Add New Type', + refresh: 'Refresh', + setUp: 'Settings', + export: 'Export' + } + }, + content: { + modelName: 'Type Name', + modelType: 'Instance Type', + machineRoomName: 'Name', + machineRoomCode: 'English Name', + architecture: 'Architecture', + bootMode: 'Boot Mode', + modelSpecification: 'Instance Spec (IS)', + image: 'Image', + device: 'Device', + CPU: 'CPU', + storage: 'Memory', + sysDisc: 'System Volume', + sysRAID: 'System Volume RAID Type', + raidConfig: 'RAID Config', + dataDisc: 'Data Volume', + dataRAID: 'Data Volume RAID Type', + networkCard: 'NIC', + networkSettings: 'Network settings', + GPU: 'GPU', + desc: 'Description', + operate: { + name: 'Actions', + edit: 'Edit', + delete: 'Delete', + more: 'More', + addModel: 'Add the same model' + } + }, + tooltip: 'The instance type cannot be deleted, please delete the instances associated with the instance type first', + edit: 'Models associated with devices do not support editing', + }, + modelDetail: { + header: { + title: 'Instance Type ', + title2: 'Model Details', + specifications: 'Specifications', + configParams: 'Config Params', + operate: { + name: 'Actions', + edit: 'Edit', + addModel: 'Add the same model', + delete: 'Delete' + }, + tip: 'The instance type cannot be deleted, please delete the instances associated with the instance type first', + volumeManagement: { + title: 'Volume Management', + label: { + name: 'Volume Name', + type: 'Volume Type', + raidCan: 'RAID Config', + raid: 'RAID Mode', + disk: 'Disk Type', + interfaceType: 'Interface Type', + minNum: 'Minimum capacity of a single disk', + amount: 'Minimum quantity (blocks)', + } + } + }, + tabs: { + basicInfo: { + name: 'Account Basics', + label: { + modelName: 'Type Name', + computerRoomName: 'Name', + modelType: 'Instance Type', + architecture: 'Architecture', + bootMode: 'Boot Mode', + modelSpecifications: 'Instance Spec (IS)', + CPU: 'CPU', + storage: 'Memory', + sysDisc: 'System Volume', + raidConfig: 'RAID Config', + sysRAID: 'System Volume RAID Type', + dataDisc: 'Data Volume', + dataRAID: 'Data Volume RAID Type', + networkCard: 'NIC', + networkSettings: 'Network settings', + GPU: 'GPU', + height: 'Count(U)', + createTime: 'Created Time', + desc: 'Description' + } + }, + relationImage: { + name: 'Associated images', + header: { + addImage: 'Associate an image', + tooltip: 'Only 20 mirrors can be associated' + }, + content: { + label: { + imageName: 'Image Name', + imageType: 'Image Type ', + architecture: 'Architecture', + operateSysPlatform: 'OS Platform', + operateSysVersion: 'OS Version', + partitionModule: 'Partition Module', + addTime: 'Created Time', + operate: { + name: 'Actions', + delete: 'Delete' + } + } + } + } + }, + other: 'Other Classes' + }, + uiPagination: { + total: 'Total {0}', + page: 'Total {0} page', + piecesAndPage: '{0} / page' + }, + addModel: { + header: { + title2: 'Add New Type', + addModel: 'Add New Type' + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + editModel: { + header: { + title2: 'Edit the Instance Type', + editModel: 'Edit the Instance Type' + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + deleteModel: { + header: { + deleteModel: 'Delete the Instance Type', + batchDeleteModel: 'Batch Delete the Instance Type' + }, + content: { + deleteTip: 'After an instance type is deleted, its association with images is also deleted synchronously. If the same instance type is added again, you need to reassociate it with images. Please operate with caution.', + deleteSure: 'Please confirm whether to delete the instance type:{0}?' + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + addImage: { + header: { + addImage: 'Associate an image', + label: { + modelName: 'Type Name', + choose: 'Number of selected mirrors' + } + }, + content: { + label: { + imageName: 'Image Name', + modelName: 'Type Name', + imageType: 'Image Type ', + architecture: 'Architecture', + operateSysPlatform: 'OS Platform', + operateSysVersion: 'OS Version', + sysPartitionModule: 'Sys Vol Partition Template' + } + }, + btn: { + cancel: 'Cancel', + save: 'Save', + sure: 'Confirm' + } + }, + deleteImage: { + header: { + deleteImage: 'Delete the image' + }, + tip: { + text: 'Confirm to delete the associated image', + delete: 'Confirm to delete the image' + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + imageList: { + header: { + imageList: 'Image List', + exportImage: 'Import Image', + operate: { + refresh: 'Refresh', + setUp: 'Settings', + export: 'Export' + } + }, + search: { + placeholder: { + imageName: 'Please enter the image name search', + imageId: 'Please enter the image id search' + }, + condition: { + imageName: 'Image Name', + imageId: 'Image Id' + } + }, + content: { + label: { + imageName: 'Image Name', + imageId: 'Image ID', + imageType: 'Image Type ', + architecture: 'Architecture', + operateSysPlatform: 'OS Platform', + operateSysVersion: 'OS Version', + format: 'Image Format', + bootMode: 'Boot Mode', + sysPartitionModule: 'Sys Vol Partition Template', + imageDesc: 'Image Desp', + numberOfAssociatedModels: 'Associated ITs', + createTime: 'Created Time', + operate: { + name: 'Actions', + delete: 'Delete' + } + } + }, + filter: { + presetImage: 'Preset image', + customImage: 'Custom image' + }, + tooltip: { + title: 'The image cannot be deleted, please delete the image associated with the instance type first', + image: 'Preset image does not support deletion' + } + }, + imageDetail: { + header: { + title2: 'Image Detail', + operate: { + title: 'Actions', + delete: 'Delete' + } + }, + tooltip: { + title: 'The image cannot be deleted, please delete the image associated with the instance type first', + image: 'Preset image does not support deletion', + title2: 'An instance of the current model is being created and cannot be removed' + }, + add: { + model: 'Add New Type' + }, + tabs: { + basicInfo: 'Account Basics', + model: 'Associated Instance' + }, + label: { + imageName: 'Image Name', + imageId: 'Image Id', + imageType: 'Image Type', + architecture: 'Architecture', + operateSysPlatform: 'OS Platform', + operateSysVersion: 'OS Version', + format: 'Image Format', + bootMode: 'Boot Mode', + sysPartitionModule: 'Sys Vol Partition Template', + imageDesc: 'Image Desp', + numberOfAssociatedModels: 'Associated ITs', + createTime: 'Created Time', + }, + table: { + label: { + modelName: 'Type Name', + modelType: 'Instance Type', + idcName: 'Name', + nameEn: 'English Name', + architecture: 'Architecture', + modelSpecifications: 'Instance Spec (IS)', + desc: 'Desc', + operate: { + title: 'Actions', + remove: 'Remove' + } + } + }, + empty: { + title: 'Add New Type' + } + }, + imageAddModel: { + header: { + title: 'Add New Type', + imageName: 'Image Name', + choose: 'Number of instance selected' + }, + label: { + modelName: 'Type Name', + modelType: 'Instance Type', + idcName: 'Name', + nameEn: 'English Name', + architecture: 'Architecture', + modelSpecifications: 'Instance Spec (IS)', + desc: 'Desc' + }, + btn: { + save: 'Save', + cancel: 'Cancel' + } + }, + removeOperate: { + header: { + remove: 'Remove Instance' + }, + content: { + deleteTip: 'Notice : The image version cannot be used when the user creates or reinstalls the type after removal, Please operate with caution.', + tip1: 'Are you sure to remove the [{0}] associated with [{1}{2}]?' + }, + btn: { + sure: 'Save', + cancel: 'Cancel' + } + }, + importImage: { + header: { + title: 'Import Image' + }, + content: { + label: { + imageName: 'Image Name', + architecture: 'Architecture', + operateSysPlatform: 'OS Platform', + operateSysVersion: 'OS Version', + imageFormat: 'Image Format', + bootMode: 'Boot Mode', + systemPartitionTemplate: 'Sys Vol Partition Template', + imageDesc: 'Image Desp', + chooseImage: 'Choose Image' + }, + placeholder: { + imageName: 'please enter the image name', + architecture: 'please select Architecture', + operateSysPlatform: 'please select OS platform', + customVersion: 'please enter the customized OS version', + customOperatePlatform: 'please enter the customized OS platform', + operateSysVersion: 'please select OS version', + imageFormat: 'please select Image Format', + bootMode: 'please select Boot Mode', + imageDesc: 'please enter the image desp', + chooseImage: 'Choose Image' + } + }, + emptyTip: { + imageName: 'Image cannot be empty', + architecture: 'please select Architecture', + operateSysPlatform: 'OS platform cannot be empty', + customVersion: 'please enter the customized OS version', + customOperatePlatform: 'Customized OS platform cannot be empty', + operateSysVersion: 'OS version cannot be empty', + imageFormat: 'please select Image Format', + bootMode: 'please select Boot Mode', + noData: 'No Data' + }, + errTip: { + upload: 'Upload, please do not close the pop-up window', + imageName: 'Please enter 1-64 characters', + imageRepeat: 'Duplicate image name', + numberLimit: 'Image cannot be empty', + error: 'Upload Failed', + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm', + upLoad: 'Upload' + } + }, + collectInfoConfirm: { + header: { + title: 'Re-collect device information and confirm' + }, + tips: 'Please confirm whether to re-acquire device information?', + checkbox: 'Clean RAID', + tipsCount: { + tip0: 'Note:', + tip1: '1. The clean RAID operation is to delete the entire disk RAID. This operation is not recoverable, so please operate with caution!
' + + '2. Clearing the RAID operation will clear all data on the server disk. Please back up the data before performing this operation to avoid data loss and cause you losses.
' + } + }, + clearRaidConfirm: { + header: { + title: 'Clear RAID operation confirmation', + }, + tipsCount: { + tip0: 'Note:', + tip1: '1. The clean RAID operation is to delete the entire disk RAID. This operation is not recoverable, so please operate with caution!
' + + '2. Clearing the RAID operation will clear all data on the server disk. Please back up the data before performing this operation to avoid data loss and cause you losses.
', + tip2: 'The device you selected [{0}] will perform the RAID clear operation. Are you sure about the operation?' + }, + }, + deviceList: { + header: { + deviceList: 'Device List' + }, + radioBtn: { + computed: 'Computer Class', + storage: 'Storage Class', + GPU: 'GPU', + other: 'Other Classes' + }, + batchOperate: { + btn: { + open: 'Start Up', + close: 'Shut Down', + restart: 'Reboot', + recovery: 'Recycling Instance', + edit: 'Edit instance name', + resetPassword: 'Reset Password', + more: 'More' + }, + tip: { + default: 'Please select resource', + turnOn: 'Only support in shutdown status can be powered on', + resetPassword: 'Only support in shutdown status can reset passwords', + restart: 'Only support in running status can be reboot', + turnOff: 'Only support in running status can be shutdown', + instanceName: 'Only created instances support editing', + lock: 'Instance Locked', + recovery: 'Servers that are in the "Shut down"&“Creation failed" statecan be removal' + } + }, + tooltip: { + up: 'Servers that are in the "Stocked" state can be mounted', + model: 'Please associate the model first', + down: 'Servers that are in the "Mounted" state can be unmounted', + delete: 'Servers that are in the "Stocked" state can be deleted', + turnOn: 'Only support in shutdown status can be powered on', + restart: 'Only support in running status can be reboot', + remove: 'Servers that are in the "running"&“Shut down" statecan be removal', + recovery: 'Servers that are in the "Shut down"&“Creation failed" statecan be removal', + lock: 'Instance Locked', + lock1: 'Unable to lock the instance', + lock2: 'Unable to unlock the instance', + reset: 'Only the device that failed the instance operation can perform the "reset instance status" operation', + turnOff: 'Only support in running status can be shutdown', + resetSystem: 'Only support in shutdown status can reinstall the system', + resetPassword: 'Only support in shutdown status can reset passwords' + }, + instanceStatus: { + creating: 'Creating', + starting: 'Starting up', + running: 'Running', + stopping: 'Shutting Down', + stopped: 'Stopped', + restarting: 'Rebooting', + resetting_password: 'Resetting password', + destroying: 'Destroying', + destroyed: 'Destroyed', + error: 'Error', + upgrading: 'Upgrading', + reinstalling: 'Reinstalling System' + }, + operate: { + instanceOperate: 'Instance Operate', + error: { + tip: 'Operation failed, please contact the administrator' + }, + exportDevice: 'Import Device', + placeholder: { + sn: 'Please enter the SN to search', + instanceOwner: 'Please enter the instance owner to search' + }, + label: { + sn: 'SN', + instanceOwner: 'Instance Owner' + }, + refresh: 'Refresh', + setUp: 'Settings', + export: 'Export' + }, + content: { + label: { + sn: 'SN', + name: 'Type Name', + modelName: 'Instance Type', + managementStatus: 'Management Status', + collectionStatus: 'Collection Status', + computerRoomName: 'Name', + cabinetCode: 'Cabinet ID', + uBit: 'Unit Location', + brand: 'Brand', + model: 'Model', + architecture: 'Architecture', + instanceImage: 'Image', + instanceName: 'Instance Name', + instanceID: 'Instance ID', + instanceStatus: 'Instance Status', + lockStatus: 'Locked Status', + instanceOwner: 'Instance Owner', + CPU: 'CPU', + storage: 'Memory', + sysDisc: 'System Volume', + dataDisc: 'Data Volume', + GPU: 'GPU', + switchIPNetworkPortOne: 'Uplink SW IP(Port #1)', + switchIPNetworkPortTwo: 'Uplink SW IP(Port #2)', + networkPortOneUplinkPort: 'Uplink SW Port #1', + networkPortTwoUplinkPort: 'Uplink SW Port #2', + networkSettings: 'Network settings', + outOfBandIP: 'OOB IP', + intranceIPv4: 'Private IPv4(eth0)', + intranceIPv4First: 'Private IPv4(eth1)', + intranetIPv6: 'Private IPv6(eth0)', + intranetIPv6First: 'Private IPv6(eth1)', + createTime: 'Created Time', + desc: 'Description', + remark: 'Remark', + operate: { + name: 'Actions', + up: 'Mount', + down: 'Unmount', + more: 'More', + lock:'Lock', + unlock:'Unlock', + delete: 'Device Delete', + reset: 'Reset instance state', + remove: 'Device Removal', + recovery: 'Recycling Instance', + open: 'Start Up', + close: 'Shut Down', + restart: 'Reboot', + resetSystem: 'Reinstall the system', + resetPassword: 'Reset Password' + } + } + }, + managementStatus: { + warehousing: 'Stocked', + onTheShelf: 'Mounted', + created: 'Created', + onShelf: 'Mounting', + unputaway: 'unputaway', + remove: 'Removed', + lowerShelf: 'Unmounting', + error: 'Mount failed' + }, + status: { + collected: 'Collect', + noCollected: 'No Collect', + collecting: 'Collecting', + collectionFailed: 'Collection Failed' + } + }, + resetSystemConfirm: { + header: { + title: 'Instructions for reinstalling the system', + tip0: 'Note:', + tip: '' + + '1. Reinstalling the system is an operation to initialize the system disk and replace the operating system. This operation is not recoverable, so please operate with caution!
' + + '2. This operation will clear all data on the instance system disk. Please back up the data before reinstalling the system to avoid data loss and cause you losses.
' + + '3. After reinstalling the system, the system will not configure an IPv6 address for the instance by default, and you need to configure it manually.', + tip2: 'The instance [{0}] you selected will perform a system reinstallation operation. Are you sure?' + } + }, + resetSystem: { + header: { + title: 'Reinstall system configuration', + tip0: 'Note:', + tip: '' + + '1. Reinstalling the system is an operation to initialize the system disk and replace the operating system. This operation is not recoverable, so please operate with caution!
' + + '2. This operation will clear all data on the instance system disk. Please back up the data before reinstalling the system to avoid data loss and cause you losses.
' + + '3. After reinstalling the system, the system will not configure an IPv6 address for the instance by default, and you need to configure it manually.', + instanceInfo: 'Instance Info', + imageType: 'Image Type', + system: 'System Volume', + systemPartition: 'System Volume Partition', + systemVolume: 'System Volume', + systemVolumePartition: 'System Volume Partition', + bootMode: 'Boot Mode', + hostName: 'HostName', + userName: 'UserName', + setPassword: 'Set Password', + password: 'Password', + confirmPassword: 'Confirm Password', + performanceMonitoring: 'Performance Monitoring', + agent: 'Install monitoring agent' + }, + table: { + label: { + instanceName: 'Instance Name', + instanceID: 'Instance ID', + operatingSystem: 'Operating System', + createdTime: 'Created Time', + sshName: 'Key Name' + } + }, + placeholder: { + select: 'Please Select', + hostName: 'Optional, computer name within the operating system' + }, + regCheckTip: { + hostName: 'It contains 2-64 characters in length and can be segmented into several sections with the separator (.). Uppercase and lowercase letters, numbers or hyphens (-) can be used in each section, but the dot (.) or the hyphen (-) cannot be continuously used in each section. It cannot start or end with a dot (.) or a hyphen (-).', + password: "Password: 8-30 characters, and simultaneously including three types (Capital letters, lowercase letters, numbers or special characters ()`~!{'@'}#{'$'}%&*_-+={'|'}{'{'}{'}'}[]:<>,.?/)", + password2: 'The passwords are inconsistent, please re-enter' + }, + emptyCheck: { + sshKey: 'Key cannot be empty', + password: 'Password cannot be empty', + confirmPassword: 'Confirm password cannot be empty', + repeat: 'The passwords are inconsistent, please re-enter' + }, + radio: { + customPassword: 'Customized Password', + sshKeyLogin: 'Key pair login' + }, + tip1: 'Provide real-time fault alarm' + }, + resetPassword: { + header: { + title: 'Reset Password', + tip: 'Note: After resetting the password, you need to power on the instance in the console/operation platform to take effect.', + resetPassword1: 'The ', + resetPassword2: ' instances you selected will be Edit reset password, Are you sure about the action?', + }, + table: { + label: { + instanceName: 'Instance Name', + instanceId: 'Instance Id', + outOfBandIP: 'OOB IP', + intranceIPv4: 'Private IPv4(eth0)', + } + }, + ipt: { + label: { + password: 'Password', + newPassword: 'New Password', + confirmPassword: 'Confirm Password' + }, + errorTip: { + password: "Password: 8-30 characters, and simultaneously including three types (Capital letters, lowercase letters, numbers or special characters ()`~!{'@'}#{'$'}%&*_-+={'|'}{'{'}{'}'}[]:<>,.?/)", + newPassword: "Password: 8-30 characters, and simultaneously including three types (Capital letters, lowercase letters, numbers or special characters ()`~!{'@'}#{'$'}%&*_-+={'|'}{'{'}{'}'}[]:<>,.?/)", + confirmPassword: 'The passwords are inconsistent, please re-enter' + }, + emptyTip: { + password: 'Password cannot be empty', + newPassword: 'New password cannot be empty', + confirmPassword: 'Confirm password cannot be empty' + } + } + }, + batchOperate: { + instanceName: { + title: 'Edit instance name in batches', + tip: 'Notice: The names of multiple instances edited in this way are named consecutively', + tip1: 'The ', + tip2: ' instances you selected will be Edit instance name, Are you sure about the action?', + label: { + instanceName: 'Instance Name', + instanceId: 'Instance Id', + outOfBandIP: 'OOB IP', + intranceIPv4: 'Private IPv4(eth0)', + newInstanceName: 'New instance name' + }, + iptTip: { + text: '2-128 characters, starting with uppercase and lowercase letters or Chinese, can contain numbers, ".", "_", ":" or "-"', + empty: 'Instance name cannot be empty', + repeat: 'Duplicate instance name' + } + }, + recoveryInstance: { + title: 'Batch Recycling instance', + tip: 'Note: Recycling will clear all data on the instance, please operate with caution.', + recovery1: 'The ', + recovery2: ' instances you selected will be recycled, Are you sure about the action?', + label: { + instanceName: 'Instance Name', + instanceId: 'Instance Id', + outOfBandIP: 'OOB IP', + intranceIPv4: 'Private IPv4(eth0)' + }, + }, + openCloseRestart: { + open: 'Batch Startup', + close: 'Batch Shutdown', + restart: 'Batch Reboot', + open1: 'The ', + open2: ' instances you selected will be startup, Are you sure about the action?', + close1: 'The ', + close2: ' instances you selected will be shutdown, Are you sure about the action?', + restart1: 'The ', + restart2: ' instances you selected will be reboot, Are you sure about the action?', + label: { + instanceName: 'Instance Name', + instanceId: 'Instance Id', + outOfBandIP: 'OOB IP', + intranceIPv4: 'Private IPv4(eth0)' + } + }, + resetPassword: { + header: { + title: 'Batch password reset', + tip: 'Note:
' + + '1. Multiple instances whose passwords are reset in this way have the same password.
' + + '2. After resetting the password, you need to power on the instance in the console/operation platform to take effect.', + resetPassword1: 'The ', + resetPassword2: ' instances you selected will be Edit reset password, Are you sure about the action?', + }, + table: { + label: { + instanceName: 'Instance Name', + instanceId: 'Instance Id', + outOfBandIP: 'OOB IP', + intranceIPv4: 'Private IPv4(eth0)', + } + }, + ipt: { + label: { + password: 'Password', + newPassword: 'New Password', + confirmPassword: 'Confirm Password' + }, + errorTip: { + password: "Password: 8-30 characters, and simultaneously including three types (Capital letters, lowercase letters, numbers or special characters ()`~!{'@'}#{'$'}%&*_-+={'|'}{'{'}{'}'}[]:<>,.?/)", + newPassword: "Password: 8-30 characters, and simultaneously including three types (Capital letters, lowercase letters, numbers or special characters ()`~!{'@'}#{'$'}%&*_-+={'|'}{'{'}{'}'}[]:<>,.?/)", + confirmPassword: 'The passwords are inconsistent, please re-enter' + }, + emptyTip: { + password: 'Password cannot be empty', + newPassword: 'New password cannot be empty', + confirmPassword: 'Confirm password cannot be empty' + } + } + } + }, + lockInstance: { + header: { + lock:'Lock', + unlock:'Unlock', + }, + lockTip: 'Confirm to lock the instance【{0}】?', + unlockTip: 'Confirm to unlock the instance【{0}】?', + tip: 'The "Delete" action is forbidden after the instance is locked.If you want to use it, you need to unlock it in advance.', + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + associatedModel: { + header: { + title: 'Associated Models' + }, + content: { + select: 'Select Model', + placeholder: 'Please select the model', + addNewModel: 'add a model', + table: { + label: { + volumeName: 'volume Name', + volumeType: 'volume Type', + raidCan: 'RAID Config', + raid: 'RAID Mode', + diskType: 'Disk Type', + interfaceType: 'InterfaceType', + minNum: 'Minimum capacity of a single disk', + minimumQuantity: 'Minimum quantity (blocks)', + associatedDisk: 'Associated Disk' + }, + diskPlaceholder: 'Please select a disk' + } + } + }, + deviceDetail: { + header: { + deviceList: 'Device List', + title2: 'Device Detail' + }, + operate: { + name: 'Actions', + up: 'Mount', + down: 'Unmount', + open: 'Start Up', + close: 'Shut Down', + restart: 'Reboot', + reset: 'Reset instance state', + remove: 'Device Removal', + recovery: 'Recycling Instance', + lock:'Lock', + unlock:'Unlock', + delete: 'Device Delete', + resetSystem: 'Reinstall the system', + resetPassword: 'Reset Password', + error: { + tip: 'Operation failed, please contact the administrator' + } + }, + tooltip: { + up: 'Servers that are in the "Stocked" state can be mounted', + model: 'Please associate the model first', + associatedModels: 'Servers that are in the "stocked" state can be associated with machine models', + down: 'Servers that are in the "Mounted" state can be unmounted', + delete: 'Servers that are in the "Stocked" state can be deleted', + remove: 'Servers that are in the "running"&“Shut down" statecan be removal', + recovery: 'Servers that are in the "Shut down"&“Creation failed" statecan be removal', + lock: 'Instance Locked', + lock1: 'Unable to lock the instance', + lock2: 'Unable to unlock the instance', + reset: 'Only the device that failed the instance operation can perform the "reset instance status" operation', + turnOn: 'Only support in shutdown status can be powered on', + restart: 'Only support in running status can be reboot', + turnOff: 'Only support in running status can be shutdown', + resetSystem: 'Only support in shutdown status can reinstall the system', + resetPassword: 'Only support in shutdown status can reset passwords' + }, + deviceInfo: { + deviceInfo: 'Device Details', + sn: 'SN', + modelName: 'Type Name', + recapture: 'Recapture', + managementStatus: 'Management status', + collectionStatus: 'Collection Status', + computerRoomName: 'Name', + cabinetCode: 'Cabinet ID', + uBit: 'Unit Location', + remark: 'Remark' + }, + instanceInfo: { + instanceInfo: 'Instance Info', + instanceName: 'Instance Name', + instanceID: 'Instance ID', + instanceImage: 'Image', + instanceStatus: 'Instance Status', + monitorAgentStatus: 'Monitor Agent status', + lockStatus: 'Locked Status', + instanceOwner: 'Instance Owner', + createTime: 'Created Time', + desc: 'Description' + }, + hardwareConfiguration: { + modelInfo: 'Model Info', + hardwareConfiguration: 'Hardware Details', + brand: 'Brand', + model: 'Model', + architecture: 'Architecture', + CPU: 'CPU', + storage: 'Memory', + sysDisc: 'System Volume', + adapeterId: 'Adapter_id (RAID card)', + enclosure1: 'System Volume 1 enclosure #', + slot1: 'System Volume 1 slot #', + enclosure2: 'System Volume 2 enclosure #', + slot2: 'System Volume 2 slot #', + dataDisc: 'Data Volume', + GPU: 'GPU', + networkCard: 'NIC', + networkSettings: 'Network settings' + }, + networkInfo: { + networkInfo: 'Network Details', + intranceIPv4: 'Private IPv4(eth0)', + intranceIPv4First: 'Private IPv4(eth1)', + intranetIPv6: 'Private IPv6(eth0)', + intranetIPv6First: 'Private IPv6(eth1)', + mac1: 'MAC1(eth0)', + mac2: 'MAC2(eth1)', + switchIPOne: 'NIC port 1 switch IP(eth0)', + switchIPTwo: 'NIC port 2 switch IP(eth1)', + switchUplinkPortOne: 'NIC port 1 (eth0) switch port', + switchUplinkPortTwo: 'NIC port 2 (eth1) switch port', + subnetMask: 'subnet mask(eth0)', + subnetMaskFirst: 'subnet mask(eth1)', + networkGateway: 'gateway' + }, + switchOutsideInfo: { + switchOutsideInfo: 'Switches & Out-of-Band Information', + userName1: 'NIC port 1 uplink switch login username', + password1: 'NIC port 1 uplink switch login password', + userName2: 'NIC port 2 uplink switch login username', + password2: 'NIC port 2 uplink switch login password', + outOfBandIP: 'OOB IP', + outOfBandLoginUserName: 'OOB IPMI Username', + outOfBandLoginPassWord: 'OOB IPMI Password' + }, + editDesc: { + header: { + title: 'Description', + title2: 'Notes' + }, + count: { + title: 'Modification Description:', + title2: 'Modification Notes:' + }, + placeholder: 'Please enter description', + placeholder2: 'Please enter notes', + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + tabs: { + baseInfo: 'Account Basics', + diskDetail: 'Disk Details', + hardwareMonitoring: 'Hardware Monitoring', + performanceMonitoring: 'Performance Monitoring', + operatLog: 'Operation Log' + }, + diskDetail: { + physicalDiskView: 'Physical disk view', + table: { + label: { + disk: 'Disk', + singleDiskCapacity: 'Single disk capacity', + diskType: 'Disk Type', + interfaceType: 'Interface Type', + enclosure: 'enclosure', + slot: 'slot' + } + }, + logicalDriveView: 'Logical disk view', + table2: { + label: { + driveLetterName: 'Driver Name', + singleDiskCapacity: 'Single disk capacity', + diskType: 'Disk Type', + interfaceType: 'Disk Interface', + } + }, + modelInfo: 'Model Info', + modelRolInfo: 'Model roll information', + modelName: 'Type Name', + btn: 'Associated Instance', + volumeManager: { + table: { + label: { + volumeName: 'volume Name', + volumeType: 'volume Type', + raid: 'RAID Mode', + diskType: 'Disk Type', + interfaceType: 'Interface Type', + minNum: 'Minimum capacity of a single disk', + minimumQuantity: 'Minimum quantity (blocks)', + associatedDisk: 'Associated Disk' + } + } + } + }, + hardwareMonitoring: { + hardwareDeviceStatus: 'Hardware Device Status', + alarmLogList: 'Alarm log list', + status: { + title: { + cpu: 'CPU', + storage: 'Memory', + hardDisk: 'Hard Disk', + networkCard: 'NIC', + powerSupply: 'Power Supply', + other: 'Other' + }, + normal: 'Normal', + error: 'Abnormal' + } + }, + table: { + label: { + serialNumber: 'Number', + faultType: 'Fault Type', + faultDesc: 'Fault Description', + faultAlarmTime: 'Fault alarm time', + updateTime: 'Update Time', + alarmNum: 'Number of alarms', + status: 'Status' + } + }, + status: { + collected: 'Collect', + noCollected: 'No Collect', + collecting: 'Collecting', + collectionFailed: 'Collection Failed' + }, + operatLog: { + header: { + title: 'Operation Log', + tips: '(The following list includes operation records from the past 90 days)' + }, + search: { + label: { + operatePeople: 'Operator', + operateTime: 'Operation Time', + }, + placeholder: { + operatePeople: 'Please enter the operator', + startDate: 'Start Date', + endDate: 'End Date' + }, + btn: { + search: 'Search', + clear: 'Clear' + } + }, + table: { + label: { + logId: 'LogID', + operateName: 'Operation Name', + operatePeople: 'Operator', + operateTime: 'Operation Time', + operateFeedback: 'Operation Feedback', + failCode: 'Fault Info' + } + } + } + }, + editDesc: { + header: { + title: 'Description', + title2: 'Notes' + }, + count: { + title: 'Modification Description:', + title2: 'Modification Notes:' + }, + placeholder: 'Please enter description', + placeholder2: 'Please enter notes', + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + removeRecovery: { + header: { + remove: 'Device Removal', + recovery: 'Recycling Instance' + }, + tooltip: { + remove: 'Please confirm whether to remove the following device?', + recovery: 'Please confirm whether to recycle the following instances?' + }, + checkbox: { + remove: 'I have understood the above precautions and agree to device removal', + recovery: 'I have understood the above precautions and agree to recycle the instance' + }, + operateTip: { + remove: 'Notice:
' + + '1. After the device is removed, the console will not display this instance, and this instance will not enter the inventory and cannot be purchased again
' + + '2. Automatically disassociate the device from the instance owner', + recovery: 'Notice:
' + + '1. After the recovery instance operation is completed, the device is re-entered into the warehouse, and the association between the device and the instance owner is automatically released
' + + '2. To avoid data loss, please confirm that the data has been backed up. The instance recovery operation will clear all data on the instance (including the system disk and data disk), and the instance will be completely deleted and cannot be restored' + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + resetInstance: { + header: { + title: 'Reset instance state' + }, + tooltip: { + title: 'Notice:
' + 'reset instance state action reset instance state to last instance stable state', + count: { + tip1: 'Confirm', + tip2: 'reset the instance status?' + } + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + importDevice: { + header: { + title: 'Import Device' + }, + label: { + computerRoomName: 'Name', + modelName: 'Type Name', + deviceInfo: 'Device Details' + }, + placeholder: { + computerRoomName: 'please select data center name', + modelName: 'please select instance type', + }, + errTip: { + upload: 'Upload, please do not close the pop-up window', + computerRoomName: 'Data center (DC) name cannot be empty', + modelName: 'Type name cannot be empty', + deviceInfo: 'Device Details cannot be empty', + error: 'Upload Failed', + }, + noData: { + tip: 'No Data' + }, + operate: { + tip1: 'If there is no suitable model, you can', + addNewModel: ' add a model', + templateDownLoad: 'Template Download' + }, + btn: { + selectionFile: 'Select a file', + cancel: 'Cancel', + sure: 'Confirm' + }, + tooltip: { + first: '1. Only 1 attachment can be selected, and the size is not more than 20M;', + two: '2. To make a successful upload, please do not modify the colume cells in the template;', + third: '3. Only one file can be uploaded, multiple file uploads will replace the original file;' + } + }, + upDownFrame: { + operate: { + addNewModel: 'add a model' + }, + placeholder: { + tip1: 'Please Select', + tip2: 'The associated disk cannot be empty' + }, + table: { + label: { + volumeName: 'volume Name', + volumeType: 'volume Type', + raidCan: 'RAID Config', + raid: 'RAID Mode', + diskType: 'Disk Type', + interfaceType: 'Interface Type', + minNum: 'Minimum capacity of a single disk', + amount: 'Minimum quantity (blocks)', + associatedDisk: 'Associated Disk' + } + }, + noData: { + tip: 'No Data' + }, + steps: { + title1: 'Associated Instance', + title2: 'Confirm Device' + }, + select: { + model: 'Select Model', + placeholder: 'Please select the model' + }, + titleTip: { + up: 'Mount', + down: 'Unmount', + delete: 'Device Delete' + }, + countTitleTip: { + down: 'Note: After the server is successfully umounted, its status will be changed to "Stocked"', + delete: 'Note: After the server is deleted, it cannot be undone. The server needs to be re-imported if it needs to be used again' + }, + headerTitleTip: { + up: 'Servers can only be launched as instances after they are mounted. Please confirm whether to mount the following servers?', + down: 'Please confirm whether to unmount the following servers?', + delete: 'Please confirm whether to delete the following servers?' + }, + btn: { + pre: 'Previous', + next: 'Next step', + cancel: 'Cancel', + sure: 'Confirm' + } + }, + publicTable: { + label: { + sn: 'SN', + instanceName: 'Instance Name', + instanceId: 'Instance Id', + instanceOwner: 'Instance Owner', + cabinetCode: 'Cabinet ID', + uBit: 'Unit Location', + outOfBandIP: 'OOB IP', + intranceIPv4: 'Private IPv4(eth0)' + } + }, + openShutDownRestart: { + titleTip: { + open: 'Start Up', + close: 'Shut Down', + restart: 'Reboot' + }, + tooltipInfo: { + open: 'Confirm to start up the instances:', + close: 'Confirm to shutdown the instances:', + restart: 'Confirm to reboot the instances:' + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + modelForm: { + header: { + params: { + text1: 'General parameters', + text2: 'Configuration parameters' + } + }, + config: { + configured: 'Configured RAID', + notConfigured: 'Not Configured RAID' + }, + radioBtn: { + computed: 'Computer Class', + storage: 'Storage Class', + GPU: 'GPU', + other: 'Other Classes' + }, + raid: 'RAID0-stripping', + none: 'none', + unrestricted: 'not limited', + netWork: { + single: 'Single Network Interface', + dual: 'Double Network Interfaces', + bond: 'Single Network port bond' + }, + specificationsType: { + presetSpecifications: 'Preset Specifications', + otherSpecifications: 'Other specifications' + }, + tooltip: { + tip: ' Add a new model using model {0} as a template', + title: 'Instance Spec (IS) corresponds to the Type name one by one.
It is recommended to use [Specification Attribute]+[Instance Type]+[Architecture].
Example: c1.medium.x86' + }, + noData: { + tip: 'No Data' + }, + list: { + manufacturer: 'Godson No.3' + }, + label: { + computerRoomName: 'Name', + modelType: 'Instance Type', + modelName: 'Type Name', + architecture: 'Architecture', + system: 'system', + data: 'data', + bootMode: 'Boot Mode', + modelSpecifications: 'Instance Spec (IS)', + desc: 'Description', + cpu: 'CPU', + cpuParams: 'CPU Parameters', + processorManufacturer: 'CPU manufacturer', + modelChoose: 'Model', + numberPhysicalCores: 'physical cores', + dominantFrequency: 'Clock Speed (GHz)', + numberOfRoutes: 'Quantity', + storage: 'Memory', + card: 'RAID controller', + storageParams: 'Memory Parameters', + interface: 'interface', + dominantFrequencyMHz: 'Clock Speed (MHz)', + capacity: 'Capacity (GB)', + modelNumber: 'Quantity', + sysType: 'System volume disk type', + sysInterfaceType: 'System volume disk interface', + sysSingleCapacityVal: 'System volume single disk capacity', + sysNumber: 'Number of system volume disks', + raidConfig: 'RAID Config', + sysRAID: 'System Volume RAID Type', + dataType: 'Data volume disk type', + dataInterfaceType: 'Data volume disk interface', + dataSingleCapacityVal: 'Data volume single disk capacity', + dataNumber: 'Number of data volume disks', + networkSpeed: 'NIC speed (GE)', + networkNumber: 'Number of NIC ports', + networkSettings: 'Network settings', + gpuBrand: 'GPU(Brand)', + gpuModel: 'GPU(Model)', + gpuNumber: 'Number of GPUs (number)', + heightU: 'Count(U)', + volumeManage: { + title: 'Volume Management', + label: { + name: 'Volume Name', + type: 'Volume Type', + raidCan: 'RAID Config', + raid: 'RAID Mode', + disk: 'Disk Type', + interfaceType: 'Interface Type', + minNum: 'Minimum capacity of a single disk', + amount: 'Minimum quantity (blocks)', + operate: 'Operate' + }, + placeholder: { + tip1: 'Please Enter' + }, + sys: { + tip1: 'Add at least one system volume', + tip2: 'Only one system volume can be added' + }, + save: { + volumeManagement: 'Please save volume management', + empty: 'Volume management cannot be empty' + }, + empty: { + name: 'Volume name cannot be empty', + type: 'Please select volume type', + raidCan: 'Please select a RAID configuration', + raid: 'Please select RAID mode', + disk: 'Please select the hard disk type', + interfaceType: 'Please select the interface type', + minNum: 'The minimum capacity of a single disk cannot be empty', + amount: 'Amount cannot be empty' + }, + btn: { + cancel: 'Cancel', + add: 'Add Volume', + sure: 'Sure', + save: 'Save', + edit: 'Edit', + delete: 'Delete' + } + } + }, + placeholder: { + modelName: 'Please enter the instance type name (1-64 characters)', + modelSpecifications: 'Please enter the instance specification', + desc: 'please enter a description', + select: 'please select an option', + processorManufacturer: 'please select a CPU manufacturer', + modelChoose: 'please select a CPU Model', + dominantFrequency: 'please enter the Clock Speed (GHz)', + interface: 'please select interface', + dominantFrequencyMHz: 'please select Clock Speed (MHz)', + capacity: 'please select Capacity (GB)', + sysType: 'please select system volume disk type', + sysInterfaceType: 'please select system volume disk interface', + sysSingleCapacityVal:'please enter the system volume single disk capacity', + raidConfig: 'Please select a RAID configuration', + sysRAID: 'please select system volume RAID mode', + dataType: 'please select data volume disk type', + dataInterfaceType: 'please select data volume disk interface', + dataSingleCapacityVal: 'please enter the data volume single disk capacity', + networkSpeed: 'please select NIC speed (GE)', + networkSettings: 'please select bond mode', + gpuBrand: 'please select GPU(Brand)', + gpuModel: 'please select GPU(Model)', + heightU: 'please select Count(U)' + }, + emptyTip: { + modelName: 'Type name cannot be empty', + modelSpecifications: 'Instance specification cannot be empty', + cpu: 'CPU cannot be empty', + processorManufacturer: 'Manufacturer cannot be empty', + modelChoose: 'Model input cannot be empty', + dominantFrequency: 'Clock Speed (GHz)cannot be empty', + storage: 'memory cannot be empty', + interface: 'interface cannot be empty', + dominantFrequencyMHz: 'Clock Speed (MHz)cannot be empty', + capacity: 'Capacity (GB) cannot be empty', + sysType: 'System volume disk type cannot be empty', + sysInterfaceType: 'System volume disk interface type cannot be empty', + sysSingleCapacityVal: 'System volume Single Disk Capacity cannot be empty', + raidConfig: 'RAID configuration cannot be empty', + sysRAID: 'The system volume RAID mode cannot be empty', + dataType: 'Data volume disk type cannot be empty', + dataInterfaceType: 'Data volume disk interface cannot be empty', + dataSingleCapacityVal: 'Data volume Single Disk Capacity cannot be empty', + networkSpeed: 'NIC speed (GE) cannot be empty', + networkSettings: 'Bond mode cannot be empty', + gpuBrand: 'GPU(brand) cannot be empty', + gpuModel: 'GPU(model) cannot be empty', + heightU: 'Count(U)cannot be empty' + }, + errorTip: { + number: '1-64 characters, the input content is a number, and the decimal point is allowed', + number1: 'Only numbers can be entered', + title: 'Please enter a valid mobile phone number', + number2: 'Only numbers can be entered, with 2 decimal places reserved', + number3: 'Exceeding maximum limit', + currency: '1-64 characters, only chinese numbers, upper and lower case letters and English underscore "" And middle Dash "-"', + currency2: 'Please enter 1-64 characters', + modelSpecifications: 'The instance specification and Type name cannot be duplicated', + name: 'Duplicate Type Name', + specifications: 'Duplicated model specifications' + } + }, + resourceMonitor: { + header: { + resourceMonitor: 'Resource monitoring graph' + }, + search: { + userName: 'User Name', + resourceType: 'Resource Type', + idcName: 'Idc Name', + instanceId: 'Instance ID', + dimensions: 'Dimensions', + monitoringMetrics: 'Monitoring Metrics', + btn: { + search: 'Search', + clear: 'Clear' + }, + count: { + resourceType: 'Instance', + dimensions: 'Instance' + } + }, + placeholder: { + userName: 'Please enter Username', + resourceType: 'Please select Resource Type', + idcName: 'Please select Idc Name', + instanceId: 'Please enter Instance ID', + dimensions: 'Please select Dimensions', + monitoringMetrics: 'Please select Monitoring Metrics' + }, + errorTip: { + userName: 'Please enter Username', + resourceType: 'Please select Resource Type', + idcName: 'Please select Idc Name', + instanceId: 'Please enter Instance ID', + dimensions: 'Please select Dimensions', + monitoringMetrics: 'Please select Monitoring Metrics' + } + }, + historyAlarmInfo: { + header: { + historyAlarmInfo: 'Historical alarm information' + }, + search: { + label: { + userName: 'User Name', + alarmTime: 'Alarm Time' + }, + placeholder: { + userName: 'Please enter Username', + startDate: 'Start Date', + endDate: 'End Date', + }, + errorTip: { + userName: 'Please enter Username', + alarmTime: 'Please select Alarm Time' + }, + btn: { + search: 'Search', + clear: 'Clear' + } + }, + table: { + label: { + name: 'User Name', + alarmTime: 'Alarm Time', + resourceName: 'Resource Type', + resourceId: 'Alarm Resources ID', + triggerDescription: 'Triggering Conditions', + alertValue: 'Alarm Value', + alertLevelDescription: 'Alarm Level', + alertPeriod: 'Duration', + userName: 'Notification Object' + }, + count: { + minute: ' minute(s)' + } + } + }, + allAlarmRulesList: { + header: { + allAlarmRulesList: 'All alarm rules' + }, + select: { + alarm: 'Alarm', + normal: 'Normal', + forbid: 'Disabled', + }, + search: { + label: { + userName: 'User Name', + ruleName: 'Rule Name', + ruleId: 'Rule ID' + }, + placeholder: { + userName: 'Please enter Username', + ruleName: 'Please enter a rule name', + ruleId: 'Please enter a rule ID' + }, + errorTip: { + userName: 'Please enter Username', + ruleName: 'Please enter a rule name', + ruleId: 'Please enter a rule ID' + }, + btn: { + search: 'Search', + clear: 'Clear' + } + }, + table: { + label: { + ruleName: 'Rule Name', + userName: 'User Name', + ruleId: 'Rule ID', + resourceName: 'Resource Type', + instanceCount: 'Instance associated number', + triggerDescription: 'Triggering Condition', + statusName: 'Status', + operate: { + title: 'Operate', + lookDetail: 'Look Detail', + alarmHistory: 'Alarm History' + } + } + } + }, + allAlarmRulesDetail: { + header: { + title2: 'Alarm rule details', + operate: { + alarmHistory: 'Alarm History' + } + }, + count: { + minute: ' minute(s)', + hours: ' hour(s)' + }, + baseInfo: { + title: 'Account Basics', + label: { + ruleId: 'Rule Id', + ruleName: 'RuleName', + resourceType: 'Resource Type' + } + }, + alarmResources: { + title: 'Alarm Resources', + table: { + label: { + instanceName: 'Instance Name', + instanceId: 'Instance ID', + ipv4: 'Private IPv4(eth0)', + ipv6: 'Private IPv6(eth0)' + } + } + }, + triggeringConditions: { + title: 'Triggering Conditions' + }, + notificationStrategy: { + title: 'Notification Strategy', + label: { + notificationCycle: 'Notification Cycle', + effectivePeriod: 'Effective Period', + notificationConditions: 'Notification Conditions', + receivingChannel: 'Receiving Channel', + notificationObject: 'Notification Object' + } + }, + notice: { + email: 'Email', + internalMessage: 'Internal message' + } + }, + hardwareStatusList: { + header: { + hardwareStatusList: 'Fault device status' + }, + search: { + label: { + idcName: 'Idc Name', + sn: 'SN' + }, + placeholder: { + idcName: 'Please Select', + sn: 'Please enter the SN' + }, + btn: { + search: 'Search', + clear: 'Clear' + } + }, + table: { + label: { + sn: 'SN', + idc: 'Idc Name', + brand: 'Brand', + model: 'Model', + managementStatus: 'Management Status', + cpu: 'CPU', + storage: 'Memory', + hardDisk: 'Hard Disk', + networkCard: 'NIC', + powerSupply: 'Power Supply', + other: 'Other', + operate: 'Operate', + opt: 'Historical Faults' + } + } + }, + surveillance: { + status: { + all: 'All', + no: 'Not Processed', + yes: 'Processed' + }, + accessory: { + cpu: 'CPU', + mem: 'Memory', + hardDisk: 'Hard Disk', + networkCard: 'NIC', + powerSupply: 'Power Supply', + voltage: 'Voltage', + fan: 'Fan', + temperature: 'Temperature', + pcie: 'PCIE Bus' + }, + }, + faultLogList: { + header: { + faultLogList: 'Alarm Log' + }, + search: { + label: { + idcName: 'Idc Name', + sn: 'SN', + level: 'Failure Level', + time: 'First fault alarm time', + accessory: 'Faulty Accessories', + status: 'Status' + }, + placeholder: { + idcName: 'Please Select', + sn: 'Please enter the SN', + level: 'Please Select', + startDate: 'Start Date', + endDate: 'End Date', + accessory: 'Please Select', + status: 'Please Select' + }, + btn: { + search: 'Search', + clear: 'Clear' + } + }, + table: { + label: { + logId: 'LogID', + sn: 'SN', + idc: 'Idc Name', + level: 'Failure Level', + type: 'Fault Type', + accessory: 'Faulty Accessories', + iloip: 'iloIP', + desc: 'Fault Desc', + originalLog: 'Fault Original log', + status: 'Status', + numberOfAlarms: 'Number of alarms', + faultDetectionTime: 'Out-of-band fault detection time', + faultAlarmTime: 'First fault alarm time', + updateTime: 'Update Time', + operate: 'Operate' + }, + operate: { + title: 'Deal', + tip: 'Only unprocessed fault logs can be processed' + } + } + }, + faultRulesList: { + header: { + faultRulesList: 'Alarm Rules' + }, + search: { + label: { + faultName: 'Fault Name', + faultAccessories: 'Faulty Accessories', + faultLevel: 'Failure Level' + }, + placeholder: { + faultName: 'Please enter the fault name', + faultAccessories: 'Please Select', + faultLevel: 'Please Select' + }, + btn: { + search: 'Search', + clear: 'Clear', + restoreDefaultSet: 'Restore default settings' + } + }, + table: { + label: { + faultName: 'Fault Name', + faultAccessories: 'Faulty Accessories', + faultType: 'Fault Type', + judgmentConditions: 'Judgment Conditions', + decisionThreshold: 'Decision Threshold', + faultLevel: 'Failure Level', + faultDesc: 'Fault Description', + faultPush: 'Failure Push', + enableStatus: 'Enabled Status', + } + } + }, + faultHandingConfirm: { + header: { + title: 'Troubleshooting Confirmation', + tip1: 'Note: After the fault is handled, the status changes to "Handed" and cannot be canceled. Please operate with caution.', + tip2: 'Please confirm whether the following faults have been resolved and restored?' + }, + label: { + sn: 'SN', + faultName: 'Fault Name', + faultType: 'Fault Type', + faultLevel: 'Failure Level', + faultDesc: 'Fault Description', + time: 'First fault alarm time' + } + }, + defaultSet: { + header: { + title: 'Restore default settings', + tip1: 'Note: After restoring the default settings, all fault status will be restored to the initial state, please operate with caution', + tip2: 'Please confirm whether you want to restore the following faults to the initial state?' + }, + label: { + faultName: 'Fault Name', + faultType: 'Fault Type', + faultLevel: 'Failure Level', + faultDesc: 'Fault Description' + } + }, + faultOperation: { + header: { + title: 'Failure operation confirmation', + tip1: 'Please make sure to enable the [{0}] fault?', + tip2: 'Please make sure to disable the [{0}] fault?' + } + }, + faultPush: { + header: { + title: 'Failure push operation confirmation', + tip1: 'Please confirm to enable fault push of [{0}]?', + tip2: 'Are you sure to disable [{0}] fault push?' + } + }, + roleList: { + header: { + roleList: 'Role List' + }, + operate: { + refresh: 'Refresh', + setUp: 'Settings', + export: 'Export' + }, + label: { + role: 'Role', + relationUser: 'Associated Users', + jurisdiction: 'Permissions' + } + }, + errorTip: { + title: 'Please enter a valid mobile phone number', + }, + userList: { + header: { + userList: 'User List' + }, + operate: { + addUser: 'Add User', + refresh: 'Refresh', + setUp: 'Settings', + export: 'Export' + }, + search: { + placeholder: { + userName: 'Please enter Username' + }, + condition: { + userName: 'User Name' + } + }, + label: { + userName: 'User Name', + userId: 'User ID', + role: 'Role', + itemNum: 'Item Num', + cellPhone: 'Mobile Phone', + email: 'Email', + desc: 'Description', + createTime: 'Created Time', + operate: { + name: 'Actions', + edit: 'Edit', + delete: 'Delete', + tooltip: { + delete: 'Owner Unable to delete', + delete2: 'Please remove the items associated with this user first' + } + } + } + }, + createKey: { + header: { + title: 'Create an API key' + }, + form: { + label: { + keyName: 'Key Name', + permissions: 'Permissions' + }, + placeholder: { + keyName: 'Please enter a key name', + permissions: 'Please select permissions' + } + }, + select: { + title: 'Read/Write' + }, + empty: { + keyName: 'Key name input cannot be empty', + permissions: 'Permission cannot be empty' + }, + errorTip: { + keyName: '1-64 characters, only numbers, letters, underscore “_” and hyphen “-” are supported', + repeat: 'Key Name Repeat' + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + deleteKey: { + header: { + title: 'Delete the API key' + }, + content: { + title: 'Confirm to delete the key: {0}?' + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + addUser: { + header: { + addUser: 'Add User' + }, + label: { + role: 'Role', + userName: 'Name', + password: 'Password', + desc: 'Desc', + cellPhone: 'Phone', + email: 'Email' + }, + role: { + owner: 'Owner', + user: 'User', + operator: 'Operator' + }, + default: { + userName: '1-32 characters, only numbers, letters, underscore “_” and hyphen “-” are supported' + }, + placeholder: { + userName: 'Please enter Username', + password: 'Please enter Password', + desc: 'please enter a description', + cellPhone: 'Please enter the Mobile Phone', + email: 'Please enter Email ' + }, + emptyTip: { + userName: 'Username input cannot be empty', + password: 'Password input cannot be empty', + cellPhone: 'Mobile phone number cannot be empty', + email: 'Email input cannot be empty' + }, + errorTip: { + number: 'Only numbers can be entered', + userName: 'Please enter a correct username', + password: "Password: 8-30 characters, and simultaneously including three types (Capital letters, lowercase letters, numbers or special characters ()`~!{'@'}#{'$'}%&*_-+={'|'}{'{'}{'}'}[]:<>,.?/)", + repeatUserName: 'Duplicated Username', + cellPhone: 'Please enter the correct mobile phone number', + email: 'Please enter the correct email address', + HongKong: 'Please enter the correct mobile phone number in HongKong, China', + MacaMacao: 'Please enter the correct mobile phone number in Macau, China', + Taiwan: 'Please enter the correct mobile phone number in Taiwan, China' + }, + tooltip: { + count: '1:Owner: Possess access to the console & operation platform, and all operation rights.
' + + '2:User:Have access to the console, all operations, no access to the operating platform.
' + + '3:Operator:Possess access rights to the operation platform, all operation rights (except
' + 'user management and role management).
' + }, + phoneData: { + China: 'China +86', + HongKong: 'Hongkong +852', + MacaMacao: 'Macao +853', + Taiwan: 'Taiwan +886', + Argentina: 'Argentina +54', + Australia: 'Australia +61', + Brazil: 'Brazil +55', + Germany: 'Germany +49', + France: 'France +33', + SouthKorea: 'South Korea +82', + Canada: 'Canada +1', + USA: 'USA +1', + Mexico: 'Mexico +52', + SouthAfrica: 'South Africa +27', + Japan: 'Japan +81', + SaudiArabia: 'Saudi Arabia +966', + Turkey: 'Turkey +90', + Italy: 'Italy +39', + India: 'India +91', + Indonesia: 'Indonesia +62', + UnitedKiongdom: 'United Kiongdom +44' + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + editUser: { + header: { + editUser: 'Edit User' + }, + label: { + role: 'Role', + userName: 'Name', + userId: 'ID', + desc: 'Desc', + cellPhone: 'Phone', + email: 'Email' + }, + placeholder: { + desc: 'please enter a description', + cellPhone: 'Please enter the Mobile Phone', + email: 'Please enter Email ' + }, + emptyTip: { + desc: 'Description input cannot be empty', + cellPhone: 'Mobile phone number cannot be empty', + email: 'Email input cannot be empty' + }, + errorTip: { + number: 'Only numbers can be entered', + cellPhone: 'Please enter the correct mobile phone number', + email: 'Please enter the correct email address', + HongKong: 'Please enter the correct mobile phone number in HongKong, China', + MacaMacao: 'Please enter the correct mobile phone number in Macau, China', + Taiwan: 'Please enter the correct mobile phone number in Taiwan, China' + }, + phoneData: { + China: 'China +86', + HongKong: 'Hongkong +852', + MacaMacao: 'Macao +853', + Taiwan: 'Taiwan +886', + Argentina: 'Argentina +54', + Australia: 'Australia +61', + Brazil: 'Brazil +55', + Germany: 'Germany +49', + France: 'France +33', + SouthKorea: 'South Korea +82', + Canada: 'Canada +1', + USA: 'USA +1', + Mexico: 'Mexico +52', + SouthAfrica: 'South Africa +27', + Japan: 'Japan +81', + SaudiArabia: 'Saudi Arabia +966', + Turkey: 'Turkey +90', + Italy: 'Italy +39', + India: 'India +91', + Indonesia: 'Indonesia +62', + UnitedKiongdom: 'United Kiongdom +44' + }, + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + myProfile: { + header: { + myProfile: 'My Profile' + } + }, + securitySettings: { + header: { + securitySettings: 'Security Settings' + } + }, + apiKey: { + header: { + apiKey: 'Personal API Keys' + } + }, + ower: { + tips1: 'You have not yet activated this module, Please send your ', + tips2: 'request code', + tips3: ' and ', + tips4: 'requirements', + tips5: ' to ', + tips6: ', and we will contact you as soon as possible.', + tips7: 'You have not yet activated this module' + }, + userCenter: { + header: { + userCenter: 'Personal Center', + title1: 'Account Basics', + title2: 'Console Preferences' + }, + tabs: { + myProfile: 'My Profile', + securitySettings: 'Security Settings', + apiKey: 'Personal API Keys', + }, + label: { + role: 'Role', + userName: 'User Name', + email: 'Email', + phoneNumber: 'Mobile Phone', + language: 'Language', + time: 'Timezone' + }, + currectPassword: 'Currect Password', + newPassword: 'New Password', + confirmPassword: 'Confirm Password', + emptyTip: { + currectPassword: 'Current password cannot be empty', + newPassword: 'New password cannot be empty', + confirmPassword: 'Confirm password cannot be empty' + }, + errorTip: { + password: "Password: 8-30 characters, and simultaneously including three types (Capital letters, lowercase letters, numbers or special characters ()`~!{'@'}#{'$'}%&*_-+={'|'}{'{'}{'}'}[]:<>,.?/)", + password2: 'The passwords are inconsistent, please re-enter' + }, + placeholder: { + phoneNumber: 'Please enter phone number', + email: 'Please enter email address', + language: 'Please select language', + time: 'Please select time zone' + }, + defaultTime: '(GMT+08:00) China Time - Beijing', + language: { + zh: 'Chinese', + en: 'English' + }, + tooltip: { + tip: 'Only supports creating 2 API keys' + }, + table: { + label: { + keyName: 'Key Name', + token: 'Token', + permissions: 'Permissions', + createTime: 'Created Time', + operate: { + name: 'Actions', + copy: 'Copy', + delete: 'Delete' + } + }, + select: { + title: 'Read/Write', + read: 'Read Only' + } + }, + btn: { + createKey: 'Create API Key', + saveChange: 'Save Changes', + save: 'Save' + } + }, + deleteUser: { + header: { + deleteUser: 'Delete user', + }, + label: { + userName: 'User Name', + role: 'Role', + cellPhone: 'Mobile Phone', + email: 'Email' + }, + deleteTip: 'Please confirm whether to delete the following users.', + btn: { + cancel: 'Cancel', + sure: 'Confirm' + } + }, + table: { + empty: 'No data is available', + tip: 'You can ' + } +}; + +export default en; diff --git a/bmp-operation-web/src/lib/i18n/index.ts b/bmp-operation-web/src/lib/i18n/index.ts new file mode 100644 index 0000000..152a1b5 --- /dev/null +++ b/bmp-operation-web/src/lib/i18n/index.ts @@ -0,0 +1,77 @@ +/** + * @file + * @author +*/ + +import {createI18n, I18n} from 'vue-i18n'; +import zh from '@/lib/i18n/zh-CN.ts'; +import en from '@/lib/i18n/en-US.ts'; +import zhLocale from 'element-plus/lib/locale/lang/zh-cn'; +import enLocale from 'element-plus/lib/locale/lang/en'; +import VueCookies from 'vue-cookies'; + +interface CookieType { + [x: string]: unknown; + get?: Function; + set?: Function; +}; + +// 配置对象-国际化 +const messages = { + en_US: { + ...en, + ...enLocale + }, + zh_CN: { + ...zh, + ...zhLocale + } +}; + +// cookie ts规范校验 +const cookie: CookieType = VueCookies; + +const isCookie = cookie?.get && cookie.get('X-Jdcloud-Language'); + +/** + * 获取语言类型 + * @return {string} key 语言种类 + * @return {string} isCookie 语言种类 + * @return {string} zh_CN 语言种类 +*/ +const getLocale = () => { + // 初次进入页面,cookie里面还未获取到值 + if (isCookie === null) { + // 浏览器语言 + const language: string = navigator.language.toLocaleLowerCase(); + // message语言 + const locale: string[] = Object.keys(messages); + for (const key of locale) { + // 如果浏览器语言类型包括message里面的类型 + if (language.indexOf(key) > -1) { + // 返回 + return key; + } + } + } + // 有cookie,优先用cookie里面的 + else if (isCookie) { + return isCookie; + } + // 默认语言 + return isCookie || 'zh_CN'; +}; + +/** + * 首先从缓存里拿,没有的话就用浏览器语言 +*/ +const i18n: I18n = createI18n({ + legacy: false, // 使用 vue3 组合式API 时必须设置为 false + locale: getLocale(), // 本地语言 + globalInjection: true, // 全局注入 $t 函数 + fallbackLocale: isCookie || 'zh_CN', // 设置备用语言 + warnHtmlMessage: false, // 解决v-html警告 + messages // 配置对象 +}); + +export default i18n; diff --git a/bmp-operation-web/src/lib/i18n/zh-CN.ts b/bmp-operation-web/src/lib/i18n/zh-CN.ts new file mode 100644 index 0000000..2300c56 --- /dev/null +++ b/bmp-operation-web/src/lib/i18n/zh-CN.ts @@ -0,0 +1,2582 @@ +const zh: {[x: string]: {[x: string]: unknown}} = { + size: { + num: '剩余全部', + all: '全部' + }, + operate: { + success: '操作成功', + fail: '操作失败', + doing: '操作中', + copy: '复制成功', + refresh: '刷新', + setUp: '设置', + export: '导出', + name: '操作', + btn: { + cancel: '取消', + sure: '确定' + }, + tip: { + default: '请选择资源', + } + }, + searchTip: { + title1: '查询到符合搜索及筛选条件的资源共 {0} 条,', + title2: '查询到符合搜索及筛选条件的资源共 {0} 条,请更换搜索关键字或', + title3: '返回列表' + }, + monitorEcharts: { + tabs: { + h1: '1小时', + h6: '6小时', + h12: '12小时', + d1: '1天', + d3: '3天', + d7: '7天', + d14: '14天' + }, + datePicker: { + startDate: '开始日期', + endDate: '结束日期' + }, + radio: { + instance: '实例', + disk: '磁盘', + diskPartition: '磁盘用量', + netWorkInterface: '网口' + }, + diskTip: 'Linux系统按设备名上报, Windows系统按盘符上报', + diskPartitionTip: 'Linux系统按分区挂载点上报,Windows系统按盘符上报', + echartsCount: { + period: '周期', + aggregationMethod: '聚合方式', + cpuUnit: 'CPU使用率(%)', + cpu: 'CPU使用率', + memUnit: '内存使用率(%)', + mem: '内存使用率', + memUsageUnit: '内存使用量(GB)', + memUsage: '内存使用量', + diskUsageUnit: '磁盘使用量(GB)', + diskUsage: '磁盘使用量', + diskUsageRateUnit: '磁盘使用率(%)', + diskUsageRate: '磁盘使用率', + diskReadWriteTrafficUnit: '磁盘读/写流量(Bps)', + diskReadWriteTraffic: '磁盘读/写流量', + diskReadTraffic: '磁盘读流量', + diskWriteTraffic: '磁盘写流量', + diskReadWriteIOPSUnit: '磁盘读/写IOPS(次/秒)', + diskReadWriteIOPS: '磁盘读/写IOPS', + diskReadIOPS: '磁盘读IOPS', + diskWriteIOPS: '磁盘写IOPS', + netWorkBpsUnit: '网口进/出流量(bps)', + netWorkBps: '网口进/出流量', + netWorkIn: '网口进流量', + netWorkOut: '网口出流量', + netWorkPackagesNumUnit: '网络进/出包数量(个/秒)', + netWorkPackagesNumber: '网络进/出包数量', + netWorkInPackageNum: '网络进包量', + netWorkOutPackageNum: '网络出包量', + averageLoad1MinUnit: '平均负载1min', + averageLoad1Min: '平均负载1min', + averageLoad5MinUnit: '平均负载5min', + averageLoad5Min: '平均负载5min', + averageLoad15MinUnit: '平均负载15min', + averageLoad15Min: '平均负载15min', + totalTCPConnectionsUnit: 'TCP总连接数(个)', + totalTCPConnections: 'TCP总连接数', + normalTCPConnectionsUnit: 'TCP正常连接数(个)', + normalTCPConnections: 'TCP正常连接数', + totalNumberOfProcessesUnit: '总进程数(个)', + totalNumberOfProcesses: '总进程数' + } + }, + userInfo: { + emptyTip: { + userName: '用户名输入不能为空', + password: '密码输入不能为空', + cellPhone: '手机号输入不能为空', + email: '邮箱地址输入不能为空' + }, + errorTip: { + number: '只能输入数字', + userName: '1~64 字符,只支持数字、大小写字母、英文下划线 “_”及中划线“-”', + password: "8-30个字符,同时包含三项(大写字母,小写字母,数字或特殊符号()`~!{'@'}#{'{'}{'}'}{'$'}%&*_-+={'|'}[]:\";\'<>,.?/)", + repeatUserName: '用户名重复', + cellPhone: '请输入正确的手机号', + email: '请输入正确的邮箱地址', + HongKong: '请输入正确的中国香港手机号', + MacaMacao: '请输入正确的中国澳门手机号', + Taiwan: '请输入正确的中国台湾手机号' + } + }, + login: { + header: { + title: '裸金属运营支撑平台(标准版)', + title2: '裸金属运营支撑平台(专业版)' + }, + formSubmit: { + title: '欢迎回来', + placeholder: { + userName: '请输入用户名', + passWord: '请输入密码' + }, + toolTip: '用户名不存在或者密码错误', + login: '登录' + } + }, + loginOut: { + title: '退出登录', + tip: '确定退出登录', + btn: { + cancel: '取消', + sure: '确定' + } + }, + navigationHeader: { + title: '裸金属运营支撑平台(标准版)', + title2: '裸金属运营支撑平台(专业版)', + myProfile: '我的账户', + securitySettings: '安全设置', + apiKey: '个人API密钥', + loginOut: '退出登录' + }, + navigationBar: { + list: { + computerRoomManagement: '机房管理', + modelManagement: '机型管理', + imageManagement: '镜像管理', + deviceManagement: '设备管理', + roleManagement: '角色管理', + userManagement: '用户管理', + inBandMonitoringManagement: '带内监控管理', + surveillanceManagement: '带外监控管理', + messageCenter: '消息中心', + userCenter: '个人中心' + }, + children: { + hardwareAlarmStatus: '硬件设备状态', + resourceEcharts: '资源监控图', + historyAlarmInfo: '历史报警信息', + allAlarmRules: '全部报警规则', + faultAlarmLog: '故障报警日志', + faultAlarmRules: '故障报警规则', + myMessages: '我的消息', + messageSet: '消息设置' + } + }, + export: { + title: '自定义导出', + content: { + scope: '导出范围:', + all: '导出全部', + Selected: '导出选中实例', + search: '仅导出搜索结果' + }, + btn: { + cancel: '取消', + sure: '确定' + } + }, + idcList: { + header: { + idcList: '机房列表', + operate: { + refresh: '刷新', + setUp: '设置', + export: '导出' + } + }, + content: { + name: '机房名称', + englishCode: '机房英文名称', + grade: '机房等级', + address: '机房地址', + createTime: '创建时间', + createPeople: '创建人', + updateTime: '更新时间', + updatePeople: '更新人', + operate: { + name: '操作', + edit: '编辑' + } + } + }, + idcDetail: { + header: { + title: '机房列表', + title2: '机房详情', + operate: { + name: '操作', + edit: '编辑' + } + }, + basicInfo: { + title: '基本信息', + label: { + name: '机房名称', + englishCode: '机房英文名称', + grade: '机房等级', + address: '机房地址', + total: '机柜总数', + createTime: '创建时间', + createPeople: '创建人', + updateTime: '更新时间', + updatePeople: '更新人' + } + }, + allAdministration: { + title: '全局管理', + name: '名称', + loginAccount: '带外', + loginUserName: '登录账号', + loginPassWord: '登录密码', + switchboardOneNum: '交换机1', + switchboardTwoNum: '交换机2', + } + }, + messageDelete: { + header: { + messageDelete: '删除消息' + }, + tips: '删除后消息将无法恢复,您确定要删除吗?' + }, + myMessage: { + day90: '前90天提醒', + day30: '前30天提醒', + day15: '前15天提醒', + expired: '已到期提醒', + header: { + myMessage: '消息列表', + title: '(共 {0} 条,其中', + title2: '条未读)' + }, + radioGroup: { + all: '全部', + read: '已读', + noRead: '未读' + }, + search: { + title: '消息内容', + placeholder: '请输入消息内容搜索' + }, + table: { + expired: '已到期', + tip15: '', + tip30: '', + tip90: '', + systemMessages: '系统消息', + faultMessages: '故障消息', + operationMessages: '操作消息', + inbondAlert: '报警消息', + remind: '提醒', + failureNotification: '失败通知', + alarmTips: '报警提醒' + }, + label: { + messageContent: '消息内容', + finishTime: '接收时间', + messageType: '消息类型', + messageSubType: '消息子类型' + }, + footer: { + tips: '请选择消息', + delete: '删除', + read: '标为已读' + } + }, + customFilter: { + placeholder: '请输入', + btn: { + confirm: '筛选', + reset: '重置' + } + }, + messageSettings: { + header: { + messageSettings: '消息设置' + }, + label: { + emailPush: '是否关联邮箱推送', + ipAddress: '邮件服务器', + port: '邮件服务器端口', + emailAddress: '邮箱地址', + emailPassword: '邮箱密码', + testEmail: '测试邮件接收邮箱' + }, + placeholder: { + ipAddress: '请输入您邮箱的smtp服务器地址', + port: '请输入邮件服务器端口', + emailAddress: '请输入需要配置的邮箱地址', + emailPassword: '请输入邮箱密码', + testEmail: '请输入测试邮件接收邮箱' + }, + empty: { + ipAddress: '邮件服务器不能为空', + port: '邮件服务器端口不能为空', + emailAddress: '邮箱地址不能为空', + emailPassword: '邮箱密码不能为空', + testEmail: '测试邮件接收邮箱不能为空' + }, + errorTip: { + port: '只能输入数字,范围1-65535', + emailAddress: '请输入正确的邮箱地址', + emailPassword: '请输入正确的邮箱密码', + testEmail: '请输入正确的邮箱地址' + }, + tips: { + pushTip: '开启邮箱推送,用户接收站内信的同时可接收邮箱消息;关闭邮箱推送,用户仅可接收站内信,无法接收邮箱消息', + checkTip: '用于验证邮箱配置信息是否正常。 单击下方【保存并验证】按钮发送测试邮件,查
看指定邮箱是否可以接收到邮件通知,邮件接收过程存在一定延时,请耐心等待。' + }, + footer: { + success: '已验证', + save: '保存并验证', + checkInfo: '校验邮箱信息' + } + }, + messageDetail: { + header: { + title2: '消息详情', + renewImmediately: '立即续费' + }, + label: { + optContent: '操作内容', + optPeople: '操作人', + optTime: '操作时间', + versionName: '版本名称', + version: '版本号', + startTime: '开始时间', + licenseEndTime: '到期时间', + licenseStatus: '许可状态', + faultType: '故障类型', + faultDesc: '故障描述', + faultAlarmTime: '故障报警时间', + alarmNum: '报警次数', + }, + optTips: { + title: '以下为操作内容详情:', + label: { + instanceName: '实例名称', + instanceId: '实例ID' + }, + instance: '的实例', + current: '当前' + }, + footer: { + pre: '上一条', + next: '下一条' + }, + failureNotification: '失败通知', + alarmTips: '报警提醒', + remind: '提醒', + tip0: '用户{0}您好!', + tip: '用户{0}您好!操作失败,请重新操作或联系管理员处理', + tip1: '', + tip11: '已到期,', + tip2: '续费后可继续正常使用云平台功能。', + tip3: '', + tip4: '以下为操作概览:', + tip5: '', + tip6: '以下为故障详情:', + tip7: '【监控报警】', + day90: '', + day30: '', + day15: '', + expired: '', + systemMessages: '系统消息', + faultMessages: '故障消息', + operationMessages: '操作消息', + inbondAlert: '报警消息', + status: { + effective: '有效', + expired: '已过期' + } + }, + emailPush: { + start: { + title: '开启邮箱推送', + content: '请确认开启邮箱推送,开启后,用户在接收站内信时将同步接收邮箱提醒。' + }, + close: { + title: '关闭邮箱推送', + content: '请确认关闭邮箱推送,关闭后,用户可接收站内信,将无法接收到邮箱提醒。' + } + }, + securityVerification: { + header: { + verification: '安全验证' + }, + label: { + userName: '用户名', + passWord: '密码' + }, + placeholder: { + userName: '请输入用户名', + passWord: '请输入密码' + }, + empty: '密码输入不能为空', + errTip: { + userName: '用户名不存在或者密码错误', + passWord: '用户名不存在或者密码错误', + currencyPassword: '请输入6-64位字符' + }, + btn: { + cancel: '取消', + sure: '确定' + } + }, + editIdc: { + header: { + name: '编辑机房' + }, + iptInfo: { + other: '其它' + }, + label: { + computerRoomName: '机房名称', + computerRoomCode: '机房英文名称', + computerRoomGrade: '机房等级', + computerRoomAddress: '机房地址', + outsideLoginAccountNum: '带外登录账号', + outsideLoginPsd: '带外登录密码', + switchboardOneNum: '交换机1登录账号', + switchboardOnePsd: '交换机1登录密码', + switchboardTwoNum: '交换机2登录账号', + switchboardTwoPsd: '交换机2登录密码' + }, + placeholder: { + computerRoomName: '请输入机房名称', + computerRoomCode: '请输入机房英文名称', + computerRoomGrade: '请选择机房等级', + customComputerRoomGrade: '请输入自定义机房等级', + computerRoomAddress: '请输入机房地址', + outsideLoginAccountNum: '请输入带外登录账号', + outsideLoginPsd: '请输入带外登录密码', + switchboardOneNum: '请输入交换机1登录账号', + switchboardOnePsd: '请输入交换机1登录密码', + switchboardTwoNum: '请输入交换机2登录账号', + switchboardTwoPsd: '请输入交换机2登录密码' + }, + errTip: { + currency: '请输入1-64位字符', + currencyPassword: '请输入1-128位字符', + computerRoomNameEmpty: '机房名称不能为空', + computerRoomCodeEmpty: '机房英文名称不能为空', + customComputerRoomGrade: '自定义机房等级输入不能为空', + computerRoomAddressEmpty: '机房地址输入不能为空', + outsideLoginAccountNumEmpty: '带外登录账号不能为空', + outsideLoginPsdEmpty: '带外登录密码不能为空', + switchboardOneNumEmpty: '交换机1登录账号不能为空', + switchboardOnePsdEmpty: '交换机1登录密码不能为空', + switchboardTwoNumEmpty: '交换机2登录账号不能为空', + switchboardTwoPsdEmpty: '交换机2登录密码不能为空' + }, + btn: { + cancel: '取消', + sure: '确定' + } + }, + customList: { + header: { + name: '自定义列表' + }, + text: { + tip: '请选择要显示在列表的信息' + }, + btn: { + cancel: '取消', + sure: '确定' + } + }, + modelList: { + header: { + modelList: '机型列表', + label: { + modelName: '机型名称', + modelSpecifications: '机型规格' + }, + placeholder: { + modelName: '请输入机型名称搜索', + modelSpecifications: '请输入机型规格搜索' + }, + operate: { + addModel: '添加机型', + refresh: '刷新', + setUp: '设置', + export: '导出' + } + }, + content: { + modelName: '机型名称', + modelType: '机型类型', + machineRoomName: '机房名称', + machineRoomCode: '机房英文名称', + architecture: '体系架构', + bootMode: '引导模式', + modelSpecification: '机型规格', + image: '镜像', + device: '设备', + CPU: 'CPU', + storage: '内存', + sysDisc: '系统盘', + sysRAID: '系统盘RAID', + raidConfig: 'RAID配置', + dataDisc: '数据盘', + dataRAID: '数据盘RAID', + networkCard: '网卡', + networkSettings: '网络设置', + GPU: 'GPU', + desc: '描述', + operate: { + name: '操作', + edit: '编辑', + delete: '删除', + more: '更多', + addModel: '添加相同机型' + } + }, + edit: '已关联设备的机型不支持编辑', + tooltip: '无法删除机型,请先删除该机型关联的实例资源' + }, + uiPagination: { + total: '共 {0} 条', + page: '共 {0} 页', + piecesAndPage: '{0} 条/页' + }, + addModel: { + header: { + title2: '添加机型', + addModel: '添加机型' + }, + btn: { + cancel: '取消', + sure: '确定' + } + }, + editModel: { + header: { + title2: '编辑机型', + editModel: '编辑机型' + }, + btn: { + cancel: '取消', + sure: '确定' + } + }, + deleteModel: { + header: { + deleteModel: '删除机型', + batchDeleteModel: '批量删除机型' + }, + content: { + deleteTip: '删除机型后,该机型与镜像关联关系也同步删除,再次添加机型需要重新添加关联镜像,请谨慎操作。', + deleteSure: '请确定是否删除机型:{0}?' + }, + btn: { + cancel: '取消', + sure: '确定' + } + }, + modelDetail: { + header: { + title: '机型管理', + title2: '机型详情', + specifications: '规格参数', + configParams: '配置参数', + operate: { + name: '操作', + edit: '编辑', + addModel: '添加相同机型', + delete: '删除' + }, + tip: '无法删除机型,请先删除该机型关联的实例资源', + volumeManagement: { + title: '卷管理', + label: { + name: '卷名称', + type: '卷类型', + raidCan: 'RAID配置', + raid: 'RAID模式', + disk: '磁盘类型', + interfaceType: '接口类型', + minNum: '单盘最小容量', + amount: '最低数量(块)' + } + } + }, + tabs: { + basicInfo: { + name: '基本信息', + label: { + modelName: '机型名称', + computerRoomName: '机房名称', + modelType: '机型类型', + architecture: '体系架构', + bootMode: '引导模式', + modelSpecifications: '机型规格', + CPU: 'CPU', + storage: '内存', + sysDisc: '系统盘', + raidConfig: 'RAID配置', + sysRAID: '系统盘RAID', + dataDisc: '数据盘', + dataRAID: '数据盘RAID', + networkCard: '网卡', + networkSettings: '网络设置', + GPU: 'GPU', + height: '高度(U)', + createTime: '创建时间', + desc: '描述' + } + }, + relationImage: { + name: '关联镜像', + header: { + addImage: '添加镜像', + tooltip: '仅支持关联20个镜像' + }, + content: { + label: { + imageName: '镜像名称', + imageType: '镜像类型', + architecture: '体系架构', + operateSysPlatform: '操作系统平台', + operateSysVersion: '操作系统版本', + partitionModule: '分区模块', + addTime: '添加时间', + operate: { + name: '操作', + delete: '删除' + } + } + } + } + }, + other: '其它' + }, + addImage: { + header: { + addImage: '添加镜像', + label: { + modelName: '机型名称', + choose: '已选镜像个数' + } + }, + content: { + label: { + imageName: '镜像名称', + modelName: '机型名称', + imageType: '镜像类型', + architecture: '体系架构', + operateSysPlatform: '操作系统平台', + operateSysVersion: '操作系统版本', + sysPartitionModule: '系统盘分区' + } + }, + btn: { + cancel: '取消', + save: '保存', + sure: '确定' + } + }, + deleteImage: { + header: { + deleteImage: '删除镜像' + }, + tip: { + text: '确认删除关联镜像', + delete: '确定删除镜像' + }, + btn: { + cancel: '取消', + sure: '确定' + } + }, + imageList: { + header: { + imageList: '镜像列表', + exportImage: '导入镜像', + operate: { + refresh: '刷新', + setUp: '设置', + export: '导出' + } + }, + search: { + placeholder: { + imageName: '请输入镜像名称搜索', + imageId: '请输入镜像ID搜索' + }, + condition: { + imageName: '镜像名称', + imageId: '镜像ID' + } + }, + content: { + label: { + imageName: '镜像名称', + imageId: '镜像ID', + imageType: '镜像类型', + architecture: '体系架构', + operateSysPlatform: '操作系统平台', + operateSysVersion: '操作系统版本', + format: '镜像格式', + bootMode: '引导模式', + sysPartitionModule: '系统盘分区', + imageDesc: '镜像描述', + numberOfAssociatedModels: '已关联机型数', + createTime: '创建时间', + operate: { + name: '操作', + delete: '删除' + } + } + }, + filter: { + presetImage: '预置镜像', + customImage: '自定义镜像' + }, + tooltip: { + title: '无法删除镜像,请先删除该镜像与机型的关联关系', + image: '预置镜像不支持删除' + } + }, + associatedModel: { + header: { + title: '关联机型' + }, + content: { + select: '选择机型', + placeholder: '请选择机型', + addNewModel: '添加新机型', + table: { + label: { + volumeName: '卷名称', + volumeType: '卷类型', + raidCan: 'RAID配置', + raid: 'RAID模式', + diskType: '磁盘类型', + interfaceType: '接口类型', + minNum: '单盘最小容量', + minimumQuantity: '最低数量(块)', + associatedDisk: '关联磁盘' + }, + diskPlaceholder: '请选择磁盘' + } + } + }, + imageDetail: { + header: { + title2: '镜像详情', + operate: { + title: '操作', + delete: '删除' + } + }, + tooltip: { + title: '无法删除镜像,请先删除该镜像与机型的关联关系', + image: '预置镜像不支持删除', + title2: '当前机型有实例在创建中,无法移除' + }, + add: { + model: '添加机型' + }, + tabs: { + basicInfo: '基本信息', + model: '关联机型' + }, + label: { + imageName: '镜像名称', + imageId: '镜像ID', + imageType: '镜像类型', + architecture: '体系架构', + operateSysPlatform: '操作系统平台', + operateSysVersion: '操作系统版本', + format: '镜像格式', + bootMode: '引导模式', + sysPartitionModule: '系统盘分区', + imageDesc: '镜像描述', + numberOfAssociatedModels: '已关联机型数', + createTime: '创建时间', + }, + table: { + label: { + modelName: '机型名称', + modelType: '机型类型', + idcName: '机房名称', + nameEn: '机房英文名称', + architecture: '体系架构', + modelSpecifications: '机型规格', + desc: '描述', + operate: { + title: '操作', + remove: '移除' + } + } + }, + empty: { + title: '添加机型' + } + }, + imageAddModel: { + header: { + title: '添加机型', + imageName: '镜像名称', + choose: '已选择机型个数' + }, + label: { + modelName: '机型名称', + modelType: '机型类型', + idcName: '机房名称', + nameEn: '机房英文名称', + architecture: '体系架构', + modelSpecifications: '机型规格', + desc: '描述' + }, + btn: { + save: '保存', + cancel: '取消' + } + }, + removeOperate: { + header: { + remove: '移除机型' + }, + content: { + deleteTip: '注意:移除后用户创建/重装该机型时无法使用该镜像版本,请谨慎操作!', + tip1: '确定将【{0}】所关联的【{1}{2}】移除吗?' + }, + btn: { + sure: '确定', + cancel: '取消' + } + }, + importImage: { + header: { + title: '导入镜像' + }, + content: { + label: { + imageName: '镜像名称', + architecture: '体系架构', + operateSysPlatform: '操作系统平台', + operateSysVersion: '操作系统版本', + imageFormat: '镜像格式', + bootMode: '引导模式', + systemPartitionTemplate: '系统盘分区', + imageDesc: '镜像描述', + chooseImage: '选择镜像' + }, + placeholder: { + imageName: '请输入镜像名称', + architecture: '请选择体系架构', + operateSysPlatform: '请选择操作系统平台', + customOperatePlatform: '请输入自定义操作系统平台', + customVersion: '请输入自定义操作系统版本', + operateSysVersion: '请选择操作系统版本', + imageFormat: '请选择镜像格式', + bootMode: '请选择引导模式', + imageDesc: '请输入镜像描述', + chooseImage: '选择镜像' + } + }, + emptyTip: { + imageName: '镜像输入不能为空', + architecture: '请选择体系架构', + operateSysPlatform: '请选择操作系统平台', + customOperatePlatform: '请输入自定义操作系统平台', + customVersion: '请输入自定义操作系统版本', + operateSysVersion: '请选择操作系统版本', + imageFormat: '请选择镜像格式', + bootMode: '请选择引导模式', + noData: '暂无数据' + }, + errTip: { + upload: '上传中,请勿关闭弹窗。', + imageName: '请输入1-64个字符', + imageRepeat: '镜像名称重复', + numberLimit: '镜像不能为空', + error: '上传失败' + }, + btn: { + cancel: '取消', + sure: '确定', + upLoad: '上传' + } + }, + collectInfoConfirm: { + header: { + title: '重新采集设备信息确认' + }, + tips: '请确定是否重新执行设备信息重新采集操作?', + checkbox: '清空RAID', + tipsCount: { + tip0: '注意:', + tip1: '1. 清除RAID操作是针对整个磁盘RAID进行删除操作,该操作不可恢复,请谨慎操作!
' + + '2. 清除RAID操作会清空服务器磁盘的所有数据,请备份好数据后再执行该操作,以免数据丢失给您造成损失。
' + } + }, + clearRaidConfirm: { + header: { + title: '清空RAID操作确认', + }, + tipsCount: { + tip0: '注意:', + tip1: '1. 清除RAID操作是针对整个磁盘RAID进行删除操作,该操作不可恢复,请谨慎操作!
' + + '2. 清除RAID操作会清空服务器磁盘的所有数据,请备份好数据后再执行该操作,以免数据丢失给您造成损失。
', + tip2: '您选择的设备【{0}】将执行清空RAID操作,您是否确定操作?' + }, + }, + deviceList: { + header: { + deviceList: '设备列表' + }, + radioBtn: { + computed: '计算型', + storage: '存储型', + GPU: 'GPU', + other: '其它' + }, + batchOperate: { + btn: { + open: '开机', + close: '关机', + restart: '重启', + recovery: '回收实例', + edit: '编辑实例名称', + resetPassword: '重置密码', + more: '更多' + }, + tip: { + default: '请选择资源', + turnOn: '仅关机状态实例可以开机', + resetPassword: '仅关机状态实例可以重置密码', + restart: '仅运行状态实例可以重启', + turnOff: '仅运行状态实例可以关机', + instanceName: '仅已创建实例支持编辑', + lock: '实例已锁定', + recovery: '只有处于“已关机”和“创建失败”的设备能进行“回收实例”操作' + } + }, + tooltip: { + up: '只有处于“已入库”状态下的设备才能上架', + model: '请先关联机型', + down: '只有处于“已上架”状态下的设备才能下架', + delete: '只有处于“已入库”状态下的服务器才能删除', + remove: '只有处于“运行中”和“已关机”的实例能进行“设备移除”操作', + lock: '实例已锁定', + lock1: '无法锁定该实例', + lock2: '无法解锁该实例', + recovery: '只有处于“已关机”和“创建失败”的设备能进行“回收实例”操作', + reset: '只有实例操作失败的设备能进行“重置实例状态”操作', + turnOn: '仅关机状态实例可以开机', + restart: '仅运行状态实例可以重启', + turnOff: '仅运行状态实例可以关机', + resetSystem: '仅关机状态实例可以重装系统', + resetPassword: '仅关机状态实例可以重置密码' + }, + instanceStatus: { + creating: '创建中', + starting: '开机中', + running: '运行', + stopping: '关机中', + stopped: '关机', + restarting: '重启中', + resetting_password: '重置密码中', + destroying: '销毁中', + destroyed: '已销毁', + error: '错误', + upgrading: '调整配置中', + reinstalling: '重装系统中' + }, + operate: { + instanceOperate: '实例操作', + error: { + tip: '操作失败,请联系管理员处理' + }, + exportDevice: '导入设备', + placeholder: { + sn: '请输入SN搜索', + instanceOwner: '请输入实例属主搜索' + }, + label: { + sn: 'SN', + instanceOwner: '实例属主' + }, + refresh: '刷新', + setUp: '设置', + export: '导出' + }, + content: { + label: { + sn: 'SN', + name: '机型名称', + modelName: '机型类型', + managementStatus: '管理状态', + collectionStatus: '采集状态', + computerRoomName: '机房名称', + cabinetCode: '机柜编码', + uBit: '所在U位', + brand: '品牌', + model: '型号', + architecture: '体系架构', + instanceImage: '镜像', + instanceName: '实例名称', + instanceID: '实例ID', + instanceStatus: '实例状态', + lockStatus: '锁定状态', + instanceOwner: '实例属主', + CPU: 'CPU', + storage: '内存', + sysDisc: '系统盘', + dataDisc: '数据盘', + GPU: 'GPU', + switchIPNetworkPortOne: '网口1交换机IP', + switchIPNetworkPortTwo: '网口2交换机IP', + networkPortOneUplinkPort: '网口1(eth0)上联端口', + networkPortTwoUplinkPort: '网口2(eth1)上联端口', + networkSettings: '网络设置', + outOfBandIP: '带外IP', + intranceIPv4: '内网IPv4(eth0)', + intranceIPv4First: '内网IPv4(eth1)', + intranetIPv6: '内网IPv6(eth0)', + intranetIPv6First: '内网IPv6(eth1)', + createTime: '创建时间', + desc: '描述', + remark: '备注', + operate: { + name: '操作', + up: '上架', + down: '下架', + more: '更多', + lock:'锁定', + unlock:'解锁', + delete: '设备删除', + reset: '重置实例状态', + remove: '设备移除', + recovery: '回收实例', + open: '开机', + close: '关机', + restart: '重启', + resetSystem: '重装系统', + resetPassword: '重置密码' + } + } + }, + managementStatus: { + warehousing: '已入库', + onTheShelf: '已上架', + created: '已创建', + onShelf: '上架中', + remove: '已移除', + unputaway: '已下架', + lowerShelf: '下架中', + error: '上架失败' + }, + status: { + collected: '已采集', + noCollected: '未采集', + collecting: '采集中', + collectionFailed: '采集失败' + } + }, + resetSystemConfirm: { + header: { + title: '重装系统须知', + tip0: '注意:', + tip: '' + + '1. 重装系统是针对系统盘做初始化、更换操作系统的操作,该操作不可恢复,请谨慎操作!
' + + '2. 该操作会清空实例系统盘所有数据,请备份好数据后再执行重装系统操作,以免数据丢失给您造成损失。
' + + '3. 重装系统后,系统默认不会为实例配置IPv6地址,您需要手工进行配置。', + tip2: '您选择的实例【{0}】将执行重装系统操作,您是否确定操作?' + } + }, + resetSystem: { + header: { + title: '重装系统配置', + tip0: '注意:', + tip: '' + + '1. 重装系统是针对系统盘做初始化、更换操作系统的操作,该操作不可恢复,请谨慎操作!
' + + '2. 该操作会清空实例系统盘所有数据,请备份好数据后再执行重装系统操作,以免数据丢失给您造成损失。
' + + '3. 重装系统后,系统默认不会为实例配置IPv6地址,您需要手工进行配置。', + instanceInfo: '实例信息', + imageType: '镜像类型', + system: '系统盘', + systemPartition: '系统盘分区', + systemVolume: '系统卷', + systemVolumePartition: '系统卷分区', + bootMode: '引导模式', + hostName: 'HostName', + userName: '用户名', + setPassword: '设置密码', + password: '密码', + confirmPassword: '确认密码', + performanceMonitoring: '性能监控', + agent: '安装监控Agent' + }, + table: { + label: { + instanceName: '实例名称', + instanceID: '实例ID', + operatingSystem: '操作系统', + createdTime: '创建时间', + sshName: '密钥名称' + } + }, + placeholder: { + select: '请选择', + hostName: '可选填,操作系统内部的计算机名' + }, + regCheckTip: { + hostName: '长度为 2-64 个字符,允许使用点号(.)分隔 字符成多段,每段允许使用大小写字母、数字或连字符(-),但不能连续使用点号(.)或连字符(-)。不能以点号(.)或连字符(-)开头或结尾', + password: "8-30个字符,同时包含三项(大写字母,小写字母,数字或特殊符号()`~!{'@'}#{'{'}{'}'}{'$'}%&*_-+={'|'}[]:\";\'<>,.?/)", + password2: '密码不一致,请重新输入' + }, + emptyCheck: { + sshKey: '密钥不能为空', + password: '密码不能为空', + confirmPassword: '确认密码不能为空', + repeat: '密码不一致,请重新输入' + }, + radio: { + customPassword: '自定义密码', + sshKeyLogin: '密钥登录' + }, + tip1: '提供实时故障告警' + }, + resetPassword: { + header: { + title: '重置密码', + tip: '注意:重置密码后,需要在控制台/运营平台对实例进行开机才能生效', + resetPassword1: '您选择的 ', + resetPassword2: ' 台实例将执行重置密码操作,您是否确定操作?', + }, + table: { + label: { + instanceName: '实例名称', + instanceId: '实例ID', + outOfBandIP: '带外IP', + intranceIPv4: '内网IPv4(eth0)' + } + }, + ipt: { + label: { + password: '密码', + newPassword: '新密码', + confirmPassword: '确认密码' + }, + errorTip: { + password: "8-30个字符,同时包含三项(大写字母,小写字母,数字或特殊符号()`~!{'@'}#{'{'}{'}'}{'$'}%&*_-+={'|'}[]:\";\'<>,.?/)", + newPassword: "8-30个字符,同时包含三项(大写字母,小写字母,数字或特殊符号()`~!{'@'}#{'{'}{'}'}{'$'}%&*_-+={'|'}[]:\";\'<>,.?/)", + confirmPassword: '密码不一致,请重新输入' + }, + emptyTip: { + password: '密码不能为空', + newPassword: '新密码不能为空', + confirmPassword: '确认密码不能为空', + } + } + }, + batchOperate: { + instanceName: { + title: '批量编辑实例名称', + tip: '注意:通过此方式编辑的多台实例名称为连续命名', + tip1: '您选择的 ', + tip2: ' 台实例将执行批量编辑实例名称操作,您是否确定操作?', + label: { + instanceName: '实例名称', + instanceId: '实例ID', + outOfBandIP: '带外IP', + intranceIPv4: '内网IPv4(eth0)', + newInstanceName: '新实例名称' + }, + iptTip: { + text: '2-128个字符,以大小写字母或中文开头,可包含数字、“.”、“_”、“:”或“-”', + empty: '实例名称不能为空', + repeat: '实例名称重复' + } + }, + recoveryInstance: { + title: '批量回收实例', + tip: '注意:回收实例将会清空实例上的所有数据,请谨慎操作。', + recovery1: '您选择的 ', + recovery2: ' 台实例将执行回收实例操作,您是否确定操作?', + label: { + instanceName: '实例名称', + instanceId: '实例ID', + outOfBandIP: '带外IP', + intranceIPv4: '内网IPv4(eth0)' + }, + }, + openCloseRestart: { + open: '批量开机', + close: '批量关机', + restart: '批量重启', + open1: '您选择的 ', + open2: ' 台实例将执行开机操作,您是否确定操作?', + close1: '您选择的 ', + close2: ' 台实例将执行关机操作,您是否确定操作?', + restart1: '您选择的 ', + restart2: ' 台实例将执行重启操作,您是否确定操作?', + label: { + instanceName: '实例名称', + instanceId: '实例ID', + outOfBandIP: '带外IP', + intranceIPv4: '内网IPv4(eth0)' + } + }, + resetPassword: { + header: { + title: '批量重置密码', + tip: '注意:
' + + '1. 通过此方式重置密码的多个实例密码均相同
' + + '2. 重置密码后,需要在控制台/运营平台对实例进行开机才能生效', + resetPassword1: '您选择的 ', + resetPassword2: ' 台实例将执行重置密码操作,您是否确定操作?', + }, + table: { + label: { + instanceName: '实例名称', + instanceId: '实例ID', + outOfBandIP: '带外IP', + intranceIPv4: '内网IPv4(eth0)' + } + }, + ipt: { + label: { + password: '密码', + newPassword: '新密码', + confirmPassword: '确认密码' + }, + errorTip: { + password: "8-30个字符,同时包含三项(大写字母,小写字母,数字或特殊符号()`~!{'@'}#{'{'}{'}'}{'$'}%&*_-+={'|'}[]:\";\'<>,.?/)", + newPassword: "8-30个字符,同时包含三项(大写字母,小写字母,数字或特殊符号()`~!{'@'}#{'{'}{'}'}{'$'}%&*_-+={'|'}[]:\";\'<>,.?/)", + confirmPassword: '密码不一致,请重新输入' + }, + emptyTip: { + password: '密码不能为空', + newPassword: '新密码不能为空', + confirmPassword: '确认密码不能为空', + } + } + } + }, + lockInstance: { + header: { + lock:'锁定', + unlock:'解锁', + }, + lockTip:'确定锁定实例【{0}】?', + unlockTip:'确定解锁实例【{0}】?', + tip: '锁定实例后“删除”操作不可用,如需使用需提前解锁', + btn: { + cancel: '取消', + sure: '确定' + } + }, + deviceDetail: { + header: { + deviceList: '设备列表', + title2: '设备详情' + }, + operate: { + name: '操作', + up: '上架', + down: '下架', + open: '开机', + close: '关机', + restart: '重启', + reset: '重置实例状态', + remove: '设备移除', + recovery: '回收实例', + lock:'锁定', + unlock:'解锁', + delete: '设备删除', + resetSystem: '重装系统', + resetPassword: '重置密码', + error: { + tip: '操作失败,请联系管理员处理' + } + }, + tooltip: { + up: '只有处于“已入库”状态下的设备才能上架', + model: '请先关联机型', + associatedModels: '只有处于“已入库”状态下的设备才能关联机型', + down: '只有处于“已上架”状态下的设备才能下架', + delete: '只有处于“已入库”状态下的服务器才能删除', + remove: '只有处于“运行中”和“已关机”的实例能进行“设备移除”操作', + recovery: '只有处于“已关机”和“创建失败”的设备能进行“回收实例”操作', + lock: '实例已锁定', + lock1: '无法锁定该实例', + lock2: '无法解锁该实例', + reset: '只有实例操作失败的设备能进行“重置实例状态”操作', + turnOn: '仅关机状态实例可以开机', + restart: '仅运行状态实例可以重启', + turnOff: '仅运行状态实例可以关机', + resetPassword: '仅关机状态实例可以重置密码', + resetSystem: '仅关机状态实例可以重装系统' + }, + deviceInfo: { + deviceInfo: '设备信息', + sn: 'SN', + modelName: '机型名称', + recapture: '重新采集', + managementStatus: '管理状态', + collectionStatus: '采集状态', + computerRoomName: '机房名称', + cabinetCode: '机柜编码', + uBit: '所在U位', + remark: '备注' + }, + instanceInfo: { + instanceInfo: '实例信息', + instanceName: '实例名称', + instanceID: '实例ID', + instanceImage: '镜像', + instanceStatus: '实例状态', + monitorAgentStatus: '监控Agent状态', + lockStatus: '锁定状态', + instanceOwner: '实例属主', + createTime: '创建时间', + desc: '描述' + }, + hardwareConfiguration: { + modelInfo: '机型信息', + hardwareConfiguration: '硬件配置', + brand: '品牌', + model: '型号', + architecture: '体系架构', + CPU: 'CPU', + storage: '内存', + sysDisc: '系统盘', + adapeterId: 'adapeter_id(RAID卡)', + enclosure1: '系统盘1背板号(enclosure)', + slot1: '系统盘1槽(slot)', + enclosure2: '系统盘2背板号(enclosure)', + slot2: '系统盘2槽(slot)', + dataDisc: '数据盘', + GPU: 'GPU', + networkCard: '网卡', + networkSettings: '网络设置' + }, + networkInfo: { + networkInfo: '网络信息', + intranceIPv4: '内网IPv4(eth0)', + intranceIPv4First: '内网IPv4(eth1)', + intranetIPv6: '内网IPv6(eth0)', + intranetIPv6First: '内网IPv6(eth1)', + mac1: 'MAC1(eth0)', + mac2: 'MAC2(eth1)', + switchIPOne: '交换机IP1(eth0)', + switchIPTwo: '交换机IP2(eth1)', + switchUplinkPortOne: '交换机上联端口1(eth0)', + switchUplinkPortTwo: '交换机上联端口2(eth1)', + subnetMask: '子网掩码(eth0)', + subnetMaskFirst: '子网掩码(eth1)', + networkGateway: '网关' + }, + switchOutsideInfo: { + switchOutsideInfo: '交换机&带外信息', + userName1: '网口1交换机登录用户名', + password1: '网口1交换机登录密码', + userName2: '网口2交换机登录用户名', + password2: '网口2交换机登录密码', + outOfBandIP: '带外IP', + outOfBandLoginUserName: '带外登录用户名', + outOfBandLoginPassWord: '带外登录密码' + }, + editDesc: { + header: { + title: '描述', + title2: '备注' + }, + count: { + title: '修改描述:', + title2: '修改备注:' + }, + placeholder: '请输入描述', + placeholder2: '请输入备注', + btn: { + cancel: '取消', + sure: '确定' + } + }, + tabs: { + baseInfo: '基本信息', + diskDetail: '磁盘详情', + hardwareMonitoring: '硬件监控', + performanceMonitoring: '性能监控', + operatLog: '操作日志' + }, + diskDetail: { + physicalDiskView: '物理盘视图', + table: { + label: { + disk: '磁盘', + singleDiskCapacity: '单盘容量', + diskType: '磁盘类型', + interfaceType: '接口类型', + enclosure: '背板号(enclosure)', + slot: '槽位(slot)' + } + }, + logicalDriveView: '逻辑盘视图', + table2: { + label: { + driveLetterName: '盘符名称', + singleDiskCapacity: '单盘容量', + diskType: '磁盘类型', + interfaceType: '接口类型', + } + }, + modelRolInfo: '机型卷信息', + modelInfo: '机型信息', + modelName: '机型名称', + btn: '关联机型', + volumeManager: { + table: { + label: { + volumeName: '卷名称', + volumeType: '卷类型', + raid: 'RAID模式', + diskType: '磁盘类型', + interfaceType: '接口类型', + minNum: '单盘最小容量', + minimumQuantity: '最低数量(块)', + associatedDisk: '关联磁盘' + } + } + } + }, + hardwareMonitoring: { + hardwareDeviceStatus: '硬件设备状态', + alarmLogList: '报警日志列表', + status: { + title: { + cpu: 'CPU', + storage: '内存', + hardDisk: '硬盘', + networkCard: '网卡', + powerSupply: '电源', + other: '其他' + }, + normal: '正常', + error: '异常' + } + }, + table: { + label: { + serialNumber: '序号', + faultType: '故障类型', + faultDesc: '故障描述', + faultAlarmTime: '故障报警时间', + updateTime: '更新时间', + alarmNum: '报警次数', + status: '状态' + } + }, + status: { + collected: '已采集', + noCollected: '未采集', + collecting: '采集中', + collectionFailed: '采集失败' + }, + operatLog: { + header: { + title: '操作日志', + tips: '(以下列表包括了近90天的操作记录)' + }, + search: { + label: { + operatePeople: '操作人', + operateTime: '操作时间', + }, + placeholder: { + operatePeople: '请输入操作人', + startDate: '开始日期', + endDate: '结束日期' + }, + btn: { + search: '搜索', + clear: '清空' + } + }, + table: { + label: { + logId: 'LogID', + operateName: '操作名称', + operatePeople: '操作人', + operateTime: '操作时间', + operateFeedback: '操作反馈', + failCode: '错误码' + } + } + } + }, + editDesc: { + header: { + title: '描述', + title2: '备注' + }, + count: { + title: '修改描述:', + title2: '修改备注:' + }, + placeholder: '请输入描述', + placeholder2: '请输入备注', + btn: { + cancel: '取消', + sure: '确定' + } + }, + removeRecovery: { + header: { + remove: '设备移除', + recovery: '回收实例' + }, + tooltip: { + remove: '请确定是否移除以下设备?', + recovery: '请确定是否回收以下实例?' + }, + checkbox: { + remove: '我已知晓以上注意事项并同意设备移除', + recovery: '我已知晓以上注意事项并同意回收实例' + }, + operateTip: { + remove: '注意:
' + + '1. 设备移除操作后控制台将不显示此实例,同时此实例不会进入库存,无法再次购买
' + + '2. 自动解除设备和实例属主的关联关系', + recovery: '注意:
' + + '1. 回收实例操作完成后设备重新入库,自动解除设备和实例属主的关联关系
' + + '2. 为避免数据丢失,请确认数据已备份,回收实例操作会清空实例上所有数据(包含系统盘和数据盘),彻底删除实例且无法恢复' + }, + btn: { + cancel: '取消', + sure: '确定' + } + }, + resetInstance: { + header: { + title: '重置实例状态' + }, + tooltip: { + title: '注意:
' + '重置实例状态操作实例状态重置为上一个实例稳定状态', + count: { + tip1: '确定将', + tip2: '重置实例状态?' + } + }, + btn: { + cancel: '取消', + sure: '确定' + } + }, + importDevice: { + header: { + title: '导入设备' + }, + label: { + computerRoomName: '机房名称', + modelName: '机型名称', + deviceInfo: '设备信息' + }, + placeholder: { + computerRoomName: '请选择机房', + modelName: '请选择机型', + }, + errTip: { + upload: '上传中,请勿关闭弹窗。', + computerRoomName: '请选择机房名称', + modelName: '请选择机型名称', + deviceInfo: '请选择设备信息', + error: '上传失败', + }, + noData: { + tip: '暂无数据' + }, + operate: { + tip1: '如无合适机型,可以', + addNewModel: '添加新机型', + templateDownLoad: '模板下载' + }, + btn: { + selectionFile: '选取文件', + cancel: '取消', + sure: '确定' + }, + tooltip: { + first: '1. 仅支持选取1个附件,且大小不超过20M;', + two: '2. 为保证上传成功,请勿对模板中的单元格进行更改;', + third: '3. 仅支持一个文件上传,多个文件上传会替换原文件;' + } + }, + upDownFrame: { + operate: { + addNewModel: '添加新机型', + }, + placeholder: { + tip1: '请选择', + tip2: '关联磁盘不能为空' + }, + table: { + label: { + volumeName: '卷名称', + volumeType: '卷类型', + raidCan: 'RAID配置', + raid: 'RAID模式', + diskType: '磁盘类型', + interfaceType: '接口类型', + minNum: '单盘最小容量', + amount: '最低数量(块)', + associatedDisk: '关联磁盘' + } + }, + noData: { + tip: '暂无数据' + }, + steps: { + title1: '关联机型', + title2: '确认设备' + }, + select: { + model: '选择机型', + placeholder: '请选择机型' + }, + titleTip: { + up: '上架', + down: '下架', + delete: '设备删除' + }, + countTitleTip: { + down: '注意:设备下架成功后,服务器状态将变更为“已入库”', + delete: '注意:设备删除执行后无法撤销,如需再次使用需要重新导入' + }, + headerTitleTip: { + up: '设备上架后才可创建使用,请确定是否上架以下设备?', + down: '请确定是否下架以下设备?', + delete: '请确定是否删除以下设备?' + }, + btn: { + pre: '上一步', + next: '下一步', + cancel: '取消', + sure: '确定' + } + }, + publicTable: { + label: { + sn: 'SN', + instanceName: '实例名称', + instanceId: '实例ID', + instanceOwner: '实例属主', + cabinetCode: '机柜编码', + uBit: '所在U位', + outOfBandIP: '带外IP', + intranceIPv4: '内网IPv4(eth0)' + } + }, + openShutDownRestart: { + titleTip: { + open: '开机', + close: '关机', + restart: '重启' + }, + tooltipInfo: { + open: '确定开启实例:', + close: '确定关闭实例:', + restart: '确定重启实例:' + }, + btn: { + cancel: '取消', + sure: '确定' + } + }, + modelForm: { + header: { + params: { + text1: '常规参数', + text2: '配置参数' + } + }, + config: { + configured: '需配置RAID', + notConfigured: '无需配置RAID' + }, + radioBtn: { + computed: '计算型', + storage: '存储型', + GPU: 'GPU', + other: '其它' + }, + netWork: { + single: '单网口', + dual: '双网口', + bond: '单网口bond' + }, + specificationsType: { + presetSpecifications: '预置规格', + otherSpecifications: '其它规格' + }, + tooltip: { + tip: ' 以机型{0}为模板添加新机型', + title: '机型规格与机型名称一一对应,建议可以使用【规格属性】+【实例类型】+【体系架构】。
例:c1.medium.x86' + }, + noData: { + tip: '暂无数据' + }, + list: { + manufacturer: '龙芯3号' + }, + raid: '单盘RAID0', + none: '无', + unrestricted: '无限制', + label: { + computerRoomName: '机房名称', + modelType: '机型类型', + modelName: '机型名称', + architecture: '体系架构', + bootMode: '引导模式', + modelSpecifications: '机型规格', + desc: '描述', + cpu: 'CPU', + cpuParams: 'CPU参数', + processorManufacturer: '处理器厂商', + modelChoose: '型号', + numberPhysicalCores: '物理核数', + dominantFrequency: '主频(GHz)', + system: '系统卷', + card: '阵列卡', + data: '数据卷', + numberOfRoutes: '数量', + storage: '内存', + storageParams: '内存参数', + interface: '接口', + dominantFrequencyMHz: '主频(MHz)', + capacity: '容量(GB)', + modelNumber: '数量', + sysType: '系统盘类型', + sysInterfaceType: '系统盘接口类型', + sysSingleCapacityVal: '系统盘单块容量', + sysNumber: '系统盘数量(块) ', + raidConfig: 'RAID配置', + sysRAID: '系统盘RAID', + dataType: '数据盘类型', + dataInterfaceType: '数据盘接口类型', + dataSingleCapacityVal: '数据盘单块容量', + dataNumber: '数据盘数量(块) ', + networkSpeed: '网卡速度(GE)', + networkNumber: '网口数量(个)', + networkSettings: '网口设置', + gpuBrand: 'GPU(品牌)', + gpuModel: 'GPU(型号)', + gpuNumber: 'GPU数量(个)', + heightU: '高度(U)', + volumeManage: { + title: '卷管理', + label: { + name: '卷名称', + type: '卷类型', + raidCan: 'RAID配置', + raid: 'RAID模式', + disk: '磁盘类型', + interfaceType: '接口类型', + minNum: '单盘最小容量', + amount: '最低数量(块)', + operate: '操作' + }, + placeholder: { + tip1: '请输入' + }, + empty: { + name: '卷名称不能为空', + type: '请选择卷类型', + raidCan: '请选择RAID配置', + raid: '请选择RAID模式', + disk: '请选择磁盘类型', + interfaceType: '请选择接口类型', + minNum: '单盘最小容量不能为空', + amount: '数量不能为空', + }, + save: { + volumeManagement: '请保存卷管理', + empty: '卷管理不能为空' + }, + sys: { + tip1: '至少添加一个系统卷', + tip2: '只能添加一个系统卷' + }, + btn: { + cancel: '取消', + add: '添加卷', + sure: '确定', + save: '保存', + edit: '编辑', + delete: '删除' + } + } + }, + placeholder: { + modelName: '请输入机型名称(1-64个字符)', + modelSpecifications: '请输入机型规格', + desc: '请输入描述', + select: '请选择', + processorManufacturer: '请选择处理器厂商', + modelChoose: '请输入型号', + dominantFrequency: '请选择主频(GHz)', + interface: '请选择接口', + dominantFrequencyMHz: '请选择主频(MHz)', + capacity: '请选择容量(GB)', + sysType: '请选择系统盘类型', + sysInterfaceType: '请选择系统盘接口类型', + sysSingleCapacityVal: '请输入系统盘单块容量', + raidConfig: '请选择RAID配置', + sysRAID: '请选择系统盘RAID', + dataType: '请选择数据盘类型', + dataInterfaceType: '请选择数据盘接口类型', + dataSingleCapacityVal: '请输入数据盘单块容量', + networkSpeed: '请选择网卡速度(GE)', + networkSettings: '请选择网口设置', + gpuBrand: '请选择GPU(品牌)', + gpuModel: '请选择GPU(型号)', + heightU: '请选择高度(U)' + }, + emptyTip: { + modelName: '机型名称输入不能为空', + modelSpecifications: '机型规格输入不能为空', + cpu: 'CPU不能为空', + processorManufacturer: '处理器厂商不能为空', + modelChoose: '型号输入不能为空', + dominantFrequency: '主频(GHz)不能为空', + storage: '内存不能为空', + interface: '接口不能为空', + dominantFrequencyMHz: '主频(MHz)不能为空', + capacity: '容量(GB)不能为空', + sysType: '系统盘类型不能为空', + sysInterfaceType: '系统盘接口类型不能为空', + sysSingleCapacityVal: '系统盘单块容量输入不能为空', + raidConfig: 'RAID配置不能为空', + sysRAID: '系统盘RAID不能为空', + dataType: '数据盘类型不能为空', + dataInterfaceType: '数据盘接口类型不能为空', + dataSingleCapacityVal: '数据盘单块容量输入不能为空', + networkSpeed: '网卡速度(GE)不能为空', + networkSettings: '网络设置不能为空', + gpuBrand: 'GPU(品牌)不能为空', + gpuModel: 'GPU(型号)不能为空', + heightU: '高度(U)不能为空' + }, + errorTip: { + number: '1-64字符,输入内容为数字,允许输入小数点', + number1: '只能输入数字', + title: '请输入合法的手机号码', + number2: '只能输入数字,小数保留2位', + number3: '超出最大限制', + currency: '1-64字符,只支持中文、数字、大小写字母、英文下划线“_”及中划线“-”"', + currency2: '请输入1-64个字符', + modelSpecifications: '机型规格与机型名称不能重复', + name: '机型名称重复', + specifications: '机型规格重复' + } + }, + resourceMonitor: { + header: { + resourceMonitor: '资源监控图' + }, + search: { + userName: '用户名', + resourceType: '资源类型', + idcName: '机房', + instanceId: '实例ID', + dimensions: '维度', + monitoringMetrics: '监控指标', + btn: { + search: '搜索', + clear: '清空' + }, + count: { + resourceType: '实例', + dimensions: '实例' + } + }, + placeholder: { + userName: '请输入用户名', + resourceType: '请选择资源类型', + idcName: '请选择机房', + instanceId: '请输入实例ID', + dimensions: '请选择维度', + monitoringMetrics: '请选择监控指标' + }, + errorTip: { + userName: '请输入用户名', + resourceType: '请选择资源类型', + idcName: '请选择机房', + instanceId: '请输入实例ID', + dimensions: '请选择维度', + monitoringMetrics: '请选择监控指标' + } + }, + historyAlarmInfo: { + header: { + historyAlarmInfo: '历史报警信息' + }, + search: { + label: { + userName: '用户名', + alarmTime: '报警时间' + }, + placeholder: { + userName: '请输入用户名', + startDate: '开始日期', + endDate: '结束日期' + }, + errorTip: { + userName: '请输入用户名', + alarmTime: '请选择报警时间' + }, + btn: { + search: '搜索', + clear: '清空' + } + }, + table: { + label: { + name: '用户名', + alarmTime: '报警时间', + resourceName: '资源类型', + resourceId: '报警资源ID', + triggerDescription: '触发条件', + alertValue: '报警值', + alertLevelDescription: '报警级别', + alertPeriod: '持续时间', + userName: '通知对象' + }, + count: { + minute: '分钟' + } + } + }, + allAlarmRulesList: { + header: { + allAlarmRulesList: '全部报警规则' + }, + select: { + alarm: '报警', + normal: '正常', + forbid: '已禁用', + }, + search: { + label: { + userName: '用户名', + ruleName: '规则名称', + ruleId: '规则ID' + }, + placeholder: { + userName: '请输入用户名', + ruleName: '请输入规则名称', + ruleId: '请输入规则ID' + }, + errorTip: { + userName: '请输入用户名', + ruleName: '请输入规则名称', + ruleId: '请输入规则ID' + }, + btn: { + search: '搜索', + clear: '清空' + } + }, + table: { + label: { + ruleName: '规则名称', + userName: '用户名', + ruleId: '规则ID', + resourceName: '资源类型', + instanceCount: '实例关联数量', + triggerDescription: '触发条件', + statusName: '状态', + operate: { + title: '操作', + lookDetail: '查看详情', + alarmHistory: '报警历史' + } + } + } + }, + allAlarmRulesDetail: { + header: { + title2: '报警规则详情', + operate: { + alarmHistory: '报警历史' + } + }, + count: { + minute: '分钟', + hours: '小时' + }, + baseInfo: { + title: '基本信息', + label: { + ruleId: '规则ID', + ruleName: '规则名称', + resourceType: '资源类型' + } + }, + alarmResources: { + title: '报警资源', + table: { + label: { + instanceName: '实例名称', + instanceId: '实例ID', + ipv4: '内网IPV4(eth0)', + ipv6: '内网IPV6(eth0)' + } + } + }, + triggeringConditions: { + title: '触发条件' + }, + notificationStrategy: { + title: '通知策略', + label: { + notificationCycle: '通知周期', + effectivePeriod: '有效时段', + notificationConditions: '通知条件', + receivingChannel: '接收渠道', + notificationObject: '通知对象' + } + }, + notice: { + email: '邮件', + internalMessage: '站内信' + } + }, + hardwareStatusList: { + header: { + hardwareStatusList: '硬件设备状态' + }, + search: { + label: { + idcName: '机房', + sn: 'SN' + }, + placeholder: { + idcName: '请选择', + sn: '请输入SN号' + }, + btn: { + search: '搜索', + clear: '清空' + } + }, + table: { + label: { + sn: 'SN', + idc: '机房', + brand: '品牌', + model: '型号', + managementStatus: '管理状态', + cpu: 'CPU', + storage: '内存', + hardDisk: '硬盘', + networkCard: '网卡', + powerSupply: '电源', + other: '其他', + operate: '操作', + opt: '历史故障' + } + } + }, + surveillance: { + status: { + all: '全部', + no: '未处理', + yes: '已处理' + }, + accessory: { + cpu: 'CPU', + mem: '内存', + hardDisk: '硬盘', + networkCard: '网卡', + powerSupply: '电源', + voltage: '电压', + fan: '风扇', + temperature: '温度', + pcie: 'PCIE 总线' + }, + }, + faultLogList: { + header: { + faultLogList: '故障报警日志' + }, + search: { + label: { + idcName: '机房', + sn: 'SN', + level: '故障等级', + time: '首次故障报警时间', + accessory: '故障配件', + status: '状态' + }, + placeholder: { + idcName: '请选择', + sn: '请输入SN号', + level: '请选择', + startDate: '开始日期', + endDate: '结束日期', + accessory: '请选择', + status: '请选择' + }, + btn: { + search: '搜索', + clear: '清空' + } + }, + table: { + label: { + logId: 'LogID', + sn: 'SN', + idc: '机房', + level: '故障等级', + type: '故障类型', + accessory: '故障配件', + iloip: 'iloIP', + desc: '故障描述', + originalLog: '故障原始日志', + status: '状态', + numberOfAlarms: '报警次数', + faultDetectionTime: '带外故障发现时间', + faultAlarmTime: '首次故障报警时间', + updateTime: '更新时间', + operate: '操作' + }, + operate: { + title: '处理', + tip: '仅未处理的故障日志可处理' + } + } + }, + faultRulesList: { + header: { + faultRulesList: '故障报警规则' + }, + search: { + label: { + faultName: '故障名称', + faultAccessories: '故障配件', + faultLevel: '故障等级' + }, + placeholder: { + faultName: '请输入故障名称', + faultAccessories: '请选择', + faultLevel: '请选择' + }, + btn: { + search: '搜索', + clear: '清空', + restoreDefaultSet: '恢复默认设置' + } + }, + table: { + label: { + faultName: '故障名称', + faultAccessories: '故障配件', + faultType: '故障类型', + judgmentConditions: '判定条件', + decisionThreshold: '判定阈值', + faultLevel: '故障等级', + faultDesc: '故障描述', + faultPush: '故障推送', + enableStatus: '启用状态', + } + } + }, + faultHandingConfirm: { + header: { + title: '故障处理确认', + tip1: '注意:故障处理后状态变更为“已处理”,不可取消,请谨慎操作。', + tip2: '请确认是否处理恢复以下故障?' + }, + label: { + sn: 'SN', + faultName: '故障名称', + faultType: '故障类型', + faultLevel: '故障等级', + faultDesc: '故障描述', + time: '首次故障报警时间' + } + }, + defaultSet: { + header: { + title: '恢复默认设置', + tip1: '注意:恢复默认设置后所有的故障状态将恢复到初始状态,请谨慎操作', + tip2: '请确认是否要恢复以下故障至初始状态?' + }, + label: { + faultName: '故障名称', + faultType: '故障类型', + faultLevel: '故障等级', + faultDesc: '故障描述' + } + }, + faultOperation: { + header: { + title: '故障操作确认', + tip1: '请确定启用【{0}】故障?', + tip2: '请确定禁用【{0}】故障?' + } + }, + faultPush: { + header: { + title: '故障推送操作确认', + tip1: '请确定启用【{0}】的故障推送?', + tip2: '请确定禁用【{0}】的故障推送?' + } + }, + roleList: { + header: { + roleList: '角色列表' + }, + operate: { + refresh: '刷新', + setUp: '设置', + export: '导出' + }, + label: { + role: '角色', + relationUser: '关联用户', + jurisdiction: '权限' + } + }, + userList: { + header: { + userList: '用户列表' + }, + operate: { + addUser: '添加用户', + refresh: '刷新', + setUp: '设置', + export: '导出' + }, + search: { + placeholder: { + userName: '请输入用户名' + }, + condition: { + userName: '用户名' + } + }, + label: { + userName: '用户名', + userId: '用户ID', + role: '角色', + itemNum: '项目数', + cellPhone: '手机', + email: '邮箱', + desc: '描述', + createTime: '创建时间', + operate: { + name: '操作', + edit: '编辑', + delete: '删除', + tooltip: { + delete: '平台拥有者无法删除', + delete2: '请先移除此用户关联的项目' + } + } + } + }, + createKey: { + header: { + title: '创建API密钥' + }, + form: { + label: { + keyName: '密钥名称', + permissions: '权限' + }, + placeholder: { + keyName: '请输入密钥名称', + permissions: '请选择权限' + } + }, + select: { + title: '读/写' + }, + empty: { + keyName: '密钥名称输入不能为空', + permissions: '权限不能为空' + }, + errorTip: { + keyName: '1-64字符,只支持中文、数字、大小写字母、英文下划线“_”及中划线“-”"', + repeat: '密钥名称重复' + }, + btn: { + cancel: '取消', + sure: '确定' + } + }, + ower: { + tips1: '您尚未开通此项模块,请您将', + tips2: '请求码', + tips3: '和', + tips4: '需求', + tips5: '发送电子邮件至 ', + tips6: ',我们将尽快与您联系。', + tips7: '您尚未开通此项模块' + }, + deleteKey: { + header: { + title: '删除API密钥' + }, + content: { + title: '请确认是否删除密钥:{0}?' + }, + btn: { + cancel: '取消', + sure: '确定' + } + }, + addUser: { + header: { + addUser: '添加用户' + }, + label: { + role: '角色', + userName: '用户名', + password: '密码', + desc: '描述', + cellPhone: '手机', + email: '邮箱' + }, + role: { + owner: '平台拥有者', + user: '普通用户', + operator: '运营人员' + }, + default: { + userName: '1~32 字符,只支持数字、大小写字母、英文下划线 “_”及中划线“-”' + }, + placeholder: { + userName: '请输入用户名', + password: '请输入密码', + desc: '请输入描述', + cellPhone: '请输入手机号', + email: '请输入邮箱地址' + }, + emptyTip: { + userName: '用户名输入不能为空', + password: '密码输入不能为空', + cellPhone: '手机号输入不能为空', + email: '邮箱地址输入不能为空' + }, + errorTip: { + number: '只能输入数字', + userName: '请输入正确的用户名', + password: "8-30个字符,同时包含三项(大写字母,小写字母,数字或特殊符号()`~!{'@'}#{'{'}{'}'}{'$'}%&*_-+={'|'}[]:\";\'<>,.?/)", + repeatUserName: '用户名重复', + cellPhone: '请输入正确的手机号', + email: '请输入正确的邮箱地址', + HongKong: '请输入正确的中国香港手机号', + MacaMacao: '请输入正确的中国澳门手机号', + Taiwan: '请输入正确的中国台湾手机号' + }, + tooltip: { + count: '1:平台拥有者,拥有访问控制台&运营平台访问权限,全部操作权限。
' + + '2:普通用户,拥有控制台访问权限,所有操作权限,无运营平台访问权限。
' + + '3:运营人员,拥有运营平台访问权限,所有操作权限(除用户管理和角色管理)。' + }, + phoneData: { + China: '中国大陆 +86', + HongKong: '中国香港 +852', + MacaMacao: '中国澳门 +853', + Taiwan: '中国台湾 +886', + Argentina: '阿根廷 +54', + Australia: '澳大利亚 +61', + Brazil: '巴西 +55', + Germany: '德国 +49', + France: '法国 +33', + SouthKorea: '韩国 +82', + Canada: '加拿大 +1', + USA: '美国 +1', + Mexico: '墨西哥 +52', + SouthAfrica: '南非 +27', + Japan: '日本 +81', + SaudiArabia: '沙特阿拉伯 +966', + Turkey: '土耳其 +90', + Italy: '意大利 +39', + India: '印度 +91', + Indonesia: '印度尼西亚 +62', + UnitedKiongdom: '英国 +44' + }, + btn: { + cancel: '取消', + sure: '确定' + } + }, + errorTip: { + title: '请输入合法的手机号码' + }, + editUser: { + header: { + editUser: '编辑用户' + }, + label: { + role: '角色', + userName: '用户名', + userId: '用户ID', + desc: '描述', + cellPhone: '手机', + email: '邮箱' + }, + placeholder: { + desc: '请输入描述', + cellPhone: '请输入手机号', + email: '请输入邮箱地址' + }, + emptyTip: { + desc: '描述输入不能为空', + cellPhone: '手机号输入不能为空', + email: '邮箱地址输入不能为空' + }, + errorTip: { + number: '只能输入数字', + cellPhone: '请输入正确的手机号', + email: '请输入正确的邮箱地址', + HongKong: '请输入正确的中国香港手机号', + MacaMacao: '请输入正确的中国澳门手机号', + Taiwan: '请输入正确的中国台湾手机号' + }, + phoneData: { + China: '中国大陆 +86', + HongKong: '中国香港 +852', + MacaMacao: '中国澳门 +853', + Taiwan: '中国台湾 +886', + Argentina: '阿根廷 +54', + Australia: '澳大利亚 +61', + Brazil: '巴西 +55', + Germany: '德国 +49', + France: '法国 +33', + SouthKorea: '韩国 +82', + Canada: '加拿大 +1', + USA: '美国 +1', + Mexico: '墨西哥 +52', + SouthAfrica: '南非 +27', + Japan: '日本 +81', + SaudiArabia: '沙特阿拉伯 +966', + Turkey: '土耳其 +90', + Italy: '意大利 +39', + India: '印度 +91', + Indonesia: '印度尼西亚 +62', + UnitedKiongdom: '英国 +44' + }, + btn: { + cancel: '取消', + sure: '确定' + } + }, + myProfile: { + header: { + myProfile: '我的账户' + } + }, + securitySettings: { + header: { + securitySettings: '安全设置' + } + }, + apiKey: { + header: { + apiKey: '个人API密钥' + } + }, + userCenter: { + header: { + userCenter: '个人中心', + title1: '基本信息', + title2: '偏好设置' + }, + tabs: { + myProfile: '我的账户', + securitySettings: '安全设置', + apiKey: '个人API密钥', + }, + label: { + role: '角色', + userName: '用户名', + email: '邮箱', + phoneNumber: '手机', + language: '语言', + time: '时区' + }, + currectPassword: '当前密码', + newPassword: '新密码', + confirmPassword: '确认密码', + emptyTip: { + currectPassword: '当前密码输入不能为空', + newPassword: '新密码输入不能为空', + confirmPassword: '确认密码输入不能为空' + }, + errorTip: { + password: "8-30个字符,同时包含三项(大写字母,小写字母,数字或特殊符号()`~!{'@'}#{'{'}{'}'}{'$'}%&*_-+={'|'}[]:\";\'<>,.?/)", + password2: '密码不一致,请重新输入' + }, + placeholder: { + phoneNumber: '请输入手机号', + email: '请输入邮箱地址', + language: '请选择语言', + time: '请选择时区' + }, + defaultTime: '(GMT+08:00)中国时间-北京', + language: { + zh: '中文', + en: 'English' + }, + tooltip: { + tip: '仅支持创建 2 个密钥' + }, + table: { + label: { + keyName: '密钥名称', + token: 'Token', + permissions: '权限', + createTime: '创建时间', + operate: { + name: '操作', + copy: '复制', + delete: '删除' + } + }, + select: { + title: '读/写', + read: '只读' + } + }, + btn: { + createKey: '创建密钥', + saveChange: '更改', + save: '保存' + } + }, + deleteUser: { + header: { + deleteUser: '删除用户', + }, + label: { + userName: '用户名', + role: '角色', + cellPhone: '手机', + email: '邮箱' + }, + deleteTip: '请确认是否删除以下用户?', + btn: { + cancel: '取消', + sure: '确定' + } + }, + table: { + empty: '暂无数据', + tip: '您可以' + } +}; + +export default zh; + diff --git a/bmp-operation-web/src/lib/mitt/mitt.ts b/bmp-operation-web/src/lib/mitt/mitt.ts new file mode 100644 index 0000000..843ccf4 --- /dev/null +++ b/bmp-operation-web/src/lib/mitt/mitt.ts @@ -0,0 +1,16 @@ +import mitt, {Emitter, EventType} from 'mitt'; // 事件总线-兄弟间传值 + +const mit: Emitter> = mitt(); + +/** + * ComponentCustomProperties用于扩充组件实例类型以支持自定义全局属性,否则会报警告 +*/ +declare module 'vue' { + export interface ComponentCustomProperties { + $Bus: typeof mit; + } +} + +const mittCommunication: (app: any) => Emitter> = (app: any) => app.config.globalProperties.$Bus = mit; + +export default mittCommunication; diff --git a/bmp-operation-web/src/lib/pinia/pinia.ts b/bmp-operation-web/src/lib/pinia/pinia.ts new file mode 100644 index 0000000..525ed69 --- /dev/null +++ b/bmp-operation-web/src/lib/pinia/pinia.ts @@ -0,0 +1,10 @@ +import {createPinia, Pinia} from 'pinia'; + +import piniaPluginPersist from 'pinia-plugin-persist'; + +const pinia: Pinia = createPinia(); + +pinia.use(piniaPluginPersist); + +export default pinia; + diff --git a/bmp-operation-web/src/lib/request/request.ts b/bmp-operation-web/src/lib/request/request.ts new file mode 100644 index 0000000..84db1f6 --- /dev/null +++ b/bmp-operation-web/src/lib/request/request.ts @@ -0,0 +1,42 @@ +/** + * @file + * @author +*/ + +import idcApiCount from 'api/idc/request.ts'; +import modelApiCount from 'api/model/request.ts'; +import roleApiCount from 'api/role/request.ts'; +import userApiCount from 'api/user/request.ts'; +import loginUserApiCount from 'api/login/request.ts'; +import faultLogApiCount from 'api/surveillance/faultLog/request.ts'; +import hardwareStatusApiCount from 'api/surveillance/hardwareStatus/request.ts'; +import licenseApiCount from 'api/userCenter/license/request.ts'; +import messageApiCount from 'api/message/request.ts'; + +interface AppType { + config: { + globalProperties: { + $idcApi: Function; + $modelApi: Parameters + $roleApi: Function; + $userApi: Function; + $faultLogApi: Function; + $loginUserApi: Function; + $hardwareStatusApi: Function; + $licenseApi: Parameters< typeof licenseApiCount>; + $messageApi: Function; + } + } +}; + +export default (app: AppType) => { + app.config.globalProperties.$idcApi = idcApiCount; + app.config.globalProperties.$modelApi = modelApiCount; + app.config.globalProperties.$roleApi = roleApiCount; + app.config.globalProperties.$userApi = userApiCount; + app.config.globalProperties.$faultLogApi = faultLogApiCount; + app.config.globalProperties.$loginUserApi = loginUserApiCount; + app.config.globalProperties.$hardwareStatusApi = hardwareStatusApiCount; + app.config.globalProperties.$licenseApi = licenseApiCount; + app.config.globalProperties.$messageApi = messageApiCount; +}; diff --git a/bmp-operation-web/src/main.ts b/bmp-operation-web/src/main.ts new file mode 100644 index 0000000..b66f300 --- /dev/null +++ b/bmp-operation-web/src/main.ts @@ -0,0 +1,39 @@ +import App from '@/App.vue'; // 根组件 +import router from 'router/index.ts'; // 路由 +import i18n from 'lib/i18n/index.ts'; // 国际化 +import ElementPlus from 'lib/element/index.ts'; // elementui +import pinia from 'lib/pinia/pinia.ts'; // pinia-store状态库 +import defInfo from 'lib/default/defInfo.ts'; // 默认 +import filter from 'lib/filters/filter.ts'; // 过滤方法 +import mittCommunication from 'lib/mitt/mitt.ts'; // mitt-跨组件通信 +import * as ElementPlusIconsVue from '@element-plus/icons-vue'; // Element-plus-icon使用 +import customUi from '@/ui/utils.ts'; // 自定义封装的ui +import plugin from 'plugin/index.ts'; // 插件 +import request from 'lib/request/request.ts'; +// import './upDate'; + +// 创建app实例 +// createApp-返回一个提供应用上下文的应用实例。应用实例挂载的整个组件树共享同一个上下文 +const app = createApp(App); + +defInfo(app); + +request(app); + +// 仿过滤器 +filter(app); + +// 跨组件通信 +mittCommunication(app); + +// ui挂载全局 +customUi.install(app); + +// Element-plus-icon +for (const [key, component] of Object.entries(ElementPlusIconsVue)) { + // 挂载,key-名称,component-组件 + app.component(key, component) +}; + +// 创建实例后,通过链式调用方法 +app.use(plugin).use(router).use(i18n).use(pinia).use(ElementPlus).mount('#app'); diff --git a/bmp-operation-web/src/mock/faultLog/config.ts b/bmp-operation-web/src/mock/faultLog/config.ts new file mode 100644 index 0000000..c4c0a4b --- /dev/null +++ b/bmp-operation-web/src/mock/faultLog/config.ts @@ -0,0 +1,9 @@ +import {CurrencyType} from '@utils/publicType'; + +const mockUrl: CurrencyType = { + faultLogListUrl: '/mock/faultLog/list' +}; + +export default mockUrl; + + diff --git a/bmp-operation-web/src/mock/faultLog/index.ts b/bmp-operation-web/src/mock/faultLog/index.ts new file mode 100644 index 0000000..4cd46e3 --- /dev/null +++ b/bmp-operation-web/src/mock/faultLog/index.ts @@ -0,0 +1,33 @@ +import Mock from 'mockjs'; +import mockUrl from './config'; + +//使用setup配置请求的响应时间,单位是毫秒 +Mock.setup({ + timeout: '2000-10000' // 意味这接口响应时间介于2000毫秒-10s之间 +}) + +// 获取 mock.Random 对象 +const Random = Mock.Random; + +const mockFaultLogList = Mock.mock({ + 'data|20': [ + { // 生成30条数据 + 'id|+1': 1, // id会自增 + logid: Random.guid(), // 获取全局唯一标识符 + sn: '210200A00JN174002217', + manageStatusName: '已创建', + deviceId: 'd-qwird47pir8ejqqvojz6lbtrvp75', + status: true, + createTime: '@datetime(yyyy-MM-dd HH:mm:ss)', // 随机生成创建时间 + role: "@pick(['ttt', 'sss', 'rrr', 'fff'])", // 随机生成角色 + } + ] +}); + +Mock.mock(mockUrl.faultLogListUrl, 'get', () => { + return { + code: 200, + ...mockFaultLogList, + totalCount: 20, + } +}); diff --git a/bmp-operation-web/src/mock/faultLog/request.ts b/bmp-operation-web/src/mock/faultLog/request.ts new file mode 100644 index 0000000..461cbfd --- /dev/null +++ b/bmp-operation-web/src/mock/faultLog/request.ts @@ -0,0 +1,12 @@ +import MockHttpRequest from '../index'; +import mockUrl from './config'; + +/** + * 设备列表接口 +*/ +export const mockFaultLogListAPI = () => { + return MockHttpRequest.service({ + url: mockUrl.faultLogListUrl , + method: 'get' + }); +}; diff --git a/bmp-operation-web/src/mock/index.ts b/bmp-operation-web/src/mock/index.ts new file mode 100644 index 0000000..49271ed --- /dev/null +++ b/bmp-operation-web/src/mock/index.ts @@ -0,0 +1,54 @@ +/** + * @file + * @author +*/ + +import axios, {AxiosError, AxiosResponse, AxiosInstance, AxiosRequestConfig} from 'axios'; +import {ElMessage} from 'element-plus'; + +const config = { + baseURL: '', + timeout: 10 * 1000, // 超时时间 + headers: { // 请求头 + 'Content-Type': 'application/json; charset=utf-8' + } +}; + +class MockHttpRequest { + service: AxiosInstance; + + constructor (config: AxiosRequestConfig) { + // 创建axios实例 + this.service = axios.create(config); + this.requestIntercept(); + this.responseIntercept(); + }; + + requestIntercept = () => { + this.service?.interceptors?.request?.use( + (config: AxiosRequestConfig): AxiosRequestConfig => { + return config; + }, + (error: AxiosError): Promise => { + return Promise.reject(error); + } + ); + }; + + /** + * 响应拦截器 + */ + responseIntercept = () => { + this.service?.interceptors?.response?.use( + (response: AxiosResponse): Promise => { + return response.data; + }, + (err): Promise | void => { + ElMessage.error(err); + return Promise.reject(err); + } + ); + }; +}; + +export default new MockHttpRequest(config); \ No newline at end of file diff --git a/bmp-operation-web/src/plugin/index.ts b/bmp-operation-web/src/plugin/index.ts new file mode 100644 index 0000000..2e19e81 --- /dev/null +++ b/bmp-operation-web/src/plugin/index.ts @@ -0,0 +1,24 @@ +import CustomList from 'components/Public/CustomList/CustomList.vue'; // 自定义列表组件 + +type PluginType = { + name: string; + components: Function; +}; + +/** + * 插件&插件名称 +*/ +const pluginName: PluginType[] = [ + { + name: 'custom-list', + components: CustomList + } +]; + +export default { + install: (app: {component: Function;}) => { + for (const key of pluginName) { + app?.component(key.name, key.components); + } + } +}; \ No newline at end of file diff --git a/bmp-operation-web/src/request/RemoveLongReq/remove.ts b/bmp-operation-web/src/request/RemoveLongReq/remove.ts new file mode 100644 index 0000000..01f8314 --- /dev/null +++ b/bmp-operation-web/src/request/RemoveLongReq/remove.ts @@ -0,0 +1,49 @@ +/** + * @file + * @author +*/ + +import {AxiosRequestConfig} from 'axios'; +import {RepeatRequestArrType} from '@utils/publicType'; + +type LongRequestObjName = { + length: number; + forEach(arg0: unknown, index?: number): void; + splice(arg0: number, arg1: number): Function; + push(arg0: RepeatRequestArrType): void; +}; + + +// 接收长请求的对象 +let longRequestObj: RepeatRequestArrType = { + methodUrl: '', + params: {}, + f: () => {} +}; + +class RemoveLongReq { + + constructor (name: string, config: AxiosRequestConfig & {islongReq?: boolean}, restData: RepeatRequestArrType) { + + if (config?.islongReq) { + if (!(longRequestObj[`${name}` as keyof typeof longRequestObj] as LongRequestObjName)) { + (longRequestObj[`${name}` as keyof typeof longRequestObj] as LongRequestObjName | []) = []; + } + (longRequestObj[`${name}` as keyof typeof longRequestObj] as LongRequestObjName).push(restData); + } + }; +}; + +const removeLong = (name: string | number) => { + if ((longRequestObj[`${name}` as keyof typeof longRequestObj] as LongRequestObjName)?.length > 0) { + (longRequestObj[`${name}` as keyof typeof longRequestObj] as LongRequestObjName).forEach((item: {f(): Function;}, index: number) => { + item.f(); + (longRequestObj[`${name}` as keyof typeof longRequestObj] as LongRequestObjName).splice(index, 1); + }) + } +} + +export { + removeLong, + RemoveLongReq +}; diff --git a/bmp-operation-web/src/request/cancel/cancel.ts b/bmp-operation-web/src/request/cancel/cancel.ts new file mode 100644 index 0000000..4ae3c4c --- /dev/null +++ b/bmp-operation-web/src/request/cancel/cancel.ts @@ -0,0 +1,65 @@ +/** + * @file + * @author +*/ + +import axios, {Canceler, CancelTokenStatic, AxiosRequestConfig} from 'axios'; +import {RemoveLongReq} from 'request/RemoveLongReq/remove.ts'; +import {CurrencyType, RepeatRequestArrType, CurrencyType3} from '@utils/publicType'; + +// 接收重复请求的数组 +let repeatRequestArr: RepeatRequestArrType[] = []; + +//获取取消请求的cancel方法 +const Cancel: CancelTokenStatic = axios.CancelToken; + +class CancelRuquest { + + /** + * 删除重复请求 + * @param {Object} config 请求头信息 + */ + removeRequest = (config: AxiosRequestConfig | {islongReq?: boolean; method: string; url: string; params: CurrencyType; data: CurrencyType}) => { + // 数组遍历 item 当前请求的接口地址+请求类型 index数组的下标 arr要处理的重复请求接口数组 + repeatRequestArr.map((item, index, arr) => { + // methodUrl 是当前请求的地址+方式,如果参数也相同 + if (item.methodUrl === config.url + '&' + config.method) { + if (this.judgeParamsEquality(config?.data || config?.params, item.params)) { + // 走到这里面说明多次请求了 + // f()是内置的取消请求的方法,此处执行 + item.f(); + // 删除当前请求的这一项 + arr.splice(index, 1); + } + } + return config; + }) + }; + + cancelReq = (name: string, config: AxiosRequestConfig & {islongReq?: boolean}) => { + // 这个c就是取消请求的方法 + config.cancelToken = new Cancel((c: Canceler) => { + const restData: RepeatRequestArrType | never = {methodUrl: config.url + '&' + config.method, params: config?.data || config?.params, f: c}; + // 添加到数组里面,methodUrl-url请求地址+method请求方式 + repeatRequestArr.push(restData); + new RemoveLongReq(name, config, restData); + }); + }; + + /** + * 判断请求参数是否相等 + * @param {Object} param1 参数1 + * @param {Object} param2 参数2 + * @return {boolean} true 多次请求 false 未多次请求 + */ + judgeParamsEquality = (param1: CurrencyType3, param2: CurrencyType3) => { + for (const key in param1) { + if (param1[key] !== param2[key]) { + return false; + } + } + return true; + }; +}; + +export default CancelRuquest; diff --git a/bmp-operation-web/src/request/config/initConfig.ts b/bmp-operation-web/src/request/config/initConfig.ts new file mode 100644 index 0000000..509da56 --- /dev/null +++ b/bmp-operation-web/src/request/config/initConfig.ts @@ -0,0 +1,30 @@ +/** + * @file + * @author +*/ +import VueCookies from 'vue-cookies'; + +class InitConfig { + cookie: { + [x: string]: unknown; + get?: Function; + set?: Function; + } = VueCookies; + + config = { + baseURL: '/operation-web/', // 所有实例添加请求前缀 + timeout: 10 * 1000, // 超时时间 + headers: { // 请求头 + 'Content-Type': 'application/json; charset=utf-8', + 'X-Jdcloud-Language': this.cookie?.get && this.cookie.get('X-Jdcloud-Language') || 'zh_CN' + }, + // 设置是否允许携带cookie等凭证信息 + withCredentials: true, + // 响应编码 + responseEncoding: 'utf8', + // 设置重定向的最大次数 + maxRedirects: 5, + }; +} + +export default InitConfig; diff --git a/bmp-operation-web/src/request/error/402.ts b/bmp-operation-web/src/request/error/402.ts new file mode 100644 index 0000000..ef0fc38 --- /dev/null +++ b/bmp-operation-web/src/request/error/402.ts @@ -0,0 +1,35 @@ +/** + * @file + * @author +*/ + +import VueCookies from 'vue-cookies'; +import router from '@/router/index.ts'; // 路由 + +class Error402 { + cookie: { + [x: string]: unknown; + get?: Function; + set?: Function; + } = VueCookies; + + constructor() { + this.#init(); + } + + #init = () => { + sessionStorage?.removeItem('roleId'); + localStorage.clear(); + // 默认地址 + const defaultPath: string = '/IdcManagement/idcList'; + const lastPath: string = router?.currentRoute?.value?.fullPath; + const path: string = lastPath === '/Login/login' ? defaultPath : lastPath; + // 跳转地址-用户最后一次访问的地址 + const pathUrl: string = window.btoa(path || defaultPath); + // 设置地址-存储到cookie + this.cookie?.set && this.cookie.set('path_url', pathUrl); + window.open('/Login/login', '_self'); + } +} + +export default Error402; diff --git a/bmp-operation-web/src/request/error/errorCode.ts b/bmp-operation-web/src/request/error/errorCode.ts new file mode 100644 index 0000000..6840b86 --- /dev/null +++ b/bmp-operation-web/src/request/error/errorCode.ts @@ -0,0 +1,21 @@ +/** + * @file + * @author +*/ +import {msgTip} from 'utils/index.ts'; + +class ErrorCode { + + setErrorCode = (code: number) => { + const obj = { + 400: '失败请求', + 404: '参数错误', + 500: '接口异常', + 502: '服务异常' + }; + const str = (obj[`${code}` as unknown as keyof typeof obj]) + return msgTip.error(str); + } +} + +export default ErrorCode; diff --git a/bmp-operation-web/src/request/error/otherError.ts b/bmp-operation-web/src/request/error/otherError.ts new file mode 100644 index 0000000..14998f9 --- /dev/null +++ b/bmp-operation-web/src/request/error/otherError.ts @@ -0,0 +1,35 @@ +/** + * @file + * @author +*/ +import {msgTip} from 'utils/index.ts'; + +class OtherError { + setError = (message: string, config: {isBusinessProcessing: boolean}, response: {status: number}) => { + const dataError = [ + [ + (status: boolean) => status, + () => { + return msgTip.error(message); + } + ], + [ + (status: boolean) => !status, + () => { + return Promise.reject({message, code: response?.status}); + } + ] + ]; + for (const key of dataError) { + if (key[0](config?.isBusinessProcessing?? false)) { + return key[1](config?.isBusinessProcessing?? false); + } + } + }; + + cancelError = () => { + return Promise.reject(''); + } +} + +export default OtherError; diff --git a/bmp-operation-web/src/request/index.ts b/bmp-operation-web/src/request/index.ts new file mode 100644 index 0000000..1f2668e --- /dev/null +++ b/bmp-operation-web/src/request/index.ts @@ -0,0 +1,100 @@ +/** + * @file + * @author +*/ + +// 暂时用不到 +// import ErrorCode from './error/errorCode'; +import axios, {AxiosError, AxiosResponse, AxiosInstance, AxiosRequestConfig, AxiosResponseHeaders} from 'axios'; +import * as types from './type'; +import Error402 from './error/402'; +import router from '@/router/index.ts'; // 路由 +import OtherError from './error/otherError'; +import InitConfig from './config/initConfig'; +import CancelRuquest from 'request/cancel/cancel.ts'; +import {locationItem} from 'utils/publicClass.ts'; +import {CurrencyType, CurrencyType3} from '@utils/publicType'; + +/** + * 封装axios请求 +*/ +class HttpRequest { + service: AxiosInstance; + axiosCancelReq = new CancelRuquest(); + + constructor (config: AxiosRequestConfig) { + // 创建axios实例 + this.service = axios.create(config); + this.requestIntercept(); + this.responseIntercept(); + }; + + /** + * 请求拦截器 + */ + requestIntercept = () => { + this.service?.interceptors?.request?.use( + (config: AxiosRequestConfig & {islongReq?: boolean}): AxiosRequestConfig => { + const userName: string = localStorage.getItem('userName')??''; + locationItem.cookie.set('X-Jdcloud-Username', window.atob(userName)); + // 删除重复请求 + this.axiosCancelReq.removeRequest(config); + const {name}: {name: string;} = router.currentRoute.value; + this.axiosCancelReq.cancelReq(name, config); + return config; + }, + (error: AxiosError): Promise => { + return Promise.reject(error); + } + ); + }; + + /** + * 响应拦截器 + */ + responseIntercept = () => { + this.service?.interceptors?.response?.use( + (response: AxiosResponse): Promise => { + // 每成功一次,数组边为空,否则其他接口重复请求会数据一直叠加 + this.axiosCancelReq.repeatRequestArr = []; + const {data, headers} : {data: CurrencyType3, headers: AxiosResponseHeaders} = response; + // 登录用户名称 + const loginUserName: string = headers['x-jdcloud-username']; + return Promise.resolve({data, loginUserName}); + }, + (err: {response: types.ErrResponseType}): Promise | void => { + const {response} : {response: types.ErrResponseType} = err; + const errInfo: types.ErrInfoType = JSON.parse(JSON.stringify(err)); + const {config, message}: types.ErrInfoType = errInfo; + const errorMsg: string = response?.data?.error?.message?? ''; + // 402登录过期-未登录 + if (Object.is(response?.status, 402)) { + new Error402(); + return Promise.resolve({data: {}}); + } + if (axios.isCancel(err)) { + return new OtherError().cancelError(); + }; + return new OtherError().setError(errorMsg || message, config, response); + } + ); + }; + + get = (url: string, params: CurrencyType, otherParams: AxiosRequestConfig): Promise => { + return this.service.get(url, {params, ...otherParams}); + }; + + post = (url: string, data: CurrencyType, status: boolean, otherParams: T): Promise => { + return this.service.post(url, data, Object.assign({isBusinessProcessing: status}, {...otherParams})); + }; + + put = (url: string, data: CurrencyType, status: boolean, otherParams: T): Promise => { + return this.service.put(url, data, Object.assign({isBusinessProcessing: status}, {...otherParams})); + }; + + deleteReq = (url: string, data: CurrencyType, status: boolean, otherParams: T): Promise => { + return this.service.delete(url, Object.assign({data, isBusinessProcessing: status}, {...otherParams})); + }; +} + +export default new HttpRequest(new InitConfig().config); diff --git a/bmp-operation-web/src/request/type.ts b/bmp-operation-web/src/request/type.ts new file mode 100644 index 0000000..c3c3946 --- /dev/null +++ b/bmp-operation-web/src/request/type.ts @@ -0,0 +1,42 @@ +/** + * @file + * @author +*/ + +type OtherParamsType = { + isBusinessProcessing: boolean; + timeout?: number; + responseType?: string; + islongReq?: boolean; + baseURL?: string; +}; + +/** + * 异常信息类 +*/ +type ErrInfoType = { + config: { + isBusinessProcessing: boolean; + }; + message: string; +}; + +type DeleteType = Omit; + +/** + * 异常返回类型 +*/ +interface ErrResponseType extends DeleteType { + status: number; + data: { + error: { + message: string; + } + }; +}; + +export { + ErrInfoType, + OtherParamsType, + ErrResponseType +} \ No newline at end of file diff --git a/bmp-operation-web/src/router/index.ts b/bmp-operation-web/src/router/index.ts new file mode 100644 index 0000000..c4830b4 --- /dev/null +++ b/bmp-operation-web/src/router/index.ts @@ -0,0 +1,47 @@ +/** + * @file + * @author +*/ + + +import {paginationOperate} from 'utils/publicClass.ts'; +import {createRouter, createWebHistory, Router, RouterHistory, RouteLocationNormalized, NavigationGuardNext} from 'vue-router'; +import routes from '@/router/routes.ts'; //导入router目录下的routes.ts +import {removeLong} from 'request/RemoveLongReq/remove.ts'; +//createWebHistory -- history模式 +//createWebHashHistory -- hash模式 +const webHistory: RouterHistory = createWebHistory(); + +const router: Router = createRouter({ + history: webHistory, + routes +}); + +// 路由守卫 +class RouterEach { + + constructor() { + this.init(); + this.routerError(); + } + + init = () => { + router.beforeEach((_: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => { + paginationOperate.routerChange.value = true; + paginationOperate.pageNumber.value = 1; + paginationOperate.pageSize.value = 20; + removeLong(from.name); + next(); + }); + } + + routerError = () => { + router.onError(() => { + window.location.reload(); + }); + } +} + +new RouterEach(); + +export default router; diff --git a/bmp-operation-web/src/router/routes.ts b/bmp-operation-web/src/router/routes.ts new file mode 100644 index 0000000..1517326 --- /dev/null +++ b/bmp-operation-web/src/router/routes.ts @@ -0,0 +1,18 @@ +import {RouteRecordRaw} from 'vue-router'; +import loginRouter from 'views/login/page.ts'; +import navBarRouter from 'views/navigationBar/page.ts'; +import idcListRouter from 'views/idcManagement/list/page.ts'; + +/** + * 路由信息 +*/ +const routes: Array = [ + idcListRouter.def, + loginRouter, + { + ...navBarRouter.nav, + children: [...navBarRouter.children] + } +]; + +export default routes; diff --git a/bmp-operation-web/src/shims-vue.d.ts b/bmp-operation-web/src/shims-vue.d.ts new file mode 100644 index 0000000..e9a135c --- /dev/null +++ b/bmp-operation-web/src/shims-vue.d.ts @@ -0,0 +1,19 @@ +/* eslint-disable */ + +// shims-vue.d.ts是为了 typescript 做的适配定义文件 +// 因为.vue 文件不是一个常规的文件类型,ts 是不能理解 vue 文件的作用 +// 加这一段是是告诉 ts,vue 文件是这种类型的,如果不写,import引入.vue文件会报错,其他同理 +declare module '*.vue' { // declare声明宣告 + import type { DefineComponent } from 'vue' + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types + const component: DefineComponent<{}, {}, any> + export default component +} + +declare module '*.js'; +declare module '*.ts'; +// 解决ts文件引入图片报错 +declare module '*.png'; +declare module '*.jpg'; +declare module '*.jpeg'; +declare module 'mockjs'; diff --git a/bmp-operation-web/src/staticData/device/index.ts b/bmp-operation-web/src/staticData/device/index.ts new file mode 100644 index 0000000..0d8af09 --- /dev/null +++ b/bmp-operation-web/src/staticData/device/index.ts @@ -0,0 +1,581 @@ +/** + * @file + * @author +*/ + +import i18n from 'lib/i18n/index.ts'; // 国际化 +import DeviceType from './type'; +import {CurrencyStatusType, ListShowTooltipType} from '@utils/publicType'; + +// 国际化 +const {global} = i18n; + +class DeviceStaticData { + // 管理状态filter数据 + static manageMentStatus: DeviceType[] = [ + { + filterParams: 'in', + text: global.t('deviceList.managementStatus.warehousing'), + value: 1 + }, + { + filterParams: 'putaway', + text: global.t('deviceList.managementStatus.onTheShelf'), + value: 2 + }, + { + filterParams: 'created', + text: global.t('deviceList.managementStatus.created'), + value: 3 + }, + { + filterParams: 'putawaying', + text: global.t('deviceList.managementStatus.onShelf'), + value: 4 + }, + { + filterParams: 'removed', + text: global.t('deviceList.managementStatus.remove'), + value: 5 + }, + { + filterParams: 'putawayfail', + text: global.t('deviceList.managementStatus.error'), + value: 6 + } + ]; + + static operationalFeedbackData = [ + { + filterParams: 'success', + text: global.t('operate.success'), + value: 1 + }, + { + filterParams: 'fail', + text: global.t('operate.fail'), + value: 2 + }, + { + filterParams: 'doing', + text: global.t('operate.doing'), + value: 3 + } + ]; + + static collectStatusData = [ + { + filterParams: '1', + text: global.t('deviceList.status.collected'), + value: 1 + }, + { + filterParams: '2', + text: global.t('deviceList.status.noCollected'), + value: 2 + }, + { + filterParams: '3', + text: global.t('deviceList.status.collecting'), + value: 3 + }, + { + filterParams: '4', + text: global.t('deviceList.status.collectionFailed'), + value: 4 + } + ]; + + static modelInfoTipData: string[] = [ + 'newDisksValTip' + ]; + + // 中间态1 + static intermediate1: string[] = ['creating', 'starting', 'stopping', 'Rebooting' , 'restarting', 'resetting_password', 'destroying', 'upgrading', 'reinstalling', 'resettingPassword']; + + // 中间态2 + static intermediate2: string[] = ['Creating', 'Starting up', 'Shutting Down', 'Rebooting', 'Restarting', 'Reset Password', 'Destroying', 'Destructing', 'Destroying', 'Upgrading', 'Reinstalling System']; + + static deviceList = [ + { + name: global.t('deviceList.content.label.sn'), + selected: true, + disabled: true, + label: 'sn', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.name'), + selected: true, + disabled: false, + label: 'deviceSeries', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.modelName'), + selected: true, + disabled: false, + label: 'deviceTypeName', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.managementStatus'), + selected: true, + disabled: false, + label: 'manageStatusName', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.collectionStatus'), + selected: true, + disabled: false, + label: 'collectStatus', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.computerRoomName'), + selected: true, + disabled: false, + label: 'idcName', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.cabinetCode'), + selected: true, + disabled: false, + label: 'cabinet', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.uBit'), + selected: true, + disabled: false, + label: 'uPosition', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.brand'), + selected: true, + disabled: false, + label: 'brand', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.model'), + selected: true, + disabled: false, + label: 'model', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.architecture'), + selected: true, + disabled: false, + label: 'architecture', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.instanceImage'), + selected: true, + disabled: false, + label: 'imageName', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.instanceName'), + selected: true, + disabled: false, + label: 'instanceName', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.instanceID'), + selected: true, + disabled: false, + label: 'instanceId', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.instanceStatus'), + selected: true, + disabled: false, + label: 'instanceStatus', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.lockStatus'), + selected: true, + disabled: false, + label: 'instanceLockedStatus', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.instanceOwner'), + selected: true, + disabled: false, + label: 'instanceOwer', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.CPU'), + selected: true, + disabled: false, + label: 'cpuInfo', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.storage'), + selected: true, + disabled: false, + label: 'memInfo', + showTooltip: false + }, + // { + // name: global.t('deviceList.content.label.sysDisc'), + // selected: true, + // disabled: false, + // label: 'svInfo', + // showTooltip: false + // }, + // { + // name: global.t('deviceList.content.label.dataDisc'), + // selected: true, + // disabled: false, + // label: 'dvInfo', + // showTooltip: false + // }, + { + name: global.t('deviceList.content.label.GPU'), + selected: true, + disabled: false, + label: 'gpuInfo', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.switchIPNetworkPortOne'), + selected: true, + disabled: false, + label: 'switchIp1', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.switchIPNetworkPortTwo'), + selected: true, + disabled: false, + label: 'switchIp2', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.networkPortOneUplinkPort'), + selected: true, + disabled: false, + label: 'switchPort1', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.networkPortTwoUplinkPort'), + selected: true, + disabled: false, + label: 'switchPort2', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.networkSettings'), + selected: true, + disabled: false, + label: 'nicInfo', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.outOfBandIP'), + selected: true, + disabled: false, + label: 'iloIp', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.intranceIPv4'), + selected: true, + disabled: false, + label: 'privateIpv4', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.intranceIPv4First'), + selected: true, + disabled: false, + label: 'privateEth1Ipv4', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.intranetIPv6'), + selected: true, + disabled: false, + label: 'privateIpv6', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.intranetIPv6First'), + selected: true, + disabled: false, + label: 'privateEth1Ipv6', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.createTime'), + selected: true, + disabled: false, + label: 'createdTime', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.remark'), + selected: true, + disabled: false, + label: 'description', + showTooltip: false + }, + { + name: global.t('deviceList.content.label.operate.name'), + selected: true, + disabled: true, + label: 'operate', + showTooltip: false + } + ]; + + static auditLogsList = [ + { + name: global.t('deviceDetail.operatLog.table.label.logId'), + selected: true, + disabled: true, + label: 'logid', + showTooltip: false + }, + { + name: global.t('deviceDetail.operatLog.table.label.operateName'), + selected: true, + disabled: true, + label: 'operationName', + showTooltip: false + }, + { + name: global.t('deviceDetail.operatLog.table.label.operatePeople'), + selected: true, + disabled: false, + label: 'userName', + showTooltip: false + }, + { + name: global.t('deviceDetail.operatLog.table.label.operateTime'), + selected: true, + disabled: false, + label: 'operateTime', + showTooltip: false + }, + { + name: global.t('deviceDetail.operatLog.table.label.operateFeedback'), + selected: true, + disabled: false, + label: 'result', + showTooltip: false + }, + { + name: global.t('deviceDetail.operatLog.table.label.failCode'), + selected: true, + disabled: false, + label: 'failReason', + showTooltip: false + } + ]; + + static deviceFaultLogList = [ + { + name: global.t('deviceDetail.table.label.serialNumber'), + selected: true, + disabled: true, + label: 'logid', + showTooltip: false + }, + { + name: global.t('deviceDetail.table.label.faultType'), + selected: true, + disabled: false, + label: 'alertType', + showTooltip: false + }, + { + name: global.t('deviceDetail.table.label.faultDesc'), + selected: true, + disabled: false, + label: 'alertDesc', + showTooltip: false + }, + { + name: global.t('deviceDetail.table.label.faultAlarmTime'), + selected: true, + disabled: false, + label: 'eventTime', + showTooltip: false + }, + { + name: global.t('deviceDetail.table.label.updateTime'), + selected: true, + disabled: false, + label: 'updateTime', + showTooltip: false + }, + { + name: global.t('deviceDetail.table.label.alarmNum'), + selected: true, + disabled: false, + label: 'count', + showTooltip: false + }, + { + name: global.t('deviceDetail.table.label.status'), + selected: true, + disabled: true, + label: 'status', + showTooltip: false + }, + ]; + + static deviceFaultLogInfo = (status1: CurrencyStatusType, status2: CurrencyStatusType) => { + return { + logid: status2, + alertType: status1, + alertDesc: status1, + eventTime: status1, + updateTime: status1, + count: status1, + status: status2, + } + }; + + static deviceInfo = (status1: CurrencyStatusType, status2: CurrencyStatusType) => { + return { + sn: status2, + deviceTypeName: status1, + deviceSeries: status1, + manageStatusName: status1, + collectStatus: status1, + idcName: status1, + cabinet: status1, + uPosition: status1, + brand: status1, + model: status1, + architecture: status1, + imageName: status1, + instanceName: status1, + instanceId: status1, + instanceStatus: status1, + instanceLockedStatus: status1, + instanceOwer: status1, + cpuInfo: status1, + memInfo: status1, + // svInfo: status1, + // dvInfo: status1, + gpuInfo: status1, + switchIp1: status1, + switchIp2: status1, + switchPort1: status1, + switchPort2: status1, + nicInfo: status1, + iloIp: status1, + privateIpv4: status1, + privateEth1Ipv4: status1, + privateIpv6: status1, + privateEth1Ipv6: status1, + createdTime: status1, + operate: status2 + } + }; + + static auditLogsInfo = (status1: CurrencyStatusType, status2: CurrencyStatusType) => { + return { + logid: status2, + operationName: status2, + userName: status1, + operateTime: status1, + result: status1, + failReason: status1 + } + }; + + static deviceTipData: string[] = [ + 'snTip', + 'deviceTypeNameTip', + 'idcNameTip', + 'cabinetTip', + 'uPositionTip', + 'brandTip', + 'modelTip', + 'architectureTip', + 'imageNameTip', + 'instanceNameTip', + 'instanceIdTip', + 'userNameTip', + 'cpuInfoTip', + 'memInfoTip', + 'svInfoTip', + 'dvInfoTip', + 'gpuInfoTip', + 'switchIp1Tip', + 'switchIp2Tip', + 'switchPort1Tip', + 'switchPort2Tip', + 'interfaceModeNameTip', + 'iloIpTip', + 'privateIpv4Tip', + 'privateEth1Ipv4Tip', + 'privateIpv6Tip', + 'privateEth1Ipv6Tip', + 'descriptionTip' + ]; + + static batchEditInstanceNameTipData: string[] = [ + 'instanceNameTip', + 'instanceIdTip' + ]; + + static resetSysTemKeyTooltip: ListShowTooltipType = { + name: { + showTooltip: false + } + }; + + static deviceFaultLogTipData: string[] = [ + 'alertTypeTip', + 'alertDescTip' + ]; + + static loadingStatusData: string[] = ['creating', 'Rebooting', 'restarting', 'starting', 'stopping', 'destroying', 'reinstalling', 'resetting_password']; + + static FailedData: string[] = [ + 'Creation failed', + 'Startup failed', + 'Shutdown failed', + 'Reboot failed', + 'Delete failed', + 'Reinstall failed', + 'Resetpasswd failed' + ]; + + static recoveryInstance: string[] = ['Creation failed', 'stopped']; + + static lockUnlocked: string[] = ['Creating', 'creating', 'Creation failed', 'destroying' , 'Destroying', 'Delete failed', 'Reinstall failed', 'Resetpasswd failed']; + + static resetInstanceStatus: string[] = ['Startup failed', 'Shutdown failed', 'Reboot failed', 'Delete failed']; + + static deleteDevice: string[] = ['in', 'putawayfail', 'removed']; + + static resetInstance: string[] = [ + 'Startup failed', + 'Shutdown failed', + 'Reboot failed', + 'Delete failed' + ]; +}; + +export default DeviceStaticData; diff --git a/bmp-operation-web/src/staticData/device/type.ts b/bmp-operation-web/src/staticData/device/type.ts new file mode 100644 index 0000000..7b159a7 --- /dev/null +++ b/bmp-operation-web/src/staticData/device/type.ts @@ -0,0 +1,13 @@ +/** + * 通用类-列表 +*/ +type CurrencyType = { + text: string; + label: string | number; + info: any; + filterParams: string; +}; + +type DeviceType = Required<{value: number | string;}> & Partial; + +export default DeviceType; diff --git a/bmp-operation-web/src/staticData/idc/index.ts b/bmp-operation-web/src/staticData/idc/index.ts new file mode 100644 index 0000000..80f12e8 --- /dev/null +++ b/bmp-operation-web/src/staticData/idc/index.ts @@ -0,0 +1,232 @@ +/** + * @file + * @author +*/ + +import i18n from 'lib/i18n/index.ts'; // 国际化 +import {CurrencyType5, CurrencyStatusType} from '@utils/publicType'; + +// 国际化 +const {global} = i18n; + +class IdcStaticData { + static machineRoomGradeData: CurrencyType5[] = [ + { + value: 1, + label: 'T3' + }, + { + value: 2, + label: 'T3+' + }, + { + value: 3, + label: 'T4' + }, + { + value: 4, + label: 'T4+' + }, + { + value: 5, + label: global.t('editIdc.iptInfo.other') + } + ]; + + static idcList = [ + { + name: global.t('idcList.content.name'), + selected: true, + disabled: true, + label: 'name', + showTooltip: false + }, + { + name: global.t('idcList.content.englishCode'), + selected: true, + disabled: false, + label: 'nameEn', + showTooltip: false + }, + { + name: global.t('idcList.content.grade'), + selected: true, + disabled: false, + label: 'level', + showTooltip: false + }, + { + name: global.t('idcList.content.address'), + selected: true, + disabled: false, + label: 'address', + showTooltip: false + }, + { + name: global.t('idcList.content.createTime'), + selected: true, + disabled: false, + label: 'createTime', + showTooltip: false + }, + { + name: global.t('idcList.content.createPeople'), + selected: true, + disabled: false, + label: 'createdBy', + showTooltip: false + }, + { + name: global.t('idcList.content.updateTime'), + selected: true, + disabled: false, + label: 'updateTime', + showTooltip: false + }, + { + name: global.t('idcList.content.updatePeople'), + selected: true, + disabled: false, + label: 'updatedBy', + showTooltip: false + }, + { + name: global.t('idcList.content.operate.name'), + selected: true, + disabled: true, + label: 'operate', + showTooltip: false + } + ]; + + static idcInfo = (status1: CurrencyStatusType, status2: CurrencyStatusType) => { + return { + address: status1, // 机房地址 + createTime: status1, // 创建时间 + createdBy: status1, // 创建人 + level: status1, // 机房等级 + name: status2, // 机房名称 + nameEn: status1, // 机房英文名称 + updateTime: status1, // 更新时间 + updatedBy: status1, // 更新人 + operate: status2 // 操作 + } + }; + + static levelData: string[] = ['T3', 'T3+', 'T4', 'T4+']; + + static otherData: string[] = ['其它', 'Other']; + + static idcTipData: string[] = [ + 'nameTip', + 'nameEnTip', + 'levelTip', + 'addressTip', + 'createdByTip', + 'updatedByTip' + ]; + + static templateData = [ + { + prop: 'name', + align: 'center', + minWidth: '110', + ifSelect: 'name', + fixed: true, + label: global.t('idcList.content.name'), + hasUserTemplate: true, + hasClick: true, + hasShowTooltip: true + }, + { + prop: 'nameEn', + align: 'center', + minWidth: '120', + ifSelect: 'nameEn', + fixed: false, + label: global.t('idcList.content.englishCode'), + hasUserTemplate: true, + hasClick: false, + hasShowTooltip: true + }, + { + prop: 'level', + align: 'center', + minWidth: '110', + ifSelect: 'level', + fixed: false, + label: global.t('idcList.content.grade'), + hasUserTemplate: true, + hasClick: false, + hasShowTooltip: true + }, + { + prop: 'address', + align: 'center', + minWidth: '140', + ifSelect: 'address', + fixed: false, + label: global.t('idcList.content.address'), + hasUserTemplate: true, + hasClick: false, + hasShowTooltip: true + }, + { + prop: 'createTime', + align: 'center', + minWidth: '150', + ifSelect: 'createTime', + fixed: false, + label: global.t('idcList.content.createTime'), + hasUserTemplate: true, + hasClick: false, + hasShowTooltip: false + }, + { + prop: 'createdBy', + align: 'center', + minWidth: '90', + ifSelect: 'createdBy', + fixed: false, + label: global.t('idcList.content.createPeople'), + hasUserTemplate: true, + hasClick: false, + hasShowTooltip: true + }, + { + prop: 'updateTime', + align: 'center', + minWidth: '150', + ifSelect: 'updateTime', + fixed: false, + label: global.t('idcList.content.updateTime'), + hasUserTemplate: true, + hasClick: false, + hasShowTooltip: false + }, + { + prop: 'updatedBy', + align: 'center', + minWidth: '90', + ifSelect: 'updatedBy', + fixed: false, + label: global.t('idcList.content.updatePeople'), + hasUserTemplate: true, + hasClick: false, + hasShowTooltip: true + }, + { + prop: 'operate', + align: 'center', + minWidth: '100', + ifSelect: 'operate', + fixed: 'right', + label: global.t('idcList.content.operate.name'), + hasUserTemplate: true, + hasClick: true, + hasShowTooltip: false + } + ]; +} + +export default IdcStaticData; diff --git a/bmp-operation-web/src/staticData/image/index.ts b/bmp-operation-web/src/staticData/image/index.ts new file mode 100644 index 0000000..a6e906a --- /dev/null +++ b/bmp-operation-web/src/staticData/image/index.ts @@ -0,0 +1,163 @@ +import i18n from 'lib/i18n/index.ts'; // 国际化 +import {CurrencyStatusType, OsStoreType} from '@utils/publicType'; + +// 国际化 +const {global} = i18n; + +class ImageStaticData { + static source: OsStoreType[] = [ // 镜像类型 + { + value: 1, + text: global.t('imageList.filter.presetImage'), + filterParams: 'common' + }, + { + value: 2, + text: global.t('imageList.filter.customImage'), + filterParams: 'user_defined' + } + ]; + static imageList = [ + { + name: global.t('imageList.content.label.imageName'), // 镜像名称 + selected: true, + disabled: true, + label: 'imageName', + showTooltip: false + }, + { + name: global.t('imageList.content.label.imageId'), // 镜像ID + selected: true, + disabled: false, + label: 'imageId', + showTooltip: false + }, + { + name: global.t('imageList.content.label.imageType'), // 镜像类型 + selected: true, + disabled: false, + label: 'source', + showTooltip: false + }, + { + name: global.t('imageList.content.label.architecture'), // 体系架构 + selected: true, + disabled: false, + label: 'architecture', + showTooltip: false + }, + { + name: global.t('imageList.content.label.operateSysPlatform'), // 操作系统平台 + selected: true, + disabled: false, + label: 'osType', + showTooltip: false + }, + { + name: global.t('imageList.content.label.operateSysVersion'), // 操作系统版本 + selected: true, + disabled: false, + label: 'osVersion', + showTooltip: false + }, + { + name: global.t('imageList.content.label.format'), // 镜像格式 + selected: true, + disabled: false, + label: 'format', + showTooltip: false + }, + { + name: global.t('imageList.content.label.bootMode'), // 引导模式 + selected: true, + disabled: false, + label: 'bootMode', + showTooltip: false + }, + { + name: global.t('imageList.content.label.sysPartitionModule'), // 系统盘分区模块 + selected: true, + disabled: false, + label: 'systemPartition', + showTooltip: false + }, + { + name: global.t('imageList.content.label.imageDesc'), // 镜像描述 + selected: true, + disabled: false, + label: 'description', + showTooltip: false + }, + { + name: global.t('imageList.content.label.numberOfAssociatedModels'), // 已关联机型数 + selected: true, + disabled: false, + label: 'deviceTypeNum', + showTooltip: false + }, + { + name: global.t('imageList.content.label.createTime'), // 创建时间 + selected: true, + disabled: false, + label: 'createdTime', + showTooltip: false + }, + { + name: global.t('imageList.content.label.operate.name'), // 操作 + selected: true, + disabled: true, + label: 'operate', + showTooltip: false + } + ]; + + static imageDetailTipData: string[] = [ + 'nameTip', + 'deviceSeriesNameTip', + 'idcNameTip', + 'idcNameEnTip', + 'architectureTip', + 'deviceTypeTip', + 'descriptionTip' + ]; + + static imageListTipData: string[] = [ + 'imageNameTip', + 'imageIdTip', + 'osTypeTip', + 'osVersionTip', + 'descriptionTip' + ]; + + static imageModelAddTipData: string[] = [ + 'nameTip', + 'idcNameTip', + 'idcNameEnTip', + 'deviceTypeTip', + 'descriptionTip' + ]; + + static imageInfo = (status1: CurrencyStatusType, status2: CurrencyStatusType) => { + return { + imageName: status2, + imageId: status1, + source: status1, + architecture: status1, + osType: status1, + osVersion: status1, + format: status1, + bootMode: status1, + systemPartition: status1, + description: status1, + deviceTypeNum: status1, + createdTime: status1, + operate: status2 + } + }; + + static otherData: string[] = ['其它', 'other', 'Other']; + + static otherSystemData :string[] = ['Windows', '其它', 'other', 'Other']; +}; + +export default ImageStaticData; diff --git a/bmp-operation-web/src/staticData/inBandMonitoring/allAlarmRules/index.ts b/bmp-operation-web/src/staticData/inBandMonitoring/allAlarmRules/index.ts new file mode 100644 index 0000000..d6c8559 --- /dev/null +++ b/bmp-operation-web/src/staticData/inBandMonitoring/allAlarmRules/index.ts @@ -0,0 +1,108 @@ +/** + * @file + * @author +*/ +import i18n from 'lib/i18n/index.ts'; // 国际化 +import {CurrencyStatusType, OsStoreType} from '@utils/publicType'; + +// 国际化 +const {global} = i18n; + +class AllAlarmRulesStatic { + static allAlarmRulesList = [ + { + name: global.t('allAlarmRulesList.table.label.userName'), // 用户名称 + selected: true, + disabled: true, + label: 'userName', + showTooltip: false + }, + { + name: global.t('allAlarmRulesList.table.label.ruleName'), // 规则名称 + selected: true, + disabled: false, + label: 'ruleName', + showTooltip: false + }, + { + name: global.t('allAlarmRulesList.table.label.ruleId'), // 规则ID + selected: true, + disabled: false, + label: 'ruleId', + showTooltip: false + }, + { + name: global.t('allAlarmRulesList.table.label.triggerDescription'), // 资源类型 + selected: true, + disabled: false, + label: 'resourceName', + showTooltip: false + }, + { + name: global.t('allAlarmRulesList.table.label.instanceCount'), // 实例关联数量 + selected: true, + disabled: false, + label: 'instanceCount', + showTooltip: false + }, + { + name: global.t('allAlarmRulesList.table.label.triggerDescription'), // 触发条件 + selected: true, + disabled: false, + label: 'triggerDescription', + showTooltip: false + }, + { + name: global.t('allAlarmRulesList.table.label.statusName'), // 状态 + selected: true, + disabled: false, + label: 'statusName', + showTooltip: false + }, + { + name: global.t('allAlarmRulesList.table.label.operate.title'), // 操作 + selected: true, + disabled: true, + label: 'operate', + showTooltip: false + } + ]; + static allAlarmRulesInfo = (status1: CurrencyStatusType, status2: CurrencyStatusType) => { + return { + userName: status2, + ruleName: status1, + ruleId: status1, + resourceName: status1, + instanceCount: status1, + triggerDescription: status1, + statusName: status1, + operate: status2 + } + }; + static allAlarmRulesListTipData: string[] = [ + 'ruleNameTip', + 'ruleIdTip', + 'triggerDescriptionTip' + ]; + + static allAlarmRulesStatusData: OsStoreType[] = [ + { + filterParams: '1', + text: global.t('allAlarmRulesList.select.normal'), + value: 1 + }, + { + filterParams: '2', + text: global.t('allAlarmRulesList.select.forbid'), + value: 2 + }, + { + filterParams: '3', + // Alert + text: global.t('allAlarmRulesList.select.alarm'), + value: 3 + } + ]; +} + +export default AllAlarmRulesStatic; diff --git a/bmp-operation-web/src/staticData/inBandMonitoring/historyAlarm/index.ts b/bmp-operation-web/src/staticData/inBandMonitoring/historyAlarm/index.ts new file mode 100644 index 0000000..e7cbcc6 --- /dev/null +++ b/bmp-operation-web/src/staticData/inBandMonitoring/historyAlarm/index.ts @@ -0,0 +1,13 @@ +/** + * @file + * @author +*/ + +class HistoryAlarmStatic { + static historyAlarmListTipData: string[] = [ + 'alertValueTip', + 'triggerDescriptionTip', + ]; +} + +export default HistoryAlarmStatic; diff --git a/bmp-operation-web/src/staticData/inBandMonitoring/resourceMonitor/index.ts b/bmp-operation-web/src/staticData/inBandMonitoring/resourceMonitor/index.ts new file mode 100644 index 0000000..a973296 --- /dev/null +++ b/bmp-operation-web/src/staticData/inBandMonitoring/resourceMonitor/index.ts @@ -0,0 +1,77 @@ +/** + * @file + * @author +*/ + +import i18n from 'lib/i18n/index.ts'; // 国际化 + +// 国际化 +const {global} = i18n; + +class ResourceMonitorStaticData { + static monitoringIndicators = [ + { + name: global.t('monitorEcharts.echartsCount.cpu'), + value: 'bmp.cpu.util' + }, + { + name: global.t('monitorEcharts.echartsCount.mem'), + value: 'bmp.memory.util' + }, + { + name: global.t('monitorEcharts.echartsCount.memUsage'), + value: 'bmp.memory.used' + }, + { + name: global.t('monitorEcharts.echartsCount.diskUsage'), + value: 'bmp.disk.used' + // value: 'bmp.disk.partition.used' + }, + { + name: global.t('monitorEcharts.echartsCount.diskUsageRate'), + value: 'bmp.disk.util' + }, + { + name: global.t('monitorEcharts.echartsCount.diskReadWriteTraffic'), + value: 'bmp.disk.bytes.read,bmp.disk.bytes.write' + }, + { + name: global.t('monitorEcharts.echartsCount.diskReadWriteIOPS'), + value: 'bmp.disk.counts.read,bmp.disk.counts.write ' + }, + { + name: global.t('monitorEcharts.echartsCount.netWorkBps'), + value: 'bmp.network.bytes.ingress,bmp.network.bytes.egress' + }, + { + name: global.t('monitorEcharts.echartsCount.netWorkPackagesNumber'), + value: 'bmp.network.packets.ingress,bmp.network.packets.egress' + }, + { + name: global.t('monitorEcharts.echartsCount.averageLoad1Min'), + value: 'bmp.avg.load1' + }, + { + name: global.t('monitorEcharts.echartsCount.averageLoad5Min'), + value: 'bmp.avg.load5' + }, + { + name: global.t('monitorEcharts.echartsCount.averageLoad15Min'), + value: 'bmp.avg.load15' + }, + { + name: global.t('monitorEcharts.echartsCount.totalTCPConnections'), + value: 'bmp.tcp.connect.total' + }, + { + name: global.t('monitorEcharts.echartsCount.normalTCPConnections'), + value: 'bmp.tcp.connect.established' + }, + { + name: global.t('monitorEcharts.echartsCount.totalNumberOfProcesses'), + value: 'bmp.process.total' + } + ] +} + +export default ResourceMonitorStaticData; diff --git a/bmp-operation-web/src/staticData/message/index.ts b/bmp-operation-web/src/staticData/message/index.ts new file mode 100644 index 0000000..0035f36 --- /dev/null +++ b/bmp-operation-web/src/staticData/message/index.ts @@ -0,0 +1,199 @@ +/** + * @file + * @author +*/ + +import i18n from 'lib/i18n/index.ts'; // 国际化 +import {CurrencyStatusType, OsStoreType} from '@utils/publicType'; + +// 国际化 +const {global} = i18n; + +class MessageStaticData { + static messageType: OsStoreType[] = [ // 镜像类型 + { + value: 1, + text: global.t('myMessage.table.inbondAlert'), + filterParams: global.t('myMessage.table.inbondAlert') + }, + { + value: 2, + text: global.t('myMessage.table.systemMessages'), + filterParams: global.t('myMessage.table.systemMessages') + }, + { + value: 3, + text: global.t('myMessage.table.faultMessages'), + filterParams: global.t('myMessage.table.faultMessages') + }, + { + value: 4, + text: global.t('myMessage.table.operationMessages'), + filterParams: global.t('myMessage.table.operationMessages') + }, + ]; + + static messageTipData: string[] = [ + 'finishTimeTip', + 'messageTypeTip', + 'messageSubTypeTip' + ]; + + static messageList = [ + { + name: global.t('myMessage.label.messageContent'), + selected: true, + disabled: true, + label: 'detail', + showTooltip: false + }, + { + name: global.t('myMessage.label.finishTime'), + selected: true, + disabled: false, + label: 'finishTime', + showTooltip: false + }, + { + name: global.t('myMessage.label.messageType'), + selected: true, + disabled: false, + label: 'messageType', + showTooltip: false + }, + { + name: global.t('myMessage.label.messageSubType'), + selected: true, + disabled: true, + label: 'messageSubType', + showTooltip: false + } + ]; + + static messageInfo = (status1: CurrencyStatusType, status2: CurrencyStatusType) => { + return { + detail: status2, + finishTime: status1, + messageType: status1, + messageSubType: status2 + } + }; + + static btnData: {id: string; text: string;}[] = [ + { + id: 'prevId', + text: global.t('messageDetail.footer.pre') + }, + { + id: 'nextId', + text: global.t('messageDetail.footer.next') + } + ]; + + static templateData: {prop: string; label: string; hasShow: string; hasTime: boolean; hasOther: boolean;}[] = [ + { + prop: 'messageSubType', + label: global.t('messageDetail.label.optContent'), + hasShow: 'optMessage', + hasTime: false, + hasOther: false + }, + { + prop: 'userName', + label: global.t('messageDetail.label.optPeople'), + hasShow: 'optMessage', + hasTime: false, + hasOther: false + }, + { + prop: 'finishTime', + label: global.t('messageDetail.label.optTime'), + hasShow: 'optMessage', + hasTime: true, + hasOther: false + }, + { + prop: 'licenseName', + label: global.t('messageDetail.label.versionName'), + hasShow: 'unexpiredExpired', + hasTime: false, + hasOther: false + }, + { + prop: 'licenseNumber', + label: global.t('messageDetail.label.version'), + hasShow: 'unexpiredExpired', + hasTime: false, + hasOther: false + }, + { + prop: 'licenseStartTime', + label: global.t('messageDetail.label.startTime'), + hasShow: 'unexpiredExpired', + hasTime: true, + hasOther: false + }, + { + prop: 'licenseEndTime', + label: global.t('messageDetail.label.licenseEndTime'), + hasShow: 'unexpiredExpired', + hasTime: true, + hasOther: false + }, + { + prop: 'licenseEndTime', + label: global.t('messageDetail.label.licenseStatus'), + hasShow: 'unexpiredExpired', + hasTime: false, + hasOther: true + }, + { + prop: 'logid', + label: 'LogID', + hasShow: 'faultMessage', + hasTime: false, + hasOther: false + }, + { + prop: 'faultType', + label: global.t('messageDetail.label.faultType'), + hasShow: 'faultMessage', + hasTime: false, + hasOther: false + }, + { + prop: 'content', + label: global.t('messageDetail.label.faultDesc'), + hasShow: 'faultMessage', + hasTime: false, + hasOther: false + }, + { + prop: 'alertTime', + label: global.t('messageDetail.label.faultAlarmTime'), + hasShow: 'faultMessage', + hasTime: true, + hasOther: false + }, + { + prop: 'alertCount', + label: global.t('messageDetail.label.alarmNum'), + hasShow: 'faultMessage', + hasTime: false, + hasOther: false + } + ]; + + static instanceTemplateData: {prop: string; label: string;}[] = [ + { + prop: 'instanceName', + label: global.t('messageDetail.optTips.label.instanceName'), + }, + { + prop: 'instanceId', + label: global.t('messageDetail.optTips.label.instanceId'), + } + ]; +} + +export default MessageStaticData; diff --git a/bmp-operation-web/src/staticData/model/index.ts b/bmp-operation-web/src/staticData/model/index.ts new file mode 100644 index 0000000..95a4f35 --- /dev/null +++ b/bmp-operation-web/src/staticData/model/index.ts @@ -0,0 +1,474 @@ +import i18n from 'lib/i18n/index.ts'; // 国际化 +import {CurrencyType5, CurrencyType7, CurrencyType8, CurrencyStatusType} from '@utils/publicType'; +import ModelType from './type'; + +// 国际化 +const {global} = i18n; + +class ModelStaticData { + static processorManufacturerData: CurrencyType5[] = [ + { + value: 1, + label: 'Intel' + }, + { + value: 2, + label: 'AMD' + }, + { + value: 3, + label: 'Ampere' + }, + { + value: 4, + label: 'PHYTIUM' + }, + { + value: 5, + label: 'Hygon' + }, + { + value: 6, + label: 'Kunpeng920' + }, + { + value: 7, + label: '龙芯3号' + } + ]; + + static interfaceData: CurrencyType5[] = [ + { + label: 'DDR', + value: 1 + }, + { + label: 'DDR2', + value: 2 + }, + { + label: 'DDR3', + value: 3 + }, + { + label: 'DDR4', + value: 4 + }, + { + label: 'DDR5', + value: 5 + } + ]; + + static dominantFrequencyMHzData: CurrencyType7[] = [ + { + label: 2400, + value: 1 + }, + { + label: 2666, + value: 2 + }, + { + label: 2933, + value: 3 + }, + { + label: 3200, + value: 4 + } + ]; + + static capacityData: CurrencyType7[] = [ + { + label: 16, + value: 1 + }, + { + label: 32, + value: 2 + }, + { + label: 64, + value: 3 + }, + { + label: 128, + value: 4 + }, + { + label: 256, + value: 5 + }, + { + label: 384, + value: 6 + } + ]; + + static systemTypeData: CurrencyType5[] = [ + { + label: 'SSD', + value: 1 + }, + { + label: 'HDD', + value: 2 + } + ]; + + static systemInterfaceTypeData: CurrencyType5[] = [ + { + label: 'SATA', + value: 1 + }, + { + label: 'SAS', + value: 2 + }, + { + label: 'NVME', + value: 3 + } + ]; + + static sysSingleCapacityData: CurrencyType5[] = [ + { + label: 'GB', + value: 1 + }, + { + label: 'TB', + value: 2 + } + ]; + + static dataTypeData: CurrencyType5[] = [ + { + label: 'SSD', + value: 1 + }, + { + label: 'HDD', + value: 2 + } + ]; + + static dataInterfaceTypeData: CurrencyType5[] = [ + { + label: 'SATA', + value: 1 + }, + { + label: 'SAS', + value: 2 + }, + { + label: 'NVME', + value: 3 + } + ]; + static dataSingleCapacityData: CurrencyType5[] = [ + { + label: 'GB', + value: 1 + }, + { + label: 'TB', + value: 2 + } + ]; + static networkSpeedData: CurrencyType7[] = [ + { + label: 1, + value: 1 + }, + { + label: 10, + value: 2 + }, + { + label: 25, + value: 3 + }, + { + label: 100, + value: 4 + } + ]; + static networkSetUpData: CurrencyType8[] = [ + { + label: global.t('modelForm.netWork.single'), + value: 'single' + } + ]; + static networkSetUpData1: CurrencyType8[] = [ + { + label: global.t('modelForm.netWork.bond'), + value: 'bond' + }, + { + label: global.t('modelForm.netWork.dual'), + value: 'dual' + } + ]; + static gpuBrandData: CurrencyType5[] = [ + { + label: 'NVIDIA', + value: 1 + } + ]; + static gpuModelData: CurrencyType5[] = [ + { + label: 'T4', + value: 1 + }, + { + label: 'P40', + value: 2 + }, + { + label: 'V100', + value: 3 + }, + { + label: 'A100', + value: 4 + } + ]; + static heightUData: CurrencyType7[] = [ + { + label: 2, + value: 1 + }, + { + label: 4, + value: 2 + } + ]; + static modelTypeData: ModelType[] = [ + { + filterParams: 'computer', + text: global.t('deviceList.radioBtn.computed'), + value: 1 + }, + { + filterParams: 'storage', + text: global.t('deviceList.radioBtn.storage'), + value: 2 + }, + { + filterParams: 'gpu', + text: global.t('deviceList.radioBtn.GPU'), + value: 3 + }, + { + filterParams: 'other', + text: global.t('deviceList.radioBtn.other'), + value: 4 + }, + ]; + static modelList = [ + { + name: global.t('modelList.content.modelName'), // 机型名称 + selected: true, + disabled: true, + label: 'name', + showTooltip: false + }, + { + name: global.t('modelList.content.modelType'), // 机型类型 + selected: true, + disabled: false, + label: 'deviceSeries', + showTooltip: false + }, + { + name: global.t('modelList.content.machineRoomName'), // 机房名称 + selected: true, + disabled: false, + label: 'idcName', + showTooltip: false + }, + { + name: global.t('modelList.content.machineRoomCode'), // 机房编码 + selected: true, + disabled: false, + label: 'idcRegion', + showTooltip: false + }, + { + name: global.t('modelList.content.architecture'), // 体系架构 + selected: true, + disabled: false, + label: 'architecture', + showTooltip: false + }, + { + name: global.t('modelList.content.bootMode'), // 引导模式 + selected: true, + disabled: false, + label: 'bootMode', + showTooltip: false + }, + { + name: global.t('modelList.content.modelSpecification'), // 机型规格 + selected: true, + disabled: false, + label: 'deviceType', + showTooltip: false + }, + { + name: global.t('modelList.content.image'), // 镜像 + selected: true, + disabled: false, + label: 'image', + showTooltip: false + }, + { + name: global.t('modelList.content.device'), // 设备 + selected: true, + disabled: false, + label: 'deviceCount', + showTooltip: false + }, + { + name: global.t('modelList.content.CPU'), // CPU + selected: true, + disabled: false, + label: 'cpu', + showTooltip: false + }, + { + name: global.t('modelList.content.storage'), // 内存 + selected: true, + disabled: false, + label: 'memory', + showTooltip: false + }, + // { + // name: global.t('modelList.content.sysDisc'), // 系统盘 + // selected: true, + // disabled: false, + // label: 'systemVolume', + // showTooltip: false + // }, + // { + // name: global.t('modelList.content.raidConfig'), // RAID配置 + // selected: true, + // disabled: false, + // label: 'raidCan', + // showTooltip: false + // }, + // { + // name: global.t('modelList.content.sysRAID'), // 系统盘RAID + // selected: true, + // disabled: false, + // label: 'systemVolumeRaid', + // showTooltip: false + // }, + // { + // name: global.t('modelList.content.dataDisc'), // 数据盘 + // selected: true, + // disabled: false, + // label: 'dataVolume', + // showTooltip: false + // }, + { + name: global.t('modelList.content.networkCard'), // 网卡 + selected: true, + disabled: false, + label: 'nicInfo', + showTooltip: false + }, + { + name: global.t('modelList.content.networkSettings'), // 网络设置 + selected: true, + disabled: false, + label: 'nic', + showTooltip: false + }, + { + name: global.t('modelList.content.GPU'), // GPU + selected: true, + disabled: false, + label: 'gpu', + showTooltip: false + }, + { + name: global.t('modelList.content.desc'), // 描述 + selected: true, + disabled: false, + label: 'remark', + showTooltip: false + }, + { + name: global.t('modelList.content.operate.name'), // 操作 + selected: true, + disabled: true, + label: 'operate', + showTooltip: false + } + ]; + static modelInfo = (status1: CurrencyStatusType, status2: CurrencyStatusType) => { + return { + name: status2, + deviceSeries: status1, + idcName: status1, + idcRegion: status1, + architecture: status1, + bootMode: status1, + deviceType: status1, + image: status1, + deviceCount: status1, + cpu: status1, + memory: status1, + // systemVolume: status1, + // raidCan: status1, + // systemVolumeRaid: status1, + // dataVolume: status1, + nicInfo: status1, + nic: status1, + gpu: status1, + remark: status1, + operate: status2 + } + }; + + static modelTipData: string[] = [ + 'nameTip', + 'deviceSeriesNameTip', + 'idcNameTip', + 'idcNameEnTip', + 'architectureTip', + 'deviceTypeTip', + 'cpuInfoTip', + 'memInfoTip', + 'svInfoTip', + 'raidCanTip', + 'raidTip', + 'dvInfoTip', + 'nicInfoTip', + 'interfaceModeNameTip', + 'gpuInfoTip', + 'descriptionTip' + ]; + + static modelDetailTipData: string[] = [ + 'imageNameTip', + 'osTypeTip', + 'osVersionTip' + ]; + + static modelSpecData: string[] = ['预置规格', 'Preset Specifications']; + + static noRaidData: string[] = ['NORAID', 'NO RAID']; + + static noRaidData2: string[] = ['', 'NO RAID', 'NORAID']; + + static otherSpecData: string[] = ['Other specifications', '其它规格']; + + static singleRaid0: string[] = ['RAID0-stripping', '单盘RAID0']; +}; + +export default ModelStaticData; diff --git a/bmp-operation-web/src/staticData/model/type.ts b/bmp-operation-web/src/staticData/model/type.ts new file mode 100644 index 0000000..777ed65 --- /dev/null +++ b/bmp-operation-web/src/staticData/model/type.ts @@ -0,0 +1,13 @@ +/** + * 通用类-列表 +*/ +type CurrencyType = { + text: string; + label: string | number; + info: any; + filterParams: string; +}; + +type ModelType = Required<{value: number | string;}> & Partial; + +export default ModelType; diff --git a/bmp-operation-web/src/staticData/navBar/index.ts b/bmp-operation-web/src/staticData/navBar/index.ts new file mode 100644 index 0000000..46ca08c --- /dev/null +++ b/bmp-operation-web/src/staticData/navBar/index.ts @@ -0,0 +1,42 @@ +/** + * @file + * @author +*/ + +// 创建一个 require 上下文,它会匹配 +const requireAll = (requireContext: T) => { + // keys 返回字典的所有的key + return requireContext.keys().map(requireContext); +} + +const svgFiles = [ + ...requireAll(require.context('../../views/', true, /\/navRouter.ts$/)), +] + +const [deviceNavData, idcNavData, imageNavData, inBandMonitoringNavData, _, modelNavData, monitoringNavData, personalCenterNavData, roleNavData, userNavData] = svgFiles.map((item) => item?.default?? item); + +// 所有数据列表 +const eyeryData = (proxy: { + $defInfo: { + routerPath: (arg0: string) => void, + imagePath: (arg0: string) => void + } +}) => { + const routerPath = proxy.$defInfo.routerPath; + const imagePath = proxy.$defInfo.imagePath; + return [ + idcNavData(routerPath, imagePath), + modelNavData(routerPath, imagePath), + imageNavData(routerPath, imagePath), + deviceNavData(routerPath, imagePath), + inBandMonitoringNavData(routerPath, imagePath), + monitoringNavData(routerPath, imagePath), + roleNavData(routerPath, imagePath), + userNavData(routerPath, imagePath), + svgFiles[4].userNavData(routerPath, imagePath), + svgFiles[4].adminUserNavData(routerPath, imagePath), + personalCenterNavData(routerPath, imagePath) + ]; +}; + +export default eyeryData; diff --git a/bmp-operation-web/src/staticData/navBar/type.ts b/bmp-operation-web/src/staticData/navBar/type.ts new file mode 100644 index 0000000..c336d70 --- /dev/null +++ b/bmp-operation-web/src/staticData/navBar/type.ts @@ -0,0 +1,16 @@ + +/** + * 导航类 +*/ +type NavType = { + title: string; + defaultImg: string; + changeImg: string; + path: string | string[]; + // detailPath: string; + otherPath: [any] | [any, string]; +}; + +type NavigationBarListaType = Required & Partial<{children?: NavType[];}>; + +export default NavigationBarListaType; \ No newline at end of file diff --git a/bmp-operation-web/src/staticData/role/index.ts b/bmp-operation-web/src/staticData/role/index.ts new file mode 100644 index 0000000..784ce1f --- /dev/null +++ b/bmp-operation-web/src/staticData/role/index.ts @@ -0,0 +1,40 @@ +import i18n from 'lib/i18n/index.ts'; // 国际化 +import {CurrencyStatusType} from '@utils/publicType'; + +// 国际化 +const {global} = i18n; + +class RoleStaticData { + static roleList = [ + { + name: global.t('roleList.label.role'), + selected: true, + disabled: true, + label: 'roleName', + showTooltip: false + }, + { + name: global.t('roleList.label.relationUser'), + selected: true, + disabled: false, + label: 'userName', + showTooltip: false + }, + { + name: global.t('roleList.label.jurisdiction'), + selected: true, + disabled: true, + label: 'operate', + showTooltip: false + } + ]; + + static roleInfo = (status1: CurrencyStatusType, status2: CurrencyStatusType) => { + return { + operate: status2, + roleName: status2, + userName: status1 + } + }; +}; +export default RoleStaticData; diff --git a/bmp-operation-web/src/staticData/staticData.ts b/bmp-operation-web/src/staticData/staticData.ts new file mode 100644 index 0000000..452e0a3 --- /dev/null +++ b/bmp-operation-web/src/staticData/staticData.ts @@ -0,0 +1,64 @@ +import IdcStaticData from './idc/index'; +import ModelStaticData from './model/index'; +import ImageStaticData from './image/index'; +import DeviceStaticData from './device/index'; +import RoleStaticData from './role/index'; +import UserStaticData from './user/index'; +import {CurrencyStatusType} from '@utils/publicType'; +import {AllCustomInfoType, AllCustomListType} from './staticDataType'; // 对应ts状态类 +import FaultRulesStaticeData from './surveillance/faultRules/index'; +import HardwareStaticData from './surveillance/hardware/index'; +import FalutLogStaticData from './surveillance/faultLog/index'; +import MessageStaticData from './message/index'; +import AllAlarmRulesStatic from './inBandMonitoring/allAlarmRules/index'; + +// 通用状态 +const currencyStatus: CurrencyStatusType = { + required: false, + selected: true +}; + +// 禁止更改状态 +const prohibitChangesStatus: CurrencyStatusType = { + required: true, + selected: true +}; + +class AllStaticData { + static allCustomListInfo: AllCustomInfoType = { + idcInfo: IdcStaticData.idcInfo(currencyStatus, prohibitChangesStatus), + modelInfo: ModelStaticData.modelInfo(currencyStatus, prohibitChangesStatus), + imageInfo: ImageStaticData.imageInfo(currencyStatus, prohibitChangesStatus), + deviceInfo: DeviceStaticData.deviceInfo(currencyStatus, prohibitChangesStatus), + deviceFaultLogInfo: DeviceStaticData.deviceFaultLogInfo(currencyStatus, prohibitChangesStatus), + messageInfo: MessageStaticData.messageInfo(currencyStatus, prohibitChangesStatus), + hardwareInfo: HardwareStaticData.hardwareInfo(currencyStatus, prohibitChangesStatus), + faultLogInfo: FalutLogStaticData.faultLogInfo(currencyStatus, prohibitChangesStatus), + faultRulesInfo: FaultRulesStaticeData.faultRulesInfo(currencyStatus, prohibitChangesStatus), + roleInfo: RoleStaticData.roleInfo(currencyStatus, prohibitChangesStatus), + userInfo: UserStaticData.userInfo(currencyStatus, prohibitChangesStatus), + auditLogsInfo: DeviceStaticData.auditLogsInfo(currencyStatus, prohibitChangesStatus), + allAlarmRulesInfo: AllAlarmRulesStatic.allAlarmRulesInfo(currencyStatus, prohibitChangesStatus) + }; + + static allCustomList: AllCustomListType = { + idcList: IdcStaticData.idcList, + modelList: ModelStaticData.modelList, + imageList: ImageStaticData.imageList, + deviceList: DeviceStaticData.deviceList, + deviceFaultLogList: DeviceStaticData.deviceFaultLogList, + messageList: MessageStaticData.messageList, + hardwareList: HardwareStaticData.hardwareList, + faultLogList: FalutLogStaticData.faultLogList, + faultRulesList: FaultRulesStaticeData.faultRulesList, + roleList: RoleStaticData.roleList, + userList: UserStaticData.userList, + auditLogsList: DeviceStaticData.auditLogsList, + allAlarmRulesList: AllAlarmRulesStatic.allAlarmRulesList + }; + + static noFoundData: string[] = ['找不到对象', 'Not found']; +}; + + +export default AllStaticData; diff --git a/bmp-operation-web/src/staticData/staticDataType.ts b/bmp-operation-web/src/staticData/staticDataType.ts new file mode 100644 index 0000000..bab8f07 --- /dev/null +++ b/bmp-operation-web/src/staticData/staticDataType.ts @@ -0,0 +1,89 @@ +import {CurrencyStatusType} from '../utils/publicType'; + +/** + * 通用类-列表 +*/ +type CurrencyType = { + text: string; + label: string | number; + info: any; + filterParams: string; +}; + +/** + * 导航类 +*/ +type NavType = { + title: string; + defaultImg: string; + changeImg: string; + path: string | string[]; + detailPath: string; +}; + +/** + * 自定义数据信息类 +*/ +type InfoType = Record>; + +/** + * 角色数据类 +*/ +type RoleNameDataType = { + filterParams: string; + showInfo: string; + text: string; + value: number; +}; + +/** + * 类集合 +*/ +interface StaticDataType { + NavigationBarListaType: Required & Partial<{children?: NavType[];}>; + CurrencyListType: Required<{value: number | string;}> & Partial; + CustomCurrencyType: Omit & Required<{name: string; disabled: boolean; showTooltip: boolean;}> & Partial<{label: string;}>; + CustomInfoType: InfoType; + ModelListCustomInfoType: InfoType; + ImageListCustomInfoType: InfoType; + DeviceListCustomType: InfoType; + MessageListCustomType: InfoType; + HardwareType: InfoType; + FaultLogType: InfoType; + FaultRulesType: InfoType; + RoleListCustomInfoType: InfoType; + UserListCustomInfoType: InfoType; + AuditLogsInfoType: InfoType; + AllAlarmRulesInfoInfoType: InfoType; + FilterDataType: Required<{text: string; value: number;}>; + roleId: RoleNameDataType[]; +}; + +type AllCustomInfoType = { + idcInfo: StaticDataType['CustomInfoType']; + modelInfo: StaticDataType['ModelListCustomInfoType']; + imageInfo: StaticDataType['ImageListCustomInfoType']; + deviceInfo: StaticDataType['DeviceListCustomType']; + messageInfo: StaticDataType['MessageListCustomType']; + deviceFaultLogInfo: StaticDataType['DeviceListCustomType']; + faultLogInfo: StaticDataType['HardwareType']; + hardwareInfo: StaticDataType['FaultLogType']; + faultRulesInfo: StaticDataType['FaultRulesType']; + roleInfo: StaticDataType['RoleListCustomInfoType']; + userInfo: StaticDataType['UserListCustomInfoType']; + auditLogsInfo: StaticDataType['AuditLogsInfoType']; + allAlarmRulesInfo: StaticDataType['AllAlarmRulesInfoInfoType']; +}; + +type key = 'idcList' | 'modelList' | 'imageList' | 'deviceList' | 'messageList' | 'deviceFaultLogList' | 'hardwareList' | 'faultLogList' | 'faultRulesList' | 'roleList' | 'userList' | 'auditLogsList' | 'allAlarmRulesList'; + + +type AllCustomListType = { + [k in key]: StaticDataType['CustomCurrencyType'][]; +}; + + +export { + AllCustomInfoType, + AllCustomListType, +}; diff --git a/bmp-operation-web/src/staticData/surveillance/faultLog/index.ts b/bmp-operation-web/src/staticData/surveillance/faultLog/index.ts new file mode 100644 index 0000000..018f784 --- /dev/null +++ b/bmp-operation-web/src/staticData/surveillance/faultLog/index.ts @@ -0,0 +1,163 @@ +import i18n from 'lib/i18n/index.ts'; // 国际化 +import {CurrencyStatusType} from '@utils/publicType'; + +// 国际化 +const {global} = i18n; + +class FalutLogStaticData { + + static faultLogTipData: string[] = [ + 'logidTip', + 'snTip', + 'idcNameTip', + 'alertLevelTip', + 'alertTypeTip', + 'alertPartTip', + 'iloIpTip', + 'alertDescTip', + 'alertContentTip', + 'statusTip', + 'countTip', + 'collectTimeTip', + 'eventTimeTip', + 'updateTimeTip' + ]; + + static faultDisposeOfConfirmTip: string[] = [ + 'snTip', + 'alertNameTip', + 'alertTypeTip', + 'alertDescTip', + 'collectTimeTip' + ]; + + static faultLogInfo = (status1: CurrencyStatusType, status2: CurrencyStatusType) => { + return { + logid: status2, + sn: status2, + idcName: status1, + alertLevel: status1, + alertType: status1, + alertPart: status1, + iloIp: status1, + alertDesc: status1, + alertContent: status1, + status: status1, + count: status1, + collectTime: status1, + eventTime: status1, + updateTime: status1, + operate: status2 + } + }; + + static faultLogList = [ + { + name: global.t('faultLogList.table.label.logId'), + selected: true, + disabled: true, + label: 'logid', + showTooltip: false + }, + { + name: global.t('faultLogList.table.label.sn'), + selected: true, + disabled: true, + label: 'sn', + showTooltip: false + }, + { + name: global.t('faultLogList.table.label.idc'), + selected: true, + disabled: false, + label: 'idcName', + showTooltip: false + }, + { + name: global.t('faultLogList.table.label.level'), + selected: true, + disabled: false, + label: 'alertLevel', + showTooltip: false + }, + { + name: global.t('faultLogList.table.label.type'), + selected: true, + disabled: false, + label: 'alertType', + showTooltip: false + }, + { + name: global.t('faultLogList.table.label.accessory'), + selected: true, + disabled: false, + label: 'alertPart', + showTooltip: false + }, + { + name: global.t('faultLogList.table.label.iloip'), + selected: true, + disabled: false, + label: 'iloIp', + showTooltip: false + }, + { + name: global.t('faultLogList.table.label.desc'), + selected: true, + disabled: false, + label: 'alertDesc', + showTooltip: false + }, + { + name: global.t('faultLogList.table.label.originalLog'), + selected: true, + disabled: false, + label: 'alertContent', + showTooltip: false + }, + { + name: global.t('faultLogList.table.label.status'), + selected: true, + disabled: false, + label: 'status', + showTooltip: false + }, + { + name: global.t('faultLogList.table.label.numberOfAlarms'), + selected: true, + disabled: false, + label: 'count', + showTooltip: false + }, + { + name: global.t('faultLogList.table.label.faultDetectionTime'), + selected: true, + disabled: false, + label: 'collectTime', + showTooltip: false + }, + { + name: global.t('faultLogList.table.label.faultAlarmTime'), + selected: true, + disabled: false, + label: 'eventTime', + showTooltip: false + }, + { + name: global.t('faultLogList.table.label.updateTime'), + selected: true, + disabled: false, + label: 'updateTime', + showTooltip: false + }, + { + name: global.t('faultLogList.table.label.operate'), + selected: true, + disabled: true, + label: 'operate', + showTooltip: false + } + ]; +}; + +export default FalutLogStaticData; diff --git a/bmp-operation-web/src/staticData/surveillance/faultRules/index.ts b/bmp-operation-web/src/staticData/surveillance/faultRules/index.ts new file mode 100644 index 0000000..d9f2246 --- /dev/null +++ b/bmp-operation-web/src/staticData/surveillance/faultRules/index.ts @@ -0,0 +1,118 @@ +import i18n from 'lib/i18n/index.ts'; // 国际化 +import {CurrencyStatusType, ListShowTooltipType} from '@utils/publicType'; + +// 国际化 +const {global} = i18n; + +class FaultRulesStaticeData { + + static faultRulesInfo = (status1: CurrencyStatusType, status2: CurrencyStatusType) => { + return { + alertName: status2, + alertSpec: status1, + alertType: status1, + alertCondition: status1, + alertThreshold: status1, + alertLevel: status1, + alertDesc: status1, + pushStatus: status2, + useStatus: status2, + } + }; + + static faultRulesList = [ + { + name: global.t('faultRulesList.table.label.faultName'), + selected: true, + disabled: true, + label: 'alertName', + showTooltip: false + }, + { + name: global.t('faultRulesList.table.label.faultAccessories'), + selected: true, + disabled: false, + label: 'alertSpec', + showTooltip: false + }, + { + name: global.t('faultRulesList.table.label.faultType'), + selected: true, + disabled: false, + label: 'alertType', + showTooltip: false + }, + { + name: global.t('faultRulesList.table.label.judgmentConditions'), + selected: true, + disabled: false, + label: 'alertCondition', + showTooltip: false + }, + { + name: global.t('faultRulesList.table.label.decisionThreshold'), + selected: true, + disabled: false, + label: 'alertThreshold', + showTooltip: false + }, + { + name: global.t('faultRulesList.table.label.faultLevel'), + selected: true, + disabled: false, + label: 'alertLevel', + showTooltip: false + }, + { + name: global.t('faultRulesList.table.label.faultDesc'), + selected: true, + disabled: false, + label: 'alertDesc', + showTooltip: false + }, + { + name: global.t('faultRulesList.table.label.faultPush'), + selected: true, + disabled: true, + label: 'pushStatus', + showTooltip: false + }, + { + name: global.t('faultRulesList.table.label.enableStatus'), + selected: true, + disabled: true, + label: 'useStatus', + showTooltip: false + } + ]; + + static faultRulesTipData: string[] = [ + 'alertNameTip', + 'alertSpecTip', + 'alertTypeTip', + 'alertConditionTip', + 'alertThresholdTip', + 'alertLevelTip', + 'alertDescTip' + ]; + + static faultRulesTooltip: ListShowTooltipType = { + alertName: {}, + alertSpec: {}, + alertType: {}, + alertCondition: {}, + alertThreshold: {}, + alertLevel: {}, + alertDesc: {} + }; + + // constructor() { + // for (const index in FaultRulesStaticeData.faultRulesTooltip) { + // FaultRulesStaticeData.faultRulesTooltip[index] = { + // showTooltip: false + // }; + // } + // } +}; + +export default FaultRulesStaticeData; diff --git a/bmp-operation-web/src/staticData/surveillance/hardware/index.ts b/bmp-operation-web/src/staticData/surveillance/hardware/index.ts new file mode 100644 index 0000000..49c570d --- /dev/null +++ b/bmp-operation-web/src/staticData/surveillance/hardware/index.ts @@ -0,0 +1,121 @@ +import i18n from 'lib/i18n/index.ts'; // 国际化 +import {CurrencyStatusType} from '@utils/publicType'; + +// 国际化 +const {global} = i18n; + +class HardwareStaticData { + + static hardwareTipData: string[] = [ + 'snTip', + 'idcNameTip', + 'brandTip', + 'modelTip' + ]; + + static hardwareInfo = (status1: CurrencyStatusType, status2: CurrencyStatusType) => { + return { + sn: status2, + idcName: status1, + brand: status1, + model: status1, + manageStatus: status1, + cpuStatus: status1, + memStatus: status1, + diskStatus: status1, + nicStatus: status1, + powerStatus: status1, + otherStatus: status1, + operate: status2 + } + }; + + static hardwareList = [ + { + name: global.t('hardwareStatusList.table.label.sn'), + selected: true, + disabled: true, + label: 'sn', + showTooltip: false + }, + { + name: global.t('hardwareStatusList.table.label.idc'), + selected: true, + disabled: false, + label: 'idcName', + showTooltip: false + }, + { + name: global.t('hardwareStatusList.table.label.brand'), + selected: true, + disabled: false, + label: 'brand', + showTooltip: false + }, + { + name: global.t('hardwareStatusList.table.label.model'), + selected: true, + disabled: false, + label: 'model', + showTooltip: false + }, + { + name: global.t('hardwareStatusList.table.label.managementStatus'), + selected: true, + disabled: false, + label: 'manageStatus', + showTooltip: false + }, + { + name: global.t('hardwareStatusList.table.label.cpu'), + selected: true, + disabled: false, + label: 'cpuStatus', + showTooltip: false + }, + { + name: global.t('hardwareStatusList.table.label.storage'), + selected: true, + disabled: false, + label: 'memStatus', + showTooltip: false + }, + { + name: global.t('hardwareStatusList.table.label.hardDisk'), + selected: true, + disabled: false, + label: 'diskStatus', + showTooltip: false + }, + { + name: global.t('hardwareStatusList.table.label.networkCard'), + selected: true, + disabled: false, + label: 'nicStatus', + showTooltip: false + }, + { + name: global.t('hardwareStatusList.table.label.powerSupply'), + selected: true, + disabled: false, + label: 'powerStatus', + showTooltip: false + }, + { + name: global.t('hardwareStatusList.table.label.other'), + selected: true, + disabled: false, + label: 'otherStatus', + showTooltip: false + }, + { + name: global.t('hardwareStatusList.table.label.operate'), + selected: true, + disabled: true, + label: 'operate', + showTooltip: false + } + ]; +}; + +export default HardwareStaticData; diff --git a/bmp-operation-web/src/staticData/surveillance/index.ts b/bmp-operation-web/src/staticData/surveillance/index.ts new file mode 100644 index 0000000..7a1b58f --- /dev/null +++ b/bmp-operation-web/src/staticData/surveillance/index.ts @@ -0,0 +1,41 @@ +import i18n from 'lib/i18n/index.ts'; // 国际化 +import {CurrencyType9} from '@utils/publicType'; + +// 国际化 +const {global} = i18n; + +class SurveillanceStaticeData { + static faultLevel: string[] = [ + 'Critical', + 'Warning' + ]; + + static faultyAccessories: string[] = [ + global.t('surveillance.accessory.cpu'), + global.t('surveillance.accessory.mem'), + global.t('surveillance.accessory.hardDisk'), + global.t('surveillance.accessory.networkCard'), + global.t('surveillance.accessory.powerSupply'), + global.t('surveillance.accessory.voltage'), + global.t('surveillance.accessory.fan'), + global.t('surveillance.accessory.temperature'), + global.t('surveillance.accessory.pcie') + ]; + + static status: CurrencyType9[] = [ + { + text: global.t('surveillance.status.all'), + value: '' + }, + { + text: global.t('surveillance.status.no'), + value: '0' + }, + { + text: global.t('surveillance.status.yes'), + value: '1' + } + ]; +}; + +export default SurveillanceStaticeData; diff --git a/bmp-operation-web/src/staticData/user/index.ts b/bmp-operation-web/src/staticData/user/index.ts new file mode 100644 index 0000000..7769008 --- /dev/null +++ b/bmp-operation-web/src/staticData/user/index.ts @@ -0,0 +1,319 @@ +import i18n from 'lib/i18n/index.ts'; // 国际化 +import {UserType, RoleNameDataType} from './type'; +import {CurrencyStatusType} from '@utils/publicType'; + +// 国际化 +const {global} = i18n; + +class UserStaticData { + // 手机号 + static cellPhoneType: UserType[] = [ + { + value: 1, + text: '086', + label: global.t('addUser.phoneData.China') // 中国大陆 + }, + { + value: 2, + text: '852', + label: global.t('addUser.phoneData.HongKong') // 中国香港 + }, + { + value: 3, + text: '853', + label: global.t('addUser.phoneData.MacaMacao') // 中国澳门 + }, + { + value: 4, + text: '886', + label: global.t('addUser.phoneData.Taiwan') // 中国台湾 + }, + { + value: 5, + text: '54', + label: global.t('addUser.phoneData.Argentina') // 阿根廷 + }, + { + value: 6, + text: '61', + label: global.t('addUser.phoneData.Australia') // 澳大利亚 + }, + { + value: 7, + text: '55', + label: global.t('addUser.phoneData.Brazil') // 巴西 + }, + { + value: 8, + text: '49', + label: global.t('addUser.phoneData.Germany') // 德国 + }, + { + value: 9, + text: '33', + label: global.t('addUser.phoneData.France') // 法国 + }, + { + value: 10, + text: '82', + label: global.t('addUser.phoneData.SouthKorea') // 韩国 + }, + { + value: 11, + text: '01', + label: global.t('addUser.phoneData.Canada') // 加拿大 + }, + { + value: 12, + text: '1', + label: global.t('addUser.phoneData.USA') // 美国 + }, + { + value: 13, + text: '52', + label: global.t('addUser.phoneData.Mexico') // 墨西哥 + }, + { + value: 14, + text: '27', + label: global.t('addUser.phoneData.SouthAfrica') // 南非 + }, + { + value: 15, + text: '81', + label: global.t('addUser.phoneData.Japan') // 日本 + }, + { + value: 16, + text: '966', + label: global.t('addUser.phoneData.SaudiArabia') // 沙特阿拉伯 + }, + { + value: 17, + text: '90', + label: global.t('addUser.phoneData.Turkey') // 土耳其 + }, + { + value: 18, + text: '39', + label: global.t('addUser.phoneData.Italy') // 意大利 + }, + { + value: 19, + text: '91', + label: global.t('addUser.phoneData.India') // 印度 + }, + { + value: 20, + text: '62', + label: global.t('addUser.phoneData.Indonesia') // 印度尼西亚 + }, + { + value: 21, + text: '44', + label: global.t('addUser.phoneData.UnitedKiongdom') // 英国 + } + ]; + + // 用户筛选数据 + static userFilterData: RoleNameDataType[] = [ + { + filterParams: 'role-admin-uuid-01', + showInfo: 'admin', + text: global.t('addUser.role.owner'), // 平台拥有者 + value: 1 + }, + { + filterParams: 'role-user-uuid-01', + showInfo: 'user', + text: global.t('addUser.role.user'), // 普通用户 + value: 2 + }, + { + filterParams: 'role-operator-uuid-01', + showInfo: 'operator', + text: global.t('addUser.role.operator'), // 运营人员 + value: 3 + } + ]; + + static phoneType: {type: string; name: string;}[] = [ + { + type: '086', + name: global.t('editUser.phoneData.China'), + }, + { + type: '852', + name: global.t('editUser.phoneData.HongKong') + }, + + { + type: '853', + name: global.t('editUser.phoneData.MacaMacao'), + }, + { + type: '886', + name: global.t('editUser.phoneData.Taiwan') + }, + { + type: '54', + name: global.t('editUser.phoneData.Argentina'), + }, + { + type: '61', + name: global.t('editUser.phoneData.Australia') + }, + { + type: '55', + name: global.t('editUser.phoneData.Brazil'), + }, + { + type: '49', + name: global.t('editUser.phoneData.Germany') + }, + + { + type: '33', + name: global.t('editUser.phoneData.France'), + }, + { + type: '82', + name: global.t('editUser.phoneData.SouthKorea') + }, + { + type: '01', + name: global.t('editUser.phoneData.Canada'), + }, + { + type: '1', + name: global.t('editUser.phoneData.USA') + }, + { + type: '52', + name: global.t('editUser.phoneData.Mexico'), + }, + { + type: '27', + name: global.t('editUser.phoneData.SouthAfrica') + }, + + { + type: '81', + name: global.t('editUser.phoneData.Japan'), + }, + { + type: '966', + name: global.t('editUser.phoneData.SaudiArabia') + }, + { + type: '90', + name: global.t('editUser.phoneData.Turkey'), + }, + { + type: '39', + name: global.t('editUser.phoneData.Italy') + }, + { + type: '91', + name: global.t('editUser.phoneData.India'), + }, + { + type: '62', + name: global.t('editUser.phoneData.Indonesia') + }, + + { + type: '44', + name: global.t('editUser.phoneData.UnitedKiongdom'), + } + ]; + + static userList = [ + { + name: global.t('userList.label.userName'), + selected: true, + disabled: true, + label: 'userName', + showTooltip: false + }, + { + name: global.t('userList.label.userId'), + selected: true, + disabled: false, + label: 'userId', + showTooltip: false + }, + { + name: global.t('userList.label.role'), + selected: true, + disabled: false, + label: 'roleName', + showTooltip: false + }, + { + name: global.t('userList.label.itemNum'), + selected: true, + disabled: false, + label: 'projectCount', + showTooltip: false + }, + { + name: global.t('userList.label.cellPhone'), + selected: true, + disabled: false, + label: 'phone', + showTooltip: false + }, + { + name: global.t('userList.label.email'), + selected: true, + disabled: false, + label: 'email', + showTooltip: false + }, + { + name: global.t('userList.label.desc'), + selected: true, + disabled: false, + label: 'remark', + showTooltip: false + }, + { + name: global.t('userList.label.createTime'), + selected: true, + disabled: false, + label: 'createTime', + showTooltip: false + }, + { + name: global.t('userList.label.operate.name'), + selected: true, + disabled: true, + label: 'operate', + showTooltip: false + } + ]; + + static userInfo = (status1: CurrencyStatusType, status2: CurrencyStatusType) => { + return { + createTime: status1, + email: status1, + operate: status2, + phone: status1, + projectCount: status1, + remark: status1, + userId: status1, + roleName: status1, + userName: status2 + } + }; + + static userTipData: string[] = [ + 'userNameTip', + 'userIdTip', + 'phoneNumberTip', + 'emailTip', + 'descriptionTip' + ]; +}; +export default UserStaticData; diff --git a/bmp-operation-web/src/staticData/user/type.ts b/bmp-operation-web/src/staticData/user/type.ts new file mode 100644 index 0000000..b716a1b --- /dev/null +++ b/bmp-operation-web/src/staticData/user/type.ts @@ -0,0 +1,26 @@ +/** + * 通用类-列表 +*/ +type CurrencyType = { + text: string; + label: string | number; + info: any; + filterParams: string; +}; + +/** + * 角色数据类 +*/ +type RoleNameDataType = { + filterParams: string; + showInfo: string; + text: string; + value: number; +}; + +type UserType = Required<{value: number | string;}> & Partial; + +export { + UserType, + RoleNameDataType +}; diff --git a/bmp-operation-web/src/staticData/userCenter/index.ts b/bmp-operation-web/src/staticData/userCenter/index.ts new file mode 100644 index 0000000..fb14ca9 --- /dev/null +++ b/bmp-operation-web/src/staticData/userCenter/index.ts @@ -0,0 +1,23 @@ +import {language} from 'utils/publicClass.ts'; +import {TabsDataType} from '@utils/publicType'; + +class UserCenterDataStatic { + static tabsStaticData: TabsDataType['tabsPangeData'] = [ + { + label: language.t('userCenter.tabs.myProfile'), + name: 'myProfile' + }, + { + label: language.t('userCenter.tabs.securitySettings'), + name: 'securitySettings' + }, + { + label: language.t('userCenter.tabs.apiKey'), + name: 'apiKey' + } + ]; + + static apiKeyTipData: string[] = ['nameTip']; +}; + +export default UserCenterDataStatic; diff --git a/bmp-operation-web/src/store/index.ts b/bmp-operation-web/src/store/index.ts new file mode 100644 index 0000000..012f9e0 --- /dev/null +++ b/bmp-operation-web/src/store/index.ts @@ -0,0 +1,34 @@ +import pinia from 'lib/pinia/pinia.ts'; // pina +import loginInfoStore from './modules/loginInfo'; +import progressInfoStore from './modules/progress'; +import customInfoStore from './modules/custom'; +import sysPartitionStore from './modules/systemPartition'; +import imagesStore from './modules/imagesData'; +import filterEmptyStore from './modules/filterEmpty'; +import navigationBarStore from './modules/navigationBar'; +import ossDataStore from './modules/ossData'; +import modeFormStore from './modules/modeForm'; +import userPurviewStore from './modules/userPurview'; +import idcStore from './modules/idc'; +import faultLevelStore from './modules/faultLevel'; +import faultSpecStore from './modules/faultSpec'; +import deviceDetailErrorTipStore from './modules/deviceDetailErrorTip'; + +const store = { + idcInfo: idcStore(pinia), + loginInfo: loginInfoStore(pinia), + progressInfo: progressInfoStore(), + customInfo: customInfoStore(), + sysPartitionInfo: sysPartitionStore(), + imagesInfo: imagesStore(), + filterEmpty: filterEmptyStore(), + navigationBarStatus: navigationBarStore(), + faultLevelInfo: faultLevelStore(), + faultSpecInfo: faultSpecStore(), + ossDataInfo: ossDataStore, + modeFormInfo: modeFormStore, + userPurviewInfo: userPurviewStore, + deviceDetailErrorTipInfo: deviceDetailErrorTipStore() +}; + +export default store; diff --git a/bmp-operation-web/src/store/modules/custom.ts b/bmp-operation-web/src/store/modules/custom.ts new file mode 100644 index 0000000..36dfe30 --- /dev/null +++ b/bmp-operation-web/src/store/modules/custom.ts @@ -0,0 +1,144 @@ +import {defineStore} from 'pinia'; // 定义容器名 +import {customListAPI, surveillanceCustomListAPI} from 'api/public/request.ts'; +import {methodsTotal} from 'utils/index.ts'; +import {IndexStateType, CheckListArrType, CurrencyStatusType} from '../typeManagement'; +import AllStaticData from 'staticData/staticData.ts'; +import storeName from 'store/storeName.ts'; // 容器名 + +const {allCustomListInfo} = AllStaticData; + +const customInfoStore = defineStore(storeName.customList, { + state: (): IndexStateType => { + return { + customDataInfo: [ + { + pageKey: 'idcList', + data: allCustomListInfo.idcInfo + }, + { + pageKey: 'deviceTypeList', + data: allCustomListInfo.modelInfo + }, + { + pageKey: 'imageList', + data: allCustomListInfo.imageInfo + }, + { + pageKey: 'deviceList', + data: allCustomListInfo.deviceInfo + }, + { + pageKey: methodsTotal.humpConversion('deviceAlertLogList'), + data: allCustomListInfo.deviceFaultLogInfo + }, + { + pageKey: methodsTotal.humpConversion('deviceStatusList'), + data: allCustomListInfo.hardwareInfo + }, + { + pageKey: methodsTotal.humpConversion('alertLogList'), + data: allCustomListInfo.faultLogInfo + }, + { + pageKey: methodsTotal.humpConversion('alertRuleList'), + data: allCustomListInfo.faultRulesInfo + }, + { + pageKey: 'roleList', + data: allCustomListInfo.roleInfo + }, + { + pageKey: 'userList', + data: allCustomListInfo.userInfo + }, + { + pageKey: 'messageList', + data: allCustomListInfo.messageInfo + }, + { + pageKey: 'auditLogsList', + data: allCustomListInfo.auditLogsInfo + }, + { + pageKey: 'monitorRulesList', + data: allCustomListInfo.allAlarmRulesInfo + } + ] + } + }, + actions: { + /** + * 自定义列表 + * @param {string} pageKey 不同列表不同key + * @param {Object} reactiveArr.hasCustomInfo 对应列表信息,用来接收接口返回的状态 + * @param {Array} checkListArr 根据接口返回的信息做数据处理 + */ + customList( + pageKey: string, + reactiveArr: { + hasCustomInfo: Record; + checkListArr: CheckListArrType; + } + ) { + let params: {pageKey?: string;}; + let requestAPI: Function; + const requestParamsAPI = [ + [ + (key: string) => key.indexOf('_') > -1, + () => { + params = methodsTotal.toLine({pageKey}); + requestAPI = surveillanceCustomListAPI; + } + ], + [ + (key: string) => !(key.includes('_')), + () => { + params = {pageKey}; + requestAPI = customListAPI; + } + ] + ]; + for (const key of requestParamsAPI) { + if (key[0](pageKey)) { + key[1](pageKey); + break; + } + } + nextTick(() => { + requestAPI( + { + ...params + } + ).then(({data} : {data: {result: {customInfo: Record;}}}) => { + const result = methodsTotal.lineConverting(data?.result); + if (result?.customInfo) { + // 列表展示数据 + const checkListArr: CheckListArrType = reactiveArr.checkListArr; + // 遍历列表展示数据 + for (const key of checkListArr) { + // 遍历自定义信息数据 + for (const index in reactiveArr.hasCustomInfo) { + // 点击的当前项等于对应数据的那一项 + if (index === key.label) { + // 状态赋值 + key.disabled = reactiveArr.hasCustomInfo[index].required; + key.selected = reactiveArr.hasCustomInfo[index].selected; + } + else { + reactiveArr.hasCustomInfo = result.customInfo; + } + } + } + return; + } + return Promise.reject(); + }) + .catch(() => { + reactiveArr.hasCustomInfo = this.customDataInfo?.filter((item: {pageKey: string}) => item.pageKey === pageKey)[0]?.data??[]; + }); + }) + } + } +}); + +export default customInfoStore; \ No newline at end of file diff --git a/bmp-operation-web/src/store/modules/deviceDetailErrorTip.ts b/bmp-operation-web/src/store/modules/deviceDetailErrorTip.ts new file mode 100644 index 0000000..57d3b9e --- /dev/null +++ b/bmp-operation-web/src/store/modules/deviceDetailErrorTip.ts @@ -0,0 +1,28 @@ +import {defineStore} from 'pinia'; // 定义容器名 +// import {faultLevelAPI} from 'api/surveillance/faultRule/request.ts'; +import storeName from 'store/storeName.ts'; // 容器名 +// import SurveillanceStaticeData from 'staticData/surveillance/index.ts'; + +const deviceDetailErrorTipStore = defineStore(storeName.deviceDetailErrorTipOpt, { + state: () => { + return { + errorStatus: false + } + }, + // 类似computed + getters: { + // 获取raids + getErrorStatus (state) { + return state.errorStatus; + } + }, + + // actions: { + + // setErrorStatus() { + // this.errorStatus = !this.errorStatus; + // } + // } +}); + +export default deviceDetailErrorTipStore; diff --git a/bmp-operation-web/src/store/modules/faultLevel.ts b/bmp-operation-web/src/store/modules/faultLevel.ts new file mode 100644 index 0000000..69313a0 --- /dev/null +++ b/bmp-operation-web/src/store/modules/faultLevel.ts @@ -0,0 +1,34 @@ +import {defineStore} from 'pinia'; // 定义容器名 +import {FaultLevelStateType} from '../typeManagement'; +import {faultLevelAPI} from 'api/surveillance/faultRule/request.ts'; +import storeName from 'store/storeName.ts'; // 容器名 +import SurveillanceStaticeData from 'staticData/surveillance/index.ts'; + +const faultLevelStore = defineStore(storeName.faultLevelData, { + state: (): FaultLevelStateType => { + return { + loading: true, + faultLevelData: [] + } + }, + + actions: { + + getFaultLevel () { + faultLevelAPI({}) + .then(({data}: {data: {result: string[]}}) => { + if (data?.result?.length) { + this.faultLevelData = data.result; + return; + } + return Promise.reject(); + }) + .catch(() => { + this.faultLevelData = SurveillanceStaticeData.faultLevel; + }) + .finally(() => this.loading = false); + } + } +}); + +export default faultLevelStore; diff --git a/bmp-operation-web/src/store/modules/faultSpec.ts b/bmp-operation-web/src/store/modules/faultSpec.ts new file mode 100644 index 0000000..24b3073 --- /dev/null +++ b/bmp-operation-web/src/store/modules/faultSpec.ts @@ -0,0 +1,34 @@ +import {defineStore} from 'pinia'; // 定义容器名 +import {FaultSpecStateType} from '../typeManagement'; +import {faultSpecAPI} from 'api/surveillance/faultRule/request.ts'; +import storeName from 'store/storeName.ts'; // 容器名 +import SurveillanceStaticeData from 'staticData/surveillance/index.ts'; + +const faultSpecStore = defineStore(storeName.faultSpecData, { + state: (): FaultSpecStateType => { + return { + loading: true, + faultSpecData: [] + } + }, + + actions: { + + getFaultSpec () { + faultSpecAPI({}) + .then(({data}: {data: {result: string[]}}) => { + if (data?.result?.length) { + this.faultSpecData = data.result; + return; + } + return Promise.reject(); + }) + .catch(() => { + this.faultSpecData = SurveillanceStaticeData.faultyAccessories; + }) + .finally(() => this.loading = false); + } + } +}); + +export default faultSpecStore; \ No newline at end of file diff --git a/bmp-operation-web/src/store/modules/filterEmpty.ts b/bmp-operation-web/src/store/modules/filterEmpty.ts new file mode 100644 index 0000000..6ddd0d0 --- /dev/null +++ b/bmp-operation-web/src/store/modules/filterEmpty.ts @@ -0,0 +1,60 @@ +import {defineStore} from 'pinia'; // 定义容器名 +import {OsStoreType} from '../typeManagement'; +import {CurrencyType} from '@utils/publicType'; +import storeName from 'store/storeName.ts'; + +// defineStore定义容器 +// 参数1:是对仓库的命名,名称必须具备唯一性; +// 参数2:配置的选项对象,即state、getters、actions +// 其中state的写法必须是函数,为了避免在服务端交叉请求导致的状态数据污染,而且必须是箭头函数,为了更好的TS类型推导 +const filterEmptyStore = defineStore(storeName.filterEmpty, { + state: () => { + return {} + }, + actions: { + /** + * 过滤参数-filter-筛选 + * @param {Object} filter 筛选的参数 + * @param {Object} ossStore 筛选的值 + * @param {Object} reactiveArr.filterParams 需要筛选的参数 + * @param {Object} filterParams 当前筛选的参数 + * @return {Function} reoslve() 成功的返回 + */ + filterParams( + filter: {[x: string]: number[]}, + ossStore: Record, + reactiveArr: {filterParams: CurrencyType}, + filterParams: CurrencyType + ) { + if (!Object.keys(filter).length) return Promise.reject(); + const tag: string[] = []; + for (const key in filter) { + if (key === filterParams[key]) { + for (const item of filter[key]) { + tag.push(ossStore[filterParams[key]][item - 1].filterParams); + } + // 找到匹配的对应参数,如果多选,数组转字符串,用逗号分隔 + reactiveArr.filterParams[filterParams[key]] = tag.join(','); + } + } + this.deleteEmtpyData(reactiveArr.filterParams); + return Promise.resolve(reactiveArr); + }, + + /** + * 删除空数据 + * @param {Object} params 当前操作的数据 + */ + deleteEmtpyData(params: CurrencyType = {}): void { + Object.keys(params).forEach((item: string) => { + if (!params[item]) { + Reflect.deleteProperty(params, item); + return; + } + return params; + }); + } + } +}); + +export default filterEmptyStore; diff --git a/bmp-operation-web/src/store/modules/idc.ts b/bmp-operation-web/src/store/modules/idc.ts new file mode 100644 index 0000000..ad44f01 --- /dev/null +++ b/bmp-operation-web/src/store/modules/idc.ts @@ -0,0 +1,66 @@ +import {defineStore} from 'pinia'; // 定义容器名 +import {locationItem} from 'utils/publicClass.ts'; +import {CurrencyType} from '@utils/publicType'; +import storeName from 'store/storeName.ts'; // 容器名 +import {IdcStoreStateType} from '../typeManagement'; + +const idcStore = defineStore(storeName.idcData, { + state: (): IdcStoreStateType => { + return { + loading: true, + idcData: [], + idcDataNoOpt: [] + } + }, + + actions: { + async getIdc (apiReq: Function) { + try { + const idcApi = await apiReq({isAll: '1'}); + if (idcApi?.data?.result?.idcs?.length) { + const {idcs} : {idcs: CurrencyType[]} = idcApi.data.result; + const newIdcs = idcs.map((item: CurrencyType) => { + return { + ...item, + newIdcName: this.setName(locationItem.getLocationItem, item) + }; + }) + this.idcData = newIdcs; + return; + } + throw new Error(''); + } + catch { + this.idcData = []; + } + finally { + this.loading = false; + } + }, + + setName (name: string, item: CurrencyType) { + const keyName: Map = new Map([ + ['zh_CN', item.name], + ['en_US', item.nameEn] + ]); + return keyName.get(name); + }, + + async idcListNoOpt (apiReq: Function) { + try { + const idcApi = await apiReq({isAll: '1'}); + if (idcApi?.data?.result?.idcs?.length) { + const {idcs}: {idcs: CurrencyType[]} = idcApi.data.result; + this.idcDataNoOpt = idcs; + return; + } + throw new Error(''); + } + catch { + this.idcDataNoOpt = []; + } + } + } +}); + +export default idcStore; \ No newline at end of file diff --git a/bmp-operation-web/src/store/modules/imagesData.ts b/bmp-operation-web/src/store/modules/imagesData.ts new file mode 100644 index 0000000..474631b --- /dev/null +++ b/bmp-operation-web/src/store/modules/imagesData.ts @@ -0,0 +1,45 @@ +import {defineStore} from 'pinia'; // 定义容器名 +import {imagesAPI} from 'api/image/request.ts'; +import {CurrencyType, CurrencyType2, PaginationType} from '@utils/publicType'; +import storeName from 'store/storeName.ts'; // 容器名 + +const imagesStore = defineStore(storeName.imagesData, { + state: () => { + return { + loginUserName: '', + email: '' + } + }, + actions: { + /** + * 获取镜像数据 + * @param {Object} params 镜像参数 + * @param {Object} reactiveArr.filterParams 镜像搜索参数 + * @return {Function} resolve, promise.resolve()方法 + * @return {Function} reject promise.reject()方法 + */ + getImage( + params: PaginationType | PaginationType & CurrencyType, + reactiveArr: { + filterParams: CurrencyType; + } + ) { + return imagesAPI( + { + ...params, + ...reactiveArr.filterParams + } + ).then(({data}: {data: {result: {images: CurrencyType2[]}}}) => { + if (data?.result?.images?.length) { + return Promise.resolve(data.result); + } + return Promise.resolve([]); + }) + .catch(({message}: {message: string;}) => { + return Promise.reject(message); + }); + }, + } +}); + +export default imagesStore; \ No newline at end of file diff --git a/bmp-operation-web/src/store/modules/loginInfo.ts b/bmp-operation-web/src/store/modules/loginInfo.ts new file mode 100644 index 0000000..8621a18 --- /dev/null +++ b/bmp-operation-web/src/store/modules/loginInfo.ts @@ -0,0 +1,30 @@ +import {defineStore} from 'pinia'; // 定义容器名 +import storeName from 'store/storeName.ts'; // 容器名 + +// defineStore定义容器 +// 参数1:是对仓库的命名,名称必须具备唯一性; +// 参数2:配置的选项对象,即state、getters、actions +// 其中state的写法必须是函数,为了避免在服务端交叉请求导致的状态数据污染,而且必须是箭头函数,为了更好的TS类型推导 +const loginInfoStore = defineStore(storeName.login, { + state: (): { + loginUserName: string; + email: string; + } => { + return { + loginUserName: '', + email: '' + } + }, + // 开启数据缓存-数据持久化 + persist: { + enabled: true, + strategies: [ + { + storage: localStorage, + paths: ['loginUserName', 'email'] + } + ] + } +}); + +export default loginInfoStore; \ No newline at end of file diff --git a/bmp-operation-web/src/store/modules/modeForm.ts b/bmp-operation-web/src/store/modules/modeForm.ts new file mode 100644 index 0000000..06eed07 --- /dev/null +++ b/bmp-operation-web/src/store/modules/modeForm.ts @@ -0,0 +1,184 @@ +import {defineStore} from 'pinia'; // 定义容器名 +// import {filterData} from 'utils/index.ts'; // 过滤重复数据 +import {language} from 'utils/publicClass.ts'; +import {getFilterListAPI} from 'api/model/request.ts'; // raids接口 filter接口 +import {CpuDataType, MemDataType} from '@utils/publicType'; +import {StateType, FormSubmitType, SetCpuMemFormSubmitType} from '../typeManagement'; // state类型 表单类型 +import storeName from 'store/storeName.ts'; // 容器名 + +/** + * 表单验证 +*/ +class FormCheck { + /** + * 输入项/选择项为空时 + * @param {string} str 提示项 + * @param {string} trigger 判断时机-change/blur + */ + inputSelectEmtpy = (str = '', trigger = 'change', required = true): FormSubmitType[] => { + return [{required, message: str, trigger}]; + }; +}; +const formCheck: FormCheck = new FormCheck(); + +// defineStore定义容器 +// 参数1:是对仓库的命名,名称必须具备唯一性; +// 参数2:配置的选项对象,即state、getters、actions +// 其中state的写法必须是函数,为了避免在服务端交叉请求导致的状态数据污染,而且必须是箭头函数,为了更好的TS类型推导 +const modeFormStore = defineStore(storeName.modeForm, { + state: (): StateType => { + return { + raidsData: [], // raids数据 + data: { + radioBtn: [ // 机型类型 + language.t('modelForm.radioBtn.computed'), + language.t('modelForm.radioBtn.storage'), + language.t('modelForm.radioBtn.GPU'), + language.t('modelForm.radioBtn.other') + ], + modelCPUBtn: [ // CPU规格 + language.t('modelForm.specificationsType.presetSpecifications'), + language.t('modelForm.specificationsType.otherSpecifications') + ], + storageData: [ // 内存规格 + language.t('modelForm.specificationsType.presetSpecifications'), + language.t('modelForm.specificationsType.otherSpecifications') + ] + }, + ruleForm: { + bootMode: [], + raidCan: '', + templateName: '', + deviceTypeName: '', + name: '', // 机型名称 + architecture: 'x86_64', // 体系架构 + deviceType: '', // 机型规格 + description: '', // 描述 + modelCPU: language.t('modelForm.specificationsType.presetSpecifications'), // 机型CPU + cpuInfo: '', // CPU + cpuManufacturer: '', // 处理器厂商 + cpuModel: '', // 型号 + cpuCores: 1, // 物理核数 + cpuFrequency: '', // 主频 + cpuAmount: 1, // cpu-数量 + modelStorage: language.t('modelForm.specificationsType.presetSpecifications'), // 机型内存 + memInfo: '', // 内存 + memType: '', // 接口 + memFrequency: '', // 主频MHz + memSize: '', // 容量(GB) + memAmount: 1, // 数量 + volumeManager: [], + nicRate: '', // 网卡速度(GE) + nicAmount: 1, // 网口数量(个) + interfaceMode: '', // 网络设置 + gpuManufacturer: '', // GPU(品牌) + gpuModel: '', // GPU(型号) + gpuAmount: 0, // GPU数量(个) + height: '', // 高度(U) + cpuData: [], // cpu数据 + memData: [] // 内存数据 + }, + rules: { + architecture: formCheck.inputSelectEmtpy(), // 体系架构 + cpuInfo: formCheck.inputSelectEmtpy(language.t('modelForm.emptyTip.cpu')), // CPU + cpuManufacturer: formCheck.inputSelectEmtpy(language.t('modelForm.emptyTip.processorManufacturer')), // 处理器厂商 + memInfo: formCheck.inputSelectEmtpy(language.t('modelForm.emptyTip.storage')), // 内存 + memType: formCheck.inputSelectEmtpy(language.t('modelForm.emptyTip.interface')), // 接口 + memFrequency: formCheck.inputSelectEmtpy(language.t('modelForm.emptyTip.dominantFrequencyMHz')), // 主频(MHz) + memSize: formCheck.inputSelectEmtpy(language.t('modelForm.emptyTip.capacity')), // 容量(GB) + nicRate: formCheck.inputSelectEmtpy(language.t('modelForm.emptyTip.networkSpeed')), // 网卡速度(GE) + interfaceMode: formCheck.inputSelectEmtpy(language.t('modelForm.emptyTip.networkSettings')), // 网络设置 + gpuManufacturer: formCheck.inputSelectEmtpy(language.t('modelForm.emptyTip.gpuBrand'), 'change', false), // GPU(品牌) + gpuModel: formCheck.inputSelectEmtpy(language.t('modelForm.emptyTip.gpuModel'), 'change', false), // GPU(型号) + height: formCheck.inputSelectEmtpy(language.t('modelForm.emptyTip.heightU')) // 高度(U) + } + } + }, + // 类似computed + getters: { + // 获取raids + getRaids (state) { + return state.raidsData; + } + }, + actions: { + + initModelType (deviceSeries: string) { + const modelType: any = { + 'computer': () => language.t('modelForm.radioBtn.computed'), + 'storage': () => language.t('modelForm.radioBtn.storage'), + 'gpu': () => language.t('modelForm.radioBtn.GPU'), + 'other': () => language.t('modelForm.radioBtn.other') + }; + if (modelType[deviceSeries]) { + return modelType[deviceSeries](); + } + return modelType['computer'](); + }, + + /** + * 获取预置数据 + * @return {Function} Promise.resolve(data.result); resolve成功的返回 + */ + getCommonData () { + return getFilterListAPI() + .then(({data} : {data: {result: {cpuSpec: CpuDataType[]; memSpec: MemDataType[]; bootMode: string[]}}}) => { + if (data?.result?.cpuSpec) { + this.ruleForm.cpuData = data.result.cpuSpec; + this.ruleForm.memData = data.result.memSpec; + this.ruleForm.bootMode = data.result.bootMode; + return Promise.resolve(data.result); + } + // return Promise.reject('') + }) + // .catch(({message}: {message: string;}) => { + // message && msgTip.error(message); + // }); + }, + + /** + * 设置机型类型 + */ + setModelType (type: string): string { + const obj = new Map([ + [language.t('modelForm.radioBtn.computed'), 'computer'], + [language.t('modelForm.radioBtn.storage'), 'storage'], + [language.t('modelForm.radioBtn.GPU'), 'gpu'], + ]); + return obj.get(type)?? 'other'; + }, + + setCpuMemData (cpuBol: boolean, memBol: boolean, formSubmit: SetCpuMemFormSubmitType) { + const memData: string[] = ['memType', 'memFrequency', 'memSize', 'memAmount']; + const cpuData: string[] = ['cpuAmount', 'cpuCores', 'cpuFrequency', 'cpuManufacturer', 'cpuModel']; + const cpuMemData = [ + [ + (status1: boolean, _: boolean) => !(status1), + () => { + const val = formSubmit?.cpuData?.find((item: {label: string}) => item.label === formSubmit.cpuInfo)?.info || []; + for(const key of cpuData) { + (formSubmit[`${key}` as keyof typeof formSubmit]) = (val[`${key}` as keyof typeof val]); + } + } + ], + [ + (_: boolean, status2: boolean) => !(status2), + () => { + const mem = formSubmit?.memData?.find((item: {label: string}) => item.label === formSubmit.memInfo)?.info || []; + for(const key of memData) { + (formSubmit[`${key}` as keyof typeof formSubmit]) = (mem[`${key}` as keyof typeof mem]); + } + } + ] + ]; + for (const key of cpuMemData) { + if (key[0](cpuBol, memBol)) { + key[1](cpuBol, memBol); + } + } + return Promise.resolve(); + } + } +}); + +export default modeFormStore; diff --git a/bmp-operation-web/src/store/modules/navigationBar.ts b/bmp-operation-web/src/store/modules/navigationBar.ts new file mode 100644 index 0000000..4affd58 --- /dev/null +++ b/bmp-operation-web/src/store/modules/navigationBar.ts @@ -0,0 +1,44 @@ +import {defineStore} from 'pinia'; // 定义容器名 +import storeName from 'store/storeName.ts'; // 容器名 +import { language } from 'utils/publicClass.ts'; +// defineStore定义容器 +// 参数1:是对仓库的命名,名称必须具备唯一性; +// 参数2:配置的选项对象,即state、getters、actions +// 其中state的写法必须是函数,为了避免在服务端交叉请求导致的状态数据污染,而且必须是箭头函数,为了更好的TS类型推导 +const navigationBarStore = defineStore(storeName.navigationBar, { + state: (): { + hasNavigationBar: boolean; + } => { + return { + hasNavigationBar: true + } + }, + + actions: { + + /** + * 侧边栏展开收起点击事件 + * @return {boolean} this.store.hasNavigationBar 状态取反 + */ + hasNavigationBarClick(): boolean { + return this.hasNavigationBar = !this.hasNavigationBar; + }, + + tootlipDisabled(locationItem: {getLocationItem: string}, title: string) { + if (!this.hasNavigationBar) return true; + const tooltipData = [ + language.t('navigationBar.children.hardwareAlarmStatus'), + language.t('navigationBar.children.myMessages'), + language.t('navigationBar.children.messageSet'), + language.t('navigationBar.children.resourceEcharts'), + language.t('navigationBar.children.historyAlarmInfo'), + language.t('navigationBar.children.allAlarmRules'), + language.t('securitySettings.header.securitySettings'), + language.t('apiKey.header.apiKey') + ] + return !(locationItem.getLocationItem === 'en_US' && tooltipData.indexOf(title) > -1) + } + } +}); + +export default navigationBarStore; diff --git a/bmp-operation-web/src/store/modules/ossData.ts b/bmp-operation-web/src/store/modules/ossData.ts new file mode 100644 index 0000000..2777a8f --- /dev/null +++ b/bmp-operation-web/src/store/modules/ossData.ts @@ -0,0 +1,174 @@ +import {defineStore} from 'pinia'; // 定义容器名 +import {getOssAPI} from 'api/public/request.ts'; // oss接口 +import {modelListAPI} from 'api/model/request.ts'; +import messageApiCount from 'api/message/request.ts'; +import {filterData} from 'utils/index.ts'; // 过滤重复数据 +import {CurrencyType} from '@utils/publicType'; +import {OsStoreType, OssStateType} from '../typeManagement'; +import DeviceStaticData from 'staticData/device/index.ts'; // 机型类型、管理状态 +import ModelStaticData from 'staticData/model/index.ts'; +import ImageStaticData from 'staticData/image/index.ts'; +import MessageStaticData from 'staticData/message/index.ts'; +import AllAlarmRulesStatic from 'staticData/inBandMonitoring/allAlarmRules/index.ts' +import storeName from 'store/storeName.ts'; // 容器名 +import {auditLogsTypesAPI} from 'api/device/request.ts'; +import { pinyin } from 'pinyin-pro'; + +const ossDataStore = defineStore(storeName.ossData, { + state: (): OssStateType => { + return { + osType: [], + architecture: [], + messageType: [], + customFilterList: [], + source: ImageStaticData.source, + manageStatus: DeviceStaticData.manageMentStatus, + deviceSeries: ModelStaticData.modelTypeData, + collectStatus: DeviceStaticData.collectStatusData, + operation: [], + deviceTypeId: [], + result: DeviceStaticData.operationalFeedbackData, + status: AllAlarmRulesStatic.allAlarmRulesStatusData + } + }, + + actions: { + + getMessagesType() { + messageApiCount.messageTypesAPI({}) + .then(({data}: {data: {result: {[x: string]: string}}}) => { + // @ts-ignore + const val: string[] = Object.keys(data.result).flat(1); + this.messageType = val?.length ? val.map((item, index) => { + return { + text: item, + filterParams: item, + value: index + 1 + } + }) : MessageStaticData.messageType; + const newData = Object.values(data.result).flat(1); + this.customFilterList = newData.map(item => { + return { + label: item, + yin: pinyin(item, {toneType: 'none'}).trim().replace(/\s/g, ""), + value: item, + checkboxStatus: false + } + }); + }) + }, + + getModelList() { + modelListAPI({ + isAll: '1' + }) + .then(({data}: any) => { + if (data?.result?.deviceTypes?.length) { + this.deviceTypeId = data.result.deviceTypes.map((item: {name: string; deviceTypeId: string;}, index: number) => { + return { + text: item.name, + filterParams: item.deviceTypeId, + value: index + 1 + } + }) + return; + } + return Promise.reject(); + }) + .catch(() => { + this.deviceTypeId = []; + }); + }, + + getModelListRes() { + return new Promise((resolve, reject) => { + return modelListAPI({isAll: '1'}) + .then(({data}: any) => { + if (data?.result?.deviceTypes?.length) { + const newData = data.result.deviceTypes.map((item: {name: string; deviceTypeId: string;}, index: number) => { + return { + text: item.name, + filterParams: item.deviceTypeId, + value: index + 1 + } + }); + return resolve(newData); + } + return Promise.reject(); + }) + .catch(() => { + return reject([]); + }) + }) + }, + + getAuditLogsTypes() { + // return new Promise((resolve, reject) => { + return auditLogsTypesAPI({}) + .then(({data}: any) => { + if (data?.result?.length) { + this.operation = data.result.map((item: {name: string; operation: string;}, index: number) => { + return { + filterParams: item.operation, + text: item.name, + value: index + 1 + } + }) + return; + // return resolve(data.result); + } + return Promise.reject(); + }) + .catch(() => { + this.operation = [] + // return reject([]); + }) + // }) + }, + + /** + * 获取oss数据 + * @return {Function} xxx 返回一个函数 + */ + getOssData(param = {}) { + const params = Object.keys(param).length ? param : { + isAll: '1' + }; + return getOssAPI ( + { + ...params + } + ) + .then(({data} : {data: {result: {oss: OsStoreType}}}) => { + if (data?.result?.oss) { + this.osType = this.processingData(data, 'osType'); + this.architecture = this.processingData(data, 'architecture'); + return; + } + return Promise.reject(); + }) + .catch(() => { + this.osType = []; + this.architecture = []; + }); + }, + + /** + * 处理数据 + * @param {Array} oss oss 数据 + * @param {string} type filter的参数名 + */ + processingData(data: {result: {oss: OsStoreType}}, type: string) { + return filterData(data.result.oss, type).map((item: CurrencyType, index: number) => { + return { + ...item, + text: item[type], + value: index + 1, + filterParams: item[type] + }; + }); + } + } +}); + +export default ossDataStore; diff --git a/bmp-operation-web/src/store/modules/progress.ts b/bmp-operation-web/src/store/modules/progress.ts new file mode 100644 index 0000000..46f738c --- /dev/null +++ b/bmp-operation-web/src/store/modules/progress.ts @@ -0,0 +1,16 @@ +import {defineStore} from 'pinia'; // 定义容器名 +import storeName from 'store/storeName.ts'; // 容器名 + +// defineStore定义容器 +// 参数1:是对仓库的命名,名称必须具备唯一性; +// 参数2:配置的选项对象,即state、getters、actions +// 其中state的写法必须是函数,为了避免在服务端交叉请求导致的状态数据污染,而且必须是箭头函数,为了更好的TS类型推导 +const progressInfoStore = defineStore(storeName.progress, { + state: (): {progressNum: number;} => { + return { + progressNum: 0 + } + } +}); + +export default progressInfoStore; \ No newline at end of file diff --git a/bmp-operation-web/src/store/modules/systemPartition.ts b/bmp-operation-web/src/store/modules/systemPartition.ts new file mode 100644 index 0000000..9d3d4aa --- /dev/null +++ b/bmp-operation-web/src/store/modules/systemPartition.ts @@ -0,0 +1,69 @@ +import {defineStore} from 'pinia'; // 定义容器名 +import {deepCopy} from 'utils/index.ts'; +import storeName from 'store/storeName.ts'; // 容器名 +import {SystemPartitionType} from '@utils/publicType'; +import {language} from 'utils/publicClass.ts'; + +const sysPartitionStore = defineStore(storeName.sysPartition, { + state: () => { + return {} + }, + + actions: { + /** + * 自定义分区模块数据展示 + * @param {Array} data 需要处理的数据 + * @return {Array} defaultPartitions 处理完成的数据 + */ + systemPartitionData (data: string, hasLabel: boolean = true) { + // 声明一个新数组 + let defaultPartitions: {size: number; format: string; point: string;}[] = []; + // try - catch捕获异常 + try { + // 正常情况下,深拷贝数据,把数据变为可遍历的 + defaultPartitions = deepCopy(JSON.parse(data)); + // 遍历数据 + defaultPartitions.map((item: {size: number;}) => { + // size 处理 + item.size = this.setSize(item.size); + }); + // 处理分区模块展示 + return defaultPartitions.reduce((pre: string, cur: {size: number; point: string; format: string;}) => { + if (hasLabel) return `${pre}

${cur.point}:${cur.size},${cur.format};

`; + return `${pre}${cur.point}:${cur.size},${cur.format};`; + }, ''); + } + catch { + if (hasLabel) return defaultPartitions = []; + return '--'; + } + }, + + systemPartitionHtml (val: SystemPartitionType[]) { + const data: SystemPartitionType[] = deepCopy(val); + data.map((item: SystemPartitionType) => { + // size 处理 + item.size = this.setSize(item.size); + }); + return data.reduce((pre: string, cur: SystemPartitionType) => { + return `${pre}${cur.point}:${cur.size},${cur.format};`; + }, ''); + }, + + setSize (size: number) { + const sizeMap = new Map([ + [999999999, language.t('size.num')] + ]); + return sizeMap.get(size)?? `${size / 1024}GiB`; + }, + + setSizeNoUnit (size: number) { + const sizeMap = new Map([ + [999999999, language.t('size.num')] + ]); + return sizeMap.get(size)?? size; + } + } +}); + +export default sysPartitionStore; diff --git a/bmp-operation-web/src/store/modules/userPurview.ts b/bmp-operation-web/src/store/modules/userPurview.ts new file mode 100644 index 0000000..55ddd11 --- /dev/null +++ b/bmp-operation-web/src/store/modules/userPurview.ts @@ -0,0 +1,75 @@ +import {defineStore} from 'pinia'; // 定义容器名 +import {encrypt} from 'utils/index.ts'; +import {userInfoAPI} from 'api/userCenter/request.ts'; +import storName from 'store/storeName.ts'; // 容器名 +import {CurrencyType} from '@utils/publicType'; +import {locationItem} from 'utils/publicClass.ts'; +// defineStore定义容器 +// 参数1:是对仓库的命名,名称必须具备唯一性; +// 参数2:配置的选项对象,即state、getters、actions +// 其中state的写法必须是函数,为了避免在服务端交叉请求导致的状态数据污染,而且必须是箭头函数,为了更好的TS类型推导 +const userPurviewStore = defineStore(storName.userInfo, { + state: (): {userPurview: string;} => { + return { + userPurview: '', + } + }, + + actions: { + + /** + * 获取用户权限 + */ + getUserPurview (api: {userPurviewAPI: Function}) { + return new Promise(async (resolve, reject) => { + try { + const userPurviewApi = await api.userPurviewAPI(); + if (userPurviewApi?.data?.result?.role?.roleId) { + this.userPurview = userPurviewApi.data.result.role.roleId; + localStorage.setItem('userPurview', encrypt(this.userPurview)) + return resolve(userPurviewApi.data.result.role.roleId); + } + throw new Error(''); + } + catch { + this.userPurview = ''; + localStorage.setItem('userPurview', encrypt(this.userPurview)) + return reject(); + } + finally { + // this.userInfo(); + } + }) + }, + + userInfo() { + userInfoAPI({}) + .then(({data} : {data: {result: CurrencyType}}) => { + if (data?.result && Object.keys(data.result).length) { + const email: string = data?.result?.email?? ''; + localStorage.setItem('email', window.btoa(email)); + const userName = window.btoa(data.result.userName); + localStorage.setItem('userName', userName); + locationItem.cookie.set('X-Jdcloud-Language', data.result.language); + } + }) + .catch(() => { + throw new Error('异常'); + }) + }, + + promiseUserInfo() { + return new Promise((resolve, reject) => { + return userInfoAPI({}) + .then(({data}: {data: {result: CurrencyType}}) => { + return resolve(data.result); + }) + .catch(() => { + return reject('异常'); + }) + }) + } + } +}); + +export default userPurviewStore; diff --git a/bmp-operation-web/src/store/storeName.ts b/bmp-operation-web/src/store/storeName.ts new file mode 100644 index 0000000..c814183 --- /dev/null +++ b/bmp-operation-web/src/store/storeName.ts @@ -0,0 +1,20 @@ +import {CurrencyType} from "@utils/publicType"; + +const storName: CurrencyType = { + login: 'loginInfo', + progress: 'progressInfo', + customList: 'customInfo', + sysPartition: 'systemPartitionInfo', + idcData: 'idcData', + imagesData: 'imagesInfo', + filterEmpty: 'filterEmpty', + navigationBar: 'navigationBar', + ossData: 'ossDataInfo', + modeForm: 'modeForm', + userInfo: 'userPurview', + faultLevelData: 'faultLevelData', + deviceDetailErrorTipOpt: 'deviceDetailErrorTipOpt', + faultSpecData: 'faultSpecData' +}; + +export default storName; diff --git a/bmp-operation-web/src/store/typeManagement.ts b/bmp-operation-web/src/store/typeManagement.ts new file mode 100644 index 0000000..28e9613 --- /dev/null +++ b/bmp-operation-web/src/store/typeManagement.ts @@ -0,0 +1,113 @@ +import {CpuDataType, CurrencyType, MemDataType, CurrencyStatusType, VerifyRulesType, CurrencyType2, PublicType6, OsStoreType} from '@utils/publicType'; + +// checkboxArr ts +type CheckListArrType = PublicType6[] & Omit[] & {disabled: boolean}[]; + +/** + * 自定义列表-数据信息-类 +*/ +type CustomDataInfoType = { + pageKey: string; + data: Record; +}; + +interface IndexStateType { + customDataInfo: CustomDataInfoType[]; +}; + +interface FormSubmitType extends VerifyRulesType {}; + +interface StateType { + data: { + radioBtn: string[]; + modelCPUBtn: string[]; + storageData: string[]; + }; + raidsData: []; + ruleForm: CurrencyType2 | {[x: string]: [] | {}}; + rules: {}; +}; + +/* modelForm.ts */ + +interface SetCpuMemFormSubmitType { + cpuData: {label: string; info: CpuDataType['info']}[]; + cpuInfo: string; + memInfo: string; + memData: {label: string; info: MemDataType['info']}[]; +}; + +interface SetFromType { + [x: string]: string | number; + modelType: string; + raidId: string; + sysRaid: never; + deviceSeries: string; + systemVolumeSize: number; + dataVolumeSize: number; +}; + +type SysRaidType = {join(arg0: string): never;}; + +type ValType = {value: boolean}; + +/** + * state ts +*/ +interface OssStateType { + osType: OsStoreType[]; + messageType: OsStoreType[]; + architecture: OsStoreType[]; + customFilterList: {label: string; value: string; checkboxStatus: boolean}[]; + source: OsStoreType[]; + manageStatus: OsStoreType[]; + collectStatus: OsStoreType[]; + operation: OsStoreType[]; + deviceSeries: OsStoreType[]; + deviceTypeId: OsStoreType[]; + result: OsStoreType[]; + status: OsStoreType[]; +}; + +/** + * idcStore +*/ +interface IdcStoreStateType { + idcData: CurrencyType[] | { newIdcName: string | undefined;}[]; + loading: boolean; + idcDataNoOpt: CurrencyType[]; +}; + +/** + * faultLevelStore +*/ +interface FaultLevelStateType { + loading: boolean; + faultLevelData: string[]; +}; + +/** + * faultSpecStore +*/ +interface FaultSpecStateType { + loading: boolean; + faultSpecData: string[]; +}; + + +export { + ValType, + StateType, + SetFromType, + SysRaidType, + OsStoreType, + OssStateType, + IndexStateType, + FormSubmitType, + CheckListArrType, + IdcStoreStateType, + CurrencyStatusType, + FaultSpecStateType, + FaultLevelStateType, + SetCpuMemFormSubmitType +}; diff --git a/bmp-operation-web/src/tests/jestTestType.ts b/bmp-operation-web/src/tests/jestTestType.ts new file mode 100644 index 0000000..82004c4 --- /dev/null +++ b/bmp-operation-web/src/tests/jestTestType.ts @@ -0,0 +1,21 @@ +export interface AggregateType { + DeleteType: { + Params: { + name: string; + age: number; + sex?: string | number; + } + }, + DeepCopyType: { + Data: { + name: number; + } + }, + OperateType: { + PropsInfo: { + title: string; + diaLog: boolean; + instanceInfo: string; + } + } +}; diff --git a/bmp-operation-web/src/tests/unit/components.spec.ts b/bmp-operation-web/src/tests/unit/components.spec.ts new file mode 100644 index 0000000..60c3759 --- /dev/null +++ b/bmp-operation-web/src/tests/unit/components.spec.ts @@ -0,0 +1,155 @@ + +import 'polyfill-object.fromentries'; +import {mount, shallowMount, DOMWrapper} from '@vue/test-utils'; // 对 Vue 组件进行测试 +import ElementPlus from 'element-plus'; +import i18n from '@/lib/i18n/index.ts'; // 国际化 +import UiButton from '@/components/Ui/Button/Button.vue'; // button组件 +import UpDownFrame from '@/components/DiaLog/DeviceOperations/UpDownFrame/UpDownFrame.vue'; // 上架、下架、删除设备操作 + +/** + * 插槽信息 +*/ +const Layout = { + template: ` +
+
+ +
+ +
+ `, + // data() { + // return { + // item: { + // sn: 'test-sn1', + // cabinet: 'test-code', + // uPosition: 'test-u', + // iloIp: 'test-ip', + // privateIpv4: 'test-ipv4' + // } + // } + // } +}; + +describe('test-Button', () => { + test('test-UiButton', () => { + const btnText = '按钮'; + const wrapper = mount(UiButton, { + slots: { + default: `${btnText}`, + } + }); + // expect 让你可以使用不同的“匹配器”去验证不同类型的东西。 + expect(wrapper.find('button').text()).toBe('按钮'); + }) +}), + + +describe('test-UpDownFrame', () => { + it('test-header', async () => { + const wrapper = mount(Layout, { + global: { + plugins: [ElementPlus, i18n] + }, + slots: { + // 会自动匹配默认插槽 + default: '
', + title: ` +

+ + + ${i18n.global.t('upDownFrame.titleTip.up')} +

+ +
+ + + +
+ ` + } + }); + // 测试是否含有span + expect(wrapper.find('.title').html()).toContain('span'); + // 测试内容 + expect(wrapper.find('.title-text').text()).toBe('Mount'); + // 获取触发事件的元素,获取到dom + const closeClick: DOMWrapper = wrapper.find('.close-icon'); + // 点击事件,然后使用trigger去触发想要测试的事件,在此使用await 是为了确保在断言之前 你的dom操作会执行完成 + await closeClick.trigger('click'); + // 点击事件是否存在 + expect(wrapper.emitted().click).toBeTruthy(); + // expect(wrapper.element).toMatchSnapshot(); // 快照渲染 + }), + + // 测试 + it('test-count', async () => { + const wrapper = shallowMount(UpDownFrame, { + props: { + diaLog: true, // 蒙层 + title: '上架', // 标题 + deleteStatus: true + }, + global: { + plugins: [ElementPlus, i18n] + }, + slots: { + default: `
` + } + }); + // 判断类是否存在 + expect(wrapper.classes('up-down-frame')).toBe(true); + // 检查类名为“count-title-tip”的元素是否为渲染成功 + expect(wrapper.find('.count-title-tip').exists()).toBe(true); + expect(wrapper.find('.count-title-tip').text()).toContain('After the server'); + expect(wrapper.find('.header-title').html()).toContain('span') + // 检查类名为“up-down-frame-count-header-title”的元素是否为渲染成功 + expect(wrapper.find('.header-title').exists()).toBe(true); + // 检查是否包含...内容 + expect(wrapper.find('.header-title').text()).toContain('Please confirm whether'); + const {vm} = wrapper; + await vm.$nextTick(); // 同步获取dom元素渲染 + // expect(wrapper.element).toMatchSnapshot(); // 快照渲染 + }), + + // 测试 + it('click & footer', async () => { + const wrapper = mount(Layout, { + global: { + plugins: [ElementPlus, i18n] + }, + slots: { + // 会自动匹配默认插槽 + default: '
', + footer: ` + + ${i18n.global.t('upDownFrame.btn.cancel')} + + ` + } + }); + // 获取触发事件的元素,获取到dom + const firstNodeContentWrapper: DOMWrapper = wrapper.find('.up-down-frame-footer-cancel-btn'); + // 测试是否含有button组件 + expect(wrapper.find('.up-down-frame-footer').html()).toContain('button'); + // 点击事件,然后使用trigger去触发想要测试的事件,在此使用await 是为了确保在断言之前 你的dom操作会执行完成 + await firstNodeContentWrapper.trigger('click'); + expect(wrapper.emitted().click).toBeTruthy(); + expect(wrapper.find('.up-down-frame-footer-cancel-btn').text()).toBe('Cancel'); + // expect(wrapper.element).toMatchSnapshot(); // 快照渲染 + }) +}); diff --git a/bmp-operation-web/src/tests/unit/index.spec.ts b/bmp-operation-web/src/tests/unit/index.spec.ts new file mode 100644 index 0000000..fe6b3c9 --- /dev/null +++ b/bmp-operation-web/src/tests/unit/index.spec.ts @@ -0,0 +1,70 @@ +import {AggregateType} from '../jestTestType'; +import {deepCopy, filterData, addImageClass, hasShowPassword, conversionRgba, hasShowTooltip} from '@/utils/index.ts'; + +describe('test-method', () => { + // deepcopy + it('test-success-Array-deepcopy', () => { + const copyData1: AggregateType['DeepCopyType']['Data'][] = [{name: 1}, {name: 2}]; + const resultData1: AggregateType['DeepCopyType']['Data'][] = [{name: 1}]; + expect(deepCopy(copyData1)).not.toEqual(deepCopy(resultData1)); + }), + it('test-success-Object-deepcopy', () => { + const copyObj1 = {name: 1, info: {age: 2, sex: '男'}}; + expect(deepCopy(copyObj1)).not.toBe(deepCopy(copyObj1)); + expect(deepCopy(copyObj1)).toEqual(copyObj1); + }), + it ('test-null-deepcopy', () => { + expect(deepCopy(null)).toBeNull(); + }), + it ('test-undefined-deepcopy', () => { + expect(deepCopy(undefined)).toBeUndefined(); + }), + it('test-string-deepcopy', () => { + expect(deepCopy('string')).toMatch(/string/); + }) + + // filterData + it('test-success-filterData', () => { + const data = [{name: 1}, {name: 1}]; + expect(filterData(data, 'name')).toEqual(filterData(data)); + expect(filterData(data, 'name')).toEqual([{name: 1}]); + }), + it('test-[]-filterData', () => { + expect(filterData([])).toEqual([]); + }), + + // addImageClass + it('test-success-addImageClass', () => { + const data = [{name: 1}]; + const moreData = Array(10).fill(true); + expect(addImageClass(data, true)).toBe('img-show'); + expect(addImageClass(moreData, true)).toBe(''); + }), + it('test-[]-addImageClass', () => { + expect(addImageClass([], true)).toBe('img-show'); + expect(addImageClass([], false)).toBe('img-empty'); + }), + + // hasShowPassword + it('test-success-hasShowPassword', () => { + expect(hasShowPassword(false, '12312')).toBe('*****'); + expect(hasShowPassword(true, '132132')).toBe('132132'); + }), + it('test-empty-hasShowPassword', () => { + expect(hasShowPassword()).toBeUndefined(); + }), + + // conversionRgba + it('test-success-conversionRgba', () => { + expect(conversionRgba('#ffffff', '.6')).toBe('rgba(255, 255,255, .6)'); + }), + it('test-error-conversionRgba', () => { + expect(conversionRgba('#fff', '.6')).toBeNull(); + expect(conversionRgba('', '.6')).toBeNull(); + expect(conversionRgba('#ffffff', '')).toBe('rgba(255, 255,255, )') + expect(conversionRgba()).toBeNull(); + }), + it('test-hasShowTooltip', () => { + expect(hasShowTooltip(false, 'adasdsad')); + }) +}); diff --git a/bmp-operation-web/src/tests/unit/regular.spec.ts b/bmp-operation-web/src/tests/unit/regular.spec.ts new file mode 100644 index 0000000..86fda4a --- /dev/null +++ b/bmp-operation-web/src/tests/unit/regular.spec.ts @@ -0,0 +1,91 @@ +import { + phoneReg, // 中国大陆手机号正则 + emailReg, // 电子邮箱正则 + userNameReg, // 用户名正则 + aOmenPhoneReg, // 中国澳门手机号正则 + taiWanPhoneReg, // 中国台湾手机号正则 + hongKongPhoneReg // 中国香港手机号正则 +} from '@/utils/regular.ts' + +// 不匹配的手机号 +const noPhone: string = '132'; + +// 不匹配的手机号 +const noPhone1: string = '523823722212'; + +// describe 这个作用域里面的测试都是针对xxxx +describe('test-regular', () => { + // 中国大陆手机号测试 + it('test-phoneReg', () => { + // 符合规则的正则 + const correctPhone: string = '13212321231'; + // 匹配正则-toBe-精准匹配 + expect(phoneReg.test(correctPhone)).toBe(true); + // 不匹配 + expect(phoneReg.test(noPhone)).not.toBe(true); + // 大于或者等于 + expect(correctPhone.length).toBeGreaterThanOrEqual(11) + // 小于 + expect(noPhone.length).toBeLessThan(4); + }), + + // 中国香港手机号测试 + it('test-hongKongPhoneReg', () => { + const correctPhone: string = '51223222'; + // 匹配正则 + expect(hongKongPhoneReg.test(correctPhone)).toBe(true); + // 不匹配 + expect(hongKongPhoneReg.test(noPhone)).not.toBe(true); + // 小于或者等于 + expect(correctPhone.length).toBeLessThanOrEqual(8); + // 大于 + expect((noPhone1).length).toBeGreaterThan(8); + }), + + // 中国澳门手机号测试 + it('test-aOmenPhoneReg', () => { + const correctPhone: string = '62343234'; + // 匹配正则 + expect(aOmenPhoneReg.test(correctPhone)).toBe(true); + // 不匹配 + expect(aOmenPhoneReg.test(noPhone)).not.toBe(true); + // 小于或者等于 + expect(correctPhone.length).toBeLessThanOrEqual(8); + // 大于 + expect((noPhone1).length).toBeGreaterThan(8); + }), + + // 中国台湾手机号测试 + it('test-taiWanPhoneReg', () => { + // 符合规则的正则 + const correctPhone: string = '0923213212'; + // 匹配正则 + expect(taiWanPhoneReg.test(correctPhone)).toBe(true); + // 不匹配 + expect(taiWanPhoneReg.test(noPhone)).not.toBe(true); + // 大于或者等于 + expect(correctPhone.length).toBeGreaterThanOrEqual(10) + // 小于 + expect(noPhone.length).toBeLessThan(4); + }), + + // 邮箱测试 + it('test-emailReg', () => { + const correctEmail: string = 'testEmal@qq.com'; + const notEmail: string = '11.@qq.com'; + // 匹配正则 + expect(emailReg.test(correctEmail)).toBe(true); + // 不匹配 + expect(emailReg.test(notEmail)).not.toBe(true); + }) + + // 用户名测试 + it('test-userNameReg', () => { + const correctUserName: string = '1'; + const notUserName: string = '&'; + // 匹配正则 + expect(userNameReg.test(correctUserName)).toBe(true); + // 不匹配 + expect(userNameReg.test(notUserName)).not.toBe(true); + }) +}); diff --git a/bmp-operation-web/src/ui/Button/Button.vue b/bmp-operation-web/src/ui/Button/Button.vue new file mode 100644 index 0000000..4e4040c --- /dev/null +++ b/bmp-operation-web/src/ui/Button/Button.vue @@ -0,0 +1,19 @@ + + + + diff --git a/bmp-operation-web/src/ui/Button/button.scss b/bmp-operation-web/src/ui/Button/button.scss new file mode 100644 index 0000000..a28fe21 --- /dev/null +++ b/bmp-operation-web/src/ui/Button/button.scss @@ -0,0 +1,49 @@ +.el-button { + // 不要用全局样式 + --el-button-bg-color: #eee; + --el-button-text-color: #666; + height: auto; + --el-font-size-base: 12px; + --el-button-hover-border-color: transparent !important; + + &:active { + // 不要用全局样式 + --el-button-active-bg-color: #dfdfdf; + } + + &:focus, + &:hover { + // 不要用全局样式 + --el-button-hover-bg-color: #eee; + --el-button-hover-text-color: #666; + } + + &--primary { + // 不要用全局样式 + --el-button-bg-color: #108ee9 !important; + --el-button-text-color: #fff; + --el-button-border-color: transparent !important; + + &:focus, + &:hover { + // 不要用全局样式 + --el-button-hover-bg-color: #108ee9 !important; + --el-button-hover-text-color: #fff; + } + + &:active { + --el-button-active-bg-color: #0f81d4 !important; + --el-button-active-border-color: transparent !important; + } + } +} + +.el-button.is-disabled { + --el-button-disabled-bg-color: #91d5ff !important; + --el-button-disabled-border-color: #91d5ff !important; + &:hover, + &:focus { + --el-button-disabled-bg-color: #91d5ff !important; + --el-button-disabled-border-color: #91d5ff !important; + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/ui/CheckBox/CheckBox.vue b/bmp-operation-web/src/ui/CheckBox/CheckBox.vue new file mode 100644 index 0000000..43af274 --- /dev/null +++ b/bmp-operation-web/src/ui/CheckBox/CheckBox.vue @@ -0,0 +1,12 @@ + + + +; diff --git a/bmp-operation-web/src/ui/CheckBox/checkBox.scss b/bmp-operation-web/src/ui/CheckBox/checkBox.scss new file mode 100644 index 0000000..599388e --- /dev/null +++ b/bmp-operation-web/src/ui/CheckBox/checkBox.scss @@ -0,0 +1,101 @@ +.el-checkbox__inner { + // 不要用全局样式 + --el-checkbox-input-height: 12px; + --el-checkbox-input-width: 12px; + border-color: $defaultColor; + + &::after { + height: 6px !important; + left: 3px; + top: 0px; + width: 3px !important; + } +} + +/* 表格里面的复选框 */ +.el-checkbox__input.is-indeterminate .el-checkbox__inner, +.el-checkbox__input.is-checked .el-checkbox__inner { + // 不要用全局样式 + --el-checkbox-checked-bg-color: #108ee9; + --el-checkbox-checked-input-border-color: #108ee9; + + &::before { + top: 4px; + } +} + +.el-checkbox__input.is-disabled { + .el-checkbox__inner { + // 不要用全局样式 + --el-checkbox-input-height: 12px; + --el-checkbox-input-width: 12px; + } +} + +/* 常规复选框 */ +.checkbox-text-ellipsis { + .el-checkbox__label { + @extend %white-flw-over; + } + + .el-checkbox { + width: 80px; + height: 17px; + margin-right: 18px; + margin-bottom: 16px; + @include display-align(flex-start); + --el-checkbox-font-weight: $fontSmallWeight; + --el-checkbox-checked-text-color: $defaultColor; + --el-disabled-text-color: $defaultColor; + --el-checkbox-font-size: 12px; + --el-checkbox-text-color: $defaultColor; + --el-checkbox-border-radius: 2px; + + &__inner { + @include set-width-height(12px); + border-color: $border17; + + &::after { + height: 6px; + left: 3px; + top: 1px; + --el-checkbox-disabled-checked-icon-color: #fff; + } + } + } + + .is-checked, + .is-foucs { + --el-checkbox-checked-input-border-color: #108ee9; + --el-checkbox-checked-bg-color: #108ee9; + } + + .is-disabled { + cursor: no-drop; + --el-checkbox-disabled-checked-input-fill: #999; + --el-checkbox-disabled-checked-input-border-color: #999; + } +} + +.el-select-dropdown__list { + margin: 0 !important; +} +.select-checkbox-all { + padding: 0px 19px; + border-bottom: 1px solid #dcdfe6; + height: 33px; + line-height: 33px; + position: sticky; + top: 0; + background: #fff; + z-index: 9; + + label { + padding: 0 !important; + width: 100%; + + .el-checkbox__label { + font-weight: $fontSmallWeight; + } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/ui/Col/Col.vue b/bmp-operation-web/src/ui/Col/Col.vue new file mode 100644 index 0000000..3ac6448 --- /dev/null +++ b/bmp-operation-web/src/ui/Col/Col.vue @@ -0,0 +1,9 @@ + + + diff --git a/bmp-operation-web/src/ui/ConfigProvider/ConfigProvider.vue b/bmp-operation-web/src/ui/ConfigProvider/ConfigProvider.vue new file mode 100644 index 0000000..de9a352 --- /dev/null +++ b/bmp-operation-web/src/ui/ConfigProvider/ConfigProvider.vue @@ -0,0 +1,9 @@ + + + diff --git a/bmp-operation-web/src/ui/DatePicker/DatePicker.vue b/bmp-operation-web/src/ui/DatePicker/DatePicker.vue new file mode 100644 index 0000000..1f43718 --- /dev/null +++ b/bmp-operation-web/src/ui/DatePicker/DatePicker.vue @@ -0,0 +1,9 @@ + + + diff --git a/bmp-operation-web/src/ui/DiaLog/DiaLog.vue b/bmp-operation-web/src/ui/DiaLog/DiaLog.vue new file mode 100644 index 0000000..0b19949 --- /dev/null +++ b/bmp-operation-web/src/ui/DiaLog/DiaLog.vue @@ -0,0 +1,19 @@ + + + + + diff --git a/bmp-operation-web/src/ui/DiaLog/diaLog.scss b/bmp-operation-web/src/ui/DiaLog/diaLog.scss new file mode 100644 index 0000000..e9c8e53 --- /dev/null +++ b/bmp-operation-web/src/ui/DiaLog/diaLog.scss @@ -0,0 +1,42 @@ +.el-overlay { + background: $background11; + + &-dialog { + display: flex; + + .el-dialog--center { + margin: auto; + --el-border-radius-small: 10px; + padding: 0 22.5px; + // 不要用全局样式 + --el-dialog-bg-color: rgba(255, 255, 255, .8); + backdrop-filter: $backdropFilter; + + .el-dialog__header { + height: 41px; + border-bottom: 1px solid $border; + --el-dialog-padding-primary: 0; + padding-bottom: 0; + } + + .el-dialog__body { + padding: 0 !important; + } + + .el-dialog__footer { + position: absolute; + bottom: 0; + left: 50%; + border-top: 1px solid $border; + padding-top: 18px; + --el-dialog-padding-primary: 20px; + transform: translateX(-50%); + z-index: 99; + + .el-button+.el-button { + margin-left: 20px; + } + } + } + } +} diff --git a/bmp-operation-web/src/ui/DropDown/DropDown.vue b/bmp-operation-web/src/ui/DropDown/DropDown.vue new file mode 100644 index 0000000..d6d8233 --- /dev/null +++ b/bmp-operation-web/src/ui/DropDown/DropDown.vue @@ -0,0 +1,17 @@ + + + + diff --git a/bmp-operation-web/src/ui/DropDown/dropDown.scss b/bmp-operation-web/src/ui/DropDown/dropDown.scss new file mode 100644 index 0000000..416953a --- /dev/null +++ b/bmp-operation-web/src/ui/DropDown/dropDown.scss @@ -0,0 +1,27 @@ +.el-dropdown-menu { + padding: 0; + + &__item { + padding: 0; + + &:focus { + background: $transparent !important; + } + } +} + +.el-dropdown { + .more-operate { + @include display-align(center); + + span { + height: 23px; + line-height: 23px; + font-size: $fontSize; + } + + .arrow-bottom-img { + @include set-width-height(16px); + } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/ui/DropDownItem/DropDownItem.vue b/bmp-operation-web/src/ui/DropDownItem/DropDownItem.vue new file mode 100644 index 0000000..513d686 --- /dev/null +++ b/bmp-operation-web/src/ui/DropDownItem/DropDownItem.vue @@ -0,0 +1,9 @@ + + + diff --git a/bmp-operation-web/src/ui/Form/Form.vue b/bmp-operation-web/src/ui/Form/Form.vue new file mode 100644 index 0000000..0faf580 --- /dev/null +++ b/bmp-operation-web/src/ui/Form/Form.vue @@ -0,0 +1,30 @@ + + + + diff --git a/bmp-operation-web/src/ui/Form/form.scss b/bmp-operation-web/src/ui/Form/form.scss new file mode 100644 index 0000000..3b35a4a --- /dev/null +++ b/bmp-operation-web/src/ui/Form/form.scss @@ -0,0 +1,21 @@ +.operate-login-ruleForm { + margin: 46px auto 0px; + + input { + width: $percentageWidth; + border: 0; + } + + .el-form-item__error { + padding-top: 13px; + top: 100%; + } + +} + +.el-form-item__label, +.el-input__inner { + // 不要用全局的 + --el-form-label-font-size: 12px; + --el-text-color-regular: #333; +} diff --git a/bmp-operation-web/src/ui/FormItem/FormItem.vue b/bmp-operation-web/src/ui/FormItem/FormItem.vue new file mode 100644 index 0000000..f60e455 --- /dev/null +++ b/bmp-operation-web/src/ui/FormItem/FormItem.vue @@ -0,0 +1,12 @@ + + + + \ No newline at end of file diff --git a/bmp-operation-web/src/ui/FormItem/formItem.scss b/bmp-operation-web/src/ui/FormItem/formItem.scss new file mode 100644 index 0000000..e350e6e --- /dev/null +++ b/bmp-operation-web/src/ui/FormItem/formItem.scss @@ -0,0 +1,3 @@ +:deep(.el-range-input) { + font-size: $fontSize; +} \ No newline at end of file diff --git a/bmp-operation-web/src/ui/Icon/Icon.vue b/bmp-operation-web/src/ui/Icon/Icon.vue new file mode 100644 index 0000000..d6a1c8f --- /dev/null +++ b/bmp-operation-web/src/ui/Icon/Icon.vue @@ -0,0 +1,12 @@ + + + + diff --git a/bmp-operation-web/src/ui/Icon/icon.scss b/bmp-operation-web/src/ui/Icon/icon.scss new file mode 100644 index 0000000..dcae851 --- /dev/null +++ b/bmp-operation-web/src/ui/Icon/icon.scss @@ -0,0 +1,12 @@ +.operate-content { + &-icon-open-eye, + &-icon-close-eye, + &-icon-user { + margin-left: 15px; + margin-right: 5px; + } + + &-icon-close { + margin-right: 13px; + } +} diff --git a/bmp-operation-web/src/ui/Input/Input.vue b/bmp-operation-web/src/ui/Input/Input.vue new file mode 100644 index 0000000..ca4bd6a --- /dev/null +++ b/bmp-operation-web/src/ui/Input/Input.vue @@ -0,0 +1,165 @@ + + + + diff --git a/bmp-operation-web/src/ui/Input/input.scss b/bmp-operation-web/src/ui/Input/input.scss new file mode 100644 index 0000000..a45b52b --- /dev/null +++ b/bmp-operation-web/src/ui/Input/input.scss @@ -0,0 +1,261 @@ +$height: 28px; + +.el-input { + &__inner { + font-size: $fontSize; + } +} + +.is-disabled { + input { + background: $background3 !important; + } +} + +.set-instance { + input { + width: 420px; + padding-right: 156px; + } + + .input-select { + &-count { + .el-input__inner { + width: 115px; + padding: 0; + } + } + } + + .input-search-clear { + right: 143px; + } +} + +.set-input { + input { + width: 497px; + padding-right: 215px; + } + + .el-input__inner { + margin-right: 8px !important; + } + + .input-select { + &-count { + .el-input__inner { + width: 185px; + padding-right: 20px; + padding-left: 8px; + } + } + } + + .input-search-clear { + // right: 200px; + right: 207px + } + + .el-input__suffix { + right: 16px !important; + } +} + +.en-select { + .input-select { + &-count { + .el-input__inner { + margin-right: 18px !important; + } + } + } +} + +.small-input { + input { + width: 420px; + padding-right: 155px; + } + + .input-select { + &-count { + .el-input__inner { + width: 118px; + padding: 0; + } + } + } + + .input-search-clear { + right: 137px; + } + + .input-select-division-line { + left: -3px !important; + } +} + +.operate-management-input { + input { + width: 375px; + padding-right: 130px; + } + + .input-select { + &-count { + .el-input__inner { + width: 75px; + padding: 0; + } + } + } + + .input-search-clear { + right: 103px; + } +} + +.en-select, +.set-input, +.small-input, +.set-instance, +.operate-management-input { + @include display-align(center); + position: relative; + + input { + height: $height; + border: 1.05px solid $color7; + border-radius: $borderRadius !important; + overflow-x: auto; + font-size: $fontSize; + padding-left: 36px; + + &::placeholder { + @include size-weight-color($fontSize, $fontSmallWeight, $color7); + } + + &:hover { + border-color: $border2; + } + + &:focus, + &:active { + border-color: $border3; + } + } + + .el-input-group__append { + position: absolute; + left: 0px; + top: 50%; + transform: translateY(-50%); + border: 0; + background: $transparent; + + .search-icon { + @include set-width-height(15px); + margin-left: -7px; + margin-top: 2px; + @include set-cursor(pointer); + } + } + + .input-select { + @include display-align(center); + position: absolute; + right: 0; + top: 50%; + transform: translateY(-50%); + + input { + border: 0; + outline: 0; + } + + span { + @include size-weight-color($fontSize, $fontSmallWeight, $color6); + } + + &-division-line { + width: 1px; + height: 11.5px; + background: $color7; + position: absolute; + left: -3px; + } + + &-count { + height: $height; + + .el-input__inner { + background: transparent; + font-size: $fontSize !important; + @include text-align(center); + margin-right: 14px; + } + + .el-input__suffix { + right: 8px; + top: -1px; + } + } + } + + .input-search-clear { + @include set-width-height(16px); + position: absolute; + } +} + +.operate-content { + + &-ipt { + width: 344px; + height: 40px; + @include display-align(center); + margin-bottom: 7px; + + input { + padding-left: 57px; + height: 40px; + border: 1px solid $border2; + border-radius: 4px; + padding-right: 32px; + + &:hover { + border-color: $border2; + } + + &:focus, + &:active { + border-color: $border3; + } + } + + &-open-eye, + &-close-eye { + cursor: pointer; + @include set-cursor(pointer); + } + + &-user-img, + &-open-eye, + &-close-eye { + @include set-width-height(32px); + transform: scale(.5); + position: absolute; + left: 15px; + z-index: 9; + } + + &-clear { + @include set-width-height(32px); + transform: scale(.5); + position: absolute; + right: 5px; + @include set-cursor(pointer); + } + } +} diff --git a/bmp-operation-web/src/ui/InputNumber/InputNumber.vue b/bmp-operation-web/src/ui/InputNumber/InputNumber.vue new file mode 100644 index 0000000..ddc2013 --- /dev/null +++ b/bmp-operation-web/src/ui/InputNumber/InputNumber.vue @@ -0,0 +1,10 @@ + + + + diff --git a/bmp-operation-web/src/ui/InputNumber/inputNumber.scss b/bmp-operation-web/src/ui/InputNumber/inputNumber.scss new file mode 100644 index 0000000..827ca0f --- /dev/null +++ b/bmp-operation-web/src/ui/InputNumber/inputNumber.scss @@ -0,0 +1,49 @@ +.change-input-number, +.disabled-input-number { + .el-input-number { + width: 115px; + } +} + +.el-input-number__decrease.is-disabled { + left: 1px; +} + +.el-input-number__increase.is-disabled { + right: 1px; + bottom: 1px; + border-left: 1px solid #dcdfe6; + +} +.el-input-number__decrease.is-disabled, .el-input-number__increase.is-disabled { + background: #eee; + font-size: 12px; + top: 1px; + + &:hover { + color: $color15; + } +} + +.el-input-number__decrease { + background-color: $whiteBackground; + color: $defaultColor; + + &:hover { + color: $defaultColor; + } +} + +.el-input-number__increase { + background: $background1; + color: $color3; + border: 0; + border-color: $border3; + right: .5px; + top: 0px; + bottom: 0px; + + &:hover { + color: $color3; + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/ui/Mask/Mask.vue b/bmp-operation-web/src/ui/Mask/Mask.vue new file mode 100644 index 0000000..25ef033 --- /dev/null +++ b/bmp-operation-web/src/ui/Mask/Mask.vue @@ -0,0 +1,40 @@ + + + + diff --git a/bmp-operation-web/src/ui/Mask/mask.scss b/bmp-operation-web/src/ui/Mask/mask.scss new file mode 100644 index 0000000..555494a --- /dev/null +++ b/bmp-operation-web/src/ui/Mask/mask.scss @@ -0,0 +1,10 @@ +.custom-mask { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + overflow-x: hidden; + overflow-y: auto; + z-index: 12; +} \ No newline at end of file diff --git a/bmp-operation-web/src/ui/Menu/Menu.vue b/bmp-operation-web/src/ui/Menu/Menu.vue new file mode 100644 index 0000000..368f3cc --- /dev/null +++ b/bmp-operation-web/src/ui/Menu/Menu.vue @@ -0,0 +1,18 @@ + + + + diff --git a/bmp-operation-web/src/ui/Menu/menu.scss b/bmp-operation-web/src/ui/Menu/menu.scss new file mode 100644 index 0000000..556b4bd --- /dev/null +++ b/bmp-operation-web/src/ui/Menu/menu.scss @@ -0,0 +1,46 @@ +/* 侧边栏高度、radius、padding样式 */ +.nav-col { + .el-menu { + height: 90%; + transition: all .3s; + overflow-x: hidden; + padding-top: 38px; + padding-bottom: 60px; + + &--collapse { + width: 56px; + transition: width .3s; + } + + /* 侧边栏-一级导航每一项的样式 */ + &-item { + // 不要用全局的 + --el-menu-hover-bg-color: #f7f7f7; + margin-bottom: 17px; + border-radius: 22px 0 0 22px; + --el-menu-item-height: 42px; + transition: all .3s; + } + + /* 侧边栏-一级导航每一项的选中样式 */ + &-item.is-active { + // 不要用全局的 + --el-menu-active-color: #108ee9; + background: $color4; + // 不要用全局的 + --el-menu-hover-bg-color: #e8f4fd; + } + + } +} + +/* 侧边栏收起-【多级菜单-子路由】样式 */ +.el-menu--vertical { + .el-menu--popup { + min-width: 150px; + + .custom-short-nav { + @extend %justify-center; + } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/ui/MenuItem/MenuItem.vue b/bmp-operation-web/src/ui/MenuItem/MenuItem.vue new file mode 100644 index 0000000..b135240 --- /dev/null +++ b/bmp-operation-web/src/ui/MenuItem/MenuItem.vue @@ -0,0 +1,12 @@ + + + diff --git a/bmp-operation-web/src/ui/MenuItemGroup/MenuItemGroup.vue b/bmp-operation-web/src/ui/MenuItemGroup/MenuItemGroup.vue new file mode 100644 index 0000000..1fde389 --- /dev/null +++ b/bmp-operation-web/src/ui/MenuItemGroup/MenuItemGroup.vue @@ -0,0 +1,8 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/ui/Option/Option.vue b/bmp-operation-web/src/ui/Option/Option.vue new file mode 100644 index 0000000..4765e55 --- /dev/null +++ b/bmp-operation-web/src/ui/Option/Option.vue @@ -0,0 +1,7 @@ + + + diff --git a/bmp-operation-web/src/ui/Pagination/Pagination.vue b/bmp-operation-web/src/ui/Pagination/Pagination.vue new file mode 100644 index 0000000..ca1f9db --- /dev/null +++ b/bmp-operation-web/src/ui/Pagination/Pagination.vue @@ -0,0 +1,370 @@ + + + diff --git a/bmp-operation-web/src/ui/Pagination/pagination.scss b/bmp-operation-web/src/ui/Pagination/pagination.scss new file mode 100644 index 0000000..7d1f7fb --- /dev/null +++ b/bmp-operation-web/src/ui/Pagination/pagination.scss @@ -0,0 +1,127 @@ +.footer-count { + margin-top: 20px; + position: relative; + width: $percentageWidth; +} + +.footer-count { + + .flex-end-right { + justify-content: flex-end; + margin-right: 57px; + } + + .my-pagination { + @include display-align(center); + @extend %justify-center; + + &-total { + @include display-align(center); + margin-right: 25px; + @include size-weight-color($fontSize, $fontSmallWeight, $color7); + + span { + margin: 0 5px; + } + } + + &-prev { + margin-right: 7px; + } + + &-disabled { + // cursor: not-allowed; + @include set-cursor(not-allowed); + opacity: .4; + } + + &-pointer { + @include set-cursor(pointer); + opacity: 1; + } + + &-next { + margin-left: 7px; + } + + &-number { + display: inline-block; + padding: 5px 7px; + @include set-cursor(pointer); + @include size-weight-color($fontSize, $fontLargeWeight, $defaultColor); + + &:hover { + color: $color1 !important; + } + } + + .active { + @extend %pointer-events; + @include size-weight-color($fontSize, $fontLargeWeight, $color1); + } + + .el-input-number--small { + width: 55px; + + input { + @include text-align(left); + padding-left: 5px !important; + } + } + + .el-input__inner { + font-size: $fontSize; + padding: 0 !important; + } + + .el-input__suffix { + background-image: url('~@/assets/img/uiImg/table-arrow-bottom.png'); + @include position-repeat(0); + background-size: backgoundSize(auto); + right: 0px; + + svg { + display: none; + } + } + + &-select, + .short-select { + @include display-align(center); + + input { + padding: 0 20px; + width: 70px; + border: 0; + } + } + + .set-width { + @include display-align(center); + + input { + padding: 0 20px; + // width: 100px !important; + border: 0; + } + } + + &-select { + margin-right: 25px; + margin-top: 1px; + } + + &-altogether, + .short-altogether { + @include size-weight-color($fontSize, $fontSmallWeight, $color7); + } + + &-altogether { + margin-left: 24px; + } + + .short-altogether { + margin-left: 5px; + } + } +} diff --git a/bmp-operation-web/src/ui/Progress/Progress.vue b/bmp-operation-web/src/ui/Progress/Progress.vue new file mode 100644 index 0000000..bc7bf27 --- /dev/null +++ b/bmp-operation-web/src/ui/Progress/Progress.vue @@ -0,0 +1,10 @@ + + + + diff --git a/bmp-operation-web/src/ui/Radio/Radio.vue b/bmp-operation-web/src/ui/Radio/Radio.vue new file mode 100644 index 0000000..57cf982 --- /dev/null +++ b/bmp-operation-web/src/ui/Radio/Radio.vue @@ -0,0 +1,12 @@ + + + + diff --git a/bmp-operation-web/src/ui/Radio/radio.scss b/bmp-operation-web/src/ui/Radio/radio.scss new file mode 100644 index 0000000..7ead119 --- /dev/null +++ b/bmp-operation-web/src/ui/Radio/radio.scss @@ -0,0 +1,40 @@ +.radio-style1 { + .el-radio { + .el-radio__input { + @include set-width-height(12px); + border: 0.62px solid $border2; + border-radius: 50%; + @include display-align(center); + @extend %justify-center; + + .el-radio__inner { + display: none; + } + } + .is-checked { + .el-radio__inner { + @include set-width-height(7px); + position: absolute; + left: 50%; + top: 50%; + transform: translate(-50%, -50%); + display: inherit !important; + // $color1 - 会有问题 + --el-color-primary: #108ee9; + + &::after { + display: none; + } + } + } + + .el-radio__label { + padding-left: 13px; + @include size-weight-color($fontSize, $fontSmallWeight, $defaultColor); + } + + .el-radio__input.is-checked+.el-radio__label { + @include size-weight-color($fontSize, $fontSmallWeight, $defaultColor); + } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/ui/RadioButton/RadioButton.vue b/bmp-operation-web/src/ui/RadioButton/RadioButton.vue new file mode 100644 index 0000000..7d19c1e --- /dev/null +++ b/bmp-operation-web/src/ui/RadioButton/RadioButton.vue @@ -0,0 +1,10 @@ + + + + diff --git a/bmp-operation-web/src/ui/RadioButton/radioButton.scss b/bmp-operation-web/src/ui/RadioButton/radioButton.scss new file mode 100644 index 0000000..94c2d68 --- /dev/null +++ b/bmp-operation-web/src/ui/RadioButton/radioButton.scss @@ -0,0 +1,52 @@ +.el-radio-button__original-radio:checked+.el-radio-button__inner { + background-color: $background1 !important; + border-radius: 4px; + font-size: $fontSize; + border-color: transparent !important; + margin-right: 12px; + + &:hover { + color: $color3 !important; + } +} +.is-disabled, +.is-active.is-disabled { + .el-radio-button__inner { + &:hover { + color: #c0c4cc !important; + } + } +} + +.custom-radio-button { + .el-radio-button--default { + .el-radio-button__inner { + margin-right: 12px; + border-radius: 4px !important; + border: .62px solid $border2; + height: 30px; + font-size: $fontSize; + + &:hover { + border-color: $border3; + color: $color1; + } + } + } + + .is-active { + .el-radio-button__inner { + border: .62px solid $border3 !important; + background: $background1 !important; + margin-right: 12px !important; + border-radius: 4px !important; + font-size: $fontSize; + color: $color3; + + &:active { + border-color: $border6 !important; + background: $background2 !important; + } + } + } +} diff --git a/bmp-operation-web/src/ui/RadioGroup/RadioGroup.vue b/bmp-operation-web/src/ui/RadioGroup/RadioGroup.vue new file mode 100644 index 0000000..082b079 --- /dev/null +++ b/bmp-operation-web/src/ui/RadioGroup/RadioGroup.vue @@ -0,0 +1,12 @@ + + + + \ No newline at end of file diff --git a/bmp-operation-web/src/ui/RadioGroup/radioGroup.scss b/bmp-operation-web/src/ui/RadioGroup/radioGroup.scss new file mode 100644 index 0000000..0c9306f --- /dev/null +++ b/bmp-operation-web/src/ui/RadioGroup/radioGroup.scss @@ -0,0 +1,30 @@ +.radio-active { + .el-radio-group { + .el-radio-button--default { + .el-radio-button__inner { + height: 30px; + font-size: $fontSize; + margin-right: 0px !important; + border-radius: 0; + font-weight: $fontSmallWeight; + + &:hover { + color: $defaultColor; + } + } + &:first-child { + .el-radio-button__inner { + border-radius: 4px 0 0 4px !important; + } + } + &:last-child { + .el-radio-button__inner { + border-radius: 0 4px 4px 0 !important; + } + } + } + .is-active { + border-radius: 0 !important; + } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/ui/Row/Row.vue b/bmp-operation-web/src/ui/Row/Row.vue new file mode 100644 index 0000000..4a0dccd --- /dev/null +++ b/bmp-operation-web/src/ui/Row/Row.vue @@ -0,0 +1,9 @@ + + + diff --git a/bmp-operation-web/src/ui/ScrollBar/ScrollBar.vue b/bmp-operation-web/src/ui/ScrollBar/ScrollBar.vue new file mode 100644 index 0000000..85a0155 --- /dev/null +++ b/bmp-operation-web/src/ui/ScrollBar/ScrollBar.vue @@ -0,0 +1,9 @@ + + + diff --git a/bmp-operation-web/src/ui/Select/Select.vue b/bmp-operation-web/src/ui/Select/Select.vue new file mode 100644 index 0000000..d05164d --- /dev/null +++ b/bmp-operation-web/src/ui/Select/Select.vue @@ -0,0 +1,27 @@ + + + + + diff --git a/bmp-operation-web/src/ui/Select/select.scss b/bmp-operation-web/src/ui/Select/select.scss new file mode 100644 index 0000000..a922667 --- /dev/null +++ b/bmp-operation-web/src/ui/Select/select.scss @@ -0,0 +1,136 @@ +.custom-select { + .el-select-dropdown__item { + @include text-align(center); + padding: 0 26px; + } + + .selected { + font-weight: $fontSmallWeight; + } +} +.select-seleted-icon { + .selected { + &::after { + position: absolute; + content: ""; + width: 4px; + height: 8px; + transform: rotate(45deg); + border-right: 1.5px solid $border3; + right: 20px; + border-bottom: 1.5px solid $border3; + top: 10px; + } + + } +} + +.custom-select, +.select-seleted-icon, +.default-select { + .el-select-dropdown__item { + // 不要用全局的 + --el-font-size-base: 12px; + --el-text-color-regular: #333; + + &:hover { + background: $background3; + color: $color1; + } + } + + .el-select-dropdown__item.is-disabled { + &:hover { + background: $whiteBackground; + color: $color15; + } + } + + .selected { + // 不要用全局的 + --el-color-primary: #108ee9; + background: $background3 !important; + } + + + .hover { + background-color: $transparent; + } +} + +.input-select-count { + .el-input__suffix { + .el-input__suffix-inner { + i { + svg { + color: $color6; + margin-top: -3px; + } + } + } + } +} + +.multiple-choice-short { + .el-form-item__content { + .el-select__tags { + .el-tag.el-tag--info.is-hit { + .el-tag__content { + width: v-bind(90px) !important; + } + } + } + } +} + +.multiple-choice-en, +.multiple-choice { + .el-form-item__content { + + input { + width: 330px; + } + + .el-select__tags { + span { + &:first-child { + display: flex; + align-items: center; + } + } + .el-tag.el-tag--info.is-hit { + border-color: transparent; + height: 22px !important; + background: $background1 !important; + color: $color3; + + .el-tag__content { + font-size: $fontSize; + + .el-select__tags-text { + width: 200px !important; + // max-width: none !important; + justify-content: flex-start; + // max-width: px !important; + } + } + } + + .el-icon, + .el-tag__close { + @include set-width-height(16px); + background-image: url('~@/assets/img/uiImg/white-clear.png'); + background-size: backgoundSize(auto); + @include position-repeat(0); + + svg { + display: none; + } + + &:hover { + background-color: transparent; + } + } + } + } +} diff --git a/bmp-operation-web/src/ui/Step/Step.vue b/bmp-operation-web/src/ui/Step/Step.vue new file mode 100644 index 0000000..da73fd4 --- /dev/null +++ b/bmp-operation-web/src/ui/Step/Step.vue @@ -0,0 +1,12 @@ + + + + + diff --git a/bmp-operation-web/src/ui/Steps/Steps.vue b/bmp-operation-web/src/ui/Steps/Steps.vue new file mode 100644 index 0000000..cfc5e96 --- /dev/null +++ b/bmp-operation-web/src/ui/Steps/Steps.vue @@ -0,0 +1,12 @@ + + + + + diff --git a/bmp-operation-web/src/ui/SubMenu/SubMenu.vue b/bmp-operation-web/src/ui/SubMenu/SubMenu.vue new file mode 100644 index 0000000..b6a39f0 --- /dev/null +++ b/bmp-operation-web/src/ui/SubMenu/SubMenu.vue @@ -0,0 +1,11 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/ui/Switch/Switch.vue b/bmp-operation-web/src/ui/Switch/Switch.vue new file mode 100644 index 0000000..c875077 --- /dev/null +++ b/bmp-operation-web/src/ui/Switch/Switch.vue @@ -0,0 +1,6 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/ui/Table/Table.vue b/bmp-operation-web/src/ui/Table/Table.vue new file mode 100644 index 0000000..4fba9e5 --- /dev/null +++ b/bmp-operation-web/src/ui/Table/Table.vue @@ -0,0 +1,61 @@ + + + + + diff --git a/bmp-operation-web/src/ui/Table/extractPublic.scss b/bmp-operation-web/src/ui/Table/extractPublic.scss new file mode 100644 index 0000000..75e9da1 --- /dev/null +++ b/bmp-operation-web/src/ui/Table/extractPublic.scss @@ -0,0 +1,46 @@ +$center: center; +$height: 45px; + +%backgroud-repeat-position { + @include position-repeat(0); +} + +%filter-trigger { + // @extend %width-height; + @include set-width-height(16px); + background-size: backgoundSize(auto) !important; + margin-left: 5px; + flex-shrink: 0; + + i { + display: none; + } +} + +%color-height-background-color { + color: $color1 !important; + height: 45px; + background-color: $background4 !important; +} + +@function tableFilterBtnImg($status) { + @if $status == 1 { + @return url(' ~@/assets/img/uiImg/table-arrow-bottom.png'); + } + @else { + @return url('~@/assets/img/listImg/arrow-bottom.png'); + } +} + +@mixin heighlight { + padding: 0 !important; + + .cell.highlight { + @extend %color-height-background-color; + + .el-table__column-filter-trigger { + @extend %filter-trigger; + background-image: tableFilterBtnImg(2); + } + } +} diff --git a/bmp-operation-web/src/ui/Table/table.scss b/bmp-operation-web/src/ui/Table/table.scss new file mode 100644 index 0000000..7c90498 --- /dev/null +++ b/bmp-operation-web/src/ui/Table/table.scss @@ -0,0 +1,341 @@ +@import './extractPublic.scss'; + +.el-table { + + &--border { + &::after, + &::before { + display: none; + } + } + + &__border-left-patch { + display: none; + } + + &__header-wrapper { + .el-table__header { + th, + .el-table-fixed-column--left, + .el-table-fixed-column--right { + background: $background14; + } + } + + .cell { + // @extend %display-flex-align; + @include display-align(center); + @extend %justify-center; + @extend %white-flw-over; + } + } + + &-column--selection { + border-left: 0 !important; + border-right: 0 !important; + } + + &-fixed-column--left { + border-left: 0 !important; + border-color: $border8 !important; + } + + &-fixed-column--left.is-last-column.el-table__cell { + border-color: $border8 !important; + border-width: 1px !important; + } + + th.lignt-filter { + padding: 0 !important; + + .cell { + @extend %color-height-background-color; + + .el-table__column-filter-trigger { + background-image: tableFilterBtnImg(2) !important; + @extend %filter-trigger; + } + } + } + + @for $i from 0 through 15 { + $key: $i; + th.def-type-status#{$key} { + @include heighlight; + } + } + + th.common-status { + padding: 0 !important; + background-color: $background4 !important; + + .cell { + @extend %color-height-background-color; + + .el-table__column-filter-trigger { + background-image: tableFilterBtnImg(2) !important; + @extend %filter-trigger; + } + } + } +} + +.no-top { + margin-top: 0px !important; +} + +.no-top, +.operate-management-count, +.currency-count-table { + .img-show { + + .el-table__body-wrapper { + display: inline-block; + opacity: 0; + + .el-table__empty-block { + background: $whiteBackground !important; + } + } + } +} + +.no-top, +.operate-management-count { + padding: 0px 30px; + + /* 修改表格空数据展示 */ + .img-empty { + + .el-table__body-wrapper { + + .el-table__empty-block { + width: 363px !important; + margin: 0px auto 0; + + .el-table__empty-text { + width: auto; + @include size-weight-color($fontSize, $fontSmallWeight, $defaultColor); + } + } + + .custom-tip-count { + .empty-text { + color: $color1; + @include set-cursor(pointer); + } + } + } + } + + /* 修改表头下拉icon样式 */ + .img-empty, + .img-show { + .el-table__header-wrapper { + .cell { + @include display-align(center); + @extend %justify-center; + + .el-table__column-filter-trigger { + background-image: tableFilterBtnImg(1); + background-repeat: no-repeat; + @extend %filter-trigger; + } + } + } + } + + &-short-table { + .el-table__header-wrapper { + @include display-align(center); + border-top-left-radius: 3px; + border-top-right-radius: 3px; + } + + .el-table__body { + padding-bottom: 10px !important; + } + } + + &-short-table, + &-table { + transition: max-height .6s; + + .cell { + @include text-align($center); + + .el-table__column-filter-trigger { + background-image: tableFilterBtnImg(1); + @extend %backgroud-repeat-position; + @extend %filter-trigger; + } + } + + .el-table__empty-block { + @extend %def-c-f-style; + // background: $background3; + } + + .el-table__row { + height: $height; + @extend %def-c-f-style; + background: $whiteBackground; + + .el-table__cell { + border-left-color: $transparent !important; + border-right-color: $transparent !important; + } + } + + .el-table__body tr:hover > td{ + background-color: $background3 !important; + } + + .el-table__cell { + border-color: $border8; + border-width: 1px; + border-bottom: 0 !important; + + .highlight { + --el-color-primary: $color1; + } + + .el-table__inner-wrapper { + &::after, + &::before { + display: none; + } + } + } + + .el-table__inner-wrapper { + &::after, + &::before { + display: none; + } + } + } + + .set-header-count-left { + .cell { + @include text-align(left); + @include display-align(flex-start); + @extend %justify-start; + padding-left: 18px !important; + } + } +} + +.operate-management-detail, +.currency { + &-count { + &-table { + .cell { + @include text-align($center); + + .el-table__column-filter-trigger { + background-image: tableFilterBtnImg(1); + @extend %backgroud-repeat-position; + @extend %filter-trigger; + } + } + + .el-table__row { + height: $height; + @extend %def-c-f-style; + background: $whiteBackground; + } + + .el-table__cell { + + .cell { + @include display-align(center); + @extend %justify-center; + } + } + + .el-table__inner-wrapper { + &::before { + display: none; + } + } + + .el-checkbox__inner { + @include set-width-height(12px); + border: 1px solid $border17; + border-radius: 2px; + + &::before { + top: 3px !important; + height: 3px !important; + } + + &::after { + box-sizing: content-box; + content: ""; + border: 1px solid $border8; + border-left: 0; + border-top: 0; + height: 6px !important; + left: 3px !important; + position: absolute; + top: 0px; + transform: rotate(45deg) scaleY(0); + width: 2px; + transition: transform .15s ease-in 50ms; + transform-origin: center; + } + } + + .el-table__body tr:hover > td{ + background-color: $background3 !important; + } + } + } +} + +/** table组件-label&下拉框筛选样式 */ +.el-popper.is-pure { + border: 0 !important; + + .el-popper__arrow { + &::before { + border-color: $border8 !important; + } + } + + .el-checkbox.el-checkbox--default { + padding: 3px; + + .el-checkbox__label { + @extend %def-c-f-style; + } + } + + .is-checked { + .el-checkbox__label { + color: $color1 !important; + } + } + + .el-table-filter__bottom { + @include display-justify(space-around); + + button.is-disabled { + color: $color7 !important; + } + + button { + color: $defaultColor; + + &:hover { + color: $color1; + } + } + + button.is-disabled, + button { + font-size: $fontSize; + } + } +} diff --git a/bmp-operation-web/src/ui/TableColumn/TableColumn.vue b/bmp-operation-web/src/ui/TableColumn/TableColumn.vue new file mode 100644 index 0000000..84d6fdb --- /dev/null +++ b/bmp-operation-web/src/ui/TableColumn/TableColumn.vue @@ -0,0 +1,29 @@ + + + + + diff --git a/bmp-operation-web/src/ui/TableColumn/tableColumn.scss b/bmp-operation-web/src/ui/TableColumn/tableColumn.scss new file mode 100644 index 0000000..40172b2 --- /dev/null +++ b/bmp-operation-web/src/ui/TableColumn/tableColumn.scss @@ -0,0 +1,10 @@ +@import '@/assets/css/communal'; + +.el-table__header-wrapper { + border-top-left-radius: 3px; + border-top-right-radius: 3px; + + table { + height: 45px; + } +} diff --git a/bmp-operation-web/src/ui/Tabs/Tabs.vue b/bmp-operation-web/src/ui/Tabs/Tabs.vue new file mode 100644 index 0000000..7e5ec28 --- /dev/null +++ b/bmp-operation-web/src/ui/Tabs/Tabs.vue @@ -0,0 +1,55 @@ + + + + diff --git a/bmp-operation-web/src/ui/Tabs/tabs.scss b/bmp-operation-web/src/ui/Tabs/tabs.scss new file mode 100644 index 0000000..ef76c4b --- /dev/null +++ b/bmp-operation-web/src/ui/Tabs/tabs.scss @@ -0,0 +1,14 @@ +.el-tabs.tabs-zh-width { + :deep(.el-tabs__item) { + width: 125px; + text-align: center; + } +} + +.el-tabs.tabs-en-width { + :deep(.el-tabs__item) { + // width: 190px; + width: 240px; + text-align: center; + } +} diff --git a/bmp-operation-web/src/ui/Tag/Tag.vue b/bmp-operation-web/src/ui/Tag/Tag.vue new file mode 100644 index 0000000..174d863 --- /dev/null +++ b/bmp-operation-web/src/ui/Tag/Tag.vue @@ -0,0 +1,11 @@ + + + diff --git a/bmp-operation-web/src/ui/Tag/tag.scss b/bmp-operation-web/src/ui/Tag/tag.scss new file mode 100644 index 0000000..154859e --- /dev/null +++ b/bmp-operation-web/src/ui/Tag/tag.scss @@ -0,0 +1,4 @@ +.el-tag { + --el-tag-text-color: #108ee9; + --el-tag-hover-color: #108ee9; +} \ No newline at end of file diff --git a/bmp-operation-web/src/ui/Text/Text.vue b/bmp-operation-web/src/ui/Text/Text.vue new file mode 100644 index 0000000..d8d0e69 --- /dev/null +++ b/bmp-operation-web/src/ui/Text/Text.vue @@ -0,0 +1,52 @@ + + + + diff --git a/bmp-operation-web/src/ui/Text/text.scss b/bmp-operation-web/src/ui/Text/text.scss new file mode 100644 index 0000000..321afde --- /dev/null +++ b/bmp-operation-web/src/ui/Text/text.scss @@ -0,0 +1,18 @@ +@import '@/assets/css/communal'; + +.empty-text { + font-size: $fontSize; + font-weight: $fontSmallWeight; + text-align: center; + margin-top: 20px; + + &-title { + color: $defaultColor; + } + + &-operate { + color: $color1; + cursor: pointer; + margin-left: 3px; + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/ui/ToolTip/ToolTip.vue b/bmp-operation-web/src/ui/ToolTip/ToolTip.vue new file mode 100644 index 0000000..4a6d36e --- /dev/null +++ b/bmp-operation-web/src/ui/ToolTip/ToolTip.vue @@ -0,0 +1,12 @@ + + + diff --git a/bmp-operation-web/src/ui/UpLoad/UpLoad.vue b/bmp-operation-web/src/ui/UpLoad/UpLoad.vue new file mode 100644 index 0000000..e6add6c --- /dev/null +++ b/bmp-operation-web/src/ui/UpLoad/UpLoad.vue @@ -0,0 +1,30 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/ui/utils.ts b/bmp-operation-web/src/ui/utils.ts new file mode 100644 index 0000000..ceb40e7 --- /dev/null +++ b/bmp-operation-web/src/ui/utils.ts @@ -0,0 +1,135 @@ +import UiRow from './Row/Row.vue'; // Layout布局 - row组件 +import UiCol from './Col/Col.vue'; // Layout布局 - col组件 +import UiTag from './Tag/Tag.vue'; // 标签 +import UiForm from './Form/Form.vue'; // form表单组件 +import UiIcon from './Icon/Icon.vue'; // icon组件 +import UiMenu from './Menu/Menu.vue'; // 菜单栏组件 +import UiTabs from './Tabs/Tabs.vue'; // 标签页组件 +import UiStep from './Step/Step.vue'; // 步骤条 +import UiSteps from './Steps/Steps.vue'; // 步骤条 +import EmptyText from './Text/Text.vue'; // 空组件-文案 +import UiRadio from './Radio/Radio.vue'; // 单选框组件 +import UiInput from './Input/Input.vue'; // input输入框组件 +import UiTable from './Table/Table.vue'; // table表格组件 +import UiSwitch from './Switch/Switch.vue'; // switch开关组件 +import UiUpload from './UpLoad/UpLoad.vue'; // 上传组件 +import UiDialog from './DiaLog/DiaLog.vue'; // 对话框组件 +import UiCustomMask from './Mask/Mask.vue'; // 自定义蒙层组件 +import UiButton from './Button/Button.vue'; // button按钮组件 +import UiSelect from './Select/Select.vue'; // select选择器组件 +import UiOption from './Option/Option.vue'; // 选择器组件 +import UiTooltip from './ToolTip/ToolTip.vue'; // 文字提示组件 +import UiFormItem from './FormItem/FormItem.vue'; // 表单-form-item组件 +import UiCheckbox from './CheckBox/CheckBox.vue'; // 多选框组件 +import UiMenuItem from './MenuItem/MenuItem.vue'; // 菜单栏-menu-item组件 +import UiProgress from './Progress/Progress.vue'; // 进度条 +import UiScrollBar from './ScrollBar/ScrollBar.vue'; // scroll高度 +import UiMenuItemGroup from './MenuItemGroup/MenuItemGroup.vue'; // 菜单栏-menu-item-group组件 +import UiSubMenu from './SubMenu/SubMenu.vue'; // 菜单栏-sub-menu组件 +import UiDropdown from './DropDown/DropDown.vue'; // 下拉菜单组件 +import UiPagination from './Pagination/Pagination.vue'; // 分页组件 +import UiRadioGroup from './RadioGroup/RadioGroup.vue'; // 单项选择器组件 +import UiInputNumber from './InputNumber/InputNumber.vue'; // 数字输入框组件 +import UiTableColumn from './TableColumn/TableColumn.vue'; // 表格-table-column组件 +import UiDatePicker from './DatePicker/DatePicker.vue'; // 日期 +import UiRadioButton from './RadioButton/RadioButton.vue'; // 单选框-button类组件 + +import UiDropdownItem from './DropDownItem/DropDownItem.vue'; // 下拉菜单-drop-down-item组件 +import UiConfigProvider from './ConfigProvider/ConfigProvider.vue'; // 国际化组件,用于element-plus内部国际化切换 +/** + * 所有组件 +*/ +const components: {[x: string]: Function;}[] = [ + UiRow, + UiCol, + UiTag, + UiMenu, + UiForm, + UiTabs, + UiStep, + UiSteps, + UiIcon, + UiRadio, + UiInput, + UiTable, + UiSwitch, + UiButton, + UiSelect, + UiOption, + UiUpload, + UiDialog, + EmptyText, + UiTooltip, + UiFormItem, + UiCheckbox, + UiMenuItem, + UiProgress, + UiScrollBar, + UiMenuItemGroup, + UiSubMenu, + UiDropdown, + UiCustomMask, + UiRadioGroup, + UiPagination, + UiDatePicker, + UiRadioButton, + UiInputNumber, + UiTableColumn, + UiDropdownItem, + UiConfigProvider +]; + +/** + * 所有组件名 +*/ +const componentsName: string[] = [ + 'UiRow', + 'UiCol', + 'UiTag', + 'UiMenu', + 'UiForm', + 'UiTabs', + 'UiStep', + 'UiSteps', + 'UiIcon', + 'UiRadio', + 'UiInput', + 'UiTable', + 'UiSwitch', + 'UiButton', + 'UiSelect', + 'UiOption', + 'UiUpload', + 'UiDialog', + 'EmptyText', + 'UiTooltip', + 'UiFormItem', + 'UiCheckbox', + 'UiMenuItem', + 'UiProgress', + 'UiScrollBar', + 'UiMenuItemGroup', + 'UiSubMenu', + 'UiDropdown', + 'UiCustomMask', + 'UiRadioGroup', + 'UiPagination', + 'UiDatePicker', + 'UiRadioButton', + 'UiInputNumber', + 'UiTableColumn', + 'UiDropdownItem', + 'UiConfigProvider' +]; + +/** + * 遍历,依次挂载 +*/ +export default { + // install 方法 接收参数app + install(app: {component: Function;}): void { + components.forEach((comp, index: number) => { + app.component(componentsName[index], comp); + }); + } +}; diff --git a/bmp-operation-web/src/upDate.ts b/bmp-operation-web/src/upDate.ts new file mode 100644 index 0000000..ef8968f --- /dev/null +++ b/bmp-operation-web/src/upDate.ts @@ -0,0 +1,117 @@ +/** + * @file + * @author +*/ +import {ElMessageBox} from 'element-plus'; + +class UpdateOpt { + flag: number = 0; + hasLoop: number = 0; + timer: null | number = null; + env: string = process.env.VUE_APP_ENV; + + constructor() { + this.init(); + this.handleVisibility(); + } + + handleVisibility = () => { + document.addEventListener('visibilitychange', () => { + const status = { + 'hidden': () => { + clearInterval(this.timer as number); + this.hasLoop = 0; + }, + 'visible': () => this.init() + } + status[document.visibilityState](); + }) + } + + init = () => { + if (!this.hasLoop) { + this.loopReq(); + } + // 定时执行,自动更新逻辑(每10s检测一次) + this.timer = setInterval(async () => { + this.loopReq(); + }, 1000 * 10); + } + + loopReq = async () => { + this.hasLoop = 1; + // 本地 + const localVersion: string = this.getLocalHash(); + // 线上 + const newVersion = await this.getPreHash(); + // 如果不一样,就进行刷新 + if(localVersion !== newVersion && ![newVersion, localVersion].includes('')) { + if (this.flag > 0 || Object.is(this.env, 'dev')) return; + ElMessageBox.confirm( + '检测到有新版本,是否更新?', + '版本提示', + { + confirmButtonText: '更新', + cancelButtonText: '取消', + type: 'warning' + } + ) + .then(() => { + this.flag = 0; + window.location.reload(); + }) + .catch(() => { + this.flag = 0; + }) + this.flag ++; + } + } + + getAppHash = (scripts: string | any[] | HTMLCollectionOf) => { + let localVersion = ''; + for(let i = 0; i < scripts.length; i++) { + let src = scripts[i].getAttribute("src"); + if (src && src.indexOf("app.") !== -1) { + // 正则返回中间版本号(如果没有,返回空) + const regRes = /app\.(.*?).js/; + if(regRes.test(src)) { + const matchResult = regRes.exec(src); + if (matchResult !== null) { + localVersion = matchResult[1]; + } + else { + // 处理未匹配到的情况,可能是赋一个默认值,或者抛出异常 + localVersion = '未找到匹配的版本号'; + throw new Error(localVersion); + } + } + } + } + return localVersion; + } + + // 获取本地的app.js版本号 + getLocalHash = () => { + return this.getAppHash(document.getElementsByTagName('script')); + } + + // 获取线上的app.js版本号 + getPreHash = () => { + return new Promise((resolve, reject) => { + // 加上时间戳,防止缓存 + fetch('/?_time=' + Date.now()).then(async res => { + // 转成字符串判断 + const html = await res.text(); + const doc = new DOMParser().parseFromString(html, 'text/html'); + const newVersion = this.getAppHash(doc.getElementsByTagName('script')); + resolve(newVersion); + }) + .catch(err => { + reject(err); + throw new Error('获取版本号失败'); + }) + }) + } +} + +new UpdateOpt(); \ No newline at end of file diff --git a/bmp-operation-web/src/utils/index.ts b/bmp-operation-web/src/utils/index.ts new file mode 100644 index 0000000..190c972 --- /dev/null +++ b/bmp-operation-web/src/utils/index.ts @@ -0,0 +1,761 @@ +import VueCookies from 'vue-cookies'; // cookie +import i18n from 'lib/i18n/index.ts'; // 国际化 +import en from 'element-plus/lib/locale/lang/en'; // 英文 +import zhCn from 'element-plus/lib/locale/lang/zh-cn'; // 中文 +import {ElMessage} from 'element-plus'; +import {CurrencyType} from './publicType'; + +const CryptoJS = require('crypto-js'); + +/** + * 国际化1 +*/ +const {global} = i18n; + +class MethodsTotal { + channel = new BroadcastChannel(''); + + sendMsg = (type: string, content: CurrencyType[]) => { + this.channel.postMessage({ + type, + content + }) + } + + listenMsg = (fn: Function) => { + const handle = (e: {data: CurrencyType[];}) => { + fn && fn(e.data); + } + + this.channel.addEventListener('message', (handle)); + return () => { + this.channel.removeEventListener('message', handle); + } + } + + static deepCopy = (data: any[]) => { + if (typeof data !== 'object' || !data) { + return data; + } + // 判断是数组还是对象 + const result: any = data instanceof Array ? [] : {}; + for (const key in data) { + // 只拷贝对象自身的属性 + if (data.hasOwnProperty(key)) { + result[key] = this.deepCopy(data[key]); + } + } + return result; + }; + + toLine(params: any) { + const conversionData = [ + [ + (params: string) => typeof params === 'string', + () => this.humpConversion(params) + ], + [ + (params: {[x: string]: string | number}) => params instanceof Object, + () => { + const obj = []; + for (const index of Object.keys(params)) { + obj.push( + { + [this.humpConversion(index)]: params[index] + } + ) + } + return Object.assign({}, ...obj); + } + ] + ]; + + for (const key of conversionData) { + if (key[0](params)) { + return key[1](params); + } + } + } + + humpConversion = (params: string) => { + return params.replace(/([A-Z])/g, '_$1').toLowerCase() + }; + + humpSplit = (params: string) => { + return params.replace(/([A-Z])/g, '-$1').toLowerCase() + }; + + lineConverting (data: any) { + if (typeof data !== 'object' || !data) return data; + if (Array.isArray(data)) { + return data.map((item): any => this.lineConverting(item)) + } + const newData: any = {} + for (let key in data) { + const newKey = key.replace(/_([a-z])/g, (_, m) => m.toUpperCase()) + newData[newKey] = this.lineConverting(data[key]) + } + return newData; + }; + + initScrollLeft = (value: any) => { + value.$refs.bodyWrapper.getElementsByClassName('el-scrollbar__wrap')[0].scrollLeft = 0; + }; + + /** + * 是否明文显示密码 + * @param {boolean} type 密码当前状态 false 加密 true 明文 + * @param {string} len 密码长度 + * @return {string} encryption.join('') 数组转字符串,','隔开 len 密码长度 + */ + hasShowPassword = (type: boolean, len: string): string => { + if (!type) { + if (!len) { + return '*********'; + } + const encryption: string[] = []; + for (let i: number = 1; i <= len.length; i++) { + encryption.push('*'); + } + return encryption.join(''); + } + return len; + }; + + /** + * 16进制颜色转rgba + * @param {string} color 十六进制颜色 + * @param {string} opacity 透明度 + * @return {string} xxx rgba颜色 + */ + conversionRgba = (color: string, opacity: string): string | null => { + // exec() 方法用于检索字符串中的正则表达式的匹配。 + // 如果字符串中有匹配的值返回该匹配值,否则返回 null。 + let result: RegExpExecArray | null = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(color); + if (!result) { + return null; + } + return `rgba(${parseInt(result[1], 16)}, ${parseInt(result[2], 16)},${parseInt(result[3], 16)}, ${opacity})`; + }; + + /** + * 复制内容 + * @param {string} text 需要复制的内容 + */ + copyInfo = (text: string) => { + if (navigator?.clipboard) { + // this.copyInfo = () => { + navigator.clipboard?.writeText(text).then(() => { + msgTip.success(global.t('operate.copy')); + }); + // } + return; + } + // this.copyInfo = () => { + const iptCopy: HTMLInputElement = document.createElement('input'); + iptCopy.value = text; + document.body.appendChild(iptCopy); + iptCopy.select(); + msgTip.success(global.t('operate.copy')); + document.execCommand('Copy'); + iptCopy.remove(); + // } + // this.copyInfo(text); + }; + + // 搜索,短时间内连续点击搜索按钮只执行一次搜索函数(节流) + throttleFun = (fn: Function, wait = 500) => { + const that = this; + let last: number, + now: number; + return function () { + now = Date.now() + if (last && now - last < wait) { + last = now + } else { + last = now + fn.call(that, ...arguments) + } + } + } + + // 监听搜索框内容的变化,等输入完成才会执行搜索函数(防抖) + static debounceFun = (fn: Function, wait = 500) =>{ + let timer: number | null; + const that = this; + return function () { + let context = that; + let args = arguments; + if (timer) clearTimeout(timer); + timer = setTimeout(() => { + fn.apply(context, args) + }, wait) + } + } + + /** + * 数组去重 + * @param {Array} arr 传入的数组 + * + */ + uniaueArray = (arr: any) => { + if (!Array.isArray(arr)) { + throw new Error('传入的不是数组'); + } + const result = []; + // 表示它现在代表的某个循环 + outer: for (const item of arr) { + for (const r of result) { + if (this.#equal(item, r)) { + // 结束outer的循环 + continue outer; + } + } + result.push(item); + } + return result; + } + + isPrimitive = (val: unknown) => { + return val === null || (typeof val !== 'object' && typeof val !== 'function'); + } + + #equal = , K extends ArrayLike | { [s: string]: unknown; }>(a: T, b: K) => { + if (this.isPrimitive(a) || this.isPrimitive(b)) { + return Object.is(a, b); + } + const ent1 = Object.entries(a); + const ent2 = Object.entries(b); + if (ent1.length !== ent2.length) { + return false; + } + for (const [key, val] of ent1) { + // @ts-ignore + if (!this.equal(val, b[key])) { + return false + } + } + return true; + } + + getLastFiveDaysTime = () => { + const result = []; + for (let i = 0; i < 5; i++) { + // 计算一天毫秒数 + const timestamp = Date.now() - (1 * 24 * 60 * 60 * 1000) * i; + result.unshift(timestamp); + } + return result; + } + + beautifyLog = () => { + const isPre = ['pre', 'prod'].includes(process.env.VUE_APP_ENV); + const isEmpty = (value: string | null | undefined) => { + return ['', null, void 0].includes(value); + }; + const befautifyPrint = (title: string, text: string, color: string) => { + if (isPre) return; + if (typeof text !== 'string') { + console.log(title, text); + return; + } + console.log( + `%c ${title} %c ${text} %c`, + `background: ${color}; border: 1px solid ${color}; padding: 1px; border-radius: 2px 0 0 2px; color: #fff;`, + `border: 1px solid ${color}; padding: 1px; border-radius: 0 2px 2px 0; color: ${color};`, + `background: transparent` + ); + }; + + const info = (textInfo: string, content: string = '') => { + setPublicInfo(textInfo, content, 'Info', '#909399'); + }; + + const error = (textError: string, content: string = '') => { + setPublicInfo(textError, content, 'Error', '#f56c6c'); + }; + + const warning = (textWarning: string, content: string = '') => { + setPublicInfo(textWarning, content, 'Warning', '#e6a23c'); + }; + + const table = (data: T) => { + return console.table(data); + } + + const success = (textSuccess: string, content: string = '') => { + setPublicInfo(textSuccess, content, 'Success', '#67c23a'); + }; + + const setPublicInfo = (typeVal: string, content: string = '', type: string, color: string) => { + const title = isEmpty(content) ? type : typeVal; + const text = isEmpty(content) ? typeVal : content; + befautifyPrint(title, text, color); + } + + return { + info, + table, + error, + warning, + success + } + } +}; + +const methodsTotal = new MethodsTotal(); + +export { + methodsTotal +} +export default MethodsTotal; + + +/** + * 深拷贝 + * @param {Object | Array | number | string | null} target 需要拷贝的数据 + * @return {number | string | null | undefined} data 深拷贝的数据 + * @return {Object | Array} result 深拷贝的数据 +*/ +export function deepCopy(data: any[]) { + if (typeof data !== 'object' || !data) { + return data; + } + // 判断是数组还是对象 + const result: any = data instanceof Array ? [] : {}; + for (const key in data) { + // 只拷贝对象自身的属性 + if (data.hasOwnProperty(key)) { + result[key] = deepCopy(data[key]); + } + } + return result; +}; + +/** + * 获取cookie里面的语言 +*/ +const vueCookiesInfo = (VueCookies as any).get('X-Jdcloud-Language')?? 'zh_CN'; + +/** + * 语言切换 + * @return {string} zhCn | en 中文|英文 +*/ +export const languageSwitch = (): string | unknown => { + return vueCookiesInfo === 'zh_CN' ? zhCn : en; +}; + + +/** + * 实例状态文案颜色 + * @param {string} status 当前状态 + * @return {string} xxx.xxx 当前状态class类 +*/ +export const instanceStatusColor = (status: string) => { + const i18n: boolean = vueCookiesInfo === 'zh_CN'; + const defaultClass: string = 'def-status'; + const enDefaultClass: string = 'en-def-status'; + const statusColorData = [ + [ + (status: string) => !status?.length, + () => {return 'set-empty'} + ], + [ + (status: string) => ['created', 'Running', 'running'].indexOf(status) > -1, + () => {return i18n ? `${defaultClass} set-status-create` : `${enDefaultClass} set-status-create-en`} + ], + [ + (status: string) => ['in', 'putaway', 'removed'].indexOf(status) > -1, + () => {return i18n ? `${defaultClass} set-status-warehousing` : `${enDefaultClass} set-status-warehousing-en`} + ], + [ + (status: string) => ['error', 'Error', 'Mount failed', 'Creation failed', 'Startup failed', 'Shutdown failed', 'Reboot failed', 'Delete failed', 'Reinstall failed', 'Resetpasswd failed'].indexOf(status) > -1, + () => {return i18n ? `${defaultClass} set-status-error` : `${enDefaultClass} set-status-error-en`} + ], + [ + (status: string) => ['Shutting Down', 'destroyed', 'Destroyed', 'stopped'].indexOf(status) > -1, + () => {return i18n ? `${defaultClass} set-status-default` : `${enDefaultClass} set-status-default-en`} + ], + [ + (status: string) => status, + () => {return i18n ? `${defaultClass} set-status-on-down` : `${enDefaultClass} set-status-on-down-en`} + ] + ]; + for (const key of statusColorData) { + if (key[0](status)) { + return key[1](status); + } + } +}; + +/** + * 管理状态文案颜色 + * @param {string} status 当前状态 + * @return {string} xxx.xxx 当前状态class类 +*/ +export const managementStatusColor = (status: string) => { + const defaultClass: string = 'def-management-status'; + const statusColorData = [ + [ + (status: string) => !status?.length, + () => {return 'set-empty'} + ], + [ + (status: string) => ['created'].indexOf(status) > -1, + () => {return `${defaultClass} set-status-create`} + ], + [ + (status: string) => ['in', 'putaway', 'removed'].indexOf(status) > -1, + () => {return `${defaultClass} set-status-warehousing`} + ], + [ + (status: string) => ['putawayfail'].indexOf(status) > -1, + () => {return `${defaultClass} set-status-error`} + ], + [ + (status: string) => ['putawaying'].indexOf(status) > -1, + () => {return `${defaultClass} set-status-on-down`} + ] + ]; + for (const key of statusColorData) { + if (key[0](status)) { + return key[1](status); + } + } +}; + +/** + * 实例状态 + * @param {string} status 实例状态 + * @return {string} xxx 实例状态名称 +*/ +export const instanceStatus = (status: string) => { + const instanceStatusColorData = [ + [ + (status: string) => ['creating', 'Creating'].indexOf(status) > -1, + () => global.t('deviceList.instanceStatus.creating') + ], + [ + (status: string) => ['starting', 'Starting up'].indexOf(status) > -1, + () => global.t('deviceList.instanceStatus.starting') + ], + [ + (status: string) => ['running', 'Running'].indexOf(status) > -1, + () => global.t('deviceList.instanceStatus.running') + ], + [ + (status: string) => ['stopping', 'Shutting Down'].indexOf(status) > -1, + () => global.t('deviceList.instanceStatus.stopping') + ], + [ + (status: string) => ['stopped', 'Stopped'].indexOf(status) > -1, + () => global.t('deviceList.instanceStatus.stopped') + ], + [ + (status: string) => ['restarting', 'Restarting', 'Rebooting'].indexOf(status) > -1, + () => global.t('deviceList.instanceStatus.restarting') + ], + [ + (status: string) => ['resetting_password', 'Reset Password', 'Resetting password', 'resettingPassword'].indexOf(status) > -1, + () => global.t('deviceList.instanceStatus.resetting_password') + ], + [ + (status: string) => ['destroying', 'Destructing', 'Destroying'].indexOf(status) > -1, + () => global.t('deviceList.instanceStatus.destroying') + ], + [ + (status: string) => ['destroyed', 'Destroyed'].indexOf(status) > -1, + () => global.t('deviceList.instanceStatus.destroyed') + ], + [ + (status: string) => ['error', 'Error', 'Creation failed', 'Startup failed', 'Shutdown failed', 'Reboot failed', 'Delete failed'].indexOf(status) > -1, + () => global.t('deviceList.instanceStatus.error') + ], + [ + (status: string) => ['upgrading', 'Upgrading'].indexOf(status) > -1, + () => global.t('deviceList.instanceStatus.upgrading') + ], + [ + (status: string) => ['reinstalling', 'Reinstalling System'].indexOf(status) > -1, + () => global.t('deviceList.instanceStatus.reinstalling') + ] + ]; + + for(const key of instanceStatusColorData) { + if (key[0](status)) { + return key[1](status); + } + } +} + +export const tableClass = computed(() => (table: {[x: string]: string}[], isLoading: boolean): string => { + const defaultClass: string = 'operate-management-count-short-table'; + if (table?.length) { + if (isLoading) { + return `${defaultClass} img-show`; + } + return 'operate-management-count-table'; + } + else { + if (isLoading) { + return `${defaultClass} img-show`; + } + return `${defaultClass} img-empty`; + } +}); + +/** +* 设置文字class类 +* @param {boolean} type 当前的class是否高亮 true 是 false 否 +* @param {string} hasRight right class类 +* @return {string} xxx 返回对应的class类 +*/ +export const setTextClass: ComputedRef<{}> = computed(() => (type: boolean, hasRight = ''): string => { + if (type) { + return `currency-style ${hasRight}`; + } + return 'default-style'; +}); + +/** + * 设置宽度 + * @param {string} width1 宽度1 + * @param {string} width2 快读2 + * @param {Array} data 表格数据 + * @return {string} width1 width2 宽度1、宽度2 +*/ +export const setWidth: ComputedRef<{}> = computed(() => (width1: string, width2: string, data: unknown[]): string => { + if (data?.length) { + return width1; + } + return width2; +}); + +/** + * 过滤重复数据 + * @param {Array} data 需要过滤的数据 + * @return {Array} newArr 过滤完毕的数据 +*/ +export const filterData = (data: CurrencyType[], filterType: string) => { + const newArr: CurrencyType[] = [] + const map: Map = new Map(); + for (const item of data) { + if (!map.has(item[filterType])) { + map.set(item[filterType], true); + newArr.push( + { + [filterType]: item[filterType], + ...item + } + ); + } + } + return newArr; +}; + +/** + * 设置不同的样式 + * @param {string} className1 样式1 + * @param {string} className2 样式2 + * @return {string} className1 || className2 根据判断,返回className1 || className2 +*/ +export const setDiffClass: ComputedRef<{}> = computed(() => (className1: string, className2: string): string => { + if (vueCookiesInfo === 'en_US') { + return className1; + } + return className2; +}); + +export const hasShowTooltip = (event: Event, row: {showTooltip: boolean}, text: string, num: number = 2.3) =>{ + // event为鼠标移入时的事件对象 + // textWidth 为文本在页面中所占的宽度,创建标签,加入到页面,获取textWidth ,最后在移除 + const createSpan: HTMLSpanElement = document.createElement('span'); + // 文本内容 + createSpan.innerText = text; + // 文本class类 + createSpan.className = 'getTextWidth' + // body里添加 + document?.querySelector('body')?.appendChild(createSpan); + // 类型断言,获取文本offsetWidth + const textWidth: number = (document?.querySelector('.getTextWidth') as HTMLElement)?.offsetWidth; + // 移除 + document?.querySelector('.getTextWidth')?.remove(); + // tableWidth为表格容器的宽度、类型断言 + const tableWidth: number = (event?.target as HTMLElement)?.offsetWidth; + // 当文本宽度小于等于容器宽度两倍时,这块会有点小误差,根据业务来换算,代表文本显示未超过两行 + textWidth <= Math.ceil(num * tableWidth) ? row.showTooltip = false : row.showTooltip = true; +}; + +/** + * 获取日期 + * @return {string} xxx 年-月-日 +*/ +export const getDate = (): string => { + const year: number = new Date().getFullYear(); + const month: number = new Date().getMonth() + 1; + const day: number = new Date().getDate(); + return `${year}-${month}-${day}` +}; + +/** + * 获取日期 + * @return {string} xxx 年-月-日 +*/ +export const getDateParams = (params: string): string => { + const year: number = new Date(params).getFullYear(); + const month: number = new Date(params).getMonth() + 1; + const day: number = new Date(params).getDate(); + return `${year}-${month}-${day}` +}; + +/** + * 获取日期 + * @return {string} xxx 年-月-日 +*/ +export const getDateParamsNum = (params: number): string => { + const newParams: number = params * 1000; + const year: number = new Date(newParams).getFullYear(); + const month: number = new Date(newParams).getMonth() + 1; + const day: number = new Date(newParams).getDate(); + return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}` +}; + +/** + * 计算两个时间之间的时间差 多少天时分秒 + * @param {number} startTime 开始时间 + * @param {number} endTime 结束时间 + * @return {string} days hours 计算出相差天数 计算出小时数 +*/ +export const intervalTime = (startTime: number, endTime: number) => { + // 开始时间 + const date1 = startTime / 1000; + // 结束时间 + const date2 = endTime / 1000; + // 时间差的毫秒数 + const date3 = (date2- date1) * 1000; + // 计算出相差天数 + const days = Math.floor(date3 / (24 * 3600 * 1000)); + // 计算出小时数 + // 计算天数后剩余的毫秒数 + const leave1 = date3 % (24 * 3600 * 1000); + const hours = Math.floor(leave1 / (3600 * 1000)); + return { + days, + hours + } +} + + +/** + * 计算两个时间之间相差多少天 + * @param {number} preTime 开始时间戳 + * @param {number} endTime 结束时间戳 +*/ +export const returnInt = (startTime: number, endTime: number) => { + // 开始日期 + const startDate = new Date(startTime); + // 结束日期 + const endDate = new Date(endTime); + // if (endDate.getTime() > startDate.getTime()) { + // return ''; + // } + // Math.abs 返回数的绝对值,防止出错 + const diffDate = Math.abs(endDate.getTime() - startDate.getTime()); + // 1000 毫秒换算为1s + return Math.ceil(diffDate / (1000 * 60 * 60 * 24)); +} + +/** + * 获取日期时分秒 + * @return {string} xxx 年-月-日-时分秒 +*/ +export const getDateMinutes = (params: T): string => { + if ([undefined, null].includes((params as undefined))) return '--'; + const newParams: number = (params as number) * 1000; + const year: number = new Date(newParams).getFullYear(); + const month: number = new Date(newParams).getMonth() + 1; + const day: number = new Date(newParams).getDate(); + const hours: number = new Date(newParams).getHours(); + const minutes: number = new Date(newParams).getMinutes(); + const mill: number = new Date(newParams).getSeconds(); + return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${mill < 10 ? '0' + mill : mill}` +}; + +/** + * 获取日期时分 + * @return {string} xxx 月-日-时分 +*/ +export const getMonthHoursMinutes = (params: T): string => { + if ([undefined, null].includes((params as undefined))) return '--'; + const newParams: number = (params as number) * 1000; + // const year: number = new Date(newParams).getFullYear(); + const month: number = new Date(newParams).getMonth() + 1; + const day: number = new Date(newParams).getDate(); + const hours: number = new Date(newParams).getHours(); + const minutes: number = new Date(newParams).getMinutes(); + // const mill: number = new Date(newParams).getSeconds(); + return `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes} ${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}` +}; + +/** + * 生成随机数字 + * @param {number} num 随机数位数 + * @return {string} xxx 生成的随机数 +*/ +export const generateRandomNum = (num: number): string => { + let randomNum: string = '' + for(let i: number = 0; i < num; i++) { + randomNum += String(Math.floor(Math.random() * 10)); + } + return randomNum; +}; + +/** + * AES加密 +*/ +export const encrypt = (str: string, keyStr = 'ABCDEFGHIJKLMNOP', ivStr = '0123456789ABCDEF') => { + const key: string = CryptoJS.enc.Utf8.parse(keyStr); + const iv: string = CryptoJS.enc.Utf8.parse(ivStr); + const srcs: string = CryptoJS.enc.Utf8.parse(str); + const encrypt: {ciphertext: string} = CryptoJS.AES.encrypt(srcs, key, { + iv, + mode: CryptoJS.mode.CBC, // AES加密模式 + padding: CryptoJS.pad.Pkcs7 + }); + return CryptoJS.enc.Base64.stringify(encrypt.ciphertext); +}; + +/** + * AES解密 +*/ +export const decrypt = (str: string, keyStr = 'ABCDEFGHIJKLMNOP', ivStr = '0123456789ABCDEF') => { + const key: string = CryptoJS.enc.Utf8.parse(keyStr); + const iv: string = CryptoJS.enc.Utf8.parse(ivStr); + const base64: string = CryptoJS.enc.Base64.parse(str); + const src: string = CryptoJS.enc.Base64.stringify(base64); + const decrypt = CryptoJS.AES.decrypt(src, key, { + iv, + mode: CryptoJS.mode.CBC, // AES解密模式 + padding: CryptoJS.pad.Pkcs7 + }); + return decrypt.toString(CryptoJS.enc.Utf8).toString(); +}; + +export const tableScroll = (arg0: number, tableMaxHeight: {value: number}) => { + const titleNav: HTMLElement | null = document!.querySelector('.operate-header'); + const windowHeight: number = document.documentElement.clientHeight; + nextTick(() => { + tableMaxHeight.value = windowHeight - arg0 - titleNav!.offsetHeight; + }); +}; + +export const msgTip = ElMessage; + +export const customTip = (type: never, message: string, duration: number, fn: Function) => { + ElMessage({ + type, + message, + duration, + onClose: () => fn() + }); +}; diff --git a/bmp-operation-web/src/utils/publicClass.ts b/bmp-operation-web/src/utils/publicClass.ts new file mode 100644 index 0000000..fbea5f0 --- /dev/null +++ b/bmp-operation-web/src/utils/publicClass.ts @@ -0,0 +1,411 @@ +/** + * @file + * @author +*/ + +import store from 'store/index.ts'; +import i18n from 'lib/i18n/index.ts'; +import VueCookies from 'vue-cookies'; +import {useRouter} from 'vue-router'; +import {Router, CurrencyType, CurrencyType2, CurrencyType3, CurrencyType4, CustomInfoType, CheckListArrType, RequestParamsType} from '@utils/publicType'; +import RegularContent from 'utils/regular.ts'; +import {msgTip, customTip, getDate, encrypt, decrypt, tableScroll, languageSwitch, generateRandomNum} from 'utils/index.ts'; +import {AxiosError} from 'axios'; + +// 语言-使用国际化 +class Language { + t = i18n.global.t +}; +const language = new Language(); + +class TimerOperate { + timer: null | number = null; +}; +new TimerOperate(); + +// element-plus 国际化 +class UiLocale { + // 国际化 + locale: CurrencyType3 = languageSwitch(); +}; +// 实例化 +const uiLocale: UiLocale = new UiLocale(); + +class CurrentInstance { + proxy = getCurrentInstance()!.proxy; + // 使用mitt传值 + instanceMitt = getCurrentInstance(); +}; + +/** + * 国际化 +*/ +class LocationItem { + // cookie ts规范校验 + cookie: { + [x: string]: unknown; + get?: Function; + set?: Function; + } = VueCookies; + getLocationItem = (this.cookie?.get && this.cookie.get('X-Jdcloud-Language'))?? 'zh_CN'; +}; +const locationItem: LocationItem = new LocationItem(); + +/** + * 检查userPurview +*/ +class InspectuserPurview { + userPurview: {userPurview: string;} = store.userPurviewInfo(); + + /** + * 检查userPurview 状态 + */ + inspectuserPurview = () => { + // 'role-admin-uuid-01' + const {proxy}: any = getCurrentInstance(); + const hasStauts = localStorage?.getItem('userPurview')?? ''; + const status: string = (decrypt(hasStauts)); + if (!status || status !== proxy.$defInfo.purview('admin')) { + return Promise.reject(); + } + return Promise.resolve(); + }; +}; + +const inspectuserPurview: InspectuserPurview = new InspectuserPurview(); + +/** + * 路由操作 +*/ +class RouterOperate { + // 路由 + router: Router = useRouter(); + // 路由地址 + routerPath?: string = ''; + + proxy = new CurrentInstance().proxy; + + /** + * 构造器-接收实例化传递过来的值 + * @param {string} path 路由地址 默认机房列表 + */ + constructor (path?: string) { + this.routerPath = path?? this.proxy!.$defInfo.routerPath('idcDetail')!; + }; + + /** + * 跳转路由 + * @param {Object} query 路由参数 + */ + jumpRouter = (query: CurrencyType = {}): void => { + this.router.push({ + path: this.routerPath, + query: query?.status ? {} : query + }); + const encryInfo: string[] = this.proxy!.$defInfo.encryptDecrypt(1)!; + if (query?.status) sessionStorage.setItem(query?.type, encrypt(query.params, encryInfo[0], encryInfo[1])); + }; +}; + +/** + * 分页操作 +*/ +class PaginationOperate { + // 总条数 + total: Ref = ref(0); + // 当前页面页数条数 + pageSize: Ref = ref(20); + // 当前页面页数 + pageNumber: Ref = ref(1); + // 路由改变 + routerChange: Ref = ref(false); + + /** + * 分页操作 + * @param {number} count 每页展示条数、页数 + * @param {string} type size、num类型 + */ + paginationChange = (count: number, type: string) => { + this.routerChange.value = false; + const paginationData = [ + [ + (type: string) => !type.localeCompare('num'), + () => this.pageNumber.value = count + ], + [ + (type: string) => !type.localeCompare('size'), + () => { + this.pageSize.value = count; + this.pageNumber.value = 1; + } + ] + ]; + for (const key of paginationData) { + if (key[0](type)) { + key[1](type); + break; + } + } + }; +}; +// 实例化 +const paginationOperate: PaginationOperate = new PaginationOperate(); + +class UserCheck { + phoneNumberType: string = ''; + type: string = ''; + + constructor (phonePrefix: string = '', type: string = 'editUser') { + this.phoneNumberType = phonePrefix; + this.type = type; + }; + + /** + * 手机号正则 + * @param {Object} _ 占位符 + * @param {string} value 输入项 + * @param {Function} callback 回调函数,返回对应状态 + */ + phoneChcek: unknown = (_: CurrencyType3, value: string, callback: (arg0?: Error | string) => void) => { + const phoneArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t(`${this.type}.emptyTip.cellPhone`))) + ], + [ + (value: string) => (!/^[0-9]*$/.test(value)), + () => callback(new Error(language.t(`errorTip.title`))) + ], + [ + (value: string) => (!RegularContent.phoneReg.test(value) && Object.is(this.phoneNumberType, language.t('addUser.phoneData.China'))), + () => callback(new Error(language.t(`${this.type}.errorTip.cellPhone`))) + ], + [ + (value: string) => (!RegularContent.hongKongPhoneReg.test(value) && this.phoneNumberType.indexOf('852') > -1), + () => callback(new Error(language.t(`${this.type}.errorTip.HongKong`))) + ], + [ + (value: string) => (!RegularContent.aOmenPhoneReg.test(value) && this.phoneNumberType.indexOf('853') > -1), + () => callback(new Error(language.t(`${this.type}.errorTip.MacaMacao`))) + ], + [ + (value: string) => (!RegularContent.taiWanPhoneReg.test(value) && this.phoneNumberType.indexOf('886') > -1), + () => callback(new Error(language.t(`${this.type}.errorTip.Taiwan`))) + ], + [ + (value: string) => value, + () => callback() + ] + ]; + for (const key of phoneArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + /** + * 邮箱正则 + * @param {Object} _ 占位符 + * @param {string} value 输入项 + * @param {Function} callback 回调函数,返回对应状态 + */ + emailChcek: unknown = (_: CurrencyType3, value: string, callback: (arg0?: Error | string) => void) => { + const emailArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t(`${this.type}.emptyTip.email`))) + ], + [ + (value: string) => (!RegularContent.emailReg.test(value)), + () => callback(new Error(language.t(`${this.type}.errorTip.email`))) + ], + [ + (value: string) => value, + () => callback() + ] + ]; + for (const key of emailArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; +}; + +/** + * 自定义操作 +*/ +class CustomOperate { + pageKey: string = ''; // pageKey + customListDiaLog: Ref = ref(false); // 自定义列表蒙层 + customStore: { // store-操作自定义列表 + customList(arg0: string, arg1: CustomInfoType): unknown; + } = store.customInfo; + reactiveArr: { // 自定义列表数据 + checkListArr: CheckListArrType; + hasCustomInfo: CurrencyType4; + } = reactive<{ + checkListArr: CheckListArrType; + hasCustomInfo: CurrencyType4; + }>({ + hasCustomInfo: {}, // 列表显示状态 + checkListArr: [] // 角色列表自定义数据 + }); + + /** + * 构造器-接收实例化传递过来的值 + * @param {string} pageKey 自定义列表 pageKey + * @param {Object} hasCustomInfo 自定义信息 + * @param {Array} checkListArr 自定义列表数据 + */ + constructor ( + pageKey: string, + hasCustomInfo: CurrencyType4, + checkListArr: CheckListArrType + ) { + this.pageKey = pageKey; + this.reactiveArr.hasCustomInfo = hasCustomInfo; + this.reactiveArr.checkListArr = checkListArr; + this.getCustomList() + }; + + /** + * 获取自定义列表 + */ + getCustomList = () => { + this.customStore.customList(this.pageKey, this.reactiveArr); + }; + + /** + * 自定义取消操作 + * @return {boolean} xxx 自定义列表组件状态 + */ + customCancelOperate = (): boolean => { + return this.customListDiaLog.value = false; + }; + + /** + * 自定义点击操作-蒙层显示、隐藏 + * @return {boolean} xxx 蒙层状态 + */ + customClickOperate = (): boolean => { + return this.customListDiaLog.value = !this.customListDiaLog.value; + }; +}; + +/** + * 导出数据操作 +*/ +class ExportDataOperate { + exportDataDiaLog: Ref = ref(false); + downloadName: string = ''; + // hasExportData: Ref = ref(true); + requestUrl: Function = () => {}; + requestParams: RequestParamsType = {exportType: '1', isAll: '1'}; + templateParams: { + type: string; + } = { + type: '' + }; + + /** + * 构造器-接收实例化传递的参数 + * @param {Function} url 请求url地址 + * @param {Object} params 请求参数 + */ + constructor ( + url:(arg0: RequestParamsType) => Promise<{data: ResponseType}>, + params: CurrencyType2 = {}, + name: string = 'idc_list' + ) { + this.requestUrl = url; + if (params.type === 'template') { + this.templateParams = { + type: params.type + }; + return; + }; + this.requestParams = {...this.requestParams, ...params}; + this.downloadName = name; + }; + + diaLogClick = (): boolean => { + return this.exportDataDiaLog.value = !this.exportDataDiaLog.value; + }; + + exportCancel = (status: boolean): boolean => { + return this.exportDataDiaLog.value = status; + }; + + /** + * 导出数据 + */ + exportData = async (status: {cancelClick(): void; isLoading: {value: boolean}}) => { + const params = this.templateParams?.type ? {} : this.requestParams; + store.filterEmpty.deleteEmtpyData(params); + try { + const exportApi = await this.requestUrl(params); + msgTip({ + message: language.t('operate.success'), + type: 'success', + customClass: 'custom-message', + duration: 1000, + onClose: () => { + status.cancelClick(); + const blob: Blob = new Blob([exportApi.data]); + // 创建a标签 + let link = document.createElement('a'); + // 创建下载的链接 + link.href = window.URL.createObjectURL(blob); + // 下载后的文件名 + link.download = this.templateParams?.type ? 'device_import' : `${this.downloadName}_${getDate()}_${generateRandomNum(6)}.xlsx`; + // 点击下载 + link.click(); + // 释放这个url + window.URL.revokeObjectURL(link.href); + // store.progressInfo.progressNum = 100; + } + }) + } + catch (e) { + if (Object.is(e, void 0)) { + throw new Error('下载失败'); + } + const err = e as AxiosError; + customTip('error', err.message, 1000, () => status.isLoading.value = false); + } + }; +}; + + +class ScrollOperate { + + constructor(countHeight: number, tableMaxHeight: {value: number}) { + tableScroll(countHeight, tableMaxHeight); + this.onResize(countHeight, tableMaxHeight); + }; + + onResize = (countHeight: number, tableMaxHeight: {value: number}) => { + window.onresize = () => { + tableScroll(countHeight, tableMaxHeight); + }; + }; +}; + +export { + language, + uiLocale, + locationItem, + paginationOperate, + inspectuserPurview, + CurrentInstance, + UserCheck, + TimerOperate, + RouterOperate, + CustomOperate, + ScrollOperate, + ExportDataOperate +}; diff --git a/bmp-operation-web/src/utils/publicType.ts b/bmp-operation-web/src/utils/publicType.ts new file mode 100644 index 0000000..18804ea --- /dev/null +++ b/bmp-operation-web/src/utils/publicType.ts @@ -0,0 +1,160 @@ +/** + * @file + * @author +*/ + +import {Router, LocationQueryValue} from 'vue-router'; // 路由 路由value类 + +// 将类型转为字符串有一定的限制,仅支持以下类型 +export type CanStringified = string | number | bigint | boolean | null | undefined; + +// 将支持的类型转化为字符串 +export type Stringify = `${T}` + +export type SuccessType = {result: {success: boolean;}}; + +export const identity = (arg: T): T => { + return arg; +}; + +/** + * 通用状态类 +*/ +export type CurrencyStatusType = { + required: boolean; + selected: boolean; +}; + +export type CurrencyStatusType2 = { + disabled: boolean; + selected: boolean; +}; + +export interface OsStoreType { + filterParams: string; + showInfo?: string; + text: string; + value: number; +}; + +export type CurrencyType = {[x: string]: string;}; +export type CurrencyType1 = {[x: string]: string | boolean;}; +export type CurrencyType2 = {[x: string]: string | number;}; +export type CurrencyType3 = {[x: string]: unknown;}; +export type CurrencyType4 = {[x: string]: {selected: boolean;}}; +export type CurrencyType5 = {value: number; label: string;}; +export type CurrencyType6 = {name: string; label: string;}; +export type CurrencyType7 = {value: number; label: number;}; +export type CurrencyType8 = {value: string; label: string;}; +export type CurrencyType9 = {value: string | number; text: string;}; +export type PublicType6 = {name: number; label: string;}; + +export type StatusParamsType boolean> = T; + +export type StatusType boolean> = T; + +export type HeightType = {offsetHeight: number; offsetTop: number;}; + +export type HeightType2 = Pick; + +export type HeightType3 = {offsetHeight: number; scrollHeight: number;}; + +export type ListShowTooltipType = {[x: string]: {showTooltip?: boolean}}; + +/** + * 显示列表的数据类 +*/ +export type CheckBoxType = { + name: string; + checkbox: boolean; + disabled: boolean; +}; + +/** + * 自定义信息类 +*/ +export interface CustomInfoType { + hasCustomInfo?: Record; + checkListArr?: CheckBoxType[]; +}; + +// 显示列表的数据类 +export type CheckListArrType = CheckBoxType[]; + + +export interface RequestParamsType extends CurrencyType2 { + exportType: string; + isAll: string; +}; + +// 分页类 +export type PaginationType = Required<{ + pageNumber: number; + pageSize: number; +}>; + +export interface TabsDataType { + tabsPangeData: { + label: string; + name: string; + }[]; +}; + +// 添加用户 & 编辑用户 +export interface RuleFormRefType { + resetFields(): Function; + clearValidate(arg0: string): Function; + validateField(arg0: string, arg1: (valid: string) => void): Function; + validate(arg0: (valid: boolean) => void): Function; +}; + +export interface UpLoadsType { + submit(): Function; + clearFiles(): Function; + handleStart(arg0: CurrencyType): Function; + abort(): Function; +}; + +export type VerifyRulesType = { + required: boolean; + trigger?: string; + message?: string; + validator?: unknown; +}; + +export type SystemPartitionType = {format: string; point: string; size: number;}; + +export type CallbackType = (arg0?: Error | string) => void; + +export interface CpuDataType extends CurrencyType5 { + info: { + cpuAmount: number; + cpuCores: number; + cpuFrequency: string; + cpuManufacturer: string; + cpuModel: string; + } +}; + +export interface MemDataType extends CurrencyType5 { + info: { + memAmount: number; + memFrequency: number; + memSize: number; + memType: string; + } +}; + +/** + * 接收重复请求的数组类型 +*/ +export interface RepeatRequestArrType { + methodUrl: string; + params: CurrencyType3; + f: Function; +}; + +export { + Router, + LocationQueryValue +}; diff --git a/bmp-operation-web/src/utils/regular.ts b/bmp-operation-web/src/utils/regular.ts new file mode 100644 index 0000000..03e4234 --- /dev/null +++ b/bmp-operation-web/src/utils/regular.ts @@ -0,0 +1,43 @@ +/** + * @file + * @author +*/ + +class RegularContent { + // 中国大陆手机号正则 + static phoneReg: RegExp = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/; + // 中国香港手机号正则 + static hongKongPhoneReg: RegExp = /^([5|6|9])\d{7}$/; + // 中国澳门手机号正则 + static aOmenPhoneReg: RegExp = /^6\d{7}$/; + // 中国台湾手机号正则 + static taiWanPhoneReg: RegExp = /^[0][9]\d{8}$/; + // 邮箱正则 + static emailReg: RegExp = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + // 多邮箱正则 + static moreEmailReg: RegExp = /^((([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6}\,))*(([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})))$/; + // 名称正则 + static nameReg: RegExp = /^[-0-9a-zA-Z_]{1,64}$/; + // 名称正则 + static name1Reg: RegExp = /^[-0-9a-zA-Z_]{1,32}$/; + // 机型名称正则 + static modelNameReg: RegExp = /^(?:[-0-9a-zA-Z_]|[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0])+$/; + // 密码正则 + static passwordReg: RegExp = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[\d\*\(\)`~!@#\$%&_\-+=\|\{\}\[\]:\";\'<>,.\?\/\)])[a-zA-Z\d\*\(\)`~!@#\$%&_\-+=\|\{\}\[\]:\";\'<>,.\?\/\)]{8,30}$/; + // 只能输入正整数(包括0)、小数点保留两位小数 + static capacityReg: RegExp = /^(([0-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/; + // 只能输入正整数(包括0) + static numberReg: RegExp = /^([0]|[1-9][0-9]*)$/; + // 实例名称 + static instanceNameReg: RegExp = new RegExp('^[a-zA-Z\\\u4e00-\\\u9fa5]([0-9a-zA-Z\\\u4e00-\\\u9fa5-_.:]{1,127})$'); + // 特殊字符 + static specialCharacters: RegExp = /[\@\#\$\%\^\&\*\+\'{'\'}\=\[\]\【\】\)\)\(\(\!\!\`\~\·\;\;\"\,\.\,\。\?\?\、\——\\\>\<\》\《\|]/g; + // 主机名正则 + static hostNameReg: RegExp = /(^((?!(^[-.])|(-$)|(--+)|(\.$)|(\.\.+))[0-9A-Za-z-.{}]){2,64}$)|(^\s*$)/; + // 验证是否含有某一个字符串 + static hasEqualReg: (type: string) => RegExp = (type: string) => new RegExp(type); + // 数字-不包括0 + static NumReg: RegExp = /^([1-9][0-9]*)$/; +}; + +export default RegularContent; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/customList/custom.ts b/bmp-operation-web/src/views/deviceManagement/detail/customList/custom.ts new file mode 100644 index 0000000..b821ed0 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/customList/custom.ts @@ -0,0 +1,17 @@ +import {methodsTotal} from 'utils/index.ts'; +import {CustomOperate} from 'utils/publicClass.ts'; +import AllStaticData from 'staticData/staticData.ts'; // 自定义列表信息 自定义列表数据 + +const {deviceFaultLogInfo} = AllStaticData.allCustomListInfo; +const {deviceFaultLogList} = AllStaticData.allCustomList; + +const name: string = methodsTotal.humpConversion('deviceAlertLogList'); + +const custom = { + name, + CustomOperate, + deviceFaultLogInfo, + deviceFaultLogList +} + +export default custom; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/customList/listCustom.vue b/bmp-operation-web/src/views/deviceManagement/detail/customList/listCustom.vue new file mode 100644 index 0000000..37230e4 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/customList/listCustom.vue @@ -0,0 +1,22 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail.scss b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail.scss new file mode 100644 index 0000000..31a055f --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail.scss @@ -0,0 +1,146 @@ +@import '@/assets/css/detail.scss'; + +.device-detail { + .en-model-info { + .el-tabs__nav { + margin-left: -28px; + } + } + + .opt-logs-count { + .operate-log-list { + margin-bottom: 0; + } + } + + .collect-count { + cursor: pointer; + color: #108ee9; + + .collect-img { + width: 16px; + height: 16px; + margin-left: 15px; + } + } + + .zh-model-info { + .el-tabs__nav { + margin-left: 6px; + } + } + + .hardware-monitoring { + background: #fff !important; + + .info-title { + font-weight: $fontSmallWeight; + } + + .info-content { + display: flex; + flex-wrap: wrap; + + .hardware-device-status { + display: flex; + align-items: center; + // min-height: 3px; + background: #f7f7f7; + border-radius: 7px; + justify-content: center; + // justify-content: space-between; + padding: 7px 10px; + margin-right: 36px; + margin-bottom: 31px; + + .normal-background { + background: #43b561; + } + + .normal-title { + color: #43b561; + } + + .error-background { + background: #ff4d4f; + } + + .error-title { + color: #ff4d4f; + } + + .line { + width: 1.5px; + height: 18.5px; + background: #333; + flex-shrink: 0; + margin: 0 13px; + } + + span { + &:first-child { + font-size: 20px; + font-weight: 400; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + &:nth-child(3) { + width: 15px; + height: 15px; + border-radius: 50%; + flex-shrink: 0; + margin-right: 13px; + } + + &:last-child { + font-size: 18px; + // color: #43B561; + font-weight: 400; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + } + } + } + + .search-tip { + display: flex; + justify-content: flex-end; + // margin-top: 7px; + + .operate-management-content-operate { + margin-bottom: 16px !important; + padding: 0; + } + } + } + + .el-form-item__content { + align-items: flex-start; + } + + .switch-info { + .el-form-item__label { + width: 165px; + text-align: left; + line-height: 1.5; + } + + .ilo-count { + .el-form-item__label { + width: auto !important; + } + } + } + + &-tip-show { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + width: 160px; + display: inline !important; + } +} diff --git a/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail.vue b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail.vue new file mode 100644 index 0000000..9f2c807 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail.vue @@ -0,0 +1,143 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/clearRaid/clearRaid.vue b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/clearRaid/clearRaid.vue new file mode 100644 index 0000000..284ad66 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/clearRaid/clearRaid.vue @@ -0,0 +1,24 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/clearRaid/raidClear.ts b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/clearRaid/raidClear.ts new file mode 100644 index 0000000..f75cf74 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/clearRaid/raidClear.ts @@ -0,0 +1,37 @@ +/** + * @file + * @author +*/ + +class RaidClearOpt { + clearInfoDiaLog: Ref = ref(false); + checkboxStatus: Ref = ref(false); + deviceDetail: {initData(): void} + collectConfirmOpt: { + resetCollectInfoDiaLog: { + value: boolean; + } + }; + + constructor(collectConfirmOpt: {resetCollectInfoDiaLog: {value: boolean}}, deviceDetail: {initData(): void}) { + this.collectConfirmOpt = collectConfirmOpt; + this.deviceDetail = deviceDetail; + } + + clearInfoClick = (type: boolean) => { + this.checkboxStatus.value = type; + this.clearInfoDiaLog.value = true; + } + + clearRaidCancel = (type: boolean) => { + this.clearInfoDiaLog.value = type; + // this.collectConfirmOpt.resetCollectInfoDiaLog.value = true; + } + + clearRaidSure = () => { + this.clearInfoDiaLog.value = false; + this.deviceDetail.initData(); + } +} + +export default RaidClearOpt; \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/collectConfirm/collect.ts b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/collectConfirm/collect.ts new file mode 100644 index 0000000..53d29d7 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/collectConfirm/collect.ts @@ -0,0 +1,34 @@ +/** + * @file + * @author +*/ + +class CollectConfirmOpt { + resetCollectInfoDiaLog: Ref = ref(false); + fn; + deviceDetail: {initData(): void} + + constructor(deviceDetail: {initData(): void}, fn: Function) { + this.fn = fn; + this.deviceDetail = deviceDetail; + } + + collectClick = () => { + this.resetCollectInfoDiaLog.value = !this.resetCollectInfoDiaLog.value; + } + + resetCollectInfoCancel = (type: boolean) => { + this.resetCollectInfoDiaLog.value = type; + } + + resetCollectInfoSure = (type: boolean) => { + this.resetCollectInfoDiaLog.value = false; + this.fn(type); + } + + resetCollectSuccessClick = () => { + this.deviceDetail.initData(); + } +} + +export default CollectConfirmOpt; \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/collectConfirm/collectConfirm.vue b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/collectConfirm/collectConfirm.vue new file mode 100644 index 0000000..c345e00 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/collectConfirm/collectConfirm.vue @@ -0,0 +1,27 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/detail.ts b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/detail.ts new file mode 100644 index 0000000..7507784 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/detail.ts @@ -0,0 +1,186 @@ +/** + * @file + * @author +*/ + +import {TimerOperate, CurrentInstance, language} from 'utils/publicClass.ts'; +import {DetailType, TipStatusType, ShowPasswordType} from '../typeManagement'; +import {CurrencyType} from '@utils/publicType'; +import {msgTip} from 'utils/index.ts'; +import DeviceStaticData from 'staticData/device/index.ts'; // 中间态1 中间态2 +import {devicesDetailAPI, desrcibeAgentStatusAPI} from 'api/device/request.ts'; +import router from 'router/index.ts'; +import AllStaticData from 'staticData/staticData.ts'; +import store from 'store/index.ts'; + +class DeviceDetail extends TimerOperate { + isIntervalRequest: boolean = false; + isLoading: Ref = ref(true); + password: Ref = ref(''); + screenWidth: Ref = ref(0); + statusName: Ref = ref(''); + reactiveArr: DetailType & TipStatusType & ShowPasswordType = reactive({ + detail: {}, // 详情数据 + internetPort1: false, // 网口1交换机登录密码 + internetPort2: false, // 网口2交换机登录密码 + outLoginPassword: false, // 带外登录密码 + info: '', // 信息,用来显示对应明文显 + tooltipStatus: { + 'svInfo': { + showTooltip: false + }, + 'dvInfo': { + showTooltip: false + }, + 'switchPort1': { + showTooltip: false + }, + 'switchPort2': { + showTooltip: false + } + } + }); + verification: any; + proxy = getCurrentInstance()!.proxy; + instanceProxy = new CurrentInstance().proxy; + + constructor (verification: any) { + super(); + onUnmounted(() => clearTimeout((this.timer as number))); + onBeforeUnmount(() => clearTimeout((this.timer as number))); + this.verification = verification; + this.screenWidth.value = window.screen.width; + // this.getDeviceDetail(); + }; + + routerJump = () => { + // if (router.options.history.state.back !== null) { + // router.go(-1); + // return; + // } + const path: string = this.instanceProxy.$defInfo.routerPath('deviceList'); + router.push(path); + }; + + initData = () => { + this.isLoading.value = true; + this.getDeviceDetail(); + }; + + setCollected = (status: string) => { + const type = new Map([ + ['1', language.t('deviceDetail.status.collected')], + ['2', language.t('deviceDetail.status.noCollected')], + ['3', language.t('deviceDetail.status.collecting')], + ['4', language.t('deviceDetail.status.collectionFailed')] + ]); + return type.get(status); + } + + getDeviceDetail = () => { + clearTimeout((this.timer as number)); + const {value}: {value: string;} = this.password; + const params: {show?: string;} = value?.length ? {show: value} : {}; + devicesDetailAPI( + { + deviceId: router?.currentRoute?.value?.query?.deviceId, + ...params + } + ) + .then(({data} : {data: {result: CurrencyType;}}) => { + if (data?.result && Object.keys(data?.result)?.length) { + this.reactiveArr.detail = data.result; + if (params?.show) { + this.getPassword(params.show); + this.setPasswordStatus(params.show); + // new ShowPassword(this, this.verification).setPasswordStatus(params.show); + } + const hasLoopReq: boolean = [...DeviceStaticData.intermediate1, ...DeviceStaticData.intermediate2].some((item: string) => item === this.reactiveArr.detail.instanceStatus); + if (['putawaying'].some((item: string) => item === this.reactiveArr.detail.manageStatus) || hasLoopReq) { + this.timer = setTimeout(() => { + this.isLoading.value = false; + this.getDeviceDetail(); + this.isIntervalRequest = true; + }, 5000) + return; + } + this.isIntervalRequest = false; + return; + } + return Promise.reject(); + }).catch(({message} : {message: string;}) => { + const path: string = this.instanceProxy.$defInfo.routerPath('deviceList'); + if (AllStaticData.noFoundData.includes(message)) { + router.push(path); + return; + } + if (!this.isIntervalRequest) { + typeof message === 'string' && msgTip.error(message); + store.deviceDetailErrorTipInfo.errorStatus = Object.is(typeof message, 'string'); + this.reactiveArr.detail = {}; + return; + } + this.timer = setTimeout(() => { + this.isLoading.value = false; + this.getDeviceDetail(); + }, 5000) + }) + .finally(() => { + this.isLoading.value = false; + }); + }; + + desrcibeAgentStatus = () => { + desrcibeAgentStatusAPI({ + instanceId: router?.currentRoute?.value?.query?.instanceId + }) + .then(({data}: {data: {result: {agentStatus: {statusName: string; length: string; map(arg0: (item: { statusName: string; }) => string): {join(arg0: string): void}}}}}) => { + if (data?.result?.agentStatus?.length) { + // @ts-ignore + this.statusName.value = data.result.agentStatus.map((item: {statusName: string}) => item.statusName).join(','); + return; + } + return Promise.reject(''); + }) + .catch(() => { + this.statusName.value = ''; + }) + } + + setPasswordStatus = (show: string) => { + this.reactiveArr.outLoginPassword = show === 'iloPassword'; + this.reactiveArr.internetPort2 = show === 'switchPassword2'; + this.reactiveArr.internetPort1 = show === 'switchPassword1'; + }; + + /** + * 是否明文显示密码 + * @param {Object} item 当前点击的这一项 + * @param {string} type 当前点击的状态是 open or close + */ + hasPasswordClick = (bol: never | boolean, type: string, status: string, dataType: string = ''): void => { + clearTimeout((this.timer as number)); + this.password.value = dataType; + if (type === 'close') { + (this.reactiveArr[`${status}` as keyof typeof this.reactiveArr] as boolean) = bol; + this.password.value = ''; + this.reactiveArr.detail[dataType] = '********'; + return; + } + this.verification.securityVerificationDiaLog.value = !this.verification.securityVerificationDiaLog.value; + this.reactiveArr.info = status; + }; + + getPassword = (show: string) => { + const {switchPassword1, switchPassword2, iloPassword} = this.reactiveArr.detail; + const empty = this.proxy!.$filter.emptyFilter; + const params: Map = new Map([ + ['switchPassword1', empty(switchPassword1)], + ['switchPassword2', empty(switchPassword2)], + ['iloPassword', empty(iloPassword)] + ]); + this.reactiveArr.detail[show] = params.get(show); + }; +}; + +export default DeviceDetail; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/detail.vue b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/detail.vue new file mode 100644 index 0000000..5332772 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/detail.vue @@ -0,0 +1,780 @@ + + + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/notesEdit/edit.ts b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/notesEdit/edit.ts new file mode 100644 index 0000000..c5f8d88 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/notesEdit/edit.ts @@ -0,0 +1,34 @@ +interface DataType { + editNotesDiaLog: Ref; + descInfo: string; +}; + +const editNotesOperate = (deviceDetail: any) => { + const data: DataType = { + editNotesDiaLog: ref(false), + descInfo: String('') + }; + + const editNotesClick = () => { + data.descInfo = deviceDetail?.reactiveArr.detail.description; + data.editNotesDiaLog.value = !data.editNotesDiaLog.value; + }; + + const editNotesCacnel = (type: boolean) => { + data.editNotesDiaLog.value = type; + }; + + const editNotesSure = () => { + document.onkeyup = () => {return;} + deviceDetail.initData(); + }; + + return { + ...data, + editNotesClick, + editNotesCacnel, + editNotesSure + }; +}; + +export default editNotesOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/notesEdit/notesEdit.vue b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/notesEdit/notesEdit.vue new file mode 100644 index 0000000..fb0a7eb --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/notesEdit/notesEdit.vue @@ -0,0 +1,28 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/verification/verification.ts b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/verification/verification.ts new file mode 100644 index 0000000..1d90b7b --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/verification/verification.ts @@ -0,0 +1,26 @@ +const verificationOperate = (fn: any) => { + // 安全验证弹窗状态 + const securityVerificationDiaLog: Ref = ref(false); + + const verificationCancel = (type: boolean) => { + securityVerificationDiaLog.value = type; + }; + + /** + * 是否可以点击编辑操作 + * @param {boolean} type false 说明不可以在验证完安全校验后进行编辑操作 + */ + const hasEditOperateClick = (type: boolean): void => { + if (!type) { + fn() + } + }; + + return { + securityVerificationDiaLog, + verificationCancel, + hasEditOperateClick + }; +}; + +export default verificationOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/verification/verification.vue b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/verification/verification.vue new file mode 100644 index 0000000..e6c246b --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/deviceDetail/verification/verification.vue @@ -0,0 +1,22 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/diskDetail/diskTable.ts b/bmp-operation-web/src/views/deviceManagement/detail/diskDetail/diskTable.ts new file mode 100644 index 0000000..95ff918 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/diskDetail/diskTable.ts @@ -0,0 +1,77 @@ +/** + * @file + * @author +*/ +import {language} from 'utils/publicClass.ts'; +import {disksDetailAPI} from 'api/device/request.ts'; +import store from 'store/index.ts'; +import DeviceStaticData from 'staticData/device/index.ts'; +import {msgTip} from 'utils/index.ts'; + +class DiskTable { + isLoading: Ref = ref(true); + reactiveArr = reactive({ + disksData: [], + tableData: [], + volumesData: [] + }); + query: { + deviceId: string + } + + constructor(query: {deviceId: string}) { + this.query = query; + // this.init() + } + + init = () => { + this.isLoading.value = true; + this.getDiskDetail(); + } + + getDiskDetail = () => { + disksDetailAPI({ + deviceId: this.query.deviceId + }) + .then(({data}: any) => { + if (data?.result && Object.keys(data?.result).length) { + const {disks, panfu, volumes} = data.result; + volumes.forEach((item: any, index: number) => { + DeviceStaticData.modelInfoTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }) + }); + this.reactiveArr.volumesData = volumes.map((item: any) => { + return { + ...item, + newDisksVal: this.setDisks(item.disks) + } + }); + this.reactiveArr.disksData = disks; + this.reactiveArr.tableData = panfu; + } + }) + .catch(({message}: {message: string}) => { + if (!store.deviceDetailErrorTipInfo.errorStatus) { + message && msgTip.error(message); + } + }) + .finally(() => { + this.isLoading.value = false; + }) + } + + setDisks = (item: {name: string; size: string; sizeUnit: string}[]) => { + return item.map((t: {name: string; size: string; sizeUnit: string}) => t.name + ': ' + t.size + t.sizeUnit).join('; '); + } + + setRaids = (item: {name: string; raidId: string}[]) => { + return item.map((t: {name: string}) => t.name).join(','); + } + + setDiskInterfaceType = (item: string) => { + return item === 'notLimited' ? language.t('modelForm.unrestricted') : item; + } +} + +export default DiskTable; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/diskDetail/table.vue b/bmp-operation-web/src/views/deviceManagement/detail/diskDetail/table.vue new file mode 100644 index 0000000..163cd36 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/diskDetail/table.vue @@ -0,0 +1,354 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/dropDown.vue b/bmp-operation-web/src/views/deviceManagement/detail/drop/dropDown.vue new file mode 100644 index 0000000..5089285 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/dropDown.vue @@ -0,0 +1,275 @@ + + + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/dropDownOpt.ts b/bmp-operation-web/src/views/deviceManagement/detail/drop/dropDownOpt.ts new file mode 100644 index 0000000..973f8b8 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/dropDownOpt.ts @@ -0,0 +1,46 @@ +import DeviceStaticData from 'staticData/device/index.ts'; + +class DropDownOpt { + + up = (manageStatus: string): boolean => { + return ['in', 'putawayfail'].includes(manageStatus) + }; + + down = (manageStatus: string): boolean => { + return ['putaway'].includes(manageStatus); + }; + + stoppedStatus = (instanceStatus: string): boolean => { + return ['stopped'].includes(instanceStatus); + }; + + resetPasswordStatus = (instanceStatus: string): boolean => { + return ['stopped', 'Resetpasswd failed'].includes(instanceStatus); + }; + + resetSystemStatus = (instanceStatus: string): boolean => { + return ['stopped', 'Reinstall failed'].includes(instanceStatus); + }; + + running = (instanceStatus: string): boolean => { + return ['running'].includes(instanceStatus); + }; + + resetInstance = (instanceStatus: string) => { + return DeviceStaticData.resetInstance.includes(instanceStatus); + }; + + deviceRemove = (instanceStatus: string): boolean => { + return ['running', 'stopped', 'Resetpasswd failed', 'Reinstall failed'].includes(instanceStatus) + }; + + recoveryInstance = (instanceStatus: string, locked: string): boolean => { + return DeviceStaticData.recoveryInstance.includes(instanceStatus) && locked === 'unlocked'; + }; + + deviceDelete = (manageStatus: string): boolean => { + return ['in', 'putawayfail', 'removed'].includes(manageStatus); + }; +}; + +export default DropDownOpt; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/instanceReset/instanceReset.vue b/bmp-operation-web/src/views/deviceManagement/detail/drop/instanceReset/instanceReset.vue new file mode 100644 index 0000000..ff367f3 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/instanceReset/instanceReset.vue @@ -0,0 +1,20 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/instanceReset/operate.ts b/bmp-operation-web/src/views/deviceManagement/detail/drop/instanceReset/operate.ts new file mode 100644 index 0000000..fb31634 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/instanceReset/operate.ts @@ -0,0 +1,37 @@ +interface DataType { + instanceId: Ref; + resetInstanceDiaLog: Ref; + instanceName: Ref; +}; + +const resetInstanceOperate = (deviceDetail: any) => { + const data: DataType = { + instanceId: ref(''), + resetInstanceDiaLog: ref(false), + instanceName: ref('') + }; + + const resetInstanceClick = (id: string, name: string, status: boolean) => { + if (!status) return; + data.instanceId.value = id; + data.instanceName.value = name; + data.resetInstanceDiaLog.value = !data.resetInstanceDiaLog.value; + }; + + const resetInstanceCancel = (type: boolean) => { + data.resetInstanceDiaLog.value = type; + }; + + const resetInstanceSure = () => { + deviceDetail.initData(); + }; + + return { + ...data, + resetInstanceClick, + resetInstanceCancel, + resetInstanceSure + }; +}; + +export default resetInstanceOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/lockUnLock/lockUnLock.vue b/bmp-operation-web/src/views/deviceManagement/detail/drop/lockUnLock/lockUnLock.vue new file mode 100644 index 0000000..9c157b3 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/lockUnLock/lockUnLock.vue @@ -0,0 +1,22 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/lockUnLock/operate.ts b/bmp-operation-web/src/views/deviceManagement/detail/drop/lockUnLock/operate.ts new file mode 100644 index 0000000..a6672d1 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/lockUnLock/operate.ts @@ -0,0 +1,39 @@ +interface DataType { + lockDiaLog: Ref; + instanceName: Ref; + operate: Ref; + instanceId: Ref; +}; + +const lockDeblocking = (deviceDetail: any) => { + const data: DataType = { + lockDiaLog: ref(false), + instanceName: ref(''), + operate: ref(''), + instanceId: ref('') + }; + + const lock = (name: string, id: string, type: string) => { + data.instanceName.value = name; + data.operate.value = type; + data.instanceId.value = id; + data.lockDiaLog.value = !data.lockDiaLog.value; + }; + + const lockCancel = (type: boolean): boolean => { + return data.lockDiaLog.value = type; + }; + + const lockSure = () => { + deviceDetail.initData(); + }; + + return { + ...data, + lock, + lockCancel, + lockSure + }; +}; + +export default lockDeblocking; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/openCloseRestart/openCloseRestart.vue b/bmp-operation-web/src/views/deviceManagement/detail/drop/openCloseRestart/openCloseRestart.vue new file mode 100644 index 0000000..6070297 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/openCloseRestart/openCloseRestart.vue @@ -0,0 +1,22 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/openCloseRestart/operate.ts b/bmp-operation-web/src/views/deviceManagement/detail/drop/openCloseRestart/operate.ts new file mode 100644 index 0000000..4b2aa61 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/openCloseRestart/operate.ts @@ -0,0 +1,60 @@ +interface DataType { + title: Ref; + instanceId: Ref; + instanceInfo: Ref; + openShutDownRestartDiaLog: Ref; +}; + +const openCloseRestart = (deviceDetail: any) => { + const data: DataType = { + // 开机、关机、重启名称 + title: ref(''), + instanceId: ref(''), + // 开机、关机、重启实例信息 + instanceInfo: ref(''), + // 开机、关机、重启组件状态 + openShutDownRestartDiaLog: ref(false) + }; + + /** + * 开机、关机、重启点击事件 + * @param {string} item.instanceName 当前点击这一项实例 + * @param {string} type 当前点击这一项状态 + * @return {string} title.value 当前点击这一项的title标题 + */ + const openShutDownRestartClick = (instanceName: string, id: string, type: string, status: boolean): string | void => { + if (!status) return; + data.openShutDownRestartDiaLog.value = !data.openShutDownRestartDiaLog.value; + data.instanceInfo.value = instanceName; + data.instanceId.value = id; + switch(type) { + case 'open': + return data.title.value = '开机'; + case 'restart': + return data.title.value = '重启'; + default: + return data.title.value = '关机'; + }; + }; + /** + * 开机、关机、重启组件取消事件 + * @param {boolean} type 弹窗状态 + * @return {boolean} openShutDownRestartDiaLog.value 开机、关机、重启组件弹窗状态 + */ + const openShutDownRestartCancel = (type: boolean): boolean => { + return data.openShutDownRestartDiaLog.value = type; + }; + + const openShutDownRestartSure = () => { + deviceDetail.initData(); + }; + + return { + ...data, + openShutDownRestartClick, + openShutDownRestartCancel, + openShutDownRestartSure + }; +}; + +export default openCloseRestart; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/passwordReset/passwordReset.ts b/bmp-operation-web/src/views/deviceManagement/detail/drop/passwordReset/passwordReset.ts new file mode 100644 index 0000000..b872520 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/passwordReset/passwordReset.ts @@ -0,0 +1,31 @@ +import {CurrentInstance} from 'utils/publicClass.ts'; + +const resetPassword = (deviceDetail: any) => { + const resetPasswordDiaLog: Ref = ref(false); + const mitt = new CurrentInstance(); + + const resetPasswordClick = async (item: any) => { + if (!['stopped', 'Resetpasswd failed']) return; + resetPasswordDiaLog.value = !resetPasswordDiaLog.value; + await nextTick(() => { + mitt.instanceMitt?.proxy?.$Bus?.emit('reset-password',item); + }); + }; + + const resetPasswordCancel = (type: boolean) => { + resetPasswordDiaLog.value = type; + }; + + const resetPasswordSure = () => { + deviceDetail.initData(); + }; + + return { + resetPasswordDiaLog, + resetPasswordClick, + resetPasswordCancel, + resetPasswordSure + } +}; + +export default resetPassword; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/passwordReset/passwordReset.vue b/bmp-operation-web/src/views/deviceManagement/detail/drop/passwordReset/passwordReset.vue new file mode 100644 index 0000000..fece499 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/passwordReset/passwordReset.vue @@ -0,0 +1,18 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/recoveryRemove/operate.ts b/bmp-operation-web/src/views/deviceManagement/detail/drop/recoveryRemove/operate.ts new file mode 100644 index 0000000..69749f1 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/recoveryRemove/operate.ts @@ -0,0 +1,45 @@ +import {CurrentInstance} from 'utils/publicClass.ts'; +import {CurrencyType} from '@utils/publicType'; +// import {DeviceDetail} from '../../methods'; + +interface DataType { + removeRecoveryTitle: Ref; + removeRecoveryDiaLog: Ref; +}; + +const removeRecoveryOperate = (deviceDetail: any) => { + const data: DataType = { + // 设备移除、实例回收标题名称 + removeRecoveryTitle: ref(''), + // 设备移除、实例回收组件状态 + removeRecoveryDiaLog: ref(false) + }; + + const mitt = new CurrentInstance(); + + const removeRecoveryClick = async (item: CurrencyType, type: string, status: boolean): Promise => { + if (!status) return; + data.removeRecoveryDiaLog.value = !data.removeRecoveryDiaLog.value; + data.removeRecoveryTitle.value = type; + await nextTick(() => { + mitt.instanceMitt?.proxy?.$Bus?.emit('device-table', {list: item, type: 'removeRecovery'}); + }); + }; + + const removeRecoveryCancel = (type: boolean) => { + data.removeRecoveryDiaLog.value = type; + }; + + const removeRecoverySure = () => { + deviceDetail.initData(); + }; + + return { + ...data, + removeRecoveryClick, + removeRecoveryCancel, + removeRecoverySure + }; +}; + +export default removeRecoveryOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/recoveryRemove/recoveryRemove.vue b/bmp-operation-web/src/views/deviceManagement/detail/drop/recoveryRemove/recoveryRemove.vue new file mode 100644 index 0000000..098b7b6 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/recoveryRemove/recoveryRemove.vue @@ -0,0 +1,20 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/resetSystem/resetSystemConfirm.ts b/bmp-operation-web/src/views/deviceManagement/detail/drop/resetSystem/resetSystemConfirm.ts new file mode 100644 index 0000000..9c31ac0 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/resetSystem/resetSystemConfirm.ts @@ -0,0 +1,35 @@ +import {CurrentInstance} from 'utils/publicClass.ts'; +// fn: any +const resetSystemConfirmOperate = (resetSystemOpt: any) => { + const secondaryConfirmationDiaLog: Ref = ref(false); + const secondaryConfirmationName: Ref = ref(''); + const mitt = new CurrentInstance(); + let items: any = {} + const resetSystemConfirmClick = async(item: {instanceStatus: string; instanceName: string;}) => { + if (!['stopped', 'Reinstall failed'].includes(item.instanceStatus)) return; + secondaryConfirmationName.value = item.instanceName; + secondaryConfirmationDiaLog.value = !secondaryConfirmationDiaLog.value; + items = item; + }; + + const secondaryConfirmationCancel = (type: boolean) => { + secondaryConfirmationDiaLog.value = type; + }; + + const secondaryConfirmationSure = async () => { + resetSystemOpt.resetSystemDiaLog.value= true; + await nextTick(() => { + mitt.instanceMitt?.proxy?.$Bus?.emit('reset-system', {...items}); + }) + }; + + return { + resetSystemConfirmClick, + secondaryConfirmationName, + secondaryConfirmationDiaLog, + secondaryConfirmationCancel, + secondaryConfirmationSure + }; +}; + +export default resetSystemConfirmOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/resetSystem/resetSystemConfirm.vue b/bmp-operation-web/src/views/deviceManagement/detail/drop/resetSystem/resetSystemConfirm.vue new file mode 100644 index 0000000..cc12fcd --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/resetSystem/resetSystemConfirm.vue @@ -0,0 +1,19 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/resetSystem/systemReset.ts b/bmp-operation-web/src/views/deviceManagement/detail/drop/resetSystem/systemReset.ts new file mode 100644 index 0000000..29cedc1 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/resetSystem/systemReset.ts @@ -0,0 +1,24 @@ +const resetSystemOperate = (deviceDetail: any) => { + const resetSystemDiaLog: Ref = ref(false); + + const resetSystemClick = () => { + resetSystemDiaLog.value = !resetSystemDiaLog.value; + }; + + const resetSystemCancel = (type: boolean) => { + resetSystemDiaLog.value = type; + }; + + const resetSystemSure = () => { + deviceDetail.initData(); + }; + + return { + resetSystemClick, + resetSystemDiaLog, + resetSystemCancel, + resetSystemSure + }; +}; + +export default resetSystemOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/resetSystem/systemReset.vue b/bmp-operation-web/src/views/deviceManagement/detail/drop/resetSystem/systemReset.vue new file mode 100644 index 0000000..3dcffc2 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/resetSystem/systemReset.vue @@ -0,0 +1,18 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/upDownDelete/operate.ts b/bmp-operation-web/src/views/deviceManagement/detail/drop/upDownDelete/operate.ts new file mode 100644 index 0000000..33056a9 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/upDownDelete/operate.ts @@ -0,0 +1,57 @@ +import {CurrentInstance} from 'utils/publicClass.ts'; +import router from 'router/index.ts'; +// import {DeviceDetail} from '../../methods'; + +interface DataType { + upDownFrameTitle: Ref; + upDownFrameDiaLog: Ref; +}; + +const upDownDeleteOperate = (deviceDetail: any) => { + const data: DataType = { + // 上架、下架、删除设备标题名称 + upDownFrameTitle: ref(''), + // 上架、下架、删除设备组件状态 + upDownFrameDiaLog: ref(false) + }; + + const mitt = new CurrentInstance().instanceMitt; + + const instanceProxy = new CurrentInstance().proxy; + + /** + * 上架、下架、删除设备点击事件 + * @param {string} type 当前点击这一项状态 + */ + const upDownFrameClick = async (type: string, status: boolean): Promise => { + if (!status) return; + data.upDownFrameDiaLog.value = !data.upDownFrameDiaLog.value; + data.upDownFrameTitle.value = type; + await nextTick(() => { + mitt?.proxy?.$Bus?.emit('device-table', {list: deviceDetail.reactiveArr.detail}); + }); + }; + + const upDownDeleteCancel = (type: boolean) => { + data.upDownFrameDiaLog.value = type; + }; + + const operateClick = (type: string) => { + const path: string = instanceProxy.$defInfo.routerPath('deviceList'); + if (type === 'delete') { + clearTimeout((deviceDetail.timer as number)); + router.push(path); + return; + } + deviceDetail.initData(); + }; + + return { + ...data, + upDownFrameClick, + upDownDeleteCancel, + operateClick + }; +}; + +export default upDownDeleteOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/drop/upDownDelete/upDownDelete.vue b/bmp-operation-web/src/views/deviceManagement/detail/drop/upDownDelete/upDownDelete.vue new file mode 100644 index 0000000..3910cb5 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/drop/upDownDelete/upDownDelete.vue @@ -0,0 +1,25 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/customList/custom.ts b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/customList/custom.ts new file mode 100644 index 0000000..b821ed0 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/customList/custom.ts @@ -0,0 +1,17 @@ +import {methodsTotal} from 'utils/index.ts'; +import {CustomOperate} from 'utils/publicClass.ts'; +import AllStaticData from 'staticData/staticData.ts'; // 自定义列表信息 自定义列表数据 + +const {deviceFaultLogInfo} = AllStaticData.allCustomListInfo; +const {deviceFaultLogList} = AllStaticData.allCustomList; + +const name: string = methodsTotal.humpConversion('deviceAlertLogList'); + +const custom = { + name, + CustomOperate, + deviceFaultLogInfo, + deviceFaultLogList +} + +export default custom; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/customList/listCustom.vue b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/customList/listCustom.vue new file mode 100644 index 0000000..37230e4 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/customList/listCustom.vue @@ -0,0 +1,22 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/deviceStatus.vue b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/deviceStatus.vue new file mode 100644 index 0000000..9e17d22 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/deviceStatus.vue @@ -0,0 +1,30 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/export/export.ts b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/export/export.ts new file mode 100644 index 0000000..8e579e3 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/export/export.ts @@ -0,0 +1,19 @@ +import {consolelogsExportAPI} from 'api/device/request.ts'; +import {ExportDataOperate, RouterOperate} from 'utils/publicClass.ts'; + +class ExportData { + query = new RouterOperate().router.currentRoute.value.query + + exportData = (that: never) => { + new ExportDataOperate(consolelogsExportAPI, {sn: this.query.sn}, 'alarm_log_list').exportData(that); + } +}; + +// 实例化-导出数据操作 +const exportDataOperate = new ExportDataOperate(consolelogsExportAPI); + +export { + ExportData, + exportDataOperate +}; + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/export/exportData.vue b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/export/exportData.vue new file mode 100644 index 0000000..5ba5f94 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/export/exportData.vue @@ -0,0 +1,13 @@ + + + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/hardwareList.vue b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/hardwareList.vue new file mode 100644 index 0000000..7b4ac58 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/hardwareList.vue @@ -0,0 +1,67 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/methods.ts b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/methods.ts new file mode 100644 index 0000000..bca0168 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/methods.ts @@ -0,0 +1,15 @@ +/** + * @file + * @author +*/ + +const requireAll = (requireContext: T) => { + // keys 返回字典的所有的key + return requireContext.keys().map(requireContext); +} + +const methods = [ + ...requireAll(require.context('./', true, /^((?!methods|module|tableScroll|setEmpty).)*\.ts$/),) +] + +export default methods; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/module.ts b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/module.ts new file mode 100644 index 0000000..6685534 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/module.ts @@ -0,0 +1,16 @@ +/** + * @file + * @author +*/ + +const requireAll = (requireContext: T) => { + // keys 返回字典的所有的key + return requireContext.keys().map(requireContext); +} + +const pluginComp = [ + ...requireAll(require.context('./', true, /^((?!hardwareList).)*\.vue$/)) +]; + + +export default pluginComp.map((item) => item.default); diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/pagination/pagination.ts b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/pagination/pagination.ts new file mode 100644 index 0000000..faac646 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/pagination/pagination.ts @@ -0,0 +1,33 @@ +/** + * @file + * @author +*/ + +import {paginationOperate} from 'utils/publicClass.ts'; + +/** + * 分页监听 +*/ +class PaginationOperate { + + // 构造器 + constructor (faultLogTable: any) { + this.watchSizeNumber(faultLogTable); + }; + + /** + * 监听分页页数、条数变化 + */ + watchSizeNumber = (faultLogTable: any) => { + + watch(() => [ + paginationOperate.pageSize.value, + paginationOperate.pageNumber.value + ], (_: boolean[]): void => { + if (paginationOperate.routerChange.value) return; + faultLogTable.refresh(); + }); + }; +}; + +export default PaginationOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/pagination/pagination.vue b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/pagination/pagination.vue new file mode 100644 index 0000000..9c0a28b --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/pagination/pagination.vue @@ -0,0 +1,27 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/table/setEmpty.ts b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/table/setEmpty.ts new file mode 100644 index 0000000..467b927 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/table/setEmpty.ts @@ -0,0 +1,54 @@ +/** + * @file + * @author +*/ + +import {language} from 'utils/publicClass.ts'; + +const p: HTMLElement = document.createElement('p'); +interface PropsType { + faultLogTable: { + reactiveArr: { + tableData: [] + } + } +} + +class SetEmpty { + + constructor(props: PropsType) { + this.watchTableData(props); + onUnmounted(() => p.innerHTML = ''); + }; + + watchTableData = (props: PropsType) => { + watch(() => props?.faultLogTable?.reactiveArr.tableData, (newValue) => { + if (!newValue?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.remove(); + }, {deep: true}) + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + ai!.innerHTML = ''; + const customText = document.querySelector('.hardware-monitoring .el-scrollbar__view'); + if (!customText) return; + const str = ` + + ${language.t('table.empty')} + + ` + const parser = new DOMParser(); + const doc = parser.parseFromString(str, 'text/html'); + p.className = 'custom-tip-count'; + customText.appendChild(p) + p.innerHTML = doc.body.innerHTML; + }; +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/table/surveillance.ts b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/table/surveillance.ts new file mode 100644 index 0000000..6b1cc78 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/table/surveillance.ts @@ -0,0 +1,129 @@ +import {deviceStatusAPI} from 'api/device/request.ts'; +import {CurrencyType} from '@utils/publicType'; +import {language, CurrentInstance} from 'utils/publicClass.ts'; +import {methodsTotal} from 'utils/index.ts'; +import router from 'router/index.ts'; +import AllStaticData from 'staticData/staticData.ts'; + +class SurveillanceOpt { + isLoading: Ref = ref(true); + titlePrefix: string = 'deviceDetail.hardwareMonitoring.status.title'; + normal: string = language.t('deviceDetail.hardwareMonitoring.status.normal'); + error: string = language.t('deviceDetail.hardwareMonitoring.status.error'); + total: Ref = ref(0); + reactiveArr: any = reactive({ + tableData: [ + { + label: language.t(`${this.titlePrefix}.cpu`), + status: '--' + }, + { + label: language.t(`${this.titlePrefix}.storage`), + status: '--' + }, + { + label: language.t(`${this.titlePrefix}.hardDisk`), + status: '--' + }, + { + label: language.t(`${this.titlePrefix}.networkCard`), + status: '--' + }, + { + label: language.t(`${this.titlePrefix}.powerSupply`), + status: '--' + }, + { + label: language.t(`${this.titlePrefix}.other`), + status: '--' + } + ] + }); + query: {sn: string;}; + instanceProxy = new CurrentInstance().proxy; + faultLogTable: {refresh(): void}; + mitt = new CurrentInstance(); + deviceDetail; + + constructor (props: {query: {sn: string}, deviceDetail: {initData(): void}}, faultLogTable: {refresh(): void;}) { + this.query = props.query; + this.deviceDetail = props.deviceDetail; + this.faultLogTable = faultLogTable; + this.deviceDetail.initData(); + this.getDeviceStatus(); + this.watchLoading(); + }; + + watchLoading = () => { + watchEffect(() => { + this.mitt.instanceMitt?.proxy?.$Bus?.emit('device-detail-hardwareMonitoring-loading', this.isLoading) + }) + } + + getDeviceStatus = () => { + this.isLoading.value = true; + deviceStatusAPI({ + sn: this.query.sn + }).then(({data}: any) => { + if (data?.result?.detail?.length) { + const result = methodsTotal.lineConverting(data.result.detail[0]); + const newData = this.reactiveArr.tableData.map((item: {label: string; status: string;}) => { + return { + ...item, + status: this.#setLabel(item, result) + } + }) + this.reactiveArr.tableData = newData; + this.total.value = data.result.total_count; + return; + } + return Promise.reject(''); + }) + .catch(({message}: {message: string}) => { + const path: string = this.instanceProxy.$defInfo.routerPath('deviceList'); + if (AllStaticData.noFoundData.indexOf(message) > -1) { + router.push(path); + return; + } + this.total.value = 0; + }) + .finally(() => { + this.isLoading.value = false; + this.faultLogTable.refresh() + }); + }; + + #setLabel = (item: {label: string; status: string;}, keys: CurrencyType) => { + const key: Map = new Map([ + [language.t(`${this.titlePrefix}.cpu`), this.#valueConvert(keys['cpuStatus'])], + [language.t(`${this.titlePrefix}.storage`), this.#valueConvert(keys['memStatus'])], + [language.t(`${this.titlePrefix}.hardDisk`), this.#valueConvert(keys['diskStatus'])], + [language.t(`${this.titlePrefix}.networkCard`), this.#valueConvert(keys['nicStatus'])], + [language.t(`${this.titlePrefix}.powerSupply`), this.#valueConvert(keys['powerStatus'])], + [language.t(`${this.titlePrefix}.other`), this.#valueConvert(keys['otherStatus'])] + ]); + return key.get(item.label); + }; + + #valueConvert = (item: string) => { + return !item ? this.normal : this.error; + }; + + setBackgourdColor = (status: string) => { + const key: Map = new Map([ + [this.normal, 'normal-background'], + [this.error, 'error-background'] + ]); + return key.get(status); + }; + + setTextColor = (status: string) => { + const key: Map = new Map([ + [this.normal, 'normal-title'], + [this.error, 'error-title'] + ]); + return key.get(status); + }; +}; + +export default SurveillanceOpt; \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/table/table.ts b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/table/table.ts new file mode 100644 index 0000000..5735028 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/table/table.ts @@ -0,0 +1,74 @@ +import {consolelogsAPI} from 'api/device/request.ts'; +import {paginationOperate, language} from 'utils/publicClass.ts'; +import {msgTip, methodsTotal} from 'utils/index.ts'; +import DeviceStaticData from 'staticData/device/index.ts'; + +class FaultLogTable { + isTableLoading: Ref = ref(true); + reactiveArr: any = reactive({ + tableData: [] + }); + errorCode: Ref = ref(0); + query: {sn: string;}; + + constructor (query: {sn: string;}) { + this.query = query; + // this.getTableList(); + }; + + refresh = () => { + this.getTableList(); + }; + + getTableList = () => { + this.isTableLoading.value = true; + const params = methodsTotal.toLine({ + pageNum: paginationOperate.pageNumber.value, + pageSize: paginationOperate.pageSize.value + }); + consolelogsAPI({ + ...params, + sn: this.query.sn + }).then(({data}: any) => { + if (data?.result?.detail?.length) { + const newResult = methodsTotal.lineConverting(data.result); + newResult.detail.forEach((item: any, index: number) => { + DeviceStaticData.deviceFaultLogTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }) + }) + paginationOperate.total.value = newResult.totalCount; + this.reactiveArr.tableData = newResult.detail; + return; + } + return Promise.reject(''); + }) + .catch(({message}: {message: string}) => { + this.reactiveArr.tableData = []; + paginationOperate.total.value = 0; + if (['module license disabled'].includes(message)) { + return; + } + message && msgTip.error(message); + }) + .finally(() => this.isTableLoading.value = false); + }; + + setStatus = (status: number | string) => { + const val: string = String(status); + const newStatus = new Map([ + ['0', language.t('surveillance.status.no')] + ]); + return newStatus.get(val)?? language.t('surveillance.status.yes') + }; + + setColor = (status: number | string) => { + const val: string = String(status); + const newColor = new Map([ + ['0', '#ff4d4f'] + ]); + return newColor.get(val)?? '#43b561'; + }; +}; + +export default FaultLogTable; \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/table/tableList.vue b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/table/tableList.vue new file mode 100644 index 0000000..3d90786 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/table/tableList.vue @@ -0,0 +1,178 @@ + + + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/table/tableScroll.ts b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/table/tableScroll.ts new file mode 100644 index 0000000..d0b3f19 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/table/tableScroll.ts @@ -0,0 +1,92 @@ +import {HeightType2} from '@utils/publicType'; +import {tableScroll} from 'utils/index.ts'; +import store from 'store/index.ts'; +import {CurrentInstance} from 'utils/publicClass.ts'; + +class TableScrollOperate { + scrollTimer: null | number = null; + fixedHeight: Ref = ref(0); + tableMaxHeight: Ref = ref(0); + headerTitle: Ref = ref({offsetHeight: 0}); + operate: Ref = ref({offsetHeight: 0}); + searchHeight: Ref = ref({offsetHeight: 0}); + mitt = new CurrentInstance(); + tabsRef: Ref = ref({offsetHeight: 8}); + constructor () { + // this.activeOperate = activeOperate; + onMounted(() => { + // this.activeName.value = this.activeOperate.activeName.value; + // if (['basicInfo', 'diskDetail', 'operatLog'].includes(this.activeName.value)) return; + this.#watchNavBar(); + }) + // const type = this.router.currentRoute.value.query.type; + + // if (type === 'hardwareMonitoring') { + // this.#watchActive(this.router.currentRoute.value.query); + // } + // this.#watchActive(); + this.#resize(); + this.mitt.instanceMitt?.proxy?.$Bus?.on('device-detail-table-scroll', this.#resize); + this.mitt.instanceMitt?.proxy?.$Bus?.on('device-detail-hardwareMonitoring-loading', this.watchLoading); + onUnmounted(() => { + clearTimeout(this.scrollTimer as number); + this.mitt.instanceMitt?.proxy?.$Bus?.off('device-detail-table-scroll', this.#resize); + this.mitt.instanceMitt?.proxy?.$Bus?.on('device-detail-hardwareMonitoring-loading', this.watchLoading); + }) + }; + + getOperateRef = (val: {value: HeightType2;})=> { + this.operate.value = val.value; + }; + + getRef = (val: {value: HeightType2}) => { + this.tabsRef.value = val.value; + }; + + getSearchRef = (val: {value: HeightType2}) => { + this.searchHeight.value = val.value; + }; + + #watchNavBar = () => { + watch(() => store.navigationBarStatus.hasNavigationBar, (_: boolean) => { + this.scrollTimer = setTimeout(() => { + this.#setHeight() + }, 300) + }); + }; + + watchLoading = (newValue: {value: boolean}) => { + if (!newValue.value) { + this.#setHeight(); + } + } + // #watchActive = (query: {type: string}) => { + // watch(() => query, (newValue) => { + // if (newValue.type === 'hardwareMonitoring') { + // this.#setHeight(); + // } + // // this.activeName.value = newValue.value; + // }, {deep: true}); + // }; + + #resize = () => { + window.onresize = () => { + // if (['basicInfo', 'diskDetail', 'operatLog'].includes(this.activeName.value)) return; + this.#setHeight(); + }; + }; + + #setHeight = () => { + nextTick(() => { + this.fixedHeight.value = this.headerTitle.value.offsetHeight * 4.9 + this.operate.value.offsetHeight + this.tabsRef.value.offsetHeight + const countHeight = this.searchHeight?.value?.offsetHeight + this.fixedHeight.value; + tableScroll(countHeight, this.tableMaxHeight) + }) + }; + + getHeaderRef = (val: {value: HeightType2;}) => { + this.headerTitle.value = val.value; + }; +} + +export default TableScrollOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/titleInfo.vue b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/titleInfo.vue new file mode 100644 index 0000000..254e202 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/hardwareMonitoring/titleInfo.vue @@ -0,0 +1,22 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/methods.ts b/bmp-operation-web/src/views/deviceManagement/detail/methods.ts new file mode 100644 index 0000000..e15ff11 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/methods.ts @@ -0,0 +1,21 @@ +/** + * @file + * @author +*/ + +const requireAll = (requireContext: T) => { + // keys 返回字典的所有的key + return requireContext.keys().map(requireContext); +} + +const methods = [ + ...requireAll(require.context('./drop', true, /^((?!dropDownOpt).)*\.ts$/)), + ...requireAll(require.context('./tabs', false, /.ts$/)), + ...requireAll(require.context('./diskDetail', false, /.ts$/)), + ...requireAll(require.context('./deviceDetail', true, /.ts$/)), + ...requireAll(require.context('./modelsAssociated', false, /.ts$/)), + ...requireAll(require.context('./hardwareMonitoring/table', false, /tableScroll.ts$/)) +]; + + +export default methods.map(item => item.default); diff --git a/bmp-operation-web/src/views/deviceManagement/detail/modelsAssociated/associatedModel.ts b/bmp-operation-web/src/views/deviceManagement/detail/modelsAssociated/associatedModel.ts new file mode 100644 index 0000000..73a8f49 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/modelsAssociated/associatedModel.ts @@ -0,0 +1,28 @@ +/** + * @file + * @author +*/ + +class AssociatedModelOpt { + associatedModelDiaLog: Ref = ref(false); + deviceDetail; + + constructor(deviceDetail: {initData(): void}) { + this.deviceDetail = deviceDetail; + } + + associatedModelClick = () => { + this.associatedModelDiaLog.value = !this.associatedModelDiaLog.value; + } + + associatedModelCancel = (type: boolean) => { + this.associatedModelDiaLog.value = type; + } + + associatedModelSure = (diskTableOpt: {init(): void}) => { + this.deviceDetail.initData(); + diskTableOpt.init(); + } +} + +export default AssociatedModelOpt; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/modelsAssociated/modelsAssociated.vue b/bmp-operation-web/src/views/deviceManagement/detail/modelsAssociated/modelsAssociated.vue new file mode 100644 index 0000000..61229c2 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/modelsAssociated/modelsAssociated.vue @@ -0,0 +1,25 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/module.ts b/bmp-operation-web/src/views/deviceManagement/detail/module.ts new file mode 100644 index 0000000..c17af98 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/module.ts @@ -0,0 +1,22 @@ +/** + * @file + * @author +*/ + +const requireAll = (requireContext: T) => { + // keys 返回字典的所有的key + return requireContext.keys().map(requireContext); +} + +const pluginComp = [ + ...requireAll(require.context('./drop', true, /^((?!deviceDetail|pagination).)*\.vue$/)), + ...requireAll(require.context('./tabs', false, /.vue$/)), + ...requireAll(require.context('./diskDetail', false, /.vue$/)), + ...requireAll(require.context('./performanceMonitoring', false, /^((?!echartsPage|echartsBig).)*\.vue$/)), + ...requireAll(require.context('./deviceDetail', true, /.vue$/)), + ...requireAll(require.context('./modelsAssociated', true, /.vue$/)), + ...requireAll(require.context('./operatLog', false, /^((?!infoTitle).)*\.vue$/)), + ...requireAll(require.context('./hardwareMonitoring', false, /^((?!deviceStatus|titleInfo).)*\.vue$/)) +]; + +export default pluginComp.map(item => item.default); diff --git a/bmp-operation-web/src/views/deviceManagement/detail/operatLog/customList/custom.ts b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/customList/custom.ts new file mode 100644 index 0000000..a8f50ee --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/customList/custom.ts @@ -0,0 +1,10 @@ +/** + * @file + * @author +*/ + +import useCustom from 'hooks/custom/useCustom.ts'; + +const customOperate = useCustom('auditLogsList').info; + +export default customOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/operatLog/customList/listCustom.vue b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/customList/listCustom.vue new file mode 100644 index 0000000..cc38056 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/customList/listCustom.vue @@ -0,0 +1,9 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/operatLog/export/export.ts b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/export/export.ts new file mode 100644 index 0000000..438e605 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/export/export.ts @@ -0,0 +1,51 @@ +import {auditLogsExportAPI} from 'api/device/request.ts'; +import {ExportDataOperate} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; + +class ExportFilterData { + // 是否导出数据 + // hasExportData: Ref = ref(true); + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + // list: any; + ruleFormOperate: { + ruleForm: {} + }; + filter: { + filterParams: {} + }; + sn; + + constructor(sn: string, ruleFormOperate: { + ruleForm: {} + }, filter: { + filterParams: {} + }) { + this.sn = sn; + this.ruleFormOperate = ruleFormOperate; + this.filter = filter; + }; + + exportData = (that: never) => { + new ExportDataOperate(auditLogsExportAPI, {sn: this.sn}, 'audit_logs_list').exportData(that); + }; + + /** + * 参数处理 + */ + paramsProcessing = (that: never) => { + this.filterEmptyInfo.deleteEmtpyData({...this.filter.filterParams, ...this.ruleFormOperate.ruleForm}); + new ExportDataOperate(auditLogsExportAPI, { + sn: this.sn, + ...this.ruleFormOperate.ruleForm, + ...this.filter.filterParams + }, 'audit_logs_list').exportData(that); + } +}; + +export { + ExportFilterData, + ExportDataOperate, + auditLogsExportAPI +}; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/operatLog/export/exportData.vue b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/export/exportData.vue new file mode 100644 index 0000000..2b9f088 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/export/exportData.vue @@ -0,0 +1,23 @@ + + + diff --git a/bmp-operation-web/src/views/deviceManagement/detail/operatLog/formRules/formRules.vue b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/formRules/formRules.vue new file mode 100644 index 0000000..2e12561 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/formRules/formRules.vue @@ -0,0 +1,78 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/operatLog/formRules/ruleForm.ts b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/formRules/ruleForm.ts new file mode 100644 index 0000000..84e4482 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/formRules/ruleForm.ts @@ -0,0 +1,83 @@ +/** + * @file + * @author +*/ + +import {RuleFormRefType} from '@utils/publicType'; +// import {getDateParams} from 'utils/index.ts'; +import {paginationOperate} from 'utils/publicClass.ts'; + +class RuleFormOperate { + // 表单ref + ruleFormRef: Ref = ref(); + ruleForm = reactive({ + // name: '', + userName: '', + operateTime: '', + startTime: '', + endTime: '' + }) + searchParams = reactive({ + ...this.ruleForm + }); + fn; + + constructor(fn: Function) { + this.fn = fn; + } + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: RuleFormRefType}): void => { + this.ruleFormRef.value = formEl.value; + }; + + disabledDate = (time: Date) => { + return time.getTime() > Date.now() || time.getTime() < Date.now() - 3600 * 1000 * 24 * 90; + }; + + userNameChange = () => { + this.ruleForm.userName = this.ruleForm.userName?.replace(/\s*/g, ''); + } + + clearUserName = () => { + this.ruleForm.userName = ''; + this.searchClick(); + } + + dateChange = (val: string[] | null) => { + if (!val) { + this.ruleForm.startTime = ''; + this.ruleForm.endTime = ''; + this.searchClick(); + return; + }; + this.ruleForm.startTime = String(new Date(val[0]).getTime() / 1000); + this.ruleForm.endTime = String(new Date(val[1]).getTime() / 1000); + } + + searchClick = () => { + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn('search'); + }; + + clearClick = () => { + const that = this; + for (let key in this.ruleForm) { + (this.ruleForm[`${key}` as keyof typeof that.ruleForm] as string) = ''; + } + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn('clear'); + }; + +} + +export default RuleFormOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/operatLog/infoTitle.vue b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/infoTitle.vue new file mode 100644 index 0000000..fde71b1 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/infoTitle.vue @@ -0,0 +1,24 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/operatLog/operatLog.vue b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/operatLog.vue new file mode 100644 index 0000000..1d64399 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/operatLog.vue @@ -0,0 +1,97 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/operatLog/operateLog.scss b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/operateLog.scss new file mode 100644 index 0000000..b156a01 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/operateLog.scss @@ -0,0 +1,49 @@ +@import 'assets/css/listSearch.scss'; + +.opt-logs-count { + + .operate-log-count { + padding: 0 30px; + margin-top: 5px; + + .operate-management-content { + margin-top: 0; + } + + .operate-management-content-operate { + padding: 0; + } + + + .no-table-img-url { + padding: 5px 0 0; + margin-bottom: 0; + } + + .operate-log-list { + padding: 0; + background: $whiteBackground; + } + + .search-filter-tip { + margin-left: 0 !important; + } + + :deep(.el-range-editor.el-input__inner) { + width: 260px; + height: 30px; + } + + :deep(.operate-feedback) { + display: flex; + align-items: center; + justify-content: center; + margin-right: 18px; + + img { + margin: 0 10px; + } + } + } + +} diff --git a/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/filter.ts b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/filter.ts new file mode 100644 index 0000000..a6f4796 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/filter.ts @@ -0,0 +1,80 @@ +/** + * @file + * @author +*/ +import store from 'store/index.ts'; +import {paginationOperate} from 'utils/publicClass.ts'; + +class FilterOperate { + // store库存储的oss数据类 + ossStore = store.ossDataInfo() + tableRef: { + [x: string]: unknown; + value?: { + clearFilter(): unknown; + } + } = {value: {clearFilter(): void{}}}; + filterEmptyInfo: { // store + filterParams( + arg0: {[x: string]: number | string}, + arg1: any, + arg2: {filterParams: {result: string; operation: string}}, + arg3: {result: string; operation: string} + ): Promise; + deleteEmtpyData(arg0: {result: string; operation: string}): unknown; + } = store.filterEmpty; + // 复杂数据类型 + reactiveArr: { + filterParams: {result: string; operation: string}; + } = reactive<{ + filterParams: {result: string; operation: string}; + }>({ + filterParams: { + operation: '', + result: '' + } + }); + fn; + + constructor(fn: Function) { + this.fn = fn; + this.ossStore?.getAuditLogsTypes(); + } + + operationFilter = () => { + return true; + } + + resultFilter = () => { + return true; + } + + /** + * 获取表格ref + * @param {Object} tableEl 表格信息 + */ + getTableRef = (tableEl: {[x: string]: unknown}): void => { + this.tableRef = tableEl; + }; + + /** + * @param {Object} filter 需要过滤的数据 + */ + filterChange = (filter: {[x: string]: number | string}) => { + const filterParams = { + operation: 'operation', + result: 'result', + }; + this.filterEmptyInfo.filterParams(filter, this.ossStore, this.reactiveArr, filterParams) + .then((res: any) => { + this.reactiveArr.filterParams = res.filterParams; + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn(); + }); + }; +} + +export default FilterOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/filterStyle.ts b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/filterStyle.ts new file mode 100644 index 0000000..8be5c4c --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/filterStyle.ts @@ -0,0 +1,140 @@ +class FilterStyleOperate { + classNameData = [ + { + name: 'def-type-status13', + type: 'operation' + }, + { + name: 'def-type-status14', + type: 'result' + } + ]; + filterStatus: any = reactive({ + operation: false, + result: false + }) + + constructor (operateLog: any, filter: any) { + onMounted(() => { + nextTick(() => { + this.customFilter(operateLog, filter); + }) + this.watchSearchTip(operateLog, filter); + this.watchFilter(filter); + }) + }; + + watchSearchTip = (operateLog: any, filter: any) => { + watch(() => + operateLog.searchTip, (newValue) => { + if (!newValue.value) { + for (let index in this.filterStatus) { + this.filterStatus[index] = false; + } + } + else { + this.setFilterStatus(filter.reactiveArr.filterParams); + } + }, { + deep: true + }); + }; + + watchFilter = (filter: any) => { + watch(() => filter.reactiveArr.filterParams, (newValue) => { + this.setFilterStatus(newValue); + }, {deep: true}) + }; + + setFilterStatus = (params: any) => { + this.classNameData.forEach((item) => { + if (['', undefined].includes(params[item.type])) { + this.filterStatus[item.type] = false; + return; + } + this.filterStatus[item.type] = true; + }) + }; + + customFilter = (operateLog: any, filter: any) => { + let filterName: HTMLElement | null; + let filterOpt: HTMLElement | null; + this.classNameData.forEach((item) => { + filterName = document.querySelector(`.${item.name} > .cell`); + filterOpt = document.querySelector(`.${item.name} > .cell > .el-table__column-filter-trigger`) + filterName?.addEventListener('click', (event) => { + event.stopPropagation(); + for (let index in this.filterStatus) { + this.filterStatus[index] = false; + } + }) + filterOpt?.addEventListener('click', (event) => { + event.stopPropagation(); + if (!operateLog.searchTip.value) { + const clickStatus: any = { + 'operation': () => { + this.filterStatus['result'] = false; + }, + 'result': () => { + this.filterStatus['operation'] = false; + } + }; + clickStatus[item.type](); + } + this.filterStatus[item.type] = !this.filterStatus[item.type]; + }); + + const filterOtherRegion = document.querySelectorAll('.el-table-filter'); + filterOtherRegion.forEach((_, index) => { + filterOtherRegion[index]?.addEventListener('click', (event) => { + event.stopPropagation(); + for (let index in this.filterStatus) { + for (const key of this.classNameData) { + if (key.type === index && filter?.reactiveArr?.filterParams[key.type]?.length) { + this.filterStatus[index] = true; + } + } + } + }) + }) + let newType = []; + document.addEventListener('click', (event) => { + event.stopPropagation(); + newType = []; + newType.push(item.type); + newType.forEach((ite) => { + this.filterDispose(ite, filter, operateLog); + }) + }) + }) + }; + + filterDispose = (type: string, filter: any, operateLog: any) => { + const filterVal = filter.reactiveArr.filterParams; + const status = Object.values(filterVal).some((item) => item !== ''); + if (!status) { + this.filterStatus[type] = false; + return; + }; + if (operateLog.searchTip.value) { + for (let key in filterVal) { + if (key === type) { + this.filterStatus[key] = true; + } + else { + if (this.filterStatus[type] && Object.keys(filterVal).length > 1) { + this.filterStatus[type] = !this.filterStatus[type]; + } + else { + this.filterStatus[type] = false; + } + } + } + } + else { + this.filterStatus[type] = false; + } + } +}; + +export default FilterStyleOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/operateLog.ts b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/operateLog.ts new file mode 100644 index 0000000..d0d5674 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/operateLog.ts @@ -0,0 +1,125 @@ +/** + * @file + * @author +*/ +import {paginationOperate, language} from 'utils/publicClass.ts'; +import {auditLogsAPI} from 'api/device/request.ts'; +import {CurrencyType} from '@utils/publicType'; +import {msgTip} from 'utils/index.ts'; +import {AxiosError} from 'axios'; +import store from 'store/index.ts'; + +class OperateLog { + searchTip: Ref = ref(false); + isLoading: Ref = ref(true); // loading态 + reactiveArr: { + tableData: CurrencyType[] + } = reactive<{ + tableData: CurrencyType[] + }>({ + tableData: [] + }); + sn: string; + ruleFormOperate; + filter; + deviceDetail; + + + constructor(props: {sn: string; deviceDetail: {initData(): void;}}, ...args: any) { + this.sn = props.sn; + this.deviceDetail = props.deviceDetail; + this.ruleFormOperate = args[0]; + this.filter = args[1]; + this.deviceDetail.initData(); + this.getOperateLogList(); + } + + searchClear = () => { + for (let index in this.ruleFormOperate.ruleForm) { + // @ts-ignore + this.ruleFormOperate.ruleForm[index] = ''; + } + } + + setResult = (str: string | null) => { + if (str === null) return ''; + const obj = { + 'success': language.t('operate.success'), + 'fail': language.t('operate.fail'), + 'doing': language.t('operate.doing') + }; + return obj[`${str}` as keyof typeof obj]; + } + + resultSrc = (item: string | null, ...args: string[]) => { + if (item === null) return ''; + const obj = { + 'success': args[0], + 'fail': args[1], + 'doing': args[2] + }; + return obj[`${item}` as keyof typeof obj]; + } + + getOperateLogList = async () => { + this.isLoading.value = true; + const params = { + sn: this.sn, + pageNumber: paginationOperate.pageNumber.value, + pageSize: paginationOperate.pageSize.value, + ...this.filter.reactiveArr.filterParams, + ...this.ruleFormOperate.ruleForm + } + this.filter.filterEmptyInfo.deleteEmtpyData(params); + try { + const res: {data: {result: {messages: T; totalCount: K}}} = await auditLogsAPI(params); + if (res?.data?.result?.messages?.length) { + this.reactiveArr.tableData = res.data.result.messages; + paginationOperate.total.value = res.data.result.totalCount; + return; + } + throw new Error(''); + } + catch(e) { + this.reactiveArr.tableData = []; + paginationOperate.total.value = 0; + const err = e as AxiosError; + if (!store.deviceDetailErrorTipInfo.errorStatus) { + err?.message && msgTip.error(err.message); + } + } + finally { + this.isLoading.value = false; + this.searchTip.value = Object.keys(params).length > 3; + } + } + + refresh = () => { + if (!paginationOperate.total.value) { + this.searchClear(); + this.reset(); + return; + } + this.reqList(); + } + + reqList = () => { + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.getOperateLogList(); + } + + reset = () => { + this.searchClear(); + for (let index in this.filter.reactiveArr.filterParams) { + // @ts-ignore + this.filter.reactiveArr.filterParams[index] = ''; + } + this.filter?.tableRef?.value?.clearFilter(); + this.reqList(); + } +} + +export default OperateLog; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/setEmpty.ts b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/setEmpty.ts new file mode 100644 index 0000000..1d0880a --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/setEmpty.ts @@ -0,0 +1,50 @@ +/** + * @file + * @author +*/ + +import {language} from 'utils/publicClass.ts'; + +const p: HTMLElement = document.createElement('p'); + +class SetEmpty { + operateLog; + + constructor(operateLog: any) { + this.operateLog = operateLog; + // operateLog: any + this.watchTableData(); + onUnmounted(() => p.innerHTML = ''); + }; + + watchTableData = () => { + watch(() => this.operateLog?.reactiveArr.tableData, (newValue) => { + if (!newValue?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.remove(); + }) + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + ai!.innerHTML = ''; + const customText = document.querySelector('.operate-log-list .el-scrollbar__view'); + if (!customText) return; + const str = ` + + ${language.t('table.empty')} + + ` + const parser = new DOMParser(); + const doc = parser.parseFromString(str, 'text/html'); + p.className = 'custom-tip-count'; + customText.appendChild(p) + p.innerHTML = doc.body.innerHTML; + }; +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/tableList.vue b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/tableList.vue new file mode 100644 index 0000000..a0e7739 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/tableList.vue @@ -0,0 +1,135 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/tableScroll.ts b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/tableScroll.ts new file mode 100644 index 0000000..207a791 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/operatLog/table/tableScroll.ts @@ -0,0 +1,75 @@ +/** + * @file + * @author +*/ + +import {HeightType, HeightType2} from '@utils/publicType'; +import {tableScroll} from 'utils/index.ts'; +import {TimerOperate, CurrentInstance} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; + + +class TableScrollOperate extends TimerOperate { + tabsHeight: number = 116; + fixedHeight: Ref = ref(0); + tableMaxHeight: Ref = ref(0); + headerTitle: Ref = ref({offsetHeight: 60}); + operate: Ref = ref({offsetHeight: 0, offsetTop: 0}); + searchHeight: any; + infoHeaderHeight: any; + mitt = new CurrentInstance(); + + constructor () { + super(); + onMounted(async () => { + tableScroll(this.#setHeight(), this.tableMaxHeight); + await this.#watchNavBar(); + }); + this.#resize(); + onUnmounted(() => { + clearTimeout(this.timer); + }); + }; + + searchRef = (val: {value: {offsetHeight: number}}) => { + this.searchHeight = val; + }; + + infoHeaderRef = (val: {value: {offsetHeight: number}}) => { + this.infoHeaderHeight = val; + }; + + #watchNavBar = () => { + watch(() => store.navigationBarStatus.hasNavigationBar, (_: boolean) => { + this.timer = setTimeout(() => { + tableScroll(this.#setHeight(), this.tableMaxHeight); + }, 180) + }); + }; + + #resize = () => { + window.onresize = () => { + if (this.searchHeight?.value?.offsetHeight !== void 0) { + tableScroll(this.#setHeight(), this.tableMaxHeight); + return; + } + this.mitt.instanceMitt?.proxy?.$Bus?.emit('device-detail-table-scroll', 'hardwareMonitoring'); + }; + }; + + #setHeight = () => { + this.fixedHeight.value = (this.headerTitle?.value?.offsetHeight * 3) + this.operate?.value?.offsetHeight + this.tabsHeight; + const countHeight = this.searchHeight?.value?.offsetHeight + this.fixedHeight.value + this.infoHeaderHeight.value.offsetHeight; + return countHeight; + }; + + getHeaderRef = (val: {value: HeightType2;}) => { + this.headerTitle.value = val.value; + }; + + getOperateRef = (val: {value: HeightType;})=> { + this.operate.value = val.value; + }; +} + +export default TableScrollOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/page.ts b/bmp-operation-web/src/views/deviceManagement/detail/page.ts new file mode 100644 index 0000000..9d04ec6 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/page.ts @@ -0,0 +1,10 @@ +const DeviceDetail = () => import(/* webpackChunkName: "DeviceDetail" */ './deviceDetail.vue'); + +export default { + path: '/DeviceManagement/deviceDetail', + name: 'DeviceDetail', + component: DeviceDetail, + meta: { + type: 'deviceDetail' + } +}; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/css/deviceEcharts.scss b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/css/deviceEcharts.scss new file mode 100644 index 0000000..aa7c3ae --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/css/deviceEcharts.scss @@ -0,0 +1,71 @@ +@import 'assets/css/listSearch.scss'; + +.echarts-search-count { + .search-radio-count { + margin-bottom: 20px; + padding: 0 30px; + + :deep(.el-radio__label) { + display: flex; + align-items: center; + } + + :deep(.el-select) { + .el-input__inner { + width: 130px; + height: 30px; + margin-left: 10px; + } + } + + .common-img { + margin-left: 3px; + } + } + + .echarts-count { + display: flex; + flex-wrap: wrap; + padding: 0 30px; + + :deep(.el-loading-mask) { + border-radius: 8px; + } + } + + :deep(.seach-opt-count) { + display: flex; + margin: 18px 0 20px; + position: relative; + + .el-range-input { + font-size: $fontSize; + } + + .radio-active { + margin-right: 16px + } + + .el-range-editor { + height: 30px; + + .el-range-separator { + font-size: 12px; + } + } + + .operate-management-content-operate2 { + width: auto; + margin-bottom: 0 !important; + padding: 0 16px 0 30px; + + &-right { + margin-top: 0; + } + + .list-data-operate0 { + margin-right: 0; + } + } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/css/echartsBig.scss b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/css/echartsBig.scss new file mode 100644 index 0000000..efc9186 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/css/echartsBig.scss @@ -0,0 +1,100 @@ +.big-size-echarts { + width: 100%; + position: fixed; + background: rgba(212, 217, 221, .6); + z-index: 99; + height: 100%; + left: 0; + top: 0; + + .header { + width: 100%; + position: relative; + margin-top: 14px; + + .close-button { + width: 23px; + height: 23px; + position: absolute; + right: -12px; + top: -29px; + background: #fff; + + &:hover, + &:active, + &:focus { + background: #fff; + border-color: #fff; + color: #108ee9; + } + + .el-icon { + margin-left: 1px; + } + } + .title { + font-size: 14px; + color: #333; + margin-left: 30px; + margin-top: 9px; + margin-bottom: 9px; + } + + .count { + display: flex; + align-items: center; + font-size: 12px; + margin-left: 30px; + + p { + &:first-child { + margin-right: 20px; + } + } + + + :deep(.el-select) { + .el-input__inner { + width: 85px; + height: 18px; + font-size: 12px; + } + } + } + } + + .size-continer { + width: 75%; + // width: 100%; + height: 400px; + background-color: #fff; + box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .50); + border-radius: 10px; + position: absolute; + left: 50%; + top: 50%; + transform: translate(-50%, -50%); + display: flex; + flex-direction: column; + align-items: center; + } + + #bigSize { + // width: 980px; + width: 100%; + height: 300px; + + :deep(div) { + canvas { + padding: 0 30px !important; + } + } + // :deep { + // div { + // canvas { + // padding: 0 30px !important; + // } + // } + // } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/css/echartsPage.scss b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/css/echartsPage.scss new file mode 100644 index 0000000..c9f29a8 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/css/echartsPage.scss @@ -0,0 +1,85 @@ +.echart-bar { + width: 359px; + height: 314px; + background: #fff; + flex-direction: column; + border: 1.05px solid #d2d2d2; + border-radius: 8px; + display: flex; + align-items: flex-end; + margin-right: 26px; + margin-bottom: 20px; + + &:hover { + border-color: #108ee9; + + .header { + .big { + opacity: 1; + background-image: url('~@/assets/img/uiImg/big-size.png'); + background-size: 100% auto; + background-repeat: no-repeat; + transition: opacity 1s; + } + } + } + + .header { + width: 100%; + position: relative; + + .big { + position: absolute; + right: 20px; + top: 7px; + opacity: 0; + + &:hover { + cursor: pointer; + } + } + + .title { + font-size: 14px; + color: #333; + margin-left: 20px; + margin-top: 9px; + margin-bottom: 9px; + } + + .count { + display: flex; + align-items: center; + font-size: 12px; + margin-left: 20px; + + p { + &:first-child { + margin-right: 20px; + } + } + + :deep(.el-select) { + .el-input__inner { + width: 55px; + height: 18px; + font-size: 12px; + padding-right: 0; + } + + .el-input__suffix { + right: 4px; + transform: scale(.8); + } + } + } + } + + .echart-context { + top: -15px; + margin-top: 14px; + // width: 355px;; + width: 100%; + height: 243px; + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/echartsBig.vue b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/echartsBig.vue new file mode 100644 index 0000000..f8f4fd6 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/echartsBig.vue @@ -0,0 +1,63 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/echartsData.ts b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/echartsData.ts new file mode 100644 index 0000000..5e326c1 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/echartsData.ts @@ -0,0 +1,454 @@ +/** + * @file + * @author +*/ + +// import echarts from './utils/publicQuote'; +import RuleFormOpt from './utils/ruleForm'; +import publicConfigOpt from './utils/publicConfig'; +import InitStaticData from './utils/initStaticData'; +import {language} from 'utils/publicClass.ts'; +import {intervalTime, getMonthHoursMinutes} from 'utils/index.ts'; +import {publicOption, seriesDataObj, echartsOpt} from './options'; +import {monitorDataAPI, desrcibeTagsAPI} from 'api/device/request.ts'; +import * as echarts from 'echarts'; +import {NewDataType, NewTimeType, HourRangesType, ReactiveArrType, EchartsDataObjType} from './type'; + +class EchartsOpt extends RuleFormOpt { + cycle: Ref = ref('1min'); + readioSearch: Ref = ref(language.t('monitorEcharts.radio.instance')); + hours: Ref = ref(language.t('monitorEcharts.tabs.h1')); + value1: Ref = ref(''); + selectValForm = reactive({ + disk: [], + mountpoint: [], + nic: [] + }) + diskVal: Ref = ref(''); + mountpointVal: Ref = ref(''); + nicVal: Ref = ref(''); + reactiveArr: ReactiveArrType = reactive({ + aggregationMethod: publicConfigOpt.aggregationMethod, + isLoadingObj: {}, + echartsParamsData: InitStaticData.echartsParamsData, + // @ts-ignore + echartsData: InitStaticData.echartsData + }); + props; + fn; + + constructor(props: any, fn: Function) { + super(); + const that = this; + for (let index in this.ruleForm) { + (this.reactiveArr.isLoadingObj[`${index}` as keyof typeof that.reactiveArr.isLoadingObj] as boolean) = true; + } + this.props = props; + this.fn = fn; + this.initEchartsParamsData(); + this.watchDetail(); + this.watchRadio(); + this.watchHours(); + this.watchValue1(); + } + + watchValue1 = () => { + watch(() => this.value1, (newValue) => { + this.value1Val(newValue.value); + if (newValue.value?.length) { + this.hours.value = ''; + const {diskVal, mountpointVal, nicVal} = this; + let obj: Record = {}; + obj['diskVal'] = diskVal.value; + obj['mountpointVal'] = mountpointVal.value; + obj['nicVal'] = nicVal.value; + let str: string = ''; + let newValS: string = ''; + if (Object.is(this.readioSearch.value, language.t('monitorEcharts.radio.instance'))) { + str = ''; + } + else { + for (const index in obj) { + if (obj[index] !== '') { + str = index; + newValS = obj[index]; + } + } + } + this.strVal(str, newValS); + } + + }, {deep: true}) + } + + value1Val = (value: string) => { + if (value !== null) { + // intervalTime 计算两个时间之间的时间差 多少天时分秒 + const val = intervalTime(value[0], value[1]); + const objData = [ + [ + () => !val.days, + () => { + const hourRanges: HourRangesType = { + '0': '1min', + '6': '5min', + '12': '10min', + '24': '1min' + }; + // @ts-ignore + const cycleValue = hourRanges[Math.floor(val.hours / 6) * 6] || ''; + if (cycleValue?.length) { + this.cycle.value = cycleValue; + } + } + ], + [ + () => val.days, + () => { + this.cycle.value = val.days >= 14 ? '180min' : val.days >= 7 ? '120min' : val.days >= 3 ? '60min' : '20min'; + } + ] + ]; + outer: for (const key of objData) { + if (key[0]()!) { + key[1](); + break outer; + } + } + return; + } + this.hours.value = language.t('monitorEcharts.tabs.h1'); + this.cycle.value = '1min'; + } + + isLoading = (type: string) => { + const that = this; + return this.reactiveArr.isLoadingObj[`${type}` as keyof typeof that.reactiveArr.isLoadingObj]; + } + + strVal = (str: string, newValS: string) => { + if (!str?.length) { + this.initData(); + return; + } + const newData = this.reactiveArr.echartsData.filter((item) => item.status?.includes(str)); + for (const key of newData) { + this.getEcharts(key, 'small', {device: newValS}); + } + } + + watchHours = () => { + watch(() => this.hours, (newValue: {value: string}) => { + if (newValue.value.length) { + if (this.value1.value?.length) { + this.value1.value = '' + } + } + const val: {value: string} = InitStaticData.radioData.filter((item: {label: string}) => item.label === newValue.value)[0]; + if (!Object.is(val, void 0)) { + this.cycle.value = val.value; + this.refresh(); + } + }, { + deep: true + }) + } + + initEchartsParamsData = () => { + const that = this; + for (const key of this.reactiveArr.echartsParamsData) { + key.model = this.ruleForm[`${key.type}` as keyof typeof that.ruleForm]; + key.bigClickVal.model = this.ruleForm[`${key.type}` as keyof typeof that.ruleForm]; + } + } + + watchDetail = () => { + watch(() => this.props.deviceDetail.reactiveArr.detail, () => { + this.initData(); + }, { + deep: true + }) + } + + watchRadio = () => { + watch(() => this.readioSearch, (newValue: {value: string}) => { + const objData = [ + [ + (value: string) => Object.is(value, language.t('monitorEcharts.radio.instance')), + () => { + this.diskVal.value = ''; + this.nicVal.value = ''; + this.mountpointVal.value = ''; + this.initData(); + } + ], + [ + (value: string) => Object.is(value, language.t('monitorEcharts.radio.disk')), + (value: string) => { + this.nicVal.value = ''; + this.mountpointVal.value = ''; + this.initTagName(this.getTagName(value)!, 1) + } + ], + [ + (value: string) => Object.is(value, language.t('monitorEcharts.radio.diskPartition')), + (value: string) => { + this.diskVal.value = ''; + this.nicVal.value = ''; + this.initTagName(this.getTagName(value)!, 2) + } + ], + [ + (value: string) => Object.is(value, language.t('monitorEcharts.radio.netWorkInterface')), + (value: string) => { + this.diskVal.value = ''; + this.mountpointVal.value = ''; + this.initTagName(this.getTagName(value)!, 3) + } + ] + ] + outer: for (const key of objData) { + // @ts-ignore + if (key[0](newValue.value)) { + key[1](newValue.value) + break outer; + } + } + }, {deep: true}) + } + + initData = () => { + if (Array.isArray(this.reactiveArr.echartsData)) { + for (const key of this.reactiveArr.echartsData) { + // 循环体 + this.getEcharts(key); + } + } + else { + throw new Error('数据格式出错,不是一个数组') + } + } + + refresh = () => { + const value = this.readioSearch.value; + const objData = [ + [ + () => Object.is(value, language.t('monitorEcharts.radio.instance')), + () => this.initData() + ], + [ + () => Object.is(value, language.t('monitorEcharts.radio.disk')), + () => this.disk(this.diskVal.value) + ], + [ + () => Object.is(value, language.t('monitorEcharts.radio.diskPartition')), + () => this.mountpoint(this.mountpointVal.value) + ], + [ + () => Object.is(value, language.t('monitorEcharts.radio.netWorkInterface')), + () => this.nic(this.nicVal.value) + ] + ]; + for (const key of objData) { + if (key[0]()!) { + return key[1](); + } + } + } + + getTagName = (value: string) => { + const tagName = new Map([ + [language.t('monitorEcharts.radio.disk'), 'disk'], + [language.t('monitorEcharts.radio.diskPartition'), 'mountpoint'], + [language.t('monitorEcharts.radio.netWorkInterface'), 'nic'] + ]); + return tagName.get(value); + } + + disabledDate = (time: any) => { + return time.getTime() > Date.now() || time.getTime() < Date.now() - 3600 * 1000 * 24 * 30; + } + + disk = (val: string) => { + this.selectData('diskVal', val); + } + + mountpoint = (val: string) => { + this.selectData('mountpointVal', val); + } + + nic = (val: string) => { + this.selectData('nicVal', val); + } + + selectData = (type: string, val: string) => { + const newData = this.reactiveArr.echartsData.filter((item) => item.status?.includes(type)); + for (const key of newData) { + this.getEcharts(key, 'small', {device: val}); + } + } + + initTagName = async (tagName: string, value: number) => { + const queryParams = new URLSearchParams(location.search); + const instanceId: string = queryParams.get('instanceId') as string;instanceId; + const that = this; + const params = { + instanceId, + tagName + }; + try { + const res = await desrcibeTagsAPI(params); + if (res?.data?.result?.length) { + this.selectValForm[`${tagName}` as keyof typeof that.selectValForm] = res.data.result; + const v = Object.is(value, 1) ? 'diskVal' : Object.is(value, 2) ? 'mountpointVal' : 'nicVal'; + this[v].value = res.data.result[0]; + // const val = this[value].value; + const val = this[v].value; + this.mountpointVal.value?.length && this.mountpoint(val); + this.diskVal.value?.length && this.disk(val); + this.nicVal.value?.length && this.nic(val); + } + } + catch { + throw new Error('error'); + } + } + + getEcharts = async (key: T, size = 'small', selectParams: any = {}) => { + Object.is(size, 'small') ? this.setLoading(key.typeVal, true) : this.fn(true); + const queryParams = new URLSearchParams(location.search); + const instanceId: string = queryParams.get('instanceId') as string;instanceId; + const param = { + metricName: this.getMetricName(key), + instanceId, + ...selectParams, + // 周期 + timeInterval: Number(this.cycle.value.split('min')[0]) * 60, + } + const otherParams = !this.value1.value ? {lastManyTime: Number(this.setTabsParams())} : this.setDateParams(); + try { + const allParams = { + ...param, + ...otherParams, + downSampleType: key.aggregationMethod + } + const res = await monitorDataAPI(allParams); + if (res?.data?.result?.length) { + if (!['main6', 'main7', 'main8', 'main9'].includes(key.id)) { + const [data] = res.data.result; + const initTimeData = data.data.map((item: {timestamp: number}) => (item.timestamp)); + key.data = data.data.map((item: {value: string}) => parseFloat(Number(item.value).toFixed(2))); + key.timeData = data.data.map((item: {timestamp: number}) => getMonthHoursMinutes(item.timestamp)); + this.setData(key, size, initTimeData); + } + else { + const newData: NewDataType[] = Array.from(res.data.result, (item: {data: {map: NewDataType['map']}}) => { + return item.data.map((ite: {value: string}) => { + const value = parseFloat(ite.value); + return isNaN(value) ? NaN : value; + }); + }); + const newTimes: NewTimeType[] = Array.from(res.data.result, (item: {data: {map: NewTimeType['map']}}) => { + return item.data.map((ite: {timestamp: number}) => getMonthHoursMinutes(ite.timestamp)); + }); + const newArrData = newData.map((item) => { + return item.map((t) => parseFloat(Number(t).toFixed(2))) + }); + const initTimes: NewTimeType[] = Array.from(res.data.result, (item: {data: {map: NewTimeType['map']}}) => { + return item.data.map((ite: {timestamp: number}) => (ite.timestamp)); + }); + key.data = newArrData; + key.timeData = [newTimes[0]]; + this.setData(key, size, initTimes[0]); + } + return; + } + throw new Error(''); + } + catch { + key.data = []; + key.timeData = []; + this.setData(key, size, []); + } + finally { + Object.is('bigSize', size) ? this.fn(false) : this.setLoading(key.typeVal, false); + } + } + + getMetricName = (key: T) => { + if (this.mountpointVal.value?.length) { + return key.paramsMetricName; + } + return typeof key.metricName === 'string' ? key.metricName : key.metricName.join(',') + } + + setLoading = (type: string, bol: boolean) => { + const that = this; + for (let index in this.reactiveArr.isLoadingObj) { + if (index === type) { + (this.reactiveArr.isLoadingObj[`${index}` as keyof typeof that.reactiveArr.isLoadingObj] as boolean) = bol; + } + } + } + + setDateParams = () => { + return { + startTime: new Date(this.value1.value[0]).getTime() / 1000, + endTime: new Date(this.value1.value[1]).getTime() / 1000 + }; + } + + setTabsParams = () => { + const obj = new Map([ + [language.t('monitorEcharts.tabs.h1'), '1'], + [language.t('monitorEcharts.tabs.h6'), '6'], + [language.t('monitorEcharts.tabs.h12'), '12'], + [language.t('monitorEcharts.tabs.d1'), '24'], + [language.t('monitorEcharts.tabs.d3'), '72'], + [language.t('monitorEcharts.tabs.d7'), '168'], + [language.t('monitorEcharts.tabs.d14'), '336'] + ]) + return obj.get(this.hours.value); + } + + setData = (key: any, size: string, data: number[] | NewTimeType) => { + let id: string = ''; + nextTick(() => { + if (document.getElementById(key.id)) { + id = Object.is(size, 'small') ? key.id : 'bigSize'; + this.reqEcharts(id, key.data, key.type, key.timeData, key.unit, key.hoverUnit, data) + } + }) + } + + reqEcharts = (id: string, ...args: any) => { + const newData = !Array.isArray(args[1]) ? [ + seriesDataObj(args[1], args[0], publicConfigOpt.singleColor) + ] : [ + ...this.setEcharts(args[1], args[0]) + ]; + const myChart = echarts?.getInstanceByDom(document.getElementById(id) as HTMLElement); + publicOption([args[1]], args[2], args[3], newData, args[0], args[4], id, args[5]).then((res: any) => { + echartsOpt(res, id, myChart); + }) + .catch((err) => { + throw new Error(err) + }) + } + + setEcharts = (data: string[], args: number[][]) => { + let newData = []; + for (let i = 0; i < data.length; i++) { + newData.push(seriesDataObj(data[i], args[i], publicConfigOpt.moreColor[i])); + } + return newData; + } + + selectChange = (val: string, value: string) => { + const that = this; + this.ruleForm[`${val}` as keyof typeof that.ruleForm] = value; + publicConfigOpt.smallBigSet(that as any, val, 'small', value); + } +} + +export default EchartsOpt; \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/echartsPage.vue b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/echartsPage.vue new file mode 100644 index 0000000..c777bdc --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/echartsPage.vue @@ -0,0 +1,64 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/options.ts b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/options.ts new file mode 100644 index 0000000..8b5ac24 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/options.ts @@ -0,0 +1,223 @@ +/** + * @file + * @author +*/ + +// import echarts from './utils/publicQuote'; +import * as echarts from 'echarts'; + +const kb: number = 1000; +const mb: number = kb * 1000; +const gb: number = mb * 1000; +const tb: number = gb * 1000; +const pb: number = tb * 1000; +const eb: number = pb * 1000; + +const reg = (str: string) => str.replace(/\.00$/, ''); +let newMyChart: any; +const publicOption = (legendData: string[], ...args: any) => { + const status = Object.is(args[5], 'bigSize'); + return new Promise((resolve) => { + resolve({ + title: { + top: '10px', + textStyle: { + fontSize: 14 + } + }, + tooltip: { + trigger: 'axis', + formatter: function (params: {seriesName: string; value: number; color: string; axisValue: string;}[]) { + let res: string = ''; + for (let i = 0, l = params.length; i < l; i++) { + const yearSecond = new Date(args[6][i] * 1000); + const yearSecondZero = new Date(args[6][0] * 1000); + const monthDateTime = params[i].axisValue.replace(/\n/g, ','); + const seconds = isNaN(yearSecond.getSeconds()) ? yearSecondZero.getSeconds() < 10 ? '0' + yearSecondZero.getSeconds() : yearSecondZero.getSeconds() : yearSecond.getSeconds() < 10 ? '0' + yearSecond.getSeconds() : yearSecond.getSeconds(); + res += `

${isNaN(yearSecond.getFullYear()) ? yearSecondZero.getFullYear() : yearSecond.getFullYear()}-${monthDateTime.split(',').reverse()[0] + ' ' + monthDateTime.split(',').reverse()[1] + ':' + seconds}

` + res += ''; + // res += symbol + ' ' + params[i].seriesName + ' : ' + params[i].value + (args[1] === 'custom' ? flag === '1' ? 'M' : flag === '2' ? 'G' : 'K' : args[4]) +'' + '
'; + // (args[1] === 'custom' ? convertBytesUnit(Number(params[i].value)) : ) + res += ' ' + params[i].seriesName + ' : ' + setUnit(args, params[i].value) + '
'; + } + return res; + }, + textStyle: { + color: '#333', + fontSize: 12 + } + }, + legend: { + data: isMultiDimensional(legendData) ? legendData[0] : legendData, + left: status ? '-5px' : '13px', + top: '5%', + itemWidth: 16, + itemHeight: 8, + textStyle: { + color: '#333', + fontSize: 12 + }, + }, + grid: { + left: status ? '0' : '4.7%', + // left: status ? '2.2%' : isMultiDimensional(args[3]) ? args[2].map((item: {data: number[]}) => item.data).flat().some((t: number) => t > 100) ? '4%' : '3%' : args[3].some((t: number) => t > 100) ? '5%' : '4%', + // left: status ? '2.2%' : isMultiDimensional(args[3]) ? args[2].map((item: {data: number[]}) => item.data).flat().some((t: number) => t > 100) ? '5%' : '1%' : Object.is(args[1], '%') && args[3].some((item: number) => item < 100) ? '5%' : args[3].some((item: number) => item > 100) ? '4%' : '3%', + // right: '7%', + bottom: '3%', + containLabel: true + }, + xAxis: { + type: 'category', + boundaryGap: false, + data: isMultiDimensional(args[0]) ? args[0][0].map(function (str: string) { + return str.replace(' ', '\n'); + }) : args[0].map(function (str: string) { + return str.replace(' ', '\n') + }), + }, + yAxis: { + type: 'value', + // min: isMultiDimensional(args[3]) ? 0 : Math.min(...args[3]), + min: isMultiDimensional(args[3]) ? 0 : args[3].every((item: number) => Number(item) < 0) ? '' : args[3].every((item: number) => Number(item) <= 100) ? 0 : Math.min(...args[3]), + max: isMultiDimensional(args[3]) ? '' : args[3].every((item: number) => Number(item) < 0) ? '' : args[3].every((item: number) => Number(item) <= 100) ? 100 : '', + // min: isMultiDimensional(args[3]) ? 0 : Object.is(args[1], '%') && args[3].some((item: number) => item > 100) ? 0 : Math.min(...args[3]), + // max: isMultiDimensional(args[3]) ? setData(args[3]).some((item: number) => item > 100) ? '' : args[3].some((item: number) => item > 100) ? '' : 100 : Object.is(args[1], '%') && args[2][0]?.data?.length ? 100 : '', + axisLabel: { + formatter: function(value: number) { + return setFormAtter(args, value) + } + } + }, + dataZoom: [ + { + type: 'inside', + show: false, + start: Math.min(...args[6]), + end: Math.max(...args[6]), + } + ], + series: args[2] + }) + }) +}; + +const addSymbol = (num: string) => { + return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'); +}; + +const setFormAtter = (args: any, value: number) => { + const objData = [ + [ + () => ['custom'].includes(args[1]), + () => {return `${convertBytesUnit(value)}`} + ], + [ + () => ['个', '次/秒', '个/秒'].includes(args[1]), + () => { + if (value >= 1000) { + // .toFixed(2) + // parseFloat + return reg(addSymbol((String(value / 1000)))) + 'K'; + } + return `${reg(value.toFixed(2))}` + } + ], + [ + () => args[1] || !args[1], + () => {return `${reg(value.toFixed(2))}`} + ] + ]; + for (const key of objData) { + if (key[0]()) { + return key[1](); + } + } +} + +const setUnit = (args: any, value: T) => { + if (['custom'].includes(args[1])) { + return convertBytesUnit(Number(value)); + } + else if (['个', '次/秒', '个/秒'].includes(args[1])) { + // if (value >= 1000) { + // // .toFixed(2) + // // parseFloat + // return reg(addSymbol((String(value / 1000)))) + 'K' + args[1]; + // } + return `${value}${args[1]}`; + } + else { + return reg(value.toFixed(2)) + args[4]; + } +} + +const convertBytesUnit = (bytes: number) => { + const dataList = [ + [ + () => bytes < kb, + () => {return reg(String(bytes)) + ' B';} + ], + [ + () => bytes < mb, + () => {return reg((bytes / kb).toFixed(2)) + ' K';} + ], + [ + () => bytes < gb, + () => {return reg((bytes / mb).toFixed(2)) + ' M';} + ], + [ + () => bytes < tb, + () => {return reg((bytes / gb).toFixed(2)) + ' G';} + ], + [ + () => bytes < pb, + () => {return reg((bytes / tb).toFixed(2)) + ' T';} + ], + [ + () => bytes < eb, + () => {return reg((bytes / pb).toFixed(2)) + ' P';} + ] + ]; + for (const key of dataList) { + if (key[0]()) { + return key[1](); + } + } +} + +const isMultiDimensional = (arr: string[] | number[][]) => { + return Array.isArray(arr) && arr.some(item => Array.isArray(item)); +} + +const seriesDataObj = (name: any, ...args: any) => { + return { + name, + type: 'line', + smooth: true, + data: args[0], + itemStyle: { + color: args[1], // 点的颜色 + lineStyle: { + color: args[1] // 线的颜色 + } + }, + }; +} + +const echartsOpt = (res: any, type: string, myChart: any) => { + if (!res.yAxis.max) { + Reflect.deleteProperty(res.yAxis, 'max') + } + if (myChart === void 0) { + myChart = echarts.init(document.getElementById(type)); + newMyChart = myChart; + } + res && myChart.setOption(res); +} + +export { + newMyChart, + publicOption, + seriesDataObj, + echartsOpt +}; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/performanceMonitoring.vue b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/performanceMonitoring.vue new file mode 100644 index 0000000..2511597 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/performanceMonitoring.vue @@ -0,0 +1,202 @@ + + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/type.ts b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/type.ts new file mode 100644 index 0000000..61421ed --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/type.ts @@ -0,0 +1,95 @@ +/** + * @file + * @author +*/ + +interface NewDataType { + map: (args: (ite: {value: string;}) => number) => NewDataType; +}[]; + +interface NewTimeType { + map: (args: (ite: {timestamp: number;}) => number) => NewTimeType; +}[]; + +interface HourRangesType { + '0': string; + '6': string; + '12': string; + '24': string; +}; + +type EchartsParamsDataType = { + title: string; + showType: string[]; + model: string; + type: string; + id: string; + bigClickVal: { + type: string; + title: string; + model: string; + } +}[]; + + +type PublicType = { + typeVal: T; + id: string; + data: NewDataType[]; + type: string | string[]; + timeData: NewTimeType[]; + aggregationMethod: string; + metricName: string | string[]; + unit: string; + hoverUnit: string; + status?: string[] | undefined; + paramsMetricName?: string; +}; + +interface EchartsDataType extends PublicType { + filter(arg0: (item: {status: string}) => boolean): []; +}; + +interface EchartsDataObjType extends PublicType {}; + +interface ReactiveArrType { + aggregationMethod: string[]; + isLoadingObj: {[x: string]: boolean} | {}; + echartsParamsData: EchartsParamsDataType; + echartsData: EchartsDataType; +}; + +type FormType1 = { + cpu: string; + mem: string; + memUsage: string; + diskUsage: string; + diskUsageRate: string; +}; + +type FormType2 = { + diskReadWriteTraffic: string; + diskReadWriteIOPS: string; + netWorkBps: string; + netWorkPackagesNum: string; + averageLoad1Min: string; +}; + +interface RuleFormType extends FormType1, FormType2 { + averageLoad5Min: string; + averageLoad15Min: string; + totalTCPConnections: string; + normalTCPConnections: string; + totalNumberOfProcesses: string; +}; + +export { + NewDataType, + NewTimeType, + RuleFormType, + HourRangesType, + EchartsDataType, + ReactiveArrType, + EchartsDataObjType, + EchartsParamsDataType +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/utils/echartsBigOpt.ts b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/utils/echartsBigOpt.ts new file mode 100644 index 0000000..2d3a391 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/utils/echartsBigOpt.ts @@ -0,0 +1,48 @@ +/** + * @file + * @author +*/ + +import {RuleFormType} from '../type'; +import publicConfigOpt from './publicConfig'; + +class EchartsBigOpt { + diaLog: Ref = ref(false); + sizeBigTitle: Ref = ref(''); + sizeRef: Ref = ref(''); + bigSizeLoading: Ref = ref(true); + props; + + constructor(props: any) { + this.props = props; + } + + closeClick = (val: string) => { + const that = this; + this.diaLog.value = !this.diaLog.value; + this.props.ruleForm[`${val}` as keyof typeof that.props.ruleForm] = this.props.ruleForm[`${this.sizeRef.value}` as keyof typeof that.props.ruleForm]; + const newVals = this.props.reactiveArr.echartsParamsData.filter((item: {type: string}) => item.type === val)[0]; + newVals.model = this.props.ruleForm[`${val}` as keyof typeof that.props.ruleForm]; + const newData = this.props.reactiveArr.echartsData.filter((item: {typeVal: string}) => item.typeVal === val) + const {diskVal, mountpointVal, nicVal} = this.props; + const deviceVal = diskVal.value ? {device: diskVal.value} : mountpointVal.value ? {device: mountpointVal.value} : nicVal.value ? {device: nicVal.value} : {}; + publicConfigOpt.clearEmptyObj(deviceVal); + for (const key of newData) { + key.aggregationMethod = this.props.ruleForm[`${this.sizeRef.value}` as keyof typeof that.props.ruleForm]; + this.props.getEcharts(key, 'small', deviceVal); + } + } + + bigClickOpt = (value: string, ...args: string[]) => { + this.sizeRef.value = value; + this.sizeBigTitle.value = args[0]; + this.diaLog.value = !this.diaLog.value; + publicConfigOpt.smallBigSet(this.props, value, 'bigSize', ''); + } + + bigSizeChange = (val: string, obj: RuleFormType, value: string) => { + publicConfigOpt.smallBigSet(this.props, val, 'bigSize', obj[`${value}` as keyof typeof obj]) + } +} + +export default EchartsBigOpt; \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/utils/initStaticData.ts b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/utils/initStaticData.ts new file mode 100644 index 0000000..ef2da00 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/utils/initStaticData.ts @@ -0,0 +1,431 @@ +/** + * @file + * @author +*/ +import {language} from 'utils/publicClass.ts'; +import {CurrencyType8} from '@utils/publicType'; +import {EchartsDataType, EchartsParamsDataType} from '../type'; + +type NewEchartsDataStaticType = Omit[]; + +class InitStaticData { + static echartsData: NewEchartsDataStaticType = [ + { + typeVal: 'cpu', + id: 'main', + data: [], + type: language.t('monitorEcharts.echartsCount.cpu'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.cpu.util', + unit: '%', + hoverUnit: '%' + }, + { + typeVal: 'mem', + id: 'main2', + data: [], + type: language.t('monitorEcharts.echartsCount.mem'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.memory.util', + unit: '%', + hoverUnit: '%' + }, + { + typeVal: 'memUsage', + id: 'main3', + data: [], + type: language.t('monitorEcharts.echartsCount.memUsage'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.memory.used', + unit: 'GB', + hoverUnit: 'GB' + }, + { + typeVal: 'diskUsage', + id: 'main4', + data: [], + type: language.t('monitorEcharts.echartsCount.diskUsage'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.disk.used', + paramsMetricName: 'bmp.disk.partition.used', + // metricName: 'bmp.disk.partition.used', + unit: 'GB', + hoverUnit: 'GB', + status: ['diskVal', 'mountpointVal'] + }, + { + typeVal: 'diskUsageRate', + id: 'main5', + data: [], + type: language.t('monitorEcharts.echartsCount.diskUsageRate'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.disk.util', + paramsMetricName: 'bmp.disk.partition.util', + unit: '%', + hoverUnit: '%', + status: ['diskVal', 'mountpointVal'] + }, + { + typeVal: 'diskReadWriteTraffic', + id: 'main6', + data: [], + type: [ + language.t('monitorEcharts.echartsCount.diskReadTraffic'), + language.t('monitorEcharts.echartsCount.diskWriteTraffic') + ], + timeData: [], + aggregationMethod: 'avg', + metricName: ['bmp.disk.bytes.read', 'bmp.disk.bytes.write'], + // unit: 'M', + unit: 'custom', + // hoverUnit: 'Bps', + // hoverUnit: 'M', + // hoverUnit: 'KBps', + hoverUnit: '', + status: ['diskVal'] + }, + { + typeVal: 'diskReadWriteIOPS', + id: 'main7', + data: [], + type: [ + language.t('monitorEcharts.echartsCount.diskReadIOPS'), + language.t('monitorEcharts.echartsCount.diskWriteIOPS') + ], + timeData: [], + aggregationMethod: 'avg', + metricName: ['bmp.disk.counts.read', 'bmp.disk.counts.write'], + unit: '次/秒', + hoverUnit: '次/秒', + status: ['diskVal'] + }, + { + typeVal: 'netWorkBps', + id: 'main8', + data: [], + type: [ + language.t('monitorEcharts.echartsCount.netWorkIn'), + language.t('monitorEcharts.echartsCount.netWorkOut') + ], + timeData: [], + aggregationMethod: 'avg', + metricName: ['bmp.network.bytes.ingress', 'bmp.network.bytes.egress'], + // unit: 'K', + unit: 'custom', + // 暂时去掉 + // unit: '', + hoverUnit: '', + status: ['nicVal'] + }, + { + typeVal: 'netWorkPackagesNum', + id: 'main9', + data: [], + type: [ + language.t('monitorEcharts.echartsCount.netWorkInPackageNum'), + language.t('monitorEcharts.echartsCount.netWorkOutPackageNum') + ], + timeData: [], + aggregationMethod: 'avg', + metricName: ['bmp.network.packets.ingress', 'bmp.network.packets.egress'], + unit: '个/秒', + hoverUnit: '个/秒', + status: ['nicVal'] + }, + { + typeVal: 'averageLoad1Min', + id: 'main10', + data: [], + type: language.t('monitorEcharts.echartsCount.averageLoad1Min'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.avg.load1', + unit: '', + hoverUnit: '' + }, + { + typeVal: 'averageLoad5Min', + id: 'main11', + data: [], + type: language.t('monitorEcharts.echartsCount.averageLoad5Min'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.avg.load5', + unit: '', + hoverUnit: '' + }, + { + typeVal: 'averageLoad15Min', + id: 'main12', + data: [], + type: language.t('monitorEcharts.echartsCount.averageLoad15Min'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.avg.load15', + unit: '', + hoverUnit: '' + }, + { + typeVal: 'totalTCPConnections', + id: 'main13', + data: [], + type: language.t('monitorEcharts.echartsCount.totalTCPConnections'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.tcp.connect.total', + unit: '个', + hoverUnit: '个' + }, + { + typeVal: 'normalTCPConnections', + id: 'main14', + data: [], + type: language.t('monitorEcharts.echartsCount.normalTCPConnections'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.tcp.connect.established', + unit: '个', + hoverUnit: '个' + }, + { + typeVal: 'totalNumberOfProcesses', + id: 'main15', + data: [], + type: language.t('monitorEcharts.echartsCount.totalNumberOfProcesses'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.process.total', + unit: '个', + hoverUnit: '个' + } + ]; + + static radioData: CurrencyType8[] = [ + { + label: language.t('monitorEcharts.tabs.h1'), + value: '1min' + }, + { + label: language.t('monitorEcharts.tabs.h6'), + value: '5min' + }, + { + label: language.t('monitorEcharts.tabs.h12'), + value: '10 min' + }, + { + label: language.t('monitorEcharts.tabs.d1'), + value: '20 min' + }, + { + label: language.t('monitorEcharts.tabs.d3'), + value: '60min' + }, + { + label: language.t('monitorEcharts.tabs.d7'), + value: '120min' + }, + { + label: language.t('monitorEcharts.tabs.d14'), + value: '180min' + } + ]; + + static echartsParamsData: EchartsParamsDataType = [ + { + title: language.t('monitorEcharts.echartsCount.cpuUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'cpu', + id: 'main', + bigClickVal: { + type: 'cpu', + title: language.t('monitorEcharts.echartsCount.cpuUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.memUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'mem', + id: 'main2', + bigClickVal: { + type: 'mem', + title: language.t('monitorEcharts.echartsCount.memUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.memUsageUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'memUsage', + id: 'main3', + bigClickVal: { + type: 'memUsage', + title: language.t('monitorEcharts.echartsCount.memUsageUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.diskUsageUnit'), + showType: [ + language.t('monitorEcharts.radio.instance'), + language.t('monitorEcharts.radio.disk'), + language.t('monitorEcharts.radio.diskPartition') + ], + model: '', + type: 'diskUsage', + id: 'main4', + bigClickVal: { + type: 'diskUsage', + title: language.t('monitorEcharts.echartsCount.diskUsageUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.diskUsageRateUnit'), + showType: [ + language.t('monitorEcharts.radio.instance'), + language.t('monitorEcharts.radio.disk'), + language.t('monitorEcharts.radio.diskPartition') + ], + model: '', + type: 'diskUsageRate', + id: 'main5', + bigClickVal: { + type: 'diskUsageRate', + title: language.t('monitorEcharts.echartsCount.diskUsageRateUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.diskReadWriteTrafficUnit'), + showType: [language.t('monitorEcharts.radio.instance'), language.t('monitorEcharts.radio.disk')], + model: '', + type: 'diskReadWriteTraffic', + id: 'main6', + bigClickVal: { + type: 'diskReadWriteTraffic', + title: language.t('monitorEcharts.echartsCount.diskReadWriteTrafficUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.diskReadWriteIOPSUnit'), + showType: [language.t('monitorEcharts.radio.instance'), language.t('monitorEcharts.radio.disk')], + model: '', + type: 'diskReadWriteIOPS', + id: 'main7', + bigClickVal: { + type: 'diskReadWriteIOPS', + title: language.t('monitorEcharts.echartsCount.diskReadWriteIOPSUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.netWorkBpsUnit'), + showType: [language.t('monitorEcharts.radio.instance'), language.t('monitorEcharts.radio.netWorkInterface')], + model: '', + type: 'netWorkBps', + id: 'main8', + bigClickVal: { + type: 'netWorkBps', + title: language.t('monitorEcharts.echartsCount.netWorkBpsUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.netWorkPackagesNumUnit'), + showType: [language.t('monitorEcharts.radio.instance'), language.t('monitorEcharts.radio.netWorkInterface')], + model: '', + type: 'netWorkPackagesNum', + id: 'main9', + bigClickVal: { + type: 'netWorkPackagesNum', + title: language.t('monitorEcharts.echartsCount.netWorkPackagesNumUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.averageLoad1MinUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'averageLoad1Min', + id: 'main10', + bigClickVal: { + type: 'averageLoad1Min', + title: language.t('monitorEcharts.echartsCount.averageLoad1MinUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.averageLoad5MinUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'averageLoad5Min', + id: 'main11', + bigClickVal: { + type: 'averageLoad5Min', + title: language.t('monitorEcharts.echartsCount.averageLoad5MinUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.averageLoad15MinUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'averageLoad15Min', + id: 'main12', + bigClickVal: { + type: 'averageLoad15Min', + title: language.t('monitorEcharts.echartsCount.averageLoad15MinUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.totalTCPConnectionsUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'totalTCPConnections', + id: 'main13', + bigClickVal: { + type: 'totalTCPConnections', + title: language.t('monitorEcharts.echartsCount.totalTCPConnectionsUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.normalTCPConnectionsUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'normalTCPConnections', + id: 'main14', + bigClickVal: { + type: 'normalTCPConnections', + title: language.t('monitorEcharts.echartsCount.normalTCPConnectionsUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.totalNumberOfProcessesUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'totalNumberOfProcesses', + id: 'main15', + bigClickVal: { + type: 'totalNumberOfProcesses', + title: language.t('monitorEcharts.echartsCount.totalNumberOfProcessesUnit'), + model: '' + } + } + ] +} + +export default InitStaticData; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/utils/publicConfig.ts b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/utils/publicConfig.ts new file mode 100644 index 0000000..570ee54 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/utils/publicConfig.ts @@ -0,0 +1,54 @@ +/** + * @file + * @author +*/ +import {EchartsDataType, EchartsDataObjType} from '../type'; + +type ObjType = { + reactiveArr: { + echartsData: EchartsDataType[]; + }; + diskVal: { + value: string; + }; + mountpointVal: { + value: string; + }; + nicVal: { + value: string; + }; + getEcharts(arg0: EchartsDataObjType, arg1: string, arg2: { device: string; } | { device?: undefined; }): void; +} + +class PublicConfigOpt { + singleColor: string = '#108ee9'; + moreColor: string[] = [ + '#108ee9', + '#29d1d3' + ]; + + aggregationMethod: string[] = ['avg', 'max', 'min', 'sum']; + + clearEmptyObj = (deviceVal: T) => { + if (!Object.keys(deviceVal).length) { + Reflect.deleteProperty(deviceVal, 'device') + } + } + + smallBigSet = (obj: ObjType, val: string, type: string, value: string) => { + const newData = obj.reactiveArr.echartsData.filter((item: {typeVal: string}) => item.typeVal === val); + const {diskVal, mountpointVal, nicVal} = obj; + const deviceVal = diskVal.value ? {device: diskVal.value} : mountpointVal.value ? {device: mountpointVal.value} : nicVal.value ? {device: nicVal.value} : {}; + this.clearEmptyObj(deviceVal); + for (const key of newData) { + if (value?.length) { + key.aggregationMethod = value; + } + obj.getEcharts(key, type, deviceVal); + } + } +} + +const publicConfigOpt = new PublicConfigOpt(); + +export default publicConfigOpt; \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/utils/ruleForm.ts b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/utils/ruleForm.ts new file mode 100644 index 0000000..f25c2cd --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/utils/ruleForm.ts @@ -0,0 +1,27 @@ +/** + * @file + * @author +*/ +import {RuleFormType} from '../type'; + +class RuleFormOpt { + ruleForm: RuleFormType = reactive({ + cpu: 'avg', + mem: 'avg', + memUsage: 'avg', + diskUsage: 'avg', + diskUsageRate: 'avg', + diskReadWriteTraffic: 'avg', + diskReadWriteIOPS: 'avg', + netWorkBps: 'avg', + netWorkPackagesNum: 'avg', + averageLoad1Min: 'avg', + averageLoad5Min: 'avg', + averageLoad15Min: 'avg', + totalTCPConnections: 'avg', + normalTCPConnections: 'avg', + totalNumberOfProcesses: 'avg' + }) +} + +export default RuleFormOpt; diff --git "a/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/\346\263\250\346\204\217\344\272\213\351\241\271.md" "b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/\346\263\250\346\204\217\344\272\213\351\241\271.md" new file mode 100644 index 0000000..a0a45c9 --- /dev/null +++ "b/bmp-operation-web/src/views/deviceManagement/detail/performanceMonitoring/\346\263\250\346\204\217\344\272\213\351\241\271.md" @@ -0,0 +1,10 @@ +#### 监控图表注意事项,主要针对引入的非同级文件做描述 + +# 1:使用把ui-组件替换为el-组件 +# 2:页面引入的其他方法-uiLocale,是ui-config-provider(el-config-provider)的国际化 +# 3:language 是国际化,可以根据自己需求改写 +# 4:intervalTime 计算两个时间之间的时间差 多少天时分秒 +# 5:getMonthHoursMinutes 获取月-日-分,进行展示 +# 6:有一些样式可能是ui-组件里面写的样式,这个可以到时候去看一下 +# 7:有些样式要是没有生效,可能是全局样式,找到没生效的样式,然后去修改就可以 +# 8:import 'default-passive-events'; 需要下载这个包,然后导入,这个是解决控制台echarts-滚动的警告问题,应该是底层源码的警告,注意不要全局引入,只要引入在图表页面即可 diff --git a/bmp-operation-web/src/views/deviceManagement/detail/tabs/active.ts b/bmp-operation-web/src/views/deviceManagement/detail/tabs/active.ts new file mode 100644 index 0000000..08c907a --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/tabs/active.ts @@ -0,0 +1,174 @@ +/** + * @file + * @author +*/ + +import {language} from 'utils/publicClass.ts'; +import {CurrencyType6, CurrencyType} from '@utils/publicType'; +import router from 'router/index.ts'; + +interface DataType { + code: Ref; + activeName: Ref; + tabsPangeOneData: {label: string; name: string}[]; + tabsPangeTwoData: {label: string; name: string}[]; + tabsPangeThreeData: {label: string; name: string}[]; + tabsPangeData: CurrencyType6[]; +} + +const tabsOperate = (deviceDetail: {desrcibeAgentStatus(): void; initData(): void;}, query: {type: string}, diskTableOpt: {init(): void;}) => { + const data: DataType = { + code: ref(0), + // 标签页切换的model + activeName: ref('basicInfo'), + tabsPangeOneData: [ + { + label: language.t('deviceDetail.tabs.baseInfo'), + name: 'basicInfo' + }, + { + label: language.t('deviceDetail.tabs.diskDetail'), + name: 'diskDetail' + }, + { + label: language.t('deviceDetail.tabs.operatLog'), + name: 'operatLog' + } + ], + tabsPangeTwoData: [ + { + label: language.t('deviceDetail.tabs.baseInfo'), + name: 'basicInfo' + }, + { + label: language.t('deviceDetail.tabs.diskDetail'), + name: 'diskDetail' + }, + { + label: language.t('deviceDetail.tabs.performanceMonitoring'), + name: 'performanceMonitoring' + }, + { + label: language.t('deviceDetail.tabs.operatLog'), + name: 'operatLog' + } + ], + tabsPangeThreeData: [ + { + label: language.t('deviceDetail.tabs.baseInfo'), + name: 'basicInfo' + }, + { + label: language.t('deviceDetail.tabs.diskDetail'), + name: 'diskDetail' + }, + { + label: language.t('deviceDetail.tabs.hardwareMonitoring'), + name: 'hardwareMonitoring' + }, + { + label: language.t('deviceDetail.tabs.operatLog'), + name: 'operatLog' + } + ], + tabsPangeData: [ + { + label: language.t('deviceDetail.tabs.baseInfo'), + name: 'basicInfo' + }, + { + label:language.t('deviceDetail.tabs.diskDetail'), + name: 'diskDetail' + }, + { + label: language.t('deviceDetail.tabs.hardwareMonitoring'), + name: 'hardwareMonitoring' + }, + { + label: language.t('deviceDetail.tabs.performanceMonitoring'), + name: 'performanceMonitoring' + }, + { + label: language.t('deviceDetail.tabs.operatLog'), + name: 'operatLog' + } + ] + }; + + onMounted(() => { + data.activeName.value = query.type; + if (query?.type === 'basicInfo') { + deviceDetail.initData(); + deviceDetail.desrcibeAgentStatus(); + return; + } + }) + + watch(() => data.activeName.value, (newValue: string) => { + const requestData = [ + [ + (newValue: string) => !newValue.localeCompare('basicInfo'), + () => { + deviceDetail.initData(); + deviceDetail.desrcibeAgentStatus(); + } + ], + [ + (newValue: string) => !newValue.localeCompare('diskDetail'), + () => { + deviceDetail.initData(); + diskTableOpt.init(); + } + ] + ]; + for(const key of requestData) { + if (key[0](newValue)) { + key[1](newValue); + break; + } + } + }); + + const setData = (status: string, monitorStatus: string) => { + if (Object.is(status, 'error')) { + if (Object.is(monitorStatus, 'error')) return data.tabsPangeOneData; + if (!Object.is(monitorStatus, 'error')) return data.tabsPangeTwoData; + } + else { + if (Object.is(monitorStatus, 'error')) return data.tabsPangeThreeData; + return data.tabsPangeData; + } + } + + /** + * 标签页切换 + * @param {string} value 当前标签页点击切换的名称 + * @return {string} activeName.value 当前标签页切换的数据 + */ + const tabsChange = (value: string): void => { + data.activeName.value = value; + const path: string = router.currentRoute.value.path; + const query: CurrencyType = router.currentRoute.value.query; + let obj: CurrencyType = {}; + let activeQuery: string = ''; + for (let index in query) { + obj = {...obj, [index]: query[index], type: data.activeName.value} + obj.type = data.activeName.value; + } + for (let key in obj) { + activeQuery += `${[key]}=${obj[key]}&` + } + activeQuery = activeQuery.slice(0, -1); + router.push(`${path}?${activeQuery}`); + + }; + + return { + ...data, + setData, + // consolelogs, + tabsChange + } +}; + +export default tabsOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/detail/tabs/tabs.vue b/bmp-operation-web/src/views/deviceManagement/detail/tabs/tabs.vue new file mode 100644 index 0000000..c6a8af6 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/tabs/tabs.vue @@ -0,0 +1,46 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/detail/typeManagement.ts b/bmp-operation-web/src/views/deviceManagement/detail/typeManagement.ts new file mode 100644 index 0000000..acaca9e --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/detail/typeManagement.ts @@ -0,0 +1,25 @@ +type DetailType = {detail: {[x: string]: string;};}; + +type CurrencyType = {[x: string]: string}; + +interface TipStatusType { + tooltipStatus: { + [x: string]: { + showTooltip: boolean; + } + } +}; + +interface ShowPasswordType { + internetPort1: boolean; + internetPort2: boolean; + outLoginPassword: boolean; + info: string; +}; + +export { + DetailType, + CurrencyType, + TipStatusType, + ShowPasswordType +}; diff --git a/bmp-operation-web/src/views/deviceManagement/list/all.ts b/bmp-operation-web/src/views/deviceManagement/list/all.ts new file mode 100644 index 0000000..bee3eed --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/all.ts @@ -0,0 +1,51 @@ +import custom from './custom/custom'; +import resetOperate from './table/reset'; +import SearchOperate from './search/search'; +import DeviceList from './table/deviceList'; +import refreshOperate from './table/refresh'; +import FilterOperate from './table/tableFilter'; +import tableScrollOperate from './table/tableScroll'; +import upDownDelete from './upDownDelete/upDownDelete'; +import deviceImport from './deviceImport/deviceImport'; +import lockDeblocking from './lockOperate/lockOperate'; +import resetInstance from './instanceReset/instanceReset'; +import removeRecovery from './recoveryRemove/recoveryRemove'; +import passwordReset from './passwordReset/passwordReset'; +import openCloseRestart from './openCloseRestart/openCloseRestart'; +import batchPasswordReset from './batchOperate/passwordReset/operate'; +import batchOpenCloseRestart from './batchOperate/openCloseRestart/operate'; +import batchRecoveryInstance from './batchOperate/recoveryInstance/operate'; +import batchEditInstanceName from './batchOperate/editInstanceName/operate'; +import resetSystemConfirmOperate from './resetSystem/resetSystemConfirm'; +import resetSystemOperate from './resetSystem/systemReset'; +import {paginationOperate} from 'utils/publicClass.ts'; +// import {paginationOperate, customPagination} from './pagination/pagination'; +import {ExportFilterData, ExportDataOperate, devicesListExportAPI} from './export/export'; + +export { + custom, + DeviceList, + FilterOperate, + SearchOperate, + ExportFilterData, + paginationOperate, + ExportDataOperate, + devicesListExportAPI, + resetOperate, + upDownDelete, + deviceImport, + passwordReset, + resetInstance, + refreshOperate, + removeRecovery, + lockDeblocking, + openCloseRestart, + // customPagination, + tableScrollOperate, + resetSystemOperate, + batchPasswordReset, + batchOpenCloseRestart, + batchRecoveryInstance, + batchEditInstanceName, + resetSystemConfirmOperate +}; diff --git a/bmp-operation-web/src/views/deviceManagement/list/batchOperate/editInstanceName/batchEditInstanceNameOperate.vue b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/editInstanceName/batchEditInstanceNameOperate.vue new file mode 100644 index 0000000..776a31c --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/editInstanceName/batchEditInstanceNameOperate.vue @@ -0,0 +1,20 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/list/batchOperate/editInstanceName/operate.ts b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/editInstanceName/operate.ts new file mode 100644 index 0000000..aeb33d6 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/editInstanceName/operate.ts @@ -0,0 +1,26 @@ +const batchEditInstanceName = (deviceList: any) => { + const batchEditInstanceNameDiaLog: Ref = ref(false); + + const batchEditInstanceNameClick = (status: boolean) => { + if (status) return; + batchEditInstanceNameDiaLog.value = !batchEditInstanceNameDiaLog.value; + }; + + const batchEditInstanceNameCancel = (type: boolean) => { + batchEditInstanceNameDiaLog.value = type; + }; + + const batchEditInstanceNameSure = () => { + deviceList.filter.tableRef?.value?.clearSelection() + deviceList.getDataList(); + }; + + return { + batchEditInstanceNameDiaLog, + batchEditInstanceNameClick, + batchEditInstanceNameCancel, + batchEditInstanceNameSure + } +}; + +export default batchEditInstanceName; diff --git a/bmp-operation-web/src/views/deviceManagement/list/batchOperate/openCloseRestart/batchOpenCloseRestartOperate.vue b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/openCloseRestart/batchOpenCloseRestartOperate.vue new file mode 100644 index 0000000..cf03b97 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/openCloseRestart/batchOpenCloseRestartOperate.vue @@ -0,0 +1,21 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/list/batchOperate/openCloseRestart/operate.ts b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/openCloseRestart/operate.ts new file mode 100644 index 0000000..b9c74bf --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/openCloseRestart/operate.ts @@ -0,0 +1,29 @@ +const batchOpenCloseRestart = (deviceList: any) => { + const types: Ref = ref(''); + const batchOpenCloseRestartDiaLog: Ref = ref(false); + + const batchOpenCloseRestartClick = (type: string) => { + types.value = type; + batchOpenCloseRestartDiaLog.value = !batchOpenCloseRestartDiaLog.value; + + }; + + const batchOpenCloseRestartCancel = (type: boolean) => { + batchOpenCloseRestartDiaLog.value = type; + }; + + const batchOpenCloseRestartSure = () => { + deviceList.filter.tableRef?.value?.clearSelection() + deviceList.getDataList(); + }; + + return { + types, + batchOpenCloseRestartDiaLog, + batchOpenCloseRestartClick, + batchOpenCloseRestartCancel, + batchOpenCloseRestartSure + }; +}; + +export default batchOpenCloseRestart; diff --git a/bmp-operation-web/src/views/deviceManagement/list/batchOperate/passwordReset/batchPasswordResetOperate.vue b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/passwordReset/batchPasswordResetOperate.vue new file mode 100644 index 0000000..ffa0566 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/passwordReset/batchPasswordResetOperate.vue @@ -0,0 +1,20 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/list/batchOperate/passwordReset/operate.ts b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/passwordReset/operate.ts new file mode 100644 index 0000000..c43883b --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/passwordReset/operate.ts @@ -0,0 +1,26 @@ +const batchPasswordReset = (deviceList: any) => { + const batchResetPasswordDiaLog: Ref = ref(false); + + const batchResetPasswordClick = (status: boolean) => { + if (status) return; + batchResetPasswordDiaLog.value = !batchResetPasswordDiaLog.value; + }; + + const batchResetPasswordCancel = (type: boolean) => { + batchResetPasswordDiaLog.value = type; + }; + + const batchResetPasswordSure = () => { + deviceList.filter.tableRef?.value?.clearSelection() + deviceList.getDataList(); + }; + + return { + batchResetPasswordDiaLog, + batchResetPasswordClick, + batchResetPasswordCancel, + batchResetPasswordSure + } +}; + +export default batchPasswordReset; diff --git a/bmp-operation-web/src/views/deviceManagement/list/batchOperate/recoveryInstance/batchRecoveryInstanceOperate.vue b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/recoveryInstance/batchRecoveryInstanceOperate.vue new file mode 100644 index 0000000..4e7d959 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/recoveryInstance/batchRecoveryInstanceOperate.vue @@ -0,0 +1,20 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/list/batchOperate/recoveryInstance/operate.ts b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/recoveryInstance/operate.ts new file mode 100644 index 0000000..64e1b4e --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/batchOperate/recoveryInstance/operate.ts @@ -0,0 +1,25 @@ +const batchRecoveryInstance = (deviceList: any) => { + const batchRecoveryInstanceDiaLog: Ref = ref(false); + + const batchRecoveryInstanceClick = () => { + batchRecoveryInstanceDiaLog.value = !batchRecoveryInstanceDiaLog.value; + }; + + const batchRecoveryInstanceCancel = (type: boolean) => { + batchRecoveryInstanceDiaLog.value = type; + }; + + const batchRecoveryInstanceSure = () => { + deviceList.filter.tableRef?.value?.clearSelection() + deviceList.getDataList(); + }; + + return { + batchRecoveryInstanceDiaLog, + batchRecoveryInstanceClick, + batchRecoveryInstanceCancel, + batchRecoveryInstanceSure + } +}; + +export default batchRecoveryInstance; diff --git a/bmp-operation-web/src/views/deviceManagement/list/custom/custom.ts b/bmp-operation-web/src/views/deviceManagement/list/custom/custom.ts new file mode 100644 index 0000000..9090eb8 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/custom/custom.ts @@ -0,0 +1,10 @@ +/** + * @file + * @author +*/ + +import useCustom from 'hooks/custom/useCustom.ts'; + +const customOperate = useCustom('deviceList').info; + +export default customOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/list/custom/customList.vue b/bmp-operation-web/src/views/deviceManagement/list/custom/customList.vue new file mode 100644 index 0000000..82034b0 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/custom/customList.vue @@ -0,0 +1,8 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/list/deviceImport/deviceImport.ts b/bmp-operation-web/src/views/deviceManagement/list/deviceImport/deviceImport.ts new file mode 100644 index 0000000..68a4122 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/deviceImport/deviceImport.ts @@ -0,0 +1,45 @@ +interface DataType { + importDeviceDiaLog: Ref; + repeatData: string[]; +}; + +const deviceImport = (reset: any) => { + const data: DataType = { + // 导入设备弹窗组件状态 + importDeviceDiaLog: ref(false), + repeatData: [''] + }; + + /** + * 导入设备点击事件 + * @return {boolean} importDeviceDiaLog.value 导入设备组件弹窗状态 + */ + const importDeviceClick = (): boolean => { + return data.importDeviceDiaLog.value = true; + }; + + /** + * 导入设备组件取消事件 + * @param {boolean} type 弹窗状态 + * @return {boolean} importDeviceDiaLog.value 导入设备组件弹窗状态 + */ + const importDeviceCancel = (type: boolean): boolean => { + return data.importDeviceDiaLog.value = type; + }; + + /** + * 导入设备成功的回调操作 + */ + const importDeviceSure = () => { + reset.reset(); + }; + + return { + ...data, + importDeviceClick, + importDeviceCancel, + importDeviceSure + }; +}; + +export default deviceImport; diff --git a/bmp-operation-web/src/views/deviceManagement/list/deviceImport/deviceImport.vue b/bmp-operation-web/src/views/deviceManagement/list/deviceImport/deviceImport.vue new file mode 100644 index 0000000..480d03a --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/deviceImport/deviceImport.vue @@ -0,0 +1,18 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/list/deviceList.vue b/bmp-operation-web/src/views/deviceManagement/list/deviceList.vue new file mode 100644 index 0000000..a7ce115 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/deviceList.vue @@ -0,0 +1,148 @@ + + + + + diff --git a/bmp-operation-web/src/views/deviceManagement/list/export/export.ts b/bmp-operation-web/src/views/deviceManagement/list/export/export.ts new file mode 100644 index 0000000..df82a89 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/export/export.ts @@ -0,0 +1,49 @@ +import store from 'store/index.ts'; +import {ExportDataOperate} from 'utils/publicClass.ts'; +import {devicesListExportAPI} from 'api/device/request.ts'; + +class ExportFilterData { + // 是否导出数据 + hasExportData: Ref = ref(true); + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + // list: any; + search: { + searchParams: {} + }; + filter: { + filterParams: {} + }; + + constructor(search: { + searchParams: {} + }, filter: { + filterParams: {} + }) { + // this.list = list; + this.search = search; + this.filter = filter; + }; + + exportData = (that: never) => { + new ExportDataOperate(devicesListExportAPI, {}, 'device_list').exportData(that); + }; + + /** + * 参数处理 + */ + paramsProcessing = (that: never) => { + this.filterEmptyInfo.deleteEmtpyData({...this.filter.filterParams, ...this.search.searchParams}); + new ExportDataOperate(devicesListExportAPI, { + ...this.search.searchParams, + ...this.filter.filterParams + }, 'device_list').exportData(that); + } +}; + +export { + ExportFilterData, + ExportDataOperate, + devicesListExportAPI +}; diff --git a/bmp-operation-web/src/views/deviceManagement/list/export/exportData.vue b/bmp-operation-web/src/views/deviceManagement/list/export/exportData.vue new file mode 100644 index 0000000..2b9f088 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/export/exportData.vue @@ -0,0 +1,23 @@ + + + diff --git a/bmp-operation-web/src/views/deviceManagement/list/instanceReset/instanceReset.ts b/bmp-operation-web/src/views/deviceManagement/list/instanceReset/instanceReset.ts new file mode 100644 index 0000000..09a53f1 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/instanceReset/instanceReset.ts @@ -0,0 +1,38 @@ +interface DataType { + resetInstanceDiaLog: Ref; + instanceName: Ref; + instanceId: Ref; +}; + +const resetInstance = (deviceList: any) => { + const data: DataType = { + resetInstanceDiaLog: ref(false), + instanceName: ref(''), + instanceId: ref('') + }; + + const resetInstanceClick = (id: string, name: string, status: boolean) => { + if (!status) return; + data.instanceId.value = id; + data.instanceName.value = name; + data.resetInstanceDiaLog.value = !data.resetInstanceDiaLog.value; + }; + + const resetInstanceCancel = (type: boolean) => { + data.resetInstanceDiaLog.value = type; + }; + + const resetInstanceSure = () => { + deviceList.filter.tableRef?.value?.clearSelection() + deviceList.getDataList(); + }; + + return { + ...data, + resetInstanceClick, + resetInstanceCancel, + resetInstanceSure + } +}; + +export default resetInstance; diff --git a/bmp-operation-web/src/views/deviceManagement/list/instanceReset/instanceReset.vue b/bmp-operation-web/src/views/deviceManagement/list/instanceReset/instanceReset.vue new file mode 100644 index 0000000..b6c2ac9 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/instanceReset/instanceReset.vue @@ -0,0 +1,21 @@ + + + diff --git a/bmp-operation-web/src/views/deviceManagement/list/lockOperate/lockOperate.ts b/bmp-operation-web/src/views/deviceManagement/list/lockOperate/lockOperate.ts new file mode 100644 index 0000000..9d85d30 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/lockOperate/lockOperate.ts @@ -0,0 +1,40 @@ +interface DataType { + lockDiaLog: Ref; + instanceName: Ref; + operate: Ref; + instanceId: Ref; +}; + +const lockDeblocking = (deviceList: any) => { + const data: DataType = { + lockDiaLog: ref(false), + instanceName: ref(''), + operate: ref(''), + instanceId: ref('') + }; + + const lock = (name: string, id: string, type: string) => { + data.lockDiaLog.value = !data.lockDiaLog.value; + data.instanceName.value = name; + data.instanceId.value = id; + data.operate.value = type; + }; + + const lockCancel = (type: boolean): boolean => { + return data.lockDiaLog.value = type; + }; + + const lockSure = () => { + deviceList.filter.tableRef?.value?.clearSelection() + deviceList.getDataList(); + }; + + return { + ...data, + lock, + lockCancel, + lockSure + } +}; + +export default lockDeblocking; diff --git a/bmp-operation-web/src/views/deviceManagement/list/lockOperate/lockOperate.vue b/bmp-operation-web/src/views/deviceManagement/list/lockOperate/lockOperate.vue new file mode 100644 index 0000000..a0f39a6 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/lockOperate/lockOperate.vue @@ -0,0 +1,21 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/list/module.ts b/bmp-operation-web/src/views/deviceManagement/list/module.ts new file mode 100644 index 0000000..9c41c2b --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/module.ts @@ -0,0 +1,40 @@ + +import Custom from './custom/customList.vue'; +import TableData from './table/tableData.vue'; +import ExportData from './export/exportData.vue'; +import Pagination from './pagination/pagination.vue'; +import SystemReset from './resetSystem/systemReset.vue'; +import LockOperate from './lockOperate/lockOperate.vue'; +import UpDownDelete from './upDownDelete/upDownDelete.vue'; +import DeviceImport from './deviceImport/deviceImport.vue'; +import PasswordReset from './passwordReset/passwordReset.vue'; +import InstanceResets from './instanceReset/instanceReset.vue'; +import RecoveryRemove from './recoveryRemove/recoveryRemove.vue'; +import ResetSystemConfirm from './resetSystem/resetSystemConfirm.vue'; +import OpenCloseRestart from './openCloseRestart/openCloseRestart.vue'; +import BatchPasswordResetOperate from './batchOperate/passwordReset/batchPasswordResetOperate.vue' +import BatchOpenCloseRestartOperate from './batchOperate/openCloseRestart/batchOpenCloseRestartOperate.vue'; +import BatchRecoveryInstanceOperate from './batchOperate/recoveryInstance/batchRecoveryInstanceOperate.vue'; +import BatchEditInstanceNameOperate from './batchOperate/editInstanceName/batchEditInstanceNameOperate.vue'; + +const pluginComp = { + Custom, + TableData, + ExportData, + Pagination, + SystemReset, + LockOperate, + UpDownDelete, + DeviceImport, + PasswordReset, + InstanceResets, + RecoveryRemove, + ResetSystemConfirm, + OpenCloseRestart, + BatchPasswordResetOperate, + BatchOpenCloseRestartOperate, + BatchRecoveryInstanceOperate, + BatchEditInstanceNameOperate +}; + +export default pluginComp; diff --git a/bmp-operation-web/src/views/deviceManagement/list/openCloseRestart/openCloseRestart.ts b/bmp-operation-web/src/views/deviceManagement/list/openCloseRestart/openCloseRestart.ts new file mode 100644 index 0000000..92d29be --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/openCloseRestart/openCloseRestart.ts @@ -0,0 +1,60 @@ +interface DataType { + openShutDownRestartDiaLog: Ref; + instanceInfo: Ref; + title: Ref; + instanceId: Ref; +}; + +const openCloseRestart = (deviceList: any) => { + const data: DataType = { + // 开机、关机、重启组件状态 + openShutDownRestartDiaLog: ref(false), + // 开机、关机、重启实例信息 + instanceInfo: ref(''), + // 开机、关机、重启名称 + title: ref(''), + instanceId: ref('') + }; + + /** + * 开机、关机、重启点击事件 + * @param {Object} item 当前点击这一项 + * @param {string} item.instanceName 当前点击这一项实例 + * @param {string} type 当前点击这一项状态 + * @return {string} title.value 当前点击这一项的title标题 + */ + const openShutDownRestartClick = (item: {instanceName: string, instanceId: string}, type: string, status: boolean): string | void => { + if (!status) return; + data.openShutDownRestartDiaLog.value = !data.openShutDownRestartDiaLog.value; + data.instanceInfo.value = item.instanceName; + data.instanceId.value = item.instanceId; + const text = new Map([ + ['open', '开机'], + ['restart', '重启'] + ]); + return data.title.value = text.get(type)?? '关机'; + }; + + /** + * 开机、关机、重启组件取消事件 + * @param {boolean} type 弹窗状态 + * @return {boolean} openShutDownRestartDiaLog.value 开机、关机、重启组件弹窗状态 + */ + const openShutDownRestartCancel = (type: boolean): boolean => { + return data.openShutDownRestartDiaLog.value = type; + }; + + const openShutDownRestartSure = () => { + deviceList.filter.tableRef?.value?.clearSelection() + deviceList.getDataList(); + }; + + return { + ...data, + openShutDownRestartClick, + openShutDownRestartCancel, + openShutDownRestartSure + }; +}; + +export default openCloseRestart; diff --git a/bmp-operation-web/src/views/deviceManagement/list/openCloseRestart/openCloseRestart.vue b/bmp-operation-web/src/views/deviceManagement/list/openCloseRestart/openCloseRestart.vue new file mode 100644 index 0000000..a7e1fb7 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/openCloseRestart/openCloseRestart.vue @@ -0,0 +1,22 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/list/page.ts b/bmp-operation-web/src/views/deviceManagement/list/page.ts new file mode 100644 index 0000000..6e782e5 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/page.ts @@ -0,0 +1,10 @@ +const DeviceList = () => import(/* webpackChunkName: "DeviceList" */ './deviceList.vue'); + +export default { + path: '/DeviceManagement/deviceList', + name: 'DeviceList', + component: DeviceList, + meta: { + type: 'deviceList' + } +}; diff --git a/bmp-operation-web/src/views/deviceManagement/list/pagination/batchOpt.ts b/bmp-operation-web/src/views/deviceManagement/list/pagination/batchOpt.ts new file mode 100644 index 0000000..09e3613 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/pagination/batchOpt.ts @@ -0,0 +1,86 @@ +import {language} from 'utils/publicClass.ts'; + +class BatchOperate { + selectStatus: Ref = ref(false); + emitValue: any; + + constructor (emitValue: any) { + this.emitValue = emitValue; + }; + + selectHover = (val: boolean): boolean => { + return this.selectStatus.value = val; + }; + + openTip = (status: number) => { + return this.#resultTip(status, 'turnOn'); + }; + + closeTip = (status: number) => { + return this.#resultTip(status, 'turnOff'); + }; + + restartTip = (status: number) => { + return this.#resultTip(status, 'restart'); + }; + + resetPasswordTip = (deviceList: any) => { + const status: number = deviceList.resetPasswordBntDisabled.value && deviceList.reactiveArr.selectArr?.length; + return this.#resultTip(status, 'resetPassword'); + }; + + editInstanceNameTip = (deviceList: any) => { + const status: number = deviceList.instanceNameBntDisabled.value && deviceList.reactiveArr.selectArr?.length; + return this.#resultTip(status, 'instanceName'); + }; + + #resultTip = (status: number, type: string) => { + const text = new Map([ + [0, language.t('deviceList.batchOperate.tip.default')] + ]); + return text.get(status)?? language.t(`deviceList.batchOperate.tip.${type}`); + }; + + recoveryInstanceTip = (selectArr: any[]) => { + const lockStatus: boolean = selectArr.every((item: {locked: string}) => !item.locked.localeCompare('locked')); + const content = [ + [ + () => !selectArr.length, + () => language.t('deviceList.batchOperate.tip.default') + ], + [ + () => lockStatus, + () => language.t('deviceList.batchOperate.tip.lock') + ], + [ + () => !lockStatus, + () => language.t('deviceList.batchOperate.tip.recovery') + ] + ]; + + for (const key of content) { + if (key[0]()) { + return key[1](); + } + } + }; + + setClass = (status: boolean) => { + const className = new Map([ + [true, 'drop-down-disabled'] + ]); + return className.get(status)?? 'drop-down-operate-content'; + }; + + openCloseRestartClick = (status: boolean, type: string) => { + if (!status) return; + this.emitValue('open-close-restart', type) + }; + + recoveryInstanceClick = (status: boolean) => { + if (!status) return; + this.emitValue('recovery-instance') + }; +}; + +export default BatchOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/list/pagination/pagination.ts b/bmp-operation-web/src/views/deviceManagement/list/pagination/pagination.ts new file mode 100644 index 0000000..84f3db9 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/pagination/pagination.ts @@ -0,0 +1,19 @@ +import {paginationOperate} from 'utils/publicClass.ts'; + +const customPagination = (list: any) => { + + watch(() => [ + paginationOperate.pageSize.value, + paginationOperate.pageNumber.value + ], (_: boolean[]): void => { + list.filter.tableRef?.value?.clearSelection() + if (paginationOperate.routerChange.value) return; + list.getDataList(); + // list.setFilterData(search, filter?.reactiveArr); + }); +}; + +export { + paginationOperate, + customPagination +}; diff --git a/bmp-operation-web/src/views/deviceManagement/list/pagination/pagination.vue b/bmp-operation-web/src/views/deviceManagement/list/pagination/pagination.vue new file mode 100644 index 0000000..e91c15a --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/pagination/pagination.vue @@ -0,0 +1,160 @@ + + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/list/passwordReset/passwordReset.ts b/bmp-operation-web/src/views/deviceManagement/list/passwordReset/passwordReset.ts new file mode 100644 index 0000000..5ec27f6 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/passwordReset/passwordReset.ts @@ -0,0 +1,32 @@ +import {CurrentInstance} from 'utils/publicClass.ts'; + +const resetPassword = (deviceList: any) => { + const resetPasswordDiaLog: Ref = ref(false); + const mitt = new CurrentInstance(); + + const resetPasswordClick = async (item: any, _: string, status: boolean) => { + if (!status) return; + resetPasswordDiaLog.value = !resetPasswordDiaLog.value; + await nextTick(() => { + mitt.instanceMitt?.proxy?.$Bus?.emit('reset-password',item); + }); + }; + + const resetPasswordCancel = (type: boolean) => { + resetPasswordDiaLog.value = type; + }; + + const resetPasswordSure = () => { + deviceList.filter.tableRef?.value?.clearSelection() + deviceList.getDataList(); + }; + + return { + resetPasswordDiaLog, + resetPasswordClick, + resetPasswordCancel, + resetPasswordSure + } +}; + +export default resetPassword; diff --git a/bmp-operation-web/src/views/deviceManagement/list/passwordReset/passwordReset.vue b/bmp-operation-web/src/views/deviceManagement/list/passwordReset/passwordReset.vue new file mode 100644 index 0000000..fece499 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/passwordReset/passwordReset.vue @@ -0,0 +1,18 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/list/recoveryRemove/recoveryRemove.ts b/bmp-operation-web/src/views/deviceManagement/list/recoveryRemove/recoveryRemove.ts new file mode 100644 index 0000000..4fb35a8 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/recoveryRemove/recoveryRemove.ts @@ -0,0 +1,49 @@ +import {CurrentInstance} from 'utils/publicClass.ts'; + +interface DataType { + removeRecoveryDiaLog: Ref; + removeRecoveryTitle: Ref; +}; + +interface DeviceListType { + filter: any; + getDataList: () => void; +}; + +const removeRecovery = (deviceList: DeviceListType) => { + const data: DataType = { + // 设备移除、实例回收组件状态 + removeRecoveryDiaLog: ref(false), + // 设备移除、实例回收标题名称 + removeRecoveryTitle: ref('') + }; + + const mitt = new CurrentInstance(); + + const removeRecoveryClick = async (item: {[x: string]: string}, type: string, status: boolean): Promise => { + if (!status) return; + data.removeRecoveryDiaLog.value = !data.removeRecoveryDiaLog.value; + data.removeRecoveryTitle.value = type; + await nextTick(() => { + mitt.instanceMitt?.proxy?.$Bus?.emit('device-table', {list: item, type: 'removeRecovery'}); + }); + }; + + const removeRecoveryCancel = (type: boolean) => { + data.removeRecoveryDiaLog.value = type; + }; + + const removeRecoverySure = () => { + deviceList.filter.tableRef?.value?.clearSelection() + deviceList.getDataList(); + }; + + return { + ...data, + removeRecoveryClick, + removeRecoveryCancel, + removeRecoverySure + } +}; + +export default removeRecovery; diff --git a/bmp-operation-web/src/views/deviceManagement/list/recoveryRemove/recoveryRemove.vue b/bmp-operation-web/src/views/deviceManagement/list/recoveryRemove/recoveryRemove.vue new file mode 100644 index 0000000..ea9faca --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/recoveryRemove/recoveryRemove.vue @@ -0,0 +1,19 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/list/resetSystem/resetSystemConfirm.ts b/bmp-operation-web/src/views/deviceManagement/list/resetSystem/resetSystemConfirm.ts new file mode 100644 index 0000000..1ac94a1 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/resetSystem/resetSystemConfirm.ts @@ -0,0 +1,36 @@ +import {CurrentInstance} from 'utils/publicClass.ts'; + +const resetSystemConfirmOperate = (resetSystemOpt: any) => { + const secondaryConfirmationDiaLog: Ref = ref(false); + const secondaryConfirmationName: Ref = ref(''); + const mitt = new CurrentInstance(); + let items: any = {} + const resetSystemConfirmClick = async(item: {instanceStatus: string; instanceName: string;}) => { + if (!['Reinstall failed', 'stopped'].includes(item.instanceStatus)) return; + secondaryConfirmationName.value = item.instanceName; + secondaryConfirmationDiaLog.value = !secondaryConfirmationDiaLog.value; + items = item; + }; + + const secondaryConfirmationCancel = (type: boolean) => { + secondaryConfirmationDiaLog.value = type; + }; + + const secondaryConfirmationSure = async () => { + resetSystemOpt.resetSystemDiaLog.value= true; + await nextTick(() => { + mitt.instanceMitt?.proxy?.$Bus?.emit('reset-system', {...items}); + }) + // fn(); + }; + + return { + resetSystemConfirmClick, + secondaryConfirmationName, + secondaryConfirmationDiaLog, + secondaryConfirmationCancel, + secondaryConfirmationSure + }; +}; + +export default resetSystemConfirmOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/list/resetSystem/resetSystemConfirm.vue b/bmp-operation-web/src/views/deviceManagement/list/resetSystem/resetSystemConfirm.vue new file mode 100644 index 0000000..cc12fcd --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/resetSystem/resetSystemConfirm.vue @@ -0,0 +1,19 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/list/resetSystem/systemReset.ts b/bmp-operation-web/src/views/deviceManagement/list/resetSystem/systemReset.ts new file mode 100644 index 0000000..2c1a8ee --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/resetSystem/systemReset.ts @@ -0,0 +1,24 @@ +const resetSystemOperate = (deviceList: any) => { + const resetSystemDiaLog: Ref = ref(false); + + const resetSystemClick = () => { + resetSystemDiaLog.value = !resetSystemDiaLog.value; + }; + + const resetSystemCancel = (type: boolean) => { + resetSystemDiaLog.value = type; + }; + + const resetSystemSure = () => { + deviceList.getDataList(); + }; + + return { + resetSystemClick, + resetSystemDiaLog, + resetSystemCancel, + resetSystemSure + }; +}; + +export default resetSystemOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/list/resetSystem/systemReset.vue b/bmp-operation-web/src/views/deviceManagement/list/resetSystem/systemReset.vue new file mode 100644 index 0000000..3dcffc2 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/resetSystem/systemReset.vue @@ -0,0 +1,18 @@ + + diff --git a/bmp-operation-web/src/views/deviceManagement/list/search/search.ts b/bmp-operation-web/src/views/deviceManagement/list/search/search.ts new file mode 100644 index 0000000..1ba5c1b --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/search/search.ts @@ -0,0 +1,72 @@ +import {language, paginationOperate} from 'utils/publicClass.ts'; + +class SearchOperate { + hasClear: Ref = ref(false); + // 搜索框值 + selectVal: Ref = ref(0); + reactiveArr: any = reactive({ + searchParams: {}, + selectOption: [ // search搜索框搜索名称 + { + value: 0, + label: language.t('deviceList.operate.label.sn') + }, + { + value: 1, + label: language.t('deviceList.operate.label.instanceOwner') + } + ] + }); + fn: any; + + constructor (fn: any) { + this.fn = fn; + }; + + /** + * input 输入框 点击搜索按钮或者回车触发 + * @param {string} enterValueIpt 输入框输入的值 + * @param {number} selectValue 筛选框筛选的值 + */ + enterValueIpt = (enterValueIpt: string, selectValue: number): void => { + selectValue ? this.reactiveArr.searchParams = {userName: enterValueIpt} : this.reactiveArr.searchParams = {sn: enterValueIpt}; + this.request(); + }; + + /** + * 搜索框筛选 + * @param {number} val 搜索框切换的搜索key + * @return {number} selectVal 对应的key + */ + changeSelect = (val: number): number => { + return this.selectVal.value = val; + }; + + clearClick = (val: string) => { + if (!val) { + this.selectChange(); + } + }; + + selectChange = () => { + const {userName, sn} :{userName?: string; sn?: string;} = this.reactiveArr.searchParams; + if (userName || sn) { + this.reactiveArr.searchParams = {}; + this.request(); + } + }; + + request = () => { + // this.deviceList.hasCheckAll.value = false; + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn(); + // this.deviceList.setFilterData(this.reactiveArr, 'search', this.hasClear); + // this.imageList.getImageList(); + }; + +}; + +export default SearchOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/list/table/deviceList.ts b/bmp-operation-web/src/views/deviceManagement/list/table/deviceList.ts new file mode 100644 index 0000000..81474a3 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/table/deviceList.ts @@ -0,0 +1,344 @@ +/** + * @file + * @author +*/ + +import {AxiosError} from 'axios'; +import {TimerOperate, paginationOperate, RouterOperate, CurrentInstance, language} from 'utils/publicClass.ts'; +import {CurrencyType} from '@utils/publicType'; +import store from 'store/index.ts'; +import {devicesListAPI} from 'api/device/request.ts'; +import {msgTip, decrypt, methodsTotal} from 'utils/index.ts'; +import DeviceStaticData from 'staticData/device/index.ts'; // 中间态1 中间态2 +import {TableType, OSSType, ReactiveArrType, FilterParamsType} from '../typeManagement'; +import {removeLong} from 'request/RemoveLongReq/remove.ts'; + +let _self: any = null; +class DeviceList extends TimerOperate { + routerOperate = new RouterOperate(); + searchTip: Ref = ref(false); + // loading态 + isLoading: Ref = ref(false); + reactiveArr: { + tableData: TableType[]; + selectArr: CurrencyType[]; + defTableData: TableType[]; + arr: any; + currentData: any; + } = reactive<{ + tableData: TableType[]; + selectArr: CurrencyType[]; + defTableData: TableType[]; + arr: TableType[]; + currentData: TableType[]; + }>({ + tableData: [], // 设备列表数据 + selectArr: [], + defTableData: [], + arr: [], + currentData: [] + }); + monitorCode: Ref = ref(0); + code: Ref = ref(0); + tableRef: { + [x: string]: unknown; + value?: { + toggleRowSelection(arg1: any, arg2: any): any; + clearFilter(): unknown; + clearSelection(): any; + } + } = {value: {clearFilter(): void{}, toggleRowSelection(): any{}, clearSelection(): any{}}}; + // hasRequest: boolean = false; + filterEmptyInfo: { // store + filterParams( + arg0: {[x: string]: number | string}, + arg1: OSSType, + arg2: ReactiveArrType, + arg3: FilterParamsType + ): Promise; + deleteEmtpyData(arg0: FilterParamsType): unknown; + } = store.filterEmpty; + isIntervalRequest: boolean = false; + type: string = ''; + search: any = {}; + filter: any = {}; + hasCheckAll: Ref = ref(false); + closeBtnDisabled: Ref = ref(true); + openBtnDisabled: Ref = ref(true); + restartBtnDisabled: Ref = ref(true); + instanceNameBntDisabled: Ref = ref(true); + resetPasswordBntDisabled: Ref = ref(true); + recoveryInstanceBtnDisabled: Ref = ref(true); + sessionId: Ref = ref(''); + instanceProxy = new CurrentInstance().proxy; + + constructor (search: any, filter: any) { + super(); + this.search = search; + this.filter = filter; + const id: string | null = sessionStorage?.getItem('deviceTypeId'); + const encryptDecrypt: string[] = this.instanceProxy.$defInfo.encryptDecrypt(1); + this.sessionId.value = id && decrypt(id, encryptDecrypt[0], encryptDecrypt[1]); + _self = this; + + // 页面销毁时-触发,清空延时器 + onUnmounted(() => { + clearTimeout((this.timer as number)); + removeLong(this.routerOperate.router.currentRoute.value.name); + sessionStorage?.removeItem('deviceTypeId'); + }); + // 页面销毁前-触发,清空延时器 + onBeforeUnmount(() => { + clearTimeout((this.timer as number)); + removeLong(this.routerOperate.router.currentRoute.value.name); + sessionStorage?.removeItem('deviceTypeId'); + }); + this.getDataList(); + this.getHardStatusList(); + }; + + getHardStatusList = async () => { + try { + await this.instanceProxy.$hardwareStatusApi.hardwareStatusAPI({pageNumber: 1}); + } + catch(e) { + const err = e as AxiosError; + this.code.value = err.code as unknown as number; + } + } + + setCollected = (status: string) => { + const type = new Map([ + ['1', language.t('deviceList.status.collected')], + ['2', language.t('deviceList.status.noCollected')], + ['3', language.t('deviceList.status.collecting')], + ['4', language.t('deviceList.status.collectionFailed')] + ]); + return type.get(status); + } + + jumpClick = (routerOperate: T, item: {sn: string; deviceId: string; instanceId: string}) => { + const path = this.instanceProxy.$defInfo.routerPath('deviceDetail'); + const defaultPath = `${path}?sn=${item.sn}&deviceId=${item.deviceId}&instanceId=${item.instanceId}&type=basicInfo`; + routerOperate.router.push(`${defaultPath}&monitorStatus=error`); + } + + /** + * 获取data数据 + */ + getDataList = () => { + this.isLoading.value = true; + this.processingParameter(); + }; + + /** + * 处理参数 + */ + processingParameter = () => { + const params = { + pageSize: paginationOperate.pageSize.value, + pageNumber: paginationOperate.pageNumber.value, + ...this.search?.reactiveArr.searchParams, + ...this.filter?.reactiveArr.filterParams + }; + this.filterEmptyInfo.deleteEmtpyData(params); + this.getDeviceList(params); + }; + + getDeviceList = (params: {[x: string]: string}) => { + clearTimeout((this.timer as number)); + if (sessionStorage?.getItem('deviceTypeId')) { + params = { + ...params, + deviceTypeId: this.sessionId.value + } + } + devicesListAPI( + { + ...params, + } + ) + .then(({data} : {data: {result: {totalCount: number; devices: TableType[]}}}) => { + if (data?.result?.devices?.length) { + const result: TableType[] = data.result.devices; + const totalCount: number = data.result.totalCount; + result.forEach((item: TableType, index: number) => { + DeviceStaticData.deviceTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }) + }) + this.reactiveArr.tableData = result; + paginationOperate.total.value = totalCount; + for (const key of this.reactiveArr.tableData) { + const hasLoopReq = [...DeviceStaticData.intermediate1, ...DeviceStaticData.intermediate2].some((item: string) => item === key.instanceStatus); + if (['putawaying'].some((item: string) => item === key.manageStatus) || hasLoopReq) { + this.isIntervalRequest = true; + this.timer = setTimeout(() => { + // if (this.hasRequest) return; + this.processingParameter(); + }, 5000) + return; + } + this.isIntervalRequest = false; + } + return; + } + this.reactiveArr.tableData = []; + paginationOperate.total.value = 0; + methodsTotal.initScrollLeft(this.filter.tableRef.value); + }) + .catch(({message} : {message: string;}) => { + if (!this.isIntervalRequest) { + this.reactiveArr.tableData = []; + paginationOperate.total.value = 0; + methodsTotal.initScrollLeft(this.filter.tableRef.value); + message && msgTip.error(message); + return; + } + this.timer = setTimeout(() => { + // if (this.hasRequest) return; + this.processingParameter(); + }, 5000); + }) + .finally(() => { + sessionStorage.removeItem('deviceTypeId') + this.isLoading.value = false; + this.search.hasClear.value = false; + this.searchTip.value = Object.keys(params).length > 2; + }); + }; + + // 多选框回显 + getRowKeys = (row: {sn: string;}) => { + if (row.sn) return row.sn; + }; + + rowClick = (row: any, _: any, event: any) => { + this.filter.tableRef?.value?.toggleRowSelection(row, event); + this.selectChange(this.reactiveArr.selectArr, row); + }; + + /** + * 单选 + */ + selectChange = (rows: CurrencyType[], row: CurrencyType) => { + const newRows: boolean | number = rows.filter((item) => !item.hasCheckbox).length && rows.indexOf(row) !== -1; + if (newRows) { + this.reactiveArr.arr.push(row); + } + else { + for(let i = 0; i < this.reactiveArr.currentData.length; i++) { + if(this.reactiveArr.currentData[i].sn === row.sn){ + this.reactiveArr.currentData.splice(i, 1); + } + } + for(let i = 0; i < this.reactiveArr.arr.length; i++){ + if(this.reactiveArr.arr[i].sn === row.sn){ + this.reactiveArr.arr.splice(i, 1); + } + } + } + }; + + cellClick = (row: CurrencyType, b: {property: string | undefined}, event: any) => { + const type = ['sn', undefined]; + if (!type.includes(b.property)) return; + this.toggleSelection([row], event); + }; + + toggleSelection = (rows: CurrencyType[], event: any) => { + if (rows) { + rows.forEach((row: any) => { + this.filter.tableRef.value?.toggleRowSelection(row, event); + }); + return; + } + this.filter.tableRef.value?.clearSelection(); + }; + + handleSelectionChange (val: CurrencyType[]) { + _self.reactiveArr.selectArr = val; + let newDefTableData: CurrencyType[] = []; + for (const key of val) { + newDefTableData.push( + { + instanceName: key.instanceName, + instanceId: key.instanceId, + iloIp: key.iloIp, + privateIpv4: key.privateIpv4 + } + ) + } + _self.reactiveArr.defTableData = newDefTableData; + _self.hasCheckAll.value = _self.reactiveArr.selectArr.length === _self.reactiveArr.tableData.length; + const runningStatus = val.every((item: CurrencyType) => ['running'].includes(item.instanceStatus)); + const stoppedStatus = val.every((item: CurrencyType) => ['stopped'].includes(item.instanceStatus)); + const recoveryInstanceStatus = val.every((item: CurrencyType) => ['Creation failed', 'stopped'].includes(item.instanceStatus) && item.locked === 'unlocked'); + const instanceNameStatus = val.every((item: CurrencyType) => item.instanceId?.length > 0); + const arrData = [ + [ + (val: CurrencyType[]) => val?.length, + () => { + _self.closeBtnDisabled.value = !runningStatus; + _self.openBtnDisabled.value = !stoppedStatus; + _self.restartBtnDisabled.value = !runningStatus; + _self.recoveryInstanceBtnDisabled.value = !recoveryInstanceStatus; + _self.instanceNameBntDisabled.value = !instanceNameStatus; + _self.resetPasswordBntDisabled.value = !stoppedStatus; + } + ], + [ + (val: CurrencyType[]) => !val?.length, + () => { + _self.closeBtnDisabled.value = true; + _self.openBtnDisabled.value = true; + _self.restartBtnDisabled.value = true; + _self.recoveryInstanceBtnDisabled.value = true; + _self.instanceNameBntDisabled.value = true; + _self.resetPasswordBntDisabled.value = true; + } + ] + ]; + for (const key of arrData) { + if (key[0](val)) { + key[1](val); + break; + } + } + }; + + checkAll = (event: boolean) => { + const newData = this.reactiveArr.tableData; + this.reactiveArr.tableData.map(item => { + // toggleRowSelection接收两个参数,第一个是被勾选的数据,第二个是选中状态(注:需要注册 ref 来引用) + if (event) { + for(let i = 0; i < newData.length; i++) { + // 未添加的才插入,否则数据会冗余 + if (!this.reactiveArr.arr.some((s: {instanceId: string;}) => s.instanceId === newData[i].instanceId)) { + this.reactiveArr.arr.push(newData[i]); + } + } + } + else { + for (let i = 0; i< this.reactiveArr.tableData.length; i++) { + for (let j = 0; j< this.reactiveArr.currentData.length; j++){ + // 移除当前页currentData的数据 + if (this.reactiveArr.currentData[j].instanceId === this.reactiveArr.tableData[i].instanceId) { + this.reactiveArr.currentData.splice(j, 1); + } + } + for(let k = 0; k < this.reactiveArr.arr.length; k++){ + // 移除当前页currentData的数据 + if (this.reactiveArr.arr[k].instanceId === this.reactiveArr.tableData[i].instanceId) { + this.reactiveArr.arr.splice(k, 1); + } + } + } + } + this.filter.tableRef?.value?.toggleRowSelection(item, event); + // this.tableRef.value?.toggleRowSelection(item, event); + }); + }; +}; + +export default DeviceList; diff --git a/bmp-operation-web/src/views/deviceManagement/list/table/filterStyle.ts b/bmp-operation-web/src/views/deviceManagement/list/table/filterStyle.ts new file mode 100644 index 0000000..b377bdc --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/table/filterStyle.ts @@ -0,0 +1,155 @@ +class FilterStyleOperate { + classNameData = [ + { + name: 'def-type-status8', + type: 'name' + }, + { + name: 'def-type-status9', + type: 'deviceSeries' + }, + { + name: 'def-type-status10', + type: 'manageStatus' + }, + { + name: 'def-type-status11', + type: 'collectStatus' + } + ]; + filterStatus: any = reactive({ + source: false, + architecture: false, + osType: false + }) + + constructor (props: any) { + onMounted(() => { + nextTick(() => { + this.customFilter(props); + }) + this.watchSearchTip(props); + this.watchFilter(props); + }) + }; + + watchSearchTip = (props: any) => { + watch(() => + props.deviceList.searchTip, (newValue) => { + if (!newValue.value) { + for (let index in this.filterStatus) { + this.filterStatus[index] = false; + } + } + else { + this.setFilterStatus(props.filterOperate.reactiveArr.filterParams); + } + }, { + deep: true + }); + }; + + watchFilter = (props: any) => { + watch(() => props.filterOperate.reactiveArr.filterParams, (newValue) => { + this.setFilterStatus(newValue); + }, {deep: true}) + }; + + setFilterStatus = (params: any) => { + this.classNameData.forEach((item) => { + if (['', undefined].includes(params[item.type])) { + this.filterStatus[item.type] = false; + return; + } + this.filterStatus[item.type] = true; + }) + }; + + customFilter = (props: any) => { + let filterName: HTMLElement | null; + let filterOpt: HTMLElement | null; + this.classNameData.forEach((item) => { + filterName = document.querySelector(`.${item.name} > .cell`); + filterOpt = document.querySelector(`.${item.name} > .cell > .el-table__column-filter-trigger`) + filterName?.addEventListener('click', () => { + // this.filterStatus[item.type] = false; + for (let index in this.filterStatus) { + this.filterStatus[index] = false; + } + }); + filterOpt?.addEventListener('click', () => { + if (!props.deviceList.searchTip.value) { + const clickStatus: any = { + 'name': () => { + this.filterStatus['deviceSeries'] = false; + this.filterStatus['manageStatus'] = false; + this.filterStatus['collectStatus'] = false; + }, + 'deviceSeries': () => { + this.filterStatus['name'] = false; + this.filterStatus['manageStatus'] = false; + this.filterStatus['collectStatus'] = false; + }, + 'manageStatus': () => { + this.filterStatus['deviceSeries'] = false; + this.filterStatus['name'] = false; + this.filterStatus['collectStatus'] = false; + }, + 'collectStatus': () => { + this.filterStatus['deviceSeries'] = false; + this.filterStatus['manageStatus'] = false; + this.filterStatus['name'] = false; + } + }; + clickStatus[item.type](); + } + this.filterStatus[item.type] = !this.filterStatus[item.type]; + }); + const filterOtherRegion = document.querySelectorAll('.el-table-filter'); + filterOtherRegion.forEach((_, index) => { + filterOtherRegion[index]?.addEventListener('click', (event) => { + event.stopPropagation(); + for (let index in this.filterStatus) { + for (const key of this.classNameData) { + if (key.type === index && props.deviceList.filter?.reactiveArr?.filterParams[key.type]?.length) { + this.filterStatus[index] = true; + } + } + } + }) + }) + let newType = []; + document.addEventListener('click', () => { + newType = []; + newType.push(item.type); + newType.forEach((ite) => { + this.filterDispose(ite, props); + }) + }) + }) + }; + + filterDispose = (type: string, props: any) => { + const filterVal = props.filterOperate.reactiveArr.filterParams; + if (props.deviceList.searchTip.value) { + for (let key in filterVal) { + if (key === type) { + this.filterStatus[key] = true; + } + else { + if (this.filterStatus[type] && Object.keys(filterVal).length > 1) { + this.filterStatus[type] = !this.filterStatus[type]; + } + else { + this.filterStatus[type] = false; + } + } + } + } + else { + this.filterStatus[type] = false; + } + } +}; + +export default FilterStyleOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/list/table/refresh.ts b/bmp-operation-web/src/views/deviceManagement/list/table/refresh.ts new file mode 100644 index 0000000..595fc5f --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/table/refresh.ts @@ -0,0 +1,33 @@ +type ImageLiatType = { + getDataList(): void; + reactiveArr: { + tableData: { + length: number; + }; + } +}; + +type ResetOperateType = { + reset(): void; +}; + +interface ParamsType { + deviceList: ImageLiatType; + resetOperate: ResetOperateType; +}; + +const refreshOperate = (deviceList: ParamsType['deviceList'], resetOperate: ParamsType['resetOperate']) => { + const refresh = () => { + if (!deviceList?.reactiveArr?.tableData?.length) { + resetOperate.reset(); + return; + } + deviceList.getDataList(); + }; + + return { + refresh + }; +}; + +export default refreshOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/list/table/reset.ts b/bmp-operation-web/src/views/deviceManagement/list/table/reset.ts new file mode 100644 index 0000000..09e2a26 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/table/reset.ts @@ -0,0 +1,43 @@ +type FilterType = { + tableRef?: { + value?: { + clearFilter(): void; + }; + }; + reactiveArr: { + filterParams: {}; + }; +}; + +type SearchType = { + hasClear: { + value: boolean; + }; + reactiveArr: { + searchParams: {}; + }; + request(): void; +}; + +interface ParamsType { + filter: FilterType; + search: SearchType; +}; + +const resetOperate = (filter: ParamsType['filter'], search: ParamsType['search']) => { + + const reset = () => { + sessionStorage?.removeItem('deviceTypeId'); + filter?.tableRef?.value?.clearFilter(); + filter.reactiveArr.filterParams = {}; + search.hasClear.value = true; + search.reactiveArr.searchParams = {}; + search.request(); + }; + + return { + reset + }; +}; + +export default resetOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/list/table/setEmpty.ts b/bmp-operation-web/src/views/deviceManagement/list/table/setEmpty.ts new file mode 100644 index 0000000..ef315c7 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/table/setEmpty.ts @@ -0,0 +1,63 @@ +/** + * @file + * @author +*/ + +import {language} from 'utils/publicClass.ts'; + +const p: HTMLElement = document.createElement('p'); +interface PropsType { + deviceList: { + reactiveArr: { + tableData: [] + } + } +} + +class SetEmpty { + emitValue: Function; + + constructor(props: PropsType, emitValue: Function) { + this.emitValue = emitValue; + this.watchTableData(props); + onUnmounted(() => p.innerHTML = ''); + }; + + watchTableData = (props: PropsType) => { + watch(() => props?.deviceList?.reactiveArr.tableData, (newValue) => { + if (!newValue?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.remove(); + }, {deep: true}) + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + ai!.innerHTML = ''; + const customText = document.querySelector('.device-list .el-scrollbar__view'); + if (!customText) return; + const str = ` + + ${language.t('table.empty')},${language.t('table.tip')} + + + ${language.t('deviceList.operate.exportDevice')} + + ` + const parser = new DOMParser(); + const doc = parser.parseFromString(str, 'text/html'); + p.className = 'custom-tip-count'; + customText.appendChild(p) + p.innerHTML = doc.body.innerHTML; + const clickOpt = document.querySelector('.device-list .custom-tip-count .empty-text'); + clickOpt!.addEventListener('click', () => { + this.emitValue('empty-click') + }) + }; +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/deviceManagement/list/table/tableData.vue b/bmp-operation-web/src/views/deviceManagement/list/table/tableData.vue new file mode 100644 index 0000000..715b27c --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/table/tableData.vue @@ -0,0 +1,1477 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/deviceManagement/list/table/tableFilter.ts b/bmp-operation-web/src/views/deviceManagement/list/table/tableFilter.ts new file mode 100644 index 0000000..7aaa0b3 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/table/tableFilter.ts @@ -0,0 +1,128 @@ +import store from 'store/index.ts'; +import {paginationOperate} from 'utils/publicClass.ts'; +import {OSSType, ReactiveArrType, FilterParamsType} from '../typeManagement'; + +let that: any = null; + +/** + * 筛选操作 +*/ +class FilterOperate { + // store库存储的oss数据类 + ossStore: OSSType = store.ossDataInfo(); + tableRef: { + [x: string]: unknown; + value?: { + toggleRowSelection(arg1: any, arg2: any): any; + clearFilter(): unknown; + clearSelection(): any; + } + } = {value: {clearFilter(): void{}, toggleRowSelection(): any{}, clearSelection(): any{}}}; + filterEmptyInfo: { // store + filterParams( + arg0: {[x: string]: number | string}, + arg1: OSSType, + arg2: ReactiveArrType, + arg3: FilterParamsType + ): Promise; + deleteEmtpyData(arg0: FilterParamsType): unknown; + } = store.filterEmpty; + // 复杂数据类型 + reactiveArr: { + filterParams: FilterParamsType; + // selectArr: any; + + } = reactive<{ + filterParams: FilterParamsType; + // selectArr: any; + }>({ + filterParams: {}, + // selectArr: [] + }); + fn: any; + + // 构造器 + constructor (fn: any) { + that = this; + that.fn = fn; + this.ossStore?.getModelList(); + this.ossStore?.getOssData(); + }; + + /** + * 获取表格ref + * @param {Object} tableEl 表格信息 + */ + getTableRef = (tableEl: {[x: string]: unknown}): void => { + this.tableRef = tableEl; + }; + + /** + * 机型名称filter + * @param {number} value 当前选中的value值 + * @param {Object} row 当前选中的这一项 + * @return {boolean} xxx 返回对应信息 + */ + nameFilter = (): boolean => { + // value: number, row: {deviceTypeName?: string} + return true; + // return row.deviceTypeName === this.ossStore?.deviceTypeId[value - 1]?.text; + }; + + /** + * 机型filter + * @param {number} value 当前选中的value值 + * @param {Object} row 当前选中的这一项 + * @return {boolean} xxx 返回对应信息 + */ + deviceSeriesFilter = (): boolean => { + // value: number, row: {deviceSeriesName: string} + return true; + // return row.deviceSeriesName === this.ossStore?.deviceSeries[value - 1]?.text; + }; + + statusFilter = () => { + return true; + } + + /** + * 管理状态filter + * @param {number} value 当前选中的value值 + * @param {Object} row 当前选中的这一项 + * @return {boolean} xxx 返回对应信息 + */ + manageStatusFilter = (): boolean => { + // value: number, row: {manageStatusName: string} + return true; + // return row.manageStatusName === this.textLocale(this.ossStore?.manageStatus[value - 1]?.text); + }; + + textLocale (str: string) { + return str.toLowerCase().split(/\s+/).map((item) => { + return item.slice(0, 1).toLocaleLowerCase() + item.slice(1); + }).join(' '); + }; + + /** + * @param {Object} filter 需要过滤的数据 + */ + filterChange = (filter: {[x: string]: number | string}) => { + this.tableRef.value?.clearSelection() + const filterParams: FilterParamsType = { + manageStatus: 'manageStatus', + deviceSeries: 'deviceSeries', + deviceTypeId: 'deviceTypeId', + collectStatus: 'collectStatus' + }; + this.filterEmptyInfo.filterParams(filter, this.ossStore, this.reactiveArr, filterParams) + .then((_: any) => { + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn(); + }) + }; +}; + +export default FilterOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/list/table/tableScroll.ts b/bmp-operation-web/src/views/deviceManagement/list/table/tableScroll.ts new file mode 100644 index 0000000..ecb7060 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/table/tableScroll.ts @@ -0,0 +1,96 @@ +import store from 'store/index.ts'; +import {tableScroll} from 'utils/index.ts'; +import {HeightType2, HeightType3} from '@utils/publicType'; + +interface TableScrollDataType { + scrollTimer: null | number; + searchTipHeight: number; + fixedHeight: Ref; + tableMaxHeight: Ref; + headerTitle: Ref; + operate: Ref; + operateBtn: Ref; +}; + +const tableScrollOperate = (filters: any['filters'], search: any['search'], searchTip: {value: boolean;}) => { + const data: TableScrollDataType = { + scrollTimer: null, + searchTipHeight: 13, + fixedHeight: ref(0), + tableMaxHeight: ref(0), + headerTitle: ref({offsetHeight: 0, scrollHeight: 0}), + operate: ref({offsetHeight: 0, scrollHeight: 0}), + operateBtn: ref({offsetHeight: 0}) + }; + + onMounted(() => { + setScroll(setHeight(), data.tableMaxHeight); + onResize(setHeight(), data.tableMaxHeight); + }); + + onUnmounted(() => { + clearTimeout(data.scrollTimer as number); + }) + + watch(() => [ + filters.filterParams, + search.searchParams, + searchTip + ], (newValue) => { + if (newValue[2].value) { + setScroll(data.fixedHeight.value, data.tableMaxHeight); + } + }, {deep: true}); + + watch(() => store.navigationBarStatus.hasNavigationBar, (_: boolean) => { + data.scrollTimer = setTimeout(() => { + setScroll(setHeight(), data.tableMaxHeight); + }, 200) + }); + + const onResize = (_: number, tableMaxHeight: {value: number}) => { + window.onresize = () => { + setScroll(setHeight(), tableMaxHeight); + }; + }; + + const setHeight = () => { + const header = data.headerTitle.value; + const operate = data.operate.value; + data.fixedHeight.value = header.offsetHeight * 2.9 + operate.offsetHeight + data.operateBtn.value.offsetHeight; + const countHeight: number = data.fixedHeight.value; + return countHeight; + }; + + + const setScroll = (countHeight: number, tableMaxHeight: {value: number}) => { + const params = {...filters.filterParams, ...search.searchParams}; + if (Object.values(params).some((item) => item !== '')) { + tableScroll(countHeight + data.searchTipHeight, tableMaxHeight); + return; + } + tableScroll(countHeight, tableMaxHeight); + }; + + const getHeaderRef = (val: {value: HeightType3;}) => { + data.headerTitle.value = val.value; + }; + + const getOperateRef = (val: {value: HeightType3;})=> { + data.operate.value = val.value; + }; + + + const getBtnRef = (val: {value: HeightType2}) => { + data.operateBtn.value = val.value; + }; + + return { + ...data, + getBtnRef, + getHeaderRef, + getOperateRef + } +}; + +export default tableScrollOperate; diff --git a/bmp-operation-web/src/views/deviceManagement/list/table/tooltipOpt.ts b/bmp-operation-web/src/views/deviceManagement/list/table/tooltipOpt.ts new file mode 100644 index 0000000..e7d0989 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/table/tooltipOpt.ts @@ -0,0 +1,54 @@ +import {language} from 'utils/publicClass.ts'; +import DeviceStaticData from 'staticData/device/index.ts'; + +class TooltipOpt { + + up = (item: {manageStatus: string}): boolean => { + return ['in', 'putawayfail'].includes(item.manageStatus) + }; + + down = (item: {manageStatus: string}): boolean => { + return ['putaway'].includes(item.manageStatus); + }; + + resetInstance = (instanceStatus: string): boolean => { + return DeviceStaticData.resetInstanceStatus.includes(instanceStatus); + }; + + runningStatus = (instanceStatus: string): boolean => { + return ['running'].includes(instanceStatus); + }; + + stoppedStatus = (instanceStatus: string): boolean => { + return ['stopped'].includes(instanceStatus); + }; + + resetPasswordStatus = (instanceStatus: string): boolean => { + return ['stopped', 'Resetpasswd failed'].includes(instanceStatus); + }; + + resetSystemStatus = (instanceStatus: string): boolean => { + return ['stopped', 'Reinstall failed'].includes(instanceStatus); + }; + + deviceRemove = (instanceStatus: string): boolean => { + return ['running', 'stopped', 'Resetpasswd failed', 'Reinstall failed'].includes(instanceStatus); + }; + + recoveryInstance = (item: {instanceStatus: string; locked: string;}): boolean => { + return DeviceStaticData.recoveryInstance.includes(item.instanceStatus) && item.locked === 'unlocked'; + }; + + recoveryInstanceContent = (locked: string) => { + const text = new Map([ + ['locked', language.t('deviceList.tooltip.lock')] + ]); + return text.get(locked)?? language.t('deviceList.tooltip.recovery'); + }; + + deviceDelete = (manageStatus: string): boolean => { + return DeviceStaticData.deleteDevice.includes(manageStatus); + }; +}; + +export default TooltipOpt; diff --git a/bmp-operation-web/src/views/deviceManagement/list/typeManagement.ts b/bmp-operation-web/src/views/deviceManagement/list/typeManagement.ts new file mode 100644 index 0000000..5015135 --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/typeManagement.ts @@ -0,0 +1,61 @@ +/** + * text类 +*/ +type TextType = { + [x: string]: { + text: string; + }; +}; + +interface OSSType { + deviceSeries: TextType; + manageStatus: TextType; + deviceTypeId: TextType; + getModelList(): void; + getOssData(): void; +}; +interface SearchArrType { + searchParams: { + sn?: string; + userName?: string; + }; + selectOption: { + value: number; + label: string; + }[]; +}; + + +/** + * filter参数类 +*/ +type FilterParamsType = {deviceSeries?: string; manageStatus?: string; name?: string; deviceTypeId?: string; collectStatus?: string;}; + + +/** + * 复杂数据类型类 +*/ +type ReactiveArrType = {filterParams?: FilterParamsType;}; + +type HeightType = {offsetHeight: number; offsetTop: number;}; + +type OperateHeightType = Pick; + +// table ts +type TableType = {devices: string;} & {[x: string]: string | boolean;}; +// 跳转路由 ts +type JumpRouterType = {sn: string; deviceId: string}; +// 导出类型 +type ExportType = {devicesListExportAPI: Function; hasExportData: {value: boolean;}; exportData: Function;}; + +export { + OSSType, + SearchArrType, + ReactiveArrType, + FilterParamsType, + HeightType, + OperateHeightType, + TableType, + JumpRouterType, + ExportType +}; diff --git a/bmp-operation-web/src/views/deviceManagement/list/upDownDelete/upDownDelete.ts b/bmp-operation-web/src/views/deviceManagement/list/upDownDelete/upDownDelete.ts new file mode 100644 index 0000000..9c82bad --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/upDownDelete/upDownDelete.ts @@ -0,0 +1,78 @@ +import {CurrentInstance} from 'utils/publicClass.ts'; + +interface ParamsType { + deviceList: { + reactiveArr: { + tableData: string | unknown[]; + }; + getDataList: () => void; + }; + reset: { + reset: () => void; + }; +}; + +interface DataType { + deviceId: Ref; + upDownDeleteDiaLog: Ref; + upDownDeleteTitle: Ref; +}; + +const upDownDelete = (deviceList: ParamsType['deviceList'], reset: ParamsType['reset']) => { + const data: DataType = { + deviceId: ref(''), + // 上架、下架、删除设备组件状态 + upDownDeleteDiaLog: ref(false), + // 上架、下架、删除设备标题名称 + upDownDeleteTitle: ref('') + }; + + const mitt = new CurrentInstance(); + + /** + * 上架、下架、删除设备点击事件 + * @param {Object} item 当前点击的这一项 + * @param {string} type 当前点击这一项状态 + */ + const upDownDeleteClick = async (item: {deviceId: string;}, type: string, status: boolean): Promise => { + if (!status) return; + data.deviceId.value = item.deviceId; + data.upDownDeleteDiaLog.value = !data.upDownDeleteDiaLog.value; + data.upDownDeleteTitle.value = type; + await nextTick(() => { + mitt.instanceMitt?.proxy?.$Bus?.emit('device-table', {list: item}); + }); + }; + + /** + * 上架、下架、删除组件取消事件 + * @param {boolean} type 弹窗状态 + * @return {boolean} upDownDeleteDiaLog.value 上架、下架、删除设备组件弹窗状态 + */ + const upDownDeleteCancel = (type: boolean): boolean => { + return data.upDownDeleteDiaLog.value = type; + }; + + const upDownDeleteSure = (type: string) => { + if (type === 'delete') { + if (deviceList.reactiveArr.tableData.length === 1) { + reset.reset(); + } + else { + deviceList.getDataList(); + } + } + else { + deviceList.getDataList(); + } + }; + + return { + ...data, + upDownDeleteClick, + upDownDeleteCancel, + upDownDeleteSure + } +}; + +export default upDownDelete; diff --git a/bmp-operation-web/src/views/deviceManagement/list/upDownDelete/upDownDelete.vue b/bmp-operation-web/src/views/deviceManagement/list/upDownDelete/upDownDelete.vue new file mode 100644 index 0000000..937a41c --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/list/upDownDelete/upDownDelete.vue @@ -0,0 +1,21 @@ + + + diff --git a/bmp-operation-web/src/views/deviceManagement/navRouter.ts b/bmp-operation-web/src/views/deviceManagement/navRouter.ts new file mode 100644 index 0000000..45450fe --- /dev/null +++ b/bmp-operation-web/src/views/deviceManagement/navRouter.ts @@ -0,0 +1,18 @@ +/** + * @file + * @author +*/ + +import {language} from "utils/publicClass.ts"; + +const deviceNavData = (pathUrl: (arg0: string) => void, imgUrl: (arg0: string) => void) => { + return { + title: language.t('navigationBar.list.deviceManagement'), + defaultImg: imgUrl('deviceDefault'), + changeImg: imgUrl('device'), + path: pathUrl('deviceList'), + otherPath: [pathUrl('deviceList'), pathUrl('deviceDetail')] + } +}; + +export default deviceNavData; diff --git a/bmp-operation-web/src/views/idcManagement/detail/basicInfo/base.ts b/bmp-operation-web/src/views/idcManagement/detail/basicInfo/base.ts new file mode 100644 index 0000000..b54ab92 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/detail/basicInfo/base.ts @@ -0,0 +1,52 @@ +/** + * @file + * @author +*/ +import {language} from 'utils/publicClass.ts'; + +class BaseInfoOpt { + static baseInfo = [ + { + label: language.t('idcDetail.basicInfo.label.name'), + info: 'name', + class: 'set-wrap info-name' + }, + { + label: language.t('idcDetail.basicInfo.label.englishCode'), + info: 'nameEn', + class: 'set-wrap info-name' + }, + { + label: language.t('idcDetail.basicInfo.label.grade'), + info: 'level', + class: 'set-wrap info-name' + }, + { + label: language.t('idcDetail.basicInfo.label.address'), + info: 'address', + class: 'set-wrap info-name' + }, + { + label: language.t('idcDetail.basicInfo.label.createTime'), + info: 'createTime', + class: 'set-wrap info-name' + }, + { + label: language.t('idcDetail.basicInfo.label.createPeople'), + info: 'createdBy', + class: 'set-wrap info-name' + }, + { + label: language.t('idcDetail.basicInfo.label.updateTime'), + info: 'updateTime', + class: 'set-wrap info-name' + }, + { + label: language.t('idcDetail.basicInfo.label.updatePeople'), + info: 'updatedBy', + class: 'set-wrap info-name' + } + ] +} + +export default BaseInfoOpt; diff --git a/bmp-operation-web/src/views/idcManagement/detail/basicInfo/basicInfo.vue b/bmp-operation-web/src/views/idcManagement/detail/basicInfo/basicInfo.vue new file mode 100644 index 0000000..0ec91d6 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/detail/basicInfo/basicInfo.vue @@ -0,0 +1,46 @@ + + + diff --git a/bmp-operation-web/src/views/idcManagement/detail/editIdc/edit.ts b/bmp-operation-web/src/views/idcManagement/detail/editIdc/edit.ts new file mode 100644 index 0000000..666f2b7 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/detail/editIdc/edit.ts @@ -0,0 +1,38 @@ +const editIdcOperate = (idcDetail: any) => { + // 编辑机房弹窗状态 + const editIdcDiaLog: Ref = ref(false); + + /** + * 编辑机房弹窗取消事件,弹窗关闭 + * @param {Array} type 控制弹窗显示隐藏 true 显示 false 隐藏 + * @return {boolean} editIdcDiaLog.value true-显示 false-隐藏 + */ + const editIdcCancel = (type: boolean): boolean => { + return editIdcDiaLog.value = type; + }; + + const editIdcSure = () => { + idcDetail.isLoading.value = true; + idcDetail.getDetailData(); + }; + + /** + * 是否可以点击编辑操作 + * @param {boolean} type false 说明不可以在验证完安全校验后进行编辑操作 + */ + const hasEditOperateClick = (type: boolean): void => { + if (!type) { + // 遍历数据 + idcDetail.getDetailData(); + } + }; + + return { + editIdcDiaLog, + editIdcCancel, + editIdcSure, + hasEditOperateClick + }; +}; + +export default editIdcOperate; diff --git a/bmp-operation-web/src/views/idcManagement/detail/editIdc/editIdcData.vue b/bmp-operation-web/src/views/idcManagement/detail/editIdc/editIdcData.vue new file mode 100644 index 0000000..5122e6a --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/detail/editIdc/editIdcData.vue @@ -0,0 +1,26 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/idcManagement/detail/idcDetail.vue b/bmp-operation-web/src/views/idcManagement/detail/idcDetail.vue new file mode 100644 index 0000000..556b71c --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/detail/idcDetail.vue @@ -0,0 +1,58 @@ + + + diff --git a/bmp-operation-web/src/views/idcManagement/detail/idcDetail/idcDetail.ts b/bmp-operation-web/src/views/idcManagement/detail/idcDetail/idcDetail.ts new file mode 100644 index 0000000..8ac37a6 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/detail/idcDetail/idcDetail.ts @@ -0,0 +1,92 @@ +import {AxiosError} from 'axios'; +import {msgTip} from 'utils/index.ts'; // 详情表格class类 +import {language, CurrentInstance} from 'utils/publicClass.ts'; +import {NewTableType, CurrencyType, ReactiveArrType, LocationQueryValue} from '../typeManagement'; +import RegularContent from 'utils/regular.ts'; +import AllStaticData from 'staticData/staticData.ts'; + +/** + * 机房详情 +*/ +class IdcDetail { + // loading态 + isLoading: Ref = ref(true); + // 上一个页面携带的idcid,用来发送详情请求 + idcId: LocationQueryValue | LocationQueryValue[] = ''; + reactiveArr: ReactiveArrType = reactive({ + detailInfo: {}, + tableData: [] // 表格全局管理数据 + }); + // 是否显示密码 + password: Ref = ref(''); + instanceProxy = new CurrentInstance().proxy; + + constructor (routerOperate: any) { + this.idcId = routerOperate.router?.currentRoute?.value?.query?.idcId?? ''; + this.getDetailData(routerOperate); + }; + + getDetailData = async (routerOperate: any) => { + const {value} : {value: string;} = this.password; + const params: {show?: string;} = value?.length ? {show: this.password.value} : {}; + try { + const detailApi = await this.instanceProxy.$idcApi.idcDetailAPI({idcid: this.idcId, ...params}); + if (detailApi?.data?.result && Object.keys(detailApi.data?.result).length) { + this.reactiveArr.detailInfo = detailApi.data.result; + const newTableData: NewTableType[][] = this.#processingData(detailApi.data, params); + this.reactiveArr.tableData = newTableData[0]; + return; + } + throw new Error(''); + } + catch (e) { + const err = e as AxiosError; + this.reactiveArr.tableData = []; + this.reactiveArr.detailInfo = {}; + const path: string = this.instanceProxy.$defInfo.routerPath('idcList'); + if (AllStaticData.noFoundData.includes(err.message)) { + routerOperate.router.push(path); + return; + } + err.message && msgTip.error(err.message); + } + finally { + this.isLoading.value = false; + } + }; + + #processingData = (data: {result: CurrencyType;}, params: {show?: string}) => { + return [data.result].map((item: CurrencyType): NewTableType[] => { + return [ + { + name: language.t('idcDetail.allAdministration.loginAccount'), + user: item.iloUser, + password: this.#setPassword('iloPassword', params, item), + type: 'iloPassword', + hasPassword: 'iloPassword' === params?.show + }, + { + name: language.t('idcDetail.allAdministration.switchboardOneNum'), + user: item.switchUser1, + password: this.#setPassword('switchPassword1', params, item), + type: 'switchPassword1', + hasPassword: 'switchPassword1' === params?.show + }, + { + name: language.t('idcDetail.allAdministration.switchboardTwoNum'), + user: item.switchUser2, + password:this.#setPassword('switchPassword2', params, item), + type: 'switchPassword2', + hasPassword: 'switchPassword2' === params?.show + } + ] + }); + }; + + #setPassword = (type: string, ...args: any) => { + const {$filter} = this.instanceProxy; + return RegularContent.hasEqualReg(type).test(args[0]?.show) ? $filter.emptyFilter((args[1][type])) : ''; + }; +}; + +export default IdcDetail; diff --git a/bmp-operation-web/src/views/idcManagement/detail/idcDetail/showPassword.ts b/bmp-operation-web/src/views/idcManagement/detail/idcDetail/showPassword.ts new file mode 100644 index 0000000..68eb379 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/detail/idcDetail/showPassword.ts @@ -0,0 +1,34 @@ + +import {PasswordType} from '../typeManagement'; + +/** + * 是否显示密码 + * @param {Object} verificationOperate 验证操作 + * @param {Object} idcDetail 当前操作的这一项 +*/ +const hasShowPassword = (verificationOperate: PasswordType['validate'], idcDetail: PasswordType['idcDetail']) => { + + /** + * 是否明文显示密码 + * @param {Object} item 当前点击的这一项 + * @param {string} type 当前点击的状态是 open or close + */ + const hasPasswordClick = (item: {hasPassword: boolean; type: string; password: string;}, type: string): void => { + verificationOperate.hasEditOperate.value = false; + idcDetail.password.value = item.type; + if (type === 'close') { + item.hasPassword = !item.hasPassword; + item.password = '********'; + idcDetail.password.value = ''; + return; + } + verificationOperate.securityVerificationDiaLog.value = !verificationOperate.securityVerificationDiaLog.value; + verificationOperate.hasEditOperate.value = false; + }; + + return { + hasPasswordClick + } +}; + +export default hasShowPassword; diff --git a/bmp-operation-web/src/views/idcManagement/detail/methods.ts b/bmp-operation-web/src/views/idcManagement/detail/methods.ts new file mode 100644 index 0000000..4c99e13 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/detail/methods.ts @@ -0,0 +1,11 @@ +import verificationOperate from './verification/verificationOperate'; +import editIdcOperate from './editIdc/edit'; +import IdcDetailData from './idcDetail/idcDetail'; +import hasShowPassword from './idcDetail/showPassword'; + +export { + verificationOperate, + editIdcOperate, + IdcDetailData, + hasShowPassword +}; diff --git a/bmp-operation-web/src/views/idcManagement/detail/module.ts b/bmp-operation-web/src/views/idcManagement/detail/module.ts new file mode 100644 index 0000000..ac13060 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/detail/module.ts @@ -0,0 +1,13 @@ +import TableData from './table/tableData.vue'; +import BasicInfo from './basicInfo/basicInfo.vue'; +import EditIdcData from './editIdc/editIdcData.vue'; +import Verification from './verification/verification.vue'; + +const pluginComp = { + TableData, + BasicInfo, + EditIdcData, + Verification +}; + +export default pluginComp; diff --git a/bmp-operation-web/src/views/idcManagement/detail/page.ts b/bmp-operation-web/src/views/idcManagement/detail/page.ts new file mode 100644 index 0000000..33f9a52 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/detail/page.ts @@ -0,0 +1,10 @@ +const IdcDetail = () => import(/* webpackChunkName: "IdcDetail" */ './idcDetail.vue'); + +export default { + path: '/IdcManagement/idcDetail', + name: 'IdcDetail', + component: IdcDetail, + meta: { + type: 'idcDetail' + } +}; diff --git a/bmp-operation-web/src/views/idcManagement/detail/table/setEmpty.ts b/bmp-operation-web/src/views/idcManagement/detail/table/setEmpty.ts new file mode 100644 index 0000000..c3b04db --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/detail/table/setEmpty.ts @@ -0,0 +1,44 @@ +/** + * @file + * @author +*/ + +import {language} from 'utils/publicClass.ts'; + +const p = document.createElement('p'); +const span = document.createElement('span'); + +class SetEmpty { + emitValue: any; + + constructor(props: any, emitValue: any) { + this.emitValue = emitValue; + this.watchTableData(props); + onUnmounted(() => p.innerHTML = ''); + }; + + watchTableData = (props: any) => { + watch(() => props?.idcDetail?.reactiveArr?.tableData, (newValue) => { + if (!newValue?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.innerHTML= ''; + }) + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + const customText = document.querySelector('.idc-detail .el-scrollbar__view'); + if (!customText) return; + p.className = 'custom-tip-count'; + customText.appendChild(p) + ai!.innerHTML = ''; + p.appendChild(span) + span.innerHTML = `${language.t('table.empty')}`; + }; +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/idcManagement/detail/table/tableData.vue b/bmp-operation-web/src/views/idcManagement/detail/table/tableData.vue new file mode 100644 index 0000000..edf8ee1 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/detail/table/tableData.vue @@ -0,0 +1,97 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/idcManagement/detail/typeManagement.ts b/bmp-operation-web/src/views/idcManagement/detail/typeManagement.ts new file mode 100644 index 0000000..09234f3 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/detail/typeManagement.ts @@ -0,0 +1,44 @@ +import {Router, CurrencyType, LocationQueryValue} from '@utils/publicType'; + +type RouterType = {router: Router; jumpRouter(path: string): void;}; + +/** + * 新table数据类型 +*/ +interface NewTableType { + name: string; + user: string; + password: string; + hasPassword: boolean; + type: string; +}; + +interface ReactiveArrType { + detailInfo: CurrencyType; + tableData: NewTableType[] +}; + +interface PasswordType { + validate: { + securityVerificationDiaLog: { + value: boolean; + }; + hasEditOperate: { + value: boolean; + }; + } + idcDetail: { + password: { + value: string; + } + } +}; + +export { + RouterType, + NewTableType, + CurrencyType, + PasswordType, + ReactiveArrType, + LocationQueryValue +}; diff --git a/bmp-operation-web/src/views/idcManagement/detail/verification/verification.vue b/bmp-operation-web/src/views/idcManagement/detail/verification/verification.vue new file mode 100644 index 0000000..8777d3c --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/detail/verification/verification.vue @@ -0,0 +1,22 @@ + + + diff --git a/bmp-operation-web/src/views/idcManagement/detail/verification/verificationOperate.ts b/bmp-operation-web/src/views/idcManagement/detail/verification/verificationOperate.ts new file mode 100644 index 0000000..02055ed --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/detail/verification/verificationOperate.ts @@ -0,0 +1,60 @@ +import {StatusType} from '@utils/publicType'; + +interface DataType { + securityVerificationDiaLog: Ref; + hasEditOperate: Ref; +}; + +interface EditIdcType { + editIdcDiaLog: { + value: boolean; + } +}; + +/** + * 安全验证操作 + * @param {Object} 编辑机房操作 +*/ +const verificationOperate = (editIdcOperate: EditIdcType) => { + const data: DataType = { + // 安全验证弹窗状态 + securityVerificationDiaLog: ref(false), + // 是否进行编辑操作-默认true + hasEditOperate: ref(true) + }; + + /** + * 点击操作,控制安全验证弹窗显示隐藏 + * @return {boolean} securityVerificationDiaLog.value true-显示 false-隐藏 + */ + const operateClick: StatusType<() => boolean> = (): boolean => { + data.hasEditOperate.value = true; + return data.securityVerificationDiaLog.value = !data.securityVerificationDiaLog.value; + }; + + /** + * 安全验证弹窗-显示隐藏 + * @return {boolean} editIdcDiaLog.value true-显示 false-隐藏 + */ + const securityVerificationSure: StatusType<() => boolean> = (): boolean => { + return editIdcOperate.editIdcDiaLog.value = true; + }; + + /** + * 安全验证弹窗取消事件,弹窗关闭 + * @param {Array} type 控制弹窗显示隐藏 true 显示 false 隐藏 + * @return {boolean} securityVerificationDiaLog.value true-显示 false-隐藏 + */ + const securityVerificationCancel = (type: boolean): boolean => { + return data.securityVerificationDiaLog.value = type; + }; + + return { + ...data, + operateClick, + securityVerificationSure, + securityVerificationCancel + } +}; + +export default verificationOperate; diff --git a/bmp-operation-web/src/views/idcManagement/list/customList/custom.ts b/bmp-operation-web/src/views/idcManagement/list/customList/custom.ts new file mode 100644 index 0000000..a7172c4 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/customList/custom.ts @@ -0,0 +1,10 @@ +/** + * @file + * @author +*/ + +import useCustom from 'hooks/custom/useCustom.ts'; + +const customOperate = useCustom('idcList').info; + +export default customOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/idcManagement/list/customList/customList.vue b/bmp-operation-web/src/views/idcManagement/list/customList/customList.vue new file mode 100644 index 0000000..c64bdcd --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/customList/customList.vue @@ -0,0 +1,9 @@ + + diff --git a/bmp-operation-web/src/views/idcManagement/list/editIdc/editIdcData.vue b/bmp-operation-web/src/views/idcManagement/list/editIdc/editIdcData.vue new file mode 100644 index 0000000..a4c2f22 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/editIdc/editIdcData.vue @@ -0,0 +1,21 @@ + + diff --git a/bmp-operation-web/src/views/idcManagement/list/editIdc/editIdcOperate.ts b/bmp-operation-web/src/views/idcManagement/list/editIdc/editIdcOperate.ts new file mode 100644 index 0000000..973b87f --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/editIdc/editIdcOperate.ts @@ -0,0 +1,40 @@ +/** + * @file + * @author +*/ + +import {StatusParamsType} from '@utils/publicType'; + +interface IdcListType { + getDataList(): void; +}; + +const editIdcOperate = (idcList: IdcListType) => { + + // 编辑机房弹窗状态 + const editingComputerRoomDiaLog: Ref = ref(false); + + /** + * 编辑机房弹窗取消事件,弹窗关闭 + * @param {Array} type 控制弹窗显示隐藏 true 显示 false 隐藏 + * @return {boolean} editingComputerRoomDiaLog.value true-显示 false-隐藏 + */ + const editIdcCancel: StatusParamsType <(type: boolean) => boolean> = (type: boolean): boolean => { + return editingComputerRoomDiaLog.value = type; + }; + + /** + * 编辑机房成功的操作 + */ + const editIdcSure = () => { + idcList.getDataList(); + }; + + return { + editingComputerRoomDiaLog, + editIdcCancel, + editIdcSure + } +}; + +export default editIdcOperate; diff --git a/bmp-operation-web/src/views/idcManagement/list/export/export.ts b/bmp-operation-web/src/views/idcManagement/list/export/export.ts new file mode 100644 index 0000000..00c1d04 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/export/export.ts @@ -0,0 +1,20 @@ +/** + * @file + * @author +*/ + +import {ExportDataOperate, CurrentInstance} from 'utils/publicClass.ts'; + +class ExportData { + + proxy = new CurrentInstance().proxy; + + exportData = (that: {isLoading: {value: boolean}}) => { + new ExportDataOperate(this.proxy.$idcApi.idcListExportAPI).exportData(that); + } +}; + +export { + ExportData, + ExportDataOperate +}; diff --git a/bmp-operation-web/src/views/idcManagement/list/export/exportData.vue b/bmp-operation-web/src/views/idcManagement/list/export/exportData.vue new file mode 100644 index 0000000..6de9fb1 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/export/exportData.vue @@ -0,0 +1,20 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/idcManagement/list/idcList.vue b/bmp-operation-web/src/views/idcManagement/list/idcList.vue new file mode 100644 index 0000000..ec924be --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/idcList.vue @@ -0,0 +1,72 @@ + + + + + diff --git a/bmp-operation-web/src/views/idcManagement/list/idcList/idcList.ts b/bmp-operation-web/src/views/idcManagement/list/idcList/idcList.ts new file mode 100644 index 0000000..75f24e7 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/idcList/idcList.ts @@ -0,0 +1,73 @@ +import {AxiosError} from 'axios'; +import {msgTip} from 'utils/index.ts'; +import {CurrencyType1, PaginationType} from '@utils/publicType'; +import {paginationOperate, CurrentInstance} from 'utils/publicClass.ts'; +import IdcStaticData from 'staticData/idc/index.ts'; + +/** + * 机房列表 +*/ +class IdcList { + // init: Ref = ref(true); + // loading态 + isLoading: Ref = ref(true); + + // 复杂响应式数据集合 + reactiveArr: { + filterParams: {name: string}; + tableData: CurrencyType1[]; + } = reactive<{ + filterParams: {name: string}; + tableData: CurrencyType1[] + }>({ + filterParams: { + name: '' + }, + tableData: [] // 表格数据-机房列表 + }); + proxy = new CurrentInstance().proxy; + templateData = IdcStaticData.templateData; + + // 构造器 + constructor() { + this.getDataList(); + }; + + /** + * 获取列表数据 + */ + getDataList = async () => { + this.isLoading.value = true; + try { + const params: PaginationType = { + pageNumber: paginationOperate.pageNumber.value, + pageSize: paginationOperate.pageSize.value + }; + const idcInfo = await this.proxy.$idcApi.idcListAPI(params); + if (idcInfo?.data?.result?.idcs?.length) { + const {idcs, totalCount} : {idcs: CurrencyType1[], totalCount: number} = idcInfo.data.result; + idcs.forEach((item: CurrencyType1, index: number) => { + IdcStaticData.idcTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }); + }); + this.reactiveArr.tableData = idcs; + paginationOperate.total.value = totalCount; + return; + } + throw new Error(''); + } + catch (e) { + const err = e as AxiosError; + paginationOperate.total.value = 0; + this.reactiveArr.tableData = []; + err.message && msgTip.error(err.message); + } + finally { + this.isLoading.value = false; + // this.init.value = false; + } + }; +}; + +export default IdcList; diff --git a/bmp-operation-web/src/views/idcManagement/list/methods.ts b/bmp-operation-web/src/views/idcManagement/list/methods.ts new file mode 100644 index 0000000..7c580d7 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/methods.ts @@ -0,0 +1,15 @@ +/** + * @file + * @author +*/ + +const requireAll = (requireContext: T) => { + // keys 返回字典的所有的key + return requireContext.keys().map(requireContext); +} + +const methods = [ + ...requireAll(require.context('./', true, /^((?!methods|module|page|setEmpty).)*\.ts$/),) +] + +export default methods; diff --git a/bmp-operation-web/src/views/idcManagement/list/module.ts b/bmp-operation-web/src/views/idcManagement/list/module.ts new file mode 100644 index 0000000..0f995d4 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/module.ts @@ -0,0 +1,16 @@ +/** + * @file + * @author +*/ + +const requireAll = (requireContext: T) => { + // keys 返回字典的所有的key + return requireContext.keys().map(requireContext); +} + +const pluginComp = [ + ...requireAll(require.context('./', true, /^((?!idcList).)*\.vue$/)) +] + + +export default pluginComp; \ No newline at end of file diff --git a/bmp-operation-web/src/views/idcManagement/list/page.ts b/bmp-operation-web/src/views/idcManagement/list/page.ts new file mode 100644 index 0000000..c8721d8 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/page.ts @@ -0,0 +1,24 @@ +const IdcList = () => import(/* webpackChunkName: "IdcList" */ './idcList.vue'); + +export default { + def: { + path: '/:pathMatch(.*)', + redirect: { + name: 'IdcList' + } + }, + noDef: { + path: '/IdcManagement/idcList', + name: 'IdcList', + component: IdcList, + meta: { + type: 'idcList' + } + } + // path: '/IdcManagement/idcList', + // name: 'IdcList', + // component: IdcList, + // meta: { + // type: 'idcList' + // } +}; diff --git a/bmp-operation-web/src/views/idcManagement/list/table/setEmpty.ts b/bmp-operation-web/src/views/idcManagement/list/table/setEmpty.ts new file mode 100644 index 0000000..704a47e --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/table/setEmpty.ts @@ -0,0 +1,42 @@ +/** + * @file + * @author +*/ + +import {language} from 'utils/publicClass.ts'; + +const p = document.createElement('p'); +const span = document.createElement('span'); + +class SetEmpty { + + constructor(props: any) { + this.watchTableData(props); + onUnmounted(() => p.innerHTML = ''); + }; + + watchTableData = (props: any) => { + watch(() => props?.idcList?.reactiveArr.tableData, (newValue) => { + if (!newValue?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.innerHTML= ''; + }, {deep: true}) + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + const customText = document.querySelector('.idc-list .el-scrollbar__view'); + if (!customText) return; + ai!.innerHTML = ''; + p.className = 'custom-tip-count'; + customText.appendChild(p) + p.appendChild(span) + span.innerHTML = `${language.t('table.empty')}`; + }; +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/idcManagement/list/table/tableList.vue b/bmp-operation-web/src/views/idcManagement/list/table/tableList.vue new file mode 100644 index 0000000..2de0ef1 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/table/tableList.vue @@ -0,0 +1,111 @@ + + + + diff --git a/bmp-operation-web/src/views/idcManagement/list/table/tableScroll.ts b/bmp-operation-web/src/views/idcManagement/list/table/tableScroll.ts new file mode 100644 index 0000000..c7dd087 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/table/tableScroll.ts @@ -0,0 +1,44 @@ +/** + * @file + * @author +*/ + +import {HeightType3} from '@utils/publicType'; +import {ScrollOperate} from 'utils/publicClass.ts'; + +interface DataType { + tableMaxHeight: Ref; + headerTitle: Ref; + operate: Ref; +}; + +const tableScrollOperate = () => { + const data: DataType = { + tableMaxHeight: ref(0), + headerTitle: ref({offsetHeight: 0, scrollHeight: 0}), + operate: ref({offsetHeight: 0, scrollHeight: 0}) + }; + + onMounted(() => { + const countHeight = data.headerTitle.value.offsetHeight + data.headerTitle.value.scrollHeight + data.operate.value.offsetHeight + data.operate.value.scrollHeight + 50; + new ScrollOperate(countHeight, data.tableMaxHeight); + }); + + onUnmounted(() => window.onresize = null); + + const getHeaderRef = (val: {value: HeightType3;}) => { + data.headerTitle.value = val.value; + }; + + const getOperateRef = (val: {value: HeightType3;})=> { + data.operate.value = val.value; + }; + + return { + ...data, + getHeaderRef, + getOperateRef + }; +}; + +export default tableScrollOperate; diff --git a/bmp-operation-web/src/views/idcManagement/list/verification/verification.vue b/bmp-operation-web/src/views/idcManagement/list/verification/verification.vue new file mode 100644 index 0000000..f609c93 --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/verification/verification.vue @@ -0,0 +1,21 @@ + + + diff --git a/bmp-operation-web/src/views/idcManagement/list/verification/verificationOperate.ts b/bmp-operation-web/src/views/idcManagement/list/verification/verificationOperate.ts new file mode 100644 index 0000000..8a9124a --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/list/verification/verificationOperate.ts @@ -0,0 +1,64 @@ +import {CurrencyType2, StatusParamsType, StatusType} from '@utils/publicType'; + +interface DataType { + reactiveArr: { + itemData: CurrencyType2; + }; + securityVerificationDiaLog: Ref; +}; + +interface EditIdcOperateType { + editingComputerRoomDiaLog: { + value: boolean; + }; +}; + +/** + * 安全验证操作 + * @param {Object} editIdcOperate 当前编辑的这一项 +*/ +const securityVerificationOperate = (editIdcOperate: EditIdcOperateType) => { + const data: DataType = { + reactiveArr: reactive<{ + itemData: CurrencyType2; + }>({ + itemData: {} + }), + securityVerificationDiaLog: ref(false) + }; + + /** + * 点击操作,控制安全验证弹窗显示隐藏 + * @return {boolean} securityVerificationDiaLog.value true-显示 false-隐藏 + */ + const operateClick = (item: string | number): boolean => { + data.reactiveArr.itemData.value = item; + return data.securityVerificationDiaLog.value = !data.securityVerificationDiaLog.value; + }; + + /** + * 安全验证弹窗取消事件,弹窗关闭 + * @param {Array} type 控制弹窗显示隐藏 true 显示 false 隐藏 + * @return {boolean} securityVerificationDiaLog.value true-显示 false-隐藏 + */ + const securityVerificationCancel: StatusParamsType <(type: boolean) => boolean> = (type: boolean): boolean => { + return data.securityVerificationDiaLog.value = type; + }; + + /** + * 安全验证弹窗成功的回调-显示隐藏 + * @return {boolean} editingComputerRoomDiaLog.value true-显示 false-隐藏 + */ + const securityVerificationSure: StatusType<() => boolean> = (): boolean => { + return editIdcOperate.editingComputerRoomDiaLog.value = !editIdcOperate.editingComputerRoomDiaLog.value; + }; + + return { + ...data, + operateClick, + securityVerificationSure, + securityVerificationCancel + } +}; + +export default securityVerificationOperate; diff --git a/bmp-operation-web/src/views/idcManagement/navRouter.ts b/bmp-operation-web/src/views/idcManagement/navRouter.ts new file mode 100644 index 0000000..89383fe --- /dev/null +++ b/bmp-operation-web/src/views/idcManagement/navRouter.ts @@ -0,0 +1,21 @@ +/** + * @file + * @author +*/ + +import {language} from "utils/publicClass.ts"; + +const idcNavData = (pathUrl: (arg0: string) => void, imgUrl: (arg0: string) => void) => { + return { + title: language.t('navigationBar.list.computerRoomManagement'), + defaultImg: imgUrl('idcManageDef'), + changeImg: imgUrl('idcManage'), + path: pathUrl('idcList'), + otherPath: [ + pathUrl('idcList'), + pathUrl('idcDetail') + ] + } +}; + +export default idcNavData; diff --git a/bmp-operation-web/src/views/imageManagement/detail/baseInfo/base.ts b/bmp-operation-web/src/views/imageManagement/detail/baseInfo/base.ts new file mode 100644 index 0000000..6907168 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/baseInfo/base.ts @@ -0,0 +1,148 @@ +/** + * @file + * @author +*/ + +import {imagesDetailAPI} from 'api/image/request.ts'; +import {CurrencyType} from '@utils/publicType'; +import store from 'store/index.ts'; +import {msgTip} from 'utils/index.ts'; +import {language, CurrentInstance} from 'utils/publicClass.ts'; +import router from 'router/index.ts'; +import AllStaticData from 'staticData/staticData.ts'; + +type BaseInfoData = { + label: string; + info: string; + class: string; + hasEdit: boolean; + formItemClass?: string[]; +} + +class BaseInfo { + infoLoading: Ref = ref(true); + deviceTypeNum: number = 0; + detail: any = {}; + systemPartitionInfo = store.sysPartitionInfo; + // 复杂数据类型 + reactiveArr: any = reactive({ + deviceTypeNum: 0, + detail: {}, + description: '' + }); + query: any; + instanceProxy = new CurrentInstance().proxy; + baseInfoData: BaseInfoData[] = [ + { + label: language.t('imageDetail.label.imageName'), + info: 'imageName', + class: 'set-wrap info-name', + hasEdit: false + }, + { + label: language.t('imageDetail.label.imageId'), + info: 'imageId', + class: 'set-wrap info-name', + hasEdit: false + }, + { + label: language.t('imageDetail.label.imageType'), + info: 'sourceName', + class: 'set-wrap info-name', + hasEdit: false + }, + { + label: language.t('imageDetail.label.architecture'), + info: 'architecture', + class: 'set-wrap info-name', + hasEdit: false + }, + { + label: language.t('imageDetail.label.operateSysPlatform'), + info: 'osType', + class: 'set-wrap info-name', + hasEdit: false + }, + { + label: language.t('imageDetail.label.operateSysVersion'), + info: 'osVersion', + class: 'set-wrap info-name', + hasEdit: false + }, + { + label: language.t('imageDetail.label.format'), + info: 'format', + class: 'set-wrap info-name', + hasEdit: false + }, + { + label: language.t('imageDetail.label.bootMode'), + info: 'bootMode', + class: 'set-wrap info-name', + hasEdit: false + }, + { + label: language.t('imageDetail.label.sysPartitionModule'), + info: 'newSystemPartition', + formItemClass: ['sys-partition-module', ''], + class: 'set-wrap info-name', + hasEdit: false + }, + { + label: language.t('imageDetail.label.numberOfAssociatedModels'), + info: 'deviceTypeNum', + class: 'set-wrap info-name', + hasEdit: false + }, + { + label: language.t('imageDetail.label.createTime'), + info: 'createdTime', + class: 'set-wrap info-name', + hasEdit: false + }, + { + label: language.t('imageDetail.label.imageDesc'), + info: 'description', + class: 'set-wrap info-name', + hasEdit: true + } + ] + + constructor (query: any) { + this.query = query; + }; + + getImageDetail = () => { + this.infoLoading.value = true; + imagesDetailAPI( + { + imageId: this.query?.imageId + } + ) + .then(({data} : {data: {result: CurrencyType}}) => { + if (data?.result && Object.keys(data.result).length) { + const newSystemPartition = this.systemPartitionInfo.systemPartitionData(data.result.systemPartition, false); + this.reactiveArr.detail = data.result; + this.reactiveArr.deviceTypeNum = data.result.deviceTypeNum; + this.reactiveArr.description = data.result.description; + this.reactiveArr.detail.newSystemPartition = newSystemPartition; + return; + } + return Promise.reject(''); + }) + .catch(({message} : {message: string}) => { + const path: string = this.instanceProxy.$defInfo.routerPath('imageList'); + this.reactiveArr.detail = {}; + if (AllStaticData.noFoundData.includes(message)) { + router.push(path); + return; + } + message && msgTip.error(message); + }) + .finally(() => { + this.infoLoading.value = false; + }); + }; +}; + +export default BaseInfo; diff --git a/bmp-operation-web/src/views/imageManagement/detail/baseInfo/baseInfo.vue b/bmp-operation-web/src/views/imageManagement/detail/baseInfo/baseInfo.vue new file mode 100644 index 0000000..9465f50 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/baseInfo/baseInfo.vue @@ -0,0 +1,73 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/detail/descEdit/desc.ts b/bmp-operation-web/src/views/imageManagement/detail/descEdit/desc.ts new file mode 100644 index 0000000..a70d299 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/descEdit/desc.ts @@ -0,0 +1,29 @@ +interface BaseInfoType { + getImageDetail(): void; +}; + +const descEdit = (baseInfo: BaseInfoType) => { + const editDescDiaLog: Ref = ref(false); + + const editDescClick = () => { + editDescDiaLog.value = !editDescDiaLog.value; + }; + + + const editDescCacnel = (type: boolean): boolean => { + return editDescDiaLog.value = type; + }; + + const editDescSure = () => { + baseInfo.getImageDetail(); + }; + + return { + editDescDiaLog, + editDescClick, + editDescCacnel, + editDescSure + }; +}; + +export default descEdit; diff --git a/bmp-operation-web/src/views/imageManagement/detail/descEdit/desc.vue b/bmp-operation-web/src/views/imageManagement/detail/descEdit/desc.vue new file mode 100644 index 0000000..960cccd --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/descEdit/desc.vue @@ -0,0 +1,27 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/detail/drop/dropDown.vue b/bmp-operation-web/src/views/imageManagement/detail/drop/dropDown.vue new file mode 100644 index 0000000..3f102e8 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/drop/dropDown.vue @@ -0,0 +1,45 @@ + + + diff --git a/bmp-operation-web/src/views/imageManagement/detail/drop/imageDelete/delete.ts b/bmp-operation-web/src/views/imageManagement/detail/drop/imageDelete/delete.ts new file mode 100644 index 0000000..27a29e1 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/drop/imageDelete/delete.ts @@ -0,0 +1,33 @@ +import {CurrentInstance} from 'utils/publicClass.ts'; + +const imageDelete = (router: any, baseInfo: any) => { + const deleteImageDiaLog: Ref = ref(false); + const instanceProxy = new CurrentInstance().proxy; + + const deleteImageClick = () => { + deleteImageDiaLog.value = !deleteImageDiaLog.value; + }; + + const deleteImageCancel = (type: boolean) => { + return deleteImageDiaLog.value = type; + }; + + const deleteImageSure = () => { + const path: string = instanceProxy.$defInfo.routerPath('imageList'); + router.push(path); + }; + + const imageDeleteError = () => { + baseInfo.getImageDetail(); + }; + + return { + deleteImageDiaLog, + deleteImageClick, + deleteImageCancel, + deleteImageSure, + imageDeleteError + }; +}; + +export default imageDelete; diff --git a/bmp-operation-web/src/views/imageManagement/detail/drop/imageDelete/imageDelete.vue b/bmp-operation-web/src/views/imageManagement/detail/drop/imageDelete/imageDelete.vue new file mode 100644 index 0000000..99b3ce9 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/drop/imageDelete/imageDelete.vue @@ -0,0 +1,26 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/detail/imageDetail.scss b/bmp-operation-web/src/views/imageManagement/detail/imageDetail.scss new file mode 100644 index 0000000..58e2350 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/imageDetail.scss @@ -0,0 +1,43 @@ +.image-detail { + + .operate-management-detail-info { + margin-top: 0; + } + + .image-delete { + &:hover, + &:active { + border-radius: 3px; + } + } + + .sys-partition-module { + @include display-align(flex-start); + } + + .edit-opt-wrap { + display: flex; + align-items: center; + } + + .en-model-info { + .el-tabs__nav { + margin-left: -5px; + } + } + + .zh-model-info { + .el-tabs__nav { + margin-left: 6px; + } + } + + .btn-bottom { + margin-bottom: 18px !important; + } + + .image-add-model { + border-radius: 15px; + @include size-weight-color($fontSize, $fontLargeWeight, $color3); + } +} diff --git a/bmp-operation-web/src/views/imageManagement/detail/imageDetail.vue b/bmp-operation-web/src/views/imageManagement/detail/imageDetail.vue new file mode 100644 index 0000000..d90bc76 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/imageDetail.vue @@ -0,0 +1,85 @@ + + + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/detail/methods.ts b/bmp-operation-web/src/views/imageManagement/detail/methods.ts new file mode 100644 index 0000000..df6d25d --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/methods.ts @@ -0,0 +1,15 @@ +/** + * @file + * @author +*/ + +const requireAll = (requireContext: T) => { + // keys 返回字典的所有的key + return requireContext.keys().map(requireContext); +} + +const methods = [ + ...requireAll(require.context('./', true, /^((?!methods|module|page|setEmpty).)*\.ts$/),) +].map(item => item.default); + +export default methods; diff --git a/bmp-operation-web/src/views/imageManagement/detail/modelAdd/add.ts b/bmp-operation-web/src/views/imageManagement/detail/modelAdd/add.ts new file mode 100644 index 0000000..dff5e1b --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/modelAdd/add.ts @@ -0,0 +1,29 @@ +interface AssociatedModelType { + getTable(): Function; +}; + +const modelAdd = (associatedModel: AssociatedModelType) => { + const addModelDiaLog: Ref = ref(false); + + + const addModelClick = () => { + return addModelDiaLog.value = !addModelDiaLog.value; + }; + + const addModelCancel = (type: boolean): boolean => { + return addModelDiaLog.value = type; + }; + + const addModelSure = () => { + associatedModel.getTable(); + }; + + return { + addModelDiaLog, + addModelClick, + addModelCancel, + addModelSure + }; +}; + +export default modelAdd; diff --git a/bmp-operation-web/src/views/imageManagement/detail/modelAdd/modelAdd.vue b/bmp-operation-web/src/views/imageManagement/detail/modelAdd/modelAdd.vue new file mode 100644 index 0000000..89326c5 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/modelAdd/modelAdd.vue @@ -0,0 +1,25 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/detail/module.ts b/bmp-operation-web/src/views/imageManagement/detail/module.ts new file mode 100644 index 0000000..f797da0 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/module.ts @@ -0,0 +1,39 @@ +// import TabsData from './tabs/tabs.vue'; +// import DescEdit from './descEdit/desc.vue'; +// import TableData from './table/tableData.vue'; +// import BaseInfo from './baseInfo/baseInfo.vue'; +// import ModelAdd from './modelAdd/modelAdd.vue'; +// import ModelRemove from './remove/remove.vue'; +// import DropDownOperate from './drop/dropDown.vue'; +// import Pagination from './pagination/pagination.vue'; +// import ImageDelete from './drop/imageDelete/imageDelete.vue'; + +// const pluginComp = { +// TabsData, +// DescEdit, +// TableData, +// BaseInfo, +// ModelAdd, +// ModelRemove, +// DropDownOperate, +// Pagination, +// ImageDelete +// }; + +// export default pluginComp; + +/** + * @file + * @author +*/ + +const requireAll = (requireContext: T) => { + // keys 返回字典的所有的key + return requireContext.keys().map(requireContext); +} + +const pluginComp = [ + ...requireAll(require.context('./', true, /^((?!imageDetail).)*\.vue$/)) +].map(item => item.default); + +export default pluginComp; diff --git a/bmp-operation-web/src/views/imageManagement/detail/page.ts b/bmp-operation-web/src/views/imageManagement/detail/page.ts new file mode 100644 index 0000000..12480c8 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/page.ts @@ -0,0 +1,10 @@ +const ImageDetail = () => import(/* webpackChunkName: "ImageDetail" */ './imageDetail.vue'); + +export default { + path: '/ImageManagement/imageDetail', + name: 'ImageDetail', + component: ImageDetail, + meta: { + type: 'imageDetail' + } +}; diff --git a/bmp-operation-web/src/views/imageManagement/detail/pagination/pagination.ts b/bmp-operation-web/src/views/imageManagement/detail/pagination/pagination.ts new file mode 100644 index 0000000..fce3072 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/pagination/pagination.ts @@ -0,0 +1,27 @@ +import {paginationOperate} from 'utils/publicClass.ts'; +/** + * 分页监听 +*/ +class PaginationOperate { + + // 构造器 + constructor (list: any) { + this.watchSizeNumber(list); + }; + + /** + * 监听分页页数、条数变化 + */ + watchSizeNumber = (list: any) => { + + watch(() => [ + paginationOperate.pageSize.value, + paginationOperate.pageNumber.value + ], (_: boolean[]): void => { + if (paginationOperate.routerChange.value) return; + list.getTable(); + }); + }; +}; + +export default PaginationOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/detail/pagination/pagination.vue b/bmp-operation-web/src/views/imageManagement/detail/pagination/pagination.vue new file mode 100644 index 0000000..404a495 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/pagination/pagination.vue @@ -0,0 +1,27 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/detail/remove/remove.ts b/bmp-operation-web/src/views/imageManagement/detail/remove/remove.ts new file mode 100644 index 0000000..ec87bb5 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/remove/remove.ts @@ -0,0 +1,50 @@ +import {CurrencyType} from '@utils/publicType'; +import {paginationOperate} from 'utils/publicClass.ts'; +interface DataType { + removeOperateDiaLog: Ref; + name: Ref; + deviceType: Ref; + deviceTypeId: Ref; +}; + +interface AssociatedModelType { + reactiveArr: any; + getTable(): Function; +}; + +const remove = (associatedModel: AssociatedModelType) => { + const data: DataType = { + removeOperateDiaLog: ref(false), + name: ref(''), + deviceType: ref(''), + deviceTypeId: ref('') + }; + + const removeClick = (item: CurrencyType) => { + data.removeOperateDiaLog.value = !data.removeOperateDiaLog.value; + data.name.value = item.name; + data.deviceType.value = item.deviceType; + data.deviceTypeId.value = item.deviceTypeId; + + }; + const removeOperateCancel = (type: boolean): boolean => { + return data.removeOperateDiaLog.value = type; + }; + + const removeOperateSure = () => { + if (paginationOperate.pageNumber.value > 1 && associatedModel.reactiveArr.tableData.length === 1) { + paginationOperate.pageNumber.value = paginationOperate.pageNumber.value - 1; + return; + } + associatedModel.getTable(); + }; + + return { + ...data, + removeClick, + removeOperateCancel, + removeOperateSure + } +}; + +export default remove; diff --git a/bmp-operation-web/src/views/imageManagement/detail/remove/remove.vue b/bmp-operation-web/src/views/imageManagement/detail/remove/remove.vue new file mode 100644 index 0000000..e0d71ac --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/remove/remove.vue @@ -0,0 +1,27 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/detail/table/setEmpty.ts b/bmp-operation-web/src/views/imageManagement/detail/table/setEmpty.ts new file mode 100644 index 0000000..5b36572 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/table/setEmpty.ts @@ -0,0 +1,60 @@ +/** + * @file + * @author +*/ + +import {language} from 'utils/publicClass.ts'; + +const p = document.createElement('p'); + +interface PropsType { + tableData: [] +} + +class SetEmpty { + emitValue: Function; + + constructor(props: PropsType, emitValue: Function) { + this.emitValue = emitValue; + this.watchTableData(props); + onUnmounted(() => p.innerHTML = ''); + }; + + watchTableData = (props: PropsType) => { + watch(() => props?.tableData, (newValue) => { + if (!newValue?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.innerHTML= ''; + }) + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + ai!.innerHTML = ''; + const customText = document.querySelector('.image-detail .el-scrollbar__view'); + if (!customText) return; + const str = ` + + ${language.t('table.empty')},${language.t('table.tip')} + + + ${language.t('imageDetail.empty.title')} + + ` + const parser = new DOMParser(); + const doc = parser.parseFromString(str, 'text/html'); + p.className = 'custom-tip-count'; + p.innerHTML = doc.body.innerHTML; + customText.appendChild(p) + const clickOpt = document.querySelector('.image-detail-model .custom-tip-count .empty-text'); + clickOpt!.addEventListener('click', () => { + this.emitValue('empty-click') + }); + }; +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/imageManagement/detail/table/tableData.vue b/bmp-operation-web/src/views/imageManagement/detail/table/tableData.vue new file mode 100644 index 0000000..3d42d8c --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/table/tableData.vue @@ -0,0 +1,296 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/detail/table/tableDetail.ts b/bmp-operation-web/src/views/imageManagement/detail/table/tableDetail.ts new file mode 100644 index 0000000..1028ed5 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/table/tableDetail.ts @@ -0,0 +1,70 @@ +/** + * @file + * @author +*/ + +import {imageDeviceTypesAPI} from 'api/image/request.ts'; +import {paginationOperate, CurrentInstance} from 'utils/publicClass.ts'; +import {msgTip} from 'utils/index.ts'; +import {CurrencyType} from '@utils/publicType'; +import router from 'router/index.ts'; +import ImageStaticData from 'staticData/image/index.ts'; +import AllStaticData from 'staticData/staticData.ts'; + +class AssociatedModel { + isLoading: Ref = ref(true); + // 复杂数据类型 + reactiveArr: any = reactive({ + tableData: [] // 表格关联机型数据 + }); + query: any; + baseInfo: any; + instanceProxy = new CurrentInstance().proxy; + + constructor (query: any, baseInfo: any) { + this.query = query; + this.baseInfo = baseInfo; + }; + + getTable = () => { + this.isLoading.value = true; + imageDeviceTypesAPI( + { + imageId: this.query?.imageId, + architecture: this.query?.architecture, + isBind: '1', + pageNumber: paginationOperate.pageNumber.value, + pageSize: paginationOperate.pageSize.value + } + ) + .then(({data}: {data: {result: {totalCount: number; deviceTypes: CurrencyType[]}}}) => { + if (data?.result?.deviceTypes?.length) { + data.result.deviceTypes.forEach((item: CurrencyType, index: number) => { + ImageStaticData.imageDetailTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }); + }) + this.reactiveArr.tableData = data.result.deviceTypes; + paginationOperate.total.value = data.result.totalCount; + return; + } + + return Promise.reject('') + }) + .catch(({message} : {message: string}) => { + paginationOperate.total.value = 0; + this.reactiveArr.tableData = []; + message && msgTip.error(message); + const path: string = this.instanceProxy.$defInfo.routerPath('imageList'); + if (AllStaticData.noFoundData.includes(message)) { + router.push(path); + } + }) + .finally(() => { + this.isLoading.value = false; + this.baseInfo.getImageDetail(); + }); + }; +}; + +export default AssociatedModel; diff --git a/bmp-operation-web/src/views/imageManagement/detail/table/tableScroll.ts b/bmp-operation-web/src/views/imageManagement/detail/table/tableScroll.ts new file mode 100644 index 0000000..15dc702 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/table/tableScroll.ts @@ -0,0 +1,78 @@ +import {HeightType3} from '@utils/publicType'; +import {tableScroll} from 'utils/index.ts'; + +interface DataType { + activeName: Ref; + headerTitle: Ref; + hasRemove: boolean; + tableMaxHeight: Ref; + title2: Ref; +}; + +interface ParamsType { + active: { + value: string; + }; +} + +const tableScrollOperate = (active: ParamsType['active']) => { + const data: DataType = { + activeName: ref(''), + hasRemove: Boolean(false), + headerTitle: ref({offsetHeight: 0, scrollHeight: 0}), + tableMaxHeight: ref(0), + title2: ref({ + offsetHeight: 0, + scrollHeight: 0 + }) + }; + + data.activeName.value = active.value; + + onMounted(() => { + if (data.activeName.value === 'basicInfo') return; + getHeightTop(); + }); + + onUnmounted(() => data.activeName.value = ''); + + window.onresize = () => { + if (data.activeName.value === 'basicInfo') return; + getHeightTop(); + }; + + watch(() => active, (newValue: {value: string}) => { + data.activeName.value = newValue.value; + getHeightTop(); + }, {deep: true}) + + const getRef = (val: DataType['title2']) => { + data.title2 = val; + getHeightTop(); + }; + + + const getRefHeader = (val: { value: HeightType3 }) => { + data.headerTitle.value = val.value; + }; + + + const getHeightTop = () => { + if (data.activeName.value === 'basicInfo') return; + nextTick(() => { + const addImageButton: any = document.querySelector('.image-add-model'); + const value1 = data.headerTitle.value; + const value2 = data.title2.value; + const countHeight = addImageButton?.offsetHeight + addImageButton?.scrollHeight + value1.scrollHeight + value2.offsetHeight + value2.scrollHeight + value1.offsetHeight + 23; + tableScroll(countHeight, data.tableMaxHeight); + }) + }; + return { + ...data, + getHeightTop, + getRefHeader, + getRef + } +}; + +export default tableScrollOperate; diff --git a/bmp-operation-web/src/views/imageManagement/detail/tabs/active.ts b/bmp-operation-web/src/views/imageManagement/detail/tabs/active.ts new file mode 100644 index 0000000..747bdb8 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/tabs/active.ts @@ -0,0 +1,88 @@ +import {language} from 'utils/publicClass.ts'; +import {CurrencyType6, CurrencyType} from '@utils/publicType'; +import router from 'router/index.ts'; +import store from 'store/index.ts'; + +interface DataType { + activeName: Ref; + tabsPangeData: CurrencyType6[]; +} + +const tabsOperate = (associatedModel: any, query: any, baseInfo: any) => { + const data: DataType = { + // 标签页切换的model + activeName: ref(''), + tabsPangeData: [ // 标签页切换信息 + { + label: language.t('imageDetail.tabs.basicInfo'), + name: 'basicInfo' + }, + { + label: language.t('imageDetail.tabs.model'), + name: 'model' + } + ] + }; + + onMounted(() => { + if (query?.deviceTypeNum?.length) { + data.activeName.value = 'model'; + return; + } + data.activeName.value = 'basicInfo'; + }) + + watch(() => data.activeName.value, (newValue: string) => { + const requestData = [ + [ + (newValue: string) => Object.is(newValue, 'basicInfo'), + () => baseInfo.getImageDetail() + ], + [ + (newValue: string) => Object.is(newValue, 'model'), + () => associatedModel.getTable() + ] + ]; + for(const key of requestData) { + if (key[0](newValue)) { + key[1](newValue); + break; + } + } + }); + + /** + * 标签页切换 + * @param {string} value 当前标签页点击切换的名称 + * @return {string} activeName.value 当前标签页切换的数据 + */ + const tabsChange = (value: string): void => { + data.activeName.value = value; + const path: string = router.currentRoute.value.path; + const query: CurrencyType = router.currentRoute.value.query; + let obj: CurrencyType = {}; + let activeQuery: string = ''; + for (let index in query) { + obj = {...obj, [index]: query[index], deviceTypeNum: query?.deviceTypeNum || '0'} + if (value === 'basicInfo') { + obj.deviceTypeNum = ''; + store.filterEmpty.deleteEmtpyData(obj); + } + else { + obj.deviceTypeNum = query?.deviceTypeNum || '0'; + } + } + for (let key in obj) { + activeQuery += `${[key]}=${obj[key]}&` + } + activeQuery = activeQuery.slice(0, -1); + router.push(`${path}?${activeQuery}`); + }; + + return { + ...data, + tabsChange + } +}; + +export default tabsOperate; diff --git a/bmp-operation-web/src/views/imageManagement/detail/tabs/tabs.vue b/bmp-operation-web/src/views/imageManagement/detail/tabs/tabs.vue new file mode 100644 index 0000000..9fb652f --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/detail/tabs/tabs.vue @@ -0,0 +1,42 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/list/custom/custom.ts b/bmp-operation-web/src/views/imageManagement/list/custom/custom.ts new file mode 100644 index 0000000..4dc0bca --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/custom/custom.ts @@ -0,0 +1,10 @@ +/** + * @file + * @author +*/ + +import useCustom from 'hooks/custom/useCustom.ts'; + +const customOperate = useCustom('imageList').info; + +export default customOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/list/custom/customList.vue b/bmp-operation-web/src/views/imageManagement/list/custom/customList.vue new file mode 100644 index 0000000..0615f6e --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/custom/customList.vue @@ -0,0 +1,9 @@ + + diff --git a/bmp-operation-web/src/views/imageManagement/list/deleteImage/delete.ts b/bmp-operation-web/src/views/imageManagement/list/deleteImage/delete.ts new file mode 100644 index 0000000..542d0a5 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/deleteImage/delete.ts @@ -0,0 +1,137 @@ +import {paginationOperate} from 'utils/publicClass.ts'; + +interface DataType { + imageId: Ref; + imageInfo: Ref; + deleteImageDiaLog: Ref; +}; + +interface ParamsType { + imageList: { + reactiveArr: { + tableData: { + length: number; + } + }; + getImageList(): Function; + }; + filter: { + tableRef: { + value: { + clearFilter(): Function; + } + }; + reactiveArr: { + filterParams: { + architecture: string; + osType: string; + source: string; + } + } + } +} + +const deleteImageOperate = (imageList: ParamsType['imageList'], filter: ParamsType['filter']) => { + const data: DataType = { + // 镜像id + imageId: ref(''), + // 镜像信息 + imageInfo: ref(''), + // 删除镜像弹窗组件 + deleteImageDiaLog: ref(false) + }; + + /** + * 点击删除镜像 + * @param {string} item 当前点击的镜像信息 + * @return {boolean} deleteImageDiaLog.value 删除镜像弹窗 + */ + const deleteImageClick = (item: {imageName: string; imageId: string;}): boolean => { + data.imageInfo.value = item.imageName; + data.imageId.value = item.imageId; + return data.deleteImageDiaLog.value = !data.deleteImageDiaLog.value; + }; + + /** + * 删除镜像取消操作 + * @param {boolean} type 删除镜像组件状态 + */ + const deleteImageCancel = (type: boolean): boolean => { + return data.deleteImageDiaLog.value = type; + }; + + /** + * 删除镜像操作成功后的处理 + */ + const deleteImageSure = () => { + if (paginationOperate.pageNumber.value > 1 && !imageList.reactiveArr.tableData.length) { + paginationOperate.pageNumber.value = paginationOperate.pageNumber.value - 1; + return; + } + if (imageList.reactiveArr.tableData.length === 1) { + filter?.tableRef?.value?.clearFilter(); + filter.reactiveArr.filterParams = {architecture: '', osType: '', source: ''}; + } + imageList.getImageList(); + }; + + const imageDeleteError = () => { + imageList.getImageList(); + }; + + return { + ...data, + deleteImageClick, + deleteImageCancel, + deleteImageSure, + imageDeleteError + } +}; + +export default deleteImageOperate; + +// /** +// * 删除镜像操作 +// */ +// class DeleteImageOperate { +// // 镜像id +// imageId: Ref = ref(''); +// // 镜像信息 +// imageInfo: Ref = ref(''); +// // 删除镜像弹窗组件 +// deleteImageDiaLog: Ref = ref(false); + +// /** +// * 点击删除镜像 +// * @param {string} item 当前点击的镜像信息 +// * @return {boolean} deleteImageDiaLog.value 删除镜像弹窗 +// */ +// deleteImageClick = (item: {imageName: string; imageId: string;}): boolean => { +// this.imageInfo.value = item.imageName; +// this.imageId.value = item.imageId; +// return this.deleteImageDiaLog.value = !this.deleteImageDiaLog.value; +// }; + +// /** +// * 删除镜像取消操作 +// * @param {boolean} type 删除镜像组件状态 +// */ +// deleteImageCancel = (type: boolean): boolean => { +// return this.deleteImageDiaLog.value = type; +// }; + +// /** +// * 删除镜像操作成功后的处理 +// */ +// deleteImageSure = () => { +// if (paginationOperate.pageNumber.value > 1 && !imageList.reactiveArr.tableData.length) { +// paginationOperate.pageNumber.value = paginationOperate.pageNumber.value - 1; +// return; +// } +// if (imageList.reactiveArr.tableData.length === 1) { +// filter?.tableRef?.value?.clearFilter(); +// filter.reactiveArr.filterParams = {architecture: '', osType: '', source: ''}; +// } +// imageList.getImageList(); +// }; +// }; \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/list/deleteImage/imageDelete.vue b/bmp-operation-web/src/views/imageManagement/list/deleteImage/imageDelete.vue new file mode 100644 index 0000000..5d0d0f1 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/deleteImage/imageDelete.vue @@ -0,0 +1,21 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/list/export/export.ts b/bmp-operation-web/src/views/imageManagement/list/export/export.ts new file mode 100644 index 0000000..9b3d1be --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/export/export.ts @@ -0,0 +1,49 @@ +import {imagesExportAPI} from 'api/image/request.ts'; +import {ExportDataOperate} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; + +class ExportFilterData { + // 是否导出数据 + hasExportData: Ref = ref(true); + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + // list: any; + search: { + searchParams: {} + }; + filter: { + filterParams: {} + }; + + constructor(search: { + searchParams: {} + }, filter: { + filterParams: {} + }) { + // this.list = list; + this.search = search; + this.filter = filter; + }; + + exportData = (that: never) => { + new ExportDataOperate(imagesExportAPI, {}, 'images_list').exportData(that); + }; + + /** + * 参数处理 + */ + paramsProcessing = (that: never) => { + this.filterEmptyInfo.deleteEmtpyData({...this.filter.filterParams, ...this.search.searchParams}); + new ExportDataOperate(imagesExportAPI, { + ...this.search.searchParams, + ...this.filter.filterParams + }, 'images_list').exportData(that); + } +}; + +export { + ExportFilterData, + ExportDataOperate, + imagesExportAPI +}; diff --git a/bmp-operation-web/src/views/imageManagement/list/export/exportData.vue b/bmp-operation-web/src/views/imageManagement/list/export/exportData.vue new file mode 100644 index 0000000..2b9f088 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/export/exportData.vue @@ -0,0 +1,23 @@ + + + diff --git a/bmp-operation-web/src/views/imageManagement/list/imageImport/imageImport.vue b/bmp-operation-web/src/views/imageManagement/list/imageImport/imageImport.vue new file mode 100644 index 0000000..2dce49c --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/imageImport/imageImport.vue @@ -0,0 +1,17 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/list/imageImport/importImage.ts b/bmp-operation-web/src/views/imageManagement/list/imageImport/importImage.ts new file mode 100644 index 0000000..425b7ba --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/imageImport/importImage.ts @@ -0,0 +1,82 @@ +interface ParamsType { + filter: { + ossStore: { + getOssData(): Function; + }; + }; + resetOperate: { + reset(): void; + } +} + +const importImageOperate = (filter: ParamsType['filter'], resetOperate: ParamsType['resetOperate']) => { + const importImageDiaLog: Ref = ref(false); + + /** + * 导入镜像点击事件 + * @return {boolean} importImageDiaLog.value 导入镜像弹窗状态 + */ + const importImageClick = (): boolean => { + return importImageDiaLog.value = true; + }; + /** + * 导入镜像组件取消事件 + * @param {boolean} type 弹窗状态 + * @return {boolean} importImageDiaLog.value 导入镜像弹窗 + */ + const importImageCancel = (type: boolean): boolean => { + return importImageDiaLog.value = type; + }; + + /** + * 导入镜像成功的回调操作 + */ + const importImageSure = () => { + resetOperate.reset(); + // filter?.tableRef?.value?.clearFilter(); + // filter.reactiveArr.filterParams = {architecture: '', osType: '', source: ''}; + // imageList.getImageList(); + filter.ossStore?.getOssData(); + }; + + return { + importImageDiaLog, + importImageClick, + importImageCancel, + importImageSure + } +}; + +export default importImageOperate; + +// class ImportImageOperate { +// // 导入镜像弹窗组件 +// importImageDiaLog: Ref = ref(false); +// // repeatData: string[] = ['']; + +// /** +// * 导入镜像点击事件 +// * @return {boolean} importImageDiaLog.value 导入镜像弹窗状态 +// */ +// importImageClick = (): boolean => { +// return this.importImageDiaLog.value = true; +// }; +// /** +// * 导入镜像组件取消事件 +// * @param {boolean} type 弹窗状态 +// * @return {boolean} importImageDiaLog.value 导入镜像弹窗 +// */ +// importImageCancel = (type: boolean): boolean => { +// return this.importImageDiaLog.value = type; +// }; + +// /** +// * 导入镜像成功的回调操作 +// */ +// importImageSure = () => { +// filter?.tableRef?.value?.clearFilter(); +// filter.reactiveArr.filterParams = {architecture: '', osType: '', source: ''}; +// imageList.getImageList(); +// filter.ossStore?.getOssData(); +// }; +// }; \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/list/imageList.vue b/bmp-operation-web/src/views/imageManagement/list/imageList.vue new file mode 100644 index 0000000..c3cf9df --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/imageList.vue @@ -0,0 +1,100 @@ + + + + diff --git a/bmp-operation-web/src/views/imageManagement/list/methods.ts b/bmp-operation-web/src/views/imageManagement/list/methods.ts new file mode 100644 index 0000000..42d83f0 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/methods.ts @@ -0,0 +1,15 @@ +/** + * @file + * @author +*/ + +const requireAll = (requireContext: T) => { + // keys 返回字典的所有的key + return requireContext.keys().map(requireContext); +} + +const methods = [ + ...requireAll(require.context('./', true, /^((?!methods|module|page|setEmpty|typeManagement|filterStyle).)*\.ts$/),) +]; + +export default methods; diff --git a/bmp-operation-web/src/views/imageManagement/list/module.ts b/bmp-operation-web/src/views/imageManagement/list/module.ts new file mode 100644 index 0000000..c54ccb3 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/module.ts @@ -0,0 +1,15 @@ +/** + * @file + * @author +*/ + +const requireAll = (requireContext: T) => { + // keys 返回字典的所有的key + return requireContext.keys().map(requireContext); +} + +const pluginComp = [ + ...requireAll(require.context('./', true, /^((?!imageList).)*\.vue$/)) +].map(item => item.default); + +export default pluginComp; \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/list/page.ts b/bmp-operation-web/src/views/imageManagement/list/page.ts new file mode 100644 index 0000000..df83016 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/page.ts @@ -0,0 +1,10 @@ +const ImageList = () => import(/* webpackChunkName: "ImageList" */ './imageList.vue'); + +export default { + path: '/ImageManagement/imageList', + name: 'ImageList', + component: ImageList, + meta: { + type: 'imageList' + } +}; diff --git a/bmp-operation-web/src/views/imageManagement/list/search/search.ts b/bmp-operation-web/src/views/imageManagement/list/search/search.ts new file mode 100644 index 0000000..1e55b4a --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/search/search.ts @@ -0,0 +1,78 @@ +/** + * @file + * @author +*/ + +import {language, paginationOperate} from 'utils/publicClass.ts'; + +class SearchOperate { + hasClear: Ref = ref(false); + // 搜索框值 + selectVal: Ref = ref(0); + reactiveArr: any = reactive({ + searchParams: {}, + selectOption: [ + { + value: 0, + label: language.t('imageList.search.condition.imageName') + }, + { + value: 1, + label: language.t('imageList.search.condition.imageId') + } + ] + }); + fn: any; + + constructor (fn: any) { + this.fn = fn; + }; + + iptValue = (enterValue: string, selectValue: number) => { + selectValue ? this.reactiveArr.searchParams = {imageId: enterValue} : this.reactiveArr.searchParams = {imageName: enterValue}; + }; + + /** + * input 输入框 点击搜索按钮或者回车触发 + * @param {string} enterValue 输入框输入的值 + * @param {number} selectValue 筛选框筛选的值 + */ + enterValueIpt = (enterValue: string, selectValue: number): void => { + selectValue ? this.reactiveArr.searchParams = {imageId: enterValue} : this.reactiveArr.searchParams = {imageName: enterValue}; + this.request(); + }; + + /** + * 搜索框筛选 + * @param {number} val 搜索框切换的搜索key + * @return {number} selectVal 对应的key + */ + changeSelect = (val: number): number => { + return this.selectVal.value = val; + }; + + clearClick = (val: string) => { + if (!val) { + this.selectChange(); + } + }; + + selectChange = () => { + const {imageId, imageName} :{imageId?: string; imageName?: string;} = this.reactiveArr.searchParams; + if (imageId || imageName) { + this.reactiveArr.searchParams = {}; + this.request(); + } + }; + + request = () => { + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn(); + }; + +}; + +export default SearchOperate; diff --git a/bmp-operation-web/src/views/imageManagement/list/table/filterStyle.ts b/bmp-operation-web/src/views/imageManagement/list/table/filterStyle.ts new file mode 100644 index 0000000..df20698 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/table/filterStyle.ts @@ -0,0 +1,165 @@ +/** + * @file + * @author +*/ + +interface FilterStatus { + source: boolean; + architecture: boolean; + osType: boolean; +}; + +class FilterStyleOperate { + classNameData = [ + { + name: 'def-type-status5', + type: 'source' + }, + { + name: 'def-type-status6', + type: 'architecture' + }, + { + name: 'def-type-status7', + type: 'osType' + } + ]; + filterStatus: FilterStatus = reactive({ + source: false, + architecture: false, + osType: false + }) + + constructor (props: any) { + onMounted(() => { + nextTick(() => { + this.customFilter(props); + }) + this.watchSearchTip(props); + this.watchFilter(props); + }) + }; + + watchSearchTip = (props: any) => { + watch(() => props.imageList.searchTip, (newValue) => { + const that = this; + if (!newValue.value) { + for (let index in this.filterStatus) { + (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = false; + } + } + else { + this.setFilterStatus(props.filter.reactiveArr.filterParams); + } + }, { + deep: true + }); + }; + + watchFilter = (props: any) => { + watch(() => props.filter.reactiveArr.filterParams, (newValue) => { + this.setFilterStatus(newValue); + }, {deep: true}) + }; + + setFilterStatus = (params: any) => { + const that = this; + this.classNameData.forEach((item) => { + if (['', void 0].includes(params[item.type])) { + (this.filterStatus[`${item.type}` as keyof typeof that.filterStatus] as boolean) = false; + return; + } + (this.filterStatus[`${item.type}` as keyof typeof that.filterStatus] as boolean) = true; + }) + }; + + customFilter = (props: any) => { + let filterName: HTMLElement | null; + let filterOpt: HTMLElement | null; + const that = this; + this.classNameData.forEach((item) => { + filterName = document.querySelector(`.${item.name} > .cell`); + filterOpt = document.querySelector(`.${item.name} > .cell > .el-table__column-filter-trigger`) + filterName?.addEventListener('click', (event) => { + event.stopPropagation(); + for (let index in this.filterStatus) { + (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = false; + } + }) + filterOpt?.addEventListener('click', (event) => { + event.stopPropagation(); + if (!props.imageList.searchTip.value) { + const clickStatus: any = { + 'source': () => { + this.filterStatus['architecture'] = false; + this.filterStatus['osType'] = false; + }, + 'architecture': () => { + this.filterStatus['source'] = false; + this.filterStatus['osType'] = false; + }, + 'osType': () => { + this.filterStatus['architecture'] = false; + this.filterStatus['source'] = false; + } + }; + clickStatus[item.type](); + } + this.filterStatus[`${item.type}` as keyof typeof that.filterStatus] = !this.filterStatus[`${item.type}` as keyof typeof that.filterStatus]; + }); + + const filterOtherRegion = document.querySelectorAll('.el-table-filter'); + filterOtherRegion.forEach((_, index) => { + filterOtherRegion[index]?.addEventListener('click', (event) => { + event.stopPropagation(); + for (let index in this.filterStatus) { + for (const key of this.classNameData) { + if (key.type === index && props.imageList.filter?.reactiveArr?.filterParams[key.type]?.length) { + (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = true; + } + } + } + }) + }) + let newType = []; + document.addEventListener('click', (event) => { + event.stopPropagation(); + newType = []; + newType.push(item.type); + newType.forEach((ite) => { + this.filterDispose(ite, props); + }) + }) + }) + }; + + filterDispose = (type: string, props: any) => { + const that = this; + const filterVal = props.filter.reactiveArr.filterParams; + const status = Object.values(filterVal).some((item) => item !== ''); + if (!status) { + this.filterStatus[`${type}` as keyof typeof that.filterStatus] = false; + return; + }; + if (props.imageList.searchTip.value) { + for (let key in filterVal) { + if (Object.is(key, type)) { + this.filterStatus[`${key}` as keyof typeof that.filterStatus] = true; + } + else { + if (this.filterStatus[`${type}` as keyof typeof that.filterStatus] && Object.keys(filterVal).length > 1) { + this.filterStatus[`${type}` as keyof typeof that.filterStatus] = !this.filterStatus[`${type}` as keyof typeof that.filterStatus]; + } + else { + this.filterStatus[`${type}` as keyof typeof that.filterStatus] = false; + } + } + } + } + else { + (this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean) = false; + } + } +}; + +export default FilterStyleOperate; diff --git a/bmp-operation-web/src/views/imageManagement/list/table/imageList.ts b/bmp-operation-web/src/views/imageManagement/list/table/imageList.ts new file mode 100644 index 0000000..ba84d33 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/table/imageList.ts @@ -0,0 +1,99 @@ +/** + * @file + * @author +*/ + +import store from 'store/index.ts'; +import {ParamsType} from '../typeManagement'; +import {CurrencyType} from '@utils/publicType'; +import {msgTip, methodsTotal} from 'utils/index.ts'; +import {paginationOperate} from 'utils/publicClass.ts'; +import ImageStaticData from 'staticData/image/index.ts'; + +// 镜像类型 +type ImagesType = {[x: string]: string | boolean;}; + +// 镜像返回类型 +type ImageResponseType = {images: {[x: string]: string}[], totalCount: number;}; + +class ImageList { + systemPartitionInfo: any = store.sysPartitionInfo; + searchTip: Ref = ref(false); + // loading态 + isLoading: Ref = ref(true); + type: string = ''; + search: any = {}; + filter: any = {}; + imagesInfo: { + getImage( + arg0: ParamsType | {isAll: string}, + arg1: {tableData: {[x: string]: string | boolean;}[]} + ): Promise; + // systemPartitionData(arg0: string, arg1: boolean): never; + } = store.imagesInfo; + // status: any = { + // value: false + // }; + + // 复杂响应式数据集合 + reactiveArr: { + tableData: { + [x: string]: string | boolean;}[]; + } = reactive<{ + tableData: ImagesType[] + }>({ + tableData: [] // 表格数据-机房列表 + }); + + // 构造器 + constructor (search: any, filter: any) { + this.search = search; + this.filter = filter; + this.getImageList(); + }; + + /** + * 获取镜像列表数据 + * @param {Object} params 请求参数,默认{} + */ + getImageList = () => { + this.isLoading.value = true; + const param: ParamsType = { + pageNumber: paginationOperate.pageNumber.value, + pageSize: paginationOperate.pageSize.value, + ...this.filter.reactiveArr.filterParams, + ...this.search.reactiveArr.searchParams + }; + store.filterEmpty.deleteEmtpyData(param); + this.imagesInfo.getImage({...param}, this.reactiveArr).then(({images, totalCount}: ImageResponseType) => { + if (totalCount > 0) { + this.reactiveArr.tableData = images.map((item: CurrencyType, index: number) => { + ImageStaticData.imageListTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }); + const val = JSON.parse((item?.systemPartition?.length ? item?.systemPartition : '[]')); + return { + ...item, + newSystemPartition: val + } + }); + paginationOperate.total.value = totalCount; + return; + } + return Promise.reject(''); + }) + .catch((message: string) => { + this.reactiveArr.tableData = []; + paginationOperate.total.value = 0; + methodsTotal.initScrollLeft(this.filter.tableRef.value); + message && msgTip.error(message); + }) + .finally(() => { + this.isLoading.value = false; + this.search.hasClear.value = false; + this.searchTip.value = Object.keys(param).length > 2; + }); + }; +}; + +export default ImageList; diff --git a/bmp-operation-web/src/views/imageManagement/list/table/refresh.ts b/bmp-operation-web/src/views/imageManagement/list/table/refresh.ts new file mode 100644 index 0000000..036bed8 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/table/refresh.ts @@ -0,0 +1,34 @@ + +type ImageLiatType = { + getImageList(): Function; + reactiveArr: { + tableData: { + length: number; + }; + } +}; + +type ResetOperateType = { + reset(): Function; +}; + +interface ParamsType { + imageList: ImageLiatType; + resetOperate: ResetOperateType; +}; + +const refreshOperate = (imageList: ParamsType['imageList'], resetOperate: ParamsType['resetOperate']) => { + const refresh = () => { + if (!imageList?.reactiveArr?.tableData?.length) { + resetOperate.reset(); + return; + } + imageList.getImageList(); + }; + + return { + refresh + }; +}; + +export default refreshOperate; diff --git a/bmp-operation-web/src/views/imageManagement/list/table/reset.ts b/bmp-operation-web/src/views/imageManagement/list/table/reset.ts new file mode 100644 index 0000000..46c565f --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/table/reset.ts @@ -0,0 +1,44 @@ + + +type FilterType = { + tableRef: { + value: { + clearFilter(): any; + }; + }; + reactiveArr: { + filterParams: {}; + }; +}; + +type SearchType = { + hasClear: { + value: boolean; + }; + reactiveArr: { + searchParams: {}; + }; + request(): Function; +}; + +interface ParamsType { + filter: FilterType; + search: SearchType; +}; + +const resetOperate = (filter: ParamsType['filter'], search: ParamsType['search']) => { + + const reset = () => { + filter?.tableRef?.value?.clearFilter(); + filter.reactiveArr.filterParams = {}; + search.hasClear.value = true; + search.reactiveArr.searchParams = {}; + search.request(); + }; + + return { + reset + }; +}; + +export default resetOperate; diff --git a/bmp-operation-web/src/views/imageManagement/list/table/setEmpty.ts b/bmp-operation-web/src/views/imageManagement/list/table/setEmpty.ts new file mode 100644 index 0000000..706a971 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/table/setEmpty.ts @@ -0,0 +1,56 @@ +/** + * @file + * @author +*/ + +import {language} from 'utils/publicClass.ts'; + +const p = document.createElement('p'); +class SetEmpty { + emitValue: any; + + constructor(props: any, emitValue: any) { + this.emitValue = emitValue; + this.watchTableData(props); + onUnmounted(() => p.innerHTML = ''); + }; + + watchTableData = (props: any) => { + watch(() => props?.imageList?.reactiveArr.tableData, (newValue) => { + if (!newValue?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.innerHTML= ''; + }, {deep: true}) + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + ai!.innerHTML = ''; + const customText = document.querySelector('.image-list .el-scrollbar__view'); + if (!customText) return; + p.className = 'custom-tip-count'; + const str = ` + + ${language.t('table.empty')},${language.t('table.tip')} + + + ${language.t('imageList.header.exportImage')} + + ` + const parser = new DOMParser(); + const doc = parser.parseFromString(str, 'text/html'); + p.className = 'custom-tip-count'; + p.innerHTML = doc.body.innerHTML; + customText.appendChild(p) + const clickOpt = document.querySelector('.image-list .custom-tip-count .empty-text'); + clickOpt!.addEventListener('click', () => { + this.emitValue('empty-click') + }) + }; +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/imageManagement/list/table/tableFilter.ts b/bmp-operation-web/src/views/imageManagement/list/table/tableFilter.ts new file mode 100644 index 0000000..b241a32 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/table/tableFilter.ts @@ -0,0 +1,120 @@ +import store from 'store/index.ts' +import {OSSType, ReactiveArrType, FilterParamsType} from '../typeManagement'; +import {paginationOperate} from 'utils/publicClass.ts'; + +/** + * 筛选操作 +*/ +class FilterOperate { + // store库存储的oss数据类 + ossStore: OSSType = store.ossDataInfo(); + tableRef: { + [x: string]: unknown; + value: { + clearFilter(): unknown; + } + } = {value: {clearFilter(): void{}}}; + filterEmptyInfo: { // store + filterParams( + arg0: {[x: string]: number | string}, + arg1: OSSType, + arg2: ReactiveArrType, + arg3: FilterParamsType + ): Promise; + deleteEmtpyData(arg0: FilterParamsType): unknown; + } = store.filterEmpty; + // 复杂数据类型 + reactiveArr: { + filterParams: FilterParamsType; + } = reactive<{ + filterParams: FilterParamsType; + }>({ + filterParams: { + source: '', + architecture: '', + osType: '' + } + }); + fn: any; + + // 构造器 + constructor (fn: any) { + this.fn = fn; + this.ossStore?.getOssData(); + }; + + /** + * 镜像类型筛选 + * @param {number} value 当前选中的value值 + * @param {Object} row 当前点击的这一项 + * @param {string} sourceName sourceName + * @return {string} row.sourceName 赋值 + */ + imageTypeFilter = (): boolean => { + // value: number, row: {sourceName: string;} + return true; + // return row.sourceName === this.ossStore?.source[value - 1]?.text; + }; + + /** + * 操作系统平台筛选 + * @param {number} value 当前选中的value值 + * @param {Object} row 当前点击的这一项 + * @param {string} osType osType + * @return {string} row.osType 赋值 + */ + operateSysFilter = (): boolean => { + // value: number, row: {osType: string;} + return true; + // return row.osType === this.ossStore?.osType[value - 1]?.text; + }; + + /** + * 体系架构筛选 + * @param {number} value 当前选中的value值 + * @param {Object} row 当前点击的这一项 + * @param {string} architecture architecture + * @return {string} row.architecture 赋值 + */ + filterArchitecture = (): boolean => { + // value: number, row: {architecture: string;} + return true; + // return row.architecture === this.ossStore?.architecture[value - 1]?.text; + }; + + /** + * @param {Object} filter 需要过滤的数据 + */ + filterChange = (filter: {[x: string]: number | string}) => { + const filterParams: FilterParamsType = { + architecture: 'architecture', + source: 'source', + osType: 'osType' + }; + this.filterEmptyInfo.filterParams(filter, this.ossStore, this.reactiveArr, filterParams) + .then((res: any) => { + this.reactiveArr.filterParams = res.filterParams; + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn(); + // this.imageList.setFilterData(res, 'filter'); + }); + }; + + /** + * 获取表格ref + * @param {Object} tableEl 表格信息 + */ + getTableRef = (tableEl: { + [x: string]: unknown; + value: { + clearFilter(): unknown; + } + }): void => { + this.tableRef = tableEl; + }; +}; + +export default FilterOperate; diff --git a/bmp-operation-web/src/views/imageManagement/list/table/tableList.vue b/bmp-operation-web/src/views/imageManagement/list/table/tableList.vue new file mode 100644 index 0000000..bf717f5 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/table/tableList.vue @@ -0,0 +1,385 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/imageManagement/list/table/tableScroll.ts b/bmp-operation-web/src/views/imageManagement/list/table/tableScroll.ts new file mode 100644 index 0000000..2d7127b --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/table/tableScroll.ts @@ -0,0 +1,95 @@ +import {HeightType2, HeightType3} from '@utils/publicType'; +import {tableScroll} from 'utils/index.ts'; +import store from 'store/index.ts'; + +interface TableScrollDataType { + scrollTimer: null | number; + searchTipHeight: number; + fixedHeight: Ref; + tableMaxHeight: Ref; + status: boolean; + headerTitle: Ref; + operate: Ref; + operateBtn: Ref; +}; + +const tableScrollOperate = (filters: any['filters'], search: any['search'], searchTip: {value: boolean;}) => { + const data: TableScrollDataType = { + scrollTimer: null, + searchTipHeight: 13, + fixedHeight: ref(0), + tableMaxHeight: ref(0), + status: false, + headerTitle: ref({offsetHeight: 0, scrollHeight: 0}), + operate: ref({offsetHeight: 0, scrollHeight: 0}), + operateBtn: ref({offsetHeight: 0}) + }; + onMounted(() => { + setScroll(setHeight(), data.tableMaxHeight); + onResize(data.tableMaxHeight); + }); + + onUnmounted(() => { + clearTimeout(data.scrollTimer as number) + }) + + watch(() => [ + filters.filterParams, + search.searchParams, + searchTip + ], (newValue) => { + if (newValue[2].value) { + setScroll(data.fixedHeight.value, data.tableMaxHeight); + } + }, {deep: true}); + + watch(() => store.navigationBarStatus.hasNavigationBar, (_: boolean) => { + data.scrollTimer = setTimeout(() => { + setScroll(setHeight(), data.tableMaxHeight); + }, 200) + }); + + const onResize = (tableMaxHeight: {value: number}) => { + window.onresize = () => { + setScroll(setHeight(), tableMaxHeight); + }; + }; + + const setHeight = () => { + const header = data.headerTitle.value; + const operate = data.operate.value; + data.fixedHeight.value = header.offsetHeight * 2.9 + operate.offsetHeight + data.operateBtn.value.offsetHeight; + const countHeight: number = data.fixedHeight.value; + return countHeight; + }; + + const setScroll = (countHeight: number, tableMaxHeight: {value: number}) => { + const params = {...filters.filterParams, ...search.searchParams}; + if (Object.values(params).some((item) => item !== '')) { + tableScroll(countHeight + data.searchTipHeight, tableMaxHeight); + return; + } + tableScroll(countHeight, tableMaxHeight); + }; + + const getBtnRef = (val: {value: HeightType2}) => { + data.operateBtn.value = val.value; + }; + + const getHeaderRef = (val: {value: HeightType3;}) => { + data.headerTitle.value = val.value; + }; + + const getOperateRef = (val: {value: HeightType3;})=> { + data.operate.value = val.value; + }; + + return { + ...data, + getBtnRef, + getHeaderRef, + getOperateRef + } +}; + +export default tableScrollOperate; diff --git a/bmp-operation-web/src/views/imageManagement/list/typeManagement.ts b/bmp-operation-web/src/views/imageManagement/list/typeManagement.ts new file mode 100644 index 0000000..822357b --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/list/typeManagement.ts @@ -0,0 +1,50 @@ +// 系统盘分区模板类 +type SystemPartitionType = {format: string; point: string; size: number;}; + +/** + * params 参数类 +*/ +interface ParamsType { + pageSize: number; + pageNumber: number; +}; + +/** + * 筛选params参数 +*/ +type FilterParamsType = { + source?: string; + architecture: string; + osType: string; +}; + +/** + * 复杂类 +*/ +interface ReactiveArrType { + filterParams?: FilterParamsType; +}; + +/** + * text类 +*/ +type TextType = { + [x: string]: { + text: string; + }; +}; + +interface OSSType { + source: TextType; + osType: TextType; + architecture: TextType; + getOssData(): Function; +}; + +export { + OSSType, + ParamsType, + ReactiveArrType, + FilterParamsType, + SystemPartitionType +}; diff --git a/bmp-operation-web/src/views/imageManagement/navRouter.ts b/bmp-operation-web/src/views/imageManagement/navRouter.ts new file mode 100644 index 0000000..cdb3fa5 --- /dev/null +++ b/bmp-operation-web/src/views/imageManagement/navRouter.ts @@ -0,0 +1,18 @@ +/** + * @file + * @author +*/ + +import {language} from "utils/publicClass.ts"; + +const imageNavData = (pathUrl: (arg0: string) => void, imgUrl: (arg0: string) => void) => { + return { + title: language.t('navigationBar.list.imageManagement'), + defaultImg: imgUrl('imageDefault'), + changeImg: imgUrl('imageManage'), + path: pathUrl('imageList'), + otherPath: [pathUrl('imageList'), pathUrl('imageDetail')] + } +}; + +export default imageNavData; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/detail/allAlarmRulesDetail.vue b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/detail/allAlarmRulesDetail.vue new file mode 100644 index 0000000..d2af48a --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/detail/allAlarmRulesDetail.vue @@ -0,0 +1,264 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/detail/detail.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/detail/detail.ts new file mode 100644 index 0000000..5669e3a --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/detail/detail.ts @@ -0,0 +1,99 @@ +/** + * @file + * @author +*/ +import {CurrentInstance, language} from 'utils/publicClass.ts'; +import {msgTip} from 'utils/index.ts'; +import {describeRulesDetailAPI} from 'api/inBandMonitoring/allAlarmRules/request.ts' +import {AxiosError} from 'axios'; +import AllStaticData from 'staticData/staticData.ts'; + +class AllAlarmRulesDetailOpt { + isLoading: Ref = ref(true); + instanceProxy = new CurrentInstance().proxy; + reactiveArr: any = reactive({ + detail: {} + }); + ruleId: Ref = ref(''); + fn; + + constructor(id: string, fn: Function) { + this.fn = fn; + this.ruleId.value = id; + this.init(); + } + + init = async () => { + this.isLoading.value = true; + try { + const res = await describeRulesDetailAPI({ruleId: this.ruleId.value}) + if (res?.data?.result?.statusName?.length) { + this.reactiveArr.detail = res.data.result; + return; + } + throw new Error(''); + } + catch(e) { + this.reactiveArr.detail = {}; + const err = e as AxiosError; + const path: string = this.instanceProxy.$defInfo.routerPath('alarmRulesList'); + if (AllStaticData.noFoundData.includes(err?.message)) { + this.fn(path); + return; + } + err?.message && msgTip.error(err.message); + } + finally { + this.isLoading.value = false; + } + } + + setName = () => { + if (!this.reactiveArr?.detail?.statusName?.length) return '--'; + const {ruleName, statusName, status} = this.reactiveArr.detail; + return ruleName + `${statusName}`; + } + + setStatusColor = (status: number) => { + const obj = new Map([ + [3, '#ff4d4f'], + [2, '#999'], + [1, '#43b561'] + ]); + return obj.get(status); + } + + setNoticePeriod = () => { + if (!this.reactiveArr?.detail?.noticeOption?.noticePeriod) return '--'; + const {noticePeriod} = this.reactiveArr.detail.noticeOption; + const objData = new Map([ + [5, `${5}${language.t('allAlarmRulesDetail.count.minute')}`], + [10, `${10}${language.t('allAlarmRulesDetail.count.minute')}`], + [15, `${15}${language.t('allAlarmRulesDetail.count.minute')}`], + [30, `${30}${language.t('allAlarmRulesDetail.count.minute')}`], + [60, `${1}${language.t('allAlarmRulesDetail.count.hours')}`], + [180, `${3}${language.t('allAlarmRulesDetail.count.hours')}`], + [360, `${6}${language.t('allAlarmRulesDetail.count.hours')}`], + [720, `${12}${language.t('allAlarmRulesDetail.count.hours')}`], + [1440, `${24}${language.t('allAlarmRulesDetail.count.hours')}`] + ]); + return objData.get(noticePeriod)?? '--'; + } + + // setNoticePeriod = () => { + // if (!this.reactiveArr?.detail?.noticeOption?.noticePeriod) return '--'; + // const {noticePeriod} = this.reactiveArr.detail.noticeOption; + // return `${noticePeriod}${language.t('allAlarmRulesDetail.count.minute')}` + // } + + setNoticeWay = () => { + if (!this.reactiveArr?.detail?.noticeOption?.noticeWay?.length) return ''; + const {noticeWay} = this.reactiveArr.detail.noticeOption; + const value1 = language.t('allAlarmRulesDetail.notice.internalMessage'); + const value2 = language.t('allAlarmRulesDetail.notice.email'); + const newData = noticeWay.map((key: number) => Object.is(key, 1) ? value1 : value2); + return newData.join('、'); + } +} + +export default AllAlarmRulesDetailOpt; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/detail/historyAlarm/historyAlarm.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/detail/historyAlarm/historyAlarm.ts new file mode 100644 index 0000000..9bba1e2 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/detail/historyAlarm/historyAlarm.ts @@ -0,0 +1,20 @@ +/** + * @file + * @author +*/ + +class AlarmHistoryOpt { + alaramHistoryDiaLog: Ref = ref(false) + ruleId: Ref = ref(''); + + alarmHistoryClick = (ruleId: string) => { + this.ruleId.value = ruleId; + this.alaramHistoryDiaLog.value = !this.alaramHistoryDiaLog.value; + } + + alarmHistoryCancel = (type: boolean) => { + this.alaramHistoryDiaLog.value = type; + } +} + +export default AlarmHistoryOpt; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/detail/historyAlarm/historyAlarm.vue b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/detail/historyAlarm/historyAlarm.vue new file mode 100644 index 0000000..97068c9 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/detail/historyAlarm/historyAlarm.vue @@ -0,0 +1,27 @@ + + + diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/detail/page.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/detail/page.ts new file mode 100644 index 0000000..6c32cdb --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/detail/page.ts @@ -0,0 +1,10 @@ +const AllAlarmRulesDetail = () => import(/* webpackChunkName: "AllAlarmRulesDetail" */ './allAlarmRulesDetail.vue'); + +export default { + path: '/InBandMonitoringManagement/allAlarmRulesDetail', + name: 'AllAlarmRulesDetail', + component: AllAlarmRulesDetail, + meta: { + type: 'allAlarmRulesDetail' + } +}; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/allAlarmRulesList.vue b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/allAlarmRulesList.vue new file mode 100644 index 0000000..2fe970d --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/allAlarmRulesList.vue @@ -0,0 +1,115 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/custom/custom.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/custom/custom.ts new file mode 100644 index 0000000..68e00f0 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/custom/custom.ts @@ -0,0 +1,10 @@ +/** + * @file + * @author +*/ + +import useCustom from 'hooks/custom/useCustom.ts'; + +const customOperate = useCustom('monitorRulesList').info; + +export default customOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/custom/customList.vue b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/custom/customList.vue new file mode 100644 index 0000000..7df5b02 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/custom/customList.vue @@ -0,0 +1,9 @@ + + diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/export/export.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/export/export.ts new file mode 100644 index 0000000..f9da7bc --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/export/export.ts @@ -0,0 +1,43 @@ +import {describeRulesExportAPI} from 'api/inBandMonitoring/allAlarmRules/request.ts'; +import {ExportDataOperate} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; + +class ExportFilterData { + // 是否导出数据 + hasExportData: Ref = ref(true); + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + search: { + ruleForm: {} + }; + searchTip: {value: boolean}; + filters; + + constructor(search: {ruleForm: {}}, searchTip: {value: boolean}, filters: any) { + this.filters = filters; + this.search = search; + this.searchTip = searchTip; + }; + + exportData = (that: never) => { + new ExportDataOperate(describeRulesExportAPI, {}, 'alert_rules_list').exportData(that); + }; + + /** + * 参数处理 + */ + paramsProcessing = (that: never) => { + const otherParams = this.searchTip.value ? {...this.search.ruleForm, ...this.filters.reactiveArr.filterParams} : {}; + this.filterEmptyInfo.deleteEmtpyData(otherParams); + new ExportDataOperate(describeRulesExportAPI, { + ...otherParams, + }, 'alert_rules_list').exportData(that); + } +}; + +export { + ExportFilterData, + ExportDataOperate, + describeRulesExportAPI +}; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/export/exportData.vue b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/export/exportData.vue new file mode 100644 index 0000000..2b9f088 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/export/exportData.vue @@ -0,0 +1,23 @@ + + + diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/formSearch/formSearch.vue b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/formSearch/formSearch.vue new file mode 100644 index 0000000..ed1042e --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/formSearch/formSearch.vue @@ -0,0 +1,71 @@ + + diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/formSearch/rules.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/formSearch/rules.ts new file mode 100644 index 0000000..7b01ddc --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/formSearch/rules.ts @@ -0,0 +1,19 @@ +/** + * @file + * @author +*/ +import {language} from 'utils/publicClass.ts'; + +class RulesOpt { + rules = reactive({ + userName: [ + { + trigger: 'blur', + required: true, + message: language.t('allAlarmRulesList.search.errorTip.userName') + } + ] + }) +} + +export default RulesOpt; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/formSearch/rulesForm.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/formSearch/rulesForm.ts new file mode 100644 index 0000000..635ca89 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/formSearch/rulesForm.ts @@ -0,0 +1,125 @@ +/** + * @file + * @author +*/ + +import {RuleFormRefType} from '@utils/publicType'; +import {RuleFormType} from '../typeManagement'; +import {language, paginationOperate} from 'utils/publicClass.ts'; +// import {getDateParams} from 'utils/index.ts'; + +let that; +class RuleFormOperate { + // 表单ref + ruleFormRef: Ref = ref(); + // 表单输入项 + ruleForm: RuleFormType = reactive({ + userName: '', + ruleName: '', + ruleId: '' + }); + searchParams: RuleFormType = reactive({ + ...this.ruleForm + }); + btnStatus: Ref = ref(false); + fn: Function; + filter; + formData = [ + { + prop: 'userName', + label: language.t('allAlarmRulesList.search.label.userName'), + model: 'userName', + placeholder: language.t('allAlarmRulesList.search.placeholder.userName'), + change: 'userName', + clear: 'userName' + }, + { + prop: 'ruleName', + label: language.t('allAlarmRulesList.search.label.ruleName'), + model: 'ruleName', + placeholder: language.t('allAlarmRulesList.search.placeholder.ruleName'), + change: 'ruleName', + clear: 'ruleName' + }, + { + prop: 'ruleId', + label: language.t('allAlarmRulesList.search.label.ruleId'), + model: 'ruleId', + placeholder: language.t('allAlarmRulesList.search.placeholder.ruleId'), + change: 'ruleId', + clear: 'ruleId' + } + ]; + btnData = [ + { + type: 'search', + text: language.t('allAlarmRulesList.search.btn.search') + }, + { + type: 'clear', + text: language.t('allAlarmRulesList.search.btn.clear') + } + ]; + + constructor(filter: any, fn: Function) { + this.filter = filter; + this.fn = fn; + }; + + iptChange = (type: string) => { + this.#replaceEmpty(type); + } + + #replaceEmpty = (type: string) => { + that = this; + this.ruleForm[`${type}` as keyof typeof that.ruleForm] = this.ruleForm[`${type}` as keyof typeof that.ruleForm]?.replace(/\s*/g, ''); + } + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: RuleFormRefType}): void => { + this.ruleFormRef.value = formEl.value; + }; + + searchClearClick = (type: string) => { + Object.is(type, 'search') ? this.searchClick() : this.clearClick(); + } + + searchClick = () => { + this.ruleFormRef.value?.validate((valid: boolean) => { + if (valid) { + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn('search'); + } + }); + }; + + clearIpt = (type: string) => { + const that = this; + this.ruleFormRef.value?.clearValidate(type); + this.ruleForm[`${type}` as keyof typeof that.ruleForm] = ''; + this.fn('hasSearch') + } + + clearClick = () => { + const that = this; + for (let key in this.ruleForm) { + (this.ruleForm[`${key}` as keyof typeof that.ruleForm] as string) = ''; + } + this.ruleFormRef.value?.resetFields(); + this.filter?.tableRef?.value?.clearFilter(); + this.filter.reactiveArr.filterParams = {}; + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn('clear'); + }; +}; + +export default RuleFormOperate; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/historyAlarm/historyAlarm.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/historyAlarm/historyAlarm.ts new file mode 100644 index 0000000..bce27fe --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/historyAlarm/historyAlarm.ts @@ -0,0 +1,20 @@ +/** + * @file + * @author +*/ + +class AlarmHistoryOpt { + alaramHistoryDiaLog: Ref = ref(false) + ruleId: Ref = ref(''); + + alarmHistoryClick = (item: {ruleId: string}) => { + this.ruleId.value = item.ruleId; + this.alaramHistoryDiaLog.value = !this.alaramHistoryDiaLog.value; + } + + alarmHistoryCancel = (type: boolean) => { + this.alaramHistoryDiaLog.value = type; + } +} + +export default AlarmHistoryOpt; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/historyAlarm/historyAlarm.vue b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/historyAlarm/historyAlarm.vue new file mode 100644 index 0000000..97068c9 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/historyAlarm/historyAlarm.vue @@ -0,0 +1,27 @@ + + + diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/page.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/page.ts new file mode 100644 index 0000000..56f91ba --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/page.ts @@ -0,0 +1,10 @@ +const AllAlarmRulesList = () => import(/* webpackChunkName: "AllAlarmRulesList" */ './allAlarmRulesList.vue'); + +export default { + path: '/InBandMonitoringManagement/allAlarmRulesList', + name: 'AllAlarmRulesList', + component: AllAlarmRulesList, + meta: { + type: 'allAlarmRulesList' + } +}; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/allAlarmRulesList.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/allAlarmRulesList.ts new file mode 100644 index 0000000..58cdec4 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/allAlarmRulesList.ts @@ -0,0 +1,129 @@ +/** + * @file + * @author +*/ +import store from 'store/index.ts'; +import {CurrencyType} from '@utils/publicType'; +import {AxiosError} from 'axios'; +import {msgTip} from 'utils/index.ts'; +import {describeRulesAPI} from 'api/inBandMonitoring/allAlarmRules/request.ts' +import {CurrentInstance, RouterOperate, paginationOperate} from 'utils/publicClass.ts'; +import AllAlarmRulesStatic from 'staticData/inBandMonitoring/allAlarmRules/index.ts' + +class AllAlarmRulesListOpt { + errorCode: Ref = ref(0); + routerOperate = new RouterOperate(); + searchTip: Ref = ref(false); + isLoading: Ref = ref(true); // loading态 + // store + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + tableRef: any; + reactiveArr: { + tableData: any[]; + } = reactive<{ + tableData: any[]; + }>({ + tableData: [], // 表格-机型列表数据 + }); + params; + proxy = new CurrentInstance().proxy; + mitt = new CurrentInstance(); + filter; + + constructor(params: any, filter: any) { + + this.filter = filter; + this.params = params; + this.getAllAlarmRulesList(); + // this.owerAuthorization(); + // onMounted(() => { + // nextTick(() => { + // this.getAllAlarmRulesList(); + // }) + // }) + } + + jumpDetail = (item: {ruleId: string}) => { + const path = this.proxy!.$defInfo.routerPath('alarmRulesDetail'); + this.routerOperate.router.push(`${path}?ruleId=${item.ruleId}`) + } + + getAllAlarmRulesList = async (otherParams?: any) => { + this.isLoading.value = true; + const params = { + pageNumber: paginationOperate.pageNumber.value, + pageSize: paginationOperate.pageSize.value, + ...this.filter.reactiveArr.filterParams, + ...otherParams + } + this.filterEmptyInfo.deleteEmtpyData(params); + try { + const res = await describeRulesAPI({...params}); + if (res?.data?.result?.rules?.length) { + const {totalCount, rules} = res.data.result; + rules.forEach((item: CurrencyType, index: number) => { + AllAlarmRulesStatic.allAlarmRulesListTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }); + }) + this.reactiveArr.tableData = rules.map((item: any) => { + return { + ...item, + // showTooltip: false + } + }); + + paginationOperate.total.value = totalCount; + return; + } + throw new Error(''); + } + catch(e) { + this.reactiveArr.tableData = []; + paginationOperate.total.value = 0; + const err = e as AxiosError; + // this.errorCode.value = err.code as unknown as number; + // if (['module license disabled'].includes(err.message)) { + // return; + // } + err?.message && msgTip.error(err.message); + } + finally { + this.isLoading.value = false; + this.searchTip.value = Object.keys(params).length > 2; + this.mitt.instanceMitt?.proxy?.$Bus?.emit('all-alarm-rule-list', this.reactiveArr.tableData); + } + } + + setStatusColor = (status: number) => { + const obj = new Map([ + [3, '#ff4d4f'], + [2, '#999'], + [1, '#43b561'] + ]); + return obj.get(status); + } + + refresh = () => { + if (!this.reactiveArr.tableData.length) { + this.params.clearClick(); + return; + } + this.searchTip.value ? this.search() : this.getAllAlarmRulesList(); + }; + + search = () => { + const params = {}; + for (let index in this.params.ruleForm) { + if (!index.includes('alarm')) { + // @ts-ignore + params[index] = this.params.ruleForm[index]; + } + } + this.getAllAlarmRulesList(params); + } +} + +export default AllAlarmRulesListOpt; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/filterStyle.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/filterStyle.ts new file mode 100644 index 0000000..9b1306b --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/filterStyle.ts @@ -0,0 +1,275 @@ +class FilterStyleOperate { + classNameData = [ + { + name: 'def-type-status15', + type: 'status' + } + ]; + filterStatus: any = reactive({ + status: false, + }) + + constructor (props: any) { + onMounted(() => { + nextTick(() => { + this.customFilter(props); + }) + this.watchSearchTip(props); + this.watchFilter(props); + }) + }; + + watchSearchTip = (props: any) => { + watch(() => + props.allAlarmRulesList.searchTip, (newValue) => { + if (!newValue.value) { + for (let index in this.filterStatus) { + this.filterStatus[index] = false; + } + } + else { + this.setFilterStatus(props.filter.reactiveArr.filterParams); + } + }, { + deep: true + }); + }; + + watchFilter = (props: any) => { + watch(() => props.filter.reactiveArr.filterParams, (newValue) => { + this.setFilterStatus(newValue); + }, {deep: true}) + }; + + setFilterStatus = (params: any) => { + this.classNameData.forEach((item) => { + if (['', undefined].includes(params[item.type])) { + this.filterStatus[item.type] = false; + return; + } + this.filterStatus[item.type] = true; + }) + }; + + customFilter = (props: any) => { + let filterName: HTMLElement | null; + let filterOpt: HTMLElement | null; + this.classNameData.forEach((item) => { + filterName = document.querySelector(`.${item.name} > .cell`); + filterOpt = document.querySelector(`.${item.name} > .cell > .el-table__column-filter-trigger`) + filterName?.addEventListener('click', (event) => { + event.stopPropagation(); + for (let index in this.filterStatus) { + this.filterStatus[index] = false; + } + }) + filterOpt?.addEventListener('click', (event) => { + event.stopPropagation(); + // if (!props.allAlarmRulesList.searchTip.value) { + // const clickStatus: any = { + // 'status': () => { + // this.filterStatus['architecture'] = false; + // this.filterStatus['osType'] = false; + // }, + // 'architecture': () => { + // this.filterStatus['source'] = false; + // this.filterStatus['osType'] = false; + // }, + // 'osType': () => { + // this.filterStatus['architecture'] = false; + // this.filterStatus['source'] = false; + // } + // }; + // clickStatus[item.type](); + // } + this.filterStatus[item.type] = !this.filterStatus[item.type]; + }); + + const filterOtherRegion = document.querySelectorAll('.el-table-filter'); + filterOtherRegion.forEach((_, index) => { + filterOtherRegion[index]?.addEventListener('click', (event) => { + event.stopPropagation(); + for (let index in this.filterStatus) { + for (const key of this.classNameData) { + if (key.type === index && props.allAlarmRulesList.filter?.reactiveArr?.filterParams[key.type]?.length) { + this.filterStatus[index] = true; + } + } + } + }) + }) + let newType = []; + document.addEventListener('click', (event) => { + event.stopPropagation(); + newType = []; + newType.push(item.type); + newType.forEach((ite) => { + this.filterDispose(ite, props); + }) + }) + }) + }; + + filterDispose = (type: string, props: any) => { + const filterVal = props.filter.reactiveArr.filterParams; + const status = Object.values(filterVal).some((item) => item !== ''); + if (!status) { + this.filterStatus[type] = false; + return; + }; + if (props.allAlarmRulesList.searchTip.value) { + for (let key in filterVal) { + if (key === type) { + this.filterStatus[key] = true; + } + else { + if (this.filterStatus[type] && Object.keys(filterVal).length > 1) { + this.filterStatus[type] = !this.filterStatus[type]; + } + else { + this.filterStatus[type] = false; + } + } + } + } + else { + this.filterStatus[type] = false; + } + } +}; + +export default FilterStyleOperate; + +/** + * @file + * @author +*/ + +// class FilterStyleOperate { +// classNameData = [ +// { +// name: 'def-type-status16', +// type: 'status' +// } +// ]; +// filterStatus: { +// status: boolean +// } = reactive({ +// status: false +// }) + +// constructor (props: any) { +// onMounted(() => { +// nextTick(() => { +// this.customFilter(props); +// }) +// this.watchSearchTip(props); +// this.watchFilter(props); +// }) +// }; + +// watchSearchTip = (props: any) => { +// watch(() => +// props.allAlarmRulesList.searchTip, (newValue) => { +// const that = this; +// if (!newValue.value) { +// for (let index in this.filterStatus) { +// (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = false; +// } +// } +// else { +// this.setFilterStatus(props.filter.reactiveArr.filterParams); +// } +// }, { +// deep: true +// }); +// }; + +// watchFilter = (props: any) => { +// watch(() => props.filter.reactiveArr.filterParams, (newValue) => { +// this.setFilterStatus(newValue); +// }, {deep: true}) +// }; + +// setFilterStatus = (params: any) => { +// const that = this; +// this.classNameData.forEach((item) => { +// if (['', void 0].includes(params[item.type])) { +// (this.filterStatus[`${item.type}` as keyof typeof that.filterStatus] as boolean) = false; +// return; +// } +// (this.filterStatus[`${item.type}` as keyof typeof that.filterStatus] as boolean) = true; +// }) +// }; + +// customFilter = (props: any) => { +// let filterName: HTMLElement | null; +// let filterOpt: HTMLElement | null; +// const that = this; +// this.classNameData.forEach((item) => { +// filterName = document.querySelector(`.${item.name} > .cell`); +// filterOpt = document.querySelector(`.${item.name} > .cell > .el-table__column-filter-trigger`) +// filterName?.addEventListener('click', (event) => { +// event.stopPropagation(); +// for (let index in this.filterStatus) { +// (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = false; +// } +// }) +// filterOpt?.addEventListener('click', (event) => { +// event.stopPropagation(); +// (this.filterStatus[`${item.type}` as keyof typeof that.filterStatus] as boolean) = !(this.filterStatus[`${item.type}` as keyof typeof that.filterStatus] as boolean); +// }); +// const filterOtherRegion = document.querySelectorAll('.el-table-filter'); +// filterOtherRegion.forEach((_, index) => { +// filterOtherRegion[index]?.addEventListener('click', (event) => { +// event.stopPropagation(); +// for (let index in this.filterStatus) { +// for (const key of this.classNameData) { +// if (index === key.type && props.allAlarmRulesList.filter.reactiveArr.filterParams[key.type]) { +// (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = true; +// } +// } +// } +// }) +// }) + +// let newType = []; +// document.addEventListener('click', (event) => { +// event.stopPropagation(); +// newType = []; +// newType.push(item.type); +// newType.forEach((ite) => { +// this.filterDispose(ite, props); +// }) +// }) +// }) +// }; + +// filterDispose = (type: string, props: any) => { +// const filterVal = props.filter.reactiveArr.filterParams; +// const that = this; +// if (props.allAlarmRulesList.searchTip.value) { +// for (let key in filterVal) { +// if (key === type) { +// (this.filterStatus[`${key}` as keyof typeof that.filterStatus] as boolean) = true; +// // this.filterStatus[key] = true; +// } +// else { +// // this.filterStatus[type] +// if ((this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean) && Object.keys(filterVal).length > 1) { +// (this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean) = !(this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean); +// } +// else { +// (this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean) = false; +// // this.filterStatus[type] = false; +// } +// } +// } +// } +// else { +// (this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean) = false; +// } +// } +// }; + +// export default FilterStyleOperate; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/setEmpty.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/setEmpty.ts new file mode 100644 index 0000000..169cab2 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/setEmpty.ts @@ -0,0 +1,49 @@ +import {language, CurrentInstance} from 'utils/publicClass'; + +const p = document.createElement('p'); + +class SetEmpty { + mitt: any = new CurrentInstance(); + props; + + constructor(props: any) { + this.props = props; + this.watchTableData(props); + this.mitt.instanceMitt?.proxy?.$Bus?.on('all-alarm-rule-list', this.watchTableData); + onUnmounted(() =>{ + p.innerHTML = ''; + this.mitt.instanceMitt?.proxy?.$Bus?.off('all-alarm-rule-list', this.watchTableData); + }); + }; + + watchTableData = (val: any) => { + if (!val?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.remove(); + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + if (ai === null) return; + ai!.innerHTML = ''; + const customText: HTMLElement | null = document.querySelector('.all-alarm-rule-list .el-scrollbar__view'); + p.className = 'custom-tip-count'; + const str2 = ` + ${language.t('table.empty')} + `; + this.otherEmpty(str2, customText!); + }; + + otherEmpty = (str: string, customText: HTMLElement) => { + const parser = new DOMParser(); + const doc = parser.parseFromString(str, 'text/html'); + p.innerHTML = doc.body.innerHTML; + customText?.appendChild(p); + } +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/tableFilter.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/tableFilter.ts new file mode 100644 index 0000000..d2c7faa --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/tableFilter.ts @@ -0,0 +1,78 @@ +import store from 'store/index.ts' +import {OsStoreType} from '@utils/publicType'; +// import {OSSType, ReactiveArrType, FilterParamsType} from '../typeManagement'; +import {paginationOperate} from 'utils/publicClass.ts'; + +/** + * 筛选操作 +*/ +class FilterOperate { + // store库存储的oss数据类 + ossStore: OsStoreType = store.ossDataInfo(); + tableRef: { + [x: string]: unknown; + value: { + clearFilter(): unknown; + } + } = {value: {clearFilter(): void{}}}; + filterEmptyInfo: { // store + filterParams( + arg0: {[x: string]: number | string}, + arg1: OsStoreType, + arg2: any, + arg3: any + ): Promise; + deleteEmtpyData(arg0: any): unknown; + } = store.filterEmpty; + // 复杂数据类型 + reactiveArr = reactive({ + filterParams: { + status: '' + } + }); + fn: any; + + // 构造器 + constructor (fn: any) { + this.fn = fn; + // this.ossStore?.getOssData(); + }; + + statusFilter = (): boolean => { + return true; + }; + + + /** + * @param {Object} filter 需要过滤的数据 + */ + filterChange = (filter: {[x: string]: number | string}) => { + const filterParams = { + status: 'status' + }; + this.filterEmptyInfo.filterParams(filter, this.ossStore, this.reactiveArr, filterParams) + .then((res: any) => { + this.reactiveArr.filterParams = res.filterParams; + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn('search'); + }); + }; + + /** + * 获取表格ref + * @param {Object} tableEl 表格信息 + */ + getTableRef = (tableEl: { + [x: string]: unknown; + value: { + clearFilter(): unknown; + } + }): void => { + this.tableRef = tableEl; + }; +}; + +export default FilterOperate; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/tableList.vue b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/tableList.vue new file mode 100644 index 0000000..841eddd --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/tableList.vue @@ -0,0 +1,251 @@ + + + diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/tableScroll.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/tableScroll.ts new file mode 100644 index 0000000..f09a458 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/table/tableScroll.ts @@ -0,0 +1,62 @@ +import {HeightType, HeightType2} from '@utils/publicType'; +import {tableScroll} from 'utils/index.ts'; +import {TimerOperate} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; + +class TableScrollOperate extends TimerOperate { + fixedHeight: Ref = ref(0); + tableMaxHeight: Ref = ref(0); + headerTitle: Ref = ref({offsetHeight: 0}); + operate: Ref = ref({offsetHeight: 0, offsetTop: 0}); + searchHeight: Ref = ref({offsetHeight: 0});; + constructor () { + super(); + onMounted(async () => { + // this.fixedHeight.value = this.headerTitle.value.offsetHeight + this.headerTitle.value.scrollHeight + this.operate.value.offsetHeight + // const countHeight = this.searchHeight?.value?.offsetHeight + this.searchHeight?.value?.scrollHeight + this.fixedHeight.value; + tableScroll(this.#setHeight(), this.tableMaxHeight); + this.#resize(); + await this.#watchNavBar(); + }); + + onUnmounted(() => clearTimeout(this.timer)); + }; + + searchRef = (val: {value: HeightType2}) => { + this.searchHeight.value = val.value; + }; + + #watchNavBar = () => { + watch(() => store.navigationBarStatus.hasNavigationBar, (_: boolean) => { + this.timer = setTimeout(() => { + // const countHeight = this.searchHeight?.value?.offsetHeight + this.searchHeight?.value?.scrollHeight + this.fixedHeight.value; + tableScroll(this.#setHeight(), this.tableMaxHeight); + }, 200) + }); + }; + + #resize = () => { + window.onresize = () => { + // const countHeight = this.searchHeight?.value?.offsetHeight + this.searchHeight?.value?.scrollHeight + fixedHeight; + tableScroll(this.#setHeight(), this.tableMaxHeight); + }; + }; + + #setHeight = () => { + // this.headerTitle.value.scrollHeight + this.fixedHeight.value = this.headerTitle.value.offsetHeight * 3 + this.operate.value.offsetHeight + 5; + // this.searchHeight?.value?.scrollHeight + const countHeight = this.searchHeight?.value?.offsetHeight + this.fixedHeight.value; + return countHeight; + }; + + getHeaderRef = (val: {value: HeightType2;}) => { + this.headerTitle.value = val.value; + }; + + getOperateRef = (val: {value: HeightType;})=> { + this.operate.value = val.value; + }; +} + +export default TableScrollOperate; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/typeManagement.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/typeManagement.ts new file mode 100644 index 0000000..b4666ab --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/allAlarmRules/list/typeManagement.ts @@ -0,0 +1,9 @@ +interface RuleFormType { + userName: string; + ruleName: string; + ruleId: string; +}; + +export { + RuleFormType +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/export/export.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/export/export.ts new file mode 100644 index 0000000..22a4233 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/export/export.ts @@ -0,0 +1,48 @@ +import {describeAlertsExportAPI} from 'api/inBandMonitoring/historyAlarmInfo/request.ts'; +import {ExportDataOperate} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; + +class ExportFilterData { + // 是否导出数据 + hasExportData: Ref = ref(true); + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + search: { + ruleForm: {} + }; + searchTip: {value: boolean}; + + constructor(search: {ruleForm: {}}, searchTip: {value: boolean}) { + this.search = search; + this.searchTip = searchTip; + }; + + exportData = (that: never) => { + new ExportDataOperate(describeAlertsExportAPI, {}, 'alert_history_list').exportData(that); + }; + + /** + * 参数处理 + */ + paramsProcessing = (that: never) => { + const params = {}; + for (let index in this.search.ruleForm) { + if (!index.includes('alarm')) { + // @ts-ignore + params[index] = this.search.ruleForm[index]; + } + } + const otherParams = this.searchTip.value ? params : {}; + this.filterEmptyInfo.deleteEmtpyData(otherParams); + new ExportDataOperate(describeAlertsExportAPI, { + ...otherParams, + }, 'alert_history_list').exportData(that); + } +}; + +export { + ExportFilterData, + ExportDataOperate, + describeAlertsExportAPI +}; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/export/exportData.vue b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/export/exportData.vue new file mode 100644 index 0000000..2b9f088 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/export/exportData.vue @@ -0,0 +1,23 @@ + + + diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/formSearch/formSearch.vue b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/formSearch/formSearch.vue new file mode 100644 index 0000000..c8a1770 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/formSearch/formSearch.vue @@ -0,0 +1,103 @@ + + diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/formSearch/rulesForm.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/formSearch/rulesForm.ts new file mode 100644 index 0000000..02cfa7d --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/formSearch/rulesForm.ts @@ -0,0 +1,113 @@ +/** + * @file + * @author +*/ + +import {RuleFormRefType} from '@utils/publicType'; +import {RuleFormType} from '../typeManagement'; +import {language, paginationOperate} from 'utils/publicClass.ts'; + +class RuleFormOperate { + // 表单ref + ruleFormRef: Ref = ref(); + // 表单输入项 + ruleForm: RuleFormType = reactive({ + userName: '', + alarmTime: '', + startTime: null, + endTime: null + }); + searchParams: RuleFormType = reactive({ + ...this.ruleForm + }); + btnStatus: Ref = ref(false); + btnData = [ + { + type: 'search', + text: language.t('historyAlarmInfo.search.btn.search') + }, + { + type: 'clear', + text: language.t('historyAlarmInfo.search.btn.clear') + } + ]; + fn: Function; + + constructor(fn: Function) { + this.fn = fn; + // watch(() => this.ruleForm.alarmTime, (newValue) => { + // if (!newValue) { + // this.ruleFormRef.value?.clearValidate('alarmTime') + + // } + // }, {deep: true}) + }; + + userNameChange = () => { + this.ruleForm.userName = this.ruleForm.userName?.replace(/\s*/g, ''); + }; + + disabledDate = (time: Date) => { + return time.getTime() > Date.now() || time.getTime() < Date.now() - 3600 * 1000 * 24 * 30; + }; + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: RuleFormRefType}): void => { + this.ruleFormRef.value = formEl.value; + }; + + searchClear = (type: string) => { + Object.is(type, 'search') ? this.searchClick() : this.clearClick(); + } + + searchClick = () => { + this.ruleFormRef.value!.validate((valid: boolean) => { + if (valid) { + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn('search'); + } + }) + }; + + clearUserName = () => { + this.ruleForm.userName = ''; + this.ruleFormRef.value?.clearValidate('userName') + this.fn('hasSearch'); + }; + + clearClick = () => { + const that = this; + this.ruleFormRef.value?.resetFields(); + for (let key in this.ruleForm) { + (this.ruleForm[`${key}` as keyof typeof that.ruleForm] as string) = ''; + } + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn('clear'); + }; + + handleBlur = () => { + this.ruleFormRef.value?.clearValidate('alarmTime') + } + + dateChange = (val: string[] | null) => { + if (!val) { + this.ruleForm.startTime = null; + this.ruleForm.endTime = null; + this.fn('hasSearch') + return; + }; + this.ruleForm.startTime = new Date(val[0]).getTime() / 1000; + this.ruleForm.endTime = new Date(val[1]).getTime() / 1000; + } +}; + +export default RuleFormOperate; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/historyAlarmInfo.vue b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/historyAlarmInfo.vue new file mode 100644 index 0000000..3b88f41 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/historyAlarmInfo.vue @@ -0,0 +1,99 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/page.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/page.ts new file mode 100644 index 0000000..7b93d78 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/page.ts @@ -0,0 +1,10 @@ +const HistoryAlarmInfo = () => import(/* webpackChunkName: "HistoryAlarmInfo" */ './historyAlarmInfo.vue'); + +export default { + path: '/InBandMonitoringManagement/historyAlarmInfo', + name: 'HistoryAlarmInfo', + component: HistoryAlarmInfo, + meta: { + type: 'historyAlarmInfo' + } +}; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/table/historyAlarmList.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/table/historyAlarmList.ts new file mode 100644 index 0000000..e08ae55 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/table/historyAlarmList.ts @@ -0,0 +1,98 @@ +/** + * @file + * @author +*/ +import store from 'store/index.ts'; +import {AxiosError} from 'axios'; +import {msgTip} from 'utils/index.ts'; +import {describeAlertsAPI} from 'api/inBandMonitoring/historyAlarmInfo/request.ts' +import {CurrentInstance, paginationOperate} from 'utils/publicClass.ts'; +import HistoryAlarmStatic from 'staticData/inBandMonitoring/historyAlarm/index.ts'; +import {CurrencyType} from '@utils/publicType'; + +class HistoryAlarmInfoOpt { + errorCode: Ref = ref(0); + searchTip: Ref = ref(false); + isLoading: Ref = ref(true); // loading态 + // store + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + tableRef: any; + reactiveArr: { + tableData: any[]; + } = reactive<{ + tableData: any[]; + }>({ + tableData: [], // 表格-机型列表数据 + }); + params; + proxy = new CurrentInstance().proxy; + mitt = new CurrentInstance(); + + constructor(params: any) { + this.params = params; + this.getHistoryAlarmList(); + } + + getHistoryAlarmList = async (otherParams?: any) => { + this.isLoading.value = true; + const params = { + pageNumber: paginationOperate.pageNumber.value, + pageSize: paginationOperate.pageSize.value, + ...otherParams + } + this.filterEmptyInfo.deleteEmtpyData(params); + try { + const res = await describeAlertsAPI({...params}); + if (res?.data?.result?.instances?.length) { + const {totalCount, instances} = res.data.result; + instances.forEach((item: CurrencyType, index: number) => { + HistoryAlarmStatic.historyAlarmListTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }); + }) + this.reactiveArr.tableData = instances; + paginationOperate.total.value = totalCount; + return; + } + throw new Error(''); + } + catch(e) { + this.reactiveArr.tableData = []; + paginationOperate.total.value = 0; + const err = e as AxiosError; + // this.errorCode.value = err.code as unknown as number; + // if (['module license disabled'].includes(err.message)) { + // return; + // } + err?.message && msgTip.error(err.message); + } + finally { + this.isLoading.value = false; + this.searchTip.value = Object.keys(params).length > 2; + this.mitt.instanceMitt?.proxy?.$Bus?.emit('history-alarm-list', this.reactiveArr.tableData); + } + } + + refresh = () => { + if (!this.reactiveArr.tableData.length) { + this.params.clearClick(); + return; + } + this.searchTip.value ? this.search() : this.getHistoryAlarmList(); + }; + + search = () => { + const params = {}; + for (let index in this.params.ruleForm) { + if (!index.includes('alarm')) { + // @ts-ignore + params[index] = this.params.ruleForm[index]; + } + } + this.getHistoryAlarmList(params); + } +} + +export default HistoryAlarmInfoOpt; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/table/setEmpty.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/table/setEmpty.ts new file mode 100644 index 0000000..047a0f1 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/table/setEmpty.ts @@ -0,0 +1,49 @@ +import {language, CurrentInstance} from 'utils/publicClass'; + +const p = document.createElement('p'); + +class SetEmpty { + mitt: any = new CurrentInstance(); + props; + + constructor(props: any) { + this.props = props; + this.watchTableData(props); + this.mitt.instanceMitt?.proxy?.$Bus?.on('history-alarm-list', this.watchTableData); + onUnmounted(() =>{ + p.innerHTML = ''; + this.mitt.instanceMitt?.proxy?.$Bus?.off('history-alarm-list', this.watchTableData); + }); + }; + + watchTableData = (val: any) => { + if (!val?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.remove(); + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + if (ai === null) return; + ai!.innerHTML = ''; + const customText: HTMLElement | null = document.querySelector('.history-alarm-list .el-scrollbar__view'); + p.className = 'custom-tip-count'; + const str2 = ` + ${language.t('table.empty')} + `; + this.otherEmpty(str2, customText!); + }; + + otherEmpty = (str: string, customText: HTMLElement) => { + const parser = new DOMParser(); + const doc = parser.parseFromString(str, 'text/html'); + p.innerHTML = doc.body.innerHTML; + customText?.appendChild(p); + } +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/table/tableList.vue b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/table/tableList.vue new file mode 100644 index 0000000..d0b2e26 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/table/tableList.vue @@ -0,0 +1,197 @@ + + + diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/table/tableScroll.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/table/tableScroll.ts new file mode 100644 index 0000000..f09a458 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/table/tableScroll.ts @@ -0,0 +1,62 @@ +import {HeightType, HeightType2} from '@utils/publicType'; +import {tableScroll} from 'utils/index.ts'; +import {TimerOperate} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; + +class TableScrollOperate extends TimerOperate { + fixedHeight: Ref = ref(0); + tableMaxHeight: Ref = ref(0); + headerTitle: Ref = ref({offsetHeight: 0}); + operate: Ref = ref({offsetHeight: 0, offsetTop: 0}); + searchHeight: Ref = ref({offsetHeight: 0});; + constructor () { + super(); + onMounted(async () => { + // this.fixedHeight.value = this.headerTitle.value.offsetHeight + this.headerTitle.value.scrollHeight + this.operate.value.offsetHeight + // const countHeight = this.searchHeight?.value?.offsetHeight + this.searchHeight?.value?.scrollHeight + this.fixedHeight.value; + tableScroll(this.#setHeight(), this.tableMaxHeight); + this.#resize(); + await this.#watchNavBar(); + }); + + onUnmounted(() => clearTimeout(this.timer)); + }; + + searchRef = (val: {value: HeightType2}) => { + this.searchHeight.value = val.value; + }; + + #watchNavBar = () => { + watch(() => store.navigationBarStatus.hasNavigationBar, (_: boolean) => { + this.timer = setTimeout(() => { + // const countHeight = this.searchHeight?.value?.offsetHeight + this.searchHeight?.value?.scrollHeight + this.fixedHeight.value; + tableScroll(this.#setHeight(), this.tableMaxHeight); + }, 200) + }); + }; + + #resize = () => { + window.onresize = () => { + // const countHeight = this.searchHeight?.value?.offsetHeight + this.searchHeight?.value?.scrollHeight + fixedHeight; + tableScroll(this.#setHeight(), this.tableMaxHeight); + }; + }; + + #setHeight = () => { + // this.headerTitle.value.scrollHeight + this.fixedHeight.value = this.headerTitle.value.offsetHeight * 3 + this.operate.value.offsetHeight + 5; + // this.searchHeight?.value?.scrollHeight + const countHeight = this.searchHeight?.value?.offsetHeight + this.fixedHeight.value; + return countHeight; + }; + + getHeaderRef = (val: {value: HeightType2;}) => { + this.headerTitle.value = val.value; + }; + + getOperateRef = (val: {value: HeightType;})=> { + this.operate.value = val.value; + }; +} + +export default TableScrollOperate; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/typeManagement.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/typeManagement.ts new file mode 100644 index 0000000..c70534d --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/historyAlarmInfo/typeManagement.ts @@ -0,0 +1,10 @@ +interface RuleFormType { + userName: string; + alarmTime: string; + startTime: number | null; + endTime: number | null; +}; + +export { + RuleFormType +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/navRouter.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/navRouter.ts new file mode 100644 index 0000000..420edd2 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/navRouter.ts @@ -0,0 +1,48 @@ +/** + * @file + * @author +*/ + +import {language} from "utils/publicClass.ts"; + +const inBandMonitoringNavData = (pathUrl: (arg0: string) => void, imgUrl: (arg0: string) => void) => { + return { + title: language.t('navigationBar.list.inBandMonitoringManagement'), + defaultImg: imgUrl('defaultInBandMonitoringDef'), + changeImg: imgUrl('defaultInBandMonitoringActive'), + childrenCentF: true, + path: [ + pathUrl('resourceMonitor'), + pathUrl('historyAlarmInfo'), + pathUrl('alarmRulesList'), + pathUrl('alarmRulesDetail') + ], + otherPath: [''], + firstIndex: 'InBandMonitoringManagement', + children: [ + { + title: language.t('navigationBar.children.resourceEcharts'), + defaultImg: imgUrl('defaultInBandMonitoringDef'), + changeImg: imgUrl('defaultInBandMonitoringActive'), + path: pathUrl('resourceMonitor'), + otherPath: [pathUrl('resourceMonitor')] + }, + { + title: language.t('navigationBar.children.historyAlarmInfo'), + defaultImg: imgUrl('defaultInBandMonitoringDef'), + changeImg: imgUrl('defaultInBandMonitoringActive'), + path: pathUrl('historyAlarmInfo'), + otherPath: [pathUrl('historyAlarmInfo')] + }, + { + title: language.t('navigationBar.children.allAlarmRules'), + defaultImg: imgUrl('defaultInBandMonitoringDef'), + changeImg: imgUrl('defaultInBandMonitoringActive'), + path: pathUrl('alarmRulesList'), + otherPath: [pathUrl('alarmRulesList'), pathUrl('alarmRulesDetail')] + }, + ] + } +}; + +export default inBandMonitoringNavData; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/css/echartsPage.scss b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/css/echartsPage.scss new file mode 100644 index 0000000..bc89fdc --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/css/echartsPage.scss @@ -0,0 +1,62 @@ +.echart-bar { + // width: 1129px; + height: 314px; + background: #fff; + flex-direction: column; + border: 1.05px solid #d2d2d2; + border-radius: 8px; + display: flex; + align-items: flex-end; + // margin-right: 26px; + margin-bottom: 20px; + + &:hover { + border-color: #108ee9; + } + + .header { + width: 100%; + position: relative; + + .title { + font-size: 14px; + color: #333; + margin-left: 20px; + margin-top: 9px; + margin-bottom: 9px; + } + + .count { + display: flex; + align-items: center; + font-size: 12px; + margin-left: 20px; + + p { + &:first-child { + margin-right: 20px; + } + } + + :deep(.el-select) { + .el-input__inner { + width: 55px; + height: 18px; + font-size: 12px; + padding-right: 0; + } + + .el-input__suffix { + right: 4px; + transform: scale(.8); + } + } + } + } + .echart-context { + top: -15px; + margin-top: 14px; + width: 100%; + height: 243px; + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/css/index.scss b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/css/index.scss new file mode 100644 index 0000000..ea8c7be --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/css/index.scss @@ -0,0 +1,87 @@ +@import 'assets/css/listSearch.scss'; + +.resource-monitor-content { + .header-count { + position: sticky; + top: 0; + } + + .resource-monitor-count { + margin-top: 25px; + + :deep(.echarts-count) { + margin: 10px 30px 0; + } + + .page-count { + position: relative; + } + + .no-ower-text { + // position: absolute; + font-size: 12px; + // bottom: 0; + // width: 100%; + // margin: 0 auto; + text-align: center; + } + + .no-empty-img { + width: 363px !important; + height: 180px !important; + margin: 0px auto 0px; + } + + :deep(.in-band-monitoring) { + label { + line-height: 1.3; + } + } + + // :deep(.el-loading-parent--relative) { + // // margin-top: 150px; + // } + + :deep(.hours-select) { + .el-form-item__content { + margin-left: 0 !important; + margin-right: 46px; + } + + .radio-active { + height: 30px; + display: flex; + align-items: center; + } + } + + :deep(.set-empty) { + margin-bottom: 28px; + + .el-form-item__error { + padding-top: 7px; + } + } + :deep(.opt-btn) { + .el-form-item__content { + margin-left: 0 !important; + } + } + :deep(.daterange-select) { + .el-date-editor { + height: 30px; + } + .el-form-item__content { + margin-left: 0 !important; + margin-right: 46px; + } + } + + :deep(.el-range-editor.el-input__inner) { + .el-range-separator { + font-size: $fontSize; + } + } + } +} + diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/echartsData.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/echartsData.ts new file mode 100644 index 0000000..cfd36ad --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/echartsData.ts @@ -0,0 +1,396 @@ +/** + * @file + * @author +*/ + +import RuleFormOpt from './utils/ruleForm'; +import publicConfigOpt from './utils/publicConfig'; +import InitStaticData from './utils/initStaticData'; +import {language} from 'utils/publicClass.ts'; +import {deepCopy, intervalTime, getMonthHoursMinutes} from 'utils/index.ts'; +import {publicOption, seriesDataObj, echartsOpt} from './options'; +import {monitorDataAPI} from 'api/inBandMonitoring/resourceMonitor/request.ts'; +import {NewDataType, NewTimeType, HourRangesType, ReactiveArrType, EchartsDataObjType} from './type'; +import * as echarts from 'echarts'; + +class EchartsOpt extends RuleFormOpt { + errorCode: Ref = ref(0); + pageLoading: Ref = ref(false); + cycle: Ref = ref('1min'); + readioSearch: Ref = ref(language.t('monitorEcharts.radio.instance')); + hours: Ref = ref(language.t('monitorEcharts.tabs.h1')); + value1: Ref = ref(''); + selectValForm = reactive({ + disk: [], + mountpoint: [], + nic: [] + }); + diskVal: Ref = ref(''); + mountpointVal: Ref = ref(''); + nicVal: Ref = ref(''); + reactiveArr: ReactiveArrType = reactive({ + aggregationMethod: publicConfigOpt.aggregationMethod, + isLoadingObj: {}, + copyData: [], + isShowObj: {}, + echartsParamsData: InitStaticData.echartsParamsData, + // @ts-ignore + echartsData: InitStaticData.echartsData + }); + str = ` + ${language.t('table.empty')} + `; + props; + + constructor(props: any) { + super(); + const that = this; + for (let index in this.ruleForm) { + (this.reactiveArr.isLoadingObj[`${index}` as keyof typeof that.reactiveArr.isLoadingObj] as boolean) = false; + (this.reactiveArr.isShowObj[`${index}` as keyof typeof that.reactiveArr.isShowObj] as boolean) = false; + } + this.props = props; + this.reactiveArr.copyData = deepCopy(this.reactiveArr.echartsData); + // this.initData(); + this.initEchartsParamsData(); + this.watchHours(); + this.watchValue1(); + this.watchEchartsShow(); + } + + watchEchartsShow = () => { + watch(() => this.reactiveArr.isShowObj, (newValue) => { + const that = this; + for (let index in newValue) { + if (!this.reactiveArr.isShowObj[`${index}` as keyof typeof that.reactiveArr.isShowObj]) { + // @ts-ignore + for (const key of this.reactiveArr.echartsData) { + if (Object.is(key.typeVal, index)) key.aggregationMethod = 'avg'; + } + } + } + }, {deep: true}) + } + + watchValue1 = () => { + watch(() => this.value1, (newValue) => { + this.value1Val(newValue.value); + if (newValue.value?.length) { + if (this.hours.value?.length) { + this.hours.value = '' + } + this.refresh(); + } + + }, {deep: true}) + } + + value1Val = (value: string) => { + if (value !== null) { + // intervalTime 计算两个时间之间的时间差 多少天时分秒 + const val = intervalTime(value[0], value[1]); + const objData = [ + [ + () => !val.days, + () => { + const hourRanges: HourRangesType = { + '0': '1min', + '6': '5min', + '12': '10min', + '24': '1min' + }; + // @ts-ignore + const cycleValue = hourRanges[Math.floor(val.hours / 6) * 6] || ''; + if (cycleValue?.length) { + this.cycle.value = cycleValue; + } + } + ], + [ + () => val.days, + () => { + this.cycle.value = val.days >= 14 ? '180min' : val.days >= 7 ? '120min' : val.days >= 3 ? '60min' : '20min'; + } + ] + ]; + for (const key of objData) { + if (key[0]()!) { + key[1](); + break; + } + } + return; + } + this.hours.value = language.t('monitorEcharts.tabs.h1'); + this.cycle.value = '1min'; + } + + isLoading = (type: string) => { + const that = this; + return this.reactiveArr.isLoadingObj[`${type}` as keyof typeof that.reactiveArr.isLoadingObj]; + } + + watchHours = () => { + watch(() => this.hours, (newValue: {value: string}) => { + const val: {value: string} = InitStaticData.radioData.filter((item: {label: string}) => item.label === newValue.value)[0]; + if (newValue.value.length) { + if (this.value1.value?.length) { + this.value1.value = '' + } + this.cycle.value = val.value; + this.refresh(); + } + else { + if (!Object.is(val, void 0)) { + this.cycle.value = val.value; + this.refresh(); + } + } + }, { + deep: true + }) + } + + searchInfo = (ruleForm: any, _: boolean = true) => { + const data = this.reactiveArr.echartsData; + const objData = ruleForm.monitoringIndicators; + const isShowObj = this.reactiveArr.isShowObj; + ruleForm.keyData = []; + if (Array.isArray(data)) { + for (const key of data) { + for (const item of objData) { + if (Array.isArray(key.metricName) && item.includes(key.metricName.join(','))) ruleForm.keyData.push(key); + else if (Object.is(item, key.metricName)) ruleForm.keyData.push(key); + } + } + } + for (const listItem of ruleForm.keyData) { + for (let index in isShowObj) { + const status: boolean = Object.is(index, listItem.typeVal); + (this.reactiveArr.isShowObj[`${index}` as keyof typeof isShowObj] as boolean) = status; + } + } + for (const key of ruleForm.keyData) { + this.getEcharts(key) + } + } + + clearSearchInfo (ruleFormOperate: {ruleForm: {keyData: []}}, ruleForm: {monitoringIndicators: []}) { + const isShowObj = this.reactiveArr.isShowObj; + // this.pageLoading.value = false; + ruleFormOperate.ruleForm.keyData = []; + ruleForm.monitoringIndicators = []; + this.reactiveArr.echartsData = this.reactiveArr.copyData; + for (let index in this.reactiveArr.isShowObj) { + (this.reactiveArr.isShowObj[`${index}` as keyof typeof isShowObj] as boolean) = false; + } + } + + initEchartsParamsData = () => { + const that = this; + for (const key of this.reactiveArr.echartsParamsData) { + key.model = this.ruleForm[`${key.type}` as keyof typeof that.ruleForm]; + key.bigClickVal.model = this.ruleForm[`${key.type}` as keyof typeof that.ruleForm]; + } + } + + initData = () => { + if (Array.isArray(this.reactiveArr.echartsData)) { + for (const key of this.props.ruleForm.keyData) { + // 循环体 + this.getEcharts(key); + } + } + else { + throw new Error('数据格式出错,不是一个数组') + } + } + + refresh = () => { + const value = this.readioSearch.value; + const objData = [ + [ + () => Object.is(value, language.t('monitorEcharts.radio.instance')), + () => this.initData() + ] + ]; + for (const key of objData) { + if (key[0]()!) { + return key[1](); + } + } + } + + getTagName = (value: string) => { + const tagName = new Map([ + [language.t('monitorEcharts.radio.disk'), 'disk'], + [language.t('monitorEcharts.radio.diskPartition'), 'mountpoint'], + [language.t('monitorEcharts.radio.netWorkInterface'), 'nic'] + ]); + return tagName.get(value); + } + + disabledDate = (time: any) => { + return time.getTime() > Date.now() || time.getTime() < Date.now() - 3600 * 1000 * 24 * 30; + } + + showStatus = () => { + const status = this.reactiveArr.echartsData.some((item) => item.data.length !== ''); + return status; + } + + echartShowStatus = (type: string) => { + const that = this; + // && !this.defaultShowLoading.value; + return this.reactiveArr.isShowObj[`${type}` as keyof typeof that.reactiveArr.isShowObj] && !this.pageLoading.value; + } + + getEcharts = async (key: T) => { + const {idcId, instanceId, userName} = this.props.ruleForm; + this.setLoading(key.typeVal, true) + this.setShow(key.typeVal, true); + // this.pageLoading.value = true; + const param = { + metricName: typeof key.metricName === 'string' ? key.metricName : key.metricName.join(','), + instanceId, + idcId, + userName, + // 周期 + timeInterval: Number(this.cycle.value.split('min')[0]) * 60, + } + const otherParams = !this.value1.value ? {lastManyTime: Number(this.setTabsParams())} : this.setDateParams(); + try { + const allParams = { + ...param, + ...otherParams, + downSampleType: key.aggregationMethod + } + const res = await monitorDataAPI(allParams); + if (res?.data?.result?.length) { + if (!['main6', 'main7', 'main8', 'main9'].includes(key.id)) { + const [data] = res.data.result; + key.data = data.data.map((item: {value: string}) => parseFloat(Number(item.value).toFixed(2))); + key.timeData = data.data.map((item: {timestamp: number}) => getMonthHoursMinutes(item.timestamp)); + const initTimeData = data.data.map((item: {timestamp: number}) => (item.timestamp)); + // @ts-ignore + this.setData(key, initTimeData); + } + else { + const newData: NewDataType[] = Array.from(res.data.result, (item: {data: {map: NewDataType['map']}}) => { + return item.data.map((ite: {value: string}) => { + const value = parseFloat(ite.value); + return isNaN(value) ? NaN : value; + }); + }); + const newTimes: NewTimeType[] = Array.from(res.data.result, (item: {data: {map: NewTimeType['map']}}) => { + return item.data.map((ite: {timestamp: number}) => getMonthHoursMinutes(ite.timestamp)); + }); + const newArrData = newData.map((item) => { + return item.map((t) => parseFloat(Number(t).toFixed(2))); + }); + const initTimes: NewTimeType[] = Array.from(res.data.result, (item: {data: {map: NewTimeType['map']}}) => { + return item.data.map((ite: {timestamp: number}) => (ite.timestamp)); + }); + key.data = newArrData; + key.timeData = [newTimes[0]]; + // @ts-ignore + this.setData(key, initTimes[0]); + } + return; + } + throw new Error(''); + } + catch { + key.data = []; + key.timeData = []; + this.reactiveArr.echartsData = this.reactiveArr.copyData; + // this.props.ruleForm.keyData = []; + // @ts-ignore + this.setData(key, []); + // this.setShow(key.typeVal, false); + } + finally { + this.pageLoading.value = false; + // this.defaultShowLoading.value = false; + this.setLoading(key.typeVal, false); + } + } + + setLoading = (type: string, bol: boolean) => { + const that = this; + for (let index in this.reactiveArr.isLoadingObj) { + if (index === type) { + (this.reactiveArr.isLoadingObj[`${index}` as keyof typeof that.reactiveArr.isLoadingObj] as boolean) = bol; + } + } + } + + setShow = (type: string, bol: boolean) => { + const that = this; + for (let index in this.reactiveArr.isShowObj) { + if (index === type) { + (this.reactiveArr.isShowObj[`${index}` as keyof typeof that.reactiveArr.isShowObj] as boolean) = bol; + } + } + } + + setDateParams = () => { + return { + startTime: new Date(this.value1.value[0]).getTime() / 1000, + endTime: new Date(this.value1.value[1]).getTime() / 1000 + }; + } + + setTabsParams = () => { + const obj = new Map([ + [language.t('monitorEcharts.tabs.h1'), '1'], + [language.t('monitorEcharts.tabs.h6'), '6'], + [language.t('monitorEcharts.tabs.h12'), '12'], + [language.t('monitorEcharts.tabs.d1'), '24'], + [language.t('monitorEcharts.tabs.d3'), '72'], + [language.t('monitorEcharts.tabs.d7'), '168'], + [language.t('monitorEcharts.tabs.d14'), '336'] + ]) + return obj.get(this.hours.value); + } + + setData = (key: {id: T, data: number[], type: K, timeData: number[], unit: K, hoverUnit: T}, data: number[] | NewTimeType) => { + nextTick(() => { + if (document.getElementById(key.id)) { + this.reqEcharts(key.id, key.data, key.type, key.timeData, key.unit, key.hoverUnit, data) + } + }) + } + + reqEcharts = (id: string, ...args: any) => { + const newData = !Array.isArray(args[1]) ? [ + seriesDataObj(args[1], args[0], publicConfigOpt.singleColor) + ] : [ + ...this.setEcharts(args[1], args[0]) + ]; + const myChart = echarts?.getInstanceByDom(document.getElementById(id) as HTMLElement); + publicOption([args[1]], args[2], args[3], newData, args[0], args[4], id, args[5]).then((res: any) => { + echartsOpt(res, id, myChart); + }) + .catch((err) => { + throw new Error(err) + }) + } + + setEcharts = (data: string[], args: number[][]) => { + let newData = []; + for (let i = 0; i < data.length; i++) { + newData.push(seriesDataObj(data[i], args[i], publicConfigOpt.moreColor[i])); + } + return newData; + } + + selectChange = (val: string, value: string) => { + const that = this; + this.ruleForm[`${val}` as keyof typeof that.ruleForm] = value; + // @ts-ignore + publicConfigOpt.smallBigSet(that, val, 'small', value); + } +} + +export default EchartsOpt; \ No newline at end of file diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/echartsPage.vue b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/echartsPage.vue new file mode 100644 index 0000000..3b0bed5 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/echartsPage.vue @@ -0,0 +1,65 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/formSearch/formSearch.vue b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/formSearch/formSearch.vue new file mode 100644 index 0000000..a1a72da --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/formSearch/formSearch.vue @@ -0,0 +1,236 @@ + + diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/formSearch/rules.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/formSearch/rules.ts new file mode 100644 index 0000000..7edbb6b --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/formSearch/rules.ts @@ -0,0 +1,54 @@ +/** + * @file + * @author +*/ +import {language} from "utils/publicClass"; + +class RulesCheckOpt { + rules = reactive({ + userName: [ + { + required: true, + trigger: 'blur', + message: language.t('resourceMonitor.errorTip.userName') + } + ], + resourceType: [ + { + required: true, + trigger: 'change', + message: language.t('resourceMonitor.errorTip.resourceType') + } + ], + idcId: [ + { + required: true, + trigger: 'blur', + message: language.t('resourceMonitor.errorTip.idcName') + } + ], + instanceId: [ + { + required: true, + trigger: 'blur', + message: language.t('resourceMonitor.errorTip.instanceId') + } + ], + dimension: [ + { + required: true, + trigger: 'change', + message: language.t('resourceMonitor.errorTip.dimensions') + } + ], + monitoringIndicators: [ + { + required: true, + trigger: 'blur', + message: language.t('resourceMonitor.errorTip.monitoringMetrics') + } + ] + }); +} + +export default RulesCheckOpt; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/formSearch/rulesForm.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/formSearch/rulesForm.ts new file mode 100644 index 0000000..a9ed8d5 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/formSearch/rulesForm.ts @@ -0,0 +1,114 @@ +/** + * @file + * @author +*/ + +import {language} from '@utils/publicClass'; +import {RuleFormType} from '../typeManagement'; +import {RuleFormRefType} from '@utils/publicType'; +import store from 'store/index.ts'; +import ResourceMonitorStaticData from 'staticData/inBandMonitoring/resourceMonitor/index.ts' + +class RuleFormOperate { + monitoringIndicators: {name: string; value: string}[] = ResourceMonitorStaticData.monitoringIndicators; + checkAll: Ref = ref(false); + indeterminate: Ref = ref(false); + // 表单ref + ruleFormRef: Ref = ref(); + // 表单输入项 + ruleForm: RuleFormType = reactive({ + keyData: [], + userName: '', + resourceType: language.t('resourceMonitor.search.count.resourceType'), + idcId: '', + instanceId: '', + dimension: language.t('resourceMonitor.search.count.dimensions'), + monitoringIndicators: [] + }); + + searchParams: RuleFormType = reactive({ + ...this.ruleForm + }); + btnStatus: Ref = ref(false); + fn: Function; + + constructor(fn: Function) { + this.fn = fn; + watch(() => store.idcInfo.idcData, (newValue: {idcId: string}[]) => { + this.ruleForm.idcId = newValue[0]?.idcId; + }) + this.watchMonitoringIndicators(); + }; + + watchMonitoringIndicators = () => { + watch(() => this.ruleForm.monitoringIndicators, (newValue) => { + this.ruleFormRef.value!.clearValidate('monitoringIndicators') + if (!newValue?.length) { + this.checkAll.value = false; + this.indeterminate.value = false; + } + else if (newValue.length === this.monitoringIndicators.length) { + this.checkAll.value = true; + this.indeterminate.value = false + } + else { + this.indeterminate.value = true + } + }) + } + + handleCheckAll = (val: boolean) => { + this.ruleForm.monitoringIndicators = val ? this.monitoringIndicators.map((item: {value: string}) => item.value) : []; + } + + userNameChange = () => { + this.ruleForm.userName = this.ruleForm.userName?.replace(/\s*/g, ''); + }; + + instanceIdChange = () => { + this.ruleForm.instanceId = this.ruleForm.instanceId?.replace(/\s*/g, ''); + }; + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: RuleFormRefType}): void => { + this.ruleFormRef.value = formEl.value; + }; + + disabledDate = (time: any) => { + return time.getTime() > Date.now() || time.getTime() < Date.now() - 3600 * 1000 * 24 * 30; + } + + searchClick = () => { + this.ruleFormRef.value?.validate((valid: boolean) => { + if (valid) this.fn('search', this.ruleForm); + }); + }; + + clearInstanceId = () => { + this.ruleForm.instanceId = ''; + } + + clearUserName = () => { + this.ruleForm.userName = ''; + }; + + clearClick = () => { + const that = this; + for (let key in this.ruleForm) { + if (Array.isArray(this.ruleForm[key as keyof RuleFormType])) { + (this.ruleForm[`${key}` as keyof typeof that.ruleForm] as []) = []; + } + if (!['resourceType', 'idcId', 'dimension'].includes(key)) { + (this.ruleForm[`${key}` as keyof typeof that.ruleForm] as string) = ''; + this.ruleFormRef.value!.clearValidate('userName'); + this.ruleFormRef.value!.clearValidate('instanceId'); + } + } + this.fn('', this.ruleForm); + }; +}; + +export default RuleFormOperate; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/options.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/options.ts new file mode 100644 index 0000000..a95ae63 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/options.ts @@ -0,0 +1,257 @@ +/** + * @file + * @author +*/ + +import store from 'store/index.ts'; +import * as echarts from 'echarts'; + +const kb: number = 1000; +const mb: number = kb * 1000; +const gb: number = mb * 1000; +const tb: number = gb * 1000; +const pb: number = tb * 1000; +const eb: number = pb * 1000; + +const reg = (str: string) => str.replace(/\.00$/, ''); +let myChartD: any = []; + +const watchNav = () => { + watch(() => store.navigationBarStatus.hasNavigationBar, () => { + if (Object.is(myChartD, void 0)) return; + setTimeout(() => { + if (myChartD?.length) { + for (const key of myChartD) { + key?.resize() + } + } + }, 200) + }, {deep: true}) +} +watchNav(); + +const publicOption = (legendData: string[], ...args: any) => { + return new Promise((resolve) => { + resolve({ + title: { + top: '10px', + textStyle: { + fontSize: 14 + } + }, + tooltip: { + trigger: 'axis', + formatter: function (params: {seriesName: string; value: number; color: string; axisValue: string;}[]) { + let res: string = ''; + for (let i = 0, l = params.length; i < l; i++) { + const yearSecond = new Date(args[6][i] * 1000); + const yearSecondZero = new Date(args[6][0] * 1000); + const monthDateTime = params[i].axisValue.replace(/\n/g, ','); + const seconds = isNaN(yearSecond.getSeconds()) ? yearSecondZero.getSeconds() < 10 ? '0' + yearSecondZero.getSeconds() : yearSecondZero.getSeconds() : yearSecond.getSeconds() < 10 ? '0' + yearSecond.getSeconds() : yearSecond.getSeconds(); + res += `

${isNaN(yearSecond.getFullYear()) ? yearSecondZero.getFullYear() : yearSecond.getFullYear()}-${monthDateTime.split(',').reverse()[0] + ' ' + monthDateTime.split(',').reverse()[1] + ':' + seconds}

` + res += ''; + // res += symbol + ' ' + params[i].seriesName + ' : ' + params[i].value + (args[1] === 'custom' ? flag === '1' ? 'M' : flag === '2' ? 'G' : 'K' : args[4]) +'' + '
'; + // (args[1] === 'custom' ? convertBytesUnit(Number(params[i].value)) : ) + res += ' ' + params[i].seriesName + ' : ' + setUnit(args, params[i].value) + '
'; + } + return res; + }, + textStyle: { + color: '#333', + fontSize: 12 + } + }, + legend: { + data: isMultiDimensional(legendData) ? legendData[0] : legendData, + left: '18', + top: '5%', + itemWidth: 16, + itemHeight: 8, + textStyle: { + color: '#333', + fontSize: 12 + }, + }, + grid: { + left: '22', + // right: '7%', + bottom: '3%', + containLabel: true + }, + xAxis: { + type: 'category', + boundaryGap: false, + data: isMultiDimensional(args[0]) ? args[0][0].map(function (str: string) { + return str.replace(' ', '\n'); + }) : args[0].map(function (str: string) { + return str.replace(' ', '\n'); + }), + }, + yAxis: { + type: 'value', + // min: isMultiDimensional(args[3]) ? 0 : Object.is(args[1], '%') && args[3].some((item: number) => item > 100) ? 0 : Math.min(...args[3]), + // max: isMultiDimensional(args[3]) ? 'dataMax' : args[3].some((item: number) => item > 100) ? 'dataMax' : 100, + // min: isMultiDimensional(args[3]) ? 0 : args[3].every((item: number) => item < 100) ? 0 : Math.min(...args[3]), + // max: isMultiDimensional(args[3]) ? '' : args[3].every((item: number) => item < 100) ? 100 : '', + min: isMultiDimensional(args[3]) ? 0 : args[3].every((item: number) => Number(item) < 0) ? '' : args[3].every((item: number) => Number(item) <= 100) ? 0 : Math.min(...args[3]), + max: isMultiDimensional(args[3]) ? '' : args[3].every((item: number) => Number(item) < 0) ? '' : args[3].every((item: number) => Number(item) <= 100) ? 100 : '', + axisLabel: { + formatter: function(value: number) { + return setFormAtter(args, value) + } + } + }, + dataZoom: [ + { + type: 'inside', + show: false, + start: Math.min(...args[6]), + end: Math.max(...args[6]), + } + ], + series: args[2] + }) + }) +}; + +const addSymbol = (num: string) => { + return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'); +}; + +const setUnit = (args: any, value: T) => { + if (['custom'].includes(args[1])) { + return convertBytesUnit(Number(value)); + } + else if (['个', '次/秒', '个/秒'].includes(args[1])) { + // if (value >= 1000) { + // // .toFixed(2) + // // parseFloat + // return reg(addSymbol((String(value / 1000)))) + 'K' + args[1]; + // } + return `${value}${args[1]}`; + } + else { + return reg(value.toFixed(2)) + args[4]; + } +} + +const setFormAtter = (args: any, value: number) => { + const objData = [ + [ + () => Object.is(args[1], 'custom'), + () => {return `${convertBytesUnit(value)}`} + ], + [ + () => ['个', '次/秒', '个/秒'].includes(args[1]), + () => { + if (value >= 1000) { + // .toFixed(2) + // parseFloat + return reg(addSymbol((String(value / 1000)))) + 'K'; + } + return `${reg(value.toFixed(2))}` + } + ], + [ + () => args[1] || !args[1], + // ${args[1]} + () => {return `${reg(value.toFixed(2))}`} + ] + ]; + for (const key of objData) { + if (key[0]()) { + return key[1](); + } + } +} + +const convertBytesUnit = (bytes: number) => { + const dataList = [ + [ + () => bytes < kb, + () => {return reg(String(bytes)) + ' B';} + ], + [ + () => bytes < mb, + () => {return reg((bytes / kb).toFixed(2)) + ' K';} + ], + [ + () => bytes < gb, + () => {return reg((bytes / mb).toFixed(2)) + ' M';} + ], + [ + () => bytes < tb, + () => {return reg((bytes / gb).toFixed(2)) + ' G';} + ], + [ + () => bytes < pb, + () => {return reg((bytes / tb).toFixed(2)) + ' T';} + ], + [ + () => bytes < eb, + () => {return reg((bytes / pb).toFixed(2)) + ' P';} + ] + ]; + for (const key of dataList) { + if (key[0]()) { + return key[1](); + } + } +} + +// const setData = (data: number[][]): number[] => { +// let newData: number[] = []; +// data.forEach((item) => { +// newData.push(...item) +// }) +// return newData; +// } + +const isMultiDimensional = (arr: string[] | number[][]) => { + return Array.isArray(arr) && arr.some(item => Array.isArray(item)); +} + +const seriesDataObj = (name: any, ...args: any) => { + return { + name, + type: 'line', + smooth: true, + data: args[0], + itemStyle: { + color: args[1], // 点的颜色 + lineStyle: { + color: args[1] // 线的颜色 + } + }, + }; +} + +const echartsOpt = (res: any, type: string, myChart: any) => { + // myChartD = []; + // myChartD = [...myChart]; + + if (!res.yAxis.max) { + Reflect.deleteProperty(res.yAxis, 'max') + } + if (Object.is(myChart, void 0)) { + myChart = echarts.init(document.getElementById(type)); + myChartD.push(myChart); + // newMyChart = myChart; + // window.addEventListener('resize', () => size(myChart)) + } + // myChartD = data; + + // myChartD = [...myChartD, ...myChart]; + res && myChart.setOption(res); +} + +// const size = (myChart: any) => { +// myChart?.resize() +// } + +export { + publicOption, + seriesDataObj, + echartsOpt, + myChartD +}; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/page.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/page.ts new file mode 100644 index 0000000..37ca733 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/page.ts @@ -0,0 +1,10 @@ +const ResourceMonitor = () => import(/* webpackChunkName: "ResourceMonitor" */ './resourceMonitor.vue'); + +export default { + path: '/InBandMonitoringManagement/resourceMonitor', + name: 'ResourceMonitor', + component: ResourceMonitor, + meta: { + type: 'resourceMonitor' + } +}; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/resourceMonitor.vue b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/resourceMonitor.vue new file mode 100644 index 0000000..f7b23cb --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/resourceMonitor.vue @@ -0,0 +1,78 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/type.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/type.ts new file mode 100644 index 0000000..086a478 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/type.ts @@ -0,0 +1,98 @@ +/** + * @file + * @author +*/ + +interface NewDataType { + map: (args: (ite: {value: string;}) => number) => NewDataType; +}[]; + +interface NewTimeType { + map: (args: (ite: {timestamp: number;}) => number) => NewTimeType; +}[]; + +interface HourRangesType { + '0': string; + '6': string; + '12': string; + '24': string; +}; + +type EchartsParamsDataType = { + title: string; + showType: string[]; + model: string; + type: string; + id: string; + bigClickVal: { + type: string; + title: string; + model: string; + } +}[]; + + +type PublicType = { + typeVal: T; + id: string; + data: NewDataType[]; + type: string | string[]; + timeData: NewTimeType[]; + aggregationMethod: string; + metricName: string | string[]; + unit: string; + hoverUnit: string; + status?: string[] | undefined; +}; + +interface EchartsDataType extends PublicType { + filter(arg0: (item: {status: string}) => boolean): []; + some(arg0: (item: {data: {length: string}}) => boolean): []; +}; + +interface EchartsDataObjType extends PublicType {}; + +interface ReactiveArrType { + aggregationMethod: string[]; + isLoadingObj: {[x: string]: boolean} | {}; + isShowObj: {[x: string]: boolean} | {}; + echartsParamsData: EchartsParamsDataType; + echartsData: EchartsDataType; + copyData: any; +}; + +type FormType1 = { + cpu: string; + mem: string; + memUsage: string; + diskUsage: string; + diskUsageRate: string; +}; + +type FormType2 = { + diskReadWriteTraffic: string; + diskReadWriteIOPS: string; + netWorkBps: string; + netWorkPackagesNum: string; + averageLoad1Min: string; +}; + +interface RuleFormType extends FormType1, FormType2 { + averageLoad5Min: string; + averageLoad15Min: string; + totalTCPConnections: string; + normalTCPConnections: string; + totalNumberOfProcesses: string; +}; + +export { + PublicType, + NewDataType, + NewTimeType, + RuleFormType, + HourRangesType, + EchartsDataType, + ReactiveArrType, + EchartsDataObjType, + EchartsParamsDataType +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/typeManagement.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/typeManagement.ts new file mode 100644 index 0000000..b378a91 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/typeManagement.ts @@ -0,0 +1,15 @@ +interface RuleFormType { + userName: string; + resourceType: string; + idcId: string; + instanceId: string; + dimension: string; + monitoringIndicators: string[]; + // hours: string; + // value1: string; + keyData: any; +}; + +export { + RuleFormType +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/utils/initStaticData.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/utils/initStaticData.ts new file mode 100644 index 0000000..799bf6e --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/utils/initStaticData.ts @@ -0,0 +1,430 @@ +/** + * @file + * @author +*/ +import {language} from 'utils/publicClass.ts'; +import {CurrencyType8} from '@utils/publicType'; +import {EchartsDataType, EchartsParamsDataType} from '../type'; + +type NewEchartsDataStaticType = Omit[] + +class InitStaticData { + static resourceData: string[] = [language.t('resourceMonitor.search.count.resourceType')]; + static dimensionsData: string[] = [language.t('resourceMonitor.search.count.dimensions')]; + static echartsData: NewEchartsDataStaticType = [ + { + typeVal: 'cpu', + id: 'main', + data: [], + type: language.t('monitorEcharts.echartsCount.cpu'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.cpu.util', + unit: '%', + hoverUnit: '%' + }, + { + typeVal: 'mem', + id: 'main2', + data: [], + type: language.t('monitorEcharts.echartsCount.mem'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.memory.util', + unit: '%', + hoverUnit: '%' + }, + { + typeVal: 'memUsage', + id: 'main3', + data: [], + type: language.t('monitorEcharts.echartsCount.memUsage'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.memory.used', + unit: 'GB', + hoverUnit: 'GB' + }, + { + typeVal: 'diskUsage', + id: 'main4', + data: [], + type: language.t('monitorEcharts.echartsCount.diskUsage'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.disk.used', + // metricName: 'bmp.disk.partition.used', + unit: 'GB', + hoverUnit: 'GB', + status: ['diskVal', 'mountpointVal'] + }, + { + typeVal: 'diskUsageRate', + id: 'main5', + data: [], + type: language.t('monitorEcharts.echartsCount.diskUsageRate'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.disk.util', + unit: '%', + hoverUnit: '%', + status: ['diskVal', 'mountpointVal'] + }, + { + typeVal: 'diskReadWriteTraffic', + id: 'main6', + data: [], + type: [ + language.t('monitorEcharts.echartsCount.diskReadTraffic'), + language.t('monitorEcharts.echartsCount.diskWriteTraffic') + ], + timeData: [], + aggregationMethod: 'avg', + metricName: ['bmp.disk.bytes.read', 'bmp.disk.bytes.write'], + // unit: 'M', + unit: 'custom', + // hoverUnit: 'Bps', + hoverUnit: '', + status: ['diskVal'] + }, + { + typeVal: 'diskReadWriteIOPS', + id: 'main7', + data: [], + type: [ + language.t('monitorEcharts.echartsCount.diskReadIOPS'), + language.t('monitorEcharts.echartsCount.diskWriteIOPS') + ], + timeData: [], + aggregationMethod: 'avg', + metricName: ['bmp.disk.counts.read', 'bmp.disk.counts.write'], + unit: '次/秒', + hoverUnit: '次/秒', + status: ['diskVal'] + }, + { + typeVal: 'netWorkBps', + id: 'main8', + data: [], + type: [ + language.t('monitorEcharts.echartsCount.netWorkIn'), + language.t('monitorEcharts.echartsCount.netWorkOut') + ], + timeData: [], + aggregationMethod: 'avg', + metricName: ['bmp.network.bytes.ingress', 'bmp.network.bytes.egress'], + // unit: 'K', + // M + // unit: '', + unit: 'custom', + // Kbps + hoverUnit: '', + status: ['nicVal'] + }, + { + typeVal: 'netWorkPackagesNum', + id: 'main9', + data: [], + type: [ + language.t('monitorEcharts.echartsCount.netWorkInPackageNum'), + language.t('monitorEcharts.echartsCount.netWorkOutPackageNum') + ], + timeData: [], + aggregationMethod: 'avg', + metricName: ['bmp.network.packets.ingress', 'bmp.network.packets.egress'], + unit: '个/秒', + hoverUnit: '个/秒', + status: ['nicVal'] + }, + { + typeVal: 'averageLoad1Min', + id: 'main10', + data: [], + type: language.t('monitorEcharts.echartsCount.averageLoad1Min'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.avg.load1', + unit: '', + hoverUnit: '' + }, + { + typeVal: 'averageLoad5Min', + id: 'main11', + data: [], + type: language.t('monitorEcharts.echartsCount.averageLoad5Min'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.avg.load5', + unit: '', + hoverUnit: '' + }, + { + typeVal: 'averageLoad15Min', + id: 'main12', + data: [], + type: language.t('monitorEcharts.echartsCount.averageLoad15Min'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.avg.load15', + unit: '', + hoverUnit: '' + }, + { + typeVal: 'totalTCPConnections', + id: 'main13', + data: [], + type: language.t('monitorEcharts.echartsCount.totalTCPConnections'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.tcp.connect.total', + unit: '个', + hoverUnit: '个' + }, + { + typeVal: 'normalTCPConnections', + id: 'main14', + data: [], + type: language.t('monitorEcharts.echartsCount.normalTCPConnections'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.tcp.connect.established', + unit: '个', + hoverUnit: '个' + }, + { + typeVal: 'totalNumberOfProcesses', + id: 'main15', + data: [], + type: language.t('monitorEcharts.echartsCount.totalNumberOfProcesses'), + timeData: [], + aggregationMethod: 'avg', + metricName: 'bmp.process.total', + unit: '个', + hoverUnit: '个' + } + ]; + + static radioData: CurrencyType8[] = [ + { + label: language.t('monitorEcharts.tabs.h1'), + value: '1min' + }, + { + label: language.t('monitorEcharts.tabs.h6'), + value: '5min' + }, + { + label: language.t('monitorEcharts.tabs.h12'), + value: '10 min' + }, + { + label: language.t('monitorEcharts.tabs.d1'), + value: '20 min' + }, + { + label: language.t('monitorEcharts.tabs.d3'), + value: '60min' + }, + { + label: language.t('monitorEcharts.tabs.d7'), + value: '120min' + }, + { + label: language.t('monitorEcharts.tabs.d14'), + value: '180min' + } + ]; + + static echartsParamsData: EchartsParamsDataType = [ + { + title: language.t('monitorEcharts.echartsCount.cpuUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'cpu', + id: 'main', + bigClickVal: { + type: 'cpu', + title: language.t('monitorEcharts.echartsCount.cpuUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.memUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'mem', + id: 'main2', + bigClickVal: { + type: 'mem', + title: language.t('monitorEcharts.echartsCount.memUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.memUsageUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'memUsage', + id: 'main3', + bigClickVal: { + type: 'memUsage', + title: language.t('monitorEcharts.echartsCount.memUsageUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.diskUsageUnit'), + showType: [ + language.t('monitorEcharts.radio.instance'), + language.t('monitorEcharts.radio.disk'), + language.t('monitorEcharts.radio.diskPartition') + ], + model: '', + type: 'diskUsage', + id: 'main4', + bigClickVal: { + type: 'diskUsage', + title: language.t('monitorEcharts.echartsCount.diskUsageUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.diskUsageRateUnit'), + showType: [ + language.t('monitorEcharts.radio.instance'), + language.t('monitorEcharts.radio.disk'), + language.t('monitorEcharts.radio.diskPartition') + ], + model: '', + type: 'diskUsageRate', + id: 'main5', + bigClickVal: { + type: 'diskUsageRate', + title: language.t('monitorEcharts.echartsCount.diskUsageRateUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.diskReadWriteTrafficUnit'), + showType: [language.t('monitorEcharts.radio.instance'), language.t('monitorEcharts.radio.disk')], + model: '', + type: 'diskReadWriteTraffic', + id: 'main6', + bigClickVal: { + type: 'diskReadWriteTraffic', + title: language.t('monitorEcharts.echartsCount.diskReadWriteTrafficUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.diskReadWriteIOPSUnit'), + showType: [language.t('monitorEcharts.radio.instance'), language.t('monitorEcharts.radio.disk')], + model: '', + type: 'diskReadWriteIOPS', + id: 'main7', + bigClickVal: { + type: 'diskReadWriteIOPS', + title: language.t('monitorEcharts.echartsCount.diskReadWriteIOPSUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.netWorkBpsUnit'), + showType: [language.t('monitorEcharts.radio.instance'), language.t('monitorEcharts.radio.netWorkInterface')], + model: '', + type: 'netWorkBps', + id: 'main8', + bigClickVal: { + type: 'netWorkBps', + title: language.t('monitorEcharts.echartsCount.netWorkBpsUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.netWorkPackagesNumUnit'), + showType: [language.t('monitorEcharts.radio.instance'), language.t('monitorEcharts.radio.netWorkInterface')], + model: '', + type: 'netWorkPackagesNum', + id: 'main9', + bigClickVal: { + type: 'netWorkPackagesNum', + title: language.t('monitorEcharts.echartsCount.netWorkPackagesNumUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.averageLoad1MinUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'averageLoad1Min', + id: 'main10', + bigClickVal: { + type: 'averageLoad1Min', + title: language.t('monitorEcharts.echartsCount.averageLoad1MinUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.averageLoad5MinUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'averageLoad5Min', + id: 'main11', + bigClickVal: { + type: 'averageLoad5Min', + title: language.t('monitorEcharts.echartsCount.averageLoad5MinUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.averageLoad15MinUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'averageLoad15Min', + id: 'main12', + bigClickVal: { + type: 'averageLoad15Min', + title: language.t('monitorEcharts.echartsCount.averageLoad15MinUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.totalTCPConnectionsUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'totalTCPConnections', + id: 'main13', + bigClickVal: { + type: 'totalTCPConnections', + title: language.t('monitorEcharts.echartsCount.totalTCPConnectionsUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.normalTCPConnectionsUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'normalTCPConnections', + id: 'main14', + bigClickVal: { + type: 'normalTCPConnections', + title: language.t('monitorEcharts.echartsCount.normalTCPConnectionsUnit'), + model: '' + } + }, + { + title: language.t('monitorEcharts.echartsCount.totalNumberOfProcessesUnit'), + showType: [language.t('monitorEcharts.radio.instance')], + model: '', + type: 'totalNumberOfProcesses', + id: 'main15', + bigClickVal: { + type: 'totalNumberOfProcesses', + title: language.t('monitorEcharts.echartsCount.totalNumberOfProcessesUnit'), + model: '' + } + } + ] +} + +export default InitStaticData; diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/utils/publicConfig.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/utils/publicConfig.ts new file mode 100644 index 0000000..570ee54 --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/utils/publicConfig.ts @@ -0,0 +1,54 @@ +/** + * @file + * @author +*/ +import {EchartsDataType, EchartsDataObjType} from '../type'; + +type ObjType = { + reactiveArr: { + echartsData: EchartsDataType[]; + }; + diskVal: { + value: string; + }; + mountpointVal: { + value: string; + }; + nicVal: { + value: string; + }; + getEcharts(arg0: EchartsDataObjType, arg1: string, arg2: { device: string; } | { device?: undefined; }): void; +} + +class PublicConfigOpt { + singleColor: string = '#108ee9'; + moreColor: string[] = [ + '#108ee9', + '#29d1d3' + ]; + + aggregationMethod: string[] = ['avg', 'max', 'min', 'sum']; + + clearEmptyObj = (deviceVal: T) => { + if (!Object.keys(deviceVal).length) { + Reflect.deleteProperty(deviceVal, 'device') + } + } + + smallBigSet = (obj: ObjType, val: string, type: string, value: string) => { + const newData = obj.reactiveArr.echartsData.filter((item: {typeVal: string}) => item.typeVal === val); + const {diskVal, mountpointVal, nicVal} = obj; + const deviceVal = diskVal.value ? {device: diskVal.value} : mountpointVal.value ? {device: mountpointVal.value} : nicVal.value ? {device: nicVal.value} : {}; + this.clearEmptyObj(deviceVal); + for (const key of newData) { + if (value?.length) { + key.aggregationMethod = value; + } + obj.getEcharts(key, type, deviceVal); + } + } +} + +const publicConfigOpt = new PublicConfigOpt(); + +export default publicConfigOpt; \ No newline at end of file diff --git a/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/utils/ruleForm.ts b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/utils/ruleForm.ts new file mode 100644 index 0000000..f25c2cd --- /dev/null +++ b/bmp-operation-web/src/views/inBandMonitoringManagement/resourceMonitor/utils/ruleForm.ts @@ -0,0 +1,27 @@ +/** + * @file + * @author +*/ +import {RuleFormType} from '../type'; + +class RuleFormOpt { + ruleForm: RuleFormType = reactive({ + cpu: 'avg', + mem: 'avg', + memUsage: 'avg', + diskUsage: 'avg', + diskUsageRate: 'avg', + diskReadWriteTraffic: 'avg', + diskReadWriteIOPS: 'avg', + netWorkBps: 'avg', + netWorkPackagesNum: 'avg', + averageLoad1Min: 'avg', + averageLoad5Min: 'avg', + averageLoad15Min: 'avg', + totalTCPConnections: 'avg', + normalTCPConnections: 'avg', + totalNumberOfProcesses: 'avg' + }) +} + +export default RuleFormOpt; diff --git a/bmp-operation-web/src/views/login/formSumbit/formSumbit.vue b/bmp-operation-web/src/views/login/formSumbit/formSumbit.vue new file mode 100644 index 0000000..3c293ad --- /dev/null +++ b/bmp-operation-web/src/views/login/formSumbit/formSumbit.vue @@ -0,0 +1,110 @@ + + diff --git a/bmp-operation-web/src/views/login/formSumbit/loginOperate.ts b/bmp-operation-web/src/views/login/formSumbit/loginOperate.ts new file mode 100644 index 0000000..dc9c544 --- /dev/null +++ b/bmp-operation-web/src/views/login/formSumbit/loginOperate.ts @@ -0,0 +1,149 @@ +/** + * @file + * @author +*/ + +import {userInfoAPI} from 'api/userCenter/request.ts'; +import {encrypt, customTip} from 'utils/index.ts'; +import {CurrencyType, RuleFormRefType} from '@utils/publicType'; +import store from 'store/index.ts'; +import {AxiosError} from 'axios'; +import {locationItem, CurrentInstance} from 'utils/publicClass.ts'; +import {CheckType, UserPurviewType} from '../typeManagement'; + +interface CheckType1 extends CheckType { + ruleFormRef: Ref; +}; + +// 登录操作 +class LoginOperate { + userPurview: UserPurviewType = store.userPurviewInfo(); + errMessage: Ref = ref(''); + // 加载态-用于登录请求时,按钮的加载态 + isLoading: Ref = ref(false); + ruleFormCheck: CheckType1; + loginInfo: {email: string} = store.loginInfo; + router: any; + instanceProxy = new CurrentInstance().proxy; + + // 构造器 + constructor (ruleFormCheck: CheckType1, router: any) { + this.router = router; + this.ruleFormCheck = ruleFormCheck; + document.onkeyup = (event: {keyCode: number;}) => { + event.keyCode === 13 && this.loginOperate(); + }; + watchEffect(() => { + this.loadingKeyDownStatus(); + }) + }; + + /** + * 登录操作,校验输入项 + */ + loginOperate = async (): Promise => { + await nextTick(() => { + this.ruleFormCheck.ruleFormRef.value!.validate((valid: boolean) => { + // 输入项符合条件 + this.errMessage.value = ''; + if (valid) { + this.isLoading.value = true; + this.#requestLogin(); + } + }); + }); + }; + + /** + * 请求登录接口 + */ + #requestLogin = async () => { + try { + const params = { + username: this.ruleFormCheck.ruleForm.loginUserName, + password: encrypt(this.ruleFormCheck.ruleForm.loginPassword) + }; + const loginApi = await this.instanceProxy.$loginUserApi.loginAPI(params); + const status: boolean = (loginApi?.data?.result?.success)?? false; + status && this.#loginDealWithResponse(); + } + catch (e) { + this.#loginDealWithCatch(e as AxiosError); + } + }; + + #loginDealWithResponse = () => { + const defaultPath: string = this.#routerUrl('idcList'); + const pathUrl: string = locationItem.cookie.get('path_url')?? ''; + this.getUserInfo(pathUrl || window.btoa(defaultPath)); + }; + + #loginDealWithCatch = (e: AxiosError) => { + const err = e as AxiosError; + if ((err.code as unknown | number) === 400) { + this.loadingKeyDownStatus(); + this.errMessage.value = err.message; + return; + } + customTip('error', err.message, 1000, () => this.loadingKeyDownStatus()); + }; + + /** + * 获取用户信息 + * @param {string} pathUrl 页面地址,登出前最后一次停留的地址 + * @param {string} loginUserName 登录用户名 + */ + getUserInfo = (pathUrl: string) => { + userInfoAPI({}) + .then(({data}: {data: {result: CurrencyType}}) => { + if (data?.result && Object.keys(data.result).length) { + // cookie获取存储的语言 + locationItem.cookie.set('X-Jdcloud-Language', data.result.language); + this.loginInfo.email = window.btoa(data.result.email); + const userName: string = data.result.userName?? ''; + const email: string = data.result.email?? ''; + // const userId = data.result.userId?? ''; + localStorage.setItem('userName', window.btoa(userName)); + localStorage.setItem('email', window.btoa(email)); + // 页面地址加密 + pathUrl = window.atob(pathUrl); + const loginPath: string = this.#routerUrl('login'); + const idcListPath: string = this.#routerUrl('idcList'); + pathUrl === loginPath ? idcListPath : pathUrl; + // const licenseExist = data.result.licenseExist; + this.userPurview.getUserPurview(this.instanceProxy.$loginUserApi) + .finally(() => { + this.router.push(pathUrl); + // loading false + // this.loadingKeyDownStatus(); + // if (licenseExist) { + // // 跳转页面 + // // window.open(pathUrl, '_self'); + // this.router.push(pathUrl); + // return; + // } + // const cardPath = this.#routerUrl('license'); + // // 跳转页面 + // // window.open(cardPath, '_self'); + // this.router.push(cardPath); + }) + } + }) + .catch(({message}: {message: string}) => { + customTip('error', message, 1000, () => this.loadingKeyDownStatus()); + }) + }; + + #routerUrl = (type: string): string => { + return this.instanceProxy!.$defInfo.routerPath(type) as unknown as string; + }; + + /** + * 登录失败-异常后的操作状态 + */ + loadingKeyDownStatus = () => { + this.isLoading.value = false; + }; +}; + +export default LoginOperate; diff --git a/bmp-operation-web/src/views/login/formSumbit/ruleFormCheck.ts b/bmp-operation-web/src/views/login/formSumbit/ruleFormCheck.ts new file mode 100644 index 0000000..c805f5e --- /dev/null +++ b/bmp-operation-web/src/views/login/formSumbit/ruleFormCheck.ts @@ -0,0 +1,62 @@ +import {language} from 'utils/publicClass.ts'; +import {RuleFormRefType} from '@utils/publicType'; +import {RuleFormType, RulesType} from '../typeManagement'; + +/** + * 表单验证 +*/ +class RuleFormCheck { + // 表单ref + ruleFormRef: Ref = ref(); + // 密码type切换 + passwordType: Ref = ref('password'); + // 表单输入项 + ruleForm: RuleFormType = reactive({ + loginUserName: '', // 用户登录账号 + loginPassword: '' // 用户登录密码 + }); + // 规则类型 + rules: RulesType = reactive({ + loginUserName: [ // 用户登录账号 + { + required: true, + message: language.t('login.formSubmit.toolTip'), + trigger: 'click' + } + ], + loginPassword: [ // 用户登录密码 + { + required: true, + message: language.t('login.formSubmit.toolTip'), + trigger: 'click' + } + ] + }); + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: RuleFormRefType}): void => { + this.ruleFormRef.value = formEl.value; + }; + + /** + * 清空输入项 + * @param {string} value 输入框输入的值 + */ + clearInput = (value: string) => { + (this.ruleForm[`${value}` as keyof typeof this.ruleForm] as string) = ''; + }; + + /** + * 密码是否明文显示,状态切换 + * @param {string} type 密码明文显示的type值 + * @return {string} passwordType.value 密码明文显示的type值 + */ + passwordStatusChange = (type: string): string => { + return this.passwordType.value = type; + }; +}; + +export default RuleFormCheck; diff --git a/bmp-operation-web/src/views/login/login.scss b/bmp-operation-web/src/views/login/login.scss new file mode 100644 index 0000000..d6b9571 --- /dev/null +++ b/bmp-operation-web/src/views/login/login.scss @@ -0,0 +1,76 @@ +@import '@/assets/css/communal'; + +.operate-content { + width: $percentageWidth; + height: $percentageHeight; + display: flex; + flex-direction: column; + justify-content: space-between; + /* 禁止用户选择 */ + user-select: none; + -ms-user-select: none; + -moz-user-select: none; + overflow-y: auto; + position: relative; + + &-header { + display: flex; + align-items: center; + justify-content: flex-start; + margin: 29px 0px 30px 57px; + } + + &-img { + width: 45px; + height: 45px; + margin-right: 20px; + } + + &-title { + font-size: 26px; + color: #333; + font-weight: 500; + } + + .operate-login { + width: 556px; + background: #fff; + box-shadow: 0 1px 6px 0 rgba(153, 153, 153, 0.50); + border-radius: 10px; + margin: 10px auto 30px; + display: flex; + flex-direction: column; + min-height: 370px; + + &-button { + width: 344px; + height: 40px; + // background: $background1; + border-radius: 4px; + margin: 30px auto 0; + } + + &-title { + font-size: 16px; + color: #666; + text-align: center; + font-weight: 400; + margin-top: 36px; + } + } + + .error-tooltip { + color: #f56c6c; + margin: -10px 0; + } + + .operate-footer { + font-size: 12px; + color: #666; + text-align: center; + font-weight: $fontLargeWeight; + display: flex; + flex-direction: column; + margin-bottom: 26px; + } +} diff --git a/bmp-operation-web/src/views/login/login.vue b/bmp-operation-web/src/views/login/login.vue new file mode 100644 index 0000000..608a2fb --- /dev/null +++ b/bmp-operation-web/src/views/login/login.vue @@ -0,0 +1,23 @@ + + + + diff --git a/bmp-operation-web/src/views/login/page.ts b/bmp-operation-web/src/views/login/page.ts new file mode 100644 index 0000000..9e60b0c --- /dev/null +++ b/bmp-operation-web/src/views/login/page.ts @@ -0,0 +1,7 @@ +const LoginPage = () => import(/* webpackChunkName: "Login" */ './login.vue'); + +export default { + name: 'Login', + path: '/Login/login', + component: LoginPage +}; diff --git a/bmp-operation-web/src/views/login/typeManagement.ts b/bmp-operation-web/src/views/login/typeManagement.ts new file mode 100644 index 0000000..d44d5d5 --- /dev/null +++ b/bmp-operation-web/src/views/login/typeManagement.ts @@ -0,0 +1,45 @@ +// 登录返回的类 +type LoginResponseType = {data: {result: {success: boolean;}}, loginUserName: string}; + +// 用户权限类 +type UserPurviewType = {getUserPurview(arg0: any): Promise;} +/** + * 用户输入的类 +*/ +type UserInfoType = { + required: boolean; + message: string; + trigger: string; +}; + +type key = 'loginUserName' | 'loginPassword'; + +/** + * 表单提交类 +*/ +type RuleFormType = { + [k in key]: string; +}; + +/** + * 表单规则类 +*/ +interface RulesType { + loginUserName: UserInfoType[]; + loginPassword: UserInfoType[]; +}; + +type CheckType = { + ruleForm: { + loginUserName: string; + loginPassword: string; + }; +}; + +export { + CheckType, + RulesType, + RuleFormType, + UserPurviewType, + LoginResponseType +}; diff --git a/bmp-operation-web/src/views/messageNotification/messageDetail/index.scss b/bmp-operation-web/src/views/messageNotification/messageDetail/index.scss new file mode 100644 index 0000000..adef676 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/messageDetail/index.scss @@ -0,0 +1,66 @@ +.message-detail { + .operate-management-count { + padding: 0 29px !important; + } + + .header-left-icon { + margin: 0 0 0 14px; + } + .delete-error { + .title { + font-size: $fontSize2; + color: $color14; + font-weight: $fontLargeWeight; + } + + .content { + @include display-align(center); + margin-top: 20px; + margin-left: 5px; + } + + .count { + font-size: 12px; + color: $defaultColor; + + span { + &:first-child { + color: $color14; + } + } + } + + .renew-immediately { + @include active-style($fontSize); + } + + .desc { + margin: 20px 0 12px; + @include size-weight-color($fontSize, $fontSmallWeight, $defaultColor); + } + + .el-table__empty-block { + background: $whiteBackground; + } + + .opt-count-detail { + margin: 32px 0 12px; + @include size-weight-color($fontSize, $fontSmallWeight, $defaultColor); + } + } + + .footer-opt { + @include display-align(center); + @extend %justify-center; + margin-top: 70px; + + .btn { + width: 98px; + height: 36px; + + &:nth-child(2) { + margin-left: 32px; + } + } + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/messageNotification/messageDetail/messageDetail.vue b/bmp-operation-web/src/views/messageNotification/messageDetail/messageDetail.vue new file mode 100644 index 0000000..71bd667 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/messageDetail/messageDetail.vue @@ -0,0 +1,135 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/messageNotification/messageDetail/msgDetail.ts b/bmp-operation-web/src/views/messageNotification/messageDetail/msgDetail.ts new file mode 100644 index 0000000..273d307 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/messageDetail/msgDetail.ts @@ -0,0 +1,246 @@ +/** + * @file + * @author +*/ + +import {AxiosError} from 'axios'; +import {getDateMinutes, methodsTotal, msgTip} from 'utils/index.ts'; +import {RouterOperate, CurrentInstance, language} from 'utils/publicClass.ts'; +import MessageStaticData from 'staticData/message/index.ts'; +import AllStaticData from 'staticData/staticData.ts'; + +class MessageDetailOpt { + instanceProxy = new CurrentInstance().proxy; + path: string = ''; + router; + code: Ref = ref(0); + monitorCode: Ref = ref(0); + msgId: Ref = ref(''); + activeType: Ref = ref(''); + newEndTime: Ref = ref(''); + activeDate: Ref = ref(''); + name: Ref = ref(''); + userName: string = localStorage?.getItem('userName')?? ''; + nextId: Ref = ref(''); + isLoading: Ref = ref(true); + prevId: Ref = ref(''); + reactiveArr = reactive({ + tableData: [ + { + messageSubType: '', + faultType: '', + instanceName: '', + sn: '', + instanceId: '', + idcName: '', + deviceId: '', + content: '' + } + ] + }); + btnData: {id: string; text: string}[] = MessageStaticData.btnData; + templateData: {prop: string; label: string; hasShow: string; hasTime: boolean; hasOther: boolean;}[] = MessageStaticData.templateData; + instanceTemplateData: {prop: string; label: string;}[] = MessageStaticData.instanceTemplateData; + + constructor() { + const obj = localStorage?.getItem('messageInfo')?? ''; + this.path = this.instanceProxy.$defInfo.routerPath('myMessage'); + this.router = new RouterOperate(this.path); + if (!obj?.length) { + this.jumpRouter(this.path); + return; + } + const {id, type, newDate, endTime} = JSON.parse(decodeURIComponent(obj)); + this.activeType.value = type; + this.msgId.value = id; + this.newEndTime.value = endTime; + this.activeDate.value = newDate; + this.name.value = this.userName ? window.atob(this.userName) : ''; + this.init(); + this.readMessageClick(); + onUnmounted(() => localStorage.removeItem('messageInfo')); + } + + readMessageClick = async () => { + await this.instanceProxy.$messageApi.doReadAPI({messageIds: [this.msgId.value]}); + } + + setIdcInfo = () => { + const {idcName} = this.#getTableData(); + return `${idcName}${language.t('messageDetail.optTips.instance')}`; + } + + inMonitor = () => { + const {instanceName, instanceId} = this.#getTableData(); + return `${instanceName}/${instanceId}` + } + + monitorCount = () => { + const {messageSubType, content} = this.#getTableData(); + return `${language.t('messageDetail.optTips.current')}${messageSubType}-${content}` + } + + setTitle = () => { + const {activeType, activeDate} = this; + const {messageSubType, faultType} = this.#getTableData(); + const obj = { + 'optMessage': `${messageSubType?.length ? '【' + messageSubType + `】${language.t('messageDetail.failureNotification')}` : '--'}`, + 'unexpiredExpired': this.setDays(activeDate.value), + 'faultMessage': `${faultType?.length ? '【' + faultType + `】${language.t('messageDetail.remind')}` : '--'}`, + 'inbondAlert': `${messageSubType?.length ? '【' + messageSubType + `】${language.t('messageDetail.alarmTips')}` : '--'}` + }; + return (obj[`${activeType.value}` as keyof typeof obj] as string)?? ''; + } + + setCount = () => { + const {activeType, name} = this; + const type = new Map([ + // 用户${name.value}您好!操作失败,请重新操作或联系管理员处理 + ['optMessage', `${language.t('messageDetail.tip', [name.value])}`], + ['unexpiredExpired', this.setActiveDate()] + ]); + // `用户${name.value}您好!` + return type.get(activeType.value)?? `${language.t('messageDetail.tip0', [name.value])}`; + } + + jumpRouter = (path: string) => { + this.router.router.push(path); + localStorage.removeItem('messageInfo'); + } + + setActiveDate = () => { + const {name, activeDate, newEndTime} = this; + const type = new Map([ + ['0', `${language.t('messageDetail.tip0', [name.value])}${language.t('messageDetail.tip1')}${language.t('messageDetail.tip11')}${language.t('messageDetail.tip2')}`] + ]); + return type.get(activeDate.value)?? ` + ${language.t('messageDetail.tip0', [name.value])} + ${language.t('messageDetail.tip3', [activeDate.value, getDateMinutes(newEndTime.value), getDateMinutes(newEndTime.value)])} + `; + } + + setDesc = () => { + const {activeType} = this; + const type = new Map([ + ['optMessage', language.t('messageDetail.tip4')], + ['unexpiredExpired', language.t('messageDetail.tip5')], + ['inbondAlert', language.t('messageDetail.tip7')] + ]); + return type.get(activeType.value)?? language.t('messageDetail.tip6'); + } + + setName = () => { + const {activeDate, activeType} = this; + const {messageSubType, faultType, instanceName, sn, instanceId} = this.#getTableData(); + const obj = { + 'optMessage': `${messageSubType?.length ? '【' + messageSubType + `】${language.t('messageDetail.failureNotification')}${instanceName ? '(' + instanceName + '/' + sn + ')' : ''}${!instanceName ? '(' + sn + ')' : ''}` : '--'}`, + 'faultMessage': `${faultType?.length ? '【' + faultType + '】' + `${language.t('messageDetail.remind')}${sn ? '(' + sn + ')' : ''}` : '--'}`, + 'unexpiredExpired': this.setDays(activeDate.value), + 'inbondAlert': `${messageSubType?.length ? '【' + messageSubType + `】${language.t('messageDetail.alarmTips')}${instanceName ? '(' + instanceName + '/' + instanceId + ')' : ''}${!instanceName ? '(' + instanceId + ')' : ''}` : '--'}`, + } + return obj[`${activeType.value}` as keyof typeof obj]; + } + + jumpDeviceDetail = (path: string) => { + const {sn, deviceId} = this.#getTableData(); + const query = `?sn=${sn}&type=performanceMonitoring&deviceId=${deviceId}`; + this.router.router.push(`${path}${query}`); + } + + #getTableData = () => { + return this.reactiveArr.tableData[0]; + } + + setDays = (newDate: string) => { + if (Object.is(newDate, null)) return ''; + const obj = new Map([ + ['90', language.t('messageDetail.day90')], + ['30', language.t('messageDetail.day30')], + ['15', language.t('messageDetail.day15')], + ['0', language.t('messageDetail.expired')] + ]); + return obj.get(newDate)?? ''; + } + + disabledSet = (id: string) => { + const that = this; + return !((this[`${id}` as keyof typeof that] as any).value !== ''); + } + + preNextClick = (id: string) => { + const that = this; + this.msgId.value = (this[`${id}` as keyof typeof that] as any).value; + this.init(); + this.readMessageClick(); + } + + preClick = () => { + this.msgId.value = this.prevId.value; + this.init(); + this.readMessageClick(); + } + + nextClick = () => { + this.msgId.value = this.nextId.value; + this.init(); + this.readMessageClick(); + } + + setStatus = (time: number | undefined) => { + if ([null, undefined].includes((time as undefined))) return ''; + const date: number = new Date().getTime() / 1000; + if ((time as number) < date) { + return language.t('messageDetail.status.expired'); + } + return language.t('messageDetail.status.effective'); + } + + getQueryType = (messageType: string) => { + const type = new Map([ + [language.t('messageDetail.faultMessages'), 'faultMessage'], + [language.t('messageDetail.systemMessages'), 'unexpiredExpired'], + [language.t('messageDetail.operationMessages'), 'optMessage'], + [language.t('messageDetail.inbondAlert'), 'inbondAlert'] + ]); + return type.get(messageType) + } + + init = async () => { + this.isLoading.value = true; + try { + const res = await this.instanceProxy.$messageApi.messageByIdAPI({messageId: this.msgId.value}); + if (res?.data?.result?.message) { + const {message, nextMessageId, prevMessageId} = methodsTotal.lineConverting(res.data.result); + this.nextId.value = nextMessageId; + this.prevId.value = prevMessageId; + this.activeType.value = (this.getQueryType(message.messageType) as string); + this.activeDate.value = message.detail; + this.newEndTime.value = message.licenseEndTime; + this.reactiveArr.tableData = [message]; + const obj = { + type: (this.getQueryType(message.messageType) as string), + id: this.msgId.value, + newDate: message.detail + } + localStorage.setItem('messageInfo', encodeURIComponent(JSON.stringify(obj))); + // if (Object.is(this.activeType.value, 'inbondAlert')) { + // this.getMonitor(); + // } + return; + } + } + catch (e) { + const err = e as AxiosError; + if (AllStaticData.noFoundData.includes(err?.message)) { + this.jumpRouter(this.path); + return; + } + err?.message && msgTip.error(err.message); + } + finally { + this.isLoading.value = false; + } + } +} + +export default MessageDetailOpt; diff --git a/bmp-operation-web/src/views/messageNotification/messageDetail/page.ts b/bmp-operation-web/src/views/messageNotification/messageDetail/page.ts new file mode 100644 index 0000000..a67d936 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/messageDetail/page.ts @@ -0,0 +1,10 @@ +const MessageDetail = () => import(/* webpackChunkName: "MessageDetail" */ './messageDetail.vue'); + +export default { + path: '/MessageNotification/messageDetail', + name: 'MessageDetail', + component: MessageDetail, + meta: { + type: 'messageDetail' + } +}; diff --git a/bmp-operation-web/src/views/messageNotification/messageSettings/index.scss b/bmp-operation-web/src/views/messageNotification/messageSettings/index.scss new file mode 100644 index 0000000..a017c3b --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/messageSettings/index.scss @@ -0,0 +1,111 @@ +.message-settings { + margin-top: 100px; + + .email-push { + margin-left: 48px; + font-size: 12px; + margin-bottom: 18px; + } + + .tooltip-img { + width: 16px; + height: 16px; + margin-left: 5px; + margin-right: 60px; + } + + .footer-opt { + display: flex; + align-items: center; + // position: relative; + padding-top: 35px; + + .is-pass { + font-family: PingFangSC-Regular; + font-size: 12px; + margin-left: 16px; + color: #43b561; + } + + // .set-loading { + // position: absolute; + // left: 210px; + // } + + .info { + font-size: 12px; + color: #108ee9; + cursor: pointer; + } + + .default-info { + font-size: 12px; + color: #999; + cursor: no-drop; + } + + .tooltip-img { + margin-top: -10px; + } + } + + .en-test-email { + .tooltip-img { + position: absolute; + left: -46px; + top: 0; + } + } + .test-email { + .tooltip-img { + position: absolute; + left: -82px; + top: 0; + } + } + + .form { + padding: 0 12px 31px; + border-bottom: 1px solid #f0f0f0; + } + + :deep(.el-form-item__label) { + margin-left: 48px; + + &::before { + display: none; + } + } + + .user-save { + width: 130px; + height: 36px; + border-radius: 5px; + // position: absolute; + margin-left: 60px; + font-size: $fontSize; + // margin-top: 35px; + } + + .set-empty { + margin-bottom: 40px !important; + } + + :deep(.el-input__inner) { + width: 400px; + height: 36px; + border-radius: 5px; + } + + :deep(.el-form-item__error) { + margin-top: 6px; + } + + .error-color-tip { + color: #f56c6c; + } + + .password-tip { + color: $color7; + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/messageNotification/messageSettings/messageSettings.vue b/bmp-operation-web/src/views/messageNotification/messageSettings/messageSettings.vue new file mode 100644 index 0000000..ac34626 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/messageSettings/messageSettings.vue @@ -0,0 +1,168 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/messageNotification/messageSettings/page.ts b/bmp-operation-web/src/views/messageNotification/messageSettings/page.ts new file mode 100644 index 0000000..5a6d30c --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/messageSettings/page.ts @@ -0,0 +1,10 @@ +const MessageSettings = () => import(/* webpackChunkName: "MessageSettings" */ './messageSettings.vue'); + +export default { + path: '/MessageNotification/messageSettings', + name: 'MessageSettings', + component: MessageSettings, + meta: { + type: 'messageSettings' + } +}; diff --git a/bmp-operation-web/src/views/messageNotification/messageSettings/pushEmail/pushEmail.ts b/bmp-operation-web/src/views/messageNotification/messageSettings/pushEmail/pushEmail.ts new file mode 100644 index 0000000..3fa66c5 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/messageSettings/pushEmail/pushEmail.ts @@ -0,0 +1,38 @@ +class PushEmailOpt { + emailPushDiaLog: Ref = ref(false); + operate: Ref = ref(''); + switchLoading: Ref = ref(false); + emailPush: Ref = ref(false); + fn; + + constructor(emailPush: boolean, fn: Function) { + this.emailPush.value = emailPush; + this.fn = fn; + } + + switchBeforeChange = () => { + this.switchLoading.value = true; + return new Promise(() => { + this.emailPushDiaLog.value = true; + }) + } + + cancel = () => { + this.switchLoading.value = false; + this.emailPushDiaLog.value = false; + } + + sure = () => { + this.switchLoading.value = false; + this.emailPushDiaLog.value = false; + this.emailPush.value = !this.emailPush.value; + this.fn(); + } + + errorClick = () => { + this.switchLoading.value = false; + this.emailPushDiaLog.value = false; + } +} + +export default PushEmailOpt; diff --git a/bmp-operation-web/src/views/messageNotification/messageSettings/pushEmail/pushEmailInfo.vue b/bmp-operation-web/src/views/messageNotification/messageSettings/pushEmail/pushEmailInfo.vue new file mode 100644 index 0000000..2d33667 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/messageSettings/pushEmail/pushEmailInfo.vue @@ -0,0 +1,22 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/messageNotification/messageSettings/utils/messageSet.ts b/bmp-operation-web/src/views/messageNotification/messageSettings/utils/messageSet.ts new file mode 100644 index 0000000..6b77cb0 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/messageSettings/utils/messageSet.ts @@ -0,0 +1,189 @@ +/** + * @file + * @author +*/ + +import {RuleFormRefType} from '@utils/publicType'; +import {inspectuserPurview, CurrentInstance, language} from 'utils/publicClass.ts'; +import {useRouter} from 'vue-router'; +import {methodsTotal, msgTip} from 'utils/index.ts'; + +type RuleFormType = { + emailPush: boolean; + ipAddress: string; + port: string; + emailAddress: string; + emailPassword: string; + testEmail: string; +} + +class MessageSetOpt { + pageLoading: Ref = ref(true); + isShowLoading: Ref = ref(false); + isLoading: Ref = ref(false); + // 表单ref + ruleFormRef: Ref = ref(); + // 表单项 + ruleForm = reactive({ + emailPush: false, + ipAddress: '', + port: '', + emailAddress: '', + emailPassword: '', + testEmail: '' + }); + disabledStatus: Ref = ref(true); + router = useRouter(); + // 规则 + rules = reactive({ + ipAddress: [ + { + required: true, + trigger: 'blur', + validator: '' + } + ], + port: [ + { + required: true, + trigger: 'blur', + validator: '' + } + ], + emailAddress: [ + { + required: true, + trigger: 'blur', + validator: '' + } + ], + emailPassword: [ + { + required: true, + trigger: 'blur', + validator: '' + } + ], + testEmail: [ + { + required: true, + trigger: 'blur', + validator: '' + } + ] + }); + validateInfo: Ref = ref(''); + regExpCheck: any; + instanceProxy = new CurrentInstance().proxy; + fn; + + constructor (regExpCheck: any, fn: Function) { + this.fn = fn; + const path: string = this.instanceProxy.$defInfo.routerPath('idcList'); + inspectuserPurview.inspectuserPurview() + .then(() => { + this.regExpCheck = regExpCheck; + this.rules['ipAddress'][0].validator = regExpCheck.ipAddressCheck; + this.rules['port'][0].validator = regExpCheck.portCheck; + this.rules['emailAddress'][0].validator = regExpCheck.emailAddressCheck; + this.rules['emailPassword'][0].validator = regExpCheck.emailPasswordCheck; + this.rules['testEmail'][0].validator = regExpCheck.testEmailCheck; + this.watchForm(); + this.getDescribeMail(); + }) + .catch(() => { + this.router.push(path); + }); + }; + + getDescribeMail = async () => { + this.pageLoading.value = true; + try { + const res = await this.instanceProxy.$messageApi.describeMailAPI({}); + const {result} = methodsTotal.lineConverting(res.data); + const {isPush, serverPort, adminAddr, adminPass, serverAddr, isPass, to} = result; + this.ruleForm.emailPush = this.#setPush(isPush); + this.fn(this.ruleForm.emailPush); + this.ruleForm.port = serverPort; + this.ruleForm.emailAddress = adminAddr; + this.ruleForm.emailPassword = adminPass; + this.ruleForm.ipAddress = serverAddr; + this.validateInfo.value = this.#setValidate(isPass) as string; + this.ruleForm.testEmail = to; + } + finally { + this.pageLoading.value = false; + } + } + + #setPush = (type: string): boolean => { + const obj = { + '0': false, + '1': true + }; + return (obj[`${type}` as keyof typeof obj] as boolean); + } + #setValidate = (type: string) => { + const info = new Map([ + ['0', ''], + ['1', language.t('messageSettings.footer.success')] + ]); + return info.get(type); + } + + watchForm = () => { + watch(() => this.ruleForm, (newValue) => { + const val = Object.values(newValue).some(item => item === ''); + this.disabledStatus.value = newValue.emailPush ? val : true; + }, { + deep: true + }) + } + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: RuleFormRefType}): void => { + this.ruleFormRef.value = formEl.value; + }; + + reviseClick = async () => { + if (this.disabledStatus.value || this.isShowLoading.value) return; + await nextTick(() => { + this.ruleFormRef.value!.validate((valid: boolean) => { + // 输入符合条件后才可以继续后续操作 + if (valid) { + this.isLoading.value = true; + this.isShowLoading.value = true; + this.dialMail(); + } + }); + }); + }; + + dialMail = async () => { + const {emailPush, ipAddress, port, emailAddress, emailPassword, testEmail} = this.ruleForm; + const params = methodsTotal.toLine({ + serverAddr: ipAddress, + serverPort: port, + adminAddr: emailAddress, + adminPass: emailPassword, + isPush: emailPush ? '1' : '0', + to: testEmail + }) + try { + const res = await this.instanceProxy.$messageApi.dialMailAPI(params); + if (res?.data?.result?.success) { + msgTip.success(language.t('operate.success')); + this.getDescribeMail(); + } + } + finally { + this.isShowLoading.value = false; + this.isLoading.value = false; + } + } +}; + +export default MessageSetOpt; diff --git a/bmp-operation-web/src/views/messageNotification/messageSettings/utils/regExpReg.ts b/bmp-operation-web/src/views/messageNotification/messageSettings/utils/regExpReg.ts new file mode 100644 index 0000000..e88c18f --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/messageSettings/utils/regExpReg.ts @@ -0,0 +1,165 @@ +// import RegularContent from 'utils/regular.ts'; +import {language} from 'utils/publicClass.ts'; +import RegularContent from 'utils/regular.ts'; + +class RegExpCheck { + emailPasswordFlag: Ref = ref(false); + emailAddressFlag: Ref = ref(false); + portFlag: Ref = ref(false); + ipAddressFlag: Ref = ref(false); + testEmailFlag: Ref = ref(false); + + ipAddressCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + this.ipAddressFlag.value = true; + const ipAddressArr = [ + [ + (value: string) => !value?.length, + () => { + callback(new Error(language.t('messageSettings.empty.ipAddress'))); + } + ], + [ + (value: string) => value, + () => { + this.ipAddressFlag.value = false; + callback(); + } + ] + ]; + for (const key of ipAddressArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + portCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + this.portFlag.value = true; + const portArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t('messageSettings.empty.port'))) + ], + [ + (value: string) => (!RegularContent.NumReg.test(value) || Number(value) >= 65536), + () => callback(new Error(language.t('messageSettings.errorTip.port'))) + ], + [ + (value: string) => value, + () => { + this.portFlag.value = false; + callback(); + } + ] + ]; + for (const key of portArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + emailAddressCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + this.emailAddressFlag.value = true; + const emailAddressArr = [ + [ + (value: string) => !value?.length, + () => { + callback(new Error(language.t('messageSettings.empty.emailAddress'))); + } + ], + [ + (value: string) => !RegularContent.emailReg.test(value), + () => callback(new Error(language.t('messageSettings.errorTip.emailAddress'))) + ], + [ + (value: string) => value, + () => { + this.emailAddressFlag.value = false; + callback(); + } + ] + ]; + for (const key of emailAddressArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + testEmailCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + this.testEmailFlag.value = true; + const testEmailArr = [ + [ + (value: string) => !value?.length, + () => { + callback(new Error(language.t('messageSettings.empty.testEmail'))); + } + ], + [ + (value: string) => !(RegularContent.emailReg.test(value)), + () => callback(new Error(language.t('messageSettings.errorTip.testEmail'))) + ], + // [ + // (value: string) => !(RegularContent.moreEmailReg.test(value)), + // () => callback(new Error(language.t('messageSettings.errorTip.testEmail'))) + // ], + [ + (value: string) => value, + () => { + this.testEmailFlag.value = false; + callback(); + } + ] + ]; + for (const key of testEmailArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + emailPasswordCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + this.emailPasswordFlag.value = true; + const emailPasswordArr = [ + [ + (value: string) => !value?.length, + () => { + callback(new Error(language.t('messageSettings.empty.emailPassword'))); + } + ], + // [ + // (value: string) => !RegularContent.passwordReg.test(value), + // () => callback(new Error(language.t('messageSettings.errorTip.emailPassword'))) + // ], + [ + (value: string) => value, + () => { + this.emailPasswordFlag.value = false; + callback(); + } + ] + ]; + for (const key of emailPasswordArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + resetFlag = () => { + const {emailPasswordFlag, emailAddressFlag, portFlag, ipAddressFlag, testEmailFlag} = this; + emailPasswordFlag.value = false; + emailAddressFlag.value = false; + portFlag.value = false; + ipAddressFlag.value = false; + testEmailFlag.value = false; + } +}; + +export default RegExpCheck; diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/custom/custom.ts b/bmp-operation-web/src/views/messageNotification/myMessage/custom/custom.ts new file mode 100644 index 0000000..4185f9c --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/custom/custom.ts @@ -0,0 +1,13 @@ +/** + * @file + * @author +*/ + +// import {methodsTotal} from 'utils/index.ts'; +import useCustom from 'hooks/custom/useCustom.ts'; + +// const name: string = methodsTotal.humpConversion('messageList'); + +const customOperate = useCustom('messageList').info; + +export default customOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/custom/customList.vue b/bmp-operation-web/src/views/messageNotification/myMessage/custom/customList.vue new file mode 100644 index 0000000..ff6e9b4 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/custom/customList.vue @@ -0,0 +1,9 @@ + + diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/export/export.ts b/bmp-operation-web/src/views/messageNotification/myMessage/export/export.ts new file mode 100644 index 0000000..9165a44 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/export/export.ts @@ -0,0 +1,56 @@ +/** + * @file + * @author zhangjingyuan02 +*/ + +import store from 'store/index.ts'; +import {ExportDataOperate, CurrentInstance} from 'utils/publicClass.ts'; + +class ExportFilterData { + // 是否导出数据 + hasExportData: Ref = ref(true); + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + // list: any; + search: { + searchParams: {}, + radioGroup: {} + }; + filter: { + filterParams: {} + }; + proxy = new CurrentInstance().proxy; + + constructor(search: { + searchParams: {}, + radioGroup: {} + }, filter: { + filterParams: {} + }) { + // this.list = list; + this.search = search; + this.filter = filter; + }; + + exportData = (that: never) => { + new ExportDataOperate(this.proxy.$messageApi.messageExportAPI, {}, 'message_list').exportData(that); + }; + + /** + * 参数处理 + */ + paramsProcessing = (that: never) => { + this.filterEmptyInfo.deleteEmtpyData({...this.filter.filterParams, ...this.search.searchParams, ...this.search.radioGroup}); + new ExportDataOperate(this.proxy.$messageApi.messageExportAPI, { + ...this.search.searchParams, + ...this.filter.filterParams, + ...this.search.radioGroup + }, 'message_list').exportData(that); + } +}; + +export { + ExportFilterData, + ExportDataOperate +}; diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/export/exportData.vue b/bmp-operation-web/src/views/messageNotification/myMessage/export/exportData.vue new file mode 100644 index 0000000..2b9f088 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/export/exportData.vue @@ -0,0 +1,23 @@ + + + diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/index.scss b/bmp-operation-web/src/views/messageNotification/myMessage/index.scss new file mode 100644 index 0000000..2b17c79 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/index.scss @@ -0,0 +1,45 @@ +.my-message-count { + .search-tip-operate2 { + .radio-active { + position: absolute; + top: 30px; + left: 30px; + } + } + + // :deep(.my-pagination) { + // justify-content: flex-end; + // margin-right: 57px; + // } + + .no-read { + margin: 0 5px; + } + + :deep(.radius-id) { + @include set-width-height(6px); + border-radius: 50%; + background: $background1; + position: absolute; + left: -26px; + top: 50%; + transform: translateY(-50%); + } + + :deep(.message-count-no) { + font-weight: 600; + &:hover { + border-bottom: 1px solid $border19; + } + } + + :deep(.message-count) { + font-weight: $fontSmallWeight; + + &:hover { + border-bottom: 1px solid $border7; + @include set-cursor(cursor); + } + color: $color6; + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/messageDelete/deleteMsg.ts b/bmp-operation-web/src/views/messageNotification/myMessage/messageDelete/deleteMsg.ts new file mode 100644 index 0000000..e799c5e --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/messageDelete/deleteMsg.ts @@ -0,0 +1,27 @@ +/** + * @file + * @author +*/ + +class DeleteMsgOpt { + deleteMsgDiaLog: Ref = ref(false); + myMessageListOpt; + + constructor(myMessageListOpt: {restoreDefaultStatus(): void}) { + this.myMessageListOpt = myMessageListOpt; + } + + deleteMsgClick = () => { + this.deleteMsgDiaLog.value = !this.deleteMsgDiaLog.value; + } + + deleteMsgCancel = (type: boolean): boolean => { + return this.deleteMsgDiaLog.value = type; + } + + deleteMsgSure = () => { + this.myMessageListOpt.restoreDefaultStatus(); + } +} + +export default DeleteMsgOpt; diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/messageDelete/messageDelete.vue b/bmp-operation-web/src/views/messageNotification/myMessage/messageDelete/messageDelete.vue new file mode 100644 index 0000000..4547857 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/messageDelete/messageDelete.vue @@ -0,0 +1,19 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/myMessage.vue b/bmp-operation-web/src/views/messageNotification/myMessage/myMessage.vue new file mode 100644 index 0000000..41063b0 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/myMessage.vue @@ -0,0 +1,120 @@ + + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/page.ts b/bmp-operation-web/src/views/messageNotification/myMessage/page.ts new file mode 100644 index 0000000..aa50424 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/page.ts @@ -0,0 +1,10 @@ +const MyMessage = () => import(/* webpackChunkName: "MyMessage" */ './myMessage.vue'); + +export default { + path: '/MessageNotification/myMessage', + name: 'MyMessage', + component: MyMessage, + meta: { + type: 'myMessage' + } +}; diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/pagination/pagination.ts b/bmp-operation-web/src/views/messageNotification/myMessage/pagination/pagination.ts new file mode 100644 index 0000000..9b5dd68 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/pagination/pagination.ts @@ -0,0 +1,19 @@ +import {paginationOperate} from 'utils/publicClass.ts'; + +const customPagination = (list: any) => { + + watch(() => [ + paginationOperate.pageSize.value, + paginationOperate.pageNumber.value + ], (_: boolean[]): void => { + list.filter.tableRef?.value?.clearSelection() + if (paginationOperate.routerChange.value) return; + list.init(); + // list.setFilterData(search, filter?.reactiveArr); + }); +}; + +export { + paginationOperate, + customPagination +}; diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/pagination/pagination.vue b/bmp-operation-web/src/views/messageNotification/myMessage/pagination/pagination.vue new file mode 100644 index 0000000..05e82ea --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/pagination/pagination.vue @@ -0,0 +1,70 @@ + + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/search/search.ts b/bmp-operation-web/src/views/messageNotification/myMessage/search/search.ts new file mode 100644 index 0000000..c523362 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/search/search.ts @@ -0,0 +1,101 @@ +// import {SearchArrType} from '../typeManagement'; +import {paginationOperate, language} from 'utils/publicClass.ts'; +class SearchOperate { + hasClear: Ref = ref(false); + // 搜索框值 + selectVal: Ref = ref(0); + reactiveArr: any = reactive({ + detail: '', + radioGroup: { + hasReadName: language.t('myMessage.radioGroup.all'), + hasRead: '' + }, + searchParams: { + // hasRead: '', + detail: '' + }, + selectOption: [ + { + value: 0, + label: language.t('myMessage.search.title') + } + ] + }); + fn: Function; + + constructor (fn: Function) { + this.fn = fn; + this.reactiveArr.radioGroup.hasRead = this.#setRadioRead(); + this.watchRadio(); + }; + + #setRadioRead = () => { + const type = new Map([ + [language.t('myMessage.radioGroup.all'), ''], + [language.t('myMessage.radioGroup.read'), '1'], + [language.t('myMessage.radioGroup.noRead'), '0'] + ]); + return type.get(this.reactiveArr.radioGroup.hasReadName); + } + + iptValue = (enterValue: string) => { + this.reactiveArr.detail = enterValue; + // this.reactiveArr.searchParams = {detail: enterValue} + // selectValue ? this.reactiveArr.searchParams = {deviceType: enterValue} : this.reactiveArr.searchParams = {name: enterValue}; + }; + + /** + * input 输入框 点击搜索按钮或者回车触发 + * @param {string} enterValueIpt 输入框输入的值 + */ + enterValueIpt = (enterValueIpt: string): void => { + this.reactiveArr.searchParams = {detail: this.reactiveArr.detail} + this.reactiveArr.searchParams = {detail: enterValueIpt}; + // selectValue ? this.reactiveArr.searchParams = {deviceType: enterValueIpt} : this.reactiveArr.searchParams = {name: enterValueIpt}; + this.request(); + }; + + /** + * 搜索框筛选 + * @param {number} val 搜索框切换的搜索key + * @return {number} selectVal 对应的key + */ + changeSelect = (val: number): number => { + return this.selectVal.value = val; + }; + + clearClick = (val: string) => { + if (!val) { + this.selectChange(); + } + }; + + selectChange = () => { + const {detail}: {detail?: string;} = this.reactiveArr.searchParams; + if (detail) { + this.reactiveArr.searchParams = {}; + this.request(); + } + }; + + noReadClick = () => { + this.reactiveArr.radioGroup.hasReadName = language.t('myMessage.radioGroup.noRead') + } + + watchRadio = () => { + watch(() => this.reactiveArr.radioGroup.hasReadName, (_: string) => { + this.reactiveArr.radioGroup.hasRead = this.#setRadioRead(); + this.fn('listTimer'); + }) + } + + request = () => { + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn('listTimer'); + }; +}; + +export default SearchOperate; diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/table/filterStyle.ts b/bmp-operation-web/src/views/messageNotification/myMessage/table/filterStyle.ts new file mode 100644 index 0000000..0a134ba --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/table/filterStyle.ts @@ -0,0 +1,164 @@ +/** + * @file + * @author +*/ + +class FilterStyleOperate { + classNameData = [ + { + name: 'def-type-status', + type: 'messageType' + } + ]; + filterStatus: { + messageType: boolean + } = reactive({ + messageType: false + }) + + constructor (props: any) { + onMounted(() => { + nextTick(() => { + this.customFilter(props); + }) + this.watchSearchTip(props); + this.watchFilter(props); + }) + }; + + watchSearchTip = (props: any) => { + watch(() => + props.myMessageList.searchTip, (newValue) => { + const that = this; + if (!newValue.value) { + for (let index in this.filterStatus) { + (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = false; + } + } + else { + this.setFilterStatus(props.filterOperate.reactiveArr.filterParams); + } + }, { + deep: true + }); + }; + + watchFilter = (props: any) => { + watch(() => props.filterOperate.reactiveArr.filterParams, (newValue) => { + this.setFilterStatus(newValue); + }, {deep: true}) + }; + + setFilterStatus = (params: any) => { + const that = this; + this.classNameData.forEach((item) => { + if (['', undefined].includes(params[item.type])) { + (this.filterStatus[`${item.type}` as keyof typeof that.filterStatus] as boolean) = false; + return; + } + (this.filterStatus[`${item.type}` as keyof typeof that.filterStatus] as boolean) = true; + }) + }; + + customFilter = (props: any) => { + let filterName: HTMLElement | null; + let filterOpt: HTMLElement | null; + const that = this; + this.classNameData.forEach((item) => { + filterName = document.querySelector(`.${item.name} > .cell`); + filterOpt = document.querySelector(`.${item.name} > .cell > .el-table__column-filter-trigger`) + filterName?.addEventListener('click', (event) => { + event.stopPropagation(); + for (let index in this.filterStatus) { + // for (const key of this.classNameData) { + if (index === item.type && props.filterOperate.reactiveArr.filterParams[item.type]) { + (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = true; + } + else { + (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = false; + } + // } + } + }) + filterOpt?.addEventListener('click', (event) => { + event.stopPropagation(); + // (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = !(this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean); + for (let index in this.filterStatus) { + // // for (const key of this.classNameData) { + if (index === item.type && props.filterOperate.reactiveArr.filterParams[item.type]) { + (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = true; + } + else { + (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = !(this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean); + // !(this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean); + } + // // } + } + }); + const filterOtherRegion = document.querySelectorAll('.el-table-filter'); + filterOtherRegion.forEach((_, index) => { + filterOtherRegion[index]?.addEventListener('click', (event) => { + event.stopPropagation(); + for (let index in this.filterStatus) { + for (const key of this.classNameData) { + if (index === key.type && props.filterOperate.reactiveArr.filterParams[key.type]) { + (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = true; + } + } + } + }) + }) + let newType = []; + document.addEventListener('click', () => { + // event.stopPropagation(); + newType = []; + newType.push(item.type); + newType.forEach((ite) => { + this.filterDispose(ite, props); + }) + }) + }) + }; + + filterDispose = (type: string, props: any) => { + const filterVal = props.filterOperate.reactiveArr.filterParams; + const that = this; + if (props.myMessageList.searchTip.value) { + for (let key in filterVal) { + if (key === type) { + (this.filterStatus[`${key}` as keyof typeof that.filterStatus] as boolean) = true; + // this.filterStatus[key] = true; + } + else { + // this.filterStatus[type] + if ((this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean) && Object.keys(filterVal).length > 1) { + for (let index in this.filterStatus) { + for (const key of this.classNameData) { + if (index === key.type && props.filterOperate.reactiveArr.filterParams[key.type]) { + return; + } + (this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean) = !(this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean); + } + } + } + else { + for (let index in this.filterStatus) { + for (const key of this.classNameData) { + if (index === key.type && props.filterOperate.reactiveArr.filterParams[key.type]) { + return; + } + (this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean) = false; + } + } + // this.filterStatus[type] = false; + } + } + } + } + else { + (this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean) = false; + } + } +}; + +export default FilterStyleOperate; diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/table/myMessageList.ts b/bmp-operation-web/src/views/messageNotification/myMessage/table/myMessageList.ts new file mode 100644 index 0000000..1bece9a --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/table/myMessageList.ts @@ -0,0 +1,463 @@ +import {TableType} from '../typeManagement'; +import {CurrencyType} from '@utils/publicType'; +import {CurrentInstance, paginationOperate, RouterOperate, language} from 'utils/publicClass'; +import {methodsTotal, deepCopy, msgTip} from 'utils/index.ts'; +// OSSType, ReactiveArrType, FilterParamsType +import store from 'store/index.ts'; +import MessageStaticData from 'staticData/message/index.ts'; +import {AxiosError} from 'axios'; +import {removeLong} from 'request/RemoveLongReq/remove.ts'; +// let d: any; +let _self: any = null; +class MyMessageListOpt { + listTimer: Ref = ref(null); + ossStore = store.ossDataInfo(); + routerOperate = new RouterOperate(); + searchTip: Ref = ref(false); + deleteBtnDisabled: Ref = ref(true); + readBtnDisabled: Ref = ref(true); + // loading态 + isLoading: Ref = ref(false); + reactiveArr: { + // filterParams: {messageSubType: string}; + tableData: {[x: string]: string}[]; + selectArr: CurrencyType[]; + defTableData: TableType[]; + arr: any; + currentData: any; + copyDataVal: {label: string; value: string; checkboxStatus: boolean}[]; + customFilterList: {label: string; value: string; checkboxStatus: boolean;}[]; + } = reactive<{ + // filterParams: {messageSubType: string}; + tableData: {[x: string]: string}[]; + selectArr: CurrencyType[]; + defTableData: TableType[]; + arr: TableType[]; + currentData: TableType[]; + copyDataVal: {label: string; value: string; checkboxStatus: boolean}[]; + customFilterList: {label: string; value: string; checkboxStatus: boolean}[]; + }>({ + tableData: [], + selectArr: [], + defTableData: [], + arr: [], + currentData: [], + copyDataVal: [], + customFilterList: [] + }); + isIntervalRequest: boolean = false; + hasCheckAll: Ref = ref(false); + total: Ref = ref(0); + noReadTotal: Ref = ref(0); + proxy = new CurrentInstance().proxy; + filter: any = {}; + search: any; + instanceMitt: any = new CurrentInstance(); + setMessageSubTypeClass: Ref = ref(false); + readonly mittData = [ + { + type: 'custom-filter-click', + fn: 'getOpt' + }, + { + type: 'custom-filter-reset', + fn: 'customResetClick' + }, + { + type: 'custom-filter-dia-log', + fn: 'getStatus' + } + ] + + constructor(filter: any, search: any) { + // super(); + this.filter = filter; + this.search = search; + this.init(); + // this.handleVisibility(); + this.watchStoreCustomList(); + // 标为已读和删除需要调用这个接口 + this.getMessageCountNoReadTotal(); + + onBeforeUnmount(() => this.unMountOpt()) + onUnmounted(() => this.unMountOpt()); + for (const key of this.mittData) { + // @ts-ignore + this.onOffMitt(key.type, this[key.fn], true); + } + _self = this; + } + + unMountOpt = () => { + clearTimeout(this.listTimer.value as number); + removeLong(this.routerOperate.router.currentRoute.value.name) + for (const key of this.mittData) { + // @ts-ignore + this.onOffMitt(key.type, this[key.fn]); + } + } + + onOffMitt = (type: string, fn: Function, hasOn: boolean = false) => { + if (!hasOn) { + this.instanceMitt?.proxy?.$Bus?.off(type, fn); + return; + } + this.instanceMitt?.proxy?.$Bus?.on(type, fn); + } + + handleVisibility = () => { + // document.addEventListener('visibilitychange', () => { + // const status = { + // 'hidden': () => clearTimeout(this.listTimer as number), + // 'visible': () => this.getMessageList() + // } + // status[document.visibilityState](); + // }) + } + + getOpt = (item: {label: string; value: string; checkboxStatus: boolean;}[]) => { + this.customFilterClick(item); + } + + watchStoreCustomList = () => { + watch(() => this.ossStore.customFilterList, (newValue) => { + this.reactiveArr.customFilterList = newValue; + this.reactiveArr.copyDataVal = deepCopy(this.reactiveArr.customFilterList); + }) + } + + rowClick = (row: {[x: string]: string}, _: any, event: Event) => { + this.filter.tableRef?.value?.toggleRowSelection(row, event); + }; + + cellClick = (row: CurrencyType, b: {property: string | undefined}, event: any) => { + // prop必传,否则为undefined + const type = ['content', undefined]; + if (!type.includes(b.property)) return; + this.toggleSelection([row], event); + }; + + toggleSelection = (rows: CurrencyType[], event: any) => { + if (rows) { + rows.forEach((row: any) => { + this.filter.tableRef.value?.toggleRowSelection(row, event); + }); + return; + } + this.filter.tableRef.value?.clearSelection(); + }; + + // 多选框回显 + getRowKeys = (row: {messageId: string;}) => { + if (row.messageId) return row.messageId; + }; + + setMessageCount = (item: any) => { + // Object.is(language.t('myMessage.table.inbondAlert'), item.messageType) ? this.#instanceId(item) + this.#setDays(item) : + const val = Object.is(language.t('myMessage.table.inbondAlert'), item.messageType) ? this.#instanceId(item) : this.#setSn(item); + return item.messageType + ' - ' + this.#setNotice(item) + val + this.#setDays(item); + } + + handleSelectionChange = async (val: {[x: string]: string}[]) => { + _self.reactiveArr.selectArr = val; + _self.hasCheckAll.value = _self.reactiveArr.selectArr.length === _self.reactiveArr.tableData.length; + _self.deleteBtnDisabled.value = !(val?.length); + _self.readBtnDisabled.value = !(val?.length); + } + + readMessageClick = async () => { + try { + // @ts-ignore + const res = await this.proxy.$messageApi.doReadAPI({messageIds: this.reactiveArr.selectArr.map(item => item.messageId)}); + if (res?.data?.result?.success) { + this.restoreDefaultStatus(); + } + } + catch (e) { + const err = e as AxiosError; + err.message && msgTip.error(err.message); + } + } + + restoreDefaultStatus = () => { + this.reactiveArr.tableData.forEach(item => { + this.filter.tableRef.value?.toggleRowSelection(item, false); + }); + this.init(); + this.getMessageCountNoReadTotal(); + } + + checkAll = (event: boolean) => { + const newData = this.reactiveArr.tableData; + this.reactiveArr.tableData.map(item => { + // toggleRowSelection接收两个参数,第一个是被勾选的数据,第二个是选中状态(注:需要注册 ref 来引用) + if (event) { + for(let i = 0; i < newData.length; i++) { + // 未添加的才插入,否则数据会冗余 + if (!this.reactiveArr.arr.some((s: {instanceId: string;}) => s.instanceId === newData[i].instanceId)) { + this.reactiveArr.arr.push(newData[i]); + } + } + } + else { + for (let i = 0; i< this.reactiveArr.tableData.length; i++) { + for (let j = 0; j< this.reactiveArr.currentData.length; j++){ + // 移除当前页currentData的数据 + if (this.reactiveArr.currentData[j].instanceId === this.reactiveArr.tableData[i].instanceId) { + this.reactiveArr.currentData.splice(j, 1); + } + } + for(let k = 0; k < this.reactiveArr.arr.length; k++){ + // 移除当前页currentData的数据 + if (this.reactiveArr.arr[k].instanceId === this.reactiveArr.tableData[i].instanceId) { + this.reactiveArr.arr.splice(k, 1); + } + } + } + } + this.filter.tableRef?.value?.toggleRowSelection(item, event); + // this.tableRef.value?.toggleRowSelection(item, event); + }); + }; + + #setInstanceName = (name: undefined) => { + const type = new Map([ + [void 0, ''], + ]); + return type.get(name)?? name + '/'; + } + + #setDays = (item: {detail: string; messageType: string}) => { + if (item?.detail === null) return ''; + if ([language.t('myMessage.table.faultMessages', language.t('myMessage.table.operationMessages'))].includes(item.messageType)) return ''; + const obj = new Map([ + ['90', language.t('myMessage.day90')], + ['30', language.t('myMessage.day30')], + ['15', language.t('myMessage.day15')], + ['0', language.t('myMessage.expired')] + ]); + return obj.get(item.detail)?? ''; + } + + #setNotice = (item: {messageType: string, faultType: string, messageSubType: string}) => { + const type = new Map([ + [language.t('myMessage.table.systemMessages'), `【${item.messageSubType}】`], + [language.t('myMessage.table.faultMessages'), `【${item.faultType}】${language.t('myMessage.table.remind')}`], + [language.t('myMessage.table.operationMessages'), `【${item.messageSubType}】 ${language.t('myMessage.table.failureNotification')}`], + [language.t('myMessage.table.inbondAlert'), `【${item.messageSubType}】 ${language.t('myMessage.table.alarmTips')}`] + ]); + return type.get(item.messageType) + } + + refresh = () => { + if (!this?.reactiveArr?.tableData?.length) { + this.reset(); + return; + } + this.init(); + } + + setClass = (messageSubType: string) => { + if (messageSubType || this.setMessageSubTypeClass.value) { + return 'def-cls lignt-filter'; + } + return 'def-cls default-filter'; + } + + reset = () => { + let hasReq: boolean = false; + const {hasClear, reactiveArr} = this.search; + const {messageType, messageSubType} = this.filter.reactiveArr.filterParams; + const status = ['0', '1'].includes(reactiveArr.radioGroup.hasRead) + hasReq = (!status && (reactiveArr.searchParams.detail || messageType || messageSubType)); + clearTimeout(this.listTimer.value) + this.filter.tableRef.value?.clearFilter(); + this.filter.reactiveArr.filterParams = {}; + this.setMessageSubTypeClass.value = false; + hasClear.value = true; + reactiveArr.detail = ''; + reactiveArr.searchParams = {}; + reactiveArr.radioGroup.hasRead = ''; + reactiveArr.radioGroup.hasReadName = language.t('myMessage.radioGroup.all') + const valData = this.reactiveArr.copyDataVal.map(item => { + return { + ...item, + checkboxStatus: false + } + }) + this.reactiveArr.customFilterList = valData; + this.reactiveArr.copyDataVal = valData; + this.instanceMitt?.proxy?.$Bus?.emit('custom-filter-input-clear'); + this.getMessageCountNoReadTotal(); + if (hasReq) { + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.init(); + } + } + + #instanceId = (item: {instanceName: string | undefined; instanceId: string | undefined}) => { + if ([item.instanceName, item.instanceId].includes(void 0)) return; + return '(' + item.instanceName + '/' + item.instanceId + ')'; + } + + #setSn = (item: {sn: undefined, instanceName: undefined}) => { + const type = new Map([ + [void 0, ''] + ]) + return type.get(item.sn)?? '(' + this.#setInstanceName(item.instanceName) + item.sn + ')'; + } + + customFilterClick = (val: {label: string; value: string}[]) => { + const data = val.map(item => item.label).join(','); + this.filter.reactiveArr.filterParams.messageSubType = data; + // paginationOperate.pageNumber.value = 1; + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.init(); + } + + customResetClick = () => { + this.reactiveArr.customFilterList = this.reactiveArr.copyDataVal.map((item: {label: string; value: string; checkboxStatus: boolean}) => { + return { + ...item, + checkboxStatus: false + } + }) + this.setMessageSubTypeClass.value = false; + this.reactiveArr.copyDataVal = this.reactiveArr.customFilterList; + this.filter.reactiveArr.filterParams.messageSubType = ''; + this.init(); + } + + jump = (item: {messageId: string; detail: string; messageType: string; licenseEndTime: number;}) => { + const path = this.proxy!.$defInfo.routerPath('myMessageDetail'); + clearTimeout(this.listTimer.value as number); + const obj = { + type: this.getQueryType(item.messageType), + id: item.messageId, + newDate: item.detail, + endTime: item.licenseEndTime + } + const val = encodeURIComponent(JSON.stringify(obj)) + localStorage.setItem('messageInfo', val); + this.routerOperate.router.push(path as unknown as string) + } + + getStatus = (val: boolean) => { + this.setMessageSubTypeClass.value = val; + } + + setDate = (detail: string) => { + if (detail === null) return; + return detail; + } + + getQueryType = (messageType: string) => { + const type = new Map([ + [language.t('myMessage.table.faultMessages'), 'faultMessage'], + [language.t('myMessage.table.systemMessages'), 'unexpiredExpired'], + [language.t('myMessage.table.operationMessages'), 'optMessage'], + [language.t('myMessage.table.inbondAlert'), 'inbondAlert'] + ]); + return type.get(messageType) + } + + init = async () => { + this.isLoading.value = true; + this.getMessageList(); + } + + getMessageList = async () => { + clearTimeout((this.listTimer.value as number)); + const path = this.proxy!.$defInfo.routerPath('myMessage'); + if (this.routerOperate.router.currentRoute.value.path !== path as unknown as string) { + return; + } + const param = { + pageNumber: paginationOperate.pageNumber.value, + pageSize: paginationOperate.pageSize.value, + ...this.filter.reactiveArr.filterParams, + ...this.search.reactiveArr.searchParams, + hasRead: this.search.reactiveArr.radioGroup.hasRead + }; + this.filter.filterEmptyInfo.deleteEmtpyData(param); + const status = Object.keys(param).length > 2; + try { + // @ts-ignore + const res = await this.proxy.$messageApi.messageListAPI({...param}); + if (![void 0].includes(res?.data?.result?.messages)) { + const {messages, totalCount} = methodsTotal.lineConverting(res.data.result); + messages.forEach((item: TableType, index: number) => { + MessageStaticData.messageTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }) + }) + this.reactiveArr.tableData = messages; + paginationOperate.total.value = totalCount; + if (status) { + clearTimeout(this.listTimer.value); + } + else { + this.listTimer.value = setTimeout(() => { + if (status) return; + this.isIntervalRequest = true; + this.getMessageList(); + this.getMessageCountNoReadTotal(); + }, 5000) + } + return; + } + this.reactiveArr.tableData = []; + paginationOperate.total.value = 0; + } + catch(e) { + if (!this.isIntervalRequest) { + const err = e as AxiosError; + if (Object.is(err?.code, 402)) return; + err?.message && msgTip.error(err.message); + return; + } + // if (status) { + // clearTimeout(this.listTimer.value); + // } + // else { + this.listTimer.value = setTimeout(() => { + if (status) { + clearTimeout(this.listTimer.value); + return; + }; + this.getMessageList(); + this.getMessageCountNoReadTotal(); + }, 5000) + // } + } + finally { + this.isLoading.value = false; + this.search.hasClear.value = false; + this.searchTip.value = status; + this.instanceMitt?.proxy?.$Bus?.emit('search-tip-value', this.searchTip.value ? 15 : 0); + this.instanceMitt?.proxy?.$Bus?.emit('message-list', this.reactiveArr.tableData); + } + } + + getMessageCountNoReadTotal = async () => { + try { + // @ts-ignore + const res = await this.proxy.$messageApi.messagesStatisticAPI({}); + const {totalCount, unreadCount} = res.data.result; + this.total.value = totalCount; + this.noReadTotal.value = unreadCount; + } + catch { + this.total.value = 0; + this.noReadTotal.value = 0; + } + } +} + +export default MyMessageListOpt; diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/table/setEmpty.ts b/bmp-operation-web/src/views/messageNotification/myMessage/table/setEmpty.ts new file mode 100644 index 0000000..add468f --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/table/setEmpty.ts @@ -0,0 +1,45 @@ +/** + * @file + * @author +*/ + +import {language, CurrentInstance} from 'utils/publicClass.ts'; + +const p = document.createElement('p'); +const span = document.createElement('span'); + +class SetEmpty { + mitt = new CurrentInstance(); + + constructor() { + this.mitt.instanceMitt?.proxy?.$Bus?.on('message-list', this.watchTableData); + onUnmounted(() => { + p.innerHTML = ''; + this.mitt.instanceMitt?.proxy?.$Bus?.off('message-list', this.watchTableData); + }); + }; + + watchTableData = (val: any) => { + if (!val?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.remove(); + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + const customText = document.querySelector('.my-message-list .el-scrollbar__view'); + if (!customText) return; + ai!.innerHTML = ''; + p.className = 'custom-tip-count'; + customText.appendChild(p) + p.appendChild(span) + span.innerHTML = `${language.t('table.empty')}`; + }; +}; + +export default SetEmpty; + diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/table/tableData.vue b/bmp-operation-web/src/views/messageNotification/myMessage/table/tableData.vue new file mode 100644 index 0000000..d0bf401 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/table/tableData.vue @@ -0,0 +1,137 @@ + + diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/table/tableFilter.ts b/bmp-operation-web/src/views/messageNotification/myMessage/table/tableFilter.ts new file mode 100644 index 0000000..258a705 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/table/tableFilter.ts @@ -0,0 +1,87 @@ +import store from 'store/index.ts'; +import {paginationOperate} from 'utils/publicClass.ts'; +import {OSSType, ReactiveArrType, FilterParamsType} from '../typeManagement'; + +let that: any = null; + +/** + * 筛选操作 +*/ +class FilterOperate { + // store库存储的oss数据类 + ossStore: OSSType = store.ossDataInfo(); + tableRef: { + [x: string]: unknown; + value?: { + toggleRowSelection(arg1: any, arg2: any): any; + clearFilter(): unknown; + clearSelection(): any; + } + } = {value: {clearFilter(): void{}, toggleRowSelection(): any{}, clearSelection(): any{}}}; + filterEmptyInfo: { // store + filterParams( + arg0: {[x: string]: number | string}, + arg1: OSSType, + arg2: ReactiveArrType, + arg3: FilterParamsType + ): Promise; + deleteEmtpyData(arg0: FilterParamsType): unknown; + } = store.filterEmpty; + // 复杂数据类型 + reactiveArr: { + filterParams: FilterParamsType; + // selectArr: any; + + } = reactive<{ + filterParams: FilterParamsType; + // selectArr: any; + }>({ + filterParams: { + messageType: '', + messageSubType: '' + }, + // selectArr: [] + }); + fn: any; + + // 构造器 + constructor (fn: any) { + that = this; + that.fn = fn; + that.ossStore.getMessagesType() + }; + + /** + * 获取表格ref + * @param {Object} tableEl 表格信息 + */ + getTableRef = (tableEl: {[x: string]: unknown}): void => { + this.tableRef = tableEl; + }; + + messageTypeFilter = (): boolean => { + return true; + }; + + /** + * @param {Object} filter 需要过滤的数据 + */ + filterChange = (filter: {[x: string]: number | string}) => { + this.tableRef.value?.clearSelection() + const filterParams: FilterParamsType = { + messageType: 'messageType', + // messageSubType: 'messageSubType' + // name: 'name' + }; + this.filterEmptyInfo.filterParams(filter, this.ossStore, this.reactiveArr, filterParams) + .then((_: any) => { + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn(); + }) + }; +}; + +export default FilterOperate; diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/table/tableScroll.ts b/bmp-operation-web/src/views/messageNotification/myMessage/table/tableScroll.ts new file mode 100644 index 0000000..6a7aef1 --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/table/tableScroll.ts @@ -0,0 +1,102 @@ +import {HeightType3} from '@utils/publicType'; +import {tableScroll} from 'utils/index.ts'; +import {CurrentInstance} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; + +interface TableScrollDataType { + scrollTimer: null | number; + searchTipHeight: number; + fixedHeight: Ref; + tableMaxHeight: Ref; + status: boolean; + headerTitle: Ref; + operate: Ref; +}; + +const tableScrollOperate = (filters: any, search: any, searchTip: {value: boolean}, path: string) => { + const data: TableScrollDataType = { + scrollTimer: null, + searchTipHeight: 13, + fixedHeight: ref(0), + tableMaxHeight: ref(0), + status: false, + headerTitle: ref({offsetHeight: 0, scrollHeight: 0}), + operate: ref({offsetHeight: 0, scrollHeight: 0}) + }; + + const mitt = new CurrentInstance(); + const pathUrl: string = mitt.proxy.$defInfo.routerPath('myMessage'); + onMounted(() => { + setScroll(setHeight(), data.tableMaxHeight); + onResize(data.tableMaxHeight); + }); + + onUnmounted(() => { + clearTimeout(data.scrollTimer as number) + }) + + + watch(() => [ + filters.filterParams, + search.searchParams, + search.radioGroup, + searchTip, + ], (newValue: any) => { + if (newValue[3].value) { + if (path !== pathUrl) return; + setScroll(setHeight(), data.tableMaxHeight); + } + }, {deep: true}) + + watch(() => store.navigationBarStatus.hasNavigationBar, (_: boolean) => { + if (path !== pathUrl) return; + data.scrollTimer = setTimeout(() => { + setScroll(setHeight(), data.tableMaxHeight); + }, 200) + }); + + const onResize = (tableMaxHeight: {value: number}) => { + if (path !== pathUrl) return; + window.onresize = async () => { + await mitt.instanceMitt?.proxy?.$Bus?.emit('custom-filter-onresize', 1); + setScroll(setHeight(), tableMaxHeight); + }; + }; + + const setHeight = () => { + const header = data.headerTitle.value; + const operate = data.operate.value; + data.fixedHeight.value = header.offsetHeight * 2.9 + operate.offsetHeight + 35; + const countHeight: number = data.fixedHeight.value; + return countHeight; + }; + + const setScroll = (countHeight: number, tableMaxHeight: {value: number}) => { + const messageType: string = filters.filterParams?.messageType??''; + const messageSubType: string = filters.filterParams?.messageSubType??''; + const content: string = search.searchParams?.content??''; + const hasRead: string = search.radioGroup?.hasRead??''; + if ([messageType, messageSubType, content, hasRead].some((item: string) => item !== '')) { + tableScroll(countHeight + data.searchTipHeight, tableMaxHeight); + return; + } + tableScroll(countHeight, tableMaxHeight); + }; + + const getHeaderRef = (val: {value:HeightType3}) => { + data.headerTitle.value = val.value; + }; + + const getOperateRef = (val: {value: HeightType3})=> { + data.operate.value = val.value; + }; + + return { + ...data, + // getBtnRef, + getHeaderRef, + getOperateRef + } +}; + +export default tableScrollOperate; diff --git a/bmp-operation-web/src/views/messageNotification/myMessage/typeManagement.ts b/bmp-operation-web/src/views/messageNotification/myMessage/typeManagement.ts new file mode 100644 index 0000000..a198b4c --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/myMessage/typeManagement.ts @@ -0,0 +1,62 @@ +/** + * text类 +*/ +type TextType = { + [x: string]: { + text: string; + }; +}; + +interface OSSType { + deviceSeries: TextType; + manageStatus: TextType; + deviceTypeId: TextType; + getModelList(): void; + getOssData(): void; +}; +interface SearchArrType { + searchParams: { + sn?: string; + userName?: string; + }; + selectOption: { + value: number; + label: string; + }[]; +}; + + +/** + * filter参数类 +*/ +// messageSubType?: string; content?: string; hasRead?: string; +type FilterParamsType = {messageType?: string; messageSubType?: string;}; + + +/** + * 复杂数据类型类 +*/ +type ReactiveArrType = {filterParams?: FilterParamsType;}; + +type HeightType = {offsetHeight: number; offsetTop: number;}; + +type OperateHeightType = Pick; + +// table ts +type TableType = {devices: string;} & {[x: string]: string | boolean;}; +// 跳转路由 ts +type JumpRouterType = {sn: string; deviceId: string}; +// 导出类型 +type ExportType = {devicesListExportAPI: Function; hasExportData: {value: boolean;}; exportData: Function;}; + +export { + OSSType, + SearchArrType, + ReactiveArrType, + FilterParamsType, + HeightType, + OperateHeightType, + TableType, + JumpRouterType, + ExportType +}; diff --git a/bmp-operation-web/src/views/messageNotification/navRouter.ts b/bmp-operation-web/src/views/messageNotification/navRouter.ts new file mode 100644 index 0000000..5f4b2ee --- /dev/null +++ b/bmp-operation-web/src/views/messageNotification/navRouter.ts @@ -0,0 +1,56 @@ +/** + * @file + * @author +*/ + +import {language} from "utils/publicClass.ts"; + +const userNavData = (pathUrl: (arg0: string) => void, imgUrl: (arg0: string) => void) => { + return { + title: language.t('navigationBar.list.messageCenter'), + defaultImg: imgUrl('messageDef'), + changeImg: imgUrl('messageLight'), + path: pathUrl('myMessage'), + otherPath: [pathUrl('myMessage'), pathUrl('myMessageDetail')], + hasAdmin: false, + isF: true, + } +}; + +const adminUserNavData = (pathUrl: (arg0: string) => void, imgUrl: (arg0: string) => void) => { + return { + title: language.t('navigationBar.list.messageCenter'), + defaultImg: imgUrl('messageDef'), + changeImg: imgUrl('messageLight'), + path: [ + pathUrl('myMessage'), + pathUrl('myMessageSettings'), + pathUrl('myMessageDetail') + ], + otherPath: [''], + firstIndex: 'MessageNotification', + childrenHasAdmin: false, + isChildrenF: true, + children: [ + { + title: language.t('navigationBar.children.myMessages'), + defaultImg: imgUrl('messageDef'), + changeImg: imgUrl('messageLight'), + path: pathUrl('myMessage'), + otherPath: [pathUrl('myMessage'), pathUrl('myMessageDetail')], + }, + { + title: language.t('navigationBar.children.messageSet'), + defaultImg: imgUrl('messageDef'), + changeImg: imgUrl('messageLight'), + path: pathUrl('myMessageSettings'), + otherPath: [pathUrl('myMessageSettings')] + } + ] + } +}; + +export { + userNavData, + adminUserNavData +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/add/index.scss b/bmp-operation-web/src/views/modelManagement/add/index.scss new file mode 100644 index 0000000..796ecd5 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/add/index.scss @@ -0,0 +1,439 @@ +@import 'assets/css/modelForm.scss'; + +.model-operate { + .operate-management-detail-header { + position: static !important; + } + + .custom-count { + height: calc(100% - 130px); + overflow-y: auto; + } + + .operate-management-detail-info { + margin-top: 30px; + } + + .el-table__empty-block { + background-color: #fff; + width: auto !important; + } + + .set-right { + .el-form-item__label { + margin-right: 30px; + } + } + + .save-btn { + margin-bottom: 36px; + } + + .edit-btn { + margin-bottom: 0 !important; + } + + .operate-btn { + cursor: pointer; + color: #108ee9; + + span { + font-size: 12px; + &:first-child { + margin-right: 10px; + } + } + } + + .active-ipt { + input { + border-color: #f56c6c; + } + } + + .error-tip { + @extend %error-tip; + } + + .default-ipt { + input { + border-color: #dcdfe6; + } + } + + .default-right { + .el-form-item__label { + margin-right: 10px; + } + } + + .boot-mode-count { + margin: 20px 0 18px; + + .el-checkbox__label { + height: 20px; + line-height: 20px; + } + } + + .add-volume-en { + font-size: 12px; + margin-left: 165px; + } + .add-volume { + font-size: 12px; + margin-left: 115px; + } + + .default-s { + color: #999; + cursor: no-drop; + margin-top: 5px; + } + + .active { + cursor: pointer; + color: #108ee9; + } + + .set-top { + margin-top: 22px !important; + } + + #volumeManager { + white-space: nowrap; + @extend %volume-manager; + } + + &-rule-form { + + #bootMode { + .el-form-item__label { + &::before { + position: relative; + font-weight: 600; + line-height: 1.5; + display: flex; + @extend %word-css; + content: "*"; + color: var(--el-color-danger); + margin-right: 4px; + } + } + } + + .template-tip { + @extend %template-tip-css; + } + + .set-empty { + margin-bottom: 32px !important; + .el-form-item__error { + margin-top: 6px !important; + } + } + + .set-empty1 { + margin-bottom: 28px !important; + .el-form-item__error { + margin-top: 6px !important; + } + } + + .set-default { + margin-bottom: 12px !important; + } + + .set-name-bottom { + margin-bottom: 47px !important; + + .el-form-item__error { + margin-top: 5px !important; + } + } + + .set-label { + display: flex; + align-items: flex-start !important; + + .el-form-item__content { + .radio-button-text-ellipsis { + margin-bottom: 5px; + } + } + } + + .device-type-count { + position: relative; + } + + .el-form-item--default { + display: flex; + align-items: center; + + .el-form-item__label { + position: relative; + font-weight: $fontLargeWeight; + line-height: 1.5; + display: flex; + @extend %word-css; + } + } + + .error-device-type { + input { + border-color: #f56c6c; + } + } + + .has-error-device-type { + position: absolute; + top: 22px; + font-size: $fontSize; + color: #f56c6c; + } + + .model-name { + .el-input { + width: auto; + } + } + + .specifications { + + .el-input { + width: auto; + } + + .el-form-item__content { + position: relative; + } + } + + .el-input--default, + .el-form-item__content { + display: flex; + } + + .set-desc { + .el-form-item__label { + display: flex; + align-items: flex-start; + margin-top: 5px; + width: 130px !important; + margin-left: 10px; + margin-top: -50px; + } + .el-input__count { + font-size: $fontSize; + color: $color7; + font-weight: $fontSmallWeight; + } + } + .set-english-width { + .el-form-item__label { + width: 130px !important; + margin-left: 10px; + } + } + + .set-width { + .el-form-item__label { + width: 100px !important; + margin-left: 10px; + } + } + + .el-table__row { + .el-table__cell { + padding: 0; + } + } + + .el-select { + width: 100%; + } + + &-desc { + + .el-textarea { + width: 507px; + } + .el-form-item__label { + width: 100px !important; + margin-left: 10px; + margin-top: -50px; + } + + .el-textarea__inner { + height: 78px; + padding: 5px 8px; + margin-top: 7px; + resize: none; + + &::placeholder { + font-size: $fontSize; + } + + font-size: $fontSize; + } + + .el-input__count { + font-size: $fontSize; + color: $color7; + font-weight: $fontSmallWeight; + } + } + + .hide-label { + .el-form-item__label { + opacity: 0; + } + } + + .set-select-width { + .el-form-item__content { + input { + width: 260px; + } + } + } + + .multiple-choice { + input { + width: 100%; + } + } + + .select-width { + .el-form-item__content { + .el-select, + input { + width: 235px; + } + } + } + + .set-data-sys-style { + .el-form-item__content { + input { + width: 300px; + border-top-right-radius: 0; + border-bottom-right-radius: 0; + } + + .el-select { + position: absolute; + left: 300px; + + input { + width: 65px; + border-top-left-radius: 0; + border-bottom-left-radius: 0; + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; + border-left: 0; + } + } + } + } + + .sys-single-capacity, + .data-single-capacity { + .el-form-item__content { + width: 224px; + position: relative; + + input { + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; + } + + .el-select .el-input.is-focus .el-input__inner { + border-color: #dcdfe6 !important; + } + + .el-select { + width: 67px; + position: absolute; + // left: 150px; + right: 0; + + input { + width: 65px; + border-top-left-radius: 0; + border-bottom-left-radius: 0; + border-top: 0; + height: 28px; + border-bottom: 0; + border-right: 0; + margin-right: 1px; + + &:focus { + border-color: #dcdfe6 !important; + } + } + } + } + } + + .el-form-item__label, + .el-input__inner { + font-size: $fontSize; + color: $defaultColor; + } + + .el-form-item--default { + margin-bottom: 18px; + + &:last-child { + margin-bottom: 0; + } + } + + input { + // width: 450px; + height: 30px; + border-radius: 4px; + } + } + + .set-bottom { + margin-bottom: 24px; + } + + .en-table-error-tip { + margin-left: 170px; + font-size: 12px; + margin-bottom: 20px; + color: #f56c6c; + } + + .table-error-tip { + margin-left: 115px; + font-size: 12px; + margin-bottom: 20px; + color: #f56c6c; + } + + .set-from-img, + .model-from-img { + right: 0px; + top: 50%; + transform: translateY(-50%); + width: 16px; + height: 16px; + position: absolute; + } + + .footer-btn { + display: flex; + align-items: center; + justify-content: center; + // margin-bottom: 50px; + button { + width: 150px; + height: 36px; + } + } +} diff --git a/bmp-operation-web/src/views/modelManagement/add/modelAdd.vue b/bmp-operation-web/src/views/modelManagement/add/modelAdd.vue new file mode 100644 index 0000000..d1ff0a7 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/add/modelAdd.vue @@ -0,0 +1,1140 @@ + + + + diff --git a/bmp-operation-web/src/views/modelManagement/add/noConfiguration.vue b/bmp-operation-web/src/views/modelManagement/add/noConfiguration.vue new file mode 100644 index 0000000..ee7436f --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/add/noConfiguration.vue @@ -0,0 +1,337 @@ + + + + diff --git a/bmp-operation-web/src/views/modelManagement/add/page.ts b/bmp-operation-web/src/views/modelManagement/add/page.ts new file mode 100644 index 0000000..1345508 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/add/page.ts @@ -0,0 +1,10 @@ +const ModelAdd = () => import(/* webpackChunkName: "ModelAdd" */ './modelAdd.vue'); + +export default { + path: '/ModelManagement/modelAdd', + name: 'ModelAdd', + component: ModelAdd, + meta: { + type: 'modelAdd' + } +}; diff --git a/bmp-operation-web/src/views/modelManagement/add/typeManagement.ts b/bmp-operation-web/src/views/modelManagement/add/typeManagement.ts new file mode 100644 index 0000000..684dd3f --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/add/typeManagement.ts @@ -0,0 +1,173 @@ +import {CurrencyType, CpuDataType, MemDataType, VerifyRulesType} from '@utils/publicType'; + +type key = 'name' | 'value'; + +type key1 = 'hasClick' | 'hasClick1' | 'hasClick2' | 'hasClick3' | 'hasClick4' | 'sysRaidFlag' | 'raidConfig'; + +/** + * 机型类型 +*/ +type RadioBtnType = { + [k in key]: string; +}; + +// type RadioBtnType = { [key in keyof T]: string} + +type IdcNameRadioBtnType = { + find(arg0: (item: {title: string;}) => boolean): {idcId: string; title: string;}; +}; + +/** + * 机房名称类 +*/ +type ComputerRoomRadioBtnType = { + title: string; + idcId: string; + showTooltip: boolean; +}; + +/** + * 通用操作类 +*/ +interface ProcessingOperationsType { + setModelType(arg0: string): string; + // processingOperations(formSubmit: CurrencyType): CurrencyType; + // cpuPreset(formSubmit: CurrencyType): CurrencyType; + // memPreset(formSubmit: CurrencyType): CurrencyType; + setCpuMemData(arg0: boolean, arg1: boolean, arg2: any): Promise; + // setFormData(formSubmit: CurrencyType): CurrencyType; + // setErrorHeight(arg0: Ref[], arg1: boolean, arg2: boolean, arg3: Ref, arg4: Ref, arg5: any, arg6: any): never; +}; + +/** + * 复杂数据类 +*/ +interface ReactiveDataType { + radioBtn: RadioBtnType[]; + computerRoomRadioBtn: ComputerRoomRadioBtnType[]; + modelCPUBtn: string[]; + storageData: string[]; +}; + +/** + * 规则验证类 +*/ +interface RuleFormType { + templateName: string; + deviceTypeName: string; + bootMode: string[] | string; + machineRoomName: string; + cpuSpec: string; + memSpec: string; + idcId: string; + modelType: string; + arrayCard: string; + // raidCan: any; + name: string; + architecture: string | number; + deviceType: string; + description: string; + modelCPU: string; + cpuInfo: string; + cpuManufacturer: string; + cpuModel: string; + cpuCores: number | string; + cpuFrequency: string; + cpuAmount: string | number; + modelStorage: string; + memInfo: string; + memType: string; + memFrequency: string | number; + memSize: string | number; + memAmount: string | number; + volumeManagerTableData: any; + noConfigurationData: any; + // systemVolumeType: string; + // systemVolumeInterfaceType: string; + // systemVolumeSize: string | number | null; + // systemVolumeUnit: string | number; + // systemVolumeAmount: string | number; + // sysRaid: string[]; + // dataVolumeType: string; + // dataVolumeInterfaceType: string; + // dataVolumeSize: string | null; + // dataVolumeUnit: string | number; + // dataVolumeAmount: number; + nicRate: number | string; + nicAmount: number; + interfaceMode: string | number; + gpuManufacturer: string; + gpuModel: string; + gpuAmount: number; + height: string | number; + cpuData: CpuDataType[]; + memData: MemDataType[]; +}; + +/** + * 规则类 +*/ +interface RulesType { + name: VerifyRulesType[]; + architecture: VerifyRulesType[]; + deviceType: VerifyRulesType[]; + cpuInfo: VerifyRulesType[]; + cpuManufacturer: VerifyRulesType[]; + cpuModel: VerifyRulesType[]; + cpuCores: VerifyRulesType[]; + cpuFrequency: VerifyRulesType[]; + memInfo: VerifyRulesType[]; + memType: VerifyRulesType[]; + memFrequency: VerifyRulesType[]; + memSize: VerifyRulesType[]; + systemVolumeType: VerifyRulesType[]; + systemVolumeInterfaceType: VerifyRulesType[]; + systemVolumeSize: VerifyRulesType[]; + systemVolumeUnit: VerifyRulesType[]; + sysRaid: VerifyRulesType[]; + dataVolumeType: VerifyRulesType[]; + dataVolumeInterfaceType: VerifyRulesType[]; + dataVolumeSize: VerifyRulesType[]; + dataVolumeUnit: VerifyRulesType[]; + dataVolumeAmount: VerifyRulesType[]; + nicRate: VerifyRulesType[]; + nicAmount: VerifyRulesType[]; + interfaceMode: VerifyRulesType[]; + gpuManufacturer: VerifyRulesType[]; + gpuModel: VerifyRulesType[]; + gpuAmount: VerifyRulesType[]; + height: VerifyRulesType[]; +}; + +interface PropsReactiveType { + architecture: string[]; + raidData: any; + volumeTypeData: string[]; + raidConfig: string[]; + noSysRaid: {label: string; value: string}[]; + diskTypeData: {label: string; value: string}[]; + noRaidInterfaceData: {label: string; value: string}[]; + interfaceData: {label: string; value: string}[]; + sysRaid: {label: string; value: string}[]; + sysDiskRaid0: {label: string; value: string}[]; + bootModeData: {label: string; select: boolean;}[]; + computerRoomRadioBtn: {title: string; idcId: string; showTooltip: boolean;}[]; +}; + +interface RadiosPropsType { + hasTemplate: boolean; + formData: {value: CurrencyType;}; cpuSpec: string; memSpec: string; +}; + +export { + key1, + CpuDataType, + MemDataType, + RulesType, + RuleFormType, + ProcessingOperationsType, + RadiosPropsType, + PropsReactiveType, + ReactiveDataType, + IdcNameRadioBtnType +}; diff --git a/bmp-operation-web/src/views/modelManagement/add/utils/dataOperate.ts b/bmp-operation-web/src/views/modelManagement/add/utils/dataOperate.ts new file mode 100644 index 0000000..db75313 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/add/utils/dataOperate.ts @@ -0,0 +1,192 @@ +/** + * @file + * @author +*/ + +import {filterData} from 'utils/index.ts'; +import {language, locationItem, CurrentInstance} from 'utils/publicClass.ts'; +import {CurrencyType} from '@utils/publicType'; +import {CpuDataType, MemDataType, RuleFormType, PropsReactiveType} from '../typeManagement'; +import store from 'store/index.ts'; + +class DataOperate { + idcData = store.idcInfo.idcDataNoOpt; + raidsStore = store.modeFormInfo(); + // 复杂数据类型 + reactiveData: PropsReactiveType = reactive({ + architecture: [], + raidConfig: [], + raidData: {}, + noSysRaid: [], + sysRaid: [], + sysDiskRaid0: [], + volumeTypeData: [ + language.t('modelForm.label.system'), + language.t('modelForm.label.data') + ], + diskTypeData: [ + { + label: 'SSD', + value: 'SSD' + }, + { + label: 'HDD', + value: 'HDD' + }, + { + label: language.t('modelForm.unrestricted'), + value: 'notLimited' + } + ], + noRaidInterfaceData: [ + { + label: 'NVME', + value: 'NVME' + } + ], + interfaceData: [ + { + label: 'SATA', + value: 'SATA' + }, + { + label: 'SAS', + value: 'SAS' + }, + { + label: language.t('modelForm.unrestricted'), + value: 'notLimited' + } + ], + bootModeData: [ + { + select: true, + label: '--' + }, + { + select: true, + label: '--' + } + ], + computerRoomRadioBtn: [ // 机房名称 + { + title: '', + idcId: '', + showTooltip: false + } + ] + }); + ruleForm: any; + proxy = new CurrentInstance().proxy; + constructor (ruleForm: RuleFormType) { + this.ruleForm = ruleForm; + ruleForm.modelCPU = this.#setDefText('common'); + ruleForm.modelStorage = this.#setDefText('common'); + // props + this.architectureData(ruleForm); + if (!this.idcData?.length) { + this.idcList(ruleForm); + return; + }; + this.getIdcData(this.idcData, ruleForm); + }; + + #setDefText = (value: string) => { + const text = new Map([ + ['common', language.t('modelForm.specificationsType.presetSpecifications')] + ]); + return text.get(value)?? language.t('modelForm.specificationsType.otherSpecifications'); + }; + + architectureData = (ruleForm: RuleFormType) => { + this.raidsStore.getCommonData() + .then((res: {architecture: CurrencyType; cpuSpec: CpuDataType[]; memSpec: MemDataType[]; raidRules: CurrencyType; bootMode: string[]}) => { + const {architecture, cpuSpec, memSpec, raidRules, bootMode} = res; + this.reactiveData.raidData = raidRules; + // 无 + const noneInfo = Object.values(raidRules['1']); + // RAID数据 + const raidInfo = Object.values(raidRules['2']); + // 单盘RAID0 + const singleInfo = Object.values(raidRules['3']); + const newNone: {label: string; value: string;}[] = []; + const newRaid: {label: string; value: string;}[] = []; + const singleRaid: {label: string; value: string;}[] = []; + this.reactiveData.noSysRaid = this.#setRaidData(noneInfo, newNone); + this.reactiveData.sysRaid = this.#setRaidData(raidInfo, newRaid); + this.reactiveData.sysDiskRaid0 = this.#setRaidData(singleInfo, singleRaid); + const raidRulesData = Object.values(raidRules); + this.reactiveData.raidConfig = this.#setRaidCan(raidRulesData); + this.reactiveData.architecture = Object.keys(architecture); + this.reactiveData.bootModeData = bootMode.map((item: string) => { + return { + label: item, + select: true + } + }); + ruleForm.cpuData = cpuSpec; + ruleForm.memData = memSpec; + ruleForm.bootMode = bootMode.join(','); + }); + }; + + #setRaidData = (dataInfo: string[], raid: {label: string; value: string;}[]) => { + dataInfo.forEach((item: string) => { + Object.keys(item).forEach((t: any) => { + raid.push({ + label: t, + value: item[t] + }) + }) + }) + return raid; + } + + idcList = async (ruleForm: {machineRoomName: string; idcId: string}) => { + try { + const res = await this.proxy.$idcApi.idcListAPI({isAll: '1'}); + if (res?.data?.result?.idcs?.length) { + const {idcs} = res.data.result; + this.getIdcData(idcs, ruleForm); + } + } + catch { + throw new Error(); + } + }; + + getIdcData = (data: CurrencyType[], ruleForm: {machineRoomName: string; idcId: string}) => { + this.reactiveData.computerRoomRadioBtn = filterData(data, 'name') + .map((item: {name: string; nameEn: string; idcId: string}) => { + return { + ...item, + title: this.#setName(locationItem.getLocationItem, item), + idcId: item.idcId + } + }); + if (!ruleForm.machineRoomName?.length) { + ruleForm.machineRoomName = this.reactiveData.computerRoomRadioBtn[0].title; + ruleForm.idcId = this.reactiveData.computerRoomRadioBtn[0].idcId; + } + }; + + #setName = (name: string, item: CurrencyType) => { + const keyName: Map = new Map([ + ['zh_CN', item.name], + ['en_US', item.nameEn] + ]); + return keyName.get(name); + }; + + #setRaidCan = (raidRulesData: string[]): string[] => { + const raidCan: string[] = []; + raidRulesData.forEach((t: string) => { + Object.keys(t).forEach((g: string) => { + raidCan.push(g); + }) + }) + return raidCan; + } +}; + +export default DataOperate; diff --git a/bmp-operation-web/src/views/modelManagement/add/utils/formRulesEvent.ts b/bmp-operation-web/src/views/modelManagement/add/utils/formRulesEvent.ts new file mode 100644 index 0000000..cf5f066 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/add/utils/formRulesEvent.ts @@ -0,0 +1,96 @@ +/** + * @file + * @author +*/ + +import {RegExpCheck} from './regExpCheck'; +import RegularContent from 'utils/regular.ts'; +import {RuleFormRefType} from '@utils/publicType'; +import {RulesType, RuleFormType} from '../typeManagement'; + +type FormVType = { + name: string;ruleForm: RuleFormType; + rules: RulesType; + ruleFormRef: Ref +}; + +class FormRulesEvent { + formRulesOperate: FormVType; + isLongTip: Ref = ref(false); + isShowLoading: Ref = ref(false); + deviceTypeLoading: Ref = ref(false); + dataVolumeSizeFlag: Ref = ref(false); + systemVolumeSizeFlag: Ref = ref(false); + + constructor (formV: FormVType) { + this.formRulesOperate = formV; + }; + + dataVolumeSizeBlur = () => { + nextTick(async () => { + await this.formRulesOperate.ruleFormRef.value!.validateField('dataVolumeSize', (valid: string) => !valid + ? this.dataVolumeSizeFlag.value = false + : this.dataVolumeSizeFlag.value = true + ); + }); + }; + + nameChange = () => { + this.verifyRepeat(1); + this.verifyNameDevice(this.isShowLoading, 'name'); + }; + + nameBlur = () => { + new RegExpCheck().nameFlag.value = true; + const nameArr = [ + [ + (value: string) => !value, + () => this.isLongTip.value = false + ], + [ + (value: string) => !(RegularContent.modelNameReg.test(value)), + () => { + this.isLongTip.value = true; + } + ], + [ + (value: string) => value, + () => { + new RegExpCheck().nameFlag.value = false; + this.isLongTip.value = false; + } + ] + ]; + for (const key of nameArr) { + if (key[0](this.formRulesOperate.ruleForm.name)) { + key[1](this.formRulesOperate.ruleForm.name); + break; + } + } + }; + + deviceTypeChange = () => { + this.verifyRepeat(0); + this.verifyNameDevice(this.deviceTypeLoading, 'deviceType'); + }; + + verifyRepeat = (type: number) => { + const name = this.formRulesOperate.ruleForm.name; + const deviceType = this.formRulesOperate.ruleForm.deviceType; + if (name === deviceType && name !== '' && deviceType !== '') { + sessionStorage.setItem('repeat', 'true'); + type && this.deviceTypeChange(); + return; + } + sessionStorage.removeItem('repeat'); + }; + + verifyNameDevice = (loading: {value: boolean}, type: string) => { + loading.value = true; + this.formRulesOperate.ruleFormRef.value!.validateField(type, (_: string) => { + loading.value = false; + }); + } +}; + +export default FormRulesEvent; diff --git a/bmp-operation-web/src/views/modelManagement/add/utils/newFormRules.ts b/bmp-operation-web/src/views/modelManagement/add/utils/newFormRules.ts new file mode 100644 index 0000000..916e2b5 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/add/utils/newFormRules.ts @@ -0,0 +1,967 @@ +import {RuleFormRefType} from '@utils/publicType'; +// +import {RuleFormType, RulesType, ProcessingOperationsType} from '../typeManagement' +import reactiveData from './reactiveData'; +import {regExpCheck} from './regExpCheck'; +import {locationItem, language} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; +import RegularContent from 'utils/regular.ts'; +import ModelStaticData from 'staticData/model/index.ts' +import {addModelAPI} from 'api/model/request.ts'; // 添加机型接口 +import {Router, useRouter} from 'vue-router'; +import {msgTip, methodsTotal} from 'utils/index.ts'; +import PageScrollOpt from './pageScroll'; + +interface DataCountType { + tableRef: {}; + hasAddFlag: Ref; + hasAddFlag2: Ref; + raidCanFlag: Ref; + volumeNameTip: Ref; + volumeTypeTip: Ref; + raidCanTip: Ref; + sysRaidTip: Ref; + diskTypeTip: Ref; + interfaceTypeTip: Ref; + minSizeNumTip: Ref; + amountTip: Ref; + isLoading: Ref; + tableHasError: Ref; + tableHasError2: Ref; + tableErrorTip: Ref; + tableErrorTip2: Ref; + // data: any; + ruleFormRef: Ref; + ruleForm: RuleFormType; + rules: RulesType; +}; + +const reactiveDataOperate = reactiveData(); + +// class FormRulesOpt { +// router: Router = useRouter(); +// idcData = store.idcInfo.idcDataNoOpt; +// languages = locationItem.getLocationItem === 'zh_CN'; +// modelFormStore: ProcessingOperationsType = store.modeFormInfo(); +// dataCount = reactive({ + +// }) +// } +const formRules = () => { + const router: Router = useRouter(); + const idcData = store.idcInfo.idcDataNoOpt; + const languages = locationItem.getLocationItem === 'zh_CN'; + const modelFormStore: ProcessingOperationsType = store.modeFormInfo(); + const dataCount: DataCountType = { + tableRef: {}, + volumeNameTip: ref(language.t('modelForm.label.volumeManage.empty.name')), + volumeTypeTip: ref(language.t('modelForm.label.volumeManage.empty.type')), + raidCanTip: ref(language.t('modelForm.label.volumeManage.empty.raidCan')), + sysRaidTip: ref(language.t('modelForm.label.volumeManage.empty.raid')), + diskTypeTip: ref(language.t('modelForm.label.volumeManage.empty.disk')), + interfaceTypeTip: ref(language.t('modelForm.label.volumeManage.empty.interfaceType')), + minSizeNumTip: ref(language.t('modelForm.label.volumeManage.empty.minNum')), + amountTip: ref(''), + isLoading: ref(false), + hasAddFlag: ref(true), + hasAddFlag2: ref(true), + raidCanFlag: ref(false), + // 表单ref + ruleFormRef: ref(), + tableHasError: ref(false), + tableHasError2: ref(false), + tableErrorTip: ref(language.t('modelForm.label.volumeManage.save.empty')), + tableErrorTip2: ref(language.t('modelForm.label.volumeManage.save.empty')), + // 表单数据 + ruleForm: reactive({ + arrayCard: '1', + machineRoomName: languages ? idcData[0]?.name : idcData[0]?.nameEn, + idcId: idcData[0]?.idcId, // idcId + modelType: reactiveDataOperate.modelFormStore.initModelType('computer'), + cpuData: [], // cpu数据 + memData: [], // 内存数据 + bootMode: [], + volumeManagerTableData: [], + noConfigurationData: [], + ...reactiveDataOperate.modelFormStore.ruleForm + }), + // 表单规则 + rules: reactive({ + cpuModel: [ + { + required: true, + trigger: 'blur', + validator: regExpCheck.cpuModelCheck + } + ], + cpuFrequency: [ + { + required: true, + trigger: 'blur', + validator: regExpCheck.cpuFrequencyCheck + } + ], // 主频 + name: [ // 机型名称 + { + required: true, + trigger: 'blur', + validator: regExpCheck.nameCheck + } + ], + deviceType: [ // 机型规格 + { + required: true, + trigger: 'blur', + validator: regExpCheck.deviceTypeCheck + } + ], + volumeManager: [ + { + required: false, + trigger: 'blur', + message: '' + } + ], + ...reactiveDataOperate.modelFormStore.rules + }) + }; + + const setAddClick = () => { + const {arrayCard} = dataCount.ruleForm; + if (arrayCard === '1') { + addVolumeClick(); + return; + } + addVolumeClick2(); + } + + /** + * 获取表格ref + * @param {Object} tableEl 表格信息 + */ + const getTableRef = (tableEl: {[x: string]: unknown}): void => { + dataCount.tableRef = tableEl; + }; + + const addVolumeClick = () => { + if (!dataCount.hasAddFlag.value) return; + dataCount.hasAddFlag.value = false; + dataCount.tableHasError.value = false; + const obj = { + id: new Date().getTime(), + editFlag: false, + volumeName: '', + volumeType: '', + newVolumeType: '', + diskType: '', + minSize: 'GB', + raidCan: '', + amount: 0, + minSizeNum: '', + sysRaid: '', + interfaceType: '', + } + dataCount.ruleForm.volumeManagerTableData.push(obj); + // methodsTotal.initScrollLeft(this.filter.tableRef.value); + }; + + const addVolumeClick2 = () => { + if (!dataCount.hasAddFlag2.value) return; + dataCount.hasAddFlag2.value = false; + dataCount.tableHasError2.value = false; + const obj = { + id: new Date().getTime(), + editFlag: false, + volumeName: '', + volumeType: '', + newVolumeType: '', + diskType: '', + minSize: 'GB', + amount: 1, + minSizeNum: '', + interfaceType: '', + } + dataCount.ruleForm.noConfigurationData.push(obj); + } + + const volumeNameBlur = (val: any, index: number) => { + val[`volumeNameFlag${index}`] = ''; + if (!val.volumeName?.length) { + val[`volumeNameFlag${index}`] = 'error'; + dataCount.volumeNameTip.value = language.t('modelForm.label.volumeManage.empty.name'); + } + else if (!RegularContent.name1Reg.test(val.volumeName)){ + val[`volumeNameFlag${index}`] = 'error'; + dataCount.volumeNameTip.value = language.t('modelForm.errorTip.currency'); + } + else { + val[`volumeNameFlag${index}`] = 'success'; + dataCount.volumeNameTip.value = ''; + } + } + + const volumeTypeChange = (val: any, index: number) => { + val[`volumeTypeFlag${index}`] = ''; + if (!val.volumeType?.length) { + val[`volumeTypeFlag${index}`] = 'error'; + } + else { + if (dataCount.ruleForm.arrayCard === '1') { + const dataTable = dataCount.ruleForm.volumeManagerTableData; + + if (val.volumeType === language.t('modelForm.label.data') && dataTable.length === 1) { + val.volumeType = ''; + val.newVolumeType = ''; + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.sys.tip1') + val[`volumeTypeFlag${index}`] = 'error'; + } + else if (val.volumeType === language.t('modelForm.label.system') && dataTable.length > 1 && dataTable.map((item: {volumeType: string}) => item.volumeType).filter((ite: string) => ite === language.t('modelForm.label.system')).length > 1) { + val.volumeType = ''; + val.newVolumeType = ''; + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.sys.tip2') + val[`volumeTypeFlag${index}`] = 'error'; + } + else { + val[`volumeTypeFlag${index}`] = 'success'; + dataCount.volumeTypeTip.value = '' + val.newVolumeType = val.volumeType; + } + } + else { + const noRaidData = dataCount.ruleForm.noConfigurationData; + if (val.volumeType === language.t('modelForm.label.data') && noRaidData.length === 1) { + val.volumeType = ''; + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.sys.tip1') + val[`volumeTypeFlag${index}`] = 'error'; + val.newVolumeType = ''; + } + else if (val.volumeType === language.t('modelForm.label.system') && noRaidData.length > 1 && noRaidData.map((item: {volumeType: string}) => item.volumeType).filter((ite: string) => ite === language.t('modelForm.label.system')).length > 1) { + val.volumeType = ''; + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.sys.tip2') + val[`volumeTypeFlag${index}`] = 'error'; + val.newVolumeType = ''; + } + else { + val[`volumeTypeFlag${index}`] = 'success'; + dataCount.volumeTypeTip.value = '' + val.newVolumeType = val.volumeType; + } + } + } + }; + + const raidCanChange = (val: any, index: number) => { + val[`raidCanFlag${index}`] = ''; + if (!val.raidCan?.length) { + val[`raidCanFlag${index}`] = 'error'; + } + else { + val[`raidCanFlag${index}`] = 'success'; + dataCount.raidCanTip.value = '' + } + if (val.sysRaid?.length) { + val.sysRaid = '' + val[`sysRaidFlag${index}`] = void 0; + } + if (val.interfaceType) { + val.interfaceType = ''; + val[`interfaceTypeFlag${index}`] = void 0; + } + }; + + const sysRaidChange = (val: any, index: number, data: any) => { + val[`sysRaidFlag${index}`] = ''; + if (typeof val.sysRaid === 'string') { + // if (data[0] === language.t('modelForm.none')) { + // val['newSysRaid'] = [''] + // } + // else { + let newId = data[0].value; + val['newSysRaid'] = [newId]; + // } + } + else { + let d: any = [] + data.forEach((item: any) => { + val.sysRaid.forEach((t: any) => { + if (item.label === t) { + d.push(item.value) + } + + }) + }) + val['newSysRaid'] = d; + } + if (Array.isArray(val.sysRaid)) { + if (val.sysRaid.length > 0) { + val[`sysRaidFlag${index}`] = 'success'; + dataCount.sysRaidTip.value = ''; + } + else { + val[`sysRaidFlag${index}`] = 'error'; + dataCount.sysRaidTip.value = language.t('modelForm.label.volumeManage.empty.raid') + } + } + else { + if (!val.sysRaid?.length) { + val[`sysRaidFlag${index}`] = 'error'; + } + else { + val[`sysRaidFlag${index}`] = 'success'; + dataCount.sysRaidTip.value = '' + } + } + }; + + const diskTypeChange = (val: any, index: number) => { + val[`diskTypeFlag${index}`] = ''; + if (!val.diskType?.length) { + val[`diskTypeFlag${index}`] = 'error'; + // dataCount.raidCanTip.value = language.t('modelForm.label.volumeManage.empty.raidCan') + } + else { + val[`diskTypeFlag${index}`] = 'success'; + dataCount.diskTypeTip.value = '' + } + } + + const interfaceTypeChange = (val: any, index: number) => { + val[`interfaceTypeFlag${index}`] = ''; + if (!val.interfaceType?.length) { + val[`interfaceTypeFlag${index}`] = 'error'; + // dataCount.raidCanTip.value = language.t('modelForm.label.volumeManage.empty.raidCan') + } + else { + val[`interfaceTypeFlag${index}`] = 'success'; + dataCount.interfaceTypeTip.value = '' + } + } + + const minSizeNumBlur = (val: any, index: number) => { + val[`minSizeNumFlag${index}`] = ''; + if (!val.minSizeNum?.length) { + val[`minSizeNumFlag${index}`] = 'error'; + dataCount.minSizeNumTip.value = language.t('modelForm.label.volumeManage.empty.minNum') + // dataCount.raidCanTip.value = language.t('modelForm.label.volumeManage.empty.raidCan') + } + else if (val.minSize === 'TB') { + val[`minSizeNumFlag${index}`] = 'error'; + if (!RegularContent.capacityReg.test(val.minSizeNum)) { + dataCount.minSizeNumTip.value = language.t('modelForm.errorTip.number2') + } + else if ((Number(val.minSizeNum) > 100000)) { + dataCount.minSizeNumTip.value = language.t('modelForm.errorTip.number3'); + } + else { + dataCount.minSizeNumTip.value = '' + val[`minSizeNumFlag${index}`] = 'success'; + } + } + else { + val[`minSizeNumFlag${index}`] = 'error'; + if (!RegularContent.numberReg.test(val.minSizeNum)) { + dataCount.minSizeNumTip.value = language.t('modelForm.errorTip.number1'); + } + else if ((Number(val.minSizeNum) > 100000)) { + dataCount.minSizeNumTip.value = language.t('modelForm.errorTip.number3'); + } + else { + dataCount.minSizeNumTip.value = '' + val[`minSizeNumFlag${index}`] = 'success'; + } + } + } + + const minSizeChange = (val: {minSizeNum: string;}) => { + val.minSizeNum = ''; + } + + watch(() => dataCount.ruleForm.modelCPU, (newValue) => { + const cpuStatus = ModelStaticData.modelSpecData.includes(newValue); + if (cpuStatus) { + regExpCheck.cpuManufacturerFlag.value = false; + regExpCheck.cpuModelFlag.value = false; + regExpCheck.cpuInfoFlag.value = false; + regExpCheck.cpuGHzFlag.value = false; + } + }) + + watch(() => dataCount.ruleForm.modelStorage, (newValue) => { + const memeStatus = ModelStaticData.modelSpecData.includes(newValue); + if (memeStatus) { + regExpCheck.memTypeFlag.value = false; + regExpCheck.memFrequencyFlag.value = false; + regExpCheck.memSizeFlag.value = false; + regExpCheck.memInfoFlag.value = false; + } + }) + + const setAmountMaxSize = (item: any, index: number) => { + if (dataCount.ruleForm.arrayCard === '2' || [language.t('modelForm.raid'), 'NO RAID'].includes(item.raidCan)) { + item.amount = 1; + dataCount.amountTip.value = '' + item[`amountFlag${index}`] = 'success'; + return 1; + } + if (!Array.isArray(item.sysRaid)) return; + // r-l6pounvfife0njlinhk6ztf2xyio + if (item.sysRaid.includes('RAID10')) { + if (item.amount % 4 === 0) { + // item.amountFlag + item[`amountFlag${index}`] = 'success'; + dataCount.amountTip.value = '' + } + return; + } + if (item.sysRaid.includes('RAID1')) { + if (item.amount % 2 === 0) { + item[`amountFlag${index}`] = 'success'; + dataCount.amountTip.value = '' + } + return; + } + + if (item.sysRaid.includes('RAID0')) { + if (item.amount >= 2) { + item[`amountFlag${index}`] = 'success'; + dataCount.amountTip.value = '' + } + return; + } + // // else + // return 1000; + } + + const setAmountMinSize = (item: any, index: number) => { + if (dataCount.ruleForm.arrayCard === '2' || [language.t('modelForm.raid'), 'NO RAID'].includes(item.raidCan)) { + item[`amountFlag${index}`] = 'success'; + return 1; + } + if (!Array.isArray(item.sysRaid) || !item.sysRaid?.length) { + return 1; + }; + // if (item.sysRaid.length === 1) { + // r-l6pounvfife0njlinhk6ztf2xyio + if (item.sysRaid.includes('RAID10')) { + if (item.amount < 4) { + item.amount = 4; + } + // else if (item.amount % 4 !== 0) { + // // item.amountFlag + // item[`amountFlag${index}`] = 'error'; + // dataCount.amountTip.value = '最低4或者大于4的偶数' + // } + return 4; + } + if (item.sysRaid.length === 1 && item.sysRaid.includes('RAID5')) { + item[`amountFlag${index}`] = 'success'; + dataCount.amountTip.value = ''; + if (item.amount < 3) { + item.amount = 3; + } + return 3; + + } + // if (item.sysRaid.includes('RAID1') && item.sysRaid.includes('RAID5')) { + // if (item.amount < 4) { + // item.amount = 4; + // } + // else { + // if (item.amount % 2 === 0) { + // item[`amountFlag${index}`] = 'success'; + // dataCount.amountTip.value = '' + // } + // // else { + // // item[`amountFlag${index}`] = 'error'; + // // dataCount.amountTip.value = '最低2块,或者大于2的偶数' + // // } + // } + // return 4; + // } + if (item.sysRaid.includes('RAID0') && item.sysRaid.includes('RAID5')) { + if (item.amount < 3) { + item.amount = 3; + } + return 3; + } + if (item.sysRaid.includes('RAID1')) { + if (item.amount < 2) { + item.amount = 2; + } + // else if (item.amount % 2 !== 0) { + // // item.amountFlag + // item[`amountFlag${index}`] = 'error'; + // dataCount.amountTip.value = '最低2或者大于2的偶数' + // } + return 2; + } + if (item.sysRaid.includes('RAID0')) { + if (item.amount < 2) { + item.amount = 2; + } + return 2; + } + } + + const sure = async () => { + await dataCount.ruleFormRef.value!.validate((valid: Required) => { + if (!valid) { + regExpCheck.heightFlag.value = true; + regExpCheck.interfaceModeFlag.value = true; + regExpCheck.nicRateFlag.value = true; + new PageScrollOpt().pageScroll(dataCount); + } + const {volumeManagerTableData, noConfigurationData} = dataCount.ruleForm; + const cpuStatus = ModelStaticData.modelSpecData.includes(dataCount.ruleForm.modelCPU); + const memStatus = ModelStaticData.modelSpecData.includes(dataCount.ruleForm.modelStorage); + setFlag(); + setOtherEmpty(cpuStatus, memStatus) + if (dataCount.ruleForm.arrayCard === '1') { + dataCount.tableHasError.value = !(volumeManagerTableData?.length > 0); + if (!dataCount.hasAddFlag.value) { + dataCount.tableHasError.value = true; + dataCount.tableErrorTip.value = language.t('modelForm.label.volumeManage.save.volumeManagement'); + // scrollError() + return + }; + if (dataCount.tableHasError.value) { + dataCount.tableHasError.value = true; + dataCount.tableErrorTip.value = language.t('modelForm.label.volumeManage.save.empty'); + // scrollError() + return; + } + } + else { + dataCount.tableHasError2.value = !(noConfigurationData?.length > 0); + if (!dataCount.hasAddFlag2.value) { + dataCount.tableHasError2.value = true; + dataCount.tableErrorTip2.value = language.t('modelForm.label.volumeManage.save.volumeManagement'); + // scrollError() + return + }; + if (dataCount.tableHasError2.value) { + dataCount.tableHasError2.value = true; + dataCount.tableErrorTip2.value = language.t('modelForm.label.volumeManage.save.empty'); + // scrollError() + return; + } + } + if (valid) { + regExpCheck.heightFlag.value = false; + // let params: any = {} + let cpuBol = false; + let memBol = false; + if (cpuStatus && memStatus) { + cpuBol = false; + memBol = false; + } + else if (cpuStatus && !memStatus) { + cpuBol = false; + memBol = true; + } + else if (!cpuStatus && memStatus) { + cpuBol = true; + memBol = false; + } + else { + cpuBol = true; + memBol = true; + } + + modelFormStore.setCpuMemData(cpuBol, memBol, dataCount.ruleForm) + .then(() => { + requestAddModel(cpuBol, memBol) + }) + } + }) + } + + const setOtherEmpty = (cpuStatus: boolean, memStatus: boolean) => { + if (cpuStatus) { + regExpCheck.cpuManufacturerFlag.value = false; + } + else { + regExpCheck.cpuInfoFlag.value = false; + } + if (memStatus) { + regExpCheck.memTypeFlag.value = false; + regExpCheck.memFrequencyFlag.value = false; + regExpCheck.memSizeFlag.value = false; + } + else { + regExpCheck.memInfoFlag.value = false; + } + } + + /** + * 请求添加机型接口,成功后把事件回传,关闭弹窗 + */ + const requestAddModel = (cpuBol: boolean, memBol: boolean) => { + const {arrayCard, noConfigurationData, gpuManufacturer, gpuModel, gpuAmount, volumeManagerTableData} = dataCount.ruleForm; + // volumeManagerTableData.map + const obj = gpuAmount > 0 ? { + gpuAmount, + gpuModel, + gpuManufacturer + } : {}; + + const volumesData = arrayCard === '1' ? volumeManagerTableData.map((item: any) => { + return { + // ...item, + volumeName: item.volumeName, + volumeType: setVolumeType(item.newVolumeType), + diskType: item.diskType, + interfaceType: item.interfaceType, + // diskType: item.diskType === language.t('modelForm.unrestricted') ? 'notLimited' : item.diskType, + // interfaceType: item.interfaceType === language.t('modelForm.unrestricted') ? 'notLimited' : item.interfaceType, + volumeSize: String(item.minSizeNum), + volumeUnit: item.minSize, + volumeAmount: item.amount, + // raidCan: item.raidCan, + raidCan: ModelStaticData.singleRaid0.includes(item.raidCan) ? 'RAID0-stripping' : item.raidCan, + raid: item.newSysRaid.join(','), + } + }) : noConfigurationData.map((item: any) => { + return { + // ...item, + volumeName: item.volumeName, + volumeType: setVolumeType(item.newVolumeType), + diskType: item.diskType, + interfaceType: item.interfaceType, + // diskType: item.diskType === language.t('modelForm.unrestricted') ? 'notLimited' : item.diskType, + // interfaceType: item.interfaceType === language.t('modelForm.unrestricted') ? 'notLimited' : item.interfaceType, + volumeSize: String(item.minSizeNum), + volumeUnit: item.minSize, + volumeAmount: item.amount, + // raidCan: item.raidCan, + // raid: item.newSysRaid.join(','), + } + }) + if (gpuAmount <= 0) { + const emptyData = ['gpuAmount', 'gpuModel', 'gpuManufacturer']; + for (const key of emptyData) { + Reflect.deleteProperty(dataCount.ruleForm, key) + } + } + + const newParams = { + // ...otherParams, + ...obj, + ...dataCount.ruleForm, + volumes: volumesData, + isNeedRaid: setIsNeedRaid(arrayCard), + // ...dataCount.ruleForm, + cpuSpec: cpuBol ? 'user_defined' : 'common', + memSpec: memBol ? 'user_defined' : 'common', + // cpuManufacturer, + // cpuCores, + // cpuModel, + // cpuAmount, + // cpuFrequency, + // memType, + // memSize, + // memAmount, + // memFrequency, + // ...params, + deviceSeries: modelFormStore.setModelType(dataCount.ruleForm.modelType) + } + + if (arrayCard === '2') { + const status = noConfigurationData.some((item: {volumeType: string}) => item.volumeType === language.t('modelForm.label.system')); + if (!status) { + dataCount.tableHasError2.value = true; + dataCount.tableErrorTip2.value = language.t('modelForm.label.volumeManage.sys.tip1'); + return; + } + } + else { + const status = volumeManagerTableData.some((item: {volumeType: string}) => item.volumeType === language.t('modelForm.label.system')); + if (!status) { + dataCount.tableHasError.value = true; + dataCount.tableErrorTip.value = language.t('modelForm.label.volumeManage.sys.tip1'); + return; + } + } + dataCount.isLoading.value = true; + addModelAPI( + { + ...newParams + } + ).then(({data} : {data: {result: {deviceTypeId: string;}}}) => { + if(data?.result?.deviceTypeId) { + msgTip.success(language.t('operate.success')); + methodsTotal.sendMsg('model-add-success', 'success'); + cancel() + } + }).finally(() => { + dataCount.isLoading.value = false; + }); + }; + + const addOptHasShow = () => { + const {arrayCard} = dataCount.ruleForm; + const {tableHasError, tableHasError2} = dataCount; + return arrayCard === '1' ? tableHasError.value : tableHasError2.value; + } + + + const addOptTipText = () => { + const {arrayCard} = dataCount.ruleForm; + const {tableErrorTip, tableErrorTip2} = dataCount; + return arrayCard === '1' ? tableErrorTip.value : tableErrorTip2.value; + } + + const setAddClass = () => { + const {arrayCard} = dataCount.ruleForm; + // formRulesOperate.ruleForm.volumeManagerTableData?.length && formRulesOperate.hasAddFlag.value ? 'set-top' : '' + return arrayCard === '1' ? setAddBtn() : setAddBtn2(); + } + + const setDataClass = () => { + const {arrayCard, volumeManagerTableData, noConfigurationData} = dataCount.ruleForm; + const {hasAddFlag, hasAddFlag2} = dataCount; + const data = [ + [ + (value: string) => value === '1', + () => volumeManagerTableData?.length && hasAddFlag.value ? 'set-top' : '' + ], + [ + (value: string) => value === '2', + () => noConfigurationData?.length && hasAddFlag2.value ? 'set-up' : '' + ] + ]; + for (const key of data) { + if (key[0](arrayCard)) { + return key[1](arrayCard); + } + } + // return arrayCard === '1' ? volumeManagerTableData?.length && hasAddFlag.value ? 'set-top' : '' + } + + const setVolumeType = (type: string) => { + const obj = new Map([ + [language.t('modelForm.label.system'), 'system'], + [language.t('modelForm.label.data'), 'data'] + ]) + return obj.get(type); + } + + const setIsNeedRaid = (type: string) => { + const obj = { + '1': 'need_raid', + '2': 'no_need_raid' + }; + // @ts-ignore + return obj[type]; + } + + const nicAmountIpt = () => { + if (dataCount.ruleForm.interfaceMode) { + dataCount.ruleForm.interfaceMode = ''; + regExpCheck.interfaceModeFlag.value = true; + } + }; + + + const setFlag = () => { + const data = ['cpuInfo', 'memInfo', 'cpuManufacturer', 'memType', 'memFrequency', 'memSize']; + for (const key of data) { + // @ts-ignore + regExpCheck[`${key}Flag`].value = !(dataCount.ruleForm[key]) + } + } + + const setAddBtn = () => { + const status = dataCount.ruleForm.volumeManagerTableData.every((item: {editFlag: boolean}) => item.editFlag); + dataCount.hasAddFlag.value = status; + return status ? 'active' : 'default-s'; + } + + const setAddBtn2 = () => { + const status = dataCount.ruleForm.noConfigurationData.every((item: {editFlag: boolean}) => item.editFlag); + dataCount.hasAddFlag2.value = status; + return status ? 'active' : 'default-s'; + } + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + const getFormRef = (formEl: {value: RuleFormRefType}) => { + dataCount.ruleFormRef.value = formEl.value; + // setFormRef('ruleFormRef', formEl) + // emitValue('rule-form-ref', dataCount.ruleFormRef); + }; + + const saveClick = (val: any, index: number) => { + const status = val[`volumeNameFlag${index}`] === 'success' && val[`volumeTypeFlag${index}`] === 'success' && val[`diskTypeFlag${index}`] === 'success' && val[`interfaceTypeFlag${index}`] === 'success' && val[`minSizeNumFlag${index}`] === 'success' && val[`amountFlag${index}`] === 'success'; + if (status && val[`raidCanFlag${index}`] === 'success' && val[`sysRaidFlag${index}`] === 'success') { + + val.editFlag = true; + + dataCount.hasAddFlag.value = true; + const hasEverySave = dataCount.ruleForm.volumeManagerTableData.every((item: {editFlag: boolean}) => item.editFlag); + if (hasEverySave) { + dataCount.tableErrorTip.value = ''; + dataCount.tableHasError.value = false; + } + } + if (dataCount.ruleForm.arrayCard === '1') { + if (val[`raidCanFlag${index}`] === void 0) { + dataCount.raidCanTip.value = language.t('modelForm.label.volumeManage.empty.raidCan') + val[`raidCanFlag${index}`] = ''; + } + + if (val[`sysRaidFlag${index}`] === void 0) { + dataCount.sysRaidTip.value = language.t('modelForm.label.volumeManage.empty.raid') + val[`sysRaidFlag${index}`] = ''; + } + + } + if (val[`volumeNameFlag${index}`] === void 0) { + dataCount.volumeNameTip.value = language.t('modelForm.label.volumeManage.empty.name') + val[`volumeNameFlag${index}`] = ''; + + } + if (val[`volumeTypeFlag${index}`] === void 0) { + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.empty.type') + val[`volumeTypeFlag${index}`] = ''; + } + + if (val[`diskTypeFlag${index}`] === void 0) { + dataCount.diskTypeTip.value = language.t('modelForm.label.volumeManage.empty.disk'); + val[`diskTypeFlag${index}`] = ''; + } + + if (val[`interfaceTypeFlag${index}`] === void 0) { + dataCount.interfaceTypeTip.value = language.t('modelForm.label.volumeManage.empty.interfaceType'); + val[`interfaceTypeFlag${index}`] = ''; + } + + if (val[`minSizeNumFlag${index}`] === void 0) { + dataCount.minSizeNumTip.value = language.t('modelForm.label.volumeManage.empty.minNum') + val[`minSizeNumFlag${index}`] = ''; + } + } + + const setDiskInterfaceType = (item: string) => { + return item === 'notLimited' ? language.t('modelForm.unrestricted') : item; + } + + const noConfigurationSaveClick = (val: any, index: number) => { + const status = val[`volumeNameFlag${index}`] === 'success' && val[`volumeTypeFlag${index}`] === 'success' && val[`diskTypeFlag${index}`] === 'success' && val[`interfaceTypeFlag${index}`] === 'success' && val[`minSizeNumFlag${index}`] === 'success'; + if (status) { + val.editFlag = true; + + dataCount.hasAddFlag2.value = true; + const hasEverySave = dataCount.ruleForm.noConfigurationData.every((item: {editFlag: boolean}) => item.editFlag); + if (hasEverySave) { + dataCount.tableErrorTip2.value = ''; + dataCount.tableHasError2.value = false; + } + return; + } + + if (val[`volumeNameFlag${index}`] === void 0) { + dataCount.volumeNameTip.value = language.t('modelForm.label.volumeManage.empty.name') + val[`volumeNameFlag${index}`] = ''; + + } + if (val[`volumeTypeFlag${index}`] === void 0) { + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.empty.type') + val[`volumeTypeFlag${index}`] = ''; + } + + if (val[`diskTypeFlag${index}`] === void 0) { + dataCount.diskTypeTip.value = language.t('modelForm.label.volumeManage.empty.disk'); + val[`diskTypeFlag${index}`] = ''; + } + + if (val[`interfaceTypeFlag${index}`] === void 0) { + dataCount.interfaceTypeTip.value = language.t('modelForm.label.volumeManage.empty.interfaceType'); + val[`interfaceTypeFlag${index}`] = ''; + } + + if (val[`minSizeNumFlag${index}`] === void 0) { + dataCount.minSizeNumTip.value = language.t('modelForm.label.volumeManage.empty.minNum') + val[`minSizeNumFlag${index}`] = ''; + } + + } + + watch(() => [dataCount.ruleForm.gpuManufacturer, dataCount.ruleForm.gpuModel], (newValue) => { + const status = newValue.some(item => item === ''); + if (status) { + dataCount.ruleForm.gpuAmount = 0; + } + }) + + const editClick = (val: {editFlag: boolean;}) => { + val.editFlag = false; + } + + const noConfigurationEditClick = (val: {editFlag: boolean;}) => { + val.editFlag = false; + } + + const deleteClick = (index: number) => { + dataCount.ruleForm.volumeManagerTableData.splice(index, 1); + dataCount.hasAddFlag.value = true; + } + + const noConfigurationDeleteClick = (index: number) => { + dataCount.ruleForm.noConfigurationData.splice(index, 1); + dataCount.hasAddFlag2.value = true; + } + + const cancel = () => { + router.push('/ModelManagement/modelList') + } + + const amountMinValue = () => { + const {gpuModel, gpuManufacturer} = dataCount.ruleForm; + if (gpuModel && gpuManufacturer) { + return 1; + } + return 0; + } + + return { + sure, + ...dataCount, + getFormRef, + getTableRef, + // addVolumeClick, + volumeNameBlur, + volumeTypeChange, + // setRaidInfo, + raidCanChange, + sysRaidChange, + diskTypeChange, + setDiskInterfaceType, + noConfigurationSaveClick, + interfaceTypeChange, + minSizeNumBlur, + minSizeChange, + setAddClick, + // addVolumeClick2, + setAmountMinSize, + setAmountMaxSize, + addOptHasShow, + addOptTipText, + setAddClass, + setDataClass, + setAddBtn, + setAddBtn2, + saveClick, + cancel, + nicAmountIpt, + amountMinValue, + editClick, + noConfigurationEditClick, + deleteClick, + noConfigurationDeleteClick + } +} + +export default formRules; \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/add/utils/pageScroll.ts b/bmp-operation-web/src/views/modelManagement/add/utils/pageScroll.ts new file mode 100644 index 0000000..839b043 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/add/utils/pageScroll.ts @@ -0,0 +1,71 @@ +/** + * @file + * @author +*/ +import ModelStaticData from 'staticData/model/index.ts' + +class PageScrollOpt { + + pageScroll = (dataCount: {ruleForm: {modelCPU: string; modelStorage: string;}}) => { + let defaultType = ['name', 'deviceType']; + let otherType = ['cpuInfo', 'memInfo']; + let defaultType2 = ['nicRate', 'nicAmount', 'interfaceMode', 'height', 'volumeManager']; + let type: string[] = [...defaultType, ...otherType]; + const cpuStatus = ModelStaticData.modelSpecData.includes(dataCount.ruleForm.modelCPU); + const memStatus = ModelStaticData.modelSpecData.includes(dataCount.ruleForm.modelStorage); + const scrollArr = [ + [ + (cpuStatus: boolean, memStatus: boolean) => (cpuStatus && memStatus), + () => { + type = [...type, ...defaultType2]; + this.scrollOpt(type, dataCount) + } + ], + [ + (cpuStatus: boolean, memStatus: boolean) => (!cpuStatus && memStatus), + () => { + otherType = ['cpuManufacturer', 'cpuModel', 'cpuCores', 'cpuFrequency', 'cpuAmount']; + type = [...defaultType, ...otherType, 'memInfo', ...defaultType2]; + this.scrollOpt(type, dataCount); + } + ], + [ + (cpuStatus: boolean, memStatus: boolean) => (cpuStatus && !memStatus), + () => { + otherType = ['memType', 'memFrequency', 'memSize', 'memAmount']; + type = [...defaultType, 'cpuInfo', ...otherType, ...defaultType2]; + this.scrollOpt(type, dataCount); + } + ], + [ + (cpuStatus: boolean, memStatus: boolean) => (!cpuStatus && !memStatus), + () => { + otherType = ['cpuManufacturer', 'cpuModel', 'cpuCores', 'cpuFrequency', 'cpuAmount', 'memType', 'memFrequency', 'memSize', 'memAmount']; + type = [...defaultType, ...otherType, ...defaultType2]; + this.scrollOpt(type, dataCount); + } + ] + ]; + for (const key of scrollArr) { + if (key[0](cpuStatus, memStatus)) { + key[1](cpuStatus, memStatus); + break; + } + } + }; + + scrollOpt = (type: string[], dataCount: { ruleForm: {[x: string]: string}; }) => { + for (const key of type) { + // @ts-ignore + if (!dataCount.ruleForm[key]) { + (document as any).getElementById(key).scrollIntoView({ + block: 'start', + behavior: 'smooth' // 代表平滑滚动 + }); + break; + } + } + }; +} + +export default PageScrollOpt; diff --git a/bmp-operation-web/src/views/modelManagement/add/utils/reactiveData.ts b/bmp-operation-web/src/views/modelManagement/add/utils/reactiveData.ts new file mode 100644 index 0000000..396558c --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/add/utils/reactiveData.ts @@ -0,0 +1,23 @@ +import {StoreGeneric, storeToRefs} from 'pinia'; // store +import {ReactiveDataType} from '..//typeManagement'; +import store from 'store/index.ts'; + +interface DataType { + modelFormStore: StoreGeneric; + reactiveData: ReactiveDataType; +}; + +const reactiveData = () => { + const data: DataType = { + modelFormStore: store.modeFormInfo(), + reactiveData: reactive({ + ...storeToRefs(store.modeFormInfo()).data.value + }) + }; + + return { + ...data + }; +}; + +export default reactiveData; diff --git a/bmp-operation-web/src/views/modelManagement/add/utils/regExpCheck.ts b/bmp-operation-web/src/views/modelManagement/add/utils/regExpCheck.ts new file mode 100644 index 0000000..3f2f1f7 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/add/utils/regExpCheck.ts @@ -0,0 +1,248 @@ +import {resourcesAPI} from 'api/public/request.ts'; +import {language} from 'utils/publicClass.ts'; +import {CallbackType} from '@utils/publicType'; +import RegularContent from 'utils/regular.ts'; + +// type ParamsType = Partial<{name: string; deviceType: string;}>; + +class RegExpCheck { + memSizeFlag: Ref = ref(false); + memFrequencyFlag: Ref = ref(false); + memTypeFlag: Ref = ref(false); + heightFlag: Ref = ref(false); + cpuManufacturerFlag: Ref = ref(false); + interfaceModeFlag: Ref = ref(false); + nicRateFlag: Ref = ref(false); + memInfoFlag: Ref = ref(false); + cpuInfoFlag: Ref = ref(false); + cpuGHzFlag: Ref = ref(false); + cpuModelFlag: Ref = ref(false); + nameFlag: Ref = ref(false); + deviceTypeFlag: Ref = ref(false); + nameLoading: Ref = ref(false); + deviceTypeLoading: Ref = ref(false); + ruleForm: { + minValUnit: string; + } = { + minValUnit: 'GB', + }; + + constructor (minValUnit: string = 'GB') { + this.ruleForm.minValUnit = minValUnit; + }; + + /** + * 机型名称校验 + * @param {Object} _ 占位符 + * @param {string} value 输入项 + * @param {Function} callback 回调函数,返回对应状态 + */ + nameCheck: unknown = (_: unknown, value: string, callback: CallbackType) => { + const nameArr = [ + [ + (value: string) => !value?.length, + () => { + this.nameFlag.value = true; + callback(new Error(language.t('modelForm.emptyTip.modelName'))) + } + ], + [ + (value: string) => value.length > 64, + () => { + this.nameFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.currency2'))) + } + ], + [ + (value: string) => (!RegularContent.modelNameReg.test(value)), + () => { + this.nameFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.currency'))) + } + ], + [ + (value: string) => value, + () => { + const name: string = sessionStorage.getItem('propsName')??''; + const status: string = sessionStorage.getItem('hasTemplate')??''; + this.nameLoading.value = true; + if (name === value && status !== 'success') { + this.nameFlag.value = false; + this.nameLoading.value = false; + callback(); + } + else { + resourcesAPI( + { + name: value + } + ) + .then(({data} : {data: {result: {success: boolean;}}}) => { + if (data?.result?.success) { + this.nameFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.name'))); + return; + } + return Promise.reject(); + }) + .catch(() => { + this.nameFlag.value = false; + callback(); + }) + .finally(() => { + this.nameLoading.value = false; + }) + } + } + ] + ]; + for (const key of nameArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + /** + * 机型规格校验 + * @param {Object} _ 占位符 + * @param {string} value 输入项 + * @param {Function} callback 回调函数,返回对应状态 + */ + deviceTypeCheck: unknown = (_: unknown, value: string, callback: CallbackType) => { + const deviceTypeArr = [ + [ + (value: string) => !value?.length, + () => { + this.deviceTypeFlag.value = true; + callback(new Error(language.t('modelForm.emptyTip.modelSpecifications'))) + } + ], + [ + (value: string) => value.length > 64, + () => { + this.deviceTypeFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.currency2'))) + } + ], + [ + (value: string) => (value && sessionStorage?.getItem('repeat')), + () => { + this.deviceTypeFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.modelSpecifications'))) + } + ], + [ + (value: string) => value, + () => { + const deviceType = sessionStorage?.getItem('propsDeviceType'); + const status = sessionStorage.getItem('hasTemplate'); + this.deviceTypeLoading.value = true; + if (deviceType === value && status !== 'success') { + this.deviceTypeFlag.value = false; + this.deviceTypeLoading.value = false; + callback(); + } + else { + resourcesAPI( + { + deviceType: value + } + ) + .then(({data} : {data: {result: {success: boolean;}}}) => { + if (data?.result?.success) { + this.deviceTypeFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.specifications'))); + return; + } + return Promise.reject(); + }) + .catch(() => { + this.deviceTypeFlag.value = false; + callback(); + }) + .finally(() => { + this.deviceTypeLoading.value = false; + }) + } + } + ] + ]; + for (const key of deviceTypeArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + /** + * cpu型号 + * @param {string} str 提示项 + * @param {string} trigger 判断时机-change/blur + */ + cpuModelCheck = (_: {}, value: string, callback: (arg0?: Error) => void) => { + this.cpuModelFlag.value = true; + const cpuModelArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t('modelForm.emptyTip.modelChoose'))) + ], + [ + (value: string) => value.length > 64, + () => callback(new Error(language.t('modelForm.errorTip.currency2'))) + ], + [ + (value: string) => value, + () => { + callback(); + this.cpuModelFlag.value = false; + } + ] + ]; + for (const key of cpuModelArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + /** + * CPU-主频 + */ + cpuFrequencyCheck = (_: unknown, value: string, callback: (arg0?: Error) => void) => { + this.cpuGHzFlag.value = true; + const cpuFrequencyArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t('modelForm.emptyTip.dominantFrequency'))) + ], + [ + (value: string) => (!RegularContent.capacityReg.test(value)), + () => callback(new Error(language.t('modelForm.errorTip.number'))) + ], + [ + (value: string) => value, + () => { + callback(); + this.cpuGHzFlag.value = false; + } + ] + ]; + for (const key of cpuFrequencyArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; +}; + +const regExpCheck: RegExpCheck = new RegExpCheck(); + +export { + RegExpCheck, + regExpCheck +}; diff --git a/bmp-operation-web/src/views/modelManagement/detail/addImage/addBtn.vue b/bmp-operation-web/src/views/modelManagement/detail/addImage/addBtn.vue new file mode 100644 index 0000000..0609afc --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/addImage/addBtn.vue @@ -0,0 +1,30 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/detail/addImage/addImage.ts b/bmp-operation-web/src/views/modelManagement/detail/addImage/addImage.ts new file mode 100644 index 0000000..a4ee18e --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/addImage/addImage.ts @@ -0,0 +1,34 @@ +const addImageOperate = (resetOperate: any) => { + // 添加镜像弹窗状态-默认false + const addImageDialog: Ref = ref(false); + + /** + * 添加镜像点击事件 + * @return {boolean} addImageDialog.value 添加镜像组件弹窗状态 + */ + const addImageClick = (): boolean => { + return addImageDialog.value = !addImageDialog.value; + }; + + /** + * 添加镜像取消事件,关闭弹窗 + * @param {boolean} type 弹窗状态 + * @return {boolean} addImageDialog.value 弹窗状态 + */ + const addImageCancel = (type: boolean): boolean => { + return addImageDialog.value = type; + }; + + const addImageSure = () => { + resetOperate(); + }; + + return { + addImageDialog, + addImageClick, + addImageCancel, + addImageSure + } +}; + +export default addImageOperate; diff --git a/bmp-operation-web/src/views/modelManagement/detail/addImage/addImage.vue b/bmp-operation-web/src/views/modelManagement/detail/addImage/addImage.vue new file mode 100644 index 0000000..47bf7d9 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/addImage/addImage.vue @@ -0,0 +1,25 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/detail/all.ts b/bmp-operation-web/src/views/modelManagement/detail/all.ts new file mode 100644 index 0000000..1a3d9a6 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/all.ts @@ -0,0 +1,31 @@ +import tableScrollOperate from './table/tableScroll'; +import BasicInfo from './baseInfo/base'; +import addImageOperate from './addImage/addImage'; +import PaginationOperate from './pagination/pagination'; +import deleteImageOperate from './deleteImage/delete'; +import deleteModelOperate from './drop/deleteModel/delete'; +// import AddIdenticalModelOperate from './addIdenticalModel/identicalModel'; +// import EditModelOperate from './drop/EditModel/edit'; +import EditModelOpt from './drop/editModel/edit'; +import ModelTemplateOpt from './drop/addModelTemplate/modelTemplate'; +import tabsOperate from './tabs/active'; +import initData from './initData/init'; +import FilterOperate from './table/tableFilter'; +import TableDetail from './table/tableDetail'; +import resetOperate from './table/dataReset'; + +export { + tableScrollOperate, + BasicInfo, + addImageOperate, + PaginationOperate, + deleteImageOperate, + deleteModelOperate, + ModelTemplateOpt, + EditModelOpt, + tabsOperate, + initData, + FilterOperate, + TableDetail, + resetOperate +}; diff --git a/bmp-operation-web/src/views/modelManagement/detail/baseInfo/base.ts b/bmp-operation-web/src/views/modelManagement/detail/baseInfo/base.ts new file mode 100644 index 0000000..4d38fe9 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/baseInfo/base.ts @@ -0,0 +1,80 @@ +/** + * @file + * @author +*/ + +import {msgTip} from 'utils/index.ts'; +import {CurrencyType} from '@utils/publicType'; +import {modelDetailAPI} from 'api/model/request.ts'; +import {CurrentInstance, language} from 'utils/publicClass.ts'; +import ModelStaticData from 'staticData/model/index.ts' +import AllStaticData from 'staticData/staticData.ts'; + +class BasicInfo { + basicInfoLoading: Ref = ref(true); + // 是否请求机型详情-默认true + isRequestmodelDetail: Ref = ref(true); + reactiveArr: any = reactive({ + // tableRef: {}, + // filterParams: {}, + type1: 0, + type2: 0, + detail: {}, + formData: {} + }); + dataInit: any; + router: any; + tableList?: any; + instanceProxy = new CurrentInstance().proxy; + + constructor (dataInit: any, router: any, tableList?: any) { + this.dataInit = dataInit; + this.router = router; + this.tableList = tableList; + }; + + getModelDetail = (): void => { + this.basicInfoLoading.value = true; + modelDetailAPI( + { + id: this.dataInit.deviceTypeId + } + ).then(({data}: {data: {result: CurrencyType}}) => { + if (data?.result && Object.keys(data.result)?.length) { + this.reactiveArr.detail = data.result; + this.reactiveArr.formData.value = this.reactiveArr.detail; + this.reactiveArr.type1 = data.result.instanceCount; + this.reactiveArr.type2 = data.result.deviceCount; + this.isRequestmodelDetail.value = false; + this.basicInfoLoading.value = false; + return; + } + this.basicInfoLoading.value = false; + }).catch(({message} : {message: string;}) => { + const path: string = this.instanceProxy.$defInfo.routerPath('modelList'); + if (AllStaticData.noFoundData.includes(message)) { + this.router.push(path); + return; + } + this.basicInfoLoading.value = false; + // !this.tableList.errorTip && + msgTip.error(message); + this.isRequestmodelDetail.value = true; + }).finally(() => { + if (this.dataInit.routerType === 'image') { + if (this.dataInit.ossStore?.source?.length) return; + this.dataInit.ossStore?.getOssData(); + } + }); + }; + + setDiskInterfaceType = (item: string) => { + return item === 'notLimited' ? language.t('modelForm.unrestricted') : item; + } + + setRaidCan = (raidCan: string) => { + return ModelStaticData.singleRaid0.includes(raidCan) ? language.t('modelForm.raid') : raidCan + } +}; + +export default BasicInfo; diff --git a/bmp-operation-web/src/views/modelManagement/detail/baseInfo/baseInfo.vue b/bmp-operation-web/src/views/modelManagement/detail/baseInfo/baseInfo.vue new file mode 100644 index 0000000..7e05eae --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/baseInfo/baseInfo.vue @@ -0,0 +1,457 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/detail/deleteImage/delete.ts b/bmp-operation-web/src/views/modelManagement/detail/deleteImage/delete.ts new file mode 100644 index 0000000..bdbde83 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/deleteImage/delete.ts @@ -0,0 +1,48 @@ +interface DataType { + deleteImageDiaLog: Ref; + imageId: Ref; + imageInfo: Ref; +} + +const deleteImageOperate = (tableDetail: any) => { + const data: DataType = { + // 删除镜像组件弹窗 默认false + deleteImageDiaLog: ref(false), + // 镜像id + imageId: ref(''), + // 镜像信息,删除镜像时传递的信息 + imageInfo: ref('') + }; + + /** + * 删除镜像点击事件 + * @return {boolean} deleteImageDiaLog.value 删除镜像组件弹窗状态 + */ + const deleteImageClick = (item: {imageName: string; imageId: string;}): boolean => { + data.imageInfo.value = item.imageName; + data.imageId.value = item.imageId; + return data.deleteImageDiaLog.value = !data.deleteImageDiaLog.value; + }; + + /** + * 删除镜像弹窗取消事件 + * @param {boolean} type false 弹窗关闭 + * @return {boolean} deleteImageDiaLog.value 删除镜像弹窗关闭 + */ + const deleteImageCancel = (type: boolean): boolean => { + return data.deleteImageDiaLog.value = type; + }; + + const deleteImageSure = () => { + tableDetail.init(); + }; + + return { + ...data, + deleteImageClick, + deleteImageCancel, + deleteImageSure + } +}; + +export default deleteImageOperate; diff --git a/bmp-operation-web/src/views/modelManagement/detail/deleteImage/imageDelete.vue b/bmp-operation-web/src/views/modelManagement/detail/deleteImage/imageDelete.vue new file mode 100644 index 0000000..0fd1c81 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/deleteImage/imageDelete.vue @@ -0,0 +1,21 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/detail/drop/addModelTemplate/modelTemplate.ts b/bmp-operation-web/src/views/modelManagement/detail/drop/addModelTemplate/modelTemplate.ts new file mode 100644 index 0000000..004f18c --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/drop/addModelTemplate/modelTemplate.ts @@ -0,0 +1,22 @@ +/** + * @file + * @author +*/ + +class ModelTemplateOpt { + proxy; + router; + + constructor(proxy: {$defInfo: {routerPath(arg0: string): void}}, router: {push(arg0: string): void}) { + this.proxy = proxy; + this.router = router; + } + + addModelTemplateClick = (item: T) => { + const path = this.proxy.$defInfo.routerPath('addModelTemplate') + localStorage.setItem('model-item', JSON.stringify(item)); + this.router.push(`${path}?deviceType=${item.deviceType}`) + } +} + +export default ModelTemplateOpt; diff --git a/bmp-operation-web/src/views/modelManagement/detail/drop/deleteModel/delModel.vue b/bmp-operation-web/src/views/modelManagement/detail/drop/deleteModel/delModel.vue new file mode 100644 index 0000000..73f589b --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/drop/deleteModel/delModel.vue @@ -0,0 +1,25 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/detail/drop/deleteModel/delete.ts b/bmp-operation-web/src/views/modelManagement/detail/drop/deleteModel/delete.ts new file mode 100644 index 0000000..1ad2286 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/drop/deleteModel/delete.ts @@ -0,0 +1,51 @@ +interface DataType { + deleteModelDiaLog: Ref; + modelInfo: Ref; +} +interface BaseInfoType { + reactiveArr: { + detail: { + name: string; + } + } +} +const deleteModelOperate = (baseInfo: BaseInfoType) => { + const data: DataType = { + // 删除机型弹窗状态-默认false + deleteModelDiaLog: ref(false), + // 机型信息,删除机型时传递的信息 + modelInfo: ref('') + } + + /** + * 删除机型点击事件 + * @return {boolean} deleteModelDiaLog.value 删除机型组件弹窗状态 + */ + const deleteModelClick = (): boolean => { + data.modelInfo.value = baseInfo.reactiveArr.detail.name; + return data.deleteModelDiaLog.value = !data.deleteModelDiaLog.value; + }; + + /** + * 删除机型弹窗取消事件 + * @param {boolean} type false 弹窗关闭 + * @return {boolean} data.deleteModelDiaLog.value 删除机型弹窗关闭 + */ + const deleteModelCancel = (type: boolean): boolean => { + return data.deleteModelDiaLog.value = type; + }; + + const deleteModelError = () => { + (baseInfo as any).getModelDetail(); + // location.reload(); + }; + + return { + ...data, + deleteModelClick, + deleteModelCancel, + deleteModelError + } +}; + +export default deleteModelOperate; diff --git a/bmp-operation-web/src/views/modelManagement/detail/drop/dropDown.vue b/bmp-operation-web/src/views/modelManagement/detail/drop/dropDown.vue new file mode 100644 index 0000000..b6eb511 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/drop/dropDown.vue @@ -0,0 +1,68 @@ + + + diff --git a/bmp-operation-web/src/views/modelManagement/detail/drop/editModel/edit.ts b/bmp-operation-web/src/views/modelManagement/detail/drop/editModel/edit.ts new file mode 100644 index 0000000..c0691c5 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/drop/editModel/edit.ts @@ -0,0 +1,23 @@ +/** + * @file + * @author +*/ + +class EditModelOpt { + proxy; + router; + + constructor(proxy: {$defInfo: {routerPath(arg0: string): void}}, router: {push(arg0: string): void}) { + this.proxy = proxy; + this.router = router; + } + + editModelClick = (item: T) => { + if (item.deviceCount !== 0) return; + const path = this.proxy.$defInfo.routerPath('editModel') + localStorage.setItem('model-item', JSON.stringify(item)); + this.router.push(`${path}?deviceType=${item.deviceType}`) + } +} + +export default EditModelOpt; diff --git a/bmp-operation-web/src/views/modelManagement/detail/initData/init.ts b/bmp-operation-web/src/views/modelManagement/detail/initData/init.ts new file mode 100644 index 0000000..22d4d46 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/initData/init.ts @@ -0,0 +1,17 @@ +import store from 'store/index.ts'; + +const initData = (router: any) => { + const {query} = router?.currentRoute?.value; + const data = { + routerType: query?.type, + deviceTypeId: query?.deviceTypeId, + ossStore: store.ossDataInfo() + }; + + return { + query, + ...data + } +}; + +export default initData; diff --git a/bmp-operation-web/src/views/modelManagement/detail/modelDetail.scss b/bmp-operation-web/src/views/modelManagement/detail/modelDetail.scss new file mode 100644 index 0000000..204a158 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/modelDetail.scss @@ -0,0 +1,36 @@ +@import '@/assets/css/detail.scss'; + +.model-detail { + .en-model-info { + .el-tabs__nav { + margin-left: -4px; + } + } + + .zh-model-info { + .el-tabs__nav { + margin-left: 6px; + } + } + + &-basic-content { + padding: 0 !important; + } + + .info-content { + padding: 0 !important; + } + + .operate-management-detail-info { + margin-top: 16px; + } + + .add-image-btn { + // background: $background1; + border-radius: 15px; + font-size: $fontSize; + // color: $color3; + font-weight: 500; + margin-bottom: 21px; + } +} diff --git a/bmp-operation-web/src/views/modelManagement/detail/modelDetail.vue b/bmp-operation-web/src/views/modelManagement/detail/modelDetail.vue new file mode 100644 index 0000000..66c9c8a --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/modelDetail.vue @@ -0,0 +1,119 @@ + + + diff --git a/bmp-operation-web/src/views/modelManagement/detail/module.ts b/bmp-operation-web/src/views/modelManagement/detail/module.ts new file mode 100644 index 0000000..858f8af --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/module.ts @@ -0,0 +1,27 @@ +import TabsData from './tabs/tabs.vue'; +import TableData from './table/tableData.vue'; +import BaseInfo from './baseInfo/baseInfo.vue'; +import AddImageBtn from './addImage/addBtn.vue'; +import AddImageC from './addImage/addImage.vue'; +import DropDownOperate from './drop/dropDown.vue'; +import Pagination from './pagination/pagination.vue'; +// import ModelEdit from './drop/EditModel/modelEdit.vue'; +import ImageDelete from './deleteImage/imageDelete.vue'; +import ModelDelete from './drop/deleteModel/delModel.vue'; +// import AddModelTemplate from './addIdenticalModel/addIdenticalModel.vue'; + +const pluginComp = { + TabsData, + TableData, + BaseInfo, + AddImageC, + AddImageBtn, + DropDownOperate, + Pagination, + // ModelEdit, + ImageDelete, + ModelDelete, + // AddModelTemplate +}; + +export default pluginComp; diff --git a/bmp-operation-web/src/views/modelManagement/detail/page.ts b/bmp-operation-web/src/views/modelManagement/detail/page.ts new file mode 100644 index 0000000..8c52423 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/page.ts @@ -0,0 +1,10 @@ +const ModelDetail = () => import(/* webpackChunkName: "ModelDetail" */ './modelDetail.vue'); + +export default { + path: '/ModelManagement/modelDetail', + name: 'ModelDetail', + component: ModelDetail, + meta: { + type: 'modelDetail' + } +}; diff --git a/bmp-operation-web/src/views/modelManagement/detail/pagination/pagination.ts b/bmp-operation-web/src/views/modelManagement/detail/pagination/pagination.ts new file mode 100644 index 0000000..1efb3ee --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/pagination/pagination.ts @@ -0,0 +1,28 @@ +import {paginationOperate} from 'utils/publicClass.ts'; + +/** + * 分页监听 +*/ +class PaginationOperate { + + // 构造器 + constructor (list: any, filter: any) { + this.watchSizeNumber(list, filter); + }; + + /** + * 监听分页页数、条数变化 + */ + watchSizeNumber = (list: any, filter: any) => { + + watch(() => [ + paginationOperate.pageSize.value, + paginationOperate.pageNumber.value + ], (_: boolean[]): void => { + if (paginationOperate.routerChange.value) return; + list.setFilterData(filter.reactiveArr, 'filter'); + }); + }; +}; + +export default PaginationOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/detail/pagination/pagination.vue b/bmp-operation-web/src/views/modelManagement/detail/pagination/pagination.vue new file mode 100644 index 0000000..e9e2453 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/pagination/pagination.vue @@ -0,0 +1,27 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/detail/table/dataReset.ts b/bmp-operation-web/src/views/modelManagement/detail/table/dataReset.ts new file mode 100644 index 0000000..ce81d89 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/table/dataReset.ts @@ -0,0 +1,14 @@ +// 重置操作 +const resetOperate = (filter: any, tableDetail: any) => { + const reset = () => { + filter.tableRef.value?.clearFilter(); + filter.reactiveArr.filterParams = {}; + tableDetail.init(); + }; + + return { + reset + } +}; + +export default resetOperate; diff --git a/bmp-operation-web/src/views/modelManagement/detail/table/filterStyle.ts b/bmp-operation-web/src/views/modelManagement/detail/table/filterStyle.ts new file mode 100644 index 0000000..03b29d8 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/table/filterStyle.ts @@ -0,0 +1,129 @@ +class FilterStyleOperate { + classNameData = [ + { + name: 'def-type-status1', + type: 'source' + }, + { + name: 'def-type-status2', + type: 'osType' + } + ]; + filterStatus: any = reactive({ + source: false, + osType: false + }) + + constructor (props: any) { + onMounted(() => { + nextTick(() => { + this.customFilter(props); + }) + this.watchSearchTip(props); + this.watchFilter(props); + }) + }; + + watchSearchTip = (props: any) => { + watch(() => + props.tableDetail.searchTip, (newValue) => { + if (!newValue.value) { + for (let index in this.filterStatus) { + this.filterStatus[index] = false; + } + } + else { + this.setFilterStatus(props.filterOperate.reactiveArr.filterParams); + } + }, { + deep: true + }); + }; + + watchFilter = (props: any) => { + watch(() => props.filterOperate.reactiveArr.filterParams, (newValue) => { + this.setFilterStatus(newValue); + }, {deep: true}) + }; + + setFilterStatus = (params: any) => { + this.classNameData.forEach((item) => { + if (['', void 0].includes(params[item.type])) { + this.filterStatus[item.type] = false; + return; + } + this.filterStatus[item.type] = true; + }) + }; + + customFilter = (props: any) => { + let filterName: HTMLElement | null; + let filterOpt: HTMLElement | null; + this.classNameData.forEach((item) => { + filterName = document.querySelector(`.${item.name} > .cell`); + filterOpt = document.querySelector(`.${item.name} > .cell > .el-table__column-filter-trigger`) + filterName?.addEventListener('click', (event) => { + event.stopPropagation(); + // this.filterStatus[item.type] = false; + for (let index in this.filterStatus) { + this.filterStatus[index] = false; + } + }) + filterOpt?.addEventListener('click', () => { + if (!props.tableDetail.searchTip.value) { + const clickStatus: any = { + 'source': () => this.filterStatus['osType'] = false, + 'osType': () => this.filterStatus['source'] = false + }; + clickStatus[item.type](); + } + this.filterStatus[item.type] = !this.filterStatus[item.type]; + }); + const filterOtherRegion = document.querySelectorAll('.el-table-filter'); + filterOtherRegion.forEach((_, index) => { + filterOtherRegion[index]?.addEventListener('click', (event) => { + event.stopPropagation(); + for (let index in this.filterStatus) { + for (const key of this.classNameData) { + if (key.type === index && props.tableDetail.filter?.reactiveArr?.filterParams[key.type]?.length) { + this.filterStatus[index] = true; + } + } + } + }) + }) + let newType = []; + document.addEventListener('click', () => { + newType = []; + newType.push(item.type); + newType.forEach((ite) => { + this.filterDispose(ite, props); + }) + }) + }) + }; + + filterDispose = (type: string, props: any) => { + const filterVal = props.filterOperate.reactiveArr.filterParams; + if (props.tableDetail.searchTip.value) { + for (let key in filterVal) { + if (key === type) { + this.filterStatus[key] = true; + } + else { + if (this.filterStatus[type] && Object.keys(filterVal).length > 1) { + this.filterStatus[type] = !this.filterStatus[type]; + } + else { + this.filterStatus[type] = false; + } + } + } + } + else { + this.filterStatus[type] = false; + } + } +}; + +export default FilterStyleOperate; diff --git a/bmp-operation-web/src/views/modelManagement/detail/table/setEmpty.ts b/bmp-operation-web/src/views/modelManagement/detail/table/setEmpty.ts new file mode 100644 index 0000000..2ada3c5 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/table/setEmpty.ts @@ -0,0 +1,64 @@ +/** + * @file + * @author +*/ + +import {language} from 'utils/publicClass.ts'; + +const p = document.createElement('p'); + +interface PropsType { + tableDetail: { + reactiveArr: { + tableData: [] + } + } +} + +class SetEmpty { + emitValue: Function; + + constructor(props: PropsType, emitValue: Function) { + this.emitValue = emitValue; + this.watchTableData(props); + onUnmounted(() => p.innerHTML = ''); + }; + + watchTableData = (props: PropsType) => { + watch(() => props?.tableDetail?.reactiveArr.tableData, (newValue) => { + if (!newValue?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.innerHTML= ''; + }) + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + ai!.innerHTML = ''; + const customText = document.querySelector('.model-detail-image .el-scrollbar__view'); + if (!customText) return; + const str = ` + + ${language.t('table.empty')},${language.t('table.tip')} + + + ${language.t('modelDetail.tabs.relationImage.header.addImage')} + + ` + const parser = new DOMParser(); + const doc = parser.parseFromString(str, 'text/html'); + p.className = 'custom-tip-count'; + p.innerHTML = doc.body.innerHTML; + customText.appendChild(p) + const clickOpt = document.querySelector('.model-detail-image .custom-tip-count .empty-text'); + clickOpt!.addEventListener('click', () => { + this.emitValue('empty-click') + }); + }; +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/modelManagement/detail/table/tableData.vue b/bmp-operation-web/src/views/modelManagement/detail/table/tableData.vue new file mode 100644 index 0000000..1c81822 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/table/tableData.vue @@ -0,0 +1,219 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/detail/table/tableDetail.ts b/bmp-operation-web/src/views/modelManagement/detail/table/tableDetail.ts new file mode 100644 index 0000000..957bb24 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/table/tableDetail.ts @@ -0,0 +1,114 @@ +import {msgTip} from 'utils/index.ts'; +import {CurrencyType} from '@utils/publicType'; +import {paginationOperate} from 'utils/publicClass.ts'; +import {relationImageListAPI} from 'api/model/request.ts'; +import store from 'store/index.ts'; +import ModelStaticData from 'staticData/model/index.ts'; + +class TableDetail { + searchTip: Ref = ref(false); + // ui库内置的国际化 + // locale = languageSwitch(); + errorTip: boolean = false; + filterEmptyInfo = store.filterEmpty; + // loading态 + isLoading: Ref = ref(true); + // architectureName: LocationQueryValue | LocationQueryValue[] = dataInit.query?.architecture; + // 是否请求镜像列表-默认true + isRequestImageList: Ref = ref(false); + systemPartitionInfo = store.sysPartitionInfo; + hasDisabled: Ref = ref(true); + reactiveArr: any = reactive({ + tableData: [] // 表格关联镜像数据 + }); + filter: any = {}; + dataInit: any; + baseInfo: any; + tableS: any; + + constructor (dataInit: any, baseInfo: any) { + this.dataInit = dataInit; + this.baseInfo = baseInfo; + }; + + init = () => { + this.getImageListData(); + }; + + setFilterData = (params: any, type: string) => { + // this.type = type; + // if (type === 'search') this.search = params; + if (type === 'filter') this.filter = params; + this.getImageListData(); + }; + + getImageListData = () => { + this.isLoading.value = true; + this.filterEmptyInfo.deleteEmtpyData(this.filter.filterParams); + // const id = deviceTypeId; + const params: any = {deviceTypeId: this.dataInit.deviceTypeId, ...this.filter.filterParams}; + relationImageListAPI( + { + ...params, + pageNumber: paginationOperate.pageNumber.value, + pageSize: paginationOperate.pageSize.value, + architecture: this.dataInit.query?.architecture + } + ).then(({data} : {data: {result: {totalCount: number, deviceTypes: CurrencyType[]}}}) => { + if (data?.result?.deviceTypes?.length) { + this.isRequestImageList.value = false; + this.reactiveArr.tableData = data.result.deviceTypes.map((item: CurrencyType, index: number) => { + ModelStaticData.modelDetailTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }) + const systemPartition = JSON.parse((item?.systemPartition?.length ? item?.systemPartition : '[]')); + return { + ...item, + newSystemPartition: systemPartition + } + }); + paginationOperate.total.value = data.result.totalCount; + this.errorTip = false; + return; + } + return Promise.reject(''); + }).catch(({message}: {message: string}) => { + message && msgTip.error(message); + paginationOperate.total.value = 0; + this.reactiveArr.tableData = []; + this.isRequestImageList.value = true; + this.errorTip = true; + }).finally(() => { + const {source, osType} = this.filter.filterParams || {}; + this.searchTip.value = (source?.length || osType?.length) ? true : false; + this.isLoading.value = false; + if (this.dataInit.routerType === 'image' && this.baseInfo.isRequestmodelDetail.value) { + this.baseInfo.getModelDetail(); + } + this.getImageAll(); + }) + }; + + getImageAll = () => { + relationImageListAPI( + { + deviceTypeId: this.dataInit.deviceTypeId, + pageNumber: 1, + pageSize: 20, + architecture: this.dataInit.query?.architecture + } + ) + .then(({data} : {data: {result: {totalCount: number, deviceTypes: CurrencyType[]}}}) => { + if (data?.result?.deviceTypes?.length) { + this.hasDisabled.value = data.result.totalCount >= 20; + return; + } + return Promise.reject(); + }) + .catch(() => { + this.hasDisabled.value = false; + }) + } +}; + +export default TableDetail; diff --git a/bmp-operation-web/src/views/modelManagement/detail/table/tableFilter.ts b/bmp-operation-web/src/views/modelManagement/detail/table/tableFilter.ts new file mode 100644 index 0000000..9352bbb --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/table/tableFilter.ts @@ -0,0 +1,95 @@ +import store from 'store/index.ts'; +import {CurrencyType} from '@utils/publicType'; +import {paginationOperate} from 'utils/publicClass.ts'; + +class FilterOperate { + // store库存储的oss数据类 + ossStore: any = store.ossDataInfo(); + // modelDetailStore(); + // tableRef: any; + tableRef: { + [x: string]: unknown; + value?: { + clearFilter(): Function; + }; + } = {}; + filterEmptyInfo: { // store + filterParams( + arg0: {[x: string]: number | string}, + arg1: any, + arg2: any, + arg3: {source: string; osType: string;} + ): Promise; + deleteEmtpyData(arg0: {source: string; osType: string;}): unknown; + } = store.filterEmpty; + // 复杂数据类型 + reactiveArr: { + filterParams: {source: string; osType: string;}; + } = reactive<{ + filterParams: {source: string; osType: string;}; + }>({ + filterParams: { + source: '', + osType: '' + } + }); + modelDetail: any; + + // 构造器 + constructor (modelDetail: any) { + this.modelDetail = modelDetail; + this.ossStore?.getOssData(); + }; + + /** + * 获取表格ref + * @param {Object} tableEl 表格信息 + */ + getTableRef = (tableEl: {[x: string]: unknown}): void => { + this.tableRef = tableEl; + }; + + /** + * 操作系统平台筛选 + */ + operateSysFilter = (): boolean => { + // return row.osType = (reactiveArr as any).osType[value - 1].text; + // return row.osType === this.ossStore?.osType[value - 1]?.text; + // value: number, row: {osType: string} + return true; + }; + + /** + * 镜像类型筛选 + * @param {number} value 当前选中的value值 + * @param {Object} row 当前点击的这一项 + * @param {string} sourceName sourceName + * @return {string} row.sourceName 赋值 + */ + imageTypeFilter = (): boolean => { + // value: number, row: {sourceName: string;} + return true; + // return row.sourceName === this.ossStore?.source[value - 1]?.text; + }; + + /** + * @param {Object} filter 需要过滤的数据 + */ + filterChange = (filter: CurrencyType) => { + const filterParams: any = { + source: 'source', + osType: 'osType' + }; + this.filterEmptyInfo.filterParams(filter, this.ossStore, this.reactiveArr, filterParams) + .then((res: any) => { + this.reactiveArr.filterParams = res.filterParams; + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.modelDetail.setFilterData(res, 'filter') + }); + }; +}; + +export default FilterOperate; diff --git a/bmp-operation-web/src/views/modelManagement/detail/table/tableScroll.ts b/bmp-operation-web/src/views/modelManagement/detail/table/tableScroll.ts new file mode 100644 index 0000000..49d2db8 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/table/tableScroll.ts @@ -0,0 +1,89 @@ +import {tableScroll} from 'utils/index.ts'; +import {CurrencyType, HeightType3} from '@utils/publicType'; + +interface DataType { + activeName: Ref; + headerTitle: Ref; + hasRemove: boolean; + tableMaxHeight: Ref; + title2: Ref; +}; + +interface ParamsType { + active: { + value: string; + }; + filter: CurrencyType; + searchTip: { + value: boolean; + } +} + +const tableScrollOperate = (params: ParamsType) => { + const {active, filter, searchTip}: ParamsType = params; + const data: DataType = { + activeName: ref(''), + hasRemove: Boolean(false), + tableMaxHeight: ref(0), + title2: ref({ + offsetHeight: 0, + scrollHeight: 0 + }), + headerTitle: ref({offsetHeight: 0, scrollHeight: 0}), + }; + + data.activeName.value = active.value; + + watch(() => [filter, searchTip.value], () => { + getHeightTop(); + }, {deep: true}) + + watch(() => active, (newValue: {value: string}) => { + data.activeName.value = newValue.value; + getHeightTop(); + }, {deep: true}) + + onMounted(() => { + if (data.activeName.value === 'essentialInformation') return; + data.hasRemove = false; + getHeightTop(); + }); + + onUnmounted(() => data.hasRemove = true); + + window.onresize = () => { + if (data.activeName.value === 'essentialInformation') return; + getHeightTop(); + }; + + const getRef = (val: DataType['title2']) => { + data.title2 = val; + getHeightTop(); + }; + + const getHeightTop = () => { + if (data.hasRemove) return; + nextTick(() => { + const addImageButton: any = document.querySelector('.add-image-btn'); + const count = searchTip.value ? 27 : 0; + const value1 = data.headerTitle.value; + const value2 = data.title2.value; + const countHeight = count + addImageButton?.offsetHeight + addImageButton?.scrollHeight + value1.scrollHeight + value2.offsetHeight + value2.scrollHeight + value1.offsetHeight + 23; + tableScroll(countHeight, data.tableMaxHeight); + }) + }; + + + const getRefHeader = (val: { value: HeightType3; }) => { + data.headerTitle.value = val.value; + }; + + + return { + ...data, + getRefHeader, + getRef + } +}; + +export default tableScrollOperate; diff --git a/bmp-operation-web/src/views/modelManagement/detail/tabs/active.ts b/bmp-operation-web/src/views/modelManagement/detail/tabs/active.ts new file mode 100644 index 0000000..a3b07e7 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/tabs/active.ts @@ -0,0 +1,67 @@ +import {language} from 'utils/publicClass.ts'; +import {CurrencyType, CurrencyType6} from '@utils/publicType'; +import router from 'router/index.ts'; + +interface DataType { + activeName: Ref; + tabsPangeData: CurrencyType6[]; +} + +const tabsOperate = (tableList: any, dataInit: any, baseInfo: any) => { + const data: DataType = { + // 标签页切换的model + activeName: ref('essentialInformation'), + tabsPangeData: [ // 标签页切换信息 + { + label: language.t('modelDetail.tabs.basicInfo.name'), + name: 'essentialInformation' + }, + { + label: language.t('modelDetail.tabs.relationImage.name'), + name: 'associatedMirror' + } + ] + }; + + onMounted(() => { + if (dataInit.routerType === 'image') { + data.activeName.value = 'associatedMirror'; + tableList.init(); + return; + } + baseInfo.getModelDetail(); + }); + + watch(() => data.activeName.value, (): void => { + if (!tableList.reactiveArr.tableData.length && dataInit.routerType !== 'image') { + tableList.init(); + dataInit.ossStore?.getOssData(); + } + }, {deep: true}); + + /** + * 标签页切换 + * @param {string} value 当前标签页点击切换的名称 + * @return {string} activeName.value 当前标签页切换的数据 + */ + const tabsChange = (value: string): void => { + data.activeName.value = value; + const path: string = router.currentRoute.value.path; + const query: CurrencyType = router.currentRoute.value.query; + let obj: CurrencyType = {}; + let activeQuery: string = ''; + for (let index in query) { + obj = Object.assign(obj, {[index]: query[index]}, {type: value === 'essentialInformation' ? 'modelDetail' : 'image'}) + activeQuery += `${[index]}=${obj[index]}&` + } + activeQuery = activeQuery.slice(0, -1); + router.push(`${path}?${activeQuery}`); + }; + + return { + ...data, + tabsChange + } +}; + +export default tabsOperate; diff --git a/bmp-operation-web/src/views/modelManagement/detail/tabs/tabs.vue b/bmp-operation-web/src/views/modelManagement/detail/tabs/tabs.vue new file mode 100644 index 0000000..2245e16 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/tabs/tabs.vue @@ -0,0 +1,42 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/detail/typeManagement.ts b/bmp-operation-web/src/views/modelManagement/detail/typeManagement.ts new file mode 100644 index 0000000..7e97070 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/detail/typeManagement.ts @@ -0,0 +1,38 @@ +/** + * 标签页类 +*/ +type TabsPangeDataType = { + label: string; + name: string; +}; + +/** + * store库存储的状态值-类 +*/ +export interface StoreType { + hasNavigationBar: boolean; +}; + +/** + * store库-oss数据类 +*/ +export interface StoreOssType { + ossData: any[]; +}; + +/** + * 复杂数据类型type +*/ +export interface ReactiveType { + tableRef: any; + filterParams: any; + detail: any; + tabsPangeData: TabsPangeDataType[]; + tableData: any[]; +}; + +export interface FilterParamsType { + deviceTypeId?: string; + architecture: string; + osType: string; +}; diff --git a/bmp-operation-web/src/views/modelManagement/edit/index.scss b/bmp-operation-web/src/views/modelManagement/edit/index.scss new file mode 100644 index 0000000..882603f --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/edit/index.scss @@ -0,0 +1,598 @@ +@import '@/assets/css/communal'; + +.model-operate { + + .volume-manager-table { + + .el-form-item__content { + justify-content: center; + } + + .ipt-height { + margin-top: 20px; + margin-bottom: 45px !important; + .el-form-item__content { + // height: 90px; + // height: 93px; + position: relative; + margin-bottom: 10px; + + .el-input { + // margin-bottom: 40px; + } + + .el-form-item__error { + text-align: left; + line-height: 1.2; + top: 100%; + // top: 50%; + padding-top: 7px; + } + } + } + + + .ipt-default { + // margin-bottom: 40px !important; + // margin-bottom: 10px !important; + .el-form-item__content { + // height: 30px; + + // height: 30px; + // margin-bottom: 10px; + + .el-input-number { + margin-bottom: 0px; + .el-input { + + margin-bottom: 0; + } + } + + .el-input { + margin-bottom: 0px; + } + } + } + + } + .el-table__empty-block { + background-color: #fff; + } + .set-right { + .el-form-item__label { + margin-right: 30px; + } + } + + .save-btn { + margin-bottom: 36px; + } + + .edit-btn { + margin-bottom: 0 !important; + } + .operate-btn { + cursor: pointer; + color: #108ee9; + // margin-bottom: 47px; + span { + font-size: 12px; + &:first-child { + margin-right: 10px; + } + } + } + + .active-ipt { + input { + border-color: #f56c6c; + } + } + + .error-tip { + position: absolute; + color: #f56c6c; + font-weight: 600; + text-align: left; + left: 0; + padding-top: 35px; + top: 0; + line-height: 1.4; + font-size: 12px; + z-index: -1; + + // &:hover { + // background: #f7f7f7; + // } + } + .default-ipt { + input { + border-color: #dcdfe6; + } + } + + .default-right { + .el-form-item__label { + margin-right: 10px; + } + } + + .add-volume-en { + font-size: 12px; + margin-left: 165px; + } + + .boot-mode-count { + margin: 20px 0 18px; + + .el-checkbox__label { + height: 20px; + line-height: 20px; + } + } + + .add-volume { + font-size: 12px; + margin-left: 115px; + } + + .default-s { + color: #999; + cursor: no-drop; + margin-top: 5px; + } + + .active { + cursor: pointer; + color: #108ee9; + } + + .set-top { + margin-top: 22px !important; + } + + #volumeManager { + display: flex; + align-items: flex-start; + margin-bottom: 0 !important; + white-space: nowrap; + + label { + line-height: 4; + + &::before { + content: "*"; + color: var(--el-color-danger); + margin-right: 4px; + } + } + } + + &-rule-form { + // margin-top: 20px; + + .el-input__inner { + // width: 507px; + // min-width: 87px; + } + + .flex-checkbox { + display: flex; + align-items: center; + + .el-checkbox { + width: auto; + margin-bottom: 0; + align-items: center !important; + } + } + + #bootMode { + .el-form-item__label { + &::before { + position: relative; + font-weight: 600; + line-height: 1.5; + display: flex; + align-items: flex-start; + word-wrap: break-word; + word-break: keep-all; + content: "*"; + color: var(--el-color-danger); + margin-right: 4px; + } + } + } + + .template-tip { + font-size: 12px; + color: #333; + font-weight: 600; + margin-bottom: 15px; + } + .set-empty { + margin-bottom: 32px !important; + .el-form-item__error { + margin-top: 6px !important; + } + } + + .set-empty1 { + margin-bottom: 28px !important; + .el-form-item__error { + margin-top: 6px !important; + } + } + + .set-default { + margin-bottom: 12px !important; + } + + .is-loading { + position: absolute; + top: 8px; + right: 0; + transform: translateY(-50%); + animation: loading .7s linear ease-in-out; + } + + @keyframes loading { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(100deg); + } + } + + .set-name-bottom { + margin-bottom: 47px !important; + + .el-form-item__error { + margin-top: 5px !important; + } + } + + .set-label { + display: flex; + align-items: flex-start !important; + + .el-form-item__content { + .radio-button-text-ellipsis { + margin-bottom: 5px; + } + } + } + + .device-type-count { + position: relative; + } + + .el-form-item--default { + display: flex; + align-items: center; + + .el-form-item__label { + position: relative; + font-weight: $fontLargeWeight; + line-height: 1.5; + display: flex; + align-items: flex-start; + word-wrap: break-word; + word-break: keep-all; + } + } + + .error-device-type { + input { + border-color: #f56c6c; + } + } + + .has-error-device-type { + position: absolute; + top: 22px; + font-size: $fontSize; + color: #f56c6c; + } + + .model-name { + .el-input { + width: auto; + } + } + .specifications { + + .el-input { + width: auto; + } + .el-form-item__content { + position: relative; + } + } + + .el-input--default, + .el-form-item__content { + display: flex; + } + + .set-desc { + .el-form-item__label { + display: flex; + align-items: flex-start; + margin-top: 5px; + width: 130px !important; + margin-left: 10px; + margin-top: -50px; + } + .el-input__count { + font-size: $fontSize; + color: $color7; + font-weight: $fontSmallWeight; + } + } + .set-english-width { + .el-form-item__label { + width: 130px !important; + margin-left: 10px; + } + } + + .set-width { + .el-form-item__label { + width: 100px !important; + margin-left: 10px; + } + } + + .el-table__row { + .el-table__cell { + // display: flex; + padding: 0; + + // align-items: flex-start; + // width: 100%; + + // .cell { + // width: 100%; + // } + } + } + + .el-select { + width: 100%; + } + + // .min-size-count { + // // display: flex; + // // align-items: center; + // // justify-content: center; + + // .unit-select { + // .el-input__inner { + // width: 100px; + // } + // } + + // .num-ipt { + // .el-input__inner { + // width: 100px; + // } + // } + + + // // .el-form-item__content { + // // justify-content: flex-end; + // // } + // } + + &-desc { + + .el-textarea { + width: 507px; + } + .el-form-item__label { + width: 100px !important; + margin-left: 10px; + margin-top: -50px; + } + + .el-textarea__inner { + height: 78px; + padding: 5px 8px; + margin-top: 7px; + resize: none; + + &::placeholder { + font-size: $fontSize; + } + + font-size: $fontSize; + } + + .el-input__count { + font-size: $fontSize; + color: $color7; + font-weight: $fontSmallWeight; + // right: 86px; + } + } + + .hide-label { + .el-form-item__label { + opacity: 0; + } + } + + .set-select-width { + .el-form-item__content { + input { + width: 260px; + } + } + } + + .multiple-choice { + input { + width: 100%; + // width: 200px; + } + } + + // .set-type-width { + // .el-form-item__content { + // input { + // width: 275px; + // } + // } + // } + + .select-width { + .el-form-item__content { + .el-select, + input { + width: 235px; + } + } + } + + .set-data-sys-style { + .el-form-item__content { + input { + width: 300px; + border-top-right-radius: 0; + border-bottom-right-radius: 0; + } + + .el-select { + position: absolute; + left: 300px; + + input { + width: 65px; + border-top-left-radius: 0; + border-bottom-left-radius: 0; + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; + border-left: 0; + + // &:active, + // &:focus { + // // border-color: $border2 !important; + // } + } + } + } + } + + .sys-single-capacity, + .data-single-capacity { + .el-form-item__content { + width: 224px; + position: relative; + + input { + // width: 160px; + // border-top-right-radius: 0; + // border-bottom-right-radius: 0; + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; + // border-right: 0 !important; + } + + .el-select .el-input.is-focus .el-input__inner { + border-color: #dcdfe6 !important; + } + + .el-select { + width: 67px; + position: absolute; + // left: 150px; + right: 0; + + input { + width: 65px; + border-top-left-radius: 0; + border-bottom-left-radius: 0; + // border-top-right-radius: 4px; + // border-bottom-right-radius: 4px; + border-top: 0; + height: 28px; + border-bottom: 0; + border-right: 0; + margin-right: 1px; + // border-left: 0; + + // &:hover, + // &:active, + &:focus { + border-color: #dcdfe6 !important; + // border-color: $border2 !important; + } + } + } + } + } + + .el-form-item__label, + .el-input__inner { + font-size: $fontSize; + color: $defaultColor; + } + + .el-form-item--default { + margin-bottom: 18px; + + &:last-child { + margin-bottom: 0; + } + } + + input { + // width: 450px; + height: 30px; + border-radius: 4px; + } + } + + .set-bottom { + margin-bottom: 24px; + } + + .en-table-error-tip { + margin-left: 170px; + font-size: 12px; + margin-bottom: 20px; + color: #f56c6c; + } + + .table-error-tip { + margin-left: 115px; + font-size: 12px; + margin-bottom: 20px; + color: #f56c6c; + } + + .set-from-img, + .model-from-img { + position: absolute; + right: 0px; + top: 50%; + transform: translateY(-50%); + width: 16px; + height: 16px; + position: absolute; + } + + .footer-btn { + display: flex; + align-items: center; + justify-content: center; + margin-bottom: 50px; + button { + width: 150px; + height: 36px; + } + } +} diff --git a/bmp-operation-web/src/views/modelManagement/edit/modelEdit.vue b/bmp-operation-web/src/views/modelManagement/edit/modelEdit.vue new file mode 100644 index 0000000..19944dc --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/edit/modelEdit.vue @@ -0,0 +1,1160 @@ + + + + diff --git a/bmp-operation-web/src/views/modelManagement/edit/noConfiguration.vue b/bmp-operation-web/src/views/modelManagement/edit/noConfiguration.vue new file mode 100644 index 0000000..ee7436f --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/edit/noConfiguration.vue @@ -0,0 +1,337 @@ + + + + diff --git a/bmp-operation-web/src/views/modelManagement/edit/page.ts b/bmp-operation-web/src/views/modelManagement/edit/page.ts new file mode 100644 index 0000000..e3371c6 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/edit/page.ts @@ -0,0 +1,10 @@ +const ModelEdit = () => import(/* webpackChunkName: "ModelEdit" */ './modelEdit.vue'); + +export default { + path: '/ModelManagement/modelEdit', + name: 'ModelEdit', + component: ModelEdit, + meta: { + type: 'modelEdit' + } +}; diff --git a/bmp-operation-web/src/views/modelManagement/edit/typeManagement.ts b/bmp-operation-web/src/views/modelManagement/edit/typeManagement.ts new file mode 100644 index 0000000..21ce26b --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/edit/typeManagement.ts @@ -0,0 +1,173 @@ +import {CurrencyType, CpuDataType, MemDataType, VerifyRulesType} from '@utils/publicType'; + +type key = 'name' | 'value'; + +type key1 = 'hasClick' | 'hasClick1' | 'hasClick2' | 'hasClick3' | 'hasClick4' | 'sysRaidFlag' | 'raidConfig'; + +/** + * 机型类型 +*/ +type RadioBtnType = { + [k in key]: string; +}; + +// type RadioBtnType = { [key in keyof T]: string} + +type IdcNameRadioBtnType = { + find(arg0: (item: {title: string;}) => boolean): {idcId: string; title: string;}; +}; + +/** + * 机房名称类 +*/ +type ComputerRoomRadioBtnType = { + title: string; + idcId: string; + showTooltip: boolean; +}; + +/** + * 通用操作类 +*/ +interface ProcessingOperationsType { + setModelType: any; + // processingOperations(formSubmit: CurrencyType): CurrencyType; + // cpuPreset(formSubmit: CurrencyType): CurrencyType; + // memPreset(formSubmit: CurrencyType): CurrencyType; + // setCpuMemData(arg0: boolean, arg1: boolean, arg2: CurrencyType): Promise; + // setFormData(formSubmit: CurrencyType): CurrencyType; + // setErrorHeight(arg0: Ref[], arg1: boolean, arg2: boolean, arg3: Ref, arg4: Ref, arg5: any, arg6: any): never; +}; + +/** + * 复杂数据类 +*/ +interface ReactiveDataType { + radioBtn: RadioBtnType[]; + computerRoomRadioBtn: ComputerRoomRadioBtnType[]; + modelCPUBtn: string[]; + storageData: string[]; +}; + +/** + * 规则验证类 +*/ +interface RuleFormType { + templateName: string; + deviceTypeName: string; + bootMode: string[] | string; + machineRoomName: string; + cpuSpec: string; + memSpec: string; + idcId: string; + modelType: string; + arrayCard: string; + // raidCan: any; + name: string; + architecture: string | number; + deviceType: string; + description: string; + modelCPU: string; + cpuInfo: string; + cpuManufacturer: string; + cpuModel: string; + cpuCores: number | string; + cpuFrequency: string; + cpuAmount: string | number; + modelStorage: string; + memInfo: string; + memType: string; + memFrequency: string | number; + memSize: string | number; + memAmount: string | number; + volumeManagerTableData: any; + noConfigurationData: any; + // systemVolumeType: string; + // systemVolumeInterfaceType: string; + // systemVolumeSize: string | number | null; + // systemVolumeUnit: string | number; + // systemVolumeAmount: string | number; + // sysRaid: string[]; + // dataVolumeType: string; + // dataVolumeInterfaceType: string; + // dataVolumeSize: string | null; + // dataVolumeUnit: string | number; + // dataVolumeAmount: number; + nicRate: number | string; + nicAmount: number; + interfaceMode: string | number; + gpuManufacturer: string; + gpuModel: string; + gpuAmount: number; + height: string | number; + cpuData: CpuDataType[]; + memData: MemDataType[]; +}; + +/** + * 规则类 +*/ +interface RulesType { + name: VerifyRulesType[]; + architecture: VerifyRulesType[]; + deviceType: VerifyRulesType[]; + cpuInfo: VerifyRulesType[]; + cpuManufacturer: VerifyRulesType[]; + cpuModel: VerifyRulesType[]; + cpuCores: VerifyRulesType[]; + cpuFrequency: VerifyRulesType[]; + memInfo: VerifyRulesType[]; + memType: VerifyRulesType[]; + memFrequency: VerifyRulesType[]; + memSize: VerifyRulesType[]; + systemVolumeType: VerifyRulesType[]; + systemVolumeInterfaceType: VerifyRulesType[]; + systemVolumeSize: VerifyRulesType[]; + systemVolumeUnit: VerifyRulesType[]; + sysRaid: VerifyRulesType[]; + dataVolumeType: VerifyRulesType[]; + dataVolumeInterfaceType: VerifyRulesType[]; + dataVolumeSize: VerifyRulesType[]; + dataVolumeUnit: VerifyRulesType[]; + dataVolumeAmount: VerifyRulesType[]; + nicRate: VerifyRulesType[]; + nicAmount: VerifyRulesType[]; + interfaceMode: VerifyRulesType[]; + gpuManufacturer: VerifyRulesType[]; + gpuModel: VerifyRulesType[]; + gpuAmount: VerifyRulesType[]; + height: VerifyRulesType[]; +}; + +interface PropsReactiveType { + architecture: string[]; + raidData: any; + volumeTypeData: string[]; + raidConfig: string[]; + diskTypeData: {label: string; value: string}[]; + noRaidInterfaceData: {label: string; value: string}[]; + interfaceData: {label: string; value: string}[]; + noSysRaid: {label: string; value: string}[]; + sysRaid: {label: string; value: string}[]; + sysDiskRaid0: {label: string; value: string}[]; + bootModeData: {label: string; select: boolean;}[]; + computerRoomRadioBtn: {title: string; idcId: string; showTooltip: boolean;}[]; +}; + +interface RadiosPropsType { + hasTemplate: boolean; + formData: {value: CurrencyType;}; cpuSpec: string; memSpec: string; +}; + +export { + key1, + CpuDataType, + MemDataType, + RulesType, + RuleFormType, + ProcessingOperationsType, + RadiosPropsType, + PropsReactiveType, + ReactiveDataType, + IdcNameRadioBtnType +}; diff --git a/bmp-operation-web/src/views/modelManagement/edit/utils/dataOperate.ts b/bmp-operation-web/src/views/modelManagement/edit/utils/dataOperate.ts new file mode 100644 index 0000000..ddcd57a --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/edit/utils/dataOperate.ts @@ -0,0 +1,253 @@ +// deepCopy +import {filterData} from 'utils/index.ts'; +import {language, locationItem, CurrentInstance} from 'utils/publicClass.ts'; +import {CurrencyType} from '@utils/publicType'; +// RadiosPropsType +import {CpuDataType, MemDataType, RuleFormType, PropsReactiveType} from '../typeManagement'; +import store from 'store/index.ts'; +// import ModelStaticData from 'staticData/model/index.ts'; + +// let raidList: any = []; +// let sysRaidData: any = []; +class DataOperate { + idcData = store.idcInfo.idcDataNoOpt; + raidsStore = store.modeFormInfo(); + // 复杂数据类型 + reactiveData: PropsReactiveType = reactive({ + architecture: [], + raidConfig: [], + raidData: {}, + volumeTypeData: [ + language.t('modelForm.label.system'), + language.t('modelForm.label.data') + ], + diskTypeData: [ + { + label: 'SSD', + value: 'SSD' + }, + { + label: 'HDD', + value: 'HDD' + }, + { + label: language.t('modelForm.unrestricted'), + value: 'notLimited' + } + ], + noRaidInterfaceData: [ + { + label: 'NVME', + value: 'NVME' + } + ], + interfaceData: [ + { + label: 'SATA', + value: 'SATA' + }, + { + label: 'SAS', + value: 'SAS' + }, + { + label: language.t('modelForm.unrestricted'), + value: 'notLimited' + } + ], + sysRaid: [], + noSysRaid: [], + sysDiskRaid0: [], + bootModeData: [ + { + select: true, + label: '--' + }, + { + select: true, + label: '--' + } + ], + computerRoomRadioBtn: [ // 机房名称 + { + title: '', + idcId: '', + showTooltip: false + } + ] + }); + ruleForm: any; + proxy = new CurrentInstance().proxy; + // props: {cpuSpec: string; memSpec: string; hasTemplate: boolean;} & RadiosPropsType + constructor (ruleForm: RuleFormType) { + this.ruleForm = ruleForm; + const val = localStorage.getItem('model-item')?? ''; + const newVal = JSON.parse(val); + ruleForm.modelCPU = this.#setDefText(newVal.cpuSpec); + ruleForm.modelStorage = this.#setDefText(newVal.memSpec); + // props + this.architectureData(ruleForm); + if (!this.idcData?.length) { + this.idcList(ruleForm); + return; + }; + this.getIdcData(this.idcData, ruleForm); + }; + + #setDefText = (value: string) => { + const text = new Map([ + ['common', language.t('modelForm.specificationsType.presetSpecifications')] + ]); + return text.get(value)?? language.t('modelForm.specificationsType.otherSpecifications'); + }; + + // , props: any + architectureData = (ruleForm: RuleFormType) => { + const val = localStorage.getItem('model-item')?? ''; + const newVal = JSON.parse(val); + this.raidsStore.getCommonData() + .then((res: {architecture: CurrencyType; cpuSpec: CpuDataType[]; memSpec: MemDataType[]; raidRules: CurrencyType; bootMode: string[]}) => { + const {architecture, cpuSpec, memSpec, raidRules, bootMode} = res; + this.reactiveData.raidData = raidRules; + // 无 + const noneInfo = Object.values(raidRules['1']); + // RAID数据 + const raidInfo = Object.values(raidRules['2']); + // 单盘RAID0 + const singleInfo = Object.values(raidRules['3']); + const newNone: {label: string; value: string;}[] = []; + const newRaid: {label: string; value: string;}[] = []; + const singleRaid: {label: string; value: string;}[] = []; + this.reactiveData.noSysRaid = this.#setRaidData(noneInfo, newNone); + this.reactiveData.sysRaid = this.#setRaidData(raidInfo, newRaid); + this.reactiveData.sysDiskRaid0 = this.#setRaidData(singleInfo, singleRaid); + const raidRulesData = Object.values(raidRules); + this.reactiveData.raidConfig = this.#setRaidCan(raidRulesData); + this.reactiveData.architecture = Object.keys(architecture); + this.reactiveData.bootModeData = bootMode.map((item: string) => { + return { + label: item, + select: true + } + }); + ruleForm.cpuData = cpuSpec; + ruleForm.memData = memSpec; + ruleForm.bootMode = bootMode.join(','); + // ruleForm, props + // this.setCpuMemStatus(ruleForm, newVal.cpuSpec, newVal.memSpec) + this.raidsData(ruleForm, newVal); + }); + }; + + idcList = async (ruleForm: {machineRoomName: string; idcId: string}) => { + try { + const res = await this.proxy.$idcApi.idcListAPI({isAll: '1'}); + if (res?.data?.result?.idcs?.length) { + const {idcs} = res.data.result; + this.getIdcData(idcs, ruleForm); + } + } + catch { + throw new Error(); + } + }; + + getIdcData = (data: CurrencyType[], ruleForm: {machineRoomName: string; idcId: string}) => { + this.reactiveData.computerRoomRadioBtn = filterData(data, 'name') + .map((item: {name: string; nameEn: string; idcId: string}) => { + return { + ...item, + title: this.#setName(locationItem.getLocationItem, item), + idcId: item.idcId + } + }); + if (!ruleForm.machineRoomName?.length) { + ruleForm.machineRoomName = this.reactiveData.computerRoomRadioBtn[0].title; + ruleForm.idcId = this.reactiveData.computerRoomRadioBtn[0].idcId; + } + }; + + #setName = (name: string, item: CurrencyType) => { + const keyName: Map = new Map([ + ['zh_CN', item.name], + ['en_US', item.nameEn] + ]); + return keyName.get(name); + }; + + #setRaidCan = (raidRulesData: string[]): string[] => { + const raidCan: string[] = []; + raidRulesData.forEach((t: string) => { + Object.keys(t).forEach((g: string) => { + raidCan.push(g); + }) + }) + return raidCan; + } + + #setRaidData = (dataInfo: string[], raid: {label: string; value: string;}[]) => { + dataInfo.forEach((item: string) => { + Object.keys(item).forEach((t: any) => { + raid.push({ + label: t, + value: item[t] + }) + }) + }) + return raid; + } + + /** + * 获取raids数据 + */ + raidsData = (ruleForm: any, newVal: any) => { + for (const key in newVal) { + for (const index in ruleForm) { + if (key === index) { + this.setCpuMemStatus(ruleForm, newVal.cpuSpec, newVal.memSpec); + (ruleForm[`${index}` as keyof typeof ruleForm] as string) = newVal[index]; + } + } + } + }; + + setCpuMemStatus = (ruleForm: RuleFormType, status: string, status2: string) => { + const sCpuMemData = [ + [ + (status: string, _: string) => status === 'common', + () => { + ruleForm.cpuAmount = 1; + ruleForm.cpuCores = 1; + ruleForm.cpuFrequency = ''; + ruleForm.cpuManufacturer = ''; + ruleForm.cpuModel = ''; + } + ], + [ + (status: string, _: string) => status !== 'common', + () => ruleForm.cpuInfo = '' + ], + [ + (_: string, status2: string) => status2 === 'common', + () => { + ruleForm.memSize = ''; + ruleForm.memAmount = 1; + ruleForm.memFrequency = ''; + ruleForm.memType = ''; + } + ], + [ + (_: string, status2: string) => status2 !== 'common', + () => ruleForm.memInfo = '' + ] + ]; + + for (const key of sCpuMemData) { + if (key[0](status, status2)) { + key[1](status, status2); + } + } + }; +}; + +export default DataOperate; diff --git a/bmp-operation-web/src/views/modelManagement/edit/utils/formRulesEvent.ts b/bmp-operation-web/src/views/modelManagement/edit/utils/formRulesEvent.ts new file mode 100644 index 0000000..d21fd95 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/edit/utils/formRulesEvent.ts @@ -0,0 +1,98 @@ +import {RegExpCheck} from './regExpCheck'; +import RegularContent from 'utils/regular.ts'; +import {RuleFormRefType} from '@utils/publicType'; +import {RulesType, RuleFormType} from '../typeManagement'; + +type FormVType = { + name: string;ruleForm: RuleFormType; + rules: RulesType; + ruleFormRef: Ref +}; + +class FormRulesEvent { + formRulesOperate: FormVType; + // name: string = ''; + // device: string = ''; + isLongTip: Ref = ref(false); + isShowLoading: Ref = ref(false); + deviceTypeLoading: Ref = ref(false); + dataVolumeSizeFlag: Ref = ref(false); + systemVolumeSizeFlag: Ref = ref(false); + formV: any; + + // , name: string, device: string + constructor (formV: FormVType) { + this.formRulesOperate = formV; + // this.name = name; + // this.device = device; + this.formV = formV; + }; + + dataVolumeSizeBlur = () => { + nextTick(async () => { + await this.formRulesOperate.ruleFormRef.value!.validateField('dataVolumeSize', (valid: string) => !valid + ? this.dataVolumeSizeFlag.value = false + : this.dataVolumeSizeFlag.value = true + ); + }); + }; + + nameChange = () => { + this.verifyRepeat(1); + this.verifyNameDevice(this.isShowLoading, 'name'); + }; + + nameBlur = () => { + new RegExpCheck().nameFlag.value = true; + const nameArr = [ + [ + (value: string) => !value, + () => this.isLongTip.value = false + ], + [ + (value: string) => !(RegularContent.modelNameReg.test(value)), + () => { + this.isLongTip.value = true; + } + ], + [ + (value: string) => value, + () => { + new RegExpCheck().nameFlag.value = false; + this.isLongTip.value = false; + } + ] + ]; + for (const key of nameArr) { + if (key[0](this.formV.ruleForm.name)) { + key[1](this.formV.ruleForm.name); + break; + } + } + }; + + deviceTypeChange = () => { + this.verifyRepeat(0); + this.verifyNameDevice(this.deviceTypeLoading, 'deviceType'); + }; + + verifyRepeat = (type: number) => { + const name = this.formRulesOperate.ruleForm.name; + const deviceType = this.formRulesOperate.ruleForm.deviceType; + if (name === deviceType && name !== '' && deviceType !== '') { + sessionStorage.setItem('repeat', 'true'); + type && this.deviceTypeChange(); + return; + } + sessionStorage.removeItem('repeat'); + }; + + verifyNameDevice = (loading: {value: boolean}, type: string) => { + loading.value = true; + this.formRulesOperate.ruleFormRef.value!.validateField(type, (_: string) => { + loading.value = false; + }); + } +}; + +export default FormRulesEvent; diff --git a/bmp-operation-web/src/views/modelManagement/edit/utils/newFormRules.ts b/bmp-operation-web/src/views/modelManagement/edit/utils/newFormRules.ts new file mode 100644 index 0000000..bbe6e69 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/edit/utils/newFormRules.ts @@ -0,0 +1,1000 @@ +import {RuleFormRefType, SuccessType} from '@utils/publicType'; +// +import {RuleFormType, RulesType, ProcessingOperationsType} from '../typeManagement' +import reactiveData from './reactiveData'; +import {regExpCheck} from './regExpCheck'; +import {locationItem, language} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; +import RegularContent from 'utils/regular.ts'; +import ModelStaticData from 'staticData/model/index.ts' +import {editModelAPI} from 'api/model/request.ts'; // 添加机型接口 +import StorageOperate from './storage'; +import {Router, useRouter} from 'vue-router'; +import {msgTip, methodsTotal} from 'utils/index.ts'; + +interface DataCountType { + hasAddFlag: Ref; + hasAddFlag2: Ref; + isLoading: Ref; + raidCanFlag: Ref; + volumeNameTip: Ref; + volumeTypeTip: Ref; + raidCanTip: Ref; + sysRaidTip: Ref; + diskTypeTip: Ref; + interfaceTypeTip: Ref; + minSizeNumTip: Ref; + amountTip: Ref; + tableHasError: Ref; + tableHasError2: Ref; + tableErrorTip: Ref; + tableErrorTip2: Ref; + ruleFormRef: Ref; + ruleForm: RuleFormType; + rules: RulesType; +}; +const reactiveDataOperate = reactiveData(); +const formRules = () => { + const router: Router = useRouter(); + const idcData = store.idcInfo.idcDataNoOpt; + const languages = locationItem.getLocationItem === 'zh_CN'; + const modelFormStore: ProcessingOperationsType | any = store.modeFormInfo(); + + const val = localStorage.getItem('model-item')?? ''; + const newVal = JSON.parse(val); + const remove = new StorageOperate(newVal); + + const dataCount: DataCountType = { + volumeNameTip: ref(language.t('modelForm.label.volumeManage.empty.name')), + volumeTypeTip: ref(language.t('modelForm.label.volumeManage.empty.type')), + raidCanTip: ref(language.t('modelForm.label.volumeManage.empty.raidCan')), + sysRaidTip: ref(language.t('modelForm.label.volumeManage.empty.raid')), + diskTypeTip: ref(language.t('modelForm.label.volumeManage.empty.disk')), + interfaceTypeTip: ref(language.t('modelForm.label.volumeManage.empty.interfaceType')), + minSizeNumTip: ref(language.t('modelForm.label.volumeManage.empty.minNum')), + amountTip: ref(''), + hasAddFlag: ref(true), + hasAddFlag2: ref(true), + isLoading: ref(false), + raidCanFlag: ref(false), + // 表单ref + ruleFormRef: ref(), + tableHasError: ref(false), + tableHasError2: ref(false), + tableErrorTip: ref(language.t('modelForm.label.volumeManage.save.empty')), + tableErrorTip2: ref(language.t('modelForm.label.volumeManage.save.empty')), + // 表单数据 + ruleForm: reactive({ + // nicAmount: newVal.nicAmount, + // gpuModel: newVal.gpuModel, + // gpuAmount: newVal.gpuAmount, + // interfaceMode: newVal.interfaceMode, + // gpuManufacturer: newVal.gpuManufacturer, + // nicRate: newVal.nicRate, + // height: newVal.height, + arrayCard: newVal.isNeedRaid === 'no_need_raid' ? '2' : '1', + // machineRoomName: languages ? idcData[0]?.name : idcData[0]?.nameEn, + machineRoomName: (languages ? idcData[0]?.name : idcData[0]?.nameEn), + // idcId: formData?.value?.idcId || idcData[0]?.idcId, // idcId + idcId: newVal?.idcId || idcData[0]?.idcId, // idcId + modelType: reactiveDataOperate.modelFormStore.initModelType(newVal.deviceSeries), + cpuData: [], // cpu数据 + memData: [], // 内存数据 + bootMode: [], + volumeManagerTableData: [], + noConfigurationData: [], + ...reactiveDataOperate.modelFormStore.ruleForm, + }), + // 表单规则 + rules: reactive({ + // height: [ + // { + // required: true, + // trigger: 'change', + // message: '请选择高度' + // } + // ], + cpuModel: [ + { + required: true, + trigger: 'blur', + validator: regExpCheck.cpuModelCheck + } + ], + cpuFrequency: [ + { + required: true, + trigger: 'blur', + validator: regExpCheck.cpuFrequencyCheck + } + ], // 主频 + name: [ // 机型名称 + { + required: true, + trigger: 'blur', + validator: regExpCheck.nameCheck + } + ], + deviceType: [ // 机型规格 + { + required: true, + trigger: 'blur', + validator: regExpCheck.deviceTypeCheck + } + ], + volumeManager: [ + { + required: false, + trigger: 'blur', + message: '' + } + ], + ...reactiveDataOperate.modelFormStore.rules + }) + }; + const initVolumeType = (type: string) => { + const obj = new Map([ + ['system', language.t('modelForm.label.system')], + ['data', language.t('modelForm.label.data')] + ]); + return obj.get(type); + } + + if (newVal.isNeedRaid === 'no_need_raid') { + const noConfigData = dataCount.ruleForm.noConfigurationData = newVal.volumes.map((item: any, index: number) => { + + return { + ...item, + id: new Date().getTime() + index, + editFlag: true, + minSizeNum: item.volumeSize, + minSize: item.volumeUnit, + amount: item.volumeAmount, + // diskType: item.diskType, + // interfaceType: item.interfaceType, + // diskType: item.diskType === 'notLimited' ? language.t('modelForm.unrestricted') : item.diskType, + // interfaceType: item.interfaceType === 'notLimited' ? language.t('modelForm.unrestricted') : item.interfaceType, + volumeType: initVolumeType(item.volumeType), + newVolumeType: initVolumeType(item.volumeType) + } + }); + // , 'raidCanFlag', 'sysRaidFlag' + const type = ['volumeNameFlag', 'volumeTypeFlag', 'diskTypeFlag', 'interfaceTypeFlag', 'minSizeNumFlag', 'minSizeNumFlag', 'amountFlag'] + noConfigData.forEach((t: any) => { + type.forEach((a: any) => { + t[`${a}${t.id}`] = 'success' + }) + }); + dataCount.ruleForm.noConfigurationData = noConfigData; + } + else { + const volumeTableData = dataCount.ruleForm.volumeManagerTableData = newVal.volumes.map((item: any, index: number) => { + return { + ...item, + id: new Date().getTime() + index, + editFlag: true, + minSizeNum: item.volumeSize, + sysRaid: item.raid, + raidCan: ModelStaticData.singleRaid0.includes(item.raidCan) ? language.t('modelForm.raid') : item.raidCan, + newSysRaid: item.raidId, + minSize: item.volumeUnit, + amount: item.volumeAmount, + volumeType: initVolumeType(item.volumeType), + newVolumeType: initVolumeType(item.volumeType) + } + }); + + const type = ['volumeNameFlag', 'volumeTypeFlag', 'diskTypeFlag', 'interfaceTypeFlag', 'minSizeNumFlag', 'minSizeNumFlag', 'amountFlag', 'raidCanFlag', 'sysRaidFlag'] + volumeTableData.forEach((t: any) => { + type.forEach((a: any) => { + t[`${a}${t.id}`] = 'success' + }) + }); + dataCount.ruleForm.volumeManagerTableData = volumeTableData; + } + + const setDiskInterfaceType = (item: string) => { + return item === 'notLimited' ? language.t('modelForm.unrestricted') : item; + } + + + const addVolumeClick = () => { + if (!dataCount.hasAddFlag.value) return; + dataCount.hasAddFlag.value = false; + dataCount.tableHasError.value = false; + const obj = { + id: new Date().getTime(), + editFlag: false, + volumeName: '', + volumeType: '', + newVolumeType: '', + diskType: '', + minSize: 'GB', + raidCan: '', + amount: 0, + minSizeNum: '', + sysRaid: '', + interfaceType: '', + } + dataCount.ruleForm.volumeManagerTableData.push(obj); + }; + + const addVolumeClick2 = () => { + if (!dataCount.hasAddFlag2.value) return; + dataCount.hasAddFlag2.value = false; + dataCount.tableHasError2.value = false; + const obj = { + id: new Date().getTime(), + editFlag: false, + volumeName: '', + volumeType: '', + newVolumeType: '', + diskType: '', + minSize: 'GB', + amount: 1, + minSizeNum: '', + interfaceType: '', + } + dataCount.ruleForm.noConfigurationData.push(obj); + } + + const volumeNameBlur = (val: any, index: number) => { + val[`volumeNameFlag${index}`] = ''; + + if (!val.volumeName?.length) { + val[`volumeNameFlag${index}`] = 'error'; + dataCount.volumeNameTip.value = language.t('modelForm.label.volumeManage.empty.name'); + } + else if (!RegularContent.name1Reg.test(val.volumeName)){ + val[`volumeNameFlag${index}`] = 'error'; + dataCount.volumeNameTip.value = language.t('modelForm.errorTip.currency'); + } + else { + val[`volumeNameFlag${index}`] = 'success'; + dataCount.volumeNameTip.value = ''; + } + } + + const volumeTypeChange = (val: any, index: number) => { + val[`volumeTypeFlag${index}`] = ''; + if (!val.volumeType?.length) { + val[`volumeTypeFlag${index}`] = 'error'; + } + else { + if (dataCount.ruleForm.arrayCard === '1') { + const dataTable = dataCount.ruleForm.volumeManagerTableData; + + if (val.volumeType === language.t('modelForm.label.data') && dataTable.length === 1) { + val.volumeType = ''; + val.newVolumeType = ''; + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.sys.tip1') + val[`volumeTypeFlag${index}`] = 'error'; + } + else if (val.volumeType === language.t('modelForm.label.system') && dataTable.length > 1 && dataTable.map((item: {volumeType: string}) => item.volumeType).filter((ite: string) => ite === language.t('modelForm.label.system')).length > 1) { + val.volumeType = ''; + val.newVolumeType = ''; + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.sys.tip2') + val[`volumeTypeFlag${index}`] = 'error'; + } + else { + val[`volumeTypeFlag${index}`] = 'success'; + dataCount.volumeTypeTip.value = '' + val.newVolumeType = val.volumeType; + } + } + else { + const noRaidData = dataCount.ruleForm.noConfigurationData; + if (val.volumeType === language.t('modelForm.label.data') && noRaidData.length === 1) { + val.volumeType = ''; + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.sys.tip1') + val[`volumeTypeFlag${index}`] = 'error'; + val.newVolumeType = ''; + } + else if (val.volumeType === language.t('modelForm.label.system') && noRaidData.length > 1 && noRaidData.map((item: {volumeType: string}) => item.volumeType).filter((ite: string) => ite === language.t('modelForm.label.system')).length > 1) { + val.volumeType = ''; + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.sys.tip2') + val[`volumeTypeFlag${index}`] = 'error'; + val.newVolumeType = ''; + } + else { + val[`volumeTypeFlag${index}`] = 'success'; + dataCount.volumeTypeTip.value = '' + val.newVolumeType = val.volumeType; + } + } + } + }; + + const raidCanChange = (val: any, index: number) => { + val[`raidCanFlag${index}`] = ''; + if (!val.raidCan?.length) { + val[`raidCanFlag${index}`] = 'error'; + } + else { + val[`raidCanFlag${index}`] = 'success'; + dataCount.raidCanTip.value = '' + } + if (val.sysRaid?.length) { + val.sysRaid = '' + val[`sysRaidFlag${index}`] = void 0; + } + if (val.interfaceType) { + val.interfaceType = ''; + val[`interfaceTypeFlag${index}`] = void 0; + } + }; + + const sysRaidChange = (val: any, index: number, data: any) => { + val[`sysRaidFlag${index}`] = ''; + if (typeof val.sysRaid === 'string') { + // if (data[0] === language.t('modelForm.none')) { + // val['newSysRaid'] = [''] + // } + // else { + // let newId = data[0].value; + // val['newSysRaid'] = [newId]; + // } + let newId = data[0].value; + val['newSysRaid'] = [newId]; + } + else { + let d: any = [] + data.forEach((item: any) => { + val.sysRaid.forEach((t: any) => { + if (item.label === t) { + d.push(item.value) + } + + }) + }) + val['newSysRaid'] = d; + } + if (Array.isArray(val.sysRaid)) { + if (val.sysRaid.length > 0) { + val[`sysRaidFlag${index}`] = 'success'; + dataCount.sysRaidTip.value = ''; + } + else { + val[`sysRaidFlag${index}`] = 'error'; + dataCount.sysRaidTip.value = language.t('modelForm.label.volumeManage.empty.raid') + } + } + else { + if (!val.sysRaid?.length) { + val[`sysRaidFlag${index}`] = 'error'; + } + else { + val[`sysRaidFlag${index}`] = 'success'; + dataCount.sysRaidTip.value = '' + } + } + }; + + const diskTypeChange = (val: any, index: number) => { + val[`diskTypeFlag${index}`] = ''; + if (!val.diskType?.length) { + val[`diskTypeFlag${index}`] = 'error'; + // dataCount.raidCanTip.value = '请选择RAID配置' + } + else { + val[`diskTypeFlag${index}`] = 'success'; + dataCount.diskTypeTip.value = '' + } + } + + const interfaceTypeChange = (val: any, index: number) => { + val[`interfaceTypeFlag${index}`] = ''; + if (!val.interfaceType?.length) { + val[`interfaceTypeFlag${index}`] = 'error'; + // dataCount.raidCanTip.value = '请选择RAID配置' + } + else { + val[`interfaceTypeFlag${index}`] = 'success'; + dataCount.interfaceTypeTip.value = '' + } + } + + const minSizeNumBlur = (val: any, index: number) => { + val[`minSizeNumFlag${index}`] = ''; + if (!String(val.minSizeNum)?.length) { + val[`minSizeNumFlag${index}`] = 'error'; + dataCount.minSizeNumTip.value = language.t('modelForm.label.volumeManage.empty.minNum') + // dataCount.raidCanTip.value = '请选择RAID配置' + } + else if (val.minSize === 'TB') { + val[`minSizeNumFlag${index}`] = 'error'; + if (!RegularContent.capacityReg.test(val.minSizeNum)) { + dataCount.minSizeNumTip.value = language.t('modelForm.errorTip.number2') + } + else if ((Number(val.minSizeNum) > 100000)) { + dataCount.minSizeNumTip.value = language.t('modelForm.errorTip.number3'); + } + else { + dataCount.minSizeNumTip.value = '' + val[`minSizeNumFlag${index}`] = 'success'; + } + } + else { + val[`minSizeNumFlag${index}`] = 'error'; + if (!RegularContent.numberReg.test(val.minSizeNum)) { + dataCount.minSizeNumTip.value = language.t('modelForm.errorTip.number1'); + } + else if ((Number(val.minSizeNum) > 100000)) { + dataCount.minSizeNumTip.value = language.t('modelForm.errorTip.number3'); + } + else { + dataCount.minSizeNumTip.value = '' + val[`minSizeNumFlag${index}`] = 'success'; + } + } + } + + const minSizeChange = (val: {minSizeNum: string;}) => { + val.minSizeNum = ''; + } + + watch(() => dataCount.ruleForm.modelCPU, (newValue) => { + const cpuStatus = ModelStaticData.modelSpecData.includes(newValue); + if (cpuStatus) { + regExpCheck.cpuManufacturerFlag.value = false; + regExpCheck.cpuModelFlag.value = false; + regExpCheck.cpuInfoFlag.value = false; + regExpCheck.cpuGHzFlag.value = false; + } + }) + + watch(() => dataCount.ruleForm.modelStorage, (newValue) => { + const memeStatus = ModelStaticData.modelSpecData.includes(newValue); + if (memeStatus) { + regExpCheck.memTypeFlag.value = false; + regExpCheck.memFrequencyFlag.value = false; + regExpCheck.memSizeFlag.value = false; + regExpCheck.memInfoFlag.value = false; + } + }) + + const setAmountMaxSize = (item: any, index: number) => { + if (dataCount.ruleForm.arrayCard === '2' || [language.t('modelForm.raid'), 'NO RAID'].includes(item.raidCan)) { + item.amount = 1; + dataCount.amountTip.value = '' + item[`amountFlag${index}`] = 'success'; + return 1; + } + if (!Array.isArray(item.sysRaid)) return; + // r-l6pounvfife0njlinhk6ztf2xyio + if (item.sysRaid.includes('RAID10')) { + if (item.amount % 4 === 0) { + // item.amountFlag + item[`amountFlag${index}`] = 'success'; + dataCount.amountTip.value = '' + } + return; + } + if (item.sysRaid.includes('RAID1')) { + if (item.amount % 2 === 0) { + item[`amountFlag${index}`] = 'success'; + dataCount.amountTip.value = '' + } + return; + } + + if (item.sysRaid.includes('RAID0')) { + if (item.amount >= 2) { + item[`amountFlag${index}`] = 'success'; + dataCount.amountTip.value = '' + } + return; + } + // // else + // return 1000; + } + + const setAmountMinSize = (item: any, index: number) => { + if (dataCount.ruleForm.arrayCard === '2' || [language.t('modelForm.raid'), 'NO RAID'].includes(item.raidCan)) { + item[`amountFlag${index}`] = 'success'; + return 1; + } + if (!Array.isArray(item.sysRaid) || !item.sysRaid?.length) { + return 1; + }; + // if (item.sysRaid.length === 1) { + // r-l6pounvfife0njlinhk6ztf2xyio + if (item.sysRaid.includes('RAID10')) { + if (item.amount < 4) { + item.amount = 4; + } + // else if (item.amount % 4 !== 0) { + // // item.amountFlag + // item[`amountFlag${index}`] = 'error'; + // dataCount.amountTip.value = '最低4或者大于4的偶数' + // } + return 4; + } + if (item.sysRaid.length === 1 && item.sysRaid.includes('RAID5')) { + item[`amountFlag${index}`] = 'success'; + dataCount.amountTip.value = ''; + if (item.amount < 3) { + item.amount = 3; + } + return 3; + + } + // if (item.sysRaid.includes('RAID1') && item.sysRaid.includes('RAID5')) { + // if (item.amount < 4) { + // item.amount = 4; + // } + // else { + // if (item.amount % 2 === 0) { + // item[`amountFlag${index}`] = 'success'; + // dataCount.amountTip.value = '' + // } + // else { + // item[`amountFlag${index}`] = 'error'; + // dataCount.amountTip.value = '最低2块,或者大于2的偶数' + // } + // } + // return 4; + // } + if (item.sysRaid.includes('RAID0') && item.sysRaid.includes('RAID5')) { + if (item.amount < 3) { + item.amount = 3; + } + return 3; + } + if (item.sysRaid.includes('RAID1')) { + if (item.amount < 2) { + item.amount = 2; + } + // else if (item.amount % 2 !== 0) { + // // item.amountFlag + // item[`amountFlag${index}`] = 'error'; + // dataCount.amountTip.value = '最低2或者大于2的偶数' + // } + return 2; + } + if (item.sysRaid.includes('RAID0')) { + if (item.amount < 2) { + item.amount = 2; + } + return 2; + } + } + + const sure = async () => { + await dataCount.ruleFormRef.value!.validate((valid: Required) => { + if (!valid) { + regExpCheck.heightFlag.value = true; + regExpCheck.interfaceModeFlag.value = true; + regExpCheck.nicRateFlag.value = true; + } + const {volumeManagerTableData, noConfigurationData} = dataCount.ruleForm; + const cpuStatus = ModelStaticData.modelSpecData.includes(dataCount.ruleForm.modelCPU); + const memStatus = ModelStaticData.modelSpecData.includes(dataCount.ruleForm.modelStorage); + setFlag(); + setOtherEmpty(cpuStatus, memStatus) + if (dataCount.ruleForm.arrayCard === '1') { + dataCount.tableHasError.value = !(volumeManagerTableData?.length > 0); + if (!dataCount.hasAddFlag.value) { + dataCount.tableHasError.value = true; + dataCount.tableErrorTip.value = language.t('modelForm.label.volumeManage.save.volumeManagement'); + return + }; + if (dataCount.tableHasError.value) { + dataCount.tableHasError.value = true; + dataCount.tableErrorTip.value = language.t('modelForm.label.volumeManage.save.empty'); + return; + } + } + else { + dataCount.tableHasError2.value = !(noConfigurationData?.length > 0); + if (!dataCount.hasAddFlag2.value) { + dataCount.tableHasError2.value = true; + dataCount.tableErrorTip2.value = language.t('modelForm.label.volumeManage.save.volumeManagement'); + return + }; + if (dataCount.tableHasError2.value) { + dataCount.tableHasError2.value = true; + dataCount.tableErrorTip2.value = language.t('modelForm.label.volumeManage.save.empty'); + return; + } + } + if (valid) { + regExpCheck.heightFlag.value = false; + // let params: any = {} + let cpuBol = false; + let memBol = false; + if (cpuStatus && memStatus) { + cpuBol = false; + memBol = false; + } + else if (cpuStatus && !memStatus) { + cpuBol = false; + memBol = true; + } + else if (!cpuStatus && memStatus) { + cpuBol = true; + memBol = false; + } + else { + cpuBol = true; + memBol = true; + } + + modelFormStore.setCpuMemData(cpuBol, memBol, dataCount.ruleForm) + .then(() => { + requestEditModel(cpuBol, memBol) + }) + } + else { + regExpCheck.heightFlag.value = true; + } + }) + } + + const setOtherEmpty = (cpuStatus: boolean, memStatus: boolean) => { + if (cpuStatus) { + regExpCheck.cpuManufacturerFlag.value = false; + } + else { + regExpCheck.cpuInfoFlag.value = false; + } + if (memStatus) { + regExpCheck.memTypeFlag.value = false; + regExpCheck.memFrequencyFlag.value = false; + regExpCheck.memSizeFlag.value = false; + } + else { + regExpCheck.memInfoFlag.value = false; + } + } + + /** + * 请求添加机型接口,成功后把事件回传,关闭弹窗 + */ + const requestEditModel = (cpuBol: boolean, memBol: boolean) => { + const {arrayCard, noConfigurationData, gpuManufacturer, gpuModel, gpuAmount, volumeManagerTableData} = dataCount.ruleForm; + const obj = gpuAmount > 0 ? { + gpuAmount, + gpuModel, + gpuManufacturer + } : {} + + const volumesData = arrayCard === '1' ? volumeManagerTableData.map((item: any) => { + return { + volumeName: item.volumeName, + volumeType: setVolumeType(item.newVolumeType), + diskType: item.diskType, + interfaceType: item.interfaceType, + volumeSize: String(item.minSizeNum), + volumeUnit: item.minSize, + volumeAmount: item.amount, + raidCan: ModelStaticData.singleRaid0.includes(item.raidCan) ? 'RAID0-stripping' : item.raidCan, + raid: typeof item.newSysRaid === 'string' ? item.newSysRaid : item.newSysRaid.join(','), + } + }) : noConfigurationData.map((item: any) => { + return { + // ...item, + volumeName: item.volumeName, + volumeType: setVolumeType(item.newVolumeType), + // item.newVolumeType === language.t('modelForm.label.system') ? 'system' : 'data', + diskType: item.diskType, + interfaceType: item.interfaceType, + // diskType: item.diskType === language.t('modelForm.unrestricted') ? 'notLimited' : item.diskType, + // interfaceType: item.interfaceType === language.t('modelForm.unrestricted') ? 'notLimited' : item.interfaceType, + volumeSize: String(item.minSizeNum), + volumeUnit: item.minSize, + volumeAmount: item.amount, + // raidCan: item.raidCan, + // raid: item.newSysRaid.join(','), + } + }) + // const otherParams = { + // idcId, + // name, + // nicAmount, + // interfaceMode, + // nicRate, + // height, + // architecture, + // deviceType, + // description, + // volumes: volumesData + // } + if (gpuAmount <= 0) { + const emptyData = ['gpuAmount', 'gpuModel', 'gpuManufacturer']; + for (const key of emptyData) { + Reflect.deleteProperty(dataCount.ruleForm, key) + } + } + const newParams = { + ...obj, + // ...otherParams, + ...dataCount.ruleForm, + volumes: volumesData, + isNeedRaid: setIsNeedRaid(arrayCard), + // ...dataCount.ruleForm, + cpuSpec: cpuBol ? 'user_defined' : 'common', + memSpec: memBol ? 'user_defined' : 'common', + // cpuManufacturer, + // cpuCores, + // cpuModel, + // cpuAmount, + // cpuFrequency, + // memType, + // memSize, + // memAmount, + // memFrequency, + // ...params, + deviceSeries: modelFormStore.setModelType(dataCount.ruleForm.modelType) + } + if (arrayCard === '2') { + const status = noConfigurationData.some((item: {volumeType: string}) => item.volumeType === language.t('modelForm.label.system')); + if (!status) { + dataCount.tableHasError2.value = true; + dataCount.tableErrorTip2.value = language.t('modelForm.label.volumeManage.sys.tip1'); + return; + } + } + else { + const status = volumeManagerTableData.some((item: {volumeType: string}) => item.volumeType === language.t('modelForm.label.system')); + if (!status) { + dataCount.tableHasError.value = true; + dataCount.tableErrorTip.value = language.t('modelForm.label.volumeManage.sys.tip1'); + return; + } + } + dataCount.isLoading.value = true; + editModelAPI( + { + ...newParams, + deviceTypeId: newVal.deviceTypeId + } + ).then(({data} : {data: SuccessType}) => { + if(data?.result?.success) { + msgTip.success(language.t('operate.success')); + // cancel(); + router.go(-1) + remove.remove(); + methodsTotal.sendMsg('model-edit-success', 'success'); + } + }).finally(() => { + dataCount.isLoading.value = false; + }); + }; + + + const setVolumeType = (type: string) => { + const data = [ + [ + (value: string) => value === language.t('modelForm.label.system'), + () => 'system' + ], + [ + (value: string) => value === language.t('modelForm.label.data'), + () => 'data' + ] + ]; + for (const key of data) { + if (key[0](type)) { + return key[1](type) + } + } + } + + const setIsNeedRaid = (type: string) => { + const obj = { + '1': 'need_raid', + '2': 'no_need_raid' + }; + // @ts-ignore + return obj[type]; + } + + const nicAmountIpt = () => { + if (dataCount.ruleForm.interfaceMode) { + dataCount.ruleForm.interfaceMode = ''; + regExpCheck.interfaceModeFlag.value = true; + } + }; + + + const setFlag = () => { + const data = ['cpuInfo', 'memInfo', 'cpuManufacturer', 'memType', 'memFrequency', 'memSize']; + for (const key of data) { + // @ts-ignore + regExpCheck[`${key}Flag`].value = !(dataCount.ruleForm[key]) + } + } + + const setAddBtn = () => { + const status = dataCount.ruleForm.volumeManagerTableData.every((item: {editFlag: boolean}) => item.editFlag); + dataCount.hasAddFlag.value = status; + return status ? 'active' : 'default-s'; + } + + const setAddBtn2 = () => { + const status = dataCount.ruleForm.noConfigurationData.every((item: {editFlag: boolean}) => item.editFlag); + dataCount.hasAddFlag2.value = status; + return status ? 'active' : 'default-s'; + } + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + const getFormRef = (formEl: {value: RuleFormRefType}) => { + dataCount.ruleFormRef.value = formEl.value; + // setFormRef('ruleFormRef', formEl) + // emitValue('rule-form-ref', dataCount.ruleFormRef); + }; + + // const totalDataSave = dataCount.ruleForm.volumeManagerTableData.every((item: {editFlag: boolean}) => item.editFlag); + const saveClick = (val: any, index: number) => { + const status = val[`volumeNameFlag${index}`] === 'success' && val[`volumeTypeFlag${index}`] === 'success' && val[`diskTypeFlag${index}`] === 'success' && val[`interfaceTypeFlag${index}`] === 'success' && val[`minSizeNumFlag${index}`] === 'success' && val[`amountFlag${index}`] === 'success'; + if (status && val[`raidCanFlag${index}`] === 'success' && val[`sysRaidFlag${index}`] === 'success') { + val.editFlag = true; + dataCount.hasAddFlag.value = true; + const hasEverySave = dataCount.ruleForm.volumeManagerTableData.every((item: {editFlag: boolean}) => item.editFlag); + if (hasEverySave) { + dataCount.tableErrorTip.value = ''; + dataCount.tableHasError.value = false; + } + } + if (dataCount.ruleForm.arrayCard === '1') { + if (val[`raidCanFlag${index}`] === void 0) { + dataCount.raidCanTip.value = language.t('modelForm.label.volumeManage.empty.raidCan') + val[`raidCanFlag${index}`] = ''; + } + + if (val[`sysRaidFlag${index}`] === void 0) { + dataCount.sysRaidTip.value = language.t('modelForm.label.volumeManage.empty.raid') + val[`sysRaidFlag${index}`] = ''; + } + + } + if (val[`volumeNameFlag${index}`] === void 0) { + dataCount.volumeNameTip.value = language.t('modelForm.label.volumeManage.empty.name') + val[`volumeNameFlag${index}`] = ''; + + } + if (val[`volumeTypeFlag${index}`] === void 0) { + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.empty.type') + val[`volumeTypeFlag${index}`] = ''; + } + + if (val[`diskTypeFlag${index}`] === void 0) { + dataCount.diskTypeTip.value = language.t('modelForm.label.volumeManage.empty.disk'); + val[`diskTypeFlag${index}`] = ''; + } + + if (val[`interfaceTypeFlag${index}`] === void 0) { + dataCount.interfaceTypeTip.value = language.t('modelForm.label.volumeManage.empty.interfaceType'); + val[`interfaceTypeFlag${index}`] = ''; + } + + if (val[`minSizeNumFlag${index}`] === void 0) { + dataCount.minSizeNumTip.value = language.t('modelForm.label.volumeManage.empty.minNum') + val[`minSizeNumFlag${index}`] = ''; + } + + + } + + const noConfigurationSaveClick = (val: any, index: number) => { + const status = val[`volumeNameFlag${index}`] === 'success' && val[`volumeTypeFlag${index}`] === 'success' && val[`diskTypeFlag${index}`] === 'success' && val[`interfaceTypeFlag${index}`] === 'success' && val[`minSizeNumFlag${index}`] === 'success'; + if (status) { + val.editFlag = true; + + dataCount.hasAddFlag2.value = true; + const hasEverySave = dataCount.ruleForm.noConfigurationData.every((item: {editFlag: boolean}) => item.editFlag); + if (hasEverySave) { + dataCount.tableErrorTip2.value = ''; + dataCount.tableHasError2.value = false; + } + return; + } + + if (val[`volumeNameFlag${index}`] === void 0) { + dataCount.volumeNameTip.value = language.t('modelForm.label.volumeManage.empty.name') + val[`volumeNameFlag${index}`] = ''; + + } + if (val[`volumeTypeFlag${index}`] === void 0) { + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.empty.type') + val[`volumeTypeFlag${index}`] = ''; + } + + if (val[`diskTypeFlag${index}`] === void 0) { + dataCount.diskTypeTip.value = language.t('modelForm.label.volumeManage.empty.disk'); + val[`diskTypeFlag${index}`] = ''; + } + + if (val[`interfaceTypeFlag${index}`] === void 0) { + dataCount.interfaceTypeTip.value = language.t('modelForm.label.volumeManage.empty.interfaceType'); + val[`interfaceTypeFlag${index}`] = ''; + } + + if (val[`minSizeNumFlag${index}`] === void 0) { + dataCount.minSizeNumTip.value = language.t('modelForm.label.volumeManage.empty.minNum') + val[`minSizeNumFlag${index}`] = ''; + } + + } + + watch(() => [dataCount.ruleForm.gpuManufacturer, dataCount.ruleForm.gpuModel], (newValue) => { + const status = newValue.some(item => item === ''); + if (status) { + dataCount.ruleForm.gpuAmount = 0; + } + }) + + const editClick = (val: { + split(arg0: string): string[];editFlag: boolean; raidCan: string; raid: string; sysRaid: string[]; +}) => { + + if (val.raidCan === 'RAID') { + val.sysRaid = val?.raid ? val.raid.split(',') : val.sysRaid; + } + val.editFlag = false; + } + + const noConfigurationEditClick = (val: {editFlag: boolean;}) => { + val.editFlag = false; + } + + const deleteClick = (index: number) => { + dataCount.ruleForm.volumeManagerTableData.splice(index, 1); + dataCount.hasAddFlag.value = true; + } + + const noConfigurationDeleteClick = (index: number) => { + dataCount.ruleForm.noConfigurationData.splice(index, 1); + dataCount.hasAddFlag2.value = true; + } + + const cancel = () => { + router.push('/ModelManagement/modelList') + } + + const amountMinValue = () => { + const {gpuModel, gpuManufacturer} = dataCount.ruleForm; + if (gpuModel && gpuManufacturer) { + return 1; + } + dataCount.ruleForm.gpuAmount = 0; + return 0; + } + + return { + sure, + ...dataCount, + getFormRef, + setDiskInterfaceType, + addVolumeClick, + volumeNameBlur, + cancel, + volumeTypeChange, + // setRaidInfo, + raidCanChange, + sysRaidChange, + diskTypeChange, + noConfigurationSaveClick, + interfaceTypeChange, + minSizeNumBlur, + minSizeChange, + addVolumeClick2, + setAmountMinSize, + setAmountMaxSize, + setAddBtn, + setAddBtn2, + saveClick, + nicAmountIpt, + editClick, + noConfigurationEditClick, + amountMinValue, + deleteClick, + noConfigurationDeleteClick + } +} + +export default formRules; \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/edit/utils/reactiveData.ts b/bmp-operation-web/src/views/modelManagement/edit/utils/reactiveData.ts new file mode 100644 index 0000000..396558c --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/edit/utils/reactiveData.ts @@ -0,0 +1,23 @@ +import {StoreGeneric, storeToRefs} from 'pinia'; // store +import {ReactiveDataType} from '..//typeManagement'; +import store from 'store/index.ts'; + +interface DataType { + modelFormStore: StoreGeneric; + reactiveData: ReactiveDataType; +}; + +const reactiveData = () => { + const data: DataType = { + modelFormStore: store.modeFormInfo(), + reactiveData: reactive({ + ...storeToRefs(store.modeFormInfo()).data.value + }) + }; + + return { + ...data + }; +}; + +export default reactiveData; diff --git a/bmp-operation-web/src/views/modelManagement/edit/utils/regExpCheck.ts b/bmp-operation-web/src/views/modelManagement/edit/utils/regExpCheck.ts new file mode 100644 index 0000000..fbd07f4 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/edit/utils/regExpCheck.ts @@ -0,0 +1,248 @@ +import {resourcesAPI} from 'api/public/request.ts'; +import {language} from 'utils/publicClass.ts'; +import {CallbackType} from '@utils/publicType'; +import RegularContent from 'utils/regular.ts'; + +// type ParamsType = Partial<{name: string; deviceType: string;}>; + +class RegExpCheck { + memSizeFlag: Ref = ref(false); + memFrequencyFlag: Ref = ref(false); + memTypeFlag: Ref = ref(false); + heightFlag: Ref = ref(false); + interfaceModeFlag: Ref = ref(false); + nicRateFlag: Ref = ref(false); + cpuManufacturerFlag: Ref = ref(false); + memInfoFlag: Ref = ref(false); + cpuInfoFlag: Ref = ref(false); + cpuGHzFlag: Ref = ref(false); + cpuModelFlag: Ref = ref(false); + nameFlag: Ref = ref(false); + deviceTypeFlag: Ref = ref(false); + nameLoading: Ref = ref(false); + deviceTypeLoading: Ref = ref(false); + ruleForm: { + minValUnit: string; + } = { + minValUnit: 'GB', + }; + + constructor (minValUnit: string = 'GB') { + this.ruleForm.minValUnit = minValUnit; + }; + + /** + * 机型名称校验 + * @param {Object} _ 占位符 + * @param {string} value 输入项 + * @param {Function} callback 回调函数,返回对应状态 + */ + nameCheck: unknown = (_: unknown, value: string, callback: CallbackType) => { + const nameArr = [ + [ + (value: string) => !value?.length, + () => { + this.nameFlag.value = true; + callback(new Error(language.t('modelForm.emptyTip.modelName'))) + } + ], + [ + (value: string) => value.length > 64, + () => { + this.nameFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.currency2'))) + } + ], + [ + (value: string) => (!RegularContent.modelNameReg.test(value)), + () => { + this.nameFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.currency'))) + } + ], + [ + (value: string) => value, + () => { + const name: string = sessionStorage.getItem('propsName')??''; + const status: string = sessionStorage.getItem('hasTemplate')??''; + this.nameLoading.value = true; + if (name === value && status !== 'success') { + this.nameFlag.value = false; + this.nameLoading.value = false; + callback(); + } + else { + resourcesAPI( + { + name: value + } + ) + .then(({data} : {data: {result: {success: boolean;}}}) => { + if (data?.result?.success) { + this.nameFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.name'))); + return; + } + return Promise.reject(); + }) + .catch(() => { + this.nameFlag.value = false; + callback(); + }) + .finally(() => { + this.nameLoading.value = false; + }) + } + } + ] + ]; + for (const key of nameArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + /** + * 机型规格校验 + * @param {Object} _ 占位符 + * @param {string} value 输入项 + * @param {Function} callback 回调函数,返回对应状态 + */ + deviceTypeCheck: unknown = (_: unknown, value: string, callback: CallbackType) => { + const deviceTypeArr = [ + [ + (value: string) => !value?.length, + () => { + this.deviceTypeFlag.value = true; + callback(new Error(language.t('modelForm.emptyTip.modelSpecifications'))) + } + ], + [ + (value: string) => value.length > 64, + () => { + this.deviceTypeFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.currency2'))) + } + ], + [ + (value: string) => (value && sessionStorage?.getItem('repeat')), + () => { + this.deviceTypeFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.modelSpecifications'))) + } + ], + [ + (value: string) => value, + () => { + const deviceType = sessionStorage?.getItem('propsDeviceType'); + const status = sessionStorage.getItem('hasTemplate'); + this.deviceTypeLoading.value = true; + if (deviceType === value && status !== 'success') { + this.deviceTypeFlag.value = false; + this.deviceTypeLoading.value = false; + callback(); + } + else { + resourcesAPI( + { + deviceType: value + } + ) + .then(({data} : {data: {result: {success: boolean;}}}) => { + if (data?.result?.success) { + this.deviceTypeFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.specifications'))); + return; + } + return Promise.reject(); + }) + .catch(() => { + this.deviceTypeFlag.value = false; + callback(); + }) + .finally(() => { + this.deviceTypeLoading.value = false; + }) + } + } + ] + ]; + for (const key of deviceTypeArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + /** + * cpu型号 + * @param {string} str 提示项 + * @param {string} trigger 判断时机-change/blur + */ + cpuModelCheck = (_: {}, value: string, callback: (arg0?: Error) => void) => { + this.cpuModelFlag.value = true; + const cpuModelArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t('modelForm.emptyTip.modelChoose'))) + ], + [ + (value: string) => value.length > 64, + () => callback(new Error(language.t('modelForm.errorTip.currency2'))) + ], + [ + (value: string) => value, + () => { + callback(); + this.cpuModelFlag.value = false; + } + ] + ]; + for (const key of cpuModelArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + /** + * CPU-主频 + */ + cpuFrequencyCheck = (_: unknown, value: string, callback: (arg0?: Error) => void) => { + this.cpuGHzFlag.value = true; + const cpuFrequencyArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t('modelForm.emptyTip.dominantFrequency'))) + ], + [ + (value: string) => (!RegularContent.capacityReg.test(value)), + () => callback(new Error(language.t('modelForm.errorTip.number'))) + ], + [ + (value: string) => value, + () => { + callback(); + this.cpuGHzFlag.value = false; + } + ] + ]; + for (const key of cpuFrequencyArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; +}; + +const regExpCheck: RegExpCheck = new RegExpCheck(); + +export { + RegExpCheck, + regExpCheck +}; diff --git a/bmp-operation-web/src/views/modelManagement/edit/utils/storage.ts b/bmp-operation-web/src/views/modelManagement/edit/utils/storage.ts new file mode 100644 index 0000000..b3e377f --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/edit/utils/storage.ts @@ -0,0 +1,15 @@ +class StorageOperate { + + constructor (props: {name: string; deviceType: string;}) { + sessionStorage.setItem('propsName', props.name); + sessionStorage.setItem('propsDeviceType', props.deviceType); + }; + + remove = () => { + sessionStorage?.removeItem('repeat') + sessionStorage?.removeItem('propsName'); + sessionStorage?.removeItem('propsDeviceType'); + }; +}; + +export default StorageOperate; diff --git a/bmp-operation-web/src/views/modelManagement/list/addModel/add.ts b/bmp-operation-web/src/views/modelManagement/list/addModel/add.ts new file mode 100644 index 0000000..8ecc79c --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/addModel/add.ts @@ -0,0 +1,22 @@ +/** + * @file + * @author +*/ + +class AddModelOpt { + proxy; + router; + + constructor(proxy: {$defInfo: {routerPath(arg0: string): void}}, router: {push(arg0: string): void}) { + this.proxy = proxy; + this.router = router; + } + + addModelClick = () => { + localStorage.removeItem('model-item'); + const path = this.proxy.$defInfo.routerPath('addModel'); + this.router.push(`${path}`) + } +} + +export default AddModelOpt; diff --git a/bmp-operation-web/src/views/modelManagement/list/addModelTemplate/modelTemplate.ts b/bmp-operation-web/src/views/modelManagement/list/addModelTemplate/modelTemplate.ts new file mode 100644 index 0000000..004f18c --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/addModelTemplate/modelTemplate.ts @@ -0,0 +1,22 @@ +/** + * @file + * @author +*/ + +class ModelTemplateOpt { + proxy; + router; + + constructor(proxy: {$defInfo: {routerPath(arg0: string): void}}, router: {push(arg0: string): void}) { + this.proxy = proxy; + this.router = router; + } + + addModelTemplateClick = (item: T) => { + const path = this.proxy.$defInfo.routerPath('addModelTemplate') + localStorage.setItem('model-item', JSON.stringify(item)); + this.router.push(`${path}?deviceType=${item.deviceType}`) + } +} + +export default ModelTemplateOpt; diff --git a/bmp-operation-web/src/views/modelManagement/list/all.ts b/bmp-operation-web/src/views/modelManagement/list/all.ts new file mode 100644 index 0000000..fd29532 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/all.ts @@ -0,0 +1,33 @@ +import customOperate from './custom/custom'; +import {ExportFilterData, ExportDataOperate, modelListExportAPI} from './export/export'; +import EditModelOpt from './editModel/edit'; +import ModelTemplateOpt from './addModelTemplate/modelTemplate'; +import AddModelOperate from './addModel/add'; +import deleteModelOperate from './deleteModel/delete'; +import tableScrollOperate from './table/tableScroll'; +import FilterOperate from './table/tableFilter'; +import ModelListOperate from './modelList/modelList'; +import resetOperate from './modelList/reset'; +// import PaginationOperate from './pagination/pagination'; +// import IdcList from './idcList/idcList'; +import refreshOperate from './modelList/refresh'; +import SearchOperate from './search/search'; + +export { + customOperate, + ExportFilterData, + ExportDataOperate, + modelListExportAPI, + EditModelOpt, + ModelTemplateOpt, + // IdcList, + AddModelOperate, + deleteModelOperate, + tableScrollOperate, + FilterOperate, + ModelListOperate, + resetOperate, + // PaginationOperate, + refreshOperate, + SearchOperate +}; diff --git a/bmp-operation-web/src/views/modelManagement/list/custom/custom.ts b/bmp-operation-web/src/views/modelManagement/list/custom/custom.ts new file mode 100644 index 0000000..9f3b0b1 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/custom/custom.ts @@ -0,0 +1,10 @@ +/** + * @file + * @author +*/ + +import useCustom from 'hooks/custom/useCustom.ts'; + +const customOperate = useCustom('deviceTypeList').info; + +export default customOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/list/custom/customList.vue b/bmp-operation-web/src/views/modelManagement/list/custom/customList.vue new file mode 100644 index 0000000..290dc13 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/custom/customList.vue @@ -0,0 +1,9 @@ + + diff --git a/bmp-operation-web/src/views/modelManagement/list/deleteModel/delete.ts b/bmp-operation-web/src/views/modelManagement/list/deleteModel/delete.ts new file mode 100644 index 0000000..608c35b --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/deleteModel/delete.ts @@ -0,0 +1,66 @@ +import {paginationOperate} from 'utils/publicClass.ts'; + +interface DataType { + deleteModelDiaLog: Ref; + modelName: Ref; + deviceTypeId: Ref; +}; + +const deleteModelOperate = (modelList: { reactiveArr: { tableData: string | unknown[]; }; getModelList: () => void; }, reset: { reset: () => void; }) => { + const data: DataType = { + // 删除机型弹窗状态 + deleteModelDiaLog: ref(false), + // 当前点击删除的机型信息 + modelName: ref(''), + // 当前点击删除的机型deviceTypeId + deviceTypeId: ref('') + }; + + /** + * 删除机型点击事件 + * @param {string} name 当前点击删除的机型名称 + * @param {string} id 当前点击的deviceTypeId + */ + const deleteModelClick = (item: any): void => { + if (item.instanceCount > 0 || item.deviceCount > 0) return; + data.deleteModelDiaLog.value = !data.deleteModelDiaLog.value; + data.modelName.value = item.name; + data.deviceTypeId.value = item.deviceTypeId; + }; + + /** + * 删除机型弹窗取消事件 + * @param {boolean} type false 弹窗关闭 + * @return {boolean} deleteModelDiaLog.value 删除机型弹窗关闭 + */ + const deleteModelCancel = (type: boolean): boolean => { + return data.deleteModelDiaLog.value = type; + }; + + const deleteModelSure = () => { + if (paginationOperate.pageNumber.value > 1 && modelList.reactiveArr.tableData.length === 1) { + paginationOperate.pageNumber.value = paginationOperate.pageNumber.value - 1; + return; + } + if (modelList.reactiveArr.tableData.length === 1) { + reset.reset(); + } + else { + modelList.getModelList(); + } + }; + + const deleteModelError = () => { + modelList.getModelList(); + }; + + return { + ...data, + deleteModelClick, + deleteModelCancel, + deleteModelSure, + deleteModelError + }; +}; + +export default deleteModelOperate; diff --git a/bmp-operation-web/src/views/modelManagement/list/deleteModel/deleteModelOperate.vue b/bmp-operation-web/src/views/modelManagement/list/deleteModel/deleteModelOperate.vue new file mode 100644 index 0000000..b9c1e53 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/deleteModel/deleteModelOperate.vue @@ -0,0 +1,20 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/list/editModel/edit.ts b/bmp-operation-web/src/views/modelManagement/list/editModel/edit.ts new file mode 100644 index 0000000..c0691c5 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/editModel/edit.ts @@ -0,0 +1,23 @@ +/** + * @file + * @author +*/ + +class EditModelOpt { + proxy; + router; + + constructor(proxy: {$defInfo: {routerPath(arg0: string): void}}, router: {push(arg0: string): void}) { + this.proxy = proxy; + this.router = router; + } + + editModelClick = (item: T) => { + if (item.deviceCount !== 0) return; + const path = this.proxy.$defInfo.routerPath('editModel') + localStorage.setItem('model-item', JSON.stringify(item)); + this.router.push(`${path}?deviceType=${item.deviceType}`) + } +} + +export default EditModelOpt; diff --git a/bmp-operation-web/src/views/modelManagement/list/export/export.ts b/bmp-operation-web/src/views/modelManagement/list/export/export.ts new file mode 100644 index 0000000..9f73a57 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/export/export.ts @@ -0,0 +1,49 @@ +import {modelListExportAPI} from 'api/model/request.ts'; +import {ExportDataOperate} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; + +class ExportFilterData { + // 是否导出数据 + // hasExportData: Ref = ref(true); + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + // list: any; + search: { + searchParams: {} + }; + filter: { + filterParams: {} + }; + + constructor(search: { + searchParams: {} + }, filter: { + filterParams: {} + }) { + // this.list = list; + this.search = search; + this.filter = filter; + }; + + exportData = (that: never) => { + new ExportDataOperate(modelListExportAPI, {}, 'device_type_list').exportData(that); + }; + + /** + * 参数处理 + */ + paramsProcessing = (that: never) => { + this.filterEmptyInfo.deleteEmtpyData({...this.filter.filterParams, ...this.search.searchParams}); + new ExportDataOperate(modelListExportAPI, { + ...this.search.searchParams, + ...this.filter.filterParams + }, 'device_type_list').exportData(that); + } +}; + +export { + ExportFilterData, + ExportDataOperate, + modelListExportAPI +}; diff --git a/bmp-operation-web/src/views/modelManagement/list/export/exportData.vue b/bmp-operation-web/src/views/modelManagement/list/export/exportData.vue new file mode 100644 index 0000000..2b9f088 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/export/exportData.vue @@ -0,0 +1,23 @@ + + + diff --git a/bmp-operation-web/src/views/modelManagement/list/modeList.scss b/bmp-operation-web/src/views/modelManagement/list/modeList.scss new file mode 100644 index 0000000..e69de29 diff --git a/bmp-operation-web/src/views/modelManagement/list/modelList.vue b/bmp-operation-web/src/views/modelManagement/list/modelList.vue new file mode 100644 index 0000000..069544a --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/modelList.vue @@ -0,0 +1,115 @@ + + + + + diff --git a/bmp-operation-web/src/views/modelManagement/list/modelList/modelList.ts b/bmp-operation-web/src/views/modelManagement/list/modelList/modelList.ts new file mode 100644 index 0000000..ca572f3 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/modelList/modelList.ts @@ -0,0 +1,88 @@ +/** + * @file + * @author +*/ + +import {AxiosError} from 'axios'; +import {ParamType, TableType} from '../typeManagement'; +import {paginationOperate, CurrentInstance} from 'utils/publicClass.ts'; +import {msgTip, methodsTotal} from 'utils/index.ts'; +import store from 'store/index.ts'; +import ModelStaticData from 'staticData/model/index.ts'; + +class ModelListOperate { + searchTip: Ref = ref(false); + isLoading: Ref = ref(true); // loading态 + // store + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + reactiveArr: { + tableData: TableType[]; + } = reactive<{ + tableData: TableType[]; + }>({ + tableData: [] // 表格-机型列表数据 + }); + search: any = {}; + filter: any = {}; + proxy = new CurrentInstance().proxy; + + constructor (search: any, filter: any) { + this.search = search; + this.filter = filter; + this.remove(); + this.init(); + }; + + remove = () => { + const removeData = ['repeat', 'hasTemplate', 'propsName', 'propsDeviceType']; + for (const key of removeData) { + sessionStorage?.removeItem(key) + } + }; + + init = () => { + this.getModelList(); + }; + + getModelList = async () => { + this.isLoading.value = true; + let param: ParamType = { + pageNumber: paginationOperate.pageNumber.value, + pageSize: paginationOperate.pageSize.value, + ...this.filter.reactiveArr.filterParams, + ...this.search.reactiveArr.searchParams + }; + this.filterEmptyInfo.deleteEmtpyData(param); + try { + const res = await this.proxy.$modelApi.modelListAPI({...param}); + if (res?.data?.result?.deviceTypes?.length) { + const {deviceTypes, totalCount} : {totalCount: number; deviceTypes: TableType[]} = res.data.result; + deviceTypes.forEach((item: TableType, index: number) => { + ModelStaticData.modelTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }); + }) + this.reactiveArr.tableData = deviceTypes; + paginationOperate.total.value = totalCount; + return; + } + throw new Error(''); + } + catch (e) { + this.reactiveArr.tableData = []; + paginationOperate.total.value = 0; + methodsTotal.initScrollLeft(this.filter.tableRef.value); + const err = e as AxiosError; + err?.message && msgTip.error(err.message); + } + finally { + this.isLoading.value = false; + this.search.hasClear.value = false; + this.searchTip.value = Object.keys(param).length > 2; + } + }; +}; + +export default ModelListOperate; diff --git a/bmp-operation-web/src/views/modelManagement/list/modelList/refresh.ts b/bmp-operation-web/src/views/modelManagement/list/modelList/refresh.ts new file mode 100644 index 0000000..f9807e3 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/modelList/refresh.ts @@ -0,0 +1,19 @@ +import {RefreshType} from '../typeManagement'; + +const refreshOperate = (modelList: RefreshType['modelList'], reset: RefreshType['reset']) => { + + // 刷新 + const refresh = () => { + if (!modelList?.reactiveArr?.tableData?.length) { + reset.reset(); + return; + } + modelList.getModelList(); + }; + + return { + refresh + } +}; + +export default refreshOperate; diff --git a/bmp-operation-web/src/views/modelManagement/list/modelList/reset.ts b/bmp-operation-web/src/views/modelManagement/list/modelList/reset.ts new file mode 100644 index 0000000..4a5219a --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/modelList/reset.ts @@ -0,0 +1,19 @@ +import {ResetType} from '../typeManagement'; + +const resetOperate = (filter: ResetType['filter'], search: ResetType['search']) => { + + // 重置 + const reset = () => { + filter.tableRef.value?.clearFilter(); + filter.reactiveArr.filterParams = {}; + search.hasClear.value = true; + search.reactiveArr.searchParams = {}; + search.request(); + }; + + return { + reset + }; +}; + +export default resetOperate; diff --git a/bmp-operation-web/src/views/modelManagement/list/module.ts b/bmp-operation-web/src/views/modelManagement/list/module.ts new file mode 100644 index 0000000..5963ed1 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/module.ts @@ -0,0 +1,21 @@ +import TableList from './table/tableList.vue'; +import CustomList from './custom/customList.vue'; +import ExportData from './export/exportData.vue'; +// import Pagination from './pagination/pagination.vue'; +// import AddModelOperate from './addModel/addModelOperate.vue'; +// import EditModelOperate from './editModel/editModelOperate.vue'; +import DeleteModelOperate from './deleteModel/deleteModelOperate.vue'; +// import AddModelTemplate from './addIdenticalModel/addIdenticalModel.vue'; + +const pluginComp = { + TableList, + CustomList, + ExportData, + // Pagination, + // AddModelOperate, + // EditModelOperate, + DeleteModelOperate, + // AddModelTemplate +}; + +export default pluginComp; diff --git a/bmp-operation-web/src/views/modelManagement/list/page.ts b/bmp-operation-web/src/views/modelManagement/list/page.ts new file mode 100644 index 0000000..32313ab --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/page.ts @@ -0,0 +1,10 @@ +const ModelList = () => import(/* webpackChunkName: "ModelList" */ './modelList.vue'); + +export default { + path: '/ModelManagement/modelList', + name: 'ModelList', + component: ModelList, + meta: { + type: 'modelList' + } +}; diff --git a/bmp-operation-web/src/views/modelManagement/list/search/search.ts b/bmp-operation-web/src/views/modelManagement/list/search/search.ts new file mode 100644 index 0000000..e7f2c33 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/search/search.ts @@ -0,0 +1,73 @@ +import {SearchArrType} from '../typeManagement'; +import {language, paginationOperate} from 'utils/publicClass.ts'; + +class SearchOperate { + hasClear: Ref = ref(false); + // 搜索框值 + selectVal: Ref = ref(0); + reactiveArr: SearchArrType = reactive({ + searchParams: {}, + selectOption: [ + { + value: 0, + label: language.t('modelList.header.label.modelName') + }, + { + value: 1, + label: language.t('modelList.header.label.modelSpecifications') + } + ] + }); + fn: any; + + constructor (fn: any) { + this.fn = fn; + }; + + iptValue = (enterValue: string, selectValue: number) => { + selectValue ? this.reactiveArr.searchParams = {deviceType: enterValue} : this.reactiveArr.searchParams = {name: enterValue}; + }; + + /** + * input 输入框 点击搜索按钮或者回车触发 + * @param {string} enterValueIpt 输入框输入的值 + * @param {number} selectValue 筛选框筛选的值 + */ + enterValueIpt = (enterValueIpt: string, selectValue: number): void => { + selectValue ? this.reactiveArr.searchParams = {deviceType: enterValueIpt} : this.reactiveArr.searchParams = {name: enterValueIpt}; + this.request(); + }; + + /** + * 搜索框筛选 + * @param {number} val 搜索框切换的搜索key + * @return {number} selectVal 对应的key + */ + changeSelect = (val: number): number => { + return this.selectVal.value = val; + }; + + clearClick = (val: string) => { + if (!val) { + this.selectChange(); + } + }; + + selectChange = () => { + const {deviceType, name}: {deviceType?: string; name?: string;} = this.reactiveArr.searchParams; + if (deviceType || name) { + this.reactiveArr.searchParams = {}; + this.request(); + } + }; + + request = () => { + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn(); + }; +}; + +export default SearchOperate; diff --git a/bmp-operation-web/src/views/modelManagement/list/table/filterStyle.ts b/bmp-operation-web/src/views/modelManagement/list/table/filterStyle.ts new file mode 100644 index 0000000..6de878d --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/table/filterStyle.ts @@ -0,0 +1,134 @@ +/** + * @file + * @author +*/ + +class FilterStyleOperate { + classNameData = [ + { + name: 'def-type-status0', + // name: 'def-model-type-status', + type: 'deviceSeries' + } + ]; + filterStatus: { + deviceSeries: boolean + } = reactive({ + deviceSeries: false + }) + + constructor (props: any) { + onMounted(() => { + nextTick(() => { + this.customFilter(props); + }) + this.watchSearchTip(props); + this.watchFilter(props); + }) + }; + + watchSearchTip = (props: any) => { + watch(() => + props.modelList.searchTip, (newValue) => { + const that = this; + if (!newValue.value) { + for (let index in this.filterStatus) { + (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = false; + } + } + else { + this.setFilterStatus(props.filter.reactiveArr.filterParams); + } + }, { + deep: true + }); + }; + + watchFilter = (props: any) => { + watch(() => props.filter.reactiveArr.filterParams, (newValue) => { + this.setFilterStatus(newValue); + }, {deep: true}) + }; + + setFilterStatus = (params: any) => { + const that = this; + this.classNameData.forEach((item) => { + if (['', void 0].includes(params[item.type])) { + (this.filterStatus[`${item.type}` as keyof typeof that.filterStatus] as boolean) = false; + return; + } + (this.filterStatus[`${item.type}` as keyof typeof that.filterStatus] as boolean) = true; + }) + }; + + customFilter = (props: any) => { + let filterName: HTMLElement | null; + let filterOpt: HTMLElement | null; + const that = this; + this.classNameData.forEach((item) => { + filterName = document.querySelector(`.${item.name} > .cell`); + filterOpt = document.querySelector(`.${item.name} > .cell > .el-table__column-filter-trigger`) + filterName?.addEventListener('click', (event) => { + event.stopPropagation(); + for (let index in this.filterStatus) { + (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = false; + } + }) + filterOpt?.addEventListener('click', (event) => { + event.stopPropagation(); + (this.filterStatus[`${item.type}` as keyof typeof that.filterStatus] as boolean) = !(this.filterStatus[`${item.type}` as keyof typeof that.filterStatus] as boolean); + }); + const filterOtherRegion = document.querySelectorAll('.el-table-filter'); + filterOtherRegion.forEach((_, index) => { + filterOtherRegion[index]?.addEventListener('click', (event) => { + event.stopPropagation(); + for (let index in this.filterStatus) { + for (const key of this.classNameData) { + if (index === key.type && props.modelList.filter.reactiveArr.filterParams[key.type]) { + (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = true; + } + } + } + }) + }) + + let newType = []; + document.addEventListener('click', (event) => { + event.stopPropagation(); + newType = []; + newType.push(item.type); + newType.forEach((ite) => { + this.filterDispose(ite, props); + }) + }) + }) + }; + + filterDispose = (type: string, props: any) => { + const filterVal = props.filter.reactiveArr.filterParams; + const that = this; + if (props.modelList.searchTip.value) { + for (let key in filterVal) { + if (key === type) { + (this.filterStatus[`${key}` as keyof typeof that.filterStatus] as boolean) = true; + // this.filterStatus[key] = true; + } + else { + // this.filterStatus[type] + if ((this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean) && Object.keys(filterVal).length > 1) { + (this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean) = !(this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean); + } + else { + (this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean) = false; + // this.filterStatus[type] = false; + } + } + } + } + else { + (this.filterStatus[`${type}` as keyof typeof that.filterStatus] as boolean) = false; + } + } +}; + +export default FilterStyleOperate; diff --git a/bmp-operation-web/src/views/modelManagement/list/table/setEmpty.ts b/bmp-operation-web/src/views/modelManagement/list/table/setEmpty.ts new file mode 100644 index 0000000..8343c5e --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/table/setEmpty.ts @@ -0,0 +1,64 @@ +/** + * @file + * @author +*/ + +import {language} from 'utils/publicClass.ts'; + +const p = document.createElement('p'); + +interface PropsType { + modelList: { + reactiveArr: { + tableData: [] + } + } +} + +class SetEmpty { + emitValue: Function; + + constructor(props: PropsType, emitValue: Function) { + this.emitValue = emitValue; + this.watchTableData(props); + onUnmounted(() => p.innerHTML = ''); + }; + + watchTableData = (props: PropsType) => { + watch(() => props?.modelList?.reactiveArr.tableData, (newValue) => { + if (!newValue?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.innerHTML= ''; + }, {deep: true}) + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + ai!.innerHTML = ''; + const customText = document.querySelector('.model-list .el-scrollbar__view'); + if (!customText) return; + const str = ` + + ${language.t('table.empty')},${language.t('table.tip')} + + + ${language.t('modelList.header.operate.addModel')} + + ` + const parser = new DOMParser(); + const doc = parser.parseFromString(str, 'text/html'); + p.className = 'custom-tip-count'; + p.innerHTML = doc.body.innerHTML; + customText.appendChild(p) + const clickOpt = document.querySelector('.model-list .custom-tip-count .empty-text'); + clickOpt!.addEventListener('click', () => { + this.emitValue('empty-click') + }); + }; +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/modelManagement/list/table/tableFilter.ts b/bmp-operation-web/src/views/modelManagement/list/table/tableFilter.ts new file mode 100644 index 0000000..0a8b706 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/table/tableFilter.ts @@ -0,0 +1,89 @@ +import store from 'store/index.ts' +import {OSSType, ReactiveArrType} from '../typeManagement'; +import {paginationOperate} from 'utils/publicClass.ts'; + +/** + * 筛选操作 +*/ +class FilterOperate { + // store库存储的oss数据类 + ossStore: OSSType = store.ossDataInfo(); + // modelDetailStore(); + tableRef: { + [x: string]: unknown; + value: { + clearFilter(): unknown; + } + } = {value: {clearFilter(): void{}}}; + filterEmptyInfo: { // store + filterParams( + arg0: {[x: string]: number | string}, + arg1: OSSType, + arg2: ReactiveArrType, + arg3: {deviceSeries?: string;} + ): Promise; + deleteEmtpyData(arg0: {deviceSeries?: string;}): unknown; + } = store.filterEmpty; + // 复杂数据类型 + reactiveArr: { + filterParams: {deviceSeries?: string;}; + } = reactive<{ + filterParams: {deviceSeries?: string;}; + }>({ + filterParams: {} + }); + fn: any; + + // 构造器 + constructor (fn: any) { + this.fn = fn; + this.ossStore?.getOssData(); + }; + + /** + * 获取表格ref + * @param {Object} tableEl 表格信息 + */ + getTableRef = (tableEl: { + [x: string]: unknown + value: { + clearFilter(): unknown; + } + }): void => { + this.tableRef = tableEl; + }; + + /** + * 机型filter + * @return {boolean} xxx 返回对应信息 + */ + deviceSeriesFilter = (): boolean => { + return true; + }; + + /** + * @param {Object} filter 需要过滤的数据 + */ + filterChange = (filter: {[x: string]: number | string}) => { + const filterParams: {deviceSeries: string;} = { + deviceSeries: 'deviceSeries' + }; + this.filterEmptyInfo.filterParams(filter, this.ossStore, this.reactiveArr, filterParams) + .then((res: any) => { + this.reactiveArr.filterParams = res.filterParams; + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn(); + }); + // .catch(() => { + // this.reactiveArr.filterParams = {}; + // this.tableRef?.value?.clearFilter(); + // this.filterEmptyInfo.deleteEmtpyData(this.reactiveArr.filterParams); + // this.modelList.setFilterData(null, null); + // }); + }; +}; + +export default FilterOperate; diff --git a/bmp-operation-web/src/views/modelManagement/list/table/tableList.vue b/bmp-operation-web/src/views/modelManagement/list/table/tableList.vue new file mode 100644 index 0000000..97594de --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/table/tableList.vue @@ -0,0 +1,737 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/list/table/tableScroll.ts b/bmp-operation-web/src/views/modelManagement/list/table/tableScroll.ts new file mode 100644 index 0000000..fae94b8 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/table/tableScroll.ts @@ -0,0 +1,99 @@ +import {HeightType3, HeightType2} from '@utils/publicType'; +import {tableScroll} from 'utils/index.ts'; +import {TableScrollType} from '../typeManagement'; +import store from 'store/index.ts'; + +interface TableScrollDataType { + scrollTimer: null | number; + searchTipHeight: number; + fixedHeight: Ref; + tableMaxHeight: Ref; + status: boolean; + headerTitle: Ref; + operate: Ref; + operateBtn: Ref; +}; + +const tableScrollOperate = (filters: TableScrollType['filters'], search: TableScrollType['search'], searchTip: {value: boolean}) => { + const data: TableScrollDataType = { + scrollTimer: null, + searchTipHeight: 13, + fixedHeight: ref(0), + tableMaxHeight: ref(0), + status: false, + headerTitle: ref({offsetHeight: 0, scrollHeight: 0}), + operate: ref({offsetHeight: 0, scrollHeight: 0}), + operateBtn: ref({offsetHeight: 0}) + }; + onMounted(() => { + setScroll(setHeight(), data.tableMaxHeight); + onResize(data.tableMaxHeight); + }); + + onUnmounted(() => { + clearTimeout(data.scrollTimer as number) + }) + + + watch(() => [ + filters.filterParams, + search.searchParams, + searchTip, + ], (newValue: any) => { + if (newValue[2].value) { + setScroll(setHeight(), data.tableMaxHeight); + } + }, {deep: true}) + + watch(() => store.navigationBarStatus.hasNavigationBar, (_: boolean) => { + data.scrollTimer = setTimeout(() => { + setScroll(setHeight(), data.tableMaxHeight); + }, 200) + }); + + const onResize = (tableMaxHeight: {value: number}) => { + window.onresize = () => { + setScroll(setHeight(), tableMaxHeight); + }; + }; + + const setHeight = () => { + const header = data.headerTitle.value; + const operate = data.operate.value; + data.fixedHeight.value = header.offsetHeight * 2.9 + operate.offsetHeight + data.operateBtn.value.offsetHeight; + const countHeight: number = data.fixedHeight.value; + return countHeight; + }; + + const setScroll = (countHeight: number, tableMaxHeight: {value: number}) => { + const deviceSeries: string = filters.filterParams?.deviceSeries??''; + const name: string = search.searchParams?.name??''; + const deviceType: string = search.searchParams?.deviceType??''; + if ([deviceSeries, name, deviceType].some((item: string) => item !== '')) { + tableScroll(countHeight + data.searchTipHeight, tableMaxHeight); + return; + } + tableScroll(countHeight, tableMaxHeight); + }; + + const getBtnRef = (val: {value: HeightType2}) => { + data.operateBtn.value = val.value; + }; + + const getHeaderRef = (val: {value:HeightType3}) => { + data.headerTitle.value = val.value; + }; + + const getOperateRef = (val: {value: HeightType3})=> { + data.operate.value = val.value; + }; + + return { + ...data, + getBtnRef, + getHeaderRef, + getOperateRef + } +}; + +export default tableScrollOperate; diff --git a/bmp-operation-web/src/views/modelManagement/list/typeManagement.ts b/bmp-operation-web/src/views/modelManagement/list/typeManagement.ts new file mode 100644 index 0000000..e1c0b21 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/list/typeManagement.ts @@ -0,0 +1,115 @@ +import {CurrencyType1 } from "@utils/publicType"; + +type TableType = {name: string; deviceType: string;} & CurrencyType1; + +type JumpRouterType = Required<{type: string; deviceTypeId: string; architecture: string;}>; + +// 导出类型 +type ExportType = {modelListExportAPI: Function; hasExportData: {value: boolean;}; exportData: Function;}; + +/** + * text类 +*/ +type TextType = { + [x: string]: { + text: string; + }; +}; + +interface OSSType { + deviceSeries: TextType; + getOssData(): void; +}; + +interface SearchArrType { + searchParams: { + name?: string; + deviceType?: string; + }; + selectOption: { + value: number; + label: string; + }[]; +}; + +/** + * 参数类型 +*/ +interface ParamType { + pageNumber: number; + pageSize: number; +}; + +interface RefreshType { + // modelList: { + // reactiveArr: { + // tableData: string | never[]; + // }; + // getModelList(): void; + // }; + modelList: { reactiveArr: { tableData: string | unknown[]; }; getModelList: () => void; }; + reset: { + reset(): void; + }; +} + +/** + * filter参数类 +*/ +type FilterParamsType = {deviceSeries?: string;}; + + +/** + * 复杂数据类型类 +*/ +type ReactiveArrType = {filterParams?: FilterParamsType;}; +interface ResetType { + filter: { + tableRef: { + value: { + clearFilter: () => void; + }; + }; + reactiveArr: { + filterParams: {}; + }; + }; + search: { + hasClear: { + value: boolean; + }; + reactiveArr: { + searchParams: {}; + }; + request(): void; + } +}; + + +interface TableScrollType { + filters: { + filterParams: { + deviceSeries?: string; + }; + }; + search: { + searchParams: { + name?: string; + deviceType?: string; + }; + } +} + +export { + OSSType, + TableType, + JumpRouterType, + ExportType, + SearchArrType, + RefreshType, + TableScrollType, + ResetType, + ReactiveArrType, + ParamType +}; + diff --git a/bmp-operation-web/src/views/modelManagement/modelAddTemplate/addModelTemplate.vue b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/addModelTemplate.vue new file mode 100644 index 0000000..14bd1d1 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/addModelTemplate.vue @@ -0,0 +1,1161 @@ + + + + diff --git a/bmp-operation-web/src/views/modelManagement/modelAddTemplate/index.scss b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/index.scss new file mode 100644 index 0000000..d3b82cd --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/index.scss @@ -0,0 +1,624 @@ +@import '@/assets/css/communal'; + +.model-operate { + // .el-dialog { + // &--center { + // --el-dialog-width: 690px; + // height: 498px; + // } + + // &__body { + // height: 358px; + // overflow-y: auto; + // overflow-x: hidden; + // } + + // &__footer { + // width: 645px; + // } + // } + + .volume-manager-table { + + .el-form-item__content { + justify-content: center; + } + // .el-input__inner { + // width: 200px; + // // // min-width: 87px; + // } + + + + // .ipt-defaults, + .ipt-height { + margin-top: 20px; + margin-bottom: 45px !important; + .el-form-item__content { + // height: 90px; + // height: 93px; + position: relative; + margin-bottom: 10px; + + .el-input { + // margin-bottom: 40px; + } + + .el-form-item__error { + text-align: left; + line-height: 1.2; + top: 100%; + // top: 50%; + padding-top: 7px; + } + } + } + + + .ipt-default { + // margin-bottom: 40px !important; + // margin-bottom: 10px !important; + .el-form-item__content { + // height: 30px; + + // height: 30px; + // margin-bottom: 10px; + + .el-input-number { + margin-bottom: 0px; + .el-input { + + margin-bottom: 0; + } + } + + .el-input { + margin-bottom: 0px; + } + } + } + + } + .el-table__empty-block { + background-color: #fff; + } + .set-right { + .el-form-item__label { + margin-right: 30px; + } + } + + .save-btn { + margin-bottom: 36px; + } + + .edit-btn { + margin-bottom: 0 !important; + } + .operate-btn { + cursor: pointer; + color: #108ee9; + // margin-bottom: 47px; + span { + font-size: 12px; + &:first-child { + margin-right: 10px; + } + } + } + + .active-ipt { + input { + border-color: #f56c6c; + } + } + + .template-tip { + font-size: 12px; + color: #333; + font-weight: 600; + margin-bottom: 20px; + margin-left: 12px; + } + + .error-tip { + position: absolute; + color: #f56c6c; + font-weight: 600; + text-align: left; + left: 0; + padding-top: 35px; + top: 0; + line-height: 1.4; + font-size: 12px; + z-index: -1; + + // &:hover { + // background: #f7f7f7; + // } + } + .default-ipt { + input { + border-color: #dcdfe6; + } + } + + .default-right { + .el-form-item__label { + margin-right: 10px; + } + } + + .boot-mode-count { + margin: 20px 0 18px; + + .el-checkbox__label { + height: 20px; + line-height: 20px; + } + } + + + .add-volume-en { + font-size: 12px; + margin-left: 165px; + } + + .add-volume { + font-size: 12px; + margin-left: 115px; + } + + .default-s { + color: #999; + cursor: no-drop; + margin-top: 5px; + } + + .active { + cursor: pointer; + color: #108ee9; + } + + .set-top { + margin-top: 22px !important; + } + + #volumeManager { + display: flex; + align-items: flex-start; + margin-bottom: 0 !important; + white-space: nowrap; + + label { + line-height: 4; + + &::before { + content: "*"; + color: var(--el-color-danger); + margin-right: 4px; + } + } + } + + &-rule-form { + // margin-top: 20px; + + .el-input__inner { + // width: 507px; + // min-width: 87px; + } + + .flex-checkbox { + display: flex; + align-items: center; + + .el-checkbox { + width: auto; + margin-bottom: 0; + align-items: center !important; + } + } + + #bootMode { + .el-form-item__label { + &::before { + position: relative; + font-weight: 600; + line-height: 1.5; + display: flex; + align-items: flex-start; + word-wrap: break-word; + word-break: keep-all; + content: "*"; + color: var(--el-color-danger); + margin-right: 4px; + } + } + } + + .set-empty { + margin-bottom: 32px !important; + .el-form-item__error { + margin-top: 6px !important; + } + } + + .set-empty1 { + margin-bottom: 28px !important; + .el-form-item__error { + margin-top: 6px !important; + } + } + + .set-default { + margin-bottom: 12px !important; + } + + .is-loading { + position: absolute; + top: 8px; + right: 0; + transform: translateY(-50%); + animation: loading .7s linear ease-in-out; + } + + @keyframes loading { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(100deg); + } + } + + .set-name-bottom { + margin-bottom: 47px !important; + + .el-form-item__error { + margin-top: 5px !important; + } + } + + .set-label { + display: flex; + align-items: flex-start !important; + + .el-form-item__content { + .radio-button-text-ellipsis { + margin-bottom: 5px; + } + } + } + + .device-type-count { + position: relative; + } + + .el-form-item--default { + display: flex; + align-items: center; + + .el-form-item__label { + position: relative; + font-weight: $fontLargeWeight; + line-height: 1.5; + display: flex; + align-items: flex-start; + word-wrap: break-word; + word-break: keep-all; + } + } + + .error-device-type { + input { + border-color: #f56c6c; + } + } + + .has-error-device-type { + position: absolute; + top: 22px; + font-size: $fontSize; + color: #f56c6c; + } + + .model-name { + .el-input { + width: auto; + } + } + .specifications { + + .el-input { + width: auto; + } + .el-form-item__content { + position: relative; + } + } + + .el-input--default, + .el-form-item__content { + display: flex; + } + + .set-desc { + .el-form-item__label { + display: flex; + align-items: flex-start; + margin-top: 5px; + width: 130px !important; + margin-left: 10px; + margin-top: -50px; + } + .el-input__count { + font-size: $fontSize; + color: $color7; + font-weight: $fontSmallWeight; + } + } + .set-english-width { + .el-form-item__label { + width: 130px !important; + margin-left: 10px; + } + } + + .set-width { + .el-form-item__label { + width: 100px !important; + margin-left: 10px; + } + } + + .el-table__row { + .el-table__cell { + // display: flex; + padding: 0; + + // align-items: flex-start; + // width: 100%; + + // .cell { + // width: 100%; + // } + } + } + + .el-select { + width: 100%; + } + + // .min-size-count { + // // display: flex; + // // align-items: center; + // // justify-content: center; + + // .unit-select { + // .el-input__inner { + // width: 100px; + // } + // } + + // .num-ipt { + // .el-input__inner { + // width: 100px; + // } + // } + + + // // .el-form-item__content { + // // justify-content: flex-end; + // // } + // } + + &-desc { + + .el-textarea { + width: 507px; + } + .el-form-item__label { + width: 100px !important; + margin-left: 10px; + margin-top: -50px; + } + + .el-textarea__inner { + height: 78px; + padding: 5px 8px; + margin-top: 7px; + resize: none; + + &::placeholder { + font-size: $fontSize; + } + + font-size: $fontSize; + } + + .el-input__count { + font-size: $fontSize; + color: $color7; + font-weight: $fontSmallWeight; + // right: 86px; + } + } + + .hide-label { + .el-form-item__label { + opacity: 0; + } + } + + .set-select-width { + .el-form-item__content { + input { + width: 260px; + } + } + } + + .multiple-choice { + input { + width: 100%; + // width: 200px; + } + } + + // .set-type-width { + // .el-form-item__content { + // input { + // width: 275px; + // } + // } + // } + + .select-width { + .el-form-item__content { + .el-select, + input { + width: 235px; + } + } + } + + .set-data-sys-style { + .el-form-item__content { + input { + width: 300px; + border-top-right-radius: 0; + border-bottom-right-radius: 0; + } + + .el-select { + position: absolute; + left: 300px; + + input { + width: 65px; + border-top-left-radius: 0; + border-bottom-left-radius: 0; + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; + border-left: 0; + + // &:active, + // &:focus { + // // border-color: $border2 !important; + // } + } + } + } + } + + .sys-single-capacity, + .data-single-capacity { + .el-form-item__content { + width: 224px; + position: relative; + + input { + // width: 160px; + // border-top-right-radius: 0; + // border-bottom-right-radius: 0; + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; + // border-right: 0 !important; + } + + .el-select .el-input.is-focus .el-input__inner { + border-color: #dcdfe6 !important; + } + + .el-select { + width: 67px; + position: absolute; + // left: 150px; + right: 0; + + input { + width: 65px; + border-top-left-radius: 0; + border-bottom-left-radius: 0; + // border-top-right-radius: 4px; + // border-bottom-right-radius: 4px; + border-top: 0; + height: 28px; + border-bottom: 0; + border-right: 0; + margin-right: 1px; + // border-left: 0; + + // &:hover, + // &:active, + &:focus { + border-color: #dcdfe6 !important; + // border-color: $border2 !important; + } + } + } + } + } + + .el-form-item__label, + .el-input__inner { + font-size: $fontSize; + color: $defaultColor; + } + + .el-form-item--default { + margin-bottom: 18px; + + &:last-child { + margin-bottom: 0; + } + } + + input { + // width: 450px; + height: 30px; + border-radius: 4px; + } + } + + .set-bottom { + margin-bottom: 24px; + } + + .en-table-error-tip { + margin-left: 170px; + font-size: 12px; + margin-bottom: 20px; + color: #f56c6c; + } + + .table-error-tip { + margin-left: 115px; + font-size: 12px; + margin-bottom: 20px; + color: #f56c6c; + } + + .set-from-img, + .model-from-img { + position: absolute; + right: 0px; + top: 50%; + transform: translateY(-50%); + width: 16px; + height: 16px; + position: absolute; + } + + .footer-btn { + display: flex; + align-items: center; + justify-content: center; + margin-bottom: 50px; + button { + width: 150px; + height: 36px; + } + } +} diff --git a/bmp-operation-web/src/views/modelManagement/modelAddTemplate/noConfiguration.vue b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/noConfiguration.vue new file mode 100644 index 0000000..b71058d --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/noConfiguration.vue @@ -0,0 +1,338 @@ + + + + diff --git a/bmp-operation-web/src/views/modelManagement/modelAddTemplate/page.ts b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/page.ts new file mode 100644 index 0000000..8fc8ec6 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/page.ts @@ -0,0 +1,10 @@ +const AddModelTemplate = () => import(/* webpackChunkName: "AddModelTemplate" */ './addModelTemplate.vue'); + +export default { + path: '/ModelManagement/addModelTemplate', + name: 'AddModelTemplate', + component: AddModelTemplate, + meta: { + type: 'addModelTemplate' + } +}; diff --git a/bmp-operation-web/src/views/modelManagement/modelAddTemplate/typeManagement.ts b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/typeManagement.ts new file mode 100644 index 0000000..04a489b --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/typeManagement.ts @@ -0,0 +1,173 @@ +import {CurrencyType, CpuDataType, MemDataType, VerifyRulesType} from '@utils/publicType'; + +type key = 'name' | 'value'; + +type key1 = 'hasClick' | 'hasClick1' | 'hasClick2' | 'hasClick3' | 'hasClick4' | 'sysRaidFlag' | 'raidConfig'; + +/** + * 机型类型 +*/ +type RadioBtnType = { + [k in key]: string; +}; + +// type RadioBtnType = { [key in keyof T]: string} + +type IdcNameRadioBtnType = { + find(arg0: (item: {title: string;}) => boolean): {idcId: string; title: string;}; +}; + +/** + * 机房名称类 +*/ +type ComputerRoomRadioBtnType = { + title: string; + idcId: string; + showTooltip: boolean; +}; + +/** + * 通用操作类 +*/ +interface ProcessingOperationsType { + setModelType: any; + // processingOperations(formSubmit: CurrencyType): CurrencyType; + // cpuPreset(formSubmit: CurrencyType): CurrencyType; + // memPreset(formSubmit: CurrencyType): CurrencyType; + // setCpuMemData(arg0: boolean, arg1: boolean, arg2: CurrencyType): Promise; + // setFormData(formSubmit: CurrencyType): CurrencyType; + // setErrorHeight(arg0: Ref[], arg1: boolean, arg2: boolean, arg3: Ref, arg4: Ref, arg5: any, arg6: any): never; +}; + +/** + * 复杂数据类 +*/ +interface ReactiveDataType { + radioBtn: RadioBtnType[]; + computerRoomRadioBtn: ComputerRoomRadioBtnType[]; + modelCPUBtn: string[]; + storageData: string[]; +}; + +/** + * 规则验证类 +*/ +interface RuleFormType { + templateName: string; + deviceTypeName: string; + bootMode: string[] | string; + machineRoomName: string; + cpuSpec: string; + memSpec: string; + idcId: string; + modelType: string; + arrayCard: string; + // raidCan: any; + name: string; + architecture: string | number; + deviceType: string; + description: string; + modelCPU: string; + cpuInfo: string; + cpuManufacturer: string; + cpuModel: string; + cpuCores: number | string; + cpuFrequency: string; + cpuAmount: string | number; + modelStorage: string; + memInfo: string; + memType: string; + memFrequency: string | number; + memSize: string | number; + memAmount: string | number; + volumeManagerTableData: any; + noConfigurationData: any; + // systemVolumeType: string; + // systemVolumeInterfaceType: string; + // systemVolumeSize: string | number | null; + // systemVolumeUnit: string | number; + // systemVolumeAmount: string | number; + // sysRaid: string[]; + // dataVolumeType: string; + // dataVolumeInterfaceType: string; + // dataVolumeSize: string | null; + // dataVolumeUnit: string | number; + // dataVolumeAmount: number; + nicRate: number | string; + nicAmount: number; + interfaceMode: string | number; + gpuManufacturer: string; + gpuModel: string; + gpuAmount: number; + height: string | number; + cpuData: CpuDataType[]; + memData: MemDataType[]; +}; + +/** + * 规则类 +*/ +interface RulesType { + name: VerifyRulesType[]; + architecture: VerifyRulesType[]; + deviceType: VerifyRulesType[]; + cpuInfo: VerifyRulesType[]; + cpuManufacturer: VerifyRulesType[]; + cpuModel: VerifyRulesType[]; + cpuCores: VerifyRulesType[]; + cpuFrequency: VerifyRulesType[]; + memInfo: VerifyRulesType[]; + memType: VerifyRulesType[]; + memFrequency: VerifyRulesType[]; + memSize: VerifyRulesType[]; + systemVolumeType: VerifyRulesType[]; + systemVolumeInterfaceType: VerifyRulesType[]; + systemVolumeSize: VerifyRulesType[]; + systemVolumeUnit: VerifyRulesType[]; + sysRaid: VerifyRulesType[]; + dataVolumeType: VerifyRulesType[]; + dataVolumeInterfaceType: VerifyRulesType[]; + dataVolumeSize: VerifyRulesType[]; + dataVolumeUnit: VerifyRulesType[]; + dataVolumeAmount: VerifyRulesType[]; + nicRate: VerifyRulesType[]; + nicAmount: VerifyRulesType[]; + interfaceMode: VerifyRulesType[]; + gpuManufacturer: VerifyRulesType[]; + gpuModel: VerifyRulesType[]; + gpuAmount: VerifyRulesType[]; + height: VerifyRulesType[]; +}; + +interface PropsReactiveType { + architecture: string[]; + raidData: any; + volumeTypeData: string[]; + diskTypeData: {label: string; value: string}[]; + noRaidInterfaceData: {label: string; value: string}[]; + interfaceData: {label: string; value: string}[]; + raidConfig: string[]; + noSysRaid: {label: string; value: string}[]; + sysRaid: {label: string; value: string}[]; + sysDiskRaid0: {label: string; value: string}[]; + bootModeData: {label: string; select: boolean;}[]; + computerRoomRadioBtn: {title: string; idcId: string; showTooltip: boolean;}[]; +}; + +interface RadiosPropsType { + hasTemplate: boolean; + formData: {value: CurrencyType;}; cpuSpec: string; memSpec: string; +}; + +export { + key1, + CpuDataType, + MemDataType, + RulesType, + RuleFormType, + ProcessingOperationsType, + RadiosPropsType, + PropsReactiveType, + ReactiveDataType, + IdcNameRadioBtnType +}; diff --git a/bmp-operation-web/src/views/modelManagement/modelAddTemplate/utils/dataOperate.ts b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/utils/dataOperate.ts new file mode 100644 index 0000000..33087ca --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/utils/dataOperate.ts @@ -0,0 +1,313 @@ +// deepCopy +import {filterData, deepCopy} from 'utils/index.ts'; +import {language, locationItem, CurrentInstance} from 'utils/publicClass.ts'; +import {CurrencyType} from '@utils/publicType'; +// RadiosPropsType +import {CpuDataType, MemDataType, RuleFormType, PropsReactiveType} from '../typeManagement'; +import store from 'store/index.ts'; +// import ModelStaticData from 'staticData/model/index.ts'; + +// let raidList: any = []; +// let sysRaidData: any = []; +class DataOperate { + idcData = store.idcInfo.idcDataNoOpt; + raidsStore = store.modeFormInfo(); + // 复杂数据类型 + reactiveData: PropsReactiveType = reactive({ + architecture: [], + raidConfig: [], + raidData: {}, + sysRaid: [], + noSysRaid: [], + sysDiskRaid0: [], + volumeTypeData: [ + language.t('modelForm.label.system'), + language.t('modelForm.label.data') + ], + bootModeData: [ + { + select: true, + label: '--' + }, + { + select: true, + label: '--' + } + ], + diskTypeData: [ + { + label: 'SSD', + value: 'SSD' + }, + { + label: 'HDD', + value: 'HDD' + }, + { + label: language.t('modelForm.unrestricted'), + value: 'notLimited' + } + ], + noRaidInterfaceData: [ + { + label: 'NVME', + value: 'NVME' + } + ], + interfaceData: [ + { + label: 'SATA', + value: 'SATA' + }, + { + label: 'SAS', + value: 'SAS' + }, + { + label: language.t('modelForm.unrestricted'), + value: 'notLimited' + } + ], + computerRoomRadioBtn: [ // 机房名称 + { + title: '', + idcId: '', + showTooltip: false + } + ] + }); + ruleForm: any; + proxy = new CurrentInstance().proxy; + // props: {cpuSpec: string; memSpec: string; hasTemplate: boolean;} & RadiosPropsType + constructor (ruleForm: RuleFormType) { + this.ruleForm = ruleForm; + const val = localStorage.getItem('model-item')?? ''; + const newVal = JSON.parse(val); + ruleForm.modelCPU = this.#setDefText(newVal.cpuSpec); + ruleForm.modelStorage = this.#setDefText(newVal.memSpec); + // props + this.architectureData(ruleForm); + if (!this.idcData?.length) { + this.idcList(ruleForm); + return; + }; + this.getIdcData(this.idcData, ruleForm); + }; + + #setDefText = (value: string) => { + const text = new Map([ + ['common', language.t('modelForm.specificationsType.presetSpecifications')] + ]); + return text.get(value)?? language.t('modelForm.specificationsType.otherSpecifications'); + }; + + // , props: any + architectureData = (ruleForm: RuleFormType) => { + const val = localStorage.getItem('model-item')?? ''; + const newVal = JSON.parse(val); + this.raidsStore.getCommonData() + .then((res: {architecture: CurrencyType; cpuSpec: CpuDataType[]; memSpec: MemDataType[]; raidRules: CurrencyType; bootMode: string[]}) => { + const {architecture, cpuSpec, memSpec, raidRules, bootMode} = res; + this.reactiveData.raidData = raidRules; + // 无 + const noneInfo = Object.values(raidRules['1']); + // RAID数据 + const raidInfo = Object.values(raidRules['2']); + // 单盘RAID0 + const singleInfo = Object.values(raidRules['3']); + const newNone: {label: string; value: string;}[] = []; + const newRaid: {label: string; value: string;}[] = []; + const singleRaid: {label: string; value: string;}[] = []; + this.reactiveData.noSysRaid = this.#setRaidData(noneInfo, newNone); + this.reactiveData.sysRaid = this.#setRaidData(raidInfo, newRaid); + this.reactiveData.sysDiskRaid0 = this.#setRaidData(singleInfo, singleRaid); + const raidRulesData = Object.values(raidRules); + this.reactiveData.raidConfig = this.#setRaidCan(raidRulesData); + this.reactiveData.architecture = Object.keys(architecture); + this.reactiveData.bootModeData = bootMode.map((item: string) => { + return { + label: item, + select: true + } + }); + ruleForm.cpuData = cpuSpec; + ruleForm.memData = memSpec; + ruleForm.bootMode = bootMode.join(','); + // ruleForm, props + // this.setCpuMemStatus(ruleForm, newVal.cpuSpec, newVal.memSpec) + this.raidsData(ruleForm, newVal); + }); + }; + + #setRaidCan = (raidRulesData: string[]): string[] => { + const raidCan: string[] = []; + raidRulesData.forEach((t: string) => { + Object.keys(t).forEach((g: string) => { + raidCan.push(g); + }) + }) + return raidCan; + } + + #setRaidData = (dataInfo: string[], raid: {label: string; value: string;}[]) => { + dataInfo.forEach((item: string) => { + Object.keys(item).forEach((t: any) => { + raid.push({ + label: t, + value: item[t] + }) + }) + }) + return raid; + } + + idcList = async (ruleForm: {machineRoomName: string; idcId: string}) => { + try { + const res = await this.proxy.$idcApi.idcListAPI({isAll: '1'}); + if (res?.data?.result?.idcs?.length) { + const {idcs} = res.data.result; + this.getIdcData(idcs, ruleForm); + } + } + catch { + throw new Error(); + } + }; + + getIdcData = (data: CurrencyType[], ruleForm: {machineRoomName: string; idcId: string}) => { + this.reactiveData.computerRoomRadioBtn = filterData(data, 'name') + .map((item: {name: string; nameEn: string; idcId: string}) => { + return { + ...item, + title: this.#setName(locationItem.getLocationItem, item), + idcId: item.idcId + } + }); + if (!ruleForm.machineRoomName?.length) { + ruleForm.machineRoomName = this.reactiveData.computerRoomRadioBtn[0].title; + ruleForm.idcId = this.reactiveData.computerRoomRadioBtn[0].idcId; + } + }; + + #setName = (name: string, item: CurrencyType) => { + const keyName: Map = new Map([ + ['zh_CN', item.name], + ['en_US', item.nameEn] + ]); + return keyName.get(name); + }; + + /** + * 获取raids数据 + */ + raidsData = (ruleForm: any, newVal: any) => { + // ruleForm: RuleFormType, props: RadiosPropsType + // raidList = []; + // sysRaidData = [] + // 如果有数据(添加机型时不需要) + // if (props?.formData?.value) { + for (const key in newVal) { + for (const index in ruleForm) { + if (key === index) { + this.setCpuMemStatus(ruleForm, newVal.cpuSpec, newVal.memSpec); + (ruleForm[`${index}` as keyof typeof ruleForm] as string) = newVal[index]; + } + } + } + + // if (newVal.hasTemplate) { + ruleForm.templateName = deepCopy(ruleForm.name); + ruleForm.name = `${ruleForm.name}_模板` + + ruleForm.deviceType = `${ruleForm.deviceType}_模板` + ruleForm.description = ''; + // } + + // const raid: string[] = props.formData.value.raid.split(','); + // let raidId: string[] = []; + // const raidObj = this.reactiveData.raidData[ruleForm.systemVolumeAmount]; + // raid.forEach((item) => { + // for (let index in raidObj) { + // raidList.push( + // { + // name: item, + // id: raidObj[index][item] + // } + // ) + // } + // }); + // const reactiveRaidObj: any = Object.values(raidObj); + // for (let index in reactiveRaidObj) { + // for (let key in reactiveRaidObj[index]) { + // sysRaidData.push( + // { + // name: key, + // id: reactiveRaidObj[index][key] + // } + // ) + // } + // } + // raidList.forEach((item: any) => { + // raidId.push(item.id); + // }); + // if (props.hasTemplate) { + // ruleForm.templateName = deepCopy(ruleForm.name); + // ruleForm.name = `${ruleForm.name}_模板` + + // ruleForm.deviceType = `${ruleForm.deviceType}_模板` + // ruleForm.description = ''; + // } + + // ruleForm.bootMode = (this.reactiveData.bootModeData as any).map((item: {label: string}) => item.label).join(','); + + // let newRaidId = raidId.filter((item) => item !== undefined); + // ruleForm.sysRaid = newRaidId.join(',').split(','); + // this.reactiveData.sysRaid = filterData([...sysRaidData], 'name'); + // if (!ModelStaticData.noRaidData.includes(ruleForm.raidCan)) { + // let newData = this.reactiveData.sysRaid.filter((item: any) => item.name !== ''); + // let newData1 = newData.filter((item: any) => item.name !== 'NORAID'); + // this.reactiveData.sysRaid = newData1; + // } + // }; + }; + + setCpuMemStatus = (ruleForm: RuleFormType, status: string, status2: string) => { + const sCpuMemData = [ + [ + (status: string, _: string) => status === 'common', + () => { + ruleForm.cpuAmount = 1; + ruleForm.cpuCores = 1; + ruleForm.cpuFrequency = ''; + ruleForm.cpuManufacturer = ''; + ruleForm.cpuModel = ''; + } + ], + [ + (status: string, _: string) => status !== 'common', + () => ruleForm.cpuInfo = '' + ], + [ + (_: string, status2: string) => status2 === 'common', + () => { + ruleForm.memSize = ''; + ruleForm.memAmount = 1; + ruleForm.memFrequency = ''; + ruleForm.memType = ''; + } + ], + [ + (_: string, status2: string) => status2 !== 'common', + () => ruleForm.memInfo = '' + ] + ]; + + for (const key of sCpuMemData) { + if (key[0](status, status2)) { + key[1](status, status2); + } + } + }; +}; + +export default DataOperate; diff --git a/bmp-operation-web/src/views/modelManagement/modelAddTemplate/utils/formRulesEvent.ts b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/utils/formRulesEvent.ts new file mode 100644 index 0000000..d21fd95 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/utils/formRulesEvent.ts @@ -0,0 +1,98 @@ +import {RegExpCheck} from './regExpCheck'; +import RegularContent from 'utils/regular.ts'; +import {RuleFormRefType} from '@utils/publicType'; +import {RulesType, RuleFormType} from '../typeManagement'; + +type FormVType = { + name: string;ruleForm: RuleFormType; + rules: RulesType; + ruleFormRef: Ref +}; + +class FormRulesEvent { + formRulesOperate: FormVType; + // name: string = ''; + // device: string = ''; + isLongTip: Ref = ref(false); + isShowLoading: Ref = ref(false); + deviceTypeLoading: Ref = ref(false); + dataVolumeSizeFlag: Ref = ref(false); + systemVolumeSizeFlag: Ref = ref(false); + formV: any; + + // , name: string, device: string + constructor (formV: FormVType) { + this.formRulesOperate = formV; + // this.name = name; + // this.device = device; + this.formV = formV; + }; + + dataVolumeSizeBlur = () => { + nextTick(async () => { + await this.formRulesOperate.ruleFormRef.value!.validateField('dataVolumeSize', (valid: string) => !valid + ? this.dataVolumeSizeFlag.value = false + : this.dataVolumeSizeFlag.value = true + ); + }); + }; + + nameChange = () => { + this.verifyRepeat(1); + this.verifyNameDevice(this.isShowLoading, 'name'); + }; + + nameBlur = () => { + new RegExpCheck().nameFlag.value = true; + const nameArr = [ + [ + (value: string) => !value, + () => this.isLongTip.value = false + ], + [ + (value: string) => !(RegularContent.modelNameReg.test(value)), + () => { + this.isLongTip.value = true; + } + ], + [ + (value: string) => value, + () => { + new RegExpCheck().nameFlag.value = false; + this.isLongTip.value = false; + } + ] + ]; + for (const key of nameArr) { + if (key[0](this.formV.ruleForm.name)) { + key[1](this.formV.ruleForm.name); + break; + } + } + }; + + deviceTypeChange = () => { + this.verifyRepeat(0); + this.verifyNameDevice(this.deviceTypeLoading, 'deviceType'); + }; + + verifyRepeat = (type: number) => { + const name = this.formRulesOperate.ruleForm.name; + const deviceType = this.formRulesOperate.ruleForm.deviceType; + if (name === deviceType && name !== '' && deviceType !== '') { + sessionStorage.setItem('repeat', 'true'); + type && this.deviceTypeChange(); + return; + } + sessionStorage.removeItem('repeat'); + }; + + verifyNameDevice = (loading: {value: boolean}, type: string) => { + loading.value = true; + this.formRulesOperate.ruleFormRef.value!.validateField(type, (_: string) => { + loading.value = false; + }); + } +}; + +export default FormRulesEvent; diff --git a/bmp-operation-web/src/views/modelManagement/modelAddTemplate/utils/newFormRules.ts b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/utils/newFormRules.ts new file mode 100644 index 0000000..61de2e2 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/utils/newFormRules.ts @@ -0,0 +1,985 @@ +import {RuleFormRefType} from '@utils/publicType'; +// +import {RuleFormType, RulesType, ProcessingOperationsType} from '../typeManagement' +import reactiveData from './reactiveData'; +import {regExpCheck} from './regExpCheck'; +import {locationItem, language} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; +import RegularContent from 'utils/regular.ts'; +import ModelStaticData from 'staticData/model/index.ts' +import {addModelAPI} from 'api/model/request.ts'; // 添加机型接口 +// import StorageOperate from './storage'; +import {Router, useRouter} from 'vue-router'; +import {msgTip, methodsTotal} from 'utils/index.ts'; + +interface DataCountType { + hasAddFlag: Ref; + hasAddFlag2: Ref; + raidCanFlag: Ref; + isLoading: Ref; + volumeNameTip: Ref; + volumeTypeTip: Ref; + raidCanTip: Ref; + sysRaidTip: Ref; + diskTypeTip: Ref; + interfaceTypeTip: Ref; + minSizeNumTip: Ref; + amountTip: Ref; + tableHasError: Ref; + tableHasError2: Ref; + tableErrorTip: Ref; + tableErrorTip2: Ref; + ruleFormRef: Ref; + ruleForm: RuleFormType; + rules: RulesType; +}; +const reactiveDataOperate = reactiveData(); +const formRules = () => { + const router: Router = useRouter(); + const idcData = store.idcInfo.idcDataNoOpt; + const languages = locationItem.getLocationItem === 'zh_CN'; + const modelFormStore: ProcessingOperationsType | any = store.modeFormInfo(); + + const val = localStorage.getItem('model-item')?? ''; + const newVal = JSON.parse(val); + // new StorageOperate(newVal); + const dataCount: DataCountType = { + volumeNameTip: ref(language.t('modelForm.label.volumeManage.empty.name')), + volumeTypeTip: ref(language.t('modelForm.label.volumeManage.empty.type')), + raidCanTip: ref(language.t('modelForm.label.volumeManage.empty.raidCan')), + sysRaidTip: ref(language.t('modelForm.label.volumeManage.empty.raid')), + diskTypeTip: ref(language.t('modelForm.label.volumeManage.empty.disk')), + interfaceTypeTip: ref(language.t('modelForm.label.volumeManage.empty.interfaceType')), + minSizeNumTip: ref(language.t('modelForm.label.volumeManage.empty.minNum')), + amountTip: ref(''), + hasAddFlag: ref(true), + isLoading: ref(false), + hasAddFlag2: ref(true), + raidCanFlag: ref(false), + // 表单ref + ruleFormRef: ref(), + tableHasError: ref(false), + tableHasError2: ref(false), + tableErrorTip: ref(language.t('modelForm.label.volumeManage.save.empty')), + tableErrorTip2: ref(language.t('modelForm.label.volumeManage.save.empty')), + // 表单数据 + ruleForm: reactive({ + // nicAmount: newVal.nicAmount, + // gpuModel: newVal.gpuModel, + // gpuAmount: newVal.gpuAmount, + // interfaceMode: newVal.interfaceMode, + // gpuManufacturer: newVal.gpuManufacturer, + // nicRate: newVal.nicRate, + // height: newVal.height, + arrayCard: newVal.isNeedRaid === 'no_need_raid' ? '2' : '1', + // machineRoomName: languages ? idcData[0]?.name : idcData[0]?.nameEn, + machineRoomName: (languages ? idcData[0]?.name : idcData[0]?.nameEn), + // idcId: formData?.value?.idcId || idcData[0]?.idcId, // idcId + idcId: newVal?.idcId || idcData[0]?.idcId, // idcId + modelType: reactiveDataOperate.modelFormStore.initModelType(newVal.deviceSeries), + cpuData: [], // cpu数据 + memData: [], // 内存数据 + bootMode: [], + volumeManagerTableData: [], + noConfigurationData: [], + ...reactiveDataOperate.modelFormStore.ruleForm, + }), + // 表单规则 + rules: reactive({ + // height: [ + // { + // required: true, + // trigger: 'change', + // message: '请选择高度' + // } + // ], + cpuModel: [ + { + required: true, + trigger: 'blur', + validator: regExpCheck.cpuModelCheck + } + ], + cpuFrequency: [ + { + required: true, + trigger: 'blur', + validator: regExpCheck.cpuFrequencyCheck + } + ], // 主频 + name: [ // 机型名称 + { + required: true, + trigger: 'blur', + validator: regExpCheck.nameCheck + } + ], + deviceType: [ // 机型规格 + { + required: true, + trigger: 'blur', + validator: regExpCheck.deviceTypeCheck + } + ], + volumeManager: [ + { + required: false, + trigger: 'blur', + message: '' + } + ], + ...reactiveDataOperate.modelFormStore.rules + }) + }; + + const initVolumeType = (type: string) => { + const obj = new Map([ + ['system', language.t('modelForm.label.system')], + ['data', language.t('modelForm.label.data')] + ]); + return obj.get(type); + } + + if (newVal.isNeedRaid === 'no_need_raid') { + const noConfigData = dataCount.ruleForm.noConfigurationData = newVal.volumes.map((item: any, index: number) => { + return { + ...item, + id: new Date().getTime() + index, + editFlag: true, + minSizeNum: item.volumeSize, + minSize: item.volumeUnit, + amount: item.volumeAmount, + // diskType: item.diskType, + // interfaceType: item.interfaceType, + // diskType: item.diskType === 'notLimited' ? language.t('modelForm.unrestricted') : item.diskType, + // interfaceType: item.interfaceType === 'notLimited' ? language.t('modelForm.unrestricted') : item.interfaceType, + volumeType: initVolumeType(item.volumeType), + newVolumeType: initVolumeType(item.volumeType) + } + }); + // , 'raidCanFlag', 'sysRaidFlag' + const type = ['volumeNameFlag', 'volumeTypeFlag', 'diskTypeFlag', 'interfaceTypeFlag', 'minSizeNumFlag', 'minSizeNumFlag', 'amountFlag'] + noConfigData.forEach((t: any) => { + type.forEach((a: any) => { + t[`${a}${t.id}`] = 'success' + }) + }); + dataCount.ruleForm.noConfigurationData = noConfigData; + } + else { + const volumeTableData = dataCount.ruleForm.volumeManagerTableData = newVal.volumes.map((item: any, index: number) => { + return { + ...item, + id: new Date().getTime() + index, + editFlag: true, + minSizeNum: item.volumeSize, + sysRaid: item.raid, + // raidCan: item.raidCan, + // diskType: item.diskType, + // interfaceType: item.interfaceType, + // diskType: item.diskType === 'notLimited' ? language.t('modelForm.unrestricted') : item.diskType, + // interfaceType: item.interfaceType === 'notLimited' ? language.t('modelForm.unrestricted') : item.interfaceType, + raidCan: ModelStaticData.singleRaid0.includes(item.raidCan) ? language.t('modelForm.raid') : item.raidCan, + newSysRaid: item.raidId, + minSize: item.volumeUnit, + amount: item.volumeAmount, + volumeType: initVolumeType(item.volumeType), + newVolumeType: initVolumeType(item.volumeType) + } + }); + + const type = ['volumeNameFlag', 'volumeTypeFlag', 'diskTypeFlag', 'interfaceTypeFlag', 'minSizeNumFlag', 'minSizeNumFlag', 'amountFlag', 'raidCanFlag', 'sysRaidFlag'] + volumeTableData.forEach((t: any) => { + type.forEach((a: any) => { + t[`${a}${t.id}`] = 'success' + }) + }); + dataCount.ruleForm.volumeManagerTableData = volumeTableData; + } + const setDiskInterfaceType = (item: string) => { + return item === 'notLimited' ? language.t('modelForm.unrestricted') : item; + } + + const addVolumeClick = () => { + if (!dataCount.hasAddFlag.value) return; + dataCount.hasAddFlag.value = false; + dataCount.tableHasError.value = false; + const obj = { + id: new Date().getTime(), + editFlag: false, + volumeName: '', + volumeType: '', + newVolumeType: '', + diskType: '', + minSize: 'GB', + raidCan: '', + amount: 0, + minSizeNum: '', + sysRaid: '', + interfaceType: '', + } + dataCount.ruleForm.volumeManagerTableData.push(obj); + }; + + const addVolumeClick2 = () => { + if (!dataCount.hasAddFlag2.value) return; + dataCount.hasAddFlag2.value = false; + dataCount.tableHasError2.value = false; + const obj = { + id: new Date().getTime(), + editFlag: false, + volumeName: '', + volumeType: '', + newVolumeType: '', + diskType: '', + minSize: 'GB', + amount: 1, + minSizeNum: '', + interfaceType: '', + } + dataCount.ruleForm.noConfigurationData.push(obj); + } + + const volumeNameBlur = (val: any, index: number) => { + val[`volumeNameFlag${index}`] = ''; + if (!val.volumeName?.length) { + val[`volumeNameFlag${index}`] = 'error'; + dataCount.volumeNameTip.value = language.t('modelForm.label.volumeManage.empty.name'); + } + else if (!RegularContent.name1Reg.test(val.volumeName)){ + val[`volumeNameFlag${index}`] = 'error'; + dataCount.volumeNameTip.value = language.t('modelForm.errorTip.currency'); + } + else { + val[`volumeNameFlag${index}`] = 'success'; + dataCount.volumeNameTip.value = ''; + } + } + + const volumeTypeChange = (val: any, index: number) => { + val[`volumeTypeFlag${index}`] = ''; + if (!val.volumeType?.length) { + val[`volumeTypeFlag${index}`] = 'error'; + } + else { + if (dataCount.ruleForm.arrayCard === '1') { + const dataTable = dataCount.ruleForm.volumeManagerTableData; + + if (val.volumeType === language.t('modelForm.label.data') && dataTable.length === 1) { + val.volumeType = ''; + val.newVolumeType = ''; + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.sys.tip1') + val[`volumeTypeFlag${index}`] = 'error'; + } + else if (val.volumeType === language.t('modelForm.label.system') && dataTable.length > 1 && dataTable.map((item: {volumeType: string}) => item.volumeType).filter((ite: string) => ite === language.t('modelForm.label.system')).length > 1) { + val.volumeType = ''; + val.newVolumeType = ''; + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.sys.tip2') + val[`volumeTypeFlag${index}`] = 'error'; + } + else { + val[`volumeTypeFlag${index}`] = 'success'; + dataCount.volumeTypeTip.value = '' + val.newVolumeType = val.volumeType; + } + } + else { + const noRaidData = dataCount.ruleForm.noConfigurationData; + if (val.volumeType === language.t('modelForm.label.data') && noRaidData.length === 1) { + val.volumeType = ''; + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.sys.tip1') + val[`volumeTypeFlag${index}`] = 'error'; + val.newVolumeType = ''; + } + else if (val.volumeType === language.t('modelForm.label.system') && noRaidData.length > 1 && noRaidData.map((item: {volumeType: string}) => item.volumeType).filter((ite: string) => ite === language.t('modelForm.label.system')).length > 1) { + val.volumeType = ''; + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.sys.tip2') + val[`volumeTypeFlag${index}`] = 'error'; + val.newVolumeType = ''; + } + else { + val[`volumeTypeFlag${index}`] = 'success'; + dataCount.volumeTypeTip.value = '' + val.newVolumeType = val.volumeType; + } + } + } + }; + + const raidCanChange = (val: any, index: number) => { + val[`raidCanFlag${index}`] = ''; + if (!val.raidCan?.length) { + val[`raidCanFlag${index}`] = 'error'; + } + else { + val[`raidCanFlag${index}`] = 'success'; + dataCount.raidCanTip.value = '' + } + if (val.sysRaid?.length) { + val.sysRaid = '' + val[`sysRaidFlag${index}`] = void 0; + } + if (val.interfaceType) { + val.interfaceType = ''; + val[`interfaceTypeFlag${index}`] = void 0; + } + }; + + const sysRaidChange = (val: any, index: number, data: any) => { + val[`sysRaidFlag${index}`] = ''; + if (typeof val.sysRaid === 'string') { + // if (data[0] === language.t('modelForm.none')) { + // val['newSysRaid'] = [''] + // } + // else { + // let newId = data[0].value; + // val['newSysRaid'] = [newId]; + // } + let newId = data[0].value; + val['newSysRaid'] = [newId]; + } + else { + let d: any = [] + data.forEach((item: any) => { + val.sysRaid.forEach((t: any) => { + if (item.label === t) { + d.push(item.value) + } + + }) + }) + val['newSysRaid'] = d; + } + if (Array.isArray(val.sysRaid)) { + if (val.sysRaid.length > 0) { + val[`sysRaidFlag${index}`] = 'success'; + dataCount.sysRaidTip.value = ''; + } + else { + val[`sysRaidFlag${index}`] = 'error'; + dataCount.sysRaidTip.value = language.t('modelForm.label.volumeManage.empty.raid') + // dataCount.sysRaidTip.value = '请选择RAID模式' + } + } + else { + if (!val.sysRaid?.length) { + val[`sysRaidFlag${index}`] = 'error'; + } + else { + val[`sysRaidFlag${index}`] = 'success'; + dataCount.sysRaidTip.value = '' + } + } + }; + + const diskTypeChange = (val: any, index: number) => { + val[`diskTypeFlag${index}`] = ''; + if (!val.diskType?.length) { + val[`diskTypeFlag${index}`] = 'error'; + // dataCount.raidCanTip.value = '请选择RAID配置' + } + else { + val[`diskTypeFlag${index}`] = 'success'; + dataCount.diskTypeTip.value = '' + } + } + + const interfaceTypeChange = (val: any, index: number) => { + val[`interfaceTypeFlag${index}`] = ''; + if (!val.interfaceType?.length) { + val[`interfaceTypeFlag${index}`] = 'error'; + // dataCount.raidCanTip.value = '请选择RAID配置' + } + else { + val[`interfaceTypeFlag${index}`] = 'success'; + dataCount.interfaceTypeTip.value = '' + } + } + + const minSizeNumBlur = (val: any, index: number) => { + val[`minSizeNumFlag${index}`] = ''; + if (!String(val.minSizeNum)?.length) { + val[`minSizeNumFlag${index}`] = 'error'; + dataCount.minSizeNumTip.value = language.t('modelForm.label.volumeManage.empty.minNum') + // dataCount.raidCanTip.value = '请选择RAID配置' + } + else if (val.minSize === 'TB') { + val[`minSizeNumFlag${index}`] = 'error'; + if (!RegularContent.capacityReg.test(val.minSizeNum)) { + dataCount.minSizeNumTip.value = language.t('modelForm.errorTip.number2') + } + else if ((Number(val.minSizeNum) > 100000)) { + dataCount.minSizeNumTip.value = language.t('modelForm.errorTip.number3'); + } + else { + dataCount.minSizeNumTip.value = '' + val[`minSizeNumFlag${index}`] = 'success'; + } + } + else { + val[`minSizeNumFlag${index}`] = 'error'; + if (!RegularContent.numberReg.test(val.minSizeNum)) { + dataCount.minSizeNumTip.value = language.t('modelForm.errorTip.number1'); + } + else if ((Number(val.minSizeNum) > 100000)) { + dataCount.minSizeNumTip.value = language.t('modelForm.errorTip.number3'); + } + else { + dataCount.minSizeNumTip.value = '' + val[`minSizeNumFlag${index}`] = 'success'; + } + } + } + + const minSizeChange = (val: {minSizeNum: string;}) => { + val.minSizeNum = ''; + } + + watch(() => dataCount.ruleForm.modelCPU, (newValue) => { + const cpuStatus = ModelStaticData.modelSpecData.includes(newValue); + if (cpuStatus) { + regExpCheck.cpuManufacturerFlag.value = false; + regExpCheck.cpuModelFlag.value = false; + regExpCheck.cpuInfoFlag.value = false; + regExpCheck.cpuGHzFlag.value = false; + } + }) + + watch(() => dataCount.ruleForm.modelStorage, (newValue) => { + const memeStatus = ModelStaticData.modelSpecData.includes(newValue); + if (memeStatus) { + regExpCheck.memTypeFlag.value = false; + regExpCheck.memFrequencyFlag.value = false; + regExpCheck.memSizeFlag.value = false; + regExpCheck.memInfoFlag.value = false; + } + }) + + const setAmountMaxSize = (item: any, index: number) => { + if (dataCount.ruleForm.arrayCard === '2' || [language.t('modelForm.raid'), 'NO RAID'].includes(item.raidCan)) { + item.amount = 1; + dataCount.amountTip.value = '' + item[`amountFlag${index}`] = 'success'; + return 1; + } + if (!Array.isArray(item.sysRaid)) return; + // r-l6pounvfife0njlinhk6ztf2xyio + if (item.sysRaid.includes('RAID10')) { + if (item.amount % 4 === 0) { + // item.amountFlag + item[`amountFlag${index}`] = 'success'; + dataCount.amountTip.value = '' + } + return; + } + if (item.sysRaid.includes('RAID1')) { + if (item.amount % 2 === 0) { + item[`amountFlag${index}`] = 'success'; + dataCount.amountTip.value = '' + } + return; + } + + if (item.sysRaid.includes('RAID0')) { + if (item.amount >= 2) { + item[`amountFlag${index}`] = 'success'; + dataCount.amountTip.value = '' + } + return; + } + // // else + // return 1000; + } + + const setAmountMinSize = (item: any, index: number) => { + if (dataCount.ruleForm.arrayCard === '2' || [language.t('modelForm.raid'), 'NO RAID'].includes(item.raidCan)) { + item[`amountFlag${index}`] = 'success'; + return 1; + } + if (!Array.isArray(item.sysRaid) || !item.sysRaid?.length) { + return 1; + }; + // if (item.sysRaid.length === 1) { + // r-l6pounvfife0njlinhk6ztf2xyio + if (item.sysRaid.includes('RAID10')) { + if (item.amount < 4) { + item.amount = 4; + } + // else if (item.amount % 4 !== 0) { + // // item.amountFlag + // item[`amountFlag${index}`] = 'error'; + // dataCount.amountTip.value = '最低4或者大于4的偶数' + // } + return 4; + } + if (item.sysRaid.length === 1 && item.sysRaid.includes('RAID5')) { + item[`amountFlag${index}`] = 'success'; + dataCount.amountTip.value = ''; + if (item.amount < 3) { + item.amount = 3; + } + return 3; + + } + // if (item.sysRaid.includes('RAID1') && item.sysRaid.includes('RAID5')) { + // if (item.amount < 4) { + // item.amount = 4; + // } + // else { + // if (item.amount % 2 === 0) { + // item[`amountFlag${index}`] = 'success'; + // dataCount.amountTip.value = '' + // } + // else { + // item[`amountFlag${index}`] = 'error'; + // dataCount.amountTip.value = '最低2块,或者大于2的偶数' + // } + // } + // return 4; + // } + if (item.sysRaid.includes('RAID0') && item.sysRaid.includes('RAID5')) { + if (item.amount < 3) { + item.amount = 3; + } + return 3; + } + if (item.sysRaid.includes('RAID1')) { + if (item.amount < 2) { + item.amount = 2; + } + // else if (item.amount % 2 !== 0) { + // // item.amountFlag + // item[`amountFlag${index}`] = 'error'; + // dataCount.amountTip.value = '最低2或者大于2的偶数' + // } + return 2; + } + if (item.sysRaid.includes('RAID0')) { + if (item.amount < 2) { + item.amount = 2; + } + return 2; + } + } + + const sure = async () => { + await dataCount.ruleFormRef.value!.validate((valid: Required) => { + if (!valid) { + regExpCheck.heightFlag.value = true; + regExpCheck.interfaceModeFlag.value = true; + regExpCheck.nicRateFlag.value = true; + } + const {volumeManagerTableData, noConfigurationData} = dataCount.ruleForm; + const cpuStatus = ModelStaticData.modelSpecData.includes(dataCount.ruleForm.modelCPU); + const memStatus = ModelStaticData.modelSpecData.includes(dataCount.ruleForm.modelStorage); + setFlag(); + setOtherEmpty(cpuStatus, memStatus) + if (dataCount.ruleForm.arrayCard === '1') { + dataCount.tableHasError.value = !(volumeManagerTableData?.length > 0); + if (!dataCount.hasAddFlag.value) { + dataCount.tableHasError.value = true; + dataCount.tableErrorTip.value = language.t('modelForm.label.volumeManage.save.volumeManagement'); + return + }; + if (dataCount.tableHasError.value) { + dataCount.tableHasError.value = true; + dataCount.tableErrorTip.value = language.t('modelForm.label.volumeManage.save.empty'); + return; + } + } + else { + dataCount.tableHasError2.value = !(noConfigurationData?.length > 0); + if (!dataCount.hasAddFlag2.value) { + dataCount.tableHasError2.value = true; + dataCount.tableErrorTip2.value = language.t('modelForm.label.volumeManage.save.volumeManagement'); + return + }; + if (dataCount.tableHasError2.value) { + dataCount.tableHasError2.value = true; + dataCount.tableErrorTip2.value = language.t('modelForm.label.volumeManage.save.empty'); + return; + } + } + if (valid) { + regExpCheck.heightFlag.value = false; + // let params: any = {} + let cpuBol = false; + let memBol = false; + if (cpuStatus && memStatus) { + cpuBol = false; + memBol = false; + } + else if (cpuStatus && !memStatus) { + cpuBol = false; + memBol = true; + } + else if (!cpuStatus && memStatus) { + cpuBol = true; + memBol = false; + } + else { + cpuBol = true; + memBol = true; + } + + modelFormStore.setCpuMemData(cpuBol, memBol, dataCount.ruleForm) + .then(() => { + requestEditModel(cpuBol, memBol) + }) + } + else { + regExpCheck.heightFlag.value = true; + } + }) + } + + const setOtherEmpty = (cpuStatus: boolean, memStatus: boolean) => { + if (cpuStatus) { + regExpCheck.cpuManufacturerFlag.value = false; + } + else { + regExpCheck.cpuInfoFlag.value = false; + } + if (memStatus) { + regExpCheck.memTypeFlag.value = false; + regExpCheck.memFrequencyFlag.value = false; + regExpCheck.memSizeFlag.value = false; + } + else { + regExpCheck.memInfoFlag.value = false; + } + } + + + const setVolumeType = (type: string) => { + const data = [ + [ + (value: string) => value === language.t('modelForm.label.system'), + () => 'system' + ], + [ + (value: string) => value === language.t('modelForm.label.data'), + () => 'data' + ] + ]; + for (const key of data) { + if (key[0](type)) { + return key[1](type) + } + } + } + + + /** + * 请求添加机型接口,成功后把事件回传,关闭弹窗 + */ + const requestEditModel = (cpuBol: boolean, memBol: boolean) => { + const {arrayCard, noConfigurationData, gpuManufacturer, gpuModel, gpuAmount, volumeManagerTableData} = dataCount.ruleForm; + const obj = gpuAmount > 0 ? { + gpuAmount, + gpuModel, + gpuManufacturer + } : {} + const volumesData = arrayCard === '1' ? volumeManagerTableData.map((item: any) => { + + return { + volumeName: item.volumeName, + volumeType: setVolumeType(item.newVolumeType), + diskType: item.diskType, + interfaceType: item.interfaceType, + volumeSize: String(item.minSizeNum), + volumeUnit: item.minSize, + volumeAmount: item.amount, + raidCan: ModelStaticData.singleRaid0.includes(item.raidCan) ? 'RAID0-stripping' : item.raidCan, + raid: typeof item.newSysRaid === 'string' ? item.newSysRaid : item.newSysRaid.join(','), + } + }) : noConfigurationData.map((item: any) => { + return { + volumeName: item.volumeName, + volumeType: setVolumeType(item.newVolumeType), + diskType: item.diskType, + interfaceType: item.interfaceType, + volumeSize: String(item.minSizeNum), + volumeUnit: item.minSize, + volumeAmount: item.amount, + } + }) + if (gpuAmount <= 0) { + const emptyData = ['gpuAmount', 'gpuModel', 'gpuManufacturer']; + for (const key of emptyData) { + Reflect.deleteProperty(dataCount.ruleForm, key) + } + } + const newParams = { + ...obj, + ...dataCount.ruleForm, + volumes: volumesData, + isNeedRaid: setIsNeedRaid(arrayCard), + cpuSpec: cpuBol ? 'user_defined' : 'common', + memSpec: memBol ? 'user_defined' : 'common', + deviceSeries: modelFormStore.setModelType(dataCount.ruleForm.modelType) + } + if (arrayCard === '2') { + const status = noConfigurationData.some((item: {volumeType: string}) => item.volumeType === language.t('modelForm.label.system')); + if (!status) { + dataCount.tableHasError2.value = true; + dataCount.tableErrorTip2.value = language.t('modelForm.label.volumeManage.sys.tip1'); + return; + } + } + else { + const status = volumeManagerTableData.some((item: {volumeType: string}) => item.volumeType === language.t('modelForm.label.system')); + if (!status) { + dataCount.tableHasError.value = true; + dataCount.tableErrorTip.value = language.t('modelForm.label.volumeManage.sys.tip1'); + return; + } + } + dataCount.isLoading.value = true; + addModelAPI( + { + ...newParams, + deviceTypeId: newVal.deviceTypeId + } + ).then(({data} : {data: {result: {deviceTypeId: string;}}}) => { + if(data?.result?.deviceTypeId) { + msgTip.success(language.t('operate.success')); + methodsTotal.sendMsg('model-add-template-success', 'success'); + cancel(); + } + }).finally(() => { + dataCount.isLoading.value = false; + }); + }; + + // const setVolumeType = (type: string) => { + // const obj = new Map([ + // [language.t('modelForm.label.system'), 'system'], + // [language.t('modelForm.label.data'), 'data'] + // ]) + // // @ts-ignore + // return obj[type]; + // } + + const setIsNeedRaid = (type: string) => { + const obj = { + '1': 'need_raid', + '2': 'no_need_raid' + }; + // @ts-ignore + return obj[type]; + } + + const nicAmountIpt = () => { + if (dataCount.ruleForm.interfaceMode) { + dataCount.ruleForm.interfaceMode = ''; + regExpCheck.interfaceModeFlag.value = true; + } + }; + + + const setFlag = () => { + const data = ['cpuInfo', 'memInfo', 'cpuManufacturer', 'memType', 'memFrequency', 'memSize']; + for (const key of data) { + // @ts-ignore + regExpCheck[`${key}Flag`].value = !(dataCount.ruleForm[key]) + } + } + + const setAddBtn = () => { + const status = dataCount.ruleForm.volumeManagerTableData.every((item: {editFlag: boolean}) => item.editFlag); + dataCount.hasAddFlag.value = status; + return status ? 'active' : 'default-s'; + } + + const setAddBtn2 = () => { + const status = dataCount.ruleForm.noConfigurationData.every((item: {editFlag: boolean}) => item.editFlag); + dataCount.hasAddFlag2.value = status; + return status ? 'active' : 'default-s'; + } + + watch(() => dataCount.ruleForm.arrayCard, (_) => { + // if (newValue === '2') { + // dataCount.ruleForm.volumeManagerTableData = []; + // dataCount.hasAddFlag.value = true; + // } + }) + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + const getFormRef = (formEl: {value: RuleFormRefType}) => { + dataCount.ruleFormRef.value = formEl.value; + // setFormRef('ruleFormRef', formEl) + // emitValue('rule-form-ref', dataCount.ruleFormRef); + }; + + const saveClick = (val: any, index: number) => { + const status = val[`volumeNameFlag${index}`] === 'success' && val[`volumeTypeFlag${index}`] === 'success' && val[`diskTypeFlag${index}`] === 'success' && val[`interfaceTypeFlag${index}`] === 'success' && val[`minSizeNumFlag${index}`] === 'success' && val[`amountFlag${index}`] === 'success'; + if (status && val[`raidCanFlag${index}`] === 'success' && val[`sysRaidFlag${index}`] === 'success') { + val.editFlag = true; + dataCount.hasAddFlag.value = true; + const hasEverySave = dataCount.ruleForm.volumeManagerTableData.every((item: {editFlag: boolean}) => item.editFlag); + if (hasEverySave) { + dataCount.tableErrorTip.value = ''; + dataCount.tableHasError.value = false; + } + } + if (dataCount.ruleForm.arrayCard === '1') { + if (val[`raidCanFlag${index}`] === void 0) { + dataCount.raidCanTip.value = language.t('modelForm.label.volumeManage.empty.raidCan') + val[`raidCanFlag${index}`] = ''; + } + + if (val[`sysRaidFlag${index}`] === void 0) { + dataCount.sysRaidTip.value = language.t('modelForm.label.volumeManage.empty.raid') + val[`sysRaidFlag${index}`] = ''; + } + + } + if (val[`volumeNameFlag${index}`] === void 0) { + dataCount.volumeNameTip.value = language.t('modelForm.label.volumeManage.empty.name') + val[`volumeNameFlag${index}`] = ''; + + } + if (val[`volumeTypeFlag${index}`] === void 0) { + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.empty.type') + val[`volumeTypeFlag${index}`] = ''; + } + + if (val[`diskTypeFlag${index}`] === void 0) { + dataCount.diskTypeTip.value = language.t('modelForm.label.volumeManage.empty.disk'); + val[`diskTypeFlag${index}`] = ''; + } + + if (val[`interfaceTypeFlag${index}`] === void 0) { + dataCount.interfaceTypeTip.value = language.t('modelForm.label.volumeManage.empty.interfaceType'); + val[`interfaceTypeFlag${index}`] = ''; + } + + if (val[`minSizeNumFlag${index}`] === void 0) { + dataCount.minSizeNumTip.value = language.t('modelForm.label.volumeManage.empty.minNum') + val[`minSizeNumFlag${index}`] = ''; + } + } + + const noConfigurationSaveClick = (val: any, index: number) => { + const status = val[`volumeNameFlag${index}`] === 'success' && val[`volumeTypeFlag${index}`] === 'success' && val[`diskTypeFlag${index}`] === 'success' && val[`interfaceTypeFlag${index}`] === 'success' && val[`minSizeNumFlag${index}`] === 'success'; + if (status) { + val.editFlag = true; + + dataCount.hasAddFlag2.value = true; + const hasEverySave = dataCount.ruleForm.noConfigurationData.every((item: {editFlag: boolean}) => item.editFlag); + if (hasEverySave) { + dataCount.tableErrorTip2.value = ''; + dataCount.tableHasError2.value = false; + } + return; + } + + if (val[`volumeNameFlag${index}`] === void 0) { + dataCount.volumeNameTip.value = language.t('modelForm.label.volumeManage.empty.name') + val[`volumeNameFlag${index}`] = ''; + + } + if (val[`volumeTypeFlag${index}`] === void 0) { + dataCount.volumeTypeTip.value = language.t('modelForm.label.volumeManage.empty.type') + val[`volumeTypeFlag${index}`] = ''; + } + + if (val[`diskTypeFlag${index}`] === void 0) { + dataCount.diskTypeTip.value = language.t('modelForm.label.volumeManage.empty.disk'); + val[`diskTypeFlag${index}`] = ''; + } + + if (val[`interfaceTypeFlag${index}`] === void 0) { + dataCount.interfaceTypeTip.value = '请选择接口类型'; + val[`interfaceTypeFlag${index}`] = ''; + } + + if (val[`minSizeNumFlag${index}`] === void 0) { + dataCount.interfaceTypeTip.value = language.t('modelForm.label.volumeManage.empty.interfaceType'); + val[`minSizeNumFlag${index}`] = ''; + } + + } + + watch(() => [dataCount.ruleForm.gpuManufacturer, dataCount.ruleForm.gpuModel], (newValue) => { + const status = newValue.some(item => item === ''); + if (status) { + dataCount.ruleForm.gpuAmount = 0; + } + }) + + const editClick = (val: { + split(arg0: string): string[];editFlag: boolean; raidCan: string; raid: string; sysRaid: string[]; +}) => { + + if (val.raidCan === 'RAID') { + val.sysRaid = val?.raid ? val.raid.split(',') : val.sysRaid; + } + val.editFlag = false; + } + + const noConfigurationEditClick = (val: {editFlag: boolean;}) => { + val.editFlag = false; + } + + const deleteClick = (index: number) => { + dataCount.ruleForm.volumeManagerTableData.splice(index, 1); + dataCount.hasAddFlag.value = true; + } + + const noConfigurationDeleteClick = (index: number) => { + dataCount.ruleForm.noConfigurationData.splice(index, 1); + dataCount.hasAddFlag2.value = true; + } + + const cancel = () => { + router.push('/ModelManagement/modelList') + } + + const amountMinValue = () => { + // const {gpuModel, gpuManufacturer} = dataCount.ruleForm; + // if (gpuModel && gpuManufacturer) { + // return 1; + // } + // return 0; + return 0; + } + + + return { + sure, + cancel, + ...dataCount, + getFormRef, + addVolumeClick, + setDiskInterfaceType, + amountMinValue, + volumeNameBlur, + volumeTypeChange, + // setRaidInfo, + raidCanChange, + sysRaidChange, + diskTypeChange, + noConfigurationSaveClick, + interfaceTypeChange, + minSizeNumBlur, + minSizeChange, + addVolumeClick2, + setAmountMinSize, + setAmountMaxSize, + setAddBtn, + setAddBtn2, + saveClick, + nicAmountIpt, + editClick, + noConfigurationEditClick, + deleteClick, + noConfigurationDeleteClick + } +} + +export default formRules; \ No newline at end of file diff --git a/bmp-operation-web/src/views/modelManagement/modelAddTemplate/utils/reactiveData.ts b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/utils/reactiveData.ts new file mode 100644 index 0000000..3dcf5dd --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/utils/reactiveData.ts @@ -0,0 +1,23 @@ +import {StoreGeneric, storeToRefs} from 'pinia'; // store +import {ReactiveDataType} from '../typeManagement'; +import store from 'store/index.ts'; + +interface DataType { + modelFormStore: StoreGeneric; + reactiveData: ReactiveDataType; +}; + +const reactiveData = () => { + const data: DataType = { + modelFormStore: store.modeFormInfo(), + reactiveData: reactive({ + ...storeToRefs(store.modeFormInfo()).data.value + }) + }; + + return { + ...data + }; +}; + +export default reactiveData; diff --git a/bmp-operation-web/src/views/modelManagement/modelAddTemplate/utils/regExpCheck.ts b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/utils/regExpCheck.ts new file mode 100644 index 0000000..fbd07f4 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/modelAddTemplate/utils/regExpCheck.ts @@ -0,0 +1,248 @@ +import {resourcesAPI} from 'api/public/request.ts'; +import {language} from 'utils/publicClass.ts'; +import {CallbackType} from '@utils/publicType'; +import RegularContent from 'utils/regular.ts'; + +// type ParamsType = Partial<{name: string; deviceType: string;}>; + +class RegExpCheck { + memSizeFlag: Ref = ref(false); + memFrequencyFlag: Ref = ref(false); + memTypeFlag: Ref = ref(false); + heightFlag: Ref = ref(false); + interfaceModeFlag: Ref = ref(false); + nicRateFlag: Ref = ref(false); + cpuManufacturerFlag: Ref = ref(false); + memInfoFlag: Ref = ref(false); + cpuInfoFlag: Ref = ref(false); + cpuGHzFlag: Ref = ref(false); + cpuModelFlag: Ref = ref(false); + nameFlag: Ref = ref(false); + deviceTypeFlag: Ref = ref(false); + nameLoading: Ref = ref(false); + deviceTypeLoading: Ref = ref(false); + ruleForm: { + minValUnit: string; + } = { + minValUnit: 'GB', + }; + + constructor (minValUnit: string = 'GB') { + this.ruleForm.minValUnit = minValUnit; + }; + + /** + * 机型名称校验 + * @param {Object} _ 占位符 + * @param {string} value 输入项 + * @param {Function} callback 回调函数,返回对应状态 + */ + nameCheck: unknown = (_: unknown, value: string, callback: CallbackType) => { + const nameArr = [ + [ + (value: string) => !value?.length, + () => { + this.nameFlag.value = true; + callback(new Error(language.t('modelForm.emptyTip.modelName'))) + } + ], + [ + (value: string) => value.length > 64, + () => { + this.nameFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.currency2'))) + } + ], + [ + (value: string) => (!RegularContent.modelNameReg.test(value)), + () => { + this.nameFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.currency'))) + } + ], + [ + (value: string) => value, + () => { + const name: string = sessionStorage.getItem('propsName')??''; + const status: string = sessionStorage.getItem('hasTemplate')??''; + this.nameLoading.value = true; + if (name === value && status !== 'success') { + this.nameFlag.value = false; + this.nameLoading.value = false; + callback(); + } + else { + resourcesAPI( + { + name: value + } + ) + .then(({data} : {data: {result: {success: boolean;}}}) => { + if (data?.result?.success) { + this.nameFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.name'))); + return; + } + return Promise.reject(); + }) + .catch(() => { + this.nameFlag.value = false; + callback(); + }) + .finally(() => { + this.nameLoading.value = false; + }) + } + } + ] + ]; + for (const key of nameArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + /** + * 机型规格校验 + * @param {Object} _ 占位符 + * @param {string} value 输入项 + * @param {Function} callback 回调函数,返回对应状态 + */ + deviceTypeCheck: unknown = (_: unknown, value: string, callback: CallbackType) => { + const deviceTypeArr = [ + [ + (value: string) => !value?.length, + () => { + this.deviceTypeFlag.value = true; + callback(new Error(language.t('modelForm.emptyTip.modelSpecifications'))) + } + ], + [ + (value: string) => value.length > 64, + () => { + this.deviceTypeFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.currency2'))) + } + ], + [ + (value: string) => (value && sessionStorage?.getItem('repeat')), + () => { + this.deviceTypeFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.modelSpecifications'))) + } + ], + [ + (value: string) => value, + () => { + const deviceType = sessionStorage?.getItem('propsDeviceType'); + const status = sessionStorage.getItem('hasTemplate'); + this.deviceTypeLoading.value = true; + if (deviceType === value && status !== 'success') { + this.deviceTypeFlag.value = false; + this.deviceTypeLoading.value = false; + callback(); + } + else { + resourcesAPI( + { + deviceType: value + } + ) + .then(({data} : {data: {result: {success: boolean;}}}) => { + if (data?.result?.success) { + this.deviceTypeFlag.value = true; + callback(new Error(language.t('modelForm.errorTip.specifications'))); + return; + } + return Promise.reject(); + }) + .catch(() => { + this.deviceTypeFlag.value = false; + callback(); + }) + .finally(() => { + this.deviceTypeLoading.value = false; + }) + } + } + ] + ]; + for (const key of deviceTypeArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + /** + * cpu型号 + * @param {string} str 提示项 + * @param {string} trigger 判断时机-change/blur + */ + cpuModelCheck = (_: {}, value: string, callback: (arg0?: Error) => void) => { + this.cpuModelFlag.value = true; + const cpuModelArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t('modelForm.emptyTip.modelChoose'))) + ], + [ + (value: string) => value.length > 64, + () => callback(new Error(language.t('modelForm.errorTip.currency2'))) + ], + [ + (value: string) => value, + () => { + callback(); + this.cpuModelFlag.value = false; + } + ] + ]; + for (const key of cpuModelArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + /** + * CPU-主频 + */ + cpuFrequencyCheck = (_: unknown, value: string, callback: (arg0?: Error) => void) => { + this.cpuGHzFlag.value = true; + const cpuFrequencyArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t('modelForm.emptyTip.dominantFrequency'))) + ], + [ + (value: string) => (!RegularContent.capacityReg.test(value)), + () => callback(new Error(language.t('modelForm.errorTip.number'))) + ], + [ + (value: string) => value, + () => { + callback(); + this.cpuGHzFlag.value = false; + } + ] + ]; + for (const key of cpuFrequencyArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; +}; + +const regExpCheck: RegExpCheck = new RegExpCheck(); + +export { + RegExpCheck, + regExpCheck +}; diff --git a/bmp-operation-web/src/views/modelManagement/navRouter.ts b/bmp-operation-web/src/views/modelManagement/navRouter.ts new file mode 100644 index 0000000..2ebebb7 --- /dev/null +++ b/bmp-operation-web/src/views/modelManagement/navRouter.ts @@ -0,0 +1,18 @@ +/** + * @file + * @author +*/ + +import {language} from "utils/publicClass.ts"; + +const modelNavData = (pathUrl: (arg0: string) => void, imgUrl: (arg0: string) => void) => { + return { + title: language.t('navigationBar.list.modelManagement'), + defaultImg: imgUrl('modelDefault'), + changeImg: imgUrl('model'), + path: pathUrl('modelList'), + otherPath: [pathUrl('modelList'), pathUrl('modelDetail'), pathUrl('addModel'), pathUrl('editModel'), pathUrl('addModelTemplate')] + } +}; + +export default modelNavData; diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/all.ts b/bmp-operation-web/src/views/monitorManagement/faultLog/all.ts new file mode 100644 index 0000000..52688e0 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/all.ts @@ -0,0 +1,20 @@ +import customOperate from './customList/custom'; +import FaultLogListOperate from './table/faultLogList'; +import PaginationOperate from './pagination/pagination'; +import TableScrollOperate from './table/tableScroll'; +import RuleFormOperate from './formSearch/rulesForm'; +import unmountOperate from './table/unmount'; +import faultHandingConfirmOpt from './faultHanding/faultHanding'; +import {ExportFilterData, ExportDataOperate} from './export/export'; + +export { + customOperate, + FaultLogListOperate, + TableScrollOperate, + RuleFormOperate, + unmountOperate, + PaginationOperate, + ExportFilterData, + ExportDataOperate, + faultHandingConfirmOpt +}; diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/customList/custom.ts b/bmp-operation-web/src/views/monitorManagement/faultLog/customList/custom.ts new file mode 100644 index 0000000..df96f99 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/customList/custom.ts @@ -0,0 +1,13 @@ +/** + * @file + * @author +*/ + +import {methodsTotal} from 'utils/index.ts'; +import useCustom from 'hooks/custom/useCustom.ts'; + +const name: string = methodsTotal.humpConversion('alertLogList'); + +const customOperate = useCustom(name).info; + +export default customOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/customList/customList.vue b/bmp-operation-web/src/views/monitorManagement/faultLog/customList/customList.vue new file mode 100644 index 0000000..fed007e --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/customList/customList.vue @@ -0,0 +1,8 @@ + + diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/export/export.ts b/bmp-operation-web/src/views/monitorManagement/faultLog/export/export.ts new file mode 100644 index 0000000..65f0f1a --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/export/export.ts @@ -0,0 +1,41 @@ +import store from 'store/index.ts'; +import {methodsTotal} from 'utils/index.ts'; +import {ExportDataOperate, CurrentInstance} from 'utils/publicClass.ts'; + +class ExportFilterData { + // 是否导出数据 + hasExportData: Ref = ref(true); + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + search: { + ruleForm: {} + }; + searchTip: {value: boolean}; + proxy = new CurrentInstance().proxy; + + constructor(search: {ruleForm: {}}, searchTip: {value: boolean}) { + this.search = search; + this.searchTip = searchTip; + }; + + exportData = (that: never) => { + new ExportDataOperate(this.proxy.$faultLogApi.faultLogExportAPI, {}, 'oob_alert_log_list').exportData(that); + }; + + /** + * 参数处理 + */ + paramsProcessing = (that: never) => { + const otherParams = this.searchTip.value ? methodsTotal.toLine(this.search.ruleForm) : {}; + this.filterEmptyInfo.deleteEmtpyData(otherParams); + new ExportDataOperate(this.proxy.$faultLogApi.faultLogExportAPI, { + ...otherParams + }, 'oob_alert_log_list').exportData(that); + } +}; + +export { + ExportFilterData, + ExportDataOperate +}; diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/export/exportData.vue b/bmp-operation-web/src/views/monitorManagement/faultLog/export/exportData.vue new file mode 100644 index 0000000..2b9f088 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/export/exportData.vue @@ -0,0 +1,23 @@ + + + diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/faultHanding/faultHanding.ts b/bmp-operation-web/src/views/monitorManagement/faultLog/faultHanding/faultHanding.ts new file mode 100644 index 0000000..56401be --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/faultHanding/faultHanding.ts @@ -0,0 +1,31 @@ +import {CurrentInstance} from 'utils/publicClass.ts'; + +const faultHandingConfirmOpt = (faultLogListOperate: {refresh(): void}) =>{ + const faultHandingConfirmDiaLog: Ref = ref(false); + const mitt = new CurrentInstance(); + + const faultHandingConfirmClick = async (item: any) => { + if (item.status) return; + faultHandingConfirmDiaLog.value = !faultHandingConfirmDiaLog.value; + await nextTick(() => { + mitt.instanceMitt?.proxy?.$Bus?.emit('fault-handing-confirm', item); + }); + }; + + const faultHandingConfirmCancel = (type: boolean) => { + faultHandingConfirmDiaLog.value = type; + }; + + const faultHandingConfirmCancelSure = () => { + faultLogListOperate.refresh(); + }; + + return { + faultHandingConfirmDiaLog, + faultHandingConfirmClick, + faultHandingConfirmCancel, + faultHandingConfirmCancelSure + } +}; + +export default faultHandingConfirmOpt; diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/faultHanding/faultHanding.vue b/bmp-operation-web/src/views/monitorManagement/faultLog/faultHanding/faultHanding.vue new file mode 100644 index 0000000..0fb6192 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/faultHanding/faultHanding.vue @@ -0,0 +1,18 @@ + + diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/faultLog.vue b/bmp-operation-web/src/views/monitorManagement/faultLog/faultLog.vue new file mode 100644 index 0000000..4af0637 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/faultLog.vue @@ -0,0 +1,101 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/formSearch/formSearch.vue b/bmp-operation-web/src/views/monitorManagement/faultLog/formSearch/formSearch.vue new file mode 100644 index 0000000..a5af179 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/formSearch/formSearch.vue @@ -0,0 +1,178 @@ + + diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/formSearch/rulesForm.ts b/bmp-operation-web/src/views/monitorManagement/faultLog/formSearch/rulesForm.ts new file mode 100644 index 0000000..87866c3 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/formSearch/rulesForm.ts @@ -0,0 +1,119 @@ +/** + * @file + * @author +*/ + +import {RuleFormRefType} from '@utils/publicType'; +import {RuleFormType} from '../typeManagement'; +import {paginationOperate} from 'utils/publicClass.ts'; +import {getDateParams} from 'utils/index.ts'; + +class RuleFormOperate { + // 表单ref + ruleFormRef: Ref = ref(); + // 表单输入项 + ruleForm: RuleFormType = reactive({ + idcId: '', + sn: '', + level: '', + faultReportingTime: '', + startTime: '', + endTime: '', + spec: '', + dealStatus: '' + }); + searchParams: RuleFormType = reactive({ + ...this.ruleForm + }); + btnStatus: Ref = ref(false); + fn: Function; + + constructor(fn: Function) { + const sn: string = sessionStorage?.getItem('sn')?? ''; + this.ruleForm.sn = sn; + this.fn = fn; + }; + + snChange = () => { + this.ruleForm.sn = this.ruleForm.sn?.replace(/\s*/g, ''); + }; + + disabledDate = (time: Date) => { + return time.getTime() > Date.now() + }; + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: RuleFormRefType}): void => { + this.ruleFormRef.value = formEl.value; + }; + + searchClick = () => { + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + const sn = sessionStorage?.getItem('sn')?? ''; + sn?.length ? this.fn('queryParams', this.ruleForm) : this.fn('search'); + }; + + clearSn = () => { + const sn = sessionStorage?.getItem('sn')??''; + const clearDataOpt = [ + [ + (sn: string) => sn?.length, + () => { + this.fn('queryParams', this.ruleForm) + sessionStorage?.removeItem('sn'); + } + ], + [ + (sn: string) => !sn?.length, + () => { + this.ruleForm.sn = ''; + this.searchParams?.sn?.length && this.fn('hasSearch'); + } + ] + ]; + for(const key of clearDataOpt) { + if (key[0](sn)) { + key[1](sn); + break; + } + } + }; + + singleClear = (type: string) => { + const that = this; + (this.ruleForm[`${type}` as keyof typeof that.ruleForm] as string) = ''; + (this.searchParams[`${type}` as keyof typeof that.searchParams] as string)?.length && this.fn('hasSearch') + }; + + clearClick = () => { + sessionStorage?.removeItem('sn'); + const that = this; + for (let key in this.ruleForm) { + (this.ruleForm[`${key}` as keyof typeof that.ruleForm] as string) = ''; + } + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn('clear'); + }; + + dateChange = (val: string[] | null) => { + if (!val) { + this.ruleForm.startTime = ''; + this.ruleForm.endTime = ''; + this.fn('hasSearch') + return; + }; + this.ruleForm.startTime = getDateParams(val[0]); + this.ruleForm.endTime = getDateParams(val[1]); + } +}; + +export default RuleFormOperate; diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/module.ts b/bmp-operation-web/src/views/monitorManagement/faultLog/module.ts new file mode 100644 index 0000000..56d70d1 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/module.ts @@ -0,0 +1,17 @@ +import TableList from './table/tableList.vue'; +import ExportData from './export/exportData.vue'; +import FormSearch from './formSearch/formSearch.vue'; +import CustomList from './customList/customList.vue'; +import Pagination from './pagination/pagination.vue'; +import FaultHanding from './faultHanding/faultHanding.vue'; + +const pluginComp = { + TableList, + ExportData, + Pagination, + CustomList, + FormSearch, + FaultHanding +}; + +export default pluginComp; diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/page.ts b/bmp-operation-web/src/views/monitorManagement/faultLog/page.ts new file mode 100644 index 0000000..b63fd4d --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/page.ts @@ -0,0 +1,10 @@ +const FaultLog = () => import(/* webpackChunkName: "FaultLog" */ './faultLog.vue'); + +export default { + path: '/MonitorManagement/faultLog', + name: 'FaultLog', + component: FaultLog, + meta: { + type: 'faultLog' + } +}; diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/pagination/pagination.ts b/bmp-operation-web/src/views/monitorManagement/faultLog/pagination/pagination.ts new file mode 100644 index 0000000..b0c3f01 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/pagination/pagination.ts @@ -0,0 +1,27 @@ +import {paginationOperate} from 'utils/publicClass.ts'; +/** + * 分页监听 +*/ +class PaginationOperate { + + // 构造器 + constructor (list: any) { + this.watchSizeNumber(list); + }; + + /** + * 监听分页页数、条数变化 + */ + watchSizeNumber = (list: any) => { + + watch(() => [ + paginationOperate.pageSize.value, + paginationOperate.pageNumber.value + ], (_: boolean[]): void => { + if (paginationOperate.routerChange.value) return; + list.search(); + }); + }; +}; + +export default PaginationOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/pagination/pagination.vue b/bmp-operation-web/src/views/monitorManagement/faultLog/pagination/pagination.vue new file mode 100644 index 0000000..ae8c6b1 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/pagination/pagination.vue @@ -0,0 +1,25 @@ + + + diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/table/faultLogList.ts b/bmp-operation-web/src/views/monitorManagement/faultLog/table/faultLogList.ts new file mode 100644 index 0000000..c8cacfc --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/table/faultLogList.ts @@ -0,0 +1,152 @@ +import {AxiosError} from 'axios'; +import {CurrencyType} from '@utils/publicType'; +import {msgTip, methodsTotal, deepCopy} from 'utils/index.ts'; +import {paginationOperate, language, CurrentInstance} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; +import FalutLogStaticData from 'staticData/surveillance/faultLog/index.ts'; + +// 坑,引入mock这个文件,文件流导出数据会有问题 +// import 'mock/faultLog/index.ts'; +// import {mockFaultLogListAPI} from 'mock/faultLog/request.ts'; + +class FaultLogListOperate { + // routerQuery = new RouterOperate().router.currentRoute.value; + env: string = process.env.VUE_APP_ENV; + searchTip: Ref = ref(false); + isLoading: Ref = ref(true); // loading态 + // store + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + tableRef: any; + errorCode: Ref = ref(0); + reactiveArr: { + tableData: any[]; + selectArr: any[]; + } = reactive<{ + tableData: any[]; + selectArr: any[]; + }>({ + tableData: [], // 表格-机型列表数据 + selectArr: [] + }); + params: any; + proxy = new CurrentInstance().proxy; + + constructor (params: any = {}) { + this.params = params; + const sn: string = sessionStorage?.getItem('sn')?? ''; + if (sn?.length) { + this.params.ruleForm.sn = sn; + this.search(); + return; + } + this.init(); + }; + + /** + * 获取表格ref + * @param {Object} tableEl 表格信息 + */ + getTableRef = (tableEl: any): void => { + this.tableRef = tableEl; + }; + + queryParamsClick = (query: any) => { + const status = Object.values(query).some((item) => item !== ''); + status ? this.search() : this.init(); + }; + + refresh = () => { + if (!this.reactiveArr.tableData.length) { + this.params.clearClick(); + return; + } + this.searchTip.value ? this.search() : this.init(); + }; + + init = () => { + this.isLoading.value = true; + this.getFaultLogList(); + }; + + search = () => { + this.isLoading.value = true; + this.getFaultLogList(methodsTotal.toLine(this.params.ruleForm)) + }; + + getFaultLogList = async (param?: any) => { + const params = methodsTotal.toLine({ + pageNum: paginationOperate.pageNumber.value, + pageSize: paginationOperate.pageSize.value + }); + const newParams = {...params, ...param} + this.filterEmptyInfo.deleteEmtpyData(newParams); + this.params.searchParams = newParams; + try { + const faultLogApi = await this.proxy.$faultLogApi.faultLogAPI(newParams); + if (faultLogApi?.data?.result?.detail?.length) { + const {detail, totalCount} = methodsTotal.lineConverting(faultLogApi.data.result); + this.reactiveArr.selectArr = deepCopy(detail); + detail.forEach((item: CurrencyType, index: number) => { + FalutLogStaticData.faultLogTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }) + }) + this.reactiveArr.tableData = detail; + paginationOperate.total.value = totalCount; + return; + } + throw new Error(''); + } + catch (e) { + const err = e as AxiosError; + this.errorCode.value = err.code as unknown as number; + this.params.btnStatus.value = this.errorCode.value === 403; + this.reactiveArr.tableData = []; + paginationOperate.total.value = 0; + methodsTotal.initScrollLeft(this.tableRef.value); + if (['module license disabled'].includes(err.message)) { + return; + } + err.message && msgTip.error(err.message); + } + finally { + this.isLoading.value = false; + this.searchTip.value = Object.keys(newParams).length > 2; + } + }; + + setStatus = (status: number) => { + const newStatus = new Map([ + [0, language.t('surveillance.status.no')], + [1, language.t('surveillance.status.yes')] + ]); + return newStatus.get(status); + }; + + setColor = (status: number | string) => { + const val: string = String(status); + const newColor = new Map([ + ['0', '#ff4d4f'], + ['1', '#43b561'] + ]); + return newColor.get(val) + }; + + mockData = () => { + // mockFaultLogListAPI() + // .then((res: any) => { + // const data = methodsTotal.lineConverting(res.data); + // data.forEach((item: any, index: number) => { + // FalutLogStaticData.faultLogTipData.forEach((t: string) => { + // Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + // }) + // }) + // this.reactiveArr.tableData = data; + // paginationOperate.total.value = res.totalCount; + // }); + } +}; + +export default FaultLogListOperate; diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/table/setEmpty.ts b/bmp-operation-web/src/views/monitorManagement/faultLog/table/setEmpty.ts new file mode 100644 index 0000000..b4835e5 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/table/setEmpty.ts @@ -0,0 +1,42 @@ +import {language} from 'utils/publicClass'; + +const p = document.createElement('p'); + +class SetEmpty { + constructor(props: any) { + this.watchTableData(props); + onUnmounted(() => p.innerHTML = ''); + }; + + watchTableData = (props: any) => { + watch(() => props?.faultLog?.reactiveArr.tableData, (newValue) => { + if (!newValue?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.innerHTML = ''; + }, {deep: true}) + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + ai!.innerHTML = ''; + const customText: HTMLElement | null = document.querySelector('.fault-log-list .el-scrollbar__view'); + p.className = 'custom-tip-count'; + const str2 = ` + ${language.t('table.empty')} + `; + this.otherEmpty(str2, customText!); + }; + + otherEmpty = (str: string, customText: HTMLElement) => { + const parser = new DOMParser(); + const doc = parser.parseFromString(str, 'text/html'); + p.innerHTML = doc.body.innerHTML; + customText?.appendChild(p); + } +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/table/tableList.vue b/bmp-operation-web/src/views/monitorManagement/faultLog/table/tableList.vue new file mode 100644 index 0000000..0e322f7 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/table/tableList.vue @@ -0,0 +1,540 @@ + + + diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/table/tableScroll.ts b/bmp-operation-web/src/views/monitorManagement/faultLog/table/tableScroll.ts new file mode 100644 index 0000000..96a2dd3 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/table/tableScroll.ts @@ -0,0 +1,56 @@ +import {HeightType, HeightType2} from '@utils/publicType'; +import {tableScroll} from 'utils/index.ts'; +import {TimerOperate} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; + +class TableScrollOperate extends TimerOperate { + fixedHeight: Ref = ref(0); + tableMaxHeight: Ref = ref(0); + headerTitle: Ref = ref({offsetHeight: 0}); + operate: Ref = ref({offsetHeight: 0, offsetTop: 0}); + searchHeight: any; + constructor () { + super(); + onMounted(async () => { + tableScroll(this.#setHeight(), this.tableMaxHeight); + this.#resize(); + await this.#watchNavBar(); + }); + + onUnmounted(() => clearTimeout(this.timer)); + }; + + searchRef = (val: {value: {offsetHeight: number}}) => { + this.searchHeight = val; + }; + + #watchNavBar = () => { + watch(() => store.navigationBarStatus.hasNavigationBar, (_: boolean) => { + this.timer = setTimeout(() => { + tableScroll(this.#setHeight(), this.tableMaxHeight); + }, 180) + }); + }; + + #resize = () => { + window.onresize = () => { + tableScroll(this.#setHeight(), this.tableMaxHeight); + }; + }; + + #setHeight = () => { + this.fixedHeight.value = (this.headerTitle.value.offsetHeight * 3) + this.operate.value.offsetHeight + 6; + const countHeight = this.searchHeight?.value?.offsetHeight + this.fixedHeight.value; + return countHeight; + }; + + getHeaderRef = (val: {value: HeightType2;}) => { + this.headerTitle.value = val.value; + }; + + getOperateRef = (val: {value: HeightType;})=> { + this.operate.value = val.value; + }; +} + +export default TableScrollOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/table/unmount.ts b/bmp-operation-web/src/views/monitorManagement/faultLog/table/unmount.ts new file mode 100644 index 0000000..82b93a2 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/table/unmount.ts @@ -0,0 +1,9 @@ +const unmountOperate = () => { + // 销毁的生命周期 + onUnmounted(() => { + const sn = sessionStorage?.getItem('sn')??''; + sn && sessionStorage.removeItem('sn'); + }); +}; + +export default unmountOperate; diff --git a/bmp-operation-web/src/views/monitorManagement/faultLog/typeManagement.ts b/bmp-operation-web/src/views/monitorManagement/faultLog/typeManagement.ts new file mode 100644 index 0000000..759c798 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultLog/typeManagement.ts @@ -0,0 +1,14 @@ +interface RuleFormType { + idcId: string; + sn: string; + level: string; + faultReportingTime: string; + startTime: string; + endTime: string; + spec: string; + dealStatus: string; +}; + +export { + RuleFormType +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/all.ts b/bmp-operation-web/src/views/monitorManagement/faultRules/all.ts new file mode 100644 index 0000000..d82b049 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/all.ts @@ -0,0 +1,23 @@ +import customOperate from './customList/custom'; +import FaultRulesListOperate from './table/faultRulesList'; +import TableScrollOperate from './table/tableScroll'; +import PaginationOperate from './pagination/pagination'; +import RuleFormOperate from './formSearch/rulesForm' +import DefaultSetOperate from './resetDefSet/resetDefSet'; +import FaultPushOperate from './faultPushOpt/faultPushOpt'; +import EnableStatusOperate from './enableStatusOpt/enableStatusOpt'; +import {ExportFilterData, ExportDataOperate, faultRulesExportAPI} from './export/export'; + +export { + customOperate, + FaultRulesListOperate, + RuleFormOperate, + DefaultSetOperate, + PaginationOperate, + FaultPushOperate, + EnableStatusOperate, + TableScrollOperate, + ExportFilterData, + ExportDataOperate, + faultRulesExportAPI +}; diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/customList/custom.ts b/bmp-operation-web/src/views/monitorManagement/faultRules/customList/custom.ts new file mode 100644 index 0000000..ff60817 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/customList/custom.ts @@ -0,0 +1,13 @@ +/** + * @file + * @author +*/ + +import {methodsTotal} from 'utils/index.ts'; +import useCustom from 'hooks/custom/useCustom.ts'; + +const name: string = methodsTotal.humpConversion('alertRuleList'); + +const customOperate = useCustom(name).info; + +export default customOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/customList/customList.vue b/bmp-operation-web/src/views/monitorManagement/faultRules/customList/customList.vue new file mode 100644 index 0000000..df5e2bb --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/customList/customList.vue @@ -0,0 +1,8 @@ + + diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/enableStatusOpt/enableStatusOpt.ts b/bmp-operation-web/src/views/monitorManagement/faultRules/enableStatusOpt/enableStatusOpt.ts new file mode 100644 index 0000000..7de7da8 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/enableStatusOpt/enableStatusOpt.ts @@ -0,0 +1,30 @@ +class EnableStatusOperate { + enableStatusDiaLog: Ref = ref(false); + useItem: {useStatus: boolean; ruleId: number; alertName: string} = {useStatus: false, ruleId: 0, alertName: ''}; + faultRulesListOpt: any; + + constructor(faultRulesListOpt: any) { + this.faultRulesListOpt = faultRulesListOpt; + }; + + enableStatusClick = (item: any) => { + item.useLoading = true; + this.useItem.useStatus = item.useStatus; + this.useItem.ruleId = item.ruleId; + this.useItem.alertName = item.alertName + nextTick(() => { + this.enableStatusDiaLog.value = !this.enableStatusDiaLog.value; + }) + }; + + enableStatusCancel = (type: boolean) => { + this.faultRulesListOpt.reactiveArr.tableData.map((item: {useLoading: boolean})=> item.useLoading = false); + this.enableStatusDiaLog.value = type; + }; + + enableStatusSure = () => { + this.faultRulesListOpt.refresh(); + }; +}; + +export default EnableStatusOperate; diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/enableStatusOpt/enableStatusOpt.vue b/bmp-operation-web/src/views/monitorManagement/faultRules/enableStatusOpt/enableStatusOpt.vue new file mode 100644 index 0000000..6dc7825 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/enableStatusOpt/enableStatusOpt.vue @@ -0,0 +1,23 @@ + + diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/export/export.ts b/bmp-operation-web/src/views/monitorManagement/faultRules/export/export.ts new file mode 100644 index 0000000..3ecb58b --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/export/export.ts @@ -0,0 +1,42 @@ +import {faultRulesExportAPI} from 'api/surveillance/faultRule/request.ts'; +import {ExportDataOperate} from 'utils/publicClass.ts'; +import {methodsTotal} from 'utils/index.ts'; +import store from 'store/index.ts'; + +class ExportFilterData { + // 是否导出数据 + hasExportData: Ref = ref(true); + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + search: { + ruleForm: {} + }; + searchTip: {value: boolean} + + constructor(search: {ruleForm: {}}, searchTip: {value: boolean}) { + this.search = search; + this.searchTip = searchTip; + }; + + exportData = (that: never) => { + new ExportDataOperate(faultRulesExportAPI, {}, 'alert_rule_list').exportData(that); + }; + + /** + * 参数处理 + */ + paramsProcessing = (that: never) => { + const otherParams = this.searchTip.value ? methodsTotal.toLine(this.search.ruleForm) : {}; + this.filterEmptyInfo.deleteEmtpyData(otherParams); + new ExportDataOperate(faultRulesExportAPI, { + ...otherParams, + }, 'alert_rule_list').exportData(that); + } +}; + +export { + ExportFilterData, + ExportDataOperate, + faultRulesExportAPI +}; diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/export/exportData.vue b/bmp-operation-web/src/views/monitorManagement/faultRules/export/exportData.vue new file mode 100644 index 0000000..2b9f088 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/export/exportData.vue @@ -0,0 +1,23 @@ + + + diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/faultPushOpt/faultPushOpt.ts b/bmp-operation-web/src/views/monitorManagement/faultRules/faultPushOpt/faultPushOpt.ts new file mode 100644 index 0000000..d94ee42 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/faultPushOpt/faultPushOpt.ts @@ -0,0 +1,39 @@ +class FaultPushOperate { + faultPushDiaLog: Ref = ref(false); + pushItem: {pushStatus: boolean; ruleId: number; alertName: string} = {pushStatus: false, ruleId: 0, alertName: ''}; + faultRulesListOpt: { + reactiveArr: { + tableData: any; + }; + refresh(): void; + }; + + constructor (faultRulesListOpt: {reactiveArr: {tableData: any}; refresh(): void;}) { + this.faultRulesListOpt = faultRulesListOpt; + }; + + faultPushClick = (item: any) => { + item.pushLoading = true; + this.pushItem.pushStatus = item.pushStatus; + this.pushItem.ruleId = item.ruleId; + this.pushItem.alertName = item.alertName + + return new Promise((resolve) => { + nextTick(() => { + this.faultPushDiaLog.value = !this.faultPushDiaLog.value; + }) + return resolve(true); + }) + }; + + faultPushCancel = (type: boolean) => { + this.faultRulesListOpt.reactiveArr.tableData.map((item: {pushLoading: boolean})=> item.pushLoading = false); + this.faultPushDiaLog.value = type; + }; + + faultPushSure = () => { + this.faultRulesListOpt.refresh(); + }; +}; + +export default FaultPushOperate; diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/faultPushOpt/faultPushOpt.vue b/bmp-operation-web/src/views/monitorManagement/faultRules/faultPushOpt/faultPushOpt.vue new file mode 100644 index 0000000..8ca3c80 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/faultPushOpt/faultPushOpt.vue @@ -0,0 +1,23 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/faultRules.vue b/bmp-operation-web/src/views/monitorManagement/faultRules/faultRules.vue new file mode 100644 index 0000000..8faa4cc --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/faultRules.vue @@ -0,0 +1,101 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/formSearch/formSearch.vue b/bmp-operation-web/src/views/monitorManagement/faultRules/formSearch/formSearch.vue new file mode 100644 index 0000000..d2881b9 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/formSearch/formSearch.vue @@ -0,0 +1,132 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/formSearch/rulesForm.ts b/bmp-operation-web/src/views/monitorManagement/faultRules/formSearch/rulesForm.ts new file mode 100644 index 0000000..5312fcc --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/formSearch/rulesForm.ts @@ -0,0 +1,75 @@ +import {RuleFormRefType} from '@utils/publicType'; +import {RuleFormType} from '../typeManagement'; +import {paginationOperate} from 'utils/publicClass.ts'; +import {methodsTotal} from 'utils/index.ts'; +class RuleFormOperate { + btnDisabled: Ref = ref(true); + // 表单ref + ruleFormRef: Ref = ref(); + // 表单输入项 + ruleForm: RuleFormType = reactive({ + alertName: '', + alertSpec: '', + alertLevel: '', + }); + searchParams: RuleFormType = reactive({ + ...this.ruleForm + }); + btnStatus: Ref = ref(false); + fn: Function + + constructor(fn: Function) { + this.fn = fn; + }; + + faultNameChange = () => { + this.ruleForm.alertName = this.ruleForm.alertName?.replace(/\s*/g, ''); + }; + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: RuleFormRefType}): void => { + this.ruleFormRef.value = formEl.value; + }; + + searchClick = () => { + // if (paginationOperate.pageNumber.value > 1) { + // paginationOperate.pageNumber.value = 1; + // return; + // } + // this.fn('search') + this.paginationNumSet('search'); + // this.list.search(); + }; + + singleClear = (type: string) => { + const that = this; + (this.ruleForm[`${type}` as keyof typeof that.ruleForm] as string) = ''; + (this.searchParams[`${methodsTotal.toLine(type)}` as keyof typeof that.searchParams] as string)?.length && this.fn('hasSearch'); + }; + + clearClick = () => { + const that = this; + for (let key in this.ruleForm) { + (this.ruleForm[`${key}` as keyof typeof that.ruleForm] as string) = ''; + } + this.paginationNumSet('clear'); + // if (paginationOperate.pageNumber.value > 1) { + // paginationOperate.pageNumber.value = 1; + // return; + // } + // this.fn('clear'); + }; + + paginationNumSet = (type: string) => { + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn(type) + }; +}; + +export default RuleFormOperate; diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/module.ts b/bmp-operation-web/src/views/monitorManagement/faultRules/module.ts new file mode 100644 index 0000000..9f33b4c --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/module.ts @@ -0,0 +1,21 @@ +import TableList from './table/tableList.vue'; +import ExportData from './export/exportData.vue'; +import Pagination from './pagination/pagination.vue'; +import CustomList from './customList/customList.vue'; +import FormSearch from './formSearch/formSearch.vue'; +import ResetDefSet from './resetDefSet/resetDefSet.vue'; +import FaultPushOpt from './faultPushOpt/faultPushOpt.vue'; +import EnableStatusOpt from './enableStatusOpt/enableStatusOpt.vue'; + +const pluginComp = { + TableList, + ExportData, + Pagination, + CustomList, + FormSearch, + ResetDefSet, + FaultPushOpt, + EnableStatusOpt +}; + +export default pluginComp; diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/page.ts b/bmp-operation-web/src/views/monitorManagement/faultRules/page.ts new file mode 100644 index 0000000..3be1c3a --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/page.ts @@ -0,0 +1,10 @@ +const FaultRules = () => import(/* webpackChunkName: "FaultRules" */ './faultRules.vue'); + +export default { + path: '/MonitorManagement/faultRules', + name: 'FaultRules', + component: FaultRules, + meta: { + type: 'faultRules' + } +}; diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/pagination/pagination.ts b/bmp-operation-web/src/views/monitorManagement/faultRules/pagination/pagination.ts new file mode 100644 index 0000000..b0c3f01 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/pagination/pagination.ts @@ -0,0 +1,27 @@ +import {paginationOperate} from 'utils/publicClass.ts'; +/** + * 分页监听 +*/ +class PaginationOperate { + + // 构造器 + constructor (list: any) { + this.watchSizeNumber(list); + }; + + /** + * 监听分页页数、条数变化 + */ + watchSizeNumber = (list: any) => { + + watch(() => [ + paginationOperate.pageSize.value, + paginationOperate.pageNumber.value + ], (_: boolean[]): void => { + if (paginationOperate.routerChange.value) return; + list.search(); + }); + }; +}; + +export default PaginationOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/pagination/pagination.vue b/bmp-operation-web/src/views/monitorManagement/faultRules/pagination/pagination.vue new file mode 100644 index 0000000..f28741b --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/pagination/pagination.vue @@ -0,0 +1,25 @@ + + + diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/resetDefSet/resetDefSet.ts b/bmp-operation-web/src/views/monitorManagement/faultRules/resetDefSet/resetDefSet.ts new file mode 100644 index 0000000..54bf783 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/resetDefSet/resetDefSet.ts @@ -0,0 +1,22 @@ +class DefaultSetOperate { + defaultSetDiaLog: Ref = ref(false); + faultRulesListOpt: {refresh(): void}; + + constructor(faultRulesListOpt: {refresh(): void}) { + this.faultRulesListOpt = faultRulesListOpt; + } + + defaultSetClick = () => { + this.defaultSetDiaLog.value = !this.defaultSetDiaLog.value; + }; + + defaultSetCancel = (type: boolean) => { + this.defaultSetDiaLog.value = type; + }; + + defaultSetSure = () => { + this.faultRulesListOpt.refresh(); + }; +}; + +export default DefaultSetOperate; diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/resetDefSet/resetDefSet.vue b/bmp-operation-web/src/views/monitorManagement/faultRules/resetDefSet/resetDefSet.vue new file mode 100644 index 0000000..cb14acd --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/resetDefSet/resetDefSet.vue @@ -0,0 +1,22 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/table/faultRulesList.ts b/bmp-operation-web/src/views/monitorManagement/faultRules/table/faultRulesList.ts new file mode 100644 index 0000000..c21d66d --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/table/faultRulesList.ts @@ -0,0 +1,144 @@ +import {faultRulesAPI} from 'api/surveillance/faultRule/request.ts'; +import {paginationOperate} from 'utils/publicClass.ts'; +import {msgTip, methodsTotal} from 'utils/index.ts'; +import store from 'store/index.ts'; +import { CurrencyType, CurrencyType3 } from '@utils/publicType'; +import FaultRulesStaticeData from 'staticData/surveillance/faultRules/index.ts'; + +class FaultRulesListOperate { + isLoading: Ref = ref(true); // loading态 + searchTip: Ref = ref(false); + // store + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + reactiveArr: { + tableData: any[]; + selectArr: CurrencyType[]; + } = reactive<{ + tableData: any[]; + selectArr: CurrencyType[]; + }>({ + tableData: [], // 表格-机型列表数据 + selectArr: [] + }); + errorCode: Ref = ref(0); + tableRef: { + [x: string]: unknown; + value?: { + toggleRowSelection(arg1: CurrencyType, arg2: undefined): void; + clearFilter(): unknown; + clearSelection(): void; + $refs: any; + } + } = { + value: { + clearFilter(): void{}, + toggleRowSelection(): void{}, + clearSelection(): void{}, + $refs: {} + } + }; + params: any; + + constructor (params: any) { + this.params = params; + this.init(); + }; + + /** + * 获取表格ref + * @param {Object} tableEl 表格信息 + */ + getTableRef = (tableEl: CurrencyType3): void => { + this.tableRef = tableEl; + }; + + refresh = () => { + if (!this.reactiveArr.tableData.length) { + this.params.clearClick(); + return; + } + this.searchTip.value ? this.search() : this.init(); + }; + + init = () => { + this.getFaultRulesList(); + }; + + search = () => { + this.getFaultRulesList(methodsTotal.toLine(this.params.ruleForm)) + }; + + getFaultRulesList = (param?: any): void => { + this.isLoading.value = true; + const params = methodsTotal.toLine({ + pageNum: paginationOperate.pageNumber.value, + pageSize: paginationOperate.pageSize.value + }); + const newParamse = {...params, ...param} + this.filterEmptyInfo.deleteEmtpyData(newParamse); + this.params.searchParams = newParamse; + faultRulesAPI( + { + ...newParamse, + } + ).then(({data}: {data: {result: {detail: CurrencyType[]}}}) => { + if (data?.result?.detail?.length) { + const {detail, totalCount} = methodsTotal.lineConverting(data.result); + const newData = detail.map((item: CurrencyType, index: number) => { + FaultRulesStaticeData.faultRulesTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }); + return { + ...item, + pushLoading: false, + useLoading: false, + pushStatus: !!(item.pushStatus), + useStatus: !!(item.useStatus) + } + }) + this.reactiveArr.tableData = newData; + paginationOperate.total.value = totalCount; + return; + } + return Promise.reject(''); + }).catch((err: {code: number; message: string}) => { + this.errorCode.value = err.code as unknown as number; + this.params.btnStatus.value = this.errorCode.value === 403; + this.reactiveArr.tableData = []; + paginationOperate.total.value = 0; + methodsTotal.initScrollLeft(this.tableRef.value); + if (['module license disabled'].includes(err.message)) { + return; + } + err.message && msgTip.error(err.message); + }).finally(() => { + this.isLoading.value = false; + this.searchTip.value = Object.keys(newParamse).length > 2; + }); + }; + + filterChange = (val: CurrencyType[]) => { + this.reactiveArr.selectArr = val; + this.params.btnDisabled.value = !val.length; + }; + + cellClick = (row: CurrencyType, b: {property: string}) => { + const type = ['pushStatus', 'useStatus']; + if (type.indexOf(b.property) > -1) return; + this.toggleSelection([row]); + }; + + toggleSelection = (rows?: CurrencyType[]) => { + if (rows) { + rows.forEach((row: CurrencyType) => { + this.tableRef.value?.toggleRowSelection(row, undefined); + }); + return; + } + this.tableRef.value?.clearSelection(); + }; +}; + +export default FaultRulesListOperate; diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/table/setEmpty.ts b/bmp-operation-web/src/views/monitorManagement/faultRules/table/setEmpty.ts new file mode 100644 index 0000000..b37cff8 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/table/setEmpty.ts @@ -0,0 +1,51 @@ +import {language} from 'utils/publicClass.ts'; +const p = document.createElement('p'); +interface PropType { + faultRules: { + reactiveArr: { + tableData: []; + }, + errorCode: { + value: number; + } + } +} + +class SetEmpty { + constructor(props: PropType) { + this.watchTableData(props); + onUnmounted(() => p.innerHTML = ''); + }; + + watchTableData = (props: PropType) => { + watch(() => props?.faultRules?.reactiveArr.tableData, (newValue) => { + if (!newValue?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.innerHTML = ''; + }, {deep: true}) + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + ai!.innerHTML = ''; + const customText: HTMLElement | null = document.querySelector('.fault-rules-list .el-scrollbar__view'); + p.className = 'custom-tip-count'; + const str2 = ` + ${language.t('table.empty')} + `; + this.otherEmpty(str2, customText!); + }; + + otherEmpty = (str: string, customText: HTMLElement) => { + const parser = new DOMParser(); + const doc = parser.parseFromString(str, 'text/html'); + p.innerHTML = doc.body.innerHTML; + customText?.appendChild(p); + } +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/table/tableList.vue b/bmp-operation-web/src/views/monitorManagement/faultRules/table/tableList.vue new file mode 100644 index 0000000..0d29810 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/table/tableList.vue @@ -0,0 +1,340 @@ + + + diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/table/tableScroll.ts b/bmp-operation-web/src/views/monitorManagement/faultRules/table/tableScroll.ts new file mode 100644 index 0000000..d27f07c --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/table/tableScroll.ts @@ -0,0 +1,56 @@ +import {HeightType, HeightType2} from '@utils/publicType'; +import {tableScroll} from 'utils/index.ts'; +import {TimerOperate} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; + +class TableScrollOperate extends TimerOperate { + fixedHeight: Ref = ref(0); + tableMaxHeight: Ref = ref(0); + headerTitle: Ref = ref({offsetHeight: 0}); + operate: Ref = ref({offsetHeight: 0, offsetTop: 0}); + searchHeight: any; + constructor () { + super(); + onMounted(async () => { + tableScroll(this.#setHeight(), this.tableMaxHeight); + this.#resize(); + await this.#watchNavBar(); + }); + + onUnmounted(() => clearTimeout(this.timer)); + }; + + searchRef = (val: {value: {offsetHeight: number}}) => { + this.searchHeight = val; + }; + + #watchNavBar = () => { + watch(() => store.navigationBarStatus.hasNavigationBar, (_: boolean) => { + this.timer = setTimeout(() => { + tableScroll(this.#setHeight(), this.tableMaxHeight); + }, 200) + }); + }; + + #resize = () => { + window.onresize = () => { + tableScroll(this.#setHeight(), this.tableMaxHeight); + }; + }; + + #setHeight = () => { + this.fixedHeight.value = (this.headerTitle.value.offsetHeight * 3) + this.operate.value.offsetHeight + 6; + const countHeight = this.searchHeight?.value?.offsetHeight + this.fixedHeight.value; + return countHeight; + }; + + getHeaderRef = (val: {value: HeightType2;}) => { + this.headerTitle.value = val.value; + }; + + getOperateRef = (val: {value: HeightType;})=> { + this.operate.value = val.value; + }; +} + +export default TableScrollOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/faultRules/typeManagement.ts b/bmp-operation-web/src/views/monitorManagement/faultRules/typeManagement.ts new file mode 100644 index 0000000..162016f --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/faultRules/typeManagement.ts @@ -0,0 +1,9 @@ +interface RuleFormType { + alertName: string; + alertSpec: string; + alertLevel: string; +}; + +export { + RuleFormType +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/all.ts b/bmp-operation-web/src/views/monitorManagement/hardware/all.ts new file mode 100644 index 0000000..200f0fd --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/all.ts @@ -0,0 +1,16 @@ +import customOperate from './customList/custom'; +import HardwareStatusListOperate from './table/hardwareList'; +import RuleFormOperate from './formSearch/rulesForm'; +import TableScrollOperate from './table/tableScroll'; +import PaginationOperate from './pagination/pagination'; +import {ExportFilterData, ExportDataOperate} from './export/export'; + +export { + customOperate, + RuleFormOperate, + TableScrollOperate, + PaginationOperate, + HardwareStatusListOperate, + ExportFilterData, + ExportDataOperate +}; diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/customList/custom.ts b/bmp-operation-web/src/views/monitorManagement/hardware/customList/custom.ts new file mode 100644 index 0000000..e0bc096 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/customList/custom.ts @@ -0,0 +1,13 @@ +/** + * @file + * @author +*/ + +import {methodsTotal} from 'utils/index.ts'; +import useCustom from 'hooks/custom/useCustom.ts'; + +const name: string = methodsTotal.humpConversion('deviceStatusList'); + +const customOperate = useCustom(name).info; + +export default customOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/customList/customList.vue b/bmp-operation-web/src/views/monitorManagement/hardware/customList/customList.vue new file mode 100644 index 0000000..27e01a4 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/customList/customList.vue @@ -0,0 +1,8 @@ + + diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/export/export.ts b/bmp-operation-web/src/views/monitorManagement/hardware/export/export.ts new file mode 100644 index 0000000..42d05ce --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/export/export.ts @@ -0,0 +1,43 @@ +import store from 'store/index.ts'; +import {methodsTotal} from 'utils/index.ts'; +import {ExportDataOperate, CurrentInstance} from 'utils/publicClass.ts'; + +class ExportFilterData { + // 是否导出数据 + hasExportData: Ref = ref(true); + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + search: { + ruleForm: {} + }; + searchTip: {value: boolean} + proxy = new CurrentInstance().proxy; + + constructor(search: {ruleForm: {}}, searchTip: {value: boolean}) { + this.search = search; + this.searchTip = searchTip; + }; + + exportData = (that: never) => { + const api = this.proxy.$hardwareStatusApi.hardwareStatusExportAPI; + new ExportDataOperate(api, {}, 'device_status_list').exportData(that); + }; + + /** + * 参数处理 + */ + paramsProcessing = (that: never) => { + const api = this.proxy.$hardwareStatusApi.hardwareStatusExportAPI; + const otherParams = this.searchTip.value ? methodsTotal.toLine(this.search.ruleForm) : {}; + this.filterEmptyInfo.deleteEmtpyData(otherParams); + new ExportDataOperate(api, { + ...otherParams, + }, 'device_status_list').exportData(that); + } +}; + +export { + ExportFilterData, + ExportDataOperate +}; diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/export/exportData.vue b/bmp-operation-web/src/views/monitorManagement/hardware/export/exportData.vue new file mode 100644 index 0000000..2b9f088 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/export/exportData.vue @@ -0,0 +1,23 @@ + + + diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/formSearch/formSearch.vue b/bmp-operation-web/src/views/monitorManagement/hardware/formSearch/formSearch.vue new file mode 100644 index 0000000..64e8341 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/formSearch/formSearch.vue @@ -0,0 +1,92 @@ + + diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/formSearch/rulesForm.ts b/bmp-operation-web/src/views/monitorManagement/hardware/formSearch/rulesForm.ts new file mode 100644 index 0000000..9497603 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/formSearch/rulesForm.ts @@ -0,0 +1,69 @@ +import {RuleFormRefType} from '@utils/publicType'; +import {RuleFormType} from '../typeManagement'; +import {paginationOperate} from 'utils/publicClass.ts'; + +class RuleFormOperate { + // 表单ref + ruleFormRef: Ref = ref(); + // 表单输入项 + ruleForm: RuleFormType = reactive({ + idcId: '', + sn: '', + }); + searchParams: RuleFormType = reactive({ + ...this.ruleForm + }); + fn: Function; + btnStatus: Ref = ref(false); + + constructor(fn: Function) { + this.fn = fn; + }; + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: RuleFormRefType}): void => { + this.ruleFormRef.value = formEl.value; + }; + + snChange = () => { + this.ruleForm.sn = this.ruleForm.sn?.replace(/\s*/g, ''); + }; + + searchClick = () => { + this.paginationNumSet('search'); + }; + + paginationNumSet = (type: string) => { + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.fn(type) + }; + + clearSn = () => { + this.ruleForm.sn = ''; + this.searchParams?.sn?.length && this.fn('hasSearch', this.searchParams) + }; + + + clearClick = () => { + const that = this; + for (let key in this.ruleForm) { + (this.ruleForm[`${key}` as keyof typeof that.ruleForm] as string) = ''; + } + this.paginationNumSet('clear'); + // if (paginationOperate.pageNumber.value > 1) { + // paginationOperate.pageNumber.value = 1; + // return; + // } + // this.fn('clear') + // this.ruleFormRef.value!.resetFields(); + // console.log(this.ruleForm, 'ruleForm'); + }; +}; + +export default RuleFormOperate; diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/hardwareStatus.vue b/bmp-operation-web/src/views/monitorManagement/hardware/hardwareStatus.vue new file mode 100644 index 0000000..a7ce6d2 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/hardwareStatus.vue @@ -0,0 +1,95 @@ + + + diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/module.ts b/bmp-operation-web/src/views/monitorManagement/hardware/module.ts new file mode 100644 index 0000000..a20bed4 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/module.ts @@ -0,0 +1,16 @@ + +import TableList from './table/tableList.vue'; +import ExportData from './export/exportData.vue'; +import CustomList from './customList/customList.vue'; +import Pagination from './pagination/pagination.vue'; +import FormSearch from './formSearch/formSearch.vue'; + +const pluginComp = { + TableList, + ExportData, + CustomList, + Pagination, + FormSearch +}; + +export default pluginComp; diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/page.ts b/bmp-operation-web/src/views/monitorManagement/hardware/page.ts new file mode 100644 index 0000000..5644373 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/page.ts @@ -0,0 +1,24 @@ +const HardwareStatus = () => import(/* webpackChunkName: "HardwareStatus" */ './hardwareStatus.vue'); + +export default { + // def: { + // path: '/MonitorManagement', + // redirect: { + // name: 'HardwareStatus' + // } + // }, + // noDef: { + // path: '/MonitorManagement/hardwareStatus', + // name: 'HardwareStatus', + // component: HardwareStatus, + // meta: { + // type: 'hardwareStatus' + // } + // } + path: '/MonitorManagement/hardwareStatus', + name: 'HardwareStatus', + component: HardwareStatus, + meta: { + type: 'hardwareStatus' + } +}; diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/pagination/pagination.ts b/bmp-operation-web/src/views/monitorManagement/hardware/pagination/pagination.ts new file mode 100644 index 0000000..b0c3f01 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/pagination/pagination.ts @@ -0,0 +1,27 @@ +import {paginationOperate} from 'utils/publicClass.ts'; +/** + * 分页监听 +*/ +class PaginationOperate { + + // 构造器 + constructor (list: any) { + this.watchSizeNumber(list); + }; + + /** + * 监听分页页数、条数变化 + */ + watchSizeNumber = (list: any) => { + + watch(() => [ + paginationOperate.pageSize.value, + paginationOperate.pageNumber.value + ], (_: boolean[]): void => { + if (paginationOperate.routerChange.value) return; + list.search(); + }); + }; +}; + +export default PaginationOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/pagination/pagination.vue b/bmp-operation-web/src/views/monitorManagement/hardware/pagination/pagination.vue new file mode 100644 index 0000000..ebeccb8 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/pagination/pagination.vue @@ -0,0 +1,25 @@ + + + diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/table/hardwareList.ts b/bmp-operation-web/src/views/monitorManagement/hardware/table/hardwareList.ts new file mode 100644 index 0000000..9a76df9 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/table/hardwareList.ts @@ -0,0 +1,129 @@ +import {AxiosError} from 'axios'; +import {paginationOperate, RouterOperate, CurrentInstance} from 'utils/publicClass.ts'; +import {msgTip, methodsTotal} from 'utils/index.ts'; +import {CurrencyType} from '@utils/publicType'; +import store from 'store/index.ts'; +import HardwareStaticData from 'staticData/surveillance/hardware/index.ts'; +import DeviceStaticData from 'staticData/device/index.ts'; + +class HardwareStatusListOperate { + router = new RouterOperate().router; + searchTip: Ref = ref(false); + isLoading: Ref = ref(true); // loading态 + tableRef: { + [x: string]: unknown; + value: any; + } = {value: {}}; + errorCode: Ref = ref(0); + // store + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + reactiveArr: { + tableData: CurrencyType[]; + } = reactive<{ + tableData: CurrencyType[]; + }>({ + tableData: [] // 表格-机型列表数据 + }); + params: any; + instanceProxy = new CurrentInstance().proxy; + + constructor (params: any) { + this.params = params; + this.init(); + }; + + /** + * 获取表格ref + * @param {Object} tableEl 表格信息 + */ + getTableRef = (tableEl: { + [x: string]: unknown + value: { + $refs: any; + } + }): void => { + this.tableRef = tableEl; + }; + + + refresh = () => { + if (!this.reactiveArr.tableData.length) { + this.params.clearClick(); + return; + } + this.searchTip.value ? this.search() : this.init(); + }; + + init = () => { + this.getHardwareList(); + }; + + search = () => { + this.getHardwareList(methodsTotal.toLine(this.params.ruleForm)) + }; + + getHardwareList = async (param?: any) => { + this.isLoading.value = true; + const params = methodsTotal.toLine({ + pageNum: paginationOperate.pageNumber.value, + pageSize: paginationOperate.pageSize.value + }); + const newParamse = {...params, ...param} + this.filterEmptyInfo.deleteEmtpyData(newParamse); + this.params.searchParams = newParamse; + try { + const listApi = await this.instanceProxy.$hardwareStatusApi.hardwareStatusAPI(newParamse); + if (listApi?.data?.result?.detail?.length) { + const {detail, totalCount} = methodsTotal.lineConverting(listApi.data.result); + detail.forEach((item: CurrencyType, index: number) => { + HardwareStaticData.hardwareTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }) + }) + this.reactiveArr.tableData = detail; + paginationOperate.total.value = totalCount; + return; + } + throw new Error(''); + } + catch (e) { + const err = e as AxiosError; + this.errorCode.value = err?.code as unknown as number; + this.params.btnStatus.value = this.errorCode.value === 403; + this.reactiveArr.tableData = []; + paginationOperate.total.value = 0; + methodsTotal.initScrollLeft(this.tableRef.value); + if (['module license disabled'].includes(err?.message)) { + return; + } + err?.message && msgTip.error(err.message); + } + finally { + this.isLoading.value = false; + this.searchTip.value = Object.keys(newParamse).length > 2; + } + }; + + setStatus = (status: number) => { + const key: Map = new Map([ + [0, this.instanceProxy.$defInfo.imagePath('greenIcon')], + [1, this.instanceProxy.$defInfo.imagePath('redIcon')] + ]); + return key.get(status); + }; + + setManagementStatus = (status: string) => { + const newStatus = DeviceStaticData.manageMentStatus.find((item: {filterParams: string; text: string}) => item.filterParams === status); + return newStatus?.text; + }; + + + jumpRouter = (sn: string, path: string) => { + this.router.push(path); + sessionStorage.setItem('sn', sn); + } +}; + +export default HardwareStatusListOperate; diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/table/setEmpty.ts b/bmp-operation-web/src/views/monitorManagement/hardware/table/setEmpty.ts new file mode 100644 index 0000000..1650d9b --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/table/setEmpty.ts @@ -0,0 +1,42 @@ +import {language} from 'utils/publicClass'; + +const p = document.createElement('p'); + +class SetEmpty { + constructor(props: any) { + this.watchTableData(props); + onUnmounted(() => p.innerHTML = ''); + }; + + watchTableData = (props: any) => { + watch(() => props?.hardware?.reactiveArr.tableData, (newValue) => { + if (!newValue?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.innerHTML = ''; + }, {deep: true}) + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + ai!.innerHTML = ''; + const customText: HTMLElement | null = document.querySelector('.hardware-list .el-scrollbar__view'); + p.className = 'custom-tip-count'; + const str2 = ` + ${language.t('table.empty')} + `; + this.otherEmpty(str2, customText!); + }; + + otherEmpty = (str: string, customText: HTMLElement) => { + const parser = new DOMParser(); + const doc = parser.parseFromString(str, 'text/html'); + p.innerHTML = doc.body.innerHTML; + customText?.appendChild(p); + } +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/table/tableList.vue b/bmp-operation-web/src/views/monitorManagement/hardware/table/tableList.vue new file mode 100644 index 0000000..c4f1bae --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/table/tableList.vue @@ -0,0 +1,341 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/table/tableScroll.ts b/bmp-operation-web/src/views/monitorManagement/hardware/table/tableScroll.ts new file mode 100644 index 0000000..f09a458 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/table/tableScroll.ts @@ -0,0 +1,62 @@ +import {HeightType, HeightType2} from '@utils/publicType'; +import {tableScroll} from 'utils/index.ts'; +import {TimerOperate} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; + +class TableScrollOperate extends TimerOperate { + fixedHeight: Ref = ref(0); + tableMaxHeight: Ref = ref(0); + headerTitle: Ref = ref({offsetHeight: 0}); + operate: Ref = ref({offsetHeight: 0, offsetTop: 0}); + searchHeight: Ref = ref({offsetHeight: 0});; + constructor () { + super(); + onMounted(async () => { + // this.fixedHeight.value = this.headerTitle.value.offsetHeight + this.headerTitle.value.scrollHeight + this.operate.value.offsetHeight + // const countHeight = this.searchHeight?.value?.offsetHeight + this.searchHeight?.value?.scrollHeight + this.fixedHeight.value; + tableScroll(this.#setHeight(), this.tableMaxHeight); + this.#resize(); + await this.#watchNavBar(); + }); + + onUnmounted(() => clearTimeout(this.timer)); + }; + + searchRef = (val: {value: HeightType2}) => { + this.searchHeight.value = val.value; + }; + + #watchNavBar = () => { + watch(() => store.navigationBarStatus.hasNavigationBar, (_: boolean) => { + this.timer = setTimeout(() => { + // const countHeight = this.searchHeight?.value?.offsetHeight + this.searchHeight?.value?.scrollHeight + this.fixedHeight.value; + tableScroll(this.#setHeight(), this.tableMaxHeight); + }, 200) + }); + }; + + #resize = () => { + window.onresize = () => { + // const countHeight = this.searchHeight?.value?.offsetHeight + this.searchHeight?.value?.scrollHeight + fixedHeight; + tableScroll(this.#setHeight(), this.tableMaxHeight); + }; + }; + + #setHeight = () => { + // this.headerTitle.value.scrollHeight + this.fixedHeight.value = this.headerTitle.value.offsetHeight * 3 + this.operate.value.offsetHeight + 5; + // this.searchHeight?.value?.scrollHeight + const countHeight = this.searchHeight?.value?.offsetHeight + this.fixedHeight.value; + return countHeight; + }; + + getHeaderRef = (val: {value: HeightType2;}) => { + this.headerTitle.value = val.value; + }; + + getOperateRef = (val: {value: HeightType;})=> { + this.operate.value = val.value; + }; +} + +export default TableScrollOperate; diff --git a/bmp-operation-web/src/views/monitorManagement/hardware/typeManagement.ts b/bmp-operation-web/src/views/monitorManagement/hardware/typeManagement.ts new file mode 100644 index 0000000..956cba4 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/hardware/typeManagement.ts @@ -0,0 +1,8 @@ +interface RuleFormType { + idcId: string; + sn: string; +}; + +export { + RuleFormType +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/monitorManagement/navRouter.ts b/bmp-operation-web/src/views/monitorManagement/navRouter.ts new file mode 100644 index 0000000..ba76760 --- /dev/null +++ b/bmp-operation-web/src/views/monitorManagement/navRouter.ts @@ -0,0 +1,47 @@ +/** + * @file + * @author +*/ + +import {language} from "utils/publicClass.ts"; + +const monitoringNavData = (pathUrl: (arg0: string) => void, imgUrl: (arg0: string) => void) => { + return { + title: language.t('navigationBar.list.surveillanceManagement'), + defaultImg: imgUrl('surveillanceDef'), + changeImg: imgUrl('surveillance'), + childrenCentF: true, + path: [ + pathUrl('hardwareStatus'), + pathUrl('faultLog'), + pathUrl('faultRules') + ], + otherPath: [''], + firstIndex: 'MonitorManagement', + children: [ + { + title: language.t('navigationBar.children.hardwareAlarmStatus'), + defaultImg: imgUrl('surveillanceDef'), + changeImg: imgUrl('surveillance'), + path: pathUrl('hardwareStatus'), + otherPath: [pathUrl('hardwareStatus')] + }, + { + title: language.t('navigationBar.children.faultAlarmLog'), + defaultImg: imgUrl('surveillanceDef'), + changeImg: imgUrl('surveillance'), + path: pathUrl('faultLog'), + otherPath: [pathUrl('faultLog')] + }, + { + title: language.t('navigationBar.children.faultAlarmRules'), + defaultImg: imgUrl('surveillanceDef'), + changeImg: imgUrl('surveillance'), + path: pathUrl('faultRules'), + otherPath: [pathUrl('faultRules')] + } + ] + } +}; + +export default monitoringNavData; diff --git a/bmp-operation-web/src/views/navigationBar/menu/menuChildren1.vue b/bmp-operation-web/src/views/navigationBar/menu/menuChildren1.vue new file mode 100644 index 0000000..fc005bc --- /dev/null +++ b/bmp-operation-web/src/views/navigationBar/menu/menuChildren1.vue @@ -0,0 +1,113 @@ + + + + + diff --git a/bmp-operation-web/src/views/navigationBar/menu/menuLeft.vue b/bmp-operation-web/src/views/navigationBar/menu/menuLeft.vue new file mode 100644 index 0000000..4c46a76 --- /dev/null +++ b/bmp-operation-web/src/views/navigationBar/menu/menuLeft.vue @@ -0,0 +1,79 @@ + + + + + diff --git a/bmp-operation-web/src/views/navigationBar/navigationBar.scss b/bmp-operation-web/src/views/navigationBar/navigationBar.scss new file mode 100644 index 0000000..805c524 --- /dev/null +++ b/bmp-operation-web/src/views/navigationBar/navigationBar.scss @@ -0,0 +1,333 @@ +$width1: 219px; + +/* 侧边栏外层样式 */ +.operate-navigationbar { + position: absolute; + left: 0; + overflow: hidden; + right: 0; + bottom: 0; + display: flex; + padding: 12px 7px 12px 0; + min-height: calc(100vh - 80px); + + .long-set-nav { + .nav-col { + width: 219px; + .el-menu { + position: relative; + } + } + } + + .set-nav { + .nav-col { + position: absolute; + + .el-menu { + position: relative; + } + } + } + + /* 侧边栏中层样式 */ + .long-set-nav, + .set-nav { + position: absolute; + height: calc(100% - 23px); + margin-left: 8px; + bottom: 0; + left: 0; + top: 13px; + right: 0; + background: #fff; + border-radius: 10px; + max-width: 219px; + transition: all .3s; + + /* 侧边栏展开样式 */ + .nav-col { + height: 100%; + box-shadow: 0 1px 4px 0 rgba(153,153,153,0.50); + border-radius: 10px; + transition: all .3s; + + .el-scrollbar { + border-radius: 10px; + } + + .el-menu { + border-right: 0; + } + + .nav-title-default { + margin-left: 36px; + } + + .nav-sub-long { + overflow: hidden; + width: 100px; + text-overflow: ellipsis; + } + + /* 侧边栏收起-【多级菜单】样式 */ + :deep(.custom-children-menu-short) { + // width: 100%; + .el-sub-menu__title { + + .default-img { + animation: img-long-short .3s forwards; + } + } + } + + /* 侧边栏收起-【多级菜单】选中样式 */ + :deep(.custom-children-menu-short.is-active) { + + .el-sub-menu__title { + background: #e8f4fd; + border-top-left-radius: 20px; + border-bottom-left-radius: 20px; + } + } + + /* 侧边栏展开-【多级菜单】样式 */ + :deep(.custom-children-menu) { + + .el-sub-menu__title { + .default-img { + animation: img-short-long .3s forwards; + } + } + } + + /* 侧边栏展开-【多级菜单】选中样式 */ + :deep(.custom-children-menu.is-active) { + .el-sub-menu__title { + background: #e8f4fd; + .el-icon { + color: #108ee9; + } + } + } + + /* 侧边栏【多级菜单】展开收起样式 */ + :deep(.custom-children-menu), + :deep(.custom-children-menu-short) { + float: right; + width: 87%; + transition: all .3s; + + /* 侧边栏展开收起子路由前缀样式 */ + .chilren-radius { + width: 5px; + height: 5px; + border-radius: 50%; + background: #000; + margin-left: 8px; + margin-right: 27px; + } + + .el-menu { + padding: 0; + display: flex; + flex-direction: column; + box-shadow: none !important; + + &-item { + height: 42px; + min-width: 190px; + padding-left: 17px !important; + } + } + + /* 侧边栏-【多级菜单】样式 */ + .el-sub-menu__title { + --el-menu-item-height: 42px; + margin-bottom: 16px; + border-top-left-radius: 20px; + border-bottom-left-radius: 20px; + + img { + width: 16px; + height: 16px; + position: absolute; + } + + &:hover { + --el-menu-hover-bg-color: #f7f7f7; + } + } + } + + .custom-height { + position: absolute; + bottom: 0; + background: #fff; + width: 100%; + height: 67px; + z-index: 9; + border-bottom-right-radius: 10px; + border-bottom-left-radius: 10px; + } + + /* 侧边栏展开分割线样式 */ + .nav-long-line { + width: 175px; + margin-left: 21px; + } + + // /* 侧边栏收起分割线样式 */ + .nav-short-line { + width: 33px; + margin-left: 12px; + } + + /* 侧边栏展开收起分割线样式 */ + .nav-long-line, + .nav-short-line { + height: .6px; + background: $color2; + display: flex; + position: absolute; + bottom: 66px; + transition: all .3s; + z-index: 10; + } + + /* 侧边栏展开icon位置 */ + .long-nav-icon { + left: 175px; + } + + /* 侧边栏收起icon位置 */ + .short-nav-icon { + left: 20px; + } + + /* 侧边栏展开收起icon样式 */ + .long-nav-icon, + .short-nav-icon { + position: absolute; + z-index: 9; + bottom: 0; + margin-bottom: 28px; + z-index: 10; + transition: left .3s; + + .img-rotate { + transform: rotateY(180deg); + transition: all .3s; + } + + .img, + .img-rotate { + width: 17px; + height: 17px; + cursor: pointer; + } + } + } + } + + /* router-view样式 */ + .long-content, + .short-content { + height: calc(100% - 23px); + position: absolute; + margin: 0; + overflow: auto; + top: 13px; + bottom: 0; + right: 9px; + display: flex; + flex-direction: column; + background: $color3; + box-shadow: 0 1px 4px 0 rgba(153,153,153,0.30); + border-radius: 10px; + transition: width .3s; + } + + /* router-view样式 */ + .long-content { + width: calc(100% - 248px); + } + + /* router-view样式 */ + .short-content { + width: calc(100% - 85px); + } + + /* 侧边栏展开样式 */ + .item-long-width { + .default-img { + animation: img-short-long .3s forwards; + } + } + + /* 侧边栏收起样式 */ + .item-short-width { + .default-img { + animation: img-long-short .3s forwards; + } + } + + .short-img { + left: 14px !important; + } + + .init-img { + left: 20px !important; + } + + /* 侧边栏展开收起img样式 */ + .item-long-width, + .item-short-width { + width: 87%; + float: right; + border-top-left-radius: 20px; + border-bottom-left-radius: 20px; + + img { + width: 16px; + height: 16px; + position: absolute; + top: 50%; + transform: translateY(-50%); + } + } + + @keyframes img-short-long { + 0% { + left: 14px; + } + 100% { + left: 20px; + } + } + + + @keyframes img-long-short { + 0% { + left: 20px; + } + 100% { + left: 14px; + } + } + +} + +/* 侧边栏收起-子路由滑过显示样式 */ +:deep(.custom-short-nav.el-menu-item) { + height: 45px !important; + + &:hover { + background: #f7f7f7 !important; + } +} + +/* 侧边栏收起-子路由选中样式 */ +:deep(.custom-short-nav.el-menu-item.is-active) { + background: #e8f4fd !important; +} diff --git a/bmp-operation-web/src/views/navigationBar/navigationBar.vue b/bmp-operation-web/src/views/navigationBar/navigationBar.vue new file mode 100644 index 0000000..e2abd0d --- /dev/null +++ b/bmp-operation-web/src/views/navigationBar/navigationBar.vue @@ -0,0 +1,89 @@ + + + + + diff --git a/bmp-operation-web/src/views/navigationBar/page.ts b/bmp-operation-web/src/views/navigationBar/page.ts new file mode 100644 index 0000000..c3e3528 --- /dev/null +++ b/bmp-operation-web/src/views/navigationBar/page.ts @@ -0,0 +1,41 @@ +/** + * @file + * @author +*/ + +import {CurrencyType} from "@utils/publicType"; + +type NavBarType = () => Promise + +const NavigationBar: NavBarType = () => import(/* webpackChunkName: "NavigationBar" */ './navigationBar.vue'); + +// 创建一个 require 上下文 +const requireAll = (requireContext: T) => { + // keys 返回字典的所有的key + return requireContext.keys().map(requireContext); +} + +// 将上下文合并为一个数组 +const allRouterData: {default: CurrencyType; noDef: CurrencyType}[] = [ + ...requireAll(require.context('../', true, /\/page.ts$/)), +] + +let arr: {default: CurrencyType; noDef: CurrencyType;}[][] = []; + +allRouterData.forEach((t, i) => { + if (!t?.default || t.default?.def || Object.is(t.default.name, 'Login')) { + arr.push(allRouterData.splice(i, 1)); + } +}) + +export default { + nav: { + name: 'NavigationBar', + path: '/IdcManagement/idcList', + component: NavigationBar + }, + children: [ + arr[0][0].default.noDef, + ...allRouterData.map((item) => item.default) + ] +}; diff --git a/bmp-operation-web/src/views/navigationBar/utils/index.md b/bmp-operation-web/src/views/navigationBar/utils/index.md new file mode 100644 index 0000000..1aefd87 --- /dev/null +++ b/bmp-operation-web/src/views/navigationBar/utils/index.md @@ -0,0 +1,7 @@ +#### 导航 + +# 1:isF---字段,角色管理、用户管理、消息中心(admin)、消息中心(非admin) +# 2:hasAdmin---字段,角色管理、用户管理、消息中心(非admin),用来判断是否有权限 +# 3:childrenHasAdmin---消息中心(admin)、个人中心有这个字段【若没有admin权限,则消息中心隐藏,显示一级导航的消息中心,无消息设置】 +# 4:isChildrenF---消息中心(admin)、个人中心有这个字段 +# 5:path、otherPath,用来判断一级导航、二级导航高亮,若为二级导航,详细配置见children-path&otherPath \ No newline at end of file diff --git a/bmp-operation-web/src/views/navigationBar/utils/navOperate.ts b/bmp-operation-web/src/views/navigationBar/utils/navOperate.ts new file mode 100644 index 0000000..85292cc --- /dev/null +++ b/bmp-operation-web/src/views/navigationBar/utils/navOperate.ts @@ -0,0 +1,136 @@ +/** + * @file + * @author +*/ + +import store from 'store/index.ts'; +import {CurrencyType3} from '@utils/publicType'; +import {RouterOperate, CurrentInstance, TimerOperate, paginationOperate} from 'utils/publicClass.ts'; + +class NavOperate extends TimerOperate { + routerOperate: {router: {currentRoute: {value: {path: string}}; push: any; replace: (arg0: { path: string; }) => void}} = new RouterOperate(); + navTimer: null | number = null; + init: Ref = ref(true); + initShort: Ref = ref(true); + userShort: Ref = ref(true); + initUser: Ref = ref(true); + menuRef: { + [x: string]: unknown; + value?: { + close(arg0: string): unknown; + } + } = {value: {close(): void{}}}; + status: { + InBandMonitoringManagement: number; + MonitorManagement: number; + MessageNotification: number; + PersonalCenter: number; + } = reactive({ + 'InBandMonitoringManagement': 1, + 'MonitorManagement': 1, + 'MessageNotification': 1, + 'PersonalCenter': 1 + }) + instanceProxy = new CurrentInstance().proxy; + + // 构造器 + constructor (purviewInfoOpt: any) { + super(); + purviewInfoOpt.getPurviewInfo(); + this.watchPath(purviewInfoOpt); + }; + + select = (path: string) => { + this.routerOperate.router.push(path); + // this.routerOperate.router.replace({ + // path: index + // }); + }; + + /** + * 监听路径path + */ + watchPath = (purviewInfoOpt: any) => { + /** + * 监听路由path + * @param {string} newValue 每次更新的路由的值 + */ + watch(() => this.routerOperate.router.currentRoute.value.path, (newValue: string) => { + clearTimeout((this.navTimer as number)); + clearTimeout((this.timer as number)); + if (newValue) { + const {hasNavigationBar} = store.navigationBarStatus; + this.init.value = hasNavigationBar; + this.initUser.value = hasNavigationBar; + this.initShort.value = !hasNavigationBar; + this.userShort.value = !hasNavigationBar; + paginationOperate.total.value = 0; + this.routerOperate.router.currentRoute.value.path = newValue; + purviewInfoOpt.getPurviewInfo(); + // const path = this.instanceProxy.$defInfo.routerPath('myProfile'); + // const publicPath = this.instanceProxy.$defInfo.routerPath; + // const path = [publicPath('myProfile'), publicPath('securitySettings'), publicPath('apiKey'), publicPath('license')] + // if (!path.includes(window.location.pathname)) { + // store.userPurviewInfo().userInfo(); + // } + const typeCount: string[] = ['InBandMonitoringManagement', 'MonitorManagement', 'PersonalCenter', 'MessageNotification']; + for (const key of typeCount) { + // @ts-ignore + this.#setClose(newValue, key); + } + } + }, {deep: true}); + }; + + #setClose = (newValue: T, type: K) => { + const that = this; + // @ts-ignore + if (!newValue.includes(type) && !this.status[type]) { + this.menuRef.value?.close(String(type)); + (that.status[`${String(type)}` as keyof typeof that.status] as number) ++; + } + } + + closeClick = (index: string) => { + if (['InBandMonitoringManagement', 'MonitorManagement', 'PersonalCenter', 'MessageNotification'].indexOf(index) > -1) { + const that = this; + (this.status[`${index}` as keyof typeof that.status] as number) = 1; + } + }; + + openClick = (index: string) => { + const that = this; + + // if (!['MonitorManagement', 'PersonalCenter', 'MessageNotification'].includes(index)) { + // (this.status[`${index}` as keyof typeof that.status] as number) = 1; + // return; + // } + (this.status[`${index}` as keyof typeof that.status] as number) = 0; + }; + + /** + * 获取Menu ref + * @param {Object} menuEl menu信息 + */ + getMenuRef = (menuEl: CurrencyType3): void => { + this.menuRef = menuEl; + }; + + unfoldCollapseClick = () => { + for (const index in this.status) { + // @ts-ignore + this.status[index] = 0; + } + this.init.value = false; + this.initUser.value = false; + this.initShort.value = false; + this.userShort.value = false; + // this.menuRef.value?.close('MonitorManagement'); + // this.menuRef.value?.close('PersonalCenter'); + // this.navTimer = setTimeout(() => { + store.navigationBarStatus.hasNavigationBarClick(); + // }, 200); + }; +}; + +export default NavOperate; diff --git a/bmp-operation-web/src/views/navigationBar/utils/purviewInfo.ts b/bmp-operation-web/src/views/navigationBar/utils/purviewInfo.ts new file mode 100644 index 0000000..bd939e9 --- /dev/null +++ b/bmp-operation-web/src/views/navigationBar/utils/purviewInfo.ts @@ -0,0 +1,117 @@ +/** + * @file + * @author +*/ + +import {decrypt} from 'utils/index.ts'; +import {CurrentInstance} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; +import eyeryData from 'staticData/navBar/index.ts'; + +class PurviewInfoOpt { + purview: Ref = ref(''); + userPurview: { + userInfo(): void; + getUserPurview: any; + userPurview: string; + } = { + userInfo: () => '', + userPurview: '', + getUserPurview: store.userPurviewInfo() + }; + instanceProxy = new CurrentInstance().proxy; + navData; + + constructor() { + this.navData = eyeryData(this.instanceProxy) + } + + navLeft1 = () => { + return eyeryData(this.instanceProxy).slice(0, 4); + }; + + navLeft2 = () => { + const purview: string = this.instanceProxy!.$defInfo.purview('admin'); + const data = eyeryData(this.instanceProxy).filter((item: {isF: boolean}) => item.isF); + const status = this.purview.value === purview; + const info = data.filter((item: {hasAdmin: boolean}) => status ? item.hasAdmin : (!item.hasAdmin)) + if (info[0].path === '/UserManagement/userList') { + return info.reverse(); + } + return info; + }; + + outOfMonitoring = () => { + return this.navData.filter((item: {childrenCentF: boolean}) => item.childrenCentF); + } + + messagePersonal = () => { + const purview: string = this.instanceProxy!.$defInfo.purview('admin'); + const data = this.navData.filter((item: {isChildrenF: boolean}) => item.isChildrenF); + const status = this.purview.value === purview; + return status ? data : data.filter((item: {childrenHasAdmin: boolean}) => item.childrenHasAdmin); + } + + /** + * 菜单栏默认态 + * @param {Object} item 当前点击的这一项路由 + * @param {string} item.path 当前点击的路由地址 + * @return {string} /xxx/xxx 路由地址 + */ + defaultActive = (item: {path: string;}): string => { + for (const key of eyeryData(this.instanceProxy)) { + if (key?.children?.length) { + for (const listKey of key.children) { + if (listKey.otherPath.includes(item.path)) { + return listKey.path; + } + } + } + if (key?.otherPath.includes(item.path)) { + return key.path; + } + } + return item.path; + }; + + /** + * 获取权限信息 + */ + getPurviewInfo = () => { + try { + const status: string = localStorage?.getItem('userPurview')?? ''; + this.purview.value = (decrypt(status)); + const operator: string = this.instanceProxy!.$defInfo.purview('operator')?? ''; + const admin: string = this.instanceProxy!.$defInfo.purview('admin')?? ''; + const userName: string = localStorage?.getItem('userName')?? ''; + const email: string = localStorage?.getItem('email')?? ''; + const requestData = [ + [ + (operator: string, admin: string) => ![operator, admin].includes(this.purview.value as never), + () => { + this.userPurview?.getUserPurview.getUserPurview(this.instanceProxy.$loginUserApi) + .then((res: string) => { + this.userPurview.userPurview = res; + store.userPurviewInfo().userInfo() + }); + } + ], + [ + () => ([userName, email].includes('')), + async () => store.userPurviewInfo().userInfo() + ] + ]; + for (const key of requestData) { + if (key[0](operator, admin)) { + key[1](operator, admin); + break; + } + } + } + catch { + throw 'error'; + } + }; +} + +export default PurviewInfoOpt; diff --git a/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKey.scss b/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKey.scss new file mode 100644 index 0000000..64d2dcb --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKey.scss @@ -0,0 +1,39 @@ +.user-center-content { + .operate-management-content { + margin-top: 0px !important; + } + + /* 个人api密钥 */ + .api-key { + margin-top: 100px; + + .user-centet-table { + :deep(.el-table__cell) { + padding: 13.5px 0 !important; + } + + :deep(.el-table__inner-wrapper tr:first-child th) { + &:first-child { + border-left: none; + } + } + + :deep(.custom-tip-count) { + font-size: $fontSize; + @include text-align(center); + margin-bottom: 30px; + } + + } + + .create-key { + border-radius: 15px; + padding: 0 13px; + height: 30px; + font-size: $fontSize; + margin-bottom: 30px; + margin-left: 30px; + } + } + +} diff --git a/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKeyApi.vue b/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKeyApi.vue new file mode 100644 index 0000000..4b25eb0 --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKeyApi.vue @@ -0,0 +1,181 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKeyCreate/apiKeyCreate.vue b/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKeyCreate/apiKeyCreate.vue new file mode 100644 index 0000000..27da252 --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKeyCreate/apiKeyCreate.vue @@ -0,0 +1,22 @@ + + diff --git a/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKeyCreate/operate.ts b/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKeyCreate/operate.ts new file mode 100644 index 0000000..6ea83b6 --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKeyCreate/operate.ts @@ -0,0 +1,24 @@ +const createKey = (apiKey: any) => { + const createKeyDiaLog: Ref = ref(false); + + const createKeyClick = () => { + createKeyDiaLog.value = !createKeyDiaLog.value; + }; + + const createKeyCancel = (type: boolean): boolean => { + return createKeyDiaLog.value = type; + }; + + const createKeySure = () => { + apiKey.getApiKey(); + }; + + return { + createKeyDiaLog, + createKeyClick, + createKeyCancel, + createKeySure + }; +}; + +export default createKey; diff --git a/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKeyDelete/apiKeyDelete.vue b/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKeyDelete/apiKeyDelete.vue new file mode 100644 index 0000000..d55fcc5 --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKeyDelete/apiKeyDelete.vue @@ -0,0 +1,23 @@ + + diff --git a/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKeyDelete/operate.ts b/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKeyDelete/operate.ts new file mode 100644 index 0000000..17ecdd1 --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/apiKeyApi/apiKeyDelete/operate.ts @@ -0,0 +1,36 @@ +interface DataType { + apikeyId: Ref; + name: Ref; + deleteKeyDiaLog: Ref; +}; + +const deleteKey = (apiKey: any) => { + const data: DataType = { + apikeyId: ref(''), + name: ref(''), + deleteKeyDiaLog: ref(false) + }; + + const deleteKeyClick = (item: {apiKeyId: string; name: string;}) => { + data.name.value = item.name; + data.apikeyId.value = item.apiKeyId; + data.deleteKeyDiaLog.value = !data.deleteKeyDiaLog.value; + }; + + const deleteKeyCancel = (type: boolean): boolean => { + return data.deleteKeyDiaLog.value = type; + }; + + const deleteKeySure = () => { + apiKey.getApiKey(); + }; + + return { + ...data, + deleteKeyClick, + deleteKeyCancel, + deleteKeySure + } +}; + +export default deleteKey; diff --git a/bmp-operation-web/src/views/personalCenter/apiKeyApi/apikey.ts b/bmp-operation-web/src/views/personalCenter/apiKeyApi/apikey.ts new file mode 100644 index 0000000..9a7f93b --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/apiKeyApi/apikey.ts @@ -0,0 +1,63 @@ +/** + * @file + * @author +*/ + +import {CurrencyType} from '@utils/publicType'; +import {getApiKeyAPI} from 'api/userCenter/request.ts'; +import {paginationOperate, CurrentInstance} from 'utils/publicClass.ts'; +import UserCenterDataStatic from 'staticData/userCenter/index.ts'; + +interface ReactiveArrType { + keyNameData: string[]; + tableData: CurrencyType[]; +} + +class ApiKey { + mitt = new CurrentInstance(); + isBtnDisabled: Ref = ref(true); + isLoading: Ref = ref(true); + reactiveArr: ReactiveArrType = reactive({ + keyNameData: [], + tableData: [] + }); + + constructor() { + this.getApiKey(); + } + + getApiKey = () => { + this.isLoading.value = true; + getApiKeyAPI( + { + isAll: '1' + } + ) + .then(({data}: {data: {result: {apikeys: CurrencyType[]; totalCount: number}}}) => { + if (data?.result?.apikeys?.length) { + this.reactiveArr.tableData = data.result.apikeys.map((item: CurrencyType, index: number) => { + UserCenterDataStatic.apiKeyTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }) + return item; + }); + paginationOperate.total.value = data.result.totalCount; + this.reactiveArr.keyNameData = data.result.apikeys.map((item: CurrencyType) => item.name); + this.isBtnDisabled.value = data.result.totalCount >= 2; + return; + } + return Promise.reject(); + }) + .catch(() => { + this.reactiveArr.tableData = []; + paginationOperate.total.value = 0; + this.isBtnDisabled.value = false; + }) + .finally(() => { + this.isLoading.value = false; + this.mitt.instanceMitt?.proxy?.$Bus?.emit('api-key-data', this.reactiveArr.tableData); + }) + }; +}; + +export default ApiKey; diff --git a/bmp-operation-web/src/views/personalCenter/apiKeyApi/page.ts b/bmp-operation-web/src/views/personalCenter/apiKeyApi/page.ts new file mode 100644 index 0000000..0deaec9 --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/apiKeyApi/page.ts @@ -0,0 +1,10 @@ +const ApiKeyApi = () => import(/* webpackChunkName: "ApiKeyApi" */ './apiKeyApi.vue'); + +export default { + path: '/PersonalCenter/apiKeyApi', + name: 'ApiKeyApi', + component: ApiKeyApi, + meta: { + type: 'apiKeyApi' + } +}; diff --git a/bmp-operation-web/src/views/personalCenter/apiKeyApi/setEmpty.ts b/bmp-operation-web/src/views/personalCenter/apiKeyApi/setEmpty.ts new file mode 100644 index 0000000..1c6e89c --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/apiKeyApi/setEmpty.ts @@ -0,0 +1,59 @@ +/** + * @file + * @author +*/ + +import {language, CurrentInstance} from 'utils/publicClass.ts'; + +const p = document.createElement('p'); + +class SetEmpty { + createKey1: {createKeyClick(): void}; + mitt = new CurrentInstance(); + + constructor(createKey1: {createKeyClick(): void}) { + this.createKey1 = createKey1; + // this.watchTableData(); + this.mitt.instanceMitt?.proxy?.$Bus?.on('api-key-data', this.watchTableData); + onUnmounted(() =>{ + p.innerHTML = ''; + this.mitt.instanceMitt?.proxy?.$Bus?.off('api-key-data', this.watchTableData); + }); + }; + + watchTableData = (val: any) => { + if (!val?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.remove(); + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + ai!.innerHTML = ''; + const customText = document.querySelector('.user-centet-table .el-scrollbar__view'); + if (!customText) return; + const str = ` + + ${language.t('table.empty')},${language.t('table.tip')} + + + ${language.t('userCenter.btn.createKey')} + + ` + const parser = new DOMParser(); + const doc = parser.parseFromString(str, 'text/html'); + p.className = 'custom-tip-count'; + p.innerHTML = doc.body.innerHTML; + customText.appendChild(p) + const clickOpt = document.querySelector('.user-centet-table .custom-tip-count .empty-text'); + clickOpt!.addEventListener('click', () => { + this.createKey1.createKeyClick(); + }); + }; +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/personalCenter/apiKeyApi/tableScroll.ts b/bmp-operation-web/src/views/personalCenter/apiKeyApi/tableScroll.ts new file mode 100644 index 0000000..c0555ef --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/apiKeyApi/tableScroll.ts @@ -0,0 +1,44 @@ +import {HeightType3} from '@utils/publicType'; +import {tableScroll} from 'utils/index.ts'; + +const tableScrollOperate = () => { + const data = { + tableMaxHeight: ref(0), + headerTitle: ref({ + offsetHeight: 0, + scrollHeight: 0 + }) + }; + + onMounted(() => { + getHeightTop(); + }); + + onUnmounted(() => { + window.onresize = null; + document.onkeyup = () => {return;} + }); + + window.onresize = () => { + getHeightTop(); + }; + + const getHeaderRef = (val: Ref) => { + data.headerTitle = val; + }; + + const getHeightTop = () => { + const createKeyBtn: HTMLElement | null = document!.querySelector('.create-key'); + nextTick(() => { + const countHeight = createKeyBtn!.offsetHeight + data.headerTitle.value.scrollHeight + data.headerTitle.value.offsetHeight + 120; + tableScroll(countHeight, data.tableMaxHeight); + }) + }; + + return { + ...data, + getHeaderRef + } +}; + +export default tableScrollOperate; diff --git a/bmp-operation-web/src/views/personalCenter/myProfile/myProfile.scss b/bmp-operation-web/src/views/personalCenter/myProfile/myProfile.scss new file mode 100644 index 0000000..8f18455 --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/myProfile/myProfile.scss @@ -0,0 +1,255 @@ +@import '@/assets/css//communal.scss'; + +.user-center-content { + // overflow-x: auto; + height: 100%; + display: flex; + flex-direction: column; + overflow-y: auto; + + .header-count-img { + margin: 0 15px 0 27px; + } + + .en-info { + padding: 0 7px; + } + + .default-info { + padding: 0 34px; + } + + .en-info, + .default-info { + margin-top: 78px; + + .el-tabs__active-bar { + background: $color1; + } + + .el-tabs__item { + font-size: $fontSize2; + color: $defaultColor; + font-weight: $fontSmallWeight; + // height: 37px; + // padding: 0 25px; + text-align: center; + + &:hover { + color: $color1; + } + } + + .el-tabs__item.is-active { + color: $color1; + font-weight: $fontSmallWeight; + } + + .el-tabs__nav-wrap { + &::after { + height: 1px !important; + background: $border; + } + } + } + + .my-info { + height: 100%; + overflow-y: auto; + margin-top: 80px; + overflow-x: hidden; + position: relative; + + .line { + height: 1px; + background: #f0f0f0; + position: absolute; + width: 100%; + left: 0; + margin-top: 17px; + } + + + .line2 { + height: 1px; + background: #f0f0f0; + position: absolute; + width: 100%; + left: -30px; + margin-top: 15px; + } + + .basinfo-count { + display: flex; + flex-direction: column; + + .m-l { + margin-left: 60px; + } + + .header-title { + display: flex; + align-items: center; + margin-bottom: 2px; + + .line-left { + width: 2px; + height: 14px; + background: #108ee9; + margin-right: 15px; + } + + .title { + font-size: $fontSize2; + font-weight: $fontLargeWeight; + color: $defaultColor; + } + } + + .header-title2 { + display: flex; + align-items: center; + font-size: $fontSize; + + span:nth-child(1) { + margin-right: 43px; + } + } + + .user-center-ruleForm { + margin-top: 11px; + + .preference-count { + position: absolute; + margin-top: 48px; + width: 100%; + padding-left: 60px; + } + + .language { + input { + width: 137px; + height: 36px; + border-radius: 5px; + } + } + + .time-one { + input { + width: 400px; + height: 36px; + border-radius: 5px; + } + } + + .set-empty { + margin-bottom: 32px !important; + } + + .el-form-item__label { + position: relative; + margin-left: 16px; + + &::before { + display: none; + } + } + + .el-form-item__error { + margin-top: 6px; + } + + .user-universal { + font-size: $fontSize; + color: $defaultColor; + font-weight: $fontSmallWeight; + width: 400px; + + input { + cursor: text !important; + color: #333; + } + } + + .el-form-item--default { + margin-bottom: 16px; + + &:last-child { + margin-bottom: 0; + } + } + + input { + // width: 515px; + height: 36px; + border-radius: 5px; + } + + .set-select-count { + .input-select { + .el-input__inner { + width: 165px; + } + } + } + + .input-select-count { + .input-select { + .el-input__inner { + width: 137px; + } + } + } + + .set-select-count, + .input-select-count { + float: left; + + .input-select { + .el-input__inner { + height: 36px; + border-radius: 5px; + color: $defaultColor; + font-weight: 500; + + // border-right: 0; + border-top-right-radius: 0; + border-bottom-right-radius: 0; + } + } + } + + .input-phone-count { + .el-input--default, + .el-input__inner { + width: 263px; + } + } + + .input-phone-count { + display: flex; + .el-form-item__content { + margin-left: 0px !important; + } + + .el-input--default, + .el-input__inner { + height: 36px; + // border-left: 0; + border-top-left-radius: 0; + border-bottom-left-radius: 0; + } + } + } + + .user-save { + width: 130px; + height: 36px; + border-radius: 5px; + font-size: $fontSize; + // position: absolute; + margin: 50px 17px 30px; + } + } + } +} diff --git a/bmp-operation-web/src/views/personalCenter/myProfile/myProfile.ts b/bmp-operation-web/src/views/personalCenter/myProfile/myProfile.ts new file mode 100644 index 0000000..f1649d1 --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/myProfile/myProfile.ts @@ -0,0 +1,186 @@ +import {RuleFormRefType} from '@utils/publicType'; +import {language, UserCheck, locationItem} from 'utils/publicClass.ts'; +import {userInfoAPI, timeOneAPI, setUserInfoAPI} from 'api/userCenter/request.ts'; +import {msgTip, customTip} from 'utils/index.ts'; +import UserStaticData from 'staticData/user/index.ts'; // 手机号类型数据 + +class FormRulesOperate { + isLoading: Ref = ref(false); + myInfoLoading: Ref = ref(true); + phoneFlag: Ref = ref(false); + emailFlag: Ref = ref(false); + reactiveArr: any = reactive({ + languageData: [ + language.t('userCenter.language.zh'), + language.t('userCenter.language.en') + ], + timezonesData: [] + }); + // 表单ref + ruleFormRef: Ref = ref(); + // 表单项 + ruleForm: any = reactive({ + phonePrefix: '', + type: '', + language: '', + timezonesVal: '', + roleName: '--', + email: '', + userName: '--', + phoneNumber: '' + }); + val: Ref = ref(''); + timeVal: string = ''; + // 规则 + rules: any = reactive({ + phoneNumber: [ // 手机号 + { + required: true, + trigger: 'blur', + // validator: new UserCheck(this.ruleForm.phonePrefix).phoneChcek + } + ], + email: [ // 邮箱 + { + required: true, + trigger: 'blur', + validator: new UserCheck().emailChcek + } + ] + }); + + constructor () { + document.onkeyup = (event: {keyCode: number;}) => { + event.keyCode === 13 && this.saveClick(); + }; + setTimeout(() => { + this.getUserName(); + }, 200) + // if (tabsOperate.activeName.value === 'myProfile') this.getUserName(); + }; + + getUserName = () => { + userInfoAPI({}) + .then(({data}: any) => { + if (data?.result && Object.keys(data.result)?.length) { + const {roleName, userName, email, phoneNumber, phonePrefix} = data.result; + const languageInfo = data.result.language; + this.ruleForm.roleName = roleName; + this.ruleForm.email = email; + this.ruleForm.userName = userName; + this.ruleForm.phoneNumber = phoneNumber; + this.ruleForm.language = languageInfo === 'en_US' ? language.t('userCenter.language.en') : language.t('userCenter.language.zh'); + this.val.value = data.result.timezone; + localStorage.setItem('email', window.btoa(this.ruleForm.email)); + // locationItem.cookie.set('X-Jdcloud-Language', languageInfo); + for(const key of UserStaticData.phoneType) { + if (key.type === phonePrefix) { + const value = UserStaticData.cellPhoneType.find((item: {label: string}) => item.label === key.name); + this.ruleForm.phonePrefix = key.name; + this.ruleForm.type = value.text; + } + } + this.rules.phoneNumber[0].validator = new UserCheck(this.ruleForm.phonePrefix).phoneChcek; + this.getTimeOne(); + } + }) + .catch(({message} : {message: string}) => { + msgTip.error(message); + }) + .finally(() => { + this.myInfoLoading.value = false; + }); + }; + + getTimeOne = () => { + timeOneAPI({}) + .then(({data} : any) => { + if (data?.result && Object.keys(data.result?.timezones).length) { + this.ruleForm.timezonesVal = data.result.timezones[this.val.value]; + for (const index in data.result.timezones) { + this.reactiveArr.timezonesData.push( + { + value: index, + label: data.result.timezones[index] + } + ) + } + this.timeVal = this.val.value; + } + }) + }; + + phonePrefixSelect = (val: string) => { + const value = UserStaticData.cellPhoneType.find((item: {label: string}) => item.label === val); + this.ruleForm.type = value.text; + this.ruleForm.phonePrefix = val; + this.ruleForm.phoneNumber = ''; + this.rules.phoneNumber[0].validator = new UserCheck(this.ruleForm.phonePrefix).phoneChcek; + }; + + timezoneChange = (val: string) => { + this.timeVal = this.reactiveArr.timezonesData.find((item: {label: string}) => item.label === val).value; + }; + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: RuleFormRefType}): void => { + this.ruleFormRef.value = formEl.value; + }; + + validate = (type1: never | string, type2: {value: boolean}) => { + this.ruleFormRef.value!.validateField(([type1] as never), (valid: string) => !valid ? type2.value = false : type2.value = true); + }; + + saveClick = async () => { + this.isLoading.value = true; + await nextTick(() => { + this.validate('phoneNumber', this.phoneFlag); + this.ruleFormRef.value!.validate((valid: boolean) => { + // 输入符合条件后才可以继续后续操作 + if (valid) { + this.setUserInfo(); + } + else { + this.isLoading.value = false; + } + }); + }); + }; + + setUserInfo = () => { + const languages = this.ruleForm.language === language.t('userCenter.language.en') ? 'en_US' : 'zh_CN'; + setUserInfoAPI( + { + language: languages, + phoneNumber: this.ruleForm.phoneNumber, + phonePrefix: this.ruleForm.type, + timezone: this.timeVal, + email: this.ruleForm.email, + userName: this.ruleForm.userName, + } + ) + .then(({data} : {data: {result: {success: boolean}}}) => { + if (data?.result?.success) { + msgTip({ + type: 'success', + message: language.t('operate.success'), + duration: 1000, + onClose: () => { + localStorage.setItem('email', window.btoa(this.ruleForm.email)); + locationItem.cookie.set('X-Jdcloud-Language', languages); + location.reload(); + this.isLoading.value = false; + } + }); + } + }) + .catch(({message}: {message: string}) => { + customTip('error', message, 800, () => this.isLoading.value = false); + }); + }; +}; + +export default FormRulesOperate; diff --git a/bmp-operation-web/src/views/personalCenter/myProfile/myProfile.vue b/bmp-operation-web/src/views/personalCenter/myProfile/myProfile.vue new file mode 100644 index 0000000..3af63e0 --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/myProfile/myProfile.vue @@ -0,0 +1,201 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/personalCenter/myProfile/page.ts b/bmp-operation-web/src/views/personalCenter/myProfile/page.ts new file mode 100644 index 0000000..835efec --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/myProfile/page.ts @@ -0,0 +1,10 @@ +const MyProfile = () => import(/* webpackChunkName: "MyProfile" */ './myProfile.vue'); + +export default { + path: '/PersonalCenter/myProfile', + name: 'MyProfile', + component: MyProfile, + meta: { + type: 'myProfile' + } +}; diff --git a/bmp-operation-web/src/views/personalCenter/navRouter.ts b/bmp-operation-web/src/views/personalCenter/navRouter.ts new file mode 100644 index 0000000..48c31c6 --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/navRouter.ts @@ -0,0 +1,48 @@ +/** + * @file + * @author +*/ + +import {language} from "utils/publicClass.ts"; + +const personalCenterNavData = (pathUrl: (arg0: string) => void, imgUrl: (arg0: string) => void) => { + return { + title: language.t('navigationBar.list.userCenter'), + defaultImg: imgUrl('userCenter'), + changeImg: imgUrl('usercCenterActive'), + path: [ + pathUrl('myProfile'), + pathUrl('securitySettings'), + pathUrl('apiKey'), + ], + otherPath: [''], + firstIndex: 'PersonalCenter', + childrenHasAdmin: true, + isChildrenF: true, + children: [ + { + title: language.t('myProfile.header.myProfile'), + defaultImg: imgUrl('userCenter'), + changeImg: imgUrl('usercCenterActive'), + path: pathUrl('myProfile'), + otherPath: [pathUrl('myProfile')] + }, + { + title: language.t('securitySettings.header.securitySettings'), + defaultImg: imgUrl('userCenter'), + changeImg: imgUrl('usercCenterActive'), + path: pathUrl('securitySettings'), + otherPath: [pathUrl('securitySettings')] + }, + { + title: language.t('apiKey.header.apiKey'), + defaultImg: imgUrl('userCenter'), + changeImg: imgUrl('usercCenterActive'), + path: pathUrl('apiKey'), + otherPath: [pathUrl('apiKey')] + } + ] + } +}; + +export default personalCenterNavData; diff --git a/bmp-operation-web/src/views/personalCenter/securitySettings/index.scss b/bmp-operation-web/src/views/personalCenter/securitySettings/index.scss new file mode 100644 index 0000000..f0ef268 --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/securitySettings/index.scss @@ -0,0 +1,69 @@ +@import '@/assets/css/communal'; + +/* 安全设置 */ +.security-setting { + margin-top: 100px; + overflow-y: auto; + padding-bottom: 30px; + + .form { + padding: 0 12px 31px; + border-bottom: 1px solid #f0f0f0; + } + + .set-confirmpassword-empty { + margin-bottom: 18px !important; + } + + .set-password-empty { + margin-bottom: 40px !important; + } + + .set-confirm-password, + .set-password { + :deep(input) { + width: 400px; + height: 36px; + border-radius: 5px; + } + + :deep(.el-form-item__label) { + margin-left: 48px; + + &::before { + display: none; + } + } + + :deep(.el-form-item__error) { + margin-top: 6px; + } + } + + .error-color-tip { + color: #f56c6c; + } + + .password-tip { + color: $color7; + } + + .user-revise { + margin-top: 32px; + margin-left: 130px; + width: 130px; + height: 36px; + border-radius: 5px; + font-size: $fontSize; + } + + .error-color-tip, + .password-tip { + font-size: $fontSize; + font-weight: $fontSmallWeight; + display: flex; + height: 17px; + align-items: center; + margin-top: 8px; + } +} \ No newline at end of file diff --git a/bmp-operation-web/src/views/personalCenter/securitySettings/page.ts b/bmp-operation-web/src/views/personalCenter/securitySettings/page.ts new file mode 100644 index 0000000..82175b1 --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/securitySettings/page.ts @@ -0,0 +1,10 @@ +const SecuritySettings = () => import(/* webpackChunkName: "SecuritySettings" */ './securitySettings.vue'); + +export default { + path: '/PersonalCenter/securitySettings', + name: 'SecuritySettings', + component: SecuritySettings, + meta: { + type: 'securitySettings' + } +}; diff --git a/bmp-operation-web/src/views/personalCenter/securitySettings/regExpReg.ts b/bmp-operation-web/src/views/personalCenter/securitySettings/regExpReg.ts new file mode 100644 index 0000000..b3342f9 --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/securitySettings/regExpReg.ts @@ -0,0 +1,114 @@ +import RegularContent from 'utils/regular.ts'; +import {language} from 'utils/publicClass.ts'; + +class RegExpCheck { + oldPasswordFlag: Ref = ref(false); + confirmPasswordFlag: Ref = ref(false); + errorTip: Ref = ref(language.t('userCenter.errorTip.password')); + colorStatus: Ref = ref(false); + newPassword: Ref = ref(''); + + /** + * 密码正则校验 + * @param {Object} _ 占位符 + * @param {string} value 输入项 + * @param {Function} callback 回调函数,返回对应状态 + */ + oldPasswordCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + this.oldPasswordFlag.value = true; + const passwordArr = [ + [ + (value: string) => !value?.length, + () => { + callback(new Error(language.t('userCenter.emptyTip.currectPassword'))); + } + ], + [ + (value: string) => (!RegularContent.passwordReg.test(value)), + () => { + callback(new Error(language.t('userCenter.errorTip.password'))); + } + ], + [ + (value: string) => value, + () => { + this.oldPasswordFlag.value = false; + callback(); + } + ] + ]; + for (const key of passwordArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + newPasswordCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + this.colorStatus.value = true; + const newPasswordArr = [ + [ + (value: string) => !value?.length, + () => { + this.errorTip.value = language.t('userCenter.emptyTip.newPassword'); + callback(new Error()); + } + ], + [ + (value: string) => (!RegularContent.passwordReg.test(value)), + () => { + this.errorTip.value = language.t('userCenter.errorTip.password'); + callback(new Error()); + } + ], + [ + (value: string) => value, + () => { + this.errorTip.value = language.t('userCenter.errorTip.password'); + this.colorStatus.value = false; + callback(); + } + ] + ]; + for (const key of newPasswordArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; + + confirmPasswordCheck: unknown = (_: {[x: string]: unknown;}, value: string, callback: (arg0?: Error | string) => void) => { + this.confirmPasswordFlag.value = true; + const confirmPasswordArr = [ + [ + (value: string) => !value?.length, + () => callback(new Error(language.t('userCenter.emptyTip.confirmPassword'))) + ], + [ + (value: string) => (!RegularContent.passwordReg.test(value)), + () => callback(new Error(language.t('userCenter.errorTip.password'))) + ], + [ + (value: string) => (value !== this.newPassword.value), + () => callback(new Error(language.t('userCenter.errorTip.password2'))) + ], + [ + (value: string) => value, + () => { + this.confirmPasswordFlag.value = false; + callback(); + } + ] + ]; + for (const key of confirmPasswordArr) { + if (key[0](value)) { + key[1](value); + break; + } + } + }; +}; + +export default RegExpCheck; diff --git a/bmp-operation-web/src/views/personalCenter/securitySettings/revisePassword.ts b/bmp-operation-web/src/views/personalCenter/securitySettings/revisePassword.ts new file mode 100644 index 0000000..6b1ba2f --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/securitySettings/revisePassword.ts @@ -0,0 +1,147 @@ +import {RuleFormRefType} from '@utils/publicType'; +import {revisePasswordAPI} from 'api/userCenter/request.ts'; +import {language} from 'utils/publicClass'; +import {encrypt, msgTip, customTip} from 'utils/index.ts'; + +class RevisePassword { + isLoading: Ref = ref(false); + // 表单ref + ruleFormRef: Ref = ref(); + // 表单项 + ruleForm: any = reactive({ + oldPassword: '', + newPassword: '', + confirmPassword: '' + }); + // 规则 + rules: any = reactive({ + oldPassword: [ + { + required: true, + trigger: 'blur', + validator: '' + } + ], + newPassword: [ // 邮箱 + { + required: true, + trigger: 'blur', + validator: '' + } + ], + confirmPassword: [ + { + required: true, + trigger: 'blur', + validator: '' + } + ] + }); + regExpCheck; + formData = [ + { + prop: 'oldPassword', + style: 'marginBottom: 20px', + label: language.t('userCenter.currectPassword'), + class: 'set-password', + flag: 'oldPasswordFlag', + formItemOtherClass: ['set-password-empty', ''], + itemOtherClass: ['', ''], + maxlength: '30', + type: 'password', + model: 'oldPassword', + placeholder: '', + showMessage: true + }, + { + prop: 'newPassword', + style: 'marginBottom: 20px', + label: language.t('userCenter.newPassword'), + class: 'set-password', + flag: 'colorStatus', + formItemOtherClass: [], + itemOtherClass: ['error-color-tip', 'password-tip'], + maxlength: '30', + type: 'password', + model: 'newPassword', + placeholder: '', + showMessage: false + }, + { + prop: 'confirmPassword', + style: '', + label: language.t('userCenter.confirmPassword'), + class: 'set-confirm-password', + flag: 'confirmPasswordFlag', + formItemOtherClass: ['set-confirmpassword-empty', ''], + itemOtherClass: ['', ''], + maxlength: '30', + type: 'password', + model: 'confirmPassword', + placeholder: '', + showMessage: true + } + ] + + constructor (regExpCheck: any) { + this.regExpCheck = regExpCheck; + this.rules['oldPassword'][0].validator = regExpCheck.oldPasswordCheck; + this.rules['newPassword'][0].validator = regExpCheck.newPasswordCheck; + this.rules['confirmPassword'][0].validator = regExpCheck.confirmPasswordCheck; + }; + + formClass = (item: {prop: string; flag: string; formItemOtherClass: string[]}, type: string) => { + return !Object.is(item.prop, type) ? this.regExpCheck[item.flag].value ? item.formItemOtherClass[0] : item.formItemOtherClass[1] : ''; + } + + customTipClass = (item: {flag: string; itemOtherClass: string[]}) => { + return this.regExpCheck[item.flag].value ? item.itemOtherClass[0] : item.itemOtherClass[1]; + } + + /** + * 获取表单ref + * @param {Object} formEl 表单的信息,可以进行清空、验证是否输入正确的操作 + */ + getFormRef = (formEl: {value: RuleFormRefType}): void => { + this.ruleFormRef.value = formEl.value; + }; + + reviseClick = async () => { + this.isLoading.value = true; + await nextTick(() => { + this.ruleFormRef.value!.validate((valid: boolean) => { + // 输入符合条件后才可以继续后续操作 + if (valid) { + this.revisePassword(); + } + else { + this.isLoading.value = false; + } + }); + }); + }; + + revisePasswordIpt = (val: any) => { + this.regExpCheck.newPassword.value = val; + }; + + revisePassword = () => { + revisePasswordAPI( + { + oldPassword: encrypt(this.ruleForm.oldPassword), + password: encrypt(this.ruleForm.newPassword) + } + ) + .then(({data} : {data: {result: {success: boolean}}}) => { + if (data?.result?.success) { + msgTip.success(language.t('operate.success')); + this.isLoading.value = false; + } + }) + .catch(({message}: {message: string}) => { + customTip('error', message, 800, () => this.isLoading.value = false) + }); + } +}; + +export default RevisePassword; diff --git a/bmp-operation-web/src/views/personalCenter/securitySettings/securitySettings.vue b/bmp-operation-web/src/views/personalCenter/securitySettings/securitySettings.vue new file mode 100644 index 0000000..dda5d1e --- /dev/null +++ b/bmp-operation-web/src/views/personalCenter/securitySettings/securitySettings.vue @@ -0,0 +1,74 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/roleManagement/list/all.ts b/bmp-operation-web/src/views/roleManagement/list/all.ts new file mode 100644 index 0000000..a071b00 --- /dev/null +++ b/bmp-operation-web/src/views/roleManagement/list/all.ts @@ -0,0 +1,14 @@ +/** + * @file + * @author +*/ + +import RoleList from './table/roleList'; +import customOperate from './custom/custom'; +import TableScrollOperate from './table/tableScroll'; + +export { + RoleList, + customOperate, + TableScrollOperate +}; diff --git a/bmp-operation-web/src/views/roleManagement/list/custom/custom.ts b/bmp-operation-web/src/views/roleManagement/list/custom/custom.ts new file mode 100644 index 0000000..7b172be --- /dev/null +++ b/bmp-operation-web/src/views/roleManagement/list/custom/custom.ts @@ -0,0 +1,10 @@ +/** + * @file + * @author +*/ + +import useCustom from 'hooks/custom/useCustom.ts'; + +const customOperate = useCustom('roleList').info; + +export default customOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/roleManagement/list/custom/customList.vue b/bmp-operation-web/src/views/roleManagement/list/custom/customList.vue new file mode 100644 index 0000000..8435cd2 --- /dev/null +++ b/bmp-operation-web/src/views/roleManagement/list/custom/customList.vue @@ -0,0 +1,8 @@ + + diff --git a/bmp-operation-web/src/views/roleManagement/list/page.ts b/bmp-operation-web/src/views/roleManagement/list/page.ts new file mode 100644 index 0000000..11de0ec --- /dev/null +++ b/bmp-operation-web/src/views/roleManagement/list/page.ts @@ -0,0 +1,10 @@ +const RoleList = () => import(/* webpackChunkName: "RoleList" */ './roleList.vue'); + +export default { + path: '/RoleManagement/roleList', + name: 'RoleList', + component: RoleList, + meta: { + type: 'roleList' + } +}; diff --git a/bmp-operation-web/src/views/roleManagement/list/roleList.vue b/bmp-operation-web/src/views/roleManagement/list/roleList.vue new file mode 100644 index 0000000..b20e246 --- /dev/null +++ b/bmp-operation-web/src/views/roleManagement/list/roleList.vue @@ -0,0 +1,52 @@ + + + + + diff --git a/bmp-operation-web/src/views/roleManagement/list/table/roleList.ts b/bmp-operation-web/src/views/roleManagement/list/table/roleList.ts new file mode 100644 index 0000000..168270f --- /dev/null +++ b/bmp-operation-web/src/views/roleManagement/list/table/roleList.ts @@ -0,0 +1,66 @@ +import {CurrencyType} from '@utils/publicType'; +import {Router, useRouter} from 'vue-router'; +import {inspectuserPurview, paginationOperate, CurrentInstance} from 'utils/publicClass.ts'; + +// 列表数据 +class RoleList { + // loading态 + isLoading: Ref = ref(true); + reactiveArr: { + tableData: CurrencyType[]; + } = reactive<{ + tableData: CurrencyType[]; + }>({ + tableData: [] // 表格数据-角色列表 + }); + instanceProxy = new CurrentInstance().proxy; + + // 构造器 + constructor () { + this.init(useRouter()); + }; + + /** + * 初始化-检查userPurview 状态 + */ + init = (router: Router) => { + const path: string = this.instanceProxy.$defInfo.routerPath('idcList'); + inspectuserPurview.inspectuserPurview() + .then(() => { + this.getRoleList(); + }) + .catch(() => { + router.push(path); + }); + }; + + /** + * 获取角色列表 + */ + getRoleList = async () => { + this.isLoading.value = true; + try { + const params = { + pageNumber: paginationOperate.pageNumber.value, + pageSize: paginationOperate.pageSize.value + }; + const roleApi = await this.instanceProxy.$roleApi.roleListAPI(params); + if (roleApi?.data?.result?.roles?.length) { + const {roles, totalCount}: {roles: CurrencyType[]; totalCount: number;} = roleApi.data.result; + this.reactiveArr.tableData = roles; + paginationOperate.total.value = totalCount; + return; + } + throw new Error(''); + } + catch { + this.reactiveArr.tableData = []; + paginationOperate.total.value = 0; + } + finally { + this.isLoading.value = false; + } + } +}; + +export default RoleList; diff --git a/bmp-operation-web/src/views/roleManagement/list/table/roleList.vue b/bmp-operation-web/src/views/roleManagement/list/table/roleList.vue new file mode 100644 index 0000000..9bbb28a --- /dev/null +++ b/bmp-operation-web/src/views/roleManagement/list/table/roleList.vue @@ -0,0 +1,93 @@ + + + diff --git a/bmp-operation-web/src/views/roleManagement/list/table/setEmpty.ts b/bmp-operation-web/src/views/roleManagement/list/table/setEmpty.ts new file mode 100644 index 0000000..775c4d8 --- /dev/null +++ b/bmp-operation-web/src/views/roleManagement/list/table/setEmpty.ts @@ -0,0 +1,41 @@ +/** + * @file + * @author +*/ + +import {language} from 'utils/publicClass.ts'; + +const p = document.createElement('p'); +const span = document.createElement('span'); + +class SetEmpty { + constructor(props: any) { + this.watchTableData(props); + onUnmounted(() => p.innerHTML = ''); + }; + + watchTableData = (props: any) => { + watch(() => props?.roleList?.reactiveArr.tableData, (newValue) => { + if (!newValue?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.innerHTML= ''; + }, {deep: true}) + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + const customText = document.querySelector('.role-list .el-scrollbar__view'); + if (!customText) return; + ai!.innerHTML = ''; + p.className = 'custom-tip-count'; + customText.appendChild(p) + p.appendChild(span) + span.innerHTML = `${language.t('table.empty')}`; + }; +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/roleManagement/list/table/tableScroll.ts b/bmp-operation-web/src/views/roleManagement/list/table/tableScroll.ts new file mode 100644 index 0000000..3815a2e --- /dev/null +++ b/bmp-operation-web/src/views/roleManagement/list/table/tableScroll.ts @@ -0,0 +1,25 @@ +import {ScrollOperate} from 'utils/publicClass.ts'; +import {HeightType3} from '@utils/publicType'; + +class TableScrollOperate { + tableMaxHeight: Ref = ref(0); + headerTitle: Ref = ref({offsetHeight: 0, scrollHeight: 0}); + operate: Ref = ref({offsetHeight: 0, scrollHeight: 0}); + + constructor() { + onMounted(() => { + const countHeight = this.headerTitle.value.offsetHeight + this.headerTitle.value.scrollHeight + this.operate.value.offsetHeight + this.operate.value.scrollHeight + 50; + new ScrollOperate(countHeight, this.tableMaxHeight); + }); + }; + + getHeaderRef = (val: {value: HeightType3;}) => { + this.headerTitle.value = val.value; + }; + + getOperateRef = (val: {value: HeightType3;})=> { + this.operate.value = val.value; + }; +}; + +export default TableScrollOperate; diff --git a/bmp-operation-web/src/views/roleManagement/navRouter.ts b/bmp-operation-web/src/views/roleManagement/navRouter.ts new file mode 100644 index 0000000..5857037 --- /dev/null +++ b/bmp-operation-web/src/views/roleManagement/navRouter.ts @@ -0,0 +1,20 @@ +/** + * @file + * @author +*/ + +import {language} from "utils/publicClass.ts"; + +const roleNavData = (pathUrl: (arg0: string) => void, imgUrl: (arg0: string) => void) => { + return { + title: language.t('navigationBar.list.roleManagement'), + defaultImg: imgUrl('roleDefault'), + changeImg: imgUrl('role'), + path: pathUrl('role'), + otherPath: [pathUrl('role')], + hasAdmin: true, + isF: true, + } +}; + +export default roleNavData; \ No newline at end of file diff --git a/bmp-operation-web/src/views/userManagement/list/custom/custom.ts b/bmp-operation-web/src/views/userManagement/list/custom/custom.ts new file mode 100644 index 0000000..d3d7acb --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/custom/custom.ts @@ -0,0 +1,10 @@ +/** + * @file + * @author +*/ + +import useCustom from 'hooks/custom/useCustom.ts'; + +const customOperate = useCustom('userList').info; + +export default customOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/userManagement/list/custom/customList.vue b/bmp-operation-web/src/views/userManagement/list/custom/customList.vue new file mode 100644 index 0000000..4ef4d90 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/custom/customList.vue @@ -0,0 +1,8 @@ + + diff --git a/bmp-operation-web/src/views/userManagement/list/export/export.ts b/bmp-operation-web/src/views/userManagement/list/export/export.ts new file mode 100644 index 0000000..b661dc3 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/export/export.ts @@ -0,0 +1,50 @@ +// import {userListExportAPI} from 'api/user/request.ts'; +import {ExportDataOperate, CurrentInstance} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; + +class ExportFilterData { + // 是否导出数据 + hasExportData: Ref = ref(true); + filterEmptyInfo: { + deleteEmtpyData(arg0?: {}): Function; + } = store.filterEmpty; + // list: any; + search: { + searchParams: {} + }; + filter: { + filterParams: {} + }; + proxy = new CurrentInstance().proxy; + + constructor(search: { + searchParams: {} + }, filter: { + filterParams: {} + }) { + // this.list = list; + this.search = search; + this.filter = filter; + }; + + exportData = (that: never) => { + new ExportDataOperate(this.proxy.$userApi.userListExportAPI, {}, 'user_list').exportData(that); + }; + + /** + * 参数处理 + */ + paramsProcessing = (that: never) => { + this.filterEmptyInfo.deleteEmtpyData({...this.filter.filterParams, ...this.search.searchParams}); + new ExportDataOperate(this.proxy.$userApi.userListExportAPI, { + ...this.search.searchParams, + ...this.filter.filterParams + }, 'user_list').exportData(that); + } +}; + +export { + ExportFilterData, + ExportDataOperate, + // userListExportAPI +}; diff --git a/bmp-operation-web/src/views/userManagement/list/export/exportData.vue b/bmp-operation-web/src/views/userManagement/list/export/exportData.vue new file mode 100644 index 0000000..2b9f088 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/export/exportData.vue @@ -0,0 +1,23 @@ + + + diff --git a/bmp-operation-web/src/views/userManagement/list/methods.ts b/bmp-operation-web/src/views/userManagement/list/methods.ts new file mode 100644 index 0000000..15e3b28 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/methods.ts @@ -0,0 +1,16 @@ +/** + * @file + * @author +*/ + +// 创建一个 require 上下文,它会匹配 +const requireAll = (requireContext: T) => { + // keys 返回字典的所有的key + return requireContext.keys().map(requireContext); +} + +const methods = [ + ...requireAll(require.context('./', true, /^((?!module|methods|page|typeManagement|pagination|filterStyle|setEmpty).)*\.ts$/)) +]; + +export default methods; diff --git a/bmp-operation-web/src/views/userManagement/list/module.ts b/bmp-operation-web/src/views/userManagement/list/module.ts new file mode 100644 index 0000000..1c9d7fb --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/module.ts @@ -0,0 +1,16 @@ +/** + * @file + * @author +*/ + +const requireAll = (requireContext: T) => { + // keys 返回字典的所有的key + return requireContext.keys().map(requireContext); +} + +// 将两个上下文合并为一个数组 +const pluginComp = [ + ...requireAll(require.context('./', true, /^((?!userList).)*\.vue$/)) +]; + +export default pluginComp; diff --git a/bmp-operation-web/src/views/userManagement/list/page.ts b/bmp-operation-web/src/views/userManagement/list/page.ts new file mode 100644 index 0000000..6a88905 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/page.ts @@ -0,0 +1,10 @@ +const UserList = () => import(/* webpackChunkName: "UserList" */ './userList.vue'); + +export default { + path: '/UserManagement/userList', + name: 'UserList', + component: UserList, + meta: { + type: 'userList' + } +}; diff --git a/bmp-operation-web/src/views/userManagement/list/pagination/pagination.ts b/bmp-operation-web/src/views/userManagement/list/pagination/pagination.ts new file mode 100644 index 0000000..0ea997d --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/pagination/pagination.ts @@ -0,0 +1,30 @@ +import {paginationOperate} from 'utils/publicClass.ts'; + +/** + * 分页监听 +*/ +class PaginationWatch { + // 构造器 + constructor (props: any) { + this.watchSizeNumber(props); + }; + + /** + * 监听分页页数、条数变化 + */ + watchSizeNumber = (props: any) => { + watch(() => [ + paginationOperate.pageSize.value, + paginationOperate.pageNumber.value + ], (_: boolean[]): void => { + if (paginationOperate.routerChange.value) return; + if (props.search.reactiveArr.searchParams?.userName) { + props.userList.requestOperate(props.search.reactiveArr.searchParams, 'search'); + return; + } + props.userList.requestOperate(props.filter.reactiveArr.filterParams, 'filter'); + }); + }; +}; + +export default PaginationWatch; diff --git a/bmp-operation-web/src/views/userManagement/list/pagination/pagination.vue b/bmp-operation-web/src/views/userManagement/list/pagination/pagination.vue new file mode 100644 index 0000000..7e61c54 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/pagination/pagination.vue @@ -0,0 +1,23 @@ + + + diff --git a/bmp-operation-web/src/views/userManagement/list/search/search.ts b/bmp-operation-web/src/views/userManagement/list/search/search.ts new file mode 100644 index 0000000..5aca895 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/search/search.ts @@ -0,0 +1,72 @@ +import {SearchArrType} from '../typeManagement'; +import {language, paginationOperate} from 'utils/publicClass.ts'; + +class SearchOperate { + hasClear: Ref = ref(false); + // 搜索框值 + selectVal: Ref = ref(0); + userList: { + requestOperate(arg0: {}, arg1: string): void; + }; + reactiveArr: SearchArrType = reactive({ + searchParams: {}, + selectOption: [ + { + value: 0, + label: language.t('userList.search.condition.userName') + } + ] + }); + + constructor(userList: { requestOperate(arg0: {}, arg1: string): void; }) { + this.userList = userList; + }; + + iptValue = (enterValue: string) => { + this.reactiveArr.searchParams = {userName: enterValue}; + }; + + + /** + * input 输入框 点击搜索按钮或者回车触发 + * @param {string} enterValueIpt 输入框输入的值 + */ + enterValueIpt = (enterValueIpt: string): void => { + this.reactiveArr.searchParams = {userName: enterValueIpt}; + this.request(); + }; + + /** + * 搜索框筛选 + * @param {number} val 搜索框切换的搜索key + * @return {number} selectVal 对应的key + */ + changeSelect = (val: number): number => { + return this.selectVal.value = val; + }; + + clearClick = (val: string) => { + if (!val) { + this.selectChange(); + } + }; + + selectChange = () => { + const {userName} :{userName?: string;} = this.reactiveArr.searchParams; + if (userName) { + this.reactiveArr.searchParams = {}; + this.request(); + } + }; + + request = () => { + if (paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.userList.requestOperate(this.reactiveArr.searchParams, 'search'); + }; + +}; + +export default SearchOperate; diff --git a/bmp-operation-web/src/views/userManagement/list/table/filterStyle.ts b/bmp-operation-web/src/views/userManagement/list/table/filterStyle.ts new file mode 100644 index 0000000..f8c5ac8 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/table/filterStyle.ts @@ -0,0 +1,120 @@ +class FilterStyleOperate { + classNameData = [ + { + name: 'def-type-status12', + type: 'role' + } + ]; + filterStatus: any = reactive({ + role: false + }) + + constructor (props: any) { + onMounted(() => { + nextTick(() => { + this.customFilter(props); + }) + this.watchSearchTip(props); + this.watchFilter(props); + }) + }; + + watchSearchTip = (props: any) => { + watch(() => + props.userList.searchTip, (newValue) => { + if (!newValue.value) { + for (let index in this.filterStatus) { + this.filterStatus[index] = false; + } + } + else { + this.setFilterStatus(props.filterOperates.reactiveArr.filterParams); + } + }, { + deep: true + }); + }; + + watchFilter = (props: any) => { + watch(() => props.filterOperates.reactiveArr.filterParams, (newValue) => { + this.setFilterStatus(newValue); + }, {deep: true}) + }; + + setFilterStatus = (params: any) => { + this.classNameData.forEach((item) => { + if (['', undefined].includes(params[item.type])) { + this.filterStatus[item.type] = false; + return; + } + this.filterStatus[item.type] = true; + }) + }; + + customFilter = (props: any) => { + let filterName: HTMLElement | null; + let filterOpt: HTMLElement | null; + const that = this; + this.classNameData.forEach((item) => { + filterName = document.querySelector(`.${item.name} > .cell`); + filterOpt = document.querySelector(`.${item.name} > .cell > .el-table__column-filter-trigger`) + filterName?.addEventListener('click', (event) => { + event.stopPropagation(); + // this.filterStatus[item.type] = false; + for (let index in this.filterStatus) { + this.filterStatus[index] = false; + } + }) + filterOpt?.addEventListener('click', (event) => { + event.stopPropagation(); + this.filterStatus[item.type] = !this.filterStatus[item.type]; + }); + const filterOtherRegion = document.querySelectorAll('.el-table-filter'); + filterOtherRegion.forEach((_, index) => { + filterOtherRegion[index]?.addEventListener('click', (event) => { + event.stopPropagation(); + for (let index in this.filterStatus) { + for (const key of this.classNameData) { + if (index === key.type && props.filterOperates.reactiveArr.filterParams[key.type]) { + (this.filterStatus[`${index}` as keyof typeof that.filterStatus] as boolean) = true; + } + } + } + }) + }) + let newType = []; + document.addEventListener('click', (event) => { + event.stopPropagation(); + newType = []; + newType.push(item.type); + newType.forEach((ite) => { + this.filterDispose(ite, props); + }) + }) + }) + }; + + filterDispose = (type: string, props: any) => { + const filterVal = props.filterOperates.reactiveArr.filterParams; + if (props.userList.searchTip.value) { + for (let key in filterVal) { + if (key === type) { + this.filterStatus[key] = true; + } + else { + if (this.filterStatus[type] && Object.keys(filterVal).length > 1) { + this.filterStatus[type] = !this.filterStatus[type]; + } + else { + this.filterStatus[type] = false; + } + } + } + } + else { + this.filterStatus[type] = false; + } + } +}; + +export default FilterStyleOperate; diff --git a/bmp-operation-web/src/views/userManagement/list/table/refreshReset.ts b/bmp-operation-web/src/views/userManagement/list/table/refreshReset.ts new file mode 100644 index 0000000..461586b --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/table/refreshReset.ts @@ -0,0 +1,65 @@ +/** + * @file + * @author +*/ + +import {TableRef} from '../typeManagement'; + +interface ClassParamsType { + filterOperates: { + // filterEmptyInfo: { + // deleteEmtpyData: void; + // } + reactiveArr: { + filterParams: {roleId: string;}; + }; + tableRef: TableRef; + }; + searchOperate: { + hasClear: { + value: boolean; + }; + reactiveArr: { + searchParams: {}; + }; + }; +}; + +interface ListType { + reactiveArr: { tableData: string | unknown[]; }; + getUserList: () => void; sessionId: { value: string; }; + resetData: (arg0: { + hasClear: { + value: boolean; + }; + reactiveArr: { + searchParams: {}; + }; + }) => void; +}; + +const refreshResetOperate = (list: T, filter: K, search: Z) => { + const refresh = () => { + if (!list.reactiveArr.tableData.length) { + reset(); + return; + } + list.getUserList(); + }; + + const reset = () => { + list.sessionId.value = '' + filter.reactiveArr.filterParams = {roleId: ''}; + search.hasClear.value = true; + search.reactiveArr.searchParams = {userName: ''}; + filter.tableRef?.value?.clearFilter(); + list.resetData(search); + }; + + return { + refresh, + reset + }; +}; + +export default refreshResetOperate; diff --git a/bmp-operation-web/src/views/userManagement/list/table/setEmpty.ts b/bmp-operation-web/src/views/userManagement/list/table/setEmpty.ts new file mode 100644 index 0000000..64b2cc3 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/table/setEmpty.ts @@ -0,0 +1,64 @@ +/** + * @file + * @author +*/ + +import {language} from 'utils/publicClass.ts'; + +const p = document.createElement('p'); + +interface PropsType { + userList: { + reactiveArr: { + tableData: [] + } + } +} + +class SetEmpty { + emitValue: Function; + + constructor(props: PropsType, emitValue: Function) { + this.emitValue = emitValue; + this.watchTableData(props); + onUnmounted(() => p.innerHTML = ''); + }; + + watchTableData = (props: PropsType) => { + watch(() => props?.userList?.reactiveArr.tableData, (newValue) => { + if (!newValue?.length) { + nextTick(() => { + this.textEmpty(); + }) + return; + } + p.innerHTML= ''; + }, {deep: true}) + }; + + textEmpty = () => { + const ai = document.querySelector('.el-table__empty-text'); + ai!.innerHTML = ''; + const customText = document.querySelector('.user-list .el-scrollbar__view'); + if (!customText) return; + const str = ` + + ${language.t('table.empty')},${language.t('table.tip')} + + + ${language.t('userList.operate.addUser')} + + ` + const parser = new DOMParser(); + const doc = parser.parseFromString(str, 'text/html'); + p.className = 'custom-tip-count'; + p.innerHTML = doc.body.innerHTML; + customText.appendChild(p) + const clickOpt = document.querySelector('.user-list .custom-tip-count .empty-text'); + clickOpt!.addEventListener('click', () => { + this.emitValue('empty-click'); + }); + }; +}; + +export default SetEmpty; diff --git a/bmp-operation-web/src/views/userManagement/list/table/tableFilter.ts b/bmp-operation-web/src/views/userManagement/list/table/tableFilter.ts new file mode 100644 index 0000000..2c91f66 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/table/tableFilter.ts @@ -0,0 +1,94 @@ +import UserStaticData from 'staticData/user/index.ts'; +import {paginationOperate} from 'utils/publicClass.ts'; +import {CurrencyType2, CurrencyType3} from '@utils/publicType'; +import {TableRef, OSStoreType, UserListType, ReactiveArrType, FilterParamsType} from '../typeManagement'; +import store from 'store/index.ts'; + +class FilterOperate { + filterEmptyInfo: { // 公共store + filterParams( + arg0: CurrencyType2, + arg1: {roleId: OSStoreType[]}, + arg2: ReactiveArrType, + arg3: FilterParamsType + ): Promise; + deleteEmtpyData(arg0: FilterParamsType): unknown; + } = store.filterEmpty; + tableRef: TableRef = {value: {clearFilter(): void{}}}; + // store库存储的oss数据类 + ossStore: {roleId: OSStoreType[]} = {roleId: UserStaticData.userFilterData}; + // 复杂数据类型 + reactiveArr: { + filterParams: FilterParamsType; + } = reactive<{ + filterParams: FilterParamsType; + }>({ + filterParams: { + roleId: '' // 角色id筛选 + } + }); + userList: UserListType; + + constructor (list: UserListType) { + this.reactiveArr.filterParams.roleId = list.sessionId?.value || ''; + this.userList = list; + }; + + + /** + * 获取表格ref + * @param {Object} tableEl 表格信息 + */ + getTableRef = (tableEl: CurrencyType3): void => { + this.tableRef = tableEl; + }; + + /** + * 用户名筛选 + * @param {number} value 当前选中的value值 + * @param {Object} row 当前选中的这一项 + * @return {boolean} xxx 返回对应信息 + */ + userNameFilter = (): boolean => { + // return row.roleName === this.ossStore?.roleId[value - 1]?.text; + // value: number, row: {roleName: string} + return true; + }; + + /** + * 点击【筛选操作】 + * @param {Object} filter 当前点击项 + */ + filterChange = (filter: CurrencyType2) => { + const filterParams: FilterParamsType = { + roleId: 'roleId' + }; + // 筛选完成后重新请求接口,页面赋值为1 + this.filterEmptyInfo.filterParams(filter, this.ossStore, this.reactiveArr, filterParams) + .then(() => { + this.filterOperate(this.reactiveArr.filterParams, 'filter'); + }) + .catch(() => { + this.reactiveArr.filterParams = {roleId: ''}; + this.tableRef?.value?.clearFilter(); + this.filterEmptyInfo.deleteEmtpyData(this.reactiveArr.filterParams); + this.filterOperate(this.reactiveArr.filterParams, 'filter'); + }); + }; + + /** + * 筛选操作时,页数重置、数据赋值,请求接口 + * @param {Object} filter 当前筛选的数据 + * @param {string} filter.roleId roleId筛选 + */ + filterOperate = (filter: {roleId: string;}, type: string = '') => { + if (Object.is(type, 'filter') && paginationOperate.pageNumber.value > 1) { + paginationOperate.pageNumber.value = 1; + return; + } + this.reactiveArr.filterParams = filter; + this.userList?.requestOperate(filter, 'filter'); + }; +}; + +export default FilterOperate; diff --git a/bmp-operation-web/src/views/userManagement/list/table/tableList.vue b/bmp-operation-web/src/views/userManagement/list/table/tableList.vue new file mode 100644 index 0000000..ce917b8 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/table/tableList.vue @@ -0,0 +1,153 @@ + + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/userManagement/list/table/tableScroll.ts b/bmp-operation-web/src/views/userManagement/list/table/tableScroll.ts new file mode 100644 index 0000000..15b738b --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/table/tableScroll.ts @@ -0,0 +1,97 @@ +import {tableScroll} from 'utils/index.ts'; +import {HeightType2, HeightType3} from '@utils/publicType'; +import {ClassParamsType} from '../typeManagement'; +import {TimerOperate} from 'utils/publicClass.ts'; +import store from 'store/index.ts'; + +class TableScrollOperate extends TimerOperate { + searchTipHeight: number = 13; + fixedHeight: Ref = ref(0); + tableMaxHeight: Ref = ref(0); + status: boolean = false; + filters: ClassParamsType['filterOperates']; + search: ClassParamsType['searchOperate']; + headerTitle: Ref = ref({offsetHeight: 0, scrollHeight: 0}); + operate: Ref = ref({offsetHeight: 0, scrollHeight: 0}); + operateBtn: Ref = ref({offsetHeight: 0}); + searchTip: { + value: boolean; + } + constructor(filter: ClassParamsType['filterOperates'], search: ClassParamsType['searchOperate'], searchTip: {value: boolean;}) { + super(); + this.filters = filter; + this.search = search; + this.searchTip = searchTip; + onMounted(async() => { + this.#setScroll(this.#setHeight(), this.tableMaxHeight); + this.#onResize(this.tableMaxHeight); + await this.#watchNavBar(); + }); + this.#watchFilterSeach(); + + onUnmounted(() => { + clearTimeout(this.timer); + }) + }; + + #watchFilterSeach = () => { + watch(() => [ + this.filters.reactiveArr.filterParams, + this.search.reactiveArr.searchParams, + this.searchTip + ], (newValue: any) => { + if (newValue[2].value) { + this.#setScroll(this.fixedHeight.value, this.tableMaxHeight); + } + }, {deep: true}) + }; + + #watchNavBar = () => { + watch(() => store.navigationBarStatus.hasNavigationBar, (_: boolean) => { + this.timer = setTimeout(() => { + this.#setScroll(this.#setHeight(), this.tableMaxHeight); + }, 200) + }); + }; + + #onResize = (tableMaxHeight: {value: number}) => { + window.onresize = () => { + this.#setScroll(this.#setHeight(), tableMaxHeight); + }; + }; + + #setHeight = () => { + const header = this.headerTitle.value; + const operate = this.operate.value; + this.fixedHeight.value = header.offsetHeight * 2.9 + operate.offsetHeight + this.operateBtn.value.offsetHeight; + const countHeight: number = this.fixedHeight.value; + return countHeight; + }; + + #setScroll = (countHeight: number, tableMaxHeight: {value: number}) => { + const params = { + ...this.filters.reactiveArr.filterParams, + ...this.search.reactiveArr.searchParams + } + if (Object.values(params).some((item: string) => item !== '')) { + tableScroll(countHeight + this.searchTipHeight, tableMaxHeight); + return; + } + tableScroll(countHeight, tableMaxHeight); + }; + + getBtnRef = (val: {value: HeightType2}) => { + this.operateBtn.value = val.value; + }; + + + getHeaderRef = (val: {value: HeightType3;}) => { + this.headerTitle.value = val.value; + }; + + getOperateRef = (val: {value: HeightType3;})=> { + this.operate.value = val.value; + }; +}; + +export default TableScrollOperate; diff --git a/bmp-operation-web/src/views/userManagement/list/table/unmount.ts b/bmp-operation-web/src/views/userManagement/list/table/unmount.ts new file mode 100644 index 0000000..7078fb3 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/table/unmount.ts @@ -0,0 +1,9 @@ +const unmountOperate = () => { + // 销毁的生命周期 + onUnmounted(async () => { + const roleId = sessionStorage?.getItem('roleId') || ''; + await roleId && sessionStorage.removeItem('roleId'); + }); +}; + +export default unmountOperate; diff --git a/bmp-operation-web/src/views/userManagement/list/table/userList.ts b/bmp-operation-web/src/views/userManagement/list/table/userList.ts new file mode 100644 index 0000000..5b12e14 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/table/userList.ts @@ -0,0 +1,233 @@ +/** + * @file + * @author +*/ + +import {AxiosError} from 'axios'; +import {decrypt, msgTip} from 'utils/index.ts'; +import {DataListType, ParamsType, EditUserType} from '../typeManagement'; +import {language, inspectuserPurview, paginationOperate, CurrentInstance} from 'utils/publicClass.ts'; +import router from 'router/index.ts'; +import UserStaticData from 'staticData/user/index.ts'; + +/** + * 请求列表,获取数据 +*/ +class UserList { + searchTip: Ref = ref(false); + sessionId: Ref = ref(''); /// query id + isLoading: Ref = ref(true); // loading态 + // 复杂数据类型 + reactiveArr: DataListType = reactive({ + tableData: [] // 表格数据-用户列表 + }); + type: string = ''; + params1: {roleId: string} = {roleId: ''}; + params2: {userName: string} = {userName: ''}; + searchOperate: {hasClear: {value: boolean}} = {hasClear: {value: false}}; + instanceProxy = new CurrentInstance().proxy; + templateData = [ + { + prop: 'userName', + minWidth: '120', + customInfo: 'userName', + fixed: 'left', + label: language.t('userList.label.userName'), + toolTip: 'userNameTip', + filterPlacement: '', + }, + { + prop: 'userId', + minWidth: '260', + customInfo: 'userId', + fixed: false, + label: language.t('userList.label.userId'), + toolTip: 'userIdTip', + filterPlacement: '' + }, + { + prop: 'roleName', + minWidth: '120', + customInfo: 'roleName', + fixed: false, + label: language.t('userList.label.role'), + toolTip: '', + filterPlacement: 'bottom-end', + key: 'roleId', + columnKey: 'roleId', + className: true, + filterStatus: 'role', + filterClass: '12', + filters: 'roleId', + filterMethod: 'userNameFilter', + marginRight: '17px', + setTextClass: false + }, + { + prop: 'projectCount', + minWidth: '80', + customInfo: 'projectCount', + fixed: false, + label: language.t('userList.label.itemNum'), + toolTip: '', + setTextClass: false + }, + { + prop: 'phoneNumber', + minWidth: '130', + customInfo: 'phone', + fixed: false, + label: language.t('userList.label.cellPhone'), + toolTip: 'phoneNumberTip', + }, + { + prop: 'email', + minWidth: '130', + customInfo: 'email', + fixed: false, + label: language.t('userList.label.email'), + toolTip: 'emailTip', + }, + { + prop: 'description', + minWidth: '160', + customInfo: 'remark', + fixed: false, + label: language.t('userList.label.desc'), + toolTip: 'descriptionTip', + }, + { + prop: 'createdTime', + minWidth: '160', + customInfo: 'createTime', + fixed: false, + label: language.t('userList.label.createTime'), + toolTip: '', + setTextClass: false + }, + { + prop: 'operate', + minWidth: '130', + customInfo: 'operate', + fixed: 'right', + label: language.t('userList.label.operate.name'), + toolTip: '' + } + ]; + + // 构造器 + constructor() { + const id: string | null = sessionStorage?.getItem('roleId'); + const encryptDecrypt: string[] = this.instanceProxy.$defInfo.encryptDecrypt(1) + this.sessionId.value = id && decrypt(id, encryptDecrypt[0], encryptDecrypt[1]); + this.init(); + }; + + /** + * 初始化-检查userPurview 状态 + */ + init = () => { + const path: string = this.instanceProxy.$defInfo.routerPath('idcList'); + inspectuserPurview.inspectuserPurview() + .then(() => { + this.getUserList(); + }) + .catch(() => { + router.push(path) + }); + }; + + /** + * 请求统一操作 + */ + requestOperate = (params: T, type: string) => { + this.type = type; + if (Object.is(type, 'search')) this.params2 = params; + if (Object.is(type, 'filter')) this.params1 = params; + this.getUserList(); + }; + + resetData = (searchOperate: {hasClear: {value: boolean}}) => { + this.searchOperate = searchOperate; + this.searchOperate.hasClear.value = true; + this.params1 = {roleId: ''}; + this.params2 = {userName: ''}; + this.getUserList(); + } + /** + * 请求用户列表接口 + */ + getUserList = async () => { + this.isLoading.value = true; + // 搜索id + const roleId: string = this.params1?.roleId; + // 初始参数 + let param: ParamsType | {isAll: string;} = { + pageNumber: paginationOperate.pageNumber.value, + pageSize: paginationOperate.pageSize.value + }; + // 如果是从角色进入,要进行数据筛选 + if (this.sessionId?.value || roleId) { + if (roleId) { + param = {...param, roleId} + } + else { + param = {...param, roleId: this.sessionId.value}; + } + } + if (!this.params1.roleId?.length) { + Reflect.deleteProperty(this.params1, 'roleId') + } + if (!this.params2?.userName?.length) { + Reflect.deleteProperty(this.params2, 'userName') + } + const params = { + ...param, + ...this.params1, + ...this.params2 + }; + try { + const userApi = await this.instanceProxy.$userApi.userListAPI(params); + if (userApi?.data?.result?.users?.length) { + // 解构赋值 + const {users, totalCount} : {users: EditUserType[]; totalCount: number;} = userApi.data.result; + + this.setList(users); + paginationOperate.total.value = totalCount; + return; + } + throw new Error(''); + } + catch (e) { + // 异常处理 + this.reactiveArr.tableData = []; + paginationOperate.total.value = 0; + const err = e as AxiosError; + err.message && msgTip.error(err.message); + } + finally { + // sessionStorage.removeItem('roleId'); + this.searchOperate.hasClear.value = false; + this.isLoading.value = false; + this.searchTip.value = Object.keys(params).length > 2; + } + }; + + setList = (users: EditUserType[], type: string = 'initDefault') => { + const newVal: EditUserType[] = users?.map((item: EditUserType, index: number) => { + UserStaticData.userTipData.forEach((t: string) => { + Object.assign(item, {[`${t}${index}`]: {showTooltip: false}}) + }); + return { + ...item, + prefix: item.phonePrefix + } + }); + this.reactiveArr.tableData = newVal; + if (type === 'delete') { + paginationOperate.total.value = paginationOperate.total.value - 1; + } + } +}; + +export default UserList; diff --git a/bmp-operation-web/src/views/userManagement/list/typeManagement.ts b/bmp-operation-web/src/views/userManagement/list/typeManagement.ts new file mode 100644 index 0000000..4a6bc03 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/typeManagement.ts @@ -0,0 +1,132 @@ +import {PaginationType, LocationQueryValue, CurrencyType} from '@utils/publicType'; + +// 筛选参数类 +type FilterParamsType = {roleId: string;}; + +type TableRef = { + [x: string]: unknown; + value?: { + clearFilter(): unknown; + }; +}; + +/** + * oss store参数类 +*/ +type OSStoreType = { + filterParams: string; + showInfo: string; + text: string; + value: number; +}; + +/** + * 参数类 +*/ +type ParamsType = PaginationType + | PaginationType & Partial + | PaginationType & Partial<{userName: string | undefined | LocationQueryValue[]}> + | PaginationType & Partial & Partial<{userName: string | undefined | LocationQueryValue[]}>; + +type key = 'userName' | 'roleId' | 'roleName' | 'userId' | 'phoneNumber' | 'email'; +/** + * 用户公用类 +*/ +type UserType = { + [k in key]: string; +}; + +// 删除用户类 +type DeleteUserType = Required; + +/** + * 编辑用户类 +*/ +interface EditUserType extends Required { + [x: string]: string | boolean; + defaultProjectId: string; + showTooltip: boolean; + phonePrefix: string; + description: string; +}; + +// 用户数据类 +interface UsersDataType extends Required{}; + +/** + * 复杂数据类型类 +*/ +interface ReactiveArrType { + filterParams?: FilterParamsType; + tableData?: EditUserType[]; +}; + +// 数据列表类 +interface DataListType {tableData: EditUserType[];}; + +type DataOperateType = {requestOperate(arg0: CurrencyType, arg1: string): void;}; + +interface ClassParamsType { + filterOperates: { + filterEmptyInfo: { + deleteEmtpyData: void; + } + reactiveArr: { + filterParams: {roleId: string;}; + }; + tableRef: TableRef; + }; + searchOperate: { + hasClear: { + value: boolean; + }; + reactiveArr: { + searchParams: {userName: string}; + }; + }, + userList: { + reactiveArr: { + tableData: {length: number}; + }; + sessionId: {value: string}; + resetData(arg0: ClassParamsType['searchOperate']): () => void; + requestOperate(): () => void; + getUserList(): () => void; + }; + refreshOperate: { + reset(): void; + } +}; + +interface UserListType { + sessionId: { + value: string; + }; + requestOperate(arg1: FilterParamsType, arg2: string): void; +}; + +interface SearchArrType { + searchParams: { + userName?: string; + }; + selectOption: { + value: number; + label: string; + }[]; +}; + +export { + TableRef, + ParamsType, + OSStoreType, + DataListType, + EditUserType, + UserListType, + SearchArrType, + UsersDataType, + DeleteUserType, + ClassParamsType, + DataOperateType, + ReactiveArrType, + FilterParamsType +}; diff --git a/bmp-operation-web/src/views/userManagement/list/userAdd/userAdd.ts b/bmp-operation-web/src/views/userManagement/list/userAdd/userAdd.ts new file mode 100644 index 0000000..b40a9f9 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/userAdd/userAdd.ts @@ -0,0 +1,54 @@ +/** + * @file + * @author +*/ + +import {ClassParamsType} from '../typeManagement'; +import {StatusParamsType, StatusType} from '@utils/publicType'; + +interface DataType { + addUserDialog: Ref; + refreshReset: ClassParamsType['refreshOperate']; +}; + +const addUserInfo = (refreshReset: ClassParamsType['refreshOperate']) => { + const data: DataType = { + // 添加用户组件弹窗状态 + addUserDialog: ref(false), + refreshReset + }; + + /** + * 点击添加用户按钮 + * @return {boolean} xxx 添加用户组件蒙层状态 + */ + const addUserClick: StatusType<() => boolean> = (): boolean =>{ + return data.addUserDialog.value = true; + }; + + /** + * 添加用户取消事件 + * @param {boolean} status 添加用户弹窗状态 + * @return {boolean} xxx 点击操作后的弹窗状态 + */ + const addUserCancel: StatusParamsType<(status: boolean) => boolean> = (status: boolean): boolean => { + return data.addUserDialog.value = status; + }; + + /** + * 添加用户操作后成功的返回 + */ + const addUserSure = () => { + // 清空搜索值,确保可以看到最新的值 + data.refreshReset.reset(); + }; + + return { + ...data, + addUserSure, + addUserClick, + addUserCancel + } +}; + +export default addUserInfo; diff --git a/bmp-operation-web/src/views/userManagement/list/userAdd/userAdd.vue b/bmp-operation-web/src/views/userManagement/list/userAdd/userAdd.vue new file mode 100644 index 0000000..6c07e96 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/userAdd/userAdd.vue @@ -0,0 +1,19 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/userManagement/list/userDelete/userDelete.ts b/bmp-operation-web/src/views/userManagement/list/userDelete/userDelete.ts new file mode 100644 index 0000000..9d98943 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/userDelete/userDelete.ts @@ -0,0 +1,77 @@ +import {StatusParamsType} from '@utils/publicType'; +import {paginationOperate} from 'utils/publicClass.ts'; +import {DeleteUserType, EditUserType} from '../typeManagement'; + +interface DataType { + listData: {[x: string]: {}}; + deleteUserDiaLog: Ref; +}; + +const deleteOperate = (userList: T, refreshReset: K) => { + const data: DataType = { + listData: reactive<{[x: string]: {}}>({}), + // 删除用户组件弹窗状态 + deleteUserDiaLog: ref(false) + }; + + /** + * 点击删除用户操作 + * @param {Object} item 当前点击的这一项 + * @return {boolean} addUserDialog.value 删除用户组件弹窗状态 + */ + const deleteUserOperate = async (item: DeleteUserType): Promise => { + const {userName, roleName, phoneNumber, userId, email}: DeleteUserType = item; + await nextTick(() => { + data.listData.value = { + userName, + roleName, + phoneNumber, + userId, + email + }; + }); + return data.deleteUserDiaLog.value = !data.deleteUserDiaLog.value; + }; + + /** + * 删除操作取消事件 + */ + const deleteCancel: StatusParamsType <(status: boolean) => boolean> = (status: boolean): boolean => { + return data.deleteUserDiaLog.value = status; + }; + + /** + * 删除成功的回调 + */ + const deleteSure = () => { + if (paginationOperate.pageNumber.value > 1 && !userList.reactiveArr.tableData.length) { + paginationOperate.pageNumber.value = paginationOperate.pageNumber.value - 1; + return; + } + const data = [ + [ + (len: number) => len === 1, + () => refreshReset.reset() + ], + [ + (len: number) => len !== 1, + () => userList.getUserList() + ] + ]; + for (const key of data) { + if (key[0](userList.reactiveArr.tableData.length)) { + key[1](userList.reactiveArr.tableData.length); + break; + } + } + }; + + return { + ...data, + deleteUserOperate, + deleteCancel, + deleteSure, + } +}; + +export default deleteOperate; diff --git a/bmp-operation-web/src/views/userManagement/list/userDelete/userDelete.vue b/bmp-operation-web/src/views/userManagement/list/userDelete/userDelete.vue new file mode 100644 index 0000000..8979dd4 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/userDelete/userDelete.vue @@ -0,0 +1,20 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/userManagement/list/userEdit/userEdit.ts b/bmp-operation-web/src/views/userManagement/list/userEdit/userEdit.ts new file mode 100644 index 0000000..04cc85c --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/userEdit/userEdit.ts @@ -0,0 +1,67 @@ +import {StatusParamsType} from '@utils/publicType'; +import {EditUserType} from '../typeManagement'; + +interface DataType { + listData: {[x: string]: {}}; + prefix: Ref; + editingUserDiaLog: Ref; +} + +const editOperate = (userList: T) => { + const data: DataType = { + listData: reactive<{[x: string]: {}}>({}), + prefix: ref(''), // 手机号类型 + // 编辑用户组件弹窗状态 + editingUserDiaLog: ref(false) + }; + + /** + * 点击编辑用户操作 + * @param {Object} item 当前点击的这一项 + * @return {boolean} addUserDialog.value 编辑用户组件弹窗状态 + */ + const editUserClick = async (item: EditUserType, phoneType: string): Promise => { + const {userName, roleName, description, phoneNumber, roleId, userId, phonePrefix, email, defaultProjectId, createdTime}: EditUserType = item; + data.prefix.value = phoneType; + await nextTick(() => { + data.listData.value = { + userName, + roleName, + description, + phoneNumber, + roleId, + userId, + phonePrefix, + email, + defaultProjectId, + createdTime + }; + }); + return data.editingUserDiaLog.value = !data.editingUserDiaLog.value; + }; + + /** + * 编辑用户取消事件 + * @param {boolean} status 状态 + * @return {boolean} xxx 蒙层状态 + */ + const editUserCancel: StatusParamsType <(status: boolean) => boolean> = (status: boolean): boolean => { + return data.editingUserDiaLog.value = status; + }; + + /** + * 编辑用户操作后的回调-请求列表接口 + */ + const editUserSure = () => { + userList.getUserList(); + }; + + return { + ...data, + editUserClick, + editUserCancel, + editUserSure + } +}; + +export default editOperate; \ No newline at end of file diff --git a/bmp-operation-web/src/views/userManagement/list/userEdit/userEdit.vue b/bmp-operation-web/src/views/userManagement/list/userEdit/userEdit.vue new file mode 100644 index 0000000..fa0ef40 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/userEdit/userEdit.vue @@ -0,0 +1,21 @@ + + \ No newline at end of file diff --git a/bmp-operation-web/src/views/userManagement/list/userList.vue b/bmp-operation-web/src/views/userManagement/list/userList.vue new file mode 100644 index 0000000..fbb5a26 --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/list/userList.vue @@ -0,0 +1,139 @@ + + + + + diff --git a/bmp-operation-web/src/views/userManagement/navRouter.ts b/bmp-operation-web/src/views/userManagement/navRouter.ts new file mode 100644 index 0000000..e022b7b --- /dev/null +++ b/bmp-operation-web/src/views/userManagement/navRouter.ts @@ -0,0 +1,20 @@ +/** + * @file + * @author +*/ + +import {language} from "utils/publicClass.ts"; + +const userNavData = (pathUrl: (arg0: string) => void, imgUrl: (arg0: string) => void) => { + return { + title: language.t('navigationBar.list.userManagement'), + defaultImg: imgUrl('userDefault'), + changeImg: imgUrl('user'), + path: pathUrl('user'), + otherPath: [pathUrl('user')], + hasAdmin: true, + isF: true, + } +}; + +export default userNavData; \ No newline at end of file diff --git a/bmp-operation-web/tsconfig.json b/bmp-operation-web/tsconfig.json new file mode 100644 index 0000000..3f4994b --- /dev/null +++ b/bmp-operation-web/tsconfig.json @@ -0,0 +1,43 @@ +{ + "compilerOptions": { + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "target": "esnext", // 指定 ECMAScript 目标版本 + "module": "esnext", // 指定使用模块 + "strict": true, // 启用所有严格类型检查选项 + "jsx": "preserve", // 指定 jsx 代码的生成: preserve + "importHelpers": true, // 从 tslib 导入辅助工具函数 + "moduleResolution": "node", // 选择模块解析策略:node + "skipLibCheck": true, // 跳过库检查 + "esModuleInterop": true, //允许使用commonjs的方式import默认文件 + "allowSyntheticDefaultImports": true, // 允许从没有设置默认导出的模块中默认导入 + "sourceMap": true, // 生成相应的.map文件 + "baseUrl": ".", // 工作根目录 + "noUnusedLocals": true, // 有未使用的变量时,抛出错误 + "noUnusedParameters": true, // 有未使用的参数时,抛出错误 + "types": [ // 需要包含的类型声明文件名列表 + "webpack-env", + "jest", + "pinia-plugin-persist" + ], + "paths": { // 模块名到基于 baseUrl 的路径映射的列表 + "@": ["src"], + "hooks/*": ["src/hooks/*.ts"], + "@utils/*": ["src/utils/*"], + "utils/*": ["src/utils/*.ts"] + }, + "lib": [ // 指定要包含在编译中的库文件 + "esnext", + "dom", + "dom.iterable", + "scripthost" + ] + }, + "include": [ // 指定编译需要编译的文件或目录 + "src/**/*" // *匹配零个或者多个字符 + ], + "exclude": [ // 用于指定当解析include选项时,需要忽略的文件列表 + "node_modules", + "dist" + ] +} \ No newline at end of file diff --git a/bmp-operation-web/vue.config.js b/bmp-operation-web/vue.config.js new file mode 100644 index 0000000..fab149a --- /dev/null +++ b/bmp-operation-web/vue.config.js @@ -0,0 +1,70 @@ +// 页面路径 +const setAlias = require('./config/setAlias'); +// 跨域配置 +const devServer = require('./config/devServer'); + +const setOutPut = require('./config/setOutPut'); + +// 避免文件的频繁变更导致浏览器缓存失效,更好的利用缓存。提升用户体验 +const runtimeChunk = require('./config/runtimeChunk'); +// 可以看到启动时的消耗模块,方便后续做优化 +const speedMeasure = require('./config/speedMeasure'); +// prod环境移除console +// const terserPlugin = require('./config/terserPlugin'); +// 减少不必要的解析 +const noParse = require('./config/noParse'); + +const publicConfig = require('./config/plugin'); + +const devTool = require('./config/devTool'); + +// devtool: 'inline-source-map' +module.exports = { + publicPath: '/', + productionSourceMap: false, // 是否在构建生产包时生成 sourceMap 文件,false将提高构建速度 + outputDir: 'dist', + // 放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录 + assetsDir: 'static', + // 指定生成的 index.html 的输出路径 (相对于 outputDir),也可以是一个绝对路径 + indexPath: 'index.html', + // 生成的静态资源在它们的文件名中包含了 hash 以便更好的控制缓存 + filenameHashing: true, + // 修改默认的webpack的配置 + configureWebpack: config => { + setOutPut(config); + runtimeChunk(config); + speedMeasure(config); + noParse(config); + publicConfig(config); + devTool(config); + + }, + // 调整内部的webpack配置 + chainWebpack: config => { + config.plugin('html').tap(args => { + args[0].unknownContextCritical = false; + return args; + }); + config.resolve.symlinks(true); // 修复热更新失效 + // 配置alias别名 + setAlias(config); + // 删除懒加载模块的prefetch,降低带宽压力 + config.plugins.delete('prefetch'); + config.module + .rule('images') + .set('parser', { + dataUrlCondition: { + maxSize: 30 * 1024 + } + } + ); + }, + ...devServer, + css: { + loaderOptions: { + scss: { + prependData: '@import "~@/assets/css/communal.scss";' + } + } + } +}; diff --git a/bmp-pronoea/.cmd b/bmp-pronoea/.cmd new file mode 100644 index 0000000..ced32d3 --- /dev/null +++ b/bmp-pronoea/.cmd @@ -0,0 +1 @@ +rm -rf vendor diff --git a/bmp-pronoea/.gitignore b/bmp-pronoea/.gitignore new file mode 100644 index 0000000..a7470ba --- /dev/null +++ b/bmp-pronoea/.gitignore @@ -0,0 +1,4 @@ +/log +.idea +lastupdate.tmp +bmp-pronoea diff --git a/bmp-pronoea/.gitmodules b/bmp-pronoea/.gitmodules new file mode 100644 index 0000000..506f24c --- /dev/null +++ b/bmp-pronoea/.gitmodules @@ -0,0 +1,3 @@ +[submodule "bmp-deploy"] + path = bmp-deploy + url = git@coding.jd.com:aidc-bmp/bmp-deploy.git diff --git a/bmp-pronoea/README.md b/bmp-pronoea/README.md new file mode 100644 index 0000000..f32729a --- /dev/null +++ b/bmp-pronoea/README.md @@ -0,0 +1,37 @@ +# PRONOEA (bmp-pronoea) + +English | [简体中文](README.zh-CN.md) + +## Introduction + +`Bmp Pronoea` In order to further improve the ability of private bare metal platform to manage and monitor instances, +and realize integrated management of monitoring and alarm, the performance monitoring (in-band monitoring) function was proposed. +That is, it supports monitoring and alarm management of resources under user names. Therefore, +the third-party alarm service Prometheus (official website: https://prometheus.io/) was introduced. +The self-developed version bmp-pronoea (Pronoa) is based on the Prometheus service, integrates product requirements, +and realizes resource monitoring and alarm management. + +![bmp-pronoea.png](../docs/zh/bmp-deploy/picture/bmp-pronoea.png) +## Core functions +### Pronoea System Module +- **Alarm rule management (prometheus-rule-agent)** + Provides the function of dynamically setting alarm rules. Receives the alarm rule information sent by the upper-layer BMP-API, + converts the alarm rule information into a yml file that Prometheus can recognize, and writes it to the specified directory. +- **Alarm information management (prometheus-alert-transform)** + Receives the alert information from the Alertmanager module, converts the information format, and returns the alert information to the downstream module. + It can be the event center, BMP-API, or other possible system modules. +- **Monitoring data management (prometheus-monitor-data)** + Prometheus provides an API-client to query the collected monitoring data. + The original intention of this module is to encapsulate the API-clieng layer and provide data query services for BMP-API. +- **Monitoring data clean (cache-del-server)** + After the monitoring data received by Pushgateway is pulled by the Prometheus main service, + it will not be deleted actively, which will cause the accumulation of useless data and waste resources. + cache-del-server is designed to actively delete this junk data at regular intervals. + +### External Dependencies +- **Proxy(bmp-monitor-proxy)** +Integrate the monitoring data of the instance, integrate the data into a specific recognizable data format, +and finally push it to Pushgateway. For details, see bmp-monitor-proxy. +- **BMP API** +The interaction between the console, operation management background and Prometheus monitoring system relies on BMP-API, for example:setting alarm rules, querying monitoring data, receiving and processing alarm information, etc. +Here, BMP API includes bmp-console-api and bmp-openapi. \ No newline at end of file diff --git a/bmp-pronoea/README.zh-CN.md b/bmp-pronoea/README.zh-CN.md new file mode 100644 index 0000000..efc9747 --- /dev/null +++ b/bmp-pronoea/README.zh-CN.md @@ -0,0 +1,27 @@ +# 普罗诺亚 (bmp-pronoea) + +[English](README.md) | 简体中文 + +## 介绍 + +`Bmp Pronoea` 为进一步完善私有化裸金属平台对实例管理监控的能力,同时实现监控和报警一体化管理,性能监控(带内监控)功能被提出。即支持针对用户名下的资源进行监控和报警管理等。因而引入了第三方告警服务Prometheus(官方网站:https://prometheus.io/)。 + 自研版bmp-pronoea(普罗诺亚)以Prometheus服务为基础,集合产品需求,实现了资源监控和报警的管理。 + +![bmp-pronoea.png](../docs/zh/bmp-deploy/picture/bmp-pronoea.png) +## 核心功能 +### 普罗诺亚系统模块 +- **告警规则管理 (prometheus-rule-agent)** + 提供动态设置告警规则的功能。接收上层BMP-API下发的告警规则信息,将这些告警规则信息转换成Prometheus可识别的yml文件,写入指定目录。 +- **告警信息管理 (prometheus-alert-transform)** + 接收Alertmanager模块的告警信息,转换信息格式后,将告警信息返给下游模块。可以是事件中心、BMP-API或其他可能有的系统模块。 +- **监控数据管理 (prometheus-monitor-data)** + Prometheus对外提供了API-client,用于查询收集到监控数据。此模块的设计初衷是,将API-clieng封装一层,对BMP-API提供数据查询服务。 +- **监控数据清理 (cache-del-server)** + Pushgateway接收的监控数据被Prometheus主服务拉取走之后,并不会主动删除,这样会造成无用数据的堆积,浪费资源。cache-del-server 被设计为定时主动删除这些垃圾数据。 + +### 外围依赖 +- **Proxy(bmp-monitor-proxy)** +整合实例的监控数据,并将数据整合成可识别的特定数据格式,最后推送至Pushgateway。详见 bmp-monitor-proxy。 +- **BMP API** +控制台、运营管理后台与Prometheus监控系统的交互,依赖BMP-API来完成,例如,设置告警规则、查询监控数据、接收处理告警信息等。 +此处BMP API包含了 bmp-console-api 和 bmp-openapi。 \ No newline at end of file diff --git a/bmp-pronoea/bmp-pronoea.Dockerfile b/bmp-pronoea/bmp-pronoea.Dockerfile new file mode 100644 index 0000000..28abedc --- /dev/null +++ b/bmp-pronoea/bmp-pronoea.Dockerfile @@ -0,0 +1,12 @@ +FROM golang:1.17-alpine AS builder +ENV GOPROXY https://goproxy.cn +WORKDIR /usr/src/bmp-pronoea +COPY . . +RUN go build -o /tmp/bmp-pronoea . + +FROM alpine:3.16 +WORKDIR /home/bmp/bmp-pronoea +COPY --from=builder /tmp/bmp-pronoea . +COPY ./conf ./conf +CMD ["./bmp-pronoea"] + diff --git a/bmp-pronoea/common/common.go b/bmp-pronoea/common/common.go new file mode 100644 index 0000000..ef9e087 --- /dev/null +++ b/bmp-pronoea/common/common.go @@ -0,0 +1,10 @@ +package common + +const ( + // 分隔符 + DELIMITER_VERTICAL = "|" + DELIMITER_COMMA = "," + + CHARACTER_LEFT_PARENTHESIS = "(" + CHARACTER_RIGTH_PARENTHESIS = ")" +) diff --git a/bmp-pronoea/common/util/common.go b/bmp-pronoea/common/util/common.go new file mode 100644 index 0000000..c1dbe43 --- /dev/null +++ b/bmp-pronoea/common/util/common.go @@ -0,0 +1,6 @@ +package util + +const ( + SEPARATOR_COMMA = "," + SEPARATOR_SEMICOLON = ";" +) diff --git a/bmp-pronoea/common/util/encrypt.go b/bmp-pronoea/common/util/encrypt.go new file mode 100644 index 0000000..b4526b8 --- /dev/null +++ b/bmp-pronoea/common/util/encrypt.go @@ -0,0 +1,30 @@ +package util + +import ( + "crypto/md5" + "crypto/sha512" + "encoding/hex" + "fmt" + uuid "github.com/satori/go.uuid" +) + +func GetMd5(str string, salts ...string) string { + h := md5.New() + h.Write([]byte(str)) + if len(salts) == 0 { + return hex.EncodeToString(h.Sum(nil)) + } else { + for _, salt := range salts { + h.Write([]byte(salt)) + } + return hex.EncodeToString(h.Sum(nil)) + } +} + +func GetUuid() string { + return fmt.Sprintf("%v", uuid.NewV4()) +} + +func GetSha512(str string) string { + return fmt.Sprintf("%x", sha512.Sum512([]byte(str))) +} diff --git a/bmp-pronoea/common/util/http.go b/bmp-pronoea/common/util/http.go new file mode 100644 index 0000000..0a646bc --- /dev/null +++ b/bmp-pronoea/common/util/http.go @@ -0,0 +1,124 @@ +package util + +import ( + "compress/gzip" + "crypto/tls" + "errors" + "fmt" + "github.com/astaxie/beego/logs" + "io" + "io/ioutil" + "net" + "net/http" + "net/url" + "strings" + "time" +) + +func DoHttpRequest(requestId, reqUrl, host, method, bodyStr string, params, headers map[string]string, connTimeout, timeout, maxIdleConnsPerHost int) ([]byte, error) { + + if connTimeout <= 0 { + connTimeout = 50000 + } + if timeout <= 0 { + timeout = 50000 + } + if maxIdleConnsPerHost <= 0 { + maxIdleConnsPerHost = 1 + } + + tr := &http.Transport{ + Dial: func(network, addr string) (net.Conn, error) { + return net.DialTimeout(network, addr, time.Duration(connTimeout)*time.Second) + }, + MaxIdleConnsPerHost: maxIdleConnsPerHost, + ResponseHeaderTimeout: time.Duration(connTimeout) * time.Second, + DisableKeepAlives: true, + } + + client := &http.Client{Transport: tr, Timeout: time.Duration(timeout) * time.Second} + + values := url.Values{} + for k, v := range params { + values.Set(k, v) + } + + var body io.Reader + body = nil + if method == "GET" { + u, err := url.ParseRequestURI(reqUrl) + if err != nil { + logs.Warn("%v:parse request uri for %v error:%v", requestId, reqUrl, err) + return nil, err + } + u.RawQuery = values.Encode() + reqUrl = fmt.Sprintf("%v", u) + } else { + if bodyStr == "" { + body = strings.NewReader(values.Encode()) + } else { + body = strings.NewReader(bodyStr) + } + } + + req, err := http.NewRequest(method, reqUrl, body) + if err != nil { + logs.Warn("%v:new request for url:%v error:%v", requestId, reqUrl, err) + return nil, err + } + logs.Trace("%v:begin send request to url:%v, body:%v, param:%v", requestId,reqUrl, body, params) + if host != "" { + req.Host = host + if strings.Contains(reqUrl, "https://") { + tls := &tls.Config{ + ServerName: host, + } + tr.TLSClientConfig = tls + } + } + + //req.Header.Set("Content-Type", contentType) "application/json" + if headers != nil && len(headers) > 0 { + for headerKey, headerValue := range headers { + req.Header.Set(headerKey, headerValue) + } + } + + // default, accept gzip + req.Header.Set("Accept-Encoding", "gzip") + + resp, err := client.Do(req) + if err != nil { + logs.Warn("%v:do request for url:%v error:%v", requestId, reqUrl, err) + return nil, err + } + defer resp.Body.Close() + + // check content type + rbody := resp.Body + resContentType := resp.Header.Get("Content-Encoding") + if strings.Contains(resContentType, "gzip") { + // decode gzip + gzipBody, err := gzip.NewReader(resp.Body) + if err != nil { + logs.Warn("%v:gzip reader error:%v", requestId, err) + return nil, err + } + rbody = gzipBody + } + + result, err := ioutil.ReadAll(rbody) + if err != nil { + logs.Warn("%v: read response from url:%v error:%v", requestId, reqUrl, err) + return nil, err + } + + if resp.StatusCode != 200 && resp.StatusCode != 202 { + logs.Warn("%v: http status code:%v, url:%v, result:%v", requestId, resp.StatusCode, reqUrl, string(result)) + return nil, errors.New(fmt.Sprintf("http response status code error, code:%v", resp.StatusCode)) + } + + logs.Trace("%v:success get result from url:%v, result:%v", requestId, reqUrl, string(result)) + + return result, nil +} \ No newline at end of file diff --git a/bmp-pronoea/common/util/interface.go b/bmp-pronoea/common/util/interface.go new file mode 100644 index 0000000..fc0f96d --- /dev/null +++ b/bmp-pronoea/common/util/interface.go @@ -0,0 +1,25 @@ +package util + +func TurnInterfaceToInt64(org interface{}) int64 { + var data int64 = 0 + switch org.(type) { + case int64: + data = org.(int64) + case int: + data = int64(org.(int)) + case float64: + data = int64(org.(float64)) + } + + return data +} + +func TurnInterfaceToString(org interface{}) string { + var str string = "" + switch org.(type) { + case string: + str = org.(string) + } + + return str +} diff --git a/bmp-pronoea/common/util/path.go b/bmp-pronoea/common/util/path.go new file mode 100644 index 0000000..2aa44c0 --- /dev/null +++ b/bmp-pronoea/common/util/path.go @@ -0,0 +1,328 @@ +package util + +import ( +"errors" +"fmt" +"io" +"io/ioutil" +"os" +"path" +"path/filepath" +"syscall" +) + +// GetParentPath 获取父级目录 +// path format is /path/to/file, return /path/to +func GetParentPath(pathStr string) string { + return path.Dir(pathStr) +} + +// CheckIsDir 是目录吗? +func CheckIsDir(filename string) error { + fi, err := os.Stat(filename) + if err != nil { + return err + } + if !fi.IsDir() { + return errors.New("The given path is not directory.") + } + + return nil +} + +// PathIsExist 目录存在吗 +func PathIsExist(path string) bool { + if _, err := os.Stat(path); err != nil { + if os.IsNotExist(err) { + return false + } + } + return true +} + + +func PathIsEmpty(path string) (bool,error) { + if !PathIsExist(path) { + return true, nil //目录不存在,认为目录为空 + } + + dirlist, err := ioutil.ReadDir(path) + if err != nil { + return true, err + } + if len(dirlist) > 0 { + return false, nil + } + return true, nil +} + +// CheckIsFile 是文件吗 +func CheckIsFile(filename string) error { + fi, err := os.Stat(filename) + if err != nil { + return err + } + if !fi.Mode().IsRegular() { + return errors.New("The given path is not file.") + } + + return nil +} + +// FileIsExist 文件存在吗 +func FileIsExist(path string) bool { + if !PathIsExist(path) { + return false + } + + err := CheckIsFile(path) + if err != nil { + return false + } + + return true +} + +func RemoveFile(path string) error { + if !FileIsExist(path) { //文件不存在认为是已经删除了 + return fmt.Errorf("file not exist") + } + + err := os.Remove(path) + return err +} + +// CheckParent make sure parents dir exist, not exist then create +func CheckParent(aph string) error { + pph := path.Dir(aph) + err := os.MkdirAll(pph, os.ModeDir|0755) + if nil != err { + return err + } + return nil +} + +// WriteFile 写文件 +func WriteFile(filename string, content string) error { + err := CheckParent(filename) + if err != nil { + return err + } + f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) + if err != nil { + return err + } + defer f.Close() + ret, err := f.WriteString(content) + if err != nil || ret != len(content) { + msg := fmt.Sprintf("WriteFile[%v] err.", filename) + return errors.New(msg) + } + + return nil +} + +func DiffDir(excludePath, spath, dpath string) (bool, string, error) { + return diffByDiffCmd(excludePath, spath, dpath) +} + +func RsyncDir(spath, dpath string) error { + isdir, err := isDir(spath) + if err != nil { + return err + } + + command := "" + if isdir { + command = fmt.Sprintf("mkdir -p %v %v && rsync -rtopg --delete %v/ %v/", spath, dpath, spath, dpath) + } else { + command = fmt.Sprintf("rsync -avrtopg --delete %v %v", spath, dpath) + } + + _, err = CmdRunWithOutput(command) + return err +} + +func RsyncDirWithOutPut(spath, dpath string) (string, error) { + isdir, err := isDir(spath) + if err != nil { + return "", err + } + + command := "" + if isdir { + command = fmt.Sprintf("mkdir -p %v %v && rsync -rtopg --delete %v/ %v/", spath, dpath, spath, dpath) + } else { + command = fmt.Sprintf("rsync -avrtopg --delete %v %v", spath, dpath) + } + + outPut, err := CmdRunWithOutput(command) + if err != nil { + return outPut, fmt.Errorf("RsyncDir error! command[%v], output:[%v], error:[%v]", command, outPut, err) + } + return outPut, err +} + +func diffByDiffCmd(excludePath, spath, dpath string) (bool, string, error) { + if !PathIsExist(spath) { + msg := fmt.Sprintf("spath[%v] not exist.", spath) + return false, "", errors.New(msg) + } + if !PathIsExist(dpath) { + // dpath is not exist + return false, "", nil + } + + command := fmt.Sprintf("diff -aHr -x '%v' %v %v", excludePath, spath, dpath) + diffStr, err := CmdRunWithOutput(command) + if err != nil { + if err.Error() == "exit status 1" { + return false, diffStr, nil + } + + msg := fmt.Sprintf("Exec diff %v %v %v error %v.\n", spath, dpath, command, err) + return true, diffStr, errors.New(msg) + } + + return true, diffStr, nil +} + +func isDir(path string) (bool, error) { + fi, err := os.Stat(path) + if err != nil { + return false, err + } + if fi.IsDir() { + return true, nil + } + if fi.Mode().IsRegular() { + return false, nil + } + return false, errors.New("File is not regular file") +} + +func diffByRsyncCmd(spath, dpath string) bool { + return true +} + +func CopyFile(src, dst string) error { + srcFile, err := os.Open(src) + if err != nil { + return err + } + defer srcFile.Close() + dstFile, err := os.Create(dst) + if err != nil { + return err + } + defer dstFile.Close() + + _, err = io.Copy(dstFile, srcFile) + + return err +} + + +func CopyDirectory(scrDir, dest string) error { + entries, err := ioutil.ReadDir(scrDir) + if err != nil { + return err + } + if !PathIsExist(dest) { + os.MkdirAll(dest, os.ModeDir|0755) + } + for _, entry := range entries { + sourcePath := filepath.Join(scrDir, entry.Name()) + destPath := filepath.Join(dest, entry.Name()) + + fileInfo, err := os.Stat(sourcePath) + if err != nil { + return err + } + + stat, ok := fileInfo.Sys().(*syscall.Stat_t) + if !ok { + return fmt.Errorf("failed to get raw syscall.Stat_t data for '%s'", sourcePath) + } + + switch fileInfo.Mode() & os.ModeType{ + case os.ModeDir: + if err := CreateIfNotExists(destPath, 0755); err != nil { + return err + } + if err := CopyDirectory(sourcePath, destPath); err != nil { + return err + } + case os.ModeSymlink: + if err := CopySymLink(sourcePath, destPath); err != nil { + return err + } + default: + if err := Copy(sourcePath, destPath); err != nil { + return err + } + } + + if err := os.Lchown(destPath, int(stat.Uid), int(stat.Gid)); err != nil { + return err + } + + isSymlink := entry.Mode()&os.ModeSymlink != 0 + if !isSymlink { + if err := os.Chmod(destPath, entry.Mode()); err != nil { + return err + } + } + } + return nil +} + +func Copy(srcFile, dstFile string) error { + out, err := os.Create(dstFile) + if err != nil { + return err + } + + defer out.Close() + + in, err := os.Open(srcFile) + defer in.Close() + if err != nil { + return err + } + + _, err = io.Copy(out, in) + if err != nil { + return err + } + + return nil +} + +func Exists(filePath string) bool { + if _, err := os.Stat(filePath); os.IsNotExist(err) { + return false + } + + return true +} + +func CreateIfNotExists(dir string, perm os.FileMode) error { + if Exists(dir) { + return nil + } + + if err := os.MkdirAll(dir, perm); err != nil { + return fmt.Errorf("failed to create directory: '%s', error: '%s'", dir, err.Error()) + } + + return nil +} + +func CopySymLink(source, dest string) error { + link, err := os.Readlink(source) + if err != nil { + return err + } + return os.Symlink(link, dest) +} \ No newline at end of file diff --git a/bmp-pronoea/common/util/strconv.go b/bmp-pronoea/common/util/strconv.go new file mode 100644 index 0000000..c8b62f4 --- /dev/null +++ b/bmp-pronoea/common/util/strconv.go @@ -0,0 +1,22 @@ +package util + +import ( + "strconv" +) + +func TurnStringToFloat64(numberStr string, prec int) (float64, error) { + float64F, err := strconv.ParseFloat(numberStr, 64) + if err != nil { + return 0, err + } + return Float64WithPrec(float64F, prec) +} +// Float64WithPrec float64 保留小数点后几位 +func Float64WithPrec(inFloat64 float64, prec int) (float64, error) { + float64With, err := strconv.ParseFloat(strconv.FormatFloat(inFloat64, 'f', prec, 64), 64) + if err != nil { + return 0, err + } + + return float64With, nil +} diff --git a/bmp-pronoea/common/util/strings.go b/bmp-pronoea/common/util/strings.go new file mode 100644 index 0000000..c1825f2 --- /dev/null +++ b/bmp-pronoea/common/util/strings.go @@ -0,0 +1,39 @@ +package util + +import ( + "strings" + "unicode" +) + +func IsNotEmpty(str ...string) bool { + for _, s := range str { + if s == "" { + return false + } + } + return true +} + +func IsEmpty(str string) bool { + return str == "" +} + +func StringsContains(str, subStr string) bool { + return strings.Contains(strings.ToLower(str), strings.ToLower(subStr)) +} + +func UnderLineToHumpCamel(name string) string { + name = strings.Replace(name, "_", " ", -1) + name = strings.Title(name) + name = strings.Replace(name, " ", "", -1) + return string(unicode.ToLower(rune(name[0]))) + name[1:] +} + +func HeadToLower(s string) string { + if s == "" { + return s + } + runes := []rune(s) + runes[0] = unicode.ToLower(runes[0]) + return string(runes) +} \ No newline at end of file diff --git a/bmp-pronoea/common/util/system.go b/bmp-pronoea/common/util/system.go new file mode 100644 index 0000000..3ed1ccf --- /dev/null +++ b/bmp-pronoea/common/util/system.go @@ -0,0 +1,21 @@ +package util + +import ( + "os/exec" + "path" +) + +func CmdRunWithOutput(command string) (string, error) { + var out []byte + var err error = nil + + if path.Ext(command) == ".sh" { + // shell + out, err = exec.Command("/bin/sh", command).CombinedOutput() + } else { + // command + out, err = exec.Command("/bin/sh", "-c", command).CombinedOutput() + } + + return string(out), err +} diff --git a/bmp-pronoea/common/util/time.go b/bmp-pronoea/common/util/time.go new file mode 100644 index 0000000..5931d06 --- /dev/null +++ b/bmp-pronoea/common/util/time.go @@ -0,0 +1,62 @@ +package util + +import ( + "github.com/astaxie/beego/logs" + "time" +) + +func GetCurrentTimeStrWithlayout(layout string) string { + return time.Now().Format(layout) +} + +func GetCurrentTimeStr() string { + return GetCurrentTimeStrWithlayout("2006-01-02 15:04:05") +} + +func GetTimestampByStr(str string) int64 { + layout := "2006-01-02 15:04:05" + return GetTimestampByStrWithLayout(str, layout) +} + +func GetTimestampByStrWithLayout(str, layout string) int64 { + loc, err := time.LoadLocation("Local") + if err != nil { + logs.Warn("load local location error:%v", err) + return 0 + } + + //layout := "2006-01-02 15:04:05" + tm, err := time.ParseInLocation(layout, str, loc) + if err != nil { + logs.Debug("get timestamp by str:%v error:%v", str, err) + return 0 + } + + t := tm.Unix() + + return t +} + +func GetCurrentTimestamp() int64 { + tNowStr := GetCurrentTimeStr() + return GetTimestampByStr(tNowStr) +} + +func GetTimeStrByTimestamp(timestamp int64) string { + tm := time.Unix(timestamp, 0) + return tm.Format("2006-01-02 15:04:05") +} + +func GetUtcTimeByTimeStr(timeStr string) (string, error) { + t, err := time.ParseInLocation("2006-01-02 15:04:05", timeStr, time.Local) + if err != nil { + return "", err + } + utcTime := t.UTC().Format("2006-01-02T15:04:05Z") + return utcTime, nil +} + +func GetUtcTimeByTimeStamp(timestamp int64) (string, error) { + timeStr := GetTimeStrByTimestamp(timestamp) + return GetUtcTimeByTimeStr(timeStr) +} \ No newline at end of file diff --git a/bmp-pronoea/conf/app.conf b/bmp-pronoea/conf/app.conf new file mode 100644 index 0000000..18c601a --- /dev/null +++ b/bmp-pronoea/conf/app.conf @@ -0,0 +1,73 @@ +appname = bmp-pronoea +httpport = ${BMP_PRONOEA_PORT||9999} +runmode = prod +autorender = false +copyrequestbody = true +EnableDocs = true +sqlconn = + +#日志相关 +log.level=7 +log.file=/var/log/bmp/bmp-pronoea/pronoea.log +log.perm=0777 +log.days=60 +log.rotateperm=0777 + +# bmp bmpconsole 接口,主要用于上报告警信息 +bmpopenapiconsole.host=${BMP_OPENAPI_CONSOLE_HOST} +bmpopenapiconsole.port=${BMP_OPENAPI_CONSOLE_PORT} +bmpopenapiconsole.connecttimeout=15 +bmpopenapiconsole.timeout=20 +bmpopenapiconsole.maxidleconnsperhost=1 +bmpopenapiconsole.authorization="Bearer Ac13LWNvdrpxkGUtxxfcp" + +# 定时清理pushgateway 数据 +crontab.wipepushgateway=${BMP_PRONOEA_CRONTAB_WIPEPUSHGATEWAY||45 30 * * * *} + +# prometheus 相关 +prometheus.rulepath="/var/lib/prometheus/conf/rules" +prometheus.host=${BMP_PROMETHEUS_HOST} +prometheus.port=${BMP_PROMETHEUS_PORT} +prometheus.connecttimeout=15 +prometheus.timeout=20 +prometheus.maxidleconnsperhost=1 + +# pushgateway 相关 +pushgateway.port=${BMP_PUSHGATEWAY_PORT} +pushgateway.host=${BMP_PUSHGATEWAY_HOST} +pushgateway.connecttimeout=15 +pushgateway.timeout=20 +pushgateway.maxidleconnsperhost=1 + +[dev] +log.level=7 +log.file=./log/pronoea.log +log.perm=0777 +log.days=60 +log.rotateperm=0777 + +# bmp bmpconsole 接口,主要用于上报告警信息 +bmpopenapiconsole.host=${BMP_OPENAPI_CONSOLE_HOST||bmp-openapi.bmp.local} +bmpopenapiconsole.port=${BMP_OPENAPI_CONSOLE_PORT||8802} +bmpopenapiconsole.connecttimeout=15 +bmpopenapiconsole.timeout=20 +bmpopenapiconsole.maxidleconnsperhost=1 +bmpopenapiconsole.authorization="Bearer Ac13LWNvdrpxkGUtxxfcp" + +# 定时清理pushgateway 数据 +crontab.wipepushgateway=${BMP_PRONOEA_CRONTAB_WIPEPUSHGATEWAY||58 * * * * *} + +# prometheus 相关 +prometheus.rulepath="./log/rules" +prometheus.host=${BMP_PROMETHEUS_HOST||bmp-prometheus-test.jdcloud.com} +prometheus.port=${BMP_PROMETHEUS_PORT||80} +prometheus.connecttimeout=15 +prometheus.timeout=20 +prometheus.maxidleconnsperhost=1 + +# pushgateway 相关 +pushgateway.host=${BMP_PUSHGATEWAY_HOST||bmp-pushgateway.bmp.local} +pushgateway.port=${BMP_PUSHGATEWAY_PORT||9091} +pushgateway.connecttimeout=15 +pushgateway.timeout=20 +pushgateway.maxidleconnsperhost=1 \ No newline at end of file diff --git a/bmp-pronoea/config/config.go b/bmp-pronoea/config/config.go new file mode 100644 index 0000000..62002b3 --- /dev/null +++ b/bmp-pronoea/config/config.go @@ -0,0 +1,72 @@ +package config + +import ( + "encoding/json" + "fmt" + "git.jd.com/bmp-pronoea/common/util" + "github.com/astaxie/beego" + "io/ioutil" +) + +type HttpConfig struct { + Domain string `json:"Domain"` + Host string `json:"Host"` + Port string `json:"Port"` + ConnectTimeout int + Timeout int + MaxIdleConnsPerHost int +} + +type BmpOpenApiConfig struct { + BaseConfig *HttpConfig + Authorization string +} + +type PrometheusConfig struct { + BaseConfig *HttpConfig + PrometheusRulePath string +} + +type PushgatewayConfig struct { + BaseConfig *HttpConfig +} + +type SystemConfig struct { + Crontabs map[string]string + PrometheusRulePath string +} + + +var SysConfig *SystemConfig + +// ParseConfig 加载本地文件的方式 +func ParseConfig(path string) error { + data, err := ioutil.ReadFile(path) + if err != nil { + return err + } + SysConfig = &SystemConfig{} + err = json.Unmarshal(data, SysConfig) + if err != nil { + return err + } + + return nil +} + + +func ParseConfigAppConf() error { + SysConfig = &SystemConfig{} + + // 初始化 crontab 配置 + SysConfig.Crontabs = initCrontabConfig() + + rulePath := beego.AppConfig.String("prometheus.rulepath") + if util.IsEmpty(rulePath) { + return fmt.Errorf("prometheus rule path empty ") + } + SysConfig.PrometheusRulePath = rulePath + return nil +} + + diff --git a/bmp-pronoea/config/crontabConfig.go b/bmp-pronoea/config/crontabConfig.go new file mode 100644 index 0000000..56d21ce --- /dev/null +++ b/bmp-pronoea/config/crontabConfig.go @@ -0,0 +1,31 @@ +package config + +import ( + "fmt" + "git.jd.com/bmp-pronoea/common/util" + "github.com/astaxie/beego" + "strings" +) + +const ( + CRONTAB_WIPE_PUSHGATEWAY = "WipePushgateway" +) + +// CrontabList 这里添加其他crontab +var CrontabList = []string{ + CRONTAB_WIPE_PUSHGATEWAY, +} + +func initCrontabConfig() map[string]string { + crontabConfig := make(map[string]string) + + for _, crontabName := range CrontabList { + crontabConfigDetail := beego.AppConfig.String(fmt.Sprintf("crontab.%v", strings.ToLower(crontabName))) + if util.IsEmpty(crontabConfigDetail) { + continue + } + crontabConfig[crontabName] = crontabConfigDetail + } + + return crontabConfig +} diff --git a/bmp-pronoea/config/httpServerConfig.go b/bmp-pronoea/config/httpServerConfig.go new file mode 100644 index 0000000..9c20c33 --- /dev/null +++ b/bmp-pronoea/config/httpServerConfig.go @@ -0,0 +1,56 @@ +package config + +import ( + "fmt" + "git.jd.com/bmp-pronoea/common/util" + "github.com/astaxie/beego" +) + +// HttpServerConfigByHeader 加载http第三方依赖的配置 +func HttpServerConfigByHeader(header string) (*HttpConfig, error) { + port := beego.AppConfig.String(fmt.Sprintf("%v.port", header)) + if util.IsEmpty(port) { + return nil, fmt.Errorf("%v.port config empty ", header) + } + + host := beego.AppConfig.String(fmt.Sprintf("%v.host", header)) + if util.IsEmpty(host) { + return nil, fmt.Errorf("%v.host config empty ", header) + } + + connecttimeout, err := beego.AppConfig.Int(fmt.Sprintf("%v.connecttimeout", header)) + if err != nil{ + return nil, fmt.Errorf("%v.connecttimeout config error %v ", header, err) + } + if connecttimeout <= 0 { + connecttimeout = 15 + } + + timeout, err := beego.AppConfig.Int(fmt.Sprintf("%v.timeout", header)) + if err != nil{ + return nil, fmt.Errorf("%v.timeout config error %v ", header, err) + } + if timeout <= 0 { + timeout = 20 + } + + maxidleconnsperhost, err := beego.AppConfig.Int(fmt.Sprintf("%v.maxidleconnsperhost", header)) + if err != nil{ + return nil, fmt.Errorf("%v.maxidleconnsperhost config error %v ", header, err) + } + if maxidleconnsperhost <= 0 { + maxidleconnsperhost = 1 + } + + configRes := &HttpConfig{ + Domain: fmt.Sprintf("http://%v:%v", host, port), + Host: host, + Port: port, + ConnectTimeout: connecttimeout, + Timeout: timeout, + MaxIdleConnsPerHost: maxidleconnsperhost, + } + + return configRes, nil +} + diff --git a/bmp-pronoea/controllers/baseController.go b/bmp-pronoea/controllers/baseController.go new file mode 100644 index 0000000..4b492e4 --- /dev/null +++ b/bmp-pronoea/controllers/baseController.go @@ -0,0 +1,111 @@ +package controllers + +import ( + "encoding/json" + "fmt" + "git.jd.com/bmp-pronoea/common/util" + "git.jd.com/bmp-pronoea/models/alert" + "git.jd.com/bmp-pronoea/models/rules" + "github.com/astaxie/beego" + "github.com/astaxie/beego/logs" +) + +const ( + /* + API_OK = 10000 + API_ARGUMENTS_ERROR = 20040 + API_NO_ARGUMENTS = 20041 + API_UNKOWN_ERROR = 20050 + API_INTERNAL_ERROR = 20051 + + */ + + HTTP_STATUS_SUCCESS = 200 + + HTTP_STATUS_BAD_REQUEST = 400 + HTTP_STATUS_FORBIDDEN = 403 + HTTP_STATUS_NOT_FOUND = 404 + HTTP_STATUS_INTERNAL = 500 + + DOWNLOAD = "download" +) + +type BaseController struct { + beego.Controller + resp HttpCommonResponse +} + +type HttpCommonResponse struct { + Code int + RequestId string + Message string + Result interface{} +} + +func (b *BaseController) GetHeader() map[string]string { + return map[string]string{ + "requestId": b.Ctx.Input.Header("X-Request-Id"), + } +} + +func (b *BaseController) Prepare() { + requestId, ok := b.GetHeader()["requestId"] + if !ok || requestId == "" { + if b.GetRequestId() == "" { + requestId = util.GetUuid() + } else { + requestId = b.GetRequestId() + } + } + b.Ctx.Input.SetData("requestId", requestId) +} + +func (b *BaseController) Finish() { + + res := b.Ctx.Input.GetData(DOWNLOAD) + if res == nil { + b.Ctx.Output.SetStatus(b.resp.Code) + b.Data["json"] = b.resp + b.ServeJSON() + + b, _ := json.Marshal(b.resp) + logs.Info(fmt.Sprintf("response : %v", string(b))) + } +} + +func (b *BaseController) GetRequestId() string { + if b.Ctx.Input.GetData("requestId") == nil { + return "" + } else { + return b.Ctx.Input.GetData("requestId").(string) + } +} + +func (b *BaseController) GetAlertModel(receiverType string) (ruleModel alert.IAlert, err error) { + err = nil + + switch receiverType { + case alert.RECEIVER_MODELS_BMP: + ruleModel = BmpAlertManagerModels + break + default: + err = fmt.Errorf("unknown receiver type:%v ", receiverType) + } + + return ruleModel, err +} + +func (b *BaseController) GetRuleModel(ruleType string) (ruleModel rules.IRule, err error) { + err = nil + + switch ruleType { + case rules.RULE_MODELS_BMPINBAND: + ruleModel = BmpInBandRuleModeles + break + default: + err = fmt.Errorf("unknown rule type:%v ", ruleType) + } + + return ruleModel, err +} + diff --git a/bmp-pronoea/controllers/init.go b/bmp-pronoea/controllers/init.go new file mode 100644 index 0000000..cf55db9 --- /dev/null +++ b/bmp-pronoea/controllers/init.go @@ -0,0 +1,19 @@ +package controllers + +import ( + "git.jd.com/bmp-pronoea/models/alert/bmpAlert" + "git.jd.com/bmp-pronoea/models/rules/bmpRules" +) + +// BmpInBandRuleModeles 获取规则 +var BmpInBandRuleModeles *bmpRules.BmpInBandMonitorRules + +// BmpAlertManagerModels 告警规则处理处理 +var BmpAlertManagerModels *bmpAlert.BmpAlertManagerModel + + +func init() { + BmpInBandRuleModeles = &bmpRules.BmpInBandMonitorRules{} + BmpAlertManagerModels = &bmpAlert.BmpAlertManagerModel{} +} + diff --git a/bmp-pronoea/controllers/prometheusAlertController.go b/bmp-pronoea/controllers/prometheusAlertController.go new file mode 100644 index 0000000..a03c77e --- /dev/null +++ b/bmp-pronoea/controllers/prometheusAlertController.go @@ -0,0 +1,62 @@ +package controllers + +import ( + "encoding/json" + "fmt" + "git.jd.com/bmp-pronoea/types/request" + "github.com/astaxie/beego/logs" +) + +type PrometheusAlertController struct { + BaseController +} + +// PrometheusAlertsReceive @Title PrometheusAlertsReceive +// @Description receive alert info +// @Param body body request.AlertReceiverRequest true "The alert info" +// @Success 200 {string} success +// @Failure 400 invalid request {message} +// @Failure 500 internal error +// @router /receiver [post] +func (c *PrometheusAlertController) PrometheusAlertsReceive() { + requestId := c.GetRequestId() + + c.resp.Code = HTTP_STATUS_SUCCESS + c.resp.RequestId = requestId + c.resp.Message = "success" + + queryByte := c.Ctx.Input.RequestBody + if queryByte == nil || len(queryByte) <= 0 { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = fmt.Sprintf("alert info empty! ") + return + } + + logs.Info(requestId, "pronoea receive alertmanager info is ", string(queryByte)) + + alertMsg := &request.AlertReceiverRequest{} + err := json.Unmarshal(queryByte, alertMsg) + if err != nil { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = fmt.Sprintf("request.AlertReceiverRequest json.Unmarshal fail:%v", err) + return + } + + alertModel, err := c.GetAlertModel(alertMsg.Receiver) + if err != nil { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = fmt.Sprintf("invalid receiver :%v", alertMsg.Receiver) + return + } + + err = alertModel.ReportAlerts(requestId, alertMsg) + if err != nil { + c.resp.Code = HTTP_STATUS_INTERNAL + c.resp.Message = err.Error() + return + } + + return +} + + diff --git a/bmp-pronoea/controllers/prometheusQueryController.go b/bmp-pronoea/controllers/prometheusQueryController.go new file mode 100644 index 0000000..638360f --- /dev/null +++ b/bmp-pronoea/controllers/prometheusQueryController.go @@ -0,0 +1,55 @@ +package controllers + +import ( + "encoding/json" + "fmt" + "git.jd.com/bmp-pronoea/models/query" + "git.jd.com/bmp-pronoea/types/request" + "github.com/astaxie/beego/logs" +) + +type PrometheusQueryController struct { + BaseController +} + +// PrometheusSearchSamples @Title PrometheusSearchSamples +// @Description write yaml rule +// @Param body body request.MetricRangeQueryRequest true "The query info" +// @Success 200 {string} success +// @Failure 400 invalid request {message} +// @Failure 500 internal error +// @router / [post] +func (c *PrometheusQueryController) PrometheusSearchSamples() { + requestId := c.GetRequestId() + + c.resp.Code = HTTP_STATUS_SUCCESS + c.resp.RequestId = requestId + c.resp.Message = "success" + + queryByte := c.Ctx.Input.RequestBody + if queryByte == nil || len(queryByte) <= 0 { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = fmt.Sprintf("rule info empty! ") + return + } + + logs.Info(requestId, fmt.Sprintf("PrometheusSearchSamples param is %v", string(queryByte))) + + req := &request.MetricRangeQueryRequest{} + err := json.Unmarshal(queryByte, req) + if err != nil { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = fmt.Sprintf("json.Unmarshal param error:%v", err) + return + } + + samples, err := query.SearchPrometheusSamples(requestId, req) + if err != nil { + c.resp.Code = HTTP_STATUS_INTERNAL + c.resp.Message = err.Error() + return + } + + c.resp.Result = samples + return +} diff --git a/bmp-pronoea/controllers/prometheusRulesController.go b/bmp-pronoea/controllers/prometheusRulesController.go new file mode 100644 index 0000000..f29ccc4 --- /dev/null +++ b/bmp-pronoea/controllers/prometheusRulesController.go @@ -0,0 +1,176 @@ +package controllers + +import ( + "encoding/json" + "fmt" + "git.jd.com/bmp-pronoea/common/util" + "git.jd.com/bmp-pronoea/types/request" + "github.com/astaxie/beego/logs" +) + +type PrometheusRulesController struct { + BaseController +} + +// PrometheusRulesWrite @Title PrometheusRulesWrite +// @Description write yaml rule +// @Param body body request.RulesRequest true "The rule info" +// @Success 200 {string} success +// @Failure 400 invalid request {message} +// @Failure 500 internal error +// @router /write [post] +func (c *PrometheusRulesController) PrometheusRulesWrite() { + requestId := c.GetRequestId() + + c.resp.Code = HTTP_STATUS_SUCCESS + c.resp.RequestId = requestId + c.resp.Message = "success" + + queryByte := c.Ctx.Input.RequestBody + if queryByte == nil || len(queryByte) <= 0 { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = fmt.Sprintf("rule info empty! ") + return + } + + logs.Info(requestId, fmt.Sprintf("PrometheusRulesWrite param is %v", string(queryByte))) + + req := &request.RulesRequest{} + err := json.Unmarshal(queryByte, req) + if err != nil { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = fmt.Sprintf("json.Unmarshal param error:%v, %v", err, string(queryByte)) + return + } + + err = req.Validate(req) + if err != nil { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = err.Error() + return + } + + for _, tmp := range req.Rules { + if err = tmp.Validate(tmp); err != nil { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = err.Error() + return + } + + for _, tri := range tmp.TriggerOption { + if err = tri.Validate(tri); err != nil { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = err.Error() + return + } + } + + err = tmp.NoticeOption.Validate(tmp.NoticeOption) + if err != nil { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = err.Error() + return + } + } + + ruleModel, err := c.GetRuleModel(req.Source) + if err != nil { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = fmt.Sprintf("invalid source :%v", req.Source) + return + } + + err = ruleModel.WriteRule(requestId, string(queryByte)) + if err != nil { + c.resp.Code = HTTP_STATUS_INTERNAL + c.resp.Message = err.Error() + return + } + + return +} + +// PrometheusRulesDelete @Title PrometheusRulesDelete +// @Description delete yaml rule +// @Param body body request.RulesDeleteRequest true "The rule id info" +// @Success 200 {string} success +// @Failure 400 invalid request {message} +// @Failure 500 internal error +// @router /delete [post] +func (c *PrometheusRulesController) PrometheusRulesDelete() { + requestId := c.GetRequestId() + + c.resp.Code = HTTP_STATUS_SUCCESS + c.resp.RequestId = requestId + c.resp.Message = "success" + + queryByte := c.Ctx.Input.RequestBody + if queryByte == nil || len(queryByte) <= 0 { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = fmt.Sprintf("param empty !") + return + } + + logs.Info(requestId, fmt.Sprintf("PrometheusRulesDelete param is %v", string(queryByte))) + + req := &request.RulesDeleteRequest{} + err := json.Unmarshal(queryByte, req) + if err != nil { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = fmt.Sprintf("json.Unmarshal param error:%v", err) + return + } + + ruleModel, err := c.GetRuleModel(req.Source) + if err != nil { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = fmt.Sprintf("invalid source :%v", req.Source) + return + } + err = ruleModel.DeleteRules(requestId, req.RuleIds, req.Source) + if err != nil { + c.resp.Code = HTTP_STATUS_INTERNAL + c.resp.Message = fmt.Sprintf("delete [%v-%v]rule fail: %v", req.RuleIds, req.Source, err) + return + } + + return +} + +// PrometheusRulesList @Title PrometheusRulesList +// @Description delete yaml rule +// @Param source query string true "The rule source" +// @Success 200 {string} success +// @Failure 400 invalid request {message} +// @Failure 500 internal error +// @router /list [get] +func (c *PrometheusRulesController) PrometheusRulesList() { + requestId := c.GetRequestId() + + c.resp.Code = HTTP_STATUS_SUCCESS + c.resp.RequestId = requestId + c.resp.Message = "success" + + source := c.GetString("source", "") + if util.IsEmpty(source) { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = fmt.Sprintf("param source empty !") + return + } + + ruleModel, err := c.GetRuleModel(source) + if err != nil { + c.resp.Code = HTTP_STATUS_BAD_REQUEST + c.resp.Message = fmt.Sprintf("invalid source :%v", source) + return + } + ruleList, err := ruleModel.RulesList(requestId, source) + if err != nil { + c.resp.Code = HTTP_STATUS_INTERNAL + c.resp.Message = fmt.Sprintf("get rule list error : %v, %v ", err, source) + return + } + + c.resp.Result = ruleList + return +} \ No newline at end of file diff --git a/bmp-pronoea/dao/api/apiRequest.go b/bmp-pronoea/dao/api/apiRequest.go new file mode 100644 index 0000000..894a5ca --- /dev/null +++ b/bmp-pronoea/dao/api/apiRequest.go @@ -0,0 +1,5 @@ +package api + +type IBaseApiRequest interface { + Decode() (map[string]interface{}, error) +} \ No newline at end of file diff --git a/bmp-pronoea/dao/api/baseApi.go b/bmp-pronoea/dao/api/baseApi.go new file mode 100644 index 0000000..35774f9 --- /dev/null +++ b/bmp-pronoea/dao/api/baseApi.go @@ -0,0 +1,217 @@ +package api + +import ( + "encoding/json" + "fmt" + "git.jd.com/bmp-pronoea/common/util" + "git.jd.com/bmp-pronoea/config" + "github.com/astaxie/beego/logs" + "io/ioutil" + "reflect" + "strconv" + "strings" + "sync" +) + +const ( + //服务 + PROMETHEUS_API = "prometheus-api" + PUSHGATEWAY_API = "pushgateway-api" + BMP_API = "bmp-api" + + //参数类型 + PARAMS_TYPE_QUERY = "query" + PARAMS_TYPE_JSON = "json" + PARAMS_TYPE_FORM = "form" + PARAMS_TYPE_URLENCODED = "urlencoded" + PARAMS_TYPE_ARRAY_JSON = "array_json" + +) + +var ( + ApiMap = make(map[string]IBaseApi) + Locker sync.Mutex +) + +type IBaseApi interface { + ServiceConfig(string) error + GetBaseApi() *BaseApi + GetRequestHeader(int64) map[string]string +} + +type BaseApi struct { + Apis map[string]*UrlPath + Host string + Domain string + Config map[string]string + ConnectTimeOut int + TimeOut int + MaxIdleConnsPerHost int + Options *Options +} + +type UrlPath struct { + Method string + Path string +} + +type Options struct { + Attributes map[string]interface{} + Data map[string]IBaseApiRequest + Headers map[string]string +} + +func (a *BaseApi) getURL(apiName string) (*UrlPath, error) { + if urlPath, ok := a.Apis[apiName]; ok { + return urlPath, nil + } + return nil, fmt.Errorf("%s apiname not found", apiName) +} + +func (a *BaseApi) ParseConfig(configPath string) (interface{}, error) { + data, err := ioutil.ReadFile(configPath) + if err != nil { + logs.Error("read config failed:" + err.Error()) + return nil, err + } + + var config interface{} + err = json.Unmarshal(data, &config) + if err != nil { + logs.Error("json parse config failed:" + err.Error()) + return nil, err + } + + return config, nil +} + +func (a *BaseApi) ParseConfigByHeader(header string) (*config.HttpConfig, error) { + return config.HttpServerConfigByHeader(header) +} + + +func GetApi(name string) (IBaseApi, error) { + api, ok := ApiMap[name] + if !ok { + return nil, fmt.Errorf("unknown api %s, %v", name, ApiMap) + } + return api, nil +} + +func Send(requestId string, a IBaseApi, apiName string) ([]byte, error) { + base := a.GetBaseApi() + urlPath, err := base.getURL(apiName) + if err != nil { + return nil, err + } + //url中的替换参数 + u := urlPath.Path + if len(base.Options.Attributes) > 0 { + for k, v := range base.Options.Attributes { + switch v.(type) { + case string: + u = strings.Replace(u, "{"+k+"}", v.(string), 1) + case int: + u = strings.Replace(u, "{"+k+"}", strconv.Itoa(v.(int)), 1) + } + } + } + + params := make(map[string]string) + body := "" + + if base.Options.Data != nil { + //处理query参数 + if data, ok := base.Options.Data[PARAMS_TYPE_QUERY]; ok { + query, err := data.Decode() + if err != nil { + return nil, err + } + //利用反射处理不同的结构体变量类型 + typeData := reflect.TypeOf(data).Elem() + for k, v := range query { + switch v.(type) { + case json.Number: + for i := 0; i < typeData.NumField(); i++ { + tag := typeData.Field(i).Tag.Get("json") + ret := strings.Split(tag, util.SEPARATOR_COMMA) + if ret[0] == k { + dataType := typeData.Field(i).Type.Name() + if dataType == "int64" || dataType == "int32" || dataType == "int" { + res, _ := v.(json.Number).Int64() + params[k] = strconv.Itoa(int(res)) + } else if dataType == "float64" || dataType == "float32" { + res, _ := v.(json.Number).Float64() + params[k] = fmt.Sprintf("%.2f", res) + } else if dataType == "string" { + params[k] = v.(json.Number).String() + } + break + } + } + case string: + params[k] = v.(string) + } + } + } + //处理application/json参数 + if data, ok := base.Options.Data[PARAMS_TYPE_JSON]; ok { + bodyData, err := json.Marshal(data) + if err != nil { + return nil, err + } + body = string(bodyData) + base.Options.Headers["Content-Type"] = "application/json" + } else if data, ok = base.Options.Data[PARAMS_TYPE_ARRAY_JSON]; ok { + bodyData, err := json.Marshal(data) + if err != nil { + return nil, err + } + body = fmt.Sprintf("[%s]", string(bodyData)) + base.Options.Headers["Content-Type"] = "application/json" + } else if data, ok = base.Options.Data[PARAMS_TYPE_URLENCODED]; ok { //处理application/x-www-form-urlencoded参数 + urlencoded, err := data.Decode() + if err != nil { + return nil, err + } + for k, v := range urlencoded { + body += k + "=" + fmt.Sprintf("%s", v) + "&" + } + body = strings.Trim(body, "&") + base.Options.Headers["Content-Type"] = "application/x-www-form-urlencoded" + } else if data, ok = base.Options.Data[PARAMS_TYPE_FORM]; ok { //处理multipart/form-data参数 + form, err := data.Decode() + if err != nil { + return nil, err + } + for k, v := range form { + body += k + "=" + fmt.Sprintf("%s", v) + ";" + } + body = strings.Trim(body, ";") + base.Options.Headers["Content-Type"] = "multipart/form-data" + } + } + + reqURL := base.Domain + u + base.Options.Headers["X-Request-Id"] = requestId + //Locker.Unlock() + response, err := util.DoHttpRequest( + requestId, + reqURL, + base.Host, + urlPath.Method, + body, + params, + base.Options.Headers, + base.ConnectTimeOut, + base.TimeOut, + base.MaxIdleConnsPerHost, + ) + if err != nil { + logs.Info(requestId, fmt.Sprintf("do http request error:%v, params:%v", err, params)) + return nil, err + } + + logs.Info(requestId, fmt.Sprintf("do http response:%s", string(response))) + return response, nil +} diff --git a/bmp-pronoea/dao/api/bmpApi/bmpAlertRequest.go b/bmp-pronoea/dao/api/bmpApi/bmpAlertRequest.go new file mode 100644 index 0000000..20bb9a1 --- /dev/null +++ b/bmp-pronoea/dao/api/bmpApi/bmpAlertRequest.go @@ -0,0 +1,37 @@ +package bmpApi + +import ( + "bytes" + "encoding/json" +) + +type BmpAlertRequest struct { + Alerts []*BmpAlertDetail `json:"alerts"` +} + +type BmpAlertDetail struct { + RuleName string `json:"ruleName" validate:"required"` //规则名称 + RuleID string `json:"ruleId" validate:"required"` + InstanceID string `json:"instanceId" validate:"required"` + Trigger string `json:"trigger" validate:"required"` //触发条件 + CalculationUnit string `json:"calculationUnit" validate:"required"` //样本单位 + AlertValue string `json:"alertValue" validate:"required"` //告警值 + AlertTimestamp int64 `json:"alertTimestamp" validate:"required"`//告警时间戳 + AlertPeriod int `json:"alertPeriod" validate:"required"` //告警持续时间 +} + +func (p *BmpAlertRequest) Decode() (map[string]interface{}, error) { + var err error + data, err := json.Marshal(p) + if err != nil { + return nil, err + } + mapData := make(map[string]interface{}) + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + if err = decoder.Decode(&mapData); err != nil { + return nil, err + } + + return mapData, nil +} diff --git a/bmp-pronoea/dao/api/bmpApi/bmpAlertResponse.go b/bmp-pronoea/dao/api/bmpApi/bmpAlertResponse.go new file mode 100644 index 0000000..66c4097 --- /dev/null +++ b/bmp-pronoea/dao/api/bmpApi/bmpAlertResponse.go @@ -0,0 +1,13 @@ +package bmpApi + +type BmpAlertResponse struct { + ReqiestId string `json:"reqiestId"` + Error *BmpAlertErrorResponse `json:"error"` + Result map[string]interface{} `json:"result"` +} + +type BmpAlertErrorResponse struct { + Code int `json:"code"` + Message string `json:"message"` + Status string `json:"result"` +} diff --git a/bmp-pronoea/dao/api/bmpApi/bmpApi.go b/bmp-pronoea/dao/api/bmpApi/bmpApi.go new file mode 100644 index 0000000..e5b357e --- /dev/null +++ b/bmp-pronoea/dao/api/bmpApi/bmpApi.go @@ -0,0 +1,81 @@ +package bmpApi + +import ( + "fmt" + "git.jd.com/bmp-pronoea/common/util" + "git.jd.com/bmp-pronoea/dao/api" + "github.com/astaxie/beego" + "os" +) + +type BmpApi struct { + api.BaseApi +} + +// 方法名 +const ( + REPORT_ALERT = "reportAlert" // 上报报警 +) + + +var apis = map[string]*api.UrlPath{ + REPORT_ALERT: { + Method: "POST", + Path: "/v1/monitorAlert/addAlert", + }, +} + +func (a *BmpApi) ServiceConfig(configHeader string) error { + networkConfig, err := a.ParseConfigByHeader(configHeader) + if err != nil { + return err + } + + a.Host = networkConfig.Host + a.Domain = networkConfig.Domain + a.TimeOut = networkConfig.Timeout + a.ConnectTimeOut = networkConfig.ConnectTimeout + a.MaxIdleConnsPerHost = networkConfig.MaxIdleConnsPerHost + + authorization := beego.AppConfig.String(fmt.Sprintf("%v.authorization", configHeader)) + if util.IsEmpty(authorization) { + return fmt.Errorf("%v.authorization config empty ", configHeader) + } + a.Config["Authorization"] = authorization + + return nil +} + +func (a *BmpApi) GetBaseApi() *api.BaseApi { + return &a.BaseApi +} + +func (a *BmpApi) GetRequestHeader(timeStamp int64) map[string]string { + headers := make(map[string]string, 0) + headers["Authorization"] = a.Config["Authorization"] + headers["Timestamp"] = fmt.Sprintf("%v", timeStamp) + + return headers +} + +func NewBmpApi() (*BmpApi, error) { + a := &BmpApi{ + api.BaseApi{ + Apis: apis, + Config: make(map[string]string), + }, + } + if err := a.ServiceConfig("bmpopenapiconsole"); err != nil { + return nil, err + } + return a, nil +} + +func init() { + a, err := NewBmpApi() + if err != nil { + fmt.Printf("init bmp api error:%s", err.Error()) + os.Exit(1) + } + api.ApiMap[api.BMP_API] = a +} diff --git a/bmp-pronoea/dao/api/bmpApi/exec/reportAlertInfo.go b/bmp-pronoea/dao/api/bmpApi/exec/reportAlertInfo.go new file mode 100644 index 0000000..ed98b37 --- /dev/null +++ b/bmp-pronoea/dao/api/bmpApi/exec/reportAlertInfo.go @@ -0,0 +1,46 @@ +package exec + +import ( + "encoding/json" + "fmt" + "git.jd.com/bmp-pronoea/common/util" + "git.jd.com/bmp-pronoea/dao/api" + "git.jd.com/bmp-pronoea/dao/api/bmpApi" +) + +func ReportAlertInfoToBmp(requestId string, req *bmpApi.BmpAlertRequest) error { + api.Locker.Lock() + defer api.Locker.Unlock() + + a, err := api.GetApi(api.BMP_API) + if err != nil { + return err + } + base := a.GetBaseApi() + + currentTime := util.GetCurrentTimestamp() + headers := a.GetRequestHeader(currentTime) + headers["Traceid"] = requestId + + base.Options = &api.Options{ + Headers: headers, + Data: map[string]api.IBaseApiRequest{ + api.PARAMS_TYPE_JSON:req, + }, + } + + resp, err := api.Send(requestId, a, bmpApi.REPORT_ALERT) + if err != nil { + return err + } + getMetricRangeDataResp := new(bmpApi.BmpAlertResponse) + if err = json.Unmarshal(resp, getMetricRangeDataResp); err != nil { + return err + } + + if getMetricRangeDataResp.Error != nil { + return fmt.Errorf("report alert info error %v", getMetricRangeDataResp) + } + + return nil +} diff --git a/bmp-pronoea/dao/api/prometheusApi/exec/metricQueryRange.go b/bmp-pronoea/dao/api/prometheusApi/exec/metricQueryRange.go new file mode 100644 index 0000000..a781aaa --- /dev/null +++ b/bmp-pronoea/dao/api/prometheusApi/exec/metricQueryRange.go @@ -0,0 +1,39 @@ +package exec + +import ( + "encoding/json" + "git.jd.com/bmp-pronoea/common/util" + "git.jd.com/bmp-pronoea/dao/api" + "git.jd.com/bmp-pronoea/dao/api/prometheusApi" +) + +func GetMetricRangeDataApi(requestId string, queryReq *prometheusApi.PrometheusRangeQueryRequest) (*prometheusApi.MetricDataListResponse, error) { + api.Locker.Lock() + defer api.Locker.Unlock() + + a, err := api.GetApi(api.PROMETHEUS_API) + if err != nil { + return nil, err + } + base := a.GetBaseApi() + + currentTime := util.GetCurrentTimestamp() + headers := a.GetRequestHeader(currentTime) + base.Options = &api.Options{ + Headers: headers, + Data: map[string]api.IBaseApiRequest{ + api.PARAMS_TYPE_QUERY: queryReq, + }, + } + + resp, err := api.Send(requestId, a, prometheusApi.METRIC_RANGE_QUERY) + if err != nil { + return nil, err + } + getMetricRangeDataResp := new(prometheusApi.MetricDataListResponse) + if err = json.Unmarshal(resp, getMetricRangeDataResp); err != nil { + return nil, err + } + + return getMetricRangeDataResp, nil +} \ No newline at end of file diff --git a/bmp-pronoea/dao/api/prometheusApi/exec/prometheusOperator.go b/bmp-pronoea/dao/api/prometheusApi/exec/prometheusOperator.go new file mode 100644 index 0000000..2db21f7 --- /dev/null +++ b/bmp-pronoea/dao/api/prometheusApi/exec/prometheusOperator.go @@ -0,0 +1,44 @@ +package exec + +import ( + "fmt" + "git.jd.com/bmp-pronoea/common/util" + "git.jd.com/bmp-pronoea/dao/api" + "git.jd.com/bmp-pronoea/dao/api/prometheusApi" + "github.com/astaxie/beego/logs" +) + +func PrometheusReload(requestId string) error { + api.Locker.Lock() + defer api.Locker.Unlock() + + a, err := api.GetApi(api.PROMETHEUS_API) + if err != nil { + return err + } + base := a.GetBaseApi() + + currentTime := util.GetCurrentTimestamp() + headers := a.GetRequestHeader(currentTime) + base.Options = &api.Options{ + Headers: headers, + } + + resp, err := api.Send(requestId, a, prometheusApi.PROMETHEUS_RELOAD) + logs.Info(requestId, fmt.Sprintf("reload prometheus res %v, err is %v", resp, err)) + + if err != nil { + return err + } + return nil +} + +func PrometheusReloadByShell(requestId string) error { + cmdRes, err := util.CmdRunWithOutput("curl -X POST http://127.0.0.1:9090/-/reload") + if err != nil || util.StringsContains(cmdRes, "fail") { + logs.Info(requestId,fmt.Sprintf("reload promethus by shell error %v, res:%v ", err, cmdRes)) + return fmt.Errorf("reload prometus by shell error %v,res:%v ", err, cmdRes) + } + logs.Info(requestId, fmt.Sprintf("reload promethus by shell success, res:%v ", cmdRes)) + return nil +} diff --git a/bmp-pronoea/dao/api/prometheusApi/prometheusApi.go b/bmp-pronoea/dao/api/prometheusApi/prometheusApi.go new file mode 100644 index 0000000..22dc523 --- /dev/null +++ b/bmp-pronoea/dao/api/prometheusApi/prometheusApi.go @@ -0,0 +1,83 @@ +package prometheusApi + +import ( + "fmt" + "git.jd.com/bmp-pronoea/dao/api" + "os" +) + +type PrometheusApi struct { + api.BaseApi +} + +// 方法名 +const ( + METRIC_RANGE_QUERY = "metricQueryRange" // 查询样本数据 + PROMETHEUS_RELOAD = "prometheusReload" // 重启prometheus +) + + +var apis = map[string]*api.UrlPath{ + METRIC_RANGE_QUERY: { + Method: "GET", + Path: "/api/v1/query_range", + }, + PROMETHEUS_RELOAD: { + Method: "POST", + Path: "/-/reload", + }, +} + +func (a *PrometheusApi) ServiceConfig(configHeader string) error { + networkConfig, err := a.ParseConfigByHeader(configHeader) + if err != nil { + return err + } + + a.Host = networkConfig.Host + a.Domain = networkConfig.Domain + a.TimeOut = networkConfig.Timeout + a.ConnectTimeOut = networkConfig.ConnectTimeout + a.MaxIdleConnsPerHost = networkConfig.MaxIdleConnsPerHost + + return nil +} + +func (a *PrometheusApi) GetBaseApi() *api.BaseApi { + return &a.BaseApi +} + +func (a *PrometheusApi) GetRequestHeader(timeStamp int64) map[string]string { + headers := make(map[string]string, 0) + headers["Timestamp"] = fmt.Sprintf("%v", timeStamp) + /* + headers["Authentication"] = a.Config["auth"] + md5Base := fmt.Sprintf("%v%v%v", a.Config["ak"], a.Config["sk"], timeStamp) + sign := util.GetMd5(md5Base) + headers["Signature"] = sign + */ + + return headers +} + +func NewPrometheusApi() (*PrometheusApi, error) { + a := &PrometheusApi{ + api.BaseApi{ + Apis: apis, + Config: make(map[string]string), + }, + } + if err := a.ServiceConfig("prometheus"); err != nil { + return nil, err + } + return a, nil +} + +func init() { + a, err := NewPrometheusApi() + if err != nil { + fmt.Printf("init prometheus api error:%s", err.Error()) + os.Exit(1) + } + api.ApiMap[api.PROMETHEUS_API] = a +} \ No newline at end of file diff --git a/bmp-pronoea/dao/api/prometheusApi/prometheusRequest.go b/bmp-pronoea/dao/api/prometheusApi/prometheusRequest.go new file mode 100644 index 0000000..852f789 --- /dev/null +++ b/bmp-pronoea/dao/api/prometheusApi/prometheusRequest.go @@ -0,0 +1,30 @@ +package prometheusApi + +import ( + "bytes" + "encoding/json" +) + +type PrometheusRangeQueryRequest struct { + Query string `json:"query"` + StartUTCTime string `json:"start"` + EndUTCTime string `json:"end"` + Step string `json:"step"` +} + +func (p *PrometheusRangeQueryRequest) Decode() (map[string]interface{}, error) { + var err error + data, err := json.Marshal(p) + if err != nil { + return nil, err + } + mapData := make(map[string]interface{}) + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + if err = decoder.Decode(&mapData); err != nil { + return nil, err + } + + return mapData, nil +} + diff --git a/bmp-pronoea/dao/api/prometheusApi/prometheusResponse.go b/bmp-pronoea/dao/api/prometheusApi/prometheusResponse.go new file mode 100644 index 0000000..43c8c86 --- /dev/null +++ b/bmp-pronoea/dao/api/prometheusApi/prometheusResponse.go @@ -0,0 +1,26 @@ +package prometheusApi + + +type BasePrometheusResponse struct { + Status string `json:"status"` + ErrorMsg string `json:"error"` + ErrorType string `json:"errorType"` + Data interface{} `json:"data"` +} + +type MetricDataListResponse struct { + BasePrometheusResponse + RequestId string `json:"requestId"` + Data *MetricDataInfo `json:"data"` +} + + +type MetricDataInfo struct { + ResultType string `json:"resultType"` + Result []*MetricDataDetail `json:"result"` +} + +type MetricDataDetail struct { + Metric map[string]string `json:"metric"` + Values [][]interface{} `json:"values"` +} diff --git a/bmp-pronoea/dao/api/pushgatewayApi/exec/pushgatewayOperator.go b/bmp-pronoea/dao/api/pushgatewayApi/exec/pushgatewayOperator.go new file mode 100644 index 0000000..2a177bd --- /dev/null +++ b/bmp-pronoea/dao/api/pushgatewayApi/exec/pushgatewayOperator.go @@ -0,0 +1,35 @@ +package exec + +import ( + "fmt" + "git.jd.com/bmp-pronoea/common/util" + "git.jd.com/bmp-pronoea/dao/api" + "git.jd.com/bmp-pronoea/dao/api/pushgatewayApi" + "github.com/astaxie/beego/logs" +) + +func WipePushgatewayDataApi(requestId string) error { + api.Locker.Lock() + defer api.Locker.Unlock() + + a, err := api.GetApi(api.PUSHGATEWAY_API) + if err != nil { + return err + } + base := a.GetBaseApi() + + currentTime := util.GetCurrentTimestamp() + headers := a.GetRequestHeader(currentTime) + base.Options = &api.Options{ + Headers: headers, + } + + resp, err := api.Send(requestId, a, pushgatewayApi.WIPE_ALL_DATA) + if err != nil { + return err + } + + logs.Info(requestId, fmt.Sprintf("delete pushgateway data res %v", resp)) + + return nil +} diff --git a/bmp-pronoea/dao/api/pushgatewayApi/pushgatewayApi.go b/bmp-pronoea/dao/api/pushgatewayApi/pushgatewayApi.go new file mode 100644 index 0000000..060b03e --- /dev/null +++ b/bmp-pronoea/dao/api/pushgatewayApi/pushgatewayApi.go @@ -0,0 +1,77 @@ +package pushgatewayApi + +import ( + "fmt" + "git.jd.com/bmp-pronoea/dao/api" + "os" +) + +type PushgatewayApi struct { + api.BaseApi +} + +// 方法名 +const ( + WIPE_ALL_DATA = "wipeAllData" // 删除全部数据 +) + +var apis = map[string]*api.UrlPath{ + WIPE_ALL_DATA: { + Method: "PUT", + Path: "/api/v1/admin/wipe", + }, +} + +func (a *PushgatewayApi) ServiceConfig(configHeader string) error { + networkConfig, err := a.ParseConfigByHeader(configHeader) + if err != nil { + return err + } + + a.Host = networkConfig.Host + a.Domain = networkConfig.Domain + a.TimeOut = networkConfig.Timeout + a.ConnectTimeOut = networkConfig.ConnectTimeout + a.MaxIdleConnsPerHost = networkConfig.MaxIdleConnsPerHost + + return nil +} + +func (a *PushgatewayApi) GetBaseApi() *api.BaseApi { + return &a.BaseApi +} + +func (a *PushgatewayApi) GetRequestHeader(timeStamp int64) map[string]string { + headers := make(map[string]string, 0) + headers["Timestamp"] = fmt.Sprintf("%v", timeStamp) + /* + headers["Authentication"] = a.Config["auth"] + md5Base := fmt.Sprintf("%v%v%v", a.Config["ak"], a.Config["sk"], timeStamp) + sign := util.GetMd5(md5Base) + headers["Signature"] = sign + */ + + return headers +} + +func NewPushgatewayApi() (*PushgatewayApi, error) { + a := &PushgatewayApi{ + api.BaseApi{ + Apis: apis, + Config: make(map[string]string), + }, + } + if err := a.ServiceConfig("pushgateway"); err != nil { + return nil, err + } + return a, nil +} + +func init() { + a, err := NewPushgatewayApi() + if err != nil { + fmt.Printf("init pushgateway api error:%s", err.Error()) + os.Exit(1) + } + api.ApiMap[api.PUSHGATEWAY_API] = a +} diff --git a/bmp-pronoea/doc/pronoea.md b/bmp-pronoea/doc/pronoea.md new file mode 100644 index 0000000..704c407 --- /dev/null +++ b/bmp-pronoea/doc/pronoea.md @@ -0,0 +1,176 @@ +# pronoea接口文档 +* [ChangeLog](#ChangeLog) + +* [环境](#环境) + +* [HTTP响应体定义](#HTTP响应体定义) + +## ChangeLog + +| 版本 | 变更内容 | 变更时间 | 变更人 | +| ------ | ---------- | ---------- | ----------------------- | +| V1.0.0 | 初始化版本 | 2024/06/20 | 马赛迪(masaidi1@jd.com) | + + + +## 环境 + + +* 测试环境 + +``` + +``` + +* 预发环境 + +``` +10.226.192.114:9999 +``` + +* 正式环境 + +``` +用户局域网,无正式环境 +``` + +## HTTP响应体定义 + +``` +{ + "Code": xxxxx, //错误码 10000 表示成功,其他为失败 + "RequestId": "xxxxxx", //请求id + "Message": "success", //错误信息 + "Result": {} +} +``` + +* [样本数据相关接口](#样本数据相关接口) + + * [时间范围查询样本数据](#时间范围查询样本数据) + +* [告警规则接口](#告警规则接口) + + * [写告警规则接口](#写告警规则接口) + * [删除告警规则接口](#删除告警规则接口) + +## 样本数据相关接口 + +### 时间范围查询样本数据 +```bash +POST /api/query +``` + +#### 请求参数 +| 参数名 | 类型 | 是否必须 | 默认值 | 描述 | +| ------------------ | ------ | -------- | ------ | --------- | +| metricName | String | 是 | --- | 样本名称,目前只有bmp_monitor | +| labels | map[string]string | 否 | --- | 标签查询条件 | +| startTime | int64 | 是 | --- | 11位起始时间戳 | +| endTime | int64 | 是 | --- | 11位结束时间戳 | +| step | int | 是 | --- | 步长 | + +#### 响应示例 + +```json +{ + "Code": 10000, + "RequestId": "5badf577-ed9c-47c6-ad48-b201cd2159e0", + "Message": "success", + "Result": { + "data": [ + { + "timestamp": 1718313728, // 时间点 + "value": "35774971904" // 时间点对应的值 + } + ], + "query": { //接收到的查询条件 + "metricName": "bmp_monitor", + "labels": null, + "startTime": 1718313728, + "endTime": 1718313788, + "step": 60 + } + } +} +``` + +## 告警规则接口 + +### 写告警规则接口 +```bash +POST /api/rules/write +``` + +#### 请求参数 + +#### 带内监控告警规则入参 +| 参数名 | 类型 | 是否必须 | 默认值 | 描述 | +| ------------------ | ------ | -------- | ------ | --------- | +| ruleId | String | 是 | --- | 规则id | +| source | String | 是 | --- | 规则来源| +| dimension | String | 否 | --- | 维度 | +| dimensionName | String | 否 | --- | 维度名称 | +| resource | String | 否 | --- | 资源类型 | +| resourceName | String | 否 | --- | 资源类型名称 | +| triggerOption | []*RuleTrigger | 是 | --- | 触发条件 | +| noticeOption | *RuleNotice | 是 | --- | 通知策略 | +| instanceIds | []String | 是 | --- | 实例ID列表 | +| deviceTag| String | 否 | --- | 盘符、挂载点、网口 | + +##### RuleTrigger结构定义 +| 参数名 | 类型 | 是否必须 | 默认值 | 描述 | +| ------------------ | ------ | -------- | ------ | --------- | +| metric | String | 是 | --- | 监控指标 | +| metricName | String | 是 | --- | 监控指标名称| +| period | int | 是 | --- | 周期 分钟位单位 | +| calculation | String | 是 | --- | 计算方式[min,max,avg,sum] | +| calculationUnit | String | 否 | --- | 单位 | +| operation | String | 是 | --- | 比较方式 [> >= < <= == !=]或者[gt gte lt lte eq neq] | +| threshold | Float64 | 是 | --- | 阈值 | +| times | int | 是 | --- | 持续周期数 [1, 2, 3, 5, 10, 15, 30, 60] | +| instanceIds | []String | 是 | --- | 实例ID列表 | +| noticeLevel| int | 是 | --- | 告警级别 [1表示一般,2表示严重,3表示紧急] | + +##### RuleNotice结构定义 +| 参数名 | 类型 | 是否必须 | 默认值 | 描述 | +| ------------------ | ------ | -------- | ------ | --------- | +| noticePeriod | String | 是 | --- | 通知周期(分钟) [5 10 15 30 60 180 360 720 1440] | + +#### 响应示例 + +```json +{ + "Code": 10000, + "RequestId": "341ae5b5-a55b-4e88-8e5d-81adfade81c2", + "Message": "success", + "Result": null +} +``` + +### 删除告警规则接口 +```bash +POST /api/rules/delete +``` + +#### 请求参数 + +#### 带内监控告警规则入参 +| 参数名 | 类型 | 是否必须 | 默认值 | 描述 | +| ------------------ | ------ | -------- | ------ | --------- | +| ruleId | String | 是 | --- | 规则id | +| source | String | 是 | --- | 规则来源| + +#### 响应示例 + +```json +{ + "Code": 10000, + "RequestId": "01343512-c291-48f1-82f3-c6589edb6028", + "Message": "success", + "Result": { + "ruleId": "19f449d9-0574-4b69-8878-64a2e380c3ab", + "source": "bmpInBand" + } +} +``` diff --git a/bmp-pronoea/go.mod b/bmp-pronoea/go.mod new file mode 100644 index 0000000..2abbadf --- /dev/null +++ b/bmp-pronoea/go.mod @@ -0,0 +1,33 @@ +module git.jd.com/bmp-pronoea + +go 1.17 + +require ( + github.com/astaxie/beego v1.12.3 + github.com/beego/beego/v2 v2.0.1 + github.com/satori/go.uuid v1.2.0 + gopkg.in/yaml.v2 v2.4.0 +) + +require ( + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.1.1 // indirect + github.com/golang/protobuf v1.4.2 // indirect + github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 // indirect + github.com/hashicorp/golang-lru v0.5.4 // indirect + github.com/jtolds/gls v4.20.0+incompatible // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/prometheus/client_golang v1.7.0 // indirect + github.com/prometheus/client_model v0.2.0 // indirect + github.com/prometheus/common v0.10.0 // indirect + github.com/prometheus/procfs v0.1.3 // indirect + github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect + github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d // indirect + github.com/smartystreets/goconvey v1.6.4 // indirect + golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect + golang.org/x/net v0.0.0-20201021035429-f5854403a974 // indirect + golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f // indirect + golang.org/x/text v0.3.3 // indirect + google.golang.org/protobuf v1.23.0 // indirect +) diff --git a/bmp-pronoea/go.sum b/bmp-pronoea/go.sum new file mode 100644 index 0000000..79c839c --- /dev/null +++ b/bmp-pronoea/go.sum @@ -0,0 +1,280 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= +github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk= +github.com/astaxie/beego v1.12.3 h1:SAQkdD2ePye+v8Gn1r4X6IKZM1wd28EyUOVQ3PDSOOQ= +github.com/astaxie/beego v1.12.3/go.mod h1:p3qIm0Ryx7zeBHLljmd7omloyca1s4yu1a8kM1FkpIA= +github.com/beego/beego/v2 v2.0.1 h1:07a7Z0Ok5vbqyqh+q53sDPl9LdhKh0ZDy3gbyGrhFnE= +github.com/beego/beego/v2 v2.0.1/go.mod h1:8zyHi1FnWO1mZLwTn62aKRIZF/aIKvkCBB2JYs+eqQI= +github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ= +github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60= +github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= +github.com/coreos/etcd v3.3.25+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U= +github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= +github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= +github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= +github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk= +github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDuKuq+uX4v1fulaMbA/7ZLLhjc85h7chZGBCQ= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= +github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.7.0 h1:wCi7urQOGBsYcQROHqpUUX4ct84xp40t9R9JX0FuA/U= +github.com/prometheus/client_golang v1.7.0/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.10.0 h1:RyRA7RzGXQZiW+tGMr7sxa85G1z0yOpM1qq5c8lNawc= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.1.3 h1:F0+tqvhOksq22sc6iCHF5WGlWjdwj92p0udFh1VFBS8= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= +github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= +github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= +github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s= +github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= +github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= +go.etcd.io/etcd v3.3.25+incompatible/go.mod h1:yaeTdrJi5lOmYerz05bd8+V7KubZs8YSFZfzsF9A6aI= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f h1:+Nyd8tzPX9R7BWHguqsrbFdRx3WQ/1ib8I44HXV5yTA= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.5/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= diff --git a/bmp-pronoea/main.go b/bmp-pronoea/main.go new file mode 100644 index 0000000..18f84fa --- /dev/null +++ b/bmp-pronoea/main.go @@ -0,0 +1,62 @@ +package main + +import ( + "fmt" + "git.jd.com/bmp-pronoea/config" + _ "git.jd.com/bmp-pronoea/routers" + "git.jd.com/bmp-pronoea/service/crontab" + "github.com/astaxie/beego/logs" + "github.com/beego/beego/v2/task" + "os" + + "github.com/astaxie/beego" +) + +func main() { + + if err := initLog() ; err != nil { + fmt.Printf("init log error: %s", err.Error()) + os.Exit(1) + } + + err := config.ParseConfigAppConf() + if err != nil { + logs.Info("system init error %v ", err) + fmt.Printf("system init error %v ", err) + os.Exit(1) + } + + logs.Info("bmp-pronoea runing... ... ") + + crontab.InitCrontab() + defer task.StopTask() + + if beego.BConfig.RunMode == "dev" { + beego.BConfig.WebConfig.DirectoryIndex = true + beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger" + } + beego.Run() +} + +func initLog() error { + level, err := beego.AppConfig.Int("log.level") + if err != nil { + return fmt.Errorf("get log.level error : %v", err) + } + + filePath := beego.AppConfig.String("log.file") + + maxDays, err := beego.AppConfig.Int("log.days") + if err != nil { + return fmt.Errorf("get log.days error : %v", err) + } + + logPerm := beego.AppConfig.String("log.perm") + logRotatePerm := beego.AppConfig.String("log.rotateperm") + + logConfigStr := fmt.Sprintf("{\"filename\": \"%s\", \"level\":%d, \"maxdays\":%d, \"perm\":\"%s\", \"rotateperm\":\"%s\" }", + filePath, level, maxDays, logPerm, logRotatePerm) + logs.SetLogger("file", logConfigStr) + + return nil +} diff --git a/bmp-pronoea/models/alert/baseAlert.go b/bmp-pronoea/models/alert/baseAlert.go new file mode 100644 index 0000000..78b80b2 --- /dev/null +++ b/bmp-pronoea/models/alert/baseAlert.go @@ -0,0 +1,25 @@ +package alert + +import ( + "fmt" + "git.jd.com/bmp-pronoea/types/request" +) + +const ( + RECEIVER_MODELS_BMP = "bmpAlertReceiver" +) + +type IAlert interface { + ReportAlerts(requestId string, alertInfo *request.AlertReceiverRequest) error +} + +type BaseAlert struct { + IAlert +} + +func (b *BaseAlert) ReportAlerts (requestId string, alertInfo *request.AlertReceiverRequest) error { + if alertInfo == nil || alertInfo.Alerts == nil || len(alertInfo.Alerts) <= 0 { + return fmt.Errorf("alert info empty ! ") + } + return nil +} diff --git a/bmp-pronoea/models/alert/bmpAlert/bmpAlertManagerModel.go b/bmp-pronoea/models/alert/bmpAlert/bmpAlertManagerModel.go new file mode 100644 index 0000000..aa093fa --- /dev/null +++ b/bmp-pronoea/models/alert/bmpAlert/bmpAlertManagerModel.go @@ -0,0 +1,153 @@ +package bmpAlert + +import ( + "encoding/json" + "fmt" + "git.jd.com/bmp-pronoea/common/util" + "git.jd.com/bmp-pronoea/dao/api/bmpApi" + "git.jd.com/bmp-pronoea/dao/api/bmpApi/exec" + "git.jd.com/bmp-pronoea/models" + "git.jd.com/bmp-pronoea/models/alert" + "git.jd.com/bmp-pronoea/models/rules/bmpRules" + "git.jd.com/bmp-pronoea/types/request" + "github.com/astaxie/beego/logs" + "net/url" + "strconv" +) + +type BmpAlertManagerModel struct { + alert.BaseAlert +} + +func (b *BmpAlertManagerModel) ReportAlerts(requestId string, alertMsg *request.AlertReceiverRequest) error { + err := b.BaseAlert.ReportAlerts(requestId, alertMsg) + if err != nil { + return err + } + + bmpAlertMsgDetailList, err := b.turnReportAlertInfoList(requestId, alertMsg) + if err != nil { + logs.Info(requestId, fmt.Sprintf("turn bmp report alert info error %v", err)) + return fmt.Errorf("turn bmp report alert info error %v", err) + } + if bmpAlertMsgDetailList == nil || len(bmpAlertMsgDetailList) <= 0 { + logs.Info(requestId, fmt.Sprintf("bmp report alert info do not have firing %v", err)) + return nil + } + bmpAlertMsg := &bmpApi.BmpAlertRequest{ + Alerts : bmpAlertMsgDetailList, + } + return exec.ReportAlertInfoToBmp(requestId, bmpAlertMsg) +} + +func (b *BmpAlertManagerModel) turnReportAlertInfoList(requestId string, alertMsg *request.AlertReceiverRequest) ([]*bmpApi.BmpAlertDetail, error) { + if alertMsg == nil || alertMsg.Alerts == nil || len(alertMsg.Alerts) <= 0 { + return nil, fmt.Errorf("alert receive info empty !") + } + + currentTime := util.GetCurrentTimestamp() + bmpAlertMsg := make([]*bmpApi.BmpAlertDetail, 0) + for _, alertInfo := range alertMsg.Alerts { + if alertInfo.Status != request.ALERT_RECEIVE_STATUS_FIRING { + continue + } + if alertInfo.Labels == nil || len(alertInfo.Labels) < 0 { + continue + } + + tiggerTmp, err := b.turnReportAlertInfoTrigger(requestId,alertInfo.Labels) + if err != nil { + logs.Info(requestId, fmt.Sprintf("turnReportAlertInfoList fail, turn tigger error %v", err)) + continue + } + triggerJsonByte, err := json.Marshal(tiggerTmp) + if err != nil { + logs.Info(requestId, fmt.Sprintf("alert info labels json.Marshal error %v %v", err, alertInfo.Labels)) + continue + //return nil, fmt.Errorf("alert info labels json.Marshal error %v", err) + } + + tmpMsg := &bmpApi.BmpAlertDetail{} + tmpMsg.RuleName = alertInfo.Labels[bmpRules.SYSTEM_BMPLABELS_ALERTNAME] + tmpMsg.RuleID = alertInfo.Labels[bmpRules.CUSTOM_BMPLABELS_RULEID] + tmpMsg.InstanceID = alertInfo.Labels[bmpRules.CUSTOM_BMPLABELS_INSTANCEID] + tmpMsg.CalculationUnit = alertInfo.Labels[bmpRules.CUSTOM_BMPLABELS_CALCULATION_UNIT] + tmpMsg.Trigger = url.QueryEscape(string(triggerJsonByte)) + + alertValue := alertInfo.Annotations[bmpRules.CUSTOM_BMPLABELS_CURRENTVALUE] + alertValueFloat64, err := util.TurnStringToFloat64(alertValue, 2) + if err != nil { + logs.Info(requestId, fmt.Sprintf("turn alert value error %v %v", err, alertValue)) + continue + } + + if metricTmp, exist := alertInfo.Labels[bmpRules.CUSTOM_BMPLABELS_METRIC]; exist { + if unitConversion, exist := models.MetricNameUnitConversionMap[metricTmp]; exist { + alertValueFloat64 = alertValueFloat64 / unitConversion + } + } + alertValue = strconv.FormatFloat(alertValueFloat64, 'f', 2, 64) + + tmpMsg.AlertValue = alertValue + tmpMsg.AlertTimestamp = currentTime + + tmpMsg.AlertPeriod = tiggerTmp.Period * tiggerTmp.Times + + bmpAlertMsg = append(bmpAlertMsg, tmpMsg) + } + return bmpAlertMsg, nil +} + +func (b *BmpAlertManagerModel) turnReportAlertInfoTrigger(requestId string, labelsMap map[string]string) (*request.RuleTrigger, error) { + if labelsMap == nil || len(labelsMap) <= 0 { + return nil, fmt.Errorf("labels info empty! ") + } + + trigger := &request.RuleTrigger{} + trigger.Metric = labelsMap[bmpRules.CUSTOM_BMPLABELS_METRIC] + trigger.Period = 0 + if _, exist := labelsMap[bmpRules.CUSTOM_BMPLABELS_PERIOD]; exist { + tmpInt, err := strconv.Atoi(labelsMap[bmpRules.CUSTOM_BMPLABELS_PERIOD]) + if err == nil { + trigger.Period = tmpInt + } else { + logs.Info(requestId, fmt.Sprintf("turn labelsMap[period] to int error %v", err)) + } + } + + trigger.Times = 0 + if _, exist := labelsMap[bmpRules.CUSTOM_BMPLABELS_TIMES]; exist { + tmpInt, err := strconv.Atoi(labelsMap[bmpRules.CUSTOM_BMPLABELS_TIMES]) + if err == nil { + trigger.Times = tmpInt + } else { + logs.Info(requestId, fmt.Sprintf("turn labelsMap[times] to int error %v", err)) + } + } + + trigger.NoticeLevel = 0 + if _, exist := labelsMap[bmpRules.CUSTOM_BMPLABELS_NOTICELEVEL]; exist { + tmpInt, err := strconv.Atoi(labelsMap[bmpRules.CUSTOM_BMPLABELS_NOTICELEVEL]) + if err == nil { + trigger.NoticeLevel = tmpInt + } else { + logs.Info(requestId, fmt.Sprintf("turn labelsMap[noticeLevel] to int error %v", err)) + } + } + + trigger.Threshold = 0 + if _, exist := labelsMap[bmpRules.CUSTOM_BMPLABELS_THRESHOID]; exist { + tmpFloat64, err := strconv.ParseFloat(labelsMap[bmpRules.CUSTOM_BMPLABELS_THRESHOID], 64) + if err == nil { + trigger.Threshold = tmpFloat64 + } else { + logs.Info(requestId, fmt.Sprintf("turn labelsMap[threshold] to float error %v", err)) + } + } + + trigger.Calculation = labelsMap[bmpRules.CUSTOM_BMPLABELS_CALCULATION] + trigger.CalculationUnit = labelsMap[bmpRules.CUSTOM_BMPLABELS_CALCULATION_UNIT] + trigger.Operation = labelsMap[bmpRules.CUSTOM_BMPLABELS_OPERATION] + + return trigger, nil +} \ No newline at end of file diff --git a/bmp-pronoea/models/common.go b/bmp-pronoea/models/common.go new file mode 100644 index 0000000..cfd94e7 --- /dev/null +++ b/bmp-pronoea/models/common.go @@ -0,0 +1,14 @@ +package models + +const ( + //METRIC_NAME_BMP = "bmp_monitor_gauge" + METRIC_NAME_BMP_GAUGE = "bmp_monitor_gauge" + METRIC_NAME_BMP_COUNTER = "bmp_monitor_counter" + +) + +// 告警规则中的单位转换 +var MetricNameUnitConversionMap = map[string]float64{ + "bmp.memory.used" : 1000000000, + "bmp.disk.used" : 1000000000, +} diff --git a/bmp-pronoea/models/pushgateway/pushGatewayModel.go b/bmp-pronoea/models/pushgateway/pushGatewayModel.go new file mode 100644 index 0000000..a57c61b --- /dev/null +++ b/bmp-pronoea/models/pushgateway/pushGatewayModel.go @@ -0,0 +1,7 @@ +package pushgateway + +import "git.jd.com/bmp-pronoea/dao/api/pushgatewayApi/exec" + +func WipeAllPushgatewayData(requestId string) error { + return exec.WipePushgatewayDataApi(requestId) +} diff --git a/bmp-pronoea/models/query/metricSampleQueryModel.go b/bmp-pronoea/models/query/metricSampleQueryModel.go new file mode 100644 index 0000000..0e52bbc --- /dev/null +++ b/bmp-pronoea/models/query/metricSampleQueryModel.go @@ -0,0 +1,154 @@ +package query + +import ( + "encoding/json" + "fmt" + "git.jd.com/bmp-pronoea/common/util" + "git.jd.com/bmp-pronoea/dao/api/prometheusApi" + "git.jd.com/bmp-pronoea/dao/api/prometheusApi/exec" + "git.jd.com/bmp-pronoea/types/request" + "git.jd.com/bmp-pronoea/types/response" + "github.com/astaxie/beego/logs" + "strconv" +) + +//查询prometheus 样本数据 +func SearchPrometheusSamples ( + requestId string, + req *request.MetricRangeQueryRequest) ([]*response.MetricRangeQueryResponse, error) { + + if err := req.Validate(req); err != nil { + return nil, err + } + + queryParamMap, err := CreateQueryParamList(req.TableName, req.SampleMethod, req.Step, req.Labels) + if err != nil { + return nil, fmt.Errorf("search prometheus sample fail %v", err) + } + /* + queryParam, err := CreateQueryParam(req.TableName, req.SampleMethod, req.Step, req.Labels) + if err != nil { + return nil, fmt.Errorf("search prometheus sample fail %v", err) + } + */ + + startUtcTime, err := util.GetUtcTimeByTimeStamp(req.StartTime) + if err != nil { + return nil, fmt.Errorf("search prometheus sample fail %v", err) + } + endUtcTime, err := util.GetUtcTimeByTimeStamp(req.EndTime) + if err != nil { + return nil, fmt.Errorf("search prometheus sample fail %v", err) + } + + resultList := make([]*response.MetricRangeQueryResponse, 0) + for labelsTmp, queryParam := range queryParamMap { + queryReq := &prometheusApi.PrometheusRangeQueryRequest{ + Query : queryParam, + StartUTCTime : startUtcTime, + EndUTCTime : endUtcTime, + Step : fmt.Sprintf("%vs", req.Step), + } + + queryResp, err := exec.GetMetricRangeDataApi(requestId, queryReq) + if err != nil { + return nil, fmt.Errorf("search prometheus sample fail %v", err) + } + if queryResp.Status == "error" { + return nil, fmt.Errorf("search prometheus sample fail %v", queryResp.ErrorMsg) + } + + results := make([]*response.MetricRangeQueryResponse, 0) + if queryResp.Data == nil || queryResp.Data.Result == nil || len(queryResp.Data.Result) <= 0 { + return results, nil + } + + results, err = turnPrometheusDataToResponse(requestId, labelsTmp, queryResp.Data.Result, req) + if err != nil { + return nil, fmt.Errorf("search prometheus sample fail %v", err) + } + resultList = append(resultList, results...) + } + + return resultList, nil +} + +func turnPrometheusDataToResponse(requestId, queryLables string, result []*prometheusApi.MetricDataDetail, req *request.MetricRangeQueryRequest) ([]*response.MetricRangeQueryResponse, error) { + returnResList := make([]*response.MetricRangeQueryResponse, 0) + + funcMap := make(map[string]int, 0) + if req.Func != nil && len(req.Func) > 0 { + for operator, value := range req.Func { + if value == 0 || util.IsEmpty(operator){ + continue + } + funcMap[operator] = value + } + } + + for _, tmp := range result { + if tmp.Values == nil || len(tmp.Values) <= 0 { + continue + } + + dataList := make([]*response.MetricRangeQueryData, 0) + for _, value := range tmp.Values { + if value == nil || len(value) != 2 { + continue + } + tmpDetail := &response.MetricRangeQueryData{} + tmpDetail.Timestamp = util.TurnInterfaceToInt64(value[0]) + tmpDetail.Value = util.TurnInterfaceToString(value[1]) + if len(funcMap) > 0 { + valueFloat64, err := util.TurnStringToFloat64(tmpDetail.Value, 2) + if err == nil { + for operator, operatorVal := range funcMap { + if operator == "/" { + tmpDetail.Value = strconv.FormatFloat( + valueFloat64 / float64(operatorVal), + 'f', 2, 64) + } + if operator == "*" { + tmpDetail.Value = strconv.FormatFloat( + valueFloat64 * float64(operatorVal), + 'f', 2, 64) + } + } + } else { + logs.Info(requestId, fmt.Sprintf("字符串转换Float64失败 %v, %v ", err, tmpDetail.Value)) + } + } + + dataList = append(dataList, tmpDetail) + } + + labelsTmp := make(map[string]string, 0) + err := json.Unmarshal([]byte(queryLables), &labelsTmp) + if err != nil { + return nil, fmt.Errorf("json.Unmarshal error %v, %v", err, queryLables) + } + for key, value := range labelsTmp { + delete(labelsTmp, key) + keyTmp := util.UnderLineToHumpCamel(key) + labelsTmp[keyTmp] = value + } + + tmpQuery := &request.MetricRangeQueryRequest{ + TableName: req.TableName, + StartTime: req.StartTime, + EndTime: req.EndTime, + Step: req.Step, + Labels: labelsTmp, + Func: req.Func, + SampleMethod: req.SampleMethod, + } + returnRes := &response.MetricRangeQueryResponse{ + Data : dataList, + Query: tmpQuery, + } + + returnResList = append(returnResList, returnRes) + } + return returnResList, nil + +} diff --git a/bmp-pronoea/models/query/queryCommonModel.go b/bmp-pronoea/models/query/queryCommonModel.go new file mode 100644 index 0000000..46ba397 --- /dev/null +++ b/bmp-pronoea/models/query/queryCommonModel.go @@ -0,0 +1,139 @@ +package query + +import ( + "encoding/json" + "fmt" + "git.jd.com/bmp-pronoea/common" + "git.jd.com/bmp-pronoea/common/util" + "git.jd.com/bmp-pronoea/models" + "git.jd.com/bmp-pronoea/models/rules/bmpRules" + "strings" +) + +const ( + PROMEQL_OPERATOR_REGULAR = "=~" + PROMEQL_OPERATOR_EQ = "=" +) + +var MetricLabelsOperatorRelation = map[string]map[string]string{ + models.METRIC_NAME_BMP_GAUGE : map[string]string { + "metric_name" : PROMEQL_OPERATOR_REGULAR, + }, + models.METRIC_NAME_BMP_COUNTER : map[string]string { + "metric_name" : PROMEQL_OPERATOR_REGULAR, + }, +} + +func CreateQueryParam(metricName, sampleMethod string, step int, labels map[string]string) (string, error) { + if util.IsEmpty(metricName) { + return "", fmt.Errorf("metric name empty! ") + } + queryParam := metricName + if labels == nil || len(labels) <= 0 { + return queryParam, nil + } + + queryLabels := make([]string, 0) + rateTemplate := "" + for labelName, labelValue := range labels { + if util.IsEmpty(labelName) { + continue + } + + operatorTmp := PROMEQL_OPERATOR_EQ + if _, exist := MetricLabelsOperatorRelation[metricName]; exist { + if tmp, existT := MetricLabelsOperatorRelation[metricName][labelName]; existT { + operatorTmp = tmp + } + } + + queryLabel := fmt.Sprintf("%v%v'%v'", labelName, operatorTmp, labelValue) + queryLabels = append(queryLabels, queryLabel) + + if labelName == "metric_name" { + if value, exist := bmpRules.SampleDefaultMethodMap[labelValue]; exist { + rateTemplate = value + } + } + + //是否需要添加rate查询 + /* + if util.IsEmpty(rateTemplate) && labelName == "metric_name" { + // 有这样的 (bmp.network.packets.ingress)|(bmp.network.packets.egress),取第一个 + labelFirstValue := labelValue + labelValueList := strings.Split(labelValue, common.DELIMITER_VERTICAL) + if labelValueList != nil && len(labelValueList) >= 1 { + labelFirstValue = labelValueList[0] + labelFirstValue = strings.Replace(labelFirstValue, common.CHARACTER_LEFT_PARENTHESIS, "", -1) + labelFirstValue = strings.Replace(labelFirstValue, common.CHARACTER_RIGTH_PARENTHESIS, "", -1) + } + + logs.Info("metric_name query %v, %v", labelValue, labelFirstValue) + + if value, exist := bmpRules.SampleDefaultMethodMap[labelFirstValue]; exist { + rateTemplate = value + } + } + */ + } + + if queryLabels != nil && len(queryLabels) > 0 { + queryParam = fmt.Sprintf("%v{%v}", queryParam, strings.Join(queryLabels, util.SEPARATOR_COMMA)) + } + + if util.IsNotEmpty(rateTemplate) { + //rate(bmp_monitor_counter{metric_name="bmp.disk.bytes.read"}[2m]) + queryParam = fmt.Sprintf(rateTemplate, queryParam, fmt.Sprintf("%vs", step+60)) + } + + if tmpTpl, exist := bmpRules.AlertExprMethodMap[sampleMethod]; exist { + queryParam = fmt.Sprintf(tmpTpl, queryParam) + } + + return queryParam, nil +} + +func CreateQueryParamList(metricName, sampleMethod string, step int, labels map[string]string) (map[string]string, error) { + metricNameValue := "" + _, exist := labels["metric_name"] + if exist { + metricNameValue = labels["metric_name"] + } + metricNameValueList := make([]string, 0) + if util.IsNotEmpty(metricNameValue) { + metricNameValueList = strings.Split(metricNameValue, common.DELIMITER_VERTICAL) + } + + queryParamList := make(map[string]string, 0) + + if len(metricNameValueList) <= 0 { + queryParam, err := CreateQueryParam(metricName, sampleMethod, step, labels) + if err != nil { + return nil, err + } + labelsByte, err := json.Marshal(labels) + if err != nil { + return nil, fmt.Errorf("json.Marshal error:%v, %v", err, labels) + } + queryParamList[string(labelsByte)] = queryParam + return queryParamList, nil + } + + //len(metricNameValueList) > 0 + for _, metricNameTmpValue := range metricNameValueList { + metricNameTmpValue = strings.Replace(metricNameTmpValue, common.CHARACTER_LEFT_PARENTHESIS, "", -1) + metricNameTmpValue = strings.Replace(metricNameTmpValue, common.CHARACTER_RIGTH_PARENTHESIS, "", -1) + + labels["metric_name"] = metricNameTmpValue + queryParam, err := CreateQueryParam(metricName, sampleMethod, step, labels) + if err != nil { + return nil, err + } + labelsByte, err := json.Marshal(labels) + if err != nil { + return nil, fmt.Errorf("json.Marshal error:%v, %v", err, labels) + } + queryParamList[string(labelsByte)] = queryParam + } + return queryParamList, nil +} diff --git a/bmp-pronoea/models/rules/baseRule.go b/bmp-pronoea/models/rules/baseRule.go new file mode 100644 index 0000000..983eb65 --- /dev/null +++ b/bmp-pronoea/models/rules/baseRule.go @@ -0,0 +1,174 @@ +package rules + +import ( + "fmt" + "git.jd.com/bmp-pronoea/common" + "git.jd.com/bmp-pronoea/common/util" + "git.jd.com/bmp-pronoea/config" + "git.jd.com/bmp-pronoea/dao/api/prometheusApi/exec" + "github.com/astaxie/beego/logs" + "io/ioutil" + "path/filepath" + "strings" +) + +const ( + RULE_MODELS_BMPINBAND = "bmpInBand" +) + +type IRule interface { + DeleteRules(requestId, ruleIds, source string) error + WriteRule(requestId, ruleContentJson string) error + RulesList(requestId, source string) (interface{}, error) + //WriteAllRule(requestId string) error + //TransforRuleYaml(requestId, ruleContentJson string) ([]byte, error) +} + +type BaseRule struct { + IRule + //RulesPath string //规则文件目录 +} + +func (b *BaseRule) checkRulePath() error { + if util.IsEmpty(config.SysConfig.PrometheusRulePath) { + return fmt.Errorf("rules path empty ! ") + } + return nil +} + +// DeleteRule 删除规则 +func (b *BaseRule) DeleteRules(requestId, ruleIds, source string) error { + if err := b.checkRulePath(); err != nil { + return err + } + + if util.IsEmpty(ruleIds) || util.IsEmpty(source) { + return fmt.Errorf("rule ids or source empty! ") + } + + ruleIdList := strings.Split(ruleIds, common.DELIMITER_COMMA) + if ruleIdList == nil || len(ruleIdList) <= 0 { + return fmt.Errorf("rule ids empty! ") + } + + filePathList := make([]string, 0) + for _, ruleId := range ruleIdList { + if util.IsEmpty(ruleId) { + continue + } + fileName := fmt.Sprintf("%v_%v", source, ruleId) + filePath := fmt.Sprintf("%s/%s", config.SysConfig.PrometheusRulePath, fileName + ".yml") + filePathList = append(filePathList, filePath) + } + + if filePathList == nil || len(filePathList) <=0 { + return fmt.Errorf("rule file path list empty ! ") + } + + // 循环删除一下 + for _, filePath := range filePathList { + err := b.DeleteRule(requestId, filePath) + if err != nil { + return fmt.Errorf("delete rule file error %v, %v", filePath, err) + } + } + + // 重启prometheus + err := b.ReloadPromethus(requestId) + if err != nil{ + logs.Info(requestId, fmt.Sprintf("remove rule file success[%v], but reload prometus error %v ", ruleIds, err)) + return fmt.Errorf("remove rule file success[%v], but reload prometus error %v ", ruleIds, err) + } + logs.Info(requestId, fmt.Sprintf("remove rule file success[%v], reload prometus success, res:%v ", requestId, ruleIds)) + return nil +} + +func (b *BaseRule) DeleteRule(requestId, filePath string) error { + if util.IsEmpty(filePath) { + return fmt.Errorf("rule file path empty ! ") + } + + if !util.FileIsExist(filePath) { + logs.Info(requestId, fmt.Sprintf("file not exist[%v], return success ", filePath)) + return nil + } + + err := util.RemoveFile(filePath) + if err != nil { + logs.Info(requestId,fmt.Sprintf("remove rule file error %v, file:%v", err, filePath)) + return fmt.Errorf("remove rule file error %v, file:%v", err, filePath) + } + return nil +} + +func (b *BaseRule) WriteRule(requestId, ruleContentJson string) error { + if err := b.checkRulePath(); err != nil { + return err + } + if util.IsEmpty(ruleContentJson) { + return fmt.Errorf("rule content empty! ") + } + return nil +} + +func (b *BaseRule) WriteRuleAndReload(requestId, filePath string, yamlByte []byte, reload bool) error { + err := util.CheckParent(filePath) + if err != nil { + logs.Info(requestId, fmt.Sprintf("write rule file error %v, file:%v", err, filePath)) + return err + } + err = ioutil.WriteFile(filePath, yamlByte, 0644) + if err != nil { + logs.Info(requestId, fmt.Sprintf("write rule file error %v, file:%v", err, filePath)) + return err + } + + // 重启 + if reload { + return b.ReloadPromethus(requestId) + } + + return nil +} + +func (b *BaseRule) ReloadPromethus(requestId string) error { + err := exec.PrometheusReload(requestId) + if err != nil { + return err + } + return nil +} + +func (b *BaseRule) RulesList(requestId, source string) (interface{}, error){ + return nil, nil +} + +func (b *BaseRule) GetRulesFileList(requestId, source string) (map[string][]byte, error) { + if err := b.checkRulePath(); err != nil { + return nil, err + } + + fileNameMatch := fmt.Sprintf("/%v_*.yml", source) + fileLists, err := filepath.Glob(config.SysConfig.PrometheusRulePath + fileNameMatch) + if err != nil { + return nil, err + } + + ruleFileMap := make(map[string][]byte, 0) + if fileLists == nil || len(fileLists) <= 0 { + return ruleFileMap, nil + } + + for _, ruleFilePath := range fileLists { + bytes, err := ioutil.ReadFile(ruleFilePath) + if err != nil { + logs.Info(requestId, fmt.Sprintf("read file:%v error:%v", ruleFilePath, err)) + return nil, err + } + ruleFileMap[ruleFilePath] = bytes + } + + return ruleFileMap, nil +} + + diff --git a/bmp-pronoea/models/rules/bmpRules/bmpInBandMonitorRules.go b/bmp-pronoea/models/rules/bmpRules/bmpInBandMonitorRules.go new file mode 100644 index 0000000..8251e98 --- /dev/null +++ b/bmp-pronoea/models/rules/bmpRules/bmpInBandMonitorRules.go @@ -0,0 +1,216 @@ +package bmpRules + +import ( + "encoding/json" + "fmt" + "git.jd.com/bmp-pronoea/common/util" + "git.jd.com/bmp-pronoea/config" + "git.jd.com/bmp-pronoea/models" + "git.jd.com/bmp-pronoea/models/rules" + "git.jd.com/bmp-pronoea/types/request" + "git.jd.com/bmp-pronoea/types/response" + "github.com/astaxie/beego/logs" + "gopkg.in/yaml.v2" + "reflect" + "strings" +) + +type BmpInBandMonitorRules struct { + rules.BaseRule +} + +// DeleteRule 删除规则 +func (b *BmpInBandMonitorRules) DeleteRules (requestId, ruleIds, source string) error { + return b.BaseRule.DeleteRules(requestId, ruleIds, source) +} + +func (b *BmpInBandMonitorRules) WriteRule(requestId, ruleContentJson string) error { + err := b.BaseRule.WriteRule(requestId, ruleContentJson) + if err != nil { + return err + } + + bmpRuleInfo := &request.RulesRequest{} + err = json.Unmarshal([]byte(ruleContentJson), &bmpRuleInfo) + if err != nil { + return err + } + + for _, ruleTmp := range bmpRuleInfo.Rules { + prometheusRule, err := b.createRuleContent(bmpRuleInfo.Source, ruleTmp) + if err != nil { + return err + } + filePath := fmt.Sprintf("%v/%v_%v.yml", + config.SysConfig.PrometheusRulePath, + bmpRuleInfo.Source, + ruleTmp.RuleId) + + ruleByte, err := yaml.Marshal(prometheusRule) + if err != nil { + return fmt.Errorf("yaml marshal error %v", err) + } + + // 同时写多个规则,写入时不重启,最后统一重新启动 + err = b.BaseRule.WriteRuleAndReload(requestId, filePath, ruleByte, false) + if err != nil { + logs.Info(requestId, fmt.Sprintf("write bmp rule error %v, %v", err, filePath)) + return err + } + } + + err = b.ReloadPromethus(requestId) + if err != nil { + logs.Info(requestId, fmt.Sprintf("write bmp rule success, but reload prometheus error %v, %v", err, ruleContentJson)) + return err + } + + return nil +} + +func (b *BmpInBandMonitorRules) createRuleContent(source string, req *request.RulesDetail) (*PrometheusRule, error) { + if err := req.Validate(req); err != nil { + return nil, err + } + + prometheusRuleGroupDetail := new(PrometheusRuleGroupDetail) + ruleName := fmt.Sprintf("%v_%v", source, req.RuleId) + prometheusRuleGroupDetail.Name = ruleName + + for _, instanceId := range req.InstanceIds { + if util.IsEmpty(instanceId) { + continue + } + for _, tigger := range req.TriggerOption { + //source_alarmId_instanceId_metricname_device + alertName := fmt.Sprintf(ALERT_NAME_TEMPLATE, + source, req.RuleId, instanceId, tigger.Metric, req.DeviceTag) + + if _, exist := AlertExprMethodMap[tigger.Calculation]; !exist { + continue + } + if _, exist := AlertExprOperatorMap[tigger.Operation]; !exist { + continue + } + + var expr string + if util.IsEmpty(req.DeviceTag) { + expr = fmt.Sprintf(ALERT_EXPR_DEVICE_WITHOUT, tigger.TableName, instanceId, tigger.Metric) + } else { + expr = fmt.Sprintf(ALERT_EXPR_DEVICE, tigger.TableName, instanceId, tigger.Metric, req.DeviceTag) + } + + //基础计算法 + if tmp, exist := SampleDefaultMethodMap[tigger.Metric]; exist { + expr = fmt.Sprintf(tmp, expr, fmt.Sprintf("%vm", tigger.Period + 1)) + } + + expr = fmt.Sprintf(AlertExprMethodMap[tigger.Calculation], expr) + + threshold := tigger.Threshold + if unitConversion, exist := models.MetricNameUnitConversionMap[tigger.Metric]; exist { + threshold = threshold * unitConversion + } + + expr = fmt.Sprintf("%v%v%v", expr, AlertExprOperatorMap[tigger.Operation], threshold) + + //持续时长 + forTimeLong := fmt.Sprintf("%vm", tigger.Times * tigger.Period) + + labels := make(map[string]interface{}, 0) + labels[CUSTOM_LABELS_NOTICE_PERIOD] = NOTICE_PERIOD_60_LABEL // 默认通知周期 + if tmpNoticePeriodLabel, exist := NoticePeriodMap[req.NoticeOption.NoticePeriod]; exist { + labels[CUSTOM_LABELS_NOTICE_PERIOD] = tmpNoticePeriodLabel + } + labels[CUSTOM_BMPLABELS_INSTANCEID] = instanceId + labels[CUSTOM_BMPLABELS_RULEID] = req.RuleId + + if tigger != nil { + tTigger := reflect.TypeOf(*tigger) + vTigger := reflect.ValueOf(*tigger) + for i := 1; i < tTigger.NumField(); i++ { + field := tTigger.Field(i) + value := vTigger.Field(i) + labels[util.HeadToLower(field.Name)] = value.Interface() + /* + switch value.Kind().String() { + case "int": + labels[field.Name] = fmt.Sprintf("%v", value.Int()) + break + case "float64": + labels[field.Name] = fmt.Sprintf("%v", value.Float()) + break + default: + labels[field.Name] = value.String() + break + } + */ + } + } + + tmpRule := &PrometheusRuleDetail{ + Alert : alertName, + Expr : expr, + For : forTimeLong, + Labels : labels, + } + tmpRule.Annotations.CurrentValue = "{{ $value }}" + prometheusRuleGroupDetail.Rules = append(prometheusRuleGroupDetail.Rules, tmpRule) + } + } + + prometheusRule := &PrometheusRule{ + Groups: make([]*PrometheusRuleGroupDetail, 0), + } + prometheusRule.Groups = append(prometheusRule.Groups, prometheusRuleGroupDetail) + + return prometheusRule, nil +} + +func (b *BmpInBandMonitorRules) RulesList(requestId, source string) (interface{}, error){ + rulesFileList, err := b.BaseRule.GetRulesFileList(requestId, source) + if err != nil { + logs.Info(requestId, fmt.Sprintf("get rule file list error %v %v", source, err)) + return nil, err + } + + ruleList := &response.PrometheusRuleListResponse{} + ruleList.Rules = make([]*response.PrometheusRuleListItem, 0) + + if rulesFileList == nil || len(rulesFileList) <= 0 { + return ruleList, nil + } + + for ruleFilePath, ruleByte := range rulesFileList { + ruleYmlObj := &PrometheusRule{} + err = yaml.Unmarshal(ruleByte, ruleYmlObj) + if err != nil { + logs.Info(requestId,fmt.Sprintf("Invalid rule %v, %v", ruleFilePath, err)) + } + + for _, detail := range ruleYmlObj.Groups { + if util.IsEmpty(detail.Name) || detail.Rules == nil || len(detail.Rules) <= 0 { + continue + } + ruleId := strings.Replace(detail.Name, fmt.Sprintf("%v_", source), "", 1) + instanceIds := make([]string, 0) + for _, tmpRule := range detail.Rules { + instanceId := util.TurnInterfaceToString(tmpRule.Labels[CUSTOM_BMPLABELS_INSTANCEID]) + instanceIds = append(instanceIds, instanceId) + } + + if instanceIds == nil || len(instanceIds) <= 0 { + continue + } + + ruleListDetail := &response.PrometheusRuleListItem{ + RuleId: ruleId, + InstanceIds : instanceIds, + } + + ruleList.Rules = append(ruleList.Rules, ruleListDetail) + } + } + + return ruleList, nil +} \ No newline at end of file diff --git a/bmp-pronoea/models/rules/bmpRules/define.go b/bmp-pronoea/models/rules/bmpRules/define.go new file mode 100644 index 0000000..9f72938 --- /dev/null +++ b/bmp-pronoea/models/rules/bmpRules/define.go @@ -0,0 +1,139 @@ +package bmpRules + +const ( + //BMP_METRIC_NAME = "bmp_monitor" + ALERT_NAME_TEMPLATE = "%v_%v_%v_%v_%v" // source_alarmId_instanceId_metricname_device + ALERT_EXPR_DEVICE = "%v{instance_id=\"%v\",metric_name=\"%v\",device=\"%v\"}" + ALERT_EXPR_DEVICE_WITHOUT = "%v{instance_id=\"%v\",metric_name=\"%v\"}" + + SAMPLE_DEFAULT_METHOD_TMP = "rate(%v[%v])" + + ALERT_EXPR_METHOD_MAX = "max" + ALERT_EXPR_METHOD_MIN = "min" + ALERT_EXPR_METHOD_SUM = "sum" + ALERT_EXPR_METHOD_AVG = "avg" + + ALERT_EXPR_OPERATOR_GT = ">" + ALERT_EXPR_OPERATOR_GT_CODE = "gt" + ALERT_EXPR_OPERATOR_GTE = ">=" + ALERT_EXPR_OPERATOR_GTE_CODE = "gte" + ALERT_EXPR_OPERATOR_LT = "<" + ALERT_EXPR_OPERATOR_LT_CODE = "lt" + ALERT_EXPR_OPERATOR_LTE = "<=" + ALERT_EXPR_OPERATOR_LTE_CODE = "lte" + ALERT_EXPR_OPERATOR_EQ = "==" + ALERT_EXPR_OPERATOR_EQ_CODE = "eq" + ALERT_EXPR_OPERATOR_NEQ = "!=" + ALERT_EXPR_OPERATOR_NEQ_CODE = "neq" + + //通知周期 5|10|15|30|60|180|360|720|1440 + NOTICE_PERIOD_5 = 5 + NOTICE_PERIOD_5_LABEL = "NoticePeriod-5m" + NOTICE_PERIOD_10 = 10 + NOTICE_PERIOD_10_LABEL = "NoticePeriod-10m" + NOTICE_PERIOD_15 = 15 + NOTICE_PERIOD_15_LABEL = "NoticePeriod-15m" + NOTICE_PERIOD_30 = 30 + NOTICE_PERIOD_30_LABEL = "NoticePeriod-30m" + NOTICE_PERIOD_60 = 60 + NOTICE_PERIOD_60_LABEL = "NoticePeriod-60m" + NOTICE_PERIOD_180 = 180 + NOTICE_PERIOD_180_LABEL = "NoticePeriod-180m" + NOTICE_PERIOD_720 = 720 + NOTICE_PERIOD_720_LABEL = "NoticePeriod-720m" + NOTICE_PERIOD_1440 = 1440 + NOTICE_PERIOD_1440_LABEL = "NoticePeriod-1440m" + + CUSTOM_LABELS_NOTICE_PERIOD = "noticePeriodLabel" + CUSTOM_BMPLABELS_RULEID = "ruleId" + CUSTOM_BMPLABELS_INSTANCEID = "instanceId" + CUSTOM_BMPLABELS_CURRENTVALUE = "currentValue" + CUSTOM_BMPLABELS_METRIC = "metric" + CUSTOM_BMPLABELS_CALCULATION = "calculation" + CUSTOM_BMPLABELS_CALCULATION_UNIT = "calculationUnit" + CUSTOM_BMPLABELS_PERIOD = "period" + CUSTOM_BMPLABELS_TIMES = "times" + CUSTOM_BMPLABELS_NOTICELEVEL = "noticeLevel" + CUSTOM_BMPLABELS_THRESHOID = "threshold" + CUSTOM_BMPLABELS_OPERATION = "operation" + + SYSTEM_BMPLABELS_ALERTNAME = "alertname" + + //需要rate计算的指标 + RATE_METRIC_DISK_READ = "bmp.disk.counts.read" + RATE_METRIC_DISK_WRITE = "bmp.disk.counts.write" + RATE_METRIC_NETWORK_INGRESS = "bmp.network.packets.ingress" + RATE_METRIC_NETWORK_EGRESS = "bmp.network.packets.egress" + RATE_METRIC_DISK_BYTESREAD = "bmp.disk.bytes.read" + RATE_METRIC_DISK_BYTESWRITE = "bmp.disk.bytes.write" + RATE_METRIC_NETWORK_BYTEINGRESS = "bmp.network.bytes.ingress" + RATE_METRIC_NETWORK_BYTEEGRESS = "bmp.network.bytes.egress" + +) + +var AlertExprOperatorMap = map[string]string { + ALERT_EXPR_OPERATOR_GT : ALERT_EXPR_OPERATOR_GT, + ALERT_EXPR_OPERATOR_GT_CODE : ALERT_EXPR_OPERATOR_GT, + ALERT_EXPR_OPERATOR_GTE : ALERT_EXPR_OPERATOR_GTE, + ALERT_EXPR_OPERATOR_GTE_CODE : ALERT_EXPR_OPERATOR_GTE, + ALERT_EXPR_OPERATOR_LT : ALERT_EXPR_OPERATOR_LT, + ALERT_EXPR_OPERATOR_LT_CODE : ALERT_EXPR_OPERATOR_LT, + ALERT_EXPR_OPERATOR_LTE : ALERT_EXPR_OPERATOR_LTE, + ALERT_EXPR_OPERATOR_LTE_CODE : ALERT_EXPR_OPERATOR_LTE, + ALERT_EXPR_OPERATOR_EQ : ALERT_EXPR_OPERATOR_EQ, + ALERT_EXPR_OPERATOR_EQ_CODE : ALERT_EXPR_OPERATOR_EQ, + ALERT_EXPR_OPERATOR_NEQ : ALERT_EXPR_OPERATOR_NEQ, + ALERT_EXPR_OPERATOR_NEQ_CODE : ALERT_EXPR_OPERATOR_NEQ, +} + +var AlertExprMethodMap = map[string]string { + ALERT_EXPR_METHOD_MAX : "max(%v)", + ALERT_EXPR_METHOD_MIN : "min(%v)", + ALERT_EXPR_METHOD_SUM : "sum(%v)", + ALERT_EXPR_METHOD_AVG : "avg(%v)", +} + +var NoticePeriodMap = map[int]string { + NOTICE_PERIOD_5 : NOTICE_PERIOD_5_LABEL, + NOTICE_PERIOD_10 : NOTICE_PERIOD_10_LABEL, + NOTICE_PERIOD_15 : NOTICE_PERIOD_15_LABEL, + NOTICE_PERIOD_30 : NOTICE_PERIOD_30_LABEL, + NOTICE_PERIOD_60 : NOTICE_PERIOD_60_LABEL, + NOTICE_PERIOD_180: NOTICE_PERIOD_180_LABEL, + NOTICE_PERIOD_720: NOTICE_PERIOD_720_LABEL, + NOTICE_PERIOD_1440 : NOTICE_PERIOD_1440_LABEL, +} + +var SampleDefaultMethodMap = map[string]string { + RATE_METRIC_DISK_READ : SAMPLE_DEFAULT_METHOD_TMP, + RATE_METRIC_DISK_WRITE : SAMPLE_DEFAULT_METHOD_TMP, + RATE_METRIC_NETWORK_INGRESS : SAMPLE_DEFAULT_METHOD_TMP, + RATE_METRIC_NETWORK_EGRESS : SAMPLE_DEFAULT_METHOD_TMP, + RATE_METRIC_DISK_BYTESREAD : SAMPLE_DEFAULT_METHOD_TMP, + RATE_METRIC_DISK_BYTESWRITE : SAMPLE_DEFAULT_METHOD_TMP, + RATE_METRIC_NETWORK_BYTEINGRESS : SAMPLE_DEFAULT_METHOD_TMP, + RATE_METRIC_NETWORK_BYTEEGRESS : SAMPLE_DEFAULT_METHOD_TMP, +} + + + +type PrometheusRule struct { + Groups []*PrometheusRuleGroupDetail `yaml:"groups"` +} + +type PrometheusRuleGroupDetail struct{ + Name string `yaml:"name"` + Rules []*PrometheusRuleDetail `yaml:"rules"` +} + +type PrometheusRuleDetail struct{ + Alert string `yaml:"alert"` + Expr string `yaml:"expr"` + For string `yaml:"for"` + Labels map[string]interface{} `yaml:"labels"` + Annotations struct { + Summary string `yaml:"summary"` + Description string `yaml:"description"` + CurrentValue string `yaml:"currentValue"` + } `yaml:"annotations"` +} diff --git a/bmp-pronoea/routers/commentsRouter_controllers.go b/bmp-pronoea/routers/commentsRouter_controllers.go new file mode 100644 index 0000000..8d4c334 --- /dev/null +++ b/bmp-pronoea/routers/commentsRouter_controllers.go @@ -0,0 +1,55 @@ +package routers + +import ( + "github.com/astaxie/beego" + "github.com/astaxie/beego/context/param" +) + +func init() { + + beego.GlobalControllerRouter["git.jd.com/bmp-pronoea/controllers:PrometheusAlertController"] = append(beego.GlobalControllerRouter["git.jd.com/bmp-pronoea/controllers:PrometheusAlertController"], + beego.ControllerComments{ + Method: "PrometheusAlertsReceive", + Router: "/receiver", + AllowHTTPMethods: []string{"post"}, + MethodParams: param.Make(), + Filters: nil, + Params: nil}) + + beego.GlobalControllerRouter["git.jd.com/bmp-pronoea/controllers:PrometheusQueryController"] = append(beego.GlobalControllerRouter["git.jd.com/bmp-pronoea/controllers:PrometheusQueryController"], + beego.ControllerComments{ + Method: "PrometheusSearchSamples", + Router: "/", + AllowHTTPMethods: []string{"post"}, + MethodParams: param.Make(), + Filters: nil, + Params: nil}) + + beego.GlobalControllerRouter["git.jd.com/bmp-pronoea/controllers:PrometheusRulesController"] = append(beego.GlobalControllerRouter["git.jd.com/bmp-pronoea/controllers:PrometheusRulesController"], + beego.ControllerComments{ + Method: "PrometheusRulesDelete", + Router: "/delete", + AllowHTTPMethods: []string{"post"}, + MethodParams: param.Make(), + Filters: nil, + Params: nil}) + + beego.GlobalControllerRouter["git.jd.com/bmp-pronoea/controllers:PrometheusRulesController"] = append(beego.GlobalControllerRouter["git.jd.com/bmp-pronoea/controllers:PrometheusRulesController"], + beego.ControllerComments{ + Method: "PrometheusRulesList", + Router: "/list", + AllowHTTPMethods: []string{"get"}, + MethodParams: param.Make(), + Filters: nil, + Params: nil}) + + beego.GlobalControllerRouter["git.jd.com/bmp-pronoea/controllers:PrometheusRulesController"] = append(beego.GlobalControllerRouter["git.jd.com/bmp-pronoea/controllers:PrometheusRulesController"], + beego.ControllerComments{ + Method: "PrometheusRulesWrite", + Router: "/write", + AllowHTTPMethods: []string{"post"}, + MethodParams: param.Make(), + Filters: nil, + Params: nil}) + +} diff --git a/bmp-pronoea/routers/router.go b/bmp-pronoea/routers/router.go new file mode 100644 index 0000000..debf9ba --- /dev/null +++ b/bmp-pronoea/routers/router.go @@ -0,0 +1,36 @@ +// Package routers @APIVersion 1.0.0 +// @Title beego Test API +// @Description beego has a very cool tools to autogenerate documents for your API +// @Contact astaxie@gmail.com +// @TermsOfServiceUrl http://beego.me/ +// @License Apache 2.0 +// @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html +package routers + +import ( + "git.jd.com/bmp-pronoea/controllers" + "github.com/astaxie/beego" +) + +func init() { + ns := beego.NewNamespace("/api", + beego.NSNamespace("/rules", + beego.NSInclude( + &controllers.PrometheusRulesController{}, + ), + ), + + beego.NSNamespace("/query", + beego.NSInclude( + &controllers.PrometheusQueryController{}, + ), + ), + + beego.NSNamespace("/alert", + beego.NSInclude( + &controllers.PrometheusAlertController{}, + ), + ), + ) + beego.AddNamespace(ns) +} diff --git a/bmp-pronoea/service/crontab/crontab.go b/bmp-pronoea/service/crontab/crontab.go new file mode 100644 index 0000000..c59c2ee --- /dev/null +++ b/bmp-pronoea/service/crontab/crontab.go @@ -0,0 +1,25 @@ +package crontab + +import ( + "fmt" + "git.jd.com/bmp-pronoea/config" + "github.com/astaxie/beego/logs" + "github.com/beego/beego/v2/task" +) + +func InitCrontab() error { + + if config.SysConfig.Crontabs == nil || len(config.SysConfig.Crontabs) <= 0 { + //logs.Info("InitCrontab", " not exist crontab tasks !") + return fmt.Errorf("not exist crontab tasks !") + } + + if _, exist := config.SysConfig.Crontabs[config.CRONTAB_WIPE_PUSHGATEWAY]; exist { + wipePushgatewayTask := task.NewTask(config.CRONTAB_WIPE_PUSHGATEWAY, config.SysConfig.Crontabs[config.CRONTAB_WIPE_PUSHGATEWAY], WipeAllPushgatewayData) + task.AddTask("wipePushgatewayTask", wipePushgatewayTask) + } + + task.StartTask() + logs.Info("InitCrontab", " crontab started !") + return nil +} diff --git a/bmp-pronoea/service/crontab/pushgatewayCrontab.go b/bmp-pronoea/service/crontab/pushgatewayCrontab.go new file mode 100644 index 0000000..b9507c1 --- /dev/null +++ b/bmp-pronoea/service/crontab/pushgatewayCrontab.go @@ -0,0 +1,22 @@ +package crontab + +import ( + "context" + "fmt" + "git.jd.com/bmp-pronoea/common/util" + "git.jd.com/bmp-pronoea/models/pushgateway" + "github.com/astaxie/beego/logs" +) + +func WipeAllPushgatewayData(ctx context.Context) error { + requestId := util.GetUuid() + logs.Info(requestId, fmt.Sprintf("start wipe pushgateway data,%v", util.GetCurrentTimeStr())) + + err := pushgateway.WipeAllPushgatewayData(requestId) + if err != nil { + logs.Info(requestId, fmt.Sprintf("wipe pushgateway data fail:%v", err)) + return err + } + logs.Info(requestId, fmt.Sprintf("wipe pushgateway data success! ")) + return nil +} \ No newline at end of file diff --git a/bmp-pronoea/swagger/favicon-16x16.png b/bmp-pronoea/swagger/favicon-16x16.png new file mode 100644 index 0000000..0f7e13b Binary files /dev/null and b/bmp-pronoea/swagger/favicon-16x16.png differ diff --git a/bmp-pronoea/swagger/favicon-32x32.png b/bmp-pronoea/swagger/favicon-32x32.png new file mode 100644 index 0000000..b0a3352 Binary files /dev/null and b/bmp-pronoea/swagger/favicon-32x32.png differ diff --git a/bmp-pronoea/swagger/index.html b/bmp-pronoea/swagger/index.html new file mode 100644 index 0000000..d425107 --- /dev/null +++ b/bmp-pronoea/swagger/index.html @@ -0,0 +1,93 @@ + + + + + + Swagger UI + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + diff --git a/bmp-pronoea/swagger/oauth2-redirect.html b/bmp-pronoea/swagger/oauth2-redirect.html new file mode 100644 index 0000000..4de4053 --- /dev/null +++ b/bmp-pronoea/swagger/oauth2-redirect.html @@ -0,0 +1,53 @@ + + + + + + diff --git a/bmp-pronoea/swagger/swagger-ui-bundle.js b/bmp-pronoea/swagger/swagger-ui-bundle.js new file mode 100644 index 0000000..634e539 --- /dev/null +++ b/bmp-pronoea/swagger/swagger-ui-bundle.js @@ -0,0 +1,108 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SwaggerUIBundle=t():e.SwaggerUIBundle=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return e[r].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var n={};return t.m=e,t.c=n,t.p="/dist",t(0)}(function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))switch(typeof e[t]){case"function":break;case"object":e[t]=function(t){var n=t.slice(1),r=e[t[0]];return function(e,t,i){r.apply(this,[e,t,i].concat(n))}}(e[t]);break;default:e[t]=e[e[t]]}return e}([function(e,t,n){n(1),e.exports=n(297)},function(e,t,n){(function(e){"use strict";function t(e,t,n){e[t]||Object[r](e,t,{writable:!0,configurable:!0,value:n})}if(n(2),n(293),n(294),e._babelPolyfill)throw new Error("only one instance of babel-polyfill is allowed");e._babelPolyfill=!0;var r="defineProperty";t(String.prototype,"padLeft","".padStart),t(String.prototype,"padRight","".padEnd),"pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function(e){[][e]&&t(Array,e,Function.call.bind([][e]))})}).call(t,function(){return this}())},function(e,t,n){n(3),n(52),n(53),n(54),n(55),n(57),n(60),n(61),n(62),n(63),n(64),n(65),n(66),n(67),n(68),n(70),n(72),n(74),n(76),n(79),n(80),n(81),n(85),n(87),n(89),n(92),n(93),n(94),n(95),n(97),n(98),n(99),n(100),n(101),n(102),n(103),n(105),n(106),n(107),n(109),n(110),n(111),n(113),n(114),n(115),n(116),n(117),n(118),n(119),n(120),n(121),n(122),n(123),n(124),n(125),n(126),n(131),n(132),n(136),n(137),n(138),n(139),n(141),n(142),n(143),n(144),n(145),n(146),n(147),n(148),n(149),n(150),n(151),n(152),n(153),n(154),n(155),n(156),n(157),n(159),n(160),n(166),n(167),n(169),n(170),n(171),n(175),n(176),n(177),n(178),n(179),n(181),n(182),n(183),n(184),n(187),n(189),n(190),n(191),n(193),n(195),n(197),n(198),n(199),n(201),n(202),n(203),n(204),n(211),n(214),n(215),n(217),n(218),n(221),n(222),n(224),n(225),n(226),n(227),n(228),n(229),n(230),n(231),n(232),n(233),n(234),n(235),n(236),n(237),n(238),n(239),n(240),n(241),n(242),n(244),n(245),n(246),n(247),n(248),n(249),n(251),n(252),n(253),n(254),n(255),n(256),n(257),n(258),n(260),n(261),n(263),n(264),n(265),n(266),n(269),n(270),n(271),n(272),n(273),n(274),n(275),n(276),n(278),n(279),n(280),n(281),n(282),n(283),n(284),n(285),n(286),n(287),n(288),n(291),n(292),e.exports=n(9)},[1378,4,5,6,8,18,22,7,23,24,19,25,26,27,29,42,45,12,32,16,17,46,49,51,11,30,50,44,43,28,10],function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},[1379,7],function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t,n){var r=n(4),i=n(9),o=n(10),a=n(18),s=n(20),u="prototype",c=function(e,t,n){var l,p,f,h,d=e&c.F,m=e&c.G,y=e&c.S,v=e&c.P,g=e&c.B,_=m?r:y?r[t]||(r[t]={}):(r[t]||{})[u],b=m?i:i[t]||(i[t]={}),x=b[u]||(b[u]={});m&&(n=t);for(l in n)p=!d&&_&&void 0!==_[l],f=(p?_:n)[l],h=g&&p?s(f,r):v&&"function"==typeof f?s(Function.call,f):f,_&&a(_,l,f,e&c.U),b[l]!=f&&o(b,l,h),v&&x[l]!=f&&(x[l]=f)};r.core=i,c.F=1,c.G=2,c.S=4,c.P=8,c.B=16,c.W=32,c.U=64,c.R=128,e.exports=c},function(e,t){var n=e.exports={version:"2.4.0"};"number"==typeof __e&&(__e=n)},[1380,11,17,6],[1381,12,14,16,6],[1382,13],function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},[1383,6,7,15],[1384,13,4],[1385,13],function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){var r=n(4),i=n(10),o=n(5),a=n(19)("src"),s="toString",u=Function[s],c=(""+u).split(s);n(9).inspectSource=function(e){return u.call(e)},(e.exports=function(e,t,n,s){var u="function"==typeof n;u&&(o(n,"name")||i(n,"name",t)),e[t]!==n&&(u&&(o(n,a)||i(n,a,e[t]?""+e[t]:c.join(String(t)))),e===r?e[t]=n:s?e[t]?e[t]=n:i(e,t,n):(delete e[t],i(e,t,n)))})(Function.prototype,s,function(){return"function"==typeof this&&this[a]||u.call(this)})},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},[1386,21],function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},[1387,19,13,5,11,7],[1388,4],[1389,11,5,25],[1390,23,19,4],[1391,25],[1392,4,9,28,26,11],function(e,t){e.exports=!1},[1393,30,32],[1394,31,41],[1395,5,32,36,40],[1396,33,35],[1397,34],function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},[1398,32,37,39],[1399,38],function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},[1400,38],[1401,23,19],function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},[1402,30,43,44],function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t){t.f={}.propertyIsEnumerable},[1403,34],[1404,12,47,41,40,15,48],[1405,11,12,30,6],[1406,4],[1407,32,50],[1408,31,41],[1409,44,17,32,16,5,14,6],[1410,8,46],[1411,8,6,11],function(e,t,n){var r=n(8);r(r.S+r.F*!n(6),"Object",{defineProperties:n(47)})},function(e,t,n){var r=n(32),i=n(51).f;n(56)("getOwnPropertyDescriptor",function(){return function(e,t){return i(r(e),t)}})},[1412,8,9,7],function(e,t,n){var r=n(58),i=n(59);n(56)("getPrototypeOf",function(){return function(e){return i(r(e))}})},[1413,35],[1414,5,58,40],[1415,58,30,56],function(e,t,n){n(56)("getOwnPropertyNames",function(){return n(49).f})},function(e,t,n){var r=n(13),i=n(22).onFreeze;n(56)("freeze",function(e){return function(t){return e&&r(t)?e(i(t)):t}})},function(e,t,n){var r=n(13),i=n(22).onFreeze;n(56)("seal",function(e){return function(t){return e&&r(t)?e(i(t)):t}})},function(e,t,n){var r=n(13),i=n(22).onFreeze;n(56)("preventExtensions",function(e){return function(t){return e&&r(t)?e(i(t)):t}})},function(e,t,n){var r=n(13);n(56)("isFrozen",function(e){return function(t){return!r(t)||!!e&&e(t)}})},function(e,t,n){var r=n(13);n(56)("isSealed",function(e){return function(t){return!r(t)||!!e&&e(t)}})},function(e,t,n){var r=n(13);n(56)("isExtensible",function(e){return function(t){return!!r(t)&&(!e||e(t))}})},[1416,8,69],[1417,30,43,44,58,33,7],function(e,t,n){var r=n(8);r(r.S,"Object",{is:n(71)})},function(e,t){e.exports=Object.is||function(e,t){return e===t?0!==e||1/e===1/t:e!=e&&t!=t}},function(e,t,n){var r=n(8);r(r.S,"Object",{setPrototypeOf:n(73).set})},function(e,t,n){var r=n(13),i=n(12),o=function(e,t){if(i(e),!r(t)&&null!==t)throw TypeError(t+": can't set as prototype!")};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{r=n(20)(Function.call,n(51).f(Object.prototype,"__proto__").set,2),r(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,n){return o(e,n),t?e.__proto__=n:r(e,n),e}}({},!1):void 0),check:o}},function(e,t,n){"use strict";var r=n(75),i={};i[n(25)("toStringTag")]="z",i+""!="[object z]"&&n(18)(Object.prototype,"toString",function(){return"[object "+r(this)+"]"},!0)},[1418,34,25],function(e,t,n){var r=n(8);r(r.P,"Function",{bind:n(77)})},function(e,t,n){"use strict";var r=n(21),i=n(13),o=n(78),a=[].slice,s={},u=function(e,t,n){if(!(t in s)){for(var r=[],i=0;i>>0||(a.test(n)?16:10))}:r},function(e,t,n){var r=n(8),i=n(35),o=n(7),a=n(84),s="["+a+"]",u="​…",c=RegExp("^"+s+s+"*"),l=RegExp(s+s+"*$"),p=function(e,t,n){var i={},s=o(function(){return!!a[e]()||u[e]()!=u}),c=i[e]=s?t(f):a[e];n&&(i[n]=c),r(r.P+r.F*s,"String",i)},f=p.trim=function(e,t){return e=String(i(e)),1&t&&(e=e.replace(c,"")),2&t&&(e=e.replace(l,"")),e};e.exports=p},function(e,t){e.exports="\t\n\v\f\r   ᠎              \u2028\u2029\ufeff"},function(e,t,n){var r=n(8),i=n(86);r(r.G+r.F*(parseFloat!=i),{parseFloat:i})},function(e,t,n){var r=n(4).parseFloat,i=n(83).trim;e.exports=1/r(n(84)+"-0")!==-(1/0)?function(e){var t=i(String(e),3),n=r(t);return 0===n&&"-"==t.charAt(0)?-0:n}:r},function(e,t,n){"use strict";var r=n(4),i=n(5),o=n(34),a=n(88),s=n(16),u=n(7),c=n(50).f,l=n(51).f,p=n(11).f,f=n(83).trim,h="Number",d=r[h],m=d,y=d.prototype,v=o(n(46)(y))==h,g="trim"in String.prototype,_=function(e){var t=s(e,!1);if("string"==typeof t&&t.length>2){t=g?t.trim():f(t,3);var n,r,i,o=t.charCodeAt(0);if(43===o||45===o){if(n=t.charCodeAt(2),88===n||120===n)return NaN}else if(48===o){switch(t.charCodeAt(1)){case 66:case 98:r=2,i=49;break;case 79:case 111:r=8,i=55;break;default:return+t}for(var a,u=t.slice(2),c=0,l=u.length;ci)return NaN;return parseInt(u,r)}}return+t};if(!d(" 0o1")||!d("0b1")||d("+0x1")){d=function(e){var t=arguments.length<1?0:e,n=this;return n instanceof d&&(v?u(function(){y.valueOf.call(n)}):o(n)!=h)?a(new m(_(t)),n,d):_(t)};for(var b,x=n(6)?c(m):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger".split(","),w=0;x.length>w;w++)i(m,b=x[w])&&!i(d,b)&&p(d,b,l(m,b));d.prototype=y,y.constructor=d,n(18)(r,h,d)}},function(e,t,n){var r=n(13),i=n(73).set;e.exports=function(e,t,n){var o,a=t.constructor;return a!==n&&"function"==typeof a&&(o=a.prototype)!==n.prototype&&r(o)&&i&&i(e,o),e}},function(e,t,n){"use strict";var r=n(8),i=n(38),o=n(90),a=n(91),s=1..toFixed,u=Math.floor,c=[0,0,0,0,0,0],l="Number.toFixed: incorrect invocation!",p="0",f=function(e,t){for(var n=-1,r=t;++n<6;)r+=e*c[n],c[n]=r%1e7,r=u(r/1e7)},h=function(e){for(var t=6,n=0;--t>=0;)n+=c[t],c[t]=u(n/e),n=n%e*1e7},d=function(){for(var e=6,t="";--e>=0;)if(""!==t||0===e||0!==c[e]){var n=String(c[e]);t=""===t?n:t+a.call(p,7-n.length)+n}return t},m=function(e,t,n){return 0===t?n:t%2===1?m(e,t-1,n*e):m(e*e,t/2,n)},y=function(e){for(var t=0,n=e;n>=4096;)t+=12,n/=4096;for(;n>=2;)t+=1,n/=2;return t};r(r.P+r.F*(!!s&&("0.000"!==8e-5.toFixed(3)||"1"!==.9.toFixed(0)||"1.25"!==1.255.toFixed(2)||"1000000000000000128"!==(0xde0b6b3a7640080).toFixed(0))||!n(7)(function(){s.call({})})),"Number",{toFixed:function(e){var t,n,r,s,u=o(this,l),c=i(e),v="",g=p;if(c<0||c>20)throw RangeError(l);if(u!=u)return"NaN";if(u<=-1e21||u>=1e21)return String(u);if(u<0&&(v="-",u=-u),u>1e-21)if(t=y(u*m(2,69,1))-69,n=t<0?u*m(2,-t,1):u/m(2,t,1),n*=4503599627370496,t=52-t,t>0){for(f(0,n),r=c;r>=7;)f(1e7,0),r-=7;for(f(m(10,r,1),0),r=t-1;r>=23;)h(1<<23),r-=23;h(1<0?(s=g.length,g=v+(s<=c?"0."+a.call(p,c-s)+g:g.slice(0,s-c)+"."+g.slice(s-c))):g=v+g,g}})},function(e,t,n){var r=n(34);e.exports=function(e,t){if("number"!=typeof e&&"Number"!=r(e))throw TypeError(t);return+e}},function(e,t,n){"use strict";var r=n(38),i=n(35);e.exports=function(e){var t=String(i(this)),n="",o=r(e);if(o<0||o==1/0)throw RangeError("Count can't be negative");for(;o>0;(o>>>=1)&&(t+=t))1&o&&(n+=t);return n}},function(e,t,n){"use strict";var r=n(8),i=n(7),o=n(90),a=1..toPrecision;r(r.P+r.F*(i(function(){return"1"!==a.call(1,void 0)})||!i(function(){a.call({})})),"Number",{toPrecision:function(e){var t=o(this,"Number#toPrecision: incorrect invocation!");return void 0===e?a.call(t):a.call(t,e)}})},function(e,t,n){var r=n(8);r(r.S,"Number",{EPSILON:Math.pow(2,-52)})},function(e,t,n){var r=n(8),i=n(4).isFinite;r(r.S,"Number",{isFinite:function(e){return"number"==typeof e&&i(e)}})},function(e,t,n){var r=n(8);r(r.S,"Number",{isInteger:n(96)})},function(e,t,n){var r=n(13),i=Math.floor;e.exports=function(e){return!r(e)&&isFinite(e)&&i(e)===e}},function(e,t,n){var r=n(8);r(r.S,"Number",{isNaN:function(e){return e!=e}})},function(e,t,n){var r=n(8),i=n(96),o=Math.abs;r(r.S,"Number",{isSafeInteger:function(e){return i(e)&&o(e)<=9007199254740991}})},function(e,t,n){var r=n(8);r(r.S,"Number",{MAX_SAFE_INTEGER:9007199254740991})},function(e,t,n){var r=n(8);r(r.S,"Number",{MIN_SAFE_INTEGER:-9007199254740991})},function(e,t,n){var r=n(8),i=n(86);r(r.S+r.F*(Number.parseFloat!=i),"Number",{parseFloat:i})},function(e,t,n){var r=n(8),i=n(82);r(r.S+r.F*(Number.parseInt!=i),"Number",{parseInt:i})},function(e,t,n){var r=n(8),i=n(104),o=Math.sqrt,a=Math.acosh;r(r.S+r.F*!(a&&710==Math.floor(a(Number.MAX_VALUE))&&a(1/0)==1/0),"Math",{acosh:function(e){return(e=+e)<1?NaN:e>94906265.62425156?Math.log(e)+Math.LN2:i(e-1+o(e-1)*o(e+1))}})},function(e,t){e.exports=Math.log1p||function(e){return(e=+e)>-1e-8&&e<1e-8?e-e*e/2:Math.log(1+e)}},function(e,t,n){function r(e){return isFinite(e=+e)&&0!=e?e<0?-r(-e):Math.log(e+Math.sqrt(e*e+1)):e}var i=n(8),o=Math.asinh;i(i.S+i.F*!(o&&1/o(0)>0),"Math",{asinh:r})},function(e,t,n){var r=n(8),i=Math.atanh;r(r.S+r.F*!(i&&1/i(-0)<0),"Math",{atanh:function(e){return 0==(e=+e)?e:Math.log((1+e)/(1-e))/2}})},function(e,t,n){var r=n(8),i=n(108);r(r.S,"Math",{cbrt:function(e){return i(e=+e)*Math.pow(Math.abs(e),1/3)}})},function(e,t){e.exports=Math.sign||function(e){return 0==(e=+e)||e!=e?e:e<0?-1:1}},function(e,t,n){var r=n(8);r(r.S,"Math",{clz32:function(e){return(e>>>=0)?31-Math.floor(Math.log(e+.5)*Math.LOG2E):32}})},function(e,t,n){var r=n(8),i=Math.exp;r(r.S,"Math",{cosh:function(e){return(i(e=+e)+i(-e))/2}})},function(e,t,n){var r=n(8),i=n(112);r(r.S+r.F*(i!=Math.expm1),"Math",{expm1:i})},function(e,t){var n=Math.expm1;e.exports=!n||n(10)>22025.465794806718||n(10)<22025.465794806718||n(-2e-17)!=-2e-17?function(e){return 0==(e=+e)?e:e>-1e-6&&e<1e-6?e+e*e/2:Math.exp(e)-1}:n},function(e,t,n){var r=n(8),i=n(108),o=Math.pow,a=o(2,-52),s=o(2,-23),u=o(2,127)*(2-s),c=o(2,-126),l=function(e){return e+1/a-1/a};r(r.S,"Math",{fround:function(e){var t,n,r=Math.abs(e),o=i(e);return ru||n!=n?o*(1/0):o*n)}})},function(e,t,n){var r=n(8),i=Math.abs;r(r.S,"Math",{hypot:function(e,t){for(var n,r,o=0,a=0,s=arguments.length,u=0;a0?(r=n/u,o+=r*r):o+=n;return u===1/0?1/0:u*Math.sqrt(o)}})},function(e,t,n){var r=n(8),i=Math.imul;r(r.S+r.F*n(7)(function(){return i(4294967295,5)!=-5||2!=i.length}),"Math",{imul:function(e,t){var n=65535,r=+e,i=+t,o=n&r,a=n&i;return 0|o*a+((n&r>>>16)*a+o*(n&i>>>16)<<16>>>0)}})},function(e,t,n){var r=n(8);r(r.S,"Math",{log10:function(e){return Math.log(e)/Math.LN10}})},function(e,t,n){var r=n(8);r(r.S,"Math",{log1p:n(104)})},function(e,t,n){var r=n(8);r(r.S,"Math",{log2:function(e){return Math.log(e)/Math.LN2}})},function(e,t,n){var r=n(8);r(r.S,"Math",{sign:n(108)})},function(e,t,n){var r=n(8),i=n(112),o=Math.exp;r(r.S+r.F*n(7)(function(){return!Math.sinh(-2e-17)!=-2e-17}),"Math",{sinh:function(e){return Math.abs(e=+e)<1?(i(e)-i(-e))/2:(o(e-1)-o(-e-1))*(Math.E/2)}})},function(e,t,n){var r=n(8),i=n(112),o=Math.exp;r(r.S,"Math",{tanh:function(e){var t=i(e=+e),n=i(-e);return t==1/0?1:n==1/0?-1:(t-n)/(o(e)+o(-e))}})},function(e,t,n){var r=n(8);r(r.S,"Math",{trunc:function(e){return(e>0?Math.floor:Math.ceil)(e)}})},function(e,t,n){var r=n(8),i=n(39),o=String.fromCharCode,a=String.fromCodePoint;r(r.S+r.F*(!!a&&1!=a.length),"String",{fromCodePoint:function(e){for(var t,n=[],r=arguments.length,a=0;r>a;){if(t=+arguments[a++],i(t,1114111)!==t)throw RangeError(t+" is not a valid code point");n.push(t<65536?o(t):o(((t-=65536)>>10)+55296,t%1024+56320))}return n.join("")}})},function(e,t,n){var r=n(8),i=n(32),o=n(37);r(r.S,"String",{raw:function(e){for(var t=i(e.raw),n=o(t.length),r=arguments.length,a=[],s=0;n>s;)a.push(String(t[s++])),s1?arguments[1]:void 0,r=i(t.length),u=void 0===n?r:Math.min(i(n),r),c=String(e);return s?s.call(t,c,u):t.slice(u-c.length,u)===c}})},function(e,t,n){var r=n(134),i=n(35);e.exports=function(e,t,n){if(r(t))throw TypeError("String#"+n+" doesn't accept regex!");return String(i(e))}},function(e,t,n){var r=n(13),i=n(34),o=n(25)("match");e.exports=function(e){var t;return r(e)&&(void 0!==(t=e[o])?!!t:"RegExp"==i(e))}},function(e,t,n){var r=n(25)("match");e.exports=function(e){var t=/./;try{"/./"[e](t)}catch(n){try{return t[r]=!1,!"/./"[e](t)}catch(e){}}return!0}},function(e,t,n){"use strict";var r=n(8),i=n(133),o="includes";r(r.P+r.F*n(135)(o),"String",{includes:function(e){return!!~i(this,e,o).indexOf(e,arguments.length>1?arguments[1]:void 0)}})},function(e,t,n){var r=n(8);r(r.P,"String",{repeat:n(91)})},function(e,t,n){"use strict";var r=n(8),i=n(37),o=n(133),a="startsWith",s=""[a];r(r.P+r.F*n(135)(a),"String",{startsWith:function(e){var t=o(this,e,a),n=i(Math.min(arguments.length>1?arguments[1]:void 0,t.length)),r=String(e);return s?s.call(t,r,n):t.slice(n,n+r.length)===r}})},function(e,t,n){"use strict";n(140)("anchor",function(e){return function(t){return e(this,"a","name",t)}})},function(e,t,n){var r=n(8),i=n(7),o=n(35),a=/"/g,s=function(e,t,n,r){var i=String(o(e)),s="<"+t;return""!==n&&(s+=" "+n+'="'+String(r).replace(a,""")+'"'),s+">"+i+""};e.exports=function(e,t){var n={};n[e]=t(s),r(r.P+r.F*i(function(){var t=""[e]('"');return t!==t.toLowerCase()||t.split('"').length>3}),"String",n)}},function(e,t,n){"use strict";n(140)("big",function(e){return function(){return e(this,"big","","")}})},function(e,t,n){"use strict";n(140)("blink",function(e){return function(){return e(this,"blink","","")}})},function(e,t,n){"use strict";n(140)("bold",function(e){return function(){return e(this,"b","","")}})},function(e,t,n){"use strict";n(140)("fixed",function(e){return function(){return e(this,"tt","","")}})},function(e,t,n){"use strict";n(140)("fontcolor",function(e){return function(t){return e(this,"font","color",t)}})},function(e,t,n){"use strict";n(140)("fontsize",function(e){return function(t){return e(this,"font","size",t)}})},function(e,t,n){"use strict";n(140)("italics",function(e){return function(){return e(this,"i","","")}})},function(e,t,n){"use strict";n(140)("link",function(e){return function(t){return e(this,"a","href",t)}})},function(e,t,n){"use strict";n(140)("small",function(e){return function(){return e(this,"small","","")}})},function(e,t,n){"use strict";n(140)("strike",function(e){return function(){return e(this,"strike","","")}})},function(e,t,n){"use strict";n(140)("sub",function(e){return function(){return e(this,"sub","","")}})},function(e,t,n){"use strict";n(140)("sup",function(e){return function(){return e(this,"sup","","")}})},function(e,t,n){var r=n(8);r(r.S,"Date",{now:function(){return(new Date).getTime()}})},function(e,t,n){"use strict";var r=n(8),i=n(58),o=n(16);r(r.P+r.F*n(7)(function(){return null!==new Date(NaN).toJSON()||1!==Date.prototype.toJSON.call({toISOString:function(){return 1}})}),"Date",{toJSON:function(e){var t=i(this),n=o(t);return"number"!=typeof n||isFinite(n)?t.toISOString():null}})},function(e,t,n){"use strict";var r=n(8),i=n(7),o=Date.prototype.getTime,a=function(e){return e>9?e:"0"+e};r(r.P+r.F*(i(function(){return"0385-07-25T07:06:39.999Z"!=new Date(-5e13-1).toISOString()})||!i(function(){new Date(NaN).toISOString()})),"Date",{toISOString:function(){if(!isFinite(o.call(this)))throw RangeError("Invalid time value");var e=this,t=e.getUTCFullYear(),n=e.getUTCMilliseconds(),r=t<0?"-":t>9999?"+":"";return r+("00000"+Math.abs(t)).slice(r?-6:-4)+"-"+a(e.getUTCMonth()+1)+"-"+a(e.getUTCDate())+"T"+a(e.getUTCHours())+":"+a(e.getUTCMinutes())+":"+a(e.getUTCSeconds())+"."+(n>99?n:"0"+a(n))+"Z"}})},function(e,t,n){var r=Date.prototype,i="Invalid Date",o="toString",a=r[o],s=r.getTime;new Date(NaN)+""!=i&&n(18)(r,o,function(){var e=s.call(this);return e===e?a.call(this):i})},function(e,t,n){var r=n(25)("toPrimitive"),i=Date.prototype;r in i||n(10)(i,r,n(158))},function(e,t,n){"use strict";var r=n(12),i=n(16),o="number";e.exports=function(e){if("string"!==e&&e!==o&&"default"!==e)throw TypeError("Incorrect hint");return i(r(this),e!=o)}},function(e,t,n){var r=n(8);r(r.S,"Array",{isArray:n(45)})},[1423,20,8,58,161,162,37,163,164,165],[1424,12],[1425,129,25],[1426,11,17],[1427,75,25,129,9],[1428,25],function(e,t,n){"use strict";var r=n(8),i=n(163);r(r.S+r.F*n(7)(function(){function e(){}return!(Array.of.call(e)instanceof e)}),"Array",{of:function(){for(var e=0,t=arguments.length,n=new("function"==typeof this?this:Array)(t);t>e;)i(n,e,arguments[e++]);return n.length=t,n}})},function(e,t,n){"use strict";var r=n(8),i=n(32),o=[].join;r(r.P+r.F*(n(33)!=Object||!n(168)(o)),"Array",{join:function(e){return o.call(i(this),void 0===e?",":e)}})},function(e,t,n){var r=n(7);e.exports=function(e,t){return!!e&&r(function(){t?e.call(null,function(){},1):e.call(null)})}},function(e,t,n){"use strict";var r=n(8),i=n(48),o=n(34),a=n(39),s=n(37),u=[].slice;r(r.P+r.F*n(7)(function(){i&&u.call(i)}),"Array",{slice:function(e,t){var n=s(this.length),r=o(this);if(t=void 0===t?n:t,"Array"==r)return u.call(this,e,t);for(var i=a(e,n),c=a(t,n),l=s(c-i),p=Array(l),f=0;f=0:p>f;f+=h)f in l&&(s=t(s,l[f],f,c));return s}},function(e,t,n){"use strict";var r=n(8),i=n(180);r(r.P+r.F*!n(168)([].reduceRight,!0),"Array",{reduceRight:function(e){return i(this,e,arguments.length,arguments[1],!0)}})},function(e,t,n){"use strict";var r=n(8),i=n(36)(!1),o=[].indexOf,a=!!o&&1/[1].indexOf(1,-0)<0;r(r.P+r.F*(a||!n(168)(o)),"Array",{indexOf:function(e){return a?o.apply(this,arguments)||0:i(this,e,arguments[1])}})},function(e,t,n){"use strict";var r=n(8),i=n(32),o=n(38),a=n(37),s=[].lastIndexOf,u=!!s&&1/[1].lastIndexOf(1,-0)<0;r(r.P+r.F*(u||!n(168)(s)),"Array",{lastIndexOf:function(e){if(u)return s.apply(this,arguments)||0;var t=i(this),n=a(t.length),r=n-1;for(arguments.length>1&&(r=Math.min(r,o(arguments[1]))),r<0&&(r=n+r);r>=0;r--)if(r in t&&t[r]===e)return r||0;return-1}})},function(e,t,n){var r=n(8);r(r.P,"Array",{copyWithin:n(185)}),n(186)("copyWithin")},function(e,t,n){"use strict";var r=n(58),i=n(39),o=n(37);e.exports=[].copyWithin||function(e,t){var n=r(this),a=o(n.length),s=i(e,a),u=i(t,a),c=arguments.length>2?arguments[2]:void 0,l=Math.min((void 0===c?a:i(c,a))-u,a-s),p=1;for(u0;)u in n?n[s]=n[u]:delete n[s],s+=p,u+=p;return n}},function(e,t,n){var r=n(25)("unscopables"),i=Array.prototype;void 0==i[r]&&n(10)(i,r,{}),e.exports=function(e){i[r][e]=!0}},function(e,t,n){var r=n(8);r(r.P,"Array",{fill:n(188)}),n(186)("fill")},function(e,t,n){"use strict";var r=n(58),i=n(39),o=n(37);e.exports=function(e){for(var t=r(this),n=o(t.length),a=arguments.length,s=i(a>1?arguments[1]:void 0,n),u=a>2?arguments[2]:void 0,c=void 0===u?n:i(u,n);c>s;)t[s++]=e;return t}},function(e,t,n){"use strict";var r=n(8),i=n(172)(5),o="find",a=!0;o in[]&&Array(1)[o](function(){a=!1}),r(r.P+r.F*a,"Array",{find:function(e){return i(this,e,arguments.length>1?arguments[1]:void 0)}}),n(186)(o)},function(e,t,n){"use strict";var r=n(8),i=n(172)(6),o="findIndex",a=!0;o in[]&&Array(1)[o](function(){a=!1}),r(r.P+r.F*a,"Array",{findIndex:function(e){return i(this,e,arguments.length>1?arguments[1]:void 0)}}),n(186)(o)},function(e,t,n){n(192)("Array")},function(e,t,n){"use strict";var r=n(4),i=n(11),o=n(6),a=n(25)("species");e.exports=function(e){var t=r[e];o&&t&&!t[a]&&i.f(t,a,{configurable:!0,get:function(){return this}})}},[1432,186,194,129,32,128],function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){var r=n(4),i=n(88),o=n(11).f,a=n(50).f,s=n(134),u=n(196),c=r.RegExp,l=c,p=c.prototype,f=/a/g,h=/a/g,d=new c(f)!==f;if(n(6)&&(!d||n(7)(function(){return h[n(25)("match")]=!1,c(f)!=f||c(h)==h||"/a/i"!=c(f,"i")}))){c=function(e,t){var n=this instanceof c,r=s(e),o=void 0===t;return!n&&r&&e.constructor===c&&o?e:i(d?new l(r&&!o?e.source:e,t):l((r=e instanceof c)?e.source:e,r&&o?u.call(e):t),n?this:p,c)};for(var m=(function(e){e in c||o(c,e,{configurable:!0,get:function(){return l[e]},set:function(t){l[e]=t}})}),y=a(l),v=0;y.length>v;)m(y[v++]);p.constructor=c,c.prototype=p,n(18)(r,"RegExp",c)}n(192)("RegExp")},function(e,t,n){"use strict";var r=n(12);e.exports=function(){var e=r(this),t="";return e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.unicode&&(t+="u"),e.sticky&&(t+="y"),t}},function(e,t,n){"use strict";n(198);var r=n(12),i=n(196),o=n(6),a="toString",s=/./[a],u=function(e){n(18)(RegExp.prototype,a,e,!0)};n(7)(function(){return"/a/b"!=s.call({source:"a",flags:"b"})})?u(function(){var e=r(this);return"/".concat(e.source,"/","flags"in e?e.flags:!o&&e instanceof RegExp?i.call(e):void 0)}):s.name!=a&&u(function(){return s.call(this)})},function(e,t,n){n(6)&&"g"!=/./g.flags&&n(11).f(RegExp.prototype,"flags",{configurable:!0,get:n(196)})},function(e,t,n){n(200)("match",1,function(e,t,n){return[function(n){"use strict";var r=e(this),i=void 0==n?void 0:n[t];return void 0!==i?i.call(n,r):new RegExp(n)[t](String(r))},n]})},function(e,t,n){"use strict";var r=n(10),i=n(18),o=n(7),a=n(35),s=n(25);e.exports=function(e,t,n){var u=s(e),c=n(a,u,""[e]),l=c[0],p=c[1];o(function(){var t={};return t[u]=function(){return 7},7!=""[e](t)})&&(i(String.prototype,e,l),r(RegExp.prototype,u,2==t?function(e,t){return p.call(e,this,t)}:function(e){return p.call(e,this)}))}},function(e,t,n){n(200)("replace",2,function(e,t,n){return[function(r,i){"use strict";var o=e(this),a=void 0==r?void 0:r[t];return void 0!==a?a.call(r,o,i):n.call(String(o),r,i)},n]})},function(e,t,n){n(200)("search",1,function(e,t,n){return[function(n){"use strict";var r=e(this),i=void 0==n?void 0:n[t];return void 0!==i?i.call(n,r):new RegExp(n)[t](String(r))},n]})},function(e,t,n){n(200)("split",2,function(e,t,r){"use strict";var i=n(134),o=r,a=[].push,s="split",u="length",c="lastIndex";if("c"=="abbc"[s](/(b)*/)[1]||4!="test"[s](/(?:)/,-1)[u]||2!="ab"[s](/(?:ab)*/)[u]||4!="."[s](/(.?)(.?)/)[u]||"."[s](/()()/)[u]>1||""[s](/.?/)[u]){var l=void 0===/()??/.exec("")[1];r=function(e,t){var n=String(this);if(void 0===e&&0===t)return[];if(!i(e))return o.call(n,e,t);var r,s,p,f,h,d=[],m=(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.unicode?"u":"")+(e.sticky?"y":""),y=0,v=void 0===t?4294967295:t>>>0,g=new RegExp(e.source,m+"g");for(l||(r=new RegExp("^"+g.source+"$(?!\\s)",m));(s=g.exec(n))&&(p=s.index+s[0][u],!(p>y&&(d.push(n.slice(y,s.index)),!l&&s[u]>1&&s[0].replace(r,function(){for(h=1;h1&&s.index=v)));)g[c]===s.index&&g[c]++;return y===n[u]?!f&&g.test("")||d.push(""):d.push(n.slice(y)),d[u]>v?d.slice(0,v):d}}else"0"[s](void 0,0)[u]&&(r=function(e,t){return void 0===e&&0===t?[]:o.call(this,e,t)});return[function(n,i){var o=e(this),a=void 0==n?void 0:n[t];return void 0!==a?a.call(n,o,i):r.call(String(o),n,i)},r]})},[1433,28,4,20,75,8,13,21,205,206,207,208,209,25,210,24,192,9,165],function(e,t){e.exports=function(e,t,n,r){if(!(e instanceof t)||void 0!==r&&r in e)throw TypeError(n+": incorrect invocation!");return e}},[1434,20,161,162,12,37,164],[1435,12,21,25],[1436,20,78,48,15,4,34],[1437,4,208,34],function(e,t,n){var r=n(18);e.exports=function(e,t,n){for(var i in t)r(e,i,t[i],n);return e}},function(e,t,n){"use strict";var r=n(212);e.exports=n(213)("Map",function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},{get:function(e){var t=r.getEntry(this,e);return t&&t.v},set:function(e,t){return r.def(this,0===e?0:e,t)}},r,!0)},function(e,t,n){"use strict";var r=n(11).f,i=n(46),o=n(210),a=n(20),s=n(205),u=n(35),c=n(206),l=n(128),p=n(194),f=n(192),h=n(6),d=n(22).fastKey,m=h?"_s":"size",y=function(e,t){var n,r=d(t);if("F"!==r)return e._i[r];for(n=e._f;n;n=n.n)if(n.k==t)return n};e.exports={getConstructor:function(e,t,n,l){var p=e(function(e,r){s(e,p,t,"_i"),e._i=i(null),e._f=void 0,e._l=void 0,e[m]=0,void 0!=r&&c(r,n,e[l],e)});return o(p.prototype,{clear:function(){for(var e=this,t=e._i,n=e._f;n;n=n.n)n.r=!0,n.p&&(n.p=n.p.n=void 0),delete t[n.i];e._f=e._l=void 0,e[m]=0},delete:function(e){var t=this,n=y(t,e);if(n){var r=n.n,i=n.p;delete t._i[n.i],n.r=!0,i&&(i.n=r),r&&(r.p=i),t._f==n&&(t._f=r),t._l==n&&(t._l=i),t[m]--}return!!n},forEach:function(e){s(this,p,"forEach");for(var t,n=a(e,arguments.length>1?arguments[1]:void 0,3);t=t?t.n:this._f;)for(n(t.v,t.k,this);t&&t.r;)t=t.p},has:function(e){return!!y(this,e)}}),h&&r(p.prototype,"size",{get:function(){return u(this[m])}}),p},def:function(e,t,n){var r,i,o=y(e,t);return o?o.v=n:(e._l=o={i:i=d(t,!0),k:t,v:n,p:r=e._l,n:void 0,r:!1},e._f||(e._f=o), +r&&(r.n=o),e[m]++,"F"!==i&&(e._i[i]=o)),e},getEntry:y,setStrong:function(e,t,n){l(e,t,function(e,t){this._t=e,this._k=t,this._l=void 0},function(){for(var e=this,t=e._k,n=e._l;n&&n.r;)n=n.p;return e._t&&(e._l=n=n?n.n:e._t._f)?"keys"==t?p(0,n.k):"values"==t?p(0,n.v):p(0,[n.k,n.v]):(e._t=void 0,p(1))},n?"entries":"values",!n,!0),f(t)}}},function(e,t,n){"use strict";var r=n(4),i=n(8),o=n(18),a=n(210),s=n(22),u=n(206),c=n(205),l=n(13),p=n(7),f=n(165),h=n(24),d=n(88);e.exports=function(e,t,n,m,y,v){var g=r[e],_=g,b=y?"set":"add",x=_&&_.prototype,w={},k=function(e){var t=x[e];o(x,e,"delete"==e?function(e){return!(v&&!l(e))&&t.call(this,0===e?0:e)}:"has"==e?function(e){return!(v&&!l(e))&&t.call(this,0===e?0:e)}:"get"==e?function(e){return v&&!l(e)?void 0:t.call(this,0===e?0:e)}:"add"==e?function(e){return t.call(this,0===e?0:e),this}:function(e,n){return t.call(this,0===e?0:e,n),this})};if("function"==typeof _&&(v||x.forEach&&!p(function(){(new _).entries().next()}))){var S=new _,E=S[b](v?{}:-0,1)!=S,C=p(function(){S.has(1)}),A=f(function(e){new _(e)}),T=!v&&p(function(){for(var e=new _,t=5;t--;)e[b](t,t);return!e.has(-0)});A||(_=t(function(t,n){c(t,_,e);var r=d(new g,t,_);return void 0!=n&&u(n,y,r[b],r),r}),_.prototype=x,x.constructor=_),(C||T)&&(k("delete"),k("has"),y&&k("get")),(T||E)&&k(b),v&&x.clear&&delete x.clear}else _=m.getConstructor(t,e,y,b),a(_.prototype,n),s.NEED=!0;return h(_,e),w[e]=_,i(i.G+i.W+i.F*(_!=g),w),v||m.setStrong(_,e,y),_}},function(e,t,n){"use strict";var r=n(212);e.exports=n(213)("Set",function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},{add:function(e){return r.def(this,e=0===e?0:e,e)}},r)},[1438,172,18,22,69,216,13,213],[1439,210,22,12,13,205,206,172,5],function(e,t,n){"use strict";var r=n(216);n(213)("WeakSet",function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},{add:function(e){return r.def(this,e,!0)}},r,!1,!0)},function(e,t,n){"use strict";var r=n(8),i=n(219),o=n(220),a=n(12),s=n(39),u=n(37),c=n(13),l=n(4).ArrayBuffer,p=n(207),f=o.ArrayBuffer,h=o.DataView,d=i.ABV&&l.isView,m=f.prototype.slice,y=i.VIEW,v="ArrayBuffer";r(r.G+r.W+r.F*(l!==f),{ArrayBuffer:f}),r(r.S+r.F*!i.CONSTR,v,{isView:function(e){return d&&d(e)||c(e)&&y in e}}),r(r.P+r.U+r.F*n(7)(function(){return!new f(2).slice(1,void 0).byteLength}),v,{slice:function(e,t){if(void 0!==m&&void 0===t)return m.call(a(this),e);for(var n=a(this).byteLength,r=s(e,n),i=s(void 0===t?n:t,n),o=new(p(this,f))(u(i-r)),c=new h(this),l=new h(o),d=0;r>1,l=23===t?O(2,-24)-O(2,-77):0,p=0,f=e<0||0===e&&1/e<0?1:0;for(e=T(e),e!=e||e===C?(i=e!=e?1:0,r=u):(r=D(M(e)/P),e*(o=O(2,-r))<1&&(r--,o*=2),e+=r+c>=1?l/o:l*O(2,1-c),e*o>=2&&(r++,o/=2),r+c>=u?(i=0,r=u):r+c>=1?(i=(e*o-1)*O(2,t),r+=c):(i=e*O(2,c-1)*O(2,t),r=0));t>=8;a[p++]=255&i,i/=256,t-=8);for(r=r<0;a[p++]=255&r,r/=256,s-=8);return a[--p]|=128*f,a},z=function(e,t,n){var r,i=8*n-t-1,o=(1<>1,s=i-7,u=n-1,c=e[u--],l=127&c;for(c>>=7;s>0;l=256*l+e[u],u--,s-=8);for(r=l&(1<<-s)-1,l>>=-s,s+=t;s>0;r=256*r+e[u],u--,s-=8);if(0===l)l=1-a;else{if(l===o)return r?NaN:c?-C:C;r+=O(2,t),l-=a}return(c?-1:1)*r*O(2,l-t)},q=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},U=function(e){return[255&e]},W=function(e){return[255&e,e>>8&255]},K=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},V=function(e){return L(e,52,8)},H=function(e){return L(e,23,4)},J=function(e,t,n){d(e[_],t,{get:function(){return this[n]}})},G=function(e,t,n,r){var i=+n,o=p(i);if(i!=o||o<0||o+t>e[F])throw E(x);var a=e[N]._b,s=o+e[B],u=a.slice(s,s+t);return r?u:u.reverse()},X=function(e,t,n,r,i,o){var a=+n,s=p(a);if(a!=s||s<0||s+t>e[F])throw E(x);for(var u=e[N]._b,c=s+e[B],l=r(+i),f=0;fee;)($=Q[ee++])in w||s(w,$,A[$]);o||(Z.constructor=w)}var te=new k(new w(2)),ne=k[_].setInt8;te.setInt8(0,2147483648),te.setInt8(1,2147483649),!te.getInt8(0)&&te.getInt8(1)||u(k[_],{setInt8:function(e,t){ne.call(this,e,t<<24>>24)},setUint8:function(e,t){ne.call(this,e,t<<24>>24)}},!0)}else w=function(e){var t=Y(this,e);this._b=m.call(Array(t),0),this[F]=t},k=function(e,t,n){l(this,k,g),l(e,w,g);var r=e[F],i=p(t);if(i<0||i>r)throw E("Wrong offset!");if(n=void 0===n?r-i:f(n),i+n>r)throw E(b);this[N]=e,this[B]=i,this[F]=n},i&&(J(w,j,"_l"),J(k,I,"_b"),J(k,j,"_l"),J(k,R,"_o")),u(k[_],{getInt8:function(e){return G(this,1,e)[0]<<24>>24},getUint8:function(e){return G(this,1,e)[0]},getInt16:function(e){var t=G(this,2,e,arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=G(this,2,e,arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return q(G(this,4,e,arguments[1]))},getUint32:function(e){return q(G(this,4,e,arguments[1]))>>>0},getFloat32:function(e){return z(G(this,4,e,arguments[1]),23,4)},getFloat64:function(e){return z(G(this,8,e,arguments[1]),52,8)},setInt8:function(e,t){X(this,1,e,U,t)},setUint8:function(e,t){X(this,1,e,U,t)},setInt16:function(e,t){X(this,2,e,W,t,arguments[2])},setUint16:function(e,t){X(this,2,e,W,t,arguments[2])},setInt32:function(e,t){X(this,4,e,K,t,arguments[2])},setUint32:function(e,t){X(this,4,e,K,t,arguments[2])},setFloat32:function(e,t){X(this,4,e,H,t,arguments[2])},setFloat64:function(e,t){X(this,8,e,V,t,arguments[2])}});y(w,v),y(k,g),s(k[_],a.VIEW,!0),t[v]=w,t[g]=k},function(e,t,n){var r=n(8);r(r.G+r.W+r.F*!n(219).ABV,{DataView:n(220).DataView})},function(e,t,n){n(223)("Int8",1,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){"use strict";if(n(6)){var r=n(28),i=n(4),o=n(7),a=n(8),s=n(219),u=n(220),c=n(20),l=n(205),p=n(17),f=n(10),h=n(210),d=n(38),m=n(37),y=n(39),v=n(16),g=n(5),_=n(71),b=n(75),x=n(13),w=n(58),k=n(162),S=n(46),E=n(59),C=n(50).f,A=n(164),T=n(19),O=n(25),D=n(172),M=n(36),P=n(207),I=n(193),j=n(129),R=n(165),N=n(192),F=n(188),B=n(185),L=n(11),z=n(51),q=L.f,U=z.f,W=i.RangeError,K=i.TypeError,V=i.Uint8Array,H="ArrayBuffer",J="Shared"+H,G="BYTES_PER_ELEMENT",X="prototype",Y=Array[X],$=u.ArrayBuffer,Z=u.DataView,Q=D(0),ee=D(2),te=D(3),ne=D(4),re=D(5),ie=D(6),oe=M(!0),ae=M(!1),se=I.values,ue=I.keys,ce=I.entries,le=Y.lastIndexOf,pe=Y.reduce,fe=Y.reduceRight,he=Y.join,de=Y.sort,me=Y.slice,ye=Y.toString,ve=Y.toLocaleString,ge=O("iterator"),_e=O("toStringTag"),be=T("typed_constructor"),xe=T("def_constructor"),we=s.CONSTR,ke=s.TYPED,Se=s.VIEW,Ee="Wrong length!",Ce=D(1,function(e,t){return Pe(P(e,e[xe]),t)}),Ae=o(function(){return 1===new V(new Uint16Array([1]).buffer)[0]}),Te=!!V&&!!V[X].set&&o(function(){new V(1).set({})}),Oe=function(e,t){if(void 0===e)throw K(Ee);var n=+e,r=m(e);if(t&&!_(n,r))throw W(Ee);return r},De=function(e,t){var n=d(e);if(n<0||n%t)throw W("Wrong offset!");return n},Me=function(e){if(x(e)&&ke in e)return e;throw K(e+" is not a typed array!")},Pe=function(e,t){if(!(x(e)&&be in e))throw K("It is not a typed array constructor!");return new e(t)},Ie=function(e,t){return je(P(e,e[xe]),t)},je=function(e,t){for(var n=0,r=t.length,i=Pe(e,r);r>n;)i[n]=t[n++];return i},Re=function(e,t,n){q(e,t,{get:function(){return this._d[n]}})},Ne=function(e){var t,n,r,i,o,a,s=w(e),u=arguments.length,l=u>1?arguments[1]:void 0,p=void 0!==l,f=A(s);if(void 0!=f&&!k(f)){for(a=f.call(s),r=[],t=0;!(o=a.next()).done;t++)r.push(o.value);s=r}for(p&&u>2&&(l=c(l,arguments[2],2)),t=0,n=m(s.length),i=Pe(this,n);n>t;t++)i[t]=p?l(s[t],t):s[t];return i},Fe=function(){for(var e=0,t=arguments.length,n=Pe(this,t);t>e;)n[e]=arguments[e++];return n},Be=!!V&&o(function(){ve.call(new V(1))}),Le=function(){return ve.apply(Be?me.call(Me(this)):Me(this),arguments)},ze={copyWithin:function(e,t){return B.call(Me(this),e,t,arguments.length>2?arguments[2]:void 0)},every:function(e){return ne(Me(this),e,arguments.length>1?arguments[1]:void 0)},fill:function(e){return F.apply(Me(this),arguments)},filter:function(e){return Ie(this,ee(Me(this),e,arguments.length>1?arguments[1]:void 0))},find:function(e){return re(Me(this),e,arguments.length>1?arguments[1]:void 0)},findIndex:function(e){return ie(Me(this),e,arguments.length>1?arguments[1]:void 0)},forEach:function(e){Q(Me(this),e,arguments.length>1?arguments[1]:void 0)},indexOf:function(e){return ae(Me(this),e,arguments.length>1?arguments[1]:void 0)},includes:function(e){return oe(Me(this),e,arguments.length>1?arguments[1]:void 0)},join:function(e){return he.apply(Me(this),arguments)},lastIndexOf:function(e){return le.apply(Me(this),arguments)},map:function(e){return Ce(Me(this),e,arguments.length>1?arguments[1]:void 0)},reduce:function(e){return pe.apply(Me(this),arguments)},reduceRight:function(e){return fe.apply(Me(this),arguments)},reverse:function(){for(var e,t=this,n=Me(t).length,r=Math.floor(n/2),i=0;i1?arguments[1]:void 0)},sort:function(e){return de.call(Me(this),e)},subarray:function(e,t){var n=Me(this),r=n.length,i=y(e,r);return new(P(n,n[xe]))(n.buffer,n.byteOffset+i*n.BYTES_PER_ELEMENT,m((void 0===t?r:y(t,r))-i))}},qe=function(e,t){return Ie(this,me.call(Me(this),e,t))},Ue=function(e){Me(this);var t=De(arguments[1],1),n=this.length,r=w(e),i=m(r.length),o=0;if(i+t>n)throw W(Ee);for(;o255?255:255&r),i.v[d](n*t+i.o,r,Ae)},O=function(e,t){q(e,t,{get:function(){return A(this,t)},set:function(e){return T(this,t,e)},enumerable:!0})};_?(y=n(function(e,n,r,i){l(e,y,c,"_d");var o,a,s,u,p=0,h=0;if(x(n)){if(!(n instanceof $||(u=b(n))==H||u==J))return ke in n?je(y,n):Ne.call(y,n);o=n,h=De(r,t);var d=n.byteLength;if(void 0===i){if(d%t)throw W(Ee);if(a=d-h,a<0)throw W(Ee)}else if(a=m(i)*t,a+h>d)throw W(Ee);s=a/t}else s=Oe(n,!0),a=s*t,o=new $(a);for(f(e,"_d",{b:o,o:h,l:a,e:s,v:new Z(o)});p=n.length)return{value:void 0,done:!0};while(!((e=n[t._i++])in t._t));return{value:e,done:!1}}),r(r.S,"Reflect",{enumerate:function(e){return new o(e)}})},function(e,t,n){function r(e,t){var n,s,l=arguments.length<3?e:arguments[2];return c(e)===l?e[t]:(n=i.f(e,t))?a(n,"value")?n.value:void 0!==n.get?n.get.call(l):void 0:u(s=o(e))?r(s,t,l):void 0}var i=n(51),o=n(59),a=n(5),s=n(8),u=n(13),c=n(12);s(s.S,"Reflect",{get:r})},function(e,t,n){var r=n(51),i=n(8),o=n(12);i(i.S,"Reflect",{getOwnPropertyDescriptor:function(e,t){return r.f(o(e),t)}})},function(e,t,n){var r=n(8),i=n(59),o=n(12);r(r.S,"Reflect",{getPrototypeOf:function(e){return i(o(e))}})},function(e,t,n){var r=n(8);r(r.S,"Reflect",{has:function(e,t){return t in e}})},function(e,t,n){var r=n(8),i=n(12),o=Object.isExtensible;r(r.S,"Reflect",{isExtensible:function(e){return i(e),!o||o(e)}})},function(e,t,n){var r=n(8);r(r.S,"Reflect",{ownKeys:n(243)})},function(e,t,n){var r=n(50),i=n(43),o=n(12),a=n(4).Reflect;e.exports=a&&a.ownKeys||function(e){var t=r.f(o(e)),n=i.f;return n?t.concat(n(e)):t}},function(e,t,n){var r=n(8),i=n(12),o=Object.preventExtensions;r(r.S,"Reflect",{preventExtensions:function(e){i(e);try{return o&&o(e),!0}catch(e){return!1}}})},function(e,t,n){function r(e,t,n){var u,f,h=arguments.length<4?e:arguments[3],d=o.f(l(e),t);if(!d){if(p(f=a(e)))return r(f,t,n,h);d=c(0)}return s(d,"value")?!(d.writable===!1||!p(h))&&(u=o.f(h,t)||c(0),u.value=n,i.f(h,t,u),!0):void 0!==d.set&&(d.set.call(h,n),!0)}var i=n(11),o=n(51),a=n(59),s=n(5),u=n(8),c=n(17),l=n(12),p=n(13);u(u.S,"Reflect",{set:r})},function(e,t,n){var r=n(8),i=n(73);i&&r(r.S,"Reflect",{setPrototypeOf:function(e,t){i.check(e,t);try{return i.set(e,t),!0}catch(e){return!1}}})},function(e,t,n){"use strict";var r=n(8),i=n(36)(!0);r(r.P,"Array",{includes:function(e){return i(this,e,arguments.length>1?arguments[1]:void 0)}}),n(186)("includes")},function(e,t,n){"use strict";var r=n(8),i=n(127)(!0);r(r.P,"String",{at:function(e){return i(this,e)}})},function(e,t,n){"use strict";var r=n(8),i=n(250);r(r.P,"String",{padStart:function(e){return i(this,e,arguments.length>1?arguments[1]:void 0,!0)}})},function(e,t,n){var r=n(37),i=n(91),o=n(35);e.exports=function(e,t,n,a){var s=String(o(e)),u=s.length,c=void 0===n?" ":String(n),l=r(t);if(l<=u||""==c)return s;var p=l-u,f=i.call(c,Math.ceil(p/c.length));return f.length>p&&(f=f.slice(0,p)),a?f+s:s+f}},function(e,t,n){"use strict";var r=n(8),i=n(250);r(r.P,"String",{padEnd:function(e){return i(this,e,arguments.length>1?arguments[1]:void 0,!1)}})},function(e,t,n){"use strict";n(83)("trimLeft",function(e){return function(){return e(this,1)}},"trimStart")},function(e,t,n){"use strict";n(83)("trimRight",function(e){return function(){return e(this,2)}},"trimEnd")},function(e,t,n){"use strict";var r=n(8),i=n(35),o=n(37),a=n(134),s=n(196),u=RegExp.prototype,c=function(e,t){this._r=e,this._s=t};n(130)(c,"RegExp String",function(){var e=this._r.exec(this._s);return{value:e,done:null===e}}),r(r.P,"String",{matchAll:function(e){if(i(this),!a(e))throw TypeError(e+" is not a regexp!");var t=String(this),n="flags"in u?String(e.flags):s.call(e),r=new RegExp(e.source,~n.indexOf("g")?n:"g"+n);return r.lastIndex=o(e.lastIndex),new c(r,t)}})},[1440,27],[1441,27],function(e,t,n){var r=n(8),i=n(243),o=n(32),a=n(51),s=n(163);r(r.S,"Object",{getOwnPropertyDescriptors:function(e){for(var t,n=o(e),r=a.f,u=i(n),c={},l=0;u.length>l;)s(c,t=u[l++],r(n,t));return c}})},function(e,t,n){var r=n(8),i=n(259)(!1);r(r.S,"Object",{values:function(e){return i(e)}})},function(e,t,n){var r=n(30),i=n(32),o=n(44).f;e.exports=function(e){return function(t){for(var n,a=i(t),s=r(a),u=s.length,c=0,l=[];u>c;)o.call(a,n=s[c++])&&l.push(e?[n,a[n]]:a[n]);return l}}},function(e,t,n){var r=n(8),i=n(259)(!0);r(r.S,"Object",{entries:function(e){return i(e)}})},function(e,t,n){"use strict";var r=n(8),i=n(58),o=n(21),a=n(11);n(6)&&r(r.P+n(262),"Object",{__defineGetter__:function(e,t){a.f(i(this),e,{get:o(t),enumerable:!0,configurable:!0})}})},function(e,t,n){e.exports=n(28)||!n(7)(function(){var e=Math.random();__defineSetter__.call(null,e,function(){}),delete n(4)[e]})},function(e,t,n){"use strict";var r=n(8),i=n(58),o=n(21),a=n(11);n(6)&&r(r.P+n(262),"Object",{__defineSetter__:function(e,t){a.f(i(this),e,{set:o(t),enumerable:!0,configurable:!0})}})},function(e,t,n){"use strict";var r=n(8),i=n(58),o=n(16),a=n(59),s=n(51).f;n(6)&&r(r.P+n(262),"Object",{__lookupGetter__:function(e){var t,n=i(this),r=o(e,!0);do if(t=s(n,r))return t.get;while(n=a(n))}})},function(e,t,n){"use strict";var r=n(8),i=n(58),o=n(16),a=n(59),s=n(51).f;n(6)&&r(r.P+n(262),"Object",{__lookupSetter__:function(e){var t,n=i(this),r=o(e,!0);do if(t=s(n,r))return t.set;while(n=a(n))}})},function(e,t,n){var r=n(8);r(r.P+r.R,"Map",{toJSON:n(267)("Map")})},function(e,t,n){var r=n(75),i=n(268);e.exports=function(e){return function(){if(r(this)!=e)throw TypeError(e+"#toJSON isn't generic");return i(this)}}},function(e,t,n){var r=n(206);e.exports=function(e,t){var n=[];return r(e,!1,n.push,n,t),n}},function(e,t,n){var r=n(8);r(r.P+r.R,"Set",{toJSON:n(267)("Set")})},function(e,t,n){var r=n(8);r(r.S,"System",{global:n(4)})},function(e,t,n){var r=n(8),i=n(34);r(r.S,"Error",{isError:function(e){return"Error"===i(e)}})},function(e,t,n){var r=n(8);r(r.S,"Math",{iaddh:function(e,t,n,r){var i=e>>>0,o=t>>>0,a=n>>>0;return o+(r>>>0)+((i&a|(i|a)&~(i+a>>>0))>>>31)|0}})},function(e,t,n){var r=n(8);r(r.S,"Math",{isubh:function(e,t,n,r){var i=e>>>0,o=t>>>0,a=n>>>0;return o-(r>>>0)-((~i&a|~(i^a)&i-a>>>0)>>>31)|0}})},function(e,t,n){var r=n(8);r(r.S,"Math",{imulh:function(e,t){var n=65535,r=+e,i=+t,o=r&n,a=i&n,s=r>>16,u=i>>16,c=(s*a>>>0)+(o*a>>>16);return s*u+(c>>16)+((o*u>>>0)+(c&n)>>16)}})},function(e,t,n){var r=n(8);r(r.S,"Math",{umulh:function(e,t){var n=65535,r=+e,i=+t,o=r&n,a=i&n,s=r>>>16,u=i>>>16,c=(s*a>>>0)+(o*a>>>16);return s*u+(c>>>16)+((o*u>>>0)+(c&n)>>>16)}})},function(e,t,n){var r=n(277),i=n(12),o=r.key,a=r.set;r.exp({defineMetadata:function(e,t,n,r){a(e,t,i(n),o(r))}})},function(e,t,n){var r=n(211),i=n(8),o=n(23)("metadata"),a=o.store||(o.store=new(n(215))),s=function(e,t,n){var i=a.get(e);if(!i){if(!n)return;a.set(e,i=new r)}var o=i.get(t);if(!o){if(!n)return;i.set(t,o=new r)}return o},u=function(e,t,n){var r=s(t,n,!1);return void 0!==r&&r.has(e)},c=function(e,t,n){var r=s(t,n,!1);return void 0===r?void 0:r.get(e)},l=function(e,t,n,r){s(n,r,!0).set(e,t)},p=function(e,t){var n=s(e,t,!1),r=[];return n&&n.forEach(function(e,t){r.push(t)}),r},f=function(e){return void 0===e||"symbol"==typeof e?e:String(e)},h=function(e){i(i.S,"Reflect",e)};e.exports={store:a,map:s,has:u,get:c,set:l,keys:p,key:f,exp:h}},function(e,t,n){var r=n(277),i=n(12),o=r.key,a=r.map,s=r.store;r.exp({deleteMetadata:function(e,t){var n=arguments.length<3?void 0:o(arguments[2]),r=a(i(t),n,!1);if(void 0===r||!r.delete(e))return!1;if(r.size)return!0;var u=s.get(t);return u.delete(n),!!u.size||s.delete(t)}})},function(e,t,n){var r=n(277),i=n(12),o=n(59),a=r.has,s=r.get,u=r.key,c=function(e,t,n){var r=a(e,t,n);if(r)return s(e,t,n);var i=o(t);return null!==i?c(e,i,n):void 0};r.exp({getMetadata:function(e,t){return c(e,i(t),arguments.length<3?void 0:u(arguments[2]))}})},function(e,t,n){var r=n(214),i=n(268),o=n(277),a=n(12),s=n(59),u=o.keys,c=o.key,l=function(e,t){var n=u(e,t),o=s(e);if(null===o)return n;var a=l(o,t);return a.length?n.length?i(new r(n.concat(a))):a:n};o.exp({getMetadataKeys:function(e){return l(a(e),arguments.length<2?void 0:c(arguments[1]))}})},function(e,t,n){var r=n(277),i=n(12),o=r.get,a=r.key;r.exp({getOwnMetadata:function(e,t){return o(e,i(t),arguments.length<3?void 0:a(arguments[2]))}})},function(e,t,n){var r=n(277),i=n(12),o=r.keys,a=r.key;r.exp({getOwnMetadataKeys:function(e){return o(i(e),arguments.length<2?void 0:a(arguments[1]))}})},function(e,t,n){var r=n(277),i=n(12),o=n(59),a=r.has,s=r.key,u=function(e,t,n){var r=a(e,t,n);if(r)return!0;var i=o(t);return null!==i&&u(e,i,n)};r.exp({hasMetadata:function(e,t){return u(e,i(t),arguments.length<3?void 0:s(arguments[2]))}})},function(e,t,n){var r=n(277),i=n(12),o=r.has,a=r.key;r.exp({hasOwnMetadata:function(e,t){return o(e,i(t),arguments.length<3?void 0:a(arguments[2]))}})},function(e,t,n){var r=n(277),i=n(12),o=n(21),a=r.key,s=r.set;r.exp({metadata:function(e,t){return function(n,r){s(e,t,(void 0!==r?i:o)(n),a(r))}}})},function(e,t,n){var r=n(8),i=n(209)(),o=n(4).process,a="process"==n(34)(o);r(r.G,{asap:function(e){var t=a&&o.domain;i(t?t.bind(e):e)}})},function(e,t,n){"use strict";var r=n(8),i=n(4),o=n(9),a=n(209)(),s=n(25)("observable"),u=n(21),c=n(12),l=n(205),p=n(210),f=n(10),h=n(206),d=h.RETURN,m=function(e){return null==e?void 0:u(e)},y=function(e){var t=e._c;t&&(e._c=void 0,t())},v=function(e){return void 0===e._o},g=function(e){v(e)||(e._o=void 0,y(e))},_=function(e,t){c(e),this._c=void 0,this._o=e,e=new b(this);try{var n=t(e),r=n;null!=n&&("function"==typeof n.unsubscribe?n=function(){r.unsubscribe()}:u(n),this._c=n)}catch(t){return void e.error(t)}v(this)&&y(this)};_.prototype=p({},{unsubscribe:function(){g(this)}});var b=function(e){this._s=e};b.prototype=p({},{next:function(e){var t=this._s;if(!v(t)){var n=t._o;try{var r=m(n.next);if(r)return r.call(n,e)}catch(e){try{g(t)}finally{throw e}}}},error:function(e){var t=this._s;if(v(t))throw e;var n=t._o;t._o=void 0;try{var r=m(n.error);if(!r)throw e;e=r.call(n,e)}catch(e){try{y(t)}finally{throw e}}return y(t),e},complete:function(e){var t=this._s;if(!v(t)){var n=t._o;t._o=void 0;try{var r=m(n.complete);e=r?r.call(n,e):void 0}catch(e){try{y(t)}finally{throw e}}return y(t),e}}});var x=function(e){l(this,x,"Observable","_f")._f=u(e)};p(x.prototype,{subscribe:function(e){return new _(e,this._f)},forEach:function(e){var t=this;return new(o.Promise||i.Promise)(function(n,r){u(e);var i=t.subscribe({next:function(t){try{return e(t)}catch(e){r(e),i.unsubscribe()}},error:r,complete:n})})}}),p(x,{from:function(e){var t="function"==typeof this?this:x,n=m(c(e)[s]);if(n){var r=c(n.call(e));return r.constructor===t?r:new t(function(e){return r.subscribe(e)})}return new t(function(t){var n=!1;return a(function(){if(!n){try{if(h(e,!1,function(e){if(t.next(e),n)return d})===d)return}catch(e){if(n)throw e;return void t.error(e)}t.complete()}}),function(){n=!0}})},of:function(){for(var e=0,t=arguments.length,n=Array(t);ea;)(n[a]=arguments[a++])===s&&(u=!0);return function(){var r,o=this,a=arguments.length,c=0,l=0;if(!u&&!a)return i(e,n,o);if(r=n.slice(),u)for(;t>c;c++)r[c]===s&&(r[c]=arguments[l++]);for(;a>l;)r.push(arguments[l++]);return i(e,r,o)}}},function(e,t,n){e.exports=n(4)},function(e,t,n){var r=n(8),i=n(208);r(r.G+r.B,{setImmediate:i.set,clearImmediate:i.clear})},function(e,t,n){for(var r=n(193),i=n(18),o=n(4),a=n(10),s=n(129),u=n(25),c=u("iterator"),l=u("toStringTag"),p=s.Array,f=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],h=0;h<5;h++){var d,m=f[h],y=o[m],v=y&&y.prototype;if(v){v[c]||a(v,c,p),v[l]||a(v,l,m),s[m]=p;for(d in r)v[d]||i(v,d,r[d],!0)}}},function(e,t){(function(t){!function(t){"use strict";function n(e,t,n,r){var o=t&&t.prototype instanceof i?t:i,a=Object.create(o.prototype),s=new h(r||[]);return a._invoke=c(e,n,s),a}function r(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}function i(){}function o(){}function a(){}function s(e){["next","throw","return"].forEach(function(t){e[t]=function(e){return this._invoke(t,e)}})}function u(e){function n(t,i,o,a){var s=r(e[t],e,i);if("throw"!==s.type){var u=s.arg,c=u.value;return c&&"object"==typeof c&&g.call(c,"__await")?Promise.resolve(c.__await).then(function(e){n("next",e,o,a)},function(e){n("throw",e,o,a)}):Promise.resolve(c).then(function(e){u.value=e,o(u)},a)}a(s.arg)}function i(e,t){function r(){return new Promise(function(r,i){n(e,t,r,i)})}return o=o?o.then(r,r):r()}"object"==typeof t.process&&t.process.domain&&(n=t.process.domain.bind(n));var o;this._invoke=i}function c(e,t,n){var i=E;return function(o,a){if(i===A)throw new Error("Generator is already running");if(i===T){if("throw"===o)throw a;return m()}for(n.method=o,n.arg=a;;){var s=n.delegate;if(s){var u=l(s,n);if(u){if(u===O)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(i===E)throw i=T,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);i=A;var c=r(e,t,n);if("normal"===c.type){if(i=n.done?T:C,c.arg===O)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(i=T,n.method="throw",n.arg=c.arg)}}}function l(e,t){var n=e.iterator[t.method];if(n===y){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=y,l(e,t),"throw"===t.method))return O;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return O}var i=r(n,e.iterator,t.arg);if("throw"===i.type)return t.method="throw",t.arg=i.arg,t.delegate=null,O;var o=i.arg;return o?o.done?(t[e.resultName]=o.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=y),t.delegate=null,O):o:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,O)}function p(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function f(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function h(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(p,this),this.reset(!0)}function d(e){if(e){var t=e[b];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,r=function t(){for(;++n=0;--r){var i=this.tryEntries[r],o=i.completion;if("root"===i.tryLoc)return t("end");if(i.tryLoc<=this.prev){var a=g.call(i,"catchLoc"),s=g.call(i,"finallyLoc");if(a&&s){if(this.prev=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&g.call(r,"finallyLoc")&&this.prev=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),f(n),O}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var i=r.arg;f(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:d(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=y),O}}}("object"==typeof t?t:"object"==typeof window?window:"object"==typeof self?self:this)}).call(t,function(){return this}())},function(e,t,n){n(295),e.exports=n(9).RegExp.escape},function(e,t,n){var r=n(8),i=n(296)(/[\\^$*+?.()|[\]{}]/g,"\\$&");r(r.S,"RegExp",{escape:function(e){return i(e)}})},function(e,t){e.exports=function(e,t){var n=t===Object(t)?function(e){return t[e]}:t;return function(t){return String(t).replace(e,n)}}},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a=n(298),s=i(a),u=n(303),c=i(u),l=n(334),p=i(l),f=n(559),h=i(f),d=n(1376),m=r(d),y=n(335),v=["url","spec","validatorUrl","onComplete","onFailure","authorizations","docExpansion","apisSorter","operationsSorter","supportedSubmitMethods","dom_id","defaultModelRendering","oauth2RedirectUrl","showRequestHeaders","custom","modelPropertyMacro","parameterMacro"],g={PACKAGE_VERSION:"3.0.13",GIT_COMMIT:"g5952bb6",GIT_DIRTY:!0},_=g.GIT_DIRTY,b=g.GIT_COMMIT,x=g.PACKAGE_VERSION;e.exports=function(e){p.default.versions=p.default.versions||{},p.default.versions.swaggerUi=x+"/"+(b||"unknown")+(_?"-dirty":"");var t={dom_id:null,spec:{},url:"",layout:"BaseLayout",validatorUrl:"https://online.swagger.io/validator",configs:{},custom:{},presets:[],plugins:[],fn:{},components:{},state:{},store:{}},n=(0,s.default)({},t,e),r=(0,s.default)({},n.store,{system:{configs:n.configs},plugins:n.presets,state:{layout:{layout:n.layout},spec:{spec:"",url:n.url}}}),i=function(){return{fn:n.fn,components:n.components,state:n.state}},a=new c.default(r);a.register([n.plugins,i]);var u=a.getSystem(),l=(0,y.parseSeach)();u.initOAuth=u.authActions.configureAuth;var f=function(e){if("object"!==("undefined"==typeof n?"undefined":o(n)))return u;var t=u.specSelectors.getLocalConfig?u.specSelectors.getLocalConfig():{},r=(0,s.default)({},t,n,e||{},l);return a.setConfigs((0,y.filterConfigs)(r,v)),null!==e&&(!l.url&&"object"===o(r.spec)&&Object.keys(r.spec).length?(u.specActions.updateUrl(""),u.specActions.updateLoadingStatus("success"),u.specActions.updateSpec(JSON.stringify(r.spec))):u.specActions.download&&r.url&&(u.specActions.updateUrl(r.url),u.specActions.download(r.url))),r.dom_id?u.render(r.dom_id,"App"):console.error("Skipped rendering: no `dom_id` was specified"),u},h=l.config||n.configUrl;if(!h||!u.specActions.getConfigByUrl||u.specActions.getConfigByUrl&&!u.specActions.getConfigByUrl(h,f))return f()},e.exports.presets={apis:h.default},e.exports.plugins=m},function(e,t,n){(function(t){/*! + * @description Recursive object extending + * @author Viacheslav Lotsmanov + * @license MIT + * + * The MIT License (MIT) + * + * Copyright (c) 2013-2015 Viacheslav Lotsmanov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +"use strict";function n(e){return e instanceof t||e instanceof Date||e instanceof RegExp}function r(e){if(e instanceof t){var n=new t(e.length);return e.copy(n),n}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e);throw new Error("Unexpected situation")}function i(e){var t=[];return e.forEach(function(e,a){"object"==typeof e&&null!==e?Array.isArray(e)?t[a]=i(e):n(e)?t[a]=r(e):t[a]=o({},e):t[a]=e}),t}var o=e.exports=function(){if(arguments.length<1||"object"!=typeof arguments[0])return!1;if(arguments.length<2)return arguments[0];var e,t,a=arguments[0],s=Array.prototype.slice.call(arguments,1);return s.forEach(function(s){"object"!=typeof s||Array.isArray(s)||Object.keys(s).forEach(function(u){return t=a[u],e=s[u],e===a?void 0:"object"!=typeof e||null===e?void(a[u]=e):Array.isArray(e)?void(a[u]=i(e)):n(e)?void(a[u]=r(e)):"object"!=typeof t||null===t||Array.isArray(t)?void(a[u]=o({},e)):void(a[u]=o(t,e))})}),a}}).call(t,n(299).Buffer)},function(e,t,n){(function(e){/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +"use strict";function r(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}function i(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(i()=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|e}function y(e){return+e!=e&&(e=0),a.alloc(+e)}function v(e,t){if(a.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return V(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return G(e).length;default:if(r)return V(e).length;t=(""+t).toLowerCase(),r=!0}}function g(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if(n>>>=0,t>>>=0,n<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return I(this,t,n);case"utf8":case"utf-8":return O(this,t,n);case"ascii":return M(this,t,n);case"latin1":case"binary":return P(this,t,n);case"base64":return T(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function _(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function b(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=a.from(t,r)),a.isBuffer(t))return 0===t.length?-1:x(e,t,n,r,i);if("number"==typeof t)return t&=255,a.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):x(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function x(e,t,n,r,i){function o(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var a=1,s=e.length,u=t.length;if(void 0!==r&&(r=String(r).toLowerCase(),"ucs2"===r||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,n/=2}var c;if(i){var l=-1;for(c=n;cs&&(n=s-u),c=n;c>=0;c--){for(var p=!0,f=0;fi&&(r=i)):r=i;var o=t.length;if(o%2!==0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var a=0;a239?4:o>223?3:o>191?2:1;if(i+s<=n){var u,c,l,p;switch(s){case 1:o<128&&(a=o);break;case 2:u=e[i+1],128===(192&u)&&(p=(31&o)<<6|63&u,p>127&&(a=p));break;case 3:u=e[i+1],c=e[i+2],128===(192&u)&&128===(192&c)&&(p=(15&o)<<12|(63&u)<<6|63&c,p>2047&&(p<55296||p>57343)&&(a=p));break;case 4:u=e[i+1],c=e[i+2],l=e[i+3],128===(192&u)&&128===(192&c)&&128===(192&l)&&(p=(15&o)<<18|(63&u)<<12|(63&c)<<6|63&l,p>65535&&p<1114112&&(a=p))}}null===a?(a=65533,s=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|1023&a),r.push(a),i+=s}return D(r)}function D(e){var t=e.length;if(t<=ee)return String.fromCharCode.apply(String,e);for(var n="",r=0;rr)&&(n=r);for(var i="",o=t;on)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,n,r,i,o){if(!a.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function F(e,t,n,r){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-n,2);i>>8*(r?i:1-i)}function B(e,t,n,r){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-n,4);i>>8*(r?i:3-i)&255}function L(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function z(e,t,n,r,i){return i||L(e,t,n,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(e,t,n,r,23,4),n+4}function q(e,t,n,r,i){return i||L(e,t,n,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(e,t,n,r,52,8),n+8}function U(e){if(e=W(e).replace(te,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function W(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function K(e){return e<16?"0"+e.toString(16):e.toString(16)}function V(e,t){t=t||1/0;for(var n,r=e.length,i=null,o=[],a=0;a55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=(i-55296<<10|n-56320)+65536}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function H(e){for(var t=[],n=0;n>8,i=n%256,o.push(i),o.push(r);return o}function G(e){return $.toByteArray(U(e))}function X(e,t,n,r){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function Y(e){return e!==e}var $=n(300),Z=n(301),Q=n(302);t.Buffer=a,t.SlowBuffer=y,t.INSPECT_MAX_BYTES=50,a.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:r(),t.kMaxLength=i(),a.poolSize=8192,a._augment=function(e){return e.__proto__=a.prototype,e},a.from=function(e,t,n){return s(null,e,t,n)},a.TYPED_ARRAY_SUPPORT&&(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0})),a.alloc=function(e,t,n){return c(null,e,t,n)},a.allocUnsafe=function(e){return l(null,e)},a.allocUnsafeSlow=function(e){return l(null,e)},a.isBuffer=function(e){return!(null==e||!e._isBuffer)},a.compare=function(e,t){if(!a.isBuffer(e)||!a.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,i=0,o=Math.min(n,r);i0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},a.prototype.compare=function(e,t,n,r,i){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,i>>>=0,this===e)return 0;for(var o=i-r,s=n-t,u=Math.min(o,s),c=this.slice(r,i),l=e.slice(t,n),p=0;pi)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return k(this,e,t,n);case"ascii":return S(this,e,t,n);case"latin1":case"binary":return E(this,e,t,n);case"base64":return C(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ee=4096;a.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),t0&&(i*=256);)r+=this[e+--t]*i;return r},a.prototype.readUInt8=function(e,t){return t||R(e,1,this.length),this[e]},a.prototype.readUInt16LE=function(e,t){return t||R(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function(e,t){return t||R(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function(e,t){return t||R(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function(e,t){return t||R(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||R(e,t,this.length);for(var r=this[e],i=1,o=0;++o=i&&(r-=Math.pow(2,8*t)),r},a.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||R(e,t,this.length);for(var r=t,i=1,o=this[e+--r];r>0&&(i*=256);)o+=this[e+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},a.prototype.readInt8=function(e,t){return t||R(e,1,this.length),128&this[e]?(255-this[e]+1)*-1:this[e]},a.prototype.readInt16LE=function(e,t){t||R(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt16BE=function(e,t){t||R(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt32LE=function(e,t){return t||R(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return t||R(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function(e,t){return t||R(e,4,this.length),Z.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return t||R(e,4,this.length),Z.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return t||R(e,8,this.length),Z.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return t||R(e,8,this.length),Z.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t|=0,n|=0,!r){var i=Math.pow(2,8*n)-1;N(this,e,t,n,i,0)}var o=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+o]=e/a&255;return t+n},a.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,1,255,0),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},a.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):F(this,e,t,!0),t+2},a.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):F(this,e,t,!1),t+2},a.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):B(this,e,t,!0),t+4},a.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):B(this,e,t,!1),t+4},a.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var i=Math.pow(2,8*n-1);N(this,e,t,n,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+n},a.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var i=Math.pow(2,8*n-1);N(this,e,t,n,i-1,-i)}var o=n-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+n},a.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,1,127,-128),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):F(this,e,t,!0),t+2},a.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):F(this,e,t,!1),t+2},a.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):B(this,e,t,!0),t+4},a.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):B(this,e,t,!1),t+4},a.prototype.writeFloatLE=function(e,t,n){return z(this,e,t,!0,n)},a.prototype.writeFloatBE=function(e,t,n){return z(this,e,t,!1,n)},a.prototype.writeDoubleLE=function(e,t,n){return q(this,e,t,!0,n)},a.prototype.writeDoubleBE=function(e,t,n){return q(this,e,t,!1,n)},a.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(o<1e3||!a.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0);var o;if("number"==typeof e)for(o=t;o0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function r(e){return 3*e.length/4-n(e)}function i(e){var t,r,i,o,a,s,u=e.length;a=n(e),s=new l(3*u/4-a),i=a>0?u-4:u;var p=0;for(t=0,r=0;t>16&255,s[p++]=o>>8&255,s[p++]=255&o;return 2===a?(o=c[e.charCodeAt(t)]<<2|c[e.charCodeAt(t+1)]>>4,s[p++]=255&o):1===a&&(o=c[e.charCodeAt(t)]<<10|c[e.charCodeAt(t+1)]<<4|c[e.charCodeAt(t+2)]>>2,s[p++]=o>>8&255,s[p++]=255&o),s}function o(e){return u[e>>18&63]+u[e>>12&63]+u[e>>6&63]+u[63&e]}function a(e,t,n){for(var r,i=[],a=t;al?l:c+s));return 1===r?(t=e[n-1],i+=u[t>>2],i+=u[t<<4&63],i+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],i+=u[t>>10],i+=u[t>>4&63],i+=u[t<<2&63],i+="="),o.push(i),o.join("")}t.byteLength=r,t.toByteArray=i,t.fromByteArray=s;for(var u=[],c=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",f=0,h=p.length;f>1,l=-7,p=n?i-1:0,f=n?-1:1,h=e[t+p];for(p+=f,o=h&(1<<-l)-1,h>>=-l,l+=s;l>0;o=256*o+e[t+p],p+=f,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=r;l>0;a=256*a+e[t+p],p+=f,l-=8);if(0===o)o=1-c;else{if(o===u)return a?NaN:(h?-1:1)*(1/0);a+=Math.pow(2,r),o-=c}return(h?-1:1)*a*Math.pow(2,o-r)},t.write=function(e,t,n,r,i,o){var a,s,u,c=8*o-i-1,l=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,h=r?0:o-1,d=r?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),t+=a+p>=1?f/u:f*Math.pow(2,1-p),t*u>=2&&(a++,u/=2),a+p>=l?(s=0,a=l):a+p>=1?(s=(t*u-1)*Math.pow(2,i),a+=p):(s=t*Math.pow(2,p-1)*Math.pow(2,i),a=0));i>=8;e[n+h]=255&s,h+=d,s/=256,i-=8);for(a=a<0;e[n+h]=255&a,h+=d,a/=256,c-=8);e[n+h-d]|=128*m}},function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t,n){var r=[(0,E.systemThunkMiddleware)(n)],i=S.default.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__||d.compose;return(0,d.createStore)(e,t,i(d.applyMiddleware.apply(void 0,r)))}function s(e,t){return(0,E.isObject)(e)&&!(0,E.isArray)(e)?e:(0,E.isFunc)(e)?s(e(t),t):(0,E.isArray)(e)?e.map(function(e){return s(e,t)}).reduce(u,{}):{}}function u(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!(0,E.isObject)(e))return{};if(!(0,E.isObject)(t))return e;var n=e.statePlugins;if((0,E.isObject)(n))for(var r in n){var i=n[r];if((0,E.isObject)(i)&&(0,E.isObject)(i.wrapActions)){var o=i.wrapActions;for(var a in o){var s=o[a];Array.isArray(s)||(s=[s],o[a]=s),t&&t.statePlugins&&t.statePlugins[r]&&t.statePlugins[r].wrapActions&&t.statePlugins[r].wrapActions[a]&&(t.statePlugins[r].wrapActions[a]=o[a].concat(t.statePlugins[r].wrapActions[a]))}}}return(0,g.default)(e,t)}function c(e){var t=(0,E.objMap)(e,function(e){return e.reducers});return l(t)}function l(e){var t=Object.keys(e).reduce(function(t,n){return t[n]=p(e[n]),t},{});return Object.keys(t).length?(0,_.combineReducers)(t):C}function p(e){return function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new m.Map,n=arguments[1];if(!e)return t;var r=e[n.type];return r?r(t,n):t}}function f(e,t,n){var r=a(e,t,n);return r}Object.defineProperty(t,"__esModule",{value:!0});var h=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{};o(this,e),(0,g.default)(this,{state:{},plugins:[],system:{configs:{},fn:{},components:{},rootInjects:{},statePlugins:{}},boundSystem:{},toolbox:{}},t),this.getSystem=this._getSystem.bind(this),this.store=f(C,(0,m.fromJS)(this.state),this.getSystem),this.buildSystem(!1),this.register(this.plugins)}return h(e,[{key:"getStore",value:function(){return this.store}},{key:"register",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=s(e,this.getSystem());u(this.system,n),t&&this.buildSystem()}},{key:"buildSystem",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=this.getStore().dispatch,n=this.getStore().getState;this.boundSystem=Object.assign({},this.getRootInjects(),this.getWrappedAndBoundActions(t),this.getBoundSelectors(n,this.getSystem),this.getStateThunks(n),this.getFn(),this.getConfigs()),e&&this.rebuildReducer()}},{key:"_getSystem",value:function(){return this.boundSystem}},{key:"getRootInjects",value:function(){return Object.assign({getSystem:this.getSystem,getStore:this.getStore.bind(this),getComponents:this.getComponents.bind(this),getState:this.getStore().getState,getConfigs:this._getConfigs.bind(this),Im:y.default},this.system.rootInjects||{})}},{key:"_getConfigs",value:function(){return this.system.configs}},{key:"getConfigs",value:function(){return{configs:this.system.configs}}},{key:"setConfigs",value:function(e){this.system.configs=e}},{key:"rebuildReducer",value:function(){this.store.replaceReducer(c(this.system.statePlugins))}},{key:"getType",value:function(e){var t=e[0].toUpperCase()+e.slice(1);return(0,E.objReduce)(this.system.statePlugins,function(n,r){var o=n[e];if(o)return i({},r+t,o)})}},{key:"getSelectors",value:function(){return this.getType("selectors")}},{key:"getActions",value:function(){var e=this.getType("actions");return(0,E.objMap)(e,function(e){return(0,E.objReduce)(e,function(e,t){if((0,E.isFn)(e))return i({},t,e)})})}},{key:"getWrappedAndBoundActions",value:function(e){var t=this,n=this.getBoundActions(e);return(0,E.objMap)(n,function(e,n){var r=t.system.statePlugins[n.slice(0,-7)].wrapActions;return r?(0,E.objMap)(e,function(e,n){var i=r[n];return i?(Array.isArray(i)||(i=[i]),i.reduce(function(e,n){var r=function(){return n(e,t.getSystem()).apply(void 0,arguments)};if(!(0,E.isFn)(r))throw new TypeError("wrapActions needs to return a function that returns a new function (ie the wrapped action)");return r},e||Function.prototype)):e}):e})}},{key:"getStates",value:function(e){return Object.keys(this.system.statePlugins).reduce(function(t,n){return t[n]=e.get(n),t},{})}},{key:"getStateThunks",value:function(e){return Object.keys(this.system.statePlugins).reduce(function(t,n){return t[n]=function(){return e().get(n)},t},{})}},{key:"getFn",value:function(){return{fn:this.system.fn}}},{key:"getComponents",value:function(e){return"undefined"!=typeof e?this.system.components[e]:this.system.components}},{key:"getBoundSelectors",value:function(e,t){return(0,E.objMap)(this.getSelectors(),function(n,r){var i=[r.slice(0,-9)],o=function(){return e().getIn(i)};return(0,E.objMap)(n,function(e){return function(){for(var n=arguments.length,r=Array(n),i=0;i>>0;if(""+n!==t||4294967295===n)return NaN;t=n}return t<0?d(e)+t:t}function y(){return!0}function v(e,t,n){return(0===e||void 0!==n&&e<=-n)&&(void 0===t||void 0!==n&&t>=n)}function g(e,t){return b(e,t,0)}function _(e,t){return b(e,t,t)}function b(e,t,n){return void 0===e?n:e<0?Math.max(0,t+e):void 0===t?e:Math.min(t,e)}function x(e){this.next=e}function w(e,t,n,r){var i=0===e?t:1===e?n:[t,n];return r?r.value=i:r={value:i,done:!1},r}function k(){return{value:void 0,done:!0}}function S(e){return!!A(e)}function E(e){return e&&"function"==typeof e.next}function C(e){var t=A(e);return t&&t.call(e)}function A(e){var t=e&&(kn&&e[kn]||e[Sn]);if("function"==typeof t)return t}function T(e){return e&&"number"==typeof e.length}function O(e){return null===e||void 0===e?B():o(e)?e.toSeq():q(e)}function D(e){return null===e||void 0===e?B().toKeyedSeq():o(e)?a(e)?e.toSeq():e.fromEntrySeq():L(e)}function M(e){return null===e||void 0===e?B():o(e)?a(e)?e.entrySeq():e.toIndexedSeq():z(e)}function P(e){return(null===e||void 0===e?B():o(e)?a(e)?e.entrySeq():e:z(e)).toSetSeq()}function I(e){this._array=e,this.size=e.length}function j(e){var t=Object.keys(e);this._object=e,this._keys=t,this.size=t.length}function R(e){this._iterable=e,this.size=e.length||e.size}function N(e){this._iterator=e,this._iteratorCache=[]}function F(e){return!(!e||!e[Cn])}function B(){return An||(An=new I([]))}function L(e){var t=Array.isArray(e)?new I(e).fromEntrySeq():E(e)?new N(e).fromEntrySeq():S(e)?new R(e).fromEntrySeq():"object"==typeof e?new j(e):void 0;if(!t)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+e);return t}function z(e){var t=U(e);if(!t)throw new TypeError("Expected Array or iterable object of values: "+e);return t}function q(e){var t=U(e)||"object"==typeof e&&new j(e);if(!t)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+e);return t}function U(e){return T(e)?new I(e):E(e)?new N(e):S(e)?new R(e):void 0}function W(e,t,n,r){var i=e._cache;if(i){for(var o=i.length-1,a=0;a<=o;a++){var s=i[n?o-a:a];if(t(s[1],r?s[0]:a,e)===!1)return a+1}return a}return e.__iterateUncached(t,n)}function K(e,t,n,r){var i=e._cache;if(i){var o=i.length-1,a=0;return new x(function(){var e=i[n?o-a:a];return a++>o?k():w(t,r?e[0]:a-1,e[1])})}return e.__iteratorUncached(t,n)}function V(e,t){return t?H(t,e,"",{"":e}):J(e)}function H(e,t,n,r){return Array.isArray(t)?e.call(r,n,M(t).map(function(n,r){return H(e,n,r,t)})):G(t)?e.call(r,n,D(t).map(function(n,r){return H(e,n,r,t)})):t}function J(e){return Array.isArray(e)?M(e).map(J).toList():G(e)?D(e).map(J).toMap():e}function G(e){return e&&(e.constructor===Object||void 0===e.constructor)}function X(e,t){if(e===t||e!==e&&t!==t)return!0;if(!e||!t)return!1;if("function"==typeof e.valueOf&&"function"==typeof t.valueOf){if(e=e.valueOf(),t=t.valueOf(),e===t||e!==e&&t!==t)return!0;if(!e||!t)return!1}return!("function"!=typeof e.equals||"function"!=typeof t.equals||!e.equals(t))}function Y(e,t){if(e===t)return!0;if(!o(t)||void 0!==e.size&&void 0!==t.size&&e.size!==t.size||void 0!==e.__hash&&void 0!==t.__hash&&e.__hash!==t.__hash||a(e)!==a(t)||s(e)!==s(t)||c(e)!==c(t))return!1;if(0===e.size&&0===t.size)return!0;var n=!u(e);if(c(e)){var r=e.entries();return t.every(function(e,t){var i=r.next().value;return i&&X(i[1],e)&&(n||X(i[0],t))})&&r.next().done}var i=!1;if(void 0===e.size)if(void 0===t.size)"function"==typeof e.cacheResult&&e.cacheResult();else{i=!0;var l=e;e=t,t=l}var p=!0,f=t.__iterate(function(t,r){if(n?!e.has(t):i?!X(t,e.get(r,vn)):!X(e.get(r,vn),t))return p=!1,!1});return p&&e.size===f}function $(e,t){if(!(this instanceof $))return new $(e,t);if(this._value=e,this.size=void 0===t?1/0:Math.max(0,t),0===this.size){if(Tn)return Tn;Tn=this}}function Z(e,t){if(!e)throw new Error(t)}function Q(e,t,n){if(!(this instanceof Q))return new Q(e,t,n);if(Z(0!==n,"Cannot step a Range by 0"),e=e||0,void 0===t&&(t=1/0),n=void 0===n?1:Math.abs(n),t>>1&1073741824|3221225471&e}function oe(e){if(e===!1||null===e||void 0===e)return 0;if("function"==typeof e.valueOf&&(e=e.valueOf(),e===!1||null===e||void 0===e))return 0;if(e===!0)return 1;var t=typeof e;if("number"===t){if(e!==e||e===1/0)return 0;var n=0|e;for(n!==e&&(n^=4294967295*e);e>4294967295;)e/=4294967295,n^=e;return ie(n)}if("string"===t)return e.length>Fn?ae(e):se(e);if("function"==typeof e.hashCode)return e.hashCode();if("object"===t)return ue(e);if("function"==typeof e.toString)return se(e.toString());throw new Error("Value type "+t+" cannot be hashed.")}function ae(e){var t=zn[e];return void 0===t&&(t=se(e),Ln===Bn&&(Ln=0,zn={}),Ln++,zn[e]=t),t}function se(e){for(var t=0,n=0;n0)switch(e.nodeType){case 1:return e.uniqueID;case 9:return e.documentElement&&e.documentElement.uniqueID}}function le(e){Z(e!==1/0,"Cannot perform this action with an infinite size.")}function pe(e){return null===e||void 0===e?we():fe(e)&&!c(e)?e:we().withMutations(function(t){var r=n(e);le(r.size),r.forEach(function(e,n){return t.set(n,e)})})}function fe(e){return!(!e||!e[qn])}function he(e,t){this.ownerID=e,this.entries=t}function de(e,t,n){this.ownerID=e,this.bitmap=t,this.nodes=n}function me(e,t,n){this.ownerID=e,this.count=t,this.nodes=n}function ye(e,t,n){this.ownerID=e,this.keyHash=t,this.entries=n}function ve(e,t,n){this.ownerID=e,this.keyHash=t,this.entry=n}function ge(e,t,n){this._type=t,this._reverse=n,this._stack=e._root&&be(e._root)}function _e(e,t){return w(e,t[0],t[1])}function be(e,t){return{node:e,index:0,__prev:t}}function xe(e,t,n,r){var i=Object.create(Un);return i.size=e,i._root=t,i.__ownerID=n,i.__hash=r,i.__altered=!1,i}function we(){return Wn||(Wn=xe(0))}function ke(e,t,n){var r,i;if(e._root){var o=l(gn),a=l(_n);if(r=Se(e._root,e.__ownerID,0,void 0,t,n,o,a),!a.value)return e;i=e.size+(o.value?n===vn?-1:1:0)}else{if(n===vn)return e;i=1,r=new he(e.__ownerID,[[t,n]])}return e.__ownerID?(e.size=i,e._root=r,e.__hash=void 0,e.__altered=!0,e):r?xe(i,r):we()}function Se(e,t,n,r,i,o,a,s){return e?e.update(t,n,r,i,o,a,s):o===vn?e:(p(s),p(a),new ve(t,r,[i,o]))}function Ee(e){return e.constructor===ve||e.constructor===ye}function Ce(e,t,n,r,i){if(e.keyHash===r)return new ye(t,r,[e.entry,i]);var o,a=(0===n?e.keyHash:e.keyHash>>>n)&yn,s=(0===n?r:r>>>n)&yn,u=a===s?[Ce(e,t,n+dn,r,i)]:(o=new ve(t,r,i),a>>=1)a[s]=1&n?t[o++]:void 0;return a[r]=i,new me(e,o+1,a)}function De(e,t,r){for(var i=[],a=0;a>1&1431655765,e=(858993459&e)+(e>>2&858993459),e=e+(e>>4)&252645135,e+=e>>8,e+=e>>16,127&e}function Ne(e,t,n,r){var i=r?e:h(e);return i[t]=n,i}function Fe(e,t,n,r){var i=e.length+1;if(r&&t+1===i)return e[t]=n,e;for(var o=new Array(i),a=0,s=0;s0&&io?0:o-n,c=a-n;return c>mn&&(c=mn),function(){if(i===c)return Yn;var e=t?--c:i++;return r&&r[e]}}function i(e,r,i){var s,u=e&&e.array,c=i>o?0:o-i>>r,l=(a-i>>r)+1;return l>mn&&(l=mn),function(){for(;;){if(s){var e=s();if(e!==Yn)return e;s=null}if(c===l)return Yn;var o=t?--l:c++;s=n(u&&u[o],r-dn,i+(o<=e.size||t<0)return e.withMutations(function(e){t<0?Xe(e,t).set(0,n):Xe(e,0,t+1).set(t,n)});t+=e._origin;var r=e._tail,i=e._root,o=l(_n);return t>=$e(e._capacity)?r=He(r,e.__ownerID,0,t,n,o):i=He(i,e.__ownerID,e._level,t,n,o),o.value?e.__ownerID?(e._root=i,e._tail=r,e.__hash=void 0,e.__altered=!0,e):We(e._origin,e._capacity,e._level,i,r):e}function He(e,t,n,r,i,o){var a=r>>>n&yn,s=e&&a0){var c=e&&e.array[a],l=He(c,t,n-dn,r,i,o);return l===c?e:(u=Je(e,t),u.array[a]=l,u)}return s&&e.array[a]===i?e:(p(o),u=Je(e,t),void 0===i&&a===u.array.length-1?u.array.pop():u.array[a]=i,u)}function Je(e,t){return t&&e&&t===e.ownerID?e:new qe(e?e.array.slice():[],t)}function Ge(e,t){if(t>=$e(e._capacity))return e._tail;if(t<1<0;)n=n.array[t>>>r&yn],r-=dn;return n}}function Xe(e,t,n){void 0!==t&&(t|=0),void 0!==n&&(n|=0);var r=e.__ownerID||new f,i=e._origin,o=e._capacity,a=i+t,s=void 0===n?o:n<0?o+n:i+n;if(a===i&&s===o)return e;if(a>=s)return e.clear();for(var u=e._level,c=e._root,l=0;a+l<0;)c=new qe(c&&c.array.length?[void 0,c]:[],r),u+=dn,l+=1<=1<p?new qe([],r):d;if(d&&h>p&&adn;v-=dn){var g=p>>>v&yn;y=y.array[g]=Je(y.array[g],r)}y.array[p>>>dn&yn]=d}if(s=h)a-=h,s-=h,u=dn,c=null,m=m&&m.removeBefore(r,0,a);else if(a>i||h>>u&yn;if(_!==h>>>u&yn)break;_&&(l+=(1<i&&(c=c.removeBefore(r,u,a-l)),c&&ha&&(a=c.size),o(u)||(c=c.map(function(e){return V(e)})),i.push(c)}return a>e.size&&(e=e.setSize(a)),Ie(e,t,i)}function $e(e){return e>>dn<=mn&&a.size>=2*o.size?(i=a.filter(function(e,t){return void 0!==e&&s!==t}),r=i.toKeyedSeq().map(function(e){return e[0]}).flip().toMap(),e.__ownerID&&(r.__ownerID=i.__ownerID=e.__ownerID)):(r=o.remove(t),i=s===a.size-1?a.pop():a.set(s,void 0))}else if(u){if(n===a.get(s)[1])return e;r=o,i=a.set(s,[t,n])}else r=o.set(t,a.size),i=a.set(a.size,[t,n]);return e.__ownerID?(e.size=r.size,e._map=r,e._list=i,e.__hash=void 0,e):et(r,i)}function rt(e,t){this._iter=e,this._useKeys=t,this.size=e.size}function it(e){this._iter=e,this.size=e.size}function ot(e){this._iter=e,this.size=e.size}function at(e){this._iter=e,this.size=e.size}function st(e){var t=Tt(e);return t._iter=e,t.size=e.size,t.flip=function(){return e},t.reverse=function(){var t=e.reverse.apply(this);return t.flip=function(){return e.reverse()},t},t.has=function(t){return e.includes(t)},t.includes=function(t){return e.has(t)},t.cacheResult=Ot,t.__iterateUncached=function(t,n){var r=this;return e.__iterate(function(e,n){return t(n,e,r)!==!1},n)},t.__iteratorUncached=function(t,n){if(t===wn){var r=e.__iterator(t,n);return new x(function(){var e=r.next();if(!e.done){var t=e.value[0];e.value[0]=e.value[1],e.value[1]=t}return e})}return e.__iterator(t===xn?bn:xn,n)},t}function ut(e,t,n){var r=Tt(e);return r.size=e.size,r.has=function(t){return e.has(t)},r.get=function(r,i){var o=e.get(r,vn);return o===vn?i:t.call(n,o,r,e)},r.__iterateUncached=function(r,i){var o=this;return e.__iterate(function(e,i,a){return r(t.call(n,e,i,a),i,o)!==!1},i)},r.__iteratorUncached=function(r,i){var o=e.__iterator(wn,i);return new x(function(){var i=o.next();if(i.done)return i;var a=i.value,s=a[0];return w(r,s,t.call(n,a[1],s,e),i)})},r}function ct(e,t){var n=Tt(e);return n._iter=e,n.size=e.size,n.reverse=function(){return e},e.flip&&(n.flip=function(){var t=st(e);return t.reverse=function(){return e.flip()},t}),n.get=function(n,r){return e.get(t?n:-1-n,r)},n.has=function(n){return e.has(t?n:-1-n)},n.includes=function(t){return e.includes(t)},n.cacheResult=Ot,n.__iterate=function(t,n){var r=this;return e.__iterate(function(e,n){return t(e,n,r)},!n)},n.__iterator=function(t,n){return e.__iterator(t,!n)},n}function lt(e,t,n,r){var i=Tt(e);return r&&(i.has=function(r){var i=e.get(r,vn);return i!==vn&&!!t.call(n,i,r,e)},i.get=function(r,i){var o=e.get(r,vn);return o!==vn&&t.call(n,o,r,e)?o:i}),i.__iterateUncached=function(i,o){var a=this,s=0;return e.__iterate(function(e,o,u){if(t.call(n,e,o,u))return s++,i(e,r?o:s-1,a)},o),s},i.__iteratorUncached=function(i,o){var a=e.__iterator(wn,o),s=0;return new x(function(){for(;;){var o=a.next();if(o.done)return o;var u=o.value,c=u[0],l=u[1];if(t.call(n,l,c,e))return w(i,r?c:s++,l,o)}})},i}function pt(e,t,n){var r=pe().asMutable();return e.__iterate(function(i,o){r.update(t.call(n,i,o,e),0,function(e){return e+1})}),r.asImmutable()}function ft(e,t,n){var r=a(e),i=(c(e)?Ze():pe()).asMutable();e.__iterate(function(o,a){i.update(t.call(n,o,a,e),function(e){return e=e||[],e.push(r?[a,o]:o),e})});var o=At(e);return i.map(function(t){return St(e,o(t))})}function ht(e,t,n,r){var i=e.size;if(void 0!==t&&(t|=0),void 0!==n&&(n===1/0?n=i:n|=0),v(t,n,i))return e;var o=g(t,i),a=_(n,i);if(o!==o||a!==a)return ht(e.toSeq().cacheResult(),t,n,r);var s,u=a-o;u===u&&(s=u<0?0:u);var c=Tt(e);return c.size=0===s?s:e.size&&s||void 0,!r&&F(e)&&s>=0&&(c.get=function(t,n){return t=m(this,t),t>=0&&ts)return k();var e=i.next();return r||t===xn?e:t===bn?w(t,u-1,void 0,e):w(t,u-1,e.value[1],e)})},c}function dt(e,t,n){var r=Tt(e);return r.__iterateUncached=function(r,i){var o=this;if(i)return this.cacheResult().__iterate(r,i);var a=0;return e.__iterate(function(e,i,s){return t.call(n,e,i,s)&&++a&&r(e,i,o)}),a},r.__iteratorUncached=function(r,i){var o=this;if(i)return this.cacheResult().__iterator(r,i);var a=e.__iterator(wn,i),s=!0;return new x(function(){if(!s)return k();var e=a.next();if(e.done)return e;var i=e.value,u=i[0],c=i[1];return t.call(n,c,u,o)?r===wn?e:w(r,u,c,e):(s=!1,k())})},r}function mt(e,t,n,r){var i=Tt(e);return i.__iterateUncached=function(i,o){var a=this;if(o)return this.cacheResult().__iterate(i,o);var s=!0,u=0;return e.__iterate(function(e,o,c){if(!s||!(s=t.call(n,e,o,c)))return u++,i(e,r?o:u-1,a)}),u},i.__iteratorUncached=function(i,o){var a=this;if(o)return this.cacheResult().__iterator(i,o);var s=e.__iterator(wn,o),u=!0,c=0;return new x(function(){var e,o,l;do{if(e=s.next(),e.done)return r||i===xn?e:i===bn?w(i,c++,void 0,e):w(i,c++,e.value[1],e);var p=e.value;o=p[0],l=p[1],u&&(u=t.call(n,l,o,a))}while(u);return i===wn?e:w(i,o,l,e)})},i}function yt(e,t){var r=a(e),i=[e].concat(t).map(function(e){return o(e)?r&&(e=n(e)):e=r?L(e):z(Array.isArray(e)?e:[e]),e}).filter(function(e){return 0!==e.size});if(0===i.length)return e;if(1===i.length){var u=i[0];if(u===e||r&&a(u)||s(e)&&s(u))return u}var c=new I(i);return r?c=c.toKeyedSeq():s(e)||(c=c.toSetSeq()),c=c.flatten(!0),c.size=i.reduce(function(e,t){if(void 0!==e){var n=t.size;if(void 0!==n)return e+n}},0),c}function vt(e,t,n){var r=Tt(e);return r.__iterateUncached=function(r,i){function a(e,c){var l=this;e.__iterate(function(e,i){return(!t||c0}function kt(e,n,r){var i=Tt(e);return i.size=new I(r).map(function(e){return e.size}).min(),i.__iterate=function(e,t){for(var n,r=this.__iterator(xn,t),i=0;!(n=r.next()).done&&e(n.value,i++,this)!==!1;);return i},i.__iteratorUncached=function(e,i){var o=r.map(function(e){return e=t(e),C(i?e.reverse():e)}),a=0,s=!1;return new x(function(){var t;return s||(t=o.map(function(e){return e.next()}),s=t.some(function(e){return e.done})),s?k():w(e,a++,n.apply(null,t.map(function(e){return e.value})))})},i}function St(e,t){return F(e)?t:e.constructor(t)}function Et(e){if(e!==Object(e))throw new TypeError("Expected [K, V] tuple: "+e)}function Ct(e){return le(e.size),d(e)}function At(e){return a(e)?n:s(e)?r:i}function Tt(e){return Object.create((a(e)?D:s(e)?M:P).prototype)}function Ot(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):O.prototype.cacheResult.call(this)}function Dt(e,t){return e>t?1:et?-1:0}function on(e){if(e.size===1/0)return 0;var t=c(e),n=a(e),r=t?1:0,i=e.__iterate(n?t?function(e,t){r=31*r+sn(oe(e),oe(t))|0}:function(e,t){r=r+sn(oe(e),oe(t))|0}:t?function(e){r=31*r+oe(e)|0}:function(e){r=r+oe(e)|0});return an(i,r)}function an(e,t){return t=Mn(t,3432918353),t=Mn(t<<15|t>>>-15,461845907),t=Mn(t<<13|t>>>-13,5),t=(t+3864292196|0)^e,t=Mn(t^t>>>16,2246822507),t=Mn(t^t>>>13,3266489909),t=ie(t^t>>>16)}function sn(e,t){return e^t+2654435769+(e<<6)+(e>>2)|0}var un=Array.prototype.slice;e(n,t),e(r,t),e(i,t),t.isIterable=o,t.isKeyed=a,t.isIndexed=s,t.isAssociative=u,t.isOrdered=c,t.Keyed=n,t.Indexed=r,t.Set=i;var cn="@@__IMMUTABLE_ITERABLE__@@",ln="@@__IMMUTABLE_KEYED__@@",pn="@@__IMMUTABLE_INDEXED__@@",fn="@@__IMMUTABLE_ORDERED__@@",hn="delete",dn=5,mn=1<r?k():w(e,i,n[t?r-i++:i++])})},e(j,D),j.prototype.get=function(e,t){return void 0===t||this.has(e)?this._object[e]:t},j.prototype.has=function(e){return this._object.hasOwnProperty(e)},j.prototype.__iterate=function(e,t){for(var n=this._object,r=this._keys,i=r.length-1,o=0;o<=i;o++){var a=r[t?i-o:o];if(e(n[a],a,this)===!1)return o+1}return o},j.prototype.__iterator=function(e,t){var n=this._object,r=this._keys,i=r.length-1,o=0;return new x(function(){var a=r[t?i-o:o];return o++>i?k():w(e,a,n[a])})},j.prototype[fn]=!0,e(R,M),R.prototype.__iterateUncached=function(e,t){if(t)return this.cacheResult().__iterate(e,t);var n=this._iterable,r=C(n),i=0;if(E(r))for(var o;!(o=r.next()).done&&e(o.value,i++,this)!==!1;);return i},R.prototype.__iteratorUncached=function(e,t){if(t)return this.cacheResult().__iterator(e,t);var n=this._iterable,r=C(n);if(!E(r))return new x(k);var i=0;return new x(function(){var t=r.next();return t.done?t:w(e,i++,t.value)})},e(N,M),N.prototype.__iterateUncached=function(e,t){if(t)return this.cacheResult().__iterate(e,t);for(var n=this._iterator,r=this._iteratorCache,i=0;i=r.length){var t=n.next();if(t.done)return t;r[i]=t.value}return w(e,i,r[i++])})};var An;e($,M),$.prototype.toString=function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},$.prototype.get=function(e,t){return this.has(e)?this._value:t},$.prototype.includes=function(e){return X(this._value,e)},$.prototype.slice=function(e,t){var n=this.size;return v(e,t,n)?this:new $(this._value,_(t,n)-g(e,n))},$.prototype.reverse=function(){return this},$.prototype.indexOf=function(e){return X(this._value,e)?0:-1},$.prototype.lastIndexOf=function(e){return X(this._value,e)?this.size:-1},$.prototype.__iterate=function(e,t){ +for(var n=0;n=0&&t=0&&nn?k():w(e,o++,a)})},Q.prototype.equals=function(e){return e instanceof Q?this._start===e._start&&this._end===e._end&&this._step===e._step:Y(this,e)};var On;e(ee,t),e(te,ee),e(ne,ee),e(re,ee),ee.Keyed=te,ee.Indexed=ne,ee.Set=re;var Dn,Mn="function"==typeof Math.imul&&Math.imul(4294967295,2)===-2?Math.imul:function(e,t){e|=0,t|=0;var n=65535&e,r=65535&t;return n*r+((e>>>16)*r+n*(t>>>16)<<16>>>0)|0},Pn=Object.isExtensible,In=function(){try{return Object.defineProperty({},"@",{}),!0}catch(e){return!1}}(),jn="function"==typeof WeakMap;jn&&(Dn=new WeakMap);var Rn=0,Nn="__immutablehash__";"function"==typeof Symbol&&(Nn=Symbol(Nn));var Fn=16,Bn=255,Ln=0,zn={};e(pe,te),pe.of=function(){var e=un.call(arguments,0);return we().withMutations(function(t){for(var n=0;n=e.length)throw new Error("Missing value for key: "+e[n]);t.set(e[n],e[n+1])}})},pe.prototype.toString=function(){return this.__toString("Map {","}")},pe.prototype.get=function(e,t){return this._root?this._root.get(0,void 0,e,t):t},pe.prototype.set=function(e,t){return ke(this,e,t)},pe.prototype.setIn=function(e,t){return this.updateIn(e,vn,function(){return t})},pe.prototype.remove=function(e){return ke(this,e,vn)},pe.prototype.deleteIn=function(e){return this.updateIn(e,function(){return vn})},pe.prototype.update=function(e,t,n){return 1===arguments.length?e(this):this.updateIn([e],t,n)},pe.prototype.updateIn=function(e,t,n){n||(n=t,t=void 0);var r=je(this,Mt(e),t,n);return r===vn?void 0:r},pe.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):we()},pe.prototype.merge=function(){return De(this,void 0,arguments)},pe.prototype.mergeWith=function(e){var t=un.call(arguments,1);return De(this,e,t)},pe.prototype.mergeIn=function(e){var t=un.call(arguments,1);return this.updateIn(e,we(),function(e){return"function"==typeof e.merge?e.merge.apply(e,t):t[t.length-1]})},pe.prototype.mergeDeep=function(){return De(this,Me,arguments)},pe.prototype.mergeDeepWith=function(e){var t=un.call(arguments,1);return De(this,Pe(e),t)},pe.prototype.mergeDeepIn=function(e){var t=un.call(arguments,1);return this.updateIn(e,we(),function(e){return"function"==typeof e.mergeDeep?e.mergeDeep.apply(e,t):t[t.length-1]})},pe.prototype.sort=function(e){return Ze(bt(this,e))},pe.prototype.sortBy=function(e,t){return Ze(bt(this,t,e))},pe.prototype.withMutations=function(e){var t=this.asMutable();return e(t),t.wasAltered()?t.__ensureOwner(this.__ownerID):this},pe.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new f)},pe.prototype.asImmutable=function(){return this.__ensureOwner()},pe.prototype.wasAltered=function(){return this.__altered},pe.prototype.__iterator=function(e,t){return new ge(this,e,t)},pe.prototype.__iterate=function(e,t){var n=this,r=0;return this._root&&this._root.iterate(function(t){return r++,e(t[1],t[0],n)},t),r},pe.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?xe(this.size,this._root,e,this.__hash):(this.__ownerID=e,this.__altered=!1,this)},pe.isMap=fe;var qn="@@__IMMUTABLE_MAP__@@",Un=pe.prototype;Un[qn]=!0,Un[hn]=Un.remove,Un.removeIn=Un.deleteIn,he.prototype.get=function(e,t,n,r){for(var i=this.entries,o=0,a=i.length;o=Kn)return Ae(e,u,r,i);var d=e&&e===this.ownerID,m=d?u:h(u);return f?s?c===l-1?m.pop():m[c]=m.pop():m[c]=[r,i]:m.push([r,i]),d?(this.entries=m,this):new he(e,m)}},de.prototype.get=function(e,t,n,r){void 0===t&&(t=oe(n));var i=1<<((0===e?t:t>>>e)&yn),o=this.bitmap;return 0===(o&i)?r:this.nodes[Re(o&i-1)].get(e+dn,t,n,r)},de.prototype.update=function(e,t,n,r,i,o,a){void 0===n&&(n=oe(r));var s=(0===t?n:n>>>t)&yn,u=1<=Vn)return Oe(e,f,c,s,d);if(l&&!d&&2===f.length&&Ee(f[1^p]))return f[1^p];if(l&&d&&1===f.length&&Ee(d))return d;var m=e&&e===this.ownerID,y=l?d?c:c^u:c|u,v=l?d?Ne(f,p,d,m):Be(f,p,m):Fe(f,p,d,m);return m?(this.bitmap=y,this.nodes=v,this):new de(e,y,v)},me.prototype.get=function(e,t,n,r){void 0===t&&(t=oe(n));var i=(0===e?t:t>>>e)&yn,o=this.nodes[i];return o?o.get(e+dn,t,n,r):r},me.prototype.update=function(e,t,n,r,i,o,a){void 0===n&&(n=oe(r));var s=(0===t?n:n>>>t)&yn,u=i===vn,c=this.nodes,l=c[s];if(u&&!l)return this;var p=Se(l,e,t+dn,n,r,i,o,a);if(p===l)return this;var f=this.count;if(l){if(!p&&(f--,f=0&&e>>t&yn;if(r>=this.array.length)return new qe([],e);var i,o=0===r;if(t>0){var a=this.array[r];if(i=a&&a.removeBefore(e,t-dn,n),i===a&&o)return this}if(o&&!i)return this;var s=Je(this,e);if(!o)for(var u=0;u>>t&yn;if(r>=this.array.length)return this;var i;if(t>0){var o=this.array[r];if(i=o&&o.removeAfter(e,t-dn,n),i===o&&r===this.array.length-1)return this}var a=Je(this,e);return a.array.splice(r+1),i&&(a.array[r]=i),a};var Xn,Yn={};e(Ze,pe),Ze.of=function(){return this(arguments)},Ze.prototype.toString=function(){return this.__toString("OrderedMap {","}")},Ze.prototype.get=function(e,t){var n=this._map.get(e);return void 0!==n?this._list.get(n)[1]:t},Ze.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._map.clear(),this._list.clear(),this):tt()},Ze.prototype.set=function(e,t){return nt(this,e,t)},Ze.prototype.remove=function(e){return nt(this,e,vn)},Ze.prototype.wasAltered=function(){return this._map.wasAltered()||this._list.wasAltered()},Ze.prototype.__iterate=function(e,t){var n=this;return this._list.__iterate(function(t){return t&&e(t[1],t[0],n)},t)},Ze.prototype.__iterator=function(e,t){return this._list.fromEntrySeq().__iterator(e,t)},Ze.prototype.__ensureOwner=function(e){if(e===this.__ownerID)return this;var t=this._map.__ensureOwner(e),n=this._list.__ensureOwner(e);return e?et(t,n,e,this.__hash):(this.__ownerID=e,this._map=t,this._list=n,this)},Ze.isOrderedMap=Qe,Ze.prototype[fn]=!0,Ze.prototype[hn]=Ze.prototype.remove;var $n;e(rt,D),rt.prototype.get=function(e,t){return this._iter.get(e,t)},rt.prototype.has=function(e){return this._iter.has(e)},rt.prototype.valueSeq=function(){return this._iter.valueSeq()},rt.prototype.reverse=function(){var e=this,t=ct(this,!0);return this._useKeys||(t.valueSeq=function(){return e._iter.toSeq().reverse()}),t},rt.prototype.map=function(e,t){var n=this,r=ut(this,e,t);return this._useKeys||(r.valueSeq=function(){return n._iter.toSeq().map(e,t)}),r},rt.prototype.__iterate=function(e,t){var n,r=this;return this._iter.__iterate(this._useKeys?function(t,n){return e(t,n,r)}:(n=t?Ct(this):0,function(i){return e(i,t?--n:n++,r)}),t)},rt.prototype.__iterator=function(e,t){if(this._useKeys)return this._iter.__iterator(e,t);var n=this._iter.__iterator(xn,t),r=t?Ct(this):0;return new x(function(){var i=n.next();return i.done?i:w(e,t?--r:r++,i.value,i)})},rt.prototype[fn]=!0,e(it,M),it.prototype.includes=function(e){return this._iter.includes(e)},it.prototype.__iterate=function(e,t){var n=this,r=0;return this._iter.__iterate(function(t){return e(t,r++,n)},t)},it.prototype.__iterator=function(e,t){var n=this._iter.__iterator(xn,t),r=0;return new x(function(){var t=n.next();return t.done?t:w(e,r++,t.value,t)})},e(ot,P),ot.prototype.has=function(e){return this._iter.includes(e)},ot.prototype.__iterate=function(e,t){var n=this;return this._iter.__iterate(function(t){return e(t,t,n)},t)},ot.prototype.__iterator=function(e,t){var n=this._iter.__iterator(xn,t);return new x(function(){var t=n.next();return t.done?t:w(e,t.value,t.value,t)})},e(at,D),at.prototype.entrySeq=function(){return this._iter.toSeq()},at.prototype.__iterate=function(e,t){var n=this;return this._iter.__iterate(function(t){if(t){Et(t);var r=o(t);return e(r?t.get(1):t[1],r?t.get(0):t[0],n)}},t)},at.prototype.__iterator=function(e,t){var n=this._iter.__iterator(xn,t);return new x(function(){for(;;){var t=n.next();if(t.done)return t;var r=t.value;if(r){Et(r);var i=o(r);return w(e,i?r.get(0):r[0],i?r.get(1):r[1],t)}}})},it.prototype.cacheResult=rt.prototype.cacheResult=ot.prototype.cacheResult=at.prototype.cacheResult=Ot,e(Pt,te),Pt.prototype.toString=function(){return this.__toString(jt(this)+" {","}")},Pt.prototype.has=function(e){return this._defaultValues.hasOwnProperty(e)},Pt.prototype.get=function(e,t){if(!this.has(e))return t;var n=this._defaultValues[e];return this._map?this._map.get(e,n):n},Pt.prototype.clear=function(){if(this.__ownerID)return this._map&&this._map.clear(),this;var e=this.constructor;return e._empty||(e._empty=It(this,we()))},Pt.prototype.set=function(e,t){if(!this.has(e))throw new Error('Cannot set unknown key "'+e+'" on '+jt(this));if(this._map&&!this._map.has(e)){var n=this._defaultValues[e];if(t===n)return this}var r=this._map&&this._map.set(e,t);return this.__ownerID||r===this._map?this:It(this,r)},Pt.prototype.remove=function(e){if(!this.has(e))return this;var t=this._map&&this._map.remove(e);return this.__ownerID||t===this._map?this:It(this,t)},Pt.prototype.wasAltered=function(){return this._map.wasAltered()},Pt.prototype.__iterator=function(e,t){var r=this;return n(this._defaultValues).map(function(e,t){return r.get(t)}).__iterator(e,t)},Pt.prototype.__iterate=function(e,t){var r=this;return n(this._defaultValues).map(function(e,t){return r.get(t)}).__iterate(e,t)},Pt.prototype.__ensureOwner=function(e){if(e===this.__ownerID)return this;var t=this._map&&this._map.__ensureOwner(e);return e?It(this,t,e):(this.__ownerID=e,this._map=t,this)};var Zn=Pt.prototype;Zn[hn]=Zn.remove,Zn.deleteIn=Zn.removeIn=Un.removeIn,Zn.merge=Un.merge,Zn.mergeWith=Un.mergeWith,Zn.mergeIn=Un.mergeIn,Zn.mergeDeep=Un.mergeDeep,Zn.mergeDeepWith=Un.mergeDeepWith,Zn.mergeDeepIn=Un.mergeDeepIn,Zn.setIn=Un.setIn,Zn.update=Un.update,Zn.updateIn=Un.updateIn,Zn.withMutations=Un.withMutations,Zn.asMutable=Un.asMutable,Zn.asImmutable=Un.asImmutable,e(Ft,re),Ft.of=function(){return this(arguments)},Ft.fromKeys=function(e){return this(n(e).keySeq())},Ft.prototype.toString=function(){return this.__toString("Set {","}")},Ft.prototype.has=function(e){return this._map.has(e)},Ft.prototype.add=function(e){return Lt(this,this._map.set(e,!0))},Ft.prototype.remove=function(e){return Lt(this,this._map.remove(e))},Ft.prototype.clear=function(){return Lt(this,this._map.clear())},Ft.prototype.union=function(){var e=un.call(arguments,0);return e=e.filter(function(e){return 0!==e.size}),0===e.length?this:0!==this.size||this.__ownerID||1!==e.length?this.withMutations(function(t){for(var n=0;n=0;n--)t={value:arguments[n],next:t};return this.__ownerID?(this.size=e,this._head=t,this.__hash=void 0,this.__altered=!0,this):Gt(e,t)},Ht.prototype.pushAll=function(e){if(e=r(e),0===e.size)return this;le(e.size);var t=this.size,n=this._head;return e.reverse().forEach(function(e){t++,n={value:e,next:n}}),this.__ownerID?(this.size=t,this._head=n,this.__hash=void 0,this.__altered=!0,this):Gt(t,n)},Ht.prototype.pop=function(){return this.slice(1)},Ht.prototype.unshift=function(){return this.push.apply(this,arguments)},Ht.prototype.unshiftAll=function(e){return this.pushAll(e)},Ht.prototype.shift=function(){return this.pop.apply(this,arguments)},Ht.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):Xt()},Ht.prototype.slice=function(e,t){if(v(e,t,this.size))return this;var n=g(e,this.size),r=_(t,this.size);if(r!==this.size)return ne.prototype.slice.call(this,e,t);for(var i=this.size-n,o=this._head;n--;)o=o.next;return this.__ownerID?(this.size=i,this._head=o,this.__hash=void 0,this.__altered=!0,this):Gt(i,o)},Ht.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?Gt(this.size,this._head,e,this.__hash):(this.__ownerID=e,this.__altered=!1,this)},Ht.prototype.__iterate=function(e,t){if(t)return this.reverse().__iterate(e);for(var n=0,r=this._head;r&&e(r.value,n++,this)!==!1;)r=r.next;return n},Ht.prototype.__iterator=function(e,t){if(t)return this.reverse().__iterator(e);var n=0,r=this._head;return new x(function(){if(r){var t=r.value;return r=r.next,w(e,n++,t)}return k()})},Ht.isStack=Jt;var ir="@@__IMMUTABLE_STACK__@@",or=Ht.prototype;or[ir]=!0,or.withMutations=Un.withMutations,or.asMutable=Un.asMutable,or.asImmutable=Un.asImmutable,or.wasAltered=Un.wasAltered;var ar;t.Iterator=x,Yt(t,{toArray:function(){le(this.size);var e=new Array(this.size||0);return this.valueSeq().__iterate(function(t,n){e[n]=t}),e},toIndexedSeq:function(){return new it(this)},toJS:function(){return this.toSeq().map(function(e){return e&&"function"==typeof e.toJS?e.toJS():e}).__toJS()},toJSON:function(){return this.toSeq().map(function(e){return e&&"function"==typeof e.toJSON?e.toJSON():e}).__toJS()},toKeyedSeq:function(){return new rt(this,!0)},toMap:function(){return pe(this.toKeyedSeq())},toObject:function(){le(this.size);var e={};return this.__iterate(function(t,n){e[n]=t}),e},toOrderedMap:function(){return Ze(this.toKeyedSeq())},toOrderedSet:function(){return Ut(a(this)?this.valueSeq():this)},toSet:function(){return Ft(a(this)?this.valueSeq():this)},toSetSeq:function(){return new ot(this)},toSeq:function(){return s(this)?this.toIndexedSeq():a(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return Ht(a(this)?this.valueSeq():this)},toList:function(){return Le(a(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(e,t){return 0===this.size?e+t:e+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+t},concat:function(){var e=un.call(arguments,0);return St(this,yt(this,e))},includes:function(e){return this.some(function(t){return X(t,e)})},entries:function(){return this.__iterator(wn)},every:function(e,t){le(this.size);var n=!0;return this.__iterate(function(r,i,o){if(!e.call(t,r,i,o))return n=!1,!1}),n},filter:function(e,t){return St(this,lt(this,e,t,!0))},find:function(e,t,n){var r=this.findEntry(e,t);return r?r[1]:n},forEach:function(e,t){return le(this.size),this.__iterate(t?e.bind(t):e)},join:function(e){le(this.size),e=void 0!==e?""+e:",";var t="",n=!0;return this.__iterate(function(r){n?n=!1:t+=e,t+=null!==r&&void 0!==r?r.toString():""}),t},keys:function(){return this.__iterator(bn)},map:function(e,t){return St(this,ut(this,e,t))},reduce:function(e,t,n){le(this.size);var r,i;return arguments.length<2?i=!0:r=t,this.__iterate(function(t,o,a){i?(i=!1,r=t):r=e.call(n,r,t,o,a)}),r},reduceRight:function(e,t,n){var r=this.toKeyedSeq().reverse();return r.reduce.apply(r,arguments)},reverse:function(){return St(this,ct(this,!0))},slice:function(e,t){return St(this,ht(this,e,t,!0))},some:function(e,t){return!this.every(Qt(e),t)},sort:function(e){return St(this,bt(this,e))},values:function(){return this.__iterator(xn)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return void 0!==this.size?0===this.size:!this.some(function(){return!0})},count:function(e,t){return d(e?this.toSeq().filter(e,t):this)},countBy:function(e,t){return pt(this,e,t)},equals:function(e){return Y(this,e)},entrySeq:function(){var e=this;if(e._cache)return new I(e._cache);var t=e.toSeq().map(Zt).toIndexedSeq();return t.fromEntrySeq=function(){return e.toSeq()},t},filterNot:function(e,t){return this.filter(Qt(e),t)},findEntry:function(e,t,n){var r=n;return this.__iterate(function(n,i,o){if(e.call(t,n,i,o))return r=[i,n],!1}),r},findKey:function(e,t){var n=this.findEntry(e,t);return n&&n[0]},findLast:function(e,t,n){return this.toKeyedSeq().reverse().find(e,t,n)},findLastEntry:function(e,t,n){return this.toKeyedSeq().reverse().findEntry(e,t,n)},findLastKey:function(e,t){return this.toKeyedSeq().reverse().findKey(e,t)},first:function(){return this.find(y)},flatMap:function(e,t){return St(this,gt(this,e,t))},flatten:function(e){return St(this,vt(this,e,!0))},fromEntrySeq:function(){return new at(this)},get:function(e,t){return this.find(function(t,n){return X(n,e)},void 0,t)},getIn:function(e,t){for(var n,r=this,i=Mt(e);!(n=i.next()).done;){var o=n.value;if(r=r&&r.get?r.get(o,vn):vn,r===vn)return t}return r},groupBy:function(e,t){return ft(this,e,t)},has:function(e){return this.get(e,vn)!==vn},hasIn:function(e){return this.getIn(e,vn)!==vn},isSubset:function(e){return e="function"==typeof e.includes?e:t(e),this.every(function(t){return e.includes(t)})},isSuperset:function(e){return e="function"==typeof e.isSubset?e:t(e),e.isSubset(this)},keyOf:function(e){return this.findKey(function(t){return X(t,e)})},keySeq:function(){return this.toSeq().map($t).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},lastKeyOf:function(e){return this.toKeyedSeq().reverse().keyOf(e)},max:function(e){return xt(this,e)},maxBy:function(e,t){return xt(this,t,e)},min:function(e){return xt(this,e?en(e):rn)},minBy:function(e,t){return xt(this,t?en(t):rn,e)},rest:function(){return this.slice(1)},skip:function(e){return this.slice(Math.max(0,e))},skipLast:function(e){return St(this,this.toSeq().reverse().skip(e).reverse())},skipWhile:function(e,t){return St(this,mt(this,e,t,!0))},skipUntil:function(e,t){return this.skipWhile(Qt(e),t)},sortBy:function(e,t){return St(this,bt(this,t,e))},take:function(e){return this.slice(0,Math.max(0,e))},takeLast:function(e){return St(this,this.toSeq().reverse().take(e).reverse())},takeWhile:function(e,t){return St(this,dt(this,e,t))},takeUntil:function(e,t){return this.takeWhile(Qt(e),t)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=on(this))}});var sr=t.prototype;sr[cn]=!0,sr[En]=sr.values,sr.__toJS=sr.toArray,sr.__toStringMapper=tn,sr.inspect=sr.toSource=function(){return this.toString()},sr.chain=sr.flatMap,sr.contains=sr.includes,Yt(n,{flip:function(){return St(this,st(this))},mapEntries:function(e,t){var n=this,r=0;return St(this,this.toSeq().map(function(i,o){return e.call(t,[o,i],r++,n)}).fromEntrySeq())},mapKeys:function(e,t){var n=this;return St(this,this.toSeq().flip().map(function(r,i){return e.call(t,r,i,n)}).flip())}});var ur=n.prototype;ur[ln]=!0,ur[En]=sr.entries,ur.__toJS=sr.toObject,ur.__toStringMapper=function(e,t){return JSON.stringify(t)+": "+tn(e)},Yt(r,{toKeyedSeq:function(){return new rt(this,!1)},filter:function(e,t){return St(this,lt(this,e,t,!1))},findIndex:function(e,t){var n=this.findEntry(e,t);return n?n[0]:-1},indexOf:function(e){var t=this.keyOf(e);return void 0===t?-1:t},lastIndexOf:function(e){var t=this.lastKeyOf(e);return void 0===t?-1:t},reverse:function(){return St(this,ct(this,!1))},slice:function(e,t){return St(this,ht(this,e,t,!1))},splice:function(e,t){var n=arguments.length;if(t=Math.max(0|t,0),0===n||2===n&&!t)return this;e=g(e,e<0?this.count():this.size);var r=this.slice(0,e);return St(this,1===n?r:r.concat(h(arguments,2),this.slice(e+t)))},findLastIndex:function(e,t){var n=this.findLastEntry(e,t);return n?n[0]:-1},first:function(){return this.get(0)},flatten:function(e){return St(this,vt(this,e,!1))},get:function(e,t){return e=m(this,e),e<0||this.size===1/0||void 0!==this.size&&e>this.size?t:this.find(function(t,n){return n===e},void 0,t)},has:function(e){return e=m(this,e),e>=0&&(void 0!==this.size?this.size===1/0||e0?"Unexpected "+(1===a.length?"property":"properties")+' "'+a.join('", "')+'" found in '+i+'. Expected to find one of the known reducer property names instead: "'+r.join('", "')+'". Unexpected properties will be ignored.':null},e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,n){if(void 0===e)throw new Error('Reducer "'+t+'" returned undefined when handling "'+n.type+'" action. To ignore an action, you must explicitly return the previous state.');return null},e.exports=t.default},function(e,t){"use strict";function n(e,t){var r;return r=Array.isArray(e)?[]:{},t.push(e),Object.keys(e).forEach(function(i){var o=e[i];if("function"!=typeof o)return o&&"object"==typeof o?t.indexOf(e[i])===-1?void(r[i]=n(e[i],t.slice(0))):void(r[i]="[Circular]"):void(r[i]=o)}),r}e.exports=function(e){if("object"==typeof e){var t=n(e,[]);return"string"==typeof e.name&&(t.name=e.name),"string"==typeof e.message&&(t.message=e.message),"string"==typeof e.stack&&(t.stack=e.stack),t}return"function"==typeof e?"[Function: "+(e.name||"anonymous")+"]":e}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){return{type:p,payload:{action:t,error:(0,l.default)(e)}}}function o(e){return{type:f,payload:e}}function a(e){return{type:h,payload:e}}function s(e){return{type:d,payload:e}}function u(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:m,payload:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.CLEAR=t.NEW_AUTH_ERR=t.NEW_SPEC_ERR=t.NEW_THROWN_ERR_BATCH=t.NEW_THROWN_ERR=void 0,t.newThrownErr=i,t.newThrownErrBatch=o,t.newSpecErr=a, +t.newAuthErr=s,t.clear=u;var c=n(332),l=r(c),p=t.NEW_THROWN_ERR="err_new_thrown_err",f=t.NEW_THROWN_ERR_BATCH="err_new_thrown_err_batch",h=t.NEW_SPEC_ERR="err_new_spec_err",d=t.NEW_AUTH_ERR="err_new_auth_err",m=t.CLEAR="err_clear"},function(e,t){"use strict";function n(){var e={location:{},history:{},open:function(){},close:function(){}};if("undefined"==typeof window)return e;try{e=window;var t=["File","Blob","FormData"],n=!0,r=!1,i=void 0;try{for(var o,a=t[Symbol.iterator]();!(n=(o=a.next()).done);n=!0){var s=o.value;s in window&&(e[s]=window[s])}}catch(e){r=!0,i=e}finally{try{!n&&a.return&&a.return()}finally{if(r)throw i}}}catch(e){console.error(e)}return e}e.exports=n()},function(e,t,n){(function(e){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e){return l(e)?U(e)?e.toObject():e:{}}function o(e){return e?e.toArray?e.toArray():u(e):[]}function a(e){return U(e)?e:l(e)?Array.isArray(e)?A.default.Seq(e).map(a).toList():A.default.Seq(e).map(a).toOrderedMap():e}function s(e,t){var n={};return Object.keys(e).filter(function(t){return"function"==typeof e[t]}).forEach(function(r){return n[r]=e[r].bind(null,t)}),n}function u(e){return Array.isArray(e)?e:[e]}function c(e){return"function"==typeof e}function l(e){return!!e&&"object"===("undefined"==typeof e?"undefined":E(e))}function p(e){return"function"==typeof e}function f(e){return Array.isArray(e)}function h(e,t){return Object.keys(e).reduce(function(n,r){return n[r]=t(e[r],r),n},{})}function d(e,t){return Object.keys(e).reduce(function(n,r){var i=t(e[r],r);return i&&"object"===("undefined"==typeof i?"undefined":E(i))&&Object.assign(n,i),n},{})}function m(e){return function(t){t.dispatch,t.getState;return function(t){return function(n){return"function"==typeof n?n(e()):t(n)}}}}function y(e){var t=e.keySeq();return t.contains(q)?q:t.filter(function(e){return"2"===(e+"")[0]}).sort().first()}function v(e,t){if(!A.default.Iterable.isIterable(e))return A.default.List();var n=e.getIn(Array.isArray(t)?t:[t]);return A.default.List.isList(n)?n:A.default.List()}function g(e){var t,n,r,i,o,a,s,u,c,l,p,f;for(l=/(>)(<)(\/*)/g,f=/[ ]*(.*)[ ]+\n/g,t=/(<.+>)(.+\n)/g,e=e.replace(/\r\n/g,"\n").replace(l,"$1\n$2$3").replace(f,"$1\n").replace(t,"$1\n$2"),r="",u=e.split("\n"),i=0,a="other",p={"single->single":0,"single->closing":-1,"single->opening":0,"single->other":0,"closing->single":0,"closing->closing":-1,"closing->opening":0,"closing->other":0,"opening->single":1,"opening->closing":0,"opening->opening":1,"opening->other":1,"other->single":0,"other->closing":-1,"other->opening":0,"other->other":0},n=function(e){var t,n,o,s,u,c;u={single:Boolean(e.match(/<.+\/>/)),closing:Boolean(e.match(/<\/.+>/)),opening:Boolean(e.match(/<[^!?].*>/))},s=function(){var e;e=[];for(n in u)c=u[n],c&&e.push(n);return e}()[0],s=void 0===s?"other":s,t=a+"->"+s,a=s,o="",i+=p[t],o=function(){var e,t,n,r;for(n=[],r=e=0,t=i;0<=t?et;r=0<=t?++e:--e)n.push(" ");return n}().join(""),"opening->closing"===t?r=r.substr(0,r.length-1)+e+"\n":r+=o+e+"\n"},o=0,s=u.length;ot)return e.textContent;var o=function(e){for(var t,o,a,s,u,c=e.textContent,l=0,p=c[0],f=1,h=e.innerHTML="",d=0;o=t,t=d<7&&"\\"==t?1:f;){if(f=p,p=c[++l],s=h.length>1,!f||d>8&&"\n"==f||[/\S/[i](f),1,1,!/[$\w]/[i](f),("/"==t||"\n"==t)&&s,'"'==t&&s,"'"==t&&s,c[l-4]+o+t=="-->",o+t=="*/"][d])for(h&&(e[r](u=n.createElement("span")).setAttribute("style",["color: #555; font-weight: bold;","","","color: #555;",""][d?d<3?2:d>6?4:d>3?3:+/^(a(bstract|lias|nd|rguments|rray|s(m|sert)?|uto)|b(ase|egin|ool(ean)?|reak|yte)|c(ase|atch|har|hecked|lass|lone|ompl|onst|ontinue)|de(bugger|cimal|clare|f(ault|er)?|init|l(egate|ete)?)|do|double|e(cho|ls?if|lse(if)?|nd|nsure|num|vent|x(cept|ec|p(licit|ort)|te(nds|nsion|rn)))|f(allthrough|alse|inal(ly)?|ixed|loat|or(each)?|riend|rom|unc(tion)?)|global|goto|guard|i(f|mp(lements|licit|ort)|n(it|clude(_once)?|line|out|stanceof|t(erface|ernal)?)?|s)|l(ambda|et|ock|ong)|m(icrolight|odule|utable)|NaN|n(amespace|ative|ext|ew|il|ot|ull)|o(bject|perator|r|ut|verride)|p(ackage|arams|rivate|rotected|rotocol|ublic)|r(aise|e(adonly|do|f|gister|peat|quire(_once)?|scue|strict|try|turn))|s(byte|ealed|elf|hort|igned|izeof|tatic|tring|truct|ubscript|uper|ynchronized|witch)|t(emplate|hen|his|hrows?|ransient|rue|ry|ype(alias|def|id|name|of))|u(n(checked|def(ined)?|ion|less|signed|til)|se|sing)|v(ar|irtual|oid|olatile)|w(char_t|hen|here|hile|ith)|xor|yield)$/[i](h):0]),u[r](n.createTextNode(h))),a=d&&d<7?d:a,h="",d=11;![1,/[\/{}[(\-+*=<>:;|\\.,?!&@~]/[i](f),/[\])]/[i](f),/[$\w]/[i](f),"/"==f&&a<2&&"<"!=t,'"'==f,"'"==f,f+p+c[l+1]+c[l+2]=="':null;var r=e.$$ref.match(/\S*\/(\S+)$/);e.xml.name=r[1]}return(0,z.memoizedCreateXMLExample)(e,n)}return JSON.stringify((0,z.memoizedSampleFromSchema)(e,n),null,2)},t.parseSeach=function(){var e={},t=window.location.search;if(""!=t){var n=t.substr(1).split("&");for(var r in n)r=n[r].split("="),e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e},t.btoa=function(t){var n=void 0;return n=t instanceof e?t:new e(t.toString(),"utf-8"),n.toString("base64")},t.sorters={operationsSorter:{alpha:function(e,t){return e.get("path").localeCompare(t.get("path"))},method:function(e,t){return e.get("method").localeCompare(t.get("method"))}}},t.buildFormData=function(e){var t=[];for(var n in e){var r=e[n];void 0!==r&&""!==r&&t.push([n,"=",encodeURIComponent(r).replace(/%20/g,"+")].join(""))}return t.join("&")},t.filterConfigs=function(e,t){var n=void 0,r={};for(n in e)t.indexOf(n)!==-1&&(r[n]=e[n]);return r}}).call(t,n(299).Buffer)},function(e,t,n){"use strict";var r=n(337);e.exports=function(e,t,n,i){var o=n?n.call(i,e,t):void 0;if(void 0!==o)return!!o;if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var a=r(e),s=r(t),u=a.length;if(u!==s.length)return!1;i=i||null;for(var c=Object.prototype.hasOwnProperty.bind(t),l=0;l-1&&e%1==0&&e-1&&e%1==0&&e<=v}function s(e){for(var t=c(e),n=t.length,r=n&&e.length,i=!!r&&a(r)&&(f(e)||p(e)),s=-1,u=[];++s0;++r-1&&e%1==0&&e<=c}function s(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function u(e){return!!e&&"object"==typeof e}var c=9007199254740991,l="[object Arguments]",p="[object Function]",f="[object GeneratorFunction]",h=Object.prototype,d=h.hasOwnProperty,m=h.toString,y=h.propertyIsEnumerable;e.exports=n},function(e,t){function n(e){return!!e&&"object"==typeof e}function r(e,t){var n=null==e?void 0:e[t];return s(n)?n:void 0}function i(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=v}function o(e){return a(e)&&d.call(e)==c}function a(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function s(e){return null!=e&&(o(e)?m.test(f.call(e)):n(e)&&l.test(e))}var u="[object Array]",c="[object Function]",l=/^\[object .+?Constructor\]$/,p=Object.prototype,f=Function.prototype.toString,h=p.hasOwnProperty,d=p.toString,m=RegExp("^"+f.call(h).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),y=r(Array,"isArray"),v=9007199254740991,g=y||function(e){return n(e)&&i(e.length)&&d.call(e)==u};e.exports=g},function(e,t,n){var r=n(342),i=n(356),o=i(function(e,t,n){return t=t.toLowerCase(),e+(n?r(t):t)});e.exports=o},function(e,t,n){function r(e){return o(i(e).toLowerCase())}var i=n(343),o=n(348);e.exports=r},function(e,t,n){function r(e){return null==e?"":i(e)}var i=n(344);e.exports=r},function(e,t,n){function r(e){if("string"==typeof e)return e;if(a(e))return o(e,r)+"";if(s(e))return l?l.call(e):"";var t=e+"";return"0"==t&&1/e==-u?"-0":t}var i=n(308),o=n(345),a=n(346),s=n(347),u=1/0,c=i?i.prototype:void 0,l=c?c.toString:void 0;e.exports=r},function(e,t){function n(e,t){for(var n=-1,r=null==e?0:e.length,i=Array(r);++n=r?e:i(e,t,n)}var i=n(351);e.exports=r},function(e,t){function n(e,t,n){var r=-1,i=e.length;t<0&&(t=-t>i?0:i+t),n=n>i?i:n,n<0&&(n+=i),i=t>n?0:n-t>>>0,t>>>=0;for(var o=Array(i);++rf))return!1;var d=l.get(e);if(d&&l.get(t))return d==t;var m=-1,y=!0,v=n&u?new i:void 0;for(l.set(e,t),l.set(t,e);++m-1&&e%1==0&&e-1&&e%1==0&&e<=r}var r=9007199254740991;e.exports=n},function(e,t){function n(e){return function(t){return e(t)}}e.exports=n},function(e,t,n){(function(e){var r=n(310),i="object"==typeof t&&t&&!t.nodeType&&t,o=i&&"object"==typeof e&&e&&!e.nodeType&&e,a=o&&o.exports===i,s=a&&r.process,u=function(){try{return s&&s.binding&&s.binding("util")}catch(e){}}();e.exports=u}).call(t,n(318)(e))},[1472,435,436],function(e,t){function n(e){var t=e&&e.constructor,n="function"==typeof t&&t.prototype||r;return e===n}var r=Object.prototype;e.exports=n},[1473,314],[1474,373,431],function(e,t,n){var r=n(439),i=n(391),o=n(440),a=n(441),s=n(442),u=n(307),c=n(377),l="[object Map]",p="[object Object]",f="[object Promise]",h="[object Set]",d="[object WeakMap]",m="[object DataView]",y=c(r),v=c(i),g=c(o),_=c(a),b=c(s),x=u;(r&&x(new r(new ArrayBuffer(1)))!=m||i&&x(new i)!=l||o&&x(o.resolve())!=f||a&&x(new a)!=h||s&&x(new s)!=d)&&(x=function(e){var t=u(e),n=t==p?e.constructor:void 0,r=n?c(n):"";if(r)switch(r){case y:return m;case v:return l;case g:return f;case _:return h;case b:return d}return t}),e.exports=x},[1475,371,309],[1476,371,309],[1477,371,309],[1478,371,309],function(e,t,n){function r(e){for(var t=o(e),n=t.length;n--;){var r=t[n],a=e[r];t[n]=[r,a,i(a)]}return t}var i=n(444),o=n(421);e.exports=r},function(e,t,n){function r(e){return e===e&&!i(e)}var i=n(374);e.exports=r},function(e,t){function n(e,t){return function(n){return null!=n&&(n[e]===t&&(void 0!==t||e in Object(n)))}}e.exports=n},function(e,t,n){function r(e,t){return s(e)&&u(t)?c(l(e),t):function(n){var r=o(n,e);return void 0===r&&r===t?a(n,e):i(t,r,p|f)}}var i=n(409),o=n(447),a=n(454),s=n(450),u=n(444),c=n(445),l=n(453),p=1,f=2;e.exports=r},[1479,448],function(e,t,n){function r(e,t){t=i(t,e);for(var n=0,r=t.length;null!=e&&n1&&void 0!==arguments[1]?arguments[1]:{},r=(0,o.objectify)(t),i=r.type,a=r.example,s=r.properties,u=r.additionalProperties,c=r.items,l=n.includeReadOnly;if(void 0!==a)return a;if(!i)if(s)i="object";else{if(!c)return;i="array"}if("object"===i){var f=(0,o.objectify)(s),h={};for(var d in f)f[d].readOnly&&!l||(h[d]=e(f[d],{includeReadOnly:l}));if(u===!0)h.additionalProp1={};else if(u)for(var m=(0,o.objectify)(u),y=e(m,{includeReadOnly:l}),v=1;v<4;v++)h["additionalProp"+v]=y;return h}return"array"===i?[e(c,{includeReadOnly:l})]:t.enum?t.default?t.default:(0,o.normalizeArray)(t.enum)[0]:p(t)},h=(t.inferSchema=function(e){return e.schema&&(e=e.schema),e.properties&&(e.type="object"),e},t.sampleXmlFromSchema=function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=(0,o.objectify)(t),i=r.type,a=r.properties,s=r.additionalProperties,u=r.items,c=r.example,l=n.includeReadOnly,f=r.default,h={},d={},m=t.xml,y=m.name,v=m.prefix,g=m.namespace,_=r.enum,b=void 0,x=void 0;if(!i)if(a||s)i="object";else{if(!u)return;i="array"}if(y=y||"notagname",b=(v?v+":":"")+y,g){var w=v?"xmlns:"+v:"xmlns";d[w]=g}if("array"===i&&u){if(u.xml=u.xml||m||{},u.xml.name=u.xml.name||m.name,m.wrapped)return h[b]=[],Array.isArray(c)?c.forEach(function(t){u.example=t,h[b].push(e(u,n))}):Array.isArray(f)?f.forEach(function(t){u.default=t,h[b].push(e(u,n))}):h[b]=[e(u,n)],d&&h[b].push({_attr:d}),h;var k=[];return Array.isArray(c)?(c.forEach(function(t){u.example=t,k.push(e(u,n))}),k):Array.isArray(f)?(f.forEach(function(t){u.default=t,k.push(e(u,n))}),k):e(u,n)}if("object"===i){var S=(0,o.objectify)(a);h[b]=[],c=c||{};for(var E in S)if(!S[E].readOnly||l)if(S[E].xml=S[E].xml||{},S[E].xml.attribute){var C=Array.isArray(S[E].enum)&&S[E].enum[0],A=S[E].example,T=S[E].default;d[S[E].xml.name||E]=void 0!==A&&A||void 0!==c[E]&&c[E]||void 0!==T&&T||C||p(S[E])}else{S[E].xml.name=S[E].xml.name||E,S[E].example=void 0!==S[E].example?S[E].example:c[E];var O=e(S[E]);Array.isArray(O)?h[b]=h[b].concat(O):h[b].push(O)}return s===!0?h[b].push({additionalProp:"Anything can be here"}):s&&h[b].push({additionalProp:p(s)}),d&&h[b].push({_attr:d}),h}return x=void 0!==c?c:void 0!==f?f:Array.isArray(_)?_[0]:p(t),h[b]=d?[{_attr:d},x]:x,h});t.memoizedCreateXMLExample=(0,c.default)(i),t.memoizedSampleFromSchema=(0,c.default)(f)},function(e,t,n){(function(t){function r(e,n){function r(e){y?t.nextTick(e):e()}function i(e,t){if(void 0!==t&&(h+=t),e&&!d&&(f=f||new l,d=!0),e&&d){var n=h;r(function(){f.emit("data",n)}),h=""}}function o(e,t){s(i,a(e,m,m?1:0),t)}function u(){if(f){var e=h;r(function(){f.emit("data",e),f.emit("end"),f.readable=!1,f.emit("close")})}}function c(e){var t=e.encoding||"UTF-8",n={version:"1.0",encoding:t};e.standalone&&(n.standalone=e.standalone),o({"?xml":{_attr:n}}),h=h.replace("/>","?>")}"object"!=typeof n&&(n={indent:n});var f=n.stream?new l:null,h="",d=!1,m=n.indent?n.indent===!0?p:n.indent:"",y=!0;return r(function(){y=!1}),n.declaration&&c(n.declaration),e&&e.forEach?e.forEach(function(t,n){var r;n+1===e.length&&(r=u),o(t,r)}):o(e,u),f?(f.readable=!0,f):h}function i(){var e=Array.prototype.slice.call(arguments),t={_elem:a(e)};return t.push=function(e){if(!this.append)throw new Error("not assigned to a parent!");var t=this,n=this._elem.indent;s(this.append,a(e,n,this._elem.icount+(n?1:0)),function(){t.append(!0)})},t.close=function(e){void 0!==e&&this.push(e),this.end&&this.end()},t}function o(e,t){return new Array(t||0).join(e||"")}function a(e,t,n){function r(e){var t=Object.keys(e);t.forEach(function(t){d.push(u(t,e[t]))})}n=n||0;var i,s=o(t,n),l=e,p=!1;if("object"==typeof e){var f=Object.keys(e);if(i=f[0],l=e[i],l&&l._elem)return l._elem.name=i,l._elem.icount=n,l._elem.indent=t,l._elem.indents=s,l._elem.interrupt=l,l._elem}var h,d=[],m=[];switch(typeof l){case"object":if(null===l)break;l._attr&&r(l._attr),l._cdata&&m.push(("/g,"]]]]>")+"]]>"),l.forEach&&(h=!1,m.push(""),l.forEach(function(e){if("object"==typeof e){var i=Object.keys(e)[0];"_attr"==i?r(e._attr):m.push(a(e,t,n+1))}else m.pop(),h=!0,m.push(c(e))}),h||m.push(""));break;default:m.push(c(l))}return{name:i,interrupt:p,attributes:d,content:m,icount:n,indents:s,indent:t}}function s(e,t,n){function r(){for(;t.content.length;){var r=t.content.shift();if(void 0!==r){if(i(r))return;s(e,r)}}e(!1,(o>1?t.indents:"")+(t.name?"":"")+(t.indent&&!n?"\n":"")),n&&n()}function i(t){return!!t.interrupt&&(t.interrupt.append=e,t.interrupt.end=r,t.interrupt=!1,e(!0),!0)}if("object"!=typeof t)return e(!1,t);var o=t.interrupt?1:t.content.length;return e(!1,t.indents+(t.name?"<"+t.name:"")+(t.attributes.length?" "+t.attributes.join(" "):"")+(o?t.name?">":"":t.name?"/>":"")+(t.indent&&o>1?"\n":"")),o?void(i(t)||r()):e(!1,t.indent?"\n":"")}function u(e,t){return e+'="'+c(t)+'"'}var c=n(471),l=n(472).Stream,p=" ";e.exports=r,e.exports.element=e.exports.Element=i}).call(t,n(470))},function(e,t){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function i(e){if(l===setTimeout)return setTimeout(e,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(e,0);try{return l(e,0)}catch(t){try{return l.call(null,e,0)}catch(t){return l.call(this,e,0)}}}function o(e){if(p===clearTimeout)return clearTimeout(e);if((p===r||!p)&&clearTimeout)return p=clearTimeout,clearTimeout(e);try{return p(e)}catch(t){try{return p.call(null,e)}catch(t){return p.call(this,e)}}}function a(){m&&h&&(m=!1,h.length?d=h.concat(d):y=-1,d.length&&s())}function s(){if(!m){var e=i(a);m=!0;for(var t=d.length;t;){for(h=d,d=[];++y1)for(var n=1;n'])/g,function(e,t){return r[t]}):e}var r={"&":"&",'"':""","'":"'","<":"<",">":">"};e.exports=n},function(e,t,n){function r(){i.call(this)}e.exports=r;var i=n(473).EventEmitter,o=n(474);o(r,i),r.Readable=n(475),r.Writable=n(492),r.Duplex=n(493),r.Transform=n(494),r.PassThrough=n(495),r.Stream=r,r.prototype.pipe=function(e,t){function n(t){e.writable&&!1===e.write(t)&&c.pause&&c.pause()}function r(){c.readable&&c.resume&&c.resume()}function o(){l||(l=!0,e.end())}function a(){l||(l=!0,"function"==typeof e.destroy&&e.destroy())}function s(e){if(u(),0===i.listenerCount(this,"error"))throw e}function u(){c.removeListener("data",n),e.removeListener("drain",r),c.removeListener("end",o),c.removeListener("close",a),c.removeListener("error",s),e.removeListener("error",s),c.removeListener("end",u),c.removeListener("close",u),e.removeListener("close",u)}var c=this;c.on("data",n),e.on("drain",r),e._isStdio||t&&t.end===!1||(c.on("end",o),c.on("close",a));var l=!1;return c.on("error",s),e.on("error",s),c.on("end",u),c.on("close",u),e.on("close",u),e.emit("pipe",c),e}},function(e,t){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function r(e){return"function"==typeof e}function i(e){return"number"==typeof e}function o(e){return"object"==typeof e&&null!==e}function a(e){return void 0===e}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!i(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},n.prototype.emit=function(e){var t,n,i,s,u,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}if(n=this._events[e],a(n))return!1;if(r(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),n.apply(this,s)}else if(o(n))for(s=Array.prototype.slice.call(arguments,1),c=n.slice(),i=c.length,u=0;u0&&this._events[e].length>i&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function n(){this.removeListener(e,n),i||(i=!0,t.apply(this,arguments))}if(!r(t))throw TypeError("listener must be a function");var i=!1;return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var n,i,a,s;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],a=n.length,i=-1,n===t||r(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(o(n)){for(s=a;s-- >0;)if(n[s]===t||n[s].listener&&n[s].listener===t){i=s;break}if(i<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(i,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],r(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(r(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t){"function"==typeof Object.create?e.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},function(e,t,n){t=e.exports=n(476),t.Stream=t,t.Readable=t,t.Writable=n(484),t.Duplex=n(483),t.Transform=n(490),t.PassThrough=n(491)},function(e,t,n){(function(t){"use strict";function r(e,t,n){return"function"==typeof e.prependListener?e.prependListener(t,n):void(e._events&&e._events[t]?D(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n))}function i(e,t){T=T||n(483),e=e||{},this.objectMode=!!e.objectMode,t instanceof T&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var r=e.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.buffer=new L,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(B||(B=n(488).StringDecoder),this.decoder=new B(e.encoding),this.encoding=e.encoding)}function o(e){return T=T||n(483),this instanceof o?(this._readableState=new i(e,this),this.readable=!0,e&&"function"==typeof e.read&&(this._read=e.read),void P.call(this)):new o(e)}function a(e,t,n,r,i){var o=l(t,n);if(o)e.emit("error",o);else if(null===n)t.reading=!1,p(e,t);else if(t.objectMode||n&&n.length>0)if(t.ended&&!i){var a=new Error("stream.push() after EOF");e.emit("error",a)}else if(t.endEmitted&&i){var u=new Error("stream.unshift() after end event");e.emit("error",u)}else{var c;!t.decoder||i||r||(n=t.decoder.write(n),c=!t.objectMode&&0===n.length),i||(t.reading=!1),c||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,i?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&f(e))),d(e,t)}else i||(t.reading=!1);return s(t)}function s(e){return!e.ended&&(e.needReadable||e.length=q?e=q:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function c(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=u(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function l(e,t){var n=null;return I.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function p(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,f(e)}}function f(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(F("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?O(h,e):h(e))}function h(e){F("emit readable"),e.emit("readable"),b(e)}function d(e,t){t.readingMore||(t.readingMore=!0,O(m,e,t))}function m(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=w(e,t.buffer,t.decoder),n}function w(e,t,n){var r;return eo.length?o.length:e;if(i+=a===o.length?o:o.slice(0,e),e-=a,0===e){a===o.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++r}return t.length-=r,i}function S(e,t){var n=j.allocUnsafe(e),r=t.head,i=1;for(r.data.copy(n),e-=r.data.length;r=r.next;){var o=r.data,a=e>o.length?o.length:e;if(o.copy(n,n.length-e,0,a),e-=a,0===e){a===o.length?(++i,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++i}return t.length-=i,n}function E(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,O(C,t,e))}function C(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function A(e,t){for(var n=0,r=e.length;n=t.highWaterMark||t.ended))return F("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?E(this):f(this),null;if(e=c(e,t),0===e&&t.ended)return 0===t.length&&E(this),null;var r=t.needReadable;F("need readable",r),(0===t.length||t.length-e0?x(e,t):null,null===i?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&E(this)),null!==i&&this.emit("data",i),i},o.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},o.prototype.pipe=function(e,n){function i(e){F("onunpipe"),e===f&&a()}function o(){F("onend"),e.end()}function a(){F("cleanup"),e.removeListener("close",c),e.removeListener("finish",l),e.removeListener("drain",v),e.removeListener("error",u),e.removeListener("unpipe",i),f.removeListener("end",o),f.removeListener("end",a),f.removeListener("data",s),g=!0,!h.awaitDrain||e._writableState&&!e._writableState.needDrain||v()}function s(t){F("ondata"),_=!1;var n=e.write(t);!1!==n||_||((1===h.pipesCount&&h.pipes===e||h.pipesCount>1&&A(h.pipes,e)!==-1)&&!g&&(F("false write response, pause",f._readableState.awaitDrain),f._readableState.awaitDrain++,_=!0),f.pause())}function u(t){F("onerror",t),p(),e.removeListener("error",u),0===M(e,"error")&&e.emit("error",t)}function c(){e.removeListener("finish",l),p()}function l(){F("onfinish"),e.removeListener("close",c),p()}function p(){F("unpipe"),f.unpipe(e)}var f=this,h=this._readableState;switch(h.pipesCount){case 0:h.pipes=e;break;case 1:h.pipes=[h.pipes,e];break;default:h.pipes.push(e)}h.pipesCount+=1,F("pipe count=%d opts=%j",h.pipesCount,n);var d=(!n||n.end!==!1)&&e!==t.stdout&&e!==t.stderr,m=d?o:a;h.endEmitted?O(m):f.once("end",m),e.on("unpipe",i);var v=y(f);e.on("drain",v);var g=!1,_=!1;return f.on("data",s),r(e,"error",u),e.once("close",c),e.once("finish",l),e.emit("pipe",f),h.flowing||(F("pipe resume"),f.resume()),e},o.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;ia)throw new RangeError("size is too large");var r=n,o=t;void 0===o&&(r=void 0,o=0);var s=new i(e);if("string"==typeof o)for(var u=new i(o,r),c=u.length,l=-1;++la)throw new RangeError("size is too large");return new i(e)},t.from=function(t,n,r){if("function"==typeof i.from&&(!e.Uint8Array||Uint8Array.from!==i.from))return i.from(t,n,r);if("number"==typeof t)throw new TypeError('"value" argument must not be a number');if("string"==typeof t)return new i(t,n);if("undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer){var o=n;if(1===arguments.length)return new i(t);"undefined"==typeof o&&(o=0);var a=r;if("undefined"==typeof a&&(a=t.byteLength-o),o>=t.byteLength)throw new RangeError("'offset' is out of bounds");if(a>t.byteLength-o)throw new RangeError("'length' is out of bounds");return new i(t.slice(o,o+a))}if(i.isBuffer(t)){var s=new i(t.length);return t.copy(s,0,0,t.length),s}if(t){if(Array.isArray(t)||"undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return new i(t);if("Buffer"===t.type&&Array.isArray(t.data))return new i(t.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")},t.allocUnsafeSlow=function(e){if("function"==typeof i.allocUnsafeSlow)return i.allocUnsafeSlow(e);if("number"!=typeof e)throw new TypeError("size must be a number");if(e>=a)throw new RangeError("size is too large");return new o(e)}}).call(t,function(){return this}())},function(e,t,n){(function(e){function n(e){return Array.isArray?Array.isArray(e):"[object Array]"===y(e)}function r(e){return"boolean"==typeof e}function i(e){return null===e}function o(e){return null==e}function a(e){return"number"==typeof e}function s(e){return"string"==typeof e}function u(e){return"symbol"==typeof e}function c(e){return void 0===e}function l(e){return"[object RegExp]"===y(e)}function p(e){return"object"==typeof e&&null!==e}function f(e){return"[object Date]"===y(e)}function h(e){return"[object Error]"===y(e)||e instanceof Error}function d(e){return"function"==typeof e}function m(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function y(e){return Object.prototype.toString.call(e)}t.isArray=n,t.isBoolean=r,t.isNull=i,t.isNullOrUndefined=o,t.isNumber=a,t.isString=s,t.isSymbol=u,t.isUndefined=c,t.isRegExp=l,t.isObject=p,t.isDate=f,t.isError=h,t.isFunction=d,t.isPrimitive=m,t.isBuffer=e.isBuffer}).call(t,n(299).Buffer)},function(e,t){},function(e,t,n){"use strict";function r(){this.head=null,this.tail=null,this.length=0}var i=(n(299).Buffer,n(479));e.exports=r,r.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},r.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},r.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},r.prototype.clear=function(){this.head=this.tail=null,this.length=0},r.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},r.prototype.concat=function(e){if(0===this.length)return i.alloc(0);if(1===this.length)return this.head.data;for(var t=i.allocUnsafe(e>>>0),n=this.head,r=0;n;)n.data.copy(t,r),r+=n.data.length,n=n.next;return t}},function(e,t,n){"use strict";function r(e){return this instanceof r?(c.call(this,e),l.call(this,e),e&&e.readable===!1&&(this.readable=!1),e&&e.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,e&&e.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",i)):new r(e)}function i(){this.allowHalfOpen||this._writableState.ended||s(o,this)}function o(e){e.end()}var a=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};e.exports=r;var s=n(477),u=n(480);u.inherits=n(474);var c=n(476),l=n(484);u.inherits(r,c);for(var p=a(l.prototype),f=0;f-1?r:E;s.WritableState=a;var A=n(480);A.inherits=n(474);var T={deprecate:n(487)},O=n(478),D=n(299).Buffer,M=n(479);A.inherits(s,O),a.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(a.prototype,"buffer",{ +get:T.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(e){}}();var P;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(P=Function.prototype[Symbol.hasInstance],Object.defineProperty(s,Symbol.hasInstance,{value:function(e){return!!P.call(this,e)||e&&e._writableState instanceof a}})):P=function(e){return e instanceof this},s.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},s.prototype.write=function(e,t,n){var r=this._writableState,o=!1,a=D.isBuffer(e);return"function"==typeof t&&(n=t,t=null),a?t="buffer":t||(t=r.defaultEncoding),"function"!=typeof n&&(n=i),r.ended?u(this,n):(a||c(this,r,e,n))&&(r.pendingcb++,o=p(this,r,a,e,t,n)),o},s.prototype.cork=function(){var e=this._writableState;e.corked++},s.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||g(this,e))},s.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},s.prototype._write=function(e,t,n){n(new Error("_write() is not implemented"))},s.prototype._writev=null,s.prototype.end=function(e,t,n){var r=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!==e&&void 0!==e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||w(this,r,n)}}).call(t,n(470),n(485).setImmediate)},function(e,t,n){function r(e,t){this._id=e,this._clearFn=t}var i=Function.prototype.apply;t.setTimeout=function(){return new r(i.call(setTimeout,window,arguments),clearTimeout)},t.setInterval=function(){return new r(i.call(setInterval,window,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e&&e.close()},r.prototype.unref=r.prototype.ref=function(){},r.prototype.close=function(){this._clearFn.call(window,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},n(486),t.setImmediate=setImmediate,t.clearImmediate=clearImmediate},function(e,t,n){(function(e,t){!function(e,n){"use strict";function r(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n>5===6?2:e>>4===14?3:e>>3===30?4:-1}function s(e,t,n){var r=t.length-1;if(r=0?(i>0&&(e.lastNeed=i-1),i):--r=0?(i>0&&(e.lastNeed=i-2),i):--r=0?(i>0&&(2===i?i=0:e.lastNeed=i-3),i):0))}function u(e,t,n){if(128!==(192&t[0]))return e.lastNeed=0,"�".repeat(n);if(e.lastNeed>1&&t.length>1){if(128!==(192&t[1]))return e.lastNeed=1,"�".repeat(n+1);if(e.lastNeed>2&&t.length>2&&128!==(192&t[2]))return e.lastNeed=2,"�".repeat(n+2)}}function c(e){var t=this.lastTotal-this.lastNeed,n=u(this,e,t);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function l(e,t){var n=s(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)}function p(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�".repeat(this.lastTotal-this.lastNeed):t}function f(e,t){if((e.length-t)%2===0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function h(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function d(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function m(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function y(e){return e.toString(this.encoding)}function v(e){return e&&e.length?this.write(e):""}var g=n(489).Buffer,_=g.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};t.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(t=this.fillLast(e),void 0===t)return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n1&&(a.normalizer=n(542)(t)):t===!1?a.normalizer=n(543)():1===t?a.normalizer=n(545)():a.normalizer=n(546)(t))),a.async&&n(547),a.promise&&n(550),a.dispose&&n(552),a.maxAge&&n(553),a.max&&n(556),a.refCounter&&n(558),o(e,a)}},function(e,t){"use strict";var n=Array.prototype.forEach,r=Object.create,i=function(e,t){var n;for(n in e)t[n]=e[n]};e.exports=function(e){var t=r(null);return n.call(arguments,function(e){null!=e&&i(Object(e),t)}),t}},function(e,t,n){"use strict";var r=n(499);e.exports=function(e,t,n){var i;return isNaN(e)?(i=t,i>=0?n&&i?i-1:i:1):e!==!1&&r(e)}},function(e,t,n){"use strict";var r=n(500),i=Math.max;e.exports=function(e){return i(0,r(e))}},function(e,t,n){"use strict";var r=n(501),i=Math.abs,o=Math.floor;e.exports=function(e){return isNaN(e)?0:(e=Number(e),0!==e&&isFinite(e)?r(e)*o(i(e)):e)}},function(e,t,n){"use strict";e.exports=n(502)()?Math.sign:n(503)},function(e,t){"use strict";e.exports=function(){var e=Math.sign;return"function"==typeof e&&(1===e(10)&&e(-20)===-1)}},function(e,t){"use strict";e.exports=function(e){return e=Number(e),isNaN(e)||0===e?e:e>0?1:-1}},function(e,t,n){"use strict";var r=n(505),i=n(506),o=n(509),a=n(510),s=n(498),u=Object.prototype.hasOwnProperty;e.exports=function e(t){var n,c,l;if(r(t),n=Object(arguments[1]),n.async&&n.promise)throw new Error("Options 'async' and 'promise' cannot be used together");return u.call(t,"__memoized__")&&!n.force?t:(c=s(n.length,t.length,n.async&&o.async),l=a(t,c,n),i(o,function(e,t){n[t]&&e(n[t],l,n)}),e.__profiler__&&e.__profiler__(l),l.updateEnv(),l.memoized)}},function(e,t){"use strict";e.exports=function(e){if("function"!=typeof e)throw new TypeError(e+" is not a function");return e}},function(e,t,n){"use strict";e.exports=n(507)("forEach")},function(e,t,n){"use strict";var r=n(505),i=n(508),o=Function.prototype.bind,a=Function.prototype.call,s=Object.keys,u=Object.prototype.propertyIsEnumerable;e.exports=function(e,t){return function(n,c){var l,p=arguments[2],f=arguments[3];return n=Object(i(n)),r(c),l=s(n),f&&l.sort("function"==typeof f?o.call(f,n):void 0),"function"!=typeof e&&(e=l[e]),a.call(e,l,function(e,r){return u.call(n,e)?a.call(c,p,n[e],e,n,r):t})}}},function(e,t){"use strict";e.exports=function(e){if(null==e)throw new TypeError("Cannot use null or undefined");return e}},function(e,t){"use strict"},function(e,t,n){"use strict";var r=n(511),i=n(518),o=n(520),a=n(525).methods,s=n(526),u=n(540),c=Function.prototype.apply,l=Function.prototype.call,p=Object.create,f=Object.prototype.hasOwnProperty,h=Object.defineProperties,d=a.on,m=a.emit;e.exports=function(e,t,n){var a,y,v,g,_,b,x,w,k,S,E,C,A,T=p(null);return y=t!==!1?t:isNaN(e.length)?1:e.length,n.normalizer&&(w=u(n.normalizer),v=w.get,g=w.set,_=w.delete,b=w.clear),null!=n.resolvers&&(A=s(n.resolvers)),C=v?i(function(t){var n,i,o=arguments;if(A&&(o=A(o)),n=v(o),null!==n&&f.call(T,n))return k&&a.emit("get",n,o,this),T[n];if(i=1===o.length?l.call(e,this,o[0]):c.call(e,this,o),null===n){if(n=v(o),null!==n)throw r("Circular invocation","CIRCULAR_INVOCATION");n=g(o)}else if(f.call(T,n))throw r("Circular invocation","CIRCULAR_INVOCATION");return T[n]=i,S&&a.emit("set",n,null,i),i},y):0===t?function(){var t;if(f.call(T,"data"))return k&&a.emit("get","data",arguments,this),T.data;if(t=arguments.length?c.call(e,this,arguments):l.call(e,this),f.call(T,"data"))throw r("Circular invocation","CIRCULAR_INVOCATION");return T.data=t,S&&a.emit("set","data",null,t),t}:function(t){var n,i,o=arguments;if(A&&(o=A(arguments)),i=String(o[0]),f.call(T,i))return k&&a.emit("get",i,o,this),T[i];if(n=1===o.length?l.call(e,this,o[0]):c.call(e,this,o),f.call(T,i))throw r("Circular invocation","CIRCULAR_INVOCATION");return T[i]=n,S&&a.emit("set",i,null,n),n},a={original:e,memoized:C,get:function(e){return A&&(e=A(e)),v?v(e):String(e[0])},has:function(e){return f.call(T,e)},delete:function(e){var t;f.call(T,e)&&(_&&_(e),t=T[e],delete T[e],E&&a.emit("delete",e,t))},clear:function(){var e=T;b&&b(),T=p(null),a.emit("clear",e)},on:function(e,t){return"get"===e?k=!0:"set"===e?S=!0:"delete"===e&&(E=!0),d.call(this,e,t)},emit:m,updateEnv:function(){e=a.original}},x=v?i(function(e){var t,n=arguments;A&&(n=A(n)),t=v(n),null!==t&&a.delete(t)},y):0===t?function(){return a.delete("data")}:function(e){return A&&(e=A(arguments)[0]),a.delete(e)},h(C,{__memoized__:o(!0),delete:o(x),clear:o(a.clear)}),a}},function(e,t,n){"use strict";var r=n(512),i=Error.captureStackTrace;t=e.exports=function(e){var n=new Error(e),o=arguments[1],a=arguments[2];return null==a&&o&&"object"==typeof o&&(a=o,o=null),null!=a&&r(n,a),null!=o&&(n.code=String(o)),i&&i(n,t),n}},function(e,t,n){"use strict";e.exports=n(513)()?Object.assign:n(514)},function(e,t){"use strict";e.exports=function(){var e,t=Object.assign;return"function"==typeof t&&(e={foo:"raz"},t(e,{bar:"dwa"},{trzy:"trzy"}),e.foo+e.bar+e.trzy==="razdwatrzy")}},function(e,t,n){"use strict";var r=n(515),i=n(508),o=Math.max;e.exports=function(e,t){var n,a,s,u=o(arguments.length,2);for(e=Object(i(e)),s=function(r){try{e[r]=t[r]}catch(e){n||(n=e)}},a=1;a-1}},function(e,t,n){"use strict";var r,i,o,a,s,u,c,l=n(520),p=n(505),f=Function.prototype.apply,h=Function.prototype.call,d=Object.create,m=Object.defineProperty,y=Object.defineProperties,v=Object.prototype.hasOwnProperty,g={configurable:!0,enumerable:!1,writable:!0};r=function(e,t){var n;return p(t),v.call(this,"__ee__")?n=this.__ee__:(n=g.value=d(null),m(this,"__ee__",g),g.value=null),n[e]?"object"==typeof n[e]?n[e].push(t):n[e]=[n[e],t]:n[e]=t,this},i=function(e,t){var n,i;return p(t),i=this,r.call(this,e,n=function(){o.call(i,e,n),f.call(t,this,arguments)}),n.__eeOnceListener__=t,this},o=function(e,t){var n,r,i,o;if(p(t),!v.call(this,"__ee__"))return this;if(n=this.__ee__,!n[e])return this;if(r=n[e],"object"==typeof r)for(o=0;i=r[o];++o)i!==t&&i.__eeOnceListener__!==t||(2===r.length?n[e]=r[o?0:1]:r.splice(o,1));else r!==t&&r.__eeOnceListener__!==t||delete n[e];return this},a=function(e){var t,n,r,i,o;if(v.call(this,"__ee__")&&(i=this.__ee__[e]))if("object"==typeof i){for(n=arguments.length,o=new Array(n-1),t=1;t=55296&&v<=56319&&(x+=e[++n])),x=w?p.call(w,k,x,d):x,t?(f.value=x,h(m,d,f)):m[d]=x,++d;y=d}if(void 0===y)for(y=a(e.length),t&&(m=new t(y)),n=0;n=0?u(c):r(this.length)-u(s(c)),t=c;ti)throw new TypeError(e+" exceeds maximum possible timeout");return e}},function(e,t){"use strict";e.exports=2147483647},function(e,t,n){"use strict";var r=n(499),i=n(557),o=n(509);o.max=function(e,t,n){var a,s,u;e=r(e),e&&(s=i(e),a=n.async&&o.async||n.promise&&o.promise?"async":"",t.on("set"+a,u=function(e){e=s.hit(e),void 0!==e&&t.delete(e)}),t.on("get"+a,u),t.on("delete"+a,s.delete),t.on("clear"+a,s.clear))}},function(e,t,n){"use strict";var r=n(499),i=Object.create,o=Object.prototype.hasOwnProperty;e.exports=function(e){var t,n=0,a=1,s=i(null),u=i(null),c=0;return e=r(e),{hit:function(r){var i=u[r],l=++c;if(s[l]=r,u[r]=l,!i){if(++n,n<=e)return;return r=s[a],t(r),r}if(delete s[i],a===i)for(;!o.call(s,++a);)continue},delete:t=function(e){var t=u[e];if(t&&(delete s[t],delete u[e],--n,a===t)){if(!n)return c=0,void(a=1);for(;!o.call(s,++a);)continue}},clear:function(){n=0,a=1,s=i(null),u=i(null),c=0}}}},function(e,t,n){"use strict";var r=n(520),i=n(509),o=Object.create,a=Object.defineProperties;i.refCounter=function(e,t,n){var s,u;s=o(null),u=n.async&&i.async||n.promise&&i.promise?"async":"",t.on("set"+u,function(e,t){s[e]=t||1}),t.on("get"+u,function(e){++s[e]}),t.on("delete"+u,function(e){delete s[e]}),t.on("clear"+u,function(){s={}}),a(t.memoized,{deleteRef:r(function(){var e=t.get(arguments);return null===e?null:s[e]?!--s[e]&&(t.delete(e),!0):null}),getRefCount:r(function(){var e=t.get(arguments);return null===e?0:s[e]?s[e]:0})})}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(){return[a.default]}Object.defineProperty(t,"__esModule",{value:!0}),t.default=i;var o=n(560),a=r(o)},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){var e={components:{App:D.default,authorizationPopup:P.default,authorizeBtn:j.default,authorizeOperationBtn:N.default,auths:B.default,authError:z.default,oauth2:H.default,apiKeyAuth:U.default,basicAuth:K.default,clear:G.default,liveResponse:Y.default,info:Ce.default,onlineValidatorBadge:Z.default,operations:ee.default,operation:ne.default,highlightCode:ie.default,responses:ae.default,response:ue.default,responseBody:le.default,parameters:fe.default,parameterRow:de.default,execute:ye.default,headers:ge.default,errors:be.default,contentType:we.default,overview:Se.default,footer:Te.default,ParamBody:De.default,curl:Pe.default,schemes:je.default,modelExample:Ne.default,model:Be.default,models:ze.default,TryItOutButton:Ue.default,Markdown:Ke.default,BaseLayout:He.default}},t={components:Ge},n={components:Ye};return[S.default,y.default,f.default,l.default,a.default,u.default,d.default,e,t,b.default,n,w.default,g.default,C.default,T.default]};var o=n(561),a=i(o),s=n(576),u=i(s),c=n(580),l=i(c),p=n(619),f=i(p),h=n(848),d=i(h),m=n(849),y=i(m),v=n(850),g=i(v),_=n(882),b=i(_),x=n(1155),w=i(x),k=n(1160),S=i(k),E=n(1162),C=i(E),A=n(1211),T=i(A),O=n(1212),D=i(O),M=n(1213),P=i(M),I=n(1214),j=i(I),R=n(1215),N=i(R),F=n(1217),B=i(F),L=n(1218),z=i(L),q=n(1219),U=i(q),W=n(1220),K=i(W),V=n(1221),H=i(V),J=n(1223),G=i(J),X=n(1224),Y=i(X),$=n(1225),Z=i($),Q=n(1226),ee=i(Q),te=n(1227),ne=i(te),re=n(1231),ie=i(re),oe=n(1232),ae=i(oe),se=n(1233),ue=i(se),ce=n(1234),le=i(ce),pe=n(1236),fe=i(pe),he=n(1237),de=i(he),me=n(1238),ye=i(me),ve=n(1239),ge=i(ve),_e=n(1240),be=i(_e),xe=n(1265),we=i(xe),ke=n(1266),Se=i(ke),Ee=n(1268),Ce=i(Ee),Ae=n(1269),Te=i(Ae),Oe=n(1270),De=i(Oe),Me=n(1271),Pe=i(Me),Ie=n(1273),je=i(Ie),Re=n(1274),Ne=i(Re),Fe=n(1275),Be=i(Fe),Le=n(1276),ze=i(Le),qe=n(1277),Ue=i(qe),We=n(1278),Ke=i(We),Ve=n(1374),He=i(Ve),Je=n(1267),Ge=r(Je),Xe=n(1375),Ye=r(Xe)},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return{statePlugins:{err:{reducers:(0,a.default)(e),actions:u,selectors:l}}}};var o=n(562),a=i(o),s=n(333),u=r(s),c=n(574),l=r(c)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t;return t={},i(t,o.NEW_THROWN_ERR,function(t,n){var r=n.payload,i=Object.assign(f,r,{type:"thrown"});return t.update("errors",function(e){return(e||(0,u.List)()).push((0,u.fromJS)(i))}).update("errors",function(t){return(0,p.default)(t,e.getSystem())})}),i(t,o.NEW_THROWN_ERR_BATCH,function(t,n){var r=n.payload;return r=r.map(function(e){return(0,u.fromJS)(Object.assign(f,e,{type:"thrown"}))}),t.update("errors",function(e){return(e||(0,u.List)()).concat((0,u.fromJS)(r))}).update("errors",function(t){return(0,p.default)(t,e.getSystem())})}),i(t,o.NEW_SPEC_ERR,function(t,n){var r=n.payload,i=(0,u.fromJS)(r);return i=i.set("type","spec"),t.update("errors",function(e){return(e||(0,u.List)()).push((0,u.fromJS)(i)).sortBy(function(e){return e.get("line")})}).update("errors",function(t){return(0,p.default)(t,e.getSystem())})}),i(t,o.NEW_AUTH_ERR,function(t,n){var r=n.payload,i=(0,u.fromJS)(Object.assign({},r));return i=i.set("type","auth"),t.update("errors",function(e){return(e||(0,u.List)()).push((0,u.fromJS)(i))}).update("errors",function(t){return(0,p.default)(t,e.getSystem())})}),i(t,o.CLEAR,function(e,t){var n=t.payload;if(n){var r=c.default.fromJS((0,s.default)((e.get("errors")||(0,u.List)()).toJS(),n));return e.merge({errors:r})}}),t};var o=n(333),a=n(563),s=r(a),u=n(325),c=r(u),l=n(567),p=r(l),f={line:0,level:"error",message:"Unknown error"}},function(e,t,n){function r(e,t){var n=s(e)?i:o;return n(e,u(a(t,3)))}var i=n(564),o=n(565),a=n(400),s=n(346),u=n(566);e.exports=r},function(e,t){function n(e,t){for(var n=-1,r=null==e?0:e.length,i=0,o=[];++n-1||c.push({name:o(e).replace(".js","").replace("./",""),transform:u(e).transform}))})},function(e,t,n){function r(e,t,n){var r=u(e)?i:s,c=arguments.length<3;return r(e,a(t,4),n,c,o)}var i=n(357),o=n(462),a=n(400),s=n(569),u=n(346);e.exports=r},function(e,t){function n(e,t,n,r,i){return i(e,function(e,i,o){n=r?(r=!1,e):t(n,e,i,o)}),n}e.exports=n},function(e,t,n){function r(e){return n(i(e))}function i(e){return o[e]||function(){throw new Error("Cannot find module '"+e+"'.")}()}var o={"./not-of-type.js":571,"./parameter-oneof.js":572,"./strip-instance.js":573};r.keys=function(){return Object.keys(o)},r.resolve=i,e.exports=r,r.id=570},function(e,t){"use strict";function n(e){return e.map(function(e){var t="is not of a type(s)",n=e.get("message").indexOf(t);if(n>-1){var i=e.get("message").slice(n+t.length).split(",");return e.set("message",e.get("message").slice(0,n)+r(i))}return e})}function r(e){return e.reduce(function(e,t,n,r){return n===r.length-1&&r.length>1?e+"or "+t:r[n+1]&&r.length>2?e+t+", ":r[n+1]?e+t+" ":e+t},"should be a")}Object.defineProperty(t,"__esModule",{value:!0}),t.transform=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){t.jsSpec;return e}Object.defineProperty(t,"__esModule",{value:!0}),t.transform=i;var o=n(447);r(o),n(325)},function(e,t){"use strict";function n(e){return e.map(function(e){return e.set("message",r(e.get("message"),"instance."))})}function r(e,t){return e.replace(new RegExp(t,"g"),"")}Object.defineProperty(t,"__esModule",{value:!0}),t.transform=n},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lastError=t.allErrors=void 0;var r=n(325),i=n(575),o=function(e){return e},a=t.allErrors=(0,i.createSelector)(o,function(e){return e.get("errors",(0,r.List)())});t.lastError=(0,i.createSelector)(a,function(e){return e.last()})},function(e,t){"use strict";function n(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t1?t-1:0),i=1;i2?r-2:0),o=2;o1&&void 0!==arguments[1])||arguments[1];return e=(0,a.normalizeArray)(e),{type:c,payload:{thing:e,shown:t}}}function o(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return e=(0,a.normalizeArray)(e),{type:u,payload:{thing:e,mode:t}}}Object.defineProperty(t,"__esModule",{value:!0}),t.SHOW=t.UPDATE_MODE=t.UPDATE_LAYOUT=void 0,t.updateLayout=r,t.show=i,t.changeMode=o;var a=n(335),s=t.UPDATE_LAYOUT="layout_update_layout",u=t.UPDATE_MODE="layout_update_mode",c=t.SHOW="layout_show"},function(e,t,n){"use strict";function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t2&&void 0!==arguments[2]?arguments[2]:"";return t=(0,o.normalizeArray)(t),e.getIn(["modes"].concat(r(t)),n)},t.showSummary=(0,i.createSelector)(a,function(e){return!s(e,"editor")})},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return{statePlugins:{spec:{wrapActions:f,reducers:a.default,actions:u,selectors:l}}}};var o=n(581),a=i(o),s=n(582),u=r(s),c=n(617),l=r(c),p=n(618),f=r(p)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e){return e instanceof Error?{type:E,error:!0,payload:e}:"string"==typeof e?{type:E,payload:e.replace(/\t/g," ")||""}:{type:E,payload:""}}function a(e){return{type:F,payload:e}}function s(e){return{type:C,payload:e}}function u(e){if(!e||"object"!==("undefined"==typeof e?"undefined":g(e)))throw new Error("updateJson must only accept a simple JSON object");return{type:A,payload:e}}function c(e,t,n,r){return{type:T,payload:{path:e,value:n,paramName:t,isXml:r}}}function l(e){return{type:O,payload:{pathMethod:e}}}function p(e){return{type:R,payload:{pathMethod:e}}}function f(e,t){return{type:N,payload:{path:e,value:t,key:"consumes_value"}}}function h(e,t){return{type:N,payload:{path:e,value:t,key:"produces_value"}}}function d(e,t){return{type:I,payload:{path:e,method:t}}}function m(e,t){return{type:j,payload:{path:e,method:t}}}function y(e,t,n){return{type:B,payload:{scheme:e,path:t,method:n}}}Object.defineProperty(t,"__esModule",{value:!0}),t.execute=t.executeRequest=t.logRequest=t.setRequest=t.setResponse=t.formatIntoYaml=t.resolveSpec=t.parseToJson=t.SET_SCHEME=t.UPDATE_RESOLVED=t.UPDATE_OPERATION_VALUE=t.ClEAR_VALIDATE_PARAMS=t.CLEAR_REQUEST=t.CLEAR_RESPONSE=t.LOG_REQUEST=t.SET_REQUEST=t.SET_RESPONSE=t.VALIDATE_PARAMS=t.UPDATE_PARAM=t.UPDATE_JSON=t.UPDATE_URL=t.UPDATE_SPEC=void 0;var v=Object.assign||function(e){for(var t=1;t0){var i=n.map(function(e){return console.error(e),e.line=e.fullPath?d(m,e.fullPath):null,e.path=e.fullPath?e.fullPath.join("."):null,e.level="error",e.type="thrown",e.source="resolver",Object.defineProperty(e,"message",{enumerable:!0,value:e.message}),e});o.newThrownErrBatch(i)}return r.updateResolved(t)})}},t.formatIntoYaml=function(){return function(e){var t=e.specActions,n=e.specSelectors,r=n.specStr,i=t.updateSpec;try{var o=b.default.safeDump(b.default.safeLoad(r()),{indent:2});i(o)}catch(e){i(e)}}},t.setResponse=function(e,t,n){return{payload:{path:e,method:t,res:n},type:D}},t.setRequest=function(e,t,n){return{payload:{path:e,method:t,req:n},type:M}},t.logRequest=function(e){return{payload:e,type:P}},t.executeRequest=function(e){return function(t){var n=t.fn,r=t.specActions,i=t.specSelectors,o=e.pathName,a=e.method,s=e.operation,u=s.toJS();e.contextUrl=(0,w.default)(i.url()).toString(),u&&u.operationId?e.operationId=u.operationId:u&&o&&a&&(e.operationId=n.opId(u,o,a));var c=Object.assign({},e);return c=n.buildRequest(c),r.setRequest(e.pathName,e.method,c),n.execute(e).then(function(t){return r.setResponse(e.pathName,e.method,t)}).catch(function(t){return r.setResponse(e.pathName,e.method,{error:!0,err:(0,S.default)(t)})})}},function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.path,n=e.method,r=i(e,["path","method"]);return function(e){var i=e.fn.fetch,o=e.specSelectors,a=e.specActions,s=o.spec().toJS(),u=o.operationScheme(t,n),c=o.contentTypeValues([t,n]).toJS(),l=c.requestContentType,p=c.responseContentType,f=/xml/i.test(l),h=o.parameterValues([t,n],f).toJS();return a.executeRequest(v({fetch:i,spec:s,pathName:t,method:n,parameters:h,requestContentType:l,scheme:u,responseContentType:p},r))}});t.execute=L},function(e,t,n){"use strict";var r=n(584);e.exports=r},function(e,t,n){"use strict";function r(e){return function(){throw new Error("Function "+e+" is deprecated and cannot be used.")}}var i=n(585),o=n(613);e.exports.Type=n(591),e.exports.Schema=n(590),e.exports.FAILSAFE_SCHEMA=n(594),e.exports.JSON_SCHEMA=n(593),e.exports.CORE_SCHEMA=n(592),e.exports.DEFAULT_SAFE_SCHEMA=n(589),e.exports.DEFAULT_FULL_SCHEMA=n(608),e.exports.load=i.load,e.exports.loadAll=i.loadAll,e.exports.safeLoad=i.safeLoad,e.exports.safeLoadAll=i.safeLoadAll,e.exports.dump=o.dump,e.exports.safeDump=o.safeDump,e.exports.YAMLException=n(587),e.exports.MINIMAL_SCHEMA=n(594),e.exports.SAFE_SCHEMA=n(589),e.exports.DEFAULT_SCHEMA=n(608),e.exports.scan=r("scan"),e.exports.parse=r("parse"),e.exports.compose=r("compose"),e.exports.addConstructor=r("addConstructor")},function(e,t,n){"use strict";function r(e){return 10===e||13===e}function i(e){return 9===e||32===e}function o(e){return 9===e||32===e||10===e||13===e}function a(e){return 44===e||91===e||93===e||123===e||125===e}function s(e){var t;return 48<=e&&e<=57?e-48:(t=32|e,97<=t&&t<=102?t-97+10:-1)}function u(e){return 120===e?2:117===e?4:85===e?8:0}function c(e){return 48<=e&&e<=57?e-48:-1}function l(e){return 48===e?"\0":97===e?"":98===e?"\b":116===e?"\t":9===e?"\t":110===e?"\n":118===e?"\v":102===e?"\f":114===e?"\r":101===e?"":32===e?" ":34===e?'"':47===e?"/":92===e?"\\":78===e?"…":95===e?" ":76===e?"\u2028":80===e?"\u2029":""}function p(e){return e<=65535?String.fromCharCode(e):String.fromCharCode((e-65536>>10)+55296,(e-65536&1023)+56320)}function f(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||K,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.documents=[]}function h(e,t){return new q(t,new U(e.filename,e.input,e.position,e.line,e.position-e.lineStart))}function d(e,t){throw h(e,t)}function m(e,t){e.onWarning&&e.onWarning.call(null,h(e,t))}function y(e,t,n,r){var i,o,a,s;if(t1&&(e.result+=z.repeat("\n",t-1))}function k(e,t,n){var s,u,c,l,p,f,h,d,m,v=e.kind,g=e.result;if(m=e.input.charCodeAt(e.position),o(m)||a(m)||35===m||38===m||42===m||33===m||124===m||62===m||39===m||34===m||37===m||64===m||96===m)return!1;if((63===m||45===m)&&(u=e.input.charCodeAt(e.position+1),o(u)||n&&a(u)))return!1;for(e.kind="scalar",e.result="",c=l=e.position,p=!1;0!==m;){if(58===m){if(u=e.input.charCodeAt(e.position+1),o(u)||n&&a(u))break}else if(35===m){if(s=e.input.charCodeAt(e.position-1),o(s))break}else{if(e.position===e.lineStart&&x(e)||n&&a(m))break;if(r(m)){if(f=e.line,h=e.lineStart,d=e.lineIndent,b(e,!1,-1),e.lineIndent>=t){p=!0,m=e.input.charCodeAt(e.position);continue}e.position=l,e.line=f,e.lineStart=h,e.lineIndent=d;break}}p&&(y(e,c,l,!1),w(e,e.line-f),c=l=e.position,p=!1),i(m)||(l=e.position+1),m=e.input.charCodeAt(++e.position)}return y(e,c,l,!1),!!e.result||(e.kind=v,e.result=g,!1)}function S(e,t){var n,i,o;if(n=e.input.charCodeAt(e.position),39!==n)return!1;for(e.kind="scalar",e.result="",e.position++,i=o=e.position;0!==(n=e.input.charCodeAt(e.position));)if(39===n){if(y(e,i,e.position,!0),n=e.input.charCodeAt(++e.position),39!==n)return!0;i=e.position,e.position++,o=e.position}else r(n)?(y(e,i,o,!0),w(e,b(e,!1,t)),i=o=e.position):e.position===e.lineStart&&x(e)?d(e,"unexpected end of the document within a single quoted scalar"):(e.position++,o=e.position);d(e,"unexpected end of the stream within a single quoted scalar")}function E(e,t){var n,i,o,a,c,l;if(l=e.input.charCodeAt(e.position),34!==l)return!1;for(e.kind="scalar",e.result="",e.position++,n=i=e.position;0!==(l=e.input.charCodeAt(e.position));){if(34===l)return y(e,n,e.position,!0),e.position++,!0;if(92===l){if(y(e,n,e.position,!0),l=e.input.charCodeAt(++e.position),r(l))b(e,!1,t);else if(l<256&&ie[l])e.result+=oe[l],e.position++;else if((c=u(l))>0){for(o=c,a=0;o>0;o--)l=e.input.charCodeAt(++e.position),(c=s(l))>=0?a=(a<<4)+c:d(e,"expected hexadecimal character");e.result+=p(a),e.position++}else d(e,"unknown escape sequence");n=i=e.position}else r(l)?(y(e,n,i,!0),w(e,b(e,!1,t)),n=i=e.position):e.position===e.lineStart&&x(e)?d(e,"unexpected end of the document within a double quoted scalar"):(e.position++,i=e.position)}d(e,"unexpected end of the stream within a double quoted scalar")}function C(e,t){var n,r,i,a,s,u,c,l,p,f,h,m=!0,y=e.tag,v=e.anchor,_={};if(h=e.input.charCodeAt(e.position),91===h)a=93,c=!1,r=[];else{if(123!==h)return!1;a=125,c=!0,r={}}for(null!==e.anchor&&(e.anchorMap[e.anchor]=r),h=e.input.charCodeAt(++e.position);0!==h;){if(b(e,!0,t),h=e.input.charCodeAt(e.position),h===a)return e.position++,e.tag=y,e.anchor=v,e.kind=c?"mapping":"sequence",e.result=r,!0;m||d(e,"missed comma between flow collection entries"),p=l=f=null,s=u=!1,63===h&&(i=e.input.charCodeAt(e.position+1),o(i)&&(s=u=!0,e.position++,b(e,!0,t))),n=e.line,I(e,t,H,!1,!0),p=e.tag,l=e.result,b(e,!0,t),h=e.input.charCodeAt(e.position),!u&&e.line!==n||58!==h||(s=!0,h=e.input.charCodeAt(++e.position),b(e,!0,t),I(e,t,H,!1,!0),f=e.result),c?g(e,r,_,p,l,f):s?r.push(g(e,null,_,p,l,f)):r.push(l),b(e,!0,t),h=e.input.charCodeAt(e.position),44===h?(m=!0,h=e.input.charCodeAt(++e.position)):m=!1}d(e,"unexpected end of the stream within a flow collection")}function A(e,t){var n,o,a,s,u=Y,l=!1,p=!1,f=t,h=0,m=!1;if(s=e.input.charCodeAt(e.position),124===s)o=!1;else{if(62!==s)return!1;o=!0}for(e.kind="scalar",e.result="";0!==s;)if(s=e.input.charCodeAt(++e.position),43===s||45===s)Y===u?u=43===s?Z:$:d(e,"repeat of a chomping mode identifier");else{if(!((a=c(s))>=0))break;0===a?d(e,"bad explicit indentation width of a block scalar; it cannot be less than one"):p?d(e,"repeat of an indentation width identifier"):(f=t+a-1,p=!0)}if(i(s)){do s=e.input.charCodeAt(++e.position);while(i(s));if(35===s)do s=e.input.charCodeAt(++e.position);while(!r(s)&&0!==s)}for(;0!==s;){for(_(e),e.lineIndent=0,s=e.input.charCodeAt(e.position);(!p||e.lineIndentf&&(f=e.lineIndent),r(s))h++;else{if(e.lineIndentt)&&0!==i)d(e,"bad indentation of a sequence entry");else if(e.lineIndentt)&&(I(e,t,X,!0,a)&&(_?y=e.result:v=e.result),_||(g(e,f,h,m,y,v,s,u),m=y=v=null),b(e,!0,-1),c=e.input.charCodeAt(e.position)),e.lineIndent>t&&0!==c)d(e,"bad indentation of a mapping entry");else if(e.lineIndentt?h=1:e.lineIndent===t?h=0:e.lineIndentt?h=1:e.lineIndent===t?h=0:e.lineIndent tag; it should be "'+l.kind+'", not "'+e.kind+'"'),l.resolve(e.result)?(e.result=l.construct(e.result),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):d(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):d(e,"unknown tag !<"+e.tag+">");return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||y}function j(e){var t,n,a,s,u=e.position,c=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap={},e.anchorMap={};0!==(s=e.input.charCodeAt(e.position))&&(b(e,!0,-1),s=e.input.charCodeAt(e.position),!(e.lineIndent>0||37!==s));){for(c=!0,s=e.input.charCodeAt(++e.position),t=e.position;0!==s&&!o(s);)s=e.input.charCodeAt(++e.position);for(n=e.input.slice(t,e.position),a=[],n.length<1&&d(e,"directive name must not be less than one character in length");0!==s;){for(;i(s);)s=e.input.charCodeAt(++e.position);if(35===s){do s=e.input.charCodeAt(++e.position);while(0!==s&&!r(s));break}if(r(s))break;for(t=e.position;0!==s&&!o(s);)s=e.input.charCodeAt(++e.position);a.push(e.input.slice(t,e.position))}0!==s&&_(e),V.call(se,n)?se[n](e,n,a):m(e,'unknown document directive "'+n+'"')}return b(e,!0,-1),0===e.lineIndent&&45===e.input.charCodeAt(e.position)&&45===e.input.charCodeAt(e.position+1)&&45===e.input.charCodeAt(e.position+2)?(e.position+=3,b(e,!0,-1)):c&&d(e,"directives end mark is expected"),I(e,e.lineIndent-1,X,!1,!0),b(e,!0,-1),e.checkLineBreaks&&ee.test(e.input.slice(u,e.position))&&m(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&x(e)?void(46===e.input.charCodeAt(e.position)&&(e.position+=3,b(e,!0,-1))):void(e.position0&&"\0\r\n…\u2028\u2029".indexOf(this.buffer.charAt(r-1))===-1;)if(r-=1,this.position-r>t/2-1){n=" ... ",r+=5;break}for(o="",a=this.position;at/2-1){o=" ... ",a-=5;break}return s=this.buffer.slice(r,a),i.repeat(" ",e)+n+s+o+"\n"+i.repeat(" ",e+this.position-r+n.length)+"^"},r.prototype.toString=function(e){var t,n="";return this.name&&(n+='in "'+this.name+'" '),n+="at line "+(this.line+1)+", column "+(this.column+1),e||(t=this.getSnippet(),t&&(n+=":\n"+t)),n},e.exports=r},function(e,t,n){"use strict";var r=n(590);e.exports=new r({include:[n(592)],implicit:[n(602),n(603)],explicit:[n(604),n(605),n(606),n(607)]})},function(e,t,n){"use strict";function r(e,t,n){var i=[];return e.include.forEach(function(e){n=r(e,t,n)}),e[t].forEach(function(e){n.forEach(function(t,n){t.tag===e.tag&&t.kind===e.kind&&i.push(n)}),n.push(e)}),n.filter(function(e,t){return i.indexOf(t)===-1})}function i(){function e(e){r[e.kind][e.tag]=r.fallback[e.tag]=e}var t,n,r={scalar:{},sequence:{},mapping:{},fallback:{}};for(t=0,n=arguments.length;t=0&&(t=t.slice(1)),".inf"===t?1===n?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===t?NaN:t.indexOf(":")>=0?(t.split(":").forEach(function(e){i.unshift(parseFloat(e,10))}),t=0,r=1,i.forEach(function(e){t+=e*r,r*=60}),n*t):n*parseFloat(t,10)}function o(e,t){var n;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(s.isNegativeZero(e))return"-0.0";return n=e.toString(10),l.test(n)?n.replace("e",".e"):n}function a(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!==0||s.isNegativeZero(e))}var s=n(586),u=n(591),c=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),l=/^[-+]?[0-9]+e/;e.exports=new u("tag:yaml.org,2002:float",{kind:"scalar",resolve:r,construct:i,predicate:a,represent:o,defaultStyle:"lowercase"})},function(e,t,n){"use strict";function r(e){return null!==e&&(null!==s.exec(e)||null!==u.exec(e))}function i(e){var t,n,r,i,o,a,c,l,p,f,h=0,d=null;if(t=s.exec(e),null===t&&(t=u.exec(e)),null===t)throw new Error("Date resolve error");if(n=+t[1],r=+t[2]-1,i=+t[3],!t[4])return new Date(Date.UTC(n,r,i));if(o=+t[4],a=+t[5],c=+t[6],t[7]){for(h=t[7].slice(0,3);h.length<3;)h+="0";h=+h}return t[9]&&(l=+t[10],p=+(t[11]||0),d=6e4*(60*l+p),"-"===t[9]&&(d=-d)),f=new Date(Date.UTC(n,r,i,o,a,c,h)),d&&f.setTime(f.getTime()-d),f}function o(e){return e.toISOString()}var a=n(591),s=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),u=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");e.exports=new a("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:r,construct:i,instanceOf:Date,represent:o})},function(e,t,n){"use strict";function r(e){return"<<"===e||null===e}var i=n(591);e.exports=new i("tag:yaml.org,2002:merge",{kind:"scalar",resolve:r})},function(e,t,n){function r(e){if(null===e)return!1;var t,n,r=0,i=e.length,o=c;for(n=0;n64)){if(t<0)return!1;r+=6}return r%8===0}function i(e){var t,n,r=e.replace(/[\r\n=]/g,""),i=r.length,o=c,a=0,u=[];for(t=0;t>16&255),u.push(a>>8&255),u.push(255&a)),a=a<<6|o.indexOf(r.charAt(t));return n=i%4*6,0===n?(u.push(a>>16&255),u.push(a>>8&255),u.push(255&a)):18===n?(u.push(a>>10&255),u.push(a>>2&255)):12===n&&u.push(a>>4&255),s?s.from?s.from(u):new s(u):u}function o(e){var t,n,r="",i=0,o=e.length,a=c;for(t=0;t>18&63],r+=a[i>>12&63],r+=a[i>>6&63],r+=a[63&i]),i=(i<<8)+e[t];return n=o%3,0===n?(r+=a[i>>18&63],r+=a[i>>12&63],r+=a[i>>6&63],r+=a[63&i]):2===n?(r+=a[i>>10&63],r+=a[i>>4&63],r+=a[i<<2&63],r+=a[64]):1===n&&(r+=a[i>>2&63],r+=a[i<<4&63],r+=a[64],r+=a[64]),r}function a(e){return s&&s.isBuffer(e)}var s;try{s=n(299).Buffer}catch(e){}var u=n(591),c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";e.exports=new u("tag:yaml.org,2002:binary",{kind:"scalar",resolve:r,construct:i,predicate:a,represent:o})},function(e,t,n){"use strict";function r(e){if(null===e)return!0;var t,n,r,i,o,u=[],c=e;for(t=0,n=c.length;t3)return!1;if("/"!==t[t.length-r.length-1])return!1}return!0}function i(e){var t=e,n=/\/([gim]*)$/.exec(e),r="";return"/"===t[0]&&(n&&(r=n[1]),t=t.slice(1,t.length-r.length-1)),new RegExp(t,r)}function o(e){var t="/"+e.source+"/";return e.global&&(t+="g"),e.multiline&&(t+="m"),e.ignoreCase&&(t+="i"),t}function a(e){return"[object RegExp]"===Object.prototype.toString.call(e)}var s=n(591);e.exports=new s("tag:yaml.org,2002:js/regexp",{kind:"scalar",resolve:r,construct:i,predicate:a,represent:o})},function(e,t,n){function r(e){if(null===e)return!1;try{var t="("+e+")",n=s.parse(t,{range:!0});return"Program"===n.type&&1===n.body.length&&"ExpressionStatement"===n.body[0].type&&"FunctionExpression"===n.body[0].expression.type}catch(e){return!1}}function i(e){var t,n="("+e+")",r=s.parse(n,{range:!0}),i=[];if("Program"!==r.type||1!==r.body.length||"ExpressionStatement"!==r.body[0].type||"FunctionExpression"!==r.body[0].expression.type)throw new Error("Failed to resolve function");return r.body[0].expression.params.forEach(function(e){i.push(e.name)}),t=r.body[0].expression.body.range,new Function(i,n.slice(t[0]+1,t[1]-1))}function o(e){return e.toString()}function a(e){return"[object Function]"===Object.prototype.toString.call(e)}var s;try{s=n(612)}catch(e){"undefined"!=typeof window&&(s=window.esprima)}var u=n(591);e.exports=new u("tag:yaml.org,2002:js/function",{kind:"scalar",resolve:r,construct:i,predicate:a,represent:o})},function(e,t,n){!function(t,n){e.exports=n()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return e[r].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function r(e,t,n){var r=null,i=function(e,t){n&&n(e,t),r&&r.visit(e,t)},u="function"==typeof n?i:null,c=!1;if(t){c="boolean"==typeof t.comment&&t.comment;var l="boolean"==typeof t.attachComment&&t.attachComment;(c||l)&&(r=new o.CommentHandler,r.attach=l,t.comment=!0,u=i)}var p;p=t&&"boolean"==typeof t.jsx&&t.jsx?new s.JSXParser(e,t,u):new a.Parser(e,t,u);var f=p.parseProgram();return c&&(f.comments=r.comments),p.config.tokens&&(f.tokens=p.tokens),p.config.tolerant&&(f.errors=p.errorHandler.errors),f}function i(e,t,n){var r,i=new u.Tokenizer(e,t);r=[];try{for(;;){var o=i.getNextToken();if(!o)break;n&&(o=n(o)),r.push(o)}}catch(e){i.errorHandler.tolerate(e)}return i.errorHandler.tolerant&&(r.errors=i.errors()),r}var o=n(1),a=n(3),s=n(11),u=n(15);t.parse=r,t.tokenize=i;var c=n(2);t.Syntax=c.Syntax,t.version="3.1.3"},function(e,t,n){"use strict";var r=n(2),i=function(){function e(){this.attach=!1,this.comments=[],this.stack=[],this.leading=[],this.trailing=[]}return e.prototype.insertInnerComments=function(e,t){if(e.type===r.Syntax.BlockStatement&&0===e.body.length){for(var n=[],i=this.leading.length-1;i>=0;--i){var o=this.leading[i];t.end.offset>=o.start&&(n.unshift(o.comment),this.leading.splice(i,1),this.trailing.splice(i,1))}n.length&&(e.innerComments=n)}},e.prototype.findTrailingComments=function(e,t){var n=[];if(this.trailing.length>0){for(var r=this.trailing.length-1;r>=0;--r){var i=this.trailing[r];i.start>=t.end.offset&&n.unshift(i.comment)}return this.trailing.length=0,n}var o=this.stack[this.stack.length-1];if(o&&o.node.trailingComments){var a=o.node.trailingComments[0];a&&a.range[0]>=t.end.offset&&(n=o.node.trailingComments,delete o.node.trailingComments)}return n},e.prototype.findLeadingComments=function(e,t){for(var n,r=[];this.stack.length>0;){var i=this.stack[this.stack.length-1];if(!(i&&i.start>=t.start.offset))break;n=this.stack.pop().node}if(n){for(var o=n.leadingComments?n.leadingComments.length:0,a=o-1;a>=0;--a){var s=n.leadingComments[a];s.range[1]<=t.start.offset&&(r.unshift(s),n.leadingComments.splice(a,1))}return n.leadingComments&&0===n.leadingComments.length&&delete n.leadingComments,r}for(var a=this.leading.length-1;a>=0;--a){var i=this.leading[a];i.start<=t.start.offset&&(r.unshift(i.comment),this.leading.splice(a,1))}return r},e.prototype.visitNode=function(e,t){if(!(e.type===r.Syntax.Program&&e.body.length>0)){this.insertInnerComments(e,t);var n=this.findTrailingComments(e,t),i=this.findLeadingComments(e,t);i.length>0&&(e.leadingComments=i),n.length>0&&(e.trailingComments=n),this.stack.push({node:e,start:t.start.offset})}},e.prototype.visitComment=function(e,t){var n="L"===e.type[0]?"Line":"Block",r={type:n,value:e.value};if(e.range&&(r.range=e.range),e.loc&&(r.loc=e.loc),this.comments.push(r),this.attach){var i={comment:{type:n,value:e.value,range:[t.start.offset,t.end.offset]},start:t.start.offset};e.loc&&(i.comment.loc=e.loc),e.type=n,this.leading.push(i),this.trailing.push(i)}},e.prototype.visit=function(e,t){"LineComment"===e.type?this.visitComment(e,t):"BlockComment"===e.type?this.visitComment(e,t):this.attach&&this.visitNode(e,t)},e}();t.CommentHandler=i},function(e,t){"use strict";t.Syntax={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DoWhileStatement:"DoWhileStatement",DebuggerStatement:"DebuggerStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForOfStatement:"ForOfStatement",ForInStatement:"ForInStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchCase:"SwitchCase",SwitchStatement:"SwitchStatement",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"}},function(e,t,n){"use strict";var r=n(4),i=n(5),o=n(6),a=n(7),s=n(8),u=n(2),c=n(10),l="ArrowParameterPlaceHolder",p=function(){function e(e,t,n){void 0===t&&(t={}),this.config={range:"boolean"==typeof t.range&&t.range,loc:"boolean"==typeof t.loc&&t.loc,source:null,tokens:"boolean"==typeof t.tokens&&t.tokens,comment:"boolean"==typeof t.comment&&t.comment,tolerant:"boolean"==typeof t.tolerant&&t.tolerant},this.config.loc&&t.source&&null!==t.source&&(this.config.source=String(t.source)),this.delegate=n,this.errorHandler=new o.ErrorHandler,this.errorHandler.tolerant=this.config.tolerant,this.scanner=new s.Scanner(e,this.errorHandler),this.scanner.trackComment=this.config.comment,this.operatorPrecedence={")":0,";":0,",":0,"=":0,"]":0,"||":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":11,"/":11,"%":11},this.sourceType=t&&"module"===t.sourceType?"module":"script",this.lookahead=null,this.hasLineTerminator=!1,this.context={allowIn:!0,allowYield:!0,firstCoverInitializedNameError:null,isAssignmentTarget:!1,isBindingElement:!1,inFunctionBody:!1,inIteration:!1,inSwitch:!1,labelSet:{},strict:"module"===this.sourceType},this.tokens=[],this.startMarker={index:0,lineNumber:this.scanner.lineNumber,lineStart:0},this.lastMarker={index:0,lineNumber:this.scanner.lineNumber,lineStart:0},this.nextToken(),this.lastMarker={index:this.scanner.index,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart}}return e.prototype.throwError=function(e){for(var t=[],n=1;n0&&this.delegate)for(var t=0;t>="===e||">>>="===e||"&="===e||"^="===e||"|="===e},e.prototype.isolateCoverGrammar=function(e){var t=this.context.isBindingElement,n=this.context.isAssignmentTarget,r=this.context.firstCoverInitializedNameError;this.context.isBindingElement=!0,this.context.isAssignmentTarget=!0,this.context.firstCoverInitializedNameError=null;var i=e.call(this);return null!==this.context.firstCoverInitializedNameError&&this.throwUnexpectedToken(this.context.firstCoverInitializedNameError),this.context.isBindingElement=t,this.context.isAssignmentTarget=n,this.context.firstCoverInitializedNameError=r,i},e.prototype.inheritCoverGrammar=function(e){var t=this.context.isBindingElement,n=this.context.isAssignmentTarget,r=this.context.firstCoverInitializedNameError;this.context.isBindingElement=!0,this.context.isAssignmentTarget=!0,this.context.firstCoverInitializedNameError=null;var i=e.call(this);return this.context.isBindingElement=this.context.isBindingElement&&t,this.context.isAssignmentTarget=this.context.isAssignmentTarget&&n,this.context.firstCoverInitializedNameError=r||this.context.firstCoverInitializedNameError,i},e.prototype.consumeSemicolon=function(){this.match(";")?this.nextToken():this.hasLineTerminator||(this.lookahead.type===a.Token.EOF||this.match("}")||this.throwUnexpectedToken(this.lookahead),this.lastMarker.index=this.startMarker.index,this.lastMarker.lineNumber=this.startMarker.lineNumber,this.lastMarker.lineStart=this.startMarker.lineStart)},e.prototype.parsePrimaryExpression=function(){var e,t,n,r,o=this.createNode();switch(this.lookahead.type){case a.Token.Identifier:"module"===this.sourceType&&"await"===this.lookahead.value&&this.tolerateUnexpectedToken(this.lookahead),e=this.finalize(o,new c.Identifier(this.nextToken().value));break;case a.Token.NumericLiteral:case a.Token.StringLiteral:this.context.strict&&this.lookahead.octal&&this.tolerateUnexpectedToken(this.lookahead,i.Messages.StrictOctalLiteral),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,n=this.nextToken(),r=this.getTokenRaw(n),e=this.finalize(o,new c.Literal(n.value,r));break;case a.Token.BooleanLiteral:this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,n=this.nextToken(),n.value="true"===n.value,r=this.getTokenRaw(n),e=this.finalize(o,new c.Literal(n.value,r));break;case a.Token.NullLiteral:this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,n=this.nextToken(),n.value=null,r=this.getTokenRaw(n),e=this.finalize(o,new c.Literal(n.value,r));break;case a.Token.Template:e=this.parseTemplateLiteral();break;case a.Token.Punctuator:switch(t=this.lookahead.value){case"(":this.context.isBindingElement=!1,e=this.inheritCoverGrammar(this.parseGroupExpression);break;case"[":e=this.inheritCoverGrammar(this.parseArrayInitializer);break;case"{":e=this.inheritCoverGrammar(this.parseObjectInitializer);break;case"/":case"/=":this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.scanner.index=this.startMarker.index,n=this.nextRegexToken(),r=this.getTokenRaw(n),e=this.finalize(o,new c.RegexLiteral(n.value,r,n.regex));break;default:this.throwUnexpectedToken(this.nextToken())}break;case a.Token.Keyword:!this.context.strict&&this.context.allowYield&&this.matchKeyword("yield")?e=this.parseIdentifierName():!this.context.strict&&this.matchKeyword("let")?e=this.finalize(o,new c.Identifier(this.nextToken().value)):(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.matchKeyword("function")?e=this.parseFunctionExpression():this.matchKeyword("this")?(this.nextToken(),e=this.finalize(o,new c.ThisExpression)):this.matchKeyword("class")?e=this.parseClassExpression():this.throwUnexpectedToken(this.nextToken()));break;default:this.throwUnexpectedToken(this.nextToken())}return e},e.prototype.parseSpreadElement=function(){var e=this.createNode();this.expect("...");var t=this.inheritCoverGrammar(this.parseAssignmentExpression);return this.finalize(e,new c.SpreadElement(t))},e.prototype.parseArrayInitializer=function(){var e=this.createNode(),t=[];for(this.expect("[");!this.match("]");)if(this.match(","))this.nextToken(),t.push(null);else if(this.match("...")){var n=this.parseSpreadElement();this.match("]")||(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.expect(",")),t.push(n)}else t.push(this.inheritCoverGrammar(this.parseAssignmentExpression)),this.match("]")||this.expect(",");return this.expect("]"),this.finalize(e,new c.ArrayExpression(t))},e.prototype.parsePropertyMethod=function(e){this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var t=this.context.strict,n=this.isolateCoverGrammar(this.parseFunctionSourceElements);return this.context.strict&&e.firstRestricted&&this.tolerateUnexpectedToken(e.firstRestricted,e.message),this.context.strict&&e.stricted&&this.tolerateUnexpectedToken(e.stricted,e.message),this.context.strict=t,n},e.prototype.parsePropertyMethodFunction=function(){var e=!1,t=this.createNode(),n=this.context.allowYield;this.context.allowYield=!1;var r=this.parseFormalParameters(),i=this.parsePropertyMethod(r);return this.context.allowYield=n,this.finalize(t,new c.FunctionExpression(null,r.params,i,e))},e.prototype.parseObjectPropertyKey=function(){var e=this.createNode(),t=this.nextToken(),n=null;switch(t.type){case a.Token.StringLiteral:case a.Token.NumericLiteral:this.context.strict&&t.octal&&this.tolerateUnexpectedToken(t,i.Messages.StrictOctalLiteral);var r=this.getTokenRaw(t);n=this.finalize(e,new c.Literal(t.value,r));break;case a.Token.Identifier:case a.Token.BooleanLiteral:case a.Token.NullLiteral:case a.Token.Keyword:n=this.finalize(e,new c.Identifier(t.value));break;case a.Token.Punctuator:"["===t.value?(n=this.isolateCoverGrammar(this.parseAssignmentExpression),this.expect("]")):this.throwUnexpectedToken(t);break;default:this.throwUnexpectedToken(t)}return n},e.prototype.isPropertyKey=function(e,t){return e.type===u.Syntax.Identifier&&e.name===t||e.type===u.Syntax.Literal&&e.value===t},e.prototype.parseObjectProperty=function(e){var t,n,r,o=this.createNode(),s=this.lookahead,u=!1,l=!1,p=!1;s.type===a.Token.Identifier?(this.nextToken(),n=this.finalize(o,new c.Identifier(s.value))):this.match("*")?this.nextToken():(u=this.match("["),n=this.parseObjectPropertyKey());var f=this.qualifiedPropertyName(this.lookahead);if(s.type===a.Token.Identifier&&"get"===s.value&&f)t="get",u=this.match("["),n=this.parseObjectPropertyKey(),this.context.allowYield=!1,r=this.parseGetterMethod();else if(s.type===a.Token.Identifier&&"set"===s.value&&f)t="set",u=this.match("["),n=this.parseObjectPropertyKey(),r=this.parseSetterMethod();else if(s.type===a.Token.Punctuator&&"*"===s.value&&f)t="init",u=this.match("["),n=this.parseObjectPropertyKey(),r=this.parseGeneratorMethod(),l=!0;else if(n||this.throwUnexpectedToken(this.lookahead),t="init",this.match(":"))!u&&this.isPropertyKey(n,"__proto__")&&(e.value&&this.tolerateError(i.Messages.DuplicateProtoProperty),e.value=!0),this.nextToken(),r=this.inheritCoverGrammar(this.parseAssignmentExpression);else if(this.match("("))r=this.parsePropertyMethodFunction(),l=!0;else if(s.type===a.Token.Identifier){var h=this.finalize(o,new c.Identifier(s.value));if(this.match("=")){this.context.firstCoverInitializedNameError=this.lookahead,this.nextToken(),p=!0;var d=this.isolateCoverGrammar(this.parseAssignmentExpression);r=this.finalize(o,new c.AssignmentPattern(h,d))}else p=!0,r=h}else this.throwUnexpectedToken(this.nextToken());return this.finalize(o,new c.Property(t,n,u,r,l,p))},e.prototype.parseObjectInitializer=function(){var e=this.createNode();this.expect("{");for(var t=[],n={value:!1};!this.match("}");)t.push(this.parseObjectProperty(n)),this.match("}")||this.expectCommaSeparator();return this.expect("}"),this.finalize(e,new c.ObjectExpression(t))},e.prototype.parseTemplateHead=function(){r.assert(this.lookahead.head,"Template literal must start with a template head");var e=this.createNode(),t=this.nextToken(),n={raw:t.value.raw,cooked:t.value.cooked};return this.finalize(e,new c.TemplateElement(n,t.tail))},e.prototype.parseTemplateElement=function(){this.lookahead.type!==a.Token.Template&&this.throwUnexpectedToken();var e=this.createNode(),t=this.nextToken(),n={raw:t.value.raw,cooked:t.value.cooked};return this.finalize(e,new c.TemplateElement(n,t.tail))},e.prototype.parseTemplateLiteral=function(){var e=this.createNode(),t=[],n=[],r=this.parseTemplateHead();for(n.push(r);!r.tail;)t.push(this.parseExpression()),r=this.parseTemplateElement(),n.push(r);return this.finalize(e,new c.TemplateLiteral(n,t))},e.prototype.reinterpretExpressionAsPattern=function(e){switch(e.type){case u.Syntax.Identifier:case u.Syntax.MemberExpression:case u.Syntax.RestElement:case u.Syntax.AssignmentPattern:break;case u.Syntax.SpreadElement:e.type=u.Syntax.RestElement,this.reinterpretExpressionAsPattern(e.argument);break;case u.Syntax.ArrayExpression:e.type=u.Syntax.ArrayPattern;for(var t=0;t")||this.expect("=>"),e={type:l,params:[]};else{var t=this.lookahead,n=[];if(this.match("..."))e=this.parseRestElement(n),this.expect(")"),this.match("=>")||this.expect("=>"),e={type:l,params:[e]};else{var r=!1;if(this.context.isBindingElement=!0,e=this.inheritCoverGrammar(this.parseAssignmentExpression),this.match(",")){var i=[];for(this.context.isAssignmentTarget=!1,i.push(e);this.startMarker.index")||this.expect("=>"),this.context.isBindingElement=!1;for(var o=0;o")&&(e.type===u.Syntax.Identifier&&"yield"===e.name&&(r=!0,e={type:l,params:[e]}),!r)){if(this.context.isBindingElement||this.throwUnexpectedToken(this.lookahead),e.type===u.Syntax.SequenceExpression)for(var o=0;o0){this.nextToken(),n.prec=r,this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;for(var i=[e,this.lookahead],o=t,a=this.isolateCoverGrammar(this.parseExponentiationExpression),s=[o,n,a];;){if(r=this.binaryPrecedence(this.lookahead),r<=0)break;for(;s.length>2&&r<=s[s.length-2].prec;){a=s.pop();var u=s.pop().value;o=s.pop(),i.pop();var l=this.startNode(i[i.length-1]);s.push(this.finalize(l,new c.BinaryExpression(u,o,a)))}n=this.nextToken(),n.prec=r,s.push(n),i.push(this.lookahead),s.push(this.isolateCoverGrammar(this.parseExponentiationExpression))}var p=s.length-1;for(t=s[p],i.pop();p>1;){var l=this.startNode(i.pop());t=this.finalize(l,new c.BinaryExpression(s[p-1].value,s[p-2],t)),p-=2}}return t},e.prototype.parseConditionalExpression=function(){var e=this.lookahead,t=this.inheritCoverGrammar(this.parseBinaryExpression);if(this.match("?")){this.nextToken();var n=this.context.allowIn;this.context.allowIn=!0;var r=this.isolateCoverGrammar(this.parseAssignmentExpression);this.context.allowIn=n,this.expect(":");var i=this.isolateCoverGrammar(this.parseAssignmentExpression);t=this.finalize(this.startNode(e),new c.ConditionalExpression(t,r,i)),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1}return t},e.prototype.checkPatternParam=function(e,t){switch(t.type){case u.Syntax.Identifier:this.validateParam(e,t,t.name);break;case u.Syntax.RestElement:this.checkPatternParam(e,t.argument);break;case u.Syntax.AssignmentPattern:this.checkPatternParam(e,t.left);break;case u.Syntax.ArrayPattern:for(var n=0;n")){this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var r=this.reinterpretAsCoverFormalsList(e);if(r){this.hasLineTerminator&&this.tolerateUnexpectedToken(this.lookahead),this.context.firstCoverInitializedNameError=null;var o=this.context.strict,a=this.context.allowYield;this.context.allowYield=!0;var s=this.startNode(t);this.expect("=>");var p=this.match("{")?this.parseFunctionSourceElements():this.isolateCoverGrammar(this.parseAssignmentExpression),f=p.type!==u.Syntax.BlockStatement;this.context.strict&&r.firstRestricted&&this.throwUnexpectedToken(r.firstRestricted,r.message),this.context.strict&&r.stricted&&this.tolerateUnexpectedToken(r.stricted,r.message),e=this.finalize(s,new c.ArrowFunctionExpression(r.params,p,f)),this.context.strict=o,this.context.allowYield=a}}else if(this.matchAssign()){if(this.context.isAssignmentTarget||this.tolerateError(i.Messages.InvalidLHSInAssignment),this.context.strict&&e.type===u.Syntax.Identifier){var h=e;this.scanner.isRestrictedWord(h.name)&&this.tolerateUnexpectedToken(n,i.Messages.StrictLHSAssignment),this.scanner.isStrictModeReservedWord(h.name)&&this.tolerateUnexpectedToken(n,i.Messages.StrictReservedWord)}this.match("=")?this.reinterpretExpressionAsPattern(e):(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1),n=this.nextToken();var d=this.isolateCoverGrammar(this.parseAssignmentExpression);e=this.finalize(this.startNode(t),new c.AssignmentExpression(n.value,e,d)),this.context.firstCoverInitializedNameError=null}}return e},e.prototype.parseExpression=function(){var e=this.lookahead,t=this.isolateCoverGrammar(this.parseAssignmentExpression);if(this.match(",")){var n=[];for(n.push(t);this.startMarker.index",t.TokenName[n.Identifier]="Identifier",t.TokenName[n.Keyword]="Keyword",t.TokenName[n.NullLiteral]="Null",t.TokenName[n.NumericLiteral]="Numeric",t.TokenName[n.Punctuator]="Punctuator",t.TokenName[n.StringLiteral]="String",t.TokenName[n.RegularExpression]="RegularExpression",t.TokenName[n.Template]="Template"},function(e,t,n){"use strict";function r(e){return"0123456789abcdef".indexOf(e.toLowerCase())}function i(e){return"01234567".indexOf(e)}var o=n(4),a=n(5),s=n(9),u=n(7),c=function(){function e(e,t){this.source=e,this.errorHandler=t,this.trackComment=!1,this.length=e.length,this.index=0,this.lineNumber=e.length>0?1:0,this.lineStart=0,this.curlyStack=[]}return e.prototype.eof=function(){return this.index>=this.length},e.prototype.throwUnexpectedToken=function(e){void 0===e&&(e=a.Messages.UnexpectedTokenIllegal),this.errorHandler.throwError(this.index,this.lineNumber,this.index-this.lineStart+1,e)},e.prototype.tolerateUnexpectedToken=function(){this.errorHandler.tolerateError(this.index,this.lineNumber,this.index-this.lineStart+1,a.Messages.UnexpectedTokenIllegal)},e.prototype.skipSingleLineComment=function(e){var t,n,r;for(this.trackComment&&(t=[],n=this.index-e,r={start:{line:this.lineNumber,column:this.index-this.lineStart-e},end:{}});!this.eof();){var i=this.source.charCodeAt(this.index);if(++this.index,s.Character.isLineTerminator(i)){if(this.trackComment){r.end={line:this.lineNumber,column:this.index-this.lineStart-1};var o={multiLine:!1,slice:[n+e,this.index-1],range:[n,this.index-1],loc:r};t.push(o)}return 13===i&&10===this.source.charCodeAt(this.index)&&++this.index,++this.lineNumber,this.lineStart=this.index,t}}if(this.trackComment){r.end={line:this.lineNumber,column:this.index-this.lineStart};var o={multiLine:!1,slice:[n+e,this.index],range:[n,this.index],loc:r};t.push(o)}return t},e.prototype.skipMultiLineComment=function(){var e,t,n;for(this.trackComment&&(e=[],t=this.index-2,n={start:{line:this.lineNumber,column:this.index-this.lineStart-2},end:{}});!this.eof();){var r=this.source.charCodeAt(this.index);if(s.Character.isLineTerminator(r))13===r&&10===this.source.charCodeAt(this.index+1)&&++this.index,++this.lineNumber,++this.index,this.lineStart=this.index;else if(42===r){if(47===this.source.charCodeAt(this.index+1)){if(this.index+=2,this.trackComment){n.end={line:this.lineNumber,column:this.index-this.lineStart};var i={multiLine:!0,slice:[t+2,this.index-2],range:[t,this.index],loc:n};e.push(i)}return e}++this.index}else++this.index}if(this.trackComment){n.end={line:this.lineNumber,column:this.index-this.lineStart};var i={multiLine:!0, +slice:[t+2,this.index],range:[t,this.index],loc:n};e.push(i)}return this.tolerateUnexpectedToken(),e},e.prototype.scanComments=function(){var e;this.trackComment&&(e=[]);for(var t=0===this.index;!this.eof();){var n=this.source.charCodeAt(this.index);if(s.Character.isWhiteSpace(n))++this.index;else if(s.Character.isLineTerminator(n))++this.index,13===n&&10===this.source.charCodeAt(this.index)&&++this.index,++this.lineNumber,this.lineStart=this.index,t=!0;else if(47===n)if(n=this.source.charCodeAt(this.index+1),47===n){this.index+=2;var r=this.skipSingleLineComment(2);this.trackComment&&(e=e.concat(r)),t=!0}else{if(42!==n)break;this.index+=2;var r=this.skipMultiLineComment();this.trackComment&&(e=e.concat(r))}else if(t&&45===n){if(45!==this.source.charCodeAt(this.index+1)||62!==this.source.charCodeAt(this.index+2))break;this.index+=3;var r=this.skipSingleLineComment(3);this.trackComment&&(e=e.concat(r))}else{if(60!==n)break;if("!--"!==this.source.slice(this.index+1,this.index+4))break;this.index+=4;var r=this.skipSingleLineComment(4);this.trackComment&&(e=e.concat(r))}}return e},e.prototype.isFutureReservedWord=function(e){switch(e){case"enum":case"export":case"import":case"super":return!0;default:return!1}},e.prototype.isStrictModeReservedWord=function(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return!0;default:return!1}},e.prototype.isRestrictedWord=function(e){return"eval"===e||"arguments"===e},e.prototype.isKeyword=function(e){switch(e.length){case 2:return"if"===e||"in"===e||"do"===e;case 3:return"var"===e||"for"===e||"new"===e||"try"===e||"let"===e;case 4:return"this"===e||"else"===e||"case"===e||"void"===e||"with"===e||"enum"===e;case 5:return"while"===e||"break"===e||"catch"===e||"throw"===e||"const"===e||"yield"===e||"class"===e||"super"===e;case 6:return"return"===e||"typeof"===e||"delete"===e||"switch"===e||"export"===e||"import"===e;case 7:return"default"===e||"finally"===e||"extends"===e;case 8:return"function"===e||"continue"===e||"debugger"===e;case 10:return"instanceof"===e;default:return!1}},e.prototype.codePointAt=function(e){var t=this.source.charCodeAt(e);if(t>=55296&&t<=56319){var n=this.source.charCodeAt(e+1);if(n>=56320&&n<=57343){var r=t;t=1024*(r-55296)+n-56320+65536}}return t},e.prototype.scanHexEscape=function(e){for(var t="u"===e?4:2,n=0,i=0;i1114111||"}"!==e)&&this.throwUnexpectedToken(),s.Character.fromCodePoint(t)},e.prototype.getIdentifier=function(){for(var e=this.index++;!this.eof();){var t=this.source.charCodeAt(this.index);if(92===t)return this.index=e,this.getComplexIdentifier();if(t>=55296&&t<57343)return this.index=e,this.getComplexIdentifier();if(!s.Character.isIdentifierPart(t))break;++this.index}return this.source.slice(e,this.index)},e.prototype.getComplexIdentifier=function(){var e=this.codePointAt(this.index),t=s.Character.fromCodePoint(e);this.index+=t.length;var n;for(92===e&&(117!==this.source.charCodeAt(this.index)&&this.throwUnexpectedToken(),++this.index,"{"===this.source[this.index]?(++this.index,n=this.scanUnicodeCodePointEscape()):(n=this.scanHexEscape("u"),e=n.charCodeAt(0),n&&"\\"!==n&&s.Character.isIdentifierStart(e)||this.throwUnexpectedToken()),t=n);!this.eof()&&(e=this.codePointAt(this.index),s.Character.isIdentifierPart(e));)n=s.Character.fromCodePoint(e),t+=n,this.index+=n.length,92===e&&(t=t.substr(0,t.length-1),117!==this.source.charCodeAt(this.index)&&this.throwUnexpectedToken(),++this.index,"{"===this.source[this.index]?(++this.index,n=this.scanUnicodeCodePointEscape()):(n=this.scanHexEscape("u"),e=n.charCodeAt(0),n&&"\\"!==n&&s.Character.isIdentifierPart(e)||this.throwUnexpectedToken()),t+=n);return t},e.prototype.octalToDecimal=function(e){var t="0"!==e,n=i(e);return!this.eof()&&s.Character.isOctalDigit(this.source.charCodeAt(this.index))&&(t=!0,n=8*n+i(this.source[this.index++]),"0123".indexOf(e)>=0&&!this.eof()&&s.Character.isOctalDigit(this.source.charCodeAt(this.index))&&(n=8*n+i(this.source[this.index++]))),{code:n,octal:t}},e.prototype.scanIdentifier=function(){var e,t=this.index,n=92===this.source.charCodeAt(t)?this.getComplexIdentifier():this.getIdentifier();return e=1===n.length?u.Token.Identifier:this.isKeyword(n)?u.Token.Keyword:"null"===n?u.Token.NullLiteral:"true"===n||"false"===n?u.Token.BooleanLiteral:u.Token.Identifier,{type:e,value:n,lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}},e.prototype.scanPunctuator=function(){var e={type:u.Token.Punctuator,value:"",lineNumber:this.lineNumber,lineStart:this.lineStart,start:this.index,end:this.index},t=this.source[this.index];switch(t){case"(":case"{":"{"===t&&this.curlyStack.push("{"),++this.index;break;case".":++this.index,"."===this.source[this.index]&&"."===this.source[this.index+1]&&(this.index+=2,t="...");break;case"}":++this.index,this.curlyStack.pop();break;case")":case";":case",":case"[":case"]":case":":case"?":case"~":++this.index;break;default:t=this.source.substr(this.index,4),">>>="===t?this.index+=4:(t=t.substr(0,3),"==="===t||"!=="===t||">>>"===t||"<<="===t||">>="===t||"**="===t?this.index+=3:(t=t.substr(0,2),"&&"===t||"||"===t||"=="===t||"!="===t||"+="===t||"-="===t||"*="===t||"/="===t||"++"===t||"--"===t||"<<"===t||">>"===t||"&="===t||"|="===t||"^="===t||"%="===t||"<="===t||">="===t||"=>"===t||"**"===t?this.index+=2:(t=this.source[this.index],"<>=!+-*%&|^/".indexOf(t)>=0&&++this.index)))}return this.index===e.start&&this.throwUnexpectedToken(),e.end=this.index,e.value=t,e},e.prototype.scanHexLiteral=function(e){for(var t="";!this.eof()&&s.Character.isHexDigit(this.source.charCodeAt(this.index));)t+=this.source[this.index++];return 0===t.length&&this.throwUnexpectedToken(),s.Character.isIdentifierStart(this.source.charCodeAt(this.index))&&this.throwUnexpectedToken(),{type:u.Token.NumericLiteral,value:parseInt("0x"+t,16),lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}},e.prototype.scanBinaryLiteral=function(e){for(var t,n="";!this.eof()&&(t=this.source[this.index],"0"===t||"1"===t);)n+=this.source[this.index++];return 0===n.length&&this.throwUnexpectedToken(),this.eof()||(t=this.source.charCodeAt(this.index),(s.Character.isIdentifierStart(t)||s.Character.isDecimalDigit(t))&&this.throwUnexpectedToken()),{type:u.Token.NumericLiteral,value:parseInt(n,2),lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}},e.prototype.scanOctalLiteral=function(e,t){var n="",r=!1;for(s.Character.isOctalDigit(e.charCodeAt(0))?(r=!0,n="0"+this.source[this.index++]):++this.index;!this.eof()&&s.Character.isOctalDigit(this.source.charCodeAt(this.index));)n+=this.source[this.index++];return r||0!==n.length||this.throwUnexpectedToken(),(s.Character.isIdentifierStart(this.source.charCodeAt(this.index))||s.Character.isDecimalDigit(this.source.charCodeAt(this.index)))&&this.throwUnexpectedToken(),{type:u.Token.NumericLiteral,value:parseInt(n,8),octal:r,lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}},e.prototype.isImplicitOctalLiteral=function(){for(var e=this.index+1;e=0&&(r=r.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g,function(e,t,r){var o=parseInt(t||r,16);return o>1114111&&i.throwUnexpectedToken(a.Messages.InvalidRegExp),o<=65535?String.fromCharCode(o):n}).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,n));try{RegExp(r)}catch(e){this.throwUnexpectedToken(a.Messages.InvalidRegExp)}try{return new RegExp(e,t)}catch(e){return null}},e.prototype.scanRegExpBody=function(){var e=this.source[this.index];o.assert("/"===e,"Regular expression literal must start with a slash");for(var t=this.source[this.index++],n=!1,r=!1;!this.eof();)if(e=this.source[this.index++],t+=e,"\\"===e)e=this.source[this.index++],s.Character.isLineTerminator(e.charCodeAt(0))&&this.throwUnexpectedToken(a.Messages.UnterminatedRegExp),t+=e;else if(s.Character.isLineTerminator(e.charCodeAt(0)))this.throwUnexpectedToken(a.Messages.UnterminatedRegExp);else if(n)"]"===e&&(n=!1);else{if("/"===e){r=!0;break}"["===e&&(n=!0)}r||this.throwUnexpectedToken(a.Messages.UnterminatedRegExp);var i=t.substr(1,t.length-2);return{value:i,literal:t}},e.prototype.scanRegExpFlags=function(){for(var e="",t="";!this.eof();){var n=this.source[this.index];if(!s.Character.isIdentifierPart(n.charCodeAt(0)))break;if(++this.index,"\\"!==n||this.eof())t+=n,e+=n;else if(n=this.source[this.index],"u"===n){++this.index;var r=this.index;if(n=this.scanHexEscape("u"))for(t+=n,e+="\\u";r=55296&&e<57343&&s.Character.isIdentifierStart(this.codePointAt(this.index))?this.scanIdentifier():this.scanPunctuator()},e}();t.Scanner=c},function(e,t){"use strict";var n={NonAsciiIdentifierStart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,NonAsciiIdentifierPart:/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/};t.Character={fromCodePoint:function(e){return e<65536?String.fromCharCode(e):String.fromCharCode(55296+(e-65536>>10))+String.fromCharCode(56320+(e-65536&1023))},isWhiteSpace:function(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&[5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279].indexOf(e)>=0},isLineTerminator:function(e){return 10===e||13===e||8232===e||8233===e},isIdentifierStart:function(e){return 36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||92===e||e>=128&&n.NonAsciiIdentifierStart.test(t.Character.fromCodePoint(e))},isIdentifierPart:function(e){return 36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||92===e||e>=128&&n.NonAsciiIdentifierPart.test(t.Character.fromCodePoint(e))},isDecimalDigit:function(e){return e>=48&&e<=57},isHexDigit:function(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102},isOctalDigit:function(e){return e>=48&&e<=55}}},function(e,t,n){"use strict";var r=n(2),i=function(){function e(e){this.type=r.Syntax.ArrayExpression,this.elements=e}return e}();t.ArrayExpression=i;var o=function(){function e(e){this.type=r.Syntax.ArrayPattern,this.elements=e}return e}();t.ArrayPattern=o;var a=function(){function e(e,t,n){this.type=r.Syntax.ArrowFunctionExpression,this.id=null,this.params=e,this.body=t,this.generator=!1,this.expression=n}return e}();t.ArrowFunctionExpression=a;var s=function(){function e(e,t,n){this.type=r.Syntax.AssignmentExpression,this.operator=e,this.left=t,this.right=n}return e}();t.AssignmentExpression=s;var u=function(){function e(e,t){this.type=r.Syntax.AssignmentPattern,this.left=e,this.right=t}return e}();t.AssignmentPattern=u;var c=function(){function e(e,t,n){var i="||"===e||"&&"===e;this.type=i?r.Syntax.LogicalExpression:r.Syntax.BinaryExpression,this.operator=e,this.left=t,this.right=n}return e}();t.BinaryExpression=c;var l=function(){function e(e){this.type=r.Syntax.BlockStatement,this.body=e}return e}();t.BlockStatement=l;var p=function(){function e(e){this.type=r.Syntax.BreakStatement,this.label=e}return e}();t.BreakStatement=p;var f=function(){function e(e,t){this.type=r.Syntax.CallExpression,this.callee=e,this.arguments=t}return e}();t.CallExpression=f;var h=function(){function e(e,t){this.type=r.Syntax.CatchClause,this.param=e,this.body=t}return e}();t.CatchClause=h;var d=function(){function e(e){this.type=r.Syntax.ClassBody,this.body=e}return e}();t.ClassBody=d;var m=function(){function e(e,t,n){this.type=r.Syntax.ClassDeclaration,this.id=e,this.superClass=t,this.body=n}return e}();t.ClassDeclaration=m;var y=function(){function e(e,t,n){this.type=r.Syntax.ClassExpression,this.id=e,this.superClass=t,this.body=n}return e}();t.ClassExpression=y;var v=function(){function e(e,t){this.type=r.Syntax.MemberExpression,this.computed=!0,this.object=e,this.property=t}return e}();t.ComputedMemberExpression=v;var g=function(){function e(e,t,n){this.type=r.Syntax.ConditionalExpression, +this.test=e,this.consequent=t,this.alternate=n}return e}();t.ConditionalExpression=g;var _=function(){function e(e){this.type=r.Syntax.ContinueStatement,this.label=e}return e}();t.ContinueStatement=_;var b=function(){function e(){this.type=r.Syntax.DebuggerStatement}return e}();t.DebuggerStatement=b;var x=function(){function e(e,t){this.type=r.Syntax.ExpressionStatement,this.expression=e,this.directive=t}return e}();t.Directive=x;var w=function(){function e(e,t){this.type=r.Syntax.DoWhileStatement,this.body=e,this.test=t}return e}();t.DoWhileStatement=w;var k=function(){function e(){this.type=r.Syntax.EmptyStatement}return e}();t.EmptyStatement=k;var S=function(){function e(e){this.type=r.Syntax.ExportAllDeclaration,this.source=e}return e}();t.ExportAllDeclaration=S;var E=function(){function e(e){this.type=r.Syntax.ExportDefaultDeclaration,this.declaration=e}return e}();t.ExportDefaultDeclaration=E;var C=function(){function e(e,t,n){this.type=r.Syntax.ExportNamedDeclaration,this.declaration=e,this.specifiers=t,this.source=n}return e}();t.ExportNamedDeclaration=C;var A=function(){function e(e,t){this.type=r.Syntax.ExportSpecifier,this.exported=t,this.local=e}return e}();t.ExportSpecifier=A;var T=function(){function e(e){this.type=r.Syntax.ExpressionStatement,this.expression=e}return e}();t.ExpressionStatement=T;var O=function(){function e(e,t,n){this.type=r.Syntax.ForInStatement,this.left=e,this.right=t,this.body=n,this.each=!1}return e}();t.ForInStatement=O;var D=function(){function e(e,t,n){this.type=r.Syntax.ForOfStatement,this.left=e,this.right=t,this.body=n}return e}();t.ForOfStatement=D;var M=function(){function e(e,t,n,i){this.type=r.Syntax.ForStatement,this.init=e,this.test=t,this.update=n,this.body=i}return e}();t.ForStatement=M;var P=function(){function e(e,t,n,i){this.type=r.Syntax.FunctionDeclaration,this.id=e,this.params=t,this.body=n,this.generator=i,this.expression=!1}return e}();t.FunctionDeclaration=P;var I=function(){function e(e,t,n,i){this.type=r.Syntax.FunctionExpression,this.id=e,this.params=t,this.body=n,this.generator=i,this.expression=!1}return e}();t.FunctionExpression=I;var j=function(){function e(e){this.type=r.Syntax.Identifier,this.name=e}return e}();t.Identifier=j;var R=function(){function e(e,t,n){this.type=r.Syntax.IfStatement,this.test=e,this.consequent=t,this.alternate=n}return e}();t.IfStatement=R;var N=function(){function e(e,t){this.type=r.Syntax.ImportDeclaration,this.specifiers=e,this.source=t}return e}();t.ImportDeclaration=N;var F=function(){function e(e){this.type=r.Syntax.ImportDefaultSpecifier,this.local=e}return e}();t.ImportDefaultSpecifier=F;var B=function(){function e(e){this.type=r.Syntax.ImportNamespaceSpecifier,this.local=e}return e}();t.ImportNamespaceSpecifier=B;var L=function(){function e(e,t){this.type=r.Syntax.ImportSpecifier,this.local=e,this.imported=t}return e}();t.ImportSpecifier=L;var z=function(){function e(e,t){this.type=r.Syntax.LabeledStatement,this.label=e,this.body=t}return e}();t.LabeledStatement=z;var q=function(){function e(e,t){this.type=r.Syntax.Literal,this.value=e,this.raw=t}return e}();t.Literal=q;var U=function(){function e(e,t){this.type=r.Syntax.MetaProperty,this.meta=e,this.property=t}return e}();t.MetaProperty=U;var W=function(){function e(e,t,n,i,o){this.type=r.Syntax.MethodDefinition,this.key=e,this.computed=t,this.value=n,this.kind=i,this.static=o}return e}();t.MethodDefinition=W;var K=function(){function e(e,t){this.type=r.Syntax.NewExpression,this.callee=e,this.arguments=t}return e}();t.NewExpression=K;var V=function(){function e(e){this.type=r.Syntax.ObjectExpression,this.properties=e}return e}();t.ObjectExpression=V;var H=function(){function e(e){this.type=r.Syntax.ObjectPattern,this.properties=e}return e}();t.ObjectPattern=H;var J=function(){function e(e,t){this.type=r.Syntax.Program,this.body=e,this.sourceType=t}return e}();t.Program=J;var G=function(){function e(e,t,n,i,o,a){this.type=r.Syntax.Property,this.key=t,this.computed=n,this.value=i,this.kind=e,this.method=o,this.shorthand=a}return e}();t.Property=G;var X=function(){function e(e,t,n){this.type=r.Syntax.Literal,this.value=e,this.raw=t,this.regex=n}return e}();t.RegexLiteral=X;var Y=function(){function e(e){this.type=r.Syntax.RestElement,this.argument=e}return e}();t.RestElement=Y;var $=function(){function e(e){this.type=r.Syntax.ReturnStatement,this.argument=e}return e}();t.ReturnStatement=$;var Z=function(){function e(e){this.type=r.Syntax.SequenceExpression,this.expressions=e}return e}();t.SequenceExpression=Z;var Q=function(){function e(e){this.type=r.Syntax.SpreadElement,this.argument=e}return e}();t.SpreadElement=Q;var ee=function(){function e(e,t){this.type=r.Syntax.MemberExpression,this.computed=!1,this.object=e,this.property=t}return e}();t.StaticMemberExpression=ee;var te=function(){function e(){this.type=r.Syntax.Super}return e}();t.Super=te;var ne=function(){function e(e,t){this.type=r.Syntax.SwitchCase,this.test=e,this.consequent=t}return e}();t.SwitchCase=ne;var re=function(){function e(e,t){this.type=r.Syntax.SwitchStatement,this.discriminant=e,this.cases=t}return e}();t.SwitchStatement=re;var ie=function(){function e(e,t){this.type=r.Syntax.TaggedTemplateExpression,this.tag=e,this.quasi=t}return e}();t.TaggedTemplateExpression=ie;var oe=function(){function e(e,t){this.type=r.Syntax.TemplateElement,this.value=e,this.tail=t}return e}();t.TemplateElement=oe;var ae=function(){function e(e,t){this.type=r.Syntax.TemplateLiteral,this.quasis=e,this.expressions=t}return e}();t.TemplateLiteral=ae;var se=function(){function e(){this.type=r.Syntax.ThisExpression}return e}();t.ThisExpression=se;var ue=function(){function e(e){this.type=r.Syntax.ThrowStatement,this.argument=e}return e}();t.ThrowStatement=ue;var ce=function(){function e(e,t,n){this.type=r.Syntax.TryStatement,this.block=e,this.handler=t,this.finalizer=n}return e}();t.TryStatement=ce;var le=function(){function e(e,t){this.type=r.Syntax.UnaryExpression,this.operator=e,this.argument=t,this.prefix=!0}return e}();t.UnaryExpression=le;var pe=function(){function e(e,t,n){this.type=r.Syntax.UpdateExpression,this.operator=e,this.argument=t,this.prefix=n}return e}();t.UpdateExpression=pe;var fe=function(){function e(e,t){this.type=r.Syntax.VariableDeclaration,this.declarations=e,this.kind=t}return e}();t.VariableDeclaration=fe;var he=function(){function e(e,t){this.type=r.Syntax.VariableDeclarator,this.id=e,this.init=t}return e}();t.VariableDeclarator=he;var de=function(){function e(e,t){this.type=r.Syntax.WhileStatement,this.test=e,this.body=t}return e}();t.WhileStatement=de;var me=function(){function e(e,t){this.type=r.Syntax.WithStatement,this.object=e,this.body=t}return e}();t.WithStatement=me;var ye=function(){function e(e,t){this.type=r.Syntax.YieldExpression,this.argument=e,this.delegate=t}return e}();t.YieldExpression=ye},function(e,t,n){"use strict";function r(e){var t;switch(e.type){case l.JSXSyntax.JSXIdentifier:var n=e;t=n.name;break;case l.JSXSyntax.JSXNamespacedName:var i=e;t=r(i.namespace)+":"+r(i.name);break;case l.JSXSyntax.JSXMemberExpression:var o=e;t=r(o.object)+"."+r(o.property)}return t}var i,o=this&&this.__extends||function(e,t){function n(){this.constructor=e}for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)},a=n(9),s=n(7),u=n(3),c=n(12),l=n(13),p=n(10),f=n(14);!function(e){e[e.Identifier=100]="Identifier",e[e.Text=101]="Text"}(i||(i={})),s.TokenName[i.Identifier]="JSXIdentifier",s.TokenName[i.Text]="JSXText";var h=function(e){function t(t,n,r){e.call(this,t,n,r)}return o(t,e),t.prototype.parsePrimaryExpression=function(){return this.match("<")?this.parseJSXRoot():e.prototype.parsePrimaryExpression.call(this)},t.prototype.startJSX=function(){this.scanner.index=this.startMarker.index,this.scanner.lineNumber=this.startMarker.lineNumber,this.scanner.lineStart=this.startMarker.lineStart},t.prototype.finishJSX=function(){this.nextToken()},t.prototype.reenterJSX=function(){this.startJSX(),this.expectJSX("}"),this.config.tokens&&this.tokens.pop()},t.prototype.createJSXNode=function(){return this.collectComments(),{index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}},t.prototype.createJSXChildNode=function(){return{index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}},t.prototype.scanXHTMLEntity=function(e){for(var t="&",n=!0,r=!1,i=!1,o=!1;!this.scanner.eof()&&n&&!r;){var s=this.scanner.source[this.scanner.index];if(s===e)break;if(r=";"===s,t+=s,++this.scanner.index,!r)switch(t.length){case 2:i="#"===s;break;case 3:i&&(o="x"===s,n=o||a.Character.isDecimalDigit(s.charCodeAt(0)),i=i&&!o);break;default:n=n&&!(i&&!a.Character.isDecimalDigit(s.charCodeAt(0))),n=n&&!(o&&!a.Character.isHexDigit(s.charCodeAt(0)))}}if(n&&r&&t.length>2){var u=t.substr(1,t.length-2);i&&u.length>1?t=String.fromCharCode(parseInt(u.substr(1),10)):o&&u.length>2?t=String.fromCharCode(parseInt("0"+u.substr(1),16)):i||o||!c.XHTMLEntities[u]||(t=c.XHTMLEntities[u])}return t},t.prototype.lexJSX=function(){var e=this.scanner.source.charCodeAt(this.scanner.index);if(60===e||62===e||47===e||58===e||61===e||123===e||125===e){var t=this.scanner.source[this.scanner.index++];return{type:s.Token.Punctuator,value:t,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:this.scanner.index-1,end:this.scanner.index}}if(34===e||39===e){for(var n=this.scanner.index,r=this.scanner.source[this.scanner.index++],o="";!this.scanner.eof();){var u=this.scanner.source[this.scanner.index++];if(u===r)break;o+="&"===u?this.scanXHTMLEntity(r):u}return{type:s.Token.StringLiteral,value:o,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:n,end:this.scanner.index}}if(46===e){var c=this.scanner.source.charCodeAt(this.scanner.index+1),l=this.scanner.source.charCodeAt(this.scanner.index+2),t=46===c&&46===l?"...":".",n=this.scanner.index;return this.scanner.index+=t.length,{type:s.Token.Punctuator,value:t,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:n,end:this.scanner.index}}if(96===e)return{type:s.Token.Template,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:this.scanner.index,end:this.scanner.index};if(a.Character.isIdentifierStart(e)&&92!==e){var n=this.scanner.index;for(++this.scanner.index;!this.scanner.eof();){var u=this.scanner.source.charCodeAt(this.scanner.index);if(a.Character.isIdentifierPart(u)&&92!==u)++this.scanner.index;else{if(45!==u)break;++this.scanner.index}}var p=this.scanner.source.slice(n,this.scanner.index);return{type:i.Identifier,value:p,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:n,end:this.scanner.index}}this.scanner.throwUnexpectedToken()},t.prototype.nextJSXToken=function(){this.collectComments(),this.startMarker.index=this.scanner.index,this.startMarker.lineNumber=this.scanner.lineNumber,this.startMarker.lineStart=this.scanner.lineStart;var e=this.lexJSX();return this.lastMarker.index=this.scanner.index,this.lastMarker.lineNumber=this.scanner.lineNumber,this.lastMarker.lineStart=this.scanner.lineStart,this.config.tokens&&this.tokens.push(this.convertToken(e)),e},t.prototype.nextJSXText=function(){this.startMarker.index=this.scanner.index,this.startMarker.lineNumber=this.scanner.lineNumber,this.startMarker.lineStart=this.scanner.lineStart;for(var e=this.scanner.index,t="";!this.scanner.eof();){var n=this.scanner.source[this.scanner.index];if("{"===n||"<"===n)break;++this.scanner.index,t+=n,a.Character.isLineTerminator(n.charCodeAt(0))&&(++this.scanner.lineNumber,"\r"===n&&"\n"===this.scanner.source[this.scanner.index]&&++this.scanner.index,this.scanner.lineStart=this.scanner.index)}this.lastMarker.index=this.scanner.index,this.lastMarker.lineNumber=this.scanner.lineNumber,this.lastMarker.lineStart=this.scanner.lineStart;var r={type:i.Text,value:t,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:e,end:this.scanner.index};return t.length>0&&this.config.tokens&&this.tokens.push(this.convertToken(r)),r},t.prototype.peekJSXToken=function(){var e=this.scanner.index,t=this.scanner.lineNumber,n=this.scanner.lineStart;this.scanner.scanComments();var r=this.lexJSX();return this.scanner.index=e,this.scanner.lineNumber=t,this.scanner.lineStart=n,r},t.prototype.expectJSX=function(e){var t=this.nextJSXToken();t.type===s.Token.Punctuator&&t.value===e||this.throwUnexpectedToken(t)},t.prototype.matchJSX=function(e){var t=this.peekJSXToken();return t.type===s.Token.Punctuator&&t.value===e},t.prototype.parseJSXIdentifier=function(){var e=this.createJSXNode(),t=this.nextJSXToken();return t.type!==i.Identifier&&this.throwUnexpectedToken(t),this.finalize(e,new f.JSXIdentifier(t.value))},t.prototype.parseJSXElementName=function(){var e=this.createJSXNode(),t=this.parseJSXIdentifier();if(this.matchJSX(":")){var n=t;this.expectJSX(":");var r=this.parseJSXIdentifier();t=this.finalize(e,new f.JSXNamespacedName(n,r))}else if(this.matchJSX("."))for(;this.matchJSX(".");){var i=t;this.expectJSX(".");var o=this.parseJSXIdentifier();t=this.finalize(e,new f.JSXMemberExpression(i,o))}return t},t.prototype.parseJSXAttributeName=function(){var e,t=this.createJSXNode(),n=this.parseJSXIdentifier();if(this.matchJSX(":")){var r=n;this.expectJSX(":");var i=this.parseJSXIdentifier();e=this.finalize(t,new f.JSXNamespacedName(r,i))}else e=n;return e},t.prototype.parseJSXStringLiteralAttribute=function(){var e=this.createJSXNode(),t=this.nextJSXToken();t.type!==s.Token.StringLiteral&&this.throwUnexpectedToken(t);var n=this.getTokenRaw(t);return this.finalize(e,new p.Literal(t.value,n))},t.prototype.parseJSXExpressionAttribute=function(){var e=this.createJSXNode();this.expectJSX("{"),this.finishJSX(),this.match("}")&&this.tolerateError("JSX attributes must only be assigned a non-empty expression");var t=this.parseAssignmentExpression();return this.reenterJSX(),this.finalize(e,new f.JSXExpressionContainer(t))},t.prototype.parseJSXAttributeValue=function(){return this.matchJSX("{")?this.parseJSXExpressionAttribute():this.matchJSX("<")?this.parseJSXElement():this.parseJSXStringLiteralAttribute()},t.prototype.parseJSXNameValueAttribute=function(){var e=this.createJSXNode(),t=this.parseJSXAttributeName(),n=null;return this.matchJSX("=")&&(this.expectJSX("="),n=this.parseJSXAttributeValue()),this.finalize(e,new f.JSXAttribute(t,n))},t.prototype.parseJSXSpreadAttribute=function(){var e=this.createJSXNode();this.expectJSX("{"),this.expectJSX("..."),this.finishJSX();var t=this.parseAssignmentExpression();return this.reenterJSX(),this.finalize(e,new f.JSXSpreadAttribute(t))},t.prototype.parseJSXAttributes=function(){for(var e=[];!this.matchJSX("/")&&!this.matchJSX(">");){var t=this.matchJSX("{")?this.parseJSXSpreadAttribute():this.parseJSXNameValueAttribute();e.push(t)}return e},t.prototype.parseJSXOpeningElement=function(){var e=this.createJSXNode();this.expectJSX("<");var t=this.parseJSXElementName(),n=this.parseJSXAttributes(),r=this.matchJSX("/");return r&&this.expectJSX("/"),this.expectJSX(">"),this.finalize(e,new f.JSXOpeningElement(t,r,n))},t.prototype.parseJSXBoundaryElement=function(){var e=this.createJSXNode();if(this.expectJSX("<"),this.matchJSX("/")){this.expectJSX("/");var t=this.parseJSXElementName();return this.expectJSX(">"),this.finalize(e,new f.JSXClosingElement(t))}var n=this.parseJSXElementName(),r=this.parseJSXAttributes(),i=this.matchJSX("/");return i&&this.expectJSX("/"),this.expectJSX(">"),this.finalize(e,new f.JSXOpeningElement(n,i,r))},t.prototype.parseJSXEmptyExpression=function(){var e=this.createJSXChildNode();return this.collectComments(),this.lastMarker.index=this.scanner.index,this.lastMarker.lineNumber=this.scanner.lineNumber,this.lastMarker.lineStart=this.scanner.lineStart,this.finalize(e,new f.JSXEmptyExpression)},t.prototype.parseJSXExpressionContainer=function(){var e=this.createJSXNode();this.expectJSX("{");var t;return this.matchJSX("}")?(t=this.parseJSXEmptyExpression(),this.expectJSX("}")):(this.finishJSX(),t=this.parseAssignmentExpression(),this.reenterJSX()),this.finalize(e,new f.JSXExpressionContainer(t))},t.prototype.parseJSXChildren=function(){for(var e=[];!this.scanner.eof();){var t=this.createJSXChildNode(),n=this.nextJSXText();if(n.start0))break;var a=this.finalize(e.node,new f.JSXElement(e.opening,e.children,e.closing));e=t.pop(),e.children.push(a)}}return e},t.prototype.parseJSXElement=function(){var e=this.createJSXNode(),t=this.parseJSXOpeningElement(),n=[],r=null;if(!t.selfClosing){var i=this.parseComplexJSXElement({node:e,opening:t,closing:r,children:n});n=i.children,r=i.closing}return this.finalize(e,new f.JSXElement(t,n,r))},t.prototype.parseJSXRoot=function(){this.config.tokens&&this.tokens.pop(),this.startJSX();var e=this.parseJSXElement();return this.finishJSX(),e},t}(u.Parser);t.JSXParser=h},function(e,t){"use strict";t.XHTMLEntities={quot:'"',amp:"&",apos:"'",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦",lang:"⟨",rang:"⟩"}},function(e,t){"use strict";t.JSXSyntax={JSXAttribute:"JSXAttribute",JSXClosingElement:"JSXClosingElement",JSXElement:"JSXElement",JSXEmptyExpression:"JSXEmptyExpression",JSXExpressionContainer:"JSXExpressionContainer",JSXIdentifier:"JSXIdentifier",JSXMemberExpression:"JSXMemberExpression",JSXNamespacedName:"JSXNamespacedName",JSXOpeningElement:"JSXOpeningElement",JSXSpreadAttribute:"JSXSpreadAttribute",JSXText:"JSXText"}},function(e,t,n){"use strict";var r=n(13),i=function(){function e(e){this.type=r.JSXSyntax.JSXClosingElement,this.name=e}return e}();t.JSXClosingElement=i;var o=function(){function e(e,t,n){this.type=r.JSXSyntax.JSXElement,this.openingElement=e,this.children=t,this.closingElement=n}return e}();t.JSXElement=o;var a=function(){function e(){this.type=r.JSXSyntax.JSXEmptyExpression}return e}();t.JSXEmptyExpression=a;var s=function(){function e(e){this.type=r.JSXSyntax.JSXExpressionContainer,this.expression=e}return e}();t.JSXExpressionContainer=s;var u=function(){function e(e){this.type=r.JSXSyntax.JSXIdentifier,this.name=e}return e}();t.JSXIdentifier=u;var c=function(){function e(e,t){this.type=r.JSXSyntax.JSXMemberExpression,this.object=e,this.property=t}return e}();t.JSXMemberExpression=c;var l=function(){function e(e,t){this.type=r.JSXSyntax.JSXAttribute,this.name=e,this.value=t}return e}();t.JSXAttribute=l;var p=function(){function e(e,t){this.type=r.JSXSyntax.JSXNamespacedName,this.namespace=e,this.name=t}return e}();t.JSXNamespacedName=p;var f=function(){function e(e,t,n){this.type=r.JSXSyntax.JSXOpeningElement,this.name=e,this.selfClosing=t,this.attributes=n}return e}();t.JSXOpeningElement=f;var h=function(){function e(e){this.type=r.JSXSyntax.JSXSpreadAttribute,this.argument=e}return e}();t.JSXSpreadAttribute=h;var d=function(){function e(e,t){this.type=r.JSXSyntax.JSXText,this.value=e,this.raw=t}return e}();t.JSXText=d},function(e,t,n){"use strict";var r=n(8),i=n(6),o=n(7),a=function(){function e(){this.values=[],this.curly=this.paren=-1}return e.prototype.beforeFunctionExpression=function(e){return["(","{","[","in","typeof","instanceof","new","return","case","delete","throw","void","=","+=","-=","*=","**=","/=","%=","<<=",">>=",">>>=","&=","|=","^=",",","+","-","*","**","/","%","++","--","<<",">>",">>>","&","|","^","!","~","&&","||","?",":","===","==",">=","<=","<",">","!=","!=="].indexOf(e)>=0},e.prototype.isRegexStart=function(){var e=this.values[this.values.length-1],t=null!==e;switch(e){case"this":case"]":t=!1;break;case")":var n=this.values[this.paren-1];t="if"===n||"while"===n||"for"===n||"with"===n;break;case"}":if(t=!1,"function"===this.values[this.curly-3]){var r=this.values[this.curly-4];t=!!r&&!this.beforeFunctionExpression(r)}else if("function"===this.values[this.curly-4]){var i=this.values[this.curly-5];t=!i||!this.beforeFunctionExpression(i)}}return t},e.prototype.push=function(e){e.type===o.Token.Punctuator||e.type===o.Token.Keyword?("{"===e.value?this.curly=this.values.length:"("===e.value&&(this.paren=this.values.length),this.values.push(e.value)):this.values.push(null)},e}(),s=function(){function e(e,t){this.errorHandler=new i.ErrorHandler,this.errorHandler.tolerant=!!t&&("boolean"==typeof t.tolerant&&t.tolerant),this.scanner=new r.Scanner(e,this.errorHandler),this.scanner.trackComment=!!t&&("boolean"==typeof t.comment&&t.comment),this.trackRange=!!t&&("boolean"==typeof t.range&&t.range),this.trackLoc=!!t&&("boolean"==typeof t.loc&&t.loc),this.buffer=[],this.reader=new a}return e.prototype.errors=function(){return this.errorHandler.errors},e.prototype.getNextToken=function(){if(0===this.buffer.length){var e=this.scanner.scanComments();if(this.scanner.trackComment)for(var t=0;tr&&" "!==e[d+1],d=o);else if(!l(a))return le;m=m&&p(a)}u=u||h&&o-d-1>r&&" "!==e[d+1]}return s||u?" "===e[0]&&n>9?le:u?ce:ue:m&&!i(e)?ae:se}function d(e,t,n,r){e.dump=function(){function i(t){return u(e,t)}if(0===t.length)return"''";if(!e.noCompatMode&&oe.indexOf(t)!==-1)return"'"+t+"'";var o=e.indent*Math.max(1,n),s=e.lineWidth===-1?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-o),c=r||e.flowLevel>-1&&n>=e.flowLevel;switch(h(t,c,e.indent,s,i)){case ae:return t;case se:return"'"+t.replace(/'/g,"''")+"'";case ue:return"|"+m(t,e.indent)+y(a(t,o));case ce:return">"+m(t,e.indent)+y(a(v(t,s),o));case le:return'"'+_(t,s)+'"';default:throw new M("impossible error: invalid scalar style")}}()}function m(e,t){var n=" "===e[0]?String(t):"",r="\n"===e[e.length-1],i=r&&("\n"===e[e.length-2]||"\n"===e),o=i?"+":r?"":"-";return n+o+"\n"}function y(e){return"\n"===e[e.length-1]?e.slice(0,-1):e}function v(e,t){for(var n,r,i=/(\n+)([^\n]*)/g,o=function(){var n=e.indexOf("\n");return n=n!==-1?n:e.length,i.lastIndex=n,g(e.slice(0,n),t)}(),a="\n"===e[0]||" "===e[0];r=i.exec(e);){var s=r[1],u=r[2];n=" "===u[0],o+=s+(a||n||""===u?"":"\n")+g(u,t),a=n}return o}function g(e,t){if(""===e||" "===e[0])return e;for(var n,r,i=/ [^ ]/g,o=0,a=0,s=0,u="";n=i.exec(e);)s=n.index,s-o>t&&(r=a>o?a:s,u+="\n"+e.slice(o,r),o=r+1),a=s;return u+="\n",u+=e.length-o>t&&a>o?e.slice(o,a)+"\n"+e.slice(a+1):e.slice(o),u.slice(1)}function _(e){for(var t,n,r="",o=0;o1024&&(s+="? "),s+=e.dump+": ",E(e,t,a,!1,!1)&&(s+=e.dump,u+=s));e.tag=c,e.dump="{"+u+"}"}function k(e,t,n,r){var i,o,a,u,c,l,p="",f=e.tag,h=Object.keys(n);if(e.sortKeys===!0)h.sort();else if("function"==typeof e.sortKeys)h.sort(e.sortKeys);else if(e.sortKeys)throw new M("sortKeys must be a boolean or a function");for(i=0,o=h.length;i1024,c&&(l+=e.dump&&F===e.dump.charCodeAt(0)?"?":"? "),l+=e.dump,c&&(l+=s(e,t)),E(e,t+1,u,!0,c)&&(l+=e.dump&&F===e.dump.charCodeAt(0)?":":": ",l+=e.dump,p+=l));e.tag=f,e.dump=p||"{}"}function S(e,t,n){var r,i,o,a,s,u;for(i=n?e.explicitTypes:e.implicitTypes,o=0,a=i.length;o tag resolver accepts not "'+u+'" style');r=s.represent[u](t,u)}e.dump=r}return!0}return!1}function E(e,t,n,r,i,o){e.tag=null,e.dump=n,S(e,n,!1)||S(e,n,!0);var a=j.call(e.dump);r&&(r=e.flowLevel<0||e.flowLevel>t);var s,u,c="[object Object]"===a||"[object Array]"===a;if(c&&(s=e.duplicates.indexOf(n),u=s!==-1),(null!==e.tag&&"?"!==e.tag||u||2!==e.indent&&t>0)&&(i=!1),u&&e.usedDuplicates[s])e.dump="*ref_"+s;else{if(c&&u&&!e.usedDuplicates[s]&&(e.usedDuplicates[s]=!0),"[object Object]"===a)r&&0!==Object.keys(e.dump).length?(k(e,t,e.dump,i),u&&(e.dump="&ref_"+s+e.dump)):(w(e,t,e.dump),u&&(e.dump="&ref_"+s+" "+e.dump));else if("[object Array]"===a)r&&0!==e.dump.length?(x(e,t,e.dump,i),u&&(e.dump="&ref_"+s+e.dump)):(b(e,t,e.dump),u&&(e.dump="&ref_"+s+" "+e.dump));else{if("[object String]"!==a){if(e.skipInvalid)return!1;throw new M("unacceptable kind of an object to dump "+a)}"?"!==e.tag&&d(e,e.dump,t,o)}null!==e.tag&&"?"!==e.tag&&(e.dump="!<"+e.tag+"> "+e.dump)}return!0}function C(e,t){var n,r,i=[],o=[];for(A(e,i,o),n=0,r=o.length;n1&&void 0!==arguments[1]?arguments[1]:"";if(h.List.isList(e))return e.some(function(e){return h.Map.isMap(e)&&e.get("in")===t})}function s(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(h.List.isList(e))return e.some(function(e){return h.Map.isMap(e)&&e.get("type")===t})}function u(e,t){var n=_(e).getIn(["paths"].concat(r(t)),(0,h.fromJS)({})),i=n.get("parameters")||new h.List,o=s(i,"file")?"multipart/form-data":a(i,"formData")?"application/x-www-form-urlencoded":n.get("consumes_value");return(0,h.fromJS)({requestContentType:o,responseContentType:n.get("produces_value")})}function c(e,t){return _(e).getIn(["paths"].concat(r(t),["consumes"]),(0,h.fromJS)({}))}function l(e){return h.Map.isMap(e)?e:new h.Map}Object.defineProperty(t,"__esModule",{value:!0}),t.validateBeforeExecute=t.canExecuteScheme=t.operationScheme=t.hasHost=t.allowTryItOutFor=t.requestFor=t.responseFor=t.requests=t.responses=t.taggedOperations=t.operationsWithTags=t.tagDetails=t.tags=t.operationsWithRootInherited=t.schemes=t.host=t.basePath=t.definitions=t.findDefinition=t.securityDefinitions=t.security=t.produces=t.consumes=t.operations=t.paths=t.semver=t.version=t.externalDocs=t.info=t.spec=t.specResolved=t.specJson=t.specSource=t.specStr=t.url=t.lastError=void 0,t.getParameter=i,t.parameterValues=o,t.parametersIncludeIn=a,t.parametersIncludeType=s,t.contentTypeValues=u,t.operationConsumes=c;var p=n(575),f=n(335),h=n(325),d="default",m=["get","put","post","delete","options","head","patch"],y=function(e){return e||(0,h.Map)()},v=(t.lastError=(0,p.createSelector)(y,function(e){return e.get("lastError")}),t.url=(0,p.createSelector)(y,function(e){return e.get("url")}),t.specStr=(0,p.createSelector)(y,function(e){return e.get("spec")||""}),t.specSource=(0,p.createSelector)(y,function(e){return e.get("specSource")||"not-editor"}),t.specJson=(0,p.createSelector)(y,function(e){return e.get("json",(0,h.Map)())})),g=t.specResolved=(0,p.createSelector)(y,function(e){return e.get("resolved",(0,h.Map)())}),_=t.spec=function(e){var t=g(e);return t.count()<1&&(t=v(e)),t},b=t.info=(0,p.createSelector)(_,function(e){return l(e&&e.get("info"))}),x=(t.externalDocs=(0,p.createSelector)(_,function(e){return l(e&&e.get("externalDocs"))}),t.version=(0,p.createSelector)(b,function(e){return e&&e.get("version")})),w=(t.semver=(0,p.createSelector)(x,function(e){return/v?([0-9]*)\.([0-9]*)\.([0-9]*)/i.exec(e).slice(1)}),t.paths=(0,p.createSelector)(_,function(e){return e.get("paths")})),k=t.operations=(0,p.createSelector)(w,function(e){if(!e||e.size<1)return(0,h.List)();var t=(0,h.List)();return e&&e.forEach?(e.forEach(function(e,n){return e&&e.forEach?void e.forEach(function(e,r){m.indexOf(r)!==-1&&(t=t.push((0,h.fromJS)({path:n,method:r,operation:e,id:r+"-"+n})))}):{}}),t):(0,h.List)()}),S=t.consumes=(0,p.createSelector)(_,function(e){return(0,h.Set)(e.get("consumes"))}),E=t.produces=(0,p.createSelector)(_,function(e){return(0,h.Set)(e.get("produces"))}),C=(t.security=(0,p.createSelector)(_,function(e){return e.get("security",(0,h.List)())}),t.securityDefinitions=(0,p.createSelector)(_,function(e){return e.get("securityDefinitions")}),t.findDefinition=function(e,t){return g(e).getIn(["definitions",t],null)},t.definitions=(0,p.createSelector)(_,function(e){return e.get("definitions")||(0,h.Map)()}),t.basePath=(0,p.createSelector)(_,function(e){return e.get("basePath")}),t.host=(0,p.createSelector)(_,function(e){return e.get("host")}),t.schemes=(0,p.createSelector)(_,function(e){return e.get("schemes",(0,h.Map)())}),t.operationsWithRootInherited=(0,p.createSelector)(k,S,E,function(e,t,n){return e.map(function(e){return e.update("operation",function(e){if(e){if(!h.Map.isMap(e))return;return e.withMutations(function(e){return e.get("consumes")||e.update("consumes",function(e){return(0,h.Set)(e).merge(t)}),e.get("produces")||e.update("produces",function(e){return(0,h.Set)(e).merge(n)}),e})}return(0,h.Map)()})})})),A=t.tags=(0,p.createSelector)(_,function(e){return e.get("tags",(0,h.List)())}),T=t.tagDetails=function(e,t){var n=A(e)||(0,h.List)();return n.filter(h.Map.isMap).find(function(e){return e.get("name")===t},(0,h.Map)())},O=t.operationsWithTags=(0,p.createSelector)(C,function(e){return e.reduce(function(e,t){var n=(0,h.Set)(t.getIn(["operation","tags"]));return n.count()<1?e.update(d,(0,h.List)(),function(e){return e.push(t)}):n.reduce(function(e,n){return e.update(n,(0,h.List)(),function(e){return e.push(t)})},e)},(0,h.Map)())}),D=(t.taggedOperations=function(e){return function(t){var n=t.getConfigs,r=n(),i=r.operationsSorter;return O(e).map(function(t,n){var r="function"==typeof i?i:f.sorters.operationsSorter[i],o=r?t.sort(r):t;return(0,h.Map)({tagDetails:T(e,n),operations:o})})}},t.responses=(0,p.createSelector)(y,function(e){return e.get("responses",(0,h.Map)())})),M=t.requests=(0,p.createSelector)(y,function(e){return e.get("requests",(0,h.Map)())}),P=(t.responseFor=function(e,t,n){return D(e).getIn([t,n],null)},t.requestFor=function(e,t,n){return M(e).getIn([t,n],null)},t.allowTryItOutFor=function(){return!0},t.hasHost=(0,p.createSelector)(_,function(e){var t=e.get("host");return"string"==typeof t&&t.length>0&&"/"!==t[0]}),t.operationScheme=function(e,t,n){var r=e.get("url"),i=r.match(/^([a-z][a-z0-9+\-.]*):/),o=Array.isArray(i)?i[1]:null;return e.getIn(["scheme",t,n])||e.getIn(["scheme","_defaultScheme"])||o||""});t.canExecuteScheme=function(e,t,n){return["http","https"].indexOf(P(e,t,n))>-1},t.validateBeforeExecute=function(e,t){var n=_(e).getIn(["paths"].concat(r(t),["parameters"]),(0,h.fromJS)([])),i=!0;return n.forEach(function(e){var t=e.get("errors");t&&t.count()&&(i=!1)}),i}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.updateSpec=function(e,t){var n=t.specActions;return function(){e.apply(void 0,arguments),n.parseToJson.apply(n,arguments)}},t.updateJsonSpec=function(e,t){var n=t.specActions;return function(){e.apply(void 0,arguments),n.resolveSpec.apply(n,arguments)}},t.executeRequest=function(e,t){var n=t.specActions;return function(t){return n.logRequest(t),e(t)}}},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getComponents,n=e.getStore,r=e.getSystem,i=o.getComponent,s=o.render,u=o.makeMappedContainer,c=(0,a.memoize)(i.bind(null,r,n,t)),l=(0,a.memoize)(u.bind(null,r,n,c,t));return{rootInjects:{getComponent:c,makeMappedContainer:l,render:s.bind(null,r,n,i,t)}}};var i=n(620),o=r(i),a=n(335)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0}),t.getComponent=t.render=t.makeMappedContainer=void 0;var s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u=Object.assign||function(e){for(var t=1;t1){for(var y=Array(m),v=0;v1){for(var _=Array(g),b=0;b8&&x<=11),S=32,E=String.fromCharCode(S),C={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["topCompositionEnd","topKeyPress","topTextInput","topPaste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:["topBlur","topCompositionEnd","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",captured:"onCompositionStartCapture"},dependencies:["topBlur","topCompositionStart","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:["topBlur","topCompositionUpdate","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]}},A=!1,T=null,O={eventTypes:C,extractEvents:function(e,t,n,r){return[c(e,t,n,r),f(e,t,n,r)]}};e.exports=O},function(e,t,n){"use strict";function r(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return v(e,r)}function i(e,t,n){var i=r(e,n,t);i&&(n._dispatchListeners=m(n._dispatchListeners,i),n._dispatchInstances=m(n._dispatchInstances,e))}function o(e){e&&e.dispatchConfig.phasedRegistrationNames&&d.traverseTwoPhase(e._targetInst,i,e)}function a(e){if(e&&e.dispatchConfig.phasedRegistrationNames){var t=e._targetInst,n=t?d.getParentInstance(t):null;d.traverseTwoPhase(n,i,e)}}function s(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,i=v(e,r);i&&(n._dispatchListeners=m(n._dispatchListeners,i),n._dispatchInstances=m(n._dispatchInstances,e))}}function u(e){e&&e.dispatchConfig.registrationName&&s(e._targetInst,null,e)}function c(e){y(e,o)}function l(e){y(e,a)}function p(e,t,n,r){d.traverseEnterLeave(n,r,s,e,t)}function f(e){y(e,u)}var h=n(661),d=n(663),m=n(665),y=n(666),v=(n(630),h.getListener),g={accumulateTwoPhaseDispatches:c,accumulateTwoPhaseDispatchesSkipTarget:l,accumulateDirectDispatches:f,accumulateEnterLeaveDispatches:p};e.exports=g},function(e,t,n){"use strict";function r(e){return"button"===e||"input"===e||"select"===e||"textarea"===e}function i(e,t,n){switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":return!(!n.disabled||!r(t));default:return!1}}var o=n(654),a=n(662),s=n(663),u=n(664),c=n(665),l=n(666),p=(n(627),{}),f=null,h=function(e,t){e&&(s.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e))},d=function(e){return h(e,!0)},m=function(e){return h(e,!1)},y=function(e){return"."+e._rootNodeID},v={injection:{injectEventPluginOrder:a.injectEventPluginOrder,injectEventPluginsByName:a.injectEventPluginsByName},putListener:function(e,t,n){"function"!=typeof n?o("94",t,typeof n):void 0;var r=y(e),i=p[t]||(p[t]={});i[r]=n;var s=a.registrationNameModules[t];s&&s.didPutListener&&s.didPutListener(e,t,n)},getListener:function(e,t){var n=p[t];if(i(t,e._currentElement.type,e._currentElement.props))return null;var r=y(e);return n&&n[r]},deleteListener:function(e,t){var n=a.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t);var r=p[t];if(r){var i=y(e);delete r[i]}},deleteAllListeners:function(e){var t=y(e);for(var n in p)if(p.hasOwnProperty(n)&&p[n][t]){var r=a.registrationNameModules[n];r&&r.willDeleteListener&&r.willDeleteListener(e,n),delete p[n][t]}},extractEvents:function(e,t,n,r){for(var i,o=a.plugins,s=0;s-1?void 0:a("96",e),!c.plugins[n]){t.extractEvents?void 0:a("97",e),c.plugins[n]=t;var r=t.eventTypes;for(var o in r)i(r[o],t,o)?void 0:a("98",o,e)}}}function i(e,t,n){c.eventNameDispatchConfigs.hasOwnProperty(n)?a("99",n):void 0,c.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var i in r)if(r.hasOwnProperty(i)){var s=r[i];o(s,t,n)}return!0}return!!e.registrationName&&(o(e.registrationName,t,n),!0)}function o(e,t,n){c.registrationNameModules[e]?a("100",e):void 0,c.registrationNameModules[e]=t,c.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var a=n(654),s=(n(627),null),u={},c={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},possibleRegistrationNames:null,injectEventPluginOrder:function(e){s?a("101"):void 0,s=Array.prototype.slice.call(e),r()},injectEventPluginsByName:function(e){var t=!1;for(var n in e)if(e.hasOwnProperty(n)){var i=e[n];u.hasOwnProperty(n)&&u[n]===i||(u[n]?a("102",n):void 0,u[n]=i,t=!0)}t&&r()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return c.registrationNameModules[t.registrationName]||null;if(void 0!==t.phasedRegistrationNames){var n=t.phasedRegistrationNames; +for(var r in n)if(n.hasOwnProperty(r)){var i=c.registrationNameModules[n[r]];if(i)return i}}return null},_resetEventPlugins:function(){s=null;for(var e in u)u.hasOwnProperty(e)&&delete u[e];c.plugins.length=0;var t=c.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=c.registrationNameModules;for(var i in r)r.hasOwnProperty(i)&&delete r[i]}};e.exports=c},function(e,t,n){"use strict";function r(e){return"topMouseUp"===e||"topTouchEnd"===e||"topTouchCancel"===e}function i(e){return"topMouseMove"===e||"topTouchMove"===e}function o(e){return"topMouseDown"===e||"topTouchStart"===e}function a(e,t,n,r){var i=e.type||"unknown-event";e.currentTarget=v.getNodeFromInstance(r),t?m.invokeGuardedCallbackWithCatch(i,n,e):m.invokeGuardedCallback(i,n,e),e.currentTarget=null}function s(e,t){var n=e._dispatchListeners,r=e._dispatchInstances;if(Array.isArray(n))for(var i=0;i1?1-t:void 0;return this._fallbackText=i.slice(e,s),this._fallbackText}}),o.addPoolingTo(r),e.exports=r},[1484,654],function(e,t,n){"use strict";function r(){return!o&&i.canUseDOM&&(o="textContent"in document.documentElement?"textContent":"innerText"),o}var i=n(667),o=null;e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=n(672),o={data:null};i.augmentClass(r,o),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){this.dispatchConfig=e,this._targetInst=t,this.nativeEvent=n;var i=this.constructor.Interface;for(var o in i)if(i.hasOwnProperty(o)){var s=i[o];s?this[o]=s(n):"target"===o?this.target=r:this[o]=n[o]}var u=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;return u?this.isDefaultPrevented=a.thatReturnsTrue:this.isDefaultPrevented=a.thatReturnsFalse,this.isPropagationStopped=a.thatReturnsFalse,this}var i=n(623),o=n(669),a=n(631),s=(n(630),"function"==typeof Proxy,["dispatchConfig","_targetInst","nativeEvent","isDefaultPrevented","isPropagationStopped","_dispatchListeners","_dispatchInstances"]),u={type:null,target:null,currentTarget:a.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};i(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=a.thatReturnsTrue)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=a.thatReturnsTrue)},persist:function(){this.isPersistent=a.thatReturnsTrue},isPersistent:a.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;for(var n=0;n8));var j=!1;x.canUseDOM&&(j=C("input")&&(!document.documentMode||document.documentMode>11));var R={get:function(){return P.get.call(this)},set:function(e){M=""+e,P.set.call(this,e)}},N={eventTypes:T,extractEvents:function(e,t,n,i){var o,a,s=t?w.getNodeFromInstance(t):window;if(r(s)?I?o=u:a=c:A(s)?j?o=h:(o=m,a=d):y(s)&&(o=v),o){var l=o(e,t);if(l){var p=S.getPooled(T.change,l,n,i);return p.type="change",b.accumulateTwoPhaseDispatches(p),p}}a&&a(e,s,t),"topBlur"===e&&g(t,s)}};e.exports=N},function(e,t,n){"use strict";function r(){A.ReactReconcileTransaction&&x?void 0:l("123")}function i(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=f.getPooled(),this.reconcileTransaction=A.ReactReconcileTransaction.getPooled(!0)}function o(e,t,n,i,o,a){return r(),x.batchedUpdates(e,t,n,i,o,a)}function a(e,t){return e._mountOrder-t._mountOrder}function s(e){var t=e.dirtyComponentsLength;t!==v.length?l("124",t,v.length):void 0,v.sort(a),g++;for(var n=0;n]/,u=n(698),c=u(function(e,t){if(e.namespaceURI!==o.svg||"innerHTML"in e)e.innerHTML=t;else{r=r||document.createElement("div"),r.innerHTML=""+t+"";for(var n=r.firstChild;n.firstChild;)e.appendChild(n.firstChild)}});if(i.canUseDOM){var l=document.createElement("div");l.innerHTML=" ",""===l.innerHTML&&(c=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),a.test(t)||"<"===t[0]&&s.test(t)){e.innerHTML=String.fromCharCode(65279)+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t}),l=null}e.exports=c},function(e,t){"use strict";var n=function(e){return"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(t,n,r,i){MSApp.execUnsafeLocalFunction(function(){return e(t,n,r,i)})}:e};e.exports=n},function(e,t,n){"use strict";var r=n(667),i=n(700),o=n(697),a=function(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&3===n.nodeType)return void(n.nodeValue=t)}e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(a=function(e,t){return 3===e.nodeType?void(e.nodeValue=t):void o(e,i(t))})),e.exports=a},function(e,t){"use strict";function n(e){var t=""+e,n=i.exec(t);if(!n)return t;var r,o="",a=0,s=0;for(a=n.index;a]/;e.exports=r},function(e,t,n){"use strict";var r=n(654),i=n(695),o=n(667),a=n(702),s=n(631),u=(n(627),{dangerouslyReplaceNodeWithMarkup:function(e,t){if(o.canUseDOM?void 0:r("56"),t?void 0:r("57"),"HTML"===e.nodeName?r("58"):void 0,"string"==typeof t){var n=a(t,s)[0];e.parentNode.replaceChild(n,e)}else i.replaceChildWithTree(e,t)}});e.exports=u},function(e,t,n){"use strict";function r(e){var t=e.match(l);return t&&t[1].toLowerCase()}function i(e,t){var n=c;c?void 0:u(!1);var i=r(e),o=i&&s(i);if(o){n.innerHTML=o[1]+e+o[2];for(var l=o[0];l--;)n=n.lastChild}else n.innerHTML=e;var p=n.getElementsByTagName("script");p.length&&(t?void 0:u(!1),a(p).forEach(t));for(var f=Array.from(n.childNodes);n.lastChild;)n.removeChild(n.lastChild);return f}var o=n(667),a=n(703),s=n(704),u=n(627),c=o.canUseDOM?document.createElement("div"):null,l=/^\s*<(\w+)/;e.exports=i},function(e,t,n){"use strict";function r(e){var t=e.length;if(Array.isArray(e)||"object"!=typeof e&&"function"!=typeof e?a(!1):void 0,"number"!=typeof t?a(!1):void 0,0===t||t-1 in e?void 0:a(!1),"function"==typeof e.callee?a(!1):void 0,e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(e){}for(var n=Array(t),r=0;r":a.innerHTML="<"+e+">",s[e]=!a.firstChild),s[e]?f[e]:null}var i=n(667),o=n(627),a=i.canUseDOM?document.createElement("div"):null,s={},u=[1,'"],c=[1,"","
"],l=[3,"","
"],p=[1,'',""],f={"*":[1,"?
","
"],area:[1,"",""],col:[2,"","
"],legend:[1,"
","
"],param:[1,"",""],tr:[2,"","
"],optgroup:u,option:u,caption:c,colgroup:c,tbody:c,tfoot:c,thead:c,td:l,th:l},h=["circle","clipPath","defs","ellipse","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","text","tspan"];h.forEach(function(e){f[e]=p,s[e]=!0}),e.exports=r},function(e,t,n){"use strict";var r=n(694),i=n(653),o={dangerouslyProcessChildrenUpdates:function(e,t){var n=i.getNodeFromInstance(e);r.processUpdates(n,t)}};e.exports=o},function(e,t,n){"use strict";function r(e){if(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" This DOM node was rendered by `"+n+"`."}}return""}function i(e,t){t&&(G[e._tag]&&(null!=t.children||null!=t.dangerouslySetInnerHTML?m("137",e._tag,e._currentElement._owner?" Check the render method of "+e._currentElement._owner.getName()+".":""):void 0),null!=t.dangerouslySetInnerHTML&&(null!=t.children?m("60"):void 0,"object"==typeof t.dangerouslySetInnerHTML&&U in t.dangerouslySetInnerHTML?void 0:m("61")),null!=t.style&&"object"!=typeof t.style?m("62",r(e)):void 0)}function o(e,t,n,r){if(!(r instanceof I)){var i=e._hostContainerInfo,o=i._node&&i._node.nodeType===K,s=o?i._node:i._ownerDocument;B(t,s),r.getReactMountReady().enqueue(a,{inst:e,registrationName:t,listener:n})}}function a(){var e=this;k.putListener(e.inst,e.registrationName,e.listener)}function s(){var e=this;T.postMountWrapper(e)}function u(){var e=this;M.postMountWrapper(e)}function c(){var e=this;O.postMountWrapper(e)}function l(){var e=this;e._rootNodeID?void 0:m("63");var t=F(e);switch(t?void 0:m("64"),e._tag){case"iframe":case"object":e._wrapperState.listeners=[E.trapBubbledEvent("topLoad","load",t)];break;case"video":case"audio":e._wrapperState.listeners=[];for(var n in V)V.hasOwnProperty(n)&&e._wrapperState.listeners.push(E.trapBubbledEvent(n,V[n],t));break;case"source":e._wrapperState.listeners=[E.trapBubbledEvent("topError","error",t)];break;case"img":e._wrapperState.listeners=[E.trapBubbledEvent("topError","error",t),E.trapBubbledEvent("topLoad","load",t)];break;case"form":e._wrapperState.listeners=[E.trapBubbledEvent("topReset","reset",t),E.trapBubbledEvent("topSubmit","submit",t)];break;case"input":case"select":case"textarea":e._wrapperState.listeners=[E.trapBubbledEvent("topInvalid","invalid",t)]}}function p(){D.postUpdateWrapper(this)}function f(e){$.call(Y,e)||(X.test(e)?void 0:m("65",e),Y[e]=!0)}function h(e,t){return e.indexOf("-")>=0||null!=t.is}function d(e){var t=e.type;f(t),this._currentElement=e,this._tag=t.toLowerCase(),this._namespaceURI=null,this._renderedChildren=null,this._previousStyle=null,this._previousStyleCopy=null,this._hostNode=null,this._hostParent=null,this._rootNodeID=0,this._domID=0,this._hostContainerInfo=null,this._wrapperState=null,this._topLevelWrapper=null,this._flags=0}var m=n(654),y=n(623),v=n(707),g=n(709),_=n(695),b=n(696),x=n(655),w=n(717),k=n(661),S=n(662),E=n(719),C=n(656),A=n(653),T=n(722),O=n(725),D=n(726),M=n(727),P=(n(681),n(728)),I=n(746),j=(n(631),n(700)),R=(n(627),n(684),n(735),n(749),n(630),C),N=k.deleteListener,F=A.getNodeFromInstance,B=E.listenTo,L=S.registrationNameModules,z={string:!0,number:!0},q="style",U="__html",W={children:null,dangerouslySetInnerHTML:null,suppressContentEditableWarning:null},K=11,V={topAbort:"abort",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topSeeked:"seeked",topSeeking:"seeking",topStalled:"stalled",topSuspend:"suspend",topTimeUpdate:"timeupdate",topVolumeChange:"volumechange",topWaiting:"waiting"},H={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},J={listing:!0,pre:!0,textarea:!0},G=y({menuitem:!0},H),X=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,Y={},$={}.hasOwnProperty,Z=1;d.displayName="ReactDOMComponent",d.Mixin={mountComponent:function(e,t,n,r){this._rootNodeID=Z++,this._domID=n._idCounter++,this._hostParent=t,this._hostContainerInfo=n;var o=this._currentElement.props;switch(this._tag){case"audio":case"form":case"iframe":case"img":case"link":case"object":case"source":case"video":this._wrapperState={listeners:null},e.getReactMountReady().enqueue(l,this);break;case"input":T.mountWrapper(this,o,t),o=T.getHostProps(this,o),e.getReactMountReady().enqueue(l,this);break;case"option":O.mountWrapper(this,o,t),o=O.getHostProps(this,o);break;case"select":D.mountWrapper(this,o,t),o=D.getHostProps(this,o),e.getReactMountReady().enqueue(l,this);break;case"textarea":M.mountWrapper(this,o,t),o=M.getHostProps(this,o),e.getReactMountReady().enqueue(l,this)}i(this,o);var a,p;null!=t?(a=t._namespaceURI,p=t._tag):n._tag&&(a=n._namespaceURI,p=n._tag),(null==a||a===b.svg&&"foreignobject"===p)&&(a=b.html),a===b.html&&("svg"===this._tag?a=b.svg:"math"===this._tag&&(a=b.mathml)),this._namespaceURI=a;var f;if(e.useCreateElement){var h,d=n._ownerDocument;if(a===b.html)if("script"===this._tag){var m=d.createElement("div"),y=this._currentElement.type;m.innerHTML="<"+y+">",h=m.removeChild(m.firstChild)}else h=o.is?d.createElement(this._currentElement.type,o.is):d.createElement(this._currentElement.type);else h=d.createElementNS(a,this._currentElement.type);A.precacheNode(this,h),this._flags|=R.hasCachedChildNodes,this._hostParent||w.setAttributeForRoot(h),this._updateDOMProperties(null,o,e);var g=_(h);this._createInitialChildren(e,o,r,g),f=g}else{var x=this._createOpenTagMarkupAndPutListeners(e,o),k=this._createContentMarkup(e,o,r);f=!k&&H[this._tag]?x+"/>":x+">"+k+""}switch(this._tag){case"input":e.getReactMountReady().enqueue(s,this),o.autoFocus&&e.getReactMountReady().enqueue(v.focusDOMComponent,this);break;case"textarea":e.getReactMountReady().enqueue(u,this),o.autoFocus&&e.getReactMountReady().enqueue(v.focusDOMComponent,this);break;case"select":o.autoFocus&&e.getReactMountReady().enqueue(v.focusDOMComponent,this);break;case"button":o.autoFocus&&e.getReactMountReady().enqueue(v.focusDOMComponent,this);break;case"option":e.getReactMountReady().enqueue(c,this)}return f},_createOpenTagMarkupAndPutListeners:function(e,t){var n="<"+this._currentElement.type;for(var r in t)if(t.hasOwnProperty(r)){var i=t[r];if(null!=i)if(L.hasOwnProperty(r))i&&o(this,r,i,e);else{r===q&&(i&&(i=this._previousStyleCopy=y({},t.style)),i=g.createMarkupForStyles(i,this));var a=null;null!=this._tag&&h(this._tag,t)?W.hasOwnProperty(r)||(a=w.createMarkupForCustomAttribute(r,i)):a=w.createMarkupForProperty(r,i),a&&(n+=" "+a)}}return e.renderToStaticMarkup?n:(this._hostParent||(n+=" "+w.createMarkupForRoot()),n+=" "+w.createMarkupForID(this._domID))},_createContentMarkup:function(e,t,n){var r="",i=t.dangerouslySetInnerHTML;if(null!=i)null!=i.__html&&(r=i.__html);else{var o=z[typeof t.children]?t.children:null,a=null!=o?null:t.children;if(null!=o)r=j(o);else if(null!=a){var s=this.mountChildren(a,e,n);r=s.join("")}}return J[this._tag]&&"\n"===r.charAt(0)?"\n"+r:r},_createInitialChildren:function(e,t,n,r){var i=t.dangerouslySetInnerHTML;if(null!=i)null!=i.__html&&_.queueHTML(r,i.__html);else{var o=z[typeof t.children]?t.children:null,a=null!=o?null:t.children;if(null!=o)""!==o&&_.queueText(r,o);else if(null!=a)for(var s=this.mountChildren(a,e,n),u=0;u0&&r.length<20?n+" (keys: "+r.join(", ")+")":n}function o(e,t){var n=s.get(e);if(!n){return null}return n}var a=n(654),s=(n(629),n(730)),u=(n(681),n(675)),c=(n(627),n(630),{isMounted:function(e){var t=s.get(e);return!!t&&!!t._renderedComponent},enqueueCallback:function(e,t,n){c.validateCallback(t,n);var i=o(e);return i?(i._pendingCallbacks?i._pendingCallbacks.push(t):i._pendingCallbacks=[t],void r(i)):null},enqueueCallbackInternal:function(e,t){e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],r(e)},enqueueForceUpdate:function(e){var t=o(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,r(t))},enqueueReplaceState:function(e,t,n){var i=o(e,"replaceState");i&&(i._pendingStateQueue=[t],i._pendingReplaceState=!0,void 0!==n&&null!==n&&(c.validateCallback(n,"replaceState"),i._pendingCallbacks?i._pendingCallbacks.push(n):i._pendingCallbacks=[n]),r(i))},enqueueSetState:function(e,t){var n=o(e,"setState");if(n){var i=n._pendingStateQueue||(n._pendingStateQueue=[]);i.push(t),r(n)}},enqueueElementInternal:function(e,t,n){e._pendingElement=t,e._context=n,r(e)},validateCallback:function(e,t){e&&"function"!=typeof e?a("122",t,i(e)):void 0}});e.exports=c},function(e,t,n){"use strict";var r=(n(623),n(631)),i=(n(630),r);e.exports=i},function(e,t,n){"use strict";var r=n(623),i=n(695),o=n(653),a=function(e){this._currentElement=null,this._hostNode=null,this._hostParent=null,this._hostContainerInfo=null,this._domID=0};r(a.prototype,{mountComponent:function(e,t,n,r){var a=n._idCounter++;this._domID=a,this._hostParent=t,this._hostContainerInfo=n;var s=" react-empty: "+this._domID+" ";if(e.useCreateElement){var u=n._ownerDocument,c=u.createComment(s);return o.precacheNode(this,c),i(c)}return e.renderToStaticMarkup?"":""},receiveComponent:function(){},getHostNode:function(){return o.getNodeFromInstance(this)},unmountComponent:function(){o.uncacheNode(this)}}),e.exports=a},function(e,t,n){"use strict";function r(e,t){"_hostNode"in e?void 0:u("33"),"_hostNode"in t?void 0:u("33");for(var n=0,r=e;r;r=r._hostParent)n++;for(var i=0,o=t;o;o=o._hostParent)i++;for(;n-i>0;)e=e._hostParent,n--;for(;i-n>0;)t=t._hostParent,i--;for(var a=n;a--;){if(e===t)return e;e=e._hostParent,t=t._hostParent}return null}function i(e,t){"_hostNode"in e?void 0:u("35"),"_hostNode"in t?void 0:u("35");for(;t;){if(t===e)return!0;t=t._hostParent}return!1}function o(e){return"_hostNode"in e?void 0:u("36"),e._hostParent}function a(e,t,n){for(var r=[];e;)r.push(e),e=e._hostParent;var i;for(i=r.length;i-- >0;)t(r[i],"captured",n);for(i=0;i0;)n(u[c],"captured",o)}var u=n(654);n(627);e.exports={isAncestor:i,getLowestCommonAncestor:r,getParentInstance:o,traverseTwoPhase:a,traverseEnterLeave:s}},function(e,t,n){"use strict";var r=n(654),i=n(623),o=n(694),a=n(695),s=n(653),u=n(700),c=(n(627),n(749),function(e){this._currentElement=e,this._stringText=""+e,this._hostNode=null,this._hostParent=null,this._domID=0,this._mountIndex=0,this._closingComment=null,this._commentNodes=null});i(c.prototype,{mountComponent:function(e,t,n,r){var i=n._idCounter++,o=" react-text: "+i+" ",c=" /react-text ";if(this._domID=i,this._hostParent=t,e.useCreateElement){var l=n._ownerDocument,p=l.createComment(o),f=l.createComment(c),h=a(l.createDocumentFragment());return a.queueChild(h,a(p)),this._stringText&&a.queueChild(h,a(l.createTextNode(this._stringText))),a.queueChild(h,a(f)),s.precacheNode(this,p),this._closingComment=f,h}var d=u(this._stringText);return e.renderToStaticMarkup?d:""+d+""; +},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e;if(n!==this._stringText){this._stringText=n;var r=this.getHostNode();o.replaceDelimitedText(r[0],r[1],n)}}},getHostNode:function(){var e=this._commentNodes;if(e)return e;if(!this._closingComment)for(var t=s.getNodeFromInstance(this),n=t.nextSibling;;){if(null==n?r("67",this._domID):void 0,8===n.nodeType&&" /react-text "===n.nodeValue){this._closingComment=n;break}n=n.nextSibling}return e=[this._hostNode,this._closingComment],this._commentNodes=e,e},unmountComponent:function(){this._closingComment=null,this._commentNodes=null,s.uncacheNode(this)}}),e.exports=c},function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var i=n(623),o=n(675),a=n(682),s=n(631),u={initialize:s,close:function(){f.isBatchingUpdates=!1}},c={initialize:s,close:o.flushBatchedUpdates.bind(o)},l=[c,u];i(r.prototype,a,{getTransactionWrappers:function(){return l}});var p=new r,f={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,i,o){var a=f.isBatchingUpdates;return f.isBatchingUpdates=!0,a?e(t,n,r,i,o):p.perform(e,null,t,n,r,i,o)}};e.exports=f},function(e,t,n){"use strict";function r(e){for(;e._hostParent;)e=e._hostParent;var t=p.getNodeFromInstance(e),n=t.parentNode;return p.getClosestInstanceFromNode(n)}function i(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function o(e){var t=h(e.nativeEvent),n=p.getClosestInstanceFromNode(t),i=n;do e.ancestors.push(i),i=i&&r(i);while(i);for(var o=0;ot.end?(n=t.end,r=t.start):(n=t.start,r=t.end),i.moveToElementText(e),i.moveStart("character",n),i.setEndPoint("EndToStart",i),i.moveEnd("character",r-n),i.select()}function s(e,t){if(window.getSelection){var n=window.getSelection(),r=e[l()].length,i=Math.min(t.start,r),o=void 0===t.end?i:Math.min(t.end,r);if(!n.extend&&i>o){var a=o;o=i,i=a}var s=c(e,i),u=c(e,o);if(s&&u){var p=document.createRange();p.setStart(s.node,s.offset),n.removeAllRanges(),i>o?(n.addRange(p),n.extend(u.node,u.offset)):(p.setEnd(u.node,u.offset),n.addRange(p))}}}var u=n(667),c=n(761),l=n(670),p=u.canUseDOM&&"selection"in document&&!("getSelection"in window),f={getOffsets:p?i:o,setOffsets:p?a:s};e.exports=f},function(e,t){"use strict";function n(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function r(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function i(e,t){for(var i=n(e),o=0,a=0;i;){if(3===i.nodeType){if(a=o+i.textContent.length,o<=t&&a>=t)return{node:i,offset:t-o};o=a}i=n(r(i))}}e.exports=i},function(e,t,n){"use strict";function r(e,t){return!(!e||!t)&&(e===t||!i(e)&&(i(t)?r(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}var i=n(763);e.exports=r},function(e,t,n){"use strict";function r(e){return i(e)&&3==e.nodeType}var i=n(764);e.exports=r},function(e,t){"use strict";function n(e){var t=e?e.ownerDocument||e:document,n=t.defaultView||window;return!(!e||!("function"==typeof n.Node?e instanceof n.Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}e.exports=n},function(e,t){"use strict";function n(e){if(e=e||("undefined"!=typeof document?document:void 0),"undefined"==typeof e)return null;try{return e.activeElement||e.body}catch(t){return e.body}}e.exports=n},function(e,t){"use strict";var n={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},r={accentHeight:"accent-height",accumulate:0,additive:0,alignmentBaseline:"alignment-baseline",allowReorder:"allowReorder",alphabetic:0,amplitude:0,arabicForm:"arabic-form",ascent:0,attributeName:"attributeName",attributeType:"attributeType",autoReverse:"autoReverse",azimuth:0,baseFrequency:"baseFrequency",baseProfile:"baseProfile",baselineShift:"baseline-shift",bbox:0,begin:0,bias:0,by:0,calcMode:"calcMode",capHeight:"cap-height",clip:0,clipPath:"clip-path",clipRule:"clip-rule",clipPathUnits:"clipPathUnits",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",contentScriptType:"contentScriptType",contentStyleType:"contentStyleType",cursor:0,cx:0,cy:0,d:0,decelerate:0,descent:0,diffuseConstant:"diffuseConstant",direction:0,display:0,divisor:0,dominantBaseline:"dominant-baseline",dur:0,dx:0,dy:0,edgeMode:"edgeMode",elevation:0,enableBackground:"enable-background",end:0,exponent:0,externalResourcesRequired:"externalResourcesRequired",fill:0,fillOpacity:"fill-opacity",fillRule:"fill-rule",filter:0,filterRes:"filterRes",filterUnits:"filterUnits",floodColor:"flood-color",floodOpacity:"flood-opacity",focusable:0,fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",format:0,from:0,fx:0,fy:0,g1:0,g2:0,glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",glyphRef:"glyphRef",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",hanging:0,horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",ideographic:0,imageRendering:"image-rendering",in:0,in2:0,intercept:0,k:0,k1:0,k2:0,k3:0,k4:0,kernelMatrix:"kernelMatrix",kernelUnitLength:"kernelUnitLength",kerning:0,keyPoints:"keyPoints",keySplines:"keySplines",keyTimes:"keyTimes",lengthAdjust:"lengthAdjust",letterSpacing:"letter-spacing",lightingColor:"lighting-color",limitingConeAngle:"limitingConeAngle",local:0,markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",markerHeight:"markerHeight",markerUnits:"markerUnits",markerWidth:"markerWidth",mask:0,maskContentUnits:"maskContentUnits",maskUnits:"maskUnits",mathematical:0,mode:0,numOctaves:"numOctaves",offset:0,opacity:0,operator:0,order:0,orient:0,orientation:0,origin:0,overflow:0,overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pathLength:"pathLength",patternContentUnits:"patternContentUnits",patternTransform:"patternTransform",patternUnits:"patternUnits",pointerEvents:"pointer-events",points:0,pointsAtX:"pointsAtX",pointsAtY:"pointsAtY",pointsAtZ:"pointsAtZ",preserveAlpha:"preserveAlpha",preserveAspectRatio:"preserveAspectRatio",primitiveUnits:"primitiveUnits",r:0,radius:0,refX:"refX",refY:"refY",renderingIntent:"rendering-intent",repeatCount:"repeatCount",repeatDur:"repeatDur",requiredExtensions:"requiredExtensions",requiredFeatures:"requiredFeatures",restart:0,result:0,rotate:0,rx:0,ry:0,scale:0,seed:0,shapeRendering:"shape-rendering",slope:0,spacing:0,specularConstant:"specularConstant",specularExponent:"specularExponent",speed:0,spreadMethod:"spreadMethod",startOffset:"startOffset",stdDeviation:"stdDeviation",stemh:0,stemv:0,stitchTiles:"stitchTiles",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",string:0,stroke:0,strokeDasharray:"stroke-dasharray",strokeDashoffset:"stroke-dashoffset",strokeLinecap:"stroke-linecap",strokeLinejoin:"stroke-linejoin",strokeMiterlimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",surfaceScale:"surfaceScale",systemLanguage:"systemLanguage",tableValues:"tableValues",targetX:"targetX",targetY:"targetY",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",textLength:"textLength",to:0,transform:0,u1:0,u2:0,underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicode:0,unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",values:0,vectorEffect:"vector-effect",version:0,vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",viewBox:"viewBox",viewTarget:"viewTarget",visibility:0,widths:0,wordSpacing:"word-spacing",writingMode:"writing-mode",x:0,xHeight:"x-height",x1:0,x2:0,xChannelSelector:"xChannelSelector",xlinkActuate:"xlink:actuate",xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlns:0,xmlnsXlink:"xmlns:xlink",xmlLang:"xml:lang",xmlSpace:"xml:space",y:0,y1:0,y2:0,yChannelSelector:"yChannelSelector",z:0,zoomAndPan:"zoomAndPan"},i={Properties:{},DOMAttributeNamespaces:{xlinkActuate:n.xlink,xlinkArcrole:n.xlink,xlinkHref:n.xlink,xlinkRole:n.xlink,xlinkShow:n.xlink,xlinkTitle:n.xlink,xlinkType:n.xlink,xmlBase:n.xml,xmlLang:n.xml,xmlSpace:n.xml},DOMAttributeNames:{}};Object.keys(r).forEach(function(e){i.Properties[e]=0,r[e]&&(i.DOMAttributeNames[e]=r[e])}),e.exports=i},function(e,t,n){"use strict";function r(e){if("selectionStart"in e&&u.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function i(e,t){if(g||null==m||m!==l())return null;var n=r(m);if(!v||!f(v,n)){v=n;var i=c.getPooled(d.select,y,e,t);return i.type="select",i.target=m,o.accumulateTwoPhaseDispatches(i),i}return null}var o=n(660),a=n(667),s=n(653),u=n(759),c=n(672),l=n(765),p=n(685),f=n(735),h=a.canUseDOM&&"documentMode"in document&&document.documentMode<=11,d={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:["topBlur","topContextMenu","topFocus","topKeyDown","topKeyUp","topMouseDown","topMouseUp","topSelectionChange"]}},m=null,y=null,v=null,g=!1,_=!1,b={eventTypes:d,extractEvents:function(e,t,n,r){if(!_)return null;var o=t?s.getNodeFromInstance(t):window;switch(e){case"topFocus":(p(o)||"true"===o.contentEditable)&&(m=o,y=t,v=null);break;case"topBlur":m=null,y=null,v=null;break;case"topMouseDown":g=!0;break;case"topContextMenu":case"topMouseUp":return g=!1,i(n,r);case"topSelectionChange":if(h)break;case"topKeyDown":case"topKeyUp":return i(n,r)}return null},didPutListener:function(e,t,n){"onSelect"===t&&(_=!0)}};e.exports=b},function(e,t,n){"use strict";function r(e){return"."+e._rootNodeID}function i(e){return"button"===e||"input"===e||"select"===e||"textarea"===e}var o=n(654),a=n(755),s=n(660),u=n(653),c=n(769),l=n(770),p=n(672),f=n(771),h=n(772),d=n(688),m=n(775),y=n(776),v=n(777),g=n(689),_=n(778),b=n(631),x=n(773),w=(n(627),{}),k={};["abort","animationEnd","animationIteration","animationStart","blur","canPlay","canPlayThrough","click","contextMenu","copy","cut","doubleClick","drag","dragEnd","dragEnter","dragExit","dragLeave","dragOver","dragStart","drop","durationChange","emptied","encrypted","ended","error","focus","input","invalid","keyDown","keyPress","keyUp","load","loadedData","loadedMetadata","loadStart","mouseDown","mouseMove","mouseOut","mouseOver","mouseUp","paste","pause","play","playing","progress","rateChange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeUpdate","touchCancel","touchEnd","touchMove","touchStart","transitionEnd","volumeChange","waiting","wheel"].forEach(function(e){var t=e[0].toUpperCase()+e.slice(1),n="on"+t,r="top"+t,i={phasedRegistrationNames:{bubbled:n,captured:n+"Capture"},dependencies:[r]};w[e]=i,k[r]=i});var S={},E={eventTypes:w,extractEvents:function(e,t,n,r){var i=k[e];if(!i)return null;var a;switch(e){case"topAbort":case"topCanPlay":case"topCanPlayThrough":case"topDurationChange":case"topEmptied":case"topEncrypted":case"topEnded":case"topError":case"topInput":case"topInvalid":case"topLoad":case"topLoadedData":case"topLoadedMetadata":case"topLoadStart":case"topPause":case"topPlay":case"topPlaying":case"topProgress":case"topRateChange":case"topReset":case"topSeeked":case"topSeeking":case"topStalled":case"topSubmit":case"topSuspend":case"topTimeUpdate":case"topVolumeChange":case"topWaiting":a=p;break;case"topKeyPress":if(0===x(n))return null;case"topKeyDown":case"topKeyUp":a=h;break;case"topBlur":case"topFocus":a=f;break;case"topClick":if(2===n.button)return null;case"topDoubleClick":case"topMouseDown":case"topMouseMove":case"topMouseUp":case"topMouseOut":case"topMouseOver":case"topContextMenu":a=d;break;case"topDrag":case"topDragEnd":case"topDragEnter":case"topDragExit":case"topDragLeave":case"topDragOver":case"topDragStart":case"topDrop":a=m;break;case"topTouchCancel":case"topTouchEnd":case"topTouchMove":case"topTouchStart":a=y;break;case"topAnimationEnd":case"topAnimationIteration":case"topAnimationStart":a=c;break;case"topTransitionEnd":a=v;break;case"topScroll":a=g;break;case"topWheel":a=_;break;case"topCopy":case"topCut":case"topPaste":a=l}a?void 0:o("86",e);var u=a.getPooled(i,t,n,r);return s.accumulateTwoPhaseDispatches(u),u},didPutListener:function(e,t,n){if("onClick"===t&&!i(e._tag)){var o=r(e),s=u.getNodeFromInstance(e);S[o]||(S[o]=a.listen(s,"click",b))}},willDeleteListener:function(e,t){if("onClick"===t&&!i(e._tag)){var n=r(e);S[n].remove(),delete S[n]}}};e.exports=E},function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=n(672),o={animationName:null,elapsedTime:null,pseudoElement:null};i.augmentClass(r,o),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=n(672),o={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};i.augmentClass(r,o),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=n(689),o={relatedTarget:null};i.augmentClass(r,o),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=n(689),o=n(773),a=n(774),s=n(691),u={key:a,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:s,charCode:function(e){return"keypress"===e.type?o(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?o(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};i.augmentClass(r,u),e.exports=r},function(e,t){"use strict";function n(e){var t,n=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===n&&(t=13)):t=n,t>=32||13===t?t:0}e.exports=n},function(e,t,n){"use strict";function r(e){if(e.key){var t=o[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=i(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?a[e.keyCode]||"Unidentified":""}var i=n(773),o={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},a={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=n(688),o={dataTransfer:null};i.augmentClass(r,o),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=n(689),o=n(691),a={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:o};i.augmentClass(r,a),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=n(672),o={propertyName:null,elapsedTime:null,pseudoElement:null};i.augmentClass(r,o),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=n(688),o={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};i.augmentClass(r,o),e.exports=r},function(e,t,n){"use strict";function r(e,t){for(var n=Math.min(e.length,t.length),r=0;r.":"function"==typeof t?" Instead of passing a class like Foo, pass React.createElement(Foo) or .":null!=t&&void 0!==t.props?" This may be caused by unintentionally loading two independent copies of React.":"");var a,s=y.createElement(B,{child:t});if(e){var u=w.get(e);a=u._processChildContext(u._context)}else a=A;var l=f(n);if(l){var p=l._currentElement,d=p.props.child;if(D(d,t)){var m=l._renderedComponent.getPublicInstance(),v=r&&function(){r.call(m)};return L._updateRootComponent(l,s,a,n,v),m}L.unmountComponentAtNode(n)}var g=i(n),_=g&&!!o(g),b=c(n),x=_&&!l&&!b,k=L._renderNewRootComponent(s,n,x,a)._renderedComponent.getPublicInstance();return r&&r.call(k),k},render:function(e,t,n){return L._renderSubtreeIntoContainer(null,e,t,n)},unmountComponentAtNode:function(e){l(e)?void 0:h("40");var t=f(e);if(!t){c(e),1===e.nodeType&&e.hasAttribute(P);return!1}return delete N[t._instance.rootID],C.batchedUpdates(u,t,e,!1),!0},_mountImageIntoNode:function(e,t,n,o,a){if(l(t)?void 0:h("41"),o){var s=i(t);if(k.canReuseMarkup(e,s))return void g.precacheNode(n,s);var u=s.getAttribute(k.CHECKSUM_ATTR_NAME);s.removeAttribute(k.CHECKSUM_ATTR_NAME);var c=s.outerHTML;s.setAttribute(k.CHECKSUM_ATTR_NAME,u);var p=e,f=r(p,c),m=" (client) "+p.substring(f-20,f+20)+"\n (server) "+c.substring(f-20,f+20);t.nodeType===j?h("42",m):void 0}if(t.nodeType===j?h("43"):void 0,a.useCreateElement){for(;t.lastChild;)t.removeChild(t.lastChild);d.insertTreeBefore(t,e,null)}else O(t,e),g.precacheNode(n,t.firstChild)}};e.exports=L},function(e,t,n){"use strict";function r(e,t){var n={_topLevelWrapper:e,_idCounter:1,_ownerDocument:t?t.nodeType===i?t:t.ownerDocument:null,_node:t,_tag:t?t.nodeName.toLowerCase():null,_namespaceURI:t?t.namespaceURI:null};return n}var i=(n(749),9);e.exports=r},function(e,t){"use strict";var n={useCreateElement:!0,useFiber:!1};e.exports=n},function(e,t,n){"use strict";var r=n(783),i=/\/?>/,o=/^<\!\-\-/,a={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return o.test(e)?e:e.replace(i," "+a.CHECKSUM_ATTR_NAME+'="'+t+'"$&')},canReuseMarkup:function(e,t){var n=t.getAttribute(a.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var i=r(e);return i===n}};e.exports=a},function(e,t){"use strict";function n(e){for(var t=1,n=0,i=0,o=e.length,a=o&-4;i3&&void 0!==arguments[3]?arguments[3]:{},c=Boolean(e),f=e||S,d=void 0;d="function"==typeof t?t:t?(0,v.default)(t):E;var y=n||C,g=r.pure,_=void 0===g||g,b=r.withRef,w=void 0!==b&&b,O=_&&y!==C,D=T++;return function(e){function t(e,t,n){var r=y(e,t,n);return r}var n="Connect("+s(e)+")",r=function(r){function s(e,t){i(this,s);var a=o(this,r.call(this,e,t));a.version=D,a.store=e.store||t.store,(0,k.default)(a.store,'Could not find "store" in either the context or '+('props of "'+n+'". ')+"Either wrap the root component in a , "+('or explicitly pass "store" as a prop to "'+n+'".'));var u=a.store.getState();return a.state={storeState:u},a.clearCache(),a}return a(s,r),s.prototype.shouldComponentUpdate=function(){return!_||this.haveOwnPropsChanged||this.hasStoreStateChanged},s.prototype.computeStateProps=function(e,t){if(!this.finalMapStateToProps)return this.configureFinalMapState(e,t);var n=e.getState(),r=this.doStatePropsDependOnOwnProps?this.finalMapStateToProps(n,t):this.finalMapStateToProps(n);return r},s.prototype.configureFinalMapState=function(e,t){var n=f(e.getState(),t),r="function"==typeof n;return this.finalMapStateToProps=r?n:f,this.doStatePropsDependOnOwnProps=1!==this.finalMapStateToProps.length,r?this.computeStateProps(e,t):n},s.prototype.computeDispatchProps=function(e,t){if(!this.finalMapDispatchToProps)return this.configureFinalMapDispatch(e,t);var n=e.dispatch,r=this.doDispatchPropsDependOnOwnProps?this.finalMapDispatchToProps(n,t):this.finalMapDispatchToProps(n);return r},s.prototype.configureFinalMapDispatch=function(e,t){var n=d(e.dispatch,t),r="function"==typeof n;return this.finalMapDispatchToProps=r?n:d,this.doDispatchPropsDependOnOwnProps=1!==this.finalMapDispatchToProps.length,r?this.computeDispatchProps(e,t):n},s.prototype.updateStatePropsIfNeeded=function(){var e=this.computeStateProps(this.store,this.props);return(!this.stateProps||!(0,m.default)(e,this.stateProps))&&(this.stateProps=e, +!0)},s.prototype.updateDispatchPropsIfNeeded=function(){var e=this.computeDispatchProps(this.store,this.props);return(!this.dispatchProps||!(0,m.default)(e,this.dispatchProps))&&(this.dispatchProps=e,!0)},s.prototype.updateMergedPropsIfNeeded=function(){var e=t(this.stateProps,this.dispatchProps,this.props);return!(this.mergedProps&&O&&(0,m.default)(e,this.mergedProps))&&(this.mergedProps=e,!0)},s.prototype.isSubscribed=function(){return"function"==typeof this.unsubscribe},s.prototype.trySubscribe=function(){c&&!this.unsubscribe&&(this.unsubscribe=this.store.subscribe(this.handleChange.bind(this)),this.handleChange())},s.prototype.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null)},s.prototype.componentDidMount=function(){this.trySubscribe()},s.prototype.componentWillReceiveProps=function(e){_&&(0,m.default)(e,this.props)||(this.haveOwnPropsChanged=!0)},s.prototype.componentWillUnmount=function(){this.tryUnsubscribe(),this.clearCache()},s.prototype.clearCache=function(){this.dispatchProps=null,this.stateProps=null,this.mergedProps=null,this.haveOwnPropsChanged=!0,this.hasStoreStateChanged=!0,this.haveStatePropsBeenPrecalculated=!1,this.statePropsPrecalculationError=null,this.renderedElement=null,this.finalMapDispatchToProps=null,this.finalMapStateToProps=null},s.prototype.handleChange=function(){if(this.unsubscribe){var e=this.store.getState(),t=this.state.storeState;if(!_||t!==e){if(_&&!this.doStatePropsDependOnOwnProps){var n=u(this.updateStatePropsIfNeeded,this);if(!n)return;n===A&&(this.statePropsPrecalculationError=A.value),this.haveStatePropsBeenPrecalculated=!0}this.hasStoreStateChanged=!0,this.setState({storeState:e})}}},s.prototype.getWrappedInstance=function(){return(0,k.default)(w,"To access the wrapped instance, you need to specify { withRef: true } as the fourth argument of the connect() call."),this.refs.wrappedInstance},s.prototype.render=function(){var t=this.haveOwnPropsChanged,n=this.hasStoreStateChanged,r=this.haveStatePropsBeenPrecalculated,i=this.statePropsPrecalculationError,o=this.renderedElement;if(this.haveOwnPropsChanged=!1,this.hasStoreStateChanged=!1,this.haveStatePropsBeenPrecalculated=!1,this.statePropsPrecalculationError=null,i)throw i;var a=!0,s=!0;_&&o&&(a=n||t&&this.doStatePropsDependOnOwnProps,s=t&&this.doDispatchPropsDependOnOwnProps);var u=!1,c=!1;r?u=!0:a&&(u=this.updateStatePropsIfNeeded()),s&&(c=this.updateDispatchPropsIfNeeded());var f=!0;return f=!!(u||c||t)&&this.updateMergedPropsIfNeeded(),!f&&o?o:(w?this.renderedElement=(0,p.createElement)(e,l({},this.mergedProps,{ref:"wrappedInstance"})):this.renderedElement=(0,p.createElement)(e,this.mergedProps),this.renderedElement)},s}(p.Component);return r.displayName=n,r.WrappedComponent=e,r.contextTypes={store:h.default},r.propTypes={store:h.default},(0,x.default)(r,e)}}t.__esModule=!0;var l=Object.assign||function(e){for(var t=1;t1),t}),s(e,c(e),n),u&&(n=i(n,l|p|f));for(var h=t.length;h--;)o(n,t[h]);return n});e.exports=h},function(e,t,n){function r(e,t,n,A,T,O){var D,I=t&k,j=t&S,N=t&E;if(n&&(D=T?n(e,A,T,O):n(e)),void 0!==D)return D;if(!x(e))return e;var F=_(e);if(F){if(D=y(e),!I)return l(e,D)}else{var B=m(e),L=B==M||B==P;if(b(e))return c(e,I);if(B==R||B==C||L&&!T){if(D=j||L?{}:g(e),!I)return j?f(e,u(D,e)):p(e,s(D,e))}else{if(!Z[B])return T?e:{};D=v(e,B,r,I)}}O||(O=new i);var z=O.get(e);if(z)return z;O.set(e,D);var q=N?j?d:h:j?keysIn:w,U=F?void 0:q(e);return o(U||e,function(i,o){U&&(o=i,i=e[o]),a(D,o,r(i,t,n,o,e,O))}),D}var i=n(403),o=n(801),a=n(802),s=n(805),u=n(807),c=n(811),l=n(812),p=n(813),f=n(816),h=n(819),d=n(821),m=n(438),y=n(822),v=n(823),g=n(833),_=n(346),b=n(426),x=n(374),w=n(421),k=1,S=2,E=4,C="[object Arguments]",A="[object Array]",T="[object Boolean]",O="[object Date]",D="[object Error]",M="[object Function]",P="[object GeneratorFunction]",I="[object Map]",j="[object Number]",R="[object Object]",N="[object RegExp]",F="[object Set]",B="[object String]",L="[object Symbol]",z="[object WeakMap]",q="[object ArrayBuffer]",U="[object DataView]",W="[object Float32Array]",K="[object Float64Array]",V="[object Int8Array]",H="[object Int16Array]",J="[object Int32Array]",G="[object Uint8Array]",X="[object Uint8ClampedArray]",Y="[object Uint16Array]",$="[object Uint32Array]",Z={};Z[C]=Z[A]=Z[q]=Z[U]=Z[T]=Z[O]=Z[W]=Z[K]=Z[V]=Z[H]=Z[J]=Z[I]=Z[j]=Z[R]=Z[N]=Z[F]=Z[B]=Z[L]=Z[G]=Z[X]=Z[Y]=Z[$]=!0,Z[D]=Z[M]=Z[z]=!1,e.exports=r},function(e,t){function n(e,t){for(var n=-1,r=null==e?0:e.length;++n0){if(++t>=r)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var r=800,i=16,o=Date.now;e.exports=n},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return{fn:o}};var i=n(468),o=r(i)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){function t(e){for(var t,n=arguments.length,r=Array(n>1?n-1:0),o=1;o=a&&(t=console)[e].apply(t,r)}var n=e.configs,r={debug:0,info:1,log:2,warn:3,error:4},i=function(e){return r[e]||-1},o=n.logLevel,a=i(o);return t.warn=t.bind(null,"warn"),t.error=t.bind(null,"error"),t.info=t.bind(null,"info"),t.debug=t.bind(null,"debug"),{rootInjects:{log:t}}}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return{fn:{AST:a},components:{JumpToPath:u.default}}};var o=n(851),a=i(o),s=n(881),u=r(s)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){function n(e,t,i){if(!e)return i&&i.start_mark?i.start_mark.line:0;if(t.length&&e.tag===v)for(r=0;r=t.column:t.line===e.start_mark.line?t.column>=e.start_mark.column:t.line===e.end_mark.line?t.column<=e.end_mark.column:e.start_mark.linet.line}var o=0;if(!e||[v,g].indexOf(e.tag)===-1)return i;if(e.tag===v)for(o=0;o0&&(a=this.buffer[u-1],e.call(r,a)<0);)if(u--,this.pointer-u>n/2-1){o=" ... ",u+=5;break}for(c="",i=this.pointer;in/2-1){c=" ... ",i-=5;break}return""+new Array(t).join(" ")+o+this.buffer.slice(u,i)+c+"\n"+new Array(t+this.pointer-u+o.length).join(" ")+"^"},t.prototype.toString=function(){var e,t;return e=this.get_snippet(),t=" on line "+(this.line+1)+", column "+(this.column+1),e?t:t+":\n"+e},t}(),this.YAMLError=function(e){function n(e){this.message=e,n.__super__.constructor.call(this),this.stack=this.toString()+"\n"+(new Error).stack.split("\n").slice(1).join("\n")}return t(n,e),n.prototype.toString=function(){return this.message},n}(Error),this.MarkedYAMLError=function(e){function n(e,t,r,i,o){this.context=e,this.context_mark=t,this.problem=r,this.problem_mark=i,this.note=o,n.__super__.constructor.call(this)}return t(n,e),n.prototype.toString=function(){var e;return e=[],null!=this.context&&e.push(this.context),null==this.context_mark||null!=this.problem&&null!=this.problem_mark&&this.context_mark.line===this.problem_mark.line&&this.context_mark.column===this.problem_mark.column||e.push(this.context_mark.toString()),null!=this.problem&&e.push(this.problem),null!=this.problem_mark&&e.push(this.problem_mark.toString()),null!=this.note&&e.push(this.note),e.join("\n")},n}(this.YAMLError)}).call(this)},function(e,t){(function(){var e,t=function(e,t){function r(){this.constructor=e}for(var i in t)n.call(t,i)&&(e[i]=t[i]);return r.prototype=t.prototype,e.prototype=new r,e.__super__=t.prototype,e},n={}.hasOwnProperty;e=0,this.Node=function(){function t(t,n,r,i){this.tag=t,this.value=n,this.start_mark=r,this.end_mark=i,this.unique_id="node_"+e++}return t}(),this.ScalarNode=function(e){function n(e,t,r,i,o){this.tag=e,this.value=t,this.start_mark=r,this.end_mark=i,this.style=o,n.__super__.constructor.apply(this,arguments)}return t(n,e),n.prototype.id="scalar",n}(this.Node),this.CollectionNode=function(e){function n(e,t,r,i,o){this.tag=e,this.value=t,this.start_mark=r,this.end_mark=i,this.flow_style=o,n.__super__.constructor.apply(this,arguments)}return t(n,e),n}(this.Node),this.SequenceNode=function(e){function n(){return n.__super__.constructor.apply(this,arguments)}return t(n,e),n.prototype.id="sequence",n}(this.CollectionNode),this.MappingNode=function(e){function n(){return n.__super__.constructor.apply(this,arguments)}return t(n,e),n.prototype.id="mapping",n}(this.CollectionNode)}).call(this)},function(e,t,n){(function(e){(function(){var r,i,o,a=function(e,t){function n(){this.constructor=e}for(var r in t)s.call(t,r)&&(e[r]=t[r]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},s={}.hasOwnProperty,u=[].indexOf||function(e){for(var t=0,n=this.length;t=0)throw new t.ConstructorError(null,null,"found unconstructable recursive node",e.start_mark);if(this.constructing_nodes.push(e.unique_id),n=null,s=null,e.tag in this.yaml_constructors)n=this.yaml_constructors[e.tag];else{for(a in this.yaml_multi_constructors)if(e.tag.indexOf(0===a)){s=e.tag.slice(a.length),n=this.yaml_multi_constructors[a];break}null==n&&(null in this.yaml_multi_constructors?(s=e.tag,n=this.yaml_multi_constructors[null]):null in this.yaml_constructors?n=this.yaml_constructors[null]:e instanceof i.ScalarNode?n=this.construct_scalar:e instanceof i.SequenceNode?n=this.construct_sequence:e instanceof i.MappingNode&&(n=this.construct_mapping))}return r=n.call(this,null!=s?s:e,e),this.constructed_objects[e.unique_id]=r,this.constructing_nodes.pop(),r},e.prototype.construct_scalar=function(e){if(!(e instanceof i.ScalarNode))throw new t.ConstructorError(null,null,"expected a scalar node but found "+e.id,e.start_mark);return e.value},e.prototype.construct_sequence=function(e){var n,r,o,a,s;if(!(e instanceof i.SequenceNode))throw new t.ConstructorError(null,null,"expected a sequence node but found "+e.id,e.start_mark);for(a=e.value,s=[],r=0,o=a.length;r=0&&(l=l.slice(1)),"0"===l)return 0;if(0===l.indexOf("0b"))return c*parseInt(l.slice(2),2);if(0===l.indexOf("0x"))return c*parseInt(l.slice(2),16);if(0===l.indexOf("0o"))return c*parseInt(l.slice(2),8);if("0"===l[0])return c*parseInt(l,8);if(u.call(l,":")>=0){for(r=function(){var e,t,n,r;for(n=l.split(/:/g),r=[],e=0,t=n.length;e=0&&(l=l.slice(1)),".inf"===l)return Infinity*c;if(".nan"===l)return NaN;if(u.call(l,":")>=0){for(r=function(){var e,t,n,r;for(n=l.split(/:/g),r=[],e=0,t=n.length;e=n?e:e.length+1===n?""+t+e:""+new Array(n-e.length+1).join(t)+e},this.to_hex=function(e){return"string"==typeof e&&(e=e.charCodeAt(0)),e.toString(16)}}).call(this)}).call(t,function(){return this}())},function(e,t,n){(function(e,r){function i(e,n){var r={seen:[],stylize:a};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),m(n)?r.showHidden=n:n&&t._extend(r,n),x(r.showHidden)&&(r.showHidden=!1),x(r.depth)&&(r.depth=2),x(r.colors)&&(r.colors=!1),x(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=o),u(r,e,r.depth)}function o(e,t){var n=i.styles[t];return n?"["+i.colors[n][0]+"m"+e+"["+i.colors[n][1]+"m":e}function a(e,t){return e}function s(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}function u(e,n,r){if(e.customInspect&&n&&C(n.inspect)&&n.inspect!==t.inspect&&(!n.constructor||n.constructor.prototype!==n)){var i=n.inspect(r,e);return _(i)||(i=u(e,i,r)),i}var o=c(e,n);if(o)return o;var a=Object.keys(n),m=s(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(n)),E(n)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return l(n);if(0===a.length){if(C(n)){var y=n.name?": "+n.name:"";return e.stylize("[Function"+y+"]","special")}if(w(n))return e.stylize(RegExp.prototype.toString.call(n),"regexp");if(S(n))return e.stylize(Date.prototype.toString.call(n),"date");if(E(n))return l(n)}var v="",g=!1,b=["{","}"];if(d(n)&&(g=!0,b=["[","]"]),C(n)){var x=n.name?": "+n.name:"";v=" [Function"+x+"]"}if(w(n)&&(v=" "+RegExp.prototype.toString.call(n)),S(n)&&(v=" "+Date.prototype.toUTCString.call(n)),E(n)&&(v=" "+l(n)),0===a.length&&(!g||0==n.length))return b[0]+v+b[1];if(r<0)return w(n)?e.stylize(RegExp.prototype.toString.call(n),"regexp"):e.stylize("[Object]","special");e.seen.push(n);var k;return k=g?p(e,n,r,m,a):a.map(function(t){return f(e,n,r,m,t,g)}),e.seen.pop(),h(k,v,b)}function c(e,t){if(x(t))return e.stylize("undefined","undefined");if(_(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return g(t)?e.stylize(""+t,"number"):m(t)?e.stylize(""+t,"boolean"):y(t)?e.stylize("null","null"):void 0}function l(e){return"["+Error.prototype.toString.call(e)+"]"}function p(e,t,n,r,i){for(var o=[],a=0,s=t.length;a-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n"))):s=e.stylize("[Circular]","special")),x(a)){if(o&&i.match(/^\d+$/))return s;a=JSON.stringify(""+i),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function h(e,t,n){var r=0,i=e.reduce(function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function d(e){return Array.isArray(e)}function m(e){return"boolean"==typeof e}function y(e){return null===e}function v(e){return null==e}function g(e){return"number"==typeof e}function _(e){return"string"==typeof e}function b(e){return"symbol"==typeof e}function x(e){return void 0===e}function w(e){return k(e)&&"[object RegExp]"===T(e)}function k(e){return"object"==typeof e&&null!==e}function S(e){return k(e)&&"[object Date]"===T(e)}function E(e){return k(e)&&("[object Error]"===T(e)||e instanceof Error)}function C(e){return"function"==typeof e}function A(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function T(e){return Object.prototype.toString.call(e)}function O(e){return e<10?"0"+e.toString(10):e.toString(10)}function D(){var e=new Date,t=[O(e.getHours()),O(e.getMinutes()),O(e.getSeconds())].join(":");return[e.getDate(),R[e.getMonth()],t].join(" ")}function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var P=/%[sdj%]/g;t.format=function(e){if(!_(e)){for(var t=[],n=0;n=o)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(e){return"[Circular]"}default:return e}}),s=r[n];n2*this.indent?t.width:80,this.best_line_break="\r"===(n=t.line_break)||"\n"===n||"\r\n"===n?t.line_break:"\n",this.tag_prefixes=null,this.prepared_anchor=null,this.prepared_tag=null,this.analysis=null,this.style=null}var r,a,c;return r="\0 \t\r\n…\u2028\u2029",a={"!":"!","tag:yaml.org,2002:":"!!"},c={"\0":"0","":"a","\b":"b","\t":"t","\n":"n","\v":"v","\f":"f","\r":"r","":"e",'"':'"',"\\":"\\","…":"N"," ":"_","\u2028":"L","\u2029":"P"},n.prototype.dispose=function(){return this.states=[],this.state=null},n.prototype.emit=function(e){var t;for(this.events.push(e),t=[];!this.need_more_events();)this.event=this.events.shift(),this.state(),t.push(this.event=null);return t},n.prototype.need_more_events=function(){var e;return 0===this.events.length||(e=this.events[0],e instanceof i.DocumentStartEvent?this.need_events(1):e instanceof i.SequenceStartEvent?this.need_events(2):e instanceof i.MappingStartEvent&&this.need_events(3))},n.prototype.need_events=function(e){var t,n,r,o,a;for(o=0,a=this.events.slice(1),n=0,r=a.length;nthis.best_width)&&this.write_indent(),this.states.push(this.expect_flow_sequence_item),this.expect_node({sequence:!0}))},n.prototype.expect_flow_sequence_item=function(){return this.event instanceof i.SequenceEndEvent?(this.indent=this.indents.pop(),this.flow_level--,this.canonical&&(this.write_indicator(",",!1),this.write_indent()),this.write_indicator("]",!1),this.state=this.states.pop()):(this.write_indicator(",",!1),(this.canonical||this.column>this.best_width)&&this.write_indent(),this.states.push(this.expect_flow_sequence_item),this.expect_node({sequence:!0}))},n.prototype.expect_flow_mapping=function(){return this.write_indicator("{",!0,{whitespace:!0}),this.flow_level++,this.increase_indent({flow:!0}),this.state=this.expect_first_flow_mapping_key},n.prototype.expect_first_flow_mapping_key=function(){return this.event instanceof i.MappingEndEvent?(this.indent=this.indents.pop(),this.flow_level--,this.write_indicator("}",!1),this.state=this.states.pop()):((this.canonical||this.column>this.best_width)&&this.write_indent(),!this.canonical&&this.check_simple_key()?(this.states.push(this.expect_flow_mapping_simple_value),this.expect_node({mapping:!0,simple_key:!0})):(this.write_indicator("?",!0),this.states.push(this.expect_flow_mapping_value),this.expect_node({mapping:!0})))},n.prototype.expect_flow_mapping_key=function(){return this.event instanceof i.MappingEndEvent?(this.indent=this.indents.pop(),this.flow_level--,this.canonical&&(this.write_indicator(",",!1),this.write_indent()),this.write_indicator("}",!1),this.state=this.states.pop()):(this.write_indicator(",",!1),(this.canonical||this.column>this.best_width)&&this.write_indent(),!this.canonical&&this.check_simple_key()?(this.states.push(this.expect_flow_mapping_simple_value),this.expect_node({mapping:!0,simple_key:!0})):(this.write_indicator("?",!0),this.states.push(this.expect_flow_mapping_value),this.expect_node({mapping:!0})))},n.prototype.expect_flow_mapping_simple_value=function(){return this.write_indicator(":",!1),this.states.push(this.expect_flow_mapping_key),this.expect_node({mapping:!0})},n.prototype.expect_flow_mapping_value=function(){return(this.canonical||this.column>this.best_width)&&this.write_indent(),this.write_indicator(":",!0),this.states.push(this.expect_flow_mapping_key),this.expect_node({mapping:!0})},n.prototype.expect_block_sequence=function(){var e;return e=this.mapping_context&&!this.indentation,this.increase_indent({indentless:e}),this.state=this.expect_first_block_sequence_item},n.prototype.expect_first_block_sequence_item=function(){return this.expect_block_sequence_item(!0)},n.prototype.expect_block_sequence_item=function(e){return null==e&&(e=!1),!e&&this.event instanceof i.SequenceEndEvent?(this.indent=this.indents.pop(),this.state=this.states.pop()):(this.write_indent(),this.write_indicator("-",!0,{indentation:!0}),this.states.push(this.expect_block_sequence_item),this.expect_node({sequence:!0}))},n.prototype.expect_block_mapping=function(){return this.increase_indent(),this.state=this.expect_first_block_mapping_key},n.prototype.expect_first_block_mapping_key=function(){return this.expect_block_mapping_key(!0)},n.prototype.expect_block_mapping_key=function(e){return null==e&&(e=!1),!e&&this.event instanceof i.MappingEndEvent?(this.indent=this.indents.pop(),this.state=this.states.pop()):(this.write_indent(),this.check_simple_key()?(this.states.push(this.expect_block_mapping_simple_value),this.expect_node({mapping:!0,simple_key:!0})):(this.write_indicator("?",!0,{indentation:!0}),this.states.push(this.expect_block_mapping_value),this.expect_node({mapping:!0})))},n.prototype.expect_block_mapping_simple_value=function(){return this.write_indicator(":",!1),this.states.push(this.expect_block_mapping_key),this.expect_node({mapping:!0})},n.prototype.expect_block_mapping_value=function(){return this.write_indent(),this.write_indicator(":",!0,{indentation:!0}),this.states.push(this.expect_block_mapping_key),this.expect_node({mapping:!0})},n.prototype.check_empty_document=function(){var e;return this.event instanceof i.DocumentStartEvent&&0!==this.events.length&&(e=this.events[0],e instanceof i.ScalarEvent&&null==e.anchor&&null==e.tag&&e.implicit&&""===e.value)},n.prototype.check_empty_sequence=function(){return this.event instanceof i.SequenceStartEvent&&this.events[0]instanceof i.SequenceEndEvent},n.prototype.check_empty_mapping=function(){return this.event instanceof i.MappingStartEvent&&this.events[0]instanceof i.MappingEndEvent},n.prototype.check_simple_key=function(){var e;return e=0,this.event instanceof i.NodeEvent&&null!=this.event.anchor&&(null==this.prepared_anchor&&(this.prepared_anchor=this.prepare_anchor(this.event.anchor)),e+=this.prepared_anchor.length),null!=this.event.tag&&(this.event instanceof i.ScalarEvent||this.event instanceof i.CollectionStartEvent)&&(null==this.prepared_tag&&(this.prepared_tag=this.prepare_tag(this.event.tag)),e+=this.prepared_tag.length),this.event instanceof i.ScalarEvent&&(null==this.analysis&&(this.analysis=this.analyze_scalar(this.event.value)),e+=this.analysis.scalar.length),e<128&&(this.event instanceof i.AliasEvent||this.event instanceof i.ScalarEvent&&!this.analysis.empty&&!this.analysis.multiline||this.check_empty_sequence()||this.check_empty_mapping())},n.prototype.process_anchor=function(e){return null==this.event.anchor?void(this.prepared_anchor=null):(null==this.prepared_anchor&&(this.prepared_anchor=this.prepare_anchor(this.event.anchor)),this.prepared_anchor&&this.write_indicator(""+e+this.prepared_anchor,!0),this.prepared_anchor=null)},n.prototype.process_tag=function(){var e;if(e=this.event.tag,this.event instanceof i.ScalarEvent){if(null==this.style&&(this.style=this.choose_scalar_style()),(!this.canonical||null==e)&&(""===this.style&&this.event.implicit[0]||""!==this.style&&this.event.implicit[1]))return void(this.prepared_tag=null);this.event.implicit[0]&&null==e&&(e="!",this.prepared_tag=null)}else if((!this.canonical||null==e)&&this.event.implicit)return void(this.prepared_tag=null);return null==e&&this.error("tag is not specified"),null==this.prepared_tag&&(this.prepared_tag=this.prepare_tag(e)),this.write_indicator(this.prepared_tag,!0),this.prepared_tag=null},n.prototype.process_scalar=function(){var e;switch(null==this.analysis&&(this.analysis=this.analyze_scalar(this.event.value)),null==this.style&&(this.style=this.choose_scalar_style()),e=!this.simple_key_context,this.style){case'"':this.write_double_quoted(this.analysis.scalar,e);break;case"'":this.write_single_quoted(this.analysis.scalar,e);break;case">":this.write_folded(this.analysis.scalar);break;case"|":this.write_literal(this.analysis.scalar);break;default:this.write_plain(this.analysis.scalar,e)}return this.analysis=null,this.style=null},n.prototype.choose_scalar_style=function(){var e;return null==this.analysis&&(this.analysis=this.analyze_scalar(this.event.value)),'"'===this.event.style||this.canonical?'"':this.event.style||!this.event.implicit[0]||this.simple_key_context&&(this.analysis.empty||this.analysis.multiline)||!(this.flow_level&&this.analysis.allow_flow_plain||!this.flow_level&&this.analysis.allow_block_plain)?this.event.style&&(e=this.event.style,u.call("|>",e)>=0)&&!this.flow_level&&!this.simple_key_context&&this.analysis.allow_block?this.event.style:this.event.style&&"'"!==this.event.style||!this.analysis.allow_single_quoted||this.simple_key_context&&this.analysis.multiline?'"':"'":""},n.prototype.prepare_version=function(e){var t,n,r;return t=e[0],n=e[1],r=t+"."+n,1===t?r:this.error("unsupported YAML version",r)},n.prototype.prepare_tag_handle=function(e){var t,n,r,i;for(e||this.error("tag handle must not be empty"),"!"===e[0]&&"!"===e.slice(-1)||this.error("tag handle must start and end with '!':",e),i=e.slice(1,-1),n=0,r=i.length;n=0||this.error("invalid character '"+t+"' in the tag handle:",e);return e},n.prototype.prepare_tag_prefix=function(e){var t,n,r,i;for(e||this.error("tag prefix must not be empty"),n=[],i=0,r=+("!"===e[0]);r=0?r++:(i=0||"!"===t&&"!"!==i?r++:(f"},n.prototype.prepare_anchor=function(e){var t,n,r;for(e||this.error("anchor must not be empty"),n=0,r=e.length;n=0||this.error("invalid character '"+t+"' in the anchor:",e);return e},n.prototype.analyze_scalar=function(t){var n,i,o,a,s,c,l,p,f,h,d,m,y,v,g,_,b,x,w,k,S,E,C,A,T,O;for(t||new e(t,!0,!1,!1,!0,!0,!0,!1),c=!1,f=!1,_=!1,C=!1,O=!1,v=!1,y=!1,T=!1,A=!1,l=!1,E=!1,0!==t.indexOf("---")&&0!==t.indexOf("...")||(c=!0,f=!0),b=!0,h=1===t.length||(k=t[1],u.call("\0 \t\r\n…\u2028\u2029",k)>=0),w=!1,x=!1,m=0,m=d=0,g=t.length;d'\"%@`",p)>=0||"-"===p&&h?(f=!0,c=!0):u.call("?:",p)>=0&&(f=!0,h&&(c=!0)):u.call(",?[]{}",p)>=0?f=!0:":"===p?(f=!0,h&&(c=!0)):"#"===p&&b&&(f=!0,c=!0),u.call("\n…\u2028\u2029",p)>=0&&(_=!0),"\n"===p||" "<=p&&p<="~"||("\ufeff"!==p&&("…"===p||" "<=p&&p<="퟿"||""<=p&&p<="�")?(O=!0,this.allow_unicode||(C=!0)):C=!0)," "===p?(0===m&&(v=!0),m===t.length-1&&(T=!0),x&&(l=!0),x=!1,w=!0):u.call("\n…\u2028\u2029",p)>=0?(0===m&&(y=!0),m===t.length-1&&(A=!0),w&&(E=!0),x=!0,w=!1):(x=!1,w=!1),b=u.call(r,p)>=0,h=m+2>=t.length||(S=t[m+2],u.call(r,S)>=0);return a=!0,i=!0,s=!0,o=!0,n=!0,(v||y||T||A)&&(a=i=!1),T&&(n=!1),l&&(a=i=s=!1),(E||C)&&(a=i=s=n=!1),_&&(a=i=!1),f&&(a=!1),c&&(i=!1),new e(t,!1,_,a,i,s,o,n)},n.prototype.write_stream_start=function(){if(this.encoding&&0===this.encoding.indexOf("utf-16"))return this.stream.write("\ufeff",this.encoding)},n.prototype.write_stream_end=function(){return this.flush_stream()},n.prototype.write_indicator=function(e,t,n){var r;return null==n&&(n={}),r=this.whitespace||!t?e:" "+e,this.whitespace=!!n.whitespace,this.indentation&&(this.indentation=!!n.indentation),this.column+=r.length,this.open_ended=!1,this.stream.write(r,this.encoding)},n.prototype.write_indent=function(){var e,t,n;if(t=null!=(n=this.indent)?n:0,(!this.indentation||this.column>t||this.column===t&&!this.whitespace)&&this.write_line_break(),this.columnthis.best_width&&t&&0!==f&&a!==e.length?this.write_indent():(o=e.slice(f,a),this.column+=o.length,this.stream.write(o,this.encoding)),f=a);else if(r){if(null==i||u.call("\n…\u2028\u2029",i)<0){for("\n"===e[f]&&this.write_line_break(),l=e.slice(f,a),s=0,c=l.length;s=0||"'"===i)&&f=0),a++}return this.write_indicator("'",!1)},n.prototype.write_double_quoted=function(e,t){var n,r,i,a;for(null==t&&(t=!0),this.write_indicator('"',!0),a=i=0;i<=e.length;)n=e[i],(null==n||u.call('"\\…\u2028\u2029\ufeff',n)>=0||!(" "<=n&&n<="~"||this.allow_unicode&&(" "<=n&&n<="퟿"||""<=n&&n<="�")))&&(a=i)&&this.column+(i-a)>this.best_width&&(r=e.slice(a,i)+"\\",a"+a,!0),"+"===a.slice(-1)&&(this.open_ended=!0),this.write_line_break(),c=!0,n=!0,h=!1,d=o=0,f=[];o<=e.length;){if(r=e[o],n){if(null==r||u.call("\n…\u2028\u2029",r)<0){for(c||null==r||" "===r||"\n"!==e[d]||this.write_line_break(),c=" "===r,p=e.slice(d,o),s=0,l=p.length;sthis.best_width?this.write_indent():(i=e.slice(d,o), +this.column+=i.length,this.stream.write(i,this.encoding)),d=o):(null==r||u.call(" \n…\u2028\u2029",r)>=0)&&(i=e.slice(d,o),this.column+=i.length,this.stream.write(i,this.encoding),null==r&&this.write_line_break(),d=o);null!=r&&(n=u.call("\n…\u2028\u2029",r)>=0,h=" "===r),f.push(o++)}return f},n.prototype.write_literal=function(e){var t,n,r,i,o,a,s,c,l,p,f;for(a=this.determine_block_hints(e),this.write_indicator("|"+a,!0),"+"===a.slice(-1)&&(this.open_ended=!0),this.write_line_break(),n=!0,f=o=0,p=[];o<=e.length;){if(r=e[o],n){if(null==r||u.call("\n…\u2028\u2029",r)<0){for(l=e.slice(f,o),s=0,c=l.length;s=0)&&(i=e.slice(f,o),this.stream.write(i,this.encoding),null==r&&this.write_line_break(),f=o);null!=r&&(n=u.call("\n…\u2028\u2029",r)>=0),p.push(o++)}return p},n.prototype.write_plain=function(e,t){var n,r,i,o,a,s,c,l,p,f,h;if(null==t&&(t=!0),e){for(this.root_context&&(this.open_ended=!0),this.whitespace||(o=" ",this.column+=o.length,this.stream.write(o,this.encoding)),this.whitespace=!1,this.indentation=!1,f=!1,r=!1,h=a=0,p=[];a<=e.length;){if(i=e[a],f)" "!==i&&(h+1===a&&this.column>this.best_width&&t?(this.write_indent(),this.whitespace=!1,this.indentation=!1):(o=e.slice(h,a),this.column+=o.length,this.stream.write(o,this.encoding)),h=a);else if(r){if(u.call("\n…\u2028\u2029",i)<0){for("\n"===e[h]&&this.write_line_break(),l=e.slice(h,a),s=0,c=l.length;s=0)&&(o=e.slice(h,a),this.column+=o.length,this.stream.write(o,this.encoding),h=a);null!=i&&(f=" "===i,r=u.call("\n…\u2028\u2029",i)>=0),p.push(a++)}return p}},n.prototype.determine_block_hints=function(e){var t,n,r,i,o;return n="",t=e[0],r=e.length-2,o=e[r++],i=e[r++],u.call(" \n…\u2028\u2029",t)>=0&&(n+=this.best_indent),u.call("\n…\u2028\u2029",i)<0?n+="-":(1===e.length||u.call("\n…\u2028\u2029",o)>=0)&&(n+="+"),n},n.prototype.flush_stream=function(){var e;return"function"==typeof(e=this.stream).flush?e.flush():void 0},n.prototype.error=function(e,n){var r,i;throw n&&(n=null!=(r=null!=n&&null!=(i=n.constructor)?i.name:void 0)?r:o.inspect(n)),new t.EmitterError(""+e+(n?" "+n:""))},n}(),e=function(){function e(e,t,n,r,i,o,a,s){this.scalar=e,this.empty=t,this.multiline=n,this.allow_flow_plain=r,this.allow_block_plain=i,this.allow_single_quoted=o,this.allow_double_quoted=a,this.allow_block=s}return e}()}).call(this)},function(e,t,n){(function(){var e,t,r,i,o=function(e,t){function n(){this.constructor=e}for(var r in t)a.call(t,r)&&(e[r]=t[r]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},a={}.hasOwnProperty;t=n(854),r=n(856),i=n(858),e=n(855).YAMLError,this.SerializerError=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return o(t,e),t}(e),this.Serializer=function(){function e(e){var t;t=null!=e?e:{},this.encoding=t.encoding,this.explicit_start=t.explicit_start,this.explicit_end=t.explicit_end,this.version=t.version,this.tags=t.tags,this.serialized_nodes={},this.anchors={},this.last_anchor_id=0,this.closed=null}return e.prototype.open=function(){if(null===this.closed)return this.emit(new t.StreamStartEvent(this.encoding)),this.closed=!1;throw this.closed?new SerializerError("serializer is closed"):new SerializerError("serializer is already open")},e.prototype.close=function(){if(null===this.closed)throw new SerializerError("serializer is not opened");if(!this.closed)return this.emit(new t.StreamEndEvent),this.closed=!0},e.prototype.serialize=function(e){if(null===this.closed)throw new SerializerError("serializer is not opened");if(this.closed)throw new SerializerError("serializer is closed");return null!=e&&(this.emit(new t.DocumentStartEvent(void 0,void 0,this.explicit_start,this.version,this.tags)),this.anchor_node(e),this.serialize_node(e),this.emit(new t.DocumentEndEvent(void 0,void 0,this.explicit_end))),this.serialized_nodes={},this.anchors={},this.last_anchor_id=0},e.prototype.anchor_node=function(e){var t,n,i,o,a,s,u,c,l,p,f,h,d,m;if(e.unique_id in this.anchors)return null!=(t=this.anchors)[c=e.unique_id]?t[c]:t[c]=this.generate_anchor(e);if(this.anchors[e.unique_id]=null,e instanceof r.SequenceNode){for(l=e.value,h=[],n=0,s=l.length;nn?p.push([l,s]):i[s]=this.yaml_path_resolvers[l][s]);else for(d=this.yaml_path_resolvers,a=0,c=d.length;a=0)return c[e];if(a.call(c,null)>=0)return c[null]}return e===t.ScalarNode?i:e===t.SequenceNode?o:e===t.MappingNode?n:void 0},e}(),this.Resolver=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return i(t,e),t}(this.BaseResolver),this.Resolver.add_implicit_resolver("tag:yaml.org,2002:bool",/^(?:yes|Yes|YES|true|True|TRUE|on|On|ON|no|No|NO|false|False|FALSE|off|Off|OFF)$/,"yYnNtTfFoO"),this.Resolver.add_implicit_resolver("tag:yaml.org,2002:float",/^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)?|\.[0-9_]+(?:[eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*|[-+]?\.(?:inf|Inf|INF)|\.(?:nan|NaN|NAN))$/,"-+0123456789."),this.Resolver.add_implicit_resolver("tag:yaml.org,2002:int",/^(?:[-+]?0b[01_]+|[-+]?0[0-7_]+|[-+]?(?:0|[1-9][0-9_]*)|[-+]?0x[0-9a-fA-F_]+|[-+]?0o[0-7_]+|[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$/,"-+0123456789"),this.Resolver.add_implicit_resolver("tag:yaml.org,2002:merge",/^(?:<<)$/,"<"),this.Resolver.add_implicit_resolver("tag:yaml.org,2002:null",/^(?:~|null|Null|NULL|)$/,["~","n","N",""]),this.Resolver.add_implicit_resolver("tag:yaml.org,2002:timestamp",/^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]|[0-9][0-9][0-9][0-9]-[0-9][0-9]?-[0-9][0-9]?(?:[Tt]|[\x20\t]+)[0-9][0-9]?:[0-9][0-9]:[0-9][0-9](?:\.[0-9]*)?(?:[\x20\t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$/,"0123456789"),this.Resolver.add_implicit_resolver("tag:yaml.org,2002:value",/^(?:=)$/,"="),this.Resolver.add_implicit_resolver("tag:yaml.org,2002:yaml",/^(?:!|&|\*)$/,"!&*")}).call(this)},function(e,t,n){(function(){var e,t,r,i,o,a,s,u=[].slice;s=n(858),i=n(868),a=n(869),r=n(871),e=n(853),o=n(866),t=n(857),this.make_loader=function(n,c,l,p,f,h){var d,m;return null==n&&(n=i.Reader),null==c&&(c=a.Scanner),null==l&&(l=r.Parser),null==p&&(p=e.Composer),null==f&&(f=o.Resolver),null==h&&(h=t.Constructor),m=[n,c,l,p,f,h],d=function(){function e(e){var n,r,i;for(m[0].call(this,e),i=m.slice(1),n=0,r=i.length;n=0||"\r"===t&&"\n"!==this.string[this.index]?(this.line++,this.column=0):this.column++,n.push(e--);return n},n.prototype.get_mark=function(){return new e(this.line,this.column,this.string,this.index)},n.prototype.check_printable=function(){var e,n,i;if(n=r.exec(this.string))throw e=n[0],i=this.string.length-this.index+n.index,new t.ReaderError(i,e,"special characters are not allowed")},n}()}).call(this)},function(e,t,n){(function(){var e,r,i,o,a=function(e,t){function n(){this.constructor=e}for(var r in t)s.call(t,r)&&(e[r]=t[r]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},s={}.hasOwnProperty,u=[].slice,c=[].indexOf||function(e){for(var t=0,n=this.length;t"===e&&0===this.flow_level)return this.fetch_folded();if("'"===e)return this.fetch_single();if('"'===e)return this.fetch_double();if(this.check_plain())return this.fetch_plain();throw new t.ScannerError("while scanning for the next token",null,"found character "+e+" that cannot start any token",this.get_mark())},e.prototype.next_possible_simple_key=function(){var e,t,n,r;n=null,r=this.possible_simple_keys;for(t in r)s.call(r,t)&&(e=r[t],(null===n||e.token_numbere;)t=this.get_mark(),this.indent=this.indents.pop(),n.push(this.tokens.push(new i.BlockEndToken(t,t)));return n}},e.prototype.add_indent=function(e){return e>this.indent&&(this.indents.push(this.indent),this.indent=e,!0)},e.prototype.fetch_stream_start=function(){var e;return e=this.get_mark(),this.tokens.push(new i.StreamStartToken(e,e,this.encoding))},e.prototype.fetch_stream_end=function(){var e;return this.unwind_indent(-1),this.remove_possible_simple_key(),this.allow_possible_simple_key=!1,this.possible_simple_keys={},e=this.get_mark(),this.tokens.push(new i.StreamEndToken(e,e)),this.done=!0},e.prototype.fetch_directive=function(){return this.unwind_indent(-1),this.remove_possible_simple_key(),this.allow_simple_key=!1,this.tokens.push(this.scan_directive())},e.prototype.fetch_document_start=function(){return this.fetch_document_indicator(i.DocumentStartToken)},e.prototype.fetch_document_end=function(){return this.fetch_document_indicator(i.DocumentEndToken)},e.prototype.fetch_document_indicator=function(e){var t;return this.unwind_indent(-1),this.remove_possible_simple_key(),this.allow_simple_key=!1,t=this.get_mark(),this.forward(3),this.tokens.push(new e(t,this.get_mark()))},e.prototype.fetch_flow_sequence_start=function(){return this.fetch_flow_collection_start(i.FlowSequenceStartToken)},e.prototype.fetch_flow_mapping_start=function(){return this.fetch_flow_collection_start(i.FlowMappingStartToken)},e.prototype.fetch_flow_collection_start=function(e){var t;return this.save_possible_simple_key(),this.flow_level++,this.allow_simple_key=!0,t=this.get_mark(),this.forward(),this.tokens.push(new e(t,this.get_mark()))},e.prototype.fetch_flow_sequence_end=function(){return this.fetch_flow_collection_end(i.FlowSequenceEndToken)},e.prototype.fetch_flow_mapping_end=function(){return this.fetch_flow_collection_end(i.FlowMappingEndToken)},e.prototype.fetch_flow_collection_end=function(e){var t;return this.remove_possible_simple_key(),this.flow_level--,this.allow_simple_key=!1,t=this.get_mark(),this.forward(),this.tokens.push(new e(t,this.get_mark()))},e.prototype.fetch_flow_entry=function(){var e;return this.allow_simple_key=!0,this.remove_possible_simple_key(),e=this.get_mark(),this.forward(),this.tokens.push(new i.FlowEntryToken(e,this.get_mark()))},e.prototype.fetch_block_entry=function(){var e,n;if(0===this.flow_level){if(!this.allow_simple_key)throw new t.ScannerError(null,null,"sequence entries are not allowed here",this.get_mark());this.add_indent(this.column)&&(e=this.get_mark(),this.tokens.push(new i.BlockSequenceStartToken(e,e)))}return this.allow_simple_key=!0,this.remove_possible_simple_key(),n=this.get_mark(),this.forward(),this.tokens.push(new i.BlockEntryToken(n,this.get_mark()))},e.prototype.fetch_key=function(){var e,n;if(0===this.flow_level){if(!this.allow_simple_key)throw new t.ScannerError(null,null,"mapping keys are not allowed here",this.get_mark());this.add_indent(this.column)&&(e=this.get_mark(),this.tokens.push(new i.BlockMappingStartToken(e,e)))}return this.allow_simple_key=!this.flow_level,this.remove_possible_simple_key(),n=this.get_mark(),this.forward(),this.tokens.push(new i.KeyToken(n,this.get_mark()))},e.prototype.fetch_value=function(){var e,n,r;if(e=this.possible_simple_keys[this.flow_level])delete this.possible_simple_keys[this.flow_level],this.tokens.splice(e.token_number-this.tokens_taken,0,new i.KeyToken(e.mark,e.mark)),0===this.flow_level&&this.add_indent(e.column)&&this.tokens.splice(e.token_number-this.tokens_taken,0,new i.BlockMappingStartToken(e.mark,e.mark)),this.allow_simple_key=!1;else{if(0===this.flow_level){if(!this.allow_simple_key)throw new t.ScannerError(null,null,"mapping values are not allowed here",this.get_mark());this.add_indent(this.column)&&(n=this.get_mark(),this.tokens.push(new i.BlockMappingStartToken(n,n)))}this.allow_simple_key=!this.flow_level,this.remove_possible_simple_key()}return r=this.get_mark(),this.forward(),this.tokens.push(new i.ValueToken(r,this.get_mark()))},e.prototype.fetch_alias=function(){return this.save_possible_simple_key(),this.allow_simple_key=!1,this.tokens.push(this.scan_anchor(i.AliasToken))},e.prototype.fetch_anchor=function(){return this.save_possible_simple_key(),this.allow_simple_key=!1,this.tokens.push(this.scan_anchor(i.AnchorToken))},e.prototype.fetch_tag=function(){return this.save_possible_simple_key(),this.allow_simple_key=!1,this.tokens.push(this.scan_tag())},e.prototype.fetch_literal=function(){return this.fetch_block_scalar("|")},e.prototype.fetch_folded=function(){return this.fetch_block_scalar(">")},e.prototype.fetch_block_scalar=function(e){return this.allow_simple_key=!0,this.remove_possible_simple_key(),this.tokens.push(this.scan_block_scalar(e))},e.prototype.fetch_single=function(){return this.fetch_flow_scalar("'")},e.prototype.fetch_double=function(){return this.fetch_flow_scalar('"')},e.prototype.fetch_flow_scalar=function(e){return this.save_possible_simple_key(),this.allow_simple_key=!1,this.tokens.push(this.scan_flow_scalar(e))},e.prototype.fetch_plain=function(){return this.save_possible_simple_key(),this.allow_simple_key=!1,this.tokens.push(this.scan_plain())},e.prototype.check_directive=function(){return 0===this.column},e.prototype.check_document_start=function(){var e;return 0===this.column&&"---"===this.prefix(3)&&(e=this.peek(3),c.call(n+l+"\0",e)>=0)},e.prototype.check_document_end=function(){var e;return 0===this.column&&"..."===this.prefix(3)&&(e=this.peek(3),c.call(n+l+"\0",e)>=0)},e.prototype.check_block_entry=function(){var e;return e=this.peek(1),c.call(n+l+"\0",e)>=0},e.prototype.check_key=function(){var e;return 0!==this.flow_level||(e=this.peek(1),c.call(n+l+"\0",e)>=0)},e.prototype.check_value=function(){var e;return 0!==this.flow_level||(e=this.peek(1),c.call(n+l+"\0",e)>=0)},e.prototype.check_plain=function(){var e,t;return e=this.peek(),c.call(n+l+"\0-?:,[]{}#&*!|>'\"%@`",e)<0||(t=this.peek(1),c.call(n+l+"\0",t)<0&&("-"===e||0===this.flow_level&&c.call("?:",e)>=0))},e.prototype.scan_to_next_token=function(){var e,t,r;for(0===this.index&&"\ufeff"===this.peek()&&this.forward(),e=!1,r=[];!e;){for(;" "===this.peek();)this.forward();if("#"===this.peek())for(;t=this.peek(),c.call(n+"\0",t)<0;)this.forward();this.scan_line_break()?0===this.flow_level?r.push(this.allow_simple_key=!0):r.push(void 0):r.push(e=!0)}return r},e.prototype.scan_directive=function(){var e,t,r,o,a;if(o=this.get_mark(),this.forward(),t=this.scan_directive_name(o),a=null,"YAML"===t)a=this.scan_yaml_directive_value(o),e=this.get_mark();else if("TAG"===t)a=this.scan_tag_directive_value(o),e=this.get_mark();else for(e=this.get_mark();r=this.peek(),c.call(n+"\0",r)<0;)this.forward();return this.scan_directive_ignored_line(o),new i.DirectiveToken(t,a,o,e)},e.prototype.scan_directive_name=function(e){var r,i,o;for(i=0,r=this.peek(i);"0"<=r&&r<="9"||"A"<=r&&r<="Z"||"a"<=r&&r<="z"||c.call("-_",r)>=0;)i++,r=this.peek(i);if(0===i)throw new t.ScannerError("while scanning a directive",e,"expected alphanumeric or numeric character but found "+r,this.get_mark());if(o=this.prefix(i),this.forward(i),r=this.peek(),c.call(n+"\0 ",r)<0)throw new t.ScannerError("while scanning a directive",e,"expected alphanumeric or numeric character but found "+r,this.get_mark());return o},e.prototype.scan_yaml_directive_value=function(e){for(var r,i,o;" "===this.peek();)this.forward();if(r=this.scan_yaml_directive_number(e),"."!==this.peek())throw new t.ScannerError("while scanning a directive",e,"expected a digit or '.' but found "+this.peek(),this.get_mark());if(this.forward(),i=this.scan_yaml_directive_number(e),o=this.peek(),c.call(n+"\0 ",o)<0)throw new t.ScannerError("while scanning a directive",e,"expected a digit or ' ' but found "+this.peek(),this.get_mark());return[r,i]},e.prototype.scan_yaml_directive_number=function(e){var n,r,i,o;if(n=this.peek(),!("0"<=n&&n<="9"))throw new t.ScannerError("while scanning a directive",e,"expected a digit but found "+n,this.get_mark());for(r=0;"0"<=(i=this.peek(r))&&i<="9";)r++;return o=parseInt(this.prefix(r)),this.forward(r),o},e.prototype.scan_tag_directive_value=function(e){for(var t,n;" "===this.peek();)this.forward();for(t=this.scan_tag_directive_handle(e);" "===this.peek();)this.forward();return n=this.scan_tag_directive_prefix(e),[t,n]},e.prototype.scan_tag_directive_handle=function(e){var n,r;if(r=this.scan_tag_handle("directive",e),n=this.peek()," "!==n)throw new t.ScannerError("while scanning a directive",e,"expected ' ' but found "+n,this.get_mark());return r},e.prototype.scan_tag_directive_prefix=function(e){var r,i;if(i=this.scan_tag_uri("directive",e),r=this.peek(),c.call(n+"\0 ",r)<0)throw new t.ScannerError("while scanning a directive",e,"expected ' ' but found "+r,this.get_mark());return i},e.prototype.scan_directive_ignored_line=function(e){for(var r,i;" "===this.peek();)this.forward();if("#"===this.peek())for(;i=this.peek(),c.call(n+"\0",i)<0;)this.forward();if(r=this.peek(),c.call(n+"\0",r)<0)throw new t.ScannerError("while scanning a directive",e,"expected a comment or a line break but found "+r,this.get_mark());return this.scan_line_break()},e.prototype.scan_anchor=function(e){var r,i,o,a,s,u;for(s=this.get_mark(),i=this.peek(),a="*"===i?"alias":"anchor",this.forward(),o=0,r=this.peek(o);"0"<=r&&r<="9"||"A"<=r&&r<="Z"||"a"<=r&&r<="z"||c.call("-_",r)>=0;)o++,r=this.peek(o);if(0===o)throw new t.ScannerError("while scanning an "+a,s,"expected alphabetic or numeric character but found '"+r+"'",this.get_mark());if(u=this.prefix(o),this.forward(o),r=this.peek(),c.call(n+l+"\0?:,]}%@`",r)<0)throw new t.ScannerError("while scanning an "+a,s,"expected alphabetic or numeric character but found '"+r+"'",this.get_mark()); +return new e(u,s,this.get_mark())},e.prototype.scan_tag=function(){var e,r,o,a,s,u;if(a=this.get_mark(),e=this.peek(1),"<"===e){if(r=null,this.forward(2),s=this.scan_tag_uri("tag",a),">"!==this.peek())throw new t.ScannerError("while parsing a tag",a,"expected '>' but found "+this.peek(),this.get_mark());this.forward()}else if(c.call(n+l+"\0",e)>=0)r=null,s="!",this.forward();else{for(o=1,u=!1;c.call(n+"\0 ",e)<0;){if("!"===e){u=!0;break}o++,e=this.peek(o)}u?r=this.scan_tag_handle("tag",a):(r="!",this.forward()),s=this.scan_tag_uri("tag",a)}if(e=this.peek(),c.call(n+"\0 ",e)<0)throw new t.ScannerError("while scanning a tag",a,"expected ' ' but found "+e,this.get_mark());return new i.TagToken([r,s],a,this.get_mark())},e.prototype.scan_block_scalar=function(e){var t,r,a,s,u,l,p,f,h,d,m,y,v,g,_,b,x,w,k,S;for(u=">"===e,a=[],S=this.get_mark(),this.forward(),v=this.scan_block_scalar_indicators(S),r=v[0],l=v[1],this.scan_block_scalar_ignored_line(S),y=this.indent+1,y<1&&(y=1),null==l?(g=this.scan_block_scalar_indentation(),t=g[0],m=g[1],s=g[2],p=Math.max(y,m)):(p=y+l-1,_=this.scan_block_scalar_breaks(p),t=_[0],s=_[1]),d="";this.column===p&&"\0"!==this.peek();){for(a=a.concat(t),b=this.peek(),f=c.call(" \t",b)<0,h=0;x=this.peek(h),c.call(n+"\0",x)<0;)h++;if(a.push(this.prefix(h)),this.forward(h),d=this.scan_line_break(),w=this.scan_block_scalar_breaks(p),t=w[0],s=w[1],this.column!==p||"\0"===this.peek())break;u&&"\n"===d&&f&&(k=this.peek(),c.call(" \t",k)<0)?o.is_empty(t)&&a.push(" "):a.push(d)}return r!==!1&&a.push(d),r===!0&&(a=a.concat(t)),new i.ScalarToken(a.join(""),!1,S,s,e)},e.prototype.scan_block_scalar_indicators=function(e){var r,i,o;if(i=null,o=null,r=this.peek(),c.call("+-",r)>=0){if(i="+"===r,this.forward(),r=this.peek(),c.call(a,r)>=0){if(o=parseInt(r),0===o)throw new t.ScannerError("while scanning a block scalar",e,"expected indentation indicator in the range 1-9 but found 0",this.get_mark());this.forward()}}else if(c.call(a,r)>=0){if(o=parseInt(r),0===o)throw new t.ScannerError("while scanning a block scalar",e,"expected indentation indicator in the range 1-9 but found 0",this.get_mark());this.forward(),r=this.peek(),c.call("+-",r)>=0&&(i="+"===r,this.forward())}if(r=this.peek(),c.call(n+"\0 ",r)<0)throw new t.ScannerError("while scanning a block scalar",e,"expected chomping or indentation indicators, but found "+r,this.get_mark());return[i,o]},e.prototype.scan_block_scalar_ignored_line=function(e){for(var r,i;" "===this.peek();)this.forward();if("#"===this.peek())for(;i=this.peek(),c.call(n+"\0",i)<0;)this.forward();if(r=this.peek(),c.call(n+"\0",r)<0)throw new t.ScannerError("while scanning a block scalar",e,"expected a comment or a line break but found "+r,this.get_mark());return this.scan_line_break()},e.prototype.scan_block_scalar_indentation=function(){var e,t,r,i;for(e=[],r=0,t=this.get_mark();i=this.peek(),c.call(n+" ",i)>=0;)" "!==this.peek()?(e.push(this.scan_line_break()),t=this.get_mark()):(this.forward(),this.column>r&&(r=this.column));return[e,r,t]},e.prototype.scan_block_scalar_breaks=function(e){var t,r,i;for(t=[],r=this.get_mark();this.column=0;)for(t.push(this.scan_line_break()),r=this.get_mark();this.column=0)o.push(i),this.forward();else{if(!e||"\\"!==i)return o;if(this.forward(),i=this.peek(),i in f)o.push(f[i]),this.forward();else if(i in p){for(d=p[i],this.forward(),h=u=0,y=d;0<=y?uy;h=0<=y?++u:--u)if(v=this.peek(h),c.call(a+"ABCDEFabcdef",v)<0)throw new t.ScannerError("while scanning a double-quoted scalar",r,"expected escape sequence of "+d+" hexadecimal numbers, but found "+this.peek(h),this.get_mark());s=parseInt(this.prefix(d),16),o.push(String.fromCharCode(s)),this.forward(d)}else{if(!(c.call(n,i)>=0))throw new t.ScannerError("while scanning a double-quoted scalar",r,"found unknown escape character "+i,this.get_mark());this.scan_line_break(),o=o.concat(this.scan_flow_scalar_breaks(e,r))}}else o.push("'"),this.forward(2)}},e.prototype.scan_flow_scalar_spaces=function(e,r){var i,o,a,s,u,p,f;for(a=[],s=0;p=this.peek(s),c.call(l,p)>=0;)s++;if(f=this.prefix(s),this.forward(s),o=this.peek(),"\0"===o)throw new t.ScannerError("while scanning a quoted scalar",r,"found unexpected end of stream",this.get_mark());return c.call(n,o)>=0?(u=this.scan_line_break(),i=this.scan_flow_scalar_breaks(e,r),"\n"!==u?a.push(u):0===i.length&&a.push(" "),a=a.concat(i)):a.push(f),a},e.prototype.scan_flow_scalar_breaks=function(e,r){var i,o,a,s,u;for(i=[];;){if(o=this.prefix(3),"---"===o||"..."===o&&(a=this.peek(3),c.call(n+l+"\0",a)>=0))throw new t.ScannerError("while scanning a quoted scalar",r,"found unexpected document separator",this.get_mark());for(;s=this.peek(),c.call(l,s)>=0;)this.forward();if(u=this.peek(),!(c.call(n,u)>=0))return i;i.push(this.scan_line_break())}},e.prototype.scan_plain=function(){var e,r,o,a,s,u,p,f,h;for(r=[],h=o=this.get_mark(),a=this.indent+1,f=[];;){if(s=0,"#"===this.peek())break;for(;;){if(e=this.peek(s),c.call(n+l+"\0",e)>=0||0===this.flow_level&&":"===e&&(u=this.peek(s+1),c.call(n+l+"\0",u)>=0)||0!==this.flow_level&&c.call(",:?[]{}",e)>=0)break;s++}if(0!==this.flow_level&&":"===e&&(p=this.peek(s+1),c.call(n+l+"\0,[]{}",p)<0))throw this.forward(s),new t.ScannerError("while scanning a plain scalar",h,"found unexpected ':'",this.get_mark(),"Please check http://pyyaml.org/wiki/YAMLColonInFlowContext");if(0===s)break;if(this.allow_simple_key=!1,r=r.concat(f),r.push(this.prefix(s)),this.forward(s),o=this.get_mark(),f=this.scan_plain_spaces(a,h),null==f||0===f.length||"#"===this.peek()||0===this.flow_level&&this.column=0;)a++;if(m=this.prefix(a),this.forward(a),i=this.peek(),c.call(n,i)>=0){if(s=this.scan_line_break(),this.allow_simple_key=!0,u=this.prefix(3),"---"===u||"..."===u&&(f=this.peek(3),c.call(n+l+"\0",f)>=0))return;for(r=[];d=this.peek(),c.call(n+" ",d)>=0;)if(" "===this.peek())this.forward();else if(r.push(this.scan_line_break()),u=this.prefix(3),"---"===u||"..."===u&&(h=this.peek(3),c.call(n+l+"\0",h)>=0))return;"\n"!==s?o.push(s):0===r.length&&o.push(" "),o=o.concat(r)}else m&&o.push(m);return o},e.prototype.scan_tag_handle=function(e,n){var r,i,o;if(r=this.peek(),"!"!==r)throw new t.ScannerError("while scanning a "+e,n,"expected '!' but found "+r,this.get_mark());if(i=1,r=this.peek(i)," "!==r){for(;"0"<=r&&r<="9"||"A"<=r&&r<="Z"||"a"<=r&&r<="z"||c.call("-_",r)>=0;)i++,r=this.peek(i);if("!"!==r)throw this.forward(i),new t.ScannerError("while scanning a "+e,n,"expected '!' but found "+r,this.get_mark());i++}return o=this.prefix(i),this.forward(i),o},e.prototype.scan_tag_uri=function(e,n){var r,i,o;for(i=[],o=0,r=this.peek(o);"0"<=r&&r<="9"||"A"<=r&&r<="Z"||"a"<=r&&r<="z"||c.call("-;/?:@&=+$,_.!~*'()[]%",r)>=0;)"%"===r?(i.push(this.prefix(o)),this.forward(o),o=0,i.push(this.scan_uri_escapes(e,n))):o++,r=this.peek(o);if(0!==o&&(i.push(this.prefix(o)),this.forward(o),o=0),0===i.length)throw new t.ScannerError("while parsing a "+e,n,"expected URI but found "+r,this.get_mark());return i.join("")},e.prototype.scan_uri_escapes=function(e,n){var r,i,o,a;for(r=[],a=this.get_mark();"%"===this.peek();){for(this.forward(),o=i=0;i<=2;o=++i)throw new t.ScannerError("while scanning a "+e,n,"expected URI escape sequence of 2 hexadecimal numbers but found "+this.peek(o),this.get_mark());r.push(String.fromCharCode(parseInt(this.prefix(2),16))),this.forward(2)}return r.join("")},e.prototype.scan_line_break=function(){var e;return e=this.peek(),c.call("\r\n…",e)>=0?("\r\n"===this.prefix(2)?this.forward(2):this.forward(),"\n"):c.call("\u2028\u2029",e)>=0?(this.forward(),e):""},e}()}).call(this)},function(e,t){(function(){var e=function(e,n){function r(){this.constructor=e}for(var i in n)t.call(n,i)&&(e[i]=n[i]);return r.prototype=n.prototype,e.prototype=new r,e.__super__=n.prototype,e},t={}.hasOwnProperty;this.Token=function(){function e(e,t){this.start_mark=e,this.end_mark=t}return e}(),this.DirectiveToken=function(t){function n(e,t,n,r){this.name=e,this.value=t,this.start_mark=n,this.end_mark=r}return e(n,t),n.prototype.id="",n}(this.Token),this.DocumentStartToken=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return e(n,t),n.prototype.id="",n}(this.Token),this.DocumentEndToken=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return e(n,t),n.prototype.id="",n}(this.Token),this.StreamStartToken=function(t){function n(e,t,n){this.start_mark=e,this.end_mark=t,this.encoding=n}return e(n,t),n.prototype.id="",n}(this.Token),this.StreamEndToken=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return e(n,t),n.prototype.id="",n}(this.Token),this.BlockSequenceStartToken=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return e(n,t),n.prototype.id="",n}(this.Token),this.BlockMappingStartToken=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return e(n,t),n.prototype.id="",n}(this.Token),this.BlockEndToken=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return e(n,t),n.prototype.id="",n}(this.Token),this.FlowSequenceStartToken=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return e(n,t),n.prototype.id="[",n}(this.Token),this.FlowMappingStartToken=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return e(n,t),n.prototype.id="{",n}(this.Token),this.FlowSequenceEndToken=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return e(n,t),n.prototype.id="]",n}(this.Token),this.FlowMappingEndToken=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return e(n,t),n.prototype.id="}",n}(this.Token),this.KeyToken=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return e(n,t),n.prototype.id="?",n}(this.Token),this.ValueToken=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return e(n,t),n.prototype.id=":",n}(this.Token),this.BlockEntryToken=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return e(n,t),n.prototype.id="-",n}(this.Token),this.FlowEntryToken=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return e(n,t),n.prototype.id=",",n}(this.Token),this.AliasToken=function(t){function n(e,t,n){this.value=e,this.start_mark=t,this.end_mark=n}return e(n,t),n.prototype.id="",n}(this.Token),this.AnchorToken=function(t){function n(e,t,n){this.value=e,this.start_mark=t,this.end_mark=n}return e(n,t),n.prototype.id="",n}(this.Token),this.TagToken=function(t){function n(e,t,n){this.value=e,this.start_mark=t,this.end_mark=n}return e(n,t),n.prototype.id="",n}(this.Token),this.ScalarToken=function(t){function n(e,t,n,r,i){this.value=e,this.plain=t,this.start_mark=n,this.end_mark=r,this.style=i}return e(n,t),n.prototype.id="",n}(this.Token)}).call(this)},function(e,t,n){(function(){var e,r,i,o=function(e,t){function n(){this.constructor=e}for(var r in t)a.call(t,r)&&(e[r]=t[r]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},a={}.hasOwnProperty,s=[].slice;r=n(854),e=n(855).MarkedYAMLError,i=n(870),this.ParserError=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return o(t,e),t}(e),this.Parser=function(){function e(){this.current_event=null,this.yaml_version=null,this.tag_handles={},this.states=[],this.marks=[],this.state="parse_stream_start"}var n;return n={"!":"!","!!":"tag:yaml.org,2002:"},e.prototype.dispose=function(){return this.states=[],this.state=null},e.prototype.check_event=function(){var e,t,n,r;if(t=1<=arguments.length?s.call(arguments,0):[],null===this.current_event&&null!=this.state&&(this.current_event=this[this.state]()),null!==this.current_event){if(0===t.length)return!0;for(n=0,r=t.length;n', but found "+this.peek_token().id,this.peek_token().start_mark);u=this.get_token(),e=u.end_mark,n=new r.DocumentStartEvent(a,e,!0,c,s),this.states.push("parse_document_end"),this.state="parse_document_content"}return n},e.prototype.parse_document_end=function(){var e,t,n,o,a;return a=this.peek_token(),o=e=a.start_mark,n=!1,this.check_token(i.DocumentEndToken)&&(a=this.get_token(),e=a.end_mark,n=!0),t=new r.DocumentEndEvent(o,e,n),this.state="parse_document_start",t},e.prototype.parse_document_content=function(){var e;return this.check_token(i.DirectiveToken,i.DocumentStartToken,i.DocumentEndToken,i.StreamEndToken)?(e=this.process_empty_scalar(this.peek_token().start_mark),this.state=this.states.pop(),e):this.parse_block_node()},e.prototype.process_directives=function(){var e,r,o,s,u,c,l,p,f,h;for(this.yaml_version=null,this.tag_handles={};this.check_token(i.DirectiveToken);)if(f=this.get_token(),"YAML"===f.name){if(null!==this.yaml_version)throw new t.ParserError(null,null,"found duplicate YAML directive",f.start_mark);if(u=f.value,r=u[0],o=u[1],1!==r)throw new t.ParserError(null,null,"found incompatible YAML document (version 1.* is required)",f.start_mark);this.yaml_version=f.value}else if("TAG"===f.name){if(c=f.value,e=c[0],s=c[1],e in this.tag_handles)throw new t.ParserError(null,null,"duplicate tag handle "+e,f.start_mark);this.tag_handles[e]=s}p=null,l=this.tag_handles;for(e in l)a.call(l,e)&&(s=l[e],null==p&&(p={}),p[e]=s);h=[this.yaml_version,p];for(e in n)a.call(n,e)&&(s=n[e],s in this.tag_handles||(this.tag_handles[e]=s));return h},e.prototype.parse_block_node=function(){return this.parse_node(!0)},e.prototype.parse_flow_node=function(){return this.parse_node()},e.prototype.parse_block_node_or_indentless_sequence=function(){return this.parse_node(!0,!0)},e.prototype.parse_node=function(e,n){var o,a,s,u,c,l,p,f,h,d,m;if(null==e&&(e=!1),null==n&&(n=!1),this.check_token(i.AliasToken))m=this.get_token(),s=new r.AliasEvent(m.value,m.start_mark,m.end_mark),this.state=this.states.pop();else{if(o=null,h=null,p=a=d=null,this.check_token(i.AnchorToken)?(m=this.get_token(),p=m.start_mark,a=m.end_mark,o=m.value,this.check_token(i.TagToken)&&(m=this.get_token(),d=m.start_mark,a=m.end_mark,h=m.value)):this.check_token(i.TagToken)&&(m=this.get_token(),p=d=m.start_mark,a=m.end_mark,h=m.value,this.check_token(i.AnchorToken)&&(m=this.get_token(),a=m.end_mark,o=m.value)),null!==h)if(u=h[0],f=h[1],null!==u){if(!(u in this.tag_handles))throw new t.ParserError("while parsing a node",p,"found undefined tag handle "+u,d);h=this.tag_handles[u]+f}else h=f;if(null===p&&(p=a=this.peek_token().start_mark),s=null,c=null===h||"!"===h,n&&this.check_token(i.BlockEntryToken))a=this.peek_token().end_mark,s=new r.SequenceStartEvent(o,h,c,p,a),this.state="parse_indentless_sequence_entry";else if(this.check_token(i.ScalarToken))m=this.get_token(),a=m.end_mark,c=m.plain&&null===h||"!"===h?[!0,!1]:null===h?[!1,!0]:[!1,!1],s=new r.ScalarEvent(o,h,c,m.value,p,a,m.style),this.state=this.states.pop();else if(this.check_token(i.FlowSequenceStartToken))a=this.peek_token().end_mark,s=new r.SequenceStartEvent(o,h,c,p,a,!0),this.state="parse_flow_sequence_first_entry";else if(this.check_token(i.FlowMappingStartToken))a=this.peek_token().end_mark,s=new r.MappingStartEvent(o,h,c,p,a,!0),this.state="parse_flow_mapping_first_key";else if(e&&this.check_token(i.BlockSequenceStartToken))a=this.peek_token().end_mark,s=new r.SequenceStartEvent(o,h,c,p,a,!1),this.state="parse_block_sequence_first_entry";else if(e&&this.check_token(i.BlockMappingStartToken))a=this.peek_token().end_mark,s=new r.MappingStartEvent(o,h,c,p,a,!1),this.state="parse_block_mapping_first_key";else{if(null===o&&null===h)throw l=e?"block":"flow",m=this.peek_token(),new t.ParserError("while parsing a "+l+" node",p,"expected the node content, but found "+m.id,m.start_mark);s=new r.ScalarEvent(o,h,[c,!1],"",p,a),this.state=this.states.pop()}}return s},e.prototype.parse_block_sequence_first_entry=function(){var e;return e=this.get_token(),this.marks.push(e.start_mark),this.parse_block_sequence_entry()},e.prototype.parse_block_sequence_entry=function(){var e,n;if(this.check_token(i.BlockEntryToken))return n=this.get_token(),this.check_token(i.BlockEntryToken,i.BlockEndToken)?(this.state="parse_block_sequence_entry",this.process_empty_scalar(n.end_mark)):(this.states.push("parse_block_sequence_entry"),this.parse_block_node());if(!this.check_token(i.BlockEndToken))throw n=this.peek_token(),new t.ParserError("while parsing a block collection",this.marks.slice(-1)[0],"expected , but found "+n.id,n.start_mark);return n=this.get_token(),e=new r.SequenceEndEvent(n.start_mark,n.end_mark),this.state=this.states.pop(),this.marks.pop(),e},e.prototype.parse_indentless_sequence_entry=function(){var e,t;return this.check_token(i.BlockEntryToken)?(t=this.get_token(),this.check_token(i.BlockEntryToken,i.KeyToken,i.ValueToken,i.BlockEndToken)?(this.state="parse_indentless_sequence_entry",this.process_empty_scalar(t.end_mark)):(this.states.push("parse_indentless_sequence_entry"),this.parse_block_node())):(t=this.peek_token(),e=new r.SequenceEndEvent(t.start_mark,t.start_mark),this.state=this.states.pop(),e)},e.prototype.parse_block_mapping_first_key=function(){var e;return e=this.get_token(),this.marks.push(e.start_mark),this.parse_block_mapping_key()},e.prototype.parse_block_mapping_key=function(){var e,n;if(this.check_token(i.KeyToken))return n=this.get_token(),this.check_token(i.KeyToken,i.ValueToken,i.BlockEndToken)?(this.state="parse_block_mapping_value",this.process_empty_scalar(n.end_mark)):(this.states.push("parse_block_mapping_value"),this.parse_block_node_or_indentless_sequence());if(!this.check_token(i.BlockEndToken))throw n=this.peek_token(),new t.ParserError("while parsing a block mapping",this.marks.slice(-1)[0],"expected , but found "+n.id,n.start_mark);return n=this.get_token(),e=new r.MappingEndEvent(n.start_mark,n.end_mark),this.state=this.states.pop(),this.marks.pop(),e},e.prototype.parse_block_mapping_value=function(){var e;return this.check_token(i.ValueToken)?(e=this.get_token(),this.check_token(i.KeyToken,i.ValueToken,i.BlockEndToken)?(this.state="parse_block_mapping_key",this.process_empty_scalar(e.end_mark)):(this.states.push("parse_block_mapping_key"),this.parse_block_node_or_indentless_sequence())):(this.state="parse_block_mapping_key",e=this.peek_token(),this.process_empty_scalar(e.start_mark))},e.prototype.parse_flow_sequence_first_entry=function(){var e;return e=this.get_token(),this.marks.push(e.start_mark),this.parse_flow_sequence_entry(!0)},e.prototype.parse_flow_sequence_entry=function(e){var n,o;if(null==e&&(e=!1),!this.check_token(i.FlowSequenceEndToken)){if(!e){if(!this.check_token(i.FlowEntryToken))throw o=this.peek_token(),new t.ParserError("while parsing a flow sequence",this.marks.slice(-1)[0],"expected ',' or ']', but got "+o.id,o.start_mark);this.get_token()}if(this.check_token(i.KeyToken))return o=this.peek_token(),n=new r.MappingStartEvent(null,null,!0,o.start_mark,o.end_mark,!0),this.state="parse_flow_sequence_entry_mapping_key",n;if(!this.check_token(i.FlowSequenceEndToken))return this.states.push("parse_flow_sequence_entry"),this.parse_flow_node()}return o=this.get_token(),n=new r.SequenceEndEvent(o.start_mark,o.end_mark),this.state=this.states.pop(),this.marks.pop(),n},e.prototype.parse_flow_sequence_entry_mapping_key=function(){var e;return e=this.get_token(),this.check_token(i.ValueToken,i.FlowEntryToken,i.FlowSequenceEndToken)?(this.state="parse_flow_sequence_entry_mapping_value",this.process_empty_scalar(e.end_mark)):(this.states.push("parse_flow_sequence_entry_mapping_value"),this.parse_flow_node())},e.prototype.parse_flow_sequence_entry_mapping_value=function(){var e;return this.check_token(i.ValueToken)?(e=this.get_token(),this.check_token(i.FlowEntryToken,i.FlowSequenceEndToken)?(this.state="parse_flow_sequence_entry_mapping_end",this.process_empty_scalar(e.end_mark)):(this.states.push("parse_flow_sequence_entry_mapping_end"),this.parse_flow_node())):(this.state="parse_flow_sequence_entry_mapping_end",e=this.peek_token(),this.process_empty_scalar(e.start_mark))},e.prototype.parse_flow_sequence_entry_mapping_end=function(){var e;return this.state="parse_flow_sequence_entry",e=this.peek_token(),new r.MappingEndEvent(e.start_mark,e.start_mark)},e.prototype.parse_flow_mapping_first_key=function(){var e;return e=this.get_token(),this.marks.push(e.start_mark),this.parse_flow_mapping_key(!0)},e.prototype.parse_flow_mapping_key=function(e){var n,o;if(null==e&&(e=!1),!this.check_token(i.FlowMappingEndToken)){if(!e){if(!this.check_token(i.FlowEntryToken))throw o=this.peek_token(),new t.ParserError("while parsing a flow mapping",this.marks.slice(-1)[0],"expected ',' or '}', but got "+o.id,o.start_mark);this.get_token()}if(this.check_token(i.KeyToken))return o=this.get_token(),this.check_token(i.ValueToken,i.FlowEntryToken,i.FlowMappingEndToken)?(this.state="parse_flow_mapping_value",this.process_empty_scalar(o.end_mark)):(this.states.push("parse_flow_mapping_value"),this.parse_flow_node());if(!this.check_token(i.FlowMappingEndToken))return this.states.push("parse_flow_mapping_empty_value"),this.parse_flow_node()}return o=this.get_token(),n=new r.MappingEndEvent(o.start_mark,o.end_mark),this.state=this.states.pop(),this.marks.pop(),n},e.prototype.parse_flow_mapping_value=function(){var e;return this.check_token(i.ValueToken)?(e=this.get_token(),this.check_token(i.FlowEntryToken,i.FlowMappingEndToken)?(this.state="parse_flow_mapping_key",this.process_empty_scalar(e.end_mark)):(this.states.push("parse_flow_mapping_key"),this.parse_flow_node())):(this.state="parse_flow_mapping_key",e=this.peek_token(),this.process_empty_scalar(e.start_mark))},e.prototype.parse_flow_mapping_empty_value=function(){return this.state="parse_flow_mapping_key",this.process_empty_scalar(this.peek_token().start_mark)},e.prototype.process_empty_scalar=function(e){return new r.ScalarEvent(null,null,[!0,!1],"",e,e)},e}()}).call(this)},function(e,t,n){function r(e){return n(i(e))}function i(e){return o[e]||function(){throw new Error("Cannot find module '"+e+"'.")}()}var o={"./composer":853,"./composer.js":853,"./constructor":857,"./constructor.js":857,"./dumper":862,"./dumper.js":862,"./emitter":863,"./emitter.js":863,"./errors":855,"./errors.js":855,"./events":854,"./events.js":854,"./loader":867,"./loader.js":867,"./nodes":856,"./nodes.js":856,"./parser":871,"./parser.js":871,"./reader":868,"./reader.js":868,"./representer":865,"./representer.js":865,"./resolver":866,"./resolver.js":866,"./scanner":869,"./scanner.js":869,"./serializer":864,"./serializer.js":864,"./tokens":870,"./tokens.js":870,"./util":858,"./util.js":858,"./yaml":852,"./yaml.js":852};r.keys=function(){return Object.keys(o)},r.resolve=i,e.exports=r,r.id=872},function(e,t){},function(e,t,n){var r=n(875),i=n(876),o=r(i);e.exports=o},function(e,t,n){function r(e){return function(t,n,r){var s=Object(t);if(!o(t)){var u=i(n,3);t=a(t),n=function(e){return u(s[e],e,s)}}var c=e(t,n,r);return c>-1?s[u?t[c]:c]:void 0}}var i=n(400),o=n(437),a=n(421);e.exports=r},function(e,t,n){function r(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var u=null==n?0:a(n);return u<0&&(u=s(r+u,0)),i(e,o(t,3),u)}var i=n(877),o=n(400),a=n(878),s=Math.max;e.exports=r},function(e,t){function n(e,t,n,r){for(var i=e.length,o=n+(r?1:-1);r?o--:++o2&&void 0!==arguments[2]?arguments[2]:"";return(e.operationId||"").replace(/\s/g,"").length?b(e.operationId):o(t,n)}function o(e,t){return""+_(t)+b(e)}function a(e,t){return _(t)+"-"+e}function s(e,t){return e&&e.paths?u(e,function(e){var n=e.pathName,r=e.method,o=e.operation;if(!o||"object"!==(void 0===o?"undefined":(0,y.default)(o)))return!1;var s=o.operationId;return[i(o,n,r),a(n,r),s].some(function(e){return e&&e===t})}):null}function u(e,t){return c(e,t,!0)||null}function c(e,t,n){if(!e||"object"!==(void 0===e?"undefined":(0,y.default)(e))||!e.paths||"object"!==(0,y.default)(e.paths))return null;var r=e.paths;for(var i in r)for(var o in r[i])if("PARAMETERS"!==o.toUpperCase()){var a=r[i][o];if(a&&"object"===(void 0===a?"undefined":(0,y.default)(a))){var s={spec:e,pathName:i,method:o.toUpperCase(),operation:a},u=t(s);if(n&&u)return s}}}function l(e){var t=e.spec,n=t.paths,r={};if(!n)return e;for(var o in n){var a=n[o];if((0,g.default)(a)){var s=a.parameters;for(var u in a)!function(e){var n=a[e];if(!(0,g.default)(n))return"continue";var u=i(n,o,e);if(u&&(r[u]?r[u].push(n):r[u]=[n],(0,d.default)(r).forEach(function(e){r[e].length>1?r[e].forEach(function(t,n){t.operationId=""+e+(n+1)}):void 0!==n.operationId&&(n.__originalOperationId=n.operationId,n.operationId=e)})),"parameters"!==e){var c=[],l={};for(var p in t)"produces"!==p&&"consumes"!==p&&"security"!==p||(l[p]=t[p],c.push(l));if(s&&(l.parameters=s,c.push(l)),c.length){var h=!0,m=!1,y=void 0;try{for(var v,_=(0,f.default)(c);!(h=(v=_.next()).done);h=!0){var b=v.value;for(var x in b)if(n[x]){if("parameters"===x){var w=!0,k=!1,S=void 0;try{for(var E,C=(0,f.default)(b[x]);!(w=(E=C.next()).done);w=!0)!function(){var e=E.value;n[x].some(function(t){return t.name===e.name})||n[x].push(e)}()}catch(e){k=!0,S=e}finally{try{!w&&C.return&&C.return()}finally{if(k)throw S}}}}else n[x]=b[x]}}catch(e){m=!0,y=e}finally{try{!h&&_.return&&_.return()}finally{if(m)throw y}}}}}(u)}}return e}Object.defineProperty(t,"__esModule",{value:!0});var p=n(10),f=r(p),h=n(0),d=r(h),m=n(5),y=r(m);t.opId=i,t.idFromPathMethod=o,t.legacyIdFromPathMethod=a,t.getOperationRaw=s,t.findOperation=u,t.eachOperation=c,t.normalizeSwagger=l;var v=n(40),g=r(v),_=function(e){return String.prototype.toLowerCase.call(e)},b=function(e){return e.replace(/[^\w]/gi,"_")}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t,n){if(n=n||{},t=(0,q.default)({},t,{path:t.path&&o(t.path)}),"merge"===t.op){var r=s(t.path);W.default.apply(e,[r]),(0,q.default)(r.value,t.value)}else if("mergeDeep"===t.op){var i=s(t.path);W.default.apply(e,[i]),(0,J.default)(i.value,t.value)}else if(W.default.apply(e,[t]),n.allowMetaPatches&&t.meta&&M(t)&&(Array.isArray(t.value)||S(t.value))){var a=s(t.path);W.default.apply(e,[a]),(0,q.default)(a.value,t.meta)}return e}function o(e){return Array.isArray(e)?e.length<1?"":"/"+e.map(function(e){return(e+"").replace(/~/g,"~0").replace(/\//g,"~1")}).join("/"):e}function a(e,t){return{op:"add",path:e,value:t}}function s(e){return{op:"_get",path:e}}function u(e,t,n){return{op:"replace",path:e,value:t,meta:n}}function c(e,t){return{op:"remove",path:e}}function l(e,t){return{type:"mutation",op:"merge",path:e,value:t}}function p(e,t){return{type:"mutation", +op:"mergeDeep",path:e,value:t}}function f(e,t){return{type:"context",path:e,value:t}}function h(e,t){try{return m(e,v,t)}catch(e){return e}}function d(e,t){try{return m(e,y,t)}catch(e){return e}}function m(e,t,n){return k(w(e.filter(M).map(function(e){return t(e.value,n,e.path)})||[]))}function y(e,t,n){return n=n||[],Array.isArray(e)?e.map(function(e,r){return y(e,t,n.concat(r))}):S(e)?(0,L.default)(e).map(function(r){return y(e[r],t,n.concat(r))}):t(e,n[n.length-1],n)}function v(e,t,n){n=n||[];var r=[];if(n.length>0){var i=t(e,n[n.length-1],n);i&&(r=r.concat(i))}if(Array.isArray(e)){var o=e.map(function(e,r){return v(e,t,n.concat(r))});o&&(r=r.concat(o))}else if(S(e)){var a=(0,L.default)(e).map(function(r){return v(e[r],t,n.concat(r))});a&&(r=r.concat(a))}return r=w(r)}function g(e,t){if(!Array.isArray(t))return!1;for(var n=0,r=t.length;n1&&void 0!==arguments[1]?arguments[1]:{};return"object"===(void 0===e?"undefined":(0,b.default)(e))&&(t=e,e=t.url),t.headers=t.headers||{},T.mergeInQueryOrForm(t),t.requestInterceptor&&(t=t.requestInterceptor(t)||t),/multipart\/form-data/i.test(t.headers["content-type"]||t.headers["Content-Type"])&&(delete t.headers["content-type"],delete t.headers["Content-Type"]),fetch(t.url,t).then(function(n){var r=T.serializeRes(n,e,t).then(function(e){return t.responseInterceptor&&(e=t.responseInterceptor(e)||e),e});if(!n.ok){var i=new Error(n.statusText);return i.statusCode=i.status=n.status,r.then(function(e){throw i.response=e,i},function(e){throw i.responseError=e,i})}return r})}function o(e){return/json/.test(e)||/xml/.test(e)||/yaml/.test(e)||/text/.test(e)}function a(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.loadSpec,i=void 0!==r&&r,a={ok:e.ok,url:e.url||t,status:e.status,statusText:e.statusText,headers:s(e.headers)},u=i||o(a.headers["content-type"]);return(u?e.text:e.blob||e.buffer).call(e).then(function(e){if(a.text=e,a.data=e,u)try{var t=S.default.safeLoad(e);a.body=t,a.obj=t}catch(e){a.parseError=e}return a})}function s(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};return"function"==typeof e.forEach?(e.forEach(function(e,n){void 0!==t[n]?(t[n]=Array.isArray(t[n])?t[n]:[t[n]],t[n].push(e)):t[n]=e}),t):t}function u(e){return"undefined"!=typeof File?e instanceof File:null!==e&&"object"===(void 0===e?"undefined":(0,b.default)(e))&&"function"==typeof e.pipe}function c(e,t){var n=e.value,r=e.collectionFormat,i=e.allowEmptyValue,o={csv:",",ssv:"%20",tsv:"%09",pipes:"|"};if(void 0===n&&i)return"";if(u(n))return n;var a=encodeURIComponent;return t&&(a=(0,A.default)(n)?function(e){return e}:function(e){return(0,g.default)(e)}),n&&!Array.isArray(n)?a(n):Array.isArray(n)&&!r?n.map(a).join(","):"multi"===r?n.map(a):n.map(a).join(o[r])}function l(e){var t=(0,y.default)(e).reduce(function(t,n){var r=e[n],i=encodeURIComponent(n),o=function(e){return e&&"object"===(void 0===e?"undefined":(0,b.default)(e))}(r)&&!Array.isArray(r);return t[i]=c(o?r:{value:r}),t},{});return w.default.stringify(t,{encode:!1,indices:!1})||""}function p(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.url,r=void 0===t?"":t,i=e.query,o=e.form;if(o){var a=(0,y.default)(o).some(function(e){return u(o[e].value)}),s=e.headers["content-type"]||e.headers["Content-Type"];if(a||/multipart\/form-data/i.test(s)){var p=n(35);e.body=new p,(0,y.default)(o).forEach(function(t){e.body.append(t,c(o[t],!0))})}else e.body=l(o);delete e.form}if(i){var f=r.split("?"),h=(0,d.default)(f,2),m=h[0],v=h[1],g="";if(v){var _=w.default.parse(v);(0,y.default)(i).forEach(function(e){return delete _[e]}),g=w.default.stringify(_,{encode:!0})}var b=function(){for(var e=arguments.length,t=Array(e),n=0;n1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e?n.url=e:n=e,!(this instanceof i))return new i(n);(0,c.default)(this,n);var r=this.resolve().then(function(){return t.disableInterfaces||(0,c.default)(t,i.makeApisTagOperation(t)),t});return r.client=this,r}var o=n(4),a=r(o),s=n(37),u=(r(s),n(8)),c=r(u),l=n(6),p=r(l),f=n(19),h=r(f),d=n(9),m=r(d),y=n(18),v=n(17),g=n(2);i.http=p.default,i.makeHttp=l.makeHttp.bind(null,i.http),i.resolve=h.default,i.execute=v.execute,i.serializeRes=l.serializeRes,i.serializeHeaders=l.serializeHeaders,i.clearCache=f.clearCache,i.parameterBuilders=v.PARAMETER_BUILDERS,i.makeApisTagOperation=y.makeApisTagOperation,i.buildRequest=v.buildRequest,i.helpers={opId:g.opId},e.exports=i,i.prototype={http:p.default,execute:function(e){return this.applyDefaults(),i.execute((0,a.default)({spec:this.spec,http:this.http.bind(this),securities:{authorized:this.authorizations}},e))},resolve:function(){var e=this;return i.resolve({spec:this.spec,url:this.url,allowMetaPatches:this.allowMetaPatches}).then(function(t){return e.originalSpec=e.spec,e.spec=t.spec,e.errors=t.errors,e})}},i.prototype.applyDefaults=function(){var e=this.spec,t=this.url;if(t&&t.startsWith("http")){var n=m.default.parse(t);e.host||(e.host=n.host),e.schemes||(e.schemes=[n.protocol.replace(":","")]),e.basePath||(e.basePath="/")}}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=e.http,n=e.fetch,r=e.spec,i=e.operationId,o=e.pathName,a=e.method,s=e.parameters,u=e.securities,c=(0,b.default)(e,["http","fetch","spec","operationId","pathName","method","parameters","securities"]);t=t||n||I.default,o&&a&&!i&&(i=(0,j.legacyIdFromPathMethod)(o,a));var l=N.buildRequest((0,g.default)({spec:r,operationId:i,parameters:s,securities:u},c));return l.body&&((0,E.default)(l.body)||(0,A.default)(l.body))&&(l.body=(0,y.default)(l.body)),t(l)}function o(e){var t=e.spec,n=e.operationId,r=e.parameters,i=e.securities,o=e.requestContentType,a=e.responseContentType,s=e.parameterBuilders,u=e.scheme,c=e.requestInterceptor,l=e.responseInterceptor,h=e.contextUrl;s=s||F;var d={url:p({spec:t,scheme:u,contextUrl:h}),credentials:"same-origin",headers:{}};if(c&&(d.requestInterceptor=c),l&&(d.responseInterceptor=l),!n)return d;var m=(0,j.getOperationRaw)(t,n),y=m.operation,v=void 0===y?{}:y,g=m.method,_=m.pathName;return d.url+=_,d.method=(""+g).toUpperCase(),r=r||{},a&&(d.headers.accept=a),R(v.parameters).concat(R(t.paths[_].parameters)).forEach(function(e){var n=s[e.in],i=void 0;if("body"===e.in&&e.schema&&e.schema.properties&&(i=r),i=e&&e.name&&r[e.name],void 0!==e.default&&void 0===i&&(i=e.default),void 0===i&&e.required&&!e.allowEmptyValue)throw new Error("Required parameter "+e.name+" is not provided");n&&n({req:d,parameter:e,value:i,operation:v,spec:t})}),d=f({request:d,securities:i,operation:v,spec:t}),(d.body||d.form)&&(o?d.headers["content-type"]=o:Array.isArray(v.consumes)?d.headers["content-type"]=v.consumes[0]:Array.isArray(t.consumes)?d.headers["content-type"]=t.consumes[0]:v.parameters.filter(function(e){return"file"===e.type}).length?d.headers["content-type"]="multipart/form-data":v.parameters.filter(function(e){return"formData"===e.in}).length&&(d.headers["content-type"]="application/x-www-form-urlencoded")),(0,P.mergeInQueryOrForm)(d),d}function a(e){var t=e.req,n=e.value;t.body=n}function s(e){var t=e.req,n=e.value,r=e.parameter;t.form=t.form||{},(n||r.allowEmptyValue)&&(t.form[r.name]={value:n,allowEmptyValue:r.allowEmptyValue,collectionFormat:r.collectionFormat})}function u(e){var t=e.req,n=e.parameter,r=e.value;t.headers=t.headers||{},void 0!==r&&(t.headers[n.name]=r)}function c(e){var t=e.req,n=e.value,r=e.parameter;t.url=t.url.replace("{"+r.name+"}",encodeURIComponent(n))}function l(e){var t=e.req,n=e.value,r=e.parameter;if(t.query=t.query||{},n)t.query[r.name]={collectionFormat:r.collectionFormat,value:n};else if(r.allowEmptyValue){var i=r.name;t.query[i]=t.query[i]||{},t.query[i].allowEmptyValue=!0}}function p(e){var t=e.spec,n=e.scheme,r=e.contextUrl,i=void 0===r?"":r,o=M.default.parse(i),a=Array.isArray(t.schemes)?t.schemes[0]:null,s=n||a||B(o.protocol)||"http",u=t.host||o.host||"",c=t.basePath||"";if(s&&u){var l=s+"://"+(u+c);return"/"===l[l.length-1]?l.slice(0,-1):l}return""}function f(e){var t=e.request,n=e.securities,r=void 0===n?{}:n,i=e.operation,o=void 0===i?{}:i,a=e.spec,s=(0,w.default)({},t),u=r.authorized,c=void 0===u?{}:u,l=r.specSecurity,p=void 0===l?{}:l,f=o.security||p,h=c&&!!(0,d.default)(c).length,m=a.securityDefinitions;return s.headers=s.headers||{},s.query=s.query||{},(0,d.default)(r).length&&h&&f&&(!Array.isArray(o.security)||o.security.length)?(f.forEach(function(e,t){for(var n in e){var r=c[n];if(r){var i=r.token,o=r.value||r,a=m[n],u=a.type,l=i&&i.access_token,p=i&&i.token_type;if(r)if("apiKey"===u){var f="query"===a.in?"query":"headers";s[f]=s[f]||{},s[f][a.name]=o}else"basic"===u?o.header?s.headers.authorization=o.header:(o.base64=(0,O.default)(o.username+":"+o.password),s.headers.authorization="Basic "+o.base64):"oauth2"===u&&(s.headers.authorization=(p||"Bearer")+" "+l)}}}),s):t}Object.defineProperty(t,"__esModule",{value:!0}),t.PARAMETER_BUILDERS=t.self=void 0;var h=n(0),d=r(h),m=n(7),y=r(m),v=n(4),g=r(v),_=n(29),b=r(_);t.execute=i,t.buildRequest=o,t.bodyBuilder=a,t.formDataBuilder=s,t.headerBuilder=u,t.pathBuilder=c,t.queryBuilder=l,t.baseUrl=p,t.applySecurities=f;var x=n(8),w=r(x),k=n(38),S=(r(k),n(41)),E=r(S),C=n(39),A=r(C),T=n(32),O=r(T),D=n(9),M=r(D),P=n(6),I=r(P),j=n(2),R=function(e){return Array.isArray(e)?e:[]},N=t.self={buildRequest:o},F=t.PARAMETER_BUILDERS={body:a,header:u,query:l,path:c,formData:s},B=function(e){return e?e.replace(/\W/g,""):null}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t){var n=t.pathName,r=t.method,i=t.operationId;return function(t){var o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e.execute((0,c.default)({spec:e.spec},(0,p.default)(e,"requestInterceptor","responseInterceptor"),{pathName:n,method:r,parameters:t,operationId:i},o))}}}function o(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=m.makeExecute(e),n=m.mapTagOperations({spec:e.spec,cb:t}),r={};for(var i in n){r[i]={operations:{}};for(var o in n[i])r[i].operations[o]={execute:n[i][o]}}return{apis:r}}function a(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=m.makeExecute(e);return{apis:m.mapTagOperations({spec:e.spec,cb:t})}}function s(e){var t=e.spec,n=e.cb,r=void 0===n?h:n,i=e.defaultTag,o=void 0===i?"default":i,a={},s={};return(0,f.eachOperation)(t,function(e){var n=e.pathName,i=e.method,u=e.operation;(u.tags?d(u.tags):[o]).forEach(function(e){if("string"==typeof e){var o=s[e]=s[e]||{},c=(0,f.opId)(u,n,i),l=r({spec:t,pathName:n,method:i,operation:u,operationId:c});if(a[c])a[c]=a[c]+1,o[""+c+a[c]]=l;else if(void 0!==o[c]){var p=a[c]||1;a[c]=p+1,o[""+c+a[c]]=l;var h=o[c];delete o[c],o[""+c+p]=h}else o[c]=l}})}),s}Object.defineProperty(t,"__esModule",{value:!0}),t.self=void 0;var u=n(4),c=r(u);t.makeExecute=i,t.makeApisTagOperationsOperationExecute=o,t.makeApisTagOperation=a,t.mapTagOperations=s;var l=n(43),p=r(l),f=n(2),h=function(){return null},d=function(e){return Array.isArray(e)?e:[e]},m=t.self={mapTagOperations:s,makeExecute:i}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e){return function(t){return e({url:t,loadSpec:!0,headers:{Accept:"application/json"}}).then(function(e){return e.body})}}function o(){c.plugins.refs.clearCache()}function a(e){function t(e){s&&(c.plugins.refs.docCache[s]=e),c.plugins.refs.fetchJSON=i(n);var t=[c.plugins.refs];return"function"==typeof y&&t.push(c.plugins.parameters),"function"==typeof m&&t.push(c.plugins.properties),"strict"!==f&&t.push(c.plugins.allOf),(0,l.default)({spec:e,context:{baseDoc:s},plugins:t,allowMetaPatches:d,parameterMacro:y,modelPropertyMacro:m}).then(p.normalizeSwagger)}var n=e.http,r=e.fetch,o=e.spec,a=e.url,s=e.baseDoc,f=e.mode,h=e.allowMetaPatches,d=void 0===h||h,m=e.modelPropertyMacro,y=e.parameterMacro;return s=s||a,n=r||n||u.default,o?t(o):i(n)(s).then(t)}Object.defineProperty(t,"__esModule",{value:!0}),t.makeFetchJSON=i,t.clearCache=o,t.default=a;var s=n(6),u=r(s),c=n(20),l=r(c),p=n(2)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e){return new R(e).dispatch()}Object.defineProperty(t,"__esModule",{value:!0}),t.plugins=t.SpecMap=void 0;var o=n(7),a=r(o),s=n(11),u=r(s),c=n(14),l=r(c),p=n(0),f=r(p),h=n(10),d=r(h),m=n(27),y=r(m),v=n(1),g=r(v),_=n(12),b=r(_),x=n(13),w=r(x);t.default=i;var k=n(3),S=r(k),E=n(26),C=r(E),A=n(21),T=r(A),O=n(24),D=r(O),M=n(25),P=r(M),I=n(22),j=r(I),R=function(){function e(t){(0,b.default)(this,e),(0,g.default)(this,{spec:"",debugLevel:"info",plugins:[],pluginHistory:{},errors:[],mutations:[],promisedPatches:[],state:{},patches:[],context:{},contextTree:new j.default,showDebug:!1,allPatches:[],pluginProp:"specMap",libMethods:(0,g.default)((0,y.default)(this),S.default),allowMetaPatches:!1},t),this.get=this._get.bind(this),this.getContext=this._getContext.bind(this),this.hasRun=this._hasRun.bind(this),this.wrappedPlugins=this.plugins.map(this.wrapPlugin.bind(this)).filter(S.default.isFunction),this.patches.push(S.default.add([],this.spec)),this.patches.push(S.default.context([],this.context)),this.updatePatches(this.patches)}return(0,w.default)(e,[{key:"debug",value:function(e){if(this.debugLevel===e){for(var t,n=arguments.length,r=Array(n>1?n-1:0),i=1;i1?n-1:0),i=1;i0})}},{key:"nextPromisedPatch",value:function(){if(this.promisedPatches.length>0)return u.default.race(this.promisedPatches.map(function(e){return e.value}))}},{key:"getPluginHistory",value:function(e){var t=this.getPluginName(e);return this.pluginHistory[t]||[]}},{key:"getPluginRunCount",value:function(e){return this.getPluginHistory(e).length}},{key:"getPluginHistoryTip",value:function(e){var t=this.getPluginHistory(e);return t&&t[t.length-1]||{}}},{key:"getPluginMutationIndex",value:function(e){var t=this.getPluginHistoryTip(e).mutationIndex;return"number"!=typeof t?-1:t}},{key:"getPluginName",value:function(e){return e.pluginName}},{key:"updatePluginHistory",value:function(e,t){var n=this.getPluginName(e);(this.pluginHistory[n]=this.pluginHistory[n]||[]).push(t)}},{key:"updatePatches",value:function(e,t){var n=this;S.default.normalizeArray(e).forEach(function(e){if(e instanceof Error)return void n.errors.push(e);try{if(!S.default.isObject(e))return void n.debug("updatePatches","Got a non-object patch",e);if(n.showDebug&&n.allPatches.push(e),S.default.isPromise(e.value))return n.promisedPatches.push(e),void n.promisedPatchThen(e);if(S.default.isContextPatch(e))return void n.setContext(e.path,e.value);if(S.default.isMutation(e))return void n.updateMutations(e)}catch(e){n.errors.push(e)}})}},{key:"updateMutations",value:function(e){S.default.applyPatch(this.state,e,{allowMetaPatches:this.allowMetaPatches})&&this.mutations.push(e)}},{key:"removePromisedPatch",value:function(e){var t=this.promisedPatches.indexOf(e);return t<0?void this.debug("Tried to remove a promisedPatch that isn't there!"):void this.promisedPatches.splice(t,1)}},{key:"promisedPatchThen",value:function(e){var t=this;return e.value=e.value.then(function(n){var r=(0,g.default)({},e,{value:n});t.removePromisedPatch(e),t.updatePatches(r)}).catch(function(n){t.removePromisedPatch(e),t.updatePatches(n)})}},{key:"getMutations",value:function(e,t){return e=e||0,"number"!=typeof t&&(t=this.mutations.length),this.mutations.slice(e,t)}},{key:"getCurrentMutations",value:function(){return this.getMutationsForPlugin(this.getCurrentPlugin())}},{key:"getMutationsForPlugin",value:function(e){var t=this.getPluginMutationIndex(e);return this.getMutations(t+1)}},{key:"getCurrentPlugin",value:function(){return this.currentPlugin}},{key:"getPatchesOfType",value:function(e,t){return e.filter(t)}},{key:"getLib",value:function(){return this.libMethods}},{key:"_get",value:function(e){return S.default.getIn(this.state,e)}},{key:"_getContext",value:function(e){return this.contextTree.get(e)}},{key:"setContext",value:function(e,t){return this.contextTree.set(e,t)}},{key:"_hasRun",value:function(e){return this.getPluginRunCount(this.getCurrentPlugin())>(e||0)}},{key:"_clone",value:function(e){return JSON.parse((0,a.default)(e))}},{key:"dispatch",value:function(){function e(e){e&&(e=S.default.fullyNormalizeArray(e),n.updatePatches(e,r))}var t=this,n=this,r=this.nextPlugin();if(!r){var i=this.nextPromisedPatch();if(i)return i.then(function(){return t.dispatch()}).catch(function(){return t.dispatch()});var o={spec:this.state,errors:this.errors};return this.showDebug&&(o.patches=this.allPatches),u.default.resolve(o)}if(n.pluginCount=n.pluginCount||{},n.pluginCount[r]=(n.pluginCount[r]||0)+1,n.pluginCount[r]>100)return u.default.resolve({spec:n.state,errors:n.errors.concat(new Error("We've reached a hard limit of 100 plugin runs"))});if(r!==this.currentPlugin&&this.promisedPatches.length){var a=this.promisedPatches.map(function(e){return e.value});return u.default.all(a.map(function(e){return e.then(Function,Function)})).then(function(){return t.dispatch()})}return function(){n.currentPlugin=r;var t=n.getCurrentMutations(),i=n.mutations.length-1;try{if(r.isGenerator){var o=!0,a=!1,s=void 0;try{for(var u,c=(0,d.default)(r(t,n.getLib()));!(o=(u=c.next()).done);o=!0)e(u.value)}catch(e){a=!0,s=e}finally{try{!o&&c.return&&c.return()}finally{if(a)throw s}}}else e(r(t,n.getLib()))}catch(t){e([(0,g.default)((0,y.default)(t),{plugin:r})])}finally{n.updatePluginHistory(r,{mutationIndex:i})}return n.dispatch()}()}}]),e}(),N={refs:C.default,allOf:T.default,parameters:D.default,properties:P.default};t.SpecMap=R,t.plugins=N},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={key:"allOf",plugin:function(e,t,n,r,i){if(!i.meta||!i.meta.$$ref){if(!Array.isArray(e)){var o=new TypeError("allOf must be an array");return o.fullPath=n,o}var a=n.slice(0,-1),s=!1;return[r.replace(a,{})].concat(e.map(function(e,t){if(!r.isObject(e)){if(s)return null;s=!0;var i=new TypeError("Elements in allOf must be objects");return i.fullPath=n,i}return r.mergeDeep(a,e)}))}}}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){return o({children:{}},e,t)}function o(e,t,n){return e.value=t||{},e.protoValue=n?(0,c.default)({},n.protoValue,e.value):e.value,(0,s.default)(e.children).forEach(function(t){var n=e.children[t];e.children[t]=o(n,n.value,e)}),e}Object.defineProperty(t,"__esModule",{value:!0});var a=n(0),s=r(a),u=n(4),c=r(u),l=n(12),p=r(l),f=n(13),h=r(f),d=function(){function e(t){(0,p.default)(this,e),this.root=i(t||{})}return(0,h.default)(e,[{key:"set",value:function(e,t){var n=this.getParent(e,!0);if(!n)return void o(this.root,t,null);var r=e[e.length-1],a=n.children;return a[r]?void o(a[r],t,n):void(a[r]=i(t,n))}},{key:"get",value:function(e){if(e=e||[],e.length<1)return this.root.value;for(var t=this.root,n=void 0,r=void 0,i=0;i")+"#"+e;if(t==r.contextTree.get([]).baseDoc&&y(o,e))return!0;var s="";return!!n.some(function(e){return s=s+"/"+d(e),i[s]&&i[s].some(function(e){return y(e,a)||y(a,e)})})||void(i[o]=(i[o]||[]).concat(a))}function g(e,t){function n(e){return j.default.isObject(e)&&(r.indexOf(e)>=0||(0,w.default)(e).some(function(t){return n(e[t])}))}var r=[e];return t.path.reduce(function(e,t){return r.push(e[t]),e[t]},e),n(t.value)}Object.defineProperty(t,"__esModule",{value:!0});var _=n(5),b=r(_),x=n(0),w=r(x),k=n(11),S=r(k),E=n(28),C=r(E),A=n(1),T=r(A),O=n(15),D=r(O),M=n(9),P=r(M),I=n(3),j=r(I),R=n(23),N=r(R),F=new RegExp("^([a-z]+://|//)","i"),B=(0,N.default)("JSONRefError",function(e,t,n){this.originalError=n,(0,T.default)(this,t||{})}),L={},z=new C.default,q={key:"$ref",plugin:function(e,t,n,r){var u=n.slice(0,-1),c=r.getContext(n).baseDoc;if("string"!=typeof e)return new B("$ref: must be a string (JSON-Ref)",{$ref:e,baseDoc:c,fullPath:n});var l=a(e),p=l[0],h=l[1]||"",d=void 0;try{d=c||p?i(p,c):null}catch(t){return o(t,{pointer:h,$ref:e,basePath:d,fullPath:n})}var m=void 0,y=void 0;if(!v(h,d,u,r)){if(null==d?(y=f(h),void 0===(m=r.get(y))&&(m=new B("Could not resolve reference: "+e,{pointer:h,$ref:e,baseDoc:c,fullPath:n}))):(m=s(d,h),m=null!=m.__value?m.__value:m.catch(function(t){throw o(t,{pointer:h,$ref:e,baseDoc:c,fullPath:n})})),m instanceof Error)return[j.default.remove(n),m];var _=j.default.replace(u,m,{$$ref:e});return d&&d!==c?[_,j.default.context(u,{baseDoc:d})]:g(r.state,_)?void 0:_}}},U=(0,T.default)(q,{docCache:L,absoluteify:i,clearCache:u,JSONRefError:B,wrapError:o,getDoc:c,split:a,extractFromDoc:s,fetchJSON:l,extract:p,jsonPointerToArray:f,unescapeJsonPointerToken:h});t.default=U;var W=function(e){return!e||"/"===e||"#"===e}},function(e,t){e.exports=n(1037)},function(e,t){e.exports=n(1040)},function(e,t){e.exports=n(1048)},function(e,t){e.exports=n(1049)},function(e,t){e.exports=n(1053)},function(e,t){e.exports=n(1058)},function(e,t){e.exports=n(298)},function(e,t){e.exports=n(1059)},function(e,t){e.exports=n(1060)},function(e,t){e.exports=n(583)},function(e,t){e.exports=n(1061)},function(e,t){e.exports=n(1129)},function(e,t){e.exports=n(999)},function(e,t){e.exports=n(980)},function(e,t){e.exports=n(1140)},function(e,t){e.exports=n(1141)},function(e,t){e.exports=n(1142)},function(e,t){e.exports=n(1150)},function(e,t,n){e.exports=n(16)}])},function(e,t,n){e.exports={default:n(885),__esModule:!0}},function(e,t,n){n(886),e.exports=n(906).Object.keys},[1415,887,889,904],[1413,888],35,[1394,890,903],[1395,891,892,895,899],5,[1396,893,888],[1397,894],34,[1398,892,896,898],[1399,897],38,[1400,897],[1401,900,902],[1388,901],4,19,41,[1412,905,906,915],function(e,t,n){var r=n(901),i=n(906),o=n(907),a=n(909),s="prototype",u=function(e,t,n){var c,l,p,f=e&u.F,h=e&u.G,d=e&u.S,m=e&u.P,y=e&u.B,v=e&u.W,g=h?i:i[t]||(i[t]={}),_=g[s],b=h?r:d?r[t]:(r[t]||{})[s];h&&(n=t);for(c in n)l=!f&&b&&void 0!==b[c],l&&c in g||(p=l?b[c]:n[c],g[c]=h&&"function"!=typeof b[c]?n[c]:y&&l?o(p,r):v&&b[c]==p?function(e){var t=function(t,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,r)}return e.apply(this,arguments)};return t[s]=e[s],t}(p):m&&"function"==typeof p?o(Function.call,p):p,m&&((g.virtual||(g.virtual={}))[c]=p,e&u.R&&_&&!_[c]&&a(_,c,p)))};u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,e.exports=u},9,[1386,908],21,[1380,910,918,914],[1381,911,913,917,914],[1382,912],13,[1383,914,915,916],[1379,915],7,[1384,912,901],[1385,912],17,function(e,t,n){e.exports={default:n(920),__esModule:!0}},function(e,t,n){n(921),e.exports=n(906).Object.assign},[1416,905,922],[1417,889,923,924,887,893,915],43,44,function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=n(919),o=r(i);t.default=o.default||function(e){for(var t=1;t1?n[i-1]:void 0,s=i>2?n[2]:void 0;for(a=e.length>3&&"function"==typeof a?(i--,a):void 0,s&&o(n[0],n[1],s)&&(a=i<3?void 0:a,i=1),t=Object(t);++r0){if(++t>=r)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var r=500,i=16,o=Date.now;e.exports=n},[1483,966,989,991,980],[1474,979,990],431,428,435,[1470,994,1e3,989],function(e,t,n){function r(e,t){var n=a(e)||o(e)?i(e.length,String):[],r=n.length,u=!!r;for(var l in e)!t&&!c.call(e,l)||u&&("length"==l||s(l,r))||n.push(l);return n}var i=n(995),o=n(996),a=n(999),s=n(991),u=Object.prototype,c=u.hasOwnProperty;e.exports=r},423,function(e,t,n){function r(e){return i(e)&&s.call(e,"callee")&&(!c.call(e,"callee")||u.call(e)==o)}var i=n(997),o="[object Arguments]",a=Object.prototype,s=a.hasOwnProperty,u=a.toString,c=a.propertyIsEnumerable;e.exports=r},function(e,t,n){function r(e){return o(e)&&i(e)}var i=n(989),o=n(998);e.exports=r},315,346,[1472,992,1001],[1473,1002],314,function(e,t,n){"use strict";function r(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function i(e,t,n){if(e&&c.isObject(e)&&e instanceof r)return e;var i=new r;return i.parse(e,t,n),i}function o(e){return c.isString(e)&&(e=i(e)),e instanceof r?e.format():r.prototype.format.call(e)}function a(e,t){return i(e,!1,!0).resolve(t)}function s(e,t){return e?i(e,!1,!0).resolveObject(t):t}var u=n(1004),c=n(1005);t.parse=i,t.resolve=a,t.resolveObject=s,t.format=o,t.Url=r;var l=/^([a-z0-9.+-]+:)/i,p=/:[0-9]*$/,f=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,h=["<",">",'"',"`"," ","\r","\n","\t"],d=["{","}","|","\\","^","`"].concat(h),m=["'"].concat(d),y=["%","/","?",";","#"].concat(m),v=["/","?","#"],g=255,_=/^[+a-z0-9A-Z_-]{0,63}$/,b=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,x={javascript:!0,"javascript:":!0},w={javascript:!0,"javascript:":!0},k={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},S=n(1006);r.prototype.parse=function(e,t,n){if(!c.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var r=e.indexOf("?"),i=r!==-1&&r127?"x":j[N];if(!R.match(_)){var B=P.slice(0,A),L=P.slice(A+1),z=j.match(b);z&&(B.push(z[1]),L.unshift(z[2])),L.length&&(s="/"+L.join(".")+s),this.hostname=B.join(".");break}}}this.hostname.length>g?this.hostname="":this.hostname=this.hostname.toLowerCase(),M||(this.hostname=u.toASCII(this.hostname));var q=this.port?":"+this.port:"",U=this.hostname||"";this.host=U+q,this.href+=this.host,M&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==s[0]&&(s="/"+s))}if(!x[d])for(var A=0,I=m.length;A0)&&n.host.split("@");E&&(n.auth=E.shift(),n.host=n.hostname=E.shift())}return n.search=e.search,n.query=e.query,c.isNull(n.pathname)&&c.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n}if(!x.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var C=x.slice(-1)[0],A=(n.host||e.host||x.length>1)&&("."===C||".."===C)||""===C,T=0,O=x.length;O>=0;O--)C=x[O],"."===C?x.splice(O,1):".."===C?(x.splice(O,1),T++):T&&(x.splice(O,1),T--);if(!_&&!b)for(;T--;T)x.unshift("..");!_||""===x[0]||x[0]&&"/"===x[0].charAt(0)||x.unshift(""),A&&"/"!==x.join("/").substr(-1)&&x.push("");var D=""===x[0]||x[0]&&"/"===x[0].charAt(0);if(S){n.hostname=n.host=D?"":x.length?x.shift():"";var E=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@");E&&(n.auth=E.shift(),n.host=n.hostname=E.shift())}return _=_||n.host&&x.length,_&&!D&&x.unshift(""),x.length?n.pathname=x.join("/"):(n.pathname=null,n.path=null),c.isNull(n.pathname)&&c.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},r.prototype.parseHost=function(){var e=this.host,t=p.exec(e);t&&(t=t[0],":"!==t&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},function(e,t,n){var r;(function(e,i){!function(o){function a(e){throw RangeError(P[e])}function s(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function u(e,t){var n=e.split("@"),r="";n.length>1&&(r=n[0]+"@",e=n[1]),e=e.replace(M,".");var i=e.split("."),o=s(i,t).join(".");return r+o}function c(e){for(var t,n,r=[],i=0,o=e.length;i=55296&&t<=56319&&i65535&&(e-=65536,t+=R(e>>>10&1023|55296),e=56320|1023&e),t+=R(e)}).join("")}function p(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:x}function f(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function h(e,t,n){var r=0;for(e=n?j(e/E):e>>1,e+=j(e/t);e>I*k>>1;r+=x)e=j(e/I);return j(r+(I+1)*e/(e+S))}function d(e){var t,n,r,i,o,s,u,c,f,d,m=[],y=e.length,v=0,g=A,_=C;for(n=e.lastIndexOf(T),n<0&&(n=0),r=0;r=128&&a("not-basic"),m.push(e.charCodeAt(r));for(i=n>0?n+1:0;i=y&&a("invalid-input"),c=p(e.charCodeAt(i++)),(c>=x||c>j((b-v)/s))&&a("overflow"),v+=c*s,f=u<=_?w:u>=_+k?k:u-_,!(cj(b/d)&&a("overflow"),s*=d;t=m.length+1,_=h(v-o,t,0==o),j(v/t)>b-g&&a("overflow"),g+=j(v/t),v%=t,m.splice(v++,0,g)}return l(m)}function m(e){var t,n,r,i,o,s,u,l,p,d,m,y,v,g,_,S=[];for(e=c(e),y=e.length,t=A,n=0,o=C,s=0;s=t&&mj((b-n)/v)&&a("overflow"),n+=(u-t)*v,t=u,s=0;sb&&a("overflow"),m==t){for(l=n,p=x;d=p<=o?w:p>=o+k?k:p-o,!(l= 0x80 (not a basic code point)","invalid-input":"Invalid input"},I=x-w,j=Math.floor,R=String.fromCharCode;_={version:"1.3.2",ucs2:{decode:c,encode:l},decode:d,encode:m,toASCII:v,toUnicode:y},r=function(){return _}.call(t,n,t,e),!(void 0!==r&&(e.exports=r))}(this)}).call(t,n(318)(e),function(){return this}())},function(e,t){"use strict";e.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},function(e,t,n){"use strict";t.decode=t.parse=n(1007),t.encode=t.stringify=n(1008)},function(e,t){"use strict";function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.exports=function(e,t,r,i){t=t||"&",r=r||"=";var o={};if("string"!=typeof e||0===e.length)return o;var a=/\+/g;e=e.split(t);var s=1e3;i&&"number"==typeof i.maxKeys&&(s=i.maxKeys);var u=e.length;s>0&&u>s&&(u=s);for(var c=0;c=0?(l=d.substr(0,m),p=d.substr(m+1)):(l=d,p=""),f=decodeURIComponent(l),h=decodeURIComponent(p),n(o,f)?Array.isArray(o[f])?o[f].push(h):o[f]=[o[f],h]:o[f]=h}return o}},function(e,t){"use strict";var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};e.exports=function(e,t,r,i){return t=t||"&",r=r||"=",null===e&&(e=void 0),"object"==typeof e?Object.keys(e).map(function(i){var o=encodeURIComponent(n(i))+r;return Array.isArray(e[i])?e[i].map(function(e){return o+encodeURIComponent(n(e))}).join(t):o+encodeURIComponent(n(e[i]))}).join(t):i?encodeURIComponent(n(i))+r+encodeURIComponent(n(e)):""}},function(e,t,n){e.exports={default:n(1010),__esModule:!0}},function(e,t,n){n(942),n(929),e.exports=n(1011)},function(e,t,n){var r=n(911),i=n(1012);e.exports=n(906).getIterator=function(e){var t=i(e);if("function"!=typeof t)throw TypeError(e+" is not iterable!");return r(t.call(e))}},[1427,1013,940,934,906],[1418,894,940],function(e,t,n){e.exports={default:n(1015),__esModule:!0}},function(e,t,n){n(958),n(929),n(942),n(1016),e.exports=n(906).Promise},[1433,932,901,907,1013,905,912,908,1017,1018,1021,1022,1024,940,1025,939,1026,906,1027],205,[1434,907,1019,1020,911,896,1012],[1424,911],[1425,934,940],[1435,911,908,940],[1436,907,1023,938,916,901,894],78,[1437,901,1022,894],function(e,t,n){var r=n(909);e.exports=function(e,t,n){for(var i in t)n&&e[i]?e[i]=t[i]:r(e,i,t[i]);return e}},function(e,t,n){"use strict";var r=n(901),i=n(906),o=n(910),a=n(914),s=n(940)("species");e.exports=function(e){var t="function"==typeof i[e]?i[e]:r[e];a&&t&&!t[s]&&o.f(t,s,{configurable:!0,get:function(){return this}})}},[1428,940],function(e,t){"use strict";t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=n(1030),o=r(i);t.default=function(){function e(e,t){for(var n=0;n=0,o=i&&r.regeneratorRuntime;if(r.regeneratorRuntime=void 0,e.exports=n(293),i)r.regeneratorRuntime=o;else try{delete r.regeneratorRuntime}catch(e){r.regeneratorRuntime=void 0}}).call(t,function(){return this}())},function(e,t,n){n(1036),e.exports=self.fetch.bind(self)},function(e,t){!function(e){"use strict";function t(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function n(e){return"string"!=typeof e&&(e=String(e)),e}function r(e){this.map={},e instanceof r?e.forEach(function(e,t){this.append(t,e)},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function i(e){return e.bodyUsed?Promise.reject(new TypeError("Already read")):void(e.bodyUsed=!0)}function o(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function a(e){var t=new FileReader;return t.readAsArrayBuffer(e),o(t)}function s(e){var t=new FileReader;return t.readAsText(e),o(t)}function u(){return this.bodyUsed=!1,this._initBody=function(e){if(this._bodyInit=e,"string"==typeof e)this._bodyText=e;else if(d.blob&&Blob.prototype.isPrototypeOf(e))this._bodyBlob=e;else if(d.formData&&FormData.prototype.isPrototypeOf(e))this._bodyFormData=e;else if(e){if(!d.arrayBuffer||!ArrayBuffer.prototype.isPrototypeOf(e))throw new Error("unsupported BodyInit type")}else this._bodyText="";this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type&&this.headers.set("content-type",this._bodyBlob.type))},d.blob?(this.blob=function(){var e=i(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this.blob().then(a)},this.text=function(){var e=i(this);if(e)return e;if(this._bodyBlob)return s(this._bodyBlob);if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)}):this.text=function(){var e=i(this);return e?e:Promise.resolve(this._bodyText)},d.formData&&(this.formData=function(){return this.text().then(p)}),this.json=function(){return this.text().then(JSON.parse)},this}function c(e){var t=e.toUpperCase();return m.indexOf(t)>-1?t:e}function l(e,t){t=t||{};var n=t.body;if(l.prototype.isPrototypeOf(e)){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new r(e.headers)),this.method=e.method,this.mode=e.mode,n||(n=e._bodyInit,e.bodyUsed=!0)}else this.url=e;if(this.credentials=t.credentials||this.credentials||"omit",!t.headers&&this.headers||(this.headers=new r(t.headers)),this.method=c(t.method||this.method||"GET"),this.mode=t.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&n)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(n)}function p(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var n=e.split("="),r=n.shift().replace(/\+/g," "),i=n.join("=").replace(/\+/g," ");t.append(decodeURIComponent(r),decodeURIComponent(i))}}),t}function f(e){var t=new r,n=(e.getAllResponseHeaders()||"").trim().split("\n");return n.forEach(function(e){var n=e.trim().split(":"),r=n.shift().trim(),i=n.join(":").trim();t.append(r,i)}),t}function h(e,t){t||(t={}),this.type="default",this.status=t.status,this.ok=this.status>=200&&this.status<300,this.statusText=t.statusText,this.headers=t.headers instanceof r?t.headers:new r(t.headers),this.url=t.url||"",this._initBody(e)}if(!e.fetch){r.prototype.append=function(e,r){e=t(e),r=n(r);var i=this.map[e];i||(i=[],this.map[e]=i),i.push(r)},r.prototype.delete=function(e){delete this.map[t(e)]},r.prototype.get=function(e){var n=this.map[t(e)];return n?n[0]:null},r.prototype.getAll=function(e){return this.map[t(e)]||[]},r.prototype.has=function(e){return this.map.hasOwnProperty(t(e))},r.prototype.set=function(e,r){this.map[t(e)]=[n(r)]},r.prototype.forEach=function(e,t){Object.getOwnPropertyNames(this.map).forEach(function(n){this.map[n].forEach(function(r){e.call(t,r,n,this)},this)},this)};var d={blob:"FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:"FormData"in e,arrayBuffer:"ArrayBuffer"in e},m=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];l.prototype.clone=function(){return new l(this)},u.call(l.prototype),u.call(h.prototype),h.prototype.clone=function(){return new h(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new r(this.headers),url:this.url})},h.error=function(){var e=new h(null,{status:0,statusText:""});return e.type="error",e};var y=[301,302,303,307,308];h.redirect=function(e,t){if(y.indexOf(t)===-1)throw new RangeError("Invalid status code");return new h(null,{status:t,headers:{location:e}})},e.Headers=r,e.Request=l,e.Response=h,e.fetch=function(e,t){return new Promise(function(n,r){function i(){return"responseURL"in a?a.responseURL:/^X-Request-URL:/m.test(a.getAllResponseHeaders())?a.getResponseHeader("X-Request-URL"):void 0}var o;o=l.prototype.isPrototypeOf(e)&&!t?e:new l(e,t);var a=new XMLHttpRequest;a.onload=function(){var e=1223===a.status?204:a.status;if(e<100||e>599)return void r(new TypeError("Network request failed"));var t={status:e,statusText:a.statusText,headers:f(a),url:i()},o="response"in a?a.response:a.responseText;n(new h(o,t))},a.onerror=function(){r(new TypeError("Network request failed"))},a.ontimeout=function(){r(new TypeError("Network request failed"))},a.open(o.method,o.url,!0),"include"===o.credentials&&(a.withCredentials=!0),"responseType"in a&&d.blob&&(a.responseType="blob"),o.headers.forEach(function(e,t){a.setRequestHeader(t,e)}),a.send("undefined"==typeof o._bodyInit?null:o._bodyInit)})},e.fetch.polyfill=!0}}("undefined"!=typeof self?self:this)},function(e,t,n){e.exports={default:n(1038),__esModule:!0}},function(e,t,n){n(1039);var r=n(906).Object;e.exports=function(e,t){return r.create(e,t)}},[1410,905,936],function(e,t,n){e.exports={default:n(1041),__esModule:!0}},function(e,t,n){n(958),n(942),n(1042),e.exports=n(906).WeakMap},[1438,1043,933,950,922,1046,912,1047],[1429,907,893,887,896,1044],[1430,1045],[1431,912,954,940],[1439,1025,950,911,912,1017,1018,1043,891],function(e,t,n){"use strict";var r=n(901),i=n(905),o=n(950),a=n(915),s=n(909),u=n(1025),c=n(1018),l=n(1017),p=n(912),f=n(939),h=n(910).f,d=n(1043)(0),m=n(914);e.exports=function(e,t,n,y,v,g){var _=r[e],b=_,x=v?"set":"add",w=b&&b.prototype,k={};return m&&"function"==typeof b&&(g||w.forEach&&!a(function(){(new b).entries().next()}))?(b=t(function(t,n){l(t,b,e,"_c"),t._c=new _,void 0!=n&&c(n,v,t[x],t)}),d("add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON".split(","),function(e){var t="add"==e||"set"==e;e in w&&(!g||"clear"!=e)&&s(b.prototype,e,function(n,r){if(l(this,b,e),!t&&g&&!p(n))return"get"==e&&void 0;var i=this._c[e](0===n?0:n,r);return t?this:i})}),"size"in w&&h(b.prototype,"size",{get:function(){return this._c.size}})):(b=y.getConstructor(t,e,v,x),u(b.prototype,n),o.NEED=!0),f(b,e),k[e]=b,i(i.G+i.W+i.F,k),g||y.setStrong(b,e,v),b}},function(e,t){"use strict";t.__esModule=!0,t.default=function(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=n(1050),o=r(i),a=n(1009),s=r(a);t.default=function(){function e(e,t){var n=[],r=!0,i=!1,o=void 0;try{for(var a,u=(0,s.default)(e);!(r=(a=u.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){i=!0,o=e}finally{try{!r&&u.return&&u.return()}finally{if(i)throw o}}return n}return function(t,n){if(Array.isArray(t))return t;if((0,o.default)(Object(t)))return e(t,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}()},function(e,t,n){e.exports={default:n(1051),__esModule:!0}},function(e,t,n){n(942),n(929),e.exports=n(1052)},function(e,t,n){var r=n(1013),i=n(940)("iterator"),o=n(934);e.exports=n(906).isIterable=function(e){var t=Object(e);return void 0!==t[i]||"@@iterator"in t||o.hasOwnProperty(r(t))}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=n(1054),o=r(i);t.default=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t0&&(e.patches=[],e.callback&&e.callback(i)),i}function l(e,t,r,i){if(t!==e){"function"==typeof t.toJSON&&(t=t.toJSON());for(var o=g(t),a=g(e),u=!1,c=!1,p=a.length-1;p>=0;p--){var f=a[p],h=e[f];if(!t.hasOwnProperty(f)||void 0===t[f]&&void 0!==h&&E(t)===!1)r.push({op:"remove",path:i+"/"+n(f)}),c=!0;else{var d=t[f];"object"==typeof h&&null!=h&&"object"==typeof d&&null!=d?l(h,d,r,i+"/"+n(f)):h!==d&&(u=!0,r.push({op:"replace",path:i+"/"+n(f),value:s(d)}))}}if(c||o.length!=a.length)for(var p=0;p=48&&t<=57))return!1;n++}}return!0}function f(e,t,n){for(var r,i,o=[],a=0,s=t.length;a=h){o.push(x[r.op].call(r,l,i,e));break}if(E(l)){if("-"===i)i=l.length;else{if(n&&!p(i))throw new C("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",a-1,r.path,r);i=parseInt(i,10)}if(f>=h){if(n&&"add"===r.op&&i>l.length)throw new C("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a-1,r.path,r);o.push(b[r.op].call(r,l,i,e));break}}else if(i&&i.indexOf("~")!=-1&&(i=i.replace(/~1/g,"/").replace(/~0/g,"~")),f>=h){o.push(_[r.op].call(r,l,i,e));break}l=l[i]}}return o}function h(e,t){var n=[];return l(e,t,n,""),n}function d(e,t){function n(){this.constructor=e}for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function m(e){if(void 0===e)return!0;if(e)if(E(e)){for(var t=0,n=e.length;t0)throw new C('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",n,t,r);if(("move"===t.op||"copy"===t.op)&&"string"!=typeof t.from)throw new C("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",n,t,r);if(("add"===t.op||"replace"===t.op||"test"===t.op)&&void 0===t.value)throw new C("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",n,t,r);if(("add"===t.op||"replace"===t.op||"test"===t.op)&&m(t.value))throw new C("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",n,t,r);if(r)if("add"==t.op){var o=t.path.split("/").length,a=i.split("/").length;if(o!==a+1&&o!==a)throw new C("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",n,t,r)}else if("replace"===t.op||"remove"===t.op||"_get"===t.op){if(t.path!==i)throw new C("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",n,t,r)}else if("move"===t.op||"copy"===t.op){var s={op:"_get",path:t.from,value:void 0},u=e.validate([s],r);if(u&&"OPERATION_PATH_UNRESOLVABLE"===u.name)throw new C("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",n,t,r)}}function v(e,t){try{if(!E(e))throw new C("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)t=JSON.parse(JSON.stringify(t)),f.call(this,t,e,!0);else for(var n=0;n=48&&o<=57||o>=65&&o<=90||o>=97&&o<=122?n+=t.charAt(i):o<128?n+=r[o]:o<2048?n+=r[192|o>>6]+r[128|63&o]:o<55296||o>=57344?n+=r[224|o>>12]+r[128|o>>6&63]+r[128|63&o]:(i+=1,o=65536+((1023&o)<<10|1023&t.charCodeAt(i)),n+=r[240|o>>18]+r[128|o>>12&63]+r[128|o>>6&63]+r[128|63&o])}return n},t.compact=function(e,n){if("object"!=typeof e||null===e)return e;var r=n||[],i=r.indexOf(e);if(i!==-1)return r[i];if(r.push(e),Array.isArray(e)){for(var o=[],a=0;a=0&&n.parseArrays&&a<=n.arrayLimit?(r=[],r[a]=s(e,t,n)):r[o]=s(e,t,n)}return r},u=function(e,t,n){if(e){var r=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,o=/(\[[^[\]]*])/,a=/(\[[^[\]]*])/g,u=o.exec(r),c=u?r.slice(0,u.index):r,l=[];if(c){if(!n.plainObjects&&i.call(Object.prototype,c)&&!n.allowPrototypes)return;l.push(c)}for(var p=0;null!==(u=a.exec(r))&&pp?d=p:this.setState({position:a,resized:!0}),this.props.onChange&&this.props.onChange(d),this.setState({draggedSize:d}),n.setState({size:d})}}}}},{key:"onMouseUp",value:function(){this.props.allowResize&&this.state.active&&("function"==typeof this.props.onDragFinished&&this.props.onDragFinished(this.state.draggedSize),this.setState({active:!1}))}},{key:"setSize",value:function(e,t){var n="first"===this.props.primary?this.pane1:this.pane2,r=void 0;n&&(r=e.size||t&&t.draggedSize||e.defaultSize||e.minSize,n.setState({size:r}),e.size!==t.draggedSize&&this.setState({draggedSize:r}))}},{key:"render",value:function(){var e=this,t=this.props,n=t.split,r=t.allowResize,i=r?"":"disabled",o=u({},this.props.style||{},{display:"flex",flex:1,position:"relative",outline:"none",overflow:"hidden",MozUserSelect:"text",WebkitUserSelect:"text",msUserSelect:"text",userSelect:"text"});"vertical"===n?u(o,{flexDirection:"row",height:"100%",position:"absolute",left:0,right:0}):u(o,{flexDirection:"column",height:"100%",minHeight:"100%",position:"absolute",top:0,bottom:0,width:"100%"});var a=this.props.children,s=["SplitPane",this.props.className,n,i],c=this.props.prefixer.prefix(u({},this.props.paneStyle||{},this.props.pane1Style||{})),l=this.props.prefixer.prefix(u({},this.props.paneStyle||{},this.props.pane2Style||{}));return p.default.createElement("div",{className:s.join(" "),style:this.props.prefixer.prefix(o),ref:function(t){e.splitPane=t}},p.default.createElement(_.default,{ref:function(t){e.pane1=t},key:"pane1",className:"Pane1",style:c,split:n,size:"first"===this.props.primary?this.props.size||this.props.defaultSize||this.props.minSize:void 0},a[0]),p.default.createElement(x.default,{ref:function(t){e.resizer=t},key:"resizer",className:i,resizerClassName:this.props.resizerClassName,onMouseDown:this.onMouseDown,onTouchStart:this.onTouchStart,onTouchEnd:this.onMouseUp,style:this.props.resizerStyle||{},split:n}),p.default.createElement(_.default,{ref:function(t){e.pane2=t},key:"pane2",className:"Pane2",style:l,split:n,size:"second"===this.props.primary?this.props.size||this.props.defaultSize||this.props.minSize:void 0},a[1]))}}]),t}(l.Component);k.propTypes={primary:l.PropTypes.oneOf(["first","second"]),minSize:l.PropTypes.oneOfType([p.default.PropTypes.string,p.default.PropTypes.number]),maxSize:l.PropTypes.oneOfType([p.default.PropTypes.string,p.default.PropTypes.number]),defaultSize:l.PropTypes.oneOfType([p.default.PropTypes.string,p.default.PropTypes.number]),size:l.PropTypes.oneOfType([p.default.PropTypes.string,p.default.PropTypes.number]),allowResize:l.PropTypes.bool,split:l.PropTypes.oneOf(["vertical","horizontal"]),onDragStarted:l.PropTypes.func,onDragFinished:l.PropTypes.func,onChange:l.PropTypes.func,prefixer:l.PropTypes.instanceOf(m.default).isRequired,style:v.default,resizerStyle:v.default,paneStyle:v.default,pane1Style:v.default,pane2Style:v.default,className:l.PropTypes.string,resizerClassName:l.PropTypes.string,children:l.PropTypes.arrayOf(l.PropTypes.node).isRequired},k.defaultProps={split:"vertical",minSize:50,allowResize:!0,prefixer:new m.default({userAgent:w}),primary:"first"},t.default=k,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=arguments[2],r=arguments[3];Object.keys(t).forEach(function(i){var o=e[i];Array.isArray(o)?[].concat(t[i]).forEach(function(t){e[i].indexOf(t)===-1&&e[i].splice(o.indexOf(n),r?0:1,t)}):e[i]=t[i]})}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n=t._browserInfo.version}).reduce(function(e,t){return e[t]=!0,e},{}),this._hasPropsRequiringPrefix=Object.keys(this._requiresPrefix).length>0):this._usePrefixAllFallback=!0}return a(e,[{key:"prefix",value:function(e){var t=this;return this._usePrefixAllFallback?(0,u.default)(e):this._hasPropsRequiringPrefix?(Object.keys(e).forEach(function(n){var r=e[n];r instanceof Object&&!Array.isArray(r)?e[n]=t.prefix(r):t._requiresPrefix[n]&&(e[t.jsPrefix+(0,d.default)(n)]=r,t._keepUnprefixed||delete e[n])}),Object.keys(e).forEach(function(n){[].concat(e[n]).forEach(function(r){L.forEach(function(i){o(e,i({property:n,value:r,styles:e,browserInfo:t._browserInfo,prefix:{js:t.jsPrefix,css:t.cssPrefix,keyframes:t.prefixedKeyframes},keepUnprefixed:t._keepUnprefixed,requiresPrefix:t._requiresPrefix}),r,t._keepUnprefixed)})})}),(0,y.default)(e)):e}}],[{key:"prefixAll",value:function(e){return(0,u.default)(e)}}]),e}();t.default=z,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e){return Object.keys(e).forEach(function(t){var n=e[t];n instanceof Object&&!Array.isArray(n)?e[t]=i(n):Object.keys(s.default).forEach(function(r){var i=s.default[r];i[t]&&(e[r+(0,c.default)(t)]=n)})}),Object.keys(e).forEach(function(t){[].concat(e[t]).forEach(function(n,r){D.forEach(function(r){return o(e,r(t,n))})})}),(0,p.default)(e)}function o(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];Object.keys(t).forEach(function(n){var r=e[n];Array.isArray(r)?[].concat(t[n]).forEach(function(t){var i=r.indexOf(t);i>-1&&e[n].splice(i,1),e[n].push(t)}):e[n]=t[n]})}Object.defineProperty(t,"__esModule",{value:!0}),t.default=i;var a=n(1170),s=r(a),u=n(1171),c=r(u),l=n(1172),p=r(l),f=n(1174),h=r(f),d=n(1175),m=r(d),y=n(1178),v=r(y),g=n(1179),_=r(g),b=n(1180),x=r(b),w=n(1181),k=r(w),S=n(1182),E=r(S),C=n(1184),A=r(C),T=n(1185),O=r(T),D=[h.default,m.default,v.default,x.default,k.default,E.default,A.default,O.default,_.default];e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={Webkit:{transform:!0,transformOrigin:!0,transformOriginX:!0,transformOriginY:!0,backfaceVisibility:!0,perspective:!0,perspectiveOrigin:!0,transformStyle:!0,transformOriginZ:!0,animation:!0,animationDelay:!0,animationDirection:!0,animationFillMode:!0,animationDuration:!0,animationIterationCount:!0,animationName:!0,animationPlayState:!0,animationTimingFunction:!0,appearance:!0,userSelect:!0,fontKerning:!0,textEmphasisPosition:!0,textEmphasis:!0,textEmphasisStyle:!0,textEmphasisColor:!0,boxDecorationBreak:!0,clipPath:!0,maskImage:!0,maskMode:!0,maskRepeat:!0,maskPosition:!0,maskClip:!0,maskOrigin:!0,maskSize:!0,maskComposite:!0,mask:!0,maskBorderSource:!0,maskBorderMode:!0,maskBorderSlice:!0,maskBorderWidth:!0,maskBorderOutset:!0,maskBorderRepeat:!0,maskBorder:!0,maskType:!0,textDecorationStyle:!0,textDecorationSkip:!0,textDecorationLine:!0,textDecorationColor:!0,filter:!0,fontFeatureSettings:!0,breakAfter:!0,breakBefore:!0,breakInside:!0,columnCount:!0,columnFill:!0,columnGap:!0,columnRule:!0,columnRuleColor:!0,columnRuleStyle:!0,columnRuleWidth:!0,columns:!0,columnSpan:!0,columnWidth:!0,flex:!0,flexBasis:!0,flexDirection:!0,flexGrow:!0,flexFlow:!0,flexShrink:!0,flexWrap:!0,alignContent:!0,alignItems:!0,alignSelf:!0,justifyContent:!0,order:!0,transition:!0,transitionDelay:!0,transitionDuration:!0,transitionProperty:!0,transitionTimingFunction:!0,backdropFilter:!0,scrollSnapType:!0,scrollSnapPointsX:!0,scrollSnapPointsY:!0,scrollSnapDestination:!0,scrollSnapCoordinate:!0,shapeImageThreshold:!0,shapeImageMargin:!0,shapeImageOutside:!0,hyphens:!0,flowInto:!0,flowFrom:!0,regionFragment:!0,textSizeAdjust:!0},Moz:{appearance:!0,userSelect:!0,boxSizing:!0,textAlignLast:!0,textDecorationStyle:!0,textDecorationSkip:!0,textDecorationLine:!0,textDecorationColor:!0,tabSize:!0,hyphens:!0,fontFeatureSettings:!0,breakAfter:!0,breakBefore:!0,breakInside:!0,columnCount:!0,columnFill:!0,columnGap:!0,columnRule:!0,columnRuleColor:!0,columnRuleStyle:!0,columnRuleWidth:!0,columns:!0,columnSpan:!0,columnWidth:!0},ms:{flex:!0,flexBasis:!1,flexDirection:!0,flexGrow:!1,flexFlow:!0,flexShrink:!1,flexWrap:!0,alignContent:!1,alignItems:!1,alignSelf:!1,justifyContent:!1,order:!1,transform:!0,transformOrigin:!0,transformOriginX:!0,transformOriginY:!0,userSelect:!0,wrapFlow:!0,wrapThrough:!0,wrapMargin:!0,scrollSnapType:!0,scrollSnapPointsX:!0,scrollSnapPointsY:!0,scrollSnapDestination:!0,scrollSnapCoordinate:!0,touchAction:!0,hyphens:!0,flowInto:!0,flowFrom:!0,breakBefore:!0,breakAfter:!0,breakInside:!0,regionFragment:!0,gridTemplateColumns:!0,gridTemplateRows:!0,gridTemplateAreas:!0,gridTemplate:!0,gridAutoColumns:!0,gridAutoRows:!0,gridAutoFlow:!0,grid:!0,gridRowStart:!0,gridColumnStart:!0,gridRowEnd:!0,gridRow:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnGap:!0,gridRowGap:!0,gridArea:!0,gridGap:!0,textSizeAdjust:!0}},e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return e.charAt(0).toUpperCase()+e.slice(1)},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e){return Object.keys(e).sort(function(e,t){return(0,a.default)(e)&&!(0,a.default)(t)?-1:!(0,a.default)(e)&&(0,a.default)(t)?1:0}).reduce(function(t,n){return t[n]=e[n],t},{})}Object.defineProperty(t,"__esModule",{value:!0}),t.default=i;var o=n(1173),a=r(o);e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return null!==e.match(/^(Webkit|Moz|O|ms)/)},e.exports=t.default},function(e,t){"use strict";function n(e,t){if("position"===e&&"sticky"===t)return{position:["-webkit-sticky","sticky"]}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if("string"==typeof t&&!(0,u.default)(t)&&t.indexOf("calc(")>-1)return(0,a.default)(e,t,function(e,t){return t.replace(/calc\(/g,e+"calc(")})}Object.defineProperty(t,"__esModule",{value:!0}),t.default=i;var o=n(1176),a=r(o),s=n(1177),u=r(s);e.exports=t.default},function(e,t){"use strict";function n(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){var r=arguments.length<=2||void 0===arguments[2]?function(e,t){return e+t}:arguments[2];return n({},e,["-webkit-","-moz-",""].map(function(e){return r(e,t)}))},e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return Array.isArray(e)&&(e=e.join(",")),null!==e.match(/-webkit-|-moz-|-ms-/)},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if("cursor"===e&&s[t])return(0,a.default)(e,t)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=i;var o=n(1176),a=r(o),s={"zoom-in":!0,"zoom-out":!0,grab:!0,grabbing:!0};e.exports=t.default},function(e,t){"use strict";function n(e,t){if("display"===e&&r[t])return{display:["-webkit-box","-moz-box","-ms-"+t+"box","-webkit-"+t,t]}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n;var r={flex:!0,"inline-flex":!0};e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(s[e]&&u[t])return(0,a.default)(e,t)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=i;var o=n(1176),a=r(o),s={maxHeight:!0,maxWidth:!0,width:!0,height:!0,columnWidth:!0,minWidth:!0,minHeight:!0},u={"min-content":!0,"max-content":!0,"fill-available":!0,"fit-content":!0,"contain-floats":!0};e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if("string"==typeof t&&!(0,u.default)(t)&&null!==t.match(c))return(0,a.default)(e,t)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=i;var o=n(1176),a=r(o),s=n(1177),u=r(s),c=/linear-gradient|radial-gradient|repeating-linear-gradient|repeating-radial-gradient/;e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){if("string"==typeof t&&m[e]){var n,r=a(t),o=r.split(/,(?![^()]*(?:\([^()]*\))?\))/g).filter(function(e){return null===e.match(/-moz-|-ms-/)}).join(",");return e.indexOf("Webkit")>-1?i({},e,o):(n={},i(n,"Webkit"+(0,l.default)(e),o),i(n,e,r),n)}}function a(e){if((0,f.default)(e))return e;var t=e.split(/,(?![^()]*(?:\([^()]*\))?\))/g);return t.forEach(function(e,n){t[n]=Object.keys(d.default).reduce(function(t,n){var r="-"+n.toLowerCase()+"-";return Object.keys(d.default[n]).forEach(function(n){var i=(0,u.default)(n);e.indexOf(i)>-1&&"order"!==i&&(t=e.replace(i,r+i)+","+t)}),t},e)}),t.join(",")}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var s=n(1183),u=r(s),c=n(1171),l=r(c),p=n(1177),f=r(p),h=n(1170),d=r(h),m={transition:!0,transitionProperty:!0,WebkitTransition:!0,WebkitTransitionProperty:!0};e.exports=t.default},function(e,t){"use strict";function n(e){return e in o?o[e]:o[e]=e.replace(r,"-$&").toLowerCase().replace(i,"-ms-")}var r=/[A-Z]/g,i=/^ms-/,o={};e.exports=n},function(e,t){"use strict";function n(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e,t){if(o[e])return n({},o[e],i[t]||t)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=r;var i={"space-around":"distribute","space-between":"justify","flex-start":"start","flex-end":"end"},o={alignContent:"msFlexLinePack",alignSelf:"msFlexItemAlign",alignItems:"msFlexAlign",justifyContent:"msFlexPack",order:"msFlexOrder",flexGrow:"msFlexPositive",flexShrink:"msFlexNegative",flexBasis:"msPreferredSize"};e.exports=t.default},function(e,t){"use strict";function n(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e,t){return"flexDirection"===e&&"string"==typeof t?{WebkitBoxOrient:t.indexOf("column")>-1?"vertical":"horizontal",WebkitBoxDirection:t.indexOf("reverse")>-1?"reverse":"normal"}:o[e]?n({},o[e],i[t]||t):void 0}Object.defineProperty(t,"__esModule",{value:!0}),t.default=r;var i={"space-around":"justify","space-between":"justify","flex-start":"start","flex-end":"end","wrap-reverse":"multiple",wrap:"multiple"},o={alignItems:"WebkitBoxAlign",justifyContent:"WebkitBoxPack",flexWrap:"WebkitBoxLines"};e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1187),o=r(i),a={Webkit:["chrome","safari","ios","android","phantom","opera","webos","blackberry","bada","tizen","chromium","vivaldi"],Moz:["firefox","seamonkey","sailfish"],ms:["msie","msedge"]},s={chrome:[["chrome"],["chromium"]],safari:[["safari"]],firefox:[["firefox"]],edge:[["msedge"]],opera:[["opera"],["vivaldi"]],ios_saf:[["ios","mobile"],["ios","tablet"]],ie:[["msie"]],op_mini:[["opera","mobile"],["opera","tablet"]],and_uc:[["android","mobile"],["android","tablet"]],android:[["android","mobile"],["android","tablet"]]},u=function(e){if(e.firefox)return"firefox";var t="";return Object.keys(s).forEach(function(n){s[n].forEach(function(r){var i=0;r.forEach(function(t){e[t]&&(i+=1)}),r.length===i&&(t=n)})}),t};t.default=function(e){if(!e)return!1;var t=o.default._detect(e);return Object.keys(a).forEach(function(e){a[e].forEach(function(n){t[n]&&(t.prefix={inline:e,css:"-"+e.toLowerCase()+"-"})})}),t.browser=u(t),t.version=t.version?parseFloat(t.version):parseInt(parseFloat(t.osversion),10),t.osversion=parseFloat(t.osversion),"ios_saf"===t.browser&&t.version>t.osversion&&(t.version=t.osversion,t.safari=!0),"android"===t.browser&&t.chrome&&t.version>37&&(t.browser="and_chr"),"android"===t.browser&&t.osversion<5&&(t.version=t.osversion),t},e.exports=t.default},function(e,t,n){/*! + * Bowser - a browser detector + * https://github.com/ded/bowser + * MIT License | (c) Dustin Diaz 2015 + */ +!function(t,r,i){"undefined"!=typeof e&&e.exports?e.exports=i():n(1188)(r,i)}(this,"bowser",function(){function e(e){function t(t){var n=e.match(t);return n&&n.length>1&&n[1]||""}function n(t){var n=e.match(t);return n&&n.length>1&&n[2]||""}function r(e){switch(e){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}var i,o=t(/(ipod|iphone|ipad)/i).toLowerCase(),s=/like android/i.test(e),u=!s&&/android/i.test(e),c=/nexus\s*[0-6]\s*/i.test(e),l=!c&&/nexus\s*[0-9]+/i.test(e),p=/CrOS/.test(e),f=/silk/i.test(e),h=/sailfish/i.test(e),d=/tizen/i.test(e),m=/(web|hpw)os/i.test(e),y=/windows phone/i.test(e),v=(/SamsungBrowser/i.test(e),!y&&/windows/i.test(e)),g=!o&&!f&&/macintosh/i.test(e),_=!u&&!h&&!d&&!m&&/linux/i.test(e),b=t(/edge\/(\d+(\.\d+)?)/i),x=t(/version\/(\d+(\.\d+)?)/i),w=/tablet/i.test(e),k=!w&&/[^-]mobi/i.test(e),S=/xbox/i.test(e);/opera/i.test(e)?i={name:"Opera",opera:a,version:x||t(/(?:opera|opr|opios)[\s\/](\d+(\.\d+)?)/i)}:/opr|opios/i.test(e)?i={name:"Opera",opera:a,version:t(/(?:opr|opios)[\s\/](\d+(\.\d+)?)/i)||x}:/SamsungBrowser/i.test(e)?i={name:"Samsung Internet for Android",samsungBrowser:a,version:x||t(/(?:SamsungBrowser)[\s\/](\d+(\.\d+)?)/i)}:/coast/i.test(e)?i={name:"Opera Coast",coast:a,version:x||t(/(?:coast)[\s\/](\d+(\.\d+)?)/i)}:/yabrowser/i.test(e)?i={name:"Yandex Browser",yandexbrowser:a,version:x||t(/(?:yabrowser)[\s\/](\d+(\.\d+)?)/i)}:/ucbrowser/i.test(e)?i={name:"UC Browser",ucbrowser:a,version:t(/(?:ucbrowser)[\s\/](\d+(?:\.\d+)+)/i)}:/mxios/i.test(e)?i={name:"Maxthon",maxthon:a,version:t(/(?:mxios)[\s\/](\d+(?:\.\d+)+)/i)}:/epiphany/i.test(e)?i={name:"Epiphany",epiphany:a,version:t(/(?:epiphany)[\s\/](\d+(?:\.\d+)+)/i)}:/puffin/i.test(e)?i={name:"Puffin",puffin:a,version:t(/(?:puffin)[\s\/](\d+(?:\.\d+)?)/i)}:/sleipnir/i.test(e)?i={name:"Sleipnir",sleipnir:a,version:t(/(?:sleipnir)[\s\/](\d+(?:\.\d+)+)/i)}:/k-meleon/i.test(e)?i={name:"K-Meleon",kMeleon:a,version:t(/(?:k-meleon)[\s\/](\d+(?:\.\d+)+)/i)}:y?(i={name:"Windows Phone",windowsphone:a},b?(i.msedge=a,i.version=b):(i.msie=a,i.version=t(/iemobile\/(\d+(\.\d+)?)/i))):/msie|trident/i.test(e)?i={name:"Internet Explorer",msie:a,version:t(/(?:msie |rv:)(\d+(\.\d+)?)/i)}:p?i={name:"Chrome",chromeos:a,chromeBook:a,chrome:a,version:t(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)}:/chrome.+? edge/i.test(e)?i={name:"Microsoft Edge",msedge:a,version:b}:/vivaldi/i.test(e)?i={name:"Vivaldi",vivaldi:a,version:t(/vivaldi\/(\d+(\.\d+)?)/i)||x}:h?i={name:"Sailfish",sailfish:a,version:t(/sailfish\s?browser\/(\d+(\.\d+)?)/i)}:/seamonkey\//i.test(e)?i={name:"SeaMonkey",seamonkey:a,version:t(/seamonkey\/(\d+(\.\d+)?)/i)}:/firefox|iceweasel|fxios/i.test(e)?(i={name:"Firefox",firefox:a,version:t(/(?:firefox|iceweasel|fxios)[ \/](\d+(\.\d+)?)/i)},/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(e)&&(i.firefoxos=a)):f?i={name:"Amazon Silk",silk:a,version:t(/silk\/(\d+(\.\d+)?)/i)}:/phantom/i.test(e)?i={name:"PhantomJS",phantom:a,version:t(/phantomjs\/(\d+(\.\d+)?)/i)}:/slimerjs/i.test(e)?i={name:"SlimerJS",slimer:a,version:t(/slimerjs\/(\d+(\.\d+)?)/i)}:/blackberry|\bbb\d+/i.test(e)||/rim\stablet/i.test(e)?i={name:"BlackBerry",blackberry:a,version:x||t(/blackberry[\d]+\/(\d+(\.\d+)?)/i)}:m?(i={name:"WebOS",webos:a,version:x||t(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i)},/touchpad\//i.test(e)&&(i.touchpad=a)):/bada/i.test(e)?i={name:"Bada",bada:a,version:t(/dolfin\/(\d+(\.\d+)?)/i)}:d?i={name:"Tizen",tizen:a,version:t(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i)||x}:/qupzilla/i.test(e)?i={name:"QupZilla",qupzilla:a,version:t(/(?:qupzilla)[\s\/](\d+(?:\.\d+)+)/i)||x}:/chromium/i.test(e)?i={name:"Chromium",chromium:a,version:t(/(?:chromium)[\s\/](\d+(?:\.\d+)?)/i)||x}:/chrome|crios|crmo/i.test(e)?i={name:"Chrome",chrome:a,version:t(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)}:u?i={name:"Android",version:x}:/safari|applewebkit/i.test(e)?(i={name:"Safari",safari:a},x&&(i.version=x)):o?(i={name:"iphone"==o?"iPhone":"ipad"==o?"iPad":"iPod"},x&&(i.version=x)):i=/googlebot/i.test(e)?{name:"Googlebot",googlebot:a,version:t(/googlebot\/(\d+(\.\d+))/i)||x}:{name:t(/^(.*)\/(.*) /),version:n(/^(.*)\/(.*) /)},!i.msedge&&/(apple)?webkit/i.test(e)?(/(apple)?webkit\/537\.36/i.test(e)?(i.name=i.name||"Blink",i.blink=a):(i.name=i.name||"Webkit",i.webkit=a),!i.version&&x&&(i.version=x)):!i.opera&&/gecko\//i.test(e)&&(i.name=i.name||"Gecko",i.gecko=a,i.version=i.version||t(/gecko\/(\d+(\.\d+)?)/i)),i.windowsphone||i.msedge||!u&&!i.silk?i.windowsphone||i.msedge||!o?g?i.mac=a:S?i.xbox=a:v?i.windows=a:_&&(i.linux=a):(i[o]=a,i.ios=a):i.android=a;var E="";i.windows?E=r(t(/Windows ((NT|XP)( \d\d?.\d)?)/i)):i.windowsphone?E=t(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i):i.mac?(E=t(/Mac OS X (\d+([_\.\s]\d+)*)/i),E=E.replace(/[_\s]/g,".")):o?(E=t(/os (\d+([_\s]\d+)*) like mac os x/i),E=E.replace(/[_\s]/g,".")):u?E=t(/android[ \/-](\d+(\.\d+)*)/i):i.webos?E=t(/(?:web|hpw)os\/(\d+(\.\d+)*)/i):i.blackberry?E=t(/rim\stablet\sos\s(\d+(\.\d+)*)/i):i.bada?E=t(/bada\/(\d+(\.\d+)*)/i):i.tizen&&(E=t(/tizen[\/\s](\d+(\.\d+)*)/i)),E&&(i.osversion=E);var C=!i.windows&&E.split(".")[0];return w||l||"ipad"==o||u&&(3==C||C>=4&&!k)||i.silk?i.tablet=a:(k||"iphone"==o||"ipod"==o||u||c||i.blackberry||i.webos||i.bada)&&(i.mobile=a),i.msedge||i.msie&&i.version>=10||i.yandexbrowser&&i.version>=15||i.vivaldi&&i.version>=1||i.chrome&&i.version>=20||i.samsungBrowser&&i.version>=4||i.firefox&&i.version>=20||i.safari&&i.version>=6||i.opera&&i.version>=10||i.ios&&i.osversion&&i.osversion.split(".")[0]>=6||i.blackberry&&i.version>=10.1||i.chromium&&i.version>=20?i.a=a:i.msie&&i.version<10||i.chrome&&i.version<20||i.firefox&&i.version<20||i.safari&&i.version<6||i.opera&&i.version<10||i.ios&&i.osversion&&i.osversion.split(".")[0]<6||i.chromium&&i.version<20?i.c=a:i.x=a,i}function t(e){return e.split(".").length}function n(e,t){var n,r=[];if(Array.prototype.map)return Array.prototype.map.call(e,t);for(n=0;n=0;){if(i[0][r]>i[1][r])return 1;if(i[0][r]!==i[1][r])return-1;if(0===r)return 0}}function i(t,n,i){var o=s;"string"==typeof n&&(i=n,n=void 0),void 0===n&&(n=!1),i&&(o=e(i));var a=""+o.version;for(var u in t)if(t.hasOwnProperty(u)&&o[u]){if("string"!=typeof t[u])throw new Error("Browser version in the minVersion map should be a string: "+u+": "+String(t));return r([a,t[u]])<0}return n}function o(e,t,n){return!i(e,t,n)}var a=!0,s=e("undefined"!=typeof navigator?navigator.userAgent||"":"");return s.test=function(e){for(var t=0;t-1&&("firefox"===o&&a<15||"chrome"===o&&a<25||"safari"===o&&a<6.1||"ios_saf"===o&&a<7))return i({},t,(0,s.default)(n.replace(/calc\(/g,u+"calc("),n,c))}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=n(1192),s=r(a);e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=e.property,n=e.value,r=e.browserInfo,i=r.browser,o=r.version,u=e.prefix.css,c=e.keepUnprefixed;if("cursor"===t&&s[n]&&("firefox"===i&&o<24||"chrome"===i&&o<37||"safari"===i&&o<9||"opera"===i&&o<24))return{cursor:(0,a.default)(u+n,n,c)}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=i;var o=n(1192),a=r(o),s={"zoom-in":!0,"zoom-out":!0};e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=e.property,n=e.value,r=e.browserInfo.browser,i=e.prefix.css,o=e.keepUnprefixed;if("cursor"===t&&s[n]&&("firefox"===r||"chrome"===r||"safari"===r||"opera"===r))return{cursor:(0,a.default)(i+n,n,o)}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=i;var o=n(1192),a=r(o),s={grab:!0,grabbing:!0};e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=e.property,n=e.value,r=e.browserInfo,i=r.browser,o=r.version,u=e.prefix.css,c=e.keepUnprefixed;if("display"===t&&s[n]&&("chrome"===i&&o<29&&o>20||("safari"===i||"ios_saf"===i)&&o<9&&o>6||"opera"===i&&(15==o||16==o)))return{display:(0,a.default)(u+n,n,c)}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=i;var o=n(1192),a=r(o),s={flex:!0,"inline-flex":!0};e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){var t=e.property,n=e.value,r=e.prefix.css,o=e.keepUnprefixed;if(u[t]&&c[n])return i({},t,(0,s.default)(r+n,n,o))}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=n(1192),s=r(a),u={maxHeight:!0,maxWidth:!0,width:!0,height:!0,columnWidth:!0,minWidth:!0,minHeight:!0},c={"min-content":!0,"max-content":!0,"fill-available":!0,"fit-content":!0,"contain-floats":!0};e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){var t=e.property,n=e.value,r=e.browserInfo,o=r.browser,a=r.version,c=e.prefix.css,l=e.keepUnprefixed;if("string"==typeof n&&null!==n.match(u)&&("firefox"===o&&a<16||"chrome"===o&&a<26||("safari"===o||"ios_saf"===o)&&a<7||("opera"===o||"op_mini"===o)&&a<12.1||"android"===o&&a<4.4||"and_uc"===o))return i({},t,(0,s.default)(c+n,n,l))}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=n(1192),s=r(a),u=/linear-gradient|radial-gradient|repeating-linear-gradient|repeating-radial-gradient/;e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){var t=e.property,n=e.value,r=e.prefix.css,o=e.requiresPrefix,s=e.keepUnprefixed,c=(0,l.default)(t);if("string"==typeof n&&p[c]){var f=function(){var e=Object.keys(o).map(function(e){return(0,u.default)(e)}),a=n.split(/,(?![^()]*(?:\([^()]*\))?\))/g);return e.forEach(function(e){a.forEach(function(t,n){t.indexOf(e)>-1&&"order"!==e&&(a[n]=t.replace(e,r+e)+(s?","+t:""))})}),{v:i({},t,a.join(","))}}();if("object"===("undefined"==typeof f?"undefined":a(f)))return f.v}}Object.defineProperty(t,"__esModule",{value:!0});var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};t.default=o;var s=n(1183),u=r(s),c=n(1200),l=r(c),p={transition:!0,transitionProperty:!0};e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.replace(/^(ms|Webkit|Moz|O)/,"");return t.charAt(0).toLowerCase()+t.slice(1)},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){var t=e.property,n=e.value,r=e.styles,o=e.browserInfo,a=o.browser,l=o.version,p=e.prefix.css,f=e.keepUnprefixed;if((c[t]||"display"===t&&"string"==typeof n&&n.indexOf("flex")>-1)&&("ie_mob"===a||"ie"===a)&&10==l){if(f||Array.isArray(r[t])||delete r[t],"display"===t&&u[n])return{display:(0,s.default)(p+u[n],n,f)};if(c[t])return i({},c[t],u[n]||n)}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=n(1192),s=r(a),u={"space-around":"distribute","space-between":"justify","flex-start":"start","flex-end":"end",flex:"flexbox","inline-flex":"inline-flexbox"},c={alignContent:"msFlexLinePack",alignSelf:"msFlexItemAlign",alignItems:"msFlexAlign",justifyContent:"msFlexPack",order:"msFlexOrder",flexGrow:"msFlexPositive",flexShrink:"msFlexNegative",flexBasis:"msPreferredSize"};e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){var t=e.property,n=e.value,r=e.styles,o=e.browserInfo,a=o.browser,l=o.version,f=e.prefix.css,h=e.keepUnprefixed;if((p.indexOf(t)>-1||"display"===t&&"string"==typeof n&&n.indexOf("flex")>-1)&&("firefox"===a&&l<22||"chrome"===a&&l<21||("safari"===a||"ios_saf"===a)&&l<=6.1||"android"===a&&l<4.4||"and_uc"===a)){if(h||Array.isArray(r[t])||delete r[t],"flexDirection"===t&&"string"==typeof n)return{WebkitBoxOrient:n.indexOf("column")>-1?"vertical":"horizontal",WebkitBoxDirection:n.indexOf("reverse")>-1?"reverse":"normal"};if("display"===t&&u[n])return{display:(0,s.default)(f+u[n],n,h)};if(c[t])return i({},c[t],u[n]||n)}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=n(1192),s=r(a),u={"space-around":"justify","space-between":"justify","flex-start":"start","flex-end":"end","wrap-reverse":"multiple",wrap:"multiple",flex:"box","inline-flex":"inline-box"},c={alignItems:"WebkitBoxAlign",justifyContent:"WebkitBoxPack",flexWrap:"WebkitBoxLines"},l=["alignContent","alignSelf","order","flexGrow","flexShrink","flexBasis","flexDirection"],p=Object.keys(c).concat(l);e.exports=t.default},function(e,t,n){var r=n(1204),i=n(621);e.exports=function(e,t,n){var i=e[t];if(i){var o=[];if(Object.keys(i).forEach(function(e){r.indexOf(e)===-1&&o.push(e)}),o.length)throw new Error("Prop "+t+" passed to "+n+". Has invalid keys "+o.join(", "))}},e.exports.isRequired=function(t,n,r){if(!t[n])throw new Error("Prop "+n+" passed to "+r+" is required");return e.exports(t,n,r)},e.exports.supportingArrays=i.PropTypes.oneOfType([i.PropTypes.arrayOf(e.exports),e.exports])},function(e,t){e.exports=["alignContent","MozAlignContent","WebKitAlignContent","MSAlignContent","OAlignContent","alignItems","MozAlignItems","WebKitAlignItems","MSAlignItems","OAlignItems","alignSelf","MozAlignSelf","WebKitAlignSelf","MSAlignSelf","OAlignSelf","all","MozAll","WebKitAll","MSAll","OAll","animation","MozAnimation","WebKitAnimation","MSAnimation","OAnimation","animationDelay","MozAnimationDelay","WebKitAnimationDelay","MSAnimationDelay","OAnimationDelay","animationDirection","MozAnimationDirection","WebKitAnimationDirection","MSAnimationDirection","OAnimationDirection","animationDuration","MozAnimationDuration","WebKitAnimationDuration","MSAnimationDuration","OAnimationDuration","animationFillMode","MozAnimationFillMode","WebKitAnimationFillMode","MSAnimationFillMode","OAnimationFillMode","animationIterationCount","MozAnimationIterationCount","WebKitAnimationIterationCount","MSAnimationIterationCount","OAnimationIterationCount","animationName","MozAnimationName","WebKitAnimationName","MSAnimationName","OAnimationName","animationPlayState","MozAnimationPlayState","WebKitAnimationPlayState","MSAnimationPlayState","OAnimationPlayState","animationTimingFunction","MozAnimationTimingFunction","WebKitAnimationTimingFunction","MSAnimationTimingFunction","OAnimationTimingFunction","backfaceVisibility","MozBackfaceVisibility","WebKitBackfaceVisibility","MSBackfaceVisibility","OBackfaceVisibility","background","MozBackground","WebKitBackground","MSBackground","OBackground","backgroundAttachment","MozBackgroundAttachment","WebKitBackgroundAttachment","MSBackgroundAttachment","OBackgroundAttachment","backgroundBlendMode","MozBackgroundBlendMode","WebKitBackgroundBlendMode","MSBackgroundBlendMode","OBackgroundBlendMode","backgroundClip","MozBackgroundClip","WebKitBackgroundClip","MSBackgroundClip","OBackgroundClip","backgroundColor","MozBackgroundColor","WebKitBackgroundColor","MSBackgroundColor","OBackgroundColor","backgroundImage","MozBackgroundImage","WebKitBackgroundImage","MSBackgroundImage","OBackgroundImage","backgroundOrigin","MozBackgroundOrigin","WebKitBackgroundOrigin","MSBackgroundOrigin","OBackgroundOrigin","backgroundPosition","MozBackgroundPosition","WebKitBackgroundPosition","MSBackgroundPosition","OBackgroundPosition","backgroundRepeat","MozBackgroundRepeat","WebKitBackgroundRepeat","MSBackgroundRepeat","OBackgroundRepeat","backgroundSize","MozBackgroundSize","WebKitBackgroundSize","MSBackgroundSize","OBackgroundSize","blockSize","MozBlockSize","WebKitBlockSize","MSBlockSize","OBlockSize","border","MozBorder","WebKitBorder","MSBorder","OBorder","borderBlockEnd","MozBorderBlockEnd","WebKitBorderBlockEnd","MSBorderBlockEnd","OBorderBlockEnd","borderBlockEndColor","MozBorderBlockEndColor","WebKitBorderBlockEndColor","MSBorderBlockEndColor","OBorderBlockEndColor","borderBlockEndStyle","MozBorderBlockEndStyle","WebKitBorderBlockEndStyle","MSBorderBlockEndStyle","OBorderBlockEndStyle","borderBlockEndWidth","MozBorderBlockEndWidth","WebKitBorderBlockEndWidth","MSBorderBlockEndWidth","OBorderBlockEndWidth","borderBlockStart","MozBorderBlockStart","WebKitBorderBlockStart","MSBorderBlockStart","OBorderBlockStart","borderBlockStartColor","MozBorderBlockStartColor","WebKitBorderBlockStartColor","MSBorderBlockStartColor","OBorderBlockStartColor","borderBlockStartStyle","MozBorderBlockStartStyle","WebKitBorderBlockStartStyle","MSBorderBlockStartStyle","OBorderBlockStartStyle","borderBlockStartWidth","MozBorderBlockStartWidth","WebKitBorderBlockStartWidth","MSBorderBlockStartWidth","OBorderBlockStartWidth","borderBottom","MozBorderBottom","WebKitBorderBottom","MSBorderBottom","OBorderBottom","borderBottomColor","MozBorderBottomColor","WebKitBorderBottomColor","MSBorderBottomColor","OBorderBottomColor","borderBottomLeftRadius","MozBorderBottomLeftRadius","WebKitBorderBottomLeftRadius","MSBorderBottomLeftRadius","OBorderBottomLeftRadius","borderBottomRightRadius","MozBorderBottomRightRadius","WebKitBorderBottomRightRadius","MSBorderBottomRightRadius","OBorderBottomRightRadius","borderBottomStyle","MozBorderBottomStyle","WebKitBorderBottomStyle","MSBorderBottomStyle","OBorderBottomStyle","borderBottomWidth","MozBorderBottomWidth","WebKitBorderBottomWidth","MSBorderBottomWidth","OBorderBottomWidth","borderCollapse","MozBorderCollapse","WebKitBorderCollapse","MSBorderCollapse","OBorderCollapse","borderColor","MozBorderColor","WebKitBorderColor","MSBorderColor","OBorderColor","borderImage","MozBorderImage","WebKitBorderImage","MSBorderImage","OBorderImage","borderImageOutset","MozBorderImageOutset","WebKitBorderImageOutset","MSBorderImageOutset","OBorderImageOutset","borderImageRepeat","MozBorderImageRepeat","WebKitBorderImageRepeat","MSBorderImageRepeat","OBorderImageRepeat","borderImageSlice","MozBorderImageSlice","WebKitBorderImageSlice","MSBorderImageSlice","OBorderImageSlice","borderImageSource","MozBorderImageSource","WebKitBorderImageSource","MSBorderImageSource","OBorderImageSource","borderImageWidth","MozBorderImageWidth","WebKitBorderImageWidth","MSBorderImageWidth","OBorderImageWidth","borderInlineEnd","MozBorderInlineEnd","WebKitBorderInlineEnd","MSBorderInlineEnd","OBorderInlineEnd","borderInlineEndColor","MozBorderInlineEndColor","WebKitBorderInlineEndColor","MSBorderInlineEndColor","OBorderInlineEndColor","borderInlineEndStyle","MozBorderInlineEndStyle","WebKitBorderInlineEndStyle","MSBorderInlineEndStyle","OBorderInlineEndStyle","borderInlineEndWidth","MozBorderInlineEndWidth","WebKitBorderInlineEndWidth","MSBorderInlineEndWidth","OBorderInlineEndWidth","borderInlineStart","MozBorderInlineStart","WebKitBorderInlineStart","MSBorderInlineStart","OBorderInlineStart","borderInlineStartColor","MozBorderInlineStartColor","WebKitBorderInlineStartColor","MSBorderInlineStartColor","OBorderInlineStartColor","borderInlineStartStyle","MozBorderInlineStartStyle","WebKitBorderInlineStartStyle","MSBorderInlineStartStyle","OBorderInlineStartStyle","borderInlineStartWidth","MozBorderInlineStartWidth","WebKitBorderInlineStartWidth","MSBorderInlineStartWidth","OBorderInlineStartWidth","borderLeft","MozBorderLeft","WebKitBorderLeft","MSBorderLeft","OBorderLeft","borderLeftColor","MozBorderLeftColor","WebKitBorderLeftColor","MSBorderLeftColor","OBorderLeftColor","borderLeftStyle","MozBorderLeftStyle","WebKitBorderLeftStyle","MSBorderLeftStyle","OBorderLeftStyle","borderLeftWidth","MozBorderLeftWidth","WebKitBorderLeftWidth","MSBorderLeftWidth","OBorderLeftWidth","borderRadius","MozBorderRadius","WebKitBorderRadius","MSBorderRadius","OBorderRadius","borderRight","MozBorderRight","WebKitBorderRight","MSBorderRight","OBorderRight","borderRightColor","MozBorderRightColor","WebKitBorderRightColor","MSBorderRightColor","OBorderRightColor","borderRightStyle","MozBorderRightStyle","WebKitBorderRightStyle","MSBorderRightStyle","OBorderRightStyle","borderRightWidth","MozBorderRightWidth","WebKitBorderRightWidth","MSBorderRightWidth","OBorderRightWidth","borderSpacing","MozBorderSpacing","WebKitBorderSpacing","MSBorderSpacing","OBorderSpacing","borderStyle","MozBorderStyle","WebKitBorderStyle","MSBorderStyle","OBorderStyle","borderTop","MozBorderTop","WebKitBorderTop","MSBorderTop","OBorderTop","borderTopColor","MozBorderTopColor","WebKitBorderTopColor","MSBorderTopColor","OBorderTopColor","borderTopLeftRadius","MozBorderTopLeftRadius","WebKitBorderTopLeftRadius","MSBorderTopLeftRadius","OBorderTopLeftRadius","borderTopRightRadius","MozBorderTopRightRadius","WebKitBorderTopRightRadius","MSBorderTopRightRadius","OBorderTopRightRadius","borderTopStyle","MozBorderTopStyle","WebKitBorderTopStyle","MSBorderTopStyle","OBorderTopStyle","borderTopWidth","MozBorderTopWidth","WebKitBorderTopWidth","MSBorderTopWidth","OBorderTopWidth","borderWidth","MozBorderWidth","WebKitBorderWidth","MSBorderWidth","OBorderWidth","bottom","MozBottom","WebKitBottom","MSBottom","OBottom","boxDecorationBreak","MozBoxDecorationBreak","WebKitBoxDecorationBreak","MSBoxDecorationBreak","OBoxDecorationBreak","boxShadow","MozBoxShadow","WebKitBoxShadow","MSBoxShadow","OBoxShadow","boxSizing","MozBoxSizing","WebKitBoxSizing","MSBoxSizing","OBoxSizing","breakAfter","MozBreakAfter","WebKitBreakAfter","MSBreakAfter","OBreakAfter","breakBefore","MozBreakBefore","WebKitBreakBefore","MSBreakBefore","OBreakBefore","breakInside","MozBreakInside","WebKitBreakInside","MSBreakInside","OBreakInside","captionSide","MozCaptionSide","WebKitCaptionSide","MSCaptionSide","OCaptionSide","ch","MozCh","WebKitCh","MSCh","OCh","clear","MozClear","WebKitClear","MSClear","OClear","clip","MozClip","WebKitClip","MSClip","OClip","clipPath","MozClipPath","WebKitClipPath","MSClipPath","OClipPath","cm","MozCm","WebKitCm","MSCm","OCm","color","MozColor","WebKitColor","MSColor","OColor","columnCount","MozColumnCount","WebKitColumnCount","MSColumnCount","OColumnCount","columnFill","MozColumnFill","WebKitColumnFill","MSColumnFill","OColumnFill","columnGap","MozColumnGap","WebKitColumnGap","MSColumnGap","OColumnGap","columnRule","MozColumnRule","WebKitColumnRule","MSColumnRule","OColumnRule","columnRuleColor","MozColumnRuleColor","WebKitColumnRuleColor","MSColumnRuleColor","OColumnRuleColor","columnRuleStyle","MozColumnRuleStyle","WebKitColumnRuleStyle","MSColumnRuleStyle","OColumnRuleStyle","columnRuleWidth","MozColumnRuleWidth","WebKitColumnRuleWidth","MSColumnRuleWidth","OColumnRuleWidth","columnSpan","MozColumnSpan","WebKitColumnSpan","MSColumnSpan","OColumnSpan","columnWidth","MozColumnWidth","WebKitColumnWidth","MSColumnWidth","OColumnWidth","columns","MozColumns","WebKitColumns","MSColumns","OColumns","content","MozContent","WebKitContent","MSContent","OContent","counterIncrement","MozCounterIncrement","WebKitCounterIncrement","MSCounterIncrement","OCounterIncrement","counterReset","MozCounterReset","WebKitCounterReset","MSCounterReset","OCounterReset","cursor","MozCursor","WebKitCursor","MSCursor","OCursor","deg","MozDeg","WebKitDeg","MSDeg","ODeg","direction","MozDirection","WebKitDirection","MSDirection","ODirection","display","MozDisplay","WebKitDisplay","MSDisplay","ODisplay","dpcm","MozDpcm","WebKitDpcm","MSDpcm","ODpcm","dpi","MozDpi","WebKitDpi","MSDpi","ODpi","dppx","MozDppx","WebKitDppx","MSDppx","ODppx","em","MozEm","WebKitEm","MSEm","OEm","emptyCells","MozEmptyCells","WebKitEmptyCells","MSEmptyCells","OEmptyCells","ex","MozEx","WebKitEx","MSEx","OEx","filter","MozFilter","WebKitFilter","MSFilter","OFilter","flex","MozFlex","WebKitFlex","MSFlex","OFlex","flexBasis","MozFlexBasis","WebKitFlexBasis","MSFlexBasis","OFlexBasis","flexDirection","MozFlexDirection","WebKitFlexDirection","MSFlexDirection","OFlexDirection","flexFlow","MozFlexFlow","WebKitFlexFlow","MSFlexFlow","OFlexFlow","flexGrow","MozFlexGrow","WebKitFlexGrow","MSFlexGrow","OFlexGrow","flexShrink","MozFlexShrink","WebKitFlexShrink","MSFlexShrink","OFlexShrink","flexWrap","MozFlexWrap","WebKitFlexWrap","MSFlexWrap","OFlexWrap","float","MozFloat","WebKitFloat","MSFloat","OFloat","font","MozFont","WebKitFont","MSFont","OFont","fontFamily","MozFontFamily","WebKitFontFamily","MSFontFamily","OFontFamily","fontFeatureSettings","MozFontFeatureSettings","WebKitFontFeatureSettings","MSFontFeatureSettings","OFontFeatureSettings","fontKerning","MozFontKerning","WebKitFontKerning","MSFontKerning","OFontKerning","fontLanguageOverride","MozFontLanguageOverride","WebKitFontLanguageOverride","MSFontLanguageOverride","OFontLanguageOverride","fontSize","MozFontSize","WebKitFontSize","MSFontSize","OFontSize","fontSizeAdjust","MozFontSizeAdjust","WebKitFontSizeAdjust","MSFontSizeAdjust","OFontSizeAdjust","fontStretch","MozFontStretch","WebKitFontStretch","MSFontStretch","OFontStretch","fontStyle","MozFontStyle","WebKitFontStyle","MSFontStyle","OFontStyle","fontSynthesis","MozFontSynthesis","WebKitFontSynthesis","MSFontSynthesis","OFontSynthesis","fontVariant","MozFontVariant","WebKitFontVariant","MSFontVariant","OFontVariant","fontVariantAlternates","MozFontVariantAlternates","WebKitFontVariantAlternates","MSFontVariantAlternates","OFontVariantAlternates","fontVariantCaps","MozFontVariantCaps","WebKitFontVariantCaps","MSFontVariantCaps","OFontVariantCaps","fontVariantEastAsian","MozFontVariantEastAsian","WebKitFontVariantEastAsian","MSFontVariantEastAsian","OFontVariantEastAsian","fontVariantLigatures","MozFontVariantLigatures","WebKitFontVariantLigatures","MSFontVariantLigatures","OFontVariantLigatures","fontVariantNumeric","MozFontVariantNumeric","WebKitFontVariantNumeric","MSFontVariantNumeric","OFontVariantNumeric","fontVariantPosition","MozFontVariantPosition","WebKitFontVariantPosition","MSFontVariantPosition","OFontVariantPosition","fontWeight","MozFontWeight","WebKitFontWeight","MSFontWeight","OFontWeight","grad","MozGrad","WebKitGrad","MSGrad","OGrad","grid","MozGrid","WebKitGrid","MSGrid","OGrid","gridArea","MozGridArea","WebKitGridArea","MSGridArea","OGridArea","gridAutoColumns","MozGridAutoColumns","WebKitGridAutoColumns","MSGridAutoColumns","OGridAutoColumns","gridAutoFlow","MozGridAutoFlow","WebKitGridAutoFlow","MSGridAutoFlow","OGridAutoFlow","gridAutoRows","MozGridAutoRows","WebKitGridAutoRows","MSGridAutoRows","OGridAutoRows","gridColumn","MozGridColumn","WebKitGridColumn","MSGridColumn","OGridColumn","gridColumnEnd","MozGridColumnEnd","WebKitGridColumnEnd","MSGridColumnEnd","OGridColumnEnd","gridColumnGap","MozGridColumnGap","WebKitGridColumnGap","MSGridColumnGap","OGridColumnGap","gridColumnStart","MozGridColumnStart","WebKitGridColumnStart","MSGridColumnStart","OGridColumnStart","gridGap","MozGridGap","WebKitGridGap","MSGridGap","OGridGap","gridRow","MozGridRow","WebKitGridRow","MSGridRow","OGridRow","gridRowEnd","MozGridRowEnd","WebKitGridRowEnd","MSGridRowEnd","OGridRowEnd","gridRowGap","MozGridRowGap","WebKitGridRowGap","MSGridRowGap","OGridRowGap","gridRowStart","MozGridRowStart","WebKitGridRowStart","MSGridRowStart","OGridRowStart","gridTemplate","MozGridTemplate","WebKitGridTemplate","MSGridTemplate","OGridTemplate","gridTemplateAreas","MozGridTemplateAreas","WebKitGridTemplateAreas","MSGridTemplateAreas","OGridTemplateAreas","gridTemplateColumns","MozGridTemplateColumns","WebKitGridTemplateColumns","MSGridTemplateColumns","OGridTemplateColumns","gridTemplateRows","MozGridTemplateRows","WebKitGridTemplateRows","MSGridTemplateRows","OGridTemplateRows","height","MozHeight","WebKitHeight","MSHeight","OHeight","hyphens","MozHyphens","WebKitHyphens","MSHyphens","OHyphens","hz","MozHz","WebKitHz","MSHz","OHz","imageOrientation","MozImageOrientation","WebKitImageOrientation","MSImageOrientation","OImageOrientation","imageRendering","MozImageRendering","WebKitImageRendering","MSImageRendering","OImageRendering","imageResolution","MozImageResolution","WebKitImageResolution","MSImageResolution","OImageResolution","imeMode","MozImeMode","WebKitImeMode","MSImeMode","OImeMode","in","MozIn","WebKitIn","MSIn","OIn","inherit","MozInherit","WebKitInherit","MSInherit","OInherit","initial","MozInitial","WebKitInitial","MSInitial","OInitial","inlineSize","MozInlineSize","WebKitInlineSize","MSInlineSize","OInlineSize","isolation","MozIsolation","WebKitIsolation","MSIsolation","OIsolation","justifyContent","MozJustifyContent","WebKitJustifyContent","MSJustifyContent","OJustifyContent","khz","MozKhz","WebKitKhz","MSKhz","OKhz","left","MozLeft","WebKitLeft","MSLeft","OLeft","letterSpacing","MozLetterSpacing","WebKitLetterSpacing","MSLetterSpacing","OLetterSpacing","lineBreak","MozLineBreak","WebKitLineBreak","MSLineBreak","OLineBreak","lineHeight","MozLineHeight","WebKitLineHeight","MSLineHeight","OLineHeight","listStyle","MozListStyle","WebKitListStyle","MSListStyle","OListStyle","listStyleImage","MozListStyleImage","WebKitListStyleImage","MSListStyleImage","OListStyleImage","listStylePosition","MozListStylePosition","WebKitListStylePosition","MSListStylePosition","OListStylePosition","listStyleType","MozListStyleType","WebKitListStyleType","MSListStyleType","OListStyleType","margin","MozMargin","WebKitMargin","MSMargin","OMargin","marginBlockEnd","MozMarginBlockEnd","WebKitMarginBlockEnd","MSMarginBlockEnd","OMarginBlockEnd","marginBlockStart","MozMarginBlockStart","WebKitMarginBlockStart","MSMarginBlockStart","OMarginBlockStart","marginBottom","MozMarginBottom","WebKitMarginBottom","MSMarginBottom","OMarginBottom","marginInlineEnd","MozMarginInlineEnd","WebKitMarginInlineEnd","MSMarginInlineEnd","OMarginInlineEnd","marginInlineStart","MozMarginInlineStart","WebKitMarginInlineStart","MSMarginInlineStart","OMarginInlineStart","marginLeft","MozMarginLeft","WebKitMarginLeft","MSMarginLeft","OMarginLeft","marginRight","MozMarginRight","WebKitMarginRight","MSMarginRight","OMarginRight","marginTop","MozMarginTop","WebKitMarginTop","MSMarginTop","OMarginTop","mask","MozMask","WebKitMask","MSMask","OMask","maskClip","MozMaskClip","WebKitMaskClip","MSMaskClip","OMaskClip","maskComposite","MozMaskComposite","WebKitMaskComposite","MSMaskComposite","OMaskComposite","maskImage","MozMaskImage","WebKitMaskImage","MSMaskImage","OMaskImage","maskMode","MozMaskMode","WebKitMaskMode","MSMaskMode","OMaskMode","maskOrigin","MozMaskOrigin","WebKitMaskOrigin","MSMaskOrigin","OMaskOrigin","maskPosition","MozMaskPosition","WebKitMaskPosition","MSMaskPosition","OMaskPosition","maskRepeat","MozMaskRepeat","WebKitMaskRepeat","MSMaskRepeat","OMaskRepeat","maskSize","MozMaskSize","WebKitMaskSize","MSMaskSize","OMaskSize","maskType","MozMaskType","WebKitMaskType","MSMaskType","OMaskType","maxBlockSize","MozMaxBlockSize","WebKitMaxBlockSize","MSMaxBlockSize","OMaxBlockSize","maxHeight","MozMaxHeight","WebKitMaxHeight","MSMaxHeight","OMaxHeight","maxInlineSize","MozMaxInlineSize","WebKitMaxInlineSize","MSMaxInlineSize","OMaxInlineSize","maxWidth","MozMaxWidth","WebKitMaxWidth","MSMaxWidth","OMaxWidth","minBlockSize","MozMinBlockSize","WebKitMinBlockSize","MSMinBlockSize","OMinBlockSize","minHeight","MozMinHeight","WebKitMinHeight","MSMinHeight","OMinHeight","minInlineSize","MozMinInlineSize","WebKitMinInlineSize","MSMinInlineSize","OMinInlineSize","minWidth","MozMinWidth","WebKitMinWidth","MSMinWidth","OMinWidth","mixBlendMode","MozMixBlendMode","WebKitMixBlendMode","MSMixBlendMode","OMixBlendMode","mm","MozMm","WebKitMm","MSMm","OMm","ms","MozMs","WebKitMs","MSMs","OMs","objectFit","MozObjectFit","WebKitObjectFit","MSObjectFit","OObjectFit","objectPosition","MozObjectPosition","WebKitObjectPosition","MSObjectPosition","OObjectPosition","offsetBlockEnd","MozOffsetBlockEnd","WebKitOffsetBlockEnd","MSOffsetBlockEnd","OOffsetBlockEnd","offsetBlockStart","MozOffsetBlockStart","WebKitOffsetBlockStart","MSOffsetBlockStart","OOffsetBlockStart","offsetInlineEnd","MozOffsetInlineEnd","WebKitOffsetInlineEnd","MSOffsetInlineEnd","OOffsetInlineEnd","offsetInlineStart","MozOffsetInlineStart","WebKitOffsetInlineStart","MSOffsetInlineStart","OOffsetInlineStart","opacity","MozOpacity","WebKitOpacity","MSOpacity","OOpacity","order","MozOrder","WebKitOrder","MSOrder","OOrder","orphans","MozOrphans","WebKitOrphans","MSOrphans","OOrphans","outline","MozOutline","WebKitOutline","MSOutline","OOutline","outlineColor","MozOutlineColor","WebKitOutlineColor","MSOutlineColor","OOutlineColor","outlineOffset","MozOutlineOffset","WebKitOutlineOffset","MSOutlineOffset","OOutlineOffset","outlineStyle","MozOutlineStyle","WebKitOutlineStyle","MSOutlineStyle","OOutlineStyle","outlineWidth","MozOutlineWidth","WebKitOutlineWidth","MSOutlineWidth","OOutlineWidth","overflow","MozOverflow","WebKitOverflow","MSOverflow","OOverflow","overflowWrap","MozOverflowWrap","WebKitOverflowWrap","MSOverflowWrap","OOverflowWrap","overflowX","MozOverflowX","WebKitOverflowX","MSOverflowX","OOverflowX","overflowY","MozOverflowY","WebKitOverflowY","MSOverflowY","OOverflowY","padding","MozPadding","WebKitPadding","MSPadding","OPadding","paddingBlockEnd","MozPaddingBlockEnd","WebKitPaddingBlockEnd","MSPaddingBlockEnd","OPaddingBlockEnd","paddingBlockStart","MozPaddingBlockStart","WebKitPaddingBlockStart","MSPaddingBlockStart","OPaddingBlockStart","paddingBottom","MozPaddingBottom","WebKitPaddingBottom","MSPaddingBottom","OPaddingBottom","paddingInlineEnd","MozPaddingInlineEnd","WebKitPaddingInlineEnd","MSPaddingInlineEnd","OPaddingInlineEnd","paddingInlineStart","MozPaddingInlineStart","WebKitPaddingInlineStart","MSPaddingInlineStart","OPaddingInlineStart","paddingLeft","MozPaddingLeft","WebKitPaddingLeft","MSPaddingLeft","OPaddingLeft","paddingRight","MozPaddingRight","WebKitPaddingRight","MSPaddingRight","OPaddingRight","paddingTop","MozPaddingTop","WebKitPaddingTop","MSPaddingTop","OPaddingTop","pageBreakAfter","MozPageBreakAfter","WebKitPageBreakAfter","MSPageBreakAfter","OPageBreakAfter","pageBreakBefore","MozPageBreakBefore","WebKitPageBreakBefore","MSPageBreakBefore","OPageBreakBefore","pageBreakInside","MozPageBreakInside","WebKitPageBreakInside","MSPageBreakInside","OPageBreakInside","pc","MozPc","WebKitPc","MSPc","OPc","perspective","MozPerspective","WebKitPerspective","MSPerspective","OPerspective","perspectiveOrigin","MozPerspectiveOrigin","WebKitPerspectiveOrigin","MSPerspectiveOrigin","OPerspectiveOrigin","pointerEvents","MozPointerEvents","WebKitPointerEvents","MSPointerEvents","OPointerEvents","position","MozPosition","WebKitPosition","MSPosition","OPosition","pt","MozPt","WebKitPt","MSPt","OPt","px","MozPx","WebKitPx","MSPx","OPx","q","MozQ","WebKitQ","MSQ","OQ","quotes","MozQuotes","WebKitQuotes","MSQuotes","OQuotes","rad","MozRad","WebKitRad","MSRad","ORad","rem","MozRem","WebKitRem","MSRem","ORem","resize","MozResize","WebKitResize","MSResize","OResize","revert","MozRevert","WebKitRevert","MSRevert","ORevert","right","MozRight","WebKitRight","MSRight","ORight","rubyAlign","MozRubyAlign","WebKitRubyAlign","MSRubyAlign","ORubyAlign","rubyMerge","MozRubyMerge","WebKitRubyMerge","MSRubyMerge","ORubyMerge","rubyPosition","MozRubyPosition","WebKitRubyPosition","MSRubyPosition","ORubyPosition","s","MozS","WebKitS","MSS","OS","scrollBehavior","MozScrollBehavior","WebKitScrollBehavior","MSScrollBehavior","OScrollBehavior","scrollSnapCoordinate","MozScrollSnapCoordinate","WebKitScrollSnapCoordinate","MSScrollSnapCoordinate","OScrollSnapCoordinate","scrollSnapDestination","MozScrollSnapDestination","WebKitScrollSnapDestination","MSScrollSnapDestination","OScrollSnapDestination","scrollSnapType","MozScrollSnapType","WebKitScrollSnapType","MSScrollSnapType","OScrollSnapType","shapeImageThreshold","MozShapeImageThreshold","WebKitShapeImageThreshold","MSShapeImageThreshold","OShapeImageThreshold","shapeMargin","MozShapeMargin","WebKitShapeMargin","MSShapeMargin","OShapeMargin","shapeOutside","MozShapeOutside","WebKitShapeOutside","MSShapeOutside","OShapeOutside","tabSize","MozTabSize","WebKitTabSize","MSTabSize","OTabSize","tableLayout","MozTableLayout","WebKitTableLayout","MSTableLayout","OTableLayout","textAlign","MozTextAlign","WebKitTextAlign","MSTextAlign","OTextAlign","textAlignLast","MozTextAlignLast","WebKitTextAlignLast","MSTextAlignLast","OTextAlignLast","textCombineUpright","MozTextCombineUpright","WebKitTextCombineUpright","MSTextCombineUpright","OTextCombineUpright","textDecoration","MozTextDecoration","WebKitTextDecoration","MSTextDecoration","OTextDecoration","textDecorationColor","MozTextDecorationColor","WebKitTextDecorationColor","MSTextDecorationColor","OTextDecorationColor","textDecorationLine","MozTextDecorationLine","WebKitTextDecorationLine","MSTextDecorationLine","OTextDecorationLine","textDecorationStyle","MozTextDecorationStyle","WebKitTextDecorationStyle","MSTextDecorationStyle","OTextDecorationStyle","textEmphasis","MozTextEmphasis","WebKitTextEmphasis","MSTextEmphasis","OTextEmphasis","textEmphasisColor","MozTextEmphasisColor","WebKitTextEmphasisColor","MSTextEmphasisColor","OTextEmphasisColor","textEmphasisPosition","MozTextEmphasisPosition","WebKitTextEmphasisPosition","MSTextEmphasisPosition","OTextEmphasisPosition","textEmphasisStyle","MozTextEmphasisStyle","WebKitTextEmphasisStyle","MSTextEmphasisStyle","OTextEmphasisStyle","textIndent","MozTextIndent","WebKitTextIndent","MSTextIndent","OTextIndent","textOrientation","MozTextOrientation","WebKitTextOrientation","MSTextOrientation","OTextOrientation","textOverflow","MozTextOverflow","WebKitTextOverflow","MSTextOverflow","OTextOverflow","textRendering","MozTextRendering","WebKitTextRendering","MSTextRendering","OTextRendering","textShadow","MozTextShadow","WebKitTextShadow","MSTextShadow","OTextShadow","textTransform","MozTextTransform","WebKitTextTransform","MSTextTransform","OTextTransform","textUnderlinePosition","MozTextUnderlinePosition","WebKitTextUnderlinePosition","MSTextUnderlinePosition","OTextUnderlinePosition","top","MozTop","WebKitTop","MSTop","OTop","touchAction","MozTouchAction","WebKitTouchAction","MSTouchAction","OTouchAction","transform","MozTransform","WebKitTransform","MSTransform","OTransform","transformBox","MozTransformBox","WebKitTransformBox","MSTransformBox","OTransformBox","transformOrigin","MozTransformOrigin","WebKitTransformOrigin","MSTransformOrigin","OTransformOrigin","transformStyle","MozTransformStyle","WebKitTransformStyle","MSTransformStyle","OTransformStyle","transition","MozTransition","WebKitTransition","MSTransition","OTransition","transitionDelay","MozTransitionDelay","WebKitTransitionDelay","MSTransitionDelay","OTransitionDelay","transitionDuration","MozTransitionDuration","WebKitTransitionDuration","MSTransitionDuration","OTransitionDuration","transitionProperty","MozTransitionProperty","WebKitTransitionProperty","MSTransitionProperty","OTransitionProperty","transitionTimingFunction","MozTransitionTimingFunction","WebKitTransitionTimingFunction","MSTransitionTimingFunction","OTransitionTimingFunction","turn","MozTurn","WebKitTurn","MSTurn","OTurn","unicodeBidi","MozUnicodeBidi","WebKitUnicodeBidi","MSUnicodeBidi","OUnicodeBidi","unset","MozUnset","WebKitUnset","MSUnset","OUnset","verticalAlign","MozVerticalAlign","WebKitVerticalAlign","MSVerticalAlign","OVerticalAlign","vh","MozVh","WebKitVh","MSVh","OVh","visibility","MozVisibility","WebKitVisibility","MSVisibility","OVisibility","vmax","MozVmax","WebKitVmax","MSVmax","OVmax","vmin","MozVmin","WebKitVmin","MSVmin","OVmin","vw","MozVw","WebKitVw","MSVw","OVw","whiteSpace","MozWhiteSpace","WebKitWhiteSpace","MSWhiteSpace","OWhiteSpace","widows","MozWidows","WebKitWidows","MSWidows","OWidows","width","MozWidth","WebKitWidth","MSWidth","OWidth","willChange","MozWillChange","WebKitWillChange","MSWillChange","OWillChange","wordBreak","MozWordBreak","WebKitWordBreak","MSWordBreak","OWordBreak","wordSpacing","MozWordSpacing","WebKitWordSpacing","MSWordSpacing","OWordSpacing","wordWrap","MozWordWrap","WebKitWordWrap","MSWordWrap","OWordWrap","writingMode","MozWritingMode","WebKitWritingMode","MSWritingMode","OWritingMode","zIndex","MozZIndex","WebKitZIndex","MSZIndex","OZIndex","fontSize","MozFontSize","WebKitFontSize","MSFontSize","OFontSize"]; +},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t=0&&_.splice(t,1)}function s(e){var t=document.createElement("style");return t.type="text/css",o(e,t),t}function u(e){var t=document.createElement("link");return t.rel="stylesheet",o(e,t),t}function c(e,t){var n,r,i;if(t.singleton){var o=g++;n=v||(v=s(t)),r=l.bind(null,n,o,!1),i=l.bind(null,n,o,!0)}else e.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=u(t),r=f.bind(null,n),i=function(){a(n),n.href&&URL.revokeObjectURL(n.href)}):(n=s(t),r=p.bind(null,n),i=function(){a(n)});return r(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;r(e=t)}else i()}}function l(e,t,n,r){var i=n?"":r.css;if(e.styleSheet)e.styleSheet.cssText=b(t,i);else{var o=document.createTextNode(i),a=e.childNodes;a[t]&&e.removeChild(a[t]),a.length?e.insertBefore(o,a[t]):e.appendChild(o)}}function p(e,t){var n=t.css,r=t.media;t.sourceMap;if(r&&e.setAttribute("media",r),e.styleSheet)e.styleSheet.cssText=n;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(n))}}function f(e,t){var n=t.css,r=(t.media,t.sourceMap);r&&(n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(r))))+" */");var i=new Blob([n],{type:"text/css"}),o=e.href;e.href=URL.createObjectURL(i),o&&URL.revokeObjectURL(o)}var h={},d=function(e){var t;return function(){return"undefined"==typeof t&&(t=e.apply(this,arguments)),t}},m=d(function(){return/msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())}),y=d(function(){return document.head||document.getElementsByTagName("head")[0]}),v=null,g=0,_=[];e.exports=function(e,t){t=t||{},"undefined"==typeof t.singleton&&(t.singleton=m()),"undefined"==typeof t.insertAt&&(t.insertAt="bottom");var n=i(e);return r(n,t),function(e){for(var o=[],a=0;a=400?(a.updateLoadingStatus("failed"),i.newThrownErr(new Error(t.statusText+" "+e))):(a.updateLoadingStatus("success"),a.updateSpec(t.text),void a.updateUrl(e))}var i=n.errActions,o=n.specSelectors,a=n.specActions,s=t.fetch;e=e||o.url(),a.updateLoadingStatus("loading"),s({url:e,loadSpec:!0,credentials:"same-origin",headers:{Accept:"application/json,*/*"}}).then(r,r)}},updateLoadingStatus:function(e){var t=[null,"loading","failed","success","failedConfig"];return t.indexOf(e)===-1&&console.error("Error: "+e+" is not one of "+JSON.stringify(t)),{type:"spec_update_loading_status",payload:e}}},r={spec_update_loading_status:function(e,t){return"string"==typeof t.payload?e.set("loadingStatus",t.payload):e}},a={loadingStatus:(0,i.createSelector)(function(e){return e||(0,o.Map)()},function(e){return e.get("loadingStatus")||null})};return{statePlugins:{spec:{actions:n,reducers:r,selectors:a}}}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=r;var i=n(575),o=n(325)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n6?s-6:0),c=6;c5?c-5:0),p=5;p5?a-5:0),u=5;u key("+l[p]+")"].concat(s));if(h instanceof Error)return h}}return i(t)}function u(e){return a(e,"List",b.List.isList)}function c(e,t,n,r){function o(){for(var i=arguments.length,o=Array(i),u=0;u5?s-5:0),c=5;c5?c-5:0),p=5;p>",w={listOf:u,mapOf:l,orderedMapOf:p,setOf:f,orderedSetOf:h,stackOf:d,iterableOf:m,recordOf:y,shape:g,contains:g,mapContains:_,list:o("List",b.List.isList),map:o("Map",b.Map.isMap),orderedMap:o("OrderedMap",b.OrderedMap.isOrderedMap),set:o("Set",b.Set.isSet),orderedSet:o("OrderedSet",b.OrderedSet.isOrderedSet),stack:o("Stack",b.Stack.isStack),seq:o("Seq",b.Seq.isSeq),record:o("Record",function(e){return e instanceof b.Record}),iterable:o("Iterable",b.Iterable.isIterable)};e.exports=w},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n-1&&e.setState({scopes:e.state.scopes.filter(function(e){return e!==i})})},this.onInputChange=function(t){var n=t.target,r=n.dataset.name,o=n.value,a=i({},r,o);e.setState(a)},this.logout=function(t){t.preventDefault();var n=e.props,r=n.authActions,i=n.errActions,o=n.name;i.clear({authId:o,type:"auth",source:"auth"}),r.logout([o])}};t.default=v},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=e.auth,n=e.authActions,r=e.errActions,i=e.configs,o=e.authConfigs,u=void 0===o?{}:o,c=t.schema,l=t.scopes,p=t.name,f=t.clientId,h=c.get("flow"),d=[];switch(h){case"password":return void n.authorizePassword(t);case"application":return void n.authorizeApplication(t);case"accessCode":d.push("response_type=code");break;case"implicit":d.push("response_type=token")}"string"==typeof f&&d.push("client_id="+encodeURIComponent(f));var m=i.oauth2RedirectUrl;if("undefined"==typeof m)return void r.newAuthErr({authId:p,source:"validation",level:"error",message:"oauth2RedirectUri configuration is not passed. Oauth2 authorization cannot be performed."});if(d.push("redirect_uri="+encodeURIComponent(m)),Array.isArray(l)&&0=0||this.state.url.indexOf("127.0.0.1")>=0?null:l.default.createElement("span",{style:{float:"right"}},l.default.createElement("a",{target:"_blank",href:this.state.validatorUrl+"/debug?url="+this.state.url},l.default.createElement(f,{src:this.state.validatorUrl+"?url="+this.state.url,alt:"Online validator badge"})))}}]),t}(l.default.Component);p.propTypes={getComponent:c.PropTypes.func.isRequired,getConfigs:c.PropTypes.func.isRequired,specSelectors:c.PropTypes.object.isRequired},t.default=p;var f=function(e){function t(e){i(this,t);var n=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.state={loaded:!1,error:!1},n}return a(t,e),u(t,[{key:"componentDidMount",value:function(){var e=this,t=new Image;t.onload=function(){e.setState({loaded:!0})},t.onerror=function(){e.setState({error:!0})},t.src=this.props.src}},{key:"componentWillReceiveProps",value:function(e){var t=this;if(e.src!==this.props.src){var n=new Image;n.onload=function(){t.setState({loaded:!0})},n.onerror=function(){t.setState({error:!0})},n.src=e.src}}},{key:"render",value:function(){return this.state.error?l.default.createElement("img",{alt:"Error"}):this.state.loaded?l.default.createElement("img",{src:this.props.src,alt:this.props.alt}):l.default.createElement("img",{alt:"Loading..."})}}]),t}(l.default.Component);f.propTypes={src:c.PropTypes.string,alt:c.PropTypes.string}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t0){var N=!w.get(String(s.get("status")));s=s.set("notDocumented",N)}var F=this.state.tryItOutEnabled,B=this.isShown(),L=[r,i];return l.default.createElement("div",{className:b?"opblock opblock-deprecated":B?"opblock opblock-"+i+" is-open":"opblock opblock-"+i,id:t},l.default.createElement("div",{className:"opblock-summary opblock-summary-"+i,onClick:this.toggleShown},l.default.createElement("span",{className:"opblock-summary-method"},i.toUpperCase()),l.default.createElement("span",{className:b?"opblock-summary-path__deprecated":"opblock-summary-path"},l.default.createElement("span",null,r),l.default.createElement(P,{path:n})),a?l.default.createElement("div",{className:"opblock-summary-description"},g):null,k&&k.count()?l.default.createElement(M,{authActions:y,security:k,authSelectors:v}):null),l.default.createElement(I,{isOpened:B,animated:!0},l.default.createElement("div",{className:"opblock-body"},b&&l.default.createElement("h4",{className:"opblock-title_normal"}," Warning: Deprecated"),_&&l.default.createElement("div",{className:"opblock-description-wrapper"},l.default.createElement("div",{className:"opblock-description"},l.default.createElement(j,{source:_}))),x&&x.get("url")?l.default.createElement("div",{className:"opblock-external-docs-wrapper"},l.default.createElement("h4",{className:"opblock-title_normal"},"Find more details"),l.default.createElement("div",{className:"opblock-external-docs"},l.default.createElement("span",{className:"opblock-external-docs__description"},x.get("description")),l.default.createElement("a",{className:"opblock-external-docs__link",href:x.get("url")},x.get("url")))):null,l.default.createElement(T,{parameters:C,onChangeKey:L,onTryoutClick:this.onTryoutClick,onCancelClick:this.onCancelClick,tryItOutEnabled:F,allowTryItOut:c,fn:p,getComponent:f,specActions:d,specSelectors:m,pathMethod:[r,i]}),F&&c&&E&&E.size?l.default.createElement("div",{className:"opblock-schemes"},l.default.createElement(R,{schemes:E,path:r,method:i,specActions:d})):null,l.default.createElement("div",{className:F&&s&&c?"btn-group":"execute-wrapper"},F&&c?l.default.createElement(O,{getComponent:f,operation:o,specActions:d,specSelectors:m,path:r,method:i,onExecute:this.onExecute}):null,F&&s&&c?l.default.createElement(D,{onClick:this.onClearClick,specActions:d,path:r,method:i}):null),this.state.executeInProgress?l.default.createElement("div",{className:"loading-container"},l.default.createElement("div",{className:"loading"})):null,w?l.default.createElement(A,{responses:w,request:u,tryItOutResponse:s,getComponent:f,specSelectors:m,specActions:d,produces:S,producesValue:o.get("produces_value"),pathMethod:[r,i],fn:p}):null)))}}]),t}(l.default.Component);y.propTypes={path:c.PropTypes.string.isRequired,method:c.PropTypes.string.isRequired,operation:c.PropTypes.object.isRequired,showSummary:c.PropTypes.bool,isShownKey:m.arrayOrString.isRequired,jumpToKey:m.arrayOrString.isRequired,allowTryItOut:c.PropTypes.bool,response:c.PropTypes.object,request:c.PropTypes.object,getComponent:c.PropTypes.func.isRequired,authActions:c.PropTypes.object,authSelectors:c.PropTypes.object,specActions:c.PropTypes.object.isRequired,specSelectors:c.PropTypes.object.isRequired,layoutActions:c.PropTypes.object.isRequired,layoutSelectors:c.PropTypes.object.isRequired,fn:c.PropTypes.object.isRequired},y.defaultProps={showSummary:!0,response:null,allowTryItOut:!0},t.default=y},function(e,t,n){e.exports=n(1229)},function(e,t,n){"use strict";function r(e,t,n){return!i(e.props,t)||!i(e.state,n)}var i=n(735);e.exports=r},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.objectWithFuncs=t.arrayOrString=void 0;var r=n(621),i=function(e,t){return r.PropTypes.shape(e.reduce(function(e,n){return e[n]=t,e},{}))};t.arrayOrString=r.PropTypes.oneOfType([r.PropTypes.arrayOf(r.PropTypes.string),r.PropTypes.string]),t.objectWithFuncs=function(e){return i(e,r.PropTypes.func.isRequired)}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n1&&(_=x[1])}p=c.default.createElement("div",null,c.default.createElement("a",{href:v,download:_},"Download file"))}else p=c.default.createElement("pre",null,"Download headers detected but your browser does not support downloading binary via XHR (Blob).")}else p="string"==typeof t?c.default.createElement(s,{value:t}):c.default.createElement("div",null,"Unknown response type");return p?c.default.createElement("div",null,c.default.createElement("h5",null,"Response body"),p):null}}]),t}(c.default.Component);h.propTypes={content:u.PropTypes.any.isRequired,contentType:u.PropTypes.string.isRequired,getComponent:u.PropTypes.func.isRequired,headers:u.PropTypes.object,url:u.PropTypes.string},t.default=h},function(e,t,n){var r=n(356),i=r(function(e,t,n){return e+(n?" ":"")+t.toLowerCase()});e.exports=i},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t-1)return this.renderFixed();var m=this.renderStatic,y=this.state.height,v=parseFloat(y).toFixed(1);y>-1&&m&&(this.renderStatic=!1);var g=s.default.createElement(p.default,{onHeightReady:this.onHeightReady},a);if(m){var _=n?{height:"auto"}:{overflow:"hidden",height:0};return!n&&y>-1?l?s.default.createElement("div",o({style:o({height:0,overflow:"hidden"},r)},d),g):null:s.default.createElement("div",o({style:o({},_,r)},d),g)}return s.default.createElement(c.Motion,{defaultStyle:{height:Math.max(0,y)},onRest:f,style:{height:this.getMotionHeight(y)}},function(t){if(e.height=h(t.height),!n&&"0.0"===e.height)return l?s.default.createElement("div",o({style:o({height:0,overflow:"hidden"},r)},d),g):null;var i=n&&e.height===v?{height:"auto"}:{height:t.height,overflow:"hidden"};return s.default.createElement("div",o({style:o({},i,r)},d),g)})}});t.default=d},function(e,t,n){"use strict";var r=n(1229),i={shouldComponentUpdate:function(e,t){return r(this,e,t)}};e.exports=i},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e.default:e}t.__esModule=!0;var i=n(1245);t.Motion=r(i);var o=n(1253);t.StaggeredMotion=r(o);var a=n(1254);t.TransitionMotion=r(a);var s=n(1256);t.spring=r(s);var u=n(1257);t.presets=r(u);var c=n(1258);t.reorderKeys=r(c)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var i=Object.assign||function(e){for(var t=1;t10*_&&(e.accumulatedTime=0),0===e.accumulatedTime)return e.animationID=null,void e.startAnimationIfNecessary();var i=(e.accumulatedTime-Math.floor(e.accumulatedTime/_)*_)/_,o=Math.floor(e.accumulatedTime/_),a={},s={},u={},c={};for(var p in t)if(t.hasOwnProperty(p)){var h=t[p];if("number"==typeof h)u[p]=h,c[p]=0,a[p]=h,s[p]=0;else{for(var d=e.state.lastIdealStyle[p],m=e.state.lastIdealVelocity[p],v=0;v10*b&&(e.accumulatedTime=0),0===e.accumulatedTime)return e.animationID=null,void e.startAnimationIfNecessary();for(var o=(e.accumulatedTime-Math.floor(e.accumulatedTime/b)*b)/b,a=Math.floor(e.accumulatedTime/b),s=[],u=[],c=[],l=[],f=0;f10*S&&(e.accumulatedTime=0),0===e.accumulatedTime)return e.animationID=null,void e.startAnimationIfNecessary();for(var u=(e.accumulatedTime-Math.floor(e.accumulatedTime/S)*S)/S,c=Math.floor(e.accumulatedTime/S),l=a(e.props.willEnter,e.props.willLeave,e.state.mergedPropsStyles,n,e.state.currentStyles,e.state.currentVelocities,e.state.lastIdealStyles,e.state.lastIdealVelocities),p=l[0],f=l[1],d=l[2],m=l[3],y=l[4],g=0;gr[l])return-1;if(i>o[l]&&ur[l])return 1;if(a>o[l]&&s=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(){for(var e=arguments.length,t=Array(e),n=0;n=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;tl,collapsedContent:w},f.default.createElement("span",{className:"brace-open object"},y),r?f.default.createElement(x,{name:n}):null,f.default.createElement("span",{className:"inner-object"},f.default.createElement("table",{className:"model",style:{marginLeft:"2em"}},f.default.createElement("tbody",null,h?f.default.createElement("tr",{style:{color:"#999",fontStyle:"italic"}},f.default.createElement("td",null,"description:"),f.default.createElement("td",null,h)):null,d&&d.size?d.entrySeq().map(function(e){var t=c(e,2),r=t[0],i=t[1],l=m.List.isList(b)&&b.contains(r),p={verticalAlign:"top",paddingRight:"0.2em"};return l&&(p.fontWeight="bold"),f.default.createElement("tr",{key:r},f.default.createElement("td",{style:p},r,":"),f.default.createElement("td",{style:{verticalAlign:"top"}},f.default.createElement(k,u({key:"object-"+n+"-"+r+"_"+i},s,{required:l,getComponent:o,schema:i,depth:a+1}))))}).toArray():null,g&&g.size?f.default.createElement("tr",null,f.default.createElement("td",null,"< * >:"),f.default.createElement("td",null,f.default.createElement(k,u({},s,{required:!1,getComponent:o,schema:g,depth:a+1})))):null))),f.default.createElement("span",{className:"brace-close"},v)))}}]),t}(p.Component);b.propTypes={schema:p.PropTypes.object.isRequired,getComponent:p.PropTypes.func.isRequired,specSelectors:p.PropTypes.object.isRequired,name:p.PropTypes.string,isRef:p.PropTypes.bool,expandDepth:p.PropTypes.number,depth:p.PropTypes.number};var x=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return s(t,e),l(t,[{key:"render",value:function(){var e=this.props,t=e.schema,n=e.required;if(!t||!t.get)return f.default.createElement("div",null);var r=t.get("type"),i=t.get("format"),o=t.get("xml"),a=t.get("enum"),s=t.filter(function(e,t){return["enum","type","format","$$ref"].indexOf(t)===-1}),u=n?{fontWeight:"bold"}:{};return f.default.createElement("span",{className:"prop"},f.default.createElement("span",{className:"prop-type",style:u},r)," ",n&&f.default.createElement("span",{style:{color:"red"}},"*"),i&&f.default.createElement("span",{className:"prop-format"},"($",i,")"),s.size?s.entrySeq().map(function(e){var t=c(e,2),n=t[0],r=t[1];return f.default.createElement("span",{key:n+"-"+r,style:g},f.default.createElement("br",null),"description"!==n&&n+": ",String(r))}):null,o&&o.size?f.default.createElement("span",null,f.default.createElement("br",null),f.default.createElement("span",{style:g},"xml:"),o.entrySeq().map(function(e){var t=c(e,2),n=t[0],r=t[1];return f.default.createElement("span",{key:n+"-"+r,style:g},f.default.createElement("br",null),"   ",n,": ",String(r))}).toArray()):null,a&&f.default.createElement(_,{value:a}))}}]),t}(p.Component);x.propTypes={schema:p.PropTypes.object.isRequired,required:p.PropTypes.bool};var w=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return s(t,e),l(t,[{key:"render",value:function(){var e=this.props,t=e.required,n=e.schema,r=e.depth,i=e.expandDepth,o=n.get("items"),a=n.filter(function(e,t){return["type","items","$$ref"].indexOf(t)===-1});return f.default.createElement("span",{className:"model"},f.default.createElement("span",{className:"model-title"},f.default.createElement("span",{className:"model-title__text"},n.get("title"))),f.default.createElement(E,{collapsed:r>i,collapsedContent:"[...]"},"[",f.default.createElement("span",null,f.default.createElement(k,u({},this.props,{schema:o,required:!1}))),"]",a.size?f.default.createElement("span",null,a.entrySeq().map(function(e){var t=c(e,2),n=t[0],r=t[1];return f.default.createElement("span",{key:n+"-"+r,style:g},f.default.createElement("br",null),n+":",String(r))}),f.default.createElement("br",null)):null),t&&f.default.createElement("span",{style:{color:"red"}},"*"))}}]),t}(p.Component);w.propTypes={schema:p.PropTypes.object.isRequired,getComponent:p.PropTypes.func.isRequired,specSelectors:p.PropTypes.object.isRequired,name:p.PropTypes.string,required:p.PropTypes.bool,expandDepth:p.PropTypes.number,depth:p.PropTypes.number};var k=function(e){function t(){var e,n,r,i;o(this,t);for(var s=arguments.length,u=Array(s),c=0;c=55296&&e<=57343)&&(!(e>=64976&&e<=65007)&&(65535!==(65535&e)&&65534!==(65535&e)&&(!(e>=0&&e<=8)&&(11!==e&&(!(e>=14&&e<=31)&&(!(e>=127&&e<=159)&&!(e>1114111)))))))}function c(e){if(e>65535){e-=65536;var t=55296+(e>>10),n=56320+(1023&e);return String.fromCharCode(t,n)}return String.fromCharCode(e)}function l(e,t){var n=0;return o(g,t)?g[t]:35===t.charCodeAt(0)&&v.test(t)&&(n="x"===t[1].toLowerCase()?parseInt(t.slice(2),16):parseInt(t.slice(1),10),u(n))?c(n):e}function p(e){return e.indexOf("&")<0?e:e.replace(y,l)}function f(e){return x[e]}function h(e){return _.test(e)?e.replace(b,f):e}var d=Object.prototype.hasOwnProperty,m=/\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g,y=/&([a-z#][a-z0-9]{1,31});/gi,v=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i,g=n(1283),_=/[&<>"]/,b=/[&<>"]/g,x={"&":"&","<":"<",">":">",'"':"""};t.assign=a,t.isString=i,t.has=o,t.unescapeMd=s,t.isValidEntityCode=u,t.fromCodePoint=c,t.replaceEntities=p,t.escapeHtml=h},function(e,t){"use strict";e.exports={Aacute:"Á",aacute:"á",Abreve:"Ă",abreve:"ă",ac:"∾",acd:"∿",acE:"∾̳",Acirc:"Â",acirc:"â",acute:"´",Acy:"А",acy:"а",AElig:"Æ",aelig:"æ",af:"⁡",Afr:"𝔄",afr:"𝔞",Agrave:"À",agrave:"à",alefsym:"ℵ",aleph:"ℵ",Alpha:"Α",alpha:"α",Amacr:"Ā",amacr:"ā",amalg:"⨿",AMP:"&",amp:"&",And:"⩓",and:"∧",andand:"⩕",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsd:"∡",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"Å",angzarr:"⍼",Aogon:"Ą",aogon:"ą",Aopf:"𝔸",aopf:"𝕒",ap:"≈",apacir:"⩯",apE:"⩰",ape:"≊",apid:"≋",apos:"'",ApplyFunction:"⁡",approx:"≈",approxeq:"≊",Aring:"Å",aring:"å",Ascr:"𝒜",ascr:"𝒶",Assign:"≔",ast:"*",asymp:"≈",asympeq:"≍",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",awconint:"∳",awint:"⨑",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",Backslash:"∖",Barv:"⫧",barvee:"⊽",Barwed:"⌆",barwed:"⌅",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",Bcy:"Б",bcy:"б",bdquo:"„",becaus:"∵",Because:"∵",because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",Bernoullis:"ℬ",Beta:"Β",beta:"β",beth:"ℶ",between:"≬",Bfr:"𝔅",bfr:"𝔟",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bNot:"⫭",bnot:"⌐",Bopf:"𝔹",bopf:"𝕓",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxbox:"⧉",boxDL:"╗",boxDl:"╖",boxdL:"╕",boxdl:"┐",boxDR:"╔",boxDr:"╓",boxdR:"╒",boxdr:"┌",boxH:"═",boxh:"─",boxHD:"╦",boxHd:"╤",boxhD:"╥",boxhd:"┬",boxHU:"╩",boxHu:"╧",boxhU:"╨",boxhu:"┴",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxUL:"╝",boxUl:"╜",boxuL:"╛",boxul:"┘",boxUR:"╚",boxUr:"╙",boxuR:"╘",boxur:"└",boxV:"║",boxv:"│",boxVH:"╬",boxVh:"╫",boxvH:"╪",boxvh:"┼",boxVL:"╣",boxVl:"╢",boxvL:"╡",boxvl:"┤",boxVR:"╠",boxVr:"╟",boxvR:"╞",boxvr:"├",bprime:"‵",Breve:"˘",breve:"˘",brvbar:"¦",Bscr:"ℬ",bscr:"𝒷",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsol:"\\",bsolb:"⧅",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",Bumpeq:"≎",bumpeq:"≏",Cacute:"Ć",cacute:"ć",Cap:"⋒",cap:"∩",capand:"⩄",capbrcup:"⩉",capcap:"⩋",capcup:"⩇",capdot:"⩀",CapitalDifferentialD:"ⅅ",caps:"∩︀",caret:"⁁",caron:"ˇ",Cayleys:"ℭ",ccaps:"⩍",Ccaron:"Č",ccaron:"č",Ccedil:"Ç",ccedil:"ç",Ccirc:"Ĉ",ccirc:"ĉ",Cconint:"∰",ccups:"⩌",ccupssm:"⩐",Cdot:"Ċ",cdot:"ċ",cedil:"¸",Cedilla:"¸",cemptyv:"⦲",cent:"¢",CenterDot:"·",centerdot:"·",Cfr:"ℭ",cfr:"𝔠",CHcy:"Ч",chcy:"ч",check:"✓",checkmark:"✓",Chi:"Χ",chi:"χ",cir:"○",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",CircleDot:"⊙",circledR:"®",circledS:"Ⓢ",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",cirE:"⧃",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",clubs:"♣",clubsuit:"♣",Colon:"∷",colon:":",Colone:"⩴",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",Congruent:"≡",Conint:"∯",conint:"∮",ContourIntegral:"∮",Copf:"ℂ",copf:"𝕔",coprod:"∐",Coproduct:"∐",COPY:"©",copy:"©",copysr:"℗",CounterClockwiseContourIntegral:"∳",crarr:"↵",Cross:"⨯",cross:"✗",Cscr:"𝒞",cscr:"𝒸",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",Cup:"⋓",cup:"∪",cupbrcap:"⩈",CupCap:"≍",cupcap:"⩆",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",Dagger:"‡",dagger:"†",daleth:"ℸ",Darr:"↡",dArr:"⇓",darr:"↓",dash:"‐",Dashv:"⫤",dashv:"⊣",dbkarow:"⤏",dblac:"˝",Dcaron:"Ď",dcaron:"ď",Dcy:"Д",dcy:"д",DD:"ⅅ",dd:"ⅆ",ddagger:"‡",ddarr:"⇊",DDotrahd:"⤑",ddotseq:"⩷",deg:"°",Del:"∇",Delta:"Δ",delta:"δ",demptyv:"⦱",dfisht:"⥿",Dfr:"𝔇",dfr:"𝔡",dHar:"⥥",dharl:"⇃",dharr:"⇂",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",diam:"⋄",Diamond:"⋄",diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",DifferentialD:"ⅆ",digamma:"ϝ",disin:"⋲",div:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",DJcy:"Ђ",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",Dopf:"𝔻",dopf:"𝕕",Dot:"¨",dot:"˙",DotDot:"⃜",doteq:"≐",doteqdot:"≑",DotEqual:"≐",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrow:"↓",Downarrow:"⇓",downarrow:"↓",DownArrowBar:"⤓",DownArrowUpArrow:"⇵",DownBreve:"̑",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVector:"↽",DownLeftVectorBar:"⥖",DownRightTeeVector:"⥟",DownRightVector:"⇁",DownRightVectorBar:"⥗",DownTee:"⊤",DownTeeArrow:"↧",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",Dscr:"𝒟",dscr:"𝒹",DScy:"Ѕ",dscy:"ѕ",dsol:"⧶",Dstrok:"Đ",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",DZcy:"Џ",dzcy:"џ",dzigrarr:"⟿",Eacute:"É",eacute:"é",easter:"⩮",Ecaron:"Ě",ecaron:"ě",ecir:"≖",Ecirc:"Ê",ecirc:"ê",ecolon:"≕",Ecy:"Э",ecy:"э",eDDot:"⩷",Edot:"Ė",eDot:"≑",edot:"ė",ee:"ⅇ",efDot:"≒",Efr:"𝔈",efr:"𝔢",eg:"⪚",Egrave:"È",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",Element:"∈",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",Emacr:"Ē",emacr:"ē",empty:"∅",emptyset:"∅",EmptySmallSquare:"◻",emptyv:"∅",EmptyVerySmallSquare:"▫",emsp:" ",emsp13:" ",emsp14:" ",ENG:"Ŋ",eng:"ŋ",ensp:" ",Eogon:"Ę",eogon:"ę",Eopf:"𝔼",eopf:"𝕖",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",Epsilon:"Ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",Equal:"⩵",equals:"=",EqualTilde:"≂",equest:"≟",Equilibrium:"⇌",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erarr:"⥱",erDot:"≓",Escr:"ℰ",escr:"ℯ",esdot:"≐",Esim:"⩳",esim:"≂",Eta:"Η",eta:"η",ETH:"Ð",eth:"ð",Euml:"Ë",euml:"ë",euro:"€",excl:"!",exist:"∃",Exists:"∃",expectation:"ℰ",ExponentialE:"ⅇ",exponentiale:"ⅇ",fallingdotseq:"≒",Fcy:"Ф",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",Ffr:"𝔉",ffr:"𝔣",filig:"fi",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",Fopf:"𝔽",fopf:"𝕗",ForAll:"∀",forall:"∀",fork:"⋔",forkv:"⫙",Fouriertrf:"ℱ",fpartint:"⨍",frac12:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",Fscr:"ℱ",fscr:"𝒻",gacute:"ǵ",Gamma:"Γ",gamma:"γ",Gammad:"Ϝ",gammad:"ϝ",gap:"⪆",Gbreve:"Ğ",gbreve:"ğ",Gcedil:"Ģ",Gcirc:"Ĝ",gcirc:"ĝ",Gcy:"Г",gcy:"г",Gdot:"Ġ",gdot:"ġ",gE:"≧",ge:"≥",gEl:"⪌",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",ges:"⩾",gescc:"⪩",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",Gfr:"𝔊",gfr:"𝔤",Gg:"⋙",gg:"≫",ggg:"⋙",gimel:"ℷ",GJcy:"Ѓ",gjcy:"ѓ",gl:"≷",gla:"⪥",glE:"⪒",glj:"⪤",gnap:"⪊",gnapprox:"⪊",gnE:"≩",gne:"⪈",gneq:"⪈",gneqq:"≩",gnsim:"⋧",Gopf:"𝔾",gopf:"𝕘",grave:"`",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"𝒢",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",GT:">",Gt:"≫",gt:">",gtcc:"⪧",gtcir:"⩺",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",Hacek:"ˇ",hairsp:" ",half:"½",hamilt:"ℋ",HARDcy:"Ъ",hardcy:"ъ",hArr:"⇔",harr:"↔",harrcir:"⥈",harrw:"↭",Hat:"^",hbar:"ℏ",Hcirc:"Ĥ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",Hfr:"ℌ",hfr:"𝔥",HilbertSpace:"ℋ",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",Hopf:"ℍ",hopf:"𝕙",horbar:"―",HorizontalLine:"─",Hscr:"ℋ",hscr:"𝒽",hslash:"ℏ",Hstrok:"Ħ",hstrok:"ħ",HumpDownHump:"≎",HumpEqual:"≏",hybull:"⁃",hyphen:"‐",Iacute:"Í",iacute:"í",ic:"⁣",Icirc:"Î",icirc:"î",Icy:"И",icy:"и",Idot:"İ",IEcy:"Е",iecy:"е",iexcl:"¡",iff:"⇔",Ifr:"ℑ",ifr:"𝔦",Igrave:"Ì",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",IJlig:"IJ",ijlig:"ij",Im:"ℑ",Imacr:"Ī",imacr:"ī",image:"ℑ",ImaginaryI:"ⅈ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",imof:"⊷",imped:"Ƶ",Implies:"⇒",in:"∈",incare:"℅",infin:"∞",infintie:"⧝",inodot:"ı",Int:"∬",int:"∫",intcal:"⊺",integers:"ℤ",Integral:"∫",intercal:"⊺",Intersection:"⋂",intlarhk:"⨗",intprod:"⨼",InvisibleComma:"⁣",InvisibleTimes:"⁢",IOcy:"Ё",iocy:"ё",Iogon:"Į",iogon:"į",Iopf:"𝕀",iopf:"𝕚",Iota:"Ι",iota:"ι",iprod:"⨼",iquest:"¿",Iscr:"ℐ",iscr:"𝒾",isin:"∈",isindot:"⋵",isinE:"⋹",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"⁢",Itilde:"Ĩ",itilde:"ĩ",Iukcy:"І",iukcy:"і",Iuml:"Ï",iuml:"ï",Jcirc:"Ĵ",jcirc:"ĵ",Jcy:"Й",jcy:"й",Jfr:"𝔍",jfr:"𝔧",jmath:"ȷ",Jopf:"𝕁",jopf:"𝕛",Jscr:"𝒥",jscr:"𝒿",Jsercy:"Ј",jsercy:"ј",Jukcy:"Є",jukcy:"є",Kappa:"Κ",kappa:"κ",kappav:"ϰ",Kcedil:"Ķ",kcedil:"ķ",Kcy:"К",kcy:"к",Kfr:"𝔎",kfr:"𝔨",kgreen:"ĸ",KHcy:"Х",khcy:"х",KJcy:"Ќ",kjcy:"ќ",Kopf:"𝕂",kopf:"𝕜",Kscr:"𝒦",kscr:"𝓀",lAarr:"⇚",Lacute:"Ĺ",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",Lambda:"Λ",lambda:"λ",Lang:"⟪",lang:"⟨",langd:"⦑",langle:"⟨",lap:"⪅",Laplacetrf:"ℒ",laquo:"«",Larr:"↞",lArr:"⇐",larr:"←",larrb:"⇤",larrbfs:"⤟",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",lat:"⪫",lAtail:"⤛",latail:"⤙",late:"⪭",lates:"⪭︀",lBarr:"⤎",lbarr:"⤌",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",Lcaron:"Ľ",lcaron:"ľ",Lcedil:"Ļ",lcedil:"ļ",lceil:"⌈",lcub:"{",Lcy:"Л",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",lE:"≦",le:"≤",LeftAngleBracket:"⟨",LeftArrow:"←",Leftarrow:"⇐",leftarrow:"←",LeftArrowBar:"⇤",LeftArrowRightArrow:"⇆",leftarrowtail:"↢",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVector:"⇃",LeftDownVectorBar:"⥙",LeftFloor:"⌊",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",LeftRightArrow:"↔",Leftrightarrow:"⇔",leftrightarrow:"↔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",LeftRightVector:"⥎",LeftTee:"⊣",LeftTeeArrow:"↤",LeftTeeVector:"⥚",leftthreetimes:"⋋",LeftTriangle:"⊲",LeftTriangleBar:"⧏",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVector:"↿",LeftUpVectorBar:"⥘",LeftVector:"↼",LeftVectorBar:"⥒",lEg:"⪋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",les:"⩽",lescc:"⪨",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",lessgtr:"≶",LessLess:"⪡",lesssim:"≲",LessSlantEqual:"⩽",LessTilde:"≲",lfisht:"⥼",lfloor:"⌊",Lfr:"𝔏",lfr:"𝔩",lg:"≶",lgE:"⪑",lHar:"⥢",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",LJcy:"Љ",ljcy:"љ",Ll:"⋘",ll:"≪",llarr:"⇇",llcorner:"⌞",Lleftarrow:"⇚",llhard:"⥫",lltri:"◺",Lmidot:"Ŀ",lmidot:"ŀ",lmoust:"⎰",lmoustache:"⎰",lnap:"⪉",lnapprox:"⪉",lnE:"≨",lne:"⪇",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",LongLeftArrow:"⟵",Longleftarrow:"⟸",longleftarrow:"⟵",LongLeftRightArrow:"⟷",Longleftrightarrow:"⟺",longleftrightarrow:"⟷",longmapsto:"⟼",LongRightArrow:"⟶",Longrightarrow:"⟹",longrightarrow:"⟶",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",Lopf:"𝕃",lopf:"𝕝",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",LowerLeftArrow:"↙",LowerRightArrow:"↘",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"‎",lrtri:"⊿",lsaquo:"‹",Lscr:"ℒ",lscr:"𝓁",Lsh:"↰",lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",Lstrok:"Ł",lstrok:"ł",LT:"<",Lt:"≪",lt:"<",ltcc:"⪦",ltcir:"⩹",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltri:"◃",ltrie:"⊴",ltrif:"◂",ltrPar:"⦖",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",macr:"¯",male:"♂",malt:"✠",maltese:"✠",Map:"⤅",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",Mcy:"М",mcy:"м",mdash:"—",mDDot:"∺",measuredangle:"∡",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"𝔐",mfr:"𝔪",mho:"℧",micro:"µ",mid:"∣",midast:"*",midcir:"⫰",middot:"·",minus:"−",minusb:"⊟",minusd:"∸",minusdu:"⨪",MinusPlus:"∓",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",Mopf:"𝕄",mopf:"𝕞",mp:"∓",Mscr:"ℳ",mscr:"𝓂",mstpos:"∾",Mu:"Μ",mu:"μ",multimap:"⊸",mumap:"⊸",nabla:"∇",Nacute:"Ń",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natur:"♮",natural:"♮",naturals:"ℕ",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",Ncaron:"Ň",ncaron:"ň",Ncedil:"Ņ",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",Ncy:"Н",ncy:"н",ndash:"–",ne:"≠",nearhk:"⤤",neArr:"⇗",nearr:"↗",nearrow:"↗",nedot:"≐̸",NegativeMediumSpace:"​",NegativeThickSpace:"​",NegativeThinSpace:"​",NegativeVeryThinSpace:"​",nequiv:"≢",nesear:"⤨",nesim:"≂̸",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:"\n",nexist:"∄",nexists:"∄",Nfr:"𝔑",nfr:"𝔫",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",nGg:"⋙̸",ngsim:"≵",nGt:"≫⃒",ngt:"≯",ngtr:"≯",nGtv:"≫̸",nhArr:"⇎",nharr:"↮",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",NJcy:"Њ",njcy:"њ",nlArr:"⇍",nlarr:"↚",nldr:"‥",nlE:"≦̸",nle:"≰",nLeftarrow:"⇍",nleftarrow:"↚",nLeftrightarrow:"⇎",nleftrightarrow:"↮",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nLl:"⋘̸",nlsim:"≴",nLt:"≪⃒",nlt:"≮",nltri:"⋪",nltrie:"⋬",nLtv:"≪̸",nmid:"∤",NoBreak:"⁠",NonBreakingSpace:" ",Nopf:"ℕ",nopf:"𝕟",Not:"⫬",not:"¬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",notin:"∉",notindot:"⋵̸",notinE:"⋹̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",NotLeftTriangle:"⋪",NotLeftTriangleBar:"⧏̸",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangle:"⋫",NotRightTriangleBar:"⧐̸",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",npar:"∦",nparallel:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",npre:"⪯̸",nprec:"⊀",npreceq:"⪯̸",nrArr:"⇏",nrarr:"↛",nrarrc:"⤳̸",nrarrw:"↝̸",nRightarrow:"⇏",nrightarrow:"↛",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",Nscr:"𝒩",nscr:"𝓃",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",Ntilde:"Ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",Nu:"Ν",nu:"ν",num:"#",numero:"№",numsp:" ",nvap:"≍⃒",nVDash:"⊯",nVdash:"⊮",nvDash:"⊭",nvdash:"⊬",nvge:"≥⃒",nvgt:">⃒",nvHarr:"⤄",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwarhk:"⤣",nwArr:"⇖",nwarr:"↖",nwarrow:"↖",nwnear:"⤧",Oacute:"Ó",oacute:"ó",oast:"⊛",ocir:"⊚",Ocirc:"Ô",ocirc:"ô",Ocy:"О",ocy:"о",odash:"⊝",Odblac:"Ő",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",OElig:"Œ",oelig:"œ",ofcir:"⦿",Ofr:"𝔒",ofr:"𝔬",ogon:"˛",Ograve:"Ò",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",Omacr:"Ō",omacr:"ō",Omega:"Ω",omega:"ω",Omicron:"Ο",omicron:"ο",omid:"⦶",ominus:"⊖",Oopf:"𝕆",oopf:"𝕠",opar:"⦷",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",operp:"⦹",oplus:"⊕",Or:"⩔",or:"∨",orarr:"↻",ord:"⩝",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oS:"Ⓢ",Oscr:"𝒪",oscr:"ℴ",Oslash:"Ø",oslash:"ø",osol:"⊘",Otilde:"Õ",otilde:"õ",Otimes:"⨷",otimes:"⊗",otimesas:"⨶",Ouml:"Ö",ouml:"ö",ovbar:"⌽",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",par:"∥",para:"¶",parallel:"∥",parsim:"⫳",parsl:"⫽",part:"∂",PartialD:"∂",Pcy:"П",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",Pfr:"𝔓",pfr:"𝔭",Phi:"Φ",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",Pi:"Π",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plus:"+",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plusdo:"∔",plusdu:"⨥",pluse:"⩲",PlusMinus:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",Poincareplane:"ℌ",pointint:"⨕",Popf:"ℙ",popf:"𝕡",pound:"£",Pr:"⪻",pr:"≺",prap:"⪷",prcue:"≼",prE:"⪳",pre:"⪯",prec:"≺",precapprox:"⪷",preccurlyeq:"≼",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",precsim:"≾",Prime:"″",prime:"′",primes:"ℙ",prnap:"⪹",prnE:"⪵",prnsim:"⋨",prod:"∏",Product:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",Proportion:"∷",Proportional:"∝",propto:"∝",prsim:"≾",prurel:"⊰",Pscr:"𝒫",pscr:"𝓅",Psi:"Ψ",psi:"ψ",puncsp:" ",Qfr:"𝔔",qfr:"𝔮",qint:"⨌",Qopf:"ℚ",qopf:"𝕢",qprime:"⁗",Qscr:"𝒬",qscr:"𝓆",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",QUOT:'"',quot:'"',rAarr:"⇛",race:"∽̱",Racute:"Ŕ",racute:"ŕ",radic:"√",raemptyv:"⦳",Rang:"⟫",rang:"⟩",rangd:"⦒",range:"⦥",rangle:"⟩",raquo:"»",Rarr:"↠",rArr:"⇒",rarr:"→",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",Rarrtl:"⤖",rarrtl:"↣",rarrw:"↝",rAtail:"⤜",ratail:"⤚",ratio:"∶",rationals:"ℚ",RBarr:"⤐",rBarr:"⤏",rbarr:"⤍",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",Rcaron:"Ř",rcaron:"ř",Rcedil:"Ŗ",rcedil:"ŗ",rceil:"⌉",rcub:"}",Rcy:"Р",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",Re:"ℜ",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",rect:"▭",REG:"®",reg:"®",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",rfisht:"⥽",rfloor:"⌋",Rfr:"ℜ",rfr:"𝔯",rHar:"⥤",rhard:"⇁",rharu:"⇀",rharul:"⥬",Rho:"Ρ",rho:"ρ",rhov:"ϱ",RightAngleBracket:"⟩",RightArrow:"→",Rightarrow:"⇒",rightarrow:"→",RightArrowBar:"⇥",RightArrowLeftArrow:"⇄",rightarrowtail:"↣",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVector:"⇂",RightDownVectorBar:"⥕",RightFloor:"⌋",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",RightTee:"⊢",RightTeeArrow:"↦",RightTeeVector:"⥛",rightthreetimes:"⋌",RightTriangle:"⊳",RightTriangleBar:"⧐",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVector:"↾",RightUpVectorBar:"⥔",RightVector:"⇀",RightVectorBar:"⥓",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"‏",rmoust:"⎱",rmoustache:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",Ropf:"ℝ",ropf:"𝕣",roplus:"⨮",rotimes:"⨵",RoundImplies:"⥰",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",Rrightarrow:"⇛",rsaquo:"›",Rscr:"ℛ",rscr:"𝓇",Rsh:"↱",rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",RuleDelayed:"⧴",ruluhar:"⥨",rx:"℞",Sacute:"Ś",sacute:"ś",sbquo:"‚",Sc:"⪼",sc:"≻",scap:"⪸",Scaron:"Š",scaron:"š",sccue:"≽",scE:"⪴",sce:"⪰",Scedil:"Ş",scedil:"ş",Scirc:"Ŝ",scirc:"ŝ",scnap:"⪺",scnE:"⪶",scnsim:"⋩",scpolint:"⨓",scsim:"≿",Scy:"С",scy:"с",sdot:"⋅",sdotb:"⊡",sdote:"⩦",searhk:"⤥",seArr:"⇘",searr:"↘",searrow:"↘",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",Sfr:"𝔖",sfr:"𝔰",sfrown:"⌢",sharp:"♯",SHCHcy:"Щ",shchcy:"щ",SHcy:"Ш",shcy:"ш",ShortDownArrow:"↓",ShortLeftArrow:"←",shortmid:"∣",shortparallel:"∥",ShortRightArrow:"→",ShortUpArrow:"↑",shy:"­",Sigma:"Σ",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",SmallCircle:"∘",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",SOFTcy:"Ь",softcy:"ь",sol:"/",solb:"⧄",solbar:"⌿",Sopf:"𝕊",sopf:"𝕤",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",Sqrt:"√",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",squ:"□",Square:"□",square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",squarf:"▪",squf:"▪",srarr:"→",Sscr:"𝒮",sscr:"𝓈",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",Star:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",Sub:"⋐",sub:"⊂",subdot:"⪽",subE:"⫅",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",Subset:"⋐",subset:"⊂",subseteq:"⊆",subseteqq:"⫅",SubsetEqual:"⊆",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succ:"≻",succapprox:"⪸",succcurlyeq:"≽",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",SuchThat:"∋",Sum:"∑",sum:"∑",sung:"♪",Sup:"⋑",sup:"⊃",sup1:"¹",sup2:"²",sup3:"³",supdot:"⪾",supdsub:"⫘",supE:"⫆",supe:"⊇",supedot:"⫄",Superset:"⊃",SupersetEqual:"⊇",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",Supset:"⋑",supset:"⊃",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swarhk:"⤦",swArr:"⇙",swarr:"↙",swarrow:"↙",swnwar:"⤪",szlig:"ß",Tab:"\t",target:"⌖",Tau:"Τ",tau:"τ",tbrk:"⎴",Tcaron:"Ť",tcaron:"ť",Tcedil:"Ţ",tcedil:"ţ",Tcy:"Т",tcy:"т",tdot:"⃛",telrec:"⌕",Tfr:"𝔗",tfr:"𝔱",there4:"∴",Therefore:"∴",therefore:"∴",Theta:"Θ",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",ThickSpace:"  ",thinsp:" ",ThinSpace:" ",thkap:"≈",thksim:"∼",THORN:"Þ",thorn:"þ",Tilde:"∼",tilde:"˜",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",times:"×",timesb:"⊠",timesbar:"⨱",timesd:"⨰",tint:"∭",toea:"⤨",top:"⊤",topbot:"⌶",topcir:"⫱",Topf:"𝕋",topf:"𝕥",topfork:"⫚",tosa:"⤩",tprime:"‴",TRADE:"™",trade:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",TripleDot:"⃛",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",Tscr:"𝒯",tscr:"𝓉",TScy:"Ц",tscy:"ц",TSHcy:"Ћ",tshcy:"ћ",Tstrok:"Ŧ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",Uacute:"Ú",uacute:"ú",Uarr:"↟",uArr:"⇑",uarr:"↑",Uarrocir:"⥉",Ubrcy:"Ў",ubrcy:"ў",Ubreve:"Ŭ",ubreve:"ŭ",Ucirc:"Û",ucirc:"û",Ucy:"У",ucy:"у",udarr:"⇅",Udblac:"Ű",udblac:"ű",udhar:"⥮",ufisht:"⥾",Ufr:"𝔘",ufr:"𝔲",Ugrave:"Ù",ugrave:"ù",uHar:"⥣",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",Umacr:"Ū",umacr:"ū",uml:"¨",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",uogon:"ų",Uopf:"𝕌",uopf:"𝕦",UpArrow:"↑",Uparrow:"⇑",uparrow:"↑",UpArrowBar:"⤒",UpArrowDownArrow:"⇅",UpDownArrow:"↕",Updownarrow:"⇕",updownarrow:"↕",UpEquilibrium:"⥮",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",UpperLeftArrow:"↖",UpperRightArrow:"↗",Upsi:"ϒ",upsi:"υ",upsih:"ϒ",Upsilon:"Υ",upsilon:"υ",UpTee:"⊥",UpTeeArrow:"↥",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",Uring:"Ů",uring:"ů",urtri:"◹",Uscr:"𝒰",uscr:"𝓊",utdot:"⋰",Utilde:"Ũ",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",Uuml:"Ü",uuml:"ü",uwangle:"⦧",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",vArr:"⇕",varr:"↕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",Vbar:"⫫",vBar:"⫨",vBarv:"⫩",Vcy:"В",vcy:"в",VDash:"⊫",Vdash:"⊩",vDash:"⊨",vdash:"⊢",Vdashl:"⫦",Vee:"⋁",vee:"∨",veebar:"⊻",veeeq:"≚",vellip:"⋮",Verbar:"‖",verbar:"|",Vert:"‖",vert:"|",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"𝔙",vfr:"𝔳",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",Vopf:"𝕍",vopf:"𝕧",vprop:"∝",vrtri:"⊳",Vscr:"𝒱",vscr:"𝓋",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",Vvdash:"⊪",vzigzag:"⦚",Wcirc:"Ŵ",wcirc:"ŵ",wedbar:"⩟",Wedge:"⋀",wedge:"∧",wedgeq:"≙",weierp:"℘",Wfr:"𝔚",wfr:"𝔴",Wopf:"𝕎",wopf:"𝕨",wp:"℘",wr:"≀",wreath:"≀",Wscr:"𝒲",wscr:"𝓌",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",Xfr:"𝔛",xfr:"𝔵",xhArr:"⟺",xharr:"⟷",Xi:"Ξ",xi:"ξ",xlArr:"⟸",xlarr:"⟵",xmap:"⟼",xnis:"⋻",xodot:"⨀",Xopf:"𝕏",xopf:"𝕩",xoplus:"⨁",xotime:"⨂",xrArr:"⟹",xrarr:"⟶",Xscr:"𝒳",xscr:"𝓍",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",Yacute:"Ý",yacute:"ý",YAcy:"Я",yacy:"я",Ycirc:"Ŷ",ycirc:"ŷ",Ycy:"Ы",ycy:"ы",yen:"¥",Yfr:"𝔜",yfr:"𝔶",YIcy:"Ї",yicy:"ї",Yopf:"𝕐",yopf:"𝕪",Yscr:"𝒴",yscr:"𝓎",YUcy:"Ю",yucy:"ю",Yuml:"Ÿ",yuml:"ÿ",Zacute:"Ź",zacute:"ź",Zcaron:"Ž",zcaron:"ž",Zcy:"З",zcy:"з",Zdot:"Ż",zdot:"ż",zeetrf:"ℨ",ZeroWidthSpace:"​",Zeta:"Ζ",zeta:"ζ",Zfr:"ℨ",zfr:"𝔷",ZHcy:"Ж",zhcy:"ж",zigrarr:"⇝",Zopf:"ℤ",zopf:"𝕫",Zscr:"𝒵",zscr:"𝓏",zwj:"‍",zwnj:"‌"}},function(e,t,n){"use strict";function r(){this.rules=i.assign({},o),this.getBreak=o.getBreak}var i=n(1282),o=n(1285);e.exports=r,r.prototype.renderInline=function(e,t,n){for(var r=this.rules,i=e.length,o=0,a="";i--;)a+=r[e[o].type](e,o++,t,n,this);return a},r.prototype.render=function(e,t,n){for(var r=this.rules,i=e.length,o=-1,a="";++o=e.length-2?t:"paragraph_open"===e[t].type&&e[t].tight&&"inline"===e[t+1].type&&0===e[t+1].content.length&&"paragraph_close"===e[t+2].type&&e[t+2].tight?r(e,t+2):t}var i=n(1282).has,o=n(1282).unescapeMd,a=n(1282).replaceEntities,s=n(1282).escapeHtml,u={};u.blockquote_open=function(){return"
\n"},u.blockquote_close=function(e,t){return"
"+c(e,t)},u.code=function(e,t){return e[t].block?"
"+s(e[t].content)+"
"+c(e,t):""+s(e[t].content)+""},u.fence=function(e,t,n,r,u){var l,p,f,h=e[t],d="",m=n.langPrefix,y="";if(h.params){if(l=h.params.split(/\s+/g),p=l.join(" "),i(u.rules.fence_custom,l[0]))return u.rules.fence_custom[l[0]](e,t,n,r,u);y=s(a(o(p))),d=' class="'+m+y+'"'}return f=n.highlight?n.highlight.apply(n.highlight,[h.content].concat(l))||s(h.content):s(h.content),"
"+f+"
"+c(e,t)},u.fence_custom={},u.heading_open=function(e,t){return""},u.heading_close=function(e,t){return"\n"},u.hr=function(e,t,n){return(n.xhtmlOut?"
":"
")+c(e,t)},u.bullet_list_open=function(){return"
    \n"},u.bullet_list_close=function(e,t){return"
"+c(e,t)},u.list_item_open=function(){return"
  • "},u.list_item_close=function(){return"
  • \n"},u.ordered_list_open=function(e,t){var n=e[t],r=n.order>1?' start="'+n.order+'"':"";return"\n"},u.ordered_list_close=function(e,t){return""+c(e,t)},u.paragraph_open=function(e,t){return e[t].tight?"":"

    "},u.paragraph_close=function(e,t){var n=!(e[t].tight&&t&&"inline"===e[t-1].type&&!e[t-1].content);return(e[t].tight?"":"

    ")+(n?c(e,t):"")},u.link_open=function(e,t,n){var r=e[t].title?' title="'+s(a(e[t].title))+'"':"",i=n.linkTarget?' target="'+n.linkTarget+'"':"";return'"},u.link_close=function(){return""},u.image=function(e,t,n){var r=' src="'+s(e[t].src)+'"',i=e[t].title?' title="'+s(a(e[t].title))+'"':"",u=' alt="'+(e[t].alt?s(a(o(e[t].alt))):"")+'"',c=n.xhtmlOut?" /":"";return""},u.table_open=function(){return"\n"},u.table_close=function(){return"
    \n"},u.thead_open=function(){return"\n"},u.thead_close=function(){return"\n"},u.tbody_open=function(){return"\n"},u.tbody_close=function(){return"\n"},u.tr_open=function(){return""},u.tr_close=function(){return"\n"},u.th_open=function(e,t){var n=e[t];return""},u.th_close=function(){return""},u.td_open=function(e,t){var n=e[t];return""},u.td_close=function(){return""},u.strong_open=function(){return""},u.strong_close=function(){return""},u.em_open=function(){return""},u.em_close=function(){return""},u.del_open=function(){return""},u.del_close=function(){return""},u.ins_open=function(){return""},u.ins_close=function(){return""},u.mark_open=function(){return""},u.mark_close=function(){return""},u.sub=function(e,t){return""+s(e[t].content)+""},u.sup=function(e,t){return""+s(e[t].content)+""},u.hardbreak=function(e,t,n){return n.xhtmlOut?"
    \n":"
    \n"},u.softbreak=function(e,t,n){return n.breaks?n.xhtmlOut?"
    \n":"
    \n":"\n"},u.text=function(e,t){return s(e[t].content)},u.htmlblock=function(e,t){return e[t].content},u.htmltag=function(e,t){return e[t].content},u.abbr_open=function(e,t){return''},u.abbr_close=function(){return""},u.footnote_ref=function(e,t){var n=Number(e[t].id+1).toString(),r="fnref"+n;return e[t].subId>0&&(r+=":"+e[t].subId),'['+n+"]"},u.footnote_block_open=function(e,t,n){var r=n.xhtmlOut?'
    \n':'
    \n';return r+'
    \n
      \n'},u.footnote_block_close=function(){return"
    \n
    \n"},u.footnote_open=function(e,t){var n=Number(e[t].id+1).toString();return'
  • '},u.footnote_close=function(){return"
  • \n"},u.footnote_anchor=function(e,t){var n=Number(e[t].id+1).toString(),r="fnref"+n;return e[t].subId>0&&(r+=":"+e[t].subId),' '},u.dl_open=function(){return"
    \n"},u.dt_open=function(){return"
    "},u.dd_open=function(){return"
    "},u.dl_close=function(){return"
    \n"},u.dt_close=function(){return"\n"},u.dd_close=function(){ +return"\n"};var c=u.getBreak=function(e,t){return t=r(e,t),t8&&n<14);)if(92===n&&t+11))break;if(41===n&&(o--,o<0))break;t++}return s!==t&&(a=i(e.src.slice(s,t)),!!e.parser.validateLink(a)&&(e.linkContent=a,e.pos=t,!0))}},function(e,t,n){"use strict";var r=n(1282).replaceEntities;e.exports=function(e){var t=r(e);try{t=decodeURI(t)}catch(e){}return encodeURI(t)}},function(e,t,n){"use strict";var r=n(1282).unescapeMd;e.exports=function(e,t){var n,i=t,o=e.posMax,a=e.src.charCodeAt(t);if(34!==a&&39!==a&&40!==a)return!1;for(t++,40===a&&(a=41);t0?a[t].count:1,r=0;r=0;t--)if(s=a[t],"text"===s.type){for(l=0,u=s.content,f.lastIndex=0,p=s.level,c=[];h=f.exec(u);)f.lastIndex>l&&c.push({type:"text",content:u.slice(l,h.index+h[1].length),level:p}),c.push({type:"abbr_open",title:e.env.abbreviations[":"+h[2]],level:p++}),c.push({type:"text",content:h[2],level:p}),c.push({type:"abbr_close",level:--p}),l=f.lastIndex-h[3].length;c.length&&(l=0;s--)if("inline"===e.tokens[s].type)for(a=e.tokens[s].children,t=a.length-1;t>=0;t--)i=a[t],"text"===i.type&&(o=i.content,o=n(o),r.test(o)&&(o=o.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---([^-]|$)/gm,"$1—$2").replace(/(^|\s)--(\s|$)/gm,"$1–$2").replace(/(^|[^-\s])--([^-\s]|$)/gm,"$1–$2")),i.content=o)}},function(e,t){"use strict";function n(e,t){return!(t<0||t>=e.length)&&!a.test(e[t])}function r(e,t,n){return e.substr(0,t)+n+e.substr(t+1)}var i=/['"]/,o=/['"]/g,a=/[-\s()\[\]]/,s="’";e.exports=function(e){var t,a,u,c,l,p,f,h,d,m,y,v,g,_,b,x,w;if(e.options.typographer)for(w=[],b=e.tokens.length-1;b>=0;b--)if("inline"===e.tokens[b].type)for(x=e.tokens[b].children,w.length=0,t=0;t=0&&!(w[g].level<=f);g--);w.length=g+1,u=a.content,l=0,p=u.length;e:for(;l=0&&(m=w[g],!(w[g].level\s]/i.test(e)}function i(e){return/^<\/a\s*>/i.test(e)}function o(){var e=[],t=new a({stripPrefix:!1,url:!0,email:!0,twitter:!1,replaceFn:function(t,n){switch(n.getType()){case"url":e.push({text:n.matchedText,url:n.getUrl()});break;case"email":e.push({text:n.matchedText,url:"mailto:"+n.getEmail().replace(/^mailto:/i,"")})}return!1}});return{links:e,autolinker:t}}var a=n(1303),s=/www|@|\:\/\//;e.exports=function(e){var t,n,a,u,c,l,p,f,h,d,m,y,v,g=e.tokens,_=null;if(e.options.linkify)for(n=0,a=g.length;n=0;t--)if(c=u[t],"link_close"!==c.type){if("htmltag"===c.type&&(r(c.content)&&m>0&&m--,i(c.content)&&m++),!(m>0)&&"text"===c.type&&s.test(c.content)){if(_||(_=o(),y=_.links,v=_.autolinker),l=c.content,y.length=0,v.link(l),!y.length)continue;for(p=[],d=c.level,f=0;f + * MIT Licensed. http://www.opensource.org/licenses/mit-license.php + * + * https://github.com/gregjacobs/Autolinker.js + */ +var e=function(t){e.Util.assign(this,t)};return e.prototype={constructor:e,urls:!0,email:!0,twitter:!0,newWindow:!0,stripPrefix:!0,truncate:void 0,className:"",htmlParser:void 0,matchParser:void 0,tagBuilder:void 0,link:function(e){for(var t=this.getHtmlParser(),n=t.parse(e),r=0,i=[],o=0,a=n.length;ot&&(n=null==n?"..":n,e=e.substring(0,t-n.length)+n),e},indexOf:function(e,t){if(Array.prototype.indexOf)return e.indexOf(t);for(var n=0,r=e.length;n",this.getInnerHtml(),""].join("")},buildAttrsStr:function(){if(!this.attrs)return"";var e=this.getAttrs(),t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n+'="'+e[n]+'"');return t.join(" ")}}),e.AnchorTagBuilder=e.Util.extend(Object,{constructor:function(t){e.Util.assign(this,t)},build:function(t){var n=new e.HtmlTag({tagName:"a",attrs:this.createAttrs(t.getType(),t.getAnchorHref()),innerHtml:this.processAnchorText(t.getAnchorText())});return n},createAttrs:function(e,t){var n={href:t},r=this.createCssClass(e);return r&&(n.class=r),this.newWindow&&(n.target="_blank"),n},createCssClass:function(e){var t=this.className;return t?t+" "+t+"-"+e:""},processAnchorText:function(e){return e=this.doTruncate(e)},doTruncate:function(t){return e.Util.ellipsis(t,this.truncate||Number.POSITIVE_INFINITY)}}),e.htmlParser.HtmlParser=e.Util.extend(Object,{htmlRegex:function(){var e=/[0-9a-zA-Z][0-9a-zA-Z:]*/,t=/[^\s\0"'>\/=\x01-\x1F\x7F]+/,n=/(?:"[^"]*?"|'[^']*?'|[^'"=<>`\s]+)/,r=t.source+"(?:\\s*=\\s*"+n.source+")?";return new RegExp(["(?:","<(!DOCTYPE)","(?:","\\s+","(?:",r,"|",n.source+")",")*",">",")","|","(?:","<(/)?","("+e.source+")","(?:","\\s+",r,")*","\\s*/?",">",")"].join(""),"gi")}(),htmlCharacterEntitiesRegex:/( | |<|<|>|>|"|"|')/gi,parse:function(e){for(var t,n,r=this.htmlRegex,i=0,o=[];null!==(t=r.exec(e));){var a=t[0],s=t[1]||t[3],u=!!t[2],c=e.substring(i,t.index);c&&(n=this.parseTextAndEntityNodes(c),o.push.apply(o,n)),o.push(this.createElementNode(a,s,u)),i=t.index+a.length}if(i=n))&&!(e.tShift[s]=0&&(e=e.replace(s,function(t,n){var r;return 10===e.charCodeAt(n)?(a=n+1,l=0,t):(r=" ".slice((n-a-l)%4),l=n-a+1,r)})),i=new o(e,this,t,n,r),void this.tokenize(i,i.line,i.lineMax)):[]},e.exports=r},function(e,t){"use strict";function n(e,t,n,r,i){var o,a,s,u,c,l,p;for(this.src=e,this.parser=t,this.options=n,this.env=r,this.tokens=i,this.bMarks=[],this.eMarks=[],this.tShift=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.parentType="root",this.ddIndent=-1,this.level=0,this.result="",a=this.src,l=0,p=!1,s=u=l=0,c=a.length;u=this.eMarks[e]},n.prototype.skipEmptyLines=function(e){for(var t=this.lineMax;en;)if(t!==this.src.charCodeAt(--e))return e+1;return e},n.prototype.getLines=function(e,t,n,r){var i,o,a,s,u,c=e;if(e>=t)return"";if(c+1===t)return o=this.bMarks[c]+Math.min(this.tShift[c],n),a=r?this.eMarks[c]+1:this.eMarks[c],this.src.slice(o,a);for(s=new Array(t-e),i=0;cn&&(u=n),u<0&&(u=0),o=this.bMarks[c]+u,a=c+1=4))break;r++,i=r}return e.line=r,e.tokens.push({type:"code",content:e.getLines(t,i,4+e.blkIndent,!0),block:!0,lines:[t,e.line],level:e.level}),!0}},function(e,t){"use strict";e.exports=function(e,t,n,r){var i,o,a,s,u,c=!1,l=e.bMarks[t]+e.tShift[t],p=e.eMarks[t];if(l+3>p)return!1;if(i=e.src.charCodeAt(l),126!==i&&96!==i)return!1;if(u=l,l=e.skipChars(l,i),o=l-u,o<3)return!1;if(a=e.src.slice(l,p).trim(),a.indexOf("`")>=0)return!1;if(r)return!0;for(s=t;(s++,!(s>=n))&&(l=u=e.bMarks[s]+e.tShift[s],p=e.eMarks[s],!(l=4||(l=e.skipChars(l,i),l-uy)return!1;if(62!==e.src.charCodeAt(m++))return!1;if(e.level>=e.options.maxNesting)return!1;if(r)return!0;for(32===e.src.charCodeAt(m)&&m++,u=e.blkIndent,e.blkIndent=0,s=[e.bMarks[t]],e.bMarks[t]=m,m=m=y,a=[e.tShift[t]],e.tShift[t]=m-e.bMarks[t],p=e.parser.ruler.getRules("blockquote"),i=t+1;i=y));i++)if(62!==e.src.charCodeAt(m++)){if(o)break;for(d=!1,f=0,h=p.length;f=y,a.push(e.tShift[i]),e.tShift[i]=m-e.bMarks[i];for(c=e.parentType,e.parentType="blockquote",e.tokens.push({type:"blockquote_open",lines:l=[t,0],level:e.level++}),e.parser.tokenize(e,t,i),e.tokens.push({type:"blockquote_close",level:--e.level}),e.parentType=c,l[1]=e.line,f=0;fu)return!1;if(i=e.src.charCodeAt(s++),42!==i&&45!==i&&95!==i)return!1;for(o=1;s=i?-1:(n=e.src.charCodeAt(r++),42!==n&&45!==n&&43!==n?-1:r=i)return-1;if(n=e.src.charCodeAt(r++),n<48||n>57)return-1;for(;;){if(r>=i)return-1;if(n=e.src.charCodeAt(r++),!(n>=48&&n<=57)){if(41===n||46===n)break;return-1}}return r=0)_=!0;else{if(!((d=n(e,t))>=0))return!1;_=!1}if(e.level>=e.options.maxNesting)return!1;if(g=e.src.charCodeAt(d-1),a)return!0;for(x=e.tokens.length,_?(h=e.bMarks[t]+e.tShift[t],v=Number(e.src.substr(h,d-h-1)),e.tokens.push({type:"ordered_list_open",order:v,lines:k=[t,0],level:e.level++})):e.tokens.push({type:"bullet_list_open",lines:k=[t,0],level:e.level++}),s=t,w=!1,E=e.parser.ruler.getRules("list");!(!(s=m?1:b-d,y>4&&(y=1),y<1&&(y=1),u=d-e.bMarks[s]+y,e.tokens.push({type:"list_item_open",lines:S=[t,0],level:e.level++}),l=e.blkIndent,p=e.tight,c=e.tShift[t],f=e.parentType,e.tShift[t]=b-e.bMarks[t],e.blkIndent=u,e.tight=!0,e.parentType="list",e.parser.tokenize(e,t,o,!0),e.tight&&!w||(O=!1),w=e.line-t>1&&e.isEmpty(e.line-1),e.blkIndent=l,e.tShift[t]=c,e.tight=p,e.parentType=f,e.tokens.push({type:"list_item_close",level:--e.level}),s=t=e.line,S[1]=s,b=e.bMarks[t],s>=o)||e.isEmpty(s)||e.tShift[s]l)return!1;if(91!==e.src.charCodeAt(c))return!1;if(94!==e.src.charCodeAt(c+1))return!1;if(e.level>=e.options.maxNesting)return!1;for(s=c+2;s=l||58!==e.src.charCodeAt(++s))&&(!!r||(s++,e.env.footnotes||(e.env.footnotes={}),e.env.footnotes.refs||(e.env.footnotes.refs={}),u=e.src.slice(c+2,s-2),e.env.footnotes.refs[":"+u]=-1,e.tokens.push({type:"footnote_reference_open",label:u,level:e.level++}),i=e.bMarks[t],o=e.tShift[t],a=e.parentType,e.tShift[t]=e.skipSpaces(s)-s,e.bMarks[t]=s,e.blkIndent+=4,e.parentType="footnote",e.tShift[t]=u)return!1;if(i=e.src.charCodeAt(s),35!==i||s>=u)return!1;for(o=1,i=e.src.charCodeAt(++s);35===i&&s6||ss&&32===e.src.charCodeAt(a-1)&&(u=a),e.line=t+1,e.tokens.push({type:"heading_open",hLevel:o,lines:[t,e.line],level:e.level}),s=n)&&(!(e.tShift[a]3)&&(i=e.bMarks[a]+e.tShift[a],o=e.eMarks[a],!(i>=o)&&(r=e.src.charCodeAt(i),(45===r||61===r)&&(i=e.skipChars(i,r),i=e.skipSpaces(i),!(i=97&&t<=122}var i=n(1315),o=/^<([a-zA-Z]{1,15})[\s\/>]/,a=/^<\/([a-zA-Z]{1,15})[\s>]/;e.exports=function(e,t,n,s){var u,c,l,p=e.bMarks[t],f=e.eMarks[t],h=e.tShift[t];if(p+=h,!e.options.html)return!1;if(h>3||p+2>=f)return!1;if(60!==e.src.charCodeAt(p))return!1;if(u=e.src.charCodeAt(p+1),33===u||63===u){if(s)return!0}else{if(47!==u&&!r(u))return!1;if(47===u){if(c=e.src.slice(p,f).match(a),!c)return!1}else if(c=e.src.slice(p,f).match(o),!c)return!1;if(i[c[1].toLowerCase()]!==!0)return!1;if(s)return!0}for(l=t+1;lr)return!1;if(c=t+1,e.tShift[c]=e.eMarks[c])return!1;if(o=e.src.charCodeAt(s),124!==o&&45!==o&&58!==o)return!1;if(a=n(e,t+1),!/^[-:| ]+$/.test(a))return!1;if(l=a.split("|"),l<=2)return!1;for(f=[],u=0;u=o?-1:(r=e.src.charCodeAt(i++),126!==r&&58!==r?-1:(n=e.skipSpaces(i),i===n?-1:n>=o?-1:n))}function r(e,t){var n,r,i=e.level+2;for(n=t+2,r=e.tokens.length-2;n=0;if(f=t+1,e.isEmpty(f)&&++f>i)return!1;if(e.tShift[f]=e.options.maxNesting)return!1;p=e.tokens.length,e.tokens.push({type:"dl_open",lines:l=[t,0],level:e.level++}),u=t,s=f;e:for(;;){for(_=!0,g=!1,e.tokens.push({type:"dt_open",lines:[u,u],level:e.level++}),e.tokens.push({type:"inline",content:e.getLines(u,u+1,e.blkIndent,!1).trim(),level:e.level+1,lines:[u,u],children:[]}),e.tokens.push({type:"dt_close",level:--e.level});;){if(e.tokens.push({type:"dd_open",lines:c=[f,0],level:e.level++}),v=e.tight,d=e.ddIndent,h=e.blkIndent,y=e.tShift[s],m=e.parentType,e.blkIndent=e.ddIndent=e.tShift[s]+2,e.tShift[s]=a-e.bMarks[s],e.tight=!0,e.parentType="deflist",e.parser.tokenize(e,s,i,!0),e.tight&&!g||(_=!1),g=e.line-s>1&&e.isEmpty(e.line-1),e.tShift[s]=y,e.tight=v,e.parentType=m,e.blkIndent=h,e.ddIndent=d,e.tokens.push({type:"dd_close",level:--e.level}),c[1]=f=e.line,f>=i)break e;if(e.tShift[f]=i)break;if(u=f,e.isEmpty(u))break;if(e.tShift[u]=i)break;if(e.isEmpty(s)&&s++,s>=i)break;if(e.tShift[s]3)){for(i=!1,o=0,a=s.length;o0)return void(e.pos=n);for(t=0;t=o)break}else e.pending+=e.src[e.pos++]}e.pending&&e.pushPending()},r.prototype.parse=function(e,t,n,r){var i=new a(e,this,t,n,r);this.tokenize(i)},e.exports=r},function(e,t){"use strict";function n(e){switch(e){case 10:case 92:case 96:case 42:case 95:case 94:case 91:case 93:case 33:case 38:case 60:case 62:case 123:case 125:case 36:case 37:case 64:case 126:case 43:case 61:case 58:return!0;default:return!1}}e.exports=function(e,t){for(var r=e.pos;r=0&&32===e.pending.charCodeAt(n))if(n>=1&&32===e.pending.charCodeAt(n-1)){for(var o=n-2;o>=0;o--)if(32!==e.pending.charCodeAt(o)){e.pending=e.pending.substring(0,o+1);break}e.push({type:"hardbreak",level:e.level})}else e.pending=e.pending.slice(0,-1),e.push({type:"softbreak",level:e.level});else e.push({type:"softbreak",level:e.level});for(i++;i?@[]^_`{|}~-".split("").forEach(function(e){n[e.charCodeAt(0)]=1}),e.exports=function(e,t){var r,i=e.pos,o=e.posMax;if(92!==e.src.charCodeAt(i))return!1;if(i++,i=s)return!1;if(126!==e.src.charCodeAt(u+1))return!1;if(e.level>=e.options.maxNesting)return!1;if(o=u>0?e.src.charCodeAt(u-1):-1,a=e.src.charCodeAt(u+2),126===o)return!1;if(126===a)return!1;if(32===a||10===a)return!1;for(r=u+2;ru+3)return e.pos+=r-u,t||(e.pending+=e.src.slice(u,r)),!0;for(e.pos=u+2,i=1;e.pos+1=s)return!1;if(43!==e.src.charCodeAt(u+1))return!1;if(e.level>=e.options.maxNesting)return!1; +if(o=u>0?e.src.charCodeAt(u-1):-1,a=e.src.charCodeAt(u+2),43===o)return!1;if(43===a)return!1;if(32===a||10===a)return!1;for(r=u+2;r=s)return!1;if(61!==e.src.charCodeAt(u+1))return!1;if(e.level>=e.options.maxNesting)return!1;if(o=u>0?e.src.charCodeAt(u-1):-1,a=e.src.charCodeAt(u+2),61===o)return!1;if(61===a)return!1;if(32===a||10===a)return!1;for(r=u+2;r=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122}function r(e,t){var r,i,o,a=t,s=!0,u=!0,c=e.posMax,l=e.src.charCodeAt(t);for(r=t>0?e.src.charCodeAt(t-1):-1;a=c&&(s=!1),o=a-t,o>=4?s=u=!1:(i=a=e.options.maxNesting)return!1;for(e.pos=p+n,u=[n];e.pos?@[\]^_`{|}~-])/g;e.exports=function(e,t){var r,i,o=e.posMax,a=e.pos;if(126!==e.src.charCodeAt(a))return!1;if(t)return!1;if(a+2>=o)return!1;if(e.level>=e.options.maxNesting)return!1;for(e.pos=a+1;e.pos?@[\]^_`{|}~-])/g;e.exports=function(e,t){var r,i,o=e.posMax,a=e.pos;if(94!==e.src.charCodeAt(a))return!1;if(t)return!1;if(a+2>=o)return!1;if(e.level>=e.options.maxNesting)return!1;for(e.pos=a+1;e.pos=e.options.maxNesting)return!1;if(n=v+1,s=r(e,v),s<0)return!1;if(p=s+1,p=y)return!1;for(v=p,i(e,p)?(c=e.linkContent,p=e.pos):c="",v=p;p=y||41!==e.src.charCodeAt(p))return e.pos=m,!1;p++}else{if(e.linkLevel>0)return!1;for(;p=0?u=e.src.slice(v,p++):p=v-1),u||("undefined"==typeof u&&(p=s+1),u=e.src.slice(n,s)),f=e.env.references[a(u)],!f)return e.pos=m,!1;c=f.href,l=f.title}return t||(e.pos=n,e.posMax=s,d?e.push({type:"image",src:c,title:l,alt:e.src.substr(n,s-n),level:e.level}):(e.push({type:"link_open",href:c,title:l,level:e.level++}),e.linkLevel++,e.parser.tokenize(e),e.linkLevel--,e.push({type:"link_close",level:--e.level}))),e.pos=p,e.posMax=y,!0}},function(e,t,n){"use strict";var r=n(1291);e.exports=function(e,t){var n,i,o,a,s=e.posMax,u=e.pos;return!(u+2>=s)&&(94===e.src.charCodeAt(u)&&(91===e.src.charCodeAt(u+1)&&(!(e.level>=e.options.maxNesting)&&(n=u+2,i=r(e,u+1),!(i<0)&&(t||(e.env.footnotes||(e.env.footnotes={}),e.env.footnotes.list||(e.env.footnotes.list=[]),o=e.env.footnotes.list.length,e.pos=n,e.posMax=i,e.push({type:"footnote_ref",id:o,level:e.level}),e.linkLevel++,a=e.tokens.length,e.parser.tokenize(e),e.env.footnotes.list[o]={tokens:e.tokens.splice(a)},e.linkLevel--),e.pos=i+1,e.posMax=s,!0)))))}},function(e,t){"use strict";e.exports=function(e,t){var n,r,i,o,a=e.posMax,s=e.pos;if(s+3>a)return!1;if(!e.env.footnotes||!e.env.footnotes.refs)return!1;if(91!==e.src.charCodeAt(s))return!1;if(94!==e.src.charCodeAt(s+1))return!1;if(e.level>=e.options.maxNesting)return!1;for(r=s+2;r=a)&&(r++,n=e.src.slice(s+2,r-1),"undefined"!=typeof e.env.footnotes.refs[":"+n]&&(t||(e.env.footnotes.list||(e.env.footnotes.list=[]),e.env.footnotes.refs[":"+n]<0?(i=e.env.footnotes.list.length,e.env.footnotes.list[i]={label:n,count:0},e.env.footnotes.refs[":"+n]=i):i=e.env.footnotes.refs[":"+n],o=e.env.footnotes.list[i].count,e.env.footnotes.list[i].count++,e.push({type:"footnote_ref",id:i,subId:o,level:e.level})),e.pos=r,e.posMax=a,!0)))}},function(e,t,n){"use strict";var r=n(1334),i=n(1294),o=/^<([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/,a=/^<([a-zA-Z.\-]{1,25}):([^<>\x00-\x20]*)>/;e.exports=function(e,t){var n,s,u,c,l,p=e.pos;return 60===e.src.charCodeAt(p)&&(n=e.src.slice(p),!(n.indexOf(">")<0)&&((s=n.match(a))?!(r.indexOf(s[1].toLowerCase())<0)&&(c=s[0].slice(1,-1),l=i(c),!!e.parser.validateLink(c)&&(t||(e.push({type:"link_open",href:l,level:e.level}),e.push({type:"text",content:c,level:e.level+1}),e.push({type:"link_close",level:e.level})),e.pos+=s[0].length,!0)):(u=n.match(o),!!u&&(c=u[0].slice(1,-1),l=i("mailto:"+c),!!e.parser.validateLink(l)&&(t||(e.push({type:"link_open",href:l,level:e.level}),e.push({type:"text",content:c,level:e.level+1}),e.push({type:"link_close",level:e.level})),e.pos+=u[0].length,!0)))))}},function(e,t){"use strict";e.exports=["coap","doi","javascript","aaa","aaas","about","acap","cap","cid","crid","data","dav","dict","dns","file","ftp","geo","go","gopher","h323","http","https","iax","icap","im","imap","info","ipp","iris","iris.beep","iris.xpc","iris.xpcs","iris.lwz","ldap","mailto","mid","msrp","msrps","mtqp","mupdate","news","nfs","ni","nih","nntp","opaquelocktoken","pop","pres","rtsp","service","session","shttp","sieve","sip","sips","sms","snmp","soap.beep","soap.beeps","tag","tel","telnet","tftp","thismessage","tn3270","tip","tv","urn","vemmi","ws","wss","xcon","xcon-userid","xmlrpc.beep","xmlrpc.beeps","xmpp","z39.50r","z39.50s","adiumxtra","afp","afs","aim","apt","attachment","aw","beshare","bitcoin","bolo","callto","chrome","chrome-extension","com-eventbrite-attendee","content","cvs","dlna-playsingle","dlna-playcontainer","dtn","dvb","ed2k","facetime","feed","finger","fish","gg","git","gizmoproject","gtalk","hcp","icon","ipn","irc","irc6","ircs","itms","jar","jms","keyparc","lastfm","ldaps","magnet","maps","market","message","mms","ms-help","msnim","mumble","mvn","notes","oid","palm","paparazzi","platform","proxy","psyc","query","res","resource","rmi","rsync","rtmp","secondlife","sftp","sgn","skype","smb","soldat","spotify","ssh","steam","svn","teamspeak","things","udp","unreal","ut2004","ventrilo","view-source","webcal","wtai","wyciwyg","xfire","xri","ymsgr"]},function(e,t,n){"use strict";function r(e){var t=32|e;return t>=97&&t<=122}var i=n(1336).HTML_TAG_RE;e.exports=function(e,t){var n,o,a,s=e.pos;return!!e.options.html&&(a=e.posMax,!(60!==e.src.charCodeAt(s)||s+2>=a)&&(n=e.src.charCodeAt(s+1),!(33!==n&&63!==n&&47!==n&&!r(n))&&(!!(o=e.src.slice(s).match(i))&&(t||e.push({type:"htmltag",content:e.src.slice(s,s+o[0].length),level:e.level}),e.pos+=o[0].length,!0))))}},function(e,t){"use strict";function n(e,t){return e=e.source,t=t||"",function n(r,i){return r?(i=i.source||i,e=e.replace(r,i),n):new RegExp(e,t)}}var r=/[a-zA-Z_:][a-zA-Z0-9:._-]*/,i=/[^"'=<>`\x00-\x20]+/,o=/'[^']*'/,a=/"[^"]*"/,s=n(/(?:unquoted|single_quoted|double_quoted)/)("unquoted",i)("single_quoted",o)("double_quoted",a)(),u=n(/(?:\s+attr_name(?:\s*=\s*attr_value)?)/)("attr_name",r)("attr_value",s)(),c=n(/<[A-Za-z][A-Za-z0-9]*attribute*\s*\/?>/)("attribute",u)(),l=/<\/[A-Za-z][A-Za-z0-9]*\s*>/,p=//,f=/<[?].*?[?]>/,h=/]*>/,d=/])*\]\]>/,m=n(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)("open_tag",c)("close_tag",l)("comment",p)("processing",f)("declaration",h)("cdata",d)();e.exports.HTML_TAG_RE=m},function(e,t,n){"use strict";var r=n(1283),i=n(1282).has,o=n(1282).isValidEntityCode,a=n(1282).fromCodePoint,s=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,u=/^&([a-z][a-z0-9]{1,31});/i;e.exports=function(e,t){var n,c,l,p=e.pos,f=e.posMax;if(38!==e.src.charCodeAt(p))return!1;if(p+1/g,">").replace(/\"/g,""")}function f(e,n){n=n.replace(/[\x00-\x20]+/g,""),n=n.replace(/<\!\-\-.*?\-\-\>/g,"");var r=n.match(/^([a-zA-Z]+)\:/);if(!r)return!!n.match(/^\/\//)&&!t.allowProtocolRelative;var o=r[1].toLowerCase();return i(t.allowedSchemesByTag,e)?t.allowedSchemesByTag[e].indexOf(o)===-1:!t.allowedSchemes||t.allowedSchemes.indexOf(o)===-1}function h(e,t){return t?(e=e.split(/\s+/),e.filter(function(e){return t.indexOf(e)!==-1}).join(" ")):e}var d="";t?(t=s(o.defaults,t),t.parser?t.parser=s(c,t.parser):t.parser=c):(t=o.defaults,t.parser=c);var m,y,v=t.nonTextTags||["script","style","textarea"];t.allowedAttributes&&(m={},y={},r(t.allowedAttributes,function(e,t){m[t]=[];var n=[];e.forEach(function(e){e.indexOf("*")>=0?n.push(u(e).replace(/\\\*/g,".*")):m[t].push(e)}),y[t]=new RegExp("^("+n.join("|")+")$")}));var g={};r(t.allowedClasses,function(e,t){m&&(i(m,t)||(m[t]=[]),m[t].push("class")),g[t]=e});var _,b={};r(t.transformTags,function(e,t){var n;"function"==typeof e?n=e:"string"==typeof e&&(n=o.simpleTransform(e)),"*"===t?_=n:b[t]=n});var x=0,w=[],k={},S={},E=!1,C=0,A=new a.Parser({onopentag:function(e,n){if(E)return void C++;var o=new l(e,n);w.push(o);var a,s=!1,u=!!o.text;i(b,e)&&(a=b[e](e,n),o.attribs=n=a.attribs,void 0!==a.text&&(o.innerText=a.text),e!==a.tagName&&(o.name=e=a.tagName,S[x]=a.tagName)),_&&(a=_(e,n),o.attribs=n=a.attribs,e!==a.tagName&&(o.name=e=a.tagName,S[x]=a.tagName)),t.allowedTags&&t.allowedTags.indexOf(e)===-1&&(s=!0,v.indexOf(e)!==-1&&(E=!0,C=1),k[x]=!0),x++,s||(d+="<"+e,(!m||i(m,e)||m["*"])&&r(n,function(t,n){if(!m||i(m,e)&&m[e].indexOf(n)!==-1||m["*"]&&m["*"].indexOf(n)!==-1||i(y,e)&&y[e].test(n)||y["*"]&&y["*"].test(n)){if(("href"===n||"src"===n)&&f(e,t))return void delete o.attribs[n];if("class"===n&&(t=h(t,g[e]),!t.length))return void delete o.attribs[n];d+=" "+n,t.length&&(d+='="'+p(t)+'"')}else delete o.attribs[n]}),t.selfClosing.indexOf(e)!==-1?d+=" />":(d+=">",!o.innerText||u||t.textFilter||(d+=o.innerText)))},ontext:function(e){if(!E){var n,r=w[w.length-1];if(r&&(n=r.tag,e=void 0!==r.innerText?r.innerText:e),"script"===n||"style"===n)d+=e;else{var i=p(e);d+=t.textFilter?t.textFilter(i):i}if(w.length){var o=w[w.length-1];o.text+=e}}},onclosetag:function(e){if(E){if(C--,C)return;E=!1}var n=w.pop();if(n){if(E=!1,x--,k[x])return delete k[x],void n.updateParentNodeText();if(S[x]&&(e=S[x],delete S[x]),t.exclusiveFilter&&t.exclusiveFilter(n))return void(d=d.substr(0,n.tagPosition));n.updateParentNodeText(),t.selfClosing.indexOf(e)===-1&&(d+="")}}},t.parser);return A.write(e),A.end(),d}var a=n(1342),s=n(1372),u=n(1373);e.exports=o;var c={decodeEntities:!0};o.defaults={allowedTags:["h3","h4","h5","h6","blockquote","p","a","ul","ol","nl","li","b","i","strong","em","strike","code","hr","br","div","table","thead","caption","tbody","tr","th","td","pre"],allowedAttributes:{a:["href","name","target"],img:["src"]},selfClosing:["img","br","hr","area","base","basefont","input","link","meta"],allowedSchemes:["http","https","ftp","mailto"],allowedSchemesByTag:{},allowProtocolRelative:!0},o.simpleTransform=function(e,t,n){return n=void 0===n||n,t=t||{},function(r,i){var o;if(n)for(o in t)i[o]=t[o];else i=t;return{tagName:e,attribs:i}}}},function(e,t,n){function r(t,n){return delete e.exports[t],e.exports[t]=n,n}var i=n(1343),o=n(1350);e.exports={Parser:i,Tokenizer:n(1344),ElementType:n(1351),DomHandler:o,get FeedHandler(){return r("FeedHandler",n(1354))},get Stream(){return r("Stream",n(1355))},get WritableStream(){return r("WritableStream",n(1356))},get ProxyHandler(){return r("ProxyHandler",n(1358))},get DomUtils(){return r("DomUtils",n(1359))},get CollectingHandler(){return r("CollectingHandler",n(1371))},DefaultHandler:o,get RssHandler(){return r("RssHandler",this.FeedHandler)},parseDOM:function(e,t){var n=new o(t);return new i(n,t).end(e),n.dom},parseFeed:function(t,n){var r=new e.exports.FeedHandler(n);return new i(r,n).end(t),r.dom},createDomStream:function(e,t,n){var r=new o(e,t,n);return new i(r,t)},EVENTS:{attribute:2,cdatastart:0,cdataend:0,text:1,processinginstruction:2,comment:1,commentend:0,closetag:1,opentag:2,opentagname:1,error:1,end:0}}},function(e,t,n){function r(e,t){this._options=t||{},this._cbs=e||{},this._tagname="",this._attribname="",this._attribvalue="",this._attribs=null,this._stack=[],this.startIndex=0,this.endIndex=null,this._lowerCaseTagNames="lowerCaseTags"in this._options?!!this._options.lowerCaseTags:!this._options.xmlMode,this._lowerCaseAttributeNames="lowerCaseAttributeNames"in this._options?!!this._options.lowerCaseAttributeNames:!this._options.xmlMode,this._options.Tokenizer&&(i=this._options.Tokenizer),this._tokenizer=new i(this._options,this),this._cbs.onparserinit&&this._cbs.onparserinit(this)}var i=n(1344),o={input:!0,option:!0,optgroup:!0,select:!0,button:!0,datalist:!0,textarea:!0},a={tr:{tr:!0,th:!0,td:!0},th:{th:!0},td:{thead:!0,th:!0,td:!0},body:{head:!0,link:!0,script:!0},li:{li:!0},p:{p:!0},h1:{p:!0},h2:{p:!0},h3:{p:!0},h4:{p:!0},h5:{p:!0},h6:{p:!0},select:o,input:o,output:o,button:o,datalist:o,textarea:o,option:{option:!0},optgroup:{optgroup:!0}},s={__proto__:null,area:!0,base:!0,basefont:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,isindex:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,path:!0,circle:!0,ellipse:!0,line:!0,rect:!0,use:!0,stop:!0,polyline:!0,polygon:!0},u=/\s|\//;n(474)(r,n(473).EventEmitter),r.prototype._updatePosition=function(e){null===this.endIndex?this._tokenizer._sectionStart<=e?this.startIndex=0:this.startIndex=this._tokenizer._sectionStart-e:this.startIndex=this.endIndex+1,this.endIndex=this._tokenizer.getAbsoluteIndex()},r.prototype.ontext=function(e){this._updatePosition(1),this.endIndex--,this._cbs.ontext&&this._cbs.ontext(e)},r.prototype.onopentagname=function(e){if(this._lowerCaseTagNames&&(e=e.toLowerCase()),this._tagname=e,!this._options.xmlMode&&e in a)for(var t;(t=this._stack[this._stack.length-1])in a[e];this.onclosetag(t));!this._options.xmlMode&&e in s||this._stack.push(e),this._cbs.onopentagname&&this._cbs.onopentagname(e),this._cbs.onopentag&&(this._attribs={})},r.prototype.onopentagend=function(){this._updatePosition(1),this._attribs&&(this._cbs.onopentag&&this._cbs.onopentag(this._tagname,this._attribs),this._attribs=null),!this._options.xmlMode&&this._cbs.onclosetag&&this._tagname in s&&this._cbs.onclosetag(this._tagname),this._tagname=""},r.prototype.onclosetag=function(e){if(this._updatePosition(1),this._lowerCaseTagNames&&(e=e.toLowerCase()),!this._stack.length||e in s&&!this._options.xmlMode)this._options.xmlMode||"br"!==e&&"p"!==e||(this.onopentagname(e),this._closeCurrentTag());else{var t=this._stack.lastIndexOf(e);if(t!==-1)if(this._cbs.onclosetag)for(t=this._stack.length-t;t--;)this._cbs.onclosetag(this._stack.pop());else this._stack.length=t;else"p"!==e||this._options.xmlMode||(this.onopentagname(e),this._closeCurrentTag())}},r.prototype.onselfclosingtag=function(){this._options.xmlMode||this._options.recognizeSelfClosing?this._closeCurrentTag():this.onopentagend()},r.prototype._closeCurrentTag=function(){var e=this._tagname;this.onopentagend(),this._stack[this._stack.length-1]===e&&(this._cbs.onclosetag&&this._cbs.onclosetag(e),this._stack.pop())},r.prototype.onattribname=function(e){this._lowerCaseAttributeNames&&(e=e.toLowerCase()),this._attribname=e},r.prototype.onattribdata=function(e){this._attribvalue+=e},r.prototype.onattribend=function(){this._cbs.onattribute&&this._cbs.onattribute(this._attribname,this._attribvalue),this._attribs&&!Object.prototype.hasOwnProperty.call(this._attribs,this._attribname)&&(this._attribs[this._attribname]=this._attribvalue),this._attribname="",this._attribvalue=""},r.prototype._getInstructionName=function(e){var t=e.search(u),n=t<0?e:e.substr(0,t);return this._lowerCaseTagNames&&(n=n.toLowerCase()),n},r.prototype.ondeclaration=function(e){if(this._cbs.onprocessinginstruction){var t=this._getInstructionName(e);this._cbs.onprocessinginstruction("!"+t,"!"+e)}},r.prototype.onprocessinginstruction=function(e){if(this._cbs.onprocessinginstruction){var t=this._getInstructionName(e);this._cbs.onprocessinginstruction("?"+t,"?"+e)}},r.prototype.oncomment=function(e){this._updatePosition(4),this._cbs.oncomment&&this._cbs.oncomment(e),this._cbs.oncommentend&&this._cbs.oncommentend()},r.prototype.oncdata=function(e){this._updatePosition(1),this._options.xmlMode||this._options.recognizeCDATA?(this._cbs.oncdatastart&&this._cbs.oncdatastart(),this._cbs.ontext&&this._cbs.ontext(e),this._cbs.oncdataend&&this._cbs.oncdataend()):this.oncomment("[CDATA["+e+"]]")},r.prototype.onerror=function(e){this._cbs.onerror&&this._cbs.onerror(e)},r.prototype.onend=function(){if(this._cbs.onclosetag)for(var e=this._stack.length;e>0;this._cbs.onclosetag(this._stack[--e]));this._cbs.onend&&this._cbs.onend()},r.prototype.reset=function(){this._cbs.onreset&&this._cbs.onreset(),this._tokenizer.reset(),this._tagname="",this._attribname="",this._attribs=null,this._stack=[],this._cbs.onparserinit&&this._cbs.onparserinit(this)},r.prototype.parseComplete=function(e){this.reset(),this.end(e)},r.prototype.write=function(e){this._tokenizer.write(e)},r.prototype.end=function(e){this._tokenizer.end(e)},r.prototype.pause=function(){this._tokenizer.pause()},r.prototype.resume=function(){this._tokenizer.resume()},r.prototype.parseChunk=r.prototype.write,r.prototype.done=r.prototype.end,e.exports=r},function(e,t,n){function r(e){return" "===e||"\n"===e||"\t"===e||"\f"===e||"\r"===e}function i(e,t){return function(n){n===e&&(this._state=t)}}function o(e,t,n){var r=e.toLowerCase();return e===r?function(e){e===r?this._state=t:(this._state=n,this._index--)}:function(i){i===r||i===e?this._state=t:(this._state=n,this._index--)}}function a(e,t){var n=e.toLowerCase();return function(r){r===n||r===e?this._state=t:(this._state=m,this._index--)}}function s(e,t){this._state=h,this._buffer="",this._sectionStart=0,this._index=0,this._bufferOffset=0,this._baseState=h,this._special=me,this._cbs=t,this._running=!0,this._ended=!1,this._xmlMode=!(!e||!e.xmlMode),this._decodeEntities=!(!e||!e.decodeEntities)}e.exports=s;var u=n(1345),c=n(1347),l=n(1348),p=n(1349),f=0,h=f++,d=f++,m=f++,y=f++,v=f++,g=f++,_=f++,b=f++,x=f++,w=f++,k=f++,S=f++,E=f++,C=f++,A=f++,T=f++,O=f++,D=f++,M=f++,P=f++,I=f++,j=f++,R=f++,N=f++,F=f++,B=f++,L=f++,z=f++,q=f++,U=f++,W=f++,K=f++,V=f++,H=f++,J=f++,G=f++,X=f++,Y=f++,$=f++,Z=f++,Q=f++,ee=f++,te=f++,ne=f++,re=f++,ie=f++,oe=f++,ae=f++,se=f++,ue=f++,ce=f++,le=f++,pe=f++,fe=f++,he=f++,de=0,me=de++,ye=de++,ve=de++;s.prototype._stateText=function(e){"<"===e?(this._index>this._sectionStart&&this._cbs.ontext(this._getSection()),this._state=d,this._sectionStart=this._index):this._decodeEntities&&this._special===me&&"&"===e&&(this._index>this._sectionStart&&this._cbs.ontext(this._getSection()),this._baseState=h,this._state=ce,this._sectionStart=this._index)},s.prototype._stateBeforeTagName=function(e){"/"===e?this._state=v:"<"===e?(this._cbs.ontext(this._getSection()),this._sectionStart=this._index):">"===e||this._special!==me||r(e)?this._state=h:"!"===e?(this._state=A,this._sectionStart=this._index+1):"?"===e?(this._state=O,this._sectionStart=this._index+1):(this._state=this._xmlMode||"s"!==e&&"S"!==e?m:W,this._sectionStart=this._index)},s.prototype._stateInTagName=function(e){("/"===e||">"===e||r(e))&&(this._emitToken("onopentagname"),this._state=b,this._index--)},s.prototype._stateBeforeCloseingTagName=function(e){r(e)||(">"===e?this._state=h:this._special!==me?"s"===e||"S"===e?this._state=K:(this._state=h,this._index--):(this._state=g,this._sectionStart=this._index))},s.prototype._stateInCloseingTagName=function(e){(">"===e||r(e))&&(this._emitToken("onclosetag"),this._state=_,this._index--)},s.prototype._stateAfterCloseingTagName=function(e){">"===e&&(this._state=h,this._sectionStart=this._index+1)},s.prototype._stateBeforeAttributeName=function(e){">"===e?(this._cbs.onopentagend(),this._state=h,this._sectionStart=this._index+1):"/"===e?this._state=y:r(e)||(this._state=x,this._sectionStart=this._index)},s.prototype._stateInSelfClosingTag=function(e){">"===e?(this._cbs.onselfclosingtag(),this._state=h,this._sectionStart=this._index+1):r(e)||(this._state=b,this._index--)},s.prototype._stateInAttributeName=function(e){("="===e||"/"===e||">"===e||r(e))&&(this._cbs.onattribname(this._getSection()),this._sectionStart=-1,this._state=w,this._index--)},s.prototype._stateAfterAttributeName=function(e){"="===e?this._state=k:"/"===e||">"===e?(this._cbs.onattribend(),this._state=b,this._index--):r(e)||(this._cbs.onattribend(),this._state=x,this._sectionStart=this._index)},s.prototype._stateBeforeAttributeValue=function(e){'"'===e?(this._state=S,this._sectionStart=this._index+1):"'"===e?(this._state=E,this._sectionStart=this._index+1):r(e)||(this._state=C,this._sectionStart=this._index,this._index--)},s.prototype._stateInAttributeValueDoubleQuotes=function(e){'"'===e?(this._emitToken("onattribdata"),this._cbs.onattribend(),this._state=b):this._decodeEntities&&"&"===e&&(this._emitToken("onattribdata"),this._baseState=this._state,this._state=ce,this._sectionStart=this._index)},s.prototype._stateInAttributeValueSingleQuotes=function(e){"'"===e?(this._emitToken("onattribdata"),this._cbs.onattribend(),this._state=b):this._decodeEntities&&"&"===e&&(this._emitToken("onattribdata"),this._baseState=this._state,this._state=ce,this._sectionStart=this._index)},s.prototype._stateInAttributeValueNoQuotes=function(e){r(e)||">"===e?(this._emitToken("onattribdata"),this._cbs.onattribend(),this._state=b,this._index--):this._decodeEntities&&"&"===e&&(this._emitToken("onattribdata"),this._baseState=this._state,this._state=ce,this._sectionStart=this._index)},s.prototype._stateBeforeDeclaration=function(e){this._state="["===e?j:"-"===e?D:T},s.prototype._stateInDeclaration=function(e){">"===e&&(this._cbs.ondeclaration(this._getSection()),this._state=h,this._sectionStart=this._index+1)},s.prototype._stateInProcessingInstruction=function(e){">"===e&&(this._cbs.onprocessinginstruction(this._getSection()),this._state=h,this._sectionStart=this._index+1)},s.prototype._stateBeforeComment=function(e){"-"===e?(this._state=M,this._sectionStart=this._index+1):this._state=T},s.prototype._stateInComment=function(e){"-"===e&&(this._state=P)},s.prototype._stateAfterComment1=function(e){"-"===e?this._state=I:this._state=M},s.prototype._stateAfterComment2=function(e){">"===e?(this._cbs.oncomment(this._buffer.substring(this._sectionStart,this._index-2)),this._state=h,this._sectionStart=this._index+1):"-"!==e&&(this._state=M)},s.prototype._stateBeforeCdata1=o("C",R,T),s.prototype._stateBeforeCdata2=o("D",N,T),s.prototype._stateBeforeCdata3=o("A",F,T),s.prototype._stateBeforeCdata4=o("T",B,T),s.prototype._stateBeforeCdata5=o("A",L,T),s.prototype._stateBeforeCdata6=function(e){"["===e?(this._state=z,this._sectionStart=this._index+1):(this._state=T,this._index--)},s.prototype._stateInCdata=function(e){"]"===e&&(this._state=q)},s.prototype._stateAfterCdata1=i("]",U),s.prototype._stateAfterCdata2=function(e){">"===e?(this._cbs.oncdata(this._buffer.substring(this._sectionStart,this._index-2)),this._state=h,this._sectionStart=this._index+1):"]"!==e&&(this._state=z)},s.prototype._stateBeforeSpecial=function(e){"c"===e||"C"===e?this._state=V:"t"===e||"T"===e?this._state=te:(this._state=m,this._index--)},s.prototype._stateBeforeSpecialEnd=function(e){this._special!==ye||"c"!==e&&"C"!==e?this._special!==ve||"t"!==e&&"T"!==e?this._state=h:this._state=oe:this._state=Y},s.prototype._stateBeforeScript1=a("R",H),s.prototype._stateBeforeScript2=a("I",J),s.prototype._stateBeforeScript3=a("P",G),s.prototype._stateBeforeScript4=a("T",X),s.prototype._stateBeforeScript5=function(e){("/"===e||">"===e||r(e))&&(this._special=ye),this._state=m,this._index--},s.prototype._stateAfterScript1=o("R",$,h),s.prototype._stateAfterScript2=o("I",Z,h),s.prototype._stateAfterScript3=o("P",Q,h),s.prototype._stateAfterScript4=o("T",ee,h),s.prototype._stateAfterScript5=function(e){">"===e||r(e)?(this._special=me,this._state=g,this._sectionStart=this._index-6,this._index--):this._state=h},s.prototype._stateBeforeStyle1=a("Y",ne),s.prototype._stateBeforeStyle2=a("L",re),s.prototype._stateBeforeStyle3=a("E",ie),s.prototype._stateBeforeStyle4=function(e){("/"===e||">"===e||r(e))&&(this._special=ve),this._state=m,this._index--},s.prototype._stateAfterStyle1=o("Y",ae,h),s.prototype._stateAfterStyle2=o("L",se,h),s.prototype._stateAfterStyle3=o("E",ue,h),s.prototype._stateAfterStyle4=function(e){">"===e||r(e)?(this._special=me,this._state=g,this._sectionStart=this._index-5,this._index--):this._state=h},s.prototype._stateBeforeEntity=o("#",le,pe),s.prototype._stateBeforeNumericEntity=o("X",he,fe),s.prototype._parseNamedEntityStrict=function(){if(this._sectionStart+16&&(t=6);t>=2;){var n=this._buffer.substr(e,t);if(l.hasOwnProperty(n))return this._emitPartial(l[n]),void(this._sectionStart+=t+1);t--}},s.prototype._stateInNamedEntity=function(e){";"===e?(this._parseNamedEntityStrict(),this._sectionStart+1"z")&&(e<"A"||e>"Z")&&(e<"0"||e>"9")&&(this._xmlMode||this._sectionStart+1===this._index||(this._baseState!==h?"="!==e&&this._parseNamedEntityStrict():this._parseLegacyEntity()),this._state=this._baseState,this._index--)},s.prototype._decodeNumericEntity=function(e,t){var n=this._sectionStart+e;if(n!==this._index){var r=this._buffer.substring(n,this._index),i=parseInt(r,t);this._emitPartial(u(i)),this._sectionStart=this._index}else this._sectionStart--;this._state=this._baseState},s.prototype._stateInNumericEntity=function(e){";"===e?(this._decodeNumericEntity(2,10),this._sectionStart++):(e<"0"||e>"9")&&(this._xmlMode?this._state=this._baseState:this._decodeNumericEntity(2,10),this._index--)},s.prototype._stateInHexEntity=function(e){";"===e?(this._decodeNumericEntity(3,16),this._sectionStart++):(e<"a"||e>"f")&&(e<"A"||e>"F")&&(e<"0"||e>"9")&&(this._xmlMode?this._state=this._baseState:this._decodeNumericEntity(3,16),this._index--)},s.prototype._cleanup=function(){this._sectionStart<0?(this._buffer="",this._bufferOffset+=this._index,this._index=0):this._running&&(this._state===h?(this._sectionStart!==this._index&&this._cbs.ontext(this._buffer.substr(this._sectionStart)),this._buffer="",this._bufferOffset+=this._index,this._index=0):this._sectionStart===this._index?(this._buffer="",this._bufferOffset+=this._index,this._index=0):(this._buffer=this._buffer.substr(this._sectionStart),this._index-=this._sectionStart,this._bufferOffset+=this._sectionStart),this._sectionStart=0)},s.prototype.write=function(e){this._ended&&this._cbs.onerror(Error(".write() after done!")),this._buffer+=e,this._parse()},s.prototype._parse=function(){for(;this._index=55296&&e<=57343||e>1114111)return"�";e in i&&(e=i[e]);var t="";return e>65535&&(e-=65536,t+=String.fromCharCode(e>>>10&1023|55296),e=56320|1023&e),t+=String.fromCharCode(e)}var i=n(1346);e.exports=r},function(e,t){e.exports={0:65533,128:8364,130:8218,131:402,132:8222,133:8230,134:8224,135:8225,136:710,137:8240,138:352,139:8249,140:338,142:381,145:8216,146:8217,147:8220,148:8221,149:8226,150:8211,151:8212,152:732,153:8482,154:353,155:8250,156:339,158:382,159:376}},function(e,t){e.exports={Aacute:"Á",aacute:"á",Abreve:"Ă",abreve:"ă",ac:"∾",acd:"∿",acE:"∾̳",Acirc:"Â",acirc:"â",acute:"´",Acy:"А",acy:"а",AElig:"Æ",aelig:"æ",af:"⁡",Afr:"𝔄",afr:"𝔞",Agrave:"À",agrave:"à",alefsym:"ℵ",aleph:"ℵ",Alpha:"Α",alpha:"α",Amacr:"Ā",amacr:"ā",amalg:"⨿",amp:"&",AMP:"&",andand:"⩕",And:"⩓",and:"∧",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angmsd:"∡",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"Å",angzarr:"⍼",Aogon:"Ą",aogon:"ą",Aopf:"𝔸",aopf:"𝕒",apacir:"⩯",ap:"≈",apE:"⩰",ape:"≊",apid:"≋",apos:"'",ApplyFunction:"⁡",approx:"≈",approxeq:"≊",Aring:"Å",aring:"å",Ascr:"𝒜",ascr:"𝒶",Assign:"≔",ast:"*",asymp:"≈",asympeq:"≍",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",awconint:"∳",awint:"⨑",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",Backslash:"∖",Barv:"⫧",barvee:"⊽",barwed:"⌅",Barwed:"⌆",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",Bcy:"Б",bcy:"б",bdquo:"„",becaus:"∵",because:"∵",Because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",Bernoullis:"ℬ",Beta:"Β",beta:"β",beth:"ℶ",between:"≬",Bfr:"𝔅",bfr:"𝔟",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bNot:"⫭",bnot:"⌐",Bopf:"𝔹",bopf:"𝕓",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxbox:"⧉",boxdl:"┐",boxdL:"╕",boxDl:"╖",boxDL:"╗",boxdr:"┌",boxdR:"╒",boxDr:"╓",boxDR:"╔",boxh:"─",boxH:"═",boxhd:"┬",boxHd:"╤",boxhD:"╥",boxHD:"╦",boxhu:"┴",boxHu:"╧",boxhU:"╨",boxHU:"╩",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxul:"┘",boxuL:"╛",boxUl:"╜",boxUL:"╝",boxur:"└",boxuR:"╘",boxUr:"╙",boxUR:"╚",boxv:"│",boxV:"║",boxvh:"┼",boxvH:"╪",boxVh:"╫",boxVH:"╬",boxvl:"┤",boxvL:"╡",boxVl:"╢",boxVL:"╣",boxvr:"├",boxvR:"╞",boxVr:"╟",boxVR:"╠",bprime:"‵",breve:"˘",Breve:"˘",brvbar:"¦",bscr:"𝒷",Bscr:"ℬ",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsolb:"⧅",bsol:"\\",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",Bumpeq:"≎",bumpeq:"≏",Cacute:"Ć",cacute:"ć",capand:"⩄",capbrcup:"⩉",capcap:"⩋",cap:"∩",Cap:"⋒",capcup:"⩇",capdot:"⩀",CapitalDifferentialD:"ⅅ",caps:"∩︀",caret:"⁁",caron:"ˇ",Cayleys:"ℭ",ccaps:"⩍",Ccaron:"Č",ccaron:"č",Ccedil:"Ç",ccedil:"ç",Ccirc:"Ĉ",ccirc:"ĉ",Cconint:"∰",ccups:"⩌",ccupssm:"⩐",Cdot:"Ċ",cdot:"ċ",cedil:"¸",Cedilla:"¸",cemptyv:"⦲",cent:"¢",centerdot:"·",CenterDot:"·",cfr:"𝔠",Cfr:"ℭ",CHcy:"Ч",chcy:"ч",check:"✓",checkmark:"✓",Chi:"Χ",chi:"χ",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",CircleDot:"⊙",circledR:"®",circledS:"Ⓢ",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",cir:"○",cirE:"⧃",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",clubs:"♣",clubsuit:"♣",colon:":",Colon:"∷",Colone:"⩴",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",Congruent:"≡",conint:"∮",Conint:"∯",ContourIntegral:"∮",copf:"𝕔",Copf:"ℂ",coprod:"∐",Coproduct:"∐",copy:"©",COPY:"©",copysr:"℗",CounterClockwiseContourIntegral:"∳",crarr:"↵",cross:"✗",Cross:"⨯",Cscr:"𝒞",cscr:"𝒸",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",cupbrcap:"⩈",cupcap:"⩆",CupCap:"≍",cup:"∪",Cup:"⋓",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",dagger:"†",Dagger:"‡",daleth:"ℸ",darr:"↓",Darr:"↡",dArr:"⇓",dash:"‐",Dashv:"⫤",dashv:"⊣",dbkarow:"⤏",dblac:"˝",Dcaron:"Ď",dcaron:"ď",Dcy:"Д",dcy:"д",ddagger:"‡",ddarr:"⇊",DD:"ⅅ",dd:"ⅆ",DDotrahd:"⤑",ddotseq:"⩷",deg:"°",Del:"∇",Delta:"Δ",delta:"δ",demptyv:"⦱",dfisht:"⥿",Dfr:"𝔇",dfr:"𝔡",dHar:"⥥",dharl:"⇃",dharr:"⇂",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",diam:"⋄",diamond:"⋄",Diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",DifferentialD:"ⅆ",digamma:"ϝ",disin:"⋲",div:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",DJcy:"Ђ",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",Dopf:"𝔻",dopf:"𝕕",Dot:"¨",dot:"˙",DotDot:"⃜",doteq:"≐",doteqdot:"≑",DotEqual:"≐",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrowBar:"⤓",downarrow:"↓",DownArrow:"↓",Downarrow:"⇓",DownArrowUpArrow:"⇵",DownBreve:"̑",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVectorBar:"⥖",DownLeftVector:"↽",DownRightTeeVector:"⥟",DownRightVectorBar:"⥗",DownRightVector:"⇁",DownTeeArrow:"↧",DownTee:"⊤",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",Dscr:"𝒟",dscr:"𝒹",DScy:"Ѕ",dscy:"ѕ",dsol:"⧶",Dstrok:"Đ",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",DZcy:"Џ",dzcy:"џ",dzigrarr:"⟿",Eacute:"É",eacute:"é",easter:"⩮",Ecaron:"Ě",ecaron:"ě",Ecirc:"Ê",ecirc:"ê",ecir:"≖",ecolon:"≕",Ecy:"Э",ecy:"э",eDDot:"⩷",Edot:"Ė",edot:"ė",eDot:"≑",ee:"ⅇ",efDot:"≒",Efr:"𝔈",efr:"𝔢",eg:"⪚",Egrave:"È",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",Element:"∈",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",Emacr:"Ē",emacr:"ē",empty:"∅",emptyset:"∅",EmptySmallSquare:"◻",emptyv:"∅",EmptyVerySmallSquare:"▫",emsp13:" ",emsp14:" ",emsp:" ",ENG:"Ŋ",eng:"ŋ",ensp:" ",Eogon:"Ę",eogon:"ę",Eopf:"𝔼",eopf:"𝕖",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",Epsilon:"Ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",Equal:"⩵",equals:"=",EqualTilde:"≂",equest:"≟",Equilibrium:"⇌",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erarr:"⥱",erDot:"≓",escr:"ℯ",Escr:"ℰ",esdot:"≐",Esim:"⩳",esim:"≂",Eta:"Η",eta:"η",ETH:"Ð",eth:"ð",Euml:"Ë",euml:"ë",euro:"€",excl:"!",exist:"∃",Exists:"∃",expectation:"ℰ",exponentiale:"ⅇ",ExponentialE:"ⅇ",fallingdotseq:"≒",Fcy:"Ф",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",Ffr:"𝔉",ffr:"𝔣",filig:"fi",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",Fopf:"𝔽",fopf:"𝕗",forall:"∀",ForAll:"∀",fork:"⋔",forkv:"⫙",Fouriertrf:"ℱ",fpartint:"⨍",frac12:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",fscr:"𝒻",Fscr:"ℱ",gacute:"ǵ",Gamma:"Γ",gamma:"γ",Gammad:"Ϝ",gammad:"ϝ",gap:"⪆",Gbreve:"Ğ",gbreve:"ğ",Gcedil:"Ģ",Gcirc:"Ĝ",gcirc:"ĝ",Gcy:"Г",gcy:"г",Gdot:"Ġ",gdot:"ġ",ge:"≥",gE:"≧",gEl:"⪌",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",gescc:"⪩",ges:"⩾",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",Gfr:"𝔊",gfr:"𝔤",gg:"≫",Gg:"⋙",ggg:"⋙",gimel:"ℷ",GJcy:"Ѓ",gjcy:"ѓ",gla:"⪥",gl:"≷",glE:"⪒",glj:"⪤",gnap:"⪊",gnapprox:"⪊",gne:"⪈",gnE:"≩",gneq:"⪈",gneqq:"≩",gnsim:"⋧",Gopf:"𝔾",gopf:"𝕘",grave:"`",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"𝒢",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",gtcc:"⪧",gtcir:"⩺",gt:">",GT:">",Gt:"≫",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",Hacek:"ˇ",hairsp:" ",half:"½",hamilt:"ℋ",HARDcy:"Ъ",hardcy:"ъ",harrcir:"⥈",harr:"↔",hArr:"⇔",harrw:"↭",Hat:"^",hbar:"ℏ",Hcirc:"Ĥ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",hfr:"𝔥",Hfr:"ℌ",HilbertSpace:"ℋ",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",hopf:"𝕙",Hopf:"ℍ",horbar:"―",HorizontalLine:"─",hscr:"𝒽",Hscr:"ℋ",hslash:"ℏ",Hstrok:"Ħ",hstrok:"ħ",HumpDownHump:"≎",HumpEqual:"≏",hybull:"⁃",hyphen:"‐",Iacute:"Í",iacute:"í",ic:"⁣",Icirc:"Î",icirc:"î",Icy:"И",icy:"и",Idot:"İ",IEcy:"Е",iecy:"е",iexcl:"¡",iff:"⇔",ifr:"𝔦",Ifr:"ℑ",Igrave:"Ì",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",IJlig:"IJ",ijlig:"ij",Imacr:"Ī",imacr:"ī",image:"ℑ",ImaginaryI:"ⅈ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",Im:"ℑ",imof:"⊷",imped:"Ƶ",Implies:"⇒",incare:"℅",in:"∈",infin:"∞",infintie:"⧝",inodot:"ı",intcal:"⊺",int:"∫",Int:"∬",integers:"ℤ",Integral:"∫",intercal:"⊺",Intersection:"⋂",intlarhk:"⨗",intprod:"⨼",InvisibleComma:"⁣",InvisibleTimes:"⁢",IOcy:"Ё",iocy:"ё",Iogon:"Į",iogon:"į",Iopf:"𝕀",iopf:"𝕚",Iota:"Ι",iota:"ι",iprod:"⨼",iquest:"¿",iscr:"𝒾",Iscr:"ℐ",isin:"∈",isindot:"⋵",isinE:"⋹",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"⁢",Itilde:"Ĩ",itilde:"ĩ",Iukcy:"І",iukcy:"і",Iuml:"Ï",iuml:"ï",Jcirc:"Ĵ",jcirc:"ĵ",Jcy:"Й",jcy:"й",Jfr:"𝔍",jfr:"𝔧",jmath:"ȷ",Jopf:"𝕁",jopf:"𝕛",Jscr:"𝒥",jscr:"𝒿",Jsercy:"Ј",jsercy:"ј",Jukcy:"Є",jukcy:"є",Kappa:"Κ",kappa:"κ",kappav:"ϰ",Kcedil:"Ķ",kcedil:"ķ",Kcy:"К",kcy:"к",Kfr:"𝔎",kfr:"𝔨",kgreen:"ĸ",KHcy:"Х",khcy:"х",KJcy:"Ќ",kjcy:"ќ",Kopf:"𝕂",kopf:"𝕜",Kscr:"𝒦",kscr:"𝓀",lAarr:"⇚",Lacute:"Ĺ",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",Lambda:"Λ",lambda:"λ",lang:"⟨",Lang:"⟪",langd:"⦑",langle:"⟨",lap:"⪅",Laplacetrf:"ℒ",laquo:"«",larrb:"⇤",larrbfs:"⤟",larr:"←",Larr:"↞",lArr:"⇐",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",latail:"⤙",lAtail:"⤛",lat:"⪫",late:"⪭",lates:"⪭︀",lbarr:"⤌",lBarr:"⤎",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",Lcaron:"Ľ",lcaron:"ľ",Lcedil:"Ļ",lcedil:"ļ",lceil:"⌈",lcub:"{",Lcy:"Л",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",le:"≤",lE:"≦",LeftAngleBracket:"⟨",LeftArrowBar:"⇤",leftarrow:"←",LeftArrow:"←",Leftarrow:"⇐",LeftArrowRightArrow:"⇆",leftarrowtail:"↢",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVectorBar:"⥙",LeftDownVector:"⇃",LeftFloor:"⌊",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",leftrightarrow:"↔",LeftRightArrow:"↔",Leftrightarrow:"⇔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",LeftRightVector:"⥎",LeftTeeArrow:"↤",LeftTee:"⊣",LeftTeeVector:"⥚",leftthreetimes:"⋋",LeftTriangleBar:"⧏",LeftTriangle:"⊲",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVectorBar:"⥘",LeftUpVector:"↿",LeftVectorBar:"⥒",LeftVector:"↼",lEg:"⪋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",lescc:"⪨",les:"⩽",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",lessgtr:"≶",LessLess:"⪡",lesssim:"≲",LessSlantEqual:"⩽",LessTilde:"≲",lfisht:"⥼",lfloor:"⌊",Lfr:"𝔏",lfr:"𝔩",lg:"≶",lgE:"⪑",lHar:"⥢",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",LJcy:"Љ",ljcy:"љ",llarr:"⇇",ll:"≪",Ll:"⋘",llcorner:"⌞",Lleftarrow:"⇚",llhard:"⥫",lltri:"◺",Lmidot:"Ŀ",lmidot:"ŀ",lmoustache:"⎰",lmoust:"⎰",lnap:"⪉",lnapprox:"⪉",lne:"⪇",lnE:"≨",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",longleftarrow:"⟵",LongLeftArrow:"⟵",Longleftarrow:"⟸",longleftrightarrow:"⟷",LongLeftRightArrow:"⟷",Longleftrightarrow:"⟺",longmapsto:"⟼",longrightarrow:"⟶",LongRightArrow:"⟶",Longrightarrow:"⟹",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",Lopf:"𝕃",lopf:"𝕝",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",LowerLeftArrow:"↙",LowerRightArrow:"↘",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"‎",lrtri:"⊿",lsaquo:"‹",lscr:"𝓁",Lscr:"ℒ",lsh:"↰",Lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",Lstrok:"Ł",lstrok:"ł",ltcc:"⪦",ltcir:"⩹",lt:"<",LT:"<",Lt:"≪",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltri:"◃",ltrie:"⊴",ltrif:"◂",ltrPar:"⦖",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",macr:"¯",male:"♂",malt:"✠",maltese:"✠",Map:"⤅",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",Mcy:"М",mcy:"м",mdash:"—",mDDot:"∺",measuredangle:"∡",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"𝔐",mfr:"𝔪",mho:"℧",micro:"µ",midast:"*",midcir:"⫰",mid:"∣",middot:"·",minusb:"⊟",minus:"−",minusd:"∸",minusdu:"⨪",MinusPlus:"∓",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",Mopf:"𝕄",mopf:"𝕞",mp:"∓",mscr:"𝓂",Mscr:"ℳ",mstpos:"∾",Mu:"Μ",mu:"μ",multimap:"⊸",mumap:"⊸",nabla:"∇",Nacute:"Ń",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natural:"♮",naturals:"ℕ",natur:"♮",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",Ncaron:"Ň",ncaron:"ň",Ncedil:"Ņ",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",Ncy:"Н",ncy:"н",ndash:"–",nearhk:"⤤",nearr:"↗",neArr:"⇗",nearrow:"↗",ne:"≠",nedot:"≐̸",NegativeMediumSpace:"​",NegativeThickSpace:"​",NegativeThinSpace:"​",NegativeVeryThinSpace:"​",nequiv:"≢",nesear:"⤨",nesim:"≂̸",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:"\n",nexist:"∄",nexists:"∄",Nfr:"𝔑",nfr:"𝔫",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",nGg:"⋙̸",ngsim:"≵",nGt:"≫⃒",ngt:"≯",ngtr:"≯",nGtv:"≫̸",nharr:"↮",nhArr:"⇎",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",NJcy:"Њ",njcy:"њ",nlarr:"↚",nlArr:"⇍",nldr:"‥",nlE:"≦̸",nle:"≰",nleftarrow:"↚",nLeftarrow:"⇍",nleftrightarrow:"↮",nLeftrightarrow:"⇎",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nLl:"⋘̸",nlsim:"≴",nLt:"≪⃒",nlt:"≮",nltri:"⋪",nltrie:"⋬",nLtv:"≪̸",nmid:"∤",NoBreak:"⁠",NonBreakingSpace:" ",nopf:"𝕟",Nopf:"ℕ",Not:"⫬",not:"¬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",notin:"∉",notindot:"⋵̸",notinE:"⋹̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",NotLeftTriangleBar:"⧏̸",NotLeftTriangle:"⋪",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangleBar:"⧐̸",NotRightTriangle:"⋫",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",nparallel:"∦",npar:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",nprec:"⊀",npreceq:"⪯̸",npre:"⪯̸",nrarrc:"⤳̸",nrarr:"↛",nrArr:"⇏",nrarrw:"↝̸",nrightarrow:"↛",nRightarrow:"⇏",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",Nscr:"𝒩",nscr:"𝓃",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",Ntilde:"Ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",Nu:"Ν",nu:"ν",num:"#",numero:"№",numsp:" ",nvap:"≍⃒",nvdash:"⊬",nvDash:"⊭",nVdash:"⊮",nVDash:"⊯",nvge:"≥⃒",nvgt:">⃒",nvHarr:"⤄",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwarhk:"⤣",nwarr:"↖",nwArr:"⇖",nwarrow:"↖",nwnear:"⤧",Oacute:"Ó",oacute:"ó",oast:"⊛",Ocirc:"Ô",ocirc:"ô",ocir:"⊚",Ocy:"О",ocy:"о",odash:"⊝",Odblac:"Ő",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",OElig:"Œ",oelig:"œ",ofcir:"⦿",Ofr:"𝔒",ofr:"𝔬",ogon:"˛",Ograve:"Ò",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",Omacr:"Ō",omacr:"ō",Omega:"Ω",omega:"ω",Omicron:"Ο",omicron:"ο",omid:"⦶",ominus:"⊖",Oopf:"𝕆",oopf:"𝕠",opar:"⦷",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",operp:"⦹",oplus:"⊕",orarr:"↻",Or:"⩔",or:"∨",ord:"⩝",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oS:"Ⓢ",Oscr:"𝒪",oscr:"ℴ",Oslash:"Ø",oslash:"ø",osol:"⊘",Otilde:"Õ",otilde:"õ",otimesas:"⨶",Otimes:"⨷",otimes:"⊗",Ouml:"Ö",ouml:"ö",ovbar:"⌽",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",para:"¶",parallel:"∥",par:"∥",parsim:"⫳",parsl:"⫽",part:"∂",PartialD:"∂",Pcy:"П",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",Pfr:"𝔓",pfr:"𝔭",Phi:"Φ",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",Pi:"Π",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plus:"+",plusdo:"∔",plusdu:"⨥",pluse:"⩲",PlusMinus:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",Poincareplane:"ℌ",pointint:"⨕",popf:"𝕡",Popf:"ℙ",pound:"£",prap:"⪷",Pr:"⪻",pr:"≺",prcue:"≼",precapprox:"⪷",prec:"≺",preccurlyeq:"≼",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",pre:"⪯",prE:"⪳",precsim:"≾",prime:"′",Prime:"″",primes:"ℙ",prnap:"⪹",prnE:"⪵",prnsim:"⋨",prod:"∏",Product:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",Proportional:"∝",Proportion:"∷",propto:"∝",prsim:"≾",prurel:"⊰",Pscr:"𝒫",pscr:"𝓅",Psi:"Ψ",psi:"ψ",puncsp:" ",Qfr:"𝔔",qfr:"𝔮",qint:"⨌",qopf:"𝕢",Qopf:"ℚ",qprime:"⁗",Qscr:"𝒬",qscr:"𝓆",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",quot:'"',QUOT:'"',rAarr:"⇛",race:"∽̱",Racute:"Ŕ",racute:"ŕ",radic:"√",raemptyv:"⦳",rang:"⟩",Rang:"⟫",rangd:"⦒",range:"⦥",rangle:"⟩",raquo:"»",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarr:"→",Rarr:"↠",rArr:"⇒",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",Rarrtl:"⤖",rarrtl:"↣",rarrw:"↝",ratail:"⤚",rAtail:"⤜",ratio:"∶",rationals:"ℚ",rbarr:"⤍",rBarr:"⤏",RBarr:"⤐",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",Rcaron:"Ř",rcaron:"ř",Rcedil:"Ŗ",rcedil:"ŗ",rceil:"⌉",rcub:"}",Rcy:"Р",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",Re:"ℜ",rect:"▭",reg:"®",REG:"®",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",rfisht:"⥽",rfloor:"⌋",rfr:"𝔯",Rfr:"ℜ",rHar:"⥤",rhard:"⇁",rharu:"⇀",rharul:"⥬",Rho:"Ρ",rho:"ρ",rhov:"ϱ",RightAngleBracket:"⟩",RightArrowBar:"⇥",rightarrow:"→",RightArrow:"→",Rightarrow:"⇒",RightArrowLeftArrow:"⇄",rightarrowtail:"↣",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVectorBar:"⥕",RightDownVector:"⇂",RightFloor:"⌋",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",RightTeeArrow:"↦",RightTee:"⊢",RightTeeVector:"⥛",rightthreetimes:"⋌",RightTriangleBar:"⧐",RightTriangle:"⊳",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVectorBar:"⥔",RightUpVector:"↾",RightVectorBar:"⥓",RightVector:"⇀",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"‏",rmoustache:"⎱",rmoust:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",ropf:"𝕣",Ropf:"ℝ",roplus:"⨮",rotimes:"⨵",RoundImplies:"⥰",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",Rrightarrow:"⇛",rsaquo:"›",rscr:"𝓇",Rscr:"ℛ",rsh:"↱",Rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",RuleDelayed:"⧴",ruluhar:"⥨",rx:"℞",Sacute:"Ś",sacute:"ś",sbquo:"‚",scap:"⪸",Scaron:"Š",scaron:"š",Sc:"⪼",sc:"≻",sccue:"≽",sce:"⪰",scE:"⪴",Scedil:"Ş",scedil:"ş",Scirc:"Ŝ",scirc:"ŝ",scnap:"⪺",scnE:"⪶",scnsim:"⋩",scpolint:"⨓",scsim:"≿",Scy:"С",scy:"с",sdotb:"⊡",sdot:"⋅",sdote:"⩦",searhk:"⤥",searr:"↘",seArr:"⇘",searrow:"↘",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",Sfr:"𝔖",sfr:"𝔰",sfrown:"⌢",sharp:"♯",SHCHcy:"Щ",shchcy:"щ",SHcy:"Ш",shcy:"ш",ShortDownArrow:"↓",ShortLeftArrow:"←",shortmid:"∣",shortparallel:"∥",ShortRightArrow:"→",ShortUpArrow:"↑",shy:"­",Sigma:"Σ",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",SmallCircle:"∘",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",SOFTcy:"Ь",softcy:"ь",solbar:"⌿",solb:"⧄",sol:"/",Sopf:"𝕊",sopf:"𝕤",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",Sqrt:"√",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",square:"□",Square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",squarf:"▪",squ:"□",squf:"▪",srarr:"→",Sscr:"𝒮",sscr:"𝓈",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",Star:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",sub:"⊂",Sub:"⋐",subdot:"⪽",subE:"⫅",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",subset:"⊂",Subset:"⋐",subseteq:"⊆",subseteqq:"⫅",SubsetEqual:"⊆",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succapprox:"⪸",succ:"≻",succcurlyeq:"≽",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",SuchThat:"∋",sum:"∑",Sum:"∑",sung:"♪",sup1:"¹",sup2:"²",sup3:"³",sup:"⊃",Sup:"⋑",supdot:"⪾",supdsub:"⫘",supE:"⫆",supe:"⊇",supedot:"⫄",Superset:"⊃",SupersetEqual:"⊇",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",supset:"⊃",Supset:"⋑",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swarhk:"⤦",swarr:"↙",swArr:"⇙",swarrow:"↙",swnwar:"⤪",szlig:"ß",Tab:"\t",target:"⌖",Tau:"Τ",tau:"τ",tbrk:"⎴",Tcaron:"Ť",tcaron:"ť",Tcedil:"Ţ",tcedil:"ţ",Tcy:"Т",tcy:"т",tdot:"⃛",telrec:"⌕",Tfr:"𝔗",tfr:"𝔱",there4:"∴",therefore:"∴",Therefore:"∴",Theta:"Θ",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",ThickSpace:"  ",ThinSpace:" ",thinsp:" ",thkap:"≈",thksim:"∼",THORN:"Þ",thorn:"þ",tilde:"˜",Tilde:"∼",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",timesbar:"⨱",timesb:"⊠",times:"×",timesd:"⨰",tint:"∭",toea:"⤨",topbot:"⌶",topcir:"⫱",top:"⊤",Topf:"𝕋",topf:"𝕥",topfork:"⫚",tosa:"⤩",tprime:"‴",trade:"™",TRADE:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",TripleDot:"⃛",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",Tscr:"𝒯",tscr:"𝓉",TScy:"Ц",tscy:"ц",TSHcy:"Ћ",tshcy:"ћ",Tstrok:"Ŧ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",Uacute:"Ú",uacute:"ú",uarr:"↑",Uarr:"↟",uArr:"⇑",Uarrocir:"⥉",Ubrcy:"Ў",ubrcy:"ў",Ubreve:"Ŭ",ubreve:"ŭ",Ucirc:"Û",ucirc:"û",Ucy:"У",ucy:"у",udarr:"⇅",Udblac:"Ű",udblac:"ű",udhar:"⥮",ufisht:"⥾",Ufr:"𝔘",ufr:"𝔲",Ugrave:"Ù",ugrave:"ù",uHar:"⥣",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",Umacr:"Ū",umacr:"ū",uml:"¨",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",uogon:"ų",Uopf:"𝕌",uopf:"𝕦",UpArrowBar:"⤒",uparrow:"↑",UpArrow:"↑",Uparrow:"⇑",UpArrowDownArrow:"⇅",updownarrow:"↕",UpDownArrow:"↕",Updownarrow:"⇕",UpEquilibrium:"⥮",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",UpperLeftArrow:"↖",UpperRightArrow:"↗",upsi:"υ",Upsi:"ϒ",upsih:"ϒ",Upsilon:"Υ",upsilon:"υ",UpTeeArrow:"↥",UpTee:"⊥",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",Uring:"Ů",uring:"ů",urtri:"◹",Uscr:"𝒰",uscr:"𝓊",utdot:"⋰",Utilde:"Ũ",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",Uuml:"Ü",uuml:"ü",uwangle:"⦧",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",varr:"↕",vArr:"⇕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",vBar:"⫨",Vbar:"⫫",vBarv:"⫩",Vcy:"В",vcy:"в",vdash:"⊢",vDash:"⊨",Vdash:"⊩",VDash:"⊫",Vdashl:"⫦",veebar:"⊻",vee:"∨",Vee:"⋁",veeeq:"≚",vellip:"⋮",verbar:"|",Verbar:"‖",vert:"|",Vert:"‖",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"𝔙",vfr:"𝔳",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",Vopf:"𝕍",vopf:"𝕧",vprop:"∝",vrtri:"⊳",Vscr:"𝒱",vscr:"𝓋",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",Vvdash:"⊪",vzigzag:"⦚",Wcirc:"Ŵ",wcirc:"ŵ",wedbar:"⩟",wedge:"∧",Wedge:"⋀",wedgeq:"≙",weierp:"℘",Wfr:"𝔚",wfr:"𝔴",Wopf:"𝕎",wopf:"𝕨",wp:"℘",wr:"≀",wreath:"≀",Wscr:"𝒲",wscr:"𝓌",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",Xfr:"𝔛",xfr:"𝔵",xharr:"⟷",xhArr:"⟺",Xi:"Ξ",xi:"ξ",xlarr:"⟵",xlArr:"⟸",xmap:"⟼",xnis:"⋻",xodot:"⨀",Xopf:"𝕏",xopf:"𝕩",xoplus:"⨁",xotime:"⨂",xrarr:"⟶",xrArr:"⟹",Xscr:"𝒳",xscr:"𝓍",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",Yacute:"Ý",yacute:"ý",YAcy:"Я",yacy:"я",Ycirc:"Ŷ",ycirc:"ŷ",Ycy:"Ы",ycy:"ы",yen:"¥",Yfr:"𝔜",yfr:"𝔶",YIcy:"Ї",yicy:"ї",Yopf:"𝕐",yopf:"𝕪",Yscr:"𝒴",yscr:"𝓎",YUcy:"Ю",yucy:"ю",yuml:"ÿ",Yuml:"Ÿ",Zacute:"Ź",zacute:"ź",Zcaron:"Ž",zcaron:"ž",Zcy:"З",zcy:"з",Zdot:"Ż",zdot:"ż",zeetrf:"ℨ",ZeroWidthSpace:"​",Zeta:"Ζ",zeta:"ζ",zfr:"𝔷",Zfr:"ℨ",ZHcy:"Ж",zhcy:"ж",zigrarr:"⇝",zopf:"𝕫",Zopf:"ℤ",Zscr:"𝒵",zscr:"𝓏",zwj:"‍",zwnj:"‌"}},function(e,t){e.exports={Aacute:"Á",aacute:"á",Acirc:"Â",acirc:"â",acute:"´",AElig:"Æ",aelig:"æ",Agrave:"À",agrave:"à",amp:"&",AMP:"&",Aring:"Å",aring:"å",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",brvbar:"¦",Ccedil:"Ç",ccedil:"ç",cedil:"¸",cent:"¢",copy:"©",COPY:"©",curren:"¤",deg:"°",divide:"÷",Eacute:"É",eacute:"é",Ecirc:"Ê",ecirc:"ê",Egrave:"È",egrave:"è",ETH:"Ð",eth:"ð",Euml:"Ë",euml:"ë",frac12:"½",frac14:"¼",frac34:"¾",gt:">",GT:">",Iacute:"Í",iacute:"í",Icirc:"Î",icirc:"î",iexcl:"¡",Igrave:"Ì",igrave:"ì",iquest:"¿",Iuml:"Ï",iuml:"ï",laquo:"«",lt:"<",LT:"<",macr:"¯",micro:"µ",middot:"·",nbsp:" ",not:"¬",Ntilde:"Ñ",ntilde:"ñ",Oacute:"Ó",oacute:"ó",Ocirc:"Ô",ocirc:"ô",Ograve:"Ò",ograve:"ò",ordf:"ª",ordm:"º",Oslash:"Ø",oslash:"ø",Otilde:"Õ",otilde:"õ",Ouml:"Ö",ouml:"ö",para:"¶",plusmn:"±",pound:"£",quot:'"',QUOT:'"',raquo:"»",reg:"®",REG:"®",sect:"§",shy:"­",sup1:"¹",sup2:"²",sup3:"³",szlig:"ß",THORN:"Þ",thorn:"þ",times:"×",Uacute:"Ú",uacute:"ú",Ucirc:"Û",ucirc:"û",Ugrave:"Ù",ugrave:"ù",uml:"¨",Uuml:"Ü",uuml:"ü",Yacute:"Ý",yacute:"ý",yen:"¥",yuml:"ÿ"}},function(e,t){e.exports={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'}},function(e,t,n){function r(e,t,n){"object"==typeof e?(n=t,t=e,e=null):"function"==typeof t&&(n=t,t=u),this._callback=e,this._options=t||u,this._elementCB=n,this.dom=[],this._done=!1,this._tagStack=[],this._parser=this._parser||null}var i=n(1351),o=/\s+/g,a=n(1352),s=n(1353),u={normalizeWhitespace:!1,withStartIndices:!1,withEndIndices:!1};r.prototype.onparserinit=function(e){this._parser=e},r.prototype.onreset=function(){r.call(this,this._callback,this._options,this._elementCB)},r.prototype.onend=function(){this._done||(this._done=!0,this._parser=null,this._handleCallback(null))},r.prototype._handleCallback=r.prototype.onerror=function(e){if("function"==typeof this._callback)this._callback(e,this.dom);else if(e)throw e},r.prototype.onclosetag=function(){var e=this._tagStack.pop();this._options.withEndIndices&&(e.endIndex=this._parser.endIndex),this._elementCB&&this._elementCB(e)},r.prototype._createDomElement=function(e){if(!this._options.withDomLvl1)return e;var t;t="tag"===e.type?Object.create(s):Object.create(a);for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t},r.prototype._addDomElement=function(e){var t=this._tagStack[this._tagStack.length-1],n=t?t.children:this.dom,r=n[n.length-1];e.next=null,this._options.withStartIndices&&(e.startIndex=this._parser.startIndex),this._options.withEndIndices&&(e.endIndex=this._parser.endIndex),r?(e.prev=r,r.next=e):e.prev=null,n.push(e),e.parent=t||null},r.prototype.onopentag=function(e,t){var n={type:"script"===e?i.Script:"style"===e?i.Style:i.Tag,name:e,attribs:t,children:[]},r=this._createDomElement(n);this._addDomElement(r),this._tagStack.push(r)},r.prototype.ontext=function(e){var t,n=this._options.normalizeWhitespace||this._options.ignoreWhitespace;if(!this._tagStack.length&&this.dom.length&&(t=this.dom[this.dom.length-1]).type===i.Text)n?t.data=(t.data+e).replace(o," "):t.data+=e;else if(this._tagStack.length&&(t=this._tagStack[this._tagStack.length-1])&&(t=t.children[t.children.length-1])&&t.type===i.Text)n?t.data=(t.data+e).replace(o," "):t.data+=e;else{n&&(e=e.replace(o," "));var r=this._createDomElement({data:e,type:i.Text});this._addDomElement(r)}},r.prototype.oncomment=function(e){var t=this._tagStack[this._tagStack.length-1];if(t&&t.type===i.Comment)return void(t.data+=e);var n={data:e,type:i.Comment},r=this._createDomElement(n);this._addDomElement(r),this._tagStack.push(r)},r.prototype.oncdatastart=function(){var e={children:[{data:"",type:i.Text}],type:i.CDATA},t=this._createDomElement(e);this._addDomElement(t),this._tagStack.push(t)},r.prototype.oncommentend=r.prototype.oncdataend=function(){this._tagStack.pop()},r.prototype.onprocessinginstruction=function(e,t){var n=this._createDomElement({name:e,data:t,type:i.Directive});this._addDomElement(n)},e.exports=r},function(e,t){e.exports={Text:"text",Directive:"directive",Comment:"comment",Script:"script",Style:"style",Tag:"tag",CDATA:"cdata",Doctype:"doctype",isTag:function(e){return"tag"===e.type||"script"===e.type||"style"===e.type}}},function(e,t){var n=e.exports={get firstChild(){var e=this.children;return e&&e[0]||null},get lastChild(){var e=this.children;return e&&e[e.length-1]||null},get nodeType(){return i[this.type]||i.element}},r={tagName:"name",childNodes:"children",parentNode:"parent",previousSibling:"prev",nextSibling:"next",nodeValue:"data"},i={element:1,text:3,cdata:4,comment:8};Object.keys(r).forEach(function(e){var t=r[e];Object.defineProperty(n,e,{get:function(){return this[t]||null},set:function(e){return this[t]=e,e}})})},function(e,t,n){var r=n(1352),i=e.exports=Object.create(r),o={tagName:"name"};Object.keys(o).forEach(function(e){var t=o[e];Object.defineProperty(i,e,{ +get:function(){return this[t]||null},set:function(e){return this[t]=e,e}})})},function(e,t,n){function r(e,t){this.init(e,t)}function i(e,t){return l.getElementsByTagName(e,t,!0)}function o(e,t){return l.getElementsByTagName(e,t,!0,1)[0]}function a(e,t,n){return l.getText(l.getElementsByTagName(e,t,n,1)).trim()}function s(e,t,n,r,i){var o=a(n,r,i);o&&(e[t]=o)}var u=n(1342),c=u.DomHandler,l=u.DomUtils;n(474)(r,c),r.prototype.init=c;var p=function(e){return"rss"===e||"feed"===e||"rdf:RDF"===e};r.prototype.onend=function(){var e,t,n={},r=o(p,this.dom);r&&("feed"===r.name?(t=r.children,n.type="atom",s(n,"id","id",t),s(n,"title","title",t),(e=o("link",t))&&(e=e.attribs)&&(e=e.href)&&(n.link=e),s(n,"description","subtitle",t),(e=a("updated",t))&&(n.updated=new Date(e)),s(n,"author","email",t,!0),n.items=i("entry",t).map(function(e){var t,n={};return e=e.children,s(n,"id","id",e),s(n,"title","title",e),(t=o("link",e))&&(t=t.attribs)&&(t=t.href)&&(n.link=t),(t=a("summary",e)||a("content",e))&&(n.description=t),(t=a("updated",e))&&(n.pubDate=new Date(t)),n})):(t=o("channel",r.children).children,n.type=r.name.substr(0,3),n.id="",s(n,"title","title",t),s(n,"link","link",t),s(n,"description","description",t),(e=a("lastBuildDate",t))&&(n.updated=new Date(e)),s(n,"author","managingEditor",t,!0),n.items=i("item",r.children).map(function(e){var t,n={};return e=e.children,s(n,"id","guid",e),s(n,"title","title",e),s(n,"link","link",e),s(n,"description","description",e),(t=a("pubDate",e))&&(n.pubDate=new Date(t)),n}))),this.dom=n,c.prototype._handleCallback.call(this,r?null:Error("couldn't find root of feed"))},e.exports=r},function(e,t,n){function r(e){o.call(this,new i(this),e)}function i(e){this.scope=e}e.exports=r;var o=n(1356);n(474)(r,o),r.prototype.readable=!0;var a=n(1342).EVENTS;Object.keys(a).forEach(function(e){if(0===a[e])i.prototype["on"+e]=function(){this.scope.emit(e)};else if(1===a[e])i.prototype["on"+e]=function(t){this.scope.emit(e,t)};else{if(2!==a[e])throw Error("wrong number of arguments!");i.prototype["on"+e]=function(t,n){this.scope.emit(e,t,n)}}})},function(e,t,n){function r(e,t){var n=this._parser=new i(e,t),r=this._decoder=new a;o.call(this,{decodeStrings:!1}),this.once("finish",function(){n.end(r.end())})}e.exports=r;var i=n(1343),o=n(472).Writable||n(1357).Writable,a=n(488).StringDecoder,s=n(299).Buffer;n(474)(r,o),o.prototype._write=function(e,t,n){e instanceof s&&(e=this._decoder.write(e)),this._parser.write(e),n()}},481,function(e,t,n){function r(e){this._cbs=e||{}}e.exports=r;var i=n(1342).EVENTS;Object.keys(i).forEach(function(e){if(0===i[e])e="on"+e,r.prototype[e]=function(){this._cbs[e]&&this._cbs[e]()};else if(1===i[e])e="on"+e,r.prototype[e]=function(t){this._cbs[e]&&this._cbs[e](t)};else{if(2!==i[e])throw Error("wrong number of arguments");e="on"+e,r.prototype[e]=function(t,n){this._cbs[e]&&this._cbs[e](t,n)}}})},function(e,t,n){var r=e.exports;[n(1360),n(1366),n(1367),n(1368),n(1369),n(1370)].forEach(function(e){Object.keys(e).forEach(function(t){r[t]=e[t].bind(r)})})},function(e,t,n){function r(e,t){return e.children?e.children.map(function(e){return a(e,t)}).join(""):""}function i(e){return Array.isArray(e)?e.map(i).join(""):s(e)||e.type===o.CDATA?i(e.children):e.type===o.Text?e.data:""}var o=n(1351),a=n(1361),s=o.isTag;e.exports={getInnerHTML:r,getOuterHTML:a,getText:i}},function(e,t,n){function r(e,t){if(e){var n,r="";for(var i in e)n=e[i],r&&(r+=" "),r+=!n&&p[i]?i:i+'="'+(t.decodeEntities?l.encodeXML(n):n)+'"';return r}}function i(e,t){"svg"===e.name&&(t={decodeEntities:t.decodeEntities,xmlMode:!0});var n="<"+e.name,i=r(e.attribs,t);return i&&(n+=" "+i),!t.xmlMode||e.children&&0!==e.children.length?(n+=">",e.children&&(n+=d(e.children,t)),h[e.name]&&!t.xmlMode||(n+="")):n+="/>",n}function o(e){return"<"+e.data+">"}function a(e,t){var n=e.data||"";return!t.decodeEntities||e.parent&&e.parent.name in f||(n=l.encodeXML(n)),n}function s(e){return""}function u(e){return""}var c=n(1362),l=n(1363),p={__proto__:null,allowfullscreen:!0,async:!0,autofocus:!0,autoplay:!0,checked:!0,controls:!0,default:!0,defer:!0,disabled:!0,hidden:!0,ismap:!0,loop:!0,multiple:!0,muted:!0,open:!0,readonly:!0,required:!0,reversed:!0,scoped:!0,seamless:!0,selected:!0,typemustmatch:!0},f={__proto__:null,style:!0,script:!0,xmp:!0,iframe:!0,noembed:!0,noframes:!0,plaintext:!0,noscript:!0},h={__proto__:null,area:!0,base:!0,basefont:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,isindex:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},d=e.exports=function(e,t){Array.isArray(e)||e.cheerio||(e=[e]),t=t||{};for(var n="",r=0;r0&&(o=i(e,o,n,r),a=a.concat(o),r-=o.length,r<=0)));s++);return a}function o(e,t){for(var n=0,r=t.length;n0&&(n=a(e,t[r].children)));return n}function s(e,t){for(var n=0,r=t.length;n0&&s(e,t[n].children)))return!0;return!1}function u(e,t){for(var n=[],r=0,i=t.length;r0&&(n=n.concat(u(e,t[r].children))));return n}var c=n(1351).isTag;e.exports={filter:r,find:i,findOneChild:o,findOne:a,existsOne:s,findAll:u}},function(e,t,n){function r(e,t){return"function"==typeof t?function(n){return n.attribs&&t(n.attribs[e])}:function(n){return n.attribs&&n.attribs[e]===t}}function i(e,t){return function(n){return e(n)||t(n)}}var o=n(1351),a=t.isTag=o.isTag;t.testElement=function(e,t){for(var n in e)if(e.hasOwnProperty(n)){if("tag_name"===n){if(!a(t)||!e.tag_name(t.name))return!1}else if("tag_type"===n){if(!e.tag_type(t.type))return!1}else if("tag_contains"===n){if(a(t)||!e.tag_contains(t.data))return!1}else if(!t.attribs||!e[n](t.attribs[n]))return!1}else;return!0};var s={tag_name:function(e){return"function"==typeof e?function(t){return a(t)&&e(t.name)}:"*"===e?a:function(t){return a(t)&&t.name===e}},tag_type:function(e){return"function"==typeof e?function(t){return e(t.type)}:function(t){return t.type===e}},tag_contains:function(e){return"function"==typeof e?function(t){return!a(t)&&e(t.data)}:function(t){return!a(t)&&t.data===e}}};t.getElements=function(e,t,n,o){var a=Object.keys(e).map(function(t){var n=e[t];return t in s?s[t](n):r(t,n)});return 0===a.length?[]:this.filter(a.reduce(i),t,n,o)},t.getElementById=function(e,t,n){return Array.isArray(t)||(t=[t]),this.findOne(r("id",e),t,n!==!1)},t.getElementsByTagName=function(e,t,n,r){return this.filter(s.tag_name(e),t,n,r)},t.getElementsByTagType=function(e,t,n,r){return this.filter(s.tag_type(e),t,n,r)}},function(e,t){t.removeSubsets=function(e){for(var t,n,r,i=e.length;--i>-1;){for(t=n=e[i],e[i]=null,r=!0;n;){if(e.indexOf(n)>-1){r=!1,e.splice(i,1);break}n=n.parent}r&&(e[i]=t)}return e};var n={DISCONNECTED:1,PRECEDING:2,FOLLOWING:4,CONTAINS:8,CONTAINED_BY:16},r=t.compareDocumentPosition=function(e,t){var r,i,o,a,s,u,c=[],l=[];if(e===t)return 0;for(r=e;r;)c.unshift(r),r=r.parent;for(r=t;r;)l.unshift(r),r=r.parent;for(u=0;c[u]===l[u];)u++;return 0===u?n.DISCONNECTED:(i=c[u-1],o=i.children,a=c[u],s=l[u],o.indexOf(a)>o.indexOf(s)?i===t?n.FOLLOWING|n.CONTAINED_BY:n.FOLLOWING:i===e?n.PRECEDING|n.CONTAINS:n.PRECEDING)};t.uniqueSort=function(e){var t,i,o=e.length;for(e=e.slice();--o>-1;)t=e[o],i=e.indexOf(t),i>-1&&ii;)Se(e,n=r[i++],t[n]);return e},Ce=function(e,t){return void 0===t?Q(e):Ee(Q(e),t)},Ae=function(e){var t=he.call(this,e=$(e,!0));return!(this===ve&&j(me,e)&&!j(ye,e))&&(!(t||!j(this,e)||!j(me,e)||j(this,pe)&&this[pe][e])||t)},Te=function(e,t){if(e=Y(e),t=$(t,!0),e!==ve||!j(me,t)||j(ye,t)){var n=ie(e,t);return!n||!j(me,t)||j(e,pe)&&e[pe][t]||(n.enumerable=!0),n}},Oe=function(e){for(var t,n=ae(Y(e)),r=[],i=0;n.length>i;)j(me,t=n[i++])||t==pe||t==B||r.push(t);return r},De=function(e){for(var t,n=e===ve,r=ae(n?ye:Y(e)),i=[],o=0;r.length>o;)!j(me,t=r[o++])||n&&!j(ve,t)||i.push(me[t]);return i};ge||(se=function(){if(this instanceof se)throw TypeError("Symbol is not a constructor!");var e=U(arguments.length>0?arguments[0]:void 0),t=function(n){this===ve&&t.call(ye,n),j(this,pe)&&j(this[pe],e)&&(this[pe][e]=!1),xe(this,e,Z(1,n))};return R&&be&&xe(ve,e,{configurable:!0,set:t}),we(e)},F(se[le],"toString",function(){return this._k}),te.f=Te,ne.f=Se,n(T).f=ee.f=Oe,n(O).f=Ae,n(D).f=De,R&&!n(M)&&F(ve,"propertyIsEnumerable",Ae,!0),K.f=function(e){return we(W(e))}),N(N.G+N.W+N.F*!ge,{Symbol:se});for(var Me="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),Pe=0;Me.length>Pe;)W(Me[Pe++]);for(var Me=re(W.store),Pe=0;Me.length>Pe;)V(Me[Pe++]);N(N.S+N.F*!ge,"Symbol",{for:function(e){return j(de,e+="")?de[e]:de[e]=se(e)},keyFor:function(e){if(ke(e))return H(de,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){be=!0},useSimple:function(){be=!1}}),N(N.S+N.F*!ge,"Object",{create:Ce,defineProperty:Se,defineProperties:Ee,getOwnPropertyDescriptor:Te,getOwnPropertyNames:Oe,getOwnPropertySymbols:De}),ue&&N(N.S+N.F*(!ge||L(function(){var e=se();return"[null]"!=ce([e])||"{}"!=ce({a:e})||"{}"!=ce(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!ke(e)){for(var t,n,r=[e],i=1;arguments.length>i;)r.push(arguments[i++]);return t=r[1],"function"==typeof t&&(n=t),!n&&G(t)||(t=function(e,t){if(n&&(t=n.call(this,e,t)),!ke(t))return t}),r[1]=t,ce.apply(ue,r)}}}),se[le][fe]||n(P)(se[le],fe,se[le].valueOf),q(se,"Symbol"),q(Math,"Math",!0),q(I.JSON,"JSON",!0)},function(e,t,n,r){e.exports=!n(r)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t,n,r,i,o){var a=n(r),s=n(i);e.exports=n(o)?function(e,t,n){return a.f(e,t,s(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n,r,i,o,a){var s=n(r),u=n(i),c=n(o),l=Object.defineProperty;t.f=n(a)?Object.defineProperty:function(e,t,n){if(s(e),t=c(t,!0),s(n),u)try{return l(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t,n,r){var i=n(r);e.exports=function(e){if(!i(e))throw TypeError(e+" is not an object!");return e}},function(e,t,n,r,i,o){e.exports=!n(r)&&!n(i)(function(){return 7!=Object.defineProperty(n(o)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n,r,i){var o=n(r),a=n(i).document,s=o(a)&&o(a.createElement);e.exports=function(e){return s?a.createElement(e):{}}},function(e,t,n,r){var i=n(r);e.exports=function(e,t){if(!i(e))return e;var n,r;if(t&&"function"==typeof(n=e.toString)&&!i(r=n.call(e)))return r;if("function"==typeof(n=e.valueOf)&&!i(r=n.call(e)))return r;if(!t&&"function"==typeof(n=e.toString)&&!i(r=n.call(e)))return r;throw TypeError("Can't convert object to primitive value")}},function(e,t,n,r){var i=n(r);e.exports=function(e,t,n){if(i(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,i){return e.call(t,n,r,i)}}return function(){return e.apply(t,arguments)}}},function(e,t,n,r,i,o,a,s){var u=n(r)("meta"),c=n(i),l=n(o),p=n(a).f,f=0,h=Object.isExtensible||function(){return!0},d=!n(s)(function(){return h(Object.preventExtensions({}))}),m=function(e){p(e,u,{value:{i:"O"+ ++f,w:{}}})},y=function(e,t){if(!c(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!l(e,u)){if(!h(e))return"F";if(!t)return"E";m(e)}return e[u].i},v=function(e,t){if(!l(e,u)){if(!h(e))return!0;if(!t)return!1;m(e)}return e[u].w},g=function(e){return d&&_.NEED&&h(e)&&!l(e,u)&&m(e),e},_=e.exports={KEY:u,NEED:!1,fastKey:y,getWeak:v,onFreeze:g}},function(e,t,n,r){var i=n(r),o="__core-js_shared__",a=i[o]||(i[o]={});e.exports=function(e){return a[e]||(a[e]={})}},function(e,t,n,r,i,o){var a=n(r).f,s=n(i),u=n(o)("toStringTag");e.exports=function(e,t,n){e&&!s(e=n?e:e.prototype,u)&&a(e,u,{configurable:!0,value:t})}},function(e,t,n,r,i,o){var a=n(r)("wks"),s=n(i),u=n(o).Symbol,c="function"==typeof u,l=e.exports=function(e){return a[e]||(a[e]=c&&u[e]||(c?u:s)("Symbol."+e))};l.store=a},function(e,t,n,r){t.f=n(r)},function(e,t,n,r,i,o,a,s){var u=n(r),c=n(i),l=n(o),p=n(a),f=n(s).f;e.exports=function(e){var t=c.Symbol||(c.Symbol=l?{}:u.Symbol||{});"_"==e.charAt(0)||e in t||f(t,e,{value:p.f(e)})}},function(e,t,n,r,i){var o=n(r),a=n(i);e.exports=function(e,t){for(var n,r=a(e),i=o(r),s=i.length,u=0;s>u;)if(r[n=i[u++]]===t)return n}},function(e,t,n,r,i){var o=n(r),a=n(i);e.exports=Object.keys||function(e){return o(e,a)}},function(e,t,n,r,i,o,a){var s=n(r),u=n(i),c=n(o)(!1),l=n(a)("IE_PROTO");e.exports=function(e,t){var n,r=u(e),i=0,o=[];for(n in r)n!=l&&s(r,n)&&o.push(n);for(;t.length>i;)s(r,n=t[i++])&&(~c(o,n)||o.push(n));return o}},function(e,t,n,r,i){var o=n(r),a=n(i);e.exports=function(e){return o(a(e))}},function(e,t,n,r){var i=n(r);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==i(e)?e.split(""):Object(e)}},function(e,t,n,r,i,o){var a=n(r),s=n(i),u=n(o);e.exports=function(e){return function(t,n,r){var i,o=a(t),c=s(o.length),l=u(r,c);if(e&&n!=n){for(;c>l;)if(i=o[l++],i!=i)return!0}else for(;c>l;l++)if((e||l in o)&&o[l]===n)return e||l||0;return!e&&-1}}},function(e,t,n,r){var i=n(r),o=Math.min;e.exports=function(e){return e>0?o(i(e),9007199254740991):0}},function(e,t,n,r){var i=n(r),o=Math.max,a=Math.min;e.exports=function(e,t){return e=i(e),e<0?o(e+t,0):a(e,t)}},function(e,t,n,r,i){var o=n(r)("keys"),a=n(i);e.exports=function(e){return o[e]||(o[e]=a(e))}},function(e,t,n,r,i,o){var a=n(r),s=n(i),u=n(o);e.exports=function(e){var t=a(e),n=s.f;if(n)for(var r,i=n(e),o=u.f,c=0;i.length>c;)o.call(e,r=i[c++])&&t.push(r);return t}},function(e,t,n,r){var i=n(r);e.exports=Array.isArray||function(e){return"Array"==i(e)}},function(e,t,n,r,i,o,a,s,u){var c=n(r),l=n(i),p=n(o),f=n(a)("IE_PROTO"),h=function(){},d="prototype",m=function(){var e,t=n(s)("iframe"),r=p.length,i="<",o=">";for(t.style.display="none",n(u).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write(i+"script"+o+"document.F=Object"+i+"/script"+o),e.close(),m=e.F;r--;)delete m[d][p[r]];return m()};e.exports=Object.create||function(e,t){var n;return null!==e?(h[d]=c(e),n=new h,h[d]=null,n[f]=e):n=m(),void 0===t?n:l(n,t)}},function(e,t,n,r,i,o,a){var s=n(r),u=n(i),c=n(o);e.exports=n(a)?Object.defineProperties:function(e,t){u(e);for(var n,r=c(t),i=r.length,o=0;i>o;)s.f(e,n=r[o++],t[n]);return e}},function(e,t,n,r){e.exports=n(r).document&&document.documentElement},function(e,t,n,r,i){var o=n(r),a=n(i).f,s={}.toString,u="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],c=function(e){try{return a(e)}catch(e){return u.slice()}};e.exports.f=function(e){return u&&"[object Window]"==s.call(e)?c(e):a(o(e))}},function(e,t,n,r,i){var o=n(r),a=n(i).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return o(e,a)}},function(e,t,n,r,i,o,a,s,u,c){var l=n(r),p=n(i),f=n(o),h=n(a),d=n(s),m=n(u),y=Object.getOwnPropertyDescriptor;t.f=n(c)?y:function(e,t){if(e=f(e),t=h(t,!0),m)try{return y(e,t)}catch(e){}if(d(e,t))return p(!l.f.call(e,t),e[t])}},function(e,t,n,r,i){var o=n(r);o(o.S,"Object",{create:n(i)})},function(e,t,n,r,i,o){var a=n(r);a(a.S+a.F*!n(i),"Object",{defineProperty:n(o).f})},function(e,t,n,r,i,o){var a=n(r),s=n(i),u=n(o);e.exports=function(e,t){var n=(s.Object||{})[e]||Object[e],r={};r[e]=t(n),a(a.S+a.F*u(function(){n(1)}),"Object",r)}},function(e,t,n,r){var i=n(r);e.exports=function(e){return Object(i(e))}},function(e,t,n,r,i,o){var a=n(r),s=n(i),u=n(o)("IE_PROTO"),c=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=s(e), +a(e,u)?e[u]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?c:null}},function(e,t,n,r,i,o){var a=n(r),s=n(i);n(o)("keys",function(){return function(e){return s(a(e))}})},function(e,t,n,r,i){var o=n(r);o(o.S+o.F,"Object",{assign:n(i)})},function(e,t,n,r,i,o,a,s,u){"use strict";var c=n(r),l=n(i),p=n(o),f=n(a),h=n(s),d=Object.assign;e.exports=!d||n(u)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=d({},e)[n]||Object.keys(d({},t)).join("")!=r})?function(e,t){for(var n=f(e),r=arguments.length,i=1,o=l.f,a=p.f;r>i;)for(var s,u=h(arguments[i++]),d=o?c(u).concat(o(u)):c(u),m=d.length,y=0;m>y;)a.call(u,s=d[y++])&&(n[s]=u[s]);return n}:d},function(e,t,n,r,i){var o=n(r),a=n(i)("toStringTag"),s="Arguments"==o(function(){return arguments}()),u=function(e,t){try{return e[t]}catch(e){}};e.exports=function(e){var t,n,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=u(t=Object(e),a))?n:s?o(t):"Object"==(r=o(t))&&"function"==typeof t.callee?"Arguments":r}},function(e,t,n,r,i){"use strict";var o=n(r)(!0);n(i)(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=o(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n,r,i){var o=n(r),a=n(i);e.exports=function(e){return function(t,n){var r,i,s=String(a(t)),u=o(n),c=s.length;return u<0||u>=c?e?"":void 0:(r=s.charCodeAt(u),r<55296||r>56319||u+1===c||(i=s.charCodeAt(u+1))<56320||i>57343?e?s.charAt(u):r:e?s.slice(u,u+2):(r-55296<<10)+(i-56320)+65536)}}},function(e,t,n,r,i,o,a,s,u,c,l,p,f){"use strict";var h=n(r),d=n(i),m=n(o),y=n(a),v=n(s),g=n(u),_=n(c),b=n(l),x=n(p),w=n(f)("iterator"),k=!([].keys&&"next"in[].keys()),S="@@iterator",E="keys",C="values",A=function(){return this};e.exports=function(e,t,n,r,i,o,a){_(n,t,r);var s,u,c,l=function(e){if(!k&&e in O)return O[e];switch(e){case E:return function(){return new n(this,e)};case C:return function(){return new n(this,e)}}return function(){return new n(this,e)}},p=t+" Iterator",f=i==C,T=!1,O=e.prototype,D=O[w]||O[S]||i&&O[i],M=D||l(i),P=i?f?l("entries"):M:void 0,I="Array"==t?O.entries||D:D;if(I&&(c=x(I.call(new e)),c!==Object.prototype&&(b(c,p,!0),h||v(c,w)||y(c,w,A))),f&&D&&D.name!==C&&(T=!0,M=function(){return D.call(this)}),h&&!a||!k&&!T&&O[w]||y(O,w,M),g[t]=M,g[p]=A,i)if(s={values:f?M:l(C),keys:o?M:l(E),entries:P},a)for(u in s)u in O||m(O,u,s[u]);else d(d.P+d.F*(k||T),t,s);return s}},function(e,t,n,r,i,o,a,s){"use strict";var u=n(r),c=n(i),l=n(o),p={};n(a)(p,n(s)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=u(p,{next:c(1,n)}),l(e,t+" Iterator")}},function(e,t,n,r,i,o,a,s,u,c,l,p){"use strict";var f=n(r),h=n(i),d=n(o),m=n(a),y=n(s),v=n(u),g=n(c),_=n(l);h(h.S+h.F*!n(p)(function(e){Array.from(e)}),"Array",{from:function(e){var t,n,r,i,o=d(e),a="function"==typeof this?this:Array,s=arguments.length,u=s>1?arguments[1]:void 0,c=void 0!==u,l=0,p=_(o);if(c&&(u=f(u,s>2?arguments[2]:void 0,2)),void 0==p||a==Array&&y(p))for(t=v(o.length),n=new a(t);t>l;l++)g(n,l,c?u(o[l],l):o[l]);else for(i=p.call(o),n=new a;!(r=i.next()).done;l++)g(n,l,c?m(i,u,[r.value,l],!0):r.value);return n.length=l,n}})},function(e,t,n,r){var i=n(r);e.exports=function(e,t,n,r){try{return r?t(i(n)[0],n[1]):t(n)}catch(t){var o=e.return;throw void 0!==o&&i(o.call(e)),t}}},function(e,t,n,r,i){var o=n(r),a=n(i)("iterator"),s=Array.prototype;e.exports=function(e){return void 0!==e&&(o.Array===e||s[a]===e)}},function(e,t,n,r,i){"use strict";var o=n(r),a=n(i);e.exports=function(e,t,n){t in e?o.f(e,t,a(0,n)):e[t]=n}},function(e,t,n,r,i,o,a){var s=n(r),u=n(i)("iterator"),c=n(o);e.exports=n(a).getIteratorMethod=function(e){if(void 0!=e)return e[u]||e["@@iterator"]||c[s(e)]}},function(e,t,n,r){var i=n(r)("iterator"),o=!1;try{var a=[7][i]();a.return=function(){o=!0},Array.from(a,function(){throw 2})}catch(e){}e.exports=function(e,t){if(!t&&!o)return!1;var n=!1;try{var r=[7],a=r[i]();a.next=function(){return{done:n=!0}},r[i]=function(){return a},e(r)}catch(e){}return n}},function(e,t,n,r,i,o,a,s){var u=n(r),c=n(i),l=n(o),p=n(a),f=n(s);e.exports=function(e,t){var n=1==e,r=2==e,i=3==e,o=4==e,a=6==e,s=5==e||a,h=t||f;return function(t,f,d){for(var m,y,v=l(t),g=c(v),_=u(f,d,3),b=p(g.length),x=0,w=n?h(t,b):r?h(t,0):void 0;b>x;x++)if((s||x in g)&&(m=g[x],y=_(m,x,v),e))if(n)w[x]=y;else if(y)switch(e){case 3:return!0;case 5:return m;case 6:return x;case 2:w.push(m)}else if(o)return!1;return a?-1:i||o?o:w}}},function(e,t,n,r){var i=n(r);e.exports=function(e,t){return new(i(e))(t)}},function(e,t,n,r,i,o){var a=n(r),s=n(i),u=n(o)("species");e.exports=function(e){var t;return s(e)&&(t=e.constructor,"function"!=typeof t||t!==Array&&!s(t.prototype)||(t=void 0),a(t)&&(t=t[u],null===t&&(t=void 0))),void 0===t?Array:t}},function(e,t,n,r,i,o,a,s){"use strict";var u=n(r),c=n(i),l=n(o),p=n(a);e.exports=n(s)(Array,"Array",function(e,t){this._t=p(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,c(1)):"keys"==t?c(0,n):"values"==t?c(0,e[n]):c(0,[n,e[n]])},"values"),l.Arguments=l.Array,u("keys"),u("values"),u("entries")},function(e,t,n,r,i,o,a,s,u,c,l,p,f,h,d,m,y,v,g,_,b){"use strict";var x,w,k,S=n(r),E=n(i),C=n(o),A=n(a),T=n(s),O=n(u),D=n(c),M=n(l),P=n(p),I=n(f),j=n(h).set,R=n(d)(),N="Promise",F=E.TypeError,B=E.process,L=E[N],B=E.process,z="process"==A(B),q=function(){},U=!!function(){try{var e=L.resolve(1),t=(e.constructor={})[n(m)("species")]=function(e){e(q,q)};return(z||"function"==typeof PromiseRejectionEvent)&&e.then(q)instanceof t}catch(e){}}(),W=function(e,t){return e===t||e===L&&t===k},K=function(e){var t;return!(!O(e)||"function"!=typeof(t=e.then))&&t},V=function(e){return W(L,e)?new H(e):new w(e)},H=w=function(e){var t,n;this.promise=new e(function(e,r){if(void 0!==t||void 0!==n)throw F("Bad Promise constructor");t=e,n=r}),this.resolve=D(t),this.reject=D(n)},J=function(e){try{e()}catch(e){return{error:e}}},G=function(e,t){if(!e._n){e._n=!0;var n=e._c;R(function(){for(var r=e._v,i=1==e._s,o=0,a=function(t){var n,o,a=i?t.ok:t.fail,s=t.resolve,u=t.reject,c=t.domain;try{a?(i||(2==e._h&&$(e),e._h=1),a===!0?n=r:(c&&c.enter(),n=a(r),c&&c.exit()),n===t.promise?u(F("Promise-chain cycle")):(o=K(n))?o.call(n,s,u):s(n)):u(r)}catch(e){u(e)}};n.length>o;)a(n[o++]);e._c=[],e._n=!1,t&&!e._h&&X(e)})}},X=function(e){j.call(E,function(){var t,n,r,i=e._v;if(Y(e)&&(t=J(function(){z?B.emit("unhandledRejection",i,e):(n=E.onunhandledrejection)?n({promise:e,reason:i}):(r=E.console)&&r.error&&r.error("Unhandled promise rejection",i)}),e._h=z||Y(e)?2:1),e._a=void 0,t)throw t.error})},Y=function(e){if(1==e._h)return!1;for(var t,n=e._a||e._c,r=0;n.length>r;)if(t=n[r++],t.fail||!Y(t.promise))return!1;return!0},$=function(e){j.call(E,function(){var t;z?B.emit("rejectionHandled",e):(t=E.onrejectionhandled)&&t({promise:e,reason:e._v})})},Z=function(e){var t=this;t._d||(t._d=!0,t=t._w||t,t._v=e,t._s=2,t._a||(t._a=t._c.slice()),G(t,!0))},Q=function(e){var t,n=this;if(!n._d){n._d=!0,n=n._w||n;try{if(n===e)throw F("Promise can't be resolved itself");(t=K(e))?R(function(){var r={_w:n,_d:!1};try{t.call(e,C(Q,r,1),C(Z,r,1))}catch(e){Z.call(r,e)}}):(n._v=e,n._s=1,G(n,!1))}catch(e){Z.call({_w:n,_d:!1},e)}}};U||(L=function(e){M(this,L,N,"_h"),D(e),x.call(this);try{e(C(Q,this,1),C(Z,this,1))}catch(e){Z.call(this,e)}},x=function(e){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},x.prototype=n(y)(L.prototype,{then:function(e,t){var n=V(I(this,L));return n.ok="function"!=typeof e||e,n.fail="function"==typeof t&&t,n.domain=z?B.domain:void 0,this._c.push(n),this._a&&this._a.push(n),this._s&&G(this,!1),n.promise},catch:function(e){return this.then(void 0,e)}}),H=function(){var e=new x;this.promise=e,this.resolve=C(Q,e,1),this.reject=C(Z,e,1)}),T(T.G+T.W+T.F*!U,{Promise:L}),n(v)(L,N),n(g)(N),k=n(_)[N],T(T.S+T.F*!U,N,{reject:function(e){var t=V(this),n=t.reject;return n(e),t.promise}}),T(T.S+T.F*(S||!U),N,{resolve:function(e){if(e instanceof L&&W(e.constructor,this))return e;var t=V(this),n=t.resolve;return n(e),t.promise}}),T(T.S+T.F*!(U&&n(b)(function(e){L.all(e).catch(q)})),N,{all:function(e){var t=this,n=V(t),r=n.resolve,i=n.reject,o=J(function(){var n=[],o=0,a=1;P(e,!1,function(e){var s=o++,u=!1;n.push(void 0),a++,t.resolve(e).then(function(e){u||(u=!0,n[s]=e,--a||r(n))},i)}),--a||r(n)});return o&&i(o.error),n.promise},race:function(e){var t=this,n=V(t),r=n.reject,i=J(function(){P(e,!1,function(e){t.resolve(e).then(n.resolve,r)})});return i&&r(i.error),n.promise}})},function(e,t,n,r,i,o,a,s,u){var c=n(r),l=n(i),p=n(o),f=n(a),h=n(s),d=n(u),m={},y={},t=e.exports=function(e,t,n,r,i){var o,a,s,u,v=i?function(){return e}:d(e),g=c(n,r,t?2:1),_=0;if("function"!=typeof v)throw TypeError(e+" is not iterable!");if(p(v)){for(o=h(e.length);o>_;_++)if(u=t?g(f(a=e[_])[0],a[1]):g(e[_]),u===m||u===y)return u}else for(s=v.call(e);!(a=s.next()).done;)if(u=l(s,g,a.value,t),u===m||u===y)return u};t.BREAK=m,t.RETURN=y},function(e,t,n,r,i,o){var a=n(r),s=n(i),u=n(o)("species");e.exports=function(e,t){var n,r=a(e).constructor;return void 0===r||void 0==(n=a(r)[u])?t:s(n)}},function(e,t,n,r,i,o,a,s,u){var c,l,p,f=n(r),h=n(i),d=n(o),m=n(a),y=n(s),v=y.process,g=y.setImmediate,_=y.clearImmediate,b=y.MessageChannel,x=0,w={},k="onreadystatechange",S=function(){var e=+this;if(w.hasOwnProperty(e)){var t=w[e];delete w[e],t()}},E=function(e){S.call(e.data)};g&&_||(g=function(e){for(var t=[],n=1;arguments.length>n;)t.push(arguments[n++]);return w[++x]=function(){h("function"==typeof e?e:Function(e),t)},c(x),x},_=function(e){delete w[e]},"process"==n(u)(v)?c=function(e){v.nextTick(f(S,e,1))}:b?(l=new b,p=l.port2,l.port1.onmessage=E,c=f(p.postMessage,p,1)):y.addEventListener&&"function"==typeof postMessage&&!y.importScripts?(c=function(e){y.postMessage(e+"","*")},y.addEventListener("message",E,!1)):c=k in m("script")?function(e){d.appendChild(m("script"))[k]=function(){d.removeChild(this),S.call(e)}}:function(e){setTimeout(f(S,e,1),0)}),e.exports={set:g,clear:_}},function(e,t,n,r,i,o){var a=n(r),s=n(i).set,u=a.MutationObserver||a.WebKitMutationObserver,c=a.process,l=a.Promise,p="process"==n(o)(c);e.exports=function(){var e,t,n,r=function(){var r,i;for(p&&(r=c.domain)&&r.exit();e;){i=e.fn,e=e.next;try{i()}catch(r){throw e?n():t=void 0,r}}t=void 0,r&&r.enter()};if(p)n=function(){c.nextTick(r)};else if(u){var i=!0,o=document.createTextNode("");new u(r).observe(o,{characterData:!0}),n=function(){o.data=i=!i}}else if(l&&l.resolve){var f=l.resolve();n=function(){f.then(r)}}else n=function(){s.call(a,r)};return function(r){var i={fn:r,next:void 0};t&&(t.next=i),e||(e=i,n()),t=i}}},function(e,t,n,r,i,o,a,s,u,c){"use strict";var l,p=n(r)(0),f=n(i),h=n(o),d=n(a),m=n(s),y=n(u),v=h.getWeak,g=Object.isExtensible,_=m.ufstore,b={},x=function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},w={get:function(e){if(y(e)){var t=v(e);return t===!0?_(this).get(e):t?t[this._i]:void 0}},set:function(e,t){return m.def(this,e,t)}},k=e.exports=n(c)("WeakMap",x,w,m,!0,!0);7!=(new k).set((Object.freeze||Object)(b),7).get(b)&&(l=m.getConstructor(x),d(l.prototype,w),h.NEED=!0,p(["delete","has","get","set"],function(e){var t=k.prototype,n=t[e];f(t,e,function(t,r){if(y(t)&&!g(t)){this._f||(this._f=new l);var i=this._f[e](t,r);return"set"==e?this:i}return n.call(this,t,r)})}))},function(e,t,n,r,i,o,a,s,u,c,l){"use strict";var p=n(r),f=n(i).getWeak,h=n(o),d=n(a),m=n(s),y=n(u),v=n(c),g=n(l),_=v(5),b=v(6),x=0,w=function(e){return e._l||(e._l=new k)},k=function(){this.a=[]},S=function(e,t){return _(e.a,function(e){return e[0]===t})};k.prototype={get:function(e){var t=S(this,e);if(t)return t[1]},has:function(e){return!!S(this,e)},set:function(e,t){var n=S(this,e);n?n[1]=t:this.a.push([e,t])},delete:function(e){var t=b(this.a,function(t){return t[0]===e});return~t&&this.a.splice(t,1),!!~t}},e.exports={getConstructor:function(e,t,n,r){var i=e(function(e,o){m(e,i,t,"_i"),e._i=x++,e._l=void 0,void 0!=o&&y(o,n,e[r],e)});return p(i.prototype,{delete:function(e){if(!d(e))return!1;var t=f(e);return t===!0?w(this).delete(e):t&&g(t,this._i)&&delete t[this._i]},has:function(e){if(!d(e))return!1;var t=f(e);return t===!0?w(this).has(e):t&&g(t,this._i)}}),i},def:function(e,t,n){var r=f(h(t),!0);return r===!0?w(e).set(t,n):r[e._i]=n,e},ufstore:w}},function(e,t,n,r){n(r)("asyncIterator")},function(e,t,n,r){n(r)("observable")},function(e,t,n,r){var i=n(r),o=i.Symbol;e.exports=o},function(e,t,n,r){var i=n(r),o="object"==typeof self&&self&&self.Object===Object&&self,a=i||o||Function("return this")();e.exports=a},function(e,t,n,r){var i=n(r),o=i(Object.getPrototypeOf,Object);e.exports=o},function(e,t,n,r,i,o){function a(){this.size=0,this.__data__={hash:new s,map:new(c||u),string:new s}}var s=n(r),u=n(i),c=n(o);e.exports=a},function(e,t,n,r){function i(){this.__data__=o?o(null):{},this.size=0}var o=n(r);e.exports=i},function(e,t,n,r){var i=n(r),o=i(Object,"create");e.exports=o},function(e,t,n,r,i){function o(e,t){var n=s(e,t);return a(n)?n:void 0}var a=n(r),s=n(i);e.exports=o},function(e,t,n,r,i,o,a){function s(e){if(!l(e)||c(e))return!1;var t=u(e)?g:h;return t.test(p(e))}var u=n(r),c=n(i),l=n(o),p=n(a),f=/[\\^$.*+?()[\]{}|]/g,h=/^\[object .+?Constructor\]$/,d=Function.prototype,m=Object.prototype,y=d.toString,v=m.hasOwnProperty,g=RegExp("^"+y.call(v).replace(f,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=s},function(e,t,n,r){function i(e){return!!a&&a in e}var o=n(r),a=function(){var e=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();e.exports=i},function(e,t,n,r){var i=n(r),o=i["__core-js_shared__"];e.exports=o},function(e,t,n,r){function i(e){var t=this.__data__;if(o){var n=t[e];return n===a?void 0:n}return u.call(t,e)?t[e]:void 0}var o=n(r),a="__lodash_hash_undefined__",s=Object.prototype,u=s.hasOwnProperty;e.exports=i},function(e,t,n,r){function i(e){var t=this.__data__;return o?void 0!==t[e]:s.call(t,e)}var o=n(r),a=Object.prototype,s=a.hasOwnProperty;e.exports=i},function(e,t,n,r){function i(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=o&&void 0===t?a:t,this}var o=n(r),a="__lodash_hash_undefined__";e.exports=i},function(e,t,n,r){function i(e){var t=this.__data__,n=o(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():s.call(t,n,1),--this.size,!0}var o=n(r),a=Array.prototype,s=a.splice;e.exports=i},function(e,t,n,r){function i(e,t){for(var n=e.length;n--;)if(o(e[n][0],t))return n;return-1}var o=n(r);e.exports=i},function(e,t,n,r){function i(e){var t=this.__data__,n=o(t,e);return n<0?void 0:t[n][1]}var o=n(r);e.exports=i},function(e,t,n,r){function i(e){return o(this.__data__,e)>-1}var o=n(r);e.exports=i},function(e,t,n,r){function i(e,t){var n=this.__data__,r=o(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}var o=n(r);e.exports=i},function(e,t,n,r,i){var o=n(r),a=n(i),s=o(a,"Map");e.exports=s},function(e,t,n,r){function i(e){var t=o(this,e).delete(e);return this.size-=t?1:0,t}var o=n(r);e.exports=i},function(e,t,n,r){function i(e,t){var n=e.__data__;return o(t)?n["string"==typeof t?"string":"hash"]:n.map}var o=n(r);e.exports=i},function(e,t,n,r){function i(e){return o(this,e).get(e)}var o=n(r);e.exports=i},function(e,t,n,r){function i(e){return o(this,e).has(e)}var o=n(r);e.exports=i},function(e,t,n,r){function i(e,t){var n=o(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}var o=n(r);e.exports=i},function(e,t,n,r,i,o,a,s,u){function c(e){var t=this.__data__=new l(e);this.size=t.size}var l=n(r),p=n(i),f=n(o),h=n(a),d=n(s),m=n(u);c.prototype.clear=p,c.prototype.delete=f,c.prototype.get=h,c.prototype.has=d,c.prototype.set=m,e.exports=c},function(e,t,n,r){function i(){this.__data__=new o,this.size=0}var o=n(r);e.exports=i},function(e,t,n,r,i,o){function a(e,t){var n=this.__data__;if(n instanceof s){var r=n.__data__;if(!u||r.length0&&n(l)?t>1?o(l,t-1,n,r,i):a(i,l):r||(i[i.length]=l)}return i}var a=n(r),s=n(i);e.exports=o},function(e,t,n,r,i,o){function a(e){return c(e)||u(e)||!!(l&&e&&e[l])}var s=n(r),u=n(i),c=n(o),l=s?s.isConcatSpreadable:void 0;e.exports=a},function(e,t,n,r){function i(e,t,n){return t=a(void 0===t?e.length-1:t,0),function(){for(var r=arguments,i=-1,s=a(r.length-t,0),u=Array(s);++i1){for(var g=Array(m),x=0;x1){for(var D=Array(y),b=0;blabel{font-size:12px;font-weight:700;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;margin:-20px 15px 0 0;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .scheme-container .schemes>label select{min-width:130px;text-transform:uppercase}.swagger-ui .loading-container{padding:40px 0 60px}.swagger-ui .loading-container .loading{position:relative}.swagger-ui .loading-container .loading:after{font-size:10px;font-weight:700;position:absolute;top:50%;left:50%;content:\"loading\";-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);text-transform:uppercase;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .loading-container .loading:before{position:absolute;top:50%;left:50%;display:block;width:60px;height:60px;margin:-30px;content:\"\";-webkit-animation:rotation 1s infinite linear,opacity .5s;animation:rotation 1s infinite linear,opacity .5s;opacity:1;border:2px solid rgba(85,85,85,.1);border-top-color:rgba(0,0,0,.6);border-radius:100%;-webkit-backface-visibility:hidden;backface-visibility:hidden}@-webkit-keyframes rotation{to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes rotation{to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@-webkit-keyframes blinker{50%{opacity:0}}@keyframes blinker{50%{opacity:0}}.swagger-ui .btn{font-size:14px;font-weight:700;padding:5px 23px;transition:all .3s;border:2px solid #888;border-radius:4px;background:transparent;box-shadow:0 1px 2px rgba(0,0,0,.1);font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .btn[disabled]{cursor:not-allowed;opacity:.3}.swagger-ui .btn:hover{box-shadow:0 0 5px rgba(0,0,0,.3)}.swagger-ui .btn.cancel{border-color:#ff6060;font-family:Titillium Web,sans-serif;color:#ff6060}.swagger-ui .btn.authorize{line-height:1;display:inline;color:#49cc90;border-color:#49cc90}.swagger-ui .btn.authorize span{float:left;padding:4px 20px 0 0}.swagger-ui .btn.authorize svg{fill:#49cc90}.swagger-ui .btn.execute{-webkit-animation:pulse 2s infinite;animation:pulse 2s infinite;color:#fff;border-color:#4990e2}@-webkit-keyframes pulse{0%{color:#fff;background:#4990e2;box-shadow:0 0 0 0 rgba(73,144,226,.8)}70%{box-shadow:0 0 0 5px rgba(73,144,226,0)}to{color:#fff;background:#4990e2;box-shadow:0 0 0 0 rgba(73,144,226,0)}}@keyframes pulse{0%{color:#fff;background:#4990e2;box-shadow:0 0 0 0 rgba(73,144,226,.8)}70%{box-shadow:0 0 0 5px rgba(73,144,226,0)}to{color:#fff;background:#4990e2;box-shadow:0 0 0 0 rgba(73,144,226,0)}}.swagger-ui .btn-group{display:-webkit-box;display:-ms-flexbox;display:flex;padding:30px}.swagger-ui .btn-group .btn{-webkit-box-flex:1;-ms-flex:1;flex:1}.swagger-ui .btn-group .btn:first-child{border-radius:4px 0 0 4px}.swagger-ui .btn-group .btn:last-child{border-radius:0 4px 4px 0}.swagger-ui .authorization__btn{padding:0 10px;border:none;background:none}.swagger-ui .authorization__btn.locked{opacity:1}.swagger-ui .authorization__btn.unlocked{opacity:.4}.swagger-ui .expand-methods,.swagger-ui .expand-operation{border:none;background:none}.swagger-ui .expand-methods svg,.swagger-ui .expand-operation svg{width:20px;height:20px}.swagger-ui .expand-methods{padding:0 10px}.swagger-ui .expand-methods:hover svg{fill:#444}.swagger-ui .expand-methods svg{transition:all .3s;fill:#777}.swagger-ui button{cursor:pointer;outline:none}.swagger-ui select{font-size:14px;font-weight:700;padding:5px 40px 5px 10px;border:2px solid #41444e;border-radius:4px;background:#f7f7f7 url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyMCAyMCI+ICAgIDxwYXRoIGQ9Ik0xMy40MTggNy44NTljLjI3MS0uMjY4LjcwOS0uMjY4Ljk3OCAwIC4yNy4yNjguMjcyLjcwMSAwIC45NjlsLTMuOTA4IDMuODNjLS4yNy4yNjgtLjcwNy4yNjgtLjk3OSAwbC0zLjkwOC0zLjgzYy0uMjctLjI2Ny0uMjctLjcwMSAwLS45NjkuMjcxLS4yNjguNzA5LS4yNjguOTc4IDBMMTAgMTFsMy40MTgtMy4xNDF6Ii8+PC9zdmc+) right 10px center no-repeat;background-size:20px;box-shadow:0 1px 2px 0 rgba(0,0,0,.25);font-family:Titillium Web,sans-serif;color:#3b4151;-webkit-appearance:none;-moz-appearance:none;appearance:none}.swagger-ui select[multiple]{margin:5px 0;padding:5px;background:#f7f7f7}.swagger-ui .opblock-body select{min-width:230px}.swagger-ui label{font-size:12px;font-weight:700;margin:0 0 5px;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui input[type=email],.swagger-ui input[type=password],.swagger-ui input[type=search],.swagger-ui input[type=text]{min-width:100px;margin:5px 0;padding:8px 10px;border:1px solid #d9d9d9;border-radius:4px;background:#fff}.swagger-ui input[type=email].invalid,.swagger-ui input[type=password].invalid,.swagger-ui input[type=search].invalid,.swagger-ui input[type=text].invalid{-webkit-animation:shake .4s 1;animation:shake .4s 1;border-color:#f93e3e;background:#feebeb}@-webkit-keyframes shake{10%,90%{-webkit-transform:translate3d(-1px,0,0);transform:translate3d(-1px,0,0)}20%,80%{-webkit-transform:translate3d(2px,0,0);transform:translate3d(2px,0,0)}30%,50%,70%{-webkit-transform:translate3d(-4px,0,0);transform:translate3d(-4px,0,0)}40%,60%{-webkit-transform:translate3d(4px,0,0);transform:translate3d(4px,0,0)}}@keyframes shake{10%,90%{-webkit-transform:translate3d(-1px,0,0);transform:translate3d(-1px,0,0)}20%,80%{-webkit-transform:translate3d(2px,0,0);transform:translate3d(2px,0,0)}30%,50%,70%{-webkit-transform:translate3d(-4px,0,0);transform:translate3d(-4px,0,0)}40%,60%{-webkit-transform:translate3d(4px,0,0);transform:translate3d(4px,0,0)}}.swagger-ui textarea{font-size:12px;width:100%;min-height:280px;padding:10px;border:none;border-radius:4px;outline:none;background:hsla(0,0%,100%,.8);font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui textarea:focus{border:2px solid #61affe}.swagger-ui textarea.curl{font-size:12px;min-height:100px;margin:0;padding:10px;resize:none;border-radius:4px;background:#41444e;font-family:Source Code Pro,monospace;font-weight:600;color:#fff}.swagger-ui .checkbox{padding:5px 0 10px;transition:opacity .5s;color:#333}.swagger-ui .checkbox label{display:-webkit-box;display:-ms-flexbox;display:flex}.swagger-ui .checkbox p{font-weight:400!important;font-style:italic;margin:0!important;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .checkbox input[type=checkbox]{display:none}.swagger-ui .checkbox input[type=checkbox]+label>.item{position:relative;top:3px;display:inline-block;width:16px;height:16px;margin:0 8px 0 0;padding:5px;cursor:pointer;border-radius:1px;background:#e8e8e8;box-shadow:0 0 0 2px #e8e8e8;-webkit-box-flex:0;-ms-flex:none;flex:none}.swagger-ui .checkbox input[type=checkbox]+label>.item:active{-webkit-transform:scale(.9);transform:scale(.9)}.swagger-ui .checkbox input[type=checkbox]:checked+label>.item{background:#e8e8e8 url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='10' height='8' viewBox='3 7 10 8' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='%2341474E' fill-rule='evenodd' d='M6.333 15L3 11.667l1.333-1.334 2 2L11.667 7 13 8.333z'/%3E%3C/svg%3E\") 50% no-repeat}.swagger-ui .dialog-ux{position:fixed;z-index:9999;top:0;right:0;bottom:0;left:0}.swagger-ui .dialog-ux .backdrop-ux{position:fixed;top:0;right:0;bottom:0;left:0;background:rgba(0,0,0,.8)}.swagger-ui .dialog-ux .modal-ux{position:absolute;z-index:9999;top:50%;left:50%;width:100%;min-width:300px;max-width:650px;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);border:1px solid #ebebeb;border-radius:4px;background:#fff;box-shadow:0 10px 30px 0 rgba(0,0,0,.2)}.swagger-ui .dialog-ux .modal-ux-content{overflow-y:auto;max-height:540px;padding:20px}.swagger-ui .dialog-ux .modal-ux-content p{font-size:12px;margin:0 0 5px;color:#41444e;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .dialog-ux .modal-ux-content h4{font-size:18px;font-weight:600;margin:15px 0 0;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .dialog-ux .modal-ux-header{display:-webkit-box;display:-ms-flexbox;display:flex;padding:12px 0;border-bottom:1px solid #ebebeb;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.swagger-ui .dialog-ux .modal-ux-header .close-modal{padding:0 10px;border:none;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none}.swagger-ui .dialog-ux .modal-ux-header h3{font-size:20px;font-weight:600;margin:0;padding:0 20px;-webkit-box-flex:1;-ms-flex:1;flex:1;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .model{font-size:12px;font-weight:300;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .model-toggle{font-size:10px;position:relative;top:6px;display:inline-block;margin:auto .3em;cursor:pointer;transition:-webkit-transform .15s ease-in;transition:transform .15s ease-in;transition:transform .15s ease-in,-webkit-transform .15s ease-in;-webkit-transform:rotate(90deg);transform:rotate(90deg);-webkit-transform-origin:50% 50%;transform-origin:50% 50%}.swagger-ui .model-toggle.collapsed{-webkit-transform:rotate(0deg);transform:rotate(0deg)}.swagger-ui .model-toggle:after{display:block;width:20px;height:20px;content:\"\";background:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z'/%3E%3C/svg%3E\") 50% no-repeat;background-size:100%}.swagger-ui .model-jump-to-path{position:relative;cursor:pointer}.swagger-ui .model-jump-to-path .view-line-link{position:absolute;top:-.4em;cursor:pointer}.swagger-ui .model-title{position:relative}.swagger-ui .model-title:hover .model-hint{visibility:visible}.swagger-ui .model-hint{position:absolute;top:-1.8em;visibility:hidden;padding:.1em .5em;white-space:nowrap;color:#ebebeb;border-radius:4px;background:rgba(0,0,0,.7)}.swagger-ui section.models{margin:30px 0;border:1px solid rgba(59,65,81,.3);border-radius:4px}.swagger-ui section.models.is-open{padding:0 0 20px}.swagger-ui section.models.is-open h4{margin:0 0 5px;border-bottom:1px solid rgba(59,65,81,.3)}.swagger-ui section.models.is-open h4 svg{-webkit-transform:rotate(90deg);transform:rotate(90deg)}.swagger-ui section.models h4{font-size:16px;display:-webkit-box;display:-ms-flexbox;display:flex;margin:0;padding:10px 20px 10px 10px;cursor:pointer;transition:all .2s;font-family:Titillium Web,sans-serif;color:#777;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.swagger-ui section.models h4 svg{transition:all .4s}.swagger-ui section.models h4 span{-webkit-box-flex:1;-ms-flex:1;flex:1}.swagger-ui section.models h4:hover{background:rgba(0,0,0,.02)}.swagger-ui section.models h5{font-size:16px;margin:0 0 10px;font-family:Titillium Web,sans-serif;color:#777}.swagger-ui section.models .model-jump-to-path{position:relative;top:5px}.swagger-ui section.models .model-container{margin:0 20px 15px;transition:all .5s;border-radius:4px;background:rgba(0,0,0,.05)}.swagger-ui section.models .model-container:hover{background:rgba(0,0,0,.07)}.swagger-ui section.models .model-container:first-of-type{margin:20px}.swagger-ui section.models .model-container:last-of-type{margin:0 20px}.swagger-ui section.models .model-box{background:none}.swagger-ui .model-box{padding:10px;border-radius:4px;background:rgba(0,0,0,.1)}.swagger-ui .model-box .model-jump-to-path{position:relative;top:4px}.swagger-ui .model-title{font-size:16px;font-family:Titillium Web,sans-serif;color:#555}.swagger-ui span>span.model,.swagger-ui span>span.model .brace-close{padding:0 0 0 10px}.swagger-ui .prop-type{color:#55a}.swagger-ui .prop-enum{display:block}.swagger-ui .prop-format{color:#999}.swagger-ui table{width:100%;padding:0 10px;border-collapse:collapse}.swagger-ui table.model tbody tr td{padding:0;vertical-align:top}.swagger-ui table.model tbody tr td:first-of-type{width:100px;padding:0}.swagger-ui table.headers td{font-size:12px;font-weight:300;vertical-align:middle;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui table tbody tr td{padding:10px 0 0;vertical-align:top}.swagger-ui table tbody tr td:first-of-type{width:20%;padding:10px 0}.swagger-ui table thead tr td,.swagger-ui table thead tr th{font-size:12px;font-weight:700;padding:12px 0;text-align:left;border-bottom:1px solid rgba(59,65,81,.2);font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .parameters-col_description p{font-size:14px;margin:0;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .parameters-col_description input[type=text]{width:100%;max-width:340px}.swagger-ui .parameter__name{font-size:16px;font-weight:400;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .parameter__name.required{font-weight:700}.swagger-ui .parameter__name.required:after{font-size:10px;position:relative;top:-6px;padding:5px;content:\"required\";color:rgba(255,0,0,.6)}.swagger-ui .parameter__in{font-size:12px;font-style:italic;font-family:Source Code Pro,monospace;font-weight:600;color:#888}.swagger-ui .table-container{padding:20px}.swagger-ui .topbar{padding:8px 30px;background-color:#89bf04}.swagger-ui .topbar .topbar-wrapper{-ms-flex-align:center}.swagger-ui .topbar .topbar-wrapper,.swagger-ui .topbar a{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;align-items:center}.swagger-ui .topbar a{font-size:1.5em;font-weight:700;max-width:300px;text-decoration:none;-webkit-box-flex:1;-ms-flex:1;flex:1;-ms-flex-align:center;font-family:Titillium Web,sans-serif;color:#fff}.swagger-ui .topbar a span{margin:0;padding:0 10px}.swagger-ui .topbar .download-url-wrapper{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-flex:3;-ms-flex:3;flex:3}.swagger-ui .topbar .download-url-wrapper input[type=text]{width:100%;min-width:350px;margin:0;border:2px solid #547f00;border-radius:4px 0 0 4px;outline:none}.swagger-ui .topbar .download-url-wrapper .download-url-button{font-size:16px;font-weight:700;padding:4px 40px;border:none;border-radius:0 4px 4px 0;background:#547f00;font-family:Titillium Web,sans-serif;color:#fff}.swagger-ui .info{margin:50px 0}.swagger-ui .info hgroup.main{margin:0 0 20px}.swagger-ui .info hgroup.main a{font-size:12px}.swagger-ui .info li,.swagger-ui .info p,.swagger-ui .info table{font-size:14px;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .info h1,.swagger-ui .info h2,.swagger-ui .info h3,.swagger-ui .info h4,.swagger-ui .info h5{font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .info code{padding:3px 5px;border-radius:4px;background:rgba(0,0,0,.05);font-family:Source Code Pro,monospace;font-weight:600;color:#9012fe}.swagger-ui .info a{font-size:14px;transition:all .4s;font-family:Open Sans,sans-serif;color:#4990e2}.swagger-ui .info a:hover{color:#1f69c0}.swagger-ui .info>div{margin:0 0 5px}.swagger-ui .info .base-url{font-size:12px;font-weight:300!important;margin:0;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .info .title{font-size:36px;margin:0;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .info .title small{font-size:10px;position:relative;top:-5px;display:inline-block;margin:0 0 0 5px;padding:2px 4px;vertical-align:super;border-radius:57px;background:#7d8492}.swagger-ui .info .title small pre{margin:0;font-family:Titillium Web,sans-serif;color:#fff}.swagger-ui .auth-btn-wrapper{display:-webkit-box;display:-ms-flexbox;display:flex;padding:10px 0;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center}.swagger-ui .auth-wrapper{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-flex:1;-ms-flex:1;flex:1;-webkit-box-pack:end;-ms-flex-pack:end;justify-content:flex-end}.swagger-ui .auth-wrapper .authorize{padding-right:20px}.swagger-ui .auth-container{margin:0 0 10px;padding:10px 20px;border-bottom:1px solid #ebebeb}.swagger-ui .auth-container:last-of-type{margin:0;padding:10px 20px;border:0}.swagger-ui .auth-container h4{margin:5px 0 15px!important}.swagger-ui .auth-container .wrapper{margin:0;padding:0}.swagger-ui .auth-container input[type=password],.swagger-ui .auth-container input[type=text]{min-width:230px}.swagger-ui .auth-container .errors{font-size:12px;padding:10px;border-radius:4px;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .scopes h2{font-size:14px;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .scope-def{padding:0 0 20px}.swagger-ui .errors-wrapper{margin:20px;padding:10px 20px;-webkit-animation:scaleUp .5s;animation:scaleUp .5s;border:2px solid #f93e3e;border-radius:4px;background:rgba(249,62,62,.1)}.swagger-ui .errors-wrapper .error-wrapper{margin:0 0 10px}.swagger-ui .errors-wrapper .errors h4{font-size:14px;margin:0;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .errors-wrapper .errors small{color:#666}.swagger-ui .errors-wrapper hgroup{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.swagger-ui .errors-wrapper hgroup h4{font-size:20px;margin:0;-webkit-box-flex:1;-ms-flex:1;flex:1;font-family:Titillium Web,sans-serif;color:#3b4151}@-webkit-keyframes scaleUp{0%{-webkit-transform:scale(.8);transform:scale(.8);opacity:0}to{-webkit-transform:scale(1);transform:scale(1);opacity:1}}@keyframes scaleUp{0%{-webkit-transform:scale(.8);transform:scale(.8);opacity:0}to{-webkit-transform:scale(1);transform:scale(1);opacity:1}}",""]); +},function(e,t){e.exports=function(){var e=[];return e.toString=function(){for(var e=[],t=0;t=0&&D.splice(t,1)}function a(e){var t=document.createElement("style");return t.type="text/css",s(e,t),t}function u(e){var t=document.createElement("link");return t.rel="stylesheet",s(e,t),t}function c(e,t){var r,i,n;if(t.singleton){var s=y++;r=x||(x=a(t)),i=l.bind(null,r,s,!1),n=l.bind(null,r,s,!0)}else e.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(r=u(t),i=p.bind(null,r),n=function(){o(r),r.href&&URL.revokeObjectURL(r.href)}):(r=a(t),i=h.bind(null,r),n=function(){o(r)});return i(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;i(e=t)}else n()}}function l(e,t,r,i){var n=r?"":i.css;if(e.styleSheet)e.styleSheet.cssText=b(t,n);else{var s=document.createTextNode(n),o=e.childNodes;o[t]&&e.removeChild(o[t]),o.length?e.insertBefore(s,o[t]):e.appendChild(s)}}function h(e,t){var r=t.css,i=t.media;t.sourceMap;if(i&&e.setAttribute("media",i),e.styleSheet)e.styleSheet.cssText=r;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(r))}}function p(e,t){var r=t.css,i=(t.media,t.sourceMap);i&&(r+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(i))))+" */");var n=new Blob([r],{type:"text/css"}),s=e.href;e.href=URL.createObjectURL(n),s&&URL.revokeObjectURL(s)}var f={},d=function(e){var t;return function(){return"undefined"==typeof t&&(t=e.apply(this,arguments)),t}},m=d(function(){return/msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())}),g=d(function(){return document.head||document.getElementsByTagName("head")[0]}),x=null,y=0,D=[];e.exports=function(e,t){t=t||{},"undefined"==typeof t.singleton&&(t.singleton=m()),"undefined"==typeof t.insertAt&&(t.insertAt="bottom");var r=n(e);return i(r,t),function(e){for(var s=[],o=0;o=400?(n.updateLoadingStatus("failedConfig"),n.updateLoadingStatus("failedConfig"),n.updateUrl(""),console.error(r.statusText+" "+e),t(null)):t(c(r.text))}var n=r.specActions;if(e)return n.downloadConfig(e).then(i,i)}}},i={getLocalConfig:function(){return c(u.default)}};return{statePlugins:{spec:{actions:r,selectors:i}}}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n;var s=r(41),o=i(s),a=r(76),u=i(a),c=function(e,t){try{return o.default.safeLoad(e)}catch(e){return t&&t.errActions.newThrownErr(new Error(e)),{}}}},function(e,t,r){"use strict";var i=r(42);e.exports=i},function(e,t,r){"use strict";function i(e){return function(){throw new Error("Function "+e+" is deprecated and cannot be used.")}}var n=r(43),s=r(75);e.exports.Type=r(49),e.exports.Schema=r(48),e.exports.FAILSAFE_SCHEMA=r(52),e.exports.JSON_SCHEMA=r(51),e.exports.CORE_SCHEMA=r(50),e.exports.DEFAULT_SAFE_SCHEMA=r(47),e.exports.DEFAULT_FULL_SCHEMA=r(70),e.exports.load=n.load,e.exports.loadAll=n.loadAll,e.exports.safeLoad=n.safeLoad,e.exports.safeLoadAll=n.safeLoadAll,e.exports.dump=s.dump,e.exports.safeDump=s.safeDump,e.exports.YAMLException=r(45),e.exports.MINIMAL_SCHEMA=r(52),e.exports.SAFE_SCHEMA=r(47),e.exports.DEFAULT_SCHEMA=r(70),e.exports.scan=i("scan"),e.exports.parse=i("parse"),e.exports.compose=i("compose"),e.exports.addConstructor=i("addConstructor")},function(e,t,r){"use strict";function i(e){return 10===e||13===e}function n(e){return 9===e||32===e}function s(e){return 9===e||32===e||10===e||13===e}function o(e){return 44===e||91===e||93===e||123===e||125===e}function a(e){var t;return 48<=e&&e<=57?e-48:(t=32|e,97<=t&&t<=102?t-97+10:-1)}function u(e){return 120===e?2:117===e?4:85===e?8:0}function c(e){return 48<=e&&e<=57?e-48:-1}function l(e){return 48===e?"\0":97===e?"":98===e?"\b":116===e?"\t":9===e?"\t":110===e?"\n":118===e?"\v":102===e?"\f":114===e?"\r":101===e?"":32===e?" ":34===e?'"':47===e?"/":92===e?"\\":78===e?"…":95===e?" ":76===e?"\u2028":80===e?"\u2029":""}function h(e){return e<=65535?String.fromCharCode(e):String.fromCharCode((e-65536>>10)+55296,(e-65536&1023)+56320)}function p(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||Y,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.documents=[]}function f(e,t){return new j(t,new X(e.filename,e.input,e.position,e.line,e.position-e.lineStart))}function d(e,t){throw f(e,t)}function m(e,t){e.onWarning&&e.onWarning.call(null,f(e,t))}function g(e,t,r,i){var n,s,o,a;if(t1&&(e.result+=z.repeat("\n",t-1))}function E(e,t,r){var a,u,c,l,h,p,f,d,m,x=e.kind,y=e.result;if(m=e.input.charCodeAt(e.position),s(m)||o(m)||35===m||38===m||42===m||33===m||124===m||62===m||39===m||34===m||37===m||64===m||96===m)return!1;if((63===m||45===m)&&(u=e.input.charCodeAt(e.position+1),s(u)||r&&o(u)))return!1;for(e.kind="scalar",e.result="",c=l=e.position,h=!1;0!==m;){if(58===m){if(u=e.input.charCodeAt(e.position+1),s(u)||r&&o(u))break}else if(35===m){if(a=e.input.charCodeAt(e.position-1),s(a))break}else{if(e.position===e.lineStart&&v(e)||r&&o(m))break;if(i(m)){if(p=e.line,f=e.lineStart,d=e.lineIndent,b(e,!1,-1),e.lineIndent>=t){h=!0,m=e.input.charCodeAt(e.position);continue}e.position=l,e.line=p,e.lineStart=f,e.lineIndent=d;break}}h&&(g(e,c,l,!1),w(e,e.line-p),c=l=e.position,h=!1),n(m)||(l=e.position+1),m=e.input.charCodeAt(++e.position)}return g(e,c,l,!1),!!e.result||(e.kind=x,e.result=y,!1)}function k(e,t){var r,n,s;if(r=e.input.charCodeAt(e.position),39!==r)return!1;for(e.kind="scalar",e.result="",e.position++,n=s=e.position;0!==(r=e.input.charCodeAt(e.position));)if(39===r){if(g(e,n,e.position,!0),r=e.input.charCodeAt(++e.position),39!==r)return!0;n=e.position,e.position++,s=e.position}else i(r)?(g(e,n,s,!0),w(e,b(e,!1,t)),n=s=e.position):e.position===e.lineStart&&v(e)?d(e,"unexpected end of the document within a single quoted scalar"):(e.position++,s=e.position);d(e,"unexpected end of the stream within a single quoted scalar")}function A(e,t){var r,n,s,o,c,l;if(l=e.input.charCodeAt(e.position),34!==l)return!1;for(e.kind="scalar",e.result="",e.position++,r=n=e.position;0!==(l=e.input.charCodeAt(e.position));){if(34===l)return g(e,r,e.position,!0),e.position++,!0;if(92===l){if(g(e,r,e.position,!0),l=e.input.charCodeAt(++e.position),i(l))b(e,!1,t);else if(l<256&&ne[l])e.result+=se[l],e.position++;else if((c=u(l))>0){for(s=c,o=0;s>0;s--)l=e.input.charCodeAt(++e.position),(c=a(l))>=0?o=(o<<4)+c:d(e,"expected hexadecimal character");e.result+=h(o),e.position++}else d(e,"unknown escape sequence");r=n=e.position}else i(l)?(g(e,r,n,!0),w(e,b(e,!1,t)),r=n=e.position):e.position===e.lineStart&&v(e)?d(e,"unexpected end of the document within a double quoted scalar"):(e.position++,n=e.position)}d(e,"unexpected end of the stream within a double quoted scalar")}function C(e,t){var r,i,n,o,a,u,c,l,h,p,f,m=!0,g=e.tag,x=e.anchor,D={};if(f=e.input.charCodeAt(e.position),91===f)o=93,c=!1,i=[];else{if(123!==f)return!1;o=125,c=!0,i={}}for(null!==e.anchor&&(e.anchorMap[e.anchor]=i),f=e.input.charCodeAt(++e.position);0!==f;){if(b(e,!0,t),f=e.input.charCodeAt(e.position),f===o)return e.position++,e.tag=g,e.anchor=x,e.kind=c?"mapping":"sequence",e.result=i,!0;m||d(e,"missed comma between flow collection entries"),h=l=p=null,a=u=!1,63===f&&(n=e.input.charCodeAt(e.position+1),s(n)&&(a=u=!0,e.position++,b(e,!0,t))),r=e.line,P(e,t,W,!1,!0),h=e.tag,l=e.result,b(e,!0,t),f=e.input.charCodeAt(e.position),!u&&e.line!==r||58!==f||(a=!0,f=e.input.charCodeAt(++e.position),b(e,!0,t),P(e,t,W,!1,!0),p=e.result),c?y(e,i,D,h,l,p):a?i.push(y(e,null,D,h,l,p)):i.push(l),b(e,!0,t),f=e.input.charCodeAt(e.position),44===f?(m=!0,f=e.input.charCodeAt(++e.position)):m=!1}d(e,"unexpected end of the stream within a flow collection")}function S(e,t){var r,s,o,a,u=V,l=!1,h=!1,p=t,f=0,m=!1;if(a=e.input.charCodeAt(e.position),124===a)s=!1;else{if(62!==a)return!1;s=!0}for(e.kind="scalar",e.result="";0!==a;)if(a=e.input.charCodeAt(++e.position),43===a||45===a)V===u?u=43===a?Z:$:d(e,"repeat of a chomping mode identifier");else{if(!((o=c(a))>=0))break;0===o?d(e,"bad explicit indentation width of a block scalar; it cannot be less than one"):h?d(e,"repeat of an indentation width identifier"):(p=t+o-1,h=!0)}if(n(a)){do a=e.input.charCodeAt(++e.position);while(n(a));if(35===a)do a=e.input.charCodeAt(++e.position);while(!i(a)&&0!==a)}for(;0!==a;){for(D(e),e.lineIndent=0,a=e.input.charCodeAt(e.position);(!h||e.lineIndentp&&(p=e.lineIndent),i(a))f++;else{if(e.lineIndentt)&&0!==n)d(e,"bad indentation of a sequence entry");else if(e.lineIndentt)&&(P(e,t,G,!0,o)&&(D?g=e.result:x=e.result),D||(y(e,p,f,m,g,x,a,u),m=g=x=null),b(e,!0,-1),c=e.input.charCodeAt(e.position)),e.lineIndent>t&&0!==c)d(e,"bad indentation of a mapping entry");else if(e.lineIndentt?f=1:e.lineIndent===t?f=0:e.lineIndentt?f=1:e.lineIndent===t?f=0:e.lineIndent tag; it should be "'+l.kind+'", not "'+e.kind+'"'),l.resolve(e.result)?(e.result=l.construct(e.result),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):d(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):d(e,"unknown tag !<"+e.tag+">");return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||g}function M(e){var t,r,o,a,u=e.position,c=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap={},e.anchorMap={};0!==(a=e.input.charCodeAt(e.position))&&(b(e,!0,-1),a=e.input.charCodeAt(e.position),!(e.lineIndent>0||37!==a));){for(c=!0,a=e.input.charCodeAt(++e.position),t=e.position;0!==a&&!s(a);)a=e.input.charCodeAt(++e.position);for(r=e.input.slice(t,e.position),o=[],r.length<1&&d(e,"directive name must not be less than one character in length");0!==a;){for(;n(a);)a=e.input.charCodeAt(++e.position);if(35===a){do a=e.input.charCodeAt(++e.position);while(0!==a&&!i(a));break}if(i(a))break;for(t=e.position;0!==a&&!s(a);)a=e.input.charCodeAt(++e.position);o.push(e.input.slice(t,e.position))}0!==a&&D(e),K.call(ae,r)?ae[r](e,r,o):m(e,'unknown document directive "'+r+'"')}return b(e,!0,-1),0===e.lineIndent&&45===e.input.charCodeAt(e.position)&&45===e.input.charCodeAt(e.position+1)&&45===e.input.charCodeAt(e.position+2)?(e.position+=3,b(e,!0,-1)):c&&d(e,"directives end mark is expected"),P(e,e.lineIndent-1,G,!1,!0),b(e,!0,-1),e.checkLineBreaks&&ee.test(e.input.slice(u,e.position))&&m(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&v(e)?void(46===e.input.charCodeAt(e.position)&&(e.position+=3,b(e,!0,-1))):void(e.position0&&"\0\r\n…\u2028\u2029".indexOf(this.buffer.charAt(i-1))===-1;)if(i-=1,this.position-i>t/2-1){r=" ... ",i+=5;break}for(s="",o=this.position;ot/2-1){s=" ... ",o-=5;break}return a=this.buffer.slice(i,o),n.repeat(" ",e)+r+a+s+"\n"+n.repeat(" ",e+this.position-i+r.length)+"^"},i.prototype.toString=function(e){var t,r="";return this.name&&(r+='in "'+this.name+'" '),r+="at line "+(this.line+1)+", column "+(this.column+1),e||(t=this.getSnippet(),t&&(r+=":\n"+t)),r},e.exports=i},function(e,t,r){"use strict";var i=r(48);e.exports=new i({include:[r(50)],implicit:[r(60),r(61)],explicit:[r(62),r(67),r(68),r(69)]})},function(e,t,r){"use strict";function i(e,t,r){var n=[];return e.include.forEach(function(e){r=i(e,t,r)}),e[t].forEach(function(e){r.forEach(function(t,r){t.tag===e.tag&&t.kind===e.kind&&n.push(r)}),r.push(e)}),r.filter(function(e,t){return n.indexOf(t)===-1})}function n(){function e(e){i[e.kind][e.tag]=i.fallback[e.tag]=e}var t,r,i={scalar:{},sequence:{},mapping:{},fallback:{}};for(t=0,r=arguments.length;t=0&&(t=t.slice(1)),".inf"===t?1===r?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===t?NaN:t.indexOf(":")>=0?(t.split(":").forEach(function(e){n.unshift(parseFloat(e,10))}),t=0,i=1,n.forEach(function(e){t+=e*i,i*=60}),r*t):r*parseFloat(t,10)}function s(e,t){var r;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(a.isNegativeZero(e))return"-0.0";return r=e.toString(10),l.test(r)?r.replace("e",".e"):r}function o(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!==0||a.isNegativeZero(e))}var a=r(44),u=r(49),c=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),l=/^[-+]?[0-9]+e/;e.exports=new u("tag:yaml.org,2002:float",{kind:"scalar",resolve:i,construct:n,predicate:o,represent:s,defaultStyle:"lowercase"})},function(e,t,r){"use strict";function i(e){return null!==e&&(null!==a.exec(e)||null!==u.exec(e))}function n(e){var t,r,i,n,s,o,c,l,h,p,f=0,d=null;if(t=a.exec(e),null===t&&(t=u.exec(e)),null===t)throw new Error("Date resolve error");if(r=+t[1],i=+t[2]-1,n=+t[3],!t[4])return new Date(Date.UTC(r,i,n));if(s=+t[4],o=+t[5],c=+t[6],t[7]){for(f=t[7].slice(0,3);f.length<3;)f+="0";f=+f}return t[9]&&(l=+t[10],h=+(t[11]||0),d=6e4*(60*l+h),"-"===t[9]&&(d=-d)),p=new Date(Date.UTC(r,i,n,s,o,c,f)),d&&p.setTime(p.getTime()-d),p}function s(e){return e.toISOString()}var o=r(49),a=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),u=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");e.exports=new o("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:i,construct:n,instanceOf:Date,represent:s})},function(e,t,r){"use strict";function i(e){return"<<"===e||null===e}var n=r(49);e.exports=new n("tag:yaml.org,2002:merge",{kind:"scalar",resolve:i})},function(e,t,r){function i(e){if(null===e)return!1;var t,r,i=0,n=e.length,s=c;for(r=0;r64)){if(t<0)return!1;i+=6}return i%8===0}function n(e){var t,r,i=e.replace(/[\r\n=]/g,""),n=i.length,s=c,o=0,u=[];for(t=0;t>16&255),u.push(o>>8&255),u.push(255&o)),o=o<<6|s.indexOf(i.charAt(t));return r=n%4*6,0===r?(u.push(o>>16&255),u.push(o>>8&255),u.push(255&o)):18===r?(u.push(o>>10&255),u.push(o>>2&255)):12===r&&u.push(o>>4&255),a?a.from?a.from(u):new a(u):u}function s(e){var t,r,i="",n=0,s=e.length,o=c;for(t=0;t>18&63],i+=o[n>>12&63],i+=o[n>>6&63],i+=o[63&n]),n=(n<<8)+e[t];return r=s%3,0===r?(i+=o[n>>18&63],i+=o[n>>12&63],i+=o[n>>6&63],i+=o[63&n]):2===r?(i+=o[n>>10&63],i+=o[n>>4&63],i+=o[n<<2&63],i+=o[64]):1===r&&(i+=o[n>>2&63],i+=o[n<<4&63],i+=o[64],i+=o[64]),i}function o(e){return a&&a.isBuffer(e)}var a;try{a=r(63).Buffer}catch(e){}var u=r(49),c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";e.exports=new u("tag:yaml.org,2002:binary",{kind:"scalar",resolve:i,construct:n,predicate:o,represent:s})},function(e,t,r){(function(e){/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +"use strict";function i(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}function n(){return o.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function s(e,t){if(n()=n())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n().toString(16)+" bytes");return 0|e}function g(e){return+e!=e&&(e=0),o.alloc(+e)}function x(e,t){if(o.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return K(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return q(e).length;default:if(i)return K(e).length;t=(""+t).toLowerCase(),i=!0}}function y(e,t,r){var i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if(r>>>=0,t>>>=0,r<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return P(this,t,r);case"utf8":case"utf-8":return T(this,t,r);case"ascii":return N(this,t,r);case"latin1":case"binary":return I(this,t,r);case"base64":return F(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function D(e,t,r){var i=e[t];e[t]=e[r],e[r]=i}function b(e,t,r,i,n){if(0===e.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=o.from(t,i)),o.isBuffer(t))return 0===t.length?-1:v(e,t,r,i,n);if("number"==typeof t)return t&=255,o.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):v(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function v(e,t,r,i,n){function s(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}var o=1,a=e.length,u=t.length;if(void 0!==i&&(i=String(i).toLowerCase(),"ucs2"===i||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;o=2,a/=2,u/=2,r/=2}var c;if(n){var l=-1;for(c=r;ca&&(r=a-u),c=r;c>=0;c--){for(var h=!0,p=0;pn&&(i=n)):i=n;var s=t.length;if(s%2!==0)throw new TypeError("Invalid hex string");i>s/2&&(i=s/2);for(var o=0;o239?4:s>223?3:s>191?2:1;if(n+a<=r){var u,c,l,h;switch(a){case 1:s<128&&(o=s);break;case 2:u=e[n+1],128===(192&u)&&(h=(31&s)<<6|63&u,h>127&&(o=h));break;case 3:u=e[n+1],c=e[n+2],128===(192&u)&&128===(192&c)&&(h=(15&s)<<12|(63&u)<<6|63&c,h>2047&&(h<55296||h>57343)&&(o=h));break;case 4:u=e[n+1],c=e[n+2],l=e[n+3],128===(192&u)&&128===(192&c)&&128===(192&l)&&(h=(15&s)<<18|(63&u)<<12|(63&c)<<6|63&l,h>65535&&h<1114112&&(o=h))}}null===o?(o=65533,a=1):o>65535&&(o-=65536,i.push(o>>>10&1023|55296),o=56320|1023&o),i.push(o),n+=a}return B(i)}function B(e){var t=e.length;if(t<=ee)return String.fromCharCode.apply(String,e);for(var r="",i=0;ii)&&(r=i);for(var n="",s=t;sr)throw new RangeError("Trying to access beyond buffer length")}function L(e,t,r,i,n,s){if(!o.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||te.length)throw new RangeError("Index out of range")}function R(e,t,r,i){t<0&&(t=65535+t+1);for(var n=0,s=Math.min(e.length-r,2);n>>8*(i?n:1-n)}function U(e,t,r,i){t<0&&(t=4294967295+t+1);for(var n=0,s=Math.min(e.length-r,4);n>>8*(i?n:3-n)&255}function _(e,t,r,i,n,s){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function z(e,t,r,i,n){return n||_(e,t,r,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(e,t,r,i,23,4),r+4}function j(e,t,r,i,n){return n||_(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(e,t,r,i,52,8),r+8}function X(e){if(e=J(e).replace(te,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function J(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function Y(e){return e<16?"0"+e.toString(16):e.toString(16)}function K(e,t){t=t||1/0;for(var r,i=e.length,n=null,s=[],o=0;o55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===i){(t-=3)>-1&&s.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&s.push(239,191,189),n=r;continue}r=(n-55296<<10|r-56320)+65536}else n&&(t-=3)>-1&&s.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function W(e){for(var t=[],r=0;r>8,n=r%256,s.push(n),s.push(i);return s}function q(e){return $.toByteArray(X(e))}function G(e,t,r,i){for(var n=0;n=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function V(e){return e!==e}var $=r(64),Z=r(65),Q=r(66);t.Buffer=o,t.SlowBuffer=g,t.INSPECT_MAX_BYTES=50,o.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:i(),t.kMaxLength=n(),o.poolSize=8192,o._augment=function(e){return e.__proto__=o.prototype,e},o.from=function(e,t,r){return a(null,e,t,r)},o.TYPED_ARRAY_SUPPORT&&(o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0})),o.alloc=function(e,t,r){return c(null,e,t,r)},o.allocUnsafe=function(e){return l(null,e)},o.allocUnsafeSlow=function(e){return l(null,e)},o.isBuffer=function(e){return!(null==e||!e._isBuffer)},o.compare=function(e,t){if(!o.isBuffer(e)||!o.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,i=t.length,n=0,s=Math.min(r,i);n0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),""},o.prototype.compare=function(e,t,r,i,n){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===n&&(n=this.length),t<0||r>e.length||i<0||n>this.length)throw new RangeError("out of range index");if(i>=n&&t>=r)return 0;if(i>=n)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,i>>>=0,n>>>=0,this===e)return 0;for(var s=n-i,a=r-t,u=Math.min(s,a),c=this.slice(i,n),l=e.slice(t,r),h=0;hn)&&(r=n),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var s=!1;;)switch(i){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return E(this,e,t,r);case"ascii":return k(this,e,t,r);case"latin1":case"binary":return A(this,e,t,r);case"base64":return C(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,r);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),s=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ee=4096;o.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),t<0?(t+=r,t<0&&(t=0)):t>r&&(t=r),t0&&(n*=256);)i+=this[e+--t]*n;return i},o.prototype.readUInt8=function(e,t){return t||O(e,1,this.length),this[e]},o.prototype.readUInt16LE=function(e,t){return t||O(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUInt16BE=function(e,t){return t||O(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUInt32LE=function(e,t){return t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},o.prototype.readUInt32BE=function(e,t){return t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||O(e,t,this.length);for(var i=this[e],n=1,s=0;++s=n&&(i-=Math.pow(2,8*t)),i},o.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||O(e,t,this.length);for(var i=t,n=1,s=this[e+--i];i>0&&(n*=256);)s+=this[e+--i]*n;return n*=128,s>=n&&(s-=Math.pow(2,8*t)),s},o.prototype.readInt8=function(e,t){return t||O(e,1,this.length),128&this[e]?(255-this[e]+1)*-1:this[e]},o.prototype.readInt16LE=function(e,t){t||O(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt16BE=function(e,t){t||O(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt32LE=function(e,t){return t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readFloatLE=function(e,t){return t||O(e,4,this.length),Z.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return t||O(e,4,this.length),Z.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return t||O(e,8,this.length),Z.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return t||O(e,8,this.length),Z.read(this,e,!1,52,8)},o.prototype.writeUIntLE=function(e,t,r,i){if(e=+e,t|=0,r|=0,!i){var n=Math.pow(2,8*r)-1;L(this,e,t,r,n,0)}var s=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+s]=e/o&255;return t+r},o.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||L(this,e,t,1,255,0),o.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},o.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||L(this,e,t,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):R(this,e,t,!0),t+2},o.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||L(this,e,t,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):R(this,e,t,!1),t+2},o.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||L(this,e,t,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):U(this,e,t,!0),t+4},o.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||L(this,e,t,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):U(this,e,t,!1),t+4},o.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t|=0,!i){var n=Math.pow(2,8*r-1);L(this,e,t,r,n-1,-n)}var s=0,o=1,a=0;for(this[t]=255&e;++s>0)-a&255;return t+r},o.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t|=0,!i){var n=Math.pow(2,8*r-1);L(this,e,t,r,n-1,-n)}var s=r-1,o=1,a=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===a&&0!==this[t+s+1]&&(a=1),this[t+s]=(e/o>>0)-a&255;return t+r},o.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||L(this,e,t,1,127,-128),o.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||L(this,e,t,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):R(this,e,t,!0),t+2},o.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||L(this,e,t,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):R(this,e,t,!1),t+2},o.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||L(this,e,t,4,2147483647,-2147483648),o.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):U(this,e,t,!0),t+4},o.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||L(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),o.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):U(this,e,t,!1),t+4},o.prototype.writeFloatLE=function(e,t,r){return z(this,e,t,!0,r)},o.prototype.writeFloatBE=function(e,t,r){return z(this,e,t,!1,r)},o.prototype.writeDoubleLE=function(e,t,r){return j(this,e,t,!0,r)},o.prototype.writeDoubleBE=function(e,t,r){return j(this,e,t,!1,r)},o.prototype.copy=function(e,t,r,i){if(r||(r=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t=0;--n)e[n+t]=this[n+r];else if(s<1e3||!o.TYPED_ARRAY_SUPPORT)for(n=0;n>>=0,r=void 0===r?this.length:r>>>0,e||(e=0);var s;if("number"==typeof e)for(s=t;s0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function i(e){return 3*e.length/4-r(e)}function n(e){var t,i,n,s,o,a,u=e.length;o=r(e),a=new l(3*u/4-o),n=o>0?u-4:u;var h=0;for(t=0,i=0;t>16&255,a[h++]=s>>8&255,a[h++]=255&s;return 2===o?(s=c[e.charCodeAt(t)]<<2|c[e.charCodeAt(t+1)]>>4,a[h++]=255&s):1===o&&(s=c[e.charCodeAt(t)]<<10|c[e.charCodeAt(t+1)]<<4|c[e.charCodeAt(t+2)]>>2,a[h++]=s>>8&255,a[h++]=255&s),a}function s(e){return u[e>>18&63]+u[e>>12&63]+u[e>>6&63]+u[63&e]}function o(e,t,r){for(var i,n=[],o=t;ol?l:c+a));return 1===i?(t=e[r-1],n+=u[t>>2],n+=u[t<<4&63],n+="=="):2===i&&(t=(e[r-2]<<8)+e[r-1],n+=u[t>>10],n+=u[t>>4&63],n+=u[t<<2&63],n+="="),s.push(n),s.join("")}t.byteLength=i,t.toByteArray=n,t.fromByteArray=a;for(var u=[],c=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=0,f=h.length;p>1,l=-7,h=r?n-1:0,p=r?-1:1,f=e[t+h];for(h+=p,s=f&(1<<-l)-1,f>>=-l,l+=a;l>0;s=256*s+e[t+h],h+=p,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=i;l>0;o=256*o+e[t+h],h+=p,l-=8);if(0===s)s=1-c;else{if(s===u)return o?NaN:(f?-1:1)*(1/0);o+=Math.pow(2,i),s-=c}return(f?-1:1)*o*Math.pow(2,s-i)},t.write=function(e,t,r,i,n,s){var o,a,u,c=8*s-n-1,l=(1<>1,p=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,f=i?0:s-1,d=i?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=l):(o=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-o))<1&&(o--,u*=2),t+=o+h>=1?p/u:p*Math.pow(2,1-h),t*u>=2&&(o++,u/=2),o+h>=l?(a=0,o=l):o+h>=1?(a=(t*u-1)*Math.pow(2,n),o+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,n),o=0));n>=8;e[r+f]=255&a,f+=d,a/=256,n-=8);for(o=o<0;e[r+f]=255&o,f+=d,o/=256,c-=8);e[r+f-d]|=128*m}},function(e,t){var r={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},function(e,t,r){"use strict";function i(e){if(null===e)return!0;var t,r,i,n,s,u=[],c=e;for(t=0,r=c.length;t3)return!1;if("/"!==t[t.length-i.length-1])return!1}return!0}function n(e){var t=e,r=/\/([gim]*)$/.exec(e),i="";return"/"===t[0]&&(r&&(i=r[1]),t=t.slice(1,t.length-i.length-1)),new RegExp(t,i)}function s(e){var t="/"+e.source+"/";return e.global&&(t+="g"),e.multiline&&(t+="m"),e.ignoreCase&&(t+="i"),t}function o(e){return"[object RegExp]"===Object.prototype.toString.call(e)}var a=r(49);e.exports=new a("tag:yaml.org,2002:js/regexp",{kind:"scalar",resolve:i,construct:n,predicate:o,represent:s})},function(e,t,r){function i(e){if(null===e)return!1;try{var t="("+e+")",r=a.parse(t,{range:!0});return"Program"===r.type&&1===r.body.length&&"ExpressionStatement"===r.body[0].type&&"FunctionExpression"===r.body[0].expression.type}catch(e){return!1}}function n(e){var t,r="("+e+")",i=a.parse(r,{range:!0}),n=[];if("Program"!==i.type||1!==i.body.length||"ExpressionStatement"!==i.body[0].type||"FunctionExpression"!==i.body[0].expression.type)throw new Error("Failed to resolve function");return i.body[0].expression.params.forEach(function(e){n.push(e.name)}),t=i.body[0].expression.body.range,new Function(n,r.slice(t[0]+1,t[1]-1))}function s(e){return e.toString()}function o(e){return"[object Function]"===Object.prototype.toString.call(e)}var a;try{a=r(74)}catch(e){"undefined"!=typeof window&&(a=window.esprima)}var u=r(49);e.exports=new u("tag:yaml.org,2002:js/function",{kind:"scalar",resolve:i,construct:n,predicate:o,represent:s})},function(e,t,r){!function(t,r){e.exports=r()}(this,function(){return function(e){function t(i){if(r[i])return r[i].exports;var n=r[i]={exports:{},id:i,loaded:!1};return e[i].call(n.exports,n,n.exports,t),n.loaded=!0,n.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";function i(e,t,r){var i=null,n=function(e,t){r&&r(e,t),i&&i.visit(e,t)},u="function"==typeof r?n:null,c=!1;if(t){c="boolean"==typeof t.comment&&t.comment;var l="boolean"==typeof t.attachComment&&t.attachComment;(c||l)&&(i=new s.CommentHandler,i.attach=l,t.comment=!0,u=n)}var h;h=t&&"boolean"==typeof t.jsx&&t.jsx?new a.JSXParser(e,t,u):new o.Parser(e,t,u);var p=h.parseProgram();return c&&(p.comments=i.comments),h.config.tokens&&(p.tokens=h.tokens),h.config.tolerant&&(p.errors=h.errorHandler.errors),p}function n(e,t,r){var i,n=new u.Tokenizer(e,t);i=[];try{for(;;){var s=n.getNextToken();if(!s)break;r&&(s=r(s)),i.push(s)}}catch(e){n.errorHandler.tolerate(e)}return n.errorHandler.tolerant&&(i.errors=n.errors()),i}var s=r(1),o=r(3),a=r(11),u=r(15);t.parse=i,t.tokenize=n;var c=r(2);t.Syntax=c.Syntax,t.version="3.1.3"},function(e,t,r){"use strict";var i=r(2),n=function(){function e(){this.attach=!1,this.comments=[],this.stack=[],this.leading=[],this.trailing=[]}return e.prototype.insertInnerComments=function(e,t){if(e.type===i.Syntax.BlockStatement&&0===e.body.length){for(var r=[],n=this.leading.length-1;n>=0;--n){var s=this.leading[n];t.end.offset>=s.start&&(r.unshift(s.comment),this.leading.splice(n,1),this.trailing.splice(n,1))}r.length&&(e.innerComments=r)}},e.prototype.findTrailingComments=function(e,t){var r=[];if(this.trailing.length>0){for(var i=this.trailing.length-1;i>=0;--i){var n=this.trailing[i];n.start>=t.end.offset&&r.unshift(n.comment)}return this.trailing.length=0,r}var s=this.stack[this.stack.length-1];if(s&&s.node.trailingComments){var o=s.node.trailingComments[0];o&&o.range[0]>=t.end.offset&&(r=s.node.trailingComments,delete s.node.trailingComments)}return r},e.prototype.findLeadingComments=function(e,t){for(var r,i=[];this.stack.length>0;){var n=this.stack[this.stack.length-1];if(!(n&&n.start>=t.start.offset))break;r=this.stack.pop().node}if(r){for(var s=r.leadingComments?r.leadingComments.length:0,o=s-1;o>=0;--o){var a=r.leadingComments[o];a.range[1]<=t.start.offset&&(i.unshift(a),r.leadingComments.splice(o,1))}return r.leadingComments&&0===r.leadingComments.length&&delete r.leadingComments,i}for(var o=this.leading.length-1;o>=0;--o){var n=this.leading[o];n.start<=t.start.offset&&(i.unshift(n.comment),this.leading.splice(o,1))}return i},e.prototype.visitNode=function(e,t){if(!(e.type===i.Syntax.Program&&e.body.length>0)){this.insertInnerComments(e,t);var r=this.findTrailingComments(e,t),n=this.findLeadingComments(e,t);n.length>0&&(e.leadingComments=n),r.length>0&&(e.trailingComments=r),this.stack.push({node:e,start:t.start.offset})}},e.prototype.visitComment=function(e,t){var r="L"===e.type[0]?"Line":"Block",i={type:r,value:e.value};if(e.range&&(i.range=e.range),e.loc&&(i.loc=e.loc),this.comments.push(i),this.attach){var n={comment:{type:r,value:e.value,range:[t.start.offset,t.end.offset]},start:t.start.offset};e.loc&&(n.comment.loc=e.loc),e.type=r,this.leading.push(n),this.trailing.push(n)}},e.prototype.visit=function(e,t){"LineComment"===e.type?this.visitComment(e,t):"BlockComment"===e.type?this.visitComment(e,t):this.attach&&this.visitNode(e,t)},e}();t.CommentHandler=n},function(e,t){"use strict";t.Syntax={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DoWhileStatement:"DoWhileStatement",DebuggerStatement:"DebuggerStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForOfStatement:"ForOfStatement",ForInStatement:"ForInStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchCase:"SwitchCase",SwitchStatement:"SwitchStatement",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"}},function(e,t,r){"use strict";var i=r(4),n=r(5),s=r(6),o=r(7),a=r(8),u=r(2),c=r(10),l="ArrowParameterPlaceHolder",h=function(){function e(e,t,r){void 0===t&&(t={}),this.config={range:"boolean"==typeof t.range&&t.range,loc:"boolean"==typeof t.loc&&t.loc,source:null,tokens:"boolean"==typeof t.tokens&&t.tokens,comment:"boolean"==typeof t.comment&&t.comment,tolerant:"boolean"==typeof t.tolerant&&t.tolerant},this.config.loc&&t.source&&null!==t.source&&(this.config.source=String(t.source)),this.delegate=r,this.errorHandler=new s.ErrorHandler,this.errorHandler.tolerant=this.config.tolerant,this.scanner=new a.Scanner(e,this.errorHandler),this.scanner.trackComment=this.config.comment,this.operatorPrecedence={")":0,";":0,",":0,"=":0,"]":0,"||":1,"&&":2,"|":3, +"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":11,"/":11,"%":11},this.sourceType=t&&"module"===t.sourceType?"module":"script",this.lookahead=null,this.hasLineTerminator=!1,this.context={allowIn:!0,allowYield:!0,firstCoverInitializedNameError:null,isAssignmentTarget:!1,isBindingElement:!1,inFunctionBody:!1,inIteration:!1,inSwitch:!1,labelSet:{},strict:"module"===this.sourceType},this.tokens=[],this.startMarker={index:0,lineNumber:this.scanner.lineNumber,lineStart:0},this.lastMarker={index:0,lineNumber:this.scanner.lineNumber,lineStart:0},this.nextToken(),this.lastMarker={index:this.scanner.index,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart}}return e.prototype.throwError=function(e){for(var t=[],r=1;r0&&this.delegate)for(var t=0;t>="===e||">>>="===e||"&="===e||"^="===e||"|="===e},e.prototype.isolateCoverGrammar=function(e){var t=this.context.isBindingElement,r=this.context.isAssignmentTarget,i=this.context.firstCoverInitializedNameError;this.context.isBindingElement=!0,this.context.isAssignmentTarget=!0,this.context.firstCoverInitializedNameError=null;var n=e.call(this);return null!==this.context.firstCoverInitializedNameError&&this.throwUnexpectedToken(this.context.firstCoverInitializedNameError),this.context.isBindingElement=t,this.context.isAssignmentTarget=r,this.context.firstCoverInitializedNameError=i,n},e.prototype.inheritCoverGrammar=function(e){var t=this.context.isBindingElement,r=this.context.isAssignmentTarget,i=this.context.firstCoverInitializedNameError;this.context.isBindingElement=!0,this.context.isAssignmentTarget=!0,this.context.firstCoverInitializedNameError=null;var n=e.call(this);return this.context.isBindingElement=this.context.isBindingElement&&t,this.context.isAssignmentTarget=this.context.isAssignmentTarget&&r,this.context.firstCoverInitializedNameError=i||this.context.firstCoverInitializedNameError,n},e.prototype.consumeSemicolon=function(){this.match(";")?this.nextToken():this.hasLineTerminator||(this.lookahead.type===o.Token.EOF||this.match("}")||this.throwUnexpectedToken(this.lookahead),this.lastMarker.index=this.startMarker.index,this.lastMarker.lineNumber=this.startMarker.lineNumber,this.lastMarker.lineStart=this.startMarker.lineStart)},e.prototype.parsePrimaryExpression=function(){var e,t,r,i,s=this.createNode();switch(this.lookahead.type){case o.Token.Identifier:"module"===this.sourceType&&"await"===this.lookahead.value&&this.tolerateUnexpectedToken(this.lookahead),e=this.finalize(s,new c.Identifier(this.nextToken().value));break;case o.Token.NumericLiteral:case o.Token.StringLiteral:this.context.strict&&this.lookahead.octal&&this.tolerateUnexpectedToken(this.lookahead,n.Messages.StrictOctalLiteral),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,r=this.nextToken(),i=this.getTokenRaw(r),e=this.finalize(s,new c.Literal(r.value,i));break;case o.Token.BooleanLiteral:this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,r=this.nextToken(),r.value="true"===r.value,i=this.getTokenRaw(r),e=this.finalize(s,new c.Literal(r.value,i));break;case o.Token.NullLiteral:this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,r=this.nextToken(),r.value=null,i=this.getTokenRaw(r),e=this.finalize(s,new c.Literal(r.value,i));break;case o.Token.Template:e=this.parseTemplateLiteral();break;case o.Token.Punctuator:switch(t=this.lookahead.value){case"(":this.context.isBindingElement=!1,e=this.inheritCoverGrammar(this.parseGroupExpression);break;case"[":e=this.inheritCoverGrammar(this.parseArrayInitializer);break;case"{":e=this.inheritCoverGrammar(this.parseObjectInitializer);break;case"/":case"/=":this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.scanner.index=this.startMarker.index,r=this.nextRegexToken(),i=this.getTokenRaw(r),e=this.finalize(s,new c.RegexLiteral(r.value,i,r.regex));break;default:this.throwUnexpectedToken(this.nextToken())}break;case o.Token.Keyword:!this.context.strict&&this.context.allowYield&&this.matchKeyword("yield")?e=this.parseIdentifierName():!this.context.strict&&this.matchKeyword("let")?e=this.finalize(s,new c.Identifier(this.nextToken().value)):(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.matchKeyword("function")?e=this.parseFunctionExpression():this.matchKeyword("this")?(this.nextToken(),e=this.finalize(s,new c.ThisExpression)):this.matchKeyword("class")?e=this.parseClassExpression():this.throwUnexpectedToken(this.nextToken()));break;default:this.throwUnexpectedToken(this.nextToken())}return e},e.prototype.parseSpreadElement=function(){var e=this.createNode();this.expect("...");var t=this.inheritCoverGrammar(this.parseAssignmentExpression);return this.finalize(e,new c.SpreadElement(t))},e.prototype.parseArrayInitializer=function(){var e=this.createNode(),t=[];for(this.expect("[");!this.match("]");)if(this.match(","))this.nextToken(),t.push(null);else if(this.match("...")){var r=this.parseSpreadElement();this.match("]")||(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.expect(",")),t.push(r)}else t.push(this.inheritCoverGrammar(this.parseAssignmentExpression)),this.match("]")||this.expect(",");return this.expect("]"),this.finalize(e,new c.ArrayExpression(t))},e.prototype.parsePropertyMethod=function(e){this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var t=this.context.strict,r=this.isolateCoverGrammar(this.parseFunctionSourceElements);return this.context.strict&&e.firstRestricted&&this.tolerateUnexpectedToken(e.firstRestricted,e.message),this.context.strict&&e.stricted&&this.tolerateUnexpectedToken(e.stricted,e.message),this.context.strict=t,r},e.prototype.parsePropertyMethodFunction=function(){var e=!1,t=this.createNode(),r=this.context.allowYield;this.context.allowYield=!1;var i=this.parseFormalParameters(),n=this.parsePropertyMethod(i);return this.context.allowYield=r,this.finalize(t,new c.FunctionExpression(null,i.params,n,e))},e.prototype.parseObjectPropertyKey=function(){var e=this.createNode(),t=this.nextToken(),r=null;switch(t.type){case o.Token.StringLiteral:case o.Token.NumericLiteral:this.context.strict&&t.octal&&this.tolerateUnexpectedToken(t,n.Messages.StrictOctalLiteral);var i=this.getTokenRaw(t);r=this.finalize(e,new c.Literal(t.value,i));break;case o.Token.Identifier:case o.Token.BooleanLiteral:case o.Token.NullLiteral:case o.Token.Keyword:r=this.finalize(e,new c.Identifier(t.value));break;case o.Token.Punctuator:"["===t.value?(r=this.isolateCoverGrammar(this.parseAssignmentExpression),this.expect("]")):this.throwUnexpectedToken(t);break;default:this.throwUnexpectedToken(t)}return r},e.prototype.isPropertyKey=function(e,t){return e.type===u.Syntax.Identifier&&e.name===t||e.type===u.Syntax.Literal&&e.value===t},e.prototype.parseObjectProperty=function(e){var t,r,i,s=this.createNode(),a=this.lookahead,u=!1,l=!1,h=!1;a.type===o.Token.Identifier?(this.nextToken(),r=this.finalize(s,new c.Identifier(a.value))):this.match("*")?this.nextToken():(u=this.match("["),r=this.parseObjectPropertyKey());var p=this.qualifiedPropertyName(this.lookahead);if(a.type===o.Token.Identifier&&"get"===a.value&&p)t="get",u=this.match("["),r=this.parseObjectPropertyKey(),this.context.allowYield=!1,i=this.parseGetterMethod();else if(a.type===o.Token.Identifier&&"set"===a.value&&p)t="set",u=this.match("["),r=this.parseObjectPropertyKey(),i=this.parseSetterMethod();else if(a.type===o.Token.Punctuator&&"*"===a.value&&p)t="init",u=this.match("["),r=this.parseObjectPropertyKey(),i=this.parseGeneratorMethod(),l=!0;else if(r||this.throwUnexpectedToken(this.lookahead),t="init",this.match(":"))!u&&this.isPropertyKey(r,"__proto__")&&(e.value&&this.tolerateError(n.Messages.DuplicateProtoProperty),e.value=!0),this.nextToken(),i=this.inheritCoverGrammar(this.parseAssignmentExpression);else if(this.match("("))i=this.parsePropertyMethodFunction(),l=!0;else if(a.type===o.Token.Identifier){var f=this.finalize(s,new c.Identifier(a.value));if(this.match("=")){this.context.firstCoverInitializedNameError=this.lookahead,this.nextToken(),h=!0;var d=this.isolateCoverGrammar(this.parseAssignmentExpression);i=this.finalize(s,new c.AssignmentPattern(f,d))}else h=!0,i=f}else this.throwUnexpectedToken(this.nextToken());return this.finalize(s,new c.Property(t,r,u,i,l,h))},e.prototype.parseObjectInitializer=function(){var e=this.createNode();this.expect("{");for(var t=[],r={value:!1};!this.match("}");)t.push(this.parseObjectProperty(r)),this.match("}")||this.expectCommaSeparator();return this.expect("}"),this.finalize(e,new c.ObjectExpression(t))},e.prototype.parseTemplateHead=function(){i.assert(this.lookahead.head,"Template literal must start with a template head");var e=this.createNode(),t=this.nextToken(),r={raw:t.value.raw,cooked:t.value.cooked};return this.finalize(e,new c.TemplateElement(r,t.tail))},e.prototype.parseTemplateElement=function(){this.lookahead.type!==o.Token.Template&&this.throwUnexpectedToken();var e=this.createNode(),t=this.nextToken(),r={raw:t.value.raw,cooked:t.value.cooked};return this.finalize(e,new c.TemplateElement(r,t.tail))},e.prototype.parseTemplateLiteral=function(){var e=this.createNode(),t=[],r=[],i=this.parseTemplateHead();for(r.push(i);!i.tail;)t.push(this.parseExpression()),i=this.parseTemplateElement(),r.push(i);return this.finalize(e,new c.TemplateLiteral(r,t))},e.prototype.reinterpretExpressionAsPattern=function(e){switch(e.type){case u.Syntax.Identifier:case u.Syntax.MemberExpression:case u.Syntax.RestElement:case u.Syntax.AssignmentPattern:break;case u.Syntax.SpreadElement:e.type=u.Syntax.RestElement,this.reinterpretExpressionAsPattern(e.argument);break;case u.Syntax.ArrayExpression:e.type=u.Syntax.ArrayPattern;for(var t=0;t")||this.expect("=>"),e={type:l,params:[]};else{var t=this.lookahead,r=[];if(this.match("..."))e=this.parseRestElement(r),this.expect(")"),this.match("=>")||this.expect("=>"),e={type:l,params:[e]};else{var i=!1;if(this.context.isBindingElement=!0,e=this.inheritCoverGrammar(this.parseAssignmentExpression),this.match(",")){var n=[];for(this.context.isAssignmentTarget=!1,n.push(e);this.startMarker.index")||this.expect("=>"),this.context.isBindingElement=!1;for(var s=0;s")&&(e.type===u.Syntax.Identifier&&"yield"===e.name&&(i=!0,e={type:l,params:[e]}),!i)){if(this.context.isBindingElement||this.throwUnexpectedToken(this.lookahead),e.type===u.Syntax.SequenceExpression)for(var s=0;s0){this.nextToken(),r.prec=i,this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;for(var n=[e,this.lookahead],s=t,o=this.isolateCoverGrammar(this.parseExponentiationExpression),a=[s,r,o];;){if(i=this.binaryPrecedence(this.lookahead),i<=0)break;for(;a.length>2&&i<=a[a.length-2].prec;){o=a.pop();var u=a.pop().value;s=a.pop(),n.pop();var l=this.startNode(n[n.length-1]);a.push(this.finalize(l,new c.BinaryExpression(u,s,o)))}r=this.nextToken(),r.prec=i,a.push(r),n.push(this.lookahead),a.push(this.isolateCoverGrammar(this.parseExponentiationExpression))}var h=a.length-1;for(t=a[h],n.pop();h>1;){var l=this.startNode(n.pop());t=this.finalize(l,new c.BinaryExpression(a[h-1].value,a[h-2],t)),h-=2}}return t},e.prototype.parseConditionalExpression=function(){var e=this.lookahead,t=this.inheritCoverGrammar(this.parseBinaryExpression);if(this.match("?")){this.nextToken();var r=this.context.allowIn;this.context.allowIn=!0;var i=this.isolateCoverGrammar(this.parseAssignmentExpression);this.context.allowIn=r,this.expect(":");var n=this.isolateCoverGrammar(this.parseAssignmentExpression);t=this.finalize(this.startNode(e),new c.ConditionalExpression(t,i,n)),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1}return t},e.prototype.checkPatternParam=function(e,t){switch(t.type){case u.Syntax.Identifier:this.validateParam(e,t,t.name);break;case u.Syntax.RestElement:this.checkPatternParam(e,t.argument);break;case u.Syntax.AssignmentPattern:this.checkPatternParam(e,t.left);break;case u.Syntax.ArrayPattern:for(var r=0;r")){this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var i=this.reinterpretAsCoverFormalsList(e);if(i){this.hasLineTerminator&&this.tolerateUnexpectedToken(this.lookahead),this.context.firstCoverInitializedNameError=null;var s=this.context.strict,o=this.context.allowYield;this.context.allowYield=!0;var a=this.startNode(t);this.expect("=>");var h=this.match("{")?this.parseFunctionSourceElements():this.isolateCoverGrammar(this.parseAssignmentExpression),p=h.type!==u.Syntax.BlockStatement;this.context.strict&&i.firstRestricted&&this.throwUnexpectedToken(i.firstRestricted,i.message),this.context.strict&&i.stricted&&this.tolerateUnexpectedToken(i.stricted,i.message),e=this.finalize(a,new c.ArrowFunctionExpression(i.params,h,p)),this.context.strict=s,this.context.allowYield=o}}else if(this.matchAssign()){if(this.context.isAssignmentTarget||this.tolerateError(n.Messages.InvalidLHSInAssignment),this.context.strict&&e.type===u.Syntax.Identifier){var f=e;this.scanner.isRestrictedWord(f.name)&&this.tolerateUnexpectedToken(r,n.Messages.StrictLHSAssignment),this.scanner.isStrictModeReservedWord(f.name)&&this.tolerateUnexpectedToken(r,n.Messages.StrictReservedWord)}this.match("=")?this.reinterpretExpressionAsPattern(e):(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1),r=this.nextToken();var d=this.isolateCoverGrammar(this.parseAssignmentExpression);e=this.finalize(this.startNode(t),new c.AssignmentExpression(r.value,e,d)),this.context.firstCoverInitializedNameError=null}}return e},e.prototype.parseExpression=function(){var e=this.lookahead,t=this.isolateCoverGrammar(this.parseAssignmentExpression);if(this.match(",")){var r=[];for(r.push(t);this.startMarker.index",t.TokenName[r.Identifier]="Identifier",t.TokenName[r.Keyword]="Keyword",t.TokenName[r.NullLiteral]="Null",t.TokenName[r.NumericLiteral]="Numeric",t.TokenName[r.Punctuator]="Punctuator",t.TokenName[r.StringLiteral]="String",t.TokenName[r.RegularExpression]="RegularExpression",t.TokenName[r.Template]="Template"},function(e,t,r){"use strict";function i(e){return"0123456789abcdef".indexOf(e.toLowerCase())}function n(e){return"01234567".indexOf(e)}var s=r(4),o=r(5),a=r(9),u=r(7),c=function(){function e(e,t){this.source=e,this.errorHandler=t,this.trackComment=!1,this.length=e.length,this.index=0,this.lineNumber=e.length>0?1:0,this.lineStart=0,this.curlyStack=[]}return e.prototype.eof=function(){return this.index>=this.length},e.prototype.throwUnexpectedToken=function(e){void 0===e&&(e=o.Messages.UnexpectedTokenIllegal),this.errorHandler.throwError(this.index,this.lineNumber,this.index-this.lineStart+1,e)},e.prototype.tolerateUnexpectedToken=function(){this.errorHandler.tolerateError(this.index,this.lineNumber,this.index-this.lineStart+1,o.Messages.UnexpectedTokenIllegal)},e.prototype.skipSingleLineComment=function(e){var t,r,i;for(this.trackComment&&(t=[],r=this.index-e,i={start:{line:this.lineNumber,column:this.index-this.lineStart-e},end:{}});!this.eof();){var n=this.source.charCodeAt(this.index);if(++this.index,a.Character.isLineTerminator(n)){if(this.trackComment){i.end={line:this.lineNumber,column:this.index-this.lineStart-1};var s={multiLine:!1,slice:[r+e,this.index-1],range:[r,this.index-1],loc:i};t.push(s)}return 13===n&&10===this.source.charCodeAt(this.index)&&++this.index,++this.lineNumber,this.lineStart=this.index,t}}if(this.trackComment){i.end={line:this.lineNumber,column:this.index-this.lineStart};var s={multiLine:!1,slice:[r+e,this.index],range:[r,this.index],loc:i};t.push(s)}return t},e.prototype.skipMultiLineComment=function(){var e,t,r;for(this.trackComment&&(e=[],t=this.index-2,r={start:{line:this.lineNumber,column:this.index-this.lineStart-2},end:{}});!this.eof();){var i=this.source.charCodeAt(this.index);if(a.Character.isLineTerminator(i))13===i&&10===this.source.charCodeAt(this.index+1)&&++this.index,++this.lineNumber,++this.index,this.lineStart=this.index;else if(42===i){if(47===this.source.charCodeAt(this.index+1)){if(this.index+=2,this.trackComment){r.end={line:this.lineNumber,column:this.index-this.lineStart};var n={multiLine:!0,slice:[t+2,this.index-2],range:[t,this.index],loc:r};e.push(n)}return e}++this.index}else++this.index}if(this.trackComment){r.end={line:this.lineNumber,column:this.index-this.lineStart};var n={multiLine:!0,slice:[t+2,this.index],range:[t,this.index],loc:r};e.push(n)}return this.tolerateUnexpectedToken(),e},e.prototype.scanComments=function(){var e;this.trackComment&&(e=[]);for(var t=0===this.index;!this.eof();){var r=this.source.charCodeAt(this.index);if(a.Character.isWhiteSpace(r))++this.index;else if(a.Character.isLineTerminator(r))++this.index,13===r&&10===this.source.charCodeAt(this.index)&&++this.index,++this.lineNumber,this.lineStart=this.index,t=!0;else if(47===r)if(r=this.source.charCodeAt(this.index+1),47===r){this.index+=2;var i=this.skipSingleLineComment(2);this.trackComment&&(e=e.concat(i)),t=!0}else{if(42!==r)break;this.index+=2;var i=this.skipMultiLineComment();this.trackComment&&(e=e.concat(i))}else if(t&&45===r){if(45!==this.source.charCodeAt(this.index+1)||62!==this.source.charCodeAt(this.index+2))break;this.index+=3;var i=this.skipSingleLineComment(3);this.trackComment&&(e=e.concat(i))}else{if(60!==r)break;if("!--"!==this.source.slice(this.index+1,this.index+4))break;this.index+=4;var i=this.skipSingleLineComment(4);this.trackComment&&(e=e.concat(i))}}return e},e.prototype.isFutureReservedWord=function(e){switch(e){case"enum":case"export":case"import":case"super":return!0;default:return!1}},e.prototype.isStrictModeReservedWord=function(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return!0;default:return!1}},e.prototype.isRestrictedWord=function(e){return"eval"===e||"arguments"===e},e.prototype.isKeyword=function(e){switch(e.length){case 2:return"if"===e||"in"===e||"do"===e;case 3:return"var"===e||"for"===e||"new"===e||"try"===e||"let"===e;case 4:return"this"===e||"else"===e||"case"===e||"void"===e||"with"===e||"enum"===e;case 5:return"while"===e||"break"===e||"catch"===e||"throw"===e||"const"===e||"yield"===e||"class"===e||"super"===e;case 6:return"return"===e||"typeof"===e||"delete"===e||"switch"===e||"export"===e||"import"===e;case 7:return"default"===e||"finally"===e||"extends"===e;case 8:return"function"===e||"continue"===e||"debugger"===e;case 10:return"instanceof"===e;default:return!1}},e.prototype.codePointAt=function(e){var t=this.source.charCodeAt(e);if(t>=55296&&t<=56319){var r=this.source.charCodeAt(e+1);if(r>=56320&&r<=57343){var i=t;t=1024*(i-55296)+r-56320+65536}}return t},e.prototype.scanHexEscape=function(e){for(var t="u"===e?4:2,r=0,n=0;n1114111||"}"!==e)&&this.throwUnexpectedToken(),a.Character.fromCodePoint(t)},e.prototype.getIdentifier=function(){for(var e=this.index++;!this.eof();){var t=this.source.charCodeAt(this.index);if(92===t)return this.index=e,this.getComplexIdentifier();if(t>=55296&&t<57343)return this.index=e,this.getComplexIdentifier();if(!a.Character.isIdentifierPart(t))break;++this.index}return this.source.slice(e,this.index)},e.prototype.getComplexIdentifier=function(){var e=this.codePointAt(this.index),t=a.Character.fromCodePoint(e);this.index+=t.length;var r;for(92===e&&(117!==this.source.charCodeAt(this.index)&&this.throwUnexpectedToken(),++this.index,"{"===this.source[this.index]?(++this.index,r=this.scanUnicodeCodePointEscape()):(r=this.scanHexEscape("u"),e=r.charCodeAt(0),r&&"\\"!==r&&a.Character.isIdentifierStart(e)||this.throwUnexpectedToken()),t=r);!this.eof()&&(e=this.codePointAt(this.index),a.Character.isIdentifierPart(e));)r=a.Character.fromCodePoint(e),t+=r,this.index+=r.length,92===e&&(t=t.substr(0,t.length-1),117!==this.source.charCodeAt(this.index)&&this.throwUnexpectedToken(),++this.index,"{"===this.source[this.index]?(++this.index,r=this.scanUnicodeCodePointEscape()):(r=this.scanHexEscape("u"),e=r.charCodeAt(0),r&&"\\"!==r&&a.Character.isIdentifierPart(e)||this.throwUnexpectedToken()),t+=r);return t},e.prototype.octalToDecimal=function(e){var t="0"!==e,r=n(e);return!this.eof()&&a.Character.isOctalDigit(this.source.charCodeAt(this.index))&&(t=!0,r=8*r+n(this.source[this.index++]),"0123".indexOf(e)>=0&&!this.eof()&&a.Character.isOctalDigit(this.source.charCodeAt(this.index))&&(r=8*r+n(this.source[this.index++]))),{code:r,octal:t}},e.prototype.scanIdentifier=function(){var e,t=this.index,r=92===this.source.charCodeAt(t)?this.getComplexIdentifier():this.getIdentifier();return e=1===r.length?u.Token.Identifier:this.isKeyword(r)?u.Token.Keyword:"null"===r?u.Token.NullLiteral:"true"===r||"false"===r?u.Token.BooleanLiteral:u.Token.Identifier,{type:e,value:r,lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}},e.prototype.scanPunctuator=function(){var e={type:u.Token.Punctuator,value:"",lineNumber:this.lineNumber,lineStart:this.lineStart,start:this.index,end:this.index},t=this.source[this.index];switch(t){case"(":case"{":"{"===t&&this.curlyStack.push("{"),++this.index;break;case".":++this.index,"."===this.source[this.index]&&"."===this.source[this.index+1]&&(this.index+=2,t="...");break;case"}":++this.index,this.curlyStack.pop();break;case")":case";":case",":case"[":case"]":case":":case"?":case"~":++this.index;break;default:t=this.source.substr(this.index,4),">>>="===t?this.index+=4:(t=t.substr(0,3),"==="===t||"!=="===t||">>>"===t||"<<="===t||">>="===t||"**="===t?this.index+=3:(t=t.substr(0,2),"&&"===t||"||"===t||"=="===t||"!="===t||"+="===t||"-="===t||"*="===t||"/="===t||"++"===t||"--"===t||"<<"===t||">>"===t||"&="===t||"|="===t||"^="===t||"%="===t||"<="===t||">="===t||"=>"===t||"**"===t?this.index+=2:(t=this.source[this.index],"<>=!+-*%&|^/".indexOf(t)>=0&&++this.index)))}return this.index===e.start&&this.throwUnexpectedToken(),e.end=this.index,e.value=t,e},e.prototype.scanHexLiteral=function(e){for(var t="";!this.eof()&&a.Character.isHexDigit(this.source.charCodeAt(this.index));)t+=this.source[this.index++];return 0===t.length&&this.throwUnexpectedToken(),a.Character.isIdentifierStart(this.source.charCodeAt(this.index))&&this.throwUnexpectedToken(),{type:u.Token.NumericLiteral,value:parseInt("0x"+t,16),lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}},e.prototype.scanBinaryLiteral=function(e){for(var t,r="";!this.eof()&&(t=this.source[this.index],"0"===t||"1"===t);)r+=this.source[this.index++];return 0===r.length&&this.throwUnexpectedToken(),this.eof()||(t=this.source.charCodeAt(this.index),(a.Character.isIdentifierStart(t)||a.Character.isDecimalDigit(t))&&this.throwUnexpectedToken()),{type:u.Token.NumericLiteral,value:parseInt(r,2),lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}},e.prototype.scanOctalLiteral=function(e,t){var r="",i=!1;for(a.Character.isOctalDigit(e.charCodeAt(0))?(i=!0,r="0"+this.source[this.index++]):++this.index;!this.eof()&&a.Character.isOctalDigit(this.source.charCodeAt(this.index));)r+=this.source[this.index++];return i||0!==r.length||this.throwUnexpectedToken(),(a.Character.isIdentifierStart(this.source.charCodeAt(this.index))||a.Character.isDecimalDigit(this.source.charCodeAt(this.index)))&&this.throwUnexpectedToken(),{type:u.Token.NumericLiteral,value:parseInt(r,8),octal:i,lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}},e.prototype.isImplicitOctalLiteral=function(){for(var e=this.index+1;e=0&&(i=i.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g,function(e,t,i){var s=parseInt(t||i,16);return s>1114111&&n.throwUnexpectedToken(o.Messages.InvalidRegExp),s<=65535?String.fromCharCode(s):r}).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,r));try{RegExp(i)}catch(e){this.throwUnexpectedToken(o.Messages.InvalidRegExp)}try{return new RegExp(e,t)}catch(e){return null}},e.prototype.scanRegExpBody=function(){var e=this.source[this.index];s.assert("/"===e,"Regular expression literal must start with a slash");for(var t=this.source[this.index++],r=!1,i=!1;!this.eof();)if(e=this.source[this.index++],t+=e,"\\"===e)e=this.source[this.index++],a.Character.isLineTerminator(e.charCodeAt(0))&&this.throwUnexpectedToken(o.Messages.UnterminatedRegExp),t+=e;else if(a.Character.isLineTerminator(e.charCodeAt(0)))this.throwUnexpectedToken(o.Messages.UnterminatedRegExp);else if(r)"]"===e&&(r=!1);else{if("/"===e){i=!0;break}"["===e&&(r=!0)}i||this.throwUnexpectedToken(o.Messages.UnterminatedRegExp);var n=t.substr(1,t.length-2);return{value:n,literal:t}},e.prototype.scanRegExpFlags=function(){for(var e="",t="";!this.eof();){var r=this.source[this.index];if(!a.Character.isIdentifierPart(r.charCodeAt(0)))break;if(++this.index,"\\"!==r||this.eof())t+=r,e+=r;else if(r=this.source[this.index],"u"===r){++this.index;var i=this.index;if(r=this.scanHexEscape("u"))for(t+=r,e+="\\u";i=55296&&e<57343&&a.Character.isIdentifierStart(this.codePointAt(this.index))?this.scanIdentifier():this.scanPunctuator()},e}();t.Scanner=c},function(e,t){"use strict";var r={NonAsciiIdentifierStart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,NonAsciiIdentifierPart:/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ +};t.Character={fromCodePoint:function(e){return e<65536?String.fromCharCode(e):String.fromCharCode(55296+(e-65536>>10))+String.fromCharCode(56320+(e-65536&1023))},isWhiteSpace:function(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&[5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279].indexOf(e)>=0},isLineTerminator:function(e){return 10===e||13===e||8232===e||8233===e},isIdentifierStart:function(e){return 36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||92===e||e>=128&&r.NonAsciiIdentifierStart.test(t.Character.fromCodePoint(e))},isIdentifierPart:function(e){return 36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||92===e||e>=128&&r.NonAsciiIdentifierPart.test(t.Character.fromCodePoint(e))},isDecimalDigit:function(e){return e>=48&&e<=57},isHexDigit:function(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102},isOctalDigit:function(e){return e>=48&&e<=55}}},function(e,t,r){"use strict";var i=r(2),n=function(){function e(e){this.type=i.Syntax.ArrayExpression,this.elements=e}return e}();t.ArrayExpression=n;var s=function(){function e(e){this.type=i.Syntax.ArrayPattern,this.elements=e}return e}();t.ArrayPattern=s;var o=function(){function e(e,t,r){this.type=i.Syntax.ArrowFunctionExpression,this.id=null,this.params=e,this.body=t,this.generator=!1,this.expression=r}return e}();t.ArrowFunctionExpression=o;var a=function(){function e(e,t,r){this.type=i.Syntax.AssignmentExpression,this.operator=e,this.left=t,this.right=r}return e}();t.AssignmentExpression=a;var u=function(){function e(e,t){this.type=i.Syntax.AssignmentPattern,this.left=e,this.right=t}return e}();t.AssignmentPattern=u;var c=function(){function e(e,t,r){var n="||"===e||"&&"===e;this.type=n?i.Syntax.LogicalExpression:i.Syntax.BinaryExpression,this.operator=e,this.left=t,this.right=r}return e}();t.BinaryExpression=c;var l=function(){function e(e){this.type=i.Syntax.BlockStatement,this.body=e}return e}();t.BlockStatement=l;var h=function(){function e(e){this.type=i.Syntax.BreakStatement,this.label=e}return e}();t.BreakStatement=h;var p=function(){function e(e,t){this.type=i.Syntax.CallExpression,this.callee=e,this.arguments=t}return e}();t.CallExpression=p;var f=function(){function e(e,t){this.type=i.Syntax.CatchClause,this.param=e,this.body=t}return e}();t.CatchClause=f;var d=function(){function e(e){this.type=i.Syntax.ClassBody,this.body=e}return e}();t.ClassBody=d;var m=function(){function e(e,t,r){this.type=i.Syntax.ClassDeclaration,this.id=e,this.superClass=t,this.body=r}return e}();t.ClassDeclaration=m;var g=function(){function e(e,t,r){this.type=i.Syntax.ClassExpression,this.id=e,this.superClass=t,this.body=r}return e}();t.ClassExpression=g;var x=function(){function e(e,t){this.type=i.Syntax.MemberExpression,this.computed=!0,this.object=e,this.property=t}return e}();t.ComputedMemberExpression=x;var y=function(){function e(e,t,r){this.type=i.Syntax.ConditionalExpression,this.test=e,this.consequent=t,this.alternate=r}return e}();t.ConditionalExpression=y;var D=function(){function e(e){this.type=i.Syntax.ContinueStatement,this.label=e}return e}();t.ContinueStatement=D;var b=function(){function e(){this.type=i.Syntax.DebuggerStatement}return e}();t.DebuggerStatement=b;var v=function(){function e(e,t){this.type=i.Syntax.ExpressionStatement,this.expression=e,this.directive=t}return e}();t.Directive=v;var w=function(){function e(e,t){this.type=i.Syntax.DoWhileStatement,this.body=e,this.test=t}return e}();t.DoWhileStatement=w;var E=function(){function e(){this.type=i.Syntax.EmptyStatement}return e}();t.EmptyStatement=E;var k=function(){function e(e){this.type=i.Syntax.ExportAllDeclaration,this.source=e}return e}();t.ExportAllDeclaration=k;var A=function(){function e(e){this.type=i.Syntax.ExportDefaultDeclaration,this.declaration=e}return e}();t.ExportDefaultDeclaration=A;var C=function(){function e(e,t,r){this.type=i.Syntax.ExportNamedDeclaration,this.declaration=e,this.specifiers=t,this.source=r}return e}();t.ExportNamedDeclaration=C;var S=function(){function e(e,t){this.type=i.Syntax.ExportSpecifier,this.exported=t,this.local=e}return e}();t.ExportSpecifier=S;var F=function(){function e(e){this.type=i.Syntax.ExpressionStatement,this.expression=e}return e}();t.ExpressionStatement=F;var T=function(){function e(e,t,r){this.type=i.Syntax.ForInStatement,this.left=e,this.right=t,this.body=r,this.each=!1}return e}();t.ForInStatement=T;var B=function(){function e(e,t,r){this.type=i.Syntax.ForOfStatement,this.left=e,this.right=t,this.body=r}return e}();t.ForOfStatement=B;var N=function(){function e(e,t,r,n){this.type=i.Syntax.ForStatement,this.init=e,this.test=t,this.update=r,this.body=n}return e}();t.ForStatement=N;var I=function(){function e(e,t,r,n){this.type=i.Syntax.FunctionDeclaration,this.id=e,this.params=t,this.body=r,this.generator=n,this.expression=!1}return e}();t.FunctionDeclaration=I;var P=function(){function e(e,t,r,n){this.type=i.Syntax.FunctionExpression,this.id=e,this.params=t,this.body=r,this.generator=n,this.expression=!1}return e}();t.FunctionExpression=P;var M=function(){function e(e){this.type=i.Syntax.Identifier,this.name=e}return e}();t.Identifier=M;var O=function(){function e(e,t,r){this.type=i.Syntax.IfStatement,this.test=e,this.consequent=t,this.alternate=r}return e}();t.IfStatement=O;var L=function(){function e(e,t){this.type=i.Syntax.ImportDeclaration,this.specifiers=e,this.source=t}return e}();t.ImportDeclaration=L;var R=function(){function e(e){this.type=i.Syntax.ImportDefaultSpecifier,this.local=e}return e}();t.ImportDefaultSpecifier=R;var U=function(){function e(e){this.type=i.Syntax.ImportNamespaceSpecifier,this.local=e}return e}();t.ImportNamespaceSpecifier=U;var _=function(){function e(e,t){this.type=i.Syntax.ImportSpecifier,this.local=e,this.imported=t}return e}();t.ImportSpecifier=_;var z=function(){function e(e,t){this.type=i.Syntax.LabeledStatement,this.label=e,this.body=t}return e}();t.LabeledStatement=z;var j=function(){function e(e,t){this.type=i.Syntax.Literal,this.value=e,this.raw=t}return e}();t.Literal=j;var X=function(){function e(e,t){this.type=i.Syntax.MetaProperty,this.meta=e,this.property=t}return e}();t.MetaProperty=X;var J=function(){function e(e,t,r,n,s){this.type=i.Syntax.MethodDefinition,this.key=e,this.computed=t,this.value=r,this.kind=n,this.static=s}return e}();t.MethodDefinition=J;var Y=function(){function e(e,t){this.type=i.Syntax.NewExpression,this.callee=e,this.arguments=t}return e}();t.NewExpression=Y;var K=function(){function e(e){this.type=i.Syntax.ObjectExpression,this.properties=e}return e}();t.ObjectExpression=K;var W=function(){function e(e){this.type=i.Syntax.ObjectPattern,this.properties=e}return e}();t.ObjectPattern=W;var H=function(){function e(e,t){this.type=i.Syntax.Program,this.body=e,this.sourceType=t}return e}();t.Program=H;var q=function(){function e(e,t,r,n,s,o){this.type=i.Syntax.Property,this.key=t,this.computed=r,this.value=n,this.kind=e,this.method=s,this.shorthand=o}return e}();t.Property=q;var G=function(){function e(e,t,r){this.type=i.Syntax.Literal,this.value=e,this.raw=t,this.regex=r}return e}();t.RegexLiteral=G;var V=function(){function e(e){this.type=i.Syntax.RestElement,this.argument=e}return e}();t.RestElement=V;var $=function(){function e(e){this.type=i.Syntax.ReturnStatement,this.argument=e}return e}();t.ReturnStatement=$;var Z=function(){function e(e){this.type=i.Syntax.SequenceExpression,this.expressions=e}return e}();t.SequenceExpression=Z;var Q=function(){function e(e){this.type=i.Syntax.SpreadElement,this.argument=e}return e}();t.SpreadElement=Q;var ee=function(){function e(e,t){this.type=i.Syntax.MemberExpression,this.computed=!1,this.object=e,this.property=t}return e}();t.StaticMemberExpression=ee;var te=function(){function e(){this.type=i.Syntax.Super}return e}();t.Super=te;var re=function(){function e(e,t){this.type=i.Syntax.SwitchCase,this.test=e,this.consequent=t}return e}();t.SwitchCase=re;var ie=function(){function e(e,t){this.type=i.Syntax.SwitchStatement,this.discriminant=e,this.cases=t}return e}();t.SwitchStatement=ie;var ne=function(){function e(e,t){this.type=i.Syntax.TaggedTemplateExpression,this.tag=e,this.quasi=t}return e}();t.TaggedTemplateExpression=ne;var se=function(){function e(e,t){this.type=i.Syntax.TemplateElement,this.value=e,this.tail=t}return e}();t.TemplateElement=se;var oe=function(){function e(e,t){this.type=i.Syntax.TemplateLiteral,this.quasis=e,this.expressions=t}return e}();t.TemplateLiteral=oe;var ae=function(){function e(){this.type=i.Syntax.ThisExpression}return e}();t.ThisExpression=ae;var ue=function(){function e(e){this.type=i.Syntax.ThrowStatement,this.argument=e}return e}();t.ThrowStatement=ue;var ce=function(){function e(e,t,r){this.type=i.Syntax.TryStatement,this.block=e,this.handler=t,this.finalizer=r}return e}();t.TryStatement=ce;var le=function(){function e(e,t){this.type=i.Syntax.UnaryExpression,this.operator=e,this.argument=t,this.prefix=!0}return e}();t.UnaryExpression=le;var he=function(){function e(e,t,r){this.type=i.Syntax.UpdateExpression,this.operator=e,this.argument=t,this.prefix=r}return e}();t.UpdateExpression=he;var pe=function(){function e(e,t){this.type=i.Syntax.VariableDeclaration,this.declarations=e,this.kind=t}return e}();t.VariableDeclaration=pe;var fe=function(){function e(e,t){this.type=i.Syntax.VariableDeclarator,this.id=e,this.init=t}return e}();t.VariableDeclarator=fe;var de=function(){function e(e,t){this.type=i.Syntax.WhileStatement,this.test=e,this.body=t}return e}();t.WhileStatement=de;var me=function(){function e(e,t){this.type=i.Syntax.WithStatement,this.object=e,this.body=t}return e}();t.WithStatement=me;var ge=function(){function e(e,t){this.type=i.Syntax.YieldExpression,this.argument=e,this.delegate=t}return e}();t.YieldExpression=ge},function(e,t,r){"use strict";function i(e){var t;switch(e.type){case l.JSXSyntax.JSXIdentifier:var r=e;t=r.name;break;case l.JSXSyntax.JSXNamespacedName:var n=e;t=i(n.namespace)+":"+i(n.name);break;case l.JSXSyntax.JSXMemberExpression:var s=e;t=i(s.object)+"."+i(s.property)}return t}var n,s=this&&this.__extends||function(e,t){function r(){this.constructor=e}for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i]);e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},o=r(9),a=r(7),u=r(3),c=r(12),l=r(13),h=r(10),p=r(14);!function(e){e[e.Identifier=100]="Identifier",e[e.Text=101]="Text"}(n||(n={})),a.TokenName[n.Identifier]="JSXIdentifier",a.TokenName[n.Text]="JSXText";var f=function(e){function t(t,r,i){e.call(this,t,r,i)}return s(t,e),t.prototype.parsePrimaryExpression=function(){return this.match("<")?this.parseJSXRoot():e.prototype.parsePrimaryExpression.call(this)},t.prototype.startJSX=function(){this.scanner.index=this.startMarker.index,this.scanner.lineNumber=this.startMarker.lineNumber,this.scanner.lineStart=this.startMarker.lineStart},t.prototype.finishJSX=function(){this.nextToken()},t.prototype.reenterJSX=function(){this.startJSX(),this.expectJSX("}"),this.config.tokens&&this.tokens.pop()},t.prototype.createJSXNode=function(){return this.collectComments(),{index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}},t.prototype.createJSXChildNode=function(){return{index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}},t.prototype.scanXHTMLEntity=function(e){for(var t="&",r=!0,i=!1,n=!1,s=!1;!this.scanner.eof()&&r&&!i;){var a=this.scanner.source[this.scanner.index];if(a===e)break;if(i=";"===a,t+=a,++this.scanner.index,!i)switch(t.length){case 2:n="#"===a;break;case 3:n&&(s="x"===a,r=s||o.Character.isDecimalDigit(a.charCodeAt(0)),n=n&&!s);break;default:r=r&&!(n&&!o.Character.isDecimalDigit(a.charCodeAt(0))),r=r&&!(s&&!o.Character.isHexDigit(a.charCodeAt(0)))}}if(r&&i&&t.length>2){var u=t.substr(1,t.length-2);n&&u.length>1?t=String.fromCharCode(parseInt(u.substr(1),10)):s&&u.length>2?t=String.fromCharCode(parseInt("0"+u.substr(1),16)):n||s||!c.XHTMLEntities[u]||(t=c.XHTMLEntities[u])}return t},t.prototype.lexJSX=function(){var e=this.scanner.source.charCodeAt(this.scanner.index);if(60===e||62===e||47===e||58===e||61===e||123===e||125===e){var t=this.scanner.source[this.scanner.index++];return{type:a.Token.Punctuator,value:t,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:this.scanner.index-1,end:this.scanner.index}}if(34===e||39===e){for(var r=this.scanner.index,i=this.scanner.source[this.scanner.index++],s="";!this.scanner.eof();){var u=this.scanner.source[this.scanner.index++];if(u===i)break;s+="&"===u?this.scanXHTMLEntity(i):u}return{type:a.Token.StringLiteral,value:s,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:r,end:this.scanner.index}}if(46===e){var c=this.scanner.source.charCodeAt(this.scanner.index+1),l=this.scanner.source.charCodeAt(this.scanner.index+2),t=46===c&&46===l?"...":".",r=this.scanner.index;return this.scanner.index+=t.length,{type:a.Token.Punctuator,value:t,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:r,end:this.scanner.index}}if(96===e)return{type:a.Token.Template,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:this.scanner.index,end:this.scanner.index};if(o.Character.isIdentifierStart(e)&&92!==e){var r=this.scanner.index;for(++this.scanner.index;!this.scanner.eof();){var u=this.scanner.source.charCodeAt(this.scanner.index);if(o.Character.isIdentifierPart(u)&&92!==u)++this.scanner.index;else{if(45!==u)break;++this.scanner.index}}var h=this.scanner.source.slice(r,this.scanner.index);return{type:n.Identifier,value:h,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:r,end:this.scanner.index}}this.scanner.throwUnexpectedToken()},t.prototype.nextJSXToken=function(){this.collectComments(),this.startMarker.index=this.scanner.index,this.startMarker.lineNumber=this.scanner.lineNumber,this.startMarker.lineStart=this.scanner.lineStart;var e=this.lexJSX();return this.lastMarker.index=this.scanner.index,this.lastMarker.lineNumber=this.scanner.lineNumber,this.lastMarker.lineStart=this.scanner.lineStart,this.config.tokens&&this.tokens.push(this.convertToken(e)),e},t.prototype.nextJSXText=function(){this.startMarker.index=this.scanner.index,this.startMarker.lineNumber=this.scanner.lineNumber,this.startMarker.lineStart=this.scanner.lineStart;for(var e=this.scanner.index,t="";!this.scanner.eof();){var r=this.scanner.source[this.scanner.index];if("{"===r||"<"===r)break;++this.scanner.index,t+=r,o.Character.isLineTerminator(r.charCodeAt(0))&&(++this.scanner.lineNumber,"\r"===r&&"\n"===this.scanner.source[this.scanner.index]&&++this.scanner.index,this.scanner.lineStart=this.scanner.index)}this.lastMarker.index=this.scanner.index,this.lastMarker.lineNumber=this.scanner.lineNumber,this.lastMarker.lineStart=this.scanner.lineStart;var i={type:n.Text,value:t,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:e,end:this.scanner.index};return t.length>0&&this.config.tokens&&this.tokens.push(this.convertToken(i)),i},t.prototype.peekJSXToken=function(){var e=this.scanner.index,t=this.scanner.lineNumber,r=this.scanner.lineStart;this.scanner.scanComments();var i=this.lexJSX();return this.scanner.index=e,this.scanner.lineNumber=t,this.scanner.lineStart=r,i},t.prototype.expectJSX=function(e){var t=this.nextJSXToken();t.type===a.Token.Punctuator&&t.value===e||this.throwUnexpectedToken(t)},t.prototype.matchJSX=function(e){var t=this.peekJSXToken();return t.type===a.Token.Punctuator&&t.value===e},t.prototype.parseJSXIdentifier=function(){var e=this.createJSXNode(),t=this.nextJSXToken();return t.type!==n.Identifier&&this.throwUnexpectedToken(t),this.finalize(e,new p.JSXIdentifier(t.value))},t.prototype.parseJSXElementName=function(){var e=this.createJSXNode(),t=this.parseJSXIdentifier();if(this.matchJSX(":")){var r=t;this.expectJSX(":");var i=this.parseJSXIdentifier();t=this.finalize(e,new p.JSXNamespacedName(r,i))}else if(this.matchJSX("."))for(;this.matchJSX(".");){var n=t;this.expectJSX(".");var s=this.parseJSXIdentifier();t=this.finalize(e,new p.JSXMemberExpression(n,s))}return t},t.prototype.parseJSXAttributeName=function(){var e,t=this.createJSXNode(),r=this.parseJSXIdentifier();if(this.matchJSX(":")){var i=r;this.expectJSX(":");var n=this.parseJSXIdentifier();e=this.finalize(t,new p.JSXNamespacedName(i,n))}else e=r;return e},t.prototype.parseJSXStringLiteralAttribute=function(){var e=this.createJSXNode(),t=this.nextJSXToken();t.type!==a.Token.StringLiteral&&this.throwUnexpectedToken(t);var r=this.getTokenRaw(t);return this.finalize(e,new h.Literal(t.value,r))},t.prototype.parseJSXExpressionAttribute=function(){var e=this.createJSXNode();this.expectJSX("{"),this.finishJSX(),this.match("}")&&this.tolerateError("JSX attributes must only be assigned a non-empty expression");var t=this.parseAssignmentExpression();return this.reenterJSX(),this.finalize(e,new p.JSXExpressionContainer(t))},t.prototype.parseJSXAttributeValue=function(){return this.matchJSX("{")?this.parseJSXExpressionAttribute():this.matchJSX("<")?this.parseJSXElement():this.parseJSXStringLiteralAttribute()},t.prototype.parseJSXNameValueAttribute=function(){var e=this.createJSXNode(),t=this.parseJSXAttributeName(),r=null;return this.matchJSX("=")&&(this.expectJSX("="),r=this.parseJSXAttributeValue()),this.finalize(e,new p.JSXAttribute(t,r))},t.prototype.parseJSXSpreadAttribute=function(){var e=this.createJSXNode();this.expectJSX("{"),this.expectJSX("..."),this.finishJSX();var t=this.parseAssignmentExpression();return this.reenterJSX(),this.finalize(e,new p.JSXSpreadAttribute(t))},t.prototype.parseJSXAttributes=function(){for(var e=[];!this.matchJSX("/")&&!this.matchJSX(">");){var t=this.matchJSX("{")?this.parseJSXSpreadAttribute():this.parseJSXNameValueAttribute();e.push(t)}return e},t.prototype.parseJSXOpeningElement=function(){var e=this.createJSXNode();this.expectJSX("<");var t=this.parseJSXElementName(),r=this.parseJSXAttributes(),i=this.matchJSX("/");return i&&this.expectJSX("/"),this.expectJSX(">"),this.finalize(e,new p.JSXOpeningElement(t,i,r))},t.prototype.parseJSXBoundaryElement=function(){var e=this.createJSXNode();if(this.expectJSX("<"),this.matchJSX("/")){this.expectJSX("/");var t=this.parseJSXElementName();return this.expectJSX(">"),this.finalize(e,new p.JSXClosingElement(t))}var r=this.parseJSXElementName(),i=this.parseJSXAttributes(),n=this.matchJSX("/");return n&&this.expectJSX("/"),this.expectJSX(">"),this.finalize(e,new p.JSXOpeningElement(r,n,i))},t.prototype.parseJSXEmptyExpression=function(){var e=this.createJSXChildNode();return this.collectComments(),this.lastMarker.index=this.scanner.index,this.lastMarker.lineNumber=this.scanner.lineNumber,this.lastMarker.lineStart=this.scanner.lineStart,this.finalize(e,new p.JSXEmptyExpression)},t.prototype.parseJSXExpressionContainer=function(){var e=this.createJSXNode();this.expectJSX("{");var t;return this.matchJSX("}")?(t=this.parseJSXEmptyExpression(),this.expectJSX("}")):(this.finishJSX(),t=this.parseAssignmentExpression(),this.reenterJSX()),this.finalize(e,new p.JSXExpressionContainer(t))},t.prototype.parseJSXChildren=function(){for(var e=[];!this.scanner.eof();){var t=this.createJSXChildNode(),r=this.nextJSXText();if(r.start0))break;var o=this.finalize(e.node,new p.JSXElement(e.opening,e.children,e.closing));e=t.pop(),e.children.push(o)}}return e},t.prototype.parseJSXElement=function(){var e=this.createJSXNode(),t=this.parseJSXOpeningElement(),r=[],i=null;if(!t.selfClosing){var n=this.parseComplexJSXElement({node:e,opening:t,closing:i,children:r});r=n.children,i=n.closing}return this.finalize(e,new p.JSXElement(t,r,i))},t.prototype.parseJSXRoot=function(){this.config.tokens&&this.tokens.pop(),this.startJSX();var e=this.parseJSXElement();return this.finishJSX(),e},t}(u.Parser);t.JSXParser=f},function(e,t){"use strict";t.XHTMLEntities={quot:'"',amp:"&",apos:"'",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦",lang:"⟨",rang:"⟩"}},function(e,t){"use strict";t.JSXSyntax={JSXAttribute:"JSXAttribute",JSXClosingElement:"JSXClosingElement",JSXElement:"JSXElement",JSXEmptyExpression:"JSXEmptyExpression",JSXExpressionContainer:"JSXExpressionContainer",JSXIdentifier:"JSXIdentifier",JSXMemberExpression:"JSXMemberExpression",JSXNamespacedName:"JSXNamespacedName",JSXOpeningElement:"JSXOpeningElement",JSXSpreadAttribute:"JSXSpreadAttribute",JSXText:"JSXText"}},function(e,t,r){"use strict";var i=r(13),n=function(){function e(e){this.type=i.JSXSyntax.JSXClosingElement,this.name=e}return e}();t.JSXClosingElement=n;var s=function(){function e(e,t,r){this.type=i.JSXSyntax.JSXElement,this.openingElement=e,this.children=t,this.closingElement=r}return e}();t.JSXElement=s;var o=function(){function e(){this.type=i.JSXSyntax.JSXEmptyExpression}return e}();t.JSXEmptyExpression=o;var a=function(){function e(e){this.type=i.JSXSyntax.JSXExpressionContainer,this.expression=e}return e}();t.JSXExpressionContainer=a;var u=function(){function e(e){this.type=i.JSXSyntax.JSXIdentifier,this.name=e}return e}();t.JSXIdentifier=u;var c=function(){function e(e,t){this.type=i.JSXSyntax.JSXMemberExpression,this.object=e,this.property=t}return e}();t.JSXMemberExpression=c;var l=function(){function e(e,t){this.type=i.JSXSyntax.JSXAttribute,this.name=e,this.value=t}return e}();t.JSXAttribute=l;var h=function(){function e(e,t){this.type=i.JSXSyntax.JSXNamespacedName,this.namespace=e,this.name=t}return e}();t.JSXNamespacedName=h;var p=function(){function e(e,t,r){this.type=i.JSXSyntax.JSXOpeningElement,this.name=e,this.selfClosing=t,this.attributes=r}return e}();t.JSXOpeningElement=p;var f=function(){function e(e){this.type=i.JSXSyntax.JSXSpreadAttribute,this.argument=e}return e}();t.JSXSpreadAttribute=f;var d=function(){function e(e,t){this.type=i.JSXSyntax.JSXText,this.value=e,this.raw=t}return e}();t.JSXText=d},function(e,t,r){"use strict";var i=r(8),n=r(6),s=r(7),o=function(){function e(){this.values=[],this.curly=this.paren=-1}return e.prototype.beforeFunctionExpression=function(e){return["(","{","[","in","typeof","instanceof","new","return","case","delete","throw","void","=","+=","-=","*=","**=","/=","%=","<<=",">>=",">>>=","&=","|=","^=",",","+","-","*","**","/","%","++","--","<<",">>",">>>","&","|","^","!","~","&&","||","?",":","===","==",">=","<=","<",">","!=","!=="].indexOf(e)>=0},e.prototype.isRegexStart=function(){var e=this.values[this.values.length-1],t=null!==e;switch(e){case"this":case"]":t=!1;break;case")":var r=this.values[this.paren-1];t="if"===r||"while"===r||"for"===r||"with"===r;break;case"}":if(t=!1,"function"===this.values[this.curly-3]){var i=this.values[this.curly-4];t=!!i&&!this.beforeFunctionExpression(i)}else if("function"===this.values[this.curly-4]){var n=this.values[this.curly-5];t=!n||!this.beforeFunctionExpression(n)}}return t},e.prototype.push=function(e){e.type===s.Token.Punctuator||e.type===s.Token.Keyword?("{"===e.value?this.curly=this.values.length:"("===e.value&&(this.paren=this.values.length),this.values.push(e.value)):this.values.push(null)},e}(),a=function(){function e(e,t){this.errorHandler=new n.ErrorHandler,this.errorHandler.tolerant=!!t&&("boolean"==typeof t.tolerant&&t.tolerant),this.scanner=new i.Scanner(e,this.errorHandler),this.scanner.trackComment=!!t&&("boolean"==typeof t.comment&&t.comment),this.trackRange=!!t&&("boolean"==typeof t.range&&t.range),this.trackLoc=!!t&&("boolean"==typeof t.loc&&t.loc),this.buffer=[],this.reader=new o}return e.prototype.errors=function(){return this.errorHandler.errors},e.prototype.getNextToken=function(){if(0===this.buffer.length){var e=this.scanner.scanComments();if(this.scanner.trackComment)for(var t=0;ti&&" "!==e[d+1],d=s);else if(!l(o))return le;m=m&&h(o)}u=u||f&&s-d-1>i&&" "!==e[d+1]}return a||u?" "===e[0]&&r>9?le:u?ce:ue:m&&!n(e)?oe:ae}function d(e,t,r,i){e.dump=function(){function n(t){return u(e,t)}if(0===t.length)return"''";if(!e.noCompatMode&&se.indexOf(t)!==-1)return"'"+t+"'";var s=e.indent*Math.max(1,r),a=e.lineWidth===-1?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-s),c=i||e.flowLevel>-1&&r>=e.flowLevel;switch(f(t,c,e.indent,a,n)){case oe:return t;case ae:return"'"+t.replace(/'/g,"''")+"'";case ue:return"|"+m(t,e.indent)+g(o(t,s));case ce:return">"+m(t,e.indent)+g(o(x(t,a),s));case le:return'"'+D(t,a)+'"';default:throw new N("impossible error: invalid scalar style")}}()}function m(e,t){var r=" "===e[0]?String(t):"",i="\n"===e[e.length-1],n=i&&("\n"===e[e.length-2]||"\n"===e),s=n?"+":i?"":"-";return r+s+"\n"}function g(e){return"\n"===e[e.length-1]?e.slice(0,-1):e}function x(e,t){for(var r,i,n=/(\n+)([^\n]*)/g,s=function(){var r=e.indexOf("\n");return r=r!==-1?r:e.length,n.lastIndex=r,y(e.slice(0,r),t)}(),o="\n"===e[0]||" "===e[0];i=n.exec(e);){var a=i[1],u=i[2];r=" "===u[0],s+=a+(o||r||""===u?"":"\n")+y(u,t),o=r}return s}function y(e,t){if(""===e||" "===e[0])return e;for(var r,i,n=/ [^ ]/g,s=0,o=0,a=0,u="";r=n.exec(e);)a=r.index,a-s>t&&(i=o>s?o:a,u+="\n"+e.slice(s,i),s=i+1),o=a;return u+="\n",u+=e.length-s>t&&o>s?e.slice(s,o)+"\n"+e.slice(o+1):e.slice(s),u.slice(1)}function D(e){for(var t,r,i="",s=0;s1024&&(a+="? "),a+=e.dump+": ",A(e,t,o,!1,!1)&&(a+=e.dump,u+=a));e.tag=c,e.dump="{"+u+"}"}function E(e,t,r,i){var n,s,o,u,c,l,h="",p=e.tag,f=Object.keys(r);if(e.sortKeys===!0)f.sort();else if("function"==typeof e.sortKeys)f.sort(e.sortKeys);else if(e.sortKeys)throw new N("sortKeys must be a boolean or a function"); +for(n=0,s=f.length;n1024,c&&(l+=e.dump&&R===e.dump.charCodeAt(0)?"?":"? "),l+=e.dump,c&&(l+=a(e,t)),A(e,t+1,u,!0,c)&&(l+=e.dump&&R===e.dump.charCodeAt(0)?":":": ",l+=e.dump,h+=l));e.tag=p,e.dump=h||"{}"}function k(e,t,r){var i,n,s,o,a,u;for(n=r?e.explicitTypes:e.implicitTypes,s=0,o=n.length;s tag resolver accepts not "'+u+'" style');i=a.represent[u](t,u)}e.dump=i}return!0}return!1}function A(e,t,r,i,n,s){e.tag=null,e.dump=r,k(e,r,!1)||k(e,r,!0);var o=M.call(e.dump);i&&(i=e.flowLevel<0||e.flowLevel>t);var a,u,c="[object Object]"===o||"[object Array]"===o;if(c&&(a=e.duplicates.indexOf(r),u=a!==-1),(null!==e.tag&&"?"!==e.tag||u||2!==e.indent&&t>0)&&(n=!1),u&&e.usedDuplicates[a])e.dump="*ref_"+a;else{if(c&&u&&!e.usedDuplicates[a]&&(e.usedDuplicates[a]=!0),"[object Object]"===o)i&&0!==Object.keys(e.dump).length?(E(e,t,e.dump,n),u&&(e.dump="&ref_"+a+e.dump)):(w(e,t,e.dump),u&&(e.dump="&ref_"+a+" "+e.dump));else if("[object Array]"===o)i&&0!==e.dump.length?(v(e,t,e.dump,n),u&&(e.dump="&ref_"+a+e.dump)):(b(e,t,e.dump),u&&(e.dump="&ref_"+a+" "+e.dump));else{if("[object String]"!==o){if(e.skipInvalid)return!1;throw new N("unacceptable kind of an object to dump "+o)}"?"!==e.tag&&d(e,e.dump,t,s)}null!==e.tag&&"?"!==e.tag&&(e.dump="!<"+e.tag+"> "+e.dump)}return!0}function C(e,t){var r,i,n=[],s=[];for(S(e,n,s),r=0,i=s.length;rlabel{font-size:12px;font-weight:700;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;margin:-20px 15px 0 0;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .scheme-container .schemes>label select{min-width:130px;text-transform:uppercase}.swagger-ui .loading-container{padding:40px 0 60px}.swagger-ui .loading-container .loading{position:relative}.swagger-ui .loading-container .loading:after{font-size:10px;font-weight:700;position:absolute;top:50%;left:50%;content:"loading";-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);text-transform:uppercase;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .loading-container .loading:before{position:absolute;top:50%;left:50%;display:block;width:60px;height:60px;margin:-30px;content:"";-webkit-animation:rotation 1s infinite linear,opacity .5s;animation:rotation 1s infinite linear,opacity .5s;opacity:1;border:2px solid rgba(85,85,85,.1);border-top-color:rgba(0,0,0,.6);border-radius:100%;-webkit-backface-visibility:hidden;backface-visibility:hidden}@-webkit-keyframes rotation{to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes rotation{to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@-webkit-keyframes blinker{50%{opacity:0}}@keyframes blinker{50%{opacity:0}}.swagger-ui .btn{font-size:14px;font-weight:700;padding:5px 23px;transition:all .3s;border:2px solid #888;border-radius:4px;background:transparent;box-shadow:0 1px 2px rgba(0,0,0,.1);font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .btn[disabled]{cursor:not-allowed;opacity:.3}.swagger-ui .btn:hover{box-shadow:0 0 5px rgba(0,0,0,.3)}.swagger-ui .btn.cancel{border-color:#ff6060;font-family:Titillium Web,sans-serif;color:#ff6060}.swagger-ui .btn.authorize{line-height:1;display:inline;color:#49cc90;border-color:#49cc90}.swagger-ui .btn.authorize span{float:left;padding:4px 20px 0 0}.swagger-ui .btn.authorize svg{fill:#49cc90}.swagger-ui .btn.execute{-webkit-animation:pulse 2s infinite;animation:pulse 2s infinite;color:#fff;border-color:#4990e2}@-webkit-keyframes pulse{0%{color:#fff;background:#4990e2;box-shadow:0 0 0 0 rgba(73,144,226,.8)}70%{box-shadow:0 0 0 5px rgba(73,144,226,0)}to{color:#fff;background:#4990e2;box-shadow:0 0 0 0 rgba(73,144,226,0)}}@keyframes pulse{0%{color:#fff;background:#4990e2;box-shadow:0 0 0 0 rgba(73,144,226,.8)}70%{box-shadow:0 0 0 5px rgba(73,144,226,0)}to{color:#fff;background:#4990e2;box-shadow:0 0 0 0 rgba(73,144,226,0)}}.swagger-ui .btn-group{display:-webkit-box;display:-ms-flexbox;display:flex;padding:30px}.swagger-ui .btn-group .btn{-webkit-box-flex:1;-ms-flex:1;flex:1}.swagger-ui .btn-group .btn:first-child{border-radius:4px 0 0 4px}.swagger-ui .btn-group .btn:last-child{border-radius:0 4px 4px 0}.swagger-ui .authorization__btn{padding:0 10px;border:none;background:none}.swagger-ui .authorization__btn.locked{opacity:1}.swagger-ui .authorization__btn.unlocked{opacity:.4}.swagger-ui .expand-methods,.swagger-ui .expand-operation{border:none;background:none}.swagger-ui .expand-methods svg,.swagger-ui .expand-operation svg{width:20px;height:20px}.swagger-ui .expand-methods{padding:0 10px}.swagger-ui .expand-methods:hover svg{fill:#444}.swagger-ui .expand-methods svg{transition:all .3s;fill:#777}.swagger-ui button{cursor:pointer;outline:none}.swagger-ui select{font-size:14px;font-weight:700;padding:5px 40px 5px 10px;border:2px solid #41444e;border-radius:4px;background:#f7f7f7 url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyMCAyMCI+ICAgIDxwYXRoIGQ9Ik0xMy40MTggNy44NTljLjI3MS0uMjY4LjcwOS0uMjY4Ljk3OCAwIC4yNy4yNjguMjcyLjcwMSAwIC45NjlsLTMuOTA4IDMuODNjLS4yNy4yNjgtLjcwNy4yNjgtLjk3OSAwbC0zLjkwOC0zLjgzYy0uMjctLjI2Ny0uMjctLjcwMSAwLS45NjkuMjcxLS4yNjguNzA5LS4yNjguOTc4IDBMMTAgMTFsMy40MTgtMy4xNDF6Ii8+PC9zdmc+) right 10px center no-repeat;background-size:20px;box-shadow:0 1px 2px 0 rgba(0,0,0,.25);font-family:Titillium Web,sans-serif;color:#3b4151;-webkit-appearance:none;-moz-appearance:none;appearance:none}.swagger-ui select[multiple]{margin:5px 0;padding:5px;background:#f7f7f7}.swagger-ui .opblock-body select{min-width:230px}.swagger-ui label{font-size:12px;font-weight:700;margin:0 0 5px;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui input[type=email],.swagger-ui input[type=password],.swagger-ui input[type=search],.swagger-ui input[type=text]{min-width:100px;margin:5px 0;padding:8px 10px;border:1px solid #d9d9d9;border-radius:4px;background:#fff}.swagger-ui input[type=email].invalid,.swagger-ui input[type=password].invalid,.swagger-ui input[type=search].invalid,.swagger-ui input[type=text].invalid{-webkit-animation:shake .4s 1;animation:shake .4s 1;border-color:#f93e3e;background:#feebeb}@-webkit-keyframes shake{10%,90%{-webkit-transform:translate3d(-1px,0,0);transform:translate3d(-1px,0,0)}20%,80%{-webkit-transform:translate3d(2px,0,0);transform:translate3d(2px,0,0)}30%,50%,70%{-webkit-transform:translate3d(-4px,0,0);transform:translate3d(-4px,0,0)}40%,60%{-webkit-transform:translate3d(4px,0,0);transform:translate3d(4px,0,0)}}@keyframes shake{10%,90%{-webkit-transform:translate3d(-1px,0,0);transform:translate3d(-1px,0,0)}20%,80%{-webkit-transform:translate3d(2px,0,0);transform:translate3d(2px,0,0)}30%,50%,70%{-webkit-transform:translate3d(-4px,0,0);transform:translate3d(-4px,0,0)}40%,60%{-webkit-transform:translate3d(4px,0,0);transform:translate3d(4px,0,0)}}.swagger-ui textarea{font-size:12px;width:100%;min-height:280px;padding:10px;border:none;border-radius:4px;outline:none;background:hsla(0,0%,100%,.8);font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui textarea:focus{border:2px solid #61affe}.swagger-ui textarea.curl{font-size:12px;min-height:100px;margin:0;padding:10px;resize:none;border-radius:4px;background:#41444e;font-family:Source Code Pro,monospace;font-weight:600;color:#fff}.swagger-ui .checkbox{padding:5px 0 10px;transition:opacity .5s;color:#333}.swagger-ui .checkbox label{display:-webkit-box;display:-ms-flexbox;display:flex}.swagger-ui .checkbox p{font-weight:400!important;font-style:italic;margin:0!important;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .checkbox input[type=checkbox]{display:none}.swagger-ui .checkbox input[type=checkbox]+label>.item{position:relative;top:3px;display:inline-block;width:16px;height:16px;margin:0 8px 0 0;padding:5px;cursor:pointer;border-radius:1px;background:#e8e8e8;box-shadow:0 0 0 2px #e8e8e8;-webkit-box-flex:0;-ms-flex:none;flex:none}.swagger-ui .checkbox input[type=checkbox]+label>.item:active{-webkit-transform:scale(.9);transform:scale(.9)}.swagger-ui .checkbox input[type=checkbox]:checked+label>.item{background:#e8e8e8 url("data:image/svg+xml;charset=utf-8,%3Csvg width='10' height='8' viewBox='3 7 10 8' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='%2341474E' fill-rule='evenodd' d='M6.333 15L3 11.667l1.333-1.334 2 2L11.667 7 13 8.333z'/%3E%3C/svg%3E") 50% no-repeat}.swagger-ui .dialog-ux{position:fixed;z-index:9999;top:0;right:0;bottom:0;left:0}.swagger-ui .dialog-ux .backdrop-ux{position:fixed;top:0;right:0;bottom:0;left:0;background:rgba(0,0,0,.8)}.swagger-ui .dialog-ux .modal-ux{position:absolute;z-index:9999;top:50%;left:50%;width:100%;min-width:300px;max-width:650px;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);border:1px solid #ebebeb;border-radius:4px;background:#fff;box-shadow:0 10px 30px 0 rgba(0,0,0,.2)}.swagger-ui .dialog-ux .modal-ux-content{overflow-y:auto;max-height:540px;padding:20px}.swagger-ui .dialog-ux .modal-ux-content p{font-size:12px;margin:0 0 5px;color:#41444e;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .dialog-ux .modal-ux-content h4{font-size:18px;font-weight:600;margin:15px 0 0;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .dialog-ux .modal-ux-header{display:-webkit-box;display:-ms-flexbox;display:flex;padding:12px 0;border-bottom:1px solid #ebebeb;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.swagger-ui .dialog-ux .modal-ux-header .close-modal{padding:0 10px;border:none;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none}.swagger-ui .dialog-ux .modal-ux-header h3{font-size:20px;font-weight:600;margin:0;padding:0 20px;-webkit-box-flex:1;-ms-flex:1;flex:1;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .model{font-size:12px;font-weight:300;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .model-toggle{font-size:10px;position:relative;top:6px;display:inline-block;margin:auto .3em;cursor:pointer;transition:-webkit-transform .15s ease-in;transition:transform .15s ease-in;transition:transform .15s ease-in,-webkit-transform .15s ease-in;-webkit-transform:rotate(90deg);transform:rotate(90deg);-webkit-transform-origin:50% 50%;transform-origin:50% 50%}.swagger-ui .model-toggle.collapsed{-webkit-transform:rotate(0deg);transform:rotate(0deg)}.swagger-ui .model-toggle:after{display:block;width:20px;height:20px;content:"";background:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z'/%3E%3C/svg%3E") 50% no-repeat;background-size:100%}.swagger-ui .model-jump-to-path{position:relative;cursor:pointer}.swagger-ui .model-jump-to-path .view-line-link{position:absolute;top:-.4em;cursor:pointer}.swagger-ui .model-title{position:relative}.swagger-ui .model-title:hover .model-hint{visibility:visible}.swagger-ui .model-hint{position:absolute;top:-1.8em;visibility:hidden;padding:.1em .5em;white-space:nowrap;color:#ebebeb;border-radius:4px;background:rgba(0,0,0,.7)}.swagger-ui section.models{margin:30px 0;border:1px solid rgba(59,65,81,.3);border-radius:4px}.swagger-ui section.models.is-open{padding:0 0 20px}.swagger-ui section.models.is-open h4{margin:0 0 5px;border-bottom:1px solid rgba(59,65,81,.3)}.swagger-ui section.models.is-open h4 svg{-webkit-transform:rotate(90deg);transform:rotate(90deg)}.swagger-ui section.models h4{font-size:16px;display:-webkit-box;display:-ms-flexbox;display:flex;margin:0;padding:10px 20px 10px 10px;cursor:pointer;transition:all .2s;font-family:Titillium Web,sans-serif;color:#777;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.swagger-ui section.models h4 svg{transition:all .4s}.swagger-ui section.models h4 span{-webkit-box-flex:1;-ms-flex:1;flex:1}.swagger-ui section.models h4:hover{background:rgba(0,0,0,.02)}.swagger-ui section.models h5{font-size:16px;margin:0 0 10px;font-family:Titillium Web,sans-serif;color:#777}.swagger-ui section.models .model-jump-to-path{position:relative;top:5px}.swagger-ui section.models .model-container{margin:0 20px 15px;transition:all .5s;border-radius:4px;background:rgba(0,0,0,.05)}.swagger-ui section.models .model-container:hover{background:rgba(0,0,0,.07)}.swagger-ui section.models .model-container:first-of-type{margin:20px}.swagger-ui section.models .model-container:last-of-type{margin:0 20px}.swagger-ui section.models .model-box{background:none}.swagger-ui .model-box{padding:10px;border-radius:4px;background:rgba(0,0,0,.1)}.swagger-ui .model-box .model-jump-to-path{position:relative;top:4px}.swagger-ui .model-title{font-size:16px;font-family:Titillium Web,sans-serif;color:#555}.swagger-ui span>span.model,.swagger-ui span>span.model .brace-close{padding:0 0 0 10px}.swagger-ui .prop-type{color:#55a}.swagger-ui .prop-enum{display:block}.swagger-ui .prop-format{color:#999}.swagger-ui table{width:100%;padding:0 10px;border-collapse:collapse}.swagger-ui table.model tbody tr td{padding:0;vertical-align:top}.swagger-ui table.model tbody tr td:first-of-type{width:100px;padding:0}.swagger-ui table.headers td{font-size:12px;font-weight:300;vertical-align:middle;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui table tbody tr td{padding:10px 0 0;vertical-align:top}.swagger-ui table tbody tr td:first-of-type{width:20%;padding:10px 0}.swagger-ui table thead tr td,.swagger-ui table thead tr th{font-size:12px;font-weight:700;padding:12px 0;text-align:left;border-bottom:1px solid rgba(59,65,81,.2);font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .parameters-col_description p{font-size:14px;margin:0;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .parameters-col_description input[type=text]{width:100%;max-width:340px}.swagger-ui .parameter__name{font-size:16px;font-weight:400;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .parameter__name.required{font-weight:700}.swagger-ui .parameter__name.required:after{font-size:10px;position:relative;top:-6px;padding:5px;content:"required";color:rgba(255,0,0,.6)}.swagger-ui .parameter__in{font-size:12px;font-style:italic;font-family:Source Code Pro,monospace;font-weight:600;color:#888}.swagger-ui .table-container{padding:20px}.swagger-ui .topbar{padding:8px 30px;background-color:#89bf04}.swagger-ui .topbar .topbar-wrapper{-ms-flex-align:center}.swagger-ui .topbar .topbar-wrapper,.swagger-ui .topbar a{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;align-items:center}.swagger-ui .topbar a{font-size:1.5em;font-weight:700;max-width:300px;text-decoration:none;-webkit-box-flex:1;-ms-flex:1;flex:1;-ms-flex-align:center;font-family:Titillium Web,sans-serif;color:#fff}.swagger-ui .topbar a span{margin:0;padding:0 10px}.swagger-ui .topbar .download-url-wrapper{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-flex:3;-ms-flex:3;flex:3}.swagger-ui .topbar .download-url-wrapper input[type=text]{width:100%;min-width:350px;margin:0;border:2px solid #547f00;border-radius:4px 0 0 4px;outline:none}.swagger-ui .topbar .download-url-wrapper .download-url-button{font-size:16px;font-weight:700;padding:4px 40px;border:none;border-radius:0 4px 4px 0;background:#547f00;font-family:Titillium Web,sans-serif;color:#fff}.swagger-ui .info{margin:50px 0}.swagger-ui .info hgroup.main{margin:0 0 20px}.swagger-ui .info hgroup.main a{font-size:12px}.swagger-ui .info li,.swagger-ui .info p,.swagger-ui .info table{font-size:14px;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .info h1,.swagger-ui .info h2,.swagger-ui .info h3,.swagger-ui .info h4,.swagger-ui .info h5{font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .info code{padding:3px 5px;border-radius:4px;background:rgba(0,0,0,.05);font-family:Source Code Pro,monospace;font-weight:600;color:#9012fe}.swagger-ui .info a{font-size:14px;transition:all .4s;font-family:Open Sans,sans-serif;color:#4990e2}.swagger-ui .info a:hover{color:#1f69c0}.swagger-ui .info>div{margin:0 0 5px}.swagger-ui .info .base-url{font-size:12px;font-weight:300!important;margin:0;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .info .title{font-size:36px;margin:0;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .info .title small{font-size:10px;position:relative;top:-5px;display:inline-block;margin:0 0 0 5px;padding:2px 4px;vertical-align:super;border-radius:57px;background:#7d8492}.swagger-ui .info .title small pre{margin:0;font-family:Titillium Web,sans-serif;color:#fff}.swagger-ui .auth-btn-wrapper{display:-webkit-box;display:-ms-flexbox;display:flex;padding:10px 0;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center}.swagger-ui .auth-wrapper{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-flex:1;-ms-flex:1;flex:1;-webkit-box-pack:end;-ms-flex-pack:end;justify-content:flex-end}.swagger-ui .auth-wrapper .authorize{padding-right:20px}.swagger-ui .auth-container{margin:0 0 10px;padding:10px 20px;border-bottom:1px solid #ebebeb}.swagger-ui .auth-container:last-of-type{margin:0;padding:10px 20px;border:0}.swagger-ui .auth-container h4{margin:5px 0 15px!important}.swagger-ui .auth-container .wrapper{margin:0;padding:0}.swagger-ui .auth-container input[type=password],.swagger-ui .auth-container input[type=text]{min-width:230px}.swagger-ui .auth-container .errors{font-size:12px;padding:10px;border-radius:4px;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .scopes h2{font-size:14px;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .scope-def{padding:0 0 20px}.swagger-ui .errors-wrapper{margin:20px;padding:10px 20px;-webkit-animation:scaleUp .5s;animation:scaleUp .5s;border:2px solid #f93e3e;border-radius:4px;background:rgba(249,62,62,.1)}.swagger-ui .errors-wrapper .error-wrapper{margin:0 0 10px}.swagger-ui .errors-wrapper .errors h4{font-size:14px;margin:0;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .errors-wrapper .errors small{color:#666}.swagger-ui .errors-wrapper hgroup{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.swagger-ui .errors-wrapper hgroup h4{font-size:20px;margin:0;-webkit-box-flex:1;-ms-flex:1;flex:1;font-family:Titillium Web,sans-serif;color:#3b4151}@-webkit-keyframes scaleUp{0%{-webkit-transform:scale(.8);transform:scale(.8);opacity:0}to{-webkit-transform:scale(1);transform:scale(1);opacity:1}}@keyframes scaleUp{0%{-webkit-transform:scale(.8);transform:scale(.8);opacity:0}to{-webkit-transform:scale(1);transform:scale(1);opacity:1}}.swagger-ui .Resizer.vertical.disabled{display:none} +/*# sourceMappingURL=swagger-ui.css.map*/ \ No newline at end of file diff --git a/bmp-pronoea/swagger/swagger-ui.css.map b/bmp-pronoea/swagger/swagger-ui.css.map new file mode 100644 index 0000000..dbf47ea --- /dev/null +++ b/bmp-pronoea/swagger/swagger-ui.css.map @@ -0,0 +1 @@ +{"version":3,"file":"swagger-ui.css","sources":[],"mappings":"","sourceRoot":""} \ No newline at end of file diff --git a/bmp-pronoea/swagger/swagger-ui.js b/bmp-pronoea/swagger/swagger-ui.js new file mode 100644 index 0000000..fed293d --- /dev/null +++ b/bmp-pronoea/swagger/swagger-ui.js @@ -0,0 +1,15 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("babel-polyfill"),require("deep-extend"),require("redux"),require("immutable"),require("redux-immutable"),require("serialize-error"),require("base64-js"),require("ieee754"),require("isarray"),require("shallowequal"),require("xml"),require("memoizee"),require("reselect"),require("js-yaml"),require("url-parse"),require("react"),require("react-dom"),require("react-redux"),require("yaml-js"),require("swagger-client"),require("react-split-pane"),require("react-immutable-proptypes"),require("react-addons-shallow-compare"),require("react-collapse"),require("react-remarkable"),require("sanitize-html")):"function"==typeof define&&define.amd?define(["babel-polyfill","deep-extend","redux","immutable","redux-immutable","serialize-error","base64-js","ieee754","isarray","shallowequal","xml","memoizee","reselect","js-yaml","url-parse","react","react-dom","react-redux","yaml-js","swagger-client","react-split-pane","react-immutable-proptypes","react-addons-shallow-compare","react-collapse","react-remarkable","sanitize-html"],t):"object"==typeof exports?exports.SwaggerUICore=t(require("babel-polyfill"),require("deep-extend"),require("redux"),require("immutable"),require("redux-immutable"),require("serialize-error"),require("base64-js"),require("ieee754"),require("isarray"),require("shallowequal"),require("xml"),require("memoizee"),require("reselect"),require("js-yaml"),require("url-parse"),require("react"),require("react-dom"),require("react-redux"),require("yaml-js"),require("swagger-client"),require("react-split-pane"),require("react-immutable-proptypes"),require("react-addons-shallow-compare"),require("react-collapse"),require("react-remarkable"),require("sanitize-html")):e.SwaggerUICore=t(e["babel-polyfill"],e["deep-extend"],e.redux,e.immutable,e["redux-immutable"],e["serialize-error"],e["base64-js"],e.ieee754,e.isarray,e.shallowequal,e.xml,e.memoizee,e.reselect,e["js-yaml"],e["url-parse"],e.react,e["react-dom"],e["react-redux"],e["yaml-js"],e["swagger-client"],e["react-split-pane"],e["react-immutable-proptypes"],e["react-addons-shallow-compare"],e["react-collapse"],e["react-remarkable"],e["sanitize-html"])}(this,function(e,t,r,n,o,a,u,i,s,l,c,f,p,d,h,y,m,v,b,g,_,E,w,j,P,O){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="/dist",t(0)}(function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))switch(typeof e[t]){case"function":break;case"object":e[t]=function(t){var r=t.slice(1),n=e[t[0]];return function(e,t,o){n.apply(this,[e,t,o].concat(r))}}(e[t]);break;default:e[t]=e[e[t]]}return e}([function(e,t,r){r(1),r(2),e.exports=r(3)},function(e,t){e.exports=require("babel-polyfill")},function(e,t){},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u=r(4),i=o(u),s=r(5),l=o(s),c=r(11),f=o(c),p=r(157),d=o(p),h=r(316),y=n(h),m=r(12),v=["url","spec","validatorUrl","onComplete","onFailure","authorizations","docExpansion","apisSorter","operationsSorter","supportedSubmitMethods","dom_id","defaultModelRendering","oauth2RedirectUrl","showRequestHeaders","custom","modelPropertyMacro","parameterMacro"],b={PACKAGE_VERSION:"3.0.13",GIT_COMMIT:"g5952bb6",GIT_DIRTY:!1},g=b.GIT_DIRTY,_=b.GIT_COMMIT,E=b.PACKAGE_VERSION;e.exports=function(e){f.default.versions=f.default.versions||{},f.default.versions.swaggerUi=E+"/"+(_||"unknown")+(g?"-dirty":"");var t={dom_id:null,spec:{},url:"",layout:"BaseLayout",validatorUrl:"https://online.swagger.io/validator",configs:{},custom:{},presets:[],plugins:[],fn:{},components:{},state:{},store:{}},r=(0,i.default)({},t,e),n=(0,i.default)({},r.store,{system:{configs:r.configs},plugins:r.presets,state:{layout:{layout:r.layout},spec:{spec:"",url:r.url}}}),o=function(){return{fn:r.fn,components:r.components,state:r.state}},u=new l.default(n);u.register([r.plugins,o]);var s=u.getSystem(),c=(0,m.parseSeach)();s.initOAuth=s.authActions.configureAuth;var p=function(e){if("object"!==("undefined"==typeof r?"undefined":a(r)))return s;var t=s.specSelectors.getLocalConfig?s.specSelectors.getLocalConfig():{},n=(0,i.default)({},t,r,e||{},c);return u.setConfigs((0,m.filterConfigs)(n,v)),null!==e&&(!c.url&&"object"===a(n.spec)&&Object.keys(n.spec).length?(s.specActions.updateUrl(""),s.specActions.updateLoadingStatus("success"),s.specActions.updateSpec(JSON.stringify(n.spec))):s.specActions.download&&n.url&&(s.specActions.updateUrl(n.url),s.specActions.download(n.url))),n.dom_id?s.render(n.dom_id,"App"):console.error("Skipped rendering: no `dom_id` was specified"),s},d=c.config||r.configUrl;if(!d||!s.specActions.getConfigByUrl||s.specActions.getConfigByUrl&&!s.specActions.getConfigByUrl(d,p))return p()},e.exports.presets={apis:d.default},e.exports.plugins=y},function(e,t){e.exports=require("deep-extend")},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t,r){var n=[(0,O.systemThunkMiddleware)(r)],o=P.default.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__||h.compose;return(0,h.createStore)(e,t,o(h.applyMiddleware.apply(void 0,n)))}function i(e,t){return(0,O.isObject)(e)&&!(0,O.isArray)(e)?e:(0,O.isFunc)(e)?i(e(t),t):(0,O.isArray)(e)?e.map(function(e){return i(e,t)}).reduce(s,{}):{}}function s(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!(0,O.isObject)(e))return{};if(!(0,O.isObject)(t))return e;var r=e.statePlugins;if((0,O.isObject)(r))for(var n in r){var o=r[n];if((0,O.isObject)(o)&&(0,O.isObject)(o.wrapActions)){var a=o.wrapActions;for(var u in a){var i=a[u];Array.isArray(i)||(i=[i],a[u]=i),t&&t.statePlugins&&t.statePlugins[n]&&t.statePlugins[n].wrapActions&&t.statePlugins[n].wrapActions[u]&&(t.statePlugins[n].wrapActions[u]=a[u].concat(t.statePlugins[n].wrapActions[u]))}}}return(0,b.default)(e,t)}function l(e){var t=(0,O.objMap)(e,function(e){return e.reducers});return c(t)}function c(e){var t=Object.keys(e).reduce(function(t,r){return t[r]=f(e[r]),t},{});return Object.keys(t).length?(0,g.combineReducers)(t):T}function f(e){return function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new y.Map,r=arguments[1];if(!e)return t;var n=e[r.type];return n?n(t,r):t}}function p(e,t,r){var n=u(e,t,r);return n}Object.defineProperty(t,"__esModule",{value:!0});var d=function(){function e(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{};a(this,e),(0,b.default)(this,{state:{},plugins:[],system:{configs:{},fn:{},components:{},rootInjects:{},statePlugins:{}},boundSystem:{},toolbox:{}},t),this.getSystem=this._getSystem.bind(this),this.store=p(T,(0,y.fromJS)(this.state),this.getSystem),this.buildSystem(!1),this.register(this.plugins)}return d(e,[{key:"getStore",value:function(){return this.store}},{key:"register",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=i(e,this.getSystem());s(this.system,r),t&&this.buildSystem()}},{key:"buildSystem",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=this.getStore().dispatch,r=this.getStore().getState;this.boundSystem=Object.assign({},this.getRootInjects(),this.getWrappedAndBoundActions(t),this.getBoundSelectors(r,this.getSystem),this.getStateThunks(r),this.getFn(),this.getConfigs()),e&&this.rebuildReducer()}},{key:"_getSystem",value:function(){return this.boundSystem}},{key:"getRootInjects",value:function(){return Object.assign({getSystem:this.getSystem,getStore:this.getStore.bind(this),getComponents:this.getComponents.bind(this),getState:this.getStore().getState,getConfigs:this._getConfigs.bind(this),Im:m.default},this.system.rootInjects||{})}},{key:"_getConfigs",value:function(){return this.system.configs}},{key:"getConfigs",value:function(){return{configs:this.system.configs}}},{key:"setConfigs",value:function(e){this.system.configs=e}},{key:"rebuildReducer",value:function(){this.store.replaceReducer(l(this.system.statePlugins))}},{key:"getType",value:function(e){var t=e[0].toUpperCase()+e.slice(1);return(0,O.objReduce)(this.system.statePlugins,function(r,n){var a=r[e];if(a)return o({},n+t,a)})}},{key:"getSelectors",value:function(){return this.getType("selectors")}},{key:"getActions",value:function(){var e=this.getType("actions");return(0,O.objMap)(e,function(e){return(0,O.objReduce)(e,function(e,t){if((0,O.isFn)(e))return o({},t,e)})})}},{key:"getWrappedAndBoundActions",value:function(e){var t=this,r=this.getBoundActions(e);return(0,O.objMap)(r,function(e,r){var n=t.system.statePlugins[r.slice(0,-7)].wrapActions;return n?(0,O.objMap)(e,function(e,r){var o=n[r];return o?(Array.isArray(o)||(o=[o]),o.reduce(function(e,r){var n=function(){return r(e,t.getSystem()).apply(void 0,arguments)};if(!(0,O.isFn)(n))throw new TypeError("wrapActions needs to return a function that returns a new function (ie the wrapped action)");return n},e||Function.prototype)):e}):e})}},{key:"getStates",value:function(e){return Object.keys(this.system.statePlugins).reduce(function(t,r){return t[r]=e.get(r),t},{})}},{key:"getStateThunks",value:function(e){return Object.keys(this.system.statePlugins).reduce(function(t,r){return t[r]=function(){return e().get(r)},t},{})}},{key:"getFn",value:function(){return{fn:this.system.fn}}},{key:"getComponents",value:function(e){return"undefined"!=typeof e?this.system.components[e]:this.system.components}},{key:"getBoundSelectors",value:function(e,t){return(0,O.objMap)(this.getSelectors(),function(r,n){var o=[n.slice(0,-9)],a=function(){return e().getIn(o)};return(0,O.objMap)(r,function(e){return function(){for(var r=arguments.length,n=Array(r),o=0;o0&&void 0!==arguments[0]?arguments[0]:{};return{type:y,payload:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.CLEAR=t.NEW_AUTH_ERR=t.NEW_SPEC_ERR=t.NEW_THROWN_ERR_BATCH=t.NEW_THROWN_ERR=void 0,t.newThrownErr=o,t.newThrownErrBatch=a,t.newSpecErr=u,t.newAuthErr=i,t.clear=s;var l=r(9),c=n(l),f=t.NEW_THROWN_ERR="err_new_thrown_err",p=t.NEW_THROWN_ERR_BATCH="err_new_thrown_err_batch",d=t.NEW_SPEC_ERR="err_new_spec_err",h=t.NEW_AUTH_ERR="err_new_auth_err",y=t.CLEAR="err_clear"},function(e,t){"use strict";function r(){var e={location:{},history:{},open:function(){},close:function(){}};if("undefined"==typeof window)return e;try{e=window;var t=["File","Blob","FormData"],r=!0,n=!1,o=void 0;try{for(var a,u=t[Symbol.iterator]();!(r=(a=u.next()).done);r=!0){var i=a.value;i in window&&(e[i]=window[i])}}catch(e){n=!0,o=e}finally{try{!r&&u.return&&u.return()}finally{if(n)throw o}}}catch(e){console.error(e)}return e}e.exports=r()},function(e,t,r){(function(e){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){return c(e)?F(e)?e.toObject():e:{}}function a(e){return e?e.toArray?e.toArray():s(e):[]}function u(e){return F(e)?e:c(e)?Array.isArray(e)?S.default.Seq(e).map(u).toList():S.default.Seq(e).map(u).toOrderedMap():e}function i(e,t){var r={};return Object.keys(e).filter(function(t){return"function"==typeof e[t]}).forEach(function(n){return r[n]=e[n].bind(null,t)}),r}function s(e){return Array.isArray(e)?e:[e]}function l(e){return"function"==typeof e}function c(e){return!!e&&"object"===("undefined"==typeof e?"undefined":O(e))}function f(e){return"function"==typeof e}function p(e){return Array.isArray(e)}function d(e,t){return Object.keys(e).reduce(function(r,n){return r[n]=t(e[n],n),r},{})}function h(e,t){return Object.keys(e).reduce(function(r,n){var o=t(e[n],n);return o&&"object"===("undefined"==typeof o?"undefined":O(o))&&Object.assign(r,o),r},{})}function y(e){return function(t){t.dispatch,t.getState;return function(t){return function(r){return"function"==typeof r?r(e()):t(r)}}}}function m(e){var t=e.keySeq();return t.contains(B)?B:t.filter(function(e){return"2"===(e+"")[0]}).sort().first()}function v(e,t){if(!S.default.Iterable.isIterable(e))return S.default.List();var r=e.getIn(Array.isArray(t)?t:[t]);return S.default.List.isList(r)?r:S.default.List()}function b(e){var t,r,n,o,a,u,i,s,l,c,f,p;for(c=/(>)(<)(\/*)/g,p=/[ ]*(.*)[ ]+\n/g,t=/(<.+>)(.+\n)/g,e=e.replace(/\r\n/g,"\n").replace(c,"$1\n$2$3").replace(p,"$1\n").replace(t,"$1\n$2"),n="",s=e.split("\n"),o=0,u="other",f={"single->single":0,"single->closing":-1,"single->opening":0,"single->other":0,"closing->single":0,"closing->closing":-1,"closing->opening":0,"closing->other":0,"opening->single":1,"opening->closing":0,"opening->opening":1,"opening->other":1,"other->single":0,"other->closing":-1,"other->opening":0,"other->other":0},r=function(e){var t,r,a,i,s,l;s={single:Boolean(e.match(/<.+\/>/)),closing:Boolean(e.match(/<\/.+>/)),opening:Boolean(e.match(/<[^!?].*>/))},i=function(){var e;e=[];for(r in s)l=s[r],l&&e.push(r);return e}()[0],i=void 0===i?"other":i,t=u+"->"+i,u=i,a="",o+=f[t],a=function(){var e,t,r,n;for(r=[],n=e=0,t=o;0<=t?et;n=0<=t?++e:--e)r.push(" ");return r}().join(""),"opening->closing"===t?n=n.substr(0,n.length-1)+e+"\n":n+=a+e+"\n"},a=0,i=s.length;at)return e.textContent;var a=function(e){for(var t,a,u,i,s,l=e.textContent,c=0,f=l[0],p=1,d=e.innerHTML="",h=0;a=t,t=h<7&&"\\"==t?1:p;){if(p=f,f=l[++c],i=d.length>1,!p||h>8&&"\n"==p||[/\S/[o](p),1,1,!/[$\w]/[o](p),("/"==t||"\n"==t)&&i,'"'==t&&i,"'"==t&&i,l[c-4]+a+t=="-->",a+t=="*/"][h])for(d&&(e[n](s=r.createElement("span")).setAttribute("style",["color: #555; font-weight: bold;","","","color: #555;",""][h?h<3?2:h>6?4:h>3?3:+/^(a(bstract|lias|nd|rguments|rray|s(m|sert)?|uto)|b(ase|egin|ool(ean)?|reak|yte)|c(ase|atch|har|hecked|lass|lone|ompl|onst|ontinue)|de(bugger|cimal|clare|f(ault|er)?|init|l(egate|ete)?)|do|double|e(cho|ls?if|lse(if)?|nd|nsure|num|vent|x(cept|ec|p(licit|ort)|te(nds|nsion|rn)))|f(allthrough|alse|inal(ly)?|ixed|loat|or(each)?|riend|rom|unc(tion)?)|global|goto|guard|i(f|mp(lements|licit|ort)|n(it|clude(_once)?|line|out|stanceof|t(erface|ernal)?)?|s)|l(ambda|et|ock|ong)|m(icrolight|odule|utable)|NaN|n(amespace|ative|ext|ew|il|ot|ull)|o(bject|perator|r|ut|verride)|p(ackage|arams|rivate|rotected|rotocol|ublic)|r(aise|e(adonly|do|f|gister|peat|quire(_once)?|scue|strict|try|turn))|s(byte|ealed|elf|hort|igned|izeof|tatic|tring|truct|ubscript|uper|ynchronized|witch)|t(emplate|hen|his|hrows?|ransient|rue|ry|ype(alias|def|id|name|of))|u(n(checked|def(ined)?|ion|less|signed|til)|se|sing)|v(ar|irtual|oid|olatile)|w(char_t|hen|here|hile|ith)|xor|yield)$/[o](d):0]),s[n](r.createTextNode(d))),u=h&&h<7?h:u,d="",h=11;![1,/[\/{}[(\-+*=<>:;|\\.,?!&@~]/[o](p),/[\])]/[o](p),/[$\w]/[o](p),"/"==p&&u<2&&"<"!=t,'"'==p,"'"==p,p+f+l[c+1]+l[c+2]=="':null;var n=e.$$ref.match(/\S*\/(\S+)$/);e.xml.name=n[1]}return(0,L.memoizedCreateXMLExample)(e,r)}return JSON.stringify((0,L.memoizedSampleFromSchema)(e,r),null,2)},t.parseSeach=function(){var e={},t=window.location.search;if(""!=t){var r=t.substr(1).split("&");for(var n in r)n=r[n].split("="),e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return e},t.btoa=function(t){var r=void 0;return r=t instanceof e?t:new e(t.toString(),"utf-8"),r.toString("base64")},t.sorters={operationsSorter:{alpha:function(e,t){return e.get("path").localeCompare(t.get("path"))},method:function(e,t){return e.get("method").localeCompare(t.get("method"))}}},t.buildFormData=function(e){var t=[];for(var r in e){var n=e[r];void 0!==n&&""!==n&&t.push([r,"=",encodeURIComponent(n).replace(/%20/g,"+")].join(""))}return t.join("&")},t.filterConfigs=function(e,t){var r=void 0,n={};for(r in e)t.indexOf(r)!==-1&&(n[r]=e[r]);return n}}).call(t,r(13).Buffer)},function(e,t,r){(function(e){/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +"use strict";function n(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}function o(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(o()=o())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o().toString(16)+" bytes");return 0|e}function m(e){return+e!=e&&(e=0),u.alloc(+e)}function v(e,t){if(u.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return $(e).length;default:if(n)return W(e).length;t=(""+t).toLowerCase(),n=!0}}function b(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if(r>>>=0,t>>>=0,r<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return q(this,t,r);case"utf8":case"utf-8":return C(this,t,r);case"ascii":return R(this,t,r);case"latin1":case"binary":return k(this,t,r);case"base64":return x(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function g(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function _(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:E(e,t,r,n,o);if("number"==typeof t)return t&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):E(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function E(e,t,r,n,o){function a(e,t){return 1===u?e[t]:e.readUInt16BE(t*u)}var u=1,i=e.length,s=t.length;if(void 0!==n&&(n=String(n).toLowerCase(),"ucs2"===n||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;u=2,i/=2,s/=2,r/=2}var l;if(o){var c=-1;for(l=r;li&&(r=i-s),l=r;l>=0;l--){for(var f=!0,p=0;po&&(n=o)):n=o;var a=t.length;if(a%2!==0)throw new TypeError("Invalid hex string");n>a/2&&(n=a/2);for(var u=0;u239?4:a>223?3:a>191?2:1;if(o+i<=r){var s,l,c,f;switch(i){case 1:a<128&&(u=a);break;case 2:s=e[o+1],128===(192&s)&&(f=(31&a)<<6|63&s,f>127&&(u=f));break;case 3:s=e[o+1],l=e[o+2],128===(192&s)&&128===(192&l)&&(f=(15&a)<<12|(63&s)<<6|63&l,f>2047&&(f<55296||f>57343)&&(u=f));break;case 4:s=e[o+1],l=e[o+2],c=e[o+3],128===(192&s)&&128===(192&l)&&128===(192&c)&&(f=(15&a)<<18|(63&s)<<12|(63&l)<<6|63&c,f>65535&&f<1114112&&(u=f))}}null===u?(u=65533,i=1):u>65535&&(u-=65536,n.push(u>>>10&1023|55296),u=56320|1023&u),n.push(u),o+=i}return A(n)}function A(e){var t=e.length;if(t<=ee)return String.fromCharCode.apply(String,e);for(var r="",n=0;nn)&&(r=n);for(var o="",a=t;ar)throw new RangeError("Trying to access beyond buffer length")}function I(e,t,r,n,o,a){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function U(e,t,r,n){t<0&&(t=65535+t+1);for(var o=0,a=Math.min(e.length-r,2);o>>8*(n?o:1-o)}function z(e,t,r,n){t<0&&(t=4294967295+t+1);for(var o=0,a=Math.min(e.length-r,4);o>>8*(n?o:3-o)&255}function D(e,t,r,n,o,a){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function L(e,t,r,n,o){return o||D(e,t,r,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(e,t,r,n,23,4),r+4}function B(e,t,r,n,o){return o||D(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(e,t,r,n,52,8),r+8}function F(e){if(e=J(e).replace(te,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function J(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function V(e){return e<16?"0"+e.toString(16):e.toString(16)}function W(e,t){t=t||1/0;for(var r,n=e.length,o=null,a=[],u=0;u55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(u+1===n){(t-=3)>-1&&a.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),o=r;continue}r=(o-55296<<10|r-56320)+65536}else o&&(t-=3)>-1&&a.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function H(e){for(var t=[],r=0;r>8,o=r%256,a.push(o),a.push(n);return a}function $(e){return G.toByteArray(F(e))}function K(e,t,r,n){for(var o=0;o=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function X(e){return e!==e}var G=r(14),Z=r(15),Q=r(16);t.Buffer=u,t.SlowBuffer=m,t.INSPECT_MAX_BYTES=50,u.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:n(),t.kMaxLength=o(),u.poolSize=8192,u._augment=function(e){return e.__proto__=u.prototype,e},u.from=function(e,t,r){return i(null,e,t,r)},u.TYPED_ARRAY_SUPPORT&&(u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0})),u.alloc=function(e,t,r){return l(null,e,t,r)},u.allocUnsafe=function(e){return c(null,e)},u.allocUnsafeSlow=function(e){return c(null,e)},u.isBuffer=function(e){return!(null==e||!e._isBuffer)},u.compare=function(e,t){if(!u.isBuffer(e)||!u.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,o=0,a=Math.min(r,n);o0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),""},u.prototype.compare=function(e,t,r,n,o){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,o>>>=0,this===e)return 0;for(var a=o-n,i=r-t,s=Math.min(a,i),l=this.slice(n,o),c=e.slice(t,r),f=0;fo)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return j(this,e,t,r);case"ascii":return P(this,e,t,r);case"latin1":case"binary":return O(this,e,t,r);case"base64":return T(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ee=4096;u.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),t<0?(t+=r,t<0&&(t=0)):t>r&&(t=r),t0&&(o*=256);)n+=this[e+--t]*o;return n},u.prototype.readUInt8=function(e,t){return t||N(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return t||N(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return t||N(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return t||N(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return t||N(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||N(e,t,this.length);for(var n=this[e],o=1,a=0;++a=o&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||N(e,t,this.length);for(var n=t,o=1,a=this[e+--n];n>0&&(o*=256);)a+=this[e+--n]*o;return o*=128,a>=o&&(a-=Math.pow(2,8*t)),a},u.prototype.readInt8=function(e,t){return t||N(e,1,this.length),128&this[e]?(255-this[e]+1)*-1:this[e]},u.prototype.readInt16LE=function(e,t){t||N(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){t||N(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return t||N(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return t||N(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return t||N(e,4,this.length),Z.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return t||N(e,4,this.length),Z.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return t||N(e,8,this.length),Z.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return t||N(e,8,this.length),Z.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t|=0,r|=0,!n){var o=Math.pow(2,8*r)-1;I(this,e,t,r,o,0)}var a=1,u=0;for(this[t]=255&e;++u=0&&(u*=256);)this[t+a]=e/u&255;return t+r},u.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,1,255,0),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):U(this,e,t,!0),t+2},u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):U(this,e,t,!1),t+2},u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):z(this,e,t,!0),t+4},u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):z(this,e,t,!1),t+4},u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var o=Math.pow(2,8*r-1);I(this,e,t,r,o-1,-o)}var a=0,u=1,i=0;for(this[t]=255&e;++a>0)-i&255;return t+r},u.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var o=Math.pow(2,8*r-1);I(this,e,t,r,o-1,-o)}var a=r-1,u=1,i=0;for(this[t+a]=255&e;--a>=0&&(u*=256);)e<0&&0===i&&0!==this[t+a+1]&&(i=1),this[t+a]=(e/u>>0)-i&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,1,127,-128),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):U(this,e,t,!0),t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):U(this,e,t,!1),t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):z(this,e,t,!0),t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):z(this,e,t,!1),t+4},u.prototype.writeFloatLE=function(e,t,r){return L(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return L(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return B(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return B(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--o)e[o+t]=this[o+r];else if(a<1e3||!u.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,r=void 0===r?this.length:r>>>0,e||(e=0);var a;if("number"==typeof e)for(a=t;a=n?e:o(e,t,r)}var o=r(35);e.exports=n},function(e,t){function r(e,t,r){var n=-1,o=e.length;t<0&&(t=-t>o?0:o+t),r=r>o?o:r,r<0&&(r+=o),o=t>r?0:r-t>>>0,t>>>=0;for(var a=Array(o);++n-1}var o=r(70);e.exports=n},function(e,t,r){function n(e,t){var r=this.__data__,n=o(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var o=r(70);e.exports=n},function(e,t,r){var n=r(55),o=r(23),a=n(o,"Map");e.exports=a},function(e,t,r){function n(e){var t=o(this,e).delete(e);return this.size-=t?1:0,t}var o=r(77);e.exports=n},function(e,t,r){function n(e,t){var r=e.__data__;return o(t)?r["string"==typeof t?"string":"hash"]:r.map}var o=r(78);e.exports=n},function(e,t){function r(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}e.exports=r},function(e,t,r){function n(e){return o(this,e).get(e)}var o=r(77);e.exports=n},function(e,t,r){function n(e){return o(this,e).has(e)}var o=r(77);e.exports=n},function(e,t,r){function n(e,t){var r=o(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var o=r(77);e.exports=n},function(e,t,r){function n(e,t,r){var n=i(e)?o:u;return r&&s(e,t,r)&&(t=void 0), +n(e,a(t,3))}var o=r(83),a=r(84),u=r(147),i=r(26),s=r(153);e.exports=n},function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length;++rp))return!1;var h=c.get(e);if(h&&c.get(t))return h==t;var y=-1,m=!0,v=r&s?new o:void 0;for(c.set(e,t),c.set(t,e);++y-1&&e%1==0&&e-1&&e%1==0&&e<=n}var n=9007199254740991;e.exports=r},function(e,t){function r(e){return function(t){return e(t)}}e.exports=r},function(e,t,r){(function(e){var n=r(24),o="object"==typeof t&&t&&!t.nodeType&&t,a=o&&"object"==typeof e&&e&&!e.nodeType&&e,u=a&&a.exports===o,i=u&&n.process,s=function(){try{return i&&i.binding&&i.binding("util")}catch(e){}}();e.exports=s}).call(t,r(111)(e))},function(e,t,r){function n(e){if(!o(e))return a(e);var t=[];for(var r in Object(e))i.call(e,r)&&"constructor"!=r&&t.push(r);return t}var o=r(120),a=r(121),u=Object.prototype,i=u.hasOwnProperty;e.exports=n},function(e,t){function r(e){var t=e&&e.constructor,r="function"==typeof t&&t.prototype||n;return e===r}var n=Object.prototype;e.exports=r},function(e,t,r){var n=r(122),o=n(Object.keys,Object);e.exports=o},function(e,t){function r(e,t){return function(r){return e(t(r))}}e.exports=r},function(e,t,r){function n(e){return null!=e&&a(e.length)&&!o(e)}var o=r(57),a=r(116);e.exports=n},function(e,t,r){var n=r(125),o=r(75),a=r(126),u=r(127),i=r(128),s=r(28),l=r(61),c="[object Map]",f="[object Object]",p="[object Promise]",d="[object Set]",h="[object WeakMap]",y="[object DataView]",m=l(n),v=l(o),b=l(a),g=l(u),_=l(i),E=s;(n&&E(new n(new ArrayBuffer(1)))!=y||o&&E(new o)!=c||a&&E(a.resolve())!=p||u&&E(new u)!=d||i&&E(new i)!=h)&&(E=function(e){var t=s(e),r=t==f?e.constructor:void 0,n=r?l(r):"";if(n)switch(n){case m:return y;case v:return c;case b:return p;case g:return d;case _:return h}return t}),e.exports=E},function(e,t,r){var n=r(55),o=r(23),a=n(o,"DataView");e.exports=a},function(e,t,r){var n=r(55),o=r(23),a=n(o,"Promise");e.exports=a},function(e,t,r){var n=r(55),o=r(23),a=n(o,"Set");e.exports=a},function(e,t,r){var n=r(55),o=r(23),a=n(o,"WeakMap");e.exports=a},function(e,t,r){function n(e){for(var t=a(e),r=t.length;r--;){var n=t[r],u=e[n];t[r]=[n,u,o(u)]}return t}var o=r(130),a=r(105);e.exports=n},function(e,t,r){function n(e){return e===e&&!o(e)}var o=r(58);e.exports=n},function(e,t){function r(e,t){return function(r){return null!=r&&(r[e]===t&&(void 0!==t||e in Object(r)))}}e.exports=r},function(e,t,r){function n(e,t){return i(e)&&s(t)?l(c(e),t):function(r){var n=a(r,e);return void 0===n&&n===t?u(r,e):o(t,n,f|p)}}var o=r(93),a=r(133),u=r(140),i=r(136),s=r(130),l=r(131),c=r(139),f=1,p=2;e.exports=n},function(e,t,r){function n(e,t,r){var n=null==e?void 0:o(e,t);return void 0===n?r:n}var o=r(134);e.exports=n},function(e,t,r){function n(e,t){t=o(t,e);for(var r=0,n=t.length;null!=e&&r1&&void 0!==arguments[1]?arguments[1]:{},n=(0,a.objectify)(t),o=n.type,u=n.example,i=n.properties,s=n.additionalProperties,l=n.items,c=r.includeReadOnly;if(void 0!==u)return u;if(!o)if(i)o="object";else{if(!l)return;o="array"}if("object"===o){var p=(0,a.objectify)(i),d={};for(var h in p)p[h].readOnly&&!c||(d[h]=e(p[h],{includeReadOnly:c}));if(s===!0)d.additionalProp1={};else if(s)for(var y=(0,a.objectify)(s),m=e(y,{includeReadOnly:c}),v=1;v<4;v++)d["additionalProp"+v]=m;return d}return"array"===o?[e(l,{includeReadOnly:c})]:t.enum?t.default?t.default:(0,a.normalizeArray)(t.enum)[0]:f(t)},d=(t.inferSchema=function(e){return e.schema&&(e=e.schema),e.properties&&(e.type="object"),e},t.sampleXmlFromSchema=function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=(0,a.objectify)(t),o=n.type,u=n.properties,i=n.additionalProperties,s=n.items,l=n.example,c=r.includeReadOnly,p=n.default,d={},h={},y=t.xml,m=y.name,v=y.prefix,b=y.namespace,g=n.enum,_=void 0,E=void 0;if(!o)if(u||i)o="object";else{if(!s)return;o="array"}if(m=m||"notagname",_=(v?v+":":"")+m,b){var w=v?"xmlns:"+v:"xmlns";h[w]=b}if("array"===o&&s){if(s.xml=s.xml||y||{},s.xml.name=s.xml.name||y.name,y.wrapped)return d[_]=[],Array.isArray(l)?l.forEach(function(t){s.example=t,d[_].push(e(s,r))}):Array.isArray(p)?p.forEach(function(t){s.default=t,d[_].push(e(s,r))}):d[_]=[e(s,r)],h&&d[_].push({_attr:h}),d;var j=[];return Array.isArray(l)?(l.forEach(function(t){s.example=t,j.push(e(s,r))}),j):Array.isArray(p)?(p.forEach(function(t){s.default=t,j.push(e(s,r))}),j):e(s,r)}if("object"===o){var P=(0,a.objectify)(u);d[_]=[],l=l||{};for(var O in P)if(!P[O].readOnly||c)if(P[O].xml=P[O].xml||{},P[O].xml.attribute){var T=Array.isArray(P[O].enum)&&P[O].enum[0],S=P[O].example,x=P[O].default;h[P[O].xml.name||O]=void 0!==S&&S||void 0!==l[O]&&l[O]||void 0!==x&&x||T||f(P[O])}else{P[O].xml.name=P[O].xml.name||O,P[O].example=void 0!==P[O].example?P[O].example:l[O];var C=e(P[O]);Array.isArray(C)?d[_]=d[_].concat(C):d[_].push(C)}return i===!0?d[_].push({additionalProp:"Anything can be here"}):i&&d[_].push({additionalProp:f(i)}),h&&d[_].push({_attr:h}),d}return E=void 0!==l?l:void 0!==p?p:Array.isArray(g)?g[0]:f(t),d[_]=h?[{_attr:h},E]:E,d});t.memoizedCreateXMLExample=(0,l.default)(o),t.memoizedSampleFromSchema=(0,l.default)(p)},function(e,t){e.exports=require("xml")},function(e,t){e.exports=require("memoizee")},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(){return[u.default]}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=r(158),u=n(a)},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){var e={components:{App:A.default,authorizationPopup:k.default,authorizeBtn:M.default,authorizeOperationBtn:I.default,auths:z.default,authError:L.default,oauth2:H.default,apiKeyAuth:F.default,basicAuth:V.default,clear:$.default,liveResponse:X.default,info:Te.default,onlineValidatorBadge:Z.default,operations:ee.default,operation:re.default,highlightCode:oe.default,responses:ue.default,response:se.default,responseBody:ce.default,parameters:pe.default,parameterRow:he.default,execute:me.default,headers:be.default,errors:_e.default,contentType:we.default,overview:Pe.default,footer:xe.default,ParamBody:Ae.default,curl:ke.default,schemes:Me.default,modelExample:Ie.default,model:ze.default,models:Le.default,TryItOutButton:Fe.default,Markdown:Ve.default,BaseLayout:He.default}},t={components:$e},r={components:Xe};return[P.default,m.default,p.default,c.default,u.default,s.default,h.default,e,t,_.default,r,w.default,b.default,T.default,x.default]};var a=r(159),u=o(a),i=r(174),s=o(i),l=r(178),c=o(l),f=r(185),p=o(f),d=r(240),h=o(d),y=r(241),m=o(y),v=r(242),b=o(v),g=r(253),_=o(g),E=r(255),w=o(E),j=r(260),P=o(j),O=r(262),T=o(O),S=r(268),x=o(S),C=r(269),A=o(C),R=r(270),k=o(R),q=r(271),M=o(q),N=r(272),I=o(N),U=r(274),z=o(U),D=r(275),L=o(D),B=r(276),F=o(B),J=r(277),V=o(J),W=r(278),H=o(W),Y=r(280),$=o(Y),K=r(281),X=o(K),G=r(282),Z=o(G),Q=r(283),ee=o(Q),te=r(284),re=o(te),ne=r(287),oe=o(ne),ae=r(288),ue=o(ae),ie=r(289),se=o(ie),le=r(290),ce=o(le),fe=r(292),pe=o(fe),de=r(293),he=o(de),ye=r(294),me=o(ye),ve=r(295),be=o(ve),ge=r(296),_e=o(ge),Ee=r(298),we=o(Ee),je=r(299),Pe=o(je),Oe=r(301),Te=o(Oe),Se=r(302),xe=o(Se),Ce=r(303),Ae=o(Ce),Re=r(304),ke=o(Re),qe=r(306),Me=o(qe),Ne=r(307),Ie=o(Ne),Ue=r(308),ze=o(Ue),De=r(309),Le=o(De),Be=r(310),Fe=o(Be),Je=r(311),Ve=o(Je),We=r(314),He=o(We),Ye=r(300),$e=n(Ye),Ke=r(315),Xe=n(Ke)},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return{statePlugins:{err:{reducers:(0,u.default)(e),actions:s,selectors:c}}}};var a=r(160),u=o(a),i=r(10),s=n(i),l=r(172),c=n(l)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t;return t={},o(t,a.NEW_THROWN_ERR,function(t,r){var n=r.payload,o=Object.assign(p,n,{type:"thrown"});return t.update("errors",function(e){return(e||(0,s.List)()).push((0,s.fromJS)(o))}).update("errors",function(t){return(0,f.default)(t,e.getSystem())})}),o(t,a.NEW_THROWN_ERR_BATCH,function(t,r){var n=r.payload;return n=n.map(function(e){return(0,s.fromJS)(Object.assign(p,e,{type:"thrown"}))}),t.update("errors",function(e){return(e||(0,s.List)()).concat((0,s.fromJS)(n))}).update("errors",function(t){return(0,f.default)(t,e.getSystem())})}),o(t,a.NEW_SPEC_ERR,function(t,r){var n=r.payload,o=(0,s.fromJS)(n);return o=o.set("type","spec"),t.update("errors",function(e){return(e||(0,s.List)()).push((0,s.fromJS)(o)).sortBy(function(e){return e.get("line")})}).update("errors",function(t){return(0,f.default)(t,e.getSystem())})}),o(t,a.NEW_AUTH_ERR,function(t,r){var n=r.payload,o=(0,s.fromJS)(Object.assign({},n));return o=o.set("type","auth"),t.update("errors",function(e){return(e||(0,s.List)()).push((0,s.fromJS)(o))}).update("errors",function(t){return(0,f.default)(t,e.getSystem())})}),o(t,a.CLEAR,function(e,t){var r=t.payload;if(r){var n=l.default.fromJS((0,i.default)((e.get("errors")||(0,s.List)()).toJS(),r));return e.merge({errors:n})}}),t};var a=r(10),u=r(161),i=n(u),s=r(7),l=n(s),c=r(165),f=n(c),p={line:0,level:"error",message:"Unknown error"}},function(e,t,r){function n(e,t){var r=i(e)?o:a;return r(e,s(u(t,3)))}var o=r(162),a=r(163),u=r(84),i=r(26),s=r(164);e.exports=n},function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length,o=0,a=[];++r-1||l.push({name:a(e).replace(".js","").replace("./",""),transform:s(e).transform}))})},function(e,t,r){function n(e,t,r){var n=s(e)?o:i,l=arguments.length<3;return n(e,u(t,4),r,l,a)}var o=r(41),a=r(148),u=r(84),i=r(167),s=r(26);e.exports=n},function(e,t){function r(e,t,r,n,o){return o(e,function(e,o,a){r=n?(n=!1,e):t(r,e,o,a)}),r}e.exports=r},function(e,t,r){function n(e){return r(o(e))}function o(e){return a[e]||function(){throw new Error("Cannot find module '"+e+"'.")}()}var a={"./not-of-type.js":169,"./parameter-oneof.js":170,"./strip-instance.js":171};n.keys=function(){return Object.keys(a)},n.resolve=o,e.exports=n,n.id=168},function(e,t){"use strict";function r(e){return e.map(function(e){var t="is not of a type(s)",r=e.get("message").indexOf(t);if(r>-1){var o=e.get("message").slice(r+t.length).split(",");return e.set("message",e.get("message").slice(0,r)+n(o))}return e})}function n(e){return e.reduce(function(e,t,r,n){return r===n.length-1&&n.length>1?e+"or "+t:n[r+1]&&n.length>2?e+t+", ":n[r+1]?e+t+" ":e+t},"should be a")}Object.defineProperty(t,"__esModule",{value:!0}),t.transform=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){t.jsSpec;return e}Object.defineProperty(t,"__esModule",{value:!0}),t.transform=o;var a=r(133);n(a),r(7)},function(e,t){"use strict";function r(e){return e.map(function(e){return e.set("message",n(e.get("message"),"instance."))})}function n(e,t){return e.replace(new RegExp(t,"g"),"")}Object.defineProperty(t,"__esModule",{value:!0}),t.transform=r},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lastError=t.allErrors=void 0;var n=r(7),o=r(173),a=function(e){return e},u=t.allErrors=(0,o.createSelector)(a,function(e){return e.get("errors",(0,n.List)())});t.lastError=(0,o.createSelector)(u,function(e){return e.last()})},function(e,t){e.exports=require("reselect")},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return{statePlugins:{layout:{reducers:u.default,actions:s,selectors:c}}}};var a=r(175),u=o(a),i=r(176),s=n(i),l=r(177),c=n(l)},function(e,t,r){"use strict";function n(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}Object.defineProperty(t,"__esModule",{value:!0});var o,a=r(176);t.default=(o={},n(o,a.UPDATE_LAYOUT,function(e,t){return e.set("layout",t.payload)}),n(o,a.SHOW,function(e,t){var r=t.payload.thing,n=t.payload.shown;return e.setIn(["shown"].concat(r),n)}),n(o,a.UPDATE_MODE,function(e,t){var r=t.payload.thing,n=t.payload.mode;return e.setIn(["modes"].concat(r),(n||"")+"")}),o)},function(e,t,r){"use strict";function n(e){return{type:i,payload:e}}function o(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e=(0,u.normalizeArray)(e),{type:l,payload:{thing:e,shown:t}}}function a(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return e=(0,u.normalizeArray)(e),{type:s,payload:{thing:e,mode:t}}}Object.defineProperty(t,"__esModule",{value:!0}),t.SHOW=t.UPDATE_MODE=t.UPDATE_LAYOUT=void 0,t.updateLayout=n,t.show=o,t.changeMode=a;var u=r(12),i=t.UPDATE_LAYOUT="layout_update_layout",s=t.UPDATE_MODE="layout_update_mode",l=t.SHOW="layout_show"},function(e,t,r){"use strict";function n(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t2&&void 0!==arguments[2]?arguments[2]:"";return t=(0,a.normalizeArray)(t),e.getIn(["modes"].concat(n(t)),r)},t.showSummary=(0,o.createSelector)(u,function(e){return!i(e,"editor")})},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return{statePlugins:{spec:{wrapActions:p,reducers:u.default,actions:s,selectors:c}}}};var a=r(179),u=o(a),i=r(180),s=n(i),l=r(183),c=n(l),f=r(184),p=n(f)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function a(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function a(e){return e instanceof Error?{type:O,error:!0,payload:e}:"string"==typeof e?{type:O,payload:e.replace(/\t/g," ")||""}:{type:O,payload:""}}function u(e){return{type:U,payload:e}}function i(e){return{type:T,payload:e}}function s(e){if(!e||"object"!==("undefined"==typeof e?"undefined":b(e)))throw new Error("updateJson must only accept a simple JSON object");return{type:S,payload:e}}function l(e,t,r,n){return{type:x,payload:{path:e,value:r,paramName:t,isXml:n}}}function c(e){return{type:C,payload:{pathMethod:e}}}function f(e){return{type:N,payload:{pathMethod:e}}}function p(e,t){return{type:I,payload:{path:e,value:t,key:"consumes_value"}}}function d(e,t){return{type:I,payload:{path:e,value:t,key:"produces_value"}}}function h(e,t){return{type:q,payload:{path:e,method:t}}}function y(e,t){return{type:M,payload:{path:e,method:t}}}function m(e,t,r){return{type:z,payload:{scheme:e,path:t,method:r}}}Object.defineProperty(t,"__esModule",{value:!0}),t.execute=t.executeRequest=t.logRequest=t.setRequest=t.setResponse=t.formatIntoYaml=t.resolveSpec=t.parseToJson=t.SET_SCHEME=t.UPDATE_RESOLVED=t.UPDATE_OPERATION_VALUE=t.ClEAR_VALIDATE_PARAMS=t.CLEAR_REQUEST=t.CLEAR_RESPONSE=t.LOG_REQUEST=t.SET_REQUEST=t.SET_RESPONSE=t.VALIDATE_PARAMS=t.UPDATE_PARAM=t.UPDATE_JSON=t.UPDATE_URL=t.UPDATE_SPEC=void 0;var v=Object.assign||function(e){for(var t=1;t0){var o=r.map(function(e){return console.error(e),e.line=e.fullPath?h(y,e.fullPath):null,e.path=e.fullPath?e.fullPath.join("."):null,e.level="error",e.type="thrown",e.source="resolver",Object.defineProperty(e,"message",{enumerable:!0,value:e.message}),e});a.newThrownErrBatch(o)}return n.updateResolved(t)})}},t.formatIntoYaml=function(){return function(e){var t=e.specActions,r=e.specSelectors,n=r.specStr,o=t.updateSpec;try{var a=_.default.safeDump(_.default.safeLoad(n()),{indent:2});o(a)}catch(e){o(e)}}},t.setResponse=function(e,t,r){return{payload:{path:e,method:t,res:r},type:A}},t.setRequest=function(e,t,r){return{payload:{path:e,method:t,req:r},type:R}},t.logRequest=function(e){return{payload:e,type:k}},t.executeRequest=function(e){return function(t){var r=t.fn,n=t.specActions,o=t.specSelectors,a=e.pathName,u=e.method,i=e.operation,s=i.toJS();e.contextUrl=(0,w.default)(o.url()).toString(),s&&s.operationId?e.operationId=s.operationId:s&&a&&u&&(e.operationId=r.opId(s,a,u));var l=Object.assign({},e);return l=r.buildRequest(l),n.setRequest(e.pathName,e.method,l),r.execute(e).then(function(t){return n.setResponse(e.pathName,e.method,t)}).catch(function(t){return n.setResponse(e.pathName,e.method,{error:!0,err:(0,P.default)(t)})})}},function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.path,r=e.method,n=o(e,["path","method"]);return function(e){var o=e.fn.fetch,a=e.specSelectors,u=e.specActions,i=a.spec().toJS(),s=a.operationScheme(t,r),l=a.contentTypeValues([t,r]).toJS(),c=l.requestContentType,f=l.responseContentType,p=/xml/i.test(c),d=a.parameterValues([t,r],p).toJS();return u.executeRequest(v({fetch:o,spec:i,pathName:t,method:r,parameters:d,requestContentType:c,scheme:s,responseContentType:f},n))}});t.execute=D},function(e,t){e.exports=require("js-yaml")},function(e,t){e.exports=require("url-parse")},function(e,t,r){"use strict";function n(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t1&&void 0!==arguments[1]?arguments[1]:"";if(d.List.isList(e))return e.some(function(e){return d.Map.isMap(e)&&e.get("in")===t})}function i(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(d.List.isList(e))return e.some(function(e){return d.Map.isMap(e)&&e.get("type")===t})}function s(e,t){var r=g(e).getIn(["paths"].concat(n(t)),(0,d.fromJS)({})),o=r.get("parameters")||new d.List,a=i(o,"file")?"multipart/form-data":u(o,"formData")?"application/x-www-form-urlencoded":r.get("consumes_value");return(0,d.fromJS)({requestContentType:a,responseContentType:r.get("produces_value")})}function l(e,t){return g(e).getIn(["paths"].concat(n(t),["consumes"]),(0,d.fromJS)({}))}function c(e){return d.Map.isMap(e)?e:new d.Map}Object.defineProperty(t,"__esModule",{value:!0}),t.validateBeforeExecute=t.canExecuteScheme=t.operationScheme=t.hasHost=t.allowTryItOutFor=t.requestFor=t.responseFor=t.requests=t.responses=t.taggedOperations=t.operationsWithTags=t.tagDetails=t.tags=t.operationsWithRootInherited=t.schemes=t.host=t.basePath=t.definitions=t.findDefinition=t.securityDefinitions=t.security=t.produces=t.consumes=t.operations=t.paths=t.semver=t.version=t.externalDocs=t.info=t.spec=t.specResolved=t.specJson=t.specSource=t.specStr=t.url=t.lastError=void 0,t.getParameter=o,t.parameterValues=a,t.parametersIncludeIn=u,t.parametersIncludeType=i,t.contentTypeValues=s,t.operationConsumes=l;var f=r(173),p=r(12),d=r(7),h="default",y=["get","put","post","delete","options","head","patch"],m=function(e){return e||(0,d.Map)()},v=(t.lastError=(0,f.createSelector)(m,function(e){return e.get("lastError")}),t.url=(0,f.createSelector)(m,function(e){return e.get("url")}),t.specStr=(0,f.createSelector)(m,function(e){return e.get("spec")||""}),t.specSource=(0,f.createSelector)(m,function(e){return e.get("specSource")||"not-editor"}),t.specJson=(0,f.createSelector)(m,function(e){return e.get("json",(0,d.Map)())})),b=t.specResolved=(0,f.createSelector)(m,function(e){return e.get("resolved",(0,d.Map)())}),g=t.spec=function(e){var t=b(e);return t.count()<1&&(t=v(e)),t},_=t.info=(0,f.createSelector)(g,function(e){return c(e&&e.get("info"))}),E=(t.externalDocs=(0,f.createSelector)(g,function(e){return c(e&&e.get("externalDocs"))}),t.version=(0,f.createSelector)(_,function(e){return e&&e.get("version")})),w=(t.semver=(0,f.createSelector)(E,function(e){return/v?([0-9]*)\.([0-9]*)\.([0-9]*)/i.exec(e).slice(1)}),t.paths=(0,f.createSelector)(g,function(e){return e.get("paths")})),j=t.operations=(0,f.createSelector)(w,function(e){if(!e||e.size<1)return(0,d.List)();var t=(0,d.List)();return e&&e.forEach?(e.forEach(function(e,r){return e&&e.forEach?void e.forEach(function(e,n){y.indexOf(n)!==-1&&(t=t.push((0,d.fromJS)({path:r,method:n,operation:e,id:n+"-"+r})))}):{}}),t):(0,d.List)()}),P=t.consumes=(0,f.createSelector)(g,function(e){return(0,d.Set)(e.get("consumes"))}),O=t.produces=(0,f.createSelector)(g,function(e){return(0,d.Set)(e.get("produces"))}),T=(t.security=(0,f.createSelector)(g,function(e){return e.get("security",(0,d.List)())}),t.securityDefinitions=(0,f.createSelector)(g,function(e){return e.get("securityDefinitions")}),t.findDefinition=function(e,t){return b(e).getIn(["definitions",t],null)},t.definitions=(0,f.createSelector)(g,function(e){return e.get("definitions")||(0,d.Map)()}),t.basePath=(0,f.createSelector)(g,function(e){return e.get("basePath")}),t.host=(0,f.createSelector)(g,function(e){return e.get("host")}),t.schemes=(0,f.createSelector)(g,function(e){return e.get("schemes",(0,d.Map)())}),t.operationsWithRootInherited=(0,f.createSelector)(j,P,O,function(e,t,r){return e.map(function(e){return e.update("operation",function(e){if(e){if(!d.Map.isMap(e))return;return e.withMutations(function(e){return e.get("consumes")||e.update("consumes",function(e){return(0,d.Set)(e).merge(t)}),e.get("produces")||e.update("produces",function(e){return(0,d.Set)(e).merge(r)}),e})}return(0,d.Map)()})})})),S=t.tags=(0,f.createSelector)(g,function(e){return e.get("tags",(0,d.List)())}),x=t.tagDetails=function(e,t){var r=S(e)||(0,d.List)();return r.filter(d.Map.isMap).find(function(e){return e.get("name")===t},(0,d.Map)())},C=t.operationsWithTags=(0,f.createSelector)(T,function(e){return e.reduce(function(e,t){var r=(0,d.Set)(t.getIn(["operation","tags"]));return r.count()<1?e.update(h,(0,d.List)(),function(e){return e.push(t)}):r.reduce(function(e,r){return e.update(r,(0,d.List)(),function(e){return e.push(t)})},e)},(0,d.Map)())}),A=(t.taggedOperations=function(e){return function(t){var r=t.getConfigs,n=r(),o=n.operationsSorter;return C(e).map(function(t,r){var n="function"==typeof o?o:p.sorters.operationsSorter[o],a=n?t.sort(n):t;return(0,d.Map)({tagDetails:x(e,r),operations:a})})}},t.responses=(0,f.createSelector)(m,function(e){return e.get("responses",(0,d.Map)())})),R=t.requests=(0,f.createSelector)(m,function(e){return e.get("requests",(0,d.Map)())}),k=(t.responseFor=function(e,t,r){return A(e).getIn([t,r],null)},t.requestFor=function(e,t,r){return R(e).getIn([t,r],null)},t.allowTryItOutFor=function(){return!0},t.hasHost=(0,f.createSelector)(g,function(e){var t=e.get("host");return"string"==typeof t&&t.length>0&&"/"!==t[0]}),t.operationScheme=function(e,t,r){var n=e.get("url"),o=n.match(/^([a-z][a-z0-9+\-.]*):/),a=Array.isArray(o)?o[1]:null;return e.getIn(["scheme",t,r])||e.getIn(["scheme","_defaultScheme"])||a||""});t.canExecuteScheme=function(e,t,r){return["http","https"].indexOf(k(e,t,r))>-1},t.validateBeforeExecute=function(e,t){var r=g(e).getIn(["paths"].concat(n(t),["parameters"]),(0,d.fromJS)([])),o=!0;return r.forEach(function(e){var t=e.get("errors");t&&t.count()&&(o=!1)}),o}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.updateSpec=function(e,t){var r=t.specActions;return function(){e.apply(void 0,arguments),r.parseToJson.apply(r,arguments)}},t.updateJsonSpec=function(e,t){var r=t.specActions;return function(){e.apply(void 0,arguments),r.resolveSpec.apply(r,arguments)}},t.executeRequest=function(e,t){var r=t.specActions;return function(t){return r.logRequest(t),e(t)}}},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getComponents,r=e.getStore,n=e.getSystem,o=a.getComponent,i=a.render,s=a.makeMappedContainer,l=(0,u.memoize)(o.bind(null,n,r,t)),c=(0,u.memoize)(s.bind(null,n,r,l,t));return{rootInjects:{getComponent:l,makeMappedContainer:c,render:i.bind(null,n,r,o,t)}}};var o=r(186),a=n(o),u=r(12)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0}),t.getComponent=t.render=t.makeMappedContainer=void 0;var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s=Object.assign||function(e){for(var t=1;t1),t}),i(e,l(e),r),s&&(r=o(r,c|f|p));for(var d=t.length;d--;)a(r,t[d]);return r});e.exports=d},function(e,t,r){function n(e,t,r,S,x,C){var A,q=t&j,M=t&P,I=t&O;if(r&&(A=x?r(e,S,x,C):r(e)),void 0!==A)return A;if(!E(e))return e;var U=g(e);if(U){if(A=m(e),!q)return c(e,A)}else{var z=y(e),D=z==R||z==k;if(_(e))return l(e,q);if(z==N||z==T||D&&!x){if(A=M||D?{}:b(e),!q)return M?p(e,s(A,e)):f(e,i(A,e))}else{if(!Z[z])return x?e:{};A=v(e,z,n,q)}}C||(C=new o);var L=C.get(e);if(L)return L;C.set(e,A);var B=I?M?h:d:M?keysIn:w,F=U?void 0:B(e);return a(F||e,function(o,a){F&&(a=o,o=e[a]),u(A,a,n(o,t,r,a,e,C))}),A}var o=r(87),a=r(192),u=r(193),i=r(196),s=r(198),l=r(202),c=r(203),f=r(204),p=r(207),d=r(211),h=r(213),y=r(124),m=r(214),v=r(215),b=r(225),g=r(26),_=r(110),E=r(58),w=r(105),j=1,P=2,O=4,T="[object Arguments]",S="[object Array]",x="[object Boolean]",C="[object Date]",A="[object Error]",R="[object Function]",k="[object GeneratorFunction]",q="[object Map]",M="[object Number]",N="[object Object]",I="[object RegExp]",U="[object Set]",z="[object String]",D="[object Symbol]",L="[object WeakMap]",B="[object ArrayBuffer]",F="[object DataView]",J="[object Float32Array]",V="[object Float64Array]",W="[object Int8Array]",H="[object Int16Array]",Y="[object Int32Array]",$="[object Uint8Array]",K="[object Uint8ClampedArray]",X="[object Uint16Array]",G="[object Uint32Array]",Z={};Z[T]=Z[S]=Z[B]=Z[F]=Z[x]=Z[C]=Z[J]=Z[V]=Z[W]=Z[H]=Z[Y]=Z[q]=Z[M]=Z[N]=Z[I]=Z[U]=Z[z]=Z[D]=Z[$]=Z[K]=Z[X]=Z[G]=!0,Z[A]=Z[R]=Z[L]=!1,e.exports=n},function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length;++r0&&r(c)?t>1?n(c,t-1,r,u,i):o(i,c):u||(i[i.length]=c)}return i}var o=r(209),a=r(233);e.exports=n},function(e,t,r){function n(e){return u(e)||a(e)||!!(i&&e&&e[i])}var o=r(22),a=r(108),u=r(26),i=o?o.isConcatSpreadable:void 0;e.exports=n},function(e,t,r){function n(e,t,r){return t=a(void 0===t?e.length-1:t,0),function(){for(var n=arguments,u=-1,i=a(n.length-t,0),s=Array(i);++u0){if(++t>=n)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var n=800,o=16,a=Date.now;e.exports=r},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return{fn:a}};var o=r(154),a=n(o)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){function t(e){for(var t,r=arguments.length,n=Array(r>1?r-1:0),a=1;a=u&&(t=console)[e].apply(t,n)}var r=e.configs,n={debug:0,info:1,log:2,warn:3,error:4},o=function(e){return n[e]||-1},a=r.logLevel,u=o(a);return t.warn=t.bind(null,"warn"),t.error=t.bind(null,"error"),t.info=t.bind(null,"info"),t.debug=t.bind(null,"debug"),{rootInjects:{log:t}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return{fn:{AST:u},components:{JumpToPath:s.default}}};var a=r(243),u=o(a),i=r(252),s=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){function r(e,t,o){if(!e)return o&&o.start_mark?o.start_mark.line:0;if(t.length&&e.tag===v)for(n=0;n=t.column:t.line===e.start_mark.line?t.column>=e.start_mark.column:t.line===e.end_mark.line?t.column<=e.end_mark.column:e.start_mark.linet.line}var a=0;if(!e||[v,b].indexOf(e.tag)===-1)return o;if(e.tag===v)for(a=0;a-1?i[s?t[l]:l]:void 0}}var o=r(84),a=r(123),u=r(105);e.exports=n},function(e,t,r){function n(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var s=null==r?0:u(r);return s<0&&(s=i(n+s,0)),o(e,a(t,3),s)}var o=r(248),a=r(84),u=r(249),i=Math.max;e.exports=n},function(e,t){function r(e,t,r,n){for(var o=e.length,a=r+(n?1:-1);n?a--:++a=400?(u.updateLoadingStatus("failed"),o.newThrownErr(new Error(t.statusText+" "+e))):(u.updateLoadingStatus("success"),u.updateSpec(t.text),void u.updateUrl(e))}var o=r.errActions,a=r.specSelectors,u=r.specActions,i=t.fetch;e=e||a.url(),u.updateLoadingStatus("loading"),i({url:e,loadSpec:!0,credentials:"same-origin",headers:{Accept:"application/json,*/*"}}).then(n,n)}},updateLoadingStatus:function(e){var t=[null,"loading","failed","success","failedConfig"];return t.indexOf(e)===-1&&console.error("Error: "+e+" is not one of "+JSON.stringify(t)),{type:"spec_update_loading_status",payload:e}}},n={spec_update_loading_status:function(e,t){return"string"==typeof t.payload?e.set("loadingStatus",t.payload):e}},u={loadingStatus:(0,o.createSelector)(function(e){return e||(0,a.Map)()},function(e){return e.get("loadingStatus")||null})};return{statePlugins:{spec:{actions:r,reducers:n,selectors:u}}}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n;var o=r(173),a=r(7)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r-1&&e.setState({scopes:e.state.scopes.filter(function(e){return e!==o})})},this.onInputChange=function(t){var r=t.target,n=r.dataset.name,a=r.value,u=o({},n,a);e.setState(u)},this.logout=function(t){t.preventDefault();var r=e.props,n=r.authActions,o=r.errActions,a=r.name;o.clear({authId:a,type:"auth",source:"auth"}),n.logout([a])}};t.default=v},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.auth,r=e.authActions,n=e.errActions,o=e.configs,a=e.authConfigs,s=void 0===a?{}:a,l=t.schema,c=t.scopes,f=t.name,p=t.clientId,d=l.get("flow"),h=[];switch(d){case"password":return void r.authorizePassword(t);case"application":return void r.authorizeApplication(t);case"accessCode":h.push("response_type=code");break;case"implicit":h.push("response_type=token")}"string"==typeof p&&h.push("client_id="+encodeURIComponent(p));var y=o.oauth2RedirectUrl;if("undefined"==typeof y)return void n.newAuthErr({authId:f,source:"validation",level:"error",message:"oauth2RedirectUri configuration is not passed. Oauth2 authorization cannot be performed."});if(h.push("redirect_uri="+encodeURIComponent(y)),Array.isArray(c)&&0=0||this.state.url.indexOf("127.0.0.1")>=0?null:c.default.createElement("span",{style:{float:"right"}},c.default.createElement("a",{target:"_blank",href:this.state.validatorUrl+"/debug?url="+this.state.url},c.default.createElement(p,{src:this.state.validatorUrl+"?url="+this.state.url,alt:"Online validator badge"})))}}]),t}(c.default.Component);f.propTypes={getComponent:l.PropTypes.func.isRequired,getConfigs:l.PropTypes.func.isRequired,specSelectors:l.PropTypes.object.isRequired},t.default=f;var p=function(e){function t(e){o(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.state={loaded:!1,error:!1},r}return u(t,e),s(t,[{key:"componentDidMount",value:function(){var e=this,t=new Image;t.onload=function(){e.setState({loaded:!0})},t.onerror=function(){e.setState({error:!0})},t.src=this.props.src}},{key:"componentWillReceiveProps",value:function(e){var t=this;if(e.src!==this.props.src){var r=new Image;r.onload=function(){t.setState({loaded:!0})},r.onerror=function(){t.setState({error:!0})},r.src=e.src}}},{key:"render",value:function(){return this.state.error?c.default.createElement("img",{alt:"Error"}):this.state.loaded?c.default.createElement("img",{src:this.props.src,alt:this.props.alt}):c.default.createElement("img",{alt:"Loading..."})}}]),t}(c.default.Component);p.propTypes={src:l.PropTypes.string,alt:l.PropTypes.string}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t0){var I=!w.get(String(i.get("status")));i=i.set("notDocumented",I)}var U=this.state.tryItOutEnabled,z=this.isShown(),D=[n,o];return c.default.createElement("div",{className:_?"opblock opblock-deprecated":z?"opblock opblock-"+o+" is-open":"opblock opblock-"+o,id:t},c.default.createElement("div",{className:"opblock-summary opblock-summary-"+o,onClick:this.toggleShown},c.default.createElement("span",{className:"opblock-summary-method"},o.toUpperCase()),c.default.createElement("span",{className:_?"opblock-summary-path__deprecated":"opblock-summary-path"},c.default.createElement("span",null,n),c.default.createElement(k,{path:r})),u?c.default.createElement("div",{className:"opblock-summary-description"},b):null,j&&j.count()?c.default.createElement(R,{authActions:m,security:j,authSelectors:v}):null),c.default.createElement(q,{isOpened:z,animated:!0},c.default.createElement("div",{className:"opblock-body"},_&&c.default.createElement("h4",{className:"opblock-title_normal"}," Warning: Deprecated"),g&&c.default.createElement("div",{className:"opblock-description-wrapper"},c.default.createElement("div",{className:"opblock-description"},c.default.createElement(M,{source:g}))),E&&E.get("url")?c.default.createElement("div",{className:"opblock-external-docs-wrapper"},c.default.createElement("h4",{className:"opblock-title_normal"},"Find more details"),c.default.createElement("div",{className:"opblock-external-docs"},c.default.createElement("span",{className:"opblock-external-docs__description"},E.get("description")),c.default.createElement("a",{className:"opblock-external-docs__link",href:E.get("url")},E.get("url")))):null,c.default.createElement(x,{parameters:T,onChangeKey:D,onTryoutClick:this.onTryoutClick,onCancelClick:this.onCancelClick,tryItOutEnabled:U,allowTryItOut:l,fn:f,getComponent:p,specActions:h,specSelectors:y,pathMethod:[n,o]}),U&&l&&O&&O.size?c.default.createElement("div",{className:"opblock-schemes"},c.default.createElement(N,{schemes:O,path:n,method:o,specActions:h})):null,c.default.createElement("div",{className:U&&i&&l?"btn-group":"execute-wrapper"},U&&l?c.default.createElement(C,{getComponent:p,operation:a,specActions:h,specSelectors:y,path:n,method:o,onExecute:this.onExecute}):null,U&&i&&l?c.default.createElement(A,{onClick:this.onClearClick,specActions:h,path:n,method:o}):null),this.state.executeInProgress?c.default.createElement("div",{className:"loading-container"},c.default.createElement("div",{className:"loading"})):null,w?c.default.createElement(S,{responses:w,request:s,tryItOutResponse:i,getComponent:p,specSelectors:y,specActions:h,produces:P,producesValue:a.get("produces_value"),pathMethod:[n,o],fn:f}):null)))}}]),t}(c.default.Component);m.propTypes={path:l.PropTypes.string.isRequired,method:l.PropTypes.string.isRequired,operation:l.PropTypes.object.isRequired,showSummary:l.PropTypes.bool,isShownKey:y.arrayOrString.isRequired,jumpToKey:y.arrayOrString.isRequired,allowTryItOut:l.PropTypes.bool,response:l.PropTypes.object,request:l.PropTypes.object,getComponent:l.PropTypes.func.isRequired,authActions:l.PropTypes.object,authSelectors:l.PropTypes.object,specActions:l.PropTypes.object.isRequired,specSelectors:l.PropTypes.object.isRequired,layoutActions:l.PropTypes.object.isRequired,layoutSelectors:l.PropTypes.object.isRequired,fn:l.PropTypes.object.isRequired},m.defaultProps={showSummary:!0,response:null,allowTryItOut:!0},t.default=m},function(e,t){e.exports=require("react-addons-shallow-compare")},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.objectWithFuncs=t.arrayOrString=void 0;var n=r(187),o=function(e,t){return n.PropTypes.shape(e.reduce(function(e,r){return e[r]=t,e},{}))};t.arrayOrString=n.PropTypes.oneOfType([n.PropTypes.arrayOf(n.PropTypes.string),n.PropTypes.string]),t.objectWithFuncs=function(e){return o(e,n.PropTypes.func.isRequired)}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r1&&(g=E[1])}f=l.default.createElement("div",null,l.default.createElement("a",{href:v,download:g},"Download file"))}else f=l.default.createElement("pre",null,"Download headers detected but your browser does not support downloading binary via XHR (Blob).")}else f="string"==typeof t?l.default.createElement(i,{value:t}):l.default.createElement("div",null,"Unknown response type");return f?l.default.createElement("div",null,l.default.createElement("h5",null,"Response body"),f):null}}]),t}(l.default.Component);d.propTypes={content:s.PropTypes.any.isRequired,contentType:s.PropTypes.string.isRequired,getComponent:s.PropTypes.func.isRequired,headers:s.PropTypes.object,url:s.PropTypes.string},t.default=d},function(e,t,r){var n=r(40),o=n(function(e,t,r){return e+(r?" ":"")+t.toLowerCase()});e.exports=o},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(){for(var e=arguments.length,t=Array(e),r=0;r=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;tc,collapsedContent:w},p.default.createElement("span",{className:"brace-open object"},m),n?p.default.createElement(E,{name:r}):null,p.default.createElement("span",{className:"inner-object"},p.default.createElement("table",{className:"model",style:{marginLeft:"2em"}},p.default.createElement("tbody",null,d?p.default.createElement("tr",{style:{color:"#999",fontStyle:"italic"}},p.default.createElement("td",null,"description:"),p.default.createElement("td",null,d)):null,h&&h.size?h.entrySeq().map(function(e){var t=l(e,2),n=t[0],o=t[1],c=y.List.isList(_)&&_.contains(n),f={verticalAlign:"top",paddingRight:"0.2em"};return c&&(f.fontWeight="bold"),p.default.createElement("tr",{key:n},p.default.createElement("td",{style:f},n,":"),p.default.createElement("td",{style:{verticalAlign:"top"}},p.default.createElement(j,s({key:"object-"+r+"-"+n+"_"+o},i,{required:c,getComponent:a,schema:o,depth:u+1}))))}).toArray():null,b&&b.size?p.default.createElement("tr",null,p.default.createElement("td",null,"< * >:"),p.default.createElement("td",null,p.default.createElement(j,s({},i,{required:!1,getComponent:a,schema:b,depth:u+1})))):null))),p.default.createElement("span",{className:"brace-close"},v)))}}]),t}(f.Component);_.propTypes={schema:f.PropTypes.object.isRequired,getComponent:f.PropTypes.func.isRequired,specSelectors:f.PropTypes.object.isRequired,name:f.PropTypes.string,isRef:f.PropTypes.bool,expandDepth:f.PropTypes.number,depth:f.PropTypes.number};var E=function(e){function t(){return a(this,t),u(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return i(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.schema,r=e.required;if(!t||!t.get)return p.default.createElement("div",null);var n=t.get("type"),o=t.get("format"),a=t.get("xml"),u=t.get("enum"),i=t.filter(function(e,t){return["enum","type","format","$$ref"].indexOf(t)===-1}),s=r?{fontWeight:"bold"}:{};return p.default.createElement("span",{className:"prop"},p.default.createElement("span",{className:"prop-type",style:s},n)," ",r&&p.default.createElement("span",{style:{color:"red"}},"*"),o&&p.default.createElement("span",{className:"prop-format"},"($",o,")"),i.size?i.entrySeq().map(function(e){var t=l(e,2),r=t[0],n=t[1];return p.default.createElement("span",{key:r+"-"+n,style:b},p.default.createElement("br",null),"description"!==r&&r+": ",String(n))}):null,a&&a.size?p.default.createElement("span",null,p.default.createElement("br",null),p.default.createElement("span",{style:b},"xml:"),a.entrySeq().map(function(e){var t=l(e,2),r=t[0],n=t[1];return p.default.createElement("span",{key:r+"-"+n,style:b},p.default.createElement("br",null),"   ",r,": ",String(n))}).toArray()):null,u&&p.default.createElement(g,{value:u}))}}]),t}(f.Component);E.propTypes={schema:f.PropTypes.object.isRequired,required:f.PropTypes.bool};var w=function(e){function t(){return a(this,t),u(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return i(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.required,r=e.schema,n=e.depth,o=e.expandDepth,a=r.get("items"),u=r.filter(function(e,t){return["type","items","$$ref"].indexOf(t)===-1});return p.default.createElement("span",{className:"model"},p.default.createElement("span",{className:"model-title"},p.default.createElement("span",{className:"model-title__text"},r.get("title"))),p.default.createElement(O,{collapsed:n>o,collapsedContent:"[...]"},"[",p.default.createElement("span",null,p.default.createElement(j,s({},this.props,{schema:a,required:!1}))),"]",u.size?p.default.createElement("span",null,u.entrySeq().map(function(e){var t=l(e,2),r=t[0],n=t[1];return p.default.createElement("span",{key:r+"-"+n,style:b},p.default.createElement("br",null),r+":",String(n))}),p.default.createElement("br",null)):null),t&&p.default.createElement("span",{style:{color:"red"}},"*"))}}]),t}(f.Component);w.propTypes={schema:f.PropTypes.object.isRequired,getComponent:f.PropTypes.func.isRequired,specSelectors:f.PropTypes.object.isRequired,name:f.PropTypes.string,required:f.PropTypes.bool,expandDepth:f.PropTypes.number,depth:f.PropTypes.number};var j=function(e){function t(){var e,r,n,o;a(this,t);for(var i=arguments.length,s=Array(i),l=0;l|>=|<|<=|==|!=|gt|gte|lt|lte|eq|neq)$/)"` //比较方式 [> >= < <= == !=]或者[gt gte lt lte eq neq] + Threshold float64 `json:"threshold" valid:"Required"` //阈值 + Times int `json:"times" valid:"Required;Match(/^(1|2|3|5|10|15|30|60)$/)"` //持续周期数 [1, 2, 3, 5, 10, 15, 30, 60] + NoticeLevel int `json:"noticeLevel" valid:"Required"` //告警级别 [1表示一般,2表示严重,3表示紧急] +} + +// RuleNotice 通知策略 +type RuleNotice struct { + BaseRequest + NoticePeriod int `json:"noticePeriod" valid:"Required;Match(/^(5|10|15|30|60|180|360|720|1440)$/)"` //通知周期(分钟) [5 10 15 30 60 180 360 720 1440] + /* + EffectiveIntervalStart string `json:"effectiveIntervalStart"` // 有效时段开始时间 ["00:00:00"] + EffectiveIntervalEnd string `json:"effectiveIntervalEnd"` // 有效时段结束时间 ["23:59:59"] + NoticeCondition []int `json:"noticeCondition"` //通知条件,可多选 [1表示报警, 2表示恢复正常] + NoticeWay []int `json:"noticeWay"` //接收渠道,可多选 [1表示站内信, 2表示邮件] + UserID string `json:"userId"` //通知对象 + */ +} + + + diff --git a/bmp-pronoea/types/request/rulesDeleteRequest.go b/bmp-pronoea/types/request/rulesDeleteRequest.go new file mode 100644 index 0000000..9fb3648 --- /dev/null +++ b/bmp-pronoea/types/request/rulesDeleteRequest.go @@ -0,0 +1,7 @@ +package request + +type RulesDeleteRequest struct { + BaseRequest + RuleIds string `json:"ruleIds" valid:"Required"` //多个id,用英文逗号分隔 + Source string `json:"source" valid:"Required"` +} diff --git a/bmp-pronoea/types/response/metricQueryResponse.go b/bmp-pronoea/types/response/metricQueryResponse.go new file mode 100644 index 0000000..ac32d86 --- /dev/null +++ b/bmp-pronoea/types/response/metricQueryResponse.go @@ -0,0 +1,14 @@ +package response + +import "git.jd.com/bmp-pronoea/types/request" + +type MetricRangeQueryResponse struct { + Data []*MetricRangeQueryData `json:"data"` + Query *request.MetricRangeQueryRequest `json:"query"` +} + +type MetricRangeQueryData struct { + Timestamp int64 `json:"timestamp"` + Value string `json:"value"` +} + diff --git a/bmp-pronoea/types/response/prometheusRulesListResponse.go b/bmp-pronoea/types/response/prometheusRulesListResponse.go new file mode 100644 index 0000000..414ee1d --- /dev/null +++ b/bmp-pronoea/types/response/prometheusRulesListResponse.go @@ -0,0 +1,12 @@ +package response + + +type PrometheusRuleListResponse struct { + Rules []*PrometheusRuleListItem `json:"rules"` +} + + +type PrometheusRuleListItem struct { + RuleId string `json:"ruleId"` + InstanceIds []string `json:"instanceIds"` +} diff --git a/bmp-scheduler/.cmd b/bmp-scheduler/.cmd new file mode 100644 index 0000000..ced32d3 --- /dev/null +++ b/bmp-scheduler/.cmd @@ -0,0 +1 @@ +rm -rf vendor diff --git a/bmp-scheduler/.gitmodules b/bmp-scheduler/.gitmodules new file mode 100644 index 0000000..506f24c --- /dev/null +++ b/bmp-scheduler/.gitmodules @@ -0,0 +1,3 @@ +[submodule "bmp-deploy"] + path = bmp-deploy + url = git@coding.jd.com:aidc-bmp/bmp-deploy.git diff --git a/bmp-scheduler/Dockerfile b/bmp-scheduler/Dockerfile new file mode 100644 index 0000000..d5337bc --- /dev/null +++ b/bmp-scheduler/Dockerfile @@ -0,0 +1,16 @@ + FROM centos:7.9.2009 + +MAINTAINER minping@jd.com +USER root +RUN groupadd -g 2001 ironic-scheduler +RUN useradd -d /home/ironic-scheduler -u 2001 -g 2001 ironic-scheduler + +WORKDIR /home/ironic-scheduler + +ADD ./ironic-scheduler /home/ironic-scheduler/ +RUN mkdir -p /home/ironic-scheduler/conf +ADD ./conf/* /home/ironic-scheduler/conf/ + +RUN chmod 755 /home/ironic-scheduler/ironic-scheduler +USER ironic-scheduler +CMD ./ironic-scheduler \ No newline at end of file diff --git a/bmp-scheduler/Makefile b/bmp-scheduler/Makefile new file mode 100644 index 0000000..7d7e3f6 --- /dev/null +++ b/bmp-scheduler/Makefile @@ -0,0 +1,10 @@ + +BUILD_TIME := $(shell date +%Y%m%d%H%M%S) +VERSION := $(shell git describe --tags --always) +COMMITID := $(shell git rev-parse ${VERSION} | cut -c 1-32) +APP_NAME := ironic-scheduler-golang + +#GOARCH=amd64 GOOS=linux +ldflags ="-s -X main.VERSION=${COMMITID} -X main.BUILD_TIME=${BUILD_TIME}" +all: + GOARCH=amd64 GOOS=linux go build -ldflags ${ldflags} -o ${APP_NAME} main.go diff --git a/bmp-scheduler/README.md b/bmp-scheduler/README.md new file mode 100644 index 0000000..af04368 --- /dev/null +++ b/bmp-scheduler/README.md @@ -0,0 +1,50 @@ +# bmp-scheduler + +English | [简体中文](README.zh-CN.md) + + +## Introduction + +The scheduling module mainly maintains the status flow of devices and instances. + +bmp arch: +![bmp arch](docs/resources/bmp(open-source)arch.png) + +Module Introduction: + +- bmp-console-web:Console front end +- bmp-operation-web:Operation platform front end +- bmp-console-api:Adaptation layer for bmp-openapi-console and bmp-console-web +- bmp-operation-api:Adaptation layer for bmp-openapi and bmp-operation-web +- bmp-openapi-console:The core openapi interface layer used by the console +- bmp-openapi:The core openapi interface layer used by the operation platform +- bmp-scheduler:The core scheduling layer is responsible for the state transfer of devices and instances. +- bmp-driver:The out-of-band control layer is responsible for sending ipmitool commands to bm +- bmp-agent:Responsible for starting liveos and interacting with bmp-scheduler +- inbond-agent:In-band monitoring collection agent, responsible for bm data collection and reporting to inbond-agent-proxy +- bmp-dhcp-agent:Responsible for adding and deleting dhcp configuration +- inbond-agent-proxy:Responsible for cleaning the data collected by inbond-agent, reporting it to pushgateway, and finally storing it in prometheus +- push-gateway:Prometheus built-in module, responsible for receiving in-band monitoring data +- prometheus:Open source prometheus components +- pronoea:A self-made module that receives alarm rules and sends the generated alarms to bmp-openapi-console. +- oob-agent:Out-of-band monitoring collection agent +- oob-alert:Responsible for filtering the data collected by oob-agent according to specified rules and issuing business alarms when alarms are triggered. + + +bmp device and instance status flow: + +![bmp LifeCycle](docs/resources/cps-lifecycle.png) + +## 2,Core Features + +- Equipment import:Bare metal equipment can be imported into the BMP system through the operation platform。 +- Equipment Collection:Collect information about the disk, network card, etc. of bare metal devices. +- Equipment putaway:After collecting bare metal devices, bind them to the appropriate model and put them on the shelf. After the devices are put on the shelf, you can create instances in the console. +- Instance create:In the console, you can specify various configurations for the listed devices to create a physical machine running an operating system. +- Instance destroy:Destroy the system disk of the physical machine running the operating system and restore it to a bare metal device. +- Instance reinstall:Reinstall the operating system on a device that has an operating system installed. +- Instance startup:Send a remote out-of-band command to power on the system. +- Instance shutdown:Send a remote out-of-band command to shut down the system. +- Instance restart:Send a remote out-of-band command to reboot. +- Instance reset password:Reset the root user login password of the operating system. + diff --git a/bmp-scheduler/README.zh-CN.md b/bmp-scheduler/README.zh-CN.md new file mode 100644 index 0000000..102ec45 --- /dev/null +++ b/bmp-scheduler/README.zh-CN.md @@ -0,0 +1,50 @@ +# bmp-scheduler + + +[English](README.md) | 简体中文 + +## 介绍 + +调度模块,主要功能是维护设备和实例的状态流转。 + +bmp架构图: +![bmp arch](docs/resources/bmp(open-source)arch.png) + +模块介绍: + +- bmp-console-web:控制台前端 +- bmp-operation-web:运营平台前端 +- bmp-console-api:控制台和前端的适配层 +- bmp-operation-api:运营平台和前端的适配层 +- bmp-openapi-console:控制台使用的核心openapi接口层 +- bmp-openapi:运营平台使用的核心openapi接口层 +- bmp-scheduler:核心调度层,负责设备和实例的状态流转 +- bmp-driver:带外控制层,负责向bm发送ipmitool命令控制 +- bmp-agent:负责liveos的启动,以及和bmp-scheduler的交互 +- inbond-agent:带内监控采集agent,负责bm的数据采集并上报到inbond-agent-proxy +- bmp-dhcp-agent:负责对dhcp配置的增删 +- inbond-agent-proxy:负责将inbond-agent采集的数据进行清洗,并上报到pushgateway,最终存储在prometheus中 +- push-gateway:prometheus内置模块,负责接收带内监控数据 +- prometheus:开源prometheus组件 +- pronoea:自制模块,负责接收告警规则,并将产生的告警发送到bmp-openapi-console,经业务告警出来 +- oob-agent:带外监控采集agent +- oob-alert:负责将oob-agent采集的数据经指定规则过滤,触发报警时经业务告警出来。 + + +bmp设备和实例状态流转: + +![bmp LifeCycle](docs/resources/cps-lifecycle.png) + +## 2,核心功能 + +- 设备导入:裸金属设备可经运营平台导入到bmp系统中。 +- 设备采集:采集裸金属设备的磁盘、网卡等信息。 +- 设备上架:裸金属设备采集后绑定合适机型,即可上架,上架后的设备可以在控制台创建实例。 +- 创建实例:在控制台可以将上架的设备指定各种配置,创建成一台运行操作系统的物理机。 +- 销毁实例:将运行操作系统的物理机销毁系统盘,还原成裸金属设备。 +- 重装实例:对已安装操作系统的设备重新安装操作系统。 +- 实例开机:发送远程带外命令开机。 +- 实例关机:发送远程带外命令关机。 +- 实例重启:发送远程带外命令重启。 +- 实例重置密码:重置操作系统root用户登陆密码。 + diff --git a/bmp-scheduler/apiActor/CollectHardwareInfoApiActor.go b/bmp-scheduler/apiActor/CollectHardwareInfoApiActor.go new file mode 100644 index 0000000..287a696 --- /dev/null +++ b/bmp-scheduler/apiActor/CollectHardwareInfoApiActor.go @@ -0,0 +1,74 @@ +package apiActor + +import ( + "encoding/json" + "fmt" + + "coding.jd.com/aidc-bmp/bmp-scheduler/service/redis" + "coding.jd.com/aidc-bmp/bmp-scheduler/types" + constants "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + "git.jd.com/cps-golang/ironic-common/ironic/enums/AuditLogsType" + + auditLogLogic "coding.jd.com/aidc-bmp/bmp-scheduler/logic/auditLogLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/template" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + log "git.jd.com/cps-golang/log" +) + +type CollectHardwareInfoActor struct { + BaseActor +} + +func NewCollectHardwareInfoActor() CollectHardwareInfoActor { + return CollectHardwareInfoActor{} +} + +func (s CollectHardwareInfoActor) Do(logger *log.Logger, msg string, task string) { + logger.Info("CollectHardwareInfoActor do starting......", msg, task) + defer logger.Info("CollectHardwareInfoActor do ending......", msg, task) + message := rabbitIronicMsgApi.CollectHardwareInfoMessage{} + if err := json.Unmarshal([]byte(msg), &message); err != nil { + logger.Warn("CollectHardwareInfoActor Unmarshal error:", err.Error()) + return + } + message.RequestId = logger.GetPoint("logid").(string) + saveCollectActionInfo(logger, message) + sns := message.Sns + c := make(chan int, 100) //并发度=100 + for i := 0; i < len(sns); i++ { + c <- 1 + go func(i int) { + defer func() { + <-c + }() + + auditLogLogic.SaveAuditLogs(logger, sns[i], "", AuditLogsType.AuditLogsCollectHardwareInfo) + + templater := template.CollectHardwareInfoTemplate{} + //拆分成子任务并写到库中 status状态为wait + templater.InitCommand(logger, message.RequestId, sns[i], message.NetworkType, message.AllowOverride, task) + + //执行第一条任务(发送到agent或者driver等下游,等下游执行完成后发送callback消息到mq,scheduler获取callback消息后再从库中取下一条指令执行) + GetAndStartFirstCommand(logger, sns[i]) + + }(i) + } +} + +// 保存信息到redis +func saveCollectActionInfo(logger *log.Logger, message rabbitIronicMsgApi.CollectHardwareInfoMessage) { + for _, sn := range message.Sns { + instance_extra := types.CollectInfoExtra{ + NetworkType: message.NetworkType, + Sn: sn, + } + val, err := json.Marshal(instance_extra) + if err != nil { + logger.Warn("saveCollectActionInfo Marshal error:", err.Error()) + return + } + if err := redis.SetObjectToRedisWithExpire(fmt.Sprintf(constants.COLLECT_EXTRA_KEY, sn), string(val), 60*60*24*15); err != nil { + logger.Warn("saveCollectActionInfo SetObjectToRedisWithExpire error:", err.Error()) + } + } +} diff --git a/bmp-scheduler/apiActor/CreateInstancesActor.go b/bmp-scheduler/apiActor/CreateInstancesActor.go new file mode 100644 index 0000000..271cfc0 --- /dev/null +++ b/bmp-scheduler/apiActor/CreateInstancesActor.go @@ -0,0 +1,120 @@ +package apiActor + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + auditLogLogic "coding.jd.com/aidc-bmp/bmp-scheduler/logic/auditLogLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceTypeLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/imageLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/osLogic" + + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/partitionLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/service/redis" + "coding.jd.com/aidc-bmp/bmp-scheduler/template" + "coding.jd.com/aidc-bmp/bmp-scheduler/types" + constants "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + "git.jd.com/cps-golang/ironic-common/ironic/enums/AuditLogsType" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + log "git.jd.com/cps-golang/log" +) + +type CreateInstancesActor struct { + BaseActor +} + +func NewCreateInstancesActor() CreateInstancesActor { + return CreateInstancesActor{} +} + +func (s CreateInstancesActor) Do(logger *log.Logger, msg string, task string) { + logger.Info("CreateInstancesActor do starting...", msg) + defer logger.Info("CreateInstancesActor do ending...", msg) + var message = rabbitIronicMsgApi.CreateInstancesMessage{} + if err := json.Unmarshal([]byte(msg), &message); err != nil { + logger.Warn("CreateInstancesActor Unmarshal error:", err.Error()) + return + } + message.RequestId = logger.GetPoint("logid").(string) + for _, instance_id := range message.InstanceIds { + instance, err := instanceLogic.GetByInstanceId(logger, instance_id) + if err != nil { + logger.Warn("CreateInstancesActor.GetByInstanceId error:", instance_id, err.Error()) + return + } + device, _ := deviceDao.GetDeviceById(logger, instance.DeviceID) + v, _ := json.Marshal(device) + logger.Info("the device is:", device.DeviceID, string(v)) + + auditLogLogic.SaveAuditLogs(logger, device.Sn, instance_id, AuditLogsType.AuditLogsTypeCreateInstances) + + instance_extra := types.InstanceExtra{ + InstanceId: instance.InstanceID, + Password: message.Password, + UserData: message.UserData, + } + + //如果要下载监控agent的话,在这里才确定了用哪个device,根据device的architecture来决定下载哪个版本的agent + ud := instance_extra.UserData + if ud != "" && device.Architecture == "aarch64" { //默认是x86_64的,如果是arm的需替换,后面需要把openapi-console的userdata逻辑移动过来 + decodeUd, err := base64.StdEncoding.DecodeString(ud) + if err != nil { + logger.Warnf("CreateInstancesActor.Base64Decode userData error:%s", err.Error()) + } else { + decodeUdStr := string(decodeUd) + decodeUdStr = strings.Replace(decodeUdStr, "bmp-agent.bin", "bmp-agent.bin.arm", -1) + ud = base64.StdEncoding.EncodeToString([]byte(decodeUdStr)) + } + } + instance_extra.UserData = ud + + if message.AliasIps != nil { + instance_extra.AliasIps = message.AliasIps.([]types.AliasIP) + } + if message.ExtensionAliasIps != nil { + instance_extra.ExtensionAliasIps = message.ExtensionAliasIps.([]types.AliasIP) + } + val, _ := json.Marshal(instance_extra) + err = redis.SetObjectToRedisWithExpire(fmt.Sprintf(constants.INSTANCE_EXTRA_KEY, instance_id), string(val), 60*60*24*2) + if err != nil { + logger.Warn("CreateInstancesActor SetObjectToRedis error:", instance_id, err.Error()) + } + + partitions_entity, err := partitionLogic.GetByDeviceTypeAndImageId(logger, instance.DeviceTypeID, instance.ImageID) + if err != nil { + logger.Warn("CreateInstancesActor_GetByDeviceTypeAndImageId sql error:", instance.DeviceTypeID, instance.ImageID, err.Error()) + } + isMakePat := false + if len(partitions_entity) > 0 { + isMakePat = true + } + v1, _ := json.Marshal(partitions_entity) + logger.Info("partitions_entity res:", string(v1)) + image_entity, err := imageLogic.GetByImageId(logger, instance.ImageID) + if err != nil { + logger.Warn("CreateInstancesActor_GetByImageId sql error:", err.Error()) + } + os_entity, err := osLogic.GetByOsId(logger, image_entity.OsID) + if err != nil { + logger.Warn("CreateInstancesActor GetByOsId sql error:", image_entity.OsID, err.Error()) + } + deviceTypeEntity, err := deviceTypeLogic.GetDeviceTypeByID(logger, device.DeviceTypeID) + if err != nil { + logger.Warn("CreateInstancesActor GetDeviceTypeByID sql error:", device.DeviceTypeID, err.Error()) + } + if os_entity.OsType != "Windows" { + templater := template.CreateInstanceTemplateComposite{} + templater.InitCommand(logger, "basic", deviceTypeEntity.InterfaceMode, message.RequestId, instance_id, device.Sn, isMakePat, image_entity.Format, task) + } else { + templater := template.CreateInstanceTemplateCompositeForWindows{} + templater.InitCommand(logger, "basic", deviceTypeEntity.InterfaceMode, message.RequestId, instance_id, device.Sn, isMakePat, image_entity.Format, task) + } + //拆分成子任务并写到库中 + GetAndStartFirstCommand(logger, device.Sn) + } + +} diff --git a/bmp-scheduler/apiActor/CutDeviceStockActor.go b/bmp-scheduler/apiActor/CutDeviceStockActor.go new file mode 100644 index 0000000..e245810 --- /dev/null +++ b/bmp-scheduler/apiActor/CutDeviceStockActor.go @@ -0,0 +1,48 @@ +package apiActor + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/template" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + log "git.jd.com/cps-golang/log" +) + +type CutDeviceStockActor struct { + BaseActor +} + +func NewCutDeviceStockActor() CutDeviceStockActor { + return CutDeviceStockActor{} +} + +func (s CutDeviceStockActor) Do(logger *log.Logger, msg string, task string) { + + message := rabbitIronicMsgApi.CutDeviceStockMessage{} + if err := json.Unmarshal([]byte(msg), &message); err != nil { + logger.Warn("CutDeviceStockActor Unmarshal error:", err.Error()) + return + } + message.RequestId = logger.GetPoint("logid").(string) + sns := message.Sns + for i := 0; i < len(sns); i++ { + if sns[i] == "" { + continue + } + device_entity, err := deviceLogic.GetBySn(logger, sns[i]) + if err != nil { + logger.Warn("CutDeviceStockActor GetBySn sql error:", sns[i], err.Error()) + } + if device_entity != nil { + logger.Warn(sns[i], " device_entity isNot del") + continue + } + templater := template.CutDeviceStockTemplate{} + //拆分成子任务并写到库中 + templater.InitCommand(logger, message.RequestId, sns[i], task) + //执行第一条任务(发送到agent或者driver等下游,等下游执行完成后发送callback消息到mq,scheduler获取callback消息后再从库中取下一条指令执行) + GetAndStartFirstCommand(logger, sns[i]) + + } +} diff --git a/bmp-scheduler/apiActor/DeleteInstanceActor.go b/bmp-scheduler/apiActor/DeleteInstanceActor.go new file mode 100644 index 0000000..d3aeedb --- /dev/null +++ b/bmp-scheduler/apiActor/DeleteInstanceActor.go @@ -0,0 +1,51 @@ +package apiActor + +import ( + "encoding/json" + + auditLogLogic "coding.jd.com/aidc-bmp/bmp-scheduler/logic/auditLogLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/template" + "git.jd.com/cps-golang/ironic-common/ironic/enums/AuditLogsType" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + log "git.jd.com/cps-golang/log" +) + +type DeleteInstanceActor struct { + BaseActor +} + +func NewDeleteInstanceActor() DeleteInstanceActor { + return DeleteInstanceActor{} +} + +func (s DeleteInstanceActor) Do(logger *log.Logger, msg string, task string) { + + message := rabbitIronicMsgApi.DeleteInstanceMessage{} + if err := json.Unmarshal([]byte(msg), &message); err != nil { + logger.Warn("DeleteInstanceActor Unmarshal error:", err.Error()) + return + } + message.RequestId = logger.GetPoint("logid").(string) + instance, err := instanceLogic.GetByInstanceId(logger, message.InstanceId) + if err != nil { + logger.Warn("DeleteInstanceActor GetByInstanceId sql error:", message.InstanceId, err.Error()) + } + device, err := deviceLogic.GetById(logger, instance.DeviceID) + if err != nil { + logger.Warn("DeleteInstanceActor GetById sql error:", instance.DeviceID, err.Error()) + } + + auditLogLogic.SaveAuditLogs(logger, device.Sn, message.InstanceId, AuditLogsType.AuditLogsDeleteInstance) + + templater := template.DeleteInstanceTemplateComposite{} + //拆分成子任务并写到库中 + templater.InitCommand(logger, "instance.NetworkType", message.RequestId, instance.InstanceID, device.Sn, task) + s.sendEmail() + GetAndStartFirstCommand(logger, device.Sn) +} + +func (s *DeleteInstanceActor) sendEmail() { + //TODO +} diff --git a/bmp-scheduler/apiActor/InstanceResetPasswordActor.go b/bmp-scheduler/apiActor/InstanceResetPasswordActor.go new file mode 100644 index 0000000..8599a33 --- /dev/null +++ b/bmp-scheduler/apiActor/InstanceResetPasswordActor.go @@ -0,0 +1,68 @@ +package apiActor + +import ( + "encoding/json" + "fmt" + + auditLogLogic "coding.jd.com/aidc-bmp/bmp-scheduler/logic/auditLogLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/service/redis" + "coding.jd.com/aidc-bmp/bmp-scheduler/template" + "coding.jd.com/aidc-bmp/bmp-scheduler/types" + constants "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + "git.jd.com/cps-golang/ironic-common/ironic/enums/AuditLogsType" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + log "git.jd.com/cps-golang/log" +) + +type InstanceResetPasswordActor struct { + BaseActor +} + +func NewInstanceResetPasswordActor() InstanceResetPasswordActor { + return InstanceResetPasswordActor{} +} + +func (s InstanceResetPasswordActor) Do(logger *log.Logger, msg string, task string) { + + message := rabbitIronicMsgApi.InstanceResetPasswordMessage{} + if err := json.Unmarshal([]byte(msg), &message); err != nil { + logger.Warn("InstanceResetPasswordActor Unmarshal error:", err.Error()) + return + } + message.RequestId = logger.GetPoint("logid").(string) + instance_id := message.InstanceId + instance, err := instanceLogic.GetByInstanceId(logger, instance_id) + if err != nil { + logger.Warn("InstanceResetPasswordActor GetByInstanceId sql error:", instance_id, err.Error()) + } + device, err := deviceLogic.GetById(logger, instance.DeviceID) + if err != nil { + logger.Warn("InstanceResetPasswordActor GetById sql error:", instance.DeviceID, err.Error()) + } + if message.Action == "Monitor" { + sendResetPasswordMessage() + return + } + + auditLogLogic.SaveAuditLogs(logger, device.Sn, message.InstanceId, AuditLogsType.AuditLogsInstanceResetPassword) + + instance_extra := types.InstanceExtra{ + InstanceId: instance_id, + Password: message.Password, + } + val, _ := json.Marshal(instance_extra) + if err = redis.SetObjectToRedisWithExpire(fmt.Sprintf(constants.INSTANCE_EXTRA_KEY, instance_id), string(val), 60*60*24*2); err != nil { + logger.Warn("InstanceResetPasswordActor SetObjectToRedis error:", instance_id, err.Error()) + } + templater := template.ResetPasswordTemplateComposite{} + //拆分成子任务并写到库中 + templater.InitCommand(logger, "instance.NetworkType", message.RequestId, instance.InstanceID, device.Sn, task) + GetAndStartFirstCommand(logger, device.Sn) + +} + +func sendResetPasswordMessage() { + //TODO +} diff --git a/bmp-scheduler/apiActor/ModifyBandwidthActor.go b/bmp-scheduler/apiActor/ModifyBandwidthActor.go new file mode 100644 index 0000000..4cab820 --- /dev/null +++ b/bmp-scheduler/apiActor/ModifyBandwidthActor.go @@ -0,0 +1,49 @@ +package apiActor + +import ( + "encoding/json" + "fmt" + + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/service/redis" + "coding.jd.com/aidc-bmp/bmp-scheduler/template" + "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + log "git.jd.com/cps-golang/log" +) + +type ModifyBandwidthActor struct { + BaseActor +} + +func NewModifyBandwidthActor() ModifyBandwidthActor { + return ModifyBandwidthActor{} +} + +func (s ModifyBandwidthActor) Do(logger *log.Logger, msg string, task string) { + + message := rabbitIronicMsgApi.ModifyBandwidthMessage{} + if err := json.Unmarshal([]byte(msg), &message); err != nil { + logger.Warn("ModifyBandwidthActor Unmarshal error:", err.Error()) + return + } + message.RequestId = logger.GetPoint("logid").(string) + instance_key := fmt.Sprintf("%s:%s", Constants.REDIS_KEY_STATUS, message.InstanceId) + if err := redis.SetObjectToRedisWithExpire(instance_key, message.InstanceStatus, Constants.TIMEOUT_INSTANCE_STATUS); err != nil { + logger.Warn("ModifyBandwidthActor SetObjectToRedis error:", err.Error()) + } + instance, err := instanceLogic.GetByInstanceId(logger, message.InstanceId) + if err != nil { + logger.Warn("ModifyBandwidthActor_GetByInstanceId sql error:", err.Error()) + } + device, err := deviceLogic.GetById(logger, instance.DeviceID) + if err != nil { + logger.Warn("ModifyBandwidthActor_GetById sql error:", err.Error()) + } + + templater := template.ModifyBandwidthTemplate{} + //拆分成子任务并写到库中 + templater.InitCommand(logger, message.RequestId, message.InstanceId, device.Sn, task) + GetAndStartFirstCommand(logger, device.Sn) +} diff --git a/bmp-scheduler/apiActor/PutawayDeviceActor.go b/bmp-scheduler/apiActor/PutawayDeviceActor.go new file mode 100644 index 0000000..4fda3cc --- /dev/null +++ b/bmp-scheduler/apiActor/PutawayDeviceActor.go @@ -0,0 +1,42 @@ +package apiActor + +import ( + "encoding/json" + + auditLogLogic "coding.jd.com/aidc-bmp/bmp-scheduler/logic/auditLogLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/template" + "git.jd.com/cps-golang/ironic-common/ironic/enums/AuditLogsType" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + log "git.jd.com/cps-golang/log" +) + +type PutawayDeviceActor struct { + BaseActor +} + +func NewPutawayDeviceActor() PutawayDeviceActor { + return PutawayDeviceActor{} +} + +func (s PutawayDeviceActor) Do(logger *log.Logger, msg string, task string) { + + message := rabbitIronicMsgApi.PutawayDeviceMessage{} + if err := json.Unmarshal([]byte(msg), &message); err != nil { + logger.Warn("StopInstancesActor Unmarshal error:", err.Error()) + return + } + message.RequestId = logger.GetPoint("logid").(string) + + device, err := deviceLogic.GetBySn(logger, message.Sn) + if err != nil { + logger.Warn("PutawayDeviceActor deviceLogic.GetBySn sql error:", message.Sn, err.Error()) + } + + auditLogLogic.SaveAuditLogs(logger, device.Sn, "", AuditLogsType.AuditLogsPutaway) + + templater := template.PutawayDeviceTemplate{} + //拆分成子任务并写到库中 + templater.InitCommand(logger, message.RequestId, "", message.Sn, task) + GetAndStartFirstCommand(logger, device.Sn) +} diff --git a/bmp-scheduler/apiActor/ReinstallInstanceActor.go b/bmp-scheduler/apiActor/ReinstallInstanceActor.go new file mode 100644 index 0000000..b011590 --- /dev/null +++ b/bmp-scheduler/apiActor/ReinstallInstanceActor.go @@ -0,0 +1,81 @@ +package apiActor + +import ( + "encoding/json" + "fmt" + + auditLogLogic "coding.jd.com/aidc-bmp/bmp-scheduler/logic/auditLogLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/imageLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/partitionLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/service/redis" + "coding.jd.com/aidc-bmp/bmp-scheduler/template" + "coding.jd.com/aidc-bmp/bmp-scheduler/types" + constants "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + "git.jd.com/cps-golang/ironic-common/ironic/enums/AuditLogsType" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + log "git.jd.com/cps-golang/log" +) + +type ReinstallInstanceActor struct { + BaseActor +} + +func NewReinstallInstanceActor() ReinstallInstanceActor { + return ReinstallInstanceActor{} +} + +func (s ReinstallInstanceActor) Do(logger *log.Logger, msg string, task string) { + + message := rabbitIronicMsgApi.ReinstallInstanceMessage{} + if err := json.Unmarshal([]byte(msg), &message); err != nil { + logger.Warn("ReinstallInstanceActor Unmarshal error:", err.Error()) + return + } + message.RequestId = logger.GetPoint("logid").(string) + instance_id := message.InstanceId + instance, err := instanceLogic.GetByInstanceId(logger, instance_id) + if err != nil { + logger.Warn("ReinstallInstanceActor GetByInstanceId sql error:", instance_id, err.Error()) + } + device, err := deviceLogic.GetById(logger, instance.DeviceID) + if err != nil { + logger.Warn("ReinstallInstanceActor GetById sql error:", instance.DeviceID, err.Error()) + } + + auditLogLogic.SaveAuditLogs(logger, device.Sn, message.InstanceId, AuditLogsType.AuditLogsReinstallInstance) + + instance_extra := types.InstanceExtra{ + InstanceId: instance_id, + Password: message.Password, + UserData: message.UserData, + KeepData: message.KeepData, + } + val, _ := json.Marshal(instance_extra) + if err = redis.SetObjectToRedisWithExpire(fmt.Sprintf(constants.INSTANCE_EXTRA_KEY, instance_id), string(val), 60*60*24*2); err != nil { + logger.Warn("ReinstallInstanceActor SetObjectToRedis error:", instance_id, err.Error()) + } + partitions_entity, err := partitionLogic.GetByDeviceTypeAndImageId(logger, device.DeviceTypeID, instance.ImageID) + if err != nil { + logger.Warn("ReinstallInstanceActor GetByDeviceTypeAndImageId sql error:", device.DeviceTypeID, instance.ImageID, err.Error()) + } + image_entity, err := imageLogic.GetByImageId(logger, instance.ImageID) + if err != nil { + logger.Warn("ReinstallInstanceActor GetByImageId sql error:", instance.ImageID, err.Error()) + } + isMakePat := false + if len(partitions_entity) > 0 { + isMakePat = true + } + + templater := template.ReinstallInstanceTemplateComposite{} + //拆分成子任务并写到库中 + templater.InitCommand(logger, "instance.NetworkType", "instance.InterfaceMode", message.RequestId, instance.InstanceID, device.Sn, message.KeepData, isMakePat, image_entity.Format, task) + s.sendEmail() + GetAndStartFirstCommand(logger, device.Sn) +} + +func (s *ReinstallInstanceActor) sendEmail() { + //TODO +} diff --git a/bmp-scheduler/apiActor/ResetSwitchConfigActor.go b/bmp-scheduler/apiActor/ResetSwitchConfigActor.go new file mode 100644 index 0000000..cdb3d24 --- /dev/null +++ b/bmp-scheduler/apiActor/ResetSwitchConfigActor.go @@ -0,0 +1,45 @@ +package apiActor + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/template" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + log "git.jd.com/cps-golang/log" +) + +type ResetSwitchConfigActor struct { + BaseActor +} + +func NewResetSwitchConfigActor() ResetSwitchConfigActor { + return ResetSwitchConfigActor{} +} + +func (s ResetSwitchConfigActor) Do(logger *log.Logger, msg string, task string) { + + message := rabbitIronicMsgApi.ResetSwitchConfigMessage{} + if err := json.Unmarshal([]byte(msg), &message); err != nil { + logger.Warn("ResetSwitchConfigActor Unmarshal error:", err.Error()) + return + } + + message.RequestId = logger.GetPoint("logid").(string) + instance_ids := message.InstanceIds + for _, instance_id := range instance_ids { + instance, err := instanceLogic.GetByInstanceId(logger, instance_id) + if err != nil { + logger.Warn("ModifyBandwidthActor_GetByInstanceId sql error:", instance_id, err.Error()) + } + device, err := deviceLogic.GetById(logger, instance.DeviceID) + if err != nil { + logger.Warn("ModifyBandwidthActor_GetById sql error:", instance.DeviceID, err.Error()) + } + templater := template.ResetSwitchConfigTemplate{} + //拆分成子任务并写到库中 + templater.InitCommand(logger, message.RequestId, instance_id, device.Sn, task) + GetAndStartFirstCommand(logger, device.Sn) + } +} diff --git a/bmp-scheduler/apiActor/RestartDhcpActor.go b/bmp-scheduler/apiActor/RestartDhcpActor.go new file mode 100644 index 0000000..5f20658 --- /dev/null +++ b/bmp-scheduler/apiActor/RestartDhcpActor.go @@ -0,0 +1,39 @@ +package apiActor + +import ( + "encoding/json" + "fmt" + + "coding.jd.com/aidc-bmp/bmp-scheduler/service/redis" + "coding.jd.com/aidc-bmp/bmp-scheduler/template" + "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + log "git.jd.com/cps-golang/log" +) + +type RestartDhcpActor struct { + BaseActor +} + +func NewRestartDhcpActor() RestartDhcpActor { + return RestartDhcpActor{} +} + +func (s RestartDhcpActor) Do(logger *log.Logger, msg string, task string) { + + message := rabbitIronicMsgApi.RestartDhcpMessage{} + if err := json.Unmarshal([]byte(msg), &message); err != nil { + logger.Warn("RestartDhcpActor Unmarshal error:", err.Error()) + return + } + message.RequestId = logger.GetPoint("logid").(string) + if err := redis.SetObjectToRedisWithExpire(Constants.DHCP_RESTART_KEY, message.Az, 60*60*24); err != nil { + logger.Warn("RestartDhcpActor SetObjectToRedis error:", message.Az, err.Error()) + } + DEFAULT_SN := "DHCP_%s" + sn := fmt.Sprintf(DEFAULT_SN, message.Az) + templater := template.DHCPRestartTemplate{} + //拆分成子任务并写到库中 + templater.InitCommand(logger, message.RequestId, sn, task) + GetAndStartFirstCommand(logger, sn) +} diff --git a/bmp-scheduler/apiActor/RestartInstancesActor.go b/bmp-scheduler/apiActor/RestartInstancesActor.go new file mode 100644 index 0000000..29dafd6 --- /dev/null +++ b/bmp-scheduler/apiActor/RestartInstancesActor.go @@ -0,0 +1,50 @@ +package apiActor + +import ( + "encoding/json" + + auditLogLogic "coding.jd.com/aidc-bmp/bmp-scheduler/logic/auditLogLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/template" + "git.jd.com/cps-golang/ironic-common/ironic/enums/AuditLogsType" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + log "git.jd.com/cps-golang/log" +) + +type RestartInstancesActor struct { + BaseActor +} + +func NewRestartInstancesActor() RestartInstancesActor { + return RestartInstancesActor{} +} + +func (s RestartInstancesActor) Do(logger *log.Logger, msg string, task string) { + + message := rabbitIronicMsgApi.RestartInstancesMessage{} + if err := json.Unmarshal([]byte(msg), &message); err != nil { + logger.Warn("RestartInstancesActor Unmarshal error:", err.Error()) + return + } + message.RequestId = logger.GetPoint("logid").(string) + instance_ids := message.InstanceIds + for _, instance_id := range instance_ids { + instance, err := instanceLogic.GetByInstanceId(logger, instance_id) + if err != nil { + logger.Warn("RestartInstancesActor_GetByInstanceId sql error:", instance_id, err.Error()) + } + device, err := deviceLogic.GetById(logger, instance.DeviceID) + if err != nil { + logger.Warn("RestartInstancesActor_GetById sql error:", instance.DeviceID, err.Error()) + } + + auditLogLogic.SaveAuditLogs(logger, device.Sn, instance_id, AuditLogsType.AuditLogsRestartInstances) + + templater := template.RestartInstanceTemplate{} + //拆分成子任务并写到库中 + templater.InitCommand(logger, message.RequestId, instance_id, device.Sn, task) + GetAndStartFirstCommand(logger, device.Sn) + } + +} diff --git a/bmp-scheduler/apiActor/StartInstancesActor.go b/bmp-scheduler/apiActor/StartInstancesActor.go new file mode 100644 index 0000000..b19c6d8 --- /dev/null +++ b/bmp-scheduler/apiActor/StartInstancesActor.go @@ -0,0 +1,50 @@ +package apiActor + +import ( + "encoding/json" + + auditLogLogic "coding.jd.com/aidc-bmp/bmp-scheduler/logic/auditLogLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/template" + "git.jd.com/cps-golang/ironic-common/ironic/enums/AuditLogsType" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + log "git.jd.com/cps-golang/log" +) + +type StartInstancesActor struct { + BaseActor +} + +func NewStartInstancesActor() StartInstancesActor { + return StartInstancesActor{} +} + +func (s StartInstancesActor) Do(logger *log.Logger, msg string, task string) { + + message := rabbitIronicMsgApi.StartInstancesMessage{} + if err := json.Unmarshal([]byte(msg), &message); err != nil { + logger.Warn("StartInstancesActor Unmarshal error:", err.Error()) + return + } + message.RequestId = logger.GetPoint("logid").(string) + instance_ids := message.InstanceIds + for _, instance_id := range instance_ids { + instance, err := instanceLogic.GetByInstanceId(logger, instance_id) + if err != nil { + logger.Warn("StartInstancesMessage_GetByInstanceId sql error:", instance_id, err.Error()) + } + device, err := deviceLogic.GetById(logger, instance.DeviceID) + if err != nil { + logger.Warn("StartInstancesMessage_GetById sql error:", instance.DeviceID, err.Error()) + } + + auditLogLogic.SaveAuditLogs(logger, device.Sn, instance_id, AuditLogsType.AuditLogsStartInstances) + + templater := template.StartInstanceTemplate{} + //拆分成子任务并写到库中 + templater.InitCommand(logger, message.RequestId, instance_id, device.Sn, task) + GetAndStartFirstCommand(logger, device.Sn) + } + +} diff --git a/bmp-scheduler/apiActor/StopInstancesActor.go b/bmp-scheduler/apiActor/StopInstancesActor.go new file mode 100644 index 0000000..95cc40c --- /dev/null +++ b/bmp-scheduler/apiActor/StopInstancesActor.go @@ -0,0 +1,50 @@ +package apiActor + +import ( + "encoding/json" + + auditLogLogic "coding.jd.com/aidc-bmp/bmp-scheduler/logic/auditLogLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/template" + "git.jd.com/cps-golang/ironic-common/ironic/enums/AuditLogsType" + rabbitIronicMsgApi "git.jd.com/cps-golang/ironic-common/ironic/event/api" + log "git.jd.com/cps-golang/log" +) + +type StopInstancesActor struct { + BaseActor +} + +func NewStopInstancesActor() StopInstancesActor { + return StopInstancesActor{} +} + +func (s StopInstancesActor) Do(logger *log.Logger, msg string, task string) { + + message := rabbitIronicMsgApi.StopInstancesMessage{} + if err := json.Unmarshal([]byte(msg), &message); err != nil { + logger.Warn("StopInstancesActor Unmarshal error:", err.Error()) + return + } + message.RequestId = logger.GetPoint("logid").(string) + instance_ids := message.InstanceIds + for _, instance_id := range instance_ids { + instance, err := instanceLogic.GetByInstanceId(logger, instance_id) + if err != nil { + logger.Warn("StopInstancesMessage_GetByInstanceId sql error:", instance_id, err.Error()) + } + device, err := deviceLogic.GetById(logger, instance.DeviceID) + if err != nil { + logger.Warn("StopInstancesMessage_GetById sql error:", instance.DeviceID, err.Error()) + } + + auditLogLogic.SaveAuditLogs(logger, device.Sn, instance_id, AuditLogsType.AuditLogsStopInstances) + + templater := template.StopInstanceTemplate{} + //拆分成子任务并写到库中 + templater.InitCommand(logger, message.RequestId, instance_id, device.Sn, task) + GetAndStartFirstCommand(logger, device.Sn) + } + +} diff --git a/bmp-scheduler/apiActor/baseApiActor.go b/bmp-scheduler/apiActor/baseApiActor.go new file mode 100644 index 0000000..fbfd7e8 --- /dev/null +++ b/bmp-scheduler/apiActor/baseApiActor.go @@ -0,0 +1,82 @@ +package apiActor + +import ( + "encoding/json" + "runtime" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/processor" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandStatus" + log "git.jd.com/cps-golang/log" +) + +type ApiActor interface { + Do(*log.Logger, string, string) +} + +type BaseActor struct { +} + +var ApiActorMap map[string]ApiActor + +func init() { + ApiActorMap = map[string]ApiActor{} + ApiActorMap["CollectHardwareInfo"] = NewCollectHardwareInfoActor() + ApiActorMap["CreateInstances"] = NewCreateInstancesActor() + ApiActorMap["CutDeviceStock"] = NewCutDeviceStockActor() + ApiActorMap["DeleteInstance"] = NewDeleteInstanceActor() + ApiActorMap["InstanceResetPassword"] = NewInstanceResetPasswordActor() + ApiActorMap["ModifyBandwidth"] = NewModifyBandwidthActor() + ApiActorMap["ReinstallInstance"] = NewReinstallInstanceActor() + ApiActorMap["ResetSwitchConfig"] = NewResetSwitchConfigActor() + ApiActorMap["RestartDhcp"] = NewRestartDhcpActor() + ApiActorMap["RestartInstances"] = NewRestartInstancesActor() + ApiActorMap["StartInstances"] = NewStartInstancesActor() + ApiActorMap["StopInstances"] = NewStopInstancesActor() + ApiActorMap["PutawayDevice"] = NewPutawayDeviceActor() + +} + +//业务代码可以直接panic终止运行 +func CatchException() { + if r := recover(); r != nil { + t := make([]byte, 1<<16) + runtime.Stack(t, true) + // b.LogPoints.Warn(string(t)) + } +} + +func GetAndStartFirstCommand(logger *log.Logger, sn string) { + // 不允许状态为running的status出现 + command_running_count, err := commandDao.CountBySnAndStatus(logger, sn, CommandStatus.RUNNING) + if err != nil { + logger.Warn(sn, "CountBySnAndStatus sql error:", err.Error()) + } + if command_running_count > 0 { + logger.Warn(sn, " commands are running. skip start message") + return + } + // 不允许状态为error的status出现 + command_error_count, err := commandDao.CountBySnAndStatus(logger, sn, CommandStatus.ERROR) + if err != nil { + logger.Warn(sn, "CountBySnAndStatus sql error:", err.Error()) + } + if command_error_count > 0 { + logger.Warn(sn, " commands are error. skip start message") + return + } + param := map[string]interface{}{ + "sn": sn, + "status": CommandStatus.WAIT, + "is_del": 0, + } + command, err := commandDao.GetFirstCommand(logger, param) + if err != nil { + logger.Warn(sn, "GetFirstCommand sql error:", err.Error()) + return + } + b, _ := json.Marshal(command) + logger.Info("get first cmd: ", string(b)) + processor.ProcessorMap[command.Action].Process(logger, command) + +} diff --git a/bmp-scheduler/bmp-scheduler.Dockerfile b/bmp-scheduler/bmp-scheduler.Dockerfile new file mode 100644 index 0000000..15a408a --- /dev/null +++ b/bmp-scheduler/bmp-scheduler.Dockerfile @@ -0,0 +1,11 @@ +FROM golang:1.17-alpine AS builder +ENV GOPROXY https://goproxy.cn +WORKDIR /usr/src/bmp-scheduler +COPY . . +RUN go build -o /tmp/bmp-scheduler . + +FROM alpine:3.16 +WORKDIR /home/bmp/bmp-scheduler +COPY --from=builder /tmp/bmp-scheduler . +COPY ./conf ./conf +CMD ["./bmp-scheduler"] diff --git a/bmp-scheduler/bmp_vendor/ironic-common/go.mod b/bmp-scheduler/bmp_vendor/ironic-common/go.mod new file mode 100644 index 0000000..5364f89 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/go.mod @@ -0,0 +1,3 @@ +module git.jd.com/cps-golang/ironic-common + +go 1.17 diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/common/Constants/Constants.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/common/Constants/Constants.go new file mode 100644 index 0000000..b987bd2 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/common/Constants/Constants.go @@ -0,0 +1,145 @@ +package Constants + +const ( + SUFFIX = "%s_command_processor" + + INSTANCE_EXTRA_KEY = "ironic_instance_extra_%s" + + RESTART_DHCP_EXTRA_KEY = "restart_dhcp_extra" + + COLLECT_EXTRA_KEY = "collect_sn_extra_%s" + + INSTANCE_ALIAS_IP_KEY = "ironic_instance_alias_ip_%s_%s" + + COMMAND_RESULT = "ironic_command_result_%s" + + REDIS_KEY_CLUSTER = "ironic_cluster" + + REDIS_KEY_CHECK = "ironic_check" + + REDIS_KEY_INSTANCE = "ironic_instance" + + REDIS_KEY_STATUS = "ironic_instance_status" + + DHCP_RESTART_KEY = "dhcp_restart_key" + + REDIS_KEY_MAIL_RECEIVER_FORMAT = "ironic_mail_receiver_%s" + + REDIS_KEY_MONITOR_COMMAND_FORMAT = "ironic_monitor_command_%s_%s" + + TIMEOUT_INSTANCE_START int = 2 * 60 + + TIMEOUT_INSTANCE_STOP int = 30 + + TIMEOUT_INSTANCE_RESTART int = 3 * 60 + + TIMEOUT_INSTANCE_RESTART_WINDOWS int = 8 * 60 + + TIMEOUT_INSTANCE_STATUS int = 60 * 60 + + TIMEOUT_MONITOR_COMMAND int = 60 * 60 + + TAR_IMAGE = "tar" + + SET_PXE_BOOT_PROCESSOR_NAME = "SetPXEBoot_command_processor" + + SET_DISK_BOOT_PROCESSOR_NAME = "SetDISKBoot_command_processor" + + POWER_ON_PROCESSOR_NAME = "PowerOn_command_processor" + + POWER_OFF_PROCESSOR_NAME = "PowerOff_command_processor" + + DHCP_RESTART_PROCESSOR_NAME = "DHCPRestart_command_processor" + + POWER_RESET_PROCESSOR_NAME = "PowerReset_command_processor" + + POWER_CYCLE_PROCESSOR_NAME = "PowerCycle_command_processor" + + INIT_ROOT_DEVICE_PROCESSOR_NAME = "InitRootDevice_command_processor" + + CLEAN_RAID_PROCESSOR_NAME = "CleanRaid_command_processor" + + MAKE_RAID_PROCESSOR_NAME = "MakeRaid_command_processor" + + PING_PROCESSOR_NAME = "Ping_command_processor" + + ADD_DHCP_CONFIG_HOST_PROCESSOR_NAME = "DHCPConfigAddHost_command_processor" + + DEL_DHCP_CONFIG_HOST_PROCESSOR_NAME = "DHCPConfigDelHost_command_processor" + + WRITE_IMAGE_RAID_PROCESSOR_NAME = "WriteImage_command_processor" + + WRITE_IMAGE_TAR_PROCESSOR_NAME = "WriteImageTar_command_processor" + + QCOW2_MAKE_PARTITIONS_PROCESSOR_NAME = "Qcow2MakePartitions_command_processor" + + MAKE_PARTITIONS_PROCESSOR_NAME = "MakePartitions_command_processor" + + SET_HOSTNAME_PROCESSOR_NAME = "SetHostname_command_processor" + + SET_PASSWORD_PROCESSOR_NAME = "SetPassword_command_processor" + + SET_NETWORK_PROCESSOR_NAME = "SetNetwork_command_processor" + + SET_BOND_PROCESSOR_NAME = "SetBond_command_processor" + + SET_RETAIL_BOND_PROCESSOR_NAME = "SetRetailBond_command_processor" + + SDN_SET_NETWORK_PROCESSOR_NAME = "SetVpcNetwork_command_processor" + + SET_USER_CMD_PROCESSOR_NAME = "SetUserCmd_command_processor" + + SET_KEYPAIRS_PROCESSOR_NAME = "SetKeypairs_command_processor" + + CLEAN_BLOCK_DEVICE_PROCESSOR_NAME = "CleanBlockDevice_command_processor" + + COLLECT_HARDWARE_INFO_PROCESSOR_NAME = "CollectHardwareInfo_command_processor" + + UPLOAD_SYSTEM_LOG_PROCESSOR_NAME = "UploadSystemLog_command_processor" + + CREATE_VRF_PROCESSOR_NAME = "CreateVRF_command_processor" + + CREATE_VRF_BALANCE_PROCESSOR_NAME = "CreateVRFBalance_command_processor" + + CREATE_VSI_INTERFACE_PROCESSOR_NAME = "CreateVSIInterface_command_processor" + + CREATE_VSI_PROCESSOR_NAME = "CreateVSI_command_processor" + + BINDING_VSI_PROCESSOR_NAME = "BindingVSI_command_processor" + + UN_BINDING_VSI_PROCESSOR_NAME = "UnBindingVSI_command_processor" + + BINDING_IPV6_PROCESSOR_NAME = "BindingIPv6_command_processor" + + CREATE_VNI_PROCESSOR_NAME = "CreateVNI_command_processor" + + ADD_ARP_STATIC_PROCESSOR_NAME = "AddArpStatic_command_processor" + + CLEAN_ARP_STATIC_PROCESSOR_NAME = "CleanArpStatic_command_processor" + + SET_BANDWIDTH_PROCESSOR_NAME = "SetBandwidth_command_processor" + + CLEAN_BANDWIDTH__PROCESSOR_NAME = "CleanBandwidth_command_processor" + + SAVE_SWITCH_CONFIG_PROCESSOR_NAME = "SaveSwitchConfig_command_processor" + + SAVE_CONFIG_TO_FTP_SERVER_PROCESSOR_NAME = "SaveConfigToFtpServer_command_processor" + + SYSTEM_ERROR_COMMAND_PROCESSOR_NAME = "SystemErrorCommand_command_processor" + + SDN_REGISTER_PROCESSOR_NAME = "SDNRegister_command_processor" + + SDN_SUBNET_BINDING_PROCESSOR_NAME = "SDNSubnetBinding_command_processor" + + SDN_SUBNET_UNBINDING_PROCESSOR_NAME = "SDNSubnetUnBinding_command_processor" + + SDN_EIP_BINDING_PROCESSOR_NAME = "SDNEipBinding_command_processor" + + SDN_EIP_UNBINDING_PROCESSOR_NAME = "SDNEipUnBinding_command_processor" + + SDN_CLEAN_PROCESSOR_NAME = "SDNClean_command_processor" + + SDN_ADD_ALIAS_IP_PROCESSOR_NAME = "SDNAddAliasIP_command_processor" + + SDN_DELETE_ALIAS_IP_PROCESSOR_NAME = "SDNDeleteAliasIP_command_processor" +) diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/AuditLogsType/AuditLogsType.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/AuditLogsType/AuditLogsType.go new file mode 100644 index 0000000..7b44e06 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/AuditLogsType/AuditLogsType.go @@ -0,0 +1,23 @@ +package AuditLogsType + +const ( + //操作消息类型 + + AuditLogsPutaway = "PutawayDevice" //上架 + AuditLogsUnPutaway = "UnPutawayDevice" //下架 + AuditLogsStartInstances = "StartInstances" //开机 + AuditLogsStopInstances = "StopInstances" //关机 + AuditLogsRestartInstances = "RestartInstances" //重启 + AuditLogsResetInstanceStatus = "ResetInstances" //重置实例状态(新增) + AuditLogsRemoveDevice = "RemoveDevice" //设备移除(新增) + AuditLogsDeleteDevice = "DeleteDevice" //设备删除(新增) + AuditLogsDeleteInstance = "DeleteInstance" //回收实例 + AuditLogsInstanceResetPassword = "InstanceResetPassword" //重置密码 + AuditLogsReinstallInstance = "ReinstallInstance" //重装系统 + AuditLogsEditInstanceName = "EditInstanceName" //编辑实例名称(新增) + AuditLogsCollectHardwareInfo = "CollectHardwareInfo" //设备采集 + AuditLogsTypeCreateInstances = "CreateInstances" //创建实例 + AuditLogsTypeDropInstances = "DropInstances" //删除实例(不走销毁流程,新增) + AuditLogsTypeLockInstances = "LockInstances" //锁定实例(新增) + +) diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/CommandAction/CommandAction.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/CommandAction/CommandAction.go new file mode 100644 index 0000000..c60b286 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/CommandAction/CommandAction.go @@ -0,0 +1,132 @@ +package CommandAction + +import ( + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/TimeoutPolicy" +) + +type CommandAction struct { + Name string + CommandType string + Timeout int + Policy string +} + +var ( + Start = CommandAction{"Start", "", 0, TimeoutPolicy.WARNING} + Heart = CommandAction{"Heart", "", 0, TimeoutPolicy.WARNING} + SystemErrorCommand = CommandAction{"SystemErrorCommand", "", 0, TimeoutPolicy.WARNING} + DHCPConfigAddSubnet = CommandAction{"DHCPConfigAddSubnet", CommandType.DRIVER, 3 * 60, TimeoutPolicy.WARNING} + CheckInitConfig = CommandAction{"CheckInitConfig", CommandType.DRIVER, 3 * 60, TimeoutPolicy.WARNING} + DHCPConfigAddHost = CommandAction{"DHCPConfigAddHost", CommandType.DRIVER, 3 * 60, TimeoutPolicy.WARNING} + DHCPConfigDelHost = CommandAction{"DHCPConfigDelHost", CommandType.DRIVER, 3 * 60, TimeoutPolicy.WARNING} + SetPXEBoot = CommandAction{"SetPXEBoot", CommandType.DRIVER, 3 * 60, TimeoutPolicy.WARNING} + SetDISKBoot = CommandAction{"SetDISKBoot", CommandType.DRIVER, 3 * 60, TimeoutPolicy.WARNING} + PowerOn = CommandAction{"PowerOn", CommandType.DRIVER, 3 * 60, TimeoutPolicy.WARNING} + PowerOff = CommandAction{"PowerOff", CommandType.DRIVER, 3 * 60, TimeoutPolicy.WARNING} + PowerReset = CommandAction{"PowerReset", CommandType.DRIVER, 3 * 60, TimeoutPolicy.WARNING} + PowerCycle = CommandAction{"PowerCycle", CommandType.DRIVER, 3 * 60, TimeoutPolicy.WARNING} + DHCPRestart = CommandAction{"DHCPRestart", CommandType.DRIVER, 3 * 60, TimeoutPolicy.SKIP} + + CollectHardwareInfo = CommandAction{"CollectHardwareInfo", CommandType.AGENT, 10 * 60, TimeoutPolicy.SKIP} + CollectDiskLocations = CommandAction{"CollectDiskLocations", CommandType.AGENT, 10 * 60, TimeoutPolicy.SKIP} + UploadSystemLog = CommandAction{"UploadSystemLog", CommandType.AGENT, 3 * 60, TimeoutPolicy.SKIP} + CleanRaid = CommandAction{"CleanRaid", CommandType.AGENT, 6 * 60, TimeoutPolicy.WARNING} + MakeRaid = CommandAction{"MakeRaid", CommandType.AGENT, 6 * 60, TimeoutPolicy.WARNING} + WriteImage = CommandAction{"WriteImage", CommandType.AGENT, 25 * 60, TimeoutPolicy.WARNING} + WriteImageTar = CommandAction{"WriteImageTar", CommandType.AGENT, 25 * 60, TimeoutPolicy.WARNING} + Qcow2MakePartitions = CommandAction{"Qcow2MakePartitions", CommandType.AGENT, 6 * 60, TimeoutPolicy.WARNING} + MakePartitions = CommandAction{"MakePartitions", CommandType.AGENT, 25 * 60, TimeoutPolicy.WARNING} + SetHostname = CommandAction{"SetHostname", CommandType.AGENT, 3 * 60, TimeoutPolicy.WARNING} + SetPassword = CommandAction{"SetPassword", CommandType.AGENT, 3 * 60, TimeoutPolicy.WARNING} + SetNetwork = CommandAction{"SetNetwork", CommandType.AGENT, 3 * 60, TimeoutPolicy.WARNING} + SetVpcNetwork = CommandAction{"SetVpcNetwork", CommandType.AGENT, 3 * 60, TimeoutPolicy.WARNING} + SetBond = CommandAction{"SetBond", CommandType.AGENT, 3 * 60, TimeoutPolicy.WARNING} + SetUserCmd = CommandAction{"SetUserCmd", CommandType.AGENT, 3 * 60, TimeoutPolicy.WARNING} + SetKeypairs = CommandAction{"SetKeypairs", CommandType.AGENT, 3 * 60, TimeoutPolicy.WARNING} + //帮忙Agent重试mq链接 + Ping = CommandAction{"Ping", CommandType.AGENT, 30 * 60, TimeoutPolicy.WARNING} + InitRootDevice = CommandAction{"InitRootDevice", CommandType.AGENT, 6 * 60, TimeoutPolicy.WARNING} + CleanBlockDevice = CommandAction{"CleanBlockDevice", CommandType.AGENT, 25 * 60, TimeoutPolicy.WARNING} + + CreateVRF = CommandAction{"CreateVRF", CommandType.NETWORK, 60, TimeoutPolicy.WARNING} + CreateVRFBalance = CommandAction{"CreateVRFBalance", CommandType.NETWORK, 60, TimeoutPolicy.WARNING} + CreateVSIInterface = CommandAction{"CreateVSIInterface", CommandType.NETWORK, 60, TimeoutPolicy.WARNING} + CreateVSI = CommandAction{"CreateVSI", CommandType.NETWORK, 60, TimeoutPolicy.WARNING} + BindingVSI = CommandAction{"BindingVSI", CommandType.NETWORK, 60, TimeoutPolicy.WARNING} + UnBindingVSI = CommandAction{"UnBindingVSI", CommandType.NETWORK, 60, TimeoutPolicy.WARNING} + SetRetailBond = CommandAction{"SetRetailBond", CommandType.NETWORK, 60, TimeoutPolicy.WARNING} + CreateVNI = CommandAction{"CreateVNI", CommandType.NETWORK, 60, TimeoutPolicy.WARNING} + AddArpStatic = CommandAction{"AddArpStatic", CommandType.NETWORK, 60, TimeoutPolicy.WARNING} + CleanArpStatic = CommandAction{"CleanArpStatic", CommandType.NETWORK, 60, TimeoutPolicy.WARNING} + SetBandwidth = CommandAction{"SetBandwidth", CommandType.NETWORK, 60, TimeoutPolicy.WARNING} + CleanBandwidth = CommandAction{"CleanBandwidth", CommandType.NETWORK, 60, TimeoutPolicy.WARNING} + SaveSwitchConfig = CommandAction{"SaveSwitchConfig", CommandType.NETWORK, 60, TimeoutPolicy.WARNING} + SaveConfigToFtpServer = CommandAction{"SaveConfigToFtpServer", CommandType.NETWORK, 60, TimeoutPolicy.WARNING} + + SDNRegister = CommandAction{"SDNRegister", CommandType.SDN, 60, TimeoutPolicy.WARNING} + SDNSubnetBinding = CommandAction{"SDNSubnetBinding", CommandType.SDN, 60, TimeoutPolicy.WARNING} + SDNSubnetUnBinding = CommandAction{"SDNSubnetUnBinding", CommandType.SDN, 60, TimeoutPolicy.WARNING} + SDNEipBinding = CommandAction{"SDNEipBinding", CommandType.SDN, 60, TimeoutPolicy.WARNING} + SDNEipUnBinding = CommandAction{"SDNEipUnBinding", CommandType.SDN, 60, TimeoutPolicy.WARNING} + SDNAddAliasIP = CommandAction{"SDNAddAliasIP", CommandType.SDN, 60, TimeoutPolicy.WARNING} + SDNDeleteAliasIP = CommandAction{"SDNDeleteAliasIP", CommandType.SDN, 60, TimeoutPolicy.WARNING} + SDNClean = CommandAction{"SDNClean", CommandType.SDN, 60, TimeoutPolicy.WARNING} +) + +var CommandActionDict = map[string]CommandAction{ + "Start": Start, + "Heart": Heart, + "SystemErrorCommand": SystemErrorCommand, + "DHCPConfigAddSubnet": DHCPConfigAddSubnet, + "CheckInitConfig": CheckInitConfig, + "DHCPConfigAddHost": DHCPConfigAddHost, + "DHCPConfigDelHost": DHCPConfigDelHost, + "SetPXEBoot": SetPXEBoot, + "SetDISKBoot": SetDISKBoot, + "PowerOn": PowerOn, + "PowerOff": PowerOff, + "PowerReset": PowerReset, + "PowerCycle": PowerCycle, + "DHCPRestart": DHCPRestart, + "CollectHardwareInfo": CollectHardwareInfo, + "UploadSystemLog": UploadSystemLog, + "CleanRaid": CleanRaid, + "MakeRaid": MakeRaid, + "WriteImage": WriteImage, + "WriteImageTar": WriteImageTar, + "Qcow2MakePartitions": Qcow2MakePartitions, + "MakePartitions": MakePartitions, + "SetHostname": SetHostname, + "SetPassword": SetPassword, + "SetNetwork": SetNetwork, + "SetVpcNetwork": SetVpcNetwork, + "SetBond": SetBond, + "SetUserCmd": SetUserCmd, + "SetKeypairs": SetKeypairs, + "Ping": Ping, + "InitRootDevice": InitRootDevice, + "CleanBlockDevice": CleanBlockDevice, + "CreateVRF": CreateVRF, + "CreateVRFBalance": CreateVRFBalance, + "CreateVSIInterface": CreateVSIInterface, + "CreateVSI": CreateVSI, + "BindingVSI": BindingVSI, + "UnBindingVSI": UnBindingVSI, + "SetRetailBond": SetRetailBond, + "CreateVNI": CreateVNI, + "AddArpStatic": AddArpStatic, + "CleanArpStatic": CleanArpStatic, + "SetBandwidth": SetBandwidth, + "CleanBandwidth": CleanBandwidth, + "SaveSwitchConfig": SaveSwitchConfig, + "SaveConfigToFtpServer": SaveConfigToFtpServer, + "SDNRegister": SDNRegister, + "SDNSubnetBinding": SDNSubnetBinding, + "SDNSubnetUnBinding": SDNSubnetUnBinding, + "SDNEipBinding": SDNEipBinding, + "SDNEipUnBinding": SDNEipUnBinding, + "SDNAddAliasIP": SDNAddAliasIP, + "SDNDeleteAliasIP": SDNDeleteAliasIP, + "SDNClean": SDNClean, +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/CommandStatus/CommandStatus.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/CommandStatus/CommandStatus.go new file mode 100644 index 0000000..044688c --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/CommandStatus/CommandStatus.go @@ -0,0 +1,28 @@ +package CommandStatus + +const ( + /** + * 待执行 + */ + WAIT = "wait" + + /** + * 执行中 + */ + RUNNING = "running" + + /** + * 完成 + */ + FINISH = "finish" + + /** + * 失败 + */ + ERROR = "error" + + /** + * 取消 + */ + CANCEL = "cancel" +) diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/CommandType/CommandType.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/CommandType/CommandType.go new file mode 100644 index 0000000..57e8834 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/CommandType/CommandType.go @@ -0,0 +1,11 @@ +package CommandType + +const ( + DRIVER = "driver" + + AGENT = "agent" + + NETWORK = "network" + + SDN = "sdn" +) diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/ImageType/ImageType.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/ImageType/ImageType.go new file mode 100644 index 0000000..310fcf3 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/ImageType/ImageType.go @@ -0,0 +1,15 @@ +package ImageType + +import "strings" + +const ( + CENTOS = "centos" + + UBUNTU = "ubuntu" + + WINDOWS = "windows" +) + +func IsWindows(imageType string) bool { + return strings.HasPrefix(strings.ToUpper(imageType), WINDOWS) +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/InstanceStatus/InstanceStatus.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/InstanceStatus/InstanceStatus.go new file mode 100644 index 0000000..7703e00 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/InstanceStatus/InstanceStatus.go @@ -0,0 +1,102 @@ +package InstanceStatus + +const ( + /** + * 创建中 + */ + CREATING = "creating" + + /** + * 开机中 + */ + STARTING = "starting" + + /** + * 运行 + */ + RUNNING = "running" + + /** + * 关机中 + */ + STOPPING = "stopping" + + /** + * 关机 + */ + STOPPED = "stopped" + + /** + * 重启中 + */ + RESTARTING = "restarting" + + /** + * 重置密码中 + */ + RESETTING_PASSWORD = "resetting_password" + + /** + * 销毁中 + */ + DESTROYING = "destroying" + + /** + * 已销毁 + */ + DESTROYED = "destroyed" + + /** + * 错误 + */ + ERROR = "error" + + /** + * 调整配置中 + */ + UPGRADING = "upgrading" + + /** + * 重装系统中 + */ + REINSTALLING = "reinstalling" + + // 创建失败 + CREATE_ERROR = "Creation failed" + // 开机失败 + START_ERROR = "Startup failed" + // 关机失败 + STOP_ERROR = "Shutdown failed" + // 重启失败 + RESTART_ERROR = "Reboot failed" + // 销毁失败 + DESTROY_ERROR = "Delete failed" + // 重装失败 + REINSTALL_ERROR = "Reinstall failed" + //重置密码失败 + RESETPASSWD_ERROR = "Resetpasswd failed" +) + +var Instance_To_Error_Status map[string]string = map[string]string{ + // "CollectHardwareInfo" : NewCollectHardwareInfoActor() + "CreateInstances": CREATE_ERROR, + // "CutDeviceStock" : NewCutDeviceStockActor() + "DeleteInstance": DESTROY_ERROR, + // "InstanceResetPassword" : NewInstanceResetPasswordActor() + // "ModifyBandwidth" : NewModifyBandwidthActor() + // "ReinstallInstance" : NewReinstallInstanceActor() + // "ResetSwitchConfig" : NewResetSwitchConfigActor() + // "RestartDhcp" : NewRestartDhcpActor() + "RestartInstances": RESTART_ERROR, + "StartInstances": START_ERROR, + "StopInstances": STOP_ERROR, + "ReinstallInstance": REINSTALL_ERROR, + "InstanceResetPassword": RESETPASSWD_ERROR, +} + +var Error_Instance_To_Reset_Status map[string]string = map[string]string{ + START_ERROR: STOPPED, + STOP_ERROR: RUNNING, + RESTART_ERROR: RUNNING, + DESTROY_ERROR: STOPPED, +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/InterfaceMode/InterfaceMode.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/InterfaceMode/InterfaceMode.go new file mode 100644 index 0000000..6acc674 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/InterfaceMode/InterfaceMode.go @@ -0,0 +1,14 @@ +package InterfaceMode + +const ( + + /** + * 单网口bond + */ + BOND = "bond" + + /** + * 双网口 + */ + DUAL = "dual" +) diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/InterfaceType/InterfaceType.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/InterfaceType/InterfaceType.go new file mode 100644 index 0000000..b01d6a6 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/InterfaceType/InterfaceType.go @@ -0,0 +1,7 @@ +package InterfaceType + +const ( + LAN = "lan" + + WAN = "wan" +) diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/MessageType/MessageType.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/MessageType/MessageType.go new file mode 100644 index 0000000..0b482b0 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/MessageType/MessageType.go @@ -0,0 +1,57 @@ +package MessageType + +const ( + //操作消息 + MessageTypeOperation = "operation" + //系统消息 + MessageTypeSystem = "system" + //监控消息 + MessageTypeOobMonitor = "oob-monitor" + //带内告警 + MessageTypeInBondAlert = "inbond-alert" +) + +const ( + //操作消息类型 + MessageSubTypeCollectHardwareInfo = "CollectHardwareInfo" + MessageSubTypeCreateDevices = "CreateDevices" + MessageSubTypeCreateInstances = "CreateInstances" + MessageSubTypeCutDeviceStock = "CutDeviceStock" + MessageSubTypeDeleteInstance = "DeleteInstance" + MessageSubTypeInstanceResetPassword = "InstanceResetPassword" + MessageSubTypePutawayDevice = "PutawayDevice" + MessageSubTypeReinstallInstance = "ReinstallInstance" + MessageSubTypeRestartInstances = "RestartInstances" + MessageSubTypeStartInstances = "StartInstances" + MessageSubTypeStopInstances = "StopInstances" + //系统消息类型 + MessageSubTypeLicenseNearTimeout = "LicenseNearTimeout" + //带外监控消息类型 + MessageSubTypePowerFault = "电力故障" + MessageSubTypeTemperatureFault = "温控故障" + MessageSubTypeCPUFault = "CPU故障" + MessageSubTypeMemFault = "内存故障" + MessageSubTypeDiskFault = "硬盘故障" + MessageSubTypeOtherFault = "其他故障" + + //带内告警类型 + MessageSubTypeCPUUsage = "bmp.cpu.util" + MessageSubTypeMemoryUsage = "bmp.memory.util" + MessageSubTypeMemoryUsed = "bmp.memory.used" + MessageSubTypeDiskUsed = "bmp.disk.used" + MessageSubTypeDiskUsage = "bmp.disk.util" + MessageSubTypeDiskReadTraffic = "bmp.disk.bytes.read" + MessageSubTypeDiskWriteTraffic = "bmp.disk.bytes.write" + MessageSubTypeDiskReadIOPS = "bmp.disk.counts.read" + MessageSubTypeDiskWriteIOPS = "bmp.disk.counts.write" + MessageSubTypeNetworkIngressTraffic = "bmp.network.bytes.ingress" + MessageSubTypeNetworkEgressTraffic = "bmp.network.bytes.egress" + MessageSubTypeNetworkIngressPackets = "bmp.network.packets.ingress" + MessageSubTypeNetworkEgressPackets = "bmp.network.packets.egress" + MessageSubTypeLoadAverage1min = "bmp.avg.load1" + MessageSubTypeLoadAverage5min = "bmp.avg.load5" + MessageSubTypeLoadAverage15min = "bmp.avg.load15" + MessageSubTypeTotalTCPConnections = "bmp.tcp.connect.total" + MessageSubTypeEstablishedTCPConnections = "bmp.tcp.connect.established" + MessageSubTypeTotalProcessCount = "bmp.process.total" +) diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/NetworkType/NetworkType.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/NetworkType/NetworkType.go new file mode 100644 index 0000000..848ef26 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/NetworkType/NetworkType.go @@ -0,0 +1,18 @@ +package NetworkType + +const ( + /** + * 基础网络 + */ + BASIC = "basic" + + /** + * 私有网络 + */ + VPC = "vpc" + + /** + * 零售中台网络 + */ + RETAIL = "retail" +) diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/TimeoutPolicy/TimeoutPolicy.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/TimeoutPolicy/TimeoutPolicy.go new file mode 100644 index 0000000..7cc87b2 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/enums/TimeoutPolicy/TimeoutPolicy.go @@ -0,0 +1,9 @@ +package TimeoutPolicy + +const ( + RETRY = "retry" + + SKIP = "skip" + + WARNING = "warning" +) diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/AllocRetailPrivateIpMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/AllocRetailPrivateIpMessage.go new file mode 100644 index 0000000..6744995 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/AllocRetailPrivateIpMessage.go @@ -0,0 +1,9 @@ +package api + +type AllocRetailPrivateIpMessage struct { + ApiMessage +} + +func (c AllocRetailPrivateIpMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.AllocRetailPrivateIpMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/ApiMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/ApiMessage.go new file mode 100644 index 0000000..9062508 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/ApiMessage.go @@ -0,0 +1,9 @@ +package api + +type ApiMessage struct { + RequestId string `json:"request_id"` +} + +func (c ApiMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.ApiMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/CollectHardwareInfoMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/CollectHardwareInfoMessage.go new file mode 100644 index 0000000..9b90a5b --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/CollectHardwareInfoMessage.go @@ -0,0 +1,13 @@ +package api + +type CollectHardwareInfoMessage struct { + ApiMessage + Sns []string `json:"sns"` + //是否清空raid + AllowOverride bool `json:"allowOverride"` + NetworkType string `json:"network_type"` +} + +func (c CollectHardwareInfoMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.CollectHardwareInfoMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/CreateDevicesMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/CreateDevicesMessage.go new file mode 100644 index 0000000..1726211 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/CreateDevicesMessage.go @@ -0,0 +1,14 @@ +package api + +type CreateDevicesMessage struct { + ApiMessage + Action string `json:"action"` + Sn string `json:"sn"` + Subnet string `json:"subnet"` + SubnetMask string `json:"subnet_mask"` + Routes string `json:"routes"` +} + +func (c CreateDevicesMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.CreateDevicesMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/CreateInstancesMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/CreateInstancesMessage.go new file mode 100644 index 0000000..d763005 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/CreateInstancesMessage.go @@ -0,0 +1,14 @@ +package api + +type CreateInstancesMessage struct { + ApiMessage + InstanceIds []string `json:"instance_ids"` + Password string `json:"password"` + UserData string `json:"user_data"` + AliasIps interface{} `json:"alias_ips"` //本来是[]AliasIP,依赖太深,直接定义成interface{} + ExtensionAliasIps interface{} `json:"extension_alias_ips"` //本来是[]AliasIP,依赖太深,直接定义成interface{} +} + +func (c CreateInstancesMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.CreateInstancesMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/CutDeviceStockMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/CutDeviceStockMessage.go new file mode 100644 index 0000000..6b61fb3 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/CutDeviceStockMessage.go @@ -0,0 +1,10 @@ +package api + +type CutDeviceStockMessage struct { + ApiMessage + Sns []string `json:"sns"` +} + +func (c CutDeviceStockMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.CutDeviceStockMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/DeleteInstanceMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/DeleteInstanceMessage.go new file mode 100644 index 0000000..952471b --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/DeleteInstanceMessage.go @@ -0,0 +1,10 @@ +package api + +type DeleteInstanceMessage struct { + ApiMessage + InstanceId string `json:"instance_id"` +} + +func (c DeleteInstanceMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.DeleteInstanceMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/InstanceResetPasswordMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/InstanceResetPasswordMessage.go new file mode 100644 index 0000000..c8e2ea8 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/InstanceResetPasswordMessage.go @@ -0,0 +1,12 @@ +package api + +type InstanceResetPasswordMessage struct { + ApiMessage + InstanceId string `json:"instance_id"` + Password string `json:"password"` + Action string `json:"action"` +} + +func (c InstanceResetPasswordMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.InstanceResetPasswordMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/ModifyBandwidthMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/ModifyBandwidthMessage.go new file mode 100644 index 0000000..05b94ea --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/ModifyBandwidthMessage.go @@ -0,0 +1,12 @@ +package api + +type ModifyBandwidthMessage struct { + ApiMessage + InstanceId string `json:"instance_id"` + Bandwidth int32 `json:"bandwidth"` + InstanceStatus string `json:"instance_status"` +} + +func (c ModifyBandwidthMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.ModifyBandwidthMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/PutawayDeviceMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/PutawayDeviceMessage.go new file mode 100644 index 0000000..2856c7f --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/PutawayDeviceMessage.go @@ -0,0 +1,11 @@ +package api + +//设备上架 +type PutawayDeviceMessage struct { + ApiMessage + Sn string `json:"sn"` +} + +func (c PutawayDeviceMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.PutawayDeviceMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/ReinstallInstanceMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/ReinstallInstanceMessage.go new file mode 100644 index 0000000..1b81a3e --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/ReinstallInstanceMessage.go @@ -0,0 +1,13 @@ +package api + +type ReinstallInstanceMessage struct { + ApiMessage + InstanceId string `json:"instance_id"` + KeepData bool `json:"keep_data"` + Password string `json:"password"` + UserData string `json:"user_data"` +} + +func (c ReinstallInstanceMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.ReinstallInstanceMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/ResetSwitchConfigMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/ResetSwitchConfigMessage.go new file mode 100644 index 0000000..ceced55 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/ResetSwitchConfigMessage.go @@ -0,0 +1,10 @@ +package api + +type ResetSwitchConfigMessage struct { + ApiMessage + InstanceIds []string `json:"instance_ids"` +} + +func (c ResetSwitchConfigMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.ResetSwitchConfigMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/RestartDhcpMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/RestartDhcpMessage.go new file mode 100644 index 0000000..2c27222 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/RestartDhcpMessage.go @@ -0,0 +1,10 @@ +package api + +type RestartDhcpMessage struct { + ApiMessage + Az string `json:"az"` +} + +func (c RestartDhcpMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.RestartDhcpMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/RestartInstancesMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/RestartInstancesMessage.go new file mode 100644 index 0000000..058e73b --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/RestartInstancesMessage.go @@ -0,0 +1,10 @@ +package api + +type RestartInstancesMessage struct { + ApiMessage + InstanceIds []string `json:"instance_ids"` +} + +func (c RestartInstancesMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.RestartInstancesMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/SDNCallbackMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/SDNCallbackMessage.go new file mode 100644 index 0000000..2b54eb7 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/SDNCallbackMessage.go @@ -0,0 +1,15 @@ +package api + +type SDNCallbackMessage struct { + ApiMessage + InstanceId string `json:"instance_id"` + Sn string `json:"sn"` + Action string `json:"action"` + Status string `json:"status"` + Message string `json:"message"` + Data interface{} `json:"data"` +} + +func (c SDNCallbackMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.SDNCallbackMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/StartInstancesMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/StartInstancesMessage.go new file mode 100644 index 0000000..1ffdbde --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/StartInstancesMessage.go @@ -0,0 +1,10 @@ +package api + +type StartInstancesMessage struct { + ApiMessage + InstanceIds []string `json:"instance_ids"` +} + +func (c StartInstancesMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.StartInstancesMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/StopInstancesMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/StopInstancesMessage.go new file mode 100644 index 0000000..254f477 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/api/StopInstancesMessage.go @@ -0,0 +1,10 @@ +package api + +type StopInstancesMessage struct { + ApiMessage + InstanceIds []string `json:"instance_ids"` +} + +func (c StopInstancesMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.api.StopInstancesMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/command/AbstractCommandMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/command/AbstractCommandMessage.go new file mode 100644 index 0000000..6b452b3 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/command/AbstractCommandMessage.go @@ -0,0 +1,10 @@ +package command + +type AbstractCommandMessage struct { + Sn string `json:"sn"` + Action string `json:"action"` +} + +func (c AbstractCommandMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.command.AbstractCommandMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/command/CallbackCommandMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/command/CallbackCommandMessage.go new file mode 100644 index 0000000..cbb981f --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/command/CallbackCommandMessage.go @@ -0,0 +1,12 @@ +package command + +type CallbackCommandMessage struct { + CommandMessage + Status string `json:"status,omitempty"` + Message string `json:"message,omitempty"` + Data interface{} `json:"data,omitempty"` +} + +func (c CallbackCommandMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.command.CallbackCommandMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/command/CommandMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/command/CommandMessage.go new file mode 100644 index 0000000..35d26b6 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/command/CommandMessage.go @@ -0,0 +1,10 @@ +package command + +type CommandMessage struct { + Sn string `json:"sn,omitempty"` + Action string `json:"action,omitempty"` +} + +func (c CommandMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.command.CommandMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/command/DefaultCommandMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/command/DefaultCommandMessage.go new file mode 100644 index 0000000..6acb4d4 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/command/DefaultCommandMessage.go @@ -0,0 +1,13 @@ +package command + +type DefaultCommandMessage struct { + CommandMessage + CommandId int64 `json:"command_id"` + RequestId string `json:"request_id"` + InstanceId string `json:"instance_id"` + Type string `json:"type"` +} + +func (c DefaultCommandMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.command.DefaultCommandMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/command/MonitorMessage.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/command/MonitorMessage.go new file mode 100644 index 0000000..104c40e --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/command/MonitorMessage.go @@ -0,0 +1,16 @@ +package command + +import "time" + +type MonitorMessage struct { + RequestId string `json:"request_id"` + Sn string `json:"sn"` + InstanceId string `json:"instance_id"` + Action string `json:"action"` + TimeoutPolicy string `json:"timeout_policy"` + Now time.Time `json:"now"` +} + +func (c MonitorMessage) ClazzName() string { + return "com.jcloud.cps.ironic.event.command.MonitorMessage" +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/event.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/event.go new file mode 100644 index 0000000..6343216 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/event/event.go @@ -0,0 +1,33 @@ +package event + +import ( + "time" + + "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +type Event struct { + EventUuid string `json:"event_uuid"` + ClazzName string `json:"clazz_name"` + Body string `json:"body"` + Time int64 `json:"time"` + UserID string `json:"user_id"` +} + +type CpsRabbitMsg interface { + ClazzName() string +} + +func NewEvent(msg CpsRabbitMsg, logid string, userId string) (*Event, error) { + b, err := util.Convert2String(msg) + if err != nil { + return nil, err + } + return &Event{ + EventUuid: logid, + ClazzName: msg.ClazzName(), + Body: string(b), + Time: time.Now().UnixNano() / 1e6, + UserID: userId, + }, nil +} diff --git a/bmp-scheduler/bmp_vendor/ironic-common/ironic/util/util.go b/bmp-scheduler/bmp_vendor/ironic-common/ironic/util/util.go new file mode 100644 index 0000000..5aca77e --- /dev/null +++ b/bmp-scheduler/bmp_vendor/ironic-common/ironic/util/util.go @@ -0,0 +1,77 @@ +package util + +import ( + "encoding/json" + "errors" + "fmt" + "math/rand" + "reflect" + "strconv" + "time" +) + +//GetRandString 借鉴RandomStringUtils.random包生成随机字符串 +// length 随机字符串的长度(不包括前缀) +// uletter 随机字符串是否包含大写字母字符 +// dletter 随机字符串是否包含小写字母字符 +// number 随机字符串是否包含数字字符 +func GetRandString(prefix string, length int32, uletter, dletter, number bool) string { + rand.Seed(time.Now().UnixNano()) + uletters := []rune("ABCDEFGHIGKLMNOPQRSTUVWXYZ") + dletters := []rune("abcdefghijklmnopqrstuvwxyz") + numbers := []rune("0123456789") + source := []rune{} + if uletter { + source = append(source, uletters...) + } + if dletter { + source = append(source, dletters...) + } + if number { + source = append(source, numbers...) + } + if len(source) == 0 { + return "atLeastContainsLetterOrNumber" + } + b := make([]rune, length) + for i := range b { + b[i] = source[rand.Intn(len(source))] + } + return prefix + string(b) +} + +// 跟现有环境一致,格式:aafc4d1b-f696-4ec2-924f-6fd012aa8345 +func GenerateRandUuid() string { + s := GetRandString("", 32, false, true, true) + runes := []rune(s) + return string(runes[0:8]) + "-" + string(runes[8:12]) + "-" + string(runes[12:16]) + "-" + string(runes[16:20]) + "-" + string(runes[20:32]) +} + +func Convert2String(val interface{}) (msg string, err error) { + + if val == nil{ + return "", nil + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool: + msg = strconv.FormatBool(val.(bool)) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + msg = fmt.Sprintf("%v", val) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + msg = fmt.Sprintf("%v", val) + case reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + msg = fmt.Sprintf("%v", val) + case reflect.String: + msg = val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + s, err := json.Marshal(val) + if err == nil { + msg = string(s) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + err = errors.New(fmt.Sprintf("type %s not support convert to string", reflect.TypeOf(val).String())) + default: + err = errors.New(fmt.Sprintf("type %s not support convert to string", reflect.TypeOf(val).String())) + } + return +} diff --git a/bmp-scheduler/bmp_vendor/log/README.md b/bmp-scheduler/bmp_vendor/log/README.md new file mode 100644 index 0000000..f39a094 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/log/README.md @@ -0,0 +1,6 @@ +精简日志库,用于打点统计,监控,告警等场景 +- WARN,FATAL等等级的日志即时打印落盘 + - 一个流量可以打印多条WARN,FATAL日志 +- INFO,DEBUG等级的日志,一个流量只落一条日志 + - 支持字段顺序自定义,便于正则匹配做监控等场景 + - 支持自定义代码段耗时打印,便于后续性能统计分析 diff --git a/bmp-scheduler/bmp_vendor/log/go.mod b/bmp-scheduler/bmp_vendor/log/go.mod new file mode 100644 index 0000000..83d5129 --- /dev/null +++ b/bmp-scheduler/bmp_vendor/log/go.mod @@ -0,0 +1,3 @@ +module git.jd.com/cps-golang/log + +go 1.17 diff --git a/bmp-scheduler/bmp_vendor/log/log.go b/bmp-scheduler/bmp_vendor/log/log.go new file mode 100644 index 0000000..6e5b79c --- /dev/null +++ b/bmp-scheduler/bmp_vendor/log/log.go @@ -0,0 +1,249 @@ +package cps_log + +import ( + "encoding/json" + "fmt" + "io" + "log" + "os" + "reflect" + "strings" + "time" +) + +// Level type +type Level uint32 + +const ( + // TraceLevel level. Designates finer-grained informational events than the Debug. + TraceLevel Level = iota + // DebugLevel level. Usually only enabled when debugging. Very verbose logging. + DebugLevel + // InfoLevel level. General operational entries about what's going on inside the + // application. + InfoLevel + // WarnLevel level. Non-critical entries that deserve eyes. + WarnLevel + // ErrorLevel level. Logs. Used for errors that should definitely be noted. + // Commonly used for hooks to send errors to an error tracking service. + ErrorLevel + // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the + // logging level is set to Panic. + FatalLevel + // PanicLevel level, highest level of severity. Logs and then calls panic with the + // message passed to Debug, Info, ... + PanicLevel +) + +var globalDefinedKeys = []string{"time", "logid", "self_t", "all_t"} + +type Logger struct { + data map[string]interface{} + level Level + fileName string + definedKeys []string +} + +func New(filename string) *Logger { + if filename == "" { + log.Fatal("filename must be provided !!!") + return nil + } + l := &Logger{ + data: make(map[string]interface{}), + fileName: filename, + } + l.definedKeys = append([]string{}, globalDefinedKeys...) + l.data["time"] = time.Now().Format("2006-01-02T15:04:05") + return l +} + +func NewLoggerWithConfig(filename string, level Level, definedKeys []string) *Logger { + l := New(filename) + l.SetLevel(level) + l.SetStableFields(definedKeys) + return l +} + +func (l *Logger) SetLevel(level Level) { + l.level = level +} + +//SetStableFields 需要固定每条日志的字段时,通过此接口设置,global在前,userdefined在后 +func (l *Logger) SetStableFields(fields []string) { + l.definedKeys = append(l.definedKeys, fields...) +} + +func (l *Logger) Point(key string, val interface{}) { + l.data[key] = val +} + +func (l *Logger) GetPoint(key string) interface{} { + return l.data[key] +} + +func (l *Logger) TimeStart(key string) { + if _, ok := l.data[key]; ok { + log.Print(fmt.Sprintf("point %s TimeStart more than once, check !!!", key)) + } + l.data[key] = time.Now() + +} + +func (l *Logger) TimeEnd(key string) { + if t, ok := l.data[key]; ok { + v := time.Now().Sub(t.(time.Time)).Milliseconds() + l.data[key] = fmt.Sprintf("%f", float64(v)/1000.0) + } else { + log.Print(fmt.Sprintf("missing call TimeStart before TimeEnd when point %s, check it!!!", key)) + } + +} + +func (l *Logger) PushPoint(key string, val interface{}) { + if _, ok := l.data[key]; !ok { + l.data[key] = []interface{}{} + } + d := l.data[key].([]interface{}) + d = append(d, val) +} + +func (l *Logger) Info(v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Infof(format string, v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warn(v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warnf(format string, v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatal(v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatalf(format string, v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Flush() { + if l.level > DebugLevel { + return + } + var beforeStr, afterStr string + for _, key := range l.definedKeys { + if val, ok := l.data[key]; ok { + if key == "time" { + beforeStr = val.(string) + continue + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + beforeStr = beforeStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + beforeStr = beforeStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + beforeStr = beforeStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Printf("val for %s unknown type!!!", key)) + + } + } + } + for key, val := range l.data { + if exist, _ := inArray(key, l.definedKeys); !exist { + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + afterStr = afterStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + afterStr = afterStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + afterStr = afterStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Sprintf("val for %s unknown type!!!", key)) + } + } + } + + line := strings.TrimSpace(beforeStr) + " " + strings.TrimSpace(afterStr) + "\r\n" + filename := fmt.Sprintf("%s.DEBUG", l.fileName) + WriteFile(filename, line) +} + +func WriteFile(filename, line string) { + TimeStamp := time.Now() + str := filename + "." + TimeStamp.Format("2006-01-02") + logf, err := os.OpenFile(str, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + if err != nil { + log.Fatal("open filename error:", err.Error()) + } + defer logf.Close() + if _, err := io.WriteString(logf, line); err != nil { + log.Fatal("write line error:", err.Error()) + } +} + +func inArray(val interface{}, array interface{}) (exists bool, index int) { + exists = false + index = -1 + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + index = i + exists = true + return + } + } + } + return +} diff --git a/bmp-scheduler/build.sh b/bmp-scheduler/build.sh new file mode 100644 index 0000000..e89c406 --- /dev/null +++ b/bmp-scheduler/build.sh @@ -0,0 +1,124 @@ +#!/bin/bash +############################################################################### +#编译脚本的原理是将编译结果放到output目录中,这个样例模版提供一个产生 +#一个最基本golang运行程序包的编译脚本,对于特殊的需求请酌情考虑 +# +#1、该脚本支持参数化,参数将传入build_package函数(内容为最终执行的编译命令) +# ,用$1,$2....表示,第1,2...个参数 +#2、部署需要启动程序,所以需要提供control文件放在当前目录中,用于启动和 +# 监控程序状态 + +###############用户修改部分################ +readonly PROJECT_NAME="ironic-scheduler" #项目名称,相对于$GOPATH/src文件夹所在的目录,可选项 +readonly PACKAGE_DIR_NAME=main.go #main文件相对于src文件夹所在的目录,可选项 +readonly PACKAGE_BIN_NAME=ironic-scheduler #定义产出的运行程序名,必填项 +readonly CONF_DIR_NAME="conf" #定义配置文件目录,此路径为相对路径,可选项 +readonly OTHERS_DIR_NAME="" #定义其它文件目录,多个目录以空格区分,此路径为相对路径,可选项 +#最终的抽包路径为$OUTPUT +########################################### + +if [[ "${PACKAGE_BIN_NAME}" == "" ]];then + echo "Please set "PACKAGE_BIN_NAME" value" + exit 1 +fi + +function set_work_dir +{ + readonly OUTPUT=$(pwd)/output + readonly WORKSPACE_DIR=$(pwd) +} + +#清理编译构建目录操作 +function clean_before_build +{ + cd ${WORKSPACE_DIR} + rm -rf bin pkg + rm -rf ${OUTPUT} +} + +#初始化编译环境 +function prepare_package() +{ + if [ ! -z "$PROJECT_NAME" ];then + mkdir -p src/$PROJECT_NAME + copy_files=`ls |grep -vw 'src'` + cp -rf $copy_files src/$PROJECT_NAME/ + fi +} + +#实际的编译命令 +#这个函数中可使用$1,$2...获取第1,2...个参数 +function build_package() +{ + cd ${WORKSPACE_DIR} + # export GOPATH=$(pwd) + go clean + echo $(pwd) + echo $(ls) + go build -v -gcflags="-N -l" -o ${PACKAGE_BIN_NAME} ${PACKAGE_DIR_NAME} || return 1 +} + +#建立最终发布的目录 +function build_dir +{ + mkdir -p ${OUTPUT}/bin || return 1 +} + +function dir_not_empty() +{ + if [[ ! -d $1 ]];then + return 1 + fi + if [[ $(ls $1|wc -l) -eq 0 ]];then + return 1 + fi + return 0 +} + +#拷贝编译结果到发布的目录 +function copy_result +{ + cd ${WORKSPACE_DIR} + cp -r ${PACKAGE_BIN_NAME} ${OUTPUT}/bin/ || return 1 + cp -r ./control ${OUTPUT}/bin || return 1 + dir_not_empty ${WORKSPACE_DIR}/${CONF_DIR_NAME} && mkdir -p ${OUTPUT}/${CONF_DIR_NAME} + cp -rf ./${CONF_DIR_NAME}/* ${OUTPUT}/${CONF_DIR_NAME}/ + test -z "$OTHERS_DIR_NAME" || cp -rf $OTHERS_DIR_NAME ${OUTPUT}/ + return 0 +} + +#执行 +function main() +{ + cd $(dirname $0) + set_work_dir + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Cleaning...' + clean_before_build || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Clean completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'preparng...' + prepare_package || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'prepare completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Building...' + build_package $@ || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Build completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Making dir...' + build_dir || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Make completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy result to publish dir...' + copy_result || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy completed' + echo + + exit 0 +} + +main $@ diff --git a/bmp-scheduler/conf/app.conf b/bmp-scheduler/conf/app.conf new file mode 100644 index 0000000..e69de29 diff --git a/bmp-scheduler/conf/bmp-scheduler-test.ini b/bmp-scheduler/conf/bmp-scheduler-test.ini new file mode 100644 index 0000000..07e2b63 --- /dev/null +++ b/bmp-scheduler/conf/bmp-scheduler-test.ini @@ -0,0 +1,41 @@ +runmode = "test" +[test] + +# httpport = 8801 +# mysql +jdbc.url= +bmp_db_host=${BMP_DB_HOST||10.226.192.72} +bmp_db_port=${BMP_DB_PORT||13306} +bmp_db_user=${BMP_DB_USER||bmp_rw} +bmp_db_password=${BMP_DB_PASSWORD||LE&oN$9wHB} +bmp_db_name=${BMP_DB_NAME||bmp} + +bmp_redis_host=${BMP_REDIS_HOST||10.226.192.72} +bmp_redis_port=${BMP_REDIS_PORT||16379} +bmp_redis_password=${BMP_REDIS_PASSWORD||LE&oN$9wHB} + + +# RabbitMQ for Ironic +bmp_mq_host=${BMP_MQ_HOST||10.226.192.72} +bmp_mq_port=${BMP_MQ_PORT||15672} +bmp_mq_user=${BMP_MQ_USER||bmp} +bmp_mq_password=${BMP_MQ_PASSWORD||LE&oN$9wHB} +bmp_mq_vhost=${BMP_MQ_VHOST||/bmp} +bmp_mq_exchange=CPS_IRONIC_SCHEDULER +bmp_mq_receive_routing_key=/test + + +sdn.configs.nameservers=114.114.114.114,8.8.8.8 + + +# mail +mail.server.host= +mail.server.port=25 +mail.server.protocol=smtp +mail.server.email= +mail.server.username=cps_bs +mail.server.password="" +mail.smtp.auth=true + + + diff --git a/bmp-scheduler/conf/bmp-scheduler.ini b/bmp-scheduler/conf/bmp-scheduler.ini new file mode 100644 index 0000000..10b4eea --- /dev/null +++ b/bmp-scheduler/conf/bmp-scheduler.ini @@ -0,0 +1,34 @@ +appname = bmp-scheduler +autorender = false +copyrequestbody = true +EnableDocs = true + +# mysql +bmp_db_host=${BMP_DB_HOST} +bmp_db_port=${BMP_DB_PORT} +bmp_db_user=${BMP_DB_USER} +bmp_db_password=${BMP_DB_PASSWORD} +bmp_db_name=${BMP_DB_NAME} + +bmp_redis_host=${BMP_REDIS_HOST} +bmp_redis_port=${BMP_REDIS_PORT} +bmp_redis_password=${BMP_REDIS_PASSWORD} + + +# RabbitMQ for Ironic +bmp_mq_host=${BMP_MQ_HOST} +bmp_mq_port=${BMP_MQ_PORT} +bmp_mq_user=${BMP_MQ_USER} +bmp_mq_password=${BMP_MQ_PASSWORD} +bmp_mq_vhost=${BMP_MQ_VHOST} +bmp_mq_exchange=CPS_IRONIC_SCHEDULER +bmp_mq_receive_routing_key=/test + +# log +log.level=DEBUG +log.max.history=10 +log.path=/var/log/bmp/bmp-scheduler + +#如果在本地环境测试,启用下面的文件,改成自己的本地环境配置 +#include "bmp-scheduler-test.ini" + diff --git a/bmp-scheduler/control b/bmp-scheduler/control new file mode 100644 index 0000000..74f81c3 --- /dev/null +++ b/bmp-scheduler/control @@ -0,0 +1,126 @@ +#!/bin/bash +set -x +cd "$(dirname $0)"/.. +BASE_DIR=`pwd` +if [ -f default_env.sh ];then + source default_env.sh +fi + +PROC_NAME=ironic-scheduler # 进程名 一般就是二进制的名字java类程序一般就是java +# PROC_PORT=10012 # 程序占用的端口,建议写,程序不占用端口的话只用ps来判断进程是否启动,机器上有同名程序是可能有问题 +WAIT_TIME=60 # 执行START_COMMAND后到程序能完全启动listen端口需要花的时间 +TMP=ironic-schedule + +USER=nginx +app_dir=/home/$USER/$PROC_NAME +mkdir -p $app_dir/log + +START_COMMAND="$app_dir/bin/ironic-scheduler -c $app_dir/conf/ironic-scheduler.ini" #在output目录下启动你程序的命令 + +help(){ + echo "${0} " + exit 1 +} + +checkhealth(){ + if [[ -n "$PROC_PORT" ]] ; then + PORT_PROC=$(/usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d |awk '{print $NF}' |grep -oP '".*"' |sed "s/\"//g" |uniq) + if [ X"$PORT_PROC" = X"$PROC_NAME" ] ; then + echo "1 running" + return 0 + fi + echo "1 not running" + return 1 + else + ps -eo comm,pid|grep -P "$TMP" + if [ "$?" = 0 ] ; then + echo "2 running" + return 0 + fi + echo "2 not running" + return 1 + fi +} + + +start(){ + checkhealth + if [ $? = 0 ]; then + echo "[WARN] $PROC_NAME is aleady running!" + return 0 + fi + + [ -d "$app_dir" ] && cd $app_dir && rm -rf `ls ${app_dir} | grep -v log` + cp -r $BASE_DIR/* ${app_dir}/ + chown -R $USER:$USER ${app_dir} + su $USER -c "nohup $START_COMMAND > ${app_dir}/logs/cps-ironic-api.log 2>&1 &" + + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ $? = 0 ]; then + echo "Start $PROC_NAME success" + return 0 + fi + done + echo "[ERROR] Start $PROC_NAME failed" + return 1 +} + +stop(){ + if [[ -n "$PROC_PORT" ]] ; then + PROC_ID=$( /usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d | awk '{print $NF}' | grep -oP ',.*,' | grep -oP "\d+" | uniq ) + else + PROC_ID=$(ps -eo comm,pid | grep "^$PROC_NAME" |awk '{print $2}') + fi + + if [[ -z "$PROC_ID" ]] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + + checkhealth + if [ "$?" != "0" ] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + kill $PROC_ID + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + done + + kill -9 $PROC_ID + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + + echo "[ERROR] Stop $PROC_NAME failed" + return 1 +} + +case "${1}" in + start) + start + ;; + stop) + stop + ;; + status|health|checkhealth) + checkhealth + ;; + restart) + stop && start + ;; + *) + help + ;; +esac + diff --git a/bmp-scheduler/dao/auditLogsDao/auditLogsDao.go b/bmp-scheduler/dao/auditLogsDao/auditLogsDao.go new file mode 100644 index 0000000..688edbf --- /dev/null +++ b/bmp-scheduler/dao/auditLogsDao/auditLogsDao.go @@ -0,0 +1,153 @@ +package auditLogsDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// 操作日志 +type AuditLogs struct { + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + Logid string `gorm:"column:logid;type:varchar(255);not null" json:"logid"` // log uuid + Sn string `gorm:"index:i_sn;column:sn;type:varchar(255);not null" json:"sn"` + DeviceID string `gorm:"index:i_device_id;column:device_id;type:varchar(255);not null" json:"device_id"` + InstanceID string `gorm:"index:i_instance_id;column:instance_id;type:varchar(255);not null" json:"instance_id"` + Operation string `gorm:"index:i_operation;column:operation;type:varchar(255);not null" json:"operation"` // action + OperateUserID string `gorm:"column:operate_user_id;type:varchar(255);not null" json:"operate_user_id"` // user_id + OperateUserName string `gorm:"column:operate_user_name;type:varchar(255);not null" json:"operate_user_name"` // user_name + Result string `gorm:"column:result;type:varchar(255);not null" json:"result"` // success/fail + FailReason string `gorm:"column:fail_reason;type:varchar(255);not null" json:"fail_reason"` // reason for fail // 完成时间戳 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 +} + +//var db *gorm.DB = dao.IronicRdb + +func (t *AuditLogs) TableName() string { + return "audit_logs" +} + +// AddCommand insert a new Command into database and returns +// last inserted Id on success. +func AddAuditLogs(logger *log.Logger, m *AuditLogs) (id int64, err error) { + m.CreatedTime = int(time.Now().Unix()) + m.UpdatedTime = int(time.Now().Unix()) + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetCommandById retrieves Command by Id. Returns error if +// Id doesn't exist +func GetAuditLogsById(logger *log.Logger, id int64) (v *AuditLogs, err error) { + v = &AuditLogs{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetCommandById retrieves Command by parentId. Returns error if +// Id doesn't exist +// GetCommandById retrieves Command by parentId. Returns error if +// Id doesn't exist +func GetAuditLogsByUUId(logger *log.Logger, uuid string) (v *AuditLogs, err error) { + v = &AuditLogs{} + err = dao.Where(logger, dao.IronicRdb, "logid = ? and is_del = 0", uuid).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetAuditLogsCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + db, err := dao.WhereBuild(dao.Model(logger, dao.IronicRdb, AuditLogs{}), query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} + +func GetAllAuditLogs(logger *log.Logger, query map[string]interface{}) (ml []*AuditLogs, err error) { + g := dao.Model(logger, dao.IronicRdb, AuditLogs{}) + g, err = dao.WhereBuild(g, query) + if err != nil { + return nil, err + } + err = g.Find(&ml).Error + return + +} + +// GetMultiCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetMultiAuditLogs(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*AuditLogs, err error) { + + var db = dao.Model(logger, dao.IronicRdb, AuditLogs{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetOneAuditLogs(logger *log.Logger, query map[string]interface{}) (l *AuditLogs, err error) { + l = &AuditLogs{} + var db = dao.Model(logger, dao.IronicRdb, AuditLogs{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetOneUnfinishedAuditLogs(logger *log.Logger, sn, instanceId, operation string) (l *AuditLogs, err error) { + v := &AuditLogs{} + err = dao.Where(logger, dao.IronicRdb, "is_del = 0 and instance_id = ? and sn = ? and operation = ? and is_del = 0 and result = 'doing'", instanceId, sn, operation).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// UpdateCommand updates Command by Id and returns error if +// the record to be updated doesn't exist +func UpdateAuditLogsById(logger *log.Logger, m *AuditLogs) (err error) { + + m.UpdatedTime = int(time.Now().Unix()) + err = dao.Model(logger, dao.IronicWdb, AuditLogs{}).Where("id = ?", m.ID).Updates(m).Error + return +} + +func UpdateMultiAuditLogs(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, AuditLogs{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} diff --git a/bmp-scheduler/dao/baseDao.go b/bmp-scheduler/dao/baseDao.go new file mode 100644 index 0000000..90ca311 --- /dev/null +++ b/bmp-scheduler/dao/baseDao.go @@ -0,0 +1,159 @@ +package dao + +import ( + "fmt" + "reflect" + "strings" + "time" + + beego "github.com/beego/beego/v2/server/web" + + clog "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +var ( + IronicRdb *gorm.DB + IronicWdb *gorm.DB +) + +type gLogger struct { + traceid string +} + +func (g *gLogger) Print(values ...interface{}) { + var ( + level = values[0] + // source = values[1] + ) + logPath, _ := beego.AppConfig.String("log.path") + logger := clog.New(logPath + "/bmp-scheduler-sql.log") + defer logger.Flush() + logger.SetStableFields([]string{"sql", "args", "cost"}) + logger.Point("logid", g.traceid) + + if level == "sql" { + logger.Point("sql", values[3]) + logger.Point("args", values[4]) + logger.Point("cost", fmt.Sprint(values[2])) + } else { + logger.Point("trace", values) + } +} + +func InitGormDb(conn string) { + + doInit(conn) + //初始化时没有完成的,择机完成初始化 + go func() { + for { + time.Sleep(10 * time.Second) + if IronicRdb != nil && IronicRdb.DB().Stats().OpenConnections == 0 { + fmt.Println(time.Now().String(), "IronicRdb reInit......") + doInitIronicRdb(conn) + } + if IronicWdb != nil && IronicWdb.DB().Stats().OpenConnections == 0 { + fmt.Println(time.Now().String(), "IronicWdb reInit......") + doInitIronicWdb(conn) + } + } + }() + +} + +func doInit(conn string) { + doInitIronicRdb(conn) + doInitIronicWdb(conn) +} + +func doInitIronicRdb(conn string) { + var err error + IronicRdb, err = gorm.Open("mysql", conn) + if err != nil { + fmt.Println(time.Now(), "IronicRdb init error:", err.Error()) + return + } + IronicRdb.LogMode(true) + IronicRdb.DB().SetMaxOpenConns(100) + IronicRdb.DB().SetMaxIdleConns(20) +} + +func doInitIronicWdb(conn string) { + var err error + IronicWdb, err = gorm.Open("mysql", conn) + if err != nil { + fmt.Println(time.Now(), "IronicWdb init error:", err.Error()) + return + } + IronicWdb.LogMode(true) + IronicWdb.DB().SetMaxOpenConns(100) + IronicWdb.DB().SetMaxIdleConns(20) +} + +func GetGormTx(logger *clog.Logger) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := IronicWdb.New() + db.SetLogger(gl) + return db +} + +type NullType byte + +const ( + _ NullType = iota + // IsNull the same as `is null` + IsNull + // IsNotNull the same as `is not null` + IsNotNull +) + +// sql build where +func WhereBuild(g *gorm.DB, query map[string]interface{}) (*gorm.DB, error) { + + for k, v := range query { + if reflect.TypeOf(v).Kind() == reflect.String { + if v.(string) == "" { + continue + } + } + ks := strings.Split(k, ".") + if len(ks) > 2 { + fmt.Println(time.Now(), fmt.Errorf("Error in query condition: %s. ", k)) + return g, fmt.Errorf("Error in query condition: %s. ", k) + } + switch len(ks) { + case 1: + g = g.Where(fmt.Sprintf("%s = ?", k), v) + break + case 2: + k = ks[0] + switch ks[1] { + case "=": + g = g.Where(fmt.Sprintf("%s = ?", k), v) + break + case ">", "gt": + g = g.Where(fmt.Sprintf("%s > ?", k), v) + case ">=", "gte": + g = g.Where(fmt.Sprintf("%s >= ?", k), v) + break + case "<", "lt": + g = g.Where(fmt.Sprintf("%s < ?", k), v) + break + case "<=", "lte": + g = g.Where(fmt.Sprintf("%s <= ?", k), v) + break + case "!=", "<>": + g = g.Where(fmt.Sprintf("%s <> ?", k), v) + break + case "in": + g = g.Where(fmt.Sprintf("%s IN (?)", k), v) + break + case "like": + g = g.Where(fmt.Sprintf("%s LIKE ?", k), v) + break + } + break + } + } + return g, nil +} diff --git a/bmp-scheduler/dao/commandDao/CommandDao.go b/bmp-scheduler/dao/commandDao/CommandDao.go new file mode 100644 index 0000000..da55951 --- /dev/null +++ b/bmp-scheduler/dao/commandDao/CommandDao.go @@ -0,0 +1,181 @@ +package commandDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// Command 指令 +type Command struct { + ID int `gorm:"primaryKey;column:id" json:"-"` // ID + RequestID string `gorm:"column:request_id" json:"requestId"` // 请求ID + Sn string `gorm:"column:sn" json:"sn"` // 设备SN + InstanceID string `gorm:"column:instance_id" json:"instanceId"` // 实例Id + Action string `gorm:"column:action" json:"action"` // 操作 + Type string `gorm:"column:type" json:"type"` // 操作类型:agent, driver, network + Status string `gorm:"column:status" json:"status"` // 状态: wait,running,finish,error + ParentCommandID int64 `gorm:"column:parent_command_id" json:"parentCommandId"` // 父指令Id + ExecuteCount int `gorm:"column:execute_count" json:"executeCount"` // 执行次数 + TimeoutTime time.Time `gorm:"column:timeout_time" json:"timeoutTime"` // timeout time + TimeoutPolicy string `gorm:"column:timeout_policy" json:"timeoutPolicy"` // timeout policy + Task string `gorm:"column:task" json:"task"` // 任务名称 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +//var db *gorm.DB = dao.IronicRdb + +func (t *Command) TableName() string { + return "command" +} + +// AddCommand insert a new Command into database and returns +// last inserted Id on success. +func AddCommand(logger *log.Logger, m *Command) (id int64, err error) { + m.CreatedTime = int(time.Now().Unix()) + m.UpdatedTime = int(time.Now().Unix()) + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetCommandById retrieves Command by Id. Returns error if +// Id doesn't exist +func GetCommandById(logger *log.Logger, id int64) (v *Command, err error) { + v = &Command{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetCommandById retrieves Command by parentId. Returns error if +// Id doesn't exist +// GetCommandById retrieves Command by parentId. Returns error if +// Id doesn't exist +func GetCommandByParentId(logger *log.Logger, parentId int64) (v *Command, err error) { + v = &Command{} + err = dao.Where(logger, dao.IronicRdb, "parent_command_id = ? and is_del = 0", parentId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetCommandCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + db, err := dao.WhereBuild(dao.Model(logger, dao.IronicRdb, Command{}), query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} + +func GetAllCommand(logger *log.Logger, query map[string]interface{}) (ml []*Command, err error) { + g := dao.Model(logger, dao.IronicRdb, Command{}) + g, err = dao.WhereBuild(g, query) + if err != nil { + return nil, err + } + err = g.Find(&ml).Error + return + +} + +// GetMultiCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetMultiCommand(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Command, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Command{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetOneCommand(logger *log.Logger, query map[string]interface{}) (l *Command, err error) { + l = &Command{} + var db = dao.Model(logger, dao.IronicRdb, Command{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// UpdateCommand updates Command by Id and returns error if +// the record to be updated doesn't exist +func UpdateCommandById(logger *log.Logger, m *Command) (err error) { + + m.UpdatedTime = int(time.Now().Unix()) + err = dao.Model(logger, dao.IronicWdb, Command{}).Where("id = ?", m.ID).Updates(m).Error + return +} + +func CountBySnAndStatus(logger *log.Logger, sn, status string) (int64, error) { + param := map[string]interface{}{ + "sn": sn, + "status": status, + "is_del": 0, + } + return GetCommandCount(logger, param) +} + +func GetFirstCommand(logger *log.Logger, query map[string]interface{}) (l *Command, err error) { + l = &Command{} + var db = dao.Model(logger, dao.IronicRdb, Command{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Order("id asc").Limit(1).Offset(0).Take(l).Error + if err != nil { + return nil, err + } + return l, nil + +} + +func QueryBySnAndStatus(logger *log.Logger, sn, status string) ([]*Command, error) { + param := map[string]interface{}{ + "sn": sn, + "status": status, + "is_del": 0, + } + return GetMultiCommand(logger, param, nil, []string{"id"}, []string{"asc"}, 0, 0) +} + +func UpdateMultiCommands(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, Command{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} diff --git a/bmp-scheduler/dao/createDao.go b/bmp-scheduler/dao/createDao.go new file mode 100644 index 0000000..944c2f8 --- /dev/null +++ b/bmp-scheduler/dao/createDao.go @@ -0,0 +1,36 @@ +package dao + +import ( + clog "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +// 插入单条记录,v2版本才支持插入多条记录? +//eg. db.Create(logger, rdb, u) +func Create(logger *clog.Logger, gdb *gorm.DB, out interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Create(out) +} + +//插入并获取刚插入数据的自增Id +//eg. db.CreateAndGetId(logger, rdb, u) +func CreateAndGetId(logger *clog.Logger, gdb *gorm.DB, out interface{}) (int64, error) { + // 事务约束,否则并发下可能获取到的是错误的id + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + tx := db.Begin() + if err := tx.Create(out).Error; err != nil { + tx.Rollback() + return 0, err + } + var id []int64 + if err := tx.Raw("select LAST_INSERT_ID() as id").Pluck("id", &id).Error; err != nil { + tx.Rollback() + return 0, err + } + tx.Commit() + return id[0], nil +} diff --git a/bmp-scheduler/dao/deleteDao.go b/bmp-scheduler/dao/deleteDao.go new file mode 100644 index 0000000..43e5850 --- /dev/null +++ b/bmp-scheduler/dao/deleteDao.go @@ -0,0 +1,21 @@ +package dao + +import ( + clog "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +//删除记录 +//eg1.根据模型删除 +/* +food := Food{} +dao.Where(logger, rdb, "id = ?", 2).Take(&food).Delete(&food) +*/ +//eg2.根据Where条件删除数据 +// dao.Where(logger, rdb, "type = ?", 5).Delete(&Food{})//注意这里Delete函数需要传递一个空的模型变量指针 +func Delete(logger *clog.Logger, gdb *gorm.DB, value interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Delete(value, where...) +} diff --git a/bmp-scheduler/dao/deviceDao/deviceDao.go b/bmp-scheduler/dao/deviceDao/deviceDao.go new file mode 100644 index 0000000..c0f2b7c --- /dev/null +++ b/bmp-scheduler/dao/deviceDao/deviceDao.go @@ -0,0 +1,298 @@ +package deviceDao + +import ( + "fmt" + "strconv" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +type Device struct { + ID int `gorm:"primaryKey;column:id" json:"-"` // 设备ID编号 + Sn string `gorm:"column:sn" json:"sn"` // 设备SN + DeviceID string `gorm:"column:device_id" json:"deviceId"` // 设备uuid + InstanceID string `gorm:"column:instance_id" json:"instanceId"` // 实例id + IDcID string `gorm:"column:idc_id" json:"idcId"` // 机型uuid + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型uuid + ManageStatus string `gorm:"column:manage_status" json:"manageStatus"` // 设备状态: 未装机,已装机 + Brand string `gorm:"column:brand" json:"brand"` // 品牌 + Model string `gorm:"column:model" json:"model"` // 型号 + Reason string `gorm:"column:reason" json:"reason"` // 设备状态变更失败原因 + Cabinet string `gorm:"column:cabinet" json:"cabinet"` // 机柜编码 + UPosition string `gorm:"column:u_position" json:"uPosition"` // U位 + IloIP string `gorm:"column:ilo_ip" json:"iloIp"` // 带外管理IP + IloUser string `gorm:"column:ilo_user" json:"iloUser"` // 带外账号 + IloPassword string `gorm:"column:ilo_password" json:"iloPassword"` // 带外账号密码 + Mac1 string `gorm:"column:mac1" json:"mac1"` // MAC1(eth0) + Mac2 string `gorm:"column:mac2" json:"mac2"` // MAC2(eth2) + SwitchIP1 string `gorm:"column:switch_ip1" json:"switchIp1"` // 交换机1ip + SwitchPort1 string `gorm:"column:switch_port1" json:"switchPort1"` // 交换机1port + SwitchIP2 string `gorm:"column:switch_ip2" json:"switchIp2"` // 交换机2ip + SwitchPort2 string `gorm:"column:switch_port2" json:"switchPort2"` // 交换机2port + SwitchUser1 string `gorm:"column:switch_user1" json:"switchUser1"` // 交换机1登录账号,如果为空,取所在机房的值 + SwitchPassword1 string `gorm:"column:switch_password1" json:"switchPassword1"` // 交换机1登录密码 + SwitchUser2 string `gorm:"column:switch_user2" json:"switchUser2"` // 交换机2登录账号,如果为空,取所在机房的值 + SwitchPassword2 string `gorm:"column:switch_password2" json:"switchPassword2"` // 交换机2登录密码 + Description string `gorm:"column:description" json:"description"` // 描述 + SwitchIP string `gorm:"column:switch_ip" json:"switchIp"` // 网口交换机IP + Mask string `gorm:"column:mask" json:"mask"` // 子网掩码 + MaskEth1 string `gorm:"column:mask_eth1" json:"mask_eth1"` // eth1子网掩码 + Gateway string `gorm:"column:gateway" json:"gateway"` // 网关地址 + PrivateIPv4 string `gorm:"column:private_ipv4" json:"privateIpv4"` // 内网IPV4 + PrivateEth1IPv4 string `gorm:"column:private_eth1_ipv4" json:"privateEth1Ipv4"` // eth1内网IPV4 + PrivateIPv6 string `gorm:"column:private_ipv6" json:"privateIpv6"` // 内网IPV6 + PrivateEth1IPv6 string `gorm:"column:private_eth1_ipv6" json:"privateEth1Ipv6"` // eth1内网IPV6 + Gateway6 string `gorm:"column:gateway6" json:"gateway6"` // 内网IPV6网关 + AdapterID int `gorm:"column:adapter_id" json:"adapterId"` // adapter_id + RaidDriver string `gorm:"column:raid_driver" json:"raidDriver"` // raid工具:(megacli64等) + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 + CurrentBootMode string `gorm:"column:current_boot_mode" json:"currentBootMode"` // 当前启动方式 + // "1"表示已采集,"2"表示未采集. "3"表示采集中,4表示采集失败 + CollectStatus string `gorm:"column:collect_status" json:"collectStatus"` + //采集失败原因 + CollectFailReason string `gorm:"column:collect_fail_reason" json:"collectFailReason"` + Architecture string `gorm:"column:architecture" json:"architecture"` // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + +} + +func (t *Device) TableName() string { + return "device" +} + +func GetBySn(logger *log.Logger, sn string) (v *Device, err error) { + v = &Device{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and is_del = 0", sn).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetOneDevice(logger *log.Logger, query map[string]interface{}) (l *Device, err error) { + l = &Device{} + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetDeviceCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} + +// AddDevice insert a new Device into database and returns +// last inserted Id on success. +func AddDevice(logger *log.Logger, m *Device) (id int64, err error) { + + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// AddDevice insert a new Device into database and returns +// last inserted Id on success. +func AddMultiDevice(logger *log.Logger, m []*Device) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, device := range m { + + if err := tx.Create(device).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetDeviceById retrieves Device by Id. Returns error if +// Id doesn't exist +func GetDeviceById(logger *log.Logger, deviceId string) (v *Device, err error) { + v = &Device{} + err = dao.Where(logger, dao.IronicRdb, "device_id = ? and is_del = 0", deviceId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetDeviceBySn retrieves Device by Sn. Returns error if +// Sn doesn't exist +func GetDeviceBySn(logger *log.Logger, sn string) (v *Device, err error) { + v = &Device{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and is_del = 0", sn).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetMultiDevice retrieves all Device matches certain condition. Returns empty list if +// no records exist +func GetMultiDevice(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Device, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// GetMultiDevice retrieves all Device matches certain condition. Returns empty list if +// no records exist +func GetAllDevice(logger *log.Logger, query map[string]interface{}) (ml []*Device, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetSingleDevice(logger *log.Logger, query map[string]interface{}) (l *Device, err error) { + l = &Device{} + var db = dao.Model(logger, dao.IronicRdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func UpdateMultiDevices(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["update_time"] = time.Now() + var db = dao.Model(logger, dao.IronicWdb, Device{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +// UpdateDevice updates Device by Id and returns error if +// the record to be updated doesn't exist +func UpdateDeviceById(logger *log.Logger, m *Device) (err error) { + + return dao.Model(logger, dao.IronicWdb, Device{}).Where("id = ?", m.ID).Updates(m).Error +} +func UpdateDeviceBySn(logger *log.Logger, m *Device) (err error) { + sql := `update device set manage_status="` + m.ManageStatus + `",reason="` + m.Reason + `" ,updated_time = ` + strconv.Itoa(int(time.Now().Unix())) + ` where sn="` + m.Sn + `" and is_del = 0` + err = dao.IronicWdb.Exec(sql).Error + fmt.Println("UpdateDeviceBySn err", err) + return + //return dao.Model(logger, dao.IronicWdb, Device{}).Where("sn=? and is_del=?", m.Sn, "0").Save(m).Error +} +func UpdateDeviceByInstanceId(logger *log.Logger, m *Device) (err error) { + sql := `update device set instance_id='',user_id = '',user_name = '',manage_status="` + m.ManageStatus + `",reason='' ,updated_time = ` + strconv.Itoa(int(time.Now().Unix())) + ` where instance_id="` + m.InstanceID + `" and is_del = 0` + err = dao.IronicWdb.Exec(sql).Error + // err = dao.Raw(logger, dao.IronicRdb, sql).Error + return + //return dao.Model(logger, dao.IronicWdb, Device{}).Where("sn=? and is_del=?", m.Sn, "0").Save(m).Error +} +func GetFirstVersionDeviceSns(logger *log.Logger) (sns []string, err error) { + sql := `select distinct d.sn from device d left join command c on d.sn = c.sn where d.is_del=0 and d.sale_status = 'sold' and d.region = 'cn-north-1' and d.az != 'cn-north-1c'` + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&sns).Error + return +} + +func GetFirstVersionAndReInstallDeviceSns(logger *log.Logger) (sns []string, err error) { + + sql := `select distinct d.sn from device d left join command c on d.sn = c.sn where d.is_del = 0 and d.sale_status = 'sold' and d.region = 'cn-north-1' and d.az != 'cn-north-1c' and c.action = 'WriteImage' and c.status = 'finish' and c.is_del = 0` + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&sns).Error + return +} + +type DeviceStock struct { + Total int64 `json:"total"` + Used int64 `json:"used"` + Available int64 `json:"available"` + Region string `json:"region"` + Az string `json:"az"` + DeviceType string `json:"device_type"` +} + +func GetDeviceStock(logger *log.Logger, device_type, region, az string) (ml []*DeviceStock, err error) { + + sql := `select region, az, device_type, count(id) as total, sum(if(sale_status = 'sold', 1, 0)) as used, sum(if(sale_status = 'selling', 1, 0)) as available from device where 1=1` + if region != "" { + sql = sql + fmt.Sprintf(" and region = '%s'", region) + } + if az != "" { + sql = sql + fmt.Sprintf(" and az = '%s'", az) + } + if device_type != "" { + sql = sql + fmt.Sprintf(" and device_type = '%s'", device_type) + } + sql = sql + " and is_del = 0 group by region,az,device_type" + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} + +type DDeviceIncludeSwitchIp struct { + *Device + SwitchIp string `json:"switch_ip"` +} + +func QueryIncludeSwitchIpByParam(logger *log.Logger, az, device_type, sale_status string) (ml []*DDeviceIncludeSwitchIp, err error) { + + sql := `select distinct switch_ip, d.* from device d left join interface i on d.sn = i.sn where 1=1` + if device_type != "" { + sql = sql + fmt.Sprintf(" and d.device_type = '%s'", device_type) + } + if az != "" { + sql = sql + fmt.Sprintf(" and d.az = '%s'", az) + } + if sale_status != "" { + sql = sql + fmt.Sprintf(" and d.sale_status = '%s'", sale_status) + } + sql = sql + ` and d.is_del = 0and i.is_del = 0` + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return + +} + +// description为空也有可能 +func UpdateDeviceAnywhere(logger *log.Logger, m *Device) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Device{}).Save(m).Error +} diff --git a/bmp-scheduler/dao/deviceHintsDao/deviceHintsDao.go b/bmp-scheduler/dao/deviceHintsDao/deviceHintsDao.go new file mode 100644 index 0000000..b416705 --- /dev/null +++ b/bmp-scheduler/dao/deviceHintsDao/deviceHintsDao.go @@ -0,0 +1,106 @@ +package deviceHintsDao + +import ( + "time" + + log "git.jd.com/cps-golang/log" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" +) + +// DeviceHints 根设备所在磁盘 +type DeviceHints struct { + ID int64 `gorm:"unique;column:id;type:bigint(20) unsigned;not null" json:"id"` // 设备ID编号 + + Sn string `gorm:"column:sn;type:varchar(64);not null" json:"sn"` // 设备SN + //volume UUID + VolumeId string `gorm:"column:volume_id;type:varchar(128)" json:"volume_id"` + VolumeType string `gorm:"column:volume_type" json:"volumeType"` // 卷类型:系统卷,数据卷 + Size int64 `gorm:"column:size;type:bigint(20);not null" json:"size"` // 以GiB为单位的设备尺寸 + Rotational int8 `gorm:"column:rotational;type:tinyint(4);not null" json:"rotational"` // 转动,可以区分HDDs(旋转-磁盘)和SSDs(非旋转-固态硬盘) + Wwn string `gorm:"column:wwn;type:varchar(128)" json:"wwn"` // 唯一的存储标识符 + Name string `gorm:"column:name;type:varchar(64);not null" json:"name"` // 设备名称,例如/dev/md0 + WwnVendorExtension string `gorm:"column:wwn_vendor_extension;type:varchar(64)" json:"wwn_vendor_extension"` // 唯一的供应商存储标识符 + WwnWithExtension string `gorm:"column:wwn_with_extension;type:varchar(64)" json:"wwn_with_extension"` // 带有供应商附加扩展的唯一的存储标识符 + Model string `gorm:"column:model;type:varchar(64)" json:"model"` // 设备标识符 + Serial string `gorm:"column:serial;type:varchar(64)" json:"serial"` // 磁盘序列号 + Hctl string `gorm:"column:hctl;type:varchar(64)" json:"hctl"` // SCSI地址(主机名、channel通道、Target和Lun) + ByPath string `gorm:"column:by_path;type:varchar(128)" json:"by_path"` // 磁盘by_path路径 + Vendor string `gorm:"column:vendor;type:varchar(64)" json:"vendor"` // 设备供应商 + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *DeviceHints) TableName() string { + return "device_hints" +} + +// AddDeviceHints insert a new DeviceHints into database and returns +// last inserted Id on success. +func AddDeviceHints(logger *log.Logger, m *DeviceHints) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetDeviceHintsById retrieves DeviceHints by Id. Returns error if +// Id doesn't exist +func GetDeviceHintsById(logger *log.Logger, id int) (v *DeviceHints, err error) { + v = &DeviceHints{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetSystemVolumnDeviceHintsBySn(logger *log.Logger, sn string) (v *DeviceHints, err error) { + v = &DeviceHints{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and volume_type = 'system' and is_del = 0", sn).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetDeviceHintsBySnAndVolumeId(logger *log.Logger, sn, volume_id string) (v *DeviceHints, err error) { + v = &DeviceHints{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and volume_id = ? and is_del = 0", sn, volume_id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllDeviceHints retrieves all DeviceHints matches certain condition. Returns empty list if +// no records exist +func GetAllDeviceHints(logger *log.Logger, query map[string]interface{}) (ml []*DeviceHints, err error) { + + var db = dao.Model(logger, dao.IronicRdb, DeviceHints{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// UpdateDeviceHintsById updates DeviceHints by Id and returns error if +// the record to be updated doesn't exist +func UpdateDeviceHintsById(logger *log.Logger, m *DeviceHints) (err error) { + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, DeviceHints{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateMultiDeviceHints(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["update_time"] = time.Now() + var db = dao.Model(logger, dao.IronicWdb, DeviceHints{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} diff --git a/bmp-scheduler/dao/deviceTypeDao/deviceTypeDao.go b/bmp-scheduler/dao/deviceTypeDao/deviceTypeDao.go new file mode 100644 index 0000000..77efd8f --- /dev/null +++ b/bmp-scheduler/dao/deviceTypeDao/deviceTypeDao.go @@ -0,0 +1,179 @@ +package deviceTypeDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +type DeviceType struct { + ID int `gorm:"primaryKey;column:id" json:"-"` // 主键 + IDcID string `gorm:"column:idc_id" json:"idcId"` // 机房id + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型uuid + Name string `gorm:"column:name" json:"name"` // 机型名称,如计算效能型,标准计算型 + DeviceType string `gorm:"column:device_type" json:"deviceType"` // 机型规格, cps.c.normal + DeviceSeries string `gorm:"column:device_series" json:"deviceSeries"` // 机型类型,如计算型,存储型 + Architecture string `gorm:"column:architecture" json:"architecture"` // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Height int `gorm:"column:height" json:"height"` // 【高度(U)】:显示机型高度 + Description string `gorm:"column:description" json:"description"` // 描述 + CPUAmount int8 `gorm:"column:cpu_amount" json:"cpuAmount"` // cpu数量 + CPUCores int8 `gorm:"column:cpu_cores" json:"cpuCores"` // 单个cpu内核数 + CPUManufacturer string `gorm:"column:cpu_manufacturer" json:"cpuManufacturer"` // cpu厂商 + CPUModel string `gorm:"column:cpu_model" json:"cpuModel"` // cpu处理器型号 + CPUFrequency string `gorm:"column:cpu_frequency" json:"cpuFrequency"` // cpu频率(G) + MemType string `gorm:"column:mem_type" json:"memType"` // 内存接口(如DDR3,DDR4) + MemSize int `gorm:"column:mem_size" json:"memSize"` // 单个内存大小(GB) + MemAmount int `gorm:"column:mem_amount" json:"memAmount"` // 内存数量 + MemFrequency int `gorm:"column:mem_frequency" json:"memFrequency"` // 内存主频(MHz) + NicAmount int8 `gorm:"column:nic_amount" json:"nicAmount"` // 网卡数量 + NicRate int `gorm:"column:nic_rate" json:"nicRate"` // 网卡传输速率(GE) + InterfaceMode string `gorm:"column:interface_mode" json:"interfaceMode"` // 【网口模式】【网络设置】: bond单网口,dual双网口 + SystemVolumeType string `gorm:"column:system_volume_type" json:"systemVolumeType"` // 系统盘类型(SSD,HDD) + SystemVolumeInterfaceType string `gorm:"column:system_volume_interface_type" json:"systemVolumeInterfaceType"` // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeSize int `gorm:"column:system_volume_size" json:"systemVolumeSize"` // 系统盘单盘大小 + SystemVolumeAmount int8 `gorm:"column:system_volume_amount" json:"systemVolumeAmount"` // 系统盘数量 + GpuAmount int8 `gorm:"column:gpu_amount" json:"gpuAmount"` // gpu数量 + GpuManufacturer string `gorm:"column:gpu_manufacturer" json:"gpuManufacturer"` // gpu厂商 + GpuModel string `gorm:"column:gpu_model" json:"gpuModel"` // gpu处理器型号 + DataVolumeType string `gorm:"column:data_volume_type" json:"dataVolumeType"` // 数据盘类型(SSD,HDD) + DataVolumeInterfaceType string `gorm:"column:data_volume_interface_type" json:"dataVolumeInterfaceType"` // 数据盘接口类型(SATA,SAS,NVME) + DataVolumeSize int `gorm:"column:data_volume_size" json:"dataVolumeSize"` // 数据盘单盘大小 + DataVolumeAmount int8 `gorm:"column:data_volume_amount" json:"dataVolumeAmount"` // 数据盘数量 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *DeviceType) TableName() string { + return "device_type" +} + +// AddDeviceType insert a new DeviceType into database and returns +// last inserted Id on success. +func AddDeviceType(logger *log.Logger, m *DeviceType) (id int64, err error) { + return dao.CreateAndGetId(logger, dao.IronicRdb, m) +} + +// GetDeviceTypeById retrieves DeviceType by Id. Returns error if +// Id doesn't exist +func GetDeviceTypeById(logger *log.Logger, deviceTypeId string) (v *DeviceType, err error) { + v = &DeviceType{} + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and is_del = 0", deviceTypeId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func QueryDeviceTypesCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} +func QueryAllDeviceTypes(logger *log.Logger, query map[string]interface{}) (ml []*DeviceType, err error) { //如果需要排序,在下面的代码中定义 + return GetMultiDeviceType(logger, query, nil, []string{"created_time"}, []string{"desc"}, 0, 0) +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func QueryDeviceTypes(logger *log.Logger, query map[string]interface{}, offset, limit int64) (ml []*DeviceType, err error) { + return GetMultiDeviceType(logger, query, nil, []string{"created_time"}, []string{"desc"}, offset, limit) + /*var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return*/ +} + +func GetOneDeviceType(logger *log.Logger, query map[string]interface{}) (l *DeviceType, err error) { + l = &DeviceType{} + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// GetMultiDeviceType retrieves all DeviceType matches certain condition. Returns empty list if +// no records exist +func GetMultiDeviceType(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*DeviceType, err error) { + + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateDeviceType updates DeviceType by Id and returns error if +// the record to be updated doesn't exist +func UpdateDeviceTypeByDeviceTypeID(logger *log.Logger, m *DeviceType, deviceTypeID string) (err error) { + //m.UpdateUser = "admin" + err = dao.Model(logger, dao.IronicWdb, DeviceType{}).Where("device_type_id = ?", deviceTypeID).Update(m).Error + return +} + +func GetByAzAndDeviceType(logger *log.Logger, az, deviceType string) (l *DeviceType, err error) { + l = &DeviceType{} + query := map[string]interface{}{ + "is_del": "0", + "device_type": deviceType, + // "az": az, + } + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func QueryByAz(logger *log.Logger, az string) (ml []*DeviceType, err error) { + query := map[string]interface{}{ + "is_del": "0", + // "az": az, + } + var db = dao.Model(logger, dao.IronicRdb, DeviceType{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} diff --git a/bmp-scheduler/dao/diskDao/diskDao.go b/bmp-scheduler/dao/diskDao/diskDao.go new file mode 100644 index 0000000..9a66139 --- /dev/null +++ b/bmp-scheduler/dao/diskDao/diskDao.go @@ -0,0 +1,142 @@ +package diskDao + +import ( + "fmt" + + log "git.jd.com/cps-golang/log" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" +) + +type Disk struct { + ID int `gorm:"primaryKey;column:id" json:"-"` // ID + DiskId string `gorm:"column:disk_id" json:"diskId"` //DISK UUID + Name string `gorm:"column:name" json:"name"` //DISK name + DeviceID string `gorm:"column:device_id" json:"deviceId"` // 设备uuid + Enclosure string `gorm:"column:enclosure" json:"enclosure"` // enclosure + Slot int `gorm:"column:slot" json:"slot"` // 卡槽槽位 + DiskType string `gorm:"column:disk_type" json:"diskType"` // 磁盘类型:system,data + Size string `gorm:"column:size" json:"size"` // 硬盘大小,不确定精度(非nvme盘) + SizeUnit string `gorm:"column:size_unit" json:"sizeUnit"` // 硬盘大小单位 MB GB TB ,1024进制 + //接口类型 + PdType string `gorm:"column:pd_type" json:"pdType"` // 硬盘类型 + AdapterID int `gorm:"column:adapter_id" json:"adapterId"` // 适配ID + //磁盘类型 + MediaType string `gorm:"column:media_type" json:"mediaType"` + DevicePath string `gorm:"column:device_path" json:"devicePath"` + Serial string `gorm:"column:serial_number" json:"serial"` + + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 + Types string `gorm:"column:types" json:"types"` // controller/nvme/panfu +} + +func (t *Disk) TableName() string { + return "disk" +} + +// AddDisk insert a new Disk into database and returns +// last inserted Id on success. +func AddDisk(logger *log.Logger, m *Disk) (id int64, err error) { + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetDiskById retrieves Disk by Id. Returns error if +// Id doesn't exist +func GetDiskById(logger *log.Logger, id int64) (v *Disk, err error) { + v = &Disk{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllDisk retrieves all Disk matches certain condition. Returns empty list if +// no records exist +func GetAllDisk(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string) (ml []*Disk, err error) { + var db = dao.Model(logger, dao.IronicRdb, Disk{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// UpdateDisk updates Disk by Id and returns error if +// the record to be updated doesn't exist +func UpdateDiskById(logger *log.Logger, m *Disk) (err error) { + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Disk{}).Where("id = ?", m.ID).Updates(m).Error +} + +// //TODO 有时间试试gorm v2支持的批量插入 +func AddMultiDisk(logger *log.Logger, m []*Disk) (id int64, err error) { + + // tx := dao.GetGormTx(logger) + // tx.Begin() + // for _, device := range m { + // //device.CreateTime = time.Now() + // //device.UpdateTime = time.Now() + // if err := tx.Create(device).Error; err != nil { + // tx.Rollback() + // return 0, err + // } + // } + // tx.Commit() + // return int64(len(m)), nil + for _, item := range m { + _, err := AddDisk(logger, item) + if err != nil { + logger.Warnf("AddMultiDisk error, device_id:%s", item.DeviceID) + } + } + return 0, nil + +} + +func UpdateMultiDisks(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = time.Now() + var db = dao.Model(logger, dao.IronicWdb, Disk{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func GetVolumeDisks(logger *log.Logger, deviceId, volumeId string) (ml []*Disk, err error) { + ml = []*Disk{} + sql := `select a.* from disk a inner join r_device_volume_disks b on a.disk_id = b.disk_id and a.is_del = 0 and b.is_del = 0 ` + + sql = sql + fmt.Sprintf(" and b.device_id = '%s' and b.volume_id = '%s'", deviceId, volumeId) + + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + if err != nil { + return nil, err + } + return ml, nil +} + +func GetDisks(logger *log.Logger, query map[string]interface{}) (ml []*Disk, err error) { + ml = []*Disk{} + var db = dao.Model(logger, dao.IronicRdb, Disk{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + if err != nil { + return nil, err + } + return +} diff --git a/bmp-scheduler/dao/idcDao/idcDao.go b/bmp-scheduler/dao/idcDao/idcDao.go new file mode 100644 index 0000000..ad7c9cc --- /dev/null +++ b/bmp-scheduler/dao/idcDao/idcDao.go @@ -0,0 +1,130 @@ +package idcDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +type Idc struct { + ID int `gorm:"primaryKey;column:id" json:"-"` // ID + IDcID string `gorm:"column:idc_id" json:"idcId"` // 机房uuid + Name string `gorm:"column:name" json:"name"` // 机房名称 + Shortname string `gorm:"column:shortname" json:"shortname"` // 机房名称缩写 + Level string `gorm:"column:level" json:"level"` // 机房等级 + Address string `gorm:"column:address" json:"address"` // 机房地址 + IloUser string `gorm:"column:ilo_user" json:"iloUser"` // 带外登录账号 + IloPassword string `gorm:"column:ilo_password" json:"iloPassword"` // 带外登录密码 + SwitchUser1 string `gorm:"column:switch_user1" json:"switchUser1"` // 交换机1登录账号 + SwitchPassword1 string `gorm:"column:switch_password1" json:"switchPassword1"` // 交换机1登录密码 + SwitchUser2 string `gorm:"column:switch_user2" json:"switchUser2"` // 交换机2登录账号 + SwitchPassword2 string `gorm:"column:switch_password2" json:"switchPassword2"` // 交换机2登录密码 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Idc) TableName() string { + return "idc" +} + +// AddIdc insert a new Idc into database and returns +// last inserted Id on success. +func CreateIdc(logger *log.Logger, m *Idc) (id int64, err error) { + return dao.CreateAndGetId(logger, dao.IronicRdb, m) +} + +// GetIdcById retrieves Idc by Id. Returns error if +// Id doesn't exist +func GetIdcById(logger *log.Logger, idcId string) (v *Idc, err error) { + v = &Idc{} + err = dao.Where(logger, dao.IronicRdb, "idc_id = ? and is_del = 0", idcId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetOneIdc(logger *log.Logger, query map[string]interface{}) (l *Idc, err error) { + l = &Idc{} + var db = dao.Model(logger, dao.IronicRdb, Idc{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// GetAllIdc retrieves all Idc matches certain condition. Returns empty list if +// no records exist +func GetAllIdc(logger *log.Logger, query map[string]interface{}) (ml []*Idc, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Idc{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiIdc retrieves all Idc matches certain condition. Returns empty list if +// no records exist +func GetMultiIdc(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Idc, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Idc{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetIdcCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Idc{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return + +} + +// UpdateIdc updates Idc by Id and returns error if +// the record to be updated doesn't exist +func UpdateIdcById(logger *log.Logger, m *Idc, dcId string) (err error) { + return dao.Model(logger, dao.IronicWdb, Idc{}).Where("idc_id = ?", dcId).Update(m).Error +} + +//func DeleteIdcById(logger *log.Logger, m *Idc) (err error) { +// m.UpdatedBy = "admin" +// //m.UpdatedAt = time.Now().Unix() +// //m.De = time.Now().Unix() +// return dao.Model(logger, dao.IronicWdb, Idc{}).Where("idc_id = ?", m.DcId).Update(m).Error +//} + +func QueryByParam(logger *log.Logger, query map[string]interface{}, offset, limit int64) (ml []*Idc, err error) { + return GetMultiIdc(logger, query, nil, []string{"id"}, []string{"desc"}, offset, limit) +} diff --git a/bmp-scheduler/dao/imageDao/imageDao.go b/bmp-scheduler/dao/imageDao/imageDao.go new file mode 100644 index 0000000..1532929 --- /dev/null +++ b/bmp-scheduler/dao/imageDao/imageDao.go @@ -0,0 +1,190 @@ +package imageDao + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "fmt" + log "git.jd.com/cps-golang/log" + "strings" +) + +// Image 镜像 +type Image struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像uuid + ImageName string `gorm:"column:image_name" json:"imageName"` // 镜像名称 + //ImageVersion string `gorm:"column:image_version" json:"imageVersion"` // 镜像版本 + OsID string `gorm:"column:os_id" json:"osId"` // OSID + Format string `gorm:"column:format" json:"format"` // 镜像格式(qcow2、tar) + Filename string `gorm:"column:filename" json:"filename"` // 镜像文件名称 + URL string `gorm:"column:url" json:"url"` // 镜像源路径 + Hash string `gorm:"column:hash" json:"hash"` // 镜像校验码 + Source string `gorm:"column:source" json:"source"` // 镜像来源(common通用、customize定制、user_defined自定义) + Description string `gorm:"column:description" json:"description"` // 描述 + SystemPartition string `gorm:"column:system_partition" json:"systemPartition"` // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + DataPartition string `gorm:"column:data_partition" json:"dataPartition"` // 数据分区信息 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Image) TableName() string { + return "image" +} + +// AddImage insert a new Image into database and returns +// last inserted Id on success. +func AddImage(logger *log.Logger, m *Image) (id int64, err error) { + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetImageById retrieves Image by Id. Returns error if +// Id doesn't exist +func GetImageById(logger *log.Logger, id int64) (v *Image, err error) { + v = &Image{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetImageByUuid retrieves Image by Uuid. Returns error if +// Id doesn't exist +func GetImageByUuid(logger *log.Logger, imageId string) (v *Image, err error) { + v = &Image{} + err = dao.Where(logger, dao.IronicRdb, "image_id = ? and is_del = 0", imageId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} +func QueryImagesCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Image{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} +func GetAllImage(logger *log.Logger, query map[string]interface{}) (ml []*Image, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Image{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiImage retrieves all Image matches certain condition. Returns empty list if +// no records exist +func GetMultiImage(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Image, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Image{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateImage updates Image by Id and returns error if +// the record to be updated doesn't exist +func UpdateImageById(logger *log.Logger, m *Image) (err error) { + return dao.Model(logger, dao.IronicWdb, Image{}).Where("image_id = ?", m.ImageID).Updates(m).Error +} + +type DImage struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像uuid + ImageName string `gorm:"column:image_name" json:"imageName"` // 镜像名称 + ImageVersion string `gorm:"column:image_version" json:"imageVersion"` // 镜像版本 + Format string `gorm:"column:format" json:"format"` // 镜像格式(qcow2、tar) + Filename string `gorm:"column:filename" json:"filename"` // 镜像文件名称 + URL string `gorm:"column:url" json:"url"` // 镜像源路径 + Hash string `gorm:"column:hash" json:"hash"` // 镜像校验码 + Source string `gorm:"column:source" json:"source"` // 镜像来源(common通用、customize定制、user_defined自定义) + Description string `gorm:"column:description" json:"description"` // 描述 + SystemPartition string `gorm:"column:system_partition" json:"systemPartition"` // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + DataPartition string `gorm:"column:data_partition" json:"dataPartition"` // 数据分区信息 + OsID string `json:"OsId"` + OsName string `json:"osName"` + OsVersion string `json:"osVersion"` + OsType string `json:"osType"` + Platform string `json:"platform"` + OsArchitecture string `json:"architecture"` + Bits int32 `json:"bits"` + CreatedBy int `json:"createdBy"` + UpdatedBy int `json:"updatedBy"` + CreatedTime int `json:"createdTime"` + UpdatedTime int `json:"updatedTime"` +} + +// QueryByDeviceOsType ... +func QueryByDeviceOsType(logger *log.Logger, param map[string]string) (ml []*DImage, err error) { + + sql := `select i.id,i.image_id,i.image_name,i.image_version,i.format,i.url,i.filename,i.description,i.os_id,i.hash,i.source, + i.created_by,i.updated_by,i.created_time,i.updated_time FROM image i` + if param["device_type"] != "" { + sql = sql + " LEFT JOIN r_device_type_image rd on i.uuid=rd.image_id" + } + if param["region"] != "" { + sql = sql + " LEFT JOIN r_region_image re on i.uuid=re.image_id" + } + sql = sql + " LEFT JOIN os o on i.os_id=o.os_id" + where := " where 1 = 1" + if param["device_type"] != "" { + where = where + " and rd.device_type=" + fmt.Sprintf("'%s'", param["device_type"]) + } + if param["region"] != "" { + where = where + " and re.region=" + fmt.Sprintf("'%s'", param["region"]) + } + if param["os_type"] != "" { + where = where + " and o.os_type=" + fmt.Sprintf("'%s'", param["os_type"]) + } + if param["os_version"] != "" { + where = where + " and o.os_version=" + fmt.Sprintf("'%s'", param["os_version"]) + } + if param["os_id"] != "" { + where = where + " and i.os_id=" + fmt.Sprintf("'%s'", param["os_id"]) + } + if param["name_en"] != "" { + where = where + fmt.Sprintf(" and i.name_en LIKE '%%s%'", param["name_en"]) + } + if param["image_ids"] != "" { + imageIds := strings.Split(param["image_ids"], ",") + for idx, v := range imageIds { + imageIds[idx] = fmt.Sprintf("'%s'", v) + } + inSql := fmt.Sprintf("(%s)", strings.Join(imageIds, ",")) + where = where + fmt.Sprintf(" and i.uuid in %s", inSql) + } + if param["source"] != "" { + where = where + fmt.Sprintf(" and i.source='%s'", param["source"]) + } + if param["device_type"] != "" { + where = where + " and rd.is_del=0" + } + if param["region"] != "" { + where = where + " and re.is_del=0" + } + sql = sql + where + " and i.is_del=0 and o.is_del=0" + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-scheduler/dao/instanceDao/instanceDao.go b/bmp-scheduler/dao/instanceDao/instanceDao.go new file mode 100644 index 0000000..6756f01 --- /dev/null +++ b/bmp-scheduler/dao/instanceDao/instanceDao.go @@ -0,0 +1,743 @@ +package instanceDao + +import ( + "fmt" + "strings" + "time" + + log "git.jd.com/cps-golang/log" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" +) + +type Instance struct { + ID int `gorm:"primaryKey;column:id" json:"-"` + InstanceID string `gorm:"column:instance_id" json:"instanceId"` // 实例ID(uuid) + IDcID string `gorm:"column:idc_id" json:"idcId"` // 机房uuid + ProjectID string `gorm:"column:project_id" json:"projectId"` // 项目id + UserID string `gorm:"column:user_id" json:"userId"` // 用户uuid + InstanceName string `gorm:"column:instance_name" json:"instanceName"` // 实例名称 + DeviceID string `gorm:"column:device_id" json:"deviceId"` // 设备uuid + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 机型uuid + Hostname string `gorm:"column:hostname" json:"hostname"` // 主机名 + Status string `gorm:"column:status" json:"status"` // 运行状态 + Reason string `gorm:"column:reason" json:"reason"` // 失败原因 + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像uuid + SystemVolumeRaidID string `gorm:"column:system_volume_raid_id" json:"systemVolumeRaidId"` // 系统盘raid + Locked string `gorm:"column:locked" json:"locked"` // 是否锁定解锁锁定:locked,解锁unlocked + DataVolumeRaidID string `gorm:"column:data_volume_raid_id" json:"dataVolumeRaidId"` // 数据盘raid + Description string `gorm:"column:description" json:"description"` // 描述 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除(0-未删, 1-已删) + BootMode string `gorm:"column:boot_mode" json:"bootMode"` // boot类型:UEFI Legacy/BIOS +} + +func (t *Instance) TableName() string { + return "instance" +} + +// AddInstance insert a new Instance into database and returns +// last inserted Id on success. +func AddInstance(logger *log.Logger, m *Instance) (id int64, err error) { + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// AddDevice insert a new Device into database and returns +// last inserted Id on success. +func AddMultiInstance(logger *log.Logger, m []*Instance) (id int64, err error) { + tx := dao.GetGormTx(logger) + tx.Begin() + for _, instance := range m { + if err := tx.Create(instance).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetInstanceById retrieves Instance by Id. Returns error if +// Id doesn't exist +func GetInstanceByUuid(logger *log.Logger, uuid string) (v *Instance, err error) { + v = &Instance{} + err = dao.Where(logger, dao.IronicRdb, "instance_id = ? and is_del = 0", uuid).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetInstanceById retrieves Instance by Id. Returns error if +// Id doesn't exist +func GetInstanceById(logger *log.Logger, id int64) (v *Instance, err error) { + v = &Instance{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetInstanceCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} + +func GetAllInstance(logger *log.Logger, query map[string]interface{}) (ml []*Instance, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetSingleInstance(logger *log.Logger, query map[string]interface{}) (l *Instance, err error) { + l = &Instance{} + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// GetAllInstance retrieves all Instance matches certain condition. Returns empty list if +// no records exist +func GetMultiInstance(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []Instance, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateInstance updates Instance by Id and returns error if +// the record to be updated doesn't exist +func UpdateInstanceById(logger *log.Logger, m *Instance) (err error) { + return dao.Model(logger, dao.IronicWdb, Instance{}).Where("id = ?", m.ID).Updates(m).Error +} + +// description为空也有可能 +func UpdateInstanceAnywhere(logger *log.Logger, m *Instance) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Instance{}).Save(m).Error +} + +func UpdateSuccessInstanceByInstanceId(logger *log.Logger, m *Instance) (err error) { + sql := `update instance set reason="` + m.Reason + `" where instance_id="` + m.InstanceID + `" and is_del = 0` + err = dao.IronicWdb.Exec(sql).Error + return +} +func UpdateInstanceByInstanceId(logger *log.Logger, m *Instance) (err error) { + return dao.Model(logger, dao.IronicWdb, Instance{}).Where("instance_id = ? and is_del= ?", m.InstanceID, 0).Updates(m).Error +} +func UpdateMultiInstances(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["update_time"] = time.Now() + var db = dao.Model(logger, dao.IronicWdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func UpdateKeypairIdAsEmpty(logger *log.Logger, tenant, keypair_id string) (err error) { + + query := map[string]interface{}{ + "tenant": tenant, + "keypair_id": keypair_id, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicWdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + + updates := map[string]interface{}{ + "keypair_id": "", + "update_time": time.Now(), + } + + err = db.Updates(updates).Error + return +} + +func QueryByTenantAndEipId(logger *log.Logger, tenant, eip_id string) (ml []*Instance, err error) { + query := map[string]interface{}{ + "tenant": tenant, + "eip_id": eip_id, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func QueryByTenantAndExtensionEipId(logger *log.Logger, tenant, eip_id string) (ml []*Instance, err error) { + query := map[string]interface{}{ + "tenant": tenant, + "extension_eip_id": eip_id, + "is_del": "0", + } + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func QueryByTenantAndSubnetId(logger *log.Logger, tenant, subnet_id string) (ml []*Instance, err error) { + query := map[string]interface{}{ + "tenant": tenant, + "subnet_id": subnet_id, + "is_del": "0", + } + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func QueryByTenantAndExtensionSubnetId(logger *log.Logger, tenant, subnet_id string) (ml []*Instance, err error) { + query := map[string]interface{}{ + "tenant": tenant, + "extension_subnet_id": subnet_id, + "is_del": "0", + } + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func QueryByTenantAndIpv6Address(logger *log.Logger, tenant, ipv6_address string) (ml []*Instance, err error) { + query := map[string]interface{}{ + "tenant": tenant, + "ipv6_address": ipv6_address, + "is_del": "0", + } + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func QueryByTenantAndExtensionIpv6Address(logger *log.Logger, tenant, ipv6_address string) (ml []*Instance, err error) { + query := map[string]interface{}{ + "tenant": tenant, + "extension_ipv6_address": ipv6_address, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +type DInstanceSaleStatistics struct { + Tenant string `json:"tenant"` + Az string `json:"az"` + DeviceType string `json:"device_type"` + Count int `json:"count"` +} + +func SaleStatisticsByTenant(logger *log.Logger) (ml []*DInstanceSaleStatistics, err error) { + + sql := `select tenant, az, device_type, count(device_type) as count from instance i left join device d on i.device_id = d.id where i.is_del = 0 group by tenant,az,device_type` + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} + +func QueryByInstanceIds(logger *log.Logger, instance_ids []string) (ml []*Instance, err error) { + query := map[string]interface{}{ + "is_del": "0", + "uuid.in": instance_ids, + } + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func QueryByUpdateTimeRange(logger *log.Logger, is_del bool, start_time, end_time time.Time) (ml []*Instance, err error) { + stime := start_time.Format("2006-01-02 15:04:05") + etime := end_time.Format("2006-01-02 15:04:05") + query := map[string]interface{}{ + "update_time.gte": stime, + "update_time.lt": etime, + "is_del": util.Bool2Int8(is_del), + } + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return + +} + +func QueryByCreateTimeRange(logger *log.Logger, is_del bool, start_time, end_time time.Time) (ml []*Instance, err error) { + + stime := start_time.Format("2006-01-02 15:04:05") + etime := end_time.Format("2006-01-02 15:04:05") + query := map[string]interface{}{ + "create_time.gte": stime, + "create_time.lt": etime, + "is_del": util.Bool2Int8(is_del), + } + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func CountByTenantAndSubnetId(logger *log.Logger, tenant, subnet_id string) (n int64, err error) { + + query := map[string]interface{}{ + "tenant": tenant, + "subnet_id": subnet_id, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicRdb, Instance{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +func CountByParam(logger *log.Logger, query map[string]string) (n int64, err error) { + + sql := `select count(1) from instance t1 left join device t2 on t1.device_id = t2.id where 1=1` + if query["tenant"] != "" { + sql = sql + fmt.Sprintf(" and t1.tenant = '%s'", query["tenant"]) + } + if query["region"] != "" { + sql = sql + fmt.Sprintf(" and t2.region = '%s'", query["region"]) + } + if query["az"] != "" { + sql = sql + fmt.Sprintf(" and t2.az = '%s'", query["az"]) + } + + if query["network_type"] != "" { + sql = sql + fmt.Sprintf(" and t1.network_type = '%s'", query["network_type"]) + } + if query["interface_mode"] != "" { + sql = sql + fmt.Sprintf(" and t1.interface_mode = '%s'", query["interface_mode"]) + } + if query["subnet_id"] != "" { + sql = sql + fmt.Sprintf(" and (t1.subnet_id = '%s' or t1.extension_subnet_id = '%s')", query["subnet_id"], query["subnet_id"]) + } + if query["name"] != "" { + sql = sql + fmt.Sprintf(" and t1.name LIKE CONCAT('%%', '%s', '%%')", query["name"]) + } + if query["private_ip"] != "" { + sql = sql + fmt.Sprintf(" and private_ip LIKE CONCAT('%%', '%s', '%%')", query["private_ip"]) + } + if query["extension_private_ip"] != "" { + sql = sql + fmt.Sprintf(" and extension_private_ip LIKE CONCAT('%%', '%s', '%%')", query["extension_private_ip"]) + } + if query["device_type"] != "" { + sql = sql + fmt.Sprintf(" and t2.device_type = '%s'", query["device_type"]) + } + if query["statuses"] != "" { + statuses := strings.Split(query["statuses"], ",") + for k, v := range statuses { + statuses[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t1.status in (%s)", strings.Join(statuses, ",")) + } + if query["instance_ids"] != "" { + instance_ids := strings.Split(query["instance_ids"], ",") + for k, v := range instance_ids { + instance_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t1.uuid in (%s)", strings.Join(instance_ids, ",")) + } + if query["sns"] != "" { + sns := strings.Split(query["sns"], ",") + for k, v := range sns { + sns[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t2.sn in (%s)", strings.Join(sns, ",")) + } + if query["eip_ids"] != "" { + eip_ids := strings.Split(query["eip_ids"], ",") + for k, v := range eip_ids { + eip_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and eip_id in (%s)", strings.Join(eip_ids, ",")) + } + if query["keypair_ids"] != "" { + keypair_ids := strings.Split(query["keypair_ids"], ",") + for k, v := range keypair_ids { + keypair_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and keypair_id in (%s)", strings.Join(keypair_ids, ",")) + } + if query["enable_internet"] != "" { + enable_internet := 0 + if query["enable_internet"] == "true" { + enable_internet = 1 + } + sql = sql + fmt.Sprintf(" and enable_internet = %d", enable_internet) + } + sql = sql + " and t1.is_del = 0" + err = dao.Raw(logger, dao.IronicRdb, sql).Count(&n).Error + return +} + +func CountInstances(logger *log.Logger, query map[string]string) (n int64, err error) { + + sql := `select count(1) from device t2 left join (select * from instance where is_del=0) t1 on t1.device_id = t2.id where 1=1 ` + if query["tenant"] != "" { + sql = sql + fmt.Sprintf(" and t1.tenant = '%s'", query["tenant"]) + } + if query["region"] != "" { + sql = sql + fmt.Sprintf(" and t2.region = '%s'", query["region"]) + } + if query["az"] != "" { + sql = sql + fmt.Sprintf(" and t2.az = '%s'", query["az"]) + } + if query["device_type"] != "" { + sql = sql + fmt.Sprintf(" and t2.device_type = '%s'", query["device_type"]) + } + if query["sale_status"] != "" { + sql = sql + fmt.Sprintf(" and t2.sale_status = '%s'", query["sale_status"]) + } + if query["statuses"] != "" { + statuses := strings.Split(query["statuses"], ",") + for k, v := range statuses { + statuses[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t1.status in (%s)", strings.Join(statuses, ",")) + } + if query["instance_ids"] != "" { + instance_ids := strings.Split(query["instance_ids"], ",") + for k, v := range instance_ids { + instance_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t1.uuid in (%s)", strings.Join(instance_ids, ",")) + } + if query["public_ips"] != "" && query["eip_ids"] != "" { + + public_ips := strings.Split(query["public_ips"], ",") + for k, v := range public_ips { + public_ips[k] = fmt.Sprintf("'%s'", v) + } + + eip_ids := strings.Split(query["eip_ids"], ",") + for k, v := range eip_ids { + eip_ids[k] = fmt.Sprintf("'%s'", v) + } + + sql = sql + fmt.Sprintf(" and (t1.public_ip in (%s) or t1.eip_id in (%s))", strings.Join(public_ips, ","), strings.Join(eip_ids, ",")) + } else if query["public_ips"] != "" { + public_ips := strings.Split(query["public_ips"], ",") + for k, v := range public_ips { + public_ips[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t1.public_ip in (%s)", strings.Join(public_ips, ",")) + } else if query["eip_ids"] != "" { + eip_ids := strings.Split(query["eip_ids"], ",") + for k, v := range eip_ids { + eip_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t1.eip_id in (%s)", strings.Join(eip_ids, ",")) + } + if query["private_ip"] != "" { + sql = sql + fmt.Sprintf(" and private_ip LIKE CONCAT('%%', '%s', '%%')", query["private_ip"]) + } + if query["sns"] != "" { + sns := strings.Split(query["sns"], ",") + for k, v := range sns { + sns[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t2.sn in (%s)", strings.Join(sns, ",")) + } + if query["ilo_ips"] != "" { + ilo_ips := strings.Split(query["ilo_ips"], ",") + for k, v := range ilo_ips { + ilo_ips[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t2.ilo_ip in (%s)", strings.Join(ilo_ips, ",")) + } + + if query["start_time"] != "" && query["end_time"] != "" { + sql = sql + fmt.Sprintf(" and t1.create_time between '%s' and '%s'", query["start_time"], query["end_time"]) + } + sql = sql + ` and t2.is_del = 0` + err = dao.Raw(logger, dao.IronicRdb, sql).Count(&n).Error + return +} + +type DInstance struct { + Uuid string `json:"uuid"` + DeviceId int64 `json:"device_id"` + Tenant string `json:"tenant"` + Region string `json:"region"` + Az string `json:"az"` + DeviceType string `json:"device_type"` + Name string `json:"name"` + Hostname string `json:"hostname"` + Description string `json:"description"` + Status string `json:"status"` + ImageId string `json:"image_id"` + SystemVolumeRaidId string `json:"system_volume_raid_id"` + DataVolumeRaidId string `json:"data_volume_raid_id"` + NetworkType string `json:"network_type"` + SubnetId string `json:"subnet_id"` + PrivateIp string `json:"private_ip"` + LineType string `json:"line_type"` + PublicIp string `json:"public_ip"` + EnableInternet bool `json:"enable_internet"` + EnableIpv6 bool `json:"enable_ipv6"` + Ipv6Address string `json:"ipv6_address"` + EipId string `json:"eip_id"` + Bandwidth int `json:"bandwidth"` + KeypairId string `json:"keypair_id"` + InterfaceMode string `json:"interface_mode"` + ExtensionSubnetId string `json:"extension_subnet_id"` + ExtensionPrivateIp string `json:"extension_private_ip"` + ExtensionEnableInternet bool `json:"extension_enable_internet"` + ExtensionEipId string `json:"extension_eip_id"` + ExtensionEnableIpv6 bool `json:"extension_enable_ipv6"` + ExtensionIpv6Address string `json:"extension_ipv6_address"` + Sn string `json:"sn"` + UPosition string `json:"u_position"` + Cabinet string `json:"cabinet"` + IloIp string `json:"ilo_ip"` + SaleStatus string `json:"sale_status"` + SwitchIp string `json:"switch_ip"` + SwitchCidr string `json:"switch_cidr"` + CreateTime time.Time `json:"create_time"` + UpdateTime time.Time `json:"update_time"` +} + +func QueryByParam(logger *log.Logger, query map[string]string, offset, limit int64) (ml []*DInstance, err error) { + + sql := `select t1.uuid,t1.device_id,t1.tenant,t1.name,t1.hostname,t1.image_id,t1.system_volume_raid_id,t1.data_volume_raid_id,t1.network_type,t1.subnet_id,t1.private_ip,t1.line_type,t1.public_ip,t1.enable_internet,t1.enable_ipv6,t1.ipv6_address,t1.eip_id,t1.extension_enable_ipv6,t1.extension_ipv6_address,t1.bandwidth,t1.status,t1.description,t1.keypair_id,t1.interface_mode,t1.extension_subnet_id,t1.extension_private_ip,t1.extension_enable_internet,t1.extension_eip_id,t1.create_time,t1.update_time, + t2.region,t2.az,t2.device_type,t2.sn,t2.u_position,t2.cabinet,t2.ilo_ip,t2.sale_status from instance t1 left join device t2 on t1.device_id = t2.id where 1=1 ` + if query["tenant"] != "" { + sql = sql + fmt.Sprintf(" and t1.tenant = '%s'", query["tenant"]) + } + if query["region"] != "" { + sql = sql + fmt.Sprintf(" and t2.region = '%s'", query["region"]) + } + if query["az"] != "" { + sql = sql + fmt.Sprintf(" and t2.az = '%s'", query["az"]) + } + + if query["network_type"] != "" { + sql = sql + fmt.Sprintf(" and t1.network_type = '%s'", query["network_type"]) + } + if query["interface_mode"] != "" { + sql = sql + fmt.Sprintf(" and t1.interface_mode = '%s'", query["interface_mode"]) + } + if query["subnet_id"] != "" { + sql = sql + fmt.Sprintf(" and (t1.subnet_id = '%s' or t1.extension_subnet_id = '%s')", query["subnet_id"], query["subnet_id"]) + } + if query["name"] != "" { + sql = sql + fmt.Sprintf(" and t1.name LIKE CONCAT('%%', '%s', '%%')", query["name"]) + } + if query["private_ip"] != "" { + sql = sql + fmt.Sprintf(" and private_ip LIKE CONCAT('%%', '%s', '%%')", query["private_ip"]) + } + if query["extension_private_ip"] != "" { + sql = sql + fmt.Sprintf(" and extension_private_ip LIKE CONCAT('%%', '%s', '%%')", query["extension_private_ip"]) + } + if query["device_type"] != "" { + sql = sql + fmt.Sprintf(" and t2.device_type = '%s'", query["device_type"]) + } + if query["statuses"] != "" { + statuses := strings.Split(query["statuses"], ",") + for k, v := range statuses { + statuses[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t1.status in (%s)", strings.Join(statuses, ",")) + } + if query["instance_ids"] != "" { + instance_ids := strings.Split(query["instance_ids"], ",") + for k, v := range instance_ids { + instance_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t1.uuid in (%s)", strings.Join(instance_ids, ",")) + } + if query["sns"] != "" { + sns := strings.Split(query["sns"], ",") + for k, v := range sns { + sns[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t2.sn in (%s)", strings.Join(sns, ",")) + } + if query["eip_ids"] != "" { + eip_ids := strings.Split(query["eip_ids"], ",") + for k, v := range eip_ids { + eip_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and eip_id in (%s)", strings.Join(eip_ids, ",")) + } + if query["keypair_ids"] != "" { + keypair_ids := strings.Split(query["keypair_ids"], ",") + for k, v := range keypair_ids { + keypair_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and keypair_id in (%s)", strings.Join(keypair_ids, ",")) + } + if query["enable_internet"] != "" { + enable_internet := 0 + if query["enable_internet"] == "true" { + enable_internet = 1 + } + sql = sql + fmt.Sprintf(" and enable_internet = %d", enable_internet) + } + sql = sql + fmt.Sprintf(" and t1.is_del = 0 ORDER BY t1.id DESC LIMIT %d, %d", offset, limit) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} + +func QueryInstances(logger *log.Logger, query map[string]string, offset, limit int64) (ml []*DInstance, err error) { + + sql := `select t1.uuid,t1.device_id,t1.tenant,t1.name,t1.hostname,t1.image_id,t1.system_volume_raid_id,t1.data_volume_raid_id,t1.network_type,t1.subnet_id,t1.private_ip,t1.line_type,t1.public_ip,t1.enable_internet,t1.enable_ipv6,t1.ipv6_address,t1.eip_id,t1.extension_enable_ipv6,t1.extension_ipv6_address,t1.bandwidth,t1.status,t1.description,t1.keypair_id,t1.interface_mode,t1.extension_subnet_id,t1.extension_private_ip,t1.extension_enable_internet,t1.extension_eip_id,t1.create_time,t1.update_time,t2.region,t2.az,t2.device_type,t2.sn,t2.u_position,t2.cabinet,t2.ilo_ip,t2.sale_status from device t2 left join (select * from instance where is_del=0) t1 on t1.device_id = t2.id where 1=1 ` + if query["tenant"] != "" { + sql = sql + fmt.Sprintf(" and t1.tenant = '%s'", query["tenant"]) + } + if query["region"] != "" { + sql = sql + fmt.Sprintf(" and t2.region = '%s'", query["region"]) + } + if query["az"] != "" { + sql = sql + fmt.Sprintf(" and t2.az = '%s'", query["az"]) + } + if query["device_type"] != "" { + sql = sql + fmt.Sprintf(" and t2.device_type = '%s'", query["device_type"]) + } + if query["sale_status"] != "" { + sql = sql + fmt.Sprintf(" and t2.sale_status = '%s'", query["sale_status"]) + } + if query["statuses"] != "" { + statuses := strings.Split(query["statuses"], ",") + for k, v := range statuses { + statuses[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t1.status in (%s)", strings.Join(statuses, ",")) + } + if query["instance_ids"] != "" { + instance_ids := strings.Split(query["instance_ids"], ",") + for k, v := range instance_ids { + instance_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t1.uuid in (%s)", strings.Join(instance_ids, ",")) + } + if query["public_ips"] != "" && query["eip_ids"] != "" { + + public_ips := strings.Split(query["public_ips"], ",") + for k, v := range public_ips { + public_ips[k] = fmt.Sprintf("'%s'", v) + } + + eip_ids := strings.Split(query["eip_ids"], ",") + for k, v := range eip_ids { + eip_ids[k] = fmt.Sprintf("'%s'", v) + } + + sql = sql + fmt.Sprintf(" and (t1.public_ip in (%s) or t1.eip_id in (%s))", strings.Join(public_ips, ","), strings.Join(eip_ids, ",")) + } else if query["public_ips"] != "" { + public_ips := strings.Split(query["public_ips"], ",") + for k, v := range public_ips { + public_ips[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t1.public_ip in (%s)", strings.Join(public_ips, ",")) + } else if query["eip_ids"] != "" { + eip_ids := strings.Split(query["eip_ids"], ",") + for k, v := range eip_ids { + eip_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t1.eip_id in (%s)", strings.Join(eip_ids, ",")) + } + if query["private_ip"] != "" { + sql = sql + fmt.Sprintf(" and private_ip LIKE CONCAT('%%', '%s', '%%')", query["private_ip"]) + } + if query["sns"] != "" { + sns := strings.Split(query["sns"], ",") + for k, v := range sns { + sns[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t2.sn in (%s)", strings.Join(sns, ",")) + } + if query["ilo_ips"] != "" { + ilo_ips := strings.Split(query["ilo_ips"], ",") + for k, v := range ilo_ips { + ilo_ips[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t2.ilo_ip in (%s)", strings.Join(ilo_ips, ",")) + } + + if query["start_time"] != "" && query["end_time"] != "" { + sql = sql + fmt.Sprintf(" and t1.create_time between '%s' and '%s'", query["start_time"], query["end_time"]) + } + sql = sql + fmt.Sprintf(" and t2.is_del = 0 ORDER BY t1.id DESC LIMIT %d, %d", offset, limit) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-scheduler/dao/instancePartitionDao/instancePartitionDao.go b/bmp-scheduler/dao/instancePartitionDao/instancePartitionDao.go new file mode 100644 index 0000000..c21c841 --- /dev/null +++ b/bmp-scheduler/dao/instancePartitionDao/instancePartitionDao.go @@ -0,0 +1,109 @@ +package instancePartitionDao + +import ( + log "git.jd.com/cps-golang/log" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" +) + +// InstancePartition 实例分区表 +type InstancePartition struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + InstanceID string `gorm:"column:instance_id" json:"instanceId"` // 实例ID + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像ID + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型 + BootMode string `gorm:"column:boot_mode" json:"bootMode"` // boot类型:bios、uefi + PartitionType string `gorm:"column:partition_type" json:"partitionType"` // 分区类型:root、boot、system、data + PartitionSize int `gorm:"column:partition_size" json:"partitionSize"` // 分区大小,单位MB + PartitionFsType string `gorm:"column:partition_fs_type" json:"partitionFsType"` // 文件系统类型:xfs + PartitionMountPoint string `gorm:"column:partition_mount_point" json:"partitionMountPoint"` // 分区目录 + PartitionLabel string `gorm:"column:partition_label" json:"partitionLabel"` // 分区标签:l_分区目录 + SystemDiskLabel string `gorm:"column:system_disk_label" json:"systemDiskLabel"` // 系统盘分区格式:gpt、msdos(做完RAID系统盘大于4T必用gpt) + DataDiskLabel string `gorm:"column:data_disk_label" json:"dataDiskLabel"` // 数据盘分区格式:gpt、msdos + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除(0-未删, 1-已删) + InstancePartitionID string `gorm:"column:instance_partition_id" json:"instancePartitionId"` // 实例分区uuID + Number int `gorm:"column:number" json:"number"` // 每个实例的分区序号 +} + +func (t *InstancePartition) TableName() string { + return "instance_partition" +} + +// AddInstancePartition insert a new InstancePartition into database and returns +// last inserted Id on success. +func AddInstancePartition(logger *log.Logger, m *InstancePartition) (id int64, err error) { + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetInstancePartitionById retrieves InstancePartition by Id. Returns error if +// Id doesn't exist +func GetInstancePartitionById(logger *log.Logger, id int64) (v *InstancePartition, err error) { + v = &InstancePartition{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllInstancePartition retrieves all InstancePartition matches certain condition. Returns empty list if +// no records exist +func GetAllInstancePartition(logger *log.Logger, query map[string]interface{}) (ml []*InstancePartition, err error) { + + var db = dao.Model(logger, dao.IronicRdb, InstancePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetOneInstancePartition(logger *log.Logger, query map[string]interface{}) (l *InstancePartition, err error) { + l = &InstancePartition{} + var db = dao.Model(logger, dao.IronicRdb, InstancePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// UpdateInterface updates Interface by Id and returns error if +// the record to be updated doesn't exist +func UpdateInstancePartitionById(logger *log.Logger, m *InstancePartition) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, InstancePartition{}).Where("id = ?", m.ID).Updates(m).Error +} + +// func GetInstancePartitionsBySn(logger *log.Logger, sn string) (ml []*InstancePartition, err error) { +// ml = []*InstancePartition{} +// err = dao.Where(logger, dao.IronicRdb, "sn = ? and is_del = 0", sn).Find(&ml).Error +// if err != nil { +// return nil, err +// } +// return ml, nil + +// } + +func GetInstancePartitionsByInstanceId(logger *log.Logger, instanceId string) (ml []*InstancePartition, err error) { + ml = []*InstancePartition{} + err = dao.Where(logger, dao.IronicRdb, "instance_id = ? and is_del = 0", instanceId).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil + +} diff --git a/bmp-scheduler/dao/interfaceDao/interfaceDao.go b/bmp-scheduler/dao/interfaceDao/interfaceDao.go new file mode 100644 index 0000000..9407416 --- /dev/null +++ b/bmp-scheduler/dao/interfaceDao/interfaceDao.go @@ -0,0 +1,171 @@ +package interfaceDao + +import ( + "fmt" + "strings" + "time" + + log "git.jd.com/cps-golang/log" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" +) + +type Interface struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + InterfaceName string `gorm:"column:interface_name;type:varchar(16)" json:"interface_name"` // 网卡名称 + InterfaceType string `gorm:"column:interface_type;type:varchar(16)" json:"interface_type"` // 网卡类型:lan/wan + Sn string `gorm:"index:i_interface_sn;column:sn;type:varchar(64);not null" json:"sn"` // 设备SN + Mac string `gorm:"column:mac;type:varchar(32);not null" json:"mac"` // MAC + SwitchIP string `gorm:"column:switch_ip;type:varchar(32);not null" json:"switch_ip"` // 内网交换机IP + SwitchPort string `gorm:"column:switch_port;type:varchar(32)" json:"switch_port"` // 内网交换机Port + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删。1-已删) + // 采集过来 + Ipv4Address string `json:"ipv4_address"` +} + +func (t *Interface) TableName() string { + return "interface" +} + +// AddInterface insert a new Interface into database and returns +// last inserted Id on success. +func AddInterface(logger *log.Logger, m *Interface) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func AddMultiInterface(logger *log.Logger, m []*Interface) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, interf := range m { + interf.CreateTime = time.Now() + interf.UpdateTime = time.Now() + if err := tx.Create(interf).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetInterfaceById retrieves Interface by Id. Returns error if +// Id doesn't exist +func GetInterfaceById(logger *log.Logger, id int64) (v *Interface, err error) { + v = &Interface{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetInterfacesBySn(logger *log.Logger, sn string) (ml []*Interface, err error) { + var db = dao.Model(logger, dao.IronicRdb, Interface{}) + err = db.Where("sn = ? and is_del = ?", sn, 0).Order("id asc").Find(&ml).Error + return +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetAllInterface(logger *log.Logger, query map[string]interface{}) (ml []*Interface, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Interface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetOneInterface(logger *log.Logger, query map[string]interface{}) (l *Interface, err error) { + l = &Interface{} + var db = dao.Model(logger, dao.IronicRdb, Interface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// GetAllInterface retrieves all Interface matches certain condition. Returns empty list if +// no records exist +func GetMultiInterface(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Interface, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Interface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateInterface updates Interface by Id and returns error if +// the record to be updated doesn't exist +func UpdateInterfaceById(logger *log.Logger, m *Interface) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Interface{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateMultiInterfaces(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["update_time"] = time.Now() + var db = dao.Model(logger, dao.IronicWdb, Interface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +type DInterface struct { + Sn string `json:"sn"` + InterfaceName string `json:"interface_name"` + InterfaceType string `json:"interface_type"` + Mac string `json:"mac"` + SwitchIp string `json:"switch_ip"` + SwitchPort string `json:"switch_port"` + PodName string `json:"pod_name"` + PodRoom string `json:"pod_room"` + CreateTime time.Time `json:"create_time"` + UpdateTime time.Time `json:"update_time"` +} + +func GetBySn(logger *log.Logger, sn string) (ml []*Interface, err error) { + + err = dao.Where(logger, dao.IronicRdb, "sn = ? and is_del = 0", sn).Find(&ml).Error + return + +} + +func GetBySns(logger *log.Logger, sns []string) (ml []*DInterface, err error) { + + sql := `select i.sn,i.interface_name,i.interface_type,i.mac,i.switch_ip,i.switch_port,i.create_time,i.update_time,n.name as pod_name,n.room as pod_room FROM interface i LEFT JOIN jd_switch j ON i.switch_ip = j.switch_ip LEFT JOIN net_pod n ON j.pod_id=n.id where 1=1` + for idx, v := range sns { + sns[idx] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and i.sn in (%s) and i.is_del=0 and j.is_del=0 and n.is_del=0", strings.Join(sns, ",")) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-scheduler/dao/jdBondInterfaceDao/jdBondInterfaceDao.go b/bmp-scheduler/dao/jdBondInterfaceDao/jdBondInterfaceDao.go new file mode 100644 index 0000000..bbba05d --- /dev/null +++ b/bmp-scheduler/dao/jdBondInterfaceDao/jdBondInterfaceDao.go @@ -0,0 +1,110 @@ +package jdBondInterfaceDao + +import ( + "fmt" + "strings" + "time" + + log "git.jd.com/cps-golang/log" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" +) + +// JdBondInterface 零售中台网络端口Bond表 +type JdBondInterface struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // 自增id + GroupID int `gorm:"column:group_id;type:int(11)" json:"group_id"` // 端口聚合组ID + Sn string `gorm:"index:i_sn;column:sn;type:varchar(64);not null" json:"sn"` // 设备sn + SwitchIP string `gorm:"index:i_switchIp;column:switch_ip;type:varchar(32);not null" json:"switch_ip"` // 交换机ip + PrivateIP string `gorm:"column:private_ip;type:varchar(30)" json:"private_ip"` // 内网IP + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime;not null" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(2);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *JdBondInterface) TableName() string { + return "jd_bond_interface" +} + +// AddJdBondInterface insert a new JdBondInterface into database and returns +// last inserted Id on success. +func AddJdBondInterface(logger *log.Logger, m *JdBondInterface) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetJdBondInterfaceById retrieves JdBondInterface by Id. Returns error if +// Id doesn't exist +func GetJdBondInterfaceById(logger *log.Logger, id int64) (v *JdBondInterface, err error) { + v = &JdBondInterface{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetJDBondInterfaceBysn(logger *log.Logger, sn string) (v *JdBondInterface, err error) { + v = &JdBondInterface{} + err = dao.Where(logger, dao.IronicRdb, "sn = ? and is_del = 0", sn).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetAllJdBondInterface(logger *log.Logger, query map[string]interface{}) (ml []*JdBondInterface, err error) { + + var db = dao.Model(logger, dao.IronicRdb, JdBondInterface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiJdBondInterface retrieves all JdBondInterface matches certain condition. Returns empty list if +// no records exist +func GetMultiJdBondInterface(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*JdBondInterface, err error) { + + var db = dao.Model(logger, dao.IronicRdb, JdBondInterface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateJdBondInterface updates JdBondInterface by Id and returns error if +// the record to be updated doesn't exist +func UpdateJdBondInterfaceById(logger *log.Logger, m *JdBondInterface) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, JdBondInterface{}).Where("id = ?", m.ID).Updates(m).Error +} + +func GetOneInterface(logger *log.Logger, query map[string]interface{}) (l *JdBondInterface, err error) { + l = &JdBondInterface{} + var db = dao.Model(logger, dao.IronicRdb, JdBondInterface{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} diff --git a/bmp-scheduler/dao/jdSwitchDao/jdSwitchDao.go b/bmp-scheduler/dao/jdSwitchDao/jdSwitchDao.go new file mode 100644 index 0000000..f5c38ca --- /dev/null +++ b/bmp-scheduler/dao/jdSwitchDao/jdSwitchDao.go @@ -0,0 +1,125 @@ +package jdSwitchDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// JdSwitch 零售中台网络交换机表 +type JdSwitch struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // 自增id + SwitchIP string `gorm:"unique;column:switch_ip;type:varchar(32);not null" json:"switch_ip"` // 交换机ip + Cidr string `gorm:"column:cidr;type:varchar(32)" json:"cidr"` // 配置的内网cidr + Mask string `gorm:"column:mask;type:varchar(32)" json:"mask"` // 配置的内网掩码 + Gateway string `gorm:"column:gateway;type:varchar(32)" json:"gateway"` // 配置的网关 + PodID int `gorm:"column:pod_id;type:int(11)" json:"pod_id"` // pod网络id + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime;not null" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(2);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *JdSwitch) TableName() string { + return "jd_switch" +} + +// AddJdSwitch insert a new JdSwitch into database and returns +// last inserted Id on success. +func AddJdSwitch(logger *log.Logger, m *JdSwitch) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetJdSwitchById retrieves JdSwitch by Id. Returns error if +// Id doesn't exist +func GetJdSwitchById(logger *log.Logger, id int64) (v *JdSwitch, err error) { + v = &JdSwitch{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetOneJdSwitch(logger *log.Logger, query map[string]interface{}) (l *JdSwitch, err error) { + l = &JdSwitch{} + var db = dao.Model(logger, dao.IronicRdb, JdSwitch{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetSwitchCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + var db = dao.Model(logger, dao.IronicRdb, JdSwitch{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return + +} + +// GetAllJdSwitch retrieves all JdSwitch matches certain condition. Returns empty list if +// no records exist +func GetAllJdSwitch(logger *log.Logger, query map[string]interface{}) (ml []*JdSwitch, err error) { + + var db = dao.Model(logger, dao.IronicRdb, JdSwitch{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiJdSwitch retrieves pages JdSwitch matches certain condition. Returns empty list if +// no records exist +func GetMultiJdSwitch(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*JdSwitch, err error) { + + var db = dao.Model(logger, dao.IronicRdb, JdSwitch{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + + db = db.Order(strings.Join(orderConditions, ",")) + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateJdSwitch updates JdSwitch by Id and returns error if +// the record to be updated doesn't exist +func UpdateJdSwitchById(logger *log.Logger, m *JdSwitch) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, JdSwitch{}).Where("id = ?", m.ID).Updates(m).Error +} + +func GetBySwitchIp(logger *log.Logger, switch_ip string) (v *JdSwitch, err error) { + v = &JdSwitch{} + err = dao.Where(logger, dao.IronicRdb, "switch_ip = ? and is_del = 0", switch_ip).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} diff --git a/bmp-scheduler/dao/keypairDao/keypairDao.go b/bmp-scheduler/dao/keypairDao/keypairDao.go new file mode 100644 index 0000000..9d3272f --- /dev/null +++ b/bmp-scheduler/dao/keypairDao/keypairDao.go @@ -0,0 +1,130 @@ +package keypairDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// Keypair 密钥对 +type Keypair struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + UUID string `gorm:"unique;column:uuid;type:varchar(36);not null" json:"uuid"` // 密钥对ID + Tenant string `gorm:"column:tenant;type:varchar(64);not null" json:"tenant"` // 租户 + Region string `gorm:"column:region;type:varchar(32);not null" json:"region"` // region + Az string `gorm:"column:az;type:varchar(32)" json:"az"` // az + Name string `gorm:"column:name;type:varchar(64);not null" json:"name"` // 密钥对名称 + PublicKey string `gorm:"column:public_key;type:varchar(2000);not null" json:"public_key"` // 公钥内容 + FingerPrint string `gorm:"column:finger_print;type:varchar(64);not null" json:"finger_print"` // 指纹 + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *Keypair) TableName() string { + return "keypair" +} + +// AddKeypair insert a new Keypair into database and returns +// last inserted Id on success. +func AddKeypair(logger *log.Logger, m *Keypair) (id int64, err error) { + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetKeypairById retrieves Keypair by Id. Returns error if +// Id doesn't exist +func GetKeypairById(logger *log.Logger, id int64) (v *Keypair, err error) { + v = &Keypair{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetOneKeypair(logger *log.Logger, query map[string]interface{}) (l *Keypair, err error) { + l = &Keypair{} + var db = dao.Model(logger, dao.IronicRdb, Keypair{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// GetAllKeypair retrieves all Keypair matches certain condition. Returns empty list if +// no records exist +func GetAllKeypair(logger *log.Logger, query map[string]interface{}) (ml []*Keypair, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Keypair{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiKeypair retrieves all Keypair matches certain condition. Returns empty list if +// no records exist +func GetMultiKeypair(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Keypair, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Keypair{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetKeypairCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Keypair{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return + +} + +// UpdateKeypair updates Keypair by Id and returns error if +// the record to be updated doesn't exist +func UpdateKeypairById(logger *log.Logger, m *Keypair) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Keypair{}).Where("id = ?", m.ID).Updates(m).Error +} + +func GetByUuidAndTenant(logger *log.Logger, uuid, tenant string) (v *Keypair, err error) { + v = &Keypair{} + err = dao.Where(logger, dao.IronicRdb, "uuid = ? and tenant = ? and is_del = 0", uuid, tenant).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func QueryByParam(logger *log.Logger, query map[string]interface{}, offset, limit int64) (ml []*Keypair, err error) { + return GetMultiKeypair(logger, query, nil, nil, nil, offset, limit) +} diff --git a/bmp-scheduler/dao/mailDao/mailDao.go b/bmp-scheduler/dao/mailDao/mailDao.go new file mode 100644 index 0000000..a9399fa --- /dev/null +++ b/bmp-scheduler/dao/mailDao/mailDao.go @@ -0,0 +1,68 @@ +package mailDao + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// MailMessage message +type MailMessage struct { + //以下为消息通用字段 + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + // 邮件服务器地址 + ServerAddr string `gorm:"column:server_addr;type:varchar(255);not null" json:"server_addr"` + // 邮件服务器端口 + ServerPort string `gorm:"column:server_port;type:varchar(255);not null" json:"server_port"` + // 管理员邮箱 + AdminAddr string `gorm:"column:admin_addr;type:varchar(255);not null" json:"admin_addr"` + // 管理员邮箱密码 + AdminPass string `gorm:"column:admin_pass;type:varchar(255);not null" json:"admin_pass"` + //收件人邮箱 + To string `gorm:"column:to;type:varchar(255);not null" json:"to"` + // 是否推送邮件告警0不推送,1推送 + IsPush string `gorm:"column:is_push;type:type:varchar(8);not null" json:"is_push"` + // 是否删除0未删除 1已删除 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` +} + +func (t *MailMessage) TableName() string { + return "mail_message" +} + +// AddMailMessage insert a new Os into database and returns +// last inserted Id on success. +func AddMailMessage(logger *log.Logger, m *MailMessage) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetMailMessage retrieves Os by Id. Returns error if +// Id doesn't exist +func GetMailMessage(logger *log.Logger) (v *MailMessage, err error) { + v = &MailMessage{} + err = dao.Where(logger, dao.IronicRdb, "is_del = 0").Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func UpdateMailMessage(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = time.Now().Unix() + var db = dao.Model(logger, dao.IronicWdb, MailMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func UpdateMailAnywhere(logger *log.Logger, m *MailMessage) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, MailMessage{}).Save(m).Error +} diff --git a/bmp-scheduler/dao/manufacturerDao/manufacturerDao.go b/bmp-scheduler/dao/manufacturerDao/manufacturerDao.go new file mode 100644 index 0000000..28e2fc4 --- /dev/null +++ b/bmp-scheduler/dao/manufacturerDao/manufacturerDao.go @@ -0,0 +1,103 @@ +package manufacturerDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// Manufacturer 产品型号信息 +type Manufacturer struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + DeviceType string `gorm:"column:device_type;type:varchar(100);not null" json:"device_type"` // 设备类型 + Manufacturer string `gorm:"column:manufacturer;type:varchar(64);not null" json:"manufacturer"` // 厂商 + ProductName string `gorm:"column:product_name;type:varchar(128);not null" json:"product_name"` // 产品型号名称 + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除:1删除,0未删除 +} + +func (t *Manufacturer) TableName() string { + return "manufacturer" +} + +// AddManufacturer insert a new Manufacturer into database and returns +// last inserted Id on success. +func AddManufacturer(logger *log.Logger, m *Manufacturer) (id int64, err error) { + + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetManufacturerById retrieves Manufacturer by Id. Returns error if +// Id doesn't exist +func GetManufacturerById(logger *log.Logger, id int64) (v *Manufacturer, err error) { + v = &Manufacturer{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetOneManufacturer(logger *log.Logger, query map[string]interface{}) (v *Manufacturer, err error) { + v = &Manufacturer{} + var db = dao.Model(logger, dao.IronicRdb, Manufacturer{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(v).Error + if err != nil { + return nil, err + } + return v, nil + +} + +// GetAllManufacturer retrieves all Manufacturer matches certain condition. Returns empty list if +// no records exist +func GetAllManufacturer(logger *log.Logger, query map[string]interface{}) (ml []*Manufacturer, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Manufacturer{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetMultiManufacturer(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Manufacturer, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Manufacturer{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateManufacturer updates Manufacturer by Id and returns error if +// the record to be updated doesn't exist +func UpdateManufacturerById(logger *log.Logger, m *Manufacturer) (err error) { + m.UpdateTime = time.Now() + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Manufacturer{}).Where("id = ?", m.ID).Updates(m).Error +} diff --git a/bmp-scheduler/dao/messageDao/messageDao.go b/bmp-scheduler/dao/messageDao/messageDao.go new file mode 100644 index 0000000..52233d3 --- /dev/null +++ b/bmp-scheduler/dao/messageDao/messageDao.go @@ -0,0 +1,116 @@ +package messageDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// WebMessage message +type WebMessage struct { + //以下为消息通用字段 + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + MessageID string `gorm:"column:message_id;type:varchar(255);not null" json:"message_id"` // message_id + UserID string `gorm:"index:i_message_userid;column:user_id;type:varchar(255);not null" json:"user_id"` // user_id + UserName string `gorm:"column:user_name;type:varchar(255);not null" json:"user_name"` // user_id + ResourceType string `gorm:"column:resource_type;type:varchar(255);not null" json:"resource_type"` // 资源类型 + Result string `gorm:"column:result;type:varchar(255);not null" json:"result"` // 操作结果 + FinishTime int `gorm:"column:finish_time;type:int(11);not null" json:"finish_time"` // 完成时间戳 + HasRead int8 `gorm:"index:i_message_read;column:has_read;type:tinyint(4);not null" json:"has_read"` // 0未读, 1已读 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 + MessageType string `gorm:"column:message_type;type:varchar(255);not null" json:"message_type"` // 消息类型 + MessageSubType string `gorm:"column:message_sub_type;type:varchar(255);not null" json:"message_sub_type"` // 消息子类型 + InstanceID string `gorm:"column:instance_id;type:varchar(255);not null" json:"instance_id"` //实例id + // 实例name + InstanceName string `gorm:"column:instance_name;type:varchar(255);not null" json:"instance_name"` + SN string `gorm:"column:sn;type:varchar(255);not null" json:"sn"` //设备sn + Detail string `gorm:"column:detail;type:varchar(4096);not null" json:"detail"` //详情,带外监控的消息比较特殊 + + //以下为带外故障消息专属字段 + FaultType string `gorm:"column:fault_type;type:varchar(10);not null" json:"fault_type"` // 故障类型 + Content string `gorm:"column:content;type:varchar(4096);not null" json:"content"` + LogID string `gorm:"column:logid;type:varchar(256);not null" json:"logid"` //带外原始日志的id + AlertTime int `gorm:"column:alert_time;type:int(11);not null" json:"alert_time"` //故障告警时间 + AlertCount int `gorm:"column:alert_count;type:int(11);not null" json:"alert_count"` //告警次数,始终为1 + + //以下为许可证到期消息专属字段 + LicenseName string `gorm:"column:license_name;type:varchar(64);not null" json:"license_name"` // 版本名称 + LicenseNumber string `gorm:"column:license_number;type:varchar(64);not null" json:"license_number"` // 版本号 + LienseStartTime int `gorm:"column:license_start_time;type:int(11);not null" json:"license_start_time"` //开始时间 + LienseEndTime int `gorm:"column:license_end_time;type:int(11);not null" json:"license_end_time"` //结束时间 + +} + +func (t *WebMessage) TableName() string { + return "web_message" +} + +// AddWebMessage insert a new Os into database and returns +// last inserted Id on success. +func AddWebMessage(logger *log.Logger, m *WebMessage) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetOsById retrieves Os by Id. Returns error if +// Id doesn't exist +func GetWebMessageById(logger *log.Logger, id int64) (v *WebMessage, err error) { + v = &WebMessage{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllOs retrieves all os matches certain condition. Returns empty list if +// no records exist +func GetAllWebMessagesByUserId(logger *log.Logger, userId string) (ml []*WebMessage, err error) { + + query := map[string]interface{}{ + "user_id": userId, + "is_del": 0, + } + var db = dao.Model(logger, dao.IronicRdb, WebMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return + +} + +// GetMultiOs retrieves all Os matches certain condition. Returns empty list if +// no records exist +func GetMultiWebMessagesByUserId(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*WebMessage, err error) { + + var db = dao.Model(logger, dao.IronicRdb, WebMessage{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateOs updates Os by Id and returns error if +// the record to be updated doesn't exist +func UpdateOsById(logger *log.Logger, m *WebMessage) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, WebMessage{}).Where("id = ?", m.ID).Updates(m).Error +} diff --git a/bmp-scheduler/dao/osDao/osDao.go b/bmp-scheduler/dao/osDao/osDao.go new file mode 100644 index 0000000..188750d --- /dev/null +++ b/bmp-scheduler/dao/osDao/osDao.go @@ -0,0 +1,105 @@ +package osDao + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "fmt" + log "git.jd.com/cps-golang/log" + "strings" +) + +// Os os +type Os struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + OsID string `gorm:"column:os_id" json:"osId"` // 操作系统uuid + OsName string `gorm:"column:os_name" json:"OsName"` // 操作系统名称 + OsType string `gorm:"column:os_type" json:"osType"` // 操作系统分类:linux/windows + //Platform string `gorm:"column:platform" json:"platform"` // suse/centos/ubuntu + Architecture string `gorm:"column:architecture" json:"architecture"` // 架构:x86/x64/i386/ + Bits int `gorm:"column:bits" json:"bits"` // 指令宽度:64/32位 + OsVersion string `gorm:"column:os_version" json:"osVersion"` // 操作系统版本 + SysUser string `gorm:"column:sys_user" json:"sysUser"` // 管理员账户 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Os) TableName() string { + return "os" +} + +// AddOs insert a new Os into database and returns +// last inserted Id on success. +func AddOs(logger *log.Logger, m *Os) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetOsById retrieves Os by Id. Returns error if +// Id doesn't exist +func GetOsById(logger *log.Logger, id int64) (v *Os, err error) { + v = &Os{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetOsByUuid retrieves Os by Uuid. Returns error if +// Id doesn't exist +func GetOsByUuid(logger *log.Logger, uuid string) (v *Os, err error) { + v = &Os{} + err = dao.Where(logger, dao.IronicRdb, "os_id = ? and is_del = 0", uuid).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllOs retrieves all os matches certain condition. Returns empty list if +// no records exist +func GetAllOs(logger *log.Logger, query map[string]interface{}) (ml []*Os, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Os{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiOs retrieves all Os matches certain condition. Returns empty list if +// no records exist +func GetMultiOs(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Os, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Os{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateOs updates Os by Id and returns error if +// the record to be updated doesn't exist +func UpdateOsById(logger *log.Logger, m *Os) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Os{}).Where("id = ?", m.ID).Updates(m).Error +} diff --git a/bmp-scheduler/dao/queryDao.go b/bmp-scheduler/dao/queryDao.go new file mode 100644 index 0000000..29c4c7a --- /dev/null +++ b/bmp-scheduler/dao/queryDao.go @@ -0,0 +1,129 @@ +package dao + +import ( + clog "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +// SELECT * FROM `foods` LIMIT 1 +//eg. db.Take(logger, rdb, &food) +func Take(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Take(out, where...) +} + +// SELECT * FROM `foods` ORDER BY `foods`.`id` ASC LIMIT 1 +//eg. db.First(logger, rdb, &food) +func First(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.First(out, where...) +} + +// SELECT * FROM `foods` ORDER BY `foods`.`id` DESC LIMIT 1 +//eg. db.Last(logger, rdb, &food) +func Last(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Last(out, where...) +} + +// SELECT * FROM `foods` 可单可复 +//eg. db.Find(logger, rdb, &foods) +func Find(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Find(out, where...) +} + +// // 查询一列值 +//eg. Model(Food{}).Pluck("title", &titles) +// func Pluck(logger *clog.Logger, model interface{}, column string, target interface{}) error { +// //等价于:SELECT title FROM `foods` 提取了title字段,保存到titles变量 +// //这里Model函数是为了绑定一个模型实例,可以从里面提取表名。 +// gl := &gLogger{traceid: logger.GetPoint("logid").(string)} +// db := gdb.New() +// db.SetLogger(gl) +// return gdb.Model(model).Pluck("title", target).Error +// } + +// 设置where条件 +//eg. dao.Where(logger, rdb, "id = ?", 10).Take(&food) +//eg. dao.Where(logger, rdb, "id in (?)", []int{1,2,5,6}).Take(&food) +//eg. dao.Where(logger, rdb, "create_time >= ? and create_time <= ?", "2018-11-06 00:00:00", "2018-11-06 23:59:59").Find(&foods) +//eg. dao.Where(logger, rdb, "title like ?", "%可乐%").Find(&foods) +func Where(logger *clog.Logger, gdb *gorm.DB, query interface{}, args ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Where(query, args...) +} + +// 指定返回的字段 +//eg. dao.Select(logger, rdb, "id,title").Where("id = ?", 1).Take(&food) +//eg. dao.Model(logger, rdb, Food{}).Select("count(*) as total").Pluck("total", &total) +func Select(logger *clog.Logger, gdb *gorm.DB, query interface{}, args ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Select(query, args...) +} + +// 指定绑定的模型,一般和Pluck一起使用 +//eg. dao.Model(logger, rdb, Food{}).Select("count(*) as total").Pluck("total", &total) +func Model(logger *clog.Logger, gdb *gorm.DB, value interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Model(value) +} + +// 指定order +//eg. dao.Order(logger, rdb, "create_time desc").Limit(10).Offset(0).Find(&foods) +//eg. dao.Where(logger, rdb, "create_time >= ?", "2018-11-06 00:00:00").Order("create_time desc").Find(&foods) +func Order(logger *clog.Logger, gdb *gorm.DB, value interface{}, reorder ...bool) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Order(value, reorder...) +} + +// limit +//eg. dao.Order(logger, rdb, "create_time desc").Limit(10).Offset(0).Find(&foods) +//eg. dao.Limit(logger, rdb, 10).Offset(0).Find(&foods) +func Limit(logger *clog.Logger, gdb *gorm.DB, limit interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Limit(limit) +} + +// Offset +//eg. dao.Order(logger, rdb, "create_time desc").Limit(10).Offset(0).Find(&foods) +//eg. dao.Offset(logger, rdb, 10).Find(&foods) +func Offset(logger *clog.Logger, gdb *gorm.DB, limit interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Offset(limit) +} + +//eg. dao.Model(logger, rdb, Food{}).Count(&total) +// COUNT + +//eg. dao.Model(logger, rdb, Food{}).Select("type, count(*) as total").Group("type").Having("total > 0").Scan(&results) +//group by,必须要搭配select一起使用 + +//Raw +//eg. dao.Raw(logger, rdb, sql, "2018-11-06 00:00:00").Scan(&results) +func Raw(logger *clog.Logger, gdb *gorm.DB, sql string, values ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Raw(sql, values...) +} diff --git a/bmp-scheduler/dao/rDeviceTypeImagePartitionDao/rDeviceTypeImagePartitionDao.go b/bmp-scheduler/dao/rDeviceTypeImagePartitionDao/rDeviceTypeImagePartitionDao.go new file mode 100644 index 0000000..bddd6f6 --- /dev/null +++ b/bmp-scheduler/dao/rDeviceTypeImagePartitionDao/rDeviceTypeImagePartitionDao.go @@ -0,0 +1,138 @@ +package rDeviceTypeImagePartitionDao + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "fmt" + log "git.jd.com/cps-golang/log" + "strings" +) + +// RDeviceTypeImagePartition device_type/image +type RDeviceTypeImagePartition struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像ID + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型 + BootMode string `gorm:"column:boot_mode" json:"bootMode"` // boot类型:bios、uefi + PartitionType string `gorm:"column:partition_type" json:"partitionType"` // 分区类型:root、boot、system、data + PartitionSize int `gorm:"column:partition_size" json:"partitionSize"` // 分区大小,单位MB + PartitionFsType string `gorm:"column:partition_fs_type" json:"partitionFsType"` // 文件系统类型:xfs + PartitionMountPoint string `gorm:"column:partition_mount_point" json:"partitionMountPoint"` // 分区目录 + PartitionLabel string `gorm:"column:partition_label" json:"partitionLabel"` // 分区标签:l_分区目录 + SystemDiskLabel string `gorm:"column:system_disk_label" json:"systemDiskLabel"` // 系统盘分区格式:gpt、msdos(做完RAID系统盘大于4T必用gpt) + DataDiskLabel string `gorm:"column:data_disk_label" json:"dataDiskLabel"` // 数据盘分区格式:gpt、msdos + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除(0-未删, 1-已删) +} + +func (t *RDeviceTypeImagePartition) TableName() string { + return "r_device_type_image_partition" +} + +// AddRDeviceTypeImage insert a new RDeviceTypeImage into database and returns +// last inserted Id on success. +func AddRDeviceTypeImagePartition(logger *log.Logger, m *RDeviceTypeImagePartition) (id int64, err error) { + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func AddMultiRDeviceTypeImagePartition(logger *log.Logger, m []*RDeviceTypeImagePartition) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, r := range m { + if err := tx.Create(r).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetRDeviceTypeImageById retrieves RDeviceTypeImage by Id. Returns error if +// Id doesn't exist +func GetRDeviceTypeImagePartitionById(logger *log.Logger, id int64) (v *RDeviceTypeImagePartition, err error) { + v = &RDeviceTypeImagePartition{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetAllRDeviceTypeImagePartition(logger *log.Logger, query map[string]interface{}) (ml []*RDeviceTypeImagePartition, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImagePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiRDeviceTypeImage retrieves all RDeviceTypeImage matches certain condition. Returns empty list if +// no records exist +func GetMultiRDeviceTypeImagePartition(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*RDeviceTypeImagePartition, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImagePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateRDeviceTypeImage updates RDeviceTypeImage by Id and returns error if +// the record to be updated doesn't exist +func UpdateRDeviceTypeImagePartitionById(logger *log.Logger, m *RDeviceTypeImagePartition) (err error) { + return dao.Model(logger, dao.IronicWdb, RDeviceTypeImagePartition{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateMultiRDeviceTypeImagePartition(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + //updates["update_time"] = time.Now() + var db = dao.Model(logger, dao.IronicWdb, RDeviceTypeImagePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func GetOneRDeviceTypeImagePartition(logger *log.Logger, query map[string]interface{}) (l *RDeviceTypeImagePartition, err error) { + l = &RDeviceTypeImagePartition{} + var db = dao.Model(logger, dao.IronicRdb, RDeviceTypeImagePartition{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetByDeviceTypeAndImageId(logger *log.Logger, deviceTypeId, imageId string) (ml []*RDeviceTypeImagePartition, err error) { + sql := fmt.Sprintf("select * from r_device_type_image_partition r where device_type_id='%s' and image_id='%s' and is_del=0", deviceTypeId, imageId) //or device_type='common' + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-scheduler/dao/rDeviceVolumeDisksDao/rDeviceVolumeDisksDao.go b/bmp-scheduler/dao/rDeviceVolumeDisksDao/rDeviceVolumeDisksDao.go new file mode 100644 index 0000000..74b81c8 --- /dev/null +++ b/bmp-scheduler/dao/rDeviceVolumeDisksDao/rDeviceVolumeDisksDao.go @@ -0,0 +1,77 @@ +package rDeviceVolumeDisksDao + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// RDeviceVolumeDisks 设备-卷-磁盘 关系表 +type RDeviceVolumeDisks struct { + ID uint32 `gorm:"primary_key;column:id;type:int(11) unsigned;not null" json:"-"` // 主键 + DeviceID string `gorm:"index:i_device_id;column:device_id;type:varchar(255);not null" json:"device_id"` // 设备uuid + VolumeID string `gorm:"index:i_volume_id;column:volume_id;type:varchar(255);not null" json:"volume_id"` // volume uuid + VolumeType string `gorm:"column:volume_type;type:varchar(255);not null" json:"volume_type"` // data|system + DiskID string `gorm:"index:i_disk_id;column:disk_id;type:varchar(255);not null" json:"disk_id"` // disk uuid + CreatedBy string `gorm:"column:created_by;type:varchar(255);not null" json:"created_by"` // 创建者 + UpdatedBy string `gorm:"column:updated_by;type:varchar(255);not null" json:"updated_by"` // 更新者 + CreatedTime int `gorm:"column:created_time;type:int(255);not null" json:"created_time"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time;type:int(11);not null" json:"updated_time"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time;type:int(11);not null" json:"deleted_time"` // 删除时间 + IsDel int8 `gorm:"index:i_is_del;column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 +} + +func (t *RDeviceVolumeDisks) TableName() string { + return "r_device_volume_disks" +} + +// GetAllRDeviceTypeRaid retrieves all raid matches certain condition. Returns empty list if +// no records exist +func GetAllRDeviceVolumeDisks(logger *log.Logger, query map[string]interface{}) (ml []*RDeviceVolumeDisks, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RDeviceVolumeDisks{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetRDeviceTypeRaidById retrieves RDeviceTypeRaid by Id. Returns error if +// Id doesn't exist +func GetRDeviceVolumeDiskByVolumeIdDiskId(logger *log.Logger, volumeId, diskId string) (v *RDeviceVolumeDisks, err error) { + v = &RDeviceVolumeDisks{} + err = dao.Where(logger, dao.IronicRdb, "volume_id = ? and disk_id = ? and is_del = 0", volumeId, diskId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func UpdateMultiRDeviceVolumeDisk(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = int(time.Now().Unix()) + var db = dao.Model(logger, dao.IronicWdb, RDeviceVolumeDisks{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func AddMultiRDeviceVolumeDisk(logger *log.Logger, m []*RDeviceVolumeDisks) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, r := range m { + //r.CreateTime = time.Now() + //r.UpdateTime = time.Now() + if err := tx.Create(r).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} diff --git a/bmp-scheduler/dao/rInstanceSshkeyDao/rInstanceSshkey.go b/bmp-scheduler/dao/rInstanceSshkeyDao/rInstanceSshkey.go new file mode 100644 index 0000000..adda289 --- /dev/null +++ b/bmp-scheduler/dao/rInstanceSshkeyDao/rInstanceSshkey.go @@ -0,0 +1,184 @@ +package rInstanceSshkeyDao + +import ( + "fmt" + "strings" + "time" + + //"coding.jd.com/aidc-bmp/bmp-scheduler/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// rInstanceSshkey device_type/image关系 +type RInstanceSshkey struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + InstanceID string `gorm:"column:instance_id" json:"instanceId"` // 实例ID + SSHkeyID string `gorm:"column:sshkey_id" json:"sshkeyId"` // sshkeyid + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *RInstanceSshkey) TableName() string { + return "r_instance_sshkey" +} + +// AddrInstanceSshkey insert a new rInstanceSshkey into database and returns +// last inserted Id on success. +func AddrInstanceSshkey(logger *log.Logger, m *RInstanceSshkey) (id int64, err error) { + // + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +func AddMultirInstanceSshkey(logger *log.Logger, m []*RInstanceSshkey) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, r := range m { + //r.CreateTime = time.Now() + //r.UpdateTime = time.Now() + if err := tx.Create(r).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetrInstanceSshkeyById retrieves rInstanceSshkey by Id. Returns error if +// Id doesn't exist +func GetrInstanceSshkeyById(logger *log.Logger, id int64) (v *RInstanceSshkey, err error) { + v = &RInstanceSshkey{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllCommand retrieves all Command matches certain condition. Returns empty list if +// no records exist +func GetAllrInstanceSshkey(logger *log.Logger, query map[string]interface{}) (ml []*RInstanceSshkey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RInstanceSshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultirInstanceSshkey retrieves all rInstanceSshkey matches certain condition. Returns empty list if +// no records exist +func GetMultirInstanceSshkey(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*RInstanceSshkey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RInstanceSshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdaterInstanceSshkey updates rInstanceSshkey by Id and returns error if +// the record to be updated doesn't exist +func UpdaterInstanceSshkeyById(logger *log.Logger, m *RInstanceSshkey, deviceTypeId, imageId string) (err error) { + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RInstanceSshkey{}).Where("device_type_id = ? and image_id = ? and is_del = ?", deviceTypeId, imageId, 0).Update(m).Error +} + +func UpdateMultirInstanceSshkey(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + updates["update_time"] = time.Now() + var db = dao.Model(logger, dao.IronicWdb, RInstanceSshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +//func AssociatedImageMultirInstanceSshkey(logger *log.Logger, items []*RInstanceSshkey) (err error) { +// //paris := []string{} +// for _, item := range items { +// //paris = append(paris, fmt.Sprintf("('%s', '%s')", item.DeviceTypeID, item.ImageID)) +// err = dao.Model(logger, dao.IronicRdb, RInstanceSshkey{}).Where("device_type_id = ? and image_id = ? and is_del = 0", item.DeviceTypeID, item.ImageID).Update(item).Error +// } +// //fmt.Sprintf(`(device_type_id, image_id) in (%s)`, strings.Join(paris, ",")) +// +// //updates := map[string]interface{}{ +// // "is_del": 0, +// // "update_time": time.Now(), +// //} +// return +//} + +func GetOnerInstanceSshkey(logger *log.Logger, query map[string]interface{}) (l *RInstanceSshkey, err error) { + l = &RInstanceSshkey{} + var db = dao.Model(logger, dao.IronicRdb, RInstanceSshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetByDeviceTypeIDAndImageID(logger *log.Logger, deviceTypeID, imageID string) (l *RInstanceSshkey, err error) { + l = &RInstanceSshkey{} + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and image_id = ? and is_del = ?", deviceTypeID, imageID, 0).Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} +func GetByDeviceTypeID(logger *log.Logger, deviceTypeID string) (l []*RInstanceSshkey, err error) { + err = dao.Where(logger, dao.IronicRdb, "device_type_id = ? and is_del = ?", deviceTypeID, 0).Find(&l).Error + if err != nil { + return nil, err + } + return l, nil +} + +func GetByDeviceTypeAndImageIdPatition(logger *log.Logger, device_type, image_id string) (ml []*RInstanceSshkey, err error) { + + sql := fmt.Sprintf("select r from r_device_type_image r where (device_type='%s' or device_type='common') and image_id='%s' and is_del=0", device_type, image_id) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} +func QueryDeviceTypeImagesCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, RInstanceSshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return n, err + } + err = db.Count(&n).Error + return +} diff --git a/bmp-scheduler/dao/rInstanceVolumeRaidDao/rInstanceVolumeRaidDao.go b/bmp-scheduler/dao/rInstanceVolumeRaidDao/rInstanceVolumeRaidDao.go new file mode 100644 index 0000000..d9ef36a --- /dev/null +++ b/bmp-scheduler/dao/rInstanceVolumeRaidDao/rInstanceVolumeRaidDao.go @@ -0,0 +1,58 @@ +package rInstanceVolumeRaidDao + +import ( + + //"coding.jd.com/aidc-bmp/bmp-scheduler/logic/baseLogic" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// RInstanceVolumeRaid 实例每个数据卷选择的raid +type RInstanceVolumeRaid struct { + ID int `gorm:"primary_key;column:id;type:int(11) unsigned;not null" json:"-"` // 主键 + InstanceID string `gorm:"index:i_instance_id;column:instance_id;type:varchar(255);not null" json:"instance_id"` // instance uuid + VolumeID string `gorm:"column:volume_id;type:varchar(255);not null" json:"volume_id"` // volume uuid + VolumeType string `gorm:"index:i_volume_type;column:volume_type;type:varchar(255);not null" json:"volume_type"` // data|system + RaidCan string `gorm:"column:raid_can;type:varchar(16);not null" json:"raid_can"` // RAID配置: (RAID,NO RAID) + RaidID string `gorm:"column:raid_id;type:varchar(255);not null" json:"raid_id"` // RAID模式:raidid,一个一条 + RaidName string `gorm:"column:raid_name;type:varchar(255);not null" json:"raid_name"` // RAID名称 + CreatedBy string `gorm:"column:created_by;type:varchar(255);not null" json:"created_by"` // 创建者 + UpdatedBy string `gorm:"column:updated_by;type:varchar(255);not null" json:"updated_by"` // 更新者 + CreatedTime int `gorm:"column:created_time;type:int(255);not null" json:"created_time"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time;type:int(11);not null" json:"updated_time"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time;type:int(11);not null" json:"deleted_time"` // 删除时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 +} + +func (t *RInstanceVolumeRaid) TableName() string { + return "r_instance_volume_raid" +} + +// AddVolume insert a new Volume into database and returns +// last inserted Id on success. +func AddRInstanceVolumeRaid(logger *log.Logger, m *RInstanceVolumeRaid) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetVolumeById retrieves Volume by Id. Returns error if +// Id doesn't exist +func GetRInstanceVolumeRaids(logger *log.Logger, instanceId string) (ml []*RInstanceVolumeRaid, err error) { + ml = []*RInstanceVolumeRaid{} + err = dao.Where(logger, dao.IronicRdb, "instance_id = ? and is_del = 0", instanceId).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil +} + +// UpdateVolume updates Volume by Id and returns error if +// the record to be updated doesn't exist +func UpdateRInstanceVolumeRaidById(logger *log.Logger, m *RInstanceVolumeRaid) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RInstanceVolumeRaid{}).Where("id = ?", m.ID).Save(m).Error +} diff --git a/bmp-scheduler/dao/rVolumeRaidDao/rVolumeRaidDao.go b/bmp-scheduler/dao/rVolumeRaidDao/rVolumeRaidDao.go new file mode 100644 index 0000000..37be109 --- /dev/null +++ b/bmp-scheduler/dao/rVolumeRaidDao/rVolumeRaidDao.go @@ -0,0 +1,120 @@ +package rVolumeRaidDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// Volume RAID 关联关系表 +type RVolumeRaid struct { + ID int `gorm:"primaryKey;column:id" json:"-"` // 主键 + VolumeID string `gorm:"column:volume_id" json:"volumeId"` // 卷uuid + VolumeType string `gorm:"column:volume_type;type:varchar(255);not null" json:"volume_type"` // data|system + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型uuid + + RaidCan string `gorm:"column:raid_can" json:"raidCan"` // RAID配置: (RAID,NO RAID) + RaidID string `gorm:"column:raid_id" json:"raidId"` // RAID模式:RAID1,RIAD10等 + RaidName string `gorm:"column:raid_name" json:"raidName"` // RAID名称 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *RVolumeRaid) TableName() string { + return "r_volume_raid" +} + +// AddVolume insert a new Volume into database and returns +// last inserted Id on success. +func AddRVolumeRaid(logger *log.Logger, m *RVolumeRaid) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetVolumeById retrieves Volume by Id. Returns error if +// Id doesn't exist +func GetRVolumeRaidsByVId(logger *log.Logger, VolumeId string) (ml []*RVolumeRaid, err error) { + ml = []*RVolumeRaid{} + err = dao.Where(logger, dao.IronicRdb, "volume_id = ? and is_del = 0", VolumeId).Find(&ml).Error + if err != nil { + return nil, err + } + return ml, nil +} + +// GetVolumeByUuid retrieves Volume by Uuid. Returns error if +// Id doesn't exist +func GetRVolumeRaidCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, RVolumeRaid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAllVolume retrieves all Volume matches certain condition. Returns empty list if +// no records exist +func GetAllRVolumeRaid(logger *log.Logger, query map[string]interface{}) (ml []*RVolumeRaid, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RVolumeRaid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiVolume retrieves all Volume matches certain condition. Returns empty list if +// no records exist +func GetMultiRVolumeRaid(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*RVolumeRaid, err error) { + + var db = dao.Model(logger, dao.IronicRdb, RVolumeRaid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateVolume updates Volume by Id and returns error if +// the record to be updated doesn't exist +func UpdateRVolumeRaidById(logger *log.Logger, m *RVolumeRaid) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, RVolumeRaid{}).Where("id = ?", m.ID).Save(m).Error +} + +func UpdateRVolumeRaidByWhere(logger *log.Logger, query map[string]interface{}, updates *RVolumeRaid) (err error) { + var db = dao.Model(logger, dao.IronicWdb, RVolumeRaid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} diff --git a/bmp-scheduler/dao/raidDao/raidDao.go b/bmp-scheduler/dao/raidDao/raidDao.go new file mode 100644 index 0000000..5c9cc91 --- /dev/null +++ b/bmp-scheduler/dao/raidDao/raidDao.go @@ -0,0 +1,132 @@ +package raidDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// Raid raid +type Raid struct { + ID uint64 `gorm:"primaryKey;column:id" json:"-"` // ID + RaidID string `gorm:"column:raid_id" json:"raidId"` // raid uuid + Name string `gorm:"column:name" json:"name"` // raid类型 noraid,raid0,raid1,raid10 + DescriptionEn string `gorm:"column:description_en" json:"descriptionEn"` // RAID英文描述 + DescriptionZh string `gorm:"column:description_zh" json:"descriptionZh"` // RAID中文描述 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Raid) TableName() string { + return "raid" +} + +// AddRaid insert a new Raid into database and returns +// last inserted Id on success. +func AddRaid(logger *log.Logger, m *Raid) (id int64, err error) { + + m.CreatedTime = int(time.Now().Unix()) + m.UpdatedTime = int(time.Now().Unix()) + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetRaidById retrieves Raid by Id. Returns error if +// Id doesn't exist +func GetRaidById(logger *log.Logger, id int64) (v *Raid, err error) { + v = &Raid{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetRaidByUuid retrieves Raid by Id. Returns error if +// Id doesn't exist +func GetRaidByUuid(logger *log.Logger, uuid string) (v *Raid, err error) { + v = &Raid{} + err = dao.Where(logger, dao.IronicRdb, "raid_id = ? and is_del = 0", uuid).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllRaid retrieves all raid matches certain condition. Returns empty list if +// no records exist +func GetAllRaid(logger *log.Logger, query map[string]interface{}) (ml []*Raid, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Raid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiRaid retrieves all Raid matches certain condition. Returns empty list if +// no records exist +func GetMultiRaid(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Raid, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Raid{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateRaid updates Raid by Id and returns error if +// the record to be updated doesn't exist +func UpdateRaidById(logger *log.Logger, m *Raid) (err error) { + + m.UpdatedTime = int(time.Now().Unix()) + return dao.Model(logger, dao.IronicWdb, Raid{}).Where("id = ?", m.ID).Updates(m).Error +} + +type DRaid struct { + RaidId string `json:"raid_id"` + NameEn string `json:"name_en"` + NameZh string `json:"name_zh"` + DeviceType string `json:"device_type"` + VolumeType string `json:"volume_type"` + VolumeDetail string `json:"volume_detail"` + DescriptionZh string `json:"description_zh"` + DescriptionEn string `json:"description_en"` +} + +func GetAllRraidDevice(logger *log.Logger, raid_id, device_type, volume_type string) (ml []*DRaid, err error) { + + sql := `select t1.uuid as raid_id, t1.name_en, t1.name_zh, t1.description_zh, t1.description_en, t2.device_type, t2.volume_type, t2.volume_detail from raid t1 left join r_device_type_raid t2 on t1.uuid = t2.raid_id where t1.is_del = 0 and t2.is_del = 0` + if raid_id != "" { + sql = sql + fmt.Sprintf(" and t1.uuid = '%s'", raid_id) + } + if device_type != "" { + sql = sql + fmt.Sprintf(" and t2.device_type = '%s'", device_type) + } + if volume_type != "" { + sql = sql + fmt.Sprintf(" and t2.volume_type = '%s'", volume_type) + } + + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return + +} diff --git a/bmp-scheduler/dao/sshkeyDao/sshkeyDao.go b/bmp-scheduler/dao/sshkeyDao/sshkeyDao.go new file mode 100644 index 0000000..15b92c6 --- /dev/null +++ b/bmp-scheduler/dao/sshkeyDao/sshkeyDao.go @@ -0,0 +1,107 @@ +package sshkeyDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// Sshkey Sshkey +type Sshkey struct { + ID int64 `gorm:"id" json:"id"` + SshkeyId string `gorm:"sshkey_id" json:"SshkeyId"` // 秘钥uuid + Name string `gorm:"name" json:"name"` // 秘钥名称 + Key string `gorm:"key" json:"key"` // 公钥,格式:ssh-rsa AAA + FingerPrint string `gorm:"finger_print" json:"fingerPrint"` // 公钥指纹 + CreatedBy string `gorm:"created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Sshkey) TableName() string { + return "ssh_key" +} + +// AddSshkey insert a new Sshkey into database and returns +// last inserted Id on success. +func AddSshkey(logger *log.Logger, m *Sshkey) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetSshkeyById retrieves Sshkey by Id. Returns error if +// Id doesn't exist +func GetSshkeyById(logger *log.Logger, SshkeyId string) (v *Sshkey, err error) { + v = &Sshkey{} + err = dao.Where(logger, dao.IronicRdb, "sshkey_id = ? and is_del = 0", SshkeyId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetSshkeyByUuid retrieves Sshkey by Uuid. Returns error if +// Id doesn't exist +func GetSshkeyCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Sshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAllSshkey retrieves all Sshkey matches certain condition. Returns empty list if +// no records exist +func GetAllSshkey(logger *log.Logger, query map[string]interface{}) (ml []*Sshkey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Sshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiSshkey retrieves all Sshkey matches certain condition. Returns empty list if +// no records exist +func GetMultiSshkey(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Sshkey, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Sshkey{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateSshkey updates Sshkey by Id and returns error if +// the record to be updated doesn't exist +func UpdateSshkeyById(logger *log.Logger, m *Sshkey) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Sshkey{}).Where("Sshkey_id = ?", m.SshkeyId).Updates(m).Error +} diff --git a/bmp-scheduler/dao/subnetDao/subnetDao.go b/bmp-scheduler/dao/subnetDao/subnetDao.go new file mode 100644 index 0000000..ebc399d --- /dev/null +++ b/bmp-scheduler/dao/subnetDao/subnetDao.go @@ -0,0 +1,179 @@ +package subnetDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// Subnet 子网 +type Subnet struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + UUID string `gorm:"unique;column:uuid;type:varchar(36);not null" json:"uuid"` // 子网ID + Az string `gorm:"column:az;type:varchar(32);not null" json:"az"` // az + Tenant string `gorm:"index:i_subnet_tenant;column:tenant;type:varchar(64);not null" json:"tenant"` // 租户 + Name string `gorm:"column:name;type:varchar(32)" json:"name"` + Cidr string `gorm:"column:cidr;type:varchar(32);not null" json:"cidr"` // 子网网段 + VxlanID int64 `gorm:"column:vxlan_id;type:bigint(20) unsigned;not null" json:"vxlan_id"` // vxlan_id + Gateway string `gorm:"column:gateway;type:varchar(32);not null" json:"gateway"` // 子网网关 + Mask string `gorm:"column:mask;type:varchar(32);not null" json:"mask"` // 子网掩码 + Mac string `gorm:"column:mac;type:varchar(32);not null" json:"mac"` // MAC + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *Subnet) TableName() string { + return "subnet" +} + +// AddSubnet insert a new Subnet into database and returns +// last inserted Id on success. +func AddSubnet(logger *log.Logger, m *Subnet) (id int64, err error) { + + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicRdb, m) +} + +// GetSubnetById retrieves Subnet by Id. Returns error if +// Id doesn't exist +func GetSubnetById(logger *log.Logger, id int64) (v *Subnet, err error) { + v = &Subnet{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetOneSubnet(logger *log.Logger, query map[string]interface{}) (v *Subnet, err error) { + v = &Subnet{} + var db = dao.Model(logger, dao.IronicRdb, Subnet{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetSubnetCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Subnet{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return + +} + +// GetAllRaid retrieves all raid matches certain condition. Returns empty list if +// no records exist +func GetAllSubnet(logger *log.Logger, query map[string]interface{}) (ml []*Subnet, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Subnet{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiSubnet retrieves all Subnet matches certain condition. Returns empty list if +// no records exist +func GetMultiSubnet(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Subnet, err error) { + var db = dao.Model(logger, dao.IronicRdb, Subnet{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateSubnet updates Subnet by Id and returns error if +// the record to be updated doesn't exist +func UpdateSubnetById(logger *log.Logger, m *Subnet) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Subnet{}).Where("id = ?", m.ID).Updates(m).Error +} + +func GetBySubnetIdAndTenant(logger *log.Logger, subnet_id, tenant string) (v *Subnet, err error) { + v = &Subnet{} + err = dao.Where(logger, dao.IronicRdb, "uuid = ? and tenant = ? and is_del = 0", subnet_id, tenant).Take(&v).Error + if err != nil { + return nil, err + } + return v, nil + +} + +func QueryByTenant(logger *log.Logger, tenant, az string) (ml []*Subnet, err error) { + err = dao.Where(logger, dao.IronicRdb, "az = ? and tenant = ? and is_del = 0", az, tenant).Find(&ml).Error + return +} + +func CountByParam(logger *log.Logger, az, tenant, name string, subnet_ids []string) (n int64, err error) { + sql := `select count(1) from subnet t where 1=1` + if az != "" { + sql = sql + fmt.Sprintf(" and t.az = '%s'", az) + } + if tenant != "" { + sql = sql + fmt.Sprintf(" and t.tenant = '%s'", tenant) + } + if name != "" { + sql = sql + fmt.Sprintf(" and t.name LIKE CONCAT('%%', '%s', '%%')", name) + } + if len(subnet_ids) > 0 { + for k, v := range subnet_ids { + subnet_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t.uuid in (%s)", strings.Join(subnet_ids, ",")) + } + sql = sql + " and t.is_del = 0" + err = dao.Raw(logger, dao.IronicRdb, sql).Count(&n).Error + return +} + +func QueryByParam(logger *log.Logger, az, tenant, name string, subnet_ids []string, offset, limit int64) (ml []*Subnet, err error) { + sql := `select * from subnet t where 1=1` + if az != "" { + sql = sql + fmt.Sprintf(" and t.az = '%s'", az) + } + if tenant != "" { + sql = sql + fmt.Sprintf(" and t.tenant = '%s'", tenant) + } + if name != "" { + sql = sql + fmt.Sprintf(" and t.name LIKE CONCAT('%%', '%s', '%%')", name) + } + if len(subnet_ids) > 0 { + for k, v := range subnet_ids { + subnet_ids[k] = fmt.Sprintf("'%s'", v) + } + sql = sql + fmt.Sprintf(" and t.uuid in (%s)", strings.Join(subnet_ids, ",")) + } + sql = sql + fmt.Sprintf(" and t.is_del = 0 limit %d ,%d", offset, limit) + err = dao.Raw(logger, dao.IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/bmp-scheduler/dao/updateDao.go b/bmp-scheduler/dao/updateDao.go new file mode 100644 index 0000000..f5adcba --- /dev/null +++ b/bmp-scheduler/dao/updateDao.go @@ -0,0 +1,53 @@ +package dao + +import ( + clog "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +//更新 根据主键id,更新所有模型字段值。查询->set->save +//eg. dao.Save(logger, rdb, &food) +func Save(logger *clog.Logger, gdb *gorm.DB, value interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Save(value) +} + +//更新单个字段值 +//eg1.更新一条记录(根据主键) dao.Model(logger, rdb, &food).Update("price", 25) +//eg2.更新所有记录 dao.Model(logger, rdb, Food{}).Update("price", 25) +//eg3.根据自定义条件更新记录 dao.Model(logger, rdb, Food{}).Where("create_time > ?", "2018-11-06 20:00:00").Update("price", 25) +func Update(logger *clog.Logger, gdb *gorm.DB, attrs ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Update(attrs...) +} + +//更新多个字段值 +/* +updataFood := Food{ + Stock:120, + Title:"柠檬雪碧", + //Age:0 +} +*/ +//eg1. 通过结构体变量设置更新字段 dao.Model(logger, rdb, &food).Updates(&updataFood) 问题是:这样只会更新updataFood中字段为非默认值的字段,比如updataFood定义时就算加上了Age:0,这个字段也不会被更新成目标0 +//eg2. 根据自定义条件更新记录 dao.Model(logger, rdb, Food{}).Where("price > ?", 10).Updates(&updataFood) 问题同上 +//eg3. 想更新所有字段值,包括零值,就是不想忽略掉空值字段时,使用map类型替代上面的结构体变量 +/* +data := make(map[string]interface{}) +data["stock"] = 0 //零值字段 +data["price"] = 35 +dao.Model(logger, rdb, Food{}).Where("id = ?", 2).Updates(data) +*/ +func Updates(logger *clog.Logger, gdb *gorm.DB, values interface{}, ignoreProtectedAttrs ...bool) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Updates(values, ignoreProtectedAttrs...) +} + +//更新表达式 +//eg. db.Model(&food).Update("stock", gorm.Expr("stock + 1")) 等价于UPDATE `foods` SET `stock` = stock + 1 WHERE `foods`.`id` = '2' diff --git a/bmp-scheduler/dao/userDao/userDao.go b/bmp-scheduler/dao/userDao/userDao.go new file mode 100644 index 0000000..f07bd6f --- /dev/null +++ b/bmp-scheduler/dao/userDao/userDao.go @@ -0,0 +1,123 @@ +package userDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// user user +type User struct { + ID int `gorm:"primaryKey;column:id" json:"-"` + UserID string `gorm:"column:user_id" json:"userId"` // 用户uuid + RoleID string `gorm:"column:role_id" json:"roleId"` // 角色uuid + UserName string `gorm:"column:user_name" json:"userName"` // 用户名,唯一 + Email string `gorm:"column:email" json:"email"` // 邮箱 + PhonePrefix string `gorm:"column:phone_prefix" json:"phonePrefix"` // 国家地区码,如86 + PhoneNumber string `gorm:"column:phone_number" json:"phoneNumber"` // 手机号 + DefaultProjectID string `gorm:"column:default_project_id" json:"defaultProjectId"` // 所属项目uuid + Language string `gorm:"column:language" json:"language"` // 语言(中文/English) + Timezone string `gorm:"column:timezone;type:varchar(64);not null" json:"timezone"` // timezone + Password string `gorm:"column:password" json:"password"` // 密码,sha256非对称加密后存储 + Description string `gorm:"column:description" json:"description"` // 描述 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *User) TableName() string { + return "user" +} + +// Adduser insert a new user into database and returns +// last inserted Id on success. +func Adduser(logger *log.Logger, m *User) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetuserById retrieves user by Id. Returns error if +// Id doesn't exist +func GetUserById(logger *log.Logger, userId string) (v *User, err error) { + v = &User{} + err = dao.Where(logger, dao.IronicRdb, "user_id = ? and is_del = 0", userId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetUserByName(logger *log.Logger, userName string) (v *User, err error) { + v = &User{} + err = dao.Where(logger, dao.IronicRdb, "user_name = ? and is_del = 0", userName).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetuserByUuid retrieves user by Uuid. Returns error if +// Id doesn't exist +func GetUserCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, User{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAlluser retrieves all user matches certain condition. Returns empty list if +// no records exist +func GetAllUser(logger *log.Logger, query map[string]interface{}) (ml []*User, err error) { + + var db = dao.Model(logger, dao.IronicRdb, User{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiuser retrieves all user matches certain condition. Returns empty list if +// no records exist +func GetMultiUser(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*User, err error) { + + var db = dao.Model(logger, dao.IronicRdb, User{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// Updateuser updates user by Id and returns error if +// the record to be updated doesn't exist +func UpdateUserById(logger *log.Logger, m *User) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, User{}).Where("user_id = ?", m.UserID).Save(m).Error +} diff --git a/bmp-scheduler/dao/volumeDao/volumeDao.go b/bmp-scheduler/dao/volumeDao/volumeDao.go new file mode 100644 index 0000000..1cca97d --- /dev/null +++ b/bmp-scheduler/dao/volumeDao/volumeDao.go @@ -0,0 +1,142 @@ +package volumeDao + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// Volume 卷管理表 +type Volume struct { + ID int `gorm:"primaryKey;column:id" json:"-"` // 主键 + VolumeID string `gorm:"column:volume_id" json:"volumeId"` // 卷uuid + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型uuid + VolumeName string `gorm:"column:volume_name" json:"volumeName"` // 卷名称 + VolumeType string `gorm:"column:volume_type" json:"volumeType"` // 卷类型:系统卷,数据卷 + DiskType string `gorm:"column:disk_type" json:"diskType"` // 硬盘类型(SSD,HDD) + InterfaceType string `gorm:"column:interface_type" json:"interfaceType"` // 接口类型(SATA,SAS,NVME,不限制) + VolumeSize string `gorm:"column:volume_size" json:"volumeSize"` // 单盘大小(最小容量) + VolumeUnit string `gorm:"column:volume_unit" json:"volumeUnit"` // 硬盘单位(GB,TB) + VolumeAmount int `gorm:"column:volume_amount" json:"volumeAmount"` // 硬盘数量(最低块数) + //RaidCan string `gorm:"column:raid_can" json:"raidCan"` // RAID配置: (RAID,NO RAID) + //Raid string `gorm:"column:raid" json:"raid"` // RAID模式:RAID1,RIAD10等 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Volume) TableName() string { + return "volume" +} + +// AddVolume insert a new Volume into database and returns +// last inserted Id on success. +func AddVolume(logger *log.Logger, m *Volume) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// GetVolumeById retrieves Volume by Id. Returns error if +// Id doesn't exist +func GetVolumeById(logger *log.Logger, VolumeId string) (v *Volume, err error) { + v = &Volume{} + err = dao.Where(logger, dao.IronicRdb, "volume_id = ? and is_del = 0", VolumeId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetSystemVolumeByDeviceTypeId(logger *log.Logger, deviceTypeId string) (v *Volume, err error) { + v = &Volume{} + err = dao.Where(logger, dao.IronicRdb, "volume_id = ? and volume_type = 'system' and is_del = 0", deviceTypeId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetVolumeByName(logger *log.Logger, VolumeName string) (v *Volume, err error) { + v = &Volume{} + err = dao.Where(logger, dao.IronicRdb, "volume_name = ? and is_del = 0", VolumeName).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetVolumeByUuid retrieves Volume by Uuid. Returns error if +// Id doesn't exist +func GetVolumeCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + var db = dao.Model(logger, dao.IronicRdb, Volume{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return +} + +// GetAllVolume retrieves all Volume matches certain condition. Returns empty list if +// no records exist +func GetAllVolume(logger *log.Logger, query map[string]interface{}) (ml []*Volume, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Volume{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiVolume retrieves all Volume matches certain condition. Returns empty list if +// no records exist +func GetMultiVolume(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Volume, err error) { + + var db = dao.Model(logger, dao.IronicRdb, Volume{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateVolume updates Volume by Id and returns error if +// the record to be updated doesn't exist +func UpdateVolumeById(logger *log.Logger, m *Volume) (err error) { + + //m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, Volume{}).Where("id = ?", m.ID).Save(m).Error +} + +func UpdateVolumeByWhere(logger *log.Logger, query map[string]interface{}, updates *Volume) (err error) { + var db = dao.Model(logger, dao.IronicWdb, Volume{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} diff --git a/bmp-scheduler/dao/wanIpDao/wanIpDao.go b/bmp-scheduler/dao/wanIpDao/wanIpDao.go new file mode 100644 index 0000000..eab7345 --- /dev/null +++ b/bmp-scheduler/dao/wanIpDao/wanIpDao.go @@ -0,0 +1,158 @@ +package wanIpDao + +import ( + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + log "git.jd.com/cps-golang/log" +) + +// WanIP 外网ip +type WanIp struct { + ID int64 `gorm:"primary_key;column:id;type:bigint(20) unsigned;not null" json:"id"` // ID + Az string `gorm:"unique_index:i_wan_ip_az_ip;column:az;type:varchar(32);not null" json:"az"` // az + WanSubnetID string `gorm:"column:wan_subnet_id;type:varchar(36);not null" json:"wan_subnet_id"` // 外网网段ID + IP string `gorm:"unique_index:i_wan_ip_az_ip;column:ip;type:varchar(32);not null" json:"ip"` // 外网ip + Status int8 `gorm:"column:status;type:tinyint(4);not null" json:"status"` // 是否已使用(0-未使用, 1-已使用) + LineType string `gorm:"column:line_type;type:varchar(20)" json:"line_type"` // 链路类型:bgp、dynamic_bgp + CreateTime time.Time `gorm:"column:create_time;type:datetime;not null" json:"create_time"` // 创建时间 + UpdateTime time.Time `gorm:"column:update_time;type:datetime" json:"update_time"` // 更新时间 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除(0-未删, 1-已删) +} + +func (t *WanIp) TableName() string { + return "wan_ip" +} + +// AddWanIp insert a new WanIp into database and returns +// last inserted Id on success. +func AddWanIp(logger *log.Logger, m *WanIp) (id int64, err error) { + + m.CreateTime = time.Now() + m.UpdateTime = time.Now() + return dao.CreateAndGetId(logger, dao.IronicWdb, m) +} + +// AddMultiWanIp insert a new WanIp into database and returns +// last inserted Id on success. +func AddMultiWanIp(logger *log.Logger, m []*WanIp) (id int64, err error) { + + tx := dao.GetGormTx(logger) + tx.Begin() + for _, device := range m { + device.CreateTime = time.Now() + device.UpdateTime = time.Now() + if err := tx.Create(device).Error; err != nil { + tx.Rollback() + return 0, err + } + } + tx.Commit() + return int64(len(m)), nil +} + +// GetWanIpById retrieves WanIp by Id. Returns error if +// Id doesn't exist +func GetWanIpById(logger *log.Logger, id int64) (v *WanIp, err error) { + + v = &WanIp{} + err = dao.Where(logger, dao.IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetAllWanIp(logger *log.Logger, query map[string]interface{}) (ml []*WanIp, err error) { + + var db = dao.Model(logger, dao.IronicRdb, WanIp{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiWanIp retrieves all WanIp matches certain condition. Returns empty list if +// no records exist +func GetMultiWanIp(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*WanIp, err error) { + + var db = dao.Model(logger, dao.IronicRdb, WanIp{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateWanIp updates WanIp by Id and returns error if +// the record to be updated doesn't exist +func UpdateWanIpById(logger *log.Logger, m *WanIp) (err error) { + + m.UpdateTime = time.Now() + return dao.Model(logger, dao.IronicWdb, WanIp{}).Where("id = ?", m.ID).Updates(m).Error +} + +func UpdateMultiWanIps(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + updates["update_time"] = time.Now() + var db = dao.Model(logger, dao.IronicWdb, WanIp{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func QueryUnusedByAz(logger *log.Logger, az string, offset, limit int64) (ml []*WanIp, err error) { + + err = dao.Where(logger, dao.IronicRdb, "az = ? and status = 0 and is_del = 0", az).Find(&ml).Error + return + +} + +func GetByAzAndIP(logger *log.Logger, az string, ip string) (l *WanIp, err error) { + query := map[string]interface{}{ + "ip": ip, + "az": az, + "is_del": "0", + } + var db = dao.Model(logger, dao.IronicRdb, WanIp{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + + err = db.Find(&l).Error + return +} + +func QueryByAzAndIP(logger *log.Logger, az string, ips []string) (ml []*WanIp, err error) { + query := map[string]interface{}{ + "ip.in": ips, + "az": az, + "is_del": "0", + } + var db = dao.Model(logger, dao.IronicRdb, WanIp{}) + db, err = dao.WhereBuild(db, query) + if err != nil { + return nil, err + } + + err = db.Find(&ml).Error + return +} diff --git a/bmp-scheduler/docs/cps-lifecycle.md b/bmp-scheduler/docs/cps-lifecycle.md new file mode 100644 index 0000000..8f7e343 --- /dev/null +++ b/bmp-scheduler/docs/cps-lifecycle.md @@ -0,0 +1,568 @@ + +* [机型录入](#机型录入) + * [机型录入相关数据表](#机型录入对应数据表) + * [机型录入api](#机型录入对应api) + * [机型录入界面入口](#机型录入对应界面入口) +* [设备录入](#设备录入) + * [设备录入相关数据表](#设备录入对应数据表) + * [设备录入api](#设备录入对应api) + * [设备录入界面入口](#设备录入对应界面入口) +* [厂商和硬盘信息录入](#厂商和硬盘信息录入) + * [厂商和硬盘信息录入相关数据表](#厂商和硬盘信息录入对应数据表) + * [厂商和硬盘信息录入api](#厂商和硬盘信息录入对应api) + * [厂商和硬盘信息录入界面入口](#厂商和硬盘信息录入对应界面入口) +* [镜像录入](#镜像录入) + * [镜像录入相关数据表](#镜像录入对应数据表) + * [镜像录入api](#镜像录入对应api) + * [镜像录入界面入口](#镜像录入对应界面入口) +* [机型和镜像关联](#机型和镜像关联) + * [机型和镜像关联相关数据表](#机型和镜像关联相关表) + * [机型和镜像关联api](#机型和镜像关联api) + * [机型和镜像关联界面入口](#机型和镜像关联界面入口) +* [raid录入](#raid录入) + * [raid录入相关数据表](#raid录入相关数据表) + * [raid录入api](#raid录入相关api) + * [raid录入界面入口](#raid录入相关界面入口) +* [机型和raid关联](#机型和raid关联) + * [机型和raid关联相关数据表](#机型和raid关联相关数据表) + * [机型和raid关联api](#机型和raid关联相关api) + * [机型和raid关联界面入口](#机型和raid关联相关界面入口) +* [设备上架售卖](#设备上架售卖) + * [设备上架售卖api](#设备上架售卖相关api) + * [设备上架售卖界面入口](#设备上架售卖相关界面入口) +* [设备下架](#设备下架) + * [设备下架api](#设备下架相关api) + * [设备下架界面入口](#设备下架相关界面入口) +* [设备退库回收](#设备退库回收) + * [设备退库回收api](#设备退库回收相关api) + * [设备退库回收界面入口](#设备退库回收相关界面入口) +* [创建实例](#创建实例) + * [创建实例api](#创建实例相关api) + * [创建实例界面入口](#创建实例相关界面入口) +* [实例开机](#实例开机) + * [实例开机api](#实例开机相关api) + * [实例开机界面入口](#实例开机相关界面入口) +* [实例关机](#实例关机) + * [实例关机api](#实例关机相关api) + * [实例关机界面入口](#实例关机相关界面入口) +* [实例重启](#实例重启) + * [实例重启api](#实例重启相关api) + * [实例重启界面入口](#实例重启相关界面入口) +* [实例重装系统](#实例重装系统) + * [实例重装系统api](#实例重装系统相关api) + * [实例重装系统界面入口](#实例重装系统相关界面入口) +* [实例重置密码](#实例重置密码) + * [实例重置密码api](#实例重置密码相关api) + * [实例重置密码界面入口](#实例重置密码相关界面入口) +* [实例销毁](#实例销毁) + * [实例销毁api](#实例销毁相关api) + * [实例销毁界面入口](#实例销毁相关界面入口) + + + + + +## 机型录入 + + +新采购一批裸机后,首先要做的就是机型(即实例类型)的录入 + +#### 机型录入对应数据表 + +机型包含的主要信息在cps_ironic.device_type表中: + + + +| id | az | device_type | name_en | name_zh | cpu_amount | cpu_cores | cpu_manufacturer | cpu_model | cpu_frequency | mem_amount | mem_size | nic_amount | nic_rate | system_volume_amount | system_volume_size | data_volume_amount | data_volume_size | gpu_amount | gpu_manufacturer | gpu_model | create_time | update_time | is_del | +|-----|-------------|---------------|--------------------------------------------|--------------------------------|------------|-----------|------------------|-----------|---------------|------------|----------|------------|----------|----------------------|--------------------|--------------------|------------------|------------|------------------|-----------|---------------------|---------------------|--------| +| 101 | cn-north-1a | cps.c.perf1 | Compute Performance Ⅰ | 计算效能型Ⅰ | 2 | 16 | Intel | 2683V4 | 2.1 | 8 | 32 | 2 | 10 | 2 | 300 | 1 | 4000 | NULL | NULL | NULL | 2018-12-03 13:53:25 | 2018-12-03 13:53:25 | 0 | +| 102 | cn-north-1c | cps.c2.perf1 | Compute PerformanceⅠ(2nd generation) | 计算效能型Ⅰ(二代) | 2 | 20 | Intel | GOLD6148 | 2.4 | 12 | 32 | 2 | 10 | 1 | 240 | 1 | 2000 | NULL | NULL | NULL | 2018-12-03 13:53:25 | 2018-12-03 13:53:25 | 0 | +| 103 | cn-north-1a | cps.c.perf2 | Compute Performance Ⅱ | 计算效能型Ⅱ | 2 | 16 | Intel | 2683V4 | 2.1 | 8 | 32 | 2 | 10 | 1 | 240 | 16 | 960 | NULL | NULL | NULL | 2018-12-03 13:53:25 | 2018-12-03 13:53:25 | 0 | +| 104 | cn-north-1c | cps.s2.normal | Storage Standard(2nd generation) | 标准存储型(二代) | 2 | 12 | Intel | 2683V4 | 2.1 | 8 | 32 | 2 | 10 | 2 | 300 | 12 | 120000 | NULL | NULL | NULL | 2018-12-03 13:53:25 | 2018-12-03 13:53:25 | 0 | + + + + +#### 机型录入对应api + +私有化本次封装api [post /v1/offline/CreateBmClazz](https://git.jd.com/minping/ironic-console/blob/master/docs/offline-api.md#%E6%9C%BA%E5%9E%8B%E5%BD%95%E5%85%A5) +#### 机型录入对应界面入口 +cps这个录入操作没有页面,pm提供excel,rd直接插表,qa校验。 + + +## 设备录入 + + +每次采购了新机器,pm都会发类似如下的excel表格: + + + + + + + + +| SN | 系统IP | 管理IP | 品牌 | 型号 | 机房 | 机柜 | U位 | 套餐 | +| --- | ----- | ----- | ---- | --- | --- | --- | --- | --- | +| 210235A2CTH219000001 | 10.209.75.139 | 10.208.75.139 | H3C | R4900 G3 | 北京_中国联通_有孚 | B5-L5-1-I-13 | 30--31 | D2001 | +| 210235A2CTH219000002 | 10.209.75.138 | 10.208.75.138 | H3C | R4900 G3 | 北京_中国联通_有孚 | B5-L5-1-I-13 | 27--28 | D2001 | +| 210235A2CTH219000003 | 10.209.75.137 | 10.208.75.137 | H3C | R4900 G3 | 北京_中国联通_有孚 | B5-L5-1-I-13 | 24--25 | D2001 | + + + + + + + + +然后第一部要做的就是录入设备,可通过ironic-api模块的/devices/CreateDevices接口来进行设备入库(cps也可以通过idc信息同步来入库),其实就是插入到device表中 + + +#### 设备录入对应数据表 + + +就是device表,内容如下: + + + + +| id | sn | region | az | device_type | manufacturer_id | ilo_ip | cabinet | u_position | sale_status | create_time | update_time | is_del | remark | +|----|----------|-------------|--------------|----------------------|-----------------|---------------|---------|------------|-------------|---------------------|---------------------|--------|--------| +| 20 | J300GT9H | cn-east-tz1 | cn-east-tz1a | edcps.c2.perf1 | 15 | 10.208.13.79 | | | sold | 2019-02-20 16:31:32 | 2020-09-17 15:17:30 | 0 | NULL | +| 54 | J300GZ8P | cn-north-1 | cn-north-1c | cps.s2.normal | 21 | 10.208.13.107 | NULL | NULL | sold | 2019-07-18 10:32:01 | 2021-06-24 10:38:40 | 0 | NULL | +| 63 | J301B9B6 | cn-north-1 | cn-north-1c | cps.c2.perf2 | 26 | 10.208.13.197 | NULL | NULL | sold | 2020-01-02 18:09:11 | 2021-09-30 11:36:46 | 0 | NULL | +| 65 | 2CVZ1K2 | cn-east-tz1 | cn-east-tz1a | edcps.huya.c.normal1 | 27 | 10.208.16.41 | NULL | NULL | sold | 2020-02-04 18:23:34 | 2020-08-18 19:55:25 | 0 | NULL | +| 66 | 2D642K2 | cn-north-1 | cn-north-1a | cps.c.normal | 32 | 10.208.11.98 | NULL | NULL | sold | 2020-02-04 18:23:34 | 2021-07-13 14:23:16 | 0 | NULL | + + + + +注意录入设备这一步只插入device_type, ilo_ip等信息,manufacturer_id是后面硬件设备信息采集才插入进去的。device_type就是对应的上面需求表中的套餐,两者的对应关系成琳在cps库中新加了一张physical_machine_package表来记录对应关系。 + + +设备录入完成后,sale_status为上架中putawaying + + +#### 设备录入对应api + + +私有化本次封装api [post v1/offline/createDevices](https://git.jd.com/minping/ironic-console/blob/master/docs/offline-api.md#%E8%AE%BE%E5%A4%87%E5%BD%95%E5%85%A5) + + + + +#### 设备录入对应界面入口 + + +无 + + +## 厂商和硬盘信息录入 + +上面的机型device_type表包含cpu,cpu_core,mem,nic,gpu等各种信息,但是唯独没有磁盘和厂商相关信息。其实这部分信息是放在manufacturer表和disk表中的。 + +#### 厂商和硬盘信息录入对应数据表 + + +manufacturer表内容: + + + + +| id | device_type | manufacturer | product_name | create_time | update_time | is_del | +|----|--------------|-------------------------------------|---------------------------------------------------------------|---------------------|---------------------|--------| +| 1 | cps.c.normal | Huawei | RH1288 V3 (Type1Sku0) | 2018-12-26 13:28:10 | 2018-12-26 13:28:13 | 0 | +| 2 | cps.c.perf2 | Dell Inc. | PowerEdge R730xd (SKU=NotProvided;ModelName=PowerEdge R730XD) | 2018-12-26 13:28:16 | 2018-12-26 13:28:18 | 0 | +| 3 | cps.c.perf1 | Dell Inc. | PowerEdge R630 (SKU=NotProvided;ModelName=PowerEdge R630) | 2018-12-26 13:28:20 | 2018-12-26 13:28:22 | 0 | +| 4 | cps.s.normal | Unis Huashan Technologies Co., Ltd. | R4900 G2 (0) | 2018-12-26 13:28:24 | 2018-12-26 13:28:27 | 0 | +| 5 | cps.gpu.1 | Sugon | W580-G20 (Default string) | 2018-12-26 13:28:29 | 2018-12-26 13:28:31 | 0 | +| 26 | cps.c2.perf2 | Lenovo | ThinkSystem SR650 -[7X06CTO1WW]- (7X06CTO1WW) | 2020-01-02 18:14:17 | 2020-01-02 18:14:17 | 0 | +| 42 | cps.c2.perf2 | Inspur | SA5212M5 (Default string) | 2020-12-01 11:36:44 | 2020-12-01 11:36:44 | 0 | + + + + + + +disk表内容: + + + + +| id | manufacturer_id | enclosure | slot | disk_type | create_time | update_time | is_del | +|----|-----------------|-----------|------|-----------|---------------------|---------------------|--------| +| 18 | 1 | 252 | 0 | system | 2018-12-04 10:57:29 | 2018-12-04 10:57:29 | 0 | +| 19 | 1 | 252 | 1 | system | 2018-12-04 10:57:29 | 2018-12-04 10:57:29 | 0 | +| 20 | 1 | 252 | 2 | data | 2018-12-04 10:57:29 | 2018-12-04 10:57:29 | 0 | +| 21 | 1 | 252 | 3 | data | 2018-12-04 10:57:29 | 2018-12-04 10:57:29 | 0 | +| 22 | 3 | 32 | 0 | system | 2018-12-04 10:57:29 | 2018-12-04 10:57:29 | 0 | + + + + +用户选择一种机型一种镜像创建实例时,如果这种机型对应多种manufacturer(比如上面的cps.c2.perf2机型有Lenovo和Inspur两个厂商可以提供),那么现在的逻辑是随机选一个。其实manufacturer对用户是透明的,而且这里的manufacturer信息只是给disk提供服务的,所以个人觉得manufacturer表完全可以去掉,而且manufacturer表其实是一个机型-manufacturer关联表,应该叫r_device_type_disk这种关联表名字更合适。但是agent和监控好像依赖manufacturer信息。 + + +#### 厂商和硬盘信息录入对应api + + +这里分两步,先接口采集厂商等基本信息,后手动登录到机器获取磁盘槽位信息,手动录入信息到disk表 + + +- 接口采集厂商等基本信息这一步是手动调用ironic-api模块的/devices/collectDeviceInfo接口,到ironic-scheduler模块下发collecthardwareinfo命令到agent,agent采集了上传到scheduler模块,插入manufacturer表中。 +- 然后通过device表该设备的带外ip登录进去,用/usr/sbin/MegaCli64 -PDList -aAll | egrep 'Enclosure | Slot'等命令获取槽位信息,将槽位信息手动插入到disk表中。 + + +私有化本次封装api [post v1/offline/collectManufacturerAndDisk](https://git.jd.com/minping/ironic-console/blob/master/docs/offline-api.md#%E5%8E%82%E5%95%86%E5%92%8C%E7%A1%AC%E7%9B%98%E4%BF%A1%E6%81%AF%E5%BD%95%E5%85%A5) + +#### 厂商和硬盘信息录入对应界面入口 + + +采集设备厂商基本信息和采集槽位信息均无界面入口,纯手工。 + + + +## 镜像录入 +上面的机型是硬件相关的,这里的镜像就是跟操作系统相关了,用户在创建实例的时候,需要选择使用哪个镜像系统。所以需要管理员先在运营平台上先录入可用的镜像。cps方面,都是唐湘先制作好镜像,上传到nginx对应镜像下载目录上,然后通知rd录入到image表中。 + + +#### 镜像录入对应数据表 + + +镜像这里有两个相关表,os表和image表,os表内容如下: + + + + +| id | uuid | name_en | name_zh | os_type | platform | architecture | bits | version | sys_user | create_time | update_time | is_del | +|----|--------------------------------|------------------------------------------------------------------|--------------------------------------------------|---------|----------|--------------|------|---------|----------|---------------------|---------------------|--------| +| 1 | o-1vc0l7zpnrt1rpnssudanmq01jbv | CentOS 6.6 64-bit | CentOS 6.6 64位 | CentOS | linux | x86 | 64 | 6.6 | root | 2018-12-17 17:40:56 | 2018-12-17 17:40:56 | 0 | +| 2 | o-hea0bysnymuquyhyrfgtxj6qtc8e | CentOS 7.1 64-bit | CentOS 7.1 64位 | CentOS | linux | x86 | 64 | 7.1 | root | 2018-12-17 17:40:56 | 2018-12-17 17:40:56 | 0 | +| 3 | o-fspugrsoajxqzt1tncelmodsbsuc | CentOS 7.2 64-bit | CentOS 7.2 64位 | CentOS | linux | x86 | 64 | 7.2 | root | 2018-12-17 17:40:56 | 2018-12-17 17:40:56 | 0 | +| 4 | o-zqxfcdf99c6fgkihaaayd1uiaofk | CentOS 7.5 64-bit | CentOS 7.5. 64位 | CentOS | linux | x86 | 64 | 7.5 | root | 2018-12-17 17:40:56 | 2018-12-17 17:40:56 | 0 | +| 5 | o-1c9ypijcvtsbqonhn2ukw5ljxgpq | Ubuntu 14.04 64-bit | Ubuntu 14.04 64位 | Ubuntu | linux | x86 | 64 | 14.04 | root | 2018-12-17 17:40:56 | 2018-12-17 17:40:56 | 0 | +| 6 | o-1uz8qa06mtz2lve8ibtabkh5kwna | Ubuntu 16.04 64-bit | Ubuntu 16.04 64位 | Ubuntu | linux | x86 | 64 | 16.04 | root | 2018-12-17 17:40:56 | 2018-12-17 17:40:56 | 0 | +| 7 | o-s916eda0byt6mihuxp77axmhybpn | Ubuntu 18.04 64-bit | Ubuntu 18.04 64位 | Ubuntu | linux | x86 | 64 | 18.04 | root | 2018-12-17 17:40:56 | 2018-12-17 17:40:56 | 0 | +| 9 | o-t4gru7kqadqaftv1mgubvum6904a | CentOS 7.5 64-bit TD Plus | CentOS 7.5 64位 TD增强版 | CentOS | linux | x86 | 64 | 7.5 | root | 2019-05-24 17:04:38 | 2019-05-24 17:04:38 | 0 | +| 10 | o-82oueik4ihvosopcoc1m4ipifv3l | Ubuntu 18.04 64-bit ARM | Ubuntu 18.04 64位 ARM | Ubuntu | linux | x86 | 64 | 18.04 | root | 2019-11-12 11:36:37 | 2019-11-12 11:36:37 | 0 | +| 11 | o-pwrdu2andavqyp1yqxlgaqrg4ywn | CentOS 7.2 64-bit | CentOS 7.2 64-bit定制版 | CentOS | linux | x86 | 64 | 7.2 | root | 2019-12-04 18:07:26 | 2019-12-04 18:07:26 | 0 | +| 14 | o-fb398c1dc66d427fa0da35a898e5 | CentOS 7.6-bit | CentOS 7.6 64位 | CentOS | linux | x86 | 64 | 7.6 | root | 2019-12-23 17:54:39 | 2019-12-23 17:54:39 | 0 | +| 15 | o-16a13d56847f4b0e9755d9c0cdb1 | Ubuntu 16.04 Huya 64-bit | Ubuntu 16.04 Huya 64位 | Ubuntu | linux | x86 | 64 | 16.04 | root | 2020-02-19 11:36:37 | 2020-02-19 11:36:37 | 0 | +| 16 | o-17ea6e54932c455c9e51909b568e | Windows Server 2016 Standard Version, 64-bit, Chinese Version | Windows Server 2016 标准版 64位 中文版 | Windows | linux | x86 | 64 | 2016 | root | 2020-06-11 10:20:20 | 2020-08-12 18:50:17 | 0 | +| 17 | o-caecaf97b62a4cb7baab799dfd3c | Windows Server 2012 R2 Standard Version, 64-bit, Chinese Version | Windows Server 2012 R2 标准版 64位 中文版 | Windows | linux | x86 | 64 | 2012 | root | 2020-07-08 18:20:41 | 2020-08-12 18:53:05 | 0 | +| 18 | o-a628710f69d2486e9842f822ff56 | Windows 2012 normal | Windows 2012 normal | Windows | linux | x86 | 64 | 2012 | root | 2020-07-14 11:50:29 | 2020-07-14 11:50:29 | 0 | +| 19 | o-50b9621c383b4d47b8f19e385630 | CentOS 7.4 64-bit BDP customize | CentOS 7.4 64位 BDP定制版 | CentOS | linux | x86 | 64 | 7.4 | root | 2020-09-01 20:57:41 | 2020-09-01 20:57:41 | 0 | +| 20 | o-b4969d4f9b464b67a46ebb6f1368 | CentOS 8.2 64-bit | CentOS 8.2 64位 | CentOS | linux | x86 | 64 | 8.2 | root | 2020-10-14 20:39:30 | 2020-10-14 20:39:30 | 0 | +| 21 | o-dfaeea19e2c64f17b7c5ace23c3a | CentOS 8.0 64-bit | CentOS 8.0 64位 | CentOS | linux | x86 | 64 | 8.0 | root | 2020-10-30 11:08:16 | 2020-10-30 11:08:16 | 0 | +| 22 | o-eda5ef18380f4e9a980777ddb263 | CentOS 7.4 64-bit | CentOS 7.4 64位 | CentOS | linux | x86 | 64 | 7.4 | root | 2020-11-11 10:36:50 | 2020-11-11 10:36:50 | 0 | +| 23 | o-s916eda0byt6mihuxp77axmhubun | Ubuntu 20.04 64-bit | Ubuntu 20.04 64位 | Ubuntu | linux | x86 | 64 | 20.04 | root | 2018-12-17 17:40:56 | 2018-12-17 17:40:56 | 0 | + + + + +image表内容如下: + + + + + + +| id | uuid | name_en | name_zh | version | os_id | format | filename | url | hash | source | create_time | update_time | is_del | +|------|------------------------------------|------------------------------------------------------------------|-----------------------------------------------------------------|---------|--------------------------------|--------|--------------------------------------------------------|---------------------------------------------------------------|----------------------------------|-----------|---------------------|---------------------|--------| +| 21 | i-d656757978ec4ad78a7d4f515037 | Windows Server 2012 R2 Standard Version, 64-bit, Chinese Version | Windows Server 2012 R2 标准版 64位 中文版 | 2012 | o-caecaf97b62a4cb7baab799dfd3c | qcow2 | windows-server-2012-cn.qcow2 | {host}/windows-server-2012-cn.qcow2 | 7eaeb8d9a8140cda22dd2174b2236ab4 | common | 2020-07-08 18:20:41 | 2020-08-12 19:01:50 | 0 | +| 1006 | i-usk5qjugotg56r0jlaruy57nzswwwtar | Ubuntu 20.04 64-bit | Ubuntu 20.04 64位 UEFI TAR | 20.04 | o-s916eda0byt6mihuxp77axmhubun | tar | ubuntu-20.04-uefi.tar.xz | {host}/ubuntu-20.04-uefi.tar.xz | 433a199dd041ac6a048fd6f3df2fa88b | common | 2018-11-27 16:41:51 | 2018-11-27 16:41:51 | 0 | +| 1118 | i-rodl94xo5nevgovh5y8k8rnofbhv | CentOS 7.5 64-bit TD Plus | CentOS 7.5 64位 TD 增强版 | 0 | o-t4gru7kqadqaftv1mgubvum6904a | qcow2 | v1.3.0-centos-7.5-td-plus-2019081316.qcow2 | {host}/v1.3.0-centos-7.5-td-plus-2019081316.qcow2 | 58e880243671a60f4fcc8805a333844a | customize | 2019-05-30 21:00:21 | 2019-08-26 21:01:56 | 0 | +| 1135 | i-tvuhgdqltetmuhem9fh7wq3dtmuy | CentOS 8.2 64-bit for mysql and es | CentOS 8.2 64位 零售MySQL&ES定制版 | 8.2 | o-b4969d4f9b464b67a46ebb6f1368 | tar | v1.3.0-centos-8.2-mysql-es-2020120416.tar.xz | {host}/v1.3.0-centos-8.2-mysql-es-2020120416.tar.xz | da981058f8f3fbe59dcf77ed21b587f7 | customize | 2020-10-29 16:44:00 | 2020-10-29 16:44:00 | 0 | + + +可以看到,os表是基础表,image表信息包含全部的os表信息,业务上几乎没有用到os表,用的都是image表。 +image表包含如下信息: + + +- uuid +- 中、英文镜像名称 +- version版本 +- 关联os_id +- 创建/修改时间 +- 镜像下载url +- 镜像文件hash +- 来源 common/customize + + + + +#### 镜像录入对应api + + +私有化本次封装api [post v1/offline/createImage](https://git.jd.com/minping/ironic-console/blob/master/docs/offline-api.md#%E9%95%9C%E5%83%8F%E5%BD%95%E5%85%A5) + + +#### 镜像录入对应界面入口 + + +无 + + + +## 机型和镜像关联 + +有些机型只能使用特定image镜像来装系统,这种关系称为机型和镜像关联。在页面上创建实例的时候也是先选机型,根据选择的机型给出可用的镜像供选择,等机型和镜像选好了后才可以创建实例装机。 + + +#### 机型和镜像关联相关表 + + +镜像和机型关联表为 r_device_type_image表和r_device_type_image_partition表。 +在创建实例,选择了机型后,列出可用的镜像就是查r_device_type_image表,表内容为: + + + + +| id | image_id | device_type | create_time | update_time | is_del | +|----|--------------------------------|--------------|---------------------|---------------------|--------| +| 37 | i-vtgpscwagbvd7urak6jk4ykstmff | cps.s.normal | 2019-01-04 20:07:51 | 2019-01-04 20:07:51 | 0 | +| 38 | i-yhzcyaxnw6rtieorpgfdnbfshfh9 | cps.s.normal | 2019-01-04 20:07:51 | 2019-01-04 20:07:51 | 0 | +| 44 | i-vtgpscwagbvd7urak6jk4ykstmff | cps.c.normal | 2019-01-04 20:07:51 | 2019-01-04 20:07:51 | 0 | +| 45 | i-yhzcyaxnw6rtieorpgfdnbfshfh9 | cps.c.normal | 2019-01-04 20:07:51 | 2019-01-04 20:07:51 | 0 | +| 51 | i-vtgpscwagbvd7urak6jk4ykstmff | cps.c.perf1 | 2019-01-04 20:07:51 | 2020-06-23 21:05:18 | 0 | +| 52 | i-yhzcyaxnw6rtieorpgfdnbfshfh9 | cps.c.perf1 | 2019-01-04 20:07:51 | 2019-01-04 20:07:51 | 0 | + + + + + +r_device_type_image_partition表看名字其实和镜像关联相关,但其实跟镜像关联的意义不大,这个表其实是给装机过程中的做分区这个子command来使用的。只要是tar格式的镜像,一般在r_device_type_image_partition表中都有一行system(系统盘)的分区信息记录(如果没有则装机在make partition这一步会失败,导致实例创建失败),data(数据盘)分区信息记录可有可没有。r_device_type_image_partition表内容如下: + + + + +| id | image_id | device_type | boot_mode | partition_type | partition_size | partition_fs_type | partition_mount_point | partition_label | system_disk_label | data_disk_label | create_time | update_time | is_del | +|----|--------------------------------|---------------------------|-----------|----------------|----------------|-------------------|-----------------------|-----------------|-------------------|-----------------|---------------------|---------------------|--------| +| 1 | i-8f5fc65dd2894c85b9865fddee97 | cps.s.normal.optimized | bios | system | 999999999 | xfs | /export | l_export | gpt | gpt | 2020-11-16 18:15:29 | 2020-11-16 18:15:29 | 0 | +| 2 | i-5a1bf8e3f0844bd19894ec21b612 | cps.c2.perf2.netenhanced | bios | data | 102400 | xfs | /export | l_export | gpt | gpt | 2020-11-16 18:15:29 | 2020-11-16 18:15:29 | 0 | +| 3 | i-1688c97caa9b414085d91c38b5dd | cps.c2.perf2.netenhanced | bios | data | 102400 | xfs | /export | l_export | gpt | gpt | 2020-11-16 18:15:29 | 2020-11-16 18:15:29 | 0 | +| 4 | i-276dfcc0dbc74925bfca67b5a497 | cps.c2.perf2.storenhanced | bios | system | 999999999 | xfs | /data0 | l_data0 | gpt | gpt | 2020-11-16 18:15:29 | 2020-11-16 18:15:29 | 0 | +| 5 | i-1688c97caa9b414085d91c38b5dd | cps.c2.perf2.storenhanced | bios | system | 102400 | xfs | /export | l_export | gpt | gpt | 2020-11-16 18:15:29 | 2020-11-16 18:15:29 | 0 | + + +#### 机型和镜像关联api + +[POST v1/offline/deviceTypes/associatedImage](https://git.jd.com/minping/ironic-console/blob/master/docs/offline-api.md#%E5%85%B3%E8%81%94%E9%95%9C%E5%83%8F) + + + + + +#### 机型和镜像关联界面入口 + + +运营平台-机型管理-管理镜像-关联镜像/移除 + + + + + +## raid录入 + +常见的raid方案有NORAID, RAID0, RAID1, RAID10, RAID51H, soft RAID1等,这些信息一般开始就录入进表了,后面基本不会动。 + + +#### raid录入相关数据表 + + +raid表的内容如下: + + + + +| id | uuid | name_en | name_zh | description_en | description_zh | create_time | update_time | is_del | +|-----|--------------------------------|---------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------|---------------------|--------| +| 100 | r-qytwf9r5h0yn9x4evjkyr0n1cwyb | NORAID | NORAID | NO RAID means that each physical disk is displayed independently as a logical disk. There is no block stripping and no data redundancy. | NO RAID是每个物理磁盘独立显示为一个逻辑盘,没有数据块分条(no block stripping),不提供数据冗余。 | 2019-01-11 11:55:14 | 2019-01-11 11:55:12 | 0 | +| 101 | r-sfykwibcvcyztuez3mk1klyha9nn | RAID0 | RAID0 | RAID0 means that the entire logical disk data is striped among multiple physical disks, it allows read/write in parallel and provides the fastest speed with no redundancy. | RAID0是整个逻辑盘的数据是被分条(stripped)分布在多个物理磁盘上,可以并行读/写,提供最快的速度,但没有冗余能力。 | 2018-11-27 10:14:26 | 2018-11-27 10:14:26 | 0 | +| 102 | r-wtzluqacgzzxgunnabdkpnpjew3d | RAID1 | RAID1 | RAID1 also known as mirroring method, provides data redundancy. In the entire mirroring process, only half of the disk capacity is valid, the other half is used to store the same data. RAID1 has taken security into consideration with half capacity and full speed. | RAID1又称镜像方式,提供数据的冗余。在整个镜像过程中,只有一半的磁盘容量是有效的(另一半磁盘容量用来存放同样的数据),RAID1考虑了安全性,容量减半、速度不变。 | 2018-11-27 10:15:26 | 2018-11-27 10:15:26 | 0 | +| 103 | r-l6pounvfife0njlinhk6ztf2xyio | RAID10 | RAID10 | RAID10 is used for achieving the high speed and security purposes. RAID 10 can be simply interpreted as the RAID 0 array composed of several disks, which then provides the image. | RAID10是为了达到既高速又安全,可以把RAID 10简单地理解成由多个磁盘组成的RAID 0阵列再进行镜像。 | 2018-11-27 10:16:08 | 2018-11-27 10:16:08 | 0 | +| 104 | r-lowdd8nf8y7v6jk5ocr5paqhvhre | RAID51H | RAID51H | RAID 5+1 hotspare offers you a resolution featuring high performance, data security and reasonable cost in storage, with added hot backup disks for better data security. | RAID 5+1 hotspare是一种存储性能、数据安全和存储成本兼顾的存储解决方案,同时增加热备盘来提升数据安全。 | 2019-05-20 19:50:23 | 2019-05-20 19:50:23 | 0 | +| 105 | r-softraiddpo98m7v6jkferhwpaqh | RAID1 | RAID1 | soft RAID1 | 软RAID1 | 2021-08-13 17:37:19 | 2021-08-13 17:37:23 | 0 | + + +#### raid录入相关api + +无 + +#### raid录入相关界面入口 + + +无 + + + + + + +## 机型和raid关联 + + +哪些机型(即device_type,也即套餐)的系统盘可以做哪种raid,数据盘可以做哪种raid,是存在r_device_type_raid表中的。其实主要是跟机型的磁盘块数有关系。 + +#### 机型和raid关联相关数据表 + + +r_device_type_raid表的内容如下: + + + + + + +| id | raid_id | device_type | volume_type | volume_detail | system_partition_count | create_time | update_time | is_del | +|-----|--------------------------------|--------------|-------------|---------------------|------------------------|---------------------|---------------------|--------| +| 101 | r-wtzluqacgzzxgunnabdkpnpjew3d | cps.s.normal | system | 300GB (2*300GB SAS) | 1 | 2019-01-14 18:21:07 | 2019-01-14 18:21:07 | 0 | +| 102 | r-qytwf9r5h0yn9x4evjkyr0n1cwyb | cps.s.normal | data | 72TB (12*6TB SATA) | 1 | 2019-01-14 18:21:07 | 2019-01-14 18:21:07 | 0 | +| 103 | r-wtzluqacgzzxgunnabdkpnpjew3d | cps.c.normal | system | 300GB (2*300GB SAS) | 1 | 2019-01-14 18:21:07 | 2019-01-14 18:21:07 | 0 | +| 104 | r-qytwf9r5h0yn9x4evjkyr0n1cwyb | cps.c.normal | data | 1.6TB (2*800GB SSD) | 1 | 2019-01-14 18:21:07 | 2019-01-14 18:21:07 | 0 | +| 105 | r-sfykwibcvcyztuez3mk1klyha9nn | cps.c.normal | data | 1.6TB (2*800GB SSD) | 1 | 2019-01-14 18:21:07 | 2019-01-14 18:21:07 | 0 | + + + + + +#### 机型和raid关联相关api + + +私有化本次封装api [post v1/offline/deviceTypes/associatedRaid](https://git.jd.com/minping/ironic-console/blob/master/docs/offline-api.md#%E6%9C%BA%E5%9E%8B%E5%92%8Craid%E5%85%B3%E8%81%94) + +#### 机型和raid关联相关界面入口 + +无 + +## 机型和raid解关联 + + +#### 机型和raid解关联相关api + + +私有化本次封装api [post v1/offline/deviceTypes/dissociatedRaid](https://git.jd.com/minping/ironic-console/blob/master/docs/offline-api.md#%E6%9C%BA%E5%9E%8B%E5%92%8Craid%E8%A7%A3%E5%85%B3%E8%81%94) + + +## 设备上架售卖 + +#### 设备上架售卖相关api + + +[/v1/offline/putawayDevices](https://git.jd.com/minping/ironic-console/blob/master/docs/offline-api.md#%E8%AE%BE%E5%A4%87%E4%B8%8A%E6%9E%B6) + + +sale_status前置状态:上架中putawaying +sale_status后置状态:售卖中selling + +#### 设备上架售卖相关界面入口 + + +资源管理-开放售卖 + + +## 设备下架 + +#### 设备下架相关api + + +[/v1/offline/unPutawayDevices](https://git.jd.com/minping/ironic-console/blob/master/docs/offline-api.md#%E8%AE%BE%E5%A4%87%E4%B8%8B%E6%9E%B6) + + +sale_status前置状态:售卖中selling +sale_status后置状态:上架中putawaying + + +#### 设备下架相关界面入口 + +资源管理-设备下架 + + +## 设备退库回收 + +#### 设备退库回收相关api + +[v1/offline/instance](https://git.jd.com/minping/ironic-console/blob/master/docs/offline-api.md#%E8%AE%BE%E5%A4%87%E5%9B%9E%E6%94%B6) + + +sale_status前置状态:putawaying +回收完后is_del置为1 + +#### 设备退库回收相关界面入口 +资源管理-设备回收 + +## 创建实例 + +#### 创建实例相关api + + +[POST /api/cps/createInstance](https://git.jd.com/minping/ironic-console/blob/master/docs/console-api.md#%E5%88%9B%E5%BB%BA%E7%89%A9%E7%90%86%E6%9C%BA) + +#### 创建实例相关界面入口 + + +## 实例开机 + +#### 实例开机相关api + + +[PUT /api/cps/startInstance](https://git.jd.com/minping/ironic-console/blob/master/docs/console-api.md#%E5%BC%80%E6%9C%BA) + +#### 实例开机相关界面入口 + + + +## 实例关机 + +#### 实例关机相关api + + +[PUT /api/cps/stopInstance](https://git.jd.com/minping/ironic-console/blob/master/docs/console-api.md#%E5%85%B3%E6%9C%BA) + +#### 实例关机相关界面入口 + + +## 实例重启 + +#### 实例重启相关api + + +[PUT /api/cps/restartInstance](https://git.jd.com/minping/ironic-console/blob/master/docs/console-api.md#%E9%87%8D%E5%90%AF) +#### 实例重启相关界面入口 + + + +## 实例重装系统 +#### 实例重装系统相关api + + +[POST /api/cps/reinstallInstance](https://git.jd.com/minping/ironic-console/blob/master/docs/console-api.md#%E9%87%8D%E8%A3%85%E7%89%A9%E7%90%86%E6%9C%BA) +#### 实例重装系统相关界面入口 + + +## 实例重置密码 + + +#### 实例重置密码相关api + + +[PUT /api/cps/resetPassword](https://git.jd.com/minping/ironic-console/blob/master/docs/console-api.md#%E9%87%8D%E7%BD%AE%E5%AF%86%E7%A0%81) +##### 实例重置密码相关界面入口 + + +## 实例销毁 + + +实例销毁和运营平台的设备回收其实是一样的意思。 +#### 实例销毁相关api + + +[DELETE /api/cps/deleteInstance](https://git.jd.com/minping/ironic-console/blob/master/docs/console-api.md#%E5%88%A0%E9%99%A4%E7%89%A9%E7%90%86%E6%9C%BA) +#### 实例销毁相关界面入口 + + + + + + + diff --git a/bmp-scheduler/docs/offline-api.md b/bmp-scheduler/docs/offline-api.md new file mode 100644 index 0000000..e1f1879 --- /dev/null +++ b/bmp-scheduler/docs/offline-api.md @@ -0,0 +1,1232 @@ +# Table of Contents + +- [机型录入](#机型录入) +- [设备录入](#设备录入) +- [厂商和硬盘信息录入](#厂商和硬盘信息录入) +- [镜像录入](#镜像录入) +- [机型和镜像关联](#关联镜像) +- [机型和镜像关联移除](#移除镜像) +- [raid录入](#raid录入) +- [机型和raid关联](#机型和raid关联) +- [机型和raid解关联](#机型和raid解关联) +- [机型管理列表](#机型管理列表) +- [查询设备类型列表](#查询设备类型列表) +- [查询镜像列表](#查询镜像列表) +- [查询 RAID 列表](#查询raid列表) +- [查询用户列表](#查询用户列表) +- [查询用户详情](#查询用户详情) +- [查询当前登录用户](#查询当前登录用户) +- [查询实例列表-已废弃](#查询实例列表-已废弃) +- [导出实例列表-已废弃](#导出实例列表-已废弃) +- [查询设备实例列表](#查询设备实例列表) +- [查询设备实例详情](#查询设备实例详情) +- [导出设备实例列表](#导出设备实例列表) +- [查询设备库存](#查询设备库存) +- [导出设备库存](#导出设备库存) +- [设备上架售卖](#设备上架) +- [设备下架](#设备下架) +- [设备回收](#设备回收) +- [售卖状态查询](#售卖状态查询) +- [实例状态查询](#实例状态查询) + +## changelog + +| 版本 | 变更日期 | 变更内容 | 变更人 | +| ----| --------- | ------- | ------ | +| v1.0.0 | 2021-09-18 | 初始化 | 闵平(minping@jd.com)| + + +## 约定 +除了GET请求外,其他格式请求的requestbody格式一律为 Content-Type=application/json + + +_通用数据结构: + +```json +{ + "requestId": "xxx", + "data": { + + }, + "error": { + "code": 500, + "message": "invalid xxx parameter", + "status": "InvalidParameter", + } +} +``` + +_后续接口定义中的内容全部都是 result 属性中的结构_ + +### 机型录入 + +##### url +```http +/v1/offline/CreateBmClazz +``` + +##### method + +```http +POST +``` + +##### 请求参数 + +```json +{ + "region" : "cn-north-1", //required, + "deviceType" : "cps.c.perf1", //required + "nameEN" : "Compute Performance Ⅰ", //required + "nameZH" : "计算效能型Ⅰ", //required" + "family" : "compute", //设备所属规格系列:存储storage 计算compute GPUgpu + "canRaid" : true, //能否做RAID:true可以, false不可以 + "isSale" : true, //是否可以买,true可以, false不可以,废弃 + "cpuAmount" : 1, //cpu数量 + "cpuCores" : 1, //required,(单个)cpu核心数 + "cpuManufacturer" : "Intel", //required, cpu厂商 + "cpuModel" : "E5-2683V4", //required cpu处理器型号 + "cpuFrequency" : "2.1", //required cpu频率(G) + "memAmount" : "8", // required 内存条数量 + "memCapacity" : "32", // required 单个内存容量(GB) + "memModel" : "DDR4", //required + "ifAmount" : "2", //required 网卡数量 + "ifRate" : "10", //required 网卡接口传输速率(GE) + "gpuAmount" : "4", //GPU数量 + "gpuManufacturer" : "NVIDIA", //GPU厂商 + "gpuModel" : "V100", //GPU处理器型号 + "systemVolumeAmount" : "6", + "systemVolumeSize" : "E5-2683V4", + "systemVolumeModel" : "SSD", + "dataVolumeAmount" : "6", + "dataVolumeSize" : "6000", + "dataVolumeModel" : "SATA", + "diskAmount" : "4", + "source" : "common", //required 来源 common|customize +} +``` + +##### 响应示例 + +```json +{ + "success" : true +} +``` + +### 设备录入 + +##### url + +```http +v1/offline/createDevices +``` + +##### method + +```http +POST +``` + +##### 请求参数 + +```json +{ + "devices" : [ + { + "region" : "cn-north-1", + "az" : "cn-north-1a", + "sn" : "1B3MXP2", // required + "device_type" : "cps.c.normal", //required + "u_position" : "2",//槽位 + "cabinet" : "1",//机柜 + "ilo_ip":"10.208.11.131", //required 带外ip + } + ] +} +``` + +##### 响应示例 + +{ + "success" : true +} + +### 厂商和硬盘信息录入 + +##### url + +```http +v1/offline/collectManufacturerAndDisk +``` + +##### method + +```http +POST +``` + +##### 请求参数 + +```json +{ + "sns" : [ + "DP50CP2", + "1B3MXP2" + ], + "network_type" : "basic" +} +``` + +##### 响应示例 + +```json +{ + "success" : true +} +``` + +### 镜像录入 + +##### url + +```http +v1/offline/createImage +``` + +##### method + +```http +POST +``` + +##### 请求参数 + +```json +{ + "name_en" : "CentOS 6.6 64-bit", // required 长度介于1-200 + "name_zh" : "CentOS 6.6 64位", // required 长度介于1-200 + "version" : "1.0", // required + "os_id" : "o-1vc0l7zpnrt1rpnssudanmq01jbv", // required + "format" : "qcow2", // required qcow2|tar + "filename" : "v1.3.0-centos-6.6-2019081310.qcow2", // required + "url" : "{host}/v1.3.0-centos-6.6-2019081310.qcow2", // required + "hash" : "2058a93ca59798b96f446ef306bcf690",// required + "source" "common" // required common|customize +} +``` + +##### 响应示例 + +```json +{ + "success" : true +} +``` + +### raid录入 + +常见的raid方案有NORAID, RAID0, RAID1, RAID10, RAID51H, soft RAID1等,这些信息一般开始就录入进表了,后面基本不会动。故暂无接口 + +### 机型和raid关联 + +##### url + +```http +v1/offline/deviceTypes/associatedRaid +``` + +##### method + +```http +POST +``` + +##### 请求参数 + +```json +{ + "raid_id" : "r-sfykwibcvcyztuez3mk1klyha9nn", //required + "device_type" : "cps.gpu.1", ////required + "volume_type" : "data", ////required data|system + "volume_detail" : "300GB (2*300GB SAS)", ////required +} +``` + +##### 响应示例 + +```json +{ + "success" : true +} +``` + +### 机型和raid解关联 + +##### url + +```http +v1/offline/deviceTypes/dissociatedRaid +``` + +##### method + +```http +DELETE +``` + +##### 请求参数 + +```json +{ + "raid_id" : "r-sfykwibcvcyztuez3mk1klyha9nn", //required + "device_type" : "cps.gpu.1", //required + "volume_type" : "data", //required data|system + "volume_detail" : "300GB (2*300GB SAS)", // +} +``` + +##### 响应示例 + +```json +{ + "success" : true +} +``` + + + +### 查询设备类型列表 + +##### url + +```http +v1/offline/deviceTypes +``` + +##### method + +```http +GET +``` + +##### 请求参数 + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +region|String|否| |region +deviceType|String|否| |实例类型 + + +##### 请求响应 + +```json +{ + "deviceTypes": [ + { + "deviceType": "cps.gpu.4", //规格 + "name": "GPU IV", //实例类型 + "region": "cn-east-2", //地域 + "family": "gpu", //系列 + "cpuConcise": "12核", //cpu概述 + "cpuDetail": "2*Intel 2683V4(12核 2.2G)", //cpu详情 + "memConcise": "256G", //内存概述 + "memDetail": "256G(8*32G)", //内存详情 + "ifConcise": "2*10GE", //网卡概述 + "ifDetail": "2*10GE", //网卡详情 + "gpuConcise": "NVIDIA P40 * 4", //gpu概述 + "gpuDetail": "NVIDIA P40 * 4", //gpu详情 + "systemDiskAmount": 2, //系统盘数量 + "systemDiskSize": 300, //系统盘大小 + "systemDiskModel": "SAS", //系统盘类型 + "dataDiskAmount": 1, //数据盘数量 + "dataDiskSize": 4000, //数据盘大小 + "dataDiskModel": "SSD NVME", //数据盘类型 + "source": "common" //来源:通用common,定制customize,自定义user_defined + } + ] +} +``` + +### 机型管理列表 + +##### url + +```http +v1/offline/deviceTypes/plus +``` + +##### method + +```http +GET +``` + +##### 请求参数 + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +region|String|否| |region +deviceType|String|否|cps.s.normal |实例类型 +pageNumber|int|否| 1|第 几 页 +pageSize|int|否| 20|每页大小 + + +##### 请求响应 + +```json +{ + "deviceTypes": [ + { + "deviceType": "cps.gpu.4", //规格 + "name": "GPU IV", //实例类型名称 + "region": "cn-east-2", //地域 + "family": "gpu", //系列 + "cpuConcise": "12核", //cpu概述 + "cpuDetail": "2*Intel 2683V4(12核 2.2G)", //cpu详情 + "memConcise": "256G", //内存概述 + "memDetail": "256G(8*32G)", //内存详情 + "ifConcise": "2*10GE", //网卡概述 + "ifDetail": "2*10GE", //网卡详情 + "gpuConcise": "NVIDIA P40 * 4", //gpu概述 + "gpuDetail": "NVIDIA P40 * 4", //gpu详情 + "systemDiskAmount": 2, //系统盘数量 + "systemDiskSize": 300, //系统盘大小 + "systemDiskModel": "SAS", //系统盘类型 + "dataDiskAmount": 1, //数据盘数量 + "dataDiskSize": 4000, //数据盘大小 + "dataDiskModel": "SSD NVME", //数据盘类型 + "source": "common", //来源:通用common,定制customize,自定义user_defined + "osCount": 3, //关联镜像数 + "dataRaids": ["RAID0", "RAID1"], + "sysRaids": ["RAID0", "RAID1"], + "serviceCode": "cps" //所属产品,cps(物理服务器)/edcps(分布式物理服务器) + } + ], + "pageNumber": 1, + "pageSize": 20, + "totalCount": 12 +} +``` + +### 查询镜像列表 + +##### url + +```http +v1/offline/oss +``` + +##### method + +```http +get +``` + +##### 请求参数 + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +region|String|否| |region +deviceType|String|否| cps.s.normal|实例类型(规格) +imageType|String|否| standard|镜像类型,标准镜像,非必填 +osType|String|否| CentOS|操作系统:CentOS,Ubuntu,非必填 +source|String|否| common|来源:通用 common,定制 customize,自定义user_defined,非必填 +pageNumber|int|否| 1|第 几 页 +pageSize|int|否| 20|每页大小 + +##### 响应参数 + +```json +{ + "oss": [ + { + "osTypeId": "i-abcdadoiadld", //镜像id + "osName": "CentOS7.4 64位", //操作系统名称 + "deviceType": "cps.c.normal", //实例类型(规格) + "osType": "CentOS", //操作系统:CentOS,Ubuntu + "osVersion": "7.4", //版本 + "source": "common" //来源:通用common,定制customize,自定义user_defined + } + ], + "pageNumber": 1, + "pageSize": 20, + "totalCount": 12 +} +``` + +### 关联镜像 + +##### url + +```http +v1/offline/deviceTypes/associatedImage +``` + +##### method + +```http +POST +``` + +##### 请求参数 +```json +{ + "region": "cn-north-1", //必填 + "deviceType": "cps.s.normal", //必填,实例类型(规格) + "osTypeIds": ["i-abcdadoiadld","i-adfaladida"], //镜像id,必填 + "pin": "test01" //给用户关联镜像时必填,其他情况不填 +} +``` + +##### 响应参数 + +```json +{ + "success": true +} +``` + +### 移除镜像 + +##### url + +```http +v1/offline/deviceTypes/dissociatedImage +``` + +##### method + +```http +Delete +``` + +##### 请求参数 + +```json +{ + "region": "cn-north-1", //必填 + "deviceType": "cps.s.normal", //必填,实例类型(规格) + "osTypeId": "i-abcdadoiadld", //镜像id,必填 + "pin": "test01" //给用户移除镜像时必填,其他情况不填 +} +``` + +##### 响应参数 + +```json +{ + "success": true +} +``` + +### 查询raid列表 + +##### url + +```http +v1/offline/raids +``` + +##### method + +```http +get +``` + +##### 请求参数 + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +deviceType|String|否| cps.s.normal|实例类型(规格) + + +##### 响应参数 + +```json +{ + "raids": [ + { + "raidTypeId": "r-lowdd8nf8y7v6jk5ocr5paqhvhre", //raid id + "raidType": "RAID1", //raid类型名称 + "deviceType": "cps.c.normal", //实例类型 + "volumeType": "system", //磁盘类型:system,data + "volumeDetail": "6720GB (14*960GB SATA)", + "description": "描述" + } + ] +} +``` + +### 查询用户列表 + +##### url + +```http +v1/offline/users +``` + +##### method + +```http +get +``` + +##### 请求参数 + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +pageNumber|int|否| 1|第 几 页 +pageSize|int|否| 20|每页大小 + +- pageNumber=1 第 1 页 +- pageSize=20 每页大小 + +##### 响应参数 + +```json +{ + "users": [ + { + "pin": "cloudid001", + "companyName": "东东有限公司" + } + ], + "pageNumber": 1, + "pageSize": 10, + "totalCount": 2 +} +``` + +### 查询用户详情 + +##### url + +```http +v1/offline/user +``` + +##### method + +```http +get +``` + +##### 请求参数 + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +username|String|否| |用户名 + + +##### 响应参数 + +```json +{ + "user": { + "pin": "cloudid001", + "companyName": "", + "phoneNumber": "13811622092", + "email": "hexinlei@jd.com", + "companyAuthStatus": false + } +} +``` + + + + + +### 查询当前登录用户 + +##### url + +```http +v1/offline/userLogin +``` + +##### method + +```http +get +``` + +##### 请求参数 + +_无_ + +##### 响应参数 + +```json +{ + "userName": "xxx" +} +``` + +### 查询实例列表-已废弃 + +##### url + +```http +v1/offline/instanceList +``` + +##### method + +```http +get +``` + +##### 请求参数 + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +pageNumber|int|否| 1|第 几 页 +pageSize|int|否| 20|每页大小 + + +##### 响应参数 + +```json +{ + "instances": [ + { + "pin": "xxx", + "instanceId": "cps-vibbcnxisj768nccslap8zqjj3lf", + "region": "华北-北京", + "az": "可用区B", + "deviceType": "标准计算型", + "regionEn": "cn-north-1", + "azEn": "cn-north-1b", + "deviceTypeEn": "cps.c.normal", + "name": "bm_test", + "description": "weqe", + "bandwidth": 1, //带宽 + "extraUplinkBandwidth": 20, //额外上行带宽 + "lineType": "bgp", //带宽类型(中文) + "lineTypeEn": "bgp", //带宽类型(英文) + "sn": "1B3MXP2", //设备号 + "privateIp": "10.0.0.2", //内网IP + "publicIp": "10.0.0.2", //公网ip + } + ], + "pageNumber": 1, + "pageSize": 10, + "totalCount": 2 +} +``` + +### 导出实例列表-已废弃 + +##### url + +```http +v1/offline/exportInstances +``` + +##### method + +```http +get +``` + +##### 请求参数 + +_无_ + +##### 响应参数 + +_无_ + +### 查询设备实例列表 + +##### url + +```http +v1/offline/deviceInstanceList +``` + +##### method + +```http +get +``` + +##### 请求参数 + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +instanceId|String|否| |实例 id +sn|String|否| |实例 sn(支持多选,逗号分隔) +saleStatus|String|否| |售卖状态 +status|String|否| |实例状态 +iloIp|String|否| |带外ip(支持多选,逗号分隔) +publicIp|String|否| |公网ip(支持多选,逗号分隔) +privateIp|String|否| |内网ip(支持多选,逗号分隔) +startTime|int64|否| |开始时间 +endTime|int64|否| |开始时间 +pageNumber|int|否| 1|第 几 页 +pageSize|int|否| 20|每页大小 + +##### 响应参数 + +```json +{ + "deviceInstances": [ + { + "pin": "xxx", + "instanceId": "cps-vibbcnxisj768nccslap8zqjj3lf", + "region": "华北-北京", + "az": "可用区B", + "deviceType": "标准计算型", + "regionEn": "cn-north-1", + "azEn": "cn-north-1b", + "deviceTypeEn": "cps.c.normal", + "name": "bm_test", + "description": "weqe", + "status": "销毁中", //实例状态 + "statusEn": "destroying", + "sn": "1B3MXP2", + "iloIp": "10.208.11.131", + "cabinet": "23234343", + "uPosition": "24-28", + "saleStatus": "已售卖", + "saleStatusEn": "sold", + "osName": "CentOS 6.6 64位", + "osType": "CentOS", + "privateIp": "10.0.0.2", + "publicIp": "10.0.0.2", + "bandwidth": 10, //带宽 + "extraUplinkBandwidth": 10, //额外上行带宽 + "switchIpOne": "10.208.11.35", //交换机1 ip + "switchIpTwo": "10.208.11.35", //交换机2 ip + "eth0SwitchPort": "Ten-GigabitEthernet1/0/2", // eth0 + "eth1SwitchPort": "Ten-GigabitEthernet1/0/26", // eth1 + "secondaryIp": ["xxx", "xxxx"], //别名ip + } + ] +} +``` + +### 查询设备实例详情 + +##### url + +```http +v1/offline/deviceInstance +``` + +##### method + +```http +get +``` + +##### 请求参数 + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +sn|String|否| |实例 sn + + + +##### 响应参数 + +```json +{ + "deviceInstance": { + "pin": "xxx", + "instanceId": "cps-vibbcnxisj768nccslap8zqjj3lf", + "region": "华北-北京", + "az": "可用区B", + "deviceType": "标准计算型", + "regionEn": "cn-north-1", + "azEn": "cn-north-1b", + "deviceTypeEn": "cps.c.normal", + "name": "bm_test", + "description": "weqe", + "status": "销毁中", //实例状态 + "statusEn": "destroying", + "sn": "1B3MXP2", + "iloIp": "10.208.11.131", + "cabinet": "23234343", + "uPosition": "24-28", + "saleStatus": "已售卖", + "saleStatusEn": "sold", + "osName": "CentOS 6.6 64位", + "osType": "CentOS", + "privateIp": "10.0.0.2", + "publicIp": "10.0.0.2", + "bandwidth": 10, //带宽 + "extraUplinkBandwidth": 10, //额外上行带宽 + "switchIpOne": "10.208.11.35", //交换机1 ip + "switchIpTwo": "10.208.11.35", //交换机2 ip + "eth0SwitchPort": "Ten-GigabitEthernet1/0/2", // eth0 + "eth1SwitchPort": "Ten-GigabitEthernet1/0/26", // eth1 + "secondaryIp": ["xxx", "xxxx"], //别名ip + } +} +``` + +### 导出设备实例列表 + +##### url + +```http +v1/offline/exportDeviceInstanceList +``` + +##### method + +```http +get +``` + +##### 请求参数 + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +instanceId|String|否| |实例 id +sn|String|否| |实例 sn(支持多选,逗号分隔) +saleStatus|String|否| |售卖状态 +status|String|否| |实例状态 +iloIp|String|否| |带外ip(支持多选,逗号分隔) +publicIp|String|否| |公网ip(支持多选,逗号分隔) +privateIp|String|否| |内网ip(支持多选,逗号分隔) +startTime|int64|否| |开始时间 +endTime|int64|否| |开始时间 + + +##### 响应参数 + +_无_ + +### 查询设备库存 + +##### url + +```http +v1/offline/devicesStock +``` + +##### method + +```http +get +``` + +##### 请求参数 + + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +deviceType|String|否| |设备类型 +pageNumber|int|否| 1|第 几 页 +pageSize|int|否| 20|每页大小 + + +##### 响应参数 + +```json +{ + "devicesStock": [ + { + "region": "华北-北京", + "az": "可用区B", + "deviceType": "标准计算型", + "regionEn": "cn-north-1", + "azEn": "cn-north-1b", + "deviceTypeEn": "cps.c.normal", + "total": 100, //总数 + "alreadyOnline": 10, //开放售卖数量 + "alreadySold": 20, //已售卖数量 + "unSold": 20, //剩余数量 + "unOnline": 20 //未开放售卖数量 + } + ], + "pageNumber": 1, + "pageSize": 10, + "totalCount": 2 +} +``` + +### 导出设备库存 + +##### url + +```http +v1/offline/exportDevicesStock +``` + +##### method + +```http +get +``` + +##### 请求参数 + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +deviceType|String|否| |设备类型 + +##### 响应参数 + +_无_ + +### 设备上架 + +##### url + +```http +v1/offline/putawayDevices +``` + +##### method + +```http +put +``` + +##### 请求 body + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +sn|[]String|是| |设备sn + +##### 响应参数 + +```json +{ + "success": true +} +``` + +### 设备下架 + +##### url + +```http +v1/offline/unPutawayDevices +``` + +##### method + +```http +put +``` + +##### 请求 body + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +sn|[]String|是| |设备sn + +##### 响应参数 + +```json +{ + "success": true +} +``` + +### 设备回收 + +##### url + +```http +v1/offline/instance +``` + +##### method + +```http +delete +``` + +##### 请求参数 + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +instanceId|String|是| |实例id + + + +##### 响应参数 + +```json +{ + "success": true +} +``` + +### 售卖状态查询 + +##### url + +```http +v1/offline/saleStatus +``` + +##### method + +```http +get +``` + +##### 请求参数 + +_无_ + +##### 响应参数 + +```json +{ + "saleStatus": [ + { + "status": "sold", + "statusName": "已售卖" + }, + { + "status": "selling", + "statusName": "售卖中" + }, + { + "status": "putawaying", + "statusName": "上架" + } + ] +} +``` + +### 实例状态查询 + +##### url + +```http +v1/offline/instanceStatus +``` + +##### method + +```http +get +``` + +##### 请求参数 + +_无_ + +##### 响应参数 + +```json +{ + "instanceStatus": [ + { + "status": "creating", + "statusName": "创建中" + }, + { + "status": "starting", + "statusName": "开机中" + }, + { + "status": "running", + "statusName": "运行" + }, + { + "status": "stopping", + "statusName": "关机中" + }, + { + "status": "stopped", + "statusName": "关机" + }, + { + "status": "restarting", + "statusName": "重启中" + }, + { + "status": "reinstalling", + "statusName": "重装系统中" + }, + { + "status": "destroying", + "statusName": "销毁中" + }, + { + "status": "error", + "statusName": "错误" + }, + { + "status": "upgrading", + "statusName": "调整配置中" + }, + { + "status": "resetting_password", + "statusName": "重置密码中" + } + ] +} +``` + +### 机型管理列表 + +##### url + +```http +v1/offline/deviceTypes/plus +``` + +##### method + +```http +GET +``` + +##### 请求参数 + + +参数名|类型|是否必须|默认值|描述 +---|---|---|---|--- +deviceType|String|否|cps.s.normal |实例类型,非必填 +pageNumber|int|否| 1|第 几 页 +pageSize|int|否| 20|每页大小 + + +##### 请求响应 + +```json +{ + "deviceTypes": [ + { + "deviceType": "cps.gpu.4", //规格 + "name": "GPU IV", //实例类型 + "region": "cn-east-2", //地域 + "family": "gpu", //系列 + "cpuConcise": "12核", //cpu概述 + "cpuDetail": "2*Intel 2683V4(12核 2.2G)", //cpu详情 + "memConcise": "256G", //内存概述 + "memDetail": "256G(8*32G)", //内存详情 + "ifConcise": "2*10GE", //网卡概述 + "ifDetail": "2*10GE", //网卡详情 + "gpuConcise": "NVIDIA P40 * 4", //gpu概述 + "gpuDetail": "NVIDIA P40 * 4", //gpu详情 + "systemDiskAmount": 2, //系统盘数量 + "systemDiskSize": 300, //系统盘大小 + "systemDiskModel": "SAS", //系统盘类型 + "dataDiskAmount": 1, //数据盘数量 + "dataDiskSize": 4000, //数据盘大小 + "dataDiskModel": "SSD NVME", //数据盘类型 + "source": "common", //来源:通用common,定制customize,自定义user_defined + "osCount": 3, //关联镜像数 + "dataRaids": ["RAID0", "RAID1"], + "sysRaids": ["RAID0", "RAID1"], + "serviceCode": "cps" //所属产品,cps/edcps + } + ], + "pageNumber": 1, + "pageSize": 20, + "totalCount": 12 +} +``` diff --git a/bmp-scheduler/docs/resources/bmp(open-source)arch.png b/bmp-scheduler/docs/resources/bmp(open-source)arch.png new file mode 100644 index 0000000..6b080d5 Binary files /dev/null and b/bmp-scheduler/docs/resources/bmp(open-source)arch.png differ diff --git a/bmp-scheduler/docs/resources/cps-lifecycle.gliffy b/bmp-scheduler/docs/resources/cps-lifecycle.gliffy new file mode 100644 index 0000000..2c2c95b --- /dev/null +++ b/bmp-scheduler/docs/resources/cps-lifecycle.gliffy @@ -0,0 +1 @@ +{"contentType":"application/gliffy+json","version":"1.1","metadata":{"title":"untitled","revision":0,"exportBorder":false},"embeddedResources":{"index":0,"resources":[]},"stage":{"objects":[{"x":-358.5,"y":-30.5,"rotation":0,"id":2,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":0,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[1293,165],[1043,165]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":10,"uid":null,"width":13,"height":27,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

    1

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":53,"px":0,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":49,"px":1,"py":0.5}}},"linkMap":[]},{"x":384.5,"y":284.5,"rotation":0,"id":25,"uid":"com.gliffy.shape.basic.basic_v1.default.ellipse","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":2,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#b7b7b7","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.461538461538461,"y":0,"rotation":0,"id":26,"uid":null,"width":155.0769230769231,"height":54,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

    开机中\n

    starting

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":104.5,"y":284.5,"rotation":0,"id":27,"uid":"com.gliffy.shape.basic.basic_v1.default.ellipse","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":4,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":1,"strokeColor":"#000000","fillColor":"#b7b7b7","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.461538461538461,"y":0,"rotation":0,"id":28,"uid":null,"width":155.0769230769231,"height":54,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

    创建中\n

    creating

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":644.5,"y":284.5,"rotation":0,"id":29,"uid":"com.gliffy.shape.basic.basic_v1.default.ellipse","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":6,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#93c47d","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.461538461538461,"y":0,"rotation":0,"id":30,"uid":null,"width":155.0769230769231,"height":54,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

    运行\n

    running

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":644.5,"y":534.5,"rotation":0,"id":31,"uid":"com.gliffy.shape.basic.basic_v1.default.ellipse","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":8,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#b7b7b7","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.461538461538461,"y":0,"rotation":0,"id":32,"uid":null,"width":155.0769230769231,"height":54,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

    关机中\n

    stopping

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":384.5,"y":534.5,"rotation":0,"id":33,"uid":"com.gliffy.shape.basic.basic_v1.default.ellipse","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":10,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#93c47d","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.461538461538461,"y":0,"rotation":0,"id":34,"uid":null,"width":155.0769230769231,"height":54,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

    关机\n

    stopped

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":934.5,"y":284.5,"rotation":0,"id":35,"uid":"com.gliffy.shape.basic.basic_v1.default.ellipse","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":12,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#b7b7b7","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.461538461538461,"y":0,"rotation":0,"id":36,"uid":null,"width":155.0769230769231,"height":54,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

    重启中\n

    restarting

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":104.5,"y":534.5,"rotation":0,"id":37,"uid":"com.gliffy.shape.basic.basic_v1.default.ellipse","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":14,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#b7b7b7","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.461538461538461,"y":0,"rotation":0,"id":38,"uid":null,"width":155.0769230769231,"height":81,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

    密码重置中\n

    restarting_password

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":384.5,"y":754.5,"rotation":0,"id":39,"uid":"com.gliffy.shape.basic.basic_v1.default.ellipse","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":16,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#b7b7b7","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.4615384615384603,"y":0,"rotation":0,"id":40,"uid":null,"width":155.07692307692307,"height":54,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

    销毁中\n

    destroying

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":104.5,"y":754.5,"rotation":0,"id":41,"uid":"com.gliffy.shape.basic.basic_v1.default.ellipse","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":18,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#93c47d","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.461538461538461,"y":0,"rotation":0,"id":42,"uid":null,"width":155.0769230769231,"height":54,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

    已销毁\n

    destroyed

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":934.5,"y":534.5,"rotation":0,"id":43,"uid":"com.gliffy.shape.basic.basic_v1.default.ellipse","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":20,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#cc0000","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.461538461538461,"y":0,"rotation":0,"id":44,"uid":null,"width":155.0769230769231,"height":54,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

    错误\n

    error

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":644.5,"y":754.5,"rotation":0,"id":45,"uid":"com.gliffy.shape.basic.basic_v1.default.ellipse","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":22,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#b7b7b7","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.461538461538461,"y":0,"rotation":0,"id":46,"uid":null,"width":155.0769230769231,"height":54,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

    调整配置中\n

    upgrading

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":934.5,"y":754.5,"rotation":0,"id":47,"uid":"com.gliffy.shape.basic.basic_v1.default.ellipse","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":24,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#b7b7b7","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.461538461538461,"y":0,"rotation":0,"id":48,"uid":null,"width":155.0769230769231,"height":54,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

    重装系统中\n

    reinstalling

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":524.5,"y":84.5,"rotation":0,"id":49,"uid":"com.gliffy.shape.basic.basic_v1.default.ellipse","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":26,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#4a86e8","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.461538461538461,"y":0,"rotation":0,"id":50,"uid":null,"width":155.0769230769231,"height":54,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

    在售\n

    selling

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":104.5,"y":84.5,"rotation":0,"id":51,"uid":"com.gliffy.shape.basic.basic_v1.default.ellipse","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":28,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#4a86e8","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.461538461538461,"y":0,"rotation":0,"id":52,"uid":null,"width":155.0769230769231,"height":54,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

    已售\n

    sold

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":934.5,"y":84.5,"rotation":0,"id":53,"uid":"com.gliffy.shape.basic.basic_v1.default.ellipse","width":160,"height":100,"lockAspectRatio":false,"lockShape":false,"order":30,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#4a86e8","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[{"x":2.461538461538461,"y":0,"rotation":0,"id":54,"uid":null,"width":155.0769230769231,"height":54,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"

    上架中\n

    putawaying

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"linkMap":[]},{"x":-354.5,"y":296.5,"rotation":0,"id":57,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":32,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[879,-162],[619,-162]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":58,"uid":null,"width":13,"height":27,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

    2

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":49,"px":0,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":51,"px":1,"py":0.5}}},"linkMap":[]},{"x":-366.5,"y":407.5,"rotation":0,"id":59,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":34,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[551,-223],[551,-123]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":67,"uid":null,"width":13,"height":27,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

    3

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":51,"px":0.5,"py":1}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":27,"px":0.5,"py":0}}},"linkMap":[]},{"x":-54.5,"y":605.5,"rotation":0,"id":61,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":36,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[319,-271],[439,-271]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":68,"uid":null,"width":13,"height":27,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

    4

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":27,"px":1,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":25,"px":0,"py":0.5}}},"linkMap":[]},{"x":58.5,"y":739.5,"rotation":0,"id":62,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":38,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[486,-405],[586,-405]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":69,"uid":null,"width":13,"height":27,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

    5

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":25,"px":1,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":29,"px":0,"py":0.5}}},"linkMap":[]},{"x":7.5,"y":1001.5,"rotation":0,"id":63,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":40,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":2,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[797,-667],[927,-667]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":64,"uid":null,"width":47,"height":27,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

    9,10

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":29,"px":1,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":35,"px":0,"py":0.5}}},"linkMap":[]},{"x":220.5,"y":646.5,"rotation":0,"id":65,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":42,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[504,-262],[504,-112]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":66,"uid":null,"width":13,"height":27,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

    6

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":29,"px":0.5,"py":1}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":31,"px":0.5,"py":0}}},"linkMap":[]},{"x":345.5,"y":776.5,"rotation":0,"id":70,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":44,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[299,-192],[199,-192]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":71,"uid":null,"width":13,"height":27,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

    7

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":31,"px":0,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":33,"px":1,"py":0.5}}},"linkMap":[]},{"x":361.5,"y":918.5,"rotation":0,"id":72,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":46,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":2,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[23,-334],[-97,-334]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":73,"uid":null,"width":58,"height":27,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

    11,12

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":33,"px":0,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":37,"px":1,"py":0.5}}},"linkMap":[]},{"x":363.5,"y":880.5,"rotation":0,"id":74,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":48,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[101,-246],[101,-126]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":75,"uid":null,"width":27,"height":27,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

    13

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":33,"px":0.5,"py":1}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":39,"px":0.5,"py":0}}},"linkMap":[]},{"x":311.5,"y":1017.5,"rotation":0,"id":76,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":50,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[73,-213],[-47,-213]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":77,"uid":null,"width":27,"height":27,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

    14

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":39,"px":0,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":41,"px":1,"py":0.5}}},"linkMap":[]},{"x":535.5,"y":920.5,"rotation":0,"id":78,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":52,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":2,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-17,-301],[399,-116]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":79,"uid":null,"width":60,"height":27,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

    15,16

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":47,"px":0,"py":0.5}}},"linkMap":[]},{"x":373.5,"y":890.5,"rotation":0,"id":80,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":54,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[91,-256],[271,-86]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":81,"uid":null,"width":27,"height":27,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

    17

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":33,"px":0.5,"py":1}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":45,"px":0,"py":0.5}}},"linkMap":[]},{"x":7.5,"y":944.5,"rotation":0,"id":82,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":56,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":true,"interpolationType":"linear","cornerRadius":null,"controlPath":[[97,-140],[57,-140],[57,-900],[597,-900],[597,-860]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":83,"uid":null,"width":27,"height":27,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

    18

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":41,"px":0,"py":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":49,"px":0.5,"py":0}}},"linkMap":[]},{"x":67.5,"y":740.5,"rotation":0,"id":84,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":59,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[397,-206],[397,-356]],"lockSegments":{}}},"children":[{"x":0,"y":0,"rotation":0,"id":85,"uid":null,"width":13,"height":27,"lockAspectRatio":false,"lockShape":false,"order":"auto","graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"both","vposition":"none","hposition":"none","html":"

    8

    ","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null}],"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":33,"px":0.5,"py":0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":25,"px":0.5,"py":1}}},"linkMap":[]}],"background":"#FFFFFF","width":1095,"height":855,"maxWidth":5000,"maxHeight":5000,"nodeIndex":87,"autoFit":true,"exportBorder":false,"gridOn":true,"snapToGrid":true,"drawingGuidesOn":true,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"shapeStyles":{"com.gliffy.shape.basic.basic_v1.default":{"fill":"#cc0000","stroke":"#000000","strokeWidth":1,"gradient":false}},"lineStyles":{"global":{"endArrow":2,"startArrow":2,"orthoMode":0}},"textStyles":{},"themeData":null}} \ No newline at end of file diff --git a/bmp-scheduler/docs/resources/cps-lifecycle.png b/bmp-scheduler/docs/resources/cps-lifecycle.png new file mode 100644 index 0000000..ce69d5d Binary files /dev/null and b/bmp-scheduler/docs/resources/cps-lifecycle.png differ diff --git a/bmp-scheduler/docs/resources/private-cps-jdstack-arch.png b/bmp-scheduler/docs/resources/private-cps-jdstack-arch.png new file mode 100644 index 0000000..51f082f Binary files /dev/null and b/bmp-scheduler/docs/resources/private-cps-jdstack-arch.png differ diff --git a/bmp-scheduler/emailTemplate/checkTimeoutCommandTpl.go b/bmp-scheduler/emailTemplate/checkTimeoutCommandTpl.go new file mode 100644 index 0000000..1f4af9b --- /dev/null +++ b/bmp-scheduler/emailTemplate/checkTimeoutCommandTpl.go @@ -0,0 +1,104 @@ +package emailTemplate + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/instanceDao" +) + +type CheckTimeoutCommandTpl struct { + CurrentDate string + Commands []*commandDao.Command + Device deviceDao.Device + Instance instanceDao.Instance +} + +const CheckTimeoutCommandMailContent string = ` + + + + + + +

    hi all:

    +

    统计时间:

    + + + + + + + + + + + + + + + + + + + + + + + +
    idcIddevice_type_idsnilo_ipinstance_idnamestatus
    +
    + + + + + + + + + + + + + + + + + + {{range .Commands}} + + + + + + + + + + + + + + {{end}} + +
    idrequest_idsninstance_idactiontypestatusparent_command_idexecute_countcreate_timeupdate_time
    + +` diff --git a/bmp-scheduler/go.mod b/bmp-scheduler/go.mod new file mode 100644 index 0000000..98b7fc2 --- /dev/null +++ b/bmp-scheduler/go.mod @@ -0,0 +1,22 @@ +module coding.jd.com/aidc-bmp/bmp-scheduler + +go 1.15 + +require ( + git.jd.com/cps-golang/ironic-common v0.0.0-00010101000000-000000000000 + git.jd.com/cps-golang/log v0.0.0-00010101000000-000000000000 + github.com/beego/beego/v2 v2.0.1 + github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df + github.com/go-redis/redis v6.14.2+incompatible + github.com/go-sql-driver/mysql v1.6.0 + github.com/jinzhu/gorm v1.9.16 + github.com/streadway/amqp v1.0.0 + golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 + gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect + gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect + gopkg.in/goyy/goyy.v0 v0.0.0-20190218140538-82e7740e526e +) + +replace git.jd.com/cps-golang/log => ./bmp_vendor/log + +replace git.jd.com/cps-golang/ironic-common => ./bmp_vendor/ironic-common diff --git a/bmp-scheduler/go.sum b/bmp-scheduler/go.sum new file mode 100644 index 0000000..71831b9 --- /dev/null +++ b/bmp-scheduler/go.sum @@ -0,0 +1,311 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= +github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk= +github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y= +github.com/beego/beego/v2 v2.0.1 h1:07a7Z0Ok5vbqyqh+q53sDPl9LdhKh0ZDy3gbyGrhFnE= +github.com/beego/beego/v2 v2.0.1/go.mod h1:8zyHi1FnWO1mZLwTn62aKRIZF/aIKvkCBB2JYs+eqQI= +github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ= +github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60= +github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= +github.com/coreos/etcd v3.3.25+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U= +github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= +github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= +github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd h1:83Wprp6ROGeiHFAP8WJdI2RoxALQYgdllERc3N5N2DM= +github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= +github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= +github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk= +github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y= +github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0= +github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= +github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df h1:Bao6dhmbTA1KFVxmJ6nBoMuOJit2yjEgLJpIMYpop0E= +github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df/go.mod h1:GJr+FCSXshIwgHBtLglIg9M2l2kQSi6QjVAngtzI08Y= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-redis/redis v6.14.2+incompatible h1:UE9pLhzmWf+xHNmZsoccjXosPicuiNaInPgym8nzfg0= +github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= +github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o= +github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.0.1 h1:HjfetcXq097iXP0uoPCdnM4Efp5/9MsM0/M+XOTeR3M= +github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDuKuq+uX4v1fulaMbA/7ZLLhjc85h7chZGBCQ= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.1.1 h1:sJZmqHoEaY7f+NPP8pgLB/WxulyR3fewgCM2qaSlBb4= +github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus= +github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U= +github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mitchellh/mapstructure v1.3.3 h1:SzB1nHZ2Xi+17FP0zVQBHIZqvwRN9408fJO8h+eeNA8= +github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.0 h1:Iw5WCbBcaAAd0fpRb1c9r5YCylv4XDoCSigm1zLevwU= +github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= +github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.7.0 h1:wCi7urQOGBsYcQROHqpUUX4ct84xp40t9R9JX0FuA/U= +github.com/prometheus/client_golang v1.7.0/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.10.0 h1:RyRA7RzGXQZiW+tGMr7sxa85G1z0yOpM1qq5c8lNawc= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.1.3 h1:F0+tqvhOksq22sc6iCHF5WGlWjdwj92p0udFh1VFBS8= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= +github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= +github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s= +github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE= +github.com/streadway/amqp v1.0.0 h1:kuuDrUJFZL1QYL9hUNuCxNObNzB0bV/ZG5jV3RWAQgo= +github.com/streadway/amqp v1.0.0/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= +github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= +go.etcd.io/etcd v3.3.25+incompatible/go.mod h1:yaeTdrJi5lOmYerz05bd8+V7KubZs8YSFZfzsF9A6aI= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f h1:+Nyd8tzPX9R7BWHguqsrbFdRx3WQ/1ib8I44HXV5yTA= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58 h1:1Bs6RVeBFtLZ8Yi1Hk07DiOqzvwLD/4hln4iahvFlag= +golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk= +gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE= +gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw= +gopkg.in/goyy/goyy.v0 v0.0.0-20190218140538-82e7740e526e h1:gtdbyLCHNaTi70xKjFhe89/vCZvQ/rlPcRyQNgtiArY= +gopkg.in/goyy/goyy.v0 v0.0.0-20190218140538-82e7740e526e/go.mod h1:0xBRLJ/WNDqMy7AGJ/CtRXvdKgU94c7uZ2oeqMR1FgA= +gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.5/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= diff --git a/bmp-scheduler/logic/auditLogLogic/auditLogLogic.go b/bmp-scheduler/logic/auditLogLogic/auditLogLogic.go new file mode 100644 index 0000000..ebee34b --- /dev/null +++ b/bmp-scheduler/logic/auditLogLogic/auditLogLogic.go @@ -0,0 +1,96 @@ +package auditLogLogic + +import ( + "time" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/auditLogsDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/userDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + log "git.jd.com/cps-golang/log" +) + +func SaveAuditLogs(logger *log.Logger, sn string, instanceId string, msgType string) error { + + userID := logger.GetPoint("user_id").(string) + var username string + if userID != "" { + userEntity, err := userDao.GetUserById(logger, userID) + if err != nil { + logger.Warnf("SaveAuditLogs.GetUserById error, user_id:%s, error:%s", userID, err.Error()) + } else { + username = userEntity.UserName + } + } + + deviceEntity, err := deviceDao.GetBySn(logger, sn) + if err != nil { + logger.Warnf("SaveAuditLogs.GetBySn error, sn:%s, error:%s", sn, err.Error()) + } + + al := &auditLogsDao.AuditLogs{ + Logid: util.GetUuid("al-"), + Sn: sn, + InstanceID: instanceId, + DeviceID: deviceEntity.DeviceID, + Operation: msgType, + OperateUserID: userID, + OperateUserName: username, + CreatedTime: int(time.Now().Unix()), + Result: "doing", + } + _, err = auditLogsDao.AddAuditLogs(logger, al) + if err != nil { + logger.Warnf("SaveAuditLogs.AddAuditLogs error, al:%s, error:%s", util.ObjToJson(al), err.Error()) + } else { + logger.Warnf("SaveAuditLogs.AddAuditLogs success, al:%s", util.ObjToJson(al)) + } + return err +} + +func SetAuditLogToSuccess(logger *log.Logger, sn string, instanceId string, msgType string) error { + + q := map[string]interface{}{ + "is_del": 0, + "sn": sn, + "instance_id": instanceId, + "operation": msgType, + } + al, err := auditLogsDao.GetOneUnfinishedAuditLogs(logger, sn, instanceId, msgType) + if err != nil { + logger.Warnf("SetAuditLogToSuccess.GetOneAuditLogs error, query:%s, error:%s", util.ObjToJson(q), err.Error()) + return err + } + al.Result = "success" + al.UpdatedTime = int(time.Now().Unix()) + + if err := auditLogsDao.UpdateAuditLogsById(logger, al); err != nil { + logger.Warnf("SetAuditLogToSuccess.UpdateAuditLogsById error, query:%s, error:%s", util.ObjToJson(q), err.Error()) + return err + } + return nil +} + +func SetAuditLogToFail(logger *log.Logger, sn string, instanceId string, msgType string, reason string) error { + + q := map[string]interface{}{ + "is_del": 0, + "sn": sn, + "instance_id": instanceId, + "operation": msgType, + } + al, err := auditLogsDao.GetOneUnfinishedAuditLogs(logger, sn, instanceId, msgType) + if err != nil { + logger.Warnf("SetAuditLogToSuccess.GetOneAuditLogs error, query:%s, error:%s", util.ObjToJson(q), err.Error()) + return err + } + al.Result = "fail" + al.FailReason = reason + al.UpdatedTime = int(time.Now().Unix()) + + if err := auditLogsDao.UpdateAuditLogsById(logger, al); err != nil { + logger.Warnf("SetAuditLogToFail.UpdateAuditLogsById error, query:%s, error:%s", util.ObjToJson(q), err.Error()) + return err + } + return nil +} diff --git a/bmp-scheduler/logic/commandLogic/commandLogic.go b/bmp-scheduler/logic/commandLogic/commandLogic.go new file mode 100644 index 0000000..9c54111 --- /dev/null +++ b/bmp-scheduler/logic/commandLogic/commandLogic.go @@ -0,0 +1,60 @@ +package commandLogic + +import ( + "time" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/types" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandStatus" + log "git.jd.com/cps-golang/log" +) + +func Create(logger *log.Logger, param types.CreateCommandRequest) int64 { + entity := &commandDao.Command{ + RequestID: param.RequestId, + Sn: param.Sn, + Action: param.Action, + Type: param.CommandType, + InstanceID: param.InstanceId, + Status: CommandStatus.WAIT, + ExecuteCount: 0, + ParentCommandID: param.ParentCommandId, + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + } + id, err := commandDao.AddCommand(logger, entity) + if err != nil { + panic(err) + } + return id +} + +func GetBySnAndActionAndStatus(logger *log.Logger, sn, action, status string) (*commandDao.Command, error) { + param := map[string]interface{}{ + "sn": sn, + "action": action, + "status": status, + "is_del": 0, + } + return commandDao.GetOneCommand(logger, param) +} + +func QueryTimeoutCommands(logger *log.Logger, stime, etime time.Time) ([]*commandDao.Command, error) { + statuses := []string{CommandStatus.RUNNING, CommandStatus.ERROR} + param := map[string]interface{}{ + "is_del": 0, + "timeout_time.gt": stime.String(), + "timeout_time.lt": etime.String(), + "status.in": statuses, + } + return commandDao.GetAllCommand(logger, param) +} + +func QueryCommandsByRequestIdAndSn(logger *log.Logger, request_id, sn string) ([]*commandDao.Command, error) { + param := map[string]interface{}{ + "is_del": 0, + "request_id": request_id, + "sn": sn, + } + return commandDao.GetAllCommand(logger, param) +} diff --git a/bmp-scheduler/logic/deviceLogic/deviceLogic.go b/bmp-scheduler/logic/deviceLogic/deviceLogic.go new file mode 100644 index 0000000..04c2c54 --- /dev/null +++ b/bmp-scheduler/logic/deviceLogic/deviceLogic.go @@ -0,0 +1,53 @@ +package deviceLogic + +import ( + deviceDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "fmt" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +func GetById(logger *log.Logger, deviceId string) (*deviceDao.Device, error) { + return deviceDao.GetDeviceById(logger, deviceId) +} + +func GetBySn(logger *log.Logger, sn string) (*deviceDao.Device, error) { + return deviceDao.GetDeviceBySn(logger, sn) +} + +func GetDelBySn(logger *log.Logger, sn string) (*deviceDao.Device, error) { + param := map[string]interface{}{ + "is_del": 1, + "sn": sn, + } + devices, err := deviceDao.GetMultiDevice(logger, param, nil, []string{"update_time"}, []string{"desc"}, 0, 1) + if devices != nil { + return devices[0], nil + } + return nil, err +} + +func UpdateDeviceBySn(logger *log.Logger, m *deviceDao.Device) (err error) { + return deviceDao.UpdateDeviceBySn(logger, m) +} + +func CheckDevice(logger *log.Logger, event ironicAgentEvent.CallbackCommandMessage) error { + manageStatus := "putaway" //已上架 + reason := "" + if event.Status != "OK" { //ERROR + manageStatus = "putawayfail" + reason = event.Status + } + fmt.Println(manageStatus, reason) + device := &deviceDao.Device{ + Sn: event.Sn, + ManageStatus: manageStatus, + Reason: reason, + IsDel: 0, + } + if err := UpdateDeviceBySn(logger, device); err != nil { + logger.Warn("设备上架中变为已上架 sql error:", event.Sn, event.Action, err.Error()) + return err + } + return nil +} diff --git a/bmp-scheduler/logic/deviceTypeLogic/deviceTypeLogic.go b/bmp-scheduler/logic/deviceTypeLogic/deviceTypeLogic.go new file mode 100644 index 0000000..7cff85a --- /dev/null +++ b/bmp-scheduler/logic/deviceTypeLogic/deviceTypeLogic.go @@ -0,0 +1,19 @@ +package deviceTypeLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceTypeDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + log "git.jd.com/cps-golang/log" +) + +func GetDeviceTypeByID(logger *log.Logger, deviceTypeId string) (*deviceTypeDao.DeviceType, error) { + return deviceTypeDao.GetDeviceTypeById(logger, deviceTypeId) +} + +func GetDeviceTypeByInstanceID(logger *log.Logger, instanceId string) (*deviceTypeDao.DeviceType, error) { + instanceEntity, err := instanceLogic.GetByInstanceId(logger, instanceId) + if err != nil { + return nil, err + } + return deviceTypeDao.GetDeviceTypeById(logger, instanceEntity.DeviceTypeID) +} diff --git a/bmp-scheduler/logic/diskLogic/diskLogic.go b/bmp-scheduler/logic/diskLogic/diskLogic.go new file mode 100644 index 0000000..3688f2e --- /dev/null +++ b/bmp-scheduler/logic/diskLogic/diskLogic.go @@ -0,0 +1,15 @@ +package diskLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/diskDao" + log "git.jd.com/cps-golang/log" +) + +func QueryByManufacturerId(logger *log.Logger, manufacturer_id int64, disk_type string) ([]*diskDao.Disk, error) { + param := map[string]interface{}{ + "manufacturer_id": manufacturer_id, + "disk_type": disk_type, + "is_del": 0, + } + return diskDao.GetAllDisk(logger, param, nil, []string{"slot"}, []string{"asc"}) +} diff --git a/bmp-scheduler/logic/idcLogic/idcLogic.go b/bmp-scheduler/logic/idcLogic/idcLogic.go new file mode 100644 index 0000000..f0663b5 --- /dev/null +++ b/bmp-scheduler/logic/idcLogic/idcLogic.go @@ -0,0 +1,18 @@ +package idcLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/idcDao" + log "git.jd.com/cps-golang/log" +) + +func GetIdcID(logger *log.Logger) (*idcDao.Idc, error) { + + query := map[string]interface{}{ + "is_del": 0, + } + idc, err := idcDao.GetOneIdc(logger, query) + if err != nil { + return nil, err + } + return idc, nil +} diff --git a/bmp-scheduler/logic/imageLogic/imageLogic.go b/bmp-scheduler/logic/imageLogic/imageLogic.go new file mode 100644 index 0000000..926b8eb --- /dev/null +++ b/bmp-scheduler/logic/imageLogic/imageLogic.go @@ -0,0 +1,10 @@ +package imageLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/imageDao" + log "git.jd.com/cps-golang/log" +) + +func GetByImageId(logger *log.Logger, image_id string) (*imageDao.Image, error) { + return imageDao.GetImageByUuid(logger, image_id) +} diff --git a/bmp-scheduler/logic/instanceLogic/instanceLogic.go b/bmp-scheduler/logic/instanceLogic/instanceLogic.go new file mode 100644 index 0000000..d038ee0 --- /dev/null +++ b/bmp-scheduler/logic/instanceLogic/instanceLogic.go @@ -0,0 +1,211 @@ +package instanceLogic + +import ( + "fmt" + "time" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/imageLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/service/redis" + "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + "git.jd.com/cps-golang/ironic-common/ironic/enums/ImageType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/InstanceStatus" + log "git.jd.com/cps-golang/log" + "gopkg.in/goyy/goyy.v0/util/strings" +) + +func CallBack(logger *log.Logger, instance_id string) { + if instance_id == "" { + logger.Warn("instanceLogic CallBack empty instance_id!!!") + return + } + + //var callbackMsg interface{} + logid := logger.GetPoint("logid").(string) + region := "" //logger.GetPoint("region").(string) + az := "" //logger.GetPoint("az").(string) + fmt.Println(logid, region, az) + instance, err := GetByInstanceId(logger, instance_id) + if instance == nil { + logger.Warn("instanceLogic CallBack empty instanceId "+instance_id, err.Error()) + return + } + fmt.Println("实例信息为", instance.InstanceID, instance.InstanceName, instance.Status, "准备写入redis") + if err != nil { + logger.Warn("instanceLogic CallBack GetByInstanceId sql error:", instance_id, err.Error()) + } + image, err := imageLogic.GetByImageId(logger, instance.ImageID) + if err != nil { + logger.Warnf("instanceLogic CallBack GetByImageId sql error, instance_id:%s, image_id:%s, error:%s:", instance_id, instance.ImageID, err.Error()) + } + // device, err := deviceLogic.GetById(logger, instance.DeviceID) + // if err != nil { + // logger.Warn("instanceLogic CallBack GetByDeviceId sql error:", err.Error()) + // } + //下面的代码是根据将该实例状态当前的状态,得出指令执行结束以后的状态,并且将这个状态写入redis,等待crontab在接下来的时间内执行完毕(不要实时更新实例状态,有可能因为重启等操作,会有一定时间的延迟),并将实例状态更新 + switch strings.ToUpper(instance.Status) { + case "CREATING": + logger.Info("instancelogic callback CREATING......", instance_id) + //callbackMsg = commonCpsEvent.BuildCreateInstanceCallbackMessage(logid, region, az, instance_id, "instance.PublicIP") + if ImageType.IsWindows(image.ImageName) { + emulatorInstanceStatus(logger, instance_id, InstanceStatus.RUNNING, Constants.TIMEOUT_INSTANCE_RESTART_WINDOWS) + } else { + emulatorInstanceStatus(logger, instance_id, InstanceStatus.RUNNING, Constants.TIMEOUT_INSTANCE_RESTART) + } + logger.Info("instance create finished, emulator status to running, instance_id: ", instance_id) + break + case "STARTING": + logger.Info("instancelogic callback STARTING......", instance_id) + //callbackMsg = commonCpsEvent.BuildStartInstanceCallbackMessage(logid, region, az, instance_id) + emulatorInstanceStatus(logger, instance_id, InstanceStatus.RUNNING, Constants.TIMEOUT_INSTANCE_START) + logger.Info("instance start finished, emulator status to running, instance_id: ", instance_id) + case "STOPPING": + logger.Info("instancelogic callback STOPPING......", instance_id) + //callbackMsg = commonCpsEvent.BuildStopInstanceCallbackMessage(logid, region, az, instance_id) + emulatorInstanceStatus(logger, instance_id, InstanceStatus.STOPPED, Constants.TIMEOUT_INSTANCE_STOP) + logger.Info("instance stop finished, emulator status to stopped, instance_id: ", instance_id) + break + case "REINSTALLING": + logger.Info("instancelogic callback REINSTALLING......", instance_id) + //callbackMsg = commonCpsEvent.BuildReinstallInstanceCallbackMessage(logid, region, az, instance_id) + if ImageType.IsWindows(image.ImageName) { + emulatorInstanceStatus(logger, instance_id, InstanceStatus.RUNNING, Constants.TIMEOUT_INSTANCE_RESTART_WINDOWS) + } else { + emulatorInstanceStatus(logger, instance_id, InstanceStatus.RUNNING, Constants.TIMEOUT_INSTANCE_RESTART) + } + logger.Info("instance reinstall finished, emulator status to running, instance_id: ", instance_id) + break + case "RESTARTING": + logger.Info("instancelogic callback RESTARTING......", instance_id) + //callbackMsg = commonCpsEvent.BuildRestartInstanceCallbackMessage(logid, region, az, instance_id) + emulatorInstanceStatus(logger, instance_id, InstanceStatus.RUNNING, Constants.TIMEOUT_INSTANCE_RESTART) + logger.Info("instance restart finished, emulator status to running, instance_id: ", instance_id) + break + case "UPGRADING": + logger.Info("instancelogic callback UPGRADING......", instance_id) + //callbackMsg = commonCpsEvent.BuildUpgradeInstanceCallbackMessage(logid, region, az, instance_id) + instance_key := fmt.Sprintf("%s:%s", Constants.REDIS_KEY_STATUS, instance_id) + status, err := redis.GetObjectFromRedis(instance_key) + if err != nil { + logger.Warn("UPGRADING callback get from redis error, key:", instance_key, err.Error()) + return + } + instance.Status = status + instance.UpdatedTime = int(time.Now().Unix()) + if err := instanceDao.UpdateInstanceById(logger, instance); err != nil { + logger.Warn("UPGRADING callback save instance error:", err.Error()) + return + } + if err := redis.DelObjectFromRedis([]string{instance_key}); err != nil { + logger.Warn("UPGRADING callback del redis error:", instance_key, err.Error()) + return + } + logger.Info("instance upgrade finished, emulator status to:", status, "instance_id:", instance_id) + break + case "DESTROYING": + logger.Info("instancelogic callback DESTROYING......", instance_id) + //callbackMsg = commonCpsEvent.BuildDestroyInstanceCallbackMessage(logid, region, az, instance_id, "instance.PublicIP") + instance.Status = InstanceStatus.DESTROYED + instance.IsDel = 1 + instance.DeletedTime = int(time.Now().Unix()) + instance.UpdatedTime = int(time.Now().Unix()) + if err := instanceDao.UpdateInstanceById(logger, instance); err != nil { + logger.Warn("DESTROYING callback save instance error:", err.Error()) + return + } + device := &deviceDao.Device{ + InstanceID: instance_id, + ManageStatus: "putaway", //实例销毁以后,设备状态变为已上架(可售卖),同时将设备对应的用户信息置空 + } + if err := deviceDao.UpdateDeviceByInstanceId(logger, device); err != nil { + logger.Warnf("instance destroy finished, change status to destroyed err. instance_id:%s, err:%s", instance_id, err.Error()) + } + logger.Info("instance destroy finished, change status to destroyed. instance_id:", instance_id) + break + case "RESETTING_PASSWORD": + logger.Info("instancelogic callback RESETTING_PASSWORD......", instance_id) + //callbackMsg = commonCpsEvent.BuildInstanceResetPasswordCallbackMessage(logid, region, az, instance_id) + emulatorInstanceStatus(logger, instance_id, InstanceStatus.STOPPED, + Constants.TIMEOUT_INSTANCE_STOP) + logger.Info("instance reset password finished, emulator status to stopped. instance_id:", instance_id) + break + default: + break + } + //v, _ := json.Marshal(callbackMsg) + //if err := rabbitMq.SendToOpenAPI(callbackMsg); err != nil { + // logger.Warnf("instanceLogic callback send msg err, callbackMsg: %s, error: %s", string(v), err.Error()) + //} + // + //logger.Infof("rabbitMq.SendToOpenAPI success, callbackMsg: %s", string(v)) + logger.Info("command exec all finished,crontab redis will update the instance status in the several minutes") + +} + +func GetByInstanceId(logger *log.Logger, instance_id string) (*instanceDao.Instance, error) { + return instanceDao.GetInstanceByUuid(logger, instance_id) +} + +func emulatorInstanceStatus(logger *log.Logger, instance_id string, status string, timeoutTime int) { + check_key := fmt.Sprintf("%s:%s", Constants.REDIS_KEY_CHECK, instance_id) + instance_key := fmt.Sprintf("%s:%s", Constants.REDIS_KEY_INSTANCE, instance_id) + if err := redis.SetObjectToRedis(check_key, status); err != nil { + logger.Warn("emulatorInstanceStatus set error:", check_key, status) + } + if _, err := redis.SetNxObjectToRedis(instance_key, status, timeoutTime); err != nil { + logger.Warn("emulatorInstanceStatus set error:", instance_key, status) + } + +} + +func resourceRecovery(logger *log.Logger, instance_entity *instanceDao.Instance) error { + // 设备可售卖 + device_entity, err := deviceDao.GetDeviceById(logger, instance_entity.DeviceID) + if err != nil { + logger.Warn("resourceRecovery GetDeviceById sql error:", err.Error()) + return err + } + device_entity.ManageStatus = "putaway" + device_entity.UpdatedTime = int(time.Now().Unix()) + if err := deviceDao.UpdateDeviceById(logger, device_entity); err != nil { + logger.Warn("resourceRecovery UpdateDeviceById sql error:", err.Error()) + return err + } + //if instance_entity.NetworkType == NetworkType.BASIC { + // // 回收公网IP + // if instance_entity.EnableInternet == 0 { + // ip_entity, err := wanIpDao.GetByAzAndIP(logger, device_entity.Az, instance_entity.PublicIP) + // if err != nil { + // logger.Warn("resourceRecovery GetByAzAndIP sql error:", err.Error()) + // } + // if ip_entity != nil { + // ip_entity.Status = 0 + // ip_entity.UpdateTime = time.Now() + // if err := wanIpDao.UpdateWanIpById(logger, ip_entity); err != nil { + // logger.Warn("resourceRecovery UpdateWanIpById sql error:", err.Error()) + // } + // } + // } + // // 删除子网 + // count, err := instanceDao.CountByTenantAndSubnetId(logger, instance_entity.Tenant, instance_entity.SubnetID) + // if err != nil { + // logger.Warn("resourceRecovery CountByTenantAndSubnetId sql error:", err.Error()) + // } + // if count == 1 { + // subnet_entity, err := subnetDao.GetBySubnetIdAndTenant(logger, instance_entity.SubnetID, instance_entity.Tenant) + // if err != nil { + // logger.Warn("resourceRecovery GetBySubnetIdAndTenant sql error:", err.Error()) + // } + // if subnet_entity != nil { + // subnet_entity.IsDel = 1 + // subnet_entity.UpdateTime = time.Now() + // if err := subnetDao.UpdateSubnetById(logger, subnet_entity); err != nil { + // logger.Warn("resourceRecovery UpdateSubnetById sql error:", err.Error()) + // } + // } + // } + //} + return nil + +} diff --git a/bmp-scheduler/logic/interfaceLogic/interfaceLogic.go b/bmp-scheduler/logic/interfaceLogic/interfaceLogic.go new file mode 100644 index 0000000..1be69a5 --- /dev/null +++ b/bmp-scheduler/logic/interfaceLogic/interfaceLogic.go @@ -0,0 +1,10 @@ +package interfaceLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/interfaceDao" + log "git.jd.com/cps-golang/log" +) + +func GetBySn(logger *log.Logger, sn string) ([]*interfaceDao.Interface, error) { + return interfaceDao.GetBySn(logger, sn) +} diff --git a/bmp-scheduler/logic/jdBondInterfaceLogic/jdBondInterfaceLogic.go b/bmp-scheduler/logic/jdBondInterfaceLogic/jdBondInterfaceLogic.go new file mode 100644 index 0000000..b30f1fe --- /dev/null +++ b/bmp-scheduler/logic/jdBondInterfaceLogic/jdBondInterfaceLogic.go @@ -0,0 +1,14 @@ +package jdBondInterfaceLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/jdBondInterfaceDao" + log "git.jd.com/cps-golang/log" +) + +func GetBySn(logger *log.Logger, sn string) (*jdBondInterfaceDao.JdBondInterface, error) { + param := map[string]interface{}{ + "is_del": 0, + "sn": sn, + } + return jdBondInterfaceDao.GetOneInterface(logger, param) +} diff --git a/bmp-scheduler/logic/keypairLogic/keypairLogic.go b/bmp-scheduler/logic/keypairLogic/keypairLogic.go new file mode 100644 index 0000000..01252a8 --- /dev/null +++ b/bmp-scheduler/logic/keypairLogic/keypairLogic.go @@ -0,0 +1,15 @@ +package keypairLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/keypairDao" + log "git.jd.com/cps-golang/log" +) + +func GetByUuidAndTenant(logger *log.Logger, keypair_id, tenant string) (*keypairDao.Keypair, error) { + param := map[string]interface{}{ + "is_del": 0, + "uuid": keypair_id, + "tenant": tenant, + } + return keypairDao.GetOneKeypair(logger, param) +} diff --git a/bmp-scheduler/logic/mailLogic/MailUtil.go b/bmp-scheduler/logic/mailLogic/MailUtil.go new file mode 100644 index 0000000..f723da6 --- /dev/null +++ b/bmp-scheduler/logic/mailLogic/MailUtil.go @@ -0,0 +1,118 @@ +package mailLogic + +import ( + "bytes" + "crypto/tls" + "errors" + "fmt" + "html/template" + "strconv" + "strings" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/mailDao" + log "git.jd.com/cps-golang/log" + + "github.com/go-gomail/gomail" +) + +func DialMail(logger *log.Logger, smtpHost string, smtpPort int, from, password, tos string, subject, msg string) error { + m := gomail.NewMessage() + to := strings.Split(tos, ",") + s := "" + m.SetHeader("From", from) + m.SetHeader("To", to...) + m.SetHeader("Subject", s+":"+subject) + m.SetBody("text/html", msg) + + username := strings.Split(from, "@")[0] + + d := gomail.NewPlainDialer( + smtpHost, + smtpPort, + username, + password) + + if d == nil { + return errors.New("Initialize Dialer Error") + } + + d.TLSConfig = &tls.Config{ServerName: d.Host, InsecureSkipVerify: true} + + // Send the email. + if err := d.DialAndSend(m); err != nil { + logger.Warnf("SendMail msg=%s : %s\n", msg, err.Error()) + return err + } + return nil +} + +// SendMail use smtp to send mail +func SendMail(logger *log.Logger, subject, msg string) error { + + mailEntity, err := mailDao.GetMailMessage(logger) + if err != nil { + logger.Warnf("SendMail.GetMail error:%s", err.Error()) + return err + } + tos := mailEntity.To + from := mailEntity.AdminAddr + smtpHost := mailEntity.ServerAddr + smtpPort, err := strconv.Atoi(mailEntity.ServerPort) + if err != nil { + logger.Warnf("SendMail.ServerPort invalid, port:%s", mailEntity.ServerPort) + return err + } + username := strings.Split(from, "@")[0] + password := mailEntity.AdminPass + + m := gomail.NewMessage() + to := strings.Split(tos, ",") + s := BaseSubjest + m.SetHeader("From", from) + m.SetHeader("To", to...) + m.SetHeader("Subject", s+":"+subject) + m.SetBody("text/html", msg) + + d := gomail.NewPlainDialer( + smtpHost, + smtpPort, + username, + password) + + if d == nil { + return errors.New("Initialize Dialer Error") + } + + d.TLSConfig = &tls.Config{ServerName: d.Host, InsecureSkipVerify: true} + + // Send the email. + if err := d.DialAndSend(m); err != nil { + fmt.Printf("SendMail msg=%s : %s\n", msg, err.Error()) + return err + } + return nil +} + +//SendMailByTpl send template mail +func SendMailByTpl(logger *log.Logger, tplName, subject string, obj interface{}) error { + tpl, errParse := template.New("Mail").Parse(tplName) + if errParse != nil { + fmt.Printf("Parse Template Error:%s\n", errParse.Error()) + return errParse + } + + byteW := new(bytes.Buffer) + err := tpl.Execute(byteW, obj) + if err != nil { + fmt.Printf("Execute Template Error:%s\n", err.Error()) + return err + } + + errMail := SendMail(logger, subject, byteW.String()) + if errMail != nil { + fmt.Printf("Send Mail Error:%s\n", errMail.Error()) + return errMail + } + + return nil +} diff --git a/bmp-scheduler/logic/mailLogic/OperationAfterInstance.go b/bmp-scheduler/logic/mailLogic/OperationAfterInstance.go new file mode 100644 index 0000000..c31b709 --- /dev/null +++ b/bmp-scheduler/logic/mailLogic/OperationAfterInstance.go @@ -0,0 +1,162 @@ +package mailLogic + +const OperationAfterInstanceTemplate string = ` + + + + + + + 操作消息(实例化后) + + + +
    +
    + BMP裸金属管理平台 +
    +
    +

    尊敬的用户,您好!

    +

    + 您帐号中的服务器资源(SN号:{{.SN}}) 【{{.MessageSubType}}】操作失败,请重新操作或联系管理员处理。详情如下: +

    + + + + + + + + + + + + + + + + + + + +
    实例名称实例ID操作内容操作人操作时间
    {{.InstanceName}}{{.InstanceID}}{{.MessageSubType}}{{.UserName}}{{.FinishTime}}
    +
    + +
    + + + +` + +type MailMessage struct { + MessageID string + SN string + MessageType string + MessageSubType string + ResourceType string + FinishTime string + Detail string + UserID string + UserName string + InstanceID string + InstanceName string +} diff --git a/bmp-scheduler/logic/mailLogic/OperationBeforeInstance.go b/bmp-scheduler/logic/mailLogic/OperationBeforeInstance.go new file mode 100644 index 0000000..3110804 --- /dev/null +++ b/bmp-scheduler/logic/mailLogic/OperationBeforeInstance.go @@ -0,0 +1,142 @@ +package mailLogic + +const OperationBeforeInstanceTemplate string = ` + + + + + + 操作消息(实例化前) + + + +
    +
    + BMP裸金属管理平台 +
    +
    +

    尊敬的用户,您好!

    +

    + 您帐号中的服务器资源(SN号:{{.SN}}) 【{{.MessageSubType}}】操作失败,请重新操作或联系管理员处理。详情如下: +

    + + + + + + + + + + + + + + + +
    操作内容操作人故障报警时间
    {{.MessageSubType}}{{.UserName}}{{.FinishTime}}
    +
    + +
    + + +` diff --git a/bmp-scheduler/logic/mailLogic/subject.go b/bmp-scheduler/logic/mailLogic/subject.go new file mode 100644 index 0000000..733b1b8 --- /dev/null +++ b/bmp-scheduler/logic/mailLogic/subject.go @@ -0,0 +1,5 @@ +package mailLogic + +const BaseSubjest string = "BMP裸金属管理平台" +const MailDialTestSubjest string = "测试邮件" +const MailDialTestContent string = "这是一封测试邮件" diff --git a/bmp-scheduler/logic/messageLogic/messageLogic.go b/bmp-scheduler/logic/messageLogic/messageLogic.go new file mode 100644 index 0000000..73fd504 --- /dev/null +++ b/bmp-scheduler/logic/messageLogic/messageLogic.go @@ -0,0 +1,69 @@ +package messagelogic + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/messageDao" + messageType "git.jd.com/cps-golang/ironic-common/ironic/enums/MessageType" + log "git.jd.com/cps-golang/log" +) + +var Types2ShowZh = map[string]string{ + //操作消息 + messageType.MessageTypeOperation: "操作消息", + //系统消息 + messageType.MessageTypeSystem: "系统消息", + //监控消息 + messageType.MessageTypeOobMonitor: "故障消息", + //带内告警消息 + messageType.MessageTypeInBondAlert: "告警消息", + //操作消息类型 + messageType.MessageSubTypeCollectHardwareInfo: "采集", + messageType.MessageSubTypeCreateDevices: "上传设备", + messageType.MessageSubTypeCreateInstances: "创建实例", + messageType.MessageSubTypeCutDeviceStock: "削减库存", + messageType.MessageSubTypeDeleteInstance: "删除实例", + messageType.MessageSubTypeInstanceResetPassword: "重置密码", + messageType.MessageSubTypePutawayDevice: "设备上架", + messageType.MessageSubTypeReinstallInstance: "重装系统", + messageType.MessageSubTypeRestartInstances: "重启实例", + messageType.MessageSubTypeStartInstances: "开机", + messageType.MessageSubTypeStopInstances: "关机", + //系统消息类型 + messageType.MessageSubTypeLicenseNearTimeout: "许可证到期", + //监控消息类型 + messageType.MessageSubTypePowerFault: "电力故障", + messageType.MessageSubTypeTemperatureFault: "温控故障", + messageType.MessageSubTypeCPUFault: "CPU故障", + messageType.MessageSubTypeMemFault: "内存故障", + messageType.MessageSubTypeDiskFault: "硬盘故障", + messageType.MessageSubTypeOtherFault: "其他故障", + + //带内告警 + messageType.MessageSubTypeCPUUsage: "CPU使用率", + messageType.MessageSubTypeMemoryUsage: "内存使用率", + messageType.MessageSubTypeMemoryUsed: "内存使用量", + messageType.MessageSubTypeDiskUsed: "磁盘使用量", + messageType.MessageSubTypeDiskUsage: "磁盘使用率", + messageType.MessageSubTypeDiskReadTraffic: "磁盘读流量", + messageType.MessageSubTypeDiskWriteTraffic: "磁盘写流量", + messageType.MessageSubTypeDiskReadIOPS: "磁盘读IOPS", + messageType.MessageSubTypeDiskWriteIOPS: "磁盘写IOPS", + messageType.MessageSubTypeNetworkIngressTraffic: "网卡进流量", + messageType.MessageSubTypeNetworkEgressTraffic: "网卡出流量", + messageType.MessageSubTypeNetworkIngressPackets: "网络进包数量", + messageType.MessageSubTypeNetworkEgressPackets: "网络出包数量", + messageType.MessageSubTypeLoadAverage1min: "平均负载均衡1min", + messageType.MessageSubTypeLoadAverage5min: "平均负载均衡5min", + messageType.MessageSubTypeLoadAverage15min: "平均负载均衡15min", + messageType.MessageSubTypeTotalTCPConnections: "TCP总连接数", + messageType.MessageSubTypeEstablishedTCPConnections: "TCP正常接数", + messageType.MessageSubTypeTotalProcessCount: "总进程数", +} + +func SendWebNotice(logger *log.Logger, msg messageDao.WebMessage) error { + if _, err := messageDao.AddWebMessage(logger, &msg); err != nil { + logger.Warnf("SendWebNotice error, msg:%v, error:%s", msg, err.Error()) + return err + } + logger.Infof("SendWebNotice success, msg:%v", msg) + return nil +} diff --git a/bmp-scheduler/logic/osLogic/osLogic.go b/bmp-scheduler/logic/osLogic/osLogic.go new file mode 100644 index 0000000..4f74865 --- /dev/null +++ b/bmp-scheduler/logic/osLogic/osLogic.go @@ -0,0 +1,29 @@ +package osLogic + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/osDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/imageLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + log "git.jd.com/cps-golang/log" +) + +func GetByOsId(logger *log.Logger, os_id string) (*osDao.Os, error) { + return osDao.GetOsByUuid(logger, os_id) +} + +func GetOsByInstanceId(logger *log.Logger, instanceId string) (*osDao.Os, error) { + instanceEntity, err := instanceLogic.GetByInstanceId(logger, instanceId) + if err != nil { + return nil, err + } + imageEntity, err := imageLogic.GetByImageId(logger, instanceEntity.ImageID) + if err != nil { + logger.Warn("CreateInstancesActor_GetByImageId sql error:", err.Error()) + } + osEntity, err := GetByOsId(logger, imageEntity.OsID) + if err != nil { + logger.Warn("CreateInstancesActor GetByOsId sql error:", imageEntity.OsID, err.Error()) + } + return osEntity, err + +} diff --git a/bmp-scheduler/logic/partitionLogic/partitionLogic.go b/bmp-scheduler/logic/partitionLogic/partitionLogic.go new file mode 100644 index 0000000..f60df9a --- /dev/null +++ b/bmp-scheduler/logic/partitionLogic/partitionLogic.go @@ -0,0 +1,15 @@ +package partitionLogic + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/rDeviceTypeImagePartitionDao" + log "git.jd.com/cps-golang/log" +) + +func GetByDeviceTypeAndImageId(logger *log.Logger, device_type_id, image_id string) ([]*dao.RDeviceTypeImagePartition, error) { + param := map[string]interface{}{ + "is_del": 0, + "device_type_id": device_type_id, // []string{device_type, "common"}, + "image_id": image_id, + } + return dao.GetAllRDeviceTypeImagePartition(logger, param) +} diff --git a/bmp-scheduler/logic/raidLogic/raidLogic.go b/bmp-scheduler/logic/raidLogic/raidLogic.go new file mode 100644 index 0000000..92818b1 --- /dev/null +++ b/bmp-scheduler/logic/raidLogic/raidLogic.go @@ -0,0 +1,11 @@ +package raidLogic + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/raidDao" + log "git.jd.com/cps-golang/log" +) + +func GetByRaidId(logger *log.Logger, raid_id string) (*dao.Raid, error) { + + return dao.GetRaidByUuid(logger, raid_id) +} diff --git a/bmp-scheduler/main.go b/bmp-scheduler/main.go new file mode 100644 index 0000000..3097a7b --- /dev/null +++ b/bmp-scheduler/main.go @@ -0,0 +1,173 @@ +package main + +import ( + "flag" + "fmt" + "os" + "strconv" + "time" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + processor "coding.jd.com/aidc-bmp/bmp-scheduler/processor" + scheduler "coding.jd.com/aidc-bmp/bmp-scheduler/scheduler" + email "coding.jd.com/aidc-bmp/bmp-scheduler/service/email" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + redis "coding.jd.com/aidc-bmp/bmp-scheduler/service/redis" + beego "github.com/beego/beego/v2/server/web" + _ "github.com/go-sql-driver/mysql" +) + +var ( + VERSION = "should be compiled with make." + BUILD_TIME = "should be compiled with make." +) + +const ( + defaultConfigFile = "conf/bmp-scheduler.ini" +) + +var configFile = flag.String("c", defaultConfigFile, "specify config file") +var versionFlag = flag.Bool("v", false, "show version") + +func main() { + + flag.Parse() + + if *versionFlag { + fmt.Println("commit_id:", VERSION, "build_time:", BUILD_TIME) + os.Exit(0) + } + + fmt.Println(time.Now(), "[bmp-scheduler] start...") + defer fmt.Println(time.Now(), "[bmp-scheduler] end...") + + initConfig() + scheduler.Run() +} + +func initConfig() { + // initial Config From file + if err := beego.LoadAppConfig("ini", *configFile); err != nil { + panic(fmt.Sprintf("LoadAppConfig Error:%s", err.Error())) + } + + if err := initRedis(); err != nil { + fmt.Println(time.Now(), "initRedis Error:", err.Error()) + } + + initGormDB() + + if err := initRabbitMqTemplate(); err != nil { + panic(fmt.Sprintf("initRabbitMqTemplate Error:%s", err.Error())) + } + + // if err := initSdnApiConfig(); err != nil { + // panic(fmt.Sprintf("initSdnApiConfig Error:%s", err.Error())) + // } + + if err := initIloConfig(); err != nil { + panic(fmt.Sprintf("initIloConfig Error:%s", err.Error())) + } + + if err := initEmailConfig(); err != nil { + panic(fmt.Sprintf("initEmailConfig Error:%s", err.Error())) + } + +} + +func initRedis() error { + // initial redis + var namespace, host, port, password string + var dbNum int + namespace, _ = beego.AppConfig.String("bmp_redis_namespace") + host, _ = beego.AppConfig.String("bmp_redis_host") + port, _ = beego.AppConfig.String("bmp_redis_port") + password, _ = beego.AppConfig.String("bmp_redis_password") + dbNum = beego.AppConfig.DefaultInt("bmp_redis_db", 0) + addr := fmt.Sprintf("%s:%s", host, port) + return redis.InitRedis(namespace, addr, password, dbNum) +} + +func initGormDB() { + // initial mysql + host, _ := beego.AppConfig.String("bmp_db_host") + port, _ := beego.AppConfig.String("bmp_db_port") + user, _ := beego.AppConfig.String("bmp_db_user") + password, _ := beego.AppConfig.String("bmp_db_password") + name, _ := beego.AppConfig.String("bmp_db_name") + //root:admin@tcp(10.226.192.113:3306)/aidc_bmp?charset=utf8&parseTime=true&charset=utf8&loc=Asia%2FShanghai + sqlconn := user + ":" + password + "@tcp(" + host + ":" + port + ")/" + name + "?charset=utf8&parseTime=true&loc=Local" + dao.InitGormDb(sqlconn) +} + +func initRabbitMqTemplate() error { + host, _ := beego.AppConfig.String("bmp_mq_host") + port, _ := beego.AppConfig.String("bmp_mq_port") + user, _ := beego.AppConfig.String("bmp_mq_user") + password, _ := beego.AppConfig.String("bmp_mq_password") + vhost, _ := beego.AppConfig.String("bmp_mq_vhost") + mqUrl := "amqp://" + user + ":" + password + "@" + host + ":" + port + "/" + vhost + // exchange, _ := beego.AppConfig.String("rabbit.mq.ironic.exchange") + // receive_routing_key, _ := beego.AppConfig.String("rabbit.mq.ironic.receive_routing_key") + + host1, _ := beego.AppConfig.String("bmp_mq_host") + port1, _ := beego.AppConfig.String("bmp_mq_port") + user1, _ := beego.AppConfig.String("bmp_mq_user") + password1, _ := beego.AppConfig.String("bmp_mq_password") + vhost1, _ := beego.AppConfig.String("bmp_mq_vhost") + mqUrl1 := "amqp://" + user1 + ":" + password1 + "@" + host1 + ":" + port1 + "/" + vhost1 + return rabbitMq.InitMqTemplate(mqUrl, mqUrl1) +} + +// func initSdnApiConfig() error { +// cn_east_1_ip, _ := beego.AppConfig.String("sdn.configs.cn-east-1.ip") +// cn_east_jdr1_ip, _ := beego.AppConfig.String("sdn.configs.cn-east-jdr1.ip") +// cn_north_1_ip, _ := beego.AppConfig.String("sdn.configs.cn-north-1.ip") +// cn_east_tz1_ip, _ := beego.AppConfig.String("sdn.configs.cn-east-tz1.ip") +// cn_east_jn1_ip, _ := beego.AppConfig.String("sdn.configs.cn-east-jn1.ip") +// cn_east_10_ip, _ := beego.AppConfig.String("sdn.configs.cn-east-10.ip") +// cn_east_11_ip, _ := beego.AppConfig.String("sdn.configs.cn-east-11.ip") + +// cn_east_1_nameservers, _ := beego.AppConfig.Strings("sdn.configs.cn-east-1.nameservers") +// cn_east_jdr1_nameservers, _ := beego.AppConfig.Strings("sdn.configs.cn-east-jdr1.nameservers") +// cn_north_1_nameservers, _ := beego.AppConfig.Strings("sdn.configs.cn-north-1.nameservers") +// cn_east_tz1_nameservers, _ := beego.AppConfig.Strings("sdn.configs.cn-east-tz1.nameservers") +// cn_east_jn1_nameservers, _ := beego.AppConfig.Strings("sdn.configs.cn-east-jn1.nameservers") +// cn_east_10_nameservers, _ := beego.AppConfig.Strings("sdn.configs.cn-east-10.nameservers") +// cn_east_11_nameservers, _ := beego.AppConfig.Strings("sdn.configs.cn-east-11.nameservers") + +// c := map[string]sdnApi.Cfg{ +// "cn-east-1": sdnApi.Cfg{cn_east_1_ip, cn_east_1_nameservers}, +// "cn-east-jdr1": sdnApi.Cfg{cn_east_jdr1_ip, cn_east_jdr1_nameservers}, +// "cn-north-1": sdnApi.Cfg{cn_north_1_ip, cn_north_1_nameservers}, +// "cn-east-tz1": sdnApi.Cfg{cn_east_tz1_ip, cn_east_tz1_nameservers}, +// "cn-east-jn1": sdnApi.Cfg{cn_east_jn1_ip, cn_east_jn1_nameservers}, +// "cn-east-10": sdnApi.Cfg{cn_east_10_ip, cn_east_10_nameservers}, +// "cn-east-11": sdnApi.Cfg{cn_east_11_ip, cn_east_11_nameservers}, +// } +// return sdnApi.InitSdnApiConfig(c) + +// } + +func initIloConfig() error { + processor.IloUsername, _ = beego.AppConfig.String("ilo.username") + processor.IloPassword, _ = beego.AppConfig.String("ilo.password") + return nil +} + +func initEmailConfig() error { + host, _ := beego.AppConfig.String("mail.server.host") + port, _ := beego.AppConfig.String("mail.server.port") + port_n, _ := strconv.Atoi(port) + username, _ := beego.AppConfig.String("mail.server.username") + password, _ := beego.AppConfig.String("mail.server.password") + from, _ := beego.AppConfig.String("mail.server.email") + c := email.EmailConfig{ + Host: host, + Port: port_n, + Username: username, + Password: password, + From: from, + } + return email.InitEmailConfig(c) +} diff --git a/bmp-scheduler/processor/AddArpStaticProcessor.go b/bmp-scheduler/processor/AddArpStaticProcessor.go new file mode 100644 index 0000000..7b62b86 --- /dev/null +++ b/bmp-scheduler/processor/AddArpStaticProcessor.go @@ -0,0 +1,61 @@ +package processor + +import ( + "fmt" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/interfaceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/interfaceLogic" + "git.jd.com/cps-golang/ironic-common/ironic/enums/InterfaceType" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type AddArpStaticProcessor struct { + BaseProcessor +} + +func NewAddArpStaticProcessor() AddArpStaticProcessor { + b := AddArpStaticProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b AddArpStaticProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b AddArpStaticProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b AddArpStaticProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil || instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process AddArpStatic error, instance %s not found", command.InstanceID)}) + } + //if !util.Int82Bool(instance.EnableInternet) { + // logger.Warn(command.InstanceID, "instance not enable internet, skip process AddArpStatic") + // return + //} + entities, err := interfaceLogic.GetBySn(logger, command.Sn) + if err != nil || len(entities) == 0 { + panic(ProcessAbortException{Msg: fmt.Sprintf("process AddArpStatic error, instance %s interface not found", command.InstanceID)}) + } + interface_map := map[string]*interfaceDao.Interface{} + for _, entity := range entities { + interface_map[entity.InterfaceType] = entity + } + wan := interface_map[InterfaceType.WAN] + if wan == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process AddArpStatic error, instance %s wan not found", command.InstanceID)}) + } + //TODO + // joypaw_api.createArpStatic() +} + +func (b AddArpStaticProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/AddDHCPConfigHostProcessor.go b/bmp-scheduler/processor/AddDHCPConfigHostProcessor.go new file mode 100644 index 0000000..353402a --- /dev/null +++ b/bmp-scheduler/processor/AddDHCPConfigHostProcessor.go @@ -0,0 +1,74 @@ +package processor + +import ( + "fmt" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + deviceDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + driverTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type AddDHCPConfigHostProcessor struct { + BaseProcessor +} + +func NewAddDHCPConfigHostProcessor() AddDHCPConfigHostProcessor { + b := AddDHCPConfigHostProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} +func (b AddDHCPConfigHostProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b AddDHCPConfigHostProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b AddDHCPConfigHostProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + var entity *deviceDao.Device + var err error + entity, err = deviceDao.GetBySn(logger, command.Sn) + + if err != nil || entity == nil { + + logger.Warn("AddDHCPConfigHostProcessor GetBySn sql error:", err.Error()) + panic(ProcessAbortException{Msg: fmt.Sprintf("process AddDHCPConfigHostProcessor error, sn %s device not found", command.Sn)}) + } + //entities, err := interfaceLogic.GetBySn(logger, command.Sn) + //if err != nil { + // logger.Warn("AddDHCPConfigHostProcessor GetBySn sql error:", command.Sn, err.Error()) + //} + //if len(entities) == 0 { + // panic(ProcessAbortException{Msg: fmt.Sprintf("process AddDHCPConfigHost error, sn %s interface not found", command.Sn)}) + //} + //jd_bond_interface, err := jdBondInterfaceLogic.GetBySn(logger, command.Sn) + //if err != nil { + // logger.Warn("AddDHCPConfigHostProcessor GetBySn sql error:", command.Sn, err.Error()) + //} + //if jd_bond_interface == nil || jd_bond_interface.PrivateIP == "" { + // panic(ProcessAbortException{Msg: fmt.Sprintf("process AddDHCPConfigHost error, sn %s jd_bond_interface not found", command.Sn)}) + //} + + config_host := driverTypes.AddDHCPConfigHost{ + Sn: command.Sn, + Ip: entity.PrivateIPv4, + Mac: entity.Mac1, + } + if err := rabbitMq.SendToAgent4Topic(entity.IDcID, config_host); err != nil { + logger.Warn("AddDHCPConfigHostProcessor SendToAgent error:", entity.IDcID, err.Error()) + return + } + + logger.Infof("AddDHCPConfigHostProcessor_SendToAgent_Msg: %s, routingkey:%s", util.ObjToJson(config_host), entity.IDcID) +} + +func (b AddDHCPConfigHostProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //不管agent,driver是否返回成功,都默认成功,执行下一条指令 + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/BaseProcessor.go b/bmp-scheduler/processor/BaseProcessor.go new file mode 100644 index 0000000..7588f71 --- /dev/null +++ b/bmp-scheduler/processor/BaseProcessor.go @@ -0,0 +1,409 @@ +package processor + +import ( + "encoding/json" + "fmt" + "runtime" + "strings" + "time" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + deviceDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/messageDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/userDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/auditLogLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/mailLogic" + messagelogic "coding.jd.com/aidc-bmp/bmp-scheduler/logic/messageLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/service/redis" + "coding.jd.com/aidc-bmp/bmp-scheduler/types" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + constants "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandStatus" + "git.jd.com/cps-golang/ironic-common/ironic/enums/InstanceStatus" + messageType "git.jd.com/cps-golang/ironic-common/ironic/enums/MessageType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/TimeoutPolicy" + ironicCommon "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +const ( + OK = "OK" + ERROR = "ERROR" + COMMAND_MAX_EXECUTE_COUNT = 3 +) + +type BaseProcessor struct { + doProcess func(*log.Logger, *commandDao.Command) + afterProcess func(*log.Logger, *commandDao.Command) +} + +type Processer interface { + Process(*log.Logger, *commandDao.Command) + doProcess(*log.Logger, *commandDao.Command) + afterProcess(*log.Logger, *commandDao.Command) + Callback(*log.Logger, *commandDao.Command, ironicCommon.CallbackCommandMessage) +} + +type Exception struct { + Msg string +} + +type ProcessAbortException struct { + Exception + Msg string +} + +var IloUsername string +var IloPassword string +var ProcessorMap map[string]Processer + +func init() { + ProcessorMap = map[string]Processer{} + ProcessorMap["AddArpStatic"] = NewAddArpStaticProcessor() + ProcessorMap["DHCPConfigAddSubnet"] = NewDHCPConfigAddSubnetProcessor() + ProcessorMap["CheckInitConfig"] = NewCheckInitConfigProcessor() + ProcessorMap["DHCPConfigAddHost"] = NewAddDHCPConfigHostProcessor() + ProcessorMap["DHCPConfigDelHost"] = NewDelDHCPConfigHostProcessor() + ProcessorMap["BindingIPv6"] = NewBindingIPv6Processor() + ProcessorMap["BindingVSI"] = NewBindingVSIProcessor() + ProcessorMap["CleanArpStatic"] = NewCleanArpStaticProcessor() + ProcessorMap["CleanBandwidth"] = NewCleanBandwidthProcessor() + ProcessorMap["CleanBlockDevice"] = NewCleanBlockDeviceProcessor() + ProcessorMap["CleanRaid"] = NewCleanRaidProcessor() + ProcessorMap["CollectHardwareInfo"] = NewCollectHardwareInfoProcessor() + ProcessorMap["CollectDiskLocations"] = NewCollectDiskLocationsProcessor() + ProcessorMap["CreateVNI"] = NewCreateVNIProcessor() + ProcessorMap["CreateVRFBalance"] = NewCreateVRFBalanceProcessor() + ProcessorMap["CreateVRF"] = NewCreateVRFProcessor() + ProcessorMap["CreateVSIInterface"] = NewCreateVSIInterfaceProcessor() + ProcessorMap["CreateVSI"] = NewCreateVSIProcessor() + ProcessorMap["DelDHCPConfigHost"] = NewDelDHCPConfigHostProcessor() + ProcessorMap["DHCPRestart"] = NewDHCPRestartProcessor() + ProcessorMap["InitRootDevice"] = NewInitRootDeviceProcessor() + ProcessorMap["InitRootDeviceV2"] = NewInitRootDeviceProcessorV2() + ProcessorMap["MakePartitions"] = NewMakePartitionsProcessor() + ProcessorMap["MakeRaid"] = NewMakeRaidProcessor() + ProcessorMap["Ping"] = NewPingProcessor() + ProcessorMap["PowerCycle"] = NewPowerCycleProcessor() + ProcessorMap["PowerOff"] = NewPowerOffProcessor() + ProcessorMap["PowerOn"] = NewPowerOnProcessor() + ProcessorMap["PowerReset"] = NewPowerResetProcessor() + ProcessorMap["Qcow2MakePartitions"] = NewQcow2MakePartitionsProcessor() + ProcessorMap["SaveConfigToFtpServer"] = NewSaveConfigToFtpServerProcessor() + ProcessorMap["SaveSwitchConfig"] = NewSaveSwitchConfigProcessor() + ProcessorMap["SDNAddAliasIP"] = NewSDNAddAliasIPProcessor() + ProcessorMap["SDNClean"] = NewSDNCleanProcessor() + ProcessorMap["SDNDeleteAliasIP"] = NewSDNDeleteAliasIPProcessor() + ProcessorMap["SDNEipBinding"] = NewSDNEipBindingProcessor() + ProcessorMap["SDNEipUnBinding"] = NewSDNEipUnBindingProcessor() + ProcessorMap["SDNRegister"] = NewSDNRegisterProcessor() + ProcessorMap["SDNSetNetwork"] = NewSDNSetNetworkProcessor() + ProcessorMap["SDNSubnetBinding"] = NewSDNSubnetBindingProcessor() + ProcessorMap["SDNSubnetUnBinding"] = NewSDNSubnetUnBindingProcessor() + ProcessorMap["SetBandwidth"] = NewSetBandwidthProcessor() + ProcessorMap["SetBond"] = NewSetBondProcessor() + ProcessorMap["SetDISKBoot"] = NewSetDISKBootProcessor() + ProcessorMap["SetHostname"] = NewSetHostnameProcessor() + ProcessorMap["SetKeypairs"] = NewSetKeypairsProcessor() + // ProcessorMap["SetNetwork"] = NewSetNetworkProcessor()//废弃 + ProcessorMap["SetPassword"] = NewSetPasswordProcessor() + ProcessorMap["SetPXEBoot"] = NewSetPXEBootProcessor() + ProcessorMap["SetRetailBond"] = NewSetRetailBondProcessor() + ProcessorMap["SetUserCmd"] = NewSetUserCmdProcessor() + ProcessorMap["UnBindingVSI"] = NewUnBindingVSIProcessor() + ProcessorMap["UploadSystemLog"] = NewUploadSystemLogProcessor() + ProcessorMap["WriteImage"] = NewWriteImageProcessor() + ProcessorMap["WriteImageTar"] = NewWriteImageTarProcessor() + + //以下用于cloudinit方式 + ProcessorMap["InitNode"] = NewInitNodeProcessor() + ProcessorMap["FormatPartitions"] = NewFormatPartitionsProcessor() + ProcessorMap["MountPartitions"] = NewMountPartitionsProcessor() + ProcessorMap["SetCloudinitConf"] = NewSetCloudinitConfProcessor() + // ProcessorMap["SetNocloudUserData"] = NewSetNocloudUserDataProcessor() + // ProcessorMap["SetNocloudMetaData"] = NewSetNocloudMetaDataProcessor() + + ProcessorMap["SetUserData"] = NewSetNocloudUserDataProcessor() + ProcessorMap["SetMetaData"] = NewSetNocloudMetaDataProcessor() + + ProcessorMap["SetNetwork"] = NewSetNocloudNetworkProcessor() //linux设置network + ProcessorMap["InitNode"] = NewInitNodeProcessor() + ProcessorMap["FormatPartitions"] = NewFormatPartitionsProcessor() + ProcessorMap["MountPartitions"] = NewMountPartitionsProcessor() + + //以下用于windows方式 + ProcessorMap["SetNetworkWindows"] = NewSetNetworkDataProcessor() +} + +// getCurrentGoroutineStack 获取当前Goroutine的调用栈,便于排查panic异常 +func getCurrentGoroutineStack() string { + + const defaultStackSize = 4096 + + var buf [defaultStackSize]byte + n := runtime.Stack(buf[:], false) + return string(buf[:n]) +} + +//Process 处理单个子command的入口 +func (b BaseProcessor) Process(logger *log.Logger, command *commandDao.Command) { + + logger.Info("[开始处理command]:", command.Action) + action := CommandAction.CommandActionDict[command.Action] + //防止有些指令没有注册策略和过期值,给默认值 + if action.Policy == "" { + action.Policy = TimeoutPolicy.WARNING + } + if action.Timeout == 0 { + action.Timeout = 180 + } + command.Status = CommandStatus.RUNNING + command.ExecuteCount += 1 + command.UpdatedTime = int(time.Now().Unix()) + command.TimeoutTime = time.Now().Add(time.Duration(action.Timeout) * time.Second) + command.TimeoutPolicy = action.Policy + if err := commandDao.UpdateCommandById(logger, command); err != nil { + logger.Warn("Process UpdateCommandById sql error:", err.Error()) + } + defer func() { + if r := recover(); r != nil { + logger.Warnf("processor.Run panic, error:%v, stack:%s", r, getCurrentGoroutineStack()) + // if reflect.TypeOf(r).String() == "processor.ProcessAbortException" { + // abortProcess(logger, command, t) + // } else { + // sendErrorCallback(logger, command, t) + // } + } + }() + p, ok := ProcessorMap[command.Action] + if !ok { + logger.Warnf("ProcessorMap not found key %s", command.Action) + return + } + p.doProcess(logger, command) + p.afterProcess(logger, command) +} + +// ironic-agent/driver 投递来command异步执行结果的入口 +func (b BaseProcessor) CallBack(logger *log.Logger, command *commandDao.Command, msg ironicCommon.CallbackCommandMessage) { + val, _ := json.Marshal(msg) + v, _ := json.Marshal(command) + if strings.ToUpper(msg.Status) == OK { + logger.Info("CallBack SuccessExecute command from driver/agent: ", string(v)) + b.AfterSuccessExecute(logger, command) + } else { + logger.Warn("CallBack FailedExecute command from driver/agent: ", string(v)) + b.AfterFailedExecute(logger, command, string(val)) + } + if err := redis.SetObjectToRedis(fmt.Sprintf(constants.COMMAND_RESULT, fmt.Sprint(command.ID)), string(val)); err != nil { + logger.Warn("BaseProcessor CallBack SetObjectToRedis error:", command.ID, err.Error()) + } +} + +func (b BaseProcessor) AfterSuccessExecute(logger *log.Logger, command *commandDao.Command) { + logger.Info("[command指令处理完成]:", command.Action, "准备将command状态更新为finish") + command.Status = CommandStatus.FINISH + command.UpdatedTime = int(time.Now().Unix()) + if err := commandDao.UpdateCommandById(logger, command); err != nil { + logger.Warn("afterSuccessExecute UpdateCommandById sql error:", err.Error()) + } + instance := &instanceDao.Instance{ + InstanceID: command.InstanceID, + Reason: "", + } + instanceDao.UpdateSuccessInstanceByInstanceId(logger, instance) //实例失败原因置为空 + instanceDao.UpdateInstanceByInstanceId(logger, instance) + logger.Info("更新实例创建原因为空,success", command.InstanceID) + next_command, err := commandDao.GetCommandByParentId(logger, int64(command.ID)) + if err != nil { + logger.Warn("afterSuccessExecute GetCommandByParentId sql error:", command.ID, err.Error()) + } + v, _ := json.Marshal(next_command) + if next_command != nil { + logger.Info("start success_execute_next_command: ", string(v)) + b.Process(logger, next_command) + } else { + //采集任务时,设置device的采集状态为成功 + deviceEntity, err := deviceDao.GetBySn(logger, command.Sn) + if err != nil { + logger.Warnf("AfterSuccessExecute.GetBySn error, sn:%s, error:%s", command.Sn, err.Error()) + } else { + deviceEntity.CollectStatus = "1" //1表示采集成功 + deviceEntity.CollectFailReason = "" + if err := deviceDao.UpdateDeviceAnywhere(logger, deviceEntity); err != nil { + logger.Warnf("AfterSuccessExecute.UpdateDeviceAnywhere error, sn:%s, error:%s", command.Sn, err.Error()) + } + } + + auditLogLogic.SetAuditLogToSuccess(logger, command.Sn, command.InstanceID, command.Task) + + logger.Infof("全部指令执行完毕,开始更新设备%s实例状态", command.Sn) + instanceLogic.CallBack(logger, command.InstanceID) + } +} + +func (b BaseProcessor) AfterFailedExecute(logger *log.Logger, command *commandDao.Command, failed_msg string) { + v, _ := json.Marshal(command) + // fmt.Println(command.Action, "已经执行的次数", command.ExecuteCount) + if command.ExecuteCount > COMMAND_MAX_EXECUTE_COUNT { + return + } else if command.ExecuteCount == COMMAND_MAX_EXECUTE_COUNT { + logger.Warn("execute faild max time, command: ", string(v)) + command.ExecuteCount += 1 + command.Status = CommandStatus.ERROR + command.UpdatedTime = int(time.Now().Unix()) + if err := commandDao.UpdateCommandById(logger, command); err != nil { + logger.Warn("BaseProcessor afterFailedExecute UpdateCommandById sql error:", err.Error()) + } + msg := &ironicCommon.CallbackCommandMessage{} + if err := json.Unmarshal([]byte(failed_msg), msg); err != nil { + logger.Warn("BaseProcessor unmarshal json error:", err.Error()) + } + var instanceEntity *instanceDao.Instance + var err error + if command.InstanceID != "" { + + instanceEntity, err = instanceDao.GetInstanceByUuid(logger, command.InstanceID) + if err != nil { + logger.Warnf("AfterFailedExecute.GetInstanceByUuid error, command_id:%d, instance_id:%s, error:%s", command.ID, command.InstanceID, err.Error()) + return + } + + instanceEntity.Status = InstanceStatus.Instance_To_Error_Status[command.Task] //实例状态置为特定错误 + + if command.Type == "driver" { + instanceEntity.Reason = msg.Status + } + if instanceEntity.Reason == "" { + instanceEntity.Reason = command.Action + "Error" + } + + instanceDao.UpdateInstanceByInstanceId(logger, instanceEntity) + logger.Info("更新实例创建失败原因", command.InstanceID, msg.Status) + + } + if command.Task == "CollectHardwareInfo" { //采集失败也需要记录失败原因 + deviceEntity, err := deviceDao.GetBySn(logger, command.Sn) + if err != nil { + logger.Warnf("AfterFailedExecute.CollectHardwareInfo.GetBySn error, sn:%s, error:%s", command.Sn, err.Error()) + } else { + deviceEntity.CollectStatus = "4" //4表示采集失败 + deviceEntity.CollectFailReason = command.Action + "Error" + if err := deviceDao.UpdateDeviceById(logger, deviceEntity); err != nil { + logger.Warnf("AfterFailedExecute.CollectHardwareInfo.UpdateDeviceById error, sn:%s, error:%s", command.Sn, err.Error()) + } + } + } + webMsg := messageDao.WebMessage{ + MessageID: util.GetUuid("m-"), + // UserID: logger.GetPoint("user_id").(string),????? + SN: command.Sn, + MessageType: messageType.MessageTypeOperation, + MessageSubType: command.Task, //注意在common库中和task(message)保持一致 + ResourceType: "instance", + Result: "failed", + FinishTime: int(time.Now().Unix()), + Detail: command.Sn, + } + mailSubject := "" + mailTpl := "" + if instanceEntity != nil { + webMsg.UserID = instanceEntity.UserID + webMsg.InstanceID = instanceEntity.InstanceID + webMsg.InstanceName = instanceEntity.InstanceName + webMsg.Detail = fmt.Sprintf("%s/%s", instanceEntity.InstanceName, command.Sn) + + user, err := userDao.GetUserById(logger, instanceEntity.UserID) + if err != nil { + logger.Warnf("AfterFailedExecute.GetUserById error, user_id:%s, error:%s", instanceEntity.UserID, err.Error()) + } + if user != nil { + webMsg.UserName = user.UserName + } + + mailSubject = fmt.Sprintf("操作消息-【%s】失败通知", webMsg.MessageSubType) + mailTpl = mailLogic.OperationAfterInstanceTemplate + + } else { + mailSubject = fmt.Sprintf("操作消息-【%s】失败通知", webMsg.MessageSubType) + mailTpl = mailLogic.OperationBeforeInstanceTemplate + } + + if err := messagelogic.SendWebNotice(logger, webMsg); err != nil { + logger.Warnf("BaseProcessor.AfterFailedExecute.SendWebNotice error:%s", err.Error()) + } + //发送邮件通知 + err = mailLogic.SendMailByTpl(logger, mailTpl, mailSubject, WebMessage2MailMessage(webMsg)) + if err != nil { + logger.Warnf("doLicenseTimeoutCron.SendMail error:%s", err.Error()) + } + // sendErrorMailMessage(logger, command, []byte(failed_msg)) + + auditLogLogic.SetAuditLogToFail(logger, command.Sn, command.InstanceID, command.Task, command.Action+"Error") + + } else { + logger.Info("execute again, command: ", string(v)) + b.Process(logger, command) //重新执行一次 + } +} + +func WebMessage2MailMessage(p messageDao.WebMessage) mailLogic.MailMessage { + m := mailLogic.MailMessage{ + MessageID: p.MessageID, + MessageType: p.MessageType, + MessageSubType: messagelogic.Types2ShowZh[p.MessageSubType], + ResourceType: p.ResourceType, + FinishTime: time.Unix(int64(p.FinishTime), 0).Format("2006-01-02 15:04:05"), + Detail: p.Detail, + SN: p.SN, + UserID: p.UserID, + UserName: p.UserName, + InstanceID: p.InstanceID, + InstanceName: p.InstanceName, + } + if m.MessageSubType == "" { + m.MessageSubType = p.MessageSubType + } + if m.UserName == "" { + m.UserName = "admin" + } + return m +} + +func abortProcess(logger *log.Logger, command *commandDao.Command, e []byte) { + command.Status = CommandStatus.ERROR + command.UpdatedTime = int(time.Now().Unix()) + if err := commandDao.UpdateCommandById(logger, command); err != nil { + logger.Warn("abortProcess UpdateCommandById sql error:", err.Error()) + } + err := redis.SetObjectToRedis(fmt.Sprintf(constants.COMMAND_RESULT, fmt.Sprint(command.ID)), string(e)) + if err != nil { + logger.Warn("QueryCommands SetObjectToRedis error:", err.Error()) + } + sendErrorMailMessage(logger, command, e) +} + +func sendErrorCallback(logger *log.Logger, command *commandDao.Command, e []byte) { + //TODO +} + +func sendErrorMailMessage(logger *log.Logger, command *commandDao.Command, e []byte) { + //TODO +} + +func loadInstanceExtra(logger *log.Logger, instance_id string) *types.InstanceExtra { + extra_json, err := redis.GetObjectFromRedis(fmt.Sprintf(constants.INSTANCE_EXTRA_KEY, instance_id)) + if err != nil || extra_json == "" { + logger.Warn("loadInstanceExtra GetObjectFromRedis error:", instance_id, err.Error()) + return nil + } + var r = types.InstanceExtra{} + if json.Unmarshal([]byte(extra_json), &r); err != nil { + logger.Warn("loadInstanceExtra Unmarshal error:", extra_json, err.Error()) + return nil + } + return &r +} diff --git a/bmp-scheduler/processor/BindingIPv6Processor.go b/bmp-scheduler/processor/BindingIPv6Processor.go new file mode 100644 index 0000000..01ac9d1 --- /dev/null +++ b/bmp-scheduler/processor/BindingIPv6Processor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type BindingIPv6Processor struct { + BaseProcessor +} + +func NewBindingIPv6Processor() BindingIPv6Processor { + b := BindingIPv6Processor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b BindingIPv6Processor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b BindingIPv6Processor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b BindingIPv6Processor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b BindingIPv6Processor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/BindingVSIProcessor.go b/bmp-scheduler/processor/BindingVSIProcessor.go new file mode 100644 index 0000000..669a573 --- /dev/null +++ b/bmp-scheduler/processor/BindingVSIProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type BindingVSIProcessor struct { + BaseProcessor +} + +func NewBindingVSIProcessor() BindingVSIProcessor { + b := BindingVSIProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b BindingVSIProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b BindingVSIProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b BindingVSIProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b BindingVSIProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/CheckInitConfigProcessor.go b/bmp-scheduler/processor/CheckInitConfigProcessor.go new file mode 100644 index 0000000..9e7de1e --- /dev/null +++ b/bmp-scheduler/processor/CheckInitConfigProcessor.go @@ -0,0 +1,78 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/idcLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + driverTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type CheckInitConfigProcessor struct { + BaseProcessor +} + +func NewCheckInitConfigProcessor() CheckInitConfigProcessor { + b := CheckInitConfigProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} +func (b CheckInitConfigProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b CheckInitConfigProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b CheckInitConfigProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + var err error + + var iloIP, iloUser, iloPassword string + + v, _ := deviceDao.GetBySn(logger, command.Sn) + if v != nil { + iloIP = v.IloIP + iloUser = v.IloUser + iloPassword = v.IloPassword + } + + //再查找idcid + idc, err := idcLogic.GetIdcID(logger) + if err != nil { + logger.Warnf("GetOneIdc error:%s", err.Error()) + panic(ProcessAbortException{Msg: "process CheckInitConfigProcessor GetIdc error"}) + + } + + msgCheck := driverTypes.CheckInitConfig{ + IloIp: iloIP, + Sn: command.Sn, + Username: iloUser, + Password: iloPassword, + Privilege: "Administrator", + } + //优先从设备取带外user/passwd,没有的话用idc的 + if msgCheck.Username == "" { + msgCheck.Username = idc.IloUser + } + if msgCheck.Password == "" { + msgCheck.Password = idc.IloPassword + } + + if err := rabbitMq.SendToAgent(idc.IDcID, msgCheck); err != nil { + logger.Warn("CheckInitConfigProcessor SendToAgent error:", idc.IDcID, err.Error()) + return + } + + logger.Infof("CheckInitConfigProcessor_SendToAgent_Msg: %s, routingkey:%s", util.ObjToJson(msgCheck), idc.IDcID) +} + +func (b CheckInitConfigProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //默认成功,执行下一条指令 + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/CleanArpStaticProcessor.go b/bmp-scheduler/processor/CleanArpStaticProcessor.go new file mode 100644 index 0000000..7da4a63 --- /dev/null +++ b/bmp-scheduler/processor/CleanArpStaticProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type CleanArpStaticProcessor struct { + BaseProcessor +} + +func NewCleanArpStaticProcessor() CleanArpStaticProcessor { + b := CleanArpStaticProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b CleanArpStaticProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b CleanArpStaticProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b CleanArpStaticProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b CleanArpStaticProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/CleanBandwidthProcessor.go b/bmp-scheduler/processor/CleanBandwidthProcessor.go new file mode 100644 index 0000000..f9223b5 --- /dev/null +++ b/bmp-scheduler/processor/CleanBandwidthProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type CleanBandwidthProcessor struct { + BaseProcessor +} + +func NewCleanBandwidthProcessor() CleanBandwidthProcessor { + b := CleanBandwidthProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b CleanBandwidthProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b CleanBandwidthProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b CleanBandwidthProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b CleanBandwidthProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/CleanBlockDeviceProcessor.go b/bmp-scheduler/processor/CleanBlockDeviceProcessor.go new file mode 100644 index 0000000..099e018 --- /dev/null +++ b/bmp-scheduler/processor/CleanBlockDeviceProcessor.go @@ -0,0 +1,61 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceHintsDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type CleanBlockDeviceProcessor struct { + BaseProcessor +} + +func NewCleanBlockDeviceProcessor() CleanBlockDeviceProcessor { + b := CleanBlockDeviceProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b CleanBlockDeviceProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b CleanBlockDeviceProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b CleanBlockDeviceProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + clean_block_device := agentTypes.CleanBlockDevice{ + Sn: command.Sn, + } + if err := rabbitMq.SendToAgent(command.Sn, clean_block_device); err != nil { + logger.Warn("CleanBlockDeviceProcessor SendToAgent error:", command.Sn, err.Error()) + return + } + logger.Infof("CleanBlockDeviceProcessor_SendToAgent_Msg:%s", util.ObjToJson(clean_block_device)) + + // 重装时再使用 + + deviceHintEntity, err := deviceHintsDao.GetSystemVolumnDeviceHintsBySn(logger, command.Sn) + if err != nil { + logger.Warn("CleanBlockDeviceProcessor.GetAllRootDeviceHints error:", command.Sn, err.Error()) + return + } + // for _, entity := range entities { + deviceHintEntity.IsDel = 1 + if err := deviceHintsDao.UpdateDeviceHintsById(logger, deviceHintEntity); err != nil { + logger.Warn("CleanBlockDeviceProcessor.UpdateRootDeviceHintsById error:", err.Error()) + } + // } + +} + +func (b CleanBlockDeviceProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/CleanRaidProcessor.go b/bmp-scheduler/processor/CleanRaidProcessor.go new file mode 100644 index 0000000..856215c --- /dev/null +++ b/bmp-scheduler/processor/CleanRaidProcessor.go @@ -0,0 +1,89 @@ +package processor + +import ( + "fmt" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceHintsDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/diskDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type CleanRaidProcessor struct { + BaseProcessor +} + +func NewCleanRaidProcessor() CleanRaidProcessor { + b := CleanRaidProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b CleanRaidProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b CleanRaidProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b CleanRaidProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + device, err := deviceLogic.GetBySn(logger, command.Sn) + if err != nil { + logger.Warnf("CleanRaidProcessor GetBySn sql error, sn:%s, error:%s", command.Sn, err.Error()) + } + if device == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("CleanRaidProcessor error, device %s not found", command.Sn)}) + } + + //需要删除device_hints中的盘符信息,但是device_hints不光有盘符,还有nvmes,所以要借助disk + query := map[string]interface{}{ + "is_del": 0, + "device_id": device.DeviceID, + "types": "panfu", + } + diskEntities, err := diskDao.GetDisks(logger, query) + serials := []string{} + for _, diskEntity := range diskEntities { + serials = append(serials, diskEntity.Serial) + } + if len(serials) > 0 { + q := map[string]interface{}{ + "is_del": 0, + "serial.in": serials, + } + u := map[string]interface{}{ + "is_del": 1, + } + if err := deviceHintsDao.UpdateMultiDeviceHints(logger, q, u); err != nil { + logger.Warnf("CleanRaidProcessor.UpdateMultiDeviceHints error, sn:%s, error:%s", command.Sn, err.Error()) + } + + } + + clean_block_device := agentTypes.CleanRaid{ + Sn: command.Sn, + RaidDatas: []agentTypes.RaidData{ + { + AdapterId: device.AdapterID, + RaidDriver: device.RaidDriver, + }, + }, + } + if err := rabbitMq.SendToAgent(command.Sn, clean_block_device); err != nil { + logger.Warn("CleanRaidProcessor SendToAgent error:", command.Sn, err.Error()) + return + } + logger.Infof("CleanRaidProcessor_SendToAgent_Msg:%s", util.ObjToJson(clean_block_device)) +} + +func (b CleanRaidProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/CollectDiskLocationsProcessor.go b/bmp-scheduler/processor/CollectDiskLocationsProcessor.go new file mode 100644 index 0000000..d840933 --- /dev/null +++ b/bmp-scheduler/processor/CollectDiskLocationsProcessor.go @@ -0,0 +1,322 @@ +package processor + +import ( + "bufio" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/diskDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + util "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" + beego "github.com/beego/beego/v2/server/web" +) + +type D struct { + Enclosure int `json:"enclosure"` + Slot int `json:"slot"` + Size float64 `json:"size"` + //GB + SizeUnit string `json:"size_unit"` + //接口类型 SAS + PdType string `json:"pd_type"` + //磁盘类型 新增, SDD + MediaType string `json:"media_type"` +} + +type Nvme struct { + //nvme无须做raid enclosure,slot都设置为0即可 + Devices []NvmeDevice `json:"devices"` +} +type NvmeDevice struct { + // /dev/nvme0n1 + DevicePath string `json:"device_path"` + Index int `json:"index"` + Serial string `json:"serial"` + Size float64 `json:"size"` + //GB + SizeUnit string `json:"size_unit"` + //接口类型 NVME + PdType string `json:"pd_type"` + //磁盘类型 新增, SDD + MediaType string `json:"media_type"` +} + +type Cit struct { + Disks []D `json:"disks"` + AdapterID int `json:"adapter_id"` //可能是int,也可能是string +} + +type TmpDiskInfo struct { + // 有的机器可能有多张raid卡的情况,每个cit都代表一个raid卡。本次只支持有一张raid卡 + Controllers []Cit `json:"controllers"` + Nvme Nvme `json:"nvme"` + //盘符 + Devices []DeviceItem `json:"devices"` +} + +type DeviceItem struct { + // /dev/nvme0n1 + DevicePath string `json:"device_path"` + //磁盘类型 新增, SDD + MediaType string `json:"media_type"` + Serial string `json:"serial"` + Size float64 `json:"size"` + //GB + SizeUnit string `json:"size_unit"` +} + +type CollectDiskLocationsProcessor struct { + BaseProcessor +} + +func NewCollectDiskLocationsProcessor() CollectDiskLocationsProcessor { + b := CollectDiskLocationsProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b CollectDiskLocationsProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b CollectDiskLocationsProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + + logger.Info("CollectDiskLocationsProcessor Callback starting...", msg.Sn) + defer logger.Info("CollectDiskLocationsProcessor Callback ending...", msg.Sn) + if strings.ToUpper(msg.Status) == OK { + logger.Infof("CollectDiskLocationsProcessor callback content is:%s", util.ObjToJson(msg.Data)) + //以后再优化成更优雅的方法 + b, err := json.Marshal(msg.Data) + if err != nil { + logger.Warn("CollectDiskLocationsProcessor Callback unmarshal error:", msg.Sn, err.Error()) + } else { + SaveDiskLocationInfo(logger, msg.Sn, b) + } + } + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b CollectDiskLocationsProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + logger.Info("CollectDiskLocationsProcessor doProcess starting...", command.Sn) + defer logger.Info("CollectDiskLocationsProcessor doProcess ending...", command.Sn) + + device, err := deviceDao.GetBySn(logger, command.Sn) + if err != nil { + logger.Warn("CollectDiskLocationsProcessor GetById sql error:", command.Sn, err.Error()) + } + if device == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process CollectDiskLocationsProcessor error,sn %s device not found", command.Sn)}) + } + + collect_disk_location := agentTypes.CollectDiskLocations{ + Sn: command.Sn, + Action: command.Action, + Version: "2.0", + // AdapterIds: []string{strconv.Itoa(device.AdapterID)}, + AllowOverride: false, + RaidDriver: device.RaidDriver, + } + // if device.AllowOverride != 0 { + // collect_disk_location.AllowOverride = true + // } + if err := rabbitMq.SendToAgent(command.Sn, collect_disk_location); err != nil { + logger.Warnf("CollectDiskLocationsProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(collect_disk_location), err.Error()) + return + } + logger.Infof("CollectDiskLocationsProcessor_SendToAgent_Msg:%s", util.ObjToJson(collect_disk_location)) +} + +func (b CollectDiskLocationsProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + logger.Info("CollectDiskLocationsProcessor afterProcess starting...", command.Sn) + defer logger.Info("CollectDiskLocationsProcessor afterProcess ending...", command.Sn) + //empty +} + +func saveDiskToDb(logger *log.Logger, sn string, c TmpDiskInfo) error { + + deviceEntity, err := deviceDao.GetBySn(logger, sn) + if err != nil { + logger.Warnf("saveDiskToDb.GetBySn error, sn:%s, err:%s", sn, err.Error()) + return err + } + if deviceEntity == nil { + logger.Warnf("saveDiskToDb deviceEntity get nil, sn:%s", sn) + return errors.New("invalid sn, check it!!!") + } + + q1 := map[string]interface{}{ + "is_del": 0, + "device_id": deviceEntity.DeviceID, + } + u1 := map[string]interface{}{ + "is_del": 1, + } + if err := diskDao.UpdateMultiDisks(logger, q1, u1); err != nil { + logger.Warnf("saveDiskToDb.delDisks error, device_id:%s, error:%s", deviceEntity.DeviceID, err.Error()) + } + + //普通盘 + var disks []D + //nvme盘 + var nvmes []NvmeDevice + //盘符 + var panfus []DeviceItem + if len(c.Controllers) > 0 { + deviceEntity.AdapterID = c.Controllers[0].AdapterID + disks = c.Controllers[0].Disks + } + if err := deviceDao.UpdateDeviceAnywhere(logger, deviceEntity); err != nil { + logger.Warnf("saveDiskToDb.UpdateDevice.HasCollected and AdapterID error, sn:%s, error:%s", deviceEntity.Sn, err.Error()) + } + + nvmes = c.Nvme.Devices + panfus = c.Devices + + diskEntities := []*diskDao.Disk{} + for _, disk := range disks { + d := &diskDao.Disk{ + DiskId: util.GetUuid("disk-"), + Name: fmt.Sprintf("磁盘%d", disk.Slot), + DeviceID: deviceEntity.DeviceID, + Enclosure: fmt.Sprintf("%d", disk.Enclosure), + Slot: disk.Slot, + Size: strconv.FormatFloat(disk.Size, 'f', -1, 64), + SizeUnit: disk.SizeUnit, + PdType: disk.PdType, + MediaType: disk.MediaType, + Types: "controller", + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + } + //agent采集过来的是二进制,这里转换成10进制 + if d.SizeUnit == "GB" { + disk.Size = 1.073741824 * disk.Size + d.Size = strconv.Itoa(int(disk.Size)) + } else if d.SizeUnit == "TB" { + disk.Size = 1.1 * disk.Size + d.Size = strconv.FormatFloat(disk.Size, 'f', 2, 64) + } + + diskEntities = append(diskEntities, d) + } + for _, nvme := range nvmes { + p := strings.Split(nvme.DevicePath, "/") + d := &diskDao.Disk{ + DiskId: util.GetUuid("disk-"), + Name: p[len(p)-1], + DeviceID: deviceEntity.DeviceID, + DevicePath: nvme.DevicePath, + Serial: nvme.Serial, + Size: strconv.FormatFloat(nvme.Size, 'f', -1, 64), + SizeUnit: nvme.SizeUnit, + PdType: nvme.PdType, + MediaType: nvme.MediaType, + Types: "nvme", + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + } + //agent采集过来的是二进制,这里转换成10进制 + if d.SizeUnit == "GB" { + nvme.Size = 1.073741824 * nvme.Size + d.Size = strconv.Itoa(int(nvme.Size)) + } else if d.SizeUnit == "TB" { + nvme.Size = 1.1 * nvme.Size + d.Size = strconv.FormatFloat(nvme.Size, 'f', 2, 64) + } + + diskEntities = append(diskEntities, d) + } + for _, panfu := range panfus { + p := strings.Split(panfu.DevicePath, "/") + + d := &diskDao.Disk{ + DiskId: util.GetUuid("disk-"), + Name: p[len(p)-1], + DeviceID: deviceEntity.DeviceID, + DevicePath: panfu.DevicePath, + MediaType: panfu.MediaType, + Serial: panfu.Serial, + Size: strconv.FormatFloat(panfu.Size, 'f', -1, 64), + SizeUnit: panfu.SizeUnit, + Types: "panfu", + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + } + //agent采集过来的是二进制,这里转换成10进制 + if d.SizeUnit == "GB" { + panfu.Size = 1.073741824 * panfu.Size + d.Size = strconv.Itoa(int(panfu.Size)) + } else if d.SizeUnit == "TB" { + panfu.Size = 1.1 * panfu.Size + d.Size = strconv.FormatFloat(panfu.Size, 'f', 2, 64) + } + + diskEntities = append(diskEntities, d) + } + + if _, err := diskDao.AddMultiDisk(logger, diskEntities); err != nil { + logger.Warnf("saveDiskToDb.AddMultiDisk error:%s", err.Error()) + return err + } + + return nil +} + +func SaveDiskLocationInfo(logger *log.Logger, sn string, content []byte) error { + + originContent := string(content) + logger.Infof("SaveDiskLocationInfo sn: %s, origin content:%s", sn, originContent) + //controllers.disks[0]的struct + + var err error + c := TmpDiskInfo{} + if err := json.Unmarshal(content, &c); err != nil { + logger.Warnf("SaveDiskLocationInfo parse error, sn:%s, content:%s, error:%s", sn, originContent, err.Error()) + return err + } + + saveDiskToDb(logger, sn, c) + + content, err = json.Marshal(c) + if err != nil { + logger.Warnf("SaveDiskLocationInfo parse2 error, sn:%s, content:%s, error:%s", sn, originContent, err.Error()) + return err + } + + logPath, _ := beego.AppConfig.String("log.path") + targetDir := filepath.Join(logPath, "disk_location_dir") + if _, err := os.Stat(targetDir); os.IsNotExist(err) { + // 必须分成两步:先创建文件夹、再修改权限 + os.Mkdir(targetDir, 0777) //0777也可以os.ModePerm + os.Chmod(targetDir, 0777) + } + targetFile := filepath.Join(targetDir, sn) + + file, err := os.OpenFile(targetFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) + if err != nil { + logger.Warn(targetFile, "文件打开失败:", err) + return err + } + //及时关闭file句柄 + defer file.Close() + write := bufio.NewWriter(file) + if _, err := write.WriteString(string(content)); err != nil { + logger.Warn(targetFile, "CollectDiskLocationsProcessor写入文件失败:", err) + return err + } + //Flush将缓存的文件真正写入到文件中 + write.Flush() + return err +} diff --git a/bmp-scheduler/processor/CollectHardwareInfoProcessor.go b/bmp-scheduler/processor/CollectHardwareInfoProcessor.go new file mode 100644 index 0000000..671cf49 --- /dev/null +++ b/bmp-scheduler/processor/CollectHardwareInfoProcessor.go @@ -0,0 +1,531 @@ +package processor + +import ( + "bufio" + "encoding/json" + "fmt" + "os" + "path/filepath" + "regexp" + "sort" + "strconv" + "strings" + "time" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + deviceDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/interfaceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/jdBondInterfaceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/jdSwitchDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + "coding.jd.com/aidc-bmp/bmp-scheduler/service/redis" + "coding.jd.com/aidc-bmp/bmp-scheduler/types" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + util "coding.jd.com/aidc-bmp/bmp-scheduler/util" + "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + "git.jd.com/cps-golang/ironic-common/ironic/enums/InterfaceType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" + beego "github.com/beego/beego/v2/server/web" +) + +const ( + SWITCH_PORT_REGEX = `[0-9]/([0-9]+)` + INTERFACE_ETH0_NAME = "eth0" + INTERFACE_ETH1_NAME = "eth1" +) + +type CollectHardwareInfoProcessor struct { + BaseProcessor +} + +func NewCollectHardwareInfoProcessor() CollectHardwareInfoProcessor { + b := CollectHardwareInfoProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b CollectHardwareInfoProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +type HardwareInfo struct { + // megacli64 + RaidDriver string `json:"raid_driver"` + // 10.208.16.165 + BmcAddress string `json:"bmc_address"` + Interfaces Interfaces `json:"interfaces"` + // Disks []Disk `json:"disks"` + Boot Boot `json:"boot"` + SystemVendor *SystemVendor `json:"system_vendor"` + Memory Memory `json:"memory"` + CPU CPU `json:"cpu"` + Platform Platform `json:"platform"` +} + +const MAX_PRIVATE_INTERFACE_INDEX = 20 + +type Interface struct { + Product string `json:"product"` + Vendor string `json:"vendor"` + Name string `json:"name"` + HasCarrier bool `json:"has_carrier"` + Ipv4Address string `json:"ipv4_address"` + SwitchManageIP string `json:"switch_manage_ip"` + Biosdevname string `json:"biosdevname"` + MacAddress string `json:"mac_address"` + SwitchIndex string `json:"switch_index"` +} + +func (i Interface) isPrivateInterface() bool { + return getSwitchPortIndex(i.SwitchIndex) <= MAX_PRIVATE_INTERFACE_INDEX +} + +type Interfaces []Interface + +func (in Interfaces) Len() int { return len(in) } + +func (in Interfaces) Swap(i, j int) { in[i], in[j] = in[j], in[i] } + +func (in Interfaces) Less(i, j int) bool { return in[i].MacAddress < in[j].MacAddress } + +type Disk struct { + Rotational bool `json:"rotational"` + Vendor string `json:"vendor"` + Name string `json:"name"` + WwnVendorExtension string `json:"wwn_vendor_extension"` + Hctl string `json:"hctl"` + WwnWithExtension string `json:"wwn_with_extension"` + ByPath string `json:"by_path"` + Model string `json:"model"` + Wwn string `json:"wwn"` + Serial string `json:"serial"` + Size int64 `json:"size"` +} + +type Boot struct { + CurrentBootMode string `json:"current_boot_mode"` +} + +type SystemVendor struct { + SerialNumber string `json:"serial_number"` + ProductName string `json:"product_name"` + Manufacturer string `json:"manufacturer"` +} + +type Memory struct { + PhysicalMb int64 `json:"physical_mb"` + Total int64 `json:"total"` +} + +type CPU struct { + Count int `json:"count"` + Frequency string `json:"frequency"` + Flags []string `json:"flags"` + ModelName string `json:"model_name"` + Architecture string `json:"architecture"` +} + +type Platform struct { + //系统架构 x86_64, aarch64 + Machine string `json:"machine"` +} + +func (b CollectHardwareInfoProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + + logger.Info("CollectHardwareInfoProcessor Callback starting...", msg.Sn) + defer logger.Info("CollectHardwareInfoProcessor Callback ending...", msg.Sn) + if strings.ToUpper(msg.Status) == OK { + + //以后再优化成更优雅的方法 + b, _ := json.Marshal(msg.Data) + saveHardwareInfo(logger, msg.Sn, b) + + } + b.BaseProcessor.CallBack(logger, command, msg) +} + +func saveHardwareInfo(logger *log.Logger, sn string, content []byte) error { + + originContent := string(content) + + logger.Infof("TmpHardwareInfo sn: %s, origin content:%s", sn, string(content)) + + var err error + c := HardwareInfo{} + if err := json.Unmarshal(content, &c); err != nil { + logger.Warnf("TmpHardwareInfo parse error, sn:%s, content:%s", sn, originContent) + return err + } + + saveHardware2Db(logger, sn, c) + + content, err = json.Marshal(c) + if err != nil { + logger.Warnf("TmpHardwareInfo parse2 error, sn:%s, content:%s", sn, originContent) + return err + } + + logPath, _ := beego.AppConfig.String("log.path") + targetDir := filepath.Join(logPath, "hardware_info_dir") + if _, err := os.Stat(targetDir); os.IsNotExist(err) { + // 必须分成两步:先创建文件夹、再修改权限 + os.Mkdir(targetDir, 0777) //0777也可以os.ModePerm + os.Chmod(targetDir, 0777) + } + targetFile := filepath.Join(targetDir, sn) + + file, err := os.OpenFile(targetFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) + if err != nil { + logger.Warn(targetFile, "文件打开失败:", err) + return err + } + //及时关闭file句柄 + defer file.Close() + write := bufio.NewWriter(file) + if _, err := write.WriteString(string(content)); err != nil { + logger.Warn(targetFile, "CollectHardwareInfoProcessor写入文件失败:", err) + return err + } + //Flush将缓存的文件真正写入到文件中 + write.Flush() + return err +} + +func saveHardware2Db(logger *log.Logger, sn string, hardware_info HardwareInfo) error { + logger.Info("saveHardware2Db starting......", sn) + defer logger.Info("saveHardware2Db ending......", sn) + device, err := deviceDao.GetBySn(logger, sn) + if device == nil { + logger.Warn(fmt.Sprintf("device not found by sn %s, sql error: %s", sn, err.Error())) + return err + } + + //这里对deviceEntity的interface信息进行设置 + if err := parseInterfaces(logger, device, hardware_info.Interfaces); err != nil { + return err + } + + system_vendor := hardware_info.SystemVendor + if system_vendor != nil { + + device.Brand = system_vendor.Manufacturer + device.Model = system_vendor.ProductName + } + device.RaidDriver = hardware_info.RaidDriver + device.CurrentBootMode = hardware_info.Boot.CurrentBootMode + device.Architecture = hardware_info.Platform.Machine + + //device.ManufacturerID = manufacturer_entity.ID + if err := deviceDao.UpdateDeviceAnywhere(logger, device); err != nil { + logger.Warnf("saveHardware2Db UpdateDeviceAnywhere error, sn:%s, error:%s", device.Sn, err.Error()) + return err + } + + return nil +} + +func isRetail(logger *log.Logger, sn string) bool { + logger.Info("isRetail ......", sn) + + var info_extra *types.CollectInfoExtra = loadCollectInfoExtra(logger, sn) + if info_extra == nil { + return false + } + return info_extra.NetworkType == NetworkType.RETAIL +} + +func loadCollectInfoExtra(logger *log.Logger, sn string) *types.CollectInfoExtra { + logger.Info("loadCollectInfoExtra ......", sn) + extra_json, err := redis.GetObjectFromRedis(fmt.Sprintf(Constants.COLLECT_EXTRA_KEY, sn)) + logger.Info("extra_json is: ", sn, extra_json) + if err != nil { + logger.Warn("loadCollectInfoExtra GetObjectFromRedis error:", sn, err.Error()) + } + if extra_json == "" { + return nil + } + var c = &types.CollectInfoExtra{} + if err := json.Unmarshal([]byte(extra_json), c); err != nil { + logger.Warn("loadCollectInfoExtra Unmarshal error:", sn, err.Error()) + return nil + } + return c +} + +func checkRetailInterfaces(logger *log.Logger, sn string, interfaces Interfaces) { + + logger.Info("checkRetailInterfaces ......", sn) + //debug...... + // s := `[{"product": "0x10fb", "vendor": "0x8086", "name": "eth1", "has_carrier": true, "ipv4_address": "10.208.14.167", "switch_manage_ip": "10.208.13.11", "biosdevname": "em2", "mac_address": "24:6e:96:b7:b0:da", "switch_index": "Ten-GigabitEthernet2/0/3"}, {"product": "0x10fb", "vendor": "0x8086", "name": "eth0", "has_carrier": true, "ipv4_address": "10.208.14.184", "switch_manage_ip": "10.208.13.11", "biosdevname": "em1", "mac_address": "24:6e:96:b7:b0:d8", "switch_index": "Ten-GigabitEthernet1/0/3"}]` + // if err := json.Unmarshal([]byte(s), &interfaces); err != nil { + // fmt.Println("mock interface error:", err.Error()) + // } + //ending debug...... + + if len(interfaces) < 2 { + panic(fmt.Sprintf("CollectHardwareInfo retail switch_index %s not match 2", sn)) + } + sort.Sort(interfaces) + for i := 0; i < len(interfaces)-1; i++ { + first := interfaces[i] + next := interfaces[i+1] + if getSwitchPortIndex(first.SwitchIndex) > getSwitchPortIndex(next.SwitchIndex) { + panic(fmt.Sprintf("CollectHardwareInfo mac&port sort error %s", sn)) + } + } +} + +func getSwitchPortIndex(switch_index string) int { + fmt.Println(time.Now(), "getSwitchPortIndex ......", switch_index) + r, _ := regexp.Compile(SWITCH_PORT_REGEX) + matcher := r.FindAllString(switch_index, -1) + if len(matcher) == 0 { + panic(fmt.Sprintf("switch_index %s not match", switch_index)) + } + n, err := strconv.Atoi(strings.Split(matcher[0], "/")[0]) + if err != nil { + panic(fmt.Sprintf("switch_index %s not match int", switch_index)) + } + return n +} + +func parseInterfaces(logger *log.Logger, device *deviceDao.Device, interfaces Interfaces) error { + logger.Info("parseAndSaveInterfaces ......", device.Sn) + //debug...... + // s := `[{"product": "0x10fb", "vendor": "0x8086", "name": "eth1", "has_carrier": true, "ipv4_address": "10.208.14.167", "switch_manage_ip": "10.208.13.11", "biosdevname": "em2", "mac_address": "24:6e:96:b7:b0:da", "switch_index": "Ten-GigabitEthernet2/0/3"}, {"product": "0x10fb", "vendor": "0x8086", "name": "eth0", "has_carrier": true, "ipv4_address": "10.208.14.184", "switch_manage_ip": "10.208.13.11", "biosdevname": "em1", "mac_address": "24:6e:96:b7:b0:d8", "switch_index": "Ten-GigabitEthernet1/0/3"}]` + // if err := json.Unmarshal([]byte(s), &interfaces); err != nil { + // fmt.Println("mock interface error:", err.Error()) + // } + // if err := deleteInterfaces(logger, sn); err != nil { + // return err + // } + var lan_interface_count int = 0 + var wan_interface_count int = 0 + entities := []*interfaceDao.Interface{} + for _, interface_info := range interfaces { + if interface_info.SwitchIndex == "" { + continue + } + entity := &interfaceDao.Interface{} + if interface_info.isPrivateInterface() { + entity.InterfaceType = InterfaceType.LAN + if lan_interface_count == 0 { + entity.InterfaceName = INTERFACE_ETH0_NAME + } else { + entity.InterfaceName = INTERFACE_ETH1_NAME + } + lan_interface_count += 1 + } else { + entity.InterfaceType = InterfaceType.WAN + if wan_interface_count == 0 { + entity.InterfaceName = INTERFACE_ETH1_NAME + } else { + entity.InterfaceName = INTERFACE_ETH0_NAME + } + wan_interface_count += 1 + } + entity.Ipv4Address = interface_info.Ipv4Address + entity.Sn = device.Sn + entity.Mac = interface_info.MacAddress + entity.SwitchIP = interface_info.SwitchManageIP + entity.SwitchPort = interface_info.SwitchIndex + entities = append(entities, entity) + } + + t := (TempDaoInterfaces)(entities) + sort.Sort(t) + // if _, err := interfaceDao.AddMultiInterface(logger, ([]*interfaceDao.Interface)(t)); err != nil { + // logger.Warn("parseAndSaveInterfaces AddMultiInterface sql error:", err.Error()) + // return err + // } + if len(t) == 1 { //只插一根网线 + device.Mac1 = t[0].Mac + device.SwitchIP = t[0].SwitchIP + device.SwitchIP1 = t[0].SwitchIP + device.SwitchPort1 = t[0].SwitchPort + device.Mac2 = "" + device.SwitchIP2 = "" + device.SwitchPort2 = "" + } else if len(t) == 2 { //插两根网线 + device.Mac1 = t[0].Mac + device.SwitchIP = t[0].SwitchIP + device.SwitchIP1 = t[0].SwitchIP + device.SwitchPort1 = t[0].SwitchPort + device.Mac2 = t[1].Mac + device.SwitchIP2 = t[1].SwitchIP + device.SwitchPort2 = t[1].SwitchPort + device.PrivateEth1IPv4 = t[1].Ipv4Address + } + return nil + +} + +type TempDaoInterfaces []*interfaceDao.Interface + +func (t TempDaoInterfaces) Len() int { return len(t) } + +func (t TempDaoInterfaces) Swap(i, j int) { t[i], t[j] = t[j], t[i] } + +func (t TempDaoInterfaces) Less(i, j int) bool { return t[i].InterfaceName < t[j].InterfaceName } + +func deleteInterfaces(logger *log.Logger, sn string) error { + logger.Info("deleteInterfaces ......", sn) + query := map[string]interface{}{ + "sn": sn, + "is_del": 0, + } + updates := map[string]interface{}{ + "is_del": 1, + "update_time": time.Now(), + } + if err := interfaceDao.UpdateMultiInterfaces(logger, query, updates); err != nil { + logger.Warn("deleteInterfaces UpdateMultiInterfaces sql sn error:", sn, err.Error()) + return err + } + logger.Info("deleteInterfaces UpdateMultiInterfaces sql success, sn:", sn) + return nil + +} + +func parseAndSaveJDBondInterface(logger *log.Logger, sn string, interfaces Interfaces) error { + + logger.Info("parseAndSaveJDBondInterface ......", sn) + bond_entity, err := jdBondInterfaceDao.GetJDBondInterfaceBysn(logger, sn) + if err != nil { + logger.Warn("parseAndSaveJDBondInterface GetJDBondInterfaceBysn sql error:", err.Error()) + } + if bond_entity != nil { + bond_entity.IsDel = 1 + bond_entity.UpdateTime = time.Now() + if err := jdBondInterfaceDao.UpdateJdBondInterfaceById(logger, bond_entity); err != nil { + logger.Warn("parseAndSaveJDBondInterface UpdateJdBondInterfaceById sql error:", err.Error()) + } + } + switch_ips := map[string]struct{}{} + for _, interface_info := range interfaces { + if interface_info.SwitchIndex == "" { + continue + } + switch_ips[interface_info.SwitchManageIP] = struct{}{} + } + if len(switch_ips) == 0 { + return fmt.Errorf("get empty switch_ip from interfaces") + } + for switch_ip, _ := range switch_ips { + //java中对switch_ip加锁,不明白加锁的意义在哪里,先不加 + jd_bond_entity := &jdBondInterfaceDao.JdBondInterface{} + jd_bond_entity.SwitchIP = switch_ip + jd_bond_entity.Sn = sn + entities, err := interfaceDao.GetBySn(logger, sn) + if err != nil { + logger.Warn("parseAndSaveJDBondInterface interfaceDao.GetBySn sql error:", err.Error()) + continue + } + jd_bond_entity.GroupID = getSwitchPortIndex(entities[0].SwitchPort) + jd_bond_entity.PrivateIP = getPrivateIp(logger, sn, switch_ip) + if _, err := jdBondInterfaceDao.AddJdBondInterface(logger, jd_bond_entity); err != nil { + logger.Warn("jdBondInterfaceDao.AddJdBondInterface sql error:", err.Error()) + return err + } + } + return nil + +} + +func getPrivateIp(logger *log.Logger, sn, switch_ip string) string { + query := map[string]interface{}{ + "is_del": 0, + "switch_ip": switch_ip, + } + jd_switch, err := jdSwitchDao.GetOneJdSwitch(logger, query) + if err != nil { + logger.Warn("getPrivateIp GetOneJdSwitch sql error:", err.Error()) + } + if jd_switch == nil || jd_switch.Cidr == "" { + return "" + } + jd_bond_interfaces, err := jdBondInterfaceDao.GetAllJdBondInterface(logger, query) + if err != nil { + logger.Warn("getPrivateIp GetAllJdBondInterface sql error:", err.Error()) + } + used_ips := []string{} + for _, entity := range jd_bond_interfaces { + if entity.PrivateIP != "" { + used_ips = append(used_ips, entity.PrivateIP) + } + } + ip_networks := util.GetAllHostIPs(jd_switch.Cidr) + var tar_ip string + for _, ip := range ip_networks { + if util.InArray(ip, used_ips) { + continue + } else { + tar_ip = ip + break + } + } + if tar_ip == "" { + logger.Warn(fmt.Sprintf("switch_ip cidr is use up %s sn %s", switch_ip, sn)) + panic(fmt.Sprintf("CollectHardwareInfo retail %s %s cidr is use up", switch_ip, sn)) + } + return tar_ip +} + +func parseAndSaveJDSwitch(logger *log.Logger, interfaces Interfaces) error { + + logger.Info("parseAndSaveJDSwitch ......") + switch_ips := map[string]struct{}{} + for _, interface_info := range interfaces { + if interface_info.SwitchIndex == "" { + continue + } + switch_ips[interface_info.SwitchManageIP] = struct{}{} + } + if len(switch_ips) == 0 { + return fmt.Errorf("get empty switch_ip from interfaces") + } + + for switch_ip := range switch_ips { + query := map[string]interface{}{ + "is_del": 0, + "switch_ip": switch_ip, + } + switch_entity, err := jdSwitchDao.GetOneJdSwitch(logger, query) + if err != nil { + logger.Warn("parseAndSaveJDSwitch GetOneJdSwitch sql error:", err.Error()) + } + if switch_entity != nil { + continue + } + jd_switch_entity := &jdSwitchDao.JdSwitch{} + jd_switch_entity.SwitchIP = switch_ip + if _, err := jdSwitchDao.AddJdSwitch(logger, jd_switch_entity); err != nil { + logger.Warn("parseAndSaveJDSwitch AddJdSwitch sql error:", err.Error()) + return err + } + } + return nil +} + +func (b CollectHardwareInfoProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + logger.Info("CollectHardwareInfoProcessor doProcess starting...", command.Sn) + defer logger.Info("CollectHardwareInfoProcessor doProcess ending...", command.Sn) + collect_hardware_info := agentTypes.CollectHardwareInfo{ + Sn: command.Sn, + Action: command.Action, + } + if err := rabbitMq.SendToAgent(command.Sn, collect_hardware_info); err != nil { + logger.Warnf("CollectHardwareInfoProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(collect_hardware_info), err.Error()) + return + } + logger.Infof("CollectHardwareInfoProcessor_SendToAgent_Msg:%s", util.ObjToJson(collect_hardware_info)) +} + +func (b CollectHardwareInfoProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + logger.Info("CollectHardwareInfoProcessor afterProcess starting...", command.Sn) + defer logger.Info("CollectHardwareInfoProcessor afterProcess ending...", command.Sn) + //empty +} diff --git a/bmp-scheduler/processor/CreateVNIProcessor.go b/bmp-scheduler/processor/CreateVNIProcessor.go new file mode 100644 index 0000000..a4ab393 --- /dev/null +++ b/bmp-scheduler/processor/CreateVNIProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type CreateVNIProcessor struct { + BaseProcessor +} + +func NewCreateVNIProcessor() CreateVNIProcessor { + b := CreateVNIProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b CreateVNIProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b CreateVNIProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b CreateVNIProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b CreateVNIProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/CreateVRFBalanceProcessor.go b/bmp-scheduler/processor/CreateVRFBalanceProcessor.go new file mode 100644 index 0000000..4942023 --- /dev/null +++ b/bmp-scheduler/processor/CreateVRFBalanceProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type CreateVRFBalanceProcessor struct { + BaseProcessor +} + +func NewCreateVRFBalanceProcessor() CreateVRFBalanceProcessor { + b := CreateVRFBalanceProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b CreateVRFBalanceProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b CreateVRFBalanceProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b CreateVRFBalanceProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b CreateVRFBalanceProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/CreateVRFProcessor.go b/bmp-scheduler/processor/CreateVRFProcessor.go new file mode 100644 index 0000000..233a68c --- /dev/null +++ b/bmp-scheduler/processor/CreateVRFProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type CreateVRFProcessor struct { + BaseProcessor +} + +func NewCreateVRFProcessor() CreateVRFProcessor { + b := CreateVRFProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b CreateVRFProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b CreateVRFProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b CreateVRFProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b CreateVRFProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/CreateVSIInterfaceProcessor.go b/bmp-scheduler/processor/CreateVSIInterfaceProcessor.go new file mode 100644 index 0000000..4e4524e --- /dev/null +++ b/bmp-scheduler/processor/CreateVSIInterfaceProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type CreateVSIInterfaceProcessor struct { + BaseProcessor +} + +func NewCreateVSIInterfaceProcessor() CreateVSIInterfaceProcessor { + b := CreateVSIInterfaceProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b CreateVSIInterfaceProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b CreateVSIInterfaceProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b CreateVSIInterfaceProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b CreateVSIInterfaceProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/CreateVSIProcessor.go b/bmp-scheduler/processor/CreateVSIProcessor.go new file mode 100644 index 0000000..b70a192 --- /dev/null +++ b/bmp-scheduler/processor/CreateVSIProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type CreateVSIProcessor struct { + BaseProcessor +} + +func NewCreateVSIProcessor() CreateVSIProcessor { + b := CreateVSIProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b CreateVSIProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b CreateVSIProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b CreateVSIProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b CreateVSIProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/DHCPConfigAddSubnetProcessor.go b/bmp-scheduler/processor/DHCPConfigAddSubnetProcessor.go new file mode 100644 index 0000000..62f0451 --- /dev/null +++ b/bmp-scheduler/processor/DHCPConfigAddSubnetProcessor.go @@ -0,0 +1,85 @@ +package processor + +import ( + "net" + "strconv" + "time" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + deviceDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/idcLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + "coding.jd.com/aidc-bmp/bmp-scheduler/service/redis" + driverTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type DHCPConfigAddSubnetProcessor struct { + BaseProcessor +} + +func NewDHCPConfigAddSubnetProcessor() DHCPConfigAddSubnetProcessor { + b := DHCPConfigAddSubnetProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} +func (b DHCPConfigAddSubnetProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b DHCPConfigAddSubnetProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b DHCPConfigAddSubnetProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + var _ipv4, _mask, _gateway string + + v, _ := deviceDao.GetBySn(logger, command.Sn) + if v != nil { + _ipv4 = v.PrivateIPv4 + _mask = v.Mask + _gateway = v.Gateway + } + + _, _, err := net.ParseCIDR(_ipv4) + ipv4 := _ipv4 + if err != nil { //如果不是cird地址,先根据掩码转成cird,假如给的地址是这种格式,10.208.14.81 + mask := net.IPMask(net.ParseIP(_mask).To4()) + prefixSize, _ := mask.Size() + ipv4 = _ipv4 + "/" + strconv.Itoa(prefixSize) + } + subnet := util.NetworkIp(ipv4) + msg := driverTypes.DHCPConfigAddSubnet{ + Subnet: subnet, + Sn: command.Sn, + SubnetMask: _mask, + Routes: _gateway, + } + idc, err := idcLogic.GetIdcID(logger) + if err != nil { + logger.Warnf("GetOneIdc error:%s", err.Error()) + panic(ProcessAbortException{Msg: "process DHCPConfigAddSubnetProcessor GetIdcID error"}) + + } + res, err := redis.RedisUtil.SetNX("set_subenet_"+subnet, true, time.Second*60).Result() + logger.Infof("set_subenet_", command.Sn, res, err, util.ObjToJson(msg)) + if res { + if err := rabbitMq.SendToAgent4Topic(idc.IDcID, msg); err != nil { + logger.Warnf("DHCPConfigAddSubnetProcessor.SendToAgent4Topic error, sn:%s, idc_id:%s, msg:%s", command.Sn, idc.IDcID, util.ObjToJson(msg)) + return + } else { + logger.Infof("DHCPConfigAddSubnetProcessor.SendToAgent4Topic success, sn:%s, idc_id:%s, msg:%s", command.Sn, idc.IDcID, util.ObjToJson(msg)) + } + } + + logger.Infof("DHCPConfigAddSubnetProcessor_SendToAgent_Msg: %s, routingkey:%s", util.ObjToJson(msg), idc.IDcID) +} + +func (b DHCPConfigAddSubnetProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //不管是否返回成功,都默认成功,执行下一条指令 + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/DHCPRestartProcessor.go b/bmp-scheduler/processor/DHCPRestartProcessor.go new file mode 100644 index 0000000..79b2d24 --- /dev/null +++ b/bmp-scheduler/processor/DHCPRestartProcessor.go @@ -0,0 +1,57 @@ +package processor + +import ( + "fmt" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + "coding.jd.com/aidc-bmp/bmp-scheduler/service/redis" + driverTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type DHCPRestartProcessor struct { + BaseProcessor +} + +func NewDHCPRestartProcessor() DHCPRestartProcessor { + b := DHCPRestartProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b DHCPRestartProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b DHCPRestartProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b DHCPRestartProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + az, err := redis.GetObjectFromRedis(Constants.DHCP_RESTART_KEY) + if err != nil { + logger.Warn("DHCPRestartProcessor GetObjectFromRedis error:", err.Error()) + } + if az == "" { + panic(ProcessAbortException{Msg: fmt.Sprintf("process DHCPRestart error, az %s is null", az)}) + } + + dhcp := driverTypes.DHCPRestart{ + Sn: command.Sn, + } + if err := rabbitMq.SendToAgent(az, dhcp); err != nil { + logger.Warn("DHCPRestartProcessor SendToAgent error:", command.Sn, err.Error()) + return + } + logger.Infof("DHCPRestartProcessor_SendToAgent_Msg: %s", util.ObjToJson(dhcp)) +} + +func (b DHCPRestartProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/DelDHCPConfigHostProcessor.go b/bmp-scheduler/processor/DelDHCPConfigHostProcessor.go new file mode 100644 index 0000000..daad603 --- /dev/null +++ b/bmp-scheduler/processor/DelDHCPConfigHostProcessor.go @@ -0,0 +1,96 @@ +package processor + +import ( + "time" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + deviceDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/interfaceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/jdBondInterfaceDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + driverTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type DelDHCPConfigHostProcessor struct { + BaseProcessor +} + +func NewDelDHCPConfigHostProcessor() DelDHCPConfigHostProcessor { + b := DelDHCPConfigHostProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b DelDHCPConfigHostProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b DelDHCPConfigHostProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b DelDHCPConfigHostProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + var entity *deviceDao.Device + var err error + entity, err = deviceDao.GetBySn(logger, command.Sn) + + if err != nil || entity == nil { + logger.Warn("DelDHCPConfigHostProcessor GetBySn error:", command.Sn, err.Error()) + } + //if entity == nil { + // panic(ProcessAbortException{Msg: fmt.Sprintf("process DelDHCPConfigHost error, sn %s device not found", command.Sn)}) + //} + //entities, err := interfaceLogic.GetBySn(logger, command.Sn) + //if err != nil { + // logger.Warn("DelDHCPConfigHostProcessor GetBySn sql error:", command.Sn, err.Error()) + //} + //if len(entities) == 0 { + // panic(ProcessAbortException{Msg: fmt.Sprintf("process DelDHCPConfigHost error, sn %s interface not found", command.Sn)}) + //} + //jd_bond_interface, err := jdBondInterfaceLogic.GetBySn(logger, command.Sn) + //if err != nil { + // logger.Warn("DelDHCPConfigHostProcessor GetBySn sql error:", command.Sn, err.Error()) + //} + //if jd_bond_interface != nil { + // + // // delJdBondInterface(logger, jd_bond_interface) + //} + config_host := driverTypes.DelDHCPConfigHost{ + Sn: command.Sn, + Ip: entity.PrivateIPv4, //.PrivateIP, + Mac: entity.Mac1, + } + if err := rabbitMq.SendToAgent4Topic(entity.IDcID, config_host); err != nil { + logger.Warnf("DelDHCPConfigHostProcessor SendToAgent error, routingkey:%s, msg:%s, error:%s", entity.IDcID, util.ObjToJson(config_host), err.Error()) + return + } + logger.Infof("DelDHCPConfigHostProcessor_SendToAgent_Msg:%s, routingkey:%s", util.ObjToJson(config_host), entity.IDcID) + // delInterface(logger, entities) +} + +func (b DelDHCPConfigHostProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} + +func delJdBondInterface(logger *log.Logger, jd_bond_interface *jdBondInterfaceDao.JdBondInterface) { + jd_bond_interface.UpdateTime = time.Now() + jd_bond_interface.IsDel = 1 + if err := jdBondInterfaceDao.UpdateJdBondInterfaceById(logger, jd_bond_interface); err != nil { + logger.Warn("delJdBondInterface sql error:", err.Error()) + } +} + +func delInterface(logger *log.Logger, entities []*interfaceDao.Interface) { + for _, entity := range entities { + entity.UpdateTime = time.Now() + entity.IsDel = 1 + if err := interfaceDao.UpdateInterfaceById(logger, entity); err != nil { + logger.Warn("delInterface sql error:", err.Error()) + } + } +} diff --git a/bmp-scheduler/processor/FormatPartitionsProcessor.go b/bmp-scheduler/processor/FormatPartitionsProcessor.go new file mode 100644 index 0000000..02cf3ae --- /dev/null +++ b/bmp-scheduler/processor/FormatPartitionsProcessor.go @@ -0,0 +1,68 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/instancePartitionDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type FormatPartitionsProcessor struct { + BaseProcessor +} + +func NewFormatPartitionsProcessor() FormatPartitionsProcessor { + b := FormatPartitionsProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b FormatPartitionsProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b FormatPartitionsProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b FormatPartitionsProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + logger.Info("FormatPartitionsProcessor doProcess......", command.Sn) + instancePartitionsEntity, err := instancePartitionDao.GetInstancePartitionsByInstanceId(logger, command.InstanceID) + if instancePartitionsEntity == nil { + logger.Warnf("FormatPartitionsProcessor GetInstancePartitionsByInstanceId error, sn:%s, instance_id:%s, err:%+v", command.Sn, command.InstanceID, err) + } + + formatPartitions := agentTypes.FormatPartitions{ + Sn: command.Sn, + Version: "2.0", + } + ps := []agentTypes.FPartition{} + for _, v := range instancePartitionsEntity { + if v.PartitionType == "data" { //数据盘 + continue + } + ps = append(ps, agentTypes.FPartition{ + Volume: v.InstancePartitionID, + FsType: v.PartitionFsType, + Label: v.PartitionLabel, + IsRoot: v.PartitionType == "root", + }) + } + formatPartitions.Partitions = ps + + if err := rabbitMq.SendToAgent(command.Sn, formatPartitions); err != nil { + logger.Warnf("FormatPartitionsProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(formatPartitions), err.Error()) + return + } + logger.Infof("FormatPartitionsProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(formatPartitions)) + +} + +func (b FormatPartitionsProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/InitNodeProcessor.go b/bmp-scheduler/processor/InitNodeProcessor.go new file mode 100644 index 0000000..4d21ad4 --- /dev/null +++ b/bmp-scheduler/processor/InitNodeProcessor.go @@ -0,0 +1,84 @@ +package processor + +import ( + "fmt" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceHintsDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/imageLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/osLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/types/domain" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type InitNodeProcessor struct { + BaseProcessor +} + +func NewInitNodeProcessor() InitNodeProcessor { + b := InitNodeProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b InitNodeProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b InitNodeProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b InitNodeProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + logger.Info("InitNodeProcessor doProcess......", command.Sn) + instanceEntity, err := instanceDao.GetInstanceByUuid(logger, command.InstanceID) + if instanceEntity == nil { + logger.Warnf("InitNodeProcessor GetInstanceByUuid error, sn:%s, instance_id:%s, err:%+v", command.Sn, command.InstanceID, err) + panic(ProcessAbortException{Msg: fmt.Sprintf("InitNodeProcessor error, instance %s not found", command.InstanceID)}) + } + imageEntity, err := imageLogic.GetByImageId(logger, instanceEntity.ImageID) + if imageEntity == nil { + logger.Warnf("InitNodeProcessor GetByImageId error, instance_id:%s, image_id:%s, err:%+v", command.InstanceID, instanceEntity.ImageID, err) + panic(ProcessAbortException{Msg: fmt.Sprintf("InitNodeProcessor error, image %s not found", instanceEntity.ImageID)}) + } + osEntity, err := osLogic.GetByOsId(logger, imageEntity.OsID) + if osEntity == nil { + logger.Warnf("InitNodeProcessor GetOsByuuid error, instance_id:%s, os_id:%s, err:%+v", command.InstanceID, imageEntity.OsID, err) + panic(ProcessAbortException{Msg: fmt.Sprintf("InitNodeProcessor error, os %s not found", imageEntity.OsID)}) + } + + rootDeviceHintsEntity, err := deviceHintsDao.GetSystemVolumnDeviceHintsBySn(logger, command.Sn) + + initNode := agentTypes.InitNode{ + Sn: command.Sn, + NodeData: agentTypes.NodeData{ + OsType: osEntity.OsType, + OsVersion: osEntity.OsVersion, + }, + } + if rootDeviceHintsEntity == nil { + logger.Warnf("InitNodeProcessor GetSystemVolumnDeviceHintsBySn error, sn:%s, err:%+v", command.Sn, err) + } else { + initNode.NodeData.RootDeviceHints = domain.RootDeviceHints{ + Serial: rootDeviceHintsEntity.Serial, + } + } + + if err := rabbitMq.SendToAgent(command.Sn, initNode); err != nil { + logger.Warnf("InitNodeProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(initNode), err.Error()) + return + } + logger.Infof("InitNodeProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(initNode)) + +} + +func (b InitNodeProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/InitRootDeviceProcessor.go b/bmp-scheduler/processor/InitRootDeviceProcessor.go new file mode 100644 index 0000000..daa005f --- /dev/null +++ b/bmp-scheduler/processor/InitRootDeviceProcessor.go @@ -0,0 +1,74 @@ +package processor + +import ( + "fmt" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/imageLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/osLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type InitRootDeviceProcessor struct { + BaseProcessor +} + +func NewInitRootDeviceProcessor() InitRootDeviceProcessor { + b := InitRootDeviceProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b InitRootDeviceProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b InitRootDeviceProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b InitRootDeviceProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("InitRootDeviceProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process InitRootDevice error, instance %s not found", command.InstanceID)}) + } + image_entity, err := imageLogic.GetByImageId(logger, instance.ImageID) + if err != nil { + logger.Warn("InitRootDeviceProcessor GetByImageId sql error:", instance.ImageID, err.Error()) + } + if image_entity == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process InitRootDevice error, image %s not found", instance.ImageID)}) + } + os_entity, err := osLogic.GetByOsId(logger, image_entity.OsID) + if err != nil { + logger.Warn("InitRootDeviceProcessor GetByOsId sql error:", image_entity.OsID, err.Error()) + } + if os_entity == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process InitRootDevice error, os %s not found", image_entity.OsID)}) + } + + init_root_device := agentTypes.InitRootDevice{ + Sn: command.Sn, + OsType: os_entity.OsType, + OsVersion: os_entity.OsVersion, + } + if err := rabbitMq.SendToAgent(command.Sn, init_root_device); err != nil { + logger.Warnf("InitRootDeviceProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(init_root_device), err.Error()) + return + } + logger.Infof("InitRootDeviceProcessor_SendToAgent_Msg:%s", util.ObjToJson(init_root_device)) +} + +func (b InitRootDeviceProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/InitRootDeviceProcessorV2.go b/bmp-scheduler/processor/InitRootDeviceProcessorV2.go new file mode 100644 index 0000000..df5e0da --- /dev/null +++ b/bmp-scheduler/processor/InitRootDeviceProcessorV2.go @@ -0,0 +1,99 @@ +package processor + +import ( + "fmt" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceHintsDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/imageLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/osLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + domainTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/domain" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + "git.jd.com/cps-golang/ironic-common/ironic/enums/InstanceStatus" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type InitRootDeviceProcessorV2 struct { + BaseProcessor +} + +func NewInitRootDeviceProcessorV2() InitRootDeviceProcessorV2 { + b := InitRootDeviceProcessorV2{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b InitRootDeviceProcessorV2) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b InitRootDeviceProcessorV2) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b InitRootDeviceProcessorV2) doProcess(logger *log.Logger, command *commandDao.Command) { + + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("InitRootDeviceProcessorV2 GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process InitRootDeviceProcessorV2 error, instance %s not found", command.InstanceID)}) + } + image_entity, err := imageLogic.GetByImageId(logger, instance.ImageID) + if err != nil { + logger.Warn("InitRootDeviceProcessorV2 GetByImageId sql error:", instance.ImageID, err.Error()) + } + if image_entity == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process InitRootDeviceProcessorV2 error, image %s not found", instance.ImageID)}) + } + os_entity, err := osLogic.GetByOsId(logger, image_entity.OsID) + if err != nil { + logger.Warn("InitRootDeviceProcessorV2 GetByOsId sql error:", image_entity.OsID, err.Error()) + } + if os_entity == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process InitRootDeviceProcessorV2 error, os %s not found", image_entity.OsID)}) + } + + init_root_device := agentTypes.InitRootDeviceV2{ + Sn: command.Sn, + OsType: os_entity.OsType, + OsVersion: os_entity.OsVersion, + } + + entity, err := deviceHintsDao.GetSystemVolumnDeviceHintsBySn(logger, command.Sn) + if err != nil { + logger.Warn("InitRootDeviceProcessorV2.GetSystemVolumnDeviceHintsBySn error:", command.Sn, err.Error()) + } + if instance.Status != InstanceStatus.CREATING && entity != nil { + rootDeviceHints := domainTypes.RootDeviceHints{ + Size: entity.Size, + Rotational: util.Int82Bool(entity.Rotational), + Wwn: entity.Wwn, + Name: entity.Name, + WwnVendorExtension: entity.WwnVendorExtension, + WwnWithExtension: entity.WwnWithExtension, + Model: entity.Model, + Serial: entity.Serial, + Vendor: entity.Vendor, + Hctl: entity.Hctl, + ByPath: entity.ByPath, + } + init_root_device.RootDeviceHints = rootDeviceHints + } + + if err := rabbitMq.SendToAgent(command.Sn, init_root_device); err != nil { + logger.Warnf("InitRootDeviceProcessorV2 SendToAgent error, sn:%s,msg:%s, error:%s", command.Sn, util.ObjToJson(init_root_device), err.Error()) + return + } + logger.Infof("InitRootDeviceProcessorV2_SendToAgent_Msg:%s", util.ObjToJson(init_root_device)) +} + +func (b InitRootDeviceProcessorV2) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/MakePartitionsProcessor.go b/bmp-scheduler/processor/MakePartitionsProcessor.go new file mode 100644 index 0000000..88e50db --- /dev/null +++ b/bmp-scheduler/processor/MakePartitionsProcessor.go @@ -0,0 +1,226 @@ +package processor + +import ( + "fmt" + "strings" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceHintsDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/imageDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/instancePartitionDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/osDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + domainTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/domain" + util "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +const ( + BOOT = "boot" + ROOT = "root" + SYSTEM = "system" + DATA = "data" +) + +type MakePartitionsProcessor struct { + BaseProcessor +} + +func NewMakePartitionsProcessor() MakePartitionsProcessor { + b := MakePartitionsProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +type DiskHintsCallBackInfo struct { + RootDeviceHints domainTypes.RootDeviceHints `json:"root_device_hints"` +} + +func (b MakePartitionsProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b MakePartitionsProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b MakePartitionsProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + fmt.Println(command.InstanceID) + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("MakePartitionsProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process MakePartitions error, instance %s not found", command.InstanceID)}) + } + image, _ := imageDao.GetImageByUuid(logger, instance.ImageID) + os, _ := osDao.GetOsByUuid(logger, image.OsID) + fmt.Println(os, os.OsType, os.OsVersion) + list, _ := instancePartitionDao.GetAllInstancePartition(logger, map[string]interface{}{ + "instance_id": command.InstanceID, + "image_id": instance.ImageID, + "partition_type.in": []string{"root", "boot", "system"}, + "is_del": 0, + }) + + make_partition := agentTypes.MakePartitions{ + Sn: command.Sn, + Version: "2.0", + AutoCreateEfi: true, + AutoCreateBiosGrub: true, + } + ps := []agentTypes.MPartition{} + for _, partition := range list { + + m := agentTypes.MPartition{ + ID: partition.InstancePartitionID, + PartType: partition.PartitionType, + FsType: partition.PartitionFsType, + Number: partition.Number, + Size: partition.PartitionSize, + } + + ps = append(ps, m) + } + make_partition.Disks = []agentTypes.Disk{ + { + IsRootDevice: true, + DiskLabel: "gpt", + Partitions: ps, + KeepData: false, + }, + } + entity, err := deviceHintsDao.GetSystemVolumnDeviceHintsBySn(logger, command.Sn) + if err != nil { + logger.Warn("MakePartitionsProcessor.GetSystemVolumnDeviceHintsBySn error:", command.Sn, err.Error()) + } + + if instance.Status != "creating" && entity != nil { + rootDeviceHints := domainTypes.RootDeviceHints{ + // Size: entity.Size, + // Rotational: util.Int82Bool(entity.Rotational), + // Wwn: entity.Wwn, + // Name: entity.Name, + // WwnVendorExtension: entity.WwnVendorExtension, + // WwnWithExtension: entity.WwnWithExtension, + // Model: entity.Model, + Serial: entity.Serial, + // Vendor: entity.Vendor, + // Hctl: entity.Hctl, + // ByPath: entity.ByPath, + } + make_partition.Disks[0].DiskHints = &rootDeviceHints + } else if instance.Status == "reinstalling" { + logger.Warnf("rootDeviceHints deal error, sn:%s", command.Sn) + } + + make_partition.BootMode = instance.BootMode //以实例的bootmode为准 + if strings.ToUpper(make_partition.BootMode) == "Legacy/BIOS" { //文案转换 + make_partition.BootMode = "bios" + } else if strings.ToUpper(make_partition.BootMode) == "UEFI" { + make_partition.BootMode = "uefi" + } else { //bios兜底 + make_partition.BootMode = "bios" + } + + if err := rabbitMq.SendToAgent(command.Sn, make_partition); err != nil { + logger.Warnf("MakePartitionsProcessor SendToAgent error, sn:%s, msg:%s, error:%s", command.Sn, util.ObjToJson(make_partition), err.Error()) + return + } + logger.Infof("MakePartitionsProcessor_SendToAgent_Msg success, sn:%s, msg:%s", command.Sn, util.ObjToJson(make_partition)) + /*以下是基于重装系统的,需要存储hits + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("MakePartitionsProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process MakePartitions error, instance %s not found", command.InstanceID)}) + } + image_entity, err := imageLogic.GetByImageId(logger, instance.ImageID) + if err != nil { + logger.Warn("MakePartitionsProcessor GetByImageId sql error:", instance.ImageID, err.Error()) + } + if image_entity == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process MakePartitions error, image %s not found", instance.ImageID)}) + } + os_entity, err := osLogic.GetByOsId(logger, image_entity.OsID) + if err != nil { + logger.Warn("MakePartitionsProcessor GetByOsId sql error:", image_entity.OsID, err.Error()) + } + device_entity, err := deviceLogic.GetById(logger, instance.DeviceID) + if err != nil { + logger.Warn("MakePartitionsProcessor GetById sql error:", instance.DeviceID, err.Error()) + } + if device_entity == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process MakePartitions error, device %s not found", fmt.Sprint(instance.DeviceID))}) + } + partitions_entity, err := partitionLogic.GetByDeviceTypeAndImageId(logger, device_entity.DeviceTypeID, instance.ImageID) + if err != nil { + logger.Warn("MakePartitionsProcessor GetByDeviceTypeAndImageId sql error:", device_entity.DeviceTypeID, instance.ImageID, err.Error()) + } + if len(partitions_entity) == 0 { + sendDefaultMakePartitionsCommand(logger, command) + return + } + + make_partition := mergePartitions(logger, command, os_entity, instance, partitions_entity, instance.ImageID) + make_partition.KeepData = false + + instance_extra := loadInstanceExtra(logger, command.InstanceID) + if instance_extra != nil && instance.Status == InstanceStatus.REINSTALLING { + if instance_extra.KeepData { + make_partition.KeepData = true + } + } + + entity, err := rootDeviceHintsDao.GetRootDeviceHintsBySn(logger, command.Sn) + if err != nil { + logger.Warn("MakePartitionsProcessor.GetRootDeviceHintsBySn error:", command.Sn, err.Error()) + } + + if instance.Status != InstanceStatus.CREATING && entity != nil { + rootDeviceHints := domainTypes.RootDeviceHints{ + Size: entity.Size, + Rotational: util.Int82Bool(entity.Rotational), + Wwn: entity.Wwn, + Name: entity.Name, + WwnVendorExtension: entity.WwnVendorExtension, + WwnWithExtension: entity.WwnWithExtension, + Model: entity.Model, + Serial: entity.Serial, + Vendor: entity.Vendor, + Hctl: entity.Hctl, + ByPath: entity.ByPath, + } + make_partition.RootDeviceHints = &rootDeviceHints + } + + if err := rabbitMq.SendToAgent(command.Sn, make_partition); err != nil { + logger.Warnf("MakePartitionsProcessor SendToAgent error, sn:%s, msg:%s, error:%s", command.Sn, util.ObjToJson(make_partition), err.Error()) + return + } + logger.Infof("MakePartitionsProcessor_SendToAgent_Msg success, sn:%s, msg:%s", command.Sn, util.ObjToJson(make_partition)) + */ +} + +func (b MakePartitionsProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} + +func sendDefaultMakePartitionsCommand(logger *log.Logger, command *commandDao.Command) { + make_partition := agentTypes.MakePartitions{ + Sn: command.Sn, + } + if err := rabbitMq.SendToAgent(command.Sn, make_partition); err != nil { + logger.Warnf("MakePartitionsProcessor sendDefaultCommand error, msg:%s, error:%s", util.ObjToJson(make_partition), err.Error()) + return + } + +} diff --git a/bmp-scheduler/processor/MakeRaidProcessor.go b/bmp-scheduler/processor/MakeRaidProcessor.go new file mode 100644 index 0000000..4328dc5 --- /dev/null +++ b/bmp-scheduler/processor/MakeRaidProcessor.go @@ -0,0 +1,221 @@ +package processor + +import ( + "encoding/json" + "fmt" + "strconv" + "strings" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceHintsDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/diskDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/rInstanceVolumeRaidDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/volumeDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/raidLogic" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type MakeRaidProcessor struct { + BaseProcessor +} + +func NewMakeRaidProcessor() MakeRaidProcessor { + b := MakeRaidProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b MakeRaidProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b MakeRaidProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + logger.Info("MakeRaidProcessor Callback starting...", msg.Sn) + defer logger.Info("MakeRaidProcessor Callback ending...", msg.Sn) + if strings.ToUpper(msg.Status) == OK { + logger.Infof("MakeRaidProcessor callback content is:%s", util.ObjToJson(msg.Data)) + //以后再优化成更优雅的方法 + b, err := json.Marshal(msg.Data) + if err != nil { + logger.Warn("MakeRaidProcessor Callback unmarshal error:", msg.Sn, err.Error()) + } else { + saveDeviceHints(logger, msg.Sn, b) + } + } + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b MakeRaidProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + logger.Info("MakeRaidProcessor doProcess......", command.Sn) + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("MakeRaidProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process MakeRaid error, instance %s not found", command.InstanceID)}) + } + + sys_raid, err := raidLogic.GetByRaidId(logger, instance.SystemVolumeRaidID) + if err != nil { + logger.Warn("MakeRaidProcessor GetByRaidId sql error:", instance.SystemVolumeRaidID, err.Error()) + } + if sys_raid == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process MakeRaid error, sys_raid %s not found", instance.SystemVolumeRaidID)}) + } + + //data_raid, err := raidLogic.GetByRaidId(logger, instance.DataVolumeRaidID) + //if err != nil { + // logger.Warn("MakeRaidProcessor GetByRaidId sql error:", instance.DataVolumeRaidID, err.Error()) + //} else { + // if command.Sn != "CFC7HP2" { //TODO trick逻辑,记得放开。因为机型不匹配,此机器的数据盘为nvme无法做raid + // raid_levels = append(raid_levels, data_raid.Name) + // } + // + //}数据盘暂时不做raid + device, err := deviceLogic.GetById(logger, instance.DeviceID) + if err != nil { + logger.Warn("MakeRaidProcessor GetById sql error:", instance.DeviceID, err.Error()) + } + if device == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process MakeRaid error, device %s not found", fmt.Sprint(instance.DeviceID))}) + } + + var systemVolumeItem agentTypes.Volume + var dataVolumeItem = []agentTypes.Volume{} + volumeEntities, err := rInstanceVolumeRaidDao.GetRInstanceVolumeRaids(logger, instance.InstanceID) + if err != nil { + logger.Warnf("MakeRaidProcessor.GetRInstanceVolumeRaids error, instance_id:%s, err:%s", instance.InstanceID, err.Error()) + } + for _, volumeEntity := range volumeEntities { + diskEntities, err := diskDao.GetVolumeDisks(logger, instance.DeviceID, volumeEntity.VolumeID) + if err != nil { + logger.Warnf("MakeRaidProcessor.GetAllRDeviceVolumeDisks error, device_id:%s, volume_id:%s, error:%s", instance.DeviceID, volumeEntity.VolumeID, err.Error()) + } + if volumeEntity.VolumeType == "system" { + systemVolumeItem = agentTypes.Volume{ + VolumeID: volumeEntity.VolumeID, + IsRootDevice: true, + RaidLevel: volumeEntity.RaidName, + PhysicalDisks: getPhysicalDisk(diskEntities), + } + } else { + dataVolumeItem = append(dataVolumeItem, agentTypes.Volume{ + VolumeID: volumeEntity.VolumeID, + IsDataDevice: true, + RaidLevel: volumeEntity.RaidName, + PhysicalDisks: getPhysicalDisk(diskEntities), + }) + } + } + + volumes := append([]agentTypes.Volume{systemVolumeItem}, dataVolumeItem...) + + makeRaidData := agentTypes.MakeRaidData{ + RaidDriver: device.RaidDriver, + AdapterID: device.AdapterID, + Volumes: volumes, + } + + make_data_raid := agentTypes.MakeRaid{ + Sn: command.Sn, + MakeRaidDatas: []agentTypes.MakeRaidData{makeRaidData}, + } + if err := rabbitMq.SendToAgent(command.Sn, make_data_raid); err != nil { + logger.Warnf("MakeRaidProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(make_data_raid), err.Error()) + return + } + logger.Infof("MakeRaidProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(make_data_raid)) + +} + +func getPhysicalDisk(disks []*diskDao.Disk) []agentTypes.PhysicalDisk { + res := []agentTypes.PhysicalDisk{} + for _, v := range disks { + ec, _ := strconv.Atoi(v.Enclosure) + res = append(res, agentTypes.PhysicalDisk{ + Enclosure: ec, + Slot: v.Slot, + }) + } + return res +} + +func (b MakeRaidProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} + +func saveDeviceHints(logger *log.Logger, sn string, content []byte) error { + + originContent := string(content) + logger.Infof("saveDeviceHints sn: %s, origin content:%s", sn, originContent) + //controllers.disks[0]的struct + + var err error + c := agentTypes.MakeRaidAgentRespData{} + if err := json.Unmarshal(content, &c); err != nil { + logger.Warnf("SaveDiskLocationInfo parse error, sn:%s, content:%s, error:%s", sn, originContent, err.Error()) + return err + } + + if len(c.MakeRaidDatas) > 0 { + for _, v := range c.MakeRaidDatas[0].Volumes { + deviceHintsEntity, _ := deviceHintsDao.GetDeviceHintsBySnAndVolumeId(logger, sn, v.VolumeId) + if deviceHintsEntity == nil { //新建 + entity := &deviceHintsDao.DeviceHints{ + Sn: sn, + VolumeId: v.VolumeId, + Size: v.RootDeviceHints.Size, + Rotational: util.Bool2Int8(v.RootDeviceHints.Rotational), + Wwn: v.RootDeviceHints.Wwn, + Name: v.RootDeviceHints.Name, + WwnVendorExtension: v.RootDeviceHints.WwnVendorExtension, + WwnWithExtension: v.RootDeviceHints.WwnWithExtension, + Model: v.RootDeviceHints.Model, + Serial: v.RootDeviceHints.Serial, + Hctl: v.RootDeviceHints.Hctl, + ByPath: v.RootDeviceHints.ByPath, + Vendor: v.RootDeviceHints.Vendor, + } + volumeEntity, err := volumeDao.GetVolumeById(logger, v.VolumeId) + if err != nil { + logger.Warnf("makeRaidProcessor.Callback.GetVolumeById error, sn:%s, volume_id:%s, error:%s", sn, v.VolumeId, err.Error()) + } + if volumeEntity != nil { + entity.VolumeType = volumeEntity.VolumeType + } + + if _, err := deviceHintsDao.AddDeviceHints(logger, entity); err != nil { + logger.Warnf("makeRaidProcessor.Callback.saveDeviceHints error, sn:%s, error:%s", sn, err.Error()) + } + } else { //更新 + deviceHintsEntity.Size = v.RootDeviceHints.Size + deviceHintsEntity.Rotational = util.Bool2Int8(v.RootDeviceHints.Rotational) + deviceHintsEntity.Wwn = v.RootDeviceHints.Wwn + deviceHintsEntity.Name = v.RootDeviceHints.Name + deviceHintsEntity.WwnVendorExtension = v.RootDeviceHints.WwnVendorExtension + deviceHintsEntity.WwnWithExtension = v.RootDeviceHints.WwnWithExtension + deviceHintsEntity.Model = v.RootDeviceHints.Model + deviceHintsEntity.Serial = v.RootDeviceHints.Serial + deviceHintsEntity.Hctl = v.RootDeviceHints.Hctl + deviceHintsEntity.ByPath = v.RootDeviceHints.ByPath + deviceHintsEntity.Vendor = v.RootDeviceHints.Vendor + if err := deviceHintsDao.UpdateDeviceHintsById(logger, deviceHintsEntity); err != nil { + logger.Warnf("makeRaidProcessor.Callback.UpdateDeviceHintsById error, sn:%s, error:%s", sn, err.Error()) + } + } + + } + } + + return err + +} diff --git a/bmp-scheduler/processor/MountPartitionsProcessor.go b/bmp-scheduler/processor/MountPartitionsProcessor.go new file mode 100644 index 0000000..243a79a --- /dev/null +++ b/bmp-scheduler/processor/MountPartitionsProcessor.go @@ -0,0 +1,99 @@ +package processor + +import ( + "fmt" + "strings" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceHintsDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/instancePartitionDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/types/domain" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type MountPartitionsProcessor struct { + BaseProcessor +} + +func NewMountPartitionsProcessor() MountPartitionsProcessor { + b := MountPartitionsProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b MountPartitionsProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b MountPartitionsProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b MountPartitionsProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + logger.Info("MountPartitionsProcessor doProcess......", command.Sn) + instancePartitionsEntity, err := instancePartitionDao.GetInstancePartitionsByInstanceId(logger, command.InstanceID) + if instancePartitionsEntity == nil { + logger.Warnf("FormatPartitionsProcessor GetInstancePartitionsByInstanceId error, sn:%s, instance_id:%s, err:%+v", command.Sn, command.InstanceID, err) + } + + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("MountPartitionsProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process MountPartitionsProcessor error, instance %s not found", command.InstanceID)}) + } + rootDeviceHintsEntity, err := deviceHintsDao.GetSystemVolumnDeviceHintsBySn(logger, command.Sn) + if err != nil { + logger.Warn("MountPartitionsProcessor.GetSystemVolumnDeviceHintsBySn error:", command.Sn, err.Error()) + } + mountPartitions := agentTypes.MonutPartitions{ + Sn: command.Sn, + Version: "2.0", + AutoMountEfi: false, //bios的时候为false,uefi的时候为true + } + if strings.ToUpper(instance.BootMode) == "UEFI" { + mountPartitions.AutoMountEfi = true + } + + ms := []agentTypes.Mount{} + for _, v := range instancePartitionsEntity { + if v.PartitionType == "data" { //数据盘 + continue + } + m := agentTypes.Mount{ + IsRootDevice: v.PartitionType != "data", + IsDataDevice: v.PartitionType == "data", + Label: v.PartitionLabel, + Mountpoint: v.PartitionMountPoint, + // Options: v.Options, + } + if rootDeviceHintsEntity != nil { + m.DiskHints = &domain.RootDeviceHints{ + // Name: rootDeviceHintsEntity.Name, + Serial: rootDeviceHintsEntity.Serial, + } + } + + ms = append(ms, m) + } + mountPartitions.Mounts = ms + + if err := rabbitMq.SendToAgent(command.Sn, mountPartitions); err != nil { + logger.Warnf("MountPartitionsProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(mountPartitions), err.Error()) + return + } + logger.Infof("MountPartitionsProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(mountPartitions)) + +} + +func (b MountPartitionsProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/PingProcessor.go b/bmp-scheduler/processor/PingProcessor.go new file mode 100644 index 0000000..e47b025 --- /dev/null +++ b/bmp-scheduler/processor/PingProcessor.go @@ -0,0 +1,45 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type PingProcessor struct { + BaseProcessor +} + +func NewPingProcessor() PingProcessor { + b := PingProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b PingProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b PingProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b PingProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + ping := agentTypes.Ping{ + Sn: command.Sn, + } + if err := rabbitMq.SendToAgent(command.Sn, ping); err != nil { + logger.Warn("PingProcessor SendToAgent error:", command.Sn, err.Error()) + return + } + logger.Infof("PingProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(ping)) +} + +func (b PingProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/PowerCycleProcessor.go b/bmp-scheduler/processor/PowerCycleProcessor.go new file mode 100644 index 0000000..fdd42e5 --- /dev/null +++ b/bmp-scheduler/processor/PowerCycleProcessor.go @@ -0,0 +1,75 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + dirverTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + "fmt" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type PowerCycleProcessor struct { + BaseProcessor +} + +func NewPowerCycleProcessor() PowerCycleProcessor { + b := PowerCycleProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b PowerCycleProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b PowerCycleProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b PowerCycleProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + device, err := deviceLogic.GetBySn(logger, command.Sn) + if err != nil { + logger.Warn("PowerCycleProcessor GetById sql error:", command.Sn, err.Error()) + } + if device == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process PowerCycle error,sn %s device not found", command.Sn)}) + } + idc, err := idcDao.GetIdcById(logger, device.IDcID) + if err != nil { + logger.Warn("机房ID不存在", device.IDcID, err.Error()) + return + } + var iloUser, iloPassword string + //如果设备的带外账号,密码没有录入,默认取机房填写的带外账号密码 + if device.IloUser == "" { + iloUser = idc.IloUser + } else { + iloUser = device.IloUser + } + if device.IloPassword == "" { + iloPassword = idc.IloPassword + } else { + iloPassword = device.IloPassword + } + power_cycle := dirverTypes.PowerCycle{ + Sn: command.Sn, + IloIp: device.IloIP, + Username: iloUser, + Password: iloPassword, + } + if err := rabbitMq.SendToAgent(device.IDcID, power_cycle); err != nil { + logger.Warnf("PowerCycleProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(power_cycle), err.Error()) + return + } + logger.Infof("PowerCycleProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(power_cycle)) +} + +func (b PowerCycleProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/PowerOffProcessor.go b/bmp-scheduler/processor/PowerOffProcessor.go new file mode 100644 index 0000000..d0156fc --- /dev/null +++ b/bmp-scheduler/processor/PowerOffProcessor.go @@ -0,0 +1,83 @@ +package processor + +import ( + "fmt" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + deviceDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/idcDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + dirverTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type PowerOffProcessor struct { + BaseProcessor +} + +func NewPowerOffProcessor() PowerOffProcessor { + b := PowerOffProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b PowerOffProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b PowerOffProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b PowerOffProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + var device *deviceDao.Device + var err error + device, err = deviceDao.GetBySn(logger, command.Sn) + if err != nil { + logger.Warn("PowerOffProcessor GetById sql error:", command.Sn, err.Error()) + } + if device == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process PowerOff error,sn %s device not found", command.Sn)}) + } + idc, err := idcDao.GetIdcById(logger, device.IDcID) + if err != nil { + logger.Warn("机房ID不存在", device.Sn, device.IDcID, err.Error()) + } + var iloUser, iloPassword string + //如果设备的带外账号,密码没有录入,默认取机房填写的带外账号密码 + if device.IloUser == "" || device.IloPassword == "" { + if idc == nil { + logger.Warn("设备和机房iloip信息都缺失", device.Sn, device.IDcID) + return + } + } + if device.IloUser == "" { + iloUser = idc.IloUser + } else { + iloUser = device.IloUser + } + if device.IloPassword == "" { + iloPassword = idc.IloPassword + } else { + iloPassword = device.IloPassword + } + power_off := dirverTypes.PowerOff{ + Sn: command.Sn, + IloIp: device.IloIP, + Username: iloUser, + Password: iloPassword, + } + if err := rabbitMq.SendToAgent(device.IDcID, power_off); err != nil { + logger.Warnf("PowerOffProcessor SendToAgent error, routingkey:%s, msg:%s, error:%s", device.IDcID, util.ObjToJson(power_off), err.Error()) + return + } + logger.Infof("PowerOffProcessor_SendToAgent_Msg success, routingkey:%s, msg:%s", device.IDcID, util.ObjToJson(power_off)) +} + +func (b PowerOffProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/PowerOnProcessor.go b/bmp-scheduler/processor/PowerOnProcessor.go new file mode 100644 index 0000000..0b2b048 --- /dev/null +++ b/bmp-scheduler/processor/PowerOnProcessor.go @@ -0,0 +1,75 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + dirverTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + "fmt" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type PowerOnProcessor struct { + BaseProcessor +} + +func NewPowerOnProcessor() PowerOnProcessor { + b := PowerOnProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b PowerOnProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b PowerOnProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b PowerOnProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + device, err := deviceLogic.GetBySn(logger, command.Sn) + if err != nil { + logger.Warn("PowerOnProcessor GetById sql error:", command.Sn, err.Error()) + } + if device == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process PowerOn error,sn %s device not found", command.Sn)}) + } + idc, err := idcDao.GetIdcById(logger, device.IDcID) + if err != nil { + logger.Warn("机房ID不存在", device.IDcID, err.Error()) + return + } + var iloUser, iloPassword string + //如果设备的带外账号,密码没有录入,默认取机房填写的带外账号密码 + if device.IloUser == "" { + iloUser = idc.IloUser + } else { + iloUser = device.IloUser + } + if device.IloPassword == "" { + iloPassword = idc.IloPassword + } else { + iloPassword = device.IloPassword + } + power_on := dirverTypes.PowerOn{ + Sn: command.Sn, + IloIp: device.IloIP, + Username: iloUser, + Password: iloPassword, + } + if err := rabbitMq.SendToAgent(device.IDcID, power_on); err != nil { + logger.Warnf("PowerOnProcessor SendToAgent error, msg: %s, error: %s", util.ObjToJson(power_on), err.Error()) + return + } + logger.Infof("PowerOnProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(power_on)) +} + +func (b PowerOnProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/PowerResetProcessor.go b/bmp-scheduler/processor/PowerResetProcessor.go new file mode 100644 index 0000000..776ed4d --- /dev/null +++ b/bmp-scheduler/processor/PowerResetProcessor.go @@ -0,0 +1,75 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + dirverTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + "fmt" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type PowerResetProcessor struct { + BaseProcessor +} + +func NewPowerResetProcessor() PowerResetProcessor { + b := PowerResetProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b PowerResetProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b PowerResetProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b PowerResetProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + device, err := deviceLogic.GetBySn(logger, command.Sn) + if err != nil { + logger.Warn("PowerResetProcessor GetById sql error:", command.Sn, err.Error()) + } + if device == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process PowerReset error,sn %s device not found", command.Sn)}) + } + idc, err := idcDao.GetIdcById(logger, device.IDcID) + if err != nil { + logger.Warn("机房ID不存在", device.IDcID, err.Error()) + return + } + var iloUser, iloPassword string + //如果设备的带外账号,密码没有录入,默认取机房填写的带外账号密码 + if device.IloUser == "" { + iloUser = idc.IloUser + } else { + iloUser = device.IloUser + } + if device.IloPassword == "" { + iloPassword = idc.IloPassword + } else { + iloPassword = device.IloPassword + } + power_reset := dirverTypes.PowerReset{ + Sn: command.Sn, + IloIp: device.IloIP, + Username: iloUser, + Password: iloPassword, + } + if err := rabbitMq.SendToAgent(device.IDcID, power_reset); err != nil { + logger.Warnf("PowerResetProcessor SendToAgent error, msg: %s, error:%s", util.ObjToJson(power_reset), err.Error()) + return + } + logger.Infof("PowerResetProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(power_reset)) +} + +func (b PowerResetProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/Qcow2MakePartitionsProcessor.go b/bmp-scheduler/processor/Qcow2MakePartitionsProcessor.go new file mode 100644 index 0000000..eb4d174 --- /dev/null +++ b/bmp-scheduler/processor/Qcow2MakePartitionsProcessor.go @@ -0,0 +1,127 @@ +package processor + +import ( + "fmt" + "strings" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/imageLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/osLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/partitionLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + domainTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/domain" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + "git.jd.com/cps-golang/ironic-common/ironic/enums/InstanceStatus" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type Qcow2MakePartitionsProcessor struct { + BaseProcessor +} + +func NewQcow2MakePartitionsProcessor() Qcow2MakePartitionsProcessor { + b := Qcow2MakePartitionsProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b Qcow2MakePartitionsProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b Qcow2MakePartitionsProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b Qcow2MakePartitionsProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("Qcow2MakePartitionsProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process Qcow2MakePartitions error, instance %s not found", command.InstanceID)}) + } + image_entity, err := imageLogic.GetByImageId(logger, instance.ImageID) + if err != nil { + logger.Warn("Qcow2MakePartitionsProcessor GetByImageId sql error:", instance.ImageID, err.Error()) + } + if image_entity == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process Qcow2MakePartitions error, image %s not found", instance.ImageID)}) + } + os_entity, err := osLogic.GetByOsId(logger, image_entity.OsID) + if err != nil { + logger.Warn("Qcow2MakePartitionsProcessor GetByOsId sql error:", image_entity.OsID, err.Error()) + } + device_entity, err := deviceLogic.GetById(logger, instance.DeviceID) + if err != nil { + logger.Warn("Qcow2MakePartitionsProcessor GetById sql error:", instance.DeviceID, err.Error()) + } + if device_entity == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process Qcow2MakePartitions error, device %s not found", fmt.Sprint(instance.DeviceID))}) + } + partitions_entity, err := partitionLogic.GetByDeviceTypeAndImageId(logger, device_entity.DeviceTypeID, instance.ImageID) + if err != nil { + logger.Warn("Qcow2MakePartitionsProcessor GetByDeviceTypeAndImageId sql error:", device_entity.DeviceTypeID, instance.ImageID, err.Error()) + } + if len(partitions_entity) == 0 { + sendDefaultQcow2MakePartitionsCommand(logger, command) + return + } + make_partition := agentTypes.Qcow2MakePartitions{ + Sn: command.Sn, + OsType: os_entity.OsType, + OsVersion: os_entity.OsVersion, + } + + make_partition.SystemPartitions = []domainTypes.Partition{} + make_partition.DataPartitions = []domainTypes.Partition{} + for _, partition := range partitions_entity { + make_partition.DataDiskLabel = partition.DataDiskLabel + p := domainTypes.Partition{ + Size: partition.PartitionSize, + FsType: partition.PartitionFsType, + MountPoint: partition.PartitionMountPoint, + Label: partition.PartitionLabel, + } + switch strings.ToLower(partition.PartitionType) { + case SYSTEM: + make_partition.SystemPartitions = append(make_partition.SystemPartitions, p) + case DATA: + make_partition.DataPartitions = append(make_partition.DataPartitions, p) + } + } + make_partition.KeepData = false + instance_extra := loadInstanceExtra(logger, command.InstanceID) + if instance_extra != nil && instance.Status == InstanceStatus.REINSTALLING { + if instance_extra.KeepData { + make_partition.KeepData = true + } + } + if err := rabbitMq.SendToAgent(command.Sn, make_partition); err != nil { + logger.Warn("Qcow2MakePartitionsProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(make_partition), err.Error()) + return + } + logger.Infof("Qcow2MakePartitionsProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(make_partition)) + +} + +func (b Qcow2MakePartitionsProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} + +func sendDefaultQcow2MakePartitionsCommand(logger *log.Logger, command *commandDao.Command) { + make_partition := agentTypes.Qcow2MakePartitions{ + Sn: command.Sn, + } + if err := rabbitMq.SendToAgent(command.Sn, make_partition); err != nil { + logger.Warnf("Qcow2MakePartitionsProcessor sendDefaultCommand error, msg:%s, error:%s", util.ObjToJson(make_partition), err.Error()) + return + } + +} diff --git a/bmp-scheduler/processor/SDNAddAliasIPProcessor.go b/bmp-scheduler/processor/SDNAddAliasIPProcessor.go new file mode 100644 index 0000000..59ffe16 --- /dev/null +++ b/bmp-scheduler/processor/SDNAddAliasIPProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SDNAddAliasIPProcessor struct { + BaseProcessor +} + +func NewSDNAddAliasIPProcessor() SDNAddAliasIPProcessor { + b := SDNAddAliasIPProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SDNAddAliasIPProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SDNAddAliasIPProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SDNAddAliasIPProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b SDNAddAliasIPProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/SDNCleanProcessor.go b/bmp-scheduler/processor/SDNCleanProcessor.go new file mode 100644 index 0000000..ecea23a --- /dev/null +++ b/bmp-scheduler/processor/SDNCleanProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SDNCleanProcessor struct { + BaseProcessor +} + +func NewSDNCleanProcessor() SDNCleanProcessor { + b := SDNCleanProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SDNCleanProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SDNCleanProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SDNCleanProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b SDNCleanProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/SDNDeleteAliasIPProcessor.go b/bmp-scheduler/processor/SDNDeleteAliasIPProcessor.go new file mode 100644 index 0000000..7c6c41c --- /dev/null +++ b/bmp-scheduler/processor/SDNDeleteAliasIPProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SDNDeleteAliasIPProcessor struct { + BaseProcessor +} + +func NewSDNDeleteAliasIPProcessor() SDNDeleteAliasIPProcessor { + b := SDNDeleteAliasIPProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SDNDeleteAliasIPProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SDNDeleteAliasIPProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SDNDeleteAliasIPProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b SDNDeleteAliasIPProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/SDNEipBindingProcessor.go b/bmp-scheduler/processor/SDNEipBindingProcessor.go new file mode 100644 index 0000000..18fb34a --- /dev/null +++ b/bmp-scheduler/processor/SDNEipBindingProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SDNEipBindingProcessor struct { + BaseProcessor +} + +func NewSDNEipBindingProcessor() SDNEipBindingProcessor { + b := SDNEipBindingProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SDNEipBindingProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SDNEipBindingProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SDNEipBindingProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b SDNEipBindingProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/SDNEipUnBindingProcessor.go b/bmp-scheduler/processor/SDNEipUnBindingProcessor.go new file mode 100644 index 0000000..e14c316 --- /dev/null +++ b/bmp-scheduler/processor/SDNEipUnBindingProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SDNEipUnBindingProcessor struct { + BaseProcessor +} + +func NewSDNEipUnBindingProcessor() SDNEipUnBindingProcessor { + b := SDNEipUnBindingProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SDNEipUnBindingProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SDNEipUnBindingProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SDNEipUnBindingProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b SDNEipUnBindingProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/SDNRegisterProcessor.go b/bmp-scheduler/processor/SDNRegisterProcessor.go new file mode 100644 index 0000000..67bcd24 --- /dev/null +++ b/bmp-scheduler/processor/SDNRegisterProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SDNRegisterProcessor struct { + BaseProcessor +} + +func NewSDNRegisterProcessor() SDNRegisterProcessor { + b := SDNRegisterProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SDNRegisterProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SDNRegisterProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SDNRegisterProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b SDNRegisterProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/SDNSetNetworkProcessor.go b/bmp-scheduler/processor/SDNSetNetworkProcessor.go new file mode 100644 index 0000000..4d1a519 --- /dev/null +++ b/bmp-scheduler/processor/SDNSetNetworkProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SDNSetNetworkProcessor struct { + BaseProcessor +} + +func NewSDNSetNetworkProcessor() SDNSetNetworkProcessor { + b := SDNSetNetworkProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SDNSetNetworkProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SDNSetNetworkProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SDNSetNetworkProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b SDNSetNetworkProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/SDNSubnetBindingProcessor.go b/bmp-scheduler/processor/SDNSubnetBindingProcessor.go new file mode 100644 index 0000000..7113d91 --- /dev/null +++ b/bmp-scheduler/processor/SDNSubnetBindingProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SDNSubnetBindingProcessor struct { + BaseProcessor +} + +func NewSDNSubnetBindingProcessor() SDNSubnetBindingProcessor { + b := SDNSubnetBindingProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SDNSubnetBindingProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SDNSubnetBindingProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SDNSubnetBindingProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b SDNSubnetBindingProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/SDNSubnetUnBindingProcessor.go b/bmp-scheduler/processor/SDNSubnetUnBindingProcessor.go new file mode 100644 index 0000000..d2ac73a --- /dev/null +++ b/bmp-scheduler/processor/SDNSubnetUnBindingProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SDNSubnetUnBindingProcessor struct { + BaseProcessor +} + +func NewSDNSubnetUnBindingProcessor() SDNSubnetUnBindingProcessor { + b := SDNSubnetUnBindingProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SDNSubnetUnBindingProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SDNSubnetUnBindingProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SDNSubnetUnBindingProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b SDNSubnetUnBindingProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/SaveConfigToFtpServerProcessor.go b/bmp-scheduler/processor/SaveConfigToFtpServerProcessor.go new file mode 100644 index 0000000..ac978d3 --- /dev/null +++ b/bmp-scheduler/processor/SaveConfigToFtpServerProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SaveConfigToFtpServerProcessor struct { + BaseProcessor +} + +func NewSaveConfigToFtpServerProcessor() SaveConfigToFtpServerProcessor { + b := SaveConfigToFtpServerProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SaveConfigToFtpServerProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SaveConfigToFtpServerProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SaveConfigToFtpServerProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b SaveConfigToFtpServerProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/SaveSwitchConfigProcessor.go b/bmp-scheduler/processor/SaveSwitchConfigProcessor.go new file mode 100644 index 0000000..aef94a8 --- /dev/null +++ b/bmp-scheduler/processor/SaveSwitchConfigProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SaveSwitchConfigProcessor struct { + BaseProcessor +} + +func NewSaveSwitchConfigProcessor() SaveSwitchConfigProcessor { + b := SaveSwitchConfigProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SaveSwitchConfigProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SaveSwitchConfigProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SaveSwitchConfigProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b SaveSwitchConfigProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/SetBandwidthProcessor.go b/bmp-scheduler/processor/SetBandwidthProcessor.go new file mode 100644 index 0000000..91e105d --- /dev/null +++ b/bmp-scheduler/processor/SetBandwidthProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SetBandwidthProcessor struct { + BaseProcessor +} + +func NewSetBandwidthProcessor() SetBandwidthProcessor { + b := SetBandwidthProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetBandwidthProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetBandwidthProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetBandwidthProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b SetBandwidthProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/SetBondProcessor.go b/bmp-scheduler/processor/SetBondProcessor.go new file mode 100644 index 0000000..79fed9a --- /dev/null +++ b/bmp-scheduler/processor/SetBondProcessor.go @@ -0,0 +1,106 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + deviceDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/interfaceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/jdSwitchDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/interfaceLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + "fmt" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" + beego "github.com/beego/beego/v2/server/web" +) + +type SetBondProcessor struct { + BaseProcessor +} + +func NewSetBondProcessor() SetBondProcessor { + b := SetBondProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetBondProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetBondProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetBondProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("SetBondProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process SetBondProcessor error, instance %s not found", command.InstanceID)}) + } + + device, err := deviceLogic.GetById(logger, instance.DeviceID) + if err != nil { + logger.Warn("SetBondProcessor GetById sql error:", instance.DeviceID, err.Error()) + } + if device == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process SetBondProcessor error, device %s not found", fmt.Sprint(instance.DeviceID))}) + } + + interfaces, err := interfaceLogic.GetBySn(logger, command.Sn) + if err != nil || len(interfaces) < 2 { + logger.Warn("SetBondProcessor GetBySn sql error:", command.Sn, err.Error()) + } + + /*if strings.EqualFold(instance.NetworkType, NetworkType.RETAIL) { + setBondOfRetail(logger, command, instance, device, interfaces) + }*/ + +} + +func setBondOfRetail(logger *log.Logger, command *commandDao.Command, instance *instanceDao.Instance, device *deviceDao.Device, interfaces []*interfaceDao.Interface) { + switch_ip := interfaces[0].SwitchIP + jd_switch, err := jdSwitchDao.GetBySwitchIp(logger, switch_ip) + if err != nil { + logger.Warnf("SetBondProcessor.setBondOfRetail.GetBySwitchIp error, switch_ip:%s, error:%s", switch_ip, err.Error()) + panic("process SetBond is error, switchIp %s JdSwitchEntity not found") + } + primary_interface := interfaces[0] + second_interface := interfaces[1] + + nameservers, _ := beego.AppConfig.Strings("sdn.configs.nameservers") + if len(nameservers) == 0 { + nameservers = []string{"10.10.10.10"} + } + + set_bond := agentTypes.SetBond{ + Sn: command.Sn, + PrimaryInterfaceName: primary_interface.InterfaceName, + PrimaryMacAddr: primary_interface.Mac, + SecondaryInterfaceName: second_interface.InterfaceName, + SecondaryMacAddr: second_interface.Mac, + IpAddr: "instance.PrivateIP", + Netmask: jd_switch.Mask, + Gateway: jd_switch.Gateway, + Nameservers: nameservers, + Mode: "4", + } + + if err := rabbitMq.SendToAgent(command.Sn, set_bond); err != nil { + logger.Warnf("SetBondProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(set_bond), err.Error()) + return + } + logger.Infof("SetBondProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(set_bond)) + +} + +func (b SetBondProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + // b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/SetCloudinitConfProcessor.go b/bmp-scheduler/processor/SetCloudinitConfProcessor.go new file mode 100644 index 0000000..83778b4 --- /dev/null +++ b/bmp-scheduler/processor/SetCloudinitConfProcessor.go @@ -0,0 +1,58 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/rInstanceSshkeyDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SetCloudinitConfProcessor struct { + BaseProcessor +} + +func NewSetCloudinitConfProcessor() SetCloudinitConfProcessor { + b := SetCloudinitConfProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetCloudinitConfProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetCloudinitConfProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetCloudinitConfProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + logger.Info("SetCloudinitConfProcessor doProcess......", command.Sn) + instanceSshkeyList, _ := rInstanceSshkeyDao.GetAllrInstanceSshkey(logger, map[string]interface{}{ + "instance_id": command.InstanceID, + "is_del": 0, + }) + sshPwauth := "yes" + if len(instanceSshkeyList) != 0 { //如果使用了ssh登录方式,那么就将密码登录禁用 + sshPwauth = "no" + } + setCloudinitConf := agentTypes.SetCloudinitConf{ + Sn: command.Sn, + Version: "2.0", + SshPwauth: sshPwauth, // //yes:启用密码登陆 //no禁用密码登陆 + } + if err := rabbitMq.SendToAgent(command.Sn, setCloudinitConf); err != nil { + logger.Warnf("SetCloudinitConfProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(setCloudinitConf), err.Error()) + return + } + logger.Infof("SetCloudinitConfProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(setCloudinitConf)) + +} + +func (b SetCloudinitConfProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/SetDISKBootProcessor.go b/bmp-scheduler/processor/SetDISKBootProcessor.go new file mode 100644 index 0000000..b8ab240 --- /dev/null +++ b/bmp-scheduler/processor/SetDISKBootProcessor.go @@ -0,0 +1,76 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/idcDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + driverTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + "fmt" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SetDISKBootProcessor struct { + BaseProcessor +} + +func NewSetDISKBootProcessor() SetDISKBootProcessor { + b := SetDISKBootProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetDISKBootProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetDISKBootProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetDISKBootProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + logger.Info("SetDISKBootProcessor doProcess starting...", command.Sn) + device, err := deviceLogic.GetBySn(logger, command.Sn) + if err != nil { + logger.Warn("SetDISKBootProcessor GetBySn sql error:", command.Sn, err.Error()) + } + if device == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process SetDISKBoot error, sn %s device not found", command.Sn)}) + } + idc, err := idcDao.GetIdcById(logger, device.IDcID) + if err != nil { + logger.Warn("机房ID不存在", device.IDcID, err.Error()) + return + } + var iloUser, iloPassword string + //如果设备的带外账号,密码没有录入,默认取机房填写的带外账号密码 + if device.IloUser == "" { + iloUser = idc.IloUser + } else { + iloUser = device.IloUser + } + if device.IloPassword == "" { + iloPassword = idc.IloPassword + } else { + iloPassword = device.IloPassword + } + set_disk_boot := driverTypes.SetDISKBoot{ + Sn: command.Sn, + IloIp: device.IloIP, + Username: iloUser, + Password: iloPassword, + } + if err := rabbitMq.SendToAgent(device.IDcID, set_disk_boot); err != nil { + logger.Warnf("SetDISKBootProcessor SendToAgent error, msg: %s, error:%s", util.ObjToJson(set_disk_boot), err.Error()) + return + } + logger.Infof("SetDISKBootProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(set_disk_boot)) +} + +func (b SetDISKBootProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/SetHostnameProcessor.go b/bmp-scheduler/processor/SetHostnameProcessor.go new file mode 100644 index 0000000..bb5a335 --- /dev/null +++ b/bmp-scheduler/processor/SetHostnameProcessor.go @@ -0,0 +1,57 @@ +package processor + +import ( + "fmt" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SetHostnameProcessor struct { + BaseProcessor +} + +func NewSetHostnameProcessor() SetHostnameProcessor { + b := SetHostnameProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetHostnameProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetHostnameProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetHostnameProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("SetHostnameProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process SetHostname error, instance %s not found", command.InstanceID)}) + } + + set_hostname := agentTypes.SetHostname{ + Sn: command.Sn, + Hostname: instance.Hostname, + } + if err := rabbitMq.SendToAgent(command.Sn, set_hostname); err != nil { + logger.Warnf("SetHostnameProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(set_hostname), err.Error()) + return + } + logger.Infof("SetHostnameProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(set_hostname)) +} + +func (b SetHostnameProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/SetKeypairsProcessor.go b/bmp-scheduler/processor/SetKeypairsProcessor.go new file mode 100644 index 0000000..532eebc --- /dev/null +++ b/bmp-scheduler/processor/SetKeypairsProcessor.go @@ -0,0 +1,68 @@ +package processor + +import ( + "fmt" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SetKeypairsProcessor struct { + BaseProcessor +} + +func NewSetKeypairsProcessor() SetKeypairsProcessor { + b := SetKeypairsProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetKeypairsProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetKeypairsProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetKeypairsProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("SetKeypairsProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process SetKeypairs error, instance %s not found", command.InstanceID)}) + } + //if instance.KeypairID == "" { + // logger.Info("SetKeypairsCommand timeoutPolicy set to skip", command.InstanceID) + // command.TimeoutPolicy = TimeoutPolicy.SKIP + // return + //} + // + //keypair, err := keypairLogic.GetByUuidAndTenant(logger, instance.KeypairID, instance.Tenant) + //if err != nil { + // logger.Warn("SetKeypairsProcessor GetByUuidAndTenant sql error:", instance.KeypairID, instance.Tenant, err.Error()) + //} + //if keypair == nil { + // panic(ProcessAbortException{Msg: fmt.Sprintf("process SetKeypairs error, keypair %s not found", instance.KeypairID)}) + //} + // + //set_keypairs := agentTypes.SetKeypairs{ + // Sn: command.Sn, + // PublicKey: keypair.PublicKey, + //} + //if err := rabbitMq.SendToAgent(command.Sn, set_keypairs); err != nil { + // logger.Warn("SetKeypairsProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(set_keypairs), err.Error()) + // return + //} + //logger.Infof("SetKeypairsProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(set_keypairs)) +} + +func (b SetKeypairsProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) + +} diff --git a/bmp-scheduler/processor/SetMetaDataProcessor.go b/bmp-scheduler/processor/SetMetaDataProcessor.go new file mode 100644 index 0000000..7a89e44 --- /dev/null +++ b/bmp-scheduler/processor/SetMetaDataProcessor.go @@ -0,0 +1,58 @@ +package processor + +import ( + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + "fmt" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SetMetaDataProcessor struct { + BaseProcessor +} + +func NewSetMetaDataProcessor() SetMetaDataProcessor { + b := SetMetaDataProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetMetaDataProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetMetaDataProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetMetaDataProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + logger.Info("SetMetaDataProcessor doProcess......", command.Sn) + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("SetMetaDataProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process SetMetaData error, instance %s not found", command.InstanceID)}) + } + SetMetaData := agentTypes.SetMetaData{ + Sn: command.Sn, + } + SetMetaData.MetaData.HostName = instance.Hostname + SetMetaData.MetaData.Uuid = instance.InstanceID + + if err := rabbitMq.SendToAgent(command.Sn, SetMetaData); err != nil { + logger.Warnf("SetMetaDataProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(SetMetaData), err.Error()) + return + } + logger.Infof("SetMetaDataProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(SetMetaData)) +} + +func (b SetMetaDataProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/SetNetworkDataProcessor.go b/bmp-scheduler/processor/SetNetworkDataProcessor.go new file mode 100644 index 0000000..e0ded5c --- /dev/null +++ b/bmp-scheduler/processor/SetNetworkDataProcessor.go @@ -0,0 +1,269 @@ +package processor + +import ( + "fmt" + "strings" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceTypeDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SetNetworkDataProcessor struct { + BaseProcessor +} + +func NewSetNetworkDataProcessor() SetNetworkDataProcessor { + b := SetNetworkDataProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetNetworkDataProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetNetworkDataProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetNetworkDataProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + logger.Info("SetNetworkDataProcessor doProcess......", command.Sn) + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("SetNetworkDataProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process MakeRaid error, instance %s not found", command.InstanceID)}) + } + device, err := deviceDao.GetDeviceById(logger, instance.DeviceID) + if err != nil { + logger.Warn("SetNetworkDataProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if device == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process SetNetworkData error, device %s not found", instance.DeviceID)}) + } + + //address := make([]string, 0) + //mask := net.IPMask(net.ParseIP(device.Mask).To4()) + //prefixSize, _ := mask.Size() + //ipv4 := device.PrivateIPv4 + "/" + strconv.Itoa(prefixSize) + //address = append(address, ipv4) + //if device.PrivateIPv6 != "" { + // address = append(address, device.PrivateIPv6) + //} + + //ipv4andv6 := make([]string, 0) + //ipv4andv6 = append(ipv4andv6, device.PrivateIPv4) + //if device.PrivateIPv6 != "" { + // ipv4andv6 = append(ipv4andv6, device.PrivateIPv6) + //} + deviceType, err := deviceTypeDao.GetDeviceTypeById(logger, instance.DeviceTypeID) + if err != nil { + logger.Warn("SetNetworkDataProcessor GetByDeviceTypeId sql error:", command.InstanceID, err.Error()) + } + if deviceType == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process SetNetworkData error, deviceType %s not found", instance.DeviceTypeID)}) + } + SetNetworkData := agentTypes.SetNetworkData{ + Sn: command.Sn, + } + SetNetworkData.NetworkData.Services = append(SetNetworkData.NetworkData.Services, agentTypes.Service{ + Type: "dns", + Address: "114.114.114.114", + }) + SetNetworkData.NetworkData.Services = append(SetNetworkData.NetworkData.Services, agentTypes.Service{ + Type: "dns", + Address: "8.8.8.8", + }) + if deviceType.InterfaceMode == "bond" { //如果是bond模式 + NetWork := agentTypes.NetWork{ + Type: "ipv4", + IPAddress: device.PrivateIPv4, + Netmask: device.Mask, + Link: "bond0", + } + NetWork.Routes = append(NetWork.Routes, agentTypes.Route{ + Netmask: "0.0.0.0", + Network: "0.0.0.0", + Gateway: device.Gateway, + }) + SetNetworkData.NetworkData.Networks = append(SetNetworkData.NetworkData.Networks, NetWork) //ipv4 + if device.PrivateIPv6 != "" { + mask := strings.Split(device.PrivateIPv6, "/") + maskStr := "64" + if len(mask) > 1 { + maskStr = mask[1] + } + NetWork := agentTypes.NetWork{ + Type: "ipv6", + IPAddress: mask[0], + Netmask: maskStr, + Link: "bond0", + } + NetWork.Routes = append(NetWork.Routes, agentTypes.Route{ + Netmask: "::", + Network: "::", + Gateway: device.Gateway6, + }) + SetNetworkData.NetworkData.Networks = append(SetNetworkData.NetworkData.Networks, NetWork) //ipv6 + } + + SetNetworkData.NetworkData.Links = append(SetNetworkData.NetworkData.Links, agentTypes.Link{ + EthernetMacAddress: device.Mac1, + Type: "phy", + ID: "eth0", + Mtu: 1500, + }) + SetNetworkData.NetworkData.Links = append(SetNetworkData.NetworkData.Links, agentTypes.Link{ + EthernetMacAddress: device.Mac2, + Type: "phy", + ID: "eth1", + Mtu: 1500, + }) + SetNetworkData.NetworkData.Links = append(SetNetworkData.NetworkData.Links, agentTypes.Link{ + EthernetMacAddress: device.Mac1, + Type: "bond", + ID: "bond0", + BondLinks: []string{"eth0", "eth1"}, + BondMiimon: 100, + BondMode: "802.3ad", + }) + } else if deviceType.InterfaceMode == "dual" { //双网口不做聚合 + //eth0 + NetWork1 := agentTypes.NetWork{ + Type: "ipv4", + IPAddress: device.PrivateIPv4, + Netmask: device.Mask, + Link: "eth0", + } + NetWork1.Routes = append(NetWork1.Routes, agentTypes.Route{ + Netmask: "0.0.0.0", + Network: "0.0.0.0", + Gateway: device.Gateway, + }) + SetNetworkData.NetworkData.Networks = append(SetNetworkData.NetworkData.Networks, NetWork1) + if device.PrivateIPv6 != "" { + mask := strings.Split(device.PrivateIPv6, "/") + maskStr := "64" + if len(mask) > 1 { + maskStr = mask[1] + } + NetWork := agentTypes.NetWork{ + Type: "ipv6", + IPAddress: mask[0], + Netmask: maskStr, + Link: "eth0", + } + NetWork.Routes = append(NetWork.Routes, agentTypes.Route{ + Netmask: "::", + Network: "::", + Gateway: device.Gateway6, + }) + SetNetworkData.NetworkData.Networks = append(SetNetworkData.NetworkData.Networks, NetWork) //ipv6 + } + //eth1 + NetWork2 := agentTypes.NetWork{ + Type: "ipv4", + IPAddress: device.PrivateEth1IPv4, + Netmask: device.MaskEth1, + Link: "eth1", + } + NetWork2.Routes = append(NetWork2.Routes, agentTypes.Route{ + Netmask: "0.0.0.0", + Network: "0.0.0.0", + Gateway: device.Gateway, + }) + SetNetworkData.NetworkData.Networks = append(SetNetworkData.NetworkData.Networks, NetWork2) //ipv4 + if device.PrivateEth1IPv6 != "" { + mask := strings.Split(device.PrivateEth1IPv6, "/") + maskStr := "64" + if len(mask) > 1 { + maskStr = mask[1] + } + NetWork := agentTypes.NetWork{ + Type: "ipv6", + IPAddress: mask[0], + Netmask: maskStr, + Link: "eth1", + } + NetWork.Routes = append(NetWork.Routes, agentTypes.Route{ + Netmask: "::", + Network: "::", + Gateway: device.Gateway6, + }) + SetNetworkData.NetworkData.Networks = append(SetNetworkData.NetworkData.Networks, NetWork) //ipv6 + } + + SetNetworkData.NetworkData.Links = append(SetNetworkData.NetworkData.Links, + agentTypes.Link{ + EthernetMacAddress: device.Mac1, + Type: "phy", + ID: "eth0", + Mtu: 1500, + }, agentTypes.Link{ + EthernetMacAddress: device.Mac2, + Type: "phy", + ID: "eth1", + Mtu: 1500, + }) + } else { //如果是单网口,只需要eth0即可 + NetWork := agentTypes.NetWork{ + Type: "ipv4", + IPAddress: device.PrivateIPv4, + Netmask: device.Mask, + Link: "eth0", + } + NetWork.Routes = append(NetWork.Routes, agentTypes.Route{ + Netmask: "0.0.0.0", + Network: "0.0.0.0", + Gateway: device.Gateway, + }) + SetNetworkData.NetworkData.Networks = append(SetNetworkData.NetworkData.Networks, NetWork) //ipv4 + if device.PrivateIPv6 != "" { + mask := strings.Split(device.PrivateIPv6, "/") + maskStr := "64" + if len(mask) > 1 { + maskStr = mask[1] + } + NetWork := agentTypes.NetWork{ + Type: "ipv6", + IPAddress: mask[0], + Netmask: maskStr, + Link: "eth0", + } + NetWork.Routes = append(NetWork.Routes, agentTypes.Route{ + Netmask: "::", + Network: "::", + Gateway: device.Gateway6, + }) + SetNetworkData.NetworkData.Networks = append(SetNetworkData.NetworkData.Networks, NetWork) //ipv6 + } + + SetNetworkData.NetworkData.Links = append(SetNetworkData.NetworkData.Links, agentTypes.Link{ + EthernetMacAddress: device.Mac1, + Type: "phy", + ID: "eth0", + Mtu: 1500, + }) + } + + if err := rabbitMq.SendToAgent(command.Sn, SetNetworkData); err != nil { + logger.Warnf("SetNetworkDataProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(SetNetworkData), err.Error()) + return + } + logger.Infof("SetNetworkDataProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(SetNetworkData)) + +} + +func (b SetNetworkDataProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/SetNetworkProcessor.go b/bmp-scheduler/processor/SetNetworkProcessor.go new file mode 100644 index 0000000..e8eea98 --- /dev/null +++ b/bmp-scheduler/processor/SetNetworkProcessor.go @@ -0,0 +1,99 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + deviceDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + "fmt" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" + beego "github.com/beego/beego/v2/server/web" +) + +type SetNetworkProcessor struct { + BaseProcessor +} + +func NewSetNetworkProcessor() SetNetworkProcessor { + b := SetNetworkProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetNetworkProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetNetworkProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetNetworkProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("SetNetworkProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process SetBondProcessor error, instance %s not found", command.InstanceID)}) + } + + device, err := deviceLogic.GetById(logger, instance.DeviceID) + if err != nil { + logger.Warn("SetNetworkProcessor GetById sql error:", instance.DeviceID, err.Error()) + } + if device == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process SetBondProcessor error, device %s not found", fmt.Sprint(instance.DeviceID))}) + } + setNetworkOfRetail(logger, command, device) + //interfaces, err := interfaceLogic.GetBySn(logger, command.Sn) + //if err != nil || len(interfaces) < 2 { + // logger.Warn("SetBondProcessor GetBySn sql error,", command.Sn, err.Error()) + //} + + //if strings.EqualFold(instance.NetworkType, NetworkType.RETAIL) { + //setNetworkOfRetail(logger, command, device) + //} + +} + +func setNetworkOfRetail(logger *log.Logger, command *commandDao.Command, device *deviceDao.Device) { + //switch_ip := interfaces[0].SwitchIP + //jd_switch, err := jdSwitchDao.GetBySwitchIp(logger, switch_ip) + //if err != nil { + // logger.Warn("SetNetworkProcessor.setNetworkOfRetail.GetBySwitchIp error:", switch_ip, err.Error()) + // panic("process SetBond is error, switchIp %s JdSwitchEntity not found") + //} + //primary_interface := interfaces[0] + + nameservers, _ := beego.AppConfig.Strings("sdn.configs.nameservers") + if len(nameservers) == 0 { + nameservers = []string{"10.10.10.10"} + } + set_network := agentTypes.SetNetwork{ + Sn: command.Sn, + PrivateInterfaceName: "eth0", //写死??primary_interface.InterfaceName, + PrivateMacAddr: device.Mac1, //primary_interface.Mac, + PrivateGateway: device.Gateway, //jd_switch.Gateway, + PrivateNetmask: device.Mask, //jd_switch.Mask, + PrivateIpAddr: device.PrivateIPv4, + // EnableNet: instance.EnableInternet, + Nameservers: nameservers, + IsSetDns: true, + } + + if err := rabbitMq.SendToAgent(command.Sn, set_network); err != nil { + logger.Warnf("SetNetworkProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(set_network), err.Error()) + return + } + logger.Infof("SetNetworkProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(set_network)) + +} + +func (b SetNetworkProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + // b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/SetNocloudMetaDataProcessor.go b/bmp-scheduler/processor/SetNocloudMetaDataProcessor.go new file mode 100644 index 0000000..c3a4f93 --- /dev/null +++ b/bmp-scheduler/processor/SetNocloudMetaDataProcessor.go @@ -0,0 +1,85 @@ +package processor + +import ( + "fmt" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/rInstanceSshkeyDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/sshkeyDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SetNocloudMetaDataProcessor struct { + BaseProcessor +} + +func NewSetNocloudMetaDataProcessor() SetNocloudMetaDataProcessor { + b := SetNocloudMetaDataProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetNocloudMetaDataProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetNocloudMetaDataProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetNocloudMetaDataProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + logger.Info("SetNocloudMetaDataProcessor doProcess......", command.Sn) + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("SetNocloudMetaDataProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process SetNocloudMetaData error, instance %s not found", command.InstanceID)}) + } + SetNocloudMetaData := agentTypes.SetNocloudMetaData{ + Sn: command.Sn, + Version: "2.0", + } + instanceSshkeyList, err := rInstanceSshkeyDao.GetAllrInstanceSshkey(logger, map[string]interface{}{ + "instance_id": command.InstanceID, + "is_del": 0, + }) + //fmt.Println(instanceSshkeyList, len(instanceSshkeyList), err.Error())//不知为啥,err.Error()报错!!! + if err != nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process SetNocloudMetaData error, instance %s not found", command.InstanceID)}) + return + } + pubKeys := []string{} + for _, v := range instanceSshkeyList { + sshKeyInfo, err := sshkeyDao.GetSshkeyById(logger, v.SSHkeyID) + if sshKeyInfo != nil { + pubKeys = append(pubKeys, sshKeyInfo.Key) + } else { + logger.Warnf("GetInstanceSshkey sql error By sshkeyId:%s, error:%s", v.SSHkeyID, err.Error()) + return + } + } + SetNocloudMetaData.MetaData.LocalHostname = instance.Hostname + SetNocloudMetaData.MetaData.InstanceID = command.InstanceID + if len(pubKeys) > 0 { + SetNocloudMetaData.MetaData.PublicKeys = pubKeys + } + + if err := rabbitMq.SendToAgent(command.Sn, SetNocloudMetaData); err != nil { + logger.Warnf("SetNocloudMetaDataProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(SetNocloudMetaData), err.Error()) + return + } + logger.Infof("SetNocloudMetaDataProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(SetNocloudMetaData)) + +} + +func (b SetNocloudMetaDataProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/SetNocloudNetworkProcessor.go b/bmp-scheduler/processor/SetNocloudNetworkProcessor.go new file mode 100644 index 0000000..1dae94e --- /dev/null +++ b/bmp-scheduler/processor/SetNocloudNetworkProcessor.go @@ -0,0 +1,198 @@ +package processor + +import ( + "fmt" + "net" + "strconv" + "strings" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceTypeDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SetNocloudNetworkProcessor struct { + BaseProcessor +} + +//linux设置network + +func NewSetNocloudNetworkProcessor() SetNocloudNetworkProcessor { + b := SetNocloudNetworkProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetNocloudNetworkProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetNocloudNetworkProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetNocloudNetworkProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + logger.Info("SetNocloudNetworkProcessor doProcess......", command.Sn) + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("SetNocloudNetworkProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + fmt.Println("shili", instance) + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process MakeRaid error, instance %s not found", command.InstanceID)}) + } + device, err := deviceDao.GetDeviceById(logger, instance.DeviceID) + if err != nil { + logger.Warn("SetNocloudNetworkProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + fmt.Println("device", device) + if device == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process SetNocloudNetwork error, device %s not found", instance.DeviceID)}) + } + + address := make([]string, 0) + mask := net.IPMask(net.ParseIP(device.Mask).To4()) + prefixSize, _ := mask.Size() + ipv4 := device.PrivateIPv4 + "/" + strconv.Itoa(prefixSize) + address = append(address, ipv4) + if device.PrivateIPv6 != "" { + address = append(address, device.PrivateIPv6) + } + + addressEth1 := make([]string, 0) + mask2 := net.IPMask(net.ParseIP(device.MaskEth1).To4()) + prefixSize2, _ := mask2.Size() + ipv4eth1 := device.PrivateEth1IPv4 + "/" + strconv.Itoa(prefixSize2) + addressEth1 = append(addressEth1, ipv4eth1) + if device.PrivateIPv6 != "" { + addressEth1 = append(addressEth1, device.PrivateEth1IPv6) + } + + //ipv4andv6 := make([]string, 0) + //ipv4andv6 = append(ipv4andv6, device.PrivateIPv4) + //if device.PrivateIPv6 != "" { + // ipv4andv6 = append(ipv4andv6, device.PrivateIPv6) + //} + deviceType, err := deviceTypeDao.GetDeviceTypeById(logger, instance.DeviceTypeID) + if err != nil { + logger.Warn("SetNocloudNetworkProcessor GetByDeviceTypeId sql error:", command.InstanceID, err.Error()) + } + if deviceType == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process SetNocloudNetwork error, deviceType %s not found", instance.DeviceTypeID)}) + } + if strings.ToLower(deviceType.InterfaceMode) == "bond" { //如果是bond模式 + SetNocloudNetwork := agentTypes.SetNocloudNetwork{ + Sn: command.Sn, + Version: "2.0", + } + SetNocloudNetwork.Network.Bonds.Bond0.Macaddress = device.Mac1 + SetNocloudNetwork.Network.Bonds.Bond0.Addresses = address + SetNocloudNetwork.Network.Bonds.Bond0.Gateway4 = device.Gateway + if device.PrivateIPv6 != "" { + SetNocloudNetwork.Network.Bonds.Bond0.Gateway6 = device.Gateway6 + } + SetNocloudNetwork.Network.Bonds.Bond0.Nameservers.Addresses = []string{"114.114.114.114", "8.8.8.8"} + + SetNocloudNetwork.Network.Bonds.Bond0.Interfaces = []string{"eth0", "eth1"} + SetNocloudNetwork.Network.Bonds.Bond0.Parameters.Mode = "802.3ad" + SetNocloudNetwork.Network.Bonds.Bond0.Parameters.MiiMonitorInterval = 100 + + SetNocloudNetwork.Network.Ethernets.Eth0.Match.Macaddress = device.Mac1 + SetNocloudNetwork.Network.Ethernets.Eth0.SetName = "eth0" + SetNocloudNetwork.Network.Ethernets.Eth1.Match.Macaddress = device.Mac2 + SetNocloudNetwork.Network.Ethernets.Eth1.SetName = "eth1" + SetNocloudNetwork.Network.Version = 2 //写死 + + fmt.Println("最终的json:", util.ObjToJson(SetNocloudNetwork)) + //os.Exit(1) + if err := rabbitMq.SendToAgent(command.Sn, SetNocloudNetwork); err != nil { + logger.Warnf("SetNocloudNetworkProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(SetNocloudNetwork), err.Error()) + return + } + logger.Infof("SetNocloudNetworkProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(SetNocloudNetwork)) + + } else if deviceType.NicAmount == 1 { //如果是单网口,只需要eth0即可 + SetNocloudNetworkNoBond := agentTypes.SetNocloudNetworkNoBond{ + Sn: command.Sn, + Version: "2.0", + } + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.Match.Macaddress = device.Mac1 + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.SetName = "eth0" //默认写死 + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.Addresses = address + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.Netmask = device.Mask + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.Gateway4 = device.Gateway + if device.PrivateIPv6 != "" { + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.Gateway6 = device.Gateway6 + } + //fmt.Println("设置前", SetNocloudNetworkNoBond, util.ObjToJson(SetNocloudNetworkNoBond)) + //双网卡基础网络环境,开启外网时(eth1是外网),此时eth0不设置gateway4,eth1设置gateway4 + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.Nameservers.Addresses = []string{"103.224.222.222", "103.224.222.223"} //"114.114.114.114", "8.8.8.8" + //fmt.Println("设置后", SetNocloudNetworkNoBond, util.ObjToJson(SetNocloudNetworkNoBond)) + ri := []agentTypes.RouteItem{ + { + To: "0.0.0.0/0", + Via: device.Gateway, + }, + } + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.Routes = ri + SetNocloudNetworkNoBond.Network.Version = 2 //写死 + + //os.Exit(1) + if err := rabbitMq.SendToAgent(command.Sn, SetNocloudNetworkNoBond); err != nil { + logger.Warnf("SetNocloudNetworkProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(SetNocloudNetworkNoBond), err.Error()) + return + } + logger.Infof("SetNocloudNetworkProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(SetNocloudNetworkNoBond)) + } else if deviceType.NicAmount == 2 { //如果是双网口非bond,需要eth0,eth1 + SetNocloudNetworkNoBond := agentTypes.SetNocloudNetworkNoBond{ + Sn: command.Sn, + Version: "2.0", + } + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.Match.Macaddress = device.Mac1 + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.SetName = "eth0" //默认写死 + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.Addresses = address + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.Netmask = device.Mask + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.Gateway4 = device.Gateway + if device.PrivateIPv6 != "" { + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.Gateway6 = device.Gateway6 + } + //fmt.Println("设置前", SetNocloudNetworkNoBond, util.ObjToJson(SetNocloudNetworkNoBond)) + //双网卡基础网络环境,开启外网时(eth1是外网),此时eth0不设置gateway4,eth1设置gateway4 + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.Nameservers.Addresses = []string{"103.224.222.222", "103.224.222.223"} + ri := []agentTypes.RouteItem{ + { + To: "0.0.0.0/0", + Via: device.Gateway, + }, + } + SetNocloudNetworkNoBond.Network.Ethernets.Eth0.Routes = ri + //fmt.Println("设置后", SetNocloudNetworkNoBond, util.ObjToJson(SetNocloudNetworkNoBond)) + SetNocloudNetworkNoBond.Network.Version = 2 //写死 + + SetNocloudNetworkNoBond.Network.Ethernets.Eth1.Match.Macaddress = device.Mac2 + SetNocloudNetworkNoBond.Network.Ethernets.Eth1.SetName = "eth1" + SetNocloudNetworkNoBond.Network.Ethernets.Eth1.Addresses = addressEth1 + SetNocloudNetworkNoBond.Network.Ethernets.Eth1.Netmask = device.MaskEth1 + SetNocloudNetworkNoBond.Network.Ethernets.Eth1.Nameservers.Addresses = []string{"103.224.222.222", "103.224.222.223"} + + //os.Exit(1) + if err := rabbitMq.SendToAgent(command.Sn, SetNocloudNetworkNoBond); err != nil { + logger.Warnf("SetNocloudNetworkProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(SetNocloudNetworkNoBond), err.Error()) + return + } + logger.Infof("SetNocloudNetworkProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(SetNocloudNetworkNoBond)) + } + +} + +func (b SetNocloudNetworkProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/SetNocloudUserDataProcessor.go b/bmp-scheduler/processor/SetNocloudUserDataProcessor.go new file mode 100644 index 0000000..9cc4e97 --- /dev/null +++ b/bmp-scheduler/processor/SetNocloudUserDataProcessor.go @@ -0,0 +1,55 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SetNocloudUserDataProcessor struct { + BaseProcessor +} + +func NewSetNocloudUserDataProcessor() SetNocloudUserDataProcessor { + b := SetNocloudUserDataProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetNocloudUserDataProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetNocloudUserDataProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetNocloudUserDataProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + logger.Info("SetNocloudUserDataProcessor doProcess......", command.Sn) + instance_extra := loadInstanceExtra(logger, command.InstanceID) + + SetNocloudUserData := agentTypes.SetNocloudUserData{ + Sn: command.Sn, + Version: "2.0", + UserData: "", // 用户自定义脚本 + } + if instance_extra != nil && instance_extra.UserData != "" { + SetNocloudUserData.UserData = instance_extra.UserData + } + + if err := rabbitMq.SendToAgent(command.Sn, SetNocloudUserData); err != nil { + logger.Warnf("SetNocloudUserDataProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(SetNocloudUserData), err.Error()) + return + } + logger.Infof("SetNocloudUserDataProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(SetNocloudUserData)) + +} + +func (b SetNocloudUserDataProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/SetPXEBootProcessor.go b/bmp-scheduler/processor/SetPXEBootProcessor.go new file mode 100644 index 0000000..24e1621 --- /dev/null +++ b/bmp-scheduler/processor/SetPXEBootProcessor.go @@ -0,0 +1,84 @@ +package processor + +import ( + "fmt" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + deviceDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/idcDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + driverTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/driver" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SetPXEBootProcessor struct { + BaseProcessor +} + +func NewSetPXEBootProcessor() SetPXEBootProcessor { + b := SetPXEBootProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetPXEBootProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetPXEBootProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetPXEBootProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + logger.Info("SetPXEBootProcessor doProcess begin...", command.Sn) + var device *deviceDao.Device + var err error + device, _ = deviceDao.GetBySn(logger, command.Sn) + + if device == nil { + logger.Warn("SetPXEBootProcessor GetBySn sql error:", err.Error()) + panic(ProcessAbortException{Msg: fmt.Sprintf("process SetPXEBootProcessor error, sn %s device not found", command.Sn)}) + } + idc, err := idcDao.GetIdcById(logger, device.IDcID) + if err != nil { + logger.Warn("机房ID不存在", device.Sn, device.IDcID, err.Error()) + } + var iloUser, iloPassword string + //如果设备的带外账号,密码没有录入,默认取机房填写的带外账号密码 + if device.IloUser == "" || device.IloPassword == "" { + if idc == nil { + logger.Warn("设备和机房iloip信息都缺失", device.Sn, device.IDcID) + return + } + } + if device.IloUser == "" { + iloUser = idc.IloUser + } else { + iloUser = device.IloUser + } + if device.IloPassword == "" { + iloPassword = idc.IloPassword + } else { + iloPassword = device.IloPassword + } + set_PXE_boot := driverTypes.SetPXEBoot{ + Sn: command.Sn, + IloIp: device.IloIP, + Username: iloUser, + Password: iloPassword, + } + if err := rabbitMq.SendToAgent(device.IDcID, set_PXE_boot); err != nil { + logger.Warnf("SetPXEBootProcessor SendToDriver error, routekey: %s, msg:%s, error:%s", device.IDcID, util.ObjToJson(set_PXE_boot), err.Error()) + return + } + logger.Infof("SetPXEBootProcessor_SendToDriver_Msg success, routekey: %s, msg:%s", device.IDcID, util.ObjToJson(set_PXE_boot)) +} + +func (b SetPXEBootProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + logger.Info("SetPXEBootProcessor afterProcess done!", command.Sn) + defer logger.Info("SetPXEBootProcessor afterProcess done!", command.Sn) + //empty +} diff --git a/bmp-scheduler/processor/SetPasswordProcessor.go b/bmp-scheduler/processor/SetPasswordProcessor.go new file mode 100644 index 0000000..2c3cabd --- /dev/null +++ b/bmp-scheduler/processor/SetPasswordProcessor.go @@ -0,0 +1,63 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/rInstanceSshkeyDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + "fmt" + "git.jd.com/cps-golang/ironic-common/ironic/enums/TimeoutPolicy" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SetPasswordProcessor struct { + BaseProcessor +} + +func NewSetPasswordProcessor() SetPasswordProcessor { + b := SetPasswordProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetPasswordProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetPasswordProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetPasswordProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + instance_extra := loadInstanceExtra(logger, command.InstanceID) + fmt.Println(instance_extra, instance_extra.Password) + if instance_extra == nil || instance_extra.Password == "" { + command.TimeoutPolicy = TimeoutPolicy.SKIP + logger.Info("SetPasswordCommand timeoutPolicy set to skip", command.InstanceID) + return + } + set_password := agentTypes.SetPassword{ + Sn: command.Sn, + Password: instance_extra.Password, + } + if err := rabbitMq.SendToAgent(command.Sn, set_password); err != nil { + logger.Warnf("SetPasswordProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(set_password), err.Error()) + return + } + logger.Infof("SetPasswordProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(set_password)) + +} + +func (b SetPasswordProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + instanceSshkeyList, _ := rInstanceSshkeyDao.GetAllrInstanceSshkey(logger, map[string]interface{}{ + "instance_id": command.InstanceID, + "is_del": 0, + }) + if len(instanceSshkeyList) != 0 { //如果使用了ssh登录方式,直接执行成功,执行下一条指令 + b.AfterSuccessExecute(logger, command) //无论是否成功,指令都没往下走? + } + +} diff --git a/bmp-scheduler/processor/SetRetailBondProcessor.go b/bmp-scheduler/processor/SetRetailBondProcessor.go new file mode 100644 index 0000000..a41485e --- /dev/null +++ b/bmp-scheduler/processor/SetRetailBondProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SetRetailBondProcessor struct { + BaseProcessor +} + +func NewSetRetailBondProcessor() SetRetailBondProcessor { + b := SetRetailBondProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetRetailBondProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetRetailBondProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetRetailBondProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b SetRetailBondProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/SetUserCmdProcessor.go b/bmp-scheduler/processor/SetUserCmdProcessor.go new file mode 100644 index 0000000..6e85a1f --- /dev/null +++ b/bmp-scheduler/processor/SetUserCmdProcessor.go @@ -0,0 +1,54 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + "git.jd.com/cps-golang/ironic-common/ironic/enums/TimeoutPolicy" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type SetUserCmdProcessor struct { + BaseProcessor +} + +func NewSetUserCmdProcessor() SetUserCmdProcessor { + b := SetUserCmdProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b SetUserCmdProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b SetUserCmdProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b SetUserCmdProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + logger.Info("SetUserCmdProcessor doProcess starting......", command.InstanceID) + instance_extra := loadInstanceExtra(logger, command.InstanceID) + if instance_extra == nil || instance_extra.UserData == "" { + logger.Info("SetUserCmdCommand timeoutPolicy set to skip", command.InstanceID) + command.TimeoutPolicy = TimeoutPolicy.SKIP + return + } + user_cmd := agentTypes.SetUserCmd{ + Sn: command.Sn, + Content: instance_extra.UserData, + } + if err := rabbitMq.SendToAgent(command.Sn, user_cmd); err != nil { + logger.Warnf("SetUserCmdProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(user_cmd), err.Error()) + return + } + logger.Infof("SetUserCmdProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(user_cmd)) +} + +func (b SetUserCmdProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/UnBindingVSIProcessor.go b/bmp-scheduler/processor/UnBindingVSIProcessor.go new file mode 100644 index 0000000..f6d4b45 --- /dev/null +++ b/bmp-scheduler/processor/UnBindingVSIProcessor.go @@ -0,0 +1,34 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type UnBindingVSIProcessor struct { + BaseProcessor +} + +func NewUnBindingVSIProcessor() UnBindingVSIProcessor { + b := UnBindingVSIProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b UnBindingVSIProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b UnBindingVSIProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b UnBindingVSIProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + //TODO +} + +func (b UnBindingVSIProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + b.AfterSuccessExecute(logger, command) +} diff --git a/bmp-scheduler/processor/UploadSystemLogProcessor.go b/bmp-scheduler/processor/UploadSystemLogProcessor.go new file mode 100644 index 0000000..c3a17cd --- /dev/null +++ b/bmp-scheduler/processor/UploadSystemLogProcessor.go @@ -0,0 +1,44 @@ +package processor + +import ( + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type UploadSystemLogProcessor struct { + BaseProcessor +} + +func NewUploadSystemLogProcessor() UploadSystemLogProcessor { + b := UploadSystemLogProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b UploadSystemLogProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b UploadSystemLogProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b UploadSystemLogProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + upload_system_log := agentTypes.UploadSystemLog{ + Sn: command.Sn, + } + if err := rabbitMq.SendToAgent(command.Sn, upload_system_log); err != nil { + logger.Warn("UploadSystemLogProcessor SendToAgent error:", command.Sn, err.Error()) + return + } + logger.Infof("UploadSystemLogProcessor_SendToAgent_Msg success, sn:", command.Sn) +} + +func (b UploadSystemLogProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/WriteImageProcessor.go b/bmp-scheduler/processor/WriteImageProcessor.go new file mode 100644 index 0000000..38b4758 --- /dev/null +++ b/bmp-scheduler/processor/WriteImageProcessor.go @@ -0,0 +1,167 @@ +package processor + +import ( + "encoding/json" + "fmt" + "strings" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + deviceDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/deviceHintsDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/volumeDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/imageLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/osLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type WriteImageProcessor struct { + BaseProcessor +} + +func NewWriteImageProcessor() WriteImageProcessor { + b := WriteImageProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b WriteImageProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b WriteImageProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + + //以下是基于重装系统的,需要存储hints + if strings.EqualFold(msg.Status, OK) { + + v, err := json.Marshal(msg.Data) + if err != nil { + logger.Warn("WriteImageProcessor.data marshal error:", err.Error()) + } else { + disk_hints := DiskHintsCallBackInfo{} + if err := json.Unmarshal(v, &disk_hints); err != nil { + logger.Warn("WriteImageProcessor.data Unmarshal error:", err.Error()) + } else { + if err := synDiskHints(logger, command.Sn, disk_hints); err != nil { + msg.Status = ERROR + msg.Message = err.Error() + } + } + } + } + + b.BaseProcessor.CallBack(logger, command, msg) +} + +func synDiskHints(logger *log.Logger, sn string, root_disk_hints DiskHintsCallBackInfo) error { + + deviceEntity, err := deviceDao.GetBySn(logger, sn) + if err != nil { + logger.Warnf("synDiskHints.GetDeviceBySn error, sn:%s, error:%s", sn, err.Error()) + return err + } + + disk_hints := root_disk_hints.RootDeviceHints + entity, err := deviceHintsDao.GetSystemVolumnDeviceHintsBySn(logger, sn) + if err != nil { + logger.Warn("MakePartitionsProcessor.synDiskHints.GetSystemVolumnDeviceHintsBySn error:", sn, err.Error()) + } + if entity != nil { + entity.Size = disk_hints.Size + entity.Rotational = util.Bool2Int8(disk_hints.Rotational) + entity.Wwn = disk_hints.Wwn + entity.Name = disk_hints.Name + entity.WwnVendorExtension = disk_hints.WwnVendorExtension + entity.WwnWithExtension = disk_hints.WwnWithExtension + entity.Model = disk_hints.Model + entity.Serial = disk_hints.Serial + entity.Vendor = disk_hints.Vendor + entity.Hctl = disk_hints.Hctl + entity.ByPath = disk_hints.ByPath + entity.IsDel = 0 + if err := deviceHintsDao.UpdateDeviceHintsById(logger, entity); err != nil { + logger.Warn("MakePartitionsProcessor.synDiskHints.UpdateDeviceHintsById error:", sn, err.Error()) + return err + } + } else { + entity = &deviceHintsDao.DeviceHints{ + Sn: sn, + Size: disk_hints.Size, + Rotational: util.Bool2Int8(disk_hints.Rotational), + Wwn: disk_hints.Wwn, + Name: disk_hints.Name, + WwnVendorExtension: disk_hints.WwnVendorExtension, + WwnWithExtension: disk_hints.WwnWithExtension, + Model: disk_hints.Model, + Serial: disk_hints.Serial, + Vendor: disk_hints.Vendor, + Hctl: disk_hints.Hctl, + ByPath: disk_hints.ByPath, + IsDel: 0, + } + volumeEntity, err := volumeDao.GetSystemVolumeByDeviceTypeId(logger, deviceEntity.DeviceTypeID) + if err != nil { + logger.Warnf("MakePartitionsProcessor.synDiskHints.GetSystemVolumeByDeviceTypeId error, device_type_id:%s, error:%s", deviceEntity.DeviceTypeID, err.Error()) + } else { + entity.VolumeId = volumeEntity.VolumeID + entity.VolumeType = "system" + if _, err := deviceHintsDao.AddDeviceHints(logger, entity); err != nil { + logger.Warn("MakePartitionsProcessor.synDiskHints.AddDeviceHints error:", sn, err.Error()) + return err + } + } + + } + return nil + +} + +func (b WriteImageProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("WriteImageProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process WriteImage error, instance %s not found", command.InstanceID)}) + } + + image_entity, err := imageLogic.GetByImageId(logger, instance.ImageID) + if err != nil { + logger.Warn("WriteImageProcessor GetByImageId sql error:", instance.ImageID, err.Error()) + } + if image_entity == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process WriteImage error, image %s not found", instance.ImageID)}) + } + os_entity, err := osLogic.GetByOsId(logger, image_entity.OsID) + if err != nil { + logger.Warn("WriteImageProcessor GetByOsId sql error:", image_entity.OsID, err.Error()) + } + if os_entity == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process WriteImage error, os %s not found", image_entity.OsID)}) + } + + write_image := agentTypes.WriteImage{ + Sn: command.Sn, + Url: image_entity.URL, + Format: image_entity.Format, + Filename: image_entity.Filename, + Hash: image_entity.Hash, + OsType: os_entity.OsType, + OsVersion: os_entity.OsVersion, + } + if err := rabbitMq.SendToAgent(command.Sn, write_image); err != nil { + logger.Warnf("WriteImageProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(write_image), err.Error()) + return + } + logger.Infof("WriteImageProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(write_image)) +} + +func (b WriteImageProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/processor/WriteImageTarProcessor.go b/bmp-scheduler/processor/WriteImageTarProcessor.go new file mode 100644 index 0000000..5706791 --- /dev/null +++ b/bmp-scheduler/processor/WriteImageTarProcessor.go @@ -0,0 +1,100 @@ +package processor + +import ( + "encoding/json" + "fmt" + "strings" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/imageLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/osLogic" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + agentTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/agent" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" +) + +type WriteImageTarProcessor struct { + BaseProcessor +} + +func NewWriteImageTarProcessor() WriteImageTarProcessor { + b := WriteImageTarProcessor{} + b.BaseProcessor.doProcess = b.doProcess + b.BaseProcessor.afterProcess = b.afterProcess + return b +} + +func (b WriteImageTarProcessor) Process(logger *log.Logger, command *commandDao.Command) { + b.BaseProcessor.Process(logger, command) +} + +func (b WriteImageTarProcessor) Callback(logger *log.Logger, command *commandDao.Command, msg ironicAgentEvent.CallbackCommandMessage) { + //以下是基于重装系统的,需要存储hints + if strings.EqualFold(msg.Status, OK) { + + v, err := json.Marshal(msg.Data) + if err != nil { + logger.Warn("WriteImageTarProcessor.data marshal error:", err.Error()) + } else { + disk_hints := DiskHintsCallBackInfo{} + if err := json.Unmarshal(v, &disk_hints); err != nil { + logger.Warn("WriteImageTarProcessor.data Unmarshal error:", err.Error()) + } else { + if err := synDiskHints(logger, command.Sn, disk_hints); err != nil { + msg.Status = ERROR + msg.Message = err.Error() + } + } + } + } + + b.BaseProcessor.CallBack(logger, command, msg) +} + +func (b WriteImageTarProcessor) doProcess(logger *log.Logger, command *commandDao.Command) { + + instance, err := instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("WriteImageTarProcessor GetByInstanceId sql error:", command.InstanceID, err.Error()) + } + if instance == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process WriteImageTar error, instance %s not found", command.InstanceID)}) + } + + image_entity, err := imageLogic.GetByImageId(logger, instance.ImageID) + if err != nil { + logger.Warn("WriteImageTarProcessor GetByImageId sql error:", instance.ImageID, err.Error()) + } + if image_entity == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process WriteImageTar error, image %s not found", instance.ImageID)}) + } + os_entity, err := osLogic.GetByOsId(logger, image_entity.OsID) + if err != nil { + logger.Warn("WriteImageTarProcessor GetByOsId sql error:", image_entity.OsID, err.Error()) + } + if os_entity == nil { + panic(ProcessAbortException{Msg: fmt.Sprintf("process WriteImageTar error, os %s not found", image_entity.OsID)}) + } + + write_image := agentTypes.WriteImageTar{ + Sn: command.Sn, + Url: image_entity.URL, + Format: image_entity.Format, + Filename: image_entity.Filename, + Hash: image_entity.Hash, + OsType: os_entity.OsType, + OsVersion: os_entity.OsVersion, + } + if err := rabbitMq.SendToAgent(command.Sn, write_image); err != nil { + logger.Warnf("WriteImageTarProcessor SendToAgent error, msg:%s, error:%s", util.ObjToJson(write_image), err.Error()) + return + } + logger.Infof("WriteImageTarProcessor_SendToAgent_Msg success, msg:%s", util.ObjToJson(write_image)) +} + +func (b WriteImageTarProcessor) afterProcess(logger *log.Logger, command *commandDao.Command) { + //empty +} diff --git a/bmp-scheduler/scheduler/checkTimeoutCommandCron.go b/bmp-scheduler/scheduler/checkTimeoutCommandCron.go new file mode 100644 index 0000000..9cef90c --- /dev/null +++ b/bmp-scheduler/scheduler/checkTimeoutCommandCron.go @@ -0,0 +1,204 @@ +package scheduler + +import ( + "encoding/json" + "fmt" + "sync" + "time" + + beego "github.com/beego/beego/v2/server/web" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/commandLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/processor" + "coding.jd.com/aidc-bmp/bmp-scheduler/service/redis" + "coding.jd.com/aidc-bmp/bmp-scheduler/util" + "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandStatus" + "git.jd.com/cps-golang/ironic-common/ironic/enums/InstanceStatus" + "git.jd.com/cps-golang/ironic-common/ironic/enums/TimeoutPolicy" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + log "git.jd.com/cps-golang/log" +) + +func doCheckTimeoutCommandCron() error { + logPath, _ := beego.AppConfig.String("log.path") + logger := log.New(logPath + "/bmp-scheduler-checkTimeoutCommandCron.log") + logger.SetStableFields([]string{"method", "uri", "header", "request", "response"}) + logger.TimeStart("all_t") + logger.TimeStart("self_t") + logger.Point("task_type", "CheckTimeoutCommandCron") + //没有requestid,临时生成 + logger.Point("logid", commonUtil.GenerateRandUuid()) + defer logger.Flush() + defer logger.TimeEnd("self_t") + defer logger.TimeEnd("all_t") + + logger.Info("doCheckTimeoutCommandCron starting......") + + key := "SchedulerLock:cps-ironic:check_timeout_command_cron" + is_set, err := redis.SetNxObjectToRedis(key, "1", 30) + //fmt.Println("设置redis key: SchedulerLock:cps-ironic:check_timeout_command_cro", is_set) + if err != nil { + logger.Warn("CheckTimeoutCommand SetNxObjectToRedis error:", err.Error()) + return nil + } + if is_set { + commands, err := commandLogic.QueryTimeoutCommands(logger, time.Now().Add(-time.Hour*8), time.Now()) + if err != nil { + logger.Warn("CheckTimeoutCommand QueryTimeoutCommands sql error:", err.Error()) + return nil + } + length := len(commands) + wg := sync.WaitGroup{} + wg.Add(length) + for i := 0; i < length; i++ { + defer wg.Done() + go dealTimeOutCmd(logger, commands[i]) + } + wg.Wait() + } + return nil +} + +func dealTimeOutCmd(logger *log.Logger, command *commandDao.Command) { + val, _ := json.Marshal(command) + logger.Info("get timeout comand :", string(val)) + defer func() { + if r := recover(); r != nil { + logger.Warn("dealTimeOutCmd processor.Run panic info:", r) + } + }() + if command.Action == CommandAction.Ping.Name { + processor.BaseProcessor{}.AfterFailedExecute(logger, command, string(val)) + return + } + + if command.Task == "CollectHardwareInfo" { + //采集任务如果失败则直接软删除,不影响后面的装机 + q := map[string]interface{}{ + "request_id": command.RequestID, + "sn": command.Sn, + "is_del": 0, + } + u := map[string]interface{}{ + "is_del": 1, + } + if err := commandDao.UpdateMultiCommands(logger, q, u); err != nil { + logger.Warnf("dealTimeOutCmd UpdateMultiCommands for CollectHardwareInfo error, sn:%s, error:%s", command.Sn, err.Error()) + return + } + + // if err := devicepreDao.DeleteBySn(logger, command.Sn); err != nil { + // logger.Warnf("dealTimeOutCmd DeletedevicePreBySn for CollectHardwareInfo error, sn:%s, error:%s", command.Sn, err.Error()) + // } + return + } + + if command.TimeoutPolicy == TimeoutPolicy.SKIP { + processor.BaseProcessor{}.AfterSuccessExecute(logger, command) + } else { + + if alreadyWarning(logger, command.RequestID, command.Sn) { + logger.Warn(fmt.Sprintf("already warning for request_id:%s, sn:%s", command.RequestID, command.Sn)) + return + } + //sendCommandTimeoutEmail(logger, command) + + //TODO + command.Status = CommandStatus.ERROR + command.UpdatedTime = int(time.Now().Unix()) + if err := commandDao.UpdateCommandById(logger, command); err != nil { + logger.Warn("BaseProcessor afterFailedExecute UpdateCommandById sql error:", err.Error()) + } + + if command.InstanceID != "" { + instanceEntity, err := instanceDao.GetInstanceByUuid(logger, command.InstanceID) + if err != nil { + logger.Warnf("dealTimeOutCmd GetInstanceByUuid error, InstanceID:%s, error:%s", command.InstanceID, err.Error()) + } else { + instanceEntity.Status = InstanceStatus.Instance_To_Error_Status[command.Task] + instanceEntity.Reason = command.Action + "Error" + if err := instanceDao.UpdateInstanceByInstanceId(logger, instanceEntity); err != nil { + logger.Warnf("更新实例创建失败原因", command.InstanceID, command.Action) + } + } + } + + } +} + +func sendCommandTimeoutEmail(logger *log.Logger, command *commandDao.Command) { + logger.Info("sendCommandTimeoutEmail start......", util.ObjToJson(command)) + device, err := deviceLogic.GetBySn(logger, command.Sn) + if err != nil { + logger.Warn("sendCommandTimeoutEmail GetBySn sql error:", command.Sn, err.Error()) + } + if device == nil { + logger.Warn("no device found by sn ", command.Sn) + return + } + commands, err := commandLogic.QueryCommandsByRequestIdAndSn(logger, command.RequestID, command.Sn) + if err != nil { + logger.Warn("sendCommandTimeoutEmail QueryCommandsByRequestIdAndSn sql error:", command.RequestID, command.Sn, err.Error()) + } + if len(commands) == 0 { + return + } + var instance *instanceDao.Instance + if command.RequestID == "" { + instance = nil + } else { + instance, err = instanceLogic.GetByInstanceId(logger, command.InstanceID) + if err != nil { + logger.Warn("sendCommandTimeoutEmail GetByInstanceId sql error:", command.InstanceID, err.Error()) + return + } + } + if instance == nil { + logger.Warn("sendCommandTimeoutEmail empty instance", command.InstanceID) + return + } + //屏蔽发邮件逻辑 + //mailData := emailTemplate.CheckTimeoutCommandTpl{ + // CurrentDate: time.Now().String(), + // Commands: commands, + // Device: *device, + // Instance: *instance, + //} + // + //logger.Info("[mailData debug]", util.ObjToJson(mailData)) + //receivers := mailLogic.GetMailReceiver(logger, MailType.COMMAND_WARNING) + //if len(receivers) == 0 { + // logger.Warn("no mail receiver found, skip send command warning email") + // return + //} + //subject := fmt.Sprintf("[%s]指令监控", "bmp-ironic-scheduler") + //if err := email.SendMailByTpl(emailTemplate.CheckTimeoutCommandMailContent, subject, mailData, receivers); err != nil { + // logger.Warn("CheckTimeoutCommand SendMailByTpl error:", err.Error()) + //} else { + // logger.Point("sendCommandTimeoutEmail_status", "succeed") + //} + // + //logger.Info("sendCommandTimeoutEmail end......") + +} + +func alreadyWarning(logger *log.Logger, request_id, sn string) bool { + key := fmt.Sprintf(Constants.REDIS_KEY_MONITOR_COMMAND_FORMAT, request_id, sn) + res, err := redis.Keys(key) + if err != nil { + logger.Warn("alreadyWarning Keys error:", request_id, sn, err.Error()) + } + if len(res) > 0 { + return true + } + if err := redis.SetObjectToRedisWithExpire(key, "1", Constants.TIMEOUT_MONITOR_COMMAND); err != nil { + logger.Warn("alreadyWarning SetObjectToRedisWithExpire error:", key, err.Error()) + } + return false +} diff --git a/bmp-scheduler/scheduler/cleanAuditLog.go b/bmp-scheduler/scheduler/cleanAuditLog.go new file mode 100644 index 0000000..35ca673 --- /dev/null +++ b/bmp-scheduler/scheduler/cleanAuditLog.go @@ -0,0 +1,42 @@ +package scheduler + +import ( + "time" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/auditLogsDao" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + log "git.jd.com/cps-golang/log" + beego "github.com/beego/beego/v2/server/web" +) + +//onst LOG_DIR = "./log" + +func doCleanAuditLogCron() error { + logPath, _ := beego.AppConfig.String("log.path") + logger := log.New(logPath + "/bmp-scheduler-cleanAuditLogCron.log") + logger.TimeStart("all_t") + logger.TimeStart("self_t") + logger.Point("task_type", "cleanAuditLogCron") + //没有requestid,临时生成 + logger.Point("logid", commonUtil.GenerateRandUuid()) + defer logger.Flush() + defer logger.TimeEnd("self_t") + defer logger.TimeEnd("all_t") + + logger.Info("doCleanAuditLogCron starting......") + + stime := time.Now().AddDate(0, 0, -90).Unix() + q := map[string]interface{}{ + "created_time.lte": stime, + "is_del": 0, + } + u := map[string]interface{}{ + "is_del": 1, + } + if err := auditLogsDao.UpdateMultiAuditLogs(logger, q, u); err != nil { + logger.Warnf("doCleanAuditLogCron.UpdateMultiAuditLogs error, stime:%d, error:%s", stime, err.Error()) + return err + } + + return nil +} diff --git a/bmp-scheduler/scheduler/cleanLog.go b/bmp-scheduler/scheduler/cleanLog.go new file mode 100644 index 0000000..385886c --- /dev/null +++ b/bmp-scheduler/scheduler/cleanLog.go @@ -0,0 +1,50 @@ +package scheduler + +import ( + "fmt" + "os" + "path/filepath" + "regexp" + "time" + + beego "github.com/beego/beego/v2/server/web" +) + +const REGEX_FILE_NAME string = `^.*\.202[0-9]{7}$` + +//onst LOG_DIR = "./log" + +func doCleanLogCron() error { + + files := []string{} + infos := []os.FileInfo{} + + remainDays, _ := beego.AppConfig.Int("logs.remainDays") + if remainDays == 0 { + remainDays = 3 //测试时默认3天 + } + logPath, _ := beego.AppConfig.String("log.path") + if err := filepath.Walk(logPath, func(path string, info os.FileInfo, err error) error { + files = append(files, path) + infos = append(infos, info) + return nil + }); err != nil { + fmt.Println("doCleanLogCron.Walk error:", err.Error()) + return err + } + + for _, info := range infos { + if info.IsDir() { + continue + } + if match, _ := regexp.MatchString(REGEX_FILE_NAME, info.Name()); match { + modifySince := time.Now().Unix() - info.ModTime().Unix() + if modifySince > int64(remainDays)*24*3600 { + if err := os.Remove(logPath + string(os.PathSeparator) + info.Name()); err != nil { + fmt.Printf("os.Remove error, file:%s, error:%s\n", info.Name(), err.Error()) + } + } + } + } + return nil +} diff --git a/bmp-scheduler/scheduler/dispatchIronicAgent.go b/bmp-scheduler/scheduler/dispatchIronicAgent.go new file mode 100644 index 0000000..5528201 --- /dev/null +++ b/bmp-scheduler/scheduler/dispatchIronicAgent.go @@ -0,0 +1,97 @@ +package scheduler + +import ( + "encoding/json" + "fmt" + "math/rand" + "time" + + beego "github.com/beego/beego/v2/server/web" + + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/commandLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/deviceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/processor" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandStatus" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + log "git.jd.com/cps-golang/log" +) + +func doReceiveFromIronicAgent(errChan chan int) { + + fmt.Println(time.Now().String() + "start doReceiveFromIronicAgent......") + ch, err := rabbitMq.ReceiveFromIronicAgentDriver() + if err != nil { + fmt.Println(time.Now().String()+"rabbitMq.ReceiveFromIronicAgentDriver error:", err.Error()) + errChan <- 1 + return + } + for v := range ch { + go dispatchIronicAgentMqMessage(v.Body) + } + fmt.Println(time.Now().String() + "doReceiveFromIronicAgent.chan closed") + //ch关闭就表示异常 + errChan <- 1 +} + +// ironic-agent/driver 消息派发 +func dispatchIronicAgentMqMessage(msg []byte) { + + logPath, _ := beego.AppConfig.String("log.path") + logger := log.New(logPath + "/bmp-scheduler-from-driver_or_agent.log") + logger.SetStableFields([]string{"method", "uri", "header", "request", "response"}) + //agent过来的消息只有sn,没有requestid,临时生成 + logger.Point("logid", commonUtil.GenerateRandUuid()) + logger.TimeStart("all_t") + logger.TimeStart("self_t") + defer logger.Flush() + defer logger.TimeEnd("self_t") + defer logger.TimeEnd("all_t") + logger.Infof("receive msg from driver/agent: %s", string(msg)) + fmt.Printf(time.Now().String()+"receive msg from driver/agent: %s \n", string(msg)) + event := ironicAgentEvent.CallbackCommandMessage{} + if err := json.Unmarshal(msg, &event); err == nil { + + sn := event.CommandMessage.Sn + if event.Action != "Heart" { + _, err := deviceLogic.GetBySn(logger, sn) + if err != nil { + logger.Warnf("dispatchIronicAgentMqMessage.GetBySn error, sn:%s, error:%s", sn, err.Error()) + return + } + + //logger.Point("region", entity.Region) + //logger.Point("az", entity.Az) + } + + if event.Action == "Ping" { + //尤其是ping指令,很可能因为重试等原因,同时接收到前后两次的响应,导致后面的指令执行两次,所以这里随机sleep一段时间,或者加锁 + num := rand.Int31n(60) + time.Sleep(time.Duration(num) * time.Second) + } + + //接受来自driver的带外检测等信息,如果正确,将设备置为已上架??暂时去掉这个逻辑 + if event.Action == "CheckInitConfig" { + if err := deviceLogic.CheckDevice(logger, event); err != nil { + logger.Warnf("update device manageStatus,reason, sn:%s, error:%s", event.Sn, err.Error()) + return + } + return + } + logger.Point("action", event.Action) + command, err := commandLogic.GetBySnAndActionAndStatus(logger, event.Sn, event.Action, CommandStatus.RUNNING) + if err != nil { + // logger.Warn("dispatchIronicAgentMqMessage GetBySnAndActionAndStatus sql error:", event.Sn, event.Action, err.Error()) + return + } + if command == nil { + return + } + v, _ := json.Marshal(command) + logger.Info("receive driver/agent for command:", string(v)) + processor.ProcessorMap[command.Action].Callback(logger, command, event) + } else { + logger.Warn("unknown format message from agent: ", string(msg)) + } +} diff --git a/bmp-scheduler/scheduler/dispatchIronicApi.go b/bmp-scheduler/scheduler/dispatchIronicApi.go new file mode 100644 index 0000000..1d25d6b --- /dev/null +++ b/bmp-scheduler/scheduler/dispatchIronicApi.go @@ -0,0 +1,87 @@ +package scheduler + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "coding.jd.com/aidc-bmp/bmp-scheduler/apiActor" + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + ironicApiEvent "git.jd.com/cps-golang/ironic-common/ironic/event" + ironicAgentEvent "git.jd.com/cps-golang/ironic-common/ironic/event/command" + log "git.jd.com/cps-golang/log" + beego "github.com/beego/beego/v2/server/web" +) + +func doReceiveFromIronicApi(errChan chan int) { + + fmt.Println(time.Now().String() + "start doReceiveFromIronicApi......") + // defer func() { + // fmt.Println("doReceiveFromIronicApi ch error1 ......") + // errChan <- 1 + // fmt.Println("doReceiveFromIronicApi ch error2 ......") + // }() + + ch, err := rabbitMq.ReceiveFromIronicApi2Scheduler() + if err != nil { + fmt.Println(time.Now().String()+"rabbitMq.ReceiveFromIronicApi2Scheduler error:", err.Error()) + errChan <- 1 + return + } + for v := range ch { + go dispatchIronicApiMqMessage(v.Body) + } + fmt.Println(time.Now().String() + "doReceiveFromIronicApi.chan closed") + //ch关闭就表示异常 + errChan <- 1 +} + +// ironic-api 消息派发 +func dispatchIronicApiMqMessage(msg []byte) { + logPath, _ := beego.AppConfig.String("log.path") + logger := log.New(logPath + "/bmp-scheduler-from-api.log") + logger.SetStableFields([]string{"method", "uri", "header", "request", "response"}) + logger.TimeStart("all_t") + logger.TimeStart("self_t") + defer logger.Flush() + defer logger.TimeEnd("self_t") + defer logger.TimeEnd("all_t") + + event := ironicApiEvent.Event{} + fmt.Println(time.Now(), "receive msg from bmp-openapi: ", string(msg)) + if err := json.Unmarshal(msg, &event); err == nil && event.ClazzName != "" { + //EventUuid就是ironicApide的requestId + logger.Point("logid", event.EventUuid) + logger.Info("receive msg from ironic-api: ", string(msg)) + logger.Point("user_id", event.UserID) + if strings.HasPrefix(event.ClazzName, "com.jcloud.cps.ironic.event.api") { + + items := strings.Split(event.ClazzName, ".") + msgType := strings.TrimSuffix(items[len(items)-1], "Message") + logger.Point("action", msgType) + logger.Point("event_uuid", event.EventUuid) + if actor, ok := apiActor.ApiActorMap[msgType]; ok { + go actor.Do(logger, event.Body, msgType) + } else { + logger.Warn("unsupported msgtype:", msgType, "msg body:", event.Body) + } + + } else if strings.EqualFold(event.ClazzName, "com.jcloud.cps.ironic.event.command.CallbackCommandMessage") { + //不知道为啥从ironic-api发过来的重试command指令被归类为类似于agent发过来的callback指令,在这里特殊处理一下 + callbackMsg := ironicAgentEvent.CallbackCommandMessage{} + if err := json.Unmarshal([]byte(event.Body), &callbackMsg); err != nil { + logger.Warn("dispatchIronicApiMqMessage.CallbackCommandMessage unmarshal error:", err.Error()) + return + } + if strings.EqualFold(callbackMsg.Action, "start") { + apiActor.GetAndStartFirstCommand(logger, callbackMsg.Sn) + } + + } else { + logger.Warn("unsupported msg from ironic-api, msg:", string(msg)) + } + } else { + fmt.Println(time.Now(), "receive unknown msg from ironic-api: ", string(msg)) + } +} diff --git a/bmp-scheduler/scheduler/scheduler.go b/bmp-scheduler/scheduler/scheduler.go new file mode 100644 index 0000000..d8c4542 --- /dev/null +++ b/bmp-scheduler/scheduler/scheduler.go @@ -0,0 +1,51 @@ +package scheduler + +import ( + "time" + + rabbitMq "coding.jd.com/aidc-bmp/bmp-scheduler/service/rabbit_mq" + "github.com/beego/beego/v2/adapter/toolbox" +) + +//ironic-scheduler模块四种任务请求都在这里做派发 + +// dispatchIronicApi 从ironic-api投递过来的任务请求 +// dispatchIronicAgent 从ironic-agent投递过来的任务请求 +// CheckTimeoutCommandCron 定时任务1,对执行超时的任务做重试等 +// UpdateInstanceStatusCron 定时任务2,执行任务完成/失败后,更新实例状态 + +func Run() { + defer rabbitMq.DestroyTemplate() + // cron1 命令执行超时定时检测任务 + c1 := toolbox.NewTask("checkTimeoutCommand", "0 */1 * * * *", doCheckTimeoutCommandCron) + toolbox.AddTask("checkTimeoutCommand", c1) + + // cron2 命令执行完后实例状态更新任务 + c2 := toolbox.NewTask("updateInstanceStatus", "*/30 * * * * *", doUpdateInstanceStatusCron) + toolbox.AddTask("updateInstanceStatus", c2) + + c3 := toolbox.NewTask("doCleanAuditLogCron", "0 0 */1 * * *", doCleanAuditLogCron) + toolbox.AddTask("doCleanAuditLogCron", c3) + + c4 := toolbox.NewTask("CleanLogCron", "0 5 */1 * * *", doCleanLogCron) + toolbox.AddTask("CleanLogCron", c4) + + toolbox.StartTask() + defer toolbox.StopTask() + + //从ironic-api获取任务 + var ironicApiErrChan chan int = make(chan int, 1) + //从ironic-agent获取任务 + var ironicAgentErrChan chan int = make(chan int, 1) + go doReceiveFromIronicApi(ironicApiErrChan) + go doReceiveFromIronicAgent(ironicAgentErrChan) + for { + select { + case <-ironicApiErrChan: + go doReceiveFromIronicApi(ironicApiErrChan) + case <-ironicAgentErrChan: + go doReceiveFromIronicAgent(ironicAgentErrChan) + } + time.Sleep(10 * time.Second) + } +} diff --git a/bmp-scheduler/scheduler/updateInstanceStatusCron.go b/bmp-scheduler/scheduler/updateInstanceStatusCron.go new file mode 100644 index 0000000..f21e67f --- /dev/null +++ b/bmp-scheduler/scheduler/updateInstanceStatusCron.go @@ -0,0 +1,84 @@ +package scheduler + +import ( + "fmt" + "strings" + "time" + + beego "github.com/beego/beego/v2/server/web" + + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/instanceLogic" + "coding.jd.com/aidc-bmp/bmp-scheduler/service/redis" + "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + log "git.jd.com/cps-golang/log" +) + +func doUpdateInstanceStatusCron() error { + logPath, _ := beego.AppConfig.String("log.path") + logger := log.New(logPath + "/bmp-scheduler-updateInstanceCron.log") + logger.SetStableFields([]string{"method", "uri", "header", "request", "response"}) + logger.TimeStart("all_t") + logger.TimeStart("self_t") + logger.Point("task_type", "UpdateInstanceStatusCron") + //没有requestid,临时生成 + logger.Point("logid", commonUtil.GenerateRandUuid()) + defer logger.Flush() + defer logger.TimeEnd("self_t") + defer logger.TimeEnd("all_t") + + key := "SchedulerLock:cps-ironic:update_instance_status_cron" + is_set, err := redis.SetNxObjectToRedis(key, "1", 60) + if err != nil { + logger.Warn("CheckTimeoutCommand SetNxObjectToRedis error:", key, err.Error()) + } + if is_set { + check_instances, err := redis.Keys(fmt.Sprintf("%s*", Constants.REDIS_KEY_CHECK)) + if err != nil { + logger.Warn("redis.Keys command error:", err.Error()) + } + logger.Info("check_instances is:", check_instances) + for _, key_check_instance := range check_instances { + check_parts := strings.Split(key_check_instance, ":") + if len(check_parts) < 2 { + logger.Warn("invalid check key:", key_check_instance) + continue + } + instance_id := check_parts[1] + instance_key := fmt.Sprintf("%s:%s", Constants.REDIS_KEY_INSTANCE, instance_id) + r, err := redis.Keys(instance_key) + + if err != nil { + logger.Warn("redis.Keys command error:", instance_id, err.Error()) + } + if len(r) > 0 { //Constants.REDIS_KEY_INSTANCE_instance_id 存在时,说明命令还没执行完,本次不操作,等待下一次cron + continue + } + instance_entity, err := instanceLogic.GetByInstanceId(logger, instance_id) + if err != nil { + logger.Warn("GetByInstanceId error:", instance_id, err.Error()) + continue + } + + status, err := redis.GetObjectFromRedis(key_check_instance) + if err != nil { + logger.Warn("GetObjectFromRedis error:", key_check_instance, err.Error()) + continue + } + instance_entity.Status = strings.ToLower(status) + instance_entity.UpdatedTime = int(time.Now().Unix()) + if err := instanceDao.UpdateInstanceById(logger, instance_entity); err != nil { + logger.Warn("UpdateInstanceById sql error:", instance_id, err.Error()) + continue + } + + if err := redis.DelObjectFromRedis([]string{key_check_instance}); err != nil { + logger.Warn("DelObjectFromRedis error:", key_check_instance, err.Error()) + continue + } + logger.Infof("changed instanceId:%s to status: %s success", instance_id, status) + } + } + return nil +} diff --git a/bmp-scheduler/service/email/email.go b/bmp-scheduler/service/email/email.go new file mode 100644 index 0000000..978468f --- /dev/null +++ b/bmp-scheduler/service/email/email.go @@ -0,0 +1,77 @@ +package email + +import ( + "bytes" + "crypto/tls" + "errors" + "fmt" + "html/template" + "time" + + "github.com/go-gomail/gomail" +) + +type EmailConfig struct { + Host string + Port int + Username string + Password string + From string +} + +var from string //发件人 + +var d *gomail.Dialer + +func InitEmailConfig(c EmailConfig) error { + d = gomail.NewDialer(c.Host, c.Port, c.Username, c.Password) + from = c.From + return nil +} + +// SendMail use smtp to send mail +func SendMail(subject, msg string, receivers []string) error { + m := gomail.NewMessage() + m.SetHeader("From", from) + m.SetHeader("To", receivers...) + m.SetHeader("Subject", subject) + m.SetBody("text/html", msg) + + if d == nil { + return errors.New("Initialize Dialer Error") + } + + d.TLSConfig = &tls.Config{ServerName: d.Host, InsecureSkipVerify: true} + + // Send the email. + if err := d.DialAndSend(m); err != nil { + fmt.Println(time.Now(), "SendMail msg=", msg, err.Error()) + return err + } + return nil +} + +//本机对smtp.jd.local:25邮件服务没有访问权限,所以邮件投递能否成功没有测试 +//SendMailByTpl send template mail +func SendMailByTpl(tplName, subject string, obj interface{}, receivers []string) error { + tpl, errParse := template.New("Mail").Parse(tplName) + if errParse != nil { + fmt.Printf("Parse Template Error:%s\n", errParse.Error()) + return errParse + } + + byteW := new(bytes.Buffer) + err := tpl.Execute(byteW, obj) + if err != nil { + fmt.Println(time.Now(), "Execute Template Error:", err.Error()) + return err + } + + errMail := SendMail(subject, byteW.String(), receivers) + if errMail != nil { + fmt.Println(time.Now(), "Send Mail Error:", errMail.Error()) + return errMail + } + + return nil +} diff --git a/bmp-scheduler/service/rabbit_mq/consumer.go b/bmp-scheduler/service/rabbit_mq/consumer.go new file mode 100644 index 0000000..3114057 --- /dev/null +++ b/bmp-scheduler/service/rabbit_mq/consumer.go @@ -0,0 +1,86 @@ +package rabbit_mq + +import ( + "errors" + "fmt" + "time" + + "github.com/streadway/amqp" +) + +//消费从openapi投递过来的msg +func ReceiveFromIronicApi2Scheduler() (<-chan amqp.Delivery, error) { + + if ironicChannel == nil { + return nil, errors.New("ironicChannel is nil") + } + q, err := queueDeclare(ironicChannel, API_TO_SCHEDULER_QUEUE_NAME) + if err != nil { + return nil, err + } + if err := queueBind(ironicChannel, q.Name, API_TO_SCHEDULER_ROUTING_KEY, IRONIC_EXCHANGE); err != nil { + return nil, err + } + msgChan, err := doConsume(ironicChannel, q.Name) + if err != nil { + return nil, err + } + return msgChan, nil +} + +//消费从agent/dhcp-agent投递过来的回执msg +func ReceiveFromIronicAgentDriver() (<-chan amqp.Delivery, error) { + + if ironicChannel == nil { + return nil, errors.New("ironicChannel is nil") + } + + q, err := queueDeclare(ironicChannel, SCHEDULER_QUEUE_NAME) + if err != nil { + fmt.Println(time.Now(), "queueDeclare error:", err.Error()) + return nil, err + } + if err := queueBind(ironicChannel, q.Name, SCHEDULER_ROUTING_KEY, IRONIC_EXCHANGE); err != nil { + fmt.Println(time.Now(), "queueBind error:", err.Error()) + return nil, err + } + msgChan, err := doConsume(ironicChannel, q.Name) + if err != nil { + fmt.Println(time.Now(), "doConsume error:", err.Error()) + return nil, err + } + return msgChan, nil +} + +func queueDeclare(ch *amqp.Channel, queueName string) (amqp.Queue, error) { + return ch.QueueDeclare( + queueName, // name + true, // durable + false, // delete when unused + false, // exclusive + false, // no-wait + nil, // arguments + ) +} + +func queueBind(ch *amqp.Channel, queueName, routing_key, exchange string) error { + return ch.QueueBind( + queueName, // queue name + routing_key, // routing key + exchange, // exchange + false, + nil, + ) +} + +func doConsume(ch *amqp.Channel, queueName string) (<-chan amqp.Delivery, error) { + return ch.Consume( + queueName, // queue + "", // consumer + true, // auto ack + false, // exclusive + false, // no local + false, // no wait + nil, // args + ) +} diff --git a/bmp-scheduler/service/rabbit_mq/producer.go b/bmp-scheduler/service/rabbit_mq/producer.go new file mode 100644 index 0000000..adbf54b --- /dev/null +++ b/bmp-scheduler/service/rabbit_mq/producer.go @@ -0,0 +1,42 @@ +package rabbit_mq + +import ( + "fmt" + "time" + + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" + "github.com/streadway/amqp" +) + +//发送给agent/driver +func SendToAgent(routing_key string, message interface{}) error { + queueDeclare(ironicChannel, routing_key) + queueBind(ironicChannel, routing_key, routing_key, IRONIC_EXCHANGE) + return doPublish(ironicChannel, IRONIC_EXCHANGE, routing_key, message) +} + +//发送给dhcp-agent +func SendToAgent4Topic(routing_key string, message interface{}) error { + queueDeclare(ironic4TopicChannel, routing_key) + queueBind(ironic4TopicChannel, routing_key, routing_key, IRONIC_4TOPIC_EXCHANGE) + return doPublish(ironic4TopicChannel, IRONIC_4TOPIC_EXCHANGE, routing_key, message) +} + +func doPublish(c *amqp.Channel, exchangeName string, routingKey string, val interface{}) (err error) { + msg, err := commonUtil.Convert2String(val) + if err != nil { + return err + } + err = c.Publish( + exchangeName, // exchange + routingKey, // routing key + false, // mandatory + false, // immediate + amqp.Publishing{ + ContentType: "application/json", + Body: []byte(msg), + }) + + fmt.Println(time.Now(), "scheduler publish to mq success, msg info:", "exchangeName:", exchangeName, "routingKey:", routingKey, "msg:", msg) + return +} diff --git a/bmp-scheduler/service/rabbit_mq/rabbit_mq.go b/bmp-scheduler/service/rabbit_mq/rabbit_mq.go new file mode 100644 index 0000000..34d9223 --- /dev/null +++ b/bmp-scheduler/service/rabbit_mq/rabbit_mq.go @@ -0,0 +1,318 @@ +package rabbit_mq + +import ( + "fmt" + "time" + + "github.com/streadway/amqp" +) + +const ( + //********************ironic******************** + IRONIC_EXCHANGE = "CPS_IRONIC_SCHEDULER" + IRONIC_EXCHANGE_TYPE = "direct" + SCHEDULER_QUEUE_NAME = "CPS_IRONIC_SCHEDULER" + SCHEDULER_ROUTING_KEY = "CPS_IRONIC_SCHEDULER" + + IRONIC_4TOPIC_EXCHANGE = "BMP_SCHEDULER_TOPIC" + IRONIC_4TOPIC_EXCHANGE_TYPE = "topic" + + API_TO_SCHEDULER_QUEUE_NAME = "CPS_IRONIC_API_TO_SCHEDULER" + API_TO_SCHEDULER_ROUTING_KEY = "CPS_IRONIC_INNER_ROUTING_KEY" + + //********************openapi******************** + OPENAPI_EXCHANGE = "CPS_OPENAPI_EXCHANGE" + OPENAPI_EXCHANGE_TYPE = "direct" + + OPENAPI_CALLBACK_QUEUE_NAME = "CPS_OPENAPI_CALLBACK_QUEUE" + OPENAPI_CALLBACK_ROUTING_KEY = "CPS_OPENAPI_CALLBACK_ROUTING_KEY" +) + +var ( + openapiUrl string + ironicUrl string + + ironicConn *amqp.Connection + ironicChannel *amqp.Channel + + ironic4TopicConn *amqp.Connection + ironic4TopicChannel *amqp.Channel + + openapiConn *amqp.Connection + openapiChannel *amqp.Channel +) + +func DestroyTemplate() { + ironicChannel.Close() + ironicConn.Close() + ironic4TopicChannel.Close() + ironic4TopicConn.Close() + openapiChannel.Close() + openapiConn.Close() +} + +//连接保活,断开时重连 +func keepAliveConn() error { + + var ironicCloseChan chan *amqp.Error + var ironic4TopicCloseChan chan *amqp.Error + var openapiCloseChan chan *amqp.Error + var ironicNotifyClose chan *amqp.Error + var ironic4TopicNotifyClose chan *amqp.Error + var openapiNotifyClose chan *amqp.Error + + for { + + if ironicConn == nil || ironicConn.IsClosed() { //连接已断开,需要重连 + fmt.Printf(time.Now().String() + "ironic conn is closed\n") + //新建连接和信道 + if err := InitIronicMq(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitIronicMq error:%s\n", err.Error()) + goto END + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitIronicMq success\n") + } + } + if ironic4TopicConn == nil || ironic4TopicConn.IsClosed() { //连接已断开,需要重连 + fmt.Printf(time.Now().String() + "ironic conn is closed\n") + //新建连接和信道 + if err := InitIronic4TopicMq(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitIronic4TopicMq error:%s\n", err.Error()) + goto END + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitIronic4TopicMq success\n") + } + } + if openapiConn == nil || openapiConn.IsClosed() { //连接已断开,需要重连 + fmt.Printf(time.Now().String() + "ironic conn is closed\n") + //新建连接和信道 + if err := InitOpenapiMq(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitOpenapiMq error:%s\n", err.Error()) + goto END + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitOpenapiMq success\n") + } + } + + ironicCloseChan = make(chan *amqp.Error, 1) + ironic4TopicCloseChan = make(chan *amqp.Error, 1) + openapiCloseChan = make(chan *amqp.Error, 1) + ironicNotifyClose = ironicChannel.NotifyClose(ironicCloseChan) //一旦消费者的channel有错误,产生一个amqp.Error,channel监听并捕捉到这个错误 + ironic4TopicNotifyClose = ironic4TopicChannel.NotifyClose(ironic4TopicCloseChan) + openapiNotifyClose = openapiChannel.NotifyClose(openapiCloseChan) + select { + case <-ironicNotifyClose: + fmt.Printf(time.Now().String() + "ironic channel error\n") + if ironicConn == nil || ironicConn.IsClosed() { //连接已断开,需要重连 + fmt.Printf(time.Now().String() + "ironic conn is closed\n") + time.Sleep(5 * time.Second) + //新建连接和信道 + if err := InitIronicMq(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitIronicMq error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitIronicMq success\n") + } + + } else { //连接还在,只是信道异常,需要获取新信道 + fmt.Printf(time.Now().String() + "ironic conn is open but channel is bad\n") + time.Sleep(5 * time.Second) + //获取新信道 + if err := InitIronicMqForNewChannel(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitIronicMqForNewChannel error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitIronicMqForNewChannel success\n") + } + } + case <-ironic4TopicNotifyClose: + fmt.Printf(time.Now().String() + "ironic4topic channel error\n") + if ironic4TopicConn == nil || ironic4TopicConn.IsClosed() { //连接已断开,需要重连 + fmt.Printf(time.Now().String() + "ironic4topic conn is closed\n") + time.Sleep(5 * time.Second) + //新建连接和信道 + if err := InitIronic4TopicMq(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitIronic4topicMq error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitIronic4topicMq success\n") + } + + } else { //连接还在,只是信道异常,需要获取新信道 + fmt.Printf(time.Now().String() + "ironic4topic conn is open but channel is bad\n") + time.Sleep(5 * time.Second) + //获取新信道 + if err := InitIronic4TopicMqForNewChannel(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitIronic4TopicMqForNewChannel error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitIronic4TopicMqForNewChannel success\n") + } + } + case <-openapiNotifyClose: + + fmt.Printf(time.Now().String() + "openapi channel error\n") + if openapiConn == nil || openapiConn.IsClosed() { //连接已断开,需要重连 + fmt.Printf(time.Now().String() + "openapi conn is closed\n") + time.Sleep(5 * time.Second) + //新建连接和信道 + if err := InitOpenapiMq(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitOpenapiMq error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitOpenapiMq success\n") + } + + } else { //连接还在,只是信道异常,需要获取新信道 + fmt.Printf(time.Now().String() + "openapi conn is open but channel is bad\n") + time.Sleep(5 * time.Second) + //获取新信道 + if err := InitOpenapiMqForNewChannel(); err != nil { + fmt.Printf(time.Now().String()+"keepAliveConn.InitOpenapiMqForNewChannel error:%s\n", err.Error()) + } else { + fmt.Printf(time.Now().String() + "keepAliveConn.InitOpenapiMqForNewChannel success\n") + } + } + } + END: + fmt.Printf(time.Now().String() + "keepAliveConn once done\n") + time.Sleep(10 * time.Second) + } + +} + +//exchange receive_routing_key 用于ironicmq +func InitMqTemplate(openapi string, ironic string) (err error) { + + openapiUrl = openapi + ironicUrl = ironic + + if err := InitIronicMq(); err != nil { + fmt.Printf(time.Now().String()+" InitIronicMq error:%s\n", err.Error()) + //return err + } + if err := InitOpenapiMq(); err != nil { + fmt.Printf(time.Now().String()+" InitOpenapiMq error:%s\n", err.Error()) + //return err + } + if err := InitIronic4TopicMq(); err != nil { + fmt.Printf(time.Now().String()+" InitIronic4TopicMq error:%s\n", err.Error()) + //return err + } + + go keepAliveConn() + + //********************ironic-topic*********************** + + return nil +} + +func InitIronic4TopicMq() error { + + var err error + + //********************ironic-direct*********************** + ironic4TopicConn, err = amqp.Dial(ironicUrl) + if err != nil { + return err + } + ironic4TopicChannel, err = ironic4TopicConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(ironic4TopicChannel, IRONIC_4TOPIC_EXCHANGE, IRONIC_4TOPIC_EXCHANGE_TYPE) + if err != nil { + return err + } + return nil +} + +//连接正常,信道异常时,获取新信道 +func InitIronic4TopicMqForNewChannel() error { + + var err error + ironic4TopicChannel, err = ironic4TopicConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(ironic4TopicChannel, IRONIC_4TOPIC_EXCHANGE, IRONIC_4TOPIC_EXCHANGE_TYPE) + if err != nil { + return err + } + return nil +} + +func InitIronicMq() error { + + var err error + + //********************ironic-direct*********************** + ironicConn, err = amqp.Dial(ironicUrl) + if err != nil { + return err + } + ironicChannel, err = ironicConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(ironicChannel, IRONIC_EXCHANGE, IRONIC_EXCHANGE_TYPE) + if err != nil { + return err + } + return nil +} + +//连接正常,信道异常时,获取新信道 +func InitIronicMqForNewChannel() error { + + var err error + ironicChannel, err = ironicConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(ironicChannel, IRONIC_EXCHANGE, IRONIC_EXCHANGE_TYPE) + if err != nil { + return err + } + return nil +} + +func InitOpenapiMq() error { + + var err error + openapiConn, err = amqp.Dial(openapiUrl) + if err != nil { + return err + } + openapiChannel, err = openapiConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(openapiChannel, OPENAPI_EXCHANGE, OPENAPI_EXCHANGE_TYPE) + if err != nil { + return err + } + return nil +} + +//连接正常,信道异常时,获取新信道 +func InitOpenapiMqForNewChannel() error { + + var err error + openapiChannel, err = openapiConn.Channel() + if err != nil { + return err + } + err = exchangeDeclare(openapiChannel, OPENAPI_EXCHANGE, OPENAPI_EXCHANGE_TYPE) + if err != nil { + return err + } + return nil +} + +func exchangeDeclare(ch *amqp.Channel, exchange, topicType string) error { + return ch.ExchangeDeclare( + exchange, // name + topicType, // type + true, // durable + false, // auto-deleted + false, // internal + false, // no-wait + nil, // arguments + ) +} diff --git a/bmp-scheduler/service/redis/redis.go b/bmp-scheduler/service/redis/redis.go new file mode 100644 index 0000000..dfcac91 --- /dev/null +++ b/bmp-scheduler/service/redis/redis.go @@ -0,0 +1,289 @@ +package redis + +import ( + "sync" + "time" + + "github.com/go-redis/redis" +) + +var redisMonitorNamespace string + +var redisOnce sync.Once + +type redisUtil struct { + *redis.Client +} + +// RedisUtil singleton redis util +var RedisUtil *redisUtil + +// InitRedis initial redisUtil instance +func InitRedis(namespace, addr, passwd string, db int) error { + redisOnce.Do(func() { + if RedisUtil == nil { + + RedisUtil = &redisUtil{ + redis.NewClient(&redis.Options{ + Addr: addr, + Password: passwd, // no password set + DB: db, // use default DB + }), + } + + redisMonitorNamespace = namespace + + } + }) + return RedisUtil.Ping().Err() +} + +// SetObjectToRedisWithExpire set string object with a expiration +func SetObjectToRedisWithExpire(key, value string, sec int) error { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + err := RedisUtil.Set(fullKey, value, time.Second*time.Duration(sec)).Err() + if err != nil { + return err + } + + return nil +} + +// SetObjectToRedis set object to Redis +func SetObjectToRedis(key string, value string) error { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + err := RedisUtil.Set(fullKey, value, 0).Err() + if err != nil { + return err + } + + return nil +} + +// SetObjectToRedis set object to Redis +func SetNxObjectToRedis(key string, value string, expire int) (bool, error) { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + return RedisUtil.SetNX(fullKey, value, time.Second*time.Duration(expire)).Result() +} + +func Keys(key string) ([]string, error) { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + return RedisUtil.Keys(fullKey).Result() +} + +// GetObjectFromRedis Get object from Redis +func GetObjectFromRedis(key string) (string, error) { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + ret, err := RedisUtil.Get(fullKey).Result() + if err != nil { + return "", err + } + + return ret, nil +} + +func DelObjectFromRedis(keys []string) error { + + if len(keys) <= 0 { + return nil + } + + var fullKeys []string + for _, v := range keys { + if v != "" { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = v + } else { + fullKey = redisMonitorNamespace + if v != "" { + fullKey = redisMonitorNamespace + ":" + v + } + } + fullKeys = append(fullKeys, fullKey) + } + } + + if len(fullKeys) > 0 { + err := RedisUtil.Del(fullKeys...).Err() + if err != nil { + return err + } + } + + return nil +} + +// HSetObjectToRedis hash set object to Redis +func HSetObjectToRedis(key, field, value string) error { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + err := RedisUtil.HSet(fullKey, field, value).Err() + if err != nil { + return err + } + + return nil +} + +// HGetObjectFromRedis hash get from redis +func HGetObjectFromRedis(key, field string) (string, error) { + + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + ret, err := RedisUtil.HGet(fullKey, field).Result() + if err != nil { + return "", err + } + return ret, nil +} + +func HDelObjectFromRedis(key string, fields []string) error { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + if len(fields) <= 0 { + return nil + } + + err := RedisUtil.HDel(fullKey, fields...).Err() + + if err != nil { + return err + } + return nil +} + +func SaddObjectToRedis(key string, members []interface{}) error { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + if len(members) <= 0 { + return nil + } + + err := RedisUtil.SAdd(fullKey, members...).Err() + + if err != nil { + return err + } + return nil +} + +func SremObjectFromRedis(key string, members []interface{}) error { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + if len(members) <= 0 { + return nil + } + + err := RedisUtil.SRem(fullKey, members...).Err() + + if err != nil { + return err + } + return nil +} + +func SmembersFromRedis(key string) ([]string, error) { + var fullKey string + if redisMonitorNamespace == "" { + fullKey = key + } else { + fullKey = redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + } + + members, err := RedisUtil.SMembers(fullKey).Result() + + if err != nil { + return nil, err + } + return members, nil +} diff --git a/bmp-scheduler/service/sdn_api/sdn_api.go b/bmp-scheduler/service/sdn_api/sdn_api.go new file mode 100644 index 0000000..5210792 --- /dev/null +++ b/bmp-scheduler/service/sdn_api/sdn_api.go @@ -0,0 +1,33 @@ +package sdn_api + +const ( + CREATE_SDN_INSTANCE = "http://%s/cps/createbm" + DELETE_SDN_INSTANCE = "http://%s/cps/delbm" + BINDING_SUBNET = "http://%s/cps/bindsub" + UNBINDING_SUBNET = "http://%s/cps/unbindsub" + BINDING_EIP = "http://%s/cps/bindeip" + UNBINDING_EIP = "http://%s/cps/unbindeip" + GET_SUBNET = "http://%s/search/getvnet" + GET_SUBNET_IP_STOCK = "http://%s/search/getvnetcidr" + GET_EIP = "http://%s/search/eipinfo" + QUERY_ALIAS_IP = "http://%s/plugin/getalias" + QUERY_INSTANCE_EIPS = "http://%s/plugin/getalog" + BATCH_ADD_ALIAS_IP = "http://%s/plugin/batchalias" + DELETE_ALIAS_IP = "http://%s/plugin/delalias" + ASSIGN_BM_IPV6_ADDRESS = "http://%s/ipv6/assignbmipv6address" + GET_VPC = "http://%s/search/vpcinfo" +) + +type Cfg struct { + Ip string + Nameservers []string +} + +var SdnProperties = map[string]Cfg{} + +func InitSdnApiConfig(c map[string]Cfg) error { + for k, v := range c { + SdnProperties[k] = v + } + return nil +} diff --git a/bmp-scheduler/template/AbstractRetailCreateInstanceTemplate.go b/bmp-scheduler/template/AbstractRetailCreateInstanceTemplate.go new file mode 100644 index 0000000..48d0355 --- /dev/null +++ b/bmp-scheduler/template/AbstractRetailCreateInstanceTemplate.go @@ -0,0 +1,127 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + log "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +type AbstractRetailCreateInstanceTemplate struct { + createSetNetworkCommand func(*gorm.DB, string, string, string, int64, string) (int64, error) +} + +func (b AbstractRetailCreateInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, make_partitions bool, image_format string, task string) { + + logger.Info("AbstractRetailCreateInstanceTemplate start,", request_id, instance_id, sn, make_partitions, image_format) + var err error + var id int64 + tx := dao.GetGormTx(logger) + tx.Begin() + logger.Info("start insert command ", instance_id) + if id, err = CreateCommand(tx, CommandAction.DHCPConfigAddHost.Name, CommandType.DRIVER, + request_id, instance_id, sn, 0, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.DHCPConfigAddHost.Name, err.Error()) + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetPXEBoot.Name, CommandType.DRIVER, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.SetPXEBoot.Name, err.Error()) + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.Ping.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.Ping.Name, err.Error()) + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.MakeRaid.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.MakeRaid.Name, err.Error()) + goto ROLLBACK + } + if Constants.TAR_IMAGE == image_format { + if make_partitions { + if id, err = CreateCommand(tx, CommandAction.MakePartitions.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.MakePartitions.Name, err.Error()) + goto ROLLBACK + } + } + if id, err = CreateCommand(tx, CommandAction.WriteImageTar.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.WriteImageTar.Name, err.Error()) + goto ROLLBACK + } + } else { + if id, err = CreateCommand(tx, CommandAction.WriteImage.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.WriteImage.Name, err.Error()) + goto ROLLBACK + } + if make_partitions { + if id, err = CreateCommand(tx, CommandAction.Qcow2MakePartitions.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.Qcow2MakePartitions.Name, err.Error()) + goto ROLLBACK + } + } + } + if id, err = CreateCommand(tx, CommandAction.SetHostname.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.SetHostname.Name, err.Error()) + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetKeypairs.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.SetKeypairs.Name, err.Error()) + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetPassword.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.SetPassword.Name, err.Error()) + goto ROLLBACK + } + // TODO 暂时注释 + if id, err = b.createSetNetworkCommand(tx, request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", "createSetNetworkCommand", err.Error()) + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetUserCmd.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.SetUserCmd.Name, err.Error()) + goto ROLLBACK + } + // if id, err = CreateCommand(tx, CommandAction.UploadSystemLog.Name, CommandType.AGENT, + // request_id, instance_id, sn, id, task); err != nil { + // logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.UploadSystemLog.Name, err.Error()) + // goto ROLLBACK + // } + // id, err = CreateCommand(tx, CommandAction.SaveSwitchConfig.Name, CommandType.NETWORK, + // request_id, instance_id, sn, id); + // + // id, err = CreateCommand(tx, CommandAction.SaveConfigToFtpServer.Name, CommandType.NETWORK, + // request_id, instance_id, sn, id); + if id, err = CreateCommand(tx, CommandAction.SetDISKBoot.Name, CommandType.DRIVER, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.SetDISKBoot.Name, err.Error()) + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.DHCPConfigDelHost.Name, CommandType.DRIVER, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.DHCPConfigDelHost.Name, err.Error()) + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.PowerCycle.Name, CommandType.DRIVER, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.PowerCycle.Name, err.Error()) + goto ROLLBACK + } + tx.Commit() + logger.Infof("AbstractRetailCreateInstanceTemplate success, instanceId:%s", instance_id) + return +ROLLBACK: + tx.Rollback() + logger.Warnf("AbstractRetailCreateInstanceTemplate failed, instanceId:%s", instance_id) +} diff --git a/bmp-scheduler/template/AbstractRetailReinstallInstanceTemplate.go b/bmp-scheduler/template/AbstractRetailReinstallInstanceTemplate.go new file mode 100644 index 0000000..80d159b --- /dev/null +++ b/bmp-scheduler/template/AbstractRetailReinstallInstanceTemplate.go @@ -0,0 +1,106 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + log "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +type AbstractRetailReinstallInstanceTemplate struct { + createSetNetworkCommand func(*gorm.DB, string, string, string, int64, string) (int64, error) +} + +func (b AbstractRetailReinstallInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, keep_data, make_partitions bool, image_format string, task string) { + logger.Info("AbstractRetailReinstallInstanceTemplate start,", request_id, instance_id, sn, keep_data, make_partitions, image_format) + var err error + var id int64 + tx := dao.GetGormTx(logger) + tx.Begin() + + if id, err = CreateCommand(tx, CommandAction.DHCPConfigAddHost.Name, CommandType.DRIVER, request_id, instance_id, sn, 0, task); err != nil { + goto ROLLBACK + } + + if id, err = CreateCommand(tx, CommandAction.SetPXEBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + if id, err = CreateCommand(tx, CommandAction.Ping.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if keep_data { + if id, err = CreateCommand(tx, CommandAction.InitRootDevice.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } else { + if id, err = CreateCommand(tx, CommandAction.CleanBlockDevice.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.MakeRaid.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } + make_partitions = true //不管是自定义分区还是默认分区,都是true + if Constants.TAR_IMAGE == image_format { + + if make_partitions { + if id, err = CreateCommand(tx, CommandAction.MakePartitions.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } + if id, err = CreateCommand(tx, CommandAction.WriteImageTar.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } else { + if id, err = CreateCommand(tx, CommandAction.WriteImage.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if make_partitions { + if id, err = CreateCommand(tx, CommandAction.Qcow2MakePartitions.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } + } + if id, err = CreateCommand(tx, CommandAction.SetHostname.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + if id, err = CreateCommand(tx, CommandAction.SetKeypairs.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + if id, err = CreateCommand(tx, CommandAction.SetPassword.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + //TODO 暂时注释 + if id, err = b.createSetNetworkCommand(tx, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetUserCmd.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + // if id, err = CreateCommand(tx, CommandAction.UploadSystemLog.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + // goto ROLLBACK + // } + if id, err = CreateCommand(tx, CommandAction.SetDISKBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.DHCPConfigDelHost.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.PowerCycle.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Infof("AbstractRetailReinstallInstanceTemplate success, instanceId: %s", instance_id) + return +ROLLBACK: + tx.Rollback() + logger.Warnf("AbstractRetailReinstallInstanceTemplate failed, instanceId: %s", instance_id) +} diff --git a/bmp-scheduler/template/AbstractSDNCreateInstanceTemplate.go b/bmp-scheduler/template/AbstractSDNCreateInstanceTemplate.go new file mode 100644 index 0000000..1924516 --- /dev/null +++ b/bmp-scheduler/template/AbstractSDNCreateInstanceTemplate.go @@ -0,0 +1,109 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + log "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +type AbstractSDNCreateInstanceTemplate struct { + createSetNetworkCommand func(*gorm.DB, string, string, string, int64, string) (int64, error) +} + +func (b AbstractSDNCreateInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, make_partitions bool, image_format string, task string) { + + logger.Info("AbstractSDNCreateInstanceTemplate start,", request_id, instance_id, sn, make_partitions, image_format) + var err error + var id int64 + tx := dao.GetGormTx(logger) + tx.Begin() + + if id, err = CreateCommand(tx, CommandAction.SDNRegister.Name, CommandType.SDN, request_id, instance_id, sn, 0, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetPXEBoot.Name, CommandType.DRIVER, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.MakeRaid.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + if Constants.TAR_IMAGE == image_format { + if make_partitions { + if id, err = CreateCommand(tx, CommandAction.MakePartitions.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } + if id, err = CreateCommand(tx, CommandAction.WriteImageTar.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } else { + if id, err = CreateCommand(tx, CommandAction.WriteImage.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + if make_partitions { + if id, err = CreateCommand(tx, CommandAction.Qcow2MakePartitions.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } + } + if id, err = CreateCommand(tx, CommandAction.SetHostname.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetPassword.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = b.createSetNetworkCommand(tx, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetUserCmd.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetKeypairs.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + // if id, err = CreateCommand(tx, CommandAction.UploadSystemLog.Name, CommandType.AGENT, + // request_id, instance_id, sn, id, task); err != nil { + // goto ROLLBACK + // } + if id, err = CreateCommand(tx, CommandAction.SDNSubnetBinding.Name, CommandType.SDN, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SDNEipBinding.Name, CommandType.SDN, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SDNAddAliasIP.Name, CommandType.SDN, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetDISKBoot.Name, CommandType.DRIVER, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if _, err = CreateCommand(tx, CommandAction.PowerCycle.Name, CommandType.DRIVER, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Point("AbstractSDNCreateInstanceTemplate_status", "finish") + +ROLLBACK: + tx.Rollback() + logger.Point("AbstractSDNCreateInstanceTemplate_status", "failed") +} diff --git a/bmp-scheduler/template/AbstractSDNReinstallInstanceTemplate.go b/bmp-scheduler/template/AbstractSDNReinstallInstanceTemplate.go new file mode 100644 index 0000000..c3c3054 --- /dev/null +++ b/bmp-scheduler/template/AbstractSDNReinstallInstanceTemplate.go @@ -0,0 +1,94 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + log "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +type AbstractSDNReinstallInstanceTemplate struct { + createSetNetworkCommand func(*gorm.DB, string, string, string, int64, string) (int64, error) +} + +func (b AbstractSDNReinstallInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, keep_data, make_partitions bool, image_format string, task string) { + + var err error + var id int64 + tx := dao.GetGormTx(logger) + tx.Begin() + + if id, err = CreateCommand(tx, CommandAction.SDNSubnetUnBinding.Name, CommandType.SDN, request_id, instance_id, sn, 0, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetPXEBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if keep_data { + if id, err = CreateCommand(tx, CommandAction.InitRootDevice.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } else { + if id, err = CreateCommand(tx, CommandAction.CleanBlockDevice.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.MakeRaid.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } + if Constants.TAR_IMAGE == image_format { + if make_partitions { + if id, err = CreateCommand(tx, CommandAction.MakePartitions.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } + if id, err = CreateCommand(tx, CommandAction.WriteImageTar.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } else { + if id, err = CreateCommand(tx, CommandAction.WriteImage.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if make_partitions { + if id, err = CreateCommand(tx, CommandAction.Qcow2MakePartitions.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } + } + if id, err = CreateCommand(tx, CommandAction.SetHostname.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetPassword.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = b.createSetNetworkCommand(tx, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetUserCmd.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetKeypairs.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + // if id, err = CreateCommand(tx, CommandAction.UploadSystemLog.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + // goto ROLLBACK + // } + if id, err = CreateCommand(tx, CommandAction.SDNSubnetBinding.Name, CommandType.SDN, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetDISKBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if _, err = CreateCommand(tx, CommandAction.PowerCycle.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Point("AbstractSDNReinstallInstanceTemplate_status", "finish") + +ROLLBACK: + tx.Rollback() + logger.Point("AbstractSDNReinstallInstanceTemplate_status", "failed") +} diff --git a/bmp-scheduler/template/AbstractTemplate.go b/bmp-scheduler/template/AbstractTemplate.go new file mode 100644 index 0000000..e345a9a --- /dev/null +++ b/bmp-scheduler/template/AbstractTemplate.go @@ -0,0 +1,34 @@ +package template + +import ( + "fmt" + "time" + + commandDao "coding.jd.com/aidc-bmp/bmp-scheduler/dao/commandDao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandStatus" + "github.com/jinzhu/gorm" +) + +func CreateCommand(tx *gorm.DB, action, command_type, request_id, instance_id, sn string, parent_command_id int64, task string) (int64, error) { + entity := &commandDao.Command{ + RequestID: request_id, + Sn: sn, + Action: action, + Type: command_type, + Task: task, + InstanceID: instance_id, + Status: CommandStatus.WAIT, + ExecuteCount: 0, + TimeoutTime: time.Now(), + ParentCommandID: parent_command_id, + CreatedTime: int(time.Now().Unix()), + UpdatedTime: int(time.Now().Unix()), + } + + err := tx.Create(entity).Error + if err != nil { + fmt.Println("插入command error", err.Error(), int64(entity.ID)) + } + + return int64(entity.ID), err +} diff --git a/bmp-scheduler/template/BasicCreateInstanceTemplate.go b/bmp-scheduler/template/BasicCreateInstanceTemplate.go new file mode 100644 index 0000000..f6f28af --- /dev/null +++ b/bmp-scheduler/template/BasicCreateInstanceTemplate.go @@ -0,0 +1,146 @@ +package template + +import ( + "fmt" + + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/raidDao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" +) + +type BasicCreateInstanceTemplate struct{} + +func (b BasicCreateInstanceTemplate) accept(network_type, interface_mode string) bool { + return NetworkType.BASIC == network_type +} + +func (b BasicCreateInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, make_partitions bool, image_format string, task string) { + + logger.Info("BasicCreateInstanceTemplate start", request_id, instance_id, sn) + var err error + var id int64 + var raid *raidDao.Raid + tx := dao.GetGormTx(logger) + tx.Begin() + instance, err := instanceDao.GetInstanceByUuid(logger, instance_id) + if err != nil { + logger.Warn("create instance err,get instance err:", instance_id+err.Error()) + return + } + + if id, err = CreateCommand(tx, CommandAction.DHCPConfigAddHost.Name, CommandType.DRIVER, request_id, instance_id, sn, 0, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetPXEBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.Ping.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if instance.SystemVolumeRaidID != "" { + raid, err = raidDao.GetRaidByUuid(logger, instance.SystemVolumeRaidID) + if err != nil { + logger.Warn("create instance err,get raid by systemVolumeRaidId err:", instance.SystemVolumeRaidID+err.Error()) + return + } + if raid.Name != "NORAID" { //如果是NORAID,不执行raid动作 + if id, err = CreateCommand(tx, CommandAction.MakeRaid.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } + } + + if id, err = CreateCommand(tx, "InitNode", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.MakePartitions.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, "FormatPartitions", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, "MountPartitions", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + if id, err = CreateCommand(tx, CommandAction.WriteImageTar.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + //if id, err = CreateCommand(tx, CommandAction.SetHostname.Name, CommandType.AGENT, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + //} + if id, err = CreateCommand(tx, CommandAction.SetPassword.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + //if id, err = CreateCommand(tx, CommandAction.SetNetwork.Name, CommandType.AGENT, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + //} + //if id, err = CreateCommand(tx, CommandAction.SetUserCmd.Name, CommandType.AGENT, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + //} + if id, err = CreateCommand(tx, "SetCloudinitConf", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + if id, err = CreateCommand(tx, "SetMetaData", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, "SetNetwork", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, "SetUserData", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + //if id, err = CreateCommand(tx, CommandAction.UploadSystemLog.Name, CommandType.AGENT, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + //} + if id, err = CreateCommand(tx, CommandAction.DHCPConfigDelHost.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + // if id, err = CreateCommand(tx, CommandAction.CreateVRF.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.CreateVRFBalance.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.CreateVSIInterface.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.CreateVNI.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.CreateVSI.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.AddArpStatic.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.SetBandwidth.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.BindingVSI.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.SaveSwitchConfig.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + if id, err = CreateCommand(tx, CommandAction.SetDISKBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if _, err = CreateCommand(tx, CommandAction.PowerCycle.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + fmt.Println("insert command finished") + logger.Point("BasicCreateInstanceTemplate_status", "finish") + return +ROLLBACK: + tx.Rollback() + logger.Point("BasicCreateInstanceTemplate_status", "failed") +} diff --git a/bmp-scheduler/template/BasicCreateInstanceTemplateForWindows.go b/bmp-scheduler/template/BasicCreateInstanceTemplateForWindows.go new file mode 100644 index 0000000..d381bab --- /dev/null +++ b/bmp-scheduler/template/BasicCreateInstanceTemplateForWindows.go @@ -0,0 +1,142 @@ +package template + +import ( + "fmt" + + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/raidDao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" +) + +type BasicCreateInstanceTemplateForWindows struct{} + +func (b BasicCreateInstanceTemplateForWindows) accept(network_type, interface_mode string) bool { + return NetworkType.BASIC == network_type +} + +func (b BasicCreateInstanceTemplateForWindows) initCommand(logger *log.Logger, request_id, instance_id, sn string, make_partitions bool, image_format string, task string) { + + logger.Info("BasicCreateInstanceTemplate start", request_id, instance_id, sn) + var err error + var id int64 + var raid *raidDao.Raid + tx := dao.GetGormTx(logger) + tx.Begin() + instance, err := instanceDao.GetInstanceByUuid(logger, instance_id) + if err != nil { + logger.Warn("create instance err,get instance err:", instance_id+err.Error()) + return + } + + if err != nil { + logger.Warn("create instance err,get raid by systemVolumeRaidId err:", instance.SystemVolumeRaidID+err.Error()) + return + } + if id, err = CreateCommand(tx, CommandAction.DHCPConfigAddHost.Name, CommandType.DRIVER, request_id, instance_id, sn, 0, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetPXEBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.Ping.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if instance.SystemVolumeRaidID != "" { + raid, err = raidDao.GetRaidByUuid(logger, instance.SystemVolumeRaidID) + if err != nil { + logger.Warn("create instance err,get raid by systemVolumeRaidId err:", instance.SystemVolumeRaidID+err.Error()) + return + } + if raid.Name != "NORAID" { //如果是NORAID,不执行raid动作 + if id, err = CreateCommand(tx, CommandAction.MakeRaid.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } + } + + if id, err = CreateCommand(tx, "InitNode", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + //if id, err = CreateCommand(tx, CommandAction.MakePartitions.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + // goto ROLLBACK + //} + if id, err = CreateCommand(tx, CommandAction.WriteImage.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + //if id, err = CreateCommand(tx, CommandAction.SetHostname.Name, CommandType.AGENT, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + //} + if id, err = CreateCommand(tx, CommandAction.SetPassword.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + //if id, err = CreateCommand(tx, CommandAction.SetNetwork.Name, CommandType.AGENT, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + //} + //if id, err = CreateCommand(tx, CommandAction.SetUserCmd.Name, CommandType.AGENT, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + //} + //if id, err = CreateCommand(tx, "SetCloudinitConf", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + // goto ROLLBACK + //} + //if id, err = CreateCommand(tx, "SetNocloudUserData", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + // goto ROLLBACK + //} + if id, err = CreateCommand(tx, "SetMetaData", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, "SetNetworkWindows", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + //if id, err = CreateCommand(tx, CommandAction.UploadSystemLog.Name, CommandType.AGENT, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + //} + if id, err = CreateCommand(tx, CommandAction.DHCPConfigDelHost.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + // if id, err = CreateCommand(tx, CommandAction.CreateVRF.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.CreateVRFBalance.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.CreateVSIInterface.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.CreateVNI.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.CreateVSI.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.AddArpStatic.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.SetBandwidth.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.BindingVSI.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.SaveSwitchConfig.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + if id, err = CreateCommand(tx, CommandAction.SetDISKBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if _, err = CreateCommand(tx, CommandAction.PowerCycle.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + fmt.Println("insert command finished") + logger.Point("BasicCreateInstanceTemplate_status", "finish") + return +ROLLBACK: + tx.Rollback() + logger.Point("BasicCreateInstanceTemplate_status", "failed") +} diff --git a/bmp-scheduler/template/BasicDeleteInstanceTemplate.go b/bmp-scheduler/template/BasicDeleteInstanceTemplate.go new file mode 100644 index 0000000..24c2740 --- /dev/null +++ b/bmp-scheduler/template/BasicDeleteInstanceTemplate.go @@ -0,0 +1,90 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/raidDao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" +) + +type BasicDeleteInstanceTemplate struct{} + +func (b BasicDeleteInstanceTemplate) accept(network_type string) bool { + return NetworkType.BASIC == network_type +} + +func (b BasicDeleteInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, task string) { + + logger.Info("BasicDeleteInstanceTemplate start", request_id, instance_id, sn) + + var err error + var id int64 + var raid *raidDao.Raid + tx := dao.GetGormTx(logger) + tx.Begin() + + instance, err := instanceDao.GetInstanceByUuid(logger, instance_id) + if err != nil { + logger.Warn("create instance err,get instance err:", instance_id+err.Error()) + return + } + + if id, err = CreateCommand(tx, CommandAction.DHCPConfigAddHost.Name, CommandType.DRIVER, request_id, instance_id, sn, 0, task); err != nil { + goto ROLLBACK + } + + // if id, err = CreateCommand(tx, CommandAction.UnBindingVSI.Name, CommandType.NETWORK, request_id, instance_id, sn, 0); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.CleanArpStatic.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.CleanBandwidth.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.SaveSwitchConfig.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + if id, err = CreateCommand(tx, CommandAction.SetPXEBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.Ping.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.CleanBlockDevice.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if instance.SystemVolumeRaidID != "" { + raid, err = raidDao.GetRaidByUuid(logger, instance.SystemVolumeRaidID) + if err != nil { + logger.Warn("create instance err,get raid by systemVolumeRaidId err:", instance.SystemVolumeRaidID+err.Error()) + return + } + if raid.Name != "NORAID" { //如果是NORAID,不执行raid动作//TODO,待确认销毁的时候要不要cleanraid + id, err = CreateCommand(tx, CommandAction.CleanRaid.Name, CommandType.AGENT, request_id, instance_id, sn, id, task) + if err != nil { + goto ROLLBACK + } + } + } + + //if id, err = CreateCommand(tx, CommandAction.UploadSystemLog.Name, CommandType.AGENT, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + //} + if id, err = CreateCommand(tx, CommandAction.DHCPConfigDelHost.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if _, err = CreateCommand(tx, CommandAction.PowerOff.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Point("BasicDeleteInstanceTemplate_status", "finish") + return +ROLLBACK: + tx.Rollback() + logger.Point("BasicDeleteInstanceTemplate_status", "failed") +} diff --git a/bmp-scheduler/template/BasicReinstallInstanceTemplate.go b/bmp-scheduler/template/BasicReinstallInstanceTemplate.go new file mode 100644 index 0000000..fb377b3 --- /dev/null +++ b/bmp-scheduler/template/BasicReinstallInstanceTemplate.go @@ -0,0 +1,156 @@ +package template + +import ( + "strings" + + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "coding.jd.com/aidc-bmp/bmp-scheduler/dao/instanceDao" + "coding.jd.com/aidc-bmp/bmp-scheduler/logic/osLogic" + "git.jd.com/cps-golang/ironic-common/ironic/common/Constants" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" +) + +type BasicReinstallInstanceTemplate struct{} + +func (b BasicReinstallInstanceTemplate) accept(network_type, interface_mode string) bool { + return NetworkType.BASIC == network_type +} + +func (b BasicReinstallInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, keep_data, make_partitions bool, image_format string, task string) { + + var err error + var id int64 + + instance, err := instanceDao.GetInstanceByUuid(logger, instance_id) + if err != nil { + logger.Warn("create instance err,get instance err:", instance_id+err.Error()) + return + } + + osEntity, err := osLogic.GetOsByInstanceId(logger, instance_id) + if err != nil { + logger.Warnf("BasicReinstallInstanceTemplate.GetOsByInstanceId error, instance_id:%s, err:%s", instance_id, err.Error()) + } + tx := dao.GetGormTx(logger) + tx.Begin() + + // if id, err = CreateCommand(tx, CommandAction.UnBindingVSI.Name, CommandType.NETWORK, request_id, instance_id, sn, 0);err != nil { + // goto ROLLBACK + // } + if id, err = CreateCommand(tx, CommandAction.DHCPConfigAddHost.Name, CommandType.DRIVER, request_id, instance_id, sn, 0, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetPXEBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.Ping.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if !keep_data { + + if id, err = CreateCommand(tx, CommandAction.CleanBlockDevice.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if instance.SystemVolumeRaidID != "" { + if id, err = CreateCommand(tx, CommandAction.MakeRaid.Name, CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } + + } + + if id, err = CreateCommand(tx, "InitNode", CommandType.AGENT, + request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + + } + + if strings.ToLower(image_format) == Constants.TAR_IMAGE { + if make_partitions { + if id, err = CreateCommand(tx, CommandAction.MakePartitions.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, "FormatPartitions", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, "MountPartitions", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } + + if id, err = CreateCommand(tx, CommandAction.WriteImageTar.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } else { + if id, err = CreateCommand(tx, CommandAction.WriteImage.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } + + // if id, err = CreateCommand(tx, CommandAction.SetHostname.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + // goto ROLLBACK + // } + if id, err = CreateCommand(tx, CommandAction.SetPassword.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + // if id, err = CreateCommand(tx, CommandAction.SetNetwork.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.SetUserCmd.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.SetKeypairs.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.UploadSystemLog.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.BindingVSI.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + if id, err = CreateCommand(tx, "SetCloudinitConf", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + if id, err = CreateCommand(tx, "SetMetaData", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + //网络设置 + if osEntity.OsType != "Windows" { + if id, err = CreateCommand(tx, "SetNetwork", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } else { + if id, err = CreateCommand(tx, "SetNetworkWindows", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } + if osEntity.OsType != "Windows" { + if id, err = CreateCommand(tx, "SetUserData", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + } + + if id, err = CreateCommand(tx, CommandAction.SetDISKBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.DHCPConfigDelHost.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if _, err = CreateCommand(tx, CommandAction.PowerCycle.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Point("BasicReinstallInstanceTemplate_status", "finish") + return +ROLLBACK: + tx.Rollback() + logger.Point("BasicReinstallInstanceTemplate_status", "failed") +} diff --git a/bmp-scheduler/template/BasicResetPasswordTemplate.go b/bmp-scheduler/template/BasicResetPasswordTemplate.go new file mode 100644 index 0000000..732a156 --- /dev/null +++ b/bmp-scheduler/template/BasicResetPasswordTemplate.go @@ -0,0 +1,61 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" +) + +type BasicResetPasswordTemplate struct{} + +func (b BasicResetPasswordTemplate) accept(network_type string) bool { + return NetworkType.BASIC == network_type +} + +func (b BasicResetPasswordTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, task string) { + + var err error + var id int64 + tx := dao.GetGormTx(logger) + tx.Begin() + + // if id, err = CreateCommand(tx, CommandAction.UnBindingVSI.Name, CommandType.NETWORK, request_id, instance_id, sn, 0); err != nil { + // goto ROLLBACK + // } + if id, err = CreateCommand(tx, CommandAction.DHCPConfigAddHost.Name, CommandType.DRIVER, request_id, instance_id, sn, 0, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetPXEBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.Ping.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, "InitNode", CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetPassword.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + // if id, err = CreateCommand(tx, CommandAction.UploadSystemLog.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + // goto ROLLBACK + // } + // if id, err = CreateCommand(tx, CommandAction.BindingVSI.Name, CommandType.NETWORK, request_id, instance_id, sn, id); err != nil { + // goto ROLLBACK + // } + if id, err = CreateCommand(tx, CommandAction.DHCPConfigDelHost.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if _, err = CreateCommand(tx, CommandAction.PowerOff.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Point("BasicResetPasswordTemplate_status", "finish") + return +ROLLBACK: + tx.Rollback() + logger.Point("BasicResetPasswordTemplate_status", "failed") +} diff --git a/bmp-scheduler/template/CollectHardwareInfoTemplate.go b/bmp-scheduler/template/CollectHardwareInfoTemplate.go new file mode 100644 index 0000000..9ca461a --- /dev/null +++ b/bmp-scheduler/template/CollectHardwareInfoTemplate.go @@ -0,0 +1,75 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" +) + +type CollectHardwareInfoTemplate struct{} + +func (c CollectHardwareInfoTemplate) InitCommand(logger *log.Logger, request_id, sn, network_type string, allowOverride bool, task string) { + + logger.Info("CollectHardwareInfoTemplate start, ", request_id, sn, network_type) + var err error + var id int64 + tx := dao.GetGormTx(logger) + tx.Begin() + + // 前几个任务是启动agent,后几个任务是收集信息。 + + //新增DHCPConfigAddSubnet,CheckInitConfig + if id, err = CreateCommand(tx, CommandAction.DHCPConfigAddSubnet.Name, CommandType.DRIVER, request_id, "", sn, id, task); err != nil { + goto ROLLBACK + } + //采集时不执行CheckInitConfig 20240530 minping + // if id, err = CreateCommand(tx, CommandAction.CheckInitConfig.Name, CommandType.DRIVER, request_id, "", sn, id, task); err != nil { + // goto ROLLBACK + // } + + if network_type == NetworkType.RETAIL { + if id, err = CreateCommand(tx, CommandAction.DHCPConfigAddHost.Name, CommandType.DRIVER, request_id, "", sn, id, task); err != nil { + goto ROLLBACK + } + } + if id, err = CreateCommand(tx, CommandAction.SetPXEBoot.Name, CommandType.DRIVER, request_id, "", sn, id, task); err != nil { + goto ROLLBACK + } + + if network_type == NetworkType.RETAIL { + if id, err = CreateCommand(tx, CommandAction.Ping.Name, CommandType.AGENT, request_id, "", sn, id, task); err != nil { + goto ROLLBACK + } + } + // 清除raid + if allowOverride { + if id, err = CreateCommand(tx, CommandAction.CleanRaid.Name, CommandType.AGENT, request_id, "", sn, id, task); err != nil { + goto ROLLBACK + } + } + + if id, err = CreateCommand(tx, CommandAction.CollectDiskLocations.Name, CommandType.AGENT, request_id, "", sn, id, task); err != nil { + goto ROLLBACK + } + + if id, err = CreateCommand(tx, CommandAction.CollectHardwareInfo.Name, CommandType.AGENT, request_id, "", sn, id, task); err != nil { + goto ROLLBACK + } + // if id, err = CreateCommand(tx, CommandAction.UploadSystemLog.Name, CommandType.AGENT, request_id, "", sn, id, task); err != nil { + // goto ROLLBACK + // } + if network_type == NetworkType.RETAIL { + if id, err = CreateCommand(tx, CommandAction.DHCPConfigDelHost.Name, CommandType.DRIVER, request_id, "", sn, id, task); err != nil { + goto ROLLBACK + } + } + CreateCommand(tx, CommandAction.PowerOff.Name, CommandType.DRIVER, request_id, "", sn, id, task) + tx.Commit() + logger.Infof("CollectHardwareInfoTemplate success, sn: %s", sn) + return +ROLLBACK: + tx.Rollback() + logger.Warnf("CollectHardwareInfoTemplate failed, sn: %s, err:%s", sn, err.Error()) +} diff --git a/bmp-scheduler/template/CreateInstanceTemplateComposite.go b/bmp-scheduler/template/CreateInstanceTemplateComposite.go new file mode 100644 index 0000000..6870386 --- /dev/null +++ b/bmp-scheduler/template/CreateInstanceTemplateComposite.go @@ -0,0 +1,35 @@ +package template + +import ( + "fmt" + + log "git.jd.com/cps-golang/log" +) + +type CreateInstanceTemplateComposite struct{} + +type CreateInstanceTemplater interface { + accept(string, string) bool + initCommand(*log.Logger, string, string, string, bool, string, string) +} + +var createtemplates []CreateInstanceTemplater + +func init() { + createtemplates = []CreateInstanceTemplater{} + createtemplates = append(createtemplates, BasicCreateInstanceTemplate{}) + //createtemplates = append(createtemplates, SDNBondCreateInstanceTemplate{}) + //createtemplates = append(createtemplates, SDNDualCreateInstanceTemplate{}) + //createtemplates = append(createtemplates, RetailBondCreateInstanceTemplate{}) + //createtemplates = append(createtemplates, RetailDualCreateInstanceTemplate{}) +} + +func (c CreateInstanceTemplateComposite) InitCommand(logger *log.Logger, network_type, interface_mode, request_id, instance_id, sn string, make_partitions bool, image_format string, task string) { + fmt.Println(createtemplates, network_type, interface_mode) + for _, ctemplate := range createtemplates { + if true { //ctemplate.accept(network_type, interface_mode) { + ctemplate.initCommand(logger, request_id, instance_id, sn, make_partitions, image_format, task) + break + } + } +} diff --git a/bmp-scheduler/template/CreateInstanceTemplateCompositeForWindows.go b/bmp-scheduler/template/CreateInstanceTemplateCompositeForWindows.go new file mode 100644 index 0000000..fc9eb28 --- /dev/null +++ b/bmp-scheduler/template/CreateInstanceTemplateCompositeForWindows.go @@ -0,0 +1,35 @@ +package template + +import ( + "fmt" + + log "git.jd.com/cps-golang/log" +) + +type CreateInstanceTemplateCompositeForWindows struct{} + +type CreateInstanceTemplaterForWindows interface { + accept(string, string) bool + initCommand(*log.Logger, string, string, string, bool, string, string) +} + +var createtemplatesForWindows []CreateInstanceTemplaterForWindows + +func init() { + createtemplatesForWindows = []CreateInstanceTemplaterForWindows{} + createtemplatesForWindows = append(createtemplatesForWindows, BasicCreateInstanceTemplateForWindows{}) + //createtemplatesForWindows = append(createtemplatesForWindows, SDNBondCreateInstanceTemplate{}) + //createtemplatesForWindows = append(createtemplatesForWindows, SDNDualCreateInstanceTemplate{}) + //createtemplatesForWindows = append(createtemplatesForWindows, RetailBondCreateInstanceTemplate{}) + //createtemplatesForWindows = append(createtemplatesForWindows, RetailDualCreateInstanceTemplate{}) +} + +func (c CreateInstanceTemplateCompositeForWindows) InitCommand(logger *log.Logger, network_type, interface_mode, request_id, instance_id, sn string, make_partitions bool, image_format string, task string) { + fmt.Println(createtemplatesForWindows, network_type, interface_mode) + for _, ctemplate := range createtemplatesForWindows { + if true { //ctemplate.accept(network_type, interface_mode) { + ctemplate.initCommand(logger, request_id, instance_id, sn, make_partitions, image_format, task) + break + } + } +} diff --git a/bmp-scheduler/template/CutDeviceStockTemplate.go b/bmp-scheduler/template/CutDeviceStockTemplate.go new file mode 100644 index 0000000..d12107e --- /dev/null +++ b/bmp-scheduler/template/CutDeviceStockTemplate.go @@ -0,0 +1,28 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + log "git.jd.com/cps-golang/log" +) + +type CutDeviceStockTemplate struct{} + +func (c CutDeviceStockTemplate) InitCommand(logger *log.Logger, request_id, sn string, task string) { + + var err error + tx := dao.GetGormTx(logger) + tx.Begin() + + if _, err = CreateCommand(tx, CommandAction.DHCPConfigDelHost.Name, CommandType.DRIVER, request_id, "", sn, 0, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Infof("CutDeviceStockTemplate success, sn:%s", sn) + +ROLLBACK: + tx.Rollback() + logger.Warnf("CutDeviceStockTemplate failed, sn:%s", sn) +} diff --git a/bmp-scheduler/template/DHCPRestartTemplate.go b/bmp-scheduler/template/DHCPRestartTemplate.go new file mode 100644 index 0000000..0fdfd54 --- /dev/null +++ b/bmp-scheduler/template/DHCPRestartTemplate.go @@ -0,0 +1,28 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + log "git.jd.com/cps-golang/log" +) + +type DHCPRestartTemplate struct{} + +func (c DHCPRestartTemplate) InitCommand(logger *log.Logger, request_id, sn string, task string) { + + var err error + tx := dao.GetGormTx(logger) + tx.Begin() + + if _, err = CreateCommand(tx, CommandAction.DHCPRestart.Name, CommandType.DRIVER, request_id, "", sn, 0, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Infof("DHCPRestartTemplate success, request_id:%s, sn:%s", request_id, sn) + +ROLLBACK: + tx.Rollback() + logger.Warnf("DHCPRestartTemplate failed, request_id:%s, sn:%s", request_id, sn) +} diff --git a/bmp-scheduler/template/DeleteInstanceTemplateComposite.go b/bmp-scheduler/template/DeleteInstanceTemplateComposite.go new file mode 100644 index 0000000..21ed29f --- /dev/null +++ b/bmp-scheduler/template/DeleteInstanceTemplateComposite.go @@ -0,0 +1,31 @@ +package template + +import ( + log "git.jd.com/cps-golang/log" +) + +type DeleteInstanceTemplateComposite struct{} + +type DeleteInstanceTemplater interface { + accept(string) bool + initCommand(*log.Logger, string, string, string, string) +} + +var deletetemplates []DeleteInstanceTemplater + +func init() { + deletetemplates = []DeleteInstanceTemplater{} + deletetemplates = append(deletetemplates, BasicDeleteInstanceTemplate{}) + deletetemplates = append(deletetemplates, SDNDeleteInstanceTemplate{}) + deletetemplates = append(deletetemplates, RetailDeleteInstanceTemplate{}) + +} + +func (c DeleteInstanceTemplateComposite) InitCommand(logger *log.Logger, network_type, request_id, instance_id, sn string, task string) { + for _, dtemplate := range deletetemplates { + //if dtemplate.accept(network_type) { + dtemplate.initCommand(logger, request_id, instance_id, sn, task) + break + //} + } +} diff --git a/bmp-scheduler/template/ModifyBandwidthTemplate.go b/bmp-scheduler/template/ModifyBandwidthTemplate.go new file mode 100644 index 0000000..bf99e58 --- /dev/null +++ b/bmp-scheduler/template/ModifyBandwidthTemplate.go @@ -0,0 +1,31 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + log "git.jd.com/cps-golang/log" +) + +type ModifyBandwidthTemplate struct{} + +func (c ModifyBandwidthTemplate) InitCommand(logger *log.Logger, request_id, instance_id, sn string, task string) { + + var err error + var id int64 + tx := dao.GetGormTx(logger) + tx.Begin() + if id, err = CreateCommand(tx, CommandAction.SetBandwidth.Name, CommandType.NETWORK, request_id, instance_id, sn, 0, task); err != nil { + goto ROLLBACK + } + if _, err = CreateCommand(tx, CommandAction.SaveSwitchConfig.Name, CommandType.NETWORK, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Point("ModifyBandwidthTemplate_status", "finish") + +ROLLBACK: + tx.Rollback() + logger.Point("ModifyBandwidthTemplate_status", "failed") +} diff --git a/bmp-scheduler/template/PutawayDeviceTemplate.go b/bmp-scheduler/template/PutawayDeviceTemplate.go new file mode 100644 index 0000000..0ffc764 --- /dev/null +++ b/bmp-scheduler/template/PutawayDeviceTemplate.go @@ -0,0 +1,34 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + log "git.jd.com/cps-golang/log" +) + +type PutawayDeviceTemplate struct{} + +func (c PutawayDeviceTemplate) InitCommand(logger *log.Logger, request_id, instance_id, sn string, task string) { + + var err error + tx := dao.GetGormTx(logger) + tx.Begin() + var id int64 + + //DHCPConfigAddSubnet,CheckInitConfig + if id, err = CreateCommand(tx, CommandAction.DHCPConfigAddSubnet.Name, CommandType.DRIVER, request_id, "", sn, id, task); err != nil { + goto ROLLBACK + } + + if _, err = CreateCommand(tx, CommandAction.CheckInitConfig.Name, CommandType.DRIVER, request_id, "", sn, id, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Infof("PutawayDeviceTemplate success, sn:%s", sn) + return +ROLLBACK: + tx.Rollback() + logger.Warnf("PutawayDeviceTemplate failed, sn:%s", sn) +} diff --git a/bmp-scheduler/template/ReinstallInstanceTemplateComposite.go b/bmp-scheduler/template/ReinstallInstanceTemplateComposite.go new file mode 100644 index 0000000..022a71f --- /dev/null +++ b/bmp-scheduler/template/ReinstallInstanceTemplateComposite.go @@ -0,0 +1,32 @@ +package template + +import ( + log "git.jd.com/cps-golang/log" +) + +type ReinstallInstanceTemplateComposite struct{} + +type ReinstallInstanceTemplater interface { + accept(string, string) bool + initCommand(*log.Logger, string, string, string, bool, bool, string, string) +} + +var reinstallTemplates []ReinstallInstanceTemplater + +func init() { + reinstallTemplates = []ReinstallInstanceTemplater{} + reinstallTemplates = append(reinstallTemplates, BasicReinstallInstanceTemplate{}) + // reinstallTemplates = append(reinstallTemplates, SDNBondReinstallInstanceTemplate{}) + // reinstallTemplates = append(reinstallTemplates, SDNDualReinstallInstanceTemplate{}) + // reinstallTemplates = append(reinstallTemplates, RetailBondReinstallInstanceTemplate{}) + // reinstallTemplates = append(reinstallTemplates, RetailDualReinstallInstanceTemplate{}) +} + +func (c ReinstallInstanceTemplateComposite) InitCommand(logger *log.Logger, network_type, interface_mode, request_id, instance_id, sn string, keep_data, make_partitions bool, image_format string, task string) { + for _, reinstallTemplate := range reinstallTemplates { + if true { //reinstallTemplate.accept(network_type, interface_mode) + reinstallTemplate.initCommand(logger, request_id, instance_id, sn, keep_data, make_partitions, image_format, task) + break + } + } +} diff --git a/bmp-scheduler/template/ResetPasswordTemplateComposite.go b/bmp-scheduler/template/ResetPasswordTemplateComposite.go new file mode 100644 index 0000000..5da3759 --- /dev/null +++ b/bmp-scheduler/template/ResetPasswordTemplateComposite.go @@ -0,0 +1,31 @@ +package template + +import ( + log "git.jd.com/cps-golang/log" +) + +type ResetPasswordTemplateComposite struct{} + +type ResetPasswordTemplater interface { + accept(string) bool + initCommand(*log.Logger, string, string, string, string) +} + +var resetPasswordtemplates []ResetPasswordTemplater + +func init() { + resetPasswordtemplates = []ResetPasswordTemplater{} + resetPasswordtemplates = append(resetPasswordtemplates, BasicResetPasswordTemplate{}) + // resetPasswordtemplates = append(resetPasswordtemplates, SDNResetPasswordTemplate{}) + // resetPasswordtemplates = append(resetPasswordtemplates, RetailResetPasswordTemplate{}) + +} + +func (c ResetPasswordTemplateComposite) InitCommand(logger *log.Logger, network_type, request_id, instance_id, sn string, task string) { + for _, rtemplate := range resetPasswordtemplates { + if true { //rtemplate.accept(network_type) + rtemplate.initCommand(logger, request_id, instance_id, sn, task) + break + } + } +} diff --git a/bmp-scheduler/template/ResetSwitchConfigTemplate.go b/bmp-scheduler/template/ResetSwitchConfigTemplate.go new file mode 100644 index 0000000..0591350 --- /dev/null +++ b/bmp-scheduler/template/ResetSwitchConfigTemplate.go @@ -0,0 +1,53 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + log "git.jd.com/cps-golang/log" +) + +type ResetSwitchConfigTemplate struct{} + +func (c ResetSwitchConfigTemplate) InitCommand(logger *log.Logger, request_id, instance_id, sn string, task string) { + + var err error + var id int64 + tx := dao.GetGormTx(logger) + tx.Begin() + + if id, err = CreateCommand(tx, CommandAction.CreateVRF.Name, CommandType.NETWORK, request_id, instance_id, sn, 0, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.CreateVSIInterface.Name, CommandType.NETWORK, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.CreateVNI.Name, CommandType.NETWORK, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.CreateVSI.Name, CommandType.NETWORK, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.AddArpStatic.Name, CommandType.NETWORK, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetBandwidth.Name, CommandType.NETWORK, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.BindingVSI.Name, CommandType.NETWORK, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SaveSwitchConfig.Name, CommandType.NETWORK, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if _, err = CreateCommand(tx, CommandAction.SaveConfigToFtpServer.Name, CommandType.NETWORK, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Point("ResetSwitchConfigTemplate_status", "finish") + +ROLLBACK: + tx.Rollback() + logger.Point("ResetSwitchConfigTemplate_status", "failed") +} diff --git a/bmp-scheduler/template/RestartInstanceTemplate.go b/bmp-scheduler/template/RestartInstanceTemplate.go new file mode 100644 index 0000000..c6a31ef --- /dev/null +++ b/bmp-scheduler/template/RestartInstanceTemplate.go @@ -0,0 +1,29 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + log "git.jd.com/cps-golang/log" +) + +type RestartInstanceTemplate struct{} + +func (c RestartInstanceTemplate) InitCommand(logger *log.Logger, request_id, instance_id, sn string, task string) { + + var err error + tx := dao.GetGormTx(logger) + tx.Begin() + + if _, err = CreateCommand(tx, CommandAction.PowerCycle.Name, CommandType.DRIVER, request_id, instance_id, sn, 0, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Infof("RestartInstanceTemplate success, instance_id:%s", instance_id) + return +ROLLBACK: + tx.Rollback() + logger.Warnf("RestartInstanceTemplate failed, instance_id:%s", instance_id) + +} diff --git a/bmp-scheduler/template/RetailBondCreateInstanceTemplate.go b/bmp-scheduler/template/RetailBondCreateInstanceTemplate.go new file mode 100644 index 0000000..ca79f55 --- /dev/null +++ b/bmp-scheduler/template/RetailBondCreateInstanceTemplate.go @@ -0,0 +1,38 @@ +package template + +import ( + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/InterfaceMode" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +type RetailBondCreateInstanceTemplate struct { + AbstractRetailCreateInstanceTemplate +} + +func (b RetailBondCreateInstanceTemplate) accept(network_type, interface_mode string) bool { + return NetworkType.RETAIL == network_type && interface_mode != InterfaceMode.DUAL +} + +func (b RetailBondCreateInstanceTemplate) createSetNetworkCommand(tx *gorm.DB, request_id, instance_id, sn string, parent_command_id int64, task string) (int64, error) { + var id int64 + var err error + + // if id, err = CreateCommand(tx, CommandAction.SetRetailBond.Name, CommandType.NETWORK, + // request_id, instance_id, sn, parent_command_id); err != nil { + // return id, err + // } + id, err = CreateCommand(tx, CommandAction.SetBond.Name, CommandType.AGENT, + request_id, instance_id, sn, parent_command_id, task) + return id, err +} + +func (b RetailBondCreateInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, make_partitions bool, image_format string, task string) { + + logger.Info("RetailBondCreateInstanceTemplate start", request_id, instance_id, sn) + b.AbstractRetailCreateInstanceTemplate.createSetNetworkCommand = b.createSetNetworkCommand + b.AbstractRetailCreateInstanceTemplate.initCommand(logger, request_id, instance_id, sn, make_partitions, image_format, task) +} diff --git a/bmp-scheduler/template/RetailBondReinstallInstanceTemplate.go b/bmp-scheduler/template/RetailBondReinstallInstanceTemplate.go new file mode 100644 index 0000000..c721b52 --- /dev/null +++ b/bmp-scheduler/template/RetailBondReinstallInstanceTemplate.go @@ -0,0 +1,39 @@ +package template + +import ( + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/InterfaceMode" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +type RetailBondReinstallInstanceTemplate struct { + AbstractRetailReinstallInstanceTemplate +} + +func (b RetailBondReinstallInstanceTemplate) accept(network_type, interface_mode string) bool { + return NetworkType.RETAIL == network_type && interface_mode != InterfaceMode.DUAL +} + +func (b RetailBondReinstallInstanceTemplate) createSetNetworkCommand(tx *gorm.DB, request_id, instance_id, sn string, parent_command_id int64, task string) (int64, error) { + + var id int64 + var err error + + // if id, err = CreateCommand(tx, CommandAction.SetRetailBond.Name, CommandType.NETWORK, + // request_id, instance_id, sn, parent_command_id); err != nil { + // return id, err + // } + id, err = CreateCommand(tx, CommandAction.SetBond.Name, CommandType.AGENT, + request_id, instance_id, sn, parent_command_id, task) + + return id, err + +} + +func (b RetailBondReinstallInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, keep_data, make_partitions bool, image_format string, task string) { + b.AbstractRetailReinstallInstanceTemplate.createSetNetworkCommand = b.createSetNetworkCommand + b.AbstractRetailReinstallInstanceTemplate.initCommand(logger, request_id, instance_id, sn, keep_data, make_partitions, image_format, task) +} diff --git a/bmp-scheduler/template/RetailDeleteInstanceTemplate.go b/bmp-scheduler/template/RetailDeleteInstanceTemplate.go new file mode 100644 index 0000000..e8064e7 --- /dev/null +++ b/bmp-scheduler/template/RetailDeleteInstanceTemplate.go @@ -0,0 +1,72 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" +) + +type RetailDeleteInstanceTemplate struct{} + +func (b RetailDeleteInstanceTemplate) accept(network_type string) bool { + return NetworkType.RETAIL == network_type +} + +func (b RetailDeleteInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, task string) { + + logger.Info("RetailDeleteInstanceTemplate start", request_id, instance_id, sn) + + var err error + var id int64 + tx := dao.GetGormTx(logger) + tx.Begin() + + if id, err = CreateCommand(tx, CommandAction.DHCPConfigAddHost.Name, CommandType.DRIVER, + request_id, instance_id, sn, 0, task); err != nil { + logger.Warn("RetailDeleteInstanceTemplate.CreateCommand.error:", CommandAction.DHCPConfigAddHost.Name, err.Error()) + goto ROLLBACK + } + + if id, err = CreateCommand(tx, CommandAction.SetPXEBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + logger.Warn("RetailDeleteInstanceTemplate.CreateCommand.error:", CommandAction.SetPXEBoot.Name, err.Error()) + goto ROLLBACK + } + // if network_type == NetworkType.RETAIL { + if id, err = CreateCommand(tx, CommandAction.Ping.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + logger.Warn("RetailDeleteInstanceTemplate.CreateCommand.error:", CommandAction.Ping.Name, err.Error()) + goto ROLLBACK + } + // } + if id, err = CreateCommand(tx, CommandAction.CleanBlockDevice.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + logger.Warn("RetailDeleteInstanceTemplate.CreateCommand.error:", CommandAction.CleanBlockDevice.Name, err.Error()) + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.CleanRaid.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + logger.Warn("RetailDeleteInstanceTemplate.CreateCommand.error:", CommandAction.CleanRaid.Name, err.Error()) + goto ROLLBACK + } + // if id, err = CreateCommand(tx, CommandAction.UploadSystemLog.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + // logger.Warn("RetailDeleteInstanceTemplate.CreateCommand.error:", CommandAction.UploadSystemLog.Name, err.Error()) + // goto ROLLBACK + // } + + if id, err = CreateCommand(tx, CommandAction.DHCPConfigDelHost.Name, CommandType.DRIVER, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.DHCPConfigDelHost.Name, err.Error()) + goto ROLLBACK + } + + if _, err = CreateCommand(tx, CommandAction.PowerOff.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + logger.Warn("AbstractRetailCreateInstanceTemplate.CreateCommand.error:", CommandAction.PowerOff.Name, err.Error()) + goto ROLLBACK + } + + tx.Commit() + logger.Infof("RetailDeleteInstanceTemplate success, instance_id: %s", instance_id) + return +ROLLBACK: + tx.Rollback() + logger.Warnf("RetailDeleteInstanceTemplate failed, instance_id: %s", instance_id) +} diff --git a/bmp-scheduler/template/RetailDualCreateInstanceTemplate.go b/bmp-scheduler/template/RetailDualCreateInstanceTemplate.go new file mode 100644 index 0000000..2ac7aaf --- /dev/null +++ b/bmp-scheduler/template/RetailDualCreateInstanceTemplate.go @@ -0,0 +1,28 @@ +package template + +import ( + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/InterfaceMode" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +type RetailDualCreateInstanceTemplate struct { + AbstractRetailCreateInstanceTemplate +} + +func (b RetailDualCreateInstanceTemplate) accept(network_type, interface_mode string) bool { + return NetworkType.RETAIL == network_type && interface_mode == InterfaceMode.DUAL +} + +func (b RetailDualCreateInstanceTemplate) createSetNetworkCommand(tx *gorm.DB, request_id, instance_id, sn string, parent_command_id int64, task string) (int64, error) { + return CreateCommand(tx, CommandAction.SetNetwork.Name, CommandType.AGENT, request_id, instance_id, sn, parent_command_id, task) +} + +func (b RetailDualCreateInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, make_partitions bool, image_format string, task string) { + logger.Info("RetailDualCreateInstanceTemplate start", request_id, instance_id, sn) + b.AbstractRetailCreateInstanceTemplate.createSetNetworkCommand = b.createSetNetworkCommand + b.AbstractRetailCreateInstanceTemplate.initCommand(logger, request_id, instance_id, sn, make_partitions, image_format, task) +} diff --git a/bmp-scheduler/template/RetailDualReinstallInstanceTemplate.go b/bmp-scheduler/template/RetailDualReinstallInstanceTemplate.go new file mode 100644 index 0000000..1835aa8 --- /dev/null +++ b/bmp-scheduler/template/RetailDualReinstallInstanceTemplate.go @@ -0,0 +1,27 @@ +package template + +import ( + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/InterfaceMode" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +type RetailDualReinstallInstanceTemplate struct { + AbstractRetailReinstallInstanceTemplate +} + +func (b RetailDualReinstallInstanceTemplate) accept(network_type, interface_mode string) bool { + return NetworkType.RETAIL == network_type && interface_mode == InterfaceMode.DUAL +} + +func (b RetailDualReinstallInstanceTemplate) createSetNetworkCommand(tx *gorm.DB, request_id, instance_id, sn string, parent_command_id int64, task string) (int64, error) { + return CreateCommand(tx, CommandAction.SetNetwork.Name, CommandType.AGENT, request_id, instance_id, sn, parent_command_id, task) +} + +func (b RetailDualReinstallInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, keep_data, make_partitions bool, image_format string, task string) { + b.AbstractRetailReinstallInstanceTemplate.createSetNetworkCommand = b.createSetNetworkCommand + b.AbstractRetailReinstallInstanceTemplate.initCommand(logger, request_id, instance_id, sn, keep_data, make_partitions, image_format, task) +} diff --git a/bmp-scheduler/template/RetailResetPasswordTemplate.go b/bmp-scheduler/template/RetailResetPasswordTemplate.go new file mode 100644 index 0000000..5029d06 --- /dev/null +++ b/bmp-scheduler/template/RetailResetPasswordTemplate.go @@ -0,0 +1,67 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" +) + +type RetailResetPasswordTemplate struct{} + +func (b RetailResetPasswordTemplate) accept(network_type string) bool { + return NetworkType.RETAIL == network_type +} + +func (b RetailResetPasswordTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, task string) { + + logger.Info("RetailResetPasswordTemplate start", request_id, instance_id, sn) + + var err error + var id int64 + tx := dao.GetGormTx(logger) + tx.Begin() + + if id, err = CreateCommand(tx, CommandAction.DHCPConfigAddHost.Name, CommandType.DRIVER, + request_id, instance_id, sn, 0, task); err != nil { + logger.Warn("RetailResetPasswordTemplate.CreateCommand.error:", CommandAction.DHCPConfigAddHost.Name, err.Error()) + goto ROLLBACK + } + + if id, err = CreateCommand(tx, CommandAction.SetPXEBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + // if network_type == NetworkType.RETAIL { + if id, err = CreateCommand(tx, CommandAction.Ping.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + // } + + if id, err = CreateCommand(tx, CommandAction.InitRootDevice.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetPassword.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + // if id, err = CreateCommand(tx, CommandAction.UploadSystemLog.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + // goto ROLLBACK + // } + + if id, err = CreateCommand(tx, CommandAction.DHCPConfigDelHost.Name, CommandType.DRIVER, + request_id, instance_id, sn, id, task); err != nil { + logger.Warn("RetailResetPasswordTemplate.CreateCommand.error:", CommandAction.DHCPConfigDelHost.Name, err.Error()) + goto ROLLBACK + } + + if _, err = CreateCommand(tx, CommandAction.PowerOff.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Infof("RetailResetPasswordTemplate success, instance_id:", instance_id) + return +ROLLBACK: + tx.Rollback() + logger.Warnf("RetailResetPasswordTemplate failed, instance_id:", instance_id) +} diff --git a/bmp-scheduler/template/SDNBondCreateInstanceTemplate.go b/bmp-scheduler/template/SDNBondCreateInstanceTemplate.go new file mode 100644 index 0000000..2235356 --- /dev/null +++ b/bmp-scheduler/template/SDNBondCreateInstanceTemplate.go @@ -0,0 +1,32 @@ +package template + +import ( + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/InterfaceMode" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +type SDNBondCreateInstanceTemplate struct { + AbstractSDNCreateInstanceTemplate +} + +func (b SDNBondCreateInstanceTemplate) accept(network_type, interface_mode string) bool { + return NetworkType.VPC == network_type && interface_mode != InterfaceMode.DUAL + +} + +func (b SDNBondCreateInstanceTemplate) createSetNetworkCommand(tx *gorm.DB, request_id, instance_id, sn string, parent_command_id int64, task string) (int64, error) { + + return CreateCommand(tx, CommandAction.SetBond.Name, CommandType.AGENT, + request_id, instance_id, sn, parent_command_id, task) +} + +func (b SDNBondCreateInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, make_partitions bool, image_format string, task string) { + logger.Info("SDNBondCreateInstanceTemplate start", request_id, instance_id, sn) + b.AbstractSDNCreateInstanceTemplate.createSetNetworkCommand = b.createSetNetworkCommand + b.AbstractSDNCreateInstanceTemplate.initCommand(logger, request_id, instance_id, sn, make_partitions, image_format, task) + logger.Point("SDNBondCreateInstanceTemplate_status", "finish") +} diff --git a/bmp-scheduler/template/SDNBondReinstallInstanceTemplate.go b/bmp-scheduler/template/SDNBondReinstallInstanceTemplate.go new file mode 100644 index 0000000..ca2675f --- /dev/null +++ b/bmp-scheduler/template/SDNBondReinstallInstanceTemplate.go @@ -0,0 +1,31 @@ +package template + +import ( + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/InterfaceMode" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +type SDNBondReinstallInstanceTemplate struct { + AbstractSDNReinstallInstanceTemplate +} + +func (b SDNBondReinstallInstanceTemplate) accept(network_type, interface_mode string) bool { + return NetworkType.VPC == network_type && interface_mode != InterfaceMode.DUAL + +} + +func (b SDNBondReinstallInstanceTemplate) createSetNetworkCommand(tx *gorm.DB, request_id, instance_id, sn string, parent_command_id int64, task string) (int64, error) { + + return CreateCommand(tx, CommandAction.SetBond.Name, CommandType.AGENT, + request_id, instance_id, sn, parent_command_id, task) +} + +func (b SDNBondReinstallInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, keep_data, make_partitions bool, image_format string, task string) { + b.AbstractSDNReinstallInstanceTemplate.createSetNetworkCommand = b.createSetNetworkCommand + b.AbstractSDNReinstallInstanceTemplate.initCommand(logger, request_id, instance_id, sn, keep_data, make_partitions, image_format, task) + logger.Point("SDNBondReinstallInstanceTemplate_status", "finish") +} diff --git a/bmp-scheduler/template/SDNDeleteInstanceTemplate.go b/bmp-scheduler/template/SDNDeleteInstanceTemplate.go new file mode 100644 index 0000000..87f08b9 --- /dev/null +++ b/bmp-scheduler/template/SDNDeleteInstanceTemplate.go @@ -0,0 +1,59 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" +) + +type SDNDeleteInstanceTemplate struct{} + +func (b SDNDeleteInstanceTemplate) accept(network_type string) bool { + return NetworkType.VPC == network_type +} + +func (b SDNDeleteInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, task string) { + + var err error + var id int64 + tx := dao.GetGormTx(logger) + tx.Begin() + + if id, err = CreateCommand(tx, CommandAction.SDNEipUnBinding.Name, CommandType.SDN, request_id, instance_id, sn, 0, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SDNDeleteAliasIP.Name, CommandType.SDN, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SDNSubnetUnBinding.Name, CommandType.SDN, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetPXEBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.CleanBlockDevice.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.CleanRaid.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + // if id, err = CreateCommand(tx, CommandAction.UploadSystemLog.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + // goto ROLLBACK + // } + if id, err = CreateCommand(tx, CommandAction.PowerOff.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if _, err = CreateCommand(tx, CommandAction.SDNClean.Name, CommandType.SDN, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Point("SDNDeleteInstanceTemplate_status", "finish") + +ROLLBACK: + tx.Rollback() + logger.Point("SDNDeleteInstanceTemplate_status", "failed") + +} diff --git a/bmp-scheduler/template/SDNDualCreateInstanceTemplate.go b/bmp-scheduler/template/SDNDualCreateInstanceTemplate.go new file mode 100644 index 0000000..215db36 --- /dev/null +++ b/bmp-scheduler/template/SDNDualCreateInstanceTemplate.go @@ -0,0 +1,32 @@ +package template + +import ( + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/InterfaceMode" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +type SDNDualCreateInstanceTemplate struct { + AbstractSDNCreateInstanceTemplate +} + +func (b SDNDualCreateInstanceTemplate) accept(network_type, interface_mode string) bool { + return NetworkType.VPC == network_type && interface_mode == InterfaceMode.DUAL + +} + +func (b SDNDualCreateInstanceTemplate) createSetNetworkCommand(tx *gorm.DB, request_id, instance_id, sn string, parent_command_id int64, task string) (int64, error) { + + return CreateCommand(tx, CommandAction.SetVpcNetwork.Name, CommandType.AGENT, + request_id, instance_id, sn, parent_command_id, task) +} + +func (b SDNDualCreateInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, make_partitions bool, image_format string, task string) { + logger.Info("SDNDualCreateInstanceTemplate start", request_id, instance_id, sn) + b.AbstractSDNCreateInstanceTemplate.createSetNetworkCommand = b.createSetNetworkCommand + b.AbstractSDNCreateInstanceTemplate.initCommand(logger, request_id, instance_id, sn, make_partitions, image_format, task) + logger.Point("SDNDualCreateInstanceTemplate_status", "finish") +} diff --git a/bmp-scheduler/template/SDNDualReinstallInstanceTemplate.go b/bmp-scheduler/template/SDNDualReinstallInstanceTemplate.go new file mode 100644 index 0000000..4318e09 --- /dev/null +++ b/bmp-scheduler/template/SDNDualReinstallInstanceTemplate.go @@ -0,0 +1,31 @@ +package template + +import ( + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/InterfaceMode" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" + "github.com/jinzhu/gorm" +) + +type SDNDualReinstallInstanceTemplate struct { + AbstractSDNReinstallInstanceTemplate +} + +func (b SDNDualReinstallInstanceTemplate) accept(network_type, interface_mode string) bool { + return NetworkType.VPC == network_type && interface_mode == InterfaceMode.DUAL + +} + +func (b SDNDualReinstallInstanceTemplate) createSetNetworkCommand(tx *gorm.DB, request_id, instance_id, sn string, parent_command_id int64, task string) (int64, error) { + + return CreateCommand(tx, CommandAction.SetVpcNetwork.Name, CommandType.AGENT, + request_id, instance_id, sn, parent_command_id, task) +} + +func (b SDNDualReinstallInstanceTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, keep_data, make_partitions bool, image_format string, task string) { + b.AbstractSDNReinstallInstanceTemplate.createSetNetworkCommand = b.createSetNetworkCommand + b.AbstractSDNReinstallInstanceTemplate.initCommand(logger, request_id, instance_id, sn, keep_data, make_partitions, image_format, task) + logger.Point("SDNDualReinstallInstanceTemplate_status", "finish") +} diff --git a/bmp-scheduler/template/SDNResetPasswordTemplate.go b/bmp-scheduler/template/SDNResetPasswordTemplate.go new file mode 100644 index 0000000..e40b111 --- /dev/null +++ b/bmp-scheduler/template/SDNResetPasswordTemplate.go @@ -0,0 +1,53 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + "git.jd.com/cps-golang/ironic-common/ironic/enums/NetworkType" + log "git.jd.com/cps-golang/log" +) + +type SDNResetPasswordTemplate struct{} + +func (b SDNResetPasswordTemplate) accept(network_type string) bool { + return NetworkType.VPC == network_type +} + +func (b SDNResetPasswordTemplate) initCommand(logger *log.Logger, request_id, instance_id, sn string, task string) { + + var err error + var id int64 + tx := dao.GetGormTx(logger) + tx.Begin() + + if id, err = CreateCommand(tx, CommandAction.SDNSubnetUnBinding.Name, CommandType.SDN, request_id, instance_id, sn, 0, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetPXEBoot.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.InitRootDevice.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if id, err = CreateCommand(tx, CommandAction.SetPassword.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + // if id, err = CreateCommand(tx, CommandAction.UploadSystemLog.Name, CommandType.AGENT, request_id, instance_id, sn, id, task); err != nil { + // goto ROLLBACK + // } + if id, err = CreateCommand(tx, CommandAction.SDNSubnetBinding.Name, CommandType.SDN, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + if _, err = CreateCommand(tx, CommandAction.PowerOff.Name, CommandType.DRIVER, request_id, instance_id, sn, id, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Point("SDNResetPasswordTemplate_status", "finish") + +ROLLBACK: + tx.Rollback() + logger.Point("SDNResetPasswordTemplate_status", "failed") + +} diff --git a/bmp-scheduler/template/StartInstanceTemplate.go b/bmp-scheduler/template/StartInstanceTemplate.go new file mode 100644 index 0000000..5378c7d --- /dev/null +++ b/bmp-scheduler/template/StartInstanceTemplate.go @@ -0,0 +1,29 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + log "git.jd.com/cps-golang/log" +) + +type StartInstanceTemplate struct{} + +func (c StartInstanceTemplate) InitCommand(logger *log.Logger, request_id, instance_id, sn string, task string) { + + var err error + tx := dao.GetGormTx(logger) + tx.Begin() + + if _, err = CreateCommand(tx, CommandAction.PowerOn.Name, CommandType.DRIVER, request_id, instance_id, sn, 0, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Infof("StartInstanceTemplate success, instanceId:%s", instance_id) + return +ROLLBACK: + tx.Rollback() + logger.Warnf("StartInstanceTemplate failed, instanceId:%s", instance_id) + +} diff --git a/bmp-scheduler/template/StopInstanceTemplate.go b/bmp-scheduler/template/StopInstanceTemplate.go new file mode 100644 index 0000000..201b73c --- /dev/null +++ b/bmp-scheduler/template/StopInstanceTemplate.go @@ -0,0 +1,28 @@ +package template + +import ( + dao "coding.jd.com/aidc-bmp/bmp-scheduler/dao" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandAction" + "git.jd.com/cps-golang/ironic-common/ironic/enums/CommandType" + log "git.jd.com/cps-golang/log" +) + +type StopInstanceTemplate struct{} + +func (c StopInstanceTemplate) InitCommand(logger *log.Logger, request_id, instance_id, sn string, task string) { + + var err error + tx := dao.GetGormTx(logger) + tx.Begin() + + if _, err = CreateCommand(tx, CommandAction.PowerOff.Name, CommandType.DRIVER, request_id, instance_id, sn, 0, task); err != nil { + goto ROLLBACK + } + + tx.Commit() + logger.Infof("StopInstanceTemplate success, instanceId:%s", instance_id) + return +ROLLBACK: + tx.Rollback() + logger.Warnf("StopInstanceTemplate failed, instanceId:%s", instance_id) +} diff --git a/bmp-scheduler/types/CollectInfoExtra.go b/bmp-scheduler/types/CollectInfoExtra.go new file mode 100644 index 0000000..c31d9c6 --- /dev/null +++ b/bmp-scheduler/types/CollectInfoExtra.go @@ -0,0 +1,6 @@ +package types + +type CollectInfoExtra struct { + Sn string `json:"sn"` + NetworkType string `json:"network_type"` +} diff --git a/bmp-scheduler/types/CreateCommandRequest.go b/bmp-scheduler/types/CreateCommandRequest.go new file mode 100644 index 0000000..042deed --- /dev/null +++ b/bmp-scheduler/types/CreateCommandRequest.go @@ -0,0 +1,10 @@ +package types + +type CreateCommandRequest struct { + Action string + CommandType string + RequestId string + Sn string + InstanceId string + ParentCommandId int64 +} diff --git a/bmp-scheduler/types/InstanceExtra.go b/bmp-scheduler/types/InstanceExtra.go new file mode 100644 index 0000000..002b9f1 --- /dev/null +++ b/bmp-scheduler/types/InstanceExtra.go @@ -0,0 +1,20 @@ +package types + +type InstanceExtra struct { + InstanceId string `json:"instance_id"` + + Password string `json:"password"` + + UserData string `json:"user_data"` + + KeepData bool `json:"keep_data"` + + AliasIps []AliasIP `json:"alias_ips"` + + ExtensionAliasIps []AliasIP `json:"extension_alias_ips"` +} + +type AliasIP struct { + SubnetId string `json:"subnet_id"` + Cidr string `json:"cidr"` +} diff --git a/bmp-scheduler/types/QueryCommandRequest.go b/bmp-scheduler/types/QueryCommandRequest.go new file mode 100644 index 0000000..1cedb75 --- /dev/null +++ b/bmp-scheduler/types/QueryCommandRequest.go @@ -0,0 +1,8 @@ +package types + +import "time" + +type QueryCommandRequest struct { + StartTime time.Time + EndTime time.Time +} diff --git a/bmp-scheduler/types/agent/CleanBlockDevice.go b/bmp-scheduler/types/agent/CleanBlockDevice.go new file mode 100644 index 0000000..092090f --- /dev/null +++ b/bmp-scheduler/types/agent/CleanBlockDevice.go @@ -0,0 +1,17 @@ +package agent + +import "encoding/json" + +type CleanBlockDevice struct { + Action string `json:"action"` + Sn string `json:"sn"` +} + +//解决struct不能设置默认值的问题 +func (d CleanBlockDevice) MarshalJSON() ([]byte, error) { + type Alias CleanBlockDevice + if d.Action == "" { + d.Action = "CleanBlockDevice" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/CleanRaid.go b/bmp-scheduler/types/agent/CleanRaid.go new file mode 100644 index 0000000..143fa38 --- /dev/null +++ b/bmp-scheduler/types/agent/CleanRaid.go @@ -0,0 +1,23 @@ +package agent + +import "encoding/json" + +type CleanRaid struct { + Action string `json:"action"` + Sn string `json:"sn"` + RaidDatas []RaidData `json:"raid_datas"` +} + +type RaidData struct { + AdapterId int `json:"adapter_id"` + RaidDriver string `json:"raid_driver"` +} + +//解决struct不能设置默认值的问题 +func (d CleanRaid) MarshalJSON() ([]byte, error) { + type Alias CleanRaid + if d.Action == "" { + d.Action = "CleanRaid" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/CollectDiskLocations.go b/bmp-scheduler/types/agent/CollectDiskLocations.go new file mode 100644 index 0000000..4641616 --- /dev/null +++ b/bmp-scheduler/types/agent/CollectDiskLocations.go @@ -0,0 +1,21 @@ +package agent + +import "encoding/json" + +type CollectDiskLocations struct { + Action string `json:"action"` + Sn string `json:"sn"` + Version string `json:"version"` + // AdapterIds []string `json:"adapter_ids"` + AllowOverride bool `json:"allow_override"` + RaidDriver string `json:"raid_driver"` +} + +//解决struct不能设置默认值的问题 +func (d CollectDiskLocations) MarshalJSON() ([]byte, error) { + type Alias CollectDiskLocations + if d.Action == "" { + d.Action = "CollectDiskLocations" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/CollectHardwareInfo.go b/bmp-scheduler/types/agent/CollectHardwareInfo.go new file mode 100644 index 0000000..58028ba --- /dev/null +++ b/bmp-scheduler/types/agent/CollectHardwareInfo.go @@ -0,0 +1,17 @@ +package agent + +import "encoding/json" + +type CollectHardwareInfo struct { + Action string `json:"action"` + Sn string `json:"sn"` +} + +//解决struct不能设置默认值的问题 +func (d CollectHardwareInfo) MarshalJSON() ([]byte, error) { + type Alias CollectHardwareInfo + if d.Action == "" { + d.Action = "CollectHardwareInfo" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/FormatPartitions.go b/bmp-scheduler/types/agent/FormatPartitions.go new file mode 100644 index 0000000..ebe71aa --- /dev/null +++ b/bmp-scheduler/types/agent/FormatPartitions.go @@ -0,0 +1,29 @@ +package agent + +import ( + "encoding/json" +) + +type FormatPartitions struct { + Action string `json:"action"` + Sn string `json:"sn"` + Version string `json:"version"` + + Partitions []FPartition `json:"partitions,omitempty"` +} + +type FPartition struct { + Volume string `json:"volume"` // 此参数来自,MakePartitions的 "id": "ipt-1bt811r0feavi4sfln5nyyz8qgvg" + FsType string `json:"fs_type"` + Label string `json:"label"` + IsRoot bool `json:"is_root"` +} + +//解决struct不能设置默认值的问题 +func (d FormatPartitions) MarshalJSON() ([]byte, error) { + type Alias FormatPartitions + if d.Action == "" { + d.Action = "FormatPartitions" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/InitNode.go b/bmp-scheduler/types/agent/InitNode.go new file mode 100644 index 0000000..32d416a --- /dev/null +++ b/bmp-scheduler/types/agent/InitNode.go @@ -0,0 +1,28 @@ +package agent + +import ( + "encoding/json" + + domainTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/domain" +) + +type InitNode struct { + Action string `json:"action"` + Sn string `json:"sn"` + NodeData NodeData `json:"node_data"` +} + +type NodeData struct { + RootDeviceHints domainTypes.RootDeviceHints `json:"root_device_hints,omitempty"` + OsType string `json:"os_type"` + OsVersion string `json:"os_version"` +} + +//解决struct不能设置默认值的问题 +func (d InitNode) MarshalJSON() ([]byte, error) { + type Alias InitNode + if d.Action == "" { + d.Action = "InitNode" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/InitRootDevice.go b/bmp-scheduler/types/agent/InitRootDevice.go new file mode 100644 index 0000000..e968598 --- /dev/null +++ b/bmp-scheduler/types/agent/InitRootDevice.go @@ -0,0 +1,19 @@ +package agent + +import "encoding/json" + +type InitRootDevice struct { + Action string `json:"action"` + Sn string `json:"sn"` + OsType string `json:"os_type"` + OsVersion string `json:"os_version"` +} + +//解决struct不能设置默认值的问题 +func (d InitRootDevice) MarshalJSON() ([]byte, error) { + type Alias InitRootDevice + if d.Action == "" { + d.Action = "InitRootDevice" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/InitRootDeviceV2.go b/bmp-scheduler/types/agent/InitRootDeviceV2.go new file mode 100644 index 0000000..8dc82f3 --- /dev/null +++ b/bmp-scheduler/types/agent/InitRootDeviceV2.go @@ -0,0 +1,25 @@ +package agent + +import ( + "encoding/json" + + domainTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/domain" +) + +type InitRootDeviceV2 struct { + Action string `json:"action"` + Sn string `json:"sn"` + OsType string `json:"os_type"` + OsVersion string `json:"os_version"` + RootPartition string `json:"root_partition"` + RootDeviceHints domainTypes.RootDeviceHints `json:"root_device_hints"` +} + +//解决struct不能设置默认值的问题 +func (d InitRootDeviceV2) MarshalJSON() ([]byte, error) { + type Alias InitRootDeviceV2 + if d.Action == "" { + d.Action = "InitRootDeviceV2" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/InterfaceRoute.go b/bmp-scheduler/types/agent/InterfaceRoute.go new file mode 100644 index 0000000..4c365ba --- /dev/null +++ b/bmp-scheduler/types/agent/InterfaceRoute.go @@ -0,0 +1,7 @@ +package agent + +type InterfaceRoute struct { + AddressCidr string `json:"address_cidr"` + Gateway string `json:"gateway"` + InterfaceName string `json:"interface_name"` +} diff --git a/bmp-scheduler/types/agent/MakePartitions.go b/bmp-scheduler/types/agent/MakePartitions.go new file mode 100644 index 0000000..393a6e5 --- /dev/null +++ b/bmp-scheduler/types/agent/MakePartitions.go @@ -0,0 +1,56 @@ +package agent + +import ( + "encoding/json" + + domainTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/domain" +) + +type MakePartitions struct { + Action string `json:"action"` + Sn string `json:"sn"` + // OsType string `json:"os_type"` + // OsVersion string `json:"os_version"` + Version string `json:"version"` // "2.0" + BootMode string `json:"boot_mode"` + + AutoCreateEfi bool `json:"auto_create_efi"` ////可选,默认:true。uefi模式下自动创建efi分区 + AutoCreateBiosGrub bool `json:"auto_create_bios_grub"` //可选,默认:true。bios模式下自动创建bios_grub分区 + + Disks []Disk `json:"volumes"` //其实叫disks更合适,老板非要叫volumes + + // DiskLabel string `json:"disk_label"` //系统盘label + // DataDiskLabel string `json:"data_disk_label"` + // PartitionRoot *domainTypes.Partition `json:"partition_root,omitempty"` + // PartitionBoot *domainTypes.Partition `json:"partition_boot,omitempty"` + // SystemPartitions []domainTypes.Partition `json:"system_partitions"` + // DataPartitions []domainTypes.Partition `json:"data_partitions"` + // RootDeviceHints *domainTypes.RootDeviceHints `json:"root_device_hints,omitempty"` //经测试,缺省值给到agent,agent会报错,所以omitempty属性 +} + +type Disk struct { + KeepData bool `json:"keep_data"` + IsRootDevice bool `json:"is_root_device"` + IsDataDevice bool `json:"is_data_device"` + DiskHints *domainTypes.RootDeviceHints `json:"disk_hints,omitempty"` //经测试,缺省值给到agent,agent会报错,所以omitempty属性 + DiskLabel string `json:"disk_label"` //gpt + Partitions []MPartition `json:"partitions"` +} + +type MPartition struct { + ID string `json:"id"` //instance_partiton表uuid ipt-haxcsxs570fhqew36zuuilks5w6v + PartType string `json:"part_type"` // "esp",//可选 + FsType string `json:"fs_type"` //"fat32",//可选 + BootFlag string `json:"boot_flag"` //"boot",//可选。bios模式:引导分区需要设置此参数(有boot分区时是) + Number int `json:"number"` //1 + Size int `json:"size"` //512,单位Mb +} + +//解决struct不能设置默认值的问题 +func (d MakePartitions) MarshalJSON() ([]byte, error) { + type Alias MakePartitions + if d.Action == "" { + d.Action = "MakePartitions" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/MakeRaid.go b/bmp-scheduler/types/agent/MakeRaid.go new file mode 100644 index 0000000..e7ca06b --- /dev/null +++ b/bmp-scheduler/types/agent/MakeRaid.go @@ -0,0 +1,55 @@ +package agent + +import ( + "encoding/json" + + domainTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/domain" +) + +type MakeRaid struct { + Action string `json:"action"` + Sn string `json:"sn"` + MakeRaidDatas []MakeRaidData `json:"raid_datas"` +} + +type MakeRaidData struct { + RaidDriver string `json:"raid_driver"` + AdapterID int `json:"adapter_id"` + Volumes []Volume `json:"volumes"` +} + +type Volume struct { + VolumeID string `json:"volume_id"` + IsRootDevice bool `json:"is_root_device"` + IsDataDevice bool `json:"is_data_device"` + RaidLevel string `json:"raid_level"` + PhysicalDisks []PhysicalDisk `json:"physical_disks"` +} + +type PhysicalDisk struct { + Enclosure int `json:"enclosure"` + Slot int `json:"slot"` +} + +//解决struct不能设置默认值的问题 +func (d MakeRaid) MarshalJSON() ([]byte, error) { + type Alias MakeRaid + if d.Action == "" { + d.Action = "MakeRaid" + } + return json.Marshal((Alias)(d)) +} + +type MakeRaidAgentRespData struct { + MakeRaidDatas []MakeRaidAgentRespRaidData `json:"raid_datas"` +} + +type MakeRaidAgentRespRaidData struct { + AdapterID int `json:"adapter_id"` + Volumes []MakeRaidAgentRespVolume `json:"volumes"` +} + +type MakeRaidAgentRespVolume struct { + VolumeId string `json:"volume_id"` + RootDeviceHints domainTypes.RootDeviceHints `json:"disk_hints"` +} diff --git a/bmp-scheduler/types/agent/MountPartitions.go b/bmp-scheduler/types/agent/MountPartitions.go new file mode 100644 index 0000000..79a3a57 --- /dev/null +++ b/bmp-scheduler/types/agent/MountPartitions.go @@ -0,0 +1,33 @@ +package agent + +import ( + "encoding/json" + + domainTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/domain" +) + +type MonutPartitions struct { + Action string `json:"action"` + Sn string `json:"sn"` + Version string `json:"version"` + AutoMountEfi bool `json:"auto_mount_efi"` + Mounts []Mount `json:"mounts"` +} + +type Mount struct { + IsRootDevice bool `json:"is_root_device"` + IsDataDevice bool `json:"is_data_device"` + DiskHints *domainTypes.RootDeviceHints `json:"disk_hints,omitempty"` //经测试,缺省值给到agent,agent会报错,所以omitempty属性 + Label string `json:"label"` //label只在每个盘符下唯一,所以同时需要确定盘符的相应信息 + Options string `json:"options"` //"options": "errors=remount-ro", + Mountpoint string `json:"mountpoint"` // "mountpoint": "/" +} + +//解决struct不能设置默认值的问题 +func (d MonutPartitions) MarshalJSON() ([]byte, error) { + type Alias MonutPartitions + if d.Action == "" { + d.Action = "MountPartitions" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/Ping.go b/bmp-scheduler/types/agent/Ping.go new file mode 100644 index 0000000..b871af4 --- /dev/null +++ b/bmp-scheduler/types/agent/Ping.go @@ -0,0 +1,17 @@ +package agent + +import "encoding/json" + +type Ping struct { + Action string `json:"action"` + Sn string `json:"sn"` +} + +//解决struct不能设置默认值的问题 +func (d Ping) MarshalJSON() ([]byte, error) { + type Alias Ping + if d.Action == "" { + d.Action = "Ping" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/Qcow2MakePartitions.go b/bmp-scheduler/types/agent/Qcow2MakePartitions.go new file mode 100644 index 0000000..ae86b58 --- /dev/null +++ b/bmp-scheduler/types/agent/Qcow2MakePartitions.go @@ -0,0 +1,27 @@ +package agent + +import ( + "encoding/json" + + domainTypes "coding.jd.com/aidc-bmp/bmp-scheduler/types/domain" +) + +type Qcow2MakePartitions struct { + Action string `json:"action"` + Sn string `json:"sn"` + OsType string `json:"os_type"` + OsVersion string `json:"os_version"` + KeepData bool `json:"keep_data"` + DataDiskLabel string `json:"data_disk_label"` + SystemPartitions []domainTypes.Partition `json:"system_partitions"` + DataPartitions []domainTypes.Partition `json:"data_partitions"` +} + +//解决struct不能设置默认值的问题 +func (d Qcow2MakePartitions) MarshalJSON() ([]byte, error) { + type Alias Qcow2MakePartitions + if d.Action == "" { + d.Action = "Qcow2MakePartitions" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/SetBond.go b/bmp-scheduler/types/agent/SetBond.go new file mode 100644 index 0000000..723df09 --- /dev/null +++ b/bmp-scheduler/types/agent/SetBond.go @@ -0,0 +1,26 @@ +package agent + +import "encoding/json" + +type SetBond struct { + Action string `json:"action"` + Sn string `json:"sn"` + PrimaryInterfaceName string `json:"primary_interface_name"` + PrimaryMacAddr string `json:"primary_mac_addr"` + SecondaryInterfaceName string `json:"secondary_interface_name"` + SecondaryMacAddr string `json:"secondary_mac_addr"` + IpAddr string `json:"ip_addr"` + Netmask string `json:"netmask"` + Gateway string `json:"gateway"` + Nameservers []string `json:"nameservers"` + Mode string `json:"mode"` +} + +//解决struct不能设置默认值的问题 +func (d SetBond) MarshalJSON() ([]byte, error) { + type Alias SetBond + if d.Action == "" { + d.Action = "SetBond" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/SetCloudinitConf.go b/bmp-scheduler/types/agent/SetCloudinitConf.go new file mode 100644 index 0000000..cbfa992 --- /dev/null +++ b/bmp-scheduler/types/agent/SetCloudinitConf.go @@ -0,0 +1,19 @@ +package agent + +import "encoding/json" + +type SetCloudinitConf struct { + Action string `json:"action"` + Sn string `json:"sn"` + Version string `json:"version"` + SshPwauth string `json:"ssh_pwauth"` +} + +//解决struct不能设置默认值的问题 +func (d SetCloudinitConf) MarshalJSON() ([]byte, error) { + type Alias SetCloudinitConf + if d.Action == "" { + d.Action = "SetCloudinitConf" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/SetHostname.go b/bmp-scheduler/types/agent/SetHostname.go new file mode 100644 index 0000000..fac5982 --- /dev/null +++ b/bmp-scheduler/types/agent/SetHostname.go @@ -0,0 +1,18 @@ +package agent + +import "encoding/json" + +type SetHostname struct { + Action string `json:"action"` + Sn string `json:"sn"` + Hostname string `json:"hostname"` +} + +//解决struct不能设置默认值的问题 +func (d SetHostname) MarshalJSON() ([]byte, error) { + type Alias SetHostname + if d.Action == "" { + d.Action = "SetHostname" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/SetKeypairs.go b/bmp-scheduler/types/agent/SetKeypairs.go new file mode 100644 index 0000000..0d41d84 --- /dev/null +++ b/bmp-scheduler/types/agent/SetKeypairs.go @@ -0,0 +1,18 @@ +package agent + +import "encoding/json" + +type SetKeypairs struct { + Action string `json:"action"` + Sn string `json:"sn"` + PublicKey string `json:"public_key"` +} + +//解决struct不能设置默认值的问题 +func (d SetKeypairs) MarshalJSON() ([]byte, error) { + type Alias SetKeypairs + if d.Action == "" { + d.Action = "SetKeypairs" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/SetMetaData.go b/bmp-scheduler/types/agent/SetMetaData.go new file mode 100644 index 0000000..fae31f6 --- /dev/null +++ b/bmp-scheduler/types/agent/SetMetaData.go @@ -0,0 +1,21 @@ +package agent + +import "encoding/json" + +type SetMetaData struct { + Action string `json:"action"` + Sn string `json:"sn"` + MetaData struct { + HostName string `json:"hostname,omitempty"` + Uuid string `json:"uuid,omitempty"` + } `json:"meta_data"` +} + +//解决struct不能设置默认值的问题 +func (d SetMetaData) MarshalJSON() ([]byte, error) { + type Alias SetMetaData + if d.Action == "" { + d.Action = "SetMetaData" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/SetNetwork.go b/bmp-scheduler/types/agent/SetNetwork.go new file mode 100644 index 0000000..8dd54f0 --- /dev/null +++ b/bmp-scheduler/types/agent/SetNetwork.go @@ -0,0 +1,30 @@ +package agent + +import "encoding/json" + +type SetNetwork struct { + Action string `json:"action"` + Sn string `json:"sn"` + PublicInterfaceName string `json:"public_interface_name"` + PublicMacAddr string `json:"public_mac_addr"` + PublicIpAddr string `json:"public_ip_addr"` + PublicNetmask string `json:"public_netmask"` + PublicGateway string `json:"public_gateway"` + PrivateInterfaceName string `json:"private_interface_name"` + PrivateMacAddr string `json:"private_mac_addr"` + PrivateIpAddr string `json:"private_ip_addr"` + PrivateNetmask string `json:"private_netmask"` + PrivateGateway string `json:"private_gateway"` + EnableNet bool `json:"enable_net"` + IsSetDns bool `json:"is_set_dns"` + Nameservers []string `json:"nameservers"` +} + +//解决struct不能设置默认值的问题 +func (d SetNetwork) MarshalJSON() ([]byte, error) { + type Alias SetNetwork + if d.Action == "" { + d.Action = "SetNetwork" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/SetNetworkData.go b/bmp-scheduler/types/agent/SetNetworkData.go new file mode 100644 index 0000000..4aa09ee --- /dev/null +++ b/bmp-scheduler/types/agent/SetNetworkData.go @@ -0,0 +1,47 @@ +package agent + +import "encoding/json" + +type SetNetworkData struct { + Sn string `json:"sn"` + Action string `json:"action"` + NetworkData struct { + Services []Service `json:"services"` + Networks []NetWork `json:"networks"` + Links []Link `json:"links"` + } `json:"network"` +} +type Service struct { + Type string `json:"type"` + Address string `json:"address"` +} +type NetWork struct { + IPAddress string `json:"ip_address"` + Type string `json:"type"` + Netmask string `json:"netmask"` + Link string `json:"link"` + Routes []Route `json:"routes"` +} +type Route struct { + Netmask string `json:"netmask"` + Network string `json:"network"` + Gateway string `json:"gateway"` +} +type Link struct { + EthernetMacAddress string `json:"ethernet_mac_address"` + Type string `json:"type"` + ID string `json:"id"` + Mtu int `json:"mtu,omitempty"` + BondMiimon int `json:"bond_miimon,omitempty"` + BondMode string `json:"bond_mode,omitempty"` + BondLinks []string `json:"bond_links,omitempty"` +} + +//解决struct不能设置默认值的问题 +func (d SetNetworkData) MarshalJSON() ([]byte, error) { + type Alias SetNetworkData + if d.Action == "" { + d.Action = "SetNetworkWindows" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/SetNetworkLinux.go b/bmp-scheduler/types/agent/SetNetworkLinux.go new file mode 100644 index 0000000..df97960 --- /dev/null +++ b/bmp-scheduler/types/agent/SetNetworkLinux.go @@ -0,0 +1,103 @@ +package agent + +import "encoding/json" + +type SetNocloudNetwork struct { + Action string `json:"action"` + Version string `json:"version"` + Sn string `json:"sn"` + Network struct { + Ethernets struct { + Eth0 struct { + Match struct { + Macaddress string `json:"macaddress,omitempty"` + } `json:"match,omitempty"` + SetName string `json:"set-name,omitempty"` + } `json:"eth0,omitempty"` + Eth1 struct { + Match struct { + Macaddress string `json:"macaddress,omitempty"` + } `json:"match,omitempty"` + SetName string `json:"set-name,omitempty"` + } `json:"eth1,omitempty"` + } `json:"ethernets"` + Bonds struct { + Bond0 struct { + Macaddress string `json:"macaddress,omitempty"` + Addresses []string `json:"addresses,omitempty"` + Gateway4 string `json:"gateway4,omitempty"` + Gateway6 string `json:"gateway6,omitempty"` + Nameservers Nameservers `json:"nameservers"` + Interfaces []string `json:"interfaces,omitempty"` + Parameters struct { + Mode string `json:"mode"` + MiiMonitorInterval int `json:"mii-monitor-interval"` + } `json:"parameters,omitempty"` + } `json:"bond0,omitempty"` + } `json:"bonds,omitempty"` + Version int `json:"version"` + } `json:"network"` +} + +type Nameservers struct { + Addresses []string `json:"addresses,omitempty"` +} + +type RouteItem struct { + To string `json:"to,omitempty"` + Via string `json:"via,omitempty"` +} + +//解决struct不能设置默认值的问题 +func (d SetNocloudNetwork) MarshalJSON() ([]byte, error) { + type Alias SetNocloudNetwork + if d.Action == "" { + d.Action = "SetNetwork" + } + return json.Marshal((Alias)(d)) +} + +type SetNocloudNetworkNoBond struct { + Action string `json:"action"` + Version string `json:"version"` + Sn string `json:"sn"` + Network struct { + Ethernets struct { + Eth0 struct { + Match struct { + Macaddress string `json:"macaddress,omitempty"` + } `json:"match,omitempty"` + SetName string `json:"set-name,omitempty"` + Addresses []string `json:"addresses,omitempty"` + Netmask string `json:"netmask,omitempty"` + Gateway4 string `json:"gateway4,omitempty"` + Gateway6 string `json:"gateway6,omitempty"` + Nameservers Nameservers `json:"nameservers,omitempty"` + Routes []RouteItem `json:"routes,omitempty"` + } `json:"eth0,omitempty"` + Eth1 struct { + Match struct { + Macaddress string `json:"macaddress,omitempty"` + } `json:"match,omitempty"` + SetName string `json:"set-name,omitempty"` + Addresses []string `json:"addresses,omitempty"` + Netmask string `json:"netmask,omitempty"` + Gateway4 string `json:"gateway4,omitempty"` + Gateway6 string `json:"gateway6,omitempty"` + Nameservers Nameservers `json:"nameservers,omitempty"` + Routes []RouteItem `json:"routes,omitempty"` + } `json:"eth1,omitempty"` //暂时先设置一个网口 + } `json:"ethernets"` + + Version int `json:"version"` + } `json:"network"` +} + +//解决struct不能设置默认值的问题 +func (d SetNocloudNetworkNoBond) MarshalJSON() ([]byte, error) { + type Alias SetNocloudNetworkNoBond + if d.Action == "" { + d.Action = "SetNetwork" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/SetNocloudMetaData.go b/bmp-scheduler/types/agent/SetNocloudMetaData.go new file mode 100644 index 0000000..bb20d99 --- /dev/null +++ b/bmp-scheduler/types/agent/SetNocloudMetaData.go @@ -0,0 +1,23 @@ +package agent + +import "encoding/json" + +type SetNocloudMetaData struct { + Action string `json:"action"` + Version string `json:"version"` + Sn string `json:"sn"` + MetaData struct { + InstanceID string `json:"instance-id"` + LocalHostname string `json:"local-hostname,omitempty"` + PublicKeys []string `json:"public-keys,omitempty"` + } `json:"meta_data"` +} + +//解决struct不能设置默认值的问题 +func (d SetNocloudMetaData) MarshalJSON() ([]byte, error) { + type Alias SetNocloudMetaData + if d.Action == "" { + d.Action = "SetMetaData" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/SetNocloudUserData.go b/bmp-scheduler/types/agent/SetNocloudUserData.go new file mode 100644 index 0000000..eec05e4 --- /dev/null +++ b/bmp-scheduler/types/agent/SetNocloudUserData.go @@ -0,0 +1,19 @@ +package agent + +import "encoding/json" + +type SetNocloudUserData struct { + Action string `json:"action"` + Sn string `json:"sn"` + Version string `json:"version"` + UserData string `json:"user_data"` +} + +//解决struct不能设置默认值的问题 +func (d SetNocloudUserData) MarshalJSON() ([]byte, error) { + type Alias SetNocloudUserData + if d.Action == "" { + d.Action = "SetUserData" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/SetPassword.go b/bmp-scheduler/types/agent/SetPassword.go new file mode 100644 index 0000000..d274ce0 --- /dev/null +++ b/bmp-scheduler/types/agent/SetPassword.go @@ -0,0 +1,18 @@ +package agent + +import "encoding/json" + +type SetPassword struct { + Action string `json:"action"` + Sn string `json:"sn"` + Password string `json:"password"` +} + +//解决struct不能设置默认值的问题 +func (d SetPassword) MarshalJSON() ([]byte, error) { + type Alias SetPassword + if d.Action == "" { + d.Action = "SetPassword" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/SetSDNNetwork.go b/bmp-scheduler/types/agent/SetSDNNetwork.go new file mode 100644 index 0000000..ad88b9f --- /dev/null +++ b/bmp-scheduler/types/agent/SetSDNNetwork.go @@ -0,0 +1,29 @@ +package agent + +import "encoding/json" + +type SetSDNNetwork struct { + Action string `json:"action"` + Sn string `json:"sn"` + PrimaryInterfaceName string `json:"primary_interface_name"` + PrimaryMacAddr string `json:"primary_mac_addr"` + PrimaryIpAddr string `json:"primary_ip_addr"` + PrimaryNetmask string `json:"primary_netmask"` + PrimaryGateway string `json:"primary_gateway"` + SecondaryInterfaceName string `json:"secondary_interface_name"` + SecondaryMacAddr string `json:"secondary_mac_addr"` + SecondaryIpAddr string `json:"secondary_ip_addr"` + SecondaryNetmask string `json:"secondary_netmask"` + SecondaryGateway string `json:"secondary_gateway"` + Nameservers []string `json:"nameservers"` + Routes []InterfaceRoute `json:"routes"` +} + +//解决struct不能设置默认值的问题 +func (d SetSDNNetwork) MarshalJSON() ([]byte, error) { + type Alias SetSDNNetwork + if d.Action == "" { + d.Action = "SetSDNNetwork" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/SetUserCmd.go b/bmp-scheduler/types/agent/SetUserCmd.go new file mode 100644 index 0000000..80c8938 --- /dev/null +++ b/bmp-scheduler/types/agent/SetUserCmd.go @@ -0,0 +1,18 @@ +package agent + +import "encoding/json" + +type SetUserCmd struct { + Action string `json:"action"` + Sn string `json:"sn"` + Content string `json:"content"` +} + +//解决struct不能设置默认值的问题 +func (d SetUserCmd) MarshalJSON() ([]byte, error) { + type Alias SetUserCmd + if d.Action == "" { + d.Action = "SetUserCmd" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/UploadSystemLog.go b/bmp-scheduler/types/agent/UploadSystemLog.go new file mode 100644 index 0000000..e68fe59 --- /dev/null +++ b/bmp-scheduler/types/agent/UploadSystemLog.go @@ -0,0 +1,17 @@ +package agent + +import "encoding/json" + +type UploadSystemLog struct { + Action string `json:"action"` + Sn string `json:"sn"` +} + +//解决struct不能设置默认值的问题 +func (d UploadSystemLog) MarshalJSON() ([]byte, error) { + type Alias UploadSystemLog + if d.Action == "" { + d.Action = "UploadSystemLog" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/WriteImage.go b/bmp-scheduler/types/agent/WriteImage.go new file mode 100644 index 0000000..f4da06e --- /dev/null +++ b/bmp-scheduler/types/agent/WriteImage.go @@ -0,0 +1,23 @@ +package agent + +import "encoding/json" + +type WriteImage struct { + Action string `json:"action"` + Sn string `json:"sn"` + Url string `json:"url"` + Format string `json:"format"` + Hash string `json:"hash"` + Filename string `json:"filename"` + OsType string `json:"os_type"` + OsVersion string `json:"os_version"` +} + +//解决struct不能设置默认值的问题 +func (d WriteImage) MarshalJSON() ([]byte, error) { + type Alias WriteImage + if d.Action == "" { + d.Action = "WriteImage" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/agent/WriteImageTar.go b/bmp-scheduler/types/agent/WriteImageTar.go new file mode 100644 index 0000000..a3e68b2 --- /dev/null +++ b/bmp-scheduler/types/agent/WriteImageTar.go @@ -0,0 +1,23 @@ +package agent + +import "encoding/json" + +type WriteImageTar struct { + Action string `json:"action"` + Sn string `json:"sn"` + Url string `json:"url"` + Format string `json:"format"` + Hash string `json:"hash"` + Filename string `json:"filename"` + OsType string `json:"os_type"` + OsVersion string `json:"os_version"` +} + +//解决struct不能设置默认值的问题 +func (d WriteImageTar) MarshalJSON() ([]byte, error) { + type Alias WriteImageTar + if d.Action == "" { + d.Action = "WriteImageTar" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/domain/Partition.go b/bmp-scheduler/types/domain/Partition.go new file mode 100644 index 0000000..200b22f --- /dev/null +++ b/bmp-scheduler/types/domain/Partition.go @@ -0,0 +1,8 @@ +package domain + +type Partition struct { + Size int `json:"size"` + FsType string `json:"fs_type"` + MountPoint string `json:"mountpoint"` + Label string `json:"label"` +} diff --git a/bmp-scheduler/types/domain/RootDeviceHints.go b/bmp-scheduler/types/domain/RootDeviceHints.go new file mode 100644 index 0000000..75b544b --- /dev/null +++ b/bmp-scheduler/types/domain/RootDeviceHints.go @@ -0,0 +1,25 @@ +package domain + +type RootDeviceHints struct { //空值传给agent会err,所以设置omitempty + Size int64 `json:"size,omitempty"` + + Rotational bool `json:"rotational,omitempty"` + + Wwn string `json:"wwn,omitempty"` + + Name string `json:"name,omitempty"` + + WwnVendorExtension string `json:"wwn_vendor_extension,omitempty"` + + WwnWithExtension string `json:"wwn_with_extension,omitempty"` + + Model string `json:"model,omitempty"` + + Serial string `json:"serial,omitempty"` + + Vendor string `json:"vendor,omitempty"` + + Hctl string `json:"hctl,omitempty"` + + ByPath string `json:"by_path,omitempty"` +} diff --git a/bmp-scheduler/types/driver/AddDHCPConfigHost.go b/bmp-scheduler/types/driver/AddDHCPConfigHost.go new file mode 100644 index 0000000..a59e78e --- /dev/null +++ b/bmp-scheduler/types/driver/AddDHCPConfigHost.go @@ -0,0 +1,19 @@ +package driver + +import "encoding/json" + +type AddDHCPConfigHost struct { + Action string `json:"action"` + Sn string `json:"sn"` + Mac string `json:"mac"` + Ip string `json:"ip"` +} + +//解决struct不能设置默认值的问题 +func (d AddDHCPConfigHost) MarshalJSON() ([]byte, error) { + type Alias AddDHCPConfigHost + if d.Action == "" { + d.Action = "DHCPConfigAddHost" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/driver/CheckInitConfig.go b/bmp-scheduler/types/driver/CheckInitConfig.go new file mode 100644 index 0000000..9aaeebf --- /dev/null +++ b/bmp-scheduler/types/driver/CheckInitConfig.go @@ -0,0 +1,21 @@ +package driver + +import "encoding/json" + +type CheckInitConfig struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` + Privilege string `json:"privilege"` +} + +//解决struct不能设置默认值的问题 +func (d CheckInitConfig) MarshalJSON() ([]byte, error) { + type Alias CheckInitConfig + if d.Action == "" { + d.Action = "CheckInitConfig" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/driver/DHCPConfigAddSubnet.go b/bmp-scheduler/types/driver/DHCPConfigAddSubnet.go new file mode 100644 index 0000000..2fdcf1f --- /dev/null +++ b/bmp-scheduler/types/driver/DHCPConfigAddSubnet.go @@ -0,0 +1,20 @@ +package driver + +import "encoding/json" + +type DHCPConfigAddSubnet struct { + Action string `json:"action"` + Sn string `json:"sn"` + Subnet string `json:"subnet"` + SubnetMask string `json:"subnet_mask"` + Routes string `json:"routes"` +} + +//解决struct不能设置默认值的问题 +func (d DHCPConfigAddSubnet) MarshalJSON() ([]byte, error) { + type Alias DHCPConfigAddSubnet + if d.Action == "" { + d.Action = "DHCPConfigAddSubnet" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/driver/DHCPRestart.go b/bmp-scheduler/types/driver/DHCPRestart.go new file mode 100644 index 0000000..e285438 --- /dev/null +++ b/bmp-scheduler/types/driver/DHCPRestart.go @@ -0,0 +1,17 @@ +package driver + +import "encoding/json" + +type DHCPRestart struct { + Action string `json:"action"` + Sn string `json:"sn"` +} + +//解决struct不能设置默认值的问题 +func (d DHCPRestart) MarshalJSON() ([]byte, error) { + type Alias DHCPRestart + if d.Action == "" { + d.Action = "DHCPRestart" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/driver/DelDHCPConfigHost.go b/bmp-scheduler/types/driver/DelDHCPConfigHost.go new file mode 100644 index 0000000..f3557be --- /dev/null +++ b/bmp-scheduler/types/driver/DelDHCPConfigHost.go @@ -0,0 +1,19 @@ +package driver + +import "encoding/json" + +type DelDHCPConfigHost struct { + Action string `json:"action"` + Sn string `json:"sn"` + Mac string `json:"mac"` + Ip string `json:"ip"` +} + +//解决struct不能设置默认值的问题 +func (d DelDHCPConfigHost) MarshalJSON() ([]byte, error) { + type Alias DelDHCPConfigHost + if d.Action == "" { + d.Action = "DHCPConfigDelHost" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/driver/PingHost.go b/bmp-scheduler/types/driver/PingHost.go new file mode 100644 index 0000000..4c842d4 --- /dev/null +++ b/bmp-scheduler/types/driver/PingHost.go @@ -0,0 +1,18 @@ +package driver + +import "encoding/json" + +type PingHost struct { + Action string `json:"action"` + Sn string `json:"sn"` + Ip string `json:"ip"` +} + +//解决struct不能设置默认值的问题 +func (d PingHost) MarshalJSON() ([]byte, error) { + type Alias PingHost + if d.Action == "" { + d.Action = "PingHost" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/driver/PowerCycle.go b/bmp-scheduler/types/driver/PowerCycle.go new file mode 100644 index 0000000..e7ca733 --- /dev/null +++ b/bmp-scheduler/types/driver/PowerCycle.go @@ -0,0 +1,20 @@ +package driver + +import "encoding/json" + +type PowerCycle struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` +} + +//解决struct不能设置默认值的问题 +func (d PowerCycle) MarshalJSON() ([]byte, error) { + type Alias PowerCycle + if d.Action == "" { + d.Action = "PowerCycle" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/driver/PowerOff.go b/bmp-scheduler/types/driver/PowerOff.go new file mode 100644 index 0000000..c2d2679 --- /dev/null +++ b/bmp-scheduler/types/driver/PowerOff.go @@ -0,0 +1,20 @@ +package driver + +import "encoding/json" + +type PowerOff struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` +} + +//解决struct不能设置默认值的问题 +func (d PowerOff) MarshalJSON() ([]byte, error) { + type Alias PowerOff + if d.Action == "" { + d.Action = "PowerOff" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/driver/PowerOn.go b/bmp-scheduler/types/driver/PowerOn.go new file mode 100644 index 0000000..adb0ce7 --- /dev/null +++ b/bmp-scheduler/types/driver/PowerOn.go @@ -0,0 +1,20 @@ +package driver + +import "encoding/json" + +type PowerOn struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` +} + +//解决struct不能设置默认值的问题 +func (d PowerOn) MarshalJSON() ([]byte, error) { + type Alias PowerOn + if d.Action == "" { + d.Action = "PowerOn" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/driver/PowerReset.go b/bmp-scheduler/types/driver/PowerReset.go new file mode 100644 index 0000000..7555260 --- /dev/null +++ b/bmp-scheduler/types/driver/PowerReset.go @@ -0,0 +1,20 @@ +package driver + +import "encoding/json" + +type PowerReset struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` +} + +//解决struct不能设置默认值的问题 +func (d PowerReset) MarshalJSON() ([]byte, error) { + type Alias PowerReset + if d.Action == "" { + d.Action = "PowerReset" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/driver/SetDISKBoot.go b/bmp-scheduler/types/driver/SetDISKBoot.go new file mode 100644 index 0000000..9aa4df5 --- /dev/null +++ b/bmp-scheduler/types/driver/SetDISKBoot.go @@ -0,0 +1,20 @@ +package driver + +import "encoding/json" + +type SetDISKBoot struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` +} + +//解决struct不能设置默认值的问题 +func (d SetDISKBoot) MarshalJSON() ([]byte, error) { + type Alias SetDISKBoot + if d.Action == "" { + d.Action = "SetDISKBoot" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/types/driver/SetPXEBoot.go b/bmp-scheduler/types/driver/SetPXEBoot.go new file mode 100644 index 0000000..b2cf32a --- /dev/null +++ b/bmp-scheduler/types/driver/SetPXEBoot.go @@ -0,0 +1,22 @@ +package driver + +import ( + "encoding/json" +) + +type SetPXEBoot struct { + Action string `json:"action"` + Sn string `json:"sn"` + IloIp string `json:"ilo_ip"` + Username string `json:"username"` + Password string `json:"password"` +} + +//解决struct不能设置默认值的问题 +func (d SetPXEBoot) MarshalJSON() ([]byte, error) { + type Alias SetPXEBoot + if d.Action == "" { + d.Action = "SetPXEBoot" + } + return json.Marshal((Alias)(d)) +} diff --git a/bmp-scheduler/util/array.go b/bmp-scheduler/util/array.go new file mode 100644 index 0000000..78e3f0d --- /dev/null +++ b/bmp-scheduler/util/array.go @@ -0,0 +1,111 @@ +package util + +import ( + "encoding/json" + "reflect" +) + +func GetValuesByField(objs []interface{}, field string) []string { + res := []string{} + for _, obj := range objs { + r := reflect.ValueOf(obj) + if reflect.TypeOf(obj).Kind() == reflect.Ptr { + r = reflect.Indirect(r) + } + f := r.FieldByName(field).String() + res = append(res, f) + } + return res +} + +func InArrayWithIndex(val interface{}, array interface{}) (exists bool, index int) { + exists = false + index = -1 + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + index = i + exists = true + return + } + } + } + return +} + +func InArray(val interface{}, array interface{}) (exists bool) { + exists = false + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + exists = true + return + } + } + } + return +} + +//求并集 +func UnionArray(slice1, slice2 []string) []string { + m := make(map[string]int) + for _, v := range slice1 { + m[v]++ + } + + for _, v := range slice2 { + times, _ := m[v] + if times == 0 { + slice1 = append(slice1, v) + } + } + return slice1 +} + +//求交集 +func IntersectArray(slice1, slice2 []string) []string { + m := make(map[string]int) + nn := make([]string, 0) + for _, v := range slice1 { + m[v]++ + } + + for _, v := range slice2 { + times, _ := m[v] + if times == 1 { + nn = append(nn, v) + } + } + return nn +} + +//求差集 slice1-并集 +func DifferenceArray(slice1, slice2 []string) []string { + m := make(map[string]int) + nn := make([]string, 0) + inter := IntersectArray(slice1, slice2) + for _, v := range inter { + m[v]++ + } + + for _, value := range slice1 { + times, _ := m[value] + if times == 0 { + nn = append(nn, value) + } + } + return nn +} + +func ObjToJson(obj interface{}) string { + dataType, err := json.Marshal(obj) + if err != nil { + return "" + } + dataString := string(dataType) + return dataString +} diff --git a/bmp-scheduler/util/array_test.go b/bmp-scheduler/util/array_test.go new file mode 100644 index 0000000..68dc442 --- /dev/null +++ b/bmp-scheduler/util/array_test.go @@ -0,0 +1,14 @@ +package util + +import( + "testing" +) + +func TestInArray(t *testing.T){ + v := InArray("aaa", []string{"aaa", "bbb"}) + if !v{ + t.Fatal("not in array") + }else{ + t.Log("in array") + } +} diff --git a/bmp-scheduler/util/bool.go b/bmp-scheduler/util/bool.go new file mode 100644 index 0000000..39da658 --- /dev/null +++ b/bmp-scheduler/util/bool.go @@ -0,0 +1,12 @@ +package util + +func Bool2Int8(b bool) int8 { + if b { + return 1 + } + return 0 +} + +func Int82Bool(i int8) bool { + return i > 0 +} diff --git a/bmp-scheduler/util/coverage.out b/bmp-scheduler/util/coverage.out new file mode 100644 index 0000000..a333b69 --- /dev/null +++ b/bmp-scheduler/util/coverage.out @@ -0,0 +1,155 @@ +mode: set +git.jd.com/cps-golang/ironic-api/util/ipv4.go:43.58,45.21 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:48.2,50.62 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:64.2,64.43 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:45.21,47.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:50.62,52.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:52.8,55.17 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:58.3,58.30 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:55.17,57.4 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:58.30,60.4 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:60.9,60.38 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:60.38,62.4 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:67.75,68.70 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:71.2,80.8 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:68.70,70.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:83.42,85.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:87.40,90.26 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:93.2,93.16 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:90.26,92.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:96.40,98.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:100.40,102.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:104.48,107.30 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:111.2,111.12 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:107.30,110.3 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:114.50,117.28 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:121.2,121.18 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:117.28,120.3 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:124.53,126.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:128.49,130.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:132.53,134.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:136.76,137.18 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:140.2,141.29 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:144.2,148.28 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:156.2,156.21 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:137.18,139.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:141.29,143.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:148.28,149.35 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:152.3,154.50 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:149.35,151.4 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:160.32,165.2 4 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:167.44,170.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:172.43,174.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:176.40,179.2 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:181.41,184.2 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:186.43,187.20 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:190.2,191.18 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:194.2,195.19 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:202.2,202.27 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:187.20,189.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:191.18,193.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:195.19,196.25 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:199.3,200.25 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:196.25,197.9 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:206.44,207.21 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:210.2,211.18 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:214.2,215.19 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:222.2,222.16 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:207.21,209.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:211.18,213.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:215.19,216.25 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:219.3,220.25 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:216.25,217.9 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:225.55,227.40 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:235.2,235.24 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:228.22,229.37 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:230.21,231.22 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:232.10,233.36 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:238.48,240.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:242.41,245.22 3 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:248.2,249.29 2 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:257.2,257.77 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:245.22,246.102 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:249.29,250.59 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:250.59,251.103 1 0 +git.jd.com/cps-golang/ironic-api/util/ipv4.go:252.9,254.4 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:30.61,54.2 14 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:57.30,60.2 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:63.57,64.16 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:64.16,66.44 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:72.52,76.2 3 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:79.50,95.16 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:98.2,111.3 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:95.16,97.3 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:115.36,132.16 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:137.2,152.16 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:156.2,158.12 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:165.2,166.11 2 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:132.16,134.3 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:152.16,154.3 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:158.12,159.23 1 0 +git.jd.com/cps-golang/ironic-api/util/mq.go:159.23,163.4 1 0 +git.jd.com/cps-golang/ironic-api/util/page.go:9.65,11.23 2 0 +git.jd.com/cps-golang/ironic-api/util/page.go:16.2,16.22 1 0 +git.jd.com/cps-golang/ironic-api/util/page.go:11.23,13.3 1 0 +git.jd.com/cps-golang/ironic-api/util/page.go:13.8,15.3 1 0 +git.jd.com/cps-golang/ironic-api/util/page.go:19.59,26.2 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:16.69,18.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:21.2,21.41 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:18.16,20.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:25.55,30.2 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:32.61,34.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:37.2,40.9 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:34.16,36.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:44.58,46.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:49.2,49.49 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:46.16,48.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:52.47,55.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:59.2,60.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:65.2,65.57 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:55.16,57.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:60.16,62.3 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:68.56,70.16 2 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:74.2,74.42 1 0 +git.jd.com/cps-golang/ironic-api/util/ssh.go:70.16,72.3 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:7.66,9.27 2 0 +git.jd.com/cps-golang/ironic-api/util/array.go:17.2,17.12 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:9.27,11.48 2 0 +git.jd.com/cps-golang/ironic-api/util/array.go:14.3,15.23 2 0 +git.jd.com/cps-golang/ironic-api/util/array.go:11.48,13.4 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:20.84,23.38 3 0 +git.jd.com/cps-golang/ironic-api/util/array.go:34.2,34.8 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:24.21,26.32 2 0 +git.jd.com/cps-golang/ironic-api/util/array.go:26.32,27.62 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:27.62,31.5 3 0 +git.jd.com/cps-golang/ironic-api/util/array.go:37.64,39.38 2 1 +git.jd.com/cps-golang/ironic-api/util/array.go:49.2,49.8 1 0 +git.jd.com/cps-golang/ironic-api/util/array.go:40.21,42.32 2 1 +git.jd.com/cps-golang/ironic-api/util/array.go:42.32,43.62 1 1 +git.jd.com/cps-golang/ironic-api/util/array.go:43.62,46.5 2 1 +git.jd.com/cps-golang/ironic-api/util/bool.go:3.29,4.7 1 0 +git.jd.com/cps-golang/ironic-api/util/bool.go:7.2,7.10 1 0 +git.jd.com/cps-golang/ironic-api/util/bool.go:4.7,6.3 1 0 +git.jd.com/cps-golang/ironic-api/util/bool.go:10.29,12.2 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:10.89,13.16 2 0 +git.jd.com/cps-golang/ironic-api/util/http.go:16.2,18.16 3 0 +git.jd.com/cps-golang/ironic-api/util/http.go:21.2,23.27 2 0 +git.jd.com/cps-golang/ironic-api/util/http.go:26.2,28.16 3 0 +git.jd.com/cps-golang/ironic-api/util/http.go:31.2,32.16 2 0 +git.jd.com/cps-golang/ironic-api/util/http.go:35.2,35.23 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:13.16,15.3 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:18.16,20.3 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:23.27,25.3 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:28.16,30.3 1 0 +git.jd.com/cps-golang/ironic-api/util/http.go:32.16,34.3 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:4.83,6.25 2 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:24.2,24.15 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:6.25,7.12 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:7.12,9.4 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:9.9,11.4 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:13.8,13.32 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:13.32,15.42 2 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:18.3,18.12 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:15.42,17.4 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:18.12,20.4 1 0 +git.jd.com/cps-golang/ironic-api/util/strings.go:20.9,22.4 1 0 diff --git a/bmp-scheduler/util/http.go b/bmp-scheduler/util/http.go new file mode 100644 index 0000000..9c19f9f --- /dev/null +++ b/bmp-scheduler/util/http.go @@ -0,0 +1,42 @@ +package util + +import ( + "bytes" + "encoding/json" + "io/ioutil" + "net/http" + "reflect" +) + +func DoHttpPost(url string, header map[string]string, data interface{}) ([]byte, error) { + var bytesData []byte + if reflect.TypeOf(data).Kind() == reflect.String { + bytesData = []byte(data.(string)) + } else { + var err error + bytesData, err = json.Marshal(data) + if err != nil { + return nil, err + } + } + reader := bytes.NewReader(bytesData) + request, err := http.NewRequest("POST", url, reader) + if err != nil { + return nil, err + } + defer request.Body.Close() + //务必带 X-Jdcloud-Requestid + for k, v := range header { + request.Header.Set(k, v) + } + client := http.Client{} + resp, err := client.Do(request) + if err != nil { + return nil, err + } + respBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + return respBytes, nil +} diff --git a/bmp-scheduler/util/ipv4.go b/bmp-scheduler/util/ipv4.go new file mode 100644 index 0000000..c5b56b3 --- /dev/null +++ b/bmp-scheduler/util/ipv4.go @@ -0,0 +1,171 @@ +package util + +import ( + "encoding/hex" + "fmt" + "net" + "strconv" + "strings" + + commonUtil "git.jd.com/cps-golang/ironic-common/ironic/util" +) + +const ( + IP_NETWORK_SPLIT = "/" + IP_ADDRESS_REGEX = `^(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))$` + IP_WIDTH int32 = 32 + IP_MAX_VALUE int64 = 0xffffffff + IP_MIN_VALUE int64 = 0 +) + +func NetworkIp(cidr string) string { + _, ipNet, _ := net.ParseCIDR(cidr) + return ipNet.IP.String() +} + +func Gateway(cidr string) string { + ip, _, err := net.ParseCIDR(cidr) + if err != nil { + panic(err.Error()) + } + IncrIP(ip) + return ip.String() +} + +func Mask(mask net.IPMask) string { + m, _ := hex.DecodeString(mask.String()) + return net.IP([]byte(m)).String() +} + +// IP地址自增 +func IncrIP(ip net.IP) { + for i := len(ip) - 1; i >= 0; i-- { + ip[i]++ + if ip[i] > 0 { + break + } + } +} + +// IP地址自减 +func DecrIP(ip net.IP) { + length := len(ip) + for i := length - 1; i >= 0; i-- { + ip[length-1]-- + if ip[length-1] < 0xFF { + break + } + for j := 1; j < length; j++ { + ip[length-j-1]-- + if ip[length-j-1] < 0xFF { + return + } + } + } +} + +// RandomMacAddress 生成随机mac地址 +func RandomMacAddress() string { + + uuid := commonUtil.GetRandString("", 12, false, false, true) + first_part := uuid[0:4] + first_part_num, _ := strconv.ParseInt("0x"+first_part, 16, 32) + first_hex_string := strconv.FormatInt(first_part_num&0xfeff, 16) + part := []string{fmt.Sprintf("%04x", first_hex_string), uuid[4:8], uuid[8:12]} + return strings.Join(part, "-") +} + +/* + * 列举一个CIDR段中的所有IP列表 + */ +func GetAllHostIPs(cidr string) []string { + //不过不包含掩码位,就当做32位IP对待 + if !strings.Contains(cidr, "/") { + return []string{cidr} + } + ip := strings.Split(cidr, "/")[0] + ipSegs := strings.Split(ip, ".") + maskLen, _ := strconv.Atoi(strings.Split(cidr, "/")[1]) + if maskLen <= 0 { + return []string{} + } + if maskLen == 32 { + return []string{ip} + } + seg1MinIp, seg1MaxIp := getIpSeg1Range(ipSegs[0], maskLen) + seg2MinIp, seg2MaxIp := getIpSeg2Range(ipSegs[1], maskLen) + seg3MinIp, seg3MaxIp := getIpSeg3Range(ipSegs[2], maskLen) + seg4MinIp, seg4MaxIp := getIpSeg4Range(ipSegs[3], maskLen) + + var ipList []string + for seg1Ip := seg1MinIp; seg1Ip <= seg1MaxIp; seg1Ip++ { + for seg2Ip := seg2MinIp; seg2Ip <= seg2MaxIp; seg2Ip++ { + for seg3Ip := seg3MinIp; seg3Ip <= seg3MaxIp; seg3Ip++ { + for seg4Ip := seg4MinIp; seg4Ip <= seg4MaxIp; seg4Ip++ { + oneIp := fmt.Sprintf("%d.%d.%d.%d", seg1Ip, seg2Ip, seg3Ip, seg4Ip) + ipList = append(ipList, oneIp) + } + } + } + } + return ipList +} + +/* + * 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)3部分的最小值和最大值 + */ +func getIpSeg1Range(ipSeg string, maskLen int) (int, int) { + //如果掩码位>16,此时说明掩码只会影响到seg2,seg3,seg4,seg1直接返回 + if maskLen > 8 { + segIp, _ := strconv.Atoi(ipSeg) + return segIp, segIp + } + ipSegNum, _ := strconv.Atoi(ipSeg) + return getIpSegRange(uint8(ipSegNum), uint8(8-maskLen)) +} + +/* +* 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)3部分的最小值和最大值 + */ +func getIpSeg2Range(ipSeg string, maskLen int) (int, int) { + //如果掩码位>16,此时说明掩码只会影响到seg3,seg4,seg2直接返回 + if maskLen > 16 { + segIp, _ := strconv.Atoi(ipSeg) + return segIp, segIp + } + ipSegNum, _ := strconv.Atoi(ipSeg) + return getIpSegRange(uint8(ipSegNum), uint8(16-maskLen)) +} + +/* +* 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)3部分的最小值和最大值 + */ +func getIpSeg3Range(ipSeg string, maskLen int) (int, int) { + //如果掩码位>24,此时说明掩码只会影响到seg4,seg3直接返回 + if maskLen > 24 { + segIp, _ := strconv.Atoi(ipSeg) + return segIp, segIp + } + ipSegNum, _ := strconv.Atoi(ipSeg) + return getIpSegRange(uint8(ipSegNum), uint8(24-maskLen)) +} + +/* + * 对于一个seg1.seg2.seg3.seg4格式的IP,本方法获取seg(ment)4部分的最小值和最大值 + */ +func getIpSeg4Range(ipSeg string, maskLen int) (int, int) { + ipSegNum, _ := strconv.Atoi(ipSeg) + segMinIp, segMaxIp := getIpSegRange(uint8(ipSegNum), uint8(32-maskLen)) + if segMinIp == 0 { + segMinIp = segMinIp + 1 //最后一段的IP不能是0,否则就会变为网段 + } + return segMinIp, segMaxIp +} + +func getIpSegRange(userSegIp, offset uint8) (int, int) { + var ipSegMax uint8 = 255 + netSegIp := ipSegMax << offset + segMinIp := netSegIp & userSegIp + segMaxIp := userSegIp&(255< target_len { //裁剪 + if ahead { //保留左边 + return string(r[:target_len]) + } else { //保留右边 + return string(r[len(r)-target_len:]) + } + + } else if len(r) < target_len { //填充 + pads := []rune{} + for i := 0; i < target_len-len(r); i++ { + pads = append(pads, padding_char) + } + if ahead { //左向填充 + return string(append(pads, r...)) + } else { //右向填充 + return string(append(r, pads...)) + } + } + return source + +} + +func GetUuid(pre string) string { + rand.Seed(time.Now().UnixNano()) + str := "0123456789abcdefghijklmnopqrstuvwxyz" + bytes := []byte(str) + var result []byte + for i := 0; i < 28; i++ { + result = append(result, bytes[rand.Intn(len(bytes))]) + } + return pre + string(result) +} diff --git a/docs/bmp-deploy/bmp-deploy.md b/docs/bmp-deploy/bmp-deploy.md new file mode 100644 index 0000000..2e593fa --- /dev/null +++ b/docs/bmp-deploy/bmp-deploy.md @@ -0,0 +1,31 @@ +# File and Directory Explanation for `bmp-deploy` +## List of Files and Directories +~~~ +bmp-deploy directory +├── bmp-deploy.sh +├── cache +├── config +├── data +├── docker-compose.yml +├── env +├── .env +├── ReleaseNotes +├── script +├── sql +├── template +└── tool +~~~ + +## Explanation of Files and Directories +* `bmp-deploy.sh`: Main deployment script. +* `cache`: Cache directory for GuestOS images and LiveOS images. +* `config`: Configuration directory. +* `data`: Cache directory for other binary files, including PXE boot programs and device import templates. +* `docker-compose.yml`: Docker Compose service orchestration file. +* `env`: Environment variable directory for each component. +* `.env`: Main configuration file for Docker Compose environment variables. +* `ReleaseNotes`: Version release information. +* `script`: Directory for initialization scripts of each component. +* `sql`: Directory for database initialization scripts. +* `template`: Template file directory. +* `tool`: Tool directory. diff --git a/docs/bmp-deploy/config.md b/docs/bmp-deploy/config.md new file mode 100644 index 0000000..f49399b --- /dev/null +++ b/docs/bmp-deploy/config.md @@ -0,0 +1,96 @@ +# [bmp安装指导](main.md) - 配置管理 +.env file configuration +~~~ +BMP_HOST_IP=xxx.xxx.xxx.xxx +# bmp registry +BMP_REGISTRY=docker.io + +# db middleware registry eg: mysql:5.7-debian +# if you cannot pull from docker.io please change docker.io to other Container image repository +BASE_REGISTRY=docker.m.daocloud.io + +BMP_VERSION=dev +COMPOSE_PROJECT_NAME=bmp +BMP_DB_HOST=bmp-db +BMP_DB_PORT=3306 +BMP_DB_USER=bmp_rw +BMP_DB_PASSWORD='LpK9Jq12Zf' +BMP_DB_NAME=bmp +BMP_REDIS_HOST=bmp-redis +BMP_REDIS_PORT=6379 +BMP_REDIS_PASSWORD='LpK9Jq12Zf' +BMP_MQ_HOST=bmp-mq +BMP_MQ_PORT=5672 +BMP_MQ_USER=bmp +BMP_MQ_PASSWORD='LpK9Jq12Zf' +BMP_MQ_VHOST=/bmp +BMP_OMAPI_HOST=bmp-dhcp-agent +BMP_OMAPI_PORT=7911 +BMP_OMAPI_TOKEN="LpK9Jq12Zf" +BMP_OPENAPI_HOST=bmp-openapi +BMP_OPENAPI_PORT=8801 +BMP_OPENAPI_CONSOLE_HOST=bmp-openapi-console +BMP_OPENAPI_CONSOLE_PORT=8802 +BMP_OOB_ALERT_HOST=bmp-oob-alert +BMP_OOB_ALERT_PORT=8804 +BMP_MQ_EXCHANGE_ROUTING_KEY=idc-vm4xsulx1k2d9z4xkctrttig02zl +BMP_IMAGE_PORT=10000 +BMP_MONITOR_PROXY_PORT=8805 +BMP_PROMETHEUS_HOST=bmp-prometheus +BMP_PROMETHEUS_PORT=9090 +BMP_PROMETHEUS_DATA_DIR=/data/prometheus +BMP_PUSHGATEWAY_HOST=bmp-pushgateway +BMP_PUSHGATEWAY_PORT=9091 +BMP_ALERTMANAGER_HOST=bmp-alertmanager +BMP_ALERTMANAGER_PORT=9093 +BMP_PRONOEA_HOST=bmp-pronoea +BMP_PRONOEA_PORT=9999 +~~~ + +## Configuration Description: +| Configuration Name | Description | +|---|---| +| BMP_HOST_IP | IP of the manager node, please configure it to the management network card IP, BMP service components listen on this IP. | +| BMP_VERSION | Version of BMP to be installed, do not modify casually. | +| COMPOSE_PROJECT_NAME | Docker Compose project name, default value is `bmp`, do not modify. | +| BMP_DB_HOST | IP/hostname of bmp-db, do not modify. | +| BMP_DB_PORT | Port of bmp-db, do not modify. | +| BMP_DB_USER | Username for bmp-db. | +| BMP_DB_PASSWORD | Password for bmp-db. | +| BMP_DB_NAME | Database name for bmp-db, do not modify. | +| BMP_REDIS_HOST | IP/hostname of bmp-redis, do not modify. | +| BMP_REDIS_PORT | Port of bmp-redis, do not modify. | +| BMP_REDIS_PASSWORD | Password for bmp-redis. | +| BMP_MQ_HOST | IP/hostname of bmp-mq, do not modify. | +| BMP_MQ_PORT | Port of bmp-mq, do not modify. | +| BMP_MQ_USER | Username for bmp-mq. | +| BMP_MQ_PASSWORD | Password for bmp-mq. | +| BMP_MQ_VHOST | Vhost name for bmp-mq, do not modify. | +| BMP_OMAPI_HOST | IP/hostname of DHCP OMAPI service, do not modify. | +| BMP_OMAPI_PORT | Port of DHCP OMAPI service, do not modify. | +| BMP_OMAPI_TOKEN | Authentication token for DHCP OMAPI. | +| BMP_OPENAPI_HOST | IP/hostname of bmp-openapi, do not modify. | +| BMP_OPENAPI_PORT | Port of bmp-openapi, do not modify. | +| BMP_OPENAPI_CONSOLE_HOST | IP/hostname of bmp-openapi-console, do not modify. | +| BMP_OPENAPI_CONSOLE_PORT | Port of bmp-openapi-console, do not modify. | +| BMP_OOB_ALERT_HOST | IP/hostname of bmp-oob-alert, do not modify. | +| BMP_OOB_ALERT_PORT | Port of bmp-oob-alert, do not modify. | +| BMP_MQ_EXCHANGE_ROUTING_KEY | MQ routing key, this value should be equal to `idc_id`, do not modify. | +| BMP_IMAGE_PORT | Port of BMP image server, do not modify. | +| BMP_MONITOR_PROXY_PORT | Port of bmp-monitor-proxy, do not modify. | +| BMP_PROMETHEUS_HOST | IP/hostname of bmp_prometheus, do not modify. | +| BMP_PROMETHEUS_PORT | Port of bmp_prometheus, do not modify. | +| BMP_PROMETHEUS_DATA_DIR | Data storage path for bmp_prometheus, this path requires a large amount of storage space, it is recommended to modify according to actual conditions. | +| BMP_PUSHGATEWAY_HOST | IP/hostname of bmp_pushgateway, do not modify. | +| BMP_PUSHGATEWAY_PORT | Port of bmp_pushgateway, do not modify. | +| BMP_ALERTMANAGER_HOST | IP/hostname of bmp_alertmanager, do not modify. | +| BMP_ALERTMANAGER_PORT | Port of bmp_alertmanager, do not modify. | +| BMP_PRONOEA_HOST | IP/hostname of bmp_pronoea, do not modify. | +| BMP_PRONOEA_PORT | Port of bmp_pronoea, do not modify. | + +## Notes +* The values of `BMP_DB_PASSWORD`, `BMP_REDIS_PASSWORD`, `BMP_MQ_PASSWORD`, and `BMP_OMAPI_TOKEN` can only consist of **uppercase and lowercase letters and numbers**. Special characters may cause errors. + + + + diff --git a/docs/bmp-deploy/picture/bm-deploy.png b/docs/bmp-deploy/picture/bm-deploy.png new file mode 100644 index 0000000..2bbed12 Binary files /dev/null and b/docs/bmp-deploy/picture/bm-deploy.png differ diff --git a/docs/bmp-deploy/picture/bmp-framework.png b/docs/bmp-deploy/picture/bmp-framework.png new file mode 100644 index 0000000..b274084 Binary files /dev/null and b/docs/bmp-deploy/picture/bmp-framework.png differ diff --git a/docs/bmp-deploy/picture/bmp-framework_en.png b/docs/bmp-deploy/picture/bmp-framework_en.png new file mode 100644 index 0000000..cc907d8 Binary files /dev/null and b/docs/bmp-deploy/picture/bmp-framework_en.png differ diff --git a/docs/bmp-deploy/picture/bmp.png b/docs/bmp-deploy/picture/bmp.png new file mode 100644 index 0000000..f9110cf Binary files /dev/null and b/docs/bmp-deploy/picture/bmp.png differ diff --git a/docs/bmp-deploy/picture/bmp_en.png b/docs/bmp-deploy/picture/bmp_en.png new file mode 100644 index 0000000..c6bd5ca Binary files /dev/null and b/docs/bmp-deploy/picture/bmp_en.png differ diff --git a/docs/bmp-deploy/picture/github.png b/docs/bmp-deploy/picture/github.png new file mode 100644 index 0000000..260709c Binary files /dev/null and b/docs/bmp-deploy/picture/github.png differ diff --git a/docs/bmp-deploy/picture/ifconfig-bond0.png b/docs/bmp-deploy/picture/ifconfig-bond0.png new file mode 100644 index 0000000..9755d38 Binary files /dev/null and b/docs/bmp-deploy/picture/ifconfig-bond0.png differ diff --git a/docs/bmp-deploy/picture/ifconfig-eth0.png b/docs/bmp-deploy/picture/ifconfig-eth0.png new file mode 100644 index 0000000..6b8301d Binary files /dev/null and b/docs/bmp-deploy/picture/ifconfig-eth0.png differ diff --git a/docs/bmp-deploy/picture/monitor.png b/docs/bmp-deploy/picture/monitor.png new file mode 100644 index 0000000..6e4a594 Binary files /dev/null and b/docs/bmp-deploy/picture/monitor.png differ diff --git a/docs/bmp-deploy/picture/network-deploy.png b/docs/bmp-deploy/picture/network-deploy.png new file mode 100644 index 0000000..f935d75 Binary files /dev/null and b/docs/bmp-deploy/picture/network-deploy.png differ diff --git a/docs/bmp-deploy/picture/network.png b/docs/bmp-deploy/picture/network.png new file mode 100644 index 0000000..0952371 Binary files /dev/null and b/docs/bmp-deploy/picture/network.png differ diff --git a/docs/bmp-deploy/service-manage.md b/docs/bmp-deploy/service-manage.md new file mode 100644 index 0000000..03b74ef --- /dev/null +++ b/docs/bmp-deploy/service-manage.md @@ -0,0 +1,121 @@ +# Service Management in BMP Installation Guide +## Usage of `bmp-deploy.sh` +~~~ +# ./bmp-deploy.sh -h + +Usage: ./bmp-deploy.sh [-t|--tag TAG] COMMAND SERVICE... + +COMMAND: + start Install and start SERVICE + stop Stop SERVICE + restart Restart SERVICE + status Check SERVICE status + images Display SERVICE image + uninstall Uninstall SERVICE + reinstall Reinstall SERVICE + config Get SERVICE config + +SERVICE: + all All SERVICES + bmp-db + bmp-redis + bmp-mq + bmp-image + bmp-pushgateway + bmp-alertmanager + bmp-prometheus + bmp-tftp + bmp-rsyslog + bmp-console-web + bmp-operation-web + bmp-console-api + bmp-operation-api + bmp-openapi + bmp-openapi-console + bmp-scheduler + bmp-driver + bmp-dhcp-agent + bmp-oob-alert + bmp-oob-agent + bmp-monitor-proxy + bmp-pronoea +~~~ + +#### Stopping Services +~~~ +# Stop the bmp-console-web service +./bmp-deploy.sh stop bmp-console-web + +# Stop both bmp-console-web and bmp-operation-web services +./bmp-deploy.sh stop bmp-console-web bmp-operation-web + +# Stop all services +./bmp-deploy.sh stop all +~~~ + +## Starting Services +~~~ +# Start the bmp-console-web service +./bmp-deploy.sh start bmp-console-web + +# Start both bmp-console-web and bmp-operation-web services +./bmp-deploy.sh start bmp-console-web bmp-operation-web + +# Start all services +./bmp-deploy.sh start all +~~~ + +## Restarting Services +~~~ +# Restart the bmp-console-web service +./bmp-deploy.sh restart bmp-console-web +~~~ + +## Checking Service Running Status +~~~ +# Check the running status of all services +./bmp-deploy.sh status all +~~~ + +## Viewing Container Images Associated with Services +~~~ +# View the container image associated with the bmp-console-web service +./bmp-deploy.sh images bmp-console-web +~~~ + +## Uninstalling Services +~~~ +# Uninstall a single service, such as bmp-console-web +# Note: Related data will also be deleted +./bmp-deploy.sh uninstall bmp-console-web + +# Uninstall all services +./bmp-deploy.sh uninstall all +~~~ + +## Uninstalling BMP (Uninstall All Services) +~~~ +cd /root/bmp-deploy/ +./bmp-deploy.sh uninstall all +cd /root +rm -rf bmp-deploy bmp-deploy*.tar.gz +rm -rf /var/log/bmp +~~~ + +## reinstall BMP +./bmp-deploy.sh reinstall all | [service...] +~~~ +#reinstall single service eg:bmp-console-web +./bmp-deploy.sh reinstall bmp-console-web +~~~ + +## get all configs of BMP +./bmp-deploy.sh config all | [service...] + +## deploy bmp with specific tag version +./bmp-deploy.sh start all | [service...] -t|--tag TAG +~~~ +#deploy with tag 1.0 +./bmp-deploy.sh start all --tag 1.0 +~~~ + diff --git a/docs/bmp-deploy/troubleshoot.md b/docs/bmp-deploy/troubleshoot.md new file mode 100644 index 0000000..7f854e9 --- /dev/null +++ b/docs/bmp-deploy/troubleshoot.md @@ -0,0 +1,20 @@ +# Service startup failed +Restart a service +~~~ +./bmp-deploy.sh status all #Check which services are not running properly +./bmp-deploy.sh start ServiceName #Start the service +~~~ + +# Reason for pxe boot failure +pxe boot failure +Is the machine's boot mode BIOS +Is the machine's out-of-band network correct +Is the machine's BMC normal +Is the machine's network port connection correct + +# Docker is not started +Error: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? +After restarting the manager node, you need to restart the docker service +~~~ +systemctl start docker.service +~~~ \ No newline at end of file diff --git a/docs/bmp-deploy/vm-example.md b/docs/bmp-deploy/vm-example.md new file mode 100644 index 0000000..16cd5d7 --- /dev/null +++ b/docs/bmp-deploy/vm-example.md @@ -0,0 +1,146 @@ +[BMP Installation Guide]-Deploying a Physical BM Node with Virtual Machines + +## Deployment Description + +• This section describes how to simulate a physical server with a virtual machine and use it as a BM node接入bmp management. + +• In this example,KVM and VirtualBMC are deployed on the same server.You can choose the BMP manager node as the deployment server,which means one server can act as both the manager node and the BM node.With just one server,you can complete the deployment and installation testing of BMP. + +## Network Architecture + + +Steps to Create a Virtualized Physical Server + +• Virtual machine network address planning +CIDR:192.168.100.0/24 +Gateway:192.168.100.1 +Virtual machine IP:192.168.100.2 +DHCP relay server IP:192.168.100.254 + + +• Install the virtual machine suite + +``` + yum install -y qemu-kvm libvirt virt-install + systemctl start libvirtd + ``` + + + +• Create a virtual bridge and configure IP,this IP will act as the gateway for the virtual BM node,see network address planning + +``` + ip link add br-vbm type bridge + ip link set br-vbm up + ip address add 192.168.100.1/24 dev br-vbm + ``` + + + +• Firewall settings + +``` + iptables -I FORWARD -i br-vbm -j ACCEPT + iptables -I FORWARD -o br-vbm -j ACCEPT + iptables -t nat -I POSTROUTING -s 192.168.100.0/24 ! -o br-vbm -j MASQUERADE + ``` + + + +• Create a virtual machine and connect it to the virtual bridge + +``` + #Create a virtual machine with configuration: 2c4G100G, SN: vmsn123456, connected to virtual bridge: br-vbm + virt-install \ + --name vbm-1 \ + --memory 4096 \ + --vcpus=2 \ + --hvm \ + --boot hd \ + --network bridge:br-vbm \ + --disk /var/lib/libvirt/images/vbm-1.qcow2,format=qcow2,size=15 \ + --noreboot \ + --graphics vnc,listen=0.0.0.0 \ + --sysinfo type=smbios,system_serial=vmsn123456 + ``` + + + +• Install VirtualBMC.VirtualBMC official documentation:[VirtualBMC Documentation]() + +``` + yum install -y python3 python3-devel libvirt-devel rust cargo #virtualbmc dependencies include python3 + python3 -m pip -U pip + python3 -m pip install setuptools_rust + python3 -m pip install virtualbmc + vbmcd + ``` + + + +• Create a VirtualBMC instance and associate it with the previously created virtual machine + +``` + vbmc add vbm-1 --port 623 #vbm-1 represents the virtual machine name, 623 represents the port that the virtual BMC listens on + vbmc start vbm-1 + vbmc list #Check VirtualBMC instances + ``` + + + +• Test if the VirtualBMC instance is effective + +``` + #The default user for VirtualBMC instances is admin, and the password is password + ipmitool -I lanplus -H 127.0.0.1 -U admin -P password -p 623 power status + ``` + + + +• Configure DHCP relay.Relay the DHCP requests sent by the virtual machine to the manager node.Since both the manager node and the libvirt service listen to the DHCP service port(udp/67),to prevent conflicts,run the DHCP relay program in an independent network namespace + +``` + #Install DHCP relay + yum install -y dhcp + + #Add network namespace and virtual network card + ip link add veth0 type veth peer name veth1 + ip link set veth0 up + ip link set veth1 up + ip link set dev veth0 master br-vbm + ip netns add ns1 + ip link set veth1 netns ns1 + + #Set IP address for DHCP relay server, must be in the same subnet as the virtual machine + ip netns exec ns1 ip address add 192.168.100.254/24 dev veth1 + ip netns exec ns1 ip route add default via 192.168.100.1 + + #Start the relay server, relay address is the manager node's management IP + ip netns exec ns1 dhcrelay 10.208.12.72 + ``` + + + +• If the manager node and the virtual BM node are the same server,you need to enable the TFTP NAT extension function,otherwise,the virtual BM node may not be able to access bmp-tftp normally. + +``` + echo 0 > /proc/sys/net/netfilter/nf_conntrack_helper + iptables -t raw -A PREROUTING -p udp --dport 69 -j CT --helper tftp + modprobe nf_nat_tftp + ``` + + + +## Importing Devices into BMP Operation Platform + +``` +Out-of-band IP: VirtualBMC server IP +Out-of-band port: VirtualBMC instance port, in this example, it is 6230 +Out-of-band login account: VirtualBMC instance user, in this example, it is admin +Out-of-band login password: VirtualBMC instance password, in this example, it is password +Subnet mask: Virtual machine network mask, in this example, it is 255.255.255.0 +Gateway: Virtual machine network gateway, in this example, it is 192.168.100.1 +Internal IPv4: Virtual machine IP, choose any available address from the CIDR, in this example, it is 192.168.100.2 +MAC1: Virtual machine network card MAC address, can be obtained through virsh domiflist VM_NAME +SN: Virtual machine SN, in this example, it is vmsn123456 +``` \ No newline at end of file diff --git a/docs/concepts.md b/docs/concepts.md new file mode 100644 index 0000000..72a4c6e --- /dev/null +++ b/docs/concepts.md @@ -0,0 +1,40 @@ +# Concept + +## Component Description +* bmp-console-web console front-end page. Use vue3 scaffolding to build. Contains login page, project management page, personal center page, instance management page and other page functions. +* bmp-console-api console api. Go language back-end business, call openapi interface to implement console related interfaces. Assemble all kinds of required data for bmp-console-web, need to be adapted to multiple languages. +* bmp-operation-web operation platform front-end page. Use vue3 scaffolding to build, including login page, idc management page, device type management page, image management page, device management page, role management page, user management page and other page functions. +* bmp-operation-api operation platform api. Go language back-end business, call openapi interface to implement operation platform related interfaces. Assemble all kinds of required data for bmp-operation-web, need to be adapted to multiple languages. +* bmp-openapi bmp-openapi is the core module of bmp. Implements the RESTful API format interface that meets the swagger2.0 specification. It provides all basic functions of bmp externally. It performs database operations internally and calls bmp-scheduler to complete related operations of instance lifecycle management. +* bmp-scheduler is an installation scheduling module. It accepts instance lifecycle management requests from bmp-openapi, converts upper-level requests into corresponding commands, and drives the execution of commands, cooperating with lower-level bmp-driver and bmp-agent to complete installation, reinstallation, startup, shutdown and other functions. +* bmp-driver is a single-idc application. In the case of multiple idcs, multiple sets of bmp-driver services need to be deployed, receiving mq, and starting, shutting down, restarting, setting pxe startup and other operations on the servers in this IDC. +* bmp-dhcp-agent is a single-idc application. Before installation, the dhcp configuration needs to be updated in advance, and the Mac-IP association relationship needs to be stored in the dhcp configuration. Only then can liveOS obtain the ip address from dhcp. +* bmp-db database +* bmp-redis redis cache +* bmp-mq message middleware +* bmp-tftp tftp server, which stores the relevant files required for pxe boot, including pxe boot program, pxe boot configuration, LiveOS kernel and initramfs. +* bmp-image http server, storing GuestOS image + +## Installation process +![Architecture diagram](./bmp-deploy/picture/bm-deploy.png) +## Installation process description +1. The client (bmp-console-web) initiates the installation request, and bmp-console-api receives the request +2. bmp-console-api checks the request parameters, and forwards the request to bmp-openapi if it passes +3. bmp-openapi performs operations such as permission check, generates installation parameters, and sends them to bmp-scheduler +4. bmp-scheduler schedules the installation task, generates a series of installation instructions, and sends them to bmp-dhcp-agent, bmp-driver and bmp-agent through the bmp-mq service +5. bmp-dhcp-agent receives the instruction and sets the built-in dhcp server, so that the bm node can obtain the correct ip configuration and tftp address (bmp-tftp address) during the pxe startup phase +6. After receiving the instruction, bmp-driver sets the bm node to pxe startup and restarts +7. The bm node executes pxe startup, the PXEClient built into the network card starts, sends a dhcp request broadcast, and the dhcp server built into bmp-dhcp-agent responds to the corresponding ip configuration and tftp address after receiving the dhcp request +8. PXEClient configures its own ip, then downloads the pxe boot program from bmp-tftp and executes it. The pxe boot program continues to obtain other boot parameters from bmp-tftp, downloads the kernel and initramfs, starts the memory operating system, and the bmp-agent service built into the memory operating system starts to start +9. bmp-agent receives instructions and executes subsequent bm installation operations, such as: setting up raid, partitioning, etc. +10. bmp-agent downloads the client operating system image file from bmp-image, writes it to the bm node disk, and then initializes the client operating system +11. bmp-agent executes a restart to complete the operating system installation + +## Glossary +* manager node: bmp management server, running all bmp components (except bmp-agent) +* bm node: bare metal server, physical server for normal operation, no operating system before installation, LiveOS during installation, and GuestOS after installation +* GuestOS: normal operating operating system +* LiveOS: memory operating system with bmp-agent pre-installed +* out-of-band network card: special network card on physical server for communication with bmc, also known as ipmi network card +* management network card: standard network card of physical server, in management network +* management network: layer 3 network, management network card of manager node communicates with management network card of bm node through management network \ No newline at end of file diff --git a/docs/develop.md b/docs/develop.md new file mode 100644 index 0000000..48bd425 --- /dev/null +++ b/docs/develop.md @@ -0,0 +1,49 @@ +# Customized development and redeployment + +## Development and deployment steps +~~~ +Step 1: Code development and testing + +Step 2: Application image creation + +Step 3: Redeployment + +Step 4: Special attention +~~~ + +## Step 1: Customized code development and testing +...... + +## Step 2: Application image creation +Each component directory contains a corresponding dockerfile file, for example: bmp-scheduler component +~~~ +# Set relevant environment variables. The .env and images.cfg files define the image repository and version number and other information +. bmp-deploy/.env +. bmp-deploy/config/image.cfg +docker build -f ./bmp-scheduler/bmp-scheduler.Dockerfile -t ${bmp_scheduler_image} ./bmp-scheduler +~~~ +Note: The image creation of bmp-console-api, bmp-operation-api, and oob-log-alert components is slightly different, refer to "Step 4: Special attention:" + +## Step 3: Redeploy +Example: bmp-scheduler +~~~ +cd bmp-deploy +chmod +x ./bmp-deploy.sh +./bmp-deploy.sh restart bmp-scheduler +~~~ + +## Step 4: Special attention: +- bmp-console-api depends on the SDK generated by bmp-openapi-console +- bmp-operation-api and oob-log-alert depend on the SDK generated by bmp-openapi + +If bmp-openapi-console and bmp-openapi components are customized, please repackage and deploy bmp-console-api or bmp-operation-api, oob-log-alert components +Example: Re-create the image of bmp-openapi-console +~~~ +# Repackage bmp-console-api and create an image +. bmp-deploy/.env +. bmp-deploy/config/image.cfg + +# Note that the last parameter of docker build is ./ (i.e. Baremetal_Manage_Platform directory) +docker build -f ./bmp-openapi-console/bmp-openapi-console.Dockerfile -t ${bmp_openapi_console_image} ./ +~~~ +The redeployment method is the same as "Step 3" \ No newline at end of file diff --git a/docs/local-develop.md b/docs/local-develop.md new file mode 100644 index 0000000..5f5aa35 --- /dev/null +++ b/docs/local-develop.md @@ -0,0 +1,744 @@ +# Local development and deployment + +## Development and deployment steps +- [Component introduction](#1) +- [Local development and debugging](#2) +- [Code introduction](#2.1) +- [Front-end component](#2.2) +- [Back-end go component](#2.3) +- [Back-end python component](#2.4) +- [Basic component](#2.5) +- [bmp-image](#2.5.1) +- [bmp-tftp](#2.5.2) +- [bmp-db](#2.5.3) +- [bmp-redis](#2.5.4) +- [bmp-mq](#2.5.5) +- [bmp-rsyslog](#2.5.6) +- [Open source component](#2.6) +- [bmp-pushgateway](#2.6.1) +- [bmp-prometheus](#2.6.2) +-[bmp-alertmanager](#2.6.3) + +## Component Introduction +* bmp-console-web console front-end page. Use vue3 scaffolding to build. Includes login page, project management page, personal center page, instance management page and other page functions. +* bmp-console-api console api. Go language backend business, call openapi interface to implement console related interfaces. Assemble all kinds of required data for bmp-console-web, and need to adapt to multiple languages. +* bmp-operation-web operation platform front-end page. Use vue3 scaffolding to build, include login page, computer room management page, model management page, image management page, device management page, role management page, user management page and other page functions. +* bmp-operation-api operation platform api. Go language back-end business, call openapi interface to implement operation platform related interfaces. To assemble all kinds of required data for bmp-operation-web, multi-language adaptation is required. +* bmp-openapi bmp-openapi is the core module of bmp. It implements the restful api format interface that meets the swagger2.0 specification. It provides all basic functions of bmp to the outside world. It performs database operations internally and calls bmp-scheduler to complete the related operations of instance lifecycle management. +* bmp-scheduler installation scheduling module. It accepts the instance lifecycle management request of bmp-openapi, converts the upper-level request into the corresponding commands, and drives the execution of commands, and cooperates with the lower-level bmp-driver and bmp-agent to complete the installation, reinstallation, startup, shutdown and other functions. +* bmp-driver single computer room application. In the case of multiple computer rooms, multiple sets of bmp-driver services need to be deployed, receive mq, and start, shut down, restart, set pxe startup and other operations on the server in this computer room. +* bmp-dhcp-agent Single computer room application, before installation, you need to update the dhcp configuration in advance and store the Mac-IP association in the dhcp configuration. Only then can liveOS obtain the ip address from dhcp. +* bmp-db database +* bmp-redis redis cache +* bmp-mq message middleware +* bmp-tftp tftp server, which stores the relevant files required for pxe boot, including pxe boot program, pxe boot configuration, LiveOS kernel and initramfs. +* bmp-image http server, storing GuestOS image +* bmp-rsyslog rsyslog log component +* bmp-oob-alert out-of-band alarm component +* bmp-oob-agent out-of-band monitoring information collection component +* bmp-monitor-proxy in-band monitoring forwarding component +* bmp-prometheus monitoring data collection component +* bmp-pushgateway collects monitoring data from bmp-monitor-proxy and pushes it to Prometheus +* bmp-alertmanager alarm component +* bmp-pronoea receives alarm information from bmp-alertmanager and converts the format, and passes it to bmp-openapi + +### Installation process +![Architecture diagram](./bmp-deploy/picture/bm-deploy.png) +### Installation process description +1. The client (bmp-console-web) initiates the installation request, and bmp-console-api receives the request +2. bmp-console-api checks the request parameters and forwards the request to bmp-openapi if it passes. +3. bmp-openapi performs permission checks and other operations, generates installation parameters, and sends them to bmp-scheduler. +4. bmp-scheduler schedules installation tasks, generates a series of installation instructions, and sends them to bmp-dhcp-agent, bmp-driver, and bmp-agent through the bmp-mq service. +5. bmp-dhcp-agent receives the instructions and sets the built-in dhcp server so that the bm node can obtain the correct ip configuration and tftp address (bmp-tftp address) during the pxe startup phase. +6. After receiving the instructions, bmp-driver sets the bm node to pxe startup and restarts. +7. The bm node executes pxe startup, the PXEClient built into the network card starts, and sends a dhcp request broadcast. After receiving the dhcp request, the built-in dhcp server of bmp-dhcp-agent responds with the corresponding ip configuration and tftp address. +8. PXEClient configures its own IP, then downloads the pxe boot program from bmp-tftp and executes it. The pxe boot program continues to obtain other boot parameters from bmp-tftp, downloads the kernel and initramfs, starts the memory operating system, and the bmp-agent service built into the memory operating system starts to start +9. bmp-agent receives instructions and performs subsequent bm installation operations, such as setting up raid, partitioning, etc. +10. bmp-agent downloads the client operating system image file from bmp-image, writes it to the bm node disk, and then initializes the client operating system +11. bmp-agent executes a restart to complete the operating system installation + +### Monitoring process +![monitor.png](bmp-deploy/picture/monitor.png) +1. The monitoring probe collects host monitoring information and aggregates it to the bmp-monitor-proxy component +2. bmp-monitor-proxy passes the monitoring information to bmp-pushgateway +3. bmp-prometheus regularly pulls monitoring data from bmp-pushgateway +4. After bmp-prometheus triggers the alarm rule, the alarm information is passed to bmp-alertmanager +5. bmp-alertmanager transfers the alarm information to bmp-pronoea for format conversion +6. bmp-pronoea transfers it to bmp-api for alarm display and alarm + +### Glossary +* manager node: bmp management server, running all bmp components (except bmp-agent) +* bm node: bare metal server, a physical server for normal operation, without an operating system before installation, running LiveOS during the installation phase, and running GuestOS after installation +* GuestOS: a normal operating operating system +* LiveOS: a memory operating system with bmp-agent pre-installed +* out-of-band network card: a special network card on a physical server used to communicate with bmc, also known as an ipmi network card +* management network card: a standard network card on a physical server, in the management network +* management network: 3-layer network, the management network card of the manager node communicates with the management network card of the bm node through the management network + +## Local development and debugging +### BMP codes are divided into the following categories: + +| Application components | Category | Language/component | +|-------------------|------| --- | +| bmp-console-web | front-end | vue | +| bmp-operation-web | front-end | vue | +| bmp-console-api | back-end | go | +| bmp-operation-api | back-end | go | +| bmp-openapi | back-end | go | +| bmp-scheduler | back-end | go | +| bmp-openapi-console | back-end | go | +| bmp-driver | back-end | go | +| bmp-oob-alert | back-end | go | +| bmp-oob-agent | back-end | go | +| bmp-pronoea | backend | go | +| bmp-monitor-proxy | backend | go | +| bmp-dhcp-agent | backend | python | +| bmp-image | basic components | nginx | +| bmp-tftp | basic components | tftp | +| bmp-db | basic components | mysql | +| bmp-redis | basic components | redis | +| bmp-mq | basic components | rabbitmq | +| bmp-rsyslog | open source components | rsyslog | +| bmp-pushgateway | open source components | pushgateway | +| bmp-alertmanager | open source components | alertmanager | +| bmp-prometheus | open source components | prometheus | + +### front-end components vue + +| application components | categories | language/components | +|-------------------|------| --- | +| bmp-console-web | front-end | vue | +| bmp-operation-web | front-end | vue | + +~~~ +# node version requirements +Version 16.19.0 + +# Install nodejs +wget https://nodejs.org/dist/v16.19.0/node-v16.19.0-linux-x64.tar.xz +tar -xvf node-v16.19.0-linux-x64.tar.xz +mv node-v16.19.0-linux-x64 /usr/local/nodejs +cd /usr/bin +ln -s /usr/local/nodejs/bin/node node +ln -s /usr/local/nodejs/bin/npm npm +ln -s /usr/local/nodejs/bin/npx npx + +# Configure npm image +npm config set registry http://registry.m.jd.com + +# Install dependencies +npm install --legacy-peer-deps + +# Packaging +npm run build-pre + +# Local development and testing +npm run dev +~~~ +### Backend go component + +| Application component | Category | Language/component | +|-------------------|------| --- | +| bmp-console-web | Frontend | vue | +| bmp-operation-web | Frontend | vue | +| bmp-console-api | Backend | go | +| bmp-operation-api | Backend | go | +| bmp-openapi | Backend | go | +| bmp-scheduler | Backend | go | +| bmp-openapi-console | Backend | go | +| bmp-driver | Backend | go | +| bmp-oob-alert | Backend | go | +| bmp-oob-agent | Backend | go | +| bmp-pronoea | Backend | go | +| bmp-monitor-proxy | Backend | go | +~~~ +# Version requirement: golang:1.17 +# Example bmp-openapi + +cd bmp-openapi + +# Compile +go build -o bmp-openapi + +# Run +./bmp-openapi +~~~ +Please note: The backend service needs to rely on middleware and other components. If local joint debugging is required, the dependent components need to be deployed in advance. For specific dependencies, see the conf directory file in each go component. For example, the conf file bmp-openapi.ini of bmp-openapi is as follows +~~~ +# mysql +jdbc.url= +bmp_db_host=${BMP_DB_HOST} +bmp_db_port=${BMP_DB_PORT} +bmp_db_user=${BMP_DB_USER} +bmp_db_password=${BMP_DB_PASSWORD} +bmp_db_name=${BMP_DB_NAME} + +bmp_redis_host=${BMP_REDIS_HOST} +bmp_redis_port=${BMP_REDIS_PORT} +bmp_redis_password=${BMP_REDIS_PASSWORD} + + +# RabbitMQ for Ironic +bmp_mq_host=${BMP_MQ_HOST} +bmp_mq_port=${BMP_MQ_PORT} +bmp_mq_user=${BMP_MQ_USER} +bmp_mq_password=${BMP_MQ_PASSWORD} +bmp_mq_vhost=${BMP_MQ_VHOST} +bmp_mq_exchange=CPS_IRONIC_SCHEDULER +bmp_mq_receive_routing_key=/test + +bmp_monitor_proxy_host=${BMP_MONITOR_PROXY_HOST||192.168.12.72} +bmp_monitor_proxy_port=${BMP_MONITOR_PROXY_PORT||8805} + +bmp_pronoea_host=${BMP_PRONOEA_HOST||192.168.12.75} +bmp_pronoea_port=${BMP_PRONOEA_PORT||9999} + +bmp_image_host=${BMP_IMAGE_HOST||192.168.12.72} +bmp_image_port=${BMP_IMAGE_PORT||10000} +~~~ +- Backend python component + +| Application component | Category | Language/component | +|-------------------|------| --- | +| bmp-dhcp-agent | Backend | python | +~~~ +# Requires python3.6+ environment + +# Locally install dhcp service, for example centos system +sudo yum install dhcp + +# Install python dependencies +pip install -i https://mirrors.jd.com/pypi/web/simple -r requirements.txt + +# Run +cd bmp-dhcp-agent +python3 bmp-dhcp-agent./bmpda/cmd/server.py +~~~ +### Basic component +#### bmp-image +Main storage GuestOS image file, bmp-agent (installation node agent), device_import template (excel file), and use nginx to provide http service to the outside world +~~~ +# Step 1: Install nginx, taking cetos as an example +yum install nginx +systemctl start nginx + +# Step 2: Download files from JD Cloud Object Storage, +# The current downloadable images are recorded in config/image.cfg + +# Download address: +bmp_oss_url=https://bmp.s3.cn-north-1.jdcloud-oss.com + +# GuestOS image +bmp_oss_guestos_prefix=GuestOS +bmp_images_x86=( + v1.7.0-centos-7.9-2022070716.tar.xz + v1.7.0-ubuntu-18.04-2022062709.tar.xz +) +bmp_images_arm64=( + v1.7.0-centos-7.9-arm-2023080716.tar.xz + v1.7.0-ubuntu-18.04-arm-2023081111.tar.xz +) +bmp_images_loonarch64=( + v1.7.0-loongnix-8.4-2023110218.tar.xz +) + +# bmp-agent +bmp_oss_agent_prefix=others +bmp_agent_images=( + bmp-agent.bin + bmp-agent.bin.arm + bmp-agent-windows.tgz +) +# Example of downloading bmp-agent +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/others/bmp-agent.bin + +# Step 3: Copy the downloaded file to the file directory of nginx, and take the default configuration of nginx as an example +cat default.conf +server { + listen 80; + listen [::]:80; + server_name localhost; + location / { + root /usr/share/nginx/html; + index index.html index.htm; + } + error_page 500 502 503 504 /50x.html; + location = /50x.html { + root /usr/share/nginx/html; + } +} +All files downloaded in step 2 need to be copied to the /usr/share/nginx/html directory +# Step 4: Start nginx +systemctl start nginx +# For more nginx configurations, please refer to the official website: +https://nginx.org/en/docs/ +~~~ + +#### bmp-tftp + +| Application Components | Category | Language/Component | +|-------------------|------| --- | +| bmp-tftp | Basic Components | tftp | + +Let's briefly review the role of the following tftp service in the installation process: +Step 1: The installation node executes pxe startup, the PXEClient built into the network card starts, and sends a dhcp request broadcast. After receiving the dhcp request, the dhcp server built into the bmp-dhcp-agent responds to the corresponding ip configuration and tftp address +Step 2: PXEClient configures its own IP, then downloads the pxe boot program from bmp-tftp and executes it. The pxe boot program continues to obtain other boot parameters from bmp-tftp, downloads the kernel and initramfs, starts the memory operating system, and the bmp-agent service built into the memory operating system starts to start (this process is automatically downloaded by the system and does not require manual configuration) +So: bmp-tftp provides services for downloading kernels and liveOS images related to system startup +~~~ +# Step 1: Install tftp +yum install tftp-server +Configure the TFTP server. In CentOS 7 and later versions, the configuration file for the TFTP service is located in /etc/xinetd.d/tftp. Use a text editor (such as vi or nano) to open the file and change disable = yes to disable = no to enable the TFTP service. +Save and close the file, then restart the xinetd service: +systemctl restart xinetd + +# Step 2: Download the kernel and liveOs files from JD Cloud Object Storage + +# The current downloadable images are recorded in config/image.cfg + +# Download address: +bmp_oss_url=https://bmp.s3.cn-north-1.jdcloud-oss.com + +# bootloader +bmp_bootloader_prefix=bootloader +bmp_bootloader_images=( + BOOTLOONGARCH64.EFI + grubaa64.efi + grubx64.efi + pxelinux.0 +) + +# LiveOS image bmp_oss_liveos_prefix=LiveOS bmp_kernel_name_x86=v2.0.7-centos_7_9-2024082914-vmlinuz bmp_initramfs_name_x86=v2.0.7-centos_7_9-2024082914-initramfs.gz bmp_kernel_name_arm64=v2.0.7-centos_7_9_ arm64-2024082914-vmlinuz bmp_initramfs_name_arm64=v2.0.7-centos_7_9_arm64-2024082914-initramfs.gz bmp_kernel_name_loonarch64=vmlinuz-loongarch bmp_initramfs_name_loonarch64=initramfs-loongarch.gz # Example; wget https://bmp.s3.cn-north-1.jdcloud-oss.com/bootloader/BOOTLOONGARCH64.EFI wget https://bmp.s3.cn-north-1.jdcloud-oss.com/LiveOS/v2.0.7-centos_7_9-2024082914-vmlinuz + +# Step 3: Copy the downloaded file to the tftp file directory +The location of the tftp file directory needs to be checked in the /etc/xinetd.d/tftp file, for example: +service tftp +{ + socket_type = dgram + protocol = udp + wait = yes + user = root + server = /usr/sbin/in.tftpd + server_args = -s /var/lib/tftpboot + disable = yes + per_source = 11 + cps = 100 2 + flags = IPv4 +} +The tftp file directory is /var/lib/tftpboot +Copy the file to the /var/lib/tftpboot directory, the structure is as follows: +. +├── images +│   ├── arm64 +│   │   ├── v2.0.7-centos_7_9_arm64-2024082914-initramfs.gz +│   │   └── v2.0.7-centos_7_9_arm64-2024082914-vmlinuz +│   └── loongarch64 +│   ├── initramfs-loongarch.gz +│   └── vmlinuz-loongarch +├── pxelinux.0 +├── pxelinux.cfg +│   └── default +├── uefi +│   ├── arm64 +│   │   ├── grubaa64.efi +│   │   └── grub.cfg +│   ├── loongarch64 +│   │   ├── BOOTLOONGARCH64.EFI +│   │   └── grub.cfg +│   └── x86_64 +│   ├── grub.cfg +│   └── grubx64.efi +├── v2.0.7-centos_7_9-2024082914-initramfs.gz +└── v2.0.7-centos_7_9-2024082914-vmlinuz + +- pxelinux +- x86_64/grub.cfg +- arm64/grub.cfg +- loongarch64/grub.cfg +The configuration templates of these four files are located in the template directory and need to be copied manually + +# Step 4: Start tftp service +systemctl restart xinetd +~~~ + +#### bmp-mysql + +| Application Components | Category | Language/Components | +|-------------------|------| --- | +| bmp-db | Basic Components | mysql | + +Here are the basic steps to install and deploy MySQL on a Linux system: +~~~ +# Step 1: Install MySQL +sudo yum install mysql-server mysql -y + +# Step 2: Start the MySQL service +sudo systemctl start mysqld + +# Step 3: Run the security script + +Run the MySQL security script to set the root password and other security options: +sudo mysql_secure_installation +Follow the prompts, including setting the root password, removing anonymous users, disabling root remote login, etc. + +# Step 4: Log in to MySQL +mysql -u root -p +Enter the password you set in the previous step. + +# Step 5: Create a new user and database +CREATE USER 'bmp_rw'@'%' IDENTIFIED BY 'LpK9Jq12Zf'; +CREATE DATABASE bmp; +GRANT ALL PRIVILEGES ON bmp.* TO 'bmp_rw'@'%'; +FLUSH PRIVILEGES; + +# Step 6: Import initialization data +The data is located in sql/bmp.sql, import command +mysql -uroot -p bmp' < ./sql/bmp.sql +Enter the set root password +~~~ +#### bmp-redis + +| Application Components | Category | Language/Component | +|-------------------|------| --- | +| bmp-redis | Basic Components | redis | + +~~~ +To install Redis on CentOS 7, follow these steps: + +# Step 1: Update System Packages +# First, update the system packages to get the latest package list: +sudo yum update -y + +# Step 2: Install EPEL repository +# Redis is not part of the default software source of CentOS, so we need to add the EPEL (Extra Packages for Enterprise Linux) repository to get the Redis installation package: +sudo yum install epel-release -y + +# Step 3: Install Redis +sudo yum install redis -y + +# Step 4: Configure Redis password +The Redis configuration file is located in /etc/redis.conf +Uncomment the requirepass line and add the password you want to set after it. For example: +requirepass LpK9Jq12Zf + +# Step 5: Start the Redis service +sudo systemctl start redis + +# Step 6: Test the password +redis-cli -a mystrongpassword ping +~~~ +#### bmp-mq + +| Application Components | Category | Language/Component | +|-------------------|------| --- | +| bmp-mq | Basic Components | rabbitmq | + +~~~ +To install RabbitMQ on CentOS 7, follow these steps: + +# Step 1: Add EPEL repository + +First, you need to add the EPEL (Extra Packages for Enterprise Linux) repository to get the RabbitMQ installation package: +sudo yum install epel-release -y + +# Step 2: Install Erlang +# RabbitMQ is written in Erlang, so we need to install Erlang first: +sudo yum install erlang -y + +# Step 3: Install RabbitMQ +sudo yum install rabbitmq-server -y + +# Step 4: Start the RabbitMQ service +sudo systemctl start rabbitmq-server + +# Step 5: Create an administrator account +# By default, RabbitMQ does not have the management plugin enabled. We need to create an administrator account and enable the management plugin: +rabbitmqctl add_vhost /bmp +rabbitmqctl add_user bmp "LpK9Jq12Zf" +rabbitmqctl set_user_tags bmp administrator +rabbitmqctl set_permissions -p "/bmp" bmp '.*' '.*' '.*' +rabbitmqctl list_users +rabbitmqctl change_password $BMP_MQ_USER "$BMP_MQ_PASSWORD" +### 7. Access RabbitMQ Management Interface + +You can now access the RabbitMQ management interface by accessing `http://your-server-ip:15672` through your browser. Log in using the administrator account you just created. +~~~~ +#### bmp-rsyslog + +| Application Components | Category | Language/Component | +|-------------------|------| --- | +| bmp-rsyslog | Open Source Components | rsyslog | + +~~~ +To install rsyslog on CentOS 7, follow these steps: + +# Step 1: Update system packages +First, update system packages to get the latest package list: +sudo yum update -y + +# Step 2: Install rsyslog +sudo yum install rsyslog -y + +# Step 3: Configure rsyslog +cat << EOF > /etc/rsyslog.d/bmp-rsyslog.conf +module(load="imudp") # needs to be done just once +input(type="imudp" port="514") +$template RemoteLogs,"/var/log/bmp/bmp-rsyslog/%fromhost-ip%/%PROGRAMNAME%-%$YEAR%-%$MONTH%-%$DAY%.log" +$template DynamicDir,"/var/log/bmp/bmp-rsyslog/%fromhost-ip%" +:syslogtag, startswith, "ip" ?DynamicDir +if $fromhost-ip != "127.0.0.1" then ?RemoteLogs +& ~ +EOF + +# Step 4: Start the rsyslog service +sudo systemctl start rsyslog +~~~ + +### Open Source Components + +| Application Components | Category | Language/Components | +|-------------------|------| --- | +| bmp-prometheus | Open Source Components | prometheus | +| bmp-pushgateway | Open Source Components | pushgateway | +| bmp-alertmanager | Open source component | alertmanager | +The above three monitoring and alarm components are open source Prometheus solutions and can be installed and used together. +The working principle of the three is +1. The application or service pushes the indicator data to Pushgateway. +2. The Prometheus server regularly pulls these indicator data from Pushgateway and stores them in its own time series database. +3. The information that triggers the alarm condition in Prometheus is sent by the alertmanager component +#### bmp-pushgateway +~~~ +To install Pushgateway on CentOS 7, follow the steps below: + +# Step 1: Download the Pushgateway binary file + +First, download the Pushgateway binary file. You can get it from the official website of Prometheus or the GitHub repository. For example, use the following command to download Pushgateway v1.4.0: +wget https://github.com/prometheus/pushgateway/releases/download/v1.4.0/pushgateway-1.4.0.linux-amd64.tar.gz + +# Step 2: Unzip the Pushgateway file +tar -xvf pushgateway-1.4.0.linux-amd64.tar.gz + +# Step 3: Create the Pushgateway user and group +sudo groupadd --system pushgateway +sudo useradd --system -s /bin/false -g pushgateway pushgateway + +# Step 4: Move the Pushgateway file to the appropriate location +sudo mv pushgateway-1.4.0.linux-amd64 /usr/local/pushgateway + +# Step 5: Set file permissions +sudo chown -R pushgateway:pushgateway /usr/local/pushgateway +sudo chmod -R 755 /usr/local/pushgateway + +# Step 6: Create Pushgateway configuration file +sudo mkdir /etc/pushgateway +sudo touch /etc/pushgateway/pushgateway.yml +Edit the `pushgateway.yml` file and add the configuration you want. For example: +web: +listen-address: ":9091" + +# Step 7: Create Pushgateway service file +sudo cat << EOF > /etc/systemd/system/pushgateway.service +[Unit] +Description=Pushgateway +Wants=network-online.target +[Service] +User=pushgateway +Group=pushgateway +ExecStart=/usr/local/pushgateway/pushgateway \ +--config.file /etc/pushgateway/pushgateway.yml \ +--web.listen-address :9091 +--web.enable-admin-api +Restart=always +[Install] +WantedBy=multi-user.target +EOF + +# Step 8: Start Pushgateway service +sudo systemctl daemon-reload +sudo systemctl start pushgateway +~~~ +#### bmp-prometheus +~~~ +To install Prometheus on CentOS, follow these steps: + +# Step 1: Download the Prometheus binary file +wget https://github.com/prometheus/prometheus/releases/download/v2.36.1/prometheus-2.36.1.linux-amd64.tar.gz + +# Step 2: Unzip the Prometheus file +tar -xvf prometheus-2.36.1.linux-amd64.tar.gz + +# Step 3: Create a Prometheus user and group +sudo groupadd --system prometheus +sudo useradd --system -s /bin/false -g prometheus prometheus + +# Step 4: Move the Prometheus file to the appropriate location +sudo mv prometheus-2.36.1.linux-amd64 /usr/local/prometheus + +# Step 5: Set file permissions +sudo chown -R prometheus:prometheus /usr/local/prometheus sudo chmod -R 755 /usr/local/prometheus +# Step 6: Create Prometheus configuration file +sudo mkdir /etc/alertmanager +sudo cat << EOF > /etc/alertmanager/alertmanager.yml +global: + resolve_timeout: 5s +route: + group_by: ['alertname'] + group_wait: 0s + group_interval: 60m + repeat_interval: 10s + receiver: 'bmpAlertReceiver' + routes: + - receiver: 'bmpAlertReceiver' + group_interval: 5m + match: + noticePeriodLabel: NoticePeriod-5m + - receiver: 'bmpAlertReceiver' + group_interval: 10m + match: + noticePeriodLabel: NoticePeriod-10m + - receiver: 'bmpAlertReceiver' + group_interval: 15m + match: + noticePeriodLabel: NoticePeriod-15m + - receiver: 'bmpAlertReceiver' + group_interval: 30m + match: + noticePeriodLabel: NoticePeriod-30m + - receiver: 'bmpAlertReceiver' + group_interval: 60m + match: + noticePeriodLabel: NoticePeriod-60m + - receiver: 'bmpAlertReceiver' + group_interval: 180m + match: + noticePeriodLabel: NoticePeriod-180m + - receiver: 'bmpAlertReceiver' + group_interval: 720m + match: + noticePeriodLabel: NoticePeriod-720m + - receiver: 'bmpAlertReceiver' + group_interval: 1440m + match: + noticePeriodLabel: NoticePeriod-1440m +receivers: + - name: 'bmpAlertReceiver' + webhook_configs: + - url: 'http://${BMP_PRONOEA_HOST}:${BMP_PRONOEA_PORT}/api/alert/receiver' +EOF +Please note that BMP_ALERTMANAGER_HOST and BMP_PUSHGATEWAY_PORT variables are set + +# Step 7: Create Prometheus service file +sudo cat << EOF > /etc/systemd/system/alertmanager.service +[Unit] +Description=Alertmanager +Wants=network-online.target + +[Service] +User=alertmanager +Group=alertmanager +ExecStart=/usr/local/alertmanager/alertmanager \ + --config.file /etc/alertmanager/alertmanager.yml \ + --web.listen-address :9093 + --log.level=debug +Restart=always + +[Install] +WantedBy=multi-user.target +EOF + +# Step 8: Start Prometheus service +sudo systemctl daemon-reload +sudo systemctl start prometheus +~~~ + +#### bmp-alertmanager +~~~ +# Step 1: Download Alertmanager binary file +wget https://github.com/prometheus/alertmanager/releases/download/v0.24.0/alertmanager-0.24.0.linux-amd64.tar.gz + +# Step 2: Unzip Alertmanager file +tar -xvf alertmanager-0.24.0.linux-amd64.tar.gz + +# Step 3: Create Alertmanager user and group +sudo groupadd --system alertmanager +sudo useradd --system -s /bin/false -g alertmanager alertmanager + +# Step 4: Move the Alertmanager file to the appropriate location +sudo mv alertmanager-0.24.0.linux-amd64 /usr/local/alertmanager + +# Step 5: Set file permissions +sudo chown -R alertmanager:alertmanager /usr/local/alertmanager +sudo chmod -R 755 /usr/local/alertmanager + +# Step 6: Create the Alertmanager configuration file +sudo mkdir /etc/alertmanager +sudo cat << EOF > /etc/alertmanager/alertmanager.yml +global: + resolve_timeout: 5s +route: + group_by: ['alertname'] + group_wait: 0s + group_interval: 60m + repeat_interval: 10s + receiver: 'bmpAlertReceiver' + routes: + - receiver: 'bmpAlertReceiver' + group_interval: 5m + match: + noticePeriodLabel: NoticePeriod-5m + - receiver: 'bmpAlertReceiver' + group_interval: 10m + match: + noticePeriodLabel: NoticePeriod-10m + - receiver: 'bmpAlertReceiver' + group_interval: 15m + match: + noticePeriodLabel: NoticePeriod-15m + - receiver: 'bmpAlertReceiver' + group_interval: 30m + match: + noticePeriodLabel: NoticePeriod-30m + - receiver: 'bmpAlertReceiver' + group_interval: 60m + match: + noticePeriodLabel: NoticePeriod-60m + - receiver: 'bmpAlertReceiver' + group_interval: 180m + match: + noticePeriodLabel: NoticePeriod-180m + - receiver: 'bmpAlertReceiver' + group_interval: 720m + match: + noticePeriodLabel: NoticePeriod-720m + - receiver: 'bmpAlertReceiver' + group_interval: 1440m + match: + noticePeriodLabel: NoticePeriod-1440m +receivers: + - name: 'bmpAlertReceiver' + webhook_configs: + - url: 'http://${BMP_PRONOEA_HOST}:${BMP_PRONOEA_PORT}/api/alert/receiver' +EOF +Please pay attention to setting the service IP and port of pronoea: BMP_PRONOEA_HOST and BMP_PRONOEA_PORT +### 7. Create Alertmanager service file +sudo cat << EOF > /etc/systemd/system/alertmanager.service +[Unit] +Description=Alertmanager +Wants=network-online.target + +[Service] +User=alertmanager +Group=alertmanager +ExecStart=/usr/local/alertmanager/alertmanager \ +--config.file /etc/alertmanager/alertmanager.yml \ +--web.listen-address :9093 +--log.level=debug +Restart=always + +[Install] +WantedBy=multi-user.target +EOF + +# Step 8: Start Alertmanager service +sudo systemctl daemon-reload +sudo systemctl start alertmanager +~~~ \ No newline at end of file diff --git a/docs/setup.md b/docs/setup.md new file mode 100644 index 0000000..c0ede59 --- /dev/null +++ b/docs/setup.md @@ -0,0 +1,223 @@ +# One-click deployment of BMP system +- [One-click deployment overview](#1) +- [Term explanation](#1.1) +- [Overall deployment steps](#1.2) +- [Environment preparation](#2) +- [Management node deployment](#3) +- [Environment preparation](#3.1) +- [Configure environment parameters](#3.2) +- [One-click deployment of BMP](#3.3) +- [Access BMP](#3.4) +- [BMP platform manages physical servers](#3.5) +- [Virtual machine simulation deployment](#4) +## One-click deployment overview +### Term explanation +- BMP +Bare Metal Manage Platform, referred to as BMP. +- manager node +BMP management server (management node), running all BMP components (except bmp-agent) +- bm node +Installation node, a physical server for normal work, without operating system before installation, running LiveOS during installation, and running GuestOS after installation. +- GuestOS +A normal operating system +- LiveOS +A memory operating system with bmp-agent pre-installed +- Out-of-band network card +A special network card on a physical server used to communicate with bmc, also known as an ipmi network card +- Management network card +A standard network card on a physical server, located in the management network + +### Overall deployment steps +- The manager node and the bm node are in a large layer 2 network (if you only experience the BMP platform and do not intend to experience the BMP bare metal installation process, this step can be skipped) +- Install the operating system CentOS 7.9 on the manager node +- Configure the dhcp-relay address of the bm node tor to the ip address of the manager node (if you only experience the BMP platform and do not intend to experience the BMP bare metal installation process, this step can be skipped) +- Deploy the BMP platform through docker on the manager node. Refer to [Management node deployment](#3) + +## Environment preparation +**Environment preparation includes *network environment preparation* and *Server preparation* Two parts, the overall architecture is as follows** + +![bmp-framework_en.png](bmp-deploy/picture/bmp-framework_en.png) + +### 1. Network preparation +*Please note: If you only experience the BMP management component, the following network environment configuration can be skipped; if you are preparing for real installation, the following network configuration must be performed* +The manager node and the bm node are in a large Layer 2 network, and the bm node needs to obtain its IP address based on the DHCP service. +Before deploying the BMP platform, you need to configure the dhcp-relay of the upstream switch of the installation node to the manager node. +The following shows an example network configuration + +![network-deploy.png](bmp-deploy/picture/network-deploy.png) +In this network structure, TOR1 represents the upstream switch of the installation node eth0 network card. +- manager node +eth0 ip: 192.168.14.80/27 +This address is usually a private network address, and the DHCP service of BMP will be started on this private network address. This private network address will also be notified to the BMP platform through the configuration file, see [Configure environment parameters](#3.2) for details +- bm node +ipmi ip: 192.168.11.130/27 +- TOR1 +ip: 192.168.12.129/27 +vlan id: 200 +- Log in to TOR1, check the dhcp relay of vlan 200, and check whether the relay address is the manager node management network card ip (in this example, 192.168.14.80) +Log in to TOR1: ssh switchuser@192.168.12.129, enter the password. +H3C switch command: dis cu int Vlan-interface 200 +~~~ +Here are the steps to reconfigure DHCP relay using H3C switch: + +#Enter system view: +system-view +#Enter interface view, for example VLAN interface 200: +interface vlan 200 +#Configure the server address of DHCP relay, i.e. management node ip: +dhcp relay server 192.168.14.80 +#Save configuration: +save f +#Return to system view: +quit +#Exit configuration mode: +quit + +Please note that the specific commands and parameters may vary depending on the switch model, software version, and configuration. Make sure you understand the specific configuration requirements of your switch. +~~~ +#### The BMP standard network communication process is shown in the figure: +![network.png](bmp-deploy/picture/network.png) +* The out-of-band network card ipmi of the physical machine, the management network card eth0 and the management network card eth0 of the manager node are all in the same Layer 2 management network. +* Each BMP component in the manager node runs as a container, and the service port is exposed to the management network access through docker-proxy and the eth0 network card. +* The built-in BMC management system of the bm node is exposed to the management network access through the ipmi network card +* Other services running on the bm node are exposed to the management network access through the eth0 network card +* In order to ensure that the system running on the bm node can obtain the IP configuration from the built-in DHCP server of the bmp-dhcp-agent container of the manager node, the upstream switch of the eth0 network card of the bm node may need to be configured with a DHCP relay, and the relay address is the management IP of the manager node. +* At the beginning of the installation, the bmp-driver accesses the out-of-band IP of the bm node through the management network to set the boot mode of the physical machine and control the power on and off. +* During the pxe boot phase, the PXEClient built into the eth0 network card of the bm node accesses the dhcp server built into the bmp-dhcp-agent through the management network, obtains the ip configuration and the pxe boot program download address, sets the eth0 ip, and downloads the LiveOS kernel and initramfs from bmp-tftp, and then starts LiveOS. +* When LiveOS starts, it also obtains the ip configuration from the dhcp server built into the bmp-dhcp-agent and sets the eth0 ip. +* During the GuesOS installation phase, bmp-agent can obtain the required installation information from bmp-mq, or download the GuestOS image from bmp-tftp +* Regardless of whether PXEClient, LiveOS or GustOS is running, the ip of the management network card eth0 of the bm node is the same, and the specific ip address is set in Operation Platform-Device Management. Please assign the correct ip address to the bm node to ensure that the system running on the bm node at each stage can work properly. + +### 2. Server preparation +manager node: +~~~ +Resource requirements +cpu: 4 cores +Memory: 8 GB +Disk: 40 GB +Operating system: CentOS 7.9 +Network requirements +Access to the public network +Ports that need to be opened to client browsers: 8080, 8081 +Ports that need to be opened to management network access: 10000, 5672, 67/udp, 69/udp +~~~ +Minimum configuration of the installed node +~~~ +cpu: 1 core +Memory: 2 GB +Disk: 40 GB +Has an out-of-band network card and a management network card +~~~ + +## Management node deployment +~~~ +Step 1: Environment preparation + +Step 2: Configure environment parameters + +Step 3: One-click deployment of BMP + +Step 4: Access BMP + +Step 5: BMP platform manages physical servers +~~~ + +### Step 1: Environment preparation id="3.1"> + +#### 1. Install docker and docker compose +- yum installation method (CentOS 7.9 system) +~~~ +#You can use domestic mirror sources, such as Tsinghua mirror sources +yum install -y yum-utils +yum-config-manager \ +--add-repo \ +https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/centos/docker-ce.repo +sed -i 's+https://download.docker.com+https://mirrors.tuna.tsinghua.edu.cn/docker-ce+' /etc/yum.repos.d/docker-ce.repo + +yum install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin + +systemctl start docker +~~~ + +For more installation methods, please refer to the docker official website +- Docker official document address: https://docs.docker.com/ +- Docker Compose official document address: https://docs.docker.com/compose/ + +### 2. Download BMP source code to the manager node server +Before downloading, first clarify the deployment directory of BMP. This instance is installed in the user's home directory by default. First +~~~ +# Jump to the home directory, and then execute the subsequent download command +cd ~ +~~~ +Find the [Code] button in the upper right corner of the homepage and click the drop-down menu, as shown in the figure +![github.png](bmp-deploy/picture/github.png) +- Method 1: Use the git clone command +~~~ +# Execute on the management node, clone the HTTPS link copied above, for example: +git clone https://github.com/jd-opensource/Baremetal_Manage_Platform.git +~~~ +- Method 2: Click Download ZIP, download the zip package directly, and manually transfer it to the management server +For more github operations, refer to the official github operation document: +https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository +- Method 3: You can download the installation package directly from JD Cloud +~~~ +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/opensource/Baremetal_Manage_Platform-33040a7.zip +unzip Baremetal_Manage_Platform-33040a7.zip -d Baremetal_Manage_Platform +~~~ + +### Step 2: Configure environment parameters +- Deployment script directory +The deployment script is located in the bmp-deploy directory +File description in the directory: [bmp-deploy file and directory description] (bmp-deploy/bmp-deploy.md) + +- Modify configuration +Edit .env file +- Modify BMP_HOST_IP to the manager node management network card IP. This example is 192.168.14.80. If the server has multiple network cards, please configure one of the IPs. If bond is configured, use the bond network card. Otherwise, try to choose a network card with a private network IP address. +ifconfig command-bond0 example image +![ifconfig-bond0.png](bmp-deploy/picture/ifconfig-bond0.png) +ifconfig command-eth0 example image +![ifconfig-eth0.png](bmp-deploy/picture/ifconfig-eth0.png) +- Modify BASE_REGISTRY. Deployment requires the use of basic container images such as mysql/redis/mq/nginx. This example pulls from quay.io by default. If the network is restricted, please modify it to other public or private image repositories + +~~~ +cd ~/Baremetal_Manage_Platform/bmp-deploy/ +# Check the server IP address, first check the IP address of bond0, and then check the IP address of eth0. If you are not sure, please consult the operation and maintenance personnel. +ifconfig + +# Edit environment variables +# Must be consistent with the manager node server IP +# Set BMP_HOST_IP=192.168.14.80 +vi .env +~~~ + +For more configurations, please refer to [Configuration Management](bmp-deploy/config.md) + +### Step 3: One-click deployment of BMP +- Install BMP +~~~ +cd ~/Baremetal_Manage_Platform/bmp-deploy/ +bash bmp-deploy-precheck.sh -e public +bash bmp-deploy.sh start all +~~~ + +- Check the status of each service +~~~ +bash bmp-deploy.sh status all +~~~ +Under normal circumstances, the status of all services is running. If some services are not running, refer to [Troubleshooting](bmp-deploy/troubleshoot.md) +During the installation process, the relevant operating system image will be automatically downloaded from JD Object Storage. The download speed is related to the server network speed. Please wait patiently. +For more service management operations, refer to [Service Management](bmp-deploy/service-manage.md) + +### Step 4: Access BMP +Note: Default account: admin, password: df9Ydfd$c + +Console: http://manager_ip:8080. This example is http://192.168.14.80:8080. + +Operation platform: http://manager_ip:8081. This example is http://192.168.14.80:8081. + +### Step 5: Manage bare metal servers on the management platform +Log in to the BMP operation platform, enter the device management interface, and import the bm node information + +## Virtual machine simulation deployment +* Intranet IPv4, network subnet mask and gateway Please fill in the correct address so that the PXEClient, LiveOS, and GuestOS running on the bm node can access the manager network normally. +If you want to use a virtual machine to simulate a bm node, see [Virtual machine simulation bm node](bmp-deploy/vm-example.md) \ No newline at end of file diff --git a/docs/zh/bmp-deploy/bmp-deploy.md b/docs/zh/bmp-deploy/bmp-deploy.md new file mode 100644 index 0000000..f9a8198 --- /dev/null +++ b/docs/zh/bmp-deploy/bmp-deploy.md @@ -0,0 +1,34 @@ +# `bmp-deploy`文件和目录说明 +## 文件和目录列表 +~~~ +bmp-deploy目录 +├── bmp-deploy.sh +├── bmp-deploy-precheck.sh +├── bmp-build-image.sh +├── cache +├── config +├── data +├── docker-compose.yml +├── env +├── .env +├── ReleaseNotes +├── script +├── sql +├── template +└── tool +~~~ +## 文件和目录说明 +* bmp-deploy.sh 主部署脚本 +* bmp-deploy-precheck.sh 部署前预检查脚本 +* bmp-build-image.sh 容器镜像制作脚本 +* cache GuestOS镜像和LiveOS镜像缓存目录 +* config 配置目录 +* data 其它二进制文件缓存目录,包含pxe引导程序,设备导入模板 +* docker-compose.yml docker-compose服务编排文件 +* env 各组件环境变量目录 +* .env docker-compose环境变量主配置文件 +* ReleaseNotes 版本发布信息 +* script 各组件初始化脚本目录 +* sql 数据库初始化脚本目录 +* template 模板文件目录 +* tool 工具目录 diff --git a/docs/zh/bmp-deploy/config.md b/docs/zh/bmp-deploy/config.md new file mode 100644 index 0000000..54fd7e1 --- /dev/null +++ b/docs/zh/bmp-deploy/config.md @@ -0,0 +1,96 @@ +# [bmp安装指导](main.md) - 配置管理 +.env文件包含bmp各种配置参数 +~~~ +BMP_HOST_IP=xxx.xxx.xxx.xxx +# bmp registry +BMP_REGISTRY=docker.io + +# db middleware registry eg: mysql:5.7-debian +# if you cannot pull from docker.io please change docker.io to other Container image repository +BASE_REGISTRY=docker.m.daocloud.io + +BMP_VERSION=dev +COMPOSE_PROJECT_NAME=bmp +BMP_DB_HOST=bmp-db +BMP_DB_PORT=3306 +BMP_DB_USER=bmp_rw +BMP_DB_PASSWORD='LpK9Jq12Zf' +BMP_DB_NAME=bmp +BMP_REDIS_HOST=bmp-redis +BMP_REDIS_PORT=6379 +BMP_REDIS_PASSWORD='LpK9Jq12Zf' +BMP_MQ_HOST=bmp-mq +BMP_MQ_PORT=5672 +BMP_MQ_USER=bmp +BMP_MQ_PASSWORD='LpK9Jq12Zf' +BMP_MQ_VHOST=/bmp +BMP_OMAPI_HOST=bmp-dhcp-agent +BMP_OMAPI_PORT=7911 +BMP_OMAPI_TOKEN="LpK9Jq12Zf" +BMP_OPENAPI_HOST=bmp-openapi +BMP_OPENAPI_PORT=8801 +BMP_OPENAPI_CONSOLE_HOST=bmp-openapi-console +BMP_OPENAPI_CONSOLE_PORT=8802 +BMP_OOB_ALERT_HOST=bmp-oob-alert +BMP_OOB_ALERT_PORT=8804 +BMP_MQ_EXCHANGE_ROUTING_KEY=idc-vm4xsulx1k2d9z4xkctrttig02zl +BMP_IMAGE_PORT=10000 +BMP_MONITOR_PROXY_PORT=8805 +BMP_PROMETHEUS_HOST=bmp-prometheus +BMP_PROMETHEUS_PORT=9090 +BMP_PROMETHEUS_DATA_DIR=/data/prometheus +BMP_PUSHGATEWAY_HOST=bmp-pushgateway +BMP_PUSHGATEWAY_PORT=9091 +BMP_ALERTMANAGER_HOST=bmp-alertmanager +BMP_ALERTMANAGER_PORT=9093 +BMP_PRONOEA_HOST=bmp-pronoea +BMP_PRONOEA_PORT=9999 +~~~ + +## 配置说明: + +| 配置名 | 说明 | +|-----------------------------|-----------------------------------------------| +| BMP_HOST_IP | manager节点ip, 请配置为管理网卡ip,bmp各服务组件监听此ip | +| BMP_VERSION | 待安装的bmp版本,请勿随便修改 | +| COMPOSE_PROJECT_NAME | docker compose 项目名,默认值是bmp,请勿修改 | +| BMP_DB_HOST | bmp-db ip/域名,请勿修改 | +| BMP_DB_PORT | bmp-db 端口,请勿修改 | +| BMP_DB_USER | bmp-db 用户名 | +| BMP_DB_PASSWORD | bmp-db 用户密码 | +| BMP_DB_NAME | bmp-db 数据库名,请勿修改 | +| BMP_REDIS_HOST | bmp-redis ip/域名,请勿修改 | +| BMP_REDIS_PORT | bmp-redis 端口,请勿修改 | +| BMP_REDIS_PASSWORD | bmp-redis 密码 | +| BMP_MQ_HOST | bmp-mq ip/域名,请勿修改 | +| BMP_MQ_PORT | bmp-mq 端口,请勿修改 | +| BMP_MQ_USER | bmp-mq 用户名 | +| BMP_MQ_PASSWORD | bmp-mq 密码 | +| BMP_MQ_VHOST | bmp-mq vhost名,请勿修改 | +| BMP_OMAPI_HOST | dhcp omapi服务 ip/域名,请勿修改 | +| BMP_OMAPI_PORT | dhcp omapi服务端口,请勿修改 | +| BMP_OMAPI_TOKEN | dhcp omapi认证token | +| BMP_OPENAPI_HOST | bmp-openapi ip/域名,请勿修改 | +| BMP_OPENAPI_PORT | bmp-openapi 端口,请勿修改 | +| BMP_OPENAPI_CONSOLE_HOST | bmp-openapi-console ip/域名,请勿修改 | +| BMP_OPENAPI_CONSOLE_PORT | bmp-openapi-console 端口,请勿修改 | +| BMP_OOB_ALERT_HOST | bmp-oob-alert ip/域名,请勿修改 | +| BMP_OOB_ALERT_PORT | bmp-oob-alert 端口,请勿修改 | +| BMP_MQ_EXCHANGE_ROUTING_KEY | mq routing key, 此值应该等于idc_id,请勿修改 | +| BMP_IMAGE_PORT | bmp 镜像服务器端口, 请勿修改 | +| BMP_MONITOR_PROXY_PORT | bmp-monitor-proxy 端口,请勿修改 | +| BMP_PROMETHEUS_HOST | bmp_prometheus ip/域名,请勿修改 | +| BMP_PROMETHEUS_PORT | bmp_prometheus 端口,请勿修改 | +| BMP_PROMETHEUS_DATA_DIR | bmp_prometheus 数据存储路径,此路径需要的存储空间较大,建议根据实际情况修改 | +| BMP_PUSHGATEWAY_HOST | bmp_pushgateway ip/域名,请勿修改 | +| BMP_PUSHGATEWAY_PORT | bmp_pushgateway 端口,请勿修改 | +| BMP_ALERTMANAGER_HOST | bmp_alertmanager ip/域名,请勿修改 | +| BMP_ALERTMANAGER_PORT | bmp_alertmanager 端口,请勿修改 | +| BMP_PRONOEA_HOST | bmp_pronoea ip/域名,请勿修改 | +| BMP_PRONOEA_PORT | bmp_pronoea 端口,请勿修改 | + +## 注意 +* BMP_DB_PASSWORD, BMP_REDIS_PASSWORD, BMP_MQ_PASSWORD, BMP_OMAPI_TOKEN的值只能由 **大小字母和数字** 组成,包含特殊字符可能会导致错误。 + + + diff --git a/docs/zh/bmp-deploy/picture/bm-deploy.png b/docs/zh/bmp-deploy/picture/bm-deploy.png new file mode 100644 index 0000000..2bbed12 Binary files /dev/null and b/docs/zh/bmp-deploy/picture/bm-deploy.png differ diff --git a/docs/zh/bmp-deploy/picture/bmp-framework.png b/docs/zh/bmp-deploy/picture/bmp-framework.png new file mode 100644 index 0000000..b274084 Binary files /dev/null and b/docs/zh/bmp-deploy/picture/bmp-framework.png differ diff --git a/docs/zh/bmp-deploy/picture/bmp-framework_en.png b/docs/zh/bmp-deploy/picture/bmp-framework_en.png new file mode 100644 index 0000000..cc907d8 Binary files /dev/null and b/docs/zh/bmp-deploy/picture/bmp-framework_en.png differ diff --git a/docs/zh/bmp-deploy/picture/bmp-pronoea.png b/docs/zh/bmp-deploy/picture/bmp-pronoea.png new file mode 100644 index 0000000..149928a Binary files /dev/null and b/docs/zh/bmp-deploy/picture/bmp-pronoea.png differ diff --git a/docs/zh/bmp-deploy/picture/bmp.png b/docs/zh/bmp-deploy/picture/bmp.png new file mode 100644 index 0000000..f9110cf Binary files /dev/null and b/docs/zh/bmp-deploy/picture/bmp.png differ diff --git a/docs/zh/bmp-deploy/picture/bmp_en.png b/docs/zh/bmp-deploy/picture/bmp_en.png new file mode 100644 index 0000000..c6bd5ca Binary files /dev/null and b/docs/zh/bmp-deploy/picture/bmp_en.png differ diff --git a/docs/zh/bmp-deploy/picture/github.png b/docs/zh/bmp-deploy/picture/github.png new file mode 100644 index 0000000..260709c Binary files /dev/null and b/docs/zh/bmp-deploy/picture/github.png differ diff --git a/docs/zh/bmp-deploy/picture/ifconfig-bond0.png b/docs/zh/bmp-deploy/picture/ifconfig-bond0.png new file mode 100644 index 0000000..9755d38 Binary files /dev/null and b/docs/zh/bmp-deploy/picture/ifconfig-bond0.png differ diff --git a/docs/zh/bmp-deploy/picture/ifconfig-eth0.png b/docs/zh/bmp-deploy/picture/ifconfig-eth0.png new file mode 100644 index 0000000..6b8301d Binary files /dev/null and b/docs/zh/bmp-deploy/picture/ifconfig-eth0.png differ diff --git a/docs/zh/bmp-deploy/picture/monitor.png b/docs/zh/bmp-deploy/picture/monitor.png new file mode 100644 index 0000000..6e4a594 Binary files /dev/null and b/docs/zh/bmp-deploy/picture/monitor.png differ diff --git a/docs/zh/bmp-deploy/picture/network-deploy.png b/docs/zh/bmp-deploy/picture/network-deploy.png new file mode 100644 index 0000000..f935d75 Binary files /dev/null and b/docs/zh/bmp-deploy/picture/network-deploy.png differ diff --git a/docs/zh/bmp-deploy/picture/network.png b/docs/zh/bmp-deploy/picture/network.png new file mode 100644 index 0000000..0952371 Binary files /dev/null and b/docs/zh/bmp-deploy/picture/network.png differ diff --git a/docs/zh/bmp-deploy/service-manage.md b/docs/zh/bmp-deploy/service-manage.md new file mode 100644 index 0000000..d10b2a4 --- /dev/null +++ b/docs/zh/bmp-deploy/service-manage.md @@ -0,0 +1,127 @@ +# [bmp安装指导](main.md) - 服务管理 +bmp-deploy.sh 使用说明 +~~~ +# ./bmp-deploy.sh -h + +Usage: ./bmp-deploy.sh [-t|--tag TAG] COMMAND SERVICE... + +COMMAND: + start Install and start SERVICE + stop Stop SERVICE + restart restart SERVICE + status check SERVICE status + images display SERVICE image + uninstall uninstall SERVICE + reinstall reinstall SERVICE + config get SERVICE config + +SERVICE: + all All SERVICES + bmp-db + bmp-redis + bmp-mq + bmp-image + bmp-pushgateway + bmp-alertmanager + bmp-prometheus + bmp-tftp + bmp-rsyslog + bmp-console-web + bmp-operation-web + bmp-console-api + bmp-operation-api + bmp-openapi + bmp-openapi-console + bmp-scheduler + bmp-driver + bmp-dhcp-agent + bmp-oob-alert + bmp-oob-agent + bmp-monitor-proxy + bmp-pronoea +~~~ +## 停止服务 +./bmp-deploy.sh stop all | [service...] +~~~ +#停止bmp-console-web服务 +./bmp-deploy.sh stop bmp-console-web + +#停止bmp-console-web和bmp-operation-web服务 +./bmp-deploy.sh stop bmp-console-web bmp-operation-web + +#停止所有服务 +./bmp-deploy.sh stop all +~~~ + +## 启动服务 +./bmp-deploy.sh start all | [service...] +~~~ +#启动bmp-console-web服务 +./bmp-deploy.sh start bmp-console-web + +#启动bmp-console-web和bmp-operation-web服务 +./bmp-deploy.sh start bmp-console-web bmp-operation-web + +#启动所有服务 +./bmp-deploy.sh start all +~~~ + +## 重启服务 +./bmp-deploy.sh restart all | [service...] +~~~ +#重启bmp-console-web服务 +./bmp-deploy.sh restart bmp-console-web +~~~ + +## 查看服务运行状态 +./bmp-deploy.sh status all | [service...] +~~~ +#查看所有服务运行状态 +./bmp-deploy.sh status all +~~~ + +## 查看服务关联的容器镜像 +./bmp-deploy.sh images all | [service...] +~~~ +#查看bmp-console-web服务关联的容器镜像 +./bmp-deploy.sh images bmp-console-web +~~~ + +## 删除服务 +./bmp-deploy.sh uninstall all | [service...] + +说明: 相关数据也会一并删除 +~~~ +#删除单个服务,如bmp-console-web +./bmp-deploy.sh uninstall bmp-console-web + +#删除所有服务 +./bmp-deploy.sh uninstall all +~~~ + +## 卸载bmp(删除所有服务) +~~~ +cd /root/bmp-deploy/ +./bmp-deploy.sh uninstall all +cd /root +rm -rf bmp-deploy bmp-deploy*.tar.gz +rm -rf /var/log/bmp +~~~ + +## 重装服务(删除+按装) +./bmp-deploy.sh reinstall all | [service...] +~~~ +#重装单个服务,如bmp-console-web +./bmp-deploy.sh reinstall bmp-console-web +~~~ + +## 获取服务配置 +./bmp-deploy.sh config all | [service...] + +## 部署bmp时指定版本 +./bmp-deploy.sh start all | [service...] -t|--tag TAG +~~~ +#部署1.0版本 +./bmp-deploy.sh start all --tag 1.0 +~~~ + diff --git a/docs/zh/bmp-deploy/troubleshoot.md b/docs/zh/bmp-deploy/troubleshoot.md new file mode 100644 index 0000000..e1c12b8 --- /dev/null +++ b/docs/zh/bmp-deploy/troubleshoot.md @@ -0,0 +1,20 @@ +# 服务启动失败 +重新启动某服务 +~~~ +./bmp-deploy.sh status all #检查哪些服务未正常运行 +./bmp-deploy.sh start ServiceName #启动服务 +~~~ + +# pxe引导失败原因 +pxe引导失败 +机器的引导模式是否为bios +机器带外网络是否正确 +机器的bmc是否正常 +机器的网口连线是否正确 + +# docker未启动 +报错:Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? +重启manager节点之后,需要重启docker服务 +~~~ +systemctl start docker.service +~~~ diff --git a/docs/zh/concepts.md b/docs/zh/concepts.md new file mode 100644 index 0000000..d5de438 --- /dev/null +++ b/docs/zh/concepts.md @@ -0,0 +1,41 @@ +# 概念 + +## 组件说明 +* bmp-console-web 控制台前端页面。使用vue3脚手架搭建。包含登录页、项目管理页、个人中心页、实例管理页等页面功能。 +* bmp-console-api 控制台api。go语言后端业务,调用openapi接口实现控制台相关接口。为bmp-console-web拼装各类需要的数据,需要进行多语言适配。 +* bmp-operation-web 运营平台前端页面。使用vue3脚手架搭建,包含登录页、机房管理页、机型管理页、镜像管理页、设备管理页、角色管理页、用户管理页等页面功能。 +* bmp-operation-api 运营平台api。go语言后端业务,调用openapi接口实现运营平台相关接口。为bmp-operation-web拼装各类需要的数据,需要进行多语言适配。 +* bmp-openapi bmp-openapi是bmp的核心模块。实现了满足swagger2.0规范的restful api格式接口。对外提供了bmp所有基础功能。对内进行数据库操作、调用bmp-scheduler完成实例生命周期管理的相关操作。 +* bmp-scheduler 装机调度模块。承接bmp-openapi的实例生命周期管理请求,将上层请求转换为对应的commands,并且驱动commands执行,协同下层的bmp-driver,bmp-agent共同完成装机、重装、开机、关机等功能。 +* bmp-driver 单机房应用,在有多个机房情况下需要部署多套bmp-driver服务,接收mq,对本机房的服务器进行开机、关机、重启、设置pxe启动等操作。 +* bmp-dhcp-agent 单机房应用,装机之前需要提前更新dhcp配置,将Mac-IP关联关系存入dhcp配置中。之后liveOS才能从dhcp中获取到ip地址。 +* bmp-db 数据库 +* bmp-redis redis缓存 +* bmp-mq 消息中间件 +* bmp-tftp tftp服务器,存储着pxe引导需要的相关文件,包括pxe引导程序,pxe引导配置,LiveOS的内核和initramfs。 +* bmp-image http服务器,存储着GuestOS镜像 + +## 装机流程 +![架构图](./bmp-deploy/picture/bm-deploy.png) +## 装机流程说明 +1. 客户端(bmp-console-web)发起装机请求,bmp-console-api接收请求 +2. bmp-console-api检查请求参数,通过后将请求转发给bmp-openapi +3. bmp-openapi执行权限检查等操作,生成装机参数,发送给bmp-scheduler +4. bmp-scheduler调度装机任务,生成一系列装机指令,通过bmp-mq服务发送给bmp-dhcp-agent、bmp-driver和bmp-agent +5. bmp-dhcp-agent收到指令,设置内置的dhcp服务器,使得bm节点在pxe启动阶段能够获取正确的ip配置和tftp地址(bmp-tftp地址) +6. bmp-driver收到指令后,将bm节点设置为pxe启动并重启 +7. bm节点执行pxe启动,内置在网卡内的PXEClient启动,发送dhcp请求广播,bmp-dhcp-agent内置的dhcp服务器收到dhcp请求后,响应相应的ip配置和tftp地址 +8. PXEClient配置自身ip,之后从bmp-tftp下载pxe引导程序并执行,pxe引导程序继续从bmp-tftp获取其它引导参数,下载内核和initramfs,启动内存操作系统,内置在内存操作系统中bmp-agent服务开始启动 +9. bmp-agent接收指令,执行后续bm装机操作,如:设置raid,分区等 +10. bmp-agent从bmp-image下载客户操作系统镜像文件,写到bm节点磁盘中,然后初始化客户操作系统 +11. bmp-agent执行重启,完成操作系统安装 + +## 名词解释 +* manager节点: bmp管理服务器,运行着所有bmp组件(除了bmp-agent) +* bm节点:裸金属服务器,正常工作用的物理服务器,未装机前无操作系统,装机阶段运行LiveOS,装机完成后运行GuestOS +* GuestOS: 正常工作的操作系统 +* LiveOS: 内存操作系统,里面预装了bmp-agent +* 带外网卡:物理服务器上用于与bmc通信的特殊网卡,又称ipmi网卡 +* 管理网卡:物理服务器的标准的网卡,处在管理网络中 +* 管理网络: 3层网络,manager节点的管理网卡与bm节点的管理网卡通过管理网络通信 + diff --git a/docs/zh/develop.md b/docs/zh/develop.md new file mode 100644 index 0000000..ba5f4ab --- /dev/null +++ b/docs/zh/develop.md @@ -0,0 +1,582 @@ +# 源码部署 + +介绍: 在上一章节[快速体验](setup.md)中,可以使用官方提供的BMP镜像快速部署bmp平台。相关镜像已经上传到quay.io镜像仓库 +本章节介绍如何通过各个组件源码,编译对应镜像,并部署BMP平台。 +分为两部分内容: +1. 对运维人员:通过【源码部署】章节,了解镜像制作过程,并完成在本地容器化部署BMP平台,包括代码拉取,环境准备,组件编译,镜像制作,应用部署等 +2. 对研发人员:通过[快速体验](setup.md)或[源码部署](#1)章节已经运行起完整的BMP平台后,通过【定制化开发及部署】章节,了解如何对某一个组件进行定制化开发,及开发后如何更新相应组件 +## 目录结构如下: +- [源码部署](#1) + - [源码部署概述](#1.1) + - [部署步骤](#1.2) + - [环境准备](#1.2.1) + - [代码下载](#1.2.2) + - [组件镜像制作](#1.2.3) + - [应用部署](#1.2.4) + - [访问BMP](#1.2.5) + - [管理平台纳管裸金属服务器](#1.2.6) +- [定制化开发及部署](#2) + - [定制化开发及部署概述](#2.1) + - [组件介绍](#2.2) + - [定制化开发](#2.3) + - [更新组件镜像](#2.4) + - [重新部署组件](#2.5) + + +## 源码部署 +## 源码部署概述 +![bmp-framework.png](bmp-deploy/picture/bmp-framework.png) +如图是BMP平台整体架构图,图中manager node即管理组件节点,bm node即被装机物理服务器 + +整体部署步骤分两部分: +- 准备整体环境,包括网络环境准备,服务器准备,思路如下: + - manager节点和bm节点在一个大二层网络中 + - manager节点安装操作系统CentOS 7.9 + - 配置bm节点上联tor的dhcp-relay地址为manager节点的ip地址(如果仅体验BMP平台,不打算体验BMP裸金属装机流程,此步骤可跳过) + - 该部分内容参见[环境准备](env-prepare.md)部分 +- 在manager节点通过docker制作容器镜像,部署BMP平台 + 关键步骤如下: + - 下载源码(对应[第一步:管理节点部署准备](#3.1)部分), + - 下载编译需要的基础镜像,使用每个组件下的dockerfile,以基础镜像为底座,制作应用镜像(对应[第三步:组件镜像制作](#3.3)),该部分是是容器化部署BMP平台的关键步骤 + - 使用docker-compose部署应用(对应[第四步:应用部署](#3.4)) + +## 部署步骤 + +第一步: [管理节点部署准备](#1.2.1) + +第二步: [配置环境变量](#1.2.2) + +第三步: [组件镜像制作](#1.2.3) + +第四步: [应用部署](#1.2.4) + +第五步: [访问BMP](#1.2.5) + +第六步: [管理平台纳管裸金属服务器](#1.2.6) + + + +### 第一步:管理节点部署准备 + +#### 1. 安装docker和docker compose +- yum安装方式(CentOS 7.9系统) +~~~ +#可使用国内镜像源,比如清华镜像源 +yum install -y yum-utils +yum-config-manager \ + --add-repo \ + https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/centos/docker-ce.repo +sed -i 's+https://download.docker.com+https://mirrors.tuna.tsinghua.edu.cn/docker-ce+' /etc/yum.repos.d/docker-ce.repo + +yum install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin + +systemctl start docker +~~~ + +更多安装方式请参考docker官网 +- Docker官方文档地址:https://docs.docker.com/ +- Docker Compose官方文档地址:https://docs.docker.com/compose/ + +#### 2. 下载BMP源码到manager节点服务器 +下载前先明确BMP的部署目录,本实例默认安装在用户家目录,首先 +~~~ +# 跳转到家目录,再执行后续下载命令 +cd ~ +~~~ +找到主页右上角的 【Code】 按钮,点开下拉菜单,如图 +![github.png](bmp-deploy/picture/github.png) +- 方式一:用git clone命令 +~~~ +# 在管理节点执行,clone 上面复制的 HTTPS 链接,举例: + git clone https://github.com/jd-opensource/Baremetal_Manage_Platform.git +~~~ +- 方式二:点击 Download ZIP ,直接下载zip包后,手动传到管理服务器上 + 更多github操作,参考 github官方操作文档: + https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository +- 方式三:可直接从京东云下载安装包 +~~~ +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/opensource/Baremetal_Manage_Platform-33040a7.zip +unzip Baremetal_Manage_Platform-33040a7.zip -d Baremetal_Manage_Platform +~~~ + +### 第二步:配置环境参数 +- 部署脚本目录 + 部署脚本位于 bmp-deploy目录下 + 目录内文件说明:[bmp-deploy文件和目录说明](bmp-deploy/bmp-deploy.md) + +- 修改配置 + 编辑.env文件 + - 修改BMP_HOST_IP为manager节点管理网卡ip。本示例为192.168.14.80,如果服务器多网卡,请配置其中一个ip。如果配置了bond,使用bond网卡。否则尽量选择私网IP地址网卡。 + ifconfig命令-bond0示例图 + ![ifconfig-bond0.png](bmp-deploy/picture/ifconfig-bond0.png) + ifconfig命令-eth0示例图 + ![ifconfig-eth0.png](bmp-deploy/picture/ifconfig-eth0.png) + - 修改BASE_REGISTRY,部署需要使用mysql/redis/mq/nginx等基础容器镜像,本示例默认从quay.io拉取,如果网络限制,请修改为其他公共或私有镜像仓库 + + +~~~ +cd ~/Baremetal_Manage_Platform/bmp-deploy/ +# 查看服务器ip地址,优先查看bond0的ip地址,再次查看eth0的ip地址。如果不确定请咨询运维人员。 +ifconfig + +# 编辑环境变量 +# 必须和manager节点服务器ip保持一致 +# 设置 BMP_HOST_IP=192.168.14.80 +vi .env +~~~ + +更多配置请参考[配置管理](bmp-deploy/config.md) + + +### 第三步:组件镜像制作 +#### 1. docker镜像制作相关知识点 +docker镜像制作是在一个基础镜像的基础上,通过dockerfile文件,制作应用镜像,dockerfile文件中包含应用镜像的构建过程,包括安装依赖,编译,拷贝文件等。 +举例: bmp-schedule的dockerfile文件如下: +~~~ +FROM golang:1.17-alpine AS builder +ENV GOPROXY https://goproxy.cn +WORKDIR /usr/src/bmp-scheduler +COPY . . +RUN go build -o /tmp/bmp-scheduler . + +FROM alpine:3.16 +WORKDIR /home/bmp/bmp-scheduler +COPY --from=builder /tmp/bmp-scheduler . +COPY ./conf ./conf +CMD ["./bmp-scheduler"] +~~~ +在该dockerfile中,定义了两个构建阶段, +- 在第一阶段中 FROM指令指定基础镜像,FROM golang:1.17-alpine AS builder 表示使用golang:1.17-alpine镜像作为基础镜像,然后在这个基础镜像基础上,执行go build -o /tmp/bmp-scheduler . 命令,将代码编译成二进制文件 +- 在第二阶段中 FROM指令指定基础镜像,FROM alpine:3.16 表示使用alpine:3.16镜像作为基础镜像,然后在这个基础镜像基础上,执行COPY --from=builder /tmp/bmp-scheduler . 命令,将第一阶段编译好的二进制文件拷贝到当前目录,然后执行CMD ["./bmp-scheduler"] 命令,启动应用 + +执行编译命令 +~~~ +docker build -f bmp-schedule.Dockerfile -t bmp-schedule:v1.0 ./ +~~~ +表示用bmp-schedule.Dockerfile作为dockerfile, ./目录下的源码作为编译用到的源码,编译后生成bmp-schedule镜像,tag为v1.0 +#### 2. 准备编译需要的基础镜像 +- alpine:3.16 +- golang:1.17-alpine +- nginx:1.22-alpine +- node:16.19-alpine3.16 +- python:3.6-alpine +- quay.io/goswagger/swagger + 拉取基础镜像 +~~~ +docker pull docker.io/alpine:3.16 +docker pull docker.io/golang:1.17-alpine +docker pull docker.io/nginx:1.22-alpine +docker pull docker.io/node:16.19-alpine3.16 +docker pull docker.io/python:3.6-alpine +docker pull quay.io/goswagger/swagger +~~~ +如果网络限制,可采用如下方式,使用其他镜像仓库,然后修改tag +~~~ +docker pull quay.io/jdcloudbmp/alpine:3.16 +docker pull quay.io/jdcloudbmp/golang:1.17-alpine +docker pull quay.io/jdcloudbmp/nginx:1.22-alpine +docker pull quay.io/jdcloudbmp/node:16.19-alpine3.16 +docker pull quay.io/jdcloudbmp/python:3.6-alpine +docker pull quay.io/goswagger/swagger + +# docker tag +docker tag quay.io/jdcloudbmp/alpine:3.16 alpine:3.16 +docker tag quay.io/jdcloudbmp/golang:1.17-alpine golang:1.17-alpine +docker tag quay.io/jdcloudbmp/nginx:1.22-alpine nginx:1.22-alpine +docker tag quay.io/jdcloudbmp/node:16.19-alpine3.16 node:16.19-alpine3.16 +docker tag quay.io/jdcloudbmp/python:3.6-alpine python:3.6-alpine +~~~ +拉取代码后执行 +~~~ +docker images +~~~ +将会看到本地新增以下镜像,说明镜像拉取成功 +~~~ +alpine 3.16 d49a5025be10 11 months ago 5.54MB +nginx 1.22-alpine 88db8eea1453 21 months ago 41MB +node 16.19-alpine3.16 1e70b7adbb19 22 months ago 115MB +golang 1.17-alpine 270c4f58750f 2 years ago 314MB +python 3.6-alpine 3a9e80fa4606 3 years ago 40.7MB +~~~ + +#### 3. 镜像制作 +所有组件镜像分为四类: +1. **使用开源镜像,直接拉取镜像** + +| 应用组件 | 类别 | 语言/组件 | 可用下载地址 | +|-------------------|------|---------|--------------------------------------------------| +| bmp-db | 基础组件 | mysql | quay.io/jdcloudbmp/mysql:5.7-debian | +| bmp-redis | 基础组件 | redis | quay.io/jdcloudbmp/redis:7.0-alpine | +| bmp-mq | 基础组件 | rabbitmq | quay.io/jdcloudbmp/rabbitmq:3.11-management-alpine | +| bmp-image | 基础组件 | nginx |quay.io/jdcloudbmp/nginx:1.22-alpine| +| bmp-pushgateway | 开源组件 | pushgateway |quay.io/prometheus/pushgateway:v1.9.0 | +| bmp-alertmanager | 开源组件 | alertmanager |quay.io/prometheus/alertmanager:v0.27.0| +| bmp-prometheus | 开源组件 | prometheus |quay.io/prometheus/prometheus:v2.52.0| +上述组件是使用开源的镜像,可直接拉取 +源码文件中默认选用镜像源 quay.io/jdcloudbmp +拉取镜像命令举例: +~~~ +docker pull quay.io/jdcloudbmp/mysql:5.7-debian +~~~ +如使用其他镜像源,需首先修改 .env 文件中的变量 BASE_REGISTRY,如:BASE_REGISTRY=docker.io,然后拉取镜像 +~~~ +docker pull docker.io/mysql:5.7-debian +~~~ + +2. **在开源镜像基础上,制作定制化镜像** + +| 应用组件 | 类别 | 语言/组件 | dockerfile路径 | +|-------------|------|---------|----------------------------------------------| +| bmp-rsyslog | 开源组件 | rsyslog | bmp-deploy/dockerfile/bmp-rsyslog.Dockerfile | +| bmp-tftp | 开源组件 | tftp | bmp-deploy/dockerfile/bmp-tftp.Dockerfile | +上述组件的预制镜像已经上传至镜像仓库,如果不需要定制化制作,可直接拉取使用 +~~~ +docker pull quay.io/jdcloudbmp/bmp-rsyslog:v1.0 +docker pull quay.io/jdcloudbmp/bmp-tftp:v1.0 +~~~ +如果需要手动制作,以下两种制作镜像方式任选其一: +- 使用脚本制作镜像 +~~~ +cd ~/Baremetal_Manage_Platform/bmp-deploy +chmod +x bmp-build-image.sh +./bmp-build-image.sh build bmp-tftp +./bmp-build-image.sh build bmp-rsyslog +~~~ +- 手动制作镜像 +~~~ +# 设置相关环境变量,.env和images.cfg文件中定义了镜像的仓库及版本号等信息 +cd ~/Baremetal_Manage_Platform + . bmp-deploy/.env + . bmp-deploy/config/image.cfg +docker build -f bmp-deploy/dockerfile/bmp-rsyslog.Dockerfile -t ${bmp_rsyslog_image} ./ +docker build -f bmp-deploy/dockerfile/bmp-tftp.Dockerfile -t ${bmp_tftp_image} ./ +~~~ + + + +3. 通过源码编译制作镜像 + +| 应用组件 | 类别 | 语言/组件 | +|-------------|------|---------| +| bmp-console-web | 前端 | vue | +| bmp-operation-web | 前端 | vue | +| bmp-openapi | 后端 | go | +| bmp-scheduler | 后端 | go | +| bmp-openapi-console | 后端 | go | +| bmp-driver | 后端 | go | +| bmp-oob-agent | 后端 | go | +| bmp-pronoea | 后端 | go | +| bmp-monitor-proxy | 后端 | go | +| bmp-dhcp-agent | 后端 | python | + +以下两种制作镜像方式任选其一: +- 使用脚本制作镜像 +~~~ + +Usage: ./bmp-build-image.sh build SERVICE... + +COMMAND: + build Build image + +SERVICE: + all All SERVICES + bmp-console-web + bmp-operation-web + bmp-console-api + bmp-operation-api + bmp-openapi + bmp-openapi-console + bmp-scheduler + bmp-driver + bmp-dhcp-agent + bmp-oob-alert + bmp-oob-agent + bmp-monitor-proxy + bmp-pronoea + bmp-tftp + bmp-rsyslog + +#举例 +cd ~/Baremetal_Manage_Platform/bmp-deploy +chmod +x bmp-build-image.sh +./bmp-build-image.sh build bmp-console-web +./bmp-build-image.sh build bmp-operation-web +./bmp-build-image.sh build bmp-openapi +./bmp-build-image.sh build bmp-openapi-console +./bmp-build-image.sh build bmp-scheduler +./bmp-build-image.sh build bmp-driver +./bmp-build-image.sh build bmp-dhcp-agent +./bmp-build-image.sh build bmp-oob-agent +./bmp-build-image.sh build bmp-monitor-proxy +./bmp-build-image.sh build bmp-pronoea + +~~~ +- 手动制作镜像 +每个组件目录下都有对应的dockerfile文件,举例:bmp-scheduler组件 +~~~ +# 设置相关环境变量,.env和images.cfg文件中定义了镜像的仓库及版本号等信息 +cd ~/Baremetal_Manage_Platform + . bmp-deploy/.env + . bmp-deploy/config/image.cfg +docker build -f ./bmp-console-web/bmp-console-web.Dockerfile -t ${bmp_console_web_image} ./bmp-console-web +docker build -f ./bmp-operation-web/bmp-operation-web.Dockerfile -t ${bmp_operation_web_image} ./bmp-operation-web +docker build -f ./bmp-openapi/bmp-openapi.Dockerfile -t ${bmp_openapi_image} ./bmp-openapi +docker build -f ./bmp-openapi-console/bmp-openapi-console.Dockerfile -t ${bmp_openapi_console_image} ./bmp-openapi-console +docker build -f ./bmp-scheduler/bmp-scheduler.Dockerfile -t ${bmp_scheduler_image} ./bmp-scheduler +docker build -f ./bmp-driver/bmp-driver.Dockerfile -t ${bmp_driver_image} ./bmp-driver +docker build -f ./bmp-dhcp-agent/bmp-dhcp-agent.Dockerfile -t ${bmp_dhcp_agent_image} ./bmp-dhcp-agent +docker build -f ./oob-log-agent/oob-log-agent.Dockerfile -t ${bmp_oob_agent_image} ./oob-log-agent +docker build -f ./bmp-monitor-proxy/bmp-monitor-proxy.Dockerfile -t ${bmp_monitor_proxy_image} ./bmp-monitor-proxy +docker build -f ./bmp-pronoea/bmp-pronoea.Dockerfile -t ${bmp_pronoea_image} ./bmp-pronoea + +~~~ + +4. **通过源码编译制作镜像,但依赖于其他组件** + +| 应用组件 | 类别 | 语言/组件 | 依赖组件 | +|-------------|------|---------|----------------------| +| bmp-console-api | 后端 | go | bmp-openapi-console | +| bmp-operation-api | 后端 | go | bmp-openapi | +| bmp-oob-alert | 后端 | go | bmp-openapi | + +如果对bmp-openapi-console和bmp-openapi 组件进行了定制化开发,请将bmp-console-api或bmp-operation-api、oob-log-alert组件重新打包部署 + +以下两种制作镜像方式任选其一: +- 使用脚本制作镜像 +~~~ +cd ~/Baremetal_Manage_Platform/bmp-deploy +chmod +x bmp-build-image.sh +./bmp-build-image.sh build bmp-console-api +./bmp-build-image.sh build bmp-operation-api +./bmp-build-image.sh build bmp-oob-alert +~~~ +- 手动制作镜像 +~~~ +cd ~/Baremetal_Manage_Platform +. bmp-deploy/.env +. bmp-deploy/config/image.cfg + +# 注意docker build 最后一个参数是 ./ (即Baremetal_Manage_Platform目录) +docker build -f ./bmp-console-api/bmp-console-api.Dockerfile -t ${bmp_console_api_image} ./ +docker build -f ./bmp-operation-api/bmp-operation-api.Dockerfile -t ${bmp_operation_api_image} ./ +docker build -f ./oob-log-alert/oob-log-alert.Dockerfile -t ${bmp_oob_alert_image} ./ + +~~~ +镜像制作完成之后,执行 +~~~ +docker images +~~~ +可以检查所有的镜像是否制作成功 + +### 第四步:应用部署 +在完成以上**环境准备**和**镜像制作**步骤后,可进行应用组件部署 + +举例:bmp-scheduler +~~~ +cd ~/Baremetal_Manage_Platform/bmp-deploy +chmod +x ./bmp-deploy.sh +./bmp-deploy.sh start bmp-scheduler +~~~ +如果启动所有应用 +~~~ +cd ~/Baremetal_Manage_Platform/bmp-deploy +chmod +x ./bmp-deploy.sh +./bmp-deploy.sh start all +~~~ +- 检查各服务状态 +~~~ +./bmp-deploy.sh status bmp-scheduler +# 检查全部服务状态 +./bmp-deploy.sh status all +~~~ +正常情况下所有服务的状态都是running,如果某些服务未运行,参考[故障排查](bmp-deploy/troubleshoot.md) +安装过程中会自动从京东对象存储下相关操作系统镜像,下载速度与服务器网速相关,请耐心等待 +更多服务管理操作,参考[服务管理](bmp-deploy/service-manage.md) + +### 第五步:访问 BMP +注:默认账号:admin,密码:df9Ydfd$c +控制台:http://manager_ip:8080。本示例是http://192.168.14.80:8080 + +运营平台: http://manager_ip:8081。本示例是http://192.168.14.80:8081 + + +### 第六步:管理平台纳管裸金属服务器 +登陆bmp运营平台,进入设备管理界面,导入bmp节点信息 + +### 注意: +* 内网IPv4,网络子网掩码和网关 请填写正确的地址,使得运行在bm节点的PXEClient,LiveOS,GuestOS能够正常的访问manager网络。 + +## 定制化开发及部署 +### 定制化开发及部署概述 +通过[快速体验](setup.md)或[源码部署](#1).已经在本地运行起BMP平台,本章节将介绍在此基础上如何定制化开发单个组件,并更新 +在 [组件介绍](#2.2) 小节介绍各个组件的功能,和相互关系 +在 [定制化开发](#2.3) 小节介绍如何定制化开发单个组件 +在 [更新组件镜像](#2.4) 小节介绍如何更新组件镜像 +在 [重新部署组件](#2.5) 小节介绍如何重新部署组件 + +### 组件介绍 + +| 应用组件 | 类别 | 语言/组件 | +|-------------------|------| --- | +| bmp-image | 基础组件 | nginx | +| bmp-tftp | 基础组件 | tftp | +| bmp-db | 基础组件 | mysql | +| bmp-redis | 基础组件 | redis | +| bmp-mq | 基础组件 | rabbitmq | +| bmp-console-web | 前端 | vue | +| bmp-operation-web | 前端 | vue | +| bmp-console-api | 后端 | go | +| bmp-operation-api | 后端 | go | +| bmp-openapi | 后端 | go | +| bmp-scheduler | 后端 | go | +| bmp-openapi-console | 后端 | go | +| bmp-driver | 后端 | go | +| bmp-oob-alert | 后端 | go | +| bmp-oob-agent | 后端 | go | +| bmp-pronoea | 后端 | go | +| bmp-monitor-proxy | 后端 | go | +| bmp-dhcp-agent | 后端 | python | +| bmp-rsyslog | 开源组件 | rsyslog | +| bmp-pushgateway | 开源组件 | pushgateway | +| bmp-alertmanager | 开源组件 | alertmanager | +| bmp-prometheus | 开源组件 | prometheus | +* bmp-console-web 控制台前端页面。使用vue3脚手架搭建。包含登录页、项目管理页、个人中心页、实例管理页等页面功能。 +* bmp-console-api 控制台api。go语言后端业务,调用openapi接口实现控制台相关接口。为bmp-console-web拼装各类需要的数据,需要进行多语言适配。 +* bmp-operation-web 运营平台前端页面。使用vue3脚手架搭建,包含登录页、机房管理页、机型管理页、镜像管理页、设备管理页、角色管理页、用户管理页等页面功能。 +* bmp-operation-api 运营平台api。go语言后端业务,调用openapi接口实现运营平台相关接口。为bmp-operation-web拼装各类需要的数据,需要进行多语言适配。 +* bmp-openapi bmp-openapi是bmp的核心模块。实现了满足swagger2.0规范的restful api格式接口。对外提供了bmp所有基础功能。对内进行数据库操作、调用bmp-scheduler完成实例生命周期管理的相关操作。 +* bmp-scheduler 装机调度模块。承接bmp-openapi的实例生命周期管理请求,将上层请求转换为对应的commands,并且驱动commands执行,协同下层的bmp-driver,bmp-agent共同完成装机、重装、开机、关机等功能。 +* bmp-driver 单机房应用,在有多个机房情况下需要部署多套bmp-driver服务,接收mq,对本机房的服务器进行开机、关机、重启、设置pxe启动等操作。 +* bmp-dhcp-agent 单机房应用,装机之前需要提前更新dhcp配置,将Mac-IP关联关系存入dhcp配置中。之后liveOS才能从dhcp中获取到ip地址。 +* bmp-db 数据库 +* bmp-redis redis缓存 +* bmp-mq 消息中间件 +* bmp-tftp tftp服务器,存储着pxe引导需要的相关文件,包括pxe引导程序,pxe引导配置,LiveOS的内核和initramfs。 +* bmp-image http服务器,存储着GuestOS镜像 +* bmp-rsyslog rsyslog 日志组件 +* bmp-oob-alert 带外告警组件 +* bmp-oob-agent 带外监控信息采集组件 +* bmp-monitor-proxy 带内监控转发组件 +* bmp-prometheus 监控数据收集组件 +* bmp-pushgateway 从bmp-monitor-proxy收集监控数据,并推送到 Prometheus +* bmp-alertmanager 告警组件 +* bmp-pronoea 从bmp-alertmanager接收告警信息并转换格式,传到给bmp-openapi + +#### 装机流程 +![架构图](./bmp-deploy/picture/bm-deploy.png) +#### 装机流程说明 +1. 客户端(bmp-console-web)发起装机请求,bmp-console-api接收请求 +2. bmp-console-api检查请求参数,通过后将请求转发给bmp-openapi +3. bmp-openapi执行权限检查等操作,生成装机参数,发送给bmp-scheduler +4. bmp-scheduler调度装机任务,生成一系列装机指令,通过bmp-mq服务发送给bmp-dhcp-agent、bmp-driver和bmp-agent +5. bmp-dhcp-agent收到指令,设置内置的dhcp服务器,使得bm节点在pxe启动阶段能够获取正确的ip配置和tftp地址(bmp-tftp地址) +6. bmp-driver收到指令后,将bm节点设置为pxe启动并重启 +7. bm节点执行pxe启动,内置在网卡内的PXEClient启动,发送dhcp请求广播,bmp-dhcp-agent内置的dhcp服务器收到dhcp请求后,响应相应的ip配置和tftp地址 +8. PXEClient配置自身ip,之后从bmp-tftp下载pxe引导程序并执行,pxe引导程序继续从bmp-tftp获取其它引导参数,下载内核和initramfs,启动内存操作系统,内置在内存操作系统中bmp-agent服务开始启动 +9. bmp-agent接收指令,执行后续bm装机操作,如:设置raid,分区等 +10. bmp-agent从bmp-image下载客户操作系统镜像文件,写到bm节点磁盘中,然后初始化客户操作系统 +11. bmp-agent执行重启,完成操作系统安装 + +#### 监控流程 +![monitor.png](bmp-deploy/picture/monitor.png) +1. 监控探针收集宿主机监控信息,汇总到bmp-monitor-proxy组件 +2. bmp-monitor-proxy将监控信息传递到bmp-pushgateway +3. bmp-prometheus定时从bmp-pushgateway拉取监控数据 +4. bmp-prometheus触发告警规则后,告警信息传递到bmp-alertmanager +5. bmp-alertmanager将告警信息转给bmp-pronoea,进行格式转换 +6. bmp-pronoea转给bmp-api,进行告警展示和告警 + +#### 名词解释 +* manager节点: bmp管理服务器,运行着所有bmp组件(除了bmp-agent) +* bm节点:裸金属服务器,正常工作用的物理服务器,未装机前无操作系统,装机阶段运行LiveOS,装机完成后运行GuestOS +* GuestOS: 正常工作的操作系统 +* LiveOS: 内存操作系统,里面预装了bmp-agent +* 带外网卡:物理服务器上用于与bmc通信的特殊网卡,又称ipmi网卡 +* 管理网卡:物理服务器的标准的网卡,处在管理网络中 +* 管理网络: 3层网络,manager节点的管理网卡与bm节点的管理网卡通过管理网络通信 + +### 定制化开发 +在[组件介绍](#2.2)章节介绍各个组件的功能,和相互关系,其中可定制化开发组件主要包括前后端组件 + +| 应用组件 | 类别 | 语言/组件 | +|-------------------|------| --- | +| bmp-console-web | 前端 | vue | +| bmp-operation-web | 前端 | vue | +| bmp-console-api | 后端 | go | +| bmp-operation-api | 后端 | go | +| bmp-openapi | 后端 | go | +| bmp-scheduler | 后端 | go | +| bmp-openapi-console | 后端 | go | +| bmp-driver | 后端 | go | +| bmp-oob-alert | 后端 | go | +| bmp-oob-agent | 后端 | go | +| bmp-pronoea | 后端 | go | +| bmp-monitor-proxy | 后端 | go | +| bmp-dhcp-agent | 后端 | python | + +每个组件都有单独的源码文件夹,组件的源码文件夹下有README.md文件,里面有组件的详细介绍,以及组件的定制化开发说明。 +研发人员可以参考组件的README.md进行定制化开发。 +### 更新组件镜像 +当对上述组件进行定制化开发后,重新制作组件的镜像,然后重新部署 +每个组件对应的镜像相关信息,记录在bmp-deploy/config/.env 和 bmp-deploy/config/image.cfg文件中, +举例说明: +bmp-scheduler组件的镜像信息如下: +bmp-deploy/config/.env文件中 +~~~ +BMP_REGISTRY=quay.io/jdcloudbmp +BMP_VERSION='v1.0' +~~~ +bmp-deploy/config/image.cfg文件中 +~~~ +bmp_scheduler_image=${bmp_registry}/bmp-scheduler:${TAG} +~~~ +镜像编译和容器部署过程中会读取.env和 image.cfg参数,bmp-scheduler的镜像即为 +~~~ +quay.io/jdcloudbmp/bmp-scheduler:v1.0 +~~~ +如果对bmp-scheduler进行定制化开发后,规划用新的镜像name和tag,举例 +~~~ +docker.io/jdcloudbmp/bmp-scheduler:v2.0 +~~~ +可直接修改 bmp-deploy/config/image.cfg 中的参数 +~~~ +bmp_scheduler_image=docker.io/jdcloudbmp/bmp-scheduler:v2.0 +~~~ +如果规划所有组件都统一用新的name和tag,可直接修改bmp-deploy/config/.env中参数,举例 +~~~ +BMP_REGISTRY=docker.io +BMP_VERSION='v2.0' +~~~ +则所有组件在编译和部署的时候,将使用新的镜像name和tag +手动镜像制作命令举例 +制作镜像前查看镜像列表,可查看到bmp-scheduler原有镜像 +~~~ +docker images | grep bmp-scheduler +# +quay.io/jdcloudbmp/bmp-scheduler v1.0 76053df0e4a6 28 hours ago 24.8MB +~~~ +手动执行镜像制作命令 +~~~ +docker build -f bmp-scheduler.Dockerfile -t bmp-scheduler:v2.0 ./ +~~~ +再次查看镜像,可以看到新的镜像bmp-scheduler:v2.0 +~~~ +docker images | grep bmp-scheduler + +bmp-scheduler v2.0 76053df0e4a6 28 hours ago 24.8MB +quay.io/jdcloudbmp/bmp-scheduler v1.0 76053df0e4a6 28 hours ago 24.8MB +~~~ +更多细节参考[镜像制作知识点](#1.2.3) + +### 重新部署组件 +重新部署组件 +~~~ +# 举例 +./bmp-deploy.sh reinstall bmp-scheduler +# 检查全部服务状态 +./bmp-deploy.sh status bmp-scheduler +~~~ +服务的状态都是running后,进行功能验证 + + + diff --git a/docs/zh/env-prepare.md b/docs/zh/env-prepare.md new file mode 100644 index 0000000..10e5a69 --- /dev/null +++ b/docs/zh/env-prepare.md @@ -0,0 +1,75 @@ +## 环境准备 +**环境准备包括 *网络环境准备* 和 *服务器准备* 两部分,整体架构如下** + +![bmp-framework.png](bmp-deploy/picture/bmp-framework.png) + +### 1. 网络准备 +*请注意: 如果只体验BMP管理组件,以下网络环境配置可跳过;如果准备真实装机,必须进行以下网络配置* +manager节点和bm节点在一个大二层网络中,bm节点需要根据DHCP服务获取其IP地址。 +在进行BMP平台部署之前,需要配置装机节点的上联交换机的dhcp-relay到manager节点。 +如下展示示例网络配置 +![network-deploy.png](bmp-deploy/picture/network-deploy.png) +此网络结构中,TOR1代表装机节点eth0网卡上联交换机。 +- manager节点 + eth0 ip: 192.168.14.80/27 + 此地址一般为私有网络地址,BMP的DHCP服务会启动在这个私有网络地址上。此私有网络地址也会通过配置文件告知BMP平台,详见[配置环境参数](#3.2) +- bm节点 + ipmi ip: 192.168.11.130/27 +- TOR1 + ip: 192.168.12.129/27 + vlan id: 200 +- 登录TOR1,查看vlan 200的dhcp中继,检查中继地址是否为manager节点管理网卡ip(本示例为192.168.14.80) + 登录TOR1:ssh switchuser@192.168.12.129,输入密码。 + H3C交换机指令:dis cu int Vlan-interface 200 +~~~ +以下是使用H3C交换机重新配置DHCP中继的步骤: + +#进入系统视图: + system-view +# 进入接口视图,例如VLAN接口200: + interface vlan 200 +# 配置DHCP中继的服务器地址,即管理节点ip: + dhcp relay server 192.168.14.80 +# 保存配置: + save f +# 返回到系统视图: + quit +# 退出配置模式: + quit + +请注意,具体的命令和参数可能会因交换机型号、软件版本和配置而有所不同。确保你已经了解了你的交换机的具体配置要求。 +~~~ + +#### BMP标准网络通信过程如图: +![network.png](bmp-deploy/picture/network.png) +* 物理机的带外网卡ipmi、管理网卡eth0和manager节点的管理网卡eth0都在同一个2层管理网络中。 +* manager节点内各个bmp组件以容器方式运行,通过docker-proxy和eth0网卡将服务端口暴露给管理网络访问。 +* bm节点内置的bmc管理系统通过ipmi网卡暴露给管理网络访问 +* bm节点运行的其它服务通过eth0网卡暴露给管理网络访问 +* 为了确保bm节点运行的系统能够从manager节点的bmp-dhcp-agent容器内置的dhcp服务器获取ip配置,bm节点eth0网卡的上联交换机可能需要配置dhcp中继,中继地址为manager节点管理ip。 +* 装机开始时,bmp-driver通过管理网络访问bm节点的带外ip,设置物理机的引导模式和控制开关机。 +* pxe引导阶段,bm节点的eth0网卡内置的PXEClient通过管理网络访问bmp-dhcp-agent内置的dhcp服务器,获取ip配置和pxe引导程序下载地址,设置eth0 ip,并从bmp-tftp下载LiveOS内核和initramfs,之后启动LiveOS。 +* LiveOS启动时,也会从bmp-dhcp-agent内置的dhcp服务器获取ip配置并设置eth0 ip。 +* 安装GuesOS阶段,bmp-agent可以从bmp-mq获取所需安装信息,也可以从bmp-tftp下载GuestOS镜像 +* 无论运行的是PXEClient、LiveOS还是GustOS,bm节点的管理网卡eth0的ip都是一样的,具体ip地址是在运营平台-设备管理中设置。请给bm节点分配正确的ip地址,确保bm节点在各个阶段运行的系统都能正常工作。 + +### 2. 服务器准备 +manager节点: +~~~ +资源要求 +cpu: 4 核 +内存: 8 GB +磁盘: 40 GB +操作系统:CentOS 7.9 +网络要求 +能够访问公网 +需要开放给客户端浏览器访问的端口:8080,8081 +需要开放给管理网络访问的端口: 10000, 5672,67/udp, 69/udp +~~~ +装机节点最小配置 +~~~ +cpu: 1 核 +内存: 2 GB +磁盘: 40 GB +拥有一个带外网卡和管理网卡 +~~~ diff --git a/docs/zh/local-develop.md b/docs/zh/local-develop.md new file mode 100644 index 0000000..79e2142 --- /dev/null +++ b/docs/zh/local-develop.md @@ -0,0 +1,1287 @@ +# 本地开发部署 +本章节介绍: +- 如何本地非容器部署和调试各个单组件(单组件调试适用于本地开发调试) +- 如何将各组件之间部署联调(联调适用于非容器化部署BMP平台) + +## 开发及部署步骤 +- [组件介绍](#1) +- [单组件部署调试](#2) + - [代码介绍及端口规划](#2.1) + - [代码介绍](#2.1.1) + - [设置环境变量](#2.1.2) + - [基础组件](#2.2) + - [bmp-image](#2.2.1) + - [bmp-tftp](#2.2.2) + - [bmp-db](#2.2.3) + - [bmp-redis](#2.2.4) + - [bmp-mq](#2.2.5) + - [bmp-rsyslog](#2.2.6) + - [前端组件](#2.3) + - [后端组件](#2.4) + - [后端go组件](#2.4.1) + - [后端python组件](#2.4.2) + - [开源组件](#2.5) + - [bmp-pushgateway](#2.5.1) + - [bmp-prometheus](#2.5.2) + - [bmp-alertmanager](#2.5.3) +- [组件联调部署](#3) + - [环境准备](#3.1) + - [设置环境变量](#3.2) + - [组件按顺序启动](#3.3) + - [访问 BMP](#3.4) + - [管理平台纳管裸金属服务器](#3.5) + + +## 组件介绍 +* bmp-console-web 控制台前端页面。使用vue3脚手架搭建。包含登录页、项目管理页、个人中心页、实例管理页等页面功能。 +* bmp-console-api 控制台api。go语言后端业务,调用openapi接口实现控制台相关接口。为bmp-console-web拼装各类需要的数据,需要进行多语言适配。 +* bmp-operation-web 运营平台前端页面。使用vue3脚手架搭建,包含登录页、机房管理页、机型管理页、镜像管理页、设备管理页、角色管理页、用户管理页等页面功能。 +* bmp-operation-api 运营平台api。go语言后端业务,调用openapi接口实现运营平台相关接口。为bmp-operation-web拼装各类需要的数据,需要进行多语言适配。 +* bmp-openapi bmp-openapi是bmp的核心模块。实现了满足swagger2.0规范的restful api格式接口。对外提供了bmp所有基础功能。对内进行数据库操作、调用bmp-scheduler完成实例生命周期管理的相关操作。 +* bmp-scheduler 装机调度模块。承接bmp-openapi的实例生命周期管理请求,将上层请求转换为对应的commands,并且驱动commands执行,协同下层的bmp-driver,bmp-agent共同完成装机、重装、开机、关机等功能。 +* bmp-driver 单机房应用,在有多个机房情况下需要部署多套bmp-driver服务,接收mq,对本机房的服务器进行开机、关机、重启、设置pxe启动等操作。 +* bmp-dhcp-agent 单机房应用,装机之前需要提前更新dhcp配置,将Mac-IP关联关系存入dhcp配置中。之后liveOS才能从dhcp中获取到ip地址。 +* bmp-db 数据库 +* bmp-redis redis缓存 +* bmp-mq 消息中间件 +* bmp-tftp tftp服务器,存储着pxe引导需要的相关文件,包括pxe引导程序,pxe引导配置,LiveOS的内核和initramfs。 +* bmp-image http服务器,存储着GuestOS镜像 +* bmp-rsyslog rsyslog 日志组件 +* bmp-oob-alert 带外告警组件 +* bmp-oob-agent 带外监控信息采集组件 +* bmp-monitor-proxy 带内监控转发组件 +* bmp-prometheus 监控数据收集组件 +* bmp-pushgateway 从bmp-monitor-proxy收集监控数据,并推送到 Prometheus +* bmp-alertmanager 告警组件 +* bmp-pronoea 从bmp-alertmanager接收告警信息并转换格式,传到给bmp-openapi + +### 装机流程 +![架构图](./bmp-deploy/picture/bm-deploy.png) +### 装机流程说明 +1. 客户端(bmp-console-web)发起装机请求,bmp-console-api接收请求 +2. bmp-console-api检查请求参数,通过后将请求转发给bmp-openapi +3. bmp-openapi执行权限检查等操作,生成装机参数,发送给bmp-scheduler +4. bmp-scheduler调度装机任务,生成一系列装机指令,通过bmp-mq服务发送给bmp-dhcp-agent、bmp-driver和bmp-agent +5. bmp-dhcp-agent收到指令,设置内置的dhcp服务器,使得bm节点在pxe启动阶段能够获取正确的ip配置和tftp地址(bmp-tftp地址) +6. bmp-driver收到指令后,将bm节点设置为pxe启动并重启 +7. bm节点执行pxe启动,内置在网卡内的PXEClient启动,发送dhcp请求广播,bmp-dhcp-agent内置的dhcp服务器收到dhcp请求后,响应相应的ip配置和tftp地址 +8. PXEClient配置自身ip,之后从bmp-tftp下载pxe引导程序并执行,pxe引导程序继续从bmp-tftp获取其它引导参数,下载内核和initramfs,启动内存操作系统,内置在内存操作系统中bmp-agent服务开始启动 +9. bmp-agent接收指令,执行后续bm装机操作,如:设置raid,分区等 +10. bmp-agent从bmp-image下载客户操作系统镜像文件,写到bm节点磁盘中,然后初始化客户操作系统 +11. bmp-agent执行重启,完成操作系统安装 + +### 监控流程 +![monitor.png](bmp-deploy/picture/monitor.png) +1. 监控探针收集宿主机监控信息,汇总到bmp-monitor-proxy组件 +2. bmp-monitor-proxy将监控信息传递到bmp-pushgateway +3. bmp-prometheus定时从bmp-pushgateway拉取监控数据 +4. bmp-prometheus触发告警规则后,告警信息传递到bmp-alertmanager +5. bmp-alertmanager将告警信息转给bmp-pronoea,进行格式转换 +6. bmp-pronoea转给bmp-api,进行告警展示和告警 + +### 名词解释 +* manager节点: bmp管理服务器,运行着所有bmp组件(除了bmp-agent) +* bm节点:裸金属服务器,正常工作用的物理服务器,未装机前无操作系统,装机阶段运行LiveOS,装机完成后运行GuestOS +* GuestOS: 正常工作的操作系统 +* LiveOS: 内存操作系统,里面预装了bmp-agent +* 带外网卡:物理服务器上用于与bmc通信的特殊网卡,又称ipmi网卡 +* 管理网卡:物理服务器的标准的网卡,处在管理网络中 +* 管理网络: 3层网络,manager节点的管理网卡与bm节点的管理网卡通过管理网络通信 + +## 单组件部署调试 +### BMP代码 +#### 代码介绍 + +| 应用组件 | 类别 | 语言/组件 | +|-------------------|------| --- | +| bmp-image | 基础组件 | nginx | +| bmp-tftp | 基础组件 | tftp | +| bmp-db | 基础组件 | mysql | +| bmp-redis | 基础组件 | redis | +| bmp-mq | 基础组件 | rabbitmq | +| bmp-console-web | 前端 | vue | +| bmp-operation-web | 前端 | vue | +| bmp-console-api | 后端 | go | +| bmp-operation-api | 后端 | go | +| bmp-openapi | 后端 | go | +| bmp-scheduler | 后端 | go | +| bmp-openapi-console | 后端 | go | +| bmp-driver | 后端 | go | +| bmp-oob-alert | 后端 | go | +| bmp-oob-agent | 后端 | go | +| bmp-pronoea | 后端 | go | +| bmp-monitor-proxy | 后端 | go | +| bmp-dhcp-agent | 后端 | python | +| bmp-rsyslog | 开源组件 | rsyslog | +| bmp-pushgateway | 开源组件 | pushgateway | +| bmp-alertmanager | 开源组件 | alertmanager | +| bmp-prometheus | 开源组件 | prometheus | + + +#### 设置环境变量 +后端组件会相互调用,规划好各组件的端口,写入配置文件 .env +举例:本环境部署在ip 192.168.14.80,配置文件 .env 如下,请将ip地址修改为实际ip地址 + +~~~ +set -a +BMP_DB_HOST=192.168.14.80 +BMP_DB_PORT=3306 +BMP_DB_USER=bmp_rw +BMP_DB_PASSWORD='LpK9Jq12Zf!' +BMP_DB_NAME=bmp +BMP_REDIS_HOST=192.168.14.80 +BMP_REDIS_PORT=6379 +BMP_REDIS_PASSWORD='LpK9Jq12Zf' +BMP_MQ_HOST=192.168.14.80 +BMP_MQ_PORT=5672 +BMP_MQ_USER=bmp +BMP_MQ_PASSWORD='LpK9Jq12Zf' +BMP_MQ_VHOST=/bmp +BMP_OMAPI_HOST=192.168.14.80 +BMP_OMAPI_PORT=7911 +BMP_OMAPI_TOKEN="LpK9Jq12Zf" +BMP_OPENAPI_HOST=192.168.14.80 +BMP_OPENAPI_PORT=8801 +BMP_OPENAPI_CONSOLE_HOST=192.168.14.80 +BMP_OPENAPI_CONSOLE_PORT=8802 +BMP_OOB_ALERT_HOST=192.168.14.80 +BMP_OOB_ALERT_PORT=8804 +BMP_MQ_EXCHANGE_ROUTING_KEY=idc-vm4xsulx1k2d9z4xkctrttig02zl +BMP_IMAGE_PORT=10000 +BMP_MONITOR_PROXY_PORT=8805 +BMP_PROMETHEUS_HOST=192.168.14.80 +BMP_PROMETHEUS_PORT=9090 +BMP_PROMETHEUS_DATA_DIR=/data/prometheus +BMP_PUSHGATEWAY_HOST=192.168.14.80 +BMP_PUSHGATEWAY_PORT=9091 +BMP_ALERTMANAGER_HOST=192.168.14.80 +BMP_ALERTMANAGER_PORT=9093 +BMP_PRONOEA_HOST=192.168.14.80 +BMP_PRONOEA_PORT=9999 +BMP_RSYSLOG_PORT=1514 +set +a +~~~ + +环境变量生效 +~~~ +source .env +~~~ +### 基础组件 +#### bmp-image +主要存储 GuestOS镜像文件,bmp-agent(装机节点agent),device_import template(excel文件),并以nginx对外提供http服务 +~~~ +# 第一步:安装nginx,以cetos为例 +yum install nginx +systemctl start nginx + +# 第二步:从京东云对象存储下载以下文件,并保存到/home/bmp/image +mkdir -p /home/bmp/bmp-image +chmod -R 755 /home/bmp/bmp-image +cd /home/bmp/bmp-image +# GuestOS image +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/GuestOS/v1.7.0-centos-7.9-2022070716.tar.xz +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/GuestOS/v1.7.0-ubuntu-18.04-2022062709.tar.xz +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/GuestOS/v1.7.0-centos-7.9-arm-2023080716.tar.xz +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/GuestOS/v1.7.0-ubuntu-18.04-arm-2023081111.tar.xz +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/GuestOS/v1.7.0-loongnix-8.4-2023110218.tar.xz + +# bmp-agent +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/others/bmp-agent.bin +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/others/bmp-agent.bin.arm +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/others/bmp-agent-windows.tgz +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/others/device_import.xlsx + +# 第三步:增加nginx配置文件 +cat << EOF > /etc/nginx/conf.d/bmp-image.conf +server { + listen 10000; + listen [::]:10000; + server_name localhost; + location / { + root /home/bmp/bmp-image; + index index.html index.htm; + } + error_page 500 502 503 504 /50x.html; + location = /50x.html { + root /home/bmp/bmp-image; + } +} +EOF + + +# 第四步:启动nginx +nginx -s reload + +# 更多nginx的配置请参考官网: +https://nginx.org/en/docs/ +~~~ + +#### bmp-tftp + +| 应用组件 | 类别 | 语言/组件 | +|-------------------|------| --- | +| bmp-tftp | 基础组件 | tftp | + +再简要回顾以下tftp服务在装机过程中的作用: +第一步:装机节点执行pxe启动,内置在网卡内的PXEClient启动,发送dhcp请求广播,bmp-dhcp-agent内置的dhcp服务器收到dhcp请求后,响应相应的ip配置和tftp地址 +第二步:PXEClient配置自身ip,之后从bmp-tftp下载pxe引导程序并执行,pxe引导程序继续从bmp-tftp获取其它引导参数,下载内核和initramfs,启动内存操作系统,内置在内存操作系统中bmp-agent服务开始启动(该过程是系统自动下载,不需要人工配置) +所以:bmp-tftp提供下载系统启动相关的内核及liveOS镜像的服务 + +部署tftp步骤如下: +- 第一步:安装tftp +~~~ +yum install tftp-server +systemctl start tftp +~~~ + +- 第二步:从京东云对象存储下载下载内核及liveOs文件 +~~~ +mkdir -p /var/lib/tftpboot/images/{arm64,loongarch64} +mkdir -p /var/lib/tftpboot/uefi/{arm64,loongarch64,x86_64} +mkdir -p /var/lib/tftpboot/pxelinux.cfg + +# arm64-image +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/LiveOS/v2.0.7-centos_7_9_arm64-2024082914-initramfs.gz -P /var/lib/tftpboot/images/arm64 +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/LiveOS/v2.0.7-centos_7_9_arm64-2024082914-vmlinuz -P /var/lib/tftpboot/images/arm64 +# loongarch64-image +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/LiveOS/initramfs-loongarch.gz -P /var/lib/tftpboot/images/loongarch64 +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/LiveOS/initramfs-loongarch.gz -P /var/lib/tftpboot/images/loongarch64 +# x86_64-image +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/LiveOS/v2.0.7-centos_7_9-2024082914-initramfs.gz -P /var/lib/tftpboot/images/ +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/LiveOS/v2.0.7-centos_7_9-2024082914-vmlinuz -P /var/lib/tftpboot/images/ +# bootloader +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/bootloader/BOOTLOONGARCH64.EFI -P /var/lib/tftpboot/uefi/loongarch64 +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/bootloader/grubaa64.efi -P /var/lib/tftpboot/uefi/x86_64 +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/bootloader/grubx64.efi -P /var/lib/tftpboot/uefi/x86_64 +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/bootloader/pxelinux.0 -P /var/lib/tftpboot/ +~~~ +# 第三步:设置配置文件 +~~~ +cat << EOF > /var/lib/tftpboot/pxelinux.cfg/default +default bmp agent + prompt 0 + timeout 1 + label bmp agent + kernel \${BMP_KERNEL_PATH_x86} + append initrd=\${BMP_INITRAMFS_PATH_x86} net.ifnames=0 biosdevname=0 BMP_MQ_HOST=\${BMP_HOST_IP} BMP_MQ_PORT=\${BMP_MQ_PORT} BMP_MQ_USER=\${BMP_MQ_USER} BMP_MQ_PASSWORD=\${BMP_MQ_PASSWORD} BMP_MQ_VHOST=\${BMP_MQ_VHOST} BMP_MQ_EXCHANGE_ROUTING_KEY=\${BMP_MQ_EXCHANGE_ROUTING_KEY} BMP_IMAGE_HOST=\${BMP_HOST_IP} BMP_IMAGE_PORT=\${BMP_IMAGE_PORT} BMP_RSYSLOG_HSOT=\${BMP_HOST_IP} BMP_RSYSLOG_PORT=\${BMP_RSYSLOG_PORT} +EOF + +cat << EOF > /var/lib/tftpboot/uefi/arm64/grub.cfg +set timeout=1 +set default=1 +menuentry "bmp agent arm64 uefi" { + linux \${BMP_KERNEL_PATH_arm64} console=ttyAMA0 console=tty0 net.ifnames=0 biosdevname=0 ksdevice=bootif kssendmac text BMP_MQ_HOST=\${BMP_HOST_IP} BMP_MQ_PORT=\${BMP_MQ_PORT} BMP_MQ_USER=\${BMP_MQ_USER} BMP_MQ_PASSWORD='\${BMP_MQ_PASSWORD}' BMP_MQ_VHOST=\${BMP_MQ_VHOST} BMP_MQ_EXCHANGE_ROUTING_KEY=\${BMP_MQ_EXCHANGE_ROUTING_KEY} BMP_IMAGE_HOST=\${BMP_HOST_IP} BMP_IMAGE_PORT=\${BMP_IMAGE_PORT} + initrd \${BMP_INITRAMFS_PATH_arm64} +} +EOF + +cat << EOF > /var/lib/tftpboot/uefi/loongarch64/grub.cfg +set timeout=1 +set default=1 +menuentry 'bmp agent loongarch64 uefi' { + linux \${BMP_KERNEL_PATH_loonarch64} console=ttyS0,115200 console=tty0 net.ifnames=0 biosdevname=0 ksdevice=bootif kssendmac text BMP_MQ_HOST=\${BMP_HOST_IP} BMP_MQ_PORT=\${BMP_MQ_PORT} BMP_MQ_USER=\${BMP_MQ_USER} BMP_MQ_PASSWORD=\${BMP_MQ_PASSWORD} BMP_MQ_VHOST=\${BMP_MQ_VHOST} BMP_MQ_EXCHANGE_ROUTING_KEY=\${BMP_MQ_EXCHANGE_ROUTING_KEY} BMP_IMAGE_HOST=\${BMP_HOST_IP} BMP_IMAGE_PORT=\${BMP_IMAGE_PORT} + initrd \${BMP_INITRAMFS_PATH_loonarch64} +} +EOF + +cat << EOF > /var/lib/tftpboot/uefi/x86_64/grub.cfg +set timeout=1 +set default=1 +menuentry 'bmp agent x86_64 uefi' { + linuxefi \${BMP_KERNEL_PATH_x86} net.ifnames=0 biosdevname=0 ksdevice=bootif kssendmac text BMP_MQ_HOST=\${BMP_HOST_IP} BMP_MQ_PORT=\${BMP_MQ_PORT} BMP_MQ_USER=\${BMP_MQ_USER} BMP_MQ_PASSWORD=\${BMP_MQ_PASSWORD} BMP_MQ_VHOST=\${BMP_MQ_VHOST} BMP_MQ_EXCHANGE_ROUTING_KEY=\${BMP_MQ_EXCHANGE_ROUTING_KEY} BMP_IMAGE_HOST=\${BMP_HOST_IP} BMP_IMAGE_PORT=\${BMP_IMAGE_PORT} + initrdefi \${BMP_INITRAMFS_PATH_x86} +} +EOF + +最终目录结构如图: +. +├── images +│   ├── arm64 +│   │   ├── v2.0.7-centos_7_9_arm64-2024082914-initramfs.gz +│   │   └── v2.0.7-centos_7_9_arm64-2024082914-vmlinuz +│   └── loongarch64 +│   ├── initramfs-loongarch.gz +│   └── vmlinuz-loongarch +├── pxelinux.0 +├── pxelinux.cfg +│   └── default +├── uefi +│   ├── arm64 +│   │   ├── grubaa64.efi +│   │   └── grub.cfg +│   ├── loongarch64 +│   │   ├── BOOTLOONGARCH64.EFI +│   │   └── grub.cfg +│   └── x86_64 +│   ├── grub.cfg +│   └── grubx64.efi +├── v2.0.7-centos_7_9-2024082914-initramfs.gz +└── v2.0.7-centos_7_9-2024082914-vmlinuz +~~~ +# 第四步: 设置环境变量 tftp.env +~~~ +set -a +BMP_DB_HOST=192.168.14.80 +BMP_DB_PORT=3306 +BMP_DB_USER=bmp_rw +BMP_DB_PASSWORD='LpK9Jq12Zf!' +BMP_DB_NAME=bmp +BMP_REDIS_HOST=192.168.14.80 +BMP_REDIS_PORT=6379 +BMP_REDIS_PASSWORD='LpK9Jq12Zf' +BMP_MQ_HOST=192.168.14.80 +BMP_MQ_PORT=5672 +BMP_MQ_USER=bmp +BMP_MQ_PASSWORD='LpK9Jq12Zf' +BMP_MQ_VHOST=/bmp +BMP_OMAPI_HOST=192.168.14.80 +BMP_OMAPI_PORT=7911 +BMP_OMAPI_TOKEN="LpK9Jq12Zf" +BMP_OPENAPI_HOST=192.168.14.80 +BMP_OPENAPI_PORT=8801 +BMP_OPENAPI_CONSOLE_HOST=192.168.14.80 +BMP_OPENAPI_CONSOLE_PORT=8802 +BMP_OOB_ALERT_HOST=192.168.14.80 +BMP_OOB_ALERT_PORT=8804 +BMP_MQ_EXCHANGE_ROUTING_KEY=idc-vm4xsulx1k2d9z4xkctrttig02zl +BMP_IMAGE_PORT=10000 +BMP_MONITOR_PROXY_PORT=8805 +BMP_PROMETHEUS_HOST=192.168.14.80 +BMP_PROMETHEUS_PORT=9090 +BMP_PROMETHEUS_DATA_DIR=/data/prometheus +BMP_PUSHGATEWAY_HOST=192.168.14.80 +BMP_PUSHGATEWAY_PORT=9091 +BMP_ALERTMANAGER_HOST=192.168.14.80 +BMP_ALERTMANAGER_PORT=9093 +BMP_PRONOEA_HOST=192.168.14.80 +BMP_PRONOEA_PORT=9999 +BMP_RSYSLOG_PORT=1514 + +# bootloader +bmp_bootloader_prefix=bootloader +bmp_bootloader_images=( + BOOTLOONGARCH64.EFI + grubaa64.efi + grubx64.efi + pxelinux.0 +) + +# LiveOS image +bmp_oss_liveos_prefix=LiveOS + +bmp_kernel_name_x86=v2.0.7-centos_7_9-2024082914-vmlinuz +bmp_initramfs_name_x86=v2.0.7-centos_7_9-2024082914-initramfs.gz + +bmp_kernel_name_arm64=v2.0.7-centos_7_9_arm64-2024082914-vmlinuz +bmp_initramfs_name_arm64=v2.0.7-centos_7_9_arm64-2024082914-initramfs.gz + +bmp_kernel_name_loonarch64=vmlinuz-loongarch +bmp_initramfs_name_loonarch64=initramfs-loongarch.gz + +bmp_liveos_images=( + ${bmp_kernel_name_x86} + ${bmp_initramfs_name_x86} + ${bmp_kernel_name_arm64} + ${bmp_initramfs_name_arm64} + ${bmp_kernel_name_loonarch64} + ${bmp_initramfs_name_loonarch64} +) +BMP_KERNEL_PATH_x86=/${bmp_kernel_name_x86} +BMP_INITRAMFS_PATH_x86=/${bmp_initramfs_name_x86} +BMP_KERNEL_PATH_arm64=/images/arm64/${bmp_kernel_name_arm64} +BMP_INITRAMFS_PATH_arm64=/images/arm64/${bmp_initramfs_name_arm64} +BMP_KERNEL_PATH_loonarch64=/images/loongarch64/${bmp_kernel_name_loonarch64} +BMP_INITRAMFS_PATH_loonarch64=/images/loongarch64/${bmp_initramfs_name_loonarch64} +set +a +~~~ +并生效 +~~~ +source tftp.env +~~~ + +# 第五步:启动tftp服务 +~~~ +systemctl restart tftp +# 检查状态 +systemctl status tftp +~~~ + +#### bmp-mysql + +| 应用组件 | 类别 | 语言/组件 | +|-------------------|------| --- | +| bmp-db | 基础组件 | mysql | + +以下是在Linux系统上安装和部署MySQL的基本步骤: +~~~ +# 第一步:安装MySQL +# 本章节介绍使用清华镜像源进行安装 +cat << EOF > /etc/yum.repos.d/tsinghua-mysql-community.repo +[mysql57-community] +name=MySQL 5.7 Community Server +baseurl=https://mirrors.tuna.tsinghua.edu.cn/mysql/yum/mysql-5.7-community-el7-\$basearch +enabled=1 +gpgcheck=0 +EOF + +sudo yum clean all +sudo yum makecache +sudo yum install mysql-community-server + +# 第二步:启动MySQL服务 +sudo systemctl start mysqld + +# 第三步:安装完成后,MySQL 会生成一个临时密码。你可以通过查看日志文件来获取这个临时密码 +grep 'temporary password' /var/log/mysqld.log + +# 第四步:登录MySQL +mysql -u root -p +输入你在上一步中找到的临时密码。 + +# 第五步:创建新用户和数据库 +ALTER USER 'root'@'localhost' IDENTIFIED BY 'LpK9Jq12Zf!'; +CREATE USER 'bmp_rw'@'%' IDENTIFIED BY 'LpK9Jq12Zf!'; +CREATE DATABASE bmp; +GRANT ALL PRIVILEGES ON bmp.* TO 'bmp_rw'@'%'; +FLUSH PRIVILEGES; + +# 第六步:导入初始化数据 +数据位于 bmp-deploy/sql/bmp.sql,导入命令 +cd bmp-deploy +mysql -uroot -p bmp < ./sql/bmp.sql +输入设置的root密码即可 +~~~ + +#### bmp-redis + +| 应用组件 | 类别 | 语言/组件 | +|-------------------|------| --- | +| bmp-redis | 基础组件 | redis | + +~~~ +在CentOS 7上安装Redis可以按照以下步骤进行: + +# 第一步: 更新系统包 +# 首先,更新系统包以获取最新的软件包列表: +sudo yum update -y + +# 第二步:安装EPEL仓库 +# Redis不是CentOS默认的软件源中的一部分,所以我们需要添加EPEL(Extra Packages for Enterprise Linux)仓库来获取Redis安装包: +sudo yum install epel-release -y + +# 第三步:安装Redis +sudo yum install redis -y + +# 第四步:配置Redis密码 +Redis的配置文件位于/etc/redis.conf +vi /etc/redis.conf +追加一行,设置密码 +requirepass LpK9Jq12Zf +追加一行,设置bind地址,即允许哪些地址可访问该redis,本实例用于测试,设置0.0.0.0,即所有地址可访问,生产环境请根据实际情况设置 +bind 0.0.0.0 + +# 第五步:启动Redis服务 +sudo systemctl start redis + +# 第六步:测试密码 +redis-cli -a LpK9Jq12Zf ping +~~~ +#### bmp-mq + +| 应用组件 | 类别 | 语言/组件 | +|-------------------|------| --- | +| bmp-mq | 基础组件 | rabbitmq | + +~~~ +在CentOS 7上安装RabbitMQ可以按照以下步骤进行: + +# 第一步:添加EPEL仓库 + +首先,需要添加EPEL(Extra Packages for Enterprise Linux)仓库来获取RabbitMQ安装包: +sudo yum install epel-release -y + +# 第二步:安装Erlang +# RabbitMQ是用Erlang编写的,所以我们需要先安装Erlang: +sudo yum install erlang -y + +# 第三步:安装RabbitMQ +sudo yum install rabbitmq-server -y + +# 第四步:启动RabbitMQ服务 +sudo systemctl start rabbitmq-server + +# 第五步:创建管理员账户 +# 默认情况下,RabbitMQ没有启用管理插件。我们需要创建一个管理员账户并启用管理插件: +rabbitmqctl add_vhost /bmp +rabbitmqctl add_user bmp "LpK9Jq12Zf" +rabbitmqctl set_user_tags bmp administrator +rabbitmqctl set_permissions -p "/bmp" bmp '.*' '.*' '.*' +rabbitmqctl list_users + +### 第六步:访问RabbitMQ管理界面 +现在,你可以通过浏览器访问`http://your-server-ip:15672`来访问RabbitMQ的管理界面。使用你刚刚创建的管理员账户登录。 +~~~ + +#### bmp-rsyslog + +| 应用组件 | 类别 | 语言/组件 | +|-------------------|------| --- | +| bmp-rsyslog | 开源组件 | rsyslog | + +~~~ +在CentOS 7上安装rsyslog可以按照以下步骤进行: + +# 第一步:更新系统包 +首先,更新系统包以获取最新的软件包列表: +sudo yum update -y + +# 第二步:安装rsyslog +sudo yum install rsyslog -y + +# 第三步:配置rsyslog +cat << EOF > /etc/rsyslog.d/bmp-rsyslog.conf +module(load="imudp") # needs to be done just once +input(type="imudp" port="514") +\$template RemoteLogs,"/var/log/bmp/bmp-rsyslog/%fromhost-ip%/%PROGRAMNAME%-%\$YEAR%-%\$MONTH%-%\$DAY%.log" +\$template DynamicDir,"/var/log/bmp/bmp-rsyslog/%fromhost-ip%" +:syslogtag, startswith, "ip" ?DynamicDir +if $fromhost-ip != "127.0.0.1" then ?RemoteLogs +& ~ +EOF + +# 第四步:启动rsyslog服务 +sudo systemctl start rsyslog +~~~ + +### 前端组件 vue + + | 应用组件 | 类别 | 语言/组件 | + |-------------------|------| --- | + | bmp-console-web | 前端 | vue | + | bmp-operation-web | 前端 | vue | + +~~~ +# node 版本要求 +版本 16.19.0 + +# 安装nodejs +wget https://nodejs.org/dist/v16.19.0/node-v16.19.0-linux-x64.tar.xz +tar -xvf node-v16.19.0-linux-x64.tar.xz +mv node-v16.19.0-linux-x64 /usr/local/nodejs +cd /usr/bin +ln -s /usr/local/nodejs/bin/node node +ln -s /usr/local/nodejs/bin/npm npm +ln -s /usr/local/nodejs/bin/npx npx + +# 配置npm镜像源 +npm config set registry https://registry.npmjs.org +# 可根据自己的网络情况配置国内镜像源 +npm config set registry https://registry.npmmirror.com + +# 安装依赖 +npm install --legacy-peer-deps + +# 打包 +npm run build-pre + +# 本地开发测试 +npm run dev +~~~ +上述编译打包命令,会生成dist目录,将dist目录分别拷贝到nginx的主目录下 +- /home/bmp/bmp-console-web +- /home/bmp/bmp-operation-web + +~~~ +mkdir -p /home/bmp/bmp-console-web +mkdir -p /home/bmp/bmp-operation-web +cp -r bmp-console-web/dist/* /home/bmp/bmp-console-web +cp -r bmp-operation-web/dist/* /home/bmp/bmp-operation-web +~~~ +- 然后配置nginx + 如果已安装nginx,请跳过安装步骤 + ~~~ + # 安装nginx + yum install nginx + systemctl start nginx + ~~~ + + - 配置bmp-console-web + 将以下内容复制到/etc/nginx/conf.d/bmp-console-web.conf + +~~~ + log_format main1 '$time_local | $remote_addr | $upstream_addr | $http_host | $status | $body_bytes_sent | $upstream_response_time | $request_time | $http_host | $request | $http_referer'; + + server { + listen 8080; + server_name bmp-console.bmp.local; + charset utf-8; + access_log /var/log/nginx/access.log main1; + + error_page 500 502 503 504 /50x.html; + location = /50x.html { + root html; + } + + root /home/bmp/bmp-console-web; + index index.html; + + location /console-web/ { + set $bmp_console_api "127.0.0.1:8800"; + rewrite ^/console-web/(.*) /$1 break; + proxy_pass http://$bmp_console_api; + } + + location /oob-alert/ { + client_max_body_size 51200M; + set $bmp_oob_alert "127.0.0.1:8804"; + rewrite ^/oob-alert/(.*) /$1 break; + proxy_pass http://$bmp_oob_alert; + } + + location / { + try_files $uri $uri/ @router; + index index.html; + } + + location @router { + rewrite ^.*$ /index.html last; + } + location ~.*\.(html)$ { + add_header Cache-Control no-cache; + } + + } +~~~ + +- 配置bmp-operation-web + 将以下内容复制到/etc/nginx/conf.d/bmp-operation-web.conf +~~~ + server { + listen 8081; + server_name bmp-operation.bmp.local; + charset utf-8; + access_log /var/log/nginx/access.log main1; + + error_page 500 502 503 504 /50x.html; + location = /50x.html { + root html; + } + + root /home/bmp/bmp-operation-web; + index index.html; + + # compression-webpack-plugin 配置 + #gzip on; + #gzip_min_length 1k; + #gzip_comp_level 9; + #gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript applicationx-httpd-php image/jpeg image/gif image/png; + #gzip_vary on; + # 配置禁用 gzip 条件,支持正则,此处表示 ie6 及以下不启用 gzip(因为ie低版本不支持) + #gzip_disable "MSIE [1-6]\."; + + location /operation-web/ { + client_max_body_size 51200M; + set $bmp_operation_api "127.0.0.1:8799"; + rewrite ^/operation-web/(.*) /$1 break; + proxy_pass http://$bmp_operation_api; + } + + location /oob-alert/ { + client_max_body_size 51200M; + set $bmp_oob_alert "127.0.0.1:8804"; + rewrite ^/oob-alert/(.*) /$1 break; + proxy_pass http://$bmp_oob_alert; + } + + location / { + try_files $uri $uri/ @router; + index index.html; + } + + location @router { + rewrite ^.*$ /index.html last; + } + location ~.*\.(html)$ { + add_header Cache-Control no-cache; + } + +} +~~~ +重新加载nginx配置 +~~~ +nginx -s reload +~~~ + +### 后端组件 +#### 后端go组件 + + | 应用组件 | 类别 | 语言/组件 | + |-------------------|------| --- | + | bmp-console-api | 后端 | go | + | bmp-operation-api | 后端 | go | + | bmp-openapi | 后端 | go | + | bmp-scheduler | 后端 | go | + | bmp-openapi-console | 后端 | go | + | bmp-driver | 后端 | go | + | bmp-oob-alert | 后端 | go | + | bmp-oob-agent | 后端 | go | + | bmp-pronoea | 后端 | go | + | bmp-monitor-proxy | 后端 | go | + + +1. 后端组件会依赖以下基础组件,本地调试后端代码前,先启动以下组件: + - [bmp-db](#2.2.3) + - [bmp-redis](#2.2.4) + - [bmp-mq](#2.2.5) + +2. 先创建各个组件的日志目录 +~~~ +# 举例 +mkdir -p /var/log/bmp/bmp-openapi +~~~ +3. [设置环境变量](#2.1.2) +4. 编译运行 +~~~ +# 版本要求: golang:1.17 + +# 安装 golang:1.17 +wget https://golang.google.cn/dl/go1.17.linux-amd64.tar.gz +tar -zxf go1.17.linux-amd64.tar.gz -C /usr/local + +# 在/etc/profile文件末尾添加以下配置。按esc后,输入 :wq保存 +#golang config +export GOROOT=/usr/local/go +export GOPATH=/local/gopath +export PATH=$PATH:$GOROOT/bin:$GOPATH/bin + +# 创建/local/gopath +mkdir -p /local/gopath + +# 环境变量生效 +source /etc/profile + +# 查看Go版本 +go version + +# 设置代理,可根据自身网络选择不同的代理 +export GOPROXY=https://goproxy.cn + +# 本地运编译调试,举例 bmp-openapi +cd bmp-openapi + +# 编译 +go build -o bmp-openapi + +# 运行 +./bmp-openapi +# 联调阶段各个组件需要在后台运行 +nohup ./bmp-openapi & +~~~ +请注意: 后端服务需要依赖中间件,及其他组件,如果进行本地联调,需要将*依赖组件*提前部署,具体依赖见每个go代码中的conf目录文件,举例bmp-openapi的conf文件bmp-openapi.ini如下 +~~~ +# mysql +jdbc.url= +bmp_db_host=${BMP_DB_HOST} +bmp_db_port=${BMP_DB_PORT} +bmp_db_user=${BMP_DB_USER} +bmp_db_password=${BMP_DB_PASSWORD} +bmp_db_name=${BMP_DB_NAME} + +bmp_redis_host=${BMP_REDIS_HOST} +bmp_redis_port=${BMP_REDIS_PORT} +bmp_redis_password=${BMP_REDIS_PASSWORD} + + +# RabbitMQ for Ironic +bmp_mq_host=${BMP_MQ_HOST} +bmp_mq_port=${BMP_MQ_PORT} +bmp_mq_user=${BMP_MQ_USER} +bmp_mq_password=${BMP_MQ_PASSWORD} +bmp_mq_vhost=${BMP_MQ_VHOST} +bmp_mq_exchange=CPS_IRONIC_SCHEDULER +bmp_mq_receive_routing_key=/test + +bmp_monitor_proxy_host=${BMP_MONITOR_PROXY_HOST||192.168.12.72} +bmp_monitor_proxy_port=${BMP_MONITOR_PROXY_PORT||8805} + +bmp_pronoea_host=${BMP_PRONOEA_HOST||192.168.12.75} +bmp_pronoea_port=${BMP_PRONOEA_PORT||9999} + +bmp_image_host=${BMP_IMAGE_HOST||192.168.12.72} +bmp_image_port=${BMP_IMAGE_PORT||10000} +~~~ + +### 后端 python 组件 + +| 应用组件 | 类别 | 语言/组件 | +|-------------------|------| --- | +| bmp-dhcp-agent | 后端 | python | + +该组件依赖环境变量,请先完成 [端口规划](#2.1.2)部分 +并设置以下环境变量 +cat bmp-dhcp-agent.env +~~~ +set -a +BMP_MQ_PORT=5672 +BMP_MQ_USER=bmp +BMP_MQ_PASSWORD='LpK9Jq12Zf' +BMP_MQ_VHOST=/bmp +BMP_OMAPI_HOST=${BMP_HOST_IP} +BMP_OMAPI_PORT=7911 +BMP_OMAPI_TOKEN="LpK9Jq12Zf" + +BMP_MQ_HOST=${BMP_HOST_IP} +BMP_OMAPI_HOST=${BMP_HOST_IP} +BMP_DHCP_CONFIG_DIR=/home/dhcp/data +BMP_DHCP_CONTROL_BIN=/home/dhcp/dhcpd_control.sh +# BMP_TFTP_CONFIG_DIR需要与tftp安装步骤中的tftp文档路径保持一致 +BMP_TFTP_CONFIG_DIR=/var/lib/tftpboot +BMP_TFTP_MQ_HOST=${BMP_HOST_IP} +BMP_TFTP_MQ_PORT=${BMP_MQ_PORT} +BMP_TFTP_MQ_USER=${BMP_MQ_USER} +BMP_TFTP_MQ_PASSWORD=${BMP_MQ_PASSWORD} +BMP_TFTP_MQ_VHOST=${BMP_MQ_VHOST} +BMP_TFTP_MQ_EXCHANGE_ROUTING_KEY=${BMP_MQ_EXCHANGE_ROUTING_KEY} +BMP_TFTP_IMAGE_HOST=${BMP_HOST_IP} +BMP_TFTP_IMAGE_PORT=${BMP_IMAGE_PORT} +BMP_TFTP_RSYSLOG_HSOT=${BMP_HOST_IP} +BMP_TFTP_RSYSLOG_PORT=${BMP_RSYSLOG_PORT} +set +a +~~~ +~~~ +source bmp-dhcp-agent.env +~~~ +创建dhcp目录 +~~~ +mkdir -p /home/dhcp/data +~~~ +编辑配置文件 /home/dhcp/data/dhcpd.conf +~~~ +ddns-update-style none; +ignore client-updates; +ddns-update-style none; +ignore client-updates; + +next-server ${BMP_HOST_IP}; +filename \"pxelinux.0\"; + +default-lease-time 600; +max-lease-time 1200; +option domain-name \"localhost\"; +option domain-name-servers 114.114.114.114,8.8.8.8; + +#pxe +option client-system-architecture code 93 = unsigned integer 16; +class \"pxe-clients\" { + match if (substring (option vendor-class-identifier, 0, 9) = \"PXEClient\") or + (substring (option vendor-class-identifier, 0, 9) = \"HW-Client\"); + if option client-system-architecture = 00:00 { + filename \"pxelinux.0\"; + }else if option client-system-architecture = 00:07 { + filename \"/uefi/x86_64/grubx64.efi\"; + }else if option client-system-architecture = 00:0b { + filename \"/uefi/arm64/grubaa64.efi\"; + }else if option client-system-architecture = 00:0c { + filename \"/uefi/loongarch64/BOOTLOONGARCH64.EFI\"; + }else if option client-system-architecture = 00:27 { + filename \"/uefi/loongarch64/BOOTLOONGARCH64.EFI\"; + } +} + +key omapi_key { + algorithm hmac-md5; + secret ${BMP_OMAPI_KEY}; +}; +omapi-key omapi_key; +omapi-port ${BMP_OMAPI_PORT}; + +subnet ${BMP_HOST_IP} netmask 255.255.255.255 { + +} +~~~ +编辑启动文件/home/dhcp/dhcpd_control.sh +~~~ +#!/bin/sh +set -ue + +[ -z "$BMP_DHCP_CONFIG_DIR" ] && echo "error! BMP_DHCP_CONFIG_DIR is unset!" && exit 1 + +if [ ! -e $BMP_DHCP_CONFIG_DIR/dhcpd.conf ] && [ -e /dhcpd.conf.tpl ]; then + eval "echo \"$(cat /dhcpd.conf.tpl)\"" > $BMP_DHCP_CONFIG_DIR/dhcpd.conf +fi + +LOG_FILE=/var/log/bmp/bmp-dhcp-agent/dhcpd.log +exec_file=/usr/sbin/dhcpd +data_dir=$BMP_DHCP_CONFIG_DIR +dhcpd_conf="$data_dir/dhcpd.conf" +PID="" +if [ ! -r "$dhcpd_conf" ]; then + echo "Please ensure '$dhcpd_conf' exists and is readable." + echo "Run the container with arguments 'man dhcpd.conf' if you need help with creating the configuration." + exit 1 +fi + +[ -e "$data_dir/dhcpd.leases" ] || touch "$data_dir/dhcpd.leases" + + +help(){ + echo "${0} " + exit 1 +} + +get_pid() +{ + local pid="" + pid=$(ps -ef | grep "$exec_file" | grep -v 'grep' | awk '{print $1}') + PID=$pid +} + +checkhealth(){ + get_pid + [ X"$PID" != X"" ] && echo "dhcpd is running" && return 0 + echo "dhcpd is not running" && return 1 +} + +start(){ + /usr/sbin/dhcpd -f -d --no-pid -cf "$data_dir/dhcpd.conf" -lf "$data_dir/dhcpd.leases" >> $LOG_FILE 2>&1 & +} + +stop(){ + checkhealth || return 0 + [ X"$PID" != X"" ] && kill $PID + sleep 2 + checkhealth || return 0 + return 1 +} + +case "${1}" in + start) + start + ;; + stop) + stop + ;; + status|health|checkhealth) + checkhealth + ;; + restart) + stop && start + ;; + *) + help + ;; +esac +~~~ +~~~ +# 要求 python3.6+ 环境 + +# 本地安装dhcp服务,举例centos系统 +sudo yum install dhcp +sudo yum install python3 +# 安装python依赖 +pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple/ -r requirements.txt + +# 运行 +cd bmp-dhcp-agent +export PYTHONPATH=$(pwd) +python3 ./bmpda/cmd/server.py +~~~ + +### 开源组件 + +| 应用组件 | 类别 | 语言/组件 | +|-------------------|------| --- | +| bmp-prometheus | 开源组件 | prometheus | +| bmp-pushgateway | 开源组件 | pushgateway | +| bmp-alertmanager | 开源组件 | alertmanager | +以上三个监控告警组件是开源prometheus解决方案,可一起安装使用 +三者工作原理是 +1. 应用程序或服务将指标数据推送到Pushgateway。 +2. Prometheus服务器定期从Pushgateway中拉取这些指标数据,并将其存储在自己的时间序列数据库中。 +3. Prometheus中触发告警条件的信息,由alertmanager组件发送告警信息 +#### bmp-pushgateway +~~~ +在CentOS 7上安装Pushgateway可以按照以下步骤进行: + +# 第一步:下载Pushgateway二进制文件 + +首先,下载Pushgateway二进制文件。可以从Prometheus的官方网站或GitHub仓库中获取。例如,使用以下命令下载Pushgateway v1.4.0: +wget https://github.com/prometheus/pushgateway/releases/download/v1.4.0/pushgateway-1.4.0.linux-amd64.tar.gz +如果网络受限,可以使用其他方式下载 +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/opensource/pushgateway-1.4.0.linux-amd64.tar.gz + +# 第二步:解压缩Pushgateway文件 +tar -xvf pushgateway-1.4.0.linux-amd64.tar.gz + +# 第三步:创建Pushgateway用户和组 +sudo groupadd --system pushgateway +sudo useradd --system -s /bin/false -g pushgateway pushgateway + +# 第四步:移动Pushgateway文件到合适的位置 +sudo mv pushgateway-1.4.0.linux-amd64 /usr/local/pushgateway + +# 第五步:设置文件权限 +sudo chown -R pushgateway:pushgateway /usr/local/pushgateway +sudo chmod -R 755 /usr/local/pushgateway + +# 第六步:创建Pushgateway配置文件 +sudo mkdir /etc/pushgateway +sudo touch /etc/pushgateway/pushgateway.yml + +# 第七步:创建Pushgateway服务文件 +sudo cat << EOF > /etc/systemd/system/pushgateway.service +[Unit] +Description=Pushgateway +Wants=network-online.target +[Service] +User=pushgateway +Group=pushgateway +ExecStart=/usr/local/pushgateway/pushgateway \ + --web.config.file /etc/pushgateway/pushgateway.yml \ + --web.listen-address :9091 \ + --web.enable-admin-api +Restart=always +[Install] +WantedBy=multi-user.target +EOF + +# 第八步:启动Pushgateway服务 +sudo systemctl daemon-reload +sudo systemctl start pushgateway +# 第九步:检查服务状态 +sudo systemctl status pushgateway +~~~ +#### bmp-prometheus +~~~ + +在CentOS上安装Prometheus可以按照以下步骤进行: + +# 第一步:下载Prometheus二进制文件 +wget https://github.com/prometheus/prometheus/releases/download/v2.36.1/prometheus-2.36.1.linux-amd64.tar.gz +如果网络受限.可以使用其他方式下载 +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/opensource/prometheus-2.36.1.linux-amd64.tar.gz + +# 第二步:解压缩Prometheus文件 +tar -xzvf prometheus-2.36.1.linux-amd64.tar.gz + +# 第三步:创建Prometheus用户和组 +sudo groupadd prometheus +sudo useradd -g prometheus -d /home/prometheus prometheus + +# 第四步:移动Prometheus文件到合适的位置 +sudo mv prometheus-2.36.1.linux-amd64 /usr/local/prometheus + +# 第五步:设置文件权限 +sudo chown -R prometheus:prometheus /usr/local/prometheus +sudo chmod -R 755 /usr/local/prometheus + +# 第六步:创建Prometheus配置文件 +sudo mkdir /etc/prometheus +sudo cat << EOF > /etc/prometheus/prometheus.yml +scrape_configs: + - job_name: 'pushgateway' + scrape_interval: 60s + honor_labels: true + static_configs: + - targets: ['\${BMP_PUSHGATEWAY_HOST}:\${BMP_PUSHGATEWAY_PORT}'] +alerting: + alertmanagers: + - static_configs: + - targets: ['\${BMP_ALERTMANAGER_HOST}:\${BMP_ALERTMANAGER_PORT}'] +rule_files: + - /home/prometheus/conf/rules/*.yml +EOF +# 请注意,设置以下四个变量值 +BMP_ALERTMANAGER_HOST / BMP_PUSHGATEWAY_PORT / BMP_ALERTMANAGER_HOST / BMP_ALERTMANAGER_PORT + +# 第七步:创建Prometheus服务文件 +sudo cat << EOF > /etc/systemd/system/prometheus.service +[Unit] +Description=Prometheus +Wants=network-online.target + +[Service] +User=prometheus +Group=prometheus +ExecStart=/usr/local/prometheus/prometheus \ + --config.file /etc/prometheus/prometheus.yml \ + --storage.tsdb.path /home/prometheus \ + --web.console.libraries /usr/local/prometheus/console-libraries \ + --web.console.templates /usr/local/prometheus/consoles \ + --web.enable-lifecycle +Restart=always +[Install] +WantedBy=multi-user.target +EOF + +# 第八步:启动Prometheus服务 +sudo systemctl daemon-reload +sudo systemctl start prometheus + +## 第九步:检查Prometheus服务状态 +sudo systemctl status prometheus +~~~ + +#### bmp-alertmanager +~~~ +# 第一步:下载Alertmanager二进制文件 +wget https://github.com/prometheus/alertmanager/releases/download/v0.24.0/alertmanager-0.24.0.linux-amd64.tar.gz +如果网络受限,可以使用其他方式下载 +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/opensource/alertmanager-0.24.0.linux-amd64.tar.gz +# 第二步:解压缩Alertmanager文件 +tar -xzvf alertmanager-0.24.0.linux-amd64.tar.gz + +# 第三步:创建Alertmanager用户和组 +sudo groupadd alertmanager +sudo useradd -g alertmanager -d /home/alertmanager alertmanager + +# 第四步:移动Alertmanager文件到合适的位置 +sudo mv alertmanager-0.24.0.linux-amd64 /usr/local/alertmanager + +# 第五步:设置文件权限 +sudo chown -R alertmanager:alertmanager /usr/local/alertmanager +sudo chmod -R 755 /usr/local/alertmanager + +# 第六步:创建Alertmanager配置文件 +sudo mkdir /etc/alertmanager +sudo cat << EOF > /etc/alertmanager/alertmanager.yml +global: + resolve_timeout: 5s +route: + group_by: ['alertname'] + group_wait: 0s + group_interval: 60m + repeat_interval: 10s + receiver: 'bmpAlertReceiver' + routes: + - receiver: 'bmpAlertReceiver' + group_interval: 5m + match: + noticePeriodLabel: NoticePeriod-5m + - receiver: 'bmpAlertReceiver' + group_interval: 10m + match: + noticePeriodLabel: NoticePeriod-10m + - receiver: 'bmpAlertReceiver' + group_interval: 15m + match: + noticePeriodLabel: NoticePeriod-15m + - receiver: 'bmpAlertReceiver' + group_interval: 30m + match: + noticePeriodLabel: NoticePeriod-30m + - receiver: 'bmpAlertReceiver' + group_interval: 60m + match: + noticePeriodLabel: NoticePeriod-60m + - receiver: 'bmpAlertReceiver' + group_interval: 180m + match: + noticePeriodLabel: NoticePeriod-180m + - receiver: 'bmpAlertReceiver' + group_interval: 720m + match: + noticePeriodLabel: NoticePeriod-720m + - receiver: 'bmpAlertReceiver' + group_interval: 1440m + match: + noticePeriodLabel: NoticePeriod-1440m +receivers: + - name: 'bmpAlertReceiver' + webhook_configs: + - url: 'http://127.0.0.1:9999/api/alert/receiver' +EOF +# 请注意127.0.0.1:9999为${BMP_PRONOEA_HOST}:${BMP_PRONOEA_PORT},可根据实际情况修改 + +### 7. 创建Alertmanager服务文件 +sudo cat << EOF > /etc/systemd/system/alertmanager.service +[Unit] +Description=Alertmanager +Wants=network-online.target + +[Service] +User=alertmanager +Group=alertmanager +ExecStart=/usr/local/alertmanager/alertmanager \ + --config.file /etc/alertmanager/alertmanager.yml \ + --web.listen-address :9093 + --log.level=debug +Restart=always + +[Install] +WantedBy=multi-user.target +EOF + +# 第八步:启动Alertmanager服务 +sudo systemctl daemon-reload +sudo systemctl start alertmanager + +## 第九步:检查Alertmanager服务状态 +sudo systemctl status alertmanager +~~~ + +## 组件联调部署 +在上述步骤中分别介绍了单个组件的非容器部署命令,本小节介绍如何按顺序依次启动各个组件,进行联调 +### 第一步: 环境准备 +**环境准备包括 *网络环境准备* 和 *服务器准备* 两部分 +具体步骤参见:[环境准备](env-prepare.md)部分** +### 第二步: [设置环境变量](#2.1.2) +### 第三步: 组件按顺序启动 +请按照以下顺序依次启动各个组件: +1. 启动底层中间件,并初始化 + - [bmp-db](#2.2.3) + - [bmp-redis](#2.2.4) + - [bmp-mq](#2.2.5) +2. 启动 [bmp-scheduler](#2.4.1) +3. 启动 [bmp-openapi 和 bmp-openapi-console](#2.4.1) +4. 启动 后端相关组件 + - [bmp-image](#2.2.1) + - [bmp-tftp](#2.2.2) + - [bmp-rsyslog](#2.2.6) + - [其他后端组件](#2.4.1) + + | 应用组件 | 类别 | 语言/组件 | + |-------------------|------| --- | + | bmp-console-api | 后端 | go | + | bmp-operation-api | 后端 | go | + | bmp-driver | 后端 | go | + | bmp-oob-alert | 后端 | go | + | bmp-oob-agent | 后端 | go | + | bmp-pronoea | 后端 | go | + | bmp-monitor-proxy | 后端 | go | + | bmp-dhcp-agent | 后端 | python | +5. 启动 监控组件 +请注意: 顺序不能乱 + - [bmp-pushgateway](#2.5.1) + - [bmp-alertmanager](#2.5.3) + - [bmp-prometheus](#2.5.2) + - [bmp-pronoea](#2.4.1) + +6. 启动 前端组件 + + | 应用组件 | 类别 | 语言/组件 | + |-------------------|------| --- | + | bmp-console-web | 前端 | vue | + | bmp-operation-web | 前端 | vue | + + +### 第四步:访问 BMP +注:默认账号:admin,密码:df9Ydfd$c +控制台:http://manager_ip:8080。本示例是http://192.168.14.80:8080。 + +运营平台: http://manager_ip:8081。本示例是http://192.168.14.80:8081。 + + +### 第五步:管理平台纳管裸金属服务器 +登陆bmp运营平台,进入设备管理界面,导入bmp节点信息 + + + + + + + + + + + diff --git a/docs/zh/setup.md b/docs/zh/setup.md new file mode 100644 index 0000000..d56783e --- /dev/null +++ b/docs/zh/setup.md @@ -0,0 +1,152 @@ +# 一键部署 BMP 系统 +- [一键部署概述](#1) + - [名词解释](#1.1) + - [整体部署步骤](#1.2) +- [环境准备](#2) +- [管理节点部署](#3) + - [环境准备](#3.1) + - [配置环境参数](#3.2) + - [一键部署 BMP](#3.3) + - [访问 BMP](#3.4) + - [BMP平台纳管物理服务器](#3.5) + +## 一键部署概述 +### 名词解释 +- BMP +裸金属管理平台,Bare Metal Manage Platform ,简称 BMP 。 +- manager节点 +BMP管理服务器(管理节点),运行着所有BMP组件(除了bmp-agent) +- bm节点 +装机节点,正常工作用的物理服务器,未装机前无操作系统,装机阶段运行LiveOS,装机完成后运行GuestOS。 +- GuestOS +正常工作的操作系统 +- LiveOS +内存操作系统,里面预装了bmp-agent +- 带外网卡 +物理服务器上用于与bmc通信的特殊网卡,又称ipmi网卡 +- 管理网卡 +物理服务器的标准的网卡,处在管理网络中 + +### 整体部署步骤 +- manager节点和bm节点在一个大二层网络中(如果仅体验BMP平台,不打算体验BMP裸金属装机流程,此步骤可跳过) +- manager节点安装操作系统CentOS 7.9 +- 配置bm节点上联tor的dhcp-relay地址为manager节点的ip地址(如果仅体验BMP平台,不打算体验BMP裸金属装机流程,此步骤可跳过) +- 在manager节点通过docker部署BMP平台 参考 [管理节点部署](#3) + +## 环境准备 +**环境准备包括 *网络环境准备* 和 *服务器准备* 两部分 +具体步骤参见:[环境准备](env-prepare.md)部分** + + +## 管理节点部署 +~~~ +第一步:环境准备 + +第二步:配置环境参数 + +第三步:一键部署 BMP + +第四步:访问 BMP + +第五步:BMP平台纳管物理服务器 +~~~ + +### 第一步:环境准备 + +#### 1. 安装docker和docker compose +- yum安装方式(CentOS 7.9系统) +~~~ +#可使用国内镜像源,比如清华镜像源 +yum install -y yum-utils +yum-config-manager \ + --add-repo \ + https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/centos/docker-ce.repo +sed -i 's+https://download.docker.com+https://mirrors.tuna.tsinghua.edu.cn/docker-ce+' /etc/yum.repos.d/docker-ce.repo + +yum install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin + +systemctl start docker +~~~ + +更多安装方式请参考docker官网 +- Docker官方文档地址:https://docs.docker.com/ +- Docker Compose官方文档地址:https://docs.docker.com/compose/ + +### 2. 下载BMP源码到manager节点服务器 +下载前先明确BMP的部署目录,本实例默认安装在用户家目录,首先 +~~~ +# 跳转到家目录,再执行后续下载命令 +cd ~ +~~~ +找到主页右上角的 【Code】 按钮,点开下拉菜单,如图 +![github.png](bmp-deploy/picture/github.png) +- 方式一:用git clone命令 +~~~ +# 在管理节点执行,clone 上面复制的 HTTPS 链接,举例: + git clone https://github.com/jd-opensource/Baremetal_Manage_Platform.git +~~~ +- 方式二:点击 Download ZIP ,直接下载zip包后,手动传到管理服务器上 +更多github操作,参考 github官方操作文档: +https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository +- 方式三:可直接从京东云下载安装包 +~~~ +wget https://bmp.s3.cn-north-1.jdcloud-oss.com/opensource/Baremetal_Manage_Platform-33040a7.zip +unzip Baremetal_Manage_Platform-33040a7.zip -d Baremetal_Manage_Platform +~~~ + +### 第二步:配置环境参数 +- 部署脚本目录 + 部署脚本位于 bmp-deploy目录下 + 目录内文件说明:[bmp-deploy文件和目录说明](bmp-deploy/bmp-deploy.md) + +- 修改配置 + 编辑.env文件 + - 修改BMP_HOST_IP为manager节点管理网卡ip。本示例为192.168.14.80,如果服务器多网卡,请配置其中一个ip。如果配置了bond,使用bond网卡。否则尽量选择私网IP地址网卡。 + ifconfig命令-bond0示例图 +![ifconfig-bond0.png](bmp-deploy/picture/ifconfig-bond0.png) + ifconfig命令-eth0示例图 +![ifconfig-eth0.png](bmp-deploy/picture/ifconfig-eth0.png) + - 修改BASE_REGISTRY,部署需要使用mysql/redis/mq/nginx等基础容器镜像,本示例默认从quay.io拉取,如果网络限制,请修改为其他公共或私有镜像仓库 + + +~~~ +cd ~/Baremetal_Manage_Platform/bmp-deploy/ +# 查看服务器ip地址,优先查看bond0的ip地址,再次查看eth0的ip地址。如果不确定请咨询运维人员。 +ifconfig + +# 编辑环境变量 +# 必须和manager节点服务器ip保持一致 +# 设置 BMP_HOST_IP=192.168.14.80 +vi .env +~~~ + +更多配置请参考[配置管理](bmp-deploy/config.md) + +### 第三步:一键部署 BMP +- 安装BMP +~~~ +cd ~/Baremetal_Manage_Platform/bmp-deploy/ +bash bmp-deploy-precheck.sh -e public +bash bmp-deploy.sh start all +~~~ + +- 检查各服务状态 +~~~ +bash bmp-deploy.sh status all +~~~ +正常情况下所有服务的状态都是running,如果某些服务未运行,参考[故障排查](bmp-deploy/troubleshoot.md) +安装过程中会自动从京东对象存储下相关操作系统镜像,下载速度与服务器网速相关,请耐心等待 +更多服务管理操作,参考[服务管理](bmp-deploy/service-manage.md) + +### 第四步:访问 BMP +注:默认账号:admin,密码:df9Ydfd$c + +控制台:http://manager_ip:8080。本示例是http://192.168.14.80:8080。 + +运营平台: http://manager_ip:8081。本示例是http://192.168.14.80:8081。 + + +### 第五步:管理平台纳管裸金属服务器 +登录BMP运营平台,进入设备管理界面,导入bm节点信息 + + diff --git a/oob-log-agent/.cmd b/oob-log-agent/.cmd new file mode 100644 index 0000000..ced32d3 --- /dev/null +++ b/oob-log-agent/.cmd @@ -0,0 +1 @@ +rm -rf vendor diff --git a/oob-log-agent/.gitignore b/oob-log-agent/.gitignore new file mode 100644 index 0000000..eab9e62 --- /dev/null +++ b/oob-log-agent/.gitignore @@ -0,0 +1,6 @@ +*.log +*.temp +*.code-workspace +*.exe +oob-log-agent +oob-log-alert diff --git a/oob-log-agent/.gitmodules b/oob-log-agent/.gitmodules new file mode 100644 index 0000000..067a828 --- /dev/null +++ b/oob-log-agent/.gitmodules @@ -0,0 +1,3 @@ +[submodule "bmp-deploy"] + path = bmp-deploy + url = git@coding.jd.com:bmp/bmp-deploy.git diff --git a/oob-log-agent/Makefile b/oob-log-agent/Makefile new file mode 100644 index 0000000..d05b776 --- /dev/null +++ b/oob-log-agent/Makefile @@ -0,0 +1,41 @@ +# Go parameters + + +GOCMD=go +GOBUILD=$(GOCMD) build +GOCLEAN=$(GOCMD) clean +GOTEST=$(GOCMD) test +GOGET=$(GOCMD) get + +AGENT=oob-log-agent +ALERT=oob-log-alert + +.PHONY: all +all: build +install: + @echo "@Install to ${GOPATH}/bin" + mkdir -p $(GOPATH)/bin + mkdir -p $(GOPATH)/conf + mkdir -p $(GOPATH)/log + cp -f $(AGENT) $(GOPATH)/bin/ + cp -f $(ALERT) $(GOPATH)/bin/ + cp -f agent-wrapper.sh $(GOPATH)/bin/ + cp -rf conf/ $(GOPATH)/ + +clean: + @echo "@Clean workspace" + $(GOCLEAN) + rm -f $(GOPATH)/bin/$(AGENT) + rm -f $(GOPATH)/bin/$(ALERT) + +vendor: glide.lock glide.yaml + @echo "@Download third party dependencies" + glide up + +build: util/*.go object/*.go log-alert/main.go log-agent/main.go + @echo "@Building ..." + $(GOBUILD) -v -gcflags="-N -l" -o $(AGENT) cps-oob-agent/log-agent + $(GOBUILD) -v -gcflags="-N -l" -o $(ALERT) cps-oob-agent/log-alert + + + diff --git a/oob-log-agent/README.md b/oob-log-agent/README.md new file mode 100644 index 0000000..9d0b938 --- /dev/null +++ b/oob-log-agent/README.md @@ -0,0 +1,17 @@ +# bmp-openapi-console + +English | [简体中文](README.zh-CN.md) + + +## Introduction + +The out-of-band monitoring collection module is responsible for obtaining system logs from the device through the ipmitool command and publishing them to redis + +The location of oob-log-agent in the entire bmp architecture is shown in:[bmp arch](../bmp-scheduler/README.md) + + + +## 2,Core Features + +- Collect the system log of the target device through the ipmitool command. +- Publish to redis after filtering. \ No newline at end of file diff --git a/oob-log-agent/README.zh-CN.md b/oob-log-agent/README.zh-CN.md new file mode 100644 index 0000000..edc2561 --- /dev/null +++ b/oob-log-agent/README.zh-CN.md @@ -0,0 +1,18 @@ +# oob-log-agent + +[English](README.md) | 简体中文 + + +## 介绍 + +带外监控采集模块,负责通过ipmitool命令从设备获取系统日志,并publish到redis中 + +oob-log-agent在整个bmp架构中的位置见:[bmp架构图](../bmp-scheduler/README.zh-CN.md) + + + +## 2,核心功能 + +- 通过ipmitool命令采集目标设备的系统日志 +- 过滤后publish到redis中 + diff --git a/oob-log-agent/bmp_vendor/bmp_log/.cmd b/oob-log-agent/bmp_vendor/bmp_log/.cmd new file mode 100644 index 0000000..5c2f328 --- /dev/null +++ b/oob-log-agent/bmp_vendor/bmp_log/.cmd @@ -0,0 +1 @@ +rm test.log.FATAL test.log.INFO test.log.WARN diff --git a/oob-log-agent/bmp_vendor/bmp_log/README.md b/oob-log-agent/bmp_vendor/bmp_log/README.md new file mode 100644 index 0000000..f39a094 --- /dev/null +++ b/oob-log-agent/bmp_vendor/bmp_log/README.md @@ -0,0 +1,6 @@ +精简日志库,用于打点统计,监控,告警等场景 +- WARN,FATAL等等级的日志即时打印落盘 + - 一个流量可以打印多条WARN,FATAL日志 +- INFO,DEBUG等级的日志,一个流量只落一条日志 + - 支持字段顺序自定义,便于正则匹配做监控等场景 + - 支持自定义代码段耗时打印,便于后续性能统计分析 diff --git a/oob-log-agent/bmp_vendor/bmp_log/go.mod b/oob-log-agent/bmp_vendor/bmp_log/go.mod new file mode 100644 index 0000000..410b4d1 --- /dev/null +++ b/oob-log-agent/bmp_vendor/bmp_log/go.mod @@ -0,0 +1,3 @@ +module coding.jd.com/aidc-bmp/bmp_log + +go 1.17 diff --git a/oob-log-agent/bmp_vendor/bmp_log/log.go b/oob-log-agent/bmp_vendor/bmp_log/log.go new file mode 100644 index 0000000..6e5b79c --- /dev/null +++ b/oob-log-agent/bmp_vendor/bmp_log/log.go @@ -0,0 +1,249 @@ +package cps_log + +import ( + "encoding/json" + "fmt" + "io" + "log" + "os" + "reflect" + "strings" + "time" +) + +// Level type +type Level uint32 + +const ( + // TraceLevel level. Designates finer-grained informational events than the Debug. + TraceLevel Level = iota + // DebugLevel level. Usually only enabled when debugging. Very verbose logging. + DebugLevel + // InfoLevel level. General operational entries about what's going on inside the + // application. + InfoLevel + // WarnLevel level. Non-critical entries that deserve eyes. + WarnLevel + // ErrorLevel level. Logs. Used for errors that should definitely be noted. + // Commonly used for hooks to send errors to an error tracking service. + ErrorLevel + // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the + // logging level is set to Panic. + FatalLevel + // PanicLevel level, highest level of severity. Logs and then calls panic with the + // message passed to Debug, Info, ... + PanicLevel +) + +var globalDefinedKeys = []string{"time", "logid", "self_t", "all_t"} + +type Logger struct { + data map[string]interface{} + level Level + fileName string + definedKeys []string +} + +func New(filename string) *Logger { + if filename == "" { + log.Fatal("filename must be provided !!!") + return nil + } + l := &Logger{ + data: make(map[string]interface{}), + fileName: filename, + } + l.definedKeys = append([]string{}, globalDefinedKeys...) + l.data["time"] = time.Now().Format("2006-01-02T15:04:05") + return l +} + +func NewLoggerWithConfig(filename string, level Level, definedKeys []string) *Logger { + l := New(filename) + l.SetLevel(level) + l.SetStableFields(definedKeys) + return l +} + +func (l *Logger) SetLevel(level Level) { + l.level = level +} + +//SetStableFields 需要固定每条日志的字段时,通过此接口设置,global在前,userdefined在后 +func (l *Logger) SetStableFields(fields []string) { + l.definedKeys = append(l.definedKeys, fields...) +} + +func (l *Logger) Point(key string, val interface{}) { + l.data[key] = val +} + +func (l *Logger) GetPoint(key string) interface{} { + return l.data[key] +} + +func (l *Logger) TimeStart(key string) { + if _, ok := l.data[key]; ok { + log.Print(fmt.Sprintf("point %s TimeStart more than once, check !!!", key)) + } + l.data[key] = time.Now() + +} + +func (l *Logger) TimeEnd(key string) { + if t, ok := l.data[key]; ok { + v := time.Now().Sub(t.(time.Time)).Milliseconds() + l.data[key] = fmt.Sprintf("%f", float64(v)/1000.0) + } else { + log.Print(fmt.Sprintf("missing call TimeStart before TimeEnd when point %s, check it!!!", key)) + } + +} + +func (l *Logger) PushPoint(key string, val interface{}) { + if _, ok := l.data[key]; !ok { + l.data[key] = []interface{}{} + } + d := l.data[key].([]interface{}) + d = append(d, val) +} + +func (l *Logger) Info(v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Infof(format string, v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warn(v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warnf(format string, v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatal(v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatalf(format string, v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Flush() { + if l.level > DebugLevel { + return + } + var beforeStr, afterStr string + for _, key := range l.definedKeys { + if val, ok := l.data[key]; ok { + if key == "time" { + beforeStr = val.(string) + continue + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + beforeStr = beforeStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + beforeStr = beforeStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + beforeStr = beforeStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Printf("val for %s unknown type!!!", key)) + + } + } + } + for key, val := range l.data { + if exist, _ := inArray(key, l.definedKeys); !exist { + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + afterStr = afterStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + afterStr = afterStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + afterStr = afterStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Sprintf("val for %s unknown type!!!", key)) + } + } + } + + line := strings.TrimSpace(beforeStr) + " " + strings.TrimSpace(afterStr) + "\r\n" + filename := fmt.Sprintf("%s.DEBUG", l.fileName) + WriteFile(filename, line) +} + +func WriteFile(filename, line string) { + TimeStamp := time.Now() + str := filename + "." + TimeStamp.Format("2006-01-02") + logf, err := os.OpenFile(str, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + if err != nil { + log.Fatal("open filename error:", err.Error()) + } + defer logf.Close() + if _, err := io.WriteString(logf, line); err != nil { + log.Fatal("write line error:", err.Error()) + } +} + +func inArray(val interface{}, array interface{}) (exists bool, index int) { + exists = false + index = -1 + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + index = i + exists = true + return + } + } + } + return +} diff --git a/oob-log-agent/build.sh b/oob-log-agent/build.sh new file mode 100644 index 0000000..e076b59 --- /dev/null +++ b/oob-log-agent/build.sh @@ -0,0 +1,112 @@ +#!/bin/bash +############################################################################### +#编译脚本的原理是将编译结果放到output目录中,这个样例模版提供一个产生 +#一个最基本golang运行程序包的编译脚本,对于特殊的需求请酌情考虑 +# +#1、该脚本支持参数化,参数将传入build_package函数(内容为最终执行的编译命令) +# ,用$1,$2....表示,第1,2...个参数 +#2、部署需要启动程序,所以需要提供control文件放在当前目录中,用于启动和 +# 监控程序状态 + +###############用户修改部分################ +readonly PACKAGE_BIN_NAME=oob-log-agent #定义产出的运行程序名,必填项 +readonly CONF_DIR_NAME="conf" #定义配置文件目录,此路径为相对路径,可选项 +readonly OTHERS_DIR_NAME="" #定义其它文件目录,多个目录以空格区分,此路径为相对路径,可选项 +#最终的抽包路径为$OUTPUT +########################################### + +if [[ "${PACKAGE_BIN_NAME}" == "" ]];then + echo "Please set "PACKAGE_BIN_NAME" value" + exit 1 +fi + +function set_work_dir +{ + readonly OUTPUT=$(pwd)/output + readonly WORKSPACE_DIR=$(pwd) +} + +#清理编译构建目录操作 +function clean_before_build +{ + cd ${WORKSPACE_DIR} + rm -rf bin pkg + rm -rf ${OUTPUT} +} + +#初始化编译环境 +#function prepare_package() + +#实际的编译命令 +#这个函数中可使用$1,$2...获取第1,2...个参数 +function build_package() +{ + cd ${WORKSPACE_DIR} + # export GOPATH=$(pwd) + go clean + go build -v -gcflags="-N -l" -o ${PACKAGE_BIN_NAME} ${WORKSPACE_DIR} || return 1 +} + +#建立最终发布的目录 +function build_dir +{ + mkdir -p ${OUTPUT}/bin || return 1 +} + +function dir_not_empty() +{ + if [[ ! -d $1 ]];then + return 1 + fi + if [[ $(ls $1|wc -l) -eq 0 ]];then + return 1 + fi + return 0 +} + +#拷贝编译结果到发布的目录 +function copy_result +{ + cd ${WORKSPACE_DIR} + cp -r ${PACKAGE_BIN_NAME} ${OUTPUT}/bin/ || return 1 + cp -r control ${OUTPUT}/bin || return 1 + dir_not_empty ${WORKSPACE_DIR}/${CONF_DIR_NAME} && mkdir -p ${OUTPUT}/${CONF_DIR_NAME};cp -rf ./${CONF_DIR_NAME}/* ${OUTPUT}/${CONF_DIR_NAME}/ + test -z "$OTHERS_DIR_NAME" || cp -rf $OTHERS_DIR_NAME ${OUTPUT}/ + return 0 +} + +#执行 +function main() +{ + cd $(dirname $0) + set_work_dir + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Cleaning...' + clean_before_build || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Clean completed' + echo + + # echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'preparng...' + # prepare_package || exit 1 + # echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'prepare completed' + # echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Building...' + build_package $@ || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Build completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Making dir...' + build_dir || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Make completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy result to publish dir...' + copy_result || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy completed' + echo + + exit 0 +} + +main $@ \ No newline at end of file diff --git a/oob-log-agent/conf/.cmd b/oob-log-agent/conf/.cmd new file mode 100644 index 0000000..2165a39 --- /dev/null +++ b/oob-log-agent/conf/.cmd @@ -0,0 +1 @@ +rm -rf agent.d agent-log-ark.xml alert.d alert-log-ark.xml cps.d diff --git a/oob-log-agent/conf/agent-config-test.ini b/oob-log-agent/conf/agent-config-test.ini new file mode 100644 index 0000000..2b974e4 --- /dev/null +++ b/oob-log-agent/conf/agent-config-test.ini @@ -0,0 +1,7 @@ +[test] + + + +bmp_redis_host=${BMP_REDIS_HOST||10.226.192.72} +bmp_redis_port=${BMP_REDIS_PORT||16379} +bmp_redis_password=${BMP_REDIS_PASSWORD||LE&oN$9wHB} diff --git a/oob-log-agent/conf/agent-config.ini b/oob-log-agent/conf/agent-config.ini new file mode 100644 index 0000000..e4b490c --- /dev/null +++ b/oob-log-agent/conf/agent-config.ini @@ -0,0 +1,37 @@ +appname = oob-log-agent +runmode = "${BMP_OOB_LOG_AGENT_RUNMODE||test}" +app.idc = "${BMP_IDC||idc-vm4xsulx1k2d9z4xkctrttig02zl}" + + + +bmp_redis_host=${BMP_REDIS_HOST} +bmp_redis_port=${BMP_REDIS_PORT} +bmp_redis_password=${BMP_REDIS_PASSWORD} +bmp_redis_db=${BMP_REDIS_DB||1} +bmp_redis_namespace=${BMP_REDIS_DB||BMP:OOB:AGENT} + +app.goroutine-num = 200 + +app.log-level = 7 +app.agent-log-file = "/var/log/bmp/bmp-oob-agent/bmp-log-agent.log" + +oob.racadm-path = "/opt/dell/srvadmin/sbin/racadm" +oob.ipmi-path = "/usr/sbin/ipmitool" +oob.error-alert-count = 3 +oob.error-alert-times = 3 + +job.check-ooblog-cron = "0 */10 * * * *" + + +# log +log.level=DEBUG +log.max.history=10 +log.path=/var/log/bmp/bmp-oob-agent + +# 本地调试的话,把下面的注释打开,读取本地配置文件 +include "agent-config-test.ini" + + + + + diff --git a/oob-log-agent/control b/oob-log-agent/control new file mode 100644 index 0000000..a678571 --- /dev/null +++ b/oob-log-agent/control @@ -0,0 +1,130 @@ +#!/bin/bash +set -x +cd "$(dirname $0)"/.. +BASE_DIR=`pwd` +if [ -f default_env.sh ];then + source default_env.sh +fi + +PROC_NAME=oob-log-agent # 进程名 一般就是二进制的名字java类程序一般就是java +CONF_NAME=agent-config.ini +# PROC_PORT=9001 # 程序占用的端口,建议写,程序不占用端口的话只用ps来判断进程是否启动,机器上有同名程序是可能有问题 +WAIT_TIME=60 # 执行START_COMMAND后到程序能完全启动listen端口需要花的时间 + +USER=jdcloud +app_dir=/home/$USER/$PROC_NAME +mkdir -p $app_dir/log + + +START_COMMAND="$app_dir/bin/$PROC_NAME -c $app_dir/conf/$CONF_NAME" #在output目录下启动你程序的命令 + + +help(){ + echo "${0} " + exit 1 +} + +checkhealth(){ + if [[ -n "$PROC_PORT" ]] ; then + PORT_PROC=$(/usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d |awk '{print $NF}' |grep -oP '".*"' |sed "s/\"//g" |uniq) + if [ X"$PORT_PROC" = X"$PROC_NAME" ] ; then + echo "running" + return 0 + fi + echo "not running" + return 1 + else + ps -eo comm,pid |grep -P "^$PROC_NAME" + if [ "$?" = 0 ] ; then + echo "running" + return 0 + fi + echo "not running" + return 1 + fi +} + + + +start(){ + checkhealth + if [ $? = 0 ]; then + echo "[WARN] $PROC_NAME is aleady running!" + return 0 + fi + + + + [ -d "$app_dir" ] && cd $app_dir && rm -rf `ls ${app_dir} | grep -v log` + cp -r $BASE_DIR/* ${app_dir}/ + chown -R $USER:$USER ${app_dir} + su $USER -c "nohup $START_COMMAND > ${app_dir}/log/bmp-log-agent.log 2>&1 &" + + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ $? = 0 ]; then + echo "Start $PROC_NAME success" + return 0 + fi + done + echo "[ERROR] Start $PROC_NAME failed" + return 1 +} + +stop(){ + if [[ -n "$PROC_PORT" ]] ; then + PROC_ID=$( /usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d | awk '{print $NF}' | grep -oP ',.*,' | grep -oP "\d+" | uniq ) + else + PROC_ID=$(ps -eo comm,pid | grep "^$PROC_NAME" |awk '{print $2}') + fi + + if [[ -z "$PROC_ID" ]] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + + checkhealth + if [ "$?" != "0" ] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + kill $PROC_ID + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + done + + kill -9 $PROC_ID + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + + echo "[ERROR] Stop $PROC_NAME failed" + return 1 +} + +case "${1}" in + start) + start + ;; + stop) + stop + ;; + status|health|checkhealth) + checkhealth + ;; + restart) + stop && start + ;; + *) + help + ;; +esac diff --git a/oob-log-agent/docs/releases/v1.5.4-release.md b/oob-log-agent/docs/releases/v1.5.4-release.md new file mode 100644 index 0000000..50769c4 --- /dev/null +++ b/oob-log-agent/docs/releases/v1.5.4-release.md @@ -0,0 +1,15 @@ +## 上线分支 +v1.5.4 + +## 上线功能点 +- 1,fix dell linux机型系统事件日志无法带外报警的问题 + - LogCollectTime 初始化时间fix + - racadm命令获取的系统事件日志适配fix + +## 验证 +#### 验证环境 +带外cps-oob预发环境 10.208.12.194 +#### 验证方法 +找一台dell机器,插拔一块硬盘: +- 从带外登录验证是否有系统事件日志 +- 是否收到cps-oob带外日志告警邮件 diff --git a/oob-log-agent/go.mod b/oob-log-agent/go.mod new file mode 100644 index 0000000..af57934 --- /dev/null +++ b/oob-log-agent/go.mod @@ -0,0 +1,36 @@ +module coding.jd.com/aidc-bmp/oob-log-agent + +go 1.17 + +require ( + coding.jd.com/aidc-bmp/bmp_log v0.0.0-00010101000000-000000000000 + github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394 + github.com/beego/beego/v2 v2.0.1 + github.com/go-redis/redis v6.15.9+incompatible + golang.org/x/crypto v0.14.0 +) + +require ( + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/golang/protobuf v1.5.3 // indirect + github.com/hashicorp/golang-lru v0.5.4 // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/prometheus/client_golang v1.16.0 // indirect + github.com/prometheus/client_model v0.3.0 // indirect + github.com/prometheus/common v0.42.0 // indirect + github.com/prometheus/procfs v0.10.1 // indirect + github.com/rogpeppe/go-internal v1.11.0 // indirect + github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18 // indirect + golang.org/x/mod v0.9.0 // indirect + golang.org/x/net v0.10.0 // indirect + golang.org/x/sys v0.13.0 // indirect + golang.org/x/text v0.13.0 // indirect + golang.org/x/tools v0.6.0 // indirect + google.golang.org/protobuf v1.30.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect +) + +replace coding.jd.com/aidc-bmp/bmp_log => ./bmp_vendor/bmp_log diff --git a/oob-log-agent/go.sum b/oob-log-agent/go.sum new file mode 100644 index 0000000..67e2c95 --- /dev/null +++ b/oob-log-agent/go.sum @@ -0,0 +1,303 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= +github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk= +github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394 h1:OYA+5W64v3OgClL+IrOD63t4i/RW7RqrAVl9LTZ9UqQ= +github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394/go.mod h1:Q8n74mJTIgjX4RBBcHnJ05h//6/k6foqmgE45jTQtxg= +github.com/beego/beego/v2 v2.0.1 h1:07a7Z0Ok5vbqyqh+q53sDPl9LdhKh0ZDy3gbyGrhFnE= +github.com/beego/beego/v2 v2.0.1/go.mod h1:8zyHi1FnWO1mZLwTn62aKRIZF/aIKvkCBB2JYs+eqQI= +github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ= +github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60= +github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= +github.com/coreos/etcd v3.3.25+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U= +github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= +github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= +github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= +github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk= +github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis v6.15.9+incompatible h1:K0pv1D7EQUjfyoMql+r/jZqCLizCGKFlFgcHWWmHQjg= +github.com/go-redis/redis v6.15.9+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= +github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDuKuq+uX4v1fulaMbA/7ZLLhjc85h7chZGBCQ= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= +github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= +github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.0 h1:Iw5WCbBcaAAd0fpRb1c9r5YCylv4XDoCSigm1zLevwU= +github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= +github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.7.0/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_golang v1.16.0 h1:yk/hx9hDbrGHovbci4BY+pRMfSuuat626eFsHb7tmT8= +github.com/prometheus/client_golang v1.16.0/go.mod h1:Zsulrv/L9oM40tJ7T815tM89lFEugiJ9HzIqaAx4LKc= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4= +github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/common v0.42.0 h1:EKsfXEYo4JpWMHH5cg+KOUWeuJSov1Id8zGR8eeI1YM= +github.com/prometheus/common v0.42.0/go.mod h1:xBwqVerjNdUDjgODMpudtOMwlOwf2SaTr1yjz4b7Zbc= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/prometheus/procfs v0.10.1 h1:kYK1Va/YMlutzCGazswoHKo//tZVlFpKYh+PymziUAg= +github.com/prometheus/procfs v0.10.1/go.mod h1:nwNm2aOCAYw8uTR/9bWRREkZFxAUcWzPHWJq+XBB/FM= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= +github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= +github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18 h1:DAYUYH5869yV94zvCES9F51oYtN5oGlwjxJJz7ZCnik= +github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= +github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= +github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s= +github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= +github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= +github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= +go.etcd.io/etcd v3.3.25+incompatible/go.mod h1:yaeTdrJi5lOmYerz05bd8+V7KubZs8YSFZfzsF9A6aI= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.9.0 h1:KENHtAZL2y3NLMYZeHY9DW8HW8V+kQyJsY/V9JlKvCs= +golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.2.0 h1:PUR+T4wwASmuSTYdKjYHI5TD22Wy5ogLU5qZCOLxBrI= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.13.0 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= +google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.5/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= diff --git a/oob-log-agent/main.go b/oob-log-agent/main.go new file mode 100644 index 0000000..e8d3dd7 --- /dev/null +++ b/oob-log-agent/main.go @@ -0,0 +1,89 @@ +package main + +import ( + "flag" + "fmt" + "os" + + "coding.jd.com/aidc-bmp/oob-log-agent/util" + + "coding.jd.com/aidc-bmp/oob-log-agent/scheduler" + + "github.com/beego/beego/v2/adapter/toolbox" + "github.com/beego/beego/v2/core/logs" + beego "github.com/beego/beego/v2/server/web" +) + +const ( + defaultConfigFile = "conf/agent-config.ini" +) + +var configFile = flag.String("c", defaultConfigFile, "specify config file") +var helpFlag = flag.Bool("h", false, "print help") + +func init() { + flag.Usage = usage +} + +func main() { + // parse flag + flag.Parse() + + if *helpFlag { + flag.Usage() + os.Exit(0) + } + + // initial Config From file + beego.LoadAppConfig("ini", *configFile) + + // init log + logConfig := "{\"filename\":\"" + beego.AppConfig.DefaultString("app.agent-log-file", "/var/log/bmp/bmp-oob-agent/bmp-log-agent.log") + "\",\"level\":" + beego.AppConfig.DefaultString("app.log-level", "7") + "}" + logs.SetLogger(logs.AdapterConsole, logConfig) + logs.EnableFuncCallDepth(true) + + logs.Info("========CPS-OOB-AGENT Start========") + defer logs.Info("========CPS-OOB-AGENT Finish========") + + // initial redis + rNamespace, _ := beego.AppConfig.String("bmp_redis_namespace") + rIdc, _ := beego.AppConfig.String("app.idc") + rhost, _ := beego.AppConfig.String("bmp_redis_host") + rport, _ := beego.AppConfig.String("bmp_redis_port") + rAddr := fmt.Sprintf("%s:%s", rhost, rport) + rPasswd, _ := beego.AppConfig.String("bmp_redis_password") + rDb, _ := beego.AppConfig.Int("bmp_redis_db") + + if err := util.InitRedis(rNamespace, rIdc, rAddr, rPasswd, rDb); err != nil { + logs.Warn("Redis Connect Error, Ping result : %s", err.Error()) + os.Exit(0) + } + defer util.RedisUtil.Close() + + // 每10分钟执行一次带外日志检测任务 + oobCheckTral, _ := beego.AppConfig.String("job.check-ooblog-cron") + c1 := toolbox.NewTask("oobCheck", oobCheckTral, scheduler.CheckOoblog) + err := c1.Run() + if err != nil { + logs.Warn("CheckOoblog() Error : " + err.Error()) + // logs.Error("CheckOoblog() Error : " + err.Error()) + } + toolbox.AddTask("oobCheck", c1) + + toolbox.StartTask() + defer toolbox.StopTask() + + //是否需要select?? + select {} + +} + +func usage() { + + fmt.Printf(`Usage: oob-log-agent [-c configfile] +Options: + +`) + flag.PrintDefaults() + +} diff --git a/oob-log-agent/object/CPSError.go b/oob-log-agent/object/CPSError.go new file mode 100644 index 0000000..92b7f89 --- /dev/null +++ b/oob-log-agent/object/CPSError.go @@ -0,0 +1,32 @@ +package object + +// +const ( + MonitorSuccess = iota + MonitorOOBError + MonitorUnimplement + MonitorUnknownCPS + MonitorCPSiLOBlank + MonitorCPSFiltered + MonitorOtherError +) + +// NewMonitorCode new a ParseCode +func NewMonitorCode(code int, text string) error { + return &MonitorCode{code, text} +} + +// MonitorCode Parser process error +type MonitorCode struct { + c int + s string +} + +func (e *MonitorCode) Error() string { + return e.s +} + +// Code return result code +func (e *MonitorCode) Code() int { + return e.c +} diff --git a/oob-log-agent/object/CPSObject.go b/oob-log-agent/object/CPSObject.go new file mode 100644 index 0000000..714dd73 --- /dev/null +++ b/oob-log-agent/object/CPSObject.go @@ -0,0 +1,161 @@ +package object + +import ( + "encoding/json" + "fmt" +) + +type CMDBObjectJD struct { + Asset string `json:"asset,omitempty"` + Cabinet string `json:"cabinet,omitempty"` + Configure string `json:"configure,omitempty"` + Cost string `json:"cost,omitempty"` + CreatedAt string `json:"created_at,omitempty"` + Department string `json:"department,omitempty"` + DeviceName string `json:"device_name,omitempty"` + DeviceSn string `json:"device_sn,omitempty"` + EthGateway string `json:"eth_gateway,omitempty"` + EthIP string `json:"eth_ip,omitempty"` + EthMac string `json:"eth_mac,omitempty"` + EthMask string `json:"eth_mask,omitempty"` + EthSwitchIP string `json:"eth_switch_ip,omitempty"` + EthSwitchPort string `json:"eth_switch_port,omitempty"` + Idc string `json:"idc,omitempty"` + IdcID int `json:"idc_id,omitempty"` + IloGateway string `json:"ilo_gateway"` + IloIP string `json:"ilo_ip"` + IloMac string `json:"ilo_mac"` + IloMask string `json:"ilo_mask"` + IloSwitchIP string `json:"ilo_switch_ip"` + IloSwitchPort string `json:"ilo_switch_port"` + MaintenanceEnd string `json:"maintenance_end"` + MaintenanceStart string `json:"maintenance_start"` + MaintenanceStatus int `json:"maintenance_status"` + Manufacturer string `json:"manufacturer"` + Model string `json:"model"` + Monitor string `json:"monitor"` + Nodeid int `json:"nodeid"` + OpAssetNumber string `json:"op_asset_number"` + OpGroup []string `json:"op_group"` + Operation string `json:"operation"` + OrganizationCode string `json:"organization_code"` + OsKernel string `json:"os_kernel"` + OsVersion string `json:"os_version"` + Package string `json:"package"` + Sn string `json:"sn"` + Type string `json:"type"` + UPosition string `json:"u_position"` + UpDown string `json:"up_down"` +} + +type CMDBObjectJDCloud struct { + Cabinet struct { + Code string `json:"code,omitempty"` + ID int `json:"id,omitempty"` + IdcID int `json:"idc_id,omitempty"` + } `json:"cabinet"` + DeviceSn string `json:"device_sn,omitempty"` + Eth struct { + DeviceSn string `json:"device_sn,omitempty"` + Gateway string `json:"gateway,omitempty"` + IP string `json:"ip,omitempty"` + Mac string `json:"mac,omitempty"` + Mask string `json:"mask,omitempty"` + SwitchIP string `json:"switch_ip,omitempty"` + SwitchPort string `json:"switch_port,omitempty"` + Type string `json:"type,omitempty"` + } `json:"eth,omitempty"` + Idc struct { + CnName string `json:"cn_name,omitempty"` + ID int `json:"id,omitempty"` + } `json:"idc,omitempty"` + Ilo struct { + DeviceSn string `json:"device_sn,omitempty"` + Gateway string `json:"gateway,omitempty"` + IP string `json:"ip,omitempty"` + Mac string `json:"mac,omitempty"` + Mask string `json:"mask,omitempty"` + SwitchIP string `json:"switch_ip,omitempty"` + SwitchPort string `json:"switch_port,omitempty"` + Type string `json:"type,omitempty"` + } `json:"ilo,omitempty"` + IloGateway string `json:"ilo_gateway,omitempty"` + IloIP string `json:"ilo_ip,omitempty"` + IloMac string `json:"ilo_mac,omitempty"` + IloMask string `json:"ilo_mask,omitempty"` + IloSwitchIP string `json:"ilo_switch_ip,omitempty"` + IloSwitchPort string `json:"ilo_switch_port,omitempty"` + Manufacturer string `json:"manufacturer,omitempty"` + Model string `json:"model,omitempty"` + OpGroup []struct { + ID int `json:"id,omitempty"` + Name string `json:"name,omitempty"` + } `json:"op_group,omitempty"` + Organization struct { + Fullname string `json:"fullname,omitempty"` + ID int `json:"id,omitempty"` + OrganizationCode string `json:"organization_code,omitempty"` + } `json:"organization,omitempty"` + Package string `json:"package,omitempty"` + Pub struct { + DeviceSn string `json:"device_sn,omitempty"` + Gateway string `json:"gateway,omitempty"` + IP string `json:"ip,omitempty"` + Mac string `json:"mac,omitempty"` + Mask string `json:"mask,omitempty"` + SwitchIP string `json:"switch_ip,omitempty"` + SwitchPort string `json:"switch_port,omitempty"` + Type string `json:"type,omitempty"` + } `json:"pub,omitempty"` + UEnd int `json:"u_end,omitempty"` + UStart int `json:"u_start,omitempty"` +} + +// CPSRecord CPS information +type CPSRecord struct { + Clazz string `json:"clazz,omitempty"` + SN string `json:"sn,omitempty"` + Region string `json:"region,omitempty"` + AZ string `json:"az,omitempty"` + InstanceID string `json:"instance_id,omitempty"` + Pin string `json:"pin,omitempty"` + Status string `json:"instance_status,omitempty"` + IloIP string `json:"ilo_ip,omitempty"` + Brand string `json:"branc,omitempty"` + Model string `json:"model,omitempty"` + Package string `json:"package,omitempty"` + Cabinet string `json:"cabinet,omitempty"` + IsSale bool `json:"is_sale"` + UPosition string `json:"u_position,omitempty"` + IloUser string `json:"ilo_user"` + IloPass string `json:"ilo_pass"` +} + +// CPSObject store CPS list per IDC ID +type CPSObject struct { + Region string `json:"region,omitempty"` + AZ string `json:"az,omitempty"` + CPSs []CPSRecord `json:"cps,omitempty"` +} + +//JSON return JSON string +func (c CPSObject) JSON() (string, error) { + + json, err := json.Marshal(c.CPSs) + if err != nil { + fmt.Println("CPSObject to JSON error:" + err.Error()) + return "", err + } + return string(json), nil +} + +// JSON return JSON string +func (c CPSRecord) JSON() (string, error) { + + json, err := json.Marshal(c) + if err != nil { + fmt.Println("CPSRecord to JSON error:" + err.Error()) + return "", err + } + return string(json), nil +} diff --git a/oob-log-agent/object/CPUObject.go b/oob-log-agent/object/CPUObject.go new file mode 100644 index 0000000..d0b1d17 --- /dev/null +++ b/oob-log-agent/object/CPUObject.go @@ -0,0 +1,36 @@ +package object + +import ( + "encoding/json" + "fmt" +) + +// CPURecord CPU record +type CPURecord struct { + FQDD string // CPU.Socket.1 + DeviceType string // CPU + NumberOfProcessorCores string // 6 + Model string // Intel(R) Xeon(R) CPU E5-2620 0 @ 2.00GHz + CurrentClockSpeed string // 2000 MHz + CPUStatus string // Disk 0 in Backplane 1 of Integrated RAID Controller 1 + PrimaryStatus string // OK + +} + +// CPUObject , the type of CPU information from Out-of-Band +type CPUObject struct { + Status bool `json:"status,omitempty"` + Count int `json:"count,omitempty"` + CPUs []CPURecord `json:"detail,omitempty"` +} + +//JSON return JSON string +func (c CPUObject) JSON() (string, error) { + + json, err := json.Marshal(c.CPUs) + if err != nil { + fmt.Println("CPUObject to JSON error:" + err.Error()) + return "", err + } + return string(json), nil +} diff --git a/oob-log-agent/object/Const.go b/oob-log-agent/object/Const.go new file mode 100644 index 0000000..3f66cb3 --- /dev/null +++ b/oob-log-agent/object/Const.go @@ -0,0 +1,42 @@ +package object + +const ( + // ConfigKey store configration, each field store different config + ConfigKey string = "Config" + + // FilterKey store filters, each field store different manufacurer filter. + FilterKey string = "Filter" + + // LogChannel log alert pubsub channel namespace + LogChannel string = "Logs" + + // OOBErrorChannel OOB access error pubsub channel namespace + OOBErrorChannel string = "OOBError" + + // PDisksField redis store field name + PDisksField string = "PDisks" + + // CPUsField redis store field name + CPUsField string = "CPUs" + + // MemsField redis store field name + MemsField string = "Mems" + + // NicsField redis store field name + NicsField string = "Nics" + + // CodeField code store monitor result + CodeField string = "Code" + + // ErrorCountField count for oob access error + ErrorCountField string = "OOBErrorCount" + + // MessageField code store monitor result message + MessageField string = "Message" + + // LogSelInfoField store last ipmi system event log info + LogSelInfoField string = "LogSelInfo" + + //LastCollectOOBTimeField 最后一次oob收集的时间,是目标机器的oob带外时间,不是目标机器的系统时间,也不是agent服务器的时间 + LastCollectOOBTimeField string = "LastCollectOobTime" +) diff --git a/oob-log-agent/object/FRUObject.go b/oob-log-agent/object/FRUObject.go new file mode 100644 index 0000000..803cb1f --- /dev/null +++ b/oob-log-agent/object/FRUObject.go @@ -0,0 +1,24 @@ +package object + +import ( + "encoding/json" + "fmt" +) + +// FRUObject type of IPMI FRU Information +type FRUObject struct { + Brand string + SN string + Model string +} + +// JSON return json string +func (l FRUObject) JSON() (string, error) { + + json, err := json.Marshal(l) + if err != nil { + fmt.Println("FRUObject to JSON error:" + err.Error()) + return "", err + } + return string(json), nil +} diff --git a/oob-log-agent/object/LogObject.go b/oob-log-agent/object/LogObject.go new file mode 100644 index 0000000..6897f4f --- /dev/null +++ b/oob-log-agent/object/LogObject.go @@ -0,0 +1,7 @@ +package object + +// LogObject type of Event log from dell lifecyclelog or IPMI +type LogObject struct { + SeqNumber string //664 + Messages []string +} diff --git a/oob-log-agent/object/MemObject.go b/oob-log-agent/object/MemObject.go new file mode 100644 index 0000000..de19ed2 --- /dev/null +++ b/oob-log-agent/object/MemObject.go @@ -0,0 +1,39 @@ +package object + +import ( + "encoding/json" + "fmt" +) + +// MemRecord Memory record +type MemRecord struct { + FQDD string // DIMM.Socket.A1 + DeviceType string // Memory + MemoryType string // DDR-3 + SerialNumber string // 134799E0 + Brand string // Samsung + Speed string // 1333 MHz + CurrentOperatingSpeed string // 1333 MHz + Rank string // Double Rank + Size string // 32768 MB + PrimaryStatus string // OK + +} + +// MemObject , the type of Memory information from Out-of-Band +type MemObject struct { + Status bool `json:"status,omitempty"` + Count int `json:"count,omitempty"` + Mems []MemRecord `json:"detail,omitempty"` +} + +//JSON return JSON string +func (c MemObject) JSON() (string, error) { + + json, err := json.Marshal(c.Mems) + if err != nil { + fmt.Println("MemObject to JSON error:" + err.Error()) + return "", err + } + return string(json), nil +} diff --git a/oob-log-agent/object/NicObject.go b/oob-log-agent/object/NicObject.go new file mode 100644 index 0000000..c12720a --- /dev/null +++ b/oob-log-agent/object/NicObject.go @@ -0,0 +1,38 @@ +package object + +import ( + "encoding/json" + "fmt" +) + +// NicRecord NIC record +type NicRecord struct { + FQDD string // NIC.Integrated.1-1-1 + DeviceType string // NIC + PermanentMACAddress string // 24:6E:96:B0:FA:8E + CurrentMACAddress string // 24:6E:96:B0:FA:8E + ProductName string // Intel(R) Ethernet 10G 4P X520/I350 rNDC - 24:6E:96:03:43:E0 + DeviceDescription string // Integrated NIC 1 Port 1 Partition 1 + LinkSpeed string // 10 Gbps + LinkDuplex string // Full Duplex + LinkStatus string // OK + +} + +// NicObject , the type of NIC information from Out-of-Band +type NicObject struct { + Status bool `json:"status,omitempty"` + Count int `json:"count,omitempty"` + Nics []NicRecord `json:"detail,omitempty"` +} + +//JSON return JSON string +func (c NicObject) JSON() (string, error) { + + json, err := json.Marshal(c.Nics) + if err != nil { + fmt.Println("NicObject to JSON error:" + err.Error()) + return "", err + } + return string(json), nil +} diff --git a/oob-log-agent/object/Object.go b/oob-log-agent/object/Object.go new file mode 100644 index 0000000..8736824 --- /dev/null +++ b/oob-log-agent/object/Object.go @@ -0,0 +1,6 @@ +package object + +// Object ,the base interface for different object +type Object interface { + JSON() (string, error) +} diff --git a/oob-log-agent/object/PhysicalDiskObject.go b/oob-log-agent/object/PhysicalDiskObject.go new file mode 100644 index 0000000..a9277bb --- /dev/null +++ b/oob-log-agent/object/PhysicalDiskObject.go @@ -0,0 +1,48 @@ +package object + +import ( + "encoding/json" + "fmt" +) + +// PhysicalDiskRecord Physical Disk record +type PhysicalDiskRecord struct { + FQDD string // Disk.Bay.0:Enclosure.Internal.0-1:RAID.Integrated.1-1 + DeviceType string // PhysicalDisk + SerialNumber string // WXU1E13TLDN2 + ManufacturingYear string // 2013 + ManufacturingWeek string // 23 + ManufacturingDay string // 7 + Manufacturer string // WD + Model string // WD3001BKHG + Slot string // 0 + DeviceDescription string // Disk 0 in Backplane 1 of Integrated RAID Controller 1 + UsedSizeInBytes string // 299439751168 Bytes + FreeSizeInBytes string // 0 Bytes + SizeInBytes string // 299439751168 Bytes + PrimaryStatus string // OK + RollupStatus string // OK + RaidStatus string // Online + HotSpareStatus string // No + MediaType string // HDD + MaxCapableSpeed string // 6Gbs + DriveFormFactor string // 2.5 inch +} + +// PhysicalDiskObject , the type of Physical Disk information from Out-of-Band +type PhysicalDiskObject struct { + Status bool `json:"status,omitempty"` + Count int `json:"count,omitempty"` + PDisks []PhysicalDiskRecord `json:"detail,omitempty"` +} + +//JSON return JSON string +func (o PhysicalDiskObject) JSON() (string, error) { + + json, err := json.Marshal(o.PDisks) + if err != nil { + fmt.Println("PhysicalDiskObject to JSON error:" + err.Error()) + return "", err + } + return string(json), nil +} diff --git a/oob-log-agent/oob-log-agent.Dockerfile b/oob-log-agent/oob-log-agent.Dockerfile new file mode 100644 index 0000000..492fb15 --- /dev/null +++ b/oob-log-agent/oob-log-agent.Dockerfile @@ -0,0 +1,13 @@ +FROM golang:1.17-alpine AS builder +ENV GOPROXY https://goproxy.cn +WORKDIR /usr/src/bmp-oob-agent +COPY . . +RUN go build -o /tmp/bmp-oob-agent . + +FROM alpine:3.16 +RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories \ + && apk add ipmitool +WORKDIR /home/bmp/bmp-oob-agent +COPY --from=builder /tmp/bmp-oob-agent . +COPY ./conf ./conf +CMD ["./bmp-oob-agent"] diff --git a/oob-log-agent/parser/DellParser.go b/oob-log-agent/parser/DellParser.go new file mode 100644 index 0000000..d5b1d83 --- /dev/null +++ b/oob-log-agent/parser/DellParser.go @@ -0,0 +1,6 @@ +package parser + +// DellParser implements Parser +type DellParser struct { + BaseParser +} diff --git a/oob-log-agent/parser/FoxconnParser.go b/oob-log-agent/parser/FoxconnParser.go new file mode 100644 index 0000000..2b7265c --- /dev/null +++ b/oob-log-agent/parser/FoxconnParser.go @@ -0,0 +1,6 @@ +package parser + +// FoxconnParser implements Parser +type FoxconnParser struct { + BaseParser +} diff --git a/oob-log-agent/parser/H3CParser.go b/oob-log-agent/parser/H3CParser.go new file mode 100644 index 0000000..c51782e --- /dev/null +++ b/oob-log-agent/parser/H3CParser.go @@ -0,0 +1,6 @@ +package parser + +// H3CParser implements Parser +type H3CParser struct { + BaseParser +} diff --git a/oob-log-agent/parser/HuaweiParser.go b/oob-log-agent/parser/HuaweiParser.go new file mode 100644 index 0000000..db30247 --- /dev/null +++ b/oob-log-agent/parser/HuaweiParser.go @@ -0,0 +1,6 @@ +package parser + +// HuaweiParser implements Parser +type HuaweiParser struct { + BaseParser +} diff --git a/oob-log-agent/parser/IBMParser.go b/oob-log-agent/parser/IBMParser.go new file mode 100644 index 0000000..782e778 --- /dev/null +++ b/oob-log-agent/parser/IBMParser.go @@ -0,0 +1,6 @@ +package parser + +// IBMParser implements Parser +type IBMParser struct { + BaseParser +} diff --git a/oob-log-agent/parser/InspurParser.go b/oob-log-agent/parser/InspurParser.go new file mode 100644 index 0000000..dff1402 --- /dev/null +++ b/oob-log-agent/parser/InspurParser.go @@ -0,0 +1,6 @@ +package parser + +// InspurParser implements Parser +type InspurParser struct { + BaseParser +} diff --git a/oob-log-agent/parser/JDcloudParser.go b/oob-log-agent/parser/JDcloudParser.go new file mode 100644 index 0000000..4e43cf0 --- /dev/null +++ b/oob-log-agent/parser/JDcloudParser.go @@ -0,0 +1,6 @@ +package parser + +// JDcloudParser implements Parser +type JDcloudParser struct { + BaseParser +} diff --git a/oob-log-agent/parser/LenovoParser.go b/oob-log-agent/parser/LenovoParser.go new file mode 100644 index 0000000..bcea602 --- /dev/null +++ b/oob-log-agent/parser/LenovoParser.go @@ -0,0 +1,6 @@ +package parser + +// LenovoParser implements Parser +type LenovoParser struct { + BaseParser +} diff --git a/oob-log-agent/parser/Parser.go b/oob-log-agent/parser/Parser.go new file mode 100644 index 0000000..b286730 --- /dev/null +++ b/oob-log-agent/parser/Parser.go @@ -0,0 +1,294 @@ +package parser + +import ( + "encoding/json" + "fmt" + "runtime" + "strings" + "time" + + "coding.jd.com/aidc-bmp/oob-log-agent/object" + "coding.jd.com/aidc-bmp/oob-log-agent/util" + + log "coding.jd.com/aidc-bmp/bmp_log" + "github.com/axgle/mahonia" + "github.com/beego/beego/v2/core/logs" + beego "github.com/beego/beego/v2/server/web" +) + +const LastCollectTimeKey = "lastCollecttTime" +const timeFormat = "01/02/2006 15:04:05" + +// Parser interface to collect and parse text +type Parser interface { + ParseFRU(*log.Logger) error + + ParseLog(*log.Logger) error +} + +func fruCmd() string { + ipmi, _ := beego.AppConfig.String("oob.ipmi-path") + return ipmi + " -I lanplus -H %s -U %s -P %s fru print 0" +} + +func selListCmd() string { + ipmi, _ := beego.AppConfig.String("oob.ipmi-path") + return ipmi + " -I lanplus -H %s -U %s -P %s sel list " +} + +// BaseParser Abstract Parser +type BaseParser struct { + SN string + Brand string + IloIP string + IloUser string + IloPass string +} + +func (b BaseParser) ParseFRU(logger *log.Logger) error { + logger.Infof(">>>>>>>>BaseParser.parseFRU(), sn:%s, ilo_ip:%s", b.SN, b.IloIP) + defer logger.Infof("<<<<<<< beego.AppConfig.DefaultInt("oob.error-alert-count", 3) && count <= (beego.AppConfig.DefaultInt("oob.error-alert-count", 3)+beego.AppConfig.DefaultInt("oob.error-alert-times", 3)) { + err := util.PubEventToRedis(object.OOBErrorChannel+":"+b.SN, err.Error()) + if err != nil { + logger.Warnf("%+v. PubEventToRedis Error : %s", b, err.Error()) + } + } + return err + } else { + // 带外连接成功,重置错误计数器 + if err := util.HDelObjectFromRedis(object.ErrorCountField, []string{b.SN}); err != nil { + logger.Warnf("%+v. HDelObjectFromRedis ErrorCountField Error : %s", b, err.Error()) + } + } + // logs.Debug("Collect():" + res) + + var retStr string + if runtime.GOOS == "windows" { + enc := mahonia.NewDecoder("GBK") + retStr = enc.ConvertString(res) + } else { + retStr = res + } + + var obj object.FRUObject + + lines := strings.Split(retStr, "\n") + + for _, line := range lines { + + tmp := strings.Split(line, ":") + if strings.Contains(tmp[0], "Product Manufacturer") { + obj.Brand = strings.TrimSpace(tmp[1]) + } + if strings.Contains(tmp[0], "Product Serial") { + obj.SN = strings.TrimSpace(tmp[1]) + } + if strings.Contains(tmp[0], "Product Name") { + obj.Model = strings.TrimSpace(tmp[1]) + } + } + + // 比较Manufacturer、SN,如果不同,发告警 + isDiff := false + var diffMsg string + // if !strings.EqualFold(obj.Manufacturer, b.Manufacturer) { //Manufacturer不一致 + // isDiff = true + // diffMsg = diffMsg + fmt.Sprintf("oob Manufacturer:%s", b.Manufacturer) + // } + if !strings.EqualFold(obj.SN, b.SN) { //sn不一致 + isDiff = true + diffMsg = diffMsg + fmt.Sprintf("oob SN:%s", b.SN) + } + + if isDiff { + message := fmt.Sprintf("Read FRU Different: SN = %s, Brand = %s", obj.SN, obj.Brand) + ", " + diffMsg + err := util.PubEventToRedis(object.OOBErrorChannel+":"+b.SN, message) + if err != nil { + logger.Warnf("%+v. PubEventToRedis Error : %s", b, err.Error()) + } + } + + logger.Infof("BaseParser.parseFRU():obj=%+v", obj) + + return nil + +} + +func (p BaseParser) ParseLog(logger *log.Logger) error { + + logger.Infof(">>>>>>>>BaseParser.ParseLog(), sn:%s, ilo_ip:%s", p.SN, p.IloIP) + defer logger.Infof("<<<<<<< 0 { + + msg := object.LogObject{ + SeqNumber: p.SN, + Messages: toPushMessages, + } + b, err := json.Marshal(msg) + if err != nil { + logger.Warnf("toPushMessages marshal error: %s", err.Error()) + return err + } + err = util.PubEventToRedis(object.LogChannel+":"+p.SN, string(b)) + if err != nil { + info := fmt.Sprintf("%s LogAlert PubEventToRedis ERROR, MSG: %s, ERROR:%s", p.SN, string(b), err.Error()) + logger.Warn(info) + return err + } else { + info := fmt.Sprintf("%s LogAlert PubEventToRedis Succeed, MSG: %s", p.SN, string(b)) + logger.Info(info) + } + } + saveResult(p.SN, code, message) + + return nil + +} + +func getLastCollectTime(sn string) time.Time { + res, err := util.HGetObjectFromRedis(LastCollectTimeKey, sn) + if err != nil { + logs.Warn("getLastCollectTime error, sn :", sn, err.Error()) + return time.Now().AddDate(-10, 0, 0) + } + t, err := time.Parse(timeFormat, res) + if err != nil { + logs.Warn("Parse LastCollectTime error, sn :%s, time: %s", sn, res) + return time.Now().AddDate(-10, 0, 0) + } + return t + +} + +func saveResult(key string, code int, msg string) error { + fields := map[string]interface{}{ + object.MessageField: msg, + object.CodeField: code, + } + + // 成功,重置错误计数 + if code == object.MonitorSuccess { + fields[object.ErrorCountField] = 0 + } + + err := util.HMSetObjectToRedis(key, fields) + if err != nil { + logs.Warn("Write %+v. Message error:%s", key, err.Error()) + return err + } + return nil +} + +func GetParser(logger *log.Logger, m object.CPSRecord) Parser { + logger.Infof("GetOobUserPasswd CPSRecord:%s", util.Obj2String(m)) + var oobUser, oobPasswd = util.GetOobUserPasswd(m) + + return BaseParser{SN: m.SN, IloIP: m.IloIP, IloUser: oobUser, IloPass: oobPasswd, Brand: m.Brand} + +} diff --git a/oob-log-agent/parser/SugonParser.go b/oob-log-agent/parser/SugonParser.go new file mode 100644 index 0000000..61446c6 --- /dev/null +++ b/oob-log-agent/parser/SugonParser.go @@ -0,0 +1,6 @@ +package parser + +// SugonParser implements Parser +type SugonParser struct { + BaseParser +} diff --git a/oob-log-agent/scheduler/Job.go b/oob-log-agent/scheduler/Job.go new file mode 100644 index 0000000..13f1e84 --- /dev/null +++ b/oob-log-agent/scheduler/Job.go @@ -0,0 +1,33 @@ +package scheduler + +import ( + "coding.jd.com/aidc-bmp/oob-log-agent/object" + "coding.jd.com/aidc-bmp/oob-log-agent/parser" + + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Job concrete type to execute monitor job +type Job struct { + cps object.CPSRecord +} + +// Run get CPS info +func (j Job) Run(logger *log.Logger) { + + logger.Infof(">>>>>>>> start Job.Run(), sn:%s", j.cps.SN) + defer logger.Infof(j.cps.SN, "<<<<<<< 0 { + err := RedisUtil.Del(fullKeys...).Err() + if err != nil { + return err + } + } + + return nil +} + +// HMGetObjectFromRedis Hash get objects from redis +func HMGetObjectFromRedis(key string, fields ...string) ([]interface{}, error) { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + if len(fields) <= 0 { + return nil, nil + } + + v, err := RedisUtil.HMGet(fullKey, fields...).Result() + + if err != nil { + return nil, err + } + return v, nil +} + +func HIncrObjectToRedis(key string, field string, count int) (int, error) { + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + v, err := RedisUtil.HIncrBy(fullKey, field, int64(count)).Result() + + if err != nil { + return 0, err + } + return int(v), nil +} + +func GetOobUserPasswd(cps object.CPSRecord) (string, string) { + //todo + return cps.IloUser, cps.IloPass +} diff --git a/oob-log-agent/util/execmd.go b/oob-log-agent/util/execmd.go new file mode 100644 index 0000000..6f50337 --- /dev/null +++ b/oob-log-agent/util/execmd.go @@ -0,0 +1,54 @@ +package util + +import ( + "errors" + "os/exec" + "regexp" + "strings" + "syscall" + + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// ExecCommand function to execute command +func ExecCommand(logger *log.Logger, cmdStr string, params ...string) (retStr string, ret int, err error) { + + defer func() { + r := recover() + if r != nil { + logger.Warnf("ExecCommand catch exception, error:%v, stack:%s", r, GetCurrentGoroutineStack()) + ret = -1 + err = errors.New("ExecCommand panic when exec") + } + }() + + logger.Infof("ExecCommand cmdStr:%s, param:+%v", cmdStr, params) + // check command injection + r := regexp.MustCompile(`[&\|;]+`) + if matched := r.MatchString(cmdStr); matched { + return "", -1, errors.New("command can not contain [&|;], ignore execute") + } + for _, param := range params { + if matched := r.MatchString(param); matched { + return "", -1, errors.New("params can not contain [&|;], ignore execute") + } + } + + cmd := exec.Command(cmdStr, params...) + + // execute + out, err := cmd.CombinedOutput() + // fmt.Printf("stdout>%v\n", string(out)) + + // get exit code + logger.Infof("%+v ExecCommand cmdStr res debug1 cmd.out:%s", params, string(out)) + logger.Infof("%+v ExecCommand cmdStr res debug1 cmd.ProcessState:%+v", params, cmd.ProcessState) + logger.Infof("%+v ExecCommand cmdStr res debug2 cmd.ProcessState.Sys:%+v", params, cmd.ProcessState.Sys()) + ret = cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus() + if ret != 0 { + err = errors.New(strings.TrimSpace(string(out[:]))) + } + // fmt.Printf("cmd>%+v \n", cmd) + + return string(out[:]), ret, err +} diff --git a/oob-log-agent/util/gopool.go b/oob-log-agent/util/gopool.go new file mode 100644 index 0000000..ee7be61 --- /dev/null +++ b/oob-log-agent/util/gopool.go @@ -0,0 +1,39 @@ +package util + +import ( + "sync" +) + +// Pool for control goroutine num to run +type Pool struct { + queue chan int + wg *sync.WaitGroup +} + +// NewPool make a pool with size +func NewPool(size int) *Pool { + if size <= 0 { + size = 1 + } + return &Pool{ + queue: make(chan int, size), + wg: &sync.WaitGroup{}, + } +} + +// Add a goroutine to pool with delta num +func (p *Pool) Add() { + p.queue <- 1 + p.wg.Add(1) +} + +// Done invoke this while goroutine is done +func (p *Pool) Done() { + <-p.queue + p.wg.Done() +} + +// Wait wait all goroutine is finished +func (p *Pool) Wait() { + p.wg.Wait() +} diff --git a/oob-log-agent/util/pidUtil.go b/oob-log-agent/util/pidUtil.go new file mode 100644 index 0000000..25cf2f9 --- /dev/null +++ b/oob-log-agent/util/pidUtil.go @@ -0,0 +1,39 @@ +package util + +import ( + "errors" + "fmt" + "io/ioutil" + "os" + "strconv" +) + +func pid() { + iPid := fmt.Sprint(os.Getpid()) + tmpDir := os.TempDir() + if err := ProcExist(tmpDir); err == nil { + pidFile, _ := os.Create(tmpDir + "\\process.pid") + defer pidFile.Close() + pidFile.WriteString(iPid) + } else { + os.Exit(1) + } +} + +// ProcExist 判断进程是否启动 +func ProcExist(tmpDir string) (err error) { + iPidFile, err := os.Open(tmpDir + "\\process.pid") + defer iPidFile.Close() + if err == nil { + filePid, err := ioutil.ReadAll(iPidFile) + if err == nil { + pidStr := fmt.Sprintf("%s", filePid) + pid, _ := strconv.Atoi(pidStr) + _, err := os.FindProcess(pid) + if err == nil { + return errors.New("[WARN] Process has been started") + } + } + } + return nil +} diff --git a/oob-log-agent/util/sshClient.go b/oob-log-agent/util/sshClient.go new file mode 100644 index 0000000..279027f --- /dev/null +++ b/oob-log-agent/util/sshClient.go @@ -0,0 +1,107 @@ +package util + +import ( + "fmt" + "net" + "time" + + "golang.org/x/crypto/ssh" +) + +// SSHClient SSH client +type SSHClient struct { + Host string + Port int + Username string + Password string + client *ssh.Client + session *ssh.Session +} + +// Exec run command at remote ssh +func (s *SSHClient) Exec(cmd string, params ...interface{}) (res string, err error) { + + var ( + buf string + ret []byte + ) + for _, arg := range params { + buf = fmt.Sprintf("%s %s", buf, arg) + } + + cmdStr := cmd + " " + buf + + fmt.Println(cmdStr) + + err = s.connect() + fmt.Println(s.session) + + if err != nil { + fmt.Println(err.Error()) + return "", err + } + + ret, err = s.session.CombinedOutput(cmdStr) + + defer func() { + s.session.Close() + s.client.Close() + }() + + return string(ret), err + +} + +func (s *SSHClient) connect() error { + var ( + auth []ssh.AuthMethod + addr string + clientConfig *ssh.ClientConfig + config ssh.Config + err error + ) + + auth = make([]ssh.AuthMethod, 0) + auth = append(auth, ssh.Password(s.Password)) + + config = ssh.Config{ + Ciphers: []string{"aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "arcfour256", "arcfour128", "aes128-cbc", "3des-cbc", "aes192-cbc", "aes256-cbc"}, + } + + clientConfig = &ssh.ClientConfig{ + User: s.Username, + Auth: auth, + Timeout: 300 * time.Second, + Config: config, + HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error { + return nil + }, + } + + // connect to ssh + addr = fmt.Sprintf("%s:%d", s.Host, s.Port) + + if s.client, err = ssh.Dial("tcp", addr, clientConfig); err != nil { + fmt.Println(err.Error()) + return err + } + + // create session + if s.session, err = s.client.NewSession(); err != nil { + fmt.Println(err.Error()) + return err + } + + modes := ssh.TerminalModes{ + ssh.ECHO: 0, // disable echoing + ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud + ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud + } + + if err := s.session.RequestPty("xterm", 80, 40, modes); err != nil { + fmt.Println(err.Error()) + return err + } + + return nil +} diff --git a/oob-log-agent/util/strings.go b/oob-log-agent/util/strings.go new file mode 100644 index 0000000..e3b3142 --- /dev/null +++ b/oob-log-agent/util/strings.go @@ -0,0 +1,60 @@ +package util + +import ( + "encoding/json" + "math/rand" + "runtime" + "time" +) + +//GetRandString 借鉴RandomStringUtils.random包生成随机字符串 +// length 随机字符串的长度(不包括前缀) +// uletter 随机字符串是否包含大写字母字符 +// dletter 随机字符串是否包含小写字母字符 +// number 随机字符串是否包含数字字符 +func GetRandString(prefix string, length int32, uletter, dletter, number bool) string { + rand.Seed(time.Now().UnixNano()) + uletters := []rune("ABCDEFGHIGKLMNOPQRSTUVWXYZ") + dletters := []rune("abcdefghijklmnopqrstuvwxyz") + numbers := []rune("0123456789") + source := []rune{} + if uletter { + source = append(source, uletters...) + } + if dletter { + source = append(source, dletters...) + } + if number { + source = append(source, numbers...) + } + if len(source) == 0 { + return "atLeastContainsLetterOrNumber" + } + b := make([]rune, length) + for i := range b { + b[i] = source[rand.Intn(len(source))] + } + return prefix + string(b) +} + +// 跟现有环境一致,格式:aafc4d1b-f696-4ec2-924f-6fd012aa8345 +func GenerateRandUuid() string { + s := GetRandString("", 32, false, true, true) + runes := []rune(s) + return string(runes[0:8]) + "-" + string(runes[8:12]) + "-" + string(runes[12:16]) + "-" + string(runes[16:20]) + "-" + string(runes[20:32]) +} + +func Obj2String(v interface{}) string { + b, _ := json.Marshal(v) + return string(b) +} + +// GetCurrentGoroutineStack 获取当前Goroutine的调用栈,便于排查panic异常 +func GetCurrentGoroutineStack() string { + + const defaultStackSize = 4096 + + var buf [defaultStackSize]byte + n := runtime.Stack(buf[:], false) + return string(buf[:n]) +} diff --git a/oob-log-alert/.cmd b/oob-log-alert/.cmd new file mode 100644 index 0000000..ced32d3 --- /dev/null +++ b/oob-log-alert/.cmd @@ -0,0 +1 @@ +rm -rf vendor diff --git a/oob-log-alert/.gitmodules b/oob-log-alert/.gitmodules new file mode 100644 index 0000000..506f24c --- /dev/null +++ b/oob-log-alert/.gitmodules @@ -0,0 +1,3 @@ +[submodule "bmp-deploy"] + path = bmp-deploy + url = git@coding.jd.com:aidc-bmp/bmp-deploy.git diff --git a/oob-log-alert/README.md b/oob-log-alert/README.md new file mode 100644 index 0000000..398e9c5 --- /dev/null +++ b/oob-log-alert/README.md @@ -0,0 +1,17 @@ +# oob-log-alert + + +English | [简体中文](README.zh-CN.md) + +## Introduction + +Out-of-band monitoring alarm module. Subscribe to the alarm log sent by oob-log-agent, and send alarms after filtering by specified rules. + +The location of oob-log-alert in the entire bmp architecture is shown in:[bmp arch](../bmp-scheduler/README.md) + + + +## 2,Core Features + +- Receives alarm logs sent by oob-log-agent. +- After rule filtering, send alarm logs to the console and operation platform. \ No newline at end of file diff --git a/oob-log-alert/README.zh-CN.md b/oob-log-alert/README.zh-CN.md new file mode 100644 index 0000000..6ca4b3f --- /dev/null +++ b/oob-log-alert/README.zh-CN.md @@ -0,0 +1,18 @@ +# oob-log-alert + + +[English](README.md) | 简体中文 + +## 介绍 + +带外监控告警模块。订阅oob-log-agent发送的告警日志,经过指定规则过滤后,发送告警。 + +oob-log-alert在整个bmp架构中的位置见:[bmp架构图](../bmp-scheduler/README.zh-CN.md) + + + +## 2,核心功能 + +- 接收oob-log-agent发送的告警日志。 +- 规则过滤后,发送告警日志到控制台和运营平台。 + diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/api_key_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/api_key_client.go new file mode 100644 index 0000000..f786155 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/api_key_client.go @@ -0,0 +1,237 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new api key API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for api key API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateUserApikey(params *CreateUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserApikeyOK, error) + + DeleteUserApikey(params *DeleteUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserApikeyOK, error) + + DescribeUserAPIKey(params *DescribeUserAPIKeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserAPIKeyOK, error) + + DescribeUserAPIKeys(params *DescribeUserAPIKeysParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserAPIKeysOK, error) + + ModifyUserApikey(params *ModifyUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserApikeyOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateUserApikey CreateUserApikey 创建apikey +*/ +func (a *Client) CreateUserApikey(params *CreateUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserApikeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateUserApikeyParams() + } + op := &runtime.ClientOperation{ + ID: "createUserApikey", + Method: "POST", + PathPattern: "/user/apikeys", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateUserApikeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateUserApikeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateUserApikeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteUserApikey DeleteUserApikey 删除某个apikey +*/ +func (a *Client) DeleteUserApikey(params *DeleteUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserApikeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteUserApikeyParams() + } + op := &runtime.ClientOperation{ + ID: "deleteUserApikey", + Method: "DELETE", + PathPattern: "/user/apikeys/{apikey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteUserApikeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteUserApikeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteUserApikeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserAPIKey DescribeUserAPIKey 获取apikey详情 +*/ +func (a *Client) DescribeUserAPIKey(params *DescribeUserAPIKeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserAPIKeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserAPIKeyParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserAPIKey", + Method: "GET", + PathPattern: "/user/apikeys/{apikey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserAPIKeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserAPIKeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserAPIKeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserAPIKeys DescribeUserAPIKeys 获取APIKey列表 +*/ +func (a *Client) DescribeUserAPIKeys(params *DescribeUserAPIKeysParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserAPIKeysOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserAPIKeysParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserAPIKeys", + Method: "GET", + PathPattern: "/user/apikeys", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserAPIKeysReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserAPIKeysOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserAPIKeysDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyUserApikey ModifyUserApikey 修改apikey(暂不启用) +*/ +func (a *Client) ModifyUserApikey(params *ModifyUserApikeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserApikeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyUserApikeyParams() + } + op := &runtime.ClientOperation{ + ID: "modifyUserApikey", + Method: "PUT", + PathPattern: "/user/apikeys/{apikey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyUserApikeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyUserApikeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyUserApikeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/create_user_apikey_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/create_user_apikey_parameters.go new file mode 100644 index 0000000..0766e20 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/create_user_apikey_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateUserApikeyParams creates a new CreateUserApikeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateUserApikeyParams() *CreateUserApikeyParams { + return &CreateUserApikeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateUserApikeyParamsWithTimeout creates a new CreateUserApikeyParams object +// with the ability to set a timeout on a request. +func NewCreateUserApikeyParamsWithTimeout(timeout time.Duration) *CreateUserApikeyParams { + return &CreateUserApikeyParams{ + timeout: timeout, + } +} + +// NewCreateUserApikeyParamsWithContext creates a new CreateUserApikeyParams object +// with the ability to set a context for a request. +func NewCreateUserApikeyParamsWithContext(ctx context.Context) *CreateUserApikeyParams { + return &CreateUserApikeyParams{ + Context: ctx, + } +} + +// NewCreateUserApikeyParamsWithHTTPClient creates a new CreateUserApikeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateUserApikeyParamsWithHTTPClient(client *http.Client) *CreateUserApikeyParams { + return &CreateUserApikeyParams{ + HTTPClient: client, + } +} + +/* CreateUserApikeyParams contains all the parameters to send to the API endpoint + for the create user apikey operation. + + Typically these are written to a http.Request. +*/ +type CreateUserApikeyParams struct { + + // Body. + Body *models.CreateApikeyRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserApikeyParams) WithDefaults() *CreateUserApikeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserApikeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create user apikey params +func (o *CreateUserApikeyParams) WithTimeout(timeout time.Duration) *CreateUserApikeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create user apikey params +func (o *CreateUserApikeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create user apikey params +func (o *CreateUserApikeyParams) WithContext(ctx context.Context) *CreateUserApikeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create user apikey params +func (o *CreateUserApikeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create user apikey params +func (o *CreateUserApikeyParams) WithHTTPClient(client *http.Client) *CreateUserApikeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create user apikey params +func (o *CreateUserApikeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create user apikey params +func (o *CreateUserApikeyParams) WithBody(body *models.CreateApikeyRequest) *CreateUserApikeyParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create user apikey params +func (o *CreateUserApikeyParams) SetBody(body *models.CreateApikeyRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create user apikey params +func (o *CreateUserApikeyParams) WithAuthorization(authorization string) *CreateUserApikeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create user apikey params +func (o *CreateUserApikeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create user apikey params +func (o *CreateUserApikeyParams) WithBmpLanguage(bmpLanguage *string) *CreateUserApikeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create user apikey params +func (o *CreateUserApikeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create user apikey params +func (o *CreateUserApikeyParams) WithBmpUserID(bmpUserID *string) *CreateUserApikeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create user apikey params +func (o *CreateUserApikeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create user apikey params +func (o *CreateUserApikeyParams) WithTraceID(traceID string) *CreateUserApikeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create user apikey params +func (o *CreateUserApikeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateUserApikeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/create_user_apikey_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/create_user_apikey_responses.go new file mode 100644 index 0000000..1f90a8e --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/create_user_apikey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateUserApikeyReader is a Reader for the CreateUserApikey structure. +type CreateUserApikeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateUserApikeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateUserApikeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateUserApikeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateUserApikeyOK creates a CreateUserApikeyOK with default headers values +func NewCreateUserApikeyOK() *CreateUserApikeyOK { + return &CreateUserApikeyOK{} +} + +/* CreateUserApikeyOK describes a response with status code 200, with default header values. + +A CreateUserApikeyResult is an response struct that is used to describe create apikey result. +*/ +type CreateUserApikeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserApikeyOKBody +} + +// IsSuccess returns true when this create user apikey o k response has a 2xx status code +func (o *CreateUserApikeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create user apikey o k response has a 3xx status code +func (o *CreateUserApikeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create user apikey o k response has a 4xx status code +func (o *CreateUserApikeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create user apikey o k response has a 5xx status code +func (o *CreateUserApikeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create user apikey o k response a status code equal to that given +func (o *CreateUserApikeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateUserApikeyOK) Error() string { + return fmt.Sprintf("[POST /user/apikeys][%d] createUserApikeyOK %+v", 200, o.Payload) +} + +func (o *CreateUserApikeyOK) String() string { + return fmt.Sprintf("[POST /user/apikeys][%d] createUserApikeyOK %+v", 200, o.Payload) +} + +func (o *CreateUserApikeyOK) GetPayload() *CreateUserApikeyOKBody { + return o.Payload +} + +func (o *CreateUserApikeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserApikeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateUserApikeyDefault creates a CreateUserApikeyDefault with default headers values +func NewCreateUserApikeyDefault(code int) *CreateUserApikeyDefault { + return &CreateUserApikeyDefault{ + _statusCode: code, + } +} + +/* CreateUserApikeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateUserApikeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserApikeyDefaultBody +} + +// Code gets the status code for the create user apikey default response +func (o *CreateUserApikeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create user apikey default response has a 2xx status code +func (o *CreateUserApikeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create user apikey default response has a 3xx status code +func (o *CreateUserApikeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create user apikey default response has a 4xx status code +func (o *CreateUserApikeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create user apikey default response has a 5xx status code +func (o *CreateUserApikeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create user apikey default response a status code equal to that given +func (o *CreateUserApikeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateUserApikeyDefault) Error() string { + return fmt.Sprintf("[POST /user/apikeys][%d] createUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserApikeyDefault) String() string { + return fmt.Sprintf("[POST /user/apikeys][%d] createUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserApikeyDefault) GetPayload() *CreateUserApikeyDefaultBody { + return o.Payload +} + +func (o *CreateUserApikeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserApikeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateUserApikeyDefaultBody create user apikey default body +swagger:model CreateUserApikeyDefaultBody +*/ +type CreateUserApikeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create user apikey default body +func (o *CreateUserApikeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserApikeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createUserApikey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateUserApikeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createUserApikey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user apikey default body based on the context it is used +func (o *CreateUserApikeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserApikeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserApikeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserApikeyDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateUserApikeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateUserApikeyOKBody create user apikey o k body +swagger:model CreateUserApikeyOKBody +*/ +type CreateUserApikeyOKBody struct { + + // result + Result *models.ApikeyID `json:"result,omitempty"` +} + +// Validate validates this create user apikey o k body +func (o *CreateUserApikeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserApikeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user apikey o k body based on the context it is used +func (o *CreateUserApikeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserApikeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserApikeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserApikeyOKBody) UnmarshalBinary(b []byte) error { + var res CreateUserApikeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/delete_user_apikey_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/delete_user_apikey_parameters.go new file mode 100644 index 0000000..3dd7d9b --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/delete_user_apikey_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteUserApikeyParams creates a new DeleteUserApikeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteUserApikeyParams() *DeleteUserApikeyParams { + return &DeleteUserApikeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteUserApikeyParamsWithTimeout creates a new DeleteUserApikeyParams object +// with the ability to set a timeout on a request. +func NewDeleteUserApikeyParamsWithTimeout(timeout time.Duration) *DeleteUserApikeyParams { + return &DeleteUserApikeyParams{ + timeout: timeout, + } +} + +// NewDeleteUserApikeyParamsWithContext creates a new DeleteUserApikeyParams object +// with the ability to set a context for a request. +func NewDeleteUserApikeyParamsWithContext(ctx context.Context) *DeleteUserApikeyParams { + return &DeleteUserApikeyParams{ + Context: ctx, + } +} + +// NewDeleteUserApikeyParamsWithHTTPClient creates a new DeleteUserApikeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteUserApikeyParamsWithHTTPClient(client *http.Client) *DeleteUserApikeyParams { + return &DeleteUserApikeyParams{ + HTTPClient: client, + } +} + +/* DeleteUserApikeyParams contains all the parameters to send to the API endpoint + for the delete user apikey operation. + + Typically these are written to a http.Request. +*/ +type DeleteUserApikeyParams struct { + + // ApikeyID. + ApikeyID string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserApikeyParams) WithDefaults() *DeleteUserApikeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserApikeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete user apikey params +func (o *DeleteUserApikeyParams) WithTimeout(timeout time.Duration) *DeleteUserApikeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete user apikey params +func (o *DeleteUserApikeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete user apikey params +func (o *DeleteUserApikeyParams) WithContext(ctx context.Context) *DeleteUserApikeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete user apikey params +func (o *DeleteUserApikeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete user apikey params +func (o *DeleteUserApikeyParams) WithHTTPClient(client *http.Client) *DeleteUserApikeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete user apikey params +func (o *DeleteUserApikeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithApikeyID adds the apikeyID to the delete user apikey params +func (o *DeleteUserApikeyParams) WithApikeyID(apikeyID string) *DeleteUserApikeyParams { + o.SetApikeyID(apikeyID) + return o +} + +// SetApikeyID adds the apikeyId to the delete user apikey params +func (o *DeleteUserApikeyParams) SetApikeyID(apikeyID string) { + o.ApikeyID = apikeyID +} + +// WithAuthorization adds the authorization to the delete user apikey params +func (o *DeleteUserApikeyParams) WithAuthorization(authorization string) *DeleteUserApikeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete user apikey params +func (o *DeleteUserApikeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete user apikey params +func (o *DeleteUserApikeyParams) WithBmpLanguage(bmpLanguage *string) *DeleteUserApikeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete user apikey params +func (o *DeleteUserApikeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete user apikey params +func (o *DeleteUserApikeyParams) WithBmpUserID(bmpUserID *string) *DeleteUserApikeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete user apikey params +func (o *DeleteUserApikeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete user apikey params +func (o *DeleteUserApikeyParams) WithTraceID(traceID string) *DeleteUserApikeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete user apikey params +func (o *DeleteUserApikeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteUserApikeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param apikey_id + if err := r.SetPathParam("apikey_id", o.ApikeyID); err != nil { + return err + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/delete_user_apikey_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/delete_user_apikey_responses.go new file mode 100644 index 0000000..cd366f1 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/delete_user_apikey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteUserApikeyReader is a Reader for the DeleteUserApikey structure. +type DeleteUserApikeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteUserApikeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteUserApikeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteUserApikeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteUserApikeyOK creates a DeleteUserApikeyOK with default headers values +func NewDeleteUserApikeyOK() *DeleteUserApikeyOK { + return &DeleteUserApikeyOK{} +} + +/* DeleteUserApikeyOK describes a response with status code 200, with default header values. + +A DeleteUserApikeyResult is an response struct that is used to describe delete Apikey result. +*/ +type DeleteUserApikeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserApikeyOKBody +} + +// IsSuccess returns true when this delete user apikey o k response has a 2xx status code +func (o *DeleteUserApikeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete user apikey o k response has a 3xx status code +func (o *DeleteUserApikeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete user apikey o k response has a 4xx status code +func (o *DeleteUserApikeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete user apikey o k response has a 5xx status code +func (o *DeleteUserApikeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete user apikey o k response a status code equal to that given +func (o *DeleteUserApikeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteUserApikeyOK) Error() string { + return fmt.Sprintf("[DELETE /user/apikeys/{apikey_id}][%d] deleteUserApikeyOK %+v", 200, o.Payload) +} + +func (o *DeleteUserApikeyOK) String() string { + return fmt.Sprintf("[DELETE /user/apikeys/{apikey_id}][%d] deleteUserApikeyOK %+v", 200, o.Payload) +} + +func (o *DeleteUserApikeyOK) GetPayload() *DeleteUserApikeyOKBody { + return o.Payload +} + +func (o *DeleteUserApikeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserApikeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteUserApikeyDefault creates a DeleteUserApikeyDefault with default headers values +func NewDeleteUserApikeyDefault(code int) *DeleteUserApikeyDefault { + return &DeleteUserApikeyDefault{ + _statusCode: code, + } +} + +/* DeleteUserApikeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteUserApikeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserApikeyDefaultBody +} + +// Code gets the status code for the delete user apikey default response +func (o *DeleteUserApikeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete user apikey default response has a 2xx status code +func (o *DeleteUserApikeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete user apikey default response has a 3xx status code +func (o *DeleteUserApikeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete user apikey default response has a 4xx status code +func (o *DeleteUserApikeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete user apikey default response has a 5xx status code +func (o *DeleteUserApikeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete user apikey default response a status code equal to that given +func (o *DeleteUserApikeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteUserApikeyDefault) Error() string { + return fmt.Sprintf("[DELETE /user/apikeys/{apikey_id}][%d] deleteUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserApikeyDefault) String() string { + return fmt.Sprintf("[DELETE /user/apikeys/{apikey_id}][%d] deleteUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserApikeyDefault) GetPayload() *DeleteUserApikeyDefaultBody { + return o.Payload +} + +func (o *DeleteUserApikeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserApikeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteUserApikeyDefaultBody delete user apikey default body +swagger:model DeleteUserApikeyDefaultBody +*/ +type DeleteUserApikeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete user apikey default body +func (o *DeleteUserApikeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserApikeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserApikey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteUserApikeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserApikey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user apikey default body based on the context it is used +func (o *DeleteUserApikeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserApikeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserApikeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserApikeyDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteUserApikeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteUserApikeyOKBody delete user apikey o k body +swagger:model DeleteUserApikeyOKBody +*/ +type DeleteUserApikeyOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete user apikey o k body +func (o *DeleteUserApikeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserApikeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user apikey o k body based on the context it is used +func (o *DeleteUserApikeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserApikeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserApikeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserApikeyOKBody) UnmarshalBinary(b []byte) error { + var res DeleteUserApikeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_key_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_key_parameters.go new file mode 100644 index 0000000..0d39690 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_key_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeUserAPIKeyParams creates a new DescribeUserAPIKeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserAPIKeyParams() *DescribeUserAPIKeyParams { + return &DescribeUserAPIKeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserAPIKeyParamsWithTimeout creates a new DescribeUserAPIKeyParams object +// with the ability to set a timeout on a request. +func NewDescribeUserAPIKeyParamsWithTimeout(timeout time.Duration) *DescribeUserAPIKeyParams { + return &DescribeUserAPIKeyParams{ + timeout: timeout, + } +} + +// NewDescribeUserAPIKeyParamsWithContext creates a new DescribeUserAPIKeyParams object +// with the ability to set a context for a request. +func NewDescribeUserAPIKeyParamsWithContext(ctx context.Context) *DescribeUserAPIKeyParams { + return &DescribeUserAPIKeyParams{ + Context: ctx, + } +} + +// NewDescribeUserAPIKeyParamsWithHTTPClient creates a new DescribeUserAPIKeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserAPIKeyParamsWithHTTPClient(client *http.Client) *DescribeUserAPIKeyParams { + return &DescribeUserAPIKeyParams{ + HTTPClient: client, + } +} + +/* DescribeUserAPIKeyParams contains all the parameters to send to the API endpoint + for the describe user API key operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserAPIKeyParams struct { + + // ApikeyID. + ApikeyID string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user API key params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserAPIKeyParams) WithDefaults() *DescribeUserAPIKeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user API key params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserAPIKeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithTimeout(timeout time.Duration) *DescribeUserAPIKeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithContext(ctx context.Context) *DescribeUserAPIKeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithHTTPClient(client *http.Client) *DescribeUserAPIKeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithApikeyID adds the apikeyID to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithApikeyID(apikeyID string) *DescribeUserAPIKeyParams { + o.SetApikeyID(apikeyID) + return o +} + +// SetApikeyID adds the apikeyId to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetApikeyID(apikeyID string) { + o.ApikeyID = apikeyID +} + +// WithAuthorization adds the authorization to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithAuthorization(authorization string) *DescribeUserAPIKeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserAPIKeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithBmpUserID(bmpUserID *string) *DescribeUserAPIKeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe user API key params +func (o *DescribeUserAPIKeyParams) WithTraceID(traceID string) *DescribeUserAPIKeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user API key params +func (o *DescribeUserAPIKeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserAPIKeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param apikey_id + if err := r.SetPathParam("apikey_id", o.ApikeyID); err != nil { + return err + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_key_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_key_responses.go new file mode 100644 index 0000000..57577a7 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_key_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserAPIKeyReader is a Reader for the DescribeUserAPIKey structure. +type DescribeUserAPIKeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserAPIKeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserAPIKeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserAPIKeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserAPIKeyOK creates a DescribeUserAPIKeyOK with default headers values +func NewDescribeUserAPIKeyOK() *DescribeUserAPIKeyOK { + return &DescribeUserAPIKeyOK{} +} + +/* DescribeUserAPIKeyOK describes a response with status code 200, with default header values. + +A DescribeUserAPIKeyResult is an response struct that is used to describe getapikey. +*/ +type DescribeUserAPIKeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserAPIKeyOKBody +} + +// IsSuccess returns true when this describe user Api key o k response has a 2xx status code +func (o *DescribeUserAPIKeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user Api key o k response has a 3xx status code +func (o *DescribeUserAPIKeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user Api key o k response has a 4xx status code +func (o *DescribeUserAPIKeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user Api key o k response has a 5xx status code +func (o *DescribeUserAPIKeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user Api key o k response a status code equal to that given +func (o *DescribeUserAPIKeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserAPIKeyOK) Error() string { + return fmt.Sprintf("[GET /user/apikeys/{apikey_id}][%d] describeUserApiKeyOK %+v", 200, o.Payload) +} + +func (o *DescribeUserAPIKeyOK) String() string { + return fmt.Sprintf("[GET /user/apikeys/{apikey_id}][%d] describeUserApiKeyOK %+v", 200, o.Payload) +} + +func (o *DescribeUserAPIKeyOK) GetPayload() *DescribeUserAPIKeyOKBody { + return o.Payload +} + +func (o *DescribeUserAPIKeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserAPIKeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserAPIKeyDefault creates a DescribeUserAPIKeyDefault with default headers values +func NewDescribeUserAPIKeyDefault(code int) *DescribeUserAPIKeyDefault { + return &DescribeUserAPIKeyDefault{ + _statusCode: code, + } +} + +/* DescribeUserAPIKeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserAPIKeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserAPIKeyDefaultBody +} + +// Code gets the status code for the describe user API key default response +func (o *DescribeUserAPIKeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user API key default response has a 2xx status code +func (o *DescribeUserAPIKeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user API key default response has a 3xx status code +func (o *DescribeUserAPIKeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user API key default response has a 4xx status code +func (o *DescribeUserAPIKeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user API key default response has a 5xx status code +func (o *DescribeUserAPIKeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user API key default response a status code equal to that given +func (o *DescribeUserAPIKeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserAPIKeyDefault) Error() string { + return fmt.Sprintf("[GET /user/apikeys/{apikey_id}][%d] describeUserAPIKey default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserAPIKeyDefault) String() string { + return fmt.Sprintf("[GET /user/apikeys/{apikey_id}][%d] describeUserAPIKey default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserAPIKeyDefault) GetPayload() *DescribeUserAPIKeyDefaultBody { + return o.Payload +} + +func (o *DescribeUserAPIKeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserAPIKeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserAPIKeyDefaultBody describe user API key default body +swagger:model DescribeUserAPIKeyDefaultBody +*/ +type DescribeUserAPIKeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user API key default body +func (o *DescribeUserAPIKeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserAPIKey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserAPIKeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserAPIKey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserAPIKey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserAPIKey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user API key default body based on the context it is used +func (o *DescribeUserAPIKeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserAPIKey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserAPIKey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserAPIKeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserAPIKeyDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserAPIKeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserAPIKeyOKBody describe user API key o k body +swagger:model DescribeUserAPIKeyOKBody +*/ +type DescribeUserAPIKeyOKBody struct { + + // result + Result *models.ApikeyInfo `json:"result,omitempty"` +} + +// Validate validates this describe user API key o k body +func (o *DescribeUserAPIKeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserApiKeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserApiKeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user API key o k body based on the context it is used +func (o *DescribeUserAPIKeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserApiKeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserApiKeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserAPIKeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserAPIKeyOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserAPIKeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_keys_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_keys_parameters.go new file mode 100644 index 0000000..4fecbc7 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_keys_parameters.go @@ -0,0 +1,396 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeUserAPIKeysParams creates a new DescribeUserAPIKeysParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserAPIKeysParams() *DescribeUserAPIKeysParams { + return &DescribeUserAPIKeysParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserAPIKeysParamsWithTimeout creates a new DescribeUserAPIKeysParams object +// with the ability to set a timeout on a request. +func NewDescribeUserAPIKeysParamsWithTimeout(timeout time.Duration) *DescribeUserAPIKeysParams { + return &DescribeUserAPIKeysParams{ + timeout: timeout, + } +} + +// NewDescribeUserAPIKeysParamsWithContext creates a new DescribeUserAPIKeysParams object +// with the ability to set a context for a request. +func NewDescribeUserAPIKeysParamsWithContext(ctx context.Context) *DescribeUserAPIKeysParams { + return &DescribeUserAPIKeysParams{ + Context: ctx, + } +} + +// NewDescribeUserAPIKeysParamsWithHTTPClient creates a new DescribeUserAPIKeysParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserAPIKeysParamsWithHTTPClient(client *http.Client) *DescribeUserAPIKeysParams { + return &DescribeUserAPIKeysParams{ + HTTPClient: client, + } +} + +/* DescribeUserAPIKeysParams contains all the parameters to send to the API endpoint + for the describe user API keys operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserAPIKeysParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否查询全部/导出 + */ + IsAll *string + + /* Name. + + 秘钥对名称 + */ + Name *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* Type. + + Token类型, [system/user] + */ + Type *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user API keys params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserAPIKeysParams) WithDefaults() *DescribeUserAPIKeysParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user API keys params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserAPIKeysParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithTimeout(timeout time.Duration) *DescribeUserAPIKeysParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithContext(ctx context.Context) *DescribeUserAPIKeysParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithHTTPClient(client *http.Client) *DescribeUserAPIKeysParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithAuthorization(authorization string) *DescribeUserAPIKeysParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserAPIKeysParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithBmpUserID(bmpUserID *string) *DescribeUserAPIKeysParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithIsAll(isAll *string) *DescribeUserAPIKeysParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithName adds the name to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithName(name *string) *DescribeUserAPIKeysParams { + o.SetName(name) + return o +} + +// SetName adds the name to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetName(name *string) { + o.Name = name +} + +// WithPageNumber adds the pageNumber to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithPageNumber(pageNumber *int64) *DescribeUserAPIKeysParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithPageSize(pageSize *int64) *DescribeUserAPIKeysParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithTraceID(traceID string) *DescribeUserAPIKeysParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithType adds the typeVar to the describe user API keys params +func (o *DescribeUserAPIKeysParams) WithType(typeVar *string) *DescribeUserAPIKeysParams { + o.SetType(typeVar) + return o +} + +// SetType adds the type to the describe user API keys params +func (o *DescribeUserAPIKeysParams) SetType(typeVar *string) { + o.Type = typeVar +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserAPIKeysParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.Type != nil { + + // query param type + var qrType string + + if o.Type != nil { + qrType = *o.Type + } + qType := qrType + if qType != "" { + + if err := r.SetQueryParam("type", qType); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_keys_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_keys_responses.go new file mode 100644 index 0000000..3f39901 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/describe_user_api_keys_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserAPIKeysReader is a Reader for the DescribeUserAPIKeys structure. +type DescribeUserAPIKeysReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserAPIKeysReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserAPIKeysOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserAPIKeysDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserAPIKeysOK creates a DescribeUserAPIKeysOK with default headers values +func NewDescribeUserAPIKeysOK() *DescribeUserAPIKeysOK { + return &DescribeUserAPIKeysOK{} +} + +/* DescribeUserAPIKeysOK describes a response with status code 200, with default header values. + +A DescribeUserAPIKeysResult is an response struct that is used to describe getapikeylist. +*/ +type DescribeUserAPIKeysOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserAPIKeysOKBody +} + +// IsSuccess returns true when this describe user Api keys o k response has a 2xx status code +func (o *DescribeUserAPIKeysOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user Api keys o k response has a 3xx status code +func (o *DescribeUserAPIKeysOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user Api keys o k response has a 4xx status code +func (o *DescribeUserAPIKeysOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user Api keys o k response has a 5xx status code +func (o *DescribeUserAPIKeysOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user Api keys o k response a status code equal to that given +func (o *DescribeUserAPIKeysOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserAPIKeysOK) Error() string { + return fmt.Sprintf("[GET /user/apikeys][%d] describeUserApiKeysOK %+v", 200, o.Payload) +} + +func (o *DescribeUserAPIKeysOK) String() string { + return fmt.Sprintf("[GET /user/apikeys][%d] describeUserApiKeysOK %+v", 200, o.Payload) +} + +func (o *DescribeUserAPIKeysOK) GetPayload() *DescribeUserAPIKeysOKBody { + return o.Payload +} + +func (o *DescribeUserAPIKeysOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserAPIKeysOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserAPIKeysDefault creates a DescribeUserAPIKeysDefault with default headers values +func NewDescribeUserAPIKeysDefault(code int) *DescribeUserAPIKeysDefault { + return &DescribeUserAPIKeysDefault{ + _statusCode: code, + } +} + +/* DescribeUserAPIKeysDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserAPIKeysDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserAPIKeysDefaultBody +} + +// Code gets the status code for the describe user API keys default response +func (o *DescribeUserAPIKeysDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user API keys default response has a 2xx status code +func (o *DescribeUserAPIKeysDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user API keys default response has a 3xx status code +func (o *DescribeUserAPIKeysDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user API keys default response has a 4xx status code +func (o *DescribeUserAPIKeysDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user API keys default response has a 5xx status code +func (o *DescribeUserAPIKeysDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user API keys default response a status code equal to that given +func (o *DescribeUserAPIKeysDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserAPIKeysDefault) Error() string { + return fmt.Sprintf("[GET /user/apikeys][%d] describeUserAPIKeys default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserAPIKeysDefault) String() string { + return fmt.Sprintf("[GET /user/apikeys][%d] describeUserAPIKeys default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserAPIKeysDefault) GetPayload() *DescribeUserAPIKeysDefaultBody { + return o.Payload +} + +func (o *DescribeUserAPIKeysDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserAPIKeysDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserAPIKeysDefaultBody describe user API keys default body +swagger:model DescribeUserAPIKeysDefaultBody +*/ +type DescribeUserAPIKeysDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user API keys default body +func (o *DescribeUserAPIKeysDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeysDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserAPIKeys default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserAPIKeysDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserAPIKeys default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserAPIKeys default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserAPIKeys default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user API keys default body based on the context it is used +func (o *DescribeUserAPIKeysDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeysDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserAPIKeys default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserAPIKeys default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserAPIKeysDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserAPIKeysDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserAPIKeysDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserAPIKeysOKBody describe user API keys o k body +swagger:model DescribeUserAPIKeysOKBody +*/ +type DescribeUserAPIKeysOKBody struct { + + // result + Result *models.ApikeyList `json:"result,omitempty"` +} + +// Validate validates this describe user API keys o k body +func (o *DescribeUserAPIKeysOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeysOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserApiKeysOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserApiKeysOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user API keys o k body based on the context it is used +func (o *DescribeUserAPIKeysOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserAPIKeysOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserApiKeysOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserApiKeysOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserAPIKeysOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserAPIKeysOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserAPIKeysOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/modify_user_apikey_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/modify_user_apikey_parameters.go new file mode 100644 index 0000000..b495f85 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/modify_user_apikey_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyUserApikeyParams creates a new ModifyUserApikeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyUserApikeyParams() *ModifyUserApikeyParams { + return &ModifyUserApikeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyUserApikeyParamsWithTimeout creates a new ModifyUserApikeyParams object +// with the ability to set a timeout on a request. +func NewModifyUserApikeyParamsWithTimeout(timeout time.Duration) *ModifyUserApikeyParams { + return &ModifyUserApikeyParams{ + timeout: timeout, + } +} + +// NewModifyUserApikeyParamsWithContext creates a new ModifyUserApikeyParams object +// with the ability to set a context for a request. +func NewModifyUserApikeyParamsWithContext(ctx context.Context) *ModifyUserApikeyParams { + return &ModifyUserApikeyParams{ + Context: ctx, + } +} + +// NewModifyUserApikeyParamsWithHTTPClient creates a new ModifyUserApikeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyUserApikeyParamsWithHTTPClient(client *http.Client) *ModifyUserApikeyParams { + return &ModifyUserApikeyParams{ + HTTPClient: client, + } +} + +/* ModifyUserApikeyParams contains all the parameters to send to the API endpoint + for the modify user apikey operation. + + Typically these are written to a http.Request. +*/ +type ModifyUserApikeyParams struct { + + // Body. + Body *models.ModifyApikeyRequest + + // ApikeyID. + ApikeyID string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserApikeyParams) WithDefaults() *ModifyUserApikeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify user apikey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserApikeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify user apikey params +func (o *ModifyUserApikeyParams) WithTimeout(timeout time.Duration) *ModifyUserApikeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify user apikey params +func (o *ModifyUserApikeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify user apikey params +func (o *ModifyUserApikeyParams) WithContext(ctx context.Context) *ModifyUserApikeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify user apikey params +func (o *ModifyUserApikeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify user apikey params +func (o *ModifyUserApikeyParams) WithHTTPClient(client *http.Client) *ModifyUserApikeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify user apikey params +func (o *ModifyUserApikeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify user apikey params +func (o *ModifyUserApikeyParams) WithBody(body *models.ModifyApikeyRequest) *ModifyUserApikeyParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify user apikey params +func (o *ModifyUserApikeyParams) SetBody(body *models.ModifyApikeyRequest) { + o.Body = body +} + +// WithApikeyID adds the apikeyID to the modify user apikey params +func (o *ModifyUserApikeyParams) WithApikeyID(apikeyID string) *ModifyUserApikeyParams { + o.SetApikeyID(apikeyID) + return o +} + +// SetApikeyID adds the apikeyId to the modify user apikey params +func (o *ModifyUserApikeyParams) SetApikeyID(apikeyID string) { + o.ApikeyID = apikeyID +} + +// WithAuthorization adds the authorization to the modify user apikey params +func (o *ModifyUserApikeyParams) WithAuthorization(authorization string) *ModifyUserApikeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify user apikey params +func (o *ModifyUserApikeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify user apikey params +func (o *ModifyUserApikeyParams) WithBmpLanguage(bmpLanguage *string) *ModifyUserApikeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify user apikey params +func (o *ModifyUserApikeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify user apikey params +func (o *ModifyUserApikeyParams) WithBmpUserID(bmpUserID *string) *ModifyUserApikeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify user apikey params +func (o *ModifyUserApikeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the modify user apikey params +func (o *ModifyUserApikeyParams) WithTraceID(traceID string) *ModifyUserApikeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify user apikey params +func (o *ModifyUserApikeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyUserApikeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // path param apikey_id + if err := r.SetPathParam("apikey_id", o.ApikeyID); err != nil { + return err + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/modify_user_apikey_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/modify_user_apikey_responses.go new file mode 100644 index 0000000..cbdadcb --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/api_key/modify_user_apikey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package api_key + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyUserApikeyReader is a Reader for the ModifyUserApikey structure. +type ModifyUserApikeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyUserApikeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyUserApikeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyUserApikeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyUserApikeyOK creates a ModifyUserApikeyOK with default headers values +func NewModifyUserApikeyOK() *ModifyUserApikeyOK { + return &ModifyUserApikeyOK{} +} + +/* ModifyUserApikeyOK describes a response with status code 200, with default header values. + +A ModifyUserApikeyResult is an response struct that is used to describe modifyApikey result. +*/ +type ModifyUserApikeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserApikeyOKBody +} + +// IsSuccess returns true when this modify user apikey o k response has a 2xx status code +func (o *ModifyUserApikeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify user apikey o k response has a 3xx status code +func (o *ModifyUserApikeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify user apikey o k response has a 4xx status code +func (o *ModifyUserApikeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify user apikey o k response has a 5xx status code +func (o *ModifyUserApikeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify user apikey o k response a status code equal to that given +func (o *ModifyUserApikeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyUserApikeyOK) Error() string { + return fmt.Sprintf("[PUT /user/apikeys/{apikey_id}][%d] modifyUserApikeyOK %+v", 200, o.Payload) +} + +func (o *ModifyUserApikeyOK) String() string { + return fmt.Sprintf("[PUT /user/apikeys/{apikey_id}][%d] modifyUserApikeyOK %+v", 200, o.Payload) +} + +func (o *ModifyUserApikeyOK) GetPayload() *ModifyUserApikeyOKBody { + return o.Payload +} + +func (o *ModifyUserApikeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserApikeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyUserApikeyDefault creates a ModifyUserApikeyDefault with default headers values +func NewModifyUserApikeyDefault(code int) *ModifyUserApikeyDefault { + return &ModifyUserApikeyDefault{ + _statusCode: code, + } +} + +/* ModifyUserApikeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyUserApikeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserApikeyDefaultBody +} + +// Code gets the status code for the modify user apikey default response +func (o *ModifyUserApikeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify user apikey default response has a 2xx status code +func (o *ModifyUserApikeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify user apikey default response has a 3xx status code +func (o *ModifyUserApikeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify user apikey default response has a 4xx status code +func (o *ModifyUserApikeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify user apikey default response has a 5xx status code +func (o *ModifyUserApikeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify user apikey default response a status code equal to that given +func (o *ModifyUserApikeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyUserApikeyDefault) Error() string { + return fmt.Sprintf("[PUT /user/apikeys/{apikey_id}][%d] modifyUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserApikeyDefault) String() string { + return fmt.Sprintf("[PUT /user/apikeys/{apikey_id}][%d] modifyUserApikey default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserApikeyDefault) GetPayload() *ModifyUserApikeyDefaultBody { + return o.Payload +} + +func (o *ModifyUserApikeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserApikeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyUserApikeyDefaultBody modify user apikey default body +swagger:model ModifyUserApikeyDefaultBody +*/ +type ModifyUserApikeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify user apikey default body +func (o *ModifyUserApikeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserApikeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserApikey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyUserApikeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserApikey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user apikey default body based on the context it is used +func (o *ModifyUserApikeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserApikeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserApikey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserApikey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserApikeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserApikeyDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyUserApikeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyUserApikeyOKBody modify user apikey o k body +swagger:model ModifyUserApikeyOKBody +*/ +type ModifyUserApikeyOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify user apikey o k body +func (o *ModifyUserApikeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserApikeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user apikey o k body based on the context it is used +func (o *ModifyUserApikeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserApikeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserApikeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserApikeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserApikeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserApikeyOKBody) UnmarshalBinary(b []byte) error { + var res ModifyUserApikeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/c_p_s_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/c_p_s_client.go new file mode 100644 index 0000000..5f0db44 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/c_p_s_client.go @@ -0,0 +1,182 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package client + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/api_key" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/collect" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/device" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/device_type" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/idc" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/image" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/instance" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/license" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/os" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/project" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/raid" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/resource" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/role" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/sshkey" + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client/user" +) + +// Default c p s HTTP client. +var Default = NewHTTPClient(nil) + +const ( + // DefaultHost is the default Host + // found in Meta (info) section of spec file + DefaultHost string = "bmp-openapi.bmp.local" + // DefaultBasePath is the default BasePath + // found in Meta (info) section of spec file + DefaultBasePath string = "/v1" +) + +// DefaultSchemes are the default schemes found in Meta (info) section of spec file +var DefaultSchemes = []string{"http"} + +// NewHTTPClient creates a new c p s HTTP client. +func NewHTTPClient(formats strfmt.Registry) *CPS { + return NewHTTPClientWithConfig(formats, nil) +} + +// NewHTTPClientWithConfig creates a new c p s HTTP client, +// using a customizable transport config. +func NewHTTPClientWithConfig(formats strfmt.Registry, cfg *TransportConfig) *CPS { + // ensure nullable parameters have default + if cfg == nil { + cfg = DefaultTransportConfig() + } + + // create transport and client + transport := httptransport.New(cfg.Host, cfg.BasePath, cfg.Schemes) + return New(transport, formats) +} + +// New creates a new c p s client +func New(transport runtime.ClientTransport, formats strfmt.Registry) *CPS { + // ensure nullable parameters have default + if formats == nil { + formats = strfmt.Default + } + + cli := new(CPS) + cli.Transport = transport + cli.APIKey = api_key.New(transport, formats) + cli.Collect = collect.New(transport, formats) + cli.Device = device.New(transport, formats) + cli.DeviceType = device_type.New(transport, formats) + cli.Idc = idc.New(transport, formats) + cli.Image = image.New(transport, formats) + cli.Instance = instance.New(transport, formats) + cli.License = license.New(transport, formats) + cli.Os = os.New(transport, formats) + cli.Project = project.New(transport, formats) + cli.Raid = raid.New(transport, formats) + cli.Resource = resource.New(transport, formats) + cli.Role = role.New(transport, formats) + cli.Sshkey = sshkey.New(transport, formats) + cli.User = user.New(transport, formats) + return cli +} + +// DefaultTransportConfig creates a TransportConfig with the +// default settings taken from the meta section of the spec file. +func DefaultTransportConfig() *TransportConfig { + return &TransportConfig{ + Host: DefaultHost, + BasePath: DefaultBasePath, + Schemes: DefaultSchemes, + } +} + +// TransportConfig contains the transport related info, +// found in the meta section of the spec file. +type TransportConfig struct { + Host string + BasePath string + Schemes []string +} + +// WithHost overrides the default host, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithHost(host string) *TransportConfig { + cfg.Host = host + return cfg +} + +// WithBasePath overrides the default basePath, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithBasePath(basePath string) *TransportConfig { + cfg.BasePath = basePath + return cfg +} + +// WithSchemes overrides the default schemes, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithSchemes(schemes []string) *TransportConfig { + cfg.Schemes = schemes + return cfg +} + +// CPS is a client for c p s +type CPS struct { + APIKey api_key.ClientService + + Collect collect.ClientService + + Device device.ClientService + + DeviceType device_type.ClientService + + Idc idc.ClientService + + Image image.ClientService + + Instance instance.ClientService + + License license.ClientService + + Os os.ClientService + + Project project.ClientService + + Raid raid.ClientService + + Resource resource.ClientService + + Role role.ClientService + + Sshkey sshkey.ClientService + + User user.ClientService + + Transport runtime.ClientTransport +} + +// SetTransport changes the transport on the client and all its subresources +func (c *CPS) SetTransport(transport runtime.ClientTransport) { + c.Transport = transport + c.APIKey.SetTransport(transport) + c.Collect.SetTransport(transport) + c.Device.SetTransport(transport) + c.DeviceType.SetTransport(transport) + c.Idc.SetTransport(transport) + c.Image.SetTransport(transport) + c.Instance.SetTransport(transport) + c.License.SetTransport(transport) + c.Os.SetTransport(transport) + c.Project.SetTransport(transport) + c.Raid.SetTransport(transport) + c.Resource.SetTransport(transport) + c.Role.SetTransport(transport) + c.Sshkey.SetTransport(transport) + c.User.SetTransport(transport) +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/collect/collect_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/collect/collect_client.go new file mode 100644 index 0000000..aa4b822 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/collect/collect_client.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package collect + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new collect API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for collect API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CollectDeviceInfo(params *CollectDeviceInfoParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CollectDeviceInfoOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CollectDeviceInfo CollectDeviceInfo 采集设备信息 +*/ +func (a *Client) CollectDeviceInfo(params *CollectDeviceInfoParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CollectDeviceInfoOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCollectDeviceInfoParams() + } + op := &runtime.ClientOperation{ + ID: "collectDeviceInfo", + Method: "POST", + PathPattern: "/collect/collectDeviceInfo", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CollectDeviceInfoReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CollectDeviceInfoOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CollectDeviceInfoDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/collect/collect_device_info_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/collect/collect_device_info_parameters.go new file mode 100644 index 0000000..44f3a14 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/collect/collect_device_info_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package collect + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCollectDeviceInfoParams creates a new CollectDeviceInfoParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCollectDeviceInfoParams() *CollectDeviceInfoParams { + return &CollectDeviceInfoParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCollectDeviceInfoParamsWithTimeout creates a new CollectDeviceInfoParams object +// with the ability to set a timeout on a request. +func NewCollectDeviceInfoParamsWithTimeout(timeout time.Duration) *CollectDeviceInfoParams { + return &CollectDeviceInfoParams{ + timeout: timeout, + } +} + +// NewCollectDeviceInfoParamsWithContext creates a new CollectDeviceInfoParams object +// with the ability to set a context for a request. +func NewCollectDeviceInfoParamsWithContext(ctx context.Context) *CollectDeviceInfoParams { + return &CollectDeviceInfoParams{ + Context: ctx, + } +} + +// NewCollectDeviceInfoParamsWithHTTPClient creates a new CollectDeviceInfoParams object +// with the ability to set a custom HTTPClient for a request. +func NewCollectDeviceInfoParamsWithHTTPClient(client *http.Client) *CollectDeviceInfoParams { + return &CollectDeviceInfoParams{ + HTTPClient: client, + } +} + +/* CollectDeviceInfoParams contains all the parameters to send to the API endpoint + for the collect device info operation. + + Typically these are written to a http.Request. +*/ +type CollectDeviceInfoParams struct { + + // Body. + Body *models.CollectDeviceInfoRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the collect device info params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CollectDeviceInfoParams) WithDefaults() *CollectDeviceInfoParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the collect device info params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CollectDeviceInfoParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the collect device info params +func (o *CollectDeviceInfoParams) WithTimeout(timeout time.Duration) *CollectDeviceInfoParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the collect device info params +func (o *CollectDeviceInfoParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the collect device info params +func (o *CollectDeviceInfoParams) WithContext(ctx context.Context) *CollectDeviceInfoParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the collect device info params +func (o *CollectDeviceInfoParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the collect device info params +func (o *CollectDeviceInfoParams) WithHTTPClient(client *http.Client) *CollectDeviceInfoParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the collect device info params +func (o *CollectDeviceInfoParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the collect device info params +func (o *CollectDeviceInfoParams) WithBody(body *models.CollectDeviceInfoRequest) *CollectDeviceInfoParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the collect device info params +func (o *CollectDeviceInfoParams) SetBody(body *models.CollectDeviceInfoRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the collect device info params +func (o *CollectDeviceInfoParams) WithAuthorization(authorization string) *CollectDeviceInfoParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the collect device info params +func (o *CollectDeviceInfoParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the collect device info params +func (o *CollectDeviceInfoParams) WithBmpLanguage(bmpLanguage *string) *CollectDeviceInfoParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the collect device info params +func (o *CollectDeviceInfoParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the collect device info params +func (o *CollectDeviceInfoParams) WithBmpUserID(bmpUserID *string) *CollectDeviceInfoParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the collect device info params +func (o *CollectDeviceInfoParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the collect device info params +func (o *CollectDeviceInfoParams) WithTraceID(traceID string) *CollectDeviceInfoParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the collect device info params +func (o *CollectDeviceInfoParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CollectDeviceInfoParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/collect/collect_device_info_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/collect/collect_device_info_responses.go new file mode 100644 index 0000000..621c8eb --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/collect/collect_device_info_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package collect + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CollectDeviceInfoReader is a Reader for the CollectDeviceInfo structure. +type CollectDeviceInfoReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CollectDeviceInfoReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCollectDeviceInfoOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCollectDeviceInfoDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCollectDeviceInfoOK creates a CollectDeviceInfoOK with default headers values +func NewCollectDeviceInfoOK() *CollectDeviceInfoOK { + return &CollectDeviceInfoOK{} +} + +/* CollectDeviceInfoOK describes a response with status code 200, with default header values. + +CollectDeviceInfoOK collect device info o k +*/ +type CollectDeviceInfoOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CollectDeviceInfoOKBody +} + +// IsSuccess returns true when this collect device info o k response has a 2xx status code +func (o *CollectDeviceInfoOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this collect device info o k response has a 3xx status code +func (o *CollectDeviceInfoOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this collect device info o k response has a 4xx status code +func (o *CollectDeviceInfoOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this collect device info o k response has a 5xx status code +func (o *CollectDeviceInfoOK) IsServerError() bool { + return false +} + +// IsCode returns true when this collect device info o k response a status code equal to that given +func (o *CollectDeviceInfoOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CollectDeviceInfoOK) Error() string { + return fmt.Sprintf("[POST /collect/collectDeviceInfo][%d] collectDeviceInfoOK %+v", 200, o.Payload) +} + +func (o *CollectDeviceInfoOK) String() string { + return fmt.Sprintf("[POST /collect/collectDeviceInfo][%d] collectDeviceInfoOK %+v", 200, o.Payload) +} + +func (o *CollectDeviceInfoOK) GetPayload() *CollectDeviceInfoOKBody { + return o.Payload +} + +func (o *CollectDeviceInfoOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CollectDeviceInfoOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCollectDeviceInfoDefault creates a CollectDeviceInfoDefault with default headers values +func NewCollectDeviceInfoDefault(code int) *CollectDeviceInfoDefault { + return &CollectDeviceInfoDefault{ + _statusCode: code, + } +} + +/* CollectDeviceInfoDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CollectDeviceInfoDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CollectDeviceInfoDefaultBody +} + +// Code gets the status code for the collect device info default response +func (o *CollectDeviceInfoDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this collect device info default response has a 2xx status code +func (o *CollectDeviceInfoDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this collect device info default response has a 3xx status code +func (o *CollectDeviceInfoDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this collect device info default response has a 4xx status code +func (o *CollectDeviceInfoDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this collect device info default response has a 5xx status code +func (o *CollectDeviceInfoDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this collect device info default response a status code equal to that given +func (o *CollectDeviceInfoDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CollectDeviceInfoDefault) Error() string { + return fmt.Sprintf("[POST /collect/collectDeviceInfo][%d] collectDeviceInfo default %+v", o._statusCode, o.Payload) +} + +func (o *CollectDeviceInfoDefault) String() string { + return fmt.Sprintf("[POST /collect/collectDeviceInfo][%d] collectDeviceInfo default %+v", o._statusCode, o.Payload) +} + +func (o *CollectDeviceInfoDefault) GetPayload() *CollectDeviceInfoDefaultBody { + return o.Payload +} + +func (o *CollectDeviceInfoDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CollectDeviceInfoDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CollectDeviceInfoDefaultBody collect device info default body +swagger:model CollectDeviceInfoDefaultBody +*/ +type CollectDeviceInfoDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this collect device info default body +func (o *CollectDeviceInfoDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CollectDeviceInfoDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("collectDeviceInfo default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CollectDeviceInfoDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("collectDeviceInfo default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("collectDeviceInfo default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("collectDeviceInfo default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this collect device info default body based on the context it is used +func (o *CollectDeviceInfoDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CollectDeviceInfoDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("collectDeviceInfo default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("collectDeviceInfo default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CollectDeviceInfoDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CollectDeviceInfoDefaultBody) UnmarshalBinary(b []byte) error { + var res CollectDeviceInfoDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CollectDeviceInfoOKBody collect device info o k body +swagger:model CollectDeviceInfoOKBody +*/ +type CollectDeviceInfoOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this collect device info o k body +func (o *CollectDeviceInfoOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CollectDeviceInfoOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("collectDeviceInfoOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("collectDeviceInfoOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this collect device info o k body based on the context it is used +func (o *CollectDeviceInfoOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CollectDeviceInfoOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("collectDeviceInfoOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("collectDeviceInfoOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CollectDeviceInfoOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CollectDeviceInfoOKBody) UnmarshalBinary(b []byte) error { + var res CollectDeviceInfoOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/create_device_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/create_device_parameters.go new file mode 100644 index 0000000..293324b --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/create_device_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateDeviceParams creates a new CreateDeviceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateDeviceParams() *CreateDeviceParams { + return &CreateDeviceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateDeviceParamsWithTimeout creates a new CreateDeviceParams object +// with the ability to set a timeout on a request. +func NewCreateDeviceParamsWithTimeout(timeout time.Duration) *CreateDeviceParams { + return &CreateDeviceParams{ + timeout: timeout, + } +} + +// NewCreateDeviceParamsWithContext creates a new CreateDeviceParams object +// with the ability to set a context for a request. +func NewCreateDeviceParamsWithContext(ctx context.Context) *CreateDeviceParams { + return &CreateDeviceParams{ + Context: ctx, + } +} + +// NewCreateDeviceParamsWithHTTPClient creates a new CreateDeviceParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateDeviceParamsWithHTTPClient(client *http.Client) *CreateDeviceParams { + return &CreateDeviceParams{ + HTTPClient: client, + } +} + +/* CreateDeviceParams contains all the parameters to send to the API endpoint + for the create device operation. + + Typically these are written to a http.Request. +*/ +type CreateDeviceParams struct { + + // Body. + Body *models.CreateDevicesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateDeviceParams) WithDefaults() *CreateDeviceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateDeviceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create device params +func (o *CreateDeviceParams) WithTimeout(timeout time.Duration) *CreateDeviceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create device params +func (o *CreateDeviceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create device params +func (o *CreateDeviceParams) WithContext(ctx context.Context) *CreateDeviceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create device params +func (o *CreateDeviceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create device params +func (o *CreateDeviceParams) WithHTTPClient(client *http.Client) *CreateDeviceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create device params +func (o *CreateDeviceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create device params +func (o *CreateDeviceParams) WithBody(body *models.CreateDevicesRequest) *CreateDeviceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create device params +func (o *CreateDeviceParams) SetBody(body *models.CreateDevicesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create device params +func (o *CreateDeviceParams) WithAuthorization(authorization string) *CreateDeviceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create device params +func (o *CreateDeviceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create device params +func (o *CreateDeviceParams) WithBmpLanguage(bmpLanguage *string) *CreateDeviceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create device params +func (o *CreateDeviceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create device params +func (o *CreateDeviceParams) WithBmpUserID(bmpUserID *string) *CreateDeviceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create device params +func (o *CreateDeviceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create device params +func (o *CreateDeviceParams) WithTraceID(traceID string) *CreateDeviceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create device params +func (o *CreateDeviceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/create_device_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/create_device_responses.go new file mode 100644 index 0000000..dced3c9 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/create_device_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateDeviceReader is a Reader for the CreateDevice structure. +type CreateDeviceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateDeviceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateDeviceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateDeviceOK creates a CreateDeviceOK with default headers values +func NewCreateDeviceOK() *CreateDeviceOK { + return &CreateDeviceOK{} +} + +/* CreateDeviceOK describes a response with status code 200, with default header values. + +CreateDeviceOK create device o k +*/ +type CreateDeviceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateDeviceOKBody +} + +// IsSuccess returns true when this create device o k response has a 2xx status code +func (o *CreateDeviceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create device o k response has a 3xx status code +func (o *CreateDeviceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create device o k response has a 4xx status code +func (o *CreateDeviceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create device o k response has a 5xx status code +func (o *CreateDeviceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create device o k response a status code equal to that given +func (o *CreateDeviceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateDeviceOK) Error() string { + return fmt.Sprintf("[POST /devices][%d] createDeviceOK %+v", 200, o.Payload) +} + +func (o *CreateDeviceOK) String() string { + return fmt.Sprintf("[POST /devices][%d] createDeviceOK %+v", 200, o.Payload) +} + +func (o *CreateDeviceOK) GetPayload() *CreateDeviceOKBody { + return o.Payload +} + +func (o *CreateDeviceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateDeviceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateDeviceDefault creates a CreateDeviceDefault with default headers values +func NewCreateDeviceDefault(code int) *CreateDeviceDefault { + return &CreateDeviceDefault{ + _statusCode: code, + } +} + +/* CreateDeviceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateDeviceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateDeviceDefaultBody +} + +// Code gets the status code for the create device default response +func (o *CreateDeviceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create device default response has a 2xx status code +func (o *CreateDeviceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create device default response has a 3xx status code +func (o *CreateDeviceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create device default response has a 4xx status code +func (o *CreateDeviceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create device default response has a 5xx status code +func (o *CreateDeviceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create device default response a status code equal to that given +func (o *CreateDeviceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateDeviceDefault) Error() string { + return fmt.Sprintf("[POST /devices][%d] createDevice default %+v", o._statusCode, o.Payload) +} + +func (o *CreateDeviceDefault) String() string { + return fmt.Sprintf("[POST /devices][%d] createDevice default %+v", o._statusCode, o.Payload) +} + +func (o *CreateDeviceDefault) GetPayload() *CreateDeviceDefaultBody { + return o.Payload +} + +func (o *CreateDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateDeviceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateDeviceDefaultBody create device default body +swagger:model CreateDeviceDefaultBody +*/ +type CreateDeviceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create device default body +func (o *CreateDeviceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createDevice default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateDeviceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createDevice default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create device default body based on the context it is used +func (o *CreateDeviceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateDeviceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateDeviceDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateDeviceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateDeviceOKBody create device o k body +swagger:model CreateDeviceOKBody +*/ +type CreateDeviceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this create device o k body +func (o *CreateDeviceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create device o k body based on the context it is used +func (o *CreateDeviceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateDeviceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateDeviceOKBody) UnmarshalBinary(b []byte) error { + var res CreateDeviceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/delete_device_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/delete_device_parameters.go new file mode 100644 index 0000000..9736479 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/delete_device_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteDeviceParams creates a new DeleteDeviceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteDeviceParams() *DeleteDeviceParams { + return &DeleteDeviceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteDeviceParamsWithTimeout creates a new DeleteDeviceParams object +// with the ability to set a timeout on a request. +func NewDeleteDeviceParamsWithTimeout(timeout time.Duration) *DeleteDeviceParams { + return &DeleteDeviceParams{ + timeout: timeout, + } +} + +// NewDeleteDeviceParamsWithContext creates a new DeleteDeviceParams object +// with the ability to set a context for a request. +func NewDeleteDeviceParamsWithContext(ctx context.Context) *DeleteDeviceParams { + return &DeleteDeviceParams{ + Context: ctx, + } +} + +// NewDeleteDeviceParamsWithHTTPClient creates a new DeleteDeviceParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteDeviceParamsWithHTTPClient(client *http.Client) *DeleteDeviceParams { + return &DeleteDeviceParams{ + HTTPClient: client, + } +} + +/* DeleteDeviceParams contains all the parameters to send to the API endpoint + for the delete device operation. + + Typically these are written to a http.Request. +*/ +type DeleteDeviceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // DeviceID. + DeviceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteDeviceParams) WithDefaults() *DeleteDeviceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteDeviceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete device params +func (o *DeleteDeviceParams) WithTimeout(timeout time.Duration) *DeleteDeviceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete device params +func (o *DeleteDeviceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete device params +func (o *DeleteDeviceParams) WithContext(ctx context.Context) *DeleteDeviceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete device params +func (o *DeleteDeviceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete device params +func (o *DeleteDeviceParams) WithHTTPClient(client *http.Client) *DeleteDeviceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete device params +func (o *DeleteDeviceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete device params +func (o *DeleteDeviceParams) WithAuthorization(authorization string) *DeleteDeviceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete device params +func (o *DeleteDeviceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete device params +func (o *DeleteDeviceParams) WithBmpLanguage(bmpLanguage *string) *DeleteDeviceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete device params +func (o *DeleteDeviceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete device params +func (o *DeleteDeviceParams) WithBmpUserID(bmpUserID *string) *DeleteDeviceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete device params +func (o *DeleteDeviceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceID adds the deviceID to the delete device params +func (o *DeleteDeviceParams) WithDeviceID(deviceID string) *DeleteDeviceParams { + o.SetDeviceID(deviceID) + return o +} + +// SetDeviceID adds the deviceId to the delete device params +func (o *DeleteDeviceParams) SetDeviceID(deviceID string) { + o.DeviceID = deviceID +} + +// WithTraceID adds the traceID to the delete device params +func (o *DeleteDeviceParams) WithTraceID(traceID string) *DeleteDeviceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete device params +func (o *DeleteDeviceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_id + if err := r.SetPathParam("device_id", o.DeviceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/delete_device_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/delete_device_responses.go new file mode 100644 index 0000000..084a18d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/delete_device_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteDeviceReader is a Reader for the DeleteDevice structure. +type DeleteDeviceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteDeviceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteDeviceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteDeviceOK creates a DeleteDeviceOK with default headers values +func NewDeleteDeviceOK() *DeleteDeviceOK { + return &DeleteDeviceOK{} +} + +/* DeleteDeviceOK describes a response with status code 200, with default header values. + +A DeleteDeviceResult is an response struct that is used to describe delete device result. +*/ +type DeleteDeviceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteDeviceOKBody +} + +// IsSuccess returns true when this delete device o k response has a 2xx status code +func (o *DeleteDeviceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete device o k response has a 3xx status code +func (o *DeleteDeviceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete device o k response has a 4xx status code +func (o *DeleteDeviceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete device o k response has a 5xx status code +func (o *DeleteDeviceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete device o k response a status code equal to that given +func (o *DeleteDeviceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteDeviceOK) Error() string { + return fmt.Sprintf("[DELETE /devices/{device_id}][%d] deleteDeviceOK %+v", 200, o.Payload) +} + +func (o *DeleteDeviceOK) String() string { + return fmt.Sprintf("[DELETE /devices/{device_id}][%d] deleteDeviceOK %+v", 200, o.Payload) +} + +func (o *DeleteDeviceOK) GetPayload() *DeleteDeviceOKBody { + return o.Payload +} + +func (o *DeleteDeviceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteDeviceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteDeviceDefault creates a DeleteDeviceDefault with default headers values +func NewDeleteDeviceDefault(code int) *DeleteDeviceDefault { + return &DeleteDeviceDefault{ + _statusCode: code, + } +} + +/* DeleteDeviceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteDeviceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteDeviceDefaultBody +} + +// Code gets the status code for the delete device default response +func (o *DeleteDeviceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete device default response has a 2xx status code +func (o *DeleteDeviceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete device default response has a 3xx status code +func (o *DeleteDeviceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete device default response has a 4xx status code +func (o *DeleteDeviceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete device default response has a 5xx status code +func (o *DeleteDeviceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete device default response a status code equal to that given +func (o *DeleteDeviceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteDeviceDefault) Error() string { + return fmt.Sprintf("[DELETE /devices/{device_id}][%d] deleteDevice default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteDeviceDefault) String() string { + return fmt.Sprintf("[DELETE /devices/{device_id}][%d] deleteDevice default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteDeviceDefault) GetPayload() *DeleteDeviceDefaultBody { + return o.Payload +} + +func (o *DeleteDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteDeviceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteDeviceDefaultBody delete device default body +swagger:model DeleteDeviceDefaultBody +*/ +type DeleteDeviceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete device default body +func (o *DeleteDeviceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteDevice default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteDeviceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteDevice default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete device default body based on the context it is used +func (o *DeleteDeviceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteDeviceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteDeviceDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteDeviceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteDeviceOKBody delete device o k body +swagger:model DeleteDeviceOKBody +*/ +type DeleteDeviceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete device o k body +func (o *DeleteDeviceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete device o k body based on the context it is used +func (o *DeleteDeviceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteDeviceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteDeviceOKBody) UnmarshalBinary(b []byte) error { + var res DeleteDeviceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_parameters.go new file mode 100644 index 0000000..7c7e31e --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeDeviceParams creates a new DescribeDeviceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceParams() *DescribeDeviceParams { + return &DescribeDeviceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceParamsWithTimeout creates a new DescribeDeviceParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceParamsWithTimeout(timeout time.Duration) *DescribeDeviceParams { + return &DescribeDeviceParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceParamsWithContext creates a new DescribeDeviceParams object +// with the ability to set a context for a request. +func NewDescribeDeviceParamsWithContext(ctx context.Context) *DescribeDeviceParams { + return &DescribeDeviceParams{ + Context: ctx, + } +} + +// NewDescribeDeviceParamsWithHTTPClient creates a new DescribeDeviceParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceParamsWithHTTPClient(client *http.Client) *DescribeDeviceParams { + return &DescribeDeviceParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceParams contains all the parameters to send to the API endpoint + for the describe device operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // DeviceID. + DeviceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceParams) WithDefaults() *DescribeDeviceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device params +func (o *DescribeDeviceParams) WithTimeout(timeout time.Duration) *DescribeDeviceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device params +func (o *DescribeDeviceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device params +func (o *DescribeDeviceParams) WithContext(ctx context.Context) *DescribeDeviceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device params +func (o *DescribeDeviceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device params +func (o *DescribeDeviceParams) WithHTTPClient(client *http.Client) *DescribeDeviceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device params +func (o *DescribeDeviceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device params +func (o *DescribeDeviceParams) WithAuthorization(authorization string) *DescribeDeviceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device params +func (o *DescribeDeviceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device params +func (o *DescribeDeviceParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device params +func (o *DescribeDeviceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device params +func (o *DescribeDeviceParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device params +func (o *DescribeDeviceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceID adds the deviceID to the describe device params +func (o *DescribeDeviceParams) WithDeviceID(deviceID string) *DescribeDeviceParams { + o.SetDeviceID(deviceID) + return o +} + +// SetDeviceID adds the deviceId to the describe device params +func (o *DescribeDeviceParams) SetDeviceID(deviceID string) { + o.DeviceID = deviceID +} + +// WithTraceID adds the traceID to the describe device params +func (o *DescribeDeviceParams) WithTraceID(traceID string) *DescribeDeviceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device params +func (o *DescribeDeviceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_id + if err := r.SetPathParam("device_id", o.DeviceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_responses.go new file mode 100644 index 0000000..d28bf8d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDeviceReader is a Reader for the DescribeDevice structure. +type DescribeDeviceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceOK creates a DescribeDeviceOK with default headers values +func NewDescribeDeviceOK() *DescribeDeviceOK { + return &DescribeDeviceOK{} +} + +/* DescribeDeviceOK describes a response with status code 200, with default header values. + +DescribeDeviceOK describe device o k +*/ +type DescribeDeviceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceOKBody +} + +// IsSuccess returns true when this describe device o k response has a 2xx status code +func (o *DescribeDeviceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device o k response has a 3xx status code +func (o *DescribeDeviceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device o k response has a 4xx status code +func (o *DescribeDeviceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device o k response has a 5xx status code +func (o *DescribeDeviceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device o k response a status code equal to that given +func (o *DescribeDeviceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceOK) Error() string { + return fmt.Sprintf("[GET /devices/{device_id}][%d] describeDeviceOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceOK) String() string { + return fmt.Sprintf("[GET /devices/{device_id}][%d] describeDeviceOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceOK) GetPayload() *DescribeDeviceOKBody { + return o.Payload +} + +func (o *DescribeDeviceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceDefault creates a DescribeDeviceDefault with default headers values +func NewDescribeDeviceDefault(code int) *DescribeDeviceDefault { + return &DescribeDeviceDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceDefaultBody +} + +// Code gets the status code for the describe device default response +func (o *DescribeDeviceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device default response has a 2xx status code +func (o *DescribeDeviceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device default response has a 3xx status code +func (o *DescribeDeviceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device default response has a 4xx status code +func (o *DescribeDeviceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device default response has a 5xx status code +func (o *DescribeDeviceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device default response a status code equal to that given +func (o *DescribeDeviceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceDefault) Error() string { + return fmt.Sprintf("[GET /devices/{device_id}][%d] describeDevice default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceDefault) String() string { + return fmt.Sprintf("[GET /devices/{device_id}][%d] describeDevice default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceDefault) GetPayload() *DescribeDeviceDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceDefaultBody describe device default body +swagger:model DescribeDeviceDefaultBody +*/ +type DescribeDeviceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device default body +func (o *DescribeDeviceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDevice default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDevice default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device default body based on the context it is used +func (o *DescribeDeviceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceOKBody describe device o k body +swagger:model DescribeDeviceOKBody +*/ +type DescribeDeviceOKBody struct { + + // result + Result *models.DeviceInfo `json:"result,omitempty"` +} + +// Validate validates this describe device o k body +func (o *DescribeDeviceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device o k body based on the context it is used +func (o *DescribeDeviceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_stock_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_stock_parameters.go new file mode 100644 index 0000000..66c5c8f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_stock_parameters.go @@ -0,0 +1,252 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeDeviceStockParams creates a new DescribeDeviceStockParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceStockParams() *DescribeDeviceStockParams { + return &DescribeDeviceStockParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceStockParamsWithTimeout creates a new DescribeDeviceStockParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceStockParamsWithTimeout(timeout time.Duration) *DescribeDeviceStockParams { + return &DescribeDeviceStockParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceStockParamsWithContext creates a new DescribeDeviceStockParams object +// with the ability to set a context for a request. +func NewDescribeDeviceStockParamsWithContext(ctx context.Context) *DescribeDeviceStockParams { + return &DescribeDeviceStockParams{ + Context: ctx, + } +} + +// NewDescribeDeviceStockParamsWithHTTPClient creates a new DescribeDeviceStockParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceStockParamsWithHTTPClient(client *http.Client) *DescribeDeviceStockParams { + return &DescribeDeviceStockParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceStockParams contains all the parameters to send to the API endpoint + for the describe device stock operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceStockParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // DeviceTypeID. + DeviceTypeID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device stock params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceStockParams) WithDefaults() *DescribeDeviceStockParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device stock params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceStockParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device stock params +func (o *DescribeDeviceStockParams) WithTimeout(timeout time.Duration) *DescribeDeviceStockParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device stock params +func (o *DescribeDeviceStockParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device stock params +func (o *DescribeDeviceStockParams) WithContext(ctx context.Context) *DescribeDeviceStockParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device stock params +func (o *DescribeDeviceStockParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device stock params +func (o *DescribeDeviceStockParams) WithHTTPClient(client *http.Client) *DescribeDeviceStockParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device stock params +func (o *DescribeDeviceStockParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device stock params +func (o *DescribeDeviceStockParams) WithAuthorization(authorization string) *DescribeDeviceStockParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device stock params +func (o *DescribeDeviceStockParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device stock params +func (o *DescribeDeviceStockParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceStockParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device stock params +func (o *DescribeDeviceStockParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device stock params +func (o *DescribeDeviceStockParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceStockParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device stock params +func (o *DescribeDeviceStockParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device stock params +func (o *DescribeDeviceStockParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDeviceStockParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device stock params +func (o *DescribeDeviceStockParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithTraceID adds the traceID to the describe device stock params +func (o *DescribeDeviceStockParams) WithTraceID(traceID string) *DescribeDeviceStockParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device stock params +func (o *DescribeDeviceStockParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceStockParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_stock_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_stock_responses.go new file mode 100644 index 0000000..74d726b --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_device_stock_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDeviceStockReader is a Reader for the DescribeDeviceStock structure. +type DescribeDeviceStockReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceStockReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceStockOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceStockDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceStockOK creates a DescribeDeviceStockOK with default headers values +func NewDescribeDeviceStockOK() *DescribeDeviceStockOK { + return &DescribeDeviceStockOK{} +} + +/* DescribeDeviceStockOK describes a response with status code 200, with default header values. + +A GetDeviceStockResult is an response struct that is used to get device stock. +*/ +type DescribeDeviceStockOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceStockOKBody +} + +// IsSuccess returns true when this describe device stock o k response has a 2xx status code +func (o *DescribeDeviceStockOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device stock o k response has a 3xx status code +func (o *DescribeDeviceStockOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device stock o k response has a 4xx status code +func (o *DescribeDeviceStockOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device stock o k response has a 5xx status code +func (o *DescribeDeviceStockOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device stock o k response a status code equal to that given +func (o *DescribeDeviceStockOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceStockOK) Error() string { + return fmt.Sprintf("[DELETE /devices/stock][%d] describeDeviceStockOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceStockOK) String() string { + return fmt.Sprintf("[DELETE /devices/stock][%d] describeDeviceStockOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceStockOK) GetPayload() *DescribeDeviceStockOKBody { + return o.Payload +} + +func (o *DescribeDeviceStockOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceStockOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceStockDefault creates a DescribeDeviceStockDefault with default headers values +func NewDescribeDeviceStockDefault(code int) *DescribeDeviceStockDefault { + return &DescribeDeviceStockDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceStockDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceStockDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceStockDefaultBody +} + +// Code gets the status code for the describe device stock default response +func (o *DescribeDeviceStockDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device stock default response has a 2xx status code +func (o *DescribeDeviceStockDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device stock default response has a 3xx status code +func (o *DescribeDeviceStockDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device stock default response has a 4xx status code +func (o *DescribeDeviceStockDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device stock default response has a 5xx status code +func (o *DescribeDeviceStockDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device stock default response a status code equal to that given +func (o *DescribeDeviceStockDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceStockDefault) Error() string { + return fmt.Sprintf("[DELETE /devices/stock][%d] describeDeviceStock default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceStockDefault) String() string { + return fmt.Sprintf("[DELETE /devices/stock][%d] describeDeviceStock default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceStockDefault) GetPayload() *DescribeDeviceStockDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceStockDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceStockDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceStockDefaultBody describe device stock default body +swagger:model DescribeDeviceStockDefaultBody +*/ +type DescribeDeviceStockDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device stock default body +func (o *DescribeDeviceStockDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceStockDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceStock default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceStockDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceStock default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceStock default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceStock default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device stock default body based on the context it is used +func (o *DescribeDeviceStockDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceStockDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceStock default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceStock default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceStockDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceStockDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceStockDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceStockOKBody describe device stock o k body +swagger:model DescribeDeviceStockOKBody +*/ +type DescribeDeviceStockOKBody struct { + + // result + Result *models.DeviceStock `json:"result,omitempty"` +} + +// Validate validates this describe device stock o k body +func (o *DescribeDeviceStockOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceStockOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceStockOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceStockOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device stock o k body based on the context it is used +func (o *DescribeDeviceStockOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceStockOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceStockOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceStockOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceStockOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceStockOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceStockOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_devices_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_devices_parameters.go new file mode 100644 index 0000000..7cad12d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_devices_parameters.go @@ -0,0 +1,736 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeDevicesParams creates a new DescribeDevicesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDevicesParams() *DescribeDevicesParams { + return &DescribeDevicesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDevicesParamsWithTimeout creates a new DescribeDevicesParams object +// with the ability to set a timeout on a request. +func NewDescribeDevicesParamsWithTimeout(timeout time.Duration) *DescribeDevicesParams { + return &DescribeDevicesParams{ + timeout: timeout, + } +} + +// NewDescribeDevicesParamsWithContext creates a new DescribeDevicesParams object +// with the ability to set a context for a request. +func NewDescribeDevicesParamsWithContext(ctx context.Context) *DescribeDevicesParams { + return &DescribeDevicesParams{ + Context: ctx, + } +} + +// NewDescribeDevicesParamsWithHTTPClient creates a new DescribeDevicesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDevicesParamsWithHTTPClient(client *http.Client) *DescribeDevicesParams { + return &DescribeDevicesParams{ + HTTPClient: client, + } +} + +/* DescribeDevicesParams contains all the parameters to send to the API endpoint + for the describe devices operation. + + Typically these are written to a http.Request. +*/ +type DescribeDevicesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceSeries. + + 机型类型 + */ + DeviceSeries *string + + /* DeviceTypeID. + + 机型id + */ + DeviceTypeID *string + + /* IdcID. + + 机房id + */ + IDcID *string + + /* IloIP. + + 带外ip + */ + IloIP *string + + /* InstanceID. + + 实例id + */ + InstanceID *string + + /* InstanceName. + + 实例名称 + */ + InstanceName *string + + /* IPV4. + + ipv4 + */ + IPV4 *string + + /* IPV6. + + ipv6 + */ + IPV6 *string + + /* IsAll. + + 是否显示全部,1不分页 + */ + IsAll *string + + /* ManageStatus. + + 设备管理状态 + */ + ManageStatus *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* Sn. + + 设备sn + */ + Sn *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserID. + + 所属用户id + */ + UserID *string + + /* UserName. + + 所属用户 + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe devices params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDevicesParams) WithDefaults() *DescribeDevicesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe devices params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDevicesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe devices params +func (o *DescribeDevicesParams) WithTimeout(timeout time.Duration) *DescribeDevicesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe devices params +func (o *DescribeDevicesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe devices params +func (o *DescribeDevicesParams) WithContext(ctx context.Context) *DescribeDevicesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe devices params +func (o *DescribeDevicesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe devices params +func (o *DescribeDevicesParams) WithHTTPClient(client *http.Client) *DescribeDevicesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe devices params +func (o *DescribeDevicesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe devices params +func (o *DescribeDevicesParams) WithAuthorization(authorization string) *DescribeDevicesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe devices params +func (o *DescribeDevicesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe devices params +func (o *DescribeDevicesParams) WithBmpLanguage(bmpLanguage *string) *DescribeDevicesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe devices params +func (o *DescribeDevicesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe devices params +func (o *DescribeDevicesParams) WithBmpUserID(bmpUserID *string) *DescribeDevicesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe devices params +func (o *DescribeDevicesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceSeries adds the deviceSeries to the describe devices params +func (o *DescribeDevicesParams) WithDeviceSeries(deviceSeries *string) *DescribeDevicesParams { + o.SetDeviceSeries(deviceSeries) + return o +} + +// SetDeviceSeries adds the deviceSeries to the describe devices params +func (o *DescribeDevicesParams) SetDeviceSeries(deviceSeries *string) { + o.DeviceSeries = deviceSeries +} + +// WithDeviceTypeID adds the deviceTypeID to the describe devices params +func (o *DescribeDevicesParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDevicesParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe devices params +func (o *DescribeDevicesParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithIDcID adds the idcID to the describe devices params +func (o *DescribeDevicesParams) WithIDcID(idcID *string) *DescribeDevicesParams { + o.SetIDcID(idcID) + return o +} + +// SetIDcID adds the idcId to the describe devices params +func (o *DescribeDevicesParams) SetIDcID(idcID *string) { + o.IDcID = idcID +} + +// WithIloIP adds the iloIP to the describe devices params +func (o *DescribeDevicesParams) WithIloIP(iloIP *string) *DescribeDevicesParams { + o.SetIloIP(iloIP) + return o +} + +// SetIloIP adds the iloIp to the describe devices params +func (o *DescribeDevicesParams) SetIloIP(iloIP *string) { + o.IloIP = iloIP +} + +// WithInstanceID adds the instanceID to the describe devices params +func (o *DescribeDevicesParams) WithInstanceID(instanceID *string) *DescribeDevicesParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the describe devices params +func (o *DescribeDevicesParams) SetInstanceID(instanceID *string) { + o.InstanceID = instanceID +} + +// WithInstanceName adds the instanceName to the describe devices params +func (o *DescribeDevicesParams) WithInstanceName(instanceName *string) *DescribeDevicesParams { + o.SetInstanceName(instanceName) + return o +} + +// SetInstanceName adds the instanceName to the describe devices params +func (o *DescribeDevicesParams) SetInstanceName(instanceName *string) { + o.InstanceName = instanceName +} + +// WithIPV4 adds the iPV4 to the describe devices params +func (o *DescribeDevicesParams) WithIPV4(iPV4 *string) *DescribeDevicesParams { + o.SetIPV4(iPV4) + return o +} + +// SetIPV4 adds the ipv4 to the describe devices params +func (o *DescribeDevicesParams) SetIPV4(iPV4 *string) { + o.IPV4 = iPV4 +} + +// WithIPV6 adds the iPV6 to the describe devices params +func (o *DescribeDevicesParams) WithIPV6(iPV6 *string) *DescribeDevicesParams { + o.SetIPV6(iPV6) + return o +} + +// SetIPV6 adds the ipv6 to the describe devices params +func (o *DescribeDevicesParams) SetIPV6(iPV6 *string) { + o.IPV6 = iPV6 +} + +// WithIsAll adds the isAll to the describe devices params +func (o *DescribeDevicesParams) WithIsAll(isAll *string) *DescribeDevicesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe devices params +func (o *DescribeDevicesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithManageStatus adds the manageStatus to the describe devices params +func (o *DescribeDevicesParams) WithManageStatus(manageStatus *string) *DescribeDevicesParams { + o.SetManageStatus(manageStatus) + return o +} + +// SetManageStatus adds the manageStatus to the describe devices params +func (o *DescribeDevicesParams) SetManageStatus(manageStatus *string) { + o.ManageStatus = manageStatus +} + +// WithPageNumber adds the pageNumber to the describe devices params +func (o *DescribeDevicesParams) WithPageNumber(pageNumber *int64) *DescribeDevicesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe devices params +func (o *DescribeDevicesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe devices params +func (o *DescribeDevicesParams) WithPageSize(pageSize *int64) *DescribeDevicesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe devices params +func (o *DescribeDevicesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithSn adds the sn to the describe devices params +func (o *DescribeDevicesParams) WithSn(sn *string) *DescribeDevicesParams { + o.SetSn(sn) + return o +} + +// SetSn adds the sn to the describe devices params +func (o *DescribeDevicesParams) SetSn(sn *string) { + o.Sn = sn +} + +// WithTraceID adds the traceID to the describe devices params +func (o *DescribeDevicesParams) WithTraceID(traceID string) *DescribeDevicesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe devices params +func (o *DescribeDevicesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserID adds the userID to the describe devices params +func (o *DescribeDevicesParams) WithUserID(userID *string) *DescribeDevicesParams { + o.SetUserID(userID) + return o +} + +// SetUserID adds the userId to the describe devices params +func (o *DescribeDevicesParams) SetUserID(userID *string) { + o.UserID = userID +} + +// WithUserName adds the userName to the describe devices params +func (o *DescribeDevicesParams) WithUserName(userName *string) *DescribeDevicesParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe devices params +func (o *DescribeDevicesParams) SetUserName(userName *string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDevicesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceSeries != nil { + + // query param deviceSeries + var qrDeviceSeries string + + if o.DeviceSeries != nil { + qrDeviceSeries = *o.DeviceSeries + } + qDeviceSeries := qrDeviceSeries + if qDeviceSeries != "" { + + if err := r.SetQueryParam("deviceSeries", qDeviceSeries); err != nil { + return err + } + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.IDcID != nil { + + // query param idcId + var qrIdcID string + + if o.IDcID != nil { + qrIdcID = *o.IDcID + } + qIdcID := qrIdcID + if qIdcID != "" { + + if err := r.SetQueryParam("idcId", qIdcID); err != nil { + return err + } + } + } + + if o.IloIP != nil { + + // query param iloIp + var qrIloIP string + + if o.IloIP != nil { + qrIloIP = *o.IloIP + } + qIloIP := qrIloIP + if qIloIP != "" { + + if err := r.SetQueryParam("iloIp", qIloIP); err != nil { + return err + } + } + } + + if o.InstanceID != nil { + + // query param instanceId + var qrInstanceID string + + if o.InstanceID != nil { + qrInstanceID = *o.InstanceID + } + qInstanceID := qrInstanceID + if qInstanceID != "" { + + if err := r.SetQueryParam("instanceId", qInstanceID); err != nil { + return err + } + } + } + + if o.InstanceName != nil { + + // query param instanceName + var qrInstanceName string + + if o.InstanceName != nil { + qrInstanceName = *o.InstanceName + } + qInstanceName := qrInstanceName + if qInstanceName != "" { + + if err := r.SetQueryParam("instanceName", qInstanceName); err != nil { + return err + } + } + } + + if o.IPV4 != nil { + + // query param ipv4 + var qrIPV4 string + + if o.IPV4 != nil { + qrIPV4 = *o.IPV4 + } + qIPV4 := qrIPV4 + if qIPV4 != "" { + + if err := r.SetQueryParam("ipv4", qIPV4); err != nil { + return err + } + } + } + + if o.IPV6 != nil { + + // query param ipv6 + var qrIPV6 string + + if o.IPV6 != nil { + qrIPV6 = *o.IPV6 + } + qIPV6 := qrIPV6 + if qIPV6 != "" { + + if err := r.SetQueryParam("ipv6", qIPV6); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.ManageStatus != nil { + + // query param manageStatus + var qrManageStatus string + + if o.ManageStatus != nil { + qrManageStatus = *o.ManageStatus + } + qManageStatus := qrManageStatus + if qManageStatus != "" { + + if err := r.SetQueryParam("manageStatus", qManageStatus); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.Sn != nil { + + // query param sn + var qrSn string + + if o.Sn != nil { + qrSn = *o.Sn + } + qSn := qrSn + if qSn != "" { + + if err := r.SetQueryParam("sn", qSn); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserID != nil { + + // query param userId + var qrUserID string + + if o.UserID != nil { + qrUserID = *o.UserID + } + qUserID := qrUserID + if qUserID != "" { + + if err := r.SetQueryParam("userId", qUserID); err != nil { + return err + } + } + } + + if o.UserName != nil { + + // query param userName + var qrUserName string + + if o.UserName != nil { + qrUserName = *o.UserName + } + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_devices_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_devices_responses.go new file mode 100644 index 0000000..0c42cca --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/describe_devices_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDevicesReader is a Reader for the DescribeDevices structure. +type DescribeDevicesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDevicesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDevicesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDevicesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDevicesOK creates a DescribeDevicesOK with default headers values +func NewDescribeDevicesOK() *DescribeDevicesOK { + return &DescribeDevicesOK{} +} + +/* DescribeDevicesOK describes a response with status code 200, with default header values. + +DescribeDevicesOK describe devices o k +*/ +type DescribeDevicesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDevicesOKBody +} + +// IsSuccess returns true when this describe devices o k response has a 2xx status code +func (o *DescribeDevicesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe devices o k response has a 3xx status code +func (o *DescribeDevicesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe devices o k response has a 4xx status code +func (o *DescribeDevicesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe devices o k response has a 5xx status code +func (o *DescribeDevicesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe devices o k response a status code equal to that given +func (o *DescribeDevicesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDevicesOK) Error() string { + return fmt.Sprintf("[GET /devices][%d] describeDevicesOK %+v", 200, o.Payload) +} + +func (o *DescribeDevicesOK) String() string { + return fmt.Sprintf("[GET /devices][%d] describeDevicesOK %+v", 200, o.Payload) +} + +func (o *DescribeDevicesOK) GetPayload() *DescribeDevicesOKBody { + return o.Payload +} + +func (o *DescribeDevicesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDevicesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDevicesDefault creates a DescribeDevicesDefault with default headers values +func NewDescribeDevicesDefault(code int) *DescribeDevicesDefault { + return &DescribeDevicesDefault{ + _statusCode: code, + } +} + +/* DescribeDevicesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDevicesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDevicesDefaultBody +} + +// Code gets the status code for the describe devices default response +func (o *DescribeDevicesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe devices default response has a 2xx status code +func (o *DescribeDevicesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe devices default response has a 3xx status code +func (o *DescribeDevicesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe devices default response has a 4xx status code +func (o *DescribeDevicesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe devices default response has a 5xx status code +func (o *DescribeDevicesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe devices default response a status code equal to that given +func (o *DescribeDevicesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDevicesDefault) Error() string { + return fmt.Sprintf("[GET /devices][%d] describeDevices default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDevicesDefault) String() string { + return fmt.Sprintf("[GET /devices][%d] describeDevices default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDevicesDefault) GetPayload() *DescribeDevicesDefaultBody { + return o.Payload +} + +func (o *DescribeDevicesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDevicesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDevicesDefaultBody describe devices default body +swagger:model DescribeDevicesDefaultBody +*/ +type DescribeDevicesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe devices default body +func (o *DescribeDevicesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDevicesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDevices default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDevicesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDevices default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevices default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevices default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe devices default body based on the context it is used +func (o *DescribeDevicesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDevicesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevices default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevices default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDevicesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDevicesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDevicesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDevicesOKBody describe devices o k body +swagger:model DescribeDevicesOKBody +*/ +type DescribeDevicesOKBody struct { + + // result + Result *models.DeviceList `json:"result,omitempty"` +} + +// Validate validates this describe devices o k body +func (o *DescribeDevicesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDevicesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevicesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevicesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe devices o k body based on the context it is used +func (o *DescribeDevicesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDevicesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDevicesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDevicesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDevicesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDevicesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDevicesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/device_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/device_client.go new file mode 100644 index 0000000..f7bdba7 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/device_client.go @@ -0,0 +1,397 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new device API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for device API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateDevice(params *CreateDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateDeviceOK, error) + + DeleteDevice(params *DeleteDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteDeviceOK, error) + + DescribeDevice(params *DescribeDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceOK, error) + + DescribeDeviceStock(params *DescribeDeviceStockParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceStockOK, error) + + DescribeDevices(params *DescribeDevicesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDevicesOK, error) + + ModifyDevice(params *ModifyDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyDeviceOK, error) + + MountDevice(params *MountDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*MountDeviceOK, error) + + RemoveDevice(params *RemoveDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RemoveDeviceOK, error) + + UnMountDevice(params *UnMountDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UnMountDeviceOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateDevice CreateDevice 创建设备 +*/ +func (a *Client) CreateDevice(params *CreateDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateDeviceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateDeviceParams() + } + op := &runtime.ClientOperation{ + ID: "createDevice", + Method: "POST", + PathPattern: "/devices", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateDeviceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateDeviceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateDeviceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteDevice DeleteDevice 删除设备 +*/ +func (a *Client) DeleteDevice(params *DeleteDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteDeviceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteDeviceParams() + } + op := &runtime.ClientOperation{ + ID: "deleteDevice", + Method: "DELETE", + PathPattern: "/devices/{device_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteDeviceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteDeviceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteDeviceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDevice DescribeDevice 获取设备详情 +*/ +func (a *Client) DescribeDevice(params *DescribeDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceParams() + } + op := &runtime.ClientOperation{ + ID: "describeDevice", + Method: "GET", + PathPattern: "/devices/{device_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceStock DescribeDeviceStock 获取指定机型的设备库存 +*/ +func (a *Client) DescribeDeviceStock(params *DescribeDeviceStockParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceStockOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceStockParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceStock", + Method: "DELETE", + PathPattern: "/devices/stock", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceStockReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceStockOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceStockDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDevices DescribeDevices 获取设备列表 +*/ +func (a *Client) DescribeDevices(params *DescribeDevicesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDevicesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDevicesParams() + } + op := &runtime.ClientOperation{ + ID: "describeDevices", + Method: "GET", + PathPattern: "/devices", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDevicesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDevicesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDevicesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyDevice ModifyDevice 修改设备信息 +*/ +func (a *Client) ModifyDevice(params *ModifyDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyDeviceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyDeviceParams() + } + op := &runtime.ClientOperation{ + ID: "modifyDevice", + Method: "PUT", + PathPattern: "/devices/{device_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyDeviceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyDeviceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyDeviceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + MountDevice MountDevice 设备上架 +*/ +func (a *Client) MountDevice(params *MountDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*MountDeviceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewMountDeviceParams() + } + op := &runtime.ClientOperation{ + ID: "mountDevice", + Method: "PUT", + PathPattern: "/devices/mount", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &MountDeviceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*MountDeviceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*MountDeviceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + RemoveDevice DeleteDevice 移除设备 +*/ +func (a *Client) RemoveDevice(params *RemoveDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RemoveDeviceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewRemoveDeviceParams() + } + op := &runtime.ClientOperation{ + ID: "removeDevice", + Method: "PUT", + PathPattern: "/devices/{device_id}/remove", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &RemoveDeviceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*RemoveDeviceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*RemoveDeviceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + UnMountDevice UnMountDevice 设备下架 +*/ +func (a *Client) UnMountDevice(params *UnMountDeviceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UnMountDeviceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewUnMountDeviceParams() + } + op := &runtime.ClientOperation{ + ID: "unMountDevice", + Method: "PUT", + PathPattern: "/devices/unmount", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UnMountDeviceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*UnMountDeviceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*UnMountDeviceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/modify_device_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/modify_device_parameters.go new file mode 100644 index 0000000..c169994 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/modify_device_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyDeviceParams creates a new ModifyDeviceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyDeviceParams() *ModifyDeviceParams { + return &ModifyDeviceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyDeviceParamsWithTimeout creates a new ModifyDeviceParams object +// with the ability to set a timeout on a request. +func NewModifyDeviceParamsWithTimeout(timeout time.Duration) *ModifyDeviceParams { + return &ModifyDeviceParams{ + timeout: timeout, + } +} + +// NewModifyDeviceParamsWithContext creates a new ModifyDeviceParams object +// with the ability to set a context for a request. +func NewModifyDeviceParamsWithContext(ctx context.Context) *ModifyDeviceParams { + return &ModifyDeviceParams{ + Context: ctx, + } +} + +// NewModifyDeviceParamsWithHTTPClient creates a new ModifyDeviceParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyDeviceParamsWithHTTPClient(client *http.Client) *ModifyDeviceParams { + return &ModifyDeviceParams{ + HTTPClient: client, + } +} + +/* ModifyDeviceParams contains all the parameters to send to the API endpoint + for the modify device operation. + + Typically these are written to a http.Request. +*/ +type ModifyDeviceParams struct { + + // Body. + Body *models.ModifyDevicesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // DeviceID. + DeviceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyDeviceParams) WithDefaults() *ModifyDeviceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyDeviceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify device params +func (o *ModifyDeviceParams) WithTimeout(timeout time.Duration) *ModifyDeviceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify device params +func (o *ModifyDeviceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify device params +func (o *ModifyDeviceParams) WithContext(ctx context.Context) *ModifyDeviceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify device params +func (o *ModifyDeviceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify device params +func (o *ModifyDeviceParams) WithHTTPClient(client *http.Client) *ModifyDeviceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify device params +func (o *ModifyDeviceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify device params +func (o *ModifyDeviceParams) WithBody(body *models.ModifyDevicesRequest) *ModifyDeviceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify device params +func (o *ModifyDeviceParams) SetBody(body *models.ModifyDevicesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify device params +func (o *ModifyDeviceParams) WithAuthorization(authorization string) *ModifyDeviceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify device params +func (o *ModifyDeviceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify device params +func (o *ModifyDeviceParams) WithBmpLanguage(bmpLanguage *string) *ModifyDeviceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify device params +func (o *ModifyDeviceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify device params +func (o *ModifyDeviceParams) WithBmpUserID(bmpUserID *string) *ModifyDeviceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify device params +func (o *ModifyDeviceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceID adds the deviceID to the modify device params +func (o *ModifyDeviceParams) WithDeviceID(deviceID string) *ModifyDeviceParams { + o.SetDeviceID(deviceID) + return o +} + +// SetDeviceID adds the deviceId to the modify device params +func (o *ModifyDeviceParams) SetDeviceID(deviceID string) { + o.DeviceID = deviceID +} + +// WithTraceID adds the traceID to the modify device params +func (o *ModifyDeviceParams) WithTraceID(traceID string) *ModifyDeviceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify device params +func (o *ModifyDeviceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_id + if err := r.SetPathParam("device_id", o.DeviceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/modify_device_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/modify_device_responses.go new file mode 100644 index 0000000..7225eed --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/modify_device_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyDeviceReader is a Reader for the ModifyDevice structure. +type ModifyDeviceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyDeviceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyDeviceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyDeviceOK creates a ModifyDeviceOK with default headers values +func NewModifyDeviceOK() *ModifyDeviceOK { + return &ModifyDeviceOK{} +} + +/* ModifyDeviceOK describes a response with status code 200, with default header values. + +A ModifyDeviceResult is an response struct that is used to describe modify device result. +*/ +type ModifyDeviceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyDeviceOKBody +} + +// IsSuccess returns true when this modify device o k response has a 2xx status code +func (o *ModifyDeviceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify device o k response has a 3xx status code +func (o *ModifyDeviceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify device o k response has a 4xx status code +func (o *ModifyDeviceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify device o k response has a 5xx status code +func (o *ModifyDeviceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify device o k response a status code equal to that given +func (o *ModifyDeviceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyDeviceOK) Error() string { + return fmt.Sprintf("[PUT /devices/{device_id}][%d] modifyDeviceOK %+v", 200, o.Payload) +} + +func (o *ModifyDeviceOK) String() string { + return fmt.Sprintf("[PUT /devices/{device_id}][%d] modifyDeviceOK %+v", 200, o.Payload) +} + +func (o *ModifyDeviceOK) GetPayload() *ModifyDeviceOKBody { + return o.Payload +} + +func (o *ModifyDeviceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyDeviceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyDeviceDefault creates a ModifyDeviceDefault with default headers values +func NewModifyDeviceDefault(code int) *ModifyDeviceDefault { + return &ModifyDeviceDefault{ + _statusCode: code, + } +} + +/* ModifyDeviceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyDeviceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyDeviceDefaultBody +} + +// Code gets the status code for the modify device default response +func (o *ModifyDeviceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify device default response has a 2xx status code +func (o *ModifyDeviceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify device default response has a 3xx status code +func (o *ModifyDeviceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify device default response has a 4xx status code +func (o *ModifyDeviceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify device default response has a 5xx status code +func (o *ModifyDeviceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify device default response a status code equal to that given +func (o *ModifyDeviceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyDeviceDefault) Error() string { + return fmt.Sprintf("[PUT /devices/{device_id}][%d] modifyDevice default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyDeviceDefault) String() string { + return fmt.Sprintf("[PUT /devices/{device_id}][%d] modifyDevice default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyDeviceDefault) GetPayload() *ModifyDeviceDefaultBody { + return o.Payload +} + +func (o *ModifyDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyDeviceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyDeviceDefaultBody modify device default body +swagger:model ModifyDeviceDefaultBody +*/ +type ModifyDeviceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify device default body +func (o *ModifyDeviceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyDevice default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyDeviceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyDevice default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify device default body based on the context it is used +func (o *ModifyDeviceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyDeviceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyDeviceDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyDeviceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyDeviceOKBody modify device o k body +swagger:model ModifyDeviceOKBody +*/ +type ModifyDeviceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify device o k body +func (o *ModifyDeviceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify device o k body based on the context it is used +func (o *ModifyDeviceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyDeviceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyDeviceOKBody) UnmarshalBinary(b []byte) error { + var res ModifyDeviceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/mount_device_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/mount_device_parameters.go new file mode 100644 index 0000000..dbe2352 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/mount_device_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewMountDeviceParams creates a new MountDeviceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewMountDeviceParams() *MountDeviceParams { + return &MountDeviceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewMountDeviceParamsWithTimeout creates a new MountDeviceParams object +// with the ability to set a timeout on a request. +func NewMountDeviceParamsWithTimeout(timeout time.Duration) *MountDeviceParams { + return &MountDeviceParams{ + timeout: timeout, + } +} + +// NewMountDeviceParamsWithContext creates a new MountDeviceParams object +// with the ability to set a context for a request. +func NewMountDeviceParamsWithContext(ctx context.Context) *MountDeviceParams { + return &MountDeviceParams{ + Context: ctx, + } +} + +// NewMountDeviceParamsWithHTTPClient creates a new MountDeviceParams object +// with the ability to set a custom HTTPClient for a request. +func NewMountDeviceParamsWithHTTPClient(client *http.Client) *MountDeviceParams { + return &MountDeviceParams{ + HTTPClient: client, + } +} + +/* MountDeviceParams contains all the parameters to send to the API endpoint + for the mount device operation. + + Typically these are written to a http.Request. +*/ +type MountDeviceParams struct { + + // Body. + Body *models.MountDevicesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the mount device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *MountDeviceParams) WithDefaults() *MountDeviceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the mount device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *MountDeviceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the mount device params +func (o *MountDeviceParams) WithTimeout(timeout time.Duration) *MountDeviceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the mount device params +func (o *MountDeviceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the mount device params +func (o *MountDeviceParams) WithContext(ctx context.Context) *MountDeviceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the mount device params +func (o *MountDeviceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the mount device params +func (o *MountDeviceParams) WithHTTPClient(client *http.Client) *MountDeviceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the mount device params +func (o *MountDeviceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the mount device params +func (o *MountDeviceParams) WithBody(body *models.MountDevicesRequest) *MountDeviceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the mount device params +func (o *MountDeviceParams) SetBody(body *models.MountDevicesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the mount device params +func (o *MountDeviceParams) WithAuthorization(authorization string) *MountDeviceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the mount device params +func (o *MountDeviceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the mount device params +func (o *MountDeviceParams) WithBmpLanguage(bmpLanguage *string) *MountDeviceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the mount device params +func (o *MountDeviceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the mount device params +func (o *MountDeviceParams) WithBmpUserID(bmpUserID *string) *MountDeviceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the mount device params +func (o *MountDeviceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the mount device params +func (o *MountDeviceParams) WithTraceID(traceID string) *MountDeviceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the mount device params +func (o *MountDeviceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *MountDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/mount_device_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/mount_device_responses.go new file mode 100644 index 0000000..53ce48a --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/mount_device_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// MountDeviceReader is a Reader for the MountDevice structure. +type MountDeviceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *MountDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewMountDeviceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewMountDeviceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewMountDeviceOK creates a MountDeviceOK with default headers values +func NewMountDeviceOK() *MountDeviceOK { + return &MountDeviceOK{} +} + +/* MountDeviceOK describes a response with status code 200, with default header values. + +A MountDeviceResult is an response struct that is used to describe mount device result. +*/ +type MountDeviceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *MountDeviceOKBody +} + +// IsSuccess returns true when this mount device o k response has a 2xx status code +func (o *MountDeviceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this mount device o k response has a 3xx status code +func (o *MountDeviceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this mount device o k response has a 4xx status code +func (o *MountDeviceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this mount device o k response has a 5xx status code +func (o *MountDeviceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this mount device o k response a status code equal to that given +func (o *MountDeviceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *MountDeviceOK) Error() string { + return fmt.Sprintf("[PUT /devices/mount][%d] mountDeviceOK %+v", 200, o.Payload) +} + +func (o *MountDeviceOK) String() string { + return fmt.Sprintf("[PUT /devices/mount][%d] mountDeviceOK %+v", 200, o.Payload) +} + +func (o *MountDeviceOK) GetPayload() *MountDeviceOKBody { + return o.Payload +} + +func (o *MountDeviceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(MountDeviceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewMountDeviceDefault creates a MountDeviceDefault with default headers values +func NewMountDeviceDefault(code int) *MountDeviceDefault { + return &MountDeviceDefault{ + _statusCode: code, + } +} + +/* MountDeviceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type MountDeviceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *MountDeviceDefaultBody +} + +// Code gets the status code for the mount device default response +func (o *MountDeviceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this mount device default response has a 2xx status code +func (o *MountDeviceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this mount device default response has a 3xx status code +func (o *MountDeviceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this mount device default response has a 4xx status code +func (o *MountDeviceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this mount device default response has a 5xx status code +func (o *MountDeviceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this mount device default response a status code equal to that given +func (o *MountDeviceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *MountDeviceDefault) Error() string { + return fmt.Sprintf("[PUT /devices/mount][%d] mountDevice default %+v", o._statusCode, o.Payload) +} + +func (o *MountDeviceDefault) String() string { + return fmt.Sprintf("[PUT /devices/mount][%d] mountDevice default %+v", o._statusCode, o.Payload) +} + +func (o *MountDeviceDefault) GetPayload() *MountDeviceDefaultBody { + return o.Payload +} + +func (o *MountDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(MountDeviceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*MountDeviceDefaultBody mount device default body +swagger:model MountDeviceDefaultBody +*/ +type MountDeviceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this mount device default body +func (o *MountDeviceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MountDeviceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("mountDevice default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *MountDeviceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("mountDevice default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("mountDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("mountDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this mount device default body based on the context it is used +func (o *MountDeviceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MountDeviceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("mountDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("mountDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *MountDeviceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *MountDeviceDefaultBody) UnmarshalBinary(b []byte) error { + var res MountDeviceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*MountDeviceOKBody mount device o k body +swagger:model MountDeviceOKBody +*/ +type MountDeviceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this mount device o k body +func (o *MountDeviceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MountDeviceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("mountDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("mountDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this mount device o k body based on the context it is used +func (o *MountDeviceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *MountDeviceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("mountDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("mountDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *MountDeviceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *MountDeviceOKBody) UnmarshalBinary(b []byte) error { + var res MountDeviceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/remove_device_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/remove_device_parameters.go new file mode 100644 index 0000000..740ce5a --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/remove_device_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewRemoveDeviceParams creates a new RemoveDeviceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewRemoveDeviceParams() *RemoveDeviceParams { + return &RemoveDeviceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewRemoveDeviceParamsWithTimeout creates a new RemoveDeviceParams object +// with the ability to set a timeout on a request. +func NewRemoveDeviceParamsWithTimeout(timeout time.Duration) *RemoveDeviceParams { + return &RemoveDeviceParams{ + timeout: timeout, + } +} + +// NewRemoveDeviceParamsWithContext creates a new RemoveDeviceParams object +// with the ability to set a context for a request. +func NewRemoveDeviceParamsWithContext(ctx context.Context) *RemoveDeviceParams { + return &RemoveDeviceParams{ + Context: ctx, + } +} + +// NewRemoveDeviceParamsWithHTTPClient creates a new RemoveDeviceParams object +// with the ability to set a custom HTTPClient for a request. +func NewRemoveDeviceParamsWithHTTPClient(client *http.Client) *RemoveDeviceParams { + return &RemoveDeviceParams{ + HTTPClient: client, + } +} + +/* RemoveDeviceParams contains all the parameters to send to the API endpoint + for the remove device operation. + + Typically these are written to a http.Request. +*/ +type RemoveDeviceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // DeviceID. + DeviceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the remove device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RemoveDeviceParams) WithDefaults() *RemoveDeviceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the remove device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RemoveDeviceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the remove device params +func (o *RemoveDeviceParams) WithTimeout(timeout time.Duration) *RemoveDeviceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the remove device params +func (o *RemoveDeviceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the remove device params +func (o *RemoveDeviceParams) WithContext(ctx context.Context) *RemoveDeviceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the remove device params +func (o *RemoveDeviceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the remove device params +func (o *RemoveDeviceParams) WithHTTPClient(client *http.Client) *RemoveDeviceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the remove device params +func (o *RemoveDeviceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the remove device params +func (o *RemoveDeviceParams) WithAuthorization(authorization string) *RemoveDeviceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the remove device params +func (o *RemoveDeviceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the remove device params +func (o *RemoveDeviceParams) WithBmpLanguage(bmpLanguage *string) *RemoveDeviceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the remove device params +func (o *RemoveDeviceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the remove device params +func (o *RemoveDeviceParams) WithBmpUserID(bmpUserID *string) *RemoveDeviceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the remove device params +func (o *RemoveDeviceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceID adds the deviceID to the remove device params +func (o *RemoveDeviceParams) WithDeviceID(deviceID string) *RemoveDeviceParams { + o.SetDeviceID(deviceID) + return o +} + +// SetDeviceID adds the deviceId to the remove device params +func (o *RemoveDeviceParams) SetDeviceID(deviceID string) { + o.DeviceID = deviceID +} + +// WithTraceID adds the traceID to the remove device params +func (o *RemoveDeviceParams) WithTraceID(traceID string) *RemoveDeviceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the remove device params +func (o *RemoveDeviceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *RemoveDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_id + if err := r.SetPathParam("device_id", o.DeviceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/remove_device_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/remove_device_responses.go new file mode 100644 index 0000000..7cd1b42 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/remove_device_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// RemoveDeviceReader is a Reader for the RemoveDevice structure. +type RemoveDeviceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *RemoveDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewRemoveDeviceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewRemoveDeviceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewRemoveDeviceOK creates a RemoveDeviceOK with default headers values +func NewRemoveDeviceOK() *RemoveDeviceOK { + return &RemoveDeviceOK{} +} + +/* RemoveDeviceOK describes a response with status code 200, with default header values. + +A RemoveDeviceResult is an response struct that is used to describe restart instance result. +*/ +type RemoveDeviceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *RemoveDeviceOKBody +} + +// IsSuccess returns true when this remove device o k response has a 2xx status code +func (o *RemoveDeviceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this remove device o k response has a 3xx status code +func (o *RemoveDeviceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this remove device o k response has a 4xx status code +func (o *RemoveDeviceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this remove device o k response has a 5xx status code +func (o *RemoveDeviceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this remove device o k response a status code equal to that given +func (o *RemoveDeviceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *RemoveDeviceOK) Error() string { + return fmt.Sprintf("[PUT /devices/{device_id}/remove][%d] removeDeviceOK %+v", 200, o.Payload) +} + +func (o *RemoveDeviceOK) String() string { + return fmt.Sprintf("[PUT /devices/{device_id}/remove][%d] removeDeviceOK %+v", 200, o.Payload) +} + +func (o *RemoveDeviceOK) GetPayload() *RemoveDeviceOKBody { + return o.Payload +} + +func (o *RemoveDeviceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RemoveDeviceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewRemoveDeviceDefault creates a RemoveDeviceDefault with default headers values +func NewRemoveDeviceDefault(code int) *RemoveDeviceDefault { + return &RemoveDeviceDefault{ + _statusCode: code, + } +} + +/* RemoveDeviceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type RemoveDeviceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *RemoveDeviceDefaultBody +} + +// Code gets the status code for the remove device default response +func (o *RemoveDeviceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this remove device default response has a 2xx status code +func (o *RemoveDeviceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this remove device default response has a 3xx status code +func (o *RemoveDeviceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this remove device default response has a 4xx status code +func (o *RemoveDeviceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this remove device default response has a 5xx status code +func (o *RemoveDeviceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this remove device default response a status code equal to that given +func (o *RemoveDeviceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *RemoveDeviceDefault) Error() string { + return fmt.Sprintf("[PUT /devices/{device_id}/remove][%d] removeDevice default %+v", o._statusCode, o.Payload) +} + +func (o *RemoveDeviceDefault) String() string { + return fmt.Sprintf("[PUT /devices/{device_id}/remove][%d] removeDevice default %+v", o._statusCode, o.Payload) +} + +func (o *RemoveDeviceDefault) GetPayload() *RemoveDeviceDefaultBody { + return o.Payload +} + +func (o *RemoveDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RemoveDeviceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*RemoveDeviceDefaultBody remove device default body +swagger:model RemoveDeviceDefaultBody +*/ +type RemoveDeviceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this remove device default body +func (o *RemoveDeviceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RemoveDeviceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("removeDevice default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *RemoveDeviceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("removeDevice default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("removeDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("removeDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this remove device default body based on the context it is used +func (o *RemoveDeviceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RemoveDeviceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("removeDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("removeDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RemoveDeviceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RemoveDeviceDefaultBody) UnmarshalBinary(b []byte) error { + var res RemoveDeviceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*RemoveDeviceOKBody remove device o k body +swagger:model RemoveDeviceOKBody +*/ +type RemoveDeviceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this remove device o k body +func (o *RemoveDeviceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RemoveDeviceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("removeDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("removeDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this remove device o k body based on the context it is used +func (o *RemoveDeviceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RemoveDeviceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("removeDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("removeDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RemoveDeviceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RemoveDeviceOKBody) UnmarshalBinary(b []byte) error { + var res RemoveDeviceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/un_mount_device_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/un_mount_device_parameters.go new file mode 100644 index 0000000..05e0aa5 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/un_mount_device_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewUnMountDeviceParams creates a new UnMountDeviceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewUnMountDeviceParams() *UnMountDeviceParams { + return &UnMountDeviceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUnMountDeviceParamsWithTimeout creates a new UnMountDeviceParams object +// with the ability to set a timeout on a request. +func NewUnMountDeviceParamsWithTimeout(timeout time.Duration) *UnMountDeviceParams { + return &UnMountDeviceParams{ + timeout: timeout, + } +} + +// NewUnMountDeviceParamsWithContext creates a new UnMountDeviceParams object +// with the ability to set a context for a request. +func NewUnMountDeviceParamsWithContext(ctx context.Context) *UnMountDeviceParams { + return &UnMountDeviceParams{ + Context: ctx, + } +} + +// NewUnMountDeviceParamsWithHTTPClient creates a new UnMountDeviceParams object +// with the ability to set a custom HTTPClient for a request. +func NewUnMountDeviceParamsWithHTTPClient(client *http.Client) *UnMountDeviceParams { + return &UnMountDeviceParams{ + HTTPClient: client, + } +} + +/* UnMountDeviceParams contains all the parameters to send to the API endpoint + for the un mount device operation. + + Typically these are written to a http.Request. +*/ +type UnMountDeviceParams struct { + + // Body. + Body *models.UnMountDevicesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the un mount device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UnMountDeviceParams) WithDefaults() *UnMountDeviceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the un mount device params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UnMountDeviceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the un mount device params +func (o *UnMountDeviceParams) WithTimeout(timeout time.Duration) *UnMountDeviceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the un mount device params +func (o *UnMountDeviceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the un mount device params +func (o *UnMountDeviceParams) WithContext(ctx context.Context) *UnMountDeviceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the un mount device params +func (o *UnMountDeviceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the un mount device params +func (o *UnMountDeviceParams) WithHTTPClient(client *http.Client) *UnMountDeviceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the un mount device params +func (o *UnMountDeviceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the un mount device params +func (o *UnMountDeviceParams) WithBody(body *models.UnMountDevicesRequest) *UnMountDeviceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the un mount device params +func (o *UnMountDeviceParams) SetBody(body *models.UnMountDevicesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the un mount device params +func (o *UnMountDeviceParams) WithAuthorization(authorization string) *UnMountDeviceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the un mount device params +func (o *UnMountDeviceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the un mount device params +func (o *UnMountDeviceParams) WithBmpLanguage(bmpLanguage *string) *UnMountDeviceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the un mount device params +func (o *UnMountDeviceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the un mount device params +func (o *UnMountDeviceParams) WithBmpUserID(bmpUserID *string) *UnMountDeviceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the un mount device params +func (o *UnMountDeviceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the un mount device params +func (o *UnMountDeviceParams) WithTraceID(traceID string) *UnMountDeviceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the un mount device params +func (o *UnMountDeviceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *UnMountDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/un_mount_device_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/un_mount_device_responses.go new file mode 100644 index 0000000..cd725bd --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device/un_mount_device_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// UnMountDeviceReader is a Reader for the UnMountDevice structure. +type UnMountDeviceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UnMountDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUnMountDeviceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewUnMountDeviceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewUnMountDeviceOK creates a UnMountDeviceOK with default headers values +func NewUnMountDeviceOK() *UnMountDeviceOK { + return &UnMountDeviceOK{} +} + +/* UnMountDeviceOK describes a response with status code 200, with default header values. + +A UnMountDeviceResult is an response struct that is used to unmount device. +*/ +type UnMountDeviceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *UnMountDeviceOKBody +} + +// IsSuccess returns true when this un mount device o k response has a 2xx status code +func (o *UnMountDeviceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this un mount device o k response has a 3xx status code +func (o *UnMountDeviceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this un mount device o k response has a 4xx status code +func (o *UnMountDeviceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this un mount device o k response has a 5xx status code +func (o *UnMountDeviceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this un mount device o k response a status code equal to that given +func (o *UnMountDeviceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *UnMountDeviceOK) Error() string { + return fmt.Sprintf("[PUT /devices/unmount][%d] unMountDeviceOK %+v", 200, o.Payload) +} + +func (o *UnMountDeviceOK) String() string { + return fmt.Sprintf("[PUT /devices/unmount][%d] unMountDeviceOK %+v", 200, o.Payload) +} + +func (o *UnMountDeviceOK) GetPayload() *UnMountDeviceOKBody { + return o.Payload +} + +func (o *UnMountDeviceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(UnMountDeviceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUnMountDeviceDefault creates a UnMountDeviceDefault with default headers values +func NewUnMountDeviceDefault(code int) *UnMountDeviceDefault { + return &UnMountDeviceDefault{ + _statusCode: code, + } +} + +/* UnMountDeviceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type UnMountDeviceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *UnMountDeviceDefaultBody +} + +// Code gets the status code for the un mount device default response +func (o *UnMountDeviceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this un mount device default response has a 2xx status code +func (o *UnMountDeviceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this un mount device default response has a 3xx status code +func (o *UnMountDeviceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this un mount device default response has a 4xx status code +func (o *UnMountDeviceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this un mount device default response has a 5xx status code +func (o *UnMountDeviceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this un mount device default response a status code equal to that given +func (o *UnMountDeviceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *UnMountDeviceDefault) Error() string { + return fmt.Sprintf("[PUT /devices/unmount][%d] unMountDevice default %+v", o._statusCode, o.Payload) +} + +func (o *UnMountDeviceDefault) String() string { + return fmt.Sprintf("[PUT /devices/unmount][%d] unMountDevice default %+v", o._statusCode, o.Payload) +} + +func (o *UnMountDeviceDefault) GetPayload() *UnMountDeviceDefaultBody { + return o.Payload +} + +func (o *UnMountDeviceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(UnMountDeviceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*UnMountDeviceDefaultBody un mount device default body +swagger:model UnMountDeviceDefaultBody +*/ +type UnMountDeviceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this un mount device default body +func (o *UnMountDeviceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnMountDeviceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("unMountDevice default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *UnMountDeviceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("unMountDevice default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unMountDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unMountDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this un mount device default body based on the context it is used +func (o *UnMountDeviceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnMountDeviceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unMountDevice default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unMountDevice default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *UnMountDeviceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *UnMountDeviceDefaultBody) UnmarshalBinary(b []byte) error { + var res UnMountDeviceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*UnMountDeviceOKBody un mount device o k body +swagger:model UnMountDeviceOKBody +*/ +type UnMountDeviceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this un mount device o k body +func (o *UnMountDeviceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnMountDeviceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unMountDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unMountDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this un mount device o k body based on the context it is used +func (o *UnMountDeviceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnMountDeviceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unMountDeviceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unMountDeviceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *UnMountDeviceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *UnMountDeviceOKBody) UnmarshalBinary(b []byte) error { + var res UnMountDeviceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/associated_image_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/associated_image_parameters.go new file mode 100644 index 0000000..593b7bc --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/associated_image_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewAssociatedImageParams creates a new AssociatedImageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewAssociatedImageParams() *AssociatedImageParams { + return &AssociatedImageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewAssociatedImageParamsWithTimeout creates a new AssociatedImageParams object +// with the ability to set a timeout on a request. +func NewAssociatedImageParamsWithTimeout(timeout time.Duration) *AssociatedImageParams { + return &AssociatedImageParams{ + timeout: timeout, + } +} + +// NewAssociatedImageParamsWithContext creates a new AssociatedImageParams object +// with the ability to set a context for a request. +func NewAssociatedImageParamsWithContext(ctx context.Context) *AssociatedImageParams { + return &AssociatedImageParams{ + Context: ctx, + } +} + +// NewAssociatedImageParamsWithHTTPClient creates a new AssociatedImageParams object +// with the ability to set a custom HTTPClient for a request. +func NewAssociatedImageParamsWithHTTPClient(client *http.Client) *AssociatedImageParams { + return &AssociatedImageParams{ + HTTPClient: client, + } +} + +/* AssociatedImageParams contains all the parameters to send to the API endpoint + for the associated image operation. + + Typically these are written to a http.Request. +*/ +type AssociatedImageParams struct { + + // Body. + Body *models.AssociateImageRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the associated image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AssociatedImageParams) WithDefaults() *AssociatedImageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the associated image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AssociatedImageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the associated image params +func (o *AssociatedImageParams) WithTimeout(timeout time.Duration) *AssociatedImageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the associated image params +func (o *AssociatedImageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the associated image params +func (o *AssociatedImageParams) WithContext(ctx context.Context) *AssociatedImageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the associated image params +func (o *AssociatedImageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the associated image params +func (o *AssociatedImageParams) WithHTTPClient(client *http.Client) *AssociatedImageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the associated image params +func (o *AssociatedImageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the associated image params +func (o *AssociatedImageParams) WithBody(body *models.AssociateImageRequest) *AssociatedImageParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the associated image params +func (o *AssociatedImageParams) SetBody(body *models.AssociateImageRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the associated image params +func (o *AssociatedImageParams) WithAuthorization(authorization string) *AssociatedImageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the associated image params +func (o *AssociatedImageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the associated image params +func (o *AssociatedImageParams) WithBmpLanguage(bmpLanguage *string) *AssociatedImageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the associated image params +func (o *AssociatedImageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the associated image params +func (o *AssociatedImageParams) WithBmpUserID(bmpUserID *string) *AssociatedImageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the associated image params +func (o *AssociatedImageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the associated image params +func (o *AssociatedImageParams) WithTraceID(traceID string) *AssociatedImageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the associated image params +func (o *AssociatedImageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *AssociatedImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/associated_image_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/associated_image_responses.go new file mode 100644 index 0000000..a45b302 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/associated_image_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// AssociatedImageReader is a Reader for the AssociatedImage structure. +type AssociatedImageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *AssociatedImageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewAssociatedImageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewAssociatedImageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewAssociatedImageOK creates a AssociatedImageOK with default headers values +func NewAssociatedImageOK() *AssociatedImageOK { + return &AssociatedImageOK{} +} + +/* AssociatedImageOK describes a response with status code 200, with default header values. + +A AssociatedImageResult is an response struct that is used to associated image result. +*/ +type AssociatedImageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *AssociatedImageOKBody +} + +// IsSuccess returns true when this associated image o k response has a 2xx status code +func (o *AssociatedImageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this associated image o k response has a 3xx status code +func (o *AssociatedImageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this associated image o k response has a 4xx status code +func (o *AssociatedImageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this associated image o k response has a 5xx status code +func (o *AssociatedImageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this associated image o k response a status code equal to that given +func (o *AssociatedImageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *AssociatedImageOK) Error() string { + return fmt.Sprintf("[POST /deviceTypes/associatedImage][%d] associatedImageOK %+v", 200, o.Payload) +} + +func (o *AssociatedImageOK) String() string { + return fmt.Sprintf("[POST /deviceTypes/associatedImage][%d] associatedImageOK %+v", 200, o.Payload) +} + +func (o *AssociatedImageOK) GetPayload() *AssociatedImageOKBody { + return o.Payload +} + +func (o *AssociatedImageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AssociatedImageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAssociatedImageDefault creates a AssociatedImageDefault with default headers values +func NewAssociatedImageDefault(code int) *AssociatedImageDefault { + return &AssociatedImageDefault{ + _statusCode: code, + } +} + +/* AssociatedImageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type AssociatedImageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *AssociatedImageDefaultBody +} + +// Code gets the status code for the associated image default response +func (o *AssociatedImageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this associated image default response has a 2xx status code +func (o *AssociatedImageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this associated image default response has a 3xx status code +func (o *AssociatedImageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this associated image default response has a 4xx status code +func (o *AssociatedImageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this associated image default response has a 5xx status code +func (o *AssociatedImageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this associated image default response a status code equal to that given +func (o *AssociatedImageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *AssociatedImageDefault) Error() string { + return fmt.Sprintf("[POST /deviceTypes/associatedImage][%d] associatedImage default %+v", o._statusCode, o.Payload) +} + +func (o *AssociatedImageDefault) String() string { + return fmt.Sprintf("[POST /deviceTypes/associatedImage][%d] associatedImage default %+v", o._statusCode, o.Payload) +} + +func (o *AssociatedImageDefault) GetPayload() *AssociatedImageDefaultBody { + return o.Payload +} + +func (o *AssociatedImageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AssociatedImageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*AssociatedImageDefaultBody associated image default body +swagger:model AssociatedImageDefaultBody +*/ +type AssociatedImageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this associated image default body +func (o *AssociatedImageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedImageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("associatedImage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *AssociatedImageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("associatedImage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this associated image default body based on the context it is used +func (o *AssociatedImageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedImageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AssociatedImageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AssociatedImageDefaultBody) UnmarshalBinary(b []byte) error { + var res AssociatedImageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*AssociatedImageOKBody associated image o k body +swagger:model AssociatedImageOKBody +*/ +type AssociatedImageOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this associated image o k body +func (o *AssociatedImageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedImageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this associated image o k body based on the context it is used +func (o *AssociatedImageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedImageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AssociatedImageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AssociatedImageOKBody) UnmarshalBinary(b []byte) error { + var res AssociatedImageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/create_device_type_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/create_device_type_parameters.go new file mode 100644 index 0000000..9a9577e --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/create_device_type_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateDeviceTypeParams creates a new CreateDeviceTypeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateDeviceTypeParams() *CreateDeviceTypeParams { + return &CreateDeviceTypeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateDeviceTypeParamsWithTimeout creates a new CreateDeviceTypeParams object +// with the ability to set a timeout on a request. +func NewCreateDeviceTypeParamsWithTimeout(timeout time.Duration) *CreateDeviceTypeParams { + return &CreateDeviceTypeParams{ + timeout: timeout, + } +} + +// NewCreateDeviceTypeParamsWithContext creates a new CreateDeviceTypeParams object +// with the ability to set a context for a request. +func NewCreateDeviceTypeParamsWithContext(ctx context.Context) *CreateDeviceTypeParams { + return &CreateDeviceTypeParams{ + Context: ctx, + } +} + +// NewCreateDeviceTypeParamsWithHTTPClient creates a new CreateDeviceTypeParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateDeviceTypeParamsWithHTTPClient(client *http.Client) *CreateDeviceTypeParams { + return &CreateDeviceTypeParams{ + HTTPClient: client, + } +} + +/* CreateDeviceTypeParams contains all the parameters to send to the API endpoint + for the create device type operation. + + Typically these are written to a http.Request. +*/ +type CreateDeviceTypeParams struct { + + // Body. + Body *models.CreateDeviceTypeRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateDeviceTypeParams) WithDefaults() *CreateDeviceTypeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateDeviceTypeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create device type params +func (o *CreateDeviceTypeParams) WithTimeout(timeout time.Duration) *CreateDeviceTypeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create device type params +func (o *CreateDeviceTypeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create device type params +func (o *CreateDeviceTypeParams) WithContext(ctx context.Context) *CreateDeviceTypeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create device type params +func (o *CreateDeviceTypeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create device type params +func (o *CreateDeviceTypeParams) WithHTTPClient(client *http.Client) *CreateDeviceTypeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create device type params +func (o *CreateDeviceTypeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create device type params +func (o *CreateDeviceTypeParams) WithBody(body *models.CreateDeviceTypeRequest) *CreateDeviceTypeParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create device type params +func (o *CreateDeviceTypeParams) SetBody(body *models.CreateDeviceTypeRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create device type params +func (o *CreateDeviceTypeParams) WithAuthorization(authorization string) *CreateDeviceTypeParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create device type params +func (o *CreateDeviceTypeParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create device type params +func (o *CreateDeviceTypeParams) WithBmpLanguage(bmpLanguage *string) *CreateDeviceTypeParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create device type params +func (o *CreateDeviceTypeParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create device type params +func (o *CreateDeviceTypeParams) WithBmpUserID(bmpUserID *string) *CreateDeviceTypeParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create device type params +func (o *CreateDeviceTypeParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create device type params +func (o *CreateDeviceTypeParams) WithTraceID(traceID string) *CreateDeviceTypeParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create device type params +func (o *CreateDeviceTypeParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateDeviceTypeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/create_device_type_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/create_device_type_responses.go new file mode 100644 index 0000000..7c5b69e --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/create_device_type_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateDeviceTypeReader is a Reader for the CreateDeviceType structure. +type CreateDeviceTypeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateDeviceTypeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateDeviceTypeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateDeviceTypeDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateDeviceTypeOK creates a CreateDeviceTypeOK with default headers values +func NewCreateDeviceTypeOK() *CreateDeviceTypeOK { + return &CreateDeviceTypeOK{} +} + +/* CreateDeviceTypeOK describes a response with status code 200, with default header values. + +A CreateDeviceTypeResult is an response struct that is used to describe create deviceType result. +*/ +type CreateDeviceTypeOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateDeviceTypeOKBody +} + +// IsSuccess returns true when this create device type o k response has a 2xx status code +func (o *CreateDeviceTypeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create device type o k response has a 3xx status code +func (o *CreateDeviceTypeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create device type o k response has a 4xx status code +func (o *CreateDeviceTypeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create device type o k response has a 5xx status code +func (o *CreateDeviceTypeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create device type o k response a status code equal to that given +func (o *CreateDeviceTypeOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateDeviceTypeOK) Error() string { + return fmt.Sprintf("[POST /deviceTypes][%d] createDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *CreateDeviceTypeOK) String() string { + return fmt.Sprintf("[POST /deviceTypes][%d] createDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *CreateDeviceTypeOK) GetPayload() *CreateDeviceTypeOKBody { + return o.Payload +} + +func (o *CreateDeviceTypeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateDeviceTypeOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateDeviceTypeDefault creates a CreateDeviceTypeDefault with default headers values +func NewCreateDeviceTypeDefault(code int) *CreateDeviceTypeDefault { + return &CreateDeviceTypeDefault{ + _statusCode: code, + } +} + +/* CreateDeviceTypeDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateDeviceTypeDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateDeviceTypeDefaultBody +} + +// Code gets the status code for the create device type default response +func (o *CreateDeviceTypeDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create device type default response has a 2xx status code +func (o *CreateDeviceTypeDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create device type default response has a 3xx status code +func (o *CreateDeviceTypeDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create device type default response has a 4xx status code +func (o *CreateDeviceTypeDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create device type default response has a 5xx status code +func (o *CreateDeviceTypeDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create device type default response a status code equal to that given +func (o *CreateDeviceTypeDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateDeviceTypeDefault) Error() string { + return fmt.Sprintf("[POST /deviceTypes][%d] createDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *CreateDeviceTypeDefault) String() string { + return fmt.Sprintf("[POST /deviceTypes][%d] createDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *CreateDeviceTypeDefault) GetPayload() *CreateDeviceTypeDefaultBody { + return o.Payload +} + +func (o *CreateDeviceTypeDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateDeviceTypeDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateDeviceTypeDefaultBody create device type default body +swagger:model CreateDeviceTypeDefaultBody +*/ +type CreateDeviceTypeDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create device type default body +func (o *CreateDeviceTypeDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createDeviceType default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateDeviceTypeDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createDeviceType default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create device type default body based on the context it is used +func (o *CreateDeviceTypeDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateDeviceTypeDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateDeviceTypeDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateDeviceTypeDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateDeviceTypeOKBody create device type o k body +swagger:model CreateDeviceTypeOKBody +*/ +type CreateDeviceTypeOKBody struct { + + // result + Result *models.DeviceTypeID `json:"result,omitempty"` +} + +// Validate validates this create device type o k body +func (o *CreateDeviceTypeOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create device type o k body based on the context it is used +func (o *CreateDeviceTypeOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateDeviceTypeOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateDeviceTypeOKBody) UnmarshalBinary(b []byte) error { + var res CreateDeviceTypeOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/delete_device_type_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/delete_device_type_parameters.go new file mode 100644 index 0000000..6ef3fdf --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/delete_device_type_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteDeviceTypeParams creates a new DeleteDeviceTypeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteDeviceTypeParams() *DeleteDeviceTypeParams { + return &DeleteDeviceTypeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteDeviceTypeParamsWithTimeout creates a new DeleteDeviceTypeParams object +// with the ability to set a timeout on a request. +func NewDeleteDeviceTypeParamsWithTimeout(timeout time.Duration) *DeleteDeviceTypeParams { + return &DeleteDeviceTypeParams{ + timeout: timeout, + } +} + +// NewDeleteDeviceTypeParamsWithContext creates a new DeleteDeviceTypeParams object +// with the ability to set a context for a request. +func NewDeleteDeviceTypeParamsWithContext(ctx context.Context) *DeleteDeviceTypeParams { + return &DeleteDeviceTypeParams{ + Context: ctx, + } +} + +// NewDeleteDeviceTypeParamsWithHTTPClient creates a new DeleteDeviceTypeParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteDeviceTypeParamsWithHTTPClient(client *http.Client) *DeleteDeviceTypeParams { + return &DeleteDeviceTypeParams{ + HTTPClient: client, + } +} + +/* DeleteDeviceTypeParams contains all the parameters to send to the API endpoint + for the delete device type operation. + + Typically these are written to a http.Request. +*/ +type DeleteDeviceTypeParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // DeviceTypeID. + DeviceTypeID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteDeviceTypeParams) WithDefaults() *DeleteDeviceTypeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteDeviceTypeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete device type params +func (o *DeleteDeviceTypeParams) WithTimeout(timeout time.Duration) *DeleteDeviceTypeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete device type params +func (o *DeleteDeviceTypeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete device type params +func (o *DeleteDeviceTypeParams) WithContext(ctx context.Context) *DeleteDeviceTypeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete device type params +func (o *DeleteDeviceTypeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete device type params +func (o *DeleteDeviceTypeParams) WithHTTPClient(client *http.Client) *DeleteDeviceTypeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete device type params +func (o *DeleteDeviceTypeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete device type params +func (o *DeleteDeviceTypeParams) WithAuthorization(authorization string) *DeleteDeviceTypeParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete device type params +func (o *DeleteDeviceTypeParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete device type params +func (o *DeleteDeviceTypeParams) WithBmpLanguage(bmpLanguage *string) *DeleteDeviceTypeParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete device type params +func (o *DeleteDeviceTypeParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete device type params +func (o *DeleteDeviceTypeParams) WithBmpUserID(bmpUserID *string) *DeleteDeviceTypeParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete device type params +func (o *DeleteDeviceTypeParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the delete device type params +func (o *DeleteDeviceTypeParams) WithDeviceTypeID(deviceTypeID string) *DeleteDeviceTypeParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the delete device type params +func (o *DeleteDeviceTypeParams) SetDeviceTypeID(deviceTypeID string) { + o.DeviceTypeID = deviceTypeID +} + +// WithTraceID adds the traceID to the delete device type params +func (o *DeleteDeviceTypeParams) WithTraceID(traceID string) *DeleteDeviceTypeParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete device type params +func (o *DeleteDeviceTypeParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteDeviceTypeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_type_id + if err := r.SetPathParam("device_type_id", o.DeviceTypeID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/delete_device_type_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/delete_device_type_responses.go new file mode 100644 index 0000000..686d347 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/delete_device_type_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteDeviceTypeReader is a Reader for the DeleteDeviceType structure. +type DeleteDeviceTypeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteDeviceTypeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteDeviceTypeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteDeviceTypeDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteDeviceTypeOK creates a DeleteDeviceTypeOK with default headers values +func NewDeleteDeviceTypeOK() *DeleteDeviceTypeOK { + return &DeleteDeviceTypeOK{} +} + +/* DeleteDeviceTypeOK describes a response with status code 200, with default header values. + +A DeleteDeviceTypeResult is an response struct that is used to delete device type. +*/ +type DeleteDeviceTypeOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteDeviceTypeOKBody +} + +// IsSuccess returns true when this delete device type o k response has a 2xx status code +func (o *DeleteDeviceTypeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete device type o k response has a 3xx status code +func (o *DeleteDeviceTypeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete device type o k response has a 4xx status code +func (o *DeleteDeviceTypeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete device type o k response has a 5xx status code +func (o *DeleteDeviceTypeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete device type o k response a status code equal to that given +func (o *DeleteDeviceTypeOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteDeviceTypeOK) Error() string { + return fmt.Sprintf("[DELETE /deviceTypes/{device_type_id}][%d] deleteDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DeleteDeviceTypeOK) String() string { + return fmt.Sprintf("[DELETE /deviceTypes/{device_type_id}][%d] deleteDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DeleteDeviceTypeOK) GetPayload() *DeleteDeviceTypeOKBody { + return o.Payload +} + +func (o *DeleteDeviceTypeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteDeviceTypeOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteDeviceTypeDefault creates a DeleteDeviceTypeDefault with default headers values +func NewDeleteDeviceTypeDefault(code int) *DeleteDeviceTypeDefault { + return &DeleteDeviceTypeDefault{ + _statusCode: code, + } +} + +/* DeleteDeviceTypeDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteDeviceTypeDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteDeviceTypeDefaultBody +} + +// Code gets the status code for the delete device type default response +func (o *DeleteDeviceTypeDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete device type default response has a 2xx status code +func (o *DeleteDeviceTypeDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete device type default response has a 3xx status code +func (o *DeleteDeviceTypeDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete device type default response has a 4xx status code +func (o *DeleteDeviceTypeDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete device type default response has a 5xx status code +func (o *DeleteDeviceTypeDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete device type default response a status code equal to that given +func (o *DeleteDeviceTypeDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteDeviceTypeDefault) Error() string { + return fmt.Sprintf("[DELETE /deviceTypes/{device_type_id}][%d] deleteDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteDeviceTypeDefault) String() string { + return fmt.Sprintf("[DELETE /deviceTypes/{device_type_id}][%d] deleteDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteDeviceTypeDefault) GetPayload() *DeleteDeviceTypeDefaultBody { + return o.Payload +} + +func (o *DeleteDeviceTypeDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteDeviceTypeDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteDeviceTypeDefaultBody delete device type default body +swagger:model DeleteDeviceTypeDefaultBody +*/ +type DeleteDeviceTypeDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete device type default body +func (o *DeleteDeviceTypeDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteDeviceType default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteDeviceTypeDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteDeviceType default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete device type default body based on the context it is used +func (o *DeleteDeviceTypeDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteDeviceTypeDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteDeviceTypeDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteDeviceTypeDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteDeviceTypeOKBody delete device type o k body +swagger:model DeleteDeviceTypeOKBody +*/ +type DeleteDeviceTypeOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete device type o k body +func (o *DeleteDeviceTypeOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete device type o k body based on the context it is used +func (o *DeleteDeviceTypeOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteDeviceTypeOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteDeviceTypeOKBody) UnmarshalBinary(b []byte) error { + var res DeleteDeviceTypeOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_image_partitions_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_image_partitions_parameters.go new file mode 100644 index 0000000..93af2e4 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_image_partitions_parameters.go @@ -0,0 +1,323 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeDeviceTypeImagePartitionsParams creates a new DescribeDeviceTypeImagePartitionsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceTypeImagePartitionsParams() *DescribeDeviceTypeImagePartitionsParams { + return &DescribeDeviceTypeImagePartitionsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceTypeImagePartitionsParamsWithTimeout creates a new DescribeDeviceTypeImagePartitionsParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceTypeImagePartitionsParamsWithTimeout(timeout time.Duration) *DescribeDeviceTypeImagePartitionsParams { + return &DescribeDeviceTypeImagePartitionsParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceTypeImagePartitionsParamsWithContext creates a new DescribeDeviceTypeImagePartitionsParams object +// with the ability to set a context for a request. +func NewDescribeDeviceTypeImagePartitionsParamsWithContext(ctx context.Context) *DescribeDeviceTypeImagePartitionsParams { + return &DescribeDeviceTypeImagePartitionsParams{ + Context: ctx, + } +} + +// NewDescribeDeviceTypeImagePartitionsParamsWithHTTPClient creates a new DescribeDeviceTypeImagePartitionsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceTypeImagePartitionsParamsWithHTTPClient(client *http.Client) *DescribeDeviceTypeImagePartitionsParams { + return &DescribeDeviceTypeImagePartitionsParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceTypeImagePartitionsParams contains all the parameters to send to the API endpoint + for the describe device type image partitions operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceTypeImagePartitionsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceTypeID. + + 机型id + */ + DeviceTypeID *string + + /* ImageID. + + 镜像id + */ + ImageID *string + + /* IsAll. + + 是否显示所有,isAll=1显示所有 + */ + IsAll *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device type image partitions params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeImagePartitionsParams) WithDefaults() *DescribeDeviceTypeImagePartitionsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device type image partitions params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeImagePartitionsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithTimeout(timeout time.Duration) *DescribeDeviceTypeImagePartitionsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithContext(ctx context.Context) *DescribeDeviceTypeImagePartitionsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithHTTPClient(client *http.Client) *DescribeDeviceTypeImagePartitionsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithAuthorization(authorization string) *DescribeDeviceTypeImagePartitionsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceTypeImagePartitionsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceTypeImagePartitionsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDeviceTypeImagePartitionsParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithImageID adds the imageID to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithImageID(imageID *string) *DescribeDeviceTypeImagePartitionsParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetImageID(imageID *string) { + o.ImageID = imageID +} + +// WithIsAll adds the isAll to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithIsAll(isAll *string) *DescribeDeviceTypeImagePartitionsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithTraceID adds the traceID to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) WithTraceID(traceID string) *DescribeDeviceTypeImagePartitionsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device type image partitions params +func (o *DescribeDeviceTypeImagePartitionsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceTypeImagePartitionsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.ImageID != nil { + + // query param imageId + var qrImageID string + + if o.ImageID != nil { + qrImageID = *o.ImageID + } + qImageID := qrImageID + if qImageID != "" { + + if err := r.SetQueryParam("imageId", qImageID); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_image_partitions_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_image_partitions_responses.go new file mode 100644 index 0000000..1666161 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_image_partitions_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDeviceTypeImagePartitionsReader is a Reader for the DescribeDeviceTypeImagePartitions structure. +type DescribeDeviceTypeImagePartitionsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceTypeImagePartitionsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceTypeImagePartitionsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceTypeImagePartitionsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceTypeImagePartitionsOK creates a DescribeDeviceTypeImagePartitionsOK with default headers values +func NewDescribeDeviceTypeImagePartitionsOK() *DescribeDeviceTypeImagePartitionsOK { + return &DescribeDeviceTypeImagePartitionsOK{} +} + +/* DescribeDeviceTypeImagePartitionsOK describes a response with status code 200, with default header values. + +DescribeDeviceTypeImagePartitionsOK describe device type image partitions o k +*/ +type DescribeDeviceTypeImagePartitionsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeImagePartitionsOKBody +} + +// IsSuccess returns true when this describe device type image partitions o k response has a 2xx status code +func (o *DescribeDeviceTypeImagePartitionsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device type image partitions o k response has a 3xx status code +func (o *DescribeDeviceTypeImagePartitionsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device type image partitions o k response has a 4xx status code +func (o *DescribeDeviceTypeImagePartitionsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device type image partitions o k response has a 5xx status code +func (o *DescribeDeviceTypeImagePartitionsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device type image partitions o k response a status code equal to that given +func (o *DescribeDeviceTypeImagePartitionsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceTypeImagePartitionsOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImagePartition][%d] describeDeviceTypeImagePartitionsOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeImagePartitionsOK) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImagePartition][%d] describeDeviceTypeImagePartitionsOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeImagePartitionsOK) GetPayload() *DescribeDeviceTypeImagePartitionsOKBody { + return o.Payload +} + +func (o *DescribeDeviceTypeImagePartitionsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeImagePartitionsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceTypeImagePartitionsDefault creates a DescribeDeviceTypeImagePartitionsDefault with default headers values +func NewDescribeDeviceTypeImagePartitionsDefault(code int) *DescribeDeviceTypeImagePartitionsDefault { + return &DescribeDeviceTypeImagePartitionsDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceTypeImagePartitionsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceTypeImagePartitionsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeImagePartitionsDefaultBody +} + +// Code gets the status code for the describe device type image partitions default response +func (o *DescribeDeviceTypeImagePartitionsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device type image partitions default response has a 2xx status code +func (o *DescribeDeviceTypeImagePartitionsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device type image partitions default response has a 3xx status code +func (o *DescribeDeviceTypeImagePartitionsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device type image partitions default response has a 4xx status code +func (o *DescribeDeviceTypeImagePartitionsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device type image partitions default response has a 5xx status code +func (o *DescribeDeviceTypeImagePartitionsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device type image partitions default response a status code equal to that given +func (o *DescribeDeviceTypeImagePartitionsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceTypeImagePartitionsDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImagePartition][%d] describeDeviceTypeImagePartitions default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeImagePartitionsDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImagePartition][%d] describeDeviceTypeImagePartitions default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeImagePartitionsDefault) GetPayload() *DescribeDeviceTypeImagePartitionsDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceTypeImagePartitionsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeImagePartitionsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceTypeImagePartitionsDefaultBody describe device type image partitions default body +swagger:model DescribeDeviceTypeImagePartitionsDefaultBody +*/ +type DescribeDeviceTypeImagePartitionsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device type image partitions default body +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeImagePartitions default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeImagePartitions default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagePartitions default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagePartitions default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type image partitions default body based on the context it is used +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagePartitions default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagePartitions default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeImagePartitionsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeImagePartitionsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceTypeImagePartitionsOKBody describe device type image partitions o k body +swagger:model DescribeDeviceTypeImagePartitionsOKBody +*/ +type DescribeDeviceTypeImagePartitionsOKBody struct { + + // result + Result *models.QueryDeviceTypeImagePartitionResponse `json:"result,omitempty"` +} + +// Validate validates this describe device type image partitions o k body +func (o *DescribeDeviceTypeImagePartitionsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagePartitionsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagePartitionsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagePartitionsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type image partitions o k body based on the context it is used +func (o *DescribeDeviceTypeImagePartitionsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagePartitionsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagePartitionsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagePartitionsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeImagePartitionsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeImagePartitionsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeImagePartitionsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_images_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_images_parameters.go new file mode 100644 index 0000000..18a2d74 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_images_parameters.go @@ -0,0 +1,600 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeDeviceTypeImagesParams creates a new DescribeDeviceTypeImagesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceTypeImagesParams() *DescribeDeviceTypeImagesParams { + return &DescribeDeviceTypeImagesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceTypeImagesParamsWithTimeout creates a new DescribeDeviceTypeImagesParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceTypeImagesParamsWithTimeout(timeout time.Duration) *DescribeDeviceTypeImagesParams { + return &DescribeDeviceTypeImagesParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceTypeImagesParamsWithContext creates a new DescribeDeviceTypeImagesParams object +// with the ability to set a context for a request. +func NewDescribeDeviceTypeImagesParamsWithContext(ctx context.Context) *DescribeDeviceTypeImagesParams { + return &DescribeDeviceTypeImagesParams{ + Context: ctx, + } +} + +// NewDescribeDeviceTypeImagesParamsWithHTTPClient creates a new DescribeDeviceTypeImagesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceTypeImagesParamsWithHTTPClient(client *http.Client) *DescribeDeviceTypeImagesParams { + return &DescribeDeviceTypeImagesParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceTypeImagesParams contains all the parameters to send to the API endpoint + for the describe device type images operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceTypeImagesParams struct { + + /* Architecture. + + 体系架构 + */ + Architecture *string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceTypeID. + + 机型id + */ + DeviceTypeID *string + + /* ImageID. + + 镜像id + */ + ImageID *string + + /* ImageName. + + 镜像名称 + */ + ImageName *string + + /* IsAll. + + 是否显示全部 + */ + IsAll *string + + /* OsID. + + 操作系统ID + */ + OsID *string + + /* OsType. + + 操作系统平台 + */ + OsType *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* Source. + + 镜像类型,预置,自定义 + */ + Source *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* Version. + + 版本号 + */ + Version *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device type images params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeImagesParams) WithDefaults() *DescribeDeviceTypeImagesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device type images params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeImagesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithTimeout(timeout time.Duration) *DescribeDeviceTypeImagesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithContext(ctx context.Context) *DescribeDeviceTypeImagesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithHTTPClient(client *http.Client) *DescribeDeviceTypeImagesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithArchitecture adds the architecture to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithArchitecture(architecture *string) *DescribeDeviceTypeImagesParams { + o.SetArchitecture(architecture) + return o +} + +// SetArchitecture adds the architecture to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetArchitecture(architecture *string) { + o.Architecture = architecture +} + +// WithAuthorization adds the authorization to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithAuthorization(authorization string) *DescribeDeviceTypeImagesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceTypeImagesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceTypeImagesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDeviceTypeImagesParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithImageID adds the imageID to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithImageID(imageID *string) *DescribeDeviceTypeImagesParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetImageID(imageID *string) { + o.ImageID = imageID +} + +// WithImageName adds the imageName to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithImageName(imageName *string) *DescribeDeviceTypeImagesParams { + o.SetImageName(imageName) + return o +} + +// SetImageName adds the imageName to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetImageName(imageName *string) { + o.ImageName = imageName +} + +// WithIsAll adds the isAll to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithIsAll(isAll *string) *DescribeDeviceTypeImagesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithOsID adds the osID to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithOsID(osID *string) *DescribeDeviceTypeImagesParams { + o.SetOsID(osID) + return o +} + +// SetOsID adds the osId to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetOsID(osID *string) { + o.OsID = osID +} + +// WithOsType adds the osType to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithOsType(osType *string) *DescribeDeviceTypeImagesParams { + o.SetOsType(osType) + return o +} + +// SetOsType adds the osType to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetOsType(osType *string) { + o.OsType = osType +} + +// WithPageNumber adds the pageNumber to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithPageNumber(pageNumber *int64) *DescribeDeviceTypeImagesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithPageSize(pageSize *int64) *DescribeDeviceTypeImagesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithSource adds the source to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithSource(source *string) *DescribeDeviceTypeImagesParams { + o.SetSource(source) + return o +} + +// SetSource adds the source to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetSource(source *string) { + o.Source = source +} + +// WithTraceID adds the traceID to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithTraceID(traceID string) *DescribeDeviceTypeImagesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithVersion adds the version to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) WithVersion(version *string) *DescribeDeviceTypeImagesParams { + o.SetVersion(version) + return o +} + +// SetVersion adds the version to the describe device type images params +func (o *DescribeDeviceTypeImagesParams) SetVersion(version *string) { + o.Version = version +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceTypeImagesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Architecture != nil { + + // query param architecture + var qrArchitecture string + + if o.Architecture != nil { + qrArchitecture = *o.Architecture + } + qArchitecture := qrArchitecture + if qArchitecture != "" { + + if err := r.SetQueryParam("architecture", qArchitecture); err != nil { + return err + } + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.ImageID != nil { + + // query param imageId + var qrImageID string + + if o.ImageID != nil { + qrImageID = *o.ImageID + } + qImageID := qrImageID + if qImageID != "" { + + if err := r.SetQueryParam("imageId", qImageID); err != nil { + return err + } + } + } + + if o.ImageName != nil { + + // query param imageName + var qrImageName string + + if o.ImageName != nil { + qrImageName = *o.ImageName + } + qImageName := qrImageName + if qImageName != "" { + + if err := r.SetQueryParam("imageName", qImageName); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.OsID != nil { + + // query param osId + var qrOsID string + + if o.OsID != nil { + qrOsID = *o.OsID + } + qOsID := qrOsID + if qOsID != "" { + + if err := r.SetQueryParam("osId", qOsID); err != nil { + return err + } + } + } + + if o.OsType != nil { + + // query param osType + var qrOsType string + + if o.OsType != nil { + qrOsType = *o.OsType + } + qOsType := qrOsType + if qOsType != "" { + + if err := r.SetQueryParam("osType", qOsType); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.Source != nil { + + // query param source + var qrSource string + + if o.Source != nil { + qrSource = *o.Source + } + qSource := qrSource + if qSource != "" { + + if err := r.SetQueryParam("source", qSource); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.Version != nil { + + // query param version + var qrVersion string + + if o.Version != nil { + qrVersion = *o.Version + } + qVersion := qrVersion + if qVersion != "" { + + if err := r.SetQueryParam("version", qVersion); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_images_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_images_responses.go new file mode 100644 index 0000000..e12580b --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_images_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDeviceTypeImagesReader is a Reader for the DescribeDeviceTypeImages structure. +type DescribeDeviceTypeImagesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceTypeImagesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceTypeImagesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceTypeImagesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceTypeImagesOK creates a DescribeDeviceTypeImagesOK with default headers values +func NewDescribeDeviceTypeImagesOK() *DescribeDeviceTypeImagesOK { + return &DescribeDeviceTypeImagesOK{} +} + +/* DescribeDeviceTypeImagesOK describes a response with status code 200, with default header values. + +DescribeDeviceTypeImagesOK describe device type images o k +*/ +type DescribeDeviceTypeImagesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeImagesOKBody +} + +// IsSuccess returns true when this describe device type images o k response has a 2xx status code +func (o *DescribeDeviceTypeImagesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device type images o k response has a 3xx status code +func (o *DescribeDeviceTypeImagesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device type images o k response has a 4xx status code +func (o *DescribeDeviceTypeImagesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device type images o k response has a 5xx status code +func (o *DescribeDeviceTypeImagesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device type images o k response a status code equal to that given +func (o *DescribeDeviceTypeImagesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceTypeImagesOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImage][%d] describeDeviceTypeImagesOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeImagesOK) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImage][%d] describeDeviceTypeImagesOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeImagesOK) GetPayload() *DescribeDeviceTypeImagesOKBody { + return o.Payload +} + +func (o *DescribeDeviceTypeImagesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeImagesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceTypeImagesDefault creates a DescribeDeviceTypeImagesDefault with default headers values +func NewDescribeDeviceTypeImagesDefault(code int) *DescribeDeviceTypeImagesDefault { + return &DescribeDeviceTypeImagesDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceTypeImagesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceTypeImagesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeImagesDefaultBody +} + +// Code gets the status code for the describe device type images default response +func (o *DescribeDeviceTypeImagesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device type images default response has a 2xx status code +func (o *DescribeDeviceTypeImagesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device type images default response has a 3xx status code +func (o *DescribeDeviceTypeImagesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device type images default response has a 4xx status code +func (o *DescribeDeviceTypeImagesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device type images default response has a 5xx status code +func (o *DescribeDeviceTypeImagesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device type images default response a status code equal to that given +func (o *DescribeDeviceTypeImagesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceTypeImagesDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImage][%d] describeDeviceTypeImages default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeImagesDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeImage][%d] describeDeviceTypeImages default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeImagesDefault) GetPayload() *DescribeDeviceTypeImagesDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceTypeImagesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeImagesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceTypeImagesDefaultBody describe device type images default body +swagger:model DescribeDeviceTypeImagesDefaultBody +*/ +type DescribeDeviceTypeImagesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device type images default body +func (o *DescribeDeviceTypeImagesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeImages default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceTypeImagesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeImages default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImages default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImages default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type images default body based on the context it is used +func (o *DescribeDeviceTypeImagesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImages default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImages default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeImagesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeImagesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeImagesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceTypeImagesOKBody describe device type images o k body +swagger:model DescribeDeviceTypeImagesOKBody +*/ +type DescribeDeviceTypeImagesOKBody struct { + + // result + Result *models.ImageList `json:"result,omitempty"` +} + +// Validate validates this describe device type images o k body +func (o *DescribeDeviceTypeImagesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type images o k body based on the context it is used +func (o *DescribeDeviceTypeImagesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeImagesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeImagesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeImagesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeImagesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeImagesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeImagesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_parameters.go new file mode 100644 index 0000000..fb352df --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeDeviceTypeParams creates a new DescribeDeviceTypeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceTypeParams() *DescribeDeviceTypeParams { + return &DescribeDeviceTypeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceTypeParamsWithTimeout creates a new DescribeDeviceTypeParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceTypeParamsWithTimeout(timeout time.Duration) *DescribeDeviceTypeParams { + return &DescribeDeviceTypeParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceTypeParamsWithContext creates a new DescribeDeviceTypeParams object +// with the ability to set a context for a request. +func NewDescribeDeviceTypeParamsWithContext(ctx context.Context) *DescribeDeviceTypeParams { + return &DescribeDeviceTypeParams{ + Context: ctx, + } +} + +// NewDescribeDeviceTypeParamsWithHTTPClient creates a new DescribeDeviceTypeParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceTypeParamsWithHTTPClient(client *http.Client) *DescribeDeviceTypeParams { + return &DescribeDeviceTypeParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceTypeParams contains all the parameters to send to the API endpoint + for the describe device type operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceTypeParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // DeviceTypeID. + DeviceTypeID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeParams) WithDefaults() *DescribeDeviceTypeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device type params +func (o *DescribeDeviceTypeParams) WithTimeout(timeout time.Duration) *DescribeDeviceTypeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device type params +func (o *DescribeDeviceTypeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device type params +func (o *DescribeDeviceTypeParams) WithContext(ctx context.Context) *DescribeDeviceTypeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device type params +func (o *DescribeDeviceTypeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device type params +func (o *DescribeDeviceTypeParams) WithHTTPClient(client *http.Client) *DescribeDeviceTypeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device type params +func (o *DescribeDeviceTypeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device type params +func (o *DescribeDeviceTypeParams) WithAuthorization(authorization string) *DescribeDeviceTypeParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device type params +func (o *DescribeDeviceTypeParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device type params +func (o *DescribeDeviceTypeParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceTypeParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device type params +func (o *DescribeDeviceTypeParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device type params +func (o *DescribeDeviceTypeParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceTypeParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device type params +func (o *DescribeDeviceTypeParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device type params +func (o *DescribeDeviceTypeParams) WithDeviceTypeID(deviceTypeID string) *DescribeDeviceTypeParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device type params +func (o *DescribeDeviceTypeParams) SetDeviceTypeID(deviceTypeID string) { + o.DeviceTypeID = deviceTypeID +} + +// WithTraceID adds the traceID to the describe device type params +func (o *DescribeDeviceTypeParams) WithTraceID(traceID string) *DescribeDeviceTypeParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device type params +func (o *DescribeDeviceTypeParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceTypeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_type_id + if err := r.SetPathParam("device_type_id", o.DeviceTypeID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_raids_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_raids_parameters.go new file mode 100644 index 0000000..b140917 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_raids_parameters.go @@ -0,0 +1,357 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeDeviceTypeRaidsParams creates a new DescribeDeviceTypeRaidsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceTypeRaidsParams() *DescribeDeviceTypeRaidsParams { + return &DescribeDeviceTypeRaidsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceTypeRaidsParamsWithTimeout creates a new DescribeDeviceTypeRaidsParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceTypeRaidsParamsWithTimeout(timeout time.Duration) *DescribeDeviceTypeRaidsParams { + return &DescribeDeviceTypeRaidsParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceTypeRaidsParamsWithContext creates a new DescribeDeviceTypeRaidsParams object +// with the ability to set a context for a request. +func NewDescribeDeviceTypeRaidsParamsWithContext(ctx context.Context) *DescribeDeviceTypeRaidsParams { + return &DescribeDeviceTypeRaidsParams{ + Context: ctx, + } +} + +// NewDescribeDeviceTypeRaidsParamsWithHTTPClient creates a new DescribeDeviceTypeRaidsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceTypeRaidsParamsWithHTTPClient(client *http.Client) *DescribeDeviceTypeRaidsParams { + return &DescribeDeviceTypeRaidsParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceTypeRaidsParams contains all the parameters to send to the API endpoint + for the describe device type raids operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceTypeRaidsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceTypeID. + + 机型id + */ + DeviceTypeID *string + + /* IsAll. + + 是否显示所有 + */ + IsAll *string + + /* RaidID. + + raidID + */ + RaidID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* VolumeType. + + 系统盘还是数据盘 + */ + VolumeType *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device type raids params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeRaidsParams) WithDefaults() *DescribeDeviceTypeRaidsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device type raids params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypeRaidsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithTimeout(timeout time.Duration) *DescribeDeviceTypeRaidsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithContext(ctx context.Context) *DescribeDeviceTypeRaidsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithHTTPClient(client *http.Client) *DescribeDeviceTypeRaidsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithAuthorization(authorization string) *DescribeDeviceTypeRaidsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceTypeRaidsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceTypeRaidsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDeviceTypeRaidsParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithIsAll adds the isAll to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithIsAll(isAll *string) *DescribeDeviceTypeRaidsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithRaidID adds the raidID to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithRaidID(raidID *string) *DescribeDeviceTypeRaidsParams { + o.SetRaidID(raidID) + return o +} + +// SetRaidID adds the raidId to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetRaidID(raidID *string) { + o.RaidID = raidID +} + +// WithTraceID adds the traceID to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithTraceID(traceID string) *DescribeDeviceTypeRaidsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithVolumeType adds the volumeType to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) WithVolumeType(volumeType *string) *DescribeDeviceTypeRaidsParams { + o.SetVolumeType(volumeType) + return o +} + +// SetVolumeType adds the volumeType to the describe device type raids params +func (o *DescribeDeviceTypeRaidsParams) SetVolumeType(volumeType *string) { + o.VolumeType = volumeType +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceTypeRaidsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.RaidID != nil { + + // query param raidId + var qrRaidID string + + if o.RaidID != nil { + qrRaidID = *o.RaidID + } + qRaidID := qrRaidID + if qRaidID != "" { + + if err := r.SetQueryParam("raidId", qRaidID); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.VolumeType != nil { + + // query param volumeType + var qrVolumeType string + + if o.VolumeType != nil { + qrVolumeType = *o.VolumeType + } + qVolumeType := qrVolumeType + if qVolumeType != "" { + + if err := r.SetQueryParam("volumeType", qVolumeType); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_raids_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_raids_responses.go new file mode 100644 index 0000000..04deb0c --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_raids_responses.go @@ -0,0 +1,415 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDeviceTypeRaidsReader is a Reader for the DescribeDeviceTypeRaids structure. +type DescribeDeviceTypeRaidsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceTypeRaidsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceTypeRaidsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceTypeRaidsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceTypeRaidsOK creates a DescribeDeviceTypeRaidsOK with default headers values +func NewDescribeDeviceTypeRaidsOK() *DescribeDeviceTypeRaidsOK { + return &DescribeDeviceTypeRaidsOK{} +} + +/* DescribeDeviceTypeRaidsOK describes a response with status code 200, with default header values. + +DescribeDeviceTypeRaidsOK describe device type raids o k +*/ +type DescribeDeviceTypeRaidsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeRaidsOKBody +} + +// IsSuccess returns true when this describe device type raids o k response has a 2xx status code +func (o *DescribeDeviceTypeRaidsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device type raids o k response has a 3xx status code +func (o *DescribeDeviceTypeRaidsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device type raids o k response has a 4xx status code +func (o *DescribeDeviceTypeRaidsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device type raids o k response has a 5xx status code +func (o *DescribeDeviceTypeRaidsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device type raids o k response a status code equal to that given +func (o *DescribeDeviceTypeRaidsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceTypeRaidsOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeRaid][%d] describeDeviceTypeRaidsOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeRaidsOK) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeRaid][%d] describeDeviceTypeRaidsOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeRaidsOK) GetPayload() *DescribeDeviceTypeRaidsOKBody { + return o.Payload +} + +func (o *DescribeDeviceTypeRaidsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeRaidsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceTypeRaidsDefault creates a DescribeDeviceTypeRaidsDefault with default headers values +func NewDescribeDeviceTypeRaidsDefault(code int) *DescribeDeviceTypeRaidsDefault { + return &DescribeDeviceTypeRaidsDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceTypeRaidsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceTypeRaidsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeRaidsDefaultBody +} + +// Code gets the status code for the describe device type raids default response +func (o *DescribeDeviceTypeRaidsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device type raids default response has a 2xx status code +func (o *DescribeDeviceTypeRaidsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device type raids default response has a 3xx status code +func (o *DescribeDeviceTypeRaidsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device type raids default response has a 4xx status code +func (o *DescribeDeviceTypeRaidsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device type raids default response has a 5xx status code +func (o *DescribeDeviceTypeRaidsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device type raids default response a status code equal to that given +func (o *DescribeDeviceTypeRaidsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceTypeRaidsDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeRaid][%d] describeDeviceTypeRaids default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeRaidsDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes/deviceTypeRaid][%d] describeDeviceTypeRaids default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeRaidsDefault) GetPayload() *DescribeDeviceTypeRaidsDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceTypeRaidsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeRaidsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceTypeRaidsDefaultBody describe device type raids default body +swagger:model DescribeDeviceTypeRaidsDefaultBody +*/ +type DescribeDeviceTypeRaidsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device type raids default body +func (o *DescribeDeviceTypeRaidsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeRaidsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeRaids default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceTypeRaidsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypeRaids default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeRaids default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeRaids default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type raids default body based on the context it is used +func (o *DescribeDeviceTypeRaidsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeRaidsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeRaids default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeRaids default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeRaidsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeRaidsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeRaidsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceTypeRaidsOKBody describe device type raids o k body +swagger:model DescribeDeviceTypeRaidsOKBody +*/ +type DescribeDeviceTypeRaidsOKBody struct { + + // result + Result []*models.RDeviceTypeRaid `json:"result"` +} + +// Validate validates this describe device type raids o k body +func (o *DescribeDeviceTypeRaidsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeRaidsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + for i := 0; i < len(o.Result); i++ { + if swag.IsZero(o.Result[i]) { // not required + continue + } + + if o.Result[i] != nil { + if err := o.Result[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeRaidsOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeRaidsOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this describe device type raids o k body based on the context it is used +func (o *DescribeDeviceTypeRaidsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeRaidsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Result); i++ { + + if o.Result[i] != nil { + if err := o.Result[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeRaidsOK" + "." + "result" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeRaidsOK" + "." + "result" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeRaidsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeRaidsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeRaidsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_responses.go new file mode 100644 index 0000000..1f10de5 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_type_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDeviceTypeReader is a Reader for the DescribeDeviceType structure. +type DescribeDeviceTypeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceTypeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceTypeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceTypeDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceTypeOK creates a DescribeDeviceTypeOK with default headers values +func NewDescribeDeviceTypeOK() *DescribeDeviceTypeOK { + return &DescribeDeviceTypeOK{} +} + +/* DescribeDeviceTypeOK describes a response with status code 200, with default header values. + +DescribeDeviceTypeOK describe device type o k +*/ +type DescribeDeviceTypeOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeOKBody +} + +// IsSuccess returns true when this describe device type o k response has a 2xx status code +func (o *DescribeDeviceTypeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device type o k response has a 3xx status code +func (o *DescribeDeviceTypeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device type o k response has a 4xx status code +func (o *DescribeDeviceTypeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device type o k response has a 5xx status code +func (o *DescribeDeviceTypeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device type o k response a status code equal to that given +func (o *DescribeDeviceTypeOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceTypeOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}][%d] describeDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeOK) String() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}][%d] describeDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypeOK) GetPayload() *DescribeDeviceTypeOKBody { + return o.Payload +} + +func (o *DescribeDeviceTypeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceTypeDefault creates a DescribeDeviceTypeDefault with default headers values +func NewDescribeDeviceTypeDefault(code int) *DescribeDeviceTypeDefault { + return &DescribeDeviceTypeDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceTypeDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceTypeDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypeDefaultBody +} + +// Code gets the status code for the describe device type default response +func (o *DescribeDeviceTypeDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device type default response has a 2xx status code +func (o *DescribeDeviceTypeDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device type default response has a 3xx status code +func (o *DescribeDeviceTypeDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device type default response has a 4xx status code +func (o *DescribeDeviceTypeDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device type default response has a 5xx status code +func (o *DescribeDeviceTypeDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device type default response a status code equal to that given +func (o *DescribeDeviceTypeDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceTypeDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}][%d] describeDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes/{device_type_id}][%d] describeDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypeDefault) GetPayload() *DescribeDeviceTypeDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceTypeDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypeDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceTypeDefaultBody describe device type default body +swagger:model DescribeDeviceTypeDefaultBody +*/ +type DescribeDeviceTypeDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device type default body +func (o *DescribeDeviceTypeDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceType default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceTypeDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceType default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type default body based on the context it is used +func (o *DescribeDeviceTypeDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceTypeOKBody describe device type o k body +swagger:model DescribeDeviceTypeOKBody +*/ +type DescribeDeviceTypeOKBody struct { + + // result + Result *models.DeviceTypeInfo `json:"result,omitempty"` +} + +// Validate validates this describe device type o k body +func (o *DescribeDeviceTypeOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device type o k body based on the context it is used +func (o *DescribeDeviceTypeOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypeOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypeOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypeOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypeOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_types_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_types_parameters.go new file mode 100644 index 0000000..515c3d8 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_types_parameters.go @@ -0,0 +1,495 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeDeviceTypesParams creates a new DescribeDeviceTypesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeDeviceTypesParams() *DescribeDeviceTypesParams { + return &DescribeDeviceTypesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeDeviceTypesParamsWithTimeout creates a new DescribeDeviceTypesParams object +// with the ability to set a timeout on a request. +func NewDescribeDeviceTypesParamsWithTimeout(timeout time.Duration) *DescribeDeviceTypesParams { + return &DescribeDeviceTypesParams{ + timeout: timeout, + } +} + +// NewDescribeDeviceTypesParamsWithContext creates a new DescribeDeviceTypesParams object +// with the ability to set a context for a request. +func NewDescribeDeviceTypesParamsWithContext(ctx context.Context) *DescribeDeviceTypesParams { + return &DescribeDeviceTypesParams{ + Context: ctx, + } +} + +// NewDescribeDeviceTypesParamsWithHTTPClient creates a new DescribeDeviceTypesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeDeviceTypesParamsWithHTTPClient(client *http.Client) *DescribeDeviceTypesParams { + return &DescribeDeviceTypesParams{ + HTTPClient: client, + } +} + +/* DescribeDeviceTypesParams contains all the parameters to send to the API endpoint + for the describe device types operation. + + Typically these are written to a http.Request. +*/ +type DescribeDeviceTypesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceSeries. + + 机型类型 + */ + DeviceSeries *string + + /* DeviceType. + + 机型规格 + */ + DeviceType *string + + /* DeviceTypeID. + + 机型id + */ + DeviceTypeID *string + + /* IdcID. + + 机房id + */ + IdcID *string + + // IsAll. + IsAll *string + + /* Name. + + 机型名称 + */ + Name *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe device types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypesParams) WithDefaults() *DescribeDeviceTypesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe device types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeDeviceTypesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe device types params +func (o *DescribeDeviceTypesParams) WithTimeout(timeout time.Duration) *DescribeDeviceTypesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe device types params +func (o *DescribeDeviceTypesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe device types params +func (o *DescribeDeviceTypesParams) WithContext(ctx context.Context) *DescribeDeviceTypesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe device types params +func (o *DescribeDeviceTypesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe device types params +func (o *DescribeDeviceTypesParams) WithHTTPClient(client *http.Client) *DescribeDeviceTypesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe device types params +func (o *DescribeDeviceTypesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe device types params +func (o *DescribeDeviceTypesParams) WithAuthorization(authorization string) *DescribeDeviceTypesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe device types params +func (o *DescribeDeviceTypesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe device types params +func (o *DescribeDeviceTypesParams) WithBmpLanguage(bmpLanguage *string) *DescribeDeviceTypesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe device types params +func (o *DescribeDeviceTypesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe device types params +func (o *DescribeDeviceTypesParams) WithBmpUserID(bmpUserID *string) *DescribeDeviceTypesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe device types params +func (o *DescribeDeviceTypesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceSeries adds the deviceSeries to the describe device types params +func (o *DescribeDeviceTypesParams) WithDeviceSeries(deviceSeries *string) *DescribeDeviceTypesParams { + o.SetDeviceSeries(deviceSeries) + return o +} + +// SetDeviceSeries adds the deviceSeries to the describe device types params +func (o *DescribeDeviceTypesParams) SetDeviceSeries(deviceSeries *string) { + o.DeviceSeries = deviceSeries +} + +// WithDeviceType adds the deviceType to the describe device types params +func (o *DescribeDeviceTypesParams) WithDeviceType(deviceType *string) *DescribeDeviceTypesParams { + o.SetDeviceType(deviceType) + return o +} + +// SetDeviceType adds the deviceType to the describe device types params +func (o *DescribeDeviceTypesParams) SetDeviceType(deviceType *string) { + o.DeviceType = deviceType +} + +// WithDeviceTypeID adds the deviceTypeID to the describe device types params +func (o *DescribeDeviceTypesParams) WithDeviceTypeID(deviceTypeID *string) *DescribeDeviceTypesParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe device types params +func (o *DescribeDeviceTypesParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithIdcID adds the idcID to the describe device types params +func (o *DescribeDeviceTypesParams) WithIdcID(idcID *string) *DescribeDeviceTypesParams { + o.SetIdcID(idcID) + return o +} + +// SetIdcID adds the idcId to the describe device types params +func (o *DescribeDeviceTypesParams) SetIdcID(idcID *string) { + o.IdcID = idcID +} + +// WithIsAll adds the isAll to the describe device types params +func (o *DescribeDeviceTypesParams) WithIsAll(isAll *string) *DescribeDeviceTypesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe device types params +func (o *DescribeDeviceTypesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithName adds the name to the describe device types params +func (o *DescribeDeviceTypesParams) WithName(name *string) *DescribeDeviceTypesParams { + o.SetName(name) + return o +} + +// SetName adds the name to the describe device types params +func (o *DescribeDeviceTypesParams) SetName(name *string) { + o.Name = name +} + +// WithPageNumber adds the pageNumber to the describe device types params +func (o *DescribeDeviceTypesParams) WithPageNumber(pageNumber *int64) *DescribeDeviceTypesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe device types params +func (o *DescribeDeviceTypesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe device types params +func (o *DescribeDeviceTypesParams) WithPageSize(pageSize *int64) *DescribeDeviceTypesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe device types params +func (o *DescribeDeviceTypesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe device types params +func (o *DescribeDeviceTypesParams) WithTraceID(traceID string) *DescribeDeviceTypesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe device types params +func (o *DescribeDeviceTypesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeDeviceTypesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceSeries != nil { + + // query param deviceSeries + var qrDeviceSeries string + + if o.DeviceSeries != nil { + qrDeviceSeries = *o.DeviceSeries + } + qDeviceSeries := qrDeviceSeries + if qDeviceSeries != "" { + + if err := r.SetQueryParam("deviceSeries", qDeviceSeries); err != nil { + return err + } + } + } + + if o.DeviceType != nil { + + // query param deviceType + var qrDeviceType string + + if o.DeviceType != nil { + qrDeviceType = *o.DeviceType + } + qDeviceType := qrDeviceType + if qDeviceType != "" { + + if err := r.SetQueryParam("deviceType", qDeviceType); err != nil { + return err + } + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.IdcID != nil { + + // query param idcId + var qrIdcID string + + if o.IdcID != nil { + qrIdcID = *o.IdcID + } + qIdcID := qrIdcID + if qIdcID != "" { + + if err := r.SetQueryParam("idcId", qIdcID); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_types_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_types_responses.go new file mode 100644 index 0000000..cc37ea3 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/describe_device_types_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeDeviceTypesReader is a Reader for the DescribeDeviceTypes structure. +type DescribeDeviceTypesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeDeviceTypesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeDeviceTypesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeDeviceTypesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeDeviceTypesOK creates a DescribeDeviceTypesOK with default headers values +func NewDescribeDeviceTypesOK() *DescribeDeviceTypesOK { + return &DescribeDeviceTypesOK{} +} + +/* DescribeDeviceTypesOK describes a response with status code 200, with default header values. + +DescribeDeviceTypesOK describe device types o k +*/ +type DescribeDeviceTypesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypesOKBody +} + +// IsSuccess returns true when this describe device types o k response has a 2xx status code +func (o *DescribeDeviceTypesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe device types o k response has a 3xx status code +func (o *DescribeDeviceTypesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe device types o k response has a 4xx status code +func (o *DescribeDeviceTypesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe device types o k response has a 5xx status code +func (o *DescribeDeviceTypesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe device types o k response a status code equal to that given +func (o *DescribeDeviceTypesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeDeviceTypesOK) Error() string { + return fmt.Sprintf("[GET /deviceTypes][%d] describeDeviceTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypesOK) String() string { + return fmt.Sprintf("[GET /deviceTypes][%d] describeDeviceTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeDeviceTypesOK) GetPayload() *DescribeDeviceTypesOKBody { + return o.Payload +} + +func (o *DescribeDeviceTypesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeDeviceTypesDefault creates a DescribeDeviceTypesDefault with default headers values +func NewDescribeDeviceTypesDefault(code int) *DescribeDeviceTypesDefault { + return &DescribeDeviceTypesDefault{ + _statusCode: code, + } +} + +/* DescribeDeviceTypesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeDeviceTypesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeDeviceTypesDefaultBody +} + +// Code gets the status code for the describe device types default response +func (o *DescribeDeviceTypesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe device types default response has a 2xx status code +func (o *DescribeDeviceTypesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe device types default response has a 3xx status code +func (o *DescribeDeviceTypesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe device types default response has a 4xx status code +func (o *DescribeDeviceTypesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe device types default response has a 5xx status code +func (o *DescribeDeviceTypesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe device types default response a status code equal to that given +func (o *DescribeDeviceTypesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeDeviceTypesDefault) Error() string { + return fmt.Sprintf("[GET /deviceTypes][%d] describeDeviceTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypesDefault) String() string { + return fmt.Sprintf("[GET /deviceTypes][%d] describeDeviceTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeDeviceTypesDefault) GetPayload() *DescribeDeviceTypesDefaultBody { + return o.Payload +} + +func (o *DescribeDeviceTypesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeDeviceTypesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeDeviceTypesDefaultBody describe device types default body +swagger:model DescribeDeviceTypesDefaultBody +*/ +type DescribeDeviceTypesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe device types default body +func (o *DescribeDeviceTypesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypes default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeDeviceTypesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeDeviceTypes default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device types default body based on the context it is used +func (o *DescribeDeviceTypesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeDeviceTypesOKBody describe device types o k body +swagger:model DescribeDeviceTypesOKBody +*/ +type DescribeDeviceTypesOKBody struct { + + // result + Result *models.DeviceTypeList `json:"result,omitempty"` +} + +// Validate validates this describe device types o k body +func (o *DescribeDeviceTypesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe device types o k body based on the context it is used +func (o *DescribeDeviceTypesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeDeviceTypesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeDeviceTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeDeviceTypesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeDeviceTypesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeDeviceTypesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeDeviceTypesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/device_type_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/device_type_client.go new file mode 100644 index 0000000..2fb876f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/device_type_client.go @@ -0,0 +1,437 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new device type API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for device type API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + AssociatedImage(params *AssociatedImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AssociatedImageOK, error) + + CreateDeviceType(params *CreateDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateDeviceTypeOK, error) + + DeleteDeviceType(params *DeleteDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteDeviceTypeOK, error) + + DescribeDeviceType(params *DescribeDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeOK, error) + + DescribeDeviceTypeImagePartitions(params *DescribeDeviceTypeImagePartitionsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeImagePartitionsOK, error) + + DescribeDeviceTypeImages(params *DescribeDeviceTypeImagesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeImagesOK, error) + + DescribeDeviceTypeRaids(params *DescribeDeviceTypeRaidsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeRaidsOK, error) + + DescribeDeviceTypes(params *DescribeDeviceTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypesOK, error) + + DissociatedImage(params *DissociatedImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DissociatedImageOK, error) + + ModifyDeviceType(params *ModifyDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyDeviceTypeOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + AssociatedImage AssociatedImage 机型绑定镜像 +*/ +func (a *Client) AssociatedImage(params *AssociatedImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AssociatedImageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewAssociatedImageParams() + } + op := &runtime.ClientOperation{ + ID: "associatedImage", + Method: "POST", + PathPattern: "/deviceTypes/associatedImage", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &AssociatedImageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*AssociatedImageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*AssociatedImageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + CreateDeviceType CreateDeviceType 添加机型 +*/ +func (a *Client) CreateDeviceType(params *CreateDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateDeviceTypeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateDeviceTypeParams() + } + op := &runtime.ClientOperation{ + ID: "createDeviceType", + Method: "POST", + PathPattern: "/deviceTypes", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateDeviceTypeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateDeviceTypeOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateDeviceTypeDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteDeviceType DeleteDeviceType 删除机型 +*/ +func (a *Client) DeleteDeviceType(params *DeleteDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteDeviceTypeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteDeviceTypeParams() + } + op := &runtime.ClientOperation{ + ID: "deleteDeviceType", + Method: "DELETE", + PathPattern: "/deviceTypes/{device_type_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteDeviceTypeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteDeviceTypeOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteDeviceTypeDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceType DescribeDeviceType 获取机型详情 +*/ +func (a *Client) DescribeDeviceType(params *DescribeDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceTypeParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceType", + Method: "GET", + PathPattern: "/deviceTypes/{device_type_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceTypeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceTypeOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceTypeDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceTypeImagePartitions QueryDeviceTypeImagePartition 根据机型,镜像,获取分区 +*/ +func (a *Client) DescribeDeviceTypeImagePartitions(params *DescribeDeviceTypeImagePartitionsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeImagePartitionsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceTypeImagePartitionsParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceTypeImagePartitions", + Method: "GET", + PathPattern: "/deviceTypes/deviceTypeImagePartition", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceTypeImagePartitionsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceTypeImagePartitionsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceTypeImagePartitionsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceTypeImages QueryDeviceTypeImage 根据机型获取镜像 +*/ +func (a *Client) DescribeDeviceTypeImages(params *DescribeDeviceTypeImagesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeImagesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceTypeImagesParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceTypeImages", + Method: "GET", + PathPattern: "/deviceTypes/deviceTypeImage", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceTypeImagesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceTypeImagesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceTypeImagesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceTypeRaids DescribeDeviceTypeRaids 根据机型获取raid +*/ +func (a *Client) DescribeDeviceTypeRaids(params *DescribeDeviceTypeRaidsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypeRaidsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceTypeRaidsParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceTypeRaids", + Method: "GET", + PathPattern: "/deviceTypes/deviceTypeRaid", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceTypeRaidsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceTypeRaidsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceTypeRaidsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeDeviceTypes DescribeDeviceTypes 获取机型列表 +*/ +func (a *Client) DescribeDeviceTypes(params *DescribeDeviceTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeDeviceTypesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeDeviceTypesParams() + } + op := &runtime.ClientOperation{ + ID: "describeDeviceTypes", + Method: "GET", + PathPattern: "/deviceTypes", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeDeviceTypesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeDeviceTypesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeDeviceTypesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DissociatedImage DissociatedImage 机型解绑镜像 +*/ +func (a *Client) DissociatedImage(params *DissociatedImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DissociatedImageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDissociatedImageParams() + } + op := &runtime.ClientOperation{ + ID: "dissociatedImage", + Method: "DELETE", + PathPattern: "/deviceTypes/dissociatedImage", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DissociatedImageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DissociatedImageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DissociatedImageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyDeviceType ModifyDeviceType 修改机型信息 +*/ +func (a *Client) ModifyDeviceType(params *ModifyDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyDeviceTypeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyDeviceTypeParams() + } + op := &runtime.ClientOperation{ + ID: "modifyDeviceType", + Method: "PUT", + PathPattern: "/deviceTypes/{device_type_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyDeviceTypeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyDeviceTypeOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyDeviceTypeDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/dissociated_image_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/dissociated_image_parameters.go new file mode 100644 index 0000000..1cf4d75 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/dissociated_image_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewDissociatedImageParams creates a new DissociatedImageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDissociatedImageParams() *DissociatedImageParams { + return &DissociatedImageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDissociatedImageParamsWithTimeout creates a new DissociatedImageParams object +// with the ability to set a timeout on a request. +func NewDissociatedImageParamsWithTimeout(timeout time.Duration) *DissociatedImageParams { + return &DissociatedImageParams{ + timeout: timeout, + } +} + +// NewDissociatedImageParamsWithContext creates a new DissociatedImageParams object +// with the ability to set a context for a request. +func NewDissociatedImageParamsWithContext(ctx context.Context) *DissociatedImageParams { + return &DissociatedImageParams{ + Context: ctx, + } +} + +// NewDissociatedImageParamsWithHTTPClient creates a new DissociatedImageParams object +// with the ability to set a custom HTTPClient for a request. +func NewDissociatedImageParamsWithHTTPClient(client *http.Client) *DissociatedImageParams { + return &DissociatedImageParams{ + HTTPClient: client, + } +} + +/* DissociatedImageParams contains all the parameters to send to the API endpoint + for the dissociated image operation. + + Typically these are written to a http.Request. +*/ +type DissociatedImageParams struct { + + // Body. + Body *models.DissociatedImageRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the dissociated image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DissociatedImageParams) WithDefaults() *DissociatedImageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the dissociated image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DissociatedImageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the dissociated image params +func (o *DissociatedImageParams) WithTimeout(timeout time.Duration) *DissociatedImageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the dissociated image params +func (o *DissociatedImageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the dissociated image params +func (o *DissociatedImageParams) WithContext(ctx context.Context) *DissociatedImageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the dissociated image params +func (o *DissociatedImageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the dissociated image params +func (o *DissociatedImageParams) WithHTTPClient(client *http.Client) *DissociatedImageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the dissociated image params +func (o *DissociatedImageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the dissociated image params +func (o *DissociatedImageParams) WithBody(body *models.DissociatedImageRequest) *DissociatedImageParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the dissociated image params +func (o *DissociatedImageParams) SetBody(body *models.DissociatedImageRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the dissociated image params +func (o *DissociatedImageParams) WithAuthorization(authorization string) *DissociatedImageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the dissociated image params +func (o *DissociatedImageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the dissociated image params +func (o *DissociatedImageParams) WithBmpLanguage(bmpLanguage *string) *DissociatedImageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the dissociated image params +func (o *DissociatedImageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the dissociated image params +func (o *DissociatedImageParams) WithBmpUserID(bmpUserID *string) *DissociatedImageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the dissociated image params +func (o *DissociatedImageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the dissociated image params +func (o *DissociatedImageParams) WithTraceID(traceID string) *DissociatedImageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the dissociated image params +func (o *DissociatedImageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DissociatedImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/dissociated_image_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/dissociated_image_responses.go new file mode 100644 index 0000000..09cb2e2 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/dissociated_image_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DissociatedImageReader is a Reader for the DissociatedImage structure. +type DissociatedImageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DissociatedImageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDissociatedImageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDissociatedImageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDissociatedImageOK creates a DissociatedImageOK with default headers values +func NewDissociatedImageOK() *DissociatedImageOK { + return &DissociatedImageOK{} +} + +/* DissociatedImageOK describes a response with status code 200, with default header values. + +A DissociatedImageResult is an response struct that is used to dissociated image result. +*/ +type DissociatedImageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DissociatedImageOKBody +} + +// IsSuccess returns true when this dissociated image o k response has a 2xx status code +func (o *DissociatedImageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this dissociated image o k response has a 3xx status code +func (o *DissociatedImageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this dissociated image o k response has a 4xx status code +func (o *DissociatedImageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this dissociated image o k response has a 5xx status code +func (o *DissociatedImageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this dissociated image o k response a status code equal to that given +func (o *DissociatedImageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DissociatedImageOK) Error() string { + return fmt.Sprintf("[DELETE /deviceTypes/dissociatedImage][%d] dissociatedImageOK %+v", 200, o.Payload) +} + +func (o *DissociatedImageOK) String() string { + return fmt.Sprintf("[DELETE /deviceTypes/dissociatedImage][%d] dissociatedImageOK %+v", 200, o.Payload) +} + +func (o *DissociatedImageOK) GetPayload() *DissociatedImageOKBody { + return o.Payload +} + +func (o *DissociatedImageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DissociatedImageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDissociatedImageDefault creates a DissociatedImageDefault with default headers values +func NewDissociatedImageDefault(code int) *DissociatedImageDefault { + return &DissociatedImageDefault{ + _statusCode: code, + } +} + +/* DissociatedImageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DissociatedImageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DissociatedImageDefaultBody +} + +// Code gets the status code for the dissociated image default response +func (o *DissociatedImageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this dissociated image default response has a 2xx status code +func (o *DissociatedImageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this dissociated image default response has a 3xx status code +func (o *DissociatedImageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this dissociated image default response has a 4xx status code +func (o *DissociatedImageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this dissociated image default response has a 5xx status code +func (o *DissociatedImageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this dissociated image default response a status code equal to that given +func (o *DissociatedImageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DissociatedImageDefault) Error() string { + return fmt.Sprintf("[DELETE /deviceTypes/dissociatedImage][%d] dissociatedImage default %+v", o._statusCode, o.Payload) +} + +func (o *DissociatedImageDefault) String() string { + return fmt.Sprintf("[DELETE /deviceTypes/dissociatedImage][%d] dissociatedImage default %+v", o._statusCode, o.Payload) +} + +func (o *DissociatedImageDefault) GetPayload() *DissociatedImageDefaultBody { + return o.Payload +} + +func (o *DissociatedImageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DissociatedImageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DissociatedImageDefaultBody dissociated image default body +swagger:model DissociatedImageDefaultBody +*/ +type DissociatedImageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this dissociated image default body +func (o *DissociatedImageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedImageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("dissociatedImage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DissociatedImageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("dissociatedImage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this dissociated image default body based on the context it is used +func (o *DissociatedImageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedImageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DissociatedImageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DissociatedImageDefaultBody) UnmarshalBinary(b []byte) error { + var res DissociatedImageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DissociatedImageOKBody dissociated image o k body +swagger:model DissociatedImageOKBody +*/ +type DissociatedImageOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this dissociated image o k body +func (o *DissociatedImageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedImageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this dissociated image o k body based on the context it is used +func (o *DissociatedImageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedImageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DissociatedImageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DissociatedImageOKBody) UnmarshalBinary(b []byte) error { + var res DissociatedImageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/modify_device_type_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/modify_device_type_parameters.go new file mode 100644 index 0000000..1e67b29 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/modify_device_type_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyDeviceTypeParams creates a new ModifyDeviceTypeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyDeviceTypeParams() *ModifyDeviceTypeParams { + return &ModifyDeviceTypeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyDeviceTypeParamsWithTimeout creates a new ModifyDeviceTypeParams object +// with the ability to set a timeout on a request. +func NewModifyDeviceTypeParamsWithTimeout(timeout time.Duration) *ModifyDeviceTypeParams { + return &ModifyDeviceTypeParams{ + timeout: timeout, + } +} + +// NewModifyDeviceTypeParamsWithContext creates a new ModifyDeviceTypeParams object +// with the ability to set a context for a request. +func NewModifyDeviceTypeParamsWithContext(ctx context.Context) *ModifyDeviceTypeParams { + return &ModifyDeviceTypeParams{ + Context: ctx, + } +} + +// NewModifyDeviceTypeParamsWithHTTPClient creates a new ModifyDeviceTypeParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyDeviceTypeParamsWithHTTPClient(client *http.Client) *ModifyDeviceTypeParams { + return &ModifyDeviceTypeParams{ + HTTPClient: client, + } +} + +/* ModifyDeviceTypeParams contains all the parameters to send to the API endpoint + for the modify device type operation. + + Typically these are written to a http.Request. +*/ +type ModifyDeviceTypeParams struct { + + // Body. + Body *models.ModifyDeviceTypeRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // DeviceTypeID. + DeviceTypeID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyDeviceTypeParams) WithDefaults() *ModifyDeviceTypeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyDeviceTypeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify device type params +func (o *ModifyDeviceTypeParams) WithTimeout(timeout time.Duration) *ModifyDeviceTypeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify device type params +func (o *ModifyDeviceTypeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify device type params +func (o *ModifyDeviceTypeParams) WithContext(ctx context.Context) *ModifyDeviceTypeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify device type params +func (o *ModifyDeviceTypeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify device type params +func (o *ModifyDeviceTypeParams) WithHTTPClient(client *http.Client) *ModifyDeviceTypeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify device type params +func (o *ModifyDeviceTypeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify device type params +func (o *ModifyDeviceTypeParams) WithBody(body *models.ModifyDeviceTypeRequest) *ModifyDeviceTypeParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify device type params +func (o *ModifyDeviceTypeParams) SetBody(body *models.ModifyDeviceTypeRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify device type params +func (o *ModifyDeviceTypeParams) WithAuthorization(authorization string) *ModifyDeviceTypeParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify device type params +func (o *ModifyDeviceTypeParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify device type params +func (o *ModifyDeviceTypeParams) WithBmpLanguage(bmpLanguage *string) *ModifyDeviceTypeParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify device type params +func (o *ModifyDeviceTypeParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify device type params +func (o *ModifyDeviceTypeParams) WithBmpUserID(bmpUserID *string) *ModifyDeviceTypeParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify device type params +func (o *ModifyDeviceTypeParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the modify device type params +func (o *ModifyDeviceTypeParams) WithDeviceTypeID(deviceTypeID string) *ModifyDeviceTypeParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the modify device type params +func (o *ModifyDeviceTypeParams) SetDeviceTypeID(deviceTypeID string) { + o.DeviceTypeID = deviceTypeID +} + +// WithTraceID adds the traceID to the modify device type params +func (o *ModifyDeviceTypeParams) WithTraceID(traceID string) *ModifyDeviceTypeParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify device type params +func (o *ModifyDeviceTypeParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyDeviceTypeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param device_type_id + if err := r.SetPathParam("device_type_id", o.DeviceTypeID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/modify_device_type_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/modify_device_type_responses.go new file mode 100644 index 0000000..339a323 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/device_type/modify_device_type_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package device_type + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyDeviceTypeReader is a Reader for the ModifyDeviceType structure. +type ModifyDeviceTypeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyDeviceTypeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyDeviceTypeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyDeviceTypeDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyDeviceTypeOK creates a ModifyDeviceTypeOK with default headers values +func NewModifyDeviceTypeOK() *ModifyDeviceTypeOK { + return &ModifyDeviceTypeOK{} +} + +/* ModifyDeviceTypeOK describes a response with status code 200, with default header values. + +A ModifyDeviceTypeResult is an response struct that is used to modify device type. +*/ +type ModifyDeviceTypeOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyDeviceTypeOKBody +} + +// IsSuccess returns true when this modify device type o k response has a 2xx status code +func (o *ModifyDeviceTypeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify device type o k response has a 3xx status code +func (o *ModifyDeviceTypeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify device type o k response has a 4xx status code +func (o *ModifyDeviceTypeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify device type o k response has a 5xx status code +func (o *ModifyDeviceTypeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify device type o k response a status code equal to that given +func (o *ModifyDeviceTypeOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyDeviceTypeOK) Error() string { + return fmt.Sprintf("[PUT /deviceTypes/{device_type_id}][%d] modifyDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *ModifyDeviceTypeOK) String() string { + return fmt.Sprintf("[PUT /deviceTypes/{device_type_id}][%d] modifyDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *ModifyDeviceTypeOK) GetPayload() *ModifyDeviceTypeOKBody { + return o.Payload +} + +func (o *ModifyDeviceTypeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyDeviceTypeOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyDeviceTypeDefault creates a ModifyDeviceTypeDefault with default headers values +func NewModifyDeviceTypeDefault(code int) *ModifyDeviceTypeDefault { + return &ModifyDeviceTypeDefault{ + _statusCode: code, + } +} + +/* ModifyDeviceTypeDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyDeviceTypeDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyDeviceTypeDefaultBody +} + +// Code gets the status code for the modify device type default response +func (o *ModifyDeviceTypeDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify device type default response has a 2xx status code +func (o *ModifyDeviceTypeDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify device type default response has a 3xx status code +func (o *ModifyDeviceTypeDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify device type default response has a 4xx status code +func (o *ModifyDeviceTypeDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify device type default response has a 5xx status code +func (o *ModifyDeviceTypeDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify device type default response a status code equal to that given +func (o *ModifyDeviceTypeDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyDeviceTypeDefault) Error() string { + return fmt.Sprintf("[PUT /deviceTypes/{device_type_id}][%d] modifyDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyDeviceTypeDefault) String() string { + return fmt.Sprintf("[PUT /deviceTypes/{device_type_id}][%d] modifyDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyDeviceTypeDefault) GetPayload() *ModifyDeviceTypeDefaultBody { + return o.Payload +} + +func (o *ModifyDeviceTypeDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyDeviceTypeDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyDeviceTypeDefaultBody modify device type default body +swagger:model ModifyDeviceTypeDefaultBody +*/ +type ModifyDeviceTypeDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify device type default body +func (o *ModifyDeviceTypeDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceTypeDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyDeviceType default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyDeviceTypeDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyDeviceType default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify device type default body based on the context it is used +func (o *ModifyDeviceTypeDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceTypeDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyDeviceTypeDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyDeviceTypeDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyDeviceTypeDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyDeviceTypeOKBody modify device type o k body +swagger:model ModifyDeviceTypeOKBody +*/ +type ModifyDeviceTypeOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify device type o k body +func (o *ModifyDeviceTypeOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceTypeOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify device type o k body based on the context it is used +func (o *ModifyDeviceTypeOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyDeviceTypeOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyDeviceTypeOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyDeviceTypeOKBody) UnmarshalBinary(b []byte) error { + var res ModifyDeviceTypeOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/create_idc_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/create_idc_parameters.go new file mode 100644 index 0000000..ae9f244 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/create_idc_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateIdcParams creates a new CreateIdcParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateIdcParams() *CreateIdcParams { + return &CreateIdcParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateIdcParamsWithTimeout creates a new CreateIdcParams object +// with the ability to set a timeout on a request. +func NewCreateIdcParamsWithTimeout(timeout time.Duration) *CreateIdcParams { + return &CreateIdcParams{ + timeout: timeout, + } +} + +// NewCreateIdcParamsWithContext creates a new CreateIdcParams object +// with the ability to set a context for a request. +func NewCreateIdcParamsWithContext(ctx context.Context) *CreateIdcParams { + return &CreateIdcParams{ + Context: ctx, + } +} + +// NewCreateIdcParamsWithHTTPClient creates a new CreateIdcParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateIdcParamsWithHTTPClient(client *http.Client) *CreateIdcParams { + return &CreateIdcParams{ + HTTPClient: client, + } +} + +/* CreateIdcParams contains all the parameters to send to the API endpoint + for the create idc operation. + + Typically these are written to a http.Request. +*/ +type CreateIdcParams struct { + + // Body. + Body *models.CreateIdcRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateIdcParams) WithDefaults() *CreateIdcParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateIdcParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create idc params +func (o *CreateIdcParams) WithTimeout(timeout time.Duration) *CreateIdcParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create idc params +func (o *CreateIdcParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create idc params +func (o *CreateIdcParams) WithContext(ctx context.Context) *CreateIdcParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create idc params +func (o *CreateIdcParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create idc params +func (o *CreateIdcParams) WithHTTPClient(client *http.Client) *CreateIdcParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create idc params +func (o *CreateIdcParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create idc params +func (o *CreateIdcParams) WithBody(body *models.CreateIdcRequest) *CreateIdcParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create idc params +func (o *CreateIdcParams) SetBody(body *models.CreateIdcRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create idc params +func (o *CreateIdcParams) WithAuthorization(authorization string) *CreateIdcParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create idc params +func (o *CreateIdcParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create idc params +func (o *CreateIdcParams) WithBmpLanguage(bmpLanguage *string) *CreateIdcParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create idc params +func (o *CreateIdcParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create idc params +func (o *CreateIdcParams) WithBmpUserID(bmpUserID *string) *CreateIdcParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create idc params +func (o *CreateIdcParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create idc params +func (o *CreateIdcParams) WithTraceID(traceID string) *CreateIdcParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create idc params +func (o *CreateIdcParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateIdcParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/create_idc_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/create_idc_responses.go new file mode 100644 index 0000000..c2a1d74 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/create_idc_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateIdcReader is a Reader for the CreateIdc structure. +type CreateIdcReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateIdcReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateIdcOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateIdcDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateIdcOK creates a CreateIdcOK with default headers values +func NewCreateIdcOK() *CreateIdcOK { + return &CreateIdcOK{} +} + +/* CreateIdcOK describes a response with status code 200, with default header values. + +A CreateIdcResult is an response struct that is used to describe create idc result. +*/ +type CreateIdcOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateIdcOKBody +} + +// IsSuccess returns true when this create idc o k response has a 2xx status code +func (o *CreateIdcOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create idc o k response has a 3xx status code +func (o *CreateIdcOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create idc o k response has a 4xx status code +func (o *CreateIdcOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create idc o k response has a 5xx status code +func (o *CreateIdcOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create idc o k response a status code equal to that given +func (o *CreateIdcOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateIdcOK) Error() string { + return fmt.Sprintf("[POST /idcs][%d] createIdcOK %+v", 200, o.Payload) +} + +func (o *CreateIdcOK) String() string { + return fmt.Sprintf("[POST /idcs][%d] createIdcOK %+v", 200, o.Payload) +} + +func (o *CreateIdcOK) GetPayload() *CreateIdcOKBody { + return o.Payload +} + +func (o *CreateIdcOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateIdcOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateIdcDefault creates a CreateIdcDefault with default headers values +func NewCreateIdcDefault(code int) *CreateIdcDefault { + return &CreateIdcDefault{ + _statusCode: code, + } +} + +/* CreateIdcDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateIdcDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateIdcDefaultBody +} + +// Code gets the status code for the create idc default response +func (o *CreateIdcDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create idc default response has a 2xx status code +func (o *CreateIdcDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create idc default response has a 3xx status code +func (o *CreateIdcDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create idc default response has a 4xx status code +func (o *CreateIdcDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create idc default response has a 5xx status code +func (o *CreateIdcDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create idc default response a status code equal to that given +func (o *CreateIdcDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateIdcDefault) Error() string { + return fmt.Sprintf("[POST /idcs][%d] createIdc default %+v", o._statusCode, o.Payload) +} + +func (o *CreateIdcDefault) String() string { + return fmt.Sprintf("[POST /idcs][%d] createIdc default %+v", o._statusCode, o.Payload) +} + +func (o *CreateIdcDefault) GetPayload() *CreateIdcDefaultBody { + return o.Payload +} + +func (o *CreateIdcDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateIdcDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateIdcDefaultBody create idc default body +swagger:model CreateIdcDefaultBody +*/ +type CreateIdcDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create idc default body +func (o *CreateIdcDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateIdcDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createIdc default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateIdcDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createIdc default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create idc default body based on the context it is used +func (o *CreateIdcDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateIdcDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateIdcDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateIdcDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateIdcDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateIdcOKBody create idc o k body +swagger:model CreateIdcOKBody +*/ +type CreateIdcOKBody struct { + + // result + Result *models.IdcID `json:"result,omitempty"` +} + +// Validate validates this create idc o k body +func (o *CreateIdcOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateIdcOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create idc o k body based on the context it is used +func (o *CreateIdcOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateIdcOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateIdcOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateIdcOKBody) UnmarshalBinary(b []byte) error { + var res CreateIdcOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/delete_idc_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/delete_idc_parameters.go new file mode 100644 index 0000000..4222fab --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/delete_idc_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteIdcParams creates a new DeleteIdcParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteIdcParams() *DeleteIdcParams { + return &DeleteIdcParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteIdcParamsWithTimeout creates a new DeleteIdcParams object +// with the ability to set a timeout on a request. +func NewDeleteIdcParamsWithTimeout(timeout time.Duration) *DeleteIdcParams { + return &DeleteIdcParams{ + timeout: timeout, + } +} + +// NewDeleteIdcParamsWithContext creates a new DeleteIdcParams object +// with the ability to set a context for a request. +func NewDeleteIdcParamsWithContext(ctx context.Context) *DeleteIdcParams { + return &DeleteIdcParams{ + Context: ctx, + } +} + +// NewDeleteIdcParamsWithHTTPClient creates a new DeleteIdcParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteIdcParamsWithHTTPClient(client *http.Client) *DeleteIdcParams { + return &DeleteIdcParams{ + HTTPClient: client, + } +} + +/* DeleteIdcParams contains all the parameters to send to the API endpoint + for the delete idc operation. + + Typically these are written to a http.Request. +*/ +type DeleteIdcParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // IdcID. + IdcID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteIdcParams) WithDefaults() *DeleteIdcParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteIdcParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete idc params +func (o *DeleteIdcParams) WithTimeout(timeout time.Duration) *DeleteIdcParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete idc params +func (o *DeleteIdcParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete idc params +func (o *DeleteIdcParams) WithContext(ctx context.Context) *DeleteIdcParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete idc params +func (o *DeleteIdcParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete idc params +func (o *DeleteIdcParams) WithHTTPClient(client *http.Client) *DeleteIdcParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete idc params +func (o *DeleteIdcParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete idc params +func (o *DeleteIdcParams) WithAuthorization(authorization string) *DeleteIdcParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete idc params +func (o *DeleteIdcParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete idc params +func (o *DeleteIdcParams) WithBmpLanguage(bmpLanguage *string) *DeleteIdcParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete idc params +func (o *DeleteIdcParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete idc params +func (o *DeleteIdcParams) WithBmpUserID(bmpUserID *string) *DeleteIdcParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete idc params +func (o *DeleteIdcParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIdcID adds the idcID to the delete idc params +func (o *DeleteIdcParams) WithIdcID(idcID string) *DeleteIdcParams { + o.SetIdcID(idcID) + return o +} + +// SetIdcID adds the idcId to the delete idc params +func (o *DeleteIdcParams) SetIdcID(idcID string) { + o.IdcID = idcID +} + +// WithTraceID adds the traceID to the delete idc params +func (o *DeleteIdcParams) WithTraceID(traceID string) *DeleteIdcParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete idc params +func (o *DeleteIdcParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteIdcParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param idc_id + if err := r.SetPathParam("idc_id", o.IdcID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/delete_idc_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/delete_idc_responses.go new file mode 100644 index 0000000..5aff303 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/delete_idc_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteIdcReader is a Reader for the DeleteIdc structure. +type DeleteIdcReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteIdcReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteIdcOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteIdcDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteIdcOK creates a DeleteIdcOK with default headers values +func NewDeleteIdcOK() *DeleteIdcOK { + return &DeleteIdcOK{} +} + +/* DeleteIdcOK describes a response with status code 200, with default header values. + +A DeleteIdcResult is an response struct that is used to delete idc. +*/ +type DeleteIdcOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteIdcOKBody +} + +// IsSuccess returns true when this delete idc o k response has a 2xx status code +func (o *DeleteIdcOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete idc o k response has a 3xx status code +func (o *DeleteIdcOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete idc o k response has a 4xx status code +func (o *DeleteIdcOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete idc o k response has a 5xx status code +func (o *DeleteIdcOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete idc o k response a status code equal to that given +func (o *DeleteIdcOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteIdcOK) Error() string { + return fmt.Sprintf("[DELETE /idcs/{idc_id}][%d] deleteIdcOK %+v", 200, o.Payload) +} + +func (o *DeleteIdcOK) String() string { + return fmt.Sprintf("[DELETE /idcs/{idc_id}][%d] deleteIdcOK %+v", 200, o.Payload) +} + +func (o *DeleteIdcOK) GetPayload() *DeleteIdcOKBody { + return o.Payload +} + +func (o *DeleteIdcOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteIdcOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteIdcDefault creates a DeleteIdcDefault with default headers values +func NewDeleteIdcDefault(code int) *DeleteIdcDefault { + return &DeleteIdcDefault{ + _statusCode: code, + } +} + +/* DeleteIdcDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteIdcDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteIdcDefaultBody +} + +// Code gets the status code for the delete idc default response +func (o *DeleteIdcDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete idc default response has a 2xx status code +func (o *DeleteIdcDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete idc default response has a 3xx status code +func (o *DeleteIdcDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete idc default response has a 4xx status code +func (o *DeleteIdcDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete idc default response has a 5xx status code +func (o *DeleteIdcDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete idc default response a status code equal to that given +func (o *DeleteIdcDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteIdcDefault) Error() string { + return fmt.Sprintf("[DELETE /idcs/{idc_id}][%d] deleteIdc default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteIdcDefault) String() string { + return fmt.Sprintf("[DELETE /idcs/{idc_id}][%d] deleteIdc default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteIdcDefault) GetPayload() *DeleteIdcDefaultBody { + return o.Payload +} + +func (o *DeleteIdcDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteIdcDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteIdcDefaultBody delete idc default body +swagger:model DeleteIdcDefaultBody +*/ +type DeleteIdcDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete idc default body +func (o *DeleteIdcDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteIdcDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteIdc default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteIdcDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteIdc default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete idc default body based on the context it is used +func (o *DeleteIdcDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteIdcDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteIdcDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteIdcDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteIdcDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteIdcOKBody delete idc o k body +swagger:model DeleteIdcOKBody +*/ +type DeleteIdcOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete idc o k body +func (o *DeleteIdcOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteIdcOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete idc o k body based on the context it is used +func (o *DeleteIdcOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteIdcOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteIdcOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteIdcOKBody) UnmarshalBinary(b []byte) error { + var res DeleteIdcOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idc_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idc_parameters.go new file mode 100644 index 0000000..8a6fc34 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idc_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeIdcParams creates a new DescribeIdcParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeIdcParams() *DescribeIdcParams { + return &DescribeIdcParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeIdcParamsWithTimeout creates a new DescribeIdcParams object +// with the ability to set a timeout on a request. +func NewDescribeIdcParamsWithTimeout(timeout time.Duration) *DescribeIdcParams { + return &DescribeIdcParams{ + timeout: timeout, + } +} + +// NewDescribeIdcParamsWithContext creates a new DescribeIdcParams object +// with the ability to set a context for a request. +func NewDescribeIdcParamsWithContext(ctx context.Context) *DescribeIdcParams { + return &DescribeIdcParams{ + Context: ctx, + } +} + +// NewDescribeIdcParamsWithHTTPClient creates a new DescribeIdcParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeIdcParamsWithHTTPClient(client *http.Client) *DescribeIdcParams { + return &DescribeIdcParams{ + HTTPClient: client, + } +} + +/* DescribeIdcParams contains all the parameters to send to the API endpoint + for the describe idc operation. + + Typically these are written to a http.Request. +*/ +type DescribeIdcParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // IdcID. + IdcID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeIdcParams) WithDefaults() *DescribeIdcParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeIdcParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe idc params +func (o *DescribeIdcParams) WithTimeout(timeout time.Duration) *DescribeIdcParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe idc params +func (o *DescribeIdcParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe idc params +func (o *DescribeIdcParams) WithContext(ctx context.Context) *DescribeIdcParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe idc params +func (o *DescribeIdcParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe idc params +func (o *DescribeIdcParams) WithHTTPClient(client *http.Client) *DescribeIdcParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe idc params +func (o *DescribeIdcParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe idc params +func (o *DescribeIdcParams) WithAuthorization(authorization string) *DescribeIdcParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe idc params +func (o *DescribeIdcParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe idc params +func (o *DescribeIdcParams) WithBmpLanguage(bmpLanguage *string) *DescribeIdcParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe idc params +func (o *DescribeIdcParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe idc params +func (o *DescribeIdcParams) WithBmpUserID(bmpUserID *string) *DescribeIdcParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe idc params +func (o *DescribeIdcParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIdcID adds the idcID to the describe idc params +func (o *DescribeIdcParams) WithIdcID(idcID string) *DescribeIdcParams { + o.SetIdcID(idcID) + return o +} + +// SetIdcID adds the idcId to the describe idc params +func (o *DescribeIdcParams) SetIdcID(idcID string) { + o.IdcID = idcID +} + +// WithTraceID adds the traceID to the describe idc params +func (o *DescribeIdcParams) WithTraceID(traceID string) *DescribeIdcParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe idc params +func (o *DescribeIdcParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeIdcParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param idc_id + if err := r.SetPathParam("idc_id", o.IdcID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idc_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idc_responses.go new file mode 100644 index 0000000..f0383d9 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idc_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeIdcReader is a Reader for the DescribeIdc structure. +type DescribeIdcReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeIdcReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeIdcOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeIdcDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeIdcOK creates a DescribeIdcOK with default headers values +func NewDescribeIdcOK() *DescribeIdcOK { + return &DescribeIdcOK{} +} + +/* DescribeIdcOK describes a response with status code 200, with default header values. + +A DescribeIdcResult is an response struct that is used to describe idc. +*/ +type DescribeIdcOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeIdcOKBody +} + +// IsSuccess returns true when this describe idc o k response has a 2xx status code +func (o *DescribeIdcOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe idc o k response has a 3xx status code +func (o *DescribeIdcOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe idc o k response has a 4xx status code +func (o *DescribeIdcOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe idc o k response has a 5xx status code +func (o *DescribeIdcOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe idc o k response a status code equal to that given +func (o *DescribeIdcOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeIdcOK) Error() string { + return fmt.Sprintf("[GET /idcs/{idc_id}][%d] describeIdcOK %+v", 200, o.Payload) +} + +func (o *DescribeIdcOK) String() string { + return fmt.Sprintf("[GET /idcs/{idc_id}][%d] describeIdcOK %+v", 200, o.Payload) +} + +func (o *DescribeIdcOK) GetPayload() *DescribeIdcOKBody { + return o.Payload +} + +func (o *DescribeIdcOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeIdcOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeIdcDefault creates a DescribeIdcDefault with default headers values +func NewDescribeIdcDefault(code int) *DescribeIdcDefault { + return &DescribeIdcDefault{ + _statusCode: code, + } +} + +/* DescribeIdcDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeIdcDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeIdcDefaultBody +} + +// Code gets the status code for the describe idc default response +func (o *DescribeIdcDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe idc default response has a 2xx status code +func (o *DescribeIdcDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe idc default response has a 3xx status code +func (o *DescribeIdcDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe idc default response has a 4xx status code +func (o *DescribeIdcDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe idc default response has a 5xx status code +func (o *DescribeIdcDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe idc default response a status code equal to that given +func (o *DescribeIdcDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeIdcDefault) Error() string { + return fmt.Sprintf("[GET /idcs/{idc_id}][%d] describeIdc default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeIdcDefault) String() string { + return fmt.Sprintf("[GET /idcs/{idc_id}][%d] describeIdc default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeIdcDefault) GetPayload() *DescribeIdcDefaultBody { + return o.Payload +} + +func (o *DescribeIdcDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeIdcDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeIdcDefaultBody describe idc default body +swagger:model DescribeIdcDefaultBody +*/ +type DescribeIdcDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe idc default body +func (o *DescribeIdcDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeIdc default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeIdcDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeIdc default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe idc default body based on the context it is used +func (o *DescribeIdcDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeIdcDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeIdcDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeIdcDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeIdcOKBody describe idc o k body +swagger:model DescribeIdcOKBody +*/ +type DescribeIdcOKBody struct { + + // result + Result *models.IdcInfo `json:"result,omitempty"` +} + +// Validate validates this describe idc o k body +func (o *DescribeIdcOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe idc o k body based on the context it is used +func (o *DescribeIdcOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeIdcOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeIdcOKBody) UnmarshalBinary(b []byte) error { + var res DescribeIdcOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idcs_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idcs_parameters.go new file mode 100644 index 0000000..b70ce2a --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idcs_parameters.go @@ -0,0 +1,430 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeIdcsParams creates a new DescribeIdcsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeIdcsParams() *DescribeIdcsParams { + return &DescribeIdcsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeIdcsParamsWithTimeout creates a new DescribeIdcsParams object +// with the ability to set a timeout on a request. +func NewDescribeIdcsParamsWithTimeout(timeout time.Duration) *DescribeIdcsParams { + return &DescribeIdcsParams{ + timeout: timeout, + } +} + +// NewDescribeIdcsParamsWithContext creates a new DescribeIdcsParams object +// with the ability to set a context for a request. +func NewDescribeIdcsParamsWithContext(ctx context.Context) *DescribeIdcsParams { + return &DescribeIdcsParams{ + Context: ctx, + } +} + +// NewDescribeIdcsParamsWithHTTPClient creates a new DescribeIdcsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeIdcsParamsWithHTTPClient(client *http.Client) *DescribeIdcsParams { + return &DescribeIdcsParams{ + HTTPClient: client, + } +} + +/* DescribeIdcsParams contains all the parameters to send to the API endpoint + for the describe idcs operation. + + Typically these are written to a http.Request. +*/ +type DescribeIdcsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否显示所有 + */ + IsAll *string + + /* Level. + + 机房等级 + */ + Level *string + + /* Name. + + 机房名称 + */ + Name *string + + /* NameEn. + + 机房英文名称 + */ + NameEn *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe idcs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeIdcsParams) WithDefaults() *DescribeIdcsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe idcs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeIdcsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe idcs params +func (o *DescribeIdcsParams) WithTimeout(timeout time.Duration) *DescribeIdcsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe idcs params +func (o *DescribeIdcsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe idcs params +func (o *DescribeIdcsParams) WithContext(ctx context.Context) *DescribeIdcsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe idcs params +func (o *DescribeIdcsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe idcs params +func (o *DescribeIdcsParams) WithHTTPClient(client *http.Client) *DescribeIdcsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe idcs params +func (o *DescribeIdcsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe idcs params +func (o *DescribeIdcsParams) WithAuthorization(authorization string) *DescribeIdcsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe idcs params +func (o *DescribeIdcsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe idcs params +func (o *DescribeIdcsParams) WithBmpLanguage(bmpLanguage *string) *DescribeIdcsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe idcs params +func (o *DescribeIdcsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe idcs params +func (o *DescribeIdcsParams) WithBmpUserID(bmpUserID *string) *DescribeIdcsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe idcs params +func (o *DescribeIdcsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe idcs params +func (o *DescribeIdcsParams) WithIsAll(isAll *string) *DescribeIdcsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe idcs params +func (o *DescribeIdcsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithLevel adds the level to the describe idcs params +func (o *DescribeIdcsParams) WithLevel(level *string) *DescribeIdcsParams { + o.SetLevel(level) + return o +} + +// SetLevel adds the level to the describe idcs params +func (o *DescribeIdcsParams) SetLevel(level *string) { + o.Level = level +} + +// WithName adds the name to the describe idcs params +func (o *DescribeIdcsParams) WithName(name *string) *DescribeIdcsParams { + o.SetName(name) + return o +} + +// SetName adds the name to the describe idcs params +func (o *DescribeIdcsParams) SetName(name *string) { + o.Name = name +} + +// WithNameEn adds the nameEn to the describe idcs params +func (o *DescribeIdcsParams) WithNameEn(nameEn *string) *DescribeIdcsParams { + o.SetNameEn(nameEn) + return o +} + +// SetNameEn adds the nameEn to the describe idcs params +func (o *DescribeIdcsParams) SetNameEn(nameEn *string) { + o.NameEn = nameEn +} + +// WithPageNumber adds the pageNumber to the describe idcs params +func (o *DescribeIdcsParams) WithPageNumber(pageNumber *int64) *DescribeIdcsParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe idcs params +func (o *DescribeIdcsParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe idcs params +func (o *DescribeIdcsParams) WithPageSize(pageSize *int64) *DescribeIdcsParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe idcs params +func (o *DescribeIdcsParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe idcs params +func (o *DescribeIdcsParams) WithTraceID(traceID string) *DescribeIdcsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe idcs params +func (o *DescribeIdcsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeIdcsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Level != nil { + + // query param level + var qrLevel string + + if o.Level != nil { + qrLevel = *o.Level + } + qLevel := qrLevel + if qLevel != "" { + + if err := r.SetQueryParam("level", qLevel); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.NameEn != nil { + + // query param nameEn + var qrNameEn string + + if o.NameEn != nil { + qrNameEn = *o.NameEn + } + qNameEn := qrNameEn + if qNameEn != "" { + + if err := r.SetQueryParam("nameEn", qNameEn); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idcs_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idcs_responses.go new file mode 100644 index 0000000..2f5ba8a --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/describe_idcs_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeIdcsReader is a Reader for the DescribeIdcs structure. +type DescribeIdcsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeIdcsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeIdcsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeIdcsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeIdcsOK creates a DescribeIdcsOK with default headers values +func NewDescribeIdcsOK() *DescribeIdcsOK { + return &DescribeIdcsOK{} +} + +/* DescribeIdcsOK describes a response with status code 200, with default header values. + +A DescribIdcsResult is an response struct that is used to describe idcs. +*/ +type DescribeIdcsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeIdcsOKBody +} + +// IsSuccess returns true when this describe idcs o k response has a 2xx status code +func (o *DescribeIdcsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe idcs o k response has a 3xx status code +func (o *DescribeIdcsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe idcs o k response has a 4xx status code +func (o *DescribeIdcsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe idcs o k response has a 5xx status code +func (o *DescribeIdcsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe idcs o k response a status code equal to that given +func (o *DescribeIdcsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeIdcsOK) Error() string { + return fmt.Sprintf("[GET /idcs][%d] describeIdcsOK %+v", 200, o.Payload) +} + +func (o *DescribeIdcsOK) String() string { + return fmt.Sprintf("[GET /idcs][%d] describeIdcsOK %+v", 200, o.Payload) +} + +func (o *DescribeIdcsOK) GetPayload() *DescribeIdcsOKBody { + return o.Payload +} + +func (o *DescribeIdcsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeIdcsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeIdcsDefault creates a DescribeIdcsDefault with default headers values +func NewDescribeIdcsDefault(code int) *DescribeIdcsDefault { + return &DescribeIdcsDefault{ + _statusCode: code, + } +} + +/* DescribeIdcsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeIdcsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeIdcsDefaultBody +} + +// Code gets the status code for the describe idcs default response +func (o *DescribeIdcsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe idcs default response has a 2xx status code +func (o *DescribeIdcsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe idcs default response has a 3xx status code +func (o *DescribeIdcsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe idcs default response has a 4xx status code +func (o *DescribeIdcsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe idcs default response has a 5xx status code +func (o *DescribeIdcsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe idcs default response a status code equal to that given +func (o *DescribeIdcsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeIdcsDefault) Error() string { + return fmt.Sprintf("[GET /idcs][%d] describeIdcs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeIdcsDefault) String() string { + return fmt.Sprintf("[GET /idcs][%d] describeIdcs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeIdcsDefault) GetPayload() *DescribeIdcsDefaultBody { + return o.Payload +} + +func (o *DescribeIdcsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeIdcsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeIdcsDefaultBody describe idcs default body +swagger:model DescribeIdcsDefaultBody +*/ +type DescribeIdcsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe idcs default body +func (o *DescribeIdcsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeIdcs default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeIdcsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeIdcs default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcs default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe idcs default body based on the context it is used +func (o *DescribeIdcsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcs default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeIdcsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeIdcsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeIdcsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeIdcsOKBody describe idcs o k body +swagger:model DescribeIdcsOKBody +*/ +type DescribeIdcsOKBody struct { + + // result + Result *models.IdcList `json:"result,omitempty"` +} + +// Validate validates this describe idcs o k body +func (o *DescribeIdcsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe idcs o k body based on the context it is used +func (o *DescribeIdcsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeIdcsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeIdcsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeIdcsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeIdcsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeIdcsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeIdcsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/idc_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/idc_client.go new file mode 100644 index 0000000..81b2591 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/idc_client.go @@ -0,0 +1,237 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new idc API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for idc API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateIdc(params *CreateIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateIdcOK, error) + + DeleteIdc(params *DeleteIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteIdcOK, error) + + DescribeIdc(params *DescribeIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeIdcOK, error) + + DescribeIdcs(params *DescribeIdcsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeIdcsOK, error) + + ModifyIdc(params *ModifyIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyIdcOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateIdc CreateIdc 创建idc(接口废弃,不对外开放) +*/ +func (a *Client) CreateIdc(params *CreateIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateIdcOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateIdcParams() + } + op := &runtime.ClientOperation{ + ID: "createIdc", + Method: "POST", + PathPattern: "/idcs", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateIdcReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateIdcOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateIdcDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteIdc DeleteIdc 删除idc +*/ +func (a *Client) DeleteIdc(params *DeleteIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteIdcOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteIdcParams() + } + op := &runtime.ClientOperation{ + ID: "deleteIdc", + Method: "DELETE", + PathPattern: "/idcs/{idc_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteIdcReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteIdcOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteIdcDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeIdc DescribeIdc 获取idc详情 +*/ +func (a *Client) DescribeIdc(params *DescribeIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeIdcOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeIdcParams() + } + op := &runtime.ClientOperation{ + ID: "describeIdc", + Method: "GET", + PathPattern: "/idcs/{idc_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeIdcReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeIdcOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeIdcDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeIdcs DescribeIdcs 获取idc列表 +*/ +func (a *Client) DescribeIdcs(params *DescribeIdcsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeIdcsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeIdcsParams() + } + op := &runtime.ClientOperation{ + ID: "describeIdcs", + Method: "GET", + PathPattern: "/idcs", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeIdcsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeIdcsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeIdcsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyIdc ModifyIdc 修改idc信息 +*/ +func (a *Client) ModifyIdc(params *ModifyIdcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyIdcOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyIdcParams() + } + op := &runtime.ClientOperation{ + ID: "modifyIdc", + Method: "PUT", + PathPattern: "/idcs/{idc_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyIdcReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyIdcOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyIdcDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/modify_idc_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/modify_idc_parameters.go new file mode 100644 index 0000000..41e22dc --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/modify_idc_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyIdcParams creates a new ModifyIdcParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyIdcParams() *ModifyIdcParams { + return &ModifyIdcParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyIdcParamsWithTimeout creates a new ModifyIdcParams object +// with the ability to set a timeout on a request. +func NewModifyIdcParamsWithTimeout(timeout time.Duration) *ModifyIdcParams { + return &ModifyIdcParams{ + timeout: timeout, + } +} + +// NewModifyIdcParamsWithContext creates a new ModifyIdcParams object +// with the ability to set a context for a request. +func NewModifyIdcParamsWithContext(ctx context.Context) *ModifyIdcParams { + return &ModifyIdcParams{ + Context: ctx, + } +} + +// NewModifyIdcParamsWithHTTPClient creates a new ModifyIdcParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyIdcParamsWithHTTPClient(client *http.Client) *ModifyIdcParams { + return &ModifyIdcParams{ + HTTPClient: client, + } +} + +/* ModifyIdcParams contains all the parameters to send to the API endpoint + for the modify idc operation. + + Typically these are written to a http.Request. +*/ +type ModifyIdcParams struct { + + // Body. + Body *models.ModifyIdcRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // IdcID. + IdcID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyIdcParams) WithDefaults() *ModifyIdcParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify idc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyIdcParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify idc params +func (o *ModifyIdcParams) WithTimeout(timeout time.Duration) *ModifyIdcParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify idc params +func (o *ModifyIdcParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify idc params +func (o *ModifyIdcParams) WithContext(ctx context.Context) *ModifyIdcParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify idc params +func (o *ModifyIdcParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify idc params +func (o *ModifyIdcParams) WithHTTPClient(client *http.Client) *ModifyIdcParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify idc params +func (o *ModifyIdcParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify idc params +func (o *ModifyIdcParams) WithBody(body *models.ModifyIdcRequest) *ModifyIdcParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify idc params +func (o *ModifyIdcParams) SetBody(body *models.ModifyIdcRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify idc params +func (o *ModifyIdcParams) WithAuthorization(authorization string) *ModifyIdcParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify idc params +func (o *ModifyIdcParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify idc params +func (o *ModifyIdcParams) WithBmpLanguage(bmpLanguage *string) *ModifyIdcParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify idc params +func (o *ModifyIdcParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify idc params +func (o *ModifyIdcParams) WithBmpUserID(bmpUserID *string) *ModifyIdcParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify idc params +func (o *ModifyIdcParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIdcID adds the idcID to the modify idc params +func (o *ModifyIdcParams) WithIdcID(idcID string) *ModifyIdcParams { + o.SetIdcID(idcID) + return o +} + +// SetIdcID adds the idcId to the modify idc params +func (o *ModifyIdcParams) SetIdcID(idcID string) { + o.IdcID = idcID +} + +// WithTraceID adds the traceID to the modify idc params +func (o *ModifyIdcParams) WithTraceID(traceID string) *ModifyIdcParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify idc params +func (o *ModifyIdcParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyIdcParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param idc_id + if err := r.SetPathParam("idc_id", o.IdcID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/modify_idc_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/modify_idc_responses.go new file mode 100644 index 0000000..fe29766 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/idc/modify_idc_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package idc + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyIdcReader is a Reader for the ModifyIdc structure. +type ModifyIdcReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyIdcReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyIdcOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyIdcDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyIdcOK creates a ModifyIdcOK with default headers values +func NewModifyIdcOK() *ModifyIdcOK { + return &ModifyIdcOK{} +} + +/* ModifyIdcOK describes a response with status code 200, with default header values. + +A ModifyIdcResult is an response struct that is used to modify idc. +*/ +type ModifyIdcOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyIdcOKBody +} + +// IsSuccess returns true when this modify idc o k response has a 2xx status code +func (o *ModifyIdcOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify idc o k response has a 3xx status code +func (o *ModifyIdcOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify idc o k response has a 4xx status code +func (o *ModifyIdcOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify idc o k response has a 5xx status code +func (o *ModifyIdcOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify idc o k response a status code equal to that given +func (o *ModifyIdcOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyIdcOK) Error() string { + return fmt.Sprintf("[PUT /idcs/{idc_id}][%d] modifyIdcOK %+v", 200, o.Payload) +} + +func (o *ModifyIdcOK) String() string { + return fmt.Sprintf("[PUT /idcs/{idc_id}][%d] modifyIdcOK %+v", 200, o.Payload) +} + +func (o *ModifyIdcOK) GetPayload() *ModifyIdcOKBody { + return o.Payload +} + +func (o *ModifyIdcOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyIdcOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyIdcDefault creates a ModifyIdcDefault with default headers values +func NewModifyIdcDefault(code int) *ModifyIdcDefault { + return &ModifyIdcDefault{ + _statusCode: code, + } +} + +/* ModifyIdcDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyIdcDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyIdcDefaultBody +} + +// Code gets the status code for the modify idc default response +func (o *ModifyIdcDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify idc default response has a 2xx status code +func (o *ModifyIdcDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify idc default response has a 3xx status code +func (o *ModifyIdcDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify idc default response has a 4xx status code +func (o *ModifyIdcDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify idc default response has a 5xx status code +func (o *ModifyIdcDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify idc default response a status code equal to that given +func (o *ModifyIdcDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyIdcDefault) Error() string { + return fmt.Sprintf("[PUT /idcs/{idc_id}][%d] modifyIdc default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyIdcDefault) String() string { + return fmt.Sprintf("[PUT /idcs/{idc_id}][%d] modifyIdc default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyIdcDefault) GetPayload() *ModifyIdcDefaultBody { + return o.Payload +} + +func (o *ModifyIdcDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyIdcDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyIdcDefaultBody modify idc default body +swagger:model ModifyIdcDefaultBody +*/ +type ModifyIdcDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify idc default body +func (o *ModifyIdcDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyIdcDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyIdc default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyIdcDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyIdc default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify idc default body based on the context it is used +func (o *ModifyIdcDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyIdcDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyIdc default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyIdc default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyIdcDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyIdcDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyIdcDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyIdcOKBody modify idc o k body +swagger:model ModifyIdcOKBody +*/ +type ModifyIdcOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify idc o k body +func (o *ModifyIdcOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyIdcOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify idc o k body based on the context it is used +func (o *ModifyIdcOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyIdcOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyIdcOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyIdcOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyIdcOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyIdcOKBody) UnmarshalBinary(b []byte) error { + var res ModifyIdcOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/associated_device_type_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/associated_device_type_parameters.go new file mode 100644 index 0000000..a331625 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/associated_device_type_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewAssociatedDeviceTypeParams creates a new AssociatedDeviceTypeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewAssociatedDeviceTypeParams() *AssociatedDeviceTypeParams { + return &AssociatedDeviceTypeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewAssociatedDeviceTypeParamsWithTimeout creates a new AssociatedDeviceTypeParams object +// with the ability to set a timeout on a request. +func NewAssociatedDeviceTypeParamsWithTimeout(timeout time.Duration) *AssociatedDeviceTypeParams { + return &AssociatedDeviceTypeParams{ + timeout: timeout, + } +} + +// NewAssociatedDeviceTypeParamsWithContext creates a new AssociatedDeviceTypeParams object +// with the ability to set a context for a request. +func NewAssociatedDeviceTypeParamsWithContext(ctx context.Context) *AssociatedDeviceTypeParams { + return &AssociatedDeviceTypeParams{ + Context: ctx, + } +} + +// NewAssociatedDeviceTypeParamsWithHTTPClient creates a new AssociatedDeviceTypeParams object +// with the ability to set a custom HTTPClient for a request. +func NewAssociatedDeviceTypeParamsWithHTTPClient(client *http.Client) *AssociatedDeviceTypeParams { + return &AssociatedDeviceTypeParams{ + HTTPClient: client, + } +} + +/* AssociatedDeviceTypeParams contains all the parameters to send to the API endpoint + for the associated device type operation. + + Typically these are written to a http.Request. +*/ +type AssociatedDeviceTypeParams struct { + + // Body. + Body *models.AssociateDeviceTypeRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the associated device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AssociatedDeviceTypeParams) WithDefaults() *AssociatedDeviceTypeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the associated device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *AssociatedDeviceTypeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the associated device type params +func (o *AssociatedDeviceTypeParams) WithTimeout(timeout time.Duration) *AssociatedDeviceTypeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the associated device type params +func (o *AssociatedDeviceTypeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the associated device type params +func (o *AssociatedDeviceTypeParams) WithContext(ctx context.Context) *AssociatedDeviceTypeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the associated device type params +func (o *AssociatedDeviceTypeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the associated device type params +func (o *AssociatedDeviceTypeParams) WithHTTPClient(client *http.Client) *AssociatedDeviceTypeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the associated device type params +func (o *AssociatedDeviceTypeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the associated device type params +func (o *AssociatedDeviceTypeParams) WithBody(body *models.AssociateDeviceTypeRequest) *AssociatedDeviceTypeParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the associated device type params +func (o *AssociatedDeviceTypeParams) SetBody(body *models.AssociateDeviceTypeRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the associated device type params +func (o *AssociatedDeviceTypeParams) WithAuthorization(authorization string) *AssociatedDeviceTypeParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the associated device type params +func (o *AssociatedDeviceTypeParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the associated device type params +func (o *AssociatedDeviceTypeParams) WithBmpLanguage(bmpLanguage *string) *AssociatedDeviceTypeParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the associated device type params +func (o *AssociatedDeviceTypeParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the associated device type params +func (o *AssociatedDeviceTypeParams) WithBmpUserID(bmpUserID *string) *AssociatedDeviceTypeParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the associated device type params +func (o *AssociatedDeviceTypeParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the associated device type params +func (o *AssociatedDeviceTypeParams) WithTraceID(traceID string) *AssociatedDeviceTypeParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the associated device type params +func (o *AssociatedDeviceTypeParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *AssociatedDeviceTypeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/associated_device_type_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/associated_device_type_responses.go new file mode 100644 index 0000000..3857d1f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/associated_device_type_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// AssociatedDeviceTypeReader is a Reader for the AssociatedDeviceType structure. +type AssociatedDeviceTypeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *AssociatedDeviceTypeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewAssociatedDeviceTypeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewAssociatedDeviceTypeDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewAssociatedDeviceTypeOK creates a AssociatedDeviceTypeOK with default headers values +func NewAssociatedDeviceTypeOK() *AssociatedDeviceTypeOK { + return &AssociatedDeviceTypeOK{} +} + +/* AssociatedDeviceTypeOK describes a response with status code 200, with default header values. + +AssociatedDeviceTypeOK associated device type o k +*/ +type AssociatedDeviceTypeOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *AssociatedDeviceTypeOKBody +} + +// IsSuccess returns true when this associated device type o k response has a 2xx status code +func (o *AssociatedDeviceTypeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this associated device type o k response has a 3xx status code +func (o *AssociatedDeviceTypeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this associated device type o k response has a 4xx status code +func (o *AssociatedDeviceTypeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this associated device type o k response has a 5xx status code +func (o *AssociatedDeviceTypeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this associated device type o k response a status code equal to that given +func (o *AssociatedDeviceTypeOK) IsCode(code int) bool { + return code == 200 +} + +func (o *AssociatedDeviceTypeOK) Error() string { + return fmt.Sprintf("[POST /images/associatedDeviceType][%d] associatedDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *AssociatedDeviceTypeOK) String() string { + return fmt.Sprintf("[POST /images/associatedDeviceType][%d] associatedDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *AssociatedDeviceTypeOK) GetPayload() *AssociatedDeviceTypeOKBody { + return o.Payload +} + +func (o *AssociatedDeviceTypeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AssociatedDeviceTypeOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAssociatedDeviceTypeDefault creates a AssociatedDeviceTypeDefault with default headers values +func NewAssociatedDeviceTypeDefault(code int) *AssociatedDeviceTypeDefault { + return &AssociatedDeviceTypeDefault{ + _statusCode: code, + } +} + +/* AssociatedDeviceTypeDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type AssociatedDeviceTypeDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *AssociatedDeviceTypeDefaultBody +} + +// Code gets the status code for the associated device type default response +func (o *AssociatedDeviceTypeDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this associated device type default response has a 2xx status code +func (o *AssociatedDeviceTypeDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this associated device type default response has a 3xx status code +func (o *AssociatedDeviceTypeDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this associated device type default response has a 4xx status code +func (o *AssociatedDeviceTypeDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this associated device type default response has a 5xx status code +func (o *AssociatedDeviceTypeDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this associated device type default response a status code equal to that given +func (o *AssociatedDeviceTypeDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *AssociatedDeviceTypeDefault) Error() string { + return fmt.Sprintf("[POST /images/associatedDeviceType][%d] associatedDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *AssociatedDeviceTypeDefault) String() string { + return fmt.Sprintf("[POST /images/associatedDeviceType][%d] associatedDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *AssociatedDeviceTypeDefault) GetPayload() *AssociatedDeviceTypeDefaultBody { + return o.Payload +} + +func (o *AssociatedDeviceTypeDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(AssociatedDeviceTypeDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*AssociatedDeviceTypeDefaultBody associated device type default body +swagger:model AssociatedDeviceTypeDefaultBody +*/ +type AssociatedDeviceTypeDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this associated device type default body +func (o *AssociatedDeviceTypeDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedDeviceTypeDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("associatedDeviceType default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *AssociatedDeviceTypeDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("associatedDeviceType default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this associated device type default body based on the context it is used +func (o *AssociatedDeviceTypeDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedDeviceTypeDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AssociatedDeviceTypeDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AssociatedDeviceTypeDefaultBody) UnmarshalBinary(b []byte) error { + var res AssociatedDeviceTypeDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*AssociatedDeviceTypeOKBody associated device type o k body +swagger:model AssociatedDeviceTypeOKBody +*/ +type AssociatedDeviceTypeOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this associated device type o k body +func (o *AssociatedDeviceTypeOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedDeviceTypeOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this associated device type o k body based on the context it is used +func (o *AssociatedDeviceTypeOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *AssociatedDeviceTypeOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("associatedDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("associatedDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *AssociatedDeviceTypeOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *AssociatedDeviceTypeOKBody) UnmarshalBinary(b []byte) error { + var res AssociatedDeviceTypeOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/create_image_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/create_image_parameters.go new file mode 100644 index 0000000..9bc6e9f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/create_image_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateImageParams creates a new CreateImageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateImageParams() *CreateImageParams { + return &CreateImageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateImageParamsWithTimeout creates a new CreateImageParams object +// with the ability to set a timeout on a request. +func NewCreateImageParamsWithTimeout(timeout time.Duration) *CreateImageParams { + return &CreateImageParams{ + timeout: timeout, + } +} + +// NewCreateImageParamsWithContext creates a new CreateImageParams object +// with the ability to set a context for a request. +func NewCreateImageParamsWithContext(ctx context.Context) *CreateImageParams { + return &CreateImageParams{ + Context: ctx, + } +} + +// NewCreateImageParamsWithHTTPClient creates a new CreateImageParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateImageParamsWithHTTPClient(client *http.Client) *CreateImageParams { + return &CreateImageParams{ + HTTPClient: client, + } +} + +/* CreateImageParams contains all the parameters to send to the API endpoint + for the create image operation. + + Typically these are written to a http.Request. +*/ +type CreateImageParams struct { + + // Body. + Body *models.CreateImageRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateImageParams) WithDefaults() *CreateImageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateImageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create image params +func (o *CreateImageParams) WithTimeout(timeout time.Duration) *CreateImageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create image params +func (o *CreateImageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create image params +func (o *CreateImageParams) WithContext(ctx context.Context) *CreateImageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create image params +func (o *CreateImageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create image params +func (o *CreateImageParams) WithHTTPClient(client *http.Client) *CreateImageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create image params +func (o *CreateImageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create image params +func (o *CreateImageParams) WithBody(body *models.CreateImageRequest) *CreateImageParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create image params +func (o *CreateImageParams) SetBody(body *models.CreateImageRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create image params +func (o *CreateImageParams) WithAuthorization(authorization string) *CreateImageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create image params +func (o *CreateImageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create image params +func (o *CreateImageParams) WithBmpLanguage(bmpLanguage *string) *CreateImageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create image params +func (o *CreateImageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create image params +func (o *CreateImageParams) WithBmpUserID(bmpUserID *string) *CreateImageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create image params +func (o *CreateImageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create image params +func (o *CreateImageParams) WithTraceID(traceID string) *CreateImageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create image params +func (o *CreateImageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/create_image_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/create_image_responses.go new file mode 100644 index 0000000..9db3776 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/create_image_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateImageReader is a Reader for the CreateImage structure. +type CreateImageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateImageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateImageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateImageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateImageOK creates a CreateImageOK with default headers values +func NewCreateImageOK() *CreateImageOK { + return &CreateImageOK{} +} + +/* CreateImageOK describes a response with status code 200, with default header values. + +A CreateImageResult is an response struct that is used to describe create image result. +*/ +type CreateImageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateImageOKBody +} + +// IsSuccess returns true when this create image o k response has a 2xx status code +func (o *CreateImageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create image o k response has a 3xx status code +func (o *CreateImageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create image o k response has a 4xx status code +func (o *CreateImageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create image o k response has a 5xx status code +func (o *CreateImageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create image o k response a status code equal to that given +func (o *CreateImageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateImageOK) Error() string { + return fmt.Sprintf("[POST /images][%d] createImageOK %+v", 200, o.Payload) +} + +func (o *CreateImageOK) String() string { + return fmt.Sprintf("[POST /images][%d] createImageOK %+v", 200, o.Payload) +} + +func (o *CreateImageOK) GetPayload() *CreateImageOKBody { + return o.Payload +} + +func (o *CreateImageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateImageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateImageDefault creates a CreateImageDefault with default headers values +func NewCreateImageDefault(code int) *CreateImageDefault { + return &CreateImageDefault{ + _statusCode: code, + } +} + +/* CreateImageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateImageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateImageDefaultBody +} + +// Code gets the status code for the create image default response +func (o *CreateImageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create image default response has a 2xx status code +func (o *CreateImageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create image default response has a 3xx status code +func (o *CreateImageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create image default response has a 4xx status code +func (o *CreateImageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create image default response has a 5xx status code +func (o *CreateImageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create image default response a status code equal to that given +func (o *CreateImageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateImageDefault) Error() string { + return fmt.Sprintf("[POST /images][%d] createImage default %+v", o._statusCode, o.Payload) +} + +func (o *CreateImageDefault) String() string { + return fmt.Sprintf("[POST /images][%d] createImage default %+v", o._statusCode, o.Payload) +} + +func (o *CreateImageDefault) GetPayload() *CreateImageDefaultBody { + return o.Payload +} + +func (o *CreateImageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateImageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateImageDefaultBody create image default body +swagger:model CreateImageDefaultBody +*/ +type CreateImageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create image default body +func (o *CreateImageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateImageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createImage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateImageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createImage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create image default body based on the context it is used +func (o *CreateImageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateImageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateImageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateImageDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateImageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateImageOKBody create image o k body +swagger:model CreateImageOKBody +*/ +type CreateImageOKBody struct { + + // result + Result *models.ImageID `json:"result,omitempty"` +} + +// Validate validates this create image o k body +func (o *CreateImageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateImageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create image o k body based on the context it is used +func (o *CreateImageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateImageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateImageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateImageOKBody) UnmarshalBinary(b []byte) error { + var res CreateImageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/delete_image_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/delete_image_parameters.go new file mode 100644 index 0000000..4de11c2 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/delete_image_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteImageParams creates a new DeleteImageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteImageParams() *DeleteImageParams { + return &DeleteImageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteImageParamsWithTimeout creates a new DeleteImageParams object +// with the ability to set a timeout on a request. +func NewDeleteImageParamsWithTimeout(timeout time.Duration) *DeleteImageParams { + return &DeleteImageParams{ + timeout: timeout, + } +} + +// NewDeleteImageParamsWithContext creates a new DeleteImageParams object +// with the ability to set a context for a request. +func NewDeleteImageParamsWithContext(ctx context.Context) *DeleteImageParams { + return &DeleteImageParams{ + Context: ctx, + } +} + +// NewDeleteImageParamsWithHTTPClient creates a new DeleteImageParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteImageParamsWithHTTPClient(client *http.Client) *DeleteImageParams { + return &DeleteImageParams{ + HTTPClient: client, + } +} + +/* DeleteImageParams contains all the parameters to send to the API endpoint + for the delete image operation. + + Typically these are written to a http.Request. +*/ +type DeleteImageParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // ImageID. + ImageID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteImageParams) WithDefaults() *DeleteImageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteImageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete image params +func (o *DeleteImageParams) WithTimeout(timeout time.Duration) *DeleteImageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete image params +func (o *DeleteImageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete image params +func (o *DeleteImageParams) WithContext(ctx context.Context) *DeleteImageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete image params +func (o *DeleteImageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete image params +func (o *DeleteImageParams) WithHTTPClient(client *http.Client) *DeleteImageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete image params +func (o *DeleteImageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete image params +func (o *DeleteImageParams) WithAuthorization(authorization string) *DeleteImageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete image params +func (o *DeleteImageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete image params +func (o *DeleteImageParams) WithBmpLanguage(bmpLanguage *string) *DeleteImageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete image params +func (o *DeleteImageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete image params +func (o *DeleteImageParams) WithBmpUserID(bmpUserID *string) *DeleteImageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete image params +func (o *DeleteImageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithImageID adds the imageID to the delete image params +func (o *DeleteImageParams) WithImageID(imageID string) *DeleteImageParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the delete image params +func (o *DeleteImageParams) SetImageID(imageID string) { + o.ImageID = imageID +} + +// WithTraceID adds the traceID to the delete image params +func (o *DeleteImageParams) WithTraceID(traceID string) *DeleteImageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete image params +func (o *DeleteImageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param image_id + if err := r.SetPathParam("image_id", o.ImageID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/delete_image_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/delete_image_responses.go new file mode 100644 index 0000000..66ce257 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/delete_image_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteImageReader is a Reader for the DeleteImage structure. +type DeleteImageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteImageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteImageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteImageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteImageOK creates a DeleteImageOK with default headers values +func NewDeleteImageOK() *DeleteImageOK { + return &DeleteImageOK{} +} + +/* DeleteImageOK describes a response with status code 200, with default header values. + +A DeleteImageResult is an response struct that is used to delete image. +*/ +type DeleteImageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteImageOKBody +} + +// IsSuccess returns true when this delete image o k response has a 2xx status code +func (o *DeleteImageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete image o k response has a 3xx status code +func (o *DeleteImageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete image o k response has a 4xx status code +func (o *DeleteImageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete image o k response has a 5xx status code +func (o *DeleteImageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete image o k response a status code equal to that given +func (o *DeleteImageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteImageOK) Error() string { + return fmt.Sprintf("[DELETE /images/{image_id}][%d] deleteImageOK %+v", 200, o.Payload) +} + +func (o *DeleteImageOK) String() string { + return fmt.Sprintf("[DELETE /images/{image_id}][%d] deleteImageOK %+v", 200, o.Payload) +} + +func (o *DeleteImageOK) GetPayload() *DeleteImageOKBody { + return o.Payload +} + +func (o *DeleteImageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteImageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteImageDefault creates a DeleteImageDefault with default headers values +func NewDeleteImageDefault(code int) *DeleteImageDefault { + return &DeleteImageDefault{ + _statusCode: code, + } +} + +/* DeleteImageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteImageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteImageDefaultBody +} + +// Code gets the status code for the delete image default response +func (o *DeleteImageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete image default response has a 2xx status code +func (o *DeleteImageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete image default response has a 3xx status code +func (o *DeleteImageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete image default response has a 4xx status code +func (o *DeleteImageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete image default response has a 5xx status code +func (o *DeleteImageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete image default response a status code equal to that given +func (o *DeleteImageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteImageDefault) Error() string { + return fmt.Sprintf("[DELETE /images/{image_id}][%d] deleteImage default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteImageDefault) String() string { + return fmt.Sprintf("[DELETE /images/{image_id}][%d] deleteImage default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteImageDefault) GetPayload() *DeleteImageDefaultBody { + return o.Payload +} + +func (o *DeleteImageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteImageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteImageDefaultBody delete image default body +swagger:model DeleteImageDefaultBody +*/ +type DeleteImageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete image default body +func (o *DeleteImageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteImageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteImage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteImageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteImage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete image default body based on the context it is used +func (o *DeleteImageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteImageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteImageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteImageDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteImageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteImageOKBody delete image o k body +swagger:model DeleteImageOKBody +*/ +type DeleteImageOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete image o k body +func (o *DeleteImageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteImageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete image o k body based on the context it is used +func (o *DeleteImageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteImageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteImageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteImageOKBody) UnmarshalBinary(b []byte) error { + var res DeleteImageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_device_types_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_device_types_parameters.go new file mode 100644 index 0000000..00dad00 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_device_types_parameters.go @@ -0,0 +1,423 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeImageDeviceTypesParams creates a new DescribeImageDeviceTypesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeImageDeviceTypesParams() *DescribeImageDeviceTypesParams { + return &DescribeImageDeviceTypesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeImageDeviceTypesParamsWithTimeout creates a new DescribeImageDeviceTypesParams object +// with the ability to set a timeout on a request. +func NewDescribeImageDeviceTypesParamsWithTimeout(timeout time.Duration) *DescribeImageDeviceTypesParams { + return &DescribeImageDeviceTypesParams{ + timeout: timeout, + } +} + +// NewDescribeImageDeviceTypesParamsWithContext creates a new DescribeImageDeviceTypesParams object +// with the ability to set a context for a request. +func NewDescribeImageDeviceTypesParamsWithContext(ctx context.Context) *DescribeImageDeviceTypesParams { + return &DescribeImageDeviceTypesParams{ + Context: ctx, + } +} + +// NewDescribeImageDeviceTypesParamsWithHTTPClient creates a new DescribeImageDeviceTypesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeImageDeviceTypesParamsWithHTTPClient(client *http.Client) *DescribeImageDeviceTypesParams { + return &DescribeImageDeviceTypesParams{ + HTTPClient: client, + } +} + +/* DescribeImageDeviceTypesParams contains all the parameters to send to the API endpoint + for the describe image device types operation. + + Typically these are written to a http.Request. +*/ +type DescribeImageDeviceTypesParams struct { + + /* Architecture. + + 体系架构 + */ + Architecture *string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* ImageID. + + 镜像ID + */ + ImageID string + + /* IsAll. + + 是否显示全部 + */ + IsAll *string + + /* IsBind. + + 镜像是否绑定了机型,0查询该镜像没有绑定的机型列表 1查询该镜像已经绑定了的机型列表 + */ + IsBind *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe image device types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImageDeviceTypesParams) WithDefaults() *DescribeImageDeviceTypesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe image device types params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImageDeviceTypesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithTimeout(timeout time.Duration) *DescribeImageDeviceTypesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithContext(ctx context.Context) *DescribeImageDeviceTypesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithHTTPClient(client *http.Client) *DescribeImageDeviceTypesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithArchitecture adds the architecture to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithArchitecture(architecture *string) *DescribeImageDeviceTypesParams { + o.SetArchitecture(architecture) + return o +} + +// SetArchitecture adds the architecture to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetArchitecture(architecture *string) { + o.Architecture = architecture +} + +// WithAuthorization adds the authorization to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithAuthorization(authorization string) *DescribeImageDeviceTypesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithBmpLanguage(bmpLanguage *string) *DescribeImageDeviceTypesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithBmpUserID(bmpUserID *string) *DescribeImageDeviceTypesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithImageID adds the imageID to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithImageID(imageID string) *DescribeImageDeviceTypesParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetImageID(imageID string) { + o.ImageID = imageID +} + +// WithIsAll adds the isAll to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithIsAll(isAll *string) *DescribeImageDeviceTypesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithIsBind adds the isBind to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithIsBind(isBind *string) *DescribeImageDeviceTypesParams { + o.SetIsBind(isBind) + return o +} + +// SetIsBind adds the isBind to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetIsBind(isBind *string) { + o.IsBind = isBind +} + +// WithPageNumber adds the pageNumber to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithPageNumber(pageNumber *int64) *DescribeImageDeviceTypesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithPageSize(pageSize *int64) *DescribeImageDeviceTypesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe image device types params +func (o *DescribeImageDeviceTypesParams) WithTraceID(traceID string) *DescribeImageDeviceTypesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe image device types params +func (o *DescribeImageDeviceTypesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeImageDeviceTypesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Architecture != nil { + + // query param architecture + var qrArchitecture string + + if o.Architecture != nil { + qrArchitecture = *o.Architecture + } + qArchitecture := qrArchitecture + if qArchitecture != "" { + + if err := r.SetQueryParam("architecture", qArchitecture); err != nil { + return err + } + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // query param imageId + qrImageID := o.ImageID + qImageID := qrImageID + if qImageID != "" { + + if err := r.SetQueryParam("imageId", qImageID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.IsBind != nil { + + // query param isBind + var qrIsBind string + + if o.IsBind != nil { + qrIsBind = *o.IsBind + } + qIsBind := qrIsBind + if qIsBind != "" { + + if err := r.SetQueryParam("isBind", qIsBind); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_device_types_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_device_types_responses.go new file mode 100644 index 0000000..0261ecc --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_device_types_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeImageDeviceTypesReader is a Reader for the DescribeImageDeviceTypes structure. +type DescribeImageDeviceTypesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeImageDeviceTypesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeImageDeviceTypesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeImageDeviceTypesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeImageDeviceTypesOK creates a DescribeImageDeviceTypesOK with default headers values +func NewDescribeImageDeviceTypesOK() *DescribeImageDeviceTypesOK { + return &DescribeImageDeviceTypesOK{} +} + +/* DescribeImageDeviceTypesOK describes a response with status code 200, with default header values. + +DescribeImageDeviceTypesOK describe image device types o k +*/ +type DescribeImageDeviceTypesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImageDeviceTypesOKBody +} + +// IsSuccess returns true when this describe image device types o k response has a 2xx status code +func (o *DescribeImageDeviceTypesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe image device types o k response has a 3xx status code +func (o *DescribeImageDeviceTypesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe image device types o k response has a 4xx status code +func (o *DescribeImageDeviceTypesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe image device types o k response has a 5xx status code +func (o *DescribeImageDeviceTypesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe image device types o k response a status code equal to that given +func (o *DescribeImageDeviceTypesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeImageDeviceTypesOK) Error() string { + return fmt.Sprintf("[GET /images/imageDeviceTypes][%d] describeImageDeviceTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeImageDeviceTypesOK) String() string { + return fmt.Sprintf("[GET /images/imageDeviceTypes][%d] describeImageDeviceTypesOK %+v", 200, o.Payload) +} + +func (o *DescribeImageDeviceTypesOK) GetPayload() *DescribeImageDeviceTypesOKBody { + return o.Payload +} + +func (o *DescribeImageDeviceTypesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImageDeviceTypesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeImageDeviceTypesDefault creates a DescribeImageDeviceTypesDefault with default headers values +func NewDescribeImageDeviceTypesDefault(code int) *DescribeImageDeviceTypesDefault { + return &DescribeImageDeviceTypesDefault{ + _statusCode: code, + } +} + +/* DescribeImageDeviceTypesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeImageDeviceTypesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImageDeviceTypesDefaultBody +} + +// Code gets the status code for the describe image device types default response +func (o *DescribeImageDeviceTypesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe image device types default response has a 2xx status code +func (o *DescribeImageDeviceTypesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe image device types default response has a 3xx status code +func (o *DescribeImageDeviceTypesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe image device types default response has a 4xx status code +func (o *DescribeImageDeviceTypesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe image device types default response has a 5xx status code +func (o *DescribeImageDeviceTypesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe image device types default response a status code equal to that given +func (o *DescribeImageDeviceTypesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeImageDeviceTypesDefault) Error() string { + return fmt.Sprintf("[GET /images/imageDeviceTypes][%d] describeImageDeviceTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImageDeviceTypesDefault) String() string { + return fmt.Sprintf("[GET /images/imageDeviceTypes][%d] describeImageDeviceTypes default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImageDeviceTypesDefault) GetPayload() *DescribeImageDeviceTypesDefaultBody { + return o.Payload +} + +func (o *DescribeImageDeviceTypesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImageDeviceTypesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeImageDeviceTypesDefaultBody describe image device types default body +swagger:model DescribeImageDeviceTypesDefaultBody +*/ +type DescribeImageDeviceTypesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe image device types default body +func (o *DescribeImageDeviceTypesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDeviceTypesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeImageDeviceTypes default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeImageDeviceTypesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeImageDeviceTypes default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageDeviceTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageDeviceTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe image device types default body based on the context it is used +func (o *DescribeImageDeviceTypesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDeviceTypesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageDeviceTypes default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageDeviceTypes default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImageDeviceTypesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImageDeviceTypesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeImageDeviceTypesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeImageDeviceTypesOKBody describe image device types o k body +swagger:model DescribeImageDeviceTypesOKBody +*/ +type DescribeImageDeviceTypesOKBody struct { + + // result + Result *models.DeviceTypeList `json:"result,omitempty"` +} + +// Validate validates this describe image device types o k body +func (o *DescribeImageDeviceTypesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDeviceTypesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageDeviceTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageDeviceTypesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe image device types o k body based on the context it is used +func (o *DescribeImageDeviceTypesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDeviceTypesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageDeviceTypesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageDeviceTypesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImageDeviceTypesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImageDeviceTypesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeImageDeviceTypesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_parameters.go new file mode 100644 index 0000000..7057d4b --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeImageParams creates a new DescribeImageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeImageParams() *DescribeImageParams { + return &DescribeImageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeImageParamsWithTimeout creates a new DescribeImageParams object +// with the ability to set a timeout on a request. +func NewDescribeImageParamsWithTimeout(timeout time.Duration) *DescribeImageParams { + return &DescribeImageParams{ + timeout: timeout, + } +} + +// NewDescribeImageParamsWithContext creates a new DescribeImageParams object +// with the ability to set a context for a request. +func NewDescribeImageParamsWithContext(ctx context.Context) *DescribeImageParams { + return &DescribeImageParams{ + Context: ctx, + } +} + +// NewDescribeImageParamsWithHTTPClient creates a new DescribeImageParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeImageParamsWithHTTPClient(client *http.Client) *DescribeImageParams { + return &DescribeImageParams{ + HTTPClient: client, + } +} + +/* DescribeImageParams contains all the parameters to send to the API endpoint + for the describe image operation. + + Typically these are written to a http.Request. +*/ +type DescribeImageParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // ImageID. + ImageID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImageParams) WithDefaults() *DescribeImageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe image params +func (o *DescribeImageParams) WithTimeout(timeout time.Duration) *DescribeImageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe image params +func (o *DescribeImageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe image params +func (o *DescribeImageParams) WithContext(ctx context.Context) *DescribeImageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe image params +func (o *DescribeImageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe image params +func (o *DescribeImageParams) WithHTTPClient(client *http.Client) *DescribeImageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe image params +func (o *DescribeImageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe image params +func (o *DescribeImageParams) WithAuthorization(authorization string) *DescribeImageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe image params +func (o *DescribeImageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe image params +func (o *DescribeImageParams) WithBmpLanguage(bmpLanguage *string) *DescribeImageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe image params +func (o *DescribeImageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe image params +func (o *DescribeImageParams) WithBmpUserID(bmpUserID *string) *DescribeImageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe image params +func (o *DescribeImageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithImageID adds the imageID to the describe image params +func (o *DescribeImageParams) WithImageID(imageID string) *DescribeImageParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the describe image params +func (o *DescribeImageParams) SetImageID(imageID string) { + o.ImageID = imageID +} + +// WithTraceID adds the traceID to the describe image params +func (o *DescribeImageParams) WithTraceID(traceID string) *DescribeImageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe image params +func (o *DescribeImageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param image_id + if err := r.SetPathParam("image_id", o.ImageID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_responses.go new file mode 100644 index 0000000..feb0907 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_image_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeImageReader is a Reader for the DescribeImage structure. +type DescribeImageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeImageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeImageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeImageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeImageOK creates a DescribeImageOK with default headers values +func NewDescribeImageOK() *DescribeImageOK { + return &DescribeImageOK{} +} + +/* DescribeImageOK describes a response with status code 200, with default header values. + +A DescribeImageResult is an response struct that is used to describe image. +*/ +type DescribeImageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImageOKBody +} + +// IsSuccess returns true when this describe image o k response has a 2xx status code +func (o *DescribeImageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe image o k response has a 3xx status code +func (o *DescribeImageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe image o k response has a 4xx status code +func (o *DescribeImageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe image o k response has a 5xx status code +func (o *DescribeImageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe image o k response a status code equal to that given +func (o *DescribeImageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeImageOK) Error() string { + return fmt.Sprintf("[GET /images/{image_id}][%d] describeImageOK %+v", 200, o.Payload) +} + +func (o *DescribeImageOK) String() string { + return fmt.Sprintf("[GET /images/{image_id}][%d] describeImageOK %+v", 200, o.Payload) +} + +func (o *DescribeImageOK) GetPayload() *DescribeImageOKBody { + return o.Payload +} + +func (o *DescribeImageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeImageDefault creates a DescribeImageDefault with default headers values +func NewDescribeImageDefault(code int) *DescribeImageDefault { + return &DescribeImageDefault{ + _statusCode: code, + } +} + +/* DescribeImageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeImageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImageDefaultBody +} + +// Code gets the status code for the describe image default response +func (o *DescribeImageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe image default response has a 2xx status code +func (o *DescribeImageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe image default response has a 3xx status code +func (o *DescribeImageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe image default response has a 4xx status code +func (o *DescribeImageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe image default response has a 5xx status code +func (o *DescribeImageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe image default response a status code equal to that given +func (o *DescribeImageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeImageDefault) Error() string { + return fmt.Sprintf("[GET /images/{image_id}][%d] describeImage default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImageDefault) String() string { + return fmt.Sprintf("[GET /images/{image_id}][%d] describeImage default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImageDefault) GetPayload() *DescribeImageDefaultBody { + return o.Payload +} + +func (o *DescribeImageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeImageDefaultBody describe image default body +swagger:model DescribeImageDefaultBody +*/ +type DescribeImageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe image default body +func (o *DescribeImageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeImage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeImageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeImage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe image default body based on the context it is used +func (o *DescribeImageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImageDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeImageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeImageOKBody describe image o k body +swagger:model DescribeImageOKBody +*/ +type DescribeImageOKBody struct { + + // result + Result *models.ImageInfo `json:"result,omitempty"` +} + +// Validate validates this describe image o k body +func (o *DescribeImageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe image o k body based on the context it is used +func (o *DescribeImageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImageOKBody) UnmarshalBinary(b []byte) error { + var res DescribeImageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_images_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_images_parameters.go new file mode 100644 index 0000000..7e11911 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_images_parameters.go @@ -0,0 +1,645 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeImagesParams creates a new DescribeImagesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeImagesParams() *DescribeImagesParams { + return &DescribeImagesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeImagesParamsWithTimeout creates a new DescribeImagesParams object +// with the ability to set a timeout on a request. +func NewDescribeImagesParamsWithTimeout(timeout time.Duration) *DescribeImagesParams { + return &DescribeImagesParams{ + timeout: timeout, + } +} + +// NewDescribeImagesParamsWithContext creates a new DescribeImagesParams object +// with the ability to set a context for a request. +func NewDescribeImagesParamsWithContext(ctx context.Context) *DescribeImagesParams { + return &DescribeImagesParams{ + Context: ctx, + } +} + +// NewDescribeImagesParamsWithHTTPClient creates a new DescribeImagesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeImagesParamsWithHTTPClient(client *http.Client) *DescribeImagesParams { + return &DescribeImagesParams{ + HTTPClient: client, + } +} + +/* DescribeImagesParams contains all the parameters to send to the API endpoint + for the describe images operation. + + Typically these are written to a http.Request. +*/ +type DescribeImagesParams struct { + + /* Architecture. + + 体系架构 + */ + Architecture *string + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceTypeID. + + 设备类型id + */ + DeviceTypeID *string + + /* ImageID. + + 镜像ID + */ + ImageID *string + + /* ImageIds. + + 镜像ID,数组,支持多个 + */ + ImageIDs []string + + /* ImageName. + + 镜像名称 + */ + ImageName *string + + /* IsAll. + + 是否显示全部 + */ + IsAll *string + + /* OsID. + + 操作系统ID + */ + OsID *string + + /* OsType. + + 操作系统平台 + */ + OsType *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* Source. + + 镜像类型,预置,自定义 + */ + Source *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* Version. + + 版本号 + */ + Version *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe images params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImagesParams) WithDefaults() *DescribeImagesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe images params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeImagesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe images params +func (o *DescribeImagesParams) WithTimeout(timeout time.Duration) *DescribeImagesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe images params +func (o *DescribeImagesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe images params +func (o *DescribeImagesParams) WithContext(ctx context.Context) *DescribeImagesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe images params +func (o *DescribeImagesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe images params +func (o *DescribeImagesParams) WithHTTPClient(client *http.Client) *DescribeImagesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe images params +func (o *DescribeImagesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithArchitecture adds the architecture to the describe images params +func (o *DescribeImagesParams) WithArchitecture(architecture *string) *DescribeImagesParams { + o.SetArchitecture(architecture) + return o +} + +// SetArchitecture adds the architecture to the describe images params +func (o *DescribeImagesParams) SetArchitecture(architecture *string) { + o.Architecture = architecture +} + +// WithAuthorization adds the authorization to the describe images params +func (o *DescribeImagesParams) WithAuthorization(authorization string) *DescribeImagesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe images params +func (o *DescribeImagesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe images params +func (o *DescribeImagesParams) WithBmpLanguage(bmpLanguage *string) *DescribeImagesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe images params +func (o *DescribeImagesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe images params +func (o *DescribeImagesParams) WithBmpUserID(bmpUserID *string) *DescribeImagesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe images params +func (o *DescribeImagesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe images params +func (o *DescribeImagesParams) WithDeviceTypeID(deviceTypeID *string) *DescribeImagesParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe images params +func (o *DescribeImagesParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithImageID adds the imageID to the describe images params +func (o *DescribeImagesParams) WithImageID(imageID *string) *DescribeImagesParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the describe images params +func (o *DescribeImagesParams) SetImageID(imageID *string) { + o.ImageID = imageID +} + +// WithImageIDs adds the imageIds to the describe images params +func (o *DescribeImagesParams) WithImageIDs(imageIds []string) *DescribeImagesParams { + o.SetImageIDs(imageIds) + return o +} + +// SetImageIDs adds the imageIds to the describe images params +func (o *DescribeImagesParams) SetImageIDs(imageIds []string) { + o.ImageIDs = imageIds +} + +// WithImageName adds the imageName to the describe images params +func (o *DescribeImagesParams) WithImageName(imageName *string) *DescribeImagesParams { + o.SetImageName(imageName) + return o +} + +// SetImageName adds the imageName to the describe images params +func (o *DescribeImagesParams) SetImageName(imageName *string) { + o.ImageName = imageName +} + +// WithIsAll adds the isAll to the describe images params +func (o *DescribeImagesParams) WithIsAll(isAll *string) *DescribeImagesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe images params +func (o *DescribeImagesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithOsID adds the osID to the describe images params +func (o *DescribeImagesParams) WithOsID(osID *string) *DescribeImagesParams { + o.SetOsID(osID) + return o +} + +// SetOsID adds the osId to the describe images params +func (o *DescribeImagesParams) SetOsID(osID *string) { + o.OsID = osID +} + +// WithOsType adds the osType to the describe images params +func (o *DescribeImagesParams) WithOsType(osType *string) *DescribeImagesParams { + o.SetOsType(osType) + return o +} + +// SetOsType adds the osType to the describe images params +func (o *DescribeImagesParams) SetOsType(osType *string) { + o.OsType = osType +} + +// WithPageNumber adds the pageNumber to the describe images params +func (o *DescribeImagesParams) WithPageNumber(pageNumber *int64) *DescribeImagesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe images params +func (o *DescribeImagesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe images params +func (o *DescribeImagesParams) WithPageSize(pageSize *int64) *DescribeImagesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe images params +func (o *DescribeImagesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithSource adds the source to the describe images params +func (o *DescribeImagesParams) WithSource(source *string) *DescribeImagesParams { + o.SetSource(source) + return o +} + +// SetSource adds the source to the describe images params +func (o *DescribeImagesParams) SetSource(source *string) { + o.Source = source +} + +// WithTraceID adds the traceID to the describe images params +func (o *DescribeImagesParams) WithTraceID(traceID string) *DescribeImagesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe images params +func (o *DescribeImagesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithVersion adds the version to the describe images params +func (o *DescribeImagesParams) WithVersion(version *string) *DescribeImagesParams { + o.SetVersion(version) + return o +} + +// SetVersion adds the version to the describe images params +func (o *DescribeImagesParams) SetVersion(version *string) { + o.Version = version +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeImagesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Architecture != nil { + + // query param architecture + var qrArchitecture string + + if o.Architecture != nil { + qrArchitecture = *o.Architecture + } + qArchitecture := qrArchitecture + if qArchitecture != "" { + + if err := r.SetQueryParam("architecture", qArchitecture); err != nil { + return err + } + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.ImageID != nil { + + // query param imageId + var qrImageID string + + if o.ImageID != nil { + qrImageID = *o.ImageID + } + qImageID := qrImageID + if qImageID != "" { + + if err := r.SetQueryParam("imageId", qImageID); err != nil { + return err + } + } + } + + if o.ImageIDs != nil { + + // binding items for imageIds + joinedImageIds := o.bindParamImageIds(reg) + + // query array param imageIds + if err := r.SetQueryParam("imageIds", joinedImageIds...); err != nil { + return err + } + } + + if o.ImageName != nil { + + // query param imageName + var qrImageName string + + if o.ImageName != nil { + qrImageName = *o.ImageName + } + qImageName := qrImageName + if qImageName != "" { + + if err := r.SetQueryParam("imageName", qImageName); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.OsID != nil { + + // query param osId + var qrOsID string + + if o.OsID != nil { + qrOsID = *o.OsID + } + qOsID := qrOsID + if qOsID != "" { + + if err := r.SetQueryParam("osId", qOsID); err != nil { + return err + } + } + } + + if o.OsType != nil { + + // query param osType + var qrOsType string + + if o.OsType != nil { + qrOsType = *o.OsType + } + qOsType := qrOsType + if qOsType != "" { + + if err := r.SetQueryParam("osType", qOsType); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.Source != nil { + + // query param source + var qrSource string + + if o.Source != nil { + qrSource = *o.Source + } + qSource := qrSource + if qSource != "" { + + if err := r.SetQueryParam("source", qSource); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.Version != nil { + + // query param version + var qrVersion string + + if o.Version != nil { + qrVersion = *o.Version + } + qVersion := qrVersion + if qVersion != "" { + + if err := r.SetQueryParam("version", qVersion); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindParamDescribeImages binds the parameter imageIds +func (o *DescribeImagesParams) bindParamImageIds(formats strfmt.Registry) []string { + imageIdsIR := o.ImageIDs + + var imageIdsIC []string + for _, imageIdsIIR := range imageIdsIR { // explode []string + + imageIdsIIV := imageIdsIIR // string as string + imageIdsIC = append(imageIdsIC, imageIdsIIV) + } + + // items.CollectionFormat: "" + imageIdsIS := swag.JoinByFormat(imageIdsIC, "") + + return imageIdsIS +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_images_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_images_responses.go new file mode 100644 index 0000000..0adb8dd --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/describe_images_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeImagesReader is a Reader for the DescribeImages structure. +type DescribeImagesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeImagesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeImagesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeImagesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeImagesOK creates a DescribeImagesOK with default headers values +func NewDescribeImagesOK() *DescribeImagesOK { + return &DescribeImagesOK{} +} + +/* DescribeImagesOK describes a response with status code 200, with default header values. + +A DescribeImagesResult is an response struct that is used to describe images. +*/ +type DescribeImagesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImagesOKBody +} + +// IsSuccess returns true when this describe images o k response has a 2xx status code +func (o *DescribeImagesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe images o k response has a 3xx status code +func (o *DescribeImagesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe images o k response has a 4xx status code +func (o *DescribeImagesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe images o k response has a 5xx status code +func (o *DescribeImagesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe images o k response a status code equal to that given +func (o *DescribeImagesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeImagesOK) Error() string { + return fmt.Sprintf("[GET /images][%d] describeImagesOK %+v", 200, o.Payload) +} + +func (o *DescribeImagesOK) String() string { + return fmt.Sprintf("[GET /images][%d] describeImagesOK %+v", 200, o.Payload) +} + +func (o *DescribeImagesOK) GetPayload() *DescribeImagesOKBody { + return o.Payload +} + +func (o *DescribeImagesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImagesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeImagesDefault creates a DescribeImagesDefault with default headers values +func NewDescribeImagesDefault(code int) *DescribeImagesDefault { + return &DescribeImagesDefault{ + _statusCode: code, + } +} + +/* DescribeImagesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeImagesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeImagesDefaultBody +} + +// Code gets the status code for the describe images default response +func (o *DescribeImagesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe images default response has a 2xx status code +func (o *DescribeImagesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe images default response has a 3xx status code +func (o *DescribeImagesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe images default response has a 4xx status code +func (o *DescribeImagesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe images default response has a 5xx status code +func (o *DescribeImagesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe images default response a status code equal to that given +func (o *DescribeImagesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeImagesDefault) Error() string { + return fmt.Sprintf("[GET /images][%d] describeImages default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImagesDefault) String() string { + return fmt.Sprintf("[GET /images][%d] describeImages default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeImagesDefault) GetPayload() *DescribeImagesDefaultBody { + return o.Payload +} + +func (o *DescribeImagesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeImagesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeImagesDefaultBody describe images default body +swagger:model DescribeImagesDefaultBody +*/ +type DescribeImagesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe images default body +func (o *DescribeImagesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImagesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeImages default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeImagesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeImages default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImages default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImages default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe images default body based on the context it is used +func (o *DescribeImagesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImagesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImages default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImages default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImagesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImagesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeImagesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeImagesOKBody describe images o k body +swagger:model DescribeImagesOKBody +*/ +type DescribeImagesOKBody struct { + + // result + Result *models.ImageList `json:"result,omitempty"` +} + +// Validate validates this describe images o k body +func (o *DescribeImagesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImagesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImagesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImagesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe images o k body based on the context it is used +func (o *DescribeImagesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeImagesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeImagesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeImagesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeImagesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeImagesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeImagesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/dissociated_device_type_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/dissociated_device_type_parameters.go new file mode 100644 index 0000000..0df631a --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/dissociated_device_type_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewDissociatedDeviceTypeParams creates a new DissociatedDeviceTypeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDissociatedDeviceTypeParams() *DissociatedDeviceTypeParams { + return &DissociatedDeviceTypeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDissociatedDeviceTypeParamsWithTimeout creates a new DissociatedDeviceTypeParams object +// with the ability to set a timeout on a request. +func NewDissociatedDeviceTypeParamsWithTimeout(timeout time.Duration) *DissociatedDeviceTypeParams { + return &DissociatedDeviceTypeParams{ + timeout: timeout, + } +} + +// NewDissociatedDeviceTypeParamsWithContext creates a new DissociatedDeviceTypeParams object +// with the ability to set a context for a request. +func NewDissociatedDeviceTypeParamsWithContext(ctx context.Context) *DissociatedDeviceTypeParams { + return &DissociatedDeviceTypeParams{ + Context: ctx, + } +} + +// NewDissociatedDeviceTypeParamsWithHTTPClient creates a new DissociatedDeviceTypeParams object +// with the ability to set a custom HTTPClient for a request. +func NewDissociatedDeviceTypeParamsWithHTTPClient(client *http.Client) *DissociatedDeviceTypeParams { + return &DissociatedDeviceTypeParams{ + HTTPClient: client, + } +} + +/* DissociatedDeviceTypeParams contains all the parameters to send to the API endpoint + for the dissociated device type operation. + + Typically these are written to a http.Request. +*/ +type DissociatedDeviceTypeParams struct { + + // Body. + Body *models.DissociatedImageRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the dissociated device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DissociatedDeviceTypeParams) WithDefaults() *DissociatedDeviceTypeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the dissociated device type params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DissociatedDeviceTypeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithTimeout(timeout time.Duration) *DissociatedDeviceTypeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithContext(ctx context.Context) *DissociatedDeviceTypeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithHTTPClient(client *http.Client) *DissociatedDeviceTypeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithBody(body *models.DissociatedImageRequest) *DissociatedDeviceTypeParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetBody(body *models.DissociatedImageRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithAuthorization(authorization string) *DissociatedDeviceTypeParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithBmpLanguage(bmpLanguage *string) *DissociatedDeviceTypeParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithBmpUserID(bmpUserID *string) *DissociatedDeviceTypeParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the dissociated device type params +func (o *DissociatedDeviceTypeParams) WithTraceID(traceID string) *DissociatedDeviceTypeParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the dissociated device type params +func (o *DissociatedDeviceTypeParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DissociatedDeviceTypeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/dissociated_device_type_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/dissociated_device_type_responses.go new file mode 100644 index 0000000..4a2b3c2 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/dissociated_device_type_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DissociatedDeviceTypeReader is a Reader for the DissociatedDeviceType structure. +type DissociatedDeviceTypeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DissociatedDeviceTypeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDissociatedDeviceTypeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDissociatedDeviceTypeDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDissociatedDeviceTypeOK creates a DissociatedDeviceTypeOK with default headers values +func NewDissociatedDeviceTypeOK() *DissociatedDeviceTypeOK { + return &DissociatedDeviceTypeOK{} +} + +/* DissociatedDeviceTypeOK describes a response with status code 200, with default header values. + +DissociatedDeviceTypeOK dissociated device type o k +*/ +type DissociatedDeviceTypeOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DissociatedDeviceTypeOKBody +} + +// IsSuccess returns true when this dissociated device type o k response has a 2xx status code +func (o *DissociatedDeviceTypeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this dissociated device type o k response has a 3xx status code +func (o *DissociatedDeviceTypeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this dissociated device type o k response has a 4xx status code +func (o *DissociatedDeviceTypeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this dissociated device type o k response has a 5xx status code +func (o *DissociatedDeviceTypeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this dissociated device type o k response a status code equal to that given +func (o *DissociatedDeviceTypeOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DissociatedDeviceTypeOK) Error() string { + return fmt.Sprintf("[DELETE /images/dissociatedDeviceType][%d] dissociatedDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DissociatedDeviceTypeOK) String() string { + return fmt.Sprintf("[DELETE /images/dissociatedDeviceType][%d] dissociatedDeviceTypeOK %+v", 200, o.Payload) +} + +func (o *DissociatedDeviceTypeOK) GetPayload() *DissociatedDeviceTypeOKBody { + return o.Payload +} + +func (o *DissociatedDeviceTypeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DissociatedDeviceTypeOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDissociatedDeviceTypeDefault creates a DissociatedDeviceTypeDefault with default headers values +func NewDissociatedDeviceTypeDefault(code int) *DissociatedDeviceTypeDefault { + return &DissociatedDeviceTypeDefault{ + _statusCode: code, + } +} + +/* DissociatedDeviceTypeDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DissociatedDeviceTypeDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DissociatedDeviceTypeDefaultBody +} + +// Code gets the status code for the dissociated device type default response +func (o *DissociatedDeviceTypeDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this dissociated device type default response has a 2xx status code +func (o *DissociatedDeviceTypeDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this dissociated device type default response has a 3xx status code +func (o *DissociatedDeviceTypeDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this dissociated device type default response has a 4xx status code +func (o *DissociatedDeviceTypeDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this dissociated device type default response has a 5xx status code +func (o *DissociatedDeviceTypeDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this dissociated device type default response a status code equal to that given +func (o *DissociatedDeviceTypeDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DissociatedDeviceTypeDefault) Error() string { + return fmt.Sprintf("[DELETE /images/dissociatedDeviceType][%d] dissociatedDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DissociatedDeviceTypeDefault) String() string { + return fmt.Sprintf("[DELETE /images/dissociatedDeviceType][%d] dissociatedDeviceType default %+v", o._statusCode, o.Payload) +} + +func (o *DissociatedDeviceTypeDefault) GetPayload() *DissociatedDeviceTypeDefaultBody { + return o.Payload +} + +func (o *DissociatedDeviceTypeDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DissociatedDeviceTypeDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DissociatedDeviceTypeDefaultBody dissociated device type default body +swagger:model DissociatedDeviceTypeDefaultBody +*/ +type DissociatedDeviceTypeDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this dissociated device type default body +func (o *DissociatedDeviceTypeDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedDeviceTypeDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("dissociatedDeviceType default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DissociatedDeviceTypeDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("dissociatedDeviceType default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this dissociated device type default body based on the context it is used +func (o *DissociatedDeviceTypeDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedDeviceTypeDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedDeviceType default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedDeviceType default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DissociatedDeviceTypeDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DissociatedDeviceTypeDefaultBody) UnmarshalBinary(b []byte) error { + var res DissociatedDeviceTypeDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DissociatedDeviceTypeOKBody dissociated device type o k body +swagger:model DissociatedDeviceTypeOKBody +*/ +type DissociatedDeviceTypeOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this dissociated device type o k body +func (o *DissociatedDeviceTypeOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedDeviceTypeOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this dissociated device type o k body based on the context it is used +func (o *DissociatedDeviceTypeOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DissociatedDeviceTypeOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dissociatedDeviceTypeOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dissociatedDeviceTypeOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DissociatedDeviceTypeOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DissociatedDeviceTypeOKBody) UnmarshalBinary(b []byte) error { + var res DissociatedDeviceTypeOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/image_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/image_client.go new file mode 100644 index 0000000..52ae2ae --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/image_client.go @@ -0,0 +1,357 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new image API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for image API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + AssociatedDeviceType(params *AssociatedDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AssociatedDeviceTypeOK, error) + + CreateImage(params *CreateImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateImageOK, error) + + DeleteImage(params *DeleteImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteImageOK, error) + + DescribeImage(params *DescribeImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImageOK, error) + + DescribeImageDeviceTypes(params *DescribeImageDeviceTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImageDeviceTypesOK, error) + + DescribeImages(params *DescribeImagesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImagesOK, error) + + DissociatedDeviceType(params *DissociatedDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DissociatedDeviceTypeOK, error) + + ModifyImage(params *ModifyImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyImageOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + AssociatedDeviceType AssociatedDeviceType 镜像绑定机型 +*/ +func (a *Client) AssociatedDeviceType(params *AssociatedDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AssociatedDeviceTypeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewAssociatedDeviceTypeParams() + } + op := &runtime.ClientOperation{ + ID: "associatedDeviceType", + Method: "POST", + PathPattern: "/images/associatedDeviceType", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &AssociatedDeviceTypeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*AssociatedDeviceTypeOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*AssociatedDeviceTypeDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + CreateImage CreateImage 添加镜像 +*/ +func (a *Client) CreateImage(params *CreateImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateImageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateImageParams() + } + op := &runtime.ClientOperation{ + ID: "createImage", + Method: "POST", + PathPattern: "/images", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateImageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateImageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateImageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteImage DeleteImage 删除镜像 +*/ +func (a *Client) DeleteImage(params *DeleteImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteImageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteImageParams() + } + op := &runtime.ClientOperation{ + ID: "deleteImage", + Method: "DELETE", + PathPattern: "/images/{image_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteImageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteImageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteImageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeImage DescribeImage 获取镜像详情 +*/ +func (a *Client) DescribeImage(params *DescribeImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeImageParams() + } + op := &runtime.ClientOperation{ + ID: "describeImage", + Method: "GET", + PathPattern: "/images/{image_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeImageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeImageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeImageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeImageDeviceTypes DescribeImageDeviceTypes 查看镜像绑定的机型 +*/ +func (a *Client) DescribeImageDeviceTypes(params *DescribeImageDeviceTypesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImageDeviceTypesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeImageDeviceTypesParams() + } + op := &runtime.ClientOperation{ + ID: "describeImageDeviceTypes", + Method: "GET", + PathPattern: "/images/imageDeviceTypes", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeImageDeviceTypesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeImageDeviceTypesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeImageDeviceTypesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeImages DescribeImages 获取镜像列表 +*/ +func (a *Client) DescribeImages(params *DescribeImagesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeImagesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeImagesParams() + } + op := &runtime.ClientOperation{ + ID: "describeImages", + Method: "GET", + PathPattern: "/images", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeImagesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeImagesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeImagesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DissociatedDeviceType DissociatedDeviceType 镜像解绑机型 +*/ +func (a *Client) DissociatedDeviceType(params *DissociatedDeviceTypeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DissociatedDeviceTypeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDissociatedDeviceTypeParams() + } + op := &runtime.ClientOperation{ + ID: "dissociatedDeviceType", + Method: "DELETE", + PathPattern: "/images/dissociatedDeviceType", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DissociatedDeviceTypeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DissociatedDeviceTypeOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DissociatedDeviceTypeDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyImage ModifyImage 修改镜像(暂不启用) +*/ +func (a *Client) ModifyImage(params *ModifyImageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyImageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyImageParams() + } + op := &runtime.ClientOperation{ + ID: "modifyImage", + Method: "PUT", + PathPattern: "/images/{image_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyImageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyImageOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyImageDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/modify_image_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/modify_image_parameters.go new file mode 100644 index 0000000..b2159e5 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/modify_image_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyImageParams creates a new ModifyImageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyImageParams() *ModifyImageParams { + return &ModifyImageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyImageParamsWithTimeout creates a new ModifyImageParams object +// with the ability to set a timeout on a request. +func NewModifyImageParamsWithTimeout(timeout time.Duration) *ModifyImageParams { + return &ModifyImageParams{ + timeout: timeout, + } +} + +// NewModifyImageParamsWithContext creates a new ModifyImageParams object +// with the ability to set a context for a request. +func NewModifyImageParamsWithContext(ctx context.Context) *ModifyImageParams { + return &ModifyImageParams{ + Context: ctx, + } +} + +// NewModifyImageParamsWithHTTPClient creates a new ModifyImageParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyImageParamsWithHTTPClient(client *http.Client) *ModifyImageParams { + return &ModifyImageParams{ + HTTPClient: client, + } +} + +/* ModifyImageParams contains all the parameters to send to the API endpoint + for the modify image operation. + + Typically these are written to a http.Request. +*/ +type ModifyImageParams struct { + + // Body. + Body *models.ModifyImageRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // ImageID. + ImageID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyImageParams) WithDefaults() *ModifyImageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify image params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyImageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify image params +func (o *ModifyImageParams) WithTimeout(timeout time.Duration) *ModifyImageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify image params +func (o *ModifyImageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify image params +func (o *ModifyImageParams) WithContext(ctx context.Context) *ModifyImageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify image params +func (o *ModifyImageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify image params +func (o *ModifyImageParams) WithHTTPClient(client *http.Client) *ModifyImageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify image params +func (o *ModifyImageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify image params +func (o *ModifyImageParams) WithBody(body *models.ModifyImageRequest) *ModifyImageParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify image params +func (o *ModifyImageParams) SetBody(body *models.ModifyImageRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify image params +func (o *ModifyImageParams) WithAuthorization(authorization string) *ModifyImageParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify image params +func (o *ModifyImageParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify image params +func (o *ModifyImageParams) WithBmpLanguage(bmpLanguage *string) *ModifyImageParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify image params +func (o *ModifyImageParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify image params +func (o *ModifyImageParams) WithBmpUserID(bmpUserID *string) *ModifyImageParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify image params +func (o *ModifyImageParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithImageID adds the imageID to the modify image params +func (o *ModifyImageParams) WithImageID(imageID string) *ModifyImageParams { + o.SetImageID(imageID) + return o +} + +// SetImageID adds the imageId to the modify image params +func (o *ModifyImageParams) SetImageID(imageID string) { + o.ImageID = imageID +} + +// WithTraceID adds the traceID to the modify image params +func (o *ModifyImageParams) WithTraceID(traceID string) *ModifyImageParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify image params +func (o *ModifyImageParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param image_id + if err := r.SetPathParam("image_id", o.ImageID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/modify_image_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/modify_image_responses.go new file mode 100644 index 0000000..f31e33a --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/image/modify_image_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package image + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyImageReader is a Reader for the ModifyImage structure. +type ModifyImageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyImageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyImageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyImageDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyImageOK creates a ModifyImageOK with default headers values +func NewModifyImageOK() *ModifyImageOK { + return &ModifyImageOK{} +} + +/* ModifyImageOK describes a response with status code 200, with default header values. + +A ModifyImageResult is an response struct that is used to modify image. +*/ +type ModifyImageOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyImageOKBody +} + +// IsSuccess returns true when this modify image o k response has a 2xx status code +func (o *ModifyImageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify image o k response has a 3xx status code +func (o *ModifyImageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify image o k response has a 4xx status code +func (o *ModifyImageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify image o k response has a 5xx status code +func (o *ModifyImageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify image o k response a status code equal to that given +func (o *ModifyImageOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyImageOK) Error() string { + return fmt.Sprintf("[PUT /images/{image_id}][%d] modifyImageOK %+v", 200, o.Payload) +} + +func (o *ModifyImageOK) String() string { + return fmt.Sprintf("[PUT /images/{image_id}][%d] modifyImageOK %+v", 200, o.Payload) +} + +func (o *ModifyImageOK) GetPayload() *ModifyImageOKBody { + return o.Payload +} + +func (o *ModifyImageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyImageOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyImageDefault creates a ModifyImageDefault with default headers values +func NewModifyImageDefault(code int) *ModifyImageDefault { + return &ModifyImageDefault{ + _statusCode: code, + } +} + +/* ModifyImageDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyImageDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyImageDefaultBody +} + +// Code gets the status code for the modify image default response +func (o *ModifyImageDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify image default response has a 2xx status code +func (o *ModifyImageDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify image default response has a 3xx status code +func (o *ModifyImageDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify image default response has a 4xx status code +func (o *ModifyImageDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify image default response has a 5xx status code +func (o *ModifyImageDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify image default response a status code equal to that given +func (o *ModifyImageDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyImageDefault) Error() string { + return fmt.Sprintf("[PUT /images/{image_id}][%d] modifyImage default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyImageDefault) String() string { + return fmt.Sprintf("[PUT /images/{image_id}][%d] modifyImage default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyImageDefault) GetPayload() *ModifyImageDefaultBody { + return o.Payload +} + +func (o *ModifyImageDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyImageDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyImageDefaultBody modify image default body +swagger:model ModifyImageDefaultBody +*/ +type ModifyImageDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify image default body +func (o *ModifyImageDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyImageDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyImage default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyImageDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyImage default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify image default body based on the context it is used +func (o *ModifyImageDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyImageDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyImage default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyImage default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyImageDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyImageDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyImageDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyImageOKBody modify image o k body +swagger:model ModifyImageOKBody +*/ +type ModifyImageOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify image o k body +func (o *ModifyImageOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyImageOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify image o k body based on the context it is used +func (o *ModifyImageOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyImageOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyImageOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyImageOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyImageOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyImageOKBody) UnmarshalBinary(b []byte) error { + var res ModifyImageOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/create_project_instance_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/create_project_instance_parameters.go new file mode 100644 index 0000000..4e370ba --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/create_project_instance_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateProjectInstanceParams creates a new CreateProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateProjectInstanceParams() *CreateProjectInstanceParams { + return &CreateProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateProjectInstanceParamsWithTimeout creates a new CreateProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewCreateProjectInstanceParamsWithTimeout(timeout time.Duration) *CreateProjectInstanceParams { + return &CreateProjectInstanceParams{ + timeout: timeout, + } +} + +// NewCreateProjectInstanceParamsWithContext creates a new CreateProjectInstanceParams object +// with the ability to set a context for a request. +func NewCreateProjectInstanceParamsWithContext(ctx context.Context) *CreateProjectInstanceParams { + return &CreateProjectInstanceParams{ + Context: ctx, + } +} + +// NewCreateProjectInstanceParamsWithHTTPClient creates a new CreateProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateProjectInstanceParamsWithHTTPClient(client *http.Client) *CreateProjectInstanceParams { + return &CreateProjectInstanceParams{ + HTTPClient: client, + } +} + +/* CreateProjectInstanceParams contains all the parameters to send to the API endpoint + for the create project instance operation. + + Typically these are written to a http.Request. +*/ +type CreateProjectInstanceParams struct { + + // Body. + Body *models.CreateInstanceRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateProjectInstanceParams) WithDefaults() *CreateProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create project instance params +func (o *CreateProjectInstanceParams) WithTimeout(timeout time.Duration) *CreateProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create project instance params +func (o *CreateProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create project instance params +func (o *CreateProjectInstanceParams) WithContext(ctx context.Context) *CreateProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create project instance params +func (o *CreateProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create project instance params +func (o *CreateProjectInstanceParams) WithHTTPClient(client *http.Client) *CreateProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create project instance params +func (o *CreateProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create project instance params +func (o *CreateProjectInstanceParams) WithBody(body *models.CreateInstanceRequest) *CreateProjectInstanceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create project instance params +func (o *CreateProjectInstanceParams) SetBody(body *models.CreateInstanceRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create project instance params +func (o *CreateProjectInstanceParams) WithAuthorization(authorization string) *CreateProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create project instance params +func (o *CreateProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create project instance params +func (o *CreateProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *CreateProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create project instance params +func (o *CreateProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create project instance params +func (o *CreateProjectInstanceParams) WithBmpUserID(bmpUserID *string) *CreateProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create project instance params +func (o *CreateProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create project instance params +func (o *CreateProjectInstanceParams) WithTraceID(traceID string) *CreateProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create project instance params +func (o *CreateProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/create_project_instance_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/create_project_instance_responses.go new file mode 100644 index 0000000..8a32dc6 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/create_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateProjectInstanceReader is a Reader for the CreateProjectInstance structure. +type CreateProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateProjectInstanceOK creates a CreateProjectInstanceOK with default headers values +func NewCreateProjectInstanceOK() *CreateProjectInstanceOK { + return &CreateProjectInstanceOK{} +} + +/* CreateProjectInstanceOK describes a response with status code 200, with default header values. + +A CreateProjectInstanceResult is an response struct that is used to describe create instance result. +*/ +type CreateProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateProjectInstanceOKBody +} + +// IsSuccess returns true when this create project instance o k response has a 2xx status code +func (o *CreateProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create project instance o k response has a 3xx status code +func (o *CreateProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create project instance o k response has a 4xx status code +func (o *CreateProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create project instance o k response has a 5xx status code +func (o *CreateProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create project instance o k response a status code equal to that given +func (o *CreateProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateProjectInstanceOK) Error() string { + return fmt.Sprintf("[POST /project/instances][%d] createProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *CreateProjectInstanceOK) String() string { + return fmt.Sprintf("[POST /project/instances][%d] createProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *CreateProjectInstanceOK) GetPayload() *CreateProjectInstanceOKBody { + return o.Payload +} + +func (o *CreateProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateProjectInstanceDefault creates a CreateProjectInstanceDefault with default headers values +func NewCreateProjectInstanceDefault(code int) *CreateProjectInstanceDefault { + return &CreateProjectInstanceDefault{ + _statusCode: code, + } +} + +/* CreateProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateProjectInstanceDefaultBody +} + +// Code gets the status code for the create project instance default response +func (o *CreateProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create project instance default response has a 2xx status code +func (o *CreateProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create project instance default response has a 3xx status code +func (o *CreateProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create project instance default response has a 4xx status code +func (o *CreateProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create project instance default response has a 5xx status code +func (o *CreateProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create project instance default response a status code equal to that given +func (o *CreateProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateProjectInstanceDefault) Error() string { + return fmt.Sprintf("[POST /project/instances][%d] createProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *CreateProjectInstanceDefault) String() string { + return fmt.Sprintf("[POST /project/instances][%d] createProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *CreateProjectInstanceDefault) GetPayload() *CreateProjectInstanceDefaultBody { + return o.Payload +} + +func (o *CreateProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateProjectInstanceDefaultBody create project instance default body +swagger:model CreateProjectInstanceDefaultBody +*/ +type CreateProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create project instance default body +func (o *CreateProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create project instance default body based on the context it is used +func (o *CreateProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateProjectInstanceOKBody create project instance o k body +swagger:model CreateProjectInstanceOKBody +*/ +type CreateProjectInstanceOKBody struct { + + // result + Result *models.InstanceIds `json:"result,omitempty"` +} + +// Validate validates this create project instance o k body +func (o *CreateProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create project instance o k body based on the context it is used +func (o *CreateProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res CreateProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/delete_instances_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/delete_instances_parameters.go new file mode 100644 index 0000000..09a6304 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/delete_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewDeleteInstancesParams creates a new DeleteInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteInstancesParams() *DeleteInstancesParams { + return &DeleteInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteInstancesParamsWithTimeout creates a new DeleteInstancesParams object +// with the ability to set a timeout on a request. +func NewDeleteInstancesParamsWithTimeout(timeout time.Duration) *DeleteInstancesParams { + return &DeleteInstancesParams{ + timeout: timeout, + } +} + +// NewDeleteInstancesParamsWithContext creates a new DeleteInstancesParams object +// with the ability to set a context for a request. +func NewDeleteInstancesParamsWithContext(ctx context.Context) *DeleteInstancesParams { + return &DeleteInstancesParams{ + Context: ctx, + } +} + +// NewDeleteInstancesParamsWithHTTPClient creates a new DeleteInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteInstancesParamsWithHTTPClient(client *http.Client) *DeleteInstancesParams { + return &DeleteInstancesParams{ + HTTPClient: client, + } +} + +/* DeleteInstancesParams contains all the parameters to send to the API endpoint + for the delete instances operation. + + Typically these are written to a http.Request. +*/ +type DeleteInstancesParams struct { + + // Body. + Body *models.DeleteInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteInstancesParams) WithDefaults() *DeleteInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete instances params +func (o *DeleteInstancesParams) WithTimeout(timeout time.Duration) *DeleteInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete instances params +func (o *DeleteInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete instances params +func (o *DeleteInstancesParams) WithContext(ctx context.Context) *DeleteInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete instances params +func (o *DeleteInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete instances params +func (o *DeleteInstancesParams) WithHTTPClient(client *http.Client) *DeleteInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete instances params +func (o *DeleteInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the delete instances params +func (o *DeleteInstancesParams) WithBody(body *models.DeleteInstancesRequest) *DeleteInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the delete instances params +func (o *DeleteInstancesParams) SetBody(body *models.DeleteInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the delete instances params +func (o *DeleteInstancesParams) WithAuthorization(authorization string) *DeleteInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete instances params +func (o *DeleteInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete instances params +func (o *DeleteInstancesParams) WithBmpLanguage(bmpLanguage *string) *DeleteInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete instances params +func (o *DeleteInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete instances params +func (o *DeleteInstancesParams) WithBmpUserID(bmpUserID *string) *DeleteInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete instances params +func (o *DeleteInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete instances params +func (o *DeleteInstancesParams) WithTraceID(traceID string) *DeleteInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete instances params +func (o *DeleteInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/delete_instances_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/delete_instances_responses.go new file mode 100644 index 0000000..05388da --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/delete_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteInstancesReader is a Reader for the DeleteInstances structure. +type DeleteInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteInstancesOK creates a DeleteInstancesOK with default headers values +func NewDeleteInstancesOK() *DeleteInstancesOK { + return &DeleteInstancesOK{} +} + +/* DeleteInstancesOK describes a response with status code 200, with default header values. + +A DeleteInstancesResult is an response struct that is used to describe modify instance result. +*/ +type DeleteInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteInstancesOKBody +} + +// IsSuccess returns true when this delete instances o k response has a 2xx status code +func (o *DeleteInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete instances o k response has a 3xx status code +func (o *DeleteInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete instances o k response has a 4xx status code +func (o *DeleteInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete instances o k response has a 5xx status code +func (o *DeleteInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete instances o k response a status code equal to that given +func (o *DeleteInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteInstancesOK) Error() string { + return fmt.Sprintf("[DELETE /project/instances/batch/instances:deleteInstances][%d] deleteInstancesOK %+v", 200, o.Payload) +} + +func (o *DeleteInstancesOK) String() string { + return fmt.Sprintf("[DELETE /project/instances/batch/instances:deleteInstances][%d] deleteInstancesOK %+v", 200, o.Payload) +} + +func (o *DeleteInstancesOK) GetPayload() *DeleteInstancesOKBody { + return o.Payload +} + +func (o *DeleteInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteInstancesDefault creates a DeleteInstancesDefault with default headers values +func NewDeleteInstancesDefault(code int) *DeleteInstancesDefault { + return &DeleteInstancesDefault{ + _statusCode: code, + } +} + +/* DeleteInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteInstancesDefaultBody +} + +// Code gets the status code for the delete instances default response +func (o *DeleteInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete instances default response has a 2xx status code +func (o *DeleteInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete instances default response has a 3xx status code +func (o *DeleteInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete instances default response has a 4xx status code +func (o *DeleteInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete instances default response has a 5xx status code +func (o *DeleteInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete instances default response a status code equal to that given +func (o *DeleteInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteInstancesDefault) Error() string { + return fmt.Sprintf("[DELETE /project/instances/batch/instances:deleteInstances][%d] deleteInstances default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteInstancesDefault) String() string { + return fmt.Sprintf("[DELETE /project/instances/batch/instances:deleteInstances][%d] deleteInstances default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteInstancesDefault) GetPayload() *DeleteInstancesDefaultBody { + return o.Payload +} + +func (o *DeleteInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteInstancesDefaultBody delete instances default body +swagger:model DeleteInstancesDefaultBody +*/ +type DeleteInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete instances default body +func (o *DeleteInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete instances default body based on the context it is used +func (o *DeleteInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteInstancesOKBody delete instances o k body +swagger:model DeleteInstancesOKBody +*/ +type DeleteInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete instances o k body +func (o *DeleteInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete instances o k body based on the context it is used +func (o *DeleteInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteInstancesOKBody) UnmarshalBinary(b []byte) error { + var res DeleteInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/delete_project_instance_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/delete_project_instance_parameters.go new file mode 100644 index 0000000..0ed6624 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/delete_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteProjectInstanceParams creates a new DeleteProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteProjectInstanceParams() *DeleteProjectInstanceParams { + return &DeleteProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteProjectInstanceParamsWithTimeout creates a new DeleteProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewDeleteProjectInstanceParamsWithTimeout(timeout time.Duration) *DeleteProjectInstanceParams { + return &DeleteProjectInstanceParams{ + timeout: timeout, + } +} + +// NewDeleteProjectInstanceParamsWithContext creates a new DeleteProjectInstanceParams object +// with the ability to set a context for a request. +func NewDeleteProjectInstanceParamsWithContext(ctx context.Context) *DeleteProjectInstanceParams { + return &DeleteProjectInstanceParams{ + Context: ctx, + } +} + +// NewDeleteProjectInstanceParamsWithHTTPClient creates a new DeleteProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteProjectInstanceParamsWithHTTPClient(client *http.Client) *DeleteProjectInstanceParams { + return &DeleteProjectInstanceParams{ + HTTPClient: client, + } +} + +/* DeleteProjectInstanceParams contains all the parameters to send to the API endpoint + for the delete project instance operation. + + Typically these are written to a http.Request. +*/ +type DeleteProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteProjectInstanceParams) WithDefaults() *DeleteProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete project instance params +func (o *DeleteProjectInstanceParams) WithTimeout(timeout time.Duration) *DeleteProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete project instance params +func (o *DeleteProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete project instance params +func (o *DeleteProjectInstanceParams) WithContext(ctx context.Context) *DeleteProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete project instance params +func (o *DeleteProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete project instance params +func (o *DeleteProjectInstanceParams) WithHTTPClient(client *http.Client) *DeleteProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete project instance params +func (o *DeleteProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete project instance params +func (o *DeleteProjectInstanceParams) WithAuthorization(authorization string) *DeleteProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete project instance params +func (o *DeleteProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete project instance params +func (o *DeleteProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *DeleteProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete project instance params +func (o *DeleteProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete project instance params +func (o *DeleteProjectInstanceParams) WithBmpUserID(bmpUserID *string) *DeleteProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete project instance params +func (o *DeleteProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the delete project instance params +func (o *DeleteProjectInstanceParams) WithInstanceID(instanceID string) *DeleteProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the delete project instance params +func (o *DeleteProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the delete project instance params +func (o *DeleteProjectInstanceParams) WithTraceID(traceID string) *DeleteProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete project instance params +func (o *DeleteProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/delete_project_instance_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/delete_project_instance_responses.go new file mode 100644 index 0000000..ea5f636 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/delete_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteProjectInstanceReader is a Reader for the DeleteProjectInstance structure. +type DeleteProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteProjectInstanceOK creates a DeleteProjectInstanceOK with default headers values +func NewDeleteProjectInstanceOK() *DeleteProjectInstanceOK { + return &DeleteProjectInstanceOK{} +} + +/* DeleteProjectInstanceOK describes a response with status code 200, with default header values. + +A DeleteProjectInstanceResult is an response struct that is used to delete stop instance result. +*/ +type DeleteProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteProjectInstanceOKBody +} + +// IsSuccess returns true when this delete project instance o k response has a 2xx status code +func (o *DeleteProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete project instance o k response has a 3xx status code +func (o *DeleteProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete project instance o k response has a 4xx status code +func (o *DeleteProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete project instance o k response has a 5xx status code +func (o *DeleteProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete project instance o k response a status code equal to that given +func (o *DeleteProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteProjectInstanceOK) Error() string { + return fmt.Sprintf("[DELETE /project/instances/{instance_id}][%d] deleteProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *DeleteProjectInstanceOK) String() string { + return fmt.Sprintf("[DELETE /project/instances/{instance_id}][%d] deleteProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *DeleteProjectInstanceOK) GetPayload() *DeleteProjectInstanceOKBody { + return o.Payload +} + +func (o *DeleteProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteProjectInstanceDefault creates a DeleteProjectInstanceDefault with default headers values +func NewDeleteProjectInstanceDefault(code int) *DeleteProjectInstanceDefault { + return &DeleteProjectInstanceDefault{ + _statusCode: code, + } +} + +/* DeleteProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteProjectInstanceDefaultBody +} + +// Code gets the status code for the delete project instance default response +func (o *DeleteProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete project instance default response has a 2xx status code +func (o *DeleteProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete project instance default response has a 3xx status code +func (o *DeleteProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete project instance default response has a 4xx status code +func (o *DeleteProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete project instance default response has a 5xx status code +func (o *DeleteProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete project instance default response a status code equal to that given +func (o *DeleteProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteProjectInstanceDefault) Error() string { + return fmt.Sprintf("[DELETE /project/instances/{instance_id}][%d] deleteProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteProjectInstanceDefault) String() string { + return fmt.Sprintf("[DELETE /project/instances/{instance_id}][%d] deleteProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteProjectInstanceDefault) GetPayload() *DeleteProjectInstanceDefaultBody { + return o.Payload +} + +func (o *DeleteProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteProjectInstanceDefaultBody delete project instance default body +swagger:model DeleteProjectInstanceDefaultBody +*/ +type DeleteProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete project instance default body +func (o *DeleteProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete project instance default body based on the context it is used +func (o *DeleteProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteProjectInstanceOKBody delete project instance o k body +swagger:model DeleteProjectInstanceOKBody +*/ +type DeleteProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete project instance o k body +func (o *DeleteProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete project instance o k body based on the context it is used +func (o *DeleteProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res DeleteProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instance_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instance_parameters.go new file mode 100644 index 0000000..f7def69 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instance_parameters.go @@ -0,0 +1,243 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeProjectInstanceParams creates a new DescribeProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeProjectInstanceParams() *DescribeProjectInstanceParams { + return &DescribeProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeProjectInstanceParamsWithTimeout creates a new DescribeProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewDescribeProjectInstanceParamsWithTimeout(timeout time.Duration) *DescribeProjectInstanceParams { + return &DescribeProjectInstanceParams{ + timeout: timeout, + } +} + +// NewDescribeProjectInstanceParamsWithContext creates a new DescribeProjectInstanceParams object +// with the ability to set a context for a request. +func NewDescribeProjectInstanceParamsWithContext(ctx context.Context) *DescribeProjectInstanceParams { + return &DescribeProjectInstanceParams{ + Context: ctx, + } +} + +// NewDescribeProjectInstanceParamsWithHTTPClient creates a new DescribeProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeProjectInstanceParamsWithHTTPClient(client *http.Client) *DescribeProjectInstanceParams { + return &DescribeProjectInstanceParams{ + HTTPClient: client, + } +} + +/* DescribeProjectInstanceParams contains all the parameters to send to the API endpoint + for the describe project instance operation. + + Typically these are written to a http.Request. +*/ +type DescribeProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* InstanceID. + + 实例uuid + */ + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeProjectInstanceParams) WithDefaults() *DescribeProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe project instance params +func (o *DescribeProjectInstanceParams) WithTimeout(timeout time.Duration) *DescribeProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe project instance params +func (o *DescribeProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe project instance params +func (o *DescribeProjectInstanceParams) WithContext(ctx context.Context) *DescribeProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe project instance params +func (o *DescribeProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe project instance params +func (o *DescribeProjectInstanceParams) WithHTTPClient(client *http.Client) *DescribeProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe project instance params +func (o *DescribeProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe project instance params +func (o *DescribeProjectInstanceParams) WithAuthorization(authorization string) *DescribeProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe project instance params +func (o *DescribeProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe project instance params +func (o *DescribeProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *DescribeProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe project instance params +func (o *DescribeProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe project instance params +func (o *DescribeProjectInstanceParams) WithBmpUserID(bmpUserID *string) *DescribeProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe project instance params +func (o *DescribeProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the describe project instance params +func (o *DescribeProjectInstanceParams) WithInstanceID(instanceID string) *DescribeProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the describe project instance params +func (o *DescribeProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the describe project instance params +func (o *DescribeProjectInstanceParams) WithTraceID(traceID string) *DescribeProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe project instance params +func (o *DescribeProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instance_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instance_responses.go new file mode 100644 index 0000000..128b26a --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeProjectInstanceReader is a Reader for the DescribeProjectInstance structure. +type DescribeProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeProjectInstanceOK creates a DescribeProjectInstanceOK with default headers values +func NewDescribeProjectInstanceOK() *DescribeProjectInstanceOK { + return &DescribeProjectInstanceOK{} +} + +/* DescribeProjectInstanceOK describes a response with status code 200, with default header values. + +A GetInstanceResult is an response struct that is used to describe instance. +*/ +type DescribeProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeProjectInstanceOKBody +} + +// IsSuccess returns true when this describe project instance o k response has a 2xx status code +func (o *DescribeProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe project instance o k response has a 3xx status code +func (o *DescribeProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe project instance o k response has a 4xx status code +func (o *DescribeProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe project instance o k response has a 5xx status code +func (o *DescribeProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe project instance o k response a status code equal to that given +func (o *DescribeProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeProjectInstanceOK) Error() string { + return fmt.Sprintf("[GET /project/instances/{instance_id}][%d] describeProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *DescribeProjectInstanceOK) String() string { + return fmt.Sprintf("[GET /project/instances/{instance_id}][%d] describeProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *DescribeProjectInstanceOK) GetPayload() *DescribeProjectInstanceOKBody { + return o.Payload +} + +func (o *DescribeProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeProjectInstanceDefault creates a DescribeProjectInstanceDefault with default headers values +func NewDescribeProjectInstanceDefault(code int) *DescribeProjectInstanceDefault { + return &DescribeProjectInstanceDefault{ + _statusCode: code, + } +} + +/* DescribeProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeProjectInstanceDefaultBody +} + +// Code gets the status code for the describe project instance default response +func (o *DescribeProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe project instance default response has a 2xx status code +func (o *DescribeProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe project instance default response has a 3xx status code +func (o *DescribeProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe project instance default response has a 4xx status code +func (o *DescribeProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe project instance default response has a 5xx status code +func (o *DescribeProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe project instance default response a status code equal to that given +func (o *DescribeProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeProjectInstanceDefault) Error() string { + return fmt.Sprintf("[GET /project/instances/{instance_id}][%d] describeProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeProjectInstanceDefault) String() string { + return fmt.Sprintf("[GET /project/instances/{instance_id}][%d] describeProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeProjectInstanceDefault) GetPayload() *DescribeProjectInstanceDefaultBody { + return o.Payload +} + +func (o *DescribeProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeProjectInstanceDefaultBody describe project instance default body +swagger:model DescribeProjectInstanceDefaultBody +*/ +type DescribeProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe project instance default body +func (o *DescribeProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe project instance default body based on the context it is used +func (o *DescribeProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeProjectInstanceOKBody describe project instance o k body +swagger:model DescribeProjectInstanceOKBody +*/ +type DescribeProjectInstanceOKBody struct { + + // result + Result *models.InstanceInfo `json:"result,omitempty"` +} + +// Validate validates this describe project instance o k body +func (o *DescribeProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe project instance o k body based on the context it is used +func (o *DescribeProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res DescribeProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instances_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instances_parameters.go new file mode 100644 index 0000000..cf169d0 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instances_parameters.go @@ -0,0 +1,702 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeProjectInstancesParams creates a new DescribeProjectInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeProjectInstancesParams() *DescribeProjectInstancesParams { + return &DescribeProjectInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeProjectInstancesParamsWithTimeout creates a new DescribeProjectInstancesParams object +// with the ability to set a timeout on a request. +func NewDescribeProjectInstancesParamsWithTimeout(timeout time.Duration) *DescribeProjectInstancesParams { + return &DescribeProjectInstancesParams{ + timeout: timeout, + } +} + +// NewDescribeProjectInstancesParamsWithContext creates a new DescribeProjectInstancesParams object +// with the ability to set a context for a request. +func NewDescribeProjectInstancesParamsWithContext(ctx context.Context) *DescribeProjectInstancesParams { + return &DescribeProjectInstancesParams{ + Context: ctx, + } +} + +// NewDescribeProjectInstancesParamsWithHTTPClient creates a new DescribeProjectInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeProjectInstancesParamsWithHTTPClient(client *http.Client) *DescribeProjectInstancesParams { + return &DescribeProjectInstancesParams{ + HTTPClient: client, + } +} + +/* DescribeProjectInstancesParams contains all the parameters to send to the API endpoint + for the describe project instances operation. + + Typically these are written to a http.Request. +*/ +type DescribeProjectInstancesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceID. + + 设备ID + */ + DeviceID *string + + /* DeviceTypeID. + + 设备类型ID + */ + DeviceTypeID *string + + /* IdcID. + + 机房ID + */ + IdcID *string + + /* IloIP. + + 带外ip,精确搜索 + */ + IloIP *string + + /* InstanceID. + + 实例ID + */ + InstanceID *string + + /* InstanceName. + + 实例名称,模糊搜索 + */ + InstanceName *string + + /* IPV4. + + ipv4,精确搜索 + */ + IPV4 *string + + /* IPV6. + + ipv6,精确搜索 + */ + IPV6 *string + + /* IsAll. + + 是否显示全部,取值为1时表示全部 + */ + IsAll *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* ProjectID. + + 项目ID + */ + ProjectID *string + + /* Sn. + + SN + */ + Sn *string + + /* Status. + + 运行状态 + */ + Status *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe project instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeProjectInstancesParams) WithDefaults() *DescribeProjectInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe project instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeProjectInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe project instances params +func (o *DescribeProjectInstancesParams) WithTimeout(timeout time.Duration) *DescribeProjectInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe project instances params +func (o *DescribeProjectInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe project instances params +func (o *DescribeProjectInstancesParams) WithContext(ctx context.Context) *DescribeProjectInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe project instances params +func (o *DescribeProjectInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe project instances params +func (o *DescribeProjectInstancesParams) WithHTTPClient(client *http.Client) *DescribeProjectInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe project instances params +func (o *DescribeProjectInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe project instances params +func (o *DescribeProjectInstancesParams) WithAuthorization(authorization string) *DescribeProjectInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe project instances params +func (o *DescribeProjectInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe project instances params +func (o *DescribeProjectInstancesParams) WithBmpLanguage(bmpLanguage *string) *DescribeProjectInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe project instances params +func (o *DescribeProjectInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithBmpUserID(bmpUserID *string) *DescribeProjectInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceID adds the deviceID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithDeviceID(deviceID *string) *DescribeProjectInstancesParams { + o.SetDeviceID(deviceID) + return o +} + +// SetDeviceID adds the deviceId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetDeviceID(deviceID *string) { + o.DeviceID = deviceID +} + +// WithDeviceTypeID adds the deviceTypeID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithDeviceTypeID(deviceTypeID *string) *DescribeProjectInstancesParams { + o.SetDeviceTypeID(deviceTypeID) + return o +} + +// SetDeviceTypeID adds the deviceTypeId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetDeviceTypeID(deviceTypeID *string) { + o.DeviceTypeID = deviceTypeID +} + +// WithIdcID adds the idcID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIdcID(idcID *string) *DescribeProjectInstancesParams { + o.SetIdcID(idcID) + return o +} + +// SetIdcID adds the idcId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIdcID(idcID *string) { + o.IdcID = idcID +} + +// WithIloIP adds the iloIP to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIloIP(iloIP *string) *DescribeProjectInstancesParams { + o.SetIloIP(iloIP) + return o +} + +// SetIloIP adds the iloIp to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIloIP(iloIP *string) { + o.IloIP = iloIP +} + +// WithInstanceID adds the instanceID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithInstanceID(instanceID *string) *DescribeProjectInstancesParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetInstanceID(instanceID *string) { + o.InstanceID = instanceID +} + +// WithInstanceName adds the instanceName to the describe project instances params +func (o *DescribeProjectInstancesParams) WithInstanceName(instanceName *string) *DescribeProjectInstancesParams { + o.SetInstanceName(instanceName) + return o +} + +// SetInstanceName adds the instanceName to the describe project instances params +func (o *DescribeProjectInstancesParams) SetInstanceName(instanceName *string) { + o.InstanceName = instanceName +} + +// WithIPV4 adds the iPV4 to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIPV4(iPV4 *string) *DescribeProjectInstancesParams { + o.SetIPV4(iPV4) + return o +} + +// SetIPV4 adds the ipv4 to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIPV4(iPV4 *string) { + o.IPV4 = iPV4 +} + +// WithIPV6 adds the iPV6 to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIPV6(iPV6 *string) *DescribeProjectInstancesParams { + o.SetIPV6(iPV6) + return o +} + +// SetIPV6 adds the ipv6 to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIPV6(iPV6 *string) { + o.IPV6 = iPV6 +} + +// WithIsAll adds the isAll to the describe project instances params +func (o *DescribeProjectInstancesParams) WithIsAll(isAll *string) *DescribeProjectInstancesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe project instances params +func (o *DescribeProjectInstancesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithPageNumber adds the pageNumber to the describe project instances params +func (o *DescribeProjectInstancesParams) WithPageNumber(pageNumber *int64) *DescribeProjectInstancesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe project instances params +func (o *DescribeProjectInstancesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe project instances params +func (o *DescribeProjectInstancesParams) WithPageSize(pageSize *int64) *DescribeProjectInstancesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe project instances params +func (o *DescribeProjectInstancesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithProjectID adds the projectID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithProjectID(projectID *string) *DescribeProjectInstancesParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetProjectID(projectID *string) { + o.ProjectID = projectID +} + +// WithSn adds the sn to the describe project instances params +func (o *DescribeProjectInstancesParams) WithSn(sn *string) *DescribeProjectInstancesParams { + o.SetSn(sn) + return o +} + +// SetSn adds the sn to the describe project instances params +func (o *DescribeProjectInstancesParams) SetSn(sn *string) { + o.Sn = sn +} + +// WithStatus adds the status to the describe project instances params +func (o *DescribeProjectInstancesParams) WithStatus(status *string) *DescribeProjectInstancesParams { + o.SetStatus(status) + return o +} + +// SetStatus adds the status to the describe project instances params +func (o *DescribeProjectInstancesParams) SetStatus(status *string) { + o.Status = status +} + +// WithTraceID adds the traceID to the describe project instances params +func (o *DescribeProjectInstancesParams) WithTraceID(traceID string) *DescribeProjectInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe project instances params +func (o *DescribeProjectInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeProjectInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceID != nil { + + // query param deviceId + var qrDeviceID string + + if o.DeviceID != nil { + qrDeviceID = *o.DeviceID + } + qDeviceID := qrDeviceID + if qDeviceID != "" { + + if err := r.SetQueryParam("deviceId", qDeviceID); err != nil { + return err + } + } + } + + if o.DeviceTypeID != nil { + + // query param deviceTypeId + var qrDeviceTypeID string + + if o.DeviceTypeID != nil { + qrDeviceTypeID = *o.DeviceTypeID + } + qDeviceTypeID := qrDeviceTypeID + if qDeviceTypeID != "" { + + if err := r.SetQueryParam("deviceTypeId", qDeviceTypeID); err != nil { + return err + } + } + } + + if o.IdcID != nil { + + // query param idcId + var qrIdcID string + + if o.IdcID != nil { + qrIdcID = *o.IdcID + } + qIdcID := qrIdcID + if qIdcID != "" { + + if err := r.SetQueryParam("idcId", qIdcID); err != nil { + return err + } + } + } + + if o.IloIP != nil { + + // query param ilo_ip + var qrIloIP string + + if o.IloIP != nil { + qrIloIP = *o.IloIP + } + qIloIP := qrIloIP + if qIloIP != "" { + + if err := r.SetQueryParam("ilo_ip", qIloIP); err != nil { + return err + } + } + } + + if o.InstanceID != nil { + + // query param instanceId + var qrInstanceID string + + if o.InstanceID != nil { + qrInstanceID = *o.InstanceID + } + qInstanceID := qrInstanceID + if qInstanceID != "" { + + if err := r.SetQueryParam("instanceId", qInstanceID); err != nil { + return err + } + } + } + + if o.InstanceName != nil { + + // query param instanceName + var qrInstanceName string + + if o.InstanceName != nil { + qrInstanceName = *o.InstanceName + } + qInstanceName := qrInstanceName + if qInstanceName != "" { + + if err := r.SetQueryParam("instanceName", qInstanceName); err != nil { + return err + } + } + } + + if o.IPV4 != nil { + + // query param ipv4 + var qrIPV4 string + + if o.IPV4 != nil { + qrIPV4 = *o.IPV4 + } + qIPV4 := qrIPV4 + if qIPV4 != "" { + + if err := r.SetQueryParam("ipv4", qIPV4); err != nil { + return err + } + } + } + + if o.IPV6 != nil { + + // query param ipv6 + var qrIPV6 string + + if o.IPV6 != nil { + qrIPV6 = *o.IPV6 + } + qIPV6 := qrIPV6 + if qIPV6 != "" { + + if err := r.SetQueryParam("ipv6", qIPV6); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.ProjectID != nil { + + // query param projectId + var qrProjectID string + + if o.ProjectID != nil { + qrProjectID = *o.ProjectID + } + qProjectID := qrProjectID + if qProjectID != "" { + + if err := r.SetQueryParam("projectId", qProjectID); err != nil { + return err + } + } + } + + if o.Sn != nil { + + // query param sn + var qrSn string + + if o.Sn != nil { + qrSn = *o.Sn + } + qSn := qrSn + if qSn != "" { + + if err := r.SetQueryParam("sn", qSn); err != nil { + return err + } + } + } + + if o.Status != nil { + + // query param status + var qrStatus string + + if o.Status != nil { + qrStatus = *o.Status + } + qStatus := qrStatus + if qStatus != "" { + + if err := r.SetQueryParam("status", qStatus); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instances_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instances_responses.go new file mode 100644 index 0000000..172005e --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/describe_project_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeProjectInstancesReader is a Reader for the DescribeProjectInstances structure. +type DescribeProjectInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeProjectInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeProjectInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeProjectInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeProjectInstancesOK creates a DescribeProjectInstancesOK with default headers values +func NewDescribeProjectInstancesOK() *DescribeProjectInstancesOK { + return &DescribeProjectInstancesOK{} +} + +/* DescribeProjectInstancesOK describes a response with status code 200, with default header values. + +A DescribeProjectInstancesResult is an response struct that is used to get instance list. +*/ +type DescribeProjectInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeProjectInstancesOKBody +} + +// IsSuccess returns true when this describe project instances o k response has a 2xx status code +func (o *DescribeProjectInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe project instances o k response has a 3xx status code +func (o *DescribeProjectInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe project instances o k response has a 4xx status code +func (o *DescribeProjectInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe project instances o k response has a 5xx status code +func (o *DescribeProjectInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe project instances o k response a status code equal to that given +func (o *DescribeProjectInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeProjectInstancesOK) Error() string { + return fmt.Sprintf("[GET /project/instances][%d] describeProjectInstancesOK %+v", 200, o.Payload) +} + +func (o *DescribeProjectInstancesOK) String() string { + return fmt.Sprintf("[GET /project/instances][%d] describeProjectInstancesOK %+v", 200, o.Payload) +} + +func (o *DescribeProjectInstancesOK) GetPayload() *DescribeProjectInstancesOKBody { + return o.Payload +} + +func (o *DescribeProjectInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeProjectInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeProjectInstancesDefault creates a DescribeProjectInstancesDefault with default headers values +func NewDescribeProjectInstancesDefault(code int) *DescribeProjectInstancesDefault { + return &DescribeProjectInstancesDefault{ + _statusCode: code, + } +} + +/* DescribeProjectInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeProjectInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeProjectInstancesDefaultBody +} + +// Code gets the status code for the describe project instances default response +func (o *DescribeProjectInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe project instances default response has a 2xx status code +func (o *DescribeProjectInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe project instances default response has a 3xx status code +func (o *DescribeProjectInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe project instances default response has a 4xx status code +func (o *DescribeProjectInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe project instances default response has a 5xx status code +func (o *DescribeProjectInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe project instances default response a status code equal to that given +func (o *DescribeProjectInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeProjectInstancesDefault) Error() string { + return fmt.Sprintf("[GET /project/instances][%d] describeProjectInstances default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeProjectInstancesDefault) String() string { + return fmt.Sprintf("[GET /project/instances][%d] describeProjectInstances default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeProjectInstancesDefault) GetPayload() *DescribeProjectInstancesDefaultBody { + return o.Payload +} + +func (o *DescribeProjectInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeProjectInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeProjectInstancesDefaultBody describe project instances default body +swagger:model DescribeProjectInstancesDefaultBody +*/ +type DescribeProjectInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe project instances default body +func (o *DescribeProjectInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeProjectInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeProjectInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeProjectInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe project instances default body based on the context it is used +func (o *DescribeProjectInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeProjectInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeProjectInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeProjectInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeProjectInstancesOKBody describe project instances o k body +swagger:model DescribeProjectInstancesOKBody +*/ +type DescribeProjectInstancesOKBody struct { + + // result + Result *models.InstanceList `json:"result,omitempty"` +} + +// Validate validates this describe project instances o k body +func (o *DescribeProjectInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe project instances o k body based on the context it is used +func (o *DescribeProjectInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeProjectInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeProjectInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeProjectInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeProjectInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeProjectInstancesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeProjectInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/instance_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/instance_client.go new file mode 100644 index 0000000..5ebe75e --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/instance_client.go @@ -0,0 +1,797 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new instance API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for instance API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateProjectInstance(params *CreateProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateProjectInstanceOK, error) + + DeleteInstances(params *DeleteInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteInstancesOK, error) + + DeleteProjectInstance(params *DeleteProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteProjectInstanceOK, error) + + DescribeProjectInstance(params *DescribeProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeProjectInstanceOK, error) + + DescribeProjectInstances(params *DescribeProjectInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeProjectInstancesOK, error) + + LockProjectInstance(params *LockProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*LockProjectInstanceOK, error) + + ModifyInstances(params *ModifyInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyInstancesOK, error) + + ModifyProjectInstance(params *ModifyProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyProjectInstanceOK, error) + + ReinstallProjectInstance(params *ReinstallProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ReinstallProjectInstanceOK, error) + + ResetInstanceStatus(params *ResetInstanceStatusParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetInstanceStatusOK, error) + + ResetProjectInstancePasswd(params *ResetProjectInstancePasswdParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetProjectInstancePasswdOK, error) + + ResetProjectInstancesPasswd(params *ResetProjectInstancesPasswdParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetProjectInstancesPasswdOK, error) + + RestartInstances(params *RestartInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RestartInstancesOK, error) + + RestartProjectInstance(params *RestartProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RestartProjectInstanceOK, error) + + StartInstances(params *StartInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StartInstancesOK, error) + + StartProjectInstance(params *StartProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StartProjectInstanceOK, error) + + StopInstances(params *StopInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StopInstancesOK, error) + + StopProjectInstance(params *StopProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StopProjectInstanceOK, error) + + UnLockProjectInstance(params *UnLockProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UnLockProjectInstanceOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateProjectInstance CreateProjectInstance 创建实例 +*/ +func (a *Client) CreateProjectInstance(params *CreateProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "createProjectInstance", + Method: "POST", + PathPattern: "/project/instances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteInstances DeleteInstances 批量删除实例 +*/ +func (a *Client) DeleteInstances(params *DeleteInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "deleteInstances", + Method: "DELETE", + PathPattern: "/project/instances/batch/instances:deleteInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteProjectInstance DeleteProjectInstance 删除实例 +*/ +func (a *Client) DeleteProjectInstance(params *DeleteProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "deleteProjectInstance", + Method: "DELETE", + PathPattern: "/project/instances/{instance_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeProjectInstance DescribeProjectInstance 获取实例详情 +*/ +func (a *Client) DescribeProjectInstance(params *DescribeProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "describeProjectInstance", + Method: "GET", + PathPattern: "/project/instances/{instance_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeProjectInstances DescribeProjectInstances 获取实例列表 +*/ +func (a *Client) DescribeProjectInstances(params *DescribeProjectInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeProjectInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeProjectInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "describeProjectInstances", + Method: "GET", + PathPattern: "/project/instances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeProjectInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeProjectInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeProjectInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + LockProjectInstance LockProjectInstance 锁定实例 +*/ +func (a *Client) LockProjectInstance(params *LockProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*LockProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewLockProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "lockProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/lock", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &LockProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*LockProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*LockProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyInstances ModifyInstances 批量修改实例名称 +*/ +func (a *Client) ModifyInstances(params *ModifyInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "modifyInstances", + Method: "PUT", + PathPattern: "/project/instances/batch/instances:modifyInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyProjectInstance ModifyProjectInstance 修改实例信息 +*/ +func (a *Client) ModifyProjectInstance(params *ModifyProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "modifyProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ReinstallProjectInstance ReinstallInstance 重装实例 +*/ +func (a *Client) ReinstallProjectInstance(params *ReinstallProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ReinstallProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewReinstallProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "reinstallProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/reinstallInstance", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ReinstallProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ReinstallProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ReinstallProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ResetInstanceStatus ResetInstanceStatus 重置实例状态 +*/ +func (a *Client) ResetInstanceStatus(params *ResetInstanceStatusParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetInstanceStatusOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewResetInstanceStatusParams() + } + op := &runtime.ClientOperation{ + ID: "resetInstanceStatus", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/resetStatus", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ResetInstanceStatusReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ResetInstanceStatusOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ResetInstanceStatusDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ResetProjectInstancePasswd ResetPasswd 重置密码 +*/ +func (a *Client) ResetProjectInstancePasswd(params *ResetProjectInstancePasswdParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetProjectInstancePasswdOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewResetProjectInstancePasswdParams() + } + op := &runtime.ClientOperation{ + ID: "resetProjectInstancePasswd", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/resetpasswd", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ResetProjectInstancePasswdReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ResetProjectInstancePasswdOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ResetProjectInstancePasswdDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ResetProjectInstancesPasswd ResetInstancesPasswd 批量重置密码 +*/ +func (a *Client) ResetProjectInstancesPasswd(params *ResetProjectInstancesPasswdParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ResetProjectInstancesPasswdOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewResetProjectInstancesPasswdParams() + } + op := &runtime.ClientOperation{ + ID: "resetProjectInstancesPasswd", + Method: "PUT", + PathPattern: "/project/instances/batch/instances:resetPasswd", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ResetProjectInstancesPasswdReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ResetProjectInstancesPasswdOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ResetProjectInstancesPasswdDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + RestartInstances StartInstances 批量重启 +*/ +func (a *Client) RestartInstances(params *RestartInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RestartInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewRestartInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "restartInstances", + Method: "PUT", + PathPattern: "/project/instances/batch/instances:restartInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &RestartInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*RestartInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*RestartInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + RestartProjectInstance RestartProjectInstance 实例重启 +*/ +func (a *Client) RestartProjectInstance(params *RestartProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*RestartProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewRestartProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "restartProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/restart", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &RestartProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*RestartProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*RestartProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + StartInstances StartInstances 批量开机 +*/ +func (a *Client) StartInstances(params *StartInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StartInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewStartInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "startInstances", + Method: "PUT", + PathPattern: "/project/instances/batch/instances:startInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &StartInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*StartInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*StartInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + StartProjectInstance StartProjectInstance 实例开机 +*/ +func (a *Client) StartProjectInstance(params *StartProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StartProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewStartProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "startProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/start", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &StartProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*StartProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*StartProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + StopInstances StartInstances 批量关机 +*/ +func (a *Client) StopInstances(params *StopInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StopInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewStopInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "stopInstances", + Method: "PUT", + PathPattern: "/project/instances/batch/instances:stopInstances", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &StopInstancesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*StopInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*StopInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + StopProjectInstance StopProjectInstance 实例关机 +*/ +func (a *Client) StopProjectInstance(params *StopProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*StopProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewStopProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "stopProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/stop", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &StopProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*StopProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*StopProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + UnLockProjectInstance UnLockProjectInstance 解锁实例 +*/ +func (a *Client) UnLockProjectInstance(params *UnLockProjectInstanceParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UnLockProjectInstanceOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewUnLockProjectInstanceParams() + } + op := &runtime.ClientOperation{ + ID: "unLockProjectInstance", + Method: "PUT", + PathPattern: "/project/instances/{instance_id}/unlock", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UnLockProjectInstanceReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*UnLockProjectInstanceOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*UnLockProjectInstanceDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/lock_project_instance_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/lock_project_instance_parameters.go new file mode 100644 index 0000000..8758de3 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/lock_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewLockProjectInstanceParams creates a new LockProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewLockProjectInstanceParams() *LockProjectInstanceParams { + return &LockProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewLockProjectInstanceParamsWithTimeout creates a new LockProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewLockProjectInstanceParamsWithTimeout(timeout time.Duration) *LockProjectInstanceParams { + return &LockProjectInstanceParams{ + timeout: timeout, + } +} + +// NewLockProjectInstanceParamsWithContext creates a new LockProjectInstanceParams object +// with the ability to set a context for a request. +func NewLockProjectInstanceParamsWithContext(ctx context.Context) *LockProjectInstanceParams { + return &LockProjectInstanceParams{ + Context: ctx, + } +} + +// NewLockProjectInstanceParamsWithHTTPClient creates a new LockProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewLockProjectInstanceParamsWithHTTPClient(client *http.Client) *LockProjectInstanceParams { + return &LockProjectInstanceParams{ + HTTPClient: client, + } +} + +/* LockProjectInstanceParams contains all the parameters to send to the API endpoint + for the lock project instance operation. + + Typically these are written to a http.Request. +*/ +type LockProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the lock project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *LockProjectInstanceParams) WithDefaults() *LockProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the lock project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *LockProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the lock project instance params +func (o *LockProjectInstanceParams) WithTimeout(timeout time.Duration) *LockProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the lock project instance params +func (o *LockProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the lock project instance params +func (o *LockProjectInstanceParams) WithContext(ctx context.Context) *LockProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the lock project instance params +func (o *LockProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the lock project instance params +func (o *LockProjectInstanceParams) WithHTTPClient(client *http.Client) *LockProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the lock project instance params +func (o *LockProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the lock project instance params +func (o *LockProjectInstanceParams) WithAuthorization(authorization string) *LockProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the lock project instance params +func (o *LockProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the lock project instance params +func (o *LockProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *LockProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the lock project instance params +func (o *LockProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the lock project instance params +func (o *LockProjectInstanceParams) WithBmpUserID(bmpUserID *string) *LockProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the lock project instance params +func (o *LockProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the lock project instance params +func (o *LockProjectInstanceParams) WithInstanceID(instanceID string) *LockProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the lock project instance params +func (o *LockProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the lock project instance params +func (o *LockProjectInstanceParams) WithTraceID(traceID string) *LockProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the lock project instance params +func (o *LockProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *LockProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/lock_project_instance_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/lock_project_instance_responses.go new file mode 100644 index 0000000..a8e125f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/lock_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// LockProjectInstanceReader is a Reader for the LockProjectInstance structure. +type LockProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *LockProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewLockProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewLockProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewLockProjectInstanceOK creates a LockProjectInstanceOK with default headers values +func NewLockProjectInstanceOK() *LockProjectInstanceOK { + return &LockProjectInstanceOK{} +} + +/* LockProjectInstanceOK describes a response with status code 200, with default header values. + +A LockProjectInstanceResult is an response struct that is used to describe lock instance result. +*/ +type LockProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *LockProjectInstanceOKBody +} + +// IsSuccess returns true when this lock project instance o k response has a 2xx status code +func (o *LockProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this lock project instance o k response has a 3xx status code +func (o *LockProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this lock project instance o k response has a 4xx status code +func (o *LockProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this lock project instance o k response has a 5xx status code +func (o *LockProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this lock project instance o k response a status code equal to that given +func (o *LockProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *LockProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/lock][%d] lockProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *LockProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/lock][%d] lockProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *LockProjectInstanceOK) GetPayload() *LockProjectInstanceOKBody { + return o.Payload +} + +func (o *LockProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(LockProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewLockProjectInstanceDefault creates a LockProjectInstanceDefault with default headers values +func NewLockProjectInstanceDefault(code int) *LockProjectInstanceDefault { + return &LockProjectInstanceDefault{ + _statusCode: code, + } +} + +/* LockProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type LockProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *LockProjectInstanceDefaultBody +} + +// Code gets the status code for the lock project instance default response +func (o *LockProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this lock project instance default response has a 2xx status code +func (o *LockProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this lock project instance default response has a 3xx status code +func (o *LockProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this lock project instance default response has a 4xx status code +func (o *LockProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this lock project instance default response has a 5xx status code +func (o *LockProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this lock project instance default response a status code equal to that given +func (o *LockProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *LockProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/lock][%d] lockProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *LockProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/lock][%d] lockProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *LockProjectInstanceDefault) GetPayload() *LockProjectInstanceDefaultBody { + return o.Payload +} + +func (o *LockProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(LockProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*LockProjectInstanceDefaultBody lock project instance default body +swagger:model LockProjectInstanceDefaultBody +*/ +type LockProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this lock project instance default body +func (o *LockProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *LockProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("lockProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *LockProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("lockProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("lockProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("lockProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this lock project instance default body based on the context it is used +func (o *LockProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *LockProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("lockProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("lockProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *LockProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *LockProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res LockProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*LockProjectInstanceOKBody lock project instance o k body +swagger:model LockProjectInstanceOKBody +*/ +type LockProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this lock project instance o k body +func (o *LockProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *LockProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("lockProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("lockProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this lock project instance o k body based on the context it is used +func (o *LockProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *LockProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("lockProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("lockProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *LockProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *LockProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res LockProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/modify_instances_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/modify_instances_parameters.go new file mode 100644 index 0000000..8354293 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/modify_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyInstancesParams creates a new ModifyInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyInstancesParams() *ModifyInstancesParams { + return &ModifyInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyInstancesParamsWithTimeout creates a new ModifyInstancesParams object +// with the ability to set a timeout on a request. +func NewModifyInstancesParamsWithTimeout(timeout time.Duration) *ModifyInstancesParams { + return &ModifyInstancesParams{ + timeout: timeout, + } +} + +// NewModifyInstancesParamsWithContext creates a new ModifyInstancesParams object +// with the ability to set a context for a request. +func NewModifyInstancesParamsWithContext(ctx context.Context) *ModifyInstancesParams { + return &ModifyInstancesParams{ + Context: ctx, + } +} + +// NewModifyInstancesParamsWithHTTPClient creates a new ModifyInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyInstancesParamsWithHTTPClient(client *http.Client) *ModifyInstancesParams { + return &ModifyInstancesParams{ + HTTPClient: client, + } +} + +/* ModifyInstancesParams contains all the parameters to send to the API endpoint + for the modify instances operation. + + Typically these are written to a http.Request. +*/ +type ModifyInstancesParams struct { + + // Body. + Body *models.ModifyInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyInstancesParams) WithDefaults() *ModifyInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify instances params +func (o *ModifyInstancesParams) WithTimeout(timeout time.Duration) *ModifyInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify instances params +func (o *ModifyInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify instances params +func (o *ModifyInstancesParams) WithContext(ctx context.Context) *ModifyInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify instances params +func (o *ModifyInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify instances params +func (o *ModifyInstancesParams) WithHTTPClient(client *http.Client) *ModifyInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify instances params +func (o *ModifyInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify instances params +func (o *ModifyInstancesParams) WithBody(body *models.ModifyInstancesRequest) *ModifyInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify instances params +func (o *ModifyInstancesParams) SetBody(body *models.ModifyInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify instances params +func (o *ModifyInstancesParams) WithAuthorization(authorization string) *ModifyInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify instances params +func (o *ModifyInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify instances params +func (o *ModifyInstancesParams) WithBmpLanguage(bmpLanguage *string) *ModifyInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify instances params +func (o *ModifyInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify instances params +func (o *ModifyInstancesParams) WithBmpUserID(bmpUserID *string) *ModifyInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify instances params +func (o *ModifyInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the modify instances params +func (o *ModifyInstancesParams) WithTraceID(traceID string) *ModifyInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify instances params +func (o *ModifyInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/modify_instances_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/modify_instances_responses.go new file mode 100644 index 0000000..9b8eec6 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/modify_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyInstancesReader is a Reader for the ModifyInstances structure. +type ModifyInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyInstancesOK creates a ModifyInstancesOK with default headers values +func NewModifyInstancesOK() *ModifyInstancesOK { + return &ModifyInstancesOK{} +} + +/* ModifyInstancesOK describes a response with status code 200, with default header values. + +A ModifyInstancesResult is an response struct that is used to describe modify instance result. +*/ +type ModifyInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyInstancesOKBody +} + +// IsSuccess returns true when this modify instances o k response has a 2xx status code +func (o *ModifyInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify instances o k response has a 3xx status code +func (o *ModifyInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify instances o k response has a 4xx status code +func (o *ModifyInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify instances o k response has a 5xx status code +func (o *ModifyInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify instances o k response a status code equal to that given +func (o *ModifyInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyInstancesOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:modifyInstances][%d] modifyInstancesOK %+v", 200, o.Payload) +} + +func (o *ModifyInstancesOK) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:modifyInstances][%d] modifyInstancesOK %+v", 200, o.Payload) +} + +func (o *ModifyInstancesOK) GetPayload() *ModifyInstancesOKBody { + return o.Payload +} + +func (o *ModifyInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyInstancesDefault creates a ModifyInstancesDefault with default headers values +func NewModifyInstancesDefault(code int) *ModifyInstancesDefault { + return &ModifyInstancesDefault{ + _statusCode: code, + } +} + +/* ModifyInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyInstancesDefaultBody +} + +// Code gets the status code for the modify instances default response +func (o *ModifyInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify instances default response has a 2xx status code +func (o *ModifyInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify instances default response has a 3xx status code +func (o *ModifyInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify instances default response has a 4xx status code +func (o *ModifyInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify instances default response has a 5xx status code +func (o *ModifyInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify instances default response a status code equal to that given +func (o *ModifyInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyInstancesDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:modifyInstances][%d] modifyInstances default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyInstancesDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:modifyInstances][%d] modifyInstances default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyInstancesDefault) GetPayload() *ModifyInstancesDefaultBody { + return o.Payload +} + +func (o *ModifyInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyInstancesDefaultBody modify instances default body +swagger:model ModifyInstancesDefaultBody +*/ +type ModifyInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify instances default body +func (o *ModifyInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify instances default body based on the context it is used +func (o *ModifyInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyInstancesOKBody modify instances o k body +swagger:model ModifyInstancesOKBody +*/ +type ModifyInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify instances o k body +func (o *ModifyInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify instances o k body based on the context it is used +func (o *ModifyInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyInstancesOKBody) UnmarshalBinary(b []byte) error { + var res ModifyInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/modify_project_instance_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/modify_project_instance_parameters.go new file mode 100644 index 0000000..8608e78 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/modify_project_instance_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyProjectInstanceParams creates a new ModifyProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyProjectInstanceParams() *ModifyProjectInstanceParams { + return &ModifyProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyProjectInstanceParamsWithTimeout creates a new ModifyProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewModifyProjectInstanceParamsWithTimeout(timeout time.Duration) *ModifyProjectInstanceParams { + return &ModifyProjectInstanceParams{ + timeout: timeout, + } +} + +// NewModifyProjectInstanceParamsWithContext creates a new ModifyProjectInstanceParams object +// with the ability to set a context for a request. +func NewModifyProjectInstanceParamsWithContext(ctx context.Context) *ModifyProjectInstanceParams { + return &ModifyProjectInstanceParams{ + Context: ctx, + } +} + +// NewModifyProjectInstanceParamsWithHTTPClient creates a new ModifyProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyProjectInstanceParamsWithHTTPClient(client *http.Client) *ModifyProjectInstanceParams { + return &ModifyProjectInstanceParams{ + HTTPClient: client, + } +} + +/* ModifyProjectInstanceParams contains all the parameters to send to the API endpoint + for the modify project instance operation. + + Typically these are written to a http.Request. +*/ +type ModifyProjectInstanceParams struct { + + // Body. + Body *models.ModifyInstanceRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyProjectInstanceParams) WithDefaults() *ModifyProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify project instance params +func (o *ModifyProjectInstanceParams) WithTimeout(timeout time.Duration) *ModifyProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify project instance params +func (o *ModifyProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify project instance params +func (o *ModifyProjectInstanceParams) WithContext(ctx context.Context) *ModifyProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify project instance params +func (o *ModifyProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify project instance params +func (o *ModifyProjectInstanceParams) WithHTTPClient(client *http.Client) *ModifyProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify project instance params +func (o *ModifyProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify project instance params +func (o *ModifyProjectInstanceParams) WithBody(body *models.ModifyInstanceRequest) *ModifyProjectInstanceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify project instance params +func (o *ModifyProjectInstanceParams) SetBody(body *models.ModifyInstanceRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify project instance params +func (o *ModifyProjectInstanceParams) WithAuthorization(authorization string) *ModifyProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify project instance params +func (o *ModifyProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify project instance params +func (o *ModifyProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *ModifyProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify project instance params +func (o *ModifyProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify project instance params +func (o *ModifyProjectInstanceParams) WithBmpUserID(bmpUserID *string) *ModifyProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify project instance params +func (o *ModifyProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the modify project instance params +func (o *ModifyProjectInstanceParams) WithInstanceID(instanceID string) *ModifyProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the modify project instance params +func (o *ModifyProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the modify project instance params +func (o *ModifyProjectInstanceParams) WithTraceID(traceID string) *ModifyProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify project instance params +func (o *ModifyProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/modify_project_instance_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/modify_project_instance_responses.go new file mode 100644 index 0000000..e22862e --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/modify_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyProjectInstanceReader is a Reader for the ModifyProjectInstance structure. +type ModifyProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyProjectInstanceOK creates a ModifyProjectInstanceOK with default headers values +func NewModifyProjectInstanceOK() *ModifyProjectInstanceOK { + return &ModifyProjectInstanceOK{} +} + +/* ModifyProjectInstanceOK describes a response with status code 200, with default header values. + +A ModifyProjectInstanceResult is an response struct that is used to describe modify instance result. +*/ +type ModifyProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyProjectInstanceOKBody +} + +// IsSuccess returns true when this modify project instance o k response has a 2xx status code +func (o *ModifyProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify project instance o k response has a 3xx status code +func (o *ModifyProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify project instance o k response has a 4xx status code +func (o *ModifyProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify project instance o k response has a 5xx status code +func (o *ModifyProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify project instance o k response a status code equal to that given +func (o *ModifyProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}][%d] modifyProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *ModifyProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}][%d] modifyProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *ModifyProjectInstanceOK) GetPayload() *ModifyProjectInstanceOKBody { + return o.Payload +} + +func (o *ModifyProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyProjectInstanceDefault creates a ModifyProjectInstanceDefault with default headers values +func NewModifyProjectInstanceDefault(code int) *ModifyProjectInstanceDefault { + return &ModifyProjectInstanceDefault{ + _statusCode: code, + } +} + +/* ModifyProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyProjectInstanceDefaultBody +} + +// Code gets the status code for the modify project instance default response +func (o *ModifyProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify project instance default response has a 2xx status code +func (o *ModifyProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify project instance default response has a 3xx status code +func (o *ModifyProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify project instance default response has a 4xx status code +func (o *ModifyProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify project instance default response has a 5xx status code +func (o *ModifyProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify project instance default response a status code equal to that given +func (o *ModifyProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}][%d] modifyProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}][%d] modifyProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyProjectInstanceDefault) GetPayload() *ModifyProjectInstanceDefaultBody { + return o.Payload +} + +func (o *ModifyProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyProjectInstanceDefaultBody modify project instance default body +swagger:model ModifyProjectInstanceDefaultBody +*/ +type ModifyProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify project instance default body +func (o *ModifyProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify project instance default body based on the context it is used +func (o *ModifyProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyProjectInstanceOKBody modify project instance o k body +swagger:model ModifyProjectInstanceOKBody +*/ +type ModifyProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify project instance o k body +func (o *ModifyProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify project instance o k body based on the context it is used +func (o *ModifyProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res ModifyProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reinstall_project_instance_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reinstall_project_instance_parameters.go new file mode 100644 index 0000000..fe4605d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reinstall_project_instance_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewReinstallProjectInstanceParams creates a new ReinstallProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewReinstallProjectInstanceParams() *ReinstallProjectInstanceParams { + return &ReinstallProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewReinstallProjectInstanceParamsWithTimeout creates a new ReinstallProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewReinstallProjectInstanceParamsWithTimeout(timeout time.Duration) *ReinstallProjectInstanceParams { + return &ReinstallProjectInstanceParams{ + timeout: timeout, + } +} + +// NewReinstallProjectInstanceParamsWithContext creates a new ReinstallProjectInstanceParams object +// with the ability to set a context for a request. +func NewReinstallProjectInstanceParamsWithContext(ctx context.Context) *ReinstallProjectInstanceParams { + return &ReinstallProjectInstanceParams{ + Context: ctx, + } +} + +// NewReinstallProjectInstanceParamsWithHTTPClient creates a new ReinstallProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewReinstallProjectInstanceParamsWithHTTPClient(client *http.Client) *ReinstallProjectInstanceParams { + return &ReinstallProjectInstanceParams{ + HTTPClient: client, + } +} + +/* ReinstallProjectInstanceParams contains all the parameters to send to the API endpoint + for the reinstall project instance operation. + + Typically these are written to a http.Request. +*/ +type ReinstallProjectInstanceParams struct { + + // Body. + Body *models.ReinstallInstanceRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the reinstall project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ReinstallProjectInstanceParams) WithDefaults() *ReinstallProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the reinstall project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ReinstallProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithTimeout(timeout time.Duration) *ReinstallProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithContext(ctx context.Context) *ReinstallProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithHTTPClient(client *http.Client) *ReinstallProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithBody(body *models.ReinstallInstanceRequest) *ReinstallProjectInstanceParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetBody(body *models.ReinstallInstanceRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithAuthorization(authorization string) *ReinstallProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *ReinstallProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithBmpUserID(bmpUserID *string) *ReinstallProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithInstanceID(instanceID string) *ReinstallProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) WithTraceID(traceID string) *ReinstallProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the reinstall project instance params +func (o *ReinstallProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ReinstallProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reinstall_project_instance_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reinstall_project_instance_responses.go new file mode 100644 index 0000000..7786a73 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reinstall_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ReinstallProjectInstanceReader is a Reader for the ReinstallProjectInstance structure. +type ReinstallProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ReinstallProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewReinstallProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewReinstallProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewReinstallProjectInstanceOK creates a ReinstallProjectInstanceOK with default headers values +func NewReinstallProjectInstanceOK() *ReinstallProjectInstanceOK { + return &ReinstallProjectInstanceOK{} +} + +/* ReinstallProjectInstanceOK describes a response with status code 200, with default header values. + +A ReinstallProjectInstanceResult is an response struct that is used to describe reinstall instance. +*/ +type ReinstallProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ReinstallProjectInstanceOKBody +} + +// IsSuccess returns true when this reinstall project instance o k response has a 2xx status code +func (o *ReinstallProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this reinstall project instance o k response has a 3xx status code +func (o *ReinstallProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this reinstall project instance o k response has a 4xx status code +func (o *ReinstallProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this reinstall project instance o k response has a 5xx status code +func (o *ReinstallProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this reinstall project instance o k response a status code equal to that given +func (o *ReinstallProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ReinstallProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/reinstallInstance][%d] reinstallProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *ReinstallProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/reinstallInstance][%d] reinstallProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *ReinstallProjectInstanceOK) GetPayload() *ReinstallProjectInstanceOKBody { + return o.Payload +} + +func (o *ReinstallProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ReinstallProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewReinstallProjectInstanceDefault creates a ReinstallProjectInstanceDefault with default headers values +func NewReinstallProjectInstanceDefault(code int) *ReinstallProjectInstanceDefault { + return &ReinstallProjectInstanceDefault{ + _statusCode: code, + } +} + +/* ReinstallProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ReinstallProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ReinstallProjectInstanceDefaultBody +} + +// Code gets the status code for the reinstall project instance default response +func (o *ReinstallProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this reinstall project instance default response has a 2xx status code +func (o *ReinstallProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this reinstall project instance default response has a 3xx status code +func (o *ReinstallProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this reinstall project instance default response has a 4xx status code +func (o *ReinstallProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this reinstall project instance default response has a 5xx status code +func (o *ReinstallProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this reinstall project instance default response a status code equal to that given +func (o *ReinstallProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ReinstallProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/reinstallInstance][%d] reinstallProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *ReinstallProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/reinstallInstance][%d] reinstallProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *ReinstallProjectInstanceDefault) GetPayload() *ReinstallProjectInstanceDefaultBody { + return o.Payload +} + +func (o *ReinstallProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ReinstallProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ReinstallProjectInstanceDefaultBody reinstall project instance default body +swagger:model ReinstallProjectInstanceDefaultBody +*/ +type ReinstallProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this reinstall project instance default body +func (o *ReinstallProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReinstallProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("reinstallProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ReinstallProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("reinstallProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("reinstallProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("reinstallProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reinstall project instance default body based on the context it is used +func (o *ReinstallProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReinstallProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("reinstallProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("reinstallProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ReinstallProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ReinstallProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res ReinstallProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ReinstallProjectInstanceOKBody reinstall project instance o k body +swagger:model ReinstallProjectInstanceOKBody +*/ +type ReinstallProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this reinstall project instance o k body +func (o *ReinstallProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReinstallProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("reinstallProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("reinstallProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reinstall project instance o k body based on the context it is used +func (o *ReinstallProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ReinstallProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("reinstallProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("reinstallProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ReinstallProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ReinstallProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res ReinstallProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_instance_status_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_instance_status_parameters.go new file mode 100644 index 0000000..853f1fe --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_instance_status_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewResetInstanceStatusParams creates a new ResetInstanceStatusParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewResetInstanceStatusParams() *ResetInstanceStatusParams { + return &ResetInstanceStatusParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewResetInstanceStatusParamsWithTimeout creates a new ResetInstanceStatusParams object +// with the ability to set a timeout on a request. +func NewResetInstanceStatusParamsWithTimeout(timeout time.Duration) *ResetInstanceStatusParams { + return &ResetInstanceStatusParams{ + timeout: timeout, + } +} + +// NewResetInstanceStatusParamsWithContext creates a new ResetInstanceStatusParams object +// with the ability to set a context for a request. +func NewResetInstanceStatusParamsWithContext(ctx context.Context) *ResetInstanceStatusParams { + return &ResetInstanceStatusParams{ + Context: ctx, + } +} + +// NewResetInstanceStatusParamsWithHTTPClient creates a new ResetInstanceStatusParams object +// with the ability to set a custom HTTPClient for a request. +func NewResetInstanceStatusParamsWithHTTPClient(client *http.Client) *ResetInstanceStatusParams { + return &ResetInstanceStatusParams{ + HTTPClient: client, + } +} + +/* ResetInstanceStatusParams contains all the parameters to send to the API endpoint + for the reset instance status operation. + + Typically these are written to a http.Request. +*/ +type ResetInstanceStatusParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the reset instance status params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetInstanceStatusParams) WithDefaults() *ResetInstanceStatusParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the reset instance status params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetInstanceStatusParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the reset instance status params +func (o *ResetInstanceStatusParams) WithTimeout(timeout time.Duration) *ResetInstanceStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the reset instance status params +func (o *ResetInstanceStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the reset instance status params +func (o *ResetInstanceStatusParams) WithContext(ctx context.Context) *ResetInstanceStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the reset instance status params +func (o *ResetInstanceStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the reset instance status params +func (o *ResetInstanceStatusParams) WithHTTPClient(client *http.Client) *ResetInstanceStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the reset instance status params +func (o *ResetInstanceStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the reset instance status params +func (o *ResetInstanceStatusParams) WithAuthorization(authorization string) *ResetInstanceStatusParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the reset instance status params +func (o *ResetInstanceStatusParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the reset instance status params +func (o *ResetInstanceStatusParams) WithBmpLanguage(bmpLanguage *string) *ResetInstanceStatusParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the reset instance status params +func (o *ResetInstanceStatusParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the reset instance status params +func (o *ResetInstanceStatusParams) WithBmpUserID(bmpUserID *string) *ResetInstanceStatusParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the reset instance status params +func (o *ResetInstanceStatusParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the reset instance status params +func (o *ResetInstanceStatusParams) WithInstanceID(instanceID string) *ResetInstanceStatusParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the reset instance status params +func (o *ResetInstanceStatusParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the reset instance status params +func (o *ResetInstanceStatusParams) WithTraceID(traceID string) *ResetInstanceStatusParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the reset instance status params +func (o *ResetInstanceStatusParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ResetInstanceStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_instance_status_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_instance_status_responses.go new file mode 100644 index 0000000..5da5276 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_instance_status_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ResetInstanceStatusReader is a Reader for the ResetInstanceStatus structure. +type ResetInstanceStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ResetInstanceStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewResetInstanceStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewResetInstanceStatusDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewResetInstanceStatusOK creates a ResetInstanceStatusOK with default headers values +func NewResetInstanceStatusOK() *ResetInstanceStatusOK { + return &ResetInstanceStatusOK{} +} + +/* ResetInstanceStatusOK describes a response with status code 200, with default header values. + +A ResetInstanceStatusResult is an response struct that is used to describe restart instance result. +*/ +type ResetInstanceStatusOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetInstanceStatusOKBody +} + +// IsSuccess returns true when this reset instance status o k response has a 2xx status code +func (o *ResetInstanceStatusOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this reset instance status o k response has a 3xx status code +func (o *ResetInstanceStatusOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this reset instance status o k response has a 4xx status code +func (o *ResetInstanceStatusOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this reset instance status o k response has a 5xx status code +func (o *ResetInstanceStatusOK) IsServerError() bool { + return false +} + +// IsCode returns true when this reset instance status o k response a status code equal to that given +func (o *ResetInstanceStatusOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ResetInstanceStatusOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetStatus][%d] resetInstanceStatusOK %+v", 200, o.Payload) +} + +func (o *ResetInstanceStatusOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetStatus][%d] resetInstanceStatusOK %+v", 200, o.Payload) +} + +func (o *ResetInstanceStatusOK) GetPayload() *ResetInstanceStatusOKBody { + return o.Payload +} + +func (o *ResetInstanceStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetInstanceStatusOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewResetInstanceStatusDefault creates a ResetInstanceStatusDefault with default headers values +func NewResetInstanceStatusDefault(code int) *ResetInstanceStatusDefault { + return &ResetInstanceStatusDefault{ + _statusCode: code, + } +} + +/* ResetInstanceStatusDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ResetInstanceStatusDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetInstanceStatusDefaultBody +} + +// Code gets the status code for the reset instance status default response +func (o *ResetInstanceStatusDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this reset instance status default response has a 2xx status code +func (o *ResetInstanceStatusDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this reset instance status default response has a 3xx status code +func (o *ResetInstanceStatusDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this reset instance status default response has a 4xx status code +func (o *ResetInstanceStatusDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this reset instance status default response has a 5xx status code +func (o *ResetInstanceStatusDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this reset instance status default response a status code equal to that given +func (o *ResetInstanceStatusDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ResetInstanceStatusDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetStatus][%d] resetInstanceStatus default %+v", o._statusCode, o.Payload) +} + +func (o *ResetInstanceStatusDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetStatus][%d] resetInstanceStatus default %+v", o._statusCode, o.Payload) +} + +func (o *ResetInstanceStatusDefault) GetPayload() *ResetInstanceStatusDefaultBody { + return o.Payload +} + +func (o *ResetInstanceStatusDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetInstanceStatusDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ResetInstanceStatusDefaultBody reset instance status default body +swagger:model ResetInstanceStatusDefaultBody +*/ +type ResetInstanceStatusDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this reset instance status default body +func (o *ResetInstanceStatusDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetInstanceStatusDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("resetInstanceStatus default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ResetInstanceStatusDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("resetInstanceStatus default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetInstanceStatus default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetInstanceStatus default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset instance status default body based on the context it is used +func (o *ResetInstanceStatusDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetInstanceStatusDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetInstanceStatus default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetInstanceStatus default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetInstanceStatusDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetInstanceStatusDefaultBody) UnmarshalBinary(b []byte) error { + var res ResetInstanceStatusDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ResetInstanceStatusOKBody reset instance status o k body +swagger:model ResetInstanceStatusOKBody +*/ +type ResetInstanceStatusOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this reset instance status o k body +func (o *ResetInstanceStatusOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetInstanceStatusOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetInstanceStatusOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetInstanceStatusOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset instance status o k body based on the context it is used +func (o *ResetInstanceStatusOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetInstanceStatusOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetInstanceStatusOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetInstanceStatusOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetInstanceStatusOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetInstanceStatusOKBody) UnmarshalBinary(b []byte) error { + var res ResetInstanceStatusOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instance_passwd_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instance_passwd_parameters.go new file mode 100644 index 0000000..e7c5925 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instance_passwd_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewResetProjectInstancePasswdParams creates a new ResetProjectInstancePasswdParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewResetProjectInstancePasswdParams() *ResetProjectInstancePasswdParams { + return &ResetProjectInstancePasswdParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewResetProjectInstancePasswdParamsWithTimeout creates a new ResetProjectInstancePasswdParams object +// with the ability to set a timeout on a request. +func NewResetProjectInstancePasswdParamsWithTimeout(timeout time.Duration) *ResetProjectInstancePasswdParams { + return &ResetProjectInstancePasswdParams{ + timeout: timeout, + } +} + +// NewResetProjectInstancePasswdParamsWithContext creates a new ResetProjectInstancePasswdParams object +// with the ability to set a context for a request. +func NewResetProjectInstancePasswdParamsWithContext(ctx context.Context) *ResetProjectInstancePasswdParams { + return &ResetProjectInstancePasswdParams{ + Context: ctx, + } +} + +// NewResetProjectInstancePasswdParamsWithHTTPClient creates a new ResetProjectInstancePasswdParams object +// with the ability to set a custom HTTPClient for a request. +func NewResetProjectInstancePasswdParamsWithHTTPClient(client *http.Client) *ResetProjectInstancePasswdParams { + return &ResetProjectInstancePasswdParams{ + HTTPClient: client, + } +} + +/* ResetProjectInstancePasswdParams contains all the parameters to send to the API endpoint + for the reset project instance passwd operation. + + Typically these are written to a http.Request. +*/ +type ResetProjectInstancePasswdParams struct { + + // Body. + Body *models.ResetInstancePasswdRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the reset project instance passwd params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetProjectInstancePasswdParams) WithDefaults() *ResetProjectInstancePasswdParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the reset project instance passwd params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetProjectInstancePasswdParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithTimeout(timeout time.Duration) *ResetProjectInstancePasswdParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithContext(ctx context.Context) *ResetProjectInstancePasswdParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithHTTPClient(client *http.Client) *ResetProjectInstancePasswdParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithBody(body *models.ResetInstancePasswdRequest) *ResetProjectInstancePasswdParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetBody(body *models.ResetInstancePasswdRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithAuthorization(authorization string) *ResetProjectInstancePasswdParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithBmpLanguage(bmpLanguage *string) *ResetProjectInstancePasswdParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithBmpUserID(bmpUserID *string) *ResetProjectInstancePasswdParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithInstanceID(instanceID string) *ResetProjectInstancePasswdParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) WithTraceID(traceID string) *ResetProjectInstancePasswdParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the reset project instance passwd params +func (o *ResetProjectInstancePasswdParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ResetProjectInstancePasswdParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instance_passwd_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instance_passwd_responses.go new file mode 100644 index 0000000..e998a94 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instance_passwd_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ResetProjectInstancePasswdReader is a Reader for the ResetProjectInstancePasswd structure. +type ResetProjectInstancePasswdReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ResetProjectInstancePasswdReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewResetProjectInstancePasswdOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewResetProjectInstancePasswdDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewResetProjectInstancePasswdOK creates a ResetProjectInstancePasswdOK with default headers values +func NewResetProjectInstancePasswdOK() *ResetProjectInstancePasswdOK { + return &ResetProjectInstancePasswdOK{} +} + +/* ResetProjectInstancePasswdOK describes a response with status code 200, with default header values. + +A ResetProjectInstancePasswdResult is an response struct that is used to describe reset instance password. +*/ +type ResetProjectInstancePasswdOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetProjectInstancePasswdOKBody +} + +// IsSuccess returns true when this reset project instance passwd o k response has a 2xx status code +func (o *ResetProjectInstancePasswdOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this reset project instance passwd o k response has a 3xx status code +func (o *ResetProjectInstancePasswdOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this reset project instance passwd o k response has a 4xx status code +func (o *ResetProjectInstancePasswdOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this reset project instance passwd o k response has a 5xx status code +func (o *ResetProjectInstancePasswdOK) IsServerError() bool { + return false +} + +// IsCode returns true when this reset project instance passwd o k response a status code equal to that given +func (o *ResetProjectInstancePasswdOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ResetProjectInstancePasswdOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetpasswd][%d] resetProjectInstancePasswdOK %+v", 200, o.Payload) +} + +func (o *ResetProjectInstancePasswdOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetpasswd][%d] resetProjectInstancePasswdOK %+v", 200, o.Payload) +} + +func (o *ResetProjectInstancePasswdOK) GetPayload() *ResetProjectInstancePasswdOKBody { + return o.Payload +} + +func (o *ResetProjectInstancePasswdOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetProjectInstancePasswdOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewResetProjectInstancePasswdDefault creates a ResetProjectInstancePasswdDefault with default headers values +func NewResetProjectInstancePasswdDefault(code int) *ResetProjectInstancePasswdDefault { + return &ResetProjectInstancePasswdDefault{ + _statusCode: code, + } +} + +/* ResetProjectInstancePasswdDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ResetProjectInstancePasswdDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetProjectInstancePasswdDefaultBody +} + +// Code gets the status code for the reset project instance passwd default response +func (o *ResetProjectInstancePasswdDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this reset project instance passwd default response has a 2xx status code +func (o *ResetProjectInstancePasswdDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this reset project instance passwd default response has a 3xx status code +func (o *ResetProjectInstancePasswdDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this reset project instance passwd default response has a 4xx status code +func (o *ResetProjectInstancePasswdDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this reset project instance passwd default response has a 5xx status code +func (o *ResetProjectInstancePasswdDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this reset project instance passwd default response a status code equal to that given +func (o *ResetProjectInstancePasswdDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ResetProjectInstancePasswdDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetpasswd][%d] resetProjectInstancePasswd default %+v", o._statusCode, o.Payload) +} + +func (o *ResetProjectInstancePasswdDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/resetpasswd][%d] resetProjectInstancePasswd default %+v", o._statusCode, o.Payload) +} + +func (o *ResetProjectInstancePasswdDefault) GetPayload() *ResetProjectInstancePasswdDefaultBody { + return o.Payload +} + +func (o *ResetProjectInstancePasswdDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetProjectInstancePasswdDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ResetProjectInstancePasswdDefaultBody reset project instance passwd default body +swagger:model ResetProjectInstancePasswdDefaultBody +*/ +type ResetProjectInstancePasswdDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this reset project instance passwd default body +func (o *ResetProjectInstancePasswdDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancePasswdDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("resetProjectInstancePasswd default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ResetProjectInstancePasswdDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("resetProjectInstancePasswd default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancePasswd default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancePasswd default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset project instance passwd default body based on the context it is used +func (o *ResetProjectInstancePasswdDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancePasswdDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancePasswd default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancePasswd default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetProjectInstancePasswdDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetProjectInstancePasswdDefaultBody) UnmarshalBinary(b []byte) error { + var res ResetProjectInstancePasswdDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ResetProjectInstancePasswdOKBody reset project instance passwd o k body +swagger:model ResetProjectInstancePasswdOKBody +*/ +type ResetProjectInstancePasswdOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this reset project instance passwd o k body +func (o *ResetProjectInstancePasswdOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancePasswdOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancePasswdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancePasswdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset project instance passwd o k body based on the context it is used +func (o *ResetProjectInstancePasswdOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancePasswdOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancePasswdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancePasswdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetProjectInstancePasswdOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetProjectInstancePasswdOKBody) UnmarshalBinary(b []byte) error { + var res ResetProjectInstancePasswdOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instances_passwd_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instances_passwd_parameters.go new file mode 100644 index 0000000..7de3615 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instances_passwd_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewResetProjectInstancesPasswdParams creates a new ResetProjectInstancesPasswdParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewResetProjectInstancesPasswdParams() *ResetProjectInstancesPasswdParams { + return &ResetProjectInstancesPasswdParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewResetProjectInstancesPasswdParamsWithTimeout creates a new ResetProjectInstancesPasswdParams object +// with the ability to set a timeout on a request. +func NewResetProjectInstancesPasswdParamsWithTimeout(timeout time.Duration) *ResetProjectInstancesPasswdParams { + return &ResetProjectInstancesPasswdParams{ + timeout: timeout, + } +} + +// NewResetProjectInstancesPasswdParamsWithContext creates a new ResetProjectInstancesPasswdParams object +// with the ability to set a context for a request. +func NewResetProjectInstancesPasswdParamsWithContext(ctx context.Context) *ResetProjectInstancesPasswdParams { + return &ResetProjectInstancesPasswdParams{ + Context: ctx, + } +} + +// NewResetProjectInstancesPasswdParamsWithHTTPClient creates a new ResetProjectInstancesPasswdParams object +// with the ability to set a custom HTTPClient for a request. +func NewResetProjectInstancesPasswdParamsWithHTTPClient(client *http.Client) *ResetProjectInstancesPasswdParams { + return &ResetProjectInstancesPasswdParams{ + HTTPClient: client, + } +} + +/* ResetProjectInstancesPasswdParams contains all the parameters to send to the API endpoint + for the reset project instances passwd operation. + + Typically these are written to a http.Request. +*/ +type ResetProjectInstancesPasswdParams struct { + + // Body. + Body *models.ResetInstancesPasswdRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the reset project instances passwd params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetProjectInstancesPasswdParams) WithDefaults() *ResetProjectInstancesPasswdParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the reset project instances passwd params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ResetProjectInstancesPasswdParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithTimeout(timeout time.Duration) *ResetProjectInstancesPasswdParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithContext(ctx context.Context) *ResetProjectInstancesPasswdParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithHTTPClient(client *http.Client) *ResetProjectInstancesPasswdParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithBody(body *models.ResetInstancesPasswdRequest) *ResetProjectInstancesPasswdParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetBody(body *models.ResetInstancesPasswdRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithAuthorization(authorization string) *ResetProjectInstancesPasswdParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithBmpLanguage(bmpLanguage *string) *ResetProjectInstancesPasswdParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithBmpUserID(bmpUserID *string) *ResetProjectInstancesPasswdParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) WithTraceID(traceID string) *ResetProjectInstancesPasswdParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the reset project instances passwd params +func (o *ResetProjectInstancesPasswdParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ResetProjectInstancesPasswdParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instances_passwd_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instances_passwd_responses.go new file mode 100644 index 0000000..dedb483 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/reset_project_instances_passwd_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ResetProjectInstancesPasswdReader is a Reader for the ResetProjectInstancesPasswd structure. +type ResetProjectInstancesPasswdReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ResetProjectInstancesPasswdReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewResetProjectInstancesPasswdOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewResetProjectInstancesPasswdDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewResetProjectInstancesPasswdOK creates a ResetProjectInstancesPasswdOK with default headers values +func NewResetProjectInstancesPasswdOK() *ResetProjectInstancesPasswdOK { + return &ResetProjectInstancesPasswdOK{} +} + +/* ResetProjectInstancesPasswdOK describes a response with status code 200, with default header values. + +A ResetProjectInstancesPasswdResult is an response struct that is used to describe reset instance password. +*/ +type ResetProjectInstancesPasswdOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetProjectInstancesPasswdOKBody +} + +// IsSuccess returns true when this reset project instances passwd o k response has a 2xx status code +func (o *ResetProjectInstancesPasswdOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this reset project instances passwd o k response has a 3xx status code +func (o *ResetProjectInstancesPasswdOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this reset project instances passwd o k response has a 4xx status code +func (o *ResetProjectInstancesPasswdOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this reset project instances passwd o k response has a 5xx status code +func (o *ResetProjectInstancesPasswdOK) IsServerError() bool { + return false +} + +// IsCode returns true when this reset project instances passwd o k response a status code equal to that given +func (o *ResetProjectInstancesPasswdOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ResetProjectInstancesPasswdOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:resetPasswd][%d] resetProjectInstancesPasswdOK %+v", 200, o.Payload) +} + +func (o *ResetProjectInstancesPasswdOK) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:resetPasswd][%d] resetProjectInstancesPasswdOK %+v", 200, o.Payload) +} + +func (o *ResetProjectInstancesPasswdOK) GetPayload() *ResetProjectInstancesPasswdOKBody { + return o.Payload +} + +func (o *ResetProjectInstancesPasswdOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetProjectInstancesPasswdOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewResetProjectInstancesPasswdDefault creates a ResetProjectInstancesPasswdDefault with default headers values +func NewResetProjectInstancesPasswdDefault(code int) *ResetProjectInstancesPasswdDefault { + return &ResetProjectInstancesPasswdDefault{ + _statusCode: code, + } +} + +/* ResetProjectInstancesPasswdDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ResetProjectInstancesPasswdDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ResetProjectInstancesPasswdDefaultBody +} + +// Code gets the status code for the reset project instances passwd default response +func (o *ResetProjectInstancesPasswdDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this reset project instances passwd default response has a 2xx status code +func (o *ResetProjectInstancesPasswdDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this reset project instances passwd default response has a 3xx status code +func (o *ResetProjectInstancesPasswdDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this reset project instances passwd default response has a 4xx status code +func (o *ResetProjectInstancesPasswdDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this reset project instances passwd default response has a 5xx status code +func (o *ResetProjectInstancesPasswdDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this reset project instances passwd default response a status code equal to that given +func (o *ResetProjectInstancesPasswdDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ResetProjectInstancesPasswdDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:resetPasswd][%d] resetProjectInstancesPasswd default %+v", o._statusCode, o.Payload) +} + +func (o *ResetProjectInstancesPasswdDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:resetPasswd][%d] resetProjectInstancesPasswd default %+v", o._statusCode, o.Payload) +} + +func (o *ResetProjectInstancesPasswdDefault) GetPayload() *ResetProjectInstancesPasswdDefaultBody { + return o.Payload +} + +func (o *ResetProjectInstancesPasswdDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ResetProjectInstancesPasswdDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ResetProjectInstancesPasswdDefaultBody reset project instances passwd default body +swagger:model ResetProjectInstancesPasswdDefaultBody +*/ +type ResetProjectInstancesPasswdDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this reset project instances passwd default body +func (o *ResetProjectInstancesPasswdDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancesPasswdDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("resetProjectInstancesPasswd default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ResetProjectInstancesPasswdDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("resetProjectInstancesPasswd default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancesPasswd default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancesPasswd default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset project instances passwd default body based on the context it is used +func (o *ResetProjectInstancesPasswdDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancesPasswdDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancesPasswd default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancesPasswd default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetProjectInstancesPasswdDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetProjectInstancesPasswdDefaultBody) UnmarshalBinary(b []byte) error { + var res ResetProjectInstancesPasswdDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ResetProjectInstancesPasswdOKBody reset project instances passwd o k body +swagger:model ResetProjectInstancesPasswdOKBody +*/ +type ResetProjectInstancesPasswdOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this reset project instances passwd o k body +func (o *ResetProjectInstancesPasswdOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancesPasswdOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancesPasswdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancesPasswdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this reset project instances passwd o k body based on the context it is used +func (o *ResetProjectInstancesPasswdOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ResetProjectInstancesPasswdOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("resetProjectInstancesPasswdOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("resetProjectInstancesPasswdOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ResetProjectInstancesPasswdOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ResetProjectInstancesPasswdOKBody) UnmarshalBinary(b []byte) error { + var res ResetProjectInstancesPasswdOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/restart_instances_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/restart_instances_parameters.go new file mode 100644 index 0000000..d308c6a --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/restart_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewRestartInstancesParams creates a new RestartInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewRestartInstancesParams() *RestartInstancesParams { + return &RestartInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewRestartInstancesParamsWithTimeout creates a new RestartInstancesParams object +// with the ability to set a timeout on a request. +func NewRestartInstancesParamsWithTimeout(timeout time.Duration) *RestartInstancesParams { + return &RestartInstancesParams{ + timeout: timeout, + } +} + +// NewRestartInstancesParamsWithContext creates a new RestartInstancesParams object +// with the ability to set a context for a request. +func NewRestartInstancesParamsWithContext(ctx context.Context) *RestartInstancesParams { + return &RestartInstancesParams{ + Context: ctx, + } +} + +// NewRestartInstancesParamsWithHTTPClient creates a new RestartInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewRestartInstancesParamsWithHTTPClient(client *http.Client) *RestartInstancesParams { + return &RestartInstancesParams{ + HTTPClient: client, + } +} + +/* RestartInstancesParams contains all the parameters to send to the API endpoint + for the restart instances operation. + + Typically these are written to a http.Request. +*/ +type RestartInstancesParams struct { + + // Body. + Body *models.RestartInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the restart instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RestartInstancesParams) WithDefaults() *RestartInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the restart instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RestartInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the restart instances params +func (o *RestartInstancesParams) WithTimeout(timeout time.Duration) *RestartInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the restart instances params +func (o *RestartInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the restart instances params +func (o *RestartInstancesParams) WithContext(ctx context.Context) *RestartInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the restart instances params +func (o *RestartInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the restart instances params +func (o *RestartInstancesParams) WithHTTPClient(client *http.Client) *RestartInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the restart instances params +func (o *RestartInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the restart instances params +func (o *RestartInstancesParams) WithBody(body *models.RestartInstancesRequest) *RestartInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the restart instances params +func (o *RestartInstancesParams) SetBody(body *models.RestartInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the restart instances params +func (o *RestartInstancesParams) WithAuthorization(authorization string) *RestartInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the restart instances params +func (o *RestartInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the restart instances params +func (o *RestartInstancesParams) WithBmpLanguage(bmpLanguage *string) *RestartInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the restart instances params +func (o *RestartInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the restart instances params +func (o *RestartInstancesParams) WithBmpUserID(bmpUserID *string) *RestartInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the restart instances params +func (o *RestartInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the restart instances params +func (o *RestartInstancesParams) WithTraceID(traceID string) *RestartInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the restart instances params +func (o *RestartInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *RestartInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/restart_instances_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/restart_instances_responses.go new file mode 100644 index 0000000..674d6a5 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/restart_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// RestartInstancesReader is a Reader for the RestartInstances structure. +type RestartInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *RestartInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewRestartInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewRestartInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewRestartInstancesOK creates a RestartInstancesOK with default headers values +func NewRestartInstancesOK() *RestartInstancesOK { + return &RestartInstancesOK{} +} + +/* RestartInstancesOK describes a response with status code 200, with default header values. + +A RestartInstancesResult is an response struct +*/ +type RestartInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *RestartInstancesOKBody +} + +// IsSuccess returns true when this restart instances o k response has a 2xx status code +func (o *RestartInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this restart instances o k response has a 3xx status code +func (o *RestartInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this restart instances o k response has a 4xx status code +func (o *RestartInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this restart instances o k response has a 5xx status code +func (o *RestartInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this restart instances o k response a status code equal to that given +func (o *RestartInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *RestartInstancesOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:restartInstances][%d] restartInstancesOK %+v", 200, o.Payload) +} + +func (o *RestartInstancesOK) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:restartInstances][%d] restartInstancesOK %+v", 200, o.Payload) +} + +func (o *RestartInstancesOK) GetPayload() *RestartInstancesOKBody { + return o.Payload +} + +func (o *RestartInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RestartInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewRestartInstancesDefault creates a RestartInstancesDefault with default headers values +func NewRestartInstancesDefault(code int) *RestartInstancesDefault { + return &RestartInstancesDefault{ + _statusCode: code, + } +} + +/* RestartInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type RestartInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *RestartInstancesDefaultBody +} + +// Code gets the status code for the restart instances default response +func (o *RestartInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this restart instances default response has a 2xx status code +func (o *RestartInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this restart instances default response has a 3xx status code +func (o *RestartInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this restart instances default response has a 4xx status code +func (o *RestartInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this restart instances default response has a 5xx status code +func (o *RestartInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this restart instances default response a status code equal to that given +func (o *RestartInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *RestartInstancesDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:restartInstances][%d] restartInstances default %+v", o._statusCode, o.Payload) +} + +func (o *RestartInstancesDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:restartInstances][%d] restartInstances default %+v", o._statusCode, o.Payload) +} + +func (o *RestartInstancesDefault) GetPayload() *RestartInstancesDefaultBody { + return o.Payload +} + +func (o *RestartInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RestartInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*RestartInstancesDefaultBody restart instances default body +swagger:model RestartInstancesDefaultBody +*/ +type RestartInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this restart instances default body +func (o *RestartInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("restartInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *RestartInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("restartInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this restart instances default body based on the context it is used +func (o *RestartInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RestartInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RestartInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res RestartInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*RestartInstancesOKBody restart instances o k body +swagger:model RestartInstancesOKBody +*/ +type RestartInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this restart instances o k body +func (o *RestartInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this restart instances o k body based on the context it is used +func (o *RestartInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RestartInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RestartInstancesOKBody) UnmarshalBinary(b []byte) error { + var res RestartInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/restart_project_instance_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/restart_project_instance_parameters.go new file mode 100644 index 0000000..d1b78b2 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/restart_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewRestartProjectInstanceParams creates a new RestartProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewRestartProjectInstanceParams() *RestartProjectInstanceParams { + return &RestartProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewRestartProjectInstanceParamsWithTimeout creates a new RestartProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewRestartProjectInstanceParamsWithTimeout(timeout time.Duration) *RestartProjectInstanceParams { + return &RestartProjectInstanceParams{ + timeout: timeout, + } +} + +// NewRestartProjectInstanceParamsWithContext creates a new RestartProjectInstanceParams object +// with the ability to set a context for a request. +func NewRestartProjectInstanceParamsWithContext(ctx context.Context) *RestartProjectInstanceParams { + return &RestartProjectInstanceParams{ + Context: ctx, + } +} + +// NewRestartProjectInstanceParamsWithHTTPClient creates a new RestartProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewRestartProjectInstanceParamsWithHTTPClient(client *http.Client) *RestartProjectInstanceParams { + return &RestartProjectInstanceParams{ + HTTPClient: client, + } +} + +/* RestartProjectInstanceParams contains all the parameters to send to the API endpoint + for the restart project instance operation. + + Typically these are written to a http.Request. +*/ +type RestartProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the restart project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RestartProjectInstanceParams) WithDefaults() *RestartProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the restart project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *RestartProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the restart project instance params +func (o *RestartProjectInstanceParams) WithTimeout(timeout time.Duration) *RestartProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the restart project instance params +func (o *RestartProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the restart project instance params +func (o *RestartProjectInstanceParams) WithContext(ctx context.Context) *RestartProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the restart project instance params +func (o *RestartProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the restart project instance params +func (o *RestartProjectInstanceParams) WithHTTPClient(client *http.Client) *RestartProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the restart project instance params +func (o *RestartProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the restart project instance params +func (o *RestartProjectInstanceParams) WithAuthorization(authorization string) *RestartProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the restart project instance params +func (o *RestartProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the restart project instance params +func (o *RestartProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *RestartProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the restart project instance params +func (o *RestartProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the restart project instance params +func (o *RestartProjectInstanceParams) WithBmpUserID(bmpUserID *string) *RestartProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the restart project instance params +func (o *RestartProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the restart project instance params +func (o *RestartProjectInstanceParams) WithInstanceID(instanceID string) *RestartProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the restart project instance params +func (o *RestartProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the restart project instance params +func (o *RestartProjectInstanceParams) WithTraceID(traceID string) *RestartProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the restart project instance params +func (o *RestartProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *RestartProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/restart_project_instance_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/restart_project_instance_responses.go new file mode 100644 index 0000000..2a76a9d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/restart_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// RestartProjectInstanceReader is a Reader for the RestartProjectInstance structure. +type RestartProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *RestartProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewRestartProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewRestartProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewRestartProjectInstanceOK creates a RestartProjectInstanceOK with default headers values +func NewRestartProjectInstanceOK() *RestartProjectInstanceOK { + return &RestartProjectInstanceOK{} +} + +/* RestartProjectInstanceOK describes a response with status code 200, with default header values. + +A RestartProjectInstanceResult is an response struct that is used to describe restart instance result. +*/ +type RestartProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *RestartProjectInstanceOKBody +} + +// IsSuccess returns true when this restart project instance o k response has a 2xx status code +func (o *RestartProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this restart project instance o k response has a 3xx status code +func (o *RestartProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this restart project instance o k response has a 4xx status code +func (o *RestartProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this restart project instance o k response has a 5xx status code +func (o *RestartProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this restart project instance o k response a status code equal to that given +func (o *RestartProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *RestartProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/restart][%d] restartProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *RestartProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/restart][%d] restartProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *RestartProjectInstanceOK) GetPayload() *RestartProjectInstanceOKBody { + return o.Payload +} + +func (o *RestartProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RestartProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewRestartProjectInstanceDefault creates a RestartProjectInstanceDefault with default headers values +func NewRestartProjectInstanceDefault(code int) *RestartProjectInstanceDefault { + return &RestartProjectInstanceDefault{ + _statusCode: code, + } +} + +/* RestartProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type RestartProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *RestartProjectInstanceDefaultBody +} + +// Code gets the status code for the restart project instance default response +func (o *RestartProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this restart project instance default response has a 2xx status code +func (o *RestartProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this restart project instance default response has a 3xx status code +func (o *RestartProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this restart project instance default response has a 4xx status code +func (o *RestartProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this restart project instance default response has a 5xx status code +func (o *RestartProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this restart project instance default response a status code equal to that given +func (o *RestartProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *RestartProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/restart][%d] restartProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *RestartProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/restart][%d] restartProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *RestartProjectInstanceDefault) GetPayload() *RestartProjectInstanceDefaultBody { + return o.Payload +} + +func (o *RestartProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(RestartProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*RestartProjectInstanceDefaultBody restart project instance default body +swagger:model RestartProjectInstanceDefaultBody +*/ +type RestartProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this restart project instance default body +func (o *RestartProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("restartProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *RestartProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("restartProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this restart project instance default body based on the context it is used +func (o *RestartProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RestartProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RestartProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res RestartProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*RestartProjectInstanceOKBody restart project instance o k body +swagger:model RestartProjectInstanceOKBody +*/ +type RestartProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this restart project instance o k body +func (o *RestartProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this restart project instance o k body based on the context it is used +func (o *RestartProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *RestartProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("restartProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("restartProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *RestartProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *RestartProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res RestartProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/start_instances_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/start_instances_parameters.go new file mode 100644 index 0000000..a6ff851 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/start_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewStartInstancesParams creates a new StartInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewStartInstancesParams() *StartInstancesParams { + return &StartInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewStartInstancesParamsWithTimeout creates a new StartInstancesParams object +// with the ability to set a timeout on a request. +func NewStartInstancesParamsWithTimeout(timeout time.Duration) *StartInstancesParams { + return &StartInstancesParams{ + timeout: timeout, + } +} + +// NewStartInstancesParamsWithContext creates a new StartInstancesParams object +// with the ability to set a context for a request. +func NewStartInstancesParamsWithContext(ctx context.Context) *StartInstancesParams { + return &StartInstancesParams{ + Context: ctx, + } +} + +// NewStartInstancesParamsWithHTTPClient creates a new StartInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewStartInstancesParamsWithHTTPClient(client *http.Client) *StartInstancesParams { + return &StartInstancesParams{ + HTTPClient: client, + } +} + +/* StartInstancesParams contains all the parameters to send to the API endpoint + for the start instances operation. + + Typically these are written to a http.Request. +*/ +type StartInstancesParams struct { + + // Body. + Body *models.StartInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the start instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StartInstancesParams) WithDefaults() *StartInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the start instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StartInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the start instances params +func (o *StartInstancesParams) WithTimeout(timeout time.Duration) *StartInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the start instances params +func (o *StartInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the start instances params +func (o *StartInstancesParams) WithContext(ctx context.Context) *StartInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the start instances params +func (o *StartInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the start instances params +func (o *StartInstancesParams) WithHTTPClient(client *http.Client) *StartInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the start instances params +func (o *StartInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the start instances params +func (o *StartInstancesParams) WithBody(body *models.StartInstancesRequest) *StartInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the start instances params +func (o *StartInstancesParams) SetBody(body *models.StartInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the start instances params +func (o *StartInstancesParams) WithAuthorization(authorization string) *StartInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the start instances params +func (o *StartInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the start instances params +func (o *StartInstancesParams) WithBmpLanguage(bmpLanguage *string) *StartInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the start instances params +func (o *StartInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the start instances params +func (o *StartInstancesParams) WithBmpUserID(bmpUserID *string) *StartInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the start instances params +func (o *StartInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the start instances params +func (o *StartInstancesParams) WithTraceID(traceID string) *StartInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the start instances params +func (o *StartInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *StartInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/start_instances_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/start_instances_responses.go new file mode 100644 index 0000000..643764c --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/start_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// StartInstancesReader is a Reader for the StartInstances structure. +type StartInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *StartInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewStartInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewStartInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewStartInstancesOK creates a StartInstancesOK with default headers values +func NewStartInstancesOK() *StartInstancesOK { + return &StartInstancesOK{} +} + +/* StartInstancesOK describes a response with status code 200, with default header values. + +A StartInstancesResult is an response struct +*/ +type StartInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *StartInstancesOKBody +} + +// IsSuccess returns true when this start instances o k response has a 2xx status code +func (o *StartInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this start instances o k response has a 3xx status code +func (o *StartInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this start instances o k response has a 4xx status code +func (o *StartInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this start instances o k response has a 5xx status code +func (o *StartInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this start instances o k response a status code equal to that given +func (o *StartInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *StartInstancesOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:startInstances][%d] startInstancesOK %+v", 200, o.Payload) +} + +func (o *StartInstancesOK) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:startInstances][%d] startInstancesOK %+v", 200, o.Payload) +} + +func (o *StartInstancesOK) GetPayload() *StartInstancesOKBody { + return o.Payload +} + +func (o *StartInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StartInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewStartInstancesDefault creates a StartInstancesDefault with default headers values +func NewStartInstancesDefault(code int) *StartInstancesDefault { + return &StartInstancesDefault{ + _statusCode: code, + } +} + +/* StartInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type StartInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *StartInstancesDefaultBody +} + +// Code gets the status code for the start instances default response +func (o *StartInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this start instances default response has a 2xx status code +func (o *StartInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this start instances default response has a 3xx status code +func (o *StartInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this start instances default response has a 4xx status code +func (o *StartInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this start instances default response has a 5xx status code +func (o *StartInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this start instances default response a status code equal to that given +func (o *StartInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *StartInstancesDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:startInstances][%d] startInstances default %+v", o._statusCode, o.Payload) +} + +func (o *StartInstancesDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:startInstances][%d] startInstances default %+v", o._statusCode, o.Payload) +} + +func (o *StartInstancesDefault) GetPayload() *StartInstancesDefaultBody { + return o.Payload +} + +func (o *StartInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StartInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*StartInstancesDefaultBody start instances default body +swagger:model StartInstancesDefaultBody +*/ +type StartInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this start instances default body +func (o *StartInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("startInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *StartInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("startInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this start instances default body based on the context it is used +func (o *StartInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StartInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StartInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res StartInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*StartInstancesOKBody start instances o k body +swagger:model StartInstancesOKBody +*/ +type StartInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this start instances o k body +func (o *StartInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this start instances o k body based on the context it is used +func (o *StartInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StartInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StartInstancesOKBody) UnmarshalBinary(b []byte) error { + var res StartInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/start_project_instance_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/start_project_instance_parameters.go new file mode 100644 index 0000000..9014aa5 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/start_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewStartProjectInstanceParams creates a new StartProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewStartProjectInstanceParams() *StartProjectInstanceParams { + return &StartProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewStartProjectInstanceParamsWithTimeout creates a new StartProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewStartProjectInstanceParamsWithTimeout(timeout time.Duration) *StartProjectInstanceParams { + return &StartProjectInstanceParams{ + timeout: timeout, + } +} + +// NewStartProjectInstanceParamsWithContext creates a new StartProjectInstanceParams object +// with the ability to set a context for a request. +func NewStartProjectInstanceParamsWithContext(ctx context.Context) *StartProjectInstanceParams { + return &StartProjectInstanceParams{ + Context: ctx, + } +} + +// NewStartProjectInstanceParamsWithHTTPClient creates a new StartProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewStartProjectInstanceParamsWithHTTPClient(client *http.Client) *StartProjectInstanceParams { + return &StartProjectInstanceParams{ + HTTPClient: client, + } +} + +/* StartProjectInstanceParams contains all the parameters to send to the API endpoint + for the start project instance operation. + + Typically these are written to a http.Request. +*/ +type StartProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the start project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StartProjectInstanceParams) WithDefaults() *StartProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the start project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StartProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the start project instance params +func (o *StartProjectInstanceParams) WithTimeout(timeout time.Duration) *StartProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the start project instance params +func (o *StartProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the start project instance params +func (o *StartProjectInstanceParams) WithContext(ctx context.Context) *StartProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the start project instance params +func (o *StartProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the start project instance params +func (o *StartProjectInstanceParams) WithHTTPClient(client *http.Client) *StartProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the start project instance params +func (o *StartProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the start project instance params +func (o *StartProjectInstanceParams) WithAuthorization(authorization string) *StartProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the start project instance params +func (o *StartProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the start project instance params +func (o *StartProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *StartProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the start project instance params +func (o *StartProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the start project instance params +func (o *StartProjectInstanceParams) WithBmpUserID(bmpUserID *string) *StartProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the start project instance params +func (o *StartProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the start project instance params +func (o *StartProjectInstanceParams) WithInstanceID(instanceID string) *StartProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the start project instance params +func (o *StartProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the start project instance params +func (o *StartProjectInstanceParams) WithTraceID(traceID string) *StartProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the start project instance params +func (o *StartProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *StartProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/start_project_instance_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/start_project_instance_responses.go new file mode 100644 index 0000000..5d6f102 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/start_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// StartProjectInstanceReader is a Reader for the StartProjectInstance structure. +type StartProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *StartProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewStartProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewStartProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewStartProjectInstanceOK creates a StartProjectInstanceOK with default headers values +func NewStartProjectInstanceOK() *StartProjectInstanceOK { + return &StartProjectInstanceOK{} +} + +/* StartProjectInstanceOK describes a response with status code 200, with default header values. + +A StartProjectInstanceResult is an response struct that is used to describe start instance result. +*/ +type StartProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *StartProjectInstanceOKBody +} + +// IsSuccess returns true when this start project instance o k response has a 2xx status code +func (o *StartProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this start project instance o k response has a 3xx status code +func (o *StartProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this start project instance o k response has a 4xx status code +func (o *StartProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this start project instance o k response has a 5xx status code +func (o *StartProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this start project instance o k response a status code equal to that given +func (o *StartProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *StartProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/start][%d] startProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *StartProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/start][%d] startProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *StartProjectInstanceOK) GetPayload() *StartProjectInstanceOKBody { + return o.Payload +} + +func (o *StartProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StartProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewStartProjectInstanceDefault creates a StartProjectInstanceDefault with default headers values +func NewStartProjectInstanceDefault(code int) *StartProjectInstanceDefault { + return &StartProjectInstanceDefault{ + _statusCode: code, + } +} + +/* StartProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type StartProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *StartProjectInstanceDefaultBody +} + +// Code gets the status code for the start project instance default response +func (o *StartProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this start project instance default response has a 2xx status code +func (o *StartProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this start project instance default response has a 3xx status code +func (o *StartProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this start project instance default response has a 4xx status code +func (o *StartProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this start project instance default response has a 5xx status code +func (o *StartProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this start project instance default response a status code equal to that given +func (o *StartProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *StartProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/start][%d] startProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *StartProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/start][%d] startProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *StartProjectInstanceDefault) GetPayload() *StartProjectInstanceDefaultBody { + return o.Payload +} + +func (o *StartProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StartProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*StartProjectInstanceDefaultBody start project instance default body +swagger:model StartProjectInstanceDefaultBody +*/ +type StartProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this start project instance default body +func (o *StartProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("startProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *StartProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("startProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this start project instance default body based on the context it is used +func (o *StartProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StartProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StartProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res StartProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*StartProjectInstanceOKBody start project instance o k body +swagger:model StartProjectInstanceOKBody +*/ +type StartProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this start project instance o k body +func (o *StartProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this start project instance o k body based on the context it is used +func (o *StartProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StartProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("startProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("startProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StartProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StartProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res StartProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/stop_instances_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/stop_instances_parameters.go new file mode 100644 index 0000000..c76e3d5 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/stop_instances_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewStopInstancesParams creates a new StopInstancesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewStopInstancesParams() *StopInstancesParams { + return &StopInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewStopInstancesParamsWithTimeout creates a new StopInstancesParams object +// with the ability to set a timeout on a request. +func NewStopInstancesParamsWithTimeout(timeout time.Duration) *StopInstancesParams { + return &StopInstancesParams{ + timeout: timeout, + } +} + +// NewStopInstancesParamsWithContext creates a new StopInstancesParams object +// with the ability to set a context for a request. +func NewStopInstancesParamsWithContext(ctx context.Context) *StopInstancesParams { + return &StopInstancesParams{ + Context: ctx, + } +} + +// NewStopInstancesParamsWithHTTPClient creates a new StopInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewStopInstancesParamsWithHTTPClient(client *http.Client) *StopInstancesParams { + return &StopInstancesParams{ + HTTPClient: client, + } +} + +/* StopInstancesParams contains all the parameters to send to the API endpoint + for the stop instances operation. + + Typically these are written to a http.Request. +*/ +type StopInstancesParams struct { + + // Body. + Body *models.StopInstancesRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the stop instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StopInstancesParams) WithDefaults() *StopInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the stop instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StopInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the stop instances params +func (o *StopInstancesParams) WithTimeout(timeout time.Duration) *StopInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the stop instances params +func (o *StopInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the stop instances params +func (o *StopInstancesParams) WithContext(ctx context.Context) *StopInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the stop instances params +func (o *StopInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the stop instances params +func (o *StopInstancesParams) WithHTTPClient(client *http.Client) *StopInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the stop instances params +func (o *StopInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the stop instances params +func (o *StopInstancesParams) WithBody(body *models.StopInstancesRequest) *StopInstancesParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the stop instances params +func (o *StopInstancesParams) SetBody(body *models.StopInstancesRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the stop instances params +func (o *StopInstancesParams) WithAuthorization(authorization string) *StopInstancesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the stop instances params +func (o *StopInstancesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the stop instances params +func (o *StopInstancesParams) WithBmpLanguage(bmpLanguage *string) *StopInstancesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the stop instances params +func (o *StopInstancesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the stop instances params +func (o *StopInstancesParams) WithBmpUserID(bmpUserID *string) *StopInstancesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the stop instances params +func (o *StopInstancesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the stop instances params +func (o *StopInstancesParams) WithTraceID(traceID string) *StopInstancesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the stop instances params +func (o *StopInstancesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *StopInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/stop_instances_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/stop_instances_responses.go new file mode 100644 index 0000000..d9bee91 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/stop_instances_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// StopInstancesReader is a Reader for the StopInstances structure. +type StopInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *StopInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewStopInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewStopInstancesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewStopInstancesOK creates a StopInstancesOK with default headers values +func NewStopInstancesOK() *StopInstancesOK { + return &StopInstancesOK{} +} + +/* StopInstancesOK describes a response with status code 200, with default header values. + +A StopInstancesResult is an response struct +*/ +type StopInstancesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *StopInstancesOKBody +} + +// IsSuccess returns true when this stop instances o k response has a 2xx status code +func (o *StopInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this stop instances o k response has a 3xx status code +func (o *StopInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this stop instances o k response has a 4xx status code +func (o *StopInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this stop instances o k response has a 5xx status code +func (o *StopInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this stop instances o k response a status code equal to that given +func (o *StopInstancesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *StopInstancesOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:stopInstances][%d] stopInstancesOK %+v", 200, o.Payload) +} + +func (o *StopInstancesOK) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:stopInstances][%d] stopInstancesOK %+v", 200, o.Payload) +} + +func (o *StopInstancesOK) GetPayload() *StopInstancesOKBody { + return o.Payload +} + +func (o *StopInstancesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StopInstancesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewStopInstancesDefault creates a StopInstancesDefault with default headers values +func NewStopInstancesDefault(code int) *StopInstancesDefault { + return &StopInstancesDefault{ + _statusCode: code, + } +} + +/* StopInstancesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type StopInstancesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *StopInstancesDefaultBody +} + +// Code gets the status code for the stop instances default response +func (o *StopInstancesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this stop instances default response has a 2xx status code +func (o *StopInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this stop instances default response has a 3xx status code +func (o *StopInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this stop instances default response has a 4xx status code +func (o *StopInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this stop instances default response has a 5xx status code +func (o *StopInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this stop instances default response a status code equal to that given +func (o *StopInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *StopInstancesDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:stopInstances][%d] stopInstances default %+v", o._statusCode, o.Payload) +} + +func (o *StopInstancesDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/batch/instances:stopInstances][%d] stopInstances default %+v", o._statusCode, o.Payload) +} + +func (o *StopInstancesDefault) GetPayload() *StopInstancesDefaultBody { + return o.Payload +} + +func (o *StopInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StopInstancesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*StopInstancesDefaultBody stop instances default body +swagger:model StopInstancesDefaultBody +*/ +type StopInstancesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this stop instances default body +func (o *StopInstancesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopInstancesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("stopInstances default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *StopInstancesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("stopInstances default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this stop instances default body based on the context it is used +func (o *StopInstancesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopInstancesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopInstances default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopInstances default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StopInstancesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StopInstancesDefaultBody) UnmarshalBinary(b []byte) error { + var res StopInstancesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*StopInstancesOKBody stop instances o k body +swagger:model StopInstancesOKBody +*/ +type StopInstancesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this stop instances o k body +func (o *StopInstancesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopInstancesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this stop instances o k body based on the context it is used +func (o *StopInstancesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopInstancesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopInstancesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopInstancesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StopInstancesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StopInstancesOKBody) UnmarshalBinary(b []byte) error { + var res StopInstancesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/stop_project_instance_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/stop_project_instance_parameters.go new file mode 100644 index 0000000..f9a48c8 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/stop_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewStopProjectInstanceParams creates a new StopProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewStopProjectInstanceParams() *StopProjectInstanceParams { + return &StopProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewStopProjectInstanceParamsWithTimeout creates a new StopProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewStopProjectInstanceParamsWithTimeout(timeout time.Duration) *StopProjectInstanceParams { + return &StopProjectInstanceParams{ + timeout: timeout, + } +} + +// NewStopProjectInstanceParamsWithContext creates a new StopProjectInstanceParams object +// with the ability to set a context for a request. +func NewStopProjectInstanceParamsWithContext(ctx context.Context) *StopProjectInstanceParams { + return &StopProjectInstanceParams{ + Context: ctx, + } +} + +// NewStopProjectInstanceParamsWithHTTPClient creates a new StopProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewStopProjectInstanceParamsWithHTTPClient(client *http.Client) *StopProjectInstanceParams { + return &StopProjectInstanceParams{ + HTTPClient: client, + } +} + +/* StopProjectInstanceParams contains all the parameters to send to the API endpoint + for the stop project instance operation. + + Typically these are written to a http.Request. +*/ +type StopProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the stop project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StopProjectInstanceParams) WithDefaults() *StopProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the stop project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *StopProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the stop project instance params +func (o *StopProjectInstanceParams) WithTimeout(timeout time.Duration) *StopProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the stop project instance params +func (o *StopProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the stop project instance params +func (o *StopProjectInstanceParams) WithContext(ctx context.Context) *StopProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the stop project instance params +func (o *StopProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the stop project instance params +func (o *StopProjectInstanceParams) WithHTTPClient(client *http.Client) *StopProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the stop project instance params +func (o *StopProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the stop project instance params +func (o *StopProjectInstanceParams) WithAuthorization(authorization string) *StopProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the stop project instance params +func (o *StopProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the stop project instance params +func (o *StopProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *StopProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the stop project instance params +func (o *StopProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the stop project instance params +func (o *StopProjectInstanceParams) WithBmpUserID(bmpUserID *string) *StopProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the stop project instance params +func (o *StopProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the stop project instance params +func (o *StopProjectInstanceParams) WithInstanceID(instanceID string) *StopProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the stop project instance params +func (o *StopProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the stop project instance params +func (o *StopProjectInstanceParams) WithTraceID(traceID string) *StopProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the stop project instance params +func (o *StopProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *StopProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/stop_project_instance_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/stop_project_instance_responses.go new file mode 100644 index 0000000..245abb7 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/stop_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// StopProjectInstanceReader is a Reader for the StopProjectInstance structure. +type StopProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *StopProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewStopProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewStopProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewStopProjectInstanceOK creates a StopProjectInstanceOK with default headers values +func NewStopProjectInstanceOK() *StopProjectInstanceOK { + return &StopProjectInstanceOK{} +} + +/* StopProjectInstanceOK describes a response with status code 200, with default header values. + +A StopProjectInstanceResult is an response struct that is used to describe stop instance result. +*/ +type StopProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *StopProjectInstanceOKBody +} + +// IsSuccess returns true when this stop project instance o k response has a 2xx status code +func (o *StopProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this stop project instance o k response has a 3xx status code +func (o *StopProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this stop project instance o k response has a 4xx status code +func (o *StopProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this stop project instance o k response has a 5xx status code +func (o *StopProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this stop project instance o k response a status code equal to that given +func (o *StopProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *StopProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/stop][%d] stopProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *StopProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/stop][%d] stopProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *StopProjectInstanceOK) GetPayload() *StopProjectInstanceOKBody { + return o.Payload +} + +func (o *StopProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StopProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewStopProjectInstanceDefault creates a StopProjectInstanceDefault with default headers values +func NewStopProjectInstanceDefault(code int) *StopProjectInstanceDefault { + return &StopProjectInstanceDefault{ + _statusCode: code, + } +} + +/* StopProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type StopProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *StopProjectInstanceDefaultBody +} + +// Code gets the status code for the stop project instance default response +func (o *StopProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this stop project instance default response has a 2xx status code +func (o *StopProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this stop project instance default response has a 3xx status code +func (o *StopProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this stop project instance default response has a 4xx status code +func (o *StopProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this stop project instance default response has a 5xx status code +func (o *StopProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this stop project instance default response a status code equal to that given +func (o *StopProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *StopProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/stop][%d] stopProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *StopProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/stop][%d] stopProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *StopProjectInstanceDefault) GetPayload() *StopProjectInstanceDefaultBody { + return o.Payload +} + +func (o *StopProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(StopProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*StopProjectInstanceDefaultBody stop project instance default body +swagger:model StopProjectInstanceDefaultBody +*/ +type StopProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this stop project instance default body +func (o *StopProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("stopProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *StopProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("stopProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this stop project instance default body based on the context it is used +func (o *StopProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StopProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StopProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res StopProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*StopProjectInstanceOKBody stop project instance o k body +swagger:model StopProjectInstanceOKBody +*/ +type StopProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this stop project instance o k body +func (o *StopProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this stop project instance o k body based on the context it is used +func (o *StopProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *StopProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("stopProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("stopProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *StopProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *StopProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res StopProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/un_lock_project_instance_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/un_lock_project_instance_parameters.go new file mode 100644 index 0000000..c23507f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/un_lock_project_instance_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewUnLockProjectInstanceParams creates a new UnLockProjectInstanceParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewUnLockProjectInstanceParams() *UnLockProjectInstanceParams { + return &UnLockProjectInstanceParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUnLockProjectInstanceParamsWithTimeout creates a new UnLockProjectInstanceParams object +// with the ability to set a timeout on a request. +func NewUnLockProjectInstanceParamsWithTimeout(timeout time.Duration) *UnLockProjectInstanceParams { + return &UnLockProjectInstanceParams{ + timeout: timeout, + } +} + +// NewUnLockProjectInstanceParamsWithContext creates a new UnLockProjectInstanceParams object +// with the ability to set a context for a request. +func NewUnLockProjectInstanceParamsWithContext(ctx context.Context) *UnLockProjectInstanceParams { + return &UnLockProjectInstanceParams{ + Context: ctx, + } +} + +// NewUnLockProjectInstanceParamsWithHTTPClient creates a new UnLockProjectInstanceParams object +// with the ability to set a custom HTTPClient for a request. +func NewUnLockProjectInstanceParamsWithHTTPClient(client *http.Client) *UnLockProjectInstanceParams { + return &UnLockProjectInstanceParams{ + HTTPClient: client, + } +} + +/* UnLockProjectInstanceParams contains all the parameters to send to the API endpoint + for the un lock project instance operation. + + Typically these are written to a http.Request. +*/ +type UnLockProjectInstanceParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // InstanceID. + InstanceID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the un lock project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UnLockProjectInstanceParams) WithDefaults() *UnLockProjectInstanceParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the un lock project instance params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UnLockProjectInstanceParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithTimeout(timeout time.Duration) *UnLockProjectInstanceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithContext(ctx context.Context) *UnLockProjectInstanceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithHTTPClient(client *http.Client) *UnLockProjectInstanceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithAuthorization(authorization string) *UnLockProjectInstanceParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithBmpLanguage(bmpLanguage *string) *UnLockProjectInstanceParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithBmpUserID(bmpUserID *string) *UnLockProjectInstanceParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithInstanceID adds the instanceID to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithInstanceID(instanceID string) *UnLockProjectInstanceParams { + o.SetInstanceID(instanceID) + return o +} + +// SetInstanceID adds the instanceId to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetInstanceID(instanceID string) { + o.InstanceID = instanceID +} + +// WithTraceID adds the traceID to the un lock project instance params +func (o *UnLockProjectInstanceParams) WithTraceID(traceID string) *UnLockProjectInstanceParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the un lock project instance params +func (o *UnLockProjectInstanceParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *UnLockProjectInstanceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param instance_id + if err := r.SetPathParam("instance_id", o.InstanceID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/un_lock_project_instance_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/un_lock_project_instance_responses.go new file mode 100644 index 0000000..1c615e7 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/instance/un_lock_project_instance_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instance + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// UnLockProjectInstanceReader is a Reader for the UnLockProjectInstance structure. +type UnLockProjectInstanceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UnLockProjectInstanceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUnLockProjectInstanceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewUnLockProjectInstanceDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewUnLockProjectInstanceOK creates a UnLockProjectInstanceOK with default headers values +func NewUnLockProjectInstanceOK() *UnLockProjectInstanceOK { + return &UnLockProjectInstanceOK{} +} + +/* UnLockProjectInstanceOK describes a response with status code 200, with default header values. + +A UnLockProjectInstanceResult is an response struct that is used to describe unlock instance result. +*/ +type UnLockProjectInstanceOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *UnLockProjectInstanceOKBody +} + +// IsSuccess returns true when this un lock project instance o k response has a 2xx status code +func (o *UnLockProjectInstanceOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this un lock project instance o k response has a 3xx status code +func (o *UnLockProjectInstanceOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this un lock project instance o k response has a 4xx status code +func (o *UnLockProjectInstanceOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this un lock project instance o k response has a 5xx status code +func (o *UnLockProjectInstanceOK) IsServerError() bool { + return false +} + +// IsCode returns true when this un lock project instance o k response a status code equal to that given +func (o *UnLockProjectInstanceOK) IsCode(code int) bool { + return code == 200 +} + +func (o *UnLockProjectInstanceOK) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/unlock][%d] unLockProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *UnLockProjectInstanceOK) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/unlock][%d] unLockProjectInstanceOK %+v", 200, o.Payload) +} + +func (o *UnLockProjectInstanceOK) GetPayload() *UnLockProjectInstanceOKBody { + return o.Payload +} + +func (o *UnLockProjectInstanceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(UnLockProjectInstanceOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUnLockProjectInstanceDefault creates a UnLockProjectInstanceDefault with default headers values +func NewUnLockProjectInstanceDefault(code int) *UnLockProjectInstanceDefault { + return &UnLockProjectInstanceDefault{ + _statusCode: code, + } +} + +/* UnLockProjectInstanceDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type UnLockProjectInstanceDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *UnLockProjectInstanceDefaultBody +} + +// Code gets the status code for the un lock project instance default response +func (o *UnLockProjectInstanceDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this un lock project instance default response has a 2xx status code +func (o *UnLockProjectInstanceDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this un lock project instance default response has a 3xx status code +func (o *UnLockProjectInstanceDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this un lock project instance default response has a 4xx status code +func (o *UnLockProjectInstanceDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this un lock project instance default response has a 5xx status code +func (o *UnLockProjectInstanceDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this un lock project instance default response a status code equal to that given +func (o *UnLockProjectInstanceDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *UnLockProjectInstanceDefault) Error() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/unlock][%d] unLockProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *UnLockProjectInstanceDefault) String() string { + return fmt.Sprintf("[PUT /project/instances/{instance_id}/unlock][%d] unLockProjectInstance default %+v", o._statusCode, o.Payload) +} + +func (o *UnLockProjectInstanceDefault) GetPayload() *UnLockProjectInstanceDefaultBody { + return o.Payload +} + +func (o *UnLockProjectInstanceDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(UnLockProjectInstanceDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*UnLockProjectInstanceDefaultBody un lock project instance default body +swagger:model UnLockProjectInstanceDefaultBody +*/ +type UnLockProjectInstanceDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this un lock project instance default body +func (o *UnLockProjectInstanceDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnLockProjectInstanceDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("unLockProjectInstance default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *UnLockProjectInstanceDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("unLockProjectInstance default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unLockProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unLockProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this un lock project instance default body based on the context it is used +func (o *UnLockProjectInstanceDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnLockProjectInstanceDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unLockProjectInstance default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unLockProjectInstance default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *UnLockProjectInstanceDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *UnLockProjectInstanceDefaultBody) UnmarshalBinary(b []byte) error { + var res UnLockProjectInstanceDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*UnLockProjectInstanceOKBody un lock project instance o k body +swagger:model UnLockProjectInstanceOKBody +*/ +type UnLockProjectInstanceOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this un lock project instance o k body +func (o *UnLockProjectInstanceOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnLockProjectInstanceOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unLockProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unLockProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this un lock project instance o k body based on the context it is used +func (o *UnLockProjectInstanceOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UnLockProjectInstanceOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("unLockProjectInstanceOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("unLockProjectInstanceOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *UnLockProjectInstanceOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *UnLockProjectInstanceOKBody) UnmarshalBinary(b []byte) error { + var res UnLockProjectInstanceOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_content_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_content_parameters.go new file mode 100644 index 0000000..aa6caae --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_content_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeLicenseContentParams creates a new DescribeLicenseContentParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeLicenseContentParams() *DescribeLicenseContentParams { + return &DescribeLicenseContentParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeLicenseContentParamsWithTimeout creates a new DescribeLicenseContentParams object +// with the ability to set a timeout on a request. +func NewDescribeLicenseContentParamsWithTimeout(timeout time.Duration) *DescribeLicenseContentParams { + return &DescribeLicenseContentParams{ + timeout: timeout, + } +} + +// NewDescribeLicenseContentParamsWithContext creates a new DescribeLicenseContentParams object +// with the ability to set a context for a request. +func NewDescribeLicenseContentParamsWithContext(ctx context.Context) *DescribeLicenseContentParams { + return &DescribeLicenseContentParams{ + Context: ctx, + } +} + +// NewDescribeLicenseContentParamsWithHTTPClient creates a new DescribeLicenseContentParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeLicenseContentParamsWithHTTPClient(client *http.Client) *DescribeLicenseContentParams { + return &DescribeLicenseContentParams{ + HTTPClient: client, + } +} + +/* DescribeLicenseContentParams contains all the parameters to send to the API endpoint + for the describe license content operation. + + Typically these are written to a http.Request. +*/ +type DescribeLicenseContentParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe license content params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLicenseContentParams) WithDefaults() *DescribeLicenseContentParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe license content params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLicenseContentParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe license content params +func (o *DescribeLicenseContentParams) WithTimeout(timeout time.Duration) *DescribeLicenseContentParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe license content params +func (o *DescribeLicenseContentParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe license content params +func (o *DescribeLicenseContentParams) WithContext(ctx context.Context) *DescribeLicenseContentParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe license content params +func (o *DescribeLicenseContentParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe license content params +func (o *DescribeLicenseContentParams) WithHTTPClient(client *http.Client) *DescribeLicenseContentParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe license content params +func (o *DescribeLicenseContentParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe license content params +func (o *DescribeLicenseContentParams) WithAuthorization(authorization string) *DescribeLicenseContentParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe license content params +func (o *DescribeLicenseContentParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe license content params +func (o *DescribeLicenseContentParams) WithBmpLanguage(bmpLanguage *string) *DescribeLicenseContentParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe license content params +func (o *DescribeLicenseContentParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe license content params +func (o *DescribeLicenseContentParams) WithBmpUserID(bmpUserID *string) *DescribeLicenseContentParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe license content params +func (o *DescribeLicenseContentParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe license content params +func (o *DescribeLicenseContentParams) WithTraceID(traceID string) *DescribeLicenseContentParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe license content params +func (o *DescribeLicenseContentParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeLicenseContentParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_content_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_content_responses.go new file mode 100644 index 0000000..eaa8bea --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_content_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeLicenseContentReader is a Reader for the DescribeLicenseContent structure. +type DescribeLicenseContentReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeLicenseContentReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeLicenseContentOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeLicenseContentDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeLicenseContentOK creates a DescribeLicenseContentOK with default headers values +func NewDescribeLicenseContentOK() *DescribeLicenseContentOK { + return &DescribeLicenseContentOK{} +} + +/* DescribeLicenseContentOK describes a response with status code 200, with default header values. + +A DescribeLicenseContentResult is an response struct that is used to describe getuser. +*/ +type DescribeLicenseContentOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLicenseContentOKBody +} + +// IsSuccess returns true when this describe license content o k response has a 2xx status code +func (o *DescribeLicenseContentOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe license content o k response has a 3xx status code +func (o *DescribeLicenseContentOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe license content o k response has a 4xx status code +func (o *DescribeLicenseContentOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe license content o k response has a 5xx status code +func (o *DescribeLicenseContentOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe license content o k response a status code equal to that given +func (o *DescribeLicenseContentOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeLicenseContentOK) Error() string { + return fmt.Sprintf("[GET /license/content][%d] describeLicenseContentOK %+v", 200, o.Payload) +} + +func (o *DescribeLicenseContentOK) String() string { + return fmt.Sprintf("[GET /license/content][%d] describeLicenseContentOK %+v", 200, o.Payload) +} + +func (o *DescribeLicenseContentOK) GetPayload() *DescribeLicenseContentOKBody { + return o.Payload +} + +func (o *DescribeLicenseContentOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLicenseContentOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeLicenseContentDefault creates a DescribeLicenseContentDefault with default headers values +func NewDescribeLicenseContentDefault(code int) *DescribeLicenseContentDefault { + return &DescribeLicenseContentDefault{ + _statusCode: code, + } +} + +/* DescribeLicenseContentDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeLicenseContentDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLicenseContentDefaultBody +} + +// Code gets the status code for the describe license content default response +func (o *DescribeLicenseContentDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe license content default response has a 2xx status code +func (o *DescribeLicenseContentDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe license content default response has a 3xx status code +func (o *DescribeLicenseContentDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe license content default response has a 4xx status code +func (o *DescribeLicenseContentDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe license content default response has a 5xx status code +func (o *DescribeLicenseContentDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe license content default response a status code equal to that given +func (o *DescribeLicenseContentDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeLicenseContentDefault) Error() string { + return fmt.Sprintf("[GET /license/content][%d] describeLicenseContent default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLicenseContentDefault) String() string { + return fmt.Sprintf("[GET /license/content][%d] describeLicenseContent default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLicenseContentDefault) GetPayload() *DescribeLicenseContentDefaultBody { + return o.Payload +} + +func (o *DescribeLicenseContentDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLicenseContentDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeLicenseContentDefaultBody describe license content default body +swagger:model DescribeLicenseContentDefaultBody +*/ +type DescribeLicenseContentDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe license content default body +func (o *DescribeLicenseContentDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseContentDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeLicenseContent default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeLicenseContentDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeLicenseContent default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseContent default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseContent default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe license content default body based on the context it is used +func (o *DescribeLicenseContentDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseContentDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseContent default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseContent default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLicenseContentDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLicenseContentDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeLicenseContentDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeLicenseContentOKBody describe license content o k body +swagger:model DescribeLicenseContentOKBody +*/ +type DescribeLicenseContentOKBody struct { + + // result + Result *models.LicenseContent `json:"result,omitempty"` +} + +// Validate validates this describe license content o k body +func (o *DescribeLicenseContentOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseContentOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseContentOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseContentOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe license content o k body based on the context it is used +func (o *DescribeLicenseContentOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseContentOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseContentOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseContentOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLicenseContentOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLicenseContentOKBody) UnmarshalBinary(b []byte) error { + var res DescribeLicenseContentOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_token_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_token_parameters.go new file mode 100644 index 0000000..36295cf --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_token_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeLicenseTokenParams creates a new DescribeLicenseTokenParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeLicenseTokenParams() *DescribeLicenseTokenParams { + return &DescribeLicenseTokenParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeLicenseTokenParamsWithTimeout creates a new DescribeLicenseTokenParams object +// with the ability to set a timeout on a request. +func NewDescribeLicenseTokenParamsWithTimeout(timeout time.Duration) *DescribeLicenseTokenParams { + return &DescribeLicenseTokenParams{ + timeout: timeout, + } +} + +// NewDescribeLicenseTokenParamsWithContext creates a new DescribeLicenseTokenParams object +// with the ability to set a context for a request. +func NewDescribeLicenseTokenParamsWithContext(ctx context.Context) *DescribeLicenseTokenParams { + return &DescribeLicenseTokenParams{ + Context: ctx, + } +} + +// NewDescribeLicenseTokenParamsWithHTTPClient creates a new DescribeLicenseTokenParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeLicenseTokenParamsWithHTTPClient(client *http.Client) *DescribeLicenseTokenParams { + return &DescribeLicenseTokenParams{ + HTTPClient: client, + } +} + +/* DescribeLicenseTokenParams contains all the parameters to send to the API endpoint + for the describe license token operation. + + Typically these are written to a http.Request. +*/ +type DescribeLicenseTokenParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe license token params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLicenseTokenParams) WithDefaults() *DescribeLicenseTokenParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe license token params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLicenseTokenParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe license token params +func (o *DescribeLicenseTokenParams) WithTimeout(timeout time.Duration) *DescribeLicenseTokenParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe license token params +func (o *DescribeLicenseTokenParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe license token params +func (o *DescribeLicenseTokenParams) WithContext(ctx context.Context) *DescribeLicenseTokenParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe license token params +func (o *DescribeLicenseTokenParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe license token params +func (o *DescribeLicenseTokenParams) WithHTTPClient(client *http.Client) *DescribeLicenseTokenParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe license token params +func (o *DescribeLicenseTokenParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe license token params +func (o *DescribeLicenseTokenParams) WithAuthorization(authorization string) *DescribeLicenseTokenParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe license token params +func (o *DescribeLicenseTokenParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe license token params +func (o *DescribeLicenseTokenParams) WithBmpLanguage(bmpLanguage *string) *DescribeLicenseTokenParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe license token params +func (o *DescribeLicenseTokenParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe license token params +func (o *DescribeLicenseTokenParams) WithBmpUserID(bmpUserID *string) *DescribeLicenseTokenParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe license token params +func (o *DescribeLicenseTokenParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe license token params +func (o *DescribeLicenseTokenParams) WithTraceID(traceID string) *DescribeLicenseTokenParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe license token params +func (o *DescribeLicenseTokenParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeLicenseTokenParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_token_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_token_responses.go new file mode 100644 index 0000000..f840018 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/describe_license_token_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeLicenseTokenReader is a Reader for the DescribeLicenseToken structure. +type DescribeLicenseTokenReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeLicenseTokenReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeLicenseTokenOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeLicenseTokenDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeLicenseTokenOK creates a DescribeLicenseTokenOK with default headers values +func NewDescribeLicenseTokenOK() *DescribeLicenseTokenOK { + return &DescribeLicenseTokenOK{} +} + +/* DescribeLicenseTokenOK describes a response with status code 200, with default header values. + +A DescribeLocalUserResult is an response struct that is used to describe getuser. +*/ +type DescribeLicenseTokenOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLicenseTokenOKBody +} + +// IsSuccess returns true when this describe license token o k response has a 2xx status code +func (o *DescribeLicenseTokenOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe license token o k response has a 3xx status code +func (o *DescribeLicenseTokenOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe license token o k response has a 4xx status code +func (o *DescribeLicenseTokenOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe license token o k response has a 5xx status code +func (o *DescribeLicenseTokenOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe license token o k response a status code equal to that given +func (o *DescribeLicenseTokenOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeLicenseTokenOK) Error() string { + return fmt.Sprintf("[GET /license/requestToken][%d] describeLicenseTokenOK %+v", 200, o.Payload) +} + +func (o *DescribeLicenseTokenOK) String() string { + return fmt.Sprintf("[GET /license/requestToken][%d] describeLicenseTokenOK %+v", 200, o.Payload) +} + +func (o *DescribeLicenseTokenOK) GetPayload() *DescribeLicenseTokenOKBody { + return o.Payload +} + +func (o *DescribeLicenseTokenOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLicenseTokenOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeLicenseTokenDefault creates a DescribeLicenseTokenDefault with default headers values +func NewDescribeLicenseTokenDefault(code int) *DescribeLicenseTokenDefault { + return &DescribeLicenseTokenDefault{ + _statusCode: code, + } +} + +/* DescribeLicenseTokenDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeLicenseTokenDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLicenseTokenDefaultBody +} + +// Code gets the status code for the describe license token default response +func (o *DescribeLicenseTokenDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe license token default response has a 2xx status code +func (o *DescribeLicenseTokenDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe license token default response has a 3xx status code +func (o *DescribeLicenseTokenDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe license token default response has a 4xx status code +func (o *DescribeLicenseTokenDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe license token default response has a 5xx status code +func (o *DescribeLicenseTokenDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe license token default response a status code equal to that given +func (o *DescribeLicenseTokenDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeLicenseTokenDefault) Error() string { + return fmt.Sprintf("[GET /license/requestToken][%d] describeLicenseToken default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLicenseTokenDefault) String() string { + return fmt.Sprintf("[GET /license/requestToken][%d] describeLicenseToken default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLicenseTokenDefault) GetPayload() *DescribeLicenseTokenDefaultBody { + return o.Payload +} + +func (o *DescribeLicenseTokenDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLicenseTokenDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeLicenseTokenDefaultBody describe license token default body +swagger:model DescribeLicenseTokenDefaultBody +*/ +type DescribeLicenseTokenDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe license token default body +func (o *DescribeLicenseTokenDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseTokenDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeLicenseToken default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeLicenseTokenDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeLicenseToken default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseToken default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseToken default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe license token default body based on the context it is used +func (o *DescribeLicenseTokenDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseTokenDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseToken default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseToken default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLicenseTokenDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLicenseTokenDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeLicenseTokenDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeLicenseTokenOKBody describe license token o k body +swagger:model DescribeLicenseTokenOKBody +*/ +type DescribeLicenseTokenOKBody struct { + + // result + Result *models.LicenseToken `json:"result,omitempty"` +} + +// Validate validates this describe license token o k body +func (o *DescribeLicenseTokenOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseTokenOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseTokenOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseTokenOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe license token o k body based on the context it is used +func (o *DescribeLicenseTokenOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLicenseTokenOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLicenseTokenOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLicenseTokenOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLicenseTokenOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLicenseTokenOKBody) UnmarshalBinary(b []byte) error { + var res DescribeLicenseTokenOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/license_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/license_client.go new file mode 100644 index 0000000..12231a8 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/license_client.go @@ -0,0 +1,157 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new license API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for license API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DescribeLicenseContent(params *DescribeLicenseContentParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLicenseContentOK, error) + + DescribeLicenseToken(params *DescribeLicenseTokenParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLicenseTokenOK, error) + + UploadLicense(params *UploadLicenseParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UploadLicenseOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DescribeLicenseContent DescribeLicenseContent 获取授权详情 +*/ +func (a *Client) DescribeLicenseContent(params *DescribeLicenseContentParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLicenseContentOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeLicenseContentParams() + } + op := &runtime.ClientOperation{ + ID: "describeLicenseContent", + Method: "GET", + PathPattern: "/license/content", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeLicenseContentReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeLicenseContentOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeLicenseContentDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeLicenseToken DescribeRequestToken 获取请求码 +*/ +func (a *Client) DescribeLicenseToken(params *DescribeLicenseTokenParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLicenseTokenOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeLicenseTokenParams() + } + op := &runtime.ClientOperation{ + ID: "describeLicenseToken", + Method: "GET", + PathPattern: "/license/requestToken", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeLicenseTokenReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeLicenseTokenOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeLicenseTokenDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + UploadLicense UploadLicense 上传授权 +*/ +func (a *Client) UploadLicense(params *UploadLicenseParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UploadLicenseOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewUploadLicenseParams() + } + op := &runtime.ClientOperation{ + ID: "uploadLicense", + Method: "POST", + PathPattern: "/license/upload", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UploadLicenseReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*UploadLicenseOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*UploadLicenseDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/upload_license_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/upload_license_parameters.go new file mode 100644 index 0000000..6435a40 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/upload_license_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewUploadLicenseParams creates a new UploadLicenseParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewUploadLicenseParams() *UploadLicenseParams { + return &UploadLicenseParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUploadLicenseParamsWithTimeout creates a new UploadLicenseParams object +// with the ability to set a timeout on a request. +func NewUploadLicenseParamsWithTimeout(timeout time.Duration) *UploadLicenseParams { + return &UploadLicenseParams{ + timeout: timeout, + } +} + +// NewUploadLicenseParamsWithContext creates a new UploadLicenseParams object +// with the ability to set a context for a request. +func NewUploadLicenseParamsWithContext(ctx context.Context) *UploadLicenseParams { + return &UploadLicenseParams{ + Context: ctx, + } +} + +// NewUploadLicenseParamsWithHTTPClient creates a new UploadLicenseParams object +// with the ability to set a custom HTTPClient for a request. +func NewUploadLicenseParamsWithHTTPClient(client *http.Client) *UploadLicenseParams { + return &UploadLicenseParams{ + HTTPClient: client, + } +} + +/* UploadLicenseParams contains all the parameters to send to the API endpoint + for the upload license operation. + + Typically these are written to a http.Request. +*/ +type UploadLicenseParams struct { + + // Body. + Body *models.CreateLicenseRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the upload license params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UploadLicenseParams) WithDefaults() *UploadLicenseParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the upload license params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UploadLicenseParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the upload license params +func (o *UploadLicenseParams) WithTimeout(timeout time.Duration) *UploadLicenseParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the upload license params +func (o *UploadLicenseParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the upload license params +func (o *UploadLicenseParams) WithContext(ctx context.Context) *UploadLicenseParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the upload license params +func (o *UploadLicenseParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the upload license params +func (o *UploadLicenseParams) WithHTTPClient(client *http.Client) *UploadLicenseParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the upload license params +func (o *UploadLicenseParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the upload license params +func (o *UploadLicenseParams) WithBody(body *models.CreateLicenseRequest) *UploadLicenseParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the upload license params +func (o *UploadLicenseParams) SetBody(body *models.CreateLicenseRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the upload license params +func (o *UploadLicenseParams) WithAuthorization(authorization string) *UploadLicenseParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the upload license params +func (o *UploadLicenseParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the upload license params +func (o *UploadLicenseParams) WithBmpLanguage(bmpLanguage *string) *UploadLicenseParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the upload license params +func (o *UploadLicenseParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the upload license params +func (o *UploadLicenseParams) WithBmpUserID(bmpUserID *string) *UploadLicenseParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the upload license params +func (o *UploadLicenseParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the upload license params +func (o *UploadLicenseParams) WithTraceID(traceID string) *UploadLicenseParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the upload license params +func (o *UploadLicenseParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *UploadLicenseParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/upload_license_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/upload_license_responses.go new file mode 100644 index 0000000..7e8828a --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/license/upload_license_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package license + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// UploadLicenseReader is a Reader for the UploadLicense structure. +type UploadLicenseReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UploadLicenseReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUploadLicenseOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewUploadLicenseDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewUploadLicenseOK creates a UploadLicenseOK with default headers values +func NewUploadLicenseOK() *UploadLicenseOK { + return &UploadLicenseOK{} +} + +/* UploadLicenseOK describes a response with status code 200, with default header values. + +A UploadLicenseResult is an response struct that is used to describe modify instance result. +*/ +type UploadLicenseOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *UploadLicenseOKBody +} + +// IsSuccess returns true when this upload license o k response has a 2xx status code +func (o *UploadLicenseOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this upload license o k response has a 3xx status code +func (o *UploadLicenseOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this upload license o k response has a 4xx status code +func (o *UploadLicenseOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this upload license o k response has a 5xx status code +func (o *UploadLicenseOK) IsServerError() bool { + return false +} + +// IsCode returns true when this upload license o k response a status code equal to that given +func (o *UploadLicenseOK) IsCode(code int) bool { + return code == 200 +} + +func (o *UploadLicenseOK) Error() string { + return fmt.Sprintf("[POST /license/upload][%d] uploadLicenseOK %+v", 200, o.Payload) +} + +func (o *UploadLicenseOK) String() string { + return fmt.Sprintf("[POST /license/upload][%d] uploadLicenseOK %+v", 200, o.Payload) +} + +func (o *UploadLicenseOK) GetPayload() *UploadLicenseOKBody { + return o.Payload +} + +func (o *UploadLicenseOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(UploadLicenseOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUploadLicenseDefault creates a UploadLicenseDefault with default headers values +func NewUploadLicenseDefault(code int) *UploadLicenseDefault { + return &UploadLicenseDefault{ + _statusCode: code, + } +} + +/* UploadLicenseDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type UploadLicenseDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *UploadLicenseDefaultBody +} + +// Code gets the status code for the upload license default response +func (o *UploadLicenseDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this upload license default response has a 2xx status code +func (o *UploadLicenseDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this upload license default response has a 3xx status code +func (o *UploadLicenseDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this upload license default response has a 4xx status code +func (o *UploadLicenseDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this upload license default response has a 5xx status code +func (o *UploadLicenseDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this upload license default response a status code equal to that given +func (o *UploadLicenseDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *UploadLicenseDefault) Error() string { + return fmt.Sprintf("[POST /license/upload][%d] uploadLicense default %+v", o._statusCode, o.Payload) +} + +func (o *UploadLicenseDefault) String() string { + return fmt.Sprintf("[POST /license/upload][%d] uploadLicense default %+v", o._statusCode, o.Payload) +} + +func (o *UploadLicenseDefault) GetPayload() *UploadLicenseDefaultBody { + return o.Payload +} + +func (o *UploadLicenseDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(UploadLicenseDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*UploadLicenseDefaultBody upload license default body +swagger:model UploadLicenseDefaultBody +*/ +type UploadLicenseDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this upload license default body +func (o *UploadLicenseDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UploadLicenseDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("uploadLicense default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *UploadLicenseDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("uploadLicense default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("uploadLicense default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("uploadLicense default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this upload license default body based on the context it is used +func (o *UploadLicenseDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UploadLicenseDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("uploadLicense default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("uploadLicense default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *UploadLicenseDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *UploadLicenseDefaultBody) UnmarshalBinary(b []byte) error { + var res UploadLicenseDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*UploadLicenseOKBody upload license o k body +swagger:model UploadLicenseOKBody +*/ +type UploadLicenseOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this upload license o k body +func (o *UploadLicenseOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UploadLicenseOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("uploadLicenseOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("uploadLicenseOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this upload license o k body based on the context it is used +func (o *UploadLicenseOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *UploadLicenseOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("uploadLicenseOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("uploadLicenseOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *UploadLicenseOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *UploadLicenseOKBody) UnmarshalBinary(b []byte) error { + var res UploadLicenseOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/create_o_s_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/create_o_s_parameters.go new file mode 100644 index 0000000..1357863 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/create_o_s_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateOSParams creates a new CreateOSParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateOSParams() *CreateOSParams { + return &CreateOSParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateOSParamsWithTimeout creates a new CreateOSParams object +// with the ability to set a timeout on a request. +func NewCreateOSParamsWithTimeout(timeout time.Duration) *CreateOSParams { + return &CreateOSParams{ + timeout: timeout, + } +} + +// NewCreateOSParamsWithContext creates a new CreateOSParams object +// with the ability to set a context for a request. +func NewCreateOSParamsWithContext(ctx context.Context) *CreateOSParams { + return &CreateOSParams{ + Context: ctx, + } +} + +// NewCreateOSParamsWithHTTPClient creates a new CreateOSParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateOSParamsWithHTTPClient(client *http.Client) *CreateOSParams { + return &CreateOSParams{ + HTTPClient: client, + } +} + +/* CreateOSParams contains all the parameters to send to the API endpoint + for the create o s operation. + + Typically these are written to a http.Request. +*/ +type CreateOSParams struct { + + // Body. + Body *models.CreateOSRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateOSParams) WithDefaults() *CreateOSParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateOSParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create o s params +func (o *CreateOSParams) WithTimeout(timeout time.Duration) *CreateOSParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create o s params +func (o *CreateOSParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create o s params +func (o *CreateOSParams) WithContext(ctx context.Context) *CreateOSParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create o s params +func (o *CreateOSParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create o s params +func (o *CreateOSParams) WithHTTPClient(client *http.Client) *CreateOSParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create o s params +func (o *CreateOSParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create o s params +func (o *CreateOSParams) WithBody(body *models.CreateOSRequest) *CreateOSParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create o s params +func (o *CreateOSParams) SetBody(body *models.CreateOSRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create o s params +func (o *CreateOSParams) WithAuthorization(authorization string) *CreateOSParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create o s params +func (o *CreateOSParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create o s params +func (o *CreateOSParams) WithBmpLanguage(bmpLanguage *string) *CreateOSParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create o s params +func (o *CreateOSParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create o s params +func (o *CreateOSParams) WithBmpUserID(bmpUserID *string) *CreateOSParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create o s params +func (o *CreateOSParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create o s params +func (o *CreateOSParams) WithTraceID(traceID string) *CreateOSParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create o s params +func (o *CreateOSParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateOSParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/create_o_s_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/create_o_s_responses.go new file mode 100644 index 0000000..3db1968 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/create_o_s_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateOSReader is a Reader for the CreateOS structure. +type CreateOSReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateOSReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateOSOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateOSDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateOSOK creates a CreateOSOK with default headers values +func NewCreateOSOK() *CreateOSOK { + return &CreateOSOK{} +} + +/* CreateOSOK describes a response with status code 200, with default header values. + +A CreateOsResult is an response struct that is used to describe create os result. +*/ +type CreateOSOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateOSOKBody +} + +// IsSuccess returns true when this create o s o k response has a 2xx status code +func (o *CreateOSOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create o s o k response has a 3xx status code +func (o *CreateOSOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create o s o k response has a 4xx status code +func (o *CreateOSOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create o s o k response has a 5xx status code +func (o *CreateOSOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create o s o k response a status code equal to that given +func (o *CreateOSOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateOSOK) Error() string { + return fmt.Sprintf("[POST /oss][%d] createOSOK %+v", 200, o.Payload) +} + +func (o *CreateOSOK) String() string { + return fmt.Sprintf("[POST /oss][%d] createOSOK %+v", 200, o.Payload) +} + +func (o *CreateOSOK) GetPayload() *CreateOSOKBody { + return o.Payload +} + +func (o *CreateOSOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateOSOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateOSDefault creates a CreateOSDefault with default headers values +func NewCreateOSDefault(code int) *CreateOSDefault { + return &CreateOSDefault{ + _statusCode: code, + } +} + +/* CreateOSDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateOSDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateOSDefaultBody +} + +// Code gets the status code for the create o s default response +func (o *CreateOSDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create o s default response has a 2xx status code +func (o *CreateOSDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create o s default response has a 3xx status code +func (o *CreateOSDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create o s default response has a 4xx status code +func (o *CreateOSDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create o s default response has a 5xx status code +func (o *CreateOSDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create o s default response a status code equal to that given +func (o *CreateOSDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateOSDefault) Error() string { + return fmt.Sprintf("[POST /oss][%d] createOS default %+v", o._statusCode, o.Payload) +} + +func (o *CreateOSDefault) String() string { + return fmt.Sprintf("[POST /oss][%d] createOS default %+v", o._statusCode, o.Payload) +} + +func (o *CreateOSDefault) GetPayload() *CreateOSDefaultBody { + return o.Payload +} + +func (o *CreateOSDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateOSDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateOSDefaultBody create o s default body +swagger:model CreateOSDefaultBody +*/ +type CreateOSDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create o s default body +func (o *CreateOSDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateOSDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createOS default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateOSDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createOS default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create o s default body based on the context it is used +func (o *CreateOSDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateOSDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateOSDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateOSDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateOSDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateOSOKBody create o s o k body +swagger:model CreateOSOKBody +*/ +type CreateOSOKBody struct { + + // result + Result *models.OsID `json:"result,omitempty"` +} + +// Validate validates this create o s o k body +func (o *CreateOSOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateOSOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create o s o k body based on the context it is used +func (o *CreateOSOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateOSOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateOSOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateOSOKBody) UnmarshalBinary(b []byte) error { + var res CreateOSOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/delete_o_s_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/delete_o_s_parameters.go new file mode 100644 index 0000000..c80c5fd --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/delete_o_s_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteOSParams creates a new DeleteOSParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteOSParams() *DeleteOSParams { + return &DeleteOSParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteOSParamsWithTimeout creates a new DeleteOSParams object +// with the ability to set a timeout on a request. +func NewDeleteOSParamsWithTimeout(timeout time.Duration) *DeleteOSParams { + return &DeleteOSParams{ + timeout: timeout, + } +} + +// NewDeleteOSParamsWithContext creates a new DeleteOSParams object +// with the ability to set a context for a request. +func NewDeleteOSParamsWithContext(ctx context.Context) *DeleteOSParams { + return &DeleteOSParams{ + Context: ctx, + } +} + +// NewDeleteOSParamsWithHTTPClient creates a new DeleteOSParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteOSParamsWithHTTPClient(client *http.Client) *DeleteOSParams { + return &DeleteOSParams{ + HTTPClient: client, + } +} + +/* DeleteOSParams contains all the parameters to send to the API endpoint + for the delete o s operation. + + Typically these are written to a http.Request. +*/ +type DeleteOSParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // OsID. + OsID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteOSParams) WithDefaults() *DeleteOSParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteOSParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete o s params +func (o *DeleteOSParams) WithTimeout(timeout time.Duration) *DeleteOSParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete o s params +func (o *DeleteOSParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete o s params +func (o *DeleteOSParams) WithContext(ctx context.Context) *DeleteOSParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete o s params +func (o *DeleteOSParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete o s params +func (o *DeleteOSParams) WithHTTPClient(client *http.Client) *DeleteOSParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete o s params +func (o *DeleteOSParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete o s params +func (o *DeleteOSParams) WithAuthorization(authorization string) *DeleteOSParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete o s params +func (o *DeleteOSParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete o s params +func (o *DeleteOSParams) WithBmpLanguage(bmpLanguage *string) *DeleteOSParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete o s params +func (o *DeleteOSParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete o s params +func (o *DeleteOSParams) WithBmpUserID(bmpUserID *string) *DeleteOSParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete o s params +func (o *DeleteOSParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithOsID adds the osID to the delete o s params +func (o *DeleteOSParams) WithOsID(osID string) *DeleteOSParams { + o.SetOsID(osID) + return o +} + +// SetOsID adds the osId to the delete o s params +func (o *DeleteOSParams) SetOsID(osID string) { + o.OsID = osID +} + +// WithTraceID adds the traceID to the delete o s params +func (o *DeleteOSParams) WithTraceID(traceID string) *DeleteOSParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete o s params +func (o *DeleteOSParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteOSParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param os_id + if err := r.SetPathParam("os_id", o.OsID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/delete_o_s_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/delete_o_s_responses.go new file mode 100644 index 0000000..e397536 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/delete_o_s_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteOSReader is a Reader for the DeleteOS structure. +type DeleteOSReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteOSReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteOSOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteOSDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteOSOK creates a DeleteOSOK with default headers values +func NewDeleteOSOK() *DeleteOSOK { + return &DeleteOSOK{} +} + +/* DeleteOSOK describes a response with status code 200, with default header values. + +A DeleteOsResult is an response struct that is used to delete stop os result. +*/ +type DeleteOSOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteOSOKBody +} + +// IsSuccess returns true when this delete o s o k response has a 2xx status code +func (o *DeleteOSOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete o s o k response has a 3xx status code +func (o *DeleteOSOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete o s o k response has a 4xx status code +func (o *DeleteOSOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete o s o k response has a 5xx status code +func (o *DeleteOSOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete o s o k response a status code equal to that given +func (o *DeleteOSOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteOSOK) Error() string { + return fmt.Sprintf("[DELETE /oss/{os_id}][%d] deleteOSOK %+v", 200, o.Payload) +} + +func (o *DeleteOSOK) String() string { + return fmt.Sprintf("[DELETE /oss/{os_id}][%d] deleteOSOK %+v", 200, o.Payload) +} + +func (o *DeleteOSOK) GetPayload() *DeleteOSOKBody { + return o.Payload +} + +func (o *DeleteOSOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteOSOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteOSDefault creates a DeleteOSDefault with default headers values +func NewDeleteOSDefault(code int) *DeleteOSDefault { + return &DeleteOSDefault{ + _statusCode: code, + } +} + +/* DeleteOSDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteOSDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteOSDefaultBody +} + +// Code gets the status code for the delete o s default response +func (o *DeleteOSDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete o s default response has a 2xx status code +func (o *DeleteOSDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete o s default response has a 3xx status code +func (o *DeleteOSDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete o s default response has a 4xx status code +func (o *DeleteOSDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete o s default response has a 5xx status code +func (o *DeleteOSDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete o s default response a status code equal to that given +func (o *DeleteOSDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteOSDefault) Error() string { + return fmt.Sprintf("[DELETE /oss/{os_id}][%d] deleteOS default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteOSDefault) String() string { + return fmt.Sprintf("[DELETE /oss/{os_id}][%d] deleteOS default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteOSDefault) GetPayload() *DeleteOSDefaultBody { + return o.Payload +} + +func (o *DeleteOSDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteOSDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteOSDefaultBody delete o s default body +swagger:model DeleteOSDefaultBody +*/ +type DeleteOSDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete o s default body +func (o *DeleteOSDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteOSDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteOS default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteOSDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteOS default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete o s default body based on the context it is used +func (o *DeleteOSDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteOSDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteOSDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteOSDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteOSDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteOSOKBody delete o s o k body +swagger:model DeleteOSOKBody +*/ +type DeleteOSOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete o s o k body +func (o *DeleteOSOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteOSOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete o s o k body based on the context it is used +func (o *DeleteOSOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteOSOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteOSOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteOSOKBody) UnmarshalBinary(b []byte) error { + var res DeleteOSOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_s_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_s_parameters.go new file mode 100644 index 0000000..df2f89f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_s_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeOSParams creates a new DescribeOSParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeOSParams() *DescribeOSParams { + return &DescribeOSParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeOSParamsWithTimeout creates a new DescribeOSParams object +// with the ability to set a timeout on a request. +func NewDescribeOSParamsWithTimeout(timeout time.Duration) *DescribeOSParams { + return &DescribeOSParams{ + timeout: timeout, + } +} + +// NewDescribeOSParamsWithContext creates a new DescribeOSParams object +// with the ability to set a context for a request. +func NewDescribeOSParamsWithContext(ctx context.Context) *DescribeOSParams { + return &DescribeOSParams{ + Context: ctx, + } +} + +// NewDescribeOSParamsWithHTTPClient creates a new DescribeOSParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeOSParamsWithHTTPClient(client *http.Client) *DescribeOSParams { + return &DescribeOSParams{ + HTTPClient: client, + } +} + +/* DescribeOSParams contains all the parameters to send to the API endpoint + for the describe o s operation. + + Typically these are written to a http.Request. +*/ +type DescribeOSParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // OsID. + OsID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeOSParams) WithDefaults() *DescribeOSParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeOSParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe o s params +func (o *DescribeOSParams) WithTimeout(timeout time.Duration) *DescribeOSParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe o s params +func (o *DescribeOSParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe o s params +func (o *DescribeOSParams) WithContext(ctx context.Context) *DescribeOSParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe o s params +func (o *DescribeOSParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe o s params +func (o *DescribeOSParams) WithHTTPClient(client *http.Client) *DescribeOSParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe o s params +func (o *DescribeOSParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe o s params +func (o *DescribeOSParams) WithAuthorization(authorization string) *DescribeOSParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe o s params +func (o *DescribeOSParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe o s params +func (o *DescribeOSParams) WithBmpLanguage(bmpLanguage *string) *DescribeOSParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe o s params +func (o *DescribeOSParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe o s params +func (o *DescribeOSParams) WithBmpUserID(bmpUserID *string) *DescribeOSParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe o s params +func (o *DescribeOSParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithOsID adds the osID to the describe o s params +func (o *DescribeOSParams) WithOsID(osID string) *DescribeOSParams { + o.SetOsID(osID) + return o +} + +// SetOsID adds the osId to the describe o s params +func (o *DescribeOSParams) SetOsID(osID string) { + o.OsID = osID +} + +// WithTraceID adds the traceID to the describe o s params +func (o *DescribeOSParams) WithTraceID(traceID string) *DescribeOSParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe o s params +func (o *DescribeOSParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeOSParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param os_id + if err := r.SetPathParam("os_id", o.OsID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_s_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_s_responses.go new file mode 100644 index 0000000..370a646 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_s_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeOSReader is a Reader for the DescribeOS structure. +type DescribeOSReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeOSReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeOSOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeOSDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeOSOK creates a DescribeOSOK with default headers values +func NewDescribeOSOK() *DescribeOSOK { + return &DescribeOSOK{} +} + +/* DescribeOSOK describes a response with status code 200, with default header values. + +A DescribeOsResult is an response struct that is used to describe os. +*/ +type DescribeOSOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeOSOKBody +} + +// IsSuccess returns true when this describe o s o k response has a 2xx status code +func (o *DescribeOSOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe o s o k response has a 3xx status code +func (o *DescribeOSOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe o s o k response has a 4xx status code +func (o *DescribeOSOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe o s o k response has a 5xx status code +func (o *DescribeOSOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe o s o k response a status code equal to that given +func (o *DescribeOSOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeOSOK) Error() string { + return fmt.Sprintf("[GET /oss/{os_id}][%d] describeOSOK %+v", 200, o.Payload) +} + +func (o *DescribeOSOK) String() string { + return fmt.Sprintf("[GET /oss/{os_id}][%d] describeOSOK %+v", 200, o.Payload) +} + +func (o *DescribeOSOK) GetPayload() *DescribeOSOKBody { + return o.Payload +} + +func (o *DescribeOSOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeOSOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeOSDefault creates a DescribeOSDefault with default headers values +func NewDescribeOSDefault(code int) *DescribeOSDefault { + return &DescribeOSDefault{ + _statusCode: code, + } +} + +/* DescribeOSDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeOSDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeOSDefaultBody +} + +// Code gets the status code for the describe o s default response +func (o *DescribeOSDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe o s default response has a 2xx status code +func (o *DescribeOSDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe o s default response has a 3xx status code +func (o *DescribeOSDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe o s default response has a 4xx status code +func (o *DescribeOSDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe o s default response has a 5xx status code +func (o *DescribeOSDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe o s default response a status code equal to that given +func (o *DescribeOSDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeOSDefault) Error() string { + return fmt.Sprintf("[GET /oss/{os_id}][%d] describeOS default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeOSDefault) String() string { + return fmt.Sprintf("[GET /oss/{os_id}][%d] describeOS default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeOSDefault) GetPayload() *DescribeOSDefaultBody { + return o.Payload +} + +func (o *DescribeOSDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeOSDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeOSDefaultBody describe o s default body +swagger:model DescribeOSDefaultBody +*/ +type DescribeOSDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe o s default body +func (o *DescribeOSDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeOS default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeOSDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeOS default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe o s default body based on the context it is used +func (o *DescribeOSDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeOSDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeOSDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeOSDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeOSOKBody describe o s o k body +swagger:model DescribeOSOKBody +*/ +type DescribeOSOKBody struct { + + // result + Result *models.OsInfo `json:"result,omitempty"` +} + +// Validate validates this describe o s o k body +func (o *DescribeOSOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe o s o k body based on the context it is used +func (o *DescribeOSOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeOSOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeOSOKBody) UnmarshalBinary(b []byte) error { + var res DescribeOSOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_ss_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_ss_parameters.go new file mode 100644 index 0000000..d009e8d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_ss_parameters.go @@ -0,0 +1,357 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeOSsParams creates a new DescribeOSsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeOSsParams() *DescribeOSsParams { + return &DescribeOSsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeOSsParamsWithTimeout creates a new DescribeOSsParams object +// with the ability to set a timeout on a request. +func NewDescribeOSsParamsWithTimeout(timeout time.Duration) *DescribeOSsParams { + return &DescribeOSsParams{ + timeout: timeout, + } +} + +// NewDescribeOSsParamsWithContext creates a new DescribeOSsParams object +// with the ability to set a context for a request. +func NewDescribeOSsParamsWithContext(ctx context.Context) *DescribeOSsParams { + return &DescribeOSsParams{ + Context: ctx, + } +} + +// NewDescribeOSsParamsWithHTTPClient creates a new DescribeOSsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeOSsParamsWithHTTPClient(client *http.Client) *DescribeOSsParams { + return &DescribeOSsParams{ + HTTPClient: client, + } +} + +/* DescribeOSsParams contains all the parameters to send to the API endpoint + for the describe o ss operation. + + Typically these are written to a http.Request. +*/ +type DescribeOSsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否显示所有 + */ + IsAll *string + + /* OsName. + + 操作系统名称 + */ + OsName *string + + /* OsType. + + 操作系统平台 + */ + OsType *string + + /* OsVersion. + + 操作系统版本 + */ + OsVersion *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe o ss params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeOSsParams) WithDefaults() *DescribeOSsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe o ss params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeOSsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe o ss params +func (o *DescribeOSsParams) WithTimeout(timeout time.Duration) *DescribeOSsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe o ss params +func (o *DescribeOSsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe o ss params +func (o *DescribeOSsParams) WithContext(ctx context.Context) *DescribeOSsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe o ss params +func (o *DescribeOSsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe o ss params +func (o *DescribeOSsParams) WithHTTPClient(client *http.Client) *DescribeOSsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe o ss params +func (o *DescribeOSsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe o ss params +func (o *DescribeOSsParams) WithAuthorization(authorization string) *DescribeOSsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe o ss params +func (o *DescribeOSsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe o ss params +func (o *DescribeOSsParams) WithBmpLanguage(bmpLanguage *string) *DescribeOSsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe o ss params +func (o *DescribeOSsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe o ss params +func (o *DescribeOSsParams) WithBmpUserID(bmpUserID *string) *DescribeOSsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe o ss params +func (o *DescribeOSsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe o ss params +func (o *DescribeOSsParams) WithIsAll(isAll *string) *DescribeOSsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe o ss params +func (o *DescribeOSsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithOsName adds the osName to the describe o ss params +func (o *DescribeOSsParams) WithOsName(osName *string) *DescribeOSsParams { + o.SetOsName(osName) + return o +} + +// SetOsName adds the osName to the describe o ss params +func (o *DescribeOSsParams) SetOsName(osName *string) { + o.OsName = osName +} + +// WithOsType adds the osType to the describe o ss params +func (o *DescribeOSsParams) WithOsType(osType *string) *DescribeOSsParams { + o.SetOsType(osType) + return o +} + +// SetOsType adds the osType to the describe o ss params +func (o *DescribeOSsParams) SetOsType(osType *string) { + o.OsType = osType +} + +// WithOsVersion adds the osVersion to the describe o ss params +func (o *DescribeOSsParams) WithOsVersion(osVersion *string) *DescribeOSsParams { + o.SetOsVersion(osVersion) + return o +} + +// SetOsVersion adds the osVersion to the describe o ss params +func (o *DescribeOSsParams) SetOsVersion(osVersion *string) { + o.OsVersion = osVersion +} + +// WithTraceID adds the traceID to the describe o ss params +func (o *DescribeOSsParams) WithTraceID(traceID string) *DescribeOSsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe o ss params +func (o *DescribeOSsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeOSsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.OsName != nil { + + // query param osName + var qrOsName string + + if o.OsName != nil { + qrOsName = *o.OsName + } + qOsName := qrOsName + if qOsName != "" { + + if err := r.SetQueryParam("osName", qOsName); err != nil { + return err + } + } + } + + if o.OsType != nil { + + // query param osType + var qrOsType string + + if o.OsType != nil { + qrOsType = *o.OsType + } + qOsType := qrOsType + if qOsType != "" { + + if err := r.SetQueryParam("osType", qOsType); err != nil { + return err + } + } + } + + if o.OsVersion != nil { + + // query param osVersion + var qrOsVersion string + + if o.OsVersion != nil { + qrOsVersion = *o.OsVersion + } + qOsVersion := qrOsVersion + if qOsVersion != "" { + + if err := r.SetQueryParam("osVersion", qOsVersion); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_ss_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_ss_responses.go new file mode 100644 index 0000000..ac6e43b --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/describe_o_ss_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeOSsReader is a Reader for the DescribeOSs structure. +type DescribeOSsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeOSsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeOSsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeOSsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeOSsOK creates a DescribeOSsOK with default headers values +func NewDescribeOSsOK() *DescribeOSsOK { + return &DescribeOSsOK{} +} + +/* DescribeOSsOK describes a response with status code 200, with default header values. + +A DescribeOssResult is an response struct that is used to describe oss. +*/ +type DescribeOSsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeOSsOKBody +} + +// IsSuccess returns true when this describe o ss o k response has a 2xx status code +func (o *DescribeOSsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe o ss o k response has a 3xx status code +func (o *DescribeOSsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe o ss o k response has a 4xx status code +func (o *DescribeOSsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe o ss o k response has a 5xx status code +func (o *DescribeOSsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe o ss o k response a status code equal to that given +func (o *DescribeOSsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeOSsOK) Error() string { + return fmt.Sprintf("[GET /oss][%d] describeOSsOK %+v", 200, o.Payload) +} + +func (o *DescribeOSsOK) String() string { + return fmt.Sprintf("[GET /oss][%d] describeOSsOK %+v", 200, o.Payload) +} + +func (o *DescribeOSsOK) GetPayload() *DescribeOSsOKBody { + return o.Payload +} + +func (o *DescribeOSsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeOSsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeOSsDefault creates a DescribeOSsDefault with default headers values +func NewDescribeOSsDefault(code int) *DescribeOSsDefault { + return &DescribeOSsDefault{ + _statusCode: code, + } +} + +/* DescribeOSsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeOSsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeOSsDefaultBody +} + +// Code gets the status code for the describe o ss default response +func (o *DescribeOSsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe o ss default response has a 2xx status code +func (o *DescribeOSsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe o ss default response has a 3xx status code +func (o *DescribeOSsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe o ss default response has a 4xx status code +func (o *DescribeOSsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe o ss default response has a 5xx status code +func (o *DescribeOSsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe o ss default response a status code equal to that given +func (o *DescribeOSsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeOSsDefault) Error() string { + return fmt.Sprintf("[GET /oss][%d] describeOSs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeOSsDefault) String() string { + return fmt.Sprintf("[GET /oss][%d] describeOSs default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeOSsDefault) GetPayload() *DescribeOSsDefaultBody { + return o.Payload +} + +func (o *DescribeOSsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeOSsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeOSsDefaultBody describe o ss default body +swagger:model DescribeOSsDefaultBody +*/ +type DescribeOSsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe o ss default body +func (o *DescribeOSsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeOSs default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeOSsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeOSs default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSs default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe o ss default body based on the context it is used +func (o *DescribeOSsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSs default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSs default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeOSsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeOSsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeOSsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeOSsOKBody describe o ss o k body +swagger:model DescribeOSsOKBody +*/ +type DescribeOSsOKBody struct { + + // result + Result *models.OsList `json:"result,omitempty"` +} + +// Validate validates this describe o ss o k body +func (o *DescribeOSsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe o ss o k body based on the context it is used +func (o *DescribeOSsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeOSsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeOSsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeOSsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeOSsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeOSsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeOSsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/modify_o_s_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/modify_o_s_parameters.go new file mode 100644 index 0000000..74a1a82 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/modify_o_s_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyOSParams creates a new ModifyOSParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyOSParams() *ModifyOSParams { + return &ModifyOSParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyOSParamsWithTimeout creates a new ModifyOSParams object +// with the ability to set a timeout on a request. +func NewModifyOSParamsWithTimeout(timeout time.Duration) *ModifyOSParams { + return &ModifyOSParams{ + timeout: timeout, + } +} + +// NewModifyOSParamsWithContext creates a new ModifyOSParams object +// with the ability to set a context for a request. +func NewModifyOSParamsWithContext(ctx context.Context) *ModifyOSParams { + return &ModifyOSParams{ + Context: ctx, + } +} + +// NewModifyOSParamsWithHTTPClient creates a new ModifyOSParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyOSParamsWithHTTPClient(client *http.Client) *ModifyOSParams { + return &ModifyOSParams{ + HTTPClient: client, + } +} + +/* ModifyOSParams contains all the parameters to send to the API endpoint + for the modify o s operation. + + Typically these are written to a http.Request. +*/ +type ModifyOSParams struct { + + // Body. + Body *models.ModifyOSRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // OsID. + OsID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyOSParams) WithDefaults() *ModifyOSParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify o s params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyOSParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify o s params +func (o *ModifyOSParams) WithTimeout(timeout time.Duration) *ModifyOSParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify o s params +func (o *ModifyOSParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify o s params +func (o *ModifyOSParams) WithContext(ctx context.Context) *ModifyOSParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify o s params +func (o *ModifyOSParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify o s params +func (o *ModifyOSParams) WithHTTPClient(client *http.Client) *ModifyOSParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify o s params +func (o *ModifyOSParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify o s params +func (o *ModifyOSParams) WithBody(body *models.ModifyOSRequest) *ModifyOSParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify o s params +func (o *ModifyOSParams) SetBody(body *models.ModifyOSRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify o s params +func (o *ModifyOSParams) WithAuthorization(authorization string) *ModifyOSParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify o s params +func (o *ModifyOSParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify o s params +func (o *ModifyOSParams) WithBmpLanguage(bmpLanguage *string) *ModifyOSParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify o s params +func (o *ModifyOSParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify o s params +func (o *ModifyOSParams) WithBmpUserID(bmpUserID *string) *ModifyOSParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify o s params +func (o *ModifyOSParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithOsID adds the osID to the modify o s params +func (o *ModifyOSParams) WithOsID(osID string) *ModifyOSParams { + o.SetOsID(osID) + return o +} + +// SetOsID adds the osId to the modify o s params +func (o *ModifyOSParams) SetOsID(osID string) { + o.OsID = osID +} + +// WithTraceID adds the traceID to the modify o s params +func (o *ModifyOSParams) WithTraceID(traceID string) *ModifyOSParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify o s params +func (o *ModifyOSParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyOSParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param os_id + if err := r.SetPathParam("os_id", o.OsID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/modify_o_s_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/modify_o_s_responses.go new file mode 100644 index 0000000..7c0f605 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/modify_o_s_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyOSReader is a Reader for the ModifyOS structure. +type ModifyOSReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyOSReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyOSOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyOSDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyOSOK creates a ModifyOSOK with default headers values +func NewModifyOSOK() *ModifyOSOK { + return &ModifyOSOK{} +} + +/* ModifyOSOK describes a response with status code 200, with default header values. + +A ModifyOsResult is an response struct that is used to describe modify os. +*/ +type ModifyOSOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyOSOKBody +} + +// IsSuccess returns true when this modify o s o k response has a 2xx status code +func (o *ModifyOSOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify o s o k response has a 3xx status code +func (o *ModifyOSOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify o s o k response has a 4xx status code +func (o *ModifyOSOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify o s o k response has a 5xx status code +func (o *ModifyOSOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify o s o k response a status code equal to that given +func (o *ModifyOSOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyOSOK) Error() string { + return fmt.Sprintf("[PUT /oss/{os_id}][%d] modifyOSOK %+v", 200, o.Payload) +} + +func (o *ModifyOSOK) String() string { + return fmt.Sprintf("[PUT /oss/{os_id}][%d] modifyOSOK %+v", 200, o.Payload) +} + +func (o *ModifyOSOK) GetPayload() *ModifyOSOKBody { + return o.Payload +} + +func (o *ModifyOSOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyOSOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyOSDefault creates a ModifyOSDefault with default headers values +func NewModifyOSDefault(code int) *ModifyOSDefault { + return &ModifyOSDefault{ + _statusCode: code, + } +} + +/* ModifyOSDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyOSDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyOSDefaultBody +} + +// Code gets the status code for the modify o s default response +func (o *ModifyOSDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify o s default response has a 2xx status code +func (o *ModifyOSDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify o s default response has a 3xx status code +func (o *ModifyOSDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify o s default response has a 4xx status code +func (o *ModifyOSDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify o s default response has a 5xx status code +func (o *ModifyOSDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify o s default response a status code equal to that given +func (o *ModifyOSDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyOSDefault) Error() string { + return fmt.Sprintf("[PUT /oss/{os_id}][%d] modifyOS default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyOSDefault) String() string { + return fmt.Sprintf("[PUT /oss/{os_id}][%d] modifyOS default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyOSDefault) GetPayload() *ModifyOSDefaultBody { + return o.Payload +} + +func (o *ModifyOSDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyOSDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyOSDefaultBody modify o s default body +swagger:model ModifyOSDefaultBody +*/ +type ModifyOSDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify o s default body +func (o *ModifyOSDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyOSDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyOS default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyOSDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyOS default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify o s default body based on the context it is used +func (o *ModifyOSDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyOSDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyOS default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyOS default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyOSDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyOSDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyOSDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyOSOKBody modify o s o k body +swagger:model ModifyOSOKBody +*/ +type ModifyOSOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify o s o k body +func (o *ModifyOSOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyOSOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify o s o k body based on the context it is used +func (o *ModifyOSOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyOSOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyOSOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyOSOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyOSOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyOSOKBody) UnmarshalBinary(b []byte) error { + var res ModifyOSOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/os_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/os_client.go new file mode 100644 index 0000000..8b6692f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/os/os_client.go @@ -0,0 +1,237 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package os + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new os API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for os API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateOS(params *CreateOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateOSOK, error) + + DeleteOS(params *DeleteOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteOSOK, error) + + DescribeOS(params *DescribeOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeOSOK, error) + + DescribeOSs(params *DescribeOSsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeOSsOK, error) + + ModifyOS(params *ModifyOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyOSOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateOS CreateOS 添加操作系统(暂不启用) +*/ +func (a *Client) CreateOS(params *CreateOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateOSOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateOSParams() + } + op := &runtime.ClientOperation{ + ID: "createOS", + Method: "POST", + PathPattern: "/oss", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateOSReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateOSOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateOSDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteOS DeleteOS 删除os(暂不启用) +*/ +func (a *Client) DeleteOS(params *DeleteOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteOSOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteOSParams() + } + op := &runtime.ClientOperation{ + ID: "deleteOS", + Method: "DELETE", + PathPattern: "/oss/{os_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteOSReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteOSOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteOSDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeOS DescribeOS 获取os系统详情(暂不启用) +*/ +func (a *Client) DescribeOS(params *DescribeOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeOSOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeOSParams() + } + op := &runtime.ClientOperation{ + ID: "describeOS", + Method: "GET", + PathPattern: "/oss/{os_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeOSReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeOSOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeOSDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeOSs DescribeOSs 获取os列表(暂不启用) +*/ +func (a *Client) DescribeOSs(params *DescribeOSsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeOSsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeOSsParams() + } + op := &runtime.ClientOperation{ + ID: "describeOSs", + Method: "GET", + PathPattern: "/oss", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeOSsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeOSsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeOSsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyOS ModifyOS 修改os信息(暂不启用) +*/ +func (a *Client) ModifyOS(params *ModifyOSParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyOSOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyOSParams() + } + op := &runtime.ClientOperation{ + ID: "modifyOS", + Method: "PUT", + PathPattern: "/oss/{os_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyOSReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyOSOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyOSDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/cancel_share_user_project_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/cancel_share_user_project_parameters.go new file mode 100644 index 0000000..1729c0c --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/cancel_share_user_project_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCancelShareUserProjectParams creates a new CancelShareUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCancelShareUserProjectParams() *CancelShareUserProjectParams { + return &CancelShareUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCancelShareUserProjectParamsWithTimeout creates a new CancelShareUserProjectParams object +// with the ability to set a timeout on a request. +func NewCancelShareUserProjectParamsWithTimeout(timeout time.Duration) *CancelShareUserProjectParams { + return &CancelShareUserProjectParams{ + timeout: timeout, + } +} + +// NewCancelShareUserProjectParamsWithContext creates a new CancelShareUserProjectParams object +// with the ability to set a context for a request. +func NewCancelShareUserProjectParamsWithContext(ctx context.Context) *CancelShareUserProjectParams { + return &CancelShareUserProjectParams{ + Context: ctx, + } +} + +// NewCancelShareUserProjectParamsWithHTTPClient creates a new CancelShareUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewCancelShareUserProjectParamsWithHTTPClient(client *http.Client) *CancelShareUserProjectParams { + return &CancelShareUserProjectParams{ + HTTPClient: client, + } +} + +/* CancelShareUserProjectParams contains all the parameters to send to the API endpoint + for the cancel share user project operation. + + Typically these are written to a http.Request. +*/ +type CancelShareUserProjectParams struct { + + // Body. + Body *models.ShareProjectRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the cancel share user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CancelShareUserProjectParams) WithDefaults() *CancelShareUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the cancel share user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CancelShareUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the cancel share user project params +func (o *CancelShareUserProjectParams) WithTimeout(timeout time.Duration) *CancelShareUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the cancel share user project params +func (o *CancelShareUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the cancel share user project params +func (o *CancelShareUserProjectParams) WithContext(ctx context.Context) *CancelShareUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the cancel share user project params +func (o *CancelShareUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the cancel share user project params +func (o *CancelShareUserProjectParams) WithHTTPClient(client *http.Client) *CancelShareUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the cancel share user project params +func (o *CancelShareUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the cancel share user project params +func (o *CancelShareUserProjectParams) WithBody(body *models.ShareProjectRequest) *CancelShareUserProjectParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the cancel share user project params +func (o *CancelShareUserProjectParams) SetBody(body *models.ShareProjectRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the cancel share user project params +func (o *CancelShareUserProjectParams) WithAuthorization(authorization string) *CancelShareUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the cancel share user project params +func (o *CancelShareUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the cancel share user project params +func (o *CancelShareUserProjectParams) WithBmpLanguage(bmpLanguage *string) *CancelShareUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the cancel share user project params +func (o *CancelShareUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the cancel share user project params +func (o *CancelShareUserProjectParams) WithBmpUserID(bmpUserID *string) *CancelShareUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the cancel share user project params +func (o *CancelShareUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the cancel share user project params +func (o *CancelShareUserProjectParams) WithProjectID(projectID string) *CancelShareUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the cancel share user project params +func (o *CancelShareUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the cancel share user project params +func (o *CancelShareUserProjectParams) WithTraceID(traceID string) *CancelShareUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the cancel share user project params +func (o *CancelShareUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CancelShareUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/cancel_share_user_project_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/cancel_share_user_project_responses.go new file mode 100644 index 0000000..4fc3307 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/cancel_share_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CancelShareUserProjectReader is a Reader for the CancelShareUserProject structure. +type CancelShareUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CancelShareUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCancelShareUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCancelShareUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCancelShareUserProjectOK creates a CancelShareUserProjectOK with default headers values +func NewCancelShareUserProjectOK() *CancelShareUserProjectOK { + return &CancelShareUserProjectOK{} +} + +/* CancelShareUserProjectOK describes a response with status code 200, with default header values. + +A CancelShareUserProjectResult is an response struct +*/ +type CancelShareUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CancelShareUserProjectOKBody +} + +// IsSuccess returns true when this cancel share user project o k response has a 2xx status code +func (o *CancelShareUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this cancel share user project o k response has a 3xx status code +func (o *CancelShareUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this cancel share user project o k response has a 4xx status code +func (o *CancelShareUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this cancel share user project o k response has a 5xx status code +func (o *CancelShareUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this cancel share user project o k response a status code equal to that given +func (o *CancelShareUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CancelShareUserProjectOK) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/cancelShare][%d] cancelShareUserProjectOK %+v", 200, o.Payload) +} + +func (o *CancelShareUserProjectOK) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/cancelShare][%d] cancelShareUserProjectOK %+v", 200, o.Payload) +} + +func (o *CancelShareUserProjectOK) GetPayload() *CancelShareUserProjectOKBody { + return o.Payload +} + +func (o *CancelShareUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CancelShareUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCancelShareUserProjectDefault creates a CancelShareUserProjectDefault with default headers values +func NewCancelShareUserProjectDefault(code int) *CancelShareUserProjectDefault { + return &CancelShareUserProjectDefault{ + _statusCode: code, + } +} + +/* CancelShareUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CancelShareUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CancelShareUserProjectDefaultBody +} + +// Code gets the status code for the cancel share user project default response +func (o *CancelShareUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this cancel share user project default response has a 2xx status code +func (o *CancelShareUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this cancel share user project default response has a 3xx status code +func (o *CancelShareUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this cancel share user project default response has a 4xx status code +func (o *CancelShareUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this cancel share user project default response has a 5xx status code +func (o *CancelShareUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this cancel share user project default response a status code equal to that given +func (o *CancelShareUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CancelShareUserProjectDefault) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/cancelShare][%d] cancelShareUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *CancelShareUserProjectDefault) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/cancelShare][%d] cancelShareUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *CancelShareUserProjectDefault) GetPayload() *CancelShareUserProjectDefaultBody { + return o.Payload +} + +func (o *CancelShareUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CancelShareUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CancelShareUserProjectDefaultBody cancel share user project default body +swagger:model CancelShareUserProjectDefaultBody +*/ +type CancelShareUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this cancel share user project default body +func (o *CancelShareUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CancelShareUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("cancelShareUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CancelShareUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("cancelShareUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cancelShareUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cancelShareUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this cancel share user project default body based on the context it is used +func (o *CancelShareUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CancelShareUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cancelShareUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cancelShareUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CancelShareUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CancelShareUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res CancelShareUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CancelShareUserProjectOKBody cancel share user project o k body +swagger:model CancelShareUserProjectOKBody +*/ +type CancelShareUserProjectOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this cancel share user project o k body +func (o *CancelShareUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CancelShareUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cancelShareUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cancelShareUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this cancel share user project o k body based on the context it is used +func (o *CancelShareUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CancelShareUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cancelShareUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cancelShareUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CancelShareUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CancelShareUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res CancelShareUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/create_user_project_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/create_user_project_parameters.go new file mode 100644 index 0000000..62ddaec --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/create_user_project_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateUserProjectParams creates a new CreateUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateUserProjectParams() *CreateUserProjectParams { + return &CreateUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateUserProjectParamsWithTimeout creates a new CreateUserProjectParams object +// with the ability to set a timeout on a request. +func NewCreateUserProjectParamsWithTimeout(timeout time.Duration) *CreateUserProjectParams { + return &CreateUserProjectParams{ + timeout: timeout, + } +} + +// NewCreateUserProjectParamsWithContext creates a new CreateUserProjectParams object +// with the ability to set a context for a request. +func NewCreateUserProjectParamsWithContext(ctx context.Context) *CreateUserProjectParams { + return &CreateUserProjectParams{ + Context: ctx, + } +} + +// NewCreateUserProjectParamsWithHTTPClient creates a new CreateUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateUserProjectParamsWithHTTPClient(client *http.Client) *CreateUserProjectParams { + return &CreateUserProjectParams{ + HTTPClient: client, + } +} + +/* CreateUserProjectParams contains all the parameters to send to the API endpoint + for the create user project operation. + + Typically these are written to a http.Request. +*/ +type CreateUserProjectParams struct { + + // Body. + Body *models.CreateProjectRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserProjectParams) WithDefaults() *CreateUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create user project params +func (o *CreateUserProjectParams) WithTimeout(timeout time.Duration) *CreateUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create user project params +func (o *CreateUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create user project params +func (o *CreateUserProjectParams) WithContext(ctx context.Context) *CreateUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create user project params +func (o *CreateUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create user project params +func (o *CreateUserProjectParams) WithHTTPClient(client *http.Client) *CreateUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create user project params +func (o *CreateUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create user project params +func (o *CreateUserProjectParams) WithBody(body *models.CreateProjectRequest) *CreateUserProjectParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create user project params +func (o *CreateUserProjectParams) SetBody(body *models.CreateProjectRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create user project params +func (o *CreateUserProjectParams) WithAuthorization(authorization string) *CreateUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create user project params +func (o *CreateUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create user project params +func (o *CreateUserProjectParams) WithBmpLanguage(bmpLanguage *string) *CreateUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create user project params +func (o *CreateUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create user project params +func (o *CreateUserProjectParams) WithBmpUserID(bmpUserID *string) *CreateUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create user project params +func (o *CreateUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create user project params +func (o *CreateUserProjectParams) WithTraceID(traceID string) *CreateUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create user project params +func (o *CreateUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/create_user_project_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/create_user_project_responses.go new file mode 100644 index 0000000..5c10d67 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/create_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateUserProjectReader is a Reader for the CreateUserProject structure. +type CreateUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateUserProjectOK creates a CreateUserProjectOK with default headers values +func NewCreateUserProjectOK() *CreateUserProjectOK { + return &CreateUserProjectOK{} +} + +/* CreateUserProjectOK describes a response with status code 200, with default header values. + +CreateUserProjectOK create user project o k +*/ +type CreateUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserProjectOKBody +} + +// IsSuccess returns true when this create user project o k response has a 2xx status code +func (o *CreateUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create user project o k response has a 3xx status code +func (o *CreateUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create user project o k response has a 4xx status code +func (o *CreateUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create user project o k response has a 5xx status code +func (o *CreateUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create user project o k response a status code equal to that given +func (o *CreateUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateUserProjectOK) Error() string { + return fmt.Sprintf("[POST /user/projects][%d] createUserProjectOK %+v", 200, o.Payload) +} + +func (o *CreateUserProjectOK) String() string { + return fmt.Sprintf("[POST /user/projects][%d] createUserProjectOK %+v", 200, o.Payload) +} + +func (o *CreateUserProjectOK) GetPayload() *CreateUserProjectOKBody { + return o.Payload +} + +func (o *CreateUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateUserProjectDefault creates a CreateUserProjectDefault with default headers values +func NewCreateUserProjectDefault(code int) *CreateUserProjectDefault { + return &CreateUserProjectDefault{ + _statusCode: code, + } +} + +/* CreateUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserProjectDefaultBody +} + +// Code gets the status code for the create user project default response +func (o *CreateUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create user project default response has a 2xx status code +func (o *CreateUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create user project default response has a 3xx status code +func (o *CreateUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create user project default response has a 4xx status code +func (o *CreateUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create user project default response has a 5xx status code +func (o *CreateUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create user project default response a status code equal to that given +func (o *CreateUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateUserProjectDefault) Error() string { + return fmt.Sprintf("[POST /user/projects][%d] createUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserProjectDefault) String() string { + return fmt.Sprintf("[POST /user/projects][%d] createUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserProjectDefault) GetPayload() *CreateUserProjectDefaultBody { + return o.Payload +} + +func (o *CreateUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateUserProjectDefaultBody create user project default body +swagger:model CreateUserProjectDefaultBody +*/ +type CreateUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create user project default body +func (o *CreateUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user project default body based on the context it is used +func (o *CreateUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateUserProjectOKBody create user project o k body +swagger:model CreateUserProjectOKBody +*/ +type CreateUserProjectOKBody struct { + + // result + Result *models.ProjectID `json:"result,omitempty"` +} + +// Validate validates this create user project o k body +func (o *CreateUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user project o k body based on the context it is used +func (o *CreateUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res CreateUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/delete_user_project_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/delete_user_project_parameters.go new file mode 100644 index 0000000..161bf7f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/delete_user_project_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteUserProjectParams creates a new DeleteUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteUserProjectParams() *DeleteUserProjectParams { + return &DeleteUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteUserProjectParamsWithTimeout creates a new DeleteUserProjectParams object +// with the ability to set a timeout on a request. +func NewDeleteUserProjectParamsWithTimeout(timeout time.Duration) *DeleteUserProjectParams { + return &DeleteUserProjectParams{ + timeout: timeout, + } +} + +// NewDeleteUserProjectParamsWithContext creates a new DeleteUserProjectParams object +// with the ability to set a context for a request. +func NewDeleteUserProjectParamsWithContext(ctx context.Context) *DeleteUserProjectParams { + return &DeleteUserProjectParams{ + Context: ctx, + } +} + +// NewDeleteUserProjectParamsWithHTTPClient creates a new DeleteUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteUserProjectParamsWithHTTPClient(client *http.Client) *DeleteUserProjectParams { + return &DeleteUserProjectParams{ + HTTPClient: client, + } +} + +/* DeleteUserProjectParams contains all the parameters to send to the API endpoint + for the delete user project operation. + + Typically these are written to a http.Request. +*/ +type DeleteUserProjectParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserProjectParams) WithDefaults() *DeleteUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete user project params +func (o *DeleteUserProjectParams) WithTimeout(timeout time.Duration) *DeleteUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete user project params +func (o *DeleteUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete user project params +func (o *DeleteUserProjectParams) WithContext(ctx context.Context) *DeleteUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete user project params +func (o *DeleteUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete user project params +func (o *DeleteUserProjectParams) WithHTTPClient(client *http.Client) *DeleteUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete user project params +func (o *DeleteUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete user project params +func (o *DeleteUserProjectParams) WithAuthorization(authorization string) *DeleteUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete user project params +func (o *DeleteUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete user project params +func (o *DeleteUserProjectParams) WithBmpLanguage(bmpLanguage *string) *DeleteUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete user project params +func (o *DeleteUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete user project params +func (o *DeleteUserProjectParams) WithBmpUserID(bmpUserID *string) *DeleteUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete user project params +func (o *DeleteUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the delete user project params +func (o *DeleteUserProjectParams) WithProjectID(projectID string) *DeleteUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the delete user project params +func (o *DeleteUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the delete user project params +func (o *DeleteUserProjectParams) WithTraceID(traceID string) *DeleteUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete user project params +func (o *DeleteUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/delete_user_project_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/delete_user_project_responses.go new file mode 100644 index 0000000..1813aed --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/delete_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteUserProjectReader is a Reader for the DeleteUserProject structure. +type DeleteUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteUserProjectOK creates a DeleteUserProjectOK with default headers values +func NewDeleteUserProjectOK() *DeleteUserProjectOK { + return &DeleteUserProjectOK{} +} + +/* DeleteUserProjectOK describes a response with status code 200, with default header values. + +DeleteUserProjectOK delete user project o k +*/ +type DeleteUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserProjectOKBody +} + +// IsSuccess returns true when this delete user project o k response has a 2xx status code +func (o *DeleteUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete user project o k response has a 3xx status code +func (o *DeleteUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete user project o k response has a 4xx status code +func (o *DeleteUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete user project o k response has a 5xx status code +func (o *DeleteUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete user project o k response a status code equal to that given +func (o *DeleteUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteUserProjectOK) Error() string { + return fmt.Sprintf("[DELETE /user/projects/{project_id}][%d] deleteUserProjectOK %+v", 200, o.Payload) +} + +func (o *DeleteUserProjectOK) String() string { + return fmt.Sprintf("[DELETE /user/projects/{project_id}][%d] deleteUserProjectOK %+v", 200, o.Payload) +} + +func (o *DeleteUserProjectOK) GetPayload() *DeleteUserProjectOKBody { + return o.Payload +} + +func (o *DeleteUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteUserProjectDefault creates a DeleteUserProjectDefault with default headers values +func NewDeleteUserProjectDefault(code int) *DeleteUserProjectDefault { + return &DeleteUserProjectDefault{ + _statusCode: code, + } +} + +/* DeleteUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserProjectDefaultBody +} + +// Code gets the status code for the delete user project default response +func (o *DeleteUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete user project default response has a 2xx status code +func (o *DeleteUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete user project default response has a 3xx status code +func (o *DeleteUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete user project default response has a 4xx status code +func (o *DeleteUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete user project default response has a 5xx status code +func (o *DeleteUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete user project default response a status code equal to that given +func (o *DeleteUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteUserProjectDefault) Error() string { + return fmt.Sprintf("[DELETE /user/projects/{project_id}][%d] deleteUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserProjectDefault) String() string { + return fmt.Sprintf("[DELETE /user/projects/{project_id}][%d] deleteUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserProjectDefault) GetPayload() *DeleteUserProjectDefaultBody { + return o.Payload +} + +func (o *DeleteUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteUserProjectDefaultBody delete user project default body +swagger:model DeleteUserProjectDefaultBody +*/ +type DeleteUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete user project default body +func (o *DeleteUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user project default body based on the context it is used +func (o *DeleteUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteUserProjectOKBody delete user project o k body +swagger:model DeleteUserProjectOKBody +*/ +type DeleteUserProjectOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete user project o k body +func (o *DeleteUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user project o k body based on the context it is used +func (o *DeleteUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res DeleteUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_project_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_project_parameters.go new file mode 100644 index 0000000..3610ef7 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_project_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeUserProjectParams creates a new DescribeUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserProjectParams() *DescribeUserProjectParams { + return &DescribeUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserProjectParamsWithTimeout creates a new DescribeUserProjectParams object +// with the ability to set a timeout on a request. +func NewDescribeUserProjectParamsWithTimeout(timeout time.Duration) *DescribeUserProjectParams { + return &DescribeUserProjectParams{ + timeout: timeout, + } +} + +// NewDescribeUserProjectParamsWithContext creates a new DescribeUserProjectParams object +// with the ability to set a context for a request. +func NewDescribeUserProjectParamsWithContext(ctx context.Context) *DescribeUserProjectParams { + return &DescribeUserProjectParams{ + Context: ctx, + } +} + +// NewDescribeUserProjectParamsWithHTTPClient creates a new DescribeUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserProjectParamsWithHTTPClient(client *http.Client) *DescribeUserProjectParams { + return &DescribeUserProjectParams{ + HTTPClient: client, + } +} + +/* DescribeUserProjectParams contains all the parameters to send to the API endpoint + for the describe user project operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserProjectParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserProjectParams) WithDefaults() *DescribeUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user project params +func (o *DescribeUserProjectParams) WithTimeout(timeout time.Duration) *DescribeUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user project params +func (o *DescribeUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user project params +func (o *DescribeUserProjectParams) WithContext(ctx context.Context) *DescribeUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user project params +func (o *DescribeUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user project params +func (o *DescribeUserProjectParams) WithHTTPClient(client *http.Client) *DescribeUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user project params +func (o *DescribeUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user project params +func (o *DescribeUserProjectParams) WithAuthorization(authorization string) *DescribeUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user project params +func (o *DescribeUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user project params +func (o *DescribeUserProjectParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user project params +func (o *DescribeUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user project params +func (o *DescribeUserProjectParams) WithBmpUserID(bmpUserID *string) *DescribeUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user project params +func (o *DescribeUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the describe user project params +func (o *DescribeUserProjectParams) WithProjectID(projectID string) *DescribeUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the describe user project params +func (o *DescribeUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the describe user project params +func (o *DescribeUserProjectParams) WithTraceID(traceID string) *DescribeUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user project params +func (o *DescribeUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_project_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_project_responses.go new file mode 100644 index 0000000..48e1fa5 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserProjectReader is a Reader for the DescribeUserProject structure. +type DescribeUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserProjectOK creates a DescribeUserProjectOK with default headers values +func NewDescribeUserProjectOK() *DescribeUserProjectOK { + return &DescribeUserProjectOK{} +} + +/* DescribeUserProjectOK describes a response with status code 200, with default header values. + +DescribeUserProjectOK describe user project o k +*/ +type DescribeUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserProjectOKBody +} + +// IsSuccess returns true when this describe user project o k response has a 2xx status code +func (o *DescribeUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user project o k response has a 3xx status code +func (o *DescribeUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user project o k response has a 4xx status code +func (o *DescribeUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user project o k response has a 5xx status code +func (o *DescribeUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user project o k response a status code equal to that given +func (o *DescribeUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserProjectOK) Error() string { + return fmt.Sprintf("[GET /user/projects/{project_id}][%d] describeUserProjectOK %+v", 200, o.Payload) +} + +func (o *DescribeUserProjectOK) String() string { + return fmt.Sprintf("[GET /user/projects/{project_id}][%d] describeUserProjectOK %+v", 200, o.Payload) +} + +func (o *DescribeUserProjectOK) GetPayload() *DescribeUserProjectOKBody { + return o.Payload +} + +func (o *DescribeUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserProjectDefault creates a DescribeUserProjectDefault with default headers values +func NewDescribeUserProjectDefault(code int) *DescribeUserProjectDefault { + return &DescribeUserProjectDefault{ + _statusCode: code, + } +} + +/* DescribeUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserProjectDefaultBody +} + +// Code gets the status code for the describe user project default response +func (o *DescribeUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user project default response has a 2xx status code +func (o *DescribeUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user project default response has a 3xx status code +func (o *DescribeUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user project default response has a 4xx status code +func (o *DescribeUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user project default response has a 5xx status code +func (o *DescribeUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user project default response a status code equal to that given +func (o *DescribeUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserProjectDefault) Error() string { + return fmt.Sprintf("[GET /user/projects/{project_id}][%d] describeUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserProjectDefault) String() string { + return fmt.Sprintf("[GET /user/projects/{project_id}][%d] describeUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserProjectDefault) GetPayload() *DescribeUserProjectDefaultBody { + return o.Payload +} + +func (o *DescribeUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserProjectDefaultBody describe user project default body +swagger:model DescribeUserProjectDefaultBody +*/ +type DescribeUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user project default body +func (o *DescribeUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user project default body based on the context it is used +func (o *DescribeUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserProjectOKBody describe user project o k body +swagger:model DescribeUserProjectOKBody +*/ +type DescribeUserProjectOKBody struct { + + // result + Result *models.ProjectInfo `json:"result,omitempty"` +} + +// Validate validates this describe user project o k body +func (o *DescribeUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user project o k body based on the context it is used +func (o *DescribeUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_projects_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_projects_parameters.go new file mode 100644 index 0000000..1a25ce1 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_projects_parameters.go @@ -0,0 +1,392 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeUserProjectsParams creates a new DescribeUserProjectsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserProjectsParams() *DescribeUserProjectsParams { + return &DescribeUserProjectsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserProjectsParamsWithTimeout creates a new DescribeUserProjectsParams object +// with the ability to set a timeout on a request. +func NewDescribeUserProjectsParamsWithTimeout(timeout time.Duration) *DescribeUserProjectsParams { + return &DescribeUserProjectsParams{ + timeout: timeout, + } +} + +// NewDescribeUserProjectsParamsWithContext creates a new DescribeUserProjectsParams object +// with the ability to set a context for a request. +func NewDescribeUserProjectsParamsWithContext(ctx context.Context) *DescribeUserProjectsParams { + return &DescribeUserProjectsParams{ + Context: ctx, + } +} + +// NewDescribeUserProjectsParamsWithHTTPClient creates a new DescribeUserProjectsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserProjectsParamsWithHTTPClient(client *http.Client) *DescribeUserProjectsParams { + return &DescribeUserProjectsParams{ + HTTPClient: client, + } +} + +/* DescribeUserProjectsParams contains all the parameters to send to the API endpoint + for the describe user projects operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserProjectsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // IsAll. + IsAll *string + + // Owned. + // + // Format: int64 + Owned *int64 + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* ProjectName. + + 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + */ + ProjectName *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user projects params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserProjectsParams) WithDefaults() *DescribeUserProjectsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user projects params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserProjectsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user projects params +func (o *DescribeUserProjectsParams) WithTimeout(timeout time.Duration) *DescribeUserProjectsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user projects params +func (o *DescribeUserProjectsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user projects params +func (o *DescribeUserProjectsParams) WithContext(ctx context.Context) *DescribeUserProjectsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user projects params +func (o *DescribeUserProjectsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user projects params +func (o *DescribeUserProjectsParams) WithHTTPClient(client *http.Client) *DescribeUserProjectsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user projects params +func (o *DescribeUserProjectsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user projects params +func (o *DescribeUserProjectsParams) WithAuthorization(authorization string) *DescribeUserProjectsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user projects params +func (o *DescribeUserProjectsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user projects params +func (o *DescribeUserProjectsParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserProjectsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user projects params +func (o *DescribeUserProjectsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user projects params +func (o *DescribeUserProjectsParams) WithBmpUserID(bmpUserID *string) *DescribeUserProjectsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user projects params +func (o *DescribeUserProjectsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe user projects params +func (o *DescribeUserProjectsParams) WithIsAll(isAll *string) *DescribeUserProjectsParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe user projects params +func (o *DescribeUserProjectsParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithOwned adds the owned to the describe user projects params +func (o *DescribeUserProjectsParams) WithOwned(owned *int64) *DescribeUserProjectsParams { + o.SetOwned(owned) + return o +} + +// SetOwned adds the owned to the describe user projects params +func (o *DescribeUserProjectsParams) SetOwned(owned *int64) { + o.Owned = owned +} + +// WithPageNumber adds the pageNumber to the describe user projects params +func (o *DescribeUserProjectsParams) WithPageNumber(pageNumber *int64) *DescribeUserProjectsParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe user projects params +func (o *DescribeUserProjectsParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe user projects params +func (o *DescribeUserProjectsParams) WithPageSize(pageSize *int64) *DescribeUserProjectsParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe user projects params +func (o *DescribeUserProjectsParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithProjectName adds the projectName to the describe user projects params +func (o *DescribeUserProjectsParams) WithProjectName(projectName *string) *DescribeUserProjectsParams { + o.SetProjectName(projectName) + return o +} + +// SetProjectName adds the projectName to the describe user projects params +func (o *DescribeUserProjectsParams) SetProjectName(projectName *string) { + o.ProjectName = projectName +} + +// WithTraceID adds the traceID to the describe user projects params +func (o *DescribeUserProjectsParams) WithTraceID(traceID string) *DescribeUserProjectsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user projects params +func (o *DescribeUserProjectsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserProjectsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Owned != nil { + + // query param owned + var qrOwned int64 + + if o.Owned != nil { + qrOwned = *o.Owned + } + qOwned := swag.FormatInt64(qrOwned) + if qOwned != "" { + + if err := r.SetQueryParam("owned", qOwned); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.ProjectName != nil { + + // query param projectName + var qrProjectName string + + if o.ProjectName != nil { + qrProjectName = *o.ProjectName + } + qProjectName := qrProjectName + if qProjectName != "" { + + if err := r.SetQueryParam("projectName", qProjectName); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_projects_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_projects_responses.go new file mode 100644 index 0000000..82f3fb5 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/describe_user_projects_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserProjectsReader is a Reader for the DescribeUserProjects structure. +type DescribeUserProjectsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserProjectsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserProjectsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserProjectsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserProjectsOK creates a DescribeUserProjectsOK with default headers values +func NewDescribeUserProjectsOK() *DescribeUserProjectsOK { + return &DescribeUserProjectsOK{} +} + +/* DescribeUserProjectsOK describes a response with status code 200, with default header values. + +DescribeUserProjectsOK describe user projects o k +*/ +type DescribeUserProjectsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserProjectsOKBody +} + +// IsSuccess returns true when this describe user projects o k response has a 2xx status code +func (o *DescribeUserProjectsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user projects o k response has a 3xx status code +func (o *DescribeUserProjectsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user projects o k response has a 4xx status code +func (o *DescribeUserProjectsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user projects o k response has a 5xx status code +func (o *DescribeUserProjectsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user projects o k response a status code equal to that given +func (o *DescribeUserProjectsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserProjectsOK) Error() string { + return fmt.Sprintf("[GET /user/projects][%d] describeUserProjectsOK %+v", 200, o.Payload) +} + +func (o *DescribeUserProjectsOK) String() string { + return fmt.Sprintf("[GET /user/projects][%d] describeUserProjectsOK %+v", 200, o.Payload) +} + +func (o *DescribeUserProjectsOK) GetPayload() *DescribeUserProjectsOKBody { + return o.Payload +} + +func (o *DescribeUserProjectsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserProjectsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserProjectsDefault creates a DescribeUserProjectsDefault with default headers values +func NewDescribeUserProjectsDefault(code int) *DescribeUserProjectsDefault { + return &DescribeUserProjectsDefault{ + _statusCode: code, + } +} + +/* DescribeUserProjectsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserProjectsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserProjectsDefaultBody +} + +// Code gets the status code for the describe user projects default response +func (o *DescribeUserProjectsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user projects default response has a 2xx status code +func (o *DescribeUserProjectsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user projects default response has a 3xx status code +func (o *DescribeUserProjectsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user projects default response has a 4xx status code +func (o *DescribeUserProjectsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user projects default response has a 5xx status code +func (o *DescribeUserProjectsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user projects default response a status code equal to that given +func (o *DescribeUserProjectsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserProjectsDefault) Error() string { + return fmt.Sprintf("[GET /user/projects][%d] describeUserProjects default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserProjectsDefault) String() string { + return fmt.Sprintf("[GET /user/projects][%d] describeUserProjects default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserProjectsDefault) GetPayload() *DescribeUserProjectsDefaultBody { + return o.Payload +} + +func (o *DescribeUserProjectsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserProjectsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserProjectsDefaultBody describe user projects default body +swagger:model DescribeUserProjectsDefaultBody +*/ +type DescribeUserProjectsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user projects default body +func (o *DescribeUserProjectsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserProjects default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserProjectsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserProjects default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjects default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjects default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user projects default body based on the context it is used +func (o *DescribeUserProjectsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjects default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjects default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserProjectsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserProjectsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserProjectsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserProjectsOKBody describe user projects o k body +swagger:model DescribeUserProjectsOKBody +*/ +type DescribeUserProjectsOKBody struct { + + // result + Result *models.ProjectList `json:"result,omitempty"` +} + +// Validate validates this describe user projects o k body +func (o *DescribeUserProjectsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjectsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjectsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user projects o k body based on the context it is used +func (o *DescribeUserProjectsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserProjectsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserProjectsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserProjectsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserProjectsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserProjectsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserProjectsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/modify_user_project_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/modify_user_project_parameters.go new file mode 100644 index 0000000..cfe9859 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/modify_user_project_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyUserProjectParams creates a new ModifyUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyUserProjectParams() *ModifyUserProjectParams { + return &ModifyUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyUserProjectParamsWithTimeout creates a new ModifyUserProjectParams object +// with the ability to set a timeout on a request. +func NewModifyUserProjectParamsWithTimeout(timeout time.Duration) *ModifyUserProjectParams { + return &ModifyUserProjectParams{ + timeout: timeout, + } +} + +// NewModifyUserProjectParamsWithContext creates a new ModifyUserProjectParams object +// with the ability to set a context for a request. +func NewModifyUserProjectParamsWithContext(ctx context.Context) *ModifyUserProjectParams { + return &ModifyUserProjectParams{ + Context: ctx, + } +} + +// NewModifyUserProjectParamsWithHTTPClient creates a new ModifyUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyUserProjectParamsWithHTTPClient(client *http.Client) *ModifyUserProjectParams { + return &ModifyUserProjectParams{ + HTTPClient: client, + } +} + +/* ModifyUserProjectParams contains all the parameters to send to the API endpoint + for the modify user project operation. + + Typically these are written to a http.Request. +*/ +type ModifyUserProjectParams struct { + + // Body. + Body *models.ModifyProjectRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserProjectParams) WithDefaults() *ModifyUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify user project params +func (o *ModifyUserProjectParams) WithTimeout(timeout time.Duration) *ModifyUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify user project params +func (o *ModifyUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify user project params +func (o *ModifyUserProjectParams) WithContext(ctx context.Context) *ModifyUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify user project params +func (o *ModifyUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify user project params +func (o *ModifyUserProjectParams) WithHTTPClient(client *http.Client) *ModifyUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify user project params +func (o *ModifyUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify user project params +func (o *ModifyUserProjectParams) WithBody(body *models.ModifyProjectRequest) *ModifyUserProjectParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify user project params +func (o *ModifyUserProjectParams) SetBody(body *models.ModifyProjectRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify user project params +func (o *ModifyUserProjectParams) WithAuthorization(authorization string) *ModifyUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify user project params +func (o *ModifyUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify user project params +func (o *ModifyUserProjectParams) WithBmpLanguage(bmpLanguage *string) *ModifyUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify user project params +func (o *ModifyUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify user project params +func (o *ModifyUserProjectParams) WithBmpUserID(bmpUserID *string) *ModifyUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify user project params +func (o *ModifyUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the modify user project params +func (o *ModifyUserProjectParams) WithProjectID(projectID string) *ModifyUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the modify user project params +func (o *ModifyUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the modify user project params +func (o *ModifyUserProjectParams) WithTraceID(traceID string) *ModifyUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify user project params +func (o *ModifyUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/modify_user_project_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/modify_user_project_responses.go new file mode 100644 index 0000000..8f83a32 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/modify_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyUserProjectReader is a Reader for the ModifyUserProject structure. +type ModifyUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyUserProjectOK creates a ModifyUserProjectOK with default headers values +func NewModifyUserProjectOK() *ModifyUserProjectOK { + return &ModifyUserProjectOK{} +} + +/* ModifyUserProjectOK describes a response with status code 200, with default header values. + +ModifyUserProjectOK modify user project o k +*/ +type ModifyUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserProjectOKBody +} + +// IsSuccess returns true when this modify user project o k response has a 2xx status code +func (o *ModifyUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify user project o k response has a 3xx status code +func (o *ModifyUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify user project o k response has a 4xx status code +func (o *ModifyUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify user project o k response has a 5xx status code +func (o *ModifyUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify user project o k response a status code equal to that given +func (o *ModifyUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyUserProjectOK) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}][%d] modifyUserProjectOK %+v", 200, o.Payload) +} + +func (o *ModifyUserProjectOK) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}][%d] modifyUserProjectOK %+v", 200, o.Payload) +} + +func (o *ModifyUserProjectOK) GetPayload() *ModifyUserProjectOKBody { + return o.Payload +} + +func (o *ModifyUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyUserProjectDefault creates a ModifyUserProjectDefault with default headers values +func NewModifyUserProjectDefault(code int) *ModifyUserProjectDefault { + return &ModifyUserProjectDefault{ + _statusCode: code, + } +} + +/* ModifyUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserProjectDefaultBody +} + +// Code gets the status code for the modify user project default response +func (o *ModifyUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify user project default response has a 2xx status code +func (o *ModifyUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify user project default response has a 3xx status code +func (o *ModifyUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify user project default response has a 4xx status code +func (o *ModifyUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify user project default response has a 5xx status code +func (o *ModifyUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify user project default response a status code equal to that given +func (o *ModifyUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyUserProjectDefault) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}][%d] modifyUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserProjectDefault) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}][%d] modifyUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserProjectDefault) GetPayload() *ModifyUserProjectDefaultBody { + return o.Payload +} + +func (o *ModifyUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyUserProjectDefaultBody modify user project default body +swagger:model ModifyUserProjectDefaultBody +*/ +type ModifyUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify user project default body +func (o *ModifyUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user project default body based on the context it is used +func (o *ModifyUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyUserProjectOKBody modify user project o k body +swagger:model ModifyUserProjectOKBody +*/ +type ModifyUserProjectOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify user project o k body +func (o *ModifyUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user project o k body based on the context it is used +func (o *ModifyUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res ModifyUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/project_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/project_client.go new file mode 100644 index 0000000..c886e48 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/project_client.go @@ -0,0 +1,317 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new project API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for project API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CancelShareUserProject(params *CancelShareUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CancelShareUserProjectOK, error) + + CreateUserProject(params *CreateUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserProjectOK, error) + + DeleteUserProject(params *DeleteUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserProjectOK, error) + + DescribeUserProject(params *DescribeUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserProjectOK, error) + + DescribeUserProjects(params *DescribeUserProjectsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserProjectsOK, error) + + ModifyUserProject(params *ModifyUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserProjectOK, error) + + ShareUserProject(params *ShareUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ShareUserProjectOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CancelShareUserProject CancelShareUserProject 取消共享项目 +*/ +func (a *Client) CancelShareUserProject(params *CancelShareUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CancelShareUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCancelShareUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "cancelShareUserProject", + Method: "PUT", + PathPattern: "/user/projects/{project_id}/cancelShare", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CancelShareUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CancelShareUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CancelShareUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + CreateUserProject CreateUserProject 创建项目 +*/ +func (a *Client) CreateUserProject(params *CreateUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "createUserProject", + Method: "POST", + PathPattern: "/user/projects", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteUserProject DeleteUserProject 删除项目 +*/ +func (a *Client) DeleteUserProject(params *DeleteUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "deleteUserProject", + Method: "DELETE", + PathPattern: "/user/projects/{project_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserProject DescribeUserProject 获取项目详情 +*/ +func (a *Client) DescribeUserProject(params *DescribeUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserProject", + Method: "GET", + PathPattern: "/user/projects/{project_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserProjects DescribeUserProjects 获取项目列表 +*/ +func (a *Client) DescribeUserProjects(params *DescribeUserProjectsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserProjectsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserProjectsParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserProjects", + Method: "GET", + PathPattern: "/user/projects", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserProjectsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserProjectsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserProjectsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyUserProject ModifyUserProject 修改项目信息 +*/ +func (a *Client) ModifyUserProject(params *ModifyUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "modifyUserProject", + Method: "PUT", + PathPattern: "/user/projects/{project_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ShareUserProject ShareUserProject 共享项目 +*/ +func (a *Client) ShareUserProject(params *ShareUserProjectParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ShareUserProjectOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewShareUserProjectParams() + } + op := &runtime.ClientOperation{ + ID: "shareUserProject", + Method: "PUT", + PathPattern: "/user/projects/{project_id}/share", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ShareUserProjectReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ShareUserProjectOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ShareUserProjectDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/share_user_project_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/share_user_project_parameters.go new file mode 100644 index 0000000..f831800 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/share_user_project_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewShareUserProjectParams creates a new ShareUserProjectParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewShareUserProjectParams() *ShareUserProjectParams { + return &ShareUserProjectParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewShareUserProjectParamsWithTimeout creates a new ShareUserProjectParams object +// with the ability to set a timeout on a request. +func NewShareUserProjectParamsWithTimeout(timeout time.Duration) *ShareUserProjectParams { + return &ShareUserProjectParams{ + timeout: timeout, + } +} + +// NewShareUserProjectParamsWithContext creates a new ShareUserProjectParams object +// with the ability to set a context for a request. +func NewShareUserProjectParamsWithContext(ctx context.Context) *ShareUserProjectParams { + return &ShareUserProjectParams{ + Context: ctx, + } +} + +// NewShareUserProjectParamsWithHTTPClient creates a new ShareUserProjectParams object +// with the ability to set a custom HTTPClient for a request. +func NewShareUserProjectParamsWithHTTPClient(client *http.Client) *ShareUserProjectParams { + return &ShareUserProjectParams{ + HTTPClient: client, + } +} + +/* ShareUserProjectParams contains all the parameters to send to the API endpoint + for the share user project operation. + + Typically these are written to a http.Request. +*/ +type ShareUserProjectParams struct { + + // Body. + Body *models.ShareProjectRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // ProjectID. + ProjectID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the share user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ShareUserProjectParams) WithDefaults() *ShareUserProjectParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the share user project params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ShareUserProjectParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the share user project params +func (o *ShareUserProjectParams) WithTimeout(timeout time.Duration) *ShareUserProjectParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the share user project params +func (o *ShareUserProjectParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the share user project params +func (o *ShareUserProjectParams) WithContext(ctx context.Context) *ShareUserProjectParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the share user project params +func (o *ShareUserProjectParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the share user project params +func (o *ShareUserProjectParams) WithHTTPClient(client *http.Client) *ShareUserProjectParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the share user project params +func (o *ShareUserProjectParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the share user project params +func (o *ShareUserProjectParams) WithBody(body *models.ShareProjectRequest) *ShareUserProjectParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the share user project params +func (o *ShareUserProjectParams) SetBody(body *models.ShareProjectRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the share user project params +func (o *ShareUserProjectParams) WithAuthorization(authorization string) *ShareUserProjectParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the share user project params +func (o *ShareUserProjectParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the share user project params +func (o *ShareUserProjectParams) WithBmpLanguage(bmpLanguage *string) *ShareUserProjectParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the share user project params +func (o *ShareUserProjectParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the share user project params +func (o *ShareUserProjectParams) WithBmpUserID(bmpUserID *string) *ShareUserProjectParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the share user project params +func (o *ShareUserProjectParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithProjectID adds the projectID to the share user project params +func (o *ShareUserProjectParams) WithProjectID(projectID string) *ShareUserProjectParams { + o.SetProjectID(projectID) + return o +} + +// SetProjectID adds the projectId to the share user project params +func (o *ShareUserProjectParams) SetProjectID(projectID string) { + o.ProjectID = projectID +} + +// WithTraceID adds the traceID to the share user project params +func (o *ShareUserProjectParams) WithTraceID(traceID string) *ShareUserProjectParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the share user project params +func (o *ShareUserProjectParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ShareUserProjectParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param project_id + if err := r.SetPathParam("project_id", o.ProjectID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/share_user_project_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/share_user_project_responses.go new file mode 100644 index 0000000..1ff7c2b --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/project/share_user_project_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package project + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ShareUserProjectReader is a Reader for the ShareUserProject structure. +type ShareUserProjectReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ShareUserProjectReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewShareUserProjectOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewShareUserProjectDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewShareUserProjectOK creates a ShareUserProjectOK with default headers values +func NewShareUserProjectOK() *ShareUserProjectOK { + return &ShareUserProjectOK{} +} + +/* ShareUserProjectOK describes a response with status code 200, with default header values. + +A ShareUserProjectResult is an response struct +*/ +type ShareUserProjectOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ShareUserProjectOKBody +} + +// IsSuccess returns true when this share user project o k response has a 2xx status code +func (o *ShareUserProjectOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this share user project o k response has a 3xx status code +func (o *ShareUserProjectOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this share user project o k response has a 4xx status code +func (o *ShareUserProjectOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this share user project o k response has a 5xx status code +func (o *ShareUserProjectOK) IsServerError() bool { + return false +} + +// IsCode returns true when this share user project o k response a status code equal to that given +func (o *ShareUserProjectOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ShareUserProjectOK) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/share][%d] shareUserProjectOK %+v", 200, o.Payload) +} + +func (o *ShareUserProjectOK) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/share][%d] shareUserProjectOK %+v", 200, o.Payload) +} + +func (o *ShareUserProjectOK) GetPayload() *ShareUserProjectOKBody { + return o.Payload +} + +func (o *ShareUserProjectOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ShareUserProjectOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewShareUserProjectDefault creates a ShareUserProjectDefault with default headers values +func NewShareUserProjectDefault(code int) *ShareUserProjectDefault { + return &ShareUserProjectDefault{ + _statusCode: code, + } +} + +/* ShareUserProjectDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ShareUserProjectDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ShareUserProjectDefaultBody +} + +// Code gets the status code for the share user project default response +func (o *ShareUserProjectDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this share user project default response has a 2xx status code +func (o *ShareUserProjectDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this share user project default response has a 3xx status code +func (o *ShareUserProjectDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this share user project default response has a 4xx status code +func (o *ShareUserProjectDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this share user project default response has a 5xx status code +func (o *ShareUserProjectDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this share user project default response a status code equal to that given +func (o *ShareUserProjectDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ShareUserProjectDefault) Error() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/share][%d] shareUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *ShareUserProjectDefault) String() string { + return fmt.Sprintf("[PUT /user/projects/{project_id}/share][%d] shareUserProject default %+v", o._statusCode, o.Payload) +} + +func (o *ShareUserProjectDefault) GetPayload() *ShareUserProjectDefaultBody { + return o.Payload +} + +func (o *ShareUserProjectDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ShareUserProjectDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ShareUserProjectDefaultBody share user project default body +swagger:model ShareUserProjectDefaultBody +*/ +type ShareUserProjectDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this share user project default body +func (o *ShareUserProjectDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ShareUserProjectDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("shareUserProject default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ShareUserProjectDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("shareUserProject default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this share user project default body based on the context it is used +func (o *ShareUserProjectDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ShareUserProjectDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareUserProject default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareUserProject default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ShareUserProjectDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ShareUserProjectDefaultBody) UnmarshalBinary(b []byte) error { + var res ShareUserProjectDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ShareUserProjectOKBody share user project o k body +swagger:model ShareUserProjectOKBody +*/ +type ShareUserProjectOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this share user project o k body +func (o *ShareUserProjectOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ShareUserProjectOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this share user project o k body based on the context it is used +func (o *ShareUserProjectOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ShareUserProjectOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareUserProjectOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareUserProjectOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ShareUserProjectOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ShareUserProjectOKBody) UnmarshalBinary(b []byte) error { + var res ShareUserProjectOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/create_device_type_raid_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/create_device_type_raid_parameters.go new file mode 100644 index 0000000..cda10a7 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/create_device_type_raid_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateDeviceTypeRaidParams creates a new CreateDeviceTypeRaidParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateDeviceTypeRaidParams() *CreateDeviceTypeRaidParams { + return &CreateDeviceTypeRaidParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateDeviceTypeRaidParamsWithTimeout creates a new CreateDeviceTypeRaidParams object +// with the ability to set a timeout on a request. +func NewCreateDeviceTypeRaidParamsWithTimeout(timeout time.Duration) *CreateDeviceTypeRaidParams { + return &CreateDeviceTypeRaidParams{ + timeout: timeout, + } +} + +// NewCreateDeviceTypeRaidParamsWithContext creates a new CreateDeviceTypeRaidParams object +// with the ability to set a context for a request. +func NewCreateDeviceTypeRaidParamsWithContext(ctx context.Context) *CreateDeviceTypeRaidParams { + return &CreateDeviceTypeRaidParams{ + Context: ctx, + } +} + +// NewCreateDeviceTypeRaidParamsWithHTTPClient creates a new CreateDeviceTypeRaidParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateDeviceTypeRaidParamsWithHTTPClient(client *http.Client) *CreateDeviceTypeRaidParams { + return &CreateDeviceTypeRaidParams{ + HTTPClient: client, + } +} + +/* CreateDeviceTypeRaidParams contains all the parameters to send to the API endpoint + for the create device type raid operation. + + Typically these are written to a http.Request. +*/ +type CreateDeviceTypeRaidParams struct { + + // Body. + Body *models.CreateDeviceTypeRaidRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create device type raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateDeviceTypeRaidParams) WithDefaults() *CreateDeviceTypeRaidParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create device type raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateDeviceTypeRaidParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithTimeout(timeout time.Duration) *CreateDeviceTypeRaidParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithContext(ctx context.Context) *CreateDeviceTypeRaidParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithHTTPClient(client *http.Client) *CreateDeviceTypeRaidParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithBody(body *models.CreateDeviceTypeRaidRequest) *CreateDeviceTypeRaidParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetBody(body *models.CreateDeviceTypeRaidRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithAuthorization(authorization string) *CreateDeviceTypeRaidParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithBmpLanguage(bmpLanguage *string) *CreateDeviceTypeRaidParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithBmpUserID(bmpUserID *string) *CreateDeviceTypeRaidParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create device type raid params +func (o *CreateDeviceTypeRaidParams) WithTraceID(traceID string) *CreateDeviceTypeRaidParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create device type raid params +func (o *CreateDeviceTypeRaidParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateDeviceTypeRaidParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/create_device_type_raid_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/create_device_type_raid_responses.go new file mode 100644 index 0000000..c1c691e --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/create_device_type_raid_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateDeviceTypeRaidReader is a Reader for the CreateDeviceTypeRaid structure. +type CreateDeviceTypeRaidReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateDeviceTypeRaidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateDeviceTypeRaidOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateDeviceTypeRaidDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateDeviceTypeRaidOK creates a CreateDeviceTypeRaidOK with default headers values +func NewCreateDeviceTypeRaidOK() *CreateDeviceTypeRaidOK { + return &CreateDeviceTypeRaidOK{} +} + +/* CreateDeviceTypeRaidOK describes a response with status code 200, with default header values. + +A CreateDeviceTypeRaidResult is an response struct that is used to describe create device type raid result. +*/ +type CreateDeviceTypeRaidOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateDeviceTypeRaidOKBody +} + +// IsSuccess returns true when this create device type raid o k response has a 2xx status code +func (o *CreateDeviceTypeRaidOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create device type raid o k response has a 3xx status code +func (o *CreateDeviceTypeRaidOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create device type raid o k response has a 4xx status code +func (o *CreateDeviceTypeRaidOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create device type raid o k response has a 5xx status code +func (o *CreateDeviceTypeRaidOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create device type raid o k response a status code equal to that given +func (o *CreateDeviceTypeRaidOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateDeviceTypeRaidOK) Error() string { + return fmt.Sprintf("[POST /raids/deviceTypeRaid][%d] createDeviceTypeRaidOK %+v", 200, o.Payload) +} + +func (o *CreateDeviceTypeRaidOK) String() string { + return fmt.Sprintf("[POST /raids/deviceTypeRaid][%d] createDeviceTypeRaidOK %+v", 200, o.Payload) +} + +func (o *CreateDeviceTypeRaidOK) GetPayload() *CreateDeviceTypeRaidOKBody { + return o.Payload +} + +func (o *CreateDeviceTypeRaidOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateDeviceTypeRaidOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateDeviceTypeRaidDefault creates a CreateDeviceTypeRaidDefault with default headers values +func NewCreateDeviceTypeRaidDefault(code int) *CreateDeviceTypeRaidDefault { + return &CreateDeviceTypeRaidDefault{ + _statusCode: code, + } +} + +/* CreateDeviceTypeRaidDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateDeviceTypeRaidDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateDeviceTypeRaidDefaultBody +} + +// Code gets the status code for the create device type raid default response +func (o *CreateDeviceTypeRaidDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create device type raid default response has a 2xx status code +func (o *CreateDeviceTypeRaidDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create device type raid default response has a 3xx status code +func (o *CreateDeviceTypeRaidDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create device type raid default response has a 4xx status code +func (o *CreateDeviceTypeRaidDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create device type raid default response has a 5xx status code +func (o *CreateDeviceTypeRaidDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create device type raid default response a status code equal to that given +func (o *CreateDeviceTypeRaidDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateDeviceTypeRaidDefault) Error() string { + return fmt.Sprintf("[POST /raids/deviceTypeRaid][%d] createDeviceTypeRaid default %+v", o._statusCode, o.Payload) +} + +func (o *CreateDeviceTypeRaidDefault) String() string { + return fmt.Sprintf("[POST /raids/deviceTypeRaid][%d] createDeviceTypeRaid default %+v", o._statusCode, o.Payload) +} + +func (o *CreateDeviceTypeRaidDefault) GetPayload() *CreateDeviceTypeRaidDefaultBody { + return o.Payload +} + +func (o *CreateDeviceTypeRaidDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateDeviceTypeRaidDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateDeviceTypeRaidDefaultBody create device type raid default body +swagger:model CreateDeviceTypeRaidDefaultBody +*/ +type CreateDeviceTypeRaidDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create device type raid default body +func (o *CreateDeviceTypeRaidDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeRaidDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createDeviceTypeRaid default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateDeviceTypeRaidDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createDeviceTypeRaid default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceTypeRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceTypeRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create device type raid default body based on the context it is used +func (o *CreateDeviceTypeRaidDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeRaidDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceTypeRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceTypeRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateDeviceTypeRaidDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateDeviceTypeRaidDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateDeviceTypeRaidDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateDeviceTypeRaidOKBody create device type raid o k body +swagger:model CreateDeviceTypeRaidOKBody +*/ +type CreateDeviceTypeRaidOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this create device type raid o k body +func (o *CreateDeviceTypeRaidOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeRaidOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceTypeRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceTypeRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create device type raid o k body based on the context it is used +func (o *CreateDeviceTypeRaidOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateDeviceTypeRaidOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createDeviceTypeRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createDeviceTypeRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateDeviceTypeRaidOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateDeviceTypeRaidOKBody) UnmarshalBinary(b []byte) error { + var res CreateDeviceTypeRaidOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/create_raid_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/create_raid_parameters.go new file mode 100644 index 0000000..3af01df --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/create_raid_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateRaidParams creates a new CreateRaidParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateRaidParams() *CreateRaidParams { + return &CreateRaidParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateRaidParamsWithTimeout creates a new CreateRaidParams object +// with the ability to set a timeout on a request. +func NewCreateRaidParamsWithTimeout(timeout time.Duration) *CreateRaidParams { + return &CreateRaidParams{ + timeout: timeout, + } +} + +// NewCreateRaidParamsWithContext creates a new CreateRaidParams object +// with the ability to set a context for a request. +func NewCreateRaidParamsWithContext(ctx context.Context) *CreateRaidParams { + return &CreateRaidParams{ + Context: ctx, + } +} + +// NewCreateRaidParamsWithHTTPClient creates a new CreateRaidParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateRaidParamsWithHTTPClient(client *http.Client) *CreateRaidParams { + return &CreateRaidParams{ + HTTPClient: client, + } +} + +/* CreateRaidParams contains all the parameters to send to the API endpoint + for the create raid operation. + + Typically these are written to a http.Request. +*/ +type CreateRaidParams struct { + + // Body. + Body *models.CreateRaidRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateRaidParams) WithDefaults() *CreateRaidParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateRaidParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create raid params +func (o *CreateRaidParams) WithTimeout(timeout time.Duration) *CreateRaidParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create raid params +func (o *CreateRaidParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create raid params +func (o *CreateRaidParams) WithContext(ctx context.Context) *CreateRaidParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create raid params +func (o *CreateRaidParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create raid params +func (o *CreateRaidParams) WithHTTPClient(client *http.Client) *CreateRaidParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create raid params +func (o *CreateRaidParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create raid params +func (o *CreateRaidParams) WithBody(body *models.CreateRaidRequest) *CreateRaidParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create raid params +func (o *CreateRaidParams) SetBody(body *models.CreateRaidRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create raid params +func (o *CreateRaidParams) WithAuthorization(authorization string) *CreateRaidParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create raid params +func (o *CreateRaidParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create raid params +func (o *CreateRaidParams) WithBmpLanguage(bmpLanguage *string) *CreateRaidParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create raid params +func (o *CreateRaidParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create raid params +func (o *CreateRaidParams) WithBmpUserID(bmpUserID *string) *CreateRaidParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create raid params +func (o *CreateRaidParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create raid params +func (o *CreateRaidParams) WithTraceID(traceID string) *CreateRaidParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create raid params +func (o *CreateRaidParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateRaidParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/create_raid_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/create_raid_responses.go new file mode 100644 index 0000000..7e4b5cd --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/create_raid_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateRaidReader is a Reader for the CreateRaid structure. +type CreateRaidReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateRaidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateRaidOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateRaidDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateRaidOK creates a CreateRaidOK with default headers values +func NewCreateRaidOK() *CreateRaidOK { + return &CreateRaidOK{} +} + +/* CreateRaidOK describes a response with status code 200, with default header values. + +A CreateRaidResult is an response struct that is used to describe create raid result. +*/ +type CreateRaidOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateRaidOKBody +} + +// IsSuccess returns true when this create raid o k response has a 2xx status code +func (o *CreateRaidOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create raid o k response has a 3xx status code +func (o *CreateRaidOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create raid o k response has a 4xx status code +func (o *CreateRaidOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create raid o k response has a 5xx status code +func (o *CreateRaidOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create raid o k response a status code equal to that given +func (o *CreateRaidOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateRaidOK) Error() string { + return fmt.Sprintf("[POST /raids][%d] createRaidOK %+v", 200, o.Payload) +} + +func (o *CreateRaidOK) String() string { + return fmt.Sprintf("[POST /raids][%d] createRaidOK %+v", 200, o.Payload) +} + +func (o *CreateRaidOK) GetPayload() *CreateRaidOKBody { + return o.Payload +} + +func (o *CreateRaidOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateRaidOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateRaidDefault creates a CreateRaidDefault with default headers values +func NewCreateRaidDefault(code int) *CreateRaidDefault { + return &CreateRaidDefault{ + _statusCode: code, + } +} + +/* CreateRaidDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateRaidDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateRaidDefaultBody +} + +// Code gets the status code for the create raid default response +func (o *CreateRaidDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create raid default response has a 2xx status code +func (o *CreateRaidDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create raid default response has a 3xx status code +func (o *CreateRaidDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create raid default response has a 4xx status code +func (o *CreateRaidDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create raid default response has a 5xx status code +func (o *CreateRaidDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create raid default response a status code equal to that given +func (o *CreateRaidDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateRaidDefault) Error() string { + return fmt.Sprintf("[POST /raids][%d] createRaid default %+v", o._statusCode, o.Payload) +} + +func (o *CreateRaidDefault) String() string { + return fmt.Sprintf("[POST /raids][%d] createRaid default %+v", o._statusCode, o.Payload) +} + +func (o *CreateRaidDefault) GetPayload() *CreateRaidDefaultBody { + return o.Payload +} + +func (o *CreateRaidDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateRaidDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateRaidDefaultBody create raid default body +swagger:model CreateRaidDefaultBody +*/ +type CreateRaidDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create raid default body +func (o *CreateRaidDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRaidDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createRaid default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateRaidDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createRaid default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create raid default body based on the context it is used +func (o *CreateRaidDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRaidDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateRaidDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateRaidDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateRaidDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateRaidOKBody create raid o k body +swagger:model CreateRaidOKBody +*/ +type CreateRaidOKBody struct { + + // result + Result *models.RaidID `json:"result,omitempty"` +} + +// Validate validates this create raid o k body +func (o *CreateRaidOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRaidOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create raid o k body based on the context it is used +func (o *CreateRaidOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRaidOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateRaidOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateRaidOKBody) UnmarshalBinary(b []byte) error { + var res CreateRaidOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/delete_device_type_raid_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/delete_device_type_raid_parameters.go new file mode 100644 index 0000000..f14b807 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/delete_device_type_raid_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewDeleteDeviceTypeRaidParams creates a new DeleteDeviceTypeRaidParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteDeviceTypeRaidParams() *DeleteDeviceTypeRaidParams { + return &DeleteDeviceTypeRaidParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteDeviceTypeRaidParamsWithTimeout creates a new DeleteDeviceTypeRaidParams object +// with the ability to set a timeout on a request. +func NewDeleteDeviceTypeRaidParamsWithTimeout(timeout time.Duration) *DeleteDeviceTypeRaidParams { + return &DeleteDeviceTypeRaidParams{ + timeout: timeout, + } +} + +// NewDeleteDeviceTypeRaidParamsWithContext creates a new DeleteDeviceTypeRaidParams object +// with the ability to set a context for a request. +func NewDeleteDeviceTypeRaidParamsWithContext(ctx context.Context) *DeleteDeviceTypeRaidParams { + return &DeleteDeviceTypeRaidParams{ + Context: ctx, + } +} + +// NewDeleteDeviceTypeRaidParamsWithHTTPClient creates a new DeleteDeviceTypeRaidParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteDeviceTypeRaidParamsWithHTTPClient(client *http.Client) *DeleteDeviceTypeRaidParams { + return &DeleteDeviceTypeRaidParams{ + HTTPClient: client, + } +} + +/* DeleteDeviceTypeRaidParams contains all the parameters to send to the API endpoint + for the delete device type raid operation. + + Typically these are written to a http.Request. +*/ +type DeleteDeviceTypeRaidParams struct { + + // Body. + Body *models.DeleteDeviceTypeRaidRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete device type raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteDeviceTypeRaidParams) WithDefaults() *DeleteDeviceTypeRaidParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete device type raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteDeviceTypeRaidParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithTimeout(timeout time.Duration) *DeleteDeviceTypeRaidParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithContext(ctx context.Context) *DeleteDeviceTypeRaidParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithHTTPClient(client *http.Client) *DeleteDeviceTypeRaidParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithBody(body *models.DeleteDeviceTypeRaidRequest) *DeleteDeviceTypeRaidParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetBody(body *models.DeleteDeviceTypeRaidRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithAuthorization(authorization string) *DeleteDeviceTypeRaidParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithBmpLanguage(bmpLanguage *string) *DeleteDeviceTypeRaidParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithBmpUserID(bmpUserID *string) *DeleteDeviceTypeRaidParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) WithTraceID(traceID string) *DeleteDeviceTypeRaidParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete device type raid params +func (o *DeleteDeviceTypeRaidParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteDeviceTypeRaidParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/delete_device_type_raid_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/delete_device_type_raid_responses.go new file mode 100644 index 0000000..63d897c --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/delete_device_type_raid_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteDeviceTypeRaidReader is a Reader for the DeleteDeviceTypeRaid structure. +type DeleteDeviceTypeRaidReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteDeviceTypeRaidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteDeviceTypeRaidOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteDeviceTypeRaidDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteDeviceTypeRaidOK creates a DeleteDeviceTypeRaidOK with default headers values +func NewDeleteDeviceTypeRaidOK() *DeleteDeviceTypeRaidOK { + return &DeleteDeviceTypeRaidOK{} +} + +/* DeleteDeviceTypeRaidOK describes a response with status code 200, with default header values. + +A DeleteDeviceTypeRaidResult is an response struct that is used to describe delete device type raid result. +*/ +type DeleteDeviceTypeRaidOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteDeviceTypeRaidOKBody +} + +// IsSuccess returns true when this delete device type raid o k response has a 2xx status code +func (o *DeleteDeviceTypeRaidOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete device type raid o k response has a 3xx status code +func (o *DeleteDeviceTypeRaidOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete device type raid o k response has a 4xx status code +func (o *DeleteDeviceTypeRaidOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete device type raid o k response has a 5xx status code +func (o *DeleteDeviceTypeRaidOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete device type raid o k response a status code equal to that given +func (o *DeleteDeviceTypeRaidOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteDeviceTypeRaidOK) Error() string { + return fmt.Sprintf("[DELETE /raids/deviceTypeRaid][%d] deleteDeviceTypeRaidOK %+v", 200, o.Payload) +} + +func (o *DeleteDeviceTypeRaidOK) String() string { + return fmt.Sprintf("[DELETE /raids/deviceTypeRaid][%d] deleteDeviceTypeRaidOK %+v", 200, o.Payload) +} + +func (o *DeleteDeviceTypeRaidOK) GetPayload() *DeleteDeviceTypeRaidOKBody { + return o.Payload +} + +func (o *DeleteDeviceTypeRaidOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteDeviceTypeRaidOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteDeviceTypeRaidDefault creates a DeleteDeviceTypeRaidDefault with default headers values +func NewDeleteDeviceTypeRaidDefault(code int) *DeleteDeviceTypeRaidDefault { + return &DeleteDeviceTypeRaidDefault{ + _statusCode: code, + } +} + +/* DeleteDeviceTypeRaidDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteDeviceTypeRaidDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteDeviceTypeRaidDefaultBody +} + +// Code gets the status code for the delete device type raid default response +func (o *DeleteDeviceTypeRaidDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete device type raid default response has a 2xx status code +func (o *DeleteDeviceTypeRaidDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete device type raid default response has a 3xx status code +func (o *DeleteDeviceTypeRaidDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete device type raid default response has a 4xx status code +func (o *DeleteDeviceTypeRaidDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete device type raid default response has a 5xx status code +func (o *DeleteDeviceTypeRaidDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete device type raid default response a status code equal to that given +func (o *DeleteDeviceTypeRaidDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteDeviceTypeRaidDefault) Error() string { + return fmt.Sprintf("[DELETE /raids/deviceTypeRaid][%d] deleteDeviceTypeRaid default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteDeviceTypeRaidDefault) String() string { + return fmt.Sprintf("[DELETE /raids/deviceTypeRaid][%d] deleteDeviceTypeRaid default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteDeviceTypeRaidDefault) GetPayload() *DeleteDeviceTypeRaidDefaultBody { + return o.Payload +} + +func (o *DeleteDeviceTypeRaidDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteDeviceTypeRaidDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteDeviceTypeRaidDefaultBody delete device type raid default body +swagger:model DeleteDeviceTypeRaidDefaultBody +*/ +type DeleteDeviceTypeRaidDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete device type raid default body +func (o *DeleteDeviceTypeRaidDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeRaidDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteDeviceTypeRaid default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteDeviceTypeRaidDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteDeviceTypeRaid default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceTypeRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceTypeRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete device type raid default body based on the context it is used +func (o *DeleteDeviceTypeRaidDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeRaidDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceTypeRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceTypeRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteDeviceTypeRaidDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteDeviceTypeRaidDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteDeviceTypeRaidDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteDeviceTypeRaidOKBody delete device type raid o k body +swagger:model DeleteDeviceTypeRaidOKBody +*/ +type DeleteDeviceTypeRaidOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete device type raid o k body +func (o *DeleteDeviceTypeRaidOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeRaidOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceTypeRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceTypeRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete device type raid o k body based on the context it is used +func (o *DeleteDeviceTypeRaidOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteDeviceTypeRaidOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteDeviceTypeRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteDeviceTypeRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteDeviceTypeRaidOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteDeviceTypeRaidOKBody) UnmarshalBinary(b []byte) error { + var res DeleteDeviceTypeRaidOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/delete_raid_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/delete_raid_parameters.go new file mode 100644 index 0000000..4264cce --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/delete_raid_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteRaidParams creates a new DeleteRaidParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteRaidParams() *DeleteRaidParams { + return &DeleteRaidParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteRaidParamsWithTimeout creates a new DeleteRaidParams object +// with the ability to set a timeout on a request. +func NewDeleteRaidParamsWithTimeout(timeout time.Duration) *DeleteRaidParams { + return &DeleteRaidParams{ + timeout: timeout, + } +} + +// NewDeleteRaidParamsWithContext creates a new DeleteRaidParams object +// with the ability to set a context for a request. +func NewDeleteRaidParamsWithContext(ctx context.Context) *DeleteRaidParams { + return &DeleteRaidParams{ + Context: ctx, + } +} + +// NewDeleteRaidParamsWithHTTPClient creates a new DeleteRaidParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteRaidParamsWithHTTPClient(client *http.Client) *DeleteRaidParams { + return &DeleteRaidParams{ + HTTPClient: client, + } +} + +/* DeleteRaidParams contains all the parameters to send to the API endpoint + for the delete raid operation. + + Typically these are written to a http.Request. +*/ +type DeleteRaidParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // RaidID. + RaidID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteRaidParams) WithDefaults() *DeleteRaidParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteRaidParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete raid params +func (o *DeleteRaidParams) WithTimeout(timeout time.Duration) *DeleteRaidParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete raid params +func (o *DeleteRaidParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete raid params +func (o *DeleteRaidParams) WithContext(ctx context.Context) *DeleteRaidParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete raid params +func (o *DeleteRaidParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete raid params +func (o *DeleteRaidParams) WithHTTPClient(client *http.Client) *DeleteRaidParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete raid params +func (o *DeleteRaidParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete raid params +func (o *DeleteRaidParams) WithAuthorization(authorization string) *DeleteRaidParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete raid params +func (o *DeleteRaidParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete raid params +func (o *DeleteRaidParams) WithBmpLanguage(bmpLanguage *string) *DeleteRaidParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete raid params +func (o *DeleteRaidParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete raid params +func (o *DeleteRaidParams) WithBmpUserID(bmpUserID *string) *DeleteRaidParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete raid params +func (o *DeleteRaidParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithRaidID adds the raidID to the delete raid params +func (o *DeleteRaidParams) WithRaidID(raidID string) *DeleteRaidParams { + o.SetRaidID(raidID) + return o +} + +// SetRaidID adds the raidId to the delete raid params +func (o *DeleteRaidParams) SetRaidID(raidID string) { + o.RaidID = raidID +} + +// WithTraceID adds the traceID to the delete raid params +func (o *DeleteRaidParams) WithTraceID(traceID string) *DeleteRaidParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete raid params +func (o *DeleteRaidParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteRaidParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param raid_id + if err := r.SetPathParam("raid_id", o.RaidID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/delete_raid_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/delete_raid_responses.go new file mode 100644 index 0000000..553b72a --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/delete_raid_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteRaidReader is a Reader for the DeleteRaid structure. +type DeleteRaidReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteRaidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteRaidOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteRaidDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteRaidOK creates a DeleteRaidOK with default headers values +func NewDeleteRaidOK() *DeleteRaidOK { + return &DeleteRaidOK{} +} + +/* DeleteRaidOK describes a response with status code 200, with default header values. + +A DeleteRaidResult is an response struct that is used to delete raid. +*/ +type DeleteRaidOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteRaidOKBody +} + +// IsSuccess returns true when this delete raid o k response has a 2xx status code +func (o *DeleteRaidOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete raid o k response has a 3xx status code +func (o *DeleteRaidOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete raid o k response has a 4xx status code +func (o *DeleteRaidOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete raid o k response has a 5xx status code +func (o *DeleteRaidOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete raid o k response a status code equal to that given +func (o *DeleteRaidOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteRaidOK) Error() string { + return fmt.Sprintf("[DELETE /raids/{raid_id}][%d] deleteRaidOK %+v", 200, o.Payload) +} + +func (o *DeleteRaidOK) String() string { + return fmt.Sprintf("[DELETE /raids/{raid_id}][%d] deleteRaidOK %+v", 200, o.Payload) +} + +func (o *DeleteRaidOK) GetPayload() *DeleteRaidOKBody { + return o.Payload +} + +func (o *DeleteRaidOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteRaidOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteRaidDefault creates a DeleteRaidDefault with default headers values +func NewDeleteRaidDefault(code int) *DeleteRaidDefault { + return &DeleteRaidDefault{ + _statusCode: code, + } +} + +/* DeleteRaidDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteRaidDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteRaidDefaultBody +} + +// Code gets the status code for the delete raid default response +func (o *DeleteRaidDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete raid default response has a 2xx status code +func (o *DeleteRaidDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete raid default response has a 3xx status code +func (o *DeleteRaidDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete raid default response has a 4xx status code +func (o *DeleteRaidDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete raid default response has a 5xx status code +func (o *DeleteRaidDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete raid default response a status code equal to that given +func (o *DeleteRaidDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteRaidDefault) Error() string { + return fmt.Sprintf("[DELETE /raids/{raid_id}][%d] deleteRaid default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteRaidDefault) String() string { + return fmt.Sprintf("[DELETE /raids/{raid_id}][%d] deleteRaid default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteRaidDefault) GetPayload() *DeleteRaidDefaultBody { + return o.Payload +} + +func (o *DeleteRaidDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteRaidDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteRaidDefaultBody delete raid default body +swagger:model DeleteRaidDefaultBody +*/ +type DeleteRaidDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete raid default body +func (o *DeleteRaidDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRaidDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteRaid default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteRaidDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteRaid default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete raid default body based on the context it is used +func (o *DeleteRaidDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRaidDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteRaidDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteRaidDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteRaidDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteRaidOKBody delete raid o k body +swagger:model DeleteRaidOKBody +*/ +type DeleteRaidOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete raid o k body +func (o *DeleteRaidOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRaidOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete raid o k body based on the context it is used +func (o *DeleteRaidOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRaidOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteRaidOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteRaidOKBody) UnmarshalBinary(b []byte) error { + var res DeleteRaidOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raid_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raid_parameters.go new file mode 100644 index 0000000..adc6c1b --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raid_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeRaidParams creates a new DescribeRaidParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeRaidParams() *DescribeRaidParams { + return &DescribeRaidParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeRaidParamsWithTimeout creates a new DescribeRaidParams object +// with the ability to set a timeout on a request. +func NewDescribeRaidParamsWithTimeout(timeout time.Duration) *DescribeRaidParams { + return &DescribeRaidParams{ + timeout: timeout, + } +} + +// NewDescribeRaidParamsWithContext creates a new DescribeRaidParams object +// with the ability to set a context for a request. +func NewDescribeRaidParamsWithContext(ctx context.Context) *DescribeRaidParams { + return &DescribeRaidParams{ + Context: ctx, + } +} + +// NewDescribeRaidParamsWithHTTPClient creates a new DescribeRaidParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeRaidParamsWithHTTPClient(client *http.Client) *DescribeRaidParams { + return &DescribeRaidParams{ + HTTPClient: client, + } +} + +/* DescribeRaidParams contains all the parameters to send to the API endpoint + for the describe raid operation. + + Typically these are written to a http.Request. +*/ +type DescribeRaidParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // RaidID. + RaidID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRaidParams) WithDefaults() *DescribeRaidParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRaidParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe raid params +func (o *DescribeRaidParams) WithTimeout(timeout time.Duration) *DescribeRaidParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe raid params +func (o *DescribeRaidParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe raid params +func (o *DescribeRaidParams) WithContext(ctx context.Context) *DescribeRaidParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe raid params +func (o *DescribeRaidParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe raid params +func (o *DescribeRaidParams) WithHTTPClient(client *http.Client) *DescribeRaidParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe raid params +func (o *DescribeRaidParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe raid params +func (o *DescribeRaidParams) WithAuthorization(authorization string) *DescribeRaidParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe raid params +func (o *DescribeRaidParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe raid params +func (o *DescribeRaidParams) WithBmpLanguage(bmpLanguage *string) *DescribeRaidParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe raid params +func (o *DescribeRaidParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe raid params +func (o *DescribeRaidParams) WithBmpUserID(bmpUserID *string) *DescribeRaidParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe raid params +func (o *DescribeRaidParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithRaidID adds the raidID to the describe raid params +func (o *DescribeRaidParams) WithRaidID(raidID string) *DescribeRaidParams { + o.SetRaidID(raidID) + return o +} + +// SetRaidID adds the raidId to the describe raid params +func (o *DescribeRaidParams) SetRaidID(raidID string) { + o.RaidID = raidID +} + +// WithTraceID adds the traceID to the describe raid params +func (o *DescribeRaidParams) WithTraceID(traceID string) *DescribeRaidParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe raid params +func (o *DescribeRaidParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeRaidParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param raid_id + if err := r.SetPathParam("raid_id", o.RaidID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raid_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raid_responses.go new file mode 100644 index 0000000..d256d8d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raid_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeRaidReader is a Reader for the DescribeRaid structure. +type DescribeRaidReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeRaidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeRaidOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeRaidDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeRaidOK creates a DescribeRaidOK with default headers values +func NewDescribeRaidOK() *DescribeRaidOK { + return &DescribeRaidOK{} +} + +/* DescribeRaidOK describes a response with status code 200, with default header values. + +A GetRaidResult is an response struct that is used to describe raid. +*/ +type DescribeRaidOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRaidOKBody +} + +// IsSuccess returns true when this describe raid o k response has a 2xx status code +func (o *DescribeRaidOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe raid o k response has a 3xx status code +func (o *DescribeRaidOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe raid o k response has a 4xx status code +func (o *DescribeRaidOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe raid o k response has a 5xx status code +func (o *DescribeRaidOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe raid o k response a status code equal to that given +func (o *DescribeRaidOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeRaidOK) Error() string { + return fmt.Sprintf("[GET /raids/{raid_id}][%d] describeRaidOK %+v", 200, o.Payload) +} + +func (o *DescribeRaidOK) String() string { + return fmt.Sprintf("[GET /raids/{raid_id}][%d] describeRaidOK %+v", 200, o.Payload) +} + +func (o *DescribeRaidOK) GetPayload() *DescribeRaidOKBody { + return o.Payload +} + +func (o *DescribeRaidOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRaidOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeRaidDefault creates a DescribeRaidDefault with default headers values +func NewDescribeRaidDefault(code int) *DescribeRaidDefault { + return &DescribeRaidDefault{ + _statusCode: code, + } +} + +/* DescribeRaidDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeRaidDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRaidDefaultBody +} + +// Code gets the status code for the describe raid default response +func (o *DescribeRaidDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe raid default response has a 2xx status code +func (o *DescribeRaidDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe raid default response has a 3xx status code +func (o *DescribeRaidDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe raid default response has a 4xx status code +func (o *DescribeRaidDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe raid default response has a 5xx status code +func (o *DescribeRaidDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe raid default response a status code equal to that given +func (o *DescribeRaidDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeRaidDefault) Error() string { + return fmt.Sprintf("[GET /raids/{raid_id}][%d] describeRaid default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRaidDefault) String() string { + return fmt.Sprintf("[GET /raids/{raid_id}][%d] describeRaid default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRaidDefault) GetPayload() *DescribeRaidDefaultBody { + return o.Payload +} + +func (o *DescribeRaidDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRaidDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeRaidDefaultBody describe raid default body +swagger:model DescribeRaidDefaultBody +*/ +type DescribeRaidDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe raid default body +func (o *DescribeRaidDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeRaid default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeRaidDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeRaid default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe raid default body based on the context it is used +func (o *DescribeRaidDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRaidDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRaidDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeRaidDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeRaidOKBody describe raid o k body +swagger:model DescribeRaidOKBody +*/ +type DescribeRaidOKBody struct { + + // result + Result *models.Raid `json:"result,omitempty"` +} + +// Validate validates this describe raid o k body +func (o *DescribeRaidOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe raid o k body based on the context it is used +func (o *DescribeRaidOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRaidOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRaidOKBody) UnmarshalBinary(b []byte) error { + var res DescribeRaidOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raids_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raids_parameters.go new file mode 100644 index 0000000..c9da3d1 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raids_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeRaidsParams creates a new DescribeRaidsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeRaidsParams() *DescribeRaidsParams { + return &DescribeRaidsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeRaidsParamsWithTimeout creates a new DescribeRaidsParams object +// with the ability to set a timeout on a request. +func NewDescribeRaidsParamsWithTimeout(timeout time.Duration) *DescribeRaidsParams { + return &DescribeRaidsParams{ + timeout: timeout, + } +} + +// NewDescribeRaidsParamsWithContext creates a new DescribeRaidsParams object +// with the ability to set a context for a request. +func NewDescribeRaidsParamsWithContext(ctx context.Context) *DescribeRaidsParams { + return &DescribeRaidsParams{ + Context: ctx, + } +} + +// NewDescribeRaidsParamsWithHTTPClient creates a new DescribeRaidsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeRaidsParamsWithHTTPClient(client *http.Client) *DescribeRaidsParams { + return &DescribeRaidsParams{ + HTTPClient: client, + } +} + +/* DescribeRaidsParams contains all the parameters to send to the API endpoint + for the describe raids operation. + + Typically these are written to a http.Request. +*/ +type DescribeRaidsParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe raids params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRaidsParams) WithDefaults() *DescribeRaidsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe raids params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRaidsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe raids params +func (o *DescribeRaidsParams) WithTimeout(timeout time.Duration) *DescribeRaidsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe raids params +func (o *DescribeRaidsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe raids params +func (o *DescribeRaidsParams) WithContext(ctx context.Context) *DescribeRaidsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe raids params +func (o *DescribeRaidsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe raids params +func (o *DescribeRaidsParams) WithHTTPClient(client *http.Client) *DescribeRaidsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe raids params +func (o *DescribeRaidsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe raids params +func (o *DescribeRaidsParams) WithAuthorization(authorization string) *DescribeRaidsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe raids params +func (o *DescribeRaidsParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe raids params +func (o *DescribeRaidsParams) WithBmpLanguage(bmpLanguage *string) *DescribeRaidsParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe raids params +func (o *DescribeRaidsParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe raids params +func (o *DescribeRaidsParams) WithBmpUserID(bmpUserID *string) *DescribeRaidsParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe raids params +func (o *DescribeRaidsParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe raids params +func (o *DescribeRaidsParams) WithTraceID(traceID string) *DescribeRaidsParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe raids params +func (o *DescribeRaidsParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeRaidsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raids_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raids_responses.go new file mode 100644 index 0000000..27ce6f8 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/describe_raids_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeRaidsReader is a Reader for the DescribeRaids structure. +type DescribeRaidsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeRaidsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeRaidsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeRaidsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeRaidsOK creates a DescribeRaidsOK with default headers values +func NewDescribeRaidsOK() *DescribeRaidsOK { + return &DescribeRaidsOK{} +} + +/* DescribeRaidsOK describes a response with status code 200, with default header values. + +QueryRaidsAllResult is an response struct that is used to query all raids. +*/ +type DescribeRaidsOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRaidsOKBody +} + +// IsSuccess returns true when this describe raids o k response has a 2xx status code +func (o *DescribeRaidsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe raids o k response has a 3xx status code +func (o *DescribeRaidsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe raids o k response has a 4xx status code +func (o *DescribeRaidsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe raids o k response has a 5xx status code +func (o *DescribeRaidsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe raids o k response a status code equal to that given +func (o *DescribeRaidsOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeRaidsOK) Error() string { + return fmt.Sprintf("[GET /raids][%d] describeRaidsOK %+v", 200, o.Payload) +} + +func (o *DescribeRaidsOK) String() string { + return fmt.Sprintf("[GET /raids][%d] describeRaidsOK %+v", 200, o.Payload) +} + +func (o *DescribeRaidsOK) GetPayload() *DescribeRaidsOKBody { + return o.Payload +} + +func (o *DescribeRaidsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRaidsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeRaidsDefault creates a DescribeRaidsDefault with default headers values +func NewDescribeRaidsDefault(code int) *DescribeRaidsDefault { + return &DescribeRaidsDefault{ + _statusCode: code, + } +} + +/* DescribeRaidsDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeRaidsDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRaidsDefaultBody +} + +// Code gets the status code for the describe raids default response +func (o *DescribeRaidsDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe raids default response has a 2xx status code +func (o *DescribeRaidsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe raids default response has a 3xx status code +func (o *DescribeRaidsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe raids default response has a 4xx status code +func (o *DescribeRaidsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe raids default response has a 5xx status code +func (o *DescribeRaidsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe raids default response a status code equal to that given +func (o *DescribeRaidsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeRaidsDefault) Error() string { + return fmt.Sprintf("[GET /raids][%d] describeRaids default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRaidsDefault) String() string { + return fmt.Sprintf("[GET /raids][%d] describeRaids default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRaidsDefault) GetPayload() *DescribeRaidsDefaultBody { + return o.Payload +} + +func (o *DescribeRaidsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRaidsDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeRaidsDefaultBody describe raids default body +swagger:model DescribeRaidsDefaultBody +*/ +type DescribeRaidsDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe raids default body +func (o *DescribeRaidsDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidsDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeRaids default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeRaidsDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeRaids default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaids default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaids default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe raids default body based on the context it is used +func (o *DescribeRaidsDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidsDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaids default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaids default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRaidsDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRaidsDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeRaidsDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeRaidsOKBody describe raids o k body +swagger:model DescribeRaidsOKBody +*/ +type DescribeRaidsOKBody struct { + + // result + Result *models.RaidList `json:"result,omitempty"` +} + +// Validate validates this describe raids o k body +func (o *DescribeRaidsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidsOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaidsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaidsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe raids o k body based on the context it is used +func (o *DescribeRaidsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRaidsOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRaidsOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRaidsOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRaidsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRaidsOKBody) UnmarshalBinary(b []byte) error { + var res DescribeRaidsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/modify_raid_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/modify_raid_parameters.go new file mode 100644 index 0000000..cc283b9 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/modify_raid_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyRaidParams creates a new ModifyRaidParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyRaidParams() *ModifyRaidParams { + return &ModifyRaidParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyRaidParamsWithTimeout creates a new ModifyRaidParams object +// with the ability to set a timeout on a request. +func NewModifyRaidParamsWithTimeout(timeout time.Duration) *ModifyRaidParams { + return &ModifyRaidParams{ + timeout: timeout, + } +} + +// NewModifyRaidParamsWithContext creates a new ModifyRaidParams object +// with the ability to set a context for a request. +func NewModifyRaidParamsWithContext(ctx context.Context) *ModifyRaidParams { + return &ModifyRaidParams{ + Context: ctx, + } +} + +// NewModifyRaidParamsWithHTTPClient creates a new ModifyRaidParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyRaidParamsWithHTTPClient(client *http.Client) *ModifyRaidParams { + return &ModifyRaidParams{ + HTTPClient: client, + } +} + +/* ModifyRaidParams contains all the parameters to send to the API endpoint + for the modify raid operation. + + Typically these are written to a http.Request. +*/ +type ModifyRaidParams struct { + + // Body. + Body *models.ModifyRaidRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // RaidID. + RaidID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyRaidParams) WithDefaults() *ModifyRaidParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify raid params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyRaidParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify raid params +func (o *ModifyRaidParams) WithTimeout(timeout time.Duration) *ModifyRaidParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify raid params +func (o *ModifyRaidParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify raid params +func (o *ModifyRaidParams) WithContext(ctx context.Context) *ModifyRaidParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify raid params +func (o *ModifyRaidParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify raid params +func (o *ModifyRaidParams) WithHTTPClient(client *http.Client) *ModifyRaidParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify raid params +func (o *ModifyRaidParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify raid params +func (o *ModifyRaidParams) WithBody(body *models.ModifyRaidRequest) *ModifyRaidParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify raid params +func (o *ModifyRaidParams) SetBody(body *models.ModifyRaidRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify raid params +func (o *ModifyRaidParams) WithAuthorization(authorization string) *ModifyRaidParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify raid params +func (o *ModifyRaidParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify raid params +func (o *ModifyRaidParams) WithBmpLanguage(bmpLanguage *string) *ModifyRaidParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify raid params +func (o *ModifyRaidParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify raid params +func (o *ModifyRaidParams) WithBmpUserID(bmpUserID *string) *ModifyRaidParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify raid params +func (o *ModifyRaidParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithRaidID adds the raidID to the modify raid params +func (o *ModifyRaidParams) WithRaidID(raidID string) *ModifyRaidParams { + o.SetRaidID(raidID) + return o +} + +// SetRaidID adds the raidId to the modify raid params +func (o *ModifyRaidParams) SetRaidID(raidID string) { + o.RaidID = raidID +} + +// WithTraceID adds the traceID to the modify raid params +func (o *ModifyRaidParams) WithTraceID(traceID string) *ModifyRaidParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify raid params +func (o *ModifyRaidParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyRaidParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param raid_id + if err := r.SetPathParam("raid_id", o.RaidID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/modify_raid_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/modify_raid_responses.go new file mode 100644 index 0000000..12bbeac --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/modify_raid_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyRaidReader is a Reader for the ModifyRaid structure. +type ModifyRaidReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyRaidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyRaidOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyRaidDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyRaidOK creates a ModifyRaidOK with default headers values +func NewModifyRaidOK() *ModifyRaidOK { + return &ModifyRaidOK{} +} + +/* ModifyRaidOK describes a response with status code 200, with default header values. + +A ModifyRaidResult is an response struct that is used to describe modify raid. +*/ +type ModifyRaidOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyRaidOKBody +} + +// IsSuccess returns true when this modify raid o k response has a 2xx status code +func (o *ModifyRaidOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify raid o k response has a 3xx status code +func (o *ModifyRaidOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify raid o k response has a 4xx status code +func (o *ModifyRaidOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify raid o k response has a 5xx status code +func (o *ModifyRaidOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify raid o k response a status code equal to that given +func (o *ModifyRaidOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyRaidOK) Error() string { + return fmt.Sprintf("[PUT /raids/{raid_id}][%d] modifyRaidOK %+v", 200, o.Payload) +} + +func (o *ModifyRaidOK) String() string { + return fmt.Sprintf("[PUT /raids/{raid_id}][%d] modifyRaidOK %+v", 200, o.Payload) +} + +func (o *ModifyRaidOK) GetPayload() *ModifyRaidOKBody { + return o.Payload +} + +func (o *ModifyRaidOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyRaidOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyRaidDefault creates a ModifyRaidDefault with default headers values +func NewModifyRaidDefault(code int) *ModifyRaidDefault { + return &ModifyRaidDefault{ + _statusCode: code, + } +} + +/* ModifyRaidDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyRaidDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyRaidDefaultBody +} + +// Code gets the status code for the modify raid default response +func (o *ModifyRaidDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify raid default response has a 2xx status code +func (o *ModifyRaidDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify raid default response has a 3xx status code +func (o *ModifyRaidDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify raid default response has a 4xx status code +func (o *ModifyRaidDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify raid default response has a 5xx status code +func (o *ModifyRaidDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify raid default response a status code equal to that given +func (o *ModifyRaidDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyRaidDefault) Error() string { + return fmt.Sprintf("[PUT /raids/{raid_id}][%d] modifyRaid default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyRaidDefault) String() string { + return fmt.Sprintf("[PUT /raids/{raid_id}][%d] modifyRaid default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyRaidDefault) GetPayload() *ModifyRaidDefaultBody { + return o.Payload +} + +func (o *ModifyRaidDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyRaidDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyRaidDefaultBody modify raid default body +swagger:model ModifyRaidDefaultBody +*/ +type ModifyRaidDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify raid default body +func (o *ModifyRaidDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRaidDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyRaid default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyRaidDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyRaid default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify raid default body based on the context it is used +func (o *ModifyRaidDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRaidDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRaid default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRaid default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyRaidDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyRaidDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyRaidDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyRaidOKBody modify raid o k body +swagger:model ModifyRaidOKBody +*/ +type ModifyRaidOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify raid o k body +func (o *ModifyRaidOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRaidOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify raid o k body based on the context it is used +func (o *ModifyRaidOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRaidOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRaidOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRaidOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyRaidOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyRaidOKBody) UnmarshalBinary(b []byte) error { + var res ModifyRaidOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/raid_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/raid_client.go new file mode 100644 index 0000000..1baf54d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/raid/raid_client.go @@ -0,0 +1,317 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package raid + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new raid API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for raid API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateDeviceTypeRaid(params *CreateDeviceTypeRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateDeviceTypeRaidOK, error) + + CreateRaid(params *CreateRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateRaidOK, error) + + DeleteDeviceTypeRaid(params *DeleteDeviceTypeRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteDeviceTypeRaidOK, error) + + DeleteRaid(params *DeleteRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteRaidOK, error) + + DescribeRaid(params *DescribeRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRaidOK, error) + + DescribeRaids(params *DescribeRaidsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRaidsOK, error) + + ModifyRaid(params *ModifyRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyRaidOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateDeviceTypeRaid CreateDeviceTypeRaid ... 机型和raid关联(暂不启用) +*/ +func (a *Client) CreateDeviceTypeRaid(params *CreateDeviceTypeRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateDeviceTypeRaidOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateDeviceTypeRaidParams() + } + op := &runtime.ClientOperation{ + ID: "createDeviceTypeRaid", + Method: "POST", + PathPattern: "/raids/deviceTypeRaid", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateDeviceTypeRaidReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateDeviceTypeRaidOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateDeviceTypeRaidDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + CreateRaid CreateRaid 创建raid(暂不启用) +*/ +func (a *Client) CreateRaid(params *CreateRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateRaidOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateRaidParams() + } + op := &runtime.ClientOperation{ + ID: "createRaid", + Method: "POST", + PathPattern: "/raids", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateRaidReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateRaidOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateRaidDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteDeviceTypeRaid DeleteDeviceTypeRaid ... 机型和raid解绑(暂不启用) +*/ +func (a *Client) DeleteDeviceTypeRaid(params *DeleteDeviceTypeRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteDeviceTypeRaidOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteDeviceTypeRaidParams() + } + op := &runtime.ClientOperation{ + ID: "deleteDeviceTypeRaid", + Method: "DELETE", + PathPattern: "/raids/deviceTypeRaid", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteDeviceTypeRaidReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteDeviceTypeRaidOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteDeviceTypeRaidDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteRaid DeleteRaid 删除raid(暂不启用) +*/ +func (a *Client) DeleteRaid(params *DeleteRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteRaidOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteRaidParams() + } + op := &runtime.ClientOperation{ + ID: "deleteRaid", + Method: "DELETE", + PathPattern: "/raids/{raid_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteRaidReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteRaidOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteRaidDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeRaid DescribeRaid 获取raid详情 +*/ +func (a *Client) DescribeRaid(params *DescribeRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRaidOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeRaidParams() + } + op := &runtime.ClientOperation{ + ID: "describeRaid", + Method: "GET", + PathPattern: "/raids/{raid_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeRaidReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeRaidOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeRaidDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeRaids DescribeRaids 获取raid列表 +*/ +func (a *Client) DescribeRaids(params *DescribeRaidsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRaidsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeRaidsParams() + } + op := &runtime.ClientOperation{ + ID: "describeRaids", + Method: "GET", + PathPattern: "/raids", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeRaidsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeRaidsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeRaidsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyRaid ModifyRaid 修改raid信息(暂不启用) +*/ +func (a *Client) ModifyRaid(params *ModifyRaidParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyRaidOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyRaidParams() + } + op := &runtime.ClientOperation{ + ID: "modifyRaid", + Method: "PUT", + PathPattern: "/raids/{raid_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyRaidReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyRaidOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyRaidDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/resource/describe_resources_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/resource/describe_resources_parameters.go new file mode 100644 index 0000000..ea3d17d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/resource/describe_resources_parameters.go @@ -0,0 +1,361 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package resource + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeResourcesParams creates a new DescribeResourcesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeResourcesParams() *DescribeResourcesParams { + return &DescribeResourcesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeResourcesParamsWithTimeout creates a new DescribeResourcesParams object +// with the ability to set a timeout on a request. +func NewDescribeResourcesParamsWithTimeout(timeout time.Duration) *DescribeResourcesParams { + return &DescribeResourcesParams{ + timeout: timeout, + } +} + +// NewDescribeResourcesParamsWithContext creates a new DescribeResourcesParams object +// with the ability to set a context for a request. +func NewDescribeResourcesParamsWithContext(ctx context.Context) *DescribeResourcesParams { + return &DescribeResourcesParams{ + Context: ctx, + } +} + +// NewDescribeResourcesParamsWithHTTPClient creates a new DescribeResourcesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeResourcesParamsWithHTTPClient(client *http.Client) *DescribeResourcesParams { + return &DescribeResourcesParams{ + HTTPClient: client, + } +} + +/* DescribeResourcesParams contains all the parameters to send to the API endpoint + for the describe resources operation. + + Typically these are written to a http.Request. +*/ +type DescribeResourcesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DeviceType. + + 机型规格 + */ + DeviceType *string + + /* ImageName. + + 镜像名称 + */ + ImageName *string + + /* Name. + + 机房名称 + IdcName string `json:"idcName"` + 机房英文名称 + IdcNameEn string `json:"idcNameEn"`[*]/ + 机型名称 + */ + Name *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserName. + + 用户名称 + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe resources params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeResourcesParams) WithDefaults() *DescribeResourcesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe resources params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeResourcesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe resources params +func (o *DescribeResourcesParams) WithTimeout(timeout time.Duration) *DescribeResourcesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe resources params +func (o *DescribeResourcesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe resources params +func (o *DescribeResourcesParams) WithContext(ctx context.Context) *DescribeResourcesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe resources params +func (o *DescribeResourcesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe resources params +func (o *DescribeResourcesParams) WithHTTPClient(client *http.Client) *DescribeResourcesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe resources params +func (o *DescribeResourcesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe resources params +func (o *DescribeResourcesParams) WithAuthorization(authorization string) *DescribeResourcesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe resources params +func (o *DescribeResourcesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe resources params +func (o *DescribeResourcesParams) WithBmpLanguage(bmpLanguage *string) *DescribeResourcesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe resources params +func (o *DescribeResourcesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe resources params +func (o *DescribeResourcesParams) WithBmpUserID(bmpUserID *string) *DescribeResourcesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe resources params +func (o *DescribeResourcesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDeviceType adds the deviceType to the describe resources params +func (o *DescribeResourcesParams) WithDeviceType(deviceType *string) *DescribeResourcesParams { + o.SetDeviceType(deviceType) + return o +} + +// SetDeviceType adds the deviceType to the describe resources params +func (o *DescribeResourcesParams) SetDeviceType(deviceType *string) { + o.DeviceType = deviceType +} + +// WithImageName adds the imageName to the describe resources params +func (o *DescribeResourcesParams) WithImageName(imageName *string) *DescribeResourcesParams { + o.SetImageName(imageName) + return o +} + +// SetImageName adds the imageName to the describe resources params +func (o *DescribeResourcesParams) SetImageName(imageName *string) { + o.ImageName = imageName +} + +// WithName adds the name to the describe resources params +func (o *DescribeResourcesParams) WithName(name *string) *DescribeResourcesParams { + o.SetName(name) + return o +} + +// SetName adds the name to the describe resources params +func (o *DescribeResourcesParams) SetName(name *string) { + o.Name = name +} + +// WithTraceID adds the traceID to the describe resources params +func (o *DescribeResourcesParams) WithTraceID(traceID string) *DescribeResourcesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe resources params +func (o *DescribeResourcesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserName adds the userName to the describe resources params +func (o *DescribeResourcesParams) WithUserName(userName *string) *DescribeResourcesParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe resources params +func (o *DescribeResourcesParams) SetUserName(userName *string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeResourcesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DeviceType != nil { + + // query param deviceType + var qrDeviceType string + + if o.DeviceType != nil { + qrDeviceType = *o.DeviceType + } + qDeviceType := qrDeviceType + if qDeviceType != "" { + + if err := r.SetQueryParam("deviceType", qDeviceType); err != nil { + return err + } + } + } + + if o.ImageName != nil { + + // query param imageName + var qrImageName string + + if o.ImageName != nil { + qrImageName = *o.ImageName + } + qImageName := qrImageName + if qImageName != "" { + + if err := r.SetQueryParam("imageName", qImageName); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserName != nil { + + // query param userName + var qrUserName string + + if o.UserName != nil { + qrUserName = *o.UserName + } + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/resource/describe_resources_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/resource/describe_resources_responses.go new file mode 100644 index 0000000..a2a1879 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/resource/describe_resources_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package resource + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeResourcesReader is a Reader for the DescribeResources structure. +type DescribeResourcesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeResourcesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeResourcesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeResourcesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeResourcesOK creates a DescribeResourcesOK with default headers values +func NewDescribeResourcesOK() *DescribeResourcesOK { + return &DescribeResourcesOK{} +} + +/* DescribeResourcesOK describes a response with status code 200, with default header values. + +DescribeResourcesOK describe resources o k +*/ +type DescribeResourcesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeResourcesOKBody +} + +// IsSuccess returns true when this describe resources o k response has a 2xx status code +func (o *DescribeResourcesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe resources o k response has a 3xx status code +func (o *DescribeResourcesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe resources o k response has a 4xx status code +func (o *DescribeResourcesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe resources o k response has a 5xx status code +func (o *DescribeResourcesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe resources o k response a status code equal to that given +func (o *DescribeResourcesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeResourcesOK) Error() string { + return fmt.Sprintf("[GET /resources][%d] describeResourcesOK %+v", 200, o.Payload) +} + +func (o *DescribeResourcesOK) String() string { + return fmt.Sprintf("[GET /resources][%d] describeResourcesOK %+v", 200, o.Payload) +} + +func (o *DescribeResourcesOK) GetPayload() *DescribeResourcesOKBody { + return o.Payload +} + +func (o *DescribeResourcesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeResourcesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeResourcesDefault creates a DescribeResourcesDefault with default headers values +func NewDescribeResourcesDefault(code int) *DescribeResourcesDefault { + return &DescribeResourcesDefault{ + _statusCode: code, + } +} + +/* DescribeResourcesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeResourcesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeResourcesDefaultBody +} + +// Code gets the status code for the describe resources default response +func (o *DescribeResourcesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe resources default response has a 2xx status code +func (o *DescribeResourcesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe resources default response has a 3xx status code +func (o *DescribeResourcesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe resources default response has a 4xx status code +func (o *DescribeResourcesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe resources default response has a 5xx status code +func (o *DescribeResourcesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe resources default response a status code equal to that given +func (o *DescribeResourcesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeResourcesDefault) Error() string { + return fmt.Sprintf("[GET /resources][%d] describeResources default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeResourcesDefault) String() string { + return fmt.Sprintf("[GET /resources][%d] describeResources default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeResourcesDefault) GetPayload() *DescribeResourcesDefaultBody { + return o.Payload +} + +func (o *DescribeResourcesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeResourcesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeResourcesDefaultBody describe resources default body +swagger:model DescribeResourcesDefaultBody +*/ +type DescribeResourcesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe resources default body +func (o *DescribeResourcesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeResourcesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeResources default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeResourcesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeResources default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeResources default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeResources default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe resources default body based on the context it is used +func (o *DescribeResourcesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeResourcesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeResources default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeResources default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeResourcesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeResourcesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeResourcesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeResourcesOKBody describe resources o k body +swagger:model DescribeResourcesOKBody +*/ +type DescribeResourcesOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this describe resources o k body +func (o *DescribeResourcesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeResourcesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeResourcesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeResourcesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe resources o k body based on the context it is used +func (o *DescribeResourcesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeResourcesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeResourcesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeResourcesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeResourcesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeResourcesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeResourcesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/resource/resource_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/resource/resource_client.go new file mode 100644 index 0000000..4bc504f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/resource/resource_client.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package resource + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new resource API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for resource API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + DescribeResources(params *DescribeResourcesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeResourcesOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + DescribeResources DescribeResources 根据某个字段值精确查询对应的资源列表(如根据imageName查询镜像列表,根据idcName查询机房列表) +*/ +func (a *Client) DescribeResources(params *DescribeResourcesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeResourcesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeResourcesParams() + } + op := &runtime.ClientOperation{ + ID: "describeResources", + Method: "GET", + PathPattern: "/resources", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeResourcesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeResourcesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeResourcesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/create_role_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/create_role_parameters.go new file mode 100644 index 0000000..352050c --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/create_role_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateRoleParams creates a new CreateRoleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateRoleParams() *CreateRoleParams { + return &CreateRoleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateRoleParamsWithTimeout creates a new CreateRoleParams object +// with the ability to set a timeout on a request. +func NewCreateRoleParamsWithTimeout(timeout time.Duration) *CreateRoleParams { + return &CreateRoleParams{ + timeout: timeout, + } +} + +// NewCreateRoleParamsWithContext creates a new CreateRoleParams object +// with the ability to set a context for a request. +func NewCreateRoleParamsWithContext(ctx context.Context) *CreateRoleParams { + return &CreateRoleParams{ + Context: ctx, + } +} + +// NewCreateRoleParamsWithHTTPClient creates a new CreateRoleParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateRoleParamsWithHTTPClient(client *http.Client) *CreateRoleParams { + return &CreateRoleParams{ + HTTPClient: client, + } +} + +/* CreateRoleParams contains all the parameters to send to the API endpoint + for the create role operation. + + Typically these are written to a http.Request. +*/ +type CreateRoleParams struct { + + // Body. + Body *models.CreateRoleRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateRoleParams) WithDefaults() *CreateRoleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateRoleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create role params +func (o *CreateRoleParams) WithTimeout(timeout time.Duration) *CreateRoleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create role params +func (o *CreateRoleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create role params +func (o *CreateRoleParams) WithContext(ctx context.Context) *CreateRoleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create role params +func (o *CreateRoleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create role params +func (o *CreateRoleParams) WithHTTPClient(client *http.Client) *CreateRoleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create role params +func (o *CreateRoleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create role params +func (o *CreateRoleParams) WithBody(body *models.CreateRoleRequest) *CreateRoleParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create role params +func (o *CreateRoleParams) SetBody(body *models.CreateRoleRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create role params +func (o *CreateRoleParams) WithAuthorization(authorization string) *CreateRoleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create role params +func (o *CreateRoleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create role params +func (o *CreateRoleParams) WithBmpLanguage(bmpLanguage *string) *CreateRoleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create role params +func (o *CreateRoleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create role params +func (o *CreateRoleParams) WithBmpUserID(bmpUserID *string) *CreateRoleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create role params +func (o *CreateRoleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create role params +func (o *CreateRoleParams) WithTraceID(traceID string) *CreateRoleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create role params +func (o *CreateRoleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateRoleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/create_role_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/create_role_responses.go new file mode 100644 index 0000000..521928d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/create_role_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateRoleReader is a Reader for the CreateRole structure. +type CreateRoleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateRoleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateRoleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateRoleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateRoleOK creates a CreateRoleOK with default headers values +func NewCreateRoleOK() *CreateRoleOK { + return &CreateRoleOK{} +} + +/* CreateRoleOK describes a response with status code 200, with default header values. + +A CreateRoleResult is an response struct that is used to describe create role result. +*/ +type CreateRoleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateRoleOKBody +} + +// IsSuccess returns true when this create role o k response has a 2xx status code +func (o *CreateRoleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create role o k response has a 3xx status code +func (o *CreateRoleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create role o k response has a 4xx status code +func (o *CreateRoleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create role o k response has a 5xx status code +func (o *CreateRoleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create role o k response a status code equal to that given +func (o *CreateRoleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateRoleOK) Error() string { + return fmt.Sprintf("[POST /roles][%d] createRoleOK %+v", 200, o.Payload) +} + +func (o *CreateRoleOK) String() string { + return fmt.Sprintf("[POST /roles][%d] createRoleOK %+v", 200, o.Payload) +} + +func (o *CreateRoleOK) GetPayload() *CreateRoleOKBody { + return o.Payload +} + +func (o *CreateRoleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateRoleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateRoleDefault creates a CreateRoleDefault with default headers values +func NewCreateRoleDefault(code int) *CreateRoleDefault { + return &CreateRoleDefault{ + _statusCode: code, + } +} + +/* CreateRoleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateRoleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateRoleDefaultBody +} + +// Code gets the status code for the create role default response +func (o *CreateRoleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create role default response has a 2xx status code +func (o *CreateRoleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create role default response has a 3xx status code +func (o *CreateRoleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create role default response has a 4xx status code +func (o *CreateRoleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create role default response has a 5xx status code +func (o *CreateRoleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create role default response a status code equal to that given +func (o *CreateRoleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateRoleDefault) Error() string { + return fmt.Sprintf("[POST /roles][%d] createRole default %+v", o._statusCode, o.Payload) +} + +func (o *CreateRoleDefault) String() string { + return fmt.Sprintf("[POST /roles][%d] createRole default %+v", o._statusCode, o.Payload) +} + +func (o *CreateRoleDefault) GetPayload() *CreateRoleDefaultBody { + return o.Payload +} + +func (o *CreateRoleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateRoleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateRoleDefaultBody create role default body +swagger:model CreateRoleDefaultBody +*/ +type CreateRoleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create role default body +func (o *CreateRoleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRoleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createRole default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateRoleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createRole default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create role default body based on the context it is used +func (o *CreateRoleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRoleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateRoleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateRoleDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateRoleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateRoleOKBody create role o k body +swagger:model CreateRoleOKBody +*/ +type CreateRoleOKBody struct { + + // result + Result *models.RoleID `json:"result,omitempty"` +} + +// Validate validates this create role o k body +func (o *CreateRoleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRoleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create role o k body based on the context it is used +func (o *CreateRoleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateRoleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateRoleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateRoleOKBody) UnmarshalBinary(b []byte) error { + var res CreateRoleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/current_role_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/current_role_parameters.go new file mode 100644 index 0000000..e39198b --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/current_role_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewCurrentRoleParams creates a new CurrentRoleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCurrentRoleParams() *CurrentRoleParams { + return &CurrentRoleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCurrentRoleParamsWithTimeout creates a new CurrentRoleParams object +// with the ability to set a timeout on a request. +func NewCurrentRoleParamsWithTimeout(timeout time.Duration) *CurrentRoleParams { + return &CurrentRoleParams{ + timeout: timeout, + } +} + +// NewCurrentRoleParamsWithContext creates a new CurrentRoleParams object +// with the ability to set a context for a request. +func NewCurrentRoleParamsWithContext(ctx context.Context) *CurrentRoleParams { + return &CurrentRoleParams{ + Context: ctx, + } +} + +// NewCurrentRoleParamsWithHTTPClient creates a new CurrentRoleParams object +// with the ability to set a custom HTTPClient for a request. +func NewCurrentRoleParamsWithHTTPClient(client *http.Client) *CurrentRoleParams { + return &CurrentRoleParams{ + HTTPClient: client, + } +} + +/* CurrentRoleParams contains all the parameters to send to the API endpoint + for the current role operation. + + Typically these are written to a http.Request. +*/ +type CurrentRoleParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the current role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CurrentRoleParams) WithDefaults() *CurrentRoleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the current role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CurrentRoleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the current role params +func (o *CurrentRoleParams) WithTimeout(timeout time.Duration) *CurrentRoleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the current role params +func (o *CurrentRoleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the current role params +func (o *CurrentRoleParams) WithContext(ctx context.Context) *CurrentRoleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the current role params +func (o *CurrentRoleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the current role params +func (o *CurrentRoleParams) WithHTTPClient(client *http.Client) *CurrentRoleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the current role params +func (o *CurrentRoleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the current role params +func (o *CurrentRoleParams) WithAuthorization(authorization string) *CurrentRoleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the current role params +func (o *CurrentRoleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the current role params +func (o *CurrentRoleParams) WithBmpLanguage(bmpLanguage *string) *CurrentRoleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the current role params +func (o *CurrentRoleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the current role params +func (o *CurrentRoleParams) WithBmpUserID(bmpUserID *string) *CurrentRoleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the current role params +func (o *CurrentRoleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the current role params +func (o *CurrentRoleParams) WithTraceID(traceID string) *CurrentRoleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the current role params +func (o *CurrentRoleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CurrentRoleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/current_role_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/current_role_responses.go new file mode 100644 index 0000000..f9a3938 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/current_role_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CurrentRoleReader is a Reader for the CurrentRole structure. +type CurrentRoleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CurrentRoleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCurrentRoleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCurrentRoleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCurrentRoleOK creates a CurrentRoleOK with default headers values +func NewCurrentRoleOK() *CurrentRoleOK { + return &CurrentRoleOK{} +} + +/* CurrentRoleOK describes a response with status code 200, with default header values. + +A CurrentRoleResult is an response struct that is used to describe role. +*/ +type CurrentRoleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CurrentRoleOKBody +} + +// IsSuccess returns true when this current role o k response has a 2xx status code +func (o *CurrentRoleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this current role o k response has a 3xx status code +func (o *CurrentRoleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this current role o k response has a 4xx status code +func (o *CurrentRoleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this current role o k response has a 5xx status code +func (o *CurrentRoleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this current role o k response a status code equal to that given +func (o *CurrentRoleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CurrentRoleOK) Error() string { + return fmt.Sprintf("[GET /roles/roleInfo/current][%d] currentRoleOK %+v", 200, o.Payload) +} + +func (o *CurrentRoleOK) String() string { + return fmt.Sprintf("[GET /roles/roleInfo/current][%d] currentRoleOK %+v", 200, o.Payload) +} + +func (o *CurrentRoleOK) GetPayload() *CurrentRoleOKBody { + return o.Payload +} + +func (o *CurrentRoleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CurrentRoleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCurrentRoleDefault creates a CurrentRoleDefault with default headers values +func NewCurrentRoleDefault(code int) *CurrentRoleDefault { + return &CurrentRoleDefault{ + _statusCode: code, + } +} + +/* CurrentRoleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CurrentRoleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CurrentRoleDefaultBody +} + +// Code gets the status code for the current role default response +func (o *CurrentRoleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this current role default response has a 2xx status code +func (o *CurrentRoleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this current role default response has a 3xx status code +func (o *CurrentRoleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this current role default response has a 4xx status code +func (o *CurrentRoleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this current role default response has a 5xx status code +func (o *CurrentRoleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this current role default response a status code equal to that given +func (o *CurrentRoleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CurrentRoleDefault) Error() string { + return fmt.Sprintf("[GET /roles/roleInfo/current][%d] currentRole default %+v", o._statusCode, o.Payload) +} + +func (o *CurrentRoleDefault) String() string { + return fmt.Sprintf("[GET /roles/roleInfo/current][%d] currentRole default %+v", o._statusCode, o.Payload) +} + +func (o *CurrentRoleDefault) GetPayload() *CurrentRoleDefaultBody { + return o.Payload +} + +func (o *CurrentRoleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CurrentRoleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CurrentRoleDefaultBody current role default body +swagger:model CurrentRoleDefaultBody +*/ +type CurrentRoleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this current role default body +func (o *CurrentRoleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CurrentRoleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("currentRole default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CurrentRoleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("currentRole default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("currentRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("currentRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this current role default body based on the context it is used +func (o *CurrentRoleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CurrentRoleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("currentRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("currentRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CurrentRoleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CurrentRoleDefaultBody) UnmarshalBinary(b []byte) error { + var res CurrentRoleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CurrentRoleOKBody current role o k body +swagger:model CurrentRoleOKBody +*/ +type CurrentRoleOKBody struct { + + // result + Result *models.RoleInfo `json:"result,omitempty"` +} + +// Validate validates this current role o k body +func (o *CurrentRoleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CurrentRoleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("currentRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("currentRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this current role o k body based on the context it is used +func (o *CurrentRoleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CurrentRoleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("currentRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("currentRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CurrentRoleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CurrentRoleOKBody) UnmarshalBinary(b []byte) error { + var res CurrentRoleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/delete_role_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/delete_role_parameters.go new file mode 100644 index 0000000..a4ef43c --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/delete_role_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteRoleParams creates a new DeleteRoleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteRoleParams() *DeleteRoleParams { + return &DeleteRoleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteRoleParamsWithTimeout creates a new DeleteRoleParams object +// with the ability to set a timeout on a request. +func NewDeleteRoleParamsWithTimeout(timeout time.Duration) *DeleteRoleParams { + return &DeleteRoleParams{ + timeout: timeout, + } +} + +// NewDeleteRoleParamsWithContext creates a new DeleteRoleParams object +// with the ability to set a context for a request. +func NewDeleteRoleParamsWithContext(ctx context.Context) *DeleteRoleParams { + return &DeleteRoleParams{ + Context: ctx, + } +} + +// NewDeleteRoleParamsWithHTTPClient creates a new DeleteRoleParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteRoleParamsWithHTTPClient(client *http.Client) *DeleteRoleParams { + return &DeleteRoleParams{ + HTTPClient: client, + } +} + +/* DeleteRoleParams contains all the parameters to send to the API endpoint + for the delete role operation. + + Typically these are written to a http.Request. +*/ +type DeleteRoleParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // RoleID. + RoleID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteRoleParams) WithDefaults() *DeleteRoleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteRoleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete role params +func (o *DeleteRoleParams) WithTimeout(timeout time.Duration) *DeleteRoleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete role params +func (o *DeleteRoleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete role params +func (o *DeleteRoleParams) WithContext(ctx context.Context) *DeleteRoleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete role params +func (o *DeleteRoleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete role params +func (o *DeleteRoleParams) WithHTTPClient(client *http.Client) *DeleteRoleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete role params +func (o *DeleteRoleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete role params +func (o *DeleteRoleParams) WithAuthorization(authorization string) *DeleteRoleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete role params +func (o *DeleteRoleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete role params +func (o *DeleteRoleParams) WithBmpLanguage(bmpLanguage *string) *DeleteRoleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete role params +func (o *DeleteRoleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete role params +func (o *DeleteRoleParams) WithBmpUserID(bmpUserID *string) *DeleteRoleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete role params +func (o *DeleteRoleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithRoleID adds the roleID to the delete role params +func (o *DeleteRoleParams) WithRoleID(roleID string) *DeleteRoleParams { + o.SetRoleID(roleID) + return o +} + +// SetRoleID adds the roleId to the delete role params +func (o *DeleteRoleParams) SetRoleID(roleID string) { + o.RoleID = roleID +} + +// WithTraceID adds the traceID to the delete role params +func (o *DeleteRoleParams) WithTraceID(traceID string) *DeleteRoleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete role params +func (o *DeleteRoleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteRoleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param role_id + if err := r.SetPathParam("role_id", o.RoleID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/delete_role_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/delete_role_responses.go new file mode 100644 index 0000000..4d9be49 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/delete_role_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteRoleReader is a Reader for the DeleteRole structure. +type DeleteRoleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteRoleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteRoleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteRoleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteRoleOK creates a DeleteRoleOK with default headers values +func NewDeleteRoleOK() *DeleteRoleOK { + return &DeleteRoleOK{} +} + +/* DeleteRoleOK describes a response with status code 200, with default header values. + +A DeleteRoleResult is an response struct that is used to delete role. +*/ +type DeleteRoleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteRoleOKBody +} + +// IsSuccess returns true when this delete role o k response has a 2xx status code +func (o *DeleteRoleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete role o k response has a 3xx status code +func (o *DeleteRoleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete role o k response has a 4xx status code +func (o *DeleteRoleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete role o k response has a 5xx status code +func (o *DeleteRoleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete role o k response a status code equal to that given +func (o *DeleteRoleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteRoleOK) Error() string { + return fmt.Sprintf("[DELETE /roles/{role_id}][%d] deleteRoleOK %+v", 200, o.Payload) +} + +func (o *DeleteRoleOK) String() string { + return fmt.Sprintf("[DELETE /roles/{role_id}][%d] deleteRoleOK %+v", 200, o.Payload) +} + +func (o *DeleteRoleOK) GetPayload() *DeleteRoleOKBody { + return o.Payload +} + +func (o *DeleteRoleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteRoleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteRoleDefault creates a DeleteRoleDefault with default headers values +func NewDeleteRoleDefault(code int) *DeleteRoleDefault { + return &DeleteRoleDefault{ + _statusCode: code, + } +} + +/* DeleteRoleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteRoleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteRoleDefaultBody +} + +// Code gets the status code for the delete role default response +func (o *DeleteRoleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete role default response has a 2xx status code +func (o *DeleteRoleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete role default response has a 3xx status code +func (o *DeleteRoleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete role default response has a 4xx status code +func (o *DeleteRoleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete role default response has a 5xx status code +func (o *DeleteRoleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete role default response a status code equal to that given +func (o *DeleteRoleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteRoleDefault) Error() string { + return fmt.Sprintf("[DELETE /roles/{role_id}][%d] deleteRole default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteRoleDefault) String() string { + return fmt.Sprintf("[DELETE /roles/{role_id}][%d] deleteRole default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteRoleDefault) GetPayload() *DeleteRoleDefaultBody { + return o.Payload +} + +func (o *DeleteRoleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteRoleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteRoleDefaultBody delete role default body +swagger:model DeleteRoleDefaultBody +*/ +type DeleteRoleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete role default body +func (o *DeleteRoleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRoleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteRole default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteRoleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteRole default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete role default body based on the context it is used +func (o *DeleteRoleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRoleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteRoleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteRoleDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteRoleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteRoleOKBody delete role o k body +swagger:model DeleteRoleOKBody +*/ +type DeleteRoleOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete role o k body +func (o *DeleteRoleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRoleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete role o k body based on the context it is used +func (o *DeleteRoleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteRoleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteRoleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteRoleOKBody) UnmarshalBinary(b []byte) error { + var res DeleteRoleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/describe_role_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/describe_role_parameters.go new file mode 100644 index 0000000..5cda2db --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/describe_role_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeRoleParams creates a new DescribeRoleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeRoleParams() *DescribeRoleParams { + return &DescribeRoleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeRoleParamsWithTimeout creates a new DescribeRoleParams object +// with the ability to set a timeout on a request. +func NewDescribeRoleParamsWithTimeout(timeout time.Duration) *DescribeRoleParams { + return &DescribeRoleParams{ + timeout: timeout, + } +} + +// NewDescribeRoleParamsWithContext creates a new DescribeRoleParams object +// with the ability to set a context for a request. +func NewDescribeRoleParamsWithContext(ctx context.Context) *DescribeRoleParams { + return &DescribeRoleParams{ + Context: ctx, + } +} + +// NewDescribeRoleParamsWithHTTPClient creates a new DescribeRoleParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeRoleParamsWithHTTPClient(client *http.Client) *DescribeRoleParams { + return &DescribeRoleParams{ + HTTPClient: client, + } +} + +/* DescribeRoleParams contains all the parameters to send to the API endpoint + for the describe role operation. + + Typically these are written to a http.Request. +*/ +type DescribeRoleParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // RoleID. + RoleID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRoleParams) WithDefaults() *DescribeRoleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRoleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe role params +func (o *DescribeRoleParams) WithTimeout(timeout time.Duration) *DescribeRoleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe role params +func (o *DescribeRoleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe role params +func (o *DescribeRoleParams) WithContext(ctx context.Context) *DescribeRoleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe role params +func (o *DescribeRoleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe role params +func (o *DescribeRoleParams) WithHTTPClient(client *http.Client) *DescribeRoleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe role params +func (o *DescribeRoleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe role params +func (o *DescribeRoleParams) WithAuthorization(authorization string) *DescribeRoleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe role params +func (o *DescribeRoleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe role params +func (o *DescribeRoleParams) WithBmpLanguage(bmpLanguage *string) *DescribeRoleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe role params +func (o *DescribeRoleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe role params +func (o *DescribeRoleParams) WithBmpUserID(bmpUserID *string) *DescribeRoleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe role params +func (o *DescribeRoleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithRoleID adds the roleID to the describe role params +func (o *DescribeRoleParams) WithRoleID(roleID string) *DescribeRoleParams { + o.SetRoleID(roleID) + return o +} + +// SetRoleID adds the roleId to the describe role params +func (o *DescribeRoleParams) SetRoleID(roleID string) { + o.RoleID = roleID +} + +// WithTraceID adds the traceID to the describe role params +func (o *DescribeRoleParams) WithTraceID(traceID string) *DescribeRoleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe role params +func (o *DescribeRoleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeRoleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param role_id + if err := r.SetPathParam("role_id", o.RoleID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/describe_role_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/describe_role_responses.go new file mode 100644 index 0000000..0ac2096 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/describe_role_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeRoleReader is a Reader for the DescribeRole structure. +type DescribeRoleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeRoleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeRoleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeRoleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeRoleOK creates a DescribeRoleOK with default headers values +func NewDescribeRoleOK() *DescribeRoleOK { + return &DescribeRoleOK{} +} + +/* DescribeRoleOK describes a response with status code 200, with default header values. + +A GetRoleResult is an response struct that is used to describe role. +*/ +type DescribeRoleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRoleOKBody +} + +// IsSuccess returns true when this describe role o k response has a 2xx status code +func (o *DescribeRoleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe role o k response has a 3xx status code +func (o *DescribeRoleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe role o k response has a 4xx status code +func (o *DescribeRoleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe role o k response has a 5xx status code +func (o *DescribeRoleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe role o k response a status code equal to that given +func (o *DescribeRoleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeRoleOK) Error() string { + return fmt.Sprintf("[GET /roles/{role_id}][%d] describeRoleOK %+v", 200, o.Payload) +} + +func (o *DescribeRoleOK) String() string { + return fmt.Sprintf("[GET /roles/{role_id}][%d] describeRoleOK %+v", 200, o.Payload) +} + +func (o *DescribeRoleOK) GetPayload() *DescribeRoleOKBody { + return o.Payload +} + +func (o *DescribeRoleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRoleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeRoleDefault creates a DescribeRoleDefault with default headers values +func NewDescribeRoleDefault(code int) *DescribeRoleDefault { + return &DescribeRoleDefault{ + _statusCode: code, + } +} + +/* DescribeRoleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeRoleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRoleDefaultBody +} + +// Code gets the status code for the describe role default response +func (o *DescribeRoleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe role default response has a 2xx status code +func (o *DescribeRoleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe role default response has a 3xx status code +func (o *DescribeRoleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe role default response has a 4xx status code +func (o *DescribeRoleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe role default response has a 5xx status code +func (o *DescribeRoleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe role default response a status code equal to that given +func (o *DescribeRoleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeRoleDefault) Error() string { + return fmt.Sprintf("[GET /roles/{role_id}][%d] describeRole default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRoleDefault) String() string { + return fmt.Sprintf("[GET /roles/{role_id}][%d] describeRole default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRoleDefault) GetPayload() *DescribeRoleDefaultBody { + return o.Payload +} + +func (o *DescribeRoleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRoleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeRoleDefaultBody describe role default body +swagger:model DescribeRoleDefaultBody +*/ +type DescribeRoleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe role default body +func (o *DescribeRoleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRoleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeRole default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeRoleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeRole default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe role default body based on the context it is used +func (o *DescribeRoleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRoleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRoleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRoleDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeRoleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeRoleOKBody describe role o k body +swagger:model DescribeRoleOKBody +*/ +type DescribeRoleOKBody struct { + + // result + Result *models.RoleInfo `json:"result,omitempty"` +} + +// Validate validates this describe role o k body +func (o *DescribeRoleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRoleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe role o k body based on the context it is used +func (o *DescribeRoleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRoleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRoleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRoleOKBody) UnmarshalBinary(b []byte) error { + var res DescribeRoleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/describe_roles_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/describe_roles_parameters.go new file mode 100644 index 0000000..d8b50db --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/describe_roles_parameters.go @@ -0,0 +1,328 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeRolesParams creates a new DescribeRolesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeRolesParams() *DescribeRolesParams { + return &DescribeRolesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeRolesParamsWithTimeout creates a new DescribeRolesParams object +// with the ability to set a timeout on a request. +func NewDescribeRolesParamsWithTimeout(timeout time.Duration) *DescribeRolesParams { + return &DescribeRolesParams{ + timeout: timeout, + } +} + +// NewDescribeRolesParamsWithContext creates a new DescribeRolesParams object +// with the ability to set a context for a request. +func NewDescribeRolesParamsWithContext(ctx context.Context) *DescribeRolesParams { + return &DescribeRolesParams{ + Context: ctx, + } +} + +// NewDescribeRolesParamsWithHTTPClient creates a new DescribeRolesParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeRolesParamsWithHTTPClient(client *http.Client) *DescribeRolesParams { + return &DescribeRolesParams{ + HTTPClient: client, + } +} + +/* DescribeRolesParams contains all the parameters to send to the API endpoint + for the describe roles operation. + + Typically these are written to a http.Request. +*/ +type DescribeRolesParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否显示所有 + */ + IsAll *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe roles params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRolesParams) WithDefaults() *DescribeRolesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe roles params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeRolesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe roles params +func (o *DescribeRolesParams) WithTimeout(timeout time.Duration) *DescribeRolesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe roles params +func (o *DescribeRolesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe roles params +func (o *DescribeRolesParams) WithContext(ctx context.Context) *DescribeRolesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe roles params +func (o *DescribeRolesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe roles params +func (o *DescribeRolesParams) WithHTTPClient(client *http.Client) *DescribeRolesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe roles params +func (o *DescribeRolesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe roles params +func (o *DescribeRolesParams) WithAuthorization(authorization string) *DescribeRolesParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe roles params +func (o *DescribeRolesParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe roles params +func (o *DescribeRolesParams) WithBmpLanguage(bmpLanguage *string) *DescribeRolesParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe roles params +func (o *DescribeRolesParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe roles params +func (o *DescribeRolesParams) WithBmpUserID(bmpUserID *string) *DescribeRolesParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe roles params +func (o *DescribeRolesParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe roles params +func (o *DescribeRolesParams) WithIsAll(isAll *string) *DescribeRolesParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe roles params +func (o *DescribeRolesParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithPageNumber adds the pageNumber to the describe roles params +func (o *DescribeRolesParams) WithPageNumber(pageNumber *int64) *DescribeRolesParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe roles params +func (o *DescribeRolesParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe roles params +func (o *DescribeRolesParams) WithPageSize(pageSize *int64) *DescribeRolesParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe roles params +func (o *DescribeRolesParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe roles params +func (o *DescribeRolesParams) WithTraceID(traceID string) *DescribeRolesParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe roles params +func (o *DescribeRolesParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeRolesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/describe_roles_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/describe_roles_responses.go new file mode 100644 index 0000000..c4d6d29 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/describe_roles_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeRolesReader is a Reader for the DescribeRoles structure. +type DescribeRolesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeRolesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeRolesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeRolesDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeRolesOK creates a DescribeRolesOK with default headers values +func NewDescribeRolesOK() *DescribeRolesOK { + return &DescribeRolesOK{} +} + +/* DescribeRolesOK describes a response with status code 200, with default header values. + +A GetRoleListResult is an response struct that is used to describe get role list. +*/ +type DescribeRolesOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRolesOKBody +} + +// IsSuccess returns true when this describe roles o k response has a 2xx status code +func (o *DescribeRolesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe roles o k response has a 3xx status code +func (o *DescribeRolesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe roles o k response has a 4xx status code +func (o *DescribeRolesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe roles o k response has a 5xx status code +func (o *DescribeRolesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe roles o k response a status code equal to that given +func (o *DescribeRolesOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeRolesOK) Error() string { + return fmt.Sprintf("[GET /roles][%d] describeRolesOK %+v", 200, o.Payload) +} + +func (o *DescribeRolesOK) String() string { + return fmt.Sprintf("[GET /roles][%d] describeRolesOK %+v", 200, o.Payload) +} + +func (o *DescribeRolesOK) GetPayload() *DescribeRolesOKBody { + return o.Payload +} + +func (o *DescribeRolesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRolesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeRolesDefault creates a DescribeRolesDefault with default headers values +func NewDescribeRolesDefault(code int) *DescribeRolesDefault { + return &DescribeRolesDefault{ + _statusCode: code, + } +} + +/* DescribeRolesDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeRolesDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeRolesDefaultBody +} + +// Code gets the status code for the describe roles default response +func (o *DescribeRolesDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe roles default response has a 2xx status code +func (o *DescribeRolesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe roles default response has a 3xx status code +func (o *DescribeRolesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe roles default response has a 4xx status code +func (o *DescribeRolesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe roles default response has a 5xx status code +func (o *DescribeRolesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe roles default response a status code equal to that given +func (o *DescribeRolesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeRolesDefault) Error() string { + return fmt.Sprintf("[GET /roles][%d] describeRoles default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRolesDefault) String() string { + return fmt.Sprintf("[GET /roles][%d] describeRoles default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeRolesDefault) GetPayload() *DescribeRolesDefaultBody { + return o.Payload +} + +func (o *DescribeRolesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeRolesDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeRolesDefaultBody describe roles default body +swagger:model DescribeRolesDefaultBody +*/ +type DescribeRolesDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe roles default body +func (o *DescribeRolesDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRolesDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeRoles default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeRolesDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeRoles default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRoles default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRoles default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe roles default body based on the context it is used +func (o *DescribeRolesDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRolesDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRoles default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRoles default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRolesDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRolesDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeRolesDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeRolesOKBody describe roles o k body +swagger:model DescribeRolesOKBody +*/ +type DescribeRolesOKBody struct { + + // result + Result *models.RoleList `json:"result,omitempty"` +} + +// Validate validates this describe roles o k body +func (o *DescribeRolesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRolesOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRolesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRolesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe roles o k body based on the context it is used +func (o *DescribeRolesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeRolesOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeRolesOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeRolesOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeRolesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeRolesOKBody) UnmarshalBinary(b []byte) error { + var res DescribeRolesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/modify_role_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/modify_role_parameters.go new file mode 100644 index 0000000..5973443 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/modify_role_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyRoleParams creates a new ModifyRoleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyRoleParams() *ModifyRoleParams { + return &ModifyRoleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyRoleParamsWithTimeout creates a new ModifyRoleParams object +// with the ability to set a timeout on a request. +func NewModifyRoleParamsWithTimeout(timeout time.Duration) *ModifyRoleParams { + return &ModifyRoleParams{ + timeout: timeout, + } +} + +// NewModifyRoleParamsWithContext creates a new ModifyRoleParams object +// with the ability to set a context for a request. +func NewModifyRoleParamsWithContext(ctx context.Context) *ModifyRoleParams { + return &ModifyRoleParams{ + Context: ctx, + } +} + +// NewModifyRoleParamsWithHTTPClient creates a new ModifyRoleParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyRoleParamsWithHTTPClient(client *http.Client) *ModifyRoleParams { + return &ModifyRoleParams{ + HTTPClient: client, + } +} + +/* ModifyRoleParams contains all the parameters to send to the API endpoint + for the modify role operation. + + Typically these are written to a http.Request. +*/ +type ModifyRoleParams struct { + + // Body. + Body *models.ModifyRoleRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // RoleID. + RoleID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyRoleParams) WithDefaults() *ModifyRoleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify role params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyRoleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify role params +func (o *ModifyRoleParams) WithTimeout(timeout time.Duration) *ModifyRoleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify role params +func (o *ModifyRoleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify role params +func (o *ModifyRoleParams) WithContext(ctx context.Context) *ModifyRoleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify role params +func (o *ModifyRoleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify role params +func (o *ModifyRoleParams) WithHTTPClient(client *http.Client) *ModifyRoleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify role params +func (o *ModifyRoleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify role params +func (o *ModifyRoleParams) WithBody(body *models.ModifyRoleRequest) *ModifyRoleParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify role params +func (o *ModifyRoleParams) SetBody(body *models.ModifyRoleRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify role params +func (o *ModifyRoleParams) WithAuthorization(authorization string) *ModifyRoleParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify role params +func (o *ModifyRoleParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify role params +func (o *ModifyRoleParams) WithBmpLanguage(bmpLanguage *string) *ModifyRoleParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify role params +func (o *ModifyRoleParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify role params +func (o *ModifyRoleParams) WithBmpUserID(bmpUserID *string) *ModifyRoleParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify role params +func (o *ModifyRoleParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithRoleID adds the roleID to the modify role params +func (o *ModifyRoleParams) WithRoleID(roleID string) *ModifyRoleParams { + o.SetRoleID(roleID) + return o +} + +// SetRoleID adds the roleId to the modify role params +func (o *ModifyRoleParams) SetRoleID(roleID string) { + o.RoleID = roleID +} + +// WithTraceID adds the traceID to the modify role params +func (o *ModifyRoleParams) WithTraceID(traceID string) *ModifyRoleParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify role params +func (o *ModifyRoleParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyRoleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param role_id + if err := r.SetPathParam("role_id", o.RoleID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/modify_role_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/modify_role_responses.go new file mode 100644 index 0000000..4893a88 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/modify_role_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyRoleReader is a Reader for the ModifyRole structure. +type ModifyRoleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyRoleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyRoleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyRoleDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyRoleOK creates a ModifyRoleOK with default headers values +func NewModifyRoleOK() *ModifyRoleOK { + return &ModifyRoleOK{} +} + +/* ModifyRoleOK describes a response with status code 200, with default header values. + +A ModifyRoleResult is an response struct that is used to describe modify role. +*/ +type ModifyRoleOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyRoleOKBody +} + +// IsSuccess returns true when this modify role o k response has a 2xx status code +func (o *ModifyRoleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify role o k response has a 3xx status code +func (o *ModifyRoleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify role o k response has a 4xx status code +func (o *ModifyRoleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify role o k response has a 5xx status code +func (o *ModifyRoleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify role o k response a status code equal to that given +func (o *ModifyRoleOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyRoleOK) Error() string { + return fmt.Sprintf("[PUT /roles/{role_id}][%d] modifyRoleOK %+v", 200, o.Payload) +} + +func (o *ModifyRoleOK) String() string { + return fmt.Sprintf("[PUT /roles/{role_id}][%d] modifyRoleOK %+v", 200, o.Payload) +} + +func (o *ModifyRoleOK) GetPayload() *ModifyRoleOKBody { + return o.Payload +} + +func (o *ModifyRoleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyRoleOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyRoleDefault creates a ModifyRoleDefault with default headers values +func NewModifyRoleDefault(code int) *ModifyRoleDefault { + return &ModifyRoleDefault{ + _statusCode: code, + } +} + +/* ModifyRoleDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyRoleDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyRoleDefaultBody +} + +// Code gets the status code for the modify role default response +func (o *ModifyRoleDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify role default response has a 2xx status code +func (o *ModifyRoleDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify role default response has a 3xx status code +func (o *ModifyRoleDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify role default response has a 4xx status code +func (o *ModifyRoleDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify role default response has a 5xx status code +func (o *ModifyRoleDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify role default response a status code equal to that given +func (o *ModifyRoleDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyRoleDefault) Error() string { + return fmt.Sprintf("[PUT /roles/{role_id}][%d] modifyRole default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyRoleDefault) String() string { + return fmt.Sprintf("[PUT /roles/{role_id}][%d] modifyRole default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyRoleDefault) GetPayload() *ModifyRoleDefaultBody { + return o.Payload +} + +func (o *ModifyRoleDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyRoleDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyRoleDefaultBody modify role default body +swagger:model ModifyRoleDefaultBody +*/ +type ModifyRoleDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify role default body +func (o *ModifyRoleDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRoleDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyRole default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyRoleDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyRole default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify role default body based on the context it is used +func (o *ModifyRoleDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRoleDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRole default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRole default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyRoleDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyRoleDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyRoleDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyRoleOKBody modify role o k body +swagger:model ModifyRoleOKBody +*/ +type ModifyRoleOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify role o k body +func (o *ModifyRoleOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRoleOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify role o k body based on the context it is used +func (o *ModifyRoleOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyRoleOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyRoleOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyRoleOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyRoleOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyRoleOKBody) UnmarshalBinary(b []byte) error { + var res ModifyRoleOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/role_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/role_client.go new file mode 100644 index 0000000..8f729cb --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/role/role_client.go @@ -0,0 +1,277 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package role + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new role API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for role API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateRole(params *CreateRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateRoleOK, error) + + CurrentRole(params *CurrentRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CurrentRoleOK, error) + + DeleteRole(params *DeleteRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteRoleOK, error) + + DescribeRole(params *DescribeRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRoleOK, error) + + DescribeRoles(params *DescribeRolesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRolesOK, error) + + ModifyRole(params *ModifyRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyRoleOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateRole CreateRole 创建角色(暂不启用) +*/ +func (a *Client) CreateRole(params *CreateRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateRoleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateRoleParams() + } + op := &runtime.ClientOperation{ + ID: "createRole", + Method: "POST", + PathPattern: "/roles", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateRoleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateRoleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateRoleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + CurrentRole CurrentRole 获取当前登录用户的角色 +*/ +func (a *Client) CurrentRole(params *CurrentRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CurrentRoleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCurrentRoleParams() + } + op := &runtime.ClientOperation{ + ID: "currentRole", + Method: "GET", + PathPattern: "/roles/roleInfo/current", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CurrentRoleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CurrentRoleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CurrentRoleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteRole DeleteRole 删除角色(暂不启用) +*/ +func (a *Client) DeleteRole(params *DeleteRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteRoleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteRoleParams() + } + op := &runtime.ClientOperation{ + ID: "deleteRole", + Method: "DELETE", + PathPattern: "/roles/{role_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteRoleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteRoleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteRoleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeRole DescribeRole 获取角色详情 +*/ +func (a *Client) DescribeRole(params *DescribeRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRoleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeRoleParams() + } + op := &runtime.ClientOperation{ + ID: "describeRole", + Method: "GET", + PathPattern: "/roles/{role_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeRoleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeRoleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeRoleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeRoles DescribeRoles 获取角色列表 +*/ +func (a *Client) DescribeRoles(params *DescribeRolesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeRolesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeRolesParams() + } + op := &runtime.ClientOperation{ + ID: "describeRoles", + Method: "GET", + PathPattern: "/roles", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeRolesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeRolesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeRolesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyRole ModifyRole 修改角色信息(暂不启用) +*/ +func (a *Client) ModifyRole(params *ModifyRoleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyRoleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyRoleParams() + } + op := &runtime.ClientOperation{ + ID: "modifyRole", + Method: "PUT", + PathPattern: "/roles/{role_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyRoleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyRoleOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyRoleDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/create_user_sshkey_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/create_user_sshkey_parameters.go new file mode 100644 index 0000000..1216d68 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/create_user_sshkey_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateUserSshkeyParams creates a new CreateUserSshkeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateUserSshkeyParams() *CreateUserSshkeyParams { + return &CreateUserSshkeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateUserSshkeyParamsWithTimeout creates a new CreateUserSshkeyParams object +// with the ability to set a timeout on a request. +func NewCreateUserSshkeyParamsWithTimeout(timeout time.Duration) *CreateUserSshkeyParams { + return &CreateUserSshkeyParams{ + timeout: timeout, + } +} + +// NewCreateUserSshkeyParamsWithContext creates a new CreateUserSshkeyParams object +// with the ability to set a context for a request. +func NewCreateUserSshkeyParamsWithContext(ctx context.Context) *CreateUserSshkeyParams { + return &CreateUserSshkeyParams{ + Context: ctx, + } +} + +// NewCreateUserSshkeyParamsWithHTTPClient creates a new CreateUserSshkeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateUserSshkeyParamsWithHTTPClient(client *http.Client) *CreateUserSshkeyParams { + return &CreateUserSshkeyParams{ + HTTPClient: client, + } +} + +/* CreateUserSshkeyParams contains all the parameters to send to the API endpoint + for the create user sshkey operation. + + Typically these are written to a http.Request. +*/ +type CreateUserSshkeyParams struct { + + // Body. + Body *models.CreateSshkeyRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserSshkeyParams) WithDefaults() *CreateUserSshkeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserSshkeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create user sshkey params +func (o *CreateUserSshkeyParams) WithTimeout(timeout time.Duration) *CreateUserSshkeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create user sshkey params +func (o *CreateUserSshkeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create user sshkey params +func (o *CreateUserSshkeyParams) WithContext(ctx context.Context) *CreateUserSshkeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create user sshkey params +func (o *CreateUserSshkeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create user sshkey params +func (o *CreateUserSshkeyParams) WithHTTPClient(client *http.Client) *CreateUserSshkeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create user sshkey params +func (o *CreateUserSshkeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create user sshkey params +func (o *CreateUserSshkeyParams) WithBody(body *models.CreateSshkeyRequest) *CreateUserSshkeyParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create user sshkey params +func (o *CreateUserSshkeyParams) SetBody(body *models.CreateSshkeyRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create user sshkey params +func (o *CreateUserSshkeyParams) WithAuthorization(authorization string) *CreateUserSshkeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create user sshkey params +func (o *CreateUserSshkeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create user sshkey params +func (o *CreateUserSshkeyParams) WithBmpLanguage(bmpLanguage *string) *CreateUserSshkeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create user sshkey params +func (o *CreateUserSshkeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create user sshkey params +func (o *CreateUserSshkeyParams) WithBmpUserID(bmpUserID *string) *CreateUserSshkeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create user sshkey params +func (o *CreateUserSshkeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create user sshkey params +func (o *CreateUserSshkeyParams) WithTraceID(traceID string) *CreateUserSshkeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create user sshkey params +func (o *CreateUserSshkeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateUserSshkeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/create_user_sshkey_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/create_user_sshkey_responses.go new file mode 100644 index 0000000..1d5e6cb --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/create_user_sshkey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateUserSshkeyReader is a Reader for the CreateUserSshkey structure. +type CreateUserSshkeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateUserSshkeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateUserSshkeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateUserSshkeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateUserSshkeyOK creates a CreateUserSshkeyOK with default headers values +func NewCreateUserSshkeyOK() *CreateUserSshkeyOK { + return &CreateUserSshkeyOK{} +} + +/* CreateUserSshkeyOK describes a response with status code 200, with default header values. + +A CreateUserSshkeyResult is an response struct that is used to describe create sshkey result. +*/ +type CreateUserSshkeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserSshkeyOKBody +} + +// IsSuccess returns true when this create user sshkey o k response has a 2xx status code +func (o *CreateUserSshkeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create user sshkey o k response has a 3xx status code +func (o *CreateUserSshkeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create user sshkey o k response has a 4xx status code +func (o *CreateUserSshkeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create user sshkey o k response has a 5xx status code +func (o *CreateUserSshkeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create user sshkey o k response a status code equal to that given +func (o *CreateUserSshkeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateUserSshkeyOK) Error() string { + return fmt.Sprintf("[POST /user/sshkeys][%d] createUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *CreateUserSshkeyOK) String() string { + return fmt.Sprintf("[POST /user/sshkeys][%d] createUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *CreateUserSshkeyOK) GetPayload() *CreateUserSshkeyOKBody { + return o.Payload +} + +func (o *CreateUserSshkeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserSshkeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateUserSshkeyDefault creates a CreateUserSshkeyDefault with default headers values +func NewCreateUserSshkeyDefault(code int) *CreateUserSshkeyDefault { + return &CreateUserSshkeyDefault{ + _statusCode: code, + } +} + +/* CreateUserSshkeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateUserSshkeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserSshkeyDefaultBody +} + +// Code gets the status code for the create user sshkey default response +func (o *CreateUserSshkeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create user sshkey default response has a 2xx status code +func (o *CreateUserSshkeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create user sshkey default response has a 3xx status code +func (o *CreateUserSshkeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create user sshkey default response has a 4xx status code +func (o *CreateUserSshkeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create user sshkey default response has a 5xx status code +func (o *CreateUserSshkeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create user sshkey default response a status code equal to that given +func (o *CreateUserSshkeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateUserSshkeyDefault) Error() string { + return fmt.Sprintf("[POST /user/sshkeys][%d] createUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserSshkeyDefault) String() string { + return fmt.Sprintf("[POST /user/sshkeys][%d] createUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserSshkeyDefault) GetPayload() *CreateUserSshkeyDefaultBody { + return o.Payload +} + +func (o *CreateUserSshkeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserSshkeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateUserSshkeyDefaultBody create user sshkey default body +swagger:model CreateUserSshkeyDefaultBody +*/ +type CreateUserSshkeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create user sshkey default body +func (o *CreateUserSshkeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserSshkeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createUserSshkey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateUserSshkeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createUserSshkey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user sshkey default body based on the context it is used +func (o *CreateUserSshkeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserSshkeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserSshkeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserSshkeyDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateUserSshkeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateUserSshkeyOKBody create user sshkey o k body +swagger:model CreateUserSshkeyOKBody +*/ +type CreateUserSshkeyOKBody struct { + + // result + Result *models.SshkeyID `json:"result,omitempty"` +} + +// Validate validates this create user sshkey o k body +func (o *CreateUserSshkeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserSshkeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user sshkey o k body based on the context it is used +func (o *CreateUserSshkeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserSshkeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserSshkeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserSshkeyOKBody) UnmarshalBinary(b []byte) error { + var res CreateUserSshkeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/delete_user_sshkey_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/delete_user_sshkey_parameters.go new file mode 100644 index 0000000..9fdcc89 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/delete_user_sshkey_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteUserSshkeyParams creates a new DeleteUserSshkeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteUserSshkeyParams() *DeleteUserSshkeyParams { + return &DeleteUserSshkeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteUserSshkeyParamsWithTimeout creates a new DeleteUserSshkeyParams object +// with the ability to set a timeout on a request. +func NewDeleteUserSshkeyParamsWithTimeout(timeout time.Duration) *DeleteUserSshkeyParams { + return &DeleteUserSshkeyParams{ + timeout: timeout, + } +} + +// NewDeleteUserSshkeyParamsWithContext creates a new DeleteUserSshkeyParams object +// with the ability to set a context for a request. +func NewDeleteUserSshkeyParamsWithContext(ctx context.Context) *DeleteUserSshkeyParams { + return &DeleteUserSshkeyParams{ + Context: ctx, + } +} + +// NewDeleteUserSshkeyParamsWithHTTPClient creates a new DeleteUserSshkeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteUserSshkeyParamsWithHTTPClient(client *http.Client) *DeleteUserSshkeyParams { + return &DeleteUserSshkeyParams{ + HTTPClient: client, + } +} + +/* DeleteUserSshkeyParams contains all the parameters to send to the API endpoint + for the delete user sshkey operation. + + Typically these are written to a http.Request. +*/ +type DeleteUserSshkeyParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // SshkeyID. + SshkeyID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserSshkeyParams) WithDefaults() *DeleteUserSshkeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserSshkeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithTimeout(timeout time.Duration) *DeleteUserSshkeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithContext(ctx context.Context) *DeleteUserSshkeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithHTTPClient(client *http.Client) *DeleteUserSshkeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithAuthorization(authorization string) *DeleteUserSshkeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithBmpLanguage(bmpLanguage *string) *DeleteUserSshkeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithBmpUserID(bmpUserID *string) *DeleteUserSshkeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithSshkeyID adds the sshkeyID to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithSshkeyID(sshkeyID string) *DeleteUserSshkeyParams { + o.SetSshkeyID(sshkeyID) + return o +} + +// SetSshkeyID adds the sshkeyId to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetSshkeyID(sshkeyID string) { + o.SshkeyID = sshkeyID +} + +// WithTraceID adds the traceID to the delete user sshkey params +func (o *DeleteUserSshkeyParams) WithTraceID(traceID string) *DeleteUserSshkeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete user sshkey params +func (o *DeleteUserSshkeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteUserSshkeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param sshkey_id + if err := r.SetPathParam("sshkey_id", o.SshkeyID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/delete_user_sshkey_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/delete_user_sshkey_responses.go new file mode 100644 index 0000000..461caf2 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/delete_user_sshkey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteUserSshkeyReader is a Reader for the DeleteUserSshkey structure. +type DeleteUserSshkeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteUserSshkeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteUserSshkeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteUserSshkeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteUserSshkeyOK creates a DeleteUserSshkeyOK with default headers values +func NewDeleteUserSshkeyOK() *DeleteUserSshkeyOK { + return &DeleteUserSshkeyOK{} +} + +/* DeleteUserSshkeyOK describes a response with status code 200, with default header values. + +A DeleteUserSshkeyResult is an response struct that is used to describe delete sshkey result. +*/ +type DeleteUserSshkeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserSshkeyOKBody +} + +// IsSuccess returns true when this delete user sshkey o k response has a 2xx status code +func (o *DeleteUserSshkeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete user sshkey o k response has a 3xx status code +func (o *DeleteUserSshkeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete user sshkey o k response has a 4xx status code +func (o *DeleteUserSshkeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete user sshkey o k response has a 5xx status code +func (o *DeleteUserSshkeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete user sshkey o k response a status code equal to that given +func (o *DeleteUserSshkeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteUserSshkeyOK) Error() string { + return fmt.Sprintf("[DELETE /user/sshkeys/{sshkey_id}][%d] deleteUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *DeleteUserSshkeyOK) String() string { + return fmt.Sprintf("[DELETE /user/sshkeys/{sshkey_id}][%d] deleteUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *DeleteUserSshkeyOK) GetPayload() *DeleteUserSshkeyOKBody { + return o.Payload +} + +func (o *DeleteUserSshkeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserSshkeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteUserSshkeyDefault creates a DeleteUserSshkeyDefault with default headers values +func NewDeleteUserSshkeyDefault(code int) *DeleteUserSshkeyDefault { + return &DeleteUserSshkeyDefault{ + _statusCode: code, + } +} + +/* DeleteUserSshkeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteUserSshkeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserSshkeyDefaultBody +} + +// Code gets the status code for the delete user sshkey default response +func (o *DeleteUserSshkeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete user sshkey default response has a 2xx status code +func (o *DeleteUserSshkeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete user sshkey default response has a 3xx status code +func (o *DeleteUserSshkeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete user sshkey default response has a 4xx status code +func (o *DeleteUserSshkeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete user sshkey default response has a 5xx status code +func (o *DeleteUserSshkeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete user sshkey default response a status code equal to that given +func (o *DeleteUserSshkeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteUserSshkeyDefault) Error() string { + return fmt.Sprintf("[DELETE /user/sshkeys/{sshkey_id}][%d] deleteUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserSshkeyDefault) String() string { + return fmt.Sprintf("[DELETE /user/sshkeys/{sshkey_id}][%d] deleteUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserSshkeyDefault) GetPayload() *DeleteUserSshkeyDefaultBody { + return o.Payload +} + +func (o *DeleteUserSshkeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserSshkeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteUserSshkeyDefaultBody delete user sshkey default body +swagger:model DeleteUserSshkeyDefaultBody +*/ +type DeleteUserSshkeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete user sshkey default body +func (o *DeleteUserSshkeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserSshkeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserSshkey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteUserSshkeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteUserSshkey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user sshkey default body based on the context it is used +func (o *DeleteUserSshkeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserSshkeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserSshkeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserSshkeyDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteUserSshkeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteUserSshkeyOKBody delete user sshkey o k body +swagger:model DeleteUserSshkeyOKBody +*/ +type DeleteUserSshkeyOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete user sshkey o k body +func (o *DeleteUserSshkeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserSshkeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user sshkey o k body based on the context it is used +func (o *DeleteUserSshkeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserSshkeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserSshkeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserSshkeyOKBody) UnmarshalBinary(b []byte) error { + var res DeleteUserSshkeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_key_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_key_parameters.go new file mode 100644 index 0000000..0039fc8 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_key_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeUserSSHKeyParams creates a new DescribeUserSSHKeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserSSHKeyParams() *DescribeUserSSHKeyParams { + return &DescribeUserSSHKeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserSSHKeyParamsWithTimeout creates a new DescribeUserSSHKeyParams object +// with the ability to set a timeout on a request. +func NewDescribeUserSSHKeyParamsWithTimeout(timeout time.Duration) *DescribeUserSSHKeyParams { + return &DescribeUserSSHKeyParams{ + timeout: timeout, + } +} + +// NewDescribeUserSSHKeyParamsWithContext creates a new DescribeUserSSHKeyParams object +// with the ability to set a context for a request. +func NewDescribeUserSSHKeyParamsWithContext(ctx context.Context) *DescribeUserSSHKeyParams { + return &DescribeUserSSHKeyParams{ + Context: ctx, + } +} + +// NewDescribeUserSSHKeyParamsWithHTTPClient creates a new DescribeUserSSHKeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserSSHKeyParamsWithHTTPClient(client *http.Client) *DescribeUserSSHKeyParams { + return &DescribeUserSSHKeyParams{ + HTTPClient: client, + } +} + +/* DescribeUserSSHKeyParams contains all the parameters to send to the API endpoint + for the describe user Ssh key operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserSSHKeyParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // SshkeyID. + SshkeyID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user Ssh key params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserSSHKeyParams) WithDefaults() *DescribeUserSSHKeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user Ssh key params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserSSHKeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithTimeout(timeout time.Duration) *DescribeUserSSHKeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithContext(ctx context.Context) *DescribeUserSSHKeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithHTTPClient(client *http.Client) *DescribeUserSSHKeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithAuthorization(authorization string) *DescribeUserSSHKeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserSSHKeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithBmpUserID(bmpUserID *string) *DescribeUserSSHKeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithSshkeyID adds the sshkeyID to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithSshkeyID(sshkeyID string) *DescribeUserSSHKeyParams { + o.SetSshkeyID(sshkeyID) + return o +} + +// SetSshkeyID adds the sshkeyId to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetSshkeyID(sshkeyID string) { + o.SshkeyID = sshkeyID +} + +// WithTraceID adds the traceID to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) WithTraceID(traceID string) *DescribeUserSSHKeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user Ssh key params +func (o *DescribeUserSSHKeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserSSHKeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param sshkey_id + if err := r.SetPathParam("sshkey_id", o.SshkeyID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_key_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_key_responses.go new file mode 100644 index 0000000..572eba8 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_key_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserSSHKeyReader is a Reader for the DescribeUserSSHKey structure. +type DescribeUserSSHKeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserSSHKeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserSSHKeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserSSHKeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserSSHKeyOK creates a DescribeUserSSHKeyOK with default headers values +func NewDescribeUserSSHKeyOK() *DescribeUserSSHKeyOK { + return &DescribeUserSSHKeyOK{} +} + +/* DescribeUserSSHKeyOK describes a response with status code 200, with default header values. + +A DescribeUserSshKeyResult is an response struct that is used to describe sshkey. +*/ +type DescribeUserSSHKeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserSSHKeyOKBody +} + +// IsSuccess returns true when this describe user Ssh key o k response has a 2xx status code +func (o *DescribeUserSSHKeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user Ssh key o k response has a 3xx status code +func (o *DescribeUserSSHKeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user Ssh key o k response has a 4xx status code +func (o *DescribeUserSSHKeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user Ssh key o k response has a 5xx status code +func (o *DescribeUserSSHKeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user Ssh key o k response a status code equal to that given +func (o *DescribeUserSSHKeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserSSHKeyOK) Error() string { + return fmt.Sprintf("[GET /user/sshkeys/{sshkey_id}][%d] describeUserSshKeyOK %+v", 200, o.Payload) +} + +func (o *DescribeUserSSHKeyOK) String() string { + return fmt.Sprintf("[GET /user/sshkeys/{sshkey_id}][%d] describeUserSshKeyOK %+v", 200, o.Payload) +} + +func (o *DescribeUserSSHKeyOK) GetPayload() *DescribeUserSSHKeyOKBody { + return o.Payload +} + +func (o *DescribeUserSSHKeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserSSHKeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserSSHKeyDefault creates a DescribeUserSSHKeyDefault with default headers values +func NewDescribeUserSSHKeyDefault(code int) *DescribeUserSSHKeyDefault { + return &DescribeUserSSHKeyDefault{ + _statusCode: code, + } +} + +/* DescribeUserSSHKeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserSSHKeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserSSHKeyDefaultBody +} + +// Code gets the status code for the describe user Ssh key default response +func (o *DescribeUserSSHKeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user Ssh key default response has a 2xx status code +func (o *DescribeUserSSHKeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user Ssh key default response has a 3xx status code +func (o *DescribeUserSSHKeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user Ssh key default response has a 4xx status code +func (o *DescribeUserSSHKeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user Ssh key default response has a 5xx status code +func (o *DescribeUserSSHKeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user Ssh key default response a status code equal to that given +func (o *DescribeUserSSHKeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserSSHKeyDefault) Error() string { + return fmt.Sprintf("[GET /user/sshkeys/{sshkey_id}][%d] describeUserSshKey default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserSSHKeyDefault) String() string { + return fmt.Sprintf("[GET /user/sshkeys/{sshkey_id}][%d] describeUserSshKey default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserSSHKeyDefault) GetPayload() *DescribeUserSSHKeyDefaultBody { + return o.Payload +} + +func (o *DescribeUserSSHKeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserSSHKeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserSSHKeyDefaultBody describe user SSH key default body +swagger:model DescribeUserSSHKeyDefaultBody +*/ +type DescribeUserSSHKeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user SSH key default body +func (o *DescribeUserSSHKeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserSshKey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserSSHKeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserSshKey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user SSH key default body based on the context it is used +func (o *DescribeUserSSHKeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserSSHKeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserSSHKeyDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserSSHKeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserSSHKeyOKBody describe user SSH key o k body +swagger:model DescribeUserSSHKeyOKBody +*/ +type DescribeUserSSHKeyOKBody struct { + + // result + Result *models.SshkeyInfo `json:"result,omitempty"` +} + +// Validate validates this describe user SSH key o k body +func (o *DescribeUserSSHKeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user SSH key o k body based on the context it is used +func (o *DescribeUserSSHKeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserSSHKeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserSSHKeyOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserSSHKeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_keys_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_keys_parameters.go new file mode 100644 index 0000000..78cbf1f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_keys_parameters.go @@ -0,0 +1,362 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeUserSSHKeysParams creates a new DescribeUserSSHKeysParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserSSHKeysParams() *DescribeUserSSHKeysParams { + return &DescribeUserSSHKeysParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserSSHKeysParamsWithTimeout creates a new DescribeUserSSHKeysParams object +// with the ability to set a timeout on a request. +func NewDescribeUserSSHKeysParamsWithTimeout(timeout time.Duration) *DescribeUserSSHKeysParams { + return &DescribeUserSSHKeysParams{ + timeout: timeout, + } +} + +// NewDescribeUserSSHKeysParamsWithContext creates a new DescribeUserSSHKeysParams object +// with the ability to set a context for a request. +func NewDescribeUserSSHKeysParamsWithContext(ctx context.Context) *DescribeUserSSHKeysParams { + return &DescribeUserSSHKeysParams{ + Context: ctx, + } +} + +// NewDescribeUserSSHKeysParamsWithHTTPClient creates a new DescribeUserSSHKeysParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserSSHKeysParamsWithHTTPClient(client *http.Client) *DescribeUserSSHKeysParams { + return &DescribeUserSSHKeysParams{ + HTTPClient: client, + } +} + +/* DescribeUserSSHKeysParams contains all the parameters to send to the API endpoint + for the describe user Ssh keys operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserSSHKeysParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* IsAll. + + 是否显示全部 + */ + IsAll *string + + /* Name. + + 秘钥名称 + */ + Name *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user Ssh keys params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserSSHKeysParams) WithDefaults() *DescribeUserSSHKeysParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user Ssh keys params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserSSHKeysParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithTimeout(timeout time.Duration) *DescribeUserSSHKeysParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithContext(ctx context.Context) *DescribeUserSSHKeysParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithHTTPClient(client *http.Client) *DescribeUserSSHKeysParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithAuthorization(authorization string) *DescribeUserSSHKeysParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserSSHKeysParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithBmpUserID(bmpUserID *string) *DescribeUserSSHKeysParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithIsAll adds the isAll to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithIsAll(isAll *string) *DescribeUserSSHKeysParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithName adds the name to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithName(name *string) *DescribeUserSSHKeysParams { + o.SetName(name) + return o +} + +// SetName adds the name to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetName(name *string) { + o.Name = name +} + +// WithPageNumber adds the pageNumber to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithPageNumber(pageNumber *int64) *DescribeUserSSHKeysParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithPageSize(pageSize *int64) *DescribeUserSSHKeysParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithTraceID adds the traceID to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) WithTraceID(traceID string) *DescribeUserSSHKeysParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user Ssh keys params +func (o *DescribeUserSSHKeysParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserSSHKeysParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_keys_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_keys_responses.go new file mode 100644 index 0000000..db54423 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/describe_user_ssh_keys_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserSSHKeysReader is a Reader for the DescribeUserSSHKeys structure. +type DescribeUserSSHKeysReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserSSHKeysReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserSSHKeysOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserSSHKeysDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserSSHKeysOK creates a DescribeUserSSHKeysOK with default headers values +func NewDescribeUserSSHKeysOK() *DescribeUserSSHKeysOK { + return &DescribeUserSSHKeysOK{} +} + +/* DescribeUserSSHKeysOK describes a response with status code 200, with default header values. + +A DescribeUserSshKeysResult is an response struct that is used to describe get sshkey list. +*/ +type DescribeUserSSHKeysOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserSSHKeysOKBody +} + +// IsSuccess returns true when this describe user Ssh keys o k response has a 2xx status code +func (o *DescribeUserSSHKeysOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user Ssh keys o k response has a 3xx status code +func (o *DescribeUserSSHKeysOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user Ssh keys o k response has a 4xx status code +func (o *DescribeUserSSHKeysOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user Ssh keys o k response has a 5xx status code +func (o *DescribeUserSSHKeysOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user Ssh keys o k response a status code equal to that given +func (o *DescribeUserSSHKeysOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserSSHKeysOK) Error() string { + return fmt.Sprintf("[GET /user/sshkeys][%d] describeUserSshKeysOK %+v", 200, o.Payload) +} + +func (o *DescribeUserSSHKeysOK) String() string { + return fmt.Sprintf("[GET /user/sshkeys][%d] describeUserSshKeysOK %+v", 200, o.Payload) +} + +func (o *DescribeUserSSHKeysOK) GetPayload() *DescribeUserSSHKeysOKBody { + return o.Payload +} + +func (o *DescribeUserSSHKeysOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserSSHKeysOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserSSHKeysDefault creates a DescribeUserSSHKeysDefault with default headers values +func NewDescribeUserSSHKeysDefault(code int) *DescribeUserSSHKeysDefault { + return &DescribeUserSSHKeysDefault{ + _statusCode: code, + } +} + +/* DescribeUserSSHKeysDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserSSHKeysDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserSSHKeysDefaultBody +} + +// Code gets the status code for the describe user Ssh keys default response +func (o *DescribeUserSSHKeysDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user Ssh keys default response has a 2xx status code +func (o *DescribeUserSSHKeysDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user Ssh keys default response has a 3xx status code +func (o *DescribeUserSSHKeysDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user Ssh keys default response has a 4xx status code +func (o *DescribeUserSSHKeysDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user Ssh keys default response has a 5xx status code +func (o *DescribeUserSSHKeysDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user Ssh keys default response a status code equal to that given +func (o *DescribeUserSSHKeysDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserSSHKeysDefault) Error() string { + return fmt.Sprintf("[GET /user/sshkeys][%d] describeUserSshKeys default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserSSHKeysDefault) String() string { + return fmt.Sprintf("[GET /user/sshkeys][%d] describeUserSshKeys default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserSSHKeysDefault) GetPayload() *DescribeUserSSHKeysDefaultBody { + return o.Payload +} + +func (o *DescribeUserSSHKeysDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserSSHKeysDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserSSHKeysDefaultBody describe user SSH keys default body +swagger:model DescribeUserSSHKeysDefaultBody +*/ +type DescribeUserSSHKeysDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user SSH keys default body +func (o *DescribeUserSSHKeysDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeysDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserSshKeys default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserSSHKeysDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserSshKeys default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeys default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeys default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user SSH keys default body based on the context it is used +func (o *DescribeUserSSHKeysDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeysDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeys default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeys default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserSSHKeysDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserSSHKeysDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserSSHKeysDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserSSHKeysOKBody describe user SSH keys o k body +swagger:model DescribeUserSSHKeysOKBody +*/ +type DescribeUserSSHKeysOKBody struct { + + // result + Result *models.SshkeyList `json:"result,omitempty"` +} + +// Validate validates this describe user SSH keys o k body +func (o *DescribeUserSSHKeysOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeysOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeysOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeysOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user SSH keys o k body based on the context it is used +func (o *DescribeUserSSHKeysOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserSSHKeysOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserSshKeysOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserSshKeysOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserSSHKeysOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserSSHKeysOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserSSHKeysOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/get_instances_by_sshkey_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/get_instances_by_sshkey_parameters.go new file mode 100644 index 0000000..d12c7d1 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/get_instances_by_sshkey_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetInstancesBySshkeyParams creates a new GetInstancesBySshkeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetInstancesBySshkeyParams() *GetInstancesBySshkeyParams { + return &GetInstancesBySshkeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetInstancesBySshkeyParamsWithTimeout creates a new GetInstancesBySshkeyParams object +// with the ability to set a timeout on a request. +func NewGetInstancesBySshkeyParamsWithTimeout(timeout time.Duration) *GetInstancesBySshkeyParams { + return &GetInstancesBySshkeyParams{ + timeout: timeout, + } +} + +// NewGetInstancesBySshkeyParamsWithContext creates a new GetInstancesBySshkeyParams object +// with the ability to set a context for a request. +func NewGetInstancesBySshkeyParamsWithContext(ctx context.Context) *GetInstancesBySshkeyParams { + return &GetInstancesBySshkeyParams{ + Context: ctx, + } +} + +// NewGetInstancesBySshkeyParamsWithHTTPClient creates a new GetInstancesBySshkeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetInstancesBySshkeyParamsWithHTTPClient(client *http.Client) *GetInstancesBySshkeyParams { + return &GetInstancesBySshkeyParams{ + HTTPClient: client, + } +} + +/* GetInstancesBySshkeyParams contains all the parameters to send to the API endpoint + for the get instances by sshkey operation. + + Typically these are written to a http.Request. +*/ +type GetInstancesBySshkeyParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + // SshkeyID. + SshkeyID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get instances by sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetInstancesBySshkeyParams) WithDefaults() *GetInstancesBySshkeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get instances by sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetInstancesBySshkeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithTimeout(timeout time.Duration) *GetInstancesBySshkeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithContext(ctx context.Context) *GetInstancesBySshkeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithHTTPClient(client *http.Client) *GetInstancesBySshkeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithAuthorization(authorization string) *GetInstancesBySshkeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithBmpLanguage(bmpLanguage *string) *GetInstancesBySshkeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithBmpUserID(bmpUserID *string) *GetInstancesBySshkeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithSshkeyID adds the sshkeyID to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithSshkeyID(sshkeyID string) *GetInstancesBySshkeyParams { + o.SetSshkeyID(sshkeyID) + return o +} + +// SetSshkeyID adds the sshkeyId to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetSshkeyID(sshkeyID string) { + o.SshkeyID = sshkeyID +} + +// WithTraceID adds the traceID to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) WithTraceID(traceID string) *GetInstancesBySshkeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the get instances by sshkey params +func (o *GetInstancesBySshkeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetInstancesBySshkeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param sshkey_id + if err := r.SetPathParam("sshkey_id", o.SshkeyID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/get_instances_by_sshkey_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/get_instances_by_sshkey_responses.go new file mode 100644 index 0000000..b7c4f1b --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/get_instances_by_sshkey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// GetInstancesBySshkeyReader is a Reader for the GetInstancesBySshkey structure. +type GetInstancesBySshkeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetInstancesBySshkeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetInstancesBySshkeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetInstancesBySshkeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetInstancesBySshkeyOK creates a GetInstancesBySshkeyOK with default headers values +func NewGetInstancesBySshkeyOK() *GetInstancesBySshkeyOK { + return &GetInstancesBySshkeyOK{} +} + +/* GetInstancesBySshkeyOK describes a response with status code 200, with default header values. + +A GetInstancesBySshkeyResult is an response struct that is used to get instance list by sshkey. +*/ +type GetInstancesBySshkeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetInstancesBySshkeyOKBody +} + +// IsSuccess returns true when this get instances by sshkey o k response has a 2xx status code +func (o *GetInstancesBySshkeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get instances by sshkey o k response has a 3xx status code +func (o *GetInstancesBySshkeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get instances by sshkey o k response has a 4xx status code +func (o *GetInstancesBySshkeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get instances by sshkey o k response has a 5xx status code +func (o *GetInstancesBySshkeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get instances by sshkey o k response a status code equal to that given +func (o *GetInstancesBySshkeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *GetInstancesBySshkeyOK) Error() string { + return fmt.Sprintf("[GET /user/sshkeys/instances/{sshkey_id}][%d] getInstancesBySshkeyOK %+v", 200, o.Payload) +} + +func (o *GetInstancesBySshkeyOK) String() string { + return fmt.Sprintf("[GET /user/sshkeys/instances/{sshkey_id}][%d] getInstancesBySshkeyOK %+v", 200, o.Payload) +} + +func (o *GetInstancesBySshkeyOK) GetPayload() *GetInstancesBySshkeyOKBody { + return o.Payload +} + +func (o *GetInstancesBySshkeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetInstancesBySshkeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetInstancesBySshkeyDefault creates a GetInstancesBySshkeyDefault with default headers values +func NewGetInstancesBySshkeyDefault(code int) *GetInstancesBySshkeyDefault { + return &GetInstancesBySshkeyDefault{ + _statusCode: code, + } +} + +/* GetInstancesBySshkeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type GetInstancesBySshkeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *GetInstancesBySshkeyDefaultBody +} + +// Code gets the status code for the get instances by sshkey default response +func (o *GetInstancesBySshkeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this get instances by sshkey default response has a 2xx status code +func (o *GetInstancesBySshkeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get instances by sshkey default response has a 3xx status code +func (o *GetInstancesBySshkeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get instances by sshkey default response has a 4xx status code +func (o *GetInstancesBySshkeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get instances by sshkey default response has a 5xx status code +func (o *GetInstancesBySshkeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get instances by sshkey default response a status code equal to that given +func (o *GetInstancesBySshkeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *GetInstancesBySshkeyDefault) Error() string { + return fmt.Sprintf("[GET /user/sshkeys/instances/{sshkey_id}][%d] getInstancesBySshkey default %+v", o._statusCode, o.Payload) +} + +func (o *GetInstancesBySshkeyDefault) String() string { + return fmt.Sprintf("[GET /user/sshkeys/instances/{sshkey_id}][%d] getInstancesBySshkey default %+v", o._statusCode, o.Payload) +} + +func (o *GetInstancesBySshkeyDefault) GetPayload() *GetInstancesBySshkeyDefaultBody { + return o.Payload +} + +func (o *GetInstancesBySshkeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(GetInstancesBySshkeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*GetInstancesBySshkeyDefaultBody get instances by sshkey default body +swagger:model GetInstancesBySshkeyDefaultBody +*/ +type GetInstancesBySshkeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this get instances by sshkey default body +func (o *GetInstancesBySshkeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetInstancesBySshkeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("getInstancesBySshkey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *GetInstancesBySshkeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("getInstancesBySshkey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getInstancesBySshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getInstancesBySshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get instances by sshkey default body based on the context it is used +func (o *GetInstancesBySshkeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetInstancesBySshkeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getInstancesBySshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getInstancesBySshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetInstancesBySshkeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetInstancesBySshkeyDefaultBody) UnmarshalBinary(b []byte) error { + var res GetInstancesBySshkeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*GetInstancesBySshkeyOKBody get instances by sshkey o k body +swagger:model GetInstancesBySshkeyOKBody +*/ +type GetInstancesBySshkeyOKBody struct { + + // result + Result *models.InstancesSshkeyInfoResponse `json:"result,omitempty"` +} + +// Validate validates this get instances by sshkey o k body +func (o *GetInstancesBySshkeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetInstancesBySshkeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getInstancesBySshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getInstancesBySshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get instances by sshkey o k body based on the context it is used +func (o *GetInstancesBySshkeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetInstancesBySshkeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getInstancesBySshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getInstancesBySshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetInstancesBySshkeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetInstancesBySshkeyOKBody) UnmarshalBinary(b []byte) error { + var res GetInstancesBySshkeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/modify_user_sshkey_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/modify_user_sshkey_parameters.go new file mode 100644 index 0000000..43464ce --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/modify_user_sshkey_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyUserSshkeyParams creates a new ModifyUserSshkeyParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyUserSshkeyParams() *ModifyUserSshkeyParams { + return &ModifyUserSshkeyParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyUserSshkeyParamsWithTimeout creates a new ModifyUserSshkeyParams object +// with the ability to set a timeout on a request. +func NewModifyUserSshkeyParamsWithTimeout(timeout time.Duration) *ModifyUserSshkeyParams { + return &ModifyUserSshkeyParams{ + timeout: timeout, + } +} + +// NewModifyUserSshkeyParamsWithContext creates a new ModifyUserSshkeyParams object +// with the ability to set a context for a request. +func NewModifyUserSshkeyParamsWithContext(ctx context.Context) *ModifyUserSshkeyParams { + return &ModifyUserSshkeyParams{ + Context: ctx, + } +} + +// NewModifyUserSshkeyParamsWithHTTPClient creates a new ModifyUserSshkeyParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyUserSshkeyParamsWithHTTPClient(client *http.Client) *ModifyUserSshkeyParams { + return &ModifyUserSshkeyParams{ + HTTPClient: client, + } +} + +/* ModifyUserSshkeyParams contains all the parameters to send to the API endpoint + for the modify user sshkey operation. + + Typically these are written to a http.Request. +*/ +type ModifyUserSshkeyParams struct { + + // Body. + Body *models.ModifySshkeyRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + // SshkeyID. + SshkeyID string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserSshkeyParams) WithDefaults() *ModifyUserSshkeyParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify user sshkey params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserSshkeyParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithTimeout(timeout time.Duration) *ModifyUserSshkeyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithContext(ctx context.Context) *ModifyUserSshkeyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithHTTPClient(client *http.Client) *ModifyUserSshkeyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithBody(body *models.ModifySshkeyRequest) *ModifyUserSshkeyParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetBody(body *models.ModifySshkeyRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithAuthorization(authorization string) *ModifyUserSshkeyParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithBmpLanguage(bmpLanguage *string) *ModifyUserSshkeyParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithBmpUserID(bmpUserID *string) *ModifyUserSshkeyParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithSshkeyID adds the sshkeyID to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithSshkeyID(sshkeyID string) *ModifyUserSshkeyParams { + o.SetSshkeyID(sshkeyID) + return o +} + +// SetSshkeyID adds the sshkeyId to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetSshkeyID(sshkeyID string) { + o.SshkeyID = sshkeyID +} + +// WithTraceID adds the traceID to the modify user sshkey params +func (o *ModifyUserSshkeyParams) WithTraceID(traceID string) *ModifyUserSshkeyParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify user sshkey params +func (o *ModifyUserSshkeyParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyUserSshkeyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // path param sshkey_id + if err := r.SetPathParam("sshkey_id", o.SshkeyID); err != nil { + return err + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/modify_user_sshkey_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/modify_user_sshkey_responses.go new file mode 100644 index 0000000..8037709 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/modify_user_sshkey_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyUserSshkeyReader is a Reader for the ModifyUserSshkey structure. +type ModifyUserSshkeyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyUserSshkeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyUserSshkeyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyUserSshkeyDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyUserSshkeyOK creates a ModifyUserSshkeyOK with default headers values +func NewModifyUserSshkeyOK() *ModifyUserSshkeyOK { + return &ModifyUserSshkeyOK{} +} + +/* ModifyUserSshkeyOK describes a response with status code 200, with default header values. + +A ModifyUserSshkeyResult is an response struct that is used to modify sshkey result. +*/ +type ModifyUserSshkeyOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserSshkeyOKBody +} + +// IsSuccess returns true when this modify user sshkey o k response has a 2xx status code +func (o *ModifyUserSshkeyOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify user sshkey o k response has a 3xx status code +func (o *ModifyUserSshkeyOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify user sshkey o k response has a 4xx status code +func (o *ModifyUserSshkeyOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify user sshkey o k response has a 5xx status code +func (o *ModifyUserSshkeyOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify user sshkey o k response a status code equal to that given +func (o *ModifyUserSshkeyOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyUserSshkeyOK) Error() string { + return fmt.Sprintf("[PUT /user/sshkeys/{sshkey_id}][%d] modifyUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *ModifyUserSshkeyOK) String() string { + return fmt.Sprintf("[PUT /user/sshkeys/{sshkey_id}][%d] modifyUserSshkeyOK %+v", 200, o.Payload) +} + +func (o *ModifyUserSshkeyOK) GetPayload() *ModifyUserSshkeyOKBody { + return o.Payload +} + +func (o *ModifyUserSshkeyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserSshkeyOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyUserSshkeyDefault creates a ModifyUserSshkeyDefault with default headers values +func NewModifyUserSshkeyDefault(code int) *ModifyUserSshkeyDefault { + return &ModifyUserSshkeyDefault{ + _statusCode: code, + } +} + +/* ModifyUserSshkeyDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyUserSshkeyDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserSshkeyDefaultBody +} + +// Code gets the status code for the modify user sshkey default response +func (o *ModifyUserSshkeyDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify user sshkey default response has a 2xx status code +func (o *ModifyUserSshkeyDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify user sshkey default response has a 3xx status code +func (o *ModifyUserSshkeyDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify user sshkey default response has a 4xx status code +func (o *ModifyUserSshkeyDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify user sshkey default response has a 5xx status code +func (o *ModifyUserSshkeyDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify user sshkey default response a status code equal to that given +func (o *ModifyUserSshkeyDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyUserSshkeyDefault) Error() string { + return fmt.Sprintf("[PUT /user/sshkeys/{sshkey_id}][%d] modifyUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserSshkeyDefault) String() string { + return fmt.Sprintf("[PUT /user/sshkeys/{sshkey_id}][%d] modifyUserSshkey default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserSshkeyDefault) GetPayload() *ModifyUserSshkeyDefaultBody { + return o.Payload +} + +func (o *ModifyUserSshkeyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserSshkeyDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyUserSshkeyDefaultBody modify user sshkey default body +swagger:model ModifyUserSshkeyDefaultBody +*/ +type ModifyUserSshkeyDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify user sshkey default body +func (o *ModifyUserSshkeyDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserSshkeyDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserSshkey default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyUserSshkeyDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyUserSshkey default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user sshkey default body based on the context it is used +func (o *ModifyUserSshkeyDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserSshkeyDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserSshkey default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserSshkey default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserSshkeyDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserSshkeyDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyUserSshkeyDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyUserSshkeyOKBody modify user sshkey o k body +swagger:model ModifyUserSshkeyOKBody +*/ +type ModifyUserSshkeyOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify user sshkey o k body +func (o *ModifyUserSshkeyOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserSshkeyOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user sshkey o k body based on the context it is used +func (o *ModifyUserSshkeyOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserSshkeyOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserSshkeyOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserSshkeyOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserSshkeyOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserSshkeyOKBody) UnmarshalBinary(b []byte) error { + var res ModifyUserSshkeyOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/sshkey_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/sshkey_client.go new file mode 100644 index 0000000..16c7309 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/sshkey/sshkey_client.go @@ -0,0 +1,277 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sshkey + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new sshkey API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for sshkey API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateUserSshkey(params *CreateUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserSshkeyOK, error) + + DeleteUserSshkey(params *DeleteUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserSshkeyOK, error) + + DescribeUserSSHKey(params *DescribeUserSSHKeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserSSHKeyOK, error) + + DescribeUserSSHKeys(params *DescribeUserSSHKeysParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserSSHKeysOK, error) + + GetInstancesBySshkey(params *GetInstancesBySshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetInstancesBySshkeyOK, error) + + ModifyUserSshkey(params *ModifyUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserSshkeyOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateUserSshkey CreateUserSshkey 创建个人sshkey +*/ +func (a *Client) CreateUserSshkey(params *CreateUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserSshkeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateUserSshkeyParams() + } + op := &runtime.ClientOperation{ + ID: "createUserSshkey", + Method: "POST", + PathPattern: "/user/sshkeys", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateUserSshkeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateUserSshkeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateUserSshkeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteUserSshkey DeleteUserSshkey 删除sshkey +*/ +func (a *Client) DeleteUserSshkey(params *DeleteUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserSshkeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteUserSshkeyParams() + } + op := &runtime.ClientOperation{ + ID: "deleteUserSshkey", + Method: "DELETE", + PathPattern: "/user/sshkeys/{sshkey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteUserSshkeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteUserSshkeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteUserSshkeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserSSHKey DescribeUserSshKey 获取sshkey详情 +*/ +func (a *Client) DescribeUserSSHKey(params *DescribeUserSSHKeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserSSHKeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserSSHKeyParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserSshKey", + Method: "GET", + PathPattern: "/user/sshkeys/{sshkey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserSSHKeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserSSHKeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserSSHKeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserSSHKeys DescribeUserSshKeys 获取个人sshkey列表 +*/ +func (a *Client) DescribeUserSSHKeys(params *DescribeUserSSHKeysParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserSSHKeysOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserSSHKeysParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserSshKeys", + Method: "GET", + PathPattern: "/user/sshkeys", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserSSHKeysReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserSSHKeysOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserSSHKeysDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + GetInstancesBySshkey GetInstancesBySshkey 根据sshkey获取实例列表 +*/ +func (a *Client) GetInstancesBySshkey(params *GetInstancesBySshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetInstancesBySshkeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetInstancesBySshkeyParams() + } + op := &runtime.ClientOperation{ + ID: "getInstancesBySshkey", + Method: "GET", + PathPattern: "/user/sshkeys/instances/{sshkey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetInstancesBySshkeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetInstancesBySshkeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetInstancesBySshkeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyUserSshkey ModifyUserSshkey 修改sshkey +*/ +func (a *Client) ModifyUserSshkey(params *ModifyUserSshkeyParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserSshkeyOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyUserSshkeyParams() + } + op := &runtime.ClientOperation{ + ID: "modifyUserSshkey", + Method: "PUT", + PathPattern: "/user/sshkeys/{sshkey_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyUserSshkeyReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyUserSshkeyOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyUserSshkeyDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/create_user_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/create_user_parameters.go new file mode 100644 index 0000000..a600f31 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/create_user_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewCreateUserParams creates a new CreateUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateUserParams() *CreateUserParams { + return &CreateUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateUserParamsWithTimeout creates a new CreateUserParams object +// with the ability to set a timeout on a request. +func NewCreateUserParamsWithTimeout(timeout time.Duration) *CreateUserParams { + return &CreateUserParams{ + timeout: timeout, + } +} + +// NewCreateUserParamsWithContext creates a new CreateUserParams object +// with the ability to set a context for a request. +func NewCreateUserParamsWithContext(ctx context.Context) *CreateUserParams { + return &CreateUserParams{ + Context: ctx, + } +} + +// NewCreateUserParamsWithHTTPClient creates a new CreateUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateUserParamsWithHTTPClient(client *http.Client) *CreateUserParams { + return &CreateUserParams{ + HTTPClient: client, + } +} + +/* CreateUserParams contains all the parameters to send to the API endpoint + for the create user operation. + + Typically these are written to a http.Request. +*/ +type CreateUserParams struct { + + // Body. + Body *models.CreateUserRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserParams) WithDefaults() *CreateUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create user params +func (o *CreateUserParams) WithTimeout(timeout time.Duration) *CreateUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create user params +func (o *CreateUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create user params +func (o *CreateUserParams) WithContext(ctx context.Context) *CreateUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create user params +func (o *CreateUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create user params +func (o *CreateUserParams) WithHTTPClient(client *http.Client) *CreateUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create user params +func (o *CreateUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create user params +func (o *CreateUserParams) WithBody(body *models.CreateUserRequest) *CreateUserParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create user params +func (o *CreateUserParams) SetBody(body *models.CreateUserRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the create user params +func (o *CreateUserParams) WithAuthorization(authorization string) *CreateUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the create user params +func (o *CreateUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the create user params +func (o *CreateUserParams) WithBmpLanguage(bmpLanguage *string) *CreateUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the create user params +func (o *CreateUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the create user params +func (o *CreateUserParams) WithBmpUserID(bmpUserID *string) *CreateUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the create user params +func (o *CreateUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the create user params +func (o *CreateUserParams) WithTraceID(traceID string) *CreateUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the create user params +func (o *CreateUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/create_user_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/create_user_responses.go new file mode 100644 index 0000000..de54876 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/create_user_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// CreateUserReader is a Reader for the CreateUser structure. +type CreateUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateUserOK creates a CreateUserOK with default headers values +func NewCreateUserOK() *CreateUserOK { + return &CreateUserOK{} +} + +/* CreateUserOK describes a response with status code 200, with default header values. + +A CreateInstancesResult is an response struct that is used to describe create instance result. +*/ +type CreateUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserOKBody +} + +// IsSuccess returns true when this create user o k response has a 2xx status code +func (o *CreateUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create user o k response has a 3xx status code +func (o *CreateUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create user o k response has a 4xx status code +func (o *CreateUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create user o k response has a 5xx status code +func (o *CreateUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create user o k response a status code equal to that given +func (o *CreateUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *CreateUserOK) Error() string { + return fmt.Sprintf("[POST /users][%d] createUserOK %+v", 200, o.Payload) +} + +func (o *CreateUserOK) String() string { + return fmt.Sprintf("[POST /users][%d] createUserOK %+v", 200, o.Payload) +} + +func (o *CreateUserOK) GetPayload() *CreateUserOKBody { + return o.Payload +} + +func (o *CreateUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateUserDefault creates a CreateUserDefault with default headers values +func NewCreateUserDefault(code int) *CreateUserDefault { + return &CreateUserDefault{ + _statusCode: code, + } +} + +/* CreateUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type CreateUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *CreateUserDefaultBody +} + +// Code gets the status code for the create user default response +func (o *CreateUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this create user default response has a 2xx status code +func (o *CreateUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create user default response has a 3xx status code +func (o *CreateUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create user default response has a 4xx status code +func (o *CreateUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create user default response has a 5xx status code +func (o *CreateUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create user default response a status code equal to that given +func (o *CreateUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *CreateUserDefault) Error() string { + return fmt.Sprintf("[POST /users][%d] createUser default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserDefault) String() string { + return fmt.Sprintf("[POST /users][%d] createUser default %+v", o._statusCode, o.Payload) +} + +func (o *CreateUserDefault) GetPayload() *CreateUserDefaultBody { + return o.Payload +} + +func (o *CreateUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(CreateUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*CreateUserDefaultBody create user default body +swagger:model CreateUserDefaultBody +*/ +type CreateUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this create user default body +func (o *CreateUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("createUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *CreateUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("createUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user default body based on the context it is used +func (o *CreateUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserDefaultBody) UnmarshalBinary(b []byte) error { + var res CreateUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*CreateUserOKBody create user o k body +swagger:model CreateUserOKBody +*/ +type CreateUserOKBody struct { + + // result + Result *models.UserID `json:"result,omitempty"` +} + +// Validate validates this create user o k body +func (o *CreateUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this create user o k body based on the context it is used +func (o *CreateUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *CreateUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("createUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("createUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *CreateUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *CreateUserOKBody) UnmarshalBinary(b []byte) error { + var res CreateUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/delete_user_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/delete_user_parameters.go new file mode 100644 index 0000000..3a1399c --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/delete_user_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteUserParams creates a new DeleteUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteUserParams() *DeleteUserParams { + return &DeleteUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteUserParamsWithTimeout creates a new DeleteUserParams object +// with the ability to set a timeout on a request. +func NewDeleteUserParamsWithTimeout(timeout time.Duration) *DeleteUserParams { + return &DeleteUserParams{ + timeout: timeout, + } +} + +// NewDeleteUserParamsWithContext creates a new DeleteUserParams object +// with the ability to set a context for a request. +func NewDeleteUserParamsWithContext(ctx context.Context) *DeleteUserParams { + return &DeleteUserParams{ + Context: ctx, + } +} + +// NewDeleteUserParamsWithHTTPClient creates a new DeleteUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteUserParamsWithHTTPClient(client *http.Client) *DeleteUserParams { + return &DeleteUserParams{ + HTTPClient: client, + } +} + +/* DeleteUserParams contains all the parameters to send to the API endpoint + for the delete user operation. + + Typically these are written to a http.Request. +*/ +type DeleteUserParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + // UserID. + UserID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserParams) WithDefaults() *DeleteUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete user params +func (o *DeleteUserParams) WithTimeout(timeout time.Duration) *DeleteUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete user params +func (o *DeleteUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete user params +func (o *DeleteUserParams) WithContext(ctx context.Context) *DeleteUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete user params +func (o *DeleteUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete user params +func (o *DeleteUserParams) WithHTTPClient(client *http.Client) *DeleteUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete user params +func (o *DeleteUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the delete user params +func (o *DeleteUserParams) WithAuthorization(authorization string) *DeleteUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the delete user params +func (o *DeleteUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the delete user params +func (o *DeleteUserParams) WithBmpLanguage(bmpLanguage *string) *DeleteUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the delete user params +func (o *DeleteUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the delete user params +func (o *DeleteUserParams) WithBmpUserID(bmpUserID *string) *DeleteUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the delete user params +func (o *DeleteUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the delete user params +func (o *DeleteUserParams) WithTraceID(traceID string) *DeleteUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the delete user params +func (o *DeleteUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserID adds the userID to the delete user params +func (o *DeleteUserParams) WithUserID(userID string) *DeleteUserParams { + o.SetUserID(userID) + return o +} + +// SetUserID adds the userId to the delete user params +func (o *DeleteUserParams) SetUserID(userID string) { + o.UserID = userID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + // path param user_id + if err := r.SetPathParam("user_id", o.UserID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/delete_user_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/delete_user_responses.go new file mode 100644 index 0000000..f0d119d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/delete_user_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DeleteUserReader is a Reader for the DeleteUser structure. +type DeleteUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDeleteUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDeleteUserOK creates a DeleteUserOK with default headers values +func NewDeleteUserOK() *DeleteUserOK { + return &DeleteUserOK{} +} + +/* DeleteUserOK describes a response with status code 200, with default header values. + +A GetUserResult is an response struct that is used to describe getuser. +*/ +type DeleteUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserOKBody +} + +// IsSuccess returns true when this delete user o k response has a 2xx status code +func (o *DeleteUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete user o k response has a 3xx status code +func (o *DeleteUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete user o k response has a 4xx status code +func (o *DeleteUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete user o k response has a 5xx status code +func (o *DeleteUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete user o k response a status code equal to that given +func (o *DeleteUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DeleteUserOK) Error() string { + return fmt.Sprintf("[DELETE /users/{user_id}][%d] deleteUserOK %+v", 200, o.Payload) +} + +func (o *DeleteUserOK) String() string { + return fmt.Sprintf("[DELETE /users/{user_id}][%d] deleteUserOK %+v", 200, o.Payload) +} + +func (o *DeleteUserOK) GetPayload() *DeleteUserOKBody { + return o.Payload +} + +func (o *DeleteUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteUserDefault creates a DeleteUserDefault with default headers values +func NewDeleteUserDefault(code int) *DeleteUserDefault { + return &DeleteUserDefault{ + _statusCode: code, + } +} + +/* DeleteUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DeleteUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DeleteUserDefaultBody +} + +// Code gets the status code for the delete user default response +func (o *DeleteUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this delete user default response has a 2xx status code +func (o *DeleteUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete user default response has a 3xx status code +func (o *DeleteUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete user default response has a 4xx status code +func (o *DeleteUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete user default response has a 5xx status code +func (o *DeleteUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete user default response a status code equal to that given +func (o *DeleteUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DeleteUserDefault) Error() string { + return fmt.Sprintf("[DELETE /users/{user_id}][%d] deleteUser default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserDefault) String() string { + return fmt.Sprintf("[DELETE /users/{user_id}][%d] deleteUser default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteUserDefault) GetPayload() *DeleteUserDefaultBody { + return o.Payload +} + +func (o *DeleteUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DeleteUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DeleteUserDefaultBody delete user default body +swagger:model DeleteUserDefaultBody +*/ +type DeleteUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this delete user default body +func (o *DeleteUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("deleteUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DeleteUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("deleteUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user default body based on the context it is used +func (o *DeleteUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserDefaultBody) UnmarshalBinary(b []byte) error { + var res DeleteUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DeleteUserOKBody delete user o k body +swagger:model DeleteUserOKBody +*/ +type DeleteUserOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this delete user o k body +func (o *DeleteUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this delete user o k body based on the context it is used +func (o *DeleteUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DeleteUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deleteUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deleteUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DeleteUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DeleteUserOKBody) UnmarshalBinary(b []byte) error { + var res DeleteUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_local_user_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_local_user_parameters.go new file mode 100644 index 0000000..737566e --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_local_user_parameters.go @@ -0,0 +1,221 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeLocalUserParams creates a new DescribeLocalUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeLocalUserParams() *DescribeLocalUserParams { + return &DescribeLocalUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeLocalUserParamsWithTimeout creates a new DescribeLocalUserParams object +// with the ability to set a timeout on a request. +func NewDescribeLocalUserParamsWithTimeout(timeout time.Duration) *DescribeLocalUserParams { + return &DescribeLocalUserParams{ + timeout: timeout, + } +} + +// NewDescribeLocalUserParamsWithContext creates a new DescribeLocalUserParams object +// with the ability to set a context for a request. +func NewDescribeLocalUserParamsWithContext(ctx context.Context) *DescribeLocalUserParams { + return &DescribeLocalUserParams{ + Context: ctx, + } +} + +// NewDescribeLocalUserParamsWithHTTPClient creates a new DescribeLocalUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeLocalUserParamsWithHTTPClient(client *http.Client) *DescribeLocalUserParams { + return &DescribeLocalUserParams{ + HTTPClient: client, + } +} + +/* DescribeLocalUserParams contains all the parameters to send to the API endpoint + for the describe local user operation. + + Typically these are written to a http.Request. +*/ +type DescribeLocalUserParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe local user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLocalUserParams) WithDefaults() *DescribeLocalUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe local user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeLocalUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe local user params +func (o *DescribeLocalUserParams) WithTimeout(timeout time.Duration) *DescribeLocalUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe local user params +func (o *DescribeLocalUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe local user params +func (o *DescribeLocalUserParams) WithContext(ctx context.Context) *DescribeLocalUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe local user params +func (o *DescribeLocalUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe local user params +func (o *DescribeLocalUserParams) WithHTTPClient(client *http.Client) *DescribeLocalUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe local user params +func (o *DescribeLocalUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe local user params +func (o *DescribeLocalUserParams) WithAuthorization(authorization string) *DescribeLocalUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe local user params +func (o *DescribeLocalUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe local user params +func (o *DescribeLocalUserParams) WithBmpLanguage(bmpLanguage *string) *DescribeLocalUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe local user params +func (o *DescribeLocalUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe local user params +func (o *DescribeLocalUserParams) WithBmpUserID(bmpUserID *string) *DescribeLocalUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe local user params +func (o *DescribeLocalUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe local user params +func (o *DescribeLocalUserParams) WithTraceID(traceID string) *DescribeLocalUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe local user params +func (o *DescribeLocalUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeLocalUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_local_user_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_local_user_responses.go new file mode 100644 index 0000000..8f3b50d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_local_user_responses.go @@ -0,0 +1,449 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeLocalUserReader is a Reader for the DescribeLocalUser structure. +type DescribeLocalUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeLocalUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeLocalUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeLocalUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeLocalUserOK creates a DescribeLocalUserOK with default headers values +func NewDescribeLocalUserOK() *DescribeLocalUserOK { + return &DescribeLocalUserOK{} +} + +/* DescribeLocalUserOK describes a response with status code 200, with default header values. + +A DescribeLocalUserResult is an response struct that is used to describe getuser. +*/ +type DescribeLocalUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLocalUserOKBody +} + +// IsSuccess returns true when this describe local user o k response has a 2xx status code +func (o *DescribeLocalUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe local user o k response has a 3xx status code +func (o *DescribeLocalUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe local user o k response has a 4xx status code +func (o *DescribeLocalUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe local user o k response has a 5xx status code +func (o *DescribeLocalUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe local user o k response a status code equal to that given +func (o *DescribeLocalUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeLocalUserOK) Error() string { + return fmt.Sprintf("[GET /local/users][%d] describeLocalUserOK %+v", 200, o.Payload) +} + +func (o *DescribeLocalUserOK) String() string { + return fmt.Sprintf("[GET /local/users][%d] describeLocalUserOK %+v", 200, o.Payload) +} + +func (o *DescribeLocalUserOK) GetPayload() *DescribeLocalUserOKBody { + return o.Payload +} + +func (o *DescribeLocalUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLocalUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeLocalUserDefault creates a DescribeLocalUserDefault with default headers values +func NewDescribeLocalUserDefault(code int) *DescribeLocalUserDefault { + return &DescribeLocalUserDefault{ + _statusCode: code, + } +} + +/* DescribeLocalUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeLocalUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeLocalUserDefaultBody +} + +// Code gets the status code for the describe local user default response +func (o *DescribeLocalUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe local user default response has a 2xx status code +func (o *DescribeLocalUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe local user default response has a 3xx status code +func (o *DescribeLocalUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe local user default response has a 4xx status code +func (o *DescribeLocalUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe local user default response has a 5xx status code +func (o *DescribeLocalUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe local user default response a status code equal to that given +func (o *DescribeLocalUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeLocalUserDefault) Error() string { + return fmt.Sprintf("[GET /local/users][%d] describeLocalUser default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLocalUserDefault) String() string { + return fmt.Sprintf("[GET /local/users][%d] describeLocalUser default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeLocalUserDefault) GetPayload() *DescribeLocalUserDefaultBody { + return o.Payload +} + +func (o *DescribeLocalUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeLocalUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeLocalUserDefaultBody describe local user default body +swagger:model DescribeLocalUserDefaultBody +*/ +type DescribeLocalUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe local user default body +func (o *DescribeLocalUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLocalUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeLocalUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeLocalUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeLocalUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe local user default body based on the context it is used +func (o *DescribeLocalUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLocalUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLocalUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLocalUserDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeLocalUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeLocalUserOKBody describe local user o k body +swagger:model DescribeLocalUserOKBody +*/ +type DescribeLocalUserOKBody struct { + + // error + Error *models.ErrorResponse `json:"error,omitempty"` + + // result + Result *models.UserInfo `json:"result,omitempty"` +} + +// Validate validates this describe local user o k body +func (o *DescribeLocalUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLocalUserOKBody) validateError(formats strfmt.Registry) error { + if swag.IsZero(o.Error) { // not required + return nil + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUserOK" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUserOK" + "." + "error") + } + return err + } + } + + return nil +} + +func (o *DescribeLocalUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe local user o k body based on the context it is used +func (o *DescribeLocalUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeLocalUserOKBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUserOK" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUserOK" + "." + "error") + } + return err + } + } + + return nil +} + +func (o *DescribeLocalUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeLocalUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeLocalUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeLocalUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeLocalUserOKBody) UnmarshalBinary(b []byte) error { + var res DescribeLocalUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_by_name_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_by_name_parameters.go new file mode 100644 index 0000000..488d83c --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_by_name_parameters.go @@ -0,0 +1,248 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeUserByNameParams creates a new DescribeUserByNameParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserByNameParams() *DescribeUserByNameParams { + return &DescribeUserByNameParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserByNameParamsWithTimeout creates a new DescribeUserByNameParams object +// with the ability to set a timeout on a request. +func NewDescribeUserByNameParamsWithTimeout(timeout time.Duration) *DescribeUserByNameParams { + return &DescribeUserByNameParams{ + timeout: timeout, + } +} + +// NewDescribeUserByNameParamsWithContext creates a new DescribeUserByNameParams object +// with the ability to set a context for a request. +func NewDescribeUserByNameParamsWithContext(ctx context.Context) *DescribeUserByNameParams { + return &DescribeUserByNameParams{ + Context: ctx, + } +} + +// NewDescribeUserByNameParamsWithHTTPClient creates a new DescribeUserByNameParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserByNameParamsWithHTTPClient(client *http.Client) *DescribeUserByNameParams { + return &DescribeUserByNameParams{ + HTTPClient: client, + } +} + +/* DescribeUserByNameParams contains all the parameters to send to the API endpoint + for the describe user by name operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserByNameParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserName. + + 用户名,唯一 + */ + UserName string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user by name params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserByNameParams) WithDefaults() *DescribeUserByNameParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user by name params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserByNameParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user by name params +func (o *DescribeUserByNameParams) WithTimeout(timeout time.Duration) *DescribeUserByNameParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user by name params +func (o *DescribeUserByNameParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user by name params +func (o *DescribeUserByNameParams) WithContext(ctx context.Context) *DescribeUserByNameParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user by name params +func (o *DescribeUserByNameParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user by name params +func (o *DescribeUserByNameParams) WithHTTPClient(client *http.Client) *DescribeUserByNameParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user by name params +func (o *DescribeUserByNameParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user by name params +func (o *DescribeUserByNameParams) WithAuthorization(authorization string) *DescribeUserByNameParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user by name params +func (o *DescribeUserByNameParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user by name params +func (o *DescribeUserByNameParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserByNameParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user by name params +func (o *DescribeUserByNameParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user by name params +func (o *DescribeUserByNameParams) WithBmpUserID(bmpUserID *string) *DescribeUserByNameParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user by name params +func (o *DescribeUserByNameParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe user by name params +func (o *DescribeUserByNameParams) WithTraceID(traceID string) *DescribeUserByNameParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user by name params +func (o *DescribeUserByNameParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserName adds the userName to the describe user by name params +func (o *DescribeUserByNameParams) WithUserName(userName string) *DescribeUserByNameParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe user by name params +func (o *DescribeUserByNameParams) SetUserName(userName string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserByNameParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + // query param userName + qrUserName := o.UserName + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_by_name_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_by_name_responses.go new file mode 100644 index 0000000..73ba314 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_by_name_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserByNameReader is a Reader for the DescribeUserByName structure. +type DescribeUserByNameReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserByNameReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserByNameOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserByNameDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserByNameOK creates a DescribeUserByNameOK with default headers values +func NewDescribeUserByNameOK() *DescribeUserByNameOK { + return &DescribeUserByNameOK{} +} + +/* DescribeUserByNameOK describes a response with status code 200, with default header values. + +A GetUserByNameResult is an response struct that is used to describe user. +*/ +type DescribeUserByNameOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserByNameOKBody +} + +// IsSuccess returns true when this describe user by name o k response has a 2xx status code +func (o *DescribeUserByNameOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user by name o k response has a 3xx status code +func (o *DescribeUserByNameOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user by name o k response has a 4xx status code +func (o *DescribeUserByNameOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user by name o k response has a 5xx status code +func (o *DescribeUserByNameOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user by name o k response a status code equal to that given +func (o *DescribeUserByNameOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserByNameOK) Error() string { + return fmt.Sprintf("[GET /users/getUserByName][%d] describeUserByNameOK %+v", 200, o.Payload) +} + +func (o *DescribeUserByNameOK) String() string { + return fmt.Sprintf("[GET /users/getUserByName][%d] describeUserByNameOK %+v", 200, o.Payload) +} + +func (o *DescribeUserByNameOK) GetPayload() *DescribeUserByNameOKBody { + return o.Payload +} + +func (o *DescribeUserByNameOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserByNameOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserByNameDefault creates a DescribeUserByNameDefault with default headers values +func NewDescribeUserByNameDefault(code int) *DescribeUserByNameDefault { + return &DescribeUserByNameDefault{ + _statusCode: code, + } +} + +/* DescribeUserByNameDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserByNameDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserByNameDefaultBody +} + +// Code gets the status code for the describe user by name default response +func (o *DescribeUserByNameDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user by name default response has a 2xx status code +func (o *DescribeUserByNameDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user by name default response has a 3xx status code +func (o *DescribeUserByNameDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user by name default response has a 4xx status code +func (o *DescribeUserByNameDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user by name default response has a 5xx status code +func (o *DescribeUserByNameDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user by name default response a status code equal to that given +func (o *DescribeUserByNameDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserByNameDefault) Error() string { + return fmt.Sprintf("[GET /users/getUserByName][%d] describeUserByName default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserByNameDefault) String() string { + return fmt.Sprintf("[GET /users/getUserByName][%d] describeUserByName default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserByNameDefault) GetPayload() *DescribeUserByNameDefaultBody { + return o.Payload +} + +func (o *DescribeUserByNameDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserByNameDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserByNameDefaultBody describe user by name default body +swagger:model DescribeUserByNameDefaultBody +*/ +type DescribeUserByNameDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user by name default body +func (o *DescribeUserByNameDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserByNameDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUserByName default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserByNameDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUserByName default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserByName default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserByName default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user by name default body based on the context it is used +func (o *DescribeUserByNameDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserByNameDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserByName default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserByName default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserByNameDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserByNameDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserByNameDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserByNameOKBody describe user by name o k body +swagger:model DescribeUserByNameOKBody +*/ +type DescribeUserByNameOKBody struct { + + // result + Result *models.UserInfo `json:"result,omitempty"` +} + +// Validate validates this describe user by name o k body +func (o *DescribeUserByNameOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserByNameOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserByNameOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserByNameOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user by name o k body based on the context it is used +func (o *DescribeUserByNameOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserByNameOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserByNameOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserByNameOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserByNameOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserByNameOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserByNameOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_parameters.go new file mode 100644 index 0000000..8b874fd --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_parameters.go @@ -0,0 +1,240 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDescribeUserParams creates a new DescribeUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUserParams() *DescribeUserParams { + return &DescribeUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUserParamsWithTimeout creates a new DescribeUserParams object +// with the ability to set a timeout on a request. +func NewDescribeUserParamsWithTimeout(timeout time.Duration) *DescribeUserParams { + return &DescribeUserParams{ + timeout: timeout, + } +} + +// NewDescribeUserParamsWithContext creates a new DescribeUserParams object +// with the ability to set a context for a request. +func NewDescribeUserParamsWithContext(ctx context.Context) *DescribeUserParams { + return &DescribeUserParams{ + Context: ctx, + } +} + +// NewDescribeUserParamsWithHTTPClient creates a new DescribeUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUserParamsWithHTTPClient(client *http.Client) *DescribeUserParams { + return &DescribeUserParams{ + HTTPClient: client, + } +} + +/* DescribeUserParams contains all the parameters to send to the API endpoint + for the describe user operation. + + Typically these are written to a http.Request. +*/ +type DescribeUserParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + // UserID. + UserID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserParams) WithDefaults() *DescribeUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe user params +func (o *DescribeUserParams) WithTimeout(timeout time.Duration) *DescribeUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe user params +func (o *DescribeUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe user params +func (o *DescribeUserParams) WithContext(ctx context.Context) *DescribeUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe user params +func (o *DescribeUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe user params +func (o *DescribeUserParams) WithHTTPClient(client *http.Client) *DescribeUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe user params +func (o *DescribeUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe user params +func (o *DescribeUserParams) WithAuthorization(authorization string) *DescribeUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe user params +func (o *DescribeUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe user params +func (o *DescribeUserParams) WithBmpLanguage(bmpLanguage *string) *DescribeUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe user params +func (o *DescribeUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe user params +func (o *DescribeUserParams) WithBmpUserID(bmpUserID *string) *DescribeUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe user params +func (o *DescribeUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the describe user params +func (o *DescribeUserParams) WithTraceID(traceID string) *DescribeUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe user params +func (o *DescribeUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserID adds the userID to the describe user params +func (o *DescribeUserParams) WithUserID(userID string) *DescribeUserParams { + o.SetUserID(userID) + return o +} + +// SetUserID adds the userId to the describe user params +func (o *DescribeUserParams) SetUserID(userID string) { + o.UserID = userID +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + // path param user_id + if err := r.SetPathParam("user_id", o.UserID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_responses.go new file mode 100644 index 0000000..f39a4d4 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_user_responses.go @@ -0,0 +1,449 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUserReader is a Reader for the DescribeUser structure. +type DescribeUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUserOK creates a DescribeUserOK with default headers values +func NewDescribeUserOK() *DescribeUserOK { + return &DescribeUserOK{} +} + +/* DescribeUserOK describes a response with status code 200, with default header values. + +DescribeUserOK describe user o k +*/ +type DescribeUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserOKBody +} + +// IsSuccess returns true when this describe user o k response has a 2xx status code +func (o *DescribeUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe user o k response has a 3xx status code +func (o *DescribeUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe user o k response has a 4xx status code +func (o *DescribeUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe user o k response has a 5xx status code +func (o *DescribeUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe user o k response a status code equal to that given +func (o *DescribeUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUserOK) Error() string { + return fmt.Sprintf("[GET /users/{user_id}][%d] describeUserOK %+v", 200, o.Payload) +} + +func (o *DescribeUserOK) String() string { + return fmt.Sprintf("[GET /users/{user_id}][%d] describeUserOK %+v", 200, o.Payload) +} + +func (o *DescribeUserOK) GetPayload() *DescribeUserOKBody { + return o.Payload +} + +func (o *DescribeUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUserDefault creates a DescribeUserDefault with default headers values +func NewDescribeUserDefault(code int) *DescribeUserDefault { + return &DescribeUserDefault{ + _statusCode: code, + } +} + +/* DescribeUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUserDefaultBody +} + +// Code gets the status code for the describe user default response +func (o *DescribeUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe user default response has a 2xx status code +func (o *DescribeUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe user default response has a 3xx status code +func (o *DescribeUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe user default response has a 4xx status code +func (o *DescribeUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe user default response has a 5xx status code +func (o *DescribeUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe user default response a status code equal to that given +func (o *DescribeUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUserDefault) Error() string { + return fmt.Sprintf("[GET /users/{user_id}][%d] describeUser default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserDefault) String() string { + return fmt.Sprintf("[GET /users/{user_id}][%d] describeUser default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUserDefault) GetPayload() *DescribeUserDefaultBody { + return o.Payload +} + +func (o *DescribeUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUserDefaultBody describe user default body +swagger:model DescribeUserDefaultBody +*/ +type DescribeUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe user default body +func (o *DescribeUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user default body based on the context it is used +func (o *DescribeUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUserOKBody describe user o k body +swagger:model DescribeUserOKBody +*/ +type DescribeUserOKBody struct { + + // error + Error *models.ErrorResponse `json:"error,omitempty"` + + // result + Result *models.UserInfo `json:"result,omitempty"` +} + +// Validate validates this describe user o k body +func (o *DescribeUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserOKBody) validateError(formats strfmt.Registry) error { + if swag.IsZero(o.Error) { // not required + return nil + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserOK" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserOK" + "." + "error") + } + return err + } + } + + return nil +} + +func (o *DescribeUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe user o k body based on the context it is used +func (o *DescribeUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUserOKBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserOK" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserOK" + "." + "error") + } + return err + } + } + + return nil +} + +func (o *DescribeUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUserOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_users_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_users_parameters.go new file mode 100644 index 0000000..6bc90a4 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_users_parameters.go @@ -0,0 +1,430 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDescribeUsersParams creates a new DescribeUsersParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDescribeUsersParams() *DescribeUsersParams { + return &DescribeUsersParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDescribeUsersParamsWithTimeout creates a new DescribeUsersParams object +// with the ability to set a timeout on a request. +func NewDescribeUsersParamsWithTimeout(timeout time.Duration) *DescribeUsersParams { + return &DescribeUsersParams{ + timeout: timeout, + } +} + +// NewDescribeUsersParamsWithContext creates a new DescribeUsersParams object +// with the ability to set a context for a request. +func NewDescribeUsersParamsWithContext(ctx context.Context) *DescribeUsersParams { + return &DescribeUsersParams{ + Context: ctx, + } +} + +// NewDescribeUsersParamsWithHTTPClient creates a new DescribeUsersParams object +// with the ability to set a custom HTTPClient for a request. +func NewDescribeUsersParamsWithHTTPClient(client *http.Client) *DescribeUsersParams { + return &DescribeUsersParams{ + HTTPClient: client, + } +} + +/* DescribeUsersParams contains all the parameters to send to the API endpoint + for the describe users operation. + + Typically these are written to a http.Request. +*/ +type DescribeUsersParams struct { + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* DefaultProjectID. + + 项目uuid + */ + DefaultProjectID *string + + /* IsAll. + + 是否显示全部, isAll=1表示全部 + */ + IsAll *string + + /* PageNumber. + + 页码 + + Format: int64 + */ + PageNumber *int64 + + /* PageSize. + + 每页数量 + + Format: int64 + */ + PageSize *int64 + + /* RoleID. + + 角色uuid + */ + RoleID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + /* UserName. + + 用户名 + */ + UserName *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the describe users params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUsersParams) WithDefaults() *DescribeUsersParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the describe users params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DescribeUsersParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the describe users params +func (o *DescribeUsersParams) WithTimeout(timeout time.Duration) *DescribeUsersParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the describe users params +func (o *DescribeUsersParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the describe users params +func (o *DescribeUsersParams) WithContext(ctx context.Context) *DescribeUsersParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the describe users params +func (o *DescribeUsersParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the describe users params +func (o *DescribeUsersParams) WithHTTPClient(client *http.Client) *DescribeUsersParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the describe users params +func (o *DescribeUsersParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAuthorization adds the authorization to the describe users params +func (o *DescribeUsersParams) WithAuthorization(authorization string) *DescribeUsersParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the describe users params +func (o *DescribeUsersParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the describe users params +func (o *DescribeUsersParams) WithBmpLanguage(bmpLanguage *string) *DescribeUsersParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the describe users params +func (o *DescribeUsersParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the describe users params +func (o *DescribeUsersParams) WithBmpUserID(bmpUserID *string) *DescribeUsersParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the describe users params +func (o *DescribeUsersParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithDefaultProjectID adds the defaultProjectID to the describe users params +func (o *DescribeUsersParams) WithDefaultProjectID(defaultProjectID *string) *DescribeUsersParams { + o.SetDefaultProjectID(defaultProjectID) + return o +} + +// SetDefaultProjectID adds the defaultProjectId to the describe users params +func (o *DescribeUsersParams) SetDefaultProjectID(defaultProjectID *string) { + o.DefaultProjectID = defaultProjectID +} + +// WithIsAll adds the isAll to the describe users params +func (o *DescribeUsersParams) WithIsAll(isAll *string) *DescribeUsersParams { + o.SetIsAll(isAll) + return o +} + +// SetIsAll adds the isAll to the describe users params +func (o *DescribeUsersParams) SetIsAll(isAll *string) { + o.IsAll = isAll +} + +// WithPageNumber adds the pageNumber to the describe users params +func (o *DescribeUsersParams) WithPageNumber(pageNumber *int64) *DescribeUsersParams { + o.SetPageNumber(pageNumber) + return o +} + +// SetPageNumber adds the pageNumber to the describe users params +func (o *DescribeUsersParams) SetPageNumber(pageNumber *int64) { + o.PageNumber = pageNumber +} + +// WithPageSize adds the pageSize to the describe users params +func (o *DescribeUsersParams) WithPageSize(pageSize *int64) *DescribeUsersParams { + o.SetPageSize(pageSize) + return o +} + +// SetPageSize adds the pageSize to the describe users params +func (o *DescribeUsersParams) SetPageSize(pageSize *int64) { + o.PageSize = pageSize +} + +// WithRoleID adds the roleID to the describe users params +func (o *DescribeUsersParams) WithRoleID(roleID *string) *DescribeUsersParams { + o.SetRoleID(roleID) + return o +} + +// SetRoleID adds the roleId to the describe users params +func (o *DescribeUsersParams) SetRoleID(roleID *string) { + o.RoleID = roleID +} + +// WithTraceID adds the traceID to the describe users params +func (o *DescribeUsersParams) WithTraceID(traceID string) *DescribeUsersParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the describe users params +func (o *DescribeUsersParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserName adds the userName to the describe users params +func (o *DescribeUsersParams) WithUserName(userName *string) *DescribeUsersParams { + o.SetUserName(userName) + return o +} + +// SetUserName adds the userName to the describe users params +func (o *DescribeUsersParams) SetUserName(userName *string) { + o.UserName = userName +} + +// WriteToRequest writes these params to a swagger request +func (o *DescribeUsersParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + if o.DefaultProjectID != nil { + + // query param defaultProjectId + var qrDefaultProjectID string + + if o.DefaultProjectID != nil { + qrDefaultProjectID = *o.DefaultProjectID + } + qDefaultProjectID := qrDefaultProjectID + if qDefaultProjectID != "" { + + if err := r.SetQueryParam("defaultProjectId", qDefaultProjectID); err != nil { + return err + } + } + } + + if o.IsAll != nil { + + // query param isAll + var qrIsAll string + + if o.IsAll != nil { + qrIsAll = *o.IsAll + } + qIsAll := qrIsAll + if qIsAll != "" { + + if err := r.SetQueryParam("isAll", qIsAll); err != nil { + return err + } + } + } + + if o.PageNumber != nil { + + // query param pageNumber + var qrPageNumber int64 + + if o.PageNumber != nil { + qrPageNumber = *o.PageNumber + } + qPageNumber := swag.FormatInt64(qrPageNumber) + if qPageNumber != "" { + + if err := r.SetQueryParam("pageNumber", qPageNumber); err != nil { + return err + } + } + } + + if o.PageSize != nil { + + // query param pageSize + var qrPageSize int64 + + if o.PageSize != nil { + qrPageSize = *o.PageSize + } + qPageSize := swag.FormatInt64(qrPageSize) + if qPageSize != "" { + + if err := r.SetQueryParam("pageSize", qPageSize); err != nil { + return err + } + } + } + + if o.RoleID != nil { + + // query param roleId + var qrRoleID string + + if o.RoleID != nil { + qrRoleID = *o.RoleID + } + qRoleID := qrRoleID + if qRoleID != "" { + + if err := r.SetQueryParam("roleId", qRoleID); err != nil { + return err + } + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if o.UserName != nil { + + // query param userName + var qrUserName string + + if o.UserName != nil { + qrUserName = *o.UserName + } + qUserName := qrUserName + if qUserName != "" { + + if err := r.SetQueryParam("userName", qUserName); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_users_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_users_responses.go new file mode 100644 index 0000000..61001ee --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/describe_users_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// DescribeUsersReader is a Reader for the DescribeUsers structure. +type DescribeUsersReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DescribeUsersReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDescribeUsersOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewDescribeUsersDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewDescribeUsersOK creates a DescribeUsersOK with default headers values +func NewDescribeUsersOK() *DescribeUsersOK { + return &DescribeUsersOK{} +} + +/* DescribeUsersOK describes a response with status code 200, with default header values. + +DescribeUsersOK describe users o k +*/ +type DescribeUsersOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUsersOKBody +} + +// IsSuccess returns true when this describe users o k response has a 2xx status code +func (o *DescribeUsersOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this describe users o k response has a 3xx status code +func (o *DescribeUsersOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this describe users o k response has a 4xx status code +func (o *DescribeUsersOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this describe users o k response has a 5xx status code +func (o *DescribeUsersOK) IsServerError() bool { + return false +} + +// IsCode returns true when this describe users o k response a status code equal to that given +func (o *DescribeUsersOK) IsCode(code int) bool { + return code == 200 +} + +func (o *DescribeUsersOK) Error() string { + return fmt.Sprintf("[GET /users][%d] describeUsersOK %+v", 200, o.Payload) +} + +func (o *DescribeUsersOK) String() string { + return fmt.Sprintf("[GET /users][%d] describeUsersOK %+v", 200, o.Payload) +} + +func (o *DescribeUsersOK) GetPayload() *DescribeUsersOKBody { + return o.Payload +} + +func (o *DescribeUsersOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUsersOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDescribeUsersDefault creates a DescribeUsersDefault with default headers values +func NewDescribeUsersDefault(code int) *DescribeUsersDefault { + return &DescribeUsersDefault{ + _statusCode: code, + } +} + +/* DescribeUsersDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type DescribeUsersDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *DescribeUsersDefaultBody +} + +// Code gets the status code for the describe users default response +func (o *DescribeUsersDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this describe users default response has a 2xx status code +func (o *DescribeUsersDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this describe users default response has a 3xx status code +func (o *DescribeUsersDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this describe users default response has a 4xx status code +func (o *DescribeUsersDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this describe users default response has a 5xx status code +func (o *DescribeUsersDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this describe users default response a status code equal to that given +func (o *DescribeUsersDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *DescribeUsersDefault) Error() string { + return fmt.Sprintf("[GET /users][%d] describeUsers default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUsersDefault) String() string { + return fmt.Sprintf("[GET /users][%d] describeUsers default %+v", o._statusCode, o.Payload) +} + +func (o *DescribeUsersDefault) GetPayload() *DescribeUsersDefaultBody { + return o.Payload +} + +func (o *DescribeUsersDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(DescribeUsersDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*DescribeUsersDefaultBody describe users default body +swagger:model DescribeUsersDefaultBody +*/ +type DescribeUsersDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this describe users default body +func (o *DescribeUsersDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUsersDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("describeUsers default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *DescribeUsersDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("describeUsers default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUsers default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUsers default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe users default body based on the context it is used +func (o *DescribeUsersDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUsersDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUsers default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUsers default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUsersDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUsersDefaultBody) UnmarshalBinary(b []byte) error { + var res DescribeUsersDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*DescribeUsersOKBody describe users o k body +swagger:model DescribeUsersOKBody +*/ +type DescribeUsersOKBody struct { + + // result + Result *models.UserList `json:"result,omitempty"` +} + +// Validate validates this describe users o k body +func (o *DescribeUsersOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUsersOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUsersOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUsersOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this describe users o k body based on the context it is used +func (o *DescribeUsersOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *DescribeUsersOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("describeUsersOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("describeUsersOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *DescribeUsersOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *DescribeUsersOKBody) UnmarshalBinary(b []byte) error { + var res DescribeUsersOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_parameters.go new file mode 100644 index 0000000..4ec0580 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyLocalUserParams creates a new ModifyLocalUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyLocalUserParams() *ModifyLocalUserParams { + return &ModifyLocalUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyLocalUserParamsWithTimeout creates a new ModifyLocalUserParams object +// with the ability to set a timeout on a request. +func NewModifyLocalUserParamsWithTimeout(timeout time.Duration) *ModifyLocalUserParams { + return &ModifyLocalUserParams{ + timeout: timeout, + } +} + +// NewModifyLocalUserParamsWithContext creates a new ModifyLocalUserParams object +// with the ability to set a context for a request. +func NewModifyLocalUserParamsWithContext(ctx context.Context) *ModifyLocalUserParams { + return &ModifyLocalUserParams{ + Context: ctx, + } +} + +// NewModifyLocalUserParamsWithHTTPClient creates a new ModifyLocalUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyLocalUserParamsWithHTTPClient(client *http.Client) *ModifyLocalUserParams { + return &ModifyLocalUserParams{ + HTTPClient: client, + } +} + +/* ModifyLocalUserParams contains all the parameters to send to the API endpoint + for the modify local user operation. + + Typically these are written to a http.Request. +*/ +type ModifyLocalUserParams struct { + + // Body. + Body *models.ModifyLocalUserRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify local user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyLocalUserParams) WithDefaults() *ModifyLocalUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify local user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyLocalUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify local user params +func (o *ModifyLocalUserParams) WithTimeout(timeout time.Duration) *ModifyLocalUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify local user params +func (o *ModifyLocalUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify local user params +func (o *ModifyLocalUserParams) WithContext(ctx context.Context) *ModifyLocalUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify local user params +func (o *ModifyLocalUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify local user params +func (o *ModifyLocalUserParams) WithHTTPClient(client *http.Client) *ModifyLocalUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify local user params +func (o *ModifyLocalUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify local user params +func (o *ModifyLocalUserParams) WithBody(body *models.ModifyLocalUserRequest) *ModifyLocalUserParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify local user params +func (o *ModifyLocalUserParams) SetBody(body *models.ModifyLocalUserRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify local user params +func (o *ModifyLocalUserParams) WithAuthorization(authorization string) *ModifyLocalUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify local user params +func (o *ModifyLocalUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify local user params +func (o *ModifyLocalUserParams) WithBmpLanguage(bmpLanguage *string) *ModifyLocalUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify local user params +func (o *ModifyLocalUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify local user params +func (o *ModifyLocalUserParams) WithBmpUserID(bmpUserID *string) *ModifyLocalUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify local user params +func (o *ModifyLocalUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the modify local user params +func (o *ModifyLocalUserParams) WithTraceID(traceID string) *ModifyLocalUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify local user params +func (o *ModifyLocalUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyLocalUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_password_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_password_parameters.go new file mode 100644 index 0000000..79c4b96 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_password_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyLocalUserPasswordParams creates a new ModifyLocalUserPasswordParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyLocalUserPasswordParams() *ModifyLocalUserPasswordParams { + return &ModifyLocalUserPasswordParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyLocalUserPasswordParamsWithTimeout creates a new ModifyLocalUserPasswordParams object +// with the ability to set a timeout on a request. +func NewModifyLocalUserPasswordParamsWithTimeout(timeout time.Duration) *ModifyLocalUserPasswordParams { + return &ModifyLocalUserPasswordParams{ + timeout: timeout, + } +} + +// NewModifyLocalUserPasswordParamsWithContext creates a new ModifyLocalUserPasswordParams object +// with the ability to set a context for a request. +func NewModifyLocalUserPasswordParamsWithContext(ctx context.Context) *ModifyLocalUserPasswordParams { + return &ModifyLocalUserPasswordParams{ + Context: ctx, + } +} + +// NewModifyLocalUserPasswordParamsWithHTTPClient creates a new ModifyLocalUserPasswordParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyLocalUserPasswordParamsWithHTTPClient(client *http.Client) *ModifyLocalUserPasswordParams { + return &ModifyLocalUserPasswordParams{ + HTTPClient: client, + } +} + +/* ModifyLocalUserPasswordParams contains all the parameters to send to the API endpoint + for the modify local user password operation. + + Typically these are written to a http.Request. +*/ +type ModifyLocalUserPasswordParams struct { + + // Body. + Body *models.ModifyUserPasswordRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify local user password params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyLocalUserPasswordParams) WithDefaults() *ModifyLocalUserPasswordParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify local user password params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyLocalUserPasswordParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithTimeout(timeout time.Duration) *ModifyLocalUserPasswordParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithContext(ctx context.Context) *ModifyLocalUserPasswordParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithHTTPClient(client *http.Client) *ModifyLocalUserPasswordParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithBody(body *models.ModifyUserPasswordRequest) *ModifyLocalUserPasswordParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetBody(body *models.ModifyUserPasswordRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithAuthorization(authorization string) *ModifyLocalUserPasswordParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithBmpLanguage(bmpLanguage *string) *ModifyLocalUserPasswordParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithBmpUserID(bmpUserID *string) *ModifyLocalUserPasswordParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the modify local user password params +func (o *ModifyLocalUserPasswordParams) WithTraceID(traceID string) *ModifyLocalUserPasswordParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify local user password params +func (o *ModifyLocalUserPasswordParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyLocalUserPasswordParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_password_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_password_responses.go new file mode 100644 index 0000000..17acafd --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_password_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyLocalUserPasswordReader is a Reader for the ModifyLocalUserPassword structure. +type ModifyLocalUserPasswordReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyLocalUserPasswordReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyLocalUserPasswordOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyLocalUserPasswordDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyLocalUserPasswordOK creates a ModifyLocalUserPasswordOK with default headers values +func NewModifyLocalUserPasswordOK() *ModifyLocalUserPasswordOK { + return &ModifyLocalUserPasswordOK{} +} + +/* ModifyLocalUserPasswordOK describes a response with status code 200, with default header values. + +A ModifyLocalUserPasswordResult is an response struct that is used to describe getuser. +*/ +type ModifyLocalUserPasswordOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyLocalUserPasswordOKBody +} + +// IsSuccess returns true when this modify local user password o k response has a 2xx status code +func (o *ModifyLocalUserPasswordOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify local user password o k response has a 3xx status code +func (o *ModifyLocalUserPasswordOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify local user password o k response has a 4xx status code +func (o *ModifyLocalUserPasswordOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify local user password o k response has a 5xx status code +func (o *ModifyLocalUserPasswordOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify local user password o k response a status code equal to that given +func (o *ModifyLocalUserPasswordOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyLocalUserPasswordOK) Error() string { + return fmt.Sprintf("[PUT /local/users/password][%d] modifyLocalUserPasswordOK %+v", 200, o.Payload) +} + +func (o *ModifyLocalUserPasswordOK) String() string { + return fmt.Sprintf("[PUT /local/users/password][%d] modifyLocalUserPasswordOK %+v", 200, o.Payload) +} + +func (o *ModifyLocalUserPasswordOK) GetPayload() *ModifyLocalUserPasswordOKBody { + return o.Payload +} + +func (o *ModifyLocalUserPasswordOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyLocalUserPasswordOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyLocalUserPasswordDefault creates a ModifyLocalUserPasswordDefault with default headers values +func NewModifyLocalUserPasswordDefault(code int) *ModifyLocalUserPasswordDefault { + return &ModifyLocalUserPasswordDefault{ + _statusCode: code, + } +} + +/* ModifyLocalUserPasswordDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyLocalUserPasswordDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyLocalUserPasswordDefaultBody +} + +// Code gets the status code for the modify local user password default response +func (o *ModifyLocalUserPasswordDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify local user password default response has a 2xx status code +func (o *ModifyLocalUserPasswordDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify local user password default response has a 3xx status code +func (o *ModifyLocalUserPasswordDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify local user password default response has a 4xx status code +func (o *ModifyLocalUserPasswordDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify local user password default response has a 5xx status code +func (o *ModifyLocalUserPasswordDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify local user password default response a status code equal to that given +func (o *ModifyLocalUserPasswordDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyLocalUserPasswordDefault) Error() string { + return fmt.Sprintf("[PUT /local/users/password][%d] modifyLocalUserPassword default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyLocalUserPasswordDefault) String() string { + return fmt.Sprintf("[PUT /local/users/password][%d] modifyLocalUserPassword default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyLocalUserPasswordDefault) GetPayload() *ModifyLocalUserPasswordDefaultBody { + return o.Payload +} + +func (o *ModifyLocalUserPasswordDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyLocalUserPasswordDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyLocalUserPasswordDefaultBody modify local user password default body +swagger:model ModifyLocalUserPasswordDefaultBody +*/ +type ModifyLocalUserPasswordDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify local user password default body +func (o *ModifyLocalUserPasswordDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserPasswordDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyLocalUserPassword default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyLocalUserPasswordDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyLocalUserPassword default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserPassword default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserPassword default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify local user password default body based on the context it is used +func (o *ModifyLocalUserPasswordDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserPasswordDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserPassword default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserPassword default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyLocalUserPasswordDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyLocalUserPasswordDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyLocalUserPasswordDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyLocalUserPasswordOKBody modify local user password o k body +swagger:model ModifyLocalUserPasswordOKBody +*/ +type ModifyLocalUserPasswordOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify local user password o k body +func (o *ModifyLocalUserPasswordOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserPasswordOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserPasswordOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserPasswordOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify local user password o k body based on the context it is used +func (o *ModifyLocalUserPasswordOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserPasswordOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserPasswordOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserPasswordOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyLocalUserPasswordOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyLocalUserPasswordOKBody) UnmarshalBinary(b []byte) error { + var res ModifyLocalUserPasswordOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_responses.go new file mode 100644 index 0000000..912ea09 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_local_user_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyLocalUserReader is a Reader for the ModifyLocalUser structure. +type ModifyLocalUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyLocalUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyLocalUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyLocalUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyLocalUserOK creates a ModifyLocalUserOK with default headers values +func NewModifyLocalUserOK() *ModifyLocalUserOK { + return &ModifyLocalUserOK{} +} + +/* ModifyLocalUserOK describes a response with status code 200, with default header values. + +A ModifyLocalUserResult is an response struct that is used to describe getuser. +*/ +type ModifyLocalUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyLocalUserOKBody +} + +// IsSuccess returns true when this modify local user o k response has a 2xx status code +func (o *ModifyLocalUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify local user o k response has a 3xx status code +func (o *ModifyLocalUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify local user o k response has a 4xx status code +func (o *ModifyLocalUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify local user o k response has a 5xx status code +func (o *ModifyLocalUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify local user o k response a status code equal to that given +func (o *ModifyLocalUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyLocalUserOK) Error() string { + return fmt.Sprintf("[PUT /local/users][%d] modifyLocalUserOK %+v", 200, o.Payload) +} + +func (o *ModifyLocalUserOK) String() string { + return fmt.Sprintf("[PUT /local/users][%d] modifyLocalUserOK %+v", 200, o.Payload) +} + +func (o *ModifyLocalUserOK) GetPayload() *ModifyLocalUserOKBody { + return o.Payload +} + +func (o *ModifyLocalUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyLocalUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyLocalUserDefault creates a ModifyLocalUserDefault with default headers values +func NewModifyLocalUserDefault(code int) *ModifyLocalUserDefault { + return &ModifyLocalUserDefault{ + _statusCode: code, + } +} + +/* ModifyLocalUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyLocalUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyLocalUserDefaultBody +} + +// Code gets the status code for the modify local user default response +func (o *ModifyLocalUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify local user default response has a 2xx status code +func (o *ModifyLocalUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify local user default response has a 3xx status code +func (o *ModifyLocalUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify local user default response has a 4xx status code +func (o *ModifyLocalUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify local user default response has a 5xx status code +func (o *ModifyLocalUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify local user default response a status code equal to that given +func (o *ModifyLocalUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyLocalUserDefault) Error() string { + return fmt.Sprintf("[PUT /local/users][%d] modifyLocalUser default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyLocalUserDefault) String() string { + return fmt.Sprintf("[PUT /local/users][%d] modifyLocalUser default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyLocalUserDefault) GetPayload() *ModifyLocalUserDefaultBody { + return o.Payload +} + +func (o *ModifyLocalUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyLocalUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyLocalUserDefaultBody modify local user default body +swagger:model ModifyLocalUserDefaultBody +*/ +type ModifyLocalUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify local user default body +func (o *ModifyLocalUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyLocalUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyLocalUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyLocalUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify local user default body based on the context it is used +func (o *ModifyLocalUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyLocalUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyLocalUserDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyLocalUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyLocalUserOKBody modify local user o k body +swagger:model ModifyLocalUserOKBody +*/ +type ModifyLocalUserOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify local user o k body +func (o *ModifyLocalUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify local user o k body based on the context it is used +func (o *ModifyLocalUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyLocalUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyLocalUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyLocalUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyLocalUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyLocalUserOKBody) UnmarshalBinary(b []byte) error { + var res ModifyLocalUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_user_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_user_parameters.go new file mode 100644 index 0000000..4b888d3 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_user_parameters.go @@ -0,0 +1,261 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewModifyUserParams creates a new ModifyUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewModifyUserParams() *ModifyUserParams { + return &ModifyUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewModifyUserParamsWithTimeout creates a new ModifyUserParams object +// with the ability to set a timeout on a request. +func NewModifyUserParamsWithTimeout(timeout time.Duration) *ModifyUserParams { + return &ModifyUserParams{ + timeout: timeout, + } +} + +// NewModifyUserParamsWithContext creates a new ModifyUserParams object +// with the ability to set a context for a request. +func NewModifyUserParamsWithContext(ctx context.Context) *ModifyUserParams { + return &ModifyUserParams{ + Context: ctx, + } +} + +// NewModifyUserParamsWithHTTPClient creates a new ModifyUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewModifyUserParamsWithHTTPClient(client *http.Client) *ModifyUserParams { + return &ModifyUserParams{ + HTTPClient: client, + } +} + +/* ModifyUserParams contains all the parameters to send to the API endpoint + for the modify user operation. + + Typically these are written to a http.Request. +*/ +type ModifyUserParams struct { + + // Body. + Body *models.ModifyUserRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid, deprecated + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + // UserID. + UserID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the modify user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserParams) WithDefaults() *ModifyUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the modify user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ModifyUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the modify user params +func (o *ModifyUserParams) WithTimeout(timeout time.Duration) *ModifyUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the modify user params +func (o *ModifyUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the modify user params +func (o *ModifyUserParams) WithContext(ctx context.Context) *ModifyUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the modify user params +func (o *ModifyUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the modify user params +func (o *ModifyUserParams) WithHTTPClient(client *http.Client) *ModifyUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the modify user params +func (o *ModifyUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the modify user params +func (o *ModifyUserParams) WithBody(body *models.ModifyUserRequest) *ModifyUserParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the modify user params +func (o *ModifyUserParams) SetBody(body *models.ModifyUserRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the modify user params +func (o *ModifyUserParams) WithAuthorization(authorization string) *ModifyUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the modify user params +func (o *ModifyUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the modify user params +func (o *ModifyUserParams) WithBmpLanguage(bmpLanguage *string) *ModifyUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the modify user params +func (o *ModifyUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the modify user params +func (o *ModifyUserParams) WithBmpUserID(bmpUserID *string) *ModifyUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the modify user params +func (o *ModifyUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the modify user params +func (o *ModifyUserParams) WithTraceID(traceID string) *ModifyUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the modify user params +func (o *ModifyUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WithUserID adds the userID to the modify user params +func (o *ModifyUserParams) WithUserID(userID string) *ModifyUserParams { + o.SetUserID(userID) + return o +} + +// SetUserID adds the userId to the modify user params +func (o *ModifyUserParams) SetUserID(userID string) { + o.UserID = userID +} + +// WriteToRequest writes these params to a swagger request +func (o *ModifyUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + // path param user_id + if err := r.SetPathParam("user_id", o.UserID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_user_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_user_responses.go new file mode 100644 index 0000000..a34d90e --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/modify_user_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// ModifyUserReader is a Reader for the ModifyUser structure. +type ModifyUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ModifyUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewModifyUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewModifyUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewModifyUserOK creates a ModifyUserOK with default headers values +func NewModifyUserOK() *ModifyUserOK { + return &ModifyUserOK{} +} + +/* ModifyUserOK describes a response with status code 200, with default header values. + +A GetUserResult is an response struct that is used to describe getuser. +*/ +type ModifyUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserOKBody +} + +// IsSuccess returns true when this modify user o k response has a 2xx status code +func (o *ModifyUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this modify user o k response has a 3xx status code +func (o *ModifyUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this modify user o k response has a 4xx status code +func (o *ModifyUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this modify user o k response has a 5xx status code +func (o *ModifyUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this modify user o k response a status code equal to that given +func (o *ModifyUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *ModifyUserOK) Error() string { + return fmt.Sprintf("[PUT /users/{user_id}][%d] modifyUserOK %+v", 200, o.Payload) +} + +func (o *ModifyUserOK) String() string { + return fmt.Sprintf("[PUT /users/{user_id}][%d] modifyUserOK %+v", 200, o.Payload) +} + +func (o *ModifyUserOK) GetPayload() *ModifyUserOKBody { + return o.Payload +} + +func (o *ModifyUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewModifyUserDefault creates a ModifyUserDefault with default headers values +func NewModifyUserDefault(code int) *ModifyUserDefault { + return &ModifyUserDefault{ + _statusCode: code, + } +} + +/* ModifyUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type ModifyUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *ModifyUserDefaultBody +} + +// Code gets the status code for the modify user default response +func (o *ModifyUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this modify user default response has a 2xx status code +func (o *ModifyUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this modify user default response has a 3xx status code +func (o *ModifyUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this modify user default response has a 4xx status code +func (o *ModifyUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this modify user default response has a 5xx status code +func (o *ModifyUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this modify user default response a status code equal to that given +func (o *ModifyUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *ModifyUserDefault) Error() string { + return fmt.Sprintf("[PUT /users/{user_id}][%d] modifyUser default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserDefault) String() string { + return fmt.Sprintf("[PUT /users/{user_id}][%d] modifyUser default %+v", o._statusCode, o.Payload) +} + +func (o *ModifyUserDefault) GetPayload() *ModifyUserDefaultBody { + return o.Payload +} + +func (o *ModifyUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(ModifyUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*ModifyUserDefaultBody modify user default body +swagger:model ModifyUserDefaultBody +*/ +type ModifyUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this modify user default body +func (o *ModifyUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("modifyUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *ModifyUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("modifyUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user default body based on the context it is used +func (o *ModifyUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserDefaultBody) UnmarshalBinary(b []byte) error { + var res ModifyUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*ModifyUserOKBody modify user o k body +swagger:model ModifyUserOKBody +*/ +type ModifyUserOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this modify user o k body +func (o *ModifyUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this modify user o k body based on the context it is used +func (o *ModifyUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *ModifyUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modifyUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modifyUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *ModifyUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *ModifyUserOKBody) UnmarshalBinary(b []byte) error { + var res ModifyUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/user_client.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/user_client.go new file mode 100644 index 0000000..6a1bae7 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/user_client.go @@ -0,0 +1,437 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new user API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for user API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption is the option for Client methods +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + CreateUser(params *CreateUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserOK, error) + + DeleteUser(params *DeleteUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserOK, error) + + DescribeLocalUser(params *DescribeLocalUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLocalUserOK, error) + + DescribeUser(params *DescribeUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserOK, error) + + DescribeUserByName(params *DescribeUserByNameParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserByNameOK, error) + + DescribeUsers(params *DescribeUsersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUsersOK, error) + + ModifyLocalUser(params *ModifyLocalUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyLocalUserOK, error) + + ModifyLocalUserPassword(params *ModifyLocalUserPasswordParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyLocalUserPasswordOK, error) + + ModifyUser(params *ModifyUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserOK, error) + + VerifyUser(params *VerifyUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*VerifyUserOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* + CreateUser CreateUser 创建用户 +*/ +func (a *Client) CreateUser(params *CreateUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateUserParams() + } + op := &runtime.ClientOperation{ + ID: "createUser", + Method: "POST", + PathPattern: "/users", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DeleteUser DeleteUser 删除用户 +*/ +func (a *Client) DeleteUser(params *DeleteUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteUserParams() + } + op := &runtime.ClientOperation{ + ID: "deleteUser", + Method: "DELETE", + PathPattern: "/users/{user_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DeleteUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeLocalUser DescribeLocalUser 控制台获取用户详情 +*/ +func (a *Client) DescribeLocalUser(params *DescribeLocalUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeLocalUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeLocalUserParams() + } + op := &runtime.ClientOperation{ + ID: "describeLocalUser", + Method: "GET", + PathPattern: "/local/users", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeLocalUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeLocalUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeLocalUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUser DescribeUser 获取用户详情 +*/ +func (a *Client) DescribeUser(params *DescribeUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserParams() + } + op := &runtime.ClientOperation{ + ID: "describeUser", + Method: "GET", + PathPattern: "/users/{user_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUserByName DescribeUserByName 根据用户名获取用户详情 +*/ +func (a *Client) DescribeUserByName(params *DescribeUserByNameParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUserByNameOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUserByNameParams() + } + op := &runtime.ClientOperation{ + ID: "describeUserByName", + Method: "GET", + PathPattern: "/users/getUserByName", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUserByNameReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUserByNameOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUserByNameDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + DescribeUsers DescribeUsers 获取用户列表 +*/ +func (a *Client) DescribeUsers(params *DescribeUsersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DescribeUsersOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDescribeUsersParams() + } + op := &runtime.ClientOperation{ + ID: "describeUsers", + Method: "GET", + PathPattern: "/users", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DescribeUsersReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DescribeUsersOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*DescribeUsersDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyLocalUser ModifyLocalUser 控制台修改除密码外的个人信息 +*/ +func (a *Client) ModifyLocalUser(params *ModifyLocalUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyLocalUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyLocalUserParams() + } + op := &runtime.ClientOperation{ + ID: "modifyLocalUser", + Method: "PUT", + PathPattern: "/local/users", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyLocalUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyLocalUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyLocalUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyLocalUserPassword ModifyLocalUserPassword 控制台修改个人密码 +*/ +func (a *Client) ModifyLocalUserPassword(params *ModifyLocalUserPasswordParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyLocalUserPasswordOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyLocalUserPasswordParams() + } + op := &runtime.ClientOperation{ + ID: "modifyLocalUserPassword", + Method: "PUT", + PathPattern: "/local/users/password", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyLocalUserPasswordReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyLocalUserPasswordOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyLocalUserPasswordDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + ModifyUser ModifyUser 修改用户信息 +*/ +func (a *Client) ModifyUser(params *ModifyUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ModifyUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewModifyUserParams() + } + op := &runtime.ClientOperation{ + ID: "modifyUser", + Method: "PUT", + PathPattern: "/users/{user_id}", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ModifyUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ModifyUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ModifyUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* + VerifyUser VerifyUser 鉴定用户 +*/ +func (a *Client) VerifyUser(params *VerifyUserParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*VerifyUserOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewVerifyUserParams() + } + op := &runtime.ClientOperation{ + ID: "verifyUser", + Method: "POST", + PathPattern: "/users/verify", + ProducesMediaTypes: []string{"application/json", "application/xml"}, + ConsumesMediaTypes: []string{"application/json", "application/xml"}, + Schemes: []string{"http"}, + Params: params, + Reader: &VerifyUserReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*VerifyUserOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*VerifyUserDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/verify_user_parameters.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/verify_user_parameters.go new file mode 100644 index 0000000..bf260ee --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/verify_user_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// NewVerifyUserParams creates a new VerifyUserParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewVerifyUserParams() *VerifyUserParams { + return &VerifyUserParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewVerifyUserParamsWithTimeout creates a new VerifyUserParams object +// with the ability to set a timeout on a request. +func NewVerifyUserParamsWithTimeout(timeout time.Duration) *VerifyUserParams { + return &VerifyUserParams{ + timeout: timeout, + } +} + +// NewVerifyUserParamsWithContext creates a new VerifyUserParams object +// with the ability to set a context for a request. +func NewVerifyUserParamsWithContext(ctx context.Context) *VerifyUserParams { + return &VerifyUserParams{ + Context: ctx, + } +} + +// NewVerifyUserParamsWithHTTPClient creates a new VerifyUserParams object +// with the ability to set a custom HTTPClient for a request. +func NewVerifyUserParamsWithHTTPClient(client *http.Client) *VerifyUserParams { + return &VerifyUserParams{ + HTTPClient: client, + } +} + +/* VerifyUserParams contains all the parameters to send to the API endpoint + for the verify user operation. + + Typically these are written to a http.Request. +*/ +type VerifyUserParams struct { + + // Body. + Body *models.VerifyUserRequest + + /* Authorization. + + demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + */ + Authorization string + + /* BmpLanguage. + + 用户语言 [zh_CN, en_US] + */ + BmpLanguage *string + + /* BmpUserID. + + 用户uuid + */ + BmpUserID *string + + /* TraceID. + + 流量唯一id + */ + TraceID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the verify user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *VerifyUserParams) WithDefaults() *VerifyUserParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the verify user params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *VerifyUserParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the verify user params +func (o *VerifyUserParams) WithTimeout(timeout time.Duration) *VerifyUserParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the verify user params +func (o *VerifyUserParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the verify user params +func (o *VerifyUserParams) WithContext(ctx context.Context) *VerifyUserParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the verify user params +func (o *VerifyUserParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the verify user params +func (o *VerifyUserParams) WithHTTPClient(client *http.Client) *VerifyUserParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the verify user params +func (o *VerifyUserParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the verify user params +func (o *VerifyUserParams) WithBody(body *models.VerifyUserRequest) *VerifyUserParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the verify user params +func (o *VerifyUserParams) SetBody(body *models.VerifyUserRequest) { + o.Body = body +} + +// WithAuthorization adds the authorization to the verify user params +func (o *VerifyUserParams) WithAuthorization(authorization string) *VerifyUserParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the verify user params +func (o *VerifyUserParams) SetAuthorization(authorization string) { + o.Authorization = authorization +} + +// WithBmpLanguage adds the bmpLanguage to the verify user params +func (o *VerifyUserParams) WithBmpLanguage(bmpLanguage *string) *VerifyUserParams { + o.SetBmpLanguage(bmpLanguage) + return o +} + +// SetBmpLanguage adds the bmpLanguage to the verify user params +func (o *VerifyUserParams) SetBmpLanguage(bmpLanguage *string) { + o.BmpLanguage = bmpLanguage +} + +// WithBmpUserID adds the bmpUserID to the verify user params +func (o *VerifyUserParams) WithBmpUserID(bmpUserID *string) *VerifyUserParams { + o.SetBmpUserID(bmpUserID) + return o +} + +// SetBmpUserID adds the bmpUserId to the verify user params +func (o *VerifyUserParams) SetBmpUserID(bmpUserID *string) { + o.BmpUserID = bmpUserID +} + +// WithTraceID adds the traceID to the verify user params +func (o *VerifyUserParams) WithTraceID(traceID string) *VerifyUserParams { + o.SetTraceID(traceID) + return o +} + +// SetTraceID adds the traceId to the verify user params +func (o *VerifyUserParams) SetTraceID(traceID string) { + o.TraceID = traceID +} + +// WriteToRequest writes these params to a swagger request +func (o *VerifyUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + } + + // header param authorization + if err := r.SetHeaderParam("authorization", o.Authorization); err != nil { + return err + } + + if o.BmpLanguage != nil { + + // header param bmpLanguage + if err := r.SetHeaderParam("bmpLanguage", *o.BmpLanguage); err != nil { + return err + } + } + + if o.BmpUserID != nil { + + // header param bmpUserId + if err := r.SetHeaderParam("bmpUserId", *o.BmpUserID); err != nil { + return err + } + } + + // header param traceId + if err := r.SetHeaderParam("traceId", o.TraceID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/verify_user_responses.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/verify_user_responses.go new file mode 100644 index 0000000..220fb78 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/client/user/verify_user_responses.go @@ -0,0 +1,403 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package user + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" +) + +// VerifyUserReader is a Reader for the VerifyUser structure. +type VerifyUserReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *VerifyUserReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewVerifyUserOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewVerifyUserDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewVerifyUserOK creates a VerifyUserOK with default headers values +func NewVerifyUserOK() *VerifyUserOK { + return &VerifyUserOK{} +} + +/* VerifyUserOK describes a response with status code 200, with default header values. + +A VerifyUserResult is an response struct that is used to describe verify user result. +*/ +type VerifyUserOK struct { + + /* 流量ID + in: header + */ + TraceID string + + Payload *VerifyUserOKBody +} + +// IsSuccess returns true when this verify user o k response has a 2xx status code +func (o *VerifyUserOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this verify user o k response has a 3xx status code +func (o *VerifyUserOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this verify user o k response has a 4xx status code +func (o *VerifyUserOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this verify user o k response has a 5xx status code +func (o *VerifyUserOK) IsServerError() bool { + return false +} + +// IsCode returns true when this verify user o k response a status code equal to that given +func (o *VerifyUserOK) IsCode(code int) bool { + return code == 200 +} + +func (o *VerifyUserOK) Error() string { + return fmt.Sprintf("[POST /users/verify][%d] verifyUserOK %+v", 200, o.Payload) +} + +func (o *VerifyUserOK) String() string { + return fmt.Sprintf("[POST /users/verify][%d] verifyUserOK %+v", 200, o.Payload) +} + +func (o *VerifyUserOK) GetPayload() *VerifyUserOKBody { + return o.Payload +} + +func (o *VerifyUserOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(VerifyUserOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewVerifyUserDefault creates a VerifyUserDefault with default headers values +func NewVerifyUserDefault(code int) *VerifyUserDefault { + return &VerifyUserDefault{ + _statusCode: code, + } +} + +/* VerifyUserDefault describes a response with status code -1, with default header values. + +unit err response for non 200 +*/ +type VerifyUserDefault struct { + _statusCode int + + /* 流量ID + in: header + */ + TraceID string + + Payload *VerifyUserDefaultBody +} + +// Code gets the status code for the verify user default response +func (o *VerifyUserDefault) Code() int { + return o._statusCode +} + +// IsSuccess returns true when this verify user default response has a 2xx status code +func (o *VerifyUserDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this verify user default response has a 3xx status code +func (o *VerifyUserDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this verify user default response has a 4xx status code +func (o *VerifyUserDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this verify user default response has a 5xx status code +func (o *VerifyUserDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this verify user default response a status code equal to that given +func (o *VerifyUserDefault) IsCode(code int) bool { + return o._statusCode == code +} + +func (o *VerifyUserDefault) Error() string { + return fmt.Sprintf("[POST /users/verify][%d] verifyUser default %+v", o._statusCode, o.Payload) +} + +func (o *VerifyUserDefault) String() string { + return fmt.Sprintf("[POST /users/verify][%d] verifyUser default %+v", o._statusCode, o.Payload) +} + +func (o *VerifyUserDefault) GetPayload() *VerifyUserDefaultBody { + return o.Payload +} + +func (o *VerifyUserDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // hydrates response header traceId + hdrTraceID := response.GetHeader("traceId") + + if hdrTraceID != "" { + o.TraceID = hdrTraceID + } + + o.Payload = new(VerifyUserDefaultBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/*VerifyUserDefaultBody verify user default body +swagger:model VerifyUserDefaultBody +*/ +type VerifyUserDefaultBody struct { + + // 流量ID + // Required: true + RequestID *string `json:"requestId"` + + // error + // Required: true + Error *models.ErrorResponse `json:"error"` +} + +// Validate validates this verify user default body +func (o *VerifyUserDefaultBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateRequestID(formats); err != nil { + res = append(res, err) + } + + if err := o.validateError(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *VerifyUserDefaultBody) validateRequestID(formats strfmt.Registry) error { + + if err := validate.Required("verifyUser default"+"."+"requestId", "body", o.RequestID); err != nil { + return err + } + + return nil +} + +func (o *VerifyUserDefaultBody) validateError(formats strfmt.Registry) error { + + if err := validate.Required("verifyUser default"+"."+"error", "body", o.Error); err != nil { + return err + } + + if o.Error != nil { + if err := o.Error.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("verifyUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("verifyUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// ContextValidate validate this verify user default body based on the context it is used +func (o *VerifyUserDefaultBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateError(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *VerifyUserDefaultBody) contextValidateError(ctx context.Context, formats strfmt.Registry) error { + + if o.Error != nil { + if err := o.Error.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("verifyUser default" + "." + "error") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("verifyUser default" + "." + "error") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *VerifyUserDefaultBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *VerifyUserDefaultBody) UnmarshalBinary(b []byte) error { + var res VerifyUserDefaultBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} + +/*VerifyUserOKBody verify user o k body +swagger:model VerifyUserOKBody +*/ +type VerifyUserOKBody struct { + + // result + Result *models.CommonResponse `json:"result,omitempty"` +} + +// Validate validates this verify user o k body +func (o *VerifyUserOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateResult(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *VerifyUserOKBody) validateResult(formats strfmt.Registry) error { + if swag.IsZero(o.Result) { // not required + return nil + } + + if o.Result != nil { + if err := o.Result.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("verifyUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("verifyUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// ContextValidate validate this verify user o k body based on the context it is used +func (o *VerifyUserOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateResult(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *VerifyUserOKBody) contextValidateResult(ctx context.Context, formats strfmt.Registry) error { + + if o.Result != nil { + if err := o.Result.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("verifyUserOK" + "." + "result") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("verifyUserOK" + "." + "result") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *VerifyUserOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *VerifyUserOKBody) UnmarshalBinary(b []byte) error { + var res VerifyUserOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/go.mod b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/go.mod new file mode 100644 index 0000000..2b82f4f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/go.mod @@ -0,0 +1,3 @@ +module coding.jd.com/aidc-bmp/bmp-openapi-sdk + +go 1.17 diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/apikey.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/apikey.go new file mode 100644 index 0000000..415fe37 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/apikey.go @@ -0,0 +1,171 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Apikey apikey +// +// swagger:model Apikey +type Apikey struct { + + // apikey uuid + // Required: true + ApikeyID *string `json:"apiKeyId"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // ID + ID int64 `json:"id,omitempty"` + + // 名称 + // Required: true + Name *string `json:"name"` + + // 是否支持只读, [0/1], 1表示只读 + // Required: true + ReadOnly *int8 `json:"readOnly"` + + // 32位字符令牌,使用token来独立访问openapi + // Required: true + Token *string `json:"token"` + + // apikey的类型,[system/user] + // Required: true + Type *string `json:"type"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 所属用户uuid + // Required: true + UserID *string `json:"userId"` +} + +// Validate validates this apikey +func (m *Apikey) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateApikeyID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateReadOnly(formats); err != nil { + res = append(res, err) + } + + if err := m.validateToken(formats); err != nil { + res = append(res, err) + } + + if err := m.validateType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Apikey) validateApikeyID(formats strfmt.Registry) error { + + if err := validate.Required("apiKeyId", "body", m.ApikeyID); err != nil { + return err + } + + return nil +} + +func (m *Apikey) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +func (m *Apikey) validateReadOnly(formats strfmt.Registry) error { + + if err := validate.Required("readOnly", "body", m.ReadOnly); err != nil { + return err + } + + return nil +} + +func (m *Apikey) validateToken(formats strfmt.Registry) error { + + if err := validate.Required("token", "body", m.Token); err != nil { + return err + } + + return nil +} + +func (m *Apikey) validateType(formats strfmt.Registry) error { + + if err := validate.Required("type", "body", m.Type); err != nil { + return err + } + + return nil +} + +func (m *Apikey) validateUserID(formats strfmt.Registry) error { + + if err := validate.Required("userId", "body", m.UserID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this apikey based on context it is used +func (m *Apikey) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Apikey) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Apikey) UnmarshalBinary(b []byte) error { + var res Apikey + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/apikey_id.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/apikey_id.go new file mode 100644 index 0000000..6097b8a --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/apikey_id.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ApikeyID apikey Id +// +// swagger:model ApikeyId +type ApikeyID struct { + + // apikey uuid + // Required: true + ApikeyID *string `json:"apikeyId"` +} + +// Validate validates this apikey Id +func (m *ApikeyID) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateApikeyID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ApikeyID) validateApikeyID(formats strfmt.Registry) error { + + if err := validate.Required("apikeyId", "body", m.ApikeyID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this apikey Id based on context it is used +func (m *ApikeyID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ApikeyID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ApikeyID) UnmarshalBinary(b []byte) error { + var res ApikeyID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/apikey_info.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/apikey_info.go new file mode 100644 index 0000000..652fa8c --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/apikey_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ApikeyInfo apikey info +// +// swagger:model ApikeyInfo +type ApikeyInfo struct { + + // apikey + Apikey *Apikey `json:"apikey,omitempty"` +} + +// Validate validates this apikey info +func (m *ApikeyInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateApikey(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ApikeyInfo) validateApikey(formats strfmt.Registry) error { + if swag.IsZero(m.Apikey) { // not required + return nil + } + + if m.Apikey != nil { + if err := m.Apikey.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("apikey") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("apikey") + } + return err + } + } + + return nil +} + +// ContextValidate validate this apikey info based on the context it is used +func (m *ApikeyInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateApikey(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ApikeyInfo) contextValidateApikey(ctx context.Context, formats strfmt.Registry) error { + + if m.Apikey != nil { + if err := m.Apikey.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("apikey") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("apikey") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ApikeyInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ApikeyInfo) UnmarshalBinary(b []byte) error { + var res ApikeyInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/apikey_list.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/apikey_list.go new file mode 100644 index 0000000..6cceae9 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/apikey_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ApikeyList apikey list +// +// swagger:model ApikeyList +type ApikeyList struct { + + // apikeys + Apikeys []*Apikey `json:"apikeys"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this apikey list +func (m *ApikeyList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateApikeys(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ApikeyList) validateApikeys(formats strfmt.Registry) error { + if swag.IsZero(m.Apikeys) { // not required + return nil + } + + for i := 0; i < len(m.Apikeys); i++ { + if swag.IsZero(m.Apikeys[i]) { // not required + continue + } + + if m.Apikeys[i] != nil { + if err := m.Apikeys[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("apikeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("apikeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this apikey list based on the context it is used +func (m *ApikeyList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateApikeys(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ApikeyList) contextValidateApikeys(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Apikeys); i++ { + + if m.Apikeys[i] != nil { + if err := m.Apikeys[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("apikeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("apikeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ApikeyList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ApikeyList) UnmarshalBinary(b []byte) error { + var res ApikeyList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/associate_device_type_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/associate_device_type_request.go new file mode 100644 index 0000000..5e22584 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/associate_device_type_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// AssociateDeviceTypeRequest associate device type request +// +// swagger:model AssociateDeviceTypeRequest +type AssociateDeviceTypeRequest struct { + + // 设备类型id,数组,支持多个 + // Required: true + DeviceTypeIDs []string `json:"deviceTypeIds"` + + // 镜像ID, + // Required: true + ImageID *string `json:"imageId"` +} + +// Validate validates this associate device type request +func (m *AssociateDeviceTypeRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceTypeIDs(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImageID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AssociateDeviceTypeRequest) validateDeviceTypeIDs(formats strfmt.Registry) error { + + if err := validate.Required("deviceTypeIds", "body", m.DeviceTypeIDs); err != nil { + return err + } + + return nil +} + +func (m *AssociateDeviceTypeRequest) validateImageID(formats strfmt.Registry) error { + + if err := validate.Required("imageId", "body", m.ImageID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this associate device type request based on context it is used +func (m *AssociateDeviceTypeRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *AssociateDeviceTypeRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AssociateDeviceTypeRequest) UnmarshalBinary(b []byte) error { + var res AssociateDeviceTypeRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/associate_image_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/associate_image_request.go new file mode 100644 index 0000000..6da7b09 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/associate_image_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// AssociateImageRequest associate image request +// +// swagger:model AssociateImageRequest +type AssociateImageRequest struct { + + // 设备类型id + // Required: true + DeviceTypeID *string `json:"deviceTypeId"` + + // 镜像ID,数组,支持多个 + // Required: true + ImageIDs []string `json:"imageIds"` +} + +// Validate validates this associate image request +func (m *AssociateImageRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceTypeID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImageIDs(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AssociateImageRequest) validateDeviceTypeID(formats strfmt.Registry) error { + + if err := validate.Required("deviceTypeId", "body", m.DeviceTypeID); err != nil { + return err + } + + return nil +} + +func (m *AssociateImageRequest) validateImageIDs(formats strfmt.Registry) error { + + if err := validate.Required("imageIds", "body", m.ImageIDs); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this associate image request based on context it is used +func (m *AssociateImageRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *AssociateImageRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AssociateImageRequest) UnmarshalBinary(b []byte) error { + var res AssociateImageRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/collect_device_info_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/collect_device_info_request.go new file mode 100644 index 0000000..38888b4 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/collect_device_info_request.go @@ -0,0 +1,119 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CollectDeviceInfoRequest collect device info request +// +// swagger:model CollectDeviceInfoRequest +type CollectDeviceInfoRequest struct { + + // 待采集项 + // Required: true + Collects []*CollectItem `json:"collects"` +} + +// Validate validates this collect device info request +func (m *CollectDeviceInfoRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCollects(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CollectDeviceInfoRequest) validateCollects(formats strfmt.Registry) error { + + if err := validate.Required("collects", "body", m.Collects); err != nil { + return err + } + + for i := 0; i < len(m.Collects); i++ { + if swag.IsZero(m.Collects[i]) { // not required + continue + } + + if m.Collects[i] != nil { + if err := m.Collects[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("collects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("collects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this collect device info request based on the context it is used +func (m *CollectDeviceInfoRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateCollects(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CollectDeviceInfoRequest) contextValidateCollects(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Collects); i++ { + + if m.Collects[i] != nil { + if err := m.Collects[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("collects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("collects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CollectDeviceInfoRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CollectDeviceInfoRequest) UnmarshalBinary(b []byte) error { + var res CollectDeviceInfoRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/collect_item.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/collect_item.go new file mode 100644 index 0000000..8cc7154 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/collect_item.go @@ -0,0 +1,196 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CollectItem collect item +// +// swagger:model CollectItem +type CollectItem struct { + + // 可选参数。 传参:True, False 。True表示传入的raid_driver值将覆盖已适配机器的raid_driver + AllowOverride *bool `json:"allowOverride,omitempty"` + + // 网关地址 + // Required: true + Gateway *string `json:"gateway"` + + // 带外IP + // Required: true + IloIP *string `json:"iloIp"` + + // 带外密码 + // Required: true + IloPassword *string `json:"iloPassword"` + + // 带外账号 + // Required: true + IloUser *string `json:"iloUser"` + + // MAC1(eth0) + // Required: true + Mac1 *string `json:"mac1"` + + // 掩码 + // Required: true + Mask *string `json:"mask"` + + // 内网IPV4 + // Required: true + PrivateIPV4 *string `json:"privateIpv4"` + + // raid_driver可选参数。传参:sas2ircu,sas3ircu,megacli64,storcli64,perccli64,no_raid。不传参数则只可采集已适配机型,如果未适配则采集失败 + RaidDriver *string `json:"raidDriver,omitempty"` + + // sn + // Required: true + Sn *string `json:"sn"` +} + +// Validate validates this collect item +func (m *CollectItem) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateGateway(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIloIP(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIloPassword(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIloUser(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMac1(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMask(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePrivateIPV4(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSn(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CollectItem) validateGateway(formats strfmt.Registry) error { + + if err := validate.Required("gateway", "body", m.Gateway); err != nil { + return err + } + + return nil +} + +func (m *CollectItem) validateIloIP(formats strfmt.Registry) error { + + if err := validate.Required("iloIp", "body", m.IloIP); err != nil { + return err + } + + return nil +} + +func (m *CollectItem) validateIloPassword(formats strfmt.Registry) error { + + if err := validate.Required("iloPassword", "body", m.IloPassword); err != nil { + return err + } + + return nil +} + +func (m *CollectItem) validateIloUser(formats strfmt.Registry) error { + + if err := validate.Required("iloUser", "body", m.IloUser); err != nil { + return err + } + + return nil +} + +func (m *CollectItem) validateMac1(formats strfmt.Registry) error { + + if err := validate.Required("mac1", "body", m.Mac1); err != nil { + return err + } + + return nil +} + +func (m *CollectItem) validateMask(formats strfmt.Registry) error { + + if err := validate.Required("mask", "body", m.Mask); err != nil { + return err + } + + return nil +} + +func (m *CollectItem) validatePrivateIPV4(formats strfmt.Registry) error { + + if err := validate.Required("privateIpv4", "body", m.PrivateIPV4); err != nil { + return err + } + + return nil +} + +func (m *CollectItem) validateSn(formats strfmt.Registry) error { + + if err := validate.Required("sn", "body", m.Sn); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this collect item based on context it is used +func (m *CollectItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CollectItem) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CollectItem) UnmarshalBinary(b []byte) error { + var res CollectItem + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/common_response.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/common_response.go new file mode 100644 index 0000000..f3957c5 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/common_response.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonResponse common response +// +// swagger:model CommonResponse +type CommonResponse struct { + + // 操作是否成功 [true/false] + Success bool `json:"success,omitempty"` +} + +// Validate validates this common response +func (m *CommonResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common response based on context it is used +func (m *CommonResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonResponse) UnmarshalBinary(b []byte) error { + var res CommonResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_apikey_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_apikey_request.go new file mode 100644 index 0000000..7462b07 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_apikey_request.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateApikeyRequest create apikey request +// +// swagger:model CreateApikeyRequest +type CreateApikeyRequest struct { + + // 秘钥对名称 + // Required: true + Name *string `json:"name"` + + // 是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法 + // Required: true + ReadOnly *int8 `json:"readOnly"` + + // Token类型, [system/user] + // Required: true + Type *string `json:"type"` +} + +// Validate validates this create apikey request +func (m *CreateApikeyRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateReadOnly(formats); err != nil { + res = append(res, err) + } + + if err := m.validateType(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateApikeyRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +func (m *CreateApikeyRequest) validateReadOnly(formats strfmt.Registry) error { + + if err := validate.Required("readOnly", "body", m.ReadOnly); err != nil { + return err + } + + return nil +} + +func (m *CreateApikeyRequest) validateType(formats strfmt.Registry) error { + + if err := validate.Required("type", "body", m.Type); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create apikey request based on context it is used +func (m *CreateApikeyRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateApikeyRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateApikeyRequest) UnmarshalBinary(b []byte) error { + var res CreateApikeyRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_device_spec.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_device_spec.go new file mode 100644 index 0000000..3630e54 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_device_spec.go @@ -0,0 +1,411 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateDeviceSpec create device spec +// +// swagger:model CreateDeviceSpec +type CreateDeviceSpec struct { + + // adapter_id + // Required: true + AdapterID *int64 `json:"adapterId"` + + // 品牌 + // Required: true + Brand *string `json:"brand"` + + // 机柜编码 + // Required: true + Cabinet *string `json:"cabinet"` + + // 描述 + Description string `json:"description,omitempty"` + + // 系统盘1背板号 + // Required: true + Enclosure1 *string `json:"enclosure1"` + + // 系统盘2背板号 + Enclosure2 string `json:"Enclosure2,omitempty"` + + // 网关地址 + // Required: true + Gateway *string `json:"gateway"` + + // 带外IP + // Required: true + IloIP *string `json:"iloIp"` + + // 带外密码 + IloPassword string `json:"iloPassword,omitempty"` + + // 带外账号 + IloUser string `json:"iloUser,omitempty"` + + // instance ID + InstanceID string `json:"instanceId,omitempty"` + + // MAC1(eth0) + // Required: true + Mac1 *string `json:"mac1"` + + // MAC2(eth1) + // Required: true + Mac2 *string `json:"mac2"` + + // 设备状态,默认已入库 + ManageStatus string `json:"manageStatus,omitempty"` + + // 子网掩码 + // Required: true + Mask *string `json:"mask"` + + // eth1子网掩码 + MaskEth1 string `json:"maskEth1,omitempty"` + + // 型号 + // Required: true + Model *string `json:"model"` + + // eth1内网IPV4(非bond模式时传值) + PrivateEth1IPV4 string `json:"privateEth1Ipv4,omitempty"` + + // eth1内网IPV6(非bond模式时传值) + PrivateEth1IPV6 string `json:"privateEth1Ipv6,omitempty"` + + // 内网IPV4 + // Required: true + PrivateIPV4 *string `json:"privateIpv4"` + + // 内网IPV6 + PrivateIPV6 string `json:"privateIpv6,omitempty"` + + // raid工具:(megacli128等) + RaidDriver string `json:"raidDriver,omitempty"` + + // 系统盘1槽位 + // Required: true + Slot1 *int64 `json:"slot1"` + + // 系统盘2槽位 + Slot2 int64 `json:"slot2,omitempty"` + + // 设备SN + // Required: true + Sn *string `json:"sn"` + + // 网口交换机IP + SwitchIP string `json:"switchIp,omitempty"` + + // 交换机1ip + // Required: true + SwitchIP1 *string `json:"switchIp1"` + + // 交换机2ip + // Required: true + SwitchIP2 *string `json:"switchIp2"` + + // 交换机1登录密码 + SwitchPassword1 string `json:"switchPassword1,omitempty"` + + // 交换机2登录密码 + SwitchPassword2 string `json:"switchPassword2,omitempty"` + + // 交换机1port + // Required: true + SwitchPort1 *string `json:"switchPort1"` + + // 交换机2port + // Required: true + SwitchPort2 *string `json:"switchPort2"` + + // 交换机1登录账号 + SwitchUser1 string `json:"switchUser1,omitempty"` + + // 交换机2登录账号 + SwitchUser2 string `json:"SwitchUser2,omitempty"` + + // 所在U位 + // Required: true + UPosition *string `json:"uPosition"` +} + +// Validate validates this create device spec +func (m *CreateDeviceSpec) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAdapterID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateBrand(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCabinet(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEnclosure1(formats); err != nil { + res = append(res, err) + } + + if err := m.validateGateway(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIloIP(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMac1(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMac2(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMask(formats); err != nil { + res = append(res, err) + } + + if err := m.validateModel(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePrivateIPV4(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSlot1(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSn(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSwitchIP1(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSwitchIP2(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSwitchPort1(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSwitchPort2(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUPosition(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateDeviceSpec) validateAdapterID(formats strfmt.Registry) error { + + if err := validate.Required("adapterId", "body", m.AdapterID); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateBrand(formats strfmt.Registry) error { + + if err := validate.Required("brand", "body", m.Brand); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateCabinet(formats strfmt.Registry) error { + + if err := validate.Required("cabinet", "body", m.Cabinet); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateEnclosure1(formats strfmt.Registry) error { + + if err := validate.Required("enclosure1", "body", m.Enclosure1); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateGateway(formats strfmt.Registry) error { + + if err := validate.Required("gateway", "body", m.Gateway); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateIloIP(formats strfmt.Registry) error { + + if err := validate.Required("iloIp", "body", m.IloIP); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateMac1(formats strfmt.Registry) error { + + if err := validate.Required("mac1", "body", m.Mac1); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateMac2(formats strfmt.Registry) error { + + if err := validate.Required("mac2", "body", m.Mac2); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateMask(formats strfmt.Registry) error { + + if err := validate.Required("mask", "body", m.Mask); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateModel(formats strfmt.Registry) error { + + if err := validate.Required("model", "body", m.Model); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validatePrivateIPV4(formats strfmt.Registry) error { + + if err := validate.Required("privateIpv4", "body", m.PrivateIPV4); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateSlot1(formats strfmt.Registry) error { + + if err := validate.Required("slot1", "body", m.Slot1); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateSn(formats strfmt.Registry) error { + + if err := validate.Required("sn", "body", m.Sn); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateSwitchIP1(formats strfmt.Registry) error { + + if err := validate.Required("switchIp1", "body", m.SwitchIP1); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateSwitchIP2(formats strfmt.Registry) error { + + if err := validate.Required("switchIp2", "body", m.SwitchIP2); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateSwitchPort1(formats strfmt.Registry) error { + + if err := validate.Required("switchPort1", "body", m.SwitchPort1); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateSwitchPort2(formats strfmt.Registry) error { + + if err := validate.Required("switchPort2", "body", m.SwitchPort2); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceSpec) validateUPosition(formats strfmt.Registry) error { + + if err := validate.Required("uPosition", "body", m.UPosition); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create device spec based on context it is used +func (m *CreateDeviceSpec) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateDeviceSpec) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateDeviceSpec) UnmarshalBinary(b []byte) error { + var res CreateDeviceSpec + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_device_type_raid_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_device_type_raid_request.go new file mode 100644 index 0000000..b43eb95 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_device_type_raid_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CreateDeviceTypeRaidRequest create device type raid request +// +// swagger:model CreateDeviceTypeRaidRequest +type CreateDeviceTypeRaidRequest struct { + + // available value + AvailableValue int64 `json:"availableValue,omitempty"` + + // device type + DeviceType string `json:"deviceType,omitempty"` + + // device type ID + DeviceTypeID string `json:"DeviceTypeId,omitempty"` + + // disk type + DiskType string `json:"diskType,omitempty"` + + // raid ID + RaidID string `json:"raidId,omitempty"` + + // system partition count + SystemPartitionCount int64 `json:"systemPartitionCount,omitempty"` + + // volume detail + VolumeDetail string `json:"volumeDetail,omitempty"` + + // volume type + VolumeType string `json:"volumeType,omitempty"` +} + +// Validate validates this create device type raid request +func (m *CreateDeviceTypeRaidRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this create device type raid request based on context it is used +func (m *CreateDeviceTypeRaidRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateDeviceTypeRaidRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateDeviceTypeRaidRequest) UnmarshalBinary(b []byte) error { + var res CreateDeviceTypeRaidRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_device_type_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_device_type_request.go new file mode 100644 index 0000000..4844c0d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_device_type_request.go @@ -0,0 +1,529 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateDeviceTypeRequest create device type request +// +// swagger:model CreateDeviceTypeRequest +type CreateDeviceTypeRequest struct { + + // 体系架构,1-64 + // Required: true + Architecture *string `json:"architecture"` + + // boot模式【UEFI Legacy/BIOS】支持多选,逗号分隔 + BootMode string `json:"boot_mode,omitempty"` + + // cpu数量1,10000 + // Required: true + CPUAmount *int64 `json:"cpuAmount"` + + // 单个cpu内核数1,10000 + // Required: true + CPUCores *int64 `json:"cpuCores"` + + // cpu频率(G)1-64 + // Required: true + CPUFrequency *string `json:"cpuFrequency"` + + // cpu厂商1-64 + // Required: true + CPUManufacturer *string `json:"cpuManufacturer"` + + // cpu处理器型号1-64 + // Required: true + CPUModel *string `json:"cpuModel"` + + // CPU 预置规格 + // Required: true + CPUSpec *string `json:"cpuSpec"` + + // 数据盘数量0-10000 + DataVolumeAmount int64 `json:"dataVolumeAmount,omitempty"` + + // 数据盘接口类型0-64 + DataVolumeInterfaceType string `json:"dataVolumeInterfaceType,omitempty"` + + // 数据盘单盘大小0-100000 + DataVolumeSize int64 `json:"dataVolumeSize,omitempty"` + + // 数据盘类型0-64 + DataVolumeType string `json:"dataVolumeType,omitempty"` + + // 数据盘单盘大小单位GB TB + DataVolumeUnit string `json:"dataVolumeUnit,omitempty"` + + // 描述0-256 + Description string `json:"description,omitempty"` + + // 机型类型,如computer storage gpu other + // Required: true + DeviceSeries *string `json:"deviceSeries"` + + // 机型规格1-64 + // Required: true + DeviceType *string `json:"deviceType"` + + // gpu数量0-1000 + GpuAmount int64 `json:"gpuAmount,omitempty"` + + // gpu品牌0-64 + GpuManufacturer string `json:"gpuManufacturer,omitempty"` + + // gpu型号0-64 + GpuModel string `json:"gpuModel,omitempty"` + + // 【高度(U)】:显示机型高度 2,4 + // Required: true + Height *int64 `json:"height"` + + // 机房id + // Required: true + IDcID *string `json:"idcId"` + + // 【网口模式】【网络设置】: bond,dual,single + // Required: true + InterfaceMode *string `json:"interfaceMode"` + + // 内存数量1-10000 + // Required: true + MemAmount *int64 `json:"memAmount"` + + // 内存主频(MHz)1-10000 + // Required: true + MemFrequency *int64 `json:"memFrequency"` + + // 单个内存大小1,10000(GB) + // Required: true + MemSize *int64 `json:"memSize"` + + // 内存 预置规格 + // Required: true + MemSpec *string `json:"memSpec"` + + // 内存接口(DDR DDR2 DDR3 DDR4 DDR5) + // Required: true + MemType *string `json:"memType"` + + // 机型名称1-64 + // Required: true + Name *string `json:"name"` + + // 网卡数量1-10000 + // Required: true + NicAmount *int64 `json:"nicAmount"` + + // 网卡传输速率(GE) 1-10000 + // Required: true + NicRate *int64 `json:"nicRate"` + + // 是否做raid,[RAID/NORAID] + RaidCan string `json:"raidCan,omitempty"` + + // 系统盘raid,支持多选,英文逗号分隔 + // Required: true + RaidID *string `json:"raidId"` + + // 系统盘数量,最少1块,最多2块 + // Required: true + SystemVolumeAmount *int64 `json:"systemVolumeAmount"` + + // 系统盘接口类型(SATA,SAS,NVME) + // Required: true + SystemVolumeInterfaceType *string `json:"systemVolumeInterfaceType"` + + // 系统盘单盘大小1-100000 + // Required: true + SystemVolumeSize *int64 `json:"systemVolumeSize"` + + // 系统盘类型(SSD,HDD) + // Required: true + SystemVolumeType *string `json:"systemVolumeType"` + + // 系统盘单盘大小单位 GB,TB + // Required: true + SystemVolumeUnit *string `json:"systemVolumeUnit"` +} + +// Validate validates this create device type request +func (m *CreateDeviceTypeRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateArchitecture(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCPUAmount(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCPUCores(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCPUFrequency(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCPUManufacturer(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCPUModel(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCPUSpec(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDeviceSeries(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDeviceType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateHeight(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIDcID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInterfaceMode(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMemAmount(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMemFrequency(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMemSize(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMemSpec(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMemType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNicAmount(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNicRate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRaidID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemVolumeAmount(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemVolumeInterfaceType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemVolumeSize(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemVolumeType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemVolumeUnit(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateDeviceTypeRequest) validateArchitecture(formats strfmt.Registry) error { + + if err := validate.Required("architecture", "body", m.Architecture); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateCPUAmount(formats strfmt.Registry) error { + + if err := validate.Required("cpuAmount", "body", m.CPUAmount); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateCPUCores(formats strfmt.Registry) error { + + if err := validate.Required("cpuCores", "body", m.CPUCores); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateCPUFrequency(formats strfmt.Registry) error { + + if err := validate.Required("cpuFrequency", "body", m.CPUFrequency); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateCPUManufacturer(formats strfmt.Registry) error { + + if err := validate.Required("cpuManufacturer", "body", m.CPUManufacturer); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateCPUModel(formats strfmt.Registry) error { + + if err := validate.Required("cpuModel", "body", m.CPUModel); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateCPUSpec(formats strfmt.Registry) error { + + if err := validate.Required("cpuSpec", "body", m.CPUSpec); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateDeviceSeries(formats strfmt.Registry) error { + + if err := validate.Required("deviceSeries", "body", m.DeviceSeries); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateDeviceType(formats strfmt.Registry) error { + + if err := validate.Required("deviceType", "body", m.DeviceType); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateHeight(formats strfmt.Registry) error { + + if err := validate.Required("height", "body", m.Height); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateIDcID(formats strfmt.Registry) error { + + if err := validate.Required("idcId", "body", m.IDcID); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateInterfaceMode(formats strfmt.Registry) error { + + if err := validate.Required("interfaceMode", "body", m.InterfaceMode); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateMemAmount(formats strfmt.Registry) error { + + if err := validate.Required("memAmount", "body", m.MemAmount); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateMemFrequency(formats strfmt.Registry) error { + + if err := validate.Required("memFrequency", "body", m.MemFrequency); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateMemSize(formats strfmt.Registry) error { + + if err := validate.Required("memSize", "body", m.MemSize); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateMemSpec(formats strfmt.Registry) error { + + if err := validate.Required("memSpec", "body", m.MemSpec); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateMemType(formats strfmt.Registry) error { + + if err := validate.Required("memType", "body", m.MemType); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateNicAmount(formats strfmt.Registry) error { + + if err := validate.Required("nicAmount", "body", m.NicAmount); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateNicRate(formats strfmt.Registry) error { + + if err := validate.Required("nicRate", "body", m.NicRate); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateRaidID(formats strfmt.Registry) error { + + if err := validate.Required("raidId", "body", m.RaidID); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateSystemVolumeAmount(formats strfmt.Registry) error { + + if err := validate.Required("systemVolumeAmount", "body", m.SystemVolumeAmount); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateSystemVolumeInterfaceType(formats strfmt.Registry) error { + + if err := validate.Required("systemVolumeInterfaceType", "body", m.SystemVolumeInterfaceType); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateSystemVolumeSize(formats strfmt.Registry) error { + + if err := validate.Required("systemVolumeSize", "body", m.SystemVolumeSize); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateSystemVolumeType(formats strfmt.Registry) error { + + if err := validate.Required("systemVolumeType", "body", m.SystemVolumeType); err != nil { + return err + } + + return nil +} + +func (m *CreateDeviceTypeRequest) validateSystemVolumeUnit(formats strfmt.Registry) error { + + if err := validate.Required("systemVolumeUnit", "body", m.SystemVolumeUnit); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create device type request based on context it is used +func (m *CreateDeviceTypeRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateDeviceTypeRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateDeviceTypeRequest) UnmarshalBinary(b []byte) error { + var res CreateDeviceTypeRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_devices_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_devices_request.go new file mode 100644 index 0000000..3f21cac --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_devices_request.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateDevicesRequest create devices request +// +// swagger:model CreateDevicesRequest +type CreateDevicesRequest struct { + + // 机型uuid + // Required: true + DeviceTypeID *string `json:"deviceTypeId"` + + // 设备信息 + // Required: true + Devices []*CreateDeviceSpec `json:"devices"` + + // 机房uuid + // Required: true + IDcID *string `json:"idcId"` +} + +// Validate validates this create devices request +func (m *CreateDevicesRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceTypeID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDevices(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIDcID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateDevicesRequest) validateDeviceTypeID(formats strfmt.Registry) error { + + if err := validate.Required("deviceTypeId", "body", m.DeviceTypeID); err != nil { + return err + } + + return nil +} + +func (m *CreateDevicesRequest) validateDevices(formats strfmt.Registry) error { + + if err := validate.Required("devices", "body", m.Devices); err != nil { + return err + } + + for i := 0; i < len(m.Devices); i++ { + if swag.IsZero(m.Devices[i]) { // not required + continue + } + + if m.Devices[i] != nil { + if err := m.Devices[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("devices" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("devices" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CreateDevicesRequest) validateIDcID(formats strfmt.Registry) error { + + if err := validate.Required("idcId", "body", m.IDcID); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this create devices request based on the context it is used +func (m *CreateDevicesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDevices(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateDevicesRequest) contextValidateDevices(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Devices); i++ { + + if m.Devices[i] != nil { + if err := m.Devices[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("devices" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("devices" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CreateDevicesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateDevicesRequest) UnmarshalBinary(b []byte) error { + var res CreateDevicesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_idc_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_idc_request.go new file mode 100644 index 0000000..4c26cfb --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_idc_request.go @@ -0,0 +1,143 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateIdcRequest create idc request +// +// swagger:model CreateIdcRequest +type CreateIdcRequest struct { + + // 机房地址 0-256 + Address string `json:"address,omitempty"` + + // 带外密码 0-64 + IloPassword string `json:"iloPassword,omitempty"` + + // 带外用户名 0-64 + IloUser string `json:"iloUser,omitempty"` + + // 机房等级 1-64 + // Required: true + Level *string `json:"level"` + + // 机房名称 1-64 + // Required: true + Name *string `json:"name"` + + // 机房英文名称 1-64 + // Required: true + NameEn *string `json:"nameEn"` + + // 机房缩写 1-64 + // Required: true + Shortname *string `json:"shortname"` + + // 交换机密码1 0-64 + SwitchPassword1 string `json:"switchPassword1,omitempty"` + + // 交换机密码2 0-64 + SwitchPassword2 string `json:"switchPassword2,omitempty"` + + // 交换机用户1 0-64 + SwitchUser1 string `json:"switchUser1,omitempty"` + + // 交换机用户2 0-64 + SwitchUser2 string `json:"switchUser2,omitempty"` +} + +// Validate validates this create idc request +func (m *CreateIdcRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateLevel(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNameEn(formats); err != nil { + res = append(res, err) + } + + if err := m.validateShortname(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateIdcRequest) validateLevel(formats strfmt.Registry) error { + + if err := validate.Required("level", "body", m.Level); err != nil { + return err + } + + return nil +} + +func (m *CreateIdcRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +func (m *CreateIdcRequest) validateNameEn(formats strfmt.Registry) error { + + if err := validate.Required("nameEn", "body", m.NameEn); err != nil { + return err + } + + return nil +} + +func (m *CreateIdcRequest) validateShortname(formats strfmt.Registry) error { + + if err := validate.Required("shortname", "body", m.Shortname); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create idc request based on context it is used +func (m *CreateIdcRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateIdcRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateIdcRequest) UnmarshalBinary(b []byte) error { + var res CreateIdcRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_image_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_image_request.go new file mode 100644 index 0000000..c812a61 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_image_request.go @@ -0,0 +1,219 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateImageRequest create image request +// +// swagger:model CreateImageRequest +type CreateImageRequest struct { + + // 体系架构 + // Required: true + Architecture *string `json:"architecture"` + + // 引导模式【UEFI Legacy/BIOS】 + // Required: true + BootMode *string `json:"boot_mode"` + + // 数据分区信息 + DataPartition string `json:"dataPartition,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 镜像文件名称 + // Required: true + Filename *string `json:"filename"` + + // 镜像文件类型 + // Required: true + Format *string `json:"format"` + + // 文件hash值 + // Required: true + Hash *string `json:"hash"` + + // 镜像名称 + // Required: true + ImageName *string `json:"imageName"` + + // 操作系统平台 + // Required: true + OsType *string `json:"osType"` + + // 镜像类型,预置,自定义 + Source string `json:"source,omitempty"` + + // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:50GiB,swap) + SystemPartition string `json:"systemPartition,omitempty"` + + // 镜像上传地址 + // Required: true + URL *string `json:"url"` + + // 版本号 + // Required: true + Version *string `json:"Version"` +} + +// Validate validates this create image request +func (m *CreateImageRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateArchitecture(formats); err != nil { + res = append(res, err) + } + + if err := m.validateBootMode(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFilename(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFormat(formats); err != nil { + res = append(res, err) + } + + if err := m.validateHash(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImageName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOsType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateURL(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateImageRequest) validateArchitecture(formats strfmt.Registry) error { + + if err := validate.Required("architecture", "body", m.Architecture); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateBootMode(formats strfmt.Registry) error { + + if err := validate.Required("boot_mode", "body", m.BootMode); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateFilename(formats strfmt.Registry) error { + + if err := validate.Required("filename", "body", m.Filename); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateFormat(formats strfmt.Registry) error { + + if err := validate.Required("format", "body", m.Format); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateHash(formats strfmt.Registry) error { + + if err := validate.Required("hash", "body", m.Hash); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateImageName(formats strfmt.Registry) error { + + if err := validate.Required("imageName", "body", m.ImageName); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateOsType(formats strfmt.Registry) error { + + if err := validate.Required("osType", "body", m.OsType); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateURL(formats strfmt.Registry) error { + + if err := validate.Required("url", "body", m.URL); err != nil { + return err + } + + return nil +} + +func (m *CreateImageRequest) validateVersion(formats strfmt.Registry) error { + + if err := validate.Required("Version", "body", m.Version); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create image request based on context it is used +func (m *CreateImageRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateImageRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateImageRequest) UnmarshalBinary(b []byte) error { + var res CreateImageRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_instance_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_instance_request.go new file mode 100644 index 0000000..4782366 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_instance_request.go @@ -0,0 +1,237 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateInstanceRequest create instance request +// +// swagger:model CreateInstanceRequest +type CreateInstanceRequest struct { + + // boot mode + BootMode string `json:"boot_mode,omitempty"` + + // 创建数量 + Count int64 `json:"count,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 设备类型ID + // Required: true + DeviceTypeID *string `json:"deviceTypeId"` + + // 主机名称 + HostName string `json:"hostname,omitempty"` + + // 机房ID + // Required: true + IdcID *string `json:"idcId"` + + // 镜像ID + // Required: true + ImageID *string `json:"imageId"` + + // 实例名称 + // Required: true + InstanceName *string `json:"instanceName"` + + // 密码 + Password string `json:"password,omitempty"` + + // 项目ID + // Required: true + ProjectID *string `json:"projectId"` + + // 秘钥ID + SSHKeyID string `json:"sshKeyId,omitempty"` + + // 系统盘分区 + SystemPartition []*Partition `json:"systemPartition"` + + // 系统盘RAID ID + // Required: true + SystemVolumeRaidID *string `json:"systemVolumeRaidId"` +} + +// Validate validates this create instance request +func (m *CreateInstanceRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceTypeID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIdcID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImageID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInstanceName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProjectID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemPartition(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemVolumeRaidID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateInstanceRequest) validateDeviceTypeID(formats strfmt.Registry) error { + + if err := validate.Required("deviceTypeId", "body", m.DeviceTypeID); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateIdcID(formats strfmt.Registry) error { + + if err := validate.Required("idcId", "body", m.IdcID); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateImageID(formats strfmt.Registry) error { + + if err := validate.Required("imageId", "body", m.ImageID); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateInstanceName(formats strfmt.Registry) error { + + if err := validate.Required("instanceName", "body", m.InstanceName); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateProjectID(formats strfmt.Registry) error { + + if err := validate.Required("projectId", "body", m.ProjectID); err != nil { + return err + } + + return nil +} + +func (m *CreateInstanceRequest) validateSystemPartition(formats strfmt.Registry) error { + if swag.IsZero(m.SystemPartition) { // not required + return nil + } + + for i := 0; i < len(m.SystemPartition); i++ { + if swag.IsZero(m.SystemPartition[i]) { // not required + continue + } + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CreateInstanceRequest) validateSystemVolumeRaidID(formats strfmt.Registry) error { + + if err := validate.Required("systemVolumeRaidId", "body", m.SystemVolumeRaidID); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this create instance request based on the context it is used +func (m *CreateInstanceRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSystemPartition(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateInstanceRequest) contextValidateSystemPartition(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.SystemPartition); i++ { + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CreateInstanceRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateInstanceRequest) UnmarshalBinary(b []byte) error { + var res CreateInstanceRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_license_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_license_request.go new file mode 100644 index 0000000..840a879 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_license_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CreateLicenseRequest create license request +// +// swagger:model CreateLicenseRequest +type CreateLicenseRequest struct { + + // content + Content string `json:"content,omitempty"` +} + +// Validate validates this create license request +func (m *CreateLicenseRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this create license request based on context it is used +func (m *CreateLicenseRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateLicenseRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateLicenseRequest) UnmarshalBinary(b []byte) error { + var res CreateLicenseRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_o_s_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_o_s_request.go new file mode 100644 index 0000000..537575b --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_o_s_request.go @@ -0,0 +1,142 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateOSRequest create o s request +// +// swagger:model CreateOSRequest +type CreateOSRequest struct { + + // 体系架构 + // Required: true + Architecture *string `json:"architecture"` + + // 位数 + // Required: true + Bits *int64 `json:"bits"` + + // 操作系统名称 + // Required: true + OsName *string `json:"osName"` + + // 操作系统平台 + // Required: true + OsType *string `json:"osType"` + + // 操作系统版本 + // Required: true + OsVersion *string `json:"osVersion"` + + // 系统用户 + SysUser string `json:"sysUser,omitempty"` +} + +// Validate validates this create o s request +func (m *CreateOSRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateArchitecture(formats); err != nil { + res = append(res, err) + } + + if err := m.validateBits(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOsName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOsType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOsVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateOSRequest) validateArchitecture(formats strfmt.Registry) error { + + if err := validate.Required("architecture", "body", m.Architecture); err != nil { + return err + } + + return nil +} + +func (m *CreateOSRequest) validateBits(formats strfmt.Registry) error { + + if err := validate.Required("bits", "body", m.Bits); err != nil { + return err + } + + return nil +} + +func (m *CreateOSRequest) validateOsName(formats strfmt.Registry) error { + + if err := validate.Required("osName", "body", m.OsName); err != nil { + return err + } + + return nil +} + +func (m *CreateOSRequest) validateOsType(formats strfmt.Registry) error { + + if err := validate.Required("osType", "body", m.OsType); err != nil { + return err + } + + return nil +} + +func (m *CreateOSRequest) validateOsVersion(formats strfmt.Registry) error { + + if err := validate.Required("osVersion", "body", m.OsVersion); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create o s request based on context it is used +func (m *CreateOSRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateOSRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateOSRequest) UnmarshalBinary(b []byte) error { + var res CreateOSRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_project_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_project_request.go new file mode 100644 index 0000000..017df2d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_project_request.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateProjectRequest create project request +// +// swagger:model CreateProjectRequest +type CreateProjectRequest struct { + + // 是否作为该用户的默认项目, [0/1], 默认为0 + IsDefault int8 `json:"isDefault,omitempty"` + + // 是否作为系统项目, [0/1], 默认为0 + IsSystem int8 `json:"isSystem,omitempty"` + + // ProjectName 1~64字符,只支持数字、大小写字母、中英文下划线“_”及中划线“-” + // Required: true + ProjectName *string `json:"projectName"` +} + +// Validate validates this create project request +func (m *CreateProjectRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateProjectName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateProjectRequest) validateProjectName(formats strfmt.Registry) error { + + if err := validate.Required("projectName", "body", m.ProjectName); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create project request based on context it is used +func (m *CreateProjectRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateProjectRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateProjectRequest) UnmarshalBinary(b []byte) error { + var res CreateProjectRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_raid_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_raid_request.go new file mode 100644 index 0000000..c52c5dc --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_raid_request.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateRaidRequest create raid request +// +// swagger:model CreateRaidRequest +type CreateRaidRequest struct { + + // raid描述(中文) + // Required: true + DescriptionEn *string `json:"descriptionEn"` + + // raid描述(英文) + // Required: true + DescriptionZh *string `json:"descriptionZh"` + + // raid名称 + // Required: true + Name *string `json:"name"` +} + +// Validate validates this create raid request +func (m *CreateRaidRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDescriptionEn(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDescriptionZh(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateRaidRequest) validateDescriptionEn(formats strfmt.Registry) error { + + if err := validate.Required("descriptionEn", "body", m.DescriptionEn); err != nil { + return err + } + + return nil +} + +func (m *CreateRaidRequest) validateDescriptionZh(formats strfmt.Registry) error { + + if err := validate.Required("descriptionZh", "body", m.DescriptionZh); err != nil { + return err + } + + return nil +} + +func (m *CreateRaidRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create raid request based on context it is used +func (m *CreateRaidRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateRaidRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateRaidRequest) UnmarshalBinary(b []byte) error { + var res CreateRaidRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_role_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_role_request.go new file mode 100644 index 0000000..744a9b3 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_role_request.go @@ -0,0 +1,122 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateRoleRequest create role request +// +// swagger:model CreateRoleRequest +type CreateRoleRequest struct { + + // 角色描述中文名称 + // Required: true + DescriptionCn *string `json:"descriptionCn"` + + // 角色描述英文名称 + // Required: true + DescriptionEn *string `json:"descriptionEn"` + + // 角色中文名称 + // Required: true + RoleNameCn *string `json:"roleNameCn"` + + // 角色英文名称 + // Required: true + RoleNameEn *string `json:"roleNameEn"` +} + +// Validate validates this create role request +func (m *CreateRoleRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDescriptionCn(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDescriptionEn(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRoleNameCn(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRoleNameEn(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateRoleRequest) validateDescriptionCn(formats strfmt.Registry) error { + + if err := validate.Required("descriptionCn", "body", m.DescriptionCn); err != nil { + return err + } + + return nil +} + +func (m *CreateRoleRequest) validateDescriptionEn(formats strfmt.Registry) error { + + if err := validate.Required("descriptionEn", "body", m.DescriptionEn); err != nil { + return err + } + + return nil +} + +func (m *CreateRoleRequest) validateRoleNameCn(formats strfmt.Registry) error { + + if err := validate.Required("roleNameCn", "body", m.RoleNameCn); err != nil { + return err + } + + return nil +} + +func (m *CreateRoleRequest) validateRoleNameEn(formats strfmt.Registry) error { + + if err := validate.Required("roleNameEn", "body", m.RoleNameEn); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create role request based on context it is used +func (m *CreateRoleRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateRoleRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateRoleRequest) UnmarshalBinary(b []byte) error { + var res CreateRoleRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_sshkey_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_sshkey_request.go new file mode 100644 index 0000000..8afaff3 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_sshkey_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateSshkeyRequest create sshkey request +// +// swagger:model CreateSshkeyRequest +type CreateSshkeyRequest struct { + + // 公钥内容,格式:^ssh-rsa AAAAB3NzaC1yc2.* + // Required: true + Key *string `json:"key"` + + // 秘钥名称 + // Required: true + Name *string `json:"name"` +} + +// Validate validates this create sshkey request +func (m *CreateSshkeyRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateKey(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateSshkeyRequest) validateKey(formats strfmt.Registry) error { + + if err := validate.Required("key", "body", m.Key); err != nil { + return err + } + + return nil +} + +func (m *CreateSshkeyRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create sshkey request based on context it is used +func (m *CreateSshkeyRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateSshkeyRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateSshkeyRequest) UnmarshalBinary(b []byte) error { + var res CreateSshkeyRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_user_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_user_request.go new file mode 100644 index 0000000..c0d97f4 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/create_user_request.go @@ -0,0 +1,126 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreateUserRequest create user request +// +// swagger:model CreateUserRequest +type CreateUserRequest struct { + + // 用户默认项目uuid + DefaultProjectID string `json:"defaultProjectId,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 邮箱 + Email string `json:"email,omitempty"` + + // 语言[en_US, zh_CN] + Language string `json:"language,omitempty"` + + // 密码 明文 密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + // Required: true + Password *string `json:"password"` + + // 手机号 + PhoneNumber string `json:"phoneNumber,omitempty"` + + // 国家地区码,如86 + PhonePrefix string `json:"phonePrefix,omitempty"` + + // 角色uuid + // Required: true + RoleID *string `json:"roleId"` + + // 时区,Asia/Shanghai + Timezone string `json:"timezone,omitempty"` + + // 用户名,唯一, 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + // Required: true + UserName *string `json:"userName"` +} + +// Validate validates this create user request +func (m *CreateUserRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validatePassword(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRoleID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreateUserRequest) validatePassword(formats strfmt.Registry) error { + + if err := validate.Required("password", "body", m.Password); err != nil { + return err + } + + return nil +} + +func (m *CreateUserRequest) validateRoleID(formats strfmt.Registry) error { + + if err := validate.Required("roleId", "body", m.RoleID); err != nil { + return err + } + + return nil +} + +func (m *CreateUserRequest) validateUserName(formats strfmt.Registry) error { + + if err := validate.Required("userName", "body", m.UserName); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this create user request based on context it is used +func (m *CreateUserRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CreateUserRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreateUserRequest) UnmarshalBinary(b []byte) error { + var res CreateUserRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/delete_device_type_raid_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/delete_device_type_raid_request.go new file mode 100644 index 0000000..f5ca7fc --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/delete_device_type_raid_request.go @@ -0,0 +1,59 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeleteDeviceTypeRaidRequest delete device type raid request +// +// swagger:model DeleteDeviceTypeRaidRequest +type DeleteDeviceTypeRaidRequest struct { + + // device type + DeviceType string `json:"deviceType,omitempty"` + + // raid Id + RaidID string `json:"raidId,omitempty"` + + // volume detail + VolumeDetail string `json:"volumeDetail,omitempty"` + + // volume type + VolumeType string `json:"volumeType,omitempty"` +} + +// Validate validates this delete device type raid request +func (m *DeleteDeviceTypeRaidRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this delete device type raid request based on context it is used +func (m *DeleteDeviceTypeRaidRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeleteDeviceTypeRaidRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeleteDeviceTypeRaidRequest) UnmarshalBinary(b []byte) error { + var res DeleteDeviceTypeRaidRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/delete_instances_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/delete_instances_request.go new file mode 100644 index 0000000..c95504b --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/delete_instances_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeleteInstancesRequest 批量删除实例 +// +// swagger:model DeleteInstancesRequest +type DeleteInstancesRequest struct { + + // 实例id列表 + InstanceIDs []string `json:"instance_ids"` +} + +// Validate validates this delete instances request +func (m *DeleteInstancesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this delete instances request based on context it is used +func (m *DeleteInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeleteInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeleteInstancesRequest) UnmarshalBinary(b []byte) error { + var res DeleteInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device.go new file mode 100644 index 0000000..2779346 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device.go @@ -0,0 +1,344 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Device device +// +// swagger:model Device +type Device struct { + + // adapter_id + AdapterID int64 `json:"adapterId,omitempty"` + + // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Architecture string `json:"architecture,omitempty"` + + // 品牌 + Brand string `json:"brand,omitempty"` + + // cpu数量 + CPUAmount int64 `json:"cpuAmount,omitempty"` + + // 单个cpu内核数 + CPUCores int64 `json:"cpuCores,omitempty"` + + // cpu频率(G) + CPUFrequency string `json:"cpuFrequency,omitempty"` + + // cpu厂商 + CPUManufacturer string `json:"cpuManufacturer,omitempty"` + + // cpu处理器型号 + CPUModel string `json:"cpuModel,omitempty"` + + // 单个cpu路数 + CPURoads int8 `json:"cpuRoads,omitempty"` + + // 机柜编码 + Cabinet string `json:"cabinet,omitempty"` + + // 拼装信息 + CPUInfo string `json:"cpuInfo,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 数据盘数量 + DataVolumeAmount int64 `json:"dataVolumeAmount,omitempty"` + + // 数据盘接口类型(SATA,SAS,NVME) + DataVolumeInterfaceType string `json:"dataVolumeInterfaceType,omitempty"` + + // 数据盘单盘大小 + DataVolumeSize int64 `json:"dataVolumeSize,omitempty"` + + // 数据盘类型(SSD,HDD) + DataVolumeType string `json:"dataVolumeType,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 设备uuid + DeviceID string `json:"deviceId,omitempty"` + + // 计算型,存储型 + DeviceSeries string `json:"deviceSeries,omitempty"` + + // 计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName,omitempty"` + + // 型号,机型规格cps.normal + DeviceType string `json:"deviceType,omitempty"` + + // 机型uuid + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // 机型名称 + DeviceTypeName string `json:"deviceTypeName,omitempty"` + + // dv info + DvInfo string `json:"dvInfo,omitempty"` + + // 添加到disk表, 系统盘1背板号 + Enclosure1 string `json:"enclosure1,omitempty"` + + // 系统盘2背板号 + Enclosure2 string `json:"Enclosure2,omitempty"` + + // ETH1子网掩码 + Eth1Mask string `json:"eth1Mask,omitempty"` + + // 网关地址 + Gateway string `json:"gateway,omitempty"` + + // gpu数量 + GpuAmount int64 `json:"gpuAmount,omitempty"` + + // gpu info + GpuInfo string `json:"gpuInfo,omitempty"` + + // gpu厂商 + GpuManufacturer string `json:"gpuManufacturer,omitempty"` + + // gpu处理器型号 + GpuModel string `json:"gpuModel,omitempty"` + + // 设备ID编号 + ID int64 `json:"id,omitempty"` + + // idcname + IDcNameEn string `json:"idcNameEn,omitempty"` + + // 机房uuid + // Required: true + IdcID *string `json:"idcId"` + + // 机房名称 + IdcName string `json:"idcName,omitempty"` + + // 带外管理IP + IloIP string `json:"iloIp,omitempty"` + + // 带外账号密码 + IloPassword string `json:"iloPassword,omitempty"` + + // 带外账号 + IloUser string `json:"iloUser,omitempty"` + + // 实例镜像名称 + ImageName string `json:"imageName,omitempty"` + + // 实例创建时间 + InstanceCreatedTime string `json:"instanceCreatedTime,omitempty"` + + // 实例描述 + InstanceDescription string `json:"instanceDescription,omitempty"` + + // 实例id + InstanceID string `json:"instanceId,omitempty"` + + // 实例名称 + InstanceName string `json:"instanceName,omitempty"` + + // 实例失败原因 + InstanceReason string `json:"instanceReason,omitempty"` + + // 实例状态 + InstanceStatus string `json:"instanceStatus,omitempty"` + + // 实例状态 + InstanceStatusName string `json:"instanceStatusName,omitempty"` + + // 【网口模式】【网络设置】: bond单网口,dual双网口 + InterfaceMode string `json:"interfaceMode,omitempty"` + + // 实例是否锁定 锁定locked 未锁定unlocked + Locked string `json:"locked,omitempty"` + + // MAC1(eth0) + Mac1 string `json:"mac1,omitempty"` + + // MAC2(eth2) + Mac2 string `json:"mac2,omitempty"` + + // 设备状态: 未装机,已装机 + ManageStatus string `json:"manageStatus,omitempty"` + + // 设备状态: 未装机,已装机 + ManageStatusName string `json:"manageStatusName,omitempty"` + + // 子网掩码 + Mask string `json:"mask,omitempty"` + + // 内存数量 + MemAmount int64 `json:"memAmount,omitempty"` + + // 内存主频(MHz) + MemFrequency int64 `json:"memFrequency,omitempty"` + + // mem info + MemInfo string `json:"memInfo,omitempty"` + + // 单个内存大小(GB) + MemSize int64 `json:"memSize,omitempty"` + + // 内存接口(如DDR3,DDR4) + MemType string `json:"memType,omitempty"` + + // 型号 + Model string `json:"model,omitempty"` + + // 网卡数量 + NicAmount int64 `json:"nicAmount,omitempty"` + + // nic info + NicInfo string `json:"nicInfo,omitempty"` + + // 网卡传输速率(GE) + NicRate int64 `json:"nicRate,omitempty"` + + // eth1内网IPV4 + PrivateEth1IPV4 string `json:"privateEth1Ipv4,omitempty"` + + // eth1内网IPV6 + PrivateEth1IPV6 string `json:"privateEth1Ipv6,omitempty"` + + // 内网IPV4 + PrivateIPV4 string `json:"privateIpv4,omitempty"` + + // 内网IPV6 + PrivateIPV6 string `json:"privateIpv6,omitempty"` + + // raid工具:(megacli64等) + RaidDriver string `json:"raidDriver,omitempty"` + + // 设备状态变更失败原因 + Reason string `json:"reason,omitempty"` + + // 系统盘1槽位 + Slot1 int64 `json:"slot1,omitempty"` + + // 系统盘2槽位 + Slot2 int64 `json:"slot2,omitempty"` + + // 设备SN + Sn string `json:"sn,omitempty"` + + // sv info + SvInfo string `json:"svInfo,omitempty"` + + // 网口交换机IP + SwitchIP string `json:"switchIp,omitempty"` + + // 交换机1ip + SwitchIP1 string `json:"switchIp1,omitempty"` + + // 交换机2ip + SwitchIP2 string `json:"switchIp2,omitempty"` + + // 交换机1登录密码 + SwitchPassword1 string `json:"switchPassword1,omitempty"` + + // 交换机2登录密码 + SwitchPassword2 string `json:"switchPassword2,omitempty"` + + // 交换机1port + SwitchPort1 string `json:"switchPort1,omitempty"` + + // 交换机2port + SwitchPort2 string `json:"switchPort2,omitempty"` + + // 交换机1登录账号,如果为空,取所在机房的值 + SwitchUser1 string `json:"switchUser1,omitempty"` + + // 交换机2登录账号,如果为空,取所在机房的值 + SwitchUser2 string `json:"switchUser2,omitempty"` + + // 系统盘数量 + SystemVolumeAmount int64 `json:"systemVolumeAmount,omitempty"` + + // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeInterfaceType string `json:"systemVolumeInterfaceType,omitempty"` + + // 系统盘单盘大小 + SystemVolumeSize int64 `json:"systemVolumeSize,omitempty"` + + // 系统盘类型(SSD,HDD) + SystemVolumeType string `json:"systemVolumeType,omitempty"` + + // U位 + UPosition string `json:"uPosition,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 实例归属用户uuid + UserID string `json:"userId,omitempty"` + + // 实例归属用户名称 + UserName string `json:"userName,omitempty"` +} + +// Validate validates this device +func (m *Device) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateIdcID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Device) validateIdcID(formats strfmt.Registry) error { + + if err := validate.Required("idcId", "body", m.IdcID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this device based on context it is used +func (m *Device) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Device) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Device) UnmarshalBinary(b []byte) error { + var res Device + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_info.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_info.go new file mode 100644 index 0000000..a70a4e4 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceInfo device info +// +// swagger:model DeviceInfo +type DeviceInfo struct { + + // device + Device *Device `json:"device,omitempty"` +} + +// Validate validates this device info +func (m *DeviceInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDevice(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceInfo) validateDevice(formats strfmt.Registry) error { + if swag.IsZero(m.Device) { // not required + return nil + } + + if m.Device != nil { + if err := m.Device.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("device") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("device") + } + return err + } + } + + return nil +} + +// ContextValidate validate this device info based on the context it is used +func (m *DeviceInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDevice(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceInfo) contextValidateDevice(ctx context.Context, formats strfmt.Registry) error { + + if m.Device != nil { + if err := m.Device.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("device") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("device") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceInfo) UnmarshalBinary(b []byte) error { + var res DeviceInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_list.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_list.go new file mode 100644 index 0000000..0f58c64 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceList device list +// +// swagger:model DeviceList +type DeviceList struct { + + // 设备列表 + Devices []*Device `json:"devices"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this device list +func (m *DeviceList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDevices(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceList) validateDevices(formats strfmt.Registry) error { + if swag.IsZero(m.Devices) { // not required + return nil + } + + for i := 0; i < len(m.Devices); i++ { + if swag.IsZero(m.Devices[i]) { // not required + continue + } + + if m.Devices[i] != nil { + if err := m.Devices[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("devices" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("devices" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this device list based on the context it is used +func (m *DeviceList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDevices(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceList) contextValidateDevices(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Devices); i++ { + + if m.Devices[i] != nil { + if err := m.Devices[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("devices" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("devices" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceList) UnmarshalBinary(b []byte) error { + var res DeviceList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_stock.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_stock.go new file mode 100644 index 0000000..5ad0cb9 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_stock.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceStock device stock +// +// swagger:model DeviceStock +type DeviceStock struct { + + // 库存量 + Stocks int64 `json:"stocks,omitempty"` +} + +// Validate validates this device stock +func (m *DeviceStock) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this device stock based on context it is used +func (m *DeviceStock) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceStock) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceStock) UnmarshalBinary(b []byte) error { + var res DeviceStock + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_type.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_type.go new file mode 100644 index 0000000..1c466fa --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_type.go @@ -0,0 +1,215 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceType device type +// +// swagger:model DeviceType +type DeviceType struct { + + // 体系架构,如i386/x86_64/ ARM64 (aarch64),默认 x86_64 + Architecture string `json:"architecture,omitempty"` + + // boot模式 + BootMode string `json:"boot_mode,omitempty"` + + // cpu数量 + CPUAmount int64 `json:"cpuAmount,omitempty"` + + // 单个cpu内核数 + CPUCores int64 `json:"cpuCores,omitempty"` + + // cpu频率(G) + CPUFrequency string `json:"cpuFrequency,omitempty"` + + // cpu厂商 + CPUManufacturer string `json:"cpuManufacturer,omitempty"` + + // cpu处理器型号 + CPUModel string `json:"cpuModel,omitempty"` + + // 拼装信息 + CPUInfo string `json:"cpuInfo,omitempty"` + + // CPU 规格,预置还是其它 + CPUSpec string `json:"cpuSpec,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 数据盘数量 + DataVolumeAmount int64 `json:"dataVolumeAmount,omitempty"` + + // 数据盘接口类型(SATA,SAS,NVME) + DataVolumeInterfaceType string `json:"dataVolumeInterfaceType,omitempty"` + + // 数据盘单盘大小 + DataVolumeSize int64 `json:"dataVolumeSize,omitempty"` + + // 数据盘类型(SSD,HDD) + DataVolumeType string `json:"dataVolumeType,omitempty"` + + // 数据盘单位(GB,TB) + DataVolumeUnit string `json:"dataVolumeUnit,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // device count + DeviceCount int64 `json:"deviceCount,omitempty"` + + // 机型类型,如计算型,存储型 + DeviceSeries string `json:"deviceSeries,omitempty"` + + // 机型类型,如计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName,omitempty"` + + // 机型规格, cps.c.normal + DeviceType string `json:"deviceType,omitempty"` + + // 机型uuid + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // dv info + DvInfo string `json:"dvInfo,omitempty"` + + // gpu数量 + GpuAmount int64 `json:"gpuAmount,omitempty"` + + // gpu info + GpuInfo string `json:"gpuInfo,omitempty"` + + // gpu厂商 + GpuManufacturer string `json:"gpuManufacturer,omitempty"` + + // gpu处理器型号 + GpuModel string `json:"gpuModel,omitempty"` + + // 显示机型高度 + Height int64 `json:"height,omitempty"` + + // ID + ID int64 `json:"id,omitempty"` + + // 机房uuid + IDcID string `json:"idcId,omitempty"` + + // 机房名称 + IDcName string `json:"idcName,omitempty"` + + // 机房名称 + IDcNameEn string `json:"idcNameEn,omitempty"` + + // instance count + InstanceCount int64 `json:"instanceCount,omitempty"` + + // instance status + InstanceStatus []string `json:"instanceStatus"` + + // bond单网口,dual双网口 + InterfaceMode string `json:"interfaceMode,omitempty"` + + // 内存数量 + MemAmount int64 `json:"memAmount,omitempty"` + + // 内存主频(MHz) + MemFrequency int64 `json:"memFrequency,omitempty"` + + // mem info + MemInfo string `json:"memInfo,omitempty"` + + // 单个内存大小(GB) + MemSize int64 `json:"memSize,omitempty"` + + // 内存 规格,预置还是其它 + MemSpec string `json:"memSpec,omitempty"` + + // 内存接口(如DDR3,DDR4) + MemType string `json:"memType,omitempty"` + + // 机型名称,如计算效能型,标准计算型 + Name string `json:"name,omitempty"` + + // 网卡数量 + NicAmount int64 `json:"nicAmount,omitempty"` + + // nic info + NicInfo string `json:"nicInfo,omitempty"` + + // 网卡传输速率(GE) + NicRate int64 `json:"nicRate,omitempty"` + + // 系统盘raid + Raid string `json:"raid,omitempty"` + + // 是否做raid,[RAID/NORAID] + RaidCan string `json:"raidCan,omitempty"` + + // StockAvailable 可用库存 + StockAvailable int64 `json:"stockAvailable,omitempty"` + + // sv info + SvInfo string `json:"svInfo,omitempty"` + + // 系统盘数量 + SystemVolumeAmount int64 `json:"systemVolumeAmount,omitempty"` + + // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeInterfaceType string `json:"systemVolumeInterfaceType,omitempty"` + + // 系统盘单盘大小 + SystemVolumeSize int64 `json:"systemVolumeSize,omitempty"` + + // 系统盘类型(SSD,HDD) + SystemVolumeType string `json:"systemVolumeType,omitempty"` + + // 系统盘单位(GB,TB) + SystemVolumeUnit string `json:"systemVolumeUnit,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` +} + +// Validate validates this device type +func (m *DeviceType) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this device type based on context it is used +func (m *DeviceType) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceType) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceType) UnmarshalBinary(b []byte) error { + var res DeviceType + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_type_id.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_type_id.go new file mode 100644 index 0000000..05dee3c --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_type_id.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DeviceTypeID device type Id +// +// swagger:model DeviceTypeId +type DeviceTypeID struct { + + // 机型uuid + // Required: true + DeviceTypeID *string `json:"deviceTypeId"` +} + +// Validate validates this device type Id +func (m *DeviceTypeID) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceTypeID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceTypeID) validateDeviceTypeID(formats strfmt.Registry) error { + + if err := validate.Required("deviceTypeId", "body", m.DeviceTypeID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this device type Id based on context it is used +func (m *DeviceTypeID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceTypeID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceTypeID) UnmarshalBinary(b []byte) error { + var res DeviceTypeID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_type_info.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_type_info.go new file mode 100644 index 0000000..382e25c --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_type_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceTypeInfo device type info +// +// swagger:model DeviceTypeInfo +type DeviceTypeInfo struct { + + // device type + DeviceType *DeviceType `json:"deviceType,omitempty"` +} + +// Validate validates this device type info +func (m *DeviceTypeInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceType(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceTypeInfo) validateDeviceType(formats strfmt.Registry) error { + if swag.IsZero(m.DeviceType) { // not required + return nil + } + + if m.DeviceType != nil { + if err := m.DeviceType.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceType") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceType") + } + return err + } + } + + return nil +} + +// ContextValidate validate this device type info based on the context it is used +func (m *DeviceTypeInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDeviceType(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceTypeInfo) contextValidateDeviceType(ctx context.Context, formats strfmt.Registry) error { + + if m.DeviceType != nil { + if err := m.DeviceType.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceType") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceType") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceTypeInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceTypeInfo) UnmarshalBinary(b []byte) error { + var res DeviceTypeInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_type_list.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_type_list.go new file mode 100644 index 0000000..8959ae5 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/device_type_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// DeviceTypeList device type list +// +// swagger:model DeviceTypeList +type DeviceTypeList struct { + + // 机型列表 + DeviceTypes []*DeviceType `json:"deviceTypes"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this device type list +func (m *DeviceTypeList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceTypes(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceTypeList) validateDeviceTypes(formats strfmt.Registry) error { + if swag.IsZero(m.DeviceTypes) { // not required + return nil + } + + for i := 0; i < len(m.DeviceTypes); i++ { + if swag.IsZero(m.DeviceTypes[i]) { // not required + continue + } + + if m.DeviceTypes[i] != nil { + if err := m.DeviceTypes[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceTypes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceTypes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this device type list based on the context it is used +func (m *DeviceTypeList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDeviceTypes(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DeviceTypeList) contextValidateDeviceTypes(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.DeviceTypes); i++ { + + if m.DeviceTypes[i] != nil { + if err := m.DeviceTypes[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("deviceTypes" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("deviceTypes" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *DeviceTypeList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DeviceTypeList) UnmarshalBinary(b []byte) error { + var res DeviceTypeList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/dissociated_image_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/dissociated_image_request.go new file mode 100644 index 0000000..c3a2d59 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/dissociated_image_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// DissociatedImageRequest dissociated image request +// +// swagger:model DissociatedImageRequest +type DissociatedImageRequest struct { + + // 设备类型id + // Required: true + DeviceTypeID *string `json:"deviceTypeId"` + + // 镜像ID + // Required: true + ImageID *string `json:"imageId"` +} + +// Validate validates this dissociated image request +func (m *DissociatedImageRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceTypeID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImageID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *DissociatedImageRequest) validateDeviceTypeID(formats strfmt.Registry) error { + + if err := validate.Required("deviceTypeId", "body", m.DeviceTypeID); err != nil { + return err + } + + return nil +} + +func (m *DissociatedImageRequest) validateImageID(formats strfmt.Registry) error { + + if err := validate.Required("imageId", "body", m.ImageID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this dissociated image request based on context it is used +func (m *DissociatedImageRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *DissociatedImageRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *DissociatedImageRequest) UnmarshalBinary(b []byte) error { + var res DissociatedImageRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/error_response.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/error_response.go new file mode 100644 index 0000000..e39f94b --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/error_response.go @@ -0,0 +1,56 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ErrorResponse error response +// +// swagger:model ErrorResponse +type ErrorResponse struct { + + // 错误码 + Code int64 `json:"code,omitempty"` + + // 错误信息 + Message string `json:"message,omitempty"` + + // 错误状态 + Status string `json:"status,omitempty"` +} + +// Validate validates this error response +func (m *ErrorResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this error response based on context it is used +func (m *ErrorResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ErrorResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ErrorResponse) UnmarshalBinary(b []byte) error { + var res ErrorResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/idc.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/idc.go new file mode 100644 index 0000000..bbe18a9 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/idc.go @@ -0,0 +1,98 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Idc idc +// +// swagger:model Idc +type Idc struct { + + // 机房地址 + Address string `json:"address,omitempty"` + + // 创建时间 + CreateTime string `json:"createTime,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // ID + ID int64 `json:"id,omitempty"` + + // 机房uuid + IDcID string `json:"idcId,omitempty"` + + // 机房公用带外管理password + IloPassword string `json:"iloPassword,omitempty"` + + // 机房公用带外管理user + IloUser string `json:"iloUser,omitempty"` + + // 机房等级 + Level string `json:"level,omitempty"` + + // 机房名称 + Name string `json:"name,omitempty"` + + // 机房名称en + NameEn string `json:"nameEn,omitempty"` + + // shortname + Shortname string `json:"shortname,omitempty"` + + // 交换机密码1 + SwitchPassword1 string `json:"switchPassword1,omitempty"` + + // 交换机密码2 + SwitchPassword2 string `json:"switchPassword2,omitempty"` + + // 交换机用户名1 + SwitchUser1 string `json:"switchUser1,omitempty"` + + // 交换机用户名2 + SwitchUser2 string `json:"switchUser2,omitempty"` + + // 修改时间 + UpdateTime string `json:"updateTime,omitempty"` + + // 修改用户 + UpdatedBy string `json:"updatedBy,omitempty"` +} + +// Validate validates this idc +func (m *Idc) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this idc based on context it is used +func (m *Idc) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Idc) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Idc) UnmarshalBinary(b []byte) error { + var res Idc + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/idc_id.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/idc_id.go new file mode 100644 index 0000000..3e7f724 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/idc_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// IdcID idc ID +// +// swagger:model IdcID +type IdcID struct { + + // 机房id + IdcID string `json:"idcId,omitempty"` +} + +// Validate validates this idc ID +func (m *IdcID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this idc ID based on context it is used +func (m *IdcID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *IdcID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *IdcID) UnmarshalBinary(b []byte) error { + var res IdcID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/idc_info.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/idc_info.go new file mode 100644 index 0000000..8ca49a0 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/idc_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// IdcInfo idc info +// +// swagger:model IdcInfo +type IdcInfo struct { + + // idc + Idc *Idc `json:"idc,omitempty"` +} + +// Validate validates this idc info +func (m *IdcInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateIdc(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *IdcInfo) validateIdc(formats strfmt.Registry) error { + if swag.IsZero(m.Idc) { // not required + return nil + } + + if m.Idc != nil { + if err := m.Idc.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("idc") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("idc") + } + return err + } + } + + return nil +} + +// ContextValidate validate this idc info based on the context it is used +func (m *IdcInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateIdc(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *IdcInfo) contextValidateIdc(ctx context.Context, formats strfmt.Registry) error { + + if m.Idc != nil { + if err := m.Idc.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("idc") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("idc") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *IdcInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *IdcInfo) UnmarshalBinary(b []byte) error { + var res IdcInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/idc_list.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/idc_list.go new file mode 100644 index 0000000..3cb1fe4 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/idc_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// IdcList idc list +// +// swagger:model IdcList +type IdcList struct { + + // 机房列表 + Idcs []*Idc `json:"idcs"` + + // 页数 + PageNumber int64 `json:"pageNumber,omitempty"` + + // 页大小 + PageSize int64 `json:"pageSize,omitempty"` + + // 总条数 + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this idc list +func (m *IdcList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateIdcs(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *IdcList) validateIdcs(formats strfmt.Registry) error { + if swag.IsZero(m.Idcs) { // not required + return nil + } + + for i := 0; i < len(m.Idcs); i++ { + if swag.IsZero(m.Idcs[i]) { // not required + continue + } + + if m.Idcs[i] != nil { + if err := m.Idcs[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("idcs" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("idcs" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this idc list based on the context it is used +func (m *IdcList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateIdcs(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *IdcList) contextValidateIdcs(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Idcs); i++ { + + if m.Idcs[i] != nil { + if err := m.Idcs[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("idcs" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("idcs" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *IdcList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *IdcList) UnmarshalBinary(b []byte) error { + var res IdcList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/image.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/image.go new file mode 100644 index 0000000..fee3c1f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/image.go @@ -0,0 +1,119 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Image image +// +// swagger:model Image +type Image struct { + + // 架构:x86/x64/i386/ + Architecture string `json:"architecture,omitempty"` + + // boot模式 + BootMode string `json:"bootMode,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 数据分区信息 + DataPartition string `json:"dataPartition,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 绑定了机型数量 + DeviceTypeNum int64 `json:"deviceTypeNum,omitempty"` + + // 镜像文件名称 + Filename string `json:"filename,omitempty"` + + // 镜像格式(qcow2、tar) + Format string `json:"format,omitempty"` + + // 镜像校验码 + Hash string `json:"hash,omitempty"` + + // ID + ID uint64 `json:"id,omitempty"` + + // 镜像uuid + ImageID string `json:"imageId,omitempty"` + + // 镜像名称 + ImageName string `json:"imageName,omitempty"` + + // 是否绑定了某个机型 + IsBind bool `json:"isBind,omitempty"` + + // 源os uuid + OsID string `json:"osId,omitempty"` + + // CentOS 7.2 64-bit + OsName string `json:"osName,omitempty"` + + // 操作系统分类:linux/windows + OsType string `json:"osType,omitempty"` + + // 操作系统版本 + OsVersion string `json:"osVersion,omitempty"` + + // 镜像来源(common通用、customize定制、user_defined自定义) + Source string `json:"source,omitempty"` + + // 镜像来源(common通用、customize定制、user_defined自定义) + SourceName string `json:"sourceName,omitempty"` + + // 系统分区信息(系统盘:“/ ” :50GiB,xfs;swap:10GiB,swap) + SystemPartition string `json:"systemPartition,omitempty"` + + // 镜像源路径 + URL string `json:"url,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` +} + +// Validate validates this image +func (m *Image) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this image based on context it is used +func (m *Image) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Image) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Image) UnmarshalBinary(b []byte) error { + var res Image + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/image_id.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/image_id.go new file mode 100644 index 0000000..0d8e965 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/image_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ImageID image Id +// +// swagger:model ImageId +type ImageID struct { + + // 镜像uuid + ImageID string `json:"imageId,omitempty"` +} + +// Validate validates this image Id +func (m *ImageID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this image Id based on context it is used +func (m *ImageID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ImageID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ImageID) UnmarshalBinary(b []byte) error { + var res ImageID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/image_info.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/image_info.go new file mode 100644 index 0000000..7064fb8 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/image_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ImageInfo image info +// +// swagger:model ImageInfo +type ImageInfo struct { + + // image + Image *Image `json:"image,omitempty"` +} + +// Validate validates this image info +func (m *ImageInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateImage(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ImageInfo) validateImage(formats strfmt.Registry) error { + if swag.IsZero(m.Image) { // not required + return nil + } + + if m.Image != nil { + if err := m.Image.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("image") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("image") + } + return err + } + } + + return nil +} + +// ContextValidate validate this image info based on the context it is used +func (m *ImageInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateImage(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ImageInfo) contextValidateImage(ctx context.Context, formats strfmt.Registry) error { + + if m.Image != nil { + if err := m.Image.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("image") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("image") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ImageInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ImageInfo) UnmarshalBinary(b []byte) error { + var res ImageInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/image_list.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/image_list.go new file mode 100644 index 0000000..61ce37d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/image_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ImageList image list +// +// swagger:model ImageList +type ImageList struct { + + // 镜像实体列表 + Images []*Image `json:"images"` + + // 页数 + PageNumber int64 `json:"pageNumber,omitempty"` + + // 页大小 + PageSize int64 `json:"pageSize,omitempty"` + + // 总条数 + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this image list +func (m *ImageList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateImages(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ImageList) validateImages(formats strfmt.Registry) error { + if swag.IsZero(m.Images) { // not required + return nil + } + + for i := 0; i < len(m.Images); i++ { + if swag.IsZero(m.Images[i]) { // not required + continue + } + + if m.Images[i] != nil { + if err := m.Images[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("images" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("images" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this image list based on the context it is used +func (m *ImageList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateImages(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ImageList) contextValidateImages(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Images); i++ { + + if m.Images[i] != nil { + if err := m.Images[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("images" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("images" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ImageList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ImageList) UnmarshalBinary(b []byte) error { + var res ImageList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/instance.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/instance.go new file mode 100644 index 0000000..9d0d2b8 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/instance.go @@ -0,0 +1,224 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Instance instance +// +// swagger:model Instance +type Instance struct { + + // cpu数量 + CPUAmount int64 `json:"cpuAmount,omitempty"` + + // 单个cpu内核数 + CPUCores int64 `json:"cpuCores,omitempty"` + + // cpu频率(GHz) + CPUFrequency string `json:"cpuFrequency,omitempty"` + + // cpu厂商 + CPUManufacturer string `json:"cpuManufacturer,omitempty"` + + // cpu处理器型号 + CPUModel string `json:"cpuModel,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 数据盘数量 + DataVolumeAmount int64 `json:"dataVolumeAmount,omitempty"` + + // 数据盘接口类型(SATA,SAS,NVME) + DataVolumeInterfaceType string `json:"dataVolumeInterfaceType,omitempty"` + + // 数据盘raidId + DataVolumeRaidID string `json:"dataVolumeRaidId,omitempty"` + + // 数据盘raid名称 + DataVolumeRaidName string `json:"DataVolumeRaidName,omitempty"` + + // 数据盘单盘大小 + DataVolumeSize int64 `json:"dataVolumeSize,omitempty"` + + // 数据盘类型(SSD,HDD) + DataVolumeType string `json:"dataVolumeType,omitempty"` + + // 系统盘单位 + DataVolumeUnit string `json:"dataVolumeUnit,omitempty"` + + // 实例描述 + Description string `json:"description,omitempty"` + + // 设备uuid + DeviceID string `json:"deviceId,omitempty"` + + // 机型类型,如computer + DeviceSeries string `json:"deviceSeries,omitempty"` + + // 机型类型,如计算型,存储型 + DeviceSeriesName string `json:"deviceSeriesName,omitempty"` + + // 机型规格, cps.c.normal + DeviceType string `json:"deviceType,omitempty"` + + // 机型uuid + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // 机型名称,如计算效能型,标准计算型 + DeviceTypeName string `json:"deviceTypeName,omitempty"` + + // gpu数量 + GpuAmount int64 `json:"gpuAmount,omitempty"` + + // gpu厂商 + GpuManufacturer string `json:"gpuManufacturer,omitempty"` + + // gpu处理器型号 + GpuModel string `json:"gpuModel,omitempty"` + + // 主机名 + Hostname string `json:"hostname,omitempty"` + + // 机房uuid + IDcID string `json:"idcId,omitempty"` + + // 机房名称 + IdcName string `json:"idcName,omitempty"` + + // 带外管理IP + IloIP string `json:"iloIp,omitempty"` + + // 镜像uuid + ImageID string `json:"imageId,omitempty"` + + // 镜像名称 + ImageName string `json:"imageName,omitempty"` + + // 实例uuid + InstanceID string `json:"instanceId,omitempty"` + + // 实例名称 + InstanceName string `json:"instanceName,omitempty"` + + // 【网口模式】【网络设置】: bond单网口,dual双网口 + InterfaceMode string `json:"interfaceMode,omitempty"` + + // 是否锁定解锁锁定:locked,解锁unlocked + Locked string `json:"locked,omitempty"` + + // 是否锁定解锁锁定:已解锁,已锁定 + LockedName string `json:"lockedName,omitempty"` + + // 内存数量 + MemAmount int64 `json:"memAmount,omitempty"` + + // 内存主频(MHz) + MemFrequency int64 `json:"memFrequency,omitempty"` + + // 单个内存大小(GB) + MemSize int64 `json:"memSize,omitempty"` + + // 内存接口(如DDR3,DDR4) + MemType string `json:"memType,omitempty"` + + // 网卡数量 + NicAmount int64 `json:"nicAmount,omitempty"` + + // 网卡传输速率(GE) + NicRate int64 `json:"nicRate,omitempty"` + + // 内网IPV4 + PrivateIPV4 string `json:"privateIpv4,omitempty"` + + // 内网IPV6 + PrivateIPV6 string `json:"privateIpv6,omitempty"` + + // 实例所属项目UUID + ProjectID string `json:"projectId,omitempty"` + + // 系统盘raid配置 + RaidCan string `json:"raidCan,omitempty"` + + // 实例错误状态时的错误原因 + Reason string `json:"reason,omitempty"` + + // 设备SN + Sn string `json:"sn,omitempty"` + + // 运行状态 + Status string `json:"status,omitempty"` + + // 运行状态中文名字 + StatusName string `json:"statusName,omitempty"` + + // 系统盘数量 + SystemVolumeAmount int64 `json:"systemVolumeAmount,omitempty"` + + // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeInterfaceType string `json:"systemVolumeInterfaceType,omitempty"` + + // 系统盘raidId + SystemVolumeRaidID string `json:"systemVolumeRaidId,omitempty"` + + // 系统盘raid名称 + SystemVolumeRaidName string `json:"systemVolumeRaidName,omitempty"` + + // 系统盘单盘大小 + SystemVolumeSize int64 `json:"systemVolumeSize,omitempty"` + + // 系统盘类型(SSD,HDD) + SystemVolumeType string `json:"systemVolumeType,omitempty"` + + // 系统盘单位 + SystemVolumeUnit string `json:"systemVolumeUnit,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 实例所属用户UUID + UserID string `json:"userId,omitempty"` +} + +// Validate validates this instance +func (m *Instance) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this instance based on context it is used +func (m *Instance) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Instance) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Instance) UnmarshalBinary(b []byte) error { + var res Instance + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/instance_ids.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/instance_ids.go new file mode 100644 index 0000000..1120ae1 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/instance_ids.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstanceIds instance ids +// +// swagger:model InstanceIds +type InstanceIds struct { + + // instanceId 列表 + InstanceIds []string `json:"instanceIds"` +} + +// Validate validates this instance ids +func (m *InstanceIds) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this instance ids based on context it is used +func (m *InstanceIds) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *InstanceIds) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstanceIds) UnmarshalBinary(b []byte) error { + var res InstanceIds + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/instance_info.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/instance_info.go new file mode 100644 index 0000000..abf1a71 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/instance_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstanceInfo instance info +// +// swagger:model InstanceInfo +type InstanceInfo struct { + + // instance + Instance *Instance `json:"instance,omitempty"` +} + +// Validate validates this instance info +func (m *InstanceInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstance(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceInfo) validateInstance(formats strfmt.Registry) error { + if swag.IsZero(m.Instance) { // not required + return nil + } + + if m.Instance != nil { + if err := m.Instance.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instance") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instance") + } + return err + } + } + + return nil +} + +// ContextValidate validate this instance info based on the context it is used +func (m *InstanceInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateInstance(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceInfo) contextValidateInstance(ctx context.Context, formats strfmt.Registry) error { + + if m.Instance != nil { + if err := m.Instance.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instance") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instance") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *InstanceInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstanceInfo) UnmarshalBinary(b []byte) error { + var res InstanceInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/instance_list.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/instance_list.go new file mode 100644 index 0000000..1cdd579 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/instance_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstanceList instance list +// +// swagger:model InstanceList +type InstanceList struct { + + // instance实体数组 + Instances []*Instance `json:"instances"` + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this instance list +func (m *InstanceList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInstances(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceList) validateInstances(formats strfmt.Registry) error { + if swag.IsZero(m.Instances) { // not required + return nil + } + + for i := 0; i < len(m.Instances); i++ { + if swag.IsZero(m.Instances[i]) { // not required + continue + } + + if m.Instances[i] != nil { + if err := m.Instances[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this instance list based on the context it is used +func (m *InstanceList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateInstances(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *InstanceList) contextValidateInstances(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Instances); i++ { + + if m.Instances[i] != nil { + if err := m.Instances[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("instances" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("instances" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *InstanceList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstanceList) UnmarshalBinary(b []byte) error { + var res InstanceList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/instances_sshkey_info_response.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/instances_sshkey_info_response.go new file mode 100644 index 0000000..e0acfb3 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/instances_sshkey_info_response.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// InstancesSshkeyInfoResponse instances sshkey info response +// +// swagger:model InstancesSshkeyInfoResponse +type InstancesSshkeyInfoResponse struct { + + // 实例Id列表 + InstanceIds []string `json:"instanceIds"` +} + +// Validate validates this instances sshkey info response +func (m *InstancesSshkeyInfoResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this instances sshkey info response based on context it is used +func (m *InstancesSshkeyInfoResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *InstancesSshkeyInfoResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InstancesSshkeyInfoResponse) UnmarshalBinary(b []byte) error { + var res InstancesSshkeyInfoResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/license_content.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/license_content.go new file mode 100644 index 0000000..3abcc96 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/license_content.go @@ -0,0 +1,143 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// LicenseContent license content +// +// swagger:model LicenseContent +type LicenseContent struct { + + // end time + EndTime int64 `json:"end_time,omitempty"` + + // hard ware + HardWare string `json:"hardwareinfo,omitempty"` + + // license name + LicenseName string `json:"license_name,omitempty"` + + // license type + LicenseType string `json:"license_type,omitempty"` + + // model list + ModelList []*ModuleItem `json:"modelList"` + + // models + Models []string `json:"models"` + + // nodes num + NodesNum int64 `json:"nodes_num,omitempty"` + + // start time + StartTime int64 `json:"start_time,omitempty"` + + // used nodes num + UsedNodesNum int64 `json:"used_nodes_num,omitempty"` + + // version + Version string `json:"version,omitempty"` +} + +// Validate validates this license content +func (m *LicenseContent) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateModelList(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *LicenseContent) validateModelList(formats strfmt.Registry) error { + if swag.IsZero(m.ModelList) { // not required + return nil + } + + for i := 0; i < len(m.ModelList); i++ { + if swag.IsZero(m.ModelList[i]) { // not required + continue + } + + if m.ModelList[i] != nil { + if err := m.ModelList[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modelList" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modelList" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this license content based on the context it is used +func (m *LicenseContent) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateModelList(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *LicenseContent) contextValidateModelList(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.ModelList); i++ { + + if m.ModelList[i] != nil { + if err := m.ModelList[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("modelList" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("modelList" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *LicenseContent) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *LicenseContent) UnmarshalBinary(b []byte) error { + var res LicenseContent + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/license_token.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/license_token.go new file mode 100644 index 0000000..f28c85f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/license_token.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// LicenseToken license token +// +// swagger:model LicenseToken +type LicenseToken struct { + + // msg + Msg string `json:"msg,omitempty"` +} + +// Validate validates this license token +func (m *LicenseToken) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this license token based on context it is used +func (m *LicenseToken) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *LicenseToken) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *LicenseToken) UnmarshalBinary(b []byte) error { + var res LicenseToken + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_apikey_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_apikey_request.go new file mode 100644 index 0000000..8a852b2 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_apikey_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ModifyApikeyRequest modify apikey request +// +// swagger:model ModifyApikeyRequest +type ModifyApikeyRequest struct { + + // 秘钥对名称 + // Required: true + Name *string `json:"name"` + + // 是否支持只读,[0/1], read_only=1 的时候说明这个key是只读key,不能访问写方法 + // Required: true + ReadOnly *int8 `json:"readOnly"` +} + +// Validate validates this modify apikey request +func (m *ModifyApikeyRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateReadOnly(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ModifyApikeyRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +func (m *ModifyApikeyRequest) validateReadOnly(formats strfmt.Registry) error { + + if err := validate.Required("readOnly", "body", m.ReadOnly); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this modify apikey request based on context it is used +func (m *ModifyApikeyRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyApikeyRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyApikeyRequest) UnmarshalBinary(b []byte) error { + var res ModifyApikeyRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_device_type_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_device_type_request.go new file mode 100644 index 0000000..0fa1cd3 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_device_type_request.go @@ -0,0 +1,158 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyDeviceTypeRequest modify device type request +// +// swagger:model ModifyDeviceTypeRequest +type ModifyDeviceTypeRequest struct { + + // 体系架构,如i386/x86_64/ ARM64(aarch64),默认 x86_64 + Architecture *string `json:"architecture,omitempty"` + + // boot模式【UEFI Legacy/BIOS】支持多选,逗号分隔 + BootMode string `json:"boot_mode,omitempty"` + + // cpu数量 + CPUAmount *int64 `json:"cpuAmount,omitempty"` + + // 单个cpu内核数 + CPUCores *int64 `json:"cpuCores,omitempty"` + + // cpu频率(G) + CPUFrequency *string `json:"cpuFrequency,omitempty"` + + // cpu厂商 + CPUManufacturer *string `json:"cpuManufacturer,omitempty"` + + // cpu处理器型号 + CPUModel *string `json:"cpuModel,omitempty"` + + // CPU 预置规格 + CPUSpec *string `json:"cpuSpec,omitempty"` + + // 数据盘数量 + DataVolumeAmount *int64 `json:"dataVolumeAmount,omitempty"` + + // 数据盘接口类型 + DataVolumeInterfaceType *string `json:"dataVolumeInterfaceType,omitempty"` + + // 数据盘单盘大小 + DataVolumeSize *int64 `json:"dataVolumeSize,omitempty"` + + // 数据盘类型 + DataVolumeType *string `json:"dataVolumeType,omitempty"` + + // 数据盘单盘大小单位 + DataVolumeUnit *string `json:"dataVolumeUnit,omitempty"` + + // 描述 + Description *string `json:"description,omitempty"` + + // 机型类型,如计算型,存储型 + DeviceSeries *string `json:"deviceSeries,omitempty"` + + // 机型规格 + DeviceType *string `json:"deviceType,omitempty"` + + // gpu数量 + GpuAmount *int64 `json:"gpuAmount,omitempty"` + + // gpu厂商 + GpuManufacturer *string `json:"gpuManufacturer,omitempty"` + + // gpu处理器型号 + GpuModel *string `json:"gpuModel,omitempty"` + + // 【高度(U)】:显示机型高度 + Height *int64 `json:"height,omitempty"` + + // 机房id + IDcID *string `json:"idcId,omitempty"` + + // 【网口模式】【网络设置】: 单网口,双网口bond,single + InterfaceMode *string `json:"interfaceMode,omitempty"` + + // 内存数量 + MemAmount *int64 `json:"memAmount,omitempty"` + + // 内存主频(MHz) + MemFrequency *int64 `json:"memFrequency,omitempty"` + + // 单个内存大小(GB) + MemSize *int64 `json:"memSize,omitempty"` + + // 内存 预置规格 + MemSpec *string `json:"memSpec,omitempty"` + + // 内存接口(如DDR3,DDR4) + MemType *string `json:"memType,omitempty"` + + // 机型名称 + Name *string `json:"name,omitempty"` + + // 网卡数量 + NicAmount *int64 `json:"nicAmount,omitempty"` + + // 网卡传输速率(GE) + NicRate *int64 `json:"nicRate,omitempty"` + + // 是否做raid,[RAID/NORAID] + RaidCan *string `json:"raidCan,omitempty"` + + // 系统盘raid,支持多选,英文逗号分隔 + RaidID *string `json:"raidId,omitempty"` + + // 系统盘数量 + SystemVolumeAmount *int64 `json:"systemVolumeAmount,omitempty"` + + // 系统盘接口类型(SATA,SAS,NVME) + SystemVolumeInterfaceType *string `json:"systemVolumeInterfaceType,omitempty"` + + // 系统盘单盘大小 + SystemVolumeSize *int64 `json:"systemVolumeSize,omitempty"` + + // 系统盘类型(SSD,HDD) + SystemVolumeType *string `json:"systemVolumeType,omitempty"` + + // 系统盘单盘大小单位 + SystemVolumeUnit *string `json:"systemVolumeUnit,omitempty"` +} + +// Validate validates this modify device type request +func (m *ModifyDeviceTypeRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify device type request based on context it is used +func (m *ModifyDeviceTypeRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyDeviceTypeRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyDeviceTypeRequest) UnmarshalBinary(b []byte) error { + var res ModifyDeviceTypeRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_devices_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_devices_request.go new file mode 100644 index 0000000..ca01a4b --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_devices_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyDevicesRequest modify devices request +// +// swagger:model ModifyDevicesRequest +type ModifyDevicesRequest struct { + + // 修改设备描述 + Description *string `json:"description,omitempty"` +} + +// Validate validates this modify devices request +func (m *ModifyDevicesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify devices request based on context it is used +func (m *ModifyDevicesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyDevicesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyDevicesRequest) UnmarshalBinary(b []byte) error { + var res ModifyDevicesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_idc_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_idc_request.go new file mode 100644 index 0000000..b490bdd --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_idc_request.go @@ -0,0 +1,80 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyIdcRequest modify idc request +// +// swagger:model ModifyIdcRequest +type ModifyIdcRequest struct { + + // 机房地址 0-256 + Address *string `json:"address,omitempty"` + + // 带外密码 0-64 + IloPassword *string `json:"iloPassword,omitempty"` + + // 带外用户名 0-64 + IloUser *string `json:"iloUser,omitempty"` + + // 机房等级 1-64 + Level *string `json:"level,omitempty"` + + // 机房名称 1-64 + Name *string `json:"name,omitempty"` + + // 机房英文名称 1-64 + NameEn *string `json:"nameEn,omitempty"` + + // 机房缩写 1-64 + Shortname *string `json:"shortname,omitempty"` + + // 交换机密码1 0-64 + SwitchPassword1 *string `json:"switchPassword1,omitempty"` + + // 交换机2密码 0-64 + SwitchPassword2 *string `json:"switchPassword2,omitempty"` + + // 交换机用户1 0-64 + SwitchUser1 *string `json:"switchUser1,omitempty"` + + // 交换机用户2 0-64 + SwitchUser2 *string `json:"switchUser2,omitempty"` +} + +// Validate validates this modify idc request +func (m *ModifyIdcRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify idc request based on context it is used +func (m *ModifyIdcRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyIdcRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyIdcRequest) UnmarshalBinary(b []byte) error { + var res ModifyIdcRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_image_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_image_request.go new file mode 100644 index 0000000..aa0c05a --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_image_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyImageRequest modify image request +// +// swagger:model ModifyImageRequest +type ModifyImageRequest struct { + + // 修改设备描述 + Description *string `json:"description,omitempty"` +} + +// Validate validates this modify image request +func (m *ModifyImageRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify image request based on context it is used +func (m *ModifyImageRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyImageRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyImageRequest) UnmarshalBinary(b []byte) error { + var res ModifyImageRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_instance_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_instance_request.go new file mode 100644 index 0000000..6cf9850 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_instance_request.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyInstanceRequest modify instance request +// +// swagger:model ModifyInstanceRequest +type ModifyInstanceRequest struct { + + // 描述 + Description *string `json:"description,omitempty"` + + // 实例名称 + InstanceName string `json:"instanceName,omitempty"` +} + +// Validate validates this modify instance request +func (m *ModifyInstanceRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify instance request based on context it is used +func (m *ModifyInstanceRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyInstanceRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyInstanceRequest) UnmarshalBinary(b []byte) error { + var res ModifyInstanceRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_instances_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_instances_request.go new file mode 100644 index 0000000..93be971 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_instances_request.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyInstancesRequest 批量修改实例名称 +// +// swagger:model ModifyInstancesRequest +type ModifyInstancesRequest struct { + + // 实例id列表 + InstanceIDs []string `json:"instance_ids"` + + // 实例名称 + InstanceName string `json:"instanceName,omitempty"` +} + +// Validate validates this modify instances request +func (m *ModifyInstancesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify instances request based on context it is used +func (m *ModifyInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyInstancesRequest) UnmarshalBinary(b []byte) error { + var res ModifyInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_local_user_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_local_user_request.go new file mode 100644 index 0000000..f08328d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_local_user_request.go @@ -0,0 +1,65 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyLocalUserRequest modify local user request +// +// swagger:model ModifyLocalUserRequest +type ModifyLocalUserRequest struct { + + // 用户默认项目uuid + DefaultProjectID *string `json:"defaultProjectId,omitempty"` + + // 邮箱 + Email *string `json:"email,omitempty"` + + // 语言[en_US, zh_CN] + Language *string `json:"language,omitempty"` + + // 手机号 + PhoneNumber *string `json:"phoneNumber,omitempty"` + + // 国家地区码,如86 + PhonePrefix *string `json:"phonePrefix,omitempty"` + + // 时区 Asia/Shanghai + Timezone *string `json:"timezone,omitempty"` +} + +// Validate validates this modify local user request +func (m *ModifyLocalUserRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify local user request based on context it is used +func (m *ModifyLocalUserRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyLocalUserRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyLocalUserRequest) UnmarshalBinary(b []byte) error { + var res ModifyLocalUserRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_o_s_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_o_s_request.go new file mode 100644 index 0000000..be8740c --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_o_s_request.go @@ -0,0 +1,65 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyOSRequest modify o s request +// +// swagger:model ModifyOSRequest +type ModifyOSRequest struct { + + // 体系架构 + Architecture string `json:"architecture,omitempty"` + + // 位数 + Bits int64 `json:"bits,omitempty"` + + // 操作系统名称 + OsName string `json:"osName,omitempty"` + + // 操作系统平台 + OsType string `json:"osType,omitempty"` + + // 操作系统版本 + OsVersion string `json:"osVersion,omitempty"` + + // 系统用户 + SysUser string `json:"sysUser,omitempty"` +} + +// Validate validates this modify o s request +func (m *ModifyOSRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify o s request based on context it is used +func (m *ModifyOSRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyOSRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyOSRequest) UnmarshalBinary(b []byte) error { + var res ModifyOSRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_project_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_project_request.go new file mode 100644 index 0000000..1e030ef --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_project_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ModifyProjectRequest modify project request +// +// swagger:model ModifyProjectRequest +type ModifyProjectRequest struct { + + // 项目名称 1~64字符,只支持数字、大小写字母、英文下划线“_”及中划线“-” + // Required: true + ProjectName *string `json:"projectName"` +} + +// Validate validates this modify project request +func (m *ModifyProjectRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateProjectName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ModifyProjectRequest) validateProjectName(formats strfmt.Registry) error { + + if err := validate.Required("projectName", "body", m.ProjectName); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this modify project request based on context it is used +func (m *ModifyProjectRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyProjectRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyProjectRequest) UnmarshalBinary(b []byte) error { + var res ModifyProjectRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_raid_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_raid_request.go new file mode 100644 index 0000000..443468e --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_raid_request.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ModifyRaidRequest modify raid request +// +// swagger:model ModifyRaidRequest +type ModifyRaidRequest struct { + + // raid描述(中文) + // Required: true + DescriptionEn *string `json:"descriptionEn"` + + // raid描述(英文) + // Required: true + DescriptionZh *string `json:"descriptionZh"` + + // raid名称 + // Required: true + Name *string `json:"name"` +} + +// Validate validates this modify raid request +func (m *ModifyRaidRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDescriptionEn(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDescriptionZh(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ModifyRaidRequest) validateDescriptionEn(formats strfmt.Registry) error { + + if err := validate.Required("descriptionEn", "body", m.DescriptionEn); err != nil { + return err + } + + return nil +} + +func (m *ModifyRaidRequest) validateDescriptionZh(formats strfmt.Registry) error { + + if err := validate.Required("descriptionZh", "body", m.DescriptionZh); err != nil { + return err + } + + return nil +} + +func (m *ModifyRaidRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this modify raid request based on context it is used +func (m *ModifyRaidRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyRaidRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyRaidRequest) UnmarshalBinary(b []byte) error { + var res ModifyRaidRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_role_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_role_request.go new file mode 100644 index 0000000..3fcc3e8 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_role_request.go @@ -0,0 +1,59 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyRoleRequest modify role request +// +// swagger:model ModifyRoleRequest +type ModifyRoleRequest struct { + + // 角色描述中文名称 + DescriptionCn string `json:"descriptionCn,omitempty"` + + // 角色描述英文名称 + DescriptionEn string `json:"descriptionEn,omitempty"` + + // 角色中文名称 + RoleNameCn string `json:"roleNameCn,omitempty"` + + // 角色英文名称 + RoleNameEn string `json:"roleNameEn,omitempty"` +} + +// Validate validates this modify role request +func (m *ModifyRoleRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify role request based on context it is used +func (m *ModifyRoleRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyRoleRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyRoleRequest) UnmarshalBinary(b []byte) error { + var res ModifyRoleRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_sshkey_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_sshkey_request.go new file mode 100644 index 0000000..5e17a3a --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_sshkey_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifySshkeyRequest modify sshkey request +// +// swagger:model ModifySshkeyRequest +type ModifySshkeyRequest struct { + + // 秘钥名称 + Name *string `json:"name,omitempty"` +} + +// Validate validates this modify sshkey request +func (m *ModifySshkeyRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify sshkey request based on context it is used +func (m *ModifySshkeyRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifySshkeyRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifySshkeyRequest) UnmarshalBinary(b []byte) error { + var res ModifySshkeyRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_user_password_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_user_password_request.go new file mode 100644 index 0000000..51fa312 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_user_password_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ModifyUserPasswordRequest modify user password request +// +// swagger:model ModifyUserPasswordRequest +type ModifyUserPasswordRequest struct { + + // 旧密码,明文 + // Required: true + OldPassword *string `json:"oldPassword"` + + // 新密码 明文,密码复杂度校验,大写,小写,数字,特殊字符至少出现3种,且密码长度{8,30} + // Required: true + Password *string `json:"password"` +} + +// Validate validates this modify user password request +func (m *ModifyUserPasswordRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateOldPassword(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePassword(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ModifyUserPasswordRequest) validateOldPassword(formats strfmt.Registry) error { + + if err := validate.Required("oldPassword", "body", m.OldPassword); err != nil { + return err + } + + return nil +} + +func (m *ModifyUserPasswordRequest) validatePassword(formats strfmt.Registry) error { + + if err := validate.Required("password", "body", m.Password); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this modify user password request based on context it is used +func (m *ModifyUserPasswordRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyUserPasswordRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyUserPasswordRequest) UnmarshalBinary(b []byte) error { + var res ModifyUserPasswordRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_user_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_user_request.go new file mode 100644 index 0000000..ea68964 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/modify_user_request.go @@ -0,0 +1,59 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModifyUserRequest modify user request +// +// swagger:model ModifyUserRequest +type ModifyUserRequest struct { + + // 描述 + Description *string `json:"description,omitempty"` + + // 邮箱 + Email *string `json:"email,omitempty"` + + // 手机号 + PhoneNumber *string `json:"phoneNumber,omitempty"` + + // 国家地区码,如86 + PhonePrefix *string `json:"phonePrefix,omitempty"` +} + +// Validate validates this modify user request +func (m *ModifyUserRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this modify user request based on context it is used +func (m *ModifyUserRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModifyUserRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModifyUserRequest) UnmarshalBinary(b []byte) error { + var res ModifyUserRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/module_item.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/module_item.go new file mode 100644 index 0000000..7d101be --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/module_item.go @@ -0,0 +1,65 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ModuleItem module item +// +// swagger:model ModuleItem +type ModuleItem struct { + + // description + Description string `json:"description,omitempty"` + + // description en + DescriptionEn string `json:"descriptionEn,omitempty"` + + // effective + Effective bool `json:"effective,omitempty"` + + // ID + ID int64 `json:"id,omitempty"` + + // name + Name string `json:"name,omitempty"` + + // name en + NameEn string `json:"nameEn,omitempty"` +} + +// Validate validates this module item +func (m *ModuleItem) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this module item based on context it is used +func (m *ModuleItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ModuleItem) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ModuleItem) UnmarshalBinary(b []byte) error { + var res ModuleItem + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/mount_devices_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/mount_devices_request.go new file mode 100644 index 0000000..88f5334 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/mount_devices_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// MountDevicesRequest mount devices request +// +// swagger:model MountDevicesRequest +type MountDevicesRequest struct { + + // 设备uuid + // Required: true + DeviceID *string `json:"deviceId"` +} + +// Validate validates this mount devices request +func (m *MountDevicesRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MountDevicesRequest) validateDeviceID(formats strfmt.Registry) error { + + if err := validate.Required("deviceId", "body", m.DeviceID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this mount devices request based on context it is used +func (m *MountDevicesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *MountDevicesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MountDevicesRequest) UnmarshalBinary(b []byte) error { + var res MountDevicesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/os.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/os.go new file mode 100644 index 0000000..f563370 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/os.go @@ -0,0 +1,89 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Os os +// +// swagger:model Os +type Os struct { + + // 架构:x86/x64/i386/ + Architecture string `json:"architecture,omitempty"` + + // 指令宽度:64/32位 + Bits int64 `json:"bits,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 删除时间 + DeletedTime string `json:"deletedTime,omitempty"` + + // ID + ID uint64 `json:"id,omitempty"` + + // 是否删除0未删除 1已删除 + IsDel int8 `json:"isDel,omitempty"` + + // 操作系统uuid + OsID string `json:"osId,omitempty"` + + // 操作系统名称 + OsName string `json:"osName,omitempty"` + + // 操作系统分类:linux/windows + OsType string `json:"osType,omitempty"` + + // 操作系统版本 + OsVersion string `json:"osVersion,omitempty"` + + // 管理员账户 + SysUser string `json:"sysUser,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` +} + +// Validate validates this os +func (m *Os) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this os based on context it is used +func (m *Os) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Os) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Os) UnmarshalBinary(b []byte) error { + var res Os + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/os_id.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/os_id.go new file mode 100644 index 0000000..427468c --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/os_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// OsID os Id +// +// swagger:model OsId +type OsID struct { + + // 操作系统uuid + OsID string `json:"osId,omitempty"` +} + +// Validate validates this os Id +func (m *OsID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this os Id based on context it is used +func (m *OsID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *OsID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *OsID) UnmarshalBinary(b []byte) error { + var res OsID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/os_info.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/os_info.go new file mode 100644 index 0000000..3042eb8 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/os_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// OsInfo os info +// +// swagger:model OsInfo +type OsInfo struct { + + // os + Os *Os `json:"os,omitempty"` +} + +// Validate validates this os info +func (m *OsInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateOs(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *OsInfo) validateOs(formats strfmt.Registry) error { + if swag.IsZero(m.Os) { // not required + return nil + } + + if m.Os != nil { + if err := m.Os.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("os") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("os") + } + return err + } + } + + return nil +} + +// ContextValidate validate this os info based on the context it is used +func (m *OsInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateOs(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *OsInfo) contextValidateOs(ctx context.Context, formats strfmt.Registry) error { + + if m.Os != nil { + if err := m.Os.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("os") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("os") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *OsInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *OsInfo) UnmarshalBinary(b []byte) error { + var res OsInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/os_list.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/os_list.go new file mode 100644 index 0000000..522f28d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/os_list.go @@ -0,0 +1,116 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// OsList os list +// +// swagger:model OsList +type OsList struct { + + // 操作系统列表 + Oss []*Os `json:"oss"` +} + +// Validate validates this os list +func (m *OsList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateOss(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *OsList) validateOss(formats strfmt.Registry) error { + if swag.IsZero(m.Oss) { // not required + return nil + } + + for i := 0; i < len(m.Oss); i++ { + if swag.IsZero(m.Oss[i]) { // not required + continue + } + + if m.Oss[i] != nil { + if err := m.Oss[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("oss" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("oss" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this os list based on the context it is used +func (m *OsList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateOss(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *OsList) contextValidateOss(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Oss); i++ { + + if m.Oss[i] != nil { + if err := m.Oss[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("oss" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("oss" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *OsList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *OsList) UnmarshalBinary(b []byte) error { + var res OsList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/partition.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/partition.go new file mode 100644 index 0000000..b0047e8 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/partition.go @@ -0,0 +1,57 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Partition 镜像默认分区 +// [{"format":"swap","point":"swap","size":10240},{"format":"xfs","point":"/","size":51200}] +// +// swagger:model Partition +type Partition struct { + + // format,如[swap, xfs] + FsType string `json:"format,omitempty"` + + // point,如[swap, /, /var] + MountPoint string `json:"point,omitempty"` + + // 分区大小, MB为单位 + Size int64 `json:"size,omitempty"` +} + +// Validate validates this partition +func (m *Partition) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this partition based on context it is used +func (m *Partition) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Partition) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Partition) UnmarshalBinary(b []byte) error { + var res Partition + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/project.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/project.go new file mode 100644 index 0000000..af6dd43 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/project.go @@ -0,0 +1,140 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Project project +// +// swagger:model Project +type Project struct { + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 项目下实例数量 + InstanceCount int64 `json:"instanceCount,omitempty"` + + // 此项目的共享标志位,1为拥有,2为共享 + Owned int64 `json:"owned,omitempty"` + + // 项目uuid + ProjectID string `json:"projectId,omitempty"` + + // 项目名称 + ProjectName string `json:"projectName,omitempty"` + + // 共享 + ShareProjects []*ShareProject `json:"shareProjects"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` +} + +// Validate validates this project +func (m *Project) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateShareProjects(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Project) validateShareProjects(formats strfmt.Registry) error { + if swag.IsZero(m.ShareProjects) { // not required + return nil + } + + for i := 0; i < len(m.ShareProjects); i++ { + if swag.IsZero(m.ShareProjects[i]) { // not required + continue + } + + if m.ShareProjects[i] != nil { + if err := m.ShareProjects[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this project based on the context it is used +func (m *Project) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateShareProjects(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Project) contextValidateShareProjects(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.ShareProjects); i++ { + + if m.ShareProjects[i] != nil { + if err := m.ShareProjects[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Project) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Project) UnmarshalBinary(b []byte) error { + var res Project + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/project_id.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/project_id.go new file mode 100644 index 0000000..3c4cef9 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/project_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ProjectID project Id +// +// swagger:model ProjectId +type ProjectID struct { + + // 项目uuid + ProjectID string `json:"projectId,omitempty"` +} + +// Validate validates this project Id +func (m *ProjectID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this project Id based on context it is used +func (m *ProjectID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ProjectID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ProjectID) UnmarshalBinary(b []byte) error { + var res ProjectID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/project_info.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/project_info.go new file mode 100644 index 0000000..8a6287d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/project_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ProjectInfo project info +// +// swagger:model ProjectInfo +type ProjectInfo struct { + + // project + Project *Project `json:"project,omitempty"` +} + +// Validate validates this project info +func (m *ProjectInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateProject(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ProjectInfo) validateProject(formats strfmt.Registry) error { + if swag.IsZero(m.Project) { // not required + return nil + } + + if m.Project != nil { + if err := m.Project.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("project") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("project") + } + return err + } + } + + return nil +} + +// ContextValidate validate this project info based on the context it is used +func (m *ProjectInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateProject(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ProjectInfo) contextValidateProject(ctx context.Context, formats strfmt.Registry) error { + + if m.Project != nil { + if err := m.Project.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("project") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("project") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ProjectInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ProjectInfo) UnmarshalBinary(b []byte) error { + var res ProjectInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/project_list.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/project_list.go new file mode 100644 index 0000000..a9e6867 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/project_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ProjectList project list +// +// swagger:model ProjectList +type ProjectList struct { + + // 页数 + PageNumber int64 `json:"pageNumber,omitempty"` + + // 页大小 + PageSize int64 `json:"pageSize,omitempty"` + + // 项目实体列表 + Projects []*Project `json:"projects"` + + // 总条数 + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this project list +func (m *ProjectList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateProjects(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ProjectList) validateProjects(formats strfmt.Registry) error { + if swag.IsZero(m.Projects) { // not required + return nil + } + + for i := 0; i < len(m.Projects); i++ { + if swag.IsZero(m.Projects[i]) { // not required + continue + } + + if m.Projects[i] != nil { + if err := m.Projects[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("projects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("projects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this project list based on the context it is used +func (m *ProjectList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateProjects(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ProjectList) contextValidateProjects(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Projects); i++ { + + if m.Projects[i] != nil { + if err := m.Projects[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("projects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("projects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ProjectList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ProjectList) UnmarshalBinary(b []byte) error { + var res ProjectList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/query_device_type_image_partition_response.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/query_device_type_image_partition_response.go new file mode 100644 index 0000000..01b3e25 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/query_device_type_image_partition_response.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// QueryDeviceTypeImagePartitionResponse query device type image partition response +// +// swagger:model QueryDeviceTypeImagePartitionResponse +type QueryDeviceTypeImagePartitionResponse struct { + + // 数据盘分区列表 + DataPartition []*Partition `json:"dataPartition"` + + // 系统盘分区列表 + SystemPartition []*Partition `json:"systemPartition"` +} + +// Validate validates this query device type image partition response +func (m *QueryDeviceTypeImagePartitionResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDataPartition(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemPartition(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *QueryDeviceTypeImagePartitionResponse) validateDataPartition(formats strfmt.Registry) error { + if swag.IsZero(m.DataPartition) { // not required + return nil + } + + for i := 0; i < len(m.DataPartition); i++ { + if swag.IsZero(m.DataPartition[i]) { // not required + continue + } + + if m.DataPartition[i] != nil { + if err := m.DataPartition[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *QueryDeviceTypeImagePartitionResponse) validateSystemPartition(formats strfmt.Registry) error { + if swag.IsZero(m.SystemPartition) { // not required + return nil + } + + for i := 0; i < len(m.SystemPartition); i++ { + if swag.IsZero(m.SystemPartition[i]) { // not required + continue + } + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this query device type image partition response based on the context it is used +func (m *QueryDeviceTypeImagePartitionResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDataPartition(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateSystemPartition(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *QueryDeviceTypeImagePartitionResponse) contextValidateDataPartition(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.DataPartition); i++ { + + if m.DataPartition[i] != nil { + if err := m.DataPartition[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *QueryDeviceTypeImagePartitionResponse) contextValidateSystemPartition(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.SystemPartition); i++ { + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *QueryDeviceTypeImagePartitionResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *QueryDeviceTypeImagePartitionResponse) UnmarshalBinary(b []byte) error { + var res QueryDeviceTypeImagePartitionResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/r_device_type_raid.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/r_device_type_raid.go new file mode 100644 index 0000000..fae862e --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/r_device_type_raid.go @@ -0,0 +1,83 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RDeviceTypeRaid r device type raid +// +// swagger:model RDeviceTypeRaid +type RDeviceTypeRaid struct { + + // 可用分区值,单位GB + AvailableValue int64 `json:"availableValue,omitempty"` + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 设备类型id + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // 磁盘类型:SAS/SATA/SSD/NVME + DiskInterfaceType string `json:"DiskInterfaceType,omitempty"` + + // 磁盘类型:SAS/SATA/SSD/NVME + DiskType string `json:"diskType,omitempty"` + + // RAID uuid + RaidID string `json:"raidId,omitempty"` + + // 系统盘noraid模式真实数量;此模式多块盘只能用一块 + SystemPartitionCount int64 `json:"systemPartitionCount,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 磁盘详细信息 + VolumeDetail string `json:"volumeDetail,omitempty"` + + // 磁盘类型 system/data + VolumeType string `json:"volumeType,omitempty"` +} + +// Validate validates this r device type raid +func (m *RDeviceTypeRaid) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this r device type raid based on context it is used +func (m *RDeviceTypeRaid) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RDeviceTypeRaid) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RDeviceTypeRaid) UnmarshalBinary(b []byte) error { + var res RDeviceTypeRaid + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/raid.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/raid.go new file mode 100644 index 0000000..896eeca --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/raid.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Raid raid +// +// swagger:model Raid +type Raid struct { + + // 可用分区值,单位GB + AvailableValue int64 `json:"availableValue,omitempty"` + + // 中文描述 + DescriptionEn string `json:"descriptionEn,omitempty"` + + // description + DescriptionZh string `json:"descriptionZh,omitempty"` + + // 设备类型uuid + DeviceTypeID string `json:"deviceTypeId,omitempty"` + + // 磁盘类型:SAS/SATA/SSD/NVME + DiskType string `json:"diskType,omitempty"` + + // raid 名称 + Name string `json:"name,omitempty"` + + // raid uuid + RaidID string `json:"raidId,omitempty"` + + // 系统盘分区数量 + SystemPartitionCount int64 `json:"systemPartitionCount,omitempty"` + + // 磁盘详细信息 + VolumeDetail string `json:"volumeDetail,omitempty"` + + // 磁盘类型 + VolumeType string `json:"volumeType,omitempty"` +} + +// Validate validates this raid +func (m *Raid) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this raid based on context it is used +func (m *Raid) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Raid) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Raid) UnmarshalBinary(b []byte) error { + var res Raid + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/raid_id.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/raid_id.go new file mode 100644 index 0000000..7883f4f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/raid_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RaidID raid Id +// +// swagger:model RaidId +type RaidID struct { + + // raid uuid + RaidID string `json:"raidId,omitempty"` +} + +// Validate validates this raid Id +func (m *RaidID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this raid Id based on context it is used +func (m *RaidID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RaidID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RaidID) UnmarshalBinary(b []byte) error { + var res RaidID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/raid_list.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/raid_list.go new file mode 100644 index 0000000..36ff208 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/raid_list.go @@ -0,0 +1,116 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RaidList raid list +// +// swagger:model RaidList +type RaidList struct { + + // raid实体列表 + Raids []*Raid `json:"raids"` +} + +// Validate validates this raid list +func (m *RaidList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRaids(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RaidList) validateRaids(formats strfmt.Registry) error { + if swag.IsZero(m.Raids) { // not required + return nil + } + + for i := 0; i < len(m.Raids); i++ { + if swag.IsZero(m.Raids[i]) { // not required + continue + } + + if m.Raids[i] != nil { + if err := m.Raids[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("raids" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("raids" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this raid list based on the context it is used +func (m *RaidList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateRaids(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RaidList) contextValidateRaids(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Raids); i++ { + + if m.Raids[i] != nil { + if err := m.Raids[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("raids" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("raids" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *RaidList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RaidList) UnmarshalBinary(b []byte) error { + var res RaidList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/reinstall_instance_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/reinstall_instance_request.go new file mode 100644 index 0000000..d2c6a3e --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/reinstall_instance_request.go @@ -0,0 +1,254 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ReinstallInstanceRequest reinstall instance request +// +// swagger:model ReinstallInstanceRequest +type ReinstallInstanceRequest struct { + + // 引导模式 [UEFI Legacy/BIOS] + // Required: true + BootMode *string `json:"bootMode"` + + // 数据盘分区 + DataPartition []*Partition `json:"dataPartition"` + + // 描述 + Description string `json:"description,omitempty"` + + // 主机名称 + HostName string `json:"hostname,omitempty"` + + // 镜像ID + // Required: true + ImageID *string `json:"imageId"` + + // 实例名称 + // Required: true + InstanceName *string `json:"instanceName"` + + // 密码 + Password string `json:"password,omitempty"` + + // 秘钥ID,运营平台重装,密钥暂时不可用 + SSHKeyID string `json:"sshKeyId,omitempty"` + + // 系统盘分区 + SystemPartition []*Partition `json:"systemPartition"` + + // 系统盘RAID ID + // Required: true + SystemVolumeRaidID *string `json:"systemVolumeRaidId"` +} + +// Validate validates this reinstall instance request +func (m *ReinstallInstanceRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateBootMode(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDataPartition(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImageID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInstanceName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemPartition(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSystemVolumeRaidID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ReinstallInstanceRequest) validateBootMode(formats strfmt.Registry) error { + + if err := validate.Required("bootMode", "body", m.BootMode); err != nil { + return err + } + + return nil +} + +func (m *ReinstallInstanceRequest) validateDataPartition(formats strfmt.Registry) error { + if swag.IsZero(m.DataPartition) { // not required + return nil + } + + for i := 0; i < len(m.DataPartition); i++ { + if swag.IsZero(m.DataPartition[i]) { // not required + continue + } + + if m.DataPartition[i] != nil { + if err := m.DataPartition[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *ReinstallInstanceRequest) validateImageID(formats strfmt.Registry) error { + + if err := validate.Required("imageId", "body", m.ImageID); err != nil { + return err + } + + return nil +} + +func (m *ReinstallInstanceRequest) validateInstanceName(formats strfmt.Registry) error { + + if err := validate.Required("instanceName", "body", m.InstanceName); err != nil { + return err + } + + return nil +} + +func (m *ReinstallInstanceRequest) validateSystemPartition(formats strfmt.Registry) error { + if swag.IsZero(m.SystemPartition) { // not required + return nil + } + + for i := 0; i < len(m.SystemPartition); i++ { + if swag.IsZero(m.SystemPartition[i]) { // not required + continue + } + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *ReinstallInstanceRequest) validateSystemVolumeRaidID(formats strfmt.Registry) error { + + if err := validate.Required("systemVolumeRaidId", "body", m.SystemVolumeRaidID); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this reinstall instance request based on the context it is used +func (m *ReinstallInstanceRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDataPartition(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateSystemPartition(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ReinstallInstanceRequest) contextValidateDataPartition(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.DataPartition); i++ { + + if m.DataPartition[i] != nil { + if err := m.DataPartition[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("dataPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *ReinstallInstanceRequest) contextValidateSystemPartition(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.SystemPartition); i++ { + + if m.SystemPartition[i] != nil { + if err := m.SystemPartition[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("systemPartition" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ReinstallInstanceRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ReinstallInstanceRequest) UnmarshalBinary(b []byte) error { + var res ReinstallInstanceRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/reset_instance_passwd_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/reset_instance_passwd_request.go new file mode 100644 index 0000000..0a735f2 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/reset_instance_passwd_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ResetInstancePasswdRequest 重置实例密码 +// +// swagger:model ResetInstancePasswdRequest +type ResetInstancePasswdRequest struct { + + // 新密码 + Password string `json:"password,omitempty"` +} + +// Validate validates this reset instance passwd request +func (m *ResetInstancePasswdRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this reset instance passwd request based on context it is used +func (m *ResetInstancePasswdRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ResetInstancePasswdRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ResetInstancePasswdRequest) UnmarshalBinary(b []byte) error { + var res ResetInstancePasswdRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/reset_instances_passwd_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/reset_instances_passwd_request.go new file mode 100644 index 0000000..fef10ab --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/reset_instances_passwd_request.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ResetInstancesPasswdRequest 批量重置实例密码 +// +// swagger:model ResetInstancesPasswdRequest +type ResetInstancesPasswdRequest struct { + + // 实例id列表 + InstanceIDs []string `json:"instance_ids"` + + // 新密码 + Password string `json:"password,omitempty"` +} + +// Validate validates this reset instances passwd request +func (m *ResetInstancesPasswdRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this reset instances passwd request based on context it is used +func (m *ResetInstancesPasswdRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ResetInstancesPasswdRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ResetInstancesPasswdRequest) UnmarshalBinary(b []byte) error { + var res ResetInstancesPasswdRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/restart_instances_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/restart_instances_request.go new file mode 100644 index 0000000..d26b5a8 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/restart_instances_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RestartInstancesRequest restart instances request +// +// swagger:model RestartInstancesRequest +type RestartInstancesRequest struct { + + // instance ids + InstanceIds []string `json:"instanceIds"` +} + +// Validate validates this restart instances request +func (m *RestartInstancesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this restart instances request based on context it is used +func (m *RestartInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RestartInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RestartInstancesRequest) UnmarshalBinary(b []byte) error { + var res RestartInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/role.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/role.go new file mode 100644 index 0000000..9881844 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/role.go @@ -0,0 +1,83 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Role role +// +// swagger:model Role +type Role struct { + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // description + DescriptionCn string `json:"descriptionCn,omitempty"` + + // 权限描述 + DescriptionEn string `json:"descriptionEn,omitempty"` + + // 权限 + Permission string `json:"permission,omitempty"` + + // 角色uuid + RoleID string `json:"roleId,omitempty"` + + // 角色名称 + RoleName string `json:"roleName,omitempty"` + + // 角色名称,唯一 + RoleNameCn string `json:"roleNameCn,omitempty"` + + // 角色名称,唯一 + RoleNameEn string `json:"roleNameEn,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 用户数 + UserCount int64 `json:"userCount,omitempty"` +} + +// Validate validates this role +func (m *Role) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this role based on context it is used +func (m *Role) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Role) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Role) UnmarshalBinary(b []byte) error { + var res Role + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/role_id.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/role_id.go new file mode 100644 index 0000000..a696dc6 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/role_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RoleID role Id +// +// swagger:model RoleId +type RoleID struct { + + // 角色uuid + RoleID string `json:"roleId,omitempty"` +} + +// Validate validates this role Id +func (m *RoleID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this role Id based on context it is used +func (m *RoleID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *RoleID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RoleID) UnmarshalBinary(b []byte) error { + var res RoleID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/role_info.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/role_info.go new file mode 100644 index 0000000..bf39a63 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/role_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RoleInfo role info +// +// swagger:model RoleInfo +type RoleInfo struct { + + // role + Role *Role `json:"role,omitempty"` +} + +// Validate validates this role info +func (m *RoleInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRole(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RoleInfo) validateRole(formats strfmt.Registry) error { + if swag.IsZero(m.Role) { // not required + return nil + } + + if m.Role != nil { + if err := m.Role.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("role") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("role") + } + return err + } + } + + return nil +} + +// ContextValidate validate this role info based on the context it is used +func (m *RoleInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateRole(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RoleInfo) contextValidateRole(ctx context.Context, formats strfmt.Registry) error { + + if m.Role != nil { + if err := m.Role.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("role") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("role") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *RoleInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RoleInfo) UnmarshalBinary(b []byte) error { + var res RoleInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/role_list.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/role_list.go new file mode 100644 index 0000000..25876cb --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/role_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// RoleList role list +// +// swagger:model RoleList +type RoleList struct { + + // page number + PageNumber int64 `json:"pageNumber,omitempty"` + + // page size + PageSize int64 `json:"pageSize,omitempty"` + + // 角色实体列表 + Roles []*Role `json:"roles"` + + // total count + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this role list +func (m *RoleList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateRoles(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RoleList) validateRoles(formats strfmt.Registry) error { + if swag.IsZero(m.Roles) { // not required + return nil + } + + for i := 0; i < len(m.Roles); i++ { + if swag.IsZero(m.Roles[i]) { // not required + continue + } + + if m.Roles[i] != nil { + if err := m.Roles[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("roles" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("roles" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this role list based on the context it is used +func (m *RoleList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateRoles(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *RoleList) contextValidateRoles(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Roles); i++ { + + if m.Roles[i] != nil { + if err := m.Roles[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("roles" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("roles" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *RoleList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *RoleList) UnmarshalBinary(b []byte) error { + var res RoleList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/share_project.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/share_project.go new file mode 100644 index 0000000..d31ebb0 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/share_project.go @@ -0,0 +1,143 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ShareProject share project +// +// swagger:model ShareProject +type ShareProject struct { + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 项目拥有者用户id + OwnerUserID string `json:"ownerUserId,omitempty"` + + // 项目拥有者用户名 + OwnerUserName string `json:"ownerUserName,omitempty"` + + // 项目uuid + ProjectID string `json:"projectId,omitempty"` + + // 项目名称 + ProjectName string `json:"projectName,omitempty"` + + // share projects + ShareProjects []*ShareProject `json:"shareProjects"` + + // 项目共享者用户id + SharedUserID string `json:"sharedUserId,omitempty"` + + // 项目拥有者用户名 + SharedUserName string `json:"sharedUserName,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` +} + +// Validate validates this share project +func (m *ShareProject) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateShareProjects(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ShareProject) validateShareProjects(formats strfmt.Registry) error { + if swag.IsZero(m.ShareProjects) { // not required + return nil + } + + for i := 0; i < len(m.ShareProjects); i++ { + if swag.IsZero(m.ShareProjects[i]) { // not required + continue + } + + if m.ShareProjects[i] != nil { + if err := m.ShareProjects[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this share project based on the context it is used +func (m *ShareProject) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateShareProjects(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ShareProject) contextValidateShareProjects(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.ShareProjects); i++ { + + if m.ShareProjects[i] != nil { + if err := m.ShareProjects[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("shareProjects" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ShareProject) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ShareProject) UnmarshalBinary(b []byte) error { + var res ShareProject + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/share_project_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/share_project_request.go new file mode 100644 index 0000000..f98de44 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/share_project_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ShareProjectRequest share project request +// +// swagger:model ShareProjectRequest +type ShareProjectRequest struct { + + // from user_id + // Required: true + OwnerID *string `json:"ownerID"` + + // to user_id + // Required: true + SharerID *string `json:"sharerID"` +} + +// Validate validates this share project request +func (m *ShareProjectRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateOwnerID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSharerID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ShareProjectRequest) validateOwnerID(formats strfmt.Registry) error { + + if err := validate.Required("ownerID", "body", m.OwnerID); err != nil { + return err + } + + return nil +} + +func (m *ShareProjectRequest) validateSharerID(formats strfmt.Registry) error { + + if err := validate.Required("sharerID", "body", m.SharerID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this share project request based on context it is used +func (m *ShareProjectRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ShareProjectRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ShareProjectRequest) UnmarshalBinary(b []byte) error { + var res ShareProjectRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/sshkey.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/sshkey.go new file mode 100644 index 0000000..5a0fae4 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/sshkey.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Sshkey sshkey +// +// swagger:model Sshkey +type Sshkey struct { + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 公钥指纹 + FingerPrint string `json:"fingerPrint,omitempty"` + + // id + ID int64 `json:"id,omitempty"` + + // 公钥,格式:ssh-rsa AAA + Key string `json:"key,omitempty"` + + // 秘钥名称 + Name string `json:"name,omitempty"` + + // 秘钥uuid + SshkeyID string `json:"sshkeyId,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 所属用户uuid + UserID string `json:"userId,omitempty"` +} + +// Validate validates this sshkey +func (m *Sshkey) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this sshkey based on context it is used +func (m *Sshkey) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Sshkey) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Sshkey) UnmarshalBinary(b []byte) error { + var res Sshkey + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/sshkey_id.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/sshkey_id.go new file mode 100644 index 0000000..c14abe6 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/sshkey_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// SshkeyID sshkey Id +// +// swagger:model SshkeyId +type SshkeyID struct { + + // sshkey uuid + SshkeyID string `json:"sshkeyId,omitempty"` +} + +// Validate validates this sshkey Id +func (m *SshkeyID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this sshkey Id based on context it is used +func (m *SshkeyID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SshkeyID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SshkeyID) UnmarshalBinary(b []byte) error { + var res SshkeyID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/sshkey_info.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/sshkey_info.go new file mode 100644 index 0000000..60eb531 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/sshkey_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// SshkeyInfo sshkey info +// +// swagger:model SshkeyInfo +type SshkeyInfo struct { + + // sshkey + Sshkey *Sshkey `json:"sshkey,omitempty"` +} + +// Validate validates this sshkey info +func (m *SshkeyInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSshkey(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SshkeyInfo) validateSshkey(formats strfmt.Registry) error { + if swag.IsZero(m.Sshkey) { // not required + return nil + } + + if m.Sshkey != nil { + if err := m.Sshkey.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sshkey") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sshkey") + } + return err + } + } + + return nil +} + +// ContextValidate validate this sshkey info based on the context it is used +func (m *SshkeyInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSshkey(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SshkeyInfo) contextValidateSshkey(ctx context.Context, formats strfmt.Registry) error { + + if m.Sshkey != nil { + if err := m.Sshkey.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sshkey") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sshkey") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SshkeyInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SshkeyInfo) UnmarshalBinary(b []byte) error { + var res SshkeyInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/sshkey_list.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/sshkey_list.go new file mode 100644 index 0000000..af8e27f --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/sshkey_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// SshkeyList sshkey list +// +// swagger:model SshkeyList +type SshkeyList struct { + + // 页数 + PageNumber int64 `json:"pageNumber,omitempty"` + + // 页大小 + PageSize int64 `json:"pageSize,omitempty"` + + // sshkey实体列表 + Sshkeys []*Sshkey `json:"sshkeys"` + + // 总条数 + TotalCount int64 `json:"totalCount,omitempty"` +} + +// Validate validates this sshkey list +func (m *SshkeyList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSshkeys(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SshkeyList) validateSshkeys(formats strfmt.Registry) error { + if swag.IsZero(m.Sshkeys) { // not required + return nil + } + + for i := 0; i < len(m.Sshkeys); i++ { + if swag.IsZero(m.Sshkeys[i]) { // not required + continue + } + + if m.Sshkeys[i] != nil { + if err := m.Sshkeys[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sshkeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sshkeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this sshkey list based on the context it is used +func (m *SshkeyList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSshkeys(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SshkeyList) contextValidateSshkeys(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Sshkeys); i++ { + + if m.Sshkeys[i] != nil { + if err := m.Sshkeys[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sshkeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sshkeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SshkeyList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SshkeyList) UnmarshalBinary(b []byte) error { + var res SshkeyList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/start_instances_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/start_instances_request.go new file mode 100644 index 0000000..cb20838 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/start_instances_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// StartInstancesRequest start instances request +// +// swagger:model StartInstancesRequest +type StartInstancesRequest struct { + + // instance ids + InstanceIds []string `json:"instanceIds"` +} + +// Validate validates this start instances request +func (m *StartInstancesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this start instances request based on context it is used +func (m *StartInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *StartInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *StartInstancesRequest) UnmarshalBinary(b []byte) error { + var res StartInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/stop_instances_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/stop_instances_request.go new file mode 100644 index 0000000..ae9f8d3 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/stop_instances_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// StopInstancesRequest stop instances request +// +// swagger:model StopInstancesRequest +type StopInstancesRequest struct { + + // instance ids + InstanceIds []string `json:"instanceIds"` +} + +// Validate validates this stop instances request +func (m *StopInstancesRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this stop instances request based on context it is used +func (m *StopInstancesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *StopInstancesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *StopInstancesRequest) UnmarshalBinary(b []byte) error { + var res StopInstancesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/un_mount_devices_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/un_mount_devices_request.go new file mode 100644 index 0000000..292ef2a --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/un_mount_devices_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// UnMountDevicesRequest un mount devices request +// +// swagger:model UnMountDevicesRequest +type UnMountDevicesRequest struct { + + // 设备uuid + // Required: true + DeviceID *string `json:"deviceId"` +} + +// Validate validates this un mount devices request +func (m *UnMountDevicesRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDeviceID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UnMountDevicesRequest) validateDeviceID(formats strfmt.Registry) error { + + if err := validate.Required("deviceId", "body", m.DeviceID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this un mount devices request based on context it is used +func (m *UnMountDevicesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *UnMountDevicesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UnMountDevicesRequest) UnmarshalBinary(b []byte) error { + var res UnMountDevicesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/user.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/user.go new file mode 100644 index 0000000..9273de3 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/user.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// User user +// +// swagger:model User +type User struct { + + // 创建者 + CreatedBy string `json:"createdBy,omitempty"` + + // 创建时间 + CreatedTime string `json:"createdTime,omitempty"` + + // 用户默认项目uuid + DefaultProjectID string `json:"defaultProjectId,omitempty"` + + // 用户默认项目名称 + DefaultProjectName string `json:"defaultProjectName,omitempty"` + + // 描述 + Description string `json:"description,omitempty"` + + // 邮箱 + Email string `json:"email,omitempty"` + + // 用户id + ID int64 `json:"id,omitempty"` + + // 用户拥有的实例数量 + InstanceCount int64 `json:"instanceCount,omitempty"` + + // 默认语言(en_US/zh_CN) + Language string `json:"language,omitempty"` + + // 手机号 + PhoneNumber string `json:"phoneNumber,omitempty"` + + // 国家地区码,如86 + PhonePrefix string `json:"phonePrefix,omitempty"` + + // 用户拥有的项目数量 + ProjectCount int64 `json:"projectCount,omitempty"` + + // 角色uuid + RoleID string `json:"roleId,omitempty"` + + // 角色名称 + RoleName string `json:"roleName,omitempty"` + + // 时区 + Timezone string `json:"timezone,omitempty"` + + // 更新者 + UpdatedBy string `json:"updatedBy,omitempty"` + + // 更新时间 + UpdatedTime string `json:"updatedTime,omitempty"` + + // 用户uuid + UserID string `json:"userId,omitempty"` + + // 用户名,唯一 + UserName string `json:"userName,omitempty"` +} + +// Validate validates this user +func (m *User) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this user based on context it is used +func (m *User) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *User) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *User) UnmarshalBinary(b []byte) error { + var res User + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/user_id.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/user_id.go new file mode 100644 index 0000000..c107f76 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/user_id.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// UserID user Id +// +// swagger:model UserId +type UserID struct { + + // 用户uuid + UserID string `json:"userId,omitempty"` +} + +// Validate validates this user Id +func (m *UserID) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this user Id based on context it is used +func (m *UserID) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *UserID) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UserID) UnmarshalBinary(b []byte) error { + var res UserID + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/user_info.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/user_info.go new file mode 100644 index 0000000..81d4111 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/user_info.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// UserInfo user info +// +// swagger:model UserInfo +type UserInfo struct { + + // user + User *User `json:"user,omitempty"` +} + +// Validate validates this user info +func (m *UserInfo) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateUser(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UserInfo) validateUser(formats strfmt.Registry) error { + if swag.IsZero(m.User) { // not required + return nil + } + + if m.User != nil { + if err := m.User.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("user") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("user") + } + return err + } + } + + return nil +} + +// ContextValidate validate this user info based on the context it is used +func (m *UserInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateUser(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UserInfo) contextValidateUser(ctx context.Context, formats strfmt.Registry) error { + + if m.User != nil { + if err := m.User.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("user") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("user") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *UserInfo) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UserInfo) UnmarshalBinary(b []byte) error { + var res UserInfo + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/user_list.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/user_list.go new file mode 100644 index 0000000..b072faa --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/user_list.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// UserList user list +// +// swagger:model UserList +type UserList struct { + + // 页数 + PageNumber int64 `json:"pageNumber,omitempty"` + + // 页大小 + PageSize int64 `json:"pageSize,omitempty"` + + // 总条数 + TotalCount int64 `json:"totalCount,omitempty"` + + // user实体列表 + Users []*User `json:"users"` +} + +// Validate validates this user list +func (m *UserList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateUsers(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UserList) validateUsers(formats strfmt.Registry) error { + if swag.IsZero(m.Users) { // not required + return nil + } + + for i := 0; i < len(m.Users); i++ { + if swag.IsZero(m.Users[i]) { // not required + continue + } + + if m.Users[i] != nil { + if err := m.Users[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("users" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("users" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this user list based on the context it is used +func (m *UserList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateUsers(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UserList) contextValidateUsers(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Users); i++ { + + if m.Users[i] != nil { + if err := m.Users[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("users" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("users" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *UserList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UserList) UnmarshalBinary(b []byte) error { + var res UserList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/verify_user_request.go b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/verify_user_request.go new file mode 100644 index 0000000..e902b1c --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp-openapi-sdk/models/verify_user_request.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// VerifyUserRequest verify user request +// +// swagger:model VerifyUserRequest +type VerifyUserRequest struct { + + // 密码 + // Required: true + Password *string `json:"password"` + + // 角色uuid + // Required: true + RoleID *string `json:"roleId"` + + // 用户名,唯一 + // Required: true + UserName *string `json:"userName"` +} + +// Validate validates this verify user request +func (m *VerifyUserRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validatePassword(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRoleID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUserName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *VerifyUserRequest) validatePassword(formats strfmt.Registry) error { + + if err := validate.Required("password", "body", m.Password); err != nil { + return err + } + + return nil +} + +func (m *VerifyUserRequest) validateRoleID(formats strfmt.Registry) error { + + if err := validate.Required("roleId", "body", m.RoleID); err != nil { + return err + } + + return nil +} + +func (m *VerifyUserRequest) validateUserName(formats strfmt.Registry) error { + + if err := validate.Required("userName", "body", m.UserName); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this verify user request based on context it is used +func (m *VerifyUserRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *VerifyUserRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *VerifyUserRequest) UnmarshalBinary(b []byte) error { + var res VerifyUserRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/oob-log-alert/bmp_vendor/bmp_log/README.md b/oob-log-alert/bmp_vendor/bmp_log/README.md new file mode 100644 index 0000000..f39a094 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp_log/README.md @@ -0,0 +1,6 @@ +精简日志库,用于打点统计,监控,告警等场景 +- WARN,FATAL等等级的日志即时打印落盘 + - 一个流量可以打印多条WARN,FATAL日志 +- INFO,DEBUG等级的日志,一个流量只落一条日志 + - 支持字段顺序自定义,便于正则匹配做监控等场景 + - 支持自定义代码段耗时打印,便于后续性能统计分析 diff --git a/oob-log-alert/bmp_vendor/bmp_log/go.mod b/oob-log-alert/bmp_vendor/bmp_log/go.mod new file mode 100644 index 0000000..410b4d1 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp_log/go.mod @@ -0,0 +1,3 @@ +module coding.jd.com/aidc-bmp/bmp_log + +go 1.17 diff --git a/oob-log-alert/bmp_vendor/bmp_log/log.go b/oob-log-alert/bmp_vendor/bmp_log/log.go new file mode 100644 index 0000000..6e5b79c --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp_log/log.go @@ -0,0 +1,249 @@ +package cps_log + +import ( + "encoding/json" + "fmt" + "io" + "log" + "os" + "reflect" + "strings" + "time" +) + +// Level type +type Level uint32 + +const ( + // TraceLevel level. Designates finer-grained informational events than the Debug. + TraceLevel Level = iota + // DebugLevel level. Usually only enabled when debugging. Very verbose logging. + DebugLevel + // InfoLevel level. General operational entries about what's going on inside the + // application. + InfoLevel + // WarnLevel level. Non-critical entries that deserve eyes. + WarnLevel + // ErrorLevel level. Logs. Used for errors that should definitely be noted. + // Commonly used for hooks to send errors to an error tracking service. + ErrorLevel + // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the + // logging level is set to Panic. + FatalLevel + // PanicLevel level, highest level of severity. Logs and then calls panic with the + // message passed to Debug, Info, ... + PanicLevel +) + +var globalDefinedKeys = []string{"time", "logid", "self_t", "all_t"} + +type Logger struct { + data map[string]interface{} + level Level + fileName string + definedKeys []string +} + +func New(filename string) *Logger { + if filename == "" { + log.Fatal("filename must be provided !!!") + return nil + } + l := &Logger{ + data: make(map[string]interface{}), + fileName: filename, + } + l.definedKeys = append([]string{}, globalDefinedKeys...) + l.data["time"] = time.Now().Format("2006-01-02T15:04:05") + return l +} + +func NewLoggerWithConfig(filename string, level Level, definedKeys []string) *Logger { + l := New(filename) + l.SetLevel(level) + l.SetStableFields(definedKeys) + return l +} + +func (l *Logger) SetLevel(level Level) { + l.level = level +} + +//SetStableFields 需要固定每条日志的字段时,通过此接口设置,global在前,userdefined在后 +func (l *Logger) SetStableFields(fields []string) { + l.definedKeys = append(l.definedKeys, fields...) +} + +func (l *Logger) Point(key string, val interface{}) { + l.data[key] = val +} + +func (l *Logger) GetPoint(key string) interface{} { + return l.data[key] +} + +func (l *Logger) TimeStart(key string) { + if _, ok := l.data[key]; ok { + log.Print(fmt.Sprintf("point %s TimeStart more than once, check !!!", key)) + } + l.data[key] = time.Now() + +} + +func (l *Logger) TimeEnd(key string) { + if t, ok := l.data[key]; ok { + v := time.Now().Sub(t.(time.Time)).Milliseconds() + l.data[key] = fmt.Sprintf("%f", float64(v)/1000.0) + } else { + log.Print(fmt.Sprintf("missing call TimeStart before TimeEnd when point %s, check it!!!", key)) + } + +} + +func (l *Logger) PushPoint(key string, val interface{}) { + if _, ok := l.data[key]; !ok { + l.data[key] = []interface{}{} + } + d := l.data[key].([]interface{}) + d = append(d, val) +} + +func (l *Logger) Info(v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Infof(format string, v ...interface{}) { + if l.level > InfoLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.INFO", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warn(v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Warnf(format string, v ...interface{}) { + if l.level > WarnLevel { + return + } + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.WARN", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatal(v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintln(v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Fatalf(format string, v ...interface{}) { + logid, _ := l.data["logid"].(string) + content := time.Now().Format("2006-01-02T15:04:05") + fmt.Sprintf(" [%s] ", logid) + fmt.Sprintf(format, v...) + filename := fmt.Sprintf("%s.FATAL", l.fileName) + WriteFile(filename, strings.TrimSpace(content)+"\r\n") +} + +func (l *Logger) Flush() { + if l.level > DebugLevel { + return + } + var beforeStr, afterStr string + for _, key := range l.definedKeys { + if val, ok := l.data[key]; ok { + if key == "time" { + beforeStr = val.(string) + continue + } + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + beforeStr = beforeStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + beforeStr = beforeStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + beforeStr = beforeStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Printf("val for %s unknown type!!!", key)) + + } + } + } + for key, val := range l.data { + if exist, _ := inArray(key, l.definedKeys); !exist { + switch reflect.TypeOf(val).Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + afterStr = afterStr + " " + key + ":" + fmt.Sprintf("%d", val) + case reflect.String: + afterStr = afterStr + " " + key + ":" + val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + afterStr = afterStr + " " + key + ":" + string(s) + } else { + log.Print(fmt.Sprintf("val for %s Marshal error: %s", key, err.Error())) + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %s not support channel or function, modify it!!!", key)) + default: + log.Print(fmt.Sprintf("val for %s unknown type!!!", key)) + } + } + } + + line := strings.TrimSpace(beforeStr) + " " + strings.TrimSpace(afterStr) + "\r\n" + filename := fmt.Sprintf("%s.DEBUG", l.fileName) + WriteFile(filename, line) +} + +func WriteFile(filename, line string) { + TimeStamp := time.Now() + str := filename + "." + TimeStamp.Format("2006-01-02") + logf, err := os.OpenFile(str, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + if err != nil { + log.Fatal("open filename error:", err.Error()) + } + defer logf.Close() + if _, err := io.WriteString(logf, line); err != nil { + log.Fatal("write line error:", err.Error()) + } +} + +func inArray(val interface{}, array interface{}) (exists bool, index int) { + exists = false + index = -1 + switch reflect.TypeOf(array).Kind() { + case reflect.Slice: + s := reflect.ValueOf(array) + for i := 0; i < s.Len(); i++ { + if reflect.DeepEqual(val, s.Index(i).Interface()) == true { + index = i + exists = true + return + } + } + } + return +} diff --git a/oob-log-alert/bmp_vendor/bmp_log/test.log.FATAL b/oob-log-alert/bmp_vendor/bmp_log/test.log.FATAL new file mode 100644 index 0000000..1b8bc66 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp_log/test.log.FATAL @@ -0,0 +1,2 @@ +2021-03-17T11:16:47 a warn logfor test10 +2021-03-17T11:24:31 a warn logfor test10 diff --git a/oob-log-alert/bmp_vendor/bmp_log/test.log.INFO b/oob-log-alert/bmp_vendor/bmp_log/test.log.INFO new file mode 100644 index 0000000..7672d74 --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp_log/test.log.INFO @@ -0,0 +1,5 @@ +2021-03-17T11:06:13 logid:ddddddd-12345 self_t:5.000000 all_t:3.000000 count:3 minping:jd +2021-03-17T11:12:36 logid:ddddddd-12346 self_t:5.000000 all_t:3.000000 minping:jd count:3 +2021-03-17T11:15:33 logid:ddddddd-12347 self_t:5.000000 all_t:3.000000 minping:jd count:3 +2021-03-17T11:16:42 logid:ddddddd-12348 self_t:5.000000 all_t:3.000000 minping:jd count:3 +2021-03-17T11:24:26 logid:ddddddd-12349 self_t:5.000000 all_t:3.000000 minping:jd count:3 diff --git a/oob-log-alert/bmp_vendor/bmp_log/test.log.WARN b/oob-log-alert/bmp_vendor/bmp_log/test.log.WARN new file mode 100644 index 0000000..bddad2d --- /dev/null +++ b/oob-log-alert/bmp_vendor/bmp_log/test.log.WARN @@ -0,0 +1,2 @@ +2021-03-17T11:06:18 a warn logfor test10 +2021-03-17T11:24:31 a warn logfor test10 diff --git a/oob-log-alert/bmp_vendor/ironic-common/go.mod b/oob-log-alert/bmp_vendor/ironic-common/go.mod new file mode 100644 index 0000000..5364f89 --- /dev/null +++ b/oob-log-alert/bmp_vendor/ironic-common/go.mod @@ -0,0 +1,3 @@ +module git.jd.com/cps-golang/ironic-common + +go 1.17 diff --git a/oob-log-alert/bmp_vendor/ironic-common/ironic/enums/MessageType/MessageType.go b/oob-log-alert/bmp_vendor/ironic-common/ironic/enums/MessageType/MessageType.go new file mode 100644 index 0000000..3dccfde --- /dev/null +++ b/oob-log-alert/bmp_vendor/ironic-common/ironic/enums/MessageType/MessageType.go @@ -0,0 +1,34 @@ +package MessageType + +const ( + //操作消息 + MessageTypeOperation = "operation" + //系统消息 + MessageTypeSystem = "system" + //监控消息 + MessageTypeOobMonitor = "oob-monitor" +) + +const ( + //操作消息类型 + MessageSubTypeCollectHardwareInfo = "CollectHardwareInfo" + MessageSubTypeCreateDevices = "CreateDevices" + MessageSubTypeCreateInstances = "CreateInstances" + MessageSubTypeCutDeviceStock = "CutDeviceStock" + MessageSubTypeDeleteInstance = "DeleteInstance" + MessageSubTypeInstanceResetPassword = "InstanceResetPassword" + MessageSubTypePutawayDevice = "PutawayDevice" + MessageSubTypeReinstallInstance = "ReinstallInstance" + MessageSubTypeRestartInstances = "RestartInstances" + MessageSubTypeStartInstances = "StartInstances" + MessageSubTypeStopInstances = "StopInstances" + //系统消息类型 + MessageSubTypeLicenseNearTimeout = "LicenseNearTimeout" + //监控消息类型 + MessageSubTypePowerFault = "电力故障" + MessageSubTypeTemperatureFault = "温控故障" + MessageSubTypeCPUFault = "CPU故障" + MessageSubTypeMemFault = "内存故障" + MessageSubTypeDiskFault = "硬盘故障" + MessageSubTypeOtherFault = "其他故障" +) diff --git a/oob-log-alert/build.sh b/oob-log-alert/build.sh new file mode 100644 index 0000000..128a83d --- /dev/null +++ b/oob-log-alert/build.sh @@ -0,0 +1,112 @@ +#!/bin/bash +############################################################################### +#编译脚本的原理是将编译结果放到output目录中,这个样例模版提供一个产生 +#一个最基本golang运行程序包的编译脚本,对于特殊的需求请酌情考虑 +# +#1、该脚本支持参数化,参数将传入build_package函数(内容为最终执行的编译命令) +# ,用$1,$2....表示,第1,2...个参数 +#2、部署需要启动程序,所以需要提供control文件放在当前目录中,用于启动和 +# 监控程序状态 + +###############用户修改部分################ +readonly PACKAGE_BIN_NAME=oob-log-alert #定义产出的运行程序名,必填项 +readonly CONF_DIR_NAME="conf" #定义配置文件目录,此路径为相对路径,可选项 +readonly OTHERS_DIR_NAME="" #定义其它文件目录,多个目录以空格区分,此路径为相对路径,可选项 +#最终的抽包路径为$OUTPUT +########################################### + +if [[ "${PACKAGE_BIN_NAME}" == "" ]];then + echo "Please set "PACKAGE_BIN_NAME" value" + exit 1 +fi + +function set_work_dir +{ + readonly OUTPUT=$(pwd)/output + readonly WORKSPACE_DIR=$(pwd) +} + +#清理编译构建目录操作 +function clean_before_build +{ + cd ${WORKSPACE_DIR} + rm -rf bin pkg + rm -rf ${OUTPUT} +} + +#初始化编译环境 +#function prepare_package() + +#实际的编译命令 +#这个函数中可使用$1,$2...获取第1,2...个参数 +function build_package() +{ + cd ${WORKSPACE_DIR} + # export GOPATH=$(pwd) + go clean + go build -v -gcflags="-N -l" -o ${PACKAGE_BIN_NAME} ${WORKSPACE_DIR} || return 1 +} + +#建立最终发布的目录 +function build_dir +{ + mkdir -p ${OUTPUT}/bin || return 1 +} + +function dir_not_empty() +{ + if [[ ! -d $1 ]];then + return 1 + fi + if [[ $(ls $1|wc -l) -eq 0 ]];then + return 1 + fi + return 0 +} + +#拷贝编译结果到发布的目录 +function copy_result +{ + cd ${WORKSPACE_DIR} + cp -r ${PACKAGE_BIN_NAME} ${OUTPUT}/bin/ || return 1 + cp -r control ${OUTPUT}/bin || return 1 + dir_not_empty ${WORKSPACE_DIR}/${CONF_DIR_NAME} && mkdir -p ${OUTPUT}/${CONF_DIR_NAME};cp -rf ./${CONF_DIR_NAME}/* ${OUTPUT}/${CONF_DIR_NAME}/ + test -z "$OTHERS_DIR_NAME" || cp -rf $OTHERS_DIR_NAME ${OUTPUT}/ + return 0 +} + +#执行 +function main() +{ + cd $(dirname $0) + set_work_dir + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Cleaning...' + clean_before_build || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Clean completed' + echo + + # echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'preparng...' + # prepare_package || exit 1 + # echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'prepare completed' + # echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Building...' + build_package $@ || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Build completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Making dir...' + build_dir || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Make completed' + echo + + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy result to publish dir...' + copy_result || exit 1 + echo "At: "$(date "+%Y-%m-%d %H:%M:%S") 'Copy completed' + echo + + exit 0 +} + +main $@ \ No newline at end of file diff --git a/oob-log-alert/conf/.cmd b/oob-log-alert/conf/.cmd new file mode 100644 index 0000000..5d01077 --- /dev/null +++ b/oob-log-alert/conf/.cmd @@ -0,0 +1 @@ +rm agent-log-ark.xml alert-log-ark.xml diff --git a/oob-log-alert/conf/alert-config-test.ini b/oob-log-alert/conf/alert-config-test.ini new file mode 100644 index 0000000..0013fdd --- /dev/null +++ b/oob-log-alert/conf/alert-config-test.ini @@ -0,0 +1,18 @@ +[test] + +app.idc = ${BMP_IDC||idc-vm4xsulx1k2d9z4xkctrttig02zl} + +bmp_redis_host=${BMP_REDIS_HOST||10.226.192.72} +bmp_redis_port=${BMP_REDIS_PORT||16379} +bmp_redis_db=${BMP_REDIS_DB||1} +bmp_redis_namespace=${BMP_REDIS_DB||BMP:OOB:AGENT} +bmp_redis_password=${BMP_REDIS_PASSWORD||LE&oN$9wHB} + +openapi_host=${BMP_OPENAPI_HOST||127.0.0.1} +openapi_port=${BMP_OPENAPI_PORT||8801} + +bmp_db_host=${BMP_DB_HOST||10.226.192.72} +bmp_db_port=${BMP_DB_PORT||13306} +bmp_db_user=${BMP_DB_USER||bmp_rw} +bmp_db_password=${BMP_DB_PASSWORD||LE&oN$9wHB} +bmp_db_name=${BMP_DB_NAME||bmp} \ No newline at end of file diff --git a/oob-log-alert/conf/alert-config.ini b/oob-log-alert/conf/alert-config.ini new file mode 100644 index 0000000..c9c2d07 --- /dev/null +++ b/oob-log-alert/conf/alert-config.ini @@ -0,0 +1,63 @@ +appname = oob-log-alert +runmode = "${BMP_OOB_LOG_ALERT_RUNMODE||test}" +autorender = false +copyrequestbody = true +httpport = 8804 + +app.idc = ${BMP_IDC} + + +bmp_redis_host=${BMP_REDIS_HOST} +bmp_redis_port=${BMP_REDIS_PORT} +bmp_redis_password=${BMP_REDIS_PASSWORD} +bmp_redis_db=${BMP_REDIS_DB||1} +bmp_redis_namespace=${BMP_REDIS_DB||BMP:OOB:AGENT} + +bmp_db_host=${BMP_DB_HOST} +bmp_db_port=${BMP_DB_PORT} +bmp_db_user=${BMP_DB_USER} +bmp_db_password=${BMP_DB_PASSWORD} +bmp_db_name=${BMP_DB_NAME} +mysql.max-idle-conn = 30 +mysql.max-open-conn = 30 + + +openapi_host=${BMP_OPENAPI_HOST} +openapi_port=${BMP_OPENAPI_PORT} +openapi_token="Ym1wLW9wZXJhdGlvbi1hcGk=" + +app.sync-method = api +app.api-sync-cron = "0 0 */2 * * *" +app.cps-list-api = "/v1/offline/bm/query" #需拼接openapi的host +app.cps-changestatus-api="/v1/offline/instances/modifyInstanceStatus" #需拼接openapi的host +app.cps-changestatus-api.token="amRjbG91ZGlkX3Rlc3QwMg==" + +#device同步到redis频率每5分钟一次 +app.sync-device-cron = "0 */5 * * * *" + +alert.daily-instance-status-cron = "0 10 2 * * *" +alert.daily-report-cron = "0 5 2 * * *" +alert.save-ipmi-log = true +alert.save-ipmi-logpath = "log/ipmi/" + + +app.log-level = 7 +app.alert-log-file = "/var/log/bmp/bmp-oob-alert/bmp-log-alert.log" + + + + + +# log +log.level=DEBUG +log.max.history=10 +log.path=/var/log/bmp/bmp-oob-alert + +upload.path=./data + +# 本地调试的话,把下面的注释打开,读取本地配置文件 +#include "alert-config-test.ini" + + + + diff --git a/oob-log-alert/conf/app.conf b/oob-log-alert/conf/app.conf new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/oob-log-alert/conf/app.conf @@ -0,0 +1 @@ + diff --git a/oob-log-alert/control b/oob-log-alert/control new file mode 100644 index 0000000..04c29d9 --- /dev/null +++ b/oob-log-alert/control @@ -0,0 +1,130 @@ +#!/bin/bash +set -x +cd "$(dirname $0)"/.. +BASE_DIR=`pwd` +if [ -f default_env.sh ];then + source default_env.sh +fi + +PROC_NAME=oob-log-alert # 进程名 一般就是二进制的名字java类程序一般就是java +CONF_NAME=alert-config.ini +PROC_PORT=9001 # 程序占用的端口,建议写,程序不占用端口的话只用ps来判断进程是否启动,机器上有同名程序是可能有问题 +WAIT_TIME=60 # 执行START_COMMAND后到程序能完全启动listen端口需要花的时间 + +USER=jdcloud +app_dir=/home/$USER/$PROC_NAME +mkdir -p $app_dir/log + + +START_COMMAND="$app_dir/bin/$PROC_NAME -c $app_dir/conf/$CONF_NAME" #在output目录下启动你程序的命令 + + +help(){ + echo "${0} " + exit 1 +} + +checkhealth(){ + if [[ -n "$PROC_PORT" ]] ; then + PORT_PROC=$(/usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d |awk '{print $NF}' |grep -oP '".*"' |sed "s/\"//g" |uniq) + if [ X"$PORT_PROC" = X"$PROC_NAME" ] ; then + echo "running" + return 0 + fi + echo "not running" + return 1 + else + ps -eo comm,pid |grep -P "^$PROC_NAME" + if [ "$?" = 0 ] ; then + echo "running" + return 0 + fi + echo "not running" + return 1 + fi +} + + + +start(){ + checkhealth + if [ $? = 0 ]; then + echo "[WARN] $PROC_NAME is aleady running!" + return 0 + fi + + + + [ -d "$app_dir" ] && cd $app_dir && rm -rf `ls ${app_dir} | grep -v log` + cp -r $BASE_DIR/* ${app_dir}/ + chown -R $USER:$USER ${app_dir} + su $USER -c "nohup $START_COMMAND > ${app_dir}/log/bmp-log-alert.log 2>&1 &" + + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ $? = 0 ]; then + echo "Start $PROC_NAME success" + return 0 + fi + done + echo "[ERROR] Start $PROC_NAME failed" + return 1 +} + +stop(){ + if [[ -n "$PROC_PORT" ]] ; then + PROC_ID=$( /usr/sbin/ss -nltp "( sport = :$PROC_PORT )" |sed 1d | awk '{print $NF}' | grep -oP ',.*,' | grep -oP "\d+" | uniq ) + else + PROC_ID=$(ps -eo comm,pid | grep "^$PROC_NAME" |awk '{print $2}') + fi + + if [[ -z "$PROC_ID" ]] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + + checkhealth + if [ "$?" != "0" ] ; then + echo "[WARN] $PROC_NAME is aleady exit, skip stop" + return 0 + fi + kill $PROC_ID + for i in $(seq $WAIT_TIME) ; do + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + done + + kill -9 $PROC_ID + sleep 1 + checkhealth + if [ "$?" != "0" ] ; then + echo "Stop $PROC_NAME success" + return 0 + fi + + echo "[ERROR] Stop $PROC_NAME failed" + return 1 +} + +case "${1}" in + start) + start + ;; + stop) + stop + ;; + status|health|checkhealth) + checkhealth + ;; + restart) + stop && start + ;; + *) + help + ;; +esac diff --git a/oob-log-alert/controllers/BaseController.go b/oob-log-alert/controllers/BaseController.go new file mode 100644 index 0000000..71a6537 --- /dev/null +++ b/oob-log-alert/controllers/BaseController.go @@ -0,0 +1,164 @@ +package controllers + +import ( + "encoding/json" + "fmt" + + log "coding.jd.com/aidc-bmp/bmp_log" + + "coding.jd.com/aidc-bmp/oob-log-alert/dao" + "coding.jd.com/aidc-bmp/oob-log-alert/service" + "coding.jd.com/aidc-bmp/oob-log-alert/util" + + "github.com/beego/beego/v2/server/web" +) + +const ( + InternalErrorResp int = 500 + ParamInvalid int = 400 + SuccessResp int = 200 +) + +type BaseResponse struct { + Result interface{} `json:"result,omitempty"` + Error *ErrorResponse `json:"error,omitempty"` + RequestId string `json:"requestId"` +} + +type ErrorResponse struct { + Code int `json:"code"` + Message string `json:"message"` +} + +type BaseController struct { + web.Controller + Res BaseResponse + logPoints *log.Logger +} + +func (b *BaseController) SetErrorResponse(code int, message string) { + b.Res.Error = &ErrorResponse{ + Code: code, + Message: message, + } +} + +func (ctrl *BaseController) GetPageReqInfo() dao.PageRequest { + + pageNum, _ := ctrl.GetInt64("page_num") + pageSize, _ := ctrl.GetInt64("page_size") + if ctrl.GetString("isAll") != "" { + pageSize = 0 //无限制 + } + return dao.PageRequest{ + PageNum: pageNum, + PageSize: pageSize, + } +} + +func (b *BaseController) GetTraceID() string { + if b.Ctx.Request.Header["Traceid"] != nil { + return b.Ctx.Request.Header["Traceid"][0] + } + //生成随机字符串logid + logid := util.GenerateRandUuid() + b.Ctx.Request.Header["Traceid"] = []string{logid} + return logid +} + +func (b *BaseController) Prepare() { + + web.ReadFromRequest(&b.Controller) + logPath, _ := web.AppConfig.String("log.path") + b.logPoints = log.New(logPath + "/oobalert-api.log") + b.logPoints.SetStableFields([]string{"method", "uri", "header", "request", "response"}) + b.logPoints.Point("uri", b.Ctx.Request.RequestURI) + b.logPoints.Point("method", b.Ctx.Request.Method) + b.logPoints.Point("header", b.Ctx.Request.Header) + b.logPoints.Point("request", string(b.Ctx.Input.RequestBody)) + b.logPoints.TimeStart("all_t") + b.logPoints.TimeStart("self_t") + traceId := b.GetTraceID() + + b.logPoints.Point("logid", traceId) + b.SetUserInfo() + b.logPoints.Point("language", b.GetLanguage()) + + b.Ctx.Output.Header("TraceId", traceId) + b.Res = BaseResponse{RequestId: traceId} + +} +func (b *BaseController) Finish() { + + // b.Data["json"] = b.Res + // if b.Res.Error != nil { + // b.Ctx.Output.Status = b.Res.Error.Code + // } + + // v, _ := json.Marshal(b.Data["json"]) + // logs.Debug("response", string(v)) + + // b.ServeJSON() + // + + if b.GetString("exportType") != "" { //test + return + } + + b.Res.RequestId = b.GetTraceID() + b.Data["json"] = b.Res + + if b.Res.Error != nil { + b.Ctx.Output.Status = b.Res.Error.Code + } + b.ServeJSON() + + b.logPoints.TimeEnd("self_t") + b.logPoints.TimeEnd("all_t") + b.logPoints.Point("response", b.Data["json"]) + + v, _ := json.Marshal(b.Data["json"]) + b.logPoints.Info("response:", string(v)) + fmt.Println("[DEBUG MINPING]response:", string(v)) + + b.logPoints.Flush() + +} + +func (b *BaseController) GetRequestID() string { + if b.Ctx.Request.Header["X-Jdcloud-Request-Id"] != nil { + return b.Ctx.Request.Header["X-Jdcloud-Request-Id"][0] + } + //生成随机字符串logid + logid := util.GenerateRandUuid() + b.Ctx.Request.Header["X-Jdcloud-Request-Id"] = []string{logid} + return logid +} + +func (b *BaseController) GetLanguage() string { + return b.Ctx.GetCookie("X-Jdcloud-Language") + //if len(b.Ctx.Request.Header["X-Jdcloud-Language"]) == 0 { + // if b.Ctx.GetCookie("X-Jdcloud-Language") == "" { + // return "" + // } else { + // return b.Ctx.GetCookie("X-Jdcloud-Language") + // } + //} + //return b.Ctx.Request.Header["X-Jdcloud-Language"][0] +} + +//设置username,userid等到logger +func (b *BaseController) SetUserInfo() { + + userName := b.Ctx.GetCookie("X-Jdcloud-Username") + if userName == "" { + b.logPoints.Warnf("username empty, check it!!!") + return + } + b.logPoints.Point("username", userName) + userId, _ := service.GetUserIdByName(b.logPoints, userName) + if userId == "" { + return + } + b.logPoints.Point("userId", userId) +} diff --git a/oob-log-alert/controllers/CustomController.go b/oob-log-alert/controllers/CustomController.go new file mode 100644 index 0000000..8a47704 --- /dev/null +++ b/oob-log-alert/controllers/CustomController.go @@ -0,0 +1,50 @@ +package controllers + +import ( + "encoding/json" + + "coding.jd.com/aidc-bmp/oob-log-alert/dao" + "coding.jd.com/aidc-bmp/oob-log-alert/service" +) + +// CustomController operations for custom info +type CustomController struct { + BaseController +} + +// SetCustomInfo ... +// swagger:route POST /custom/set-custom-info custom setCustomInfo +// SetCustomInfo 设置自定义信息 +// Responses: +// 200: setCustomInfo +// default: ErrorResponse + +func (c *CustomController) SetCustomInfo() { + + req := dao.SetCustomInfoRequest{} + // req.Validate() + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil { + c.logPoints.Warnf("SetCustomInfo param invalid, body:%s, error:%s", string(c.Ctx.Input.RequestBody), err.Error()) + c.SetErrorResponse(ParamInvalid, err.Error()) + } + res := service.SetCustomInfo(c.logPoints, req) + c.Res.Result = res +} + +// GetCustomInfo ... +// swagger:route GET /custom/get-custom-info custom getCustomInfo +// GetCustomInfo 获取自定义信息 +// Responses: +// 200: getCustomInfo +// default: ErrorResponse + +func (c *CustomController) GetCustomInfo() { + + req := dao.QueryCustomInfoRequest{ + PageKey: c.GetString("page_key"), + Reload: c.GetString("reload"), + } + // req.Validate() + res := service.GetCustomInfo(c.logPoints, req) + c.Res.Result = res +} diff --git a/oob-log-alert/controllers/DeviceController.go b/oob-log-alert/controllers/DeviceController.go new file mode 100644 index 0000000..40ea9ab --- /dev/null +++ b/oob-log-alert/controllers/DeviceController.go @@ -0,0 +1,56 @@ +package controllers + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/dao" + "coding.jd.com/aidc-bmp/oob-log-alert/service" + + "github.com/beego/beego/v2/core/logs" +) + +// DeviceController controller of api device +type DeviceController struct { + BaseController +} + +// swagger:route GET /v1/oob-alert/device/status device getDeviceStatus +// +// GetDeviceStatus 获取设备带外总体状态 +// +// Responses: +// 200: getDeviceStatus +// default: ErrorResponse +func (ctrl *DeviceController) GetDeviceStatus() { + logs.Debug(">>>>>>>>DeviceController.GetDeviceStatus()") + defer logs.Debug("<<<<<<<>>>>>>>LogController.GetLogs()") + defer logs.Debug("<<<<<<<>>>>>>>LogController.GetLogCollectionsBySn()") + defer logs.Debug("<<<<<<<>>>>>>>LogController.DealLogCollection()") + defer logs.Debug("<<<<<<<>>>>>>>RuleController.RuleList()") + defer logs.Debug("<<<<<<<>>>>>>>RuleController.ChangePush()") + defer logs.Debug("<<<<<<<>>>>>>>RuleController.ChangeUse()") + defer logs.Debug("<<<<<<<>>>>>>>RuleController.RuleResetPushAndUse()") + defer logs.Debug("<<<<<<<>>>>>>>DescribeInstanceMonitorController()") + defer logs.Debug("<<<<<<<>>>>>>>InstanceStatusReportController()") + defer logs.Debug("<<<<<<<>>>>>>>DailyReportController()") + defer logs.Debug("<<<<<<< 0 { + err = service.DelCPSFromRedis(delSNs) + if err != nil { + logs.Error("delCPSFromRedis() Error : " + err.Error()) + } + } + } + + // logs.Debug(cpsList) + if len(cpsList.CPSs) == 0 { + return nil + } + + idc, _ := dao.GetIdcById(logger, rIdc) + for k, v := range cpsList.CPSs { + if v.IloUser == "" || v.IloPass == "" { //设备的带外用户名密码如果为空,用机房的带外用户名密码来代替 + v.IloUser = idc.IloUser + v.IloPass = idc.IloPassword + } + cpsList.CPSs[k] = v + } + + err = service.WriteCPSListToRedis(cpsList) + if err != nil { + logs.Error("WriteCPSListToRedis() Error : " + err.Error()) + return err + } + return nil +} + +func devices2cpsList(idc string, devices []*dao.Device) object.CPSObject { + o := object.CPSObject{ + Idc: idc, + CPSs: []object.CPSRecord{}, + } + for _, device := range devices { + cpsObject := device2cpsObject(device) + o.CPSs = append(o.CPSs, cpsObject) + } + return o +} + +func device2cpsObject(device *dao.Device) object.CPSRecord { + return object.CPSRecord{ + Clazz: device.DeviceTypeID, + SN: device.Sn, + IdcId: device.IDcID, + InstanceID: device.InstanceID, + // InstanceName: device.in, + Status: device.ManageStatus, + IloIP: device.IloIP, + Brand: device.Brand, + Model: device.Model, + Ipv4: device.PrivateIPv4, + IloUser: device.IloUser, + IloPass: device.IloPassword, + } +} + +// getCurrentGoroutineStack 获取当前Goroutine的调用栈,便于排查panic异常 +func getCurrentGoroutineStack() string { + + const defaultStackSize = 4096 + + var buf [defaultStackSize]byte + n := runtime.Stack(buf[:], false) + return string(buf[:n]) +} diff --git a/oob-log-alert/dao/Cps.go b/oob-log-alert/dao/Cps.go new file mode 100644 index 0000000..192e789 --- /dev/null +++ b/oob-log-alert/dao/Cps.go @@ -0,0 +1,158 @@ +package dao + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type Device struct { + ID int `gorm:"primaryKey;column:id" json:"id"` // 设备ID编号 + Sn string `gorm:"column:sn" json:"sn"` // 设备SN + DeviceID string `gorm:"column:device_id" json:"deviceId"` // 设备uuid + InstanceID string `gorm:"column:instance_id" json:"instanceId"` // 实例id + IDcID string `gorm:"column:idc_id" json:"idcId"` // 机型uuid + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 设备类型uuid + ManageStatus string `gorm:"column:manage_status" json:"manageStatus"` // 设备状态: 未装机,已装机 + UserId string `gorm:"column:user_id" json:"userId"` // 设备状态: 未装机,已装机 + UserName string `gorm:"column:user_name" json:"userName"` // 设备状态: 未装机,已装机 + Brand string `gorm:"column:brand" json:"brand"` // 品牌 + Model string `gorm:"column:model" json:"model"` // 型号 + DeviceSeries string `gorm:"column:device_series" json:"deviceSeries"` // 机型类型,如计算型,存储型 + Reason string `gorm:"column:reason" json:"reason"` // 设备状态变更失败原因 + Cabinet string `gorm:"column:cabinet" json:"cabinet"` // 机柜编码 + UPosition string `gorm:"column:u_position" json:"uPosition"` // U位 + IloIP string `gorm:"column:ilo_ip" json:"iloIp"` // 带外管理IP + IloUser string `gorm:"column:ilo_user" json:"iloUser"` // 带外账号 + IloPassword string `gorm:"column:ilo_password" json:"iloPassword"` // 带外账号密码 + Mac1 string `gorm:"column:mac1" json:"mac1"` // MAC1(eth0) + Mac2 string `gorm:"column:mac2" json:"mac2"` // MAC2(eth2) + SwitchIP1 string `gorm:"column:switch_ip1" json:"switchIp1"` // 交换机1ip + SwitchPort1 string `gorm:"column:switch_port1" json:"switchPort1"` // 交换机1port + SwitchIP2 string `gorm:"column:switch_ip2" json:"switchIp2"` // 交换机2ip + SwitchPort2 string `gorm:"column:switch_port2" json:"switchPort2"` // 交换机2port + SwitchUser1 string `gorm:"column:switch_user1" json:"switchUser1"` // 交换机1登录账号,如果为空,取所在机房的值 + SwitchPassword1 string `gorm:"column:switch_password1" json:"switchPassword1"` // 交换机1登录密码 + SwitchUser2 string `gorm:"column:switch_user2" json:"switchUser2"` // 交换机2登录账号,如果为空,取所在机房的值 + SwitchPassword2 string `gorm:"column:switch_password2" json:"switchPassword2"` // 交换机2登录密码 + Description string `gorm:"column:description" json:"description"` // 描述 + SwitchIP string `gorm:"column:switch_ip" json:"switchIp"` // 网口交换机IP + Mask string `gorm:"column:mask" json:"mask"` // 子网掩码 + MaskEth1 string `gorm:"column:mask_eth1" json:"mask_eth1"` // eth1子网掩码 + Gateway string `gorm:"column:gateway" json:"gateway"` // 网关地址 + PrivateIPv4 string `gorm:"column:private_ipv4" json:"privateIpv4"` // 内网IPV4 + PrivateEth1IPv4 string `gorm:"column:private_eth1_ipv4" json:"privateEth1Ipv4"` // eth1内网IPV4 + PrivateIPv6 string `gorm:"column:private_ipv6" json:"privateIpv6"` // 内网IPV6 + PrivateEth1IPv6 string `gorm:"column:private_eth1_ipv6" json:"privateEth1Ipv6"` // eth1内网IPV6 + Gateway6 string `gorm:"column:gateway6" json:"gateway6"` // IPV6网关地址 + AdapterID int `gorm:"column:adapter_id" json:"adapterId"` // adapter_id + RaidDriver string `gorm:"column:raid_driver" json:"raidDriver"` // raid工具:(megacli64等) + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Device) TableName() string { + return "device" +} + +func GetCpssCount(logger *log.Logger, sn, idc string) (n int64, err error) { + + query := map[string]interface{}{ + "is_del": 0, + } + if sn != "" { + query["sn"] = sn + } + if idc != "" { + query["idc_id"] = idc + } + var db = Model(logger, IronicRdb, Device{}) + db, err = WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return + +} + +func GetCpssByCond(logger *log.Logger, sn, idc string, limit, offset int) (ml []*Device, err error) { + var db = Model(logger, IronicRdb, Device{}) + query := map[string]interface{}{ + "is_del": 0, + } + if sn != "" { + query["sn"] = sn + } + if idc != "" { + query["idc_id"] = idc + } + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Order("id desc").Offset(offset).Limit(limit).Find(&ml).Error + return + +} + +func GetCpssByCondNoLimit(logger *log.Logger, sn, idc string) (ml []*Device, err error) { + var db = Model(logger, IronicRdb, Device{}) + query := map[string]interface{}{ + "is_del": 0, + } + if sn != "" { + query["sn"] = sn + } + if idc != "" { + query["idc_id"] = idc + } + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + + err = db.Order("id desc").Find(&ml).Error + return + +} + +func GetCpssBySns(logger *log.Logger, sns []string) (ml []*Device, err error) { + var db = Model(logger, IronicRdb, Device{}) + query := map[string]interface{}{ + "is_del": 0, + "sn.in": sns, + } + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + + err = db.Order("id desc").Find(&ml).Error + return + +} + +func GetCpsBySn(logger *log.Logger, sn string) (v *Device, err error) { + v = &Device{} + var db = Model(logger, IronicRdb, Device{}) + query := map[string]interface{}{ + "is_del": 0, + "sn": sn, + } + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + + err = db.Order("id desc").Take(v).Error + return + +} diff --git a/oob-log-alert/dao/Custom.go b/oob-log-alert/dao/Custom.go new file mode 100644 index 0000000..1af11f2 --- /dev/null +++ b/oob-log-alert/dao/Custom.go @@ -0,0 +1,10 @@ +package dao + +type QueryCustomInfoRequest struct { + PageKey string `json:"page_key"` + Reload string `json:"reload"` +} +type SetCustomInfoRequest struct { + PageKey string `json:"page_key"` + PageValue map[string]map[string]bool `json:"page_value"` +} diff --git a/oob-log-alert/dao/Device.go b/oob-log-alert/dao/Device.go new file mode 100644 index 0000000..8646b16 --- /dev/null +++ b/oob-log-alert/dao/Device.go @@ -0,0 +1,50 @@ +package dao + +type GetDeviceStatusRequest struct { + IdcId string `json:"idc_id"` + Sn string `json:"sn"` + PageRequest + // ExportType 非空要导出 + ExportType string `json:"exportType"` +} + +type GetDeviceStatusResponse struct { + Detail []*DeviceStatus `json:"detail"` + PageResult +} + +type DeviceStatus struct { + DeviceItem + StatusItem +} + +type DeviceItem struct { + IdcId string `json:"idc_id"` + IdcName string `json:"idc_name"` + Sn string `json:"sn"` + DeviceId string `json:"device_id"` + Brand string `json:"brand"` + // Manufacturer string `json:"manufacturer"` + Model string `json:"model"` + // IsSale int `json:"is_sale"` + ManageStatus string `json:"manage_status"` +} + +type StatusItem struct { + CpuStatus int `json:"cpu_status"` + MemStatus int `json:"mem_status"` + DiskStatus int `json:"disk_status"` + NicStatus int `json:"nic_status"` + PowerStatus int `json:"power_status"` + OtherStatus int `json:"other_status"` +} + +type GetPowerStatusDiffRequest struct { + IdcId string `json:"idc_id"` + InstanceId string `json:"instanceId"` +} + +type PowerStatusSyncRequest struct { + IdcId string `json:"idc_id"` + InstanceId string `json:"instanceId"` +} diff --git a/oob-log-alert/dao/FaultRule.go b/oob-log-alert/dao/FaultRule.go new file mode 100644 index 0000000..9b705f6 --- /dev/null +++ b/oob-log-alert/dao/FaultRule.go @@ -0,0 +1,220 @@ +package dao + +import ( + "fmt" + "strings" + "time" + + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type RuleListRequest struct { + AlertName string `json:"alert_name"` + AlertSpec string `json:"alert_spec"` + AlertLevel string `json:"alert_level"` + // ExportType 非空要导出 + ExportType string `json:"exportType"` + PageRequest +} + +type RuleListResponse struct { + Detail []*RuleListResponseItem `json:"detail"` + PageResult +} + +type RuleListResponseItem struct { + RuleId int `json:"rule_id"` + AlertName string `json:"alert_name"` + AlertSpec string `json:"alert_spec"` + AlertLevel string `json:"alert_level"` + AlertDesc string `json:"alert_desc"` + AlertType string `json:"alert_type"` + // 判定条件 + AlertCondition string `json:"alert_condition"` + // 判定阈值 + AlertThreshold string `json:"alert_threshold"` + // 是否推送,0表示关闭,1表示开启 + PushStatus int `json:"push_status"` + // 是否启用,0表示关闭,1表示开启 + UseStatus int `json:"use_status"` +} + +type ChangePushRequest struct { + RuleID int `json:"rule_id"` + PushStatus int `json:"push_status"` +} + +type ChangeUseRequest struct { + RuleID int `json:"rule_id"` + UseStatus int `json:"use_status"` +} + +type RuleResetPushAndUseRequest struct { + RuleIDs string `json:"rule_ids"` +} + +// CpsFaultRules [...] +type CpsFaultRules struct { + ID int `gorm:"primary_key;column:id;type:int(32) unsigned;not null" json:"-"` // ID + Name string `gorm:"column:name;type:varchar(52);not null" json:"name"` // 故障名称 + Parts string `gorm:"index:parts_idx;column:parts;type:varchar(12);not null" json:"parts"` // 故障配件 + FaultType string `gorm:"column:fault_type;type:varchar(10);not null" json:"fault_type"` // 故障类型 + Condition string `gorm:"column:condition;type:varchar(20);not null" json:"condition"` // 判定条件 + Threshold string `gorm:"column:threshold;type:varchar(52);not null" json:"threshold"` // 判定阀值 + Level string `gorm:"column:level;type:varchar(16);not null" json:"level"` // 故障等级 + Desc string `gorm:"column:desc;type:varchar(152);not null" json:"desc"` // 故障描述 + IsPush bool `gorm:"index:is_push_idx;column:is_push;type:tinyint(1);not null" json:"is_push"` // 故障是否推送 0-否 1-是 + IsUse bool `gorm:"index:is_use_idx;column:is_use;type:tinyint(1);not null" json:"is_use"` // 规则是否启动 0-否 1-是 + IsDefaultPush bool `gorm:"column:is_default_push;type:tinyint(1);not null" json:"is_default_push"` // 故障是否默认推送 0-否 1-是 + IsDefaultUse bool `gorm:"column:is_default_use;type:tinyint(1);not null" json:"is_default_use"` // 规则是否默认启动 0-否 1-是 + IsDel bool `gorm:"column:is_del;type:tinyint(1);not null" json:"is_del"` // 是否删除 0-否 1-是 + CreateTime time.Time `gorm:"column:create_time;type:timestamp" json:"create_time"` // 创建时间 + Owned string `gorm:"index:owned_idx;column:owned;type:varchar(12);not null" json:"owned"` +} + +func (u *CpsFaultRules) TableName() string { + return "cps_fault_rules" +} + +func GetFaultRules(logger *log.Logger) (ml []*CpsFaultRules, err error) { + + query := map[string]interface{}{ + "is_use": 1, + "is_del": 0, + } + + var db = Model(logger, IronicRdb, CpsFaultRules{}) + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetFaultPushedRules(logger *log.Logger) (ml []*CpsFaultRules, err error) { + + query := map[string]interface{}{ + "is_use": 1, + "is_del": 0, + "is_push": 1, + } + + var db = Model(logger, IronicRdb, CpsFaultRules{}) + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetFaultUsedRules(logger *log.Logger) (ml []*CpsFaultRules, err error) { + + query := map[string]interface{}{ + "is_use": 1, + "is_del": 0, + } + + var db = Model(logger, IronicRdb, CpsFaultRules{}) + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetFaultRulesByRids(logger *log.Logger, rids []int) (ml []*CpsFaultRules, err error) { + + query := map[string]interface{}{ + // "is_use": 1,//规则后面会变,所以不能加此过滤条件 + "is_del": 0, + "id.in": rids, + } + + var db = Model(logger, IronicRdb, CpsFaultRules{}) + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return + +} + +func GetRuleList(logger *log.Logger, name, part, level string, limit, offset int64) (ml []*CpsFaultRules, n int64, err error) { + + query := map[string]interface{}{ + "is_del": 0, + } + if name != "" { + query["name.like"] = "%" + name + "%" + } + if part != "" { + query["parts"] = part + } + if level != "" { + query["level"] = level + } + var db = Model(logger, IronicRdb, CpsFaultRules{}) + db, err = WhereBuild(db, query) + if err != nil { + return nil, 0, err + } + err = db.Count(&n).Error + if err != nil { + return nil, 0, err + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func ChangePushStatusByRuleId(logger *log.Logger, ruleId int, pushStatus int8) (err error) { + + query := map[string]interface{}{ + "is_del": 0, + "id": ruleId, + } + updates := map[string]interface{}{ + "is_push": pushStatus, + } + var db = Model(logger, IronicWdb, CpsFaultRules{}) + db, err = WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func ChangeUseStatusByRuleId(logger *log.Logger, ruleId int, useStatus int8) (err error) { + + query := map[string]interface{}{ + "is_del": 0, + "id": ruleId, + } + updates := map[string]interface{}{ + "is_use": useStatus, + } + var db = Model(logger, IronicWdb, CpsFaultRules{}) + db, err = WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func RuleResetPushAndUse(logger *log.Logger, ruleIds []int) (err error) { + + var ris string + for _, v := range ruleIds { + ris = ris + fmt.Sprintf(",%d", v) + } + ris = strings.TrimLeft(ris, ",") + sql := fmt.Sprintf("update cps_fault_rules set is_push = is_default_push, is_use = is_default_use where id in (%s)", ris) + err = IronicWdb.Exec(sql).Error + return + +} diff --git a/oob-log-alert/dao/IdcDao.go b/oob-log-alert/dao/IdcDao.go new file mode 100644 index 0000000..81f3a2e --- /dev/null +++ b/oob-log-alert/dao/IdcDao.go @@ -0,0 +1,133 @@ +package dao + +import ( + "fmt" + "strings" + + log "coding.jd.com/aidc-bmp/bmp_log" +) + +type Idc struct { + ID int `gorm:"primaryKey;column:id" json:"id"` // ID + IDcID string `gorm:"column:idc_id" json:"idcId"` // 机房uuid + Name string `gorm:"column:name" json:"name"` + NameEn string `gorm:"column:name_en" json:"nameEn"` + Shortname string `gorm:"column:shortname" json:"shortname"` // 机房名称缩写 + Level string `gorm:"column:level" json:"level"` // 机房等级 + Address string `gorm:"column:address" json:"address"` // 机房地址 + IloUser string `gorm:"column:ilo_user" json:"iloUser"` // 带外登录账号 + IloPassword string `gorm:"column:ilo_password" json:"iloPassword"` // 带外登录密码 + SwitchUser1 string `gorm:"column:switch_user1" json:"switchUser1"` // 交换机1登录账号 + SwitchPassword1 string `gorm:"column:switch_password1" json:"switchPassword1"` // 交换机1登录密码 + SwitchUser2 string `gorm:"column:switch_user2" json:"switchUser2"` // 交换机2登录账号 + SwitchPassword2 string `gorm:"column:switch_password2" json:"switchPassword2"` // 交换机2登录密码 + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Idc) TableName() string { + return "idc" +} + +// AddIdc insert a new Idc into database and returns +// last inserted Id on success. +func CreateIdc(logger *log.Logger, m *Idc) (id int64, err error) { + return CreateAndGetId(logger, IronicRdb, m) +} + +// GetIdcById retrieves Idc by Id. Returns error if +// Id doesn't exist +func GetIdcById(logger *log.Logger, idcId string) (v *Idc, err error) { + v = &Idc{} + err = Where(logger, IronicRdb, "idc_id = ? and is_del = 0", idcId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetOneIdc(logger *log.Logger, query map[string]interface{}) (l *Idc, err error) { + l = &Idc{} + var db = Model(logger, IronicRdb, Idc{}) + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Take(l).Error + if err != nil { + return nil, err + } + return l, nil +} + +// GetAllIdc retrieves all Idc matches certain condition. Returns empty list if +// no records exist +func GetAllIdc(logger *log.Logger, query map[string]interface{}) (ml []*Idc, err error) { + + var db = Model(logger, IronicRdb, Idc{}) + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +// GetMultiIdc retrieves all Idc matches certain condition. Returns empty list if +// no records exist +func GetMultiIdc(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*Idc, err error) { + + var db = Model(logger, IronicRdb, Idc{}) + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + if offset == 0 && limit == 0 { + err = db.Find(&ml).Error + return + } + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +func GetIdcCount(logger *log.Logger, query map[string]interface{}) (n int64, err error) { + + var db = Model(logger, IronicRdb, Idc{}) + db, err = WhereBuild(db, query) + if err != nil { + return 0, err + } + err = db.Count(&n).Error + return + +} + +// UpdateIdc updates Idc by Id and returns error if +// the record to be updated doesn't exist +func UpdateIdcById(logger *log.Logger, m *Idc, dcId string) (err error) { + return Model(logger, IronicWdb, Idc{}).Where("idc_id = ?", dcId).Save(m).Error +} + +//func DeleteIdcById(logger *log.Logger, m *Idc) (err error) { +// m.UpdatedBy = logger.GetPoint("username").(string) +// //m.UpdatedAt = time.Now().Unix() +// //m.De = time.Now().Unix() +// return Model(logger, IronicWdb, Idc{}).Where("idc_id = ?", m.DcId).Update(m).Error +//} + +func QueryByParam(logger *log.Logger, query map[string]interface{}, offset, limit int64) (ml []*Idc, err error) { + return GetMultiIdc(logger, query, nil, []string{"id"}, []string{"desc"}, offset, limit) +} diff --git a/oob-log-alert/dao/Instance.go b/oob-log-alert/dao/Instance.go new file mode 100644 index 0000000..fccd8ee --- /dev/null +++ b/oob-log-alert/dao/Instance.go @@ -0,0 +1,47 @@ +package dao + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// Instance Instance +type Instance struct { + ID int `gorm:"primaryKey;column:id" json:"-"` + InstanceID string `gorm:"column:instance_id" json:"instanceId"` // 实例ID(uuid) + IDcID string `gorm:"column:idc_id" json:"idcId"` // 机房uuid + ProjectID string `gorm:"column:project_id" json:"projectId"` // 项目id + UserID string `gorm:"column:user_id" json:"userId"` // 用户uuid + InstanceName string `gorm:"column:instance_name" json:"instanceName"` // 实例名称 + DeviceID string `gorm:"column:device_id" json:"deviceId"` // 设备uuid + DeviceTypeID string `gorm:"column:device_type_id" json:"deviceTypeId"` // 机型uuid + Hostname string `gorm:"column:hostname" json:"hostname"` // 主机名 + Status string `gorm:"column:status" json:"status"` // 失败原因 + Reason string `gorm:"column:reason" json:"reason"` // 运行状态 + ImageID string `gorm:"column:image_id" json:"imageId"` // 镜像uuid + SystemVolumeRaidID string `gorm:"column:system_volume_raid_id" json:"systemVolumeRaidId"` // 系统盘raid + Locked string `gorm:"column:locked" json:"locked"` // 是否锁定解锁锁定:locked,解锁unlocked + DataVolumeRaidID string `gorm:"column:data_volume_raid_id" json:"dataVolumeRaidId"` // 数据盘raid + Description string `gorm:"column:description" json:"description"` // 描述 + BootMode string `gorm:"column:boot_mode" json:"bootMode"` // boot类型:UEFI Legacy/BIOS + CreatedBy string `gorm:"column:created_by" json:"createdBy"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"updatedBy"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"createdTime"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"updatedTime"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"deletedTime"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"isDel"` // 是否删除0未删除 1已删除 +} + +func (t *Instance) TableName() string { + return "instance" +} + +// GetInstanceById retrieves Instance by Id. Returns error if +// Id doesn't exist +func GetInstanceById(logger *log.Logger, InstanceId string) (v *Instance, err error) { + v = &Instance{} + err = Where(logger, IronicRdb, "instance_id = ? and is_del = 0", InstanceId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} diff --git a/oob-log-alert/dao/LogCollection.go b/oob-log-alert/dao/LogCollection.go new file mode 100644 index 0000000..ce5d3ed --- /dev/null +++ b/oob-log-alert/dao/LogCollection.go @@ -0,0 +1,299 @@ +package dao + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + log "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +type GetLogCollectionsRequest struct { + IdcId string `json:"idc_id"` + Sn string `json:"sn"` + // 故障等级 + Level string `json:"level"` + // 故障配件 + Spec string `json:"spec"` + StartTime string `json:"start_time"` + EndTime string `json:"end_time"` + DealStatus string `json:"deal_status"` //0是未处理,1是已处理 + // ExportType 非空要导出 + ExportType string `json:"exportType"` + PageRequest +} + +type GetLogCollectionsBySnRequest struct { + Sn string `json:"sn"` + // ExportType 非空要导出 + ExportType string `json:"exportType"` + PageRequest +} + +type GetLogCollectionsResponse struct { + Detail []*LogRespItem `json:"detail"` + PageResult +} + +type LogRespItem struct { + LogId int `json:"logid"` + Sn string `json:"sn"` + DeviceId string `json:"device_id"` + IdcId string `json:"idc_id"` + IdcName string `json:"idc_name"` + IloIp string `json:"ilo_ip"` + // 故障名称 + AlertName string `json:"alert_name"` + // 故障描述 + AlertDesc string `json:"alert_desc"` + // 故障类型 + AlertType string `json:"alert_type"` + // 故障配件 + AlertPart string `json:"alert_part"` + // 故障等级 + AlertLevel string `json:"alert_level"` + // 故障原始日志 + AlertContent string `json:"alert_content"` + // 带外故障发现时间 + CollectTime time.Time `json:"collect_time"` + // 首次故障报警时间 + EventTime time.Time `json:"event_time"` + // 更新时间 + UpdateTime time.Time `json:"update_time"` + // 告警次数 + Count int `json:"count"` + // 状态:0为未处理,1为已恢复 + Status int8 `json:"status"` + // 设备状态 + ManageStatus string `json:"manage_status"` +} + +func (d LogRespItem) MarshalJSON() ([]byte, error) { + type Alias LogRespItem + return json.Marshal(struct { + Alias + CollectTime string `json:"collect_time"` + EventTime string `json:"event_time"` + UpdateTime string `json:"update_time"` + }{ + Alias: Alias(d), + CollectTime: d.CollectTime.Format("2006-01-02 15:04:05"), + EventTime: d.EventTime.Format("2006-01-02 15:04:05"), + UpdateTime: d.UpdateTime.Format("2006-01-02 15:04:05"), + }) +} + +type DealLogCollectionRequest struct { + Cid int `json:"logid"` +} + +// CpsLogContentCollection [...] +type CpsLogContentCollection struct { + ID int `gorm:"primary_key;column:id;type:int(32) unsigned;not null" json:"-"` // ID + Content string `gorm:"column:content;type:varchar(256);not null" json:"content"` + FaultConfID uint32 `gorm:"index:rule_id_idx;column:fault_conf_id;type:int(32) unsigned;not null" json:"fault_conf_id"` + IsDel bool `gorm:"index:idx_isdel;column:is_del;type:tinyint(1);not null" json:"is_del"` // : 0,; 1, + Sn string `gorm:"index:sn_idx;column:sn;type:varchar(32);not null" json:"sn"` // sn + Count uint32 `gorm:"column:count;type:int(32) unsigned;not null" json:"count"` // count + Level string `gorm:"index:level_idx;column:level;type:varchar(16);not null" json:"level"` + EventTime time.Time `gorm:"column:event_time;type:timestamp" json:"event_time"` + CollectTime time.Time `gorm:"column:collect_time;type:timestamp" json:"collect_time"` + UpdateTime time.Time `gorm:"column:update_time;type:timestamp" json:"update_time"` +} + +func (u *CpsLogContentCollection) TableName() string { + return "cps_log_content_collection" +} + +func GetAllCpsLogContentCollection(logger *log.Logger) (ml []*CpsLogContentCollection, err error) { + + query := map[string]interface{}{ + "is_del": 0, + } + + var db = Model(logger, IronicRdb, CpsLogContentCollection{}) + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func InsertAndGetCollectionID(logger *log.Logger, sn, content string, ruleID int, collectTime, eventTime time.Time, level string) (n int64, err error) { + + var db = Model(logger, IronicRdb, CpsLogContentCollection{}) + c := &CpsLogContentCollection{} + if e := db.Where("sn = ? and content = ? and is_del = 0", sn, content).Take(c).Error; e != nil { + if e == gorm.ErrRecordNotFound { + c.Content = content + c.FaultConfID = uint32(ruleID) + c.Count = 1 + c.Sn = sn + c.Level = level + c.EventTime = eventTime + c.CollectTime = collectTime + c.UpdateTime = collectTime + id, err := InsertLogCollection(logger, c) + if err != nil { + return 0, fmt.Errorf("InsertLogCollection Error, content : %s", content) + } + logger.Infof("InsertLogCollection success, content:%s, id:%d", content, id) + return id, nil + } else { + logger.Warnf("InsertAndGetCollectionID.Unexpected, err:%+v, content:%s", e, content) + return 0, err + } + } + c.Count += 1 + c.CollectTime = collectTime + c.UpdateTime = collectTime + if err := UpdateCpsLogContentCollectionById(logger, c); err != nil { + return 0, err + } + + return int64(c.ID), nil +} + +func InsertLogCollection(logger *log.Logger, lc *CpsLogContentCollection) (n int64, err error) { + + n, err = CreateAndGetId(logger, IronicWdb, lc) + if err != nil { + return 0, fmt.Errorf("InsertAndGetCollectionID.Instert error, sn:%s, content : %s, err:%s", lc.Sn, lc.Content, err.Error()) + } + return + +} + +func UpdateCpsLogContentCollectionById(logger *log.Logger, m *CpsLogContentCollection) (err error) { + + return Model(logger, IronicWdb, CpsLogContentCollection{}).Where("id = ?", m.ID).Updates(m).Error + +} + +type OperationLogsItem struct { + CpsLogContentCollection + // cps_ops_cps + IdcId string `json:"idc_id"` + Brand string `json:"brand"` + Model string `json:"model"` + DeviceId string `json:"device_id"` + IloIp string `json:"ilo_ip"` + Cabinet string `json:"cabinet"` + ManageStatus string `json:"manage_status"` + // Clazz string `json:"clazz"` + // cps_fault_rules + Name string `json:"name"` + Parts string `json:"parts"` + FaultType string `json:"fault_type"` + Condition string `json:"condition"` + Threshold string `json:"threshold"` + Desc string `json:"desc"` + IsPush int8 `json:"is_push"` + IsUse int8 `json:"is_use"` +} + +func GetLogCollectionsforOperation(logger *log.Logger, sn, level, spec, idcId, startTime, endTime string, dealStatus string, limit, offset int64) (ml []*OperationLogsItem, n int64, err error) { + + var baseSql string = ` from cps_log_content_collection a join device b join cps_fault_rules c on a.sn = b.sn and a.fault_conf_id = c.id where c.is_del = 0 ` + + if idcId != "" { + baseSql += ` and b.idc_id = '` + idcId + `'` + } + if startTime != "" { + baseSql += ` and a.event_time >= '` + startTime + `'` + } + if endTime != "" { + baseSql += ` and a.event_time <= '` + endTime + `'` + } + if sn != "" { + baseSql += ` and a.sn = '` + sn + `'` + } + if level != "" { + baseSql += ` and c.level = '` + level + `'` + } + if spec != "" { + baseSql += ` and c.parts = '` + spec + `'` + } + if dealStatus != "" { + if dealStatus == "0" { //未处理 + baseSql += ` and a.count > 0` + } else { //已处理 + baseSql += ` and a.count = 0` + } + + } + + countSql := `select count(*) ` + baseSql + err = Raw(logger, IronicRdb, countSql).Count(&n).Error + if err != nil { + return nil, 0, err + } + + logger.Info("GetLogCollectionsforOperation.countSql is:", countSql) + + var selectSql string + selectedColumn := `a.*, b.idc_id, b.brand, b.model, b.ilo_ip, b.cabinet, b.manage_status, b.device_id, c.name, c.parts, c.fault_type, c.condition, c.threshold, c.desc, c.is_push, c.is_use` + if limit == 0 { + selectSql = `select ` + selectedColumn + baseSql + " order by a.collect_time desc" + } else { + selectSql = `select ` + selectedColumn + baseSql + " order by a.collect_time desc" + fmt.Sprintf(" limit %d offset %d", limit, offset) + } + logger.Info("GetLogCollectionsforOperation.selectSql is:", selectSql) + err = Raw(logger, IronicRdb, selectSql).Scan(&ml).Error + return +} + +// console是push的 +func GetLogCollectionsforConsole(logger *log.Logger, sn string, limit, offset int64) (ml []*CpsLogContentCollection, n int64, err error) { + + err = Raw(logger, IronicRdb, "select count(*) from cps_log_content_collection a join cps_fault_rules b on a.fault_conf_id = b.id where sn = ? and b.is_push = 1", sn).Count(&n).Error + if err != nil { + return nil, 0, err + } + if limit == 0 { + err = Raw(logger, IronicRdb, "select * from cps_log_content_collection a join cps_fault_rules b on a.fault_conf_id = b.id where sn = ? and b.is_push = 1 order by a.id desc", sn).Scan(&ml).Error + return + } else { + err = Raw(logger, IronicRdb, "select * from cps_log_content_collection a join cps_fault_rules b on a.fault_conf_id = b.id where sn = ? and b.is_push = 1 order by a.id desc limit ? offset ?", sn, limit, offset).Scan(&ml).Error + return + } +} + +func DealCollectionByID(logger *log.Logger, cid int) (err error) { + + updates := map[string]interface{}{ + "count": 0, + } + err = Model(logger, IronicWdb, CpsLogContentCollection{}).Where("id = ?", cid).Updates(updates).Error + if err != nil { + logger.Warnf("DealCollectionByID.CpsLogContentCollection.update err, id:%d, err:%s", cid, err.Error()) + return + } + updates = map[string]interface{}{ + "is_dealed": 1, + } + err = Model(logger, IronicWdb, CpsLogItems{}).Where("collection_id = ?", cid).Updates(updates).Error + if err != nil { + logger.Warnf("DealCollectionByID.CpsLogItems.update err, id:%d, err:%s", cid, err.Error()) + return + } + return +} + +type OrmOwnedStatusItem struct { + Sn string `json:"sn"` + CollectionId int `json:"collection_id"` + RuleId int `json:"rule_id"` + Count int `json:"count"` + Owned string `json:"owned"` +} + +func GetOwnedStatusBySns(logger *log.Logger, sns []string) (ml []*OrmOwnedStatusItem, err error) { + snsc := "'" + strings.Join(sns, "','") + "'" + sql := fmt.Sprintf("select a.sn, b.id as collection_id, b.fault_conf_id as rule_id, b.count, c.owned from device a join cps_log_content_collection b join cps_fault_rules c on a.sn = b.sn and b.fault_conf_id = c.id where a.sn in (%s)", snsc) + err = Raw(logger, IronicRdb, sql).Scan(&ml).Error + return +} diff --git a/oob-log-alert/dao/LogItems.go b/oob-log-alert/dao/LogItems.go new file mode 100644 index 0000000..9735a29 --- /dev/null +++ b/oob-log-alert/dao/LogItems.go @@ -0,0 +1,87 @@ +package dao + +import ( + "time" + + log "coding.jd.com/aidc-bmp/bmp_log" + "coding.jd.com/aidc-bmp/oob-log-alert/util" +) + +// CpsLogItems [...] +type CpsLogItems struct { + ID int `gorm:"primary_key;column:id;type:int(32) unsigned;not null" json:"-"` // ID + CollectionID int `gorm:"index:collection_id_idx;column:collection_id;type:int(32) unsigned;not null" json:"collection_id"` // id + CollectTime time.Time `gorm:"column:collect_time;type:timestamp" json:"collect_time"` + EventTime time.Time `gorm:"column:event_time;type:timestamp" json:"event_time"` + IsDealed bool `gorm:"index:is_dealed_idx;column:is_dealed;type:tinyint(1);not null" json:"is_dealed"` // : 0,, 1, + IsDel bool `gorm:"index:idx_isdel;column:is_del;type:tinyint(1);not null" json:"is_del"` // : 0,; 1, + Sn string `gorm:"index:sn_idx;column:sn;type:varchar(32);not null" json:"sn"` // sn +} + +func (u *CpsLogItems) TableName() string { + return "cps_log_items" +} + +func GetAllCpsLogItems(logger *log.Logger) (ml []*CpsLogItems, err error) { + + query := map[string]interface{}{ + "is_del": 0, + } + + var db = Model(logger, IronicRdb, CpsLogItems{}) + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetAllToDealedCpsLogItems(logger *log.Logger) (ml []*CpsLogItems, err error) { + + query := map[string]interface{}{ + "is_del": 0, + "is_dealed": 0, + } + + var db = Model(logger, IronicRdb, CpsLogItems{}) + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func GetToDealedLogItemsBySn(logger *log.Logger, sn string) (ml []*CpsLogItems, err error) { + + query := map[string]interface{}{ + "is_del": 0, + "is_dealed": 0, + "sn": sn, + } + + var db = Model(logger, IronicRdb, CpsLogItems{}) + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return +} + +func BatchInsertLogItems(logger *log.Logger, items []*CpsLogItems) (err error) { + + tx := GetGormTx(logger) + tx.Begin() + for _, item := range items { + err = tx.Create(item).Error + if err != nil { + logger.Warnf("BatchInsertLogItems.create error, content:%s", util.ToString(item)) + tx.Rollback() + return + } + } + tx.Commit() + return +} diff --git a/oob-log-alert/dao/Page.go b/oob-log-alert/dao/Page.go new file mode 100644 index 0000000..bb342fd --- /dev/null +++ b/oob-log-alert/dao/Page.go @@ -0,0 +1,13 @@ +package dao + +type PageResult struct { + Total int64 `json:"total_count"` + PageNumber int64 `json:"page_number"` + PageSize int64 `json:"page_size"` +} + +type PageRequest struct { + PageNum int64 `json:"page_num"` + PageSize int64 `json:"page_size"` + IsAll string `json:"isAll"` //非空表示全部 +} diff --git a/oob-log-alert/dao/PowerStatus.go b/oob-log-alert/dao/PowerStatus.go new file mode 100644 index 0000000..c4cd1c7 --- /dev/null +++ b/oob-log-alert/dao/PowerStatus.go @@ -0,0 +1,20 @@ +package dao + +import ( + "time" +) + +type PowerStatus struct { + Id int `json:"id"` + SN string `json:"sn"` + InstanceID string `json:"instance_id"` + InstanceName string `json:"instance_name"` + IdcId string `json:"idc_id"` + Pin string `json:"pin"` + IloIp string `json:"ilo_ip"` + Status string `json:"status"` + IloStatus string `json:"ilo_status"` + Ipv4 string `json:"ipv4"` + DeviceType string `json:"device_type"` + UpdateTime time.Time `json:"update_time"` +} diff --git a/oob-log-alert/dao/baseDao.go b/oob-log-alert/dao/baseDao.go new file mode 100644 index 0000000..94a14aa --- /dev/null +++ b/oob-log-alert/dao/baseDao.go @@ -0,0 +1,162 @@ +package dao + +import ( + "fmt" + "reflect" + "strings" + "time" + + beego "github.com/beego/beego/v2/server/web" + + clog "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +var ( + IronicRdb *gorm.DB + IronicWdb *gorm.DB +) + +type gLogger struct { + traceid string +} + +func (g *gLogger) Print(values ...interface{}) { + var ( + level = values[0] + // source = values[1] + ) + logPath, _ := beego.AppConfig.String("log.path") + logger := clog.New(logPath + "/bmp-logalert-sql.log") + defer logger.Flush() + logger.SetStableFields([]string{"sql", "args", "cost"}) + logger.Point("logid", g.traceid) + + if level == "sql" { + logger.Point("sql", values[3]) + logger.Point("args", values[4]) + logger.Point("cost", fmt.Sprint(values[2])) + } else { + logger.Point("trace", values) + } +} + +func InitGormDb(conn string) { + + doInit(conn) + //初始化时没有完成的,择机完成初始化 + go func() { + for { + time.Sleep(10 * time.Second) + if IronicRdb != nil && IronicRdb.DB().Stats().OpenConnections == 0 { + fmt.Println(time.Now().String(), "IronicRdb reInit......") + doInitIronicRdb(conn) + } + if IronicWdb != nil && IronicWdb.DB().Stats().OpenConnections == 0 { + fmt.Println(time.Now().String(), "IronicWdb reInit......") + doInitIronicWdb(conn) + } + } + }() + +} + +func doInit(conn string) { + doInitIronicRdb(conn) + doInitIronicWdb(conn) +} + +func doInitIronicRdb(conn string) { + var err error + IronicRdb, err = gorm.Open("mysql", conn) + if err != nil { + fmt.Println(time.Now(), "IronicRdb init error:", err.Error()) + return + } + IronicRdb.LogMode(true) + IronicRdb.DB().SetMaxOpenConns(100) + IronicRdb.DB().SetMaxIdleConns(20) +} + +func doInitIronicWdb(conn string) { + var err error + IronicWdb, err = gorm.Open("mysql", conn) + if err != nil { + fmt.Println(time.Now(), "IronicWdb init error:", err.Error()) + return + } + IronicWdb.LogMode(true) + IronicWdb.DB().SetMaxOpenConns(100) + IronicWdb.DB().SetMaxIdleConns(20) +} + +func GetGormTx(logger *clog.Logger) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := IronicWdb.New() + db.SetLogger(gl) + return db +} + +type NullType byte + +const ( + _ NullType = iota + // IsNull the same as `is null` + IsNull + // IsNotNull the same as `is not null` + IsNotNull +) + +// sql build where +func WhereBuild(g *gorm.DB, query map[string]interface{}) (*gorm.DB, error) { + logger := clog.New("./log/bmp-logalert-sql.log") + query["is_del"] = 0 + for k, v := range query { + if reflect.TypeOf(v).Kind() == reflect.String { + if v.(string) == "" { + continue + } + } + ks := strings.Split(k, ".") + if len(ks) > 2 { + fmt.Println(time.Now(), fmt.Errorf("Error in query condition: %s. ", k)) + logger.Warn(fmt.Errorf("Error in query condition: %s. ", k)) + + return g, fmt.Errorf("Error in query condition: %s. ", k) + } + switch len(ks) { + case 1: + g = g.Where(fmt.Sprintf("%s = ?", k), v) + break + case 2: + k = ks[0] + switch ks[1] { + case "=": + g = g.Where(fmt.Sprintf("%s = ?", k), v) + break + case ">", "gt": + g = g.Where(fmt.Sprintf("%s > ?", k), v) + case ">=", "gte": + g = g.Where(fmt.Sprintf("%s >= ?", k), v) + break + case "<", "lt": + g = g.Where(fmt.Sprintf("%s < ?", k), v) + break + case "<=", "lte": + g = g.Where(fmt.Sprintf("%s <= ?", k), v) + break + case "!=", "<>": + g = g.Where(fmt.Sprintf("%s <> ?", k), v) + break + case "in": + g = g.Where(fmt.Sprintf("%s IN (?)", k), v) + break + case "like": + g = g.Where(fmt.Sprintf("%s LIKE ?", k), v) + break + } + break + } + } + return g, nil +} diff --git a/oob-log-alert/dao/common.go b/oob-log-alert/dao/common.go new file mode 100644 index 0000000..f0df686 --- /dev/null +++ b/oob-log-alert/dao/common.go @@ -0,0 +1,6 @@ +package dao + +type CommonResponse struct { + // 操作是否成功 [true/false] + Success bool `json:"success"` +} diff --git a/oob-log-alert/dao/createDao.go b/oob-log-alert/dao/createDao.go new file mode 100644 index 0000000..d7f5ade --- /dev/null +++ b/oob-log-alert/dao/createDao.go @@ -0,0 +1,36 @@ +package dao + +import ( + clog "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +// 插入单条记录,v2版本才支持插入多条记录? +//eg. db.Create(logger, rdb, u) +func Create(logger *clog.Logger, gdb *gorm.DB, out interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Create(out) +} + +//插入并获取刚插入数据的自增Id +//eg. db.CreateAndGetId(logger, rdb, u) +func CreateAndGetId(logger *clog.Logger, gdb *gorm.DB, out interface{}) (int64, error) { + // 事务约束,否则并发下可能获取到的是错误的id + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + tx := db.Begin() + if err := tx.Create(out).Error; err != nil { + tx.Rollback() + return 0, err + } + var id []int64 + if err := tx.Raw("select LAST_INSERT_ID() as id").Pluck("id", &id).Error; err != nil { + tx.Rollback() + return 0, err + } + tx.Commit() + return id[0], nil +} diff --git a/oob-log-alert/dao/deleteDao.go b/oob-log-alert/dao/deleteDao.go new file mode 100644 index 0000000..190aba8 --- /dev/null +++ b/oob-log-alert/dao/deleteDao.go @@ -0,0 +1,21 @@ +package dao + +import ( + clog "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +//删除记录 +//eg1.根据模型删除 +/* +food := Food{} +dao.Where(logger, rdb, "id = ?", 2).Take(&food).Delete(&food) +*/ +//eg2.根据Where条件删除数据 +// dao.Where(logger, rdb, "type = ?", 5).Delete(&Food{})//注意这里Delete函数需要传递一个空的模型变量指针 +func Delete(logger *clog.Logger, gdb *gorm.DB, value interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Delete(value, where...) +} diff --git a/oob-log-alert/dao/mailDao.go b/oob-log-alert/dao/mailDao.go new file mode 100644 index 0000000..15990c5 --- /dev/null +++ b/oob-log-alert/dao/mailDao.go @@ -0,0 +1,67 @@ +package dao + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// MailMessage message +type MailMessage struct { + //以下为消息通用字段 + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + // 邮件服务器地址 + ServerAddr string `gorm:"column:server_addr;type:varchar(255);not null" json:"server_addr"` + // 邮件服务器端口 + ServerPort string `gorm:"column:server_port;type:varchar(255);not null" json:"server_port"` + // 管理员邮箱 + AdminAddr string `gorm:"column:admin_addr;type:varchar(255);not null" json:"admin_addr"` + // 管理员邮箱密码 + AdminPass string `gorm:"column:admin_pass;type:varchar(255);not null" json:"admin_pass"` + //收件人邮箱 + To string `gorm:"column:to;type:varchar(255);not null" json:"to"` + // 是否推送邮件告警0不推送,1推送 + IsPush string `gorm:"column:is_push;type:type:varchar(8);not null" json:"is_push"` + // 是否删除0未删除 1已删除 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` +} + +func (t *MailMessage) TableName() string { + return "mail_message" +} + +// AddMailMessage insert a new Os into database and returns +// last inserted Id on success. +func AddMailMessage(logger *log.Logger, m *MailMessage) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + return CreateAndGetId(logger, IronicWdb, m) +} + +// GetMailMessage retrieves Os by Id. Returns error if +// Id doesn't exist +func GetMailMessage(logger *log.Logger) (v *MailMessage, err error) { + v = &MailMessage{} + err = Where(logger, IronicRdb, "is_del = 0").Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func UpdateMailMessage(logger *log.Logger, query map[string]interface{}, updates map[string]interface{}) (err error) { + + // updates["updated_time"] = time.Now().Unix() + var db = Model(logger, IronicWdb, MailMessage{}) + db, err = WhereBuild(db, query) + if err != nil { + return err + } + err = db.Updates(updates).Error + return +} + +func UpdateMailAnywhere(logger *log.Logger, m *MailMessage) (err error) { + + //m.UpdateTime = time.Now() + return Model(logger, IronicWdb, MailMessage{}).Save(m).Error +} diff --git a/oob-log-alert/dao/queryDao.go b/oob-log-alert/dao/queryDao.go new file mode 100644 index 0000000..8931f0c --- /dev/null +++ b/oob-log-alert/dao/queryDao.go @@ -0,0 +1,131 @@ +package dao + +import ( + clog "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +// SELECT * FROM `foods` LIMIT 1 +//eg. db.Take(logger, rdb, &food) +func Take(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Take(out, where...) +} + +// SELECT * FROM `foods` ORDER BY `foods`.`id` ASC LIMIT 1 +//eg. db.First(logger, rdb, &food) +func First(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.First(out, where...) +} + +// SELECT * FROM `foods` ORDER BY `foods`.`id` DESC LIMIT 1 +//eg. db.Last(logger, rdb, &food) +func Last(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Last(out, where...) +} + +// SELECT * FROM `foods` 可单可复 +//eg. db.Find(logger, rdb, &foods) +func Find(logger *clog.Logger, gdb *gorm.DB, out interface{}, where ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Find(out, where...) +} + +// // 查询一列值 +//eg. Model(Food{}).Pluck("title", &titles) +// func Pluck(logger *clog.Logger, model interface{}, column string, target interface{}) error { +// //等价于:SELECT title FROM `foods` 提取了title字段,保存到titles变量 +// //这里Model函数是为了绑定一个模型实例,可以从里面提取表名。 +// gl := &gLogger{traceid: logger.GetPoint("logid").(string)} +// db := gdb.New() +// db.SetLogger(gl) +// return gdb.Model(model).Pluck("title", target).Error +// } + +// 设置where条件 +//eg. dao.Where(logger, rdb, "id = ?", 10).Take(&food) +//eg. dao.Where(logger, rdb, "id in (?)", []int{1,2,5,6}).Take(&food) +//eg. dao.Where(logger, rdb, "create_time >= ? and create_time <= ?", "2018-11-06 00:00:00", "2018-11-06 23:59:59").Find(&foods) +//eg. dao.Where(logger, rdb, "title like ?", "%可乐%").Find(&foods) +func Where(logger *clog.Logger, gdb *gorm.DB, query interface{}, args ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Where(query, args...) +} + +// 指定返回的字段 +//eg. dao.Select(logger, rdb, "id,title").Where("id = ?", 1).Take(&food) +//eg. dao.Model(logger, rdb, Food{}).Select("count(*) as total").Pluck("total", &total) +func Select(logger *clog.Logger, gdb *gorm.DB, query interface{}, args ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Select(query, args...) +} + +// 指定绑定的模型,一般和Pluck一起使用 +//eg. dao.Model(logger, rdb, Food{}).Select("count(*) as total").Pluck("total", &total) +func Model(logger *clog.Logger, gdb *gorm.DB, value interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + //db.Callback().Update().Remove("gorm:update_time_stamp") + //db.Callback().Update().Remove("gorm:delete_time_stamp") + return db.Model(value) +} + +// 指定order +//eg. dao.Order(logger, rdb, "create_time desc").Limit(10).Offset(0).Find(&foods) +//eg. dao.Where(logger, rdb, "create_time >= ?", "2018-11-06 00:00:00").Order("create_time desc").Find(&foods) +func Order(logger *clog.Logger, gdb *gorm.DB, value interface{}, reorder ...bool) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Order(value, reorder...) +} + +// limit +//eg. dao.Order(logger, rdb, "create_time desc").Limit(10).Offset(0).Find(&foods) +//eg. dao.Limit(logger, rdb, 10).Offset(0).Find(&foods) +func Limit(logger *clog.Logger, gdb *gorm.DB, limit interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Limit(limit) +} + +// Offset +//eg. dao.Order(logger, rdb, "create_time desc").Limit(10).Offset(0).Find(&foods) +//eg. dao.Offset(logger, rdb, 10).Find(&foods) +func Offset(logger *clog.Logger, gdb *gorm.DB, limit interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Offset(limit) +} + +//eg. dao.Model(logger, rdb, Food{}).Count(&total) +// COUNT + +//eg. dao.Model(logger, rdb, Food{}).Select("type, count(*) as total").Group("type").Having("total > 0").Scan(&results) +//group by,必须要搭配select一起使用 + +//Raw +//eg. dao.Raw(logger, rdb, sql, "2018-11-06 00:00:00").Scan(&results) +func Raw(logger *clog.Logger, gdb *gorm.DB, sql string, values ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Raw(sql, values...) +} diff --git a/oob-log-alert/dao/updateDao.go b/oob-log-alert/dao/updateDao.go new file mode 100644 index 0000000..e65b9d6 --- /dev/null +++ b/oob-log-alert/dao/updateDao.go @@ -0,0 +1,53 @@ +package dao + +import ( + clog "coding.jd.com/aidc-bmp/bmp_log" + "github.com/jinzhu/gorm" +) + +//更新 根据主键id,更新所有模型字段值。查询->set->save +//eg. dao.Save(logger, rdb, &food) +func Save(logger *clog.Logger, gdb *gorm.DB, value interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Save(value) +} + +//更新单个字段值 +//eg1.更新一条记录(根据主键) dao.Model(logger, rdb, &food).Update("price", 25) +//eg2.更新所有记录 dao.Model(logger, rdb, Food{}).Update("price", 25) +//eg3.根据自定义条件更新记录 dao.Model(logger, rdb, Food{}).Where("create_time > ?", "2018-11-06 20:00:00").Update("price", 25) +func Update(logger *clog.Logger, gdb *gorm.DB, attrs ...interface{}) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Update(attrs...) +} + +//更新多个字段值 +/* +updataFood := Food{ + Stock:120, + Title:"柠檬雪碧", + //Age:0 +} +*/ +//eg1. 通过结构体变量设置更新字段 dao.Model(logger, rdb, &food).Updates(&updataFood) 问题是:这样只会更新updataFood中字段为非默认值的字段,比如updataFood定义时就算加上了Age:0,这个字段也不会被更新成目标0 +//eg2. 根据自定义条件更新记录 dao.Model(logger, rdb, Food{}).Where("price > ?", 10).Updates(&updataFood) 问题同上 +//eg3. 想更新所有字段值,包括零值,就是不想忽略掉空值字段时,使用map类型替代上面的结构体变量 +/* +data := make(map[string]interface{}) +data["stock"] = 0 //零值字段 +data["price"] = 35 +dao.Model(logger, rdb, Food{}).Where("id = ?", 2).Updates(data) +*/ +func Updates(logger *clog.Logger, gdb *gorm.DB, values interface{}, ignoreProtectedAttrs ...bool) *gorm.DB { + gl := &gLogger{traceid: logger.GetPoint("logid").(string)} + db := gdb.New() + db.SetLogger(gl) + return db.Updates(values, ignoreProtectedAttrs...) +} + +//更新表达式 +//eg. db.Model(&food).Update("stock", gorm.Expr("stock + 1")) 等价于UPDATE `foods` SET `stock` = stock + 1 WHERE `foods`.`id` = '2' diff --git a/oob-log-alert/dao/userDao.go b/oob-log-alert/dao/userDao.go new file mode 100644 index 0000000..6d233b3 --- /dev/null +++ b/oob-log-alert/dao/userDao.go @@ -0,0 +1,51 @@ +package dao + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// user user +type User struct { + ID int `gorm:"primaryKey;column:id" json:"-"` + UserID string `gorm:"column:user_id" json:"userId"` // 用户uuid + RoleID string `gorm:"column:role_id" json:"-"` // 角色uuid + UserName string `gorm:"column:user_name" json:"userName"` // 用户名,唯一 + Email string `gorm:"column:email" json:"-"` // 邮箱 + PhonePrefix string `gorm:"column:phone_prefix" json:"-"` // 国家地区码,如86 + PhoneNumber string `gorm:"column:phone_number" json:"-"` // 手机号 + DefaultProjectID string `gorm:"column:default_project_id" json:"-"` // 所属项目uuid + Language string `gorm:"column:language" json:"language"` // 语言(中文/English) + Timezone string `gorm:"column:timezone;type:varchar(64);not null" json:"-"` // timezone + Password string `gorm:"column:password" json:"-"` // 密码,sha256非对称加密后存储 + Description string `gorm:"column:description" json:"-"` // 描述 + CreatedBy string `gorm:"column:created_by" json:"-"` // 创建者 + UpdatedBy string `gorm:"column:updated_by" json:"-"` // 更新者 + CreatedTime int `gorm:"column:created_time" json:"-"` // 创建时间戳 + UpdatedTime int `gorm:"column:updated_time" json:"-"` // 更新时间戳 + DeletedTime int `gorm:"column:deleted_time" json:"-"` // 删除时间戳 + IsDel int8 `gorm:"column:is_del" json:"-"` // 是否删除0未删除 1已删除 +} + +func (t *User) TableName() string { + return "user" +} + +// GetuserById retrieves user by Id. Returns error if +// Id doesn't exist +func GetUserById(logger *log.Logger, userId string) (v *User, err error) { + v = &User{} + err = Where(logger, IronicRdb, "user_id = ? and is_del = 0", userId).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +func GetUserByName(logger *log.Logger, userName string) (v *User, err error) { + v = &User{} + err = Where(logger, IronicRdb, "user_name = ? and is_del = 0", userName).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} diff --git a/oob-log-alert/dao/webMessage.go b/oob-log-alert/dao/webMessage.go new file mode 100644 index 0000000..cebc948 --- /dev/null +++ b/oob-log-alert/dao/webMessage.go @@ -0,0 +1,136 @@ +package dao + +import ( + "fmt" + "strings" + + log "coding.jd.com/aidc-bmp/bmp_log" +) + +// WebMessage message +type WebMessage struct { + //以下为消息通用字段 + ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"` + MessageID string `gorm:"column:message_id;type:varchar(255);not null" json:"message_id"` // message_id + UserID string `gorm:"index:i_message_userid;column:user_id;type:varchar(255);not null" json:"user_id"` // user_id + UserName string `gorm:"column:user_name;type:varchar(255);not null" json:"user_name"` // user_id + ResourceType string `gorm:"column:resource_type;type:varchar(255);not null" json:"resource_type"` // 资源类型 + Result string `gorm:"column:result;type:varchar(255);not null" json:"result"` // 操作结果 + FinishTime int `gorm:"column:finish_time;type:int(11);not null" json:"finish_time"` // 完成时间戳 + HasRead int8 `gorm:"index:i_message_read;column:has_read;type:tinyint(4);not null" json:"has_read"` // 0未读, 1已读 + IsDel int8 `gorm:"column:is_del;type:tinyint(4);not null" json:"is_del"` // 是否删除0未删除 1已删除 + MessageType string `gorm:"column:message_type;type:varchar(255);not null" json:"message_type"` // 消息类型 + MessageSubType string `gorm:"column:message_sub_type;type:varchar(255);not null" json:"message_sub_type"` // 消息子类型 + InstanceID string `gorm:"column:instance_id;type:varchar(255);not null" json:"instance_id"` //实例id + InstanceName string `gorm:"column:instance_name;type:varchar(255);not null" json:"instance_name"` + SN string `gorm:"column:sn;type:varchar(255);not null" json:"sn"` //设备sn + Detail string `gorm:"column:detail;type:varchar(4096);not null" json:"detail"` //详情,带外监控的消息比较特殊 + + //以下为带外故障消息专属字段 + FaultType string `gorm:"column:fault_type;type:varchar(10);not null" json:"fault_type"` // 故障类型 + Content string `gorm:"column:content;type:varchar(4096);not null" json:"content"` + LogID string `gorm:"column:logid;type:varchar(256);not null" json:"logid"` //带外原始日志的id + AlertTime int `gorm:"column:alert_time;type:int(11);not null" json:"alert_time"` //故障告警时间 + AlertCount int `gorm:"column:alert_count;type:int(11);not null" json:"alert_count"` //告警次数,始终为1 + + //以下为许可证到期消息专属字段 + LicenseName string `gorm:"column:license_name;type:varchar(64);not null" json:"license_name"` // 版本名称 + LicenseNumber string `gorm:"column:license_number;type:varchar(64);not null" json:"license_number"` // 版本号 + LienseStartTime int `gorm:"column:license_start_time;type:int(11);not null" json:"license_start_time"` //开始时间 + LienseEndTime int `gorm:"column:license_end_time;type:int(11);not null" json:"license_end_time"` //结束时间 + +} + +func (t *WebMessage) TableName() string { + return "web_message" +} + +// AddWebMessage insert a new Os into database and returns +// last inserted Id on success. +func AddWebMessage(logger *log.Logger, m *WebMessage) (id int64, err error) { + + //m.CreateTime = time.Now() + //m.UpdateTime = time.Now() + + return CreateAndGetId(logger, IronicWdb, m) +} + +// GetOsById retrieves Os by Id. Returns error if +// Id doesn't exist +func GetWebMessageById(logger *log.Logger, id int64) (v *WebMessage, err error) { + v = &WebMessage{} + err = Where(logger, IronicRdb, "id = ? and is_del = 0", id).Take(v).Error + if err != nil { + return nil, err + } + return v, nil +} + +// GetAllOs retrieves all os matches certain condition. Returns empty list if +// no records exist +func GetAllWebMessagesByUserId(logger *log.Logger, userId string) (ml []*WebMessage, err error) { + + query := map[string]interface{}{ + "user_id": userId, + "is_del": 0, + } + var db = Model(logger, IronicRdb, WebMessage{}) + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + err = db.Find(&ml).Error + return + +} + +// GetMultiOs retrieves all Os matches certain condition. Returns empty list if +// no records exist +func GetMultiWebMessagesByUserId(logger *log.Logger, query map[string]interface{}, fields []string, sortby []string, order []string, + offset int64, limit int64) (ml []*WebMessage, err error) { + + var db = Model(logger, IronicRdb, WebMessage{}) + db, err = WhereBuild(db, query) + if err != nil { + return nil, err + } + if len(fields) > 0 { + db = db.Select(fields) + } + orderConditions := []string{} + for i := 0; i < len(sortby); i++ { + orderConditions = append(orderConditions, fmt.Sprintf("%s %s", sortby[i], order[i])) + } + db = db.Order(strings.Join(orderConditions, ",")) + err = db.Offset(offset).Limit(limit).Find(&ml).Error + return +} + +// UpdateOs updates Os by Id and returns error if +// the record to be updated doesn't exist +func UpdateOsById(logger *log.Logger, m *WebMessage) (err error) { + + //m.UpdateTime = time.Now() + return Model(logger, IronicWdb, WebMessage{}).Where("id = ?", m.ID).Updates(m).Error +} + +func GetInstanceBySn(logger *log.Logger, sn string) (*Instance, error) { + deviceEntity, err := GetCpsBySn(logger, sn) + if err != nil { + logger.Warnf("GetInstanceBySn.GetCpsBySn error, sn:%s, error:%s", sn, err.Error()) + return nil, err + } + instanceEntity, err := GetInstanceById(logger, deviceEntity.InstanceID) + if err != nil { + logger.Warnf("GetInstanceBySn.GetInstanceById error, instance_id:%s, error:%s", deviceEntity.InstanceID, err.Error()) + return nil, err + } + return instanceEntity, nil + +} + +func InsertMessage(logger *log.Logger, message *WebMessage) (err error) { + + return Create(logger, IronicWdb, message).Error + +} diff --git a/oob-log-alert/go.mod b/oob-log-alert/go.mod new file mode 100644 index 0000000..541bdf7 --- /dev/null +++ b/oob-log-alert/go.mod @@ -0,0 +1,72 @@ +module coding.jd.com/aidc-bmp/oob-log-alert + +go 1.17 + +require ( + coding.jd.com/aidc-bmp/bmp-openapi-sdk v0.0.0-00010101000000-000000000000 + coding.jd.com/aidc-bmp/bmp_log v0.0.0-00010101000000-000000000000 + git.jd.com/cps-golang/ironic-common v0.0.0-00010101000000-000000000000 + github.com/beego/beego/v2 v2.0.6 + github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df + github.com/go-openapi/runtime v0.24.2 + github.com/go-openapi/strfmt v0.21.3 + github.com/go-redis/redis v6.15.9+incompatible + github.com/go-sql-driver/mysql v1.7.0 + github.com/jinzhu/gorm v1.9.16 + github.com/xuri/excelize/v2 v2.5.0 + golang.org/x/crypto v0.12.0 +) + +require ( + github.com/PuerkitoBio/purell v1.1.1 // indirect + github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect + github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.1.2 // indirect + github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/go-openapi/analysis v0.21.2 // indirect + github.com/go-openapi/errors v0.20.3 // indirect + github.com/go-openapi/jsonpointer v0.19.5 // indirect + github.com/go-openapi/jsonreference v0.19.6 // indirect + github.com/go-openapi/loads v0.21.1 // indirect + github.com/go-openapi/spec v0.20.4 // indirect + github.com/go-openapi/swag v0.22.3 // indirect + github.com/go-openapi/validate v0.21.0 // indirect + github.com/golang/protobuf v1.5.2 // indirect + github.com/google/go-cmp v0.5.9 // indirect + github.com/hashicorp/golang-lru v0.5.4 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect + github.com/mitchellh/mapstructure v1.4.3 // indirect + github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect + github.com/oklog/ulid v1.3.1 // indirect + github.com/onsi/ginkgo v1.16.5 // indirect + github.com/onsi/gomega v1.24.1 // indirect + github.com/opentracing/opentracing-go v1.2.0 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/prometheus/client_golang v1.12.1 // indirect + github.com/prometheus/client_model v0.2.0 // indirect + github.com/prometheus/common v0.32.1 // indirect + github.com/prometheus/procfs v0.7.3 // indirect + github.com/richardlehane/mscfb v1.0.4 // indirect + github.com/richardlehane/msoleps v1.0.3 // indirect + github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18 // indirect + github.com/xuri/efp v0.0.0-20230802181842-ad255f2331ca // indirect + go.mongodb.org/mongo-driver v1.10.0 // indirect + golang.org/x/net v0.14.0 // indirect + golang.org/x/sys v0.11.0 // indirect + golang.org/x/text v0.12.0 // indirect + google.golang.org/protobuf v1.28.0 // indirect + gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect + gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) + +replace git.jd.com/cps-golang/ironic-common => ./bmp_vendor/ironic-common + +replace coding.jd.com/aidc-bmp/bmp_log => ./bmp_vendor/bmp_log + +replace coding.jd.com/aidc-bmp/bmp-openapi-sdk => ./bmp_vendor/bmp-openapi-sdk diff --git a/oob-log-alert/go.sum b/oob-log-alert/go.sum new file mode 100644 index 0000000..457ee82 --- /dev/null +++ b/oob-log-alert/go.sum @@ -0,0 +1,722 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= +cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= +cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= +cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= +cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= +cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= +cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= +cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= +cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= +cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= +cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= +cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= +cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= +cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= +cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= +cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= +cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= +cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= +cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= +cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= +cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc= +github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= +github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= +github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y= +github.com/asaskevich/govalidator v0.0.0-20200907205600-7a23bdc65eef/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d h1:Byv0BzEl3/e6D5CLfI0j/7hiIEtvGVFPCZ7Ei2oq8iQ= +github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/beego/beego/v2 v2.0.6 h1:21Aqz3+RzUE1yP9a5xdU6LK54n9Z7NLEJtR4PE7NrPQ= +github.com/beego/beego/v2 v2.0.6/go.mod h1:CH2/JIaB4ceGYVQlYqTAFft4pVk/ol1ZkakUrUvAyns= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= +github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd h1:83Wprp6ROGeiHFAP8WJdI2RoxALQYgdllERc3N5N2DM= +github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= +github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/elazarl/go-bindata-assetfs v1.0.1 h1:m0kkaHRKEu7tUIUFVwhGGGYClXvyl4RE03qmvRTNfbw= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y= +github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= +github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df h1:Bao6dhmbTA1KFVxmJ6nBoMuOJit2yjEgLJpIMYpop0E= +github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df/go.mod h1:GJr+FCSXshIwgHBtLglIg9M2l2kQSi6QjVAngtzI08Y= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-openapi/analysis v0.21.2 h1:hXFrOYFHUAMQdu6zwAiKKJHJQ8kqZs1ux/ru1P1wLJU= +github.com/go-openapi/analysis v0.21.2/go.mod h1:HZwRk4RRisyG8vx2Oe6aqeSQcoxRp47Xkp3+K6q+LdY= +github.com/go-openapi/errors v0.19.8/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= +github.com/go-openapi/errors v0.19.9/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= +github.com/go-openapi/errors v0.20.2/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M= +github.com/go-openapi/errors v0.20.3 h1:rz6kiC84sqNQoqrtulzaL/VERgkoCyB6WdEkc2ujzUc= +github.com/go-openapi/errors v0.20.3/go.mod h1:Z3FlZ4I8jEGxjUK+bugx3on2mIAk4txuAOhlsB1FSgk= +github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= +github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs= +github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= +github.com/go-openapi/loads v0.21.1 h1:Wb3nVZpdEzDTcly8S4HMkey6fjARRzb7iEaySimlDW0= +github.com/go-openapi/loads v0.21.1/go.mod h1:/DtAMXXneXFjbQMGEtbamCZb+4x7eGwkvZCvBmwUG+g= +github.com/go-openapi/runtime v0.24.2 h1:yX9HMGQbz32M87ECaAhGpJjBmErO3QLcgdZj9BzGx7c= +github.com/go-openapi/runtime v0.24.2/go.mod h1:AKurw9fNre+h3ELZfk6ILsfvPN+bvvlaU/M9q/r9hpk= +github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M= +github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= +github.com/go-openapi/strfmt v0.21.0/go.mod h1:ZRQ409bWMj+SOgXofQAGTIo2Ebu72Gs+WaRADcS5iNg= +github.com/go-openapi/strfmt v0.21.1/go.mod h1:I/XVKeLc5+MM5oPNN7P6urMOpuLXEcNrCX/rPGuWb0k= +github.com/go-openapi/strfmt v0.21.2/go.mod h1:I/XVKeLc5+MM5oPNN7P6urMOpuLXEcNrCX/rPGuWb0k= +github.com/go-openapi/strfmt v0.21.3 h1:xwhj5X6CjXEZZHMWy1zKJxvW9AfHC9pkyUjLvHtKG7o= +github.com/go-openapi/strfmt v0.21.3/go.mod h1:k+RzNO0Da+k3FrrynSNN8F7n/peCmQQqbbXjtDfvmGg= +github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= +github.com/go-openapi/swag v0.21.1/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= +github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g= +github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= +github.com/go-openapi/validate v0.21.0 h1:+Wqk39yKOhfpLqNLEC0/eViCkzM5FVXVqrvt526+wcI= +github.com/go-openapi/validate v0.21.0/go.mod h1:rjnrwK57VJ7A8xqfpAOEKRH8yQSGUriMu5/zuPSQ1hg= +github.com/go-redis/redis v6.15.9+incompatible h1:K0pv1D7EQUjfyoMql+r/jZqCLizCGKFlFgcHWWmHQjg= +github.com/go-redis/redis v6.15.9+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc= +github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +github.com/gobuffalo/attrs v0.0.0-20190224210810-a9411de4debd/go.mod h1:4duuawTqi2wkkpB4ePgWMaai6/Kc6WEz83bhFwpHzj0= +github.com/gobuffalo/depgen v0.0.0-20190329151759-d478694a28d3/go.mod h1:3STtPUQYuzV0gBVOY3vy6CfMm/ljR4pABfrTeHNLHUY= +github.com/gobuffalo/depgen v0.1.0/go.mod h1:+ifsuy7fhi15RWncXQQKjWS9JPkdah5sZvtHc2RXGlg= +github.com/gobuffalo/envy v1.6.15/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI= +github.com/gobuffalo/envy v1.7.0/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI= +github.com/gobuffalo/flect v0.1.0/go.mod h1:d2ehjJqGOH/Kjqcoz+F7jHTBbmDb38yXA598Hb50EGs= +github.com/gobuffalo/flect v0.1.1/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI= +github.com/gobuffalo/flect v0.1.3/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI= +github.com/gobuffalo/genny v0.0.0-20190329151137-27723ad26ef9/go.mod h1:rWs4Z12d1Zbf19rlsn0nurr75KqhYp52EAGGxTbBhNk= +github.com/gobuffalo/genny v0.0.0-20190403191548-3ca520ef0d9e/go.mod h1:80lIj3kVJWwOrXWWMRzzdhW3DsrdjILVil/SFKBzF28= +github.com/gobuffalo/genny v0.1.0/go.mod h1:XidbUqzak3lHdS//TPu2OgiFB+51Ur5f7CSnXZ/JDvo= +github.com/gobuffalo/genny v0.1.1/go.mod h1:5TExbEyY48pfunL4QSXxlDOmdsD44RRq4mVZ0Ex28Xk= +github.com/gobuffalo/gitgen v0.0.0-20190315122116-cc086187d211/go.mod h1:vEHJk/E9DmhejeLeNt7UVvlSGv3ziL+djtTr3yyzcOw= +github.com/gobuffalo/gogen v0.0.0-20190315121717-8f38393713f5/go.mod h1:V9QVDIxsgKNZs6L2IYiGR8datgMhB577vzTDqypH360= +github.com/gobuffalo/gogen v0.1.0/go.mod h1:8NTelM5qd8RZ15VjQTFkAW6qOMx5wBbW4dSCS3BY8gg= +github.com/gobuffalo/gogen v0.1.1/go.mod h1:y8iBtmHmGc4qa3urIyo1shvOD8JftTtfcKi+71xfDNE= +github.com/gobuffalo/logger v0.0.0-20190315122211-86e12af44bc2/go.mod h1:QdxcLw541hSGtBnhUc4gaNIXRjiDppFGaDqzbrBd3v8= +github.com/gobuffalo/mapi v1.0.1/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc= +github.com/gobuffalo/mapi v1.0.2/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc= +github.com/gobuffalo/packd v0.0.0-20190315124812-a385830c7fc0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4= +github.com/gobuffalo/packd v0.1.0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4= +github.com/gobuffalo/packr/v2 v2.0.9/go.mod h1:emmyGweYTm6Kdper+iywB6YK5YzuKchGtJQZ0Odn4pQ= +github.com/gobuffalo/packr/v2 v2.2.0/go.mod h1:CaAwI0GPIAv+5wKLtv8Afwl+Cm78K/I/VCm/3ptBN+0= +github.com/gobuffalo/syncx v0.0.0-20190224160051-33c29581e754/go.mod h1:HhnNqWY95UYwwW3uSASeV7vtgYkT2t16hJgV3AEPUpw= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o= +github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.0.1 h1:HjfetcXq097iXP0uoPCdnM4Efp5/9MsM0/M+XOTeR3M= +github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= +github.com/karrick/godirwalk v1.8.0/go.mod h1:H5KPZjojv4lE+QYImBI8xVtrBRgYrIVsaRPx4tDPEn4= +github.com/karrick/godirwalk v1.10.3/go.mod h1:RoGL9dQei4vP9ilrpETWE8CLOZ1kiN0LhBygSwrAsHA= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.10.5 h1:J+gdV2cUmX7ZqL2B0lFcW0m+egaHC2V3lpO8nWxyYiQ= +github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/markbates/oncer v0.0.0-20181203154359-bf2de49a0be2/go.mod h1:Ld9puTsIW75CHf65OeIOkyKbteujpZVXDpWK6YGZbxE= +github.com/markbates/safe v1.0.1/go.mod h1:nAqgmRi7cY2nqMc92/bSEeQA+R4OheNU2T1kNSCBdG0= +github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus= +github.com/mattn/go-sqlite3 v1.14.7 h1:fxWBnXkxfM6sRiuH3bqJ4CfzZojMOLVc0UTsTglEghA= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/mapstructure v1.4.3 h1:OVowDSCllw/YjdLkam3/sm7wEtOy59d8ndGgCcyj8cs= +github.com/mitchellh/mapstructure v1.4.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= +github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= +github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= +github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.24.1 h1:KORJXNNTzJXzu4ScJWssJfJMnJ+2QJqhoQSRwNlze9E= +github.com/onsi/gomega v1.24.1/go.mod h1:3AOiACssS3/MajrniINInwbfOOtfZvplPzuRSmvt1jM= +github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/pelletier/go-toml v1.7.0/go.mod h1:vwGMzjaWMwyfHwgIBhI2YUM4fB6nL6lVAvS1LBMMhTE= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= +github.com/prometheus/client_golang v1.12.1 h1:ZiaPsmm9uiBeaSMRznKsCDNtPCS0T3JVDGF+06gjBzk= +github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= +github.com/prometheus/common v0.32.1 h1:hWIdL3N2HoUx3B8j3YN9mWor0qhY/NlEKZEaXxuIRh4= +github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= +github.com/prometheus/procfs v0.7.3 h1:4jVXhlkAyzOScmCkXBTOLRLTz8EeU+eyjrwB/EPq0VU= +github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= +github.com/richardlehane/mscfb v1.0.3/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk= +github.com/richardlehane/mscfb v1.0.4 h1:WULscsljNPConisD5hR0+OyZjwK46Pfyr6mPu5ZawpM= +github.com/richardlehane/mscfb v1.0.4/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk= +github.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg= +github.com/richardlehane/msoleps v1.0.3 h1:aznSZzrwYRl3rLKRT3gUk9am7T/mLNSnJINvN0AQoVM= +github.com/richardlehane/msoleps v1.0.3/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg= +github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18 h1:DAYUYH5869yV94zvCES9F51oYtN5oGlwjxJJz7ZCnik= +github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= +github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= +github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs= +github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g= +github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM= +github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8= +github.com/xuri/efp v0.0.0-20210322160811-ab561f5b45e3/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI= +github.com/xuri/efp v0.0.0-20230802181842-ad255f2331ca h1:uvPMDVyP7PXMMioYdyPH+0O+Ta/UO1WFfNYMO3Wz0eg= +github.com/xuri/efp v0.0.0-20230802181842-ad255f2331ca/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI= +github.com/xuri/excelize/v2 v2.5.0 h1:nDDVfX0qaDuGjAvb+5zTd0Bxxoqa1Ffv9B4kiE23PTM= +github.com/xuri/excelize/v2 v2.5.0/go.mod h1:rSu0C3papjzxQA3sdK8cU544TebhrPUoTOaGPIh0Q1A= +github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= +github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.mongodb.org/mongo-driver v1.7.3/go.mod h1:NqaYOwnXWr5Pm7AOpO5QFxKJ503nbMse/R79oO62zWg= +go.mongodb.org/mongo-driver v1.7.5/go.mod h1:VXEWRZ6URJIkUq2SCAyapmhH0ZLRBP+FT4xhp5Zvxng= +go.mongodb.org/mongo-driver v1.8.3/go.mod h1:0sQWfOeY63QTntERDJJ/0SuKK0T1uVSgKCuAROlKEPY= +go.mongodb.org/mongo-driver v1.10.0 h1:UtV6N5k14upNp4LTduX0QCufG124fSu25Wz9tu94GLg= +go.mongodb.org/mongo-driver v1.10.0/go.mod h1:wsihk0Kdgv8Kqu1Anit4sfK+22vSFbUrAVEYRhCXrA8= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= +go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190422162423-af44ce270edf/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= +golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.12.0 h1:tFM/ta59kqch6LlvYnPa0yx5a83cL2nHflFhYKvv9Yk= +golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb h1:fqpd0EBDzlHRCjiphRR5Zo/RSWWQlWv34418dnEixWk= +golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= +golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.14.0 h1:BONx9s002vGdD9umnlX1Po8vOZmrgH34qlHcD1MfK14= +golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190412183630-56d357773e84/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190419153524-e8e3143a4f4a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190531175056-4c3a928424d2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM= +golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.11.0 h1:F9tnn/DA/Im8nCwm+fX+1/eBwi4qFjRT++MhtVC4ZX0= +golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.12.0 h1:k+n5B8goJNdU7hSvEtMUz3d1Q6D/XW4COJSJR6fN0mc= +golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190329151228-23e29df326fe/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190416151739-9c9e1878f421/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190420181800-aa740d480789/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= +google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= +google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= +google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= +google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk= +gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE= +gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200605160147-a5ece683394c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= +rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/oob-log-alert/log/.cmd b/oob-log-alert/log/.cmd new file mode 100644 index 0000000..ad9e572 --- /dev/null +++ b/oob-log-alert/log/.cmd @@ -0,0 +1 @@ +rm aaa.log log-alert.log oob-log-alert.2023-03-08.001.log oob-log-alert.2023-03-31.001.log oob-log-alert.2023-04-01.001.log oob-log-alert.2023-04-02.001.log oob-log-alert.2023-04-03.001.log oob-log-alert.2023-04-04.001.log oob-log-alert.2023-04-05.001.log oob-log-alert.2023-04-06.001.log oob-log-alert.log run.log diff --git a/oob-log-alert/main.go b/oob-log-alert/main.go new file mode 100644 index 0000000..5ee788d --- /dev/null +++ b/oob-log-alert/main.go @@ -0,0 +1,169 @@ +package main + +import ( + "flag" + "fmt" + "os" + "os/signal" + "syscall" + + "coding.jd.com/aidc-bmp/oob-log-alert/crontab" + "coding.jd.com/aidc-bmp/oob-log-alert/dao" + "coding.jd.com/aidc-bmp/oob-log-alert/util" + + _ "coding.jd.com/aidc-bmp/oob-log-alert/router" + "coding.jd.com/aidc-bmp/oob-log-alert/service" + + "github.com/beego/beego/v2/adapter/toolbox" + "github.com/beego/beego/v2/core/logs" + + "github.com/beego/beego/v2/client/orm" + "github.com/beego/beego/v2/server/web" + _ "github.com/go-sql-driver/mysql" +) + +const ( + defaultConfigFile = "conf/alert-config.ini" +) + +var configFile = flag.String("c", defaultConfigFile, "specify config file") +var helpFlag = flag.Bool("h", false, "print help") + +func init() { + flag.Usage = usage +} + +func main() { + + // parse flag + flag.Parse() + + if *helpFlag { + flag.Usage() + exit(0) + } + + // initial Config From file + if err := web.LoadAppConfig("ini", *configFile); err != nil { + fmt.Println("LoadAppConfig() Error:" + err.Error()) + exit(1) + } + + // init log + logConfig := "{\"filename\":\"" + web.AppConfig.DefaultString("app.alert-log-file", "/var/log/bmp/bmp-oob-alert/bmp-log-alert.log") + "\",\"level\":" + web.AppConfig.DefaultString("app.log-level", "7") + "}" + logs.SetLogger(logs.AdapterFile, logConfig) + logs.EnableFuncCallDepth(true) + + logs.Info("========CPS-OOB-ALERT Start========") + + // initial redis + // initial redis + rNamespace, _ := web.AppConfig.String("bmp_redis_namespace") + rIdc, _ := web.AppConfig.String("app.idc") + rhost, _ := web.AppConfig.String("bmp_redis_host") + rport, _ := web.AppConfig.String("bmp_redis_port") + rAddr := fmt.Sprintf("%s:%s", rhost, rport) + rPasswd, _ := web.AppConfig.String("bmp_redis_password") + rDb, _ := web.AppConfig.Int("bmp_redis_db") + + if err := util.InitRedis(rNamespace, rIdc, rAddr, rPasswd, rDb); err != nil { + logs.Warn("Redis Connect Error, Ping result : %s", err.Error()) + os.Exit(0) + } + defer util.RedisUtil.Close() + + // init Database + host, _ := web.AppConfig.String("bmp_db_host") + port, _ := web.AppConfig.String("bmp_db_port") + user, _ := web.AppConfig.String("bmp_db_user") + password, _ := web.AppConfig.String("bmp_db_password") + name, _ := web.AppConfig.String("bmp_db_name") + //root:admin@tcp(10.226.192.113:3306)/aidc_bmp?charset=utf8&parseTime=true&charset=utf8&loc=Asia%2FShanghai + mysqlUrn := user + ":" + password + "@tcp(" + host + ":" + port + ")/" + name + "?charset=utf8&parseTime=true&loc=Local" + if err := orm.RegisterDataBase("default", "mysql", mysqlUrn); err != nil { + logs.Warn("Mysql Connect Error : %s", err.Error()) + exit(0) + } + // create table + // orm.RunSyncdb("default", false, true) + orm.Debug = true + dao.InitGormDb(mysqlUrn) + + // register exit func + signalChan := make(chan os.Signal, 1) + signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL) + go func() { + <-signalChan + exit(0) + }() + + // fmt.Println("[DEBUG]", web.AppConfig.String("redis.addr")) + + // init HealthCheck + // toolbox.AddHealthCheck("Redis", &service.RedisCheck{}) + // toolbox.AddHealthCheck("Mysql", &service.MySQLCheck{}) + + // init powerstatus check task + // dailyInstanceStatusCron, _ := web.AppConfig.String("alert.daily-instance-status-cron") + // powerStatusTask := toolbox.NewTask("PowerStatus", dailyInstanceStatusCron, service.DoStaticCpsPowerState) + // err := powerStatusTask.Run() + // if err != nil { + // logs.Error("powerStatusTask() Error : " + err.Error()) + // } + // toolbox.AddTask("PowerStatus", powerStatusTask) + + // init daily report task + // dailyReportCron, _ := web.AppConfig.String("alert.daily-report-cron") + // dailReportTask := toolbox.NewTask("DailyReport", dailyReportCron, service.DailReportEvent) + // err = dailReportTask.Run() + // if err != nil { + // logs.Error("dailReportTask() Error : " + err.Error()) + // } + // toolbox.AddTask("DailyReport", dailReportTask) + + //定时任务同步device数据到redis,供agent使用 + deviceSyncCron, _ := web.AppConfig.String("app.sync-device-cron") + syncDeviceTask := toolbox.NewTask("SyncDeviceTask", deviceSyncCron, crontab.SyncDeviceToRedis) + err := syncDeviceTask.Run() + if err != nil { + logs.Error("syncDeviceTask() Error : " + err.Error()) + } + toolbox.AddTask("SyncDeviceTask", syncDeviceTask) + + toolbox.StartTask() + defer toolbox.StopTask() + + // init event subscribe + ipmiLogpath, _ := web.AppConfig.String("alert.save-ipmi-logpath") + if err := service.InitAlert( + web.AppConfig.DefaultBool("alert.save-ipmi-log", false), + ipmiLogpath); err != nil { + + logs.Critical("Alert Init Error") + exit(3) + } + + util.InitOpenapi() + + // start web + web.Run() + +} + +func usage() { + + fmt.Printf(`Usage: oob-log-alert [-c configfile] +Options: + +`) + flag.PrintDefaults() +} + +func exit(result int) { + + util.RedisUtil.Close() + + logs.Info("========CPS-OOB-ALERT Exit========") + + os.Exit(result) +} diff --git a/oob-log-alert/object/CPSError.go b/oob-log-alert/object/CPSError.go new file mode 100644 index 0000000..92b7f89 --- /dev/null +++ b/oob-log-alert/object/CPSError.go @@ -0,0 +1,32 @@ +package object + +// +const ( + MonitorSuccess = iota + MonitorOOBError + MonitorUnimplement + MonitorUnknownCPS + MonitorCPSiLOBlank + MonitorCPSFiltered + MonitorOtherError +) + +// NewMonitorCode new a ParseCode +func NewMonitorCode(code int, text string) error { + return &MonitorCode{code, text} +} + +// MonitorCode Parser process error +type MonitorCode struct { + c int + s string +} + +func (e *MonitorCode) Error() string { + return e.s +} + +// Code return result code +func (e *MonitorCode) Code() int { + return e.c +} diff --git a/oob-log-alert/object/CPSObject.go b/oob-log-alert/object/CPSObject.go new file mode 100644 index 0000000..0c7396c --- /dev/null +++ b/oob-log-alert/object/CPSObject.go @@ -0,0 +1,161 @@ +package object + +import ( + "encoding/json" + "fmt" +) + +type CMDBObjectJD struct { + Asset string `json:"asset,omitempty"` + Cabinet string `json:"cabinet,omitempty"` + Configure string `json:"configure,omitempty"` + Cost string `json:"cost,omitempty"` + CreatedAt string `json:"created_at,omitempty"` + Department string `json:"department,omitempty"` + DeviceName string `json:"device_name,omitempty"` + DeviceSn string `json:"device_sn,omitempty"` + EthGateway string `json:"eth_gateway,omitempty"` + EthIP string `json:"eth_ip,omitempty"` + EthMac string `json:"eth_mac,omitempty"` + EthMask string `json:"eth_mask,omitempty"` + EthSwitchIP string `json:"eth_switch_ip,omitempty"` + EthSwitchPort string `json:"eth_switch_port,omitempty"` + Idc string `json:"idc,omitempty"` + IdcID int `json:"idc_id,omitempty"` + IloGateway string `json:"ilo_gateway"` + IloIP string `json:"ilo_ip"` + IloMac string `json:"ilo_mac"` + IloMask string `json:"ilo_mask"` + IloSwitchIP string `json:"ilo_switch_ip"` + IloSwitchPort string `json:"ilo_switch_port"` + MaintenanceEnd string `json:"maintenance_end"` + MaintenanceStart string `json:"maintenance_start"` + MaintenanceStatus int `json:"maintenance_status"` + Manufacturer string `json:"manufacturer"` + Model string `json:"model"` + Monitor string `json:"monitor"` + Nodeid int `json:"nodeid"` + OpAssetNumber string `json:"op_asset_number"` + OpGroup []string `json:"op_group"` + Operation string `json:"operation"` + OrganizationCode string `json:"organization_code"` + OsKernel string `json:"os_kernel"` + OsVersion string `json:"os_version"` + Package string `json:"package"` + Sn string `json:"sn"` + Type string `json:"type"` + UPosition string `json:"u_position"` + UpDown string `json:"up_down"` +} + +type CMDBObjectJDCloud struct { + Cabinet struct { + Code string `json:"code,omitempty"` + ID int `json:"id,omitempty"` + IdcID int `json:"idc_id,omitempty"` + } `json:"cabinet"` + DeviceSn string `json:"device_sn,omitempty"` + Eth struct { + DeviceSn string `json:"device_sn,omitempty"` + Gateway string `json:"gateway,omitempty"` + IP string `json:"ip,omitempty"` + Mac string `json:"mac,omitempty"` + Mask string `json:"mask,omitempty"` + SwitchIP string `json:"switch_ip,omitempty"` + SwitchPort string `json:"switch_port,omitempty"` + Type string `json:"type,omitempty"` + } `json:"eth,omitempty"` + Idc struct { + CnName string `json:"cn_name,omitempty"` + ID int `json:"id,omitempty"` + } `json:"idc,omitempty"` + Ilo struct { + DeviceSn string `json:"device_sn,omitempty"` + Gateway string `json:"gateway,omitempty"` + IP string `json:"ip,omitempty"` + Mac string `json:"mac,omitempty"` + Mask string `json:"mask,omitempty"` + SwitchIP string `json:"switch_ip,omitempty"` + SwitchPort string `json:"switch_port,omitempty"` + Type string `json:"type,omitempty"` + } `json:"ilo,omitempty"` + IloGateway string `json:"ilo_gateway,omitempty"` + IloIP string `json:"ilo_ip,omitempty"` + IloMac string `json:"ilo_mac,omitempty"` + IloMask string `json:"ilo_mask,omitempty"` + IloSwitchIP string `json:"ilo_switch_ip,omitempty"` + IloSwitchPort string `json:"ilo_switch_port,omitempty"` + Manufacturer string `json:"manufacturer,omitempty"` + Model string `json:"model,omitempty"` + OpGroup []struct { + ID int `json:"id,omitempty"` + Name string `json:"name,omitempty"` + } `json:"op_group,omitempty"` + Organization struct { + Fullname string `json:"fullname,omitempty"` + ID int `json:"id,omitempty"` + OrganizationCode string `json:"organization_code,omitempty"` + } `json:"organization,omitempty"` + Package string `json:"package,omitempty"` + Pub struct { + DeviceSn string `json:"device_sn,omitempty"` + Gateway string `json:"gateway,omitempty"` + IP string `json:"ip,omitempty"` + Mac string `json:"mac,omitempty"` + Mask string `json:"mask,omitempty"` + SwitchIP string `json:"switch_ip,omitempty"` + SwitchPort string `json:"switch_port,omitempty"` + Type string `json:"type,omitempty"` + } `json:"pub,omitempty"` + UEnd int `json:"u_end,omitempty"` + UStart int `json:"u_start,omitempty"` +} + +// CPSRecord CPS information +type CPSRecord struct { + Clazz string `json:"clazz,omitempty"` + SN string `json:"sn,omitempty"` + IdcId string `json:"idc_id,omitempty"` + InstanceID string `json:"instance_id,omitempty"` + InstanceName string `json:"instance_name,omitempty"` + Pin string `json:"pin,omitempty"` + Status string `json:"manage_status,omitempty"` + IloIP string `json:"ilo_ip,omitempty"` + Brand string `json:"brand,omitempty"` + Model string `json:"model,omitempty"` + Package string `json:"package,omitempty"` + Cabinet string `json:"cabinet,omitempty"` + UPosition string `json:"u_position,omitempty"` + Ipv4 string `json:"ipv4"` + DeviceType string `json:"device_type"` + IloUser string `json:"ilo_user"` + IloPass string `json:"ilo_pass"` +} + +// CPSObject store CPS list per IDC ID +type CPSObject struct { + Idc string `json:"idc,omitempty"` + CPSs []CPSRecord `json:"cps,omitempty"` +} + +//JSON return JSON string +func (c CPSObject) JSON() (string, error) { + + json, err := json.Marshal(c.CPSs) + if err != nil { + fmt.Println("CPSObject to JSON error:" + err.Error()) + return "", err + } + return string(json), nil +} + +// JSON return JSON string +func (c CPSRecord) JSON() (string, error) { + + json, err := json.Marshal(c) + if err != nil { + fmt.Println("CPSRecord to JSON error:" + err.Error()) + return "", err + } + return string(json), nil +} diff --git a/oob-log-alert/object/CPUObject.go b/oob-log-alert/object/CPUObject.go new file mode 100644 index 0000000..d0b1d17 --- /dev/null +++ b/oob-log-alert/object/CPUObject.go @@ -0,0 +1,36 @@ +package object + +import ( + "encoding/json" + "fmt" +) + +// CPURecord CPU record +type CPURecord struct { + FQDD string // CPU.Socket.1 + DeviceType string // CPU + NumberOfProcessorCores string // 6 + Model string // Intel(R) Xeon(R) CPU E5-2620 0 @ 2.00GHz + CurrentClockSpeed string // 2000 MHz + CPUStatus string // Disk 0 in Backplane 1 of Integrated RAID Controller 1 + PrimaryStatus string // OK + +} + +// CPUObject , the type of CPU information from Out-of-Band +type CPUObject struct { + Status bool `json:"status,omitempty"` + Count int `json:"count,omitempty"` + CPUs []CPURecord `json:"detail,omitempty"` +} + +//JSON return JSON string +func (c CPUObject) JSON() (string, error) { + + json, err := json.Marshal(c.CPUs) + if err != nil { + fmt.Println("CPUObject to JSON error:" + err.Error()) + return "", err + } + return string(json), nil +} diff --git a/oob-log-alert/object/Const.go b/oob-log-alert/object/Const.go new file mode 100644 index 0000000..47a43d0 --- /dev/null +++ b/oob-log-alert/object/Const.go @@ -0,0 +1,45 @@ +package object + +const ( + // ConfigKey store configration, each field store different config + ConfigKey string = "Config" + + // FilterKey store filters, each field store different manufacurer filter. + FilterKey string = "Filter" + + // LogChannel log alert pubsub channel namespace + LogChannel string = "Logs" + + // OOBErrorChannel OOB access error pubsub channel namespace + OOBErrorChannel string = "OOBError" + + // PDisksField redis store field name + PDisksField string = "PDisks" + + // CPUsField redis store field name + CPUsField string = "CPUs" + + // MemsField redis store field name + MemsField string = "Mems" + + // NicsField redis store field name + NicsField string = "Nics" + + // CodeField code store monitor result + CodeField string = "Code" + + // ErrorCountField count for oob access error + ErrorCountField string = "OOBErrorCount" + + // MessageField code store monitor result message + MessageField string = "Message" + + // LogCollectTimeField store last successful log collect time + LogCollectTimeField string = "LogCollectTime" + + // LogSelInfoField store last ipmi system event log info + LogSelInfoField string = "LogSelInfo" + + //LastCollectOOBTimeField 最后一次oob收集的时间,是目标机器的oob带外时间,不是目标机器的系统时间,也不是agent服务器的时间 + LastCollectOOBTimeField string = "LastCollectOobTime" +) diff --git a/oob-log-alert/object/FRUObject.go b/oob-log-alert/object/FRUObject.go new file mode 100644 index 0000000..3d71ea1 --- /dev/null +++ b/oob-log-alert/object/FRUObject.go @@ -0,0 +1,24 @@ +package object + +import ( + "encoding/json" + "fmt" +) + +// FRUObject type of IPMI FRU Information +type FRUObject struct { + Manufacturer string + SN string + Model string +} + +// JSON return json string +func (l FRUObject) JSON() (string, error) { + + json, err := json.Marshal(l) + if err != nil { + fmt.Println("FRUObject to JSON error:" + err.Error()) + return "", err + } + return string(json), nil +} diff --git a/oob-log-alert/object/LogObject.go b/oob-log-alert/object/LogObject.go new file mode 100644 index 0000000..6897f4f --- /dev/null +++ b/oob-log-alert/object/LogObject.go @@ -0,0 +1,7 @@ +package object + +// LogObject type of Event log from dell lifecyclelog or IPMI +type LogObject struct { + SeqNumber string //664 + Messages []string +} diff --git a/oob-log-alert/object/MemObject.go b/oob-log-alert/object/MemObject.go new file mode 100644 index 0000000..f56cf8a --- /dev/null +++ b/oob-log-alert/object/MemObject.go @@ -0,0 +1,39 @@ +package object + +import ( + "encoding/json" + "fmt" +) + +// MemRecord Memory record +type MemRecord struct { + FQDD string // DIMM.Socket.A1 + DeviceType string // Memory + MemoryType string // DDR-3 + SerialNumber string // 134799E0 + Manufacturer string // Samsung + Speed string // 1333 MHz + CurrentOperatingSpeed string // 1333 MHz + Rank string // Double Rank + Size string // 32768 MB + PrimaryStatus string // OK + +} + +// MemObject , the type of Memory information from Out-of-Band +type MemObject struct { + Status bool `json:"status,omitempty"` + Count int `json:"count,omitempty"` + Mems []MemRecord `json:"detail,omitempty"` +} + +//JSON return JSON string +func (c MemObject) JSON() (string, error) { + + json, err := json.Marshal(c.Mems) + if err != nil { + fmt.Println("MemObject to JSON error:" + err.Error()) + return "", err + } + return string(json), nil +} diff --git a/oob-log-alert/object/NicObject.go b/oob-log-alert/object/NicObject.go new file mode 100644 index 0000000..c12720a --- /dev/null +++ b/oob-log-alert/object/NicObject.go @@ -0,0 +1,38 @@ +package object + +import ( + "encoding/json" + "fmt" +) + +// NicRecord NIC record +type NicRecord struct { + FQDD string // NIC.Integrated.1-1-1 + DeviceType string // NIC + PermanentMACAddress string // 24:6E:96:B0:FA:8E + CurrentMACAddress string // 24:6E:96:B0:FA:8E + ProductName string // Intel(R) Ethernet 10G 4P X520/I350 rNDC - 24:6E:96:03:43:E0 + DeviceDescription string // Integrated NIC 1 Port 1 Partition 1 + LinkSpeed string // 10 Gbps + LinkDuplex string // Full Duplex + LinkStatus string // OK + +} + +// NicObject , the type of NIC information from Out-of-Band +type NicObject struct { + Status bool `json:"status,omitempty"` + Count int `json:"count,omitempty"` + Nics []NicRecord `json:"detail,omitempty"` +} + +//JSON return JSON string +func (c NicObject) JSON() (string, error) { + + json, err := json.Marshal(c.Nics) + if err != nil { + fmt.Println("NicObject to JSON error:" + err.Error()) + return "", err + } + return string(json), nil +} diff --git a/oob-log-alert/object/Object.go b/oob-log-alert/object/Object.go new file mode 100644 index 0000000..8736824 --- /dev/null +++ b/oob-log-alert/object/Object.go @@ -0,0 +1,6 @@ +package object + +// Object ,the base interface for different object +type Object interface { + JSON() (string, error) +} diff --git a/oob-log-alert/object/PhysicalDiskObject.go b/oob-log-alert/object/PhysicalDiskObject.go new file mode 100644 index 0000000..a9277bb --- /dev/null +++ b/oob-log-alert/object/PhysicalDiskObject.go @@ -0,0 +1,48 @@ +package object + +import ( + "encoding/json" + "fmt" +) + +// PhysicalDiskRecord Physical Disk record +type PhysicalDiskRecord struct { + FQDD string // Disk.Bay.0:Enclosure.Internal.0-1:RAID.Integrated.1-1 + DeviceType string // PhysicalDisk + SerialNumber string // WXU1E13TLDN2 + ManufacturingYear string // 2013 + ManufacturingWeek string // 23 + ManufacturingDay string // 7 + Manufacturer string // WD + Model string // WD3001BKHG + Slot string // 0 + DeviceDescription string // Disk 0 in Backplane 1 of Integrated RAID Controller 1 + UsedSizeInBytes string // 299439751168 Bytes + FreeSizeInBytes string // 0 Bytes + SizeInBytes string // 299439751168 Bytes + PrimaryStatus string // OK + RollupStatus string // OK + RaidStatus string // Online + HotSpareStatus string // No + MediaType string // HDD + MaxCapableSpeed string // 6Gbs + DriveFormFactor string // 2.5 inch +} + +// PhysicalDiskObject , the type of Physical Disk information from Out-of-Band +type PhysicalDiskObject struct { + Status bool `json:"status,omitempty"` + Count int `json:"count,omitempty"` + PDisks []PhysicalDiskRecord `json:"detail,omitempty"` +} + +//JSON return JSON string +func (o PhysicalDiskObject) JSON() (string, error) { + + json, err := json.Marshal(o.PDisks) + if err != nil { + fmt.Println("PhysicalDiskObject to JSON error:" + err.Error()) + return "", err + } + return string(json), nil +} diff --git a/oob-log-alert/oob-log-alert b/oob-log-alert/oob-log-alert new file mode 100755 index 0000000..07655de Binary files /dev/null and b/oob-log-alert/oob-log-alert differ diff --git a/oob-log-alert/oob-log-alert.Dockerfile b/oob-log-alert/oob-log-alert.Dockerfile new file mode 100644 index 0000000..1b6cd2e --- /dev/null +++ b/oob-log-alert/oob-log-alert.Dockerfile @@ -0,0 +1,25 @@ +FROM quay.io/goswagger/swagger AS SDK +ENV GOPROXY https://goproxy.cn +WORKDIR /usr/src/bmp-openapi +COPY ./bmp-openapi . +RUN swagger generate spec -o ./swagger.yml +RUN swagger validate swagger.yml +RUN mkdir -p ../bmp-openapi-sdk +RUN cd ../bmp-openapi-sdk && go mod init coding.jd.com/aidc-bmp/bmp-openapi-sdk +RUN cd ../bmp-openapi +RUN swagger generate client -f swagger.yml --target=../bmp-openapi-sdk + +FROM golang:1.17-alpine AS builder +ENV GOPROXY https://goproxy.cn +WORKDIR /usr/src/bmp-oob-alert +COPY ./oob-log-alert . +COPY --from=SDK /usr/src/bmp-openapi-sdk ./bmp_vendor/bmp-openapi-sdk +RUN go mod tidy -compat=1.17 +RUN go mod vendor +RUN go build -o /tmp/bmp-oob-alert . + +FROM alpine:3.16 +WORKDIR /home/bmp/bmp-oob-alert +COPY --from=builder /tmp/bmp-oob-alert . +COPY ./oob-log-alert/conf ./conf +CMD ["./bmp-oob-alert"] diff --git a/oob-log-alert/router/router.go b/oob-log-alert/router/router.go new file mode 100644 index 0000000..8c18010 --- /dev/null +++ b/oob-log-alert/router/router.go @@ -0,0 +1,47 @@ +package router + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/controllers" + + beego "github.com/beego/beego/v2/server/web" +) + +func init() { + + INS := beego.NewNamespace("/describeInstanceMonitor", + // init api controller + beego.NSRouter("/", &controllers.DescribeInstanceMonitorController{}, "get:Get"), + ) + beego.AddNamespace(INS) + + InnerNS := beego.NewNamespace("/inner", + // init api controller + beego.NSRouter("/describeInstanceMonitor", &controllers.DescribeInstanceMonitorController{}, "get:Get"), + beego.NSRouter("/trigPowerStatusReport", &controllers.InstanceStatusReportController{}, "get:Get"), + beego.NSRouter("/trigDailyReport", &controllers.DailyReportController{}, "get:Get"), + ) + beego.AddNamespace(InnerNS) + + v1NS := beego.NewNamespace("/v1/oob-alert", + //新增接口 + beego.NSRouter("/device/status", &controllers.DeviceController{}, "get:GetDeviceStatus"), + // beego.NSRouter("/device/getPowerStatusDiff", &controllers.DeviceController{}, "get:GetPowerStatusDiff"), //获取状态不一致接口 + // beego.NSRouter("/device/syncPowerStatus", &controllers.DeviceController{}, "post:SyncPowerStatus"), //同步状态不一致接口 + //运营平台 + beego.NSRouter("/logs", &controllers.LogController{}, "get:GetLogCollections"), + //控制台 + beego.NSRouter("/consolelogs", &controllers.LogController{}, "get:GetLogCollectionsBySn"), + beego.NSRouter("/logs/deal", &controllers.LogController{}, "post:DealLogCollection"), + + beego.NSRouter("/rules/alert-spec-list", &controllers.RuleController{}, "get:AlertPartList"), + beego.NSRouter("/rules/alert-level-list", &controllers.RuleController{}, "get:AlertLevelList"), + beego.NSRouter("/rules", &controllers.RuleController{}, "get:RuleList"), + + beego.NSRouter("/rules/change-push", &controllers.RuleController{}, "post:ChangePush"), + beego.NSRouter("/rules/change-use", &controllers.RuleController{}, "post:ChangeUse"), + beego.NSRouter("/rules/reset", &controllers.RuleController{}, "post:RuleResetPushAndUse"), + beego.NSRouter("/custom/set-custom-info", &controllers.CustomController{}, "post:SetCustomInfo"), + beego.NSRouter("/custom/get-custom-info", &controllers.CustomController{}, "get:GetCustomInfo"), + ) + beego.AddNamespace(v1NS) +} diff --git a/oob-log-alert/service/alertService.go b/oob-log-alert/service/alertService.go new file mode 100644 index 0000000..b8aeb1d --- /dev/null +++ b/oob-log-alert/service/alertService.go @@ -0,0 +1,122 @@ +package service + +import ( + "fmt" + "strings" + "time" + + log "coding.jd.com/aidc-bmp/bmp_log" + + "coding.jd.com/aidc-bmp/oob-log-alert/object" + + "coding.jd.com/aidc-bmp/oob-log-alert/util" + "github.com/beego/beego/v2/core/logs" + beego "github.com/beego/beego/v2/server/web" + "github.com/go-redis/redis" +) + +// Alert for send Alert main +type Alert struct { + pubsub *redis.PubSub + ch <-chan *redis.Message + IsSaveLog bool + LogPath string +} + +// InitAlert initial Alert ,subscribe to Redis, +func InitAlert(isSaveLog bool, logPath string) error { + + a := &Alert{IsSaveLog: isSaveLog, LogPath: logPath} + // init subscribe + a.pubsub = util.PSubEventToRedis(object.LogChannel, object.OOBErrorChannel) + + _, err := a.pubsub.Receive() + if err != nil { + logs.Critical("psubscribe error:%s", err.Error()) + return err + } + + logs.Debug("InitAlert config", a) + a.Run() + return nil + +} + +// Run Alert Module run in a goroutine +func (a Alert) Run() { + + // Consume messages. + go func(a *Alert) { + + a.ch = a.pubsub.Channel() + logs.Debug("psubcribe success:", a.pubsub) + logs.Debug("waiting message...") + + for msg := range a.ch { + + tmp := strings.Split(msg.Channel, ":") + channel := tmp[len(tmp)-2] + deviceSN := tmp[len(tmp)-1] + + // check + if msg.Payload == "" { + continue + } + + if dailyMoreThanOnce(deviceSN, msg.Payload) { //同一设备同类型的报警,每天只报一次 + continue + } + + logPath, _ := beego.AppConfig.String("log.path") + logger := log.New(logPath + "/msg-from-oob_agent.log") + logger.SetStableFields([]string{"method", "uri", "header", "request", "response"}) + //agent过来的消息只有sn,没有requestid,临时生成 + logger.Point("logid", util.GenerateRandUuid()) + logger.TimeStart("all_t") + logger.TimeStart("self_t") + defer logger.Flush() + defer logger.TimeEnd("self_t") + defer logger.TimeEnd("all_t") + + // switch which type of message + var err error + switch channel { + case object.LogChannel: + logger.Point("task", "LogChannel") + err = LogEvent(logger, deviceSN, msg.Payload, a.IsSaveLog, a.LogPath) + case object.OOBErrorChannel: + logger.Point("task", "OOBErrorChannel") + err = CPSEvent(deviceSN, msg.Payload) + default: + continue + } + + if err != nil { + logs.Error("Alert Receive ERROR MSG:", msg, err.Error()) + } + } + }(&a) + +} + +func dailyMoreThanOnce(sn, payload string) bool { + if len(payload) > 1024 { + payload = payload[:1024] + } + k := fmt.Sprintf("%s_day_only_once_%s", sn, payload) + if v, err := util.GetObjectFromRedis(k); err == nil && v == "true" { //已经报过 + logs.Warn("Alert more than once,sn:%s, msg:%s", sn, payload) + return true + } + + current := time.Now() + t, _ := time.ParseInLocation("2006-01-02", current.Format("2006-01-02"), time.Local) + e := t.Unix() + 86400 + c := current.Unix() + ttl := int(e - c) + if err := util.SetObjectToRedisWithExpire(k, "true", ttl); err != nil { + logs.Warn("Alert set once daily info error, sn:%s, msg:%s, err:%+v", sn, payload, err) + } + return false + +} diff --git a/oob-log-alert/service/customInfoLogic.go b/oob-log-alert/service/customInfoLogic.go new file mode 100644 index 0000000..bf4be85 --- /dev/null +++ b/oob-log-alert/service/customInfoLogic.go @@ -0,0 +1,52 @@ +package service + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/dao" + "coding.jd.com/aidc-bmp/oob-log-alert/util" + + "encoding/json" + + log "coding.jd.com/aidc-bmp/bmp_log" +) + +func SetCustomInfo(logger *log.Logger, param dao.SetCustomInfoRequest) dao.CommonResponse { + userId := logger.GetPoint("userId").(string) + key := "custom_info_operation_" + userId + ":" + param.PageKey + redisValue := make(map[string]map[string]map[string]bool, 0) + redisValue["custom_info"] = param.PageValue + err := util.SetObjectToRedis(key, util.ToString(redisValue)) + if err != nil { + logger.Warnf("SetCustomInfo to redis error, key:%s", key) + } + res := dao.CommonResponse{ + Success: true, + } + return res +} +func GetCustomInfo(logger *log.Logger, param dao.QueryCustomInfoRequest) map[string]map[string]map[string]bool { + userId := logger.GetPoint("userId").(string) + key := "custom_info_operation_" + userId + ":" + param.PageKey + + result, err := util.GetObjectFromRedis(key) + if err != nil { + logger.Warnf("GetCustomInfo error, err:%s", err.Error()) + } + + if param.Reload == "true" || result == "" { + result := util.ToString(util.HeaderList[param.PageKey]) + go func() { + err := util.SetObjectToRedis(key, result) + if err != nil { + logger.Warnf("GetCustomInfo.reload.reset to redis error, key:%s", key) + } + }() + return util.HeaderList[param.PageKey] + } + + obj := make(map[string]map[string]map[string]bool, 0) //responseWeb.GetCustomInfoResponse{} + if err = json.Unmarshal([]byte(result), &obj); err != nil { + logger.Warnf("GetCustomInfo unmarshal error, key:%s, content:%s, error:%s", key, result, err.Error()) + return nil + } + return obj +} diff --git a/oob-log-alert/service/deviceService.go b/oob-log-alert/service/deviceService.go new file mode 100644 index 0000000..0b66fb9 --- /dev/null +++ b/oob-log-alert/service/deviceService.go @@ -0,0 +1,237 @@ +package service + +import ( + "errors" + "math/rand" + "regexp" + "strconv" + "time" + + log "coding.jd.com/aidc-bmp/bmp_log" + + "coding.jd.com/aidc-bmp/oob-log-alert/dao" + "coding.jd.com/aidc-bmp/oob-log-alert/util" + + "github.com/beego/beego/v2/core/logs" +) + +const ( + IN = "in" //已入库 + PUTAWAY = "putaway" //已上架 + CREATED = "created" //已创建 + PUTAWAYING = "putawaying" //上架中 + PUTAWAYFAIL = "putawayfail" //上架失败 + UNPUTAWAY = "unputaway" //下架 + UNPUTAWAYING = "unputawaying" //下架中,将“已上架”的设备执行“下架”操作的中间过程状态 + REMOVED = "removed" //已移除 + +) + +var DeviceManageStatus = map[string]string{ + IN: "已入库", + PUTAWAY: "已上架", + UNPUTAWAY: "已下架", + CREATED: "已创建", + PUTAWAYING: "上架中", + PUTAWAYFAIL: "上架失败", + UNPUTAWAYING: "下架中", + REMOVED: "已移除", +} + +func GetDeviceStatus(logger *log.Logger, req dao.GetDeviceStatusRequest) (*dao.GetDeviceStatusResponse, error) { + limit := req.PageSize + offset := (req.PageNum - 1) * req.PageSize + if limit == 0 { + offset = 0 + } + cnt, devices, err := GetDevices(logger, req.IdcId, req.Sn, limit, offset) + if err != nil { + return nil, err + } + + oobstatus, err := GetDeviceOOBstatusBySns(logger, devices) + if err != nil { + logs.Debug("GetDeviceOOBstatusBySns error:%s", err.Error()) + return nil, err + } + + return &dao.GetDeviceStatusResponse{ + Detail: oobstatus, + PageResult: dao.PageResult{ + Total: cnt, + PageNumber: req.PageNum, + PageSize: req.PageSize, + }, + }, nil + +} + +func GetDevices(logger *log.Logger, idc, sn string, limit, offset int64) (int64, []*dao.DeviceItem, error) { + + language := logger.GetPoint("language").(string) + if sn != "" { + matched, err := regexp.MatchString(`^[0-9a-zA-Z]{1,}$`, sn) + if err != nil { + return 0, nil, err + } + if !matched { + return 0, nil, errors.New("sn invalid") + } + } + + cnt, err := dao.GetCpssCount(logger, sn, idc) + if err != nil { + return 0, nil, err + } + var ds []*dao.Device + if limit == 0 { + ds, err = dao.GetCpssByCondNoLimit(logger, sn, idc) + if err != nil { + return 0, nil, err + } + + } else { + ds, err = dao.GetCpssByCond(logger, sn, idc, int(limit), int(offset)) + if err != nil { + return 0, nil, err + } + } + var idcEntity *dao.Idc + if len(ds) > 0 { + idcEntity, _ = dao.GetIdcById(logger, ds[0].IDcID) + } + devices := []*dao.DeviceItem{} + for _, d := range ds { + ds := &dao.DeviceItem{ + IdcId: d.IDcID, + IdcName: idcEntity.Name, + Sn: d.Sn, + DeviceId: d.DeviceID, + Brand: d.Brand, + Model: d.Model, + ManageStatus: d.ManageStatus, + } + if language == util.EN_US { + ds.IdcName = idcEntity.NameEn + } + devices = append(devices, ds) + + } + return cnt, devices, nil +} + +func GetDeviceOOBstatusBySns(logger *log.Logger, devices []*dao.DeviceItem) ([]*dao.DeviceStatus, error) { + + sns := []string{} + for _, d := range devices { + sns = append(sns, d.Sn) + } + + ormStatusRes, err := dao.GetOwnedStatusBySns(logger, sns) + if err != nil { + return nil, err + } + + res := map[string]*dao.DeviceStatus{} + for _, de := range devices { + res[de.Sn] = &dao.DeviceStatus{ + DeviceItem: *de, + StatusItem: dao.StatusItem{}, + } + } + for _, v := range ormStatusRes { + switch v.Owned { + case "cpu": + if v.Count > 0 { + res[v.Sn].StatusItem.CpuStatus = 1 + } + case "mem": + if v.Count > 0 { + res[v.Sn].StatusItem.MemStatus = 1 + } + case "disk": + if v.Count > 0 { + res[v.Sn].StatusItem.DiskStatus = 1 + } + case "power": + if v.Count > 0 { + res[v.Sn].StatusItem.PowerStatus = 1 + } + case "nic": + if v.Count > 0 { + res[v.Sn].StatusItem.NicStatus = 1 + } + case "other": + if v.Count > 0 { + res[v.Sn].StatusItem.OtherStatus = 1 + } + + } + } + + finalRes := []*dao.DeviceStatus{} + for _, sn := range sns { + finalRes = append(finalRes, res[sn]) + } + // for _, de := range res { + // finalRes = append(finalRes, de) + + // } + return finalRes, nil + +} + +func inArray(arr []int, v int) bool { + for _, item := range arr { + if item == v { + return true + } + } + return false +} + +// 导出Excel文件 +func ExportDeviceStatusExcel(logger *log.Logger, result []*dao.DeviceStatus) (string, string, error) { + language := logger.GetPoint("language").(string) + e := util.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + + for _, data := range result { + item := []string{ + data.Sn, // SN + data.IdcName, // idc + data.Brand, + data.Model, + data.ManageStatus, + util.StatusIntDesc(data.CpuStatus, language), + util.StatusIntDesc(data.MemStatus, language), + util.StatusIntDesc(data.DiskStatus, language), + util.StatusIntDesc(data.NicStatus, language), + util.StatusIntDesc(data.PowerStatus, language), + util.StatusIntDesc(data.OtherStatus, language), + } + if language == util.CN_ZH { + item[4] = DeviceManageStatus[data.ManageStatus] + } + sheetData = append(sheetData, item) + } + exportExcelHeader := util.ExportDeviceStatusHeader + if language == util.EN_US { + exportExcelHeader = util.ExportDeviceStatusHeaderEn + } + if err := e.SetSheetData("Sheet1", exportExcelHeader, sheetData); err != nil { + logger.Warn("create excel error:", err.Error()) + return "", "", err + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + // 生成100000到100000+900000之间的随机数,左闭右开 + downloadFileName := "device_status_list_" + time.Now().Format(util.FormatDate) + "_" + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Warn("保存excel到本地失败" + err.Error()) + return "", "", err + } + return fileName, downloadFileName, nil +} diff --git a/oob-log-alert/service/faultRuleService.go b/oob-log-alert/service/faultRuleService.go new file mode 100644 index 0000000..98cbc28 --- /dev/null +++ b/oob-log-alert/service/faultRuleService.go @@ -0,0 +1,228 @@ +package service + +import ( + "math/rand" + "strconv" + "time" + + log "coding.jd.com/aidc-bmp/bmp_log" + "coding.jd.com/aidc-bmp/oob-log-alert/dao" + "coding.jd.com/aidc-bmp/oob-log-alert/util" +) + +var owned []string = []string{ + "cpu", + "disk", + "nic", + "mem", + "power", + "other", +} + +var partsTran = map[string]string{ + "Fan": "风扇", + "PCIE Bus": "PCIE总线", + "Power Supply": "电源", + "voltage": "电压", + "Temperature": "温度", + "CPU": "CPU", + "Memory": "内存", + "Hard Disk": "硬盘", + "NIC": "网卡", +} + +var partsTran2En = map[string]string{ + "风扇": "Fan", + "PCIE总线": "PCIE Bus", + "电源": "Power Supply", + "电压": "voltage", + "温度": "Temperature", + "CPU": "CPU", + "内存": "Memory", + "硬盘": "Hard Disk", + "网卡": "NIC", +} + +func GetAllInUsedRuleIdsGroupByOwn(logger *log.Logger) (map[string][]int, error) { + faultRules, err := dao.GetFaultPushedRules(logger) + if err != nil { + return nil, err + } + res := map[string][]int{} + for _, v := range faultRules { + _, ok := res[v.Owned] + if ok { + res[v.Owned] = append(res[v.Owned], v.ID) + } else { + res[v.Owned] = []int{v.ID} + } + } + return res, nil +} + +func GetAlertPartList(logger *log.Logger) ([]string, error) { + + /* + rules, err := models.GetFaultRules() + if err != nil { + return nil, err + } + parts := map[string]struct{}{} + for _, v := range rules { + parts[v.Parts] = struct{}{} + } + res := []string{} + for k := range parts { + res = append(res, k) + } + return res, nil + */ + parts := []string{} + language := logger.GetPoint("language").(string) + if language != util.EN_US { + for _, v := range partsTran { + parts = append(parts, v) + } + } else { + for k, _ := range partsTran { + parts = append(parts, k) + } + } + + return parts, nil +} + +func GetAlertLevelList(logger *log.Logger) ([]string, error) { + + rules, err := dao.GetFaultRules(logger) + if err != nil { + return nil, err + } + levels := map[string]struct{}{} + for _, v := range rules { + levels[v.Level] = struct{}{} + } + res := []string{} + for k := range levels { + res = append(res, k) + } + return res, nil +} + +func GetRuleList(logger *log.Logger, req dao.RuleListRequest) (*dao.RuleListResponse, error) { + language := logger.GetPoint("language").(string) + limit := req.PageSize + offset := (req.PageNum - 1) * req.PageSize + if limit == 0 { + limit = 20 + offset = 0 + } + if language == util.EN_US { + req.AlertSpec = partsTran[req.AlertSpec] + } + rules, cnt, err := dao.GetRuleList(logger, req.AlertName, req.AlertSpec, req.AlertLevel, limit, offset) + if err != nil { + return nil, err + } + res := &dao.RuleListResponse{ + Detail: []*dao.RuleListResponseItem{}, + PageResult: dao.PageResult{ + Total: cnt, + PageNumber: req.PageNum, + PageSize: req.PageSize, + }, + } + for _, v := range rules { + item := &dao.RuleListResponseItem{ + RuleId: v.ID, + AlertName: v.Name, + AlertSpec: v.Parts, + AlertLevel: v.Level, + AlertDesc: v.Desc, + AlertType: v.FaultType, + // 判定条件 + AlertCondition: v.Condition, + // 判定阈值 + AlertThreshold: v.Threshold, + // 是否推送,0表示关闭,1表示开启 + PushStatus: bool2int(v.IsPush), + UseStatus: bool2int(v.IsUse), + } + if language == util.EN_US { + item.AlertSpec = partsTran2En[item.AlertSpec] + } + res.Detail = append(res.Detail, item) + } + + return res, nil +} + +// 导出Excel文件 +func ExportRulesExcel(logger *log.Logger, result []*dao.RuleListResponseItem) (string, string, error) { + language := logger.GetPoint("language").(string) + e := util.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + + for _, data := range result { + sheetData = append(sheetData, []string{ + data.AlertName, + data.AlertSpec, + data.AlertType, + data.AlertCondition, + data.AlertThreshold, + data.AlertLevel, + data.AlertDesc, + util.PushStatusIntDesc(data.PushStatus, language), + util.PushStatusIntDesc(data.UseStatus, language), + }) + } + exportExcelHeader := util.ExportRulesHeader + if language == util.EN_US { + exportExcelHeader = util.ExportRulesHeaderEn + } + if err := e.SetSheetData("Sheet1", exportExcelHeader, sheetData); err != nil { + logger.Warn("create excel error:", err.Error()) + return "", "", err + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + // 生成100000到100000+900000之间的随机数,左闭右开 + downloadFileName := "alert_rule_list_" + time.Now().Format(util.FormatDate) + "_" + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Warn("保存excel到本地失败" + err.Error()) + return "", "", err + } + return fileName, downloadFileName, nil +} + +func bool2int(b bool) int { + if b { + return 1 + } else { + return 0 + } +} + +func ChangeRulePush(logger *log.Logger, req dao.ChangePushRequest) (bool, error) { + if err := dao.ChangePushStatusByRuleId(logger, req.RuleID, int8(req.PushStatus)); err != nil { + return false, err + } + return true, nil +} + +func ChangeRuleUse(logger *log.Logger, req dao.ChangeUseRequest) (bool, error) { + if err := dao.ChangeUseStatusByRuleId(logger, req.RuleID, int8(req.UseStatus)); err != nil { + return false, err + } + return true, nil +} + +func RuleResetPushAndUse(logger *log.Logger, ids []int) (bool, error) { + + if err := dao.RuleResetPushAndUse(logger, ids); err != nil { + return false, err + } + return true, nil +} diff --git a/oob-log-alert/service/health.go b/oob-log-alert/service/health.go new file mode 100644 index 0000000..370bdf8 --- /dev/null +++ b/oob-log-alert/service/health.go @@ -0,0 +1,34 @@ +package service + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/util" +) + +// RedisCheck beego health check struct, implement Check method +type RedisCheck struct { +} + +// Check health check for redis +func (redis *RedisCheck) Check() error { + err := redis.ping() + if err != nil { + return err + } + return nil + +} + +func (redis *RedisCheck) ping() error { + return util.RedisUtil.Ping().Err() + +} + +type MySQLCheck struct { +} + +// Check health check for MySQL +func (redis *MySQLCheck) Check() error { + + return nil + +} diff --git a/oob-log-alert/service/logCollection.go b/oob-log-alert/service/logCollection.go new file mode 100644 index 0000000..f2d6be6 --- /dev/null +++ b/oob-log-alert/service/logCollection.go @@ -0,0 +1,284 @@ +package service + +import ( + "math/rand" + "strconv" + "time" + + "coding.jd.com/aidc-bmp/oob-log-alert/util" + + log "coding.jd.com/aidc-bmp/bmp_log" + "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +func GetLogCollections(logger *log.Logger, req dao.GetLogCollectionsRequest) (*dao.GetLogCollectionsResponse, error) { + + language := logger.GetPoint("language").(string) + limit := req.PageSize + offset := (req.PageNum - 1) * req.PageSize + if limit == 0 { + offset = 0 + } + if language == util.EN_US { + req.Spec = partsTran[req.Spec] + } + logCollectionItems, cnt, err := dao.GetLogCollectionsforOperation(logger, req.Sn, req.Level, req.Spec, req.IdcId, req.StartTime, req.EndTime, req.DealStatus, limit, offset) + if err != nil { + return nil, err + } + if cnt == 0 { + return &dao.GetLogCollectionsResponse{ + Detail: []*dao.LogRespItem{}, + PageResult: dao.PageResult{ + Total: 0, + PageNumber: req.PageNum, + PageSize: req.PageSize, + }, + }, nil + } + + logger.Info("logCollectionItems res:", util.ToString(logCollectionItems)) + + res := &dao.GetLogCollectionsResponse{ + Detail: []*dao.LogRespItem{}, + PageResult: dao.PageResult{ + Total: cnt, + PageNumber: req.PageNum, + PageSize: req.PageSize, + }, + } + + var idcEntity *dao.Idc + if len(logCollectionItems) > 0 { + idcEntity, _ = dao.GetIdcById(logger, logCollectionItems[0].IdcId) + } + + for _, v := range logCollectionItems { + lri := &dao.LogRespItem{ + LogId: v.ID, + Sn: v.Sn, + DeviceId: v.DeviceId, + IloIp: v.IloIp, + IdcId: v.IdcId, + IdcName: idcEntity.Name, + AlertName: v.Name, + AlertDesc: v.Desc, + AlertType: v.FaultType, + AlertPart: v.Parts, + AlertLevel: v.Level, + AlertContent: v.Content, + Count: int(v.Count), + CollectTime: v.CollectTime, + EventTime: v.EventTime, + UpdateTime: v.UpdateTime, + ManageStatus: v.ManageStatus, + } + if language == util.EN_US { + lri.IdcName = idcEntity.NameEn + lri.AlertPart = partsTran2En[lri.AlertPart] + } + if lri.Count == 0 { + lri.Status = 1 + } + + res.Detail = append(res.Detail, lri) + } + return res, nil + +} + +// 导出Excel文件 +func ExportLogCollectionsExcel(logger *log.Logger, result []*dao.LogRespItem) (string, string, error) { + language := logger.GetPoint("language").(string) + e := util.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + + for _, data := range result { + sheetData = append(sheetData, []string{ + util.ToString(data.LogId), // SN + data.Sn, // idc + data.IdcName, + data.AlertLevel, + data.AlertType, + data.AlertPart, + data.IloIp, + data.AlertDesc, + data.AlertContent, + util.LogDealStatusIntDesc(int(data.Status), language), + util.ToString(data.Count), + util.Time2String(data.CollectTime), + util.Time2String(data.EventTime), + util.Time2String(data.UpdateTime), + }) + } + exportExcelHeader := util.ExportLogCollectionsHeader + if language == util.EN_US { + exportExcelHeader = util.ExportLogCollectionsHeaderEn + } + if err := e.SetSheetData("Sheet1", exportExcelHeader, sheetData); err != nil { + logger.Warn("create excel error:", err.Error()) + return "", "", err + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + // 生成100000到100000+900000之间的随机数,左闭右开 + downloadFileName := "oob_alert_log_list_" + time.Now().Format(util.FormatDate) + "_" + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Warn("保存excel到本地失败" + err.Error()) + return "", "", err + } else { + logger.Infof("保存excel到本地成功,filename:%s", fileName) + } + return fileName, downloadFileName, nil +} + +func GetLogCollectionsBySn(logger *log.Logger, req dao.GetLogCollectionsBySnRequest) (*dao.GetLogCollectionsResponse, error) { + + limit := req.PageSize + offset := (req.PageNum - 1) * req.PageSize + if limit == 0 { + offset = 0 + } + logCollectionItems, cnt, err := dao.GetLogCollectionsforConsole(logger, req.Sn, limit, offset) + if err != nil { + return nil, err + } + + logger.Infof("GetLogCollectionsforConsole origin content for sn:%s is:%s", req.Sn, util.ToString(logCollectionItems)) + + //获取sn和cps的对应关系 + sns := []string{} + for _, v := range logCollectionItems { + sns = append(sns, v.Sn) + } + if len(sns) == 0 { + return &dao.GetLogCollectionsResponse{ + Detail: []*dao.LogRespItem{}, + PageResult: dao.PageResult{ + Total: 0, + PageNumber: req.PageNum, + PageSize: req.PageSize, + }, + }, nil + } + snToCps, err := GetSnToCpsMap(logger, sns) + if err != nil { + return nil, err + } + logger.Infof("GetSnToCpsMap origin content for sns:%s is:%s", util.ToString(sns), util.ToString(snToCps)) + + //获取collectionId和faultrule的对应关系 + rids := []int{} + for _, v := range logCollectionItems { + rids = append(rids, int(v.FaultConfID)) + } + ridToFaultRule, err := GetRidToFaultRuleMap(logger, rids) + if err != nil { + return nil, err + } + + logger.Infof("GetRidToFaultRuleMap origin content for rids:%s is:%s", util.ToString(rids), util.ToString(ridToFaultRule)) + + res := &dao.GetLogCollectionsResponse{ + Detail: []*dao.LogRespItem{}, + PageResult: dao.PageResult{ + Total: cnt, + PageNumber: req.PageNum, + PageSize: req.PageSize, + }, + } + + for _, v := range logCollectionItems { + lri := &dao.LogRespItem{ + LogId: v.ID, + Sn: v.Sn, + IloIp: snToCps[v.Sn].IloIP, + AlertName: ridToFaultRule[int(v.FaultConfID)].Name, + AlertDesc: ridToFaultRule[int(v.FaultConfID)].Desc, + AlertType: ridToFaultRule[int(v.FaultConfID)].FaultType, + AlertPart: ridToFaultRule[int(v.FaultConfID)].Parts, + AlertLevel: ridToFaultRule[int(v.FaultConfID)].Level, + AlertContent: v.Content, + Count: int(v.Count), + CollectTime: v.CollectTime, + EventTime: v.EventTime, + UpdateTime: v.UpdateTime, + } + if lri.Count == 0 { + lri.Status = 1 + } + + res.Detail = append(res.Detail, lri) + } + return res, nil +} + +// 导出Excel文件 +func ExportLogCollectionBySnExcel(logger *log.Logger, result []*dao.LogRespItem) (string, string, error) { + language := logger.GetPoint("language").(string) + e := util.NewExcelInstance() + index := e.SetNewSheet("Sheet1") + sheetData := make([][]string, 0) + + for _, data := range result { + sheetData = append(sheetData, []string{ + util.ToString(data.LogId), // + data.AlertType, + data.AlertDesc, + util.Time2String(data.EventTime), + util.Time2String(data.UpdateTime), + util.ToString(data.Count), + util.LogDealStatusIntDesc(int(data.Status), language), + }) + } + exportExcelHeader := util.ExportLogCollectionBySnHeader + if language == util.EN_US { + exportExcelHeader = util.ExportLogCollectionBySnHeaderEn + } + if err := e.SetSheetData("Sheet1", exportExcelHeader, sheetData); err != nil { + logger.Warn("create excel error:", err.Error()) + return "", "", err + } + e.File.SetActiveSheet(index) + rand.Seed(time.Now().UnixNano()) + // 生成100000到100000+900000之间的随机数,左闭右开 + downloadFileName := "oob_console_list_" + time.Now().Format(util.FormatDate) + "_" + strconv.Itoa(rand.Intn(900000)+100000) + ".xlsx" + fileName, err := e.SaveFile(downloadFileName) + if err != nil { + logger.Warn("保存excel到本地失败" + err.Error()) + return "", "", err + } + return fileName, downloadFileName, nil +} + +func GetSnToCpsMap(logger *log.Logger, sns []string) (map[string]*dao.Device, error) { + cpss, err := dao.GetCpssBySns(logger, sns) + if err != nil { + return nil, err + } + res := map[string]*dao.Device{} + for _, v := range cpss { + res[v.Sn] = v + } + return res, nil +} + +func GetRidToFaultRuleMap(logger *log.Logger, rids []int) (map[int]*dao.CpsFaultRules, error) { + cfrs, err := dao.GetFaultRulesByRids(logger, rids) + if err != nil { + return nil, err + } + res := map[int]*dao.CpsFaultRules{} + for _, v := range cfrs { + res[v.ID] = v + } + return res, nil +} + +func DealLogCollection(logger *log.Logger, req dao.DealLogCollectionRequest) error { + + cid := req.Cid + return dao.DealCollectionByID(logger, cid) +} diff --git a/oob-log-alert/service/logItem.go b/oob-log-alert/service/logItem.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/oob-log-alert/service/logItem.go @@ -0,0 +1 @@ +package service diff --git a/oob-log-alert/service/mailLogic/MailUtil.go b/oob-log-alert/service/mailLogic/MailUtil.go new file mode 100644 index 0000000..9c06d06 --- /dev/null +++ b/oob-log-alert/service/mailLogic/MailUtil.go @@ -0,0 +1,118 @@ +package mailLogic + +import ( + "bytes" + "crypto/tls" + "errors" + "fmt" + "html/template" + "strconv" + "strings" + + log "coding.jd.com/aidc-bmp/bmp_log" + "coding.jd.com/aidc-bmp/oob-log-alert/dao" + + "github.com/go-gomail/gomail" +) + +func DialMail(logger *log.Logger, smtpHost string, smtpPort int, from, password, tos string, subject, msg string) error { + m := gomail.NewMessage() + to := strings.Split(tos, ",") + s := "" + m.SetHeader("From", from) + m.SetHeader("To", to...) + m.SetHeader("Subject", s+":"+subject) + m.SetBody("text/html", msg) + + username := strings.Split(from, "@")[0] + + d := gomail.NewPlainDialer( + smtpHost, + smtpPort, + username, + password) + + if d == nil { + return errors.New("Initialize Dialer Error") + } + + d.TLSConfig = &tls.Config{ServerName: d.Host, InsecureSkipVerify: true} + + // Send the email. + if err := d.DialAndSend(m); err != nil { + logger.Warnf("SendMail msg=%s : %s\n", msg, err.Error()) + return err + } + return nil +} + +// SendMail use smtp to send mail +func SendMail(logger *log.Logger, subject, msg string) error { + + mailEntity, err := dao.GetMailMessage(logger) + if err != nil { + logger.Warnf("SendMail.GetMail error:%s", err.Error()) + return err + } + tos := mailEntity.To + from := mailEntity.AdminAddr + smtpHost := mailEntity.ServerAddr + smtpPort, err := strconv.Atoi(mailEntity.ServerPort) + if err != nil { + logger.Warnf("SendMail.ServerPort invalid, port:%s", mailEntity.ServerPort) + return err + } + username := strings.Split(from, "@")[0] + password := mailEntity.AdminPass + + m := gomail.NewMessage() + to := strings.Split(tos, ",") + s := BaseSubjest + m.SetHeader("From", from) + m.SetHeader("To", to...) + m.SetHeader("Subject", s+"-"+subject) + m.SetBody("text/html", msg) + + d := gomail.NewPlainDialer( + smtpHost, + smtpPort, + username, + password) + + if d == nil { + return errors.New("Initialize Dialer Error") + } + + d.TLSConfig = &tls.Config{ServerName: d.Host, InsecureSkipVerify: true} + + // Send the email. + if err := d.DialAndSend(m); err != nil { + fmt.Printf("SendMail msg=%s : %s\n", msg, err.Error()) + return err + } + return nil +} + +//SendMailByTpl send template mail +func SendMailByTpl(logger *log.Logger, tplName, subject string, obj interface{}) error { + tpl, errParse := template.New("Mail").Parse(tplName) + if errParse != nil { + logger.Warnf("Parse Template Error:%s\n", errParse.Error()) + return errParse + } + + byteW := new(bytes.Buffer) + err := tpl.Execute(byteW, obj) + if err != nil { + logger.Warnf("Execute Template Error:%s\n", err.Error()) + return err + } + + errMail := SendMail(logger, subject, byteW.String()) + if errMail != nil { + logger.Warnf("Send Mail Error:%s\n", errMail.Error()) + return errMail + } + + return nil +} diff --git a/oob-log-alert/service/mailLogic/subject.go b/oob-log-alert/service/mailLogic/subject.go new file mode 100644 index 0000000..733b1b8 --- /dev/null +++ b/oob-log-alert/service/mailLogic/subject.go @@ -0,0 +1,5 @@ +package mailLogic + +const BaseSubjest string = "BMP裸金属管理平台" +const MailDialTestSubjest string = "测试邮件" +const MailDialTestContent string = "这是一封测试邮件" diff --git a/oob-log-alert/service/mailLogic/template.go b/oob-log-alert/service/mailLogic/template.go new file mode 100644 index 0000000..dc71819 --- /dev/null +++ b/oob-log-alert/service/mailLogic/template.go @@ -0,0 +1,166 @@ +package mailLogic + +const MessageOobTemplate string = ` + + + + + + 故障消息 + + + +
    +
    + BMP裸金属管理平台 +
    +
    +

    尊敬的用户 admin,您好!

    +

    + 您帐号中的服务器资源(SN号: {{.SN}} )于({{.AlertTime}})发生【{{.MessageSubType}}】。详情如下: +

    + + + + + + + + + + + + + + + + + + + +
    LogID故障类型故障描述故障报警时间报警次数
    {{.LogID}}{{.MessageSubType}}{{.Detail}}{{.AlertTime}}1
    +
    + +
    + + +` + +type MailMessage struct { + MessageID string + ResourceType string + FinishTime string + MessageType string + MessageSubType string + SN string + FaultType string + Content string + Detail string + LogID string + AlertTime string + AlertCount string + + InstanceID string + InstanceName string + UserID string + UserName string +} diff --git a/oob-log-alert/service/powerStatus.go b/oob-log-alert/service/powerStatus.go new file mode 100644 index 0000000..9d9df3c --- /dev/null +++ b/oob-log-alert/service/powerStatus.go @@ -0,0 +1,281 @@ +package service + +import ( + "encoding/json" + "errors" + "fmt" + "runtime" + "strings" + "sync" + "time" + + "coding.jd.com/aidc-bmp/oob-log-alert/object" + + "coding.jd.com/aidc-bmp/oob-log-alert/util" + + "coding.jd.com/aidc-bmp/oob-log-alert/dao" + + "github.com/beego/beego/v2/core/logs" + "github.com/beego/beego/v2/server/web" +) + +var statusMap map[string]string = map[string]string{ + "running": "on", + "stopped": "off", + "creating": "unknown", + "starting": "unknown", + "stopping": "unknown", + "restarting": "unknown", + "restarting_password": "unknown", + "destroying": "unknown", + "destroyed": "unknown", + "error": "unknown", + "upgrading": "unknown", + "reinstalling": "unknown", +} + +func GetPowerStatusDiff(idc string, instanceIds []string) ([]*dao.PowerStatus, error) { + + namespace, _ := web.AppConfig.String("redis.namespace") + + cpslist, err := GetCPSFromRedisforAzAndInstanceID(namespace, idc, instanceIds) + if err != nil { + logs.Warn("DailReportEvent() GetCPSFromRedis Error:%s", err.Error()) + return nil, err + } + updateRes := getInstancePowerStatusDiff(cpslist) + + v, _ := json.Marshal(updateRes) + logs.Info("getInstancePowerStatusDiff success, idc:%s, instanceIds:%s, res:%s", idc, strings.Join(instanceIds, ","), string(v)) + + res := []*dao.PowerStatus{} + for _, v := range updateRes { + // mailTpl.Info = append(mailTpl.Info, *v) + if v.IloStatus == "ipmi unreachable" { //带外不通的忽略 + v.IloStatus = "--" + } + res = append(res, v) + } + + return res, nil +} + +func SyncPowerStatusApi(idc string, instanceIds []string) (bool, error) { + + instanceEntries, _ := GetPowerStatusDiff(idc, instanceIds) + if len(instanceEntries) == 0 { + logs.Warn("SyncPowerStatusApi GetPowerStatusDiff empty, instanceid:%s", instanceIds) + return false, errors.New("param.instanceId powerstatus all sync already") + } + changes := map[string][]string{} + for _, v := range instanceEntries { + var targetStatus string + if v.IloStatus == "on" { + targetStatus = "running" + } else if v.IloStatus == "off" { + targetStatus = "stopped" + } else { + continue + } + changes[targetStatus] = append(changes[targetStatus], v.InstanceID) + } + + for status, instanceIDs := range changes { + if len(instanceIDs) == 0 { + continue + } + if err := sendChangeStatusRequest(status, instanceIDs); err != nil { + logs.Warn("sendChangeStatusRequest %s to status %s error:%s", strings.Join(instanceIDs, ","), status, err.Error()) + } else { + logs.Info("sendChangeStatusRequest %s to status %s succeed.", strings.Join(instanceIDs, ","), status) + } + } + return true, nil +} + +func getInstancePowerStatusDiff(cpslist object.CPSObject) []*dao.PowerStatus { + iloUser, _ := web.AppConfig.String("oob.username") + iloPass, _ := web.AppConfig.String("oob.password") + wg := sync.WaitGroup{} + wg.Add(len(cpslist.CPSs)) + + diffResChan := make(chan *dao.PowerStatus) + updateRes := []*dao.PowerStatus{} + go func() { + for { + i, ok := <-diffResChan + if !ok { //chan关闭 + break + } + updateRes = append(updateRes, i) + } + }() + + rateLimitSize := 20 //令牌池大小,用来限制下并发量 + rateLimitchan := make(chan int, rateLimitSize) + + for _, cps := range cpslist.CPSs { + rateLimitchan <- 1 //取令牌 + go func(cps object.CPSRecord) { + defer func() { + wg.Done() + <-rateLimitchan //任务完成后还令牌 + }() + if cps.InstanceID == "" { //未装机等边界情况下不检查 + return + } + if statusMap[cps.Status] == "unknown" { //实例处于边界状态(装机中,销毁中等)时不做检查 + return + } + ilo_status := getIloipPowerStatus(cps.IloIP, iloUser, iloPass) + + fmt.Printf("diff debug, ilo_status:%s, cps_status:%s\n", ilo_status, statusMap[cps.Status]) + if !strings.EqualFold(ilo_status, statusMap[cps.Status]) { + diffResChan <- &dao.PowerStatus{ + SN: cps.SN, + InstanceID: cps.InstanceID, + InstanceName: cps.InstanceName, + IdcId: cps.IdcId, + Pin: cps.Pin, + IloIp: cps.IloIP, + Status: statusMap[cps.Status], + IloStatus: ilo_status, + Ipv4: cps.Ipv4, + DeviceType: cps.DeviceType, + } + } + }(cps) + } + wg.Wait() + close(diffResChan) + + time.Sleep(5 * time.Second) + + return updateRes +} + +func DoStaticCpsPowerState() error { + + defer func() { + if r := recover(); r != nil { + t := make([]byte, 1<<16) + runtime.Stack(t, true) + // t, _ := json.Marshal(r) + logs.Warn("DoStaticCpsPowerState.panic msg,", string(t)) + } + }() + + logs.Trace(">>>>>>>>DoStaticCpsPowerState()") + defer logs.Trace("<<<<<<< 0 { + tmp := cpsObject.CPSs + for _, v := range tmp { + if inArrayStr(v.InstanceID, instanceIds) { + cpsObject.CPSs = append(cpsObject.CPSs, v) + } + } + } else { + cpsObject.CPSs = tmp + } + + return cpsObject, nil +} + +// writeCPSListToRedis write CPS to Redis +func WriteCPSListToRedis(cpsObject object.CPSObject) error { + + cpsMap := make(map[string]interface{}) + + for _, v := range cpsObject.CPSs { + jsonStr, err := v.JSON() + if err != nil { + logs.Warn(err.Error()) + continue + } + cpsMap[v.SN] = jsonStr + } + // write to Redis + err := util.HMSetObjectToRedis("", cpsMap) + if err != nil { + logs.Warn("Write cps list to Redis. status: %v", err.Error()) + return err + } + + return nil +} + +func DelCPSFromRedis(cpsSNs []string) error { + + // del Hash fields + err := util.HDelObjectFromRedis("", cpsSNs) + if err != nil { + logs.Warn("Del cps list from Redis. ERROR: %v", err.Error()) + return err + } + + // del monitor keys + err = util.DelObjectFromRedis(cpsSNs) + if err != nil { + logs.Warn("Del cps monitor from Redis. ERROR: %v", err.Error()) + return err + } + + return nil +} + +// GetInstanceMonitor get instance monitor data from redis. construct data +func GetInstanceMonitor(instanceID string) (interface{}, error) { + + all, err := util.HGetAllFromRedis(instanceID) + if err != nil { + logs.Warn("Get %s Error:%s", instanceID, err.Error()) + return nil, err + } + + // lastMonitorTime := all[object.LastMonitorTimeField] + pDisk, _ := getDisk(all[object.PDisksField]) + cpu, _ := getCPU(all[object.CPUsField]) + mem, _ := getMem(all[object.MemsField]) + nic, _ := getNIC(all[object.NicsField]) + + data := map[string]interface{}{ + "instanceID": instanceID, + // "lastMonitorTime": lastMonitorTime, + "pdisks": pDisk, + "cpus": cpu, + "mems": mem, + "nics": nic, + } + + return &data, nil + +} + +func getDisk(str string) (*object.PhysicalDiskObject, error) { + + if str == "" { + return nil, nil + } + + pDisk := object.PhysicalDiskObject{} + pDisk.PDisks = []object.PhysicalDiskRecord{} + + err := json.Unmarshal([]byte(str), &(pDisk.PDisks)) + if err != nil { + logs.Warn("Unmarshal Error:%s", err.Error()) + } + + pDisk.Status = true + for _, v := range pDisk.PDisks { + if strings.Compare(strings.ToUpper(v.PrimaryStatus), "OK") != 0 { + pDisk.Status = false + } + } + pDisk.Count = len(pDisk.PDisks) + + return &pDisk, nil +} + +func getCPU(str string) (*object.CPUObject, error) { + + if str == "" { + return nil, nil + } + + cpu := object.CPUObject{} + cpu.CPUs = []object.CPURecord{} + + err := json.Unmarshal([]byte(str), &(cpu.CPUs)) + if err != nil { + logs.Warn("Unmarshal Error:%s", err.Error()) + } + + cpu.Status = true + for _, v := range cpu.CPUs { + if strings.Compare(strings.ToUpper(v.PrimaryStatus), "OK") != 0 { + cpu.Status = false + } + } + cpu.Count = len(cpu.CPUs) + + return &cpu, nil +} + +func getMem(str string) (*object.MemObject, error) { + + if str == "" { + return nil, nil + } + + mem := object.MemObject{} + mem.Mems = []object.MemRecord{} + + err := json.Unmarshal([]byte(str), &(mem.Mems)) + if err != nil { + logs.Warn("Unmarshal Error:%s", err.Error()) + } + + mem.Status = true + for _, v := range mem.Mems { + if strings.Compare(strings.ToUpper(v.PrimaryStatus), "OK") != 0 { + mem.Status = false + } + } + mem.Count = len(mem.Mems) + + return &mem, nil +} + +func getNIC(str string) (*object.NicObject, error) { + + if str == "" { + return nil, nil + } + + nic := object.NicObject{} + nic.Nics = []object.NicRecord{} + + err := json.Unmarshal([]byte(str), &(nic.Nics)) + if err != nil { + logs.Warn("Unmarshal Error:%s", err.Error()) + } + + nic.Status = true + for _, v := range nic.Nics { + if strings.Compare(strings.ToUpper(v.LinkStatus), "UP") != 0 { + nic.Status = false + } + } + nic.Count = len(nic.Nics) + + return &nic, nil +} diff --git a/oob-log-alert/service/serviceAlert.go b/oob-log-alert/service/serviceAlert.go new file mode 100644 index 0000000..59184ff --- /dev/null +++ b/oob-log-alert/service/serviceAlert.go @@ -0,0 +1,257 @@ +package service + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + log "coding.jd.com/aidc-bmp/bmp_log" + "coding.jd.com/aidc-bmp/oob-log-alert/object" + "coding.jd.com/aidc-bmp/oob-log-alert/service/mailLogic" + "coding.jd.com/aidc-bmp/oob-log-alert/util" + + "coding.jd.com/aidc-bmp/oob-log-alert/dao" + messageType "git.jd.com/cps-golang/ironic-common/ironic/enums/MessageType" + + "github.com/beego/beego/v2/core/logs" +) + +const timeFormat = "01/02/2006 15:04:05" + +// LogEvent process Logs event, filter and send mail +func LogEvent(logger *log.Logger, sn, message string, isSaveLog bool, logPath string) error { + + log := object.LogObject{} + + errJSON := json.Unmarshal([]byte(message), &log) + if errJSON != nil { + logs.Warn("%s LogEvent %s JSONUmarshal Error %s", sn, errJSON.Error()) + return errJSON + } + // end check + + // get cps + cps, err := GetCPS(sn) + if err != nil { + return err + } + // end get cps + mailAlertItems := []MailAlertLog{} + mailMessageItems := []*dao.WebMessage{} + logItems := []*dao.CpsLogItems{} + + // GetFilter + filters, err := dao.GetFaultUsedRules(logger) + if err != nil { + logs.Warn("%s GetFaultUsedRules err: %s", sn, err.Error()) + return err + } else { + // filter + for i := len(log.Messages) - 1; i >= 0; i-- { + line := log.Messages[i] + + items := strings.Split(line, "|") + if len(items) != 6 { + logs.Debug(sn, " Sel list item invalid:", line) + continue + } + logid := strings.TrimSpace(items[0]) + eventTime, err := time.Parse(timeFormat, fmt.Sprintf("%s %s", strings.TrimSpace(items[1]), strings.TrimSpace(items[2]))) + if err != nil { + logs.Warn("%s Sel list item time invalid:%s", sn, line) + } + logcondition := strings.TrimSpace(items[3]) + logdesc := strings.TrimSpace(strings.Join(items[4:], "|")) + eventDetail := strings.TrimSpace(strings.Join(items[3:], "|")) + + logger.Infof("logcondition is %s, logdesc is :%s\n", logcondition, logdesc) + + isMatch := false + + var selectedf *dao.CpsFaultRules + + for _, f := range filters { + if strings.HasPrefix(logcondition, strings.TrimSpace(f.Condition)) && strings.HasPrefix(logdesc, strings.TrimSpace(f.Threshold)) { + isMatch = true + selectedf = f + break + } + + } + + collectTime := time.Now() + + if isMatch { + + cid, err := dao.InsertAndGetCollectionID(logger, sn, eventDetail, selectedf.ID, collectTime, eventTime, selectedf.Level) + if err != nil { + logger.Warnf("InsertAndGetCollectionID error: %s", err.Error()) + return nil + } else { + logger.Infof("InsertAndGetCollectionID success, sn: %s, line:%s, cid:%d", sn, line, cid) + } + + item := dao.CpsLogItems{ + Sn: sn, + CollectionID: int(cid), + EventTime: eventTime, + CollectTime: collectTime, + } + logItems = append(logItems, &item) + mailAlertItems = append(mailAlertItems, MailAlertLog{ + EventTime: eventTime, + FaultTypeZh: selectedf.FaultType, + FaultNameZh: selectedf.Desc, + }) + + //插入消息到message表 + c := fmt.Sprintf("%s/%s", cps.InstanceName, sn) + if cps.InstanceName == "" { + c = sn + } + message := &dao.WebMessage{ + MessageID: util.GetUuid("m-"), + ResourceType: "oob-alert-log", + FinishTime: int(time.Now().Unix()), + MessageType: messageType.MessageTypeOobMonitor, + MessageSubType: selectedf.FaultType, + SN: item.Sn, + FaultType: selectedf.FaultType, + Content: eventDetail, + Detail: c, //都赋值, + LogID: logid, + AlertTime: int(item.EventTime.Unix()), + AlertCount: 1, + } + instanceEntity, err := dao.GetInstanceBySn(logger, item.Sn) + if err != nil { + logger.Warnf("InsertMessage.GetInstanceBySn error, sn:%s, error:%s", item.Sn, err.Error()) + } + if instanceEntity != nil { + message.InstanceID = instanceEntity.InstanceID + message.InstanceName = instanceEntity.InstanceName + message.UserID = instanceEntity.UserID + + user, err := dao.GetUserById(logger, instanceEntity.UserID) + if err != nil { + logger.Warnf("InsertMessage.GetUserById error, user_id:%s, error:%s", instanceEntity.UserID, err.Error()) + } + if user != nil { + message.UserName = user.UserName + } + } + mailMessageItems = append(mailMessageItems, message) + err = dao.InsertMessage(logger, message) + if err != nil { + logger.Warnf("sn %s insert message err, error:%s, content:%s ", cps.SN, err.Error(), util.ToString(item)) + } else { + logger.Infof("sn %s insert message succeed, content:%s", cps.SN, util.ToString(item)) + } + + } + if !isMatch { + //告警日志被过滤掉时,记录日志方便排查 + info := fmt.Sprintf("%s Log alert filtered, line: %s", sn, line) + logger.Warnf(info) + } else { + info := fmt.Sprintf("%s Log alert selected, line: %s, rule:%s", sn, line, selectedf.Desc) + logger.Info(info) + } + } + // end filter + + } + + if len(logItems) == 0 { + return nil + } + + // insert to Database + err = dao.BatchInsertLogItems(logger, logItems) + if err != nil { + logger.Warnf("sn %s insert oob-log-items err, error:%s, content:%s ", cps.SN, err.Error(), util.ToString(logItems)) + } else { + logger.Infof("sn %s insert oob-log-items succeed, content:%s", cps.SN, util.ToString(logItems)) + } + + // if dailyMoreThanOnce(sn, message) { //同一设备同类型的报警,每天只邮件报一次 + // return nil + // } + + // send mail + // mailObject := logMailTpl{CPS: cps, Logs: mailAlertItems} + // errMail := util.SendMailByTpl(logMailTemplate, logMailSubject, mailObject) + // if errMail != nil { + // logs.Warn(cps.SN + " Send LogEvent Mail failed: " + errMail.Error()) + // return errMail + // } else { + // logs.Debug(cps.SN + " Send LogEvent Mail succeed") + // } + // end send mail + if len(mailMessageItems) > 0 { + items := []mailLogic.MailMessage{} + for _, v := range mailMessageItems { + items = append(items, mailLogic.MailMessage{ + MessageID: v.MessageID, + ResourceType: v.ResourceType, + FinishTime: time.Unix(int64(v.FinishTime), 0).Format("2006-01-02 15:04:05"), + MessageType: v.MessageType, + MessageSubType: v.MessageSubType, + SN: v.SN, + FaultType: v.FaultType, + Content: v.Content, + Detail: v.Detail, + LogID: v.LogID, + AlertTime: time.Unix(int64(v.AlertTime), 0).Format("2006-01-02 15:04:05"), + AlertCount: fmt.Sprintf("%d", v.AlertCount), + + InstanceID: v.InstanceID, + InstanceName: v.InstanceName, + UserID: v.UserID, + UserName: v.UserName, + }) + } + subject := fmt.Sprintf("故障消息-【%s】提醒", mailMessageItems[0].MessageSubType) + mailTpl := mailLogic.MessageOobTemplate + err = mailLogic.SendMailByTpl(logger, mailTpl, subject, items) + if err != nil { + logger.Warnf("oob message SendMailByTpl error:%s", err.Error()) + } else { + logger.Info("oob message SendMailByTpl success") + } + } + + return nil +} + +// CPSEvent process CPS event for oob access error, send mail +func CPSEvent(sn, message string) error { + + if message == "" { + return nil + } + + // get cps + // cps, err := GetCPS(sn) + // if err != nil { + // return err + // } + // end get cps + + // send mail + // mailObject := alertOOBMailTpl{CPS: cps, Err: message} + // logs.Debug(sn, "mailObject:", mailObject) + + // errMail := util.SendMailByTpl(alertOOBMailTemplate, alertOOBMailSubject, mailObject) + // if errMail != nil { + // logs.Warn(sn, "Send CPSEvent Mail Error:%s", errMail.Error()) + // return errMail + // } else { + // logs.Warn(sn, "Send CPSEvent Mail Succeed") + // } + // end send mail + + return nil + +} diff --git a/oob-log-alert/service/serviceReport.go b/oob-log-alert/service/serviceReport.go new file mode 100644 index 0000000..f733d3c --- /dev/null +++ b/oob-log-alert/service/serviceReport.go @@ -0,0 +1,126 @@ +package service + +import ( + "encoding/json" + "fmt" + "runtime" + "strconv" + + "coding.jd.com/aidc-bmp/oob-log-alert/object" + + "coding.jd.com/aidc-bmp/oob-log-alert/util" + + "github.com/beego/beego/v2/core/logs" +) + +// DailReportEvent process daily report, get cps monitor status from redis and count errors. send mail +func DailReportEvent() error { + + defer func() { + if r := recover(); r != nil { + t := make([]byte, 1<<16) + runtime.Stack(t, true) + // t, _ := json.Marshal(r) + logs.Warn("DailReportEvent.panic msg,", string(t)) + } + }() + + logs.Trace(">>>>>>>>DailReportEvent()") + defer logs.Trace("<<<<<<< + + + + +
    {{.Az}}可用区实例状态被带外巡检自动更新详情:
    + + + + + + + + + + + {{range .DiffStatus}} + + + + + + + + + + {{end}} +
    实例sn实例idaz用户pinilo_ip更改前状态更改后状态
    {{.SN}}{{.InstanceID}}{{.Az}}{{.Pin}}{{.IloIp}}{{.Status}}{{.IloStatus}}
    + +
    {{.Az}}可用区带外不通的实例如下:
    + + + + + + + + + + {{range .Unreachable}} + + + + + + + + + {{end}} +
    实例sn实例idaz用户pinilo_ip控制台状态
    {{.SN}}{{.InstanceID}}{{.Az}}{{.Pin}}{{.IloIp}}{{.Status}}
    + +` + +const logMailTemplate string = ` + + + + + +
    CPS信息
    + + + + + + + + + + + + + + + + + + + + + + + +
    SNIdcId用户pin品牌型号套餐机柜已售iLO IP
    {{.CPS.SN}}{{.CPS.IdcId}}{{.CPS.Pin}}{{.CPS.Brand}}{{.CPS.Model}}{{.CPS.Package}}{{.CPS.Cabinet}}{{.CPS.IsSale}}{{.CPS.IloIP}}
    +

    +
    告警日志
    + + + + + + + + {{range .Logs}} + + + + + + {{end}} + +
    故障带外时间故障类型故障名称
    {{.EventTime}}{{.FaultTypeZh}}{{.FaultNameZh}}
    + +` + +const alertOOBMailTemplate string = ` + + + + + +
    CPS信息
    + + + + + + + + + + + + + + + + + + + + + +
    SNIdcId品牌型号套餐机柜已售iLO IP
    {{.CPS.SN}}{{.CPS.IdcId}}{{.CPS.Brand}}{{.CPS.Model}}{{.CPS.Package}}{{.CPS.Cabinet}}{{.CPS.IsSale}}{{.CPS.IloIP}}
    +

    +
    带外连接错误
    + + + + + + + + +
    错误信息
    {{.Err}}
    + +` + +const dailyReportMailTemplate string = ` + + + + + +
    CPS监控统计
    + + + + + + + + + + + + + + + +
    IdcId总数成功带外访问错误其他错误
    {{.IdcId}}{{.TotalCount}}{{.SuccessCount}}{{.OOBErrorCount}}{{.OtherErrorCount}}
    +



    +
    CPS监控详情
    + + + + + + + + + + + + + {{range .CPSResult}} + {{if eq .Code 0}} + + {{else}} + + {{end}} + + + + + + + + + + + {{end}} + +
    SN品牌型号套餐机柜已售iLO IPCodeMsg
    {{.CPS.SN}}{{.CPS.Brand}}{{.CPS.Model}}{{.CPS.Package}}{{.CPS.Cabinet}}{{.CPS.IsSale}}{{.CPS.IloIP}}{{.Code}}{{.Msg}}
    + +` diff --git a/oob-log-alert/service/user.go b/oob-log-alert/service/user.go new file mode 100644 index 0000000..5b34a9e --- /dev/null +++ b/oob-log-alert/service/user.go @@ -0,0 +1,18 @@ +package service + +import ( + log "coding.jd.com/aidc-bmp/bmp_log" + "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +func GetUserIdByName(logger *log.Logger, username string) (string, error) { + + user, err := dao.GetUserByName(logger, username) + if err != nil { + logger.Warnf("GetUserIdByName error, username:%s, err:%s", username, err.Error()) + return "", err + } + logger.Infof("GetUserIdByName succ, username:%s, userid:%s", username, user.UserID) + return user.UserID, nil + +} diff --git a/oob-log-alert/swagger.yml b/oob-log-alert/swagger.yml new file mode 100644 index 0000000..bc16985 --- /dev/null +++ b/oob-log-alert/swagger.yml @@ -0,0 +1,836 @@ +basePath: /v1 +consumes: + - application/json + - application/xml +definitions: + ChangePushRequest: + properties: + push_status: + format: int64 + type: integer + x-go-name: PushStatus + rule_id: + format: int64 + type: integer + x-go-name: RuleID + type: object + x-go-package: coding.jd.com/aidc-bmp/oob-log-alert/dao + ChangeUseRequest: + properties: + rule_id: + format: int64 + type: integer + x-go-name: RuleID + use_status: + format: int64 + type: integer + x-go-name: UseStatus + type: object + x-go-package: coding.jd.com/aidc-bmp/oob-log-alert/dao + CommonResponse: + properties: + success: + description: 操作是否成功 [true/false] + type: boolean + x-go-name: Success + type: object + x-go-package: coding.jd.com/aidc-bmp/oob-log-alert/dao + DealLogCollectionRequest: + properties: + logid: + format: int64 + type: integer + x-go-name: Cid + type: object + x-go-package: coding.jd.com/aidc-bmp/oob-log-alert/dao + DeviceStatus: + properties: + brand: + type: string + x-go-name: Brand + cpu_status: + format: int64 + type: integer + x-go-name: CpuStatus + device_id: + type: string + x-go-name: DeviceId + disk_status: + format: int64 + type: integer + x-go-name: DiskStatus + idc_id: + type: string + x-go-name: IdcId + idc_name: + type: string + x-go-name: IdcName + manage_status: + description: IsSale int `json:"is_sale"` + type: string + x-go-name: ManageStatus + mem_status: + format: int64 + type: integer + x-go-name: MemStatus + model: + description: Manufacturer string `json:"manufacturer"` + type: string + x-go-name: Model + nic_status: + format: int64 + type: integer + x-go-name: NicStatus + other_status: + format: int64 + type: integer + x-go-name: OtherStatus + power_status: + format: int64 + type: integer + x-go-name: PowerStatus + sn: + type: string + x-go-name: Sn + type: object + x-go-package: coding.jd.com/aidc-bmp/oob-log-alert/dao + ErrorResponse: + properties: + code: + format: int64 + type: integer + x-go-name: Code + message: + type: string + x-go-name: Message + type: object + x-go-package: coding.jd.com/aidc-bmp/oob-log-alert/controllers + GetDeviceStatusResponse: + properties: + detail: + items: + $ref: '#/definitions/DeviceStatus' + type: array + x-go-name: Detail + page_number: + format: int64 + type: integer + x-go-name: PageNumber + page_size: + format: int64 + type: integer + x-go-name: PageSize + total_count: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: coding.jd.com/aidc-bmp/oob-log-alert/dao + GetLogCollectionsResponse: + properties: + detail: + items: + $ref: '#/definitions/LogRespItem' + type: array + x-go-name: Detail + page_number: + format: int64 + type: integer + x-go-name: PageNumber + page_size: + format: int64 + type: integer + x-go-name: PageSize + total_count: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: coding.jd.com/aidc-bmp/oob-log-alert/dao + LogRespItem: + properties: + alert_content: + description: 故障原始日志 + type: string + x-go-name: AlertContent + alert_desc: + description: 故障描述 + type: string + x-go-name: AlertDesc + alert_level: + description: 故障等级 + type: string + x-go-name: AlertLevel + alert_name: + description: 故障名称 + type: string + x-go-name: AlertName + alert_part: + description: 故障配件 + type: string + x-go-name: AlertPart + alert_type: + description: 故障类型 + type: string + x-go-name: AlertType + collect_time: + description: 带外故障发现时间 + format: date-time + type: string + x-go-name: CollectTime + count: + description: 告警次数 + format: int64 + type: integer + x-go-name: Count + device_id: + type: string + x-go-name: DeviceId + event_time: + description: 首次故障报警时间 + format: date-time + type: string + x-go-name: EventTime + idc_id: + type: string + x-go-name: IdcId + idc_name: + type: string + x-go-name: IdcName + ilo_ip: + type: string + x-go-name: IloIp + logid: + format: int64 + type: integer + x-go-name: LogId + manage_status: + description: 设备状态 + type: string + x-go-name: ManageStatus + sn: + type: string + x-go-name: Sn + status: + description: 状态:0为未处理,1为已恢复 + format: int8 + type: integer + x-go-name: Status + update_time: + description: 更新时间 + format: date-time + type: string + x-go-name: UpdateTime + type: object + x-go-package: coding.jd.com/aidc-bmp/oob-log-alert/dao + RuleListResponse: + properties: + detail: + items: + $ref: '#/definitions/RuleListResponseItem' + type: array + x-go-name: Detail + page_number: + format: int64 + type: integer + x-go-name: PageNumber + page_size: + format: int64 + type: integer + x-go-name: PageSize + total_count: + format: int64 + type: integer + x-go-name: Total + type: object + x-go-package: coding.jd.com/aidc-bmp/oob-log-alert/dao + RuleListResponseItem: + properties: + alert_condition: + description: 判定条件 + type: string + x-go-name: AlertCondition + alert_desc: + type: string + x-go-name: AlertDesc + alert_level: + type: string + x-go-name: AlertLevel + alert_name: + type: string + x-go-name: AlertName + alert_spec: + type: string + x-go-name: AlertSpec + alert_threshold: + description: 判定阈值 + type: string + x-go-name: AlertThreshold + alert_type: + type: string + x-go-name: AlertType + push_status: + description: 是否推送,0表示关闭,1表示开启 + format: int64 + type: integer + x-go-name: PushStatus + rule_id: + format: int64 + type: integer + x-go-name: RuleId + use_status: + description: 是否启用,0表示关闭,1表示开启 + format: int64 + type: integer + x-go-name: UseStatus + type: object + x-go-package: coding.jd.com/aidc-bmp/oob-log-alert/dao + RuleResetPushAndUseRequest: + properties: + rule_ids: + type: string + x-go-name: RuleIDs + type: object + x-go-package: coding.jd.com/aidc-bmp/oob-log-alert/dao +host: bmp-oob-alert.bmp.local +info: + contact: + email: minping@jd.com + description: |- + the purpose of this application is to provide an application + that is using plain go code to define an API + + This should demonstrate all the possible comment annotations + that are available to turn go code into a fully compliant swagger 2.0 spec + license: + name: MIT + url: http://opensource.org/licenses/MIT + termsOfService: there are no TOS at this moment, use at your own risk we take no responsibility + title: BMP + version: 0.0.1 +paths: + /custom/getCustomInfo: + get: + description: GetCustomInfo 获取自定义信息 + operationId: getCustomInfo + responses: + "200": + $ref: '#/responses/getCustomInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - custom + /custom/setCustomInfo: + post: + description: SetCustomInfo 设置自定义信息 + operationId: setCustomInfo + responses: + "200": + $ref: '#/responses/setCustomInfo' + default: + $ref: '#/responses/ErrorResponse' + tags: + - custom + /v1/oob-alert/consolelogs: + get: + description: GetLogCollectionsBySn 故障报警日志-控制台(只有符合push状态规则的才在控制台展示) + operationId: getLogCollectionsBySn + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - format: int64 + in: query + name: page_num + type: integer + x-go-name: PageNum + - format: int64 + in: query + name: page_size + type: integer + x-go-name: PageSize + - in: query + name: isAll + type: string + x-go-name: IsAll + - in: query + name: sn + type: string + x-go-name: Sn + - description: ExportType 非空要导出 + in: query + name: exportType + type: string + x-go-name: ExportType + responses: + "200": + $ref: '#/responses/getLogCollectionsBySn' + default: + $ref: '#/responses/ErrorResponse' + tags: + - ooblog + /v1/oob-alert/device/status: + get: + description: GetDeviceStatus 获取设备带外总体状态 + operationId: getDeviceStatus + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - format: int64 + in: query + name: page_num + type: integer + x-go-name: PageNum + - format: int64 + in: query + name: page_size + type: integer + x-go-name: PageSize + - in: query + name: isAll + type: string + x-go-name: IsAll + - in: query + name: idc_id + type: string + x-go-name: IdcId + - in: query + name: sn + type: string + x-go-name: Sn + - description: ExportType 非空要导出 + in: query + name: exportType + type: string + x-go-name: ExportType + responses: + "200": + $ref: '#/responses/getDeviceStatus' + default: + $ref: '#/responses/ErrorResponse' + tags: + - device + /v1/oob-alert/logs: + get: + description: GetLogCollections 故障报警日志-运营平台 + operationId: getLogCollections + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - format: int64 + in: query + name: page_num + type: integer + x-go-name: PageNum + - format: int64 + in: query + name: page_size + type: integer + x-go-name: PageSize + - in: query + name: isAll + type: string + x-go-name: IsAll + - in: query + name: idc_id + type: string + x-go-name: IdcId + - in: query + name: sn + type: string + x-go-name: Sn + - description: 故障等级 + in: query + name: level + type: string + x-go-name: Level + - description: 故障配件 + in: query + name: spec + type: string + x-go-name: Spec + - in: query + name: start_time + type: string + x-go-name: StartTime + - in: query + name: end_time + type: string + x-go-name: EndTime + - in: query + name: deal_status + type: string + x-go-name: DealStatus + - description: ExportType 非空要导出 + in: query + name: exportType + type: string + x-go-name: ExportType + responses: + "200": + $ref: '#/responses/getLogCollections' + default: + $ref: '#/responses/ErrorResponse' + tags: + - ooblog + /v1/oob-alert/logs/deal: + post: + description: DealLogCollection 故障报警日志-处理 + operationId: dealLogCollection + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: body + name: Body + schema: + $ref: '#/definitions/DealLogCollectionRequest' + responses: + "200": + $ref: '#/responses/dealLogCollection' + default: + $ref: '#/responses/ErrorResponse' + tags: + - ooblog + /v1/oob-alert/rules: + get: + description: RuleList 故障报警规则列表 + operationId: ruleList + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - format: int64 + in: query + name: page_num + type: integer + x-go-name: PageNum + - format: int64 + in: query + name: page_size + type: integer + x-go-name: PageSize + - in: query + name: isAll + type: string + x-go-name: IsAll + - in: query + name: alert_name + type: string + x-go-name: AlertName + - in: query + name: alert_spec + type: string + x-go-name: AlertSpec + - in: query + name: alert_level + type: string + x-go-name: AlertLevel + - description: ExportType 非空要导出 + in: query + name: exportType + type: string + x-go-name: ExportType + responses: + "200": + $ref: '#/responses/ruleList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - alert-rule + /v1/oob-alert/rules/alert-level-list: + get: + description: AlertLevelList 故障报警规则-故障等级列表 + operationId: alertLevelList + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + responses: + "200": + $ref: '#/responses/alertLevelList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - alert-rule + /v1/oob-alert/rules/alert-spec-list: + get: + description: AlertPartList 故障报警规则-故障配件列表 + operationId: alertPartList + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + responses: + "200": + $ref: '#/responses/alertPartList' + default: + $ref: '#/responses/ErrorResponse' + tags: + - alert-rule + /v1/oob-alert/rules/change-push: + post: + description: ChangePush 故障报警规则列表-故障推送开关 + operationId: changePush + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: body + name: Body + schema: + $ref: '#/definitions/ChangePushRequest' + responses: + "200": + $ref: '#/responses/changePush' + default: + $ref: '#/responses/ErrorResponse' + tags: + - alert-rule + /v1/oob-alert/rules/change-use: + post: + description: ChangeUse 故障报警规则列表-故障启用开关 + operationId: changeUse + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: body + name: Body + schema: + $ref: '#/definitions/ChangeUseRequest' + responses: + "200": + $ref: '#/responses/changeUse' + default: + $ref: '#/responses/ErrorResponse' + tags: + - alert-rule + /v1/oob-alert/rules/reset: + post: + description: RuleResetPushAndUse 故障报警规则列表-恢复默认规则重置 + operationId: ruleResetPushAndUse + parameters: + - description: 流量唯一id + in: header + name: traceId + required: true + type: string + x-go-name: TraceID + - in: body + name: Body + schema: + $ref: '#/definitions/RuleResetPushAndUseRequest' + responses: + "200": + $ref: '#/responses/ruleResetPushAndUse' + default: + $ref: '#/responses/ErrorResponse' + tags: + - alert-rule +produces: + - application/json + - application/xml +responses: + ErrorResponse: + description: unit err response for non 200 + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + error: + $ref: '#/definitions/ErrorResponse' + requestId: + description: 流量ID + type: string + x-go-name: RequestId + required: + - error + - requestId + type: object + alertLevelList: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + items: + type: string + type: array + x-go-name: Result + type: object + alertPartList: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + items: + type: string + type: array + x-go-name: Result + type: object + changePush: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + changeUse: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + dealLogCollection: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object + getDeviceStatus: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/GetDeviceStatusResponse' + type: object + getLogCollections: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/GetLogCollectionsResponse' + type: object + getLogCollectionsBySn: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/GetLogCollectionsResponse' + type: object + ruleList: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/RuleListResponse' + type: object + ruleResetPushAndUse: + description: "" + headers: + traceId: + description: |- + 流量ID + in: header + type: string + schema: + properties: + result: + $ref: '#/definitions/CommonResponse' + type: object +schemes: + - http +security: + - api_key: [] +securityDefinitions: + api_key: + in: header + name: bmp-ak + type: apiKey +swagger: "2.0" +x-meta-array: + - value1 + - value2 +x-meta-array-obj: + - name: obj + value: field +x-meta-value: value diff --git a/oob-log-alert/swagger_gen.sh b/oob-log-alert/swagger_gen.sh new file mode 100644 index 0000000..61bf1be --- /dev/null +++ b/oob-log-alert/swagger_gen.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +# install goswagger: https://goswagger.io/install.html#Installing%20from%20source + +swagger version +\rm ./swagger.yml | swagger generate spec -o ./swagger.yml +# swagger validate ./swagger.yml goswagger有缺陷,且报错无法提供有效信息,建议使用https://editor.swagger.io/来校验 +# validate 和 generate命令在0.25.0版本有panic,0.30.3版本已修复 +swagger validate swagger.yml +\rm -rf ../bmp-oob-alert-sdk/client && \rm -rf ../bmp-oob-alert-sdk/models +swagger generate client -f swagger.yml --target=../bmp-oob-alert-sdk diff --git a/oob-log-alert/swaggermodels/AlertLevelListRequest.go b/oob-log-alert/swaggermodels/AlertLevelListRequest.go new file mode 100644 index 0000000..1e63ecf --- /dev/null +++ b/oob-log-alert/swaggermodels/AlertLevelListRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters alertLevelList +type AlertLevelListRequest struct { + ReadRequestHeader +} diff --git a/oob-log-alert/swaggermodels/AlertLevelListResult.go b/oob-log-alert/swaggermodels/AlertLevelListResult.go new file mode 100644 index 0000000..9cd8139 --- /dev/null +++ b/oob-log-alert/swaggermodels/AlertLevelListResult.go @@ -0,0 +1,10 @@ +package swaggermodels + +// swagger:response alertLevelList +type AlertLevelListResult struct { + ResponseHeader + // in: body + Body struct { + Result []string `json:"result"` + } +} diff --git a/oob-log-alert/swaggermodels/AlertPartListRequest.go b/oob-log-alert/swaggermodels/AlertPartListRequest.go new file mode 100644 index 0000000..dd8caf1 --- /dev/null +++ b/oob-log-alert/swaggermodels/AlertPartListRequest.go @@ -0,0 +1,6 @@ +package swaggermodels + +// swagger:parameters alertPartList +type AlertPartListRequest struct { + ReadRequestHeader +} diff --git a/oob-log-alert/swaggermodels/AlertPartListResult.go b/oob-log-alert/swaggermodels/AlertPartListResult.go new file mode 100644 index 0000000..f0c9e63 --- /dev/null +++ b/oob-log-alert/swaggermodels/AlertPartListResult.go @@ -0,0 +1,10 @@ +package swaggermodels + +// swagger:response alertPartList +type AlertPartListResult struct { + ResponseHeader + // in: body + Body struct { + Result []string `json:"result"` + } +} diff --git a/oob-log-alert/swaggermodels/ChangePushRequest.go b/oob-log-alert/swaggermodels/ChangePushRequest.go new file mode 100644 index 0000000..88aa5ba --- /dev/null +++ b/oob-log-alert/swaggermodels/ChangePushRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:parameters changePush +type ChangePushRequest struct { + WriteRequestHeader + + // in:body + Body dao.ChangePushRequest +} diff --git a/oob-log-alert/swaggermodels/ChangePushResult.go b/oob-log-alert/swaggermodels/ChangePushResult.go new file mode 100644 index 0000000..03f1216 --- /dev/null +++ b/oob-log-alert/swaggermodels/ChangePushResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:response changePush +type ChangePushResult struct { + ResponseHeader + // in: body + Body struct { + Result dao.CommonResponse `json:"result"` + } +} diff --git a/oob-log-alert/swaggermodels/ChangeUseRequest.go b/oob-log-alert/swaggermodels/ChangeUseRequest.go new file mode 100644 index 0000000..198a9f8 --- /dev/null +++ b/oob-log-alert/swaggermodels/ChangeUseRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:parameters changeUse +type ChangeUseRequest struct { + WriteRequestHeader + + // in:body + Body dao.ChangeUseRequest +} diff --git a/oob-log-alert/swaggermodels/ChangeUseResult.go b/oob-log-alert/swaggermodels/ChangeUseResult.go new file mode 100644 index 0000000..461def3 --- /dev/null +++ b/oob-log-alert/swaggermodels/ChangeUseResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:response changeUse +type ChangeUseResult struct { + ResponseHeader + // in: body + Body struct { + Result dao.CommonResponse `json:"result"` + } +} diff --git a/oob-log-alert/swaggermodels/Common.go b/oob-log-alert/swaggermodels/Common.go new file mode 100644 index 0000000..019fde4 --- /dev/null +++ b/oob-log-alert/swaggermodels/Common.go @@ -0,0 +1,61 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/controllers" +) + +type ReadRequestHeader struct { + // 流量唯一id + // required: true + // in: header + TraceID string `json:"traceId"` + // // demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + // // required: true + // // in: header + // Authorization string `json:"authorization"` + // // 用户uuid, deprecated + // // in: header + // BmpUserID string `json:"bmpUserId"` + // // 用户语言 [zh_CN, en_US] + // // in: header + // BmpLanguage string `json:"bmpLanguage"` +} + +type WriteRequestHeader struct { + // 流量唯一id + // required: true + // in: header + TraceID string `json:"traceId"` + // // demo: curl -X GET -H "Authorization:Bearer wwabmrpdxz04qa10frpuw7key9qkd9bu" http://127.0.0.1:8801/v1/idcs 请使用个人自己创建apikey时候的token + // // required: true + // // in: header + // Authorization string `json:"authorization"` + // // 用户uuid + // // in: header + // BmpUserID string `json:"bmpUserId"` + // // 用户语言 [zh_CN, en_US] + // // in: header + // BmpLanguage string `json:"bmpLanguage"` +} + +// unit err response for non 200 +// swagger:response ErrorResponse +type ErrorResponse struct { + ResponseHeader + //In: body + Body struct { + // 错误信息 + // required: true + Err controllers.ErrorResponse `json:"error"` + // 流量ID + // required: true + RequestId string `json:"requestId"` + } +} + +// 返回body里面的公共字段 +type ResponseHeader struct { + // 流量ID + // in: header + TraceID string `json:"traceId"` +} diff --git a/oob-log-alert/swaggermodels/DealLogCollectionRequest.go b/oob-log-alert/swaggermodels/DealLogCollectionRequest.go new file mode 100644 index 0000000..9de2bc6 --- /dev/null +++ b/oob-log-alert/swaggermodels/DealLogCollectionRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:parameters dealLogCollection +type DealLogCollectionRequest struct { + WriteRequestHeader + + // in:body + Body dao.DealLogCollectionRequest +} diff --git a/oob-log-alert/swaggermodels/DealLogCollectionResult.go b/oob-log-alert/swaggermodels/DealLogCollectionResult.go new file mode 100644 index 0000000..2eac5c9 --- /dev/null +++ b/oob-log-alert/swaggermodels/DealLogCollectionResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:response dealLogCollection +type DealLogCollectionResult struct { + ResponseHeader + // in: body + Body struct { + Result dao.CommonResponse `json:"result"` + } +} diff --git a/oob-log-alert/swaggermodels/GetDeviceStatusRequest.go b/oob-log-alert/swaggermodels/GetDeviceStatusRequest.go new file mode 100644 index 0000000..f5dc39b --- /dev/null +++ b/oob-log-alert/swaggermodels/GetDeviceStatusRequest.go @@ -0,0 +1,12 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:parameters getDeviceStatus +type GetDeviceStatusRequest struct { + ReadRequestHeader + // in: query + requestTypes.GetDeviceStatusRequest +} diff --git a/oob-log-alert/swaggermodels/GetDeviceStatusResult.go b/oob-log-alert/swaggermodels/GetDeviceStatusResult.go new file mode 100644 index 0000000..b1be860 --- /dev/null +++ b/oob-log-alert/swaggermodels/GetDeviceStatusResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:response getDeviceStatus +type GetDeviceStatusResult struct { + ResponseHeader + // in: body + Body struct { + Result dao.GetDeviceStatusResponse `json:"result"` + } +} diff --git a/oob-log-alert/swaggermodels/GetLogCollectionsBySnRequest.go b/oob-log-alert/swaggermodels/GetLogCollectionsBySnRequest.go new file mode 100644 index 0000000..da480c9 --- /dev/null +++ b/oob-log-alert/swaggermodels/GetLogCollectionsBySnRequest.go @@ -0,0 +1,12 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:parameters getLogCollectionsBySn +type GetLogCollectionsBySnRequest struct { + ReadRequestHeader + // in: query + requestTypes.GetLogCollectionsBySnRequest +} diff --git a/oob-log-alert/swaggermodels/GetLogCollectionsBySnResult.go b/oob-log-alert/swaggermodels/GetLogCollectionsBySnResult.go new file mode 100644 index 0000000..e4389bb --- /dev/null +++ b/oob-log-alert/swaggermodels/GetLogCollectionsBySnResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:response getLogCollectionsBySn +type GetLogCollectionsBySnResult struct { + ResponseHeader + // in: body + Body struct { + Result dao.GetLogCollectionsResponse `json:"result"` + } +} diff --git a/oob-log-alert/swaggermodels/GetLogCollectionsRequest.go b/oob-log-alert/swaggermodels/GetLogCollectionsRequest.go new file mode 100644 index 0000000..e0ff5e2 --- /dev/null +++ b/oob-log-alert/swaggermodels/GetLogCollectionsRequest.go @@ -0,0 +1,12 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:parameters getLogCollections +type GetLogCollectionsRequest struct { + ReadRequestHeader + // in: query + requestTypes.GetLogCollectionsRequest +} diff --git a/oob-log-alert/swaggermodels/GetLogCollectionsResult.go b/oob-log-alert/swaggermodels/GetLogCollectionsResult.go new file mode 100644 index 0000000..513f55c --- /dev/null +++ b/oob-log-alert/swaggermodels/GetLogCollectionsResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:response getLogCollections +type GetLogCollectionsResult struct { + ResponseHeader + // in: body + Body struct { + Result dao.GetLogCollectionsResponse `json:"result"` + } +} diff --git a/oob-log-alert/swaggermodels/RuleListRequest.go b/oob-log-alert/swaggermodels/RuleListRequest.go new file mode 100644 index 0000000..4ab83a4 --- /dev/null +++ b/oob-log-alert/swaggermodels/RuleListRequest.go @@ -0,0 +1,12 @@ +package swaggermodels + +import ( + requestTypes "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:parameters ruleList +type RuleListRequest struct { + ReadRequestHeader + // in: query + requestTypes.RuleListRequest +} diff --git a/oob-log-alert/swaggermodels/RuleListResult.go b/oob-log-alert/swaggermodels/RuleListResult.go new file mode 100644 index 0000000..d022752 --- /dev/null +++ b/oob-log-alert/swaggermodels/RuleListResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:response ruleList +type RuleListResult struct { + ResponseHeader + // in: body + Body struct { + Result dao.RuleListResponse `json:"result"` + } +} diff --git a/oob-log-alert/swaggermodels/RuleResetPushAndUseRequest.go b/oob-log-alert/swaggermodels/RuleResetPushAndUseRequest.go new file mode 100644 index 0000000..b2a5121 --- /dev/null +++ b/oob-log-alert/swaggermodels/RuleResetPushAndUseRequest.go @@ -0,0 +1,13 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:parameters ruleResetPushAndUse +type RuleResetPushAndUseRequest struct { + WriteRequestHeader + + // in:body + Body dao.RuleResetPushAndUseRequest +} diff --git a/oob-log-alert/swaggermodels/RuleResetPushAndUseResult.go b/oob-log-alert/swaggermodels/RuleResetPushAndUseResult.go new file mode 100644 index 0000000..e254672 --- /dev/null +++ b/oob-log-alert/swaggermodels/RuleResetPushAndUseResult.go @@ -0,0 +1,14 @@ +package swaggermodels + +import ( + "coding.jd.com/aidc-bmp/oob-log-alert/dao" +) + +// swagger:response ruleResetPushAndUse +type RuleResetPushAndUseResult struct { + ResponseHeader + // in: body + Body struct { + Result dao.CommonResponse `json:"result"` + } +} diff --git a/oob-log-alert/swaggermodels/swaggerinfo.go b/oob-log-alert/swaggermodels/swaggerinfo.go new file mode 100644 index 0000000..d2821f2 --- /dev/null +++ b/oob-log-alert/swaggermodels/swaggerinfo.go @@ -0,0 +1,47 @@ +// Package classification BMP +// +// the purpose of this application is to provide an application +// that is using plain go code to define an API +// +// This should demonstrate all the possible comment annotations +// that are available to turn go code into a fully compliant swagger 2.0 spec +// +// Terms Of Service: +// +// there are no TOS at this moment, use at your own risk we take no responsibility +// +// Schemes: http +// Host: bmp-oob-alert.bmp.local +// BasePath: /v1 +// Version: 0.0.1 +// License: MIT http://opensource.org/licenses/MIT +// Contact: minping@jd.com +// +// Consumes: +// - application/json +// - application/xml +// +// Produces: +// - application/json +// - application/xml +// +// Security: +// - api_key: +// +// SecurityDefinitions: +// api_key: +// type: apiKey +// name: bmp-ak +// in: header +// +// Extensions: +// x-meta-value: value +// x-meta-array: +// - value1 +// - value2 +// x-meta-array-obj: +// - name: obj +// value: field +// +// swagger:meta +package swaggermodels diff --git a/oob-log-alert/util/HttpUtil.go b/oob-log-alert/util/HttpUtil.go new file mode 100644 index 0000000..7851fc0 --- /dev/null +++ b/oob-log-alert/util/HttpUtil.go @@ -0,0 +1,121 @@ +package util + +import ( + "crypto/tls" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +func doPost(urlstr, param string, header map[string]string) (resp string, err error) { + u, err := url.Parse(urlstr) + if err != nil { + return "", err + } + u.RawQuery = u.Query().Encode() + + //跳过证书验证,禁止连接保持 + c := &http.Client{ + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + DisableKeepAlives: true, + }, + } + + req, err := http.NewRequest("POST", u.String(), strings.NewReader(param)) + if err != nil { + return "", err + } + + // req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + //增加header选项 + for k, v := range header { + req.Header.Add(k, v) + } + + respBody, err := c.Do(req) + if err != nil { + return "", err + } + defer respBody.Body.Close() + + if respBody.StatusCode != 200 { + return "", fmt.Errorf("Http Post %s return %d", urlstr, respBody.StatusCode) + } + + body, err := ioutil.ReadAll(respBody.Body) + if err != nil { + return "", err + } + + return string(body), nil +} + +// HTTPPost http post +func HTTPPost(urlstr, param string) (resp string, err error) { + return doPost(urlstr, param, nil) +} + +func HTTPPostWithHeader(urlstr, param string, header map[string]string) (resp string, err error) { + return doPost(urlstr, param, header) +} + +func doGet(urlstr string, user string, pass string, header map[string]string) (resp string, err error) { + u, err := url.Parse(urlstr) + if err != nil { + return "", err + } + if user != "" { + u.User = url.UserPassword(user, pass) + } + u.RawQuery = u.Query().Encode() + + //跳过证书验证,禁止连接保持 + c := &http.Client{ + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + DisableKeepAlives: true, + }, + } + + //提交请求 + req, err := http.NewRequest("GET", u.String(), nil) + if err != nil { + return "", err + } + + //增加header选项 + for k, v := range header { + req.Header.Add(k, v) + } + + respBody, errGet := c.Do(req) + if errGet != nil { + return "", errGet + } + defer respBody.Body.Close() + + if respBody.StatusCode != 200 { + return "", fmt.Errorf("Http Get %s return %d", urlstr, respBody.StatusCode) + } + body, err := ioutil.ReadAll(respBody.Body) + if err != nil { + return "", err + } + + return string(body), nil +} +func HTTPGetWithHeader(urlstr string, header map[string]string) (resp string, err error) { + return doGet(urlstr, "", "", header) +} + +func HTTPGetWithBasicAuth(urlstr string, user string, pass string) (resp string, err error) { + return doGet(urlstr, user, pass, nil) +} + +// HTTPGet http Get +func HTTPGet(urlstr string) (resp string, err error) { + return doGet(urlstr, "", "", nil) +} diff --git a/oob-log-alert/util/MailUtil.go b/oob-log-alert/util/MailUtil.go new file mode 100644 index 0000000..eba2c69 --- /dev/null +++ b/oob-log-alert/util/MailUtil.go @@ -0,0 +1,71 @@ +package util + +import ( + "bytes" + "crypto/tls" + "errors" + "fmt" + "html/template" + + "github.com/beego/beego/v2/server/web" + "github.com/go-gomail/gomail" +) + +// SendMail use smtp to send mail +func SendMail(subject, msg string) error { + m := gomail.NewMessage() + from, _ := web.AppConfig.String("alert.mail.from") + to, _ := web.AppConfig.Strings("alert.mail.to") + s, _ := web.AppConfig.String("alert.mail.subject") + m.SetHeader("From", from) + m.SetHeader("To", to...) + m.SetHeader("Subject", s+":"+subject) + m.SetBody("text/html", msg) + + smtpHost, _ := web.AppConfig.String("alert.mail.smtp-host") + username, _ := web.AppConfig.String("alert.mail.username") + password, _ := web.AppConfig.String("alert.mail.password") + + d := gomail.NewPlainDialer( + smtpHost, + web.AppConfig.DefaultInt("alert.mail.smtp-port", 25), + username, + password) + + if d == nil { + return errors.New("Initialize Dialer Error") + } + + d.TLSConfig = &tls.Config{ServerName: d.Host, InsecureSkipVerify: true} + + // Send the email. + if err := d.DialAndSend(m); err != nil { + fmt.Printf("SendMail msg=%s : %s\n", msg, err.Error()) + return err + } + return nil +} + +//SendMailByTpl send template mail +func SendMailByTpl(tplName, subject string, obj interface{}) error { + tpl, errParse := template.New("Mail").Parse(tplName) + if errParse != nil { + fmt.Printf("Parse Template Error:%s\n", errParse.Error()) + return errParse + } + + byteW := new(bytes.Buffer) + err := tpl.Execute(byteW, obj) + if err != nil { + fmt.Printf("Execute Template Error:%s\n", err.Error()) + return err + } + + errMail := SendMail(subject, byteW.String()) + if errMail != nil { + fmt.Printf("Send Mail Error:%s\n", errMail.Error()) + return errMail + } + + return nil +} diff --git a/oob-log-alert/util/RedisUtil.go b/oob-log-alert/util/RedisUtil.go new file mode 100644 index 0000000..c6cf242 --- /dev/null +++ b/oob-log-alert/util/RedisUtil.go @@ -0,0 +1,276 @@ +package util + +import ( + "errors" + "fmt" + "sync" + "time" + + "github.com/go-redis/redis" +) + +var redisMonitorNamespace string + +var redisOnce sync.Once + +type redisUtil struct { + *redis.Client +} + +// RedisUtil singleton redis util +var RedisUtil *redisUtil + +// InitRedis initial redisUtil instance +func InitRedis(namespace, idc, addr, passwd string, db int) error { + redisOnce.Do(func() { + if RedisUtil == nil { + + RedisUtil = &redisUtil{ + redis.NewClient(&redis.Options{ + Addr: addr, + Password: passwd, // no password set + DB: db, // use default DB + }), + } + + redisMonitorNamespace = namespace + if idc != "" { + redisMonitorNamespace = namespace + ":" + idc + } + + } + }) + + return RedisUtil.Ping().Err() +} + +// PubEventToRedis pub event to redis +func PubEventToRedis(subKey, message string) error { + + ret, err := RedisUtil.Publish(redisMonitorNamespace+":"+subKey, message).Result() + if err != nil { + return err + } + + if ret == int64(0) { + return errors.New("no subcriber") + } + + return nil + +} + +// PSubEventToRedis psubscribe event from redis +func PSubEventToRedis(ch ...string) *redis.PubSub { + if len(ch) == 0 { + return nil + } + + var chs []string + + for _, arg := range ch { + if arg == "" { + chs = append(chs, redisMonitorNamespace+":*") + } else { + chs = append(chs, redisMonitorNamespace+":"+arg+":*") + } + } + + return RedisUtil.PSubscribe(chs...) +} + +// SetObjectToRedisWithExpire set string object with a expiration +func SetObjectToRedisWithExpire(key, value string, sec int) error { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + err := RedisUtil.Set(fullKey, value, time.Second*time.Duration(sec)).Err() + if err != nil { + return err + } + + return nil +} + +// SetObjectToRedis set object to Redis +func SetObjectToRedis(key string, value string) error { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + err := RedisUtil.Set(fullKey, value, 0).Err() + if err != nil { + return err + } + + return nil +} + +// GetObjectFromRedis Get object from Redis +func GetObjectFromRedis(key string) (string, error) { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + ret, err := RedisUtil.Get(fullKey).Result() + if err != nil { + return "", err + } + + return ret, nil +} + +// HSetObjectToRedis hash set object to Redis +func HSetObjectToRedis(key, field, value string) error { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + err := RedisUtil.HSet(fullKey, field, value).Err() + if err != nil { + return err + } + + return nil +} + +// HGetObjectFromRedis hash get from redis +func HGetObjectFromRedis(key, field string) (string, error) { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + ret, err := RedisUtil.HGet(fullKey, field).Result() + if err != nil { + return "", err + } + return ret, nil +} + +// HGetAllFromRedis hash get from redis +func HGetAllFromRedis(key string) (map[string]string, error) { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + ret, err := RedisUtil.HGetAll(fullKey).Result() + if err != nil { + return nil, err + } + + return ret, nil +} + +// HGetAllFromRedis hash get from redis +func HGetAllFromRedisCustom(namespace, idc string) (map[string]string, error) { + ret, err := RedisUtil.HGetAll(fmt.Sprintf("%s:%s", namespace, idc)).Result() + if err != nil { + return nil, err + } + + return ret, nil +} + +// HMSetObjectToRedis hash set objects to Redis +func HMSetObjectToRedis(key string, fields map[string]interface{}) error { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + err := RedisUtil.HMSet(fullKey, fields).Err() + if err != nil { + return err + } + + return nil +} + +func HDelObjectFromRedis(key string, fields []string) error { + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + if len(fields) <= 0 { + return nil + } + + err := RedisUtil.HDel(fullKey, fields...).Err() + + if err != nil { + return err + } + return nil +} + +func DelObjectFromRedis(keys []string) error { + + if len(keys) <= 0 { + return nil + } + + var fullKeys []string + for _, v := range keys { + if v != "" { + fullKeys = append(fullKeys, redisMonitorNamespace+":"+v) + } + } + + if len(fullKeys) > 0 { + err := RedisUtil.Del(fullKeys...).Err() + if err != nil { + return err + } + } + + return nil +} + +// HMGetObjectFromRedis Hash get objects from redis +func HMGetObjectFromRedis(key string, fields ...string) ([]interface{}, error) { + + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + if len(fields) <= 0 { + return nil, nil + } + + v, err := RedisUtil.HMGet(fullKey, fields...).Result() + + if err != nil { + return nil, err + } + return v, nil +} + +func HIncrObjectToRedis(key string, field string, count int) (int, error) { + fullKey := redisMonitorNamespace + if key != "" { + fullKey = redisMonitorNamespace + ":" + key + } + + v, err := RedisUtil.HIncrBy(fullKey, field, int64(count)).Result() + + if err != nil { + return 0, err + } + return int(v), nil +} diff --git a/oob-log-alert/util/contants.go b/oob-log-alert/util/contants.go new file mode 100644 index 0000000..b47b85b --- /dev/null +++ b/oob-log-alert/util/contants.go @@ -0,0 +1,410 @@ +package util + +const ( + EN_US = "en_US" + CN_ZH = "zh_CN" +) + +//设备是否有带外故障 +var statusDesc = map[int]string{ + 0: "正常", + 1: "异常", +} +var statusDescEn = map[int]string{ + 0: "normal", + 1: "unexpected", +} + +//带外故障是否已处理 +var logDealStatusDesc = map[int]string{ + 0: "未处理", + 1: "已处理", +} +var logDealStatusDescEn = map[int]string{ + 0: "Unhandled", + 1: "Handled", +} + +var pushStatusDesc = map[int]string{ + 0: "未启用", + 1: "已启用", +} + +var pushStatusDescEn = map[int]string{ + 0: "disabled", + 1: "enabled", +} + +func StatusIntDesc(status int, language string) string { + if language == EN_US { + return statusDescEn[status] + } else { + return statusDesc[status] + } +} + +func LogDealStatusIntDesc(status int, language string) string { + if language == EN_US { + return logDealStatusDescEn[status] + } else { + return logDealStatusDesc[status] + } +} + +func PushStatusIntDesc(status int, language string) string { + if language == EN_US { + return pushStatusDescEn[status] + } else { + return pushStatusDesc[status] + } +} + +var ( + FormatTime = "2006-01-02 15:04:05" + FormatDate = "2006-01-02" + + ExportDeviceStatusHeader = []string{ + "SN", + "机房", + "品牌", + "型号", + "管理状态", + "CPU", + "内存", + "硬盘", + "网卡", + "电源", + "其他", + } + ExportDeviceStatusHeaderEn = []string{ + "SN", + "Idc Name", + "Brand", + "Model", + "Manage Status", + "CPU", + "Memory", + "Harddisk", + "NIC", + "POWER Supply", + "Other", + } + + ExportLogCollectionsHeader = []string{ + "LogID", + "SN", + "机房", + "故障等级", + "故障类型", + "故障配件", + "iloIP", + "故障描述", + "故障原始日志", + "状态", + "报警次数", + "带外故障发现时间", + "首次故障报警时间", + "更新时间", + } + + ExportLogCollectionsHeaderEn = []string{ + "LogID", + "SN", + "Idc Name", + "Failure Level", + "Fault Type", + "Faulty accessories", + "iloIP", + "Fault Desc", + "Fault Original log", + "Status", + "Number of alarms", + "Out-of-band fault detection time", + "First fault alarm time", + "Update Time", + } + + ExportLogCollectionBySnHeader = []string{ + "序号", + "故障类型", + "故障描述", + "故障报警时间", + "更新时间", + "报警次数", + "状态", + } + + ExportLogCollectionBySnHeaderEn = []string{ + "LogID", + "Fault Type", + "Fault Desc", + "Out-of-band fault detection time", + "Update Time", + "Number of alarms", + "Status", + } + + ExportRulesHeader = []string{ + "故障名称", + "故障配件", + "故障类型", + "判定条件", + "判定阈值", + "故障等级", + "故障描述", + "故障推送", + "启用状态", + } + + ExportRulesHeaderEn = []string{ + "Fault Name", + "Faulty accessories", + "Fault Type", + "Judgment Conditions", + "Decision Threshold", + "Failure Level", + "Fault Description", + "Failure Push", + "Enabled Status", + } +) + +var HeaderList = map[string]map[string]map[string]map[string]bool{ + //运营平台故障日志自定义列表 + "alert_log_list": { + "custom_info": { + "logid": { + "selected": true, //默认选中 + "required": true, //true代表灰色按钮,直接就是选中,不可更改选中状态,默认就是选中 + }, + "sn": { + "selected": true, //默认选中 + "required": true, //true代表灰色按钮,直接就是选中,不可更改选中状态,默认就是选中 + }, + "idc_name": { // + "selected": true, + "required": false, + }, + "alert_level": { //体系架构 + "selected": true, + "required": false, + }, + "alert_type": { + "selected": true, + "required": false, + }, + "alert_part": { + "selected": true, + "required": false, + }, + "ilo_ip": { + "required": false, + "selected": true, + }, + "alert_desc": { + "selected": true, + "required": false, + }, + "alert_content": { + "selected": true, + "required": false, + }, + "status": { + "selected": true, + "required": false, + }, + "count": { + "selected": true, + "required": false, + }, + "collect_time": { + "selected": true, + "required": false, + }, + "event_time": { + "selected": true, + "required": false, + }, + "update_time": { + "selected": true, + "required": false, + }, + "operate": { + "selected": true, + "required": true, + }, + }, + }, + //控制台故障日志自定义列表 + "alert_log_by_sn_list": { + "custom_info": { + "logid": { + "selected": true, //默认选中 + "required": true, //true代表灰色按钮,直接就是选中,不可更改选中状态,默认就是选中 + }, + "alert_type": { + "selected": true, + "required": false, + }, + "alert_desc": { + "selected": true, + "required": false, + }, + "event_time": { + "selected": true, + "required": true, + }, + "update_time": { + "selected": true, + "required": true, + }, + "count": { + "selected": true, + "required": true, + }, + "status": { + "selected": true, + "required": false, + }, + "operate": { + "selected": true, + "required": true, + }, + }, + }, + //运营平台故障规则自定义列表 + "alert_rule_list": { + "custom_info": { + "alert_name": { + "selected": true, + "required": false, + }, + "alert_spec": { + "selected": true, + "required": false, + }, + "alert_type": { + "selected": true, + "required": false, + }, + "alert_condition": { + "selected": true, + "required": false, + }, + "alert_threshold": { + "selected": true, + "required": false, + }, + "alert_level": { + "selected": true, + "required": false, + }, + "alert_desc": { + "selected": true, + "required": false, + }, + "push_status": { + "selected": true, + "required": true, + }, + "use_status": { + "selected": true, + "required": true, + }, + "operate": { + "selected": true, + "required": true, + }, + }, + }, + //运营平台硬件设备状态 + "device_status_list": { + "custom_info": { + "sn": { + "selected": true, + "required": true, + }, + "idc_name": { + "selected": true, + "required": false, + }, + "brand": { + "selected": true, + "required": false, + }, + "model": { + "selected": true, + "required": false, + }, + "manage_status": { + "selected": true, + "required": false, + }, + "cpu_status": { + "selected": true, + "required": false, + }, + "mem_status": { + "selected": true, + "required": false, + }, + "disk_status": { + "selected": true, + "required": false, + }, + "nic_status": { + "selected": true, + "required": false, + }, + "power_status": { + "selected": true, + "required": false, + }, + "other_status": { + "selected": true, + "required": false, + }, + "operate": { + "selected": true, + "required": true, + }, + }, + }, + //运营平台设备管理硬件监控状态 + "device_alert_log_list": { + "custom_info": { + "logid": { + "selected": true, //默认选中 + "required": true, //true代表灰色按钮,直接就是选中,不可更改选中状态,默认就是选中 + }, + "alert_type": { + "selected": true, + "required": false, + }, + "alert_desc": { + "selected": true, + "required": false, + }, + "event_time": { + "selected": true, + "required": false, + }, + "update_time": { + "selected": true, + "required": false, + }, + "count": { + "selected": true, + "required": false, + }, + "status": { + "selected": true, + "required": true, + }, + "operate": { + "selected": true, + "required": true, + }, + }, + }, +} diff --git a/oob-log-alert/util/errors.go b/oob-log-alert/util/errors.go new file mode 100644 index 0000000..fdfde4b --- /dev/null +++ b/oob-log-alert/util/errors.go @@ -0,0 +1,53 @@ +package util + +import ( + "reflect" + + sdkModels "coding.jd.com/aidc-bmp/bmp-openapi-sdk/models" + apiRuntime "github.com/go-openapi/runtime" +) + +/* +sdk的原因,写了此GetOpenapiError用来解析openapi的返回err。err如果已知,为具体类型(比如GetUserListDefault)或者APIError类型(多了一层),如果未知解析失败,第二个参数为false + +type GetUserListDefault struct { + _statusCode int + TraceID string + Payload *GetUserListDefaultBody + } + + type GetUserListDefaultBody struct { + + // error + Error *models.ErrorResponse `json:"error,omitempty"` +} + +APIError{ + OperationName: opName, + Response: interface{}(GetUserListDefault), + Code: code, +} + +*/ + +func GetOpenapiError(err error) (*sdkModels.ErrorResponse, bool) { + + var v interface{} + e, ok := err.(*apiRuntime.APIError) + if ok { + v = e.Response + } else { + v = err + } + if reflect.ValueOf(v).MethodByName("GetPayload").IsValid() { + val := reflect.ValueOf(v).MethodByName("GetPayload").Call([]reflect.Value{}) + if reflect.Indirect(val[0]).FieldByName("Error").IsValid() { + err1, ok := reflect.Indirect(val[0]).FieldByName("Error").Interface().(*sdkModels.ErrorResponse) + if ok { + return err1, true + } + } + } + return nil, false + +} diff --git a/oob-log-alert/util/excel.go b/oob-log-alert/util/excel.go new file mode 100644 index 0000000..6d341ff --- /dev/null +++ b/oob-log-alert/util/excel.go @@ -0,0 +1,146 @@ +package util + +import ( + "os" + "path/filepath" + "strconv" + + beego "github.com/beego/beego/v2/server/web" + + "github.com/xuri/excelize/v2" +) + +type IExcel interface { + GetSheetData() ([][]string, error) + SetSheetData(string, []string, [][]string) error + SetNewSheet(string) int + SaveFile(string) (string, error) + SetSheetHeader(string, []string) error + SetSheetDataRandom(string, string, [][]string, int) error +} + +type Excel struct { + File *excelize.File +} + +func NewExcelInstance() *Excel { + return &Excel{ + File: excelize.NewFile(), + } +} + +func LoadExcel(fileName string) (*Excel, error) { + f, err := excelize.OpenFile(fileName) + if err != nil { + return nil, err + } + return &Excel{ + File: f, + }, nil +} + +func (e *Excel) GetSheetData() ([][]string, error) { + index := e.File.GetActiveSheetIndex() + name := e.File.GetSheetName(index) + return e.File.GetRows(name) +} + +func (e *Excel) SetNewSheet(sheetName string) int { + return e.File.NewSheet(sheetName) +} + +func (e *Excel) SetSheetHeader(sheetName string, sheetHeaders []string) error { + colNum, rowNum := 1, 1 + for _, header := range sheetHeaders { + //从第一列开始获取每列第一个元素位置 + axis, err := excelize.ColumnNumberToName(colNum) + if err != nil { + return err + } + axis = axis + strconv.Itoa(rowNum) + if err = e.File.SetCellValue(sheetName, axis, header); err != nil { + return err + } + colNum++ + } + return nil +} + +func (e *Excel) SetSheetDataRandom(requestId, sheetName string, sheetData [][]string, rowNum int) error { + for _, row := range sheetData { + colNum := 1 + for _, value := range row { + axis, err := excelize.ColumnNumberToName(colNum) + if err != nil { + return err + } + axis = axis + strconv.Itoa(rowNum) + if err := e.File.SetCellValue(sheetName, axis, value); err != nil { + return err + } + colNum++ + } + rowNum++ + } + return nil +} + +func (e *Excel) SetSheetData(sheetName string, sheetHeaders []string, sheetData [][]string) error { + if err := e.SetSheetHeader(sheetName, sheetHeaders); err != nil { + return err + } + rowNum := 2 + for _, row := range sheetData { + colNum := 1 + for _, value := range row { + axis, err := excelize.ColumnNumberToName(colNum) + if err != nil { + return err + } + axis = axis + strconv.Itoa(rowNum) + if err := e.File.SetCellValue(sheetName, axis, value); err != nil { + return err + } + colNum++ + } + rowNum++ + } + return nil +} + +func (e *Excel) SaveFile(fileName string) (string, error) { + // basePath, err := os.Executable() + // if err != nil { + // return "", err + // } + // res, err := filepath.EvalSymlinks(filepath.Dir(basePath)) + // if err != nil { + // return "", err + // } + excelPath, _ := beego.AppConfig.String("log.path") + CreateDirIfNotExist(excelPath + string(os.PathSeparator) + "data") + fileName = filepath.Join(excelPath, "data", fileName) + return fileName, e.File.SaveAs(fileName) +} + +/** +判断文件是否存在 +*/ +func CreateDirIfNotExist(fileAddr string) bool { + s, err := os.Stat(fileAddr) + if err != nil { + return CreateDir(fileAddr) + } + return s.IsDir() +} + +/** +创建文件夹 +*/ +func CreateDir(dirName string) bool { + err := os.Mkdir(dirName, 0777) + if err != nil { + return false + } + return true +} diff --git a/oob-log-alert/util/execmd.go b/oob-log-alert/util/execmd.go new file mode 100644 index 0000000..875c349 --- /dev/null +++ b/oob-log-alert/util/execmd.go @@ -0,0 +1,39 @@ +package util + +import ( + "errors" + "os/exec" + "regexp" + "strings" + "syscall" +) + +// ExecCommand function to execute command +func ExecCommand(cmdStr string, params ...string) (retStr string, ret int, err error) { + + // check command injection + r := regexp.MustCompile(`[&\|;]+`) + if matched := r.MatchString(cmdStr); matched { + return "", -1, errors.New("command can not contain [&|;], ignore execute") + } + for _, param := range params { + if matched := r.MatchString(param); matched { + return "", -1, errors.New("params can not contain [&|;], ignore execute") + } + } + + cmd := exec.Command(cmdStr, params...) + + // execute + out, err := cmd.CombinedOutput() + // fmt.Printf("stdout>%v\n", string(out)) + + // get exit code + ret = cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus() + if ret != 0 { + err = errors.New(strings.TrimSpace(string(out[:]))) + } + // fmt.Printf("cmd>%+v \n", cmd) + + return string(out[:]), ret, err +} diff --git a/oob-log-alert/util/gopool.go b/oob-log-alert/util/gopool.go new file mode 100644 index 0000000..ee7be61 --- /dev/null +++ b/oob-log-alert/util/gopool.go @@ -0,0 +1,39 @@ +package util + +import ( + "sync" +) + +// Pool for control goroutine num to run +type Pool struct { + queue chan int + wg *sync.WaitGroup +} + +// NewPool make a pool with size +func NewPool(size int) *Pool { + if size <= 0 { + size = 1 + } + return &Pool{ + queue: make(chan int, size), + wg: &sync.WaitGroup{}, + } +} + +// Add a goroutine to pool with delta num +func (p *Pool) Add() { + p.queue <- 1 + p.wg.Add(1) +} + +// Done invoke this while goroutine is done +func (p *Pool) Done() { + <-p.queue + p.wg.Done() +} + +// Wait wait all goroutine is finished +func (p *Pool) Wait() { + p.wg.Wait() +} diff --git a/oob-log-alert/util/openapi.go b/oob-log-alert/util/openapi.go new file mode 100644 index 0000000..f2946fc --- /dev/null +++ b/oob-log-alert/util/openapi.go @@ -0,0 +1,37 @@ +package util + +import ( + "fmt" + + sdk "coding.jd.com/aidc-bmp/bmp-openapi-sdk/client" + beego "github.com/beego/beego/v2/server/web" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +var ( + SdkClient *sdk.CPS +) + +func InitOpenapi() { + + host, _ := beego.AppConfig.String("openapi_host") + port, _ := beego.AppConfig.String("openapi_port") + host = fmt.Sprintf("%s:%s", host, port) + fmt.Println("openapi host:", host) + + token, _ := beego.AppConfig.String("openapi_token") + /* + cfg := sdk.TransportConfig{ + Host: host, + BasePath: "/v1", + Schemes: []string{"http"}, + } + SdkClient = sdk.NewHTTPClientWithConfig(nil, &cfg) + */ + + r := httptransport.New(host, "/v1", []string{"http"}) + r.SetDebug(true) + r.DefaultAuthentication = httptransport.BearerToken(token) + SdkClient = sdk.New(r, strfmt.Default) +} diff --git a/oob-log-alert/util/pidUtil.go b/oob-log-alert/util/pidUtil.go new file mode 100644 index 0000000..25cf2f9 --- /dev/null +++ b/oob-log-alert/util/pidUtil.go @@ -0,0 +1,39 @@ +package util + +import ( + "errors" + "fmt" + "io/ioutil" + "os" + "strconv" +) + +func pid() { + iPid := fmt.Sprint(os.Getpid()) + tmpDir := os.TempDir() + if err := ProcExist(tmpDir); err == nil { + pidFile, _ := os.Create(tmpDir + "\\process.pid") + defer pidFile.Close() + pidFile.WriteString(iPid) + } else { + os.Exit(1) + } +} + +// ProcExist 判断进程是否启动 +func ProcExist(tmpDir string) (err error) { + iPidFile, err := os.Open(tmpDir + "\\process.pid") + defer iPidFile.Close() + if err == nil { + filePid, err := ioutil.ReadAll(iPidFile) + if err == nil { + pidStr := fmt.Sprintf("%s", filePid) + pid, _ := strconv.Atoi(pidStr) + _, err := os.FindProcess(pid) + if err == nil { + return errors.New("[WARN] Process has been started") + } + } + } + return nil +} diff --git a/oob-log-alert/util/sshClient.go b/oob-log-alert/util/sshClient.go new file mode 100644 index 0000000..279027f --- /dev/null +++ b/oob-log-alert/util/sshClient.go @@ -0,0 +1,107 @@ +package util + +import ( + "fmt" + "net" + "time" + + "golang.org/x/crypto/ssh" +) + +// SSHClient SSH client +type SSHClient struct { + Host string + Port int + Username string + Password string + client *ssh.Client + session *ssh.Session +} + +// Exec run command at remote ssh +func (s *SSHClient) Exec(cmd string, params ...interface{}) (res string, err error) { + + var ( + buf string + ret []byte + ) + for _, arg := range params { + buf = fmt.Sprintf("%s %s", buf, arg) + } + + cmdStr := cmd + " " + buf + + fmt.Println(cmdStr) + + err = s.connect() + fmt.Println(s.session) + + if err != nil { + fmt.Println(err.Error()) + return "", err + } + + ret, err = s.session.CombinedOutput(cmdStr) + + defer func() { + s.session.Close() + s.client.Close() + }() + + return string(ret), err + +} + +func (s *SSHClient) connect() error { + var ( + auth []ssh.AuthMethod + addr string + clientConfig *ssh.ClientConfig + config ssh.Config + err error + ) + + auth = make([]ssh.AuthMethod, 0) + auth = append(auth, ssh.Password(s.Password)) + + config = ssh.Config{ + Ciphers: []string{"aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "arcfour256", "arcfour128", "aes128-cbc", "3des-cbc", "aes192-cbc", "aes256-cbc"}, + } + + clientConfig = &ssh.ClientConfig{ + User: s.Username, + Auth: auth, + Timeout: 300 * time.Second, + Config: config, + HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error { + return nil + }, + } + + // connect to ssh + addr = fmt.Sprintf("%s:%d", s.Host, s.Port) + + if s.client, err = ssh.Dial("tcp", addr, clientConfig); err != nil { + fmt.Println(err.Error()) + return err + } + + // create session + if s.session, err = s.client.NewSession(); err != nil { + fmt.Println(err.Error()) + return err + } + + modes := ssh.TerminalModes{ + ssh.ECHO: 0, // disable echoing + ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud + ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud + } + + if err := s.session.RequestPty("xterm", 80, 40, modes); err != nil { + fmt.Println(err.Error()) + return err + } + + return nil +} diff --git a/oob-log-alert/util/strings.go b/oob-log-alert/util/strings.go new file mode 100644 index 0000000..360a3ef --- /dev/null +++ b/oob-log-alert/util/strings.go @@ -0,0 +1,82 @@ +package util + +import ( + "encoding/json" + "fmt" + "log" + "math/rand" + "reflect" + "time" +) + +func ToString(val interface{}) string { + switch reflect.TypeOf(val).Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + return fmt.Sprintf("%d", val) + case reflect.String: + return val.(string) + case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Interface, reflect.Map, reflect.Struct: + if s, err := json.Marshal(val); err == nil { + return string(s) + } else { + log.Print(fmt.Sprintf("val for %+v ToString error: %s", val, err.Error())) + return "" + } + case reflect.Func, reflect.Chan, reflect.UnsafePointer: + log.Print(fmt.Sprintf("val for %+v ToString error", val)) + return "" + } + return "" +} + +func Time2String(t time.Time) string { + return t.Format("2006-01-02 15:04:05") +} + +//GetRandString 借鉴RandomStringUtils.random包生成随机字符串 +// length 随机字符串的长度(不包括前缀) +// uletter 随机字符串是否包含大写字母字符 +// dletter 随机字符串是否包含小写字母字符 +// number 随机字符串是否包含数字字符 +func GetRandString(prefix string, length int32, uletter, dletter, number bool) string { + rand.Seed(time.Now().UnixNano()) + uletters := []rune("ABCDEFGHIGKLMNOPQRSTUVWXYZ") + dletters := []rune("abcdefghijklmnopqrstuvwxyz") + numbers := []rune("0123456789") + source := []rune{} + if uletter { + source = append(source, uletters...) + } + if dletter { + source = append(source, dletters...) + } + if number { + source = append(source, numbers...) + } + if len(source) == 0 { + return "atLeastContainsLetterOrNumber" + } + b := make([]rune, length) + for i := range b { + b[i] = source[rand.Intn(len(source))] + } + return prefix + string(b) +} + +// 跟现有环境一致,格式:aafc4d1b-f696-4ec2-924f-6fd012aa8345 +func GenerateRandUuid() string { + s := GetRandString("", 32, false, true, true) + runes := []rune(s) + return string(runes[0:8]) + "-" + string(runes[8:12]) + "-" + string(runes[12:16]) + "-" + string(runes[16:20]) + "-" + string(runes[20:32]) +} + +func GetUuid(pre string) string { + rand.Seed(time.Now().UnixNano()) + str := "0123456789abcdefghijklmnopqrstuvwxyz" + bytes := []byte(str) + var result []byte + for i := 0; i < 28; i++ { + result = append(result, bytes[rand.Intn(len(bytes))]) + } + return pre + string(result) +}